@itrocks/config
Version:
Loads and merges config.yaml files from all dependencies for unified, project-wide configuration
91 lines • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.config = void 0;
exports.scanConfigFiles = scanConfigFiles;
const app_dir_1 = require("@itrocks/app-dir");
const dependency_1 = require("@itrocks/dependency");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const node_path_2 = require("node:path");
const yaml_1 = require("yaml");
exports.config = {};
async function loadDir(path, relativePathSlice = 0) {
await loadFile((0, node_path_2.join)(path, 'config.yaml'), relativePathSlice);
await loadFile((0, node_path_2.join)(path, 'local.yaml'), relativePathSlice);
}
async function loadFile(file, relativePathSlice = 0) {
let yaml;
try {
yaml = await (0, promises_1.readFile)(file, 'utf-8');
}
catch {
return;
}
loadYaml(yaml, relativePathSlice ? (0, node_path_1.dirname)(file).slice(relativePathSlice) : (0, node_path_1.dirname)(file));
}
function loadYaml(buffer, path) {
mergeConfig(exports.config, (0, yaml_1.parse)(buffer), path);
}
function mergeConfig(config, merge, path, prepend = false, depth = 0) {
const entries = prepend
? Object.entries(config)
: undefined;
if (entries) {
for (const key in config) {
delete config[key];
}
}
Object.entries(merge).forEach(([key, value]) => {
if (key === '') {
if (value === null) {
for (const key in config) {
delete config[key];
}
}
return;
}
if (value === null) {
delete config[key];
return;
}
const pathValue = (value) => ((typeof value === 'string') && value.startsWith('./'))
? (path + value.slice(1))
: value;
if (!(key in config)) {
config[key] = pathValue(value);
return;
}
if (Array.isArray(value)) {
if (!Array.isArray(config[key])) {
config[key] = [config[key]];
}
config[key].push(...value.map(pathValue));
return;
}
if (Array.isArray(config[key])) {
config[key].push(pathValue(value));
return;
}
if (typeof config[key] === 'object') {
mergeConfig(config[key], value, path, depth ? false : (key === 'menu'), depth + 1);
return;
}
config[key] = pathValue(value);
});
if (entries) {
for (const [key, value] of entries) {
config[key] = value;
}
}
}
async function scanModules(path, relativePathSlice = 0) {
for (const module of await (0, dependency_1.dependencies)(path)) {
await loadDir((0, node_path_2.join)(path, 'node_modules', module), relativePathSlice);
}
}
async function scanConfigFiles(path = app_dir_1.appDir) {
const relativePathSlice = path.startsWith(app_dir_1.appDir) ? app_dir_1.appDir.length : 0;
await scanModules(path, relativePathSlice);
await loadDir(path, relativePathSlice);
}
//# sourceMappingURL=config.js.map