@karmaniverous/get-dotenv 5.2.6 → 6.0.0-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +106 -70
  2. package/dist/cliHost.d.ts +232 -226
  3. package/dist/cliHost.mjs +777 -545
  4. package/dist/config.d.ts +7 -2
  5. package/dist/env-overlay.d.ts +21 -9
  6. package/dist/env-overlay.mjs +14 -19
  7. package/dist/getdotenv.cli.mjs +1366 -1163
  8. package/dist/index.d.ts +415 -242
  9. package/dist/index.mjs +1364 -1414
  10. package/dist/plugins-aws.d.ts +149 -94
  11. package/dist/plugins-aws.mjs +307 -195
  12. package/dist/plugins-batch.d.ts +153 -99
  13. package/dist/plugins-batch.mjs +277 -95
  14. package/dist/plugins-cmd.d.ts +140 -94
  15. package/dist/plugins-cmd.mjs +636 -502
  16. package/dist/plugins-demo.d.ts +140 -94
  17. package/dist/plugins-demo.mjs +237 -46
  18. package/dist/plugins-init.d.ts +140 -94
  19. package/dist/plugins-init.mjs +129 -12
  20. package/dist/plugins.d.ts +166 -103
  21. package/dist/plugins.mjs +977 -840
  22. package/package.json +15 -53
  23. package/templates/cli/ts/plugins/hello.ts +27 -6
  24. package/templates/config/js/getdotenv.config.js +1 -1
  25. package/templates/config/ts/getdotenv.config.ts +9 -2
  26. package/dist/cliHost.cjs +0 -1875
  27. package/dist/cliHost.d.cts +0 -409
  28. package/dist/cliHost.d.mts +0 -409
  29. package/dist/config.cjs +0 -252
  30. package/dist/config.d.cts +0 -55
  31. package/dist/config.d.mts +0 -55
  32. package/dist/env-overlay.cjs +0 -163
  33. package/dist/env-overlay.d.cts +0 -50
  34. package/dist/env-overlay.d.mts +0 -50
  35. package/dist/index.cjs +0 -4140
  36. package/dist/index.d.cts +0 -457
  37. package/dist/index.d.mts +0 -457
  38. package/dist/plugins-aws.cjs +0 -667
  39. package/dist/plugins-aws.d.cts +0 -158
  40. package/dist/plugins-aws.d.mts +0 -158
  41. package/dist/plugins-batch.cjs +0 -616
  42. package/dist/plugins-batch.d.cts +0 -180
  43. package/dist/plugins-batch.d.mts +0 -180
  44. package/dist/plugins-cmd.cjs +0 -1113
  45. package/dist/plugins-cmd.d.cts +0 -178
  46. package/dist/plugins-cmd.d.mts +0 -178
  47. package/dist/plugins-demo.cjs +0 -307
  48. package/dist/plugins-demo.d.cts +0 -158
  49. package/dist/plugins-demo.d.mts +0 -158
  50. package/dist/plugins-init.cjs +0 -289
  51. package/dist/plugins-init.d.cts +0 -162
  52. package/dist/plugins-init.d.mts +0 -162
  53. package/dist/plugins.cjs +0 -2283
  54. package/dist/plugins.d.cts +0 -210
  55. package/dist/plugins.d.mts +0 -210
package/dist/index.d.ts CHANGED
@@ -1,22 +1,6 @@
1
- import { Command } from 'commander';
2
-
3
- /** src/cliCore/spawnEnv.ts
4
- * Build a sanitized environment bag for child processes.
5
- *
6
- * Requirements addressed:
7
- * - Provide a single helper (buildSpawnEnv) to normalize/dedupe child env.
8
- * - Drop undefined values (exactOptional semantics).
9
- * - On Windows, dedupe keys case-insensitively and prefer the last value,
10
- * preserving the latest key's casing. Ensure HOME fallback from USERPROFILE.
11
- * Normalize TMP/TEMP consistency when either is present.
12
- * - On POSIX, keep keys as-is; when a temp dir key is present (TMPDIR/TMP/TEMP),
13
- * ensure TMPDIR exists for downstream consumers that expect it.
14
- *
15
- * Adapter responsibility: pure mapping; no business logic.
16
- */
17
- type SpawnEnv = Readonly<Partial<Record<string, string>>>;
18
- /** Build a sanitized env for child processes from base + overlay. */
19
- declare const buildSpawnEnv: (base?: NodeJS.ProcessEnv, overlay?: Record<string, string | undefined>) => SpawnEnv;
1
+ import { z, ZodObject } from 'zod';
2
+ export { z } from 'zod';
3
+ import { Command, Option } from 'commander';
20
4
 
21
5
  /**
22
6
  * Minimal root options shape shared by CLI and generator layers.
@@ -64,8 +48,92 @@ type RootOptionsShape = {
64
48
  */
65
49
  type ScriptsTable<TShell extends string | boolean = string | boolean> = Record<string, string | {
66
50
  cmd: string;
67
- shell?: TShell;
51
+ shell?: TShell | undefined;
68
52
  }>;
