@karmaniverous/get-dotenv 6.0.0-0 → 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.
Files changed (93) hide show
  1. package/README.md +86 -334
  2. package/dist/cli.d.ts +569 -0
  3. package/dist/cli.mjs +18788 -0
  4. package/dist/cliHost.d.ts +548 -253
  5. package/dist/cliHost.mjs +1990 -1458
  6. package/dist/config.d.ts +192 -14
  7. package/dist/config.mjs +256 -81
  8. package/dist/env-overlay.d.ts +226 -18
  9. package/dist/env-overlay.mjs +181 -22
  10. package/dist/getdotenv.cli.mjs +18166 -3437
  11. package/dist/index.d.ts +729 -136
  12. package/dist/index.mjs +18207 -3457
  13. package/dist/plugins-aws.d.ts +289 -104
  14. package/dist/plugins-aws.mjs +2462 -350
  15. package/dist/plugins-batch.d.ts +355 -105
  16. package/dist/plugins-batch.mjs +2595 -420
  17. package/dist/plugins-cmd.d.ts +287 -118
  18. package/dist/plugins-cmd.mjs +2661 -839
  19. package/dist/plugins-init.d.ts +272 -100
  20. package/dist/plugins-init.mjs +2152 -37
  21. package/dist/plugins.d.ts +323 -140
  22. package/dist/plugins.mjs +18006 -2025
  23. package/dist/templates/cli/index.ts +26 -0
  24. package/dist/templates/cli/plugins/hello.ts +43 -0
  25. package/dist/templates/config/js/getdotenv.config.js +20 -0
  26. package/dist/templates/config/json/local/getdotenv.config.local.json +7 -0
  27. package/dist/templates/config/json/public/getdotenv.config.json +9 -0
  28. package/dist/templates/config/public/getdotenv.config.json +8 -0
  29. package/dist/templates/config/ts/getdotenv.config.ts +28 -0
  30. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +7 -0
  31. package/dist/templates/config/yaml/public/getdotenv.config.yaml +7 -0
  32. package/dist/templates/getdotenv.config.js +20 -0
  33. package/dist/templates/getdotenv.config.json +9 -0
  34. package/dist/templates/getdotenv.config.local.json +7 -0
  35. package/dist/templates/getdotenv.config.local.yaml +7 -0
  36. package/dist/templates/getdotenv.config.ts +28 -0
  37. package/dist/templates/getdotenv.config.yaml +7 -0
  38. package/dist/templates/hello.ts +43 -0
  39. package/dist/templates/index.ts +26 -0
  40. package/dist/templates/js/getdotenv.config.js +20 -0
  41. package/dist/templates/json/local/getdotenv.config.local.json +7 -0
  42. package/dist/templates/json/public/getdotenv.config.json +9 -0
  43. package/dist/templates/local/getdotenv.config.local.json +7 -0
  44. package/dist/templates/local/getdotenv.config.local.yaml +7 -0
  45. package/dist/templates/plugins/hello.ts +43 -0
  46. package/dist/templates/public/getdotenv.config.json +9 -0
  47. package/dist/templates/public/getdotenv.config.yaml +7 -0
  48. package/dist/templates/ts/getdotenv.config.ts +28 -0
  49. package/dist/templates/yaml/local/getdotenv.config.local.yaml +7 -0
  50. package/dist/templates/yaml/public/getdotenv.config.yaml +7 -0
  51. package/getdotenv.config.json +1 -19
  52. package/package.json +52 -89
  53. package/templates/cli/index.ts +26 -0
  54. package/templates/cli/plugins/hello.ts +43 -0
  55. package/templates/config/js/getdotenv.config.js +9 -4
  56. package/templates/config/json/public/getdotenv.config.json +0 -3
  57. package/templates/config/public/getdotenv.config.json +0 -5
  58. package/templates/config/ts/getdotenv.config.ts +17 -5
  59. package/templates/config/yaml/public/getdotenv.config.yaml +0 -3
  60. package/dist/cliHost.cjs +0 -2078
  61. package/dist/cliHost.d.cts +0 -451
  62. package/dist/cliHost.d.mts +0 -451
  63. package/dist/config.cjs +0 -252
  64. package/dist/config.d.cts +0 -55
  65. package/dist/config.d.mts +0 -55
  66. package/dist/env-overlay.cjs +0 -163
  67. package/dist/env-overlay.d.cts +0 -50
  68. package/dist/env-overlay.d.mts +0 -50
  69. package/dist/index.cjs +0 -4077
  70. package/dist/index.d.cts +0 -318
  71. package/dist/index.d.mts +0 -318
  72. package/dist/plugins-aws.cjs +0 -666
  73. package/dist/plugins-aws.d.cts +0 -158
  74. package/dist/plugins-aws.d.mts +0 -158
  75. package/dist/plugins-batch.cjs +0 -658
  76. package/dist/plugins-batch.d.cts +0 -181
  77. package/dist/plugins-batch.d.mts +0 -181
  78. package/dist/plugins-cmd.cjs +0 -1112
  79. package/dist/plugins-cmd.d.cts +0 -178
  80. package/dist/plugins-cmd.d.mts +0 -178
  81. package/dist/plugins-demo.cjs +0 -352
  82. package/dist/plugins-demo.d.cts +0 -158
  83. package/dist/plugins-demo.d.mts +0 -158
  84. package/dist/plugins-demo.d.ts +0 -158
  85. package/dist/plugins-demo.mjs +0 -350
  86. package/dist/plugins-init.cjs +0 -289
  87. package/dist/plugins-init.d.cts +0 -162
  88. package/dist/plugins-init.d.mts +0 -162
  89. package/dist/plugins.cjs +0 -2327
  90. package/dist/plugins.d.cts +0 -211
  91. package/dist/plugins.d.mts +0 -211
  92. package/templates/cli/ts/index.ts +0 -9
  93. package/templates/cli/ts/plugins/hello.ts +0 -17
