@itrocks/config
Version:
Loads and merges config.yaml files from all dependencies for unified, project-wide configuration
85 lines • 3.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.config = void 0;
exports.scanConfigFiles = scanConfigFiles;
const app_dir_1 = require("@itrocks/app-dir");
const promises_1 = require("node:fs/promises");
const promises_2 = 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_2.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) {
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);
return;
}
config[key] = pathValue(value);
});
}
async function scanModules(path, relativePathSlice = 0) {
const entries = await (0, promises_1.readdir)(path, { withFileTypes: true });
await Promise.all(entries.map(async (entry) => {
if (!entry.isDirectory()) {
return;
}
if (entry.name[0] === '@') {
await scanModules((0, node_path_2.join)(path, entry.name), relativePathSlice);
return;
}
await loadDir((0, node_path_2.join)(path, entry.name), 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((0, node_path_2.join)(path, 'node_modules'), relativePathSlice);
await loadDir(path, relativePathSlice);
}
//# sourceMappingURL=config.js.map