@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
@@ -1,14 +1,434 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { execaCommand } from 'execa';
4
- import { globby } from 'globby';
5
- import { packageDirectory } from 'package-directory';
6
- import path, { join } from 'path';
7
3
  import fs from 'fs-extra';
8
- import url, { fileURLToPath } from 'url';
9
- import { createHash } from 'crypto';
4
+ import { packageDirectory } from 'package-directory';
5
+ import path, { join, extname } from 'path';
6
+ import { z } from 'zod';
7
+ import url, { fileURLToPath, pathToFileURL } from 'url';
8
+ import YAML from 'yaml';
10
9
  import { nanoid } from 'nanoid';
11
10
  import { parse } from 'dotenv';
11
+ import { createHash } from 'crypto';
12
+ import { execa, execaCommand } from 'execa';
13
+ import { globby } from 'globby';
14
+ import { stdin, stdout } from 'node:process';
15
+ import { createInterface } from 'readline/promises';
16
+
17
+ // Base root CLI defaults (shared; kept untyped here to avoid cross-layer deps).
18
+ const baseRootOptionDefaults = {
19
+ dotenvToken: '.env',
20
+ loadProcess: true,
21
+ logger: console,
22
+ paths: './',
23
+ pathsDelimiter: ' ',
24
+ privateToken: 'local',
25
+ scripts: {
26
+ 'git-status': {
27
+ cmd: 'git branch --show-current && git status -s -u',
28
+ shell: true,
29
+ },
30
+ },
31
+ shell: true,
32
+ vars: '',
33
+ varsAssignor: '=',
34
+ varsDelimiter: ' ',
35
+ // tri-state flags default to unset unless explicitly provided
36
+ // (debug/log/exclude* resolved via flag utils)
37
+ };
38
+
39
+ const baseGetDotenvCliOptions = baseRootOptionDefaults;
40
+
41
+ /** @internal */
42
+ const isPlainObject = (value) => value !== null &&
43
+ typeof value === 'object' &&
44
+ Object.getPrototypeOf(value) === Object.prototype;
45
+ const mergeInto = (target, source) => {
46
+ for (const [key, sVal] of Object.entries(source)) {
47
+ if (sVal === undefined)
48
+ continue; // do not overwrite with undefined
49
+ const tVal = target[key];
50
+ if (isPlainObject(tVal) && isPlainObject(sVal)) {
51
+ target[key] = mergeInto({ ...tVal }, sVal);
52
+ }
53
+ else if (isPlainObject(sVal)) {
54
+ target[key] = mergeInto({}, sVal);
55
+ }
56
+ else {
57
+ target[key] = sVal;
58
+ }
59
+ }
60
+ return target;
61
+ };
62
+ /**
63
+ * Perform a deep defaults-style merge across plain objects. *
64
+ * - Only merges plain objects (prototype === Object.prototype).
65
+ * - Arrays and non-objects are replaced, not merged.
66
+ * - `undefined` values are ignored and do not overwrite prior values.
67
+ *
68
+ * @typeParam T - The resulting shape after merging all layers.
69
+ * @param layers - Zero or more partial layers in ascending precedence order.
70
+ * @returns The merged object typed as {@link T}.
71
+ *
72
+ * @example
73
+ * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
74
+ * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
75
+ */
76
+ const defaultsDeep = (...layers) => {
77
+ const result = layers
78
+ .filter(Boolean)
79
+ .reduce((acc, layer) => mergeInto(acc, layer), {});
80
+ return result;
81
+ };
82
+
83
+ // src/GetDotenvOptions.ts
84
+ const getDotenvOptionsFilename = 'getdotenv.config.json'; /**
85
+ * A minimal representation of an environment key/value mapping.
86
+ * Values may be `undefined` to represent "unset".
87
+ */
88
+ /**
89
+ * Converts programmatic CLI options to `getDotenv` options. *
90
+ * @param cliOptions - CLI options. Defaults to `{}`.
91
+ *
92
+ * @returns `getDotenv` options.
93
+ */
94
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
95
+ /**
96
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
97
+ *
98
+ * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter
99
+ * or a regular expression pattern into a string array. * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
100
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
101
+ * - Drops CLI-only keys that have no programmatic equivalent.
102
+ *
103
+ * @remarks
104
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
105
+ */
106
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
107
+ // Create a shallow copy then delete optional CLI-only keys if present.
108
+ const restObj = { ...rest };
109
+ delete restObj.debug;
110
+ delete restObj.scripts;
111
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
112
+ const kvPairs = (vars
113
+ ? splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
114
+ ? RegExp(varsAssignorPattern)
115
+ : (varsAssignor ?? '=')))
116
+ : []);
117
+ const parsedVars = Object.fromEntries(kvPairs);
118
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
119
+ return {
120
+ ...restObj,
121
+ ...(paths !== undefined
122
+ ? {
123
+ paths: splitBy(paths, pathsDelimiter, pathsDelimiterPattern),
124
+ }
125
+ : {}),
126
+ ...(vars !== undefined ? { vars: parsedVars } : {}),
127
+ };
128
+ };
129
+ const resolveGetDotenvOptions = async (customOptions) => {
130
+ /**
131
+ * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
132
+ *
133
+ * 1. Base defaults derived from the CLI generator defaults
134
+ * ({@link baseGetDotenvCliOptions}).
135
+ * 2. Local project overrides from a `getdotenv.config.json` in the nearest
136
+ * package root (if present).
137
+ * 3. The provided {@link customOptions}.
138
+ *
139
+ * The result preserves explicit empty values and drops only `undefined`.
140
+ *
141
+ * @returns Fully-resolved {@link GetDotenvOptions}.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * const options = await resolveGetDotenvOptions({ env: 'dev' });
146
+ * ```
147
+ */
148
+ const localPkgDir = await packageDirectory();
149
+ const localOptionsPath = localPkgDir
150
+ ? join(localPkgDir, getDotenvOptionsFilename)
151
+ : undefined;
152
+ const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
153
+ ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
154
+ : {});
155
+ // Merge order: base < local < custom (custom has highest precedence)
156
+ const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
157
+ const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
158
+ const result = defaultsDeep(defaultsFromCli, customOptions);
159
+ return {
160
+ ...result, // Keep explicit empty strings/zeros; drop only undefined
161
+ vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
162
+ };
163
+ };
164
+
165
+ /**
166
+ * Zod schemas for programmatic GetDotenv options.
167
+ *
168
+ * NOTE: These schemas are introduced without wiring to avoid behavior changes.
169
+ * Legacy paths continue to use existing types/logic. The new plugin host will
170
+ * use these schemas in strict mode; legacy paths will adopt them in warn mode
171
+ * later per the staged plan.
172
+ */
173
+ // Minimal process env representation: string values or undefined to indicate "unset".
174
+ const processEnvSchema = z.record(z.string(), z.string().optional());
175
+ // RAW: all fields optional — undefined means "inherit" from lower layers.
176
+ const getDotenvOptionsSchemaRaw = z.object({
177
+ defaultEnv: z.string().optional(),
178
+ dotenvToken: z.string().optional(),
179
+ dynamicPath: z.string().optional(),
180
+ // Dynamic map is intentionally wide for now; refine once sources are normalized.
181
+ dynamic: z.record(z.string(), z.unknown()).optional(),
182
+ env: z.string().optional(),
183
+ excludeDynamic: z.boolean().optional(),
184
+ excludeEnv: z.boolean().optional(),
185
+ excludeGlobal: z.boolean().optional(),
186
+ excludePrivate: z.boolean().optional(),
187
+ excludePublic: z.boolean().optional(),
188
+ loadProcess: z.boolean().optional(),
189
+ log: z.boolean().optional(),
190
+ outputPath: z.string().optional(),
191
+ paths: z.array(z.string()).optional(),
192
+ privateToken: z.string().optional(),
193
+ vars: processEnvSchema.optional(),
194
+ // Host-only feature flag: guarded integration of config loader/overlay
195
+ useConfigLoader: z.boolean().optional(),
196
+ });
197
+ // RESOLVED: service-boundary contract (post-inheritance).
198
+ // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
199
+ const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
200
+
201
+ /**
202
+ * Zod schemas for configuration files discovered by the new loader. *
203
+ * Notes:
204
+ * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
205
+ * - RESOLVED: normalized shapes (paths always string[]).
206
+ * - For this step (JSON/YAML only), any defined `dynamic` will be rejected by the loader.
207
+ */
208
+ // String-only env value map
209
+ const stringMap = z.record(z.string(), z.string());
210
+ const envStringMap = z.record(z.string(), stringMap);
211
+ // Allow string[] or single string for "paths" in RAW; normalize later.
212
+ const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
213
+ const getDotenvConfigSchemaRaw = z.object({
214
+ dotenvToken: z.string().optional(),
215
+ privateToken: z.string().optional(),
216
+ paths: rawPathsSchema,
217
+ loadProcess: z.boolean().optional(),
218
+ log: z.boolean().optional(),
219
+ shell: z.union([z.string(), z.boolean()]).optional(),
220
+ scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
221
+ vars: stringMap.optional(), // public, global
222
+ envVars: envStringMap.optional(), // public, per-env
223
+ // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
224
+ dynamic: z.unknown().optional(),
225
+ // Per-plugin config bag; validated by plugins/host when used.
226
+ plugins: z.record(z.string(), z.unknown()).optional(),
227
+ });
228
+ // Normalize paths to string[]
229
+ const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
230
+ const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
231
+ ...raw,
232
+ paths: normalizePaths(raw.paths),
233
+ }));
234
+
235
+ // Discovery candidates (first match wins per scope/privacy).
236
+ // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
237
+ const PUBLIC_FILENAMES = [
238
+ 'getdotenv.config.json',
239
+ 'getdotenv.config.yaml',
240
+ 'getdotenv.config.yml',
241
+ 'getdotenv.config.js',
242
+ 'getdotenv.config.mjs',
243
+ 'getdotenv.config.cjs',
244
+ 'getdotenv.config.ts',
245
+ 'getdotenv.config.mts',
246
+ 'getdotenv.config.cts',
247
+ ];
248
+ const LOCAL_FILENAMES = [
249
+ 'getdotenv.config.local.json',
250
+ 'getdotenv.config.local.yaml',
251
+ 'getdotenv.config.local.yml',
252
+ 'getdotenv.config.local.js',
253
+ 'getdotenv.config.local.mjs',
254
+ 'getdotenv.config.local.cjs',
255
+ 'getdotenv.config.local.ts',
256
+ 'getdotenv.config.local.mts',
257
+ 'getdotenv.config.local.cts',
258
+ ];
259
+ const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
260
+ const isJson = (p) => extname(p).toLowerCase() === '.json';
261
+ const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
262
+ // --- Internal JS/TS module loader helpers (default export) ---
263
+ const importDefault$1 = async (fileUrl) => {
264
+ const mod = (await import(fileUrl));
265
+ return mod.default;
266
+ };
267
+ const cacheName = (absPath, suffix) => {
268
+ // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
269
+ const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
270
+ return `${base}.${suffix}.mjs`;
271
+ };
272
+ const ensureDir$1 = async (dir) => {
273
+ await fs.ensureDir(dir);
274
+ return dir;
275
+ };
276
+ const loadJsTsDefault = async (absPath) => {
277
+ const fileUrl = pathToFileURL(absPath).toString();
278
+ const ext = extname(absPath).toLowerCase();
279
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
280
+ return importDefault$1(fileUrl);
281
+ }
282
+ // Try direct import first in case a TS loader is active.
283
+ try {
284
+ const val = await importDefault$1(fileUrl);
285
+ if (val)
286
+ return val;
287
+ }
288
+ catch {
289
+ /* fallthrough */
290
+ }
291
+ // esbuild bundle to a temp ESM file
292
+ try {
293
+ const esbuild = (await import('esbuild'));
294
+ const outDir = await ensureDir$1(path.resolve('.tsbuild', 'getdotenv-config'));
295
+ const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
296
+ await esbuild.build({
297
+ entryPoints: [absPath],
298
+ bundle: true,
299
+ platform: 'node',
300
+ format: 'esm',
301
+ target: 'node20',
302
+ outfile,
303
+ sourcemap: false,
304
+ logLevel: 'silent',
305
+ });
306
+ return await importDefault$1(pathToFileURL(outfile).toString());
307
+ }
308
+ catch {
309
+ /* fallthrough to TS transpile */
310
+ }
311
+ // typescript.transpileModule simple transpile (single-file)
312
+ try {
313
+ const ts = (await import('typescript'));
314
+ const src = await fs.readFile(absPath, 'utf-8');
315
+ const out = ts.transpileModule(src, {
316
+ compilerOptions: {
317
+ module: 'ESNext',
318
+ target: 'ES2022',
319
+ moduleResolution: 'NodeNext',
320
+ },
321
+ }).outputText;
322
+ const outDir = await ensureDir$1(path.resolve('.tsbuild', 'getdotenv-config'));
323
+ const outfile = path.join(outDir, cacheName(absPath, 'ts'));
324
+ await fs.writeFile(outfile, out, 'utf-8');
325
+ return await importDefault$1(pathToFileURL(outfile).toString());
326
+ }
327
+ catch {
328
+ throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
329
+ }
330
+ };
331
+ /**
332
+ * Discover JSON/YAML config files in the packaged root and project root.
333
+ * Order: packaged public → project public → project local. */
334
+ const discoverConfigFiles = async (importMetaUrl) => {
335
+ const files = [];
336
+ // Packaged root via importMetaUrl (optional)
337
+ if (importMetaUrl) {
338
+ const fromUrl = fileURLToPath(importMetaUrl);
339
+ const packagedRoot = await packageDirectory({ cwd: fromUrl });
340
+ if (packagedRoot) {
341
+ for (const name of PUBLIC_FILENAMES) {
342
+ const p = join(packagedRoot, name);
343
+ if (await fs.pathExists(p)) {
344
+ files.push({ path: p, privacy: 'public', scope: 'packaged' });
345
+ break; // only one public file expected per scope
346
+ }
347
+ }
348
+ // By policy, packaged .local is not expected; skip even if present.
349
+ }
350
+ }
351
+ // Project root (from current working directory)
352
+ const projectRoot = await packageDirectory();
353
+ if (projectRoot) {
354
+ for (const name of PUBLIC_FILENAMES) {
355
+ const p = join(projectRoot, name);
356
+ if (await fs.pathExists(p)) {
357
+ files.push({ path: p, privacy: 'public', scope: 'project' });
358
+ break;
359
+ }
360
+ }
361
+ for (const name of LOCAL_FILENAMES) {
362
+ const p = join(projectRoot, name);
363
+ if (await fs.pathExists(p)) {
364
+ files.push({ path: p, privacy: 'local', scope: 'project' });
365
+ break;
366
+ }
367
+ }
368
+ }
369
+ return files;
370
+ };
371
+ /**
372
+ * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
373
+ * Validates with Zod RAW schema, then normalizes to RESOLVED.
374
+ *
375
+ * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
376
+ * For JS/TS: default export is loaded; "dynamic" is allowed.
377
+ */
378
+ const loadConfigFile = async (filePath) => {
379
+ let raw = {};
380
+ try {
381
+ const abs = path.resolve(filePath);
382
+ if (isJsOrTs(abs)) {
383
+ // JS/TS support: load default export via robust pipeline.
384
+ const mod = await loadJsTsDefault(abs);
385
+ raw = mod ?? {};
386
+ }
387
+ else {
388
+ const txt = await fs.readFile(abs, 'utf-8');
389
+ raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
390
+ }
391
+ }
392
+ catch (err) {
393
+ throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
394
+ }
395
+ // Validate RAW
396
+ const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
397
+ if (!parsed.success) {
398
+ const msgs = parsed.error.issues
399
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
400
+ .join('\n');
401
+ throw new Error(`Invalid config ${filePath}:\n${msgs}`);
402
+ }
403
+ // Disallow dynamic in JSON/YAML; allow in JS/TS
404
+ if (!isJsOrTs(filePath) && parsed.data.dynamic !== undefined) {
405
+ throw new Error(`Config ${filePath} specifies "dynamic"; JSON/YAML configs cannot include dynamic in this step. Use JS/TS config.`);
406
+ }
407
+ return getDotenvConfigSchemaResolved.parse(parsed.data);
408
+ };
409
+ /**
410
+ * Discover and load configs into resolved shapes, ordered by scope/privacy.
411
+ * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
412
+ */
413
+ const resolveGetDotenvConfigSources = async (importMetaUrl) => {
414
+ const discovered = await discoverConfigFiles(importMetaUrl);
415
+ const result = {};
416
+ for (const f of discovered) {
417
+ const cfg = await loadConfigFile(f.path);
418
+ if (f.scope === 'packaged') {
419
+ // packaged public only
420
+ result.packaged = cfg;
421
+ }
422
+ else {
423
+ result.project ??= {};
424
+ if (f.privacy === 'public')
425
+ result.project.public = cfg;
426
+ else
427
+ result.project.local = cfg;
428
+ }
429
+ }
430
+ return result;
431
+ };
12
432
 
13
433
  /**
14
434
  * Dotenv expansion utilities.
@@ -146,273 +566,558 @@ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduc
146
566
  */
147
567
  const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
148
568
 
149
- const baseGetDotenvCliOptions = {
150
- dotenvToken: '.env',
151
- loadProcess: true,
152
- logger: console,
153
- paths: './',
154
- pathsDelimiter: ' ',
155
- privateToken: 'local',
156
- scripts: {
157
- 'git-status': {
158
- cmd: 'git branch --show-current && git status -s -u',
159
- shell: true,
160
- },
161
- },
162
- shell: true,
163
- vars: '',
164
- varsAssignor: '=',
165
- varsDelimiter: ' ',
569
+ const applyKv = (current, kv) => {
570
+ if (!kv || Object.keys(kv).length === 0)
571
+ return current;
572
+ const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
573
+ return { ...current, ...expanded };
574
+ };
575
+ const applyConfigSlice = (current, cfg, env) => {
576
+ if (!cfg)
577
+ return current;
578
+ // kind axis: global then env (env overrides global)
579
+ const afterGlobal = applyKv(current, cfg.vars);
580
+ const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
581
+ return applyKv(afterGlobal, envKv);
166
582
  };
167
-
168
583
  /**
169
- * Resolve a command string from the {@link Scripts} table.
170
- * A script may be expressed as a string or an object with a `cmd` property.
584
+ * Overlay config-provided values onto a base ProcessEnv using precedence axes:
585
+ * - kind: env \> global
586
+ * - privacy: local \> public
587
+ * - source: project \> packaged \> base
171
588
  *
172
- * @param scripts - Optional scripts table.
173
- * @param command - User-provided command name or string.
174
- * @returns Resolved command string (falls back to the provided command).
589
+ * Programmatic explicit vars (if provided) override all config slices.
590
+ * Progressive expansion is applied within each slice.
175
591
  */
176
- const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
177
- ? scripts[command].cmd
178
- : (scripts?.[command] ?? command);
592
+ const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
593
+ let current = { ...base };
594
+ // Source: packaged (public -> local)
595
+ current = applyConfigSlice(current, configs.packaged, env);
596
+ // Packaged "local" is not expected by policy; if present, honor it.
597
+ // We do not have a separate object for packaged.local in sources, keep as-is.
598
+ // Source: project (public -> local)
599
+ current = applyConfigSlice(current, configs.project?.public, env);
600
+ current = applyConfigSlice(current, configs.project?.local, env);
601
+ // Programmatic explicit vars (top of static tier)
602
+ if (programmaticVars) {
603
+ const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
604
+ current = applyKv(current, toApply);
605
+ }
606
+ return current;
607
+ };
608
+
179
609
  /**
180
- * Resolve the shell setting for a given command:
181
- * - If the script entry is an object, prefer its `shell` override.
182
- * - Otherwise use the provided `shell` (string | boolean).
610
+ * Asynchronously read a dotenv file & parse it into an object.
183
611
  *
184
- * @param scripts - Optional scripts table.
185
- * @param command - User-provided command name or string.
186
- * @param shell - Global shell preference (string | boolean).
612
+ * @param path - Path to dotenv file.
613
+ * @returns The parsed dotenv object.
187
614
  */
