@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
@@ -1,9 +1,39 @@
1
- import { Command } from 'commander';
2
- import { ZodType } from 'zod';
1
+ import { z, ZodObject } from 'zod';
2
+ import { Command, Option } from 'commander';
3
+
4
+ /**
5
+ * Scripts table shape (configurable shell type).
6
+ */
7
+ type ScriptsTable<TShell extends string | boolean = string | boolean> = Record<string, string | {
8
+ cmd: string;
9
+ shell?: TShell | undefined;
10
+ }>;
11
+
12
+ declare const getDotenvOptionsSchemaResolved: z.ZodObject<{
13
+ defaultEnv: z.ZodOptional<z.ZodString>;
14
+ dotenvToken: z.ZodOptional<z.ZodString>;
15
+ dynamicPath: z.ZodOptional<z.ZodString>;
16
+ dynamic: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
17
+ env: z.ZodOptional<z.ZodString>;
18
+ excludeDynamic: z.ZodOptional<z.ZodBoolean>;
19
+ excludeEnv: z.ZodOptional<z.ZodBoolean>;
20
+ excludeGlobal: z.ZodOptional<z.ZodBoolean>;
21
+ excludePrivate: z.ZodOptional<z.ZodBoolean>;
22
+ excludePublic: z.ZodOptional<z.ZodBoolean>;
23
+ loadProcess: z.ZodOptional<z.ZodBoolean>;
24
+ log: z.ZodOptional<z.ZodBoolean>;
25
+ logger: z.ZodOptional<z.ZodUnknown>;
26
+ outputPath: z.ZodOptional<z.ZodString>;
27
+ paths: z.ZodOptional<z.ZodArray<z.ZodString>>;
28
+ privateToken: z.ZodOptional<z.ZodString>;
29
+ vars: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
30
+ }, z.core.$strip>;
3
31
 
4
32
  /**
5
33
  * A minimal representation of an environment key/value mapping.
6
- * Values may be `undefined` to represent "unset". */ type ProcessEnv = Record<string, string | undefined>;
34
+ * Values may be `undefined` to represent "unset".
35
+ */
36
+ type ProcessEnv = Record<string, string | undefined>;
7
37
  /**
8
38
  * Dynamic variable function signature. Receives the current expanded variables
9
39
  * and the selected environment (if any), and returns either a string to set
@@ -13,87 +43,86 @@ type GetDotenvDynamicFunction = (vars: ProcessEnv, env: string | undefined) => s
13
43
  type GetDotenvDynamic = Record<string, GetDotenvDynamicFunction | ReturnType<GetDotenvDynamicFunction>>;
14
44
  type Logger = Record<string, (...args: unknown[]) => void> | typeof console;
15
45
  /**
16
- * Options passed programmatically to `getDotenv`.
46
+ * Canonical programmatic options type (schema-derived).
47
+ * This type is the single source of truth for programmatic options.
17
48
  */