53
+ /**
54
+ * Identity helper to define a scripts table while preserving a concrete TShell
55
+ * type parameter in downstream inference.
56
+ */
57
+ declare const defineScripts: <TShell extends string | boolean>() => <T extends ScriptsTable<TShell>>(t: T) => T;
58
+
59
+ /** Build a sanitized env for child processes from base + overlay. */
60
+ declare const buildSpawnEnv: (base?: NodeJS.ProcessEnv, overlay?: Record<string, string | undefined>) => NodeJS.ProcessEnv;
61
+
62
+ declare const getDotenvCliOptionsSchemaResolved: z.ZodObject<{
63
+ defaultEnv: z.ZodOptional<z.ZodString>;
64
+ dotenvToken: z.ZodOptional<z.ZodString>;
65
+ dynamicPath: z.ZodOptional<z.ZodString>;
66
+ dynamic: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
67
+ env: z.ZodOptional<z.ZodString>;
68
+ excludeDynamic: z.ZodOptional<z.ZodBoolean>;
69
+ excludeEnv: z.ZodOptional<z.ZodBoolean>;
70
+ excludeGlobal: z.ZodOptional<z.ZodBoolean>;
71
+ excludePrivate: z.ZodOptional<z.ZodBoolean>;
72
+ excludePublic: z.ZodOptional<z.ZodBoolean>;
73
+ loadProcess: z.ZodOptional<z.ZodBoolean>;
74
+ log: z.ZodOptional<z.ZodBoolean>;
75
+ logger: z.ZodOptional<z.ZodUnknown>;
76
+ outputPath: z.ZodOptional<z.ZodString>;
77
+ privateToken: z.ZodOptional<z.ZodString>;
78
+ debug: z.ZodOptional<z.ZodBoolean>;
79
+ strict: z.ZodOptional<z.ZodBoolean>;
80
+ capture: z.ZodOptional<z.ZodBoolean>;
81
+ trace: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodArray<z.ZodString>]>>;
82
+ redact: z.ZodOptional<z.ZodBoolean>;
83
+ warnEntropy: z.ZodOptional<z.ZodBoolean>;
84
+ entropyThreshold: z.ZodOptional<z.ZodNumber>;
85
+ entropyMinLength: z.ZodOptional<z.ZodNumber>;
86
+ entropyWhitelist: z.ZodOptional<z.ZodArray<z.ZodString>>;
87
+ redactPatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
88
+ paths: z.ZodOptional<z.ZodString>;
89
+ pathsDelimiter: z.ZodOptional<z.ZodString>;
90
+ pathsDelimiterPattern: z.ZodOptional<z.ZodString>;
91
+ scripts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
92
+ shell: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
93
+ vars: z.ZodOptional<z.ZodString>;
94
+ varsAssignor: z.ZodOptional<z.ZodString>;
95
+ varsAssignorPattern: z.ZodOptional<z.ZodString>;
96
+ varsDelimiter: z.ZodOptional<z.ZodString>;
97
+ varsDelimiterPattern: z.ZodOptional<z.ZodString>;
98
+ }, z.core.$strip>;
99
+
100
+ type Scripts = ScriptsTable;
101
+ /**
102
+ * Canonical CLI options type derived from the Zod schema output.
103
+ * Includes CLI-only flags (debug/strict/capture/trace/redaction/entropy),
104
+ * stringly paths/vars, and inherited programmatic fields (minus normalized
105
+ * shapes that are handled by resolution).
106
+ */
107
+ type GetDotenvCliOptions = z.output<typeof getDotenvCliOptionsSchemaResolved> & {
108
+ /**
109
+ * Compile-only overlay for DX: logger narrowed from unknown.
110
+ */
111
+ logger?: Logger;
112
+ /**
113
+ * Compile-only overlay for DX: scripts narrowed from Record\<string, unknown\>.
114
+ */
115
+ scripts?: Scripts;
116
+ };
117
+
118
+ declare const getDotenvOptionsSchemaResolved: z.ZodObject<{
119
+ defaultEnv: z.ZodOptional<z.ZodString>;
120
+ dotenvToken: z.ZodOptional<z.ZodString>;
121
+ dynamicPath: z.ZodOptional<z.ZodString>;
122
+ dynamic: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
123
+ env: z.ZodOptional<z.ZodString>;
124
+ excludeDynamic: z.ZodOptional<z.ZodBoolean>;
125
+ excludeEnv: z.ZodOptional<z.ZodBoolean>;
126
+ excludeGlobal: z.ZodOptional<z.ZodBoolean>;
127
+ excludePrivate: z.ZodOptional<z.ZodBoolean>;
128
+ excludePublic: z.ZodOptional<z.ZodBoolean>;
129
+ loadProcess: z.ZodOptional<z.ZodBoolean>;
130
+ log: z.ZodOptional<z.ZodBoolean>;
131
+ logger: z.ZodOptional<z.ZodUnknown>;
132
+ outputPath: z.ZodOptional<z.ZodString>;
133
+ paths: z.ZodOptional<z.ZodArray<z.ZodString>>;
134
+ privateToken: z.ZodOptional<z.ZodString>;
135
+ vars: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
136
+ }, z.core.$strip>;
69
137
 