188
- const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
189
- ? (scripts[command].shell ?? false)
190
- : (shell ?? false);
615
+ const readDotenv = async (path) => {
616
+ try {
617
+ return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
618
+ }
619
+ catch {
620
+ return {};
621
+ }
622
+ };
191
623
 
192
- const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
193
- let cwd = process.cwd();
194
- if (pkgCwd) {
195
- const pkgDir = await packageDirectory();
196
- if (!pkgDir) {
197
- logger.error('No package directory found.');
198
- process.exit(0);
199
- }
200
- cwd = pkgDir;
624
+ const importDefault = async (fileUrl) => {
625
+ const mod = (await import(fileUrl));
626
+ return mod.default;
627
+ };
628
+ const cacheHash = (absPath, mtimeMs) => createHash('sha1')
629
+ .update(absPath)
630
+ .update(String(mtimeMs))
631
+ .digest('hex')
632
+ .slice(0, 12);
633
+ /**
634
+ * Remove older compiled cache files for a given source base name, keeping
635
+ * at most `keep` most-recent files. Errors are ignored by design.
636
+ */
637
+ const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
638
+ try {
639
+ const entries = await fs.readdir(cacheDir);
640
+ const mine = entries
641
+ .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
642
+ .map((f) => path.join(cacheDir, f));
643
+ if (mine.length <= keep)
644
+ return;
645
+ const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
646
+ stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
647
+ const toDelete = stats.slice(keep).map((s) => s.p);
648
+ await Promise.all(toDelete.map(async (p) => {
649
+ try {
650
+ await fs.remove(p);
651
+ }
652
+ catch {
653
+ // best-effort cleanup
654
+ }
655
+ }));
201
656
  }
202
- const absRootPath = path.posix.join(cwd.split(path.sep).join(path.posix.sep), rootPath.split(path.sep).join(path.posix.sep));
203
- const paths = await globby(globs.split(/\s+/), {
204
- cwd: absRootPath,
205
- expandDirectories: false,
206
- onlyDirectories: true,
207
- absolute: true,
208
- });
209
- if (!paths.length) {
210
- logger.error(`No paths found for globs '${globs}' at '${absRootPath}'.`);
211
- process.exit(0);
657
+ catch {
658
+ // best-effort cleanup
212
659
  }
213
- return { absRootPath, paths };
214
660
  };
215
- const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, ignoreErrors, list, logger, pkgCwd, rootPath, shell, }) => {
216
- if (!command) {
217
- logger.error(`No command provided.`);
218
- process.exit(0);
661
+ /**
662
+ * Load a module default export from a JS/TS file with robust fallbacks:
663
+ * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
664
+ * 1) try direct import (if a TS loader is active),
665
+ * 2) esbuild bundle to a temp ESM file,
666
+ * 3) typescript.transpileModule fallback for simple modules.
667
+ *
668
+ * @param absPath - absolute path to source file
669
+ * @param cacheDirName - cache subfolder under .tsbuild
670
+ */
671
+ const loadModuleDefault = async (absPath, cacheDirName) => {
672
+ const ext = path.extname(absPath).toLowerCase();
673
+ const fileUrl = url.pathToFileURL(absPath).toString();
674
+ if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
675
+ return importDefault(fileUrl);
219
676
  }
220
- const { absRootPath, paths } = await globPaths({
221
- globs,
222
- logger,
223
- rootPath,
224
- // exactOptionalPropertyTypes: only include when defined
225
- ...(pkgCwd !== undefined ? { pkgCwd } : {}),
226
- });
227
- const headerTitle = list
228
- ? 'Listing working directories...'
229
- : 'Executing command batch...';
230
- logger.info('');
231
- const headerRootPath = `ROOT: ${absRootPath}`;
232
- const headerGlobs = `GLOBS: ${globs}`;
233
- const headerCommand = `CMD: ${command}`;
234
- logger.info('*'.repeat(Math.max(headerTitle.length, headerRootPath.length, headerGlobs.length, headerCommand.length)));
235
- logger.info(headerTitle);
236
- logger.info('');
237
- logger.info(headerRootPath);
238
- logger.info(headerGlobs);
239
- logger.info(headerCommand);
240
- for (const path of paths) {
241
- // Write path and command to console.
242
- const pathLabel = `CWD: ${path}`;
243
- if (list) {
244
- logger.info(pathLabel);
245
- continue;
677
+ // Try direct import first (TS loader active)
678
+ try {
679
+ const dyn = await importDefault(fileUrl);
680
+ if (dyn)
681
+ return dyn;
682
+ }
683
+ catch {
684
+ /* fall through */
685
+ }
686
+ const stat = await fs.stat(absPath);
687
+ const hash = cacheHash(absPath, stat.mtimeMs);
688
+ const cacheDir = path.resolve('.tsbuild', cacheDirName);
689
+ await fs.ensureDir(cacheDir);
690
+ const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
691
+ // Try esbuild
692
+ try {
693
+ const esbuild = (await import('esbuild'));
694
+ await esbuild.build({
695
+ entryPoints: [absPath],
696
+ bundle: true,
697
+ platform: 'node',
698
+ format: 'esm',
699
+ target: 'node20',
700
+ outfile: cacheFile,
701
+ sourcemap: false,
702
+ logLevel: 'silent',
703
+ });
704
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
705
+ // Best-effort: trim older cache files for this source.
706
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
707
+ return result;
708
+ }
709
+ catch {
710
+ /* fall through to TS transpile */
711
+ }
712
+ // TypeScript transpile fallback
713
+ try {
714
+ const ts = (await import('typescript'));
715
+ const code = await fs.readFile(absPath, 'utf-8');
716
+ const out = ts.transpileModule(code, {
717
+ compilerOptions: {
718
+ module: 'ESNext',
719
+ target: 'ES2022',
720
+ moduleResolution: 'NodeNext',
721
+ },
722
+ }).outputText;
723
+ await fs.writeFile(cacheFile, out, 'utf-8');
724
+ const result = await importDefault(url.pathToFileURL(cacheFile).toString());
725
+ // Best-effort: trim older cache files for this source.
726
+ await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
727
+ return result;
728
+ }
729
+ catch {
730
+ // Caller decides final error wording; rethrow for upstream mapping.
731
+ throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
732
+ }
733
+ };
734
+
735
+ /**
736
+ * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
737
+ *
738
+ * @param options - `GetDotenvOptions` object
739
+ * @returns The combined parsed dotenv object.
740
+ * * @example Load from the project root with default tokens
741
+ * ```ts
742
+ * const vars = await getDotenv();
743
+ * console.log(vars.MY_SETTING);
744
+ * ```
745
+ *
746
+ * @example Load from multiple paths and a specific environment
747
+ * ```ts
748
+ * const vars = await getDotenv({
749
+ * env: 'dev',
750
+ * dotenvToken: '.testenv',
751
+ * privateToken: 'secret',
752
+ * paths: ['./', './packages/app'],
753
+ * });
754
+ * ```
755
+ *
756
+ * @example Use dynamic variables
757
+ * ```ts
758
+ * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
759
+ * const vars = await getDotenv({ dynamicPath: '.env.js' });
760
+ * ```
761
+ *
762
+ * @remarks
763
+ * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
764
+ * into `process.env` as a side effect.
765
+ * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
766
+ * The path is resolved after expansion, so it may reference previously loaded vars.
767
+ *
768
+ * @throws Error when a dynamic module is present but cannot be imported.
769
+ * @throws Error when an output path was requested but could not be resolved.
770
+ */
771
+ const getDotenv = async (options = {}) => {
772
+ // Apply defaults.
773
+ 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);
774
+ // Read .env files.
775
+ const loaded = paths.length
776
+ ? await paths.reduce(async (e, p) => {
777
+ const publicGlobal = excludePublic || excludeGlobal
778
+ ? Promise.resolve({})
779
+ : readDotenv(path.resolve(p, dotenvToken));
780
+ const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
781
+ ? Promise.resolve({})
782
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
783
+ const privateGlobal = excludePrivate || excludeGlobal
784
+ ? Promise.resolve({})
785
+ : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
786
+ const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
787
+ ? Promise.resolve({})
788
+ : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
789
+ const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
790
+ e,
791
+ publicGlobal,
792
+ publicEnv,
793
+ privateGlobal,
794
+ privateEnv,
795
+ ]);
796
+ return {
797
+ ...eResolved,
798
+ ...publicGlobalResolved,
799
+ ...publicEnvResolved,
800
+ ...privateGlobalResolved,
801
+ ...privateEnvResolved,
802
+ };
803
+ }, Promise.resolve({}))
804
+ : {};
805
+ const outputKey = nanoid();
806
+ const dotenv = dotenvExpandAll({
807
+ ...loaded,
808
+ ...vars,
809
+ ...(outputPath ? { [outputKey]: outputPath } : {}),
810
+ }, { progressive: true });
811
+ // Process dynamic variables. Programmatic option takes precedence over path.
812
+ if (!excludeDynamic) {
813
+ let dynamic = undefined;
814
+ if (options.dynamic && Object.keys(options.dynamic).length > 0) {
815
+ dynamic = options.dynamic;
246
816
  }
247
- logger.info('');
248
- logger.info('*'.repeat(pathLabel.length));
249
- logger.info(pathLabel);
250
- logger.info(headerCommand);
251
- // Execute command.
252
- try {
253
- await execaCommand(command, {
254
- cwd: path,
255
- env: {
256
- ...process.env,
257
- getDotenvCliOptions: getDotenvCliOptions
258
- ? JSON.stringify(getDotenvCliOptions)
259
- : undefined,
260
- },
261
- stdio: 'inherit',
262
- shell, // already normalized to string | boolean | URL
263
- });
817
+ else if (dynamicPath) {
818
+ const absDynamicPath = path.resolve(dynamicPath);
819
+ if (await fs.exists(absDynamicPath)) {
820
+ try {
821
+ dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
822
+ }
823
+ catch {
824
+ // Preserve legacy error text for compatibility with tests/docs.
825
+ throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
826
+ `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
827
+ }
828
+ }
264
829
  }
265
- catch (error) {
266
- if (!ignoreErrors) {
267
- throw error;
830
+ if (dynamic) {
831
+ try {
832
+ for (const key in dynamic)
833
+ Object.assign(dotenv, {
834
+ [key]: typeof dynamic[key] === 'function'
835
+ ? dynamic[key](dotenv, env ?? defaultEnv)
836
+ : dynamic[key],
837
+ });
838
+ }
839
+ catch {
840
+ throw new Error(`Unable to evaluate dynamic variables.`);
268
841
  }
269
842
  }
270
843
  }
271
- logger.info('');
844
+ // Write output file.
845
+ let resultDotenv = dotenv;
846
+ if (outputPath) {
847
+ const outputPathResolved = dotenv[outputKey];
848
+ if (!outputPathResolved)
849
+ throw new Error('Output path not found.');
850
+ const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
851
+ await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
852
+ const value = dotenvForOutput[key] ?? '';
853
+ return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
854
+ }, ''), { encoding: 'utf-8' });
855
+ resultDotenv = dotenvForOutput;
856
+ }
857
+ // Log result.
858
+ if (log)
859
+ logger.log(resultDotenv);
860
+ // Load process.env.
861
+ if (loadProcess)
862
+ Object.assign(process.env, resultDotenv);
863
+ return resultDotenv;
272
864
  };
273
865
 
274
- const cmdCommand$1 = new Command()
275
- .name('cmd')
276
- .description('execute command, conflicts with --command option (default subcommand)')
277
- .enablePositionalOptions()
278
- .passThroughOptions()
279
- .action(async (_options, thisCommand) => {
280
- if (!thisCommand.parent)
281
- throw new Error(`unable to resolve parent command`);
282
- if (!thisCommand.parent.parent)
283
- throw new Error(`unable to resolve root command`);
284
- const { getDotenvCliOptions: { logger = console, ...getDotenvCliOptions }, } = thisCommand.parent.parent;
285
- const raw = thisCommand.parent.opts();
286
- const ignoreErrors = !!raw.ignoreErrors;
287
- const globs = typeof raw.globs === 'string' ? raw.globs : '*';
288
- const list = !!raw.list;
289
- const pkgCwd = !!raw.pkgCwd;
290
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : './';
291
- // Execute command.
292
- const command = thisCommand.args.join(' ');
293
- await execShellCommandBatch({
294
- command: resolveCommand(getDotenvCliOptions.scripts, command),
295
- getDotenvCliOptions,
296
- globs,
297
- ignoreErrors,
298
- list,
299
- logger,
300
- pkgCwd,
301
- rootPath,
302
- // execa expects string | boolean | URL for `shell`. We normalize earlier;
303
- // scripts[name].shell overrides take precedence and may be boolean or string.
304
- shell: resolveShell(getDotenvCliOptions.scripts, command, getDotenvCliOptions.shell),
866
+ /**
867
+ * Compute the dotenv context for the host (uses the config loader/overlay path).
868
+ * - Resolves and validates options strictly (host-only).
869
+ * - Applies file cascade, overlays, dynamics, and optional effects.
870
+ * - Merges and validates per-plugin config slices (when provided).
871
+ *
872
+ * @param customOptions - Partial options from the current invocation.
873
+ * @param plugins - Installed plugins (for config validation).
874
+ * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
875
+ const computeContext = async (customOptions, plugins, hostMetaUrl) => {
876
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
877
+ const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
878
+ // Always-on loader path
879
+ // 1) Base from files only (no dynamic, no programmatic vars)
880
+ const base = await getDotenv({
881
+ ...validated,
882
+ // Build a pure base without side effects or logging.
883
+ excludeDynamic: true,
884
+ vars: {},
885
+ log: false,
886
+ loadProcess: false,
887
+ outputPath: undefined,
305
888
  });
306
- });
307
-
308
- const batchCommand = new Command()
309
- .name('batch')
310
- .description('Batch command execution across multiple working directories.')
311
- .enablePositionalOptions()
312
- .passThroughOptions()
313
- .option('-p, --pkg-cwd', 'use nearest package directory as current working directory')
314
- .option('-r, --root-path <string>', 'path to batch root directory from current working directory', './')
315
- .option('-g, --globs <string>', 'space-delimited globs from root path', '*')
316
- .option('-c, --command <string>', 'command executed according to the base --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv)
317
- .option('-l, --list', 'list working directories without executing command')
318
- .option('-e, --ignore-errors', 'ignore errors and continue with next path')
319
- .hook('preSubcommand', async (thisCommand) => {
320
- if (!thisCommand.parent)
321
- throw new Error(`unable to resolve root command`);
322
- const { getDotenvCliOptions: { logger = console, ...getDotenvCliOptions }, } = thisCommand.parent;
323
- const raw = thisCommand.opts();
324
- const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
325
- const ignoreErrors = !!raw.ignoreErrors;
326
- const globs = typeof raw.globs === 'string' ? raw.globs : '*';
327
- const list = !!raw.list;
328
- const pkgCwd = !!raw.pkgCwd;
329
- const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : './';
330
- const argCount = thisCommand.args.length;
331
- if (typeof commandOpt === 'string' && argCount > 0) {
332
- logger.error(`--command option conflicts with cmd subcommand.`);
333
- process.exit(0);
889
+ // 2) Discover config sources and overlay
890
+ const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
891
+ const dotenvOverlaid = overlayEnv({
892
+ base,
893
+ env: validated.env ?? validated.defaultEnv,
894
+ configs: sources,
895
+ ...(validated.vars ? { programmaticVars: validated.vars } : {}),
896
+ });
897
+ // Helper to apply a dynamic map progressively.
898
+ const applyDynamic = (target, dynamic, env) => {
899
+ if (!dynamic)
900
+ return;
901
+ for (const key of Object.keys(dynamic)) {
902
+ const value = typeof dynamic[key] === 'function'
903
+ ? dynamic[key](target, env)
904
+ : dynamic[key];
905
+ Object.assign(target, { [key]: value });
906
+ }
907
+ };
908
+ // 3) Apply dynamics in order
909
+ const dotenv = { ...dotenvOverlaid };
910
+ applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
911
+ applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
912
+ applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
913
+ applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
914
+ // file dynamicPath (lowest)
915
+ if (validated.dynamicPath) {
916
+ const absDynamicPath = path.resolve(validated.dynamicPath);
917
+ try {
918
+ const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
919
+ applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
920
+ }
921
+ catch {
922
+ throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
923
+ }
924
+ }
925
+ // 4) Output/log/process merge
926
+ if (validated.outputPath) {
927
+ await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
928
+ const value = dotenv[key] ?? '';
929
+ return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
930
+ }, ''), { encoding: 'utf-8' });
931
+ }
932
+ const logger = validated.logger ?? console;
933
+ if (validated.log)
934
+ logger.log(dotenv);
935
+ if (validated.loadProcess)
936
+ Object.assign(process.env, dotenv);
937
+ // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
938
+ const packagedPlugins = (sources.packaged &&
939
+ sources.packaged.plugins) ??
940
+ {};
941
+ const publicPlugins = (sources.project?.public &&
942
+ sources.project.public.plugins) ??
943
+ {};
944
+ const localPlugins = (sources.project?.local &&
945
+ sources.project.local.plugins) ??
946
+ {};
947
+ const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
948
+ for (const p of plugins) {
949
+ if (!p.id || !p.configSchema)
950
+ continue;
951
+ const slice = mergedPluginConfigs[p.id];
952
+ if (slice === undefined)
953
+ continue;
954
+ const parsed = p.configSchema.safeParse(slice);
955
+ if (!parsed.success) {
956
+ const msgs = parsed.error.issues
957
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
958
+ .join('\n');
959
+ throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
960
+ }
961
+ mergedPluginConfigs[p.id] = parsed.data;
334
962
  }
335
- // Execute command.
336
- if (typeof commandOpt === 'string')
337
- await execShellCommandBatch({
338
- command: resolveCommand(getDotenvCliOptions.scripts, commandOpt),
339
- getDotenvCliOptions,
340
- globs,
341
- ignoreErrors,
342
- list,
343
- logger,
344
- pkgCwd,
345
- rootPath,
346
- // execa expects string | boolean | URL for `shell`. We normalize earlier;
347
- // scripts[name].shell overrides take precedence and may be boolean or string.
348
- shell: resolveShell(getDotenvCliOptions.scripts, commandOpt, getDotenvCliOptions.shell),
963
+ return {
964
+ optionsResolved: validated,
965
+ dotenv: dotenv,
966
+ plugins: {},
967
+ pluginConfigs: mergedPluginConfigs,
968
+ };
969
+ };
970
+
971
+ const HOST_META_URL = import.meta.url;
972
+ const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
973
+ /**
974
+ * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
975
+ *
976
+ * Responsibilities:
977
+ * - Resolve options strictly and compute dotenv context (resolveAndLoad).
978
+ * - Expose a stable accessor for the current context (getCtx).
979
+ * - Provide a namespacing helper (ns).
980
+ * - Support composable plugins with parent → children install and afterResolve.
981
+ *
982
+ * NOTE: This host is additive and does not alter the legacy CLI.
983
+ */
984
+ class GetDotenvCli extends Command {
985
+ /** Registered top-level plugins (composition happens via .use()) */
986
+ _plugins = [];
987
+ /** One-time installation guard */
988
+ _installed = false;
989
+ constructor(alias = 'getdotenv') {
990
+ super(alias);
991
+ // Ensure subcommands that use passThroughOptions can be attached safely.
992
+ // Commander requires parent commands to enable positional options when a
993
+ // child uses passThroughOptions.
994
+ this.enablePositionalOptions();
995
+ // Skeleton preSubcommand hook: produce a context if absent, without
996
+ // mutating process.env. The passOptions hook (when installed) will
997
+ // compute the final context using merged CLI options; keeping
998
+ // loadProcess=false here avoids leaking dotenv values into the parent
999
+ // process env before subcommands execute.
1000
+ this.hook('preSubcommand', async () => {
1001
+ if (this.getCtx())
1002
+ return;
1003
+ await this.resolveAndLoad({ loadProcess: false });
349
1004
  });
350
- })
351
- .addCommand(cmdCommand$1, { isDefault: true });
352
-
353
- const cmdCommand = new Command()
354
- .name('cmd')
355
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
356
- .configureHelp({ showGlobalOptions: true })
357
- .enablePositionalOptions()
358
- .passThroughOptions()
359
- .action(async (_options, thisCommand) => {
360
- const args = thisCommand.args;
361
- if (args.length === 0)
362
- return;
363
- if (!thisCommand.parent)
364
- throw new Error('parent command not found');
365
- const { getDotenvCliOptions: { logger = console, ...getDotenvCliOptions }, } = thisCommand.parent;
366
- const command = args.map(String).join(' ');
367
- const cmd = resolveCommand(getDotenvCliOptions.scripts, command);
368
- if (getDotenvCliOptions.debug)
369
- logger.log('\n*** command ***\n', `'${cmd}'`);
370
- await execaCommand(cmd, {
371
- env: {
372
- ...process.env,
373
- getDotenvCliOptions: JSON.stringify(getDotenvCliOptions),
374
- },
375
- // execa expects string | boolean | URL; we normalize in generator
376
- // and allow script-level overrides.
377
- shell: resolveShell(getDotenvCliOptions.scripts, command, getDotenvCliOptions.shell),
378
- stdio: 'inherit',
379
- });
380
- });
1005
+ }
1006
+ /**
1007
+ * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
1008
+ */
1009
+ async resolveAndLoad(customOptions = {}) {
1010
+ // Resolve defaults, then validate strictly under the new host.
1011
+ const optionsResolved = await resolveGetDotenvOptions(customOptions);
1012
+ getDotenvOptionsSchemaResolved.parse(optionsResolved);
1013
+ // Delegate the heavy lifting to the shared helper (guarded path supported).
1014
+ const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
1015
+ // Persist context on the instance for later access.
1016
+ this[CTX_SYMBOL] =
1017
+ ctx;
1018
+ // Ensure plugins are installed exactly once, then run afterResolve.
1019
+ await this.install();
1020
+ await this._runAfterResolve(ctx);
1021
+ return ctx;
1022
+ }
1023
+ /**
1024
+ * Retrieve the current invocation context (if any).
1025
+ */
1026
+ getCtx() {
1027
+ return this[CTX_SYMBOL];
1028
+ }
1029
+ /** * Convenience helper to create a namespaced subcommand.
1030
+ */
1031
+ ns(name) {
1032
+ return this.command(name);
1033
+ }
1034
+ /**
1035
+ * Register a plugin for installation (parent level).
1036
+ * Installation occurs on first resolveAndLoad() (or explicit install()).
1037
+ */
1038
+ use(plugin) {
1039
+ this._plugins.push(plugin);
1040
+ // Immediately run setup so subcommands exist before parsing.
1041
+ const setupOne = (p) => {
1042
+ p.setup(this);
1043
+ for (const child of p.children)
1044
+ setupOne(child);
1045
+ };
1046
+ setupOne(plugin);
1047
+ return this;
1048
+ }
1049
+ /**
1050
+ * Install all registered plugins in parent → children (pre-order).
1051
+ * Runs only once per CLI instance.
1052
+ */
1053
+ async install() {
1054
+ // Setup is performed immediately in use(); here we only guard for afterResolve.
1055
+ this._installed = true;
1056
+ // Satisfy require-await without altering behavior.
1057
+ await Promise.resolve();
1058
+ }
1059
+ /**
1060
+ * Run afterResolve hooks for all plugins (parent → children).
1061
+ */
1062
+ async _runAfterResolve(ctx) {
1063
+ const run = async (p) => {
1064
+ if (p.afterResolve)
1065
+ await p.afterResolve(this, ctx);
1066
+ for (const child of p.children)
1067
+ await run(child);
1068
+ };
1069
+ for (const p of this._plugins)
1070
+ await run(p);
1071
+ }
1072
+ }
381
1073
 
382
1074
  /**
383
- * Create the root Commander command with all options and subcommands.
384
- * Pure builder: no side-effects; the caller attaches lifecycle hooks.
1075
+ * Attach legacy root flags to a Commander program.
1076
+ * Uses provided defaults to render help labels without coupling to generators.
385
1077
  */
386
- const createRootCommand = (opts) => {
387
- 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;
388
- const excludeAll = !!excludeDynamic &&
389
- ((!!excludeEnv && !!excludeGlobal) ||
390
- (!!excludePrivate && !!excludePublic));
391
- const program = new Command()
392
- .name(alias)
393
- .description(description)
1078
+ const attachRootOptions = (program, defaults, opts) => {
1079
+ const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
1080
+ const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
1081
+ const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
1082
+ // Build initial chain.
1083
+ let p = program
394
1084
  .enablePositionalOptions()
395
1085
  .passThroughOptions()
396
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env)
397
- .option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
1086
+ .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
1087
+ p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
398
1088
  ['KEY1', 'VAL1'],
399
1089
  ['KEY2', 'VAL2'],
400
1090
  ]
401
- .map((v) => v.join(varsAssignor ?? '='))
402
- .join(varsDelimiter ?? ' ')}`, dotenvExpandFromProcessEnv)
403
- .option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv)
1091
+ .map((v) => v.join(va))
1092
+ .join(vd)}`, dotenvExpandFromProcessEnv);
1093
+ // Optional legacy root command flag (kept for generated CLI compatibility).
1094
+ // Default is OFF; the generator opts in explicitly.
1095
+ if (opts?.includeCommandOption === true) {
1096
+ p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
1097
+ }
1098
+ p = p
404
1099
  .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
405
1100
  .addOption(new Option('-s, --shell [string]', (() => {
406
- const defaultLabel = shell
407
- ? ` (default ${typeof shell === 'boolean' ? 'OS shell' : shell})`
408
- : '';
1101
+ let defaultLabel = '';
1102
+ if (shell !== undefined) {
1103
+ if (typeof shell === 'boolean') {
1104
+ defaultLabel = ' (default OS shell)';
1105
+ }
1106
+ else if (typeof shell === 'string') {
1107
+ // Safe string interpolation
1108
+ defaultLabel = ` (default ${shell})`;
1109
+ }
1110
+ }
409
1111
  return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
410
1112
  })()).conflicts('shellOff'))
411
1113
  .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
412
1114
  .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
413
1115
  .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
414
- .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeAll ? ' (default)' : ''}`).conflicts('excludeAllOff'))
415
- .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF${!excludeAll ? ' (default)' : ''}`).conflicts('excludeAll'))
1116
+ .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
1117
+ ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
1118
+ ? ' (default)'
1119
+ : ''}`).conflicts('excludeAllOff'))
1120
+ .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
416
1121
  .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