18
- interface GetDotenvOptions {
19
- /**
20
- * default target environment (used if `env` is not provided)
21
- */
22
- defaultEnv?: string;
49
+ type GetDotenvOptions = z.output<typeof getDotenvOptionsSchemaResolved> & {
23
50
  /**
24
- * token indicating a dotenv file
51
+ * Compile-time overlay: narrowed logger for DX (schema stores unknown).
25
52
  */
26
- dotenvToken: string;
27
- /**
28
- * path to JS/TS module default-exporting an object keyed to dynamic variable functions
29
- */
30
- dynamicPath?: string;
53
+ logger?: Logger;
31
54
  /**
32
- * Programmatic dynamic variables map. When provided, this takes precedence
33
- * over {@link GetDotenvOptions.dynamicPath}.
55
+ * Compile-time overlay: narrowed dynamic map for DX (schema stores unknown).
34
56
  */
35
57
  dynamic?: GetDotenvDynamic;
58
+ };
59
+
60
+ declare const getDotenvCliOptionsSchemaResolved: z.ZodObject<{
61
+ defaultEnv: z.ZodOptional<z.ZodString>;
62
+ dotenvToken: z.ZodOptional<z.ZodString>;
63
+ dynamicPath: z.ZodOptional<z.ZodString>;
64
+ dynamic: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
65
+ env: z.ZodOptional<z.ZodString>;
66
+ excludeDynamic: z.ZodOptional<z.ZodBoolean>;
67
+ excludeEnv: z.ZodOptional<z.ZodBoolean>;
68
+ excludeGlobal: z.ZodOptional<z.ZodBoolean>;
69
+ excludePrivate: z.ZodOptional<z.ZodBoolean>;
70
+ excludePublic: z.ZodOptional<z.ZodBoolean>;
71
+ loadProcess: z.ZodOptional<z.ZodBoolean>;
72
+ log: z.ZodOptional<z.ZodBoolean>;
73
+ logger: z.ZodOptional<z.ZodUnknown>;
74
+ outputPath: z.ZodOptional<z.ZodString>;
75
+ privateToken: z.ZodOptional<z.ZodString>;
76
+ debug: z.ZodOptional<z.ZodBoolean>;
77
+ strict: z.ZodOptional<z.ZodBoolean>;
78
+ capture: z.ZodOptional<z.ZodBoolean>;
79
+ trace: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodArray<z.ZodString>]>>;
80
+ redact: z.ZodOptional<z.ZodBoolean>;
81
+ warnEntropy: z.ZodOptional<z.ZodBoolean>;
82
+ entropyThreshold: z.ZodOptional<z.ZodNumber>;
83
+ entropyMinLength: z.ZodOptional<z.ZodNumber>;
84
+ entropyWhitelist: z.ZodOptional<z.ZodArray<z.ZodString>>;
85
+ redactPatterns: z.ZodOptional<z.ZodArray<z.ZodString>>;
86
+ paths: z.ZodOptional<z.ZodString>;
87
+ pathsDelimiter: z.ZodOptional<z.ZodString>;
88
+ pathsDelimiterPattern: z.ZodOptional<z.ZodString>;
89
+ scripts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
90
+ shell: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
91
+ vars: z.ZodOptional<z.ZodString>;
92
+ varsAssignor: z.ZodOptional<z.ZodString>;
93
+ varsAssignorPattern: z.ZodOptional<z.ZodString>;
94
+ varsDelimiter: z.ZodOptional<z.ZodString>;
95
+ varsDelimiterPattern: z.ZodOptional<z.ZodString>;
96
+ }, z.core.$strip>;
97
+
98
+ type Scripts = ScriptsTable;
99
+ /**
100
+ * Canonical CLI options type derived from the Zod schema output.
101
+ * Includes CLI-only flags (debug/strict/capture/trace/redaction/entropy),
102
+ * stringly paths/vars, and inherited programmatic fields (minus normalized
103
+ * shapes that are handled by resolution).
104
+ */
105
+ type GetDotenvCliOptions = z.output<typeof getDotenvCliOptionsSchemaResolved> & {
36
106
  /**
37
- * target environment
38
- */
39
- env?: string;
40
- /**
41
- * exclude dynamic variables from loading
42
- */
43
- excludeDynamic?: boolean;
44
- /**
45
- * exclude environment-specific variables from loading
46
- */
47
- excludeEnv?: boolean;
48
- /**
49
- * exclude global variables from loading
50
- */
51
- excludeGlobal?: boolean;
52
- /**
53
- * exclude private variables from loading
54
- */
55
- excludePrivate?: boolean;
56
- /**
57
- * exclude public variables from loading
58
- */
59
- excludePublic?: boolean;
60
- /**
61
- * load dotenv variables to `process.env`
62
- */
63
- loadProcess?: boolean;
64
- /**
65
- * log loaded dotenv variables to `logger`
66
- */
67
- log?: boolean;
68
- /**
69
- * logger object (defaults to console)
107
+ * Compile-only overlay for DX: logger narrowed from unknown.
70
108
  */
71
109
  logger?: Logger;
72
110
  /**
73
- * if populated, writes consolidated dotenv file to this path (follows dotenvExpand rules)
74
- */
75
- outputPath?: string;
76
- /**
77
- * array of input directory paths
78
- */
79
- paths?: string[];
80
- /**
81
- * filename token indicating private variables
82
- */
83
- privateToken?: string;
84
- /**
85
- * explicit variables to include
111
+ * Compile-only overlay for DX: scripts narrowed from Record\<string, unknown\>.
86
112
  */
87
- vars?: ProcessEnv;
88
- /**
89
- * Reserved: config loader flag (no-op).
90
- * The plugin-first host and generator paths already use the config
91
- * loader/overlay pipeline unconditionally (no-op when no config files
92
- * are present). This flag is accepted for forward compatibility but
93
- * currently has no effect.
94
- */
95
- useConfigLoader?: boolean;
96
- }
113
+ scripts?: Scripts;
114
+ };
115
+
116
+ type ResolvedHelpConfig = Partial<GetDotenvCliOptions> & {
117
+ plugins: Record<string, unknown>;
118
+ };
119
+ /** Per-invocation context shared with plugins and actions. */
120
+ type GetDotenvCliCtx<TOptions extends GetDotenvOptions = GetDotenvOptions> = {
121
+ optionsResolved: TOptions;
122
+ dotenv: ProcessEnv;
123
+ plugins?: Record<string, unknown>;
124
+ pluginConfigs?: Record<string, unknown>;
125
+ };
97
126
 