@@ -1,1112 +0,0 @@
1
- 'use strict';
2
-
3
- var execa = require('execa');
4
- require('fs-extra');
5
- require('package-directory');
6
- require('path');
7
-
8
- // Minimal tokenizer for shell-off execution:
9
- // Splits by whitespace while preserving quoted segments (single or double quotes).
10
- const tokenize = (command) => {
11
- const out = [];
12
- let cur = '';
13
- let quote = null;
14
- for (let i = 0; i < command.length; i++) {
15
- const c = command.charAt(i);
16
- if (quote) {
17
- if (c === quote) {
18
- // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
19
- // "" -> " and '' -> '
20
- const next = command.charAt(i + 1);
21
- if (next === quote) {
22
- cur += quote;
23
- i += 1; // skip the second quote
24
- }
25
- else {
26
- // end of quoted segment
27
- quote = null;
28
- }
29
- }
30
- else {
31
- cur += c;
32
- }
33
- }
34
- else {
35
- if (c === '"' || c === "'") {
36
- quote = c;
37
- }
38
- else if (/\s/.test(c)) {
39
- if (cur) {
40
- out.push(cur);
41
- cur = '';
42
- }
43
- }
44
- else {
45
- cur += c;
46
- }
47
- }
48
- }
49
- if (cur)
50
- out.push(cur);
51
- return out;
52
- };
53
-
54
- const dbg$1 = (...args) => {
55
- if (process.env.GETDOTENV_DEBUG) {
56
- // Use stderr to avoid interfering with stdout assertions
57
- console.error('[getdotenv:run]', ...args);
58
- }
59
- };
60
- // Strip repeated symmetric outer quotes (single or double) until stable.
61
- // This is safe for argv arrays passed to execa (no quoting needed) and avoids
62
- // passing quote characters through to Node (e.g., for `node -e "<code>"`).
63
- // Handles stacked quotes from shells like PowerShell: """code""" -> code.
64
- const stripOuterQuotes = (s) => {
65
- let out = s;
66
- // Repeatedly trim only when the entire string is wrapped in matching quotes.
67
- // Stop as soon as the ends are asymmetric or no quotes remain.
68
- while (out.length >= 2) {
69
- const a = out.charAt(0);
70
- const b = out.charAt(out.length - 1);
71
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
72
- if (!symmetric)
73
- break;
74
- out = out.slice(1, -1);
75
- }
76
- return out;
77
- };
78
- // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
79
- // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
80
- const sanitizeEnv = (env) => {
81
- if (!env)
82
- return undefined;
83
- const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
84
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
85
- };
86
- const runCommand = async (command, shell, opts) => {
87
- if (shell === false) {
88
- let file;
89
- let args = [];
90
- if (Array.isArray(command)) {
91
- file = command[0];
92
- args = command.slice(1).map(stripOuterQuotes);
93
- }
94
- else {
95
- const tokens = tokenize(command);
96
- file = tokens[0];
97
- args = tokens.slice(1);
98
- }
99
- if (!file)
100
- return 0;
101
- dbg$1('exec (plain)', { file, args, stdio: opts.stdio });
102
- // Build options without injecting undefined properties (exactOptionalPropertyTypes).
103
- const envSan = sanitizeEnv(opts.env);
104
- const plainOpts = {};
105
- if (opts.cwd !== undefined)
106
- plainOpts.cwd = opts.cwd;
107
- if (envSan !== undefined)
108
- plainOpts.env = envSan;
109
- if (opts.stdio !== undefined)
110
- plainOpts.stdio = opts.stdio;
111
- const result = await execa.execa(file, args, plainOpts);
112
- if (opts.stdio === 'pipe' && result.stdout) {
113
- process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
114
- }
115
- const exit = result?.exitCode;
116
- dbg$1('exit (plain)', { exitCode: exit });
117
- return typeof exit === 'number' ? exit : Number.NaN;
118
- }
119
- else {
120
- const commandStr = Array.isArray(command) ? command.join(' ') : command;
121
- dbg$1('exec (shell)', {
122
- shell: typeof shell === 'string' ? shell : 'custom',
123
- stdio: opts.stdio,
124
- command: commandStr,
125
- });
126
- const envSan = sanitizeEnv(opts.env);
127
- const shellOpts = { shell };
128
- if (opts.cwd !== undefined)
129
- shellOpts.cwd = opts.cwd;
130
- if (envSan !== undefined)
131
- shellOpts.env = envSan;
132
- if (opts.stdio !== undefined)
133
- shellOpts.stdio = opts.stdio;
134
- const result = await execa.execaCommand(commandStr, shellOpts);
135
- const out = result?.stdout;
136
- if (opts.stdio === 'pipe' && out) {
137
- process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
138
- }
139
- const exit = result?.exitCode;
140
- dbg$1('exit (shell)', { exitCode: exit });
141
- return typeof exit === 'number' ? exit : Number.NaN;
142
- }
143
- };
144
-
145
- const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
146
- /** Build a sanitized env for child processes from base + overlay. */
147
- const buildSpawnEnv = (base, overlay) => {
148
- const raw = {
149
- ...(base ?? {}),
150
- ...(overlay ?? {}),
151
- };
152
- // Drop undefined first
153
- const entries = Object.entries(dropUndefined(raw));
154
- if (process.platform === 'win32') {
155
- // Windows: keys are case-insensitive; collapse duplicates
156
- const byLower = new Map();
157
- for (const [k, v] of entries) {
158
- byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
159
- }
160
- const out = {};
161
- for (const [, [k, v]] of byLower)
162
- out[k] = v;
163
- // HOME fallback from USERPROFILE (common expectation)
164
- if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
165
- const up = out['USERPROFILE'];
166
- if (typeof up === 'string' && up.length > 0)
167
- out['HOME'] = up;
168
- }
169
- // Normalize TMP/TEMP coherence (pick any present; reflect to both)
170
- const tmp = out['TMP'] ?? out['TEMP'];
171
- if (typeof tmp === 'string' && tmp.length > 0) {
172
- out['TMP'] = tmp;
173
- out['TEMP'] = tmp;
174
- }
175
- return out;
176
- }
177
- // POSIX: keep keys as-is
178
- const out = Object.fromEntries(entries);
179
- // Ensure TMPDIR exists when any temp key is present (best-effort)
180
- const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
181
- if (typeof tmpdir === 'string' && tmpdir.length > 0) {
182
- out['TMPDIR'] = tmpdir;
183
- }
184
- return out;
185
- };
186
-
187
- /** src/cliHost/definePlugin.ts
188
- * Plugin contracts for the GetDotenv CLI host.
189
- *
190
- * This module exposes a structural public interface for the host that plugins
191
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
192
- * nominal class identity issues (private fields) in downstream consumers.
193
- */
194
- /**
195
- * Define a GetDotenv CLI plugin with compositional helpers.
196
- *
197
- * @example
198
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
199
- * .use(childA)
200
- * .use(childB);
201
- */
202
- const definePlugin = (spec) => {
203
- const { children = [], ...rest } = spec;
204
- const plugin = {
205
- ...rest,
206
- children: [...children],
207
- use(child) {
208
- this.children.push(child);
209
- return this;
210
- },
211
- };
212
- return plugin;
213
- };
214
-
215
- /** src/diagnostics/entropy.ts
216
- * Entropy diagnostics (presentation-only).
217
- * - Gated by min length and printable ASCII.
218
- * - Warn once per key per run when bits/char \>= threshold.
219
- * - Supports whitelist patterns to suppress known-noise keys.
220
- */
221
- const warned = new Set();
222
- const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
223
- const compile$1 = (patterns) => (patterns ?? []).map((p) => new RegExp(p, 'i'));
224
- const whitelisted = (key, regs) => regs.some((re) => re.test(key));
225
- const shannonBitsPerChar = (s) => {
226
- const freq = new Map();
227
- for (const ch of s)
228
- freq.set(ch, (freq.get(ch) ?? 0) + 1);
229
- const n = s.length;
230
- let h = 0;
231
- for (const c of freq.values()) {
232
- const p = c / n;
233
- h -= p * Math.log2(p);
234
- }
235
- return h;
236
- };
237
- /**
238
- * Maybe emit a one-line entropy warning for a key.
239
- * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
240
- */
241
- const maybeWarnEntropy = (key, value, origin, opts, emit) => {
242
- if (!opts || opts.warnEntropy === false)
243
- return;
244
- if (warned.has(key))
245
- return;
246
- const v = value ?? '';
247
- const minLen = Math.max(0, opts.entropyMinLength ?? 16);
248
- const threshold = opts.entropyThreshold ?? 3.8;
249
- if (v.length < minLen)
250
- return;
251
- if (!isPrintableAscii(v))
252
- return;
253
- const wl = compile$1(opts.entropyWhitelist);
254
- if (whitelisted(key, wl))
255
- return;
256
- const bpc = shannonBitsPerChar(v);
257
- if (bpc >= threshold) {
258
- warned.add(key);
259
- emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
260
- }
261
- };
262
-
263
- const DEFAULT_PATTERNS = [
264
- '\\bsecret\\b',
265
- '\\btoken\\b',
266
- '\\bpass(word)?\\b',
267
- '\\bapi[_-]?key\\b',
268
- '\\bkey\\b',
269
- ];
270
- const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
271
- const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
272
- const MASK = '[redacted]';
273
- /**
274
- * Utility to redact three related displayed values (parent/dotenv/final)
275
- * consistently for trace lines.
276
- */
277
- const redactTriple = (key, triple, opts) => {
278
- if (!opts?.redact)
279
- return triple;
280
- const regs = compile(opts.redactPatterns);
281
- const maskIf = (v) => (v && shouldRedactKey(key, regs) ? MASK : v);
282
- const out = {};
283
- const p = maskIf(triple.parent);
284
- const d = maskIf(triple.dotenv);
285
- const f = maskIf(triple.final);
286
- if (p !== undefined)
287
- out.parent = p;
288
- if (d !== undefined)
289
- out.dotenv = d;
290
- if (f !== undefined)
291
- out.final = f;
292
- return out;
293
- };
294
-
295
- /**
296
- * Batch services (neutral): resolve command and shell settings.
297
- * Shared by the generator path and the batch plugin to avoid circular deps.
298
- */
299
- /**
300
- * Resolve a command string from the {@link Scripts} table.
301
- * A script may be expressed as a string or an object with a `cmd` property.
302
- *
303
- * @param scripts - Optional scripts table.
304
- * @param command - User-provided command name or string.
305
- * @returns Resolved command string (falls back to the provided command).
306
- */
307
- const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
308
- ? scripts[command].cmd
309
- : (scripts?.[command] ?? command);
310
- /**
311
- * Resolve the shell setting for a given command:
312
- * - If the script entry is an object, prefer its `shell` override.
313
- * - Otherwise use the provided `shell` (string | boolean).
314
- *
315
- * @param scripts - Optional scripts table.
316
- * @param command - User-provided command name or string.
317
- * @param shell - Global shell preference (string | boolean).
318
- */
319
- const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
320
- ? (scripts[command].shell ?? false)
321
- : (shell ?? false);
322
-
323
- // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
324
- const baseRootOptionDefaults = {
325
- dotenvToken: '.env',
326
- loadProcess: true,
327
- logger: console,
328
- // Diagnostics defaults
329
- warnEntropy: true,
330
- entropyThreshold: 3.8,
331
- entropyMinLength: 16,
332
- entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
333
- paths: './',
334
- pathsDelimiter: ' ',
335
- privateToken: 'local',
336
- scripts: {
337
- 'git-status': {
338
- cmd: 'git branch --show-current && git status -s -u',
339
- shell: true,
340
- },
341
- },
342
- shell: true,
343
- vars: '',
344
- varsAssignor: '=',
345
- varsDelimiter: ' ',
346
- // tri-state flags default to unset unless explicitly provided
347
- // (debug/log/exclude* resolved via flag utils)
348
- };
349
-
350
- /** @internal */
351
- const isPlainObject = (value) => value !== null &&
352
- typeof value === 'object' &&
353
- Object.getPrototypeOf(value) === Object.prototype;
354
- const mergeInto = (target, source) => {
355
- for (const [key, sVal] of Object.entries(source)) {
356
- if (sVal === undefined)
357
- continue; // do not overwrite with undefined
358
- const tVal = target[key];
359
- if (isPlainObject(tVal) && isPlainObject(sVal)) {
360
- target[key] = mergeInto({ ...tVal }, sVal);
361
- }
362
- else if (isPlainObject(sVal)) {
363
- target[key] = mergeInto({}, sVal);
364
- }
365
- else {
366
- target[key] = sVal;
367
- }
368
- }
369
- return target;
370
- };
371
- /**
372
- * Perform a deep defaults-style merge across plain objects. *
373
- * - Only merges plain objects (prototype === Object.prototype).
374
- * - Arrays and non-objects are replaced, not merged.
375
- * - `undefined` values are ignored and do not overwrite prior values.
376
- *
377
- * @typeParam T - The resulting shape after merging all layers.
378
- * @param layers - Zero or more partial layers in ascending precedence order.
379
- * @returns The merged object typed as {@link T}.
380
- *
381
- * @example
382
- * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
383
- * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
384
- */
385
- const defaultsDeep = (...layers) => {
386
- const result = layers
387
- .filter(Boolean)
388
- .reduce((acc, layer) => mergeInto(acc, layer), {});
389
- return result;
390
- };
391
-
392
- /**
393
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
394
- * - If the user explicitly enabled the flag, return true.
395
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
396
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
397
- *
398
- * @param exclude - The "on" flag value as parsed by Commander.
399
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
400
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
401
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
402
- *
403
- * @example
404
- * ```ts
405
- * resolveExclusion(undefined, undefined, true); // => true
406
- * ```
407
- */
408
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
409
- /**
410
- * Resolve an optional flag with "--exclude-all" overrides.
411
- * If excludeAll is set and the individual "...-off" is not, force true.
412
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
413
- * Otherwise, adopt the default (true → set; false/undefined → unset).
414
- *
415
- * @param exclude - Individual include/exclude flag.
416
- * @param excludeOff - Individual "...-off" flag.
417
- * @param defaultValue - Default for the individual flag.
418
- * @param excludeAll - Global "exclude-all" flag.
419
- * @param excludeAllOff - Global "exclude-all-off" flag.
420
- *
421
- * @example
422
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
423
- */
424
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
425
- // Order of precedence:
426
- // 1) Individual explicit "on" wins outright.
427
- // 2) Individual explicit "off" wins over any global.
428
- // 3) Global exclude-all forces true when not explicitly turned off.
429
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
430
- // 5) Fall back to the default (true => set; false/undefined => unset).
431
- (() => {
432
- // Individual "on"
433
- if (exclude === true)
434
- return true;
435
- // Individual "off"
436
- if (excludeOff === true)
437
- return undefined;
438
- // Global "exclude-all" ON (unless explicitly turned off)
439
- if (excludeAll === true)
440
- return true;
441
- // Global "exclude-all-off" (unless explicitly enabled)
442
- if (excludeAllOff === true)
443
- return undefined;
444
- // Default
445
- return defaultValue ? true : undefined;
446
- })();
447
- /**
448
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
449
- * delete when undefined; assign when defined — without requiring an index signature on T.
450
- *
451
- * @typeParam T - Target object type.
452
- * @param obj - The object to write to.
453
- * @param key - The optional boolean property key of {@link T}.
454
- * @param value - The value to set or `undefined` to unset.
455
- *
456
- * @remarks
457
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
458
- */
459
- const setOptionalFlag = (obj, key, value) => {
460
- const target = obj;
461
- const k = key;
462
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
463
- if (value === undefined)
464
- delete target[k];
465
- else
466
- target[k] = value;
467
- };
468
-
469
- /**
470
- * Merge and normalize raw Commander options (current + parent + defaults)
471
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
472
- * avoid cross-layer coupling; callers may cast as needed.
473
- */
474
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
475
- const parent = typeof parentJson === 'string' && parentJson.length > 0
476
- ? JSON.parse(parentJson)
477
- : undefined;
478
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
479
- const current = { ...rest };
480
- if (typeof scripts === 'string') {
481
- try {
482
- current.scripts = JSON.parse(scripts);
483
- }
484
- catch {
485
- // ignore parse errors; leave scripts undefined
486
- }
487
- }
488
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
489
- const d = defaults;
490
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
491
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
492
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
493
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
494
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
495
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
496
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
497
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
498
- // warnEntropy (tri-state)
499
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
500
- // Normalize shell for predictability: explicit default shell per OS.
501
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
502
- let resolvedShell = merged.shell;
503
- if (shellOff)
504
- resolvedShell = false;
505
- else if (resolvedShell === true || resolvedShell === undefined) {
506
- resolvedShell = defaultShell;
507
- }
508
- else if (typeof resolvedShell !== 'string' &&
509
- typeof defaults.shell === 'string') {
510
- resolvedShell = defaults.shell;
511
- }
512
- merged.shell = resolvedShell;
513
- const cmd = typeof command === 'string' ? command : undefined;
514
- return cmd !== undefined ? { merged, command: cmd } : { merged };
515
- };
516
-
517
- /**
518
- * Dotenv expansion utilities.
519
- *
520
- * This module implements recursive expansion of environment-variable
521
- * references in strings and records. It supports both whitespace and
522
- * bracket syntaxes with optional defaults:
523
- *
524
- * - Whitespace: `$VAR[:default]`
525
- * - Bracketed: `${VAR[:default]}`
526
- *
527
- * Escaped dollar signs (`\$`) are preserved.
528
- * Unknown variables resolve to empty string unless a default is provided.
529
- */
530
- /**
531
- * Like String.prototype.search but returns the last index.
532
- * @internal
533
- */
534
- const searchLast = (str, rgx) => {
535
- const matches = Array.from(str.matchAll(rgx));
536
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
537
- };
538
- const replaceMatch = (value, match, ref) => {
539
- /**
540
- * @internal
541
- */
542
- const group = match[0];
543
- const key = match[1];
544
- const defaultValue = match[2];
545
- if (!key)
546
- return value;
547
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
548
- return interpolate(replacement, ref);
549
- };
550
- const interpolate = (value = '', ref = {}) => {
551
- /**
552
- * @internal
553
- */
554
- // if value is falsy, return it as is
555
- if (!value)
556
- return value;
557
- // get position of last unescaped dollar sign
558
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
559
- // return value if none found
560
- if (lastUnescapedDollarSignIndex === -1)
561
- return value;
562
- // evaluate the value tail
563
- const tail = value.slice(lastUnescapedDollarSignIndex);
564
- // find whitespace pattern: $KEY:DEFAULT
565
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
566
- const whitespaceMatch = whitespacePattern.exec(tail);
567
- if (whitespaceMatch != null)
568
- return replaceMatch(value, whitespaceMatch, ref);
569
- else {
570
- // find bracket pattern: ${KEY:DEFAULT}
571
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
572
- const bracketMatch = bracketPattern.exec(tail);
573
- if (bracketMatch != null)
574
- return replaceMatch(value, bracketMatch, ref);
575
- }
576
- return value;
577
- };
578
- /**
579
- * Recursively expands environment variables in a string. Variables may be
580
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
581
- * Unknown variables will expand to an empty string.
582
- *
583
- * @param value - The string to expand.
584
- * @param ref - The reference object to use for variable expansion.
585
- * @returns The expanded string.
586
- *
587
- * @example
588
- * ```ts
589
- * process.env.FOO = 'bar';
590
- * dotenvExpand('Hello $FOO'); // "Hello bar"
591
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
592
- * ```
593
- *
594
- * @remarks
595
- * The expansion is recursive. If a referenced variable itself contains
596
- * references, those will also be expanded until a stable value is reached.
597
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
598
- */
599
- const dotenvExpand = (value, ref = process.env) => {
600
- const result = interpolate(value, ref);
601
- return result ? result.replace(/\\\$/g, '$') : undefined;
602
- };
603
- /**
604
- * Recursively expands environment variables in a string using `process.env` as
605
- * the expansion reference. Variables may be presented with optional default as
606
- * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
607
- * empty string.
608
- *
609
- * @param value - The string to expand.
610
- * @returns The expanded string.
611
- *
612
- * @example
613
- * ```ts
614
- * process.env.FOO = 'bar';
615
- * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
616
- * ```
617
- */
618
- const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
619
-
620
- // src/GetDotenvOptions.ts
621
- /**
622
- * Converts programmatic CLI options to `getDotenv` options. *
623
- * @param cliOptions - CLI options. Defaults to `{}`.
624
- *
625
- * @returns `getDotenv` options.
626
- */
627
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
628
- /**
629
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
630
- *
631
- * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
632
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
633
- * - Drops CLI-only keys that have no programmatic equivalent.
634
- *
635
- * @remarks
636
- * Follows exact-optional semantics by not emitting undefined-valued entries.
637
- */
638
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
639
- // Create a shallow copy then delete optional CLI-only keys if present.
640
- const restObj = { ...rest };
641
- delete restObj.debug;
642
- delete restObj.scripts;
643
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
644
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
645
- let parsedVars;
646
- if (typeof vars === 'string') {
647
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
648
- ? RegExp(varsAssignorPattern)
649
- : (varsAssignor ?? '=')));
650
- parsedVars = Object.fromEntries(kvPairs);
651
- }
652
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
653
- // Keep only string or undefined values to match ProcessEnv.
654
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
655
- parsedVars = Object.fromEntries(entries);
656
- }
657
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
658
- // expectations and the compat test assertions.
659
- if (parsedVars) {
660
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
661
- }
662
- // Tolerate paths as either a delimited string or string[]
663
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
664
- // under the RootOptionsShape (which declares paths as string | undefined).
665
- const pathsAny = paths;
666
- const pathsOut = Array.isArray(pathsAny)
667
- ? pathsAny.filter((p) => typeof p === 'string')
668
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
669
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
670
- return {
671
- ...restObj,
672
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
673
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
674
- };
675
- };
676
-
677
- const dbg = (...args) => {
678
- if (process.env.GETDOTENV_DEBUG) {
679
- // Use stderr to avoid interfering with stdout assertions
680
- console.error('[getdotenv:alias]', ...args);
681
- }
682
- };
683
- const attachParentAlias = (cli, options, _cmd) => {
684
- const aliasSpec = typeof options.optionAlias === 'string'
685
- ? { flags: options.optionAlias, description: undefined, expand: true }
686
- : options.optionAlias;
687
- if (!aliasSpec)
688
- return;
689
- const deriveKey = (flags) => {
690
- dbg('install alias option', flags);
691
- const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
692
- const name = long.replace(/^--/, '');
693
- return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
694
- };
695
- const aliasKey = deriveKey(aliasSpec.flags);
696
- // Expose the option on the parent.
697
- const desc = aliasSpec.description ??
698
- 'alias of cmd subcommand; provide command tokens (variadic)';
699
- cli.option(aliasSpec.flags, desc);
700
- // Tag the just-added parent option for grouped help rendering.
701
- try {
702
- const optsArr = cli.options;
703
- if (Array.isArray(optsArr) && optsArr.length > 0) {
704
- const last = optsArr[optsArr.length - 1];
705
- last.__group = 'plugin:cmd';
706
- }
707
- }
708
- catch {
709
- /* noop */
710
- }
711
- // Shared alias executor for either preAction or preSubcommand hooks.
712
- // Ensure we only execute once even if both hooks fire in a single parse.
713
- let aliasHandled = false;
714
- const maybeRunAlias = async (thisCommand) => {
715
- dbg('alias:maybe:start');
716
- const raw = thisCommand.rawArgs ?? [];
717
- const childNames = thisCommand.commands.flatMap((c) => [
718
- c.name(),
719
- ...c.aliases(),
720
- ]);
721
- const hasSub = childNames.some((n) => raw.includes(n));
722
- // Read alias value from parent opts.
723
- const o = thisCommand.opts();
724
- const val = o[aliasKey];
725
- const provided = typeof val === 'string'
726
- ? val.length > 0
727
- : Array.isArray(val)
728
- ? val.length > 0
729
- : false;
730
- if (!provided || hasSub) {
731
- dbg('alias:maybe:skip', { provided, hasSub });
732
- return; // not an alias-only invocation
733
- }
734
- if (aliasHandled) {
735
- dbg('alias:maybe:already-handled');
736
- return;
737
- }
738
- aliasHandled = true;
739
- dbg('alias-only invocation detected');
740
- // Merge CLI options and resolve dotenv context.
741
- const { merged } = resolveCliOptions(o,
742
- // cast through unknown to avoid readonly -> mutable incompatibilities
743
- baseRootOptionDefaults, process.env.getDotenvCliOptions);
744
- const logger = merged.logger ?? console;
745
- const serviceOptions = getDotenvCliOptions2Options(merged);
746
- await cli.resolveAndLoad(serviceOptions);
747
- // Normalize alias value.
748
- const joined = typeof val === 'string'
749
- ? val
750
- : Array.isArray(val)
751
- ? val.map(String).join(' ')
752
- : '';
753
- const input = aliasSpec.expand === false
754
- ? joined
755
- : (dotenvExpandFromProcessEnv(joined) ?? joined);
756
- dbg('resolved input', { input });
757
- const resolved = resolveCommand(merged.scripts, input);
758
- const lg = logger;
759
- if (merged.debug) {
760
- (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
761
- }
762
- const { logger: _omit, ...envBag } = merged;
763
- // Test guard: when running under tests, prefer stdio: 'inherit' to avoid
764
- // assertions depending on captured stdio; ignore GETDOTENV_STDIO/capture.
765
- const underTests = process.env.GETDOTENV_TEST === '1' ||
766
- typeof process.env.VITEST_WORKER_ID === 'string';
767
- const forceExit = process.env.GETDOTENV_FORCE_EXIT === '1';
768
- const capture = !underTests &&
769
- (process.env.GETDOTENV_STDIO === 'pipe' ||
770
- Boolean(merged.capture));
771
- dbg('run:start', { capture, shell: merged.shell });
772
- // Prefer explicit env injection: include resolved dotenv map to avoid leaking
773
- // parent process.env secrets when exclusions are set.
774
- const ctx = cli.getCtx();
775
- const dotenv = (ctx?.dotenv ?? {});
776
- // Diagnostics: --trace [keys...]
777
- const traceOpt = merged.trace;
778
- if (traceOpt) {
779
- const parentKeys = Object.keys(process.env);
780
- const dotenvKeys = Object.keys(dotenv);
781
- const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
782
- const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
783
- const childEnvPreview = {
784
- ...process.env,
785
- ...dotenv,
786
- };
787
- for (const k of keys) {
788
- const parent = process.env[k];
789
- const dot = dotenv[k];
790
- const final = childEnvPreview[k];
791
- const origin = dot !== undefined
792
- ? 'dotenv'
793
- : parent !== undefined
794
- ? 'parent'
795
- : 'unset';
796
- // Build redact options and triple bag without undefined-valued fields
797
- const redOpts = {};
798
- const redFlag = merged.redact;
799
- const redPatterns = merged
800
- .redactPatterns;
801
- if (redFlag)
802
- redOpts.redact = true;
803
- if (redFlag && Array.isArray(redPatterns))
804
- redOpts.redactPatterns = redPatterns;
805
- const tripleBag = {};
806
- if (parent !== undefined)
807
- tripleBag.parent = parent;
808
- if (dot !== undefined)
809
- tripleBag.dotenv = dot;
810
- if (final !== undefined)
811
- tripleBag.final = final;
812
- const triple = redactTriple(k, tripleBag, redOpts);
813
- process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
814
- const entOpts = {};
815
- const warnEntropy = merged.warnEntropy;
816
- const entropyThreshold = merged
817
- .entropyThreshold;
818
- const entropyMinLength = merged
819
- .entropyMinLength;
820
- const entropyWhitelist = merged
821
- .entropyWhitelist;
822
- if (typeof warnEntropy === 'boolean')
823
- entOpts.warnEntropy = warnEntropy;
824
- if (typeof entropyThreshold === 'number')
825
- entOpts.entropyThreshold = entropyThreshold;
826
- if (typeof entropyMinLength === 'number')
827
- entOpts.entropyMinLength = entropyMinLength;
828
- if (Array.isArray(entropyWhitelist))
829
- entOpts.entropyWhitelist = entropyWhitelist;
830
- maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
831
- }
832
- }
833
- let exitCode = Number.NaN;
834
- try {
835
- // Resolve shell and preserve argv for Node -e snippets under shell-off.
836
- const shellSetting = resolveShell(merged.scripts, input, merged.shell);
837
- let commandArg = resolved;
838
- /** * Special-case: when shell is OFF and no script alias remap occurred
839
- * (resolved === input), treat a Node eval payload as an argv array to
840
- * avoid lossy re-tokenization of the code string.
841
- *
842
- * Examples handled:
843
- * "node -e \"console.log(JSON.stringify(...))\""
844
- * "node --eval 'console.log(...)'"
845
- *
846
- * We peel exactly one pair of symmetric outer quotes from the code
847
- * argument when present; inner quotes remain untouched.
848
- */
849
- if (shellSetting === false && resolved === input) {
850
- // Helper: strip one symmetric outer quote layer
851
- const stripOne = (s) => {
852
- if (s.length < 2)
853
- return s;
854
- const a = s.charAt(0);
855
- const b = s.charAt(s.length - 1);
856
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
857
- return symmetric ? s.slice(1, -1) : s;
858
- };
859
- // Normalize whole input once for robust matching
860
- const normalized = stripOne(input.trim());
861
- // First try a lightweight regex on the normalized string
862
- const m = /^\s*node\s+(--eval|-e)\s+([\s\S]+)$/i.exec(normalized);
863
- if (m && typeof m[1] === 'string' && typeof m[2] === 'string') {
864
- const evalFlag = m[1];
865
- let codeArg = m[2].trim();
866
- codeArg = stripOne(codeArg);
867
- const flag = evalFlag.startsWith('--') ? '--eval' : '-e';
868
- commandArg = ['node', flag, codeArg];
869
- }
870
- else {
871
- // Fallback: tokenize and detect node -e/--eval form
872
- const parts = tokenize(input);
873
- if (parts.length >= 3) {
874
- // Narrow under noUncheckedIndexedAccess
875
- const p0 = parts[0];
876
- const p1 = parts[1];
877
- if (p0?.toLowerCase() === 'node' &&
878
- (p1 === '-e' || p1 === '--eval')) {
879
- commandArg = parts;
880
- }
881
- }
882
- }
883
- }
884
- exitCode = await runCommand(commandArg, shellSetting, {
885
- env: buildSpawnEnv(process.env, {
886
- ...dotenv,
887
- getDotenvCliOptions: JSON.stringify(envBag),
888
- }),
889
- stdio: capture ? 'pipe' : 'inherit',
890
- });
891
- dbg('run:done', { exitCode });
892
- }
893
- catch (err) {
894
- const code = typeof err.exitCode === 'number'
895
- ? err.exitCode
896
- : 1;
897
- dbg('run:error', { exitCode: code, error: String(err) });
898
- if (!underTests) {
899
- dbg('process.exit (error path)', { exitCode: code });
900
- process.exit(code);
901
- }
902
- else {
903
- dbg('process.exit suppressed for tests (error path)', {
904
- exitCode: code,
905
- });
906
- }
907
- return;
908
- }
909
- if (!Number.isNaN(exitCode)) {
910
- dbg('process.exit', { exitCode });
911
- process.exit(exitCode);
912
- }
913
- // Fallback: Some environments may not surface a numeric exitCode even on success.
914
- // Always terminate alias-only invocations outside tests to avoid hanging the process,
915
- // regardless of capture/GETDOTENV_STDIO. Under tests, suppress to keep the runner alive.
916
- if (!underTests) {
917
- dbg('process.exit (fallback: non-numeric exitCode)', { exitCode: 0 });
918
- process.exit(0);
919
- }
920
- else {
921
- dbg('process.exit (fallback suppressed for tests: non-numeric exitCode)', { exitCode: 0 });
922
- }
923
- // Optional last-resort guard: force an exit on the next tick when enabled.
924
- // Intended for diagnosing environments where the process appears to linger
925
- // despite reaching the success/error handlers above. Disabled under tests.
926
- if (forceExit) {
927
- try {
928
- if (process.env.GETDOTENV_DEBUG_VERBOSE) {
929
- const getHandles = process._getActiveHandles;
930
- const handles = typeof getHandles === 'function' ? getHandles() : [];
931
- dbg('active handles before forced exit', {
932
- count: Array.isArray(handles) ? handles.length : undefined,
933
- });
934
- }
935
- }
936
- catch {
937
- // best-effort only
938
- }
939
- const code = Number.isNaN(exitCode) ? 0 : exitCode;
940
- dbg('process.exit (forced)', { exitCode: code });
941
- setImmediate(() => process.exit(code));
942
- }
943
- };
944
- // Execute alias-only invocations whether the root handles the action // itself (preAction) or Commander routes to a default subcommand (preSubcommand).
945
- cli.hook('preAction', async (thisCommand, _actionCommand) => {
946
- await maybeRunAlias(thisCommand);
947
- });
948
- cli.hook('preSubcommand', async (thisCommand) => {
949
- await maybeRunAlias(thisCommand);
950
- });
951
- };
952
-
953
- /**+ Cmd plugin: executes a command using the current getdotenv CLI context.
954
- *
955
- * - Joins positional args into a single command string.
956
- * - Resolves scripts and shell settings using shared helpers.
957
- * - Forwards merged CLI options to subprocesses via
958
- * process.env.getDotenvCliOptions for nested CLI behavior. */
959
- const cmdPlugin = (options = {}) => definePlugin({
960
- id: 'cmd',
961
- setup(cli) {
962
- const aliasSpec = typeof options.optionAlias === 'string'
963
- ? { flags: options.optionAlias}
964
- : options.optionAlias;
965
- const deriveKey = (flags) => {
966
- const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
967
- const name = long.replace(/^--/, '');
968
- return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
969
- };
970
- const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
971
- // Create as a GetDotenvCli child so helpInformation includes a trailing blank line.
972
- const cmd = cli
973
- .createCommand('cmd')
974
- .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
975
- .enablePositionalOptions()
976
- .passThroughOptions()
977
- .argument('[command...]')
978
- .action(async (commandParts, _opts, thisCommand) => {
979
- // Commander passes positional tokens as the first action argument
980
- const args = Array.isArray(commandParts) ? commandParts : [];
981
- // No-op when invoked as the default command with no args.
982
- if (args.length === 0)
983
- return;
984
- const parent = thisCommand.parent;
985
- if (!parent)
986
- throw new Error('parent command not found'); // Conflict detection: if an alias option is present on parent, do not
987
- // also accept positional cmd args.
988
- if (aliasKey) {
989
- const pv = parent.opts();
990
- const ov = pv[aliasKey];
991
- if (ov !== undefined) {
992
- const merged = parent.getDotenvCliOptions ?? {};
993
- const logger = merged.logger ?? console;
994
- const lr = logger;
995
- const emit = lr.error ?? lr.log;
996
- emit(`--${aliasKey} option conflicts with cmd subcommand.`);
997
- process.exit(0);
998
- }
999
- }
1000
- // Merged CLI options are persisted by the shipped CLI preSubcommand hook.
1001
- const merged = parent.getDotenvCliOptions ?? {};
1002
- const logger = merged.logger ?? console;
1003
- // Join positional args into the command string.
1004
- const input = args.map(String).join(' ');
1005
- // Resolve command and shell using shared helpers.
1006
- const scripts = merged.scripts;
1007
- const shell = merged.shell;
1008
- const resolved = resolveCommand(scripts, input);
1009
- if (merged.debug) {
1010
- const lg = logger;
1011
- (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
1012
- }
1013
- // Round-trip CLI options for nested getdotenv invocations.
1014
- // Omit logger (functions are not serializable).
1015
- const { logger: _omit, ...envBag } = merged;
1016
- const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
1017
- Boolean(merged.capture);
1018
- // Prefer explicit env injection using the resolved dotenv map.
1019
- const ctx = cli.getCtx();
1020
- const dotenv = (ctx?.dotenv ?? {});
1021
- // Diagnostics: --trace [keys...] (space-delimited keys if provided; all keys when true)
1022
- const traceOpt = merged.trace;
1023
- if (traceOpt) {
1024
- // Determine keys to trace: all keys (parent ∪ dotenv) or selected.
1025
- const parentKeys = Object.keys(process.env);
1026
- const dotenvKeys = Object.keys(dotenv);
1027
- const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
1028
- const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
1029
- // Child env preview (as composed below; excluding getDotenvCliOptions)
1030
- const childEnvPreview = {
1031
- ...process.env,
1032
- ...dotenv,
1033
- };
1034
- for (const k of keys) {
1035
- const parent = process.env[k];
1036
- const dot = dotenv[k];
1037
- const final = childEnvPreview[k];
1038
- const origin = dot !== undefined
1039
- ? 'dotenv'
1040
- : parent !== undefined
1041
- ? 'parent'
1042
- : 'unset';
1043
- // Apply presentation-time redaction (if enabled)
1044
- const redFlag = merged.redact;
1045
- const redPatterns = merged
1046
- .redactPatterns;
1047
- const redOpts = {};
1048
- if (redFlag)
1049
- redOpts.redact = true;
1050
- if (redFlag && Array.isArray(redPatterns))
1051
- redOpts.redactPatterns = redPatterns;
1052
- const tripleBag = {};
1053
- if (parent !== undefined)
1054
- tripleBag.parent = parent;
1055
- if (dot !== undefined)
1056
- tripleBag.dotenv = dot;
1057
- if (final !== undefined)
1058
- tripleBag.final = final;
1059
- const triple = redactTriple(k, tripleBag, redOpts);
1060
- // Emit concise diagnostic line to stderr.
1061
- process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
1062
- // Optional entropy warning (once-per-key)
1063
- const entOpts = {};
1064
- const warnEntropy = merged
1065
- .warnEntropy;
1066
- const entropyThreshold = merged.entropyThreshold;
1067
- const entropyMinLength = merged.entropyMinLength;
1068
- const entropyWhitelist = merged.entropyWhitelist;
1069
- if (typeof warnEntropy === 'boolean')
1070
- entOpts.warnEntropy = warnEntropy;
1071
- if (typeof entropyThreshold === 'number')
1072
- entOpts.entropyThreshold = entropyThreshold;
1073
- if (typeof entropyMinLength === 'number')
1074
- entOpts.entropyMinLength = entropyMinLength;
1075
- if (Array.isArray(entropyWhitelist))
1076
- entOpts.entropyWhitelist = entropyWhitelist;
1077
- maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
1078
- }
1079
- }
1080
- const shellSetting = resolveShell(scripts, input, shell);
1081
- /**
1082
- * Preserve original argv array when:
1083
- * - shell is OFF (plain execa), and
1084
- * - no script alias remap occurred (resolved === input).
1085
- *
1086
- * This avoids lossy re-tokenization of code snippets such as:
1087
- * node -e "console.log(process.env.APP_SECRET ?? '')"
1088
- * where quotes may have been stripped by the parent shell and
1089
- * spaces inside the code must remain a single argument.
1090
- */
1091
- const commandArg = shellSetting === false && resolved === input
1092
- ? args.map(String)
1093
- : resolved;
1094
- await runCommand(commandArg, shellSetting, {
1095
- env: buildSpawnEnv(process.env, {
1096
- ...dotenv,
1097
- getDotenvCliOptions: JSON.stringify(envBag),
1098
- }),
1099
- stdio: capture ? 'pipe' : 'inherit',
1100
- });
1101
- });
1102
- if (options.asDefault)
1103
- cli.addCommand(cmd, { isDefault: true });
1104
- else
1105
- cli.addCommand(cmd);
1106
- // Parent-attached option alias (optional).
1107
- if (aliasSpec)
1108
- attachParentAlias(cli, options);
1109
- },
1110
- });
1111
-
1112
- exports.cmdPlugin = cmdPlugin;