417
1122
  .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
418
1123
  .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
@@ -425,8 +1130,7 @@ const createRootCommand = (opts) => {
425
1130
  .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
426
1131
  .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
427
1132
  .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
428
- .addOption(new Option('-d, --debug', `debug mode ON${debug ? ' (default)' : ''}`).conflicts('debugOff'))
429
- .addOption(new Option('-D, --debug-off', `debug mode OFF${!debug ? ' (default)' : ''}`).conflicts('debug'))
1133
+ .option('--capture', 'capture child process stdio for commands (tests/CI)')
430
1134
  .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
431
1135
  .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
432
1136
  .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
@@ -438,579 +1142,1918 @@ const createRootCommand = (opts) => {
438
1142
  .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
439
1143
  .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
440
1144
  .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
1145
+ // Hidden scripts pipe-through (stringified)
441
1146
  .addOption(new Option('--scripts <string>')
442
1147
  .default(JSON.stringify(scripts))
443
- .hideHelp())
444
- .addCommand(batchCommand)
445
- .addCommand(cmdCommand, { isDefault: true });
446
- return program;
1148
+ .hideHelp());
1149
+ // Diagnostics: opt-in tracing; optional variadic keys after the flag.
1150
+ p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
1151
+ return p;
447
1152
  };
448
1153
 
449
- /** @internal */
450
- const isPlainObject = (value) => value !== null &&
451
- typeof value === 'object' &&
452
- Object.getPrototypeOf(value) === Object.prototype;
453
- const mergeInto = (target, source) => {
454
- for (const [key, sVal] of Object.entries(source)) {
455
- if (sVal === undefined)
456
- continue; // do not overwrite with undefined
457
- const tVal = target[key];
458
- if (isPlainObject(tVal) && isPlainObject(sVal)) {
459
- target[key] = mergeInto({ ...tVal }, sVal);
460
- }
461
- else if (isPlainObject(sVal)) {
462
- target[key] = mergeInto({}, sVal);
463
- }
464
- else {
465
- target[key] = sVal;
466
- }
467
- }
468
- return target;
469
- };
470
1154
  /**
471
- * Perform a deep defaults-style merge across plain objects. *
472
- * - Only merges plain objects (prototype === Object.prototype).
473
- * - Arrays and non-objects are replaced, not merged.
474
- * - `undefined` values are ignored and do not overwrite prior values.
1155
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1156
+ * - If the user explicitly enabled the flag, return true.
1157
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1158
+ * - Otherwise, adopt the default (true set; false/undefined unset).
475
1159
  *
476
- * @typeParam T - The resulting shape after merging all layers.
477
- * @param layers - Zero or more partial layers in ascending precedence order.
478
- * @returns The merged object typed as {@link T}.
1160
+ * @param exclude - The "on" flag value as parsed by Commander.
1161
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1162
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1163
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
479
1164
  *
480
1165
  * @example
481
- * defaultsDeep(\{ a: 1, nested: \{ b: 2 \} \}, \{ nested: \{ b: 3, c: 4 \} \})
482
- * =\> \{ a: 1, nested: \{ b: 3, c: 4 \} \}
1166
+ * ```ts
1167
+ * resolveExclusion(undefined, undefined, true); // => true
1168
+ * ```
483
1169
  */
484
- const defaultsDeep = (...layers) => {
485
- const result = layers
486
- .filter(Boolean)
487
- .reduce((acc, layer) => mergeInto(acc, layer), {});
488
- return result;
489
- };
490
-
491
- // src/GetDotenvOptions.ts
492
- const getDotenvOptionsFilename = 'getdotenv.config.json';
1170
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
493
1171
  /**
494
- * Converts programmatic CLI options to `getDotenv` options.
1172
+ * Resolve an optional flag with "--exclude-all" overrides.
1173
+ * If excludeAll is set and the individual "...-off" is not, force true.
1174
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1175
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
495
1176
  *
496
- * @param cliOptions - CLI options. Defaults to `{}`.
1177
+ * @param exclude - Individual include/exclude flag.
1178
+ * @param excludeOff - Individual "...-off" flag.
1179
+ * @param defaultValue - Default for the individual flag.
1180
+ * @param excludeAll - Global "exclude-all" flag.
1181
+ * @param excludeAllOff - Global "exclude-all-off" flag.
497
1182
  *
498
- * @returns `getDotenv` options.
1183
+ * @example
1184
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
499
1185
  */
500
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
501
- /**
502
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
503
- *
504
- * - Splits {@link GetDotenvCliOptions.paths} using either a delimiter
505
- * or a regular expression pattern into a string array.
506
- * - Parses {@link GetDotenvCliOptions.vars} as space-separated `KEY=VALUE`
507
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
508
- * - Drops CLI-only keys that have no programmatic equivalent.
509
- *
510
- * @remarks
511
- * Follows exact-optional semantics by not emitting undefined-valued entries.
512
- */
513
- // Drop CLI-only keys
514
- const { debug, scripts, ...restFlags } = rest;
515
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
516
- const kvPairs = (vars
517
- ? splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
518
- ? RegExp(varsAssignorPattern)
519
- : (varsAssignor ?? '=')))
520
- : []);
521
- const parsedVars = Object.fromEntries(kvPairs);
522
- return {
523
- ...restFlags,
524
- paths: splitBy(paths, pathsDelimiter, pathsDelimiterPattern),
525
- vars: parsedVars,
526
- };
1186
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1187
+ // Order of precedence:
1188
+ // 1) Individual explicit "on" wins outright.
1189
+ // 2) Individual explicit "off" wins over any global.
1190
+ // 3) Global exclude-all forces true when not explicitly turned off.
1191
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1192
+ // 5) Fall back to the default (true => set; false/undefined => unset).
1193
+ (() => {
1194
+ // Individual "on"
1195
+ if (exclude === true)
1196
+ return true;
1197
+ // Individual "off"
1198
+ if (excludeOff === true)
1199
+ return undefined;
1200
+ // Global "exclude-all" ON (unless explicitly turned off)
1201
+ if (excludeAll === true)
1202
+ return true;
1203
+ // Global "exclude-all-off" (unless explicitly enabled)
1204
+ if (excludeAllOff === true)
1205
+ return undefined;
1206
+ // Default
1207
+ return defaultValue ? true : undefined;
1208
+ })();
1209
+ /**
1210
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1211
+ * delete when undefined; assign when defined — without requiring an index signature on T.
1212
+ *
1213
+ * @typeParam T - Target object type.
1214
+ * @param obj - The object to write to.
1215
+ * @param key - The optional boolean property key of {@link T}.
1216
+ * @param value - The value to set or `undefined` to unset.
1217
+ *
1218
+ * @remarks
1219
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1220
+ */
1221
+ const setOptionalFlag = (obj, key, value) => {
1222
+ const target = obj;
1223
+ const k = key;
1224
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1225
+ if (value === undefined)
1226
+ delete target[k];
1227
+ else
1228
+ target[k] = value;
527
1229
  };
528
- const resolveGetDotenvOptions = async (customOptions) => {
529
- /**
530
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
531
- *
532
- * 1. Base defaults derived from the CLI generator defaults
533
- * ({@link baseGetDotenvCliOptions}).
534
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
535
- * package root (if present).
536
- * 3. The provided {@link customOptions}.
537
- *
538
- * The result preserves explicit empty values and drops only `undefined`.
539
- *
540
- * @returns Fully-resolved {@link GetDotenvOptions}.
541
- *
542
- * @example
543
- * ```ts
544
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
545
- * ```
546
- */
547
- const localPkgDir = await packageDirectory();
548
- const localOptionsPath = localPkgDir
549
- ? join(localPkgDir, getDotenvOptionsFilename)
1230
+
1231
+ /**
1232
+ * Merge and normalize raw Commander options (current + parent + defaults)
1233
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1234
+ * avoid cross-layer coupling; callers may cast as needed.
1235
+ */
1236
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1237
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
1238
+ ? JSON.parse(parentJson)
550
1239
  : undefined;
551
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
552
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
553
- : {});
554
- // Merge order: base < local < custom (custom has highest precedence)
555
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
556
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
557
- const result = defaultsDeep(defaultsFromCli, customOptions);
1240
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, scripts, shellOff, ...rest } = rawCliOptions;
1241
+ const current = { ...rest };
1242
+ if (typeof scripts === 'string') {
1243
+ try {
1244
+ current.scripts = JSON.parse(scripts);
1245
+ }
1246
+ catch {
1247
+ // ignore parse errors; leave scripts undefined
1248
+ }
1249
+ }
1250
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1251
+ const d = defaults;
1252
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1253
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1254
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1255
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1256
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1257
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1258
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1259
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1260
+ // Normalize shell for predictability: explicit default shell per OS.
1261
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1262
+ let resolvedShell = merged.shell;
1263
+ if (shellOff)
1264
+ resolvedShell = false;
1265
+ else if (resolvedShell === true || resolvedShell === undefined) {
1266
+ resolvedShell = defaultShell;
1267
+ }
1268
+ else if (typeof resolvedShell !== 'string' &&
1269
+ typeof defaults.shell === 'string') {
1270
+ resolvedShell = defaults.shell;
1271
+ }
1272
+ merged.shell = resolvedShell;
1273
+ const cmd = typeof command === 'string' ? command : undefined;
1274
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
1275
+ };
1276
+
1277
+ GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
1278
+ const d = (defaults ?? baseRootOptionDefaults);
1279
+ attachRootOptions(this, d, opts);
1280
+ return this;
1281
+ };
1282
+ GetDotenvCli.prototype.passOptions = function (defaults) {
1283
+ const d = (defaults ?? baseRootOptionDefaults);
1284
+ this.hook('preSubcommand', async (thisCommand) => {
1285
+ const raw = thisCommand.opts();
1286
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1287
+ // Persist merged options for nested invocations (batch exec).
1288
+ thisCommand.getDotenvCliOptions =
1289
+ merged;
1290
+ // Build service options and compute context (always-on config loader path).
1291
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1292
+ await this.resolveAndLoad(serviceOptions);
1293
+ });
1294
+ // Also handle root-level flows (no subcommand) so option-aliases can run
1295
+ // with the same merged options and context without duplicating logic.
1296
+ this.hook('preAction', async (thisCommand) => {
1297
+ const raw = thisCommand.opts();
1298
+ const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
1299
+ thisCommand.getDotenvCliOptions =
1300
+ merged;
1301
+ // Avoid duplicate heavy work if a context is already present.
1302
+ if (!this.getCtx()) {
1303
+ const serviceOptions = getDotenvCliOptions2Options(merged);
1304
+ await this.resolveAndLoad(serviceOptions);
1305
+ }
1306
+ });
1307
+ return this;
1308
+ };
1309
+
1310
+ // Minimal tokenizer for shell-off execution:
1311
+ // Splits by whitespace while preserving quoted segments (single or double quotes).
1312
+ const tokenize = (command) => {
1313
+ const out = [];
1314
+ let cur = '';
1315
+ let quote = null;
1316
+ for (let i = 0; i < command.length; i++) {
1317
+ const c = command.charAt(i);
1318
+ if (quote) {
1319
+ if (c === quote) {
1320
+ // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
1321
+ // "" -> " and '' -> '
1322
+ const next = command.charAt(i + 1);
1323
+ if (next === quote) {
1324
+ cur += quote;
1325
+ i += 1; // skip the second quote
1326
+ }
1327
+ else {
1328
+ // end of quoted segment
1329
+ quote = null;
1330
+ }
1331
+ }
1332
+ else {
1333
+ cur += c;
1334
+ }
1335
+ }
1336
+ else {
1337
+ if (c === '"' || c === "'") {
1338
+ quote = c;
1339
+ }
1340
+ else if (/\s/.test(c)) {
1341
+ if (cur) {
1342
+ out.push(cur);
1343
+ cur = '';
1344
+ }
1345
+ }
1346
+ else {
1347
+ cur += c;
1348
+ }
1349
+ }
1350
+ }
1351
+ if (cur)
1352
+ out.push(cur);
1353
+ return out;
1354
+ };
1355
+
1356
+ const dbg$1 = (...args) => {
1357
+ if (process.env.GETDOTENV_DEBUG) {
1358
+ // Use stderr to avoid interfering with stdout assertions
1359
+ console.error('[getdotenv:run]', ...args);
1360
+ }
1361
+ };
1362
+ // Strip repeated symmetric outer quotes (single or double) until stable.
1363
+ // This is safe for argv arrays passed to execa (no quoting needed) and avoids
1364
+ // passing quote characters through to Node (e.g., for `node -e "<code>"`).
1365
+ // Handles stacked quotes from shells like PowerShell: """code""" -> code.
1366
+ const stripOuterQuotes = (s) => {
1367
+ let out = s;
1368
+ // Repeatedly trim only when the entire string is wrapped in matching quotes.
1369
+ // Stop as soon as the ends are asymmetric or no quotes remain.
1370
+ while (out.length >= 2) {
1371
+ const a = out.charAt(0);
1372
+ const b = out.charAt(out.length - 1);
1373
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
1374
+ if (!symmetric)
1375
+ break;
1376
+ out = out.slice(1, -1);
1377
+ }
1378
+ return out;
1379
+ };
1380
+ // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
1381
+ const pickResult = (r) => {
1382
+ const exit = r.exitCode;
1383
+ const stdoutVal = r.stdout;
1384
+ const stderrVal = r.stderr;
558
1385
  return {
559
- ...result, // Keep explicit empty strings/zeros; drop only undefined
560
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
1386
+ exitCode: typeof exit === 'number' ? exit : Number.NaN,
1387
+ stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
1388
+ stderr: typeof stderrVal === 'string' ? stderrVal : '',
561
1389
  };
562
1390
  };
