@karmaniverous/get-dotenv 6.0.0-1 → 6.0.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/README.md +91 -379
- package/dist/cli.d.ts +569 -0
- package/dist/cli.mjs +18788 -0
- package/dist/cliHost.d.ts +515 -184
- package/dist/cliHost.mjs +1931 -1428
- package/dist/config.d.ts +187 -14
- package/dist/config.mjs +256 -81
- package/dist/env-overlay.d.ts +212 -16
- package/dist/env-overlay.mjs +168 -4
- package/dist/getdotenv.cli.mjs +18227 -3487
- package/dist/index.d.ts +541 -260
- package/dist/index.mjs +18294 -3556
- package/dist/plugins-aws.d.ts +221 -91
- package/dist/plugins-aws.mjs +2360 -361
- package/dist/plugins-batch.d.ts +300 -103
- package/dist/plugins-batch.mjs +2519 -484
- package/dist/plugins-cmd.d.ts +229 -106
- package/dist/plugins-cmd.mjs +2480 -793
- package/dist/plugins-init.d.ts +221 -95
- package/dist/plugins-init.mjs +2102 -104
- package/dist/plugins.d.ts +246 -125
- package/dist/plugins.mjs +17861 -1973
- package/dist/templates/cli/index.ts +26 -0
- package/{templates/cli/ts → dist/templates/cli}/plugins/hello.ts +11 -6
- package/dist/templates/config/js/getdotenv.config.js +20 -0
- package/dist/templates/config/json/local/getdotenv.config.local.json +7 -0
- package/dist/templates/config/json/public/getdotenv.config.json +9 -0
- package/dist/templates/config/public/getdotenv.config.json +8 -0
- package/dist/templates/config/ts/getdotenv.config.ts +28 -0
- package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +7 -0
- package/dist/templates/config/yaml/public/getdotenv.config.yaml +7 -0
- package/dist/templates/getdotenv.config.js +20 -0
- package/dist/templates/getdotenv.config.json +9 -0
- package/dist/templates/getdotenv.config.local.json +7 -0
- package/dist/templates/getdotenv.config.local.yaml +7 -0
- package/dist/templates/getdotenv.config.ts +28 -0
- package/dist/templates/getdotenv.config.yaml +7 -0
- package/dist/templates/hello.ts +43 -0
- package/dist/templates/index.ts +26 -0
- package/dist/templates/js/getdotenv.config.js +20 -0
- package/dist/templates/json/local/getdotenv.config.local.json +7 -0
- package/dist/templates/json/public/getdotenv.config.json +9 -0
- package/dist/templates/local/getdotenv.config.local.json +7 -0
- package/dist/templates/local/getdotenv.config.local.yaml +7 -0
- package/dist/templates/plugins/hello.ts +43 -0
- package/dist/templates/public/getdotenv.config.json +9 -0
- package/dist/templates/public/getdotenv.config.yaml +7 -0
- package/dist/templates/ts/getdotenv.config.ts +28 -0
- package/dist/templates/yaml/local/getdotenv.config.local.yaml +7 -0
- package/dist/templates/yaml/public/getdotenv.config.yaml +7 -0
- package/getdotenv.config.json +1 -19
- package/package.json +42 -39
- package/templates/cli/index.ts +26 -0
- package/templates/cli/plugins/hello.ts +43 -0
- package/templates/config/js/getdotenv.config.js +8 -3
- package/templates/config/json/public/getdotenv.config.json +0 -3
- package/templates/config/public/getdotenv.config.json +0 -5
- package/templates/config/ts/getdotenv.config.ts +9 -4
- package/templates/config/yaml/public/getdotenv.config.yaml +0 -3
- package/dist/plugins-demo.d.ts +0 -204
- package/dist/plugins-demo.mjs +0 -496
- package/templates/cli/ts/index.ts +0 -9
package/dist/cliHost.mjs
CHANGED
|
@@ -1,41 +1,125 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
export { z } from 'zod';
|
|
3
|
+
import path, { join, extname } from 'path';
|
|
3
4
|
import fs from 'fs-extra';
|
|
4
5
|
import { packageDirectory } from 'package-directory';
|
|
5
|
-
import
|
|
6
|
-
import url, { fileURLToPath, pathToFileURL } from 'url';
|
|
6
|
+
import url, { fileURLToPath } from 'url';
|
|
7
7
|
import YAML from 'yaml';
|
|
8
|
-
import {
|
|
8
|
+
import { createHash } from 'crypto';
|
|
9
9
|
import { nanoid } from 'nanoid';
|
|
10
10
|
import { parse } from 'dotenv';
|
|
11
|
-
import {
|
|
11
|
+
import { execa, execaCommand } from 'execa';
|
|
12
|
+
import { Option, Command } from '@commander-js/extra-typings';
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Zod schemas for programmatic GetDotenv options.
|
|
16
|
+
*
|
|
17
|
+
* Canonical source of truth for options shape. Public types are derived
|
|
18
|
+
* from these schemas (see consumers via z.output\<\>).
|
|
19
|
+
*/
|
|
20
|
+
/**
|
|
21
|
+
* Minimal process env representation used by options and helpers.
|
|
22
|
+
* Values may be `undefined` to indicate "unset".
|
|
23
|
+
*/
|
|
24
|
+
const processEnvSchema = z.record(z.string(), z.string().optional());
|
|
25
|
+
// RAW: all fields optional — undefined means "inherit" from lower layers.
|
|
26
|
+
const getDotenvOptionsSchemaRaw = z.object({
|
|
27
|
+
defaultEnv: z.string().optional(),
|
|
28
|
+
dotenvToken: z.string().optional(),
|
|
29
|
+
dynamicPath: z.string().optional(),
|
|
30
|
+
// Dynamic map is intentionally wide for now; refine once sources are normalized.
|
|
31
|
+
dynamic: z.record(z.string(), z.unknown()).optional(),
|
|
32
|
+
env: z.string().optional(),
|
|
33
|
+
excludeDynamic: z.boolean().optional(),
|
|
34
|
+
excludeEnv: z.boolean().optional(),
|
|
35
|
+
excludeGlobal: z.boolean().optional(),
|
|
36
|
+
excludePrivate: z.boolean().optional(),
|
|
37
|
+
excludePublic: z.boolean().optional(),
|
|
38
|
+
loadProcess: z.boolean().optional(),
|
|
39
|
+
log: z.boolean().optional(),
|
|
40
|
+
logger: z.unknown().default(console),
|
|
41
|
+
outputPath: z.string().optional(),
|
|
42
|
+
paths: z.array(z.string()).optional(),
|
|
43
|
+
privateToken: z.string().optional(),
|
|
44
|
+
vars: processEnvSchema.optional(),
|
|
45
|
+
});
|
|
46
|
+
/**
|
|
47
|
+
* Resolved programmatic options schema (post-inheritance).
|
|
48
|
+
* For now, this mirrors the RAW schema; future stages may materialize defaults
|
|
49
|
+
* and narrow shapes as resolution is wired into the host.
|
|
50
|
+
*/
|
|
51
|
+
const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Zod schemas for CLI-facing GetDotenv options (raw/resolved stubs).
|
|
55
|
+
*
|
|
56
|
+
* RAW allows stringly inputs (paths/vars + splitters). RESOLVED will later
|
|
57
|
+
* reflect normalized types (paths: string[], vars: ProcessEnv), applied in the
|
|
58
|
+
* CLI resolution pipeline.
|
|
59
|
+
*/
|
|
60
|
+
const getDotenvCliOptionsSchemaRaw = getDotenvOptionsSchemaRaw.extend({
|
|
61
|
+
// CLI-specific fields (stringly inputs before preprocessing)
|
|
62
|
+
debug: z.boolean().optional(),
|
|
63
|
+
strict: z.boolean().optional(),
|
|
64
|
+
capture: z.boolean().optional(),
|
|
65
|
+
trace: z.union([z.boolean(), z.array(z.string())]).optional(),
|
|
66
|
+
redact: z.boolean().optional(),
|
|
67
|
+
warnEntropy: z.boolean().optional(),
|
|
68
|
+
entropyThreshold: z.number().optional(),
|
|
69
|
+
entropyMinLength: z.number().optional(),
|
|
70
|
+
entropyWhitelist: z.array(z.string()).optional(),
|
|
71
|
+
redactPatterns: z.array(z.string()).optional(),
|
|
72
|
+
paths: z.string().optional(),
|
|
73
|
+
pathsDelimiter: z.string().optional(),
|
|
74
|
+
pathsDelimiterPattern: z.string().optional(),
|
|
75
|
+
scripts: z.record(z.string(), z.unknown()).optional(),
|
|
76
|
+
shell: z.union([z.boolean(), z.string()]).optional(),
|
|
77
|
+
vars: z.string().optional(),
|
|
78
|
+
varsAssignor: z.string().optional(),
|
|
79
|
+
varsAssignorPattern: z.string().optional(),
|
|
80
|
+
varsDelimiter: z.string().optional(),
|
|
81
|
+
varsDelimiterPattern: z.string().optional(),
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const visibilityMap = z.record(z.string(), z.boolean());
|
|
85
|
+
/**
|
|
86
|
+
* Zod schemas for configuration files discovered by the new loader.
|
|
87
|
+
*
|
|
88
|
+
* Notes:
|
|
89
|
+
* - RAW: all fields optional; only allowed top-level keys are:
|
|
90
|
+
* - rootOptionDefaults, rootOptionVisibility
|
|
91
|
+
* - scripts, vars, envVars
|
|
92
|
+
* - dynamic (JS/TS only), schema (JS/TS only)
|
|
93
|
+
* - plugins, requiredKeys
|
|
94
|
+
* - RESOLVED: mirrors RAW (no path normalization).
|
|
95
|
+
* - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS only).
|
|
96
|
+
*/
|
|
97
|
+
// String-only env value map
|
|
98
|
+
const stringMap = z.record(z.string(), z.string());
|
|
99
|
+
const envStringMap = z.record(z.string(), stringMap);
|
|
100
|
+
/**
|
|
101
|
+
* Raw configuration schema for get‑dotenv config files (JSON/YAML/JS/TS).
|
|
102
|
+
* Validates allowed top‑level keys without performing path normalization.
|
|
103
|
+
*/
|
|
104
|
+
const getDotenvConfigSchemaRaw = z.object({
|
|
105
|
+
rootOptionDefaults: getDotenvCliOptionsSchemaRaw.optional(),
|
|
106
|
+
rootOptionVisibility: visibilityMap.optional(),
|
|
107
|
+
scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
|
|
108
|
+
requiredKeys: z.array(z.string()).optional(),
|
|
109
|
+
schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
|
|
110
|
+
vars: stringMap.optional(), // public, global
|
|
111
|
+
envVars: envStringMap.optional(), // public, per-env
|
|
112
|
+
// Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
|
|
113
|
+
dynamic: z.unknown().optional(),
|
|
114
|
+
// Per-plugin config bag; validated by plugins/host when used.
|
|
115
|
+
plugins: z.record(z.string(), z.unknown()).optional(),
|
|
116
|
+
});
|
|
117
|
+
/**
|
|
118
|
+
* Resolved configuration schema which preserves the raw shape while narrowing
|
|
119
|
+
* the output to {@link GetDotenvConfigResolved}. Consumers get a strongly typed
|
|
120
|
+
* object, while the underlying validation remains Zod‑driven.
|
|
121
|
+
*/
|
|
122
|
+
const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => raw);
|
|
39
123
|
|
|
40
124
|
/** @internal */
|
|
41
125
|
const isPlainObject$1 = (value) => value !== null &&
|
|
@@ -66,167 +150,404 @@ function defaultsDeep(...layers) {
|
|
|
66
150
|
}
|
|
67
151
|
|
|
68
152
|
/**
|
|
69
|
-
*
|
|
70
|
-
* -
|
|
71
|
-
|
|
72
|
-
|
|
153
|
+
* Serialize a dotenv record to a file with minimal quoting (multiline values are quoted).
|
|
154
|
+
* Future-proofs for ordering/sorting changes (currently insertion order).
|
|
155
|
+
*/
|
|
156
|
+
async function writeDotenvFile(filename, data) {
|
|
157
|
+
// Serialize: key=value with quotes only for multiline values.
|
|
158
|
+
const body = Object.keys(data).reduce((acc, key) => {
|
|
159
|
+
const v = data[key] ?? '';
|
|
160
|
+
const val = v.includes('\n') ? `"${v}"` : v;
|
|
161
|
+
return `${acc}${key}=${val}\n`;
|
|
162
|
+
}, '');
|
|
163
|
+
await fs.writeFile(filename, body, { encoding: 'utf-8' });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Dotenv expansion utilities.
|
|
73
168
|
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
* @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
|
|
169
|
+
* This module implements recursive expansion of environment-variable
|
|
170
|
+
* references in strings and records. It supports both whitespace and
|
|
171
|
+
* bracket syntaxes with optional defaults:
|
|
78
172
|
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
173
|
+
* - Whitespace: `$VAR[:default]`
|
|
174
|
+
* - Bracketed: `${VAR[:default]}`
|
|
175
|
+
*
|
|
176
|
+
* Escaped dollar signs (`\$`) are preserved.
|
|
177
|
+
* Unknown variables resolve to empty string unless a default is provided.
|
|
83
178
|
*/
|
|
84
|
-
const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
|
|
85
179
|
/**
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
|
|
89
|
-
|
|
180
|
+
* Like String.prototype.search but returns the last index.
|
|
181
|
+
* @internal
|
|
182
|
+
*/
|
|
183
|
+
const searchLast = (str, rgx) => {
|
|
184
|
+
const matches = Array.from(str.matchAll(rgx));
|
|
185
|
+
return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
|
|
186
|
+
};
|
|
187
|
+
const replaceMatch = (value, match, ref) => {
|
|
188
|
+
/**
|
|
189
|
+
* @internal
|
|
190
|
+
*/
|
|
191
|
+
const group = match[0];
|
|
192
|
+
const key = match[1];
|
|
193
|
+
const defaultValue = match[2];
|
|
194
|
+
if (!key)
|
|
195
|
+
return value;
|
|
196
|
+
const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
|
|
197
|
+
return interpolate(replacement, ref);
|
|
198
|
+
};
|
|
199
|
+
const interpolate = (value = '', ref = {}) => {
|
|
200
|
+
/**
|
|
201
|
+
* @internal
|
|
202
|
+
*/
|
|
203
|
+
// if value is falsy, return it as is
|
|
204
|
+
if (!value)
|
|
205
|
+
return value;
|
|
206
|
+
// get position of last unescaped dollar sign
|
|
207
|
+
const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
|
|
208
|
+
// return value if none found
|
|
209
|
+
if (lastUnescapedDollarSignIndex === -1)
|
|
210
|
+
return value;
|
|
211
|
+
// evaluate the value tail
|
|
212
|
+
const tail = value.slice(lastUnescapedDollarSignIndex);
|
|
213
|
+
// find whitespace pattern: $KEY:DEFAULT
|
|
214
|
+
const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
|
|
215
|
+
const whitespaceMatch = whitespacePattern.exec(tail);
|
|
216
|
+
if (whitespaceMatch != null)
|
|
217
|
+
return replaceMatch(value, whitespaceMatch, ref);
|
|
218
|
+
else {
|
|
219
|
+
// find bracket pattern: ${KEY:DEFAULT}
|
|
220
|
+
const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
|
|
221
|
+
const bracketMatch = bracketPattern.exec(tail);
|
|
222
|
+
if (bracketMatch != null)
|
|
223
|
+
return replaceMatch(value, bracketMatch, ref);
|
|
224
|
+
}
|
|
225
|
+
return value;
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* Recursively expands environment variables in a string. Variables may be
|
|
229
|
+
* presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
|
|
230
|
+
* Unknown variables will expand to an empty string.
|
|
90
231
|
*
|
|
91
|
-
* @param
|
|
92
|
-
* @param
|
|
93
|
-
* @
|
|
94
|
-
* @param excludeAll - Global "exclude-all" flag.
|
|
95
|
-
* @param excludeAllOff - Global "exclude-all-off" flag.
|
|
232
|
+
* @param value - The string to expand.
|
|
233
|
+
* @param ref - The reference object to use for variable expansion.
|
|
234
|
+
* @returns The expanded string.
|
|
96
235
|
*
|
|
97
236
|
* @example
|
|
98
|
-
*
|
|
237
|
+
* ```ts
|
|
238
|
+
* process.env.FOO = 'bar';
|
|
239
|
+
* dotenvExpand('Hello $FOO'); // "Hello bar"
|
|
240
|
+
* dotenvExpand('Hello $BAZ:world'); // "Hello world"
|
|
241
|
+
* ```
|
|
242
|
+
*
|
|
243
|
+
* @remarks
|
|
244
|
+
* The expansion is recursive. If a referenced variable itself contains
|
|
245
|
+
* references, those will also be expanded until a stable value is reached.
|
|
246
|
+
* Escaped references (e.g. `\$FOO`) are preserved as literals.
|
|
99
247
|
*/
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
// 3) Global exclude-all forces true when not explicitly turned off.
|
|
105
|
-
// 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
|
|
106
|
-
// 5) Fall back to the default (true => set; false/undefined => unset).
|
|
107
|
-
(() => {
|
|
108
|
-
// Individual "on"
|
|
109
|
-
if (exclude === true)
|
|
110
|
-
return true;
|
|
111
|
-
// Individual "off"
|
|
112
|
-
if (excludeOff === true)
|
|
113
|
-
return undefined;
|
|
114
|
-
// Global "exclude-all" ON (unless explicitly turned off)
|
|
115
|
-
if (excludeAll === true)
|
|
116
|
-
return true;
|
|
117
|
-
// Global "exclude-all-off" (unless explicitly enabled)
|
|
118
|
-
if (excludeAllOff === true)
|
|
119
|
-
return undefined;
|
|
120
|
-
// Default
|
|
121
|
-
return defaultValue ? true : undefined;
|
|
122
|
-
})();
|
|
248
|
+
const dotenvExpand = (value, ref = process.env) => {
|
|
249
|
+
const result = interpolate(value, ref);
|
|
250
|
+
return result ? result.replace(/\\\$/g, '$') : undefined;
|
|
251
|
+
};
|
|
123
252
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
253
|
+
* Recursively expands environment variables in the values of a JSON object.
|
|
254
|
+
* Variables may be presented with optional default as `$VAR[:default]` or
|
|
255
|
+
* `${VAR[:default]}`. Unknown variables will expand to an empty string.
|
|
126
256
|
*
|
|
127
|
-
* @
|
|
128
|
-
* @param
|
|
129
|
-
* @
|
|
130
|
-
*
|
|
257
|
+
* @param values - The values object to expand.
|
|
258
|
+
* @param options - Expansion options.
|
|
259
|
+
* @returns The value object with expanded string values.
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* ```ts
|
|
263
|
+
* process.env.FOO = 'bar';
|
|
264
|
+
* dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
|
|
265
|
+
* // => { A: "bar", B: "xbary" }
|
|
266
|
+
* ```
|
|
131
267
|
*
|
|
132
268
|
* @remarks
|
|
133
|
-
*
|
|
269
|
+
* Options:
|
|
270
|
+
* - ref: The reference object to use for expansion (defaults to process.env).
|
|
271
|
+
* - progressive: Whether to progressively add expanded values to the set of
|
|
272
|
+
* reference keys.
|
|
273
|
+
*
|
|
274
|
+
* When `progressive` is true, each expanded key becomes available for
|
|
275
|
+
* subsequent expansions in the same object (left-to-right by object key order).
|
|
134
276
|
*/
|
|
135
|
-
|
|
136
|
-
const
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
};
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
*
|
|
277
|
+
function dotenvExpandAll(values, options = {}) {
|
|
278
|
+
const { ref = process.env, progressive = false, } = options;
|
|
279
|
+
const out = Object.keys(values).reduce((acc, key) => {
|
|
280
|
+
acc[key] = dotenvExpand(values[key], {
|
|
281
|
+
...ref,
|
|
282
|
+
...(progressive ? acc : {}),
|
|
283
|
+
});
|
|
284
|
+
return acc;
|
|
285
|
+
}, {});
|
|
286
|
+
// Key-preserving return with a permissive index signature to allow later additions.
|
|
287
|
+
return out;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Recursively expands environment variables in a string using `process.env` as
|
|
291
|
+
* the expansion reference. Variables may be presented with optional default as
|
|
292
|
+
* `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
|
|
293
|
+
* empty string.
|
|
294
|
+
*
|
|
295
|
+
* @param value - The string to expand.
|
|
296
|
+
* @returns The expanded string.
|
|
297
|
+
*
|
|
298
|
+
* @example
|
|
299
|
+
* ```ts
|
|
300
|
+
* process.env.FOO = 'bar';
|
|
301
|
+
* dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
|
|
302
|
+
* ```
|
|
149
303
|
*/
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
304
|
+
const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
|
|
305
|
+
|
|
306
|
+
/** @internal */
|
|
307
|
+
const isPlainObject = (v) => v !== null &&
|
|
308
|
+
typeof v === 'object' &&
|
|
309
|
+
!Array.isArray(v) &&
|
|
310
|
+
Object.getPrototypeOf(v) === Object.prototype;
|
|
311
|
+
/**
|
|
312
|
+
* Deeply interpolate string leaves against envRef.
|
|
313
|
+
* Arrays are not recursed into; they are returned unchanged.
|
|
314
|
+
*
|
|
315
|
+
* @typeParam T - Shape of the input value.
|
|
316
|
+
* @param value - Input value (object/array/primitive).
|
|
317
|
+
* @param envRef - Reference environment for interpolation.
|
|
318
|
+
* @returns A new value with string leaves interpolated.
|
|
319
|
+
*/
|
|
320
|
+
const interpolateDeep = (value, envRef) => {
|
|
321
|
+
// Strings: expand and return
|
|
322
|
+
if (typeof value === 'string') {
|
|
323
|
+
const out = dotenvExpand(value, envRef);
|
|
324
|
+
// dotenvExpand returns string | undefined; preserve original on undefined
|
|
325
|
+
return (out ?? value);
|
|
326
|
+
}
|
|
327
|
+
// Arrays: return as-is (no recursion)
|
|
328
|
+
if (Array.isArray(value)) {
|
|
329
|
+
return value;
|
|
330
|
+
}
|
|
331
|
+
// Plain objects: shallow clone and recurse into values
|
|
332
|
+
if (isPlainObject(value)) {
|
|
333
|
+
const src = value;
|
|
334
|
+
const out = {};
|
|
335
|
+
for (const [k, v] of Object.entries(src)) {
|
|
336
|
+
// Recurse for strings/objects; keep arrays as-is; preserve other scalars
|
|
337
|
+
if (typeof v === 'string')
|
|
338
|
+
out[k] = dotenvExpand(v, envRef) ?? v;
|
|
339
|
+
else if (Array.isArray(v))
|
|
340
|
+
out[k] = v;
|
|
341
|
+
else if (isPlainObject(v))
|
|
342
|
+
out[k] = interpolateDeep(v, envRef);
|
|
343
|
+
else
|
|
344
|
+
out[k] = v;
|
|
162
345
|
}
|
|
346
|
+
return out;
|
|
163
347
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
348
|
+
// Other primitives/types: return as-is
|
|
349
|
+
return value;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const importDefault = async (fileUrl) => {
|
|
353
|
+
const mod = (await import(fileUrl));
|
|
354
|
+
return mod.default;
|
|
355
|
+
};
|
|
356
|
+
const cacheHash = (absPath, mtimeMs) => createHash('sha1')
|
|
357
|
+
.update(absPath)
|
|
358
|
+
.update(String(mtimeMs))
|
|
359
|
+
.digest('hex')
|
|
360
|
+
.slice(0, 12);
|
|
361
|
+
/**
|
|
362
|
+
* Remove older compiled cache files for a given source base name, keeping
|
|
363
|
+
* at most `keep` most-recent files. Errors are ignored by design.
|
|
364
|
+
*/
|
|
365
|
+
const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
|
|
366
|
+
try {
|
|
367
|
+
const entries = await fs.readdir(cacheDir);
|
|
368
|
+
const mine = entries
|
|
369
|
+
.filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
|
|
370
|
+
.map((f) => path.join(cacheDir, f));
|
|
371
|
+
if (mine.length <= keep)
|
|
372
|
+
return;
|
|
373
|
+
const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
|
|
374
|
+
stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
375
|
+
const toDelete = stats.slice(keep).map((s) => s.p);
|
|
376
|
+
await Promise.all(toDelete.map(async (p) => {
|
|
377
|
+
try {
|
|
378
|
+
await fs.remove(p);
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
// best-effort cleanup
|
|
382
|
+
}
|
|
383
|
+
}));
|
|
183
384
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
385
|
+
catch {
|
|
386
|
+
// best-effort cleanup
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
/**
|
|
390
|
+
* Load a module default export from a JS/TS file with robust fallbacks:
|
|
391
|
+
* - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
|
|
392
|
+
* 1) try direct import (if a TS loader is active),
|
|
393
|
+
* 2) esbuild bundle to a temp ESM file,
|
|
394
|
+
* 3) typescript.transpileModule fallback for simple modules.
|
|
395
|
+
*
|
|
396
|
+
* @param absPath - absolute path to source file
|
|
397
|
+
* @param cacheDirName - cache subfolder under .tsbuild
|
|
398
|
+
*/
|
|
399
|
+
const loadModuleDefault = async (absPath, cacheDirName) => {
|
|
400
|
+
const ext = path.extname(absPath).toLowerCase();
|
|
401
|
+
const fileUrl = url.pathToFileURL(absPath).toString();
|
|
402
|
+
if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
|
|
403
|
+
return importDefault(fileUrl);
|
|
404
|
+
}
|
|
405
|
+
// Try direct import first (TS loader active)
|
|
406
|
+
try {
|
|
407
|
+
const dyn = await importDefault(fileUrl);
|
|
408
|
+
if (dyn)
|
|
409
|
+
return dyn;
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
/* fall through */
|
|
413
|
+
}
|
|
414
|
+
const stat = await fs.stat(absPath);
|
|
415
|
+
const hash = cacheHash(absPath, stat.mtimeMs);
|
|
416
|
+
const cacheDir = path.resolve('.tsbuild', cacheDirName);
|
|
417
|
+
await fs.ensureDir(cacheDir);
|
|
418
|
+
const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
|
|
419
|
+
// Try esbuild
|
|
420
|
+
try {
|
|
421
|
+
const esbuild = (await import('esbuild'));
|
|
422
|
+
await esbuild.build({
|
|
423
|
+
entryPoints: [absPath],
|
|
424
|
+
bundle: true,
|
|
425
|
+
platform: 'node',
|
|
426
|
+
format: 'esm',
|
|
427
|
+
target: 'node20',
|
|
428
|
+
outfile: cacheFile,
|
|
429
|
+
sourcemap: false,
|
|
430
|
+
logLevel: 'silent',
|
|
431
|
+
});
|
|
432
|
+
const result = await importDefault(url.pathToFileURL(cacheFile).toString());
|
|
433
|
+
// Best-effort: trim older cache files for this source.
|
|
434
|
+
await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
|
|
435
|
+
return result;
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
/* fall through to TS transpile */
|
|
439
|
+
}
|
|
440
|
+
// TypeScript transpile fallback
|
|
441
|
+
try {
|
|
442
|
+
const ts = (await import('typescript'));
|
|
443
|
+
const code = await fs.readFile(absPath, 'utf-8');
|
|
444
|
+
const out = ts.transpileModule(code, {
|
|
445
|
+
compilerOptions: {
|
|
446
|
+
module: 'ESNext',
|
|
447
|
+
target: 'ES2022',
|
|
448
|
+
moduleResolution: 'NodeNext',
|
|
449
|
+
},
|
|
450
|
+
}).outputText;
|
|
451
|
+
await fs.writeFile(cacheFile, out, 'utf-8');
|
|
452
|
+
const result = await importDefault(url.pathToFileURL(cacheFile).toString());
|
|
453
|
+
// Best-effort: trim older cache files for this source.
|
|
454
|
+
await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
|
|
455
|
+
return result;
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
// Caller decides final error wording; rethrow for upstream mapping.
|
|
459
|
+
throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
|
|
187
460
|
}
|
|
188
|
-
merged.shell = resolvedShell;
|
|
189
|
-
const cmd = typeof command === 'string' ? command : undefined;
|
|
190
|
-
return cmd !== undefined ? { merged, command: cmd } : { merged };
|
|
191
461
|
};
|
|
192
462
|
|
|
463
|
+
/** src/util/omitUndefined.ts
|
|
464
|
+
* Helpers to drop undefined-valued properties in a typed-friendly way.
|
|
465
|
+
*/
|
|
193
466
|
/**
|
|
194
|
-
*
|
|
467
|
+
* Omit keys whose runtime value is undefined from a shallow object.
|
|
468
|
+
* Returns a Partial with non-undefined value types preserved.
|
|
469
|
+
*/
|
|
470
|
+
function omitUndefined(obj) {
|
|
471
|
+
const out = {};
|
|
472
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
473
|
+
if (v !== undefined)
|
|
474
|
+
out[k] = v;
|
|
475
|
+
}
|
|
476
|
+
return out;
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Specialized helper for env-like maps: drop undefined and return string-only.
|
|
480
|
+
*/
|
|
481
|
+
function omitUndefinedRecord(obj) {
|
|
482
|
+
const out = {};
|
|
483
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
484
|
+
if (v !== undefined)
|
|
485
|
+
out[k] = v;
|
|
486
|
+
}
|
|
487
|
+
return out;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Minimal tokenizer for shell-off execution.
|
|
492
|
+
* Splits by whitespace while preserving quoted segments (single or double quotes).
|
|
195
493
|
*
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
* - RESOLVED: normalized shapes (paths always string[]).
|
|
199
|
-
* - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
|
|
494
|
+
* @param command - The command string to tokenize.
|
|
495
|
+
* @param opts - Tokenization options (e.g. quote handling).
|
|
200
496
|
*/
|
|
201
|
-
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
497
|
+
const tokenize = (command, opts) => {
|
|
498
|
+
const out = [];
|
|
499
|
+
let cur = '';
|
|
500
|
+
let quote = null;
|
|
501
|
+
for (let i = 0; i < command.length; i++) {
|
|
502
|
+
const c = command.charAt(i);
|
|
503
|
+
if (quote) {
|
|
504
|
+
if (c === quote) {
|
|
505
|
+
// Support doubled quotes inside a quoted segment:
|
|
506
|
+
// default: "" -> " and '' -> ' (Windows/PowerShell style)
|
|
507
|
+
// preserve: keep as "" to allow empty string literals in Node -e payloads
|
|
508
|
+
const next = command.charAt(i + 1);
|
|
509
|
+
if (next === quote) {
|
|
510
|
+
{
|
|
511
|
+
// Collapse to a single literal quote
|
|
512
|
+
cur += quote;
|
|
513
|
+
i += 1; // skip the second quote
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
// end of quoted segment
|
|
518
|
+
quote = null;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
else {
|
|
522
|
+
cur += c;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
if (c === '"' || c === "'") {
|
|
527
|
+
quote = c;
|
|
528
|
+
}
|
|
529
|
+
else if (/\s/.test(c)) {
|
|
530
|
+
if (cur) {
|
|
531
|
+
out.push(cur);
|
|
532
|
+
cur = '';
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
else {
|
|
536
|
+
cur += c;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (cur)
|
|
541
|
+
out.push(cur);
|
|
542
|
+
return out;
|
|
543
|
+
};
|
|
229
544
|
|
|
545
|
+
/**
|
|
546
|
+
* @packageDocumentation
|
|
547
|
+
* Configuration discovery and loading for get‑dotenv. Discovers config files
|
|
548
|
+
* in the packaged root and project root, loads JSON/YAML/JS/TS documents, and
|
|
549
|
+
* validates them against Zod schemas.
|
|
550
|
+
*/
|
|
230
551
|
// Discovery candidates (first match wins per scope/privacy).
|
|
231
552
|
// Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
|
|
232
553
|
const PUBLIC_FILENAMES = [
|
|
@@ -254,75 +575,6 @@ const LOCAL_FILENAMES = [
|
|
|
254
575
|
const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
|
|
255
576
|
const isJson = (p) => extname(p).toLowerCase() === '.json';
|
|
256
577
|
const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
|
|
257
|
-
// --- Internal JS/TS module loader helpers (default export) ---
|
|
258
|
-
const importDefault$1 = async (fileUrl) => {
|
|
259
|
-
const mod = (await import(fileUrl));
|
|
260
|
-
return mod.default;
|
|
261
|
-
};
|
|
262
|
-
const cacheName = (absPath, suffix) => {
|
|
263
|
-
// sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
|
|
264
|
-
const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
265
|
-
return `${base}.${suffix}.mjs`;
|
|
266
|
-
};
|
|
267
|
-
const ensureDir = async (dir) => {
|
|
268
|
-
await fs.ensureDir(dir);
|
|
269
|
-
return dir;
|
|
270
|
-
};
|
|
271
|
-
const loadJsTsDefault = async (absPath) => {
|
|
272
|
-
const fileUrl = pathToFileURL(absPath).toString();
|
|
273
|
-
const ext = extname(absPath).toLowerCase();
|
|
274
|
-
if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
|
|
275
|
-
return importDefault$1(fileUrl);
|
|
276
|
-
}
|
|
277
|
-
// Try direct import first in case a TS loader is active.
|
|
278
|
-
try {
|
|
279
|
-
const val = await importDefault$1(fileUrl);
|
|
280
|
-
if (val)
|
|
281
|
-
return val;
|
|
282
|
-
}
|
|
283
|
-
catch {
|
|
284
|
-
/* fallthrough */
|
|
285
|
-
}
|
|
286
|
-
// esbuild bundle to a temp ESM file
|
|
287
|
-
try {
|
|
288
|
-
const esbuild = (await import('esbuild'));
|
|
289
|
-
const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
|
|
290
|
-
const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
|
|
291
|
-
await esbuild.build({
|
|
292
|
-
entryPoints: [absPath],
|
|
293
|
-
bundle: true,
|
|
294
|
-
platform: 'node',
|
|
295
|
-
format: 'esm',
|
|
296
|
-
target: 'node20',
|
|
297
|
-
outfile,
|
|
298
|
-
sourcemap: false,
|
|
299
|
-
logLevel: 'silent',
|
|
300
|
-
});
|
|
301
|
-
return await importDefault$1(pathToFileURL(outfile).toString());
|
|
302
|
-
}
|
|
303
|
-
catch {
|
|
304
|
-
/* fallthrough to TS transpile */
|
|
305
|
-
}
|
|
306
|
-
// typescript.transpileModule simple transpile (single-file)
|
|
307
|
-
try {
|
|
308
|
-
const ts = (await import('typescript'));
|
|
309
|
-
const src = await fs.readFile(absPath, 'utf-8');
|
|
310
|
-
const out = ts.transpileModule(src, {
|
|
311
|
-
compilerOptions: {
|
|
312
|
-
module: 'ESNext',
|
|
313
|
-
target: 'ES2022',
|
|
314
|
-
moduleResolution: 'NodeNext',
|
|
315
|
-
},
|
|
316
|
-
}).outputText;
|
|
317
|
-
const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
|
|
318
|
-
const outfile = path.join(outDir, cacheName(absPath, 'ts'));
|
|
319
|
-
await fs.writeFile(outfile, out, 'utf-8');
|
|
320
|
-
return await importDefault$1(pathToFileURL(outfile).toString());
|
|
321
|
-
}
|
|
322
|
-
catch {
|
|
323
|
-
throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
|
|
324
|
-
}
|
|
325
|
-
};
|
|
326
578
|
/**
|
|
327
579
|
* Discover JSON/YAML config files in the packaged root and project root.
|
|
328
580
|
* Order: packaged public → project public → project local. */
|
|
@@ -375,8 +627,8 @@ const loadConfigFile = async (filePath) => {
|
|
|
375
627
|
try {
|
|
376
628
|
const abs = path.resolve(filePath);
|
|
377
629
|
if (isJsOrTs(abs)) {
|
|
378
|
-
// JS/TS support: load default export via robust pipeline.
|
|
379
|
-
const mod = await
|
|
630
|
+
// JS/TS support: load default export via shared robust pipeline.
|
|
631
|
+
const mod = await loadModuleDefault(abs, 'getdotenv-config');
|
|
380
632
|
raw = mod ?? {};
|
|
381
633
|
}
|
|
382
634
|
else {
|
|
@@ -392,571 +644,87 @@ const loadConfigFile = async (filePath) => {
|
|
|
392
644
|
if (!parsed.success) {
|
|
393
645
|
const msgs = parsed.error.issues
|
|
394
646
|
.map((i) => `${i.path.join('.')}: ${i.message}`)
|
|
395
|
-
.join('\n');
|
|
396
|
-
throw new Error(`Invalid config ${filePath}:\n${msgs}`);
|
|
397
|
-
}
|
|
398
|
-
// Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
|
|
399
|
-
if (!isJsOrTs(filePath) &&
|
|
400
|
-
(parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
|
|
401
|
-
throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
|
|
402
|
-
`Use JS/TS config for "dynamic" or "schema".`);
|
|
403
|
-
}
|
|
404
|
-
return getDotenvConfigSchemaResolved.parse(parsed.data);
|
|
405
|
-
};
|
|
406
|
-
/**
|
|
407
|
-
* Discover and load configs into resolved shapes, ordered by scope/privacy.
|
|
408
|
-
* JSON/YAML/JS/TS supported; first match per scope/privacy applies.
|
|
409
|
-
*/
|
|
410
|
-
const resolveGetDotenvConfigSources = async (importMetaUrl) => {
|
|
411
|
-
const discovered = await discoverConfigFiles(importMetaUrl);
|
|
412
|
-
const result = {};
|
|
413
|
-
for (const f of discovered) {
|
|
414
|
-
const cfg = await loadConfigFile(f.path);
|
|
415
|
-
if (f.scope === 'packaged') {
|
|
416
|
-
// packaged public only
|
|
417
|
-
result.packaged = cfg;
|
|
418
|
-
}
|
|
419
|
-
else {
|
|
420
|
-
result.project ??= {};
|
|
421
|
-
if (f.privacy === 'public')
|
|
422
|
-
result.project.public = cfg;
|
|
423
|
-
else
|
|
424
|
-
result.project.local = cfg;
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
return result;
|
|
428
|
-
};
|
|
429
|
-
|
|
430
|
-
/**
|
|
431
|
-
* Validate a composed env against config-provided validation surfaces.
|
|
432
|
-
* Precedence for validation definitions:
|
|
433
|
-
* project.local -\> project.public -\> packaged
|
|
434
|
-
*
|
|
435
|
-
* Behavior:
|
|
436
|
-
* - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
|
|
437
|
-
* - Else if `requiredKeys` is present, check presence (value !== undefined).
|
|
438
|
-
* - Returns a flat list of issue strings; caller decides warn vs fail.
|
|
439
|
-
*/
|
|
440
|
-
const validateEnvAgainstSources = (finalEnv, sources) => {
|
|
441
|
-
const pick = (getter) => {
|
|
442
|
-
const pl = sources.project?.local;
|
|
443
|
-
const pp = sources.project?.public;
|
|
444
|
-
const pk = sources.packaged;
|
|
445
|
-
return ((pl && getter(pl)) ||
|
|
446
|
-
(pp && getter(pp)) ||
|
|
447
|
-
(pk && getter(pk)) ||
|
|
448
|
-
undefined);
|
|
449
|
-
};
|
|
450
|
-
const schema = pick((cfg) => cfg['schema']);
|
|
451
|
-
if (schema &&
|
|
452
|
-
typeof schema.safeParse === 'function') {
|
|
453
|
-
try {
|
|
454
|
-
const parsed = schema.safeParse(finalEnv);
|
|
455
|
-
if (!parsed.success) {
|
|
456
|
-
// Try to render zod-style issues when available.
|
|
457
|
-
const err = parsed.error;
|
|
458
|
-
const issues = Array.isArray(err.issues) && err.issues.length > 0
|
|
459
|
-
? err.issues.map((i) => {
|
|
460
|
-
const path = Array.isArray(i.path) ? i.path.join('.') : '';
|
|
461
|
-
const msg = i.message ?? 'Invalid value';
|
|
462
|
-
return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
|
|
463
|
-
})
|
|
464
|
-
: ['[schema] validation failed'];
|
|
465
|
-
return issues;
|
|
466
|
-
}
|
|
467
|
-
return [];
|
|
468
|
-
}
|
|
469
|
-
catch {
|
|
470
|
-
// If schema invocation fails, surface a single diagnostic.
|
|
471
|
-
return [
|
|
472
|
-
'[schema] validation failed (unable to execute schema.safeParse)',
|
|
473
|
-
];
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
const requiredKeys = pick((cfg) => cfg['requiredKeys']);
|
|
477
|
-
if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
|
|
478
|
-
const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
|
|
479
|
-
if (missing.length > 0) {
|
|
480
|
-
return missing.map((k) => `[requiredKeys] missing: ${k}`);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
return [];
|
|
484
|
-
};
|
|
485
|
-
|
|
486
|
-
const baseGetDotenvCliOptions = baseRootOptionDefaults;
|
|
487
|
-
|
|
488
|
-
/** src/util/omitUndefined.ts
|
|
489
|
-
* Helpers to drop undefined-valued properties in a typed-friendly way.
|
|
490
|
-
*/
|
|
491
|
-
/**
|
|
492
|
-
* Omit keys whose runtime value is undefined from a shallow object.
|
|
493
|
-
* Returns a Partial with non-undefined value types preserved.
|
|
494
|
-
*/
|
|
495
|
-
function omitUndefined(obj) {
|
|
496
|
-
const out = {};
|
|
497
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
498
|
-
if (v !== undefined)
|
|
499
|
-
out[k] = v;
|
|
500
|
-
}
|
|
501
|
-
return out;
|
|
502
|
-
}
|
|
503
|
-
/**
|
|
504
|
-
* Specialized helper for env-like maps: drop undefined and return string-only.
|
|
505
|
-
*/
|
|
506
|
-
function omitUndefinedRecord(obj) {
|
|
507
|
-
const out = {};
|
|
508
|
-
for (const [k, v] of Object.entries(obj)) {
|
|
509
|
-
if (v !== undefined)
|
|
510
|
-
out[k] = v;
|
|
511
|
-
}
|
|
512
|
-
return out;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
// src/GetDotenvOptions.ts
|
|
516
|
-
/**
|
|
517
|
-
* Canonical programmatic options and helpers for get-dotenv.
|
|
518
|
-
*
|
|
519
|
-
* Requirements addressed:
|
|
520
|
-
* - GetDotenvOptions derives from the Zod schema output (single source of truth).
|
|
521
|
-
* - Removed deprecated/compat flags from the public shape (e.g., useConfigLoader).
|
|
522
|
-
* - Provide Vars-aware defineDynamic and a typed config builder defineGetDotenvConfig\<Vars, Env\>().
|
|
523
|
-
* - Preserve existing behavior for defaults resolution and compat converters.
|
|
524
|
-
*/
|
|
525
|
-
const getDotenvOptionsFilename = 'getdotenv.config.json';
|
|
526
|
-
/**
|
|
527
|
-
* Converts programmatic CLI options to `getDotenv` options.
|
|
528
|
-
*
|
|
529
|
-
* Accepts "stringly" CLI inputs for vars/paths and normalizes them into
|
|
530
|
-
* the programmatic shape. Preserves exactOptionalPropertyTypes semantics by
|
|
531
|
-
* omitting keys when undefined.
|
|
532
|
-
*/
|
|
533
|
-
const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern,
|
|
534
|
-
// drop CLI-only keys from the pass-through bag
|
|
535
|
-
debug: _debug, scripts: _scripts, ...rest }) => {
|
|
536
|
-
// Split helper for delimited strings or regex patterns
|
|
537
|
-
const splitBy = (value, delim, pattern) => {
|
|
538
|
-
if (!value)
|
|
539
|
-
return [];
|
|
540
|
-
if (pattern)
|
|
541
|
-
return value.split(RegExp(pattern));
|
|
542
|
-
if (typeof delim === 'string')
|
|
543
|
-
return value.split(delim);
|
|
544
|
-
return value.split(' ');
|
|
545
|
-
};
|
|
546
|
-
// Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
|
|
547
|
-
let parsedVars;
|
|
548
|
-
if (typeof vars === 'string') {
|
|
549
|
-
const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern)
|
|
550
|
-
.map((v) => v.split(varsAssignorPattern
|
|
551
|
-
? RegExp(varsAssignorPattern)
|
|
552
|
-
: (varsAssignor ?? '=')))
|
|
553
|
-
.filter(([k]) => typeof k === 'string' && k.length > 0);
|
|
554
|
-
parsedVars = Object.fromEntries(kvPairs);
|
|
555
|
-
}
|
|
556
|
-
else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
|
|
557
|
-
// Accept provided object map of string | undefined; drop undefined values
|
|
558
|
-
// in the normalization step below to produce a ProcessEnv-compatible bag.
|
|
559
|
-
parsedVars = Object.fromEntries(Object.entries(vars));
|
|
560
|
-
}
|
|
561
|
-
// Drop undefined-valued entries at the converter stage to match ProcessEnv
|
|
562
|
-
// expectations and the compat test assertions.
|
|
563
|
-
if (parsedVars) {
|
|
564
|
-
parsedVars = omitUndefinedRecord(parsedVars);
|
|
565
|
-
}
|
|
566
|
-
// Tolerate paths as either a delimited string or string[]
|
|
567
|
-
const pathsOut = Array.isArray(paths)
|
|
568
|
-
? paths.filter((p) => typeof p === 'string')
|
|
569
|
-
: splitBy(paths, pathsDelimiter, pathsDelimiterPattern);
|
|
570
|
-
// Preserve exactOptionalPropertyTypes: only include keys when defined.
|
|
571
|
-
return {
|
|
572
|
-
...rest,
|
|
573
|
-
...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
|
|
574
|
-
...(parsedVars !== undefined ? { vars: parsedVars } : {}),
|
|
575
|
-
};
|
|
576
|
-
};
|
|
577
|
-
/**
|
|
578
|
-
* Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
|
|
579
|
-
*
|
|
580
|
-
* 1. Base defaults derived from the CLI generator defaults
|
|
581
|
-
* ({@link baseGetDotenvCliOptions}).
|
|
582
|
-
* 2. Local project overrides from a `getdotenv.config.json` in the nearest
|
|
583
|
-
* package root (if present).
|
|
584
|
-
* 3. The provided customOptions.
|
|
585
|
-
*
|
|
586
|
-
* The result preserves explicit empty values and drops only `undefined`.
|
|
587
|
-
*/
|
|
588
|
-
const resolveGetDotenvOptions = async (customOptions) => {
|
|
589
|
-
const localPkgDir = await packageDirectory();
|
|
590
|
-
const localOptionsPath = localPkgDir
|
|
591
|
-
? join(localPkgDir, getDotenvOptionsFilename)
|
|
592
|
-
: undefined;
|
|
593
|
-
// Safely read local CLI-facing defaults (defensive typing to satisfy strict linting).
|
|
594
|
-
let localOptions = {};
|
|
595
|
-
if (localOptionsPath && (await fs.exists(localOptionsPath))) {
|
|
596
|
-
try {
|
|
597
|
-
const txt = await fs.readFile(localOptionsPath, 'utf-8');
|
|
598
|
-
const parsed = JSON.parse(txt);
|
|
599
|
-
if (parsed && typeof parsed === 'object') {
|
|
600
|
-
localOptions = parsed;
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
catch {
|
|
604
|
-
// Malformed or unreadable local options are treated as absent.
|
|
605
|
-
localOptions = {};
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
// Merge order: base < local < custom (custom has highest precedence)
|
|
609
|
-
const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
|
|
610
|
-
const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
|
|
611
|
-
const result = defaultsDeep(defaultsFromCli, customOptions);
|
|
612
|
-
return {
|
|
613
|
-
...result, // Keep explicit empty strings/zeros; drop only undefined
|
|
614
|
-
vars: omitUndefinedRecord(result.vars ?? {}),
|
|
615
|
-
};
|
|
616
|
-
};
|
|
617
|
-
|
|
618
|
-
/**
|
|
619
|
-
* Dotenv expansion utilities.
|
|
620
|
-
*
|
|
621
|
-
* This module implements recursive expansion of environment-variable
|
|
622
|
-
* references in strings and records. It supports both whitespace and
|
|
623
|
-
* bracket syntaxes with optional defaults:
|
|
624
|
-
*
|
|
625
|
-
* - Whitespace: `$VAR[:default]`
|
|
626
|
-
* - Bracketed: `${VAR[:default]}`
|
|
627
|
-
*
|
|
628
|
-
* Escaped dollar signs (`\$`) are preserved.
|
|
629
|
-
* Unknown variables resolve to empty string unless a default is provided.
|
|
630
|
-
*/
|
|
631
|
-
/**
|
|
632
|
-
* Like String.prototype.search but returns the last index.
|
|
633
|
-
* @internal
|
|
634
|
-
*/
|
|
635
|
-
const searchLast = (str, rgx) => {
|
|
636
|
-
const matches = Array.from(str.matchAll(rgx));
|
|
637
|
-
return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
|
|
638
|
-
};
|
|
639
|
-
const replaceMatch = (value, match, ref) => {
|
|
640
|
-
/**
|
|
641
|
-
* @internal
|
|
642
|
-
*/
|
|
643
|
-
const group = match[0];
|
|
644
|
-
const key = match[1];
|
|
645
|
-
const defaultValue = match[2];
|
|
646
|
-
if (!key)
|
|
647
|
-
return value;
|
|
648
|
-
const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
|
|
649
|
-
return interpolate(replacement, ref);
|
|
650
|
-
};
|
|
651
|
-
const interpolate = (value = '', ref = {}) => {
|
|
652
|
-
/**
|
|
653
|
-
* @internal
|
|
654
|
-
*/
|
|
655
|
-
// if value is falsy, return it as is
|
|
656
|
-
if (!value)
|
|
657
|
-
return value;
|
|
658
|
-
// get position of last unescaped dollar sign
|
|
659
|
-
const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
|
|
660
|
-
// return value if none found
|
|
661
|
-
if (lastUnescapedDollarSignIndex === -1)
|
|
662
|
-
return value;
|
|
663
|
-
// evaluate the value tail
|
|
664
|
-
const tail = value.slice(lastUnescapedDollarSignIndex);
|
|
665
|
-
// find whitespace pattern: $KEY:DEFAULT
|
|
666
|
-
const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
|
|
667
|
-
const whitespaceMatch = whitespacePattern.exec(tail);
|
|
668
|
-
if (whitespaceMatch != null)
|
|
669
|
-
return replaceMatch(value, whitespaceMatch, ref);
|
|
670
|
-
else {
|
|
671
|
-
// find bracket pattern: ${KEY:DEFAULT}
|
|
672
|
-
const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
|
|
673
|
-
const bracketMatch = bracketPattern.exec(tail);
|
|
674
|
-
if (bracketMatch != null)
|
|
675
|
-
return replaceMatch(value, bracketMatch, ref);
|
|
647
|
+
.join('\n');
|
|
648
|
+
throw new Error(`Invalid config ${filePath}:\n${msgs}`);
|
|
676
649
|
}
|
|
677
|
-
|
|
650
|
+
// Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
|
|
651
|
+
if (!isJsOrTs(filePath) &&
|
|
652
|
+
(parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
|
|
653
|
+
throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
|
|
654
|
+
`Use JS/TS config for "dynamic" or "schema".`);
|
|
655
|
+
}
|
|
656
|
+
return getDotenvConfigSchemaResolved.parse(parsed.data);
|
|
678
657
|
};
|
|
679
658
|
/**
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
* Unknown variables will expand to an empty string.
|
|
683
|
-
*
|
|
684
|
-
* @param value - The string to expand.
|
|
685
|
-
* @param ref - The reference object to use for variable expansion.
|
|
686
|
-
* @returns The expanded string.
|
|
687
|
-
*
|
|
688
|
-
* @example
|
|
689
|
-
* ```ts
|
|
690
|
-
* process.env.FOO = 'bar';
|
|
691
|
-
* dotenvExpand('Hello $FOO'); // "Hello bar"
|
|
692
|
-
* dotenvExpand('Hello $BAZ:world'); // "Hello world"
|
|
693
|
-
* ```
|
|
694
|
-
*
|
|
695
|
-
* @remarks
|
|
696
|
-
* The expansion is recursive. If a referenced variable itself contains
|
|
697
|
-
* references, those will also be expanded until a stable value is reached.
|
|
698
|
-
* Escaped references (e.g. `\$FOO`) are preserved as literals.
|
|
659
|
+
* Discover and load configs into resolved shapes, ordered by scope/privacy.
|
|
660
|
+
* JSON/YAML/JS/TS supported; first match per scope/privacy applies.
|
|
699
661
|
*/
|
|
700
|
-
const
|
|
701
|
-
const
|
|
702
|
-
|
|
662
|
+
const resolveGetDotenvConfigSources = async (importMetaUrl) => {
|
|
663
|
+
const discovered = await discoverConfigFiles(importMetaUrl);
|
|
664
|
+
const result = {};
|
|
665
|
+
for (const f of discovered) {
|
|
666
|
+
const cfg = await loadConfigFile(f.path);
|
|
667
|
+
if (f.scope === 'packaged') {
|
|
668
|
+
// packaged public only
|
|
669
|
+
result.packaged = cfg;
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
result.project ??= {};
|
|
673
|
+
if (f.privacy === 'public')
|
|
674
|
+
result.project.public = cfg;
|
|
675
|
+
else
|
|
676
|
+
result.project.local = cfg;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return result;
|
|
703
680
|
};
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
*
|
|
707
|
-
* `${VAR[:default]}`. Unknown variables will expand to an empty string.
|
|
708
|
-
*
|
|
709
|
-
* @param values - The values object to expand.
|
|
710
|
-
* @param options - Expansion options.
|
|
711
|
-
* @returns The value object with expanded string values.
|
|
712
|
-
*
|
|
713
|
-
* @example
|
|
714
|
-
* ```ts
|
|
715
|
-
* process.env.FOO = 'bar';
|
|
716
|
-
* dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
|
|
717
|
-
* // => { A: "bar", B: "xbary" }
|
|
718
|
-
* ```
|
|
719
|
-
*
|
|
720
|
-
* @remarks
|
|
721
|
-
* Options:
|
|
722
|
-
* - ref: The reference object to use for expansion (defaults to process.env).
|
|
723
|
-
* - progressive: Whether to progressively add expanded values to the set of
|
|
724
|
-
* reference keys.
|
|
725
|
-
*
|
|
726
|
-
* When `progressive` is true, each expanded key becomes available for
|
|
727
|
-
* subsequent expansions in the same object (left-to-right by object key order).
|
|
728
|
-
*/
|
|
729
|
-
function dotenvExpandAll(values, options = {}) {
|
|
730
|
-
const { ref = process.env, progressive = false, } = options;
|
|
731
|
-
const out = Object.keys(values).reduce((acc, key) => {
|
|
732
|
-
acc[key] = dotenvExpand(values[key], {
|
|
733
|
-
...ref,
|
|
734
|
-
...(progressive ? acc : {}),
|
|
735
|
-
});
|
|
736
|
-
return acc;
|
|
737
|
-
}, {});
|
|
738
|
-
// Key-preserving return with a permissive index signature to allow later additions.
|
|
739
|
-
return out;
|
|
740
|
-
}
|
|
741
|
-
/**
|
|
742
|
-
* Recursively expands environment variables in a string using `process.env` as
|
|
743
|
-
* the expansion reference. Variables may be presented with optional default as
|
|
744
|
-
* `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
|
|
745
|
-
* empty string.
|
|
746
|
-
*
|
|
747
|
-
* @param value - The string to expand.
|
|
748
|
-
* @returns The expanded string.
|
|
681
|
+
|
|
682
|
+
/** src/env/dynamic.ts
|
|
683
|
+
* Helpers for applying and loading dynamic variables (JS/TS).
|
|
749
684
|
*
|
|
750
|
-
*
|
|
751
|
-
*
|
|
752
|
-
*
|
|
753
|
-
*
|
|
754
|
-
* ```
|
|
685
|
+
* Requirements addressed:
|
|
686
|
+
* - Single service to apply a dynamic map progressively.
|
|
687
|
+
* - Single service to load a JS/TS dynamic module with robust fallbacks (util/loadModuleDefault).
|
|
688
|
+
* - Unify error messaging so callers show consistent guidance.
|
|
755
689
|
*/
|
|
756
|
-
const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
|
|
757
|
-
|
|
758
|
-
/* eslint-disable @typescript-eslint/no-deprecated */
|
|
759
690
|
/**
|
|
760
|
-
*
|
|
761
|
-
* -
|
|
762
|
-
* -
|
|
691
|
+
* Apply a dynamic map to the target progressively.
|
|
692
|
+
* - Functions receive (target, env) and may return string | undefined.
|
|
693
|
+
* - Literals are assigned directly (including undefined).
|
|
763
694
|
*/
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
const
|
|
768
|
-
const
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
const originalAddOption = program.addOption.bind(program);
|
|
775
|
-
const originalOption = program.option.bind(program);
|
|
776
|
-
program.addOption = function patchedAdd(opt) {
|
|
777
|
-
program.setOptionGroup(opt, GROUP);
|
|
778
|
-
return originalAddOption(opt);
|
|
779
|
-
};
|
|
780
|
-
program.option = function patchedOption(...args) {
|
|
781
|
-
const ret = originalOption(...args);
|
|
782
|
-
tagLatest(this, GROUP);
|
|
783
|
-
return ret;
|
|
784
|
-
};
|
|
785
|
-
const { defaultEnv, dotenvToken, dynamicPath, env, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
|
|
786
|
-
const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
|
|
787
|
-
const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
|
|
788
|
-
// Helper: append (default) tags for ON/OFF toggles
|
|
789
|
-
const onOff = (on, isDefault) => on
|
|
790
|
-
? `ON${isDefault ? ' (default)' : ''}`
|
|
791
|
-
: `OFF${isDefault ? ' (default)' : ''}`;
|
|
792
|
-
let p = program
|
|
793
|
-
.enablePositionalOptions()
|
|
794
|
-
.passThroughOptions()
|
|
795
|
-
.option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
|
|
796
|
-
p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
|
|
797
|
-
['KEY1', 'VAL1'],
|
|
798
|
-
['KEY2', 'VAL2'],
|
|
799
|
-
]
|
|
800
|
-
.map((v) => v.join(va))
|
|
801
|
-
.join(vd)}`, dotenvExpandFromProcessEnv);
|
|
802
|
-
// Output path (interpolated later; help can remain static)
|
|
803
|
-
p = p.option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath);
|
|
804
|
-
// Shell ON (string or boolean true => default shell)
|
|
805
|
-
p = p
|
|
806
|
-
.addOption(program
|
|
807
|
-
.createDynamicOption('-s, --shell [string]', (cfg) => {
|
|
808
|
-
const s = cfg.shell;
|
|
809
|
-
let tag = '';
|
|
810
|
-
if (typeof s === 'boolean' && s)
|
|
811
|
-
tag = ' (default OS shell)';
|
|
812
|
-
else if (typeof s === 'string' && s.length > 0)
|
|
813
|
-
tag = ` (default ${s})`;
|
|
814
|
-
return `command execution shell, no argument for default OS shell or provide shell string${tag}`;
|
|
815
|
-
})
|
|
816
|
-
.conflicts('shellOff'))
|
|
817
|
-
// Shell OFF
|
|
818
|
-
.addOption(program
|
|
819
|
-
.createDynamicOption('-S, --shell-off', (cfg) => {
|
|
820
|
-
const s = cfg.shell;
|
|
821
|
-
return `command execution shell OFF${s === false ? ' (default)' : ''}`;
|
|
822
|
-
})
|
|
823
|
-
.conflicts('shell'));
|
|
824
|
-
// Load process ON/OFF (dynamic defaults)
|
|
825
|
-
p = p
|
|
826
|
-
.addOption(program
|
|
827
|
-
.createDynamicOption('-p, --load-process', (cfg) => `load variables to process.env ${onOff(true, Boolean(cfg.loadProcess))}`)
|
|
828
|
-
.conflicts('loadProcessOff'))
|
|
829
|
-
.addOption(program
|
|
830
|
-
.createDynamicOption('-P, --load-process-off', (cfg) => `load variables to process.env ${onOff(false, !cfg.loadProcess)}`)
|
|
831
|
-
.conflicts('loadProcess'));
|
|
832
|
-
// Exclusion master toggle (dynamic)
|
|
833
|
-
p = p
|
|
834
|
-
.addOption(program
|
|
835
|
-
.createDynamicOption('-a, --exclude-all', (cfg) => {
|
|
836
|
-
const allOn = !!cfg.excludeDynamic &&
|
|
837
|
-
((!!cfg.excludeEnv && !!cfg.excludeGlobal) ||
|
|
838
|
-
(!!cfg.excludePrivate && !!cfg.excludePublic));
|
|
839
|
-
const suffix = allOn ? ' (default)' : '';
|
|
840
|
-
return `exclude all dotenv variables from loading ON${suffix}`;
|
|
841
|
-
})
|
|
842
|
-
.conflicts('excludeAllOff'))
|
|
843
|
-
.addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'));
|
|
844
|
-
// Per-family exclusions (dynamic defaults)
|
|
845
|
-
p = p
|
|
846
|
-
.addOption(program
|
|
847
|
-
.createDynamicOption('-z, --exclude-dynamic', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(true, Boolean(cfg.excludeDynamic))}`)
|
|
848
|
-
.conflicts('excludeDynamicOff'))
|
|
849
|
-
.addOption(program
|
|
850
|
-
.createDynamicOption('-Z, --exclude-dynamic-off', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(false, !cfg.excludeDynamic)}`)
|
|
851
|
-
.conflicts('excludeDynamic'))
|
|
852
|
-
.addOption(program
|
|
853
|
-
.createDynamicOption('-n, --exclude-env', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(true, Boolean(cfg.excludeEnv))}`)
|
|
854
|
-
.conflicts('excludeEnvOff'))
|
|
855
|
-
.addOption(program
|
|
856
|
-
.createDynamicOption('-N, --exclude-env-off', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(false, !cfg.excludeEnv)}`)
|
|
857
|
-
.conflicts('excludeEnv'))
|
|
858
|
-
.addOption(program
|
|
859
|
-
.createDynamicOption('-g, --exclude-global', (cfg) => `exclude global dotenv variables from loading ${onOff(true, Boolean(cfg.excludeGlobal))}`)
|
|
860
|
-
.conflicts('excludeGlobalOff'))
|
|
861
|
-
.addOption(program
|
|
862
|
-
.createDynamicOption('-G, --exclude-global-off', (cfg) => `exclude global dotenv variables from loading ${onOff(false, !cfg.excludeGlobal)}`)
|
|
863
|
-
.conflicts('excludeGlobal'))
|
|
864
|
-
.addOption(program
|
|
865
|
-
.createDynamicOption('-r, --exclude-private', (cfg) => `exclude private dotenv variables from loading ${onOff(true, Boolean(cfg.excludePrivate))}`)
|
|
866
|
-
.conflicts('excludePrivateOff'))
|
|
867
|
-
.addOption(program
|
|
868
|
-
.createDynamicOption('-R, --exclude-private-off', (cfg) => `exclude private dotenv variables from loading ${onOff(false, !cfg.excludePrivate)}`)
|
|
869
|
-
.conflicts('excludePrivate'))
|
|
870
|
-
.addOption(program
|
|
871
|
-
.createDynamicOption('-u, --exclude-public', (cfg) => `exclude public dotenv variables from loading ${onOff(true, Boolean(cfg.excludePublic))}`)
|
|
872
|
-
.conflicts('excludePublicOff'))
|
|
873
|
-
.addOption(program
|
|
874
|
-
.createDynamicOption('-U, --exclude-public-off', (cfg) => `exclude public dotenv variables from loading ${onOff(false, !cfg.excludePublic)}`)
|
|
875
|
-
.conflicts('excludePublic'));
|
|
876
|
-
// Log ON/OFF (dynamic)
|
|
877
|
-
p = p
|
|
878
|
-
.addOption(program
|
|
879
|
-
.createDynamicOption('-l, --log', (cfg) => `console log loaded variables ${onOff(true, Boolean(cfg.log))}`)
|
|
880
|
-
.conflicts('logOff'))
|
|
881
|
-
.addOption(program
|
|
882
|
-
.createDynamicOption('-L, --log-off', (cfg) => `console log loaded variables ${onOff(false, !cfg.log)}`)
|
|
883
|
-
.conflicts('log'));
|
|
884
|
-
// Capture flag (no default display; static)
|
|
885
|
-
p = p.option('--capture', 'capture child process stdio for commands (tests/CI)');
|
|
886
|
-
// Core bootstrap/static flags (kept static in help)
|
|
887
|
-
p = p
|
|
888
|
-
.option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
|
|
889
|
-
.option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
|
|
890
|
-
.option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
|
|
891
|
-
.option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
|
|
892
|
-
.option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
|
|
893
|
-
.option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
|
|
894
|
-
.option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
|
|
895
|
-
.option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
|
|
896
|
-
.option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
|
|
897
|
-
.option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
|
|
898
|
-
.option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
|
|
899
|
-
// Hidden scripts pipe-through (stringified)
|
|
900
|
-
.addOption(new Option('--scripts <string>')
|
|
901
|
-
.default(JSON.stringify(scripts))
|
|
902
|
-
.hideHelp());
|
|
903
|
-
// Diagnostics / validation / entropy
|
|
904
|
-
p = p
|
|
905
|
-
.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)')
|
|
906
|
-
.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
|
|
907
|
-
p = p
|
|
908
|
-
.addOption(program
|
|
909
|
-
.createDynamicOption('--entropy-warn', (cfg) => {
|
|
910
|
-
const warn = cfg.warnEntropy;
|
|
911
|
-
// Default is effectively ON when warnEntropy is true or undefined.
|
|
912
|
-
return `enable entropy warnings${warn === false ? '' : ' (default on)'}`;
|
|
913
|
-
})
|
|
914
|
-
.conflicts('entropyWarnOff'))
|
|
915
|
-
.addOption(program
|
|
916
|
-
.createDynamicOption('--entropy-warn-off', (cfg) => `disable entropy warnings${cfg.warnEntropy === false ? ' (default)' : ''}`)
|
|
917
|
-
.conflicts('entropyWarn'))
|
|
918
|
-
.option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
|
|
919
|
-
.option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
|
|
920
|
-
.option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
|
|
921
|
-
.option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
|
|
922
|
-
// Restore original methods
|
|
923
|
-
program.addOption = originalAddOption;
|
|
924
|
-
program.option = originalOption;
|
|
925
|
-
return p;
|
|
926
|
-
};
|
|
927
|
-
|
|
695
|
+
function applyDynamicMap(target, map, env) {
|
|
696
|
+
if (!map)
|
|
697
|
+
return;
|
|
698
|
+
for (const key of Object.keys(map)) {
|
|
699
|
+
const val = typeof map[key] === 'function'
|
|
700
|
+
? map[key](target, env)
|
|
701
|
+
: map[key];
|
|
702
|
+
Object.assign(target, { [key]: val });
|
|
703
|
+
}
|
|
704
|
+
}
|
|
928
705
|
/**
|
|
929
|
-
*
|
|
706
|
+
* Load a default-export dynamic map from a JS/TS file and apply it.
|
|
707
|
+
* Uses util/loadModuleDefault for robust TS handling (direct import, esbuild,
|
|
708
|
+
* typescript.transpile fallback).
|
|
930
709
|
*
|
|
931
|
-
*
|
|
932
|
-
*
|
|
710
|
+
* Error behavior:
|
|
711
|
+
* - On failure to load/compile/evaluate the module, throws a unified message:
|
|
712
|
+
* "Unable to load dynamic TypeScript file: <absPath>. Install 'esbuild'..."
|
|
933
713
|
*/
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
excludePublic: z.boolean().optional(),
|
|
949
|
-
loadProcess: z.boolean().optional(),
|
|
950
|
-
log: z.boolean().optional(),
|
|
951
|
-
logger: z.unknown().optional(),
|
|
952
|
-
outputPath: z.string().optional(),
|
|
953
|
-
paths: z.array(z.string()).optional(),
|
|
954
|
-
privateToken: z.string().optional(),
|
|
955
|
-
vars: processEnvSchema.optional(),
|
|
956
|
-
});
|
|
957
|
-
// RESOLVED: service-boundary contract (post-inheritance).
|
|
958
|
-
// For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
|
|
959
|
-
const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
|
|
714
|
+
async function loadAndApplyDynamic(target, absPath, env, cacheDirName) {
|
|
715
|
+
if (!(await fs.exists(absPath)))
|
|
716
|
+
return;
|
|
717
|
+
let dyn;
|
|
718
|
+
try {
|
|
719
|
+
dyn = await loadModuleDefault(absPath, cacheDirName);
|
|
720
|
+
}
|
|
721
|
+
catch {
|
|
722
|
+
// Preserve legacy/clear guidance used by tests and docs.
|
|
723
|
+
throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
|
|
724
|
+
`Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
|
|
725
|
+
}
|
|
726
|
+
applyDynamicMap(target, dyn, env);
|
|
727
|
+
}
|
|
960
728
|
|
|
961
729
|
const applyKv = (current, kv) => {
|
|
962
730
|
if (!kv || Object.keys(kv).length === 0)
|
|
@@ -972,7 +740,8 @@ const applyConfigSlice = (current, cfg, env) => {
|
|
|
972
740
|
const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
|
|
973
741
|
return applyKv(afterGlobal, envKv);
|
|
974
742
|
};
|
|
975
|
-
function overlayEnv(
|
|
743
|
+
function overlayEnv(args) {
|
|
744
|
+
const { base, env, configs } = args;
|
|
976
745
|
let current = { ...base };
|
|
977
746
|
// Source: packaged (public -> local)
|
|
978
747
|
current = applyConfigSlice(current, configs.packaged, env);
|
|
@@ -982,8 +751,8 @@ function overlayEnv({ base, env, configs, programmaticVars, }) {
|
|
|
982
751
|
current = applyConfigSlice(current, configs.project?.public, env);
|
|
983
752
|
current = applyConfigSlice(current, configs.project?.local, env);
|
|
984
753
|
// Programmatic explicit vars (top of static tier)
|
|
985
|
-
if (programmaticVars) {
|
|
986
|
-
const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
|
|
754
|
+
if ('programmaticVars' in args) {
|
|
755
|
+
const toApply = Object.fromEntries(Object.entries(args.programmaticVars).filter(([_k, v]) => typeof v === 'string'));
|
|
987
756
|
current = applyKv(current, toApply);
|
|
988
757
|
}
|
|
989
758
|
return current;
|
|
@@ -1036,29 +805,145 @@ const maybeWarnEntropy = (key, value, origin, opts, emit) => {
|
|
|
1036
805
|
emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
|
|
1037
806
|
}
|
|
1038
807
|
};
|
|
1039
|
-
|
|
1040
|
-
const DEFAULT_PATTERNS = [
|
|
1041
|
-
'\\bsecret\\b',
|
|
1042
|
-
'\\btoken\\b',
|
|
1043
|
-
'\\bpass(word)?\\b',
|
|
1044
|
-
'\\bapi[_-]?key\\b',
|
|
1045
|
-
'\\bkey\\b',
|
|
1046
|
-
];
|
|
1047
|
-
const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => typeof p === 'string' ? new RegExp(p, 'i') : p);
|
|
1048
|
-
const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
|
|
1049
|
-
const MASK = '[redacted]';
|
|
808
|
+
|
|
809
|
+
const DEFAULT_PATTERNS = [
|
|
810
|
+
'\\bsecret\\b',
|
|
811
|
+
'\\btoken\\b',
|
|
812
|
+
'\\bpass(word)?\\b',
|
|
813
|
+
'\\bapi[_-]?key\\b',
|
|
814
|
+
'\\bkey\\b',
|
|
815
|
+
];
|
|
816
|
+
const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => typeof p === 'string' ? new RegExp(p, 'i') : p);
|
|
817
|
+
const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
|
|
818
|
+
const MASK = '[redacted]';
|
|
819
|
+
/**
|
|
820
|
+
* Produce a shallow redacted copy of an env-like object for display.
|
|
821
|
+
*/
|
|
822
|
+
const redactObject = (obj, opts) => {
|
|
823
|
+
if (!opts?.redact)
|
|
824
|
+
return { ...obj };
|
|
825
|
+
const regs = compile(opts.redactPatterns);
|
|
826
|
+
const out = {};
|
|
827
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
828
|
+
out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
|
|
829
|
+
}
|
|
830
|
+
return out;
|
|
831
|
+
};
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
|
|
835
|
+
* Used as the bottom layer for CLI option resolution.
|
|
836
|
+
*/
|
|
837
|
+
/**
|
|
838
|
+
* Default values for root CLI options used by the host and helpers as the
|
|
839
|
+
* baseline layer during option resolution.
|
|
840
|
+
*
|
|
841
|
+
* These defaults correspond to the "stringly" root surface (see `RootOptionsShape`)
|
|
842
|
+
* and are merged by precedence with create-time overrides and any discovered
|
|
843
|
+
* configuration `rootOptionDefaults` before CLI flags are applied.
|
|
844
|
+
*/
|
|
845
|
+
const baseRootOptionDefaults = {
|
|
846
|
+
dotenvToken: '.env',
|
|
847
|
+
loadProcess: true,
|
|
848
|
+
logger: console,
|
|
849
|
+
// Diagnostics defaults
|
|
850
|
+
warnEntropy: true,
|
|
851
|
+
entropyThreshold: 3.8,
|
|
852
|
+
entropyMinLength: 16,
|
|
853
|
+
entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
|
|
854
|
+
paths: './',
|
|
855
|
+
pathsDelimiter: ' ',
|
|
856
|
+
privateToken: 'local',
|
|
857
|
+
scripts: {
|
|
858
|
+
'git-status': {
|
|
859
|
+
cmd: 'git branch --show-current && git status -s -u',
|
|
860
|
+
shell: true,
|
|
861
|
+
},
|
|
862
|
+
},
|
|
863
|
+
shell: true,
|
|
864
|
+
vars: '',
|
|
865
|
+
varsAssignor: '=',
|
|
866
|
+
varsDelimiter: ' ',
|
|
867
|
+
// tri-state flags default to unset unless explicitly provided
|
|
868
|
+
// (debug/log/exclude* resolved via flag utils)
|
|
869
|
+
};
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Converts programmatic CLI options to `getDotenv` options.
|
|
873
|
+
*
|
|
874
|
+
* Accepts "stringly" CLI inputs for vars/paths and normalizes them into
|
|
875
|
+
* the programmatic shape. Preserves exactOptionalPropertyTypes semantics by
|
|
876
|
+
* omitting keys when undefined.
|
|
877
|
+
*/
|
|
878
|
+
const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern,
|
|
879
|
+
// drop CLI-only keys from the pass-through bag
|
|
880
|
+
debug: _debug, scripts: _scripts, ...rest }) => {
|
|
881
|
+
// Split helper for delimited strings or regex patterns
|
|
882
|
+
const splitBy = (value, delim, pattern) => {
|
|
883
|
+
if (!value)
|
|
884
|
+
return [];
|
|
885
|
+
if (pattern)
|
|
886
|
+
return value.split(RegExp(pattern));
|
|
887
|
+
if (typeof delim === 'string')
|
|
888
|
+
return value.split(delim);
|
|
889
|
+
return value.split(' ');
|
|
890
|
+
};
|
|
891
|
+
// Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
|
|
892
|
+
let parsedVars;
|
|
893
|
+
if (typeof vars === 'string') {
|
|
894
|
+
const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern)
|
|
895
|
+
.map((v) => v.split(varsAssignorPattern
|
|
896
|
+
? RegExp(varsAssignorPattern)
|
|
897
|
+
: (varsAssignor ?? '=')))
|
|
898
|
+
.filter(([k]) => typeof k === 'string' && k.length > 0);
|
|
899
|
+
parsedVars = Object.fromEntries(kvPairs);
|
|
900
|
+
}
|
|
901
|
+
else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
|
|
902
|
+
// Accept provided object map of string | undefined; drop undefined values
|
|
903
|
+
// in the normalization step below to produce a ProcessEnv-compatible bag.
|
|
904
|
+
parsedVars = Object.fromEntries(Object.entries(vars));
|
|
905
|
+
}
|
|
906
|
+
// Drop undefined-valued entries at the converter stage to match ProcessEnv
|
|
907
|
+
// expectations and the compat test assertions.
|
|
908
|
+
if (parsedVars) {
|
|
909
|
+
parsedVars = omitUndefinedRecord(parsedVars);
|
|
910
|
+
}
|
|
911
|
+
// Tolerate paths as either a delimited string or string[]
|
|
912
|
+
const pathsOut = Array.isArray(paths)
|
|
913
|
+
? paths.filter((p) => typeof p === 'string')
|
|
914
|
+
: splitBy(paths, pathsDelimiter, pathsDelimiterPattern);
|
|
915
|
+
// Preserve exactOptionalPropertyTypes: only include keys when defined.
|
|
916
|
+
return {
|
|
917
|
+
// Ensure the required logger property is present. The base CLI defaults
|
|
918
|
+
// specify console as the logger; callers can override upstream if desired.
|
|
919
|
+
logger: console,
|
|
920
|
+
...rest,
|
|
921
|
+
...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
|
|
922
|
+
...(parsedVars !== undefined ? { vars: parsedVars } : {}),
|
|
923
|
+
};
|
|
924
|
+
};
|
|
1050
925
|
/**
|
|
1051
|
-
*
|
|
926
|
+
* Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
|
|
927
|
+
*
|
|
928
|
+
* 1. Base defaults derived from the CLI generator defaults
|
|
929
|
+
* ({@link baseGetDotenvCliOptions}).
|
|
930
|
+
* 2. Local project overrides from a `getdotenv.config.json` in the nearest
|
|
931
|
+
* package root (if present).
|
|
932
|
+
* 3. The provided customOptions.
|
|
933
|
+
*
|
|
934
|
+
* The result preserves explicit empty values and drops only `undefined`.
|
|
1052
935
|
*/
|
|
1053
|
-
const
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
const
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
936
|
+
const resolveGetDotenvOptions = (customOptions) => {
|
|
937
|
+
// Programmatic callers use neutral defaults only. Do not read local packaged
|
|
938
|
+
// getdotenv.config.json here; the host path applies packaged/project configs
|
|
939
|
+
// via the dedicated loader/overlay pipeline.
|
|
940
|
+
const mergedDefaults = baseRootOptionDefaults;
|
|
941
|
+
const defaultsFromCli = getDotenvCliOptions2Options(mergedDefaults);
|
|
942
|
+
const result = defaultsDeep(defaultsFromCli, customOptions);
|
|
943
|
+
return Promise.resolve({
|
|
944
|
+
...result, // Keep explicit empty strings/zeros; drop only undefined
|
|
945
|
+
vars: omitUndefinedRecord(result.vars ?? {}),
|
|
946
|
+
});
|
|
1062
947
|
};
|
|
1063
948
|
|
|
1064
949
|
/**
|
|
@@ -1076,117 +961,6 @@ const readDotenv = async (path) => {
|
|
|
1076
961
|
}
|
|
1077
962
|
};
|
|
1078
963
|
|
|
1079
|
-
const importDefault = async (fileUrl) => {
|
|
1080
|
-
const mod = (await import(fileUrl));
|
|
1081
|
-
return mod.default;
|
|
1082
|
-
};
|
|
1083
|
-
const cacheHash = (absPath, mtimeMs) => createHash('sha1')
|
|
1084
|
-
.update(absPath)
|
|
1085
|
-
.update(String(mtimeMs))
|
|
1086
|
-
.digest('hex')
|
|
1087
|
-
.slice(0, 12);
|
|
1088
|
-
/**
|
|
1089
|
-
* Remove older compiled cache files for a given source base name, keeping
|
|
1090
|
-
* at most `keep` most-recent files. Errors are ignored by design.
|
|
1091
|
-
*/
|
|
1092
|
-
const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
|
|
1093
|
-
try {
|
|
1094
|
-
const entries = await fs.readdir(cacheDir);
|
|
1095
|
-
const mine = entries
|
|
1096
|
-
.filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
|
|
1097
|
-
.map((f) => path.join(cacheDir, f));
|
|
1098
|
-
if (mine.length <= keep)
|
|
1099
|
-
return;
|
|
1100
|
-
const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
|
|
1101
|
-
stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
1102
|
-
const toDelete = stats.slice(keep).map((s) => s.p);
|
|
1103
|
-
await Promise.all(toDelete.map(async (p) => {
|
|
1104
|
-
try {
|
|
1105
|
-
await fs.remove(p);
|
|
1106
|
-
}
|
|
1107
|
-
catch {
|
|
1108
|
-
// best-effort cleanup
|
|
1109
|
-
}
|
|
1110
|
-
}));
|
|
1111
|
-
}
|
|
1112
|
-
catch {
|
|
1113
|
-
// best-effort cleanup
|
|
1114
|
-
}
|
|
1115
|
-
};
|
|
1116
|
-
/**
|
|
1117
|
-
* Load a module default export from a JS/TS file with robust fallbacks:
|
|
1118
|
-
* - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
|
|
1119
|
-
* 1) try direct import (if a TS loader is active),
|
|
1120
|
-
* 2) esbuild bundle to a temp ESM file,
|
|
1121
|
-
* 3) typescript.transpileModule fallback for simple modules.
|
|
1122
|
-
*
|
|
1123
|
-
* @param absPath - absolute path to source file
|
|
1124
|
-
* @param cacheDirName - cache subfolder under .tsbuild
|
|
1125
|
-
*/
|
|
1126
|
-
const loadModuleDefault = async (absPath, cacheDirName) => {
|
|
1127
|
-
const ext = path.extname(absPath).toLowerCase();
|
|
1128
|
-
const fileUrl = url.pathToFileURL(absPath).toString();
|
|
1129
|
-
if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
|
|
1130
|
-
return importDefault(fileUrl);
|
|
1131
|
-
}
|
|
1132
|
-
// Try direct import first (TS loader active)
|
|
1133
|
-
try {
|
|
1134
|
-
const dyn = await importDefault(fileUrl);
|
|
1135
|
-
if (dyn)
|
|
1136
|
-
return dyn;
|
|
1137
|
-
}
|
|
1138
|
-
catch {
|
|
1139
|
-
/* fall through */
|
|
1140
|
-
}
|
|
1141
|
-
const stat = await fs.stat(absPath);
|
|
1142
|
-
const hash = cacheHash(absPath, stat.mtimeMs);
|
|
1143
|
-
const cacheDir = path.resolve('.tsbuild', cacheDirName);
|
|
1144
|
-
await fs.ensureDir(cacheDir);
|
|
1145
|
-
const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
|
|
1146
|
-
// Try esbuild
|
|
1147
|
-
try {
|
|
1148
|
-
const esbuild = (await import('esbuild'));
|
|
1149
|
-
await esbuild.build({
|
|
1150
|
-
entryPoints: [absPath],
|
|
1151
|
-
bundle: true,
|
|
1152
|
-
platform: 'node',
|
|
1153
|
-
format: 'esm',
|
|
1154
|
-
target: 'node20',
|
|
1155
|
-
outfile: cacheFile,
|
|
1156
|
-
sourcemap: false,
|
|
1157
|
-
logLevel: 'silent',
|
|
1158
|
-
});
|
|
1159
|
-
const result = await importDefault(url.pathToFileURL(cacheFile).toString());
|
|
1160
|
-
// Best-effort: trim older cache files for this source.
|
|
1161
|
-
await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
|
|
1162
|
-
return result;
|
|
1163
|
-
}
|
|
1164
|
-
catch {
|
|
1165
|
-
/* fall through to TS transpile */
|
|
1166
|
-
}
|
|
1167
|
-
// TypeScript transpile fallback
|
|
1168
|
-
try {
|
|
1169
|
-
const ts = (await import('typescript'));
|
|
1170
|
-
const code = await fs.readFile(absPath, 'utf-8');
|
|
1171
|
-
const out = ts.transpileModule(code, {
|
|
1172
|
-
compilerOptions: {
|
|
1173
|
-
module: 'ESNext',
|
|
1174
|
-
target: 'ES2022',
|
|
1175
|
-
moduleResolution: 'NodeNext',
|
|
1176
|
-
},
|
|
1177
|
-
}).outputText;
|
|
1178
|
-
await fs.writeFile(cacheFile, out, 'utf-8');
|
|
1179
|
-
const result = await importDefault(url.pathToFileURL(cacheFile).toString());
|
|
1180
|
-
// Best-effort: trim older cache files for this source.
|
|
1181
|
-
await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
|
|
1182
|
-
return result;
|
|
1183
|
-
}
|
|
1184
|
-
catch {
|
|
1185
|
-
// Caller decides final error wording; rethrow for upstream mapping.
|
|
1186
|
-
throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
|
|
1187
|
-
}
|
|
1188
|
-
};
|
|
1189
|
-
|
|
1190
964
|
async function getDotenv(options = {}) {
|
|
1191
965
|
// Apply defaults.
|
|
1192
966
|
const { defaultEnv, dotenvToken = '.env', dynamicPath, env, excludeDynamic = false, excludeEnv = false, excludeGlobal = false, excludePrivate = false, excludePublic = false, loadProcess = false, log = false, logger = console, outputPath, paths = [], privateToken = 'local', vars = {}, } = await resolveGetDotenvOptions(options);
|
|
@@ -1235,25 +1009,11 @@ async function getDotenv(options = {}) {
|
|
|
1235
1009
|
}
|
|
1236
1010
|
else if (dynamicPath) {
|
|
1237
1011
|
const absDynamicPath = path.resolve(dynamicPath);
|
|
1238
|
-
|
|
1239
|
-
try {
|
|
1240
|
-
dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
|
|
1241
|
-
}
|
|
1242
|
-
catch {
|
|
1243
|
-
// Preserve legacy error text for compatibility with tests/docs.
|
|
1244
|
-
throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
|
|
1245
|
-
`Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
|
|
1246
|
-
}
|
|
1247
|
-
}
|
|
1012
|
+
await loadAndApplyDynamic(dotenv, absDynamicPath, env ?? defaultEnv, 'getdotenv-dynamic');
|
|
1248
1013
|
}
|
|
1249
1014
|
if (dynamic) {
|
|
1250
1015
|
try {
|
|
1251
|
-
|
|
1252
|
-
Object.assign(dotenv, {
|
|
1253
|
-
[key]: typeof dynamic[key] === 'function'
|
|
1254
|
-
? dynamic[key](dotenv, env ?? defaultEnv)
|
|
1255
|
-
: dynamic[key],
|
|
1256
|
-
});
|
|
1016
|
+
applyDynamicMap(dotenv, dynamic, env ?? defaultEnv);
|
|
1257
1017
|
}
|
|
1258
1018
|
catch {
|
|
1259
1019
|
throw new Error(`Unable to evaluate dynamic variables.`);
|
|
@@ -1267,10 +1027,7 @@ async function getDotenv(options = {}) {
|
|
|
1267
1027
|
if (!outputPathResolved)
|
|
1268
1028
|
throw new Error('Output path not found.');
|
|
1269
1029
|
const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
|
|
1270
|
-
await
|
|
1271
|
-
const value = dotenvForOutput[key] ?? '';
|
|
1272
|
-
return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
|
|
1273
|
-
}, ''), { encoding: 'utf-8' });
|
|
1030
|
+
await writeDotenvFile(outputPathResolved, dotenvForOutput);
|
|
1274
1031
|
resultDotenv = dotenvForOutput;
|
|
1275
1032
|
}
|
|
1276
1033
|
// Log result.
|
|
@@ -1315,60 +1072,26 @@ async function getDotenv(options = {}) {
|
|
|
1315
1072
|
}
|
|
1316
1073
|
|
|
1317
1074
|
/**
|
|
1318
|
-
*
|
|
1319
|
-
*
|
|
1320
|
-
* - Preserves non-strings as-is.
|
|
1321
|
-
* - Does not recurse into arrays (arrays are returned unchanged).
|
|
1075
|
+
* Compute the realized path for a command mount (leaf-up to root).
|
|
1076
|
+
* Excludes the root application alias.
|
|
1322
1077
|
*
|
|
1323
|
-
*
|
|
1324
|
-
* - Phase C option/config interpolation after composing ctx.dotenv.
|
|
1325
|
-
* - Per-plugin config slice interpolation before afterResolve.
|
|
1078
|
+
* @param cli - The mounted command instance.
|
|
1326
1079
|
*/
|
|
1327
|
-
/** @internal */
|
|
1328
|
-
const isPlainObject = (v) => v !== null &&
|
|
1329
|
-
typeof v === 'object' &&
|
|
1330
|
-
!Array.isArray(v) &&
|
|
1331
|
-
Object.getPrototypeOf(v) === Object.prototype;
|
|
1332
1080
|
/**
|
|
1333
|
-
*
|
|
1334
|
-
*
|
|
1335
|
-
*
|
|
1336
|
-
* @typeParam T - Shape of the input value.
|
|
1337
|
-
* @param value - Input value (object/array/primitive).
|
|
1338
|
-
* @param envRef - Reference environment for interpolation.
|
|
1339
|
-
* @returns A new value with string leaves interpolated.
|
|
1081
|
+
* Flatten a plugin tree into a list of `{ plugin, path }` entries.
|
|
1082
|
+
* Traverses the namespace chain in pre-order.
|
|
1340
1083
|
*/
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
const
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
// Arrays: return as-is (no recursion)
|
|
1349
|
-
if (Array.isArray(value)) {
|
|
1350
|
-
return value;
|
|
1351
|
-
}
|
|
1352
|
-
// Plain objects: shallow clone and recurse into values
|
|
1353
|
-
if (isPlainObject(value)) {
|
|
1354
|
-
const src = value;
|
|
1355
|
-
const out = {};
|
|
1356
|
-
for (const [k, v] of Object.entries(src)) {
|
|
1357
|
-
// Recurse for strings/objects; keep arrays as-is; preserve other scalars
|
|
1358
|
-
if (typeof v === 'string')
|
|
1359
|
-
out[k] = dotenvExpand(v, envRef) ?? v;
|
|
1360
|
-
else if (Array.isArray(v))
|
|
1361
|
-
out[k] = v;
|
|
1362
|
-
else if (isPlainObject(v))
|
|
1363
|
-
out[k] = interpolateDeep(v, envRef);
|
|
1364
|
-
else
|
|
1365
|
-
out[k] = v;
|
|
1084
|
+
function flattenPluginTreeByPath(plugins, prefix) {
|
|
1085
|
+
const out = [];
|
|
1086
|
+
for (const p of plugins) {
|
|
1087
|
+
const here = prefix && prefix.length > 0 ? `${prefix}/${p.ns}` : p.ns;
|
|
1088
|
+
out.push({ plugin: p, path: here });
|
|
1089
|
+
if (Array.isArray(p.children) && p.children.length > 0) {
|
|
1090
|
+
out.push(...flattenPluginTreeByPath(p.children.map((c) => c.plugin), here));
|
|
1366
1091
|
}
|
|
1367
|
-
return out;
|
|
1368
1092
|
}
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
};
|
|
1093
|
+
return out;
|
|
1094
|
+
}
|
|
1372
1095
|
|
|
1373
1096
|
/**
|
|
1374
1097
|
* Instance-bound plugin config store.
|
|
@@ -1378,15 +1101,26 @@ const interpolateDeep = (value, envRef) => {
|
|
|
1378
1101
|
* plugin instance.
|
|
1379
1102
|
*/
|
|
1380
1103
|
const PLUGIN_CONFIG_STORE = new WeakMap();
|
|
1381
|
-
|
|
1104
|
+
/**
|
|
1105
|
+
* Store a validated, interpolated config slice for a specific plugin instance.
|
|
1106
|
+
* Generic on both the host options type and the plugin config type to avoid
|
|
1107
|
+
* defaulting to GetDotenvOptions under exactOptionalPropertyTypes.
|
|
1108
|
+
*/
|
|
1109
|
+
const setPluginConfig = (plugin, cfg) => {
|
|
1382
1110
|
PLUGIN_CONFIG_STORE.set(plugin, cfg);
|
|
1383
1111
|
};
|
|
1384
|
-
|
|
1112
|
+
/**
|
|
1113
|
+
* Retrieve the validated/interpolated config slice for a plugin instance.
|
|
1114
|
+
*/
|
|
1115
|
+
const getPluginConfig = (plugin) => {
|
|
1116
|
+
return PLUGIN_CONFIG_STORE.get(plugin);
|
|
1117
|
+
};
|
|
1385
1118
|
/**
|
|
1386
1119
|
* Compute the dotenv context for the host (uses the config loader/overlay path).
|
|
1387
1120
|
* - Resolves and validates options strictly (host-only).
|
|
1388
1121
|
* - Applies file cascade, overlays, dynamics, and optional effects.
|
|
1389
|
-
* - Merges and validates per-plugin config slices (when provided)
|
|
1122
|
+
* - Merges and validates per-plugin config slices (when provided), keyed by
|
|
1123
|
+
* realized mount path (ns chain).
|
|
1390
1124
|
*
|
|
1391
1125
|
* @param customOptions - Partial options from the current invocation.
|
|
1392
1126
|
* @param plugins - Installed plugins (for config validation).
|
|
@@ -1397,21 +1131,16 @@ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
|
|
|
1397
1131
|
// Zod boundary: parse returns the schema-derived shape; we adopt our public
|
|
1398
1132
|
// GetDotenvOptions overlay (logger/dynamic typing) for internal processing.
|
|
1399
1133
|
const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
|
|
1400
|
-
//
|
|
1401
|
-
// 1) Base from files only (no dynamic, no programmatic vars)
|
|
1402
|
-
// Sanitize to avoid passing properties explicitly set to undefined.
|
|
1134
|
+
// Build a pure base without side effects or logging (no dynamics, no programmatic vars).
|
|
1403
1135
|
const cleanedValidated = omitUndefined(validated);
|
|
1404
1136
|
const base = await getDotenv({
|
|
1405
1137
|
...cleanedValidated,
|
|
1406
|
-
// Build a pure base without side effects or logging.
|
|
1407
1138
|
excludeDynamic: true,
|
|
1408
1139
|
vars: {},
|
|
1409
1140
|
log: false,
|
|
1410
1141
|
loadProcess: false,
|
|
1411
|
-
// Intentionally omit outputPath for the base pass; including a key with
|
|
1412
|
-
// undefined would violate exactOptionalPropertyTypes on the Partial target.
|
|
1413
1142
|
});
|
|
1414
|
-
//
|
|
1143
|
+
// Discover config sources and overlay with progressive expansion per slice.
|
|
1415
1144
|
const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
|
|
1416
1145
|
const dotenvOverlaid = overlayEnv({
|
|
1417
1146
|
base,
|
|
@@ -1419,47 +1148,31 @@ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
|
|
|
1419
1148
|
configs: sources,
|
|
1420
1149
|
...(validated.vars ? { programmaticVars: validated.vars } : {}),
|
|
1421
1150
|
});
|
|
1422
|
-
// Helper to apply a dynamic map progressively.
|
|
1423
|
-
const applyDynamic = (target, dynamic, env) => {
|
|
1424
|
-
if (!dynamic)
|
|
1425
|
-
return;
|
|
1426
|
-
for (const key of Object.keys(dynamic)) {
|
|
1427
|
-
const value = typeof dynamic[key] === 'function'
|
|
1428
|
-
? dynamic[key](target, env)
|
|
1429
|
-
: dynamic[key];
|
|
1430
|
-
Object.assign(target, { [key]: value });
|
|
1431
|
-
}
|
|
1432
|
-
};
|
|
1433
|
-
// 3) Apply dynamics in order
|
|
1434
1151
|
const dotenv = { ...dotenvOverlaid };
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1152
|
+
// Programmatic dynamic variables (when provided)
|
|
1153
|
+
applyDynamicMap(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
|
|
1154
|
+
// Packaged/project dynamics
|
|
1155
|
+
const packagedDyn = (sources.packaged?.dynamic ?? undefined);
|
|
1156
|
+
const publicDyn = (sources.project?.public?.dynamic ?? undefined);
|
|
1157
|
+
const localDyn = (sources.project?.local?.dynamic ?? undefined);
|
|
1158
|
+
applyDynamicMap(dotenv, packagedDyn, validated.env ?? validated.defaultEnv);
|
|
1159
|
+
applyDynamicMap(dotenv, publicDyn, validated.env ?? validated.defaultEnv);
|
|
1160
|
+
applyDynamicMap(dotenv, localDyn, validated.env ?? validated.defaultEnv);
|
|
1439
1161
|
// file dynamicPath (lowest)
|
|
1440
1162
|
if (validated.dynamicPath) {
|
|
1441
1163
|
const absDynamicPath = path.resolve(validated.dynamicPath);
|
|
1442
|
-
|
|
1443
|
-
const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
|
|
1444
|
-
applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
|
|
1445
|
-
}
|
|
1446
|
-
catch {
|
|
1447
|
-
throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
|
|
1448
|
-
}
|
|
1164
|
+
await loadAndApplyDynamic(dotenv, absDynamicPath, validated.env ?? validated.defaultEnv, 'getdotenv-dynamic-host');
|
|
1449
1165
|
}
|
|
1450
|
-
//
|
|
1166
|
+
// Effects:
|
|
1451
1167
|
if (validated.outputPath) {
|
|
1452
|
-
await
|
|
1453
|
-
const value = dotenv[key] ?? '';
|
|
1454
|
-
return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
|
|
1455
|
-
}, ''), { encoding: 'utf-8' });
|
|
1168
|
+
await writeDotenvFile(validated.outputPath, dotenv);
|
|
1456
1169
|
}
|
|
1457
|
-
const logger =
|
|
1170
|
+
const logger = validated.logger;
|
|
1458
1171
|
if (validated.log)
|
|
1459
1172
|
logger.log(dotenv);
|
|
1460
1173
|
if (validated.loadProcess)
|
|
1461
1174
|
Object.assign(process.env, dotenv);
|
|
1462
|
-
//
|
|
1175
|
+
// Merge and validate per-plugin config keyed by realized path (ns chain).
|
|
1463
1176
|
const packagedPlugins = (sources.packaged &&
|
|
1464
1177
|
sources.packaged.plugins) ??
|
|
1465
1178
|
{};
|
|
@@ -1469,95 +1182,563 @@ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
|
|
|
1469
1182
|
const localPlugins = (sources.project?.local &&
|
|
1470
1183
|
sources.project.local.plugins) ??
|
|
1471
1184
|
{};
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
const
|
|
1480
|
-
|
|
1481
|
-
const
|
|
1482
|
-
|
|
1483
|
-
...process.env,
|
|
1484
|
-
};
|
|
1485
|
-
const interpolated = slice && typeof slice === 'object'
|
|
1486
|
-
? interpolateDeep(slice, envRef)
|
|
1185
|
+
const entries = flattenPluginTreeByPath(plugins);
|
|
1186
|
+
const mergedPluginConfigsByPath = {};
|
|
1187
|
+
const envRef = {
|
|
1188
|
+
...dotenv,
|
|
1189
|
+
...process.env,
|
|
1190
|
+
};
|
|
1191
|
+
for (const e of entries) {
|
|
1192
|
+
const pathKey = e.path;
|
|
1193
|
+
const mergedRaw = defaultsDeep({}, packagedPlugins[pathKey] ?? {}, publicPlugins[pathKey] ?? {}, localPlugins[pathKey] ?? {});
|
|
1194
|
+
const interpolated = mergedRaw && typeof mergedRaw === 'object'
|
|
1195
|
+
? interpolateDeep(mergedRaw, envRef)
|
|
1487
1196
|
: {};
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1197
|
+
const schema = e.plugin.configSchema;
|
|
1198
|
+
if (schema) {
|
|
1199
|
+
const parsed = schema.safeParse(interpolated);
|
|
1200
|
+
if (!parsed.success) {
|
|
1201
|
+
const err = parsed.error;
|
|
1202
|
+
const msgs = err.issues
|
|
1203
|
+
.map((i) => {
|
|
1204
|
+
const pth = Array.isArray(i.path) ? i.path.join('.') : '';
|
|
1205
|
+
const msg = typeof i.message === 'string' ? i.message : 'Invalid value';
|
|
1206
|
+
return pth ? `${pth}: ${msg}` : msg;
|
|
1207
|
+
})
|
|
1208
|
+
.join('\n');
|
|
1209
|
+
throw new Error(`Invalid config for plugin at '${pathKey}':\n${msgs}`);
|
|
1210
|
+
}
|
|
1211
|
+
const frozen = Object.freeze(parsed.data);
|
|
1212
|
+
setPluginConfig(e.plugin, frozen);
|
|
1213
|
+
mergedPluginConfigsByPath[pathKey] = frozen;
|
|
1214
|
+
}
|
|
1215
|
+
else {
|
|
1216
|
+
const frozen = Object.freeze(interpolated);
|
|
1217
|
+
setPluginConfig(e.plugin, frozen);
|
|
1218
|
+
mergedPluginConfigsByPath[pathKey] = frozen;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
return {
|
|
1222
|
+
optionsResolved: validated,
|
|
1223
|
+
dotenv,
|
|
1224
|
+
plugins: {},
|
|
1225
|
+
pluginConfigs: mergedPluginConfigsByPath,
|
|
1226
|
+
};
|
|
1227
|
+
};
|
|
1228
|
+
|
|
1229
|
+
// Implementation
|
|
1230
|
+
function definePlugin(spec) {
|
|
1231
|
+
const { ...rest } = spec;
|
|
1232
|
+
const effectiveSchema = spec.configSchema ?? z.object({}).strict();
|
|
1233
|
+
const base = {
|
|
1234
|
+
...rest,
|
|
1235
|
+
configSchema: effectiveSchema,
|
|
1236
|
+
children: [],
|
|
1237
|
+
use(child, override) {
|
|
1238
|
+
// Enforce sibling uniqueness at composition time.
|
|
1239
|
+
const desired = (override && typeof override.ns === 'string' && override.ns.length > 0
|
|
1240
|
+
? override.ns
|
|
1241
|
+
: child.ns).trim();
|
|
1242
|
+
const collision = this.children.some((c) => {
|
|
1243
|
+
const ns = (c.override &&
|
|
1244
|
+
typeof c.override.ns === 'string' &&
|
|
1245
|
+
c.override.ns.length > 0
|
|
1246
|
+
? c.override.ns
|
|
1247
|
+
: c.plugin.ns).trim();
|
|
1248
|
+
return ns === desired;
|
|
1249
|
+
});
|
|
1250
|
+
if (collision) {
|
|
1251
|
+
const under = this.ns && this.ns.length > 0 ? this.ns : 'root';
|
|
1252
|
+
throw new Error(`Duplicate namespace '${desired}' under '${under}'. ` +
|
|
1253
|
+
`Override via .use(plugin, { ns: '...' }).`);
|
|
1254
|
+
}
|
|
1255
|
+
this.children.push({ plugin: child, override });
|
|
1256
|
+
return this;
|
|
1257
|
+
},
|
|
1258
|
+
};
|
|
1259
|
+
const extended = base;
|
|
1260
|
+
extended.readConfig = function (_cli) {
|
|
1261
|
+
const value = getPluginConfig(extended);
|
|
1262
|
+
if (value === undefined) {
|
|
1263
|
+
throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
|
|
1503
1264
|
}
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1265
|
+
return value;
|
|
1266
|
+
};
|
|
1267
|
+
extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
|
|
1268
|
+
// Derive realized path strictly from the provided mount (leaf-up).
|
|
1269
|
+
const realizedPath = (() => {
|
|
1270
|
+
const parts = [];
|
|
1271
|
+
let node = cli;
|
|
1272
|
+
while (node.parent) {
|
|
1273
|
+
parts.push(node.name());
|
|
1274
|
+
node = node.parent;
|
|
1275
|
+
}
|
|
1276
|
+
return parts.reverse().join('/');
|
|
1277
|
+
})();
|
|
1278
|
+
return cli.createDynamicOption(flags, (c) => {
|
|
1279
|
+
const fromStore = getPluginConfig(extended);
|
|
1280
|
+
let cfgVal = fromStore ?? {};
|
|
1281
|
+
// Strict fallback only by realized path for help-time synthetic usage.
|
|
1282
|
+
if (!fromStore && realizedPath.length > 0) {
|
|
1283
|
+
const bag = c.plugins;
|
|
1284
|
+
const maybe = bag[realizedPath];
|
|
1285
|
+
if (maybe && typeof maybe === 'object') {
|
|
1286
|
+
cfgVal = maybe;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
// c is strictly typed as ResolvedHelpConfig from cli.createDynamicOption
|
|
1290
|
+
return desc(c, cfgVal);
|
|
1291
|
+
}, parser, defaultValue);
|
|
1292
|
+
};
|
|
1293
|
+
return extended;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
const dbg = (...args) => {
|
|
1297
|
+
if (process.env.GETDOTENV_DEBUG) {
|
|
1298
|
+
// Use stderr to avoid interfering with stdout assertions
|
|
1299
|
+
console.error('[getdotenv:run]', ...args);
|
|
1300
|
+
}
|
|
1301
|
+
};
|
|
1302
|
+
// Strip repeated symmetric outer quotes (single or double) until stable.
|
|
1303
|
+
// This is safe for argv arrays passed to execa (no quoting needed) and avoids
|
|
1304
|
+
// passing quote characters through to Node (e.g., for `node -e "<code>"`).
|
|
1305
|
+
// Handles stacked quotes from shells like PowerShell: """code""" -> code.
|
|
1306
|
+
const stripOuterQuotes = (s) => {
|
|
1307
|
+
let out = s;
|
|
1308
|
+
// Repeatedly trim only when the entire string is wrapped in matching quotes.
|
|
1309
|
+
// Stop as soon as the ends are asymmetric or no quotes remain.
|
|
1310
|
+
while (out.length >= 2) {
|
|
1311
|
+
const a = out.charAt(0);
|
|
1312
|
+
const b = out.charAt(out.length - 1);
|
|
1313
|
+
const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
|
|
1314
|
+
if (!symmetric)
|
|
1315
|
+
break;
|
|
1316
|
+
out = out.slice(1, -1);
|
|
1508
1317
|
}
|
|
1318
|
+
return out;
|
|
1319
|
+
};
|
|
1320
|
+
// Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
|
|
1321
|
+
const pickResult = (r) => {
|
|
1322
|
+
const exit = r.exitCode;
|
|
1323
|
+
const stdoutVal = r.stdout;
|
|
1324
|
+
const stderrVal = r.stderr;
|
|
1509
1325
|
return {
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
// Retained for legacy root help dynamic evaluation only. Instance-bound
|
|
1514
|
-
// access is used by plugins themselves and tests/docs moving forward.
|
|
1515
|
-
pluginConfigs: mergedPluginConfigsById,
|
|
1326
|
+
exitCode: typeof exit === 'number' ? exit : Number.NaN,
|
|
1327
|
+
stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
|
|
1328
|
+
stderr: typeof stderrVal === 'string' ? stderrVal : '',
|
|
1516
1329
|
};
|
|
1517
1330
|
};
|
|
1518
|
-
|
|
1519
|
-
//
|
|
1520
|
-
const
|
|
1331
|
+
// Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
|
|
1332
|
+
// expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
|
|
1333
|
+
const sanitizeEnv = (env) => {
|
|
1334
|
+
if (!env)
|
|
1335
|
+
return undefined;
|
|
1336
|
+
const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
|
|
1337
|
+
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
|
|
1338
|
+
};
|
|
1521
1339
|
/**
|
|
1522
|
-
*
|
|
1340
|
+
* Core executor that normalizes shell/plain forms and capture/inherit modes.
|
|
1341
|
+
* Returns captured buffers; callers may stream stdout when desired.
|
|
1523
1342
|
*/
|
|
1524
|
-
function
|
|
1525
|
-
const
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1343
|
+
async function _execNormalized(command, shell, opts = {}) {
|
|
1344
|
+
const envSan = sanitizeEnv(opts.env);
|
|
1345
|
+
const timeoutBits = typeof opts.timeoutMs === 'number'
|
|
1346
|
+
? { timeout: opts.timeoutMs, killSignal: 'SIGKILL' }
|
|
1347
|
+
: {};
|
|
1348
|
+
const stdio = opts.stdio ?? 'pipe';
|
|
1349
|
+
if (shell === false) {
|
|
1350
|
+
let file;
|
|
1351
|
+
let args = [];
|
|
1352
|
+
if (typeof command === 'string') {
|
|
1353
|
+
const tokens = tokenize(command);
|
|
1354
|
+
file = tokens[0];
|
|
1355
|
+
args = tokens.slice(1);
|
|
1356
|
+
}
|
|
1357
|
+
else {
|
|
1358
|
+
file = command[0];
|
|
1359
|
+
args = command.slice(1).map(stripOuterQuotes);
|
|
1360
|
+
}
|
|
1361
|
+
if (!file)
|
|
1362
|
+
return { exitCode: 0, stdout: '', stderr: '' };
|
|
1363
|
+
dbg('exec (plain)', { file, args, stdio });
|
|
1364
|
+
try {
|
|
1365
|
+
const ok = pickResult((await execa(file, args, {
|
|
1366
|
+
...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
|
|
1367
|
+
...(envSan !== undefined ? { env: envSan } : {}),
|
|
1368
|
+
stdio,
|
|
1369
|
+
...timeoutBits,
|
|
1370
|
+
})));
|
|
1371
|
+
dbg('exit (plain)', { exitCode: ok.exitCode });
|
|
1372
|
+
return ok;
|
|
1373
|
+
}
|
|
1374
|
+
catch (e) {
|
|
1375
|
+
const out = pickResult(e);
|
|
1376
|
+
dbg('exit:error (plain)', { exitCode: out.exitCode });
|
|
1377
|
+
return out;
|
|
1378
|
+
}
|
|
1529
1379
|
}
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1380
|
+
// Shell path (string|true|URL): execaCommand handles shell resolution.
|
|
1381
|
+
const commandStr = typeof command === 'string' ? command : command.join(' ');
|
|
1382
|
+
dbg('exec (shell)', {
|
|
1383
|
+
command: commandStr,
|
|
1384
|
+
shell: typeof shell === 'string' ? shell : 'custom',
|
|
1385
|
+
stdio,
|
|
1386
|
+
});
|
|
1387
|
+
try {
|
|
1388
|
+
const ok = pickResult((await execaCommand(commandStr, {
|
|
1389
|
+
shell,
|
|
1390
|
+
...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
|
|
1391
|
+
...(envSan !== undefined ? { env: envSan } : {}),
|
|
1392
|
+
stdio,
|
|
1393
|
+
...timeoutBits,
|
|
1394
|
+
})));
|
|
1395
|
+
dbg('exit (shell)', { exitCode: ok.exitCode });
|
|
1396
|
+
return ok;
|
|
1397
|
+
}
|
|
1398
|
+
catch (e) {
|
|
1399
|
+
const out = pickResult(e);
|
|
1400
|
+
dbg('exit:error (shell)', { exitCode: out.exitCode });
|
|
1401
|
+
return out;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
async function runCommandResult(command, shell, opts = {}) {
|
|
1405
|
+
// Build opts without injecting undefined (exactOptionalPropertyTypes-safe)
|
|
1406
|
+
const coreOpts = { stdio: 'pipe' };
|
|
1407
|
+
if (opts.cwd !== undefined) {
|
|
1408
|
+
coreOpts.cwd = opts.cwd;
|
|
1409
|
+
}
|
|
1410
|
+
if (opts.env !== undefined) {
|
|
1411
|
+
coreOpts.env = opts.env;
|
|
1412
|
+
}
|
|
1413
|
+
if (opts.timeoutMs !== undefined) {
|
|
1414
|
+
coreOpts.timeoutMs = opts.timeoutMs;
|
|
1415
|
+
}
|
|
1416
|
+
return _execNormalized(command, shell, coreOpts);
|
|
1533
1417
|
}
|
|
1418
|
+
async function runCommand(command, shell, opts) {
|
|
1419
|
+
// Build opts without injecting undefined (exactOptionalPropertyTypes-safe)
|
|
1420
|
+
const callOpts = {};
|
|
1421
|
+
if (opts.cwd !== undefined) {
|
|
1422
|
+
callOpts.cwd = opts.cwd;
|
|
1423
|
+
}
|
|
1424
|
+
if (opts.env !== undefined) {
|
|
1425
|
+
callOpts.env = opts.env;
|
|
1426
|
+
}
|
|
1427
|
+
if (opts.stdio !== undefined)
|
|
1428
|
+
callOpts.stdio = opts.stdio;
|
|
1429
|
+
const ok = await _execNormalized(command, shell, callOpts);
|
|
1430
|
+
if (opts.stdio === 'pipe' && ok.stdout) {
|
|
1431
|
+
process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
|
|
1432
|
+
}
|
|
1433
|
+
return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1534
1436
|
/**
|
|
1535
|
-
*
|
|
1437
|
+
* Attach root flags to a {@link GetDotenvCli} instance.
|
|
1438
|
+
*
|
|
1439
|
+
* Program is typed as {@link GetDotenvCli} and supports {@link GetDotenvCli.createDynamicOption | createDynamicOption}.
|
|
1536
1440
|
*/
|
|
1537
|
-
|
|
1538
|
-
const
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1441
|
+
const attachRootOptions = (program, defaults) => {
|
|
1442
|
+
const GROUP = 'base';
|
|
1443
|
+
const { defaultEnv, dotenvToken, dynamicPath, env, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
|
|
1444
|
+
const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
|
|
1445
|
+
const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
|
|
1446
|
+
// Helper: append (default) tags for ON/OFF toggles
|
|
1447
|
+
const onOff = (on, isDefault) => on
|
|
1448
|
+
? `ON${isDefault ? ' (default)' : ''}`
|
|
1449
|
+
: `OFF${isDefault ? ' (default)' : ''}`;
|
|
1450
|
+
program.enablePositionalOptions().passThroughOptions();
|
|
1451
|
+
// -e, --env <string>
|
|
1452
|
+
{
|
|
1453
|
+
const opt = new Option('-e, --env <string>', 'target environment (dotenv-expanded)');
|
|
1454
|
+
opt.argParser(dotenvExpandFromProcessEnv);
|
|
1455
|
+
if (env !== undefined)
|
|
1456
|
+
opt.default(env);
|
|
1457
|
+
program.addOption(opt);
|
|
1458
|
+
program.setOptionGroup(opt, GROUP);
|
|
1459
|
+
}
|
|
1460
|
+
// -v, --vars <string>
|
|
1461
|
+
{
|
|
1462
|
+
const examples = [
|
|
1463
|
+
['KEY1', 'VAL1'],
|
|
1464
|
+
['KEY2', 'VAL2'],
|
|
1465
|
+
]
|
|
1466
|
+
.map((v) => v.join(va))
|
|
1467
|
+
.join(vd);
|
|
1468
|
+
const opt = new Option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${examples}`);
|
|
1469
|
+
opt.argParser(dotenvExpandFromProcessEnv);
|
|
1470
|
+
program.addOption(opt);
|
|
1471
|
+
program.setOptionGroup(opt, GROUP);
|
|
1472
|
+
}
|
|
1473
|
+
// Output path (interpolated later; help can remain static)
|
|
1474
|
+
{
|
|
1475
|
+
const opt = new Option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)');
|
|
1476
|
+
opt.argParser(dotenvExpandFromProcessEnv);
|
|
1477
|
+
if (outputPath !== undefined)
|
|
1478
|
+
opt.default(outputPath);
|
|
1479
|
+
program.addOption(opt);
|
|
1480
|
+
program.setOptionGroup(opt, GROUP);
|
|
1481
|
+
}
|
|
1482
|
+
// Shell ON (string or boolean true => default shell)
|
|
1483
|
+
{
|
|
1484
|
+
const opt = program
|
|
1485
|
+
.createDynamicOption('-s, --shell [string]', (cfg) => {
|
|
1486
|
+
const s = cfg.shell;
|
|
1487
|
+
let tag = '';
|
|
1488
|
+
if (typeof s === 'boolean' && s)
|
|
1489
|
+
tag = ' (default OS shell)';
|
|
1490
|
+
else if (typeof s === 'string' && s.length > 0)
|
|
1491
|
+
tag = ` (default ${s})`;
|
|
1492
|
+
return `command execution shell, no argument for default OS shell or provide shell string${tag}`;
|
|
1493
|
+
})
|
|
1494
|
+
.conflicts('shellOff');
|
|
1495
|
+
program.addOption(opt);
|
|
1496
|
+
program.setOptionGroup(opt, GROUP);
|
|
1497
|
+
}
|
|
1498
|
+
// Shell OFF
|
|
1499
|
+
{
|
|
1500
|
+
const opt = program
|
|
1501
|
+
.createDynamicOption('-S, --shell-off', (cfg) => {
|
|
1502
|
+
const s = cfg.shell;
|
|
1503
|
+
return `command execution shell OFF${s === false ? ' (default)' : ''}`;
|
|
1504
|
+
})
|
|
1505
|
+
.conflicts('shell');
|
|
1506
|
+
program.addOption(opt);
|
|
1507
|
+
program.setOptionGroup(opt, GROUP);
|
|
1508
|
+
}
|
|
1509
|
+
// Load process ON/OFF (dynamic defaults)
|
|
1510
|
+
{
|
|
1511
|
+
const optOn = program
|
|
1512
|
+
.createDynamicOption('-p, --load-process', (cfg) => `load variables to process.env ${onOff(true, Boolean(cfg.loadProcess))}`)
|
|
1513
|
+
.conflicts('loadProcessOff');
|
|
1514
|
+
program.addOption(optOn);
|
|
1515
|
+
program.setOptionGroup(optOn, GROUP);
|
|
1516
|
+
const optOff = program
|
|
1517
|
+
.createDynamicOption('-P, --load-process-off', (cfg) => `load variables to process.env ${onOff(false, !cfg.loadProcess)}`)
|
|
1518
|
+
.conflicts('loadProcess');
|
|
1519
|
+
program.addOption(optOff);
|
|
1520
|
+
program.setOptionGroup(optOff, GROUP);
|
|
1521
|
+
}
|
|
1522
|
+
// Exclusion master toggle (dynamic)
|
|
1523
|
+
{
|
|
1524
|
+
const optAll = program
|
|
1525
|
+
.createDynamicOption('-a, --exclude-all', (cfg) => {
|
|
1526
|
+
const allOn = !!cfg.excludeDynamic &&
|
|
1527
|
+
((!!cfg.excludeEnv && !!cfg.excludeGlobal) ||
|
|
1528
|
+
(!!cfg.excludePrivate && !!cfg.excludePublic));
|
|
1529
|
+
const suffix = allOn ? ' (default)' : '';
|
|
1530
|
+
return `exclude all dotenv variables from loading ON${suffix}`;
|
|
1531
|
+
})
|
|
1532
|
+
.conflicts('excludeAllOff');
|
|
1533
|
+
program.addOption(optAll);
|
|
1534
|
+
program.setOptionGroup(optAll, GROUP);
|
|
1535
|
+
const optAllOff = new Option('-A, --exclude-all-off', 'exclude all dotenv variables from loading OFF (default)').conflicts('excludeAll');
|
|
1536
|
+
program.addOption(optAllOff);
|
|
1537
|
+
program.setOptionGroup(optAllOff, GROUP);
|
|
1538
|
+
}
|
|
1539
|
+
// Per-family exclusions (dynamic defaults)
|
|
1540
|
+
{
|
|
1541
|
+
const o1 = program
|
|
1542
|
+
.createDynamicOption('-z, --exclude-dynamic', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(true, Boolean(cfg.excludeDynamic))}`)
|
|
1543
|
+
.conflicts('excludeDynamicOff');
|
|
1544
|
+
program.addOption(o1);
|
|
1545
|
+
program.setOptionGroup(o1, GROUP);
|
|
1546
|
+
const o2 = program
|
|
1547
|
+
.createDynamicOption('-Z, --exclude-dynamic-off', (cfg) => `exclude dynamic dotenv variables from loading ${onOff(false, !cfg.excludeDynamic)}`)
|
|
1548
|
+
.conflicts('excludeDynamic');
|
|
1549
|
+
program.addOption(o2);
|
|
1550
|
+
program.setOptionGroup(o2, GROUP);
|
|
1551
|
+
}
|
|
1552
|
+
{
|
|
1553
|
+
const o1 = program
|
|
1554
|
+
.createDynamicOption('-n, --exclude-env', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(true, Boolean(cfg.excludeEnv))}`)
|
|
1555
|
+
.conflicts('excludeEnvOff');
|
|
1556
|
+
program.addOption(o1);
|
|
1557
|
+
program.setOptionGroup(o1, GROUP);
|
|
1558
|
+
const o2 = program
|
|
1559
|
+
.createDynamicOption('-N, --exclude-env-off', (cfg) => `exclude environment-specific dotenv variables from loading ${onOff(false, !cfg.excludeEnv)}`)
|
|
1560
|
+
.conflicts('excludeEnv');
|
|
1561
|
+
program.addOption(o2);
|
|
1562
|
+
program.setOptionGroup(o2, GROUP);
|
|
1563
|
+
}
|
|
1564
|
+
{
|
|
1565
|
+
const o1 = program
|
|
1566
|
+
.createDynamicOption('-g, --exclude-global', (cfg) => `exclude global dotenv variables from loading ${onOff(true, Boolean(cfg.excludeGlobal))}`)
|
|
1567
|
+
.conflicts('excludeGlobalOff');
|
|
1568
|
+
program.addOption(o1);
|
|
1569
|
+
program.setOptionGroup(o1, GROUP);
|
|
1570
|
+
const o2 = program
|
|
1571
|
+
.createDynamicOption('-G, --exclude-global-off', (cfg) => `exclude global dotenv variables from loading ${onOff(false, !cfg.excludeGlobal)}`)
|
|
1572
|
+
.conflicts('excludeGlobal');
|
|
1573
|
+
program.addOption(o2);
|
|
1574
|
+
program.setOptionGroup(o2, GROUP);
|
|
1575
|
+
}
|
|
1576
|
+
{
|
|
1577
|
+
const p1 = program
|
|
1578
|
+
.createDynamicOption('-r, --exclude-private', (cfg) => `exclude private dotenv variables from loading ${onOff(true, Boolean(cfg.excludePrivate))}`)
|
|
1579
|
+
.conflicts('excludePrivateOff');
|
|
1580
|
+
program.addOption(p1);
|
|
1581
|
+
program.setOptionGroup(p1, GROUP);
|
|
1582
|
+
const p2 = program
|
|
1583
|
+
.createDynamicOption('-R, --exclude-private-off', (cfg) => `exclude private dotenv variables from loading ${onOff(false, !cfg.excludePrivate)}`)
|
|
1584
|
+
.conflicts('excludePrivate');
|
|
1585
|
+
program.addOption(p2);
|
|
1586
|
+
program.setOptionGroup(p2, GROUP);
|
|
1587
|
+
const pu1 = program
|
|
1588
|
+
.createDynamicOption('-u, --exclude-public', (cfg) => `exclude public dotenv variables from loading ${onOff(true, Boolean(cfg.excludePublic))}`)
|
|
1589
|
+
.conflicts('excludePublicOff');
|
|
1590
|
+
program.addOption(pu1);
|
|
1591
|
+
program.setOptionGroup(pu1, GROUP);
|
|
1592
|
+
const pu2 = program
|
|
1593
|
+
.createDynamicOption('-U, --exclude-public-off', (cfg) => `exclude public dotenv variables from loading ${onOff(false, !cfg.excludePublic)}`)
|
|
1594
|
+
.conflicts('excludePublic');
|
|
1595
|
+
program.addOption(pu2);
|
|
1596
|
+
program.setOptionGroup(pu2, GROUP);
|
|
1597
|
+
}
|
|
1598
|
+
// Log ON/OFF (dynamic)
|
|
1599
|
+
{
|
|
1600
|
+
const lo = program
|
|
1601
|
+
.createDynamicOption('-l, --log', (cfg) => `console log loaded variables ${onOff(true, Boolean(cfg.log))}`)
|
|
1602
|
+
.conflicts('logOff');
|
|
1603
|
+
program.addOption(lo);
|
|
1604
|
+
program.setOptionGroup(lo, GROUP);
|
|
1605
|
+
const lf = program
|
|
1606
|
+
.createDynamicOption('-L, --log-off', (cfg) => `console log loaded variables ${onOff(false, !cfg.log)}`)
|
|
1607
|
+
.conflicts('log');
|
|
1608
|
+
program.addOption(lf);
|
|
1609
|
+
program.setOptionGroup(lf, GROUP);
|
|
1610
|
+
}
|
|
1611
|
+
// Capture flag (no default display; static)
|
|
1612
|
+
{
|
|
1613
|
+
const opt = new Option('--capture', 'capture child process stdio for commands (tests/CI)');
|
|
1614
|
+
program.addOption(opt);
|
|
1615
|
+
program.setOptionGroup(opt, GROUP);
|
|
1616
|
+
}
|
|
1617
|
+
// Core bootstrap/static flags (kept static in help)
|
|
1618
|
+
{
|
|
1619
|
+
const o1 = new Option('--default-env <string>', 'default target environment');
|
|
1620
|
+
o1.argParser(dotenvExpandFromProcessEnv);
|
|
1621
|
+
if (defaultEnv !== undefined)
|
|
1622
|
+
o1.default(defaultEnv);
|
|
1623
|
+
program.addOption(o1);
|
|
1624
|
+
program.setOptionGroup(o1, GROUP);
|
|
1625
|
+
const o2 = new Option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file');
|
|
1626
|
+
o2.argParser(dotenvExpandFromProcessEnv);
|
|
1627
|
+
if (dotenvToken !== undefined)
|
|
1628
|
+
o2.default(dotenvToken);
|
|
1629
|
+
program.addOption(o2);
|
|
1630
|
+
program.setOptionGroup(o2, GROUP);
|
|
1631
|
+
const o3 = new Option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)');
|
|
1632
|
+
o3.argParser(dotenvExpandFromProcessEnv);
|
|
1633
|
+
if (dynamicPath !== undefined)
|
|
1634
|
+
o3.default(dynamicPath);
|
|
1635
|
+
program.addOption(o3);
|
|
1636
|
+
program.setOptionGroup(o3, GROUP);
|
|
1637
|
+
const o4 = new Option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory');
|
|
1638
|
+
o4.argParser(dotenvExpandFromProcessEnv);
|
|
1639
|
+
if (paths !== undefined)
|
|
1640
|
+
o4.default(paths);
|
|
1641
|
+
program.addOption(o4);
|
|
1642
|
+
program.setOptionGroup(o4, GROUP);
|
|
1643
|
+
const o5 = new Option('--paths-delimiter <string>', 'paths delimiter string');
|
|
1644
|
+
if (pathsDelimiter !== undefined)
|
|
1645
|
+
o5.default(pathsDelimiter);
|
|
1646
|
+
program.addOption(o5);
|
|
1647
|
+
program.setOptionGroup(o5, GROUP);
|
|
1648
|
+
const o6 = new Option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern');
|
|
1649
|
+
if (pathsDelimiterPattern !== undefined)
|
|
1650
|
+
o6.default(pathsDelimiterPattern);
|
|
1651
|
+
program.addOption(o6);
|
|
1652
|
+
program.setOptionGroup(o6, GROUP);
|
|
1653
|
+
const o7 = new Option('--private-token <string>', 'dotenv-expanded token indicating private variables');
|
|
1654
|
+
o7.argParser(dotenvExpandFromProcessEnv);
|
|
1655
|
+
if (privateToken !== undefined)
|
|
1656
|
+
o7.default(privateToken);
|
|
1657
|
+
program.addOption(o7);
|
|
1658
|
+
program.setOptionGroup(o7, GROUP);
|
|
1659
|
+
const o8 = new Option('--vars-delimiter <string>', 'vars delimiter string');
|
|
1660
|
+
if (varsDelimiter !== undefined)
|
|
1661
|
+
o8.default(varsDelimiter);
|
|
1662
|
+
program.addOption(o8);
|
|
1663
|
+
program.setOptionGroup(o8, GROUP);
|
|
1664
|
+
const o9 = new Option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern');
|
|
1665
|
+
if (varsDelimiterPattern !== undefined)
|
|
1666
|
+
o9.default(varsDelimiterPattern);
|
|
1667
|
+
program.addOption(o9);
|
|
1668
|
+
program.setOptionGroup(o9, GROUP);
|
|
1669
|
+
const o10 = new Option('--vars-assignor <string>', 'vars assignment operator string');
|
|
1670
|
+
if (varsAssignor !== undefined)
|
|
1671
|
+
o10.default(varsAssignor);
|
|
1672
|
+
program.addOption(o10);
|
|
1673
|
+
program.setOptionGroup(o10, GROUP);
|
|
1674
|
+
const o11 = new Option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern');
|
|
1675
|
+
if (varsAssignorPattern !== undefined)
|
|
1676
|
+
o11.default(varsAssignorPattern);
|
|
1677
|
+
program.addOption(o11);
|
|
1678
|
+
program.setOptionGroup(o11, GROUP);
|
|
1679
|
+
}
|
|
1680
|
+
// Diagnostics / validation / entropy
|
|
1681
|
+
{
|
|
1682
|
+
const tr = new Option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
|
|
1683
|
+
program.addOption(tr);
|
|
1684
|
+
program.setOptionGroup(tr, GROUP);
|
|
1685
|
+
const st = new Option('--strict', 'fail on env validation errors (schema/requiredKeys)');
|
|
1686
|
+
program.addOption(st);
|
|
1687
|
+
program.setOptionGroup(st, GROUP);
|
|
1688
|
+
}
|
|
1689
|
+
{
|
|
1690
|
+
const w = program
|
|
1691
|
+
.createDynamicOption('--entropy-warn', (cfg) => {
|
|
1692
|
+
const warn = cfg.warnEntropy;
|
|
1693
|
+
// Default is effectively ON when warnEntropy is true or undefined.
|
|
1694
|
+
return `enable entropy warnings${warn === false ? '' : ' (default on)'}`;
|
|
1695
|
+
})
|
|
1696
|
+
.conflicts('entropyWarnOff');
|
|
1697
|
+
program.addOption(w);
|
|
1698
|
+
program.setOptionGroup(w, GROUP);
|
|
1699
|
+
const woff = program
|
|
1700
|
+
.createDynamicOption('--entropy-warn-off', (cfg) => `disable entropy warnings${cfg.warnEntropy === false ? ' (default)' : ''}`)
|
|
1701
|
+
.conflicts('entropyWarn');
|
|
1702
|
+
program.addOption(woff);
|
|
1703
|
+
program.setOptionGroup(woff, GROUP);
|
|
1704
|
+
const th = new Option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)');
|
|
1705
|
+
program.addOption(th);
|
|
1706
|
+
program.setOptionGroup(th, GROUP);
|
|
1707
|
+
const ml = new Option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)');
|
|
1708
|
+
program.addOption(ml);
|
|
1709
|
+
program.setOptionGroup(ml, GROUP);
|
|
1710
|
+
const wl = new Option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern');
|
|
1711
|
+
program.addOption(wl);
|
|
1712
|
+
program.setOptionGroup(wl, GROUP);
|
|
1713
|
+
const rp = new Option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
|
|
1714
|
+
program.addOption(rp);
|
|
1715
|
+
program.setOptionGroup(rp, GROUP);
|
|
1716
|
+
// Redact ON/OFF (dynamic)
|
|
1717
|
+
{
|
|
1718
|
+
const rOn = program
|
|
1719
|
+
.createDynamicOption('--redact', (cfg) => `presentation-time redaction for secret-like keys ON${cfg.redact ? ' (default)' : ''}`)
|
|
1720
|
+
.conflicts('redactOff');
|
|
1721
|
+
program.addOption(rOn);
|
|
1722
|
+
program.setOptionGroup(rOn, GROUP);
|
|
1723
|
+
const rOff = program
|
|
1724
|
+
.createDynamicOption('--redact-off', (cfg) => `presentation-time redaction for secret-like keys OFF${cfg.redact === false ? ' (default)' : ''}`)
|
|
1725
|
+
.conflicts('redact');
|
|
1726
|
+
program.addOption(rOff);
|
|
1727
|
+
program.setOptionGroup(rOff, GROUP);
|
|
1552
1728
|
}
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
visit(root);
|
|
1557
|
-
}
|
|
1729
|
+
}
|
|
1730
|
+
return program;
|
|
1731
|
+
};
|
|
1558
1732
|
|
|
1559
|
-
|
|
1733
|
+
/**
|
|
1734
|
+
* Registry for option grouping.
|
|
1735
|
+
* Root help renders these groups between "Options" and "Commands".
|
|
1736
|
+
*/
|
|
1560
1737
|
const GROUP_TAG = new WeakMap();
|
|
1738
|
+
/**
|
|
1739
|
+
* Render help option groups (App/Plugins) for a given command.
|
|
1740
|
+
* Groups are injected between Options and Commands in the help output.
|
|
1741
|
+
*/
|
|
1561
1742
|
function renderOptionGroups(cmd) {
|
|
1562
1743
|
const all = cmd.options;
|
|
1563
1744
|
const byGroup = new Map();
|
|
@@ -1611,6 +1792,271 @@ function renderOptionGroups(cmd) {
|
|
|
1611
1792
|
return out;
|
|
1612
1793
|
}
|
|
1613
1794
|
|
|
1795
|
+
/**
|
|
1796
|
+
* Compose root/parent help output by inserting grouped sections between
|
|
1797
|
+
* Options and Commands, ensuring a trailing blank line.
|
|
1798
|
+
*/
|
|
1799
|
+
function buildHelpInformation(base, cmd) {
|
|
1800
|
+
const groups = renderOptionGroups(cmd);
|
|
1801
|
+
const block = typeof groups === 'string' ? groups.trim() : '';
|
|
1802
|
+
if (!block) {
|
|
1803
|
+
return base.endsWith('\n\n')
|
|
1804
|
+
? base
|
|
1805
|
+
: base.endsWith('\n')
|
|
1806
|
+
? `${base}\n`
|
|
1807
|
+
: `${base}\n\n`;
|
|
1808
|
+
}
|
|
1809
|
+
const marker = '\nCommands:';
|
|
1810
|
+
const idx = base.indexOf(marker);
|
|
1811
|
+
let out = base;
|
|
1812
|
+
if (idx >= 0) {
|
|
1813
|
+
const toInsert = groups.startsWith('\n') ? groups : `\n${groups}`;
|
|
1814
|
+
out = `${base.slice(0, idx)}${toInsert}${base.slice(idx)}`;
|
|
1815
|
+
}
|
|
1816
|
+
else {
|
|
1817
|
+
const sep = base.endsWith('\n') || groups.startsWith('\n') ? '' : '\n';
|
|
1818
|
+
out = `${base}${sep}${groups}`;
|
|
1819
|
+
}
|
|
1820
|
+
return out.endsWith('\n\n')
|
|
1821
|
+
? out
|
|
1822
|
+
: out.endsWith('\n')
|
|
1823
|
+
? `${out}\n`
|
|
1824
|
+
: `${out}\n\n`;
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/** src/cliHost/GetDotenvCli/dynamicOptions.ts
|
|
1828
|
+
* Helpers for dynamic option descriptions and evaluation.
|
|
1829
|
+
*/
|
|
1830
|
+
/**
|
|
1831
|
+
* Registry for dynamic descriptions keyed by Option (WeakMap for GC safety).
|
|
1832
|
+
*/
|
|
1833
|
+
const DYN_DESC = new WeakMap();
|
|
1834
|
+
/**
|
|
1835
|
+
* Create an Option with a dynamic description callback stored in DYN_DESC.
|
|
1836
|
+
*/
|
|
1837
|
+
function makeDynamicOption(flags, desc, parser, defaultValue) {
|
|
1838
|
+
const opt = new Option(flags, '');
|
|
1839
|
+
DYN_DESC.set(opt, desc);
|
|
1840
|
+
if (parser) {
|
|
1841
|
+
opt.argParser((value, previous) => parser(value, previous));
|
|
1842
|
+
}
|
|
1843
|
+
if (defaultValue !== undefined)
|
|
1844
|
+
opt.default(defaultValue);
|
|
1845
|
+
// Commander.Option is structurally compatible; help-time wiring is stored in DYN_DESC.
|
|
1846
|
+
return opt;
|
|
1847
|
+
}
|
|
1848
|
+
/**
|
|
1849
|
+
* Evaluate dynamic descriptions across a command tree using the resolved config.
|
|
1850
|
+
*/
|
|
1851
|
+
function evaluateDynamicOptions(root, resolved) {
|
|
1852
|
+
const visit = (cmd) => {
|
|
1853
|
+
const arr = cmd.options;
|
|
1854
|
+
for (const o of arr) {
|
|
1855
|
+
const dyn = DYN_DESC.get(o);
|
|
1856
|
+
if (typeof dyn === 'function') {
|
|
1857
|
+
try {
|
|
1858
|
+
const txt = dyn(resolved);
|
|
1859
|
+
// Commander uses Option.description during help rendering.
|
|
1860
|
+
o.description = txt;
|
|
1861
|
+
}
|
|
1862
|
+
catch {
|
|
1863
|
+
/* best-effort; leave as-is */
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
for (const c of cmd.commands)
|
|
1868
|
+
visit(c);
|
|
1869
|
+
};
|
|
1870
|
+
visit(root);
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
function initializeInstance(cli, headerGetter) {
|
|
1874
|
+
// Configure grouped help: show only base options in default "Options";
|
|
1875
|
+
// subcommands show all of their own options.
|
|
1876
|
+
cli.configureHelp({
|
|
1877
|
+
visibleOptions: (cmd) => {
|
|
1878
|
+
const all = cmd.options;
|
|
1879
|
+
const isRoot = cmd.parent === null;
|
|
1880
|
+
const list = isRoot
|
|
1881
|
+
? all.filter((opt) => {
|
|
1882
|
+
const group = GROUP_TAG.get(opt);
|
|
1883
|
+
return group === 'base';
|
|
1884
|
+
})
|
|
1885
|
+
: all.slice();
|
|
1886
|
+
// Sort: short-aliased options first, then long-only; stable by flags.
|
|
1887
|
+
const hasShort = (opt) => {
|
|
1888
|
+
const flags = opt.flags;
|
|
1889
|
+
return /(^|\s|,)-[A-Za-z]/.test(flags);
|
|
1890
|
+
};
|
|
1891
|
+
const byFlags = (opt) => opt.flags;
|
|
1892
|
+
list.sort((a, b) => {
|
|
1893
|
+
const aS = hasShort(a) ? 1 : 0;
|
|
1894
|
+
const bS = hasShort(b) ? 1 : 0;
|
|
1895
|
+
return bS - aS || byFlags(a).localeCompare(byFlags(b));
|
|
1896
|
+
});
|
|
1897
|
+
return list;
|
|
1898
|
+
},
|
|
1899
|
+
});
|
|
1900
|
+
// Optional branded header before help text (kept minimal and deterministic).
|
|
1901
|
+
cli.addHelpText('beforeAll', () => {
|
|
1902
|
+
const header = headerGetter();
|
|
1903
|
+
return header && header.length > 0 ? `${header}\n\n` : '';
|
|
1904
|
+
});
|
|
1905
|
+
// Tests-only: suppress process.exit during help/version flows under Vitest.
|
|
1906
|
+
// Unit tests often construct GetDotenvCli directly (bypassing createCli),
|
|
1907
|
+
// so install a local exitOverride when a test environment is detected.
|
|
1908
|
+
const underTests = process.env.GETDOTENV_TEST === '1' ||
|
|
1909
|
+
typeof process.env.VITEST_WORKER_ID === 'string';
|
|
1910
|
+
if (underTests) {
|
|
1911
|
+
cli.exitOverride((err) => {
|
|
1912
|
+
const code = err?.code;
|
|
1913
|
+
if (code === 'commander.helpDisplayed' ||
|
|
1914
|
+
code === 'commander.version' ||
|
|
1915
|
+
code === 'commander.help')
|
|
1916
|
+
return;
|
|
1917
|
+
throw err;
|
|
1918
|
+
});
|
|
1919
|
+
}
|
|
1920
|
+
// Ensure the root has a no-op action so preAction hooks installed by
|
|
1921
|
+
// passOptions() fire for root-only invocations (no subcommand).
|
|
1922
|
+
// Subcommands still take precedence and will not hit this action.
|
|
1923
|
+
// This keeps root-side effects (e.g., --log) working in direct hosts/tests.
|
|
1924
|
+
cli.action(() => {
|
|
1925
|
+
/* no-op */
|
|
1926
|
+
});
|
|
1927
|
+
// PreSubcommand hook: compute a context if absent, without mutating process.env.
|
|
1928
|
+
// The passOptions() helper, when installed, resolves the final context.
|
|
1929
|
+
cli.hook('preSubcommand', async () => {
|
|
1930
|
+
if (cli.hasCtx())
|
|
1931
|
+
return;
|
|
1932
|
+
await cli.resolveAndLoad({ loadProcess: false });
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
/**
|
|
1937
|
+
* Determine the effective namespace for a child plugin (override \> default).
|
|
1938
|
+
*/
|
|
1939
|
+
const effectiveNs = (child) => {
|
|
1940
|
+
const o = child.override;
|
|
1941
|
+
return (o && typeof o.ns === 'string' && o.ns.length > 0 ? o.ns : child.plugin.ns).trim();
|
|
1942
|
+
};
|
|
1943
|
+
const isPromise = (v) => !!v && typeof v.then === 'function';
|
|
1944
|
+
function runInstall(parentCli, plugin) {
|
|
1945
|
+
// Create mount and run setup
|
|
1946
|
+
const mount = parentCli.ns(plugin.ns);
|
|
1947
|
+
const setupRet = plugin.setup(mount);
|
|
1948
|
+
const pending = [];
|
|
1949
|
+
if (isPromise(setupRet))
|
|
1950
|
+
pending.push(setupRet.then(() => undefined));
|
|
1951
|
+
// Enforce sibling uniqueness before creating children
|
|
1952
|
+
const names = new Set();
|
|
1953
|
+
for (const entry of plugin.children) {
|
|
1954
|
+
const ns = effectiveNs(entry);
|
|
1955
|
+
if (names.has(ns)) {
|
|
1956
|
+
const under = mount.name();
|
|
1957
|
+
throw new Error(`Duplicate namespace '${ns}' under '${under || 'root'}'. Override via .use(plugin, { ns: '...' }).`);
|
|
1958
|
+
}
|
|
1959
|
+
names.add(ns);
|
|
1960
|
+
}
|
|
1961
|
+
// Install children (pre-order), synchronously when possible
|
|
1962
|
+
for (const entry of plugin.children) {
|
|
1963
|
+
const childRet = runInstall(mount, entry.plugin);
|
|
1964
|
+
if (isPromise(childRet))
|
|
1965
|
+
pending.push(childRet);
|
|
1966
|
+
}
|
|
1967
|
+
if (pending.length > 0)
|
|
1968
|
+
return Promise.all(pending).then(() => undefined);
|
|
1969
|
+
return;
|
|
1970
|
+
}
|
|
1971
|
+
/**
|
|
1972
|
+
* Install a plugin and its children (pre-order setup phase).
|
|
1973
|
+
* Enforces sibling namespace uniqueness.
|
|
1974
|
+
*/
|
|
1975
|
+
function setupPluginTree(cli, plugin) {
|
|
1976
|
+
const ret = runInstall(cli, plugin);
|
|
1977
|
+
return isPromise(ret) ? ret : Promise.resolve();
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
/**
|
|
1981
|
+
* Resolve options strictly and compute the dotenv context via the loader/overlay path.
|
|
1982
|
+
*
|
|
1983
|
+
* @param customOptions - Partial options overlay.
|
|
1984
|
+
* @param plugins - Plugins list for config validation.
|
|
1985
|
+
* @param hostMetaUrl - Import URL for resolving the packaged root.
|
|
1986
|
+
*/
|
|
1987
|
+
async function resolveAndComputeContext(customOptions, plugins, hostMetaUrl) {
|
|
1988
|
+
const optionsResolved = await resolveGetDotenvOptions(customOptions);
|
|
1989
|
+
// Strict schema validation
|
|
1990
|
+
getDotenvOptionsSchemaResolved.parse(optionsResolved);
|
|
1991
|
+
const ctx = await computeContext(optionsResolved, plugins, hostMetaUrl);
|
|
1992
|
+
return ctx;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
/**
|
|
1996
|
+
* Run afterResolve hooks for a plugin tree (parent → children).
|
|
1997
|
+
*/
|
|
1998
|
+
async function runAfterResolveTree(cli, plugins, ctx) {
|
|
1999
|
+
const run = async (p) => {
|
|
2000
|
+
if (p.afterResolve)
|
|
2001
|
+
await p.afterResolve(cli, ctx);
|
|
2002
|
+
for (const child of p.children)
|
|
2003
|
+
await run(child.plugin);
|
|
2004
|
+
};
|
|
2005
|
+
for (const p of plugins)
|
|
2006
|
+
await run(p);
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
/**
|
|
2010
|
+
* Temporarily tag options added during a callback as 'app' for grouped help.
|
|
2011
|
+
* Wraps `addOption` on the command instance.
|
|
2012
|
+
*/
|
|
2013
|
+
function tagAppOptionsAround(root, setOptionGroup, fn) {
|
|
2014
|
+
const originalAddOption = root.addOption.bind(root);
|
|
2015
|
+
root.addOption = ((opt) => {
|
|
2016
|
+
setOptionGroup(opt, 'app');
|
|
2017
|
+
return originalAddOption(opt);
|
|
2018
|
+
});
|
|
2019
|
+
try {
|
|
2020
|
+
return fn(root);
|
|
2021
|
+
}
|
|
2022
|
+
finally {
|
|
2023
|
+
root.addOption = originalAddOption;
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
/**
|
|
2028
|
+
* Read the version from the nearest `package.json` relative to the provided import URL.
|
|
2029
|
+
*
|
|
2030
|
+
* @param importMetaUrl - The `import.meta.url` of the calling module.
|
|
2031
|
+
* @returns The version string or undefined if not found.
|
|
2032
|
+
*/
|
|
2033
|
+
async function readPkgVersion(importMetaUrl) {
|
|
2034
|
+
if (!importMetaUrl)
|
|
2035
|
+
return undefined;
|
|
2036
|
+
try {
|
|
2037
|
+
const fromUrl = fileURLToPath(importMetaUrl);
|
|
2038
|
+
const pkgDir = await packageDirectory({ cwd: fromUrl });
|
|
2039
|
+
if (!pkgDir)
|
|
2040
|
+
return undefined;
|
|
2041
|
+
const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
|
|
2042
|
+
const pkg = JSON.parse(txt);
|
|
2043
|
+
return pkg.version ?? undefined;
|
|
2044
|
+
}
|
|
2045
|
+
catch {
|
|
2046
|
+
// best-effort only
|
|
2047
|
+
return undefined;
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
/** src/cliHost/GetDotenvCli.ts
|
|
2052
|
+
* Plugin-first CLI host for get-dotenv with Commander generics preserved.
|
|
2053
|
+
* Public surface implements GetDotenvCliPublic and provides:
|
|
2054
|
+
* - attachRootOptions (builder-only; no public override wiring)
|
|
2055
|
+
* - resolveAndLoad (strict resolve + context compute)
|
|
2056
|
+
* - getCtx/hasCtx accessors
|
|
2057
|
+
* - ns() for typed subcommand creation with duplicate-name guard
|
|
2058
|
+
* - grouped help rendering with dynamic option descriptions
|
|
2059
|
+
*/
|
|
1614
2060
|
const HOST_META_URL = import.meta.url;
|
|
1615
2061
|
const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
|
|
1616
2062
|
const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
|
|
@@ -1624,11 +2070,13 @@ const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
|
|
|
1624
2070
|
* - Provide a namespacing helper (ns).
|
|
1625
2071
|
* - Support composable plugins with parent → children install and afterResolve.
|
|
1626
2072
|
*/
|
|
1627
|
-
|
|
2073
|
+
class GetDotenvCli extends Command {
|
|
1628
2074
|
/** Registered top-level plugins (composition happens via .use()) */
|
|
1629
2075
|
_plugins = [];
|
|
1630
2076
|
/** One-time installation guard */
|
|
1631
2077
|
_installed = false;
|
|
2078
|
+
/** In-flight installation promise to guard against concurrent installs */
|
|
2079
|
+
_installing;
|
|
1632
2080
|
/** Optional header line to prepend in help output */
|
|
1633
2081
|
[HELP_HEADER_SYMBOL];
|
|
1634
2082
|
/** Context/options stored under symbols (typed) */
|
|
@@ -1639,56 +2087,23 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1639
2087
|
* dynamicOption on children.
|
|
1640
2088
|
*/
|
|
1641
2089
|
createCommand(name) {
|
|
1642
|
-
// Explicitly construct a GetDotenvCli
|
|
2090
|
+
// Explicitly construct a GetDotenvCli for children to preserve helpers.
|
|
1643
2091
|
return new GetDotenvCli(name);
|
|
1644
2092
|
}
|
|
1645
2093
|
constructor(alias = 'getdotenv') {
|
|
1646
2094
|
super(alias);
|
|
1647
|
-
// Ensure subcommands that use passThroughOptions can be attached safely.
|
|
1648
|
-
// Commander requires parent commands to enable positional options when a
|
|
1649
|
-
// child uses passThroughOptions.
|
|
1650
2095
|
this.enablePositionalOptions();
|
|
1651
|
-
//
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
: all.slice(); // subcommands: show all options (their own "Options:" block)
|
|
1663
|
-
// Sort: short-aliased options first, then long-only; stable by flags.
|
|
1664
|
-
const hasShort = (opt) => {
|
|
1665
|
-
const flags = opt.flags;
|
|
1666
|
-
// Matches "-x," or starting "-x " before any long
|
|
1667
|
-
return /(^|\s|,)-[A-Za-z]/.test(flags);
|
|
1668
|
-
};
|
|
1669
|
-
const byFlags = (opt) => opt.flags;
|
|
1670
|
-
list.sort((a, b) => {
|
|
1671
|
-
const aS = hasShort(a) ? 1 : 0;
|
|
1672
|
-
const bS = hasShort(b) ? 1 : 0;
|
|
1673
|
-
return bS - aS || byFlags(a).localeCompare(byFlags(b));
|
|
1674
|
-
});
|
|
1675
|
-
return list;
|
|
1676
|
-
},
|
|
1677
|
-
});
|
|
1678
|
-
this.addHelpText('beforeAll', () => {
|
|
1679
|
-
const header = this[HELP_HEADER_SYMBOL];
|
|
1680
|
-
return header && header.length > 0 ? `${header}\n\n` : '';
|
|
1681
|
-
});
|
|
1682
|
-
// Skeleton preSubcommand hook: produce a context if absent, without
|
|
1683
|
-
// mutating process.env. The passOptions hook (when installed) will
|
|
1684
|
-
// compute the final context using merged CLI options; keeping
|
|
1685
|
-
// loadProcess=false here avoids leaking dotenv values into the parent
|
|
1686
|
-
// process env before subcommands execute.
|
|
1687
|
-
this.hook('preSubcommand', async () => {
|
|
1688
|
-
if (this.getCtx())
|
|
1689
|
-
return;
|
|
1690
|
-
await this.resolveAndLoad({ loadProcess: false });
|
|
1691
|
-
});
|
|
2096
|
+
// Delegate the heavy setup to a helper to keep the constructor lean.
|
|
2097
|
+
initializeInstance(this, () => this[HELP_HEADER_SYMBOL]);
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Attach legacy/base root flags to this CLI instance.
|
|
2101
|
+
* Delegates to the pure builder in attachRootOptions.ts.
|
|
2102
|
+
*/
|
|
2103
|
+
attachRootOptions(defaults) {
|
|
2104
|
+
const d = (defaults ?? baseRootOptionDefaults);
|
|
2105
|
+
attachRootOptions(this, d);
|
|
2106
|
+
return this;
|
|
1692
2107
|
}
|
|
1693
2108
|
/**
|
|
1694
2109
|
* Resolve options (strict) and compute dotenv context.
|
|
@@ -1700,11 +2115,9 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1700
2115
|
* long-running side-effects while still evaluating dynamic help text.
|
|
1701
2116
|
*/
|
|
1702
2117
|
async resolveAndLoad(customOptions = {}, opts) {
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
// Delegate the heavy lifting to the shared helper (guarded path supported).
|
|
1707
|
-
const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
|
|
2118
|
+
const ctx = await resolveAndComputeContext(customOptions,
|
|
2119
|
+
// Pass only plugin instances to the resolver (not entries with overrides)
|
|
2120
|
+
this._plugins.map((e) => e.plugin), HOST_META_URL);
|
|
1708
2121
|
// Persist context on the instance for later access.
|
|
1709
2122
|
this[CTX_SYMBOL] = ctx;
|
|
1710
2123
|
// Ensure plugins are installed exactly once, then run afterResolve.
|
|
@@ -1718,14 +2131,6 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1718
2131
|
createDynamicOption(flags, desc, parser, defaultValue) {
|
|
1719
2132
|
return makeDynamicOption(flags, (c) => desc(c), parser, defaultValue);
|
|
1720
2133
|
}
|
|
1721
|
-
/**
|
|
1722
|
-
* Chainable helper mirroring .option(), but with a dynamic description.
|
|
1723
|
-
* Equivalent to addOption(createDynamicOption(...)).
|
|
1724
|
-
*/
|
|
1725
|
-
dynamicOption(flags, desc, parser, defaultValue) {
|
|
1726
|
-
this.addOption(this.createDynamicOption(flags, desc, parser, defaultValue));
|
|
1727
|
-
return this;
|
|
1728
|
-
}
|
|
1729
2134
|
/**
|
|
1730
2135
|
* Evaluate dynamic descriptions for this command and all descendants using
|
|
1731
2136
|
* the provided resolved configuration. Mutates the Option.description in
|
|
@@ -1734,24 +2139,58 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1734
2139
|
evaluateDynamicOptions(resolved) {
|
|
1735
2140
|
evaluateDynamicOptions(this, resolved);
|
|
1736
2141
|
}
|
|
2142
|
+
/** Internal: climb to the true root (host) command. */
|
|
2143
|
+
_root() {
|
|
2144
|
+
let node = this;
|
|
2145
|
+
while (node.parent) {
|
|
2146
|
+
node = node.parent;
|
|
2147
|
+
}
|
|
2148
|
+
return node;
|
|
2149
|
+
}
|
|
1737
2150
|
/**
|
|
1738
2151
|
* Retrieve the current invocation context (if any).
|
|
1739
2152
|
*/
|
|
1740
2153
|
getCtx() {
|
|
1741
|
-
|
|
2154
|
+
let ctx = this[CTX_SYMBOL];
|
|
2155
|
+
if (!ctx) {
|
|
2156
|
+
const root = this._root();
|
|
2157
|
+
ctx = root[CTX_SYMBOL];
|
|
2158
|
+
}
|
|
2159
|
+
if (!ctx) {
|
|
2160
|
+
throw new Error('Dotenv context unavailable. Ensure resolveAndLoad() has been called or the host is wired with passOptions() before invoking commands.');
|
|
2161
|
+
}
|
|
2162
|
+
return ctx;
|
|
2163
|
+
}
|
|
2164
|
+
/**
|
|
2165
|
+
* Check whether a context has been resolved (non-throwing guard).
|
|
2166
|
+
*/
|
|
2167
|
+
hasCtx() {
|
|
2168
|
+
if (this[CTX_SYMBOL] !== undefined)
|
|
2169
|
+
return true;
|
|
2170
|
+
const root = this._root();
|
|
2171
|
+
return root[CTX_SYMBOL] !== undefined;
|
|
1742
2172
|
}
|
|
1743
2173
|
/**
|
|
1744
2174
|
* Retrieve the merged root CLI options bag (if set by passOptions()).
|
|
1745
2175
|
* Downstream-safe: no generics required.
|
|
1746
2176
|
*/
|
|
1747
2177
|
getOptions() {
|
|
1748
|
-
|
|
2178
|
+
if (this[OPTS_SYMBOL])
|
|
2179
|
+
return this[OPTS_SYMBOL];
|
|
2180
|
+
const root = this._root();
|
|
2181
|
+
const bag = root[OPTS_SYMBOL];
|
|
2182
|
+
if (bag)
|
|
2183
|
+
return bag;
|
|
2184
|
+
return undefined;
|
|
1749
2185
|
}
|
|
1750
2186
|
/** Internal: set the merged root options bag for this run. */
|
|
1751
2187
|
_setOptionsBag(bag) {
|
|
1752
2188
|
this[OPTS_SYMBOL] = bag;
|
|
1753
2189
|
}
|
|
1754
|
-
/**
|
|
2190
|
+
/**
|
|
2191
|
+
* Convenience helper to create a namespaced subcommand with argument inference.
|
|
2192
|
+
* This mirrors Commander generics so downstream chaining stays fully typed.
|
|
2193
|
+
*/
|
|
1755
2194
|
ns(name) {
|
|
1756
2195
|
// Guard against same-level duplicate command names for clearer diagnostics.
|
|
1757
2196
|
const exists = this.commands.some((c) => c.name() === name);
|
|
@@ -1765,18 +2204,7 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1765
2204
|
* Allows downstream apps to demarcate their root-level options.
|
|
1766
2205
|
*/
|
|
1767
2206
|
tagAppOptions(fn) {
|
|
1768
|
-
|
|
1769
|
-
const originalAddOption = root.addOption.bind(root);
|
|
1770
|
-
root.addOption = function patchedAdd(opt) {
|
|
1771
|
-
root.setOptionGroup(opt, 'app');
|
|
1772
|
-
return originalAddOption(opt);
|
|
1773
|
-
};
|
|
1774
|
-
try {
|
|
1775
|
-
return fn(root);
|
|
1776
|
-
}
|
|
1777
|
-
finally {
|
|
1778
|
-
root.addOption = originalAddOption;
|
|
1779
|
-
}
|
|
2207
|
+
return tagAppOptionsAround(this, this.setOptionGroup.bind(this), fn);
|
|
1780
2208
|
}
|
|
1781
2209
|
/**
|
|
1782
2210
|
* Branding helper: set CLI name/description/version and optional help header.
|
|
@@ -1785,26 +2213,11 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1785
2213
|
*/
|
|
1786
2214
|
async brand(args) {
|
|
1787
2215
|
const { name, description, version, importMetaUrl, helpHeader } = args;
|
|
1788
|
-
if (typeof name === 'string' && name.length > 0)
|
|
1789
|
-
this.name(name);
|
|
1790
|
-
if (typeof description === 'string')
|
|
1791
|
-
this.description(description);
|
|
1792
|
-
|
|
1793
|
-
if (!v && importMetaUrl) {
|
|
1794
|
-
try {
|
|
1795
|
-
const fromUrl = fileURLToPath(importMetaUrl);
|
|
1796
|
-
const pkgDir = await packageDirectory({ cwd: fromUrl });
|
|
1797
|
-
if (pkgDir) {
|
|
1798
|
-
const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
|
|
1799
|
-
const pkg = JSON.parse(txt);
|
|
1800
|
-
if (pkg.version)
|
|
1801
|
-
v = pkg.version;
|
|
1802
|
-
}
|
|
1803
|
-
}
|
|
1804
|
-
catch {
|
|
1805
|
-
// best-effort only
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
2216
|
+
if (typeof name === 'string' && name.length > 0)
|
|
2217
|
+
this.name(name);
|
|
2218
|
+
if (typeof description === 'string')
|
|
2219
|
+
this.description(description);
|
|
2220
|
+
const v = version ?? (await readPkgVersion(importMetaUrl));
|
|
1808
2221
|
if (v)
|
|
1809
2222
|
this.version(v);
|
|
1810
2223
|
// Help header:
|
|
@@ -1824,34 +2237,7 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1824
2237
|
* hybrid ordering. Applies to root and any parent command.
|
|
1825
2238
|
*/
|
|
1826
2239
|
helpInformation() {
|
|
1827
|
-
|
|
1828
|
-
const base = super.helpInformation();
|
|
1829
|
-
const groups = renderOptionGroups(this);
|
|
1830
|
-
const block = typeof groups === 'string' ? groups.trim() : '';
|
|
1831
|
-
let out = base;
|
|
1832
|
-
if (!block) {
|
|
1833
|
-
// Ensure a trailing blank line even when no extra groups render.
|
|
1834
|
-
if (!out.endsWith('\n\n'))
|
|
1835
|
-
out = out.endsWith('\n') ? `${out}\n` : `${out}\n\n`;
|
|
1836
|
-
return out;
|
|
1837
|
-
}
|
|
1838
|
-
// Insert just before "Commands:" when present.
|
|
1839
|
-
const marker = '\nCommands:';
|
|
1840
|
-
const idx = base.indexOf(marker);
|
|
1841
|
-
if (idx >= 0) {
|
|
1842
|
-
const toInsert = groups.startsWith('\n') ? groups : `\n${groups}`;
|
|
1843
|
-
out = `${base.slice(0, idx)}${toInsert}${base.slice(idx)}`;
|
|
1844
|
-
}
|
|
1845
|
-
else {
|
|
1846
|
-
// Otherwise append.
|
|
1847
|
-
const sep = base.endsWith('\n') || groups.startsWith('\n') ? '' : '\n';
|
|
1848
|
-
out = `${base}${sep}${groups}`;
|
|
1849
|
-
}
|
|
1850
|
-
// Ensure a trailing blank line for prompt separation.
|
|
1851
|
-
if (!out.endsWith('\n\n')) {
|
|
1852
|
-
out = out.endsWith('\n') ? `${out}\n` : `${out}\n\n`;
|
|
1853
|
-
}
|
|
1854
|
-
return out;
|
|
2240
|
+
return buildHelpInformation(super.helpInformation(), this);
|
|
1855
2241
|
}
|
|
1856
2242
|
/**
|
|
1857
2243
|
* Public: tag an Option with a display group for help (root/app/plugin:<id>).
|
|
@@ -1863,15 +2249,8 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1863
2249
|
* Register a plugin for installation (parent level).
|
|
1864
2250
|
* Installation occurs on first resolveAndLoad() (or explicit install()).
|
|
1865
2251
|
*/
|
|
1866
|
-
use(plugin) {
|
|
1867
|
-
this._plugins.push(plugin);
|
|
1868
|
-
// Immediately run setup so subcommands exist before parsing.
|
|
1869
|
-
const setupOne = (p) => {
|
|
1870
|
-
p.setup(this);
|
|
1871
|
-
for (const child of p.children)
|
|
1872
|
-
setupOne(child);
|
|
1873
|
-
};
|
|
1874
|
-
setupOne(plugin);
|
|
2252
|
+
use(plugin, override) {
|
|
2253
|
+
this._plugins.push({ plugin, override });
|
|
1875
2254
|
return this;
|
|
1876
2255
|
}
|
|
1877
2256
|
/**
|
|
@@ -1879,24 +2258,52 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1879
2258
|
* Runs only once per CLI instance.
|
|
1880
2259
|
*/
|
|
1881
2260
|
async install() {
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
2261
|
+
if (this._installed)
|
|
2262
|
+
return;
|
|
2263
|
+
if (this._installing) {
|
|
2264
|
+
await this._installing;
|
|
2265
|
+
return;
|
|
2266
|
+
}
|
|
2267
|
+
this._installing = (async () => {
|
|
2268
|
+
// Install parent → children with host-created mounts (async-aware).
|
|
2269
|
+
for (const entry of this._plugins) {
|
|
2270
|
+
const p = entry.plugin;
|
|
2271
|
+
await setupPluginTree(this, p);
|
|
2272
|
+
}
|
|
2273
|
+
this._installed = true;
|
|
2274
|
+
})();
|
|
2275
|
+
try {
|
|
2276
|
+
await this._installing;
|
|
2277
|
+
}
|
|
2278
|
+
finally {
|
|
2279
|
+
// leave _installing as resolved; subsequent calls return early via _installed
|
|
2280
|
+
}
|
|
1886
2281
|
}
|
|
1887
2282
|
/**
|
|
1888
2283
|
* Run afterResolve hooks for all plugins (parent → children).
|
|
1889
2284
|
*/
|
|
1890
2285
|
async _runAfterResolve(ctx) {
|
|
1891
|
-
|
|
1892
|
-
if (p.afterResolve)
|
|
1893
|
-
await p.afterResolve(this, ctx);
|
|
1894
|
-
for (const child of p.children)
|
|
1895
|
-
await run(child);
|
|
1896
|
-
};
|
|
1897
|
-
for (const p of this._plugins)
|
|
1898
|
-
await run(p);
|
|
2286
|
+
await runAfterResolveTree(this, this._plugins.map((e) => e.plugin), ctx);
|
|
1899
2287
|
}
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
/**
|
|
2291
|
+
* Base CLI options derived from the shared root option defaults.
|
|
2292
|
+
* Used for type-safe initialization of CLI options bags.
|
|
2293
|
+
*/
|
|
2294
|
+
const baseGetDotenvCliOptions = baseRootOptionDefaults;
|
|
2295
|
+
|
|
2296
|
+
/**
|
|
2297
|
+
* Return the top-level root command for a given mount or action's thisCommand.
|
|
2298
|
+
*
|
|
2299
|
+
* @param cmd - any command (mount or thisCommand inside an action)
|
|
2300
|
+
* @returns the root command instance
|
|
2301
|
+
*/
|
|
2302
|
+
const getRootCommand = (cmd) => {
|
|
2303
|
+
let node = cmd;
|
|
2304
|
+
while (node.parent)
|
|
2305
|
+
node = node.parent;
|
|
2306
|
+
return node;
|
|
1900
2307
|
};
|
|
1901
2308
|
|
|
1902
2309
|
/**
|
|
@@ -1904,199 +2311,295 @@ let GetDotenvCli$1 = class GetDotenvCli extends Command {
|
|
|
1904
2311
|
* Centralizes construction and reduces inline casts at call sites.
|
|
1905
2312
|
*/
|
|
1906
2313
|
const toHelpConfig = (merged, plugins) => {
|
|
1907
|
-
|
|
2314
|
+
return {
|
|
1908
2315
|
...merged,
|
|
1909
2316
|
plugins: plugins ?? {},
|
|
1910
2317
|
};
|
|
1911
|
-
return bag;
|
|
1912
2318
|
};
|
|
1913
2319
|
|
|
1914
|
-
/**
|
|
1915
|
-
*
|
|
1916
|
-
*
|
|
1917
|
-
* This module exposes a structural public interface for the host that plugins
|
|
1918
|
-
* should use (GetDotenvCliPublic). Using a structural type at the seam avoids
|
|
1919
|
-
* nominal class identity issues (private fields) in downstream consumers.
|
|
2320
|
+
/**
|
|
2321
|
+
* Compose a child-process env overlay from dotenv and the merged CLI options bag.
|
|
2322
|
+
* Returns a shallow object including getDotenvCliOptions when serializable.
|
|
1920
2323
|
*/
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
const
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
},
|
|
1938
|
-
};
|
|
1939
|
-
// Attach instance-bound helpers on the returned plugin object.
|
|
1940
|
-
const extended = base;
|
|
1941
|
-
extended.readConfig = function (_cli) {
|
|
1942
|
-
// Config is stored per-plugin-instance by the host (WeakMap in computeContext).
|
|
1943
|
-
const value = _getPluginConfigForInstance(extended);
|
|
1944
|
-
if (value === undefined) {
|
|
1945
|
-
// Guard: host has not resolved config yet (incorrect lifecycle usage).
|
|
1946
|
-
throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
|
|
1947
|
-
}
|
|
1948
|
-
return value;
|
|
1949
|
-
};
|
|
1950
|
-
// Plugin-bound dynamic option factory
|
|
1951
|
-
extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
|
|
1952
|
-
return cli.createDynamicOption(flags, (cfg) => {
|
|
1953
|
-
// Prefer the validated slice stored per instance; fallback to help-bag
|
|
1954
|
-
// (by-id) so top-level `-h` can render effective defaults before resolve.
|
|
1955
|
-
const fromStore = _getPluginConfigForInstance(extended);
|
|
1956
|
-
const id = extended.id;
|
|
1957
|
-
let fromBag;
|
|
1958
|
-
if (!fromStore && id) {
|
|
1959
|
-
const maybe = cfg.plugins[id];
|
|
1960
|
-
if (maybe && typeof maybe === 'object') {
|
|
1961
|
-
fromBag = maybe;
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
// Always provide a concrete object to dynamic callbacks:
|
|
1965
|
-
// - With a schema: computeContext stores the parsed object.
|
|
1966
|
-
// - Without a schema: computeContext stores {}.
|
|
1967
|
-
// - Help-time fallback: coalesce to {} when only a by-id bag exists.
|
|
1968
|
-
const cfgVal = (fromStore ?? fromBag ?? {});
|
|
1969
|
-
return desc(cfg, cfgVal);
|
|
1970
|
-
}, parser, defaultValue);
|
|
1971
|
-
};
|
|
1972
|
-
return extended;
|
|
2324
|
+
function composeNestedEnv(merged, dotenv) {
|
|
2325
|
+
const out = {};
|
|
2326
|
+
for (const [k, v] of Object.entries(dotenv)) {
|
|
2327
|
+
if (typeof v === 'string')
|
|
2328
|
+
out[k] = v;
|
|
2329
|
+
}
|
|
2330
|
+
try {
|
|
2331
|
+
const { logger: _omit, ...bag } = merged;
|
|
2332
|
+
const txt = JSON.stringify(bag);
|
|
2333
|
+
if (typeof txt === 'string')
|
|
2334
|
+
out.getDotenvCliOptions = txt;
|
|
2335
|
+
}
|
|
2336
|
+
catch {
|
|
2337
|
+
/* best-effort only */
|
|
2338
|
+
}
|
|
2339
|
+
return out;
|
|
1973
2340
|
}
|
|
1974
|
-
|
|
1975
2341
|
/**
|
|
1976
|
-
*
|
|
1977
|
-
*
|
|
1978
|
-
*
|
|
1979
|
-
|
|
2342
|
+
* Strip one layer of symmetric outer quotes (single or double) from a string.
|
|
2343
|
+
*
|
|
2344
|
+
* @param s - Input string.
|
|
2345
|
+
*/
|
|
2346
|
+
const stripOne = (s) => {
|
|
2347
|
+
if (s.length < 2)
|
|
2348
|
+
return s;
|
|
2349
|
+
const a = s.charAt(0);
|
|
2350
|
+
const b = s.charAt(s.length - 1);
|
|
2351
|
+
const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
|
|
2352
|
+
return symmetric ? s.slice(1, -1) : s;
|
|
2353
|
+
};
|
|
2354
|
+
/**
|
|
2355
|
+
* Preserve argv array for Node -e/--eval payloads under shell-off and
|
|
2356
|
+
* peel one symmetric outer quote layer from the code argument.
|
|
1980
2357
|
*/
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
}
|
|
1991
|
-
/**
|
|
1992
|
-
* Install preSubcommand/preAction hooks that:
|
|
1993
|
-
* - Merge options (parent round-trip + current invocation) using resolveCliOptions.
|
|
1994
|
-
* - Persist the merged bag on the current command and on the host (for ergonomics).
|
|
1995
|
-
* - Compute the dotenv context once via resolveAndLoad(serviceOptions).
|
|
1996
|
-
* - Validate the composed env against discovered config (warn or --strict fail).
|
|
1997
|
-
*/
|
|
1998
|
-
passOptions(defaults) {
|
|
1999
|
-
const d = (defaults ?? baseRootOptionDefaults);
|
|
2000
|
-
this.hook('preSubcommand', async (thisCommand) => {
|
|
2001
|
-
const raw = thisCommand.opts();
|
|
2002
|
-
const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
|
|
2003
|
-
// Persist merged options (for nested behavior and ergonomic access).
|
|
2004
|
-
thisCommand.getDotenvCliOptions =
|
|
2005
|
-
merged;
|
|
2006
|
-
this._setOptionsBag(merged);
|
|
2007
|
-
// Build service options and compute context (always-on loader path).
|
|
2008
|
-
const serviceOptions = getDotenvCliOptions2Options(merged);
|
|
2009
|
-
await this.resolveAndLoad(serviceOptions);
|
|
2010
|
-
// Refresh dynamic option descriptions using resolved config + plugin slices
|
|
2011
|
-
try {
|
|
2012
|
-
const ctx = this.getCtx();
|
|
2013
|
-
const helpCfg = toHelpConfig(merged, ctx?.pluginConfigs ?? {});
|
|
2014
|
-
this.evaluateDynamicOptions(helpCfg);
|
|
2015
|
-
}
|
|
2016
|
-
catch {
|
|
2017
|
-
/* best-effort */
|
|
2018
|
-
}
|
|
2019
|
-
// Global validation: once after Phase C using config sources.
|
|
2020
|
-
try {
|
|
2021
|
-
const ctx = this.getCtx();
|
|
2022
|
-
const dotenv = ctx?.dotenv ?? {};
|
|
2023
|
-
const sources = await resolveGetDotenvConfigSources(import.meta.url);
|
|
2024
|
-
const issues = validateEnvAgainstSources(dotenv, sources);
|
|
2025
|
-
if (Array.isArray(issues) && issues.length > 0) {
|
|
2026
|
-
const logger = (merged
|
|
2027
|
-
.logger ?? console);
|
|
2028
|
-
const emit = logger.error ?? logger.log;
|
|
2029
|
-
issues.forEach((m) => {
|
|
2030
|
-
emit(m);
|
|
2031
|
-
});
|
|
2032
|
-
if (merged.strict)
|
|
2033
|
-
process.exit(1);
|
|
2034
|
-
}
|
|
2035
|
-
}
|
|
2036
|
-
catch {
|
|
2037
|
-
// Be tolerant: do not crash non-strict flows on unexpected validator failures.
|
|
2038
|
-
}
|
|
2039
|
-
});
|
|
2040
|
-
// Also handle root-level flows (no subcommand) so option-aliases can run
|
|
2041
|
-
// with the same merged options and context without duplicating logic.
|
|
2042
|
-
this.hook('preAction', async (thisCommand) => {
|
|
2043
|
-
const raw = thisCommand.opts();
|
|
2044
|
-
const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
|
|
2045
|
-
thisCommand.getDotenvCliOptions =
|
|
2046
|
-
merged;
|
|
2047
|
-
this._setOptionsBag(merged);
|
|
2048
|
-
// Avoid duplicate heavy work if a context is already present.
|
|
2049
|
-
if (!this.getCtx()) {
|
|
2050
|
-
const serviceOptions = getDotenvCliOptions2Options(merged);
|
|
2051
|
-
await this.resolveAndLoad(serviceOptions);
|
|
2052
|
-
try {
|
|
2053
|
-
const ctx = this.getCtx();
|
|
2054
|
-
const helpCfg = toHelpConfig(merged, ctx?.pluginConfigs ?? {});
|
|
2055
|
-
this.evaluateDynamicOptions(helpCfg);
|
|
2056
|
-
}
|
|
2057
|
-
catch {
|
|
2058
|
-
/* tolerate */
|
|
2059
|
-
}
|
|
2060
|
-
try {
|
|
2061
|
-
const ctx = this.getCtx();
|
|
2062
|
-
const dotenv = (ctx?.dotenv ?? {});
|
|
2063
|
-
const sources = await resolveGetDotenvConfigSources(import.meta.url);
|
|
2064
|
-
const issues = validateEnvAgainstSources(dotenv, sources);
|
|
2065
|
-
if (Array.isArray(issues) && issues.length > 0) {
|
|
2066
|
-
const logger = (merged
|
|
2067
|
-
.logger ?? console);
|
|
2068
|
-
const emit = logger.error ?? logger.log;
|
|
2069
|
-
issues.forEach((m) => {
|
|
2070
|
-
emit(m);
|
|
2071
|
-
});
|
|
2072
|
-
if (merged.strict) {
|
|
2073
|
-
process.exit(1);
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
}
|
|
2077
|
-
catch {
|
|
2078
|
-
// Tolerate validation side-effects in non-strict mode.
|
|
2079
|
-
}
|
|
2080
|
-
}
|
|
2081
|
-
});
|
|
2082
|
-
return this;
|
|
2358
|
+
function maybePreserveNodeEvalArgv(args) {
|
|
2359
|
+
if (args.length >= 3) {
|
|
2360
|
+
const first = (args[0] ?? '').toLowerCase();
|
|
2361
|
+
const hasEval = args[1] === '-e' || args[1] === '--eval';
|
|
2362
|
+
if (first === 'node' && hasEval) {
|
|
2363
|
+
const copy = args.slice();
|
|
2364
|
+
copy[2] = stripOne(copy[2] ?? '');
|
|
2365
|
+
return copy;
|
|
2366
|
+
}
|
|
2083
2367
|
}
|
|
2368
|
+
return args;
|
|
2084
2369
|
}
|
|
2370
|
+
|
|
2085
2371
|
/**
|
|
2086
|
-
*
|
|
2087
|
-
*
|
|
2372
|
+
* Retrieve the merged root options bag from the current command context.
|
|
2373
|
+
* Climbs to the root `GetDotenvCli` instance to access the persisted options.
|
|
2374
|
+
*
|
|
2375
|
+
* @param cmd - The current command instance (thisCommand).
|
|
2376
|
+
* @throws Error if the root is not a GetDotenvCli or options are missing.
|
|
2088
2377
|
*/
|
|
2089
2378
|
const readMergedOptions = (cmd) => {
|
|
2090
|
-
//
|
|
2379
|
+
// Climb to the true root
|
|
2091
2380
|
let root = cmd;
|
|
2092
|
-
while (root.parent)
|
|
2381
|
+
while (root.parent)
|
|
2093
2382
|
root = root.parent;
|
|
2383
|
+
// Assert we ended at our host
|
|
2384
|
+
if (!(root instanceof GetDotenvCli)) {
|
|
2385
|
+
throw new Error('readMergedOptions: root command is not a GetDotenvCli.' +
|
|
2386
|
+
'Ensure your CLI is constructed with GetDotenvCli.');
|
|
2387
|
+
}
|
|
2388
|
+
// Require passOptions() to have persisted the bag
|
|
2389
|
+
const bag = root.getOptions();
|
|
2390
|
+
if (!bag || typeof bag !== 'object') {
|
|
2391
|
+
throw new Error('readMergedOptions: merged options are unavailable. ' +
|
|
2392
|
+
'Call .passOptions() on the host before parsing.');
|
|
2393
|
+
}
|
|
2394
|
+
return bag;
|
|
2395
|
+
};
|
|
2396
|
+
|
|
2397
|
+
/**
|
|
2398
|
+
* Batch services (neutral): resolve command and shell settings.
|
|
2399
|
+
* Shared by the generator path and the batch plugin to avoid circular deps.
|
|
2400
|
+
*/
|
|
2401
|
+
/**
|
|
2402
|
+
* Resolve a command string from the {@link ScriptsTable} table.
|
|
2403
|
+
* A script may be expressed as a string or an object with a `cmd` property.
|
|
2404
|
+
*
|
|
2405
|
+
* @param scripts - Optional scripts table.
|
|
2406
|
+
* @param command - User-provided command name or string.
|
|
2407
|
+
* @returns Resolved command string (falls back to the provided command).
|
|
2408
|
+
*/
|
|
2409
|
+
const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
|
|
2410
|
+
? scripts[command].cmd
|
|
2411
|
+
: (scripts?.[command] ?? command);
|
|
2412
|
+
/**
|
|
2413
|
+
* Resolve the shell setting for a given command:
|
|
2414
|
+
* - If the script entry is an object, prefer its `shell` override.
|
|
2415
|
+
* - Otherwise use the provided `shell` (string | boolean).
|
|
2416
|
+
*
|
|
2417
|
+
* @param scripts - Optional scripts table.
|
|
2418
|
+
* @param command - User-provided command name or string.
|
|
2419
|
+
* @param shell - Global shell preference (string | boolean).
|
|
2420
|
+
*/
|
|
2421
|
+
const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
|
|
2422
|
+
? (scripts[command].shell ?? false)
|
|
2423
|
+
: (shell ?? false);
|
|
2424
|
+
|
|
2425
|
+
/**
|
|
2426
|
+
* Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
|
|
2427
|
+
* - If the user explicitly enabled the flag, return true.
|
|
2428
|
+
* - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
|
|
2429
|
+
* - Otherwise, adopt the default (true → set; false/undefined → unset).
|
|
2430
|
+
*
|
|
2431
|
+
* @param exclude - The "on" flag value as parsed by Commander.
|
|
2432
|
+
* @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
|
|
2433
|
+
* @param defaultValue - The generator default to adopt when no explicit toggle is present.
|
|
2434
|
+
* @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
|
|
2435
|
+
*
|
|
2436
|
+
* @example
|
|
2437
|
+
* ```ts
|
|
2438
|
+
* resolveExclusion(undefined, undefined, true); // => true
|
|
2439
|
+
* ```
|
|
2440
|
+
*/
|
|
2441
|
+
const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
|
|
2442
|
+
/**
|
|
2443
|
+
* Resolve an optional flag with "--exclude-all" overrides.
|
|
2444
|
+
* If excludeAll is set and the individual "...-off" is not, force true.
|
|
2445
|
+
* If excludeAllOff is set and the individual flag is not explicitly set, unset.
|
|
2446
|
+
* Otherwise, adopt the default (true → set; false/undefined → unset).
|
|
2447
|
+
*
|
|
2448
|
+
* @param exclude - Individual include/exclude flag.
|
|
2449
|
+
* @param excludeOff - Individual "...-off" flag.
|
|
2450
|
+
* @param defaultValue - Default for the individual flag.
|
|
2451
|
+
* @param excludeAll - Global "exclude-all" flag.
|
|
2452
|
+
* @param excludeAllOff - Global "exclude-all-off" flag.
|
|
2453
|
+
*
|
|
2454
|
+
* @example
|
|
2455
|
+
* resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
|
|
2456
|
+
*/
|
|
2457
|
+
const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
|
|
2458
|
+
// Order of precedence:
|
|
2459
|
+
// 1) Individual explicit "on" wins outright.
|
|
2460
|
+
// 2) Individual explicit "off" wins over any global.
|
|
2461
|
+
// 3) Global exclude-all forces true when not explicitly turned off.
|
|
2462
|
+
// 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
|
|
2463
|
+
// 5) Fall back to the default (true => set; false/undefined => unset).
|
|
2464
|
+
(() => {
|
|
2465
|
+
// Individual "on"
|
|
2466
|
+
if (exclude === true)
|
|
2467
|
+
return true;
|
|
2468
|
+
// Individual "off"
|
|
2469
|
+
if (excludeOff === true)
|
|
2470
|
+
return undefined;
|
|
2471
|
+
// Global "exclude-all" ON (unless explicitly turned off)
|
|
2472
|
+
if (excludeAll === true)
|
|
2473
|
+
return true;
|
|
2474
|
+
// Global "exclude-all-off" (unless explicitly enabled)
|
|
2475
|
+
if (excludeAllOff === true)
|
|
2476
|
+
return undefined;
|
|
2477
|
+
// Default
|
|
2478
|
+
return defaultValue ? true : undefined;
|
|
2479
|
+
})();
|
|
2480
|
+
/**
|
|
2481
|
+
* exactOptionalPropertyTypes-safe setter for optional boolean flags:
|
|
2482
|
+
* delete when undefined; assign when defined — without requiring an index signature on T.
|
|
2483
|
+
*
|
|
2484
|
+
* @typeParam T - Target object type.
|
|
2485
|
+
* @param obj - The object to write to.
|
|
2486
|
+
* @param key - The optional boolean property key of {@link T}.
|
|
2487
|
+
* @param value - The value to set or `undefined` to unset.
|
|
2488
|
+
*
|
|
2489
|
+
* @remarks
|
|
2490
|
+
* Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
|
|
2491
|
+
*/
|
|
2492
|
+
const setOptionalFlag = (obj, key, value) => {
|
|
2493
|
+
const target = obj;
|
|
2494
|
+
const k = key;
|
|
2495
|
+
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
|
|
2496
|
+
if (value === undefined)
|
|
2497
|
+
delete target[k];
|
|
2498
|
+
else
|
|
2499
|
+
target[k] = value;
|
|
2500
|
+
};
|
|
2501
|
+
|
|
2502
|
+
/**
|
|
2503
|
+
* Merge and normalize raw Commander options (current + parent + defaults)
|
|
2504
|
+
* into a GetDotenvCliOptions-like object. Types are intentionally wide to
|
|
2505
|
+
* avoid cross-layer coupling; callers may cast as needed.
|
|
2506
|
+
*/
|
|
2507
|
+
const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
|
|
2508
|
+
const parent = typeof parentJson === 'string' && parentJson.length > 0
|
|
2509
|
+
? JSON.parse(parentJson)
|
|
2510
|
+
: undefined;
|
|
2511
|
+
const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
|
|
2512
|
+
const current = { ...rest };
|
|
2513
|
+
if (typeof scripts === 'string') {
|
|
2514
|
+
try {
|
|
2515
|
+
current.scripts = JSON.parse(scripts);
|
|
2516
|
+
}
|
|
2517
|
+
catch {
|
|
2518
|
+
// ignore parse errors; leave scripts undefined
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
const merged = defaultsDeep({}, defaults, parent ?? {}, current);
|
|
2522
|
+
const d = defaults;
|
|
2523
|
+
setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
|
|
2524
|
+
setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
|
|
2525
|
+
setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
|
|
2526
|
+
setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
|
|
2527
|
+
setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
|
|
2528
|
+
setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
|
|
2529
|
+
setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
|
|
2530
|
+
setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
|
|
2531
|
+
// warnEntropy (tri-state)
|
|
2532
|
+
setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
|
|
2533
|
+
// Normalize shell for predictability: explicit default shell per OS.
|
|
2534
|
+
const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
|
|
2535
|
+
let resolvedShell = merged.shell;
|
|
2536
|
+
if (shellOff)
|
|
2537
|
+
resolvedShell = false;
|
|
2538
|
+
else if (resolvedShell === true || resolvedShell === undefined) {
|
|
2539
|
+
resolvedShell = defaultShell;
|
|
2540
|
+
}
|
|
2541
|
+
else if (typeof resolvedShell !== 'string' &&
|
|
2542
|
+
typeof defaults.shell === 'string') {
|
|
2543
|
+
resolvedShell = defaults.shell;
|
|
2544
|
+
}
|
|
2545
|
+
merged.shell = resolvedShell;
|
|
2546
|
+
const cmd = typeof command === 'string' ? command : undefined;
|
|
2547
|
+
return cmd !== undefined ? { merged, command: cmd } : { merged };
|
|
2548
|
+
};
|
|
2549
|
+
|
|
2550
|
+
const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
|
|
2551
|
+
/**
|
|
2552
|
+
* Build a sanitized environment object for spawning child processes.
|
|
2553
|
+
* Merges `base` and `overlay`, drops undefined values, and handles platform-specific
|
|
2554
|
+
* normalization (e.g. case-insensitivity on Windows).
|
|
2555
|
+
*
|
|
2556
|
+
* @param base - Base environment (usually `process.env`).
|
|
2557
|
+
* @param overlay - Environment variables to overlay.
|
|
2558
|
+
*/
|
|
2559
|
+
const buildSpawnEnv = (base, overlay) => {
|
|
2560
|
+
const raw = {
|
|
2561
|
+
...(base ?? {}),
|
|
2562
|
+
...(overlay ?? {}),
|
|
2563
|
+
};
|
|
2564
|
+
// Drop undefined first
|
|
2565
|
+
const entries = Object.entries(dropUndefined(raw));
|
|
2566
|
+
if (process.platform === 'win32') {
|
|
2567
|
+
// Windows: keys are case-insensitive; collapse duplicates
|
|
2568
|
+
const byLower = new Map();
|
|
2569
|
+
for (const [k, v] of entries) {
|
|
2570
|
+
byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
|
|
2571
|
+
}
|
|
2572
|
+
const out = {};
|
|
2573
|
+
for (const [, [k, v]] of byLower)
|
|
2574
|
+
out[k] = v;
|
|
2575
|
+
// HOME fallback from USERPROFILE (common expectation)
|
|
2576
|
+
if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
|
|
2577
|
+
const up = out['USERPROFILE'];
|
|
2578
|
+
if (typeof up === 'string' && up.length > 0)
|
|
2579
|
+
out['HOME'] = up;
|
|
2580
|
+
}
|
|
2581
|
+
// Normalize TMP/TEMP coherence (pick any present; reflect to both)
|
|
2582
|
+
const tmp = out['TMP'] ?? out['TEMP'];
|
|
2583
|
+
if (typeof tmp === 'string' && tmp.length > 0) {
|
|
2584
|
+
out['TMP'] = tmp;
|
|
2585
|
+
out['TEMP'] = tmp;
|
|
2586
|
+
}
|
|
2587
|
+
return out;
|
|
2588
|
+
}
|
|
2589
|
+
// POSIX: keep keys as-is
|
|
2590
|
+
const out = Object.fromEntries(entries);
|
|
2591
|
+
// Ensure TMPDIR exists when any temp key is present (best-effort)
|
|
2592
|
+
const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
|
|
2593
|
+
if (typeof tmpdir === 'string' && tmpdir.length > 0) {
|
|
2594
|
+
out['TMPDIR'] = tmpdir;
|
|
2094
2595
|
}
|
|
2095
|
-
|
|
2096
|
-
return typeof hostAny.getOptions === 'function'
|
|
2097
|
-
? hostAny.getOptions()
|
|
2098
|
-
: root
|
|
2099
|
-
.getDotenvCliOptions;
|
|
2596
|
+
return out;
|
|
2100
2597
|
};
|
|
2101
2598
|
|
|
2102
|
-
|
|
2599
|
+
/**
|
|
2600
|
+
* Identity helper to define a scripts table while preserving a concrete TShell
|
|
2601
|
+
* type parameter in downstream inference.
|
|
2602
|
+
*/
|
|
2603
|
+
const defineScripts = () => (t) => t;
|
|
2604
|
+
|
|
2605
|
+
export { GetDotenvCli, baseGetDotenvCliOptions, buildSpawnEnv, composeNestedEnv, definePlugin, defineScripts, getRootCommand, maybePreserveNodeEvalArgv, readMergedOptions, resolveCliOptions, resolveCommand, resolveShell, runCommand, runCommandResult, stripOne, toHelpConfig };
|