70
138
  type RootOptionsShapeCompat = Omit<RootOptionsShape, 'vars' | 'paths'> & {
71
139
  vars?: string | Record<string, string | undefined>;
@@ -73,7 +141,9 @@ type RootOptionsShapeCompat = Omit<RootOptionsShape, 'vars' | 'paths'> & {
73
141
  };
74
142
  /**
75
143
  * A minimal representation of an environment key/value mapping.
76
- * Values may be `undefined` to represent "unset". */ type ProcessEnv = Record<string, string | undefined>;
144
+ * Values may be `undefined` to represent "unset".
145
+ */
146
+ type ProcessEnv = Record<string, string | undefined>;
77
147
  /**
78
148
  * Dynamic variable function signature. Receives the current expanded variables
79
149
  * and the selected environment (if any), and returns either a string to set
@@ -83,101 +153,72 @@ type GetDotenvDynamicFunction = (vars: ProcessEnv, env: string | undefined) => s
83
153
  type GetDotenvDynamic = Record<string, GetDotenvDynamicFunction | ReturnType<GetDotenvDynamicFunction>>;
84
154
  type Logger = Record<string, (...args: unknown[]) => void> | typeof console;
85
155
  /**
86
- * Helper to define a dynamic map with strong inference.
87
- *
88
- * @example
89
- * const dynamic = defineDynamic(\{ KEY: (\{ FOO = '' \}) =\> FOO + '-x' \});
90
- */
91
- declare const defineDynamic: <T extends GetDotenvDynamic>(d: T) => T;
92
- /**
93
- * Options passed programmatically to `getDotenv`.
156
+ * Canonical programmatic options type (schema-derived).
157
+ * This type is the single source of truth for programmatic options.
94
158
  */
95
- interface GetDotenvOptions {
96
- /**
97
- * default target environment (used if `env` is not provided)
98
- */
99
- defaultEnv?: string;
159
+ type GetDotenvOptions = z.output<typeof getDotenvOptionsSchemaResolved> & {
100
160
  /**
101
- * token indicating a dotenv file
161
+ * Compile-time overlay: narrowed logger for DX (schema stores unknown).
102
162
  */
103
- dotenvToken: string;
104
- /**
105
- * path to JS/TS module default-exporting an object keyed to dynamic variable functions
106
- */
107
- dynamicPath?: string;
163
+ logger?: Logger;
108
164
  /**
109
- * Programmatic dynamic variables map. When provided, this takes precedence
110
- * over {@link GetDotenvOptions.dynamicPath}.
165
+ * Compile-time overlay: narrowed dynamic map for DX (schema stores unknown).
111
166
  */
112
167
  dynamic?: GetDotenvDynamic;
113
- /**
114
- * target environment
115
- */
116
- env?: string;
117
- /**
118
- * exclude dynamic variables from loading
119
- */
120
- excludeDynamic?: boolean;
121
- /**
122
- * exclude environment-specific variables from loading
123
- */
124
- excludeEnv?: boolean;
125
- /**
126
- * exclude global variables from loading
127
- */
128
- excludeGlobal?: boolean;
129
- /**
130
- * exclude private variables from loading
131
- */
132
- excludePrivate?: boolean;
133
- /**
134
- * exclude public variables from loading
135
- */
136
- excludePublic?: boolean;
137
- /**
138
- * load dotenv variables to `process.env`
139
- */
168
+ };
169
+ /**
170
+ * Vars-aware dynamic helpers (compile-time DX).
171
+ * DynamicFn: receive the current expanded variables and optional env.
172
+ */
173
+ type DynamicFn<Vars extends Record<string, string | undefined>> = (vars: Vars, env?: string) => string | undefined;
174
+ type DynamicMap<Vars extends Record<string, string | undefined>> = Record<string, DynamicFn<Vars> | ReturnType<DynamicFn<Vars>>>;
175
+ /**
176
+ * Helper to define a dynamic map with strong inference (Vars-aware).
177
+ *
178
+ * Overload A (preferred): bind Vars to your intended key set for improved inference.
179
+ */
180
+ declare function defineDynamic<Vars extends Record<string, string | undefined>, T extends DynamicMap<Vars>>(d: T): T;
181
+ /**
182
+ * Overload B (backward-compatible): generic over legacy GetDotenvDynamic.
183
+ *
184
+ * Accepts legacy GetDotenvDynamic without Vars binding.
185
+ */
186
+ declare function defineDynamic<T extends GetDotenvDynamic>(d: T): T;
187
+ /**
188
+ * Typed config shape and builder for authoring JS/TS getdotenv config files.
189
+ *
190
+ * Compile-time only; the runtime loader remains schema-driven.
191
+ */
192
+ type GetDotenvConfig<Vars extends ProcessEnv, Env extends string = string> = {
193
+ dotenvToken?: string;
194
+ privateToken?: string;
195
+ paths?: string | string[];
140
196
  loadProcess?: boolean;
141
- /**
142
- * log loaded dotenv variables to `logger`
143
- */
144
197
  log?: boolean;
145
- /**
146
- * logger object (defaults to console)
147
- */
148
- logger?: Logger;
149
- /**
150
- * if populated, writes consolidated dotenv file to this path (follows dotenvExpand rules)
151
- */
152
- outputPath?: string;
153
- /**
154
- * array of input directory paths
155
- */
156
- paths?: string[];
157
- /**
158
- * filename token indicating private variables
159
- */
160
- privateToken?: string;
161
- /**
162
- * explicit variables to include
163
- */
164
- vars?: ProcessEnv;
165
- /**
166
- * Reserved: config loader flag (no-op).
167
- * The plugin-first host and generator paths already use the config
168
- * loader/overlay pipeline unconditionally (no-op when no config files
169
- * are present). This flag is accepted for forward compatibility but
170
- * currently has no effect.
171
- */
172
- useConfigLoader?: boolean;
173
- }
198
+ shell?: string | boolean;
199
+ scripts?: Scripts;
200
+ requiredKeys?: string[];
201
+ schema?: unknown;
202
+ vars?: Vars;
203
+ envVars?: Record<Env, Partial<Vars>>;
204
+ dynamic?: DynamicMap<Vars>;
205
+ plugins?: Record<string, unknown>;
206
+ };
207
+ declare function defineGetDotenvConfig<Vars extends ProcessEnv, Env extends string = string, T extends GetDotenvConfig<Vars, Env> = GetDotenvConfig<Vars, Env>>(cfg: T): T;
208
+ /**
209
+ * Compile-time helper to derive the Vars shape from a typed getdotenv config document.
210
+ */
211
+ type InferGetDotenvVarsFromConfig<T> = T extends {
212
+ vars?: infer V;
213
+ } ? V extends Record<string, string | undefined> ? V : never : never;
174
214
  /**
175
- * Converts programmatic CLI options to `getDotenv` options. *
176
- * @param cliOptions - CLI options. Defaults to `{}`.
215
+ * Converts programmatic CLI options to `getDotenv` options.
177
216
  *
178
- * @returns `getDotenv` options.
217
+ * Accepts "stringly" CLI inputs for vars/paths and normalizes them into
218
+ * the programmatic shape. Preserves exactOptionalPropertyTypes semantics by
219
+ * omitting keys when undefined.
179
220
  */
180
- declare const getDotenvCliOptions2Options: ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }: RootOptionsShapeCompat) => GetDotenvOptions;
221
+ declare const getDotenvCliOptions2Options: ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, debug: _debug, scripts: _scripts, ...rest }: RootOptionsShapeCompat) => GetDotenvOptions;
181
222
 
