@karmaniverous/get-dotenv 5.2.6 → 6.0.0-1

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 (55) hide show
  1. package/README.md +106 -70
  2. package/dist/cliHost.d.ts +232 -226
  3. package/dist/cliHost.mjs +777 -545
  4. package/dist/config.d.ts +7 -2
  5. package/dist/env-overlay.d.ts +21 -9
  6. package/dist/env-overlay.mjs +14 -19
  7. package/dist/getdotenv.cli.mjs +1366 -1163
  8. package/dist/index.d.ts +415 -242
  9. package/dist/index.mjs +1364 -1414
  10. package/dist/plugins-aws.d.ts +149 -94
  11. package/dist/plugins-aws.mjs +307 -195
  12. package/dist/plugins-batch.d.ts +153 -99
  13. package/dist/plugins-batch.mjs +277 -95
  14. package/dist/plugins-cmd.d.ts +140 -94
  15. package/dist/plugins-cmd.mjs +636 -502
  16. package/dist/plugins-demo.d.ts +140 -94
  17. package/dist/plugins-demo.mjs +237 -46
  18. package/dist/plugins-init.d.ts +140 -94
  19. package/dist/plugins-init.mjs +129 -12
  20. package/dist/plugins.d.ts +166 -103
  21. package/dist/plugins.mjs +977 -840
  22. package/package.json +15 -53
  23. package/templates/cli/ts/plugins/hello.ts +27 -6
  24. package/templates/config/js/getdotenv.config.js +1 -1
  25. package/templates/config/ts/getdotenv.config.ts +9 -2
  26. package/dist/cliHost.cjs +0 -1875
  27. package/dist/cliHost.d.cts +0 -409
  28. package/dist/cliHost.d.mts +0 -409
  29. package/dist/config.cjs +0 -252
  30. package/dist/config.d.cts +0 -55
  31. package/dist/config.d.mts +0 -55
  32. package/dist/env-overlay.cjs +0 -163
  33. package/dist/env-overlay.d.cts +0 -50
  34. package/dist/env-overlay.d.mts +0 -50
  35. package/dist/index.cjs +0 -4140
  36. package/dist/index.d.cts +0 -457
  37. package/dist/index.d.mts +0 -457
  38. package/dist/plugins-aws.cjs +0 -667
  39. package/dist/plugins-aws.d.cts +0 -158
  40. package/dist/plugins-aws.d.mts +0 -158
  41. package/dist/plugins-batch.cjs +0 -616
  42. package/dist/plugins-batch.d.cts +0 -180
  43. package/dist/plugins-batch.d.mts +0 -180
  44. package/dist/plugins-cmd.cjs +0 -1113
  45. package/dist/plugins-cmd.d.cts +0 -178
  46. package/dist/plugins-cmd.d.mts +0 -178
  47. package/dist/plugins-demo.cjs +0 -307
  48. package/dist/plugins-demo.d.cts +0 -158
  49. package/dist/plugins-demo.d.mts +0 -158
  50. package/dist/plugins-init.cjs +0 -289
  51. package/dist/plugins-init.d.cts +0 -162
  52. package/dist/plugins-init.d.mts +0 -162
  53. package/dist/plugins.cjs +0 -2283
  54. package/dist/plugins.d.cts +0 -210
  55. package/dist/plugins.d.mts +0 -210
