@karmaniverous/get-dotenv 4.6.0-0 → 5.0.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +130 -23
  2. package/dist/cliHost.cjs +1078 -0
  3. package/dist/cliHost.d.cts +193 -0
  4. package/dist/cliHost.d.mts +193 -0
  5. package/dist/cliHost.d.ts +193 -0
  6. package/dist/cliHost.mjs +1074 -0
  7. package/dist/config.cjs +247 -0
  8. package/dist/config.d.cts +53 -0
  9. package/dist/config.d.mts +53 -0
  10. package/dist/config.d.ts +53 -0
  11. package/dist/config.mjs +242 -0
  12. package/dist/env-overlay.cjs +163 -0
  13. package/dist/env-overlay.d.cts +50 -0
  14. package/dist/env-overlay.d.mts +50 -0
  15. package/dist/env-overlay.d.ts +50 -0
  16. package/dist/env-overlay.mjs +161 -0
  17. package/dist/getdotenv.cli.mjs +2776 -733
  18. package/dist/index.cjs +886 -275
  19. package/dist/index.d.cts +117 -61
  20. package/dist/index.d.mts +117 -61
  21. package/dist/index.d.ts +117 -61
  22. package/dist/index.mjs +888 -278
  23. package/dist/plugins-aws.cjs +618 -0
  24. package/dist/plugins-aws.d.cts +178 -0
  25. package/dist/plugins-aws.d.mts +178 -0
  26. package/dist/plugins-aws.d.ts +178 -0
  27. package/dist/plugins-aws.mjs +616 -0
  28. package/dist/plugins-batch.cjs +569 -0
  29. package/dist/plugins-batch.d.cts +200 -0
  30. package/dist/plugins-batch.d.mts +200 -0
  31. package/dist/plugins-batch.d.ts +200 -0
  32. package/dist/plugins-batch.mjs +567 -0
  33. package/dist/plugins-init.cjs +282 -0
  34. package/dist/plugins-init.d.cts +182 -0
  35. package/dist/plugins-init.d.mts +182 -0
  36. package/dist/plugins-init.d.ts +182 -0
  37. package/dist/plugins-init.mjs +280 -0
  38. package/getdotenv.config.json +19 -0
  39. package/package.json +88 -17
  40. package/templates/cli/ts/index.ts +9 -0
  41. package/templates/cli/ts/plugins/hello.ts +17 -0
  42. package/templates/config/js/getdotenv.config.js +15 -0
  43. package/templates/config/json/local/getdotenv.config.local.json +7 -0
  44. package/templates/config/json/public/getdotenv.config.json +12 -0
  45. package/templates/config/public/getdotenv.config.json +13 -0
  46. package/templates/config/ts/getdotenv.config.ts +16 -0
  47. package/templates/config/yaml/local/getdotenv.config.local.yaml +7 -0
  48. package/templates/config/yaml/public/getdotenv.config.yaml +10 -0
package/dist/index.cjs CHANGED
@@ -1,16 +1,19 @@
1
1
  'use strict';
2
2
 
3
3
  var commander = require('commander');
4
- var execa = require('execa');
5
4
  var globby = require('globby');
6
5
  var packageDirectory = require('package-directory');
7
6
  var path = require('path');
7
+ var execa = require('execa');
8
8
  var fs = require('fs-extra');
9
9
  var url = require('url');
10
- var crypto = require('crypto');
11
10
  var nanoid = require('nanoid');
12
11
  var dotenv = require('dotenv');
12
+ var crypto = require('crypto');
13
+ var YAML = require('yaml');
14
+ var zod = require('zod');
13
15
 
16
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
14
17
  /**
15
18
  * Dotenv expansion utilities.
16
19
  *
@@ -147,25 +150,90 @@ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduc
147
150
  */
148
151
  const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
149
152
 