182
223
  /**
183
224
  * Recursively expands environment variables in a string. Variables may be
@@ -226,10 +267,12 @@ declare const dotenvExpand: (value: string | undefined, ref?: ProcessEnv) => str
226
267
  * When `progressive` is true, each expanded key becomes available for
227
268
  * subsequent expansions in the same object (left-to-right by object key order).
228
269
  */
229
- declare const dotenvExpandAll: (values?: ProcessEnv, options?: {
230
- ref?: ProcessEnv;
270
+ declare function dotenvExpandAll<T extends Record<string, string | undefined> | Readonly<Record<string, string | undefined>>>(values: T, options?: {
271
+ ref?: Record<string, string | undefined>;
231
272
  progressive?: boolean;
232
- }) => Record<string, string | undefined>;
273
+ }): Record<string, string | undefined> & {
274
+ [K in keyof T]: string | undefined;
275
+ };
233
276
  /**
234
277
  * Recursively expands environment variables in a string using `process.env` as
235
278
  * the expansion reference. Variables may be presented with optional default as
@@ -247,198 +290,328 @@ declare const dotenvExpandAll: (values?: ProcessEnv, options?: {
247
290
  */
248
291
  declare const dotenvExpandFromProcessEnv: (value: string | undefined) => string | undefined;
249
292
 
250
- type Scripts = Record<string, string | {
251
- cmd: string;
252
- shell?: string | boolean;
253
- }>;
254
293
  /**
255
- * Options passed programmatically to `getDotenvCli`.
294
+ * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
295
+ *
296
+ * @param options - `GetDotenvOptions` object
297
+ * @returns The combined parsed dotenv object.
298
+ * * @example Load from the project root with default tokens
299
+ * ```ts
300
+ * const vars = await getDotenv();
301
+ * console.log(vars.MY_SETTING);
302
+ * ```
303
+ *
304
+ * @example Load from multiple paths and a specific environment
305
+ * ```ts
306
+ * const vars = await getDotenv({
307
+ * env: 'dev',
308
+ * dotenvToken: '.testenv',
309
+ * privateToken: 'secret',
310
+ * paths: ['./', './packages/app'],
311
+ * });
312
+ * ```
313
+ *
314
+ * @example Use dynamic variables
315
+ * ```ts
316
+ * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
317
+ * const vars = await getDotenv({ dynamicPath: '.env.js' });
318
+ * ```
319
+ *
320
+ * @remarks
321
+ * - When {@link GetDotenvOptions | loadProcess} is true, the resulting variables are merged
322
+ * into `process.env` as a side effect.
323
+ * - When {@link GetDotenvOptions | outputPath} is provided, a consolidated dotenv file is written.
324
+ * The path is resolved after expansion, so it may reference previously loaded vars.
325
+ *
326
+ * @throws Error when a dynamic module is present but cannot be imported.
327
+ * @throws Error when an output path was requested but could not be resolved.
328
+ */
329
+ declare function getDotenv<Vars extends ProcessEnv = ProcessEnv>(options?: Partial<GetDotenvOptions>): Promise<Vars>;
330
+ declare function getDotenv<Vars extends ProcessEnv>(options: Partial<GetDotenvOptions> & {
331
+ vars: Vars;
332
+ }): Promise<ProcessEnv & Vars>;
333
+
334
+ /** src/types/deepReadonly.ts
335
+ * Utility DeepReadonly type for downstream DX.
336
+ * Compile-time only; no runtime footprint.
337
+ */
338
+ type DeepReadonly<T> = T extends (...args: unknown[]) => unknown ? T : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepReadonly<U>> : T extends Array<infer U> ? ReadonlyArray<DeepReadonly<U>> : T extends object ? {
339
+ readonly [K in keyof T]: DeepReadonly<T[K]>;
340
+ } : T;
341
+
342
+ /**
343
+ * Deeply interpolate string leaves against envRef.
344
+ * Arrays are not recursed into; they are returned unchanged.
345
+ *
346
+ * @typeParam T - Shape of the input value.
347
+ * @param value - Input value (object/array/primitive).
348
+ * @param envRef - Reference environment for interpolation.
349
+ * @returns A new value with string leaves interpolated.
256
350
  */