package/dist/plugins.cjs DELETED
@@ -1,2283 +0,0 @@
1
- 'use strict';
2
-
3
- var execa = require('execa');
4
- var zod = require('zod');
5
- var commander = require('commander');
6
- var globby = require('globby');
7
- var packageDirectory = require('package-directory');
8
- var path = require('path');
9
- var fs = require('fs-extra');
10
- var node_process = require('node:process');
11
- var promises = require('readline/promises');
12
-
13
- // Minimal tokenizer for shell-off execution:
14
- // Splits by whitespace while preserving quoted segments (single or double quotes).
15
- const tokenize = (command) => {
16
- const out = [];
17
- let cur = '';
18
- let quote = null;
19
- for (let i = 0; i < command.length; i++) {
20
- const c = command.charAt(i);
21
- if (quote) {
22
- if (c === quote) {
23
- // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
24
- // "" -> " and '' -> '
25
- const next = command.charAt(i + 1);
26
- if (next === quote) {
27
- cur += quote;
28
- i += 1; // skip the second quote
29
- }
30
- else {
31
- // end of quoted segment
32
- quote = null;
33
- }
34
- }
35
- else {
36
- cur += c;
37
- }
38
- }
39
- else {
40
- if (c === '"' || c === "'") {
41
- quote = c;
42
- }
43
- else if (/\s/.test(c)) {
44
- if (cur) {
45
- out.push(cur);
46
- cur = '';
47
- }
48
- }
49
- else {
50
- cur += c;
51
- }
52
- }
53
- }
54
- if (cur)
55
- out.push(cur);
56
- return out;
57
- };
58
-
59
- const dbg$1 = (...args) => {
60
- if (process.env.GETDOTENV_DEBUG) {
61
- // Use stderr to avoid interfering with stdout assertions
62
- console.error('[getdotenv:run]', ...args);
63
- }
64
- };
65
- // Strip repeated symmetric outer quotes (single or double) until stable.
66
- // This is safe for argv arrays passed to execa (no quoting needed) and avoids
67
- // passing quote characters through to Node (e.g., for `node -e "<code>"`).
68
- // Handles stacked quotes from shells like PowerShell: """code""" -> code.
69
- const stripOuterQuotes = (s) => {
70
- let out = s;
71
- // Repeatedly trim only when the entire string is wrapped in matching quotes.
72
- // Stop as soon as the ends are asymmetric or no quotes remain.
73
- while (out.length >= 2) {
74
- const a = out.charAt(0);
75
- const b = out.charAt(out.length - 1);
76
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
77
- if (!symmetric)
78
- break;
79
- out = out.slice(1, -1);
80
- }
81
- return out;
82
- };
83
- // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
84
- const pickResult = (r) => {
85
- const exit = r.exitCode;
86
- const stdoutVal = r.stdout;
87
- const stderrVal = r.stderr;
88
- return {
89
- exitCode: typeof exit === 'number' ? exit : Number.NaN,
90
- stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
91
- stderr: typeof stderrVal === 'string' ? stderrVal : '',
92
- };
93
- };
94
- // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
95
- // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
96
- const sanitizeEnv = (env) => {
97
- if (!env)
98
- return undefined;
99
- const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
100
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
101
- };
102
- /**
103
- * Execute a command and capture stdout/stderr (buffered).
104
- * - Preserves plain vs shell behavior and argv/string normalization.
105
- * - Never re-emits stdout/stderr to parent; returns captured buffers.
106
- * - Supports optional timeout (ms).
107
- */
108
- const runCommandResult = async (command, shell, opts = {}) => {
109
- const envSan = sanitizeEnv(opts.env);
110
- {
111
- let file;
112
- let args = [];
113
- if (Array.isArray(command)) {
114
- file = command[0];
115
- args = command.slice(1).map(stripOuterQuotes);
116
- }
117
- else {
118
- const tokens = tokenize(command);
119
- file = tokens[0];
120
- args = tokens.slice(1);
121
- }
122
- if (!file)
123
- return { exitCode: 0, stdout: '', stderr: '' };
124
- dbg$1('exec:capture (plain)', { file, args });
125
- try {
126
- const result = await execa.execa(file, args, {
127
- ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
128
- ...(envSan !== undefined ? { env: envSan } : {}),
129
- stdio: 'pipe',
130
- ...(opts.timeoutMs !== undefined
131
- ? { timeout: opts.timeoutMs, killSignal: 'SIGKILL' }
132
- : {}),
133
- });
134
- const ok = pickResult(result);
135
- dbg$1('exit:capture (plain)', { exitCode: ok.exitCode });
136
- return ok;
137
- }
138
- catch (err) {
139
- const out = pickResult(err);
140
- dbg$1('exit:capture:error (plain)', { exitCode: out.exitCode });
141
- return out;
142
- }
143
- }
144
- };
145
- const runCommand = async (command, shell, opts) => {
146
- if (shell === false) {
147
- let file;
148
- let args = [];
149
- if (Array.isArray(command)) {
150
- file = command[0];
151
- args = command.slice(1).map(stripOuterQuotes);
152
- }
153
- else {
154
- const tokens = tokenize(command);
155
- file = tokens[0];
156
- args = tokens.slice(1);
157
- }
158
- if (!file)
159
- return 0;
160
- dbg$1('exec (plain)', { file, args, stdio: opts.stdio });
161
- // Build options without injecting undefined properties (exactOptionalPropertyTypes).
162
- const envSan = sanitizeEnv(opts.env);
163
- const plainOpts = {};
164
- if (opts.cwd !== undefined)
165
- plainOpts.cwd = opts.cwd;
166
- if (envSan !== undefined)
167
- plainOpts.env = envSan;
168
- if (opts.stdio !== undefined)
169
- plainOpts.stdio = opts.stdio;
170
- const result = await execa.execa(file, args, plainOpts);
171
- if (opts.stdio === 'pipe' && result.stdout) {
172
- process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
173
- }
174
- const exit = result?.exitCode;
175
- dbg$1('exit (plain)', { exitCode: exit });
176
- return typeof exit === 'number' ? exit : Number.NaN;
177
- }
178
- else {
179
- const commandStr = Array.isArray(command) ? command.join(' ') : command;
180
- dbg$1('exec (shell)', {
181
- shell: typeof shell === 'string' ? shell : 'custom',
182
- stdio: opts.stdio,
183
- command: commandStr,
184
- });
185
- const envSan = sanitizeEnv(opts.env);
186
- const shellOpts = { shell };
187
- if (opts.cwd !== undefined)
188
- shellOpts.cwd = opts.cwd;
189
- if (envSan !== undefined)
190
- shellOpts.env = envSan;
191
- if (opts.stdio !== undefined)
192
- shellOpts.stdio = opts.stdio;
193
- const result = await execa.execaCommand(commandStr, shellOpts);
194
- const out = result?.stdout;
195
- if (opts.stdio === 'pipe' && out) {
196
- process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
197
- }
198
- const exit = result?.exitCode;
199
- dbg$1('exit (shell)', { exitCode: exit });
200
- return typeof exit === 'number' ? exit : Number.NaN;
201
- }
202
- };
203
-
204
- const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
205
- /** Build a sanitized env for child processes from base + overlay. */
206
- const buildSpawnEnv = (base, overlay) => {
207
- const raw = {
208
- ...(base ?? {}),
209
- ...(overlay ?? {}),
210
- };
211
- // Drop undefined first
212
- const entries = Object.entries(dropUndefined(raw));
213
- if (process.platform === 'win32') {
214
- // Windows: keys are case-insensitive; collapse duplicates
215
- const byLower = new Map();
216
- for (const [k, v] of entries) {
217
- byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
218
- }
219
- const out = {};
220
- for (const [, [k, v]] of byLower)
221
- out[k] = v;
222
- // HOME fallback from USERPROFILE (common expectation)
223
- if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
224
- const up = out['USERPROFILE'];
225
- if (typeof up === 'string' && up.length > 0)
226
- out['HOME'] = up;
227
- }
228
- // Normalize TMP/TEMP coherence (pick any present; reflect to both)
229
- const tmp = out['TMP'] ?? out['TEMP'];
230
- if (typeof tmp === 'string' && tmp.length > 0) {
231
- out['TMP'] = tmp;
232
- out['TEMP'] = tmp;
233
- }
234
- return out;
235
- }
236
- // POSIX: keep keys as-is
237
- const out = Object.fromEntries(entries);
238
- // Ensure TMPDIR exists when any temp key is present (best-effort)
239
- const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
240
- if (typeof tmpdir === 'string' && tmpdir.length > 0) {
241
- out['TMPDIR'] = tmpdir;
242
- }
243
- return out;
244
- };
245
-
246
- /** src/cliHost/definePlugin.ts
247
- * Plugin contracts for the GetDotenv CLI host.
248
- *
249
- * This module exposes a structural public interface for the host that plugins
250
- * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
251
- * nominal class identity issues (private fields) in downstream consumers.
252
- */
253
- /**
254
- * Define a GetDotenv CLI plugin with compositional helpers.
255
- *
256
- * @example
257
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
258
- * .use(childA)
259
- * .use(childB);
260
- */
261
- const definePlugin = (spec) => {
262
- const { children = [], ...rest } = spec;
263
- const plugin = {
264
- ...rest,
265
- children: [...children],
266
- use(child) {
267
- this.children.push(child);
268
- return this;
269
- },
270
- };
271
- return plugin;
272
- };
273
-
274
- /**
275
- * Batch services (neutral): resolve command and shell settings.
276
- * Shared by the generator path and the batch plugin to avoid circular deps.
277
- */
278
- /**
279
- * Resolve a command string from the {@link Scripts} table.
280
- * A script may be expressed as a string or an object with a `cmd` property.
281
- *
282
- * @param scripts - Optional scripts table.
283
- * @param command - User-provided command name or string.
284
- * @returns Resolved command string (falls back to the provided command).
285
- */
286
- const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
287
- ? scripts[command].cmd
288
- : (scripts?.[command] ?? command);
289
- /**
290
- * Resolve the shell setting for a given command:
291
- * - If the script entry is an object, prefer its `shell` override.
292
- * - Otherwise use the provided `shell` (string | boolean).
293
- *
294
- * @param scripts - Optional scripts table.
295
- * @param command - User-provided command name or string.
296
- * @param shell - Global shell preference (string | boolean).
297
- */
298
- const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
299
- ? (scripts[command].shell ?? false)
300
- : (shell ?? false);
301
-
302
- const DEFAULT_TIMEOUT_MS = 15_000;
303
- const trim = (s) => (typeof s === 'string' ? s.trim() : '');
304
- const unquote = (s) => s.length >= 2 &&
305
- ((s.startsWith('"') && s.endsWith('"')) ||
306
- (s.startsWith("'") && s.endsWith("'")))
307
- ? s.slice(1, -1)
308
- : s;
309
- const parseExportCredentialsJson = (txt) => {
310
- try {
311
- const obj = JSON.parse(txt);
312
- const src = obj.Credentials ?? obj;
313
- const ak = src.AccessKeyId;
314
- const sk = src.SecretAccessKey;
315
- const tk = src.SessionToken;
316
- if (ak && sk)
317
- return {
318
- accessKeyId: ak,
319
- secretAccessKey: sk,
320
- ...(tk ? { sessionToken: tk } : {}),
321
- };
322
- }
323
- catch {
324
- /* ignore */
325
- }
326
- return undefined;
327
- };
328
- const parseExportCredentialsEnv = (txt) => {
329
- const lines = txt.split(/\r?\n/);
330
- let id;
331
- let secret;
332
- let token;
333
- for (const raw of lines) {
334
- const line = raw.trim();
335
- if (!line)
336
- continue;
337
- // POSIX: export AWS_ACCESS_KEY_ID=..., export AWS_SECRET_ACCESS_KEY=..., export AWS_SESSION_TOKEN=...
338
- let m = /^export\s+([A-Z0-9_]+)\s*=\s*(.+)$/.exec(line);
339
- if (!m) {
340
- // PowerShell: $Env:AWS_ACCESS_KEY_ID="...", etc.
341
- m = /^\$Env:([A-Z0-9_]+)\s*=\s*(.+)$/.exec(line);
342
- }
343
- if (!m)
344
- continue;
345
- const k = m[1];
346
- const valRaw = m[2];
347
- if (typeof valRaw !== 'string')
348
- continue;
349
- let v = unquote(valRaw.trim());
350
- // Drop trailing semicolons if present (some shells)
351
- v = v.replace(/;$/, '');
352
- if (k === 'AWS_ACCESS_KEY_ID')
353
- id = v;
354
- else if (k === 'AWS_SECRET_ACCESS_KEY')
355
- secret = v;
356
- else if (k === 'AWS_SESSION_TOKEN')
357
- token = v;
358
- }
359
- if (id && secret)
360
- return {
361
- accessKeyId: id,
362
- secretAccessKey: secret,
363
- ...(token ? { sessionToken: token } : {}),
364
- };
365
- return undefined;
366
- };
367
- const getAwsConfigure = async (key, profile, timeoutMs = DEFAULT_TIMEOUT_MS) => {
368
- const r = await runCommandResult(['aws', 'configure', 'get', key, '--profile', profile], false, {
369
- env: process.env,
370
- timeoutMs,
371
- });
372
- // Guard for mocked undefined in tests; keep narrow lint scope.
373
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
374
- if (!r || typeof r.exitCode !== 'number')
375
- return undefined;
376
- if (r.exitCode === 0) {
377
- const v = trim(r.stdout);
378
- return v.length > 0 ? v : undefined;
379
- }
380
- return undefined;
381
- };
382
- const exportCredentials = async (profile, timeoutMs = DEFAULT_TIMEOUT_MS) => {
383
- // Try JSON format first (AWS CLI v2)
384
- const rJson = await runCommandResult([
385
- 'aws',
386
- 'configure',
387
- 'export-credentials',
388
- '--profile',
389
- profile,
390
- '--format',
391
- 'json',
392
- ], false, { env: process.env, timeoutMs });
393
- if (rJson.exitCode === 0) {
394
- const creds = parseExportCredentialsJson(rJson.stdout);
395
- if (creds)
396
- return creds;
397
- }
398
- // Fallback: env lines
399
- const rEnv = await runCommandResult(['aws', 'configure', 'export-credentials', '--profile', profile], false, { env: process.env, timeoutMs });
400
- if (rEnv.exitCode === 0) {
401
- const creds = parseExportCredentialsEnv(rEnv.stdout);
402
- if (creds)
403
- return creds;
404
- }
405
- return undefined;
406
- };
407
- const resolveAwsContext = async ({ dotenv, cfg, }) => {
408
- const profileKey = cfg.profileKey ?? 'AWS_LOCAL_PROFILE';
409
- const profileFallbackKey = cfg.profileFallbackKey ?? 'AWS_PROFILE';
410
- const regionKey = cfg.regionKey ?? 'AWS_REGION';
411
- const profile = cfg.profile ??
412
- dotenv[profileKey] ??
413
- dotenv[profileFallbackKey] ??
414
- undefined;
415
- let region = cfg.region ?? dotenv[regionKey] ?? undefined;
416
- // Short-circuit when strategy is disabled.
417
- if (cfg.strategy === 'none') {
418
- // If region is still missing and we have a profile, try best-effort region resolve.
419
- if (!region && profile)
420
- region = await getAwsConfigure('region', profile);
421
- if (!region && cfg.defaultRegion)
422
- region = cfg.defaultRegion;
423
- const out = {};
424
- if (profile !== undefined)
425
- out.profile = profile;
426
- if (region !== undefined)
427
- out.region = region;
428
- return out;
429
- }
430
- // Env-first credentials.
431
- let credentials;
432
- const envId = trim(process.env.AWS_ACCESS_KEY_ID);
433
- const envSecret = trim(process.env.AWS_SECRET_ACCESS_KEY);
434
- const envToken = trim(process.env.AWS_SESSION_TOKEN);
435
- if (envId && envSecret) {
436
- credentials = {
437
- accessKeyId: envId,
438
- secretAccessKey: envSecret,
439
- ...(envToken ? { sessionToken: envToken } : {}),
440
- };
441
- }
442
- else if (profile) {
443
- // Try export-credentials
444
- credentials = await exportCredentials(profile);
445
- // On failure, detect SSO and optionally login then retry
446
- if (!credentials) {
447
- const ssoSession = await getAwsConfigure('sso_session', profile);
448
- const looksSSO = typeof ssoSession === 'string' && ssoSession.length > 0;
449
- if (looksSSO && cfg.loginOnDemand) {
450
- // Best-effort login, then retry export once.
451
- await runCommandResult(['aws', 'sso', 'login', '--profile', profile], false, {
452
- env: process.env,
453
- timeoutMs: DEFAULT_TIMEOUT_MS,
454
- });
455
- credentials = await exportCredentials(profile);
456
- }
457
- }
458
- // Static fallback if still missing.
459
- if (!credentials) {
460
- const id = await getAwsConfigure('aws_access_key_id', profile);
461
- const secret = await getAwsConfigure('aws_secret_access_key', profile);
462
- const token = await getAwsConfigure('aws_session_token', profile);
463
- if (id && secret) {
464
- credentials = {
465
- accessKeyId: id,
466
- secretAccessKey: secret,
467
- ...(token ? { sessionToken: token } : {}),
468
- };
469
- }
470
- }
471
- }
472
- // Final region resolution
473
- if (!region && profile)
474
- region = await getAwsConfigure('region', profile);
475
- if (!region && cfg.defaultRegion)
476
- region = cfg.defaultRegion;
477
- const out = {};
478
- if (profile !== undefined)
479
- out.profile = profile;
480
- if (region !== undefined)
481
- out.region = region;
482
- if (credentials)
483
- out.credentials = credentials;
484
- return out;
485
- };
486
-
487
- const AwsPluginConfigSchema = zod.z.object({
488
- profile: zod.z.string().optional(),
489
- region: zod.z.string().optional(),
490
- defaultRegion: zod.z.string().optional(),
491
- profileKey: zod.z.string().default('AWS_LOCAL_PROFILE').optional(),
492
- profileFallbackKey: zod.z.string().default('AWS_PROFILE').optional(),
493
- regionKey: zod.z.string().default('AWS_REGION').optional(),
494
- strategy: zod.z.enum(['cli-export', 'none']).default('cli-export').optional(),
495
- loginOnDemand: zod.z.boolean().default(false).optional(),
496
- setEnv: zod.z.boolean().default(true).optional(),
497
- addCtx: zod.z.boolean().default(true).optional(),
498
- });
499
-
500
- const awsPlugin = () => definePlugin({
501
- id: 'aws',
502
- // Host validates this slice when the loader path is active.
503
- configSchema: AwsPluginConfigSchema,
504
- setup(cli) {
505
- // Subcommand: aws
506
- cli
507
- .ns('aws')
508
- .description('Establish an AWS session and optionally forward to the AWS CLI')
509
- .configureHelp({ showGlobalOptions: true })
510
- .enablePositionalOptions()
511
- .passThroughOptions()
512
- .allowUnknownOption(true)
513
- // Boolean toggles
514
- .option('--login-on-demand', 'attempt aws sso login on-demand')
515
- .option('--no-login-on-demand', 'disable sso login on-demand')
516
- .option('--set-env', 'write resolved values into process.env')
517
- .option('--no-set-env', 'do not write resolved values into process.env')
518
- .option('--add-ctx', 'mirror results under ctx.plugins.aws')
519
- .option('--no-add-ctx', 'do not mirror results under ctx.plugins.aws')
520
- // Strings / enums
521
- .option('--profile <string>', 'AWS profile name')
522
- .option('--region <string>', 'AWS region')
523
- .option('--default-region <string>', 'fallback region')
524
- .option('--strategy <string>', 'credential acquisition strategy: cli-export|none')
525
- // Advanced key overrides
526
- .option('--profile-key <string>', 'dotenv/config key for local profile')
527
- .option('--profile-fallback-key <string>', 'fallback dotenv/config key for profile')
528
- .option('--region-key <string>', 'dotenv/config key for region')
529
- // Accept any extra operands so Commander does not error when tokens appear after "--".
530
- .argument('[args...]')
531
- .action(async (args, opts, thisCommand) => {
532
- const self = thisCommand;
533
- const parent = (self.parent ?? null);
534
- // Access merged root CLI options (installed by passOptions())
535
- const rootOpts = (parent?.getDotenvCliOptions ?? {});
536
- const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
537
- Boolean(rootOpts?.capture);
538
- const underTests = process.env.GETDOTENV_TEST === '1' ||
539
- typeof process.env.VITEST_WORKER_ID === 'string';
540
- // Build overlay cfg from subcommand flags layered over discovered config.
541
- const ctx = cli.getCtx();
542
- const cfgBase = (ctx?.pluginConfigs?.['aws'] ??
543
- {});
544
- const overlay = {};
545
- // Map boolean toggles (respect explicit --no-*)
546
- if (Object.prototype.hasOwnProperty.call(opts, 'loginOnDemand'))
547
- overlay.loginOnDemand = Boolean(opts.loginOnDemand);
548
- if (Object.prototype.hasOwnProperty.call(opts, 'setEnv'))
549
- overlay.setEnv = Boolean(opts.setEnv);
550
- if (Object.prototype.hasOwnProperty.call(opts, 'addCtx'))
551
- overlay.addCtx = Boolean(opts.addCtx);
552
- // Strings/enums
553
- if (typeof opts.profile === 'string')
554
- overlay.profile = opts.profile;
555
- if (typeof opts.region === 'string')
556
- overlay.region = opts.region;
557
- if (typeof opts.defaultRegion === 'string')
558
- overlay.defaultRegion = opts.defaultRegion;
559
- if (typeof opts.strategy === 'string')
560
- overlay.strategy =
561
- opts.strategy;
562
- // Advanced key overrides
563
- if (typeof opts.profileKey === 'string')
564
- overlay.profileKey = opts.profileKey;
565
- if (typeof opts.profileFallbackKey === 'string')
566
- overlay.profileFallbackKey = opts.profileFallbackKey;
567
- if (typeof opts.regionKey === 'string')
568
- overlay.regionKey = opts.regionKey;
569
- const cfg = {
570
- ...cfgBase,
571
- ...overlay,
572
- };
573
- // Resolve current context with overrides
574
- const out = await resolveAwsContext({
575
- dotenv: ctx?.dotenv ?? {},
576
- cfg,
577
- });
578
- // Apply env/ctx mirrors per toggles
579
- if (cfg.setEnv !== false) {
580
- if (out.region) {
581
- process.env.AWS_REGION = out.region;
582
- if (!process.env.AWS_DEFAULT_REGION)
583
- process.env.AWS_DEFAULT_REGION = out.region;
584
- }
585
- if (out.credentials) {
586
- process.env.AWS_ACCESS_KEY_ID = out.credentials.accessKeyId;
587
- process.env.AWS_SECRET_ACCESS_KEY =
588
- out.credentials.secretAccessKey;
589
- if (out.credentials.sessionToken !== undefined) {
590
- process.env.AWS_SESSION_TOKEN = out.credentials.sessionToken;
591
- }
592
- }
593
- }
594
- if (cfg.addCtx !== false) {
595
- if (ctx) {
596
- ctx.plugins ??= {};
597
- ctx.plugins['aws'] = {
598
- ...(out.profile ? { profile: out.profile } : {}),
599
- ...(out.region ? { region: out.region } : {}),
600
- ...(out.credentials ? { credentials: out.credentials } : {}),
601
- };
602
- }
603
- }
604
- // Forward when positional args are present; otherwise session-only.
605
- if (Array.isArray(args) && args.length > 0) {
606
- const argv = ['aws', ...args];
607
- const shellSetting = resolveShell(rootOpts?.scripts, 'aws', rootOpts?.shell);
608
- const ctxDotenv = (ctx?.dotenv ?? {});
609
- const exit = await runCommand(argv, shellSetting, {
610
- env: buildSpawnEnv(process.env, ctxDotenv),
611
- stdio: capture ? 'pipe' : 'inherit',
612
- });
613
- // Deterministic termination (suppressed under tests)
614
- if (!underTests) {
615
- process.exit(typeof exit === 'number' ? exit : 0);
616
- }
617
- return;
618
- }
619
- else {
620
- // Session only: low-noise breadcrumb under debug
621
- if (process.env.GETDOTENV_DEBUG) {
622
- const log = console;
623
- log.log('[aws] session established', {
624
- profile: out.profile,
625
- region: out.region,
626
- hasCreds: Boolean(out.credentials),
627
- });
628
- }
629
- if (!underTests)
630
- process.exit(0);
631
- return;
632
- }
633
- });
634
- },
635
- async afterResolve(_cli, ctx) {
636
- const log = console;
637
- const cfgRaw = (ctx.pluginConfigs?.['aws'] ?? {});
638
- const cfg = (cfgRaw || {});
639
- const out = await resolveAwsContext({
640
- dotenv: ctx.dotenv,
641
- cfg,
642
- });
643
- const { profile, region, credentials } = out;
644
- if (cfg.setEnv !== false) {
645
- if (region) {
646
- process.env.AWS_REGION = region;
647
- if (!process.env.AWS_DEFAULT_REGION)
648
- process.env.AWS_DEFAULT_REGION = region;
649
- }
650
- if (credentials) {
651
- process.env.AWS_ACCESS_KEY_ID = credentials.accessKeyId;
652
- process.env.AWS_SECRET_ACCESS_KEY = credentials.secretAccessKey;
653
- if (credentials.sessionToken !== undefined) {
654
- process.env.AWS_SESSION_TOKEN = credentials.sessionToken;
655
- }
656
- }
657
- }
658
- if (cfg.addCtx !== false) {
659
- ctx.plugins ??= {};
660
- ctx.plugins['aws'] = {
661
- ...(profile ? { profile } : {}),
662
- ...(region ? { region } : {}),
663
- ...(credentials ? { credentials } : {}),
664
- };
665
- }
666
- // Optional: low-noise breadcrumb for diagnostics
667
- if (process.env.GETDOTENV_DEBUG) {
668
- log.log('[aws] afterResolve', {
669
- profile,
670
- region,
671
- hasCreds: Boolean(credentials),
672
- });
673
- }
674
- },
675
- });
676
-
677
- const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
678
- let cwd = process.cwd();
679
- if (pkgCwd) {
680
- const pkgDir = await packageDirectory.packageDirectory();
681
- if (!pkgDir) {
682
- logger.error('No package directory found.');
683
- process.exit(0);
684
- }
685
- cwd = pkgDir;
686
- }
687
- const absRootPath = path.posix.join(cwd.split(path.sep).join(path.posix.sep), rootPath.split(path.sep).join(path.posix.sep));
688
- const paths = await globby.globby(globs.split(/\s+/), {
689
- cwd: absRootPath,
690
- expandDirectories: false,
691
- onlyDirectories: true,
692
- absolute: true,
693
- });
694
- if (!paths.length) {
695
- logger.error(`No paths found for globs '${globs}' at '${absRootPath}'.`);
696
- process.exit(0);
697
- }
698
- return { absRootPath, paths };
699
- };
700
- const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, ignoreErrors, list, logger, pkgCwd, rootPath, shell, }) => {
701
- const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
702
- Boolean(getDotenvCliOptions?.capture); // Require a command only when not listing. In list mode, a command is optional.
703
- if (!command && !list) {
704
- logger.error(`No command provided. Use --command or --list.`);
705
- process.exit(0);
706
- }
707
- const { absRootPath, paths } = await globPaths({
708
- globs,
709
- logger,
710
- rootPath,
711
- // exactOptionalPropertyTypes: only include when defined
712
- ...(pkgCwd !== undefined ? { pkgCwd } : {}),
713
- });
714
- const headerTitle = list
715
- ? 'Listing working directories...'
716
- : 'Executing command batch...';
717
- logger.info('');
718
- const headerRootPath = `ROOT: ${absRootPath}`;
719
- const headerGlobs = `GLOBS: ${globs}`;
720
- // Prepare a safe label for the header (avoid undefined in template)
721
- const commandLabel = Array.isArray(command)
722
- ? command.join(' ')
723
- : typeof command === 'string' && command.length > 0
724
- ? command
725
- : '';
726
- const headerCommand = list ? `CMD: (list only)` : `CMD: ${commandLabel}`;
727
- logger.info('*'.repeat(Math.max(headerTitle.length, headerRootPath.length, headerGlobs.length, headerCommand.length)));
728
- logger.info(headerTitle);
729
- logger.info('');
730
- logger.info(headerRootPath);
731
- logger.info(headerGlobs);
732
- logger.info(headerCommand);
733
- for (const path of paths) {
734
- // Write path and command to console.
735
- const pathLabel = `CWD: ${path}`;
736
- if (list) {
737
- logger.info(pathLabel);
738
- continue;
739
- }
740
- logger.info('');
741
- logger.info('*'.repeat(pathLabel.length));
742
- logger.info(pathLabel);
743
- logger.info(headerCommand);
744
- // Execute command.
745
- try {
746
- const hasCmd = (typeof command === 'string' && command.length > 0) ||
747
- (Array.isArray(command) && command.length > 0);
748
- if (hasCmd) {
749
- const envBag = getDotenvCliOptions !== undefined
750
- ? { getDotenvCliOptions: JSON.stringify(getDotenvCliOptions) }
751
- : undefined;
752
- await runCommand(command, shell, {
753
- cwd: path,
754
- env: buildSpawnEnv(process.env, envBag),
755
- stdio: capture ? 'pipe' : 'inherit',
756
- });
757
- }
758
- else {
759
- // Should not occur due to the early guard; retain for type safety.
760
- logger.error(`No command provided. Use --command or --list.`);
761
- process.exit(0);
762
- }
763
- }
764
- catch (error) {
765
- if (!ignoreErrors) {
766
- throw error;
767
- }
768
- }
769
- }
770
- logger.info('');
771
- };
772
-
773
- /**
774
- * Build the default "cmd" subcommand action for the batch plugin.
775
- * Mirrors the original inline implementation with identical behavior.
776
- */
777
- const buildDefaultCmdAction = (cli, batchCmd, opts) => async (commandParts, _subOpts, _thisCommand) => {
778
- const loggerLocal = opts.logger ?? console;
779
- // Guard: when invoked without positional args (e.g., `batch --list`),
780
- // defer entirely to the parent action handler.
781
- const argsRaw = Array.isArray(commandParts)
782
- ? commandParts
783
- : [];
784
- const localList = argsRaw.includes('-l') || argsRaw.includes('--list');
785
- const args = localList
786
- ? argsRaw.filter((t) => t !== '-l' && t !== '--list')
787
- : argsRaw;
788
- // Access merged per-plugin config from host context (if any).
789
- const ctx = cli.getCtx();
790
- const cfgRaw = (ctx?.pluginConfigs?.['batch'] ?? {});
791
- const cfg = (cfgRaw || {});
792
- // Resolve batch flags from the captured parent (batch) command.
793
- const raw = batchCmd.opts();
794
- const listFromParent = !!raw.list;
795
- const ignoreErrors = !!raw.ignoreErrors;
796
- const globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
797
- const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
798
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
799
- // Resolve scripts/shell with precedence:
800
- // plugin opts → plugin config → merged root CLI options
801
- const mergedBag = ((batchCmd.parent ?? null)?.getDotenvCliOptions ?? {});
802
- const scripts = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
803
- const shell = opts.shell ?? cfg.shell ?? mergedBag.shell;
804
- // If no positional args were given, bridge to --command/--list paths here.
805
- if (args.length === 0) {
806
- const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
807
- if (typeof commandOpt === 'string') {
808
- await execShellCommandBatch({
809
- command: resolveCommand(scripts, commandOpt),
810
- globs,
811
- ignoreErrors,
812
- list: false,
813
- logger: loggerLocal,
814
- ...(pkgCwd ? { pkgCwd } : {}),
815
- rootPath,
816
- shell: resolveShell(scripts, commandOpt, shell),
817
- });
818
- return;
819
- }
820
- if (raw.list || localList) {
821
- await execShellCommandBatch({
822
- globs,
823
- ignoreErrors,
824
- list: true,
825
- logger: loggerLocal,
826
- ...(pkgCwd ? { pkgCwd } : {}),
827
- rootPath,
828
- shell: (shell ?? false),
829
- });
830
- return;
831
- }
832
- {
833
- const lr = loggerLocal;
834
- const emit = lr.error ?? lr.log;
835
- emit(`No command provided. Use --command or --list.`);
836
- }
837
- process.exit(0);
838
- }
839
- // If a local list flag was supplied with positional tokens (and no --command),
840
- // treat tokens as additional globs and execute list mode.
841
- if (localList && typeof raw.command !== 'string') {
842
- const extraGlobs = args.map(String).join(' ').trim();
843
- const mergedGlobs = [globs, extraGlobs].filter(Boolean).join(' ');
844
- const shellBag = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
845
- await execShellCommandBatch({
846
- globs: mergedGlobs,
847
- ignoreErrors,
848
- list: true,
849
- logger: loggerLocal,
850
- ...(pkgCwd ? { pkgCwd } : {}),
851
- rootPath,
852
- shell: (shell ?? shellBag.shell ?? false),
853
- });
854
- return;
855
- }
856
- // If parent list flag is set and positional tokens are present (and no --command),
857
- // treat tokens as additional globs for list-only mode.
858
- if (listFromParent && args.length > 0 && typeof raw.command !== 'string') {
859
- const extra = args.map(String).join(' ').trim();
860
- const mergedGlobs = [globs, extra].filter(Boolean).join(' ');
861
- const mergedBag2 = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
862
- await execShellCommandBatch({
863
- globs: mergedGlobs,
864
- ignoreErrors,
865
- list: true,
866
- logger: loggerLocal,
867
- ...(pkgCwd ? { pkgCwd } : {}),
868
- rootPath,
869
- shell: (shell ?? mergedBag2.shell ?? false),
870
- });
871
- return;
872
- }
873
- // Join positional args as the command to execute.
874
- const input = args.map(String).join(' ');
875
- // Optional: round-trip parent merged options if present (shipped CLI).
876
- const envBag = (batchCmd.parent ?? undefined)?.getDotenvCliOptions;
877
- const mergedExec = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
878
- const scriptsExec = scripts ?? mergedExec.scripts;
879
- const shellExec = shell ?? mergedExec.shell;
880
- const resolved = resolveCommand(scriptsExec, input);
881
- const shellSetting = resolveShell(scriptsExec, input, shellExec);
882
- // Preserve argv array only for shell-off Node -e snippets to avoid
883
- // lossy re-tokenization (Windows/PowerShell quoting). For simple
884
- // commands (e.g., "echo OK") keep string form to satisfy unit tests.
885
- let commandArg = resolved;
886
- if (shellSetting === false && resolved === input) {
887
- const first = (args[0] ?? '').toLowerCase();
888
- const hasEval = args.includes('-e') || args.includes('--eval');
889
- if (first === 'node' && hasEval) {
890
- commandArg = args.map(String);
891
- }
892
- }
893
- await execShellCommandBatch({
894
- command: commandArg,
895
- ...(envBag ? { getDotenvCliOptions: envBag } : {}),
896
- globs,
897
- ignoreErrors,
898
- list: false,
899
- logger: loggerLocal,
900
- ...(pkgCwd ? { pkgCwd } : {}),
901
- rootPath,
902
- shell: shellSetting,
903
- });
904
- };
905
-
906
- /**
907
- * Build the parent "batch" action handler (no explicit subcommand).
908
- */
909
- const buildParentAction = (cli, opts) => async (commandParts, thisCommand) => {
910
- const logger = opts.logger ?? console;
911
- // Ensure context exists (host preSubcommand on root creates if missing).
912
- const ctx = cli.getCtx();
913
- const cfgRaw = (ctx?.pluginConfigs?.['batch'] ?? {});
914
- const cfg = (cfgRaw || {});
915
- const raw = thisCommand.opts();
916
- const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
917
- const ignoreErrors = !!raw.ignoreErrors;
918
- let globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
919
- const list = !!raw.list;
920
- const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
921
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
922
- // Treat parent positional tokens as the command when no explicit 'cmd' is used.
923
- const argsParent = Array.isArray(commandParts) ? commandParts : [];
924
- if (argsParent.length > 0 && !list) {
925
- const input = argsParent.map(String).join(' ');
926
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
927
- const scriptsAll = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
928
- const shellAll = opts.shell ?? cfg.shell ?? mergedBag.shell;
929
- const resolved = resolveCommand(scriptsAll, input);
930
- const shellSetting = resolveShell(scriptsAll, input, shellAll);
931
- // Parent path: pass a string; executor handles shell-specific details.
932
- const commandArg = resolved;
933
- await execShellCommandBatch({
934
- command: commandArg,
935
- globs,
936
- ignoreErrors,
937
- list: false,
938
- logger,
939
- ...(pkgCwd ? { pkgCwd } : {}),
940
- rootPath,
941
- shell: shellSetting,
942
- });
943
- return;
944
- }
945
- // List-only: merge extra positional tokens into globs when no --command is present.
946
- if (list && argsParent.length > 0 && !commandOpt) {
947
- const extra = argsParent.map(String).join(' ').trim();
948
- if (extra.length > 0)
949
- globs = [globs, extra].filter(Boolean).join(' ');
950
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
951
- await execShellCommandBatch({
952
- globs,
953
- ignoreErrors,
954
- list: true,
955
- logger,
956
- ...(pkgCwd ? { pkgCwd } : {}),
957
- rootPath,
958
- shell: (opts.shell ?? cfg.shell ?? mergedBag.shell ?? false),
959
- });
960
- return;
961
- }
962
- if (!commandOpt && !list) {
963
- logger.error(`No command provided. Use --command or --list.`);
964
- process.exit(0);
965
- }
966
- if (typeof commandOpt === 'string') {
967
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
968
- const scriptsOpt = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
969
- const shellOpt = opts.shell ?? cfg.shell ?? mergedBag.shell;
970
- await execShellCommandBatch({
971
- command: resolveCommand(scriptsOpt, commandOpt),
972
- globs,
973
- ignoreErrors,
974
- list,
975
- logger,
976
- ...(pkgCwd ? { pkgCwd } : {}),
977
- rootPath,
978
- shell: resolveShell(scriptsOpt, commandOpt, shellOpt),
979
- });
980
- return;
981
- }
982
- // list only (explicit --list without --command)
983
- const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
984
- const shellOnly = (opts.shell ?? cfg.shell ?? mergedBag.shell ?? false);
985
- await execShellCommandBatch({
986
- globs,
987
- ignoreErrors,
988
- list: true,
989
- logger,
990
- ...(pkgCwd ? { pkgCwd } : {}),
991
- rootPath,
992
- shell: (shellOnly ?? false),
993
- });
994
- };
995
-
996
- // Per-plugin config schema (optional fields; used as defaults).
997
- const ScriptSchema = zod.z.union([
998
- zod.z.string(),
999
- zod.z.object({
1000
- cmd: zod.z.string(),
1001
- shell: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
1002
- }),
1003
- ]);
1004
- const BatchConfigSchema = zod.z.object({
1005
- scripts: zod.z.record(zod.z.string(), ScriptSchema).optional(),
1006
- shell: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
1007
- rootPath: zod.z.string().optional(),
1008
- globs: zod.z.string().optional(),
1009
- pkgCwd: zod.z.boolean().optional(),
1010
- });
1011
-
1012
- /**
1013
- * Batch plugin for the GetDotenv CLI host.
1014
- *
1015
- * Mirrors the legacy batch subcommand behavior without altering the shipped CLI. * Options:
1016
- * - scripts/shell: used to resolve command and shell behavior per script or global default.
1017
- * - logger: defaults to console.
1018
- */
1019
- const batchPlugin = (opts = {}) => definePlugin({
1020
- id: 'batch',
1021
- // Host validates this when config-loader is enabled; plugins may also
1022
- // re-validate at action time as a safety belt.
1023
- configSchema: BatchConfigSchema,
1024
- setup(cli) {
1025
- const ns = cli.ns('batch');
1026
- const batchCmd = ns; // capture the parent "batch" command for default-subcommand context
1027
- ns.description('Batch command execution across multiple working directories.')
1028
- .enablePositionalOptions()
1029
- .passThroughOptions()
1030
- .option('-p, --pkg-cwd', 'use nearest package directory as current working directory')
1031
- .option('-r, --root-path <string>', 'path to batch root directory from current working directory', './')
1032
- .option('-g, --globs <string>', 'space-delimited globs from root path', '*')
1033
- .option('-c, --command <string>', 'command executed according to the base shell resolution')
1034
- .option('-l, --list', 'list working directories without executing command')
1035
- .option('-e, --ignore-errors', 'ignore errors and continue with next path')
1036
- .argument('[command...]')
1037
- .addCommand(new commander.Command()
1038
- .name('cmd')
1039
- .description('execute command, conflicts with --command option (default subcommand)')
1040
- .enablePositionalOptions()
1041
- .passThroughOptions()
1042
- .argument('[command...]')
1043
- .action(buildDefaultCmdAction(cli, batchCmd, opts)), { isDefault: true })
1044
- .action(buildParentAction(cli, opts));
1045
- },
1046
- });
1047
-
1048
- /** src/diagnostics/entropy.ts
1049
- * Entropy diagnostics (presentation-only).
1050
- * - Gated by min length and printable ASCII.
1051
- * - Warn once per key per run when bits/char \>= threshold.
1052
- * - Supports whitelist patterns to suppress known-noise keys.
1053
- */
1054
- const warned = new Set();
1055
- const isPrintableAscii = (s) => /^[\x20-\x7E]+$/.test(s);
1056
- const compile$1 = (patterns) => (patterns ?? []).map((p) => new RegExp(p, 'i'));
1057
- const whitelisted = (key, regs) => regs.some((re) => re.test(key));
1058
- const shannonBitsPerChar = (s) => {
1059
- const freq = new Map();
1060
- for (const ch of s)
1061
- freq.set(ch, (freq.get(ch) ?? 0) + 1);
1062
- const n = s.length;
1063
- let h = 0;
1064
- for (const c of freq.values()) {
1065
- const p = c / n;
1066
- h -= p * Math.log2(p);
1067
- }
1068
- return h;
1069
- };
1070
- /**
1071
- * Maybe emit a one-line entropy warning for a key.
1072
- * Caller supplies an `emit(line)` function; the helper ensures once-per-key.
1073
- */
1074
- const maybeWarnEntropy = (key, value, origin, opts, emit) => {
1075
- if (!opts || opts.warnEntropy === false)
1076
- return;
1077
- if (warned.has(key))
1078
- return;
1079
- const v = value ?? '';
1080
- const minLen = Math.max(0, opts.entropyMinLength ?? 16);
1081
- const threshold = opts.entropyThreshold ?? 3.8;
1082
- if (v.length < minLen)
1083
- return;
1084
- if (!isPrintableAscii(v))
1085
- return;
1086
- const wl = compile$1(opts.entropyWhitelist);
1087
- if (whitelisted(key, wl))
1088
- return;
1089
- const bpc = shannonBitsPerChar(v);
1090
- if (bpc >= threshold) {
1091
- warned.add(key);
1092
- emit(`[entropy] key=${key} score=${bpc.toFixed(2)} len=${String(v.length)} origin=${origin}`);
1093
- }
1094
- };
1095
-
1096
- const DEFAULT_PATTERNS = [
1097
- '\\bsecret\\b',
1098
- '\\btoken\\b',
1099
- '\\bpass(word)?\\b',
1100
- '\\bapi[_-]?key\\b',
1101
- '\\bkey\\b',
1102
- ];
1103
- const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
1104
- const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
1105
- const MASK = '[redacted]';
1106
- /**
1107
- * Utility to redact three related displayed values (parent/dotenv/final)
1108
- * consistently for trace lines.
1109
- */
1110
- const redactTriple = (key, triple, opts) => {
1111
- if (!opts?.redact)
1112
- return triple;
1113
- const regs = compile(opts.redactPatterns);
1114
- const maskIf = (v) => (v && shouldRedactKey(key, regs) ? MASK : v);
1115
- const out = {};
1116
- const p = maskIf(triple.parent);
1117
- const d = maskIf(triple.dotenv);
1118
- const f = maskIf(triple.final);
1119
- if (p !== undefined)
1120
- out.parent = p;
1121
- if (d !== undefined)
1122
- out.dotenv = d;
1123
- if (f !== undefined)
1124
- out.final = f;
1125
- return out;
1126
- };
1127
-
1128
- // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
1129
- const baseRootOptionDefaults = {
1130
- dotenvToken: '.env',
1131
- loadProcess: true,
1132
- logger: console,
1133
- // Diagnostics defaults
1134
- warnEntropy: true,
1135
- entropyThreshold: 3.8,
1136
- entropyMinLength: 16,
1137
- entropyWhitelist: ['^GIT_', '^npm_', '^CI$', 'SHLVL'],
1138
- paths: './',
1139
- pathsDelimiter: ' ',
1140
- privateToken: 'local',
1141
- scripts: {
1142
- 'git-status': {
1143
- cmd: 'git branch --show-current && git status -s -u',
1144
- shell: true,
1145
- },
1146
- },
1147
- shell: true,
1148
- vars: '',
1149
- varsAssignor: '=',
1150
- varsDelimiter: ' ',
1151
- // tri-state flags default to unset unless explicitly provided
1152
- // (debug/log/exclude* resolved via flag utils)
1153
- };
1154
-
1155
- /** @internal */
1156
- const isPlainObject = (value) => value !== null &&
1157
- typeof value === 'object' &&
1158
- Object.getPrototypeOf(value) === Object.prototype;
1159
- const mergeInto = (target, source) => {
1160
- for (const [key, sVal] of Object.entries(source)) {
1161
- if (sVal === undefined)
1162
- continue; // do not overwrite with undefined
1163
- const tVal = target[key];
1164
- if (isPlainObject(tVal) && isPlainObject(sVal)) {
1165
- target[key] = mergeInto({ ...tVal }, sVal);
1166
- }
1167
- else if (isPlainObject(sVal)) {
1168
- target[key] = mergeInto({}, sVal);
1169
- }
1170
- else {
1171
- target[key] = sVal;
1172
- }
1173
- }
1174
- return target;
1175
- };
1176
- /**
1177
- * Perform a deep defaults-style merge across plain objects. *
1178
- * - Only merges plain objects (prototype === Object.prototype).
1179
- * - Arrays and non-objects are replaced, not merged.
1180
- * - `undefined` values are ignored and do not overwrite prior values.
1181
- *
1182
- * @typeParam T - The resulting shape after merging all layers.
1183
- * @param layers - Zero or more partial layers in ascending precedence order.
1184
- * @returns The merged object typed as {@link T}.
1185
- *
1186
- * @example
1187
- * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
1188
- * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
1189
- */
1190
- const defaultsDeep = (...layers) => {
1191
- const result = layers
1192
- .filter(Boolean)
1193
- .reduce((acc, layer) => mergeInto(acc, layer), {});
1194
- return result;
1195
- };
1196
-
1197
- /**
1198
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1199
- * - If the user explicitly enabled the flag, return true.
1200
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1201
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
1202
- *
1203
- * @param exclude - The "on" flag value as parsed by Commander.
1204
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1205
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1206
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1207
- *
1208
- * @example
1209
- * ```ts
1210
- * resolveExclusion(undefined, undefined, true); // => true
1211
- * ```
1212
- */
1213
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1214
- /**
1215
- * Resolve an optional flag with "--exclude-all" overrides.
1216
- * If excludeAll is set and the individual "...-off" is not, force true.
1217
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1218
- * Otherwise, adopt the default (true → set; false/undefined → unset).
1219
- *
1220
- * @param exclude - Individual include/exclude flag.
1221
- * @param excludeOff - Individual "...-off" flag.
1222
- * @param defaultValue - Default for the individual flag.
1223
- * @param excludeAll - Global "exclude-all" flag.
1224
- * @param excludeAllOff - Global "exclude-all-off" flag.
1225
- *
1226
- * @example
1227
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1228
- */
1229
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1230
- // Order of precedence:
1231
- // 1) Individual explicit "on" wins outright.
1232
- // 2) Individual explicit "off" wins over any global.
1233
- // 3) Global exclude-all forces true when not explicitly turned off.
1234
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1235
- // 5) Fall back to the default (true => set; false/undefined => unset).
1236
- (() => {
1237
- // Individual "on"
1238
- if (exclude === true)
1239
- return true;
1240
- // Individual "off"
1241
- if (excludeOff === true)
1242
- return undefined;
1243
- // Global "exclude-all" ON (unless explicitly turned off)
1244
- if (excludeAll === true)
1245
- return true;
1246
- // Global "exclude-all-off" (unless explicitly enabled)
1247
- if (excludeAllOff === true)
1248
- return undefined;
1249
- // Default
1250
- return defaultValue ? true : undefined;
1251
- })();
1252
- /**
1253
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1254
- * delete when undefined; assign when defined — without requiring an index signature on T.
1255
- *
1256
- * @typeParam T - Target object type.
1257
- * @param obj - The object to write to.
1258
- * @param key - The optional boolean property key of {@link T}.
1259
- * @param value - The value to set or `undefined` to unset.
1260
- *
1261
- * @remarks
1262
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1263
- */
1264
- const setOptionalFlag = (obj, key, value) => {
1265
- const target = obj;
1266
- const k = key;
1267
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1268
- if (value === undefined)
1269
- delete target[k];
1270
- else
1271
- target[k] = value;
1272
- };
1273
-
1274
- /**
1275
- * Merge and normalize raw Commander options (current + parent + defaults)
1276
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1277
- * avoid cross-layer coupling; callers may cast as needed.
1278
- */
1279
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1280
- const parent = typeof parentJson === 'string' && parentJson.length > 0
1281
- ? JSON.parse(parentJson)
1282
- : undefined;
1283
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1284
- const current = { ...rest };
1285
- if (typeof scripts === 'string') {
1286
- try {
1287
- current.scripts = JSON.parse(scripts);
1288
- }
1289
- catch {
1290
- // ignore parse errors; leave scripts undefined
1291
- }
1292
- }
1293
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1294
- const d = defaults;
1295
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1296
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1297
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1298
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1299
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1300
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1301
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1302
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1303
- // warnEntropy (tri-state)
1304
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1305
- // Normalize shell for predictability: explicit default shell per OS.
1306
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1307
- let resolvedShell = merged.shell;
1308
- if (shellOff)
1309
- resolvedShell = false;
1310
- else if (resolvedShell === true || resolvedShell === undefined) {
1311
- resolvedShell = defaultShell;
1312
- }
1313
- else if (typeof resolvedShell !== 'string' &&
1314
- typeof defaults.shell === 'string') {
1315
- resolvedShell = defaults.shell;
1316
- }
1317
- merged.shell = resolvedShell;
1318
- const cmd = typeof command === 'string' ? command : undefined;
1319
- return cmd !== undefined ? { merged, command: cmd } : { merged };
1320
- };
1321
-
1322
- /**
1323
- * Dotenv expansion utilities.
1324
- *
1325
- * This module implements recursive expansion of environment-variable
1326
- * references in strings and records. It supports both whitespace and
1327
- * bracket syntaxes with optional defaults:
1328
- *
1329
- * - Whitespace: `$VAR[:default]`
1330
- * - Bracketed: `${VAR[:default]}`
1331
- *
1332
- * Escaped dollar signs (`\$`) are preserved.
1333
- * Unknown variables resolve to empty string unless a default is provided.
1334
- */
1335
- /**
1336
- * Like String.prototype.search but returns the last index.
1337
- * @internal
1338
- */
1339
- const searchLast = (str, rgx) => {
1340
- const matches = Array.from(str.matchAll(rgx));
1341
- return matches.length > 0 ? (matches.slice(-1)[0]?.index ?? -1) : -1;
1342
- };
1343
- const replaceMatch = (value, match, ref) => {
1344
- /**
1345
- * @internal
1346
- */
1347
- const group = match[0];
1348
- const key = match[1];
1349
- const defaultValue = match[2];
1350
- if (!key)
1351
- return value;
1352
- const replacement = value.replace(group, ref[key] ?? defaultValue ?? '');
1353
- return interpolate(replacement, ref);
1354
- };
1355
- const interpolate = (value = '', ref = {}) => {
1356
- /**
1357
- * @internal
1358
- */
1359
- // if value is falsy, return it as is
1360
- if (!value)
1361
- return value;
1362
- // get position of last unescaped dollar sign
1363
- const lastUnescapedDollarSignIndex = searchLast(value, /(?!(?<=\\))\$/g);
1364
- // return value if none found
1365
- if (lastUnescapedDollarSignIndex === -1)
1366
- return value;
1367
- // evaluate the value tail
1368
- const tail = value.slice(lastUnescapedDollarSignIndex);
1369
- // find whitespace pattern: $KEY:DEFAULT
1370
- const whitespacePattern = /^\$([\w]+)(?::([^\s]*))?/;
1371
- const whitespaceMatch = whitespacePattern.exec(tail);
1372
- if (whitespaceMatch != null)
1373
- return replaceMatch(value, whitespaceMatch, ref);
1374
- else {
1375
- // find bracket pattern: ${KEY:DEFAULT}
1376
- const bracketPattern = /^\${([\w]+)(?::([^}]*))?}/;
1377
- const bracketMatch = bracketPattern.exec(tail);
1378
- if (bracketMatch != null)
1379
- return replaceMatch(value, bracketMatch, ref);
1380
- }
1381
- return value;
1382
- };
1383
- /**
1384
- * Recursively expands environment variables in a string. Variables may be
1385
- * presented with optional default as `$VAR[:default]` or `${VAR[:default]}`.
1386
- * Unknown variables will expand to an empty string.
1387
- *
1388
- * @param value - The string to expand.
1389
- * @param ref - The reference object to use for variable expansion.
1390
- * @returns The expanded string.
1391
- *
1392
- * @example
1393
- * ```ts
1394
- * process.env.FOO = 'bar';
1395
- * dotenvExpand('Hello $FOO'); // "Hello bar"
1396
- * dotenvExpand('Hello $BAZ:world'); // "Hello world"
1397
- * ```
1398
- *
1399
- * @remarks
1400
- * The expansion is recursive. If a referenced variable itself contains
1401
- * references, those will also be expanded until a stable value is reached.
1402
- * Escaped references (e.g. `\$FOO`) are preserved as literals.
1403
- */
1404
- const dotenvExpand = (value, ref = process.env) => {
1405
- const result = interpolate(value, ref);
1406
- return result ? result.replace(/\\\$/g, '$') : undefined;
1407
- };
1408
- /**
1409
- * Recursively expands environment variables in a string using `process.env` as
1410
- * the expansion reference. Variables may be presented with optional default as
1411
- * `$VAR[:default]` or `${VAR[:default]}`. Unknown variables will expand to an
1412
- * empty string.
1413
- *
1414
- * @param value - The string to expand.
1415
- * @returns The expanded string.
1416
- *
1417
- * @example
1418
- * ```ts
1419
- * process.env.FOO = 'bar';
1420
- * dotenvExpandFromProcessEnv('Hello $FOO'); // "Hello bar"
1421
- * ```
1422
- */
1423
- const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
1424
-
1425
- // src/GetDotenvOptions.ts
1426
- /**
1427
- * Converts programmatic CLI options to `getDotenv` options. *
1428
- * @param cliOptions - CLI options. Defaults to `{}`.
1429
- *
1430
- * @returns `getDotenv` options.
1431
- */
1432
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
1433
- /**
1434
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
1435
- *
1436
- * - 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`
1437
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
1438
- * - Drops CLI-only keys that have no programmatic equivalent.
1439
- *
1440
- * @remarks
1441
- * Follows exact-optional semantics by not emitting undefined-valued entries.
1442
- */
1443
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
1444
- // Create a shallow copy then delete optional CLI-only keys if present.
1445
- const restObj = { ...rest };
1446
- delete restObj.debug;
1447
- delete restObj.scripts;
1448
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
1449
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
1450
- let parsedVars;
1451
- if (typeof vars === 'string') {
1452
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
1453
- ? RegExp(varsAssignorPattern)
1454
- : (varsAssignor ?? '=')));
1455
- parsedVars = Object.fromEntries(kvPairs);
1456
- }
1457
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
1458
- // Keep only string or undefined values to match ProcessEnv.
1459
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
1460
- parsedVars = Object.fromEntries(entries);
1461
- }
1462
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
1463
- // expectations and the compat test assertions.
1464
- if (parsedVars) {
1465
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
1466
- }
1467
- // Tolerate paths as either a delimited string or string[]
1468
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
1469
- // under the RootOptionsShape (which declares paths as string | undefined).
1470
- const pathsAny = paths;
1471
- const pathsOut = Array.isArray(pathsAny)
1472
- ? pathsAny.filter((p) => typeof p === 'string')
1473
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
1474
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
1475
- return {
1476
- ...restObj,
1477
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
1478
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
1479
- };
1480
- };
1481
-
1482
- const dbg = (...args) => {
1483
- if (process.env.GETDOTENV_DEBUG) {
1484
- // Use stderr to avoid interfering with stdout assertions
1485
- console.error('[getdotenv:alias]', ...args);
1486
- }
1487
- };
1488
- const attachParentAlias = (cli, options, _cmd) => {
1489
- const aliasSpec = typeof options.optionAlias === 'string'
1490
- ? { flags: options.optionAlias, description: undefined, expand: true }
1491
- : options.optionAlias;
1492
- if (!aliasSpec)
1493
- return;
1494
- const deriveKey = (flags) => {
1495
- dbg('install alias option', flags);
1496
- const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
1497
- const name = long.replace(/^--/, '');
1498
- return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
1499
- };
1500
- const aliasKey = deriveKey(aliasSpec.flags);
1501
- // Expose the option on the parent.
1502
- const desc = aliasSpec.description ??
1503
- 'alias of cmd subcommand; provide command tokens (variadic)';
1504
- cli.option(aliasSpec.flags, desc);
1505
- // Tag the just-added parent option for grouped help rendering.
1506
- try {
1507
- const optsArr = cli.options;
1508
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1509
- const last = optsArr[optsArr.length - 1];
1510
- last.__group = 'plugin:cmd';
1511
- }
1512
- }
1513
- catch {
1514
- /* noop */
1515
- }
1516
- // Shared alias executor for either preAction or preSubcommand hooks.
1517
- // Ensure we only execute once even if both hooks fire in a single parse.
1518
- let aliasHandled = false;
1519
- const maybeRunAlias = async (thisCommand) => {
1520
- dbg('alias:maybe:start');
1521
- const raw = thisCommand.rawArgs ?? [];
1522
- const childNames = thisCommand.commands.flatMap((c) => [
1523
- c.name(),
1524
- ...c.aliases(),
1525
- ]);
1526
- const hasSub = childNames.some((n) => raw.includes(n));
1527
- // Read alias value from parent opts.
1528
- const o = thisCommand.opts();
1529
- const val = o[aliasKey];
1530
- const provided = typeof val === 'string'
1531
- ? val.length > 0
1532
- : Array.isArray(val)
1533
- ? val.length > 0
1534
- : false;
1535
- if (!provided || hasSub) {
1536
- dbg('alias:maybe:skip', { provided, hasSub });
1537
- return; // not an alias-only invocation
1538
- }
1539
- if (aliasHandled) {
1540
- dbg('alias:maybe:already-handled');
1541
- return;
1542
- }
1543
- aliasHandled = true;
1544
- dbg('alias-only invocation detected');
1545
- // Merge CLI options and resolve dotenv context.
1546
- const { merged } = resolveCliOptions(o,
1547
- // cast through unknown to avoid readonly -> mutable incompatibilities
1548
- baseRootOptionDefaults, process.env.getDotenvCliOptions);
1549
- const logger = merged.logger ?? console;
1550
- const serviceOptions = getDotenvCliOptions2Options(merged);
1551
- await cli.resolveAndLoad(serviceOptions);
1552
- // Normalize alias value.
1553
- const joined = typeof val === 'string'
1554
- ? val
1555
- : Array.isArray(val)
1556
- ? val.map(String).join(' ')
1557
- : '';
1558
- const input = aliasSpec.expand === false
1559
- ? joined
1560
- : (dotenvExpandFromProcessEnv(joined) ?? joined);
1561
- dbg('resolved input', { input });
1562
- const resolved = resolveCommand(merged.scripts, input);
1563
- const lg = logger;
1564
- if (merged.debug) {
1565
- (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
1566
- }
1567
- const { logger: _omit, ...envBag } = merged;
1568
- // Test guard: when running under tests, prefer stdio: 'inherit' to avoid
1569
- // assertions depending on captured stdio; ignore GETDOTENV_STDIO/capture.
1570
- const underTests = process.env.GETDOTENV_TEST === '1' ||
1571
- typeof process.env.VITEST_WORKER_ID === 'string';
1572
- const forceExit = process.env.GETDOTENV_FORCE_EXIT === '1';
1573
- const capture = !underTests &&
1574
- (process.env.GETDOTENV_STDIO === 'pipe' ||
1575
- Boolean(merged.capture));
1576
- dbg('run:start', { capture, shell: merged.shell });
1577
- // Prefer explicit env injection: include resolved dotenv map to avoid leaking
1578
- // parent process.env secrets when exclusions are set.
1579
- const ctx = cli.getCtx();
1580
- const dotenv = (ctx?.dotenv ?? {});
1581
- // Diagnostics: --trace [keys...]
1582
- const traceOpt = merged.trace;
1583
- if (traceOpt) {
1584
- const parentKeys = Object.keys(process.env);
1585
- const dotenvKeys = Object.keys(dotenv);
1586
- const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
1587
- const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
1588
- const childEnvPreview = {
1589
- ...process.env,
1590
- ...dotenv,
1591
- };
1592
- for (const k of keys) {
1593
- const parent = process.env[k];
1594
- const dot = dotenv[k];
1595
- const final = childEnvPreview[k];
1596
- const origin = dot !== undefined
1597
- ? 'dotenv'
1598
- : parent !== undefined
1599
- ? 'parent'
1600
- : 'unset';
1601
- // Build redact options and triple bag without undefined-valued fields
1602
- const redOpts = {};
1603
- const redFlag = merged.redact;
1604
- const redPatterns = merged
1605
- .redactPatterns;
1606
- if (redFlag)
1607
- redOpts.redact = true;
1608
- if (redFlag && Array.isArray(redPatterns))
1609
- redOpts.redactPatterns = redPatterns;
1610
- const tripleBag = {};
1611
- if (parent !== undefined)
1612
- tripleBag.parent = parent;
1613
- if (dot !== undefined)
1614
- tripleBag.dotenv = dot;
1615
- if (final !== undefined)
1616
- tripleBag.final = final;
1617
- const triple = redactTriple(k, tripleBag, redOpts);
1618
- process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
1619
- const entOpts = {};
1620
- const warnEntropy = merged.warnEntropy;
1621
- const entropyThreshold = merged
1622
- .entropyThreshold;
1623
- const entropyMinLength = merged
1624
- .entropyMinLength;
1625
- const entropyWhitelist = merged
1626
- .entropyWhitelist;
1627
- if (typeof warnEntropy === 'boolean')
1628
- entOpts.warnEntropy = warnEntropy;
1629
- if (typeof entropyThreshold === 'number')
1630
- entOpts.entropyThreshold = entropyThreshold;
1631
- if (typeof entropyMinLength === 'number')
1632
- entOpts.entropyMinLength = entropyMinLength;
1633
- if (Array.isArray(entropyWhitelist))
1634
- entOpts.entropyWhitelist = entropyWhitelist;
1635
- maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
1636
- }
1637
- }
1638
- let exitCode = Number.NaN;
1639
- try {
1640
- // Resolve shell and preserve argv for Node -e snippets under shell-off.
1641
- const shellSetting = resolveShell(merged.scripts, input, merged.shell);
1642
- let commandArg = resolved;
1643
- /** * Special-case: when shell is OFF and no script alias remap occurred
1644
- * (resolved === input), treat a Node eval payload as an argv array to
1645
- * avoid lossy re-tokenization of the code string.
1646
- *
1647
- * Examples handled:
1648
- * "node -e \"console.log(JSON.stringify(...))\""
1649
- * "node --eval 'console.log(...)'"
1650
- *
1651
- * We peel exactly one pair of symmetric outer quotes from the code
1652
- * argument when present; inner quotes remain untouched.
1653
- */
1654
- if (shellSetting === false && resolved === input) {
1655
- // Helper: strip one symmetric outer quote layer
1656
- const stripOne = (s) => {
1657
- if (s.length < 2)
1658
- return s;
1659
- const a = s.charAt(0);
1660
- const b = s.charAt(s.length - 1);
1661
- const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
1662
- return symmetric ? s.slice(1, -1) : s;
1663
- };
1664
- // Normalize whole input once for robust matching
1665
- const normalized = stripOne(input.trim());
1666
- // First try a lightweight regex on the normalized string
1667
- const m = /^\s*node\s+(--eval|-e)\s+([\s\S]+)$/i.exec(normalized);
1668
- if (m && typeof m[1] === 'string' && typeof m[2] === 'string') {
1669
- const evalFlag = m[1];
1670
- let codeArg = m[2].trim();
1671
- codeArg = stripOne(codeArg);
1672
- const flag = evalFlag.startsWith('--') ? '--eval' : '-e';
1673
- commandArg = ['node', flag, codeArg];
1674
- }
1675
- else {
1676
- // Fallback: tokenize and detect node -e/--eval form
1677
- const parts = tokenize(input);
1678
- if (parts.length >= 3) {
1679
- // Narrow under noUncheckedIndexedAccess
1680
- const p0 = parts[0];
1681
- const p1 = parts[1];
1682
- if (p0?.toLowerCase() === 'node' &&
1683
- (p1 === '-e' || p1 === '--eval')) {
1684
- commandArg = parts;
1685
- }
1686
- }
1687
- }
1688
- }
1689
- exitCode = await runCommand(commandArg, shellSetting, {
1690
- env: buildSpawnEnv(process.env, {
1691
- ...dotenv,
1692
- getDotenvCliOptions: JSON.stringify(envBag),
1693
- }),
1694
- stdio: capture ? 'pipe' : 'inherit',
1695
- });
1696
- dbg('run:done', { exitCode });
1697
- }
1698
- catch (err) {
1699
- const code = typeof err.exitCode === 'number'
1700
- ? err.exitCode
1701
- : 1;
1702
- dbg('run:error', { exitCode: code, error: String(err) });
1703
- if (!underTests) {
1704
- dbg('process.exit (error path)', { exitCode: code });
1705
- process.exit(code);
1706
- }
1707
- else {
1708
- dbg('process.exit suppressed for tests (error path)', {
1709
- exitCode: code,
1710
- });
1711
- }
1712
- return;
1713
- }
1714
- if (!Number.isNaN(exitCode)) {
1715
- dbg('process.exit', { exitCode });
1716
- process.exit(exitCode);
1717
- }
1718
- // Fallback: Some environments may not surface a numeric exitCode even on success.
1719
- // Always terminate alias-only invocations outside tests to avoid hanging the process,
1720
- // regardless of capture/GETDOTENV_STDIO. Under tests, suppress to keep the runner alive.
1721
- if (!underTests) {
1722
- dbg('process.exit (fallback: non-numeric exitCode)', { exitCode: 0 });
1723
- process.exit(0);
1724
- }
1725
- else {
1726
- dbg('process.exit (fallback suppressed for tests: non-numeric exitCode)', { exitCode: 0 });
1727
- }
1728
- // Optional last-resort guard: force an exit on the next tick when enabled.
1729
- // Intended for diagnosing environments where the process appears to linger
1730
- // despite reaching the success/error handlers above. Disabled under tests.
1731
- if (forceExit) {
1732
- try {
1733
- if (process.env.GETDOTENV_DEBUG_VERBOSE) {
1734
- const getHandles = process._getActiveHandles;
1735
- const handles = typeof getHandles === 'function' ? getHandles() : [];
1736
- dbg('active handles before forced exit', {
1737
- count: Array.isArray(handles) ? handles.length : undefined,
1738
- });
1739
- }
1740
- }
1741
- catch {
1742
- // best-effort only
1743
- }
1744
- const code = Number.isNaN(exitCode) ? 0 : exitCode;
1745
- dbg('process.exit (forced)', { exitCode: code });
1746
- setImmediate(() => process.exit(code));
1747
- }
1748
- };
1749
- // Execute alias-only invocations whether the root handles the action // itself (preAction) or Commander routes to a default subcommand (preSubcommand).
1750
- cli.hook('preAction', async (thisCommand, _actionCommand) => {
1751
- await maybeRunAlias(thisCommand);
1752
- });
1753
- cli.hook('preSubcommand', async (thisCommand) => {
1754
- await maybeRunAlias(thisCommand);
1755
- });
1756
- };
1757
-
1758
- /**+ Cmd plugin: executes a command using the current getdotenv CLI context.
1759
- *
1760
- * - Joins positional args into a single command string.
1761
- * - Resolves scripts and shell settings using shared helpers.
1762
- * - Forwards merged CLI options to subprocesses via
1763
- * process.env.getDotenvCliOptions for nested CLI behavior. */
1764
- const cmdPlugin = (options = {}) => definePlugin({
1765
- id: 'cmd',
1766
- setup(cli) {
1767
- const aliasSpec = typeof options.optionAlias === 'string'
1768
- ? { flags: options.optionAlias}
1769
- : options.optionAlias;
1770
- const deriveKey = (flags) => {
1771
- const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
1772
- const name = long.replace(/^--/, '');
1773
- return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
1774
- };
1775
- const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
1776
- const cmd = new commander.Command()
1777
- .name('cmd')
1778
- .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
1779
- .configureHelp({ showGlobalOptions: true })
1780
- .enablePositionalOptions()
1781
- .passThroughOptions()
1782
- .argument('[command...]')
1783
- .action(async (commandParts, _opts, thisCommand) => {
1784
- // Commander passes positional tokens as the first action argument
1785
- const args = Array.isArray(commandParts) ? commandParts : [];
1786
- // No-op when invoked as the default command with no args.
1787
- if (args.length === 0)
1788
- return;
1789
- const parent = thisCommand.parent;
1790
- if (!parent)
1791
- throw new Error('parent command not found'); // Conflict detection: if an alias option is present on parent, do not
1792
- // also accept positional cmd args.
1793
- if (aliasKey) {
1794
- const pv = parent.opts();
1795
- const ov = pv[aliasKey];
1796
- if (ov !== undefined) {
1797
- const merged = parent.getDotenvCliOptions ?? {};
1798
- const logger = merged.logger ?? console;
1799
- const lr = logger;
1800
- const emit = lr.error ?? lr.log;
1801
- emit(`--${aliasKey} option conflicts with cmd subcommand.`);
1802
- process.exit(0);
1803
- }
1804
- }
1805
- // Merged CLI options are persisted by the shipped CLI preSubcommand hook.
1806
- const merged = parent.getDotenvCliOptions ?? {};
1807
- const logger = merged.logger ?? console;
1808
- // Join positional args into the command string.
1809
- const input = args.map(String).join(' ');
1810
- // Resolve command and shell using shared helpers.
1811
- const scripts = merged.scripts;
1812
- const shell = merged.shell;
1813
- const resolved = resolveCommand(scripts, input);
1814
- if (merged.debug) {
1815
- const lg = logger;
1816
- (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
1817
- }
1818
- // Round-trip CLI options for nested getdotenv invocations.
1819
- // Omit logger (functions are not serializable).
1820
- const { logger: _omit, ...envBag } = merged;
1821
- const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
1822
- Boolean(merged.capture);
1823
- // Prefer explicit env injection using the resolved dotenv map.
1824
- const ctx = cli.getCtx();
1825
- const dotenv = (ctx?.dotenv ?? {});
1826
- // Diagnostics: --trace [keys...] (space-delimited keys if provided; all keys when true)
1827
- const traceOpt = merged.trace;
1828
- if (traceOpt) {
1829
- // Determine keys to trace: all keys (parent ∪ dotenv) or selected.
1830
- const parentKeys = Object.keys(process.env);
1831
- const dotenvKeys = Object.keys(dotenv);
1832
- const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
1833
- const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
1834
- // Child env preview (as composed below; excluding getDotenvCliOptions)
1835
- const childEnvPreview = {
1836
- ...process.env,
1837
- ...dotenv,
1838
- };
1839
- for (const k of keys) {
1840
- const parent = process.env[k];
1841
- const dot = dotenv[k];
1842
- const final = childEnvPreview[k];
1843
- const origin = dot !== undefined
1844
- ? 'dotenv'
1845
- : parent !== undefined
1846
- ? 'parent'
1847
- : 'unset';
1848
- // Apply presentation-time redaction (if enabled)
1849
- const redFlag = merged.redact;
1850
- const redPatterns = merged
1851
- .redactPatterns;
1852
- const redOpts = {};
1853
- if (redFlag)
1854
- redOpts.redact = true;
1855
- if (redFlag && Array.isArray(redPatterns))
1856
- redOpts.redactPatterns = redPatterns;
1857
- const tripleBag = {};
1858
- if (parent !== undefined)
1859
- tripleBag.parent = parent;
1860
- if (dot !== undefined)
1861
- tripleBag.dotenv = dot;
1862
- if (final !== undefined)
1863
- tripleBag.final = final;
1864
- const triple = redactTriple(k, tripleBag, redOpts);
1865
- // Emit concise diagnostic line to stderr.
1866
- process.stderr.write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}\n`);
1867
- // Optional entropy warning (once-per-key)
1868
- const entOpts = {};
1869
- const warnEntropy = merged
1870
- .warnEntropy;
1871
- const entropyThreshold = merged.entropyThreshold;
1872
- const entropyMinLength = merged.entropyMinLength;
1873
- const entropyWhitelist = merged.entropyWhitelist;
1874
- if (typeof warnEntropy === 'boolean')
1875
- entOpts.warnEntropy = warnEntropy;
1876
- if (typeof entropyThreshold === 'number')
1877
- entOpts.entropyThreshold = entropyThreshold;
1878
- if (typeof entropyMinLength === 'number')
1879
- entOpts.entropyMinLength = entropyMinLength;
1880
- if (Array.isArray(entropyWhitelist))
1881
- entOpts.entropyWhitelist = entropyWhitelist;
1882
- maybeWarnEntropy(k, final, origin, entOpts, (line) => process.stderr.write(line + '\n'));
1883
- }
1884
- }
1885
- const shellSetting = resolveShell(scripts, input, shell);
1886
- /**
1887
- * Preserve original argv array when:
1888
- * - shell is OFF (plain execa), and
1889
- * - no script alias remap occurred (resolved === input).
1890
- *
1891
- * This avoids lossy re-tokenization of code snippets such as:
1892
- * node -e "console.log(process.env.APP_SECRET ?? '')"
1893
- * where quotes may have been stripped by the parent shell and
1894
- * spaces inside the code must remain a single argument.
1895
- */
1896
- const commandArg = shellSetting === false && resolved === input
1897
- ? args.map(String)
1898
- : resolved;
1899
- await runCommand(commandArg, shellSetting, {
1900
- env: buildSpawnEnv(process.env, {
1901
- ...dotenv,
1902
- getDotenvCliOptions: JSON.stringify(envBag),
1903
- }),
1904
- stdio: capture ? 'pipe' : 'inherit',
1905
- });
1906
- });
1907
- if (options.asDefault)
1908
- cli.addCommand(cmd, { isDefault: true });
1909
- else
1910
- cli.addCommand(cmd);
1911
- // Parent-attached option alias (optional).
1912
- if (aliasSpec)
1913
- attachParentAlias(cli, options);
1914
- },
1915
- });
1916
-
1917
- const demoPlugin = () => definePlugin({
1918
- id: 'demo',
1919
- setup(cli) {
1920
- const logger = console;
1921
- const ns = cli
1922
- .ns('demo')
1923
- .description('Educational demo of host/plugin features (context, child exec, scripts/shell)');
1924
- /**
1925
- * demo ctx
1926
- * Print a summary of the current dotenv context.
1927
- *
1928
- * Notes:
1929
- * - The host resolves context once per invocation in a preSubcommand hook
1930
- * (added by enhanceGetDotenvCli.passOptions() in the shipped CLI).
1931
- * - ctx.dotenv contains the final merged values after overlays/dynamics.
1932
- */
1933
- ns.command('ctx')
1934
- .description('Print a summary of the current dotenv context')
1935
- .action(() => {
1936
- const ctx = cli.getCtx();
1937
- const dotenv = ctx?.dotenv ?? {};
1938
- const keys = Object.keys(dotenv).sort();
1939
- const sample = keys.slice(0, 5);
1940
- logger.log('[demo] Context summary:');
1941
- logger.log(`- keys: ${keys.length.toString()}`);
1942
- logger.log(`- sample keys: ${sample.join(', ') || '(none)'}`);
1943
- logger.log('- tip: use "--trace [keys...]" for per-key diagnostics');
1944
- });
1945
- /**
1946
- * demo run [--print KEY]
1947
- * Execute a small child process that prints a dotenv value.
1948
- *
1949
- * Design:
1950
- * - Use shell-off + argv array to avoid cross-platform quoting pitfalls.
1951
- * - Inject ctx.dotenv explicitly into the child env.
1952
- * - Inherit stdio so output streams live (works well outside CI).
1953
- *
1954
- * Tip:
1955
- * - For deterministic capture in CI, run with "--capture" (or set
1956
- * GETDOTENV_STDIO=pipe). The shipped CLI honors both.
1957
- */
1958
- ns.command('run')
1959
- .description('Run a small child process under the current dotenv (shell-off)')
1960
- .option('--print <key>', 'dotenv key to print', 'APP_SETTING')
1961
- .action(async (opts) => {
1962
- const key = typeof opts.print === 'string' && opts.print.length > 0
1963
- ? opts.print
1964
- : 'APP_SETTING';
1965
- // Build a minimal node -e payload via argv array (avoid quoting issues).
1966
- const code = `console.log(process.env.${key} ?? "")`;
1967
- const ctx = cli.getCtx();
1968
- const dotenv = (ctx?.dotenv ?? {});
1969
- // Inherit stdio for an interactive demo. Use --capture for CI.
1970
- await runCommand(['node', '-e', code], false, {
1971
- env: { ...process.env, ...dotenv },
1972
- stdio: 'inherit',
1973
- });
1974
- });
1975
- /**
1976
- * demo script [command...]
1977
- * Resolve and execute a command using the current scripts table and
1978
- * shell preference (with per-script overrides).
1979
- *
1980
- * How it works:
1981
- * - We read the merged CLI options persisted by the shipped CLI’s
1982
- * passOptions() hook on the current command instance’s parent.
1983
- * - resolveCommand resolves a script name → cmd or passes through a raw
1984
- * command string.
1985
- * - resolveShell chooses the appropriate shell:
1986
- * scripts[name].shell ?? global shell (string|boolean).
1987
- */
1988
- ns.command('script')
1989
- .description('Resolve a command via scripts and execute it with the proper shell')
1990
- .argument('[command...]')
1991
- .action(async (commandParts, _opts, thisCommand) => {
1992
- // Safely access the parent’s merged options (installed by passOptions()).
1993
- const parent = thisCommand.parent;
1994
- const bag = (parent?.getDotenvCliOptions ?? {});
1995
- const input = Array.isArray(commandParts)
1996
- ? commandParts.map(String).join(' ')
1997
- : '';
1998
- if (!input) {
1999
- logger.log('[demo] Please provide a command or script name, e.g. "echo OK" or "git-status".');
2000
- return;
2001
- }
2002
- const resolved = resolveCommand(bag?.scripts, input);
2003
- const shell = resolveShell(bag?.scripts, input, bag?.shell);
2004
- // Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
2005
- const ctx = cli.getCtx();
2006
- const dotenv = (ctx?.dotenv ?? {});
2007
- await runCommand(resolved, shell, {
2008
- env: { ...process.env, ...dotenv },
2009
- stdio: 'inherit',
2010
- });
2011
- });
2012
- },
2013
- /**
2014
- * Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
2015
- * For the demo we just log once to hint where such logic would live.
2016
- */
2017
- afterResolve(_cli, ctx) {
2018
- const keys = Object.keys(ctx.dotenv);
2019
- if (keys.length > 0) {
2020
- // Keep noise low; a single-line breadcrumb is sufficient for the demo.
2021
- console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
2022
- }
2023
- },
2024
- });
2025
-
2026
- const ensureDir = async (p) => {
2027
- await fs.ensureDir(p);
2028
- return p;
2029
- };
2030
- const writeFile = async (dest, data) => {
2031
- await ensureDir(path.dirname(dest));
2032
- await fs.writeFile(dest, data, 'utf-8');
2033
- };
2034
- const copyTextFile = async (src, dest, substitutions) => {
2035
- const contents = await fs.readFile(src, 'utf-8');
2036
- const out = substitutions && Object.keys(substitutions).length > 0
2037
- ? Object.entries(substitutions).reduce((acc, [k, v]) => acc.split(k).join(v), contents)
2038
- : contents;
2039
- await writeFile(dest, out);
2040
- };
2041
- /**
2042
- * Ensure a set of lines exist (exact match) in a file. Creates the file
2043
- * when missing. Returns whether it was created or changed.
2044
- */
2045
- const ensureLines = async (filePath, lines) => {
2046
- const exists = await fs.pathExists(filePath);
2047
- const current = exists ? await fs.readFile(filePath, 'utf-8') : '';
2048
- const curLines = current.split(/\r?\n/);
2049
- const have = new Set(curLines.filter((l) => l.length > 0));
2050
- let mutated = false;
2051
- for (const l of lines) {
2052
- if (!have.has(l)) {
2053
- curLines.push(l);
2054
- have.add(l);
2055
- mutated = true;
2056
- }
2057
- }
2058
- // Normalize to LF and ensure trailing newline
2059
- const next = curLines.filter((l) => l.length > 0).join('\n') + '\n';
2060
- if (!exists) {
2061
- await writeFile(filePath, next);
2062
- return { created: true, changed: true };
2063
- }
2064
- if (mutated) {
2065
- await fs.writeFile(filePath, next, 'utf-8');
2066
- return { created: false, changed: true };
2067
- }
2068
- return { created: false, changed: false };
2069
- };
2070
-
2071
- // Templates root used by the scaffolder
2072
- const TEMPLATES_ROOT = path.resolve('templates');
2073
-
2074
- const planConfigCopies = ({ format, withLocal, destRoot, }) => {
2075
- const copies = [];
2076
- if (format === 'json') {
2077
- copies.push({
2078
- src: path.join(TEMPLATES_ROOT, 'config', 'json', 'public', 'getdotenv.config.json'),
2079
- dest: path.join(destRoot, 'getdotenv.config.json'),
2080
- });
2081
- if (withLocal) {
2082
- copies.push({
2083
- src: path.join(TEMPLATES_ROOT, 'config', 'json', 'local', 'getdotenv.config.local.json'),
2084
- dest: path.join(destRoot, 'getdotenv.config.local.json'),
2085
- });
2086
- }
2087
- }
2088
- else if (format === 'yaml') {
2089
- copies.push({
2090
- src: path.join(TEMPLATES_ROOT, 'config', 'yaml', 'public', 'getdotenv.config.yaml'),
2091
- dest: path.join(destRoot, 'getdotenv.config.yaml'),
2092
- });
2093
- if (withLocal) {
2094
- copies.push({
2095
- src: path.join(TEMPLATES_ROOT, 'config', 'yaml', 'local', 'getdotenv.config.local.yaml'),
2096
- dest: path.join(destRoot, 'getdotenv.config.local.yaml'),
2097
- });
2098
- }
2099
- }
2100
- else if (format === 'js') {
2101
- copies.push({
2102
- src: path.join(TEMPLATES_ROOT, 'config', 'js', 'getdotenv.config.js'),
2103
- dest: path.join(destRoot, 'getdotenv.config.js'),
2104
- });
2105
- }
2106
- else {
2107
- copies.push({
2108
- src: path.join(TEMPLATES_ROOT, 'config', 'ts', 'getdotenv.config.ts'),
2109
- dest: path.join(destRoot, 'getdotenv.config.ts'),
2110
- });
2111
- }
2112
- return copies;
2113
- };
2114
- const planCliCopies = ({ cliName, destRoot, }) => {
2115
- const subs = { __CLI_NAME__: cliName };
2116
- const base = path.join(destRoot, 'src', 'cli', cliName);
2117
- return [
2118
- {
2119
- src: path.join(TEMPLATES_ROOT, 'cli', 'ts', 'index.ts'),
2120
- dest: path.join(base, 'index.ts'),
2121
- subs,
2122
- },
2123
- {
2124
- src: path.join(TEMPLATES_ROOT, 'cli', 'ts', 'plugins', 'hello.ts'),
2125
- dest: path.join(base, 'plugins', 'hello.ts'),
2126
- subs,
2127
- },
2128
- ];
2129
- };
2130
-
2131
- /**
2132
- * Determine whether the current environment should be treated as non-interactive.
2133
- * CI heuristics include: CI, GITHUB_ACTIONS, BUILDKITE, TEAMCITY_VERSION, TF_BUILD.
2134
- */
2135
- const isNonInteractive = () => {
2136
- const ciLike = process.env.CI ||
2137
- process.env.GITHUB_ACTIONS ||
2138
- process.env.BUILDKITE ||
2139
- process.env.TEAMCITY_VERSION ||
2140
- process.env.TF_BUILD;
2141
- return Boolean(ciLike) || !(node_process.stdin.isTTY && node_process.stdout.isTTY);
2142
- };
2143
- const promptDecision = async (filePath, logger, rl) => {
2144
- logger.log(`File exists: ${filePath}\nChoose: [o]verwrite, [e]xample, [s]kip, [O]verwrite All, [E]xample All, [S]kip All`);
2145
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2146
- while (true) {
2147
- const a = (await rl.question('> ')).trim();
2148
- const valid = ['o', 'e', 's', 'O', 'E', 'S'];
2149
- if (valid.includes(a))
2150
- return a;
2151
- logger.log('Please enter one of: o e s O E S');
2152
- }
2153
- };
2154
-
2155
- /**
2156
- * Requirements: Init scaffolding plugin with collision flow and CI detection.
2157
- * Note: Large file scheduled for decomposition; tracked in stan.todo.md.
2158
- */
2159
- const initPlugin = (opts = {}) => definePlugin({
2160
- id: 'init',
2161
- setup(cli) {
2162
- const logger = opts.logger ?? console;
2163
- const cmd = cli
2164
- .ns('init')
2165
- .description('Scaffold getdotenv config files and a host-based CLI skeleton.')
2166
- .argument('[dest]', 'destination path (default: ./)', '.')
2167
- .option('--config-format <format>', 'config format: json|yaml|js|ts', 'json')
2168
- .option('--with-local', 'include .local config variant')
2169
- .option('--dynamic', 'include dynamic examples (JS/TS configs)')
2170
- .option('--cli-name <string>', 'CLI name for skeleton and tokens')
2171
- .option('--force', 'overwrite all existing files')
2172
- .option('--yes', 'skip all collisions (no overwrite)')
2173
- .action(async (destArg) => {
2174
- // Read options directly from the captured command instance.
2175
- // Cast to a plain record to satisfy exact-optional and lint safety.
2176
- const o = cmd.opts() ?? {};
2177
- const destRel = typeof destArg === 'string' && destArg.length > 0 ? destArg : '.';
2178
- const cwd = process.cwd();
2179
- const destRoot = path.resolve(cwd, destRel);
2180
- const formatInput = o.configFormat;
2181
- const formatRaw = typeof formatInput === 'string'
2182
- ? formatInput.toLowerCase()
2183
- : 'json';
2184
- const format = (['json', 'yaml', 'js', 'ts'].includes(formatRaw)
2185
- ? formatRaw
2186
- : 'json');
2187
- const withLocal = !!o.withLocal;
2188
- // dynamic flag reserved for future template variants; present for UX compatibility
2189
- void o.dynamic;
2190
- // CLI name default: --cli-name | basename(dest) | 'mycli'
2191
- const cliName = (typeof o.cliName === 'string' && o.cliName.length > 0
2192
- ? o.cliName
2193
- : path.basename(destRoot) || 'mycli') || 'mycli';
2194
- // Precedence: --force > --yes > auto-detect(non-interactive => yes)
2195
- const force = !!o.force;
2196
- const yes = !!o.yes || (!force && isNonInteractive());
2197
- // Build copy plan
2198
- const cfgCopies = planConfigCopies({ format, withLocal, destRoot });
2199
- const cliCopies = planCliCopies({ cliName, destRoot });
2200
- const copies = [...cfgCopies, ...cliCopies];
2201
- // Interactive state
2202
- let globalDecision;
2203
- const rl = promises.createInterface({ input: node_process.stdin, output: node_process.stdout });
2204
- try {
2205
- for (const item of copies) {
2206
- const exists = await fs.pathExists(item.dest);
2207
- if (!exists) {
2208
- const subs = item.subs ?? {};
2209
- await copyTextFile(item.src, item.dest, subs);
2210
- logger.log(`Created ${path.relative(cwd, item.dest)}`);
2211
- continue;
2212
- }
2213
- // Collision
2214
- if (force) {
2215
- const subs = item.subs ?? {};
2216
- await copyTextFile(item.src, item.dest, subs);
2217
- logger.log(`Overwrote ${path.relative(cwd, item.dest)}`);
2218
- continue;
2219
- }
2220
- if (yes) {
2221
- logger.log(`Skipped ${path.relative(cwd, item.dest)}`);
2222
- continue;
2223
- }
2224
- let decision = globalDecision;
2225
- if (!decision) {
2226
- const a = await promptDecision(item.dest, logger, rl);
2227
- if (a === 'O') {
2228
- globalDecision = 'overwrite';
2229
- decision = 'overwrite';
2230
- }
2231
- else if (a === 'E') {
2232
- globalDecision = 'example';
2233
- decision = 'example';
2234
- }
2235
- else if (a === 'S') {
2236
- globalDecision = 'skip';
2237
- decision = 'skip';
2238
- }
2239
- else {
2240
- decision =
2241
- a === 'o' ? 'overwrite' : a === 'e' ? 'example' : 'skip';
2242
- }
2243
- }
2244
- if (decision === 'overwrite') {
2245
- const subs = item.subs ?? {};
2246
- await copyTextFile(item.src, item.dest, subs);
2247
- logger.log(`Overwrote ${path.relative(cwd, item.dest)}`);
2248
- }
2249
- else if (decision === 'example') {
2250
- const destEx = `${item.dest}.example`;
2251
- const subs = item.subs ?? {};
2252
- await copyTextFile(item.src, destEx, subs);
2253
- logger.log(`Wrote example ${path.relative(cwd, destEx)}`);
2254
- }
2255
- else {
2256
- logger.log(`Skipped ${path.relative(cwd, item.dest)}`);
2257
- }
2258
- }
2259
- // Ensure .gitignore includes local config patterns.
2260
- const giPath = path.join(destRoot, '.gitignore');
2261
- const { created, changed } = await ensureLines(giPath, [
2262
- 'getdotenv.config.local.*',
2263
- '*.local',
2264
- ]);
2265
- if (created) {
2266
- logger.log(`Created ${path.relative(cwd, giPath)}`);
2267
- }
2268
- else if (changed) {
2269
- logger.log(`Updated ${path.relative(cwd, giPath)}`);
2270
- }
2271
- }
2272
- finally {
2273
- rl.close();
2274
- }
2275
- });
2276
- },
2277
- });
2278
-
2279
- exports.awsPlugin = awsPlugin;
2280
- exports.batchPlugin = batchPlugin;
2281
- exports.cmdPlugin = cmdPlugin;
2282
- exports.demoPlugin = demoPlugin;
2283
- exports.initPlugin = initPlugin;