98
127
  /** src/cliHost/definePlugin.ts
99
128
  * Plugin contracts for the GetDotenv CLI host.
@@ -111,48 +140,65 @@ interface GetDotenvOptions {
111
140
  * Purpose: remove nominal class identity (private fields) from the plugin seam
112
141
  * to avoid TS2379 under exactOptionalPropertyTypes in downstream consumers.
113
142
  */
114
- type GetDotenvCliPublic<TOptions extends GetDotenvOptions = GetDotenvOptions> = Command & {
115
- ns: (name: string) => Command;
116
- getCtx: () => GetDotenvCliCtx<TOptions> | undefined;
117
- resolveAndLoad: (customOptions?: Partial<TOptions>) => Promise<GetDotenvCliCtx<TOptions>>;
118
- };
143
+ interface GetDotenvCliPublic<TOptions extends GetDotenvOptions = GetDotenvOptions> extends Command {
144
+ ns(name: string): Command;
145
+ getCtx(): GetDotenvCliCtx<TOptions> | undefined;
146
+ resolveAndLoad(customOptions?: Partial<TOptions>, opts?: {
147
+ runAfterResolve?: boolean;
148
+ }): Promise<GetDotenvCliCtx<TOptions>>;
149
+ setOptionGroup(opt: Option, group: string): void;
150
+ /**
151
+ * Create a dynamic option whose description is computed at help time
152
+ * from the resolved configuration.
153
+ */
154
+ createDynamicOption(flags: string, desc: (cfg: ResolvedHelpConfig & {
155
+ plugins: Record<string, unknown>;
156
+ }) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option;
157
+ createDynamicOption<TValue = unknown>(flags: string, desc: (cfg: ResolvedHelpConfig & {
158
+ plugins: Record<string, unknown>;
159
+ }) => string, parser: (value: string, previous?: TValue) => TValue, defaultValue?: TValue): Option;
160
+ }
119
161
  /** Public plugin contract used by the GetDotenv CLI host. */
120
- interface GetDotenvCliPlugin {
162
+ interface GetDotenvCliPlugin<TOptions extends GetDotenvOptions = GetDotenvOptions> {
121
163
  id?: string;
122
164
  /**
123
165
  * Setup phase: register commands and wiring on the provided CLI instance.
124
166
  * Runs parent → children (pre-order).
125
167
  */
126
- setup: (cli: GetDotenvCliPublic) => void | Promise<void>;
168
+ setup: (cli: GetDotenvCliPublic<TOptions>) => void | Promise<void>;
127
169
  /**
128
170
  * After the dotenv context is resolved, initialize any clients/secrets
129
171
  * or attach per-plugin state under ctx.plugins (by convention).
130
172
  * Runs parent → children (pre-order).
131
173
  */
132
- afterResolve?: (cli: GetDotenvCliPublic, ctx: GetDotenvCliCtx) => void | Promise<void>;
174
+ afterResolve?: (cli: GetDotenvCliPublic<TOptions>, ctx: GetDotenvCliCtx<TOptions>) => void | Promise<void>;
133
175
  /**
134
- * Optional Zod schema for this plugin's config slice (from config.plugins[id]).
135
- * When provided, the host validates the merged config under the guarded loader path.
176
+ * Zod schema for this plugin's config slice (from config.plugins[id]).
177
+ * Enforced object-like (ZodObject) to simplify code paths and inference.
136
178
  */
137
- configSchema?: ZodType;
179
+ configSchema?: ZodObject;
138
180
  /**
139
181
  * Compositional children. Installed after the parent per pre-order.
140
182
  */
141
- children: GetDotenvCliPlugin[];
183
+ children: GetDotenvCliPlugin<TOptions>[];
142
184
  /**
143
185
  * Compose a child plugin. Returns the parent to enable chaining.
144
186
  */
145
- use: (child: GetDotenvCliPlugin) => GetDotenvCliPlugin;
187
+ use: (child: GetDotenvCliPlugin<TOptions>) => GetDotenvCliPlugin<TOptions>;
146
188
  }
147
-
148
- /** * Per-invocation context shared with plugins and actions. */
149
- type GetDotenvCliCtx<TOptions extends GetDotenvOptions = GetDotenvOptions> = {
150
- optionsResolved: TOptions;
151
- dotenv: ProcessEnv;
152
- plugins?: Record<string, unknown>;
153
- pluginConfigs?: Record<string, unknown>;
189
+ /**
190
+ * Compile-time helper type: the plugin object returned by definePlugin always
191
+ * includes the instance-bound helpers as required members. Keeping the public
192
+ * interface optional preserves compatibility for ad-hoc/test plugins, while
193
+ * return types from definePlugin provide stronger DX for shipped/typed plugins.
194
+ */
195
+ type PluginWithInstanceHelpers<TOptions extends GetDotenvOptions = GetDotenvOptions, TConfig = unknown> = GetDotenvCliPlugin<TOptions> & {
196
+ readConfig<TCfg = TConfig>(cli: GetDotenvCliPublic<TOptions>): Readonly<TCfg>;
197
+ createPluginDynamicOption<TCfg = TConfig>(cli: GetDotenvCliPublic<TOptions>, flags: string, desc: (cfg: ResolvedHelpConfig & {
198
+ plugins: Record<string, unknown>;
199
+ }, pluginCfg: Readonly<TCfg>) => string, parser?: (value: string, previous?: unknown) => unknown, defaultValue?: unknown): Option;
154
200
  };
155
201
 
156
- declare const demoPlugin: () => GetDotenvCliPlugin;
202
+ declare const demoPlugin: () => PluginWithInstanceHelpers<GetDotenvOptions, {}>;
157
203
 
158
204
  export { demoPlugin };
@@ -1,8 +1,20 @@
1
1
  import { execa, execaCommand } from 'execa';
2
+ import { z } from 'zod';
3
+ import 'fs-extra';
4
+ import 'path';
5
+ import 'package-directory';
6
+ import 'url';
7
+ import 'yaml';
8
+ import 'nanoid';
9
+ import 'dotenv';
10
+ import 'crypto';
2
11
 
3
12
  // Minimal tokenizer for shell-off execution:
4
13
  // Splits by whitespace while preserving quoted segments (single or double quotes).
5
- const tokenize = (command) => {
14
+ // Optionally preserve doubled quotes inside quoted segments:
15
+ // - default: "" => " (Windows/PowerShell style literal-quote escape)
16
+ // - preserveDoubledQuotes: true => "" stays "" (needed for Node -e payloads)
17
+ const tokenize = (command, opts) => {
6
18
  const out = [];
7
19
  let cur = '';
8
20
  let quote = null;
@@ -10,12 +22,16 @@ const tokenize = (command) => {
10
22
  const c = command.charAt(i);
11
23
  if (quote) {
12
24
  if (c === quote) {
13
- // Support doubled quotes inside a quoted segment (Windows/PowerShell style):
14
- // "" -> " and '' -> '
25
+ // Support doubled quotes inside a quoted segment:
26
+ // default: "" -> " and '' -> ' (Windows/PowerShell style)
27
+ // preserve: keep as "" to allow empty string literals in Node -e payloads
15
28
  const next = command.charAt(i + 1);
16
29
  if (next === quote) {
17
- cur += quote;
18
- i += 1; // skip the second quote
30
+ {
31
+ // Collapse to a single literal quote
32
+ cur += quote;
33
+ i += 1; // skip the second quote
34
+ }
19
35
  }
20
36
  else {
21
37
  // end of quoted segment
@@ -70,6 +86,17 @@ const stripOuterQuotes = (s) => {
70
86
  }
71
87
  return out;
72
88
  };
89
+ // Extract exitCode/stdout/stderr from execa result or error in a tolerant way.
90
+ const pickResult = (r) => {
91
+ const exit = r.exitCode;
92
+ const stdoutVal = r.stdout;
93
+ const stderrVal = r.stderr;
94
+ return {
95
+ exitCode: typeof exit === 'number' ? exit : Number.NaN,
96
+ stdout: typeof stdoutVal === 'string' ? stdoutVal : '',
97
+ stderr: typeof stderrVal === 'string' ? stderrVal : '',
98
+ };
99
+ };
73
100
  // Convert NodeJS.ProcessEnv (string | undefined values) to the shape execa
74
101
  // expects (Readonly<Partial<Record<string, string>>>), dropping undefineds.
75
102
  const sanitizeEnv = (env) => {
@@ -78,19 +105,19 @@ const sanitizeEnv = (env) => {
78
105
  const entries = Object.entries(env).filter((e) => typeof e[1] === 'string');
79
106
  return entries.length > 0 ? Object.fromEntries(entries) : undefined;
80
107
  };
81
- const runCommand = async (command, shell, opts) => {
108
+ async function runCommand(command, shell, opts) {
82
109
  if (shell === false) {
83
110
  let file;
84
111
  let args = [];
85
- if (Array.isArray(command)) {
86
- file = command[0];
87
- args = command.slice(1).map(stripOuterQuotes);
88
- }
89
- else {
112
+ if (typeof command === 'string') {
90
113
  const tokens = tokenize(command);
91
114
  file = tokens[0];
92
115
  args = tokens.slice(1);
93
116
  }
117
+ else {
118
+ file = command[0];
119
+ args = command.slice(1).map(stripOuterQuotes);
120
+ }
94
121
  if (!file)
95
122
  return 0;
96
123
  dbg('exec (plain)', { file, args, stdio: opts.stdio });
@@ -103,16 +130,15 @@ const runCommand = async (command, shell, opts) => {
103
130
  plainOpts.env = envSan;
104
131
  if (opts.stdio !== undefined)
105
132
  plainOpts.stdio = opts.stdio;
106
- const result = await execa(file, args, plainOpts);
107
- if (opts.stdio === 'pipe' && result.stdout) {
108
- process.stdout.write(result.stdout + (result.stdout.endsWith('\n') ? '' : '\n'));
133
+ const ok = pickResult((await execa(file, args, plainOpts)));
134
+ if (opts.stdio === 'pipe' && ok.stdout) {
135
+ process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
109
136
  }
110
- const exit = result?.exitCode;
111
- dbg('exit (plain)', { exitCode: exit });
112
- return typeof exit === 'number' ? exit : Number.NaN;
137
+ dbg('exit (plain)', { exitCode: ok.exitCode });
138
+ return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
113
139
  }
114
140
  else {
115
- const commandStr = Array.isArray(command) ? command.join(' ') : command;
141
+ const commandStr = typeof command === 'string' ? command : command.join(' ');
116
142
  dbg('exec (shell)', {
117
143
  shell: typeof shell === 'string' ? shell : 'custom',
118
144
  stdio: opts.stdio,
@@ -126,17 +152,148 @@ const runCommand = async (command, shell, opts) => {
126
152
  shellOpts.env = envSan;
127
153
  if (opts.stdio !== undefined)
128
154
  shellOpts.stdio = opts.stdio;
129
- const result = await execaCommand(commandStr, shellOpts);
130
- const out = result?.stdout;
131
- if (opts.stdio === 'pipe' && out) {
132
- process.stdout.write(out + (out.endsWith('\n') ? '' : '\n'));
155
+ const ok = pickResult((await execaCommand(commandStr, shellOpts)));
156
+ if (opts.stdio === 'pipe' && ok.stdout) {
157
+ process.stdout.write(ok.stdout + (ok.stdout.endsWith('\n') ? '' : '\n'));
158
+ }
159
+ dbg('exit (shell)', { exitCode: ok.exitCode });
160
+ return typeof ok.exitCode === 'number' ? ok.exitCode : Number.NaN;
161
+ }
162
+ }
163
+
164
+ /** src/cliCore/spawnEnv.ts
165
+ * Build a sanitized environment bag for child processes.
166
+ *
167
+ * Requirements addressed:
168
+ * - Provide a single helper (buildSpawnEnv) to normalize/dedupe child env.
169
+ * - Drop undefined values (exactOptional semantics).
170
+ * - On Windows, dedupe keys case-insensitively and prefer the last value,
171
+ * preserving the latest key's casing. Ensure HOME fallback from USERPROFILE.
172
+ * Normalize TMP/TEMP consistency when either is present.
173
+ * - On POSIX, keep keys as-is; when a temp dir key is present (TMPDIR/TMP/TEMP),
174
+ * ensure TMPDIR exists for downstream consumers that expect it.
175
+ *
176
+ * Adapter responsibility: pure mapping; no business logic.
177
+ */
178
+ const dropUndefined = (bag) => Object.fromEntries(Object.entries(bag).filter((e) => typeof e[1] === 'string'));
179
+ /** Build a sanitized env for child processes from base + overlay. */
180
+ const buildSpawnEnv = (base, overlay) => {
181
+ const raw = {
182
+ ...(base ?? {}),
183
+ ...(overlay ?? {}),
184
+ };
185
+ // Drop undefined first
186
+ const entries = Object.entries(dropUndefined(raw));
187
+ if (process.platform === 'win32') {
188
+ // Windows: keys are case-insensitive; collapse duplicates
189
+ const byLower = new Map();
190
+ for (const [k, v] of entries) {
191
+ byLower.set(k.toLowerCase(), [k, v]); // last wins; preserve latest casing
133
192
  }
134
- const exit = result?.exitCode;
135
- dbg('exit (shell)', { exitCode: exit });
136
- return typeof exit === 'number' ? exit : Number.NaN;
193
+ const out = {};
194
+ for (const [, [k, v]] of byLower)
195
+ out[k] = v;
196
+ // HOME fallback from USERPROFILE (common expectation)
197
+ if (!Object.prototype.hasOwnProperty.call(out, 'HOME')) {
198
+ const up = out['USERPROFILE'];
199
+ if (typeof up === 'string' && up.length > 0)
200
+ out['HOME'] = up;
201
+ }
202
+ // Normalize TMP/TEMP coherence (pick any present; reflect to both)
203
+ const tmp = out['TMP'] ?? out['TEMP'];
204
+ if (typeof tmp === 'string' && tmp.length > 0) {
205
+ out['TMP'] = tmp;
206
+ out['TEMP'] = tmp;
207
+ }
208
+ return out;
209
+ }
210
+ // POSIX: keep keys as-is
211
+ const out = Object.fromEntries(entries);
212
+ // Ensure TMPDIR exists when any temp key is present (best-effort)
213
+ const tmpdir = out['TMPDIR'] ?? out['TMP'] ?? out['TEMP'];
214
+ if (typeof tmpdir === 'string' && tmpdir.length > 0) {
215
+ out['TMPDIR'] = tmpdir;
137
216
  }
217
+ return out;
138
218
  };
139
219
 
220
+ /**
221
+ * Zod schemas for configuration files discovered by the new loader.
222
+ *
223
+ * Notes:
224
+ * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
225
+ * - RESOLVED: normalized shapes (paths always string[]).
226
+ * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
227
+ */
228
+ // String-only env value map
229
+ const stringMap = z.record(z.string(), z.string());
230
+ const envStringMap = z.record(z.string(), stringMap);
231
+ // Allow string[] or single string for "paths" in RAW; normalize later.
232
+ const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
233
+ const getDotenvConfigSchemaRaw = z.object({
234
+ dotenvToken: z.string().optional(),
235
+ privateToken: z.string().optional(),
236
+ paths: rawPathsSchema,
237
+ loadProcess: z.boolean().optional(),
238
+ log: z.boolean().optional(),
239
+ shell: z.union([z.string(), z.boolean()]).optional(),
240
+ scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
241
+ requiredKeys: z.array(z.string()).optional(),
242
+ schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
243
+ vars: stringMap.optional(), // public, global
244
+ envVars: envStringMap.optional(), // public, per-env
245
+ // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
246
+ dynamic: z.unknown().optional(),
247
+ // Per-plugin config bag; validated by plugins/host when used.
248
+ plugins: z.record(z.string(), z.unknown()).optional(),
249
+ });
250
+ // Normalize paths to string[]
251
+ const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
252
+ getDotenvConfigSchemaRaw.transform((raw) => ({
253
+ ...raw,
254
+ paths: normalizePaths(raw.paths),
255
+ }));
256
+
257
+ /**
258
+ * Zod schemas for programmatic GetDotenv options.
259
+ *
260
+ * Canonical source of truth for options shape. Public types are derived
261
+ * from these schemas (see consumers via z.output\<\>).
262
+ */
263
+ // Minimal process env representation: string values or undefined to indicate "unset".
264
+ const processEnvSchema = z.record(z.string(), z.string().optional());
265
+ // RAW: all fields optional — undefined means "inherit" from lower layers.
266
+ z.object({
267
+ defaultEnv: z.string().optional(),
268
+ dotenvToken: z.string().optional(),
269
+ dynamicPath: z.string().optional(),
270
+ // Dynamic map is intentionally wide for now; refine once sources are normalized.
271
+ dynamic: z.record(z.string(), z.unknown()).optional(),
272
+ env: z.string().optional(),
273
+ excludeDynamic: z.boolean().optional(),
274
+ excludeEnv: z.boolean().optional(),
275
+ excludeGlobal: z.boolean().optional(),
276
+ excludePrivate: z.boolean().optional(),
277
+ excludePublic: z.boolean().optional(),
278
+ loadProcess: z.boolean().optional(),
279
+ log: z.boolean().optional(),
280
+ logger: z.unknown().optional(),
281
+ outputPath: z.string().optional(),
282
+ paths: z.array(z.string()).optional(),
283
+ privateToken: z.string().optional(),
284
+ vars: processEnvSchema.optional(),
285
+ });
286
+
287
+ /**
288
+ * Instance-bound plugin config store.
289
+ * Host stores the validated/interpolated slice per plugin instance.
290
+ * The store is intentionally private to this module; definePlugin()
291
+ * provides a typed accessor that reads from this store for the calling
292
+ * plugin instance.
293
+ */
294
+ const PLUGIN_CONFIG_STORE = new WeakMap();
295
+ const _getPluginConfigForInstance = (plugin) => PLUGIN_CONFIG_STORE.get(plugin);
296
+
140
297
  /** src/cliHost/definePlugin.ts
141
298
  * Plugin contracts for the GetDotenv CLI host.
142
299
  *
@@ -144,26 +301,59 @@ const runCommand = async (command, shell, opts) => {
144
301
  * should use (GetDotenvCliPublic). Using a structural type at the seam avoids
145
302
  * nominal class identity issues (private fields) in downstream consumers.
146
303
  */
147
- /**
148
- * Define a GetDotenv CLI plugin with compositional helpers.
149
- *
150
- * @example
151
- * const parent = definePlugin(\{ id: 'p', setup(cli) \{ /* ... *\/ \} \})
152
- * .use(childA)
153
- * .use(childB);
154
- */
155
- const definePlugin = (spec) => {
304
+ /* eslint-disable tsdoc/syntax */
305
+ function definePlugin(spec) {
156
306
  const { children = [], ...rest } = spec;
157
- const plugin = {
307
+ // Default to a strict empty-object schema so “no-config” plugins fail fast
308
+ // on unknown keys and provide a concrete {} at runtime.
309
+ const effectiveSchema = spec.configSchema ?? z.object({}).strict();
310
+ // Build base plugin first, then extend with instance-bound helpers.
311
+ const base = {
158
312
  ...rest,
313
+ // Always carry a schema (strict empty by default) to simplify host logic
314
+ // and improve inference/ergonomics for plugin authors.
315
+ configSchema: effectiveSchema,
159
316
  children: [...children],
160
317
  use(child) {
161
318
  this.children.push(child);
162
319
  return this;
163
320
  },
164
321
  };
165
- return plugin;
166
- };
322
+ // Attach instance-bound helpers on the returned plugin object.
323
+ const extended = base;
324
+ extended.readConfig = function (_cli) {
325
+ // Config is stored per-plugin-instance by the host (WeakMap in computeContext).
326
+ const value = _getPluginConfigForInstance(extended);
327
+ if (value === undefined) {
328
+ // Guard: host has not resolved config yet (incorrect lifecycle usage).
329
+ throw new Error('Plugin config not available. Ensure resolveAndLoad() has been called before readConfig().');
330
+ }
331
+ return value;
332
+ };
333
+ // Plugin-bound dynamic option factory
334
+ extended.createPluginDynamicOption = function (cli, flags, desc, parser, defaultValue) {
335
+ return cli.createDynamicOption(flags, (cfg) => {
336
+ // Prefer the validated slice stored per instance; fallback to help-bag
337
+ // (by-id) so top-level `-h` can render effective defaults before resolve.
338
+ const fromStore = _getPluginConfigForInstance(extended);
339
+ const id = extended.id;
340
+ let fromBag;
341
+ if (!fromStore && id) {
342
+ const maybe = cfg.plugins[id];
343
+ if (maybe && typeof maybe === 'object') {
344
+ fromBag = maybe;
345
+ }
346
+ }
347
+ // Always provide a concrete object to dynamic callbacks:
348
+ // - With a schema: computeContext stores the parsed object.
349
+ // - Without a schema: computeContext stores {}.
350
+ // - Help-time fallback: coalesce to {} when only a by-id bag exists.
351
+ const cfgVal = (fromStore ?? fromBag ?? {});
352
+ return desc(cfg, cfgVal);
353
+ }, parser, defaultValue);
354
+ };
355
+ return extended;
356
+ }
167
357
 
168
358
  /**
169
359
  * Batch services (neutral): resolve command and shell settings.
@@ -244,10 +434,9 @@ const demoPlugin = () => definePlugin({
244
434
  // Build a minimal node -e payload via argv array (avoid quoting issues).
245
435
  const code = `console.log(process.env.${key} ?? "")`;
246
436
  const ctx = cli.getCtx();
247
- const dotenv = (ctx?.dotenv ?? {});
248
437
  // Inherit stdio for an interactive demo. Use --capture for CI.
249
438
  await runCommand(['node', '-e', code], false, {
250
- env: { ...process.env, ...dotenv },
439
+ env: buildSpawnEnv(process.env, ctx?.dotenv),
251
440
  stdio: 'inherit',
252
441
  });
253
442
  });
@@ -282,22 +471,24 @@ const demoPlugin = () => definePlugin({
282
471
  const shell = resolveShell(bag?.scripts, input, bag?.shell);
283
472
  // Compose child env (parent + ctx.dotenv). This mirrors cmd/batch behavior.
284
473
  const ctx = cli.getCtx();
285
- const dotenv = (ctx?.dotenv ?? {});
286
474
  await runCommand(resolved, shell, {
287
- env: { ...process.env, ...dotenv },
475
+ env: buildSpawnEnv(process.env, ctx?.dotenv),
288
476
  stdio: 'inherit',
289
477
  });
290
478
  });
291
479
  },
292
480
  /**
293
481
  * Optional: afterResolve can initialize per-plugin state using ctx.dotenv.
294
- * For the demo we just log once to hint where such logic would live.
482
+ * For the demo we emit a single breadcrumb only when GETDOTENV_DEBUG is set,
483
+ * keeping default runs (tests/CI/smoke) quiet.
295
484
  */
296
485
  afterResolve(_cli, ctx) {
297
- const keys = Object.keys(ctx.dotenv);
298
- if (keys.length > 0) {
299
- // Keep noise low; a single-line breadcrumb is sufficient for the demo.
300
- console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
486
+ if (process.env.GETDOTENV_DEBUG) {
487
+ const keys = Object.keys(ctx.dotenv);
488
+ if (keys.length > 0) {
489
+ // Keep noise low; a single-line breadcrumb is sufficient for the demo.
490
+ console.error('[demo] afterResolve: dotenv keys loaded:', keys.length);
491
+ }
301
492
  }
302
493
  },
303
494
  });