@karmaniverous/get-dotenv 5.2.4 → 5.2.6

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.
@@ -2,17 +2,10 @@
2
2
 
3
3
  var commander = require('commander');
4
4
  var execa = require('execa');
5
- var fs = require('fs-extra');
6
- var packageDirectory = require('package-directory');
7
- var url = require('url');
8
- var path = require('path');
9
- var zod = require('zod');
10
- var YAML = require('yaml');
11
- var nanoid = require('nanoid');
12
- var dotenv = require('dotenv');
13
- var crypto = require('crypto');
5
+ require('fs-extra');
6
+ require('package-directory');
7
+ require('path');
14
8
 
15
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
9
  // Minimal tokenizer for shell-off execution:
17
10
  // Splits by whitespace while preserving quoted segments (single or double quotes).
18
11
  const tokenize = (command) => {
@@ -278,19 +271,6 @@ const DEFAULT_PATTERNS = [
278
271
  const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
279
272
  const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
280
273
  const MASK = '[redacted]';
281
- /**
282
- * Produce a shallow redacted copy of an env-like object for display.
283
- */
284
- const redactObject = (obj, opts) => {
285
- if (!opts?.redact)
286
- return { ...obj };
287
- const regs = compile(opts.redactPatterns);
288
- const out = {};
289
- for (const [k, v] of Object.entries(obj)) {
290
- out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
291
- }
292
- return out;
293
- };
294
274
  /**
295
275
  * Utility to redact three related displayed values (parent/dotenv/final)
296
276
  * consistently for trace lines.
@@ -368,10 +348,8 @@ const baseRootOptionDefaults = {
368
348
  // (debug/log/exclude* resolved via flag utils)
369
349
  };
370
350
 
371
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
372
-
373
351
  /** @internal */
374
- const isPlainObject$1 = (value) => value !== null &&
352
+ const isPlainObject = (value) => value !== null &&
375
353
  typeof value === 'object' &&
376
354
  Object.getPrototypeOf(value) === Object.prototype;
377
355
  const mergeInto = (target, source) => {
@@ -379,10 +357,10 @@ const mergeInto = (target, source) => {
379
357
  if (sVal === undefined)
380
358
  continue; // do not overwrite with undefined
381
359
  const tVal = target[key];
382
- if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
360
+ if (isPlainObject(tVal) && isPlainObject(sVal)) {
383
361
  target[key] = mergeInto({ ...tVal }, sVal);
384
362
  }
385
- else if (isPlainObject$1(sVal)) {
363
+ else if (isPlainObject(sVal)) {
386
364
  target[key] = mergeInto({}, sVal);
387
365
  }
388
366
  else {
@@ -412,370 +390,129 @@ const defaultsDeep = (...layers) => {
412
390
  return result;
413
391
  };
414
392
 
415
- // src/GetDotenvOptions.ts
416
- const getDotenvOptionsFilename = 'getdotenv.config.json';
417
393
  /**
418
- * Converts programmatic CLI options to `getDotenv` options. *
419
- * @param cliOptions - CLI options. Defaults to `{}`.
394
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
395
+ * - If the user explicitly enabled the flag, return true.
396
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
397
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
420
398
  *
421
- * @returns `getDotenv` options.
399
+ * @param exclude - The "on" flag value as parsed by Commander.
400
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
401
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
402
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * resolveExclusion(undefined, undefined, true); // => true
407
+ * ```
422
408
  */
423
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
424
- /**
425
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
426
- *
427
- * - 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`
428
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
429
- * - Drops CLI-only keys that have no programmatic equivalent.
430
- *
431
- * @remarks
432
- * Follows exact-optional semantics by not emitting undefined-valued entries.
433
- */
434
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
435
- // Create a shallow copy then delete optional CLI-only keys if present.
436
- const restObj = { ...rest };
437
- delete restObj.debug;
438
- delete restObj.scripts;
439
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
440
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
441
- let parsedVars;
442
- if (typeof vars === 'string') {
443
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
444
- ? RegExp(varsAssignorPattern)
445
- : (varsAssignor ?? '=')));
446
- parsedVars = Object.fromEntries(kvPairs);
447
- }
448
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
449
- // Keep only string or undefined values to match ProcessEnv.
450
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
451
- parsedVars = Object.fromEntries(entries);
452
- }
453
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
454
- // expectations and the compat test assertions.
455
- if (parsedVars) {
456
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
457
- }
458
- // Tolerate paths as either a delimited string or string[]
459
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
460
- // under the RootOptionsShape (which declares paths as string | undefined).
461
- const pathsAny = paths;
462
- const pathsOut = Array.isArray(pathsAny)
463
- ? pathsAny.filter((p) => typeof p === 'string')
464
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
465
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
466
- return {
467
- ...restObj,
468
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
469
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
470
- };
471
- };
472
- const resolveGetDotenvOptions = async (customOptions) => {
473
- /**
474
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
475
- *
476
- * 1. Base defaults derived from the CLI generator defaults
477
- * ({@link baseGetDotenvCliOptions}).
478
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
479
- * package root (if present).
480
- * 3. The provided {@link customOptions}.
481
- *
482
- * The result preserves explicit empty values and drops only `undefined`.
483
- *
484
- * @returns Fully-resolved {@link GetDotenvOptions}.
485
- *
486
- * @example
487
- * ```ts
488
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
489
- * ```
490
- */
491
- const localPkgDir = await packageDirectory.packageDirectory();
492
- const localOptionsPath = localPkgDir
493
- ? path.join(localPkgDir, getDotenvOptionsFilename)
494
- : undefined;
495
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
496
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
497
- : {});
498
- // Merge order: base < local < custom (custom has highest precedence)
499
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
500
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
501
- const result = defaultsDeep(defaultsFromCli, customOptions);
502
- return {
503
- ...result, // Keep explicit empty strings/zeros; drop only undefined
504
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
505
- };
506
- };
507
-
409
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
508
410
  /**
509
- * Zod schemas for programmatic GetDotenv options.
411
+ * Resolve an optional flag with "--exclude-all" overrides.
412
+ * If excludeAll is set and the individual "...-off" is not, force true.
413
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
414
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
415
+ *
416
+ * @param exclude - Individual include/exclude flag.
417
+ * @param excludeOff - Individual "...-off" flag.
418
+ * @param defaultValue - Default for the individual flag.
419
+ * @param excludeAll - Global "exclude-all" flag.
420
+ * @param excludeAllOff - Global "exclude-all-off" flag.
510
421
  *
511
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
512
- * Legacy paths continue to use existing types/logic. The new plugin host will
513
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
514
- * later per the staged plan.
422
+ * @example
423
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
515
424
  */
516
- // Minimal process env representation: string values or undefined to indicate "unset".
517
- const processEnvSchema = zod.z.record(zod.z.string(), zod.z.string().optional());
518
- // RAW: all fields optional — undefined means "inherit" from lower layers.
519
- const getDotenvOptionsSchemaRaw = zod.z.object({
520
- defaultEnv: zod.z.string().optional(),
521
- dotenvToken: zod.z.string().optional(),
522
- dynamicPath: zod.z.string().optional(),
523
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
524
- dynamic: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
525
- env: zod.z.string().optional(),
526
- excludeDynamic: zod.z.boolean().optional(),
527
- excludeEnv: zod.z.boolean().optional(),
528
- excludeGlobal: zod.z.boolean().optional(),
529
- excludePrivate: zod.z.boolean().optional(),
530
- excludePublic: zod.z.boolean().optional(),
531
- loadProcess: zod.z.boolean().optional(),
532
- log: zod.z.boolean().optional(),
533
- outputPath: zod.z.string().optional(),
534
- paths: zod.z.array(zod.z.string()).optional(),
535
- privateToken: zod.z.string().optional(),
536
- vars: processEnvSchema.optional(),
537
- // Host-only feature flag: guarded integration of config loader/overlay
538
- useConfigLoader: zod.z.boolean().optional(),
539
- });
540
- // RESOLVED: service-boundary contract (post-inheritance).
541
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
542
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
543
-
425
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
426
+ // Order of precedence:
427
+ // 1) Individual explicit "on" wins outright.
428
+ // 2) Individual explicit "off" wins over any global.
429
+ // 3) Global exclude-all forces true when not explicitly turned off.
430
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
431
+ // 5) Fall back to the default (true => set; false/undefined => unset).
432
+ (() => {
433
+ // Individual "on"
434
+ if (exclude === true)
435
+ return true;
436
+ // Individual "off"
437
+ if (excludeOff === true)
438
+ return undefined;
439
+ // Global "exclude-all" ON (unless explicitly turned off)
440
+ if (excludeAll === true)
441
+ return true;
442
+ // Global "exclude-all-off" (unless explicitly enabled)
443
+ if (excludeAllOff === true)
444
+ return undefined;
445
+ // Default
446
+ return defaultValue ? true : undefined;
447
+ })();
544
448
  /**
545
- * Zod schemas for configuration files discovered by the new loader.
449
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
450
+ * delete when undefined; assign when defined — without requiring an index signature on T.
451
+ *
452
+ * @typeParam T - Target object type.
453
+ * @param obj - The object to write to.
454
+ * @param key - The optional boolean property key of {@link T}.
455
+ * @param value - The value to set or `undefined` to unset.
546
456
  *
547
- * Notes:
548
- * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
549
- * - RESOLVED: normalized shapes (paths always string[]).
550
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
457
+ * @remarks
458
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
551
459
  */
552
- // String-only env value map
553
- const stringMap = zod.z.record(zod.z.string(), zod.z.string());
554
- const envStringMap = zod.z.record(zod.z.string(), stringMap);
555
- // Allow string[] or single string for "paths" in RAW; normalize later.
556
- const rawPathsSchema = zod.z.union([zod.z.array(zod.z.string()), zod.z.string()]).optional();
557
- const getDotenvConfigSchemaRaw = zod.z.object({
558
- dotenvToken: zod.z.string().optional(),
559
- privateToken: zod.z.string().optional(),
560
- paths: rawPathsSchema,
561
- loadProcess: zod.z.boolean().optional(),
562
- log: zod.z.boolean().optional(),
563
- shell: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
564
- scripts: zod.z.record(zod.z.string(), zod.z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
565
- requiredKeys: zod.z.array(zod.z.string()).optional(),
566
- schema: zod.z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
567
- vars: stringMap.optional(), // public, global
568
- envVars: envStringMap.optional(), // public, per-env
569
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
570
- dynamic: zod.z.unknown().optional(),
571
- // Per-plugin config bag; validated by plugins/host when used.
572
- plugins: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
573
- });
574
- // Normalize paths to string[]
575
- const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
576
- const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
577
- ...raw,
578
- paths: normalizePaths(raw.paths),
579
- }));
580
-
581
- // Discovery candidates (first match wins per scope/privacy).
582
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
583
- const PUBLIC_FILENAMES = [
584
- 'getdotenv.config.json',
585
- 'getdotenv.config.yaml',
586
- 'getdotenv.config.yml',
587
- 'getdotenv.config.js',
588
- 'getdotenv.config.mjs',
589
- 'getdotenv.config.cjs',
590
- 'getdotenv.config.ts',
591
- 'getdotenv.config.mts',
592
- 'getdotenv.config.cts',
593
- ];
594
- const LOCAL_FILENAMES = [
595
- 'getdotenv.config.local.json',
596
- 'getdotenv.config.local.yaml',
597
- 'getdotenv.config.local.yml',
598
- 'getdotenv.config.local.js',
599
- 'getdotenv.config.local.mjs',
600
- 'getdotenv.config.local.cjs',
601
- 'getdotenv.config.local.ts',
602
- 'getdotenv.config.local.mts',
603
- 'getdotenv.config.local.cts',
604
- ];
605
- const isYaml = (p) => ['.yaml', '.yml'].includes(path.extname(p).toLowerCase());
606
- const isJson = (p) => path.extname(p).toLowerCase() === '.json';
607
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(path.extname(p).toLowerCase());
608
- // --- Internal JS/TS module loader helpers (default export) ---
609
- const importDefault$1 = async (fileUrl) => {
610
- const mod = (await import(fileUrl));
611
- return mod.default;
612
- };
613
- const cacheName = (absPath, suffix) => {
614
- // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
615
- const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
616
- return `${base}.${suffix}.mjs`;
617
- };
618
- const ensureDir = async (dir) => {
619
- await fs.ensureDir(dir);
620
- return dir;
621
- };
622
- const loadJsTsDefault = async (absPath) => {
623
- const fileUrl = url.pathToFileURL(absPath).toString();
624
- const ext = path.extname(absPath).toLowerCase();
625
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
626
- return importDefault$1(fileUrl);
627
- }
628
- // Try direct import first in case a TS loader is active.
629
- try {
630
- const val = await importDefault$1(fileUrl);
631
- if (val)
632
- return val;
633
- }
634
- catch {
635
- /* fallthrough */
636
- }
637
- // esbuild bundle to a temp ESM file
638
- try {
639
- const esbuild = (await import('esbuild'));
640
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
641
- const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
642
- await esbuild.build({
643
- entryPoints: [absPath],
644
- bundle: true,
645
- platform: 'node',
646
- format: 'esm',
647
- target: 'node20',
648
- outfile,
649
- sourcemap: false,
650
- logLevel: 'silent',
651
- });
652
- return await importDefault$1(url.pathToFileURL(outfile).toString());
653
- }
654
- catch {
655
- /* fallthrough to TS transpile */
656
- }
657
- // typescript.transpileModule simple transpile (single-file)
658
- try {
659
- const ts = (await import('typescript'));
660
- const src = await fs.readFile(absPath, 'utf-8');
661
- const out = ts.transpileModule(src, {
662
- compilerOptions: {
663
- module: 'ESNext',
664
- target: 'ES2022',
665
- moduleResolution: 'NodeNext',
666
- },
667
- }).outputText;
668
- const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
669
- const outfile = path.join(outDir, cacheName(absPath, 'ts'));
670
- await fs.writeFile(outfile, out, 'utf-8');
671
- return await importDefault$1(url.pathToFileURL(outfile).toString());
672
- }
673
- catch {
674
- throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
675
- }
676
- };
677
- /**
678
- * Discover JSON/YAML config files in the packaged root and project root.
679
- * Order: packaged public → project public → project local. */
680
- const discoverConfigFiles = async (importMetaUrl) => {
681
- const files = [];
682
- // Packaged root via importMetaUrl (optional)
683
- if (importMetaUrl) {
684
- const fromUrl = url.fileURLToPath(importMetaUrl);
685
- const packagedRoot = await packageDirectory.packageDirectory({ cwd: fromUrl });
686
- if (packagedRoot) {
687
- for (const name of PUBLIC_FILENAMES) {
688
- const p = path.join(packagedRoot, name);
689
- if (await fs.pathExists(p)) {
690
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
691
- break; // only one public file expected per scope
692
- }
693
- }
694
- // By policy, packaged .local is not expected; skip even if present.
695
- }
696
- }
697
- // Project root (from current working directory)
698
- const projectRoot = await packageDirectory.packageDirectory();
699
- if (projectRoot) {
700
- for (const name of PUBLIC_FILENAMES) {
701
- const p = path.join(projectRoot, name);
702
- if (await fs.pathExists(p)) {
703
- files.push({ path: p, privacy: 'public', scope: 'project' });
704
- break;
705
- }
706
- }
707
- for (const name of LOCAL_FILENAMES) {
708
- const p = path.join(projectRoot, name);
709
- if (await fs.pathExists(p)) {
710
- files.push({ path: p, privacy: 'local', scope: 'project' });
711
- break;
712
- }
713
- }
714
- }
715
- return files;
460
+ const setOptionalFlag = (obj, key, value) => {
461
+ const target = obj;
462
+ const k = key;
463
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
464
+ if (value === undefined)
465
+ delete target[k];
466
+ else
467
+ target[k] = value;
716
468
  };
469
+
717
470
  /**
718
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
719
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
720
- *
721
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
722
- * For JS/TS: default export is loaded; "dynamic" is allowed.
471
+ * Merge and normalize raw Commander options (current + parent + defaults)
472
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
473
+ * avoid cross-layer coupling; callers may cast as needed.
723
474
  */
724
- const loadConfigFile = async (filePath) => {
725
- let raw = {};
726
- try {
727
- const abs = path.resolve(filePath);
728
- if (isJsOrTs(abs)) {
729
- // JS/TS support: load default export via robust pipeline.
730
- const mod = await loadJsTsDefault(abs);
731
- raw = mod ?? {};
475
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
476
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
477
+ ? JSON.parse(parentJson)
478
+ : undefined;
479
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
480
+ const current = { ...rest };
481
+ if (typeof scripts === 'string') {
482
+ try {
483
+ current.scripts = JSON.parse(scripts);
732
484
  }
733
- else {
734
- const txt = await fs.readFile(abs, 'utf-8');
735
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
485
+ catch {
486
+ // ignore parse errors; leave scripts undefined
736
487
  }
737
488
  }
738
- catch (err) {
739
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
740
- }
741
- // Validate RAW
742
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
743
- if (!parsed.success) {
744
- const msgs = parsed.error.issues
745
- .map((i) => `${i.path.join('.')}: ${i.message}`)
746
- .join('\n');
747
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
748
- }
749
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
750
- if (!isJsOrTs(filePath) &&
751
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
752
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
753
- `Use JS/TS config for "dynamic" or "schema".`);
489
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
490
+ const d = defaults;
491
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
492
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
493
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
494
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
495
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
496
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
497
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
498
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
499
+ // warnEntropy (tri-state)
500
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
501
+ // Normalize shell for predictability: explicit default shell per OS.
502
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
503
+ let resolvedShell = merged.shell;
504
+ if (shellOff)
505
+ resolvedShell = false;
506
+ else if (resolvedShell === true || resolvedShell === undefined) {
507
+ resolvedShell = defaultShell;
754
508
  }
755
- return getDotenvConfigSchemaResolved.parse(parsed.data);
756
- };
757
- /**
758
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
759
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
760
- */
761
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
762
- const discovered = await discoverConfigFiles(importMetaUrl);
763
- const result = {};
764
- for (const f of discovered) {
765
- const cfg = await loadConfigFile(f.path);
766
- if (f.scope === 'packaged') {
767
- // packaged public only
768
- result.packaged = cfg;
769
- }
770
- else {
771
- result.project ??= {};
772
- if (f.privacy === 'public')
773
- result.project.public = cfg;
774
- else
775
- result.project.local = cfg;
776
- }
509
+ else if (typeof resolvedShell !== 'string' &&
510
+ typeof defaults.shell === 'string') {
511
+ resolvedShell = defaults.shell;
777
512
  }
778
- return result;
513
+ merged.shell = resolvedShell;
514
+ const cmd = typeof command === 'string' ? command : undefined;
515
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
779
516
  };
780
517
 
781
518
  /**
@@ -864,39 +601,6 @@ const dotenvExpand = (value, ref = process.env) => {
864
601
  const result = interpolate(value, ref);
865
602
  return result ? result.replace(/\\\$/g, '$') : undefined;
866
603
  };
867
- /**
868
- * Recursively expands environment variables in the values of a JSON object.
869
- * Variables may be presented with optional default as `$VAR[:default]` or
870
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
871
- *
872
- * @param values - The values object to expand.
873
- * @param options - Expansion options.
874
- * @returns The value object with expanded string values.
875
- *
876
- * @example
877
- * ```ts
878
- * process.env.FOO = 'bar';
879
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
880
- * // => { A: "bar", B: "xbary" }
881
- * ```
882
- *
883
- * @remarks
884
- * Options:
885
- * - ref: The reference object to use for expansion (defaults to process.env).
886
- * - progressive: Whether to progressively add expanded values to the set of
887
- * reference keys.
888
- *
889
- * When `progressive` is true, each expanded key becomes available for
890
- * subsequent expansions in the same object (left-to-right by object key order).
891
- */
892
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
893
- const { ref = process.env, progressive = false } = options;
894
- acc[key] = dotenvExpand(values[key], {
895
- ...ref,
896
- ...(progressive ? acc : {}),
897
- });
898
- return acc;
899
- }, {});
900
604
  /**
901
605
  * Recursively expands environment variables in a string using `process.env` as
902
606
  * the expansion reference. Variables may be presented with optional default as
@@ -914,1157 +618,61 @@ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduc
914
618
  */
915
619
  const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
916
620
 
917
- const applyKv = (current, kv) => {
918
- if (!kv || Object.keys(kv).length === 0)
919
- return current;
920
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
921
- return { ...current, ...expanded };
922
- };
923
- const applyConfigSlice = (current, cfg, env) => {
924
- if (!cfg)
925
- return current;
926
- // kind axis: global then env (env overrides global)
927
- const afterGlobal = applyKv(current, cfg.vars);
928
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
929
- return applyKv(afterGlobal, envKv);
930
- };
931
- /**
932
- * Overlay config-provided values onto a base ProcessEnv using precedence axes:
933
- * - kind: env \> global
934
- * - privacy: local \> public
935
- * - source: project \> packaged \> base
936
- *
937
- * Programmatic explicit vars (if provided) override all config slices.
938
- * Progressive expansion is applied within each slice.
939
- */
940
- const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
941
- let current = { ...base };
942
- // Source: packaged (public -> local)
943
- current = applyConfigSlice(current, configs.packaged, env);
944
- // Packaged "local" is not expected by policy; if present, honor it.
945
- // We do not have a separate object for packaged.local in sources, keep as-is.
946
- // Source: project (public -> local)
947
- current = applyConfigSlice(current, configs.project?.public, env);
948
- current = applyConfigSlice(current, configs.project?.local, env);
949
- // Programmatic explicit vars (top of static tier)
950
- if (programmaticVars) {
951
- const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
952
- current = applyKv(current, toApply);
953
- }
954
- return current;
955
- };
956
-
621
+ // src/GetDotenvOptions.ts
957
622
  /**
958
- * Asynchronously read a dotenv file & parse it into an object.
623
+ * Converts programmatic CLI options to `getDotenv` options. *
624
+ * @param cliOptions - CLI options. Defaults to `{}`.
959
625
  *
960
- * @param path - Path to dotenv file.
961
- * @returns The parsed dotenv object.
626
+ * @returns `getDotenv` options.
962
627
  */
963
- const readDotenv = async (path) => {
964
- try {
965
- return (await fs.exists(path)) ? dotenv.parse(await fs.readFile(path)) : {};
966
- }
967
- catch {
968
- return {};
969
- }
970
- };
971
-
972
- const importDefault = async (fileUrl) => {
973
- const mod = (await import(fileUrl));
974
- return mod.default;
975
- };
976
- const cacheHash = (absPath, mtimeMs) => crypto.createHash('sha1')
977
- .update(absPath)
978
- .update(String(mtimeMs))
979
- .digest('hex')
980
- .slice(0, 12);
981
- /**
982
- * Remove older compiled cache files for a given source base name, keeping
983
- * at most `keep` most-recent files. Errors are ignored by design.
984
- */
985
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
986
- try {
987
- const entries = await fs.readdir(cacheDir);
988
- const mine = entries
989
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
990
- .map((f) => path.join(cacheDir, f));
991
- if (mine.length <= keep)
992
- return;
993
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
994
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
995
- const toDelete = stats.slice(keep).map((s) => s.p);
996
- await Promise.all(toDelete.map(async (p) => {
997
- try {
998
- await fs.remove(p);
999
- }
1000
- catch {
1001
- // best-effort cleanup
1002
- }
1003
- }));
1004
- }
1005
- catch {
1006
- // best-effort cleanup
1007
- }
1008
- };
1009
- /**
1010
- * Load a module default export from a JS/TS file with robust fallbacks:
1011
- * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1012
- * 1) try direct import (if a TS loader is active),
1013
- * 2) esbuild bundle to a temp ESM file,
1014
- * 3) typescript.transpileModule fallback for simple modules.
1015
- *
1016
- * @param absPath - absolute path to source file
1017
- * @param cacheDirName - cache subfolder under .tsbuild
1018
- */
1019
- const loadModuleDefault = async (absPath, cacheDirName) => {
1020
- const ext = path.extname(absPath).toLowerCase();
1021
- const fileUrl = url.pathToFileURL(absPath).toString();
1022
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1023
- return importDefault(fileUrl);
1024
- }
1025
- // Try direct import first (TS loader active)
1026
- try {
1027
- const dyn = await importDefault(fileUrl);
1028
- if (dyn)
1029
- return dyn;
1030
- }
1031
- catch {
1032
- /* fall through */
1033
- }
1034
- const stat = await fs.stat(absPath);
1035
- const hash = cacheHash(absPath, stat.mtimeMs);
1036
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
1037
- await fs.ensureDir(cacheDir);
1038
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
1039
- // Try esbuild
1040
- try {
1041
- const esbuild = (await import('esbuild'));
1042
- await esbuild.build({
1043
- entryPoints: [absPath],
1044
- bundle: true,
1045
- platform: 'node',
1046
- format: 'esm',
1047
- target: 'node20',
1048
- outfile: cacheFile,
1049
- sourcemap: false,
1050
- logLevel: 'silent',
1051
- });
1052
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1053
- // Best-effort: trim older cache files for this source.
1054
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1055
- return result;
1056
- }
1057
- catch {
1058
- /* fall through to TS transpile */
1059
- }
1060
- // TypeScript transpile fallback
1061
- try {
1062
- const ts = (await import('typescript'));
1063
- const code = await fs.readFile(absPath, 'utf-8');
1064
- const out = ts.transpileModule(code, {
1065
- compilerOptions: {
1066
- module: 'ESNext',
1067
- target: 'ES2022',
1068
- moduleResolution: 'NodeNext',
1069
- },
1070
- }).outputText;
1071
- await fs.writeFile(cacheFile, out, 'utf-8');
1072
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1073
- // Best-effort: trim older cache files for this source.
1074
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1075
- return result;
1076
- }
1077
- catch {
1078
- // Caller decides final error wording; rethrow for upstream mapping.
1079
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
1080
- }
1081
- };
1082
-
1083
- /**
1084
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
1085
- *
1086
- * @param options - `GetDotenvOptions` object
1087
- * @returns The combined parsed dotenv object.
1088
- * * @example Load from the project root with default tokens
1089
- * ```ts
1090
- * const vars = await getDotenv();
1091
- * console.log(vars.MY_SETTING);
1092
- * ```
1093
- *
1094
- * @example Load from multiple paths and a specific environment
1095
- * ```ts
1096
- * const vars = await getDotenv({
1097
- * env: 'dev',
1098
- * dotenvToken: '.testenv',
1099
- * privateToken: 'secret',
1100
- * paths: ['./', './packages/app'],
1101
- * });
1102
- * ```
1103
- *
1104
- * @example Use dynamic variables
1105
- * ```ts
1106
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
1107
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
1108
- * ```
1109
- *
1110
- * @remarks
1111
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
1112
- * into `process.env` as a side effect.
1113
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
1114
- * The path is resolved after expansion, so it may reference previously loaded vars.
1115
- *
1116
- * @throws Error when a dynamic module is present but cannot be imported.
1117
- * @throws Error when an output path was requested but could not be resolved.
1118
- */
1119
- const getDotenv = async (options = {}) => {
1120
- // Apply defaults.
1121
- const { defaultEnv, dotenvToken = '.env', dynamicPath, env, excludeDynamic = false, excludeEnv = false, excludeGlobal = false, excludePrivate = false, excludePublic = false, loadProcess = false, log = false, logger = console, outputPath, paths = [], privateToken = 'local', vars = {}, } = await resolveGetDotenvOptions(options);
1122
- // Read .env files.
1123
- const loaded = paths.length
1124
- ? await paths.reduce(async (e, p) => {
1125
- const publicGlobal = excludePublic || excludeGlobal
1126
- ? Promise.resolve({})
1127
- : readDotenv(path.resolve(p, dotenvToken));
1128
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1129
- ? Promise.resolve({})
1130
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1131
- const privateGlobal = excludePrivate || excludeGlobal
1132
- ? Promise.resolve({})
1133
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1134
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1135
- ? Promise.resolve({})
1136
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1137
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1138
- e,
1139
- publicGlobal,
1140
- publicEnv,
1141
- privateGlobal,
1142
- privateEnv,
1143
- ]);
1144
- return {
1145
- ...eResolved,
1146
- ...publicGlobalResolved,
1147
- ...publicEnvResolved,
1148
- ...privateGlobalResolved,
1149
- ...privateEnvResolved,
1150
- };
1151
- }, Promise.resolve({}))
1152
- : {};
1153
- const outputKey = nanoid.nanoid();
1154
- const dotenv = dotenvExpandAll({
1155
- ...loaded,
1156
- ...vars,
1157
- ...(outputPath ? { [outputKey]: outputPath } : {}),
1158
- }, { progressive: true });
1159
- // Process dynamic variables. Programmatic option takes precedence over path.
1160
- if (!excludeDynamic) {
1161
- let dynamic = undefined;
1162
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1163
- dynamic = options.dynamic;
1164
- }
1165
- else if (dynamicPath) {
1166
- const absDynamicPath = path.resolve(dynamicPath);
1167
- if (await fs.exists(absDynamicPath)) {
1168
- try {
1169
- dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1170
- }
1171
- catch {
1172
- // Preserve legacy error text for compatibility with tests/docs.
1173
- throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1174
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1175
- }
1176
- }
1177
- }
1178
- if (dynamic) {
1179
- try {
1180
- for (const key in dynamic)
1181
- Object.assign(dotenv, {
1182
- [key]: typeof dynamic[key] === 'function'
1183
- ? dynamic[key](dotenv, env ?? defaultEnv)
1184
- : dynamic[key],
1185
- });
1186
- }
1187
- catch {
1188
- throw new Error(`Unable to evaluate dynamic variables.`);
1189
- }
1190
- }
1191
- }
1192
- // Write output file.
1193
- let resultDotenv = dotenv;
1194
- if (outputPath) {
1195
- const outputPathResolved = dotenv[outputKey];
1196
- if (!outputPathResolved)
1197
- throw new Error('Output path not found.');
1198
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1199
- await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
1200
- const value = dotenvForOutput[key] ?? '';
1201
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1202
- }, ''), { encoding: 'utf-8' });
1203
- resultDotenv = dotenvForOutput;
1204
- }
1205
- // Log result.
1206
- if (log) {
1207
- const redactFlag = options.redact ?? false;
1208
- const redactPatterns = options.redactPatterns ?? undefined;
1209
- const redOpts = {};
1210
- if (redactFlag)
1211
- redOpts.redact = true;
1212
- if (redactFlag && Array.isArray(redactPatterns))
1213
- redOpts.redactPatterns = redactPatterns;
1214
- const bag = redactFlag
1215
- ? redactObject(resultDotenv, redOpts)
1216
- : { ...resultDotenv };
1217
- logger.log(bag);
1218
- // Entropy warnings: once-per-key-per-run (presentation only)
1219
- const warnEntropyVal = options.warnEntropy ?? true;
1220
- const entropyThresholdVal = options
1221
- .entropyThreshold;
1222
- const entropyMinLengthVal = options
1223
- .entropyMinLength;
1224
- const entropyWhitelistVal = options
1225
- .entropyWhitelist;
1226
- const entOpts = {};
1227
- if (typeof warnEntropyVal === 'boolean')
1228
- entOpts.warnEntropy = warnEntropyVal;
1229
- if (typeof entropyThresholdVal === 'number')
1230
- entOpts.entropyThreshold = entropyThresholdVal;
1231
- if (typeof entropyMinLengthVal === 'number')
1232
- entOpts.entropyMinLength = entropyMinLengthVal;
1233
- if (Array.isArray(entropyWhitelistVal))
1234
- entOpts.entropyWhitelist = entropyWhitelistVal;
1235
- for (const [k, v] of Object.entries(resultDotenv)) {
1236
- maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
1237
- logger.log(line);
1238
- });
1239
- }
1240
- }
1241
- // Load process.env.
1242
- if (loadProcess)
1243
- Object.assign(process.env, resultDotenv);
1244
- return resultDotenv;
1245
- };
1246
-
1247
- /**
1248
- * Deep interpolation utility for string leaves.
1249
- * - Expands string values using dotenv-style expansion against the provided envRef.
1250
- * - Preserves non-strings as-is.
1251
- * - Does not recurse into arrays (arrays are returned unchanged).
1252
- *
1253
- * Intended for:
1254
- * - Phase C option/config interpolation after composing ctx.dotenv.
1255
- * - Per-plugin config slice interpolation before afterResolve.
1256
- */
1257
- /** @internal */
1258
- const isPlainObject = (v) => v !== null &&
1259
- typeof v === 'object' &&
1260
- !Array.isArray(v) &&
1261
- Object.getPrototypeOf(v) === Object.prototype;
1262
- /**
1263
- * Deeply interpolate string leaves against envRef.
1264
- * Arrays are not recursed into; they are returned unchanged.
1265
- *
1266
- * @typeParam T - Shape of the input value.
1267
- * @param value - Input value (object/array/primitive).
1268
- * @param envRef - Reference environment for interpolation.
1269
- * @returns A new value with string leaves interpolated.
1270
- */
1271
- const interpolateDeep = (value, envRef) => {
1272
- // Strings: expand and return
1273
- if (typeof value === 'string') {
1274
- const out = dotenvExpand(value, envRef);
1275
- // dotenvExpand returns string | undefined; preserve original on undefined
1276
- return (out ?? value);
1277
- }
1278
- // Arrays: return as-is (no recursion)
1279
- if (Array.isArray(value)) {
1280
- return value;
1281
- }
1282
- // Plain objects: shallow clone and recurse into values
1283
- if (isPlainObject(value)) {
1284
- const src = value;
1285
- const out = {};
1286
- for (const [k, v] of Object.entries(src)) {
1287
- // Recurse for strings/objects; keep arrays as-is; preserve other scalars
1288
- if (typeof v === 'string')
1289
- out[k] = dotenvExpand(v, envRef) ?? v;
1290
- else if (Array.isArray(v))
1291
- out[k] = v;
1292
- else if (isPlainObject(v))
1293
- out[k] = interpolateDeep(v, envRef);
1294
- else
1295
- out[k] = v;
1296
- }
1297
- return out;
1298
- }
1299
- // Other primitives/types: return as-is
1300
- return value;
1301
- };
1302
-
1303
- /**
1304
- * Compute the dotenv context for the host (uses the config loader/overlay path).
1305
- * - Resolves and validates options strictly (host-only).
1306
- * - Applies file cascade, overlays, dynamics, and optional effects.
1307
- * - Merges and validates per-plugin config slices (when provided).
1308
- *
1309
- * @param customOptions - Partial options from the current invocation.
1310
- * @param plugins - Installed plugins (for config validation).
1311
- * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
1312
- const computeContext = async (customOptions, plugins, hostMetaUrl) => {
1313
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1314
- const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
1315
- // Always-on loader path
1316
- // 1) Base from files only (no dynamic, no programmatic vars)
1317
- const base = await getDotenv({
1318
- ...validated,
1319
- // Build a pure base without side effects or logging.
1320
- excludeDynamic: true,
1321
- vars: {},
1322
- log: false,
1323
- loadProcess: false,
1324
- outputPath: undefined,
1325
- });
1326
- // 2) Discover config sources and overlay
1327
- const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
1328
- const dotenvOverlaid = overlayEnv({
1329
- base,
1330
- env: validated.env ?? validated.defaultEnv,
1331
- configs: sources,
1332
- ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1333
- });
1334
- // Helper to apply a dynamic map progressively.
1335
- const applyDynamic = (target, dynamic, env) => {
1336
- if (!dynamic)
1337
- return;
1338
- for (const key of Object.keys(dynamic)) {
1339
- const value = typeof dynamic[key] === 'function'
1340
- ? dynamic[key](target, env)
1341
- : dynamic[key];
1342
- Object.assign(target, { [key]: value });
1343
- }
1344
- };
1345
- // 3) Apply dynamics in order
1346
- const dotenv = { ...dotenvOverlaid };
1347
- applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1348
- applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1349
- applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1350
- applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1351
- // file dynamicPath (lowest)
1352
- if (validated.dynamicPath) {
1353
- const absDynamicPath = path.resolve(validated.dynamicPath);
1354
- try {
1355
- const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
1356
- applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
1357
- }
1358
- catch {
1359
- throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
1360
- }
1361
- }
1362
- // 4) Output/log/process merge
1363
- if (validated.outputPath) {
1364
- await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
1365
- const value = dotenv[key] ?? '';
1366
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1367
- }, ''), { encoding: 'utf-8' });
1368
- }
1369
- const logger = validated.logger ?? console;
1370
- if (validated.log)
1371
- logger.log(dotenv);
1372
- if (validated.loadProcess)
1373
- Object.assign(process.env, dotenv);
1374
- // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
1375
- const packagedPlugins = (sources.packaged &&
1376
- sources.packaged.plugins) ??
1377
- {};
1378
- const publicPlugins = (sources.project?.public &&
1379
- sources.project.public.plugins) ??
1380
- {};
1381
- const localPlugins = (sources.project?.local &&
1382
- sources.project.local.plugins) ??
1383
- {};
1384
- const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
1385
- for (const p of plugins) {
1386
- if (!p.id)
1387
- continue;
1388
- const slice = mergedPluginConfigs[p.id];
1389
- if (slice === undefined)
1390
- continue;
1391
- // Per-plugin interpolation just before validation/afterResolve:
1392
- // precedence: process.env wins over ctx.dotenv for slice defaults.
1393
- const envRef = {
1394
- ...dotenv,
1395
- ...process.env,
1396
- };
1397
- const interpolated = interpolateDeep(slice, envRef);
1398
- // Validate if a schema is provided; otherwise accept interpolated slice as-is.
1399
- if (p.configSchema) {
1400
- const parsed = p.configSchema.safeParse(interpolated);
1401
- if (!parsed.success) {
1402
- const msgs = parsed.error.issues
1403
- .map((i) => `${i.path.join('.')}: ${i.message}`)
1404
- .join('\n');
1405
- throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
1406
- }
1407
- mergedPluginConfigs[p.id] = parsed.data;
1408
- }
1409
- else {
1410
- mergedPluginConfigs[p.id] = interpolated;
1411
- }
1412
- }
1413
- return {
1414
- optionsResolved: validated,
1415
- dotenv: dotenv,
1416
- plugins: {},
1417
- pluginConfigs: mergedPluginConfigs,
1418
- };
1419
- };
1420
-
1421
- const HOST_META_URL = (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugins-cmd.cjs', document.baseURI).href));
1422
- const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
1423
- const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
1424
- const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
1425
- /**
1426
- * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
1427
- *
1428
- * Responsibilities:
1429
- * - Resolve options strictly and compute dotenv context (resolveAndLoad).
1430
- * - Expose a stable accessor for the current context (getCtx).
1431
- * - Provide a namespacing helper (ns).
1432
- * - Support composable plugins with parent → children install and afterResolve.
1433
- *
1434
- * NOTE: This host is additive and does not alter the legacy CLI.
1435
- */
1436
- class GetDotenvCli extends commander.Command {
1437
- /** Registered top-level plugins (composition happens via .use()) */
1438
- _plugins = [];
1439
- /** One-time installation guard */
1440
- _installed = false;
1441
- /** Optional header line to prepend in help output */
1442
- [HELP_HEADER_SYMBOL];
1443
- constructor(alias = 'getdotenv') {
1444
- super(alias);
1445
- // Ensure subcommands that use passThroughOptions can be attached safely.
1446
- // Commander requires parent commands to enable positional options when a
1447
- // child uses passThroughOptions.
1448
- this.enablePositionalOptions();
1449
- // Configure grouped help: show only base options in default "Options";
1450
- // append App/Plugin sections after default help.
1451
- this.configureHelp({
1452
- visibleOptions: (cmd) => {
1453
- const all = cmd.options ??
1454
- [];
1455
- const base = all.filter((opt) => {
1456
- const group = opt.__group;
1457
- return group === 'base';
1458
- });
1459
- // Sort: short-aliased options first, then long-only; stable by flags.
1460
- const hasShort = (opt) => {
1461
- const flags = opt.flags ?? '';
1462
- // Matches "-x," or starting "-x " before any long
1463
- return /(^|\s|,)-[A-Za-z]/.test(flags);
1464
- };
1465
- const byFlags = (opt) => opt.flags ?? '';
1466
- base.sort((a, b) => {
1467
- const aS = hasShort(a) ? 1 : 0;
1468
- const bS = hasShort(b) ? 1 : 0;
1469
- return bS - aS || byFlags(a).localeCompare(byFlags(b));
1470
- });
1471
- return base;
1472
- },
1473
- });
1474
- this.addHelpText('beforeAll', () => {
1475
- const header = this[HELP_HEADER_SYMBOL];
1476
- return header && header.length > 0 ? `${header}\n\n` : '';
1477
- });
1478
- this.addHelpText('afterAll', (ctx) => this.#renderOptionGroups(ctx.command));
1479
- // Skeleton preSubcommand hook: produce a context if absent, without
1480
- // mutating process.env. The passOptions hook (when installed) will // compute the final context using merged CLI options; keeping
1481
- // loadProcess=false here avoids leaking dotenv values into the parent
1482
- // process env before subcommands execute.
1483
- this.hook('preSubcommand', async () => {
1484
- if (this.getCtx())
1485
- return;
1486
- await this.resolveAndLoad({ loadProcess: false });
1487
- });
1488
- }
1489
- /**
1490
- * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
1491
- */
1492
- async resolveAndLoad(customOptions = {}) {
1493
- // Resolve defaults, then validate strictly under the new host.
1494
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
1495
- getDotenvOptionsSchemaResolved.parse(optionsResolved);
1496
- // Delegate the heavy lifting to the shared helper (guarded path supported).
1497
- const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
1498
- // Persist context on the instance for later access.
1499
- this[CTX_SYMBOL] =
1500
- ctx;
1501
- // Ensure plugins are installed exactly once, then run afterResolve.
1502
- await this.install();
1503
- await this._runAfterResolve(ctx);
1504
- return ctx;
1505
- }
1506
- /**
1507
- * Retrieve the current invocation context (if any).
1508
- */
1509
- getCtx() {
1510
- return this[CTX_SYMBOL];
1511
- }
1512
- /**
1513
- * Retrieve the merged root CLI options bag (if set by passOptions()).
1514
- * Downstream-safe: no generics required.
1515
- */
1516
- getOptions() {
1517
- return this[OPTS_SYMBOL];
1518
- }
1519
- /** Internal: set the merged root options bag for this run. */
1520
- _setOptionsBag(bag) {
1521
- this[OPTS_SYMBOL] = bag;
1522
- }
1523
- /** * Convenience helper to create a namespaced subcommand.
1524
- */
1525
- ns(name) {
1526
- return this.command(name);
1527
- }
1528
- /**
1529
- * Tag options added during the provided callback as 'app' for grouped help.
1530
- * Allows downstream apps to demarcate their root-level options.
1531
- */
1532
- tagAppOptions(fn) {
1533
- const root = this;
1534
- const originalAddOption = root.addOption.bind(root);
1535
- const originalOption = root.option.bind(root);
1536
- const tagLatest = (cmd, group) => {
1537
- const optsArr = cmd.options;
1538
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1539
- const last = optsArr[optsArr.length - 1];
1540
- last.__group = group;
1541
- }
1542
- };
1543
- root.addOption = function patchedAdd(opt) {
1544
- opt.__group = 'app';
1545
- return originalAddOption(opt);
1546
- };
1547
- root.option = function patchedOption(...args) {
1548
- const ret = originalOption(...args);
1549
- tagLatest(this, 'app');
1550
- return ret;
1551
- };
1552
- try {
1553
- return fn(root);
1554
- }
1555
- finally {
1556
- root.addOption = originalAddOption;
1557
- root.option = originalOption;
1558
- }
1559
- }
1560
- /**
1561
- * Branding helper: set CLI name/description/version and optional help header.
1562
- * If version is omitted and importMetaUrl is provided, attempts to read the
1563
- * nearest package.json version (best-effort; non-fatal on failure).
1564
- */
1565
- async brand(args) {
1566
- const { name, description, version, importMetaUrl, helpHeader } = args;
1567
- if (typeof name === 'string' && name.length > 0)
1568
- this.name(name);
1569
- if (typeof description === 'string')
1570
- this.description(description);
1571
- let v = version;
1572
- if (!v && importMetaUrl) {
1573
- try {
1574
- const fromUrl = url.fileURLToPath(importMetaUrl);
1575
- const pkgDir = await packageDirectory.packageDirectory({ cwd: fromUrl });
1576
- if (pkgDir) {
1577
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
1578
- const pkg = JSON.parse(txt);
1579
- if (pkg.version)
1580
- v = pkg.version;
1581
- }
1582
- }
1583
- catch {
1584
- // best-effort only
1585
- }
1586
- }
1587
- if (v)
1588
- this.version(v);
1589
- // Help header:
1590
- // - If caller provides helpHeader, use it.
1591
- // - Otherwise, when a version is known, default to "<name> v<version>".
1592
- if (typeof helpHeader === 'string') {
1593
- this[HELP_HEADER_SYMBOL] = helpHeader;
1594
- }
1595
- else if (v) {
1596
- // Use the current command name (possibly overridden by 'name' above).
1597
- const header = `${this.name()} v${v}`;
1598
- this[HELP_HEADER_SYMBOL] = header;
1599
- }
1600
- return this;
1601
- }
1602
- /**
1603
- * Register a plugin for installation (parent level).
1604
- * Installation occurs on first resolveAndLoad() (or explicit install()).
1605
- */
1606
- use(plugin) {
1607
- this._plugins.push(plugin);
1608
- // Immediately run setup so subcommands exist before parsing.
1609
- const setupOne = (p) => {
1610
- p.setup(this);
1611
- for (const child of p.children)
1612
- setupOne(child);
1613
- };
1614
- setupOne(plugin);
1615
- return this;
1616
- }
1617
- /**
1618
- * Install all registered plugins in parent → children (pre-order).
1619
- * Runs only once per CLI instance.
1620
- */
1621
- async install() {
1622
- // Setup is performed immediately in use(); here we only guard for afterResolve.
1623
- this._installed = true;
1624
- // Satisfy require-await without altering behavior.
1625
- await Promise.resolve();
1626
- }
628
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
1627
629
  /**
1628
- * Run afterResolve hooks for all plugins (parent → children).
630
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
631
+ *
632
+ * - 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`
633
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
634
+ * - Drops CLI-only keys that have no programmatic equivalent.
635
+ *
636
+ * @remarks
637
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
1629
638
  */
1630
- async _runAfterResolve(ctx) {
1631
- const run = async (p) => {
1632
- if (p.afterResolve)
1633
- await p.afterResolve(this, ctx);
1634
- for (const child of p.children)
1635
- await run(child);
1636
- };
1637
- for (const p of this._plugins)
1638
- await run(p);
1639
- }
1640
- // Render App/Plugin grouped options appended after default help.
1641
- #renderOptionGroups(cmd) {
1642
- const all = cmd.options ?? [];
1643
- const byGroup = new Map();
1644
- for (const o of all) {
1645
- const opt = o;
1646
- const g = opt.__group;
1647
- if (!g || g === 'base')
1648
- continue; // base handled by default help
1649
- const rows = byGroup.get(g) ?? [];
1650
- rows.push({
1651
- flags: opt.flags ?? '',
1652
- description: opt.description ?? '',
1653
- });
1654
- byGroup.set(g, rows);
1655
- }
1656
- if (byGroup.size === 0)
1657
- return '';
1658
- const renderRows = (title, rows) => {
1659
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
1660
- // Sort within group: short-aliased flags first
1661
- rows.sort((a, b) => {
1662
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
1663
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
1664
- return bS - aS || a.flags.localeCompare(b.flags);
1665
- });
1666
- const lines = rows
1667
- .map((r) => {
1668
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
1669
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
1670
- })
1671
- .join('\n');
1672
- return `\n${title}:\n${lines}\n`;
1673
- };
1674
- let out = '';
1675
- // App options (if any)
1676
- const app = byGroup.get('app');
1677
- if (app && app.length > 0) {
1678
- out += renderRows('App options', app);
1679
- }
1680
- // Plugin groups sorted by id
1681
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
1682
- pluginKeys.sort((a, b) => a.localeCompare(b));
1683
- for (const k of pluginKeys) {
1684
- const id = k.slice('plugin:'.length) || '(unknown)';
1685
- const rows = byGroup.get(k) ?? [];
1686
- if (rows.length > 0) {
1687
- out += renderRows(`Plugin options — ${id}`, rows);
1688
- }
1689
- }
1690
- return out;
639
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
640
+ // Create a shallow copy then delete optional CLI-only keys if present.
641
+ const restObj = { ...rest };
642
+ delete restObj.debug;
643
+ delete restObj.scripts;
644
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
645
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
646
+ let parsedVars;
647
+ if (typeof vars === 'string') {
648
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
649
+ ? RegExp(varsAssignorPattern)
650
+ : (varsAssignor ?? '=')));
651
+ parsedVars = Object.fromEntries(kvPairs);
1691
652
  }
