This repository has been archived on 2024-09-11. You can view files and clone it, but cannot push or open issues or pull requests.
svrjs-blog-newsletter/cronjob/node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js
2024-05-26 22:54:55 +02:00

52 lines
2.2 KiB
JavaScript

import { IniSectionType } from "@smithy/types";
import { CONFIG_PREFIX_SEPARATOR } from "./loadSharedConfigFiles";
const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/;
const profileNameBlockList = ["__proto__", "profile __proto__"];
export const parseIni = (iniData) => {
const map = {};
let currentSection;
let currentSubSection;
for (const iniLine of iniData.split(/\r?\n/)) {
const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim();
const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]";
if (isSection) {
currentSection = undefined;
currentSubSection = undefined;
const sectionName = trimmedLine.substring(1, trimmedLine.length - 1);
const matches = prefixKeyRegex.exec(sectionName);
if (matches) {
const [, prefix, , name] = matches;
if (Object.values(IniSectionType).includes(prefix)) {
currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR);
}
}
else {
currentSection = sectionName;
}
if (profileNameBlockList.includes(sectionName)) {
throw new Error(`Found invalid profile name "${sectionName}"`);
}
}
else if (currentSection) {
const indexOfEqualsSign = trimmedLine.indexOf("=");
if (![0, -1].includes(indexOfEqualsSign)) {
const [name, value] = [
trimmedLine.substring(0, indexOfEqualsSign).trim(),
trimmedLine.substring(indexOfEqualsSign + 1).trim(),
];
if (value === "") {
currentSubSection = name;
}
else {
if (currentSubSection && iniLine.trimStart() === iniLine) {
currentSubSection = undefined;
}
map[currentSection] = map[currentSection] || {};
const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name;
map[currentSection][key] = value;
}
}
}
}
return map;
};