confstash 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/discover.d.ts +27 -0
- package/discover.js +118 -0
- package/esm/discover.d.ts +27 -0
- package/esm/discover.js +80 -0
- package/esm/extends.d.ts +16 -0
- package/esm/extends.js +57 -0
- package/esm/index.d.ts +14 -0
- package/esm/index.js +13 -0
- package/esm/loader.d.ts +19 -0
- package/esm/loader.js +103 -0
- package/esm/loaders.d.ts +14 -0
- package/esm/loaders.js +129 -0
- package/esm/merge.d.ts +14 -0
- package/esm/merge.js +110 -0
- package/esm/types.d.ts +85 -0
- package/esm/types.js +4 -0
- package/extends.d.ts +16 -0
- package/extends.js +93 -0
- package/index.d.ts +14 -0
- package/index.js +28 -0
- package/loader.d.ts +19 -0
- package/loader.js +140 -0
- package/loaders.d.ts +14 -0
- package/loaders.js +171 -0
- package/merge.d.ts +14 -0
- package/merge.js +115 -0
- package/package.json +51 -0
- package/types.d.ts +85 -0
- package/types.js +5 -0
package/loader.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.createConfigLoader = createConfigLoader;
|
|
37
|
+
exports.defineConfig = defineConfig;
|
|
38
|
+
const fs = __importStar(require("fs"));
|
|
39
|
+
const path = __importStar(require("path"));
|
|
40
|
+
const appstash_1 = require("appstash");
|
|
41
|
+
const discover_1 = require("./discover");
|
|
42
|
+
const extends_1 = require("./extends");
|
|
43
|
+
const loaders_1 = require("./loaders");
|
|
44
|
+
const merge_1 = require("./merge");
|
|
45
|
+
function createConfigLoader(options) {
|
|
46
|
+
const searchPlaces = options.searchPlaces ?? (0, discover_1.defaultSearchPlaces)(options.tool);
|
|
47
|
+
const presets = options.presets ?? {};
|
|
48
|
+
const arrayMerge = options.arrayMerge ?? 'replace';
|
|
49
|
+
const walkUp = options.walkUp ?? true;
|
|
50
|
+
function discover(params) {
|
|
51
|
+
if (params.configFile) {
|
|
52
|
+
const filepath = path.resolve(params.cwd ?? process.cwd(), params.configFile);
|
|
53
|
+
if (!fs.existsSync(filepath)) {
|
|
54
|
+
throw new Error(`Config file not found: ${filepath}`);
|
|
55
|
+
}
|
|
56
|
+
return { filepath };
|
|
57
|
+
}
|
|
58
|
+
return (0, discover_1.findConfigSync)(params.cwd ?? process.cwd(), searchPlaces, walkUp);
|
|
59
|
+
}
|
|
60
|
+
function buildLayers(params, found, fileConfig) {
|
|
61
|
+
const layers = [];
|
|
62
|
+
if (options.defaults) {
|
|
63
|
+
layers.push({ source: 'defaults', origin: 'built-in defaults', config: options.defaults });
|
|
64
|
+
}
|
|
65
|
+
if (options.userStash) {
|
|
66
|
+
const user = readUserStash(options.tool);
|
|
67
|
+
if (user)
|
|
68
|
+
layers.push(user);
|
|
69
|
+
}
|
|
70
|
+
if (found && fileConfig) {
|
|
71
|
+
const baseDir = path.dirname(found.filepath);
|
|
72
|
+
const expanded = (0, extends_1.expandExtends)(fileConfig, { presets, baseDir }, found.filepath);
|
|
73
|
+
layers.push(...expanded);
|
|
74
|
+
}
|
|
75
|
+
if (options.envLayer) {
|
|
76
|
+
const env = params.env ?? process.env;
|
|
77
|
+
const envConfig = options.envLayer(env);
|
|
78
|
+
if (envConfig && Object.keys(envConfig).length > 0) {
|
|
79
|
+
layers.push({ source: 'env', origin: 'environment variables', config: envConfig });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (params.overrides && Object.keys(params.overrides).length > 0) {
|
|
83
|
+
layers.push({ source: 'overrides', origin: 'runtime overrides', config: params.overrides });
|
|
84
|
+
}
|
|
85
|
+
return layers;
|
|
86
|
+
}
|
|
87
|
+
function finalize(params, found, fileConfig) {
|
|
88
|
+
const layers = buildLayers(params, found, fileConfig);
|
|
89
|
+
let config = (0, merge_1.mergeLayers)(layers, arrayMerge);
|
|
90
|
+
if (options.validate) {
|
|
91
|
+
const validated = options.validate(config);
|
|
92
|
+
if (validated !== undefined)
|
|
93
|
+
config = validated;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
config,
|
|
97
|
+
filepath: found?.filepath,
|
|
98
|
+
layers,
|
|
99
|
+
isEmpty: found == null
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
searchPlaces,
|
|
104
|
+
async load(params = {}) {
|
|
105
|
+
const found = discover(params);
|
|
106
|
+
const fileConfig = found ? (await (0, loaders_1.loadFile)(found)) : null;
|
|
107
|
+
return finalize(params, found, fileConfig);
|
|
108
|
+
},
|
|
109
|
+
loadSync(params = {}) {
|
|
110
|
+
const found = discover(params);
|
|
111
|
+
const fileConfig = found ? (0, loaders_1.loadFileSync)(found) : null;
|
|
112
|
+
return finalize(params, found, fileConfig);
|
|
113
|
+
},
|
|
114
|
+
explainSync(params = {}) {
|
|
115
|
+
const found = discover(params);
|
|
116
|
+
const fileConfig = found ? (0, loaders_1.loadFileSync)(found) : null;
|
|
117
|
+
const layers = buildLayers(params, found, fileConfig);
|
|
118
|
+
return (0, merge_1.explainLayers)(layers, arrayMerge);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function readUserStash(tool) {
|
|
123
|
+
try {
|
|
124
|
+
const dirs = (0, appstash_1.appstash)(tool);
|
|
125
|
+
const filepath = (0, appstash_1.resolve)(dirs, 'config', 'config.json');
|
|
126
|
+
if (!fs.existsSync(filepath))
|
|
127
|
+
return null;
|
|
128
|
+
const config = JSON.parse(fs.readFileSync(filepath, 'utf8'));
|
|
129
|
+
if (config == null || typeof config !== 'object' || Array.isArray(config))
|
|
130
|
+
return null;
|
|
131
|
+
return { source: 'user', origin: filepath, config: config };
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Identity helper for typed config authoring in `<tool>.config.ts/js`. */
|
|
138
|
+
function defineConfig(config) {
|
|
139
|
+
return config;
|
|
140
|
+
}
|
package/loaders.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { FoundConfig } from './discover';
|
|
2
|
+
export declare class ConfigLoadError extends Error {
|
|
3
|
+
readonly filepath: string;
|
|
4
|
+
readonly cause?: unknown;
|
|
5
|
+
constructor(message: string, filepath: string, cause?: unknown);
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Load a config file synchronously. Supports .json, .yaml/.yml, extensionless
|
|
9
|
+
* rc files (JSON or YAML), .js/.cjs (require), and .ts (require — needs a TS
|
|
10
|
+
* runtime like ts-node/tsx registered). `.mjs` requires the async loader.
|
|
11
|
+
*/
|
|
12
|
+
export declare function loadFileSync(found: FoundConfig): Record<string, unknown>;
|
|
13
|
+
/** Async variant of {@link loadFileSync} that additionally supports `.mjs` and ESM `.js`. */
|
|
14
|
+
export declare function loadFile(found: FoundConfig): Promise<Record<string, unknown>>;
|
package/loaders.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.ConfigLoadError = void 0;
|
|
40
|
+
exports.loadFileSync = loadFileSync;
|
|
41
|
+
exports.loadFile = loadFile;
|
|
42
|
+
const fs = __importStar(require("fs"));
|
|
43
|
+
const path = __importStar(require("path"));
|
|
44
|
+
const js_yaml_1 = __importDefault(require("js-yaml"));
|
|
45
|
+
class ConfigLoadError extends Error {
|
|
46
|
+
filepath;
|
|
47
|
+
cause;
|
|
48
|
+
constructor(message, filepath, cause) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.filepath = filepath;
|
|
51
|
+
this.cause = cause;
|
|
52
|
+
this.name = 'ConfigLoadError';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exports.ConfigLoadError = ConfigLoadError;
|
|
56
|
+
/**
|
|
57
|
+
* Load a config file synchronously. Supports .json, .yaml/.yml, extensionless
|
|
58
|
+
* rc files (JSON or YAML), .js/.cjs (require), and .ts (require — needs a TS
|
|
59
|
+
* runtime like ts-node/tsx registered). `.mjs` requires the async loader.
|
|
60
|
+
*/
|
|
61
|
+
function loadFileSync(found) {
|
|
62
|
+
const { filepath, packageJsonKey } = found;
|
|
63
|
+
if (packageJsonKey) {
|
|
64
|
+
const pkg = parseJsonFile(filepath);
|
|
65
|
+
return asObject(pkg[packageJsonKey], filepath, `package.json key "${packageJsonKey}"`);
|
|
66
|
+
}
|
|
67
|
+
const ext = path.extname(filepath);
|
|
68
|
+
switch (ext) {
|
|
69
|
+
case '.json':
|
|
70
|
+
return asObject(parseJsonFile(filepath), filepath, 'JSON config');
|
|
71
|
+
case '.yaml':
|
|
72
|
+
case '.yml':
|
|
73
|
+
return asObject(parseYamlFile(filepath), filepath, 'YAML config');
|
|
74
|
+
case '.js':
|
|
75
|
+
case '.cjs':
|
|
76
|
+
case '.ts':
|
|
77
|
+
return requireModule(filepath);
|
|
78
|
+
case '.mjs':
|
|
79
|
+
throw new ConfigLoadError(`Cannot load ESM config "${filepath}" synchronously — use the async loader (load()) instead.`, filepath);
|
|
80
|
+
case '': {
|
|
81
|
+
// extensionless rc file: try JSON first, then YAML
|
|
82
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
83
|
+
try {
|
|
84
|
+
return asObject(JSON.parse(raw), filepath, 'rc config');
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return asObject(js_yaml_1.default.load(raw), filepath, 'rc config');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
default:
|
|
91
|
+
throw new ConfigLoadError(`Unsupported config file type: ${ext}`, filepath);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Async variant of {@link loadFileSync} that additionally supports `.mjs` and ESM `.js`. */
|
|
95
|
+
async function loadFile(found) {
|
|
96
|
+
const { filepath } = found;
|
|
97
|
+
const ext = path.extname(filepath);
|
|
98
|
+
if (ext === '.mjs') {
|
|
99
|
+
return importModule(filepath);
|
|
100
|
+
}
|
|
101
|
+
if (ext === '.js' || ext === '.ts') {
|
|
102
|
+
try {
|
|
103
|
+
return loadFileSync(found);
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
// ESM ".js" (package "type": "module") fails require() — fall back to import()
|
|
107
|
+
if (isEsmRequireError(err)) {
|
|
108
|
+
return importModule(filepath);
|
|
109
|
+
}
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return loadFileSync(found);
|
|
114
|
+
}
|
|
115
|
+
function isEsmRequireError(err) {
|
|
116
|
+
const code = err?.code
|
|
117
|
+
?? err?.cause?.code;
|
|
118
|
+
return code === 'ERR_REQUIRE_ESM';
|
|
119
|
+
}
|
|
120
|
+
function requireModule(filepath) {
|
|
121
|
+
try {
|
|
122
|
+
delete require.cache[require.resolve(filepath)];
|
|
123
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
124
|
+
const mod = require(filepath);
|
|
125
|
+
return asObject(mod?.default ?? mod, filepath, 'module config');
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
if (isEsmRequireError(err))
|
|
129
|
+
throw err;
|
|
130
|
+
throw new ConfigLoadError(`Failed to load config module "${filepath}": ${err.message}`, filepath, err);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function importModule(filepath) {
|
|
134
|
+
try {
|
|
135
|
+
const { pathToFileURL } = require('url');
|
|
136
|
+
// Indirect eval keeps bundlers/transpilers (tsc CJS output, jest) from
|
|
137
|
+
// rewriting the dynamic import into a require(), which cannot load ESM.
|
|
138
|
+
const dynamicImport = new Function('u', 'return import(u)');
|
|
139
|
+
const mod = await dynamicImport(pathToFileURL(filepath).href);
|
|
140
|
+
return asObject(mod?.default ?? mod, filepath, 'module config');
|
|
141
|
+
}
|
|
142
|
+
catch (err) {
|
|
143
|
+
throw new ConfigLoadError(`Failed to import config module "${filepath}": ${err.message}`, filepath, err);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function parseJsonFile(filepath) {
|
|
147
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(raw);
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
throw new ConfigLoadError(`Invalid JSON in "${filepath}": ${err.message}`, filepath, err);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function parseYamlFile(filepath) {
|
|
156
|
+
const raw = fs.readFileSync(filepath, 'utf8');
|
|
157
|
+
try {
|
|
158
|
+
return js_yaml_1.default.load(raw);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
throw new ConfigLoadError(`Invalid YAML in "${filepath}": ${err.message}`, filepath, err);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function asObject(value, filepath, what) {
|
|
165
|
+
if (value == null)
|
|
166
|
+
return {};
|
|
167
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
168
|
+
throw new ConfigLoadError(`Expected ${what} in "${filepath}" to be an object, got ${Array.isArray(value) ? 'array' : typeof value}.`, filepath);
|
|
169
|
+
}
|
|
170
|
+
return value;
|
|
171
|
+
}
|
package/merge.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ArrayMergeStrategy, ConfigLayer, ExplainedValue } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Deep-merge two values. Plain objects merge recursively; arrays follow the
|
|
4
|
+
* given strategy ('replace' by default — matching @pgpmjs/env semantics);
|
|
5
|
+
* everything else: source wins.
|
|
6
|
+
*/
|
|
7
|
+
export declare function deepMerge(target: unknown, source: unknown, arrayMerge?: ArrayMergeStrategy): unknown;
|
|
8
|
+
/** Merge layers in order (lowest precedence first). */
|
|
9
|
+
export declare function mergeLayers<T>(layers: ConfigLayer<T>[], arrayMerge?: ArrayMergeStrategy): T;
|
|
10
|
+
/**
|
|
11
|
+
* Explain the provenance of every leaf value in the merged config: for each
|
|
12
|
+
* dotted path, which layer supplied the winning value.
|
|
13
|
+
*/
|
|
14
|
+
export declare function explainLayers<T>(layers: ConfigLayer<T>[], arrayMerge?: ArrayMergeStrategy): ExplainedValue[];
|
package/merge.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.deepMerge = deepMerge;
|
|
4
|
+
exports.mergeLayers = mergeLayers;
|
|
5
|
+
exports.explainLayers = explainLayers;
|
|
6
|
+
function isPlainObject(value) {
|
|
7
|
+
return (value != null &&
|
|
8
|
+
typeof value === 'object' &&
|
|
9
|
+
!Array.isArray(value) &&
|
|
10
|
+
Object.getPrototypeOf(value) === Object.prototype);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Deep-merge two values. Plain objects merge recursively; arrays follow the
|
|
14
|
+
* given strategy ('replace' by default — matching @pgpmjs/env semantics);
|
|
15
|
+
* everything else: source wins.
|
|
16
|
+
*/
|
|
17
|
+
function deepMerge(target, source, arrayMerge = 'replace') {
|
|
18
|
+
if (Array.isArray(target) && Array.isArray(source)) {
|
|
19
|
+
return arrayMerge === 'concat' ? [...target, ...source] : [...source];
|
|
20
|
+
}
|
|
21
|
+
if (isPlainObject(target) && isPlainObject(source)) {
|
|
22
|
+
const out = { ...target };
|
|
23
|
+
for (const key of Object.keys(source)) {
|
|
24
|
+
const sv = source[key];
|
|
25
|
+
if (sv === undefined)
|
|
26
|
+
continue;
|
|
27
|
+
out[key] = key in out ? deepMerge(out[key], sv, arrayMerge) : cloneValue(sv);
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
return cloneValue(source);
|
|
32
|
+
}
|
|
33
|
+
function cloneValue(value) {
|
|
34
|
+
if (Array.isArray(value))
|
|
35
|
+
return value.map(cloneValue);
|
|
36
|
+
if (isPlainObject(value)) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const key of Object.keys(value))
|
|
39
|
+
out[key] = cloneValue(value[key]);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
/** Merge layers in order (lowest precedence first). */
|
|
45
|
+
function mergeLayers(layers, arrayMerge = 'replace') {
|
|
46
|
+
let acc = {};
|
|
47
|
+
for (const layer of layers) {
|
|
48
|
+
acc = deepMerge(acc, layer.config, arrayMerge);
|
|
49
|
+
}
|
|
50
|
+
return acc;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Explain the provenance of every leaf value in the merged config: for each
|
|
54
|
+
* dotted path, which layer supplied the winning value.
|
|
55
|
+
*/
|
|
56
|
+
function explainLayers(layers, arrayMerge = 'replace') {
|
|
57
|
+
const merged = mergeLayers(layers, arrayMerge);
|
|
58
|
+
const out = [];
|
|
59
|
+
const walk = (value, pathParts) => {
|
|
60
|
+
if (isPlainObject(value)) {
|
|
61
|
+
for (const key of Object.keys(value))
|
|
62
|
+
walk(value[key], [...pathParts, key]);
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const dotted = pathParts.join('.');
|
|
66
|
+
const winner = findWinner(layers, pathParts, value);
|
|
67
|
+
out.push({
|
|
68
|
+
path: dotted,
|
|
69
|
+
value,
|
|
70
|
+
source: winner?.source ?? 'defaults',
|
|
71
|
+
origin: winner?.origin ?? 'unknown'
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
walk(merged, []);
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
function findWinner(layers, pathParts, finalValue) {
|
|
78
|
+
for (let i = layers.length - 1; i >= 0; i--) {
|
|
79
|
+
const candidate = getPath(layers[i].config, pathParts);
|
|
80
|
+
if (candidate === undefined)
|
|
81
|
+
continue;
|
|
82
|
+
// Arrays with 'concat' can be composites of multiple layers; attribute to
|
|
83
|
+
// the last contributing layer regardless.
|
|
84
|
+
if (deepEqual(candidate, finalValue) || Array.isArray(finalValue)) {
|
|
85
|
+
return layers[i];
|
|
86
|
+
}
|
|
87
|
+
// The last layer that defines the path wins under deepMerge for scalars.
|
|
88
|
+
return layers[i];
|
|
89
|
+
}
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
function getPath(obj, pathParts) {
|
|
93
|
+
let cur = obj;
|
|
94
|
+
for (const part of pathParts) {
|
|
95
|
+
if (!isPlainObject(cur))
|
|
96
|
+
return undefined;
|
|
97
|
+
cur = cur[part];
|
|
98
|
+
if (cur === undefined)
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
return cur;
|
|
102
|
+
}
|
|
103
|
+
function deepEqual(a, b) {
|
|
104
|
+
if (a === b)
|
|
105
|
+
return true;
|
|
106
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
107
|
+
return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
108
|
+
}
|
|
109
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
110
|
+
const ka = Object.keys(a);
|
|
111
|
+
const kb = Object.keys(b);
|
|
112
|
+
return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "confstash",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"author": "Constructive <developers@constructive.io>",
|
|
5
|
+
"description": "Standardized project configuration loading — config files, rc files, presets, and layered merge with provenance",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/dev-utils",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/dev-utils"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/dev-utils/issues"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"copy": "makage assets",
|
|
24
|
+
"clean": "makage clean",
|
|
25
|
+
"prepublishOnly": "npm run build",
|
|
26
|
+
"build": "makage build",
|
|
27
|
+
"lint": "eslint . --fix",
|
|
28
|
+
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
|
29
|
+
"test:watch": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --watch"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"appstash": "0.7.0",
|
|
33
|
+
"js-yaml": "^4.1.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/js-yaml": "^4.0.9",
|
|
37
|
+
"cross-env": "^10.1.0",
|
|
38
|
+
"makage": "0.1.10"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"config",
|
|
42
|
+
"configuration",
|
|
43
|
+
"rc",
|
|
44
|
+
"cosmiconfig",
|
|
45
|
+
"presets",
|
|
46
|
+
"extends",
|
|
47
|
+
"loader",
|
|
48
|
+
"cli"
|
|
49
|
+
],
|
|
50
|
+
"gitHead": "8a788f355703ecb6abe9d5926940f7682502ee34"
|
|
51
|
+
}
|
package/types.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core types for confstash — standardized project configuration loading.
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* A place to search for configuration. Either a filename (searched during the
|
|
6
|
+
* walk-up) or a key inside `package.json`.
|
|
7
|
+
*/
|
|
8
|
+
export type SearchPlace = string | {
|
|
9
|
+
packageJson: string;
|
|
10
|
+
};
|
|
11
|
+
/** Where a resolved config value (or layer) came from. */
|
|
12
|
+
export type LayerSource = 'defaults' | 'preset' | 'user' | 'file' | 'env' | 'overrides';
|
|
13
|
+
export interface ConfigLayer<T = Record<string, unknown>> {
|
|
14
|
+
source: LayerSource;
|
|
15
|
+
/** Human-readable origin: file path, preset name, env prefix, … */
|
|
16
|
+
origin: string;
|
|
17
|
+
config: Partial<T>;
|
|
18
|
+
}
|
|
19
|
+
export interface LoadResult<T = Record<string, unknown>> {
|
|
20
|
+
/** Fully merged configuration. */
|
|
21
|
+
config: T;
|
|
22
|
+
/** Path of the project config file that was found, if any. */
|
|
23
|
+
filepath?: string;
|
|
24
|
+
/** Every layer that contributed, in merge order (lowest precedence first). */
|
|
25
|
+
layers: ConfigLayer<T>[];
|
|
26
|
+
/** Whether any project config file was found. */
|
|
27
|
+
isEmpty: boolean;
|
|
28
|
+
}
|
|
29
|
+
export type ArrayMergeStrategy = 'replace' | 'concat';
|
|
30
|
+
export interface LoadParams<T = Record<string, unknown>> {
|
|
31
|
+
/** Directory to start the walk-up search from. Default: process.cwd(). */
|
|
32
|
+
cwd?: string;
|
|
33
|
+
/** Highest-precedence overrides (e.g. parsed CLI flags). */
|
|
34
|
+
overrides?: Partial<T>;
|
|
35
|
+
/** Load an exact config file, skipping discovery. */
|
|
36
|
+
configFile?: string;
|
|
37
|
+
/** Environment to read the env layer from. Default: process.env. */
|
|
38
|
+
env?: NodeJS.ProcessEnv;
|
|
39
|
+
}
|
|
40
|
+
export interface ConfigLoaderOptions<T = Record<string, unknown>> {
|
|
41
|
+
/** Tool name, e.g. 'safegres'. Drives default search places and stash dir. */
|
|
42
|
+
tool: string;
|
|
43
|
+
/**
|
|
44
|
+
* Ordered list of places to look for project config. When omitted, defaults
|
|
45
|
+
* derived from the tool name are used (see `defaultSearchPlaces`).
|
|
46
|
+
*/
|
|
47
|
+
searchPlaces?: SearchPlace[];
|
|
48
|
+
/** Built-in defaults — the lowest-precedence layer. */
|
|
49
|
+
defaults?: Partial<T>;
|
|
50
|
+
/**
|
|
51
|
+
* Named presets resolvable via `extends` (e.g. `'safegres:recommended'`).
|
|
52
|
+
* A preset is just a partial config, and may itself use `extends`.
|
|
53
|
+
*/
|
|
54
|
+
presets?: Record<string, Partial<T>>;
|
|
55
|
+
/**
|
|
56
|
+
* Map environment variables into a config layer. Return a partial config.
|
|
57
|
+
* Runs between the project-file layer and CLI overrides.
|
|
58
|
+
*/
|
|
59
|
+
envLayer?: (env: NodeJS.ProcessEnv) => Partial<T>;
|
|
60
|
+
/**
|
|
61
|
+
* Include a user-level layer read from `~/.<tool>/config/config.json`
|
|
62
|
+
* (via appstash). Default: false.
|
|
63
|
+
*/
|
|
64
|
+
userStash?: boolean;
|
|
65
|
+
/** Array merge behavior. Default: 'replace' (later layers win entirely). */
|
|
66
|
+
arrayMerge?: ArrayMergeStrategy;
|
|
67
|
+
/**
|
|
68
|
+
* Validate/normalize the final merged config. Throw to reject. The return
|
|
69
|
+
* value (if not undefined) replaces the config.
|
|
70
|
+
*/
|
|
71
|
+
validate?: (config: T) => T | void;
|
|
72
|
+
/**
|
|
73
|
+
* When true, `load()`/`loadSync()` stop at the first search place found in
|
|
74
|
+
* each directory but keep walking up if none matched (cosmiconfig behavior).
|
|
75
|
+
* Default: true. When false, only `cwd` itself is searched.
|
|
76
|
+
*/
|
|
77
|
+
walkUp?: boolean;
|
|
78
|
+
}
|
|
79
|
+
/** A single key's provenance, produced by `explain()`. */
|
|
80
|
+
export interface ExplainedValue {
|
|
81
|
+
path: string;
|
|
82
|
+
value: unknown;
|
|
83
|
+
source: LayerSource;
|
|
84
|
+
origin: string;
|
|
85
|
+
}
|