1692
- }
1693
-
1694
- /**
1695
- * Validate a composed env against config-provided validation surfaces.
1696
- * Precedence for validation definitions:
1697
- * project.local -\> project.public -\> packaged
1698
- *
1699
- * Behavior:
1700
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
1701
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
1702
- * - Returns a flat list of issue strings; caller decides warn vs fail.
1703
- */
1704
- const validateEnvAgainstSources = (finalEnv, sources) => {
1705
- const pick = (getter) => {
1706
- const pl = sources.project?.local;
1707
- const pp = sources.project?.public;
1708
- const pk = sources.packaged;
1709
- return ((pl && getter(pl)) ||
1710
- (pp && getter(pp)) ||
1711
- (pk && getter(pk)) ||
1712
- undefined);
1713
- };
1714
- const schema = pick((cfg) => cfg['schema']);
1715
- if (schema &&
1716
- typeof schema.safeParse === 'function') {
1717
- try {
1718
- const parsed = schema.safeParse(finalEnv);
1719
- if (!parsed.success) {
1720
- // Try to render zod-style issues when available.
1721
- const err = parsed.error;
1722
- const issues = Array.isArray(err.issues) && err.issues.length > 0
1723
- ? err.issues.map((i) => {
1724
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
1725
- const msg = i.message ?? 'Invalid value';
1726
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
1727
- })
1728
- : ['[schema] validation failed'];
1729
- return issues;
1730
- }
1731
- return [];
1732
- }
1733
- catch {
1734
- // If schema invocation fails, surface a single diagnostic.
1735
- return [
1736
- '[schema] validation failed (unable to execute schema.safeParse)',
1737
- ];
1738
- }
653
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
654
+ // Keep only string or undefined values to match ProcessEnv.
655
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
656
+ parsedVars = Object.fromEntries(entries);
1739
657
  }
1740
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
1741
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
1742
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
1743
- if (missing.length > 0) {
1744
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
1745
- }
658
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
659
+ // expectations and the compat test assertions.
660
+ if (parsedVars) {
661
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
1746
662
  }
1747
- return [];
1748
- };
1749
-
1750
- /**
1751
- * Attach legacy root flags to a Commander program.
1752
- * Uses provided defaults to render help labels without coupling to generators.
1753
- */
1754
- const attachRootOptions = (program, defaults, opts) => {
1755
- // Install temporary wrappers to tag all options added here as "base".
1756
- const GROUP = 'base';
1757
- const tagLatest = (cmd, group) => {
1758
- const optsArr = cmd.options;
1759
- if (Array.isArray(optsArr) && optsArr.length > 0) {
1760
- const last = optsArr[optsArr.length - 1];
1761
- last.__group = group;
1762
- }
1763
- };
1764
- const originalAddOption = program.addOption.bind(program);
1765
- const originalOption = program.option.bind(program);
1766
- program.addOption = function patchedAdd(opt) {
1767
- // Tag before adding, in case consumers inspect the Option directly.
1768
- opt.__group = GROUP;
1769
- const ret = originalAddOption(opt);
1770
- return ret;
1771
- };
1772
- program.option = function patchedOption(...args) {
1773
- const ret = originalOption(...args);
1774
- tagLatest(this, GROUP);
1775
- return ret;
663
+ // Tolerate paths as either a delimited string or string[]
664
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
665
+ // under the RootOptionsShape (which declares paths as string | undefined).
666
+ const pathsAny = paths;
667
+ const pathsOut = Array.isArray(pathsAny)
668
+ ? pathsAny.filter((p) => typeof p === 'string')
669
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
670
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
671
+ return {
672
+ ...restObj,
673
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
674
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
1776
675
  };
1777
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1778
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1779
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1780
- // Build initial chain.
1781
- let p = program
1782
- .enablePositionalOptions()
1783
- .passThroughOptions()
1784
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1785
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1786
- ['KEY1', 'VAL1'],
1787
- ['KEY2', 'VAL2'],
1788
- ]
1789
- .map((v) => v.join(va))
1790
- .join(vd)}`, dotenvExpandFromProcessEnv);
1791
- // Optional legacy root command flag (kept for generated CLI compatibility).
1792
- // Default is OFF; the generator opts in explicitly.
1793
- if (opts?.includeCommandOption === true) {
1794
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1795
- }
1796
- p = p
1797
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
1798
- .addOption(new commander.Option('-s, --shell [string]', (() => {
1799
- let defaultLabel = '';
1800
- if (shell !== undefined) {
1801
- if (typeof shell === 'boolean') {
1802
- defaultLabel = ' (default OS shell)';
1803
- }
1804
- else if (typeof shell === 'string') {
1805
- // Safe string interpolation
1806
- defaultLabel = ` (default ${shell})`;
1807
- }
1808
- }
1809
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
1810
- })()).conflicts('shellOff'))
1811
- .addOption(new commander.Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
1812
- .addOption(new commander.Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
1813
- .addOption(new commander.Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
1814
- .addOption(new commander.Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1815
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1816
- ? ' (default)'
1817
- : ''}`).conflicts('excludeAllOff'))
1818
- .addOption(new commander.Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
1819
- .addOption(new commander.Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
1820
- .addOption(new commander.Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
1821
- .addOption(new commander.Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
1822
- .addOption(new commander.Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
1823
- .addOption(new commander.Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
1824
- .addOption(new commander.Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
1825
- .addOption(new commander.Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
1826
- .addOption(new commander.Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
1827
- .addOption(new commander.Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
1828
- .addOption(new commander.Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
1829
- .addOption(new commander.Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
1830
- .addOption(new commander.Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
1831
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
1832
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
1833
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
1834
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
1835
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
1836
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
1837
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
1838
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
1839
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
1840
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
1841
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
1842
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
1843
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1844
- // Hidden scripts pipe-through (stringified)
1845
- .addOption(new commander.Option('--scripts <string>')
1846
- .default(JSON.stringify(scripts))
1847
- .hideHelp());
1848
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1849
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1850
- // Validation: strict mode fails on env validation issues (warn by default).
1851
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
1852
- // Entropy diagnostics (presentation-only)
1853
- p = p
1854
- .addOption(new commander.Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
1855
- .addOption(new commander.Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
1856
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
1857
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
1858
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
1859
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
1860
- // Restore original methods to avoid tagging future additions outside base.
1861
- program.addOption = originalAddOption;
1862
- program.option = originalOption;
1863
- return p;
1864
- };
1865
-
1866
- /**
1867
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1868
- * - If the user explicitly enabled the flag, return true.
1869
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1870
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
1871
- *
1872
- * @param exclude - The "on" flag value as parsed by Commander.
1873
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1874
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1875
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1876
- *
1877
- * @example
1878
- * ```ts
1879
- * resolveExclusion(undefined, undefined, true); // => true
1880
- * ```
1881
- */
1882
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1883
- /**
1884
- * Resolve an optional flag with "--exclude-all" overrides.
1885
- * If excludeAll is set and the individual "...-off" is not, force true.
1886
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1887
- * Otherwise, adopt the default (true → set; false/undefined → unset).
1888
- *
1889
- * @param exclude - Individual include/exclude flag.
1890
- * @param excludeOff - Individual "...-off" flag.
1891
- * @param defaultValue - Default for the individual flag.
1892
- * @param excludeAll - Global "exclude-all" flag.
1893
- * @param excludeAllOff - Global "exclude-all-off" flag.
1894
- *
1895
- * @example
1896
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1897
- */
1898
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1899
- // Order of precedence:
1900
- // 1) Individual explicit "on" wins outright.
1901
- // 2) Individual explicit "off" wins over any global.
1902
- // 3) Global exclude-all forces true when not explicitly turned off.
1903
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1904
- // 5) Fall back to the default (true => set; false/undefined => unset).
1905
- (() => {
1906
- // Individual "on"
1907
- if (exclude === true)
1908
- return true;
1909
- // Individual "off"
1910
- if (excludeOff === true)
1911
- return undefined;
1912
- // Global "exclude-all" ON (unless explicitly turned off)
1913
- if (excludeAll === true)
1914
- return true;
1915
- // Global "exclude-all-off" (unless explicitly enabled)
1916
- if (excludeAllOff === true)
1917
- return undefined;
1918
- // Default
1919
- return defaultValue ? true : undefined;
1920
- })();
1921
- /**
1922
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1923
- * delete when undefined; assign when defined — without requiring an index signature on T.
1924
- *
1925
- * @typeParam T - Target object type.
1926
- * @param obj - The object to write to.
1927
- * @param key - The optional boolean property key of {@link T}.
1928
- * @param value - The value to set or `undefined` to unset.
1929
- *
1930
- * @remarks
1931
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1932
- */
1933
- const setOptionalFlag = (obj, key, value) => {
1934
- const target = obj;
1935
- const k = key;
1936
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1937
- if (value === undefined)
1938
- delete target[k];
1939
- else
1940
- target[k] = value;
1941
- };
1942
-
1943
- /**
1944
- * Merge and normalize raw Commander options (current + parent + defaults)
1945
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1946
- * avoid cross-layer coupling; callers may cast as needed.
1947
- */
1948
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1949
- const parent = typeof parentJson === 'string' && parentJson.length > 0
1950
- ? JSON.parse(parentJson)
1951
- : undefined;
1952
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1953
- const current = { ...rest };
1954
- if (typeof scripts === 'string') {
1955
- try {
1956
- current.scripts = JSON.parse(scripts);
1957
- }
1958
- catch {
1959
- // ignore parse errors; leave scripts undefined
1960
- }
1961
- }
1962
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1963
- const d = defaults;
1964
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1965
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1966
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1967
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1968
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1969
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1970
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1971
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1972
- // warnEntropy (tri-state)
1973
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1974
- // Normalize shell for predictability: explicit default shell per OS.
1975
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1976
- let resolvedShell = merged.shell;
1977
- if (shellOff)
1978
- resolvedShell = false;
1979
- else if (resolvedShell === true || resolvedShell === undefined) {
1980
- resolvedShell = defaultShell;
1981
- }
1982
- else if (typeof resolvedShell !== 'string' &&
1983
- typeof defaults.shell === 'string') {
1984
- resolvedShell = defaults.shell;
1985
- }
1986
- merged.shell = resolvedShell;
1987
- const cmd = typeof command === 'string' ? command : undefined;
1988
- return cmd !== undefined ? { merged, command: cmd } : { merged };
1989
- };
1990
-
1991
- GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1992
- const d = (defaults ?? baseRootOptionDefaults);
1993
- attachRootOptions(this, d, opts);
1994
- return this;
1995
- };
1996
- GetDotenvCli.prototype.passOptions = function (defaults) {
1997
- const d = (defaults ?? baseRootOptionDefaults);
1998
- this.hook('preSubcommand', async (thisCommand) => {
1999
- const raw = thisCommand.opts();
2000
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2001
- // Persist merged options for nested invocations (batch exec).
2002
- thisCommand.getDotenvCliOptions =
2003
- merged;
2004
- // Also store on the host for downstream ergonomic accessors.
2005
- this._setOptionsBag(merged);
2006
- // Build service options and compute context (always-on config loader path).
2007
- const serviceOptions = getDotenvCliOptions2Options(merged);
2008
- await this.resolveAndLoad(serviceOptions);
2009
- // Global validation: once after Phase C using config sources.
2010
- try {
2011
- const ctx = this.getCtx();
2012
- const dotenv = (ctx?.dotenv ?? {});
2013
- const sources = await resolveGetDotenvConfigSources((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugins-cmd.cjs', document.baseURI).href)));
2014
- const issues = validateEnvAgainstSources(dotenv, sources);
2015
- if (Array.isArray(issues) && issues.length > 0) {
2016
- const logger = (merged.logger ??
2017
- console);
2018
- const emit = logger.error ?? logger.log;
2019
- issues.forEach((m) => {
2020
- emit(m);
2021
- });
2022
- if (merged.strict) {
2023
- // Deterministic failure under strict mode
2024
- process.exit(1);
2025
- }
2026
- }
2027
- }
2028
- catch {
2029
- // Be tolerant: validation errors reported above; unexpected failures here
2030
- // should not crash non-strict flows.
2031
- }
2032
- });
2033
- // Also handle root-level flows (no subcommand) so option-aliases can run
2034
- // with the same merged options and context without duplicating logic.
2035
- this.hook('preAction', async (thisCommand) => {
2036
- const raw = thisCommand.opts();
2037
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2038
- thisCommand.getDotenvCliOptions =
2039
- merged;
2040
- this._setOptionsBag(merged);
2041
- // Avoid duplicate heavy work if a context is already present.
2042
- if (!this.getCtx()) {
2043
- const serviceOptions = getDotenvCliOptions2Options(merged);
2044
- await this.resolveAndLoad(serviceOptions);
2045
- try {
2046
- const ctx = this.getCtx();
2047
- const dotenv = (ctx?.dotenv ?? {});
2048
- const sources = await resolveGetDotenvConfigSources((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('plugins-cmd.cjs', document.baseURI).href)));
2049
- const issues = validateEnvAgainstSources(dotenv, sources);
2050
- if (Array.isArray(issues) && issues.length > 0) {
2051
- const logger = (merged
2052
- .logger ?? console);
2053
- const emit = logger.error ?? logger.log;
2054
- issues.forEach((m) => {
2055
- emit(m);
2056
- });
2057
- if (merged.strict) {
2058
- process.exit(1);
2059
- }
2060
- }
2061
- }
2062
- catch {
2063
- // Tolerate validation side-effects in non-strict mode
2064
- }
2065
- }
2066
- });
2067
- return this;
2068
676
  };
2069
677
 
2070
678
  const dbg = (...args) => {
@@ -2363,7 +971,7 @@ const cmdPlugin = (options = {}) => definePlugin({
2363
971
  const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
2364
972
  const cmd = new commander.Command()
2365
973
  .name('cmd')
2366
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
974
+ .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
2367
975
  .configureHelp({ showGlobalOptions: true })
2368
976
  .enablePositionalOptions()
2369
977
  .passThroughOptions()