150
- const baseGetDotenvCliOptions = {
151
- dotenvToken: '.env',
152
- loadProcess: true,
153
- logger: console,
154
- paths: './',
155
- pathsDelimiter: ' ',
156
- privateToken: 'local',
157
- scripts: {
158
- 'git-status': {
159
- cmd: 'git branch --show-current && git status -s -u',
160
- shell: true,
161
- },
162
- },
163
- shell: true,
164
- vars: '',
165
- varsAssignor: '=',
166
- varsDelimiter: ' ',
153
+ /**
154
+ * Attach legacy root flags to a Commander program.
155
+ * Uses provided defaults to render help labels without coupling to generators.
156
+ */
157
+ const attachRootOptions = (program, defaults, opts) => {
158
+ const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
159
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
160
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
161
+ // Build initial chain.
162
+ let p = program
163
+ .enablePositionalOptions()
164
+ .passThroughOptions()
165
+ .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
166
+ p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
167
+ ['KEY1', 'VAL1'],
168
+ ['KEY2', 'VAL2'],
169
+ ]
170
+ .map((v) => v.join(va))
171
+ .join(vd)}`, dotenvExpandFromProcessEnv);
172
+ // Optional legacy root command flag (kept for generated CLI compatibility).
173
+ // Default is OFF; the generator opts in explicitly.
174
+ {
175
+ p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
176
+ }
177
+ p = p
178
+ .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
179
+ .addOption(new commander.Option('-s, --shell [string]', (() => {
180
+ let defaultLabel = '';
181
+ if (shell !== undefined) {
182
+ if (typeof shell === 'boolean') {
183
+ defaultLabel = ' (default OS shell)';
184
+ }
185
+ else if (typeof shell === 'string') {
186
+ // Safe string interpolation
187
+ defaultLabel = ` (default ${shell})`;
188
+ }
189
+ }
190
+ return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
191
+ })()).conflicts('shellOff'))
192
+ .addOption(new commander.Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
193
+ .addOption(new commander.Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
194
+ .addOption(new commander.Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
195
+ .addOption(new commander.Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
196
+ ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
197
+ ? ' (default)'
198
+ : ''}`).conflicts('excludeAllOff'))
199
+ .addOption(new commander.Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
200
+ .addOption(new commander.Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
201
+ .addOption(new commander.Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
202
+ .addOption(new commander.Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
203
+ .addOption(new commander.Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
204
+ .addOption(new commander.Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
205
+ .addOption(new commander.Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
206
+ .addOption(new commander.Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
207
+ .addOption(new commander.Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
208
+ .addOption(new commander.Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
209
+ .addOption(new commander.Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
210
+ .addOption(new commander.Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
211
+ .addOption(new commander.Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
212
+ .option('--capture', 'capture child process stdio for commands (tests/CI)')
213
+ .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
214
+ .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
215
+ .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
216
+ .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
217
+ .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
218
+ .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
219
+ .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
220
+ .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
221
+ .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
222
+ .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
223
+ .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
224
+ // Hidden scripts pipe-through (stringified)
225
+ .addOption(new commander.Option('--scripts <string>')
226
+ .default(JSON.stringify(scripts))
227
+ .hideHelp());
228
+ // Diagnostics: opt-in tracing; optional variadic keys after the flag.
229
+ p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
230
+ return p;
167
231
  };
168
232
 
233
+ /**
234
+ * Batch services (neutral): resolve command and shell settings.
235
+ * Shared by the generator path and the batch plugin to avoid circular deps.
236
+ */
169
237
  /**
170
238
  * Resolve a command string from the {@link Scripts} table.
171
239
  * A script may be expressed as a string or an object with a `cmd` property.
@@ -190,6 +258,143 @@ const resolveShell = (scripts, command, shell) => scripts && typeof scripts[comm
190
258
  ? (scripts[command].shell ?? false)
191
259
  : (shell ?? false);
192
260
 
261
+ // Minimal tokenizer for shell-off execution:
262
+ // Splits by whitespace while preserving quoted segments (single or double quotes).
263
+ const tokenize = (command) => {
264
+ const out = [];
265
+ let cur = '';
266
+ let quote = null;
267
+ for (let i = 0; i < command.length; i++) {
268
+ const c = command.charAt(i);
269
+ if (quote) {
270
+ if (c === quote) {
271
+ // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
272
+ // "" -> " and '' -> '
273
+ const next = command.charAt(i + 1);
274
+ if (next === quote) {
275
+ cur += quote;
276
+ i += 1; // skip the second quote
277
+ }
278
+ else {
279
+ // end of quoted segment
280
+ quote = null;
281
+ }
282
+ }
283
+ else {
284
+ cur += c;
285
+ }
286
+ }
287
+ else {
288
+ if (c === '"' || c === "'") {
289
+ quote = c;
290
+ }
291
+ else if (/\s/.test(c)) {
292
+ if (cur) {
293
+ out.push(cur);
294
+ cur = '';
295
+ }
296
+ }
297
+ else {
298
+ cur += c;
299
+ }
300
+ }
301
+ }
302
+ if (cur)
303
+ out.push(cur);
304
+ return out;
305
+ };
306
+
307
+ const dbg = (...args) => {
308
+ if (process.env.GETDOTENV_DEBUG) {
309
+ // Use stderr to avoid interfering with stdout assertions
310
+ console.error('[getdotenv:run]', ...args);
311
+ }
312
+ };
313
+ // Strip repeated symmetric outer quotes (single or double) until stable.
314
+ // This is safe for argv arrays passed to execa (no quoting needed) and avoids
315
+ // passing quote characters through to Node (e.g., for `node -e "<code>"`).
316
+ // Handles stacked quotes from shells like PowerShell: """code""" -> code.
317
+ const stripOuterQuotes = (s) => {
318
+ let out = s;
319
+ // Repeatedly trim only when the entire string is wrapped in matching quotes.
320
+ // Stop as soon as the ends are asymmetric or no quotes remain.
321
+ while (out.length >= 2) {
322
+ const a = out.charAt(0);
323
+ const b = out.charAt(out.length - 1);
324
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
325
+ if (!symmetric)
326
+ break;
327
+ out = out.slice(1, -1);
328
+ }
329
+ return out;
330
+ };
331
+ // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
332
+ // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
333
+ const sanitizeEnv = (env) => {
334
+ if (!env)
335
+ return undefined;
336
+ const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
337
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
338
+ };
339
+ const runCommand = async (command, shell, opts) => {
340
+ if (shell === false) {
341
+ let file;
342
+ let args = [];
343
+ if (Array.isArray(command)) {
344
+ file = command[0];
345
+ args = command.slice(1).map(stripOuterQuotes);
346
+ }
347
+ else {
348
+ const tokens = tokenize(command);
349
+ file = tokens[0];
350
+ args = tokens.slice(1);
351
+ }
352
+ if (!file)
353
+ return 0;
354
+ dbg('exec (plain)', { file, args, stdio: opts.stdio });
355
+ // Build options without injecting undefined properties (exactOptionalPropertyTypes).
356
+ const envSan = sanitizeEnv(opts.env);
357
+ const plainOpts = {};
358
+ if (opts.cwd !== undefined)
359
+ plainOpts.cwd = opts.cwd;
360
+ if (envSan !== undefined)
361
+ plainOpts.env = envSan;
362
+ if (opts.stdio !== undefined)
363
+ plainOpts.stdio = opts.stdio;
364
+ const result = await execa.execa(file, args, plainOpts);
365
+ if (opts.stdio === 'pipe' && result.stdout) {
366
+ process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
367
+ }
368
+ const exit = result?.exitCode;
369
+ dbg('exit (plain)', { exitCode: exit });
370
+ return typeof exit === 'number' ? exit : Number.NaN;
371
+ }
372
+ else {
373
+ const commandStr = Array.isArray(command) ? command.join(' ') : command;
374
+ dbg('exec (shell)', {
375
+ shell: typeof shell === 'string' ? shell : 'custom',
376
+ stdio: opts.stdio,
377
+ command: commandStr,
378
+ });
379
+ const envSan = sanitizeEnv(opts.env);
380
+ const shellOpts = { shell };
381
+ if (opts.cwd !== undefined)
382
+ shellOpts.cwd = opts.cwd;
383
+ if (envSan !== undefined)
384
+ shellOpts.env = envSan;
385
+ if (opts.stdio !== undefined)
386
+ shellOpts.stdio = opts.stdio;
387
+ const result = await execa.execaCommand(commandStr, shellOpts);
388
+ const out = result?.stdout;
389
+ if (opts.stdio === 'pipe' && out) {
390
+ process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
391
+ }
392
+ const exit = result?.exitCode;
393
+ dbg('exit (shell)', { exitCode: exit });
394
+ return typeof exit === 'number' ? exit : Number.NaN;
395
+ }
396
+ };
397
+
193
398
  const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
194
399
  let cwd = process.cwd();
195
400
  if (pkgCwd) {
@@ -214,8 +419,10 @@ const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
214
419
  return { absRootPath, paths };
215
420
  };
216
421
  const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, ignoreErrors, list, logger, pkgCwd, rootPath, shell, }) => {
217
- if (!command) {
218
- logger.error(`No command provided.`);
422
+ const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
423
+ Boolean(getDotenvCliOptions?.capture); // Require a command only when not listing. In list mode, a command is optional.
424
+ if (!command && !list) {
425
+ logger.error(`No command provided. Use --command or --list.`);
219
426
  process.exit(0);
220
427
  }
221
428
  const { absRootPath, paths } = await globPaths({
@@ -231,7 +438,13 @@ const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, igno
231
438
  logger.info('');
232
439
  const headerRootPath = `ROOT: ${absRootPath}`;
233
440
  const headerGlobs = `GLOBS: ${globs}`;
234
- const headerCommand = `CMD: ${command}`;
441
+ // Prepare a safe label for the header (avoid undefined in template)
442
+ const commandLabel = Array.isArray(command)
443
+ ? command.join(' ')
444
+ : typeof command === 'string' && command.length > 0
445
+ ? command
446
+ : '';
447
+ const headerCommand = list ? `CMD: (list only)` : `CMD: ${commandLabel}`;
235
448
  logger.info('*'.repeat(Math.max(headerTitle.length, headerRootPath.length, headerGlobs.length, headerCommand.length)));
236
449
  logger.info(headerTitle);
237
450
  logger.info('');
@@ -251,17 +464,25 @@ const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, igno
251
464
  logger.info(headerCommand);
252
465
  // Execute command.
253
466
  try {
254
- await execa.execaCommand(command, {
255
- cwd: path,
256
- env: {
257
- ...process.env,
258
- getDotenvCliOptions: getDotenvCliOptions
259
- ? JSON.stringify(getDotenvCliOptions)
260
- : undefined,
261
- },
262
- stdio: 'inherit',
263
- shell, // already normalized to string | boolean | URL
264
- });
467
+ const hasCmd = (typeof command === 'string' && command.length > 0) ||
468
+ (Array.isArray(command) && command.length > 0);
469
+ if (hasCmd) {
470
+ await runCommand(command, shell, {
471
+ cwd: path,
472
+ env: {
473
+ ...process.env,
474
+ getDotenvCliOptions: getDotenvCliOptions
475
+ ? JSON.stringify(getDotenvCliOptions)
476
+ : undefined,
477
+ },
478
+ stdio: capture ? 'pipe' : 'inherit',
479
+ });
480
+ }
481
+ else {
482
+ // Should not occur due to the early guard; retain for type safety.
483
+ logger.error(`No command provided. Use --command or --list.`);
484
+ process.exit(0);
485
+ }
265
486
  }
266
487
  catch (error) {
267
488
  if (!ignoreErrors) {
@@ -381,72 +602,43 @@ const cmdCommand = new commander.Command()
381
602
  });
382
603
 
383
604
  /**
384
- * Create the root Commander command with all options and subcommands.
385
- * Pure builder: no side-effects; the caller attaches lifecycle hooks.
605
+ * Create the root Commander command with legacy root options (via cliCore)
606
+ * and built-in subcommands. Pure builder: no side-effects; the caller attaches
607
+ * lifecycle hooks separately.
386
608
  */
387
609
  const createRootCommand = (opts) => {
388
- const { alias, debug, defaultEnv, description, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = opts;
389
- const excludeAll = !!excludeDynamic &&
390
- ((!!excludeEnv && !!excludeGlobal) ||
391
- (!!excludePrivate && !!excludePublic));
392
- const program = new commander.Command()
393
- .name(alias)
394
- .description(description)
395
- .enablePositionalOptions()
396
- .passThroughOptions()
397
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env)
398
- .option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
399
- ['KEY1', 'VAL1'],
400
- ['KEY2', 'VAL2'],
401
- ]
402
- .map((v) => v.join(varsAssignor ?? '='))
403
- .join(varsDelimiter ?? ' ')}`, dotenvExpandFromProcessEnv)
404
- .option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv)
405
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
406
- .addOption(new commander.Option('-s, --shell [string]', (() => {
407
- const defaultLabel = shell
408
- ? ` (default ${typeof shell === 'boolean' ? 'OS shell' : shell})`
409
- : '';
410
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
411
- })()).conflicts('shellOff'))
412
- .addOption(new commander.Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
413
- .addOption(new commander.Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
414
- .addOption(new commander.Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
415
- .addOption(new commander.Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeAll ? ' (default)' : ''}`).conflicts('excludeAllOff'))
416
- .addOption(new commander.Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF${!excludeAll ? ' (default)' : ''}`).conflicts('excludeAll'))
417
- .addOption(new commander.Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
418
- .addOption(new commander.Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
419
- .addOption(new commander.Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
420
- .addOption(new commander.Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
421
- .addOption(new commander.Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
422
- .addOption(new commander.Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
423
- .addOption(new commander.Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
424
- .addOption(new commander.Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
425
- .addOption(new commander.Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
426
- .addOption(new commander.Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
427
- .addOption(new commander.Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
428
- .addOption(new commander.Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
429
- .addOption(new commander.Option('-d, --debug', `debug mode ON${debug ? ' (default)' : ''}`).conflicts('debugOff'))
430
- .addOption(new commander.Option('-D, --debug-off', `debug mode OFF${!debug ? ' (default)' : ''}`).conflicts('debug'))
431
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
432
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
433
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
434
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
435
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
436
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
437
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
438
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
439
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
440
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
441
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
442
- .addOption(new commander.Option('--scripts <string>')
443
- .default(JSON.stringify(scripts))
444
- .hideHelp())
445
- .addCommand(batchCommand)
446
- .addCommand(cmdCommand, { isDefault: true });
610
+ const program = new commander.Command().name(opts.alias).description(opts.description);
611
+ // Attach legacy root flags using shared cliCore builder to keep parity.
612
+ attachRootOptions(program, opts);
613
+ // Subcommands
614
+ program.addCommand(batchCommand).addCommand(cmdCommand, { isDefault: true });
447
615
  return program;
448
616
  };
449
617
 
618
+ // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
619
+ const baseRootOptionDefaults = {
620
+ dotenvToken: '.env',
621
+ loadProcess: true,
622
+ logger: console,
623
+ paths: './',
624
+ pathsDelimiter: ' ',
625
+ privateToken: 'local',
626
+ scripts: {
627
+ 'git-status': {
628
+ cmd: 'git branch --show-current && git status -s -u',
629
+ shell: true,
630
+ },
631
+ },
632
+ shell: true,
633
+ vars: '',
634
+ varsAssignor: '=',
635
+ varsDelimiter: ' ',
636
+ // tri-state flags default to unset unless explicitly provided
637
+ // (debug/log/exclude* resolved via flag utils)
638
+ };
639
+
640
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
641
+
450
642
  /** @internal */
451
643
  const isPlainObject = (value) => value !== null &&
452
644
  typeof value === 'object' &&
@@ -490,7 +682,10 @@ const defaultsDeep = (...layers) => {
490
682
  };
491
683
 
492
684
  // src/GetDotenvOptions.ts
493
- const getDotenvOptionsFilename = 'getdotenv.config.json';
685
+ const getDotenvOptionsFilename = 'getdotenv.config.json'; /**
686
+ * A minimal representation of an environment key/value mapping.
687
+ * Values may be `undefined` to represent "unset".
688
+ */
494
689
  /**
495
690
  * Helper to define a dynamic map with strong inference.
496
691
  *
@@ -499,8 +694,7 @@ const getDotenvOptionsFilename = 'getdotenv.config.json';
499
694
  */
500
695
  const defineDynamic = (d) => d;
501
696
  /**
502
- * Converts programmatic CLI options to `getDotenv` options.
503
- *
697
+ * Converts programmatic CLI options to `getDotenv` options. *
504
698
  * @param cliOptions - CLI options. Defaults to `{}`.
505
699
  *
506
700
  * @returns `getDotenv` options.
@@ -510,16 +704,18 @@ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPatt
510
704
  * Convert CLI-facing string options into {@link GetDotenvOptions}.
511
705
  *
512
706
  * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter
513
- * or a regular expression pattern into a string array.
514
- * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
707
+ * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
515
708
  * pairs (configurable delimiters) into a {@link ProcessEnv}.
516
709
  * - Drops CLI-only keys that have no programmatic equivalent.
517
710
  *
518
711
  * @remarks
519
712
  * Follows exact-optional semantics by not emitting undefined-valued entries.
520
713
  */
521
- // Drop CLI-only keys
522
- const { debug, scripts, ...restFlags } = rest;
714
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
715
+ // Create a shallow copy then delete optional CLI-only keys if present.
716
+ const restObj = { ...rest };
717
+ delete restObj.debug;
718
+ delete restObj.scripts;
523
719
  const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
524
720
  const kvPairs = (vars
525
721
  ? splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
@@ -527,10 +723,15 @@ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPatt
527
723
  : (varsAssignor ?? '=')))
528
724
  : []);
529
725
  const parsedVars = Object.fromEntries(kvPairs);
726
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
530
727
  return {
531
- ...restFlags,
532
- paths: splitBy(paths, pathsDelimiter, pathsDelimiterPattern),
533
- vars: parsedVars,
728
+ ...restObj,
729
+ ...(paths !== undefined
730
+ ? {
731
+ paths: splitBy(paths, pathsDelimiter, pathsDelimiterPattern),
732
+ }
733
+ : {}),
734
+ ...(vars !== undefined ? { vars: parsedVars } : {}),
534
735
  };
535
736
  };
536
737
  const resolveGetDotenvOptions = async (customOptions) => {
@@ -603,6 +804,169 @@ const resolveGetDotenvCliGenerateOptions = async ({ importMetaUrl, ...customOpti
603
804
  return merged;
604
805
  };
605
806
 
807
+ /**
808
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
809
+ * - If the user explicitly enabled the flag, return true.
810
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
811
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
812
+ *
813
+ * @param exclude - The "on" flag value as parsed by Commander.
814
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
815
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
816
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
817
+ *
818
+ * @example
819
+ * ```ts
820
+ * resolveExclusion(undefined, undefined, true); // => true
821
+ * ```
822
+ */
823
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
824
+ /**
825
+ * Resolve an optional flag with "--exclude-all" overrides.
826
+ * If excludeAll is set and the individual "...-off" is not, force true.
827
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
828
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
829
+ *
830
+ * @param exclude - Individual include/exclude flag.
831
+ * @param excludeOff - Individual "...-off" flag.
832
+ * @param defaultValue - Default for the individual flag.
833
+ * @param excludeAll - Global "exclude-all" flag.
834
+ * @param excludeAllOff - Global "exclude-all-off" flag.
835
+ *
836
+ * @example
837
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
838
+ */
839
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
840
+ // Order of precedence:
841
+ // 1) Individual explicit "on" wins outright.
842
+ // 2) Individual explicit "off" wins over any global.
843
+ // 3) Global exclude-all forces true when not explicitly turned off.
844
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
845
+ // 5) Fall back to the default (true => set; false/undefined => unset).
846
+ (() => {
847
+ // Individual "on"
848
+ if (exclude === true)
849
+ return true;
850
+ // Individual "off"
851
+ if (excludeOff === true)
852
+ return undefined;
853
+ // Global "exclude-all" ON (unless explicitly turned off)
854
+ if (excludeAll === true)
855
+ return true;
856
+ // Global "exclude-all-off" (unless explicitly enabled)
857
+ if (excludeAllOff === true)
858
+ return undefined;
859
+ // Default
860
+ return defaultValue ? true : undefined;
861
+ })();
862
+ /**
863
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
864
+ * delete when undefined; assign when defined — without requiring an index signature on T.
865
+ *
866
+ * @typeParam T - Target object type.
867
+ * @param obj - The object to write to.
868
+ * @param key - The optional boolean property key of {@link T}.
869
+ * @param value - The value to set or `undefined` to unset.
870
+ *
871
+ * @remarks
872
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
873
+ */
874
+ const setOptionalFlag = (obj, key, value) => {
875
+ const target = obj;
876
+ const k = key;
877
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
878
+ if (value === undefined)
879
+ delete target[k];
880
+ else
881
+ target[k] = value;
882
+ };
883
+
884
+ /**
885
+ * Merge and normalize raw Commander options (current + parent + defaults)
886
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
887
+ * avoid cross-layer coupling; callers may cast as needed.
888
+ */
889
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
890
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
891
+ ? JSON.parse(parentJson)
892
+ : undefined;
893
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, scripts, shellOff, ...rest } = rawCliOptions;
894
+ const current = { ...rest };
895
+ if (typeof scripts === 'string') {
896
+ try {
897
+ current.scripts = JSON.parse(scripts);
898
+ }
899
+ catch {
900
+ // ignore parse errors; leave scripts undefined
901
+ }
902
+ }
903
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
904
+ const d = defaults;
905
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
906
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
907
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
908
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
909
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
910
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
911
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
912
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
913
+ // Normalize shell for predictability: explicit default shell per OS.
914
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
915
+ let resolvedShell = merged.shell;
916
+ if (shellOff)
917
+ resolvedShell = false;
918
+ else if (resolvedShell === true || resolvedShell === undefined) {
919
+ resolvedShell = defaultShell;
920
+ }
921
+ else if (typeof resolvedShell !== 'string' &&
922
+ typeof defaults.shell === 'string') {
923
+ resolvedShell = defaults.shell;
924
+ }
925
+ merged.shell = resolvedShell;
926
+ const cmd = typeof command === 'string' ? command : undefined;
927
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
928
+ };
929
+
930
+ const applyKv = (current, kv) => {
931
+ if (!kv || Object.keys(kv).length === 0)
932
+ return current;
933
+ const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
934
+ return { ...current, ...expanded };
935
+ };
936
+ const applyConfigSlice = (current, cfg, env) => {
937
+ if (!cfg)
938
+ return current;
939
+ // kind axis: global then env (env overrides global)
940
+ const afterGlobal = applyKv(current, cfg.vars);
941
+ const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
942
+ return applyKv(afterGlobal, envKv);
943
+ };
944
+ /**
945
+ * Overlay config-provided values onto a base ProcessEnv using precedence axes:
946
+ * - kind: env \> global
947
+ * - privacy: local \> public
948
+ * - source: project \> packaged \> base
949
+ *
950
+ * Programmatic explicit vars (if provided) override all config slices.
951
+ * Progressive expansion is applied within each slice.
952
+ */
953
+ const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
954
+ let current = { ...base };
955
+ // Source: packaged (public -> local)
956
+ current = applyConfigSlice(current, configs.packaged, env);
957
+ // Packaged "local" is not expected by policy; if present, honor it.
958
+ // We do not have a separate object for packaged.local in sources, keep as-is.
959
+ // Source: project (public -> local)
960
+ current = applyConfigSlice(current, configs.project?.public, env);
961
+ current = applyConfigSlice(current, configs.project?.local, env);
962
+ // Programmatic explicit vars (top of static tier)
963
+ if (programmaticVars) {
964
+ const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
965
+ current = applyKv(current, toApply);
966
+ }
967
+ return current;
968
+ };
969
+
606
970
  /**
607
971
  * Asynchronously read a dotenv file & parse it into an object.
608
972
  *
@@ -618,65 +982,95 @@ const readDotenv = async (path) => {
618
982
  }
619
983
  };
620
984
 
621
- const importDefault = async (fileUrl) => {
985
+ const importDefault$1 = async (fileUrl) => {
622
986
  const mod = (await import(fileUrl));
623
987
  return mod.default;
624
988
  };
625
- /**
626
- * @internal Compute a short hash from path + mtime for cache filenames.
627
- */
628
989
  const cacheHash = (absPath, mtimeMs) => crypto.createHash('sha1')
629
990
  .update(absPath)
630
991
  .update(String(mtimeMs))
631
992
  .digest('hex')
632
993
  .slice(0, 12);
633
994
  /**
634
- * @internal Load a dynamic module from path. Supports .js/.mjs/.ts/.tsx:
635
- * - .js/.mjs: direct import
636
- * - .ts/.tsx: try direct import (in case a TS loader is active), otherwise:
637
- * - esbuild (if present): bundle to a temp ESM file and import it
638
- * - fallback: typescript.transpileModule (single-file), then import temp file
995
+ * Remove older compiled cache files for a given source base name, keeping
996
+ * at most `keep` most-recent files. Errors are ignored by design.
639
997
  */
640
- const loadDynamicFromPath = async (absPath) => {
641
- if (!(await fs.exists(absPath)))
642
- return undefined;
998
+ const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
999
+ try {
1000
+ const entries = await fs.readdir(cacheDir);
1001
+ const mine = entries
1002
+ .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
1003
+ .map((f) => path.join(cacheDir, f));
1004
+ if (mine.length <= keep)
1005
+ return;
1006
+ const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
1007
+ stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
1008
+ const toDelete = stats.slice(keep).map((s) => s.p);
1009
+ await Promise.all(toDelete.map(async (p) => {
1010
+ try {
1011
+ await fs.remove(p);
1012
+ }
1013
+ catch {
1014
+ // best-effort cleanup
1015
+ }
1016
+ }));
1017
+ }
1018
+ catch {
1019
+ // best-effort cleanup
1020
+ }
1021
+ };
1022
+ /**
1023
+ * Load a module default export from a JS/TS file with robust fallbacks:
1024
+ * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1025
+ * 1) try direct import (if a TS loader is active),
1026
+ * 2) esbuild bundle to a temp ESM file,
1027
+ * 3) typescript.transpileModule fallback for simple modules.
1028
+ *
1029
+ * @param absPath - absolute path to source file
1030
+ * @param cacheDirName - cache subfolder under .tsbuild
1031
+ */
1032
+ const loadModuleDefault = async (absPath, cacheDirName) => {
643
1033
  const ext = path.extname(absPath).toLowerCase();
644
1034
  const fileUrl = url.pathToFileURL(absPath).toString();
645
- if (ext !== '.ts' && ext !== '.tsx') {
646
- return importDefault(fileUrl);
1035
+ if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1036
+ return importDefault$1(fileUrl);
647
1037
  }
648
- // Try direct import (in case user started Node with a TS loader).
1038
+ // Try direct import first (TS loader active)
649
1039
  try {
650
- const dyn = await importDefault(fileUrl);
1040
+ const dyn = await importDefault$1(fileUrl);
651
1041
  if (dyn)
652
1042
  return dyn;
653
1043
  }
654
1044
  catch {
655
- // ignore; fall through to compile
1045
+ /* fall through */
656
1046
  }
657
1047
  const stat = await fs.stat(absPath);
658
1048
  const hash = cacheHash(absPath, stat.mtimeMs);
659
- const cacheDir = path.resolve('.tsbuild', 'getdotenv-dynamic');
1049
+ const cacheDir = path.resolve('.tsbuild', cacheDirName);
1050
+ await fs.ensureDir(cacheDir);
660
1051
  const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
661
- // Try esbuild first
1052
+ // Try esbuild
662
1053
  try {
663
1054
  const esbuild = (await import('esbuild'));
664
- await fs.ensureDir(cacheDir);
665
1055
  await esbuild.build({
666
1056
  entryPoints: [absPath],
667
1057
  bundle: true,
668
1058
  platform: 'node',
669
1059
  format: 'esm',
670
- target: 'node22',
1060
+ target: 'node20',
671
1061
  outfile: cacheFile,
672
1062
  sourcemap: false,
673
1063
  logLevel: 'silent',
674
1064
  });
675
- return await importDefault(url.pathToFileURL(cacheFile).toString());
1065
+ const result = await importDefault$1(url.pathToFileURL(cacheFile).toString());
1066
+ // Best-effort: trim older cache files for this source.
1067
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1068
+ return result;
676
1069
  }
677
1070
  catch {
678
- // no esbuild; fall back to TS transpile for simple modules
1071
+ /* fall through to TS transpile */
679
1072
  }
1073
+ // TypeScript transpile fallback
680
1074
  try {
681
1075
  const ts = (await import('typescript'));
682
1076
  const code = await fs.readFile(absPath, 'utf-8');
@@ -686,16 +1080,19 @@ const loadDynamicFromPath = async (absPath) => {
686
1080
  target: 'ES2022',
687
1081
  moduleResolution: 'NodeNext',
688
1082
  },
689
- });
690
- await fs.ensureDir(cacheDir);
691
- await fs.writeFile(cacheFile, out.outputText, 'utf-8');
692
- return await importDefault(url.pathToFileURL(cacheFile).toString());
1083
+ }).outputText;
1084
+ await fs.writeFile(cacheFile, out, 'utf-8');
1085
+ const result = await importDefault$1(url.pathToFileURL(cacheFile).toString());
1086
+ // Best-effort: trim older cache files for this source.
1087
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1088
+ return result;
693
1089
  }
694
1090
  catch {
695
- throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
696
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1091
+ // Caller decides final error wording; rethrow for upstream mapping.
1092
+ throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
697
1093
  }
698
1094
  };
1095
+
699
1096
  /**
700
1097
  * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
701
1098
  *
@@ -780,7 +1177,16 @@ const getDotenv = async (options = {}) => {
780
1177
  }
781
1178
  else if (dynamicPath) {
782
1179
  const absDynamicPath = path.resolve(dynamicPath);
783
- dynamic = await loadDynamicFromPath(absDynamicPath);
1180
+ if (await fs.exists(absDynamicPath)) {
1181
+ try {
1182
+ dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1183
+ }
1184
+ catch {
1185
+ // Preserve legacy error text for compatibility with tests/docs.
1186
+ throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1187
+ `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1188
+ }
1189
+ }
784
1190
  }
785
1191
  if (dynamic) {
786
1192
  try {
@@ -819,72 +1225,320 @@ const getDotenv = async (options = {}) => {
819
1225
  };
820
1226
 
821
1227
  /**
822
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
823
- * - If the user explicitly enabled the flag, return true.
824
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
825
- * - Otherwise, adopt the default (true set; false/undefined → unset).
826
- *
827
- * @param exclude - The "on" flag value as parsed by Commander.
828
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
829
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
830
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
831
- *
832
- * @example
833
- * ```ts
834
- * resolveExclusion(undefined, undefined, true); // => true
835
- * ```
1228
+ * Zod schemas for configuration files discovered by the new loader. *
1229
+ * Notes:
1230
+ * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
1231
+ * - RESOLVED: normalized shapes (paths always string[]).
1232
+ * - For this step (JSON/YAML only), any defined `dynamic` will be rejected by the loader.
836
1233
  */
837
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1234
+ // String-only env value map
1235
+ const stringMap = zod.z.record(zod.z.string(), zod.z.string());
1236
+ const envStringMap = zod.z.record(zod.z.string(), stringMap);
1237
+ // Allow string[] or single string for "paths" in RAW; normalize later.
1238
+ const rawPathsSchema = zod.z.union([zod.z.array(zod.z.string()), zod.z.string()]).optional();
1239
+ const getDotenvConfigSchemaRaw = zod.z.object({
1240
+ dotenvToken: zod.z.string().optional(),
1241
+ privateToken: zod.z.string().optional(),
1242
+ paths: rawPathsSchema,
1243
+ loadProcess: zod.z.boolean().optional(),
1244
+ log: zod.z.boolean().optional(),
1245
+ shell: zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
1246
+ scripts: zod.z.record(zod.z.string(), zod.z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
1247
+ vars: stringMap.optional(), // public, global
1248
+ envVars: envStringMap.optional(), // public, per-env
1249
+ // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
1250
+ dynamic: zod.z.unknown().optional(),
1251
+ // Per-plugin config bag; validated by plugins/host when used.
1252
+ plugins: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
1253
+ });
1254
+ // Normalize paths to string[]
1255
+ const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
1256
+ const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
1257
+ ...raw,
1258
+ paths: normalizePaths(raw.paths),
1259
+ }));
1260
+
1261
+ // Discovery candidates (first match wins per scope/privacy).
1262
+ // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
1263
+ const PUBLIC_FILENAMES = [
1264
+ 'getdotenv.config.json',
1265
+ 'getdotenv.config.yaml',
1266
+ 'getdotenv.config.yml',
1267
+ 'getdotenv.config.js',
1268
+ 'getdotenv.config.mjs',
1269
+ 'getdotenv.config.cjs',
1270
+ 'getdotenv.config.ts',
1271
+ 'getdotenv.config.mts',
1272
+ 'getdotenv.config.cts',
1273
+ ];
1274
+ const LOCAL_FILENAMES = [
1275
+ 'getdotenv.config.local.json',
1276
+ 'getdotenv.config.local.yaml',
1277
+ 'getdotenv.config.local.yml',
1278
+ 'getdotenv.config.local.js',
1279
+ 'getdotenv.config.local.mjs',
1280
+ 'getdotenv.config.local.cjs',
1281
+ 'getdotenv.config.local.ts',
1282
+ 'getdotenv.config.local.mts',
1283
+ 'getdotenv.config.local.cts',
1284
+ ];
1285
+ const isYaml = (p) => ['.yaml', '.yml'].includes(path.extname(p).toLowerCase());
1286
+ const isJson = (p) => path.extname(p).toLowerCase() === '.json';
1287
+ const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(path.extname(p).toLowerCase());
1288
+ // --- Internal JS/TS module loader helpers (default export) ---
1289
+ const importDefault = async (fileUrl) => {
1290
+ const mod = (await import(fileUrl));
1291
+ return mod.default;
1292
+ };
1293
+ const cacheName = (absPath, suffix) => {
1294
+ // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
1295
+ const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
1296
+ return `${base}.${suffix}.mjs`;
1297
+ };
1298
+ const ensureDir = async (dir) => {
1299
+ await fs.ensureDir(dir);
1300
+ return dir;
1301
+ };
1302
+ const loadJsTsDefault = async (absPath) => {
1303
+ const fileUrl = url.pathToFileURL(absPath).toString();
1304
+ const ext = path.extname(absPath).toLowerCase();
1305
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
1306
+ return importDefault(fileUrl);
1307
+ }
1308
+ // Try direct import first in case a TS loader is active.
1309
+ try {
1310
+ const val = await importDefault(fileUrl);
1311
+ if (val)
1312
+ return val;
1313
+ }
1314
+ catch {
1315
+ /* fallthrough */
1316
+ }
1317
+ // esbuild bundle to a temp ESM file
1318
+ try {
1319
+ const esbuild = (await import('esbuild'));
1320
+ const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
1321
+ const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
1322
+ await esbuild.build({
1323
+ entryPoints: [absPath],
1324
+ bundle: true,
1325
+ platform: 'node',
1326
+ format: 'esm',
1327
+ target: 'node20',
1328
+ outfile,
1329
+ sourcemap: false,
1330
+ logLevel: 'silent',
1331
+ });
1332
+ return await importDefault(url.pathToFileURL(outfile).toString());
1333
+ }
1334
+ catch {
1335
+ /* fallthrough to TS transpile */
1336
+ }
1337
+ // typescript.transpileModule simple transpile (single-file)
1338
+ try {
1339
+ const ts = (await import('typescript'));
1340
+ const src = await fs.readFile(absPath, 'utf-8');
1341
+ const out = ts.transpileModule(src, {
1342
+ compilerOptions: {
1343
+ module: 'ESNext',
1344
+ target: 'ES2022',
1345
+ moduleResolution: 'NodeNext',
1346
+ },
1347
+ }).outputText;
1348
+ const outDir = await ensureDir(path.resolve('.tsbuild', 'getdotenv-config'));
1349
+ const outfile = path.join(outDir, cacheName(absPath, 'ts'));
1350
+ await fs.writeFile(outfile, out, 'utf-8');
1351
+ return await importDefault(url.pathToFileURL(outfile).toString());
1352
+ }
1353
+ catch {
1354
+ throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
1355
+ }
1356
+ };
838
1357
  /**
839
- * Resolve an optional flag with "--exclude-all" overrides.
840
- * If excludeAll is set and the individual "...-off" is not, force true.
841
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
842
- * Otherwise, adopt the default (true → set; false/undefined → unset).
843
- *
844
- * @param exclude - Individual include/exclude flag.
845
- * @param excludeOff - Individual "...-off" flag.
846
- * @param defaultValue - Default for the individual flag.
847
- * @param excludeAll - Global "exclude-all" flag.
848
- * @param excludeAllOff - Global "exclude-all-off" flag.
1358
+ * Discover JSON/YAML config files in the packaged root and project root.
1359
+ * Order: packaged public project public project local. */
1360
+ const discoverConfigFiles = async (importMetaUrl) => {
1361
+ const files = [];
1362
+ // Packaged root via importMetaUrl (optional)
1363
+ if (importMetaUrl) {
1364
+ const fromUrl = url.fileURLToPath(importMetaUrl);
1365
+ const packagedRoot = await packageDirectory.packageDirectory({ cwd: fromUrl });
1366
+ if (packagedRoot) {
1367
+ for (const name of PUBLIC_FILENAMES) {
1368
+ const p = path.join(packagedRoot, name);
1369
+ if (await fs.pathExists(p)) {
1370
+ files.push({ path: p, privacy: 'public', scope: 'packaged' });
1371
+ break; // only one public file expected per scope
1372
+ }
1373
+ }
1374
+ // By policy, packaged .local is not expected; skip even if present.
1375
+ }
1376
+ }
1377
+ // Project root (from current working directory)
1378
+ const projectRoot = await packageDirectory.packageDirectory();
1379
+ if (projectRoot) {
1380
+ for (const name of PUBLIC_FILENAMES) {
1381
+ const p = path.join(projectRoot, name);
1382
+ if (await fs.pathExists(p)) {
1383
+ files.push({ path: p, privacy: 'public', scope: 'project' });
1384
+ break;
1385
+ }
1386
+ }
1387
+ for (const name of LOCAL_FILENAMES) {
1388
+ const p = path.join(projectRoot, name);
1389
+ if (await fs.pathExists(p)) {
1390
+ files.push({ path: p, privacy: 'local', scope: 'project' });
1391
+ break;
1392
+ }
1393
+ }
1394
+ }
1395
+ return files;
1396
+ };
1397
+ /**
1398
+ * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
1399
+ * Validates with Zod RAW schema, then normalizes to RESOLVED.
849
1400
  *
850
- * @example
851
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1401
+ * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
1402
+ * For JS/TS: default export is loaded; "dynamic" is allowed.
1403
+ */
1404
+ const loadConfigFile = async (filePath) => {
1405
+ let raw = {};
1406
+ try {
1407
+ const abs = path.resolve(filePath);
1408
+ if (isJsOrTs(abs)) {
1409
+ // JS/TS support: load default export via robust pipeline.
1410
+ const mod = await loadJsTsDefault(abs);
1411
+ raw = mod ?? {};
1412
+ }
1413
+ else {
1414
+ const txt = await fs.readFile(abs, 'utf-8');
1415
+ raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
1416
+ }
1417
+ }
1418
+ catch (err) {
1419
+ throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
1420
+ }
1421
+ // Validate RAW
1422
+ const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
1423
+ if (!parsed.success) {
1424
+ const msgs = parsed.error.issues
1425
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
1426
+ .join('\n');
1427
+ throw new Error(`Invalid config ${filePath}:\n${msgs}`);
1428
+ }
1429
+ // Disallow dynamic in JSON/YAML; allow in JS/TS
1430
+ if (!isJsOrTs(filePath) && parsed.data.dynamic !== undefined) {
1431
+ throw new Error(`Config ${filePath} specifies "dynamic"; JSON/YAML configs cannot include dynamic in this step. Use JS/TS config.`);
1432
+ }
1433
+ return getDotenvConfigSchemaResolved.parse(parsed.data);
1434
+ };
1435
+ /**
1436
+ * Discover and load configs into resolved shapes, ordered by scope/privacy.
1437
+ * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
852
1438
  */
853
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) => excludeAll && !excludeOff
854
- ? true
855
- : excludeAllOff && !exclude
856
- ? undefined
857
- : defaultValue
858
- ? true
859
- : undefined;
1439
+ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
1440
+ const discovered = await discoverConfigFiles(importMetaUrl);
1441
+ const result = {};
1442
+ for (const f of discovered) {
1443
+ const cfg = await loadConfigFile(f.path);
1444
+ if (f.scope === 'packaged') {
1445
+ // packaged public only
1446
+ result.packaged = cfg;
1447
+ }
1448
+ else {
1449
+ result.project ??= {};
1450
+ if (f.privacy === 'public')
1451
+ result.project.public = cfg;
1452
+ else
1453
+ result.project.local = cfg;
1454
+ }
1455
+ }
1456
+ return result;
1457
+ };
1458
+
860
1459
  /**
861
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
862
- * delete when undefined; assign when defined without requiring an index signature on T.
1460
+ * Resolve dotenv values using the config-loader/overlay path (always-on in
1461
+ * host/generator flows; no-op when no config files are present).
863
1462
  *
864
- * @typeParam T - Target object type.
865
- * @param obj - The object to write to.
866
- * @param key - The optional boolean property key of {@link T}.
867
- * @param value - The value to set or `undefined` to unset.
868
- *
869
- * @remarks
870
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1463
+ * Order:
1464
+ * 1) Compute base from files only (exclude dynamic; ignore programmatic vars).
1465
+ * 2) Discover packaged + project config sources and overlay onto base.
1466
+ * 3) Apply dynamics in order:
1467
+ * programmatic dynamic \> config dynamic (packaged → project public → project local)
1468
+ * \> file dynamicPath. * 4) Optionally write outputPath, log, and merge into process.env.
871
1469
  */
872
- const setOptionalFlag = (obj, key, value) => {
873
- const target = obj;
874
- const k = key;
875
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
876
- if (value === undefined)
877
- delete target[k];
878
- else
879
- target[k] = value;
1470
+ const resolveDotenvWithConfigLoader = async (validated) => {
1471
+ // 1) Base from files, no dynamic, no programmatic vars
1472
+ const base = await getDotenv({
1473
+ ...validated,
1474
+ // Build a pure base without side effects or logging.
1475
+ excludeDynamic: true,
1476
+ vars: {},
1477
+ log: false,
1478
+ loadProcess: false,
1479
+ outputPath: undefined,
1480
+ });
1481
+ // 2) Discover config sources (packaged via this module's import.meta.url)
1482
+ const sources = await resolveGetDotenvConfigSources((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
1483
+ const dotenv = overlayEnv({
1484
+ base,
1485
+ env: validated.env ?? validated.defaultEnv,
1486
+ configs: sources,
1487
+ ...(validated.vars ? { programmaticVars: validated.vars } : {}),
1488
+ });
1489
+ // Helper to apply a dynamic map progressively.
1490
+ const applyDynamic = (target, dynamic, env) => {
1491
+ if (!dynamic)
1492
+ return;
1493
+ for (const key of Object.keys(dynamic)) {
1494
+ const value = typeof dynamic[key] === 'function'
1495
+ ? dynamic[key](target, env)
1496
+ : dynamic[key];
1497
+ Object.assign(target, { [key]: value });
1498
+ }
1499
+ };
1500
+ // 3) Apply dynamics in order
1501
+ applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
1502
+ applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1503
+ applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1504
+ applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
1505
+ // file dynamicPath (lowest)
1506
+ if (validated.dynamicPath) {
1507
+ const absDynamicPath = path.resolve(validated.dynamicPath);
1508
+ try {
1509
+ const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
1510
+ applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
1511
+ }
1512
+ catch {
1513
+ throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
1514
+ }
1515
+ }
1516
+ // 4) Output/log/process merge
1517
+ if (validated.outputPath) {
1518
+ await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
1519
+ const value = dotenv[key] ?? '';
1520
+ return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
1521
+ }, ''), { encoding: 'utf-8' });
1522
+ }
1523
+ const logger = validated.logger ?? console;
1524
+ if (validated.log)
1525
+ logger.log(dotenv);
1526
+ if (validated.loadProcess)
1527
+ Object.assign(process.env, dotenv);
1528
+ return dotenv;
880
1529
  };
881
1530
 
1531
+ /**
1532
+ * Omit a "logger" key from an options object in a typed manner.
1533
+ */
1534
+ const omitLogger = (obj) => {
1535
+ const { logger: _omitted, ...rest } = obj;
1536
+ return rest;
1537
+ };
882
1538
  /**
883
1539
  * Build the Commander preSubcommand hook using the provided context.
884
- *
885
- * Responsibilities:
886
- * - Merge parent CLI options with current invocation (parent \< current).
887
- * - Resolve tri-state flags, including `--exclude-all` overrides.
1540
+ * * Responsibilities:
1541
+ * - Merge parent CLI options with current invocation (parent \< current). * - Resolve tri-state flags, including `--exclude-all` overrides.
888
1542
  * - Normalize the shell setting to a concrete value (string | boolean).
889
1543
  * - Persist merged options on the command instance and pass to subcommands.
890
1544
  * - Execute {@link getDotenv} and optional post-hook.
@@ -894,95 +1548,52 @@ const setOptionalFlag = (obj, key, value) => {
894
1548
  * @returns An async hook suitable for Commander’s `preSubcommand`.
895
1549
  *
896
1550
  * @example `program.hook('preSubcommand', makePreSubcommandHook(ctx));`
897
- */ const makePreSubcommandHook = ({ logger, preHook, postHook, defaults }) => async (thisCommand) => {
898
- // Get parent command GetDotenvCliOptions.
899
- const parentGetDotenvCliOptions = process.env.getDotenvCliOptions
900
- ? JSON.parse(process.env.getDotenvCliOptions)
901
- : undefined;
902
- // Get raw CLI options from commander.
903
- const rawCliOptions = thisCommand.opts();
904
- // Extract current GetDotenvCliOptions from raw CLI options.
905
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, scripts, shellOff, ...rawCliOptionsRest } = rawCliOptions;
906
- const currentGetDotenvCliOptions = rawCliOptionsRest;
907
- if (scripts)
908
- currentGetDotenvCliOptions.scripts = JSON.parse(scripts);
909
- // Merge current & parent GetDotenvCliOptions (parent < current).
910
- const mergedGetDotenvCliOptions = defaultsDeep((parentGetDotenvCliOptions ?? {}), currentGetDotenvCliOptions);
911
- // Resolve flags using defaults + current + exclude-all toggles.
912
- setOptionalFlag(mergedGetDotenvCliOptions, 'debug', resolveExclusion(mergedGetDotenvCliOptions.debug, debugOff, defaults.debug));
913
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeDynamic', resolveExclusionAll(mergedGetDotenvCliOptions.excludeDynamic, excludeDynamicOff, defaults.excludeDynamic, excludeAll, excludeAllOff));
914
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeEnv', resolveExclusionAll(mergedGetDotenvCliOptions.excludeEnv, excludeEnvOff, defaults.excludeEnv, excludeAll, excludeAllOff));
915
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeGlobal', resolveExclusionAll(mergedGetDotenvCliOptions.excludeGlobal, excludeGlobalOff, defaults.excludeGlobal, excludeAll, excludeAllOff));
916
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludePrivate', resolveExclusionAll(mergedGetDotenvCliOptions.excludePrivate, excludePrivateOff, defaults.excludePrivate, excludeAll, excludeAllOff));
917
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludePublic', resolveExclusionAll(mergedGetDotenvCliOptions.excludePublic, excludePublicOff, defaults.excludePublic, excludeAll, excludeAllOff));
918
- setOptionalFlag(mergedGetDotenvCliOptions, 'log', resolveExclusion(mergedGetDotenvCliOptions.log, logOff, defaults.log));
919
- setOptionalFlag(mergedGetDotenvCliOptions, 'loadProcess', resolveExclusion(mergedGetDotenvCliOptions.loadProcess, loadProcessOff, defaults.loadProcess));
920
- // Normalize shell for predictability: explicit default shell per OS.
921
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
922
- let resolvedShell = mergedGetDotenvCliOptions.shell;
923
- if (shellOff)
924
- resolvedShell = false;
925
- else if (resolvedShell === true || resolvedShell === undefined) {
926
- resolvedShell = defaultShell;
927
- }
928
- else if (typeof resolvedShell !== 'string' &&
929
- typeof defaults.shell === 'string') {
930
- resolvedShell = defaults.shell;
931
- }
932
- mergedGetDotenvCliOptions.shell = resolvedShell;
933
- if (mergedGetDotenvCliOptions.debug && parentGetDotenvCliOptions) {
934
- logger.debug('\n*** parent command GetDotenvCliOptions ***\n', parentGetDotenvCliOptions);
935
- }
936
- if (mergedGetDotenvCliOptions.debug)
937
- logger.debug('\n*** current command raw options ***\n', rawCliOptions);
938
- if (mergedGetDotenvCliOptions.debug)
939
- logger.debug('\n*** merged GetDotenvCliOptions ***\n', {
940
- mergedGetDotenvCliOptions,
941
- });
942
- // Execute pre-hook.
943
- if (preHook) {
944
- await preHook(mergedGetDotenvCliOptions);
945
- if (mergedGetDotenvCliOptions.debug)
946
- logger.debug('\n*** GetDotenvCliOptions after pre-hook ***\n', mergedGetDotenvCliOptions);
947
- }
948
- // Persist GetDotenvCliOptions in command for subcommand access.
949
- thisCommand.getDotenvCliOptions = mergedGetDotenvCliOptions;
950
- // Execute getdotenv.
951
- const dotenv = await getDotenv(getDotenvCliOptions2Options(mergedGetDotenvCliOptions));
952
- if (mergedGetDotenvCliOptions.debug)
953
- logger.debug('\n*** getDotenv output ***\n', dotenv);
954
- // Execute post-hook.
955
- if (postHook)
956
- await postHook(dotenv);
957
- // Execute command.
958
- const args = thisCommand.args ?? [];
959
- const isCommand = typeof command === 'string' && command.length > 0;
960
- if (isCommand && args.length > 0) {
961
- const lr = logger;
962
- (lr.error ?? lr.log)(`--command option conflicts with cmd subcommand.`);
963
- process.exit(0);
964
- }
965
- if (typeof command === 'string' && command.length > 0) {
966
- const cmd = resolveCommand(mergedGetDotenvCliOptions.scripts, command);
967
- if (mergedGetDotenvCliOptions.debug)
968
- logger.debug('\n*** command ***\n', cmd);
969
- const envSafe = {
970
- ...mergedGetDotenvCliOptions,
971
- };
972
- delete envSafe.logger;
973
- await execa.execaCommand(cmd, {
974
- env: {
975
- ...process.env,
976
- getDotenvCliOptions: JSON.stringify(envSafe),
977
- },
978
- shell: resolveShell(mergedGetDotenvCliOptions.scripts, command, mergedGetDotenvCliOptions.shell),
979
- stdio: 'inherit',
980
- });
981
- }
1551
+ */
1552
+ const makePreSubcommandHook = ({ logger, preHook, postHook, defaults, }) => {
1553
+ return async (thisCommand) => {
1554
+ // Get raw CLI options from commander.
1555
+ const rawCliOptions = thisCommand.opts();
1556
+ const { merged: mergedGetDotenvCliOptions, command: commandOpt } = resolveCliOptions(rawCliOptions, defaults, process.env.getDotenvCliOptions);
1557
+ // Optional debug logging retained via mergedGetDotenvCliOptions.debug if desired. // Execute pre-hook.
1558
+ if (preHook) {
1559
+ await preHook(mergedGetDotenvCliOptions);
1560
+ if (mergedGetDotenvCliOptions.debug)
1561
+ logger.debug('\n*** GetDotenvCliOptions after pre-hook ***\n', mergedGetDotenvCliOptions);
1562
+ }
1563
+ // Persist GetDotenvCliOptions in command for subcommand access.
1564
+ thisCommand.getDotenvCliOptions =
1565
+ mergedGetDotenvCliOptions;
1566
+ // Execute getdotenv via always-on config loader/overlay path.
1567
+ const serviceOptions = getDotenvCliOptions2Options(mergedGetDotenvCliOptions);
1568
+ const dotenv = await resolveDotenvWithConfigLoader(serviceOptions);
1569
+ // Execute post-hook.
1570
+ if (postHook)
1571
+ await postHook(dotenv); // Execute command.
1572
+ const args = thisCommand.args ?? [];
1573
+ const isCommand = typeof commandOpt === 'string' && commandOpt.length > 0;
1574
+ if (isCommand && args.length > 0) {
1575
+ const lr = logger;
1576
+ (lr.error ?? lr.log)(`--command option conflicts with cmd subcommand.`);
1577
+ process.exit(0);
1578
+ }
1579
+ if (typeof commandOpt === 'string' && commandOpt.length > 0) {
1580
+ const cmd = resolveCommand(mergedGetDotenvCliOptions.scripts, commandOpt);
1581
+ if (mergedGetDotenvCliOptions.debug)
1582
+ logger.debug('\n*** command ***\n', cmd);
1583
+ // Build a logger-free bag for env round-trip.
1584
+ const envSafe = omitLogger(mergedGetDotenvCliOptions);
1585
+ await execa.execaCommand(cmd, {
1586
+ env: { ...process.env, getDotenvCliOptions: JSON.stringify(envSafe) },
1587
+ shell: resolveShell(mergedGetDotenvCliOptions.scripts, commandOpt, mergedGetDotenvCliOptions.shell),
1588
+ stdio: 'inherit',
1589
+ });
1590
+ }
1591
+ };
982
1592
  };
983
1593
 
984
1594
  /**
985
- * Generate a Commander CLI Command for get-dotenv. * Orchestration only: delegates building and lifecycle hooks.
1595
+ * Generate a Commander CLI Command for get-dotenv.
1596
+ * Orchestration only: delegates building and lifecycle hooks.
986
1597
  */
987
1598
  const generateGetDotenvCli = async (customOptions) => {
988
1599
  const options = await resolveGetDotenvCliGenerateOptions(customOptions);