1391
+ // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
1392
+ // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
1393
+ const sanitizeEnv = (env) => {
1394
+ if (!env)
1395
+ return undefined;
1396
+ const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
1397
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
1398
+ };
1399
+ /**
1400
+ * Execute a command and capture stdout/stderr (buffered).
1401
+ * - Preserves plain vs shell behavior and argv/string normalization.
1402
+ * - Never re-emits stdout/stderr to parent; returns captured buffers.
1403
+ * - Supports optional timeout (ms).
1404
+ */
1405
+ const runCommandResult = async (command, shell, opts = {}) => {
1406
+ const envSan = sanitizeEnv(opts.env);
1407
+ {
1408
+ let file;
1409
+ let args = [];
1410
+ if (Array.isArray(command)) {
1411
+ file = command[0];
1412
+ args = command.slice(1).map(stripOuterQuotes);
1413
+ }
1414
+ else {
1415
+ const tokens = tokenize(command);
1416
+ file = tokens[0];
1417
+ args = tokens.slice(1);
1418
+ }
1419
+ if (!file)
1420
+ return { exitCode: 0, stdout: '', stderr: '' };
1421
+ dbg$1('exec:capture (plain)', { file, args });
1422
+ try {
1423
+ const result = await execa(file, args, {
1424
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
1425
+ ...(envSan !== undefined ? { env: envSan } : {}),
1426
+ stdio: 'pipe',
1427
+ ...(opts.timeoutMs !== undefined
1428
+ ? { timeout: opts.timeoutMs, killSignal: 'SIGKILL' }
1429
+ : {}),
1430
+ });
1431
+ const ok = pickResult(result);
1432
+ dbg$1('exit:capture (plain)', { exitCode: ok.exitCode });
1433
+ return ok;
1434
+ }
1435
+ catch (err) {
1436
+ const out = pickResult(err);
1437
+ dbg$1('exit:capture:error (plain)', { exitCode: out.exitCode });
1438
+ return out;
1439
+ }
1440
+ }
1441
+ };
1442
+ const runCommand = async (command, shell, opts) => {
1443
+ if (shell === false) {
1444
+ let file;
1445
+ let args = [];
1446
+ if (Array.isArray(command)) {
1447
+ file = command[0];
1448
+ args = command.slice(1).map(stripOuterQuotes);
1449
+ }
1450
+ else {
1451
+ const tokens = tokenize(command);
1452
+ file = tokens[0];
1453
+ args = tokens.slice(1);
1454
+ }
1455
+ if (!file)
1456
+ return 0;
1457
+ dbg$1('exec (plain)', { file, args, stdio: opts.stdio });
1458
+ // Build options without injecting undefined properties (exactOptionalPropertyTypes).
1459
+ const envSan = sanitizeEnv(opts.env);
1460
+ const plainOpts = {};
1461
+ if (opts.cwd !== undefined)
1462
+ plainOpts.cwd = opts.cwd;
1463
+ if (envSan !== undefined)
1464
+ plainOpts.env = envSan;
1465
+ if (opts.stdio !== undefined)
1466
+ plainOpts.stdio = opts.stdio;
1467
+ const result = await execa(file, args, plainOpts);
1468
+ if (opts.stdio === 'pipe' && result.stdout) {
1469
+ process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
1470
+ }
1471
+ const exit = result?.exitCode;
1472
+ dbg$1('exit (plain)', { exitCode: exit });
1473
+ return typeof exit === 'number' ? exit : Number.NaN;
1474
+ }
1475
+ else {
1476
+ const commandStr = Array.isArray(command) ? command.join(' ') : command;
1477
+ dbg$1('exec (shell)', {
1478
+ shell: typeof shell === 'string' ? shell : 'custom',
1479
+ stdio: opts.stdio,
1480
+ command: commandStr,
1481
+ });
1482
+ const envSan = sanitizeEnv(opts.env);
1483
+ const shellOpts = { shell };
1484
+ if (opts.cwd !== undefined)
1485
+ shellOpts.cwd = opts.cwd;
1486
+ if (envSan !== undefined)
1487
+ shellOpts.env = envSan;
1488
+ if (opts.stdio !== undefined)
1489
+ shellOpts.stdio = opts.stdio;
1490
+ const result = await execaCommand(commandStr, shellOpts);
1491
+ const out = result?.stdout;
1492
+ if (opts.stdio === 'pipe' && out) {
1493
+ process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
1494
+ }
1495
+ const exit = result?.exitCode;
1496
+ dbg$1('exit (shell)', { exitCode: exit });
1497
+ return typeof exit === 'number' ? exit : Number.NaN;
1498
+ }
1499
+ };
563
1500
 
564
1501
  /**
565
- * Resolve `GetDotenvCliGenerateOptions` from `import.meta.url` and custom options.
1502
+ * Define a GetDotenv CLI plugin with compositional helpers.
1503
+ *
1504
+ * @example
1505
+ * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
1506
+ * .use(childA)
1507
+ * .use(childB);
566
1508
  */
