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