257
- interface GetDotenvCliOptions extends Omit<GetDotenvOptions, 'paths' | 'vars'> {
258
- /**
259
- * Logs CLI internals when true.
260
- */
261
- debug?: boolean;
351
+ declare const interpolateDeep: <T>(value: T, envRef: ProcessEnv) => T;
352
+
353
+ type ResolvedHelpConfig = Partial<GetDotenvCliOptions> & {
354
+ plugins: Record<string, unknown>;
355
+ };
356
+ /** Per-invocation context shared with plugins and actions. */
357
+ type GetDotenvCliCtx<TOptions extends GetDotenvOptions = GetDotenvOptions> = {
358
+ optionsResolved: TOptions;
359
+ dotenv: ProcessEnv;
360
+ plugins?: Record<string, unknown>;
361
+ pluginConfigs?: Record<string, unknown>;
362
+ };
363
+ declare const CTX_SYMBOL: unique symbol;
364
+ declare const OPTS_SYMBOL: unique symbol;
365
+ declare const HELP_HEADER_SYMBOL: unique symbol;
366
+ /**
367
+ * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
368
+ *
369
+ * Responsibilities:
370
+ * - Resolve options strictly and compute dotenv context (resolveAndLoad).
371
+ * - Expose a stable accessor for the current context (getCtx).
372
+ * - Provide a namespacing helper (ns).
373
+ * - Support composable plugins with parent → children install and afterResolve.
374
+ */
375
+ declare class GetDotenvCli$1<TOptions extends GetDotenvOptions = GetDotenvOptions> extends Command implements GetDotenvCliPublic<TOptions> {
376
+ /** Registered top-level plugins (composition happens via .use()) */
377
+ private _plugins;
378
+ /** One-time installation guard */
379
+ private _installed;
380
+ /** Optional header line to prepend in help output */
381
+ private [HELP_HEADER_SYMBOL];
382
+ /** Context/options stored under symbols (typed) */
383
+ private [CTX_SYMBOL]?;
384
+ private [OPTS_SYMBOL]?;
262
385
  /**
263
- * Strict mode: fail the run when env validation issues are detected
264
- * (schema or requiredKeys). Warns by default when false or unset.
386
+ * Create a subcommand using the same subclass, preserving helpers like
387
+ * dynamicOption on children.
265
388
  */
266
- strict?: boolean;
389
+ createCommand(name?: string): Command;
390
+ constructor(alias?: string);
267
391
  /**
268
- * Redaction (presentation): mask secret-like values in logs/trace.
392
+ * Resolve options (strict) and compute dotenv context.
393
+ * Stores the context on the instance under a symbol.
394
+ *
395
+ * Options:
396
+ * - opts.runAfterResolve (default true): when false, skips running plugin
397
+ * afterResolve hooks. Useful for top-level help rendering to avoid
398
+ * long-running side-effects while still evaluating dynamic help text.
269
399
  */
270
- redact?: boolean;
400
+ resolveAndLoad(customOptions?: Partial<TOptions>, opts?: {
401
+ runAfterResolve?: boolean;
402
+ }): Promise<GetDotenvCliCtx<TOptions>>;
271
403
  /**
272
- * Entropy warnings (presentation): emit once-per-key warnings for high-entropy values.
404
+ * Create a Commander Option that computes its description at help time.
405
+ * The returned Option may be configured (conflicts, default, parser) and
406
+ * added via addOption().
273
407
  */
274
- warnEntropy?: boolean;
275
- entropyThreshold?: number;
276
- entropyMinLength?: number;
277
- entropyWhitelist?: string[];
278
- redactPatterns?: string[];
408
+ createDynamicOption(flags: string, desc: (cfg: ResolvedHelpConfig & {
409
+ plugins: Record<string, unknown>;
410
+ }) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option;
411
+ createDynamicOption<TValue = unknown>(flags: string, desc: (cfg: ResolvedHelpConfig & {
412
+ plugins: Record<string, unknown>;
413
+ }) => string, parser: (value: string, previous?: TValue) => TValue, defaultValue?: TValue): Option;
279
414
  /**
280
- * When true, capture child stdout/stderr and re-emit after completion.
281
- * Useful for tests/CI. Default behavior is streaming via stdio: 'inherit'.
415
+ * Chainable helper mirroring .option(), but with a dynamic description.
416
+ * Equivalent to addOption(createDynamicOption(...)).
282
417
  */
283
- capture?: boolean;
418
+ dynamicOption(flags: string, desc: (cfg: ResolvedHelpConfig & {
419
+ plugins: Record<string, unknown>;
420
+ }) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): this;
284
421
  /**
285
- * A delimited string of paths to dotenv files.
422
+ * Evaluate dynamic descriptions for this command and all descendants using
423
+ * the provided resolved configuration. Mutates the Option.description in
424
+ * place so Commander help renders updated text.
286
425
  */
287
- paths?: string;
426
+ evaluateDynamicOptions(resolved: ResolvedHelpConfig): void;
288
427
  /**
289
- * A delimiter string with which to split `paths`. Only used if
290
- * `pathsDelimiterPattern` is not provided.
428
+ * Retrieve the current invocation context (if any).
291
429
  */
292
- pathsDelimiter?: string;
430
+ getCtx(): GetDotenvCliCtx<TOptions> | undefined;
293
431
  /**
294
- * A regular expression pattern with which to split `paths`. Supersedes
295
- * `pathsDelimiter`.
432
+ * Retrieve the merged root CLI options bag (if set by passOptions()).
433
+ * Downstream-safe: no generics required.
296
434
  */
297
- pathsDelimiterPattern?: string;
435
+ getOptions(): GetDotenvCliOptions | undefined;
436
+ /** Internal: set the merged root options bag for this run. */
437
+ _setOptionsBag(bag: GetDotenvCliOptions): void;
438
+ /** Convenience helper to create a namespaced subcommand. */
439
+ ns(name: string): Command;
298
440
  /**
299
- * Scripts that can be executed from the CLI, either individually or via the batch subcommand.
441
+ * Tag options added during the provided callback as 'app' for grouped help.
442
+ * Allows downstream apps to demarcate their root-level options.
300
443
  */
301
- scripts?: Scripts;
444
+ tagAppOptions<T>(fn: (root: Command) => T): T;
302
445
  /**
303
- * Determines how commands and scripts are executed. If `false` or
304
- * `undefined`, commands are executed as plain Javascript using the default
305
- * execa parser. If `true`, commands are executed using the default OS shell
306
- * parser. Otherwise the user may provide a specific shell string (e.g.
307
- * `/bin/bash`)
446
+ * Branding helper: set CLI name/description/version and optional help header.
447
+ * If version is omitted and importMetaUrl is provided, attempts to read the
448
+ * nearest package.json version (best-effort; non-fatal on failure).
308
449
  */
309
- shell?: string | boolean;
450
+ brand(args: {
451
+ name?: string;
452
+ description?: string;
453
+ version?: string;
454
+ importMetaUrl?: string;
455
+ helpHeader?: string;
456
+ }): Promise<this>;
310
457
  /**
311
- * A delimited string of key-value pairs declaratively specifying variables &
312
- * values to be loaded in addition to any dotenv files.
458
+ * Insert grouped plugin/app options between "Options" and "Commands" for
459
+ * hybrid ordering. Applies to root and any parent command.
313
460
  */
314
- vars?: string;
461
+ helpInformation(): string;
315
462
  /**
316
- * A string with which to split keys from values in `vars`. Only used if
317
- * `varsDelimiterPattern` is not provided.
463
+ * Public: tag an Option with a display group for help (root/app/plugin:<id>).
318
464
  */
319
- varsAssignor?: string;
465
+ setOptionGroup(opt: Option, group: string): void;
320
466
  /**
321
- * A regular expression pattern with which to split variable names from values
322
- * in `vars`. Supersedes `varsAssignor`.
467
+ * Register a plugin for installation (parent level).
468
+ * Installation occurs on first resolveAndLoad() (or explicit install()).
323
469
  */
324
- varsAssignorPattern?: string;
470
+ use(plugin: GetDotenvCliPlugin<TOptions>): this;
325
471
  /**
326
- * A string with which to split `vars` into key-value pairs. Only used if
327
- * `varsDelimiterPattern` is not provided.
472
+ * Install all registered plugins in parent children (pre-order).
473
+ * Runs only once per CLI instance.
328
474
  */
329
- varsDelimiter?: string;
475
+ install(): Promise<void>;
330
476
  /**
331
- * A regular expression pattern with which to split `vars` into key-value
332
- * pairs. Supersedes `varsDelimiter`.
477
+ * Run afterResolve hooks for all plugins (parent children).
333
478
  */
334
- varsDelimiterPattern?: string;
479
+ private _runAfterResolve;
335
480
  }
336
481
 
337
- /**
338
- * GetDotenv CLI Pre-hook Callback function type. Mutates inbound options &
339
- * executes side effects within the `getDotenv` context.
340
- */
341
- type GetDotenvCliPreHookCallback = (options: GetDotenvCliOptions) => Promise<void>;
342
- /**
343
- * GetDotenv CLI Post-hook Callback function type. Executes side effects within
344
- * the `getDotenv` context.
482
+ /** src/cliHost/definePlugin.ts
483
+ * Plugin contracts for the GetDotenv CLI host.
484
+ *
485
+ * This module exposes a structural public interface for the host that plugins
486
+ * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
487
+ * nominal class identity issues (private fields) in downstream consumers.
345
488
  */
346
- type GetDotenvCliPostHookCallback = (dotenv: ProcessEnv) => Promise<void>;
489
+
347
490
  /**
348
- * `generateGetDotenvCli` options. Defines local instance of the GetDotenv CLI and
349
- * sets defaults that can be overridden by local `getdotenv.config.json` in
350
- * projects that import the CLI.
491
+ * Structural public interface for the host exposed to plugins.
492
+ * - Extends Commander.Command so plugins can attach options/commands/hooks.
493
+ * - Adds host-specific helpers used by built-in plugins.
494
+ *
495
+ * Purpose: remove nominal class identity (private fields) from the plugin seam
496
+ * to avoid TS2379 under exactOptionalPropertyTypes in downstream consumers.
351
497
  */
352
- interface GetDotenvCliGenerateOptions extends GetDotenvCliOptions {
353
- /**
354
- * CLI alias. Should align with the `bin` property in `package.json`.
355
- */
356
- alias: string;
498
+ interface GetDotenvCliPublic<TOptions extends GetDotenvOptions = GetDotenvOptions> extends Command {
499
+ ns(name: string): Command;
500
+ getCtx(): GetDotenvCliCtx<TOptions> | undefined;
501
+ resolveAndLoad(customOptions?: Partial<TOptions>, opts?: {
502
+ runAfterResolve?: boolean;
503
+ }): Promise<GetDotenvCliCtx<TOptions>>;
504
+ setOptionGroup(opt: Option, group: string): void;
505
+ /**
506
+ * Create a dynamic option whose description is computed at help time
507
+ * from the resolved configuration.
508
+ */
509
+ createDynamicOption(flags: string, desc: (cfg: ResolvedHelpConfig & {
510
+ plugins: Record<string, unknown>;
511
+ }) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option;
512
+ createDynamicOption<TValue = unknown>(flags: string, desc: (cfg: ResolvedHelpConfig & {
513
+ plugins: Record<string, unknown>;
514
+ }) => string, parser: (value: string, previous?: TValue) => TValue, defaultValue?: TValue): Option;
515
+ }
516
+ /** Public plugin contract used by the GetDotenv CLI host. */
517
+ interface GetDotenvCliPlugin<TOptions extends GetDotenvOptions = GetDotenvOptions> {
518
+ id?: string;
357
519
  /**
358
- * Cli description (appears in CLI help).
520
+ * Setup phase: register commands and wiring on the provided CLI instance.
521
+ * Runs parent → children (pre-order).
359
522
  */
360
- description: string;
523
+ setup: (cli: GetDotenvCliPublic<TOptions>) => void | Promise<void>;
361
524
  /**
362
- * The `import.meta.url` of the module generating the CLI.
525
+ * After the dotenv context is resolved, initialize any clients/secrets
526
+ * or attach per-plugin state under ctx.plugins (by convention).
527
+ * Runs parent → children (pre-order).
363
528
  */
364
- importMetaUrl: string;
529
+ afterResolve?: (cli: GetDotenvCliPublic<TOptions>, ctx: GetDotenvCliCtx<TOptions>) => void | Promise<void>;
365
530
  /**
366
- * Logger object (defaults to console)
531
+ * Zod schema for this plugin's config slice (from config.plugins[id]).
532
+ * Enforced object-like (ZodObject) to simplify code paths and inference.
367
533
  */
368
- logger: Logger;
534
+ configSchema?: ZodObject;
369
535
  /**
370
- * Mutates inbound options & executes side effects within the `getDotenv`
371
- * context before executing CLI commands.
536
+ * Compositional children. Installed after the parent per pre-order.
372
537
  */
373
- preHook?: GetDotenvCliPreHookCallback;
538
+ children: GetDotenvCliPlugin<TOptions>[];
374
539
  /**
375
- * Executes side effects within the `getDotenv` context after executing CLI
376
- * commands.
540
+ * Compose a child plugin. Returns the parent to enable chaining.
377
541
  */
378
- postHook?: GetDotenvCliPostHookCallback;
542
+ use: (child: GetDotenvCliPlugin<TOptions>) => GetDotenvCliPlugin<TOptions>;
379
543
  }
380
-
381
544
  /**
382
- * Generate a Commander CLI Command for get-dotenv.
383
- * Orchestration only: delegates building and lifecycle hooks.
545
+ * Compile-time helper type: the plugin object returned by definePlugin always
546
+ * includes the instance-bound helpers as required members. Keeping the public
547
+ * interface optional preserves compatibility for ad-hoc/test plugins, while
548
+ * return types from definePlugin provide stronger DX for shipped/typed plugins.
384
549
  */
385
- declare const generateGetDotenvCli: (customOptions: Pick<GetDotenvCliGenerateOptions, "importMetaUrl"> & Partial<Omit<GetDotenvCliGenerateOptions, "importMetaUrl">>) => Promise<Command>;
386
-
550
+ type PluginWithInstanceHelpers<TOptions extends GetDotenvOptions = GetDotenvOptions, TConfig = unknown> = GetDotenvCliPlugin<TOptions> & {
551
+ readConfig<TCfg = TConfig>(cli: GetDotenvCliPublic<TOptions>): Readonly<TCfg>;
552
+ createPluginDynamicOption<TCfg = TConfig>(cli: GetDotenvCliPublic<TOptions>, flags: string, desc: (cfg: ResolvedHelpConfig & {
553
+ plugins: Record<string, unknown>;
554
+ }, pluginCfg: Readonly<TCfg>) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option;
555
+ };
387
556
  /**
388
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
389
- *
390
- * @param options - `GetDotenvOptions` object
391
- * @returns The combined parsed dotenv object.
392
- * * @example Load from the project root with default tokens
393
- * ```ts
394
- * const vars = await getDotenv();
395
- * console.log(vars.MY_SETTING);
396
- * ```
397
- *
398
- * @example Load from multiple paths and a specific environment
399
- * ```ts
400
- * const vars = await getDotenv({
401
- * env: 'dev',
402
- * dotenvToken: '.testenv',
403
- * privateToken: 'secret',
404
- * paths: ['./', './packages/app'],
405
- * });
406
- * ```
407
- *
408
- * @example Use dynamic variables
409
- * ```ts
410
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
411
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
412
- * ```
413
- *
414
- * @remarks
415
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
416
- * into `process.env` as a side effect.
417
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
418
- * The path is resolved after expansion, so it may reference previously loaded vars.
557
+ * Public spec type for defining a plugin with optional children.
558
+ * Exported to ensure TypeDoc links and navigation resolve correctly.
559
+ */
560
+ type DefineSpec<TOptions extends GetDotenvOptions = GetDotenvOptions> = Omit<GetDotenvCliPlugin<TOptions>, 'children' | 'use'> & {
561
+ children?: GetDotenvCliPlugin<TOptions>[];
562
+ };
563
+ /**
564
+ * Define a GetDotenv CLI plugin with compositional helpers.
419
565
  *
420
- * @throws Error when a dynamic module is present but cannot be imported.
421
- * @throws Error when an output path was requested but could not be resolved.
566
+ * @example
567
+ * const parent = definePlugin({ id: 'p', setup(cli) { /* omitted *\/ } })
568
+ * .use(childA)
569
+ * .use(childB);
422
570
  */
423
- declare const getDotenv: (options?: Partial<GetDotenvOptions>) => Promise<ProcessEnv>;
571
+ declare function definePlugin<TOptions extends GetDotenvOptions, Schema extends ZodObject>(spec: Omit<DefineSpec<TOptions>, 'configSchema'> & {
572
+ configSchema: Schema;
573
+ }): PluginWithInstanceHelpers<TOptions, z.output<Schema>>;
574
+ declare function definePlugin<TOptions extends GetDotenvOptions>(spec: DefineSpec<TOptions>): PluginWithInstanceHelpers<TOptions, {}>;
424
575
 
425
576
  /**
426
- * Deeply interpolate string leaves against envRef.
427
- * Arrays are not recursed into; they are returned unchanged.
428
- *
429
- * @typeParam T - Shape of the input value.
430
- * @param value - Input value (object/array/primitive).
431
- * @param envRef - Reference environment for interpolation.
432
- * @returns A new value with string leaves interpolated.
577
+ * Infer the compile-time plugin config type from a plugin instance created by definePlugin.
578
+ * Returns a deeply readonly view to discourage mutation at call sites.
433
579
  */
434
- declare const interpolateDeep: <T>(value: T, envRef: ProcessEnv) => T;
580
+ type InferPluginConfig<P> = P extends PluginWithInstanceHelpers<GetDotenvOptions, infer C> ? Readonly<C> : never;
581
+
582
+ /**
583
+ * GetDotenvCli with root helpers as real class methods.
584
+ * - attachRootOptions: installs legacy/base root flags on the command.
585
+ * - passOptions: merges flags (parent \< current), computes dotenv context once,
586
+ * runs validation, and persists merged options for nested flows.
587
+ */
588
+ declare class GetDotenvCli extends GetDotenvCli$1 {
589
+ /**
590
+ * Attach legacy root flags to this CLI instance. Defaults come from
591
+ * baseRootOptionDefaults when none are provided.
592
+ */
593
+ attachRootOptions(defaults?: Partial<RootOptionsShape>): this;
594
+ /**
595
+ * Install preSubcommand/preAction hooks that:
596
+ * - Merge options (parent round-trip + current invocation) using resolveCliOptions.
597
+ * - Persist the merged bag on the current command and on the host (for ergonomics).
598
+ * - Compute the dotenv context once via resolveAndLoad(serviceOptions).
599
+ * - Validate the composed env against discovered config (warn or --strict fail).
600
+ */
601
+ passOptions(defaults?: Partial<RootOptionsShape>): this;
602
+ }
603
+ /**
604
+ * Helper to retrieve the merged root options bag from any action handler
605
+ * that only has access to thisCommand. Avoids structural casts.
606
+ */
607
+ declare const readMergedOptions: (cmd: Command) => GetDotenvCliOptions | undefined;
435
608
 
436
609
  /**
437
610
  * Create a get-dotenv CLI host with included plugins.
438
611
  *
439
612
  * Options:
440
613
  * - alias: command name used for help/argv scaffolding (default: "getdotenv")
441
- * - branding: optional help header; when omitted, brand() uses "<alias> v<version>"
614
+ * - branding: optional help header; when omitted, brand() uses "\<alias\> v\<version\>"
442
615
  *
443
616
  * Usage:
444
617
  * import \{ createCli \} from '\@karmaniverous/get-dotenv';
@@ -453,5 +626,5 @@ declare function createCli(opts?: CreateCliOptions): {
453
626
  run: (argv: string[]) => Promise<void>;
454
627
  };
455
628
 
456
- export { buildSpawnEnv, createCli, defineDynamic, dotenvExpand, dotenvExpandAll, dotenvExpandFromProcessEnv, generateGetDotenvCli, getDotenv, getDotenvCliOptions2Options, interpolateDeep };
457
- export type { CreateCliOptions, GetDotenvDynamic, GetDotenvOptions, ProcessEnv };
629
+ export { GetDotenvCli, buildSpawnEnv, createCli, defineDynamic, defineGetDotenvConfig, definePlugin, defineScripts, dotenvExpand, dotenvExpandAll, dotenvExpandFromProcessEnv, getDotenv, getDotenvCliOptions2Options, interpolateDeep, readMergedOptions };
630
+ export type { CreateCliOptions, DeepReadonly, DynamicFn, DynamicMap, GetDotenvCliOptions, GetDotenvCliPlugin, GetDotenvCliPublic, GetDotenvConfig, GetDotenvDynamic, GetDotenvOptions, InferGetDotenvVarsFromConfig, InferPluginConfig, PluginWithInstanceHelpers, ProcessEnv, ScriptsTable };