567
- const resolveGetDotenvCliGenerateOptions = async ({ importMetaUrl, ...customOptions }) => {
568
- const baseOptions = {
569
- ...baseGetDotenvCliOptions,
570
- alias: 'getdotenv',
571
- description: 'Base CLI.',
1509
+ const definePlugin = (spec) => {
1510
+ const { children = [], ...rest } = spec;
1511
+ const plugin = {
1512
+ ...rest,
1513
+ children: [...children],
1514
+ use(child) {
1515
+ this.children.push(child);
1516
+ return this;
1517
+ },
572
1518
  };
573
- const globalPkgDir = importMetaUrl
574
- ? await packageDirectory({
575
- cwd: fileURLToPath(importMetaUrl),
576
- })
577
- : undefined;
578
- const globalOptionsPath = globalPkgDir
579
- ? join(globalPkgDir, getDotenvOptionsFilename)
580
- : undefined;
581
- const globalOptions = (globalOptionsPath && (await fs.exists(globalOptionsPath))
582
- ? JSON.parse((await fs.readFile(globalOptionsPath)).toString())
583
- : {});
584
- const localPkgDir = await packageDirectory();
585
- const localOptionsPath = localPkgDir
586
- ? join(localPkgDir, getDotenvOptionsFilename)
587
- : undefined;
588
- const localOptions = (localOptionsPath &&
589
- localOptionsPath !== globalOptionsPath &&
590
- (await fs.exists(localOptionsPath))
591
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
592
- : {});
593
- // Merge order: base < global < local < custom
594
- const merged = defaultsDeep(baseOptions, globalOptions, localOptions, customOptions);
595
- return merged;
1519
+ return plugin;
596
1520
  };
597
1521
 
598
1522
  /**
599
- * Asynchronously read a dotenv file & parse it into an object.
1523
+ * Batch services (neutral): resolve command and shell settings.
1524
+ * Shared by the generator path and the batch plugin to avoid circular deps.
1525
+ */
1526
+ /**
1527
+ * Resolve a command string from the {@link Scripts} table.
1528
+ * A script may be expressed as a string or an object with a `cmd` property.
600
1529
  *
601
- * @param path - Path to dotenv file.
602
- * @returns The parsed dotenv object.
1530
+ * @param scripts - Optional scripts table.
1531
+ * @param command - User-provided command name or string.
1532
+ * @returns Resolved command string (falls back to the provided command).
603
1533
  */
604
- const readDotenv = async (path) => {
1534
+ const resolveCommand = (scripts, command) => scripts && typeof scripts[command] === 'object'
1535
+ ? scripts[command].cmd
1536
+ : (scripts?.[command] ?? command);
1537
+ /**
1538
+ * Resolve the shell setting for a given command:
1539
+ * - If the script entry is an object, prefer its `shell` override.
1540
+ * - Otherwise use the provided `shell` (string | boolean).
1541
+ *
1542
+ * @param scripts - Optional scripts table.
1543
+ * @param command - User-provided command name or string.
1544
+ * @param shell - Global shell preference (string | boolean).
1545
+ */
1546
+ const resolveShell = (scripts, command, shell) => scripts && typeof scripts[command] === 'object'
1547
+ ? (scripts[command].shell ?? false)
1548
+ : (shell ?? false);
1549
+
1550
+ const DEFAULT_TIMEOUT_MS = 15_000;
1551
+ const trim = (s) => (typeof s === 'string' ? s.trim() : '');
1552
+ const unquote = (s) => s.length >= 2 &&
1553
+ ((s.startsWith('"') && s.endsWith('"')) ||
1554
+ (s.startsWith("'") && s.endsWith("'")))
1555
+ ? s.slice(1, -1)
1556
+ : s;
1557
+ const parseExportCredentialsJson = (txt) => {
605
1558
  try {
606
- return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
1559
+ const obj = JSON.parse(txt);
1560
+ const src = obj.Credentials ?? obj;
1561
+ const ak = src.AccessKeyId;
1562
+ const sk = src.SecretAccessKey;
1563
+ const tk = src.SessionToken;
1564
+ if (ak && sk)
1565
+ return {
1566
+ accessKeyId: ak,
1567
+ secretAccessKey: sk,
1568
+ ...(tk ? { sessionToken: tk } : {}),
1569
+ };
607
1570
  }
608
1571
  catch {
609
- return {};
1572
+ /* ignore */
610
1573
  }
1574
+ return undefined;
611
1575
  };
612
-
613
- const importDefault = async (fileUrl) => {
614
- const mod = (await import(fileUrl));
615
- return mod.default;
1576
+ const parseExportCredentialsEnv = (txt) => {
1577
+ const lines = txt.split(/\r?\n/);
1578
+ let id;
1579
+ let secret;
1580
+ let token;
1581
+ for (const raw of lines) {
1582
+ const line = raw.trim();
1583
+ if (!line)
1584
+ continue;
1585
+ // POSIX: export AWS_ACCESS_KEY_ID=..., export AWS_SECRET_ACCESS_KEY=..., export AWS_SESSION_TOKEN=...
1586
+ let m = /^export\s+([A-Z0-9_]+)\s*=\s*(.+)$/.exec(line);
1587
+ if (!m) {
1588
+ // PowerShell: $Env:AWS_ACCESS_KEY_ID="...", etc.
1589
+ m = /^\$Env:([A-Z0-9_]+)\s*=\s*(.+)$/.exec(line);
1590
+ }
1591
+ if (!m)
1592
+ continue;
1593
+ const k = m[1];
1594
+ const valRaw = m[2];
1595
+ if (typeof valRaw !== 'string')
1596
+ continue;
1597
+ let v = unquote(valRaw.trim());
1598
+ // Drop trailing semicolons if present (some shells)
1599
+ v = v.replace(/;$/, '');
1600
+ if (k === 'AWS_ACCESS_KEY_ID')
1601
+ id = v;
1602
+ else if (k === 'AWS_SECRET_ACCESS_KEY')
1603
+ secret = v;
1604
+ else if (k === 'AWS_SESSION_TOKEN')
1605
+ token = v;
1606
+ }
1607
+ if (id && secret)
1608
+ return {
1609
+ accessKeyId: id,
1610
+ secretAccessKey: secret,
1611
+ ...(token ? { sessionToken: token } : {}),
1612
+ };
1613
+ return undefined;
616
1614
  };
617
- /**
618
- * @internal Compute a short hash from path + mtime for cache filenames.
619
- */
620
- const cacheHash = (absPath, mtimeMs) => createHash('sha1')
621
- .update(absPath)
622
- .update(String(mtimeMs))
623
- .digest('hex')
624
- .slice(0, 12);
625
- /**
626
- * @internal Load a dynamic module from path. Supports .js/.mjs/.ts/.tsx:
627
- * - .js/.mjs: direct import
628
- * - .ts/.tsx: try direct import (in case a TS loader is active), otherwise:
629
- * - esbuild (if present): bundle to a temp ESM file and import it
630
- * - fallback: typescript.transpileModule (single-file), then import temp file
631
- */
632
- const loadDynamicFromPath = async (absPath) => {
633
- if (!(await fs.exists(absPath)))
1615
+ const getAwsConfigure = async (key, profile, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1616
+ const r = await runCommandResult(['aws', 'configure', 'get', key, '--profile', profile], false, {
1617
+ env: process.env,
1618
+ timeoutMs,
1619
+ });
1620
+ // Guard for mocked undefined in tests; keep narrow lint scope.
1621
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1622
+ if (!r || typeof r.exitCode !== 'number')
634
1623
  return undefined;
635
- const ext = path.extname(absPath).toLowerCase();
636
- const fileUrl = url.pathToFileURL(absPath).toString();
637
- if (ext !== '.ts' && ext !== '.tsx') {
638
- return importDefault(fileUrl);
1624
+ if (r.exitCode === 0) {
1625
+ const v = trim(r.stdout);
1626
+ return v.length > 0 ? v : undefined;
639
1627
  }
640
- // Try direct import (in case user started Node with a TS loader).
641
- try {
642
- const dyn = await importDefault(fileUrl);
643
- if (dyn)
644
- return dyn;
1628
+ return undefined;
1629
+ };
1630
+ const exportCredentials = async (profile, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1631
+ // Try JSON format first (AWS CLI v2)
1632
+ const rJson = await runCommandResult([
1633
+ 'aws',
1634
+ 'configure',
1635
+ 'export-credentials',
1636
+ '--profile',
1637
+ profile,
1638
+ '--format',
1639
+ 'json',
1640
+ ], false, { env: process.env, timeoutMs });
1641
+ if (rJson.exitCode === 0) {
1642
+ const creds = parseExportCredentialsJson(rJson.stdout);
1643
+ if (creds)
1644
+ return creds;
645
1645
  }
646
- catch {
647
- // ignore; fall through to compile
1646
+ // Fallback: env lines
1647
+ const rEnv = await runCommandResult(['aws', 'configure', 'export-credentials', '--profile', profile], false, { env: process.env, timeoutMs });
1648
+ if (rEnv.exitCode === 0) {
1649
+ const creds = parseExportCredentialsEnv(rEnv.stdout);
1650
+ if (creds)
1651
+ return creds;
648
1652
  }
649
- const stat = await fs.stat(absPath);
650
- const hash = cacheHash(absPath, stat.mtimeMs);
651
- const cacheDir = path.resolve('.tsbuild', 'getdotenv-dynamic');
652
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
653
- // Try esbuild first
654
- try {
655
- const esbuild = (await import('esbuild'));
656
- await fs.ensureDir(cacheDir);
657
- await esbuild.build({
658
- entryPoints: [absPath],
659
- bundle: true,
660
- platform: 'node',
661
- format: 'esm',
662
- target: 'node22',
663
- outfile: cacheFile,
664
- sourcemap: false,
665
- logLevel: 'silent',
1653
+ return undefined;
1654
+ };
1655
+ const resolveAwsContext = async ({ dotenv, cfg, }) => {
1656
+ const profileKey = cfg.profileKey ?? 'AWS_LOCAL_PROFILE';
1657
+ const profileFallbackKey = cfg.profileFallbackKey ?? 'AWS_PROFILE';
1658
+ const regionKey = cfg.regionKey ?? 'AWS_REGION';
1659
+ const profile = cfg.profile ??
1660
+ dotenv[profileKey] ??
1661
+ dotenv[profileFallbackKey] ??
1662
+ undefined;
1663
+ let region = cfg.region ?? dotenv[regionKey] ?? undefined;
1664
+ // Short-circuit when strategy is disabled.
1665
+ if (cfg.strategy === 'none') {
1666
+ // If region is still missing and we have a profile, try best-effort region resolve.
1667
+ if (!region && profile)
1668
+ region = await getAwsConfigure('region', profile);
1669
+ if (!region && cfg.defaultRegion)
1670
+ region = cfg.defaultRegion;
1671
+ const out = {};
1672
+ if (profile !== undefined)
1673
+ out.profile = profile;
1674
+ if (region !== undefined)
1675
+ out.region = region;
1676
+ return out;
1677
+ }
1678
+ // Env-first credentials.
1679
+ let credentials;
1680
+ const envId = trim(process.env.AWS_ACCESS_KEY_ID);
1681
+ const envSecret = trim(process.env.AWS_SECRET_ACCESS_KEY);
1682
+ const envToken = trim(process.env.AWS_SESSION_TOKEN);
1683
+ if (envId && envSecret) {
1684
+ credentials = {
1685
+ accessKeyId: envId,
1686
+ secretAccessKey: envSecret,
1687
+ ...(envToken ? { sessionToken: envToken } : {}),
1688
+ };
1689
+ }
1690
+ else if (profile) {
1691
+ // Try export-credentials
1692
+ credentials = await exportCredentials(profile);
1693
+ // On failure, detect SSO and optionally login then retry
1694
+ if (!credentials) {
1695
+ const ssoSession = await getAwsConfigure('sso_session', profile);
1696
+ const looksSSO = typeof ssoSession === 'string' && ssoSession.length > 0;
1697
+ if (looksSSO && cfg.loginOnDemand) {
1698
+ // Best-effort login, then retry export once.
1699
+ await runCommandResult(['aws', 'sso', 'login', '--profile', profile], false, {
1700
+ env: process.env,
1701
+ timeoutMs: DEFAULT_TIMEOUT_MS,
1702
+ });
1703
+ credentials = await exportCredentials(profile);
1704
+ }
1705
+ }
1706
+ // Static fallback if still missing.
1707
+ if (!credentials) {
1708
+ const id = await getAwsConfigure('aws_access_key_id', profile);
1709
+ const secret = await getAwsConfigure('aws_secret_access_key', profile);
1710
+ const token = await getAwsConfigure('aws_session_token', profile);
1711
+ if (id && secret) {
1712
+ credentials = {
1713
+ accessKeyId: id,
1714
+ secretAccessKey: secret,
1715
+ ...(token ? { sessionToken: token } : {}),
1716
+ };
1717
+ }
1718
+ }
1719
+ }
1720
+ // Final region resolution
1721
+ if (!region && profile)
1722
+ region = await getAwsConfigure('region', profile);
1723
+ if (!region && cfg.defaultRegion)
1724
+ region = cfg.defaultRegion;
1725
+ const out = {};
1726
+ if (profile !== undefined)
1727
+ out.profile = profile;
1728
+ if (region !== undefined)
1729
+ out.region = region;
1730
+ if (credentials)
1731
+ out.credentials = credentials;
1732
+ return out;
1733
+ };
1734
+
1735
+ const AwsPluginConfigSchema = z.object({
1736
+ profile: z.string().optional(),
1737
+ region: z.string().optional(),
1738
+ defaultRegion: z.string().optional(),
1739
+ profileKey: z.string().default('AWS_LOCAL_PROFILE').optional(),
1740
+ profileFallbackKey: z.string().default('AWS_PROFILE').optional(),
1741
+ regionKey: z.string().default('AWS_REGION').optional(),
1742
+ strategy: z.enum(['cli-export', 'none']).default('cli-export').optional(),
1743
+ loginOnDemand: z.boolean().default(false).optional(),
1744
+ setEnv: z.boolean().default(true).optional(),
1745
+ addCtx: z.boolean().default(true).optional(),
1746
+ });
1747
+
1748
+ const awsPlugin = () => definePlugin({
1749
+ id: 'aws',
1750
+ // Host validates this slice when the loader path is active.
1751
+ configSchema: AwsPluginConfigSchema,
1752
+ setup(cli) {
1753
+ // Subcommand: aws
1754
+ cli
1755
+ .ns('aws')
1756
+ .description('Establish an AWS session and optionally forward to the AWS CLI')
1757
+ .configureHelp({ showGlobalOptions: true })
1758
+ .enablePositionalOptions()
1759
+ .passThroughOptions()
1760
+ .allowUnknownOption(true)
1761
+ // Boolean toggles
1762
+ .option('--login-on-demand', 'attempt aws sso login on-demand')
1763
+ .option('--no-login-on-demand', 'disable sso login on-demand')
1764
+ .option('--set-env', 'write resolved values into process.env')
1765
+ .option('--no-set-env', 'do not write resolved values into process.env')
1766
+ .option('--add-ctx', 'mirror results under ctx.plugins.aws')
1767
+ .option('--no-add-ctx', 'do not mirror results under ctx.plugins.aws')
1768
+ // Strings / enums
1769
+ .option('--profile <string>', 'AWS profile name')
1770
+ .option('--region <string>', 'AWS region')
1771
+ .option('--default-region <string>', 'fallback region')
1772
+ .option('--strategy <string>', 'credential acquisition strategy: cli-export|none')
1773
+ // Advanced key overrides
1774
+ .option('--profile-key <string>', 'dotenv/config key for local profile')
1775
+ .option('--profile-fallback-key <string>', 'fallback dotenv/config key for profile')
1776
+ .option('--region-key <string>', 'dotenv/config key for region')
1777
+ // Accept any extra operands so Commander does not error when tokens appear after "--".
1778
+ .argument('[args...]')
1779
+ .action(async (args, opts, thisCommand) => {
1780
+ const self = thisCommand;
1781
+ const parent = (self.parent ?? null);
1782
+ // Access merged root CLI options (installed by passOptions())
1783
+ const rootOpts = (parent?.getDotenvCliOptions ?? {});
1784
+ const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
1785
+ Boolean(rootOpts?.capture);
1786
+ const underTests = process.env.GETDOTENV_TEST === '1' ||
1787
+ typeof process.env.VITEST_WORKER_ID === 'string';
1788
+ // Build overlay cfg from subcommand flags layered over discovered config.
1789
+ const ctx = cli.getCtx();
1790
+ const cfgBase = (ctx?.pluginConfigs?.['aws'] ??
1791
+ {});
1792
+ const overlay = {};
1793
+ // Map boolean toggles (respect explicit --no-*)
1794
+ if (Object.prototype.hasOwnProperty.call(opts, 'loginOnDemand'))
1795
+ overlay.loginOnDemand = Boolean(opts.loginOnDemand);
1796
+ if (Object.prototype.hasOwnProperty.call(opts, 'setEnv'))
1797
+ overlay.setEnv = Boolean(opts.setEnv);
1798
+ if (Object.prototype.hasOwnProperty.call(opts, 'addCtx'))
1799
+ overlay.addCtx = Boolean(opts.addCtx);
1800
+ // Strings/enums
1801
+ if (typeof opts.profile === 'string')
1802
+ overlay.profile = opts.profile;
1803
+ if (typeof opts.region === 'string')
1804
+ overlay.region = opts.region;
1805
+ if (typeof opts.defaultRegion === 'string')
1806
+ overlay.defaultRegion = opts.defaultRegion;
1807
+ if (typeof opts.strategy === 'string')
1808
+ overlay.strategy =
1809
+ opts.strategy;
1810
+ // Advanced key overrides
1811
+ if (typeof opts.profileKey === 'string')
1812
+ overlay.profileKey = opts.profileKey;
1813
+ if (typeof opts.profileFallbackKey === 'string')
1814
+ overlay.profileFallbackKey = opts.profileFallbackKey;
1815
+ if (typeof opts.regionKey === 'string')
1816
+ overlay.regionKey = opts.regionKey;
1817
+ const cfg = {
1818
+ ...cfgBase,
1819
+ ...overlay,
1820
+ };
1821
+ // Resolve current context with overrides
1822
+ const out = await resolveAwsContext({
1823
+ dotenv: ctx?.dotenv ?? {},
1824
+ cfg,
1825
+ });
1826
+ // Apply env/ctx mirrors per toggles
1827
+ if (cfg.setEnv !== false) {
1828
+ if (out.region) {
1829
+ process.env.AWS_REGION = out.region;
1830
+ if (!process.env.AWS_DEFAULT_REGION)
1831
+ process.env.AWS_DEFAULT_REGION = out.region;
1832
+ }
1833
+ if (out.credentials) {
1834
+ process.env.AWS_ACCESS_KEY_ID = out.credentials.accessKeyId;
1835
+ process.env.AWS_SECRET_ACCESS_KEY =
1836
+ out.credentials.secretAccessKey;
1837
+ if (out.credentials.sessionToken !== undefined) {
1838
+ process.env.AWS_SESSION_TOKEN = out.credentials.sessionToken;
1839
+ }
1840
+ }
1841
+ }
1842
+ if (cfg.addCtx !== false) {
1843
+ if (ctx) {
1844
+ ctx.plugins ??= {};
1845
+ ctx.plugins['aws'] = {
1846
+ ...(out.profile ? { profile: out.profile } : {}),
1847
+ ...(out.region ? { region: out.region } : {}),
1848
+ ...(out.credentials ? { credentials: out.credentials } : {}),
1849
+ };
1850
+ }
1851
+ }
1852
+ // Forward when positional args are present; otherwise session-only.
1853
+ if (Array.isArray(args) && args.length > 0) {
1854
+ const argv = ['aws', ...args];
1855
+ const shellSetting = resolveShell(rootOpts?.scripts, 'aws', rootOpts?.shell);
1856
+ const ctxDotenv = (ctx?.dotenv ?? {});
1857
+ const exit = await runCommand(argv, shellSetting, {
1858
+ env: { ...process.env, ...ctxDotenv },
1859
+ stdio: capture ? 'pipe' : 'inherit',
1860
+ });
1861
+ // Deterministic termination (suppressed under tests)
1862
+ if (!underTests) {
1863
+ process.exit(typeof exit === 'number' ? exit : 0);
1864
+ }
1865
+ return;
1866
+ }
1867
+ else {
1868
+ // Session only: low-noise breadcrumb under debug
1869
+ if (process.env.GETDOTENV_DEBUG) {
1870
+ const log = console;
1871
+ log.log('[aws] session established', {
1872
+ profile: out.profile,
1873
+ region: out.region,
1874
+ hasCreds: Boolean(out.credentials),
1875
+ });
1876
+ }
1877
+ if (!underTests)
1878
+ process.exit(0);
1879
+ return;
1880
+ }
1881
+ });
1882
+ },
1883
+ async afterResolve(_cli, ctx) {
1884
+ const log = console;
1885
+ const cfgRaw = (ctx.pluginConfigs?.['aws'] ?? {});
1886
+ const cfg = (cfgRaw || {});
1887
+ const out = await resolveAwsContext({
1888
+ dotenv: ctx.dotenv,
1889
+ cfg,
666
1890
  });
667
- return await importDefault(url.pathToFileURL(cacheFile).toString());
1891
+ const { profile, region, credentials } = out;
1892
+ if (cfg.setEnv !== false) {
1893
+ if (region) {
1894
+ process.env.AWS_REGION = region;
1895
+ if (!process.env.AWS_DEFAULT_REGION)
1896
+ process.env.AWS_DEFAULT_REGION = region;
1897
+ }
1898
+ if (credentials) {
1899
+ process.env.AWS_ACCESS_KEY_ID = credentials.accessKeyId;
1900
+ process.env.AWS_SECRET_ACCESS_KEY = credentials.secretAccessKey;
1901
+ if (credentials.sessionToken !== undefined) {
1902
+ process.env.AWS_SESSION_TOKEN = credentials.sessionToken;
1903
+ }
1904
+ }
1905
+ }
1906
+ if (cfg.addCtx !== false) {
1907
+ ctx.plugins ??= {};
1908
+ ctx.plugins['aws'] = {
1909
+ ...(profile ? { profile } : {}),
1910
+ ...(region ? { region } : {}),
1911
+ ...(credentials ? { credentials } : {}),
1912
+ };
1913
+ }
1914
+ // Optional: low-noise breadcrumb for diagnostics
1915
+ if (process.env.GETDOTENV_DEBUG) {
1916
+ log.log('[aws] afterResolve', {
1917
+ profile,
1918
+ region,
1919
+ hasCreds: Boolean(credentials),
1920
+ });
1921
+ }
1922
+ },
1923
+ });
1924
+
1925
+ const globPaths = async ({ globs, logger, pkgCwd, rootPath, }) => {
1926
+ let cwd = process.cwd();
1927
+ if (pkgCwd) {
1928
+ const pkgDir = await packageDirectory();
1929
+ if (!pkgDir) {
1930
+ logger.error('No package directory found.');
1931
+ process.exit(0);
1932
+ }
1933
+ cwd = pkgDir;
668
1934
  }
669
- catch {
670
- // no esbuild; fall back to TS transpile for simple modules
1935
+ const absRootPath = path.posix.join(cwd.split(path.sep).join(path.posix.sep), rootPath.split(path.sep).join(path.posix.sep));
1936
+ const paths = await globby(globs.split(/\s+/), {
1937
+ cwd: absRootPath,
1938
+ expandDirectories: false,
1939
+ onlyDirectories: true,
1940
+ absolute: true,
1941
+ });
1942
+ if (!paths.length) {
1943
+ logger.error(`No paths found for globs '${globs}' at '${absRootPath}'.`);
1944
+ process.exit(0);
671
1945
  }
672
- try {
673
- const ts = (await import('typescript'));
674
- const code = await fs.readFile(absPath, 'utf-8');
675
- const out = ts.transpileModule(code, {
676
- compilerOptions: {
677
- module: 'ESNext',
678
- target: 'ES2022',
679
- moduleResolution: 'NodeNext',
680
- },
1946
+ return { absRootPath, paths };
1947
+ };
1948
+ const execShellCommandBatch = async ({ command, getDotenvCliOptions, globs, ignoreErrors, list, logger, pkgCwd, rootPath, shell, }) => {
1949
+ const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
1950
+ Boolean(getDotenvCliOptions?.capture); // Require a command only when not listing. In list mode, a command is optional.
1951
+ if (!command && !list) {
1952
+ logger.error(`No command provided. Use --command or --list.`);
1953
+ process.exit(0);
1954
+ }
1955
+ const { absRootPath, paths } = await globPaths({
1956
+ globs,
1957
+ logger,
1958
+ rootPath,
1959
+ // exactOptionalPropertyTypes: only include when defined
1960
+ ...(pkgCwd !== undefined ? { pkgCwd } : {}),
1961
+ });
1962
+ const headerTitle = list
1963
+ ? 'Listing working directories...'
1964
+ : 'Executing command batch...';
1965
+ logger.info('');
1966
+ const headerRootPath = `ROOT: ${absRootPath}`;
1967
+ const headerGlobs = `GLOBS: ${globs}`;
1968
+ // Prepare a safe label for the header (avoid undefined in template)
1969
+ const commandLabel = Array.isArray(command)
1970
+ ? command.join(' ')
1971
+ : typeof command === 'string' && command.length > 0
1972
+ ? command
1973
+ : '';
1974
+ const headerCommand = list ? `CMD: (list only)` : `CMD: ${commandLabel}`;
1975
+ logger.info('*'.repeat(Math.max(headerTitle.length, headerRootPath.length, headerGlobs.length, headerCommand.length)));
1976
+ logger.info(headerTitle);
1977
+ logger.info('');
1978
+ logger.info(headerRootPath);
1979
+ logger.info(headerGlobs);
1980
+ logger.info(headerCommand);
1981
+ for (const path of paths) {
1982
+ // Write path and command to console.
1983
+ const pathLabel = `CWD: ${path}`;
1984
+ if (list) {
1985
+ logger.info(pathLabel);
1986
+ continue;
1987
+ }
1988
+ logger.info('');
1989
+ logger.info('*'.repeat(pathLabel.length));
1990
+ logger.info(pathLabel);
1991
+ logger.info(headerCommand);
1992
+ // Execute command.
1993
+ try {
1994
+ const hasCmd = (typeof command === 'string' && command.length > 0) ||
1995
+ (Array.isArray(command) && command.length > 0);
1996
+ if (hasCmd) {
1997
+ await runCommand(command, shell, {
1998
+ cwd: path,
1999
+ env: {
2000
+ ...process.env,
2001
+ getDotenvCliOptions: getDotenvCliOptions
2002
+ ? JSON.stringify(getDotenvCliOptions)
2003
+ : undefined,
2004
+ },
2005
+ stdio: capture ? 'pipe' : 'inherit',
2006
+ });
2007
+ }
2008
+ else {
2009
+ // Should not occur due to the early guard; retain for type safety.
2010
+ logger.error(`No command provided. Use --command or --list.`);
2011
+ process.exit(0);
2012
+ }
2013
+ }
2014
+ catch (error) {
2015
+ if (!ignoreErrors) {
2016
+ throw error;
2017
+ }
2018
+ }
2019
+ }
2020
+ logger.info('');
2021
+ };
2022
+
2023
+ /**
2024
+ * Build the default "cmd" subcommand action for the batch plugin.
2025
+ * Mirrors the original inline implementation with identical behavior.
2026
+ */
2027
+ const buildDefaultCmdAction = (cli, batchCmd, opts) => async (commandParts, _subOpts, _thisCommand) => {
2028
+ const loggerLocal = opts.logger ?? console;
2029
+ // Guard: when invoked without positional args (e.g., `batch --list`),
2030
+ // defer entirely to the parent action handler.
2031
+ const argsRaw = Array.isArray(commandParts)
2032
+ ? commandParts
2033
+ : [];
2034
+ const localList = argsRaw.includes('-l') || argsRaw.includes('--list');
2035
+ const args = localList
2036
+ ? argsRaw.filter((t) => t !== '-l' && t !== '--list')
2037
+ : argsRaw;
2038
+ // Access merged per-plugin config from host context (if any).
2039
+ const ctx = cli.getCtx();
2040
+ const cfgRaw = (ctx?.pluginConfigs?.['batch'] ?? {});
2041
+ const cfg = (cfgRaw || {});
2042
+ // Resolve batch flags from the captured parent (batch) command.
2043
+ const raw = batchCmd.opts();
2044
+ const listFromParent = !!raw.list;
2045
+ const ignoreErrors = !!raw.ignoreErrors;
2046
+ const globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
2047
+ const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
2048
+ const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
2049
+ // Resolve scripts/shell with precedence:
2050
+ // plugin opts → plugin config → merged root CLI options
2051
+ const mergedBag = ((batchCmd.parent ?? null)?.getDotenvCliOptions ?? {});
2052
+ const scripts = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
2053
+ const shell = opts.shell ?? cfg.shell ?? mergedBag.shell;
2054
+ // If no positional args were given, bridge to --command/--list paths here.
2055
+ if (args.length === 0) {
2056
+ const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
2057
+ if (typeof commandOpt === 'string') {
2058
+ await execShellCommandBatch({
2059
+ command: resolveCommand(scripts, commandOpt),
2060
+ globs,
2061
+ ignoreErrors,
2062
+ list: false,
2063
+ logger: loggerLocal,
2064
+ ...(pkgCwd ? { pkgCwd } : {}),
2065
+ rootPath,
2066
+ shell: resolveShell(scripts, commandOpt, shell),
2067
+ });
2068
+ return;
2069
+ }
2070
+ if (raw.list || localList) {
2071
+ await execShellCommandBatch({
2072
+ globs,
2073
+ ignoreErrors,
2074
+ list: true,
2075
+ logger: loggerLocal,
2076
+ ...(pkgCwd ? { pkgCwd } : {}),
2077
+ rootPath,
2078
+ shell: (shell ?? false),
2079
+ });
2080
+ return;
2081
+ }
2082
+ {
2083
+ const lr = loggerLocal;
2084
+ const emit = lr.error ?? lr.log;
2085
+ emit(`No command provided. Use --command or --list.`);
2086
+ }
2087
+ process.exit(0);
2088
+ }
2089
+ // If a local list flag was supplied with positional tokens (and no --command),
2090
+ // treat tokens as additional globs and execute list mode.
2091
+ if (localList && typeof raw.command !== 'string') {
2092
+ const extraGlobs = args.map(String).join(' ').trim();
2093
+ const mergedGlobs = [globs, extraGlobs].filter(Boolean).join(' ');
2094
+ const shellBag = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
2095
+ await execShellCommandBatch({
2096
+ globs: mergedGlobs,
2097
+ ignoreErrors,
2098
+ list: true,
2099
+ logger: loggerLocal,
2100
+ ...(pkgCwd ? { pkgCwd } : {}),
2101
+ rootPath,
2102
+ shell: (shell ?? shellBag.shell ?? false),
681
2103
  });
682
- await fs.ensureDir(cacheDir);
683
- await fs.writeFile(cacheFile, out.outputText, 'utf-8');
684
- return await importDefault(url.pathToFileURL(cacheFile).toString());
2104
+ return;
685
2105
  }
686
- catch {
687
- throw new Error(`Unable to load dynamic TypeScript file: ${absPath}. ` +
688
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
2106
+ // If parent list flag is set and positional tokens are present (and no --command),
2107
+ // treat tokens as additional globs for list-only mode.
2108
+ if (listFromParent && args.length > 0 && typeof raw.command !== 'string') {
2109
+ const extra = args.map(String).join(' ').trim();
2110
+ const mergedGlobs = [globs, extra].filter(Boolean).join(' ');
2111
+ const mergedBag2 = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
2112
+ await execShellCommandBatch({
2113
+ globs: mergedGlobs,
2114
+ ignoreErrors,
2115
+ list: true,
2116
+ logger: loggerLocal,
2117
+ ...(pkgCwd ? { pkgCwd } : {}),
2118
+ rootPath,
2119
+ shell: (shell ?? mergedBag2.shell ?? false),
2120
+ });
2121
+ return;
689
2122
  }
2123
+ // Join positional args as the command to execute.
2124
+ const input = args.map(String).join(' ');
2125
+ // Optional: round-trip parent merged options if present (shipped CLI).
2126
+ const envBag = (batchCmd.parent ?? undefined)?.getDotenvCliOptions;
2127
+ const mergedExec = ((batchCmd.parent ?? undefined)?.getDotenvCliOptions ?? {});
2128
+ const scriptsExec = scripts ?? mergedExec.scripts;
2129
+ const shellExec = shell ?? mergedExec.shell;
2130
+ const resolved = resolveCommand(scriptsExec, input);
2131
+ const shellSetting = resolveShell(scriptsExec, input, shellExec);
2132
+ // Preserve argv array only for shell-off Node -e snippets to avoid
2133
+ // lossy re-tokenization (Windows/PowerShell quoting). For simple
2134
+ // commands (e.g., "echo OK") keep string form to satisfy unit tests.
2135
+ let commandArg = resolved;
2136
+ if (shellSetting === false && resolved === input) {
2137
+ const first = (args[0] ?? '').toLowerCase();
2138
+ const hasEval = args.includes('-e') || args.includes('--eval');
2139
+ if (first === 'node' && hasEval) {
2140
+ commandArg = args.map(String);
2141
+ }
2142
+ }
2143
+ await execShellCommandBatch({
2144
+ command: commandArg,
2145
+ ...(envBag ? { getDotenvCliOptions: envBag } : {}),
2146
+ globs,
2147
+ ignoreErrors,
2148
+ list: false,
2149
+ logger: loggerLocal,
2150
+ ...(pkgCwd ? { pkgCwd } : {}),
2151
+ rootPath,
2152
+ shell: shellSetting,
2153
+ });
690
2154
  };
2155
+
691
2156
  /**
692
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
693
- *
694
- * @param options - `GetDotenvOptions` object
695
- * @returns The combined parsed dotenv object.
696
- * * @example Load from the project root with default tokens
697
- * ```ts
698
- * const vars = await getDotenv();
699
- * console.log(vars.MY_SETTING);
700
- * ```
701
- *
702
- * @example Load from multiple paths and a specific environment
703
- * ```ts
704
- * const vars = await getDotenv({
705
- * env: 'dev',
706
- * dotenvToken: '.testenv',
707
- * privateToken: 'secret',
708
- * paths: ['./', './packages/app'],
709
- * });
710
- * ```
711
- *
712
- * @example Use dynamic variables
713
- * ```ts
714
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
715
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
716
- * ```
717
- *
718
- * @remarks
719
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
720
- * into `process.env` as a side effect.
721
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
722
- * The path is resolved after expansion, so it may reference previously loaded vars.
2157
+ * Build the parent "batch" action handler (no explicit subcommand).
2158
+ */
2159
+ const buildParentAction = (cli, opts) => async (commandParts, thisCommand) => {
2160
+ const logger = opts.logger ?? console;
2161
+ // Ensure context exists (host preSubcommand on root creates if missing).
2162
+ const ctx = cli.getCtx();
2163
+ const cfgRaw = (ctx?.pluginConfigs?.['batch'] ?? {});
2164
+ const cfg = (cfgRaw || {});
2165
+ const raw = thisCommand.opts();
2166
+ const commandOpt = typeof raw.command === 'string' ? raw.command : undefined;
2167
+ const ignoreErrors = !!raw.ignoreErrors;
2168
+ let globs = typeof raw.globs === 'string' ? raw.globs : (cfg.globs ?? '*');
2169
+ const list = !!raw.list;
2170
+ const pkgCwd = raw.pkgCwd !== undefined ? !!raw.pkgCwd : !!cfg.pkgCwd;
2171
+ const rootPath = typeof raw.rootPath === 'string' ? raw.rootPath : (cfg.rootPath ?? './');
2172
+ // Treat parent positional tokens as the command when no explicit 'cmd' is used.
2173
+ const argsParent = Array.isArray(commandParts) ? commandParts : [];
2174
+ if (argsParent.length > 0 && !list) {
2175
+ const input = argsParent.map(String).join(' ');
2176
+ const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
2177
+ const scriptsAll = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
2178
+ const shellAll = opts.shell ?? cfg.shell ?? mergedBag.shell;
2179
+ const resolved = resolveCommand(scriptsAll, input);
2180
+ const shellSetting = resolveShell(scriptsAll, input, shellAll);
2181
+ // Parent path: pass a string; executor handles shell-specific details.
2182
+ const commandArg = resolved;
2183
+ await execShellCommandBatch({
2184
+ command: commandArg,
2185
+ globs,
2186
+ ignoreErrors,
2187
+ list: false,
2188
+ logger,
2189
+ ...(pkgCwd ? { pkgCwd } : {}),
2190
+ rootPath,
2191
+ shell: shellSetting,
2192
+ });
2193
+ return;
2194
+ }
2195
+ // List-only: merge extra positional tokens into globs when no --command is present.
2196
+ if (list && argsParent.length > 0 && !commandOpt) {
2197
+ const extra = argsParent.map(String).join(' ').trim();
2198
+ if (extra.length > 0)
2199
+ globs = [globs, extra].filter(Boolean).join(' ');
2200
+ const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
2201
+ await execShellCommandBatch({
2202
+ globs,
2203
+ ignoreErrors,
2204
+ list: true,
2205
+ logger,
2206
+ ...(pkgCwd ? { pkgCwd } : {}),
2207
+ rootPath,
2208
+ shell: (opts.shell ?? cfg.shell ?? mergedBag.shell ?? false),
2209
+ });
2210
+ return;
2211
+ }
2212
+ if (!commandOpt && !list) {
2213
+ logger.error(`No command provided. Use --command or --list.`);
2214
+ process.exit(0);
2215
+ }
2216
+ if (typeof commandOpt === 'string') {
2217
+ const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
2218
+ const scriptsOpt = opts.scripts ?? cfg.scripts ?? mergedBag.scripts;
2219
+ const shellOpt = opts.shell ?? cfg.shell ?? mergedBag.shell;
2220
+ await execShellCommandBatch({
2221
+ command: resolveCommand(scriptsOpt, commandOpt),
2222
+ globs,
2223
+ ignoreErrors,
2224
+ list,
2225
+ logger,
2226
+ ...(pkgCwd ? { pkgCwd } : {}),
2227
+ rootPath,
2228
+ shell: resolveShell(scriptsOpt, commandOpt, shellOpt),
2229
+ });
2230
+ return;
2231
+ }
2232
+ // list only (explicit --list without --command)
2233
+ const mergedBag = ((thisCommand.parent ?? null)?.getDotenvCliOptions ?? {});
2234
+ const shellOnly = (opts.shell ?? cfg.shell ?? mergedBag.shell ?? false);
2235
+ await execShellCommandBatch({
2236
+ globs,
2237
+ ignoreErrors,
2238
+ list: true,
2239
+ logger,
2240
+ ...(pkgCwd ? { pkgCwd } : {}),
2241
+ rootPath,
2242
+ shell: (shellOnly ?? false),
2243
+ });
2244
+ };
2245
+
2246
+ // Per-plugin config schema (optional fields; used as defaults).
2247
+ const ScriptSchema = z.union([
2248
+ z.string(),
2249
+ z.object({
2250
+ cmd: z.string(),
2251
+ shell: z.union([z.string(), z.boolean()]).optional(),
2252
+ }),
2253
+ ]);
2254
+ const BatchConfigSchema = z.object({
2255
+ scripts: z.record(z.string(), ScriptSchema).optional(),
2256
+ shell: z.union([z.string(), z.boolean()]).optional(),
2257
+ rootPath: z.string().optional(),
2258
+ globs: z.string().optional(),
2259
+ pkgCwd: z.boolean().optional(),
2260
+ });
2261
+
2262
+ /**
2263
+ * Batch plugin for the GetDotenv CLI host.
723
2264
  *
724
- * @throws Error when a dynamic module is present but cannot be imported.
725
- * @throws Error when an output path was requested but could not be resolved.
2265
+ * Mirrors the legacy batch subcommand behavior without altering the shipped CLI. * Options:
2266
+ * - scripts/shell: used to resolve command and shell behavior per script or global default.
2267
+ * - logger: defaults to console.
726
2268
  */
727
- const getDotenv = async (options = {}) => {
728
- // Apply defaults.
729
- 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);
730
- // Read .env files.
731
- const loaded = paths.length
732
- ? await paths.reduce(async (e, p) => {
733
- const publicGlobal = excludePublic || excludeGlobal
734
- ? Promise.resolve({})
735
- : readDotenv(path.resolve(p, dotenvToken));
736
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
737
- ? Promise.resolve({})
738
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
739
- const privateGlobal = excludePrivate || excludeGlobal
740
- ? Promise.resolve({})
741
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
742
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
743
- ? Promise.resolve({})
744
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
745
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
746
- e,
747
- publicGlobal,
748
- publicEnv,
749
- privateGlobal,
750
- privateEnv,
751
- ]);
752
- return {
753
- ...eResolved,
754
- ...publicGlobalResolved,
755
- ...publicEnvResolved,
756
- ...privateGlobalResolved,
757
- ...privateEnvResolved,
2269
+ const batchPlugin = (opts = {}) => definePlugin({
2270
+ id: 'batch',
2271
+ // Host validates this when config-loader is enabled; plugins may also
2272
+ // re-validate at action time as a safety belt.
2273
+ configSchema: BatchConfigSchema,
2274
+ setup(cli) {
2275
+ const ns = cli.ns('batch');
2276
+ const batchCmd = ns; // capture the parent "batch" command for default-subcommand context
2277
+ ns.description('Batch command execution across multiple working directories.')
2278
+ .enablePositionalOptions()
2279
+ .passThroughOptions()
2280
+ .option('-p, --pkg-cwd', 'use nearest package directory as current working directory')
2281
+ .option('-r, --root-path <string>', 'path to batch root directory from current working directory', './')
2282
+ .option('-g, --globs <string>', 'space-delimited globs from root path', '*')
2283
+ .option('-c, --command <string>', 'command executed according to the base shell resolution')
2284
+ .option('-l, --list', 'list working directories without executing command')
2285
+ .option('-e, --ignore-errors', 'ignore errors and continue with next path')
2286
+ .argument('[command...]')
2287
+ .addCommand(new Command()
2288
+ .name('cmd')
2289
+ .description('execute command, conflicts with --command option (default subcommand)')
2290
+ .enablePositionalOptions()
2291
+ .passThroughOptions()
2292
+ .argument('[command...]')
2293
+ .action(buildDefaultCmdAction(cli, batchCmd, opts)), { isDefault: true })
2294
+ .action(buildParentAction(cli, opts));
2295
+ },
2296
+ });
2297
+
2298
+ const dbg = (...args) => {
2299
+ if (process.env.GETDOTENV_DEBUG) {
2300
+ // Use stderr to avoid interfering with stdout assertions
2301
+ console.error('[getdotenv:alias]', ...args);
2302
+ }
2303
+ };
2304
+ const attachParentAlias = (cli, options, _cmd) => {
2305
+ const aliasSpec = typeof options.optionAlias === 'string'
2306
+ ? { flags: options.optionAlias, description: undefined, expand: true }
2307
+ : options.optionAlias;
2308
+ if (!aliasSpec)
2309
+ return;
2310
+ const deriveKey = (flags) => {
2311
+ dbg('install alias option', flags);
2312
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
2313
+ const name = long.replace(/^--/, '');
2314
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
2315
+ };
2316
+ const aliasKey = deriveKey(aliasSpec.flags);
2317
+ // Expose the option on the parent.
2318
+ const desc = aliasSpec.description ??
2319
+ 'alias of cmd subcommand; provide command tokens (variadic)';
2320
+ cli.option(aliasSpec.flags, desc);
2321
+ // Shared alias executor for either preAction or preSubcommand hooks.
2322
+ // Ensure we only execute once even if both hooks fire in a single parse.
2323
+ let aliasHandled = false;
2324
+ const maybeRunAlias = async (thisCommand) => {
2325
+ dbg('alias:maybe:start');
2326
+ const raw = thisCommand.rawArgs ?? [];
2327
+ const childNames = thisCommand.commands.flatMap((c) => [
2328
+ c.name(),
2329
+ ...c.aliases(),
2330
+ ]);
2331
+ const hasSub = childNames.some((n) => raw.includes(n));
2332
+ // Read alias value from parent opts.
2333
+ const o = thisCommand.opts();
2334
+ const val = o[aliasKey];
2335
+ const provided = typeof val === 'string'
2336
+ ? val.length > 0
2337
+ : Array.isArray(val)
2338
+ ? val.length > 0
2339
+ : false;
2340
+ if (!provided || hasSub) {
2341
+ dbg('alias:maybe:skip', { provided, hasSub });
2342
+ return; // not an alias-only invocation
2343
+ }
2344
+ if (aliasHandled) {
2345
+ dbg('alias:maybe:already-handled');
2346
+ return;
2347
+ }
2348
+ aliasHandled = true;
2349
+ dbg('alias-only invocation detected');
2350
+ // Merge CLI options and resolve dotenv context.
2351
+ const { merged } = resolveCliOptions(o, baseRootOptionDefaults, process.env.getDotenvCliOptions);
2352
+ const logger = merged.logger ?? console;
2353
+ const serviceOptions = getDotenvCliOptions2Options(merged);
2354
+ await cli.resolveAndLoad(serviceOptions);
2355
+ // Normalize alias value.
2356
+ const joined = typeof val === 'string'
2357
+ ? val
2358
+ : Array.isArray(val)
2359
+ ? val.map(String).join(' ')
2360
+ : '';
2361
+ const input = aliasSpec.expand === false
2362
+ ? joined
2363
+ : (dotenvExpandFromProcessEnv(joined) ?? joined);
2364
+ dbg('resolved input', { input });
2365
+ const resolved = resolveCommand(merged.scripts, input);
2366
+ const lg = logger;
2367
+ if (merged.debug) {
2368
+ (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
2369
+ }
2370
+ const { logger: _omit, ...envBag } = merged;
2371
+ // Test guard: when running under tests, prefer stdio: 'inherit' to avoid
2372
+ // assertions depending on captured stdio; ignore GETDOTENV_STDIO/capture.
2373
+ const underTests = process.env.GETDOTENV_TEST === '1' ||
2374
+ typeof process.env.VITEST_WORKER_ID === 'string';
2375
+ const forceExit = process.env.GETDOTENV_FORCE_EXIT === '1';
2376
+ const capture = !underTests &&
2377
+ (process.env.GETDOTENV_STDIO === 'pipe' ||
2378
+ Boolean(merged.capture));
2379
+ dbg('run:start', { capture, shell: merged.shell });
2380
+ // Prefer explicit env injection: include resolved dotenv map to avoid leaking
2381
+ // parent process.env secrets when exclusions are set.
2382
+ const ctx = cli.getCtx();
2383
+ const dotenv = (ctx?.dotenv ?? {});
2384
+ // Diagnostics: --trace [keys...]
2385
+ const traceOpt = merged.trace;
2386
+ if (traceOpt) {
2387
+ const parentKeys = Object.keys(process.env);
2388
+ const dotenvKeys = Object.keys(dotenv);
2389
+ const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
2390
+ const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
2391
+ const childEnvPreview = {
2392
+ ...process.env,
2393
+ ...dotenv,
758
2394
  };
759
- }, Promise.resolve({}))
760
- : {};
761
- const outputKey = nanoid();
762
- const dotenv = dotenvExpandAll({
763
- ...loaded,
764
- ...vars,
765
- ...(outputPath ? { [outputKey]: outputPath } : {}),
766
- }, { progressive: true });
767
- // Process dynamic variables. Programmatic option takes precedence over path.
768
- if (!excludeDynamic) {
769
- let dynamic = undefined;
770
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
771
- dynamic = options.dynamic;
2395
+ for (const k of keys) {
2396
+ const parent = process.env[k];
2397
+ const dot = dotenv[k];
2398
+ const final = childEnvPreview[k];
2399
+ const origin = dot !== undefined
2400
+ ? 'dotenv'
2401
+ : parent !== undefined
2402
+ ? 'parent'
2403
+ : 'unset';
2404
+ process.stderr.write(`[trace] key=${k} origin=${origin} parent=${parent ?? ''} dotenv=${dot ?? ''} final=${final ?? ''}\n`);
2405
+ }
772
2406
  }
773
- else if (dynamicPath) {
774
- const absDynamicPath = path.resolve(dynamicPath);
775
- dynamic = await loadDynamicFromPath(absDynamicPath);
2407
+ let exitCode = Number.NaN;
2408
+ try {
2409
+ // Resolve shell and preserve argv for Node -e snippets under shell-off.
2410
+ const shellSetting = resolveShell(merged.scripts, input, merged.shell);
2411
+ let commandArg = resolved;
2412
+ /** * Special-case: when shell is OFF and no script alias remap occurred
2413
+ * (resolved === input), treat a Node eval payload as an argv array to
2414
+ * avoid lossy re-tokenization of the code string.
2415
+ *
2416
+ * Examples handled:
2417
+ * "node -e \"console.log(JSON.stringify(...))\""
2418
+ * "node --eval 'console.log(...)'"
2419
+ *
2420
+ * We peel exactly one pair of symmetric outer quotes from the code
2421
+ * argument when present; inner quotes remain untouched.
2422
+ */
2423
+ if (shellSetting === false && resolved === input) {
2424
+ // Helper: strip one symmetric outer quote layer
2425
+ const stripOne = (s) => {
2426
+ if (s.length < 2)
2427
+ return s;
2428
+ const a = s.charAt(0);
2429
+ const b = s.charAt(s.length - 1);
2430
+ const symmetric = (a === '"' && b === '"') || (a === "'" && b === "'");
2431
+ return symmetric ? s.slice(1, -1) : s;
2432
+ };
2433
+ // Normalize whole input once for robust matching
2434
+ const normalized = stripOne(input.trim());
2435
+ // First try a lightweight regex on the normalized string
2436
+ const m = /^\s*node\s+(--eval|-e)\s+([\s\S]+)$/i.exec(normalized);
2437
+ if (m && typeof m[1] === 'string' && typeof m[2] === 'string') {
2438
+ const evalFlag = m[1];
2439
+ let codeArg = m[2].trim();
2440
+ codeArg = stripOne(codeArg);
2441
+ const flag = evalFlag.startsWith('--') ? '--eval' : '-e';
2442
+ commandArg = ['node', flag, codeArg];
2443
+ }
2444
+ else {
2445
+ // Fallback: tokenize and detect node -e/--eval form
2446
+ const parts = tokenize(input);
2447
+ if (parts.length >= 3) {
2448
+ // Narrow under noUncheckedIndexedAccess
2449
+ const p0 = parts[0];
2450
+ const p1 = parts[1];
2451
+ if (p0?.toLowerCase() === 'node' &&
2452
+ (p1 === '-e' || p1 === '--eval')) {
2453
+ commandArg = parts;
2454
+ }
2455
+ }
2456
+ }
2457
+ }
2458
+ exitCode = await runCommand(commandArg, shellSetting, {
2459
+ env: {
2460
+ ...process.env,
2461
+ ...dotenv,
2462
+ getDotenvCliOptions: JSON.stringify(envBag),
2463
+ },
2464
+ stdio: capture ? 'pipe' : 'inherit',
2465
+ });
2466
+ dbg('run:done', { exitCode });
776
2467
  }
777
- if (dynamic) {
2468
+ catch (err) {
2469
+ const code = typeof err.exitCode === 'number'
2470
+ ? err.exitCode
2471
+ : 1;
2472
+ dbg('run:error', { exitCode: code, error: String(err) });
2473
+ if (!underTests) {
2474
+ dbg('process.exit (error path)', { exitCode: code });
2475
+ process.exit(code);
2476
+ }
2477
+ else {
2478
+ dbg('process.exit suppressed for tests (error path)', {
2479
+ exitCode: code,
2480
+ });
2481
+ }
2482
+ return;
2483
+ }
2484
+ if (!Number.isNaN(exitCode)) {
2485
+ dbg('process.exit', { exitCode });
2486
+ process.exit(exitCode);
2487
+ }
2488
+ // Fallback: Some environments may not surface a numeric exitCode even on success.
2489
+ // Always terminate alias-only invocations outside tests to avoid hanging the process,
2490
+ // regardless of capture/GETDOTENV_STDIO. Under tests, suppress to keep the runner alive.
2491
+ if (!underTests) {
2492
+ dbg('process.exit (fallback: non-numeric exitCode)', { exitCode: 0 });
2493
+ process.exit(0);
2494
+ }
2495
+ else {
2496
+ dbg('process.exit (fallback suppressed for tests: non-numeric exitCode)', { exitCode: 0 });
2497
+ }
2498
+ // Optional last-resort guard: force an exit on the next tick when enabled.
2499
+ // Intended for diagnosing environments where the process appears to linger
2500
+ // despite reaching the success/error handlers above. Disabled under tests.
2501
+ if (forceExit) {
778
2502
  try {
779
- for (const key in dynamic)
780
- Object.assign(dotenv, {
781
- [key]: typeof dynamic[key] === 'function'
782
- ? dynamic[key](dotenv, env ?? defaultEnv)
783
- : dynamic[key],
2503
+ if (process.env.GETDOTENV_DEBUG_VERBOSE) {
2504
+ const getHandles = process._getActiveHandles;
2505
+ const handles = typeof getHandles === 'function' ? getHandles() : [];
2506
+ dbg('active handles before forced exit', {
2507
+ count: Array.isArray(handles) ? handles.length : undefined,
784
2508
  });
2509
+ }
785
2510
  }
786
2511
  catch {
787
- throw new Error(`Unable to evaluate dynamic variables.`);
2512
+ // best-effort only
788
2513
  }
2514
+ const code = Number.isNaN(exitCode) ? 0 : exitCode;
2515
+ dbg('process.exit (forced)', { exitCode: code });
2516
+ setImmediate(() => process.exit(code));
789
2517
  }
790
- }
791
- // Write output file.
792
- let resultDotenv = dotenv;
793
- if (outputPath) {
794
- const outputPathResolved = dotenv[outputKey];
795
- if (!outputPathResolved)
796
- throw new Error('Output path not found.');
797
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
798
- await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
799
- const value = dotenvForOutput[key] ?? '';
800
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
801
- }, ''), { encoding: 'utf-8' });
802
- resultDotenv = dotenvForOutput;
803
- }
804
- // Log result.
805
- if (log)
806
- logger.log(resultDotenv);
807
- // Load process.env.
808
- if (loadProcess)
809
- Object.assign(process.env, resultDotenv);
810
- return resultDotenv;
2518
+ };
2519
+ // Execute alias-only invocations whether the root handles the action // itself (preAction) or Commander routes to a default subcommand (preSubcommand).
2520
+ cli.hook('preAction', async (thisCommand, _actionCommand) => {
2521
+ await maybeRunAlias(thisCommand);
2522
+ });
2523
+ cli.hook('preSubcommand', async (thisCommand) => {
2524
+ await maybeRunAlias(thisCommand);
2525
+ });
811
2526
  };
812
2527
 
813
- /**
814
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
815
- * - If the user explicitly enabled the flag, return true.
816
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
817
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
818
- *
819
- * @param exclude - The "on" flag value as parsed by Commander.
820
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
821
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
822
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
2528
+ /**+ Cmd plugin: executes a command using the current getdotenv CLI context.
823
2529
  *
824
- * @example
825
- * ```ts
826
- * resolveExclusion(undefined, undefined, true); // => true
827
- * ```
828
- */
829
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
2530
+ * - Joins positional args into a single command string.
2531
+ * - Resolves scripts and shell settings using shared helpers.
2532
+ * - Forwards merged CLI options to subprocesses via
2533
+ * process.env.getDotenvCliOptions for nested CLI behavior. */
2534
+ const cmdPlugin = (options = {}) => definePlugin({
2535
+ id: 'cmd',
2536
+ setup(cli) {
2537
+ const aliasSpec = typeof options.optionAlias === 'string'
2538
+ ? { flags: options.optionAlias}
2539
+ : options.optionAlias;
2540
+ const deriveKey = (flags) => {
2541
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
2542
+ const name = long.replace(/^--/, '');
2543
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
2544
+ };
2545
+ const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
2546
+ const cmd = new Command()
2547
+ .name('cmd')
2548
+ .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
2549
+ .configureHelp({ showGlobalOptions: true })
2550
+ .enablePositionalOptions()
2551
+ .passThroughOptions()
2552
+ .argument('[command...]')
2553
+ .action(async (commandParts, _opts, thisCommand) => {
2554
+ // Commander passes positional tokens as the first action argument
2555
+ const args = Array.isArray(commandParts) ? commandParts : [];
2556
+ // No-op when invoked as the default command with no args.
2557
+ if (args.length === 0)
2558
+ return;
2559
+ const parent = thisCommand.parent;
2560
+ if (!parent)
2561
+ throw new Error('parent command not found'); // Conflict detection: if an alias option is present on parent, do not
2562
+ // also accept positional cmd args.
2563
+ if (aliasKey) {
2564
+ const pv = parent.opts();
2565
+ const ov = pv[aliasKey];
2566
+ if (ov !== undefined) {
2567
+ const merged = parent.getDotenvCliOptions ?? {};
2568
+ const logger = merged.logger ?? console;
2569
+ const lr = logger;
2570
+ const emit = lr.error ?? lr.log;
2571
+ emit(`--${aliasKey} option conflicts with cmd subcommand.`);
2572
+ process.exit(0);
2573
+ }
2574
+ }
2575
+ // Merged CLI options are persisted by the shipped CLI preSubcommand hook.
2576
+ const merged = parent.getDotenvCliOptions ?? {};
2577
+ const logger = merged.logger ?? console;
2578
+ // Join positional args into the command string.
2579
+ const input = args.map(String).join(' ');
2580
+ // Resolve command and shell using shared helpers.
2581
+ const scripts = merged.scripts;
2582
+ const shell = merged.shell;
2583
+ const resolved = resolveCommand(scripts, input);
2584
+ if (merged.debug) {
2585
+ const lg = logger;
2586
+ (lg.debug ?? lg.log)('\n*** command ***\n', `'${resolved}'`);
2587
+ }
2588
+ // Round-trip CLI options for nested getdotenv invocations.
2589
+ // Omit logger (functions are not serializable).
2590
+ const { logger: _omit, ...envBag } = merged;
2591
+ const capture = process.env.GETDOTENV_STDIO === 'pipe' ||
2592
+ Boolean(merged.capture);
2593
+ // Prefer explicit env injection: pass the resolved dotenv map to the child.
2594
+ // This avoids leaking prior secrets from the parent process.env when
2595
+ // exclusions (e.g., --exclude-private) are in effect.
2596
+ const host = cli;
2597
+ const ctx = host.getCtx();
2598
+ const dotenv = (ctx?.dotenv ?? {});
2599
+ // Diagnostics: --trace [keys...] (space-delimited keys if provided; all keys when true)
2600
+ const traceOpt = merged.trace;
2601
+ if (traceOpt) {
2602
+ // Determine keys to trace: all keys (parent ∪ dotenv) or selected.
2603
+ const parentKeys = Object.keys(process.env);
2604
+ const dotenvKeys = Object.keys(dotenv);
2605
+ const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
2606
+ const keys = Array.isArray(traceOpt) ? traceOpt : allKeys;
2607
+ // Child env preview (as composed below; excluding getDotenvCliOptions)
2608
+ const childEnvPreview = {
2609
+ ...process.env,
2610
+ ...dotenv,
2611
+ };
2612
+ for (const k of keys) {
2613
+ const parent = process.env[k];
2614
+ const dot = dotenv[k];
2615
+ const final = childEnvPreview[k];
2616
+ const origin = dot !== undefined
2617
+ ? 'dotenv'
2618
+ : parent !== undefined
2619
+ ? 'parent'
2620
+ : 'unset';
2621
+ // Emit concise diagnostic line to stderr.
2622
+ process.stderr.write(`[trace] key=${k} origin=${origin} parent=${parent ?? ''} dotenv=${dot ?? ''} final=${final ?? ''}\n`);
2623
+ }
2624
+ }
2625
+ const shellSetting = resolveShell(scripts, input, shell);
2626
+ /**
2627
+ * Preserve original argv array when:
2628
+ * - shell is OFF (plain execa), and
2629
+ * - no script alias remap occurred (resolved === input).
2630
+ *
2631
+ * This avoids lossy re-tokenization of code snippets such as:
2632
+ * node -e "console.log(process.env.APP_SECRET ?? '')"
2633
+ * where quotes may have been stripped by the parent shell and
2634
+ * spaces inside the code must remain a single argument.
2635
+ */
2636
+ const commandArg = shellSetting === false && resolved === input
2637
+ ? args.map(String)
2638
+ : resolved;
2639
+ await runCommand(commandArg, shellSetting, {
2640
+ env: {
2641
+ ...process.env,
2642
+ ...dotenv,
2643
+ getDotenvCliOptions: JSON.stringify(envBag),
2644
+ },
2645
+ stdio: capture ? 'pipe' : 'inherit',
2646
+ });
2647
+ });
2648
+ if (options.asDefault)
2649
+ cli.addCommand(cmd, { isDefault: true });
2650
+ else
2651
+ cli.addCommand(cmd);
2652
+ // Parent-attached option alias (optional).
2653
+ if (aliasSpec)
2654
+ attachParentAlias(cli, options);
2655
+ },
2656
+ });
2657
+
830
2658
  /**
831
- * Resolve an optional flag with "--exclude-all" overrides.
832
- * If excludeAll is set and the individual "...-off" is not, force true.
833
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
834
- * Otherwise, adopt the default (true → set; false/undefined → unset).
2659
+ * Demo plugin (educational).
835
2660
  *
836
- * @param exclude - Individual include/exclude flag.
837
- * @param excludeOff - Individual "...-off" flag.
838
- * @param defaultValue - Default for the individual flag.
839
- * @param excludeAll - Global "exclude-all" flag.
840
- * @param excludeAllOff - Global "exclude-all-off" flag.
2661
+ * Purpose
2662
+ * - Showcase how to build a plugin for the GetDotenv CLI host.
2663
+ * - Demonstrate:
2664
+ * - Accessing the resolved dotenv context (ctx).
2665
+ * - Executing child processes with explicit env injection.
2666
+ * - Resolving commands via scripts and honoring per-script shell overrides.
2667
+ * - Thin adapters: business logic stays minimal; use shared helpers.
841
2668
  *
842
- * @example
843
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
844
- */
845
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) => excludeAll && !excludeOff
846
- ? true
847
- : excludeAllOff && !exclude
848
- ? undefined
849
- : defaultValue
850
- ? true
851
- : undefined;
852
- /**
853
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
854
- * delete when undefined; assign when defined — without requiring an index signature on T.
2669
+ * Key host APIs used:
2670
+ * - definePlugin: declare a plugin with setup and optional afterResolve.
2671
+ * - cli.ns(name): create a namespaced subcommand under the root CLI.
2672
+ * - cli.getCtx(): access \{ optionsResolved, dotenv, plugins?, pluginConfigs? \}.
855
2673
  *
856
- * @typeParam T - Target object type.
857
- * @param obj - The object to write to.
858
- * @param key - The optional boolean property key of {@link T}.
859
- * @param value - The value to set or `undefined` to unset.
2674
+ * Design notes
2675
+ * - We use the shared runCommand() helper so behavior matches the built-in
2676
+ * cmd/batch plugins (env sanitization, plain vs shell execution, stdio).
2677
+ * - We inject ctx.dotenv into child env explicitly to avoid bleeding prior
2678
+ * secrets from process.env when exclusions are set (e.g., --exclude-private).
2679
+ * - We resolve scripts and shell using shared helpers to honor overrides:
2680
+ * resolveCommand(scripts, input) and resolveShell(scripts, input, shell).
860
2681
  *
861
- * @remarks
862
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
2682
+ * Usage (examples)
2683
+ * getdotenv demo ctx
2684
+ * getdotenv demo run --print APP_SETTING
2685
+ * getdotenv demo script echo OK
2686
+ * getdotenv --trace demo run --print ENV_SETTING
863
2687
  */
864
- const setOptionalFlag = (obj, key, value) => {
865
- const target = obj;
866
- const k = key;
867
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
868
- if (value === undefined)
869
- delete target[k];
870
- else
871
- target[k] = value;
872
- };
2688
+ const demoPlugin = () => definePlugin({
2689
+ id: 'demo',
2690
+ setup(cli) {
2691
+ const logger = console;
2692
+ const ns = cli
2693
+ .ns('demo')
2694
+ .description('Educational demo of host/plugin features (context, child exec, scripts/shell)');
2695
+ /**
2696
+ * demo ctx
2697
+ * Print a summary of the current dotenv context.
2698
+ *
2699
+ * Notes:
2700
+ * - The host resolves context once per invocation in a preSubcommand hook
2701
+ * (added by enhanceGetDotenvCli.passOptions() in the shipped CLI).
2702
+ * - ctx.dotenv contains the final merged values after overlays/dynamics.
2703
+ */
2704
+ ns.command('ctx')
2705
+ .description('Print a summary of the current dotenv context')
2706
+ .action(() => {
2707
+ const ctx = cli.getCtx();
2708
+ const dotenv = ctx?.dotenv ?? {};
2709
+ const keys = Object.keys(dotenv).sort();
2710
+ const sample = keys.slice(0, 5);
2711
+ logger.log('[demo] Context summary:');
2712
+ logger.log(`- keys: ${keys.length.toString()}`);
2713
+ logger.log(`- sample keys: ${sample.join(', ') || '(none)'}`);
2714
+ logger.log('- tip: use "--trace [keys...]" for per-key diagnostics');
2715
+ });
2716
+ /**
2717
+ * demo run [--print KEY]
2718
+ * Execute a small child process that prints a dotenv value.
2719
+ *
2720
+ * Design:
2721
+ * - Use shell-off + argv array to avoid cross-platform quoting pitfalls.
2722
+ * - Inject ctx.dotenv explicitly into the child env.
2723
+ * - Inherit stdio so output streams live (works well outside CI).
2724
+ *
2725
+ * Tip:
2726
+ * - For deterministic capture in CI, run with "--capture" (or set
2727
+ * GETDOTENV_STDIO=pipe). The shipped CLI honors both.
2728
+ */
2729
+ ns.command('run')
2730
+ .description('Run a small child process under the current dotenv (shell-off)')
2731
+ .option('--print <key>', 'dotenv key to print', 'APP_SETTING')
2732
+ .action(async (opts) => {
2733
+ const key = typeof opts.print === 'string' && opts.print.length > 0
2734
+ ? opts.print
2735
+ : 'APP_SETTING';
2736
+ // Build a minimal node -e payload via argv array (avoid quoting issues).
2737
+ const code = `console.log(process.env.${key} ?? "")`;
2738
+ const ctx = cli.getCtx();
2739
+ const dotenv = (ctx?.dotenv ?? {});
2740
+ // Inherit stdio for an interactive demo. Use --capture for CI.
2741
+ await runCommand(['node', '-e', code], false, {
2742
+ env: { ...process.env, ...dotenv },
2743
+ stdio: 'inherit',
2744
+ });
2745
+ });
2746
+ /**
2747
+ * demo script [command...]
2748
+ * Resolve and execute a command using the current scripts table and
2749
+ * shell preference (with per-script overrides).
2750
+ *
2751
+ * How it works:
2752
+ * - We read the merged CLI options persisted by the shipped CLI’s
2753
+ * passOptions() hook on the current command instance’s parent.
2754
+ * - resolveCommand resolves a script name → cmd or passes through a raw
2755
+ * command string.
2756
+ * - resolveShell chooses the appropriate shell:
2757
+ * scripts[name].shell ?? global shell (string|boolean).
2758
+ */
2759
+ ns.command('script')
2760
+ .description('Resolve a command via scripts and execute it with the proper shell')
2761
+ .argument('[command...]')
2762
+ .action(async (commandParts, _opts, thisCommand) => {
2763
+ // Safely access the parent’s merged options (installed by passOptions()).
2764
+ const parent = thisCommand.parent;
2765
+ const bag = (parent?.getDotenvCliOptions ?? {});
2766
+ const input = Array.isArray(commandParts)
2767
+ ? commandParts.map(String).join(' ')
2768
+ : '';
2769
+ if (!input) {
2770
+ logger.log('[demo] Please provide a command or script name, e.g. "echo OK" or "git-status".');
2771
+ return;
2772
+ }
2773
+ const resolved = resolveCommand(bag?.scripts, input);
2774
+ const shell = resolveShell(bag?.scripts, input, bag?.shell);
2775
+ // Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
2776
+ const ctx = cli.getCtx();
2777
+ const dotenv = (ctx?.dotenv ?? {});
2778
+ await runCommand(resolved, shell, {
2779
+ env: { ...process.env, ...dotenv },
2780
+ stdio: 'inherit',
2781
+ });
2782
+ });
2783
+ },
2784
+ /**
2785
+ * Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
2786
+ * For the demo we just log once to hint where such logic would live.
2787
+ */
2788
+ afterResolve(_cli, ctx) {
2789
+ const keys = Object.keys(ctx.dotenv);
2790
+ if (keys.length > 0) {
2791
+ // Keep noise low; a single-line breadcrumb is sufficient for the demo.
2792
+ console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
2793
+ }
2794
+ },
2795
+ });
873
2796
 
2797
+ const ensureDir = async (p) => {
2798
+ await fs.ensureDir(p);
2799
+ return p;
2800
+ };
2801
+ const writeFile = async (dest, data) => {
2802
+ await ensureDir(path.dirname(dest));
2803
+ await fs.writeFile(dest, data, 'utf-8');
2804
+ };
2805
+ const copyTextFile = async (src, dest, substitutions) => {
2806
+ const contents = await fs.readFile(src, 'utf-8');
2807
+ const out = substitutions && Object.keys(substitutions).length > 0
2808
+ ? Object.entries(substitutions).reduce((acc, [k, v]) => acc.split(k).join(v), contents)
2809
+ : contents;
2810
+ await writeFile(dest, out);
2811
+ };
874
2812
  /**
875
- * Build the Commander preSubcommand hook using the provided context.
876
- *
877
- * Responsibilities:
878
- * - Merge parent CLI options with current invocation (parent \< current).
879
- * - Resolve tri-state flags, including `--exclude-all` overrides.
880
- * - Normalize the shell setting to a concrete value (string | boolean).
881
- * - Persist merged options on the command instance and pass to subcommands.
882
- * - Execute {@link getDotenv} and optional post-hook.
883
- * - Either forward to the default `cmd` subcommand or execute `--command`.
884
- *
885
- * @param context - See {@link PreSubHookContext}.
886
- * @returns An async hook suitable for Commander’s `preSubcommand`.
887
- *
888
- * @example `program.hook('preSubcommand', makePreSubcommandHook(ctx));`
889
- */ const makePreSubcommandHook = ({ logger, preHook, postHook, defaults }) => async (thisCommand) => {
890
- // Get parent command GetDotenvCliOptions.
891
- const parentGetDotenvCliOptions = process.env.getDotenvCliOptions
892
- ? JSON.parse(process.env.getDotenvCliOptions)
893
- : undefined;
894
- // Get raw CLI options from commander.
895
- const rawCliOptions = thisCommand.opts();
896
- // Extract current GetDotenvCliOptions from raw CLI options.
897
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, scripts, shellOff, ...rawCliOptionsRest } = rawCliOptions;
898
- const currentGetDotenvCliOptions = rawCliOptionsRest;
899
- if (scripts)
900
- currentGetDotenvCliOptions.scripts = JSON.parse(scripts);
901
- // Merge current & parent GetDotenvCliOptions (parent < current).
902
- const mergedGetDotenvCliOptions = defaultsDeep((parentGetDotenvCliOptions ?? {}), currentGetDotenvCliOptions);
903
- // Resolve flags using defaults + current + exclude-all toggles.
904
- setOptionalFlag(mergedGetDotenvCliOptions, 'debug', resolveExclusion(mergedGetDotenvCliOptions.debug, debugOff, defaults.debug));
905
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeDynamic', resolveExclusionAll(mergedGetDotenvCliOptions.excludeDynamic, excludeDynamicOff, defaults.excludeDynamic, excludeAll, excludeAllOff));
906
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeEnv', resolveExclusionAll(mergedGetDotenvCliOptions.excludeEnv, excludeEnvOff, defaults.excludeEnv, excludeAll, excludeAllOff));
907
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludeGlobal', resolveExclusionAll(mergedGetDotenvCliOptions.excludeGlobal, excludeGlobalOff, defaults.excludeGlobal, excludeAll, excludeAllOff));
908
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludePrivate', resolveExclusionAll(mergedGetDotenvCliOptions.excludePrivate, excludePrivateOff, defaults.excludePrivate, excludeAll, excludeAllOff));
909
- setOptionalFlag(mergedGetDotenvCliOptions, 'excludePublic', resolveExclusionAll(mergedGetDotenvCliOptions.excludePublic, excludePublicOff, defaults.excludePublic, excludeAll, excludeAllOff));
910
- setOptionalFlag(mergedGetDotenvCliOptions, 'log', resolveExclusion(mergedGetDotenvCliOptions.log, logOff, defaults.log));
911
- setOptionalFlag(mergedGetDotenvCliOptions, 'loadProcess', resolveExclusion(mergedGetDotenvCliOptions.loadProcess, loadProcessOff, defaults.loadProcess));
912
- // Normalize shell for predictability: explicit default shell per OS.
913
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
914
- let resolvedShell = mergedGetDotenvCliOptions.shell;
915
- if (shellOff)
916
- resolvedShell = false;
917
- else if (resolvedShell === true || resolvedShell === undefined) {
918
- resolvedShell = defaultShell;
2813
+ * Ensure a set of lines exist (exact match) in a file. Creates the file
2814
+ * when missing. Returns whether it was created or changed.
2815
+ */
2816
+ const ensureLines = async (filePath, lines) => {
2817
+ const exists = await fs.pathExists(filePath);
2818
+ const current = exists ? await fs.readFile(filePath, 'utf-8') : '';
2819
+ const curLines = current.split(/\r?\n/);
2820
+ const have = new Set(curLines.filter((l) => l.length > 0));
2821
+ let mutated = false;
2822
+ for (const l of lines) {
2823
+ if (!have.has(l)) {
2824
+ curLines.push(l);
2825
+ have.add(l);
2826
+ mutated = true;
2827
+ }
919
2828
  }
920
- else if (typeof resolvedShell !== 'string' &&
921
- typeof defaults.shell === 'string') {
922
- resolvedShell = defaults.shell;
2829
+ // Normalize to LF and ensure trailing newline
2830
+ const next = curLines.filter((l) => l.length > 0).join('\n') + '\n';
2831
+ if (!exists) {
2832
+ await writeFile(filePath, next);
2833
+ return { created: true, changed: true };
923
2834
  }
924
- mergedGetDotenvCliOptions.shell = resolvedShell;
925
- if (mergedGetDotenvCliOptions.debug && parentGetDotenvCliOptions) {
926
- logger.debug('\n*** parent command GetDotenvCliOptions ***\n', parentGetDotenvCliOptions);
2835
+ if (mutated) {
2836
+ await fs.writeFile(filePath, next, 'utf-8');
2837
+ return { created: false, changed: true };
927
2838
  }
928
- if (mergedGetDotenvCliOptions.debug)
929
- logger.debug('\n*** current command raw options ***\n', rawCliOptions);
930
- if (mergedGetDotenvCliOptions.debug)
931
- logger.debug('\n*** merged GetDotenvCliOptions ***\n', {
932
- mergedGetDotenvCliOptions,
2839
+ return { created: false, changed: false };
2840
+ };
2841
+
2842
+ // Templates root used by the scaffolder
2843
+ const TEMPLATES_ROOT = path.resolve('templates');
2844
+
2845
+ const planConfigCopies = ({ format, withLocal, destRoot, }) => {
2846
+ const copies = [];
2847
+ if (format === 'json') {
2848
+ copies.push({
2849
+ src: path.join(TEMPLATES_ROOT, 'config', 'json', 'public', 'getdotenv.config.json'),
2850
+ dest: path.join(destRoot, 'getdotenv.config.json'),
933
2851
  });
934
- // Execute pre-hook.
935
- if (preHook) {
936
- await preHook(mergedGetDotenvCliOptions);
937
- if (mergedGetDotenvCliOptions.debug)
938
- logger.debug('\n*** GetDotenvCliOptions after pre-hook ***\n', mergedGetDotenvCliOptions);
939
- }
940
- // Persist GetDotenvCliOptions in command for subcommand access.
941
- thisCommand.getDotenvCliOptions = mergedGetDotenvCliOptions;
942
- // Execute getdotenv.
943
- const dotenv = await getDotenv(getDotenvCliOptions2Options(mergedGetDotenvCliOptions));
944
- if (mergedGetDotenvCliOptions.debug)
945
- logger.debug('\n*** getDotenv output ***\n', dotenv);
946
- // Execute post-hook.
947
- if (postHook)
948
- await postHook(dotenv);
949
- // Execute command.
950
- const args = thisCommand.args ?? [];
951
- const isCommand = typeof command === 'string' && command.length > 0;
952
- if (isCommand && args.length > 0) {
953
- const lr = logger;
954
- (lr.error ?? lr.log)(`--command option conflicts with cmd subcommand.`);
955
- process.exit(0);
2852
+ if (withLocal) {
2853
+ copies.push({
2854
+ src: path.join(TEMPLATES_ROOT, 'config', 'json', 'local', 'getdotenv.config.local.json'),
2855
+ dest: path.join(destRoot, 'getdotenv.config.local.json'),
2856
+ });
2857
+ }
956
2858
  }
957
- if (typeof command === 'string' && command.length > 0) {
958
- const cmd = resolveCommand(mergedGetDotenvCliOptions.scripts, command);
959
- if (mergedGetDotenvCliOptions.debug)
960
- logger.debug('\n*** command ***\n', cmd);
961
- const envSafe = {
962
- ...mergedGetDotenvCliOptions,
963
- };
964
- delete envSafe.logger;
965
- await execaCommand(cmd, {
966
- env: {
967
- ...process.env,
968
- getDotenvCliOptions: JSON.stringify(envSafe),
969
- },
970
- shell: resolveShell(mergedGetDotenvCliOptions.scripts, command, mergedGetDotenvCliOptions.shell),
971
- stdio: 'inherit',
2859
+ else if (format === 'yaml') {
2860
+ copies.push({
2861
+ src: path.join(TEMPLATES_ROOT, 'config', 'yaml', 'public', 'getdotenv.config.yaml'),
2862
+ dest: path.join(destRoot, 'getdotenv.config.yaml'),
2863
+ });
2864
+ if (withLocal) {
2865
+ copies.push({
2866
+ src: path.join(TEMPLATES_ROOT, 'config', 'yaml', 'local', 'getdotenv.config.local.yaml'),
2867
+ dest: path.join(destRoot, 'getdotenv.config.local.yaml'),
2868
+ });
2869
+ }
2870
+ }
2871
+ else if (format === 'js') {
2872
+ copies.push({
2873
+ src: path.join(TEMPLATES_ROOT, 'config', 'js', 'getdotenv.config.js'),
2874
+ dest: path.join(destRoot, 'getdotenv.config.js'),
2875
+ });
2876
+ }
2877
+ else {
2878
+ copies.push({
2879
+ src: path.join(TEMPLATES_ROOT, 'config', 'ts', 'getdotenv.config.ts'),
2880
+ dest: path.join(destRoot, 'getdotenv.config.ts'),
972
2881
  });
973
2882
  }
2883
+ return copies;
2884
+ };
2885
+ const planCliCopies = ({ cliName, destRoot, }) => {
2886
+ const subs = { __CLI_NAME__: cliName };
2887
+ const base = path.join(destRoot, 'src', 'cli', cliName);
2888
+ return [
2889
+ {
2890
+ src: path.join(TEMPLATES_ROOT, 'cli', 'ts', 'index.ts'),
2891
+ dest: path.join(base, 'index.ts'),
2892
+ subs,
2893
+ },
2894
+ {
2895
+ src: path.join(TEMPLATES_ROOT, 'cli', 'ts', 'plugins', 'hello.ts'),
2896
+ dest: path.join(base, 'plugins', 'hello.ts'),
2897
+ subs,
2898
+ },
2899
+ ];
974
2900
  };
975
2901
 
976
2902
  /**
977
- * Generate a Commander CLI Command for get-dotenv. * Orchestration only: delegates building and lifecycle hooks.
978
- */
979
- const generateGetDotenvCli = async (customOptions) => {
980
- const options = await resolveGetDotenvCliGenerateOptions(customOptions);
981
- const program = createRootCommand(options);
982
- const defaults = {};
983
- if (options.debug !== undefined)
984
- defaults.debug = options.debug;
985
- if (options.excludeDynamic !== undefined)
986
- defaults.excludeDynamic = options.excludeDynamic;
987
- if (options.excludeEnv !== undefined)
988
- defaults.excludeEnv = options.excludeEnv;
989
- if (options.excludeGlobal !== undefined)
990
- defaults.excludeGlobal = options.excludeGlobal;
991
- if (options.excludePrivate !== undefined)
992
- defaults.excludePrivate = options.excludePrivate;
993
- if (options.excludePublic !== undefined)
994
- defaults.excludePublic = options.excludePublic;
995
- if (options.loadProcess !== undefined)
996
- defaults.loadProcess = options.loadProcess;
997
- if (options.log !== undefined)
998
- defaults.log = options.log;
999
- if (options.scripts !== undefined)
1000
- defaults.scripts = options.scripts;
1001
- if (options.shell !== undefined)
1002
- defaults.shell = options.shell;
1003
- const ctx = {
1004
- logger: options.logger,
1005
- defaults,
1006
- ...(options.preHook ? { preHook: options.preHook } : {}),
1007
- ...(options.postHook ? { postHook: options.postHook } : {}),
1008
- };
1009
- program.hook('preSubcommand', makePreSubcommandHook(ctx));
1010
- return program;
2903
+ * Determine whether the current environment should be treated as non-interactive.
2904
+ * CI heuristics include: CI, GITHUB_ACTIONS, BUILDKITE, TEAMCITY_VERSION, TF_BUILD.
2905
+ */
2906
+ const isNonInteractive = () => {
2907
+ const ciLike = process.env.CI ||
2908
+ process.env.GITHUB_ACTIONS ||
2909
+ process.env.BUILDKITE ||
2910
+ process.env.TEAMCITY_VERSION ||
2911
+ process.env.TF_BUILD;
2912
+ return Boolean(ciLike) || !(stdin.isTTY && stdout.isTTY);
2913
+ };
2914
+ const promptDecision = async (filePath, logger, rl) => {
2915
+ logger.log(`File exists: ${filePath}\nChoose: [o]verwrite, [e]xample, [s]kip, [O]verwrite All, [E]xample All, [S]kip All`);
2916
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2917
+ while (true) {
2918
+ const a = (await rl.question('> ')).trim();
2919
+ const valid = ['o', 'e', 's', 'O', 'E', 'S'];
2920
+ if (valid.includes(a))
2921
+ return a;
2922
+ logger.log('Please enter one of: o e s O E S');
2923
+ }
1011
2924
  };
1012
2925
 
1013
- const program = await generateGetDotenvCli({
1014
- importMetaUrl: import.meta.url,
2926
+ /**
2927
+ * Requirements: Init scaffolding plugin with collision flow and CI detection.
2928
+ * Note: Large file scheduled for decomposition; tracked in stan.todo.md.
2929
+ */
2930
+ const initPlugin = (opts = {}) => definePlugin({
2931
+ id: 'init',
2932
+ setup(cli) {
2933
+ const logger = opts.logger ?? console;
2934
+ const cmd = cli
2935
+ .ns('init')
2936
+ .description('Scaffold getdotenv config files and a host-based CLI skeleton.')
2937
+ .argument('[dest]', 'destination path (default: ./)', '.')
2938
+ .option('--config-format <format>', 'config format: json|yaml|js|ts', 'json')
2939
+ .option('--with-local', 'include .local config variant')
2940
+ .option('--dynamic', 'include dynamic examples (JS/TS configs)')
2941
+ .option('--cli-name <string>', 'CLI name for skeleton and tokens')
2942
+ .option('--force', 'overwrite all existing files')
2943
+ .option('--yes', 'skip all collisions (no overwrite)')
2944
+ .action(async (destArg) => {
2945
+ // Read options directly from the captured command instance.
2946
+ // Cast to a plain record to satisfy exact-optional and lint safety.
2947
+ const o = cmd.opts() ?? {};
2948
+ const destRel = typeof destArg === 'string' && destArg.length > 0 ? destArg : '.';
2949
+ const cwd = process.cwd();
2950
+ const destRoot = path.resolve(cwd, destRel);
2951
+ const formatInput = o.configFormat;
2952
+ const formatRaw = typeof formatInput === 'string'
2953
+ ? formatInput.toLowerCase()
2954
+ : 'json';
2955
+ const format = (['json', 'yaml', 'js', 'ts'].includes(formatRaw)
2956
+ ? formatRaw
2957
+ : 'json');
2958
+ const withLocal = !!o.withLocal;
2959
+ // dynamic flag reserved for future template variants; present for UX compatibility
2960
+ void o.dynamic;
2961
+ // CLI name default: --cli-name | basename(dest) | 'mycli'
2962
+ const cliName = (typeof o.cliName === 'string' && o.cliName.length > 0
2963
+ ? o.cliName
2964
+ : path.basename(destRoot) || 'mycli') || 'mycli';
2965
+ // Precedence: --force > --yes > auto-detect(non-interactive => yes)
2966
+ const force = !!o.force;
2967
+ const yes = !!o.yes || (!force && isNonInteractive());
2968
+ // Build copy plan
2969
+ const cfgCopies = planConfigCopies({ format, withLocal, destRoot });
2970
+ const cliCopies = planCliCopies({ cliName, destRoot });
2971
+ const copies = [...cfgCopies, ...cliCopies];
2972
+ // Interactive state
2973
+ let globalDecision;
2974
+ const rl = createInterface({ input: stdin, output: stdout });
2975
+ try {
2976
+ for (const item of copies) {
2977
+ const exists = await fs.pathExists(item.dest);
2978
+ if (!exists) {
2979
+ const subs = item.subs ?? {};
2980
+ await copyTextFile(item.src, item.dest, subs);
2981
+ logger.log(`Created ${path.relative(cwd, item.dest)}`);
2982
+ continue;
2983
+ }
2984
+ // Collision
2985
+ if (force) {
2986
+ const subs = item.subs ?? {};
2987
+ await copyTextFile(item.src, item.dest, subs);
2988
+ logger.log(`Overwrote ${path.relative(cwd, item.dest)}`);
2989
+ continue;
2990
+ }
2991
+ if (yes) {
2992
+ logger.log(`Skipped ${path.relative(cwd, item.dest)}`);
2993
+ continue;
2994
+ }
2995
+ let decision = globalDecision;
2996
+ if (!decision) {
2997
+ const a = await promptDecision(item.dest, logger, rl);
2998
+ if (a === 'O') {
2999
+ globalDecision = 'overwrite';
3000
+ decision = 'overwrite';
3001
+ }
3002
+ else if (a === 'E') {
3003
+ globalDecision = 'example';
3004
+ decision = 'example';
3005
+ }
3006
+ else if (a === 'S') {
3007
+ globalDecision = 'skip';
3008
+ decision = 'skip';
3009
+ }
3010
+ else {
3011
+ decision =
3012
+ a === 'o' ? 'overwrite' : a === 'e' ? 'example' : 'skip';
3013
+ }
3014
+ }
3015
+ if (decision === 'overwrite') {
3016
+ const subs = item.subs ?? {};
3017
+ await copyTextFile(item.src, item.dest, subs);
3018
+ logger.log(`Overwrote ${path.relative(cwd, item.dest)}`);
3019
+ }
3020
+ else if (decision === 'example') {
3021
+ const destEx = `${item.dest}.example`;
3022
+ const subs = item.subs ?? {};
3023
+ await copyTextFile(item.src, destEx, subs);
3024
+ logger.log(`Wrote example ${path.relative(cwd, destEx)}`);
3025
+ }
3026
+ else {
3027
+ logger.log(`Skipped ${path.relative(cwd, item.dest)}`);
3028
+ }
3029
+ }
3030
+ // Ensure .gitignore includes local config patterns.
3031
+ const giPath = path.join(destRoot, '.gitignore');
3032
+ const { created, changed } = await ensureLines(giPath, [
3033
+ 'getdotenv.config.local.*',
3034
+ '*.local',
3035
+ ]);
3036
+ if (created) {
3037
+ logger.log(`Created ${path.relative(cwd, giPath)}`);
3038
+ }
3039
+ else if (changed) {
3040
+ logger.log(`Updated ${path.relative(cwd, giPath)}`);
3041
+ }
3042
+ }
3043
+ finally {
3044
+ rl.close();
3045
+ }
3046
+ });
3047
+ },
1015
3048
  });
3049
+
3050
+ // Shipped CLI rebased on plugin-first host.
3051
+ const program = new GetDotenvCli('getdotenv')
3052
+ .attachRootOptions({ loadProcess: false })
3053
+ .use(cmdPlugin({ asDefault: true, optionAlias: '-c, --cmd <command...>' }))
3054
+ .use(batchPlugin())
3055
+ .use(awsPlugin())
3056
+ .use(demoPlugin())
3057
+ .use(initPlugin())
3058
+ .passOptions({ loadProcess: false });
1016
3059
  await program.parseAsync();