@karmaniverous/get-dotenv 5.2.4 → 5.2.6

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/dist/plugins.mjs CHANGED
@@ -1,15 +1,10 @@
1
1
  import { execa, execaCommand } from 'execa';
2
2
  import { z } from 'zod';
3
- import { Command, Option } from 'commander';
3
+ import { Command } from 'commander';
4
4
  import { globby } from 'globby';
5
5
  import { packageDirectory } from 'package-directory';
6
- import path, { join, extname } from 'path';
6
+ import path from 'path';
7
7
  import fs from 'fs-extra';
8
- import url, { fileURLToPath, pathToFileURL } from 'url';
9
- import YAML from 'yaml';
10
- import { nanoid } from 'nanoid';
11
- import { parse } from 'dotenv';
12
- import { createHash } from 'crypto';
13
8
  import { stdin, stdout } from 'node:process';
14
9
  import { createInterface } from 'readline/promises';
15
10
 
@@ -1106,19 +1101,6 @@ const DEFAULT_PATTERNS = [
1106
1101
  const compile = (patterns) => (patterns && patterns.length > 0 ? patterns : DEFAULT_PATTERNS).map((p) => new RegExp(p, 'i'));
1107
1102
  const shouldRedactKey = (key, regs) => regs.some((re) => re.test(key));
1108
1103
  const MASK = '[redacted]';
1109
- /**
1110
- * Produce a shallow redacted copy of an env-like object for display.
1111
- */
1112
- const redactObject = (obj, opts) => {
1113
- if (!opts?.redact)
1114
- return { ...obj };
1115
- const regs = compile(opts.redactPatterns);
1116
- const out = {};
1117
- for (const [k, v] of Object.entries(obj)) {
1118
- out[k] = v && shouldRedactKey(k, regs) ? MASK : v;
1119
- }
1120
- return out;
1121
- };
1122
1104
  /**
1123
1105
  * Utility to redact three related displayed values (parent/dotenv/final)
1124
1106
  * consistently for trace lines.
@@ -1168,10 +1150,8 @@ const baseRootOptionDefaults = {
1168
1150
  // (debug/log/exclude* resolved via flag utils)
1169
1151
  };
1170
1152
 
1171
- const baseGetDotenvCliOptions = baseRootOptionDefaults;
1172
-
1173
1153
  /** @internal */
1174
- const isPlainObject$1 = (value) => value !== null &&
1154
+ const isPlainObject = (value) => value !== null &&
1175
1155
  typeof value === 'object' &&
1176
1156
  Object.getPrototypeOf(value) === Object.prototype;
1177
1157
  const mergeInto = (target, source) => {
@@ -1179,10 +1159,10 @@ const mergeInto = (target, source) => {
1179
1159
  if (sVal === undefined)
1180
1160
  continue; // do not overwrite with undefined
1181
1161
  const tVal = target[key];
1182
- if (isPlainObject$1(tVal) && isPlainObject$1(sVal)) {
1162
+ if (isPlainObject(tVal) && isPlainObject(sVal)) {
1183
1163
  target[key] = mergeInto({ ...tVal }, sVal);
1184
1164
  }
1185
- else if (isPlainObject$1(sVal)) {
1165
+ else if (isPlainObject(sVal)) {
1186
1166
  target[key] = mergeInto({}, sVal);
1187
1167
  }
1188
1168
  else {
@@ -1212,370 +1192,129 @@ const defaultsDeep = (...layers) => {
1212
1192
  return result;
1213
1193
  };
1214
1194
 
1215
- // src/GetDotenvOptions.ts
1216
- const getDotenvOptionsFilename = 'getdotenv.config.json';
1217
1195
  /**
1218
- * Converts programmatic CLI options to `getDotenv` options. *
1219
- * @param cliOptions - CLI options. Defaults to `{}`.
1196
+ * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
1197
+ * - If the user explicitly enabled the flag, return true.
1198
+ * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
1199
+ * - Otherwise, adopt the default (true → set; false/undefined → unset).
1220
1200
  *
1221
- * @returns `getDotenv` options.
1201
+ * @param exclude - The "on" flag value as parsed by Commander.
1202
+ * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
1203
+ * @param defaultValue - The generator default to adopt when no explicit toggle is present.
1204
+ * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
1205
+ *
1206
+ * @example
1207
+ * ```ts
1208
+ * resolveExclusion(undefined, undefined, true); // => true
1209
+ * ```
1222
1210
  */
1223
- const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
1224
- /**
1225
- * Convert CLI-facing string options into {@link GetDotenvOptions}.
1226
- *
1227
- * - 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`
1228
- * pairs (configurable delimiters) into a {@link ProcessEnv}.
1229
- * - Drops CLI-only keys that have no programmatic equivalent.
1230
- *
1231
- * @remarks
1232
- * Follows exact-optional semantics by not emitting undefined-valued entries.
1233
- */
1234
- // Drop CLI-only keys (debug/scripts) without relying on Record casts.
1235
- // Create a shallow copy then delete optional CLI-only keys if present.
1236
- const restObj = { ...rest };
1237
- delete restObj.debug;
1238
- delete restObj.scripts;
1239
- const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
1240
- // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
1241
- let parsedVars;
1242
- if (typeof vars === 'string') {
1243
- const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
1244
- ? RegExp(varsAssignorPattern)
1245
- : (varsAssignor ?? '=')));
1246
- parsedVars = Object.fromEntries(kvPairs);
1247
- }
1248
- else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
1249
- // Keep only string or undefined values to match ProcessEnv.
1250
- const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
1251
- parsedVars = Object.fromEntries(entries);
1252
- }
1253
- // Drop undefined-valued entries at the converter stage to match ProcessEnv
1254
- // expectations and the compat test assertions.
1255
- if (parsedVars) {
1256
- parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
1257
- }
1258
- // Tolerate paths as either a delimited string or string[]
1259
- // Use a locally cast union type to avoid lint warnings about always-falsy conditions
1260
- // under the RootOptionsShape (which declares paths as string | undefined).
1261
- const pathsAny = paths;
1262
- const pathsOut = Array.isArray(pathsAny)
1263
- ? pathsAny.filter((p) => typeof p === 'string')
1264
- : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
1265
- // Preserve exactOptionalPropertyTypes: only include keys when defined.
1266
- return {
1267
- ...restObj,
1268
- ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
1269
- ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
1270
- };
1271
- };
1272
- const resolveGetDotenvOptions = async (customOptions) => {
1273
- /**
1274
- * Resolve {@link GetDotenvOptions} by layering defaults in ascending precedence:
1275
- *
1276
- * 1. Base defaults derived from the CLI generator defaults
1277
- * ({@link baseGetDotenvCliOptions}).
1278
- * 2. Local project overrides from a `getdotenv.config.json` in the nearest
1279
- * package root (if present).
1280
- * 3. The provided {@link customOptions}.
1281
- *
1282
- * The result preserves explicit empty values and drops only `undefined`.
1283
- *
1284
- * @returns Fully-resolved {@link GetDotenvOptions}.
1285
- *
1286
- * @example
1287
- * ```ts
1288
- * const options = await resolveGetDotenvOptions({ env: 'dev' });
1289
- * ```
1290
- */
1291
- const localPkgDir = await packageDirectory();
1292
- const localOptionsPath = localPkgDir
1293
- ? join(localPkgDir, getDotenvOptionsFilename)
1294
- : undefined;
1295
- const localOptions = (localOptionsPath && (await fs.exists(localOptionsPath))
1296
- ? JSON.parse((await fs.readFile(localOptionsPath)).toString())
1297
- : {});
1298
- // Merge order: base < local < custom (custom has highest precedence)
1299
- const mergedCli = defaultsDeep(baseGetDotenvCliOptions, localOptions);
1300
- const defaultsFromCli = getDotenvCliOptions2Options(mergedCli);
1301
- const result = defaultsDeep(defaultsFromCli, customOptions);
1302
- return {
1303
- ...result, // Keep explicit empty strings/zeros; drop only undefined
1304
- vars: Object.fromEntries(Object.entries(result.vars ?? {}).filter(([, v]) => v !== undefined)),
1305
- };
1306
- };
1307
-
1211
+ const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
1308
1212
  /**
1309
- * Zod schemas for programmatic GetDotenv options.
1213
+ * Resolve an optional flag with "--exclude-all" overrides.
1214
+ * If excludeAll is set and the individual "...-off" is not, force true.
1215
+ * If excludeAllOff is set and the individual flag is not explicitly set, unset.
1216
+ * Otherwise, adopt the default (true → set; false/undefined → unset).
1217
+ *
1218
+ * @param exclude - Individual include/exclude flag.
1219
+ * @param excludeOff - Individual "...-off" flag.
1220
+ * @param defaultValue - Default for the individual flag.
1221
+ * @param excludeAll - Global "exclude-all" flag.
1222
+ * @param excludeAllOff - Global "exclude-all-off" flag.
1310
1223
  *
1311
- * NOTE: These schemas are introduced without wiring to avoid behavior changes.
1312
- * Legacy paths continue to use existing types/logic. The new plugin host will
1313
- * use these schemas in strict mode; legacy paths will adopt them in warn mode
1314
- * later per the staged plan.
1224
+ * @example
1225
+ * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
1315
1226
  */
1316
- // Minimal process env representation: string values or undefined to indicate "unset".
1317
- const processEnvSchema = z.record(z.string(), z.string().optional());
1318
- // RAW: all fields optional — undefined means "inherit" from lower layers.
1319
- const getDotenvOptionsSchemaRaw = z.object({
1320
- defaultEnv: z.string().optional(),
1321
- dotenvToken: z.string().optional(),
1322
- dynamicPath: z.string().optional(),
1323
- // Dynamic map is intentionally wide for now; refine once sources are normalized.
1324
- dynamic: z.record(z.string(), z.unknown()).optional(),
1325
- env: z.string().optional(),
1326
- excludeDynamic: z.boolean().optional(),
1327
- excludeEnv: z.boolean().optional(),
1328
- excludeGlobal: z.boolean().optional(),
1329
- excludePrivate: z.boolean().optional(),
1330
- excludePublic: z.boolean().optional(),
1331
- loadProcess: z.boolean().optional(),
1332
- log: z.boolean().optional(),
1333
- outputPath: z.string().optional(),
1334
- paths: z.array(z.string()).optional(),
1335
- privateToken: z.string().optional(),
1336
- vars: processEnvSchema.optional(),
1337
- // Host-only feature flag: guarded integration of config loader/overlay
1338
- useConfigLoader: z.boolean().optional(),
1339
- });
1340
- // RESOLVED: service-boundary contract (post-inheritance).
1341
- // For Step A, keep identical to RAW (no behavior change). Later stages will// materialize required defaults and narrow shapes as resolution is wired.
1342
- const getDotenvOptionsSchemaResolved = getDotenvOptionsSchemaRaw;
1343
-
1227
+ const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
1228
+ // Order of precedence:
1229
+ // 1) Individual explicit "on" wins outright.
1230
+ // 2) Individual explicit "off" wins over any global.
1231
+ // 3) Global exclude-all forces true when not explicitly turned off.
1232
+ // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
1233
+ // 5) Fall back to the default (true => set; false/undefined => unset).
1234
+ (() => {
1235
+ // Individual "on"
1236
+ if (exclude === true)
1237
+ return true;
1238
+ // Individual "off"
1239
+ if (excludeOff === true)
1240
+ return undefined;
1241
+ // Global "exclude-all" ON (unless explicitly turned off)
1242
+ if (excludeAll === true)
1243
+ return true;
1244
+ // Global "exclude-all-off" (unless explicitly enabled)
1245
+ if (excludeAllOff === true)
1246
+ return undefined;
1247
+ // Default
1248
+ return defaultValue ? true : undefined;
1249
+ })();
1344
1250
  /**
1345
- * Zod schemas for configuration files discovered by the new loader.
1251
+ * exactOptionalPropertyTypes-safe setter for optional boolean flags:
1252
+ * delete when undefined; assign when defined — without requiring an index signature on T.
1253
+ *
1254
+ * @typeParam T - Target object type.
1255
+ * @param obj - The object to write to.
1256
+ * @param key - The optional boolean property key of {@link T}.
1257
+ * @param value - The value to set or `undefined` to unset.
1346
1258
  *
1347
- * Notes:
1348
- * - RAW: all fields optional; shapes are stringly-friendly (paths may be string[] or string).
1349
- * - RESOLVED: normalized shapes (paths always string[]).
1350
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS-only).
1259
+ * @remarks
1260
+ * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
1351
1261
  */
1352
- // String-only env value map
1353
- const stringMap = z.record(z.string(), z.string());
1354
- const envStringMap = z.record(z.string(), stringMap);
1355
- // Allow string[] or single string for "paths" in RAW; normalize later.
1356
- const rawPathsSchema = z.union([z.array(z.string()), z.string()]).optional();
1357
- const getDotenvConfigSchemaRaw = z.object({
1358
- dotenvToken: z.string().optional(),
1359
- privateToken: z.string().optional(),
1360
- paths: rawPathsSchema,
1361
- loadProcess: z.boolean().optional(),
1362
- log: z.boolean().optional(),
1363
- shell: z.union([z.string(), z.boolean()]).optional(),
1364
- scripts: z.record(z.string(), z.unknown()).optional(), // Scripts validation left wide; generator validates elsewhere
1365
- requiredKeys: z.array(z.string()).optional(),
1366
- schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
1367
- vars: stringMap.optional(), // public, global
1368
- envVars: envStringMap.optional(), // public, per-env
1369
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
1370
- dynamic: z.unknown().optional(),
1371
- // Per-plugin config bag; validated by plugins/host when used.
1372
- plugins: z.record(z.string(), z.unknown()).optional(),
1373
- });
1374
- // Normalize paths to string[]
1375
- const normalizePaths = (p) => p === undefined ? undefined : Array.isArray(p) ? p : [p];
1376
- const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => ({
1377
- ...raw,
1378
- paths: normalizePaths(raw.paths),
1379
- }));
1380
-
1381
- // Discovery candidates (first match wins per scope/privacy).
1382
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
1383
- const PUBLIC_FILENAMES = [
1384
- 'getdotenv.config.json',
1385
- 'getdotenv.config.yaml',
1386
- 'getdotenv.config.yml',
1387
- 'getdotenv.config.js',
1388
- 'getdotenv.config.mjs',
1389
- 'getdotenv.config.cjs',
1390
- 'getdotenv.config.ts',
1391
- 'getdotenv.config.mts',
1392
- 'getdotenv.config.cts',
1393
- ];
1394
- const LOCAL_FILENAMES = [
1395
- 'getdotenv.config.local.json',
1396
- 'getdotenv.config.local.yaml',
1397
- 'getdotenv.config.local.yml',
1398
- 'getdotenv.config.local.js',
1399
- 'getdotenv.config.local.mjs',
1400
- 'getdotenv.config.local.cjs',
1401
- 'getdotenv.config.local.ts',
1402
- 'getdotenv.config.local.mts',
1403
- 'getdotenv.config.local.cts',
1404
- ];
1405
- const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
1406
- const isJson = (p) => extname(p).toLowerCase() === '.json';
1407
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
1408
- // --- Internal JS/TS module loader helpers (default export) ---
1409
- const importDefault$1 = async (fileUrl) => {
1410
- const mod = (await import(fileUrl));
1411
- return mod.default;
1412
- };
1413
- const cacheName = (absPath, suffix) => {
1414
- // sanitized filename with suffix; recompile on mtime changes not tracked here (simplified)
1415
- const base = path.basename(absPath).replace(/[^a-zA-Z0-9._-]/g, '_');
1416
- return `${base}.${suffix}.mjs`;
1417
- };
1418
- const ensureDir$1 = async (dir) => {
1419
- await fs.ensureDir(dir);
1420
- return dir;
1421
- };
1422
- const loadJsTsDefault = async (absPath) => {
1423
- const fileUrl = pathToFileURL(absPath).toString();
1424
- const ext = extname(absPath).toLowerCase();
1425
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
1426
- return importDefault$1(fileUrl);
1427
- }
1428
- // Try direct import first in case a TS loader is active.
1429
- try {
1430
- const val = await importDefault$1(fileUrl);
1431
- if (val)
1432
- return val;
1433
- }
1434
- catch {
1435
- /* fallthrough */
1436
- }
1437
- // esbuild bundle to a temp ESM file
1438
- try {
1439
- const esbuild = (await import('esbuild'));
1440
- const outDir = await ensureDir$1(path.resolve('.tsbuild', 'getdotenv-config'));
1441
- const outfile = path.join(outDir, cacheName(absPath, 'bundle'));
1442
- await esbuild.build({
1443
- entryPoints: [absPath],
1444
- bundle: true,
1445
- platform: 'node',
1446
- format: 'esm',
1447
- target: 'node20',
1448
- outfile,
1449
- sourcemap: false,
1450
- logLevel: 'silent',
1451
- });
1452
- return await importDefault$1(pathToFileURL(outfile).toString());
1453
- }
1454
- catch {
1455
- /* fallthrough to TS transpile */
1456
- }
1457
- // typescript.transpileModule simple transpile (single-file)
1458
- try {
1459
- const ts = (await import('typescript'));
1460
- const src = await fs.readFile(absPath, 'utf-8');
1461
- const out = ts.transpileModule(src, {
1462
- compilerOptions: {
1463
- module: 'ESNext',
1464
- target: 'ES2022',
1465
- moduleResolution: 'NodeNext',
1466
- },
1467
- }).outputText;
1468
- const outDir = await ensureDir$1(path.resolve('.tsbuild', 'getdotenv-config'));
1469
- const outfile = path.join(outDir, cacheName(absPath, 'ts'));
1470
- await fs.writeFile(outfile, out, 'utf-8');
1471
- return await importDefault$1(pathToFileURL(outfile).toString());
1472
- }
1473
- catch {
1474
- throw new Error(`Unable to load JS/TS config: ${absPath}. Install 'esbuild' for robust bundling or ensure a TS loader.`);
1475
- }
1476
- };
1477
- /**
1478
- * Discover JSON/YAML config files in the packaged root and project root.
1479
- * Order: packaged public → project public → project local. */
1480
- const discoverConfigFiles = async (importMetaUrl) => {
1481
- const files = [];
1482
- // Packaged root via importMetaUrl (optional)
1483
- if (importMetaUrl) {
1484
- const fromUrl = fileURLToPath(importMetaUrl);
1485
- const packagedRoot = await packageDirectory({ cwd: fromUrl });
1486
- if (packagedRoot) {
1487
- for (const name of PUBLIC_FILENAMES) {
1488
- const p = join(packagedRoot, name);
1489
- if (await fs.pathExists(p)) {
1490
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
1491
- break; // only one public file expected per scope
1492
- }
1493
- }
1494
- // By policy, packaged .local is not expected; skip even if present.
1495
- }
1496
- }
1497
- // Project root (from current working directory)
1498
- const projectRoot = await packageDirectory();
1499
- if (projectRoot) {
1500
- for (const name of PUBLIC_FILENAMES) {
1501
- const p = join(projectRoot, name);
1502
- if (await fs.pathExists(p)) {
1503
- files.push({ path: p, privacy: 'public', scope: 'project' });
1504
- break;
1505
- }
1506
- }
1507
- for (const name of LOCAL_FILENAMES) {
1508
- const p = join(projectRoot, name);
1509
- if (await fs.pathExists(p)) {
1510
- files.push({ path: p, privacy: 'local', scope: 'project' });
1511
- break;
1512
- }
1513
- }
1514
- }
1515
- return files;
1262
+ const setOptionalFlag = (obj, key, value) => {
1263
+ const target = obj;
1264
+ const k = key;
1265
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1266
+ if (value === undefined)
1267
+ delete target[k];
1268
+ else
1269
+ target[k] = value;
1516
1270
  };
1271
+
1517
1272
  /**
1518
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
1519
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
1520
- *
1521
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
1522
- * For JS/TS: default export is loaded; "dynamic" is allowed.
1273
+ * Merge and normalize raw Commander options (current + parent + defaults)
1274
+ * into a GetDotenvCliOptions-like object. Types are intentionally wide to
1275
+ * avoid cross-layer coupling; callers may cast as needed.
1523
1276
  */
1524
- const loadConfigFile = async (filePath) => {
1525
- let raw = {};
1526
- try {
1527
- const abs = path.resolve(filePath);
1528
- if (isJsOrTs(abs)) {
1529
- // JS/TS support: load default export via robust pipeline.
1530
- const mod = await loadJsTsDefault(abs);
1531
- raw = mod ?? {};
1277
+ const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
1278
+ const parent = typeof parentJson === 'string' && parentJson.length > 0
1279
+ ? JSON.parse(parentJson)
1280
+ : undefined;
1281
+ const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
1282
+ const current = { ...rest };
1283
+ if (typeof scripts === 'string') {
1284
+ try {
1285
+ current.scripts = JSON.parse(scripts);
1532
1286
  }
1533
- else {
1534
- const txt = await fs.readFile(abs, 'utf-8');
1535
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
1287
+ catch {
1288
+ // ignore parse errors; leave scripts undefined
1536
1289
  }
1537
1290
  }
1538
- catch (err) {
1539
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
1540
- }
1541
- // Validate RAW
1542
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
1543
- if (!parsed.success) {
1544
- const msgs = parsed.error.issues
1545
- .map((i) => `${i.path.join('.')}: ${i.message}`)
1546
- .join('\n');
1547
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
1548
- }
1549
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
1550
- if (!isJsOrTs(filePath) &&
1551
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
1552
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
1553
- `Use JS/TS config for "dynamic" or "schema".`);
1291
+ const merged = defaultsDeep({}, defaults, parent ?? {}, current);
1292
+ const d = defaults;
1293
+ setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
1294
+ setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
1295
+ setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
1296
+ setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
1297
+ setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
1298
+ setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
1299
+ setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
1300
+ setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
1301
+ // warnEntropy (tri-state)
1302
+ setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
1303
+ // Normalize shell for predictability: explicit default shell per OS.
1304
+ const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
1305
+ let resolvedShell = merged.shell;
1306
+ if (shellOff)
1307
+ resolvedShell = false;
1308
+ else if (resolvedShell === true || resolvedShell === undefined) {
1309
+ resolvedShell = defaultShell;
1554
1310
  }
1555
- return getDotenvConfigSchemaResolved.parse(parsed.data);
1556
- };
1557
- /**
1558
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
1559
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
1560
- */
1561
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
1562
- const discovered = await discoverConfigFiles(importMetaUrl);
1563
- const result = {};
1564
- for (const f of discovered) {
1565
- const cfg = await loadConfigFile(f.path);
1566
- if (f.scope === 'packaged') {
1567
- // packaged public only
1568
- result.packaged = cfg;
1569
- }
1570
- else {
1571
- result.project ??= {};
1572
- if (f.privacy === 'public')
1573
- result.project.public = cfg;
1574
- else
1575
- result.project.local = cfg;
1576
- }
1311
+ else if (typeof resolvedShell !== 'string' &&
1312
+ typeof defaults.shell === 'string') {
1313
+ resolvedShell = defaults.shell;
1577
1314
  }
1578
- return result;
1315
+ merged.shell = resolvedShell;
1316
+ const cmd = typeof command === 'string' ? command : undefined;
1317
+ return cmd !== undefined ? { merged, command: cmd } : { merged };
1579
1318
  };
1580
1319
 
1581
1320
  /**
@@ -1664,39 +1403,6 @@ const dotenvExpand = (value, ref = process.env) => {
1664
1403
  const result = interpolate(value, ref);
1665
1404
  return result ? result.replace(/\\\$/g, '$') : undefined;
1666
1405
  };
1667
- /**
1668
- * Recursively expands environment variables in the values of a JSON object.
1669
- * Variables may be presented with optional default as `$VAR[:default]` or
1670
- * `${VAR[:default]}`. Unknown variables will expand to an empty string.
1671
- *
1672
- * @param values - The values object to expand.
1673
- * @param options - Expansion options.
1674
- * @returns The value object with expanded string values.
1675
- *
1676
- * @example
1677
- * ```ts
1678
- * process.env.FOO = 'bar';
1679
- * dotenvExpandAll({ A: '$FOO', B: 'x${FOO}y' });
1680
- * // => { A: "bar", B: "xbary" }
1681
- * ```
1682
- *
1683
- * @remarks
1684
- * Options:
1685
- * - ref: The reference object to use for expansion (defaults to process.env).
1686
- * - progressive: Whether to progressively add expanded values to the set of
1687
- * reference keys.
1688
- *
1689
- * When `progressive` is true, each expanded key becomes available for
1690
- * subsequent expansions in the same object (left-to-right by object key order).
1691
- */
1692
- const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduce((acc, key) => {
1693
- const { ref = process.env, progressive = false } = options;
1694
- acc[key] = dotenvExpand(values[key], {
1695
- ...ref,
1696
- ...(progressive ? acc : {}),
1697
- });
1698
- return acc;
1699
- }, {});
1700
1406
  /**
1701
1407
  * Recursively expands environment variables in a string using `process.env` as
1702
1408
  * the expansion reference. Variables may be presented with optional default as
@@ -1714,1157 +1420,61 @@ const dotenvExpandAll = (values = {}, options = {}) => Object.keys(values).reduc
1714
1420
  */
1715
1421
  const dotenvExpandFromProcessEnv = (value) => dotenvExpand(value, process.env);
1716
1422
 
1717
- const applyKv = (current, kv) => {
1718
- if (!kv || Object.keys(kv).length === 0)
1719
- return current;
1720
- const expanded = dotenvExpandAll(kv, { ref: current, progressive: true });
1721
- return { ...current, ...expanded };
1722
- };
1723
- const applyConfigSlice = (current, cfg, env) => {
1724
- if (!cfg)
1725
- return current;
1726
- // kind axis: global then env (env overrides global)
1727
- const afterGlobal = applyKv(current, cfg.vars);
1728
- const envKv = env && cfg.envVars ? cfg.envVars[env] : undefined;
1729
- return applyKv(afterGlobal, envKv);
1730
- };
1731
- /**
1732
- * Overlay config-provided values onto a base ProcessEnv using precedence axes:
1733
- * - kind: env \> global
1734
- * - privacy: local \> public
1735
- * - source: project \> packaged \> base
1736
- *
1737
- * Programmatic explicit vars (if provided) override all config slices.
1738
- * Progressive expansion is applied within each slice.
1739
- */
1740
- const overlayEnv = ({ base, env, configs, programmaticVars, }) => {
1741
- let current = { ...base };
1742
- // Source: packaged (public -> local)
1743
- current = applyConfigSlice(current, configs.packaged, env);
1744
- // Packaged "local" is not expected by policy; if present, honor it.
1745
- // We do not have a separate object for packaged.local in sources, keep as-is.
1746
- // Source: project (public -> local)
1747
- current = applyConfigSlice(current, configs.project?.public, env);
1748
- current = applyConfigSlice(current, configs.project?.local, env);
1749
- // Programmatic explicit vars (top of static tier)
1750
- if (programmaticVars) {
1751
- const toApply = Object.fromEntries(Object.entries(programmaticVars).filter(([_k, v]) => typeof v === 'string'));
1752
- current = applyKv(current, toApply);
1753
- }
1754
- return current;
1755
- };
1756
-
1423
+ // src/GetDotenvOptions.ts
1757
1424
  /**
1758
- * Asynchronously read a dotenv file & parse it into an object.
1425
+ * Converts programmatic CLI options to `getDotenv` options. *
1426
+ * @param cliOptions - CLI options. Defaults to `{}`.
1759
1427
  *
1760
- * @param path - Path to dotenv file.
1761
- * @returns The parsed dotenv object.
1428
+ * @returns `getDotenv` options.
1762
1429
  */
1763
- const readDotenv = async (path) => {
1764
- try {
1765
- return (await fs.exists(path)) ? parse(await fs.readFile(path)) : {};
1766
- }
1767
- catch {
1768
- return {};
1769
- }
1770
- };
1771
-
1772
- const importDefault = async (fileUrl) => {
1773
- const mod = (await import(fileUrl));
1774
- return mod.default;
1775
- };
1776
- const cacheHash = (absPath, mtimeMs) => createHash('sha1')
1777
- .update(absPath)
1778
- .update(String(mtimeMs))
1779
- .digest('hex')
1780
- .slice(0, 12);
1781
- /**
1782
- * Remove older compiled cache files for a given source base name, keeping
1783
- * at most `keep` most-recent files. Errors are ignored by design.
1784
- */
1785
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
1786
- try {
1787
- const entries = await fs.readdir(cacheDir);
1788
- const mine = entries
1789
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
1790
- .map((f) => path.join(cacheDir, f));
1791
- if (mine.length <= keep)
1792
- return;
1793
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
1794
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
1795
- const toDelete = stats.slice(keep).map((s) => s.p);
1796
- await Promise.all(toDelete.map(async (p) => {
1797
- try {
1798
- await fs.remove(p);
1799
- }
1800
- catch {
1801
- // best-effort cleanup
1802
- }
1803
- }));
1804
- }
1805
- catch {
1806
- // best-effort cleanup
1807
- }
1808
- };
1809
- /**
1810
- * Load a module default export from a JS/TS file with robust fallbacks:
1811
- * - .js/.mjs/.cjs: direct import * - .ts/.mts/.cts/.tsx:
1812
- * 1) try direct import (if a TS loader is active),
1813
- * 2) esbuild bundle to a temp ESM file,
1814
- * 3) typescript.transpileModule fallback for simple modules.
1815
- *
1816
- * @param absPath - absolute path to source file
1817
- * @param cacheDirName - cache subfolder under .tsbuild
1818
- */
1819
- const loadModuleDefault = async (absPath, cacheDirName) => {
1820
- const ext = path.extname(absPath).toLowerCase();
1821
- const fileUrl = url.pathToFileURL(absPath).toString();
1822
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
1823
- return importDefault(fileUrl);
1824
- }
1825
- // Try direct import first (TS loader active)
1826
- try {
1827
- const dyn = await importDefault(fileUrl);
1828
- if (dyn)
1829
- return dyn;
1830
- }
1831
- catch {
1832
- /* fall through */
1833
- }
1834
- const stat = await fs.stat(absPath);
1835
- const hash = cacheHash(absPath, stat.mtimeMs);
1836
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
1837
- await fs.ensureDir(cacheDir);
1838
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
1839
- // Try esbuild
1840
- try {
1841
- const esbuild = (await import('esbuild'));
1842
- await esbuild.build({
1843
- entryPoints: [absPath],
1844
- bundle: true,
1845
- platform: 'node',
1846
- format: 'esm',
1847
- target: 'node20',
1848
- outfile: cacheFile,
1849
- sourcemap: false,
1850
- logLevel: 'silent',
1851
- });
1852
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1853
- // Best-effort: trim older cache files for this source.
1854
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1855
- return result;
1856
- }
1857
- catch {
1858
- /* fall through to TS transpile */
1859
- }
1860
- // TypeScript transpile fallback
1861
- try {
1862
- const ts = (await import('typescript'));
1863
- const code = await fs.readFile(absPath, 'utf-8');
1864
- const out = ts.transpileModule(code, {
1865
- compilerOptions: {
1866
- module: 'ESNext',
1867
- target: 'ES2022',
1868
- moduleResolution: 'NodeNext',
1869
- },
1870
- }).outputText;
1871
- await fs.writeFile(cacheFile, out, 'utf-8');
1872
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
1873
- // Best-effort: trim older cache files for this source.
1874
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
1875
- return result;
1876
- }
1877
- catch {
1878
- // Caller decides final error wording; rethrow for upstream mapping.
1879
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
1880
- }
1881
- };
1882
-
1883
- /**
1884
- * Asynchronously process dotenv files of the form `.env[.<ENV>][.<PRIVATE_TOKEN>]`
1885
- *
1886
- * @param options - `GetDotenvOptions` object
1887
- * @returns The combined parsed dotenv object.
1888
- * * @example Load from the project root with default tokens
1889
- * ```ts
1890
- * const vars = await getDotenv();
1891
- * console.log(vars.MY_SETTING);
1892
- * ```
1893
- *
1894
- * @example Load from multiple paths and a specific environment
1895
- * ```ts
1896
- * const vars = await getDotenv({
1897
- * env: 'dev',
1898
- * dotenvToken: '.testenv',
1899
- * privateToken: 'secret',
1900
- * paths: ['./', './packages/app'],
1901
- * });
1902
- * ```
1903
- *
1904
- * @example Use dynamic variables
1905
- * ```ts
1906
- * // .env.js default-exports: { DYNAMIC: ({ PREV }) => `${PREV}-suffix` }
1907
- * const vars = await getDotenv({ dynamicPath: '.env.js' });
1908
- * ```
1909
- *
1910
- * @remarks
1911
- * - When {@link GetDotenvOptions.loadProcess} is true, the resulting variables are merged
1912
- * into `process.env` as a side effect.
1913
- * - When {@link GetDotenvOptions.outputPath} is provided, a consolidated dotenv file is written.
1914
- * The path is resolved after expansion, so it may reference previously loaded vars.
1915
- *
1916
- * @throws Error when a dynamic module is present but cannot be imported.
1917
- * @throws Error when an output path was requested but could not be resolved.
1918
- */
1919
- const getDotenv = async (options = {}) => {
1920
- // Apply defaults.
1921
- 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);
1922
- // Read .env files.
1923
- const loaded = paths.length
1924
- ? await paths.reduce(async (e, p) => {
1925
- const publicGlobal = excludePublic || excludeGlobal
1926
- ? Promise.resolve({})
1927
- : readDotenv(path.resolve(p, dotenvToken));
1928
- const publicEnv = excludePublic || excludeEnv || (!env && !defaultEnv)
1929
- ? Promise.resolve({})
1930
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}`));
1931
- const privateGlobal = excludePrivate || excludeGlobal
1932
- ? Promise.resolve({})
1933
- : readDotenv(path.resolve(p, `${dotenvToken}.${privateToken}`));
1934
- const privateEnv = excludePrivate || excludeEnv || (!env && !defaultEnv)
1935
- ? Promise.resolve({})
1936
- : readDotenv(path.resolve(p, `${dotenvToken}.${env ?? defaultEnv ?? ''}.${privateToken}`));
1937
- const [eResolved, publicGlobalResolved, publicEnvResolved, privateGlobalResolved, privateEnvResolved,] = await Promise.all([
1938
- e,
1939
- publicGlobal,
1940
- publicEnv,
1941
- privateGlobal,
1942
- privateEnv,
1943
- ]);
1944
- return {
1945
- ...eResolved,
1946
- ...publicGlobalResolved,
1947
- ...publicEnvResolved,
1948
- ...privateGlobalResolved,
1949
- ...privateEnvResolved,
1950
- };
1951
- }, Promise.resolve({}))
1952
- : {};
1953
- const outputKey = nanoid();
1954
- const dotenv = dotenvExpandAll({
1955
- ...loaded,
1956
- ...vars,
1957
- ...(outputPath ? { [outputKey]: outputPath } : {}),
1958
- }, { progressive: true });
1959
- // Process dynamic variables. Programmatic option takes precedence over path.
1960
- if (!excludeDynamic) {
1961
- let dynamic = undefined;
1962
- if (options.dynamic && Object.keys(options.dynamic).length > 0) {
1963
- dynamic = options.dynamic;
1964
- }
1965
- else if (dynamicPath) {
1966
- const absDynamicPath = path.resolve(dynamicPath);
1967
- if (await fs.exists(absDynamicPath)) {
1968
- try {
1969
- dynamic = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic');
1970
- }
1971
- catch {
1972
- // Preserve legacy error text for compatibility with tests/docs.
1973
- throw new Error(`Unable to load dynamic TypeScript file: ${absDynamicPath}. ` +
1974
- `Install 'esbuild' (devDependency) to enable TypeScript dynamic modules.`);
1975
- }
1976
- }
1977
- }
1978
- if (dynamic) {
1979
- try {
1980
- for (const key in dynamic)
1981
- Object.assign(dotenv, {
1982
- [key]: typeof dynamic[key] === 'function'
1983
- ? dynamic[key](dotenv, env ?? defaultEnv)
1984
- : dynamic[key],
1985
- });
1986
- }
1987
- catch {
1988
- throw new Error(`Unable to evaluate dynamic variables.`);
1989
- }
1990
- }
1991
- }
1992
- // Write output file.
1993
- let resultDotenv = dotenv;
1994
- if (outputPath) {
1995
- const outputPathResolved = dotenv[outputKey];
1996
- if (!outputPathResolved)
1997
- throw new Error('Output path not found.');
1998
- const { [outputKey]: _omitted, ...dotenvForOutput } = dotenv;
1999
- await fs.writeFile(outputPathResolved, Object.keys(dotenvForOutput).reduce((contents, key) => {
2000
- const value = dotenvForOutput[key] ?? '';
2001
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
2002
- }, ''), { encoding: 'utf-8' });
2003
- resultDotenv = dotenvForOutput;
2004
- }
2005
- // Log result.
2006
- if (log) {
2007
- const redactFlag = options.redact ?? false;
2008
- const redactPatterns = options.redactPatterns ?? undefined;
2009
- const redOpts = {};
2010
- if (redactFlag)
2011
- redOpts.redact = true;
2012
- if (redactFlag && Array.isArray(redactPatterns))
2013
- redOpts.redactPatterns = redactPatterns;
2014
- const bag = redactFlag
2015
- ? redactObject(resultDotenv, redOpts)
2016
- : { ...resultDotenv };
2017
- logger.log(bag);
2018
- // Entropy warnings: once-per-key-per-run (presentation only)
2019
- const warnEntropyVal = options.warnEntropy ?? true;
2020
- const entropyThresholdVal = options
2021
- .entropyThreshold;
2022
- const entropyMinLengthVal = options
2023
- .entropyMinLength;
2024
- const entropyWhitelistVal = options
2025
- .entropyWhitelist;
2026
- const entOpts = {};
2027
- if (typeof warnEntropyVal === 'boolean')
2028
- entOpts.warnEntropy = warnEntropyVal;
2029
- if (typeof entropyThresholdVal === 'number')
2030
- entOpts.entropyThreshold = entropyThresholdVal;
2031
- if (typeof entropyMinLengthVal === 'number')
2032
- entOpts.entropyMinLength = entropyMinLengthVal;
2033
- if (Array.isArray(entropyWhitelistVal))
2034
- entOpts.entropyWhitelist = entropyWhitelistVal;
2035
- for (const [k, v] of Object.entries(resultDotenv)) {
2036
- maybeWarnEntropy(k, v, v !== undefined ? 'dotenv' : 'unset', entOpts, (line) => {
2037
- logger.log(line);
2038
- });
2039
- }
2040
- }
2041
- // Load process.env.
2042
- if (loadProcess)
2043
- Object.assign(process.env, resultDotenv);
2044
- return resultDotenv;
2045
- };
2046
-
2047
- /**
2048
- * Deep interpolation utility for string leaves.
2049
- * - Expands string values using dotenv-style expansion against the provided envRef.
2050
- * - Preserves non-strings as-is.
2051
- * - Does not recurse into arrays (arrays are returned unchanged).
2052
- *
2053
- * Intended for:
2054
- * - Phase C option/config interpolation after composing ctx.dotenv.
2055
- * - Per-plugin config slice interpolation before afterResolve.
2056
- */
2057
- /** @internal */
2058
- const isPlainObject = (v) => v !== null &&
2059
- typeof v === 'object' &&
2060
- !Array.isArray(v) &&
2061
- Object.getPrototypeOf(v) === Object.prototype;
2062
- /**
2063
- * Deeply interpolate string leaves against envRef.
2064
- * Arrays are not recursed into; they are returned unchanged.
2065
- *
2066
- * @typeParam T - Shape of the input value.
2067
- * @param value - Input value (object/array/primitive).
2068
- * @param envRef - Reference environment for interpolation.
2069
- * @returns A new value with string leaves interpolated.
2070
- */
2071
- const interpolateDeep = (value, envRef) => {
2072
- // Strings: expand and return
2073
- if (typeof value === 'string') {
2074
- const out = dotenvExpand(value, envRef);
2075
- // dotenvExpand returns string | undefined; preserve original on undefined
2076
- return (out ?? value);
2077
- }
2078
- // Arrays: return as-is (no recursion)
2079
- if (Array.isArray(value)) {
2080
- return value;
2081
- }
2082
- // Plain objects: shallow clone and recurse into values
2083
- if (isPlainObject(value)) {
2084
- const src = value;
2085
- const out = {};
2086
- for (const [k, v] of Object.entries(src)) {
2087
- // Recurse for strings/objects; keep arrays as-is; preserve other scalars
2088
- if (typeof v === 'string')
2089
- out[k] = dotenvExpand(v, envRef) ?? v;
2090
- else if (Array.isArray(v))
2091
- out[k] = v;
2092
- else if (isPlainObject(v))
2093
- out[k] = interpolateDeep(v, envRef);
2094
- else
2095
- out[k] = v;
2096
- }
2097
- return out;
2098
- }
2099
- // Other primitives/types: return as-is
2100
- return value;
2101
- };
2102
-
2103
- /**
2104
- * Compute the dotenv context for the host (uses the config loader/overlay path).
2105
- * - Resolves and validates options strictly (host-only).
2106
- * - Applies file cascade, overlays, dynamics, and optional effects.
2107
- * - Merges and validates per-plugin config slices (when provided).
2108
- *
2109
- * @param customOptions - Partial options from the current invocation.
2110
- * @param plugins - Installed plugins (for config validation).
2111
- * @param hostMetaUrl - import.meta.url of the host module (for packaged root discovery). */
2112
- const computeContext = async (customOptions, plugins, hostMetaUrl) => {
2113
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
2114
- const validated = getDotenvOptionsSchemaResolved.parse(optionsResolved);
2115
- // Always-on loader path
2116
- // 1) Base from files only (no dynamic, no programmatic vars)
2117
- const base = await getDotenv({
2118
- ...validated,
2119
- // Build a pure base without side effects or logging.
2120
- excludeDynamic: true,
2121
- vars: {},
2122
- log: false,
2123
- loadProcess: false,
2124
- outputPath: undefined,
2125
- });
2126
- // 2) Discover config sources and overlay
2127
- const sources = await resolveGetDotenvConfigSources(hostMetaUrl);
2128
- const dotenvOverlaid = overlayEnv({
2129
- base,
2130
- env: validated.env ?? validated.defaultEnv,
2131
- configs: sources,
2132
- ...(validated.vars ? { programmaticVars: validated.vars } : {}),
2133
- });
2134
- // Helper to apply a dynamic map progressively.
2135
- const applyDynamic = (target, dynamic, env) => {
2136
- if (!dynamic)
2137
- return;
2138
- for (const key of Object.keys(dynamic)) {
2139
- const value = typeof dynamic[key] === 'function'
2140
- ? dynamic[key](target, env)
2141
- : dynamic[key];
2142
- Object.assign(target, { [key]: value });
2143
- }
2144
- };
2145
- // 3) Apply dynamics in order
2146
- const dotenv = { ...dotenvOverlaid };
2147
- applyDynamic(dotenv, validated.dynamic, validated.env ?? validated.defaultEnv);
2148
- applyDynamic(dotenv, (sources.packaged?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
2149
- applyDynamic(dotenv, (sources.project?.public?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
2150
- applyDynamic(dotenv, (sources.project?.local?.dynamic ?? undefined), validated.env ?? validated.defaultEnv);
2151
- // file dynamicPath (lowest)
2152
- if (validated.dynamicPath) {
2153
- const absDynamicPath = path.resolve(validated.dynamicPath);
2154
- try {
2155
- const dyn = await loadModuleDefault(absDynamicPath, 'getdotenv-dynamic-host');
2156
- applyDynamic(dotenv, dyn, validated.env ?? validated.defaultEnv);
2157
- }
2158
- catch {
2159
- throw new Error(`Unable to load dynamic from ${validated.dynamicPath}`);
2160
- }
2161
- }
2162
- // 4) Output/log/process merge
2163
- if (validated.outputPath) {
2164
- await fs.writeFile(validated.outputPath, Object.keys(dotenv).reduce((contents, key) => {
2165
- const value = dotenv[key] ?? '';
2166
- return `${contents}${key}=${value.includes('\n') ? `"${value}"` : value}\n`;
2167
- }, ''), { encoding: 'utf-8' });
2168
- }
2169
- const logger = validated.logger ?? console;
2170
- if (validated.log)
2171
- logger.log(dotenv);
2172
- if (validated.loadProcess)
2173
- Object.assign(process.env, dotenv);
2174
- // 5) Merge and validate per-plugin config (packaged < project.public < project.local)
2175
- const packagedPlugins = (sources.packaged &&
2176
- sources.packaged.plugins) ??
2177
- {};
2178
- const publicPlugins = (sources.project?.public &&
2179
- sources.project.public.plugins) ??
2180
- {};
2181
- const localPlugins = (sources.project?.local &&
2182
- sources.project.local.plugins) ??
2183
- {};
2184
- const mergedPluginConfigs = defaultsDeep({}, packagedPlugins, publicPlugins, localPlugins);
2185
- for (const p of plugins) {
2186
- if (!p.id)
2187
- continue;
2188
- const slice = mergedPluginConfigs[p.id];
2189
- if (slice === undefined)
2190
- continue;
2191
- // Per-plugin interpolation just before validation/afterResolve:
2192
- // precedence: process.env wins over ctx.dotenv for slice defaults.
2193
- const envRef = {
2194
- ...dotenv,
2195
- ...process.env,
2196
- };
2197
- const interpolated = interpolateDeep(slice, envRef);
2198
- // Validate if a schema is provided; otherwise accept interpolated slice as-is.
2199
- if (p.configSchema) {
2200
- const parsed = p.configSchema.safeParse(interpolated);
2201
- if (!parsed.success) {
2202
- const msgs = parsed.error.issues
2203
- .map((i) => `${i.path.join('.')}: ${i.message}`)
2204
- .join('\n');
2205
- throw new Error(`Invalid config for plugin '${p.id}':\n${msgs}`);
2206
- }
2207
- mergedPluginConfigs[p.id] = parsed.data;
2208
- }
2209
- else {
2210
- mergedPluginConfigs[p.id] = interpolated;
2211
- }
2212
- }
2213
- return {
2214
- optionsResolved: validated,
2215
- dotenv: dotenv,
2216
- plugins: {},
2217
- pluginConfigs: mergedPluginConfigs,
2218
- };
2219
- };
2220
-
2221
- const HOST_META_URL = import.meta.url;
2222
- const CTX_SYMBOL = Symbol('GetDotenvCli.ctx');
2223
- const OPTS_SYMBOL = Symbol('GetDotenvCli.options');
2224
- const HELP_HEADER_SYMBOL = Symbol('GetDotenvCli.helpHeader');
2225
- /**
2226
- * Plugin-first CLI host for get-dotenv. Extends Commander.Command.
2227
- *
2228
- * Responsibilities:
2229
- * - Resolve options strictly and compute dotenv context (resolveAndLoad).
2230
- * - Expose a stable accessor for the current context (getCtx).
2231
- * - Provide a namespacing helper (ns).
2232
- * - Support composable plugins with parent → children install and afterResolve.
2233
- *
2234
- * NOTE: This host is additive and does not alter the legacy CLI.
2235
- */
2236
- class GetDotenvCli extends Command {
2237
- /** Registered top-level plugins (composition happens via .use()) */
2238
- _plugins = [];
2239
- /** One-time installation guard */
2240
- _installed = false;
2241
- /** Optional header line to prepend in help output */
2242
- [HELP_HEADER_SYMBOL];
2243
- constructor(alias = 'getdotenv') {
2244
- super(alias);
2245
- // Ensure subcommands that use passThroughOptions can be attached safely.
2246
- // Commander requires parent commands to enable positional options when a
2247
- // child uses passThroughOptions.
2248
- this.enablePositionalOptions();
2249
- // Configure grouped help: show only base options in default "Options";
2250
- // append App/Plugin sections after default help.
2251
- this.configureHelp({
2252
- visibleOptions: (cmd) => {
2253
- const all = cmd.options ??
2254
- [];
2255
- const base = all.filter((opt) => {
2256
- const group = opt.__group;
2257
- return group === 'base';
2258
- });
2259
- // Sort: short-aliased options first, then long-only; stable by flags.
2260
- const hasShort = (opt) => {
2261
- const flags = opt.flags ?? '';
2262
- // Matches "-x," or starting "-x " before any long
2263
- return /(^|\s|,)-[A-Za-z]/.test(flags);
2264
- };
2265
- const byFlags = (opt) => opt.flags ?? '';
2266
- base.sort((a, b) => {
2267
- const aS = hasShort(a) ? 1 : 0;
2268
- const bS = hasShort(b) ? 1 : 0;
2269
- return bS - aS || byFlags(a).localeCompare(byFlags(b));
2270
- });
2271
- return base;
2272
- },
2273
- });
2274
- this.addHelpText('beforeAll', () => {
2275
- const header = this[HELP_HEADER_SYMBOL];
2276
- return header && header.length > 0 ? `${header}\n\n` : '';
2277
- });
2278
- this.addHelpText('afterAll', (ctx) => this.#renderOptionGroups(ctx.command));
2279
- // Skeleton preSubcommand hook: produce a context if absent, without
2280
- // mutating process.env. The passOptions hook (when installed) will // compute the final context using merged CLI options; keeping
2281
- // loadProcess=false here avoids leaking dotenv values into the parent
2282
- // process env before subcommands execute.
2283
- this.hook('preSubcommand', async () => {
2284
- if (this.getCtx())
2285
- return;
2286
- await this.resolveAndLoad({ loadProcess: false });
2287
- });
2288
- }
2289
- /**
2290
- * Resolve options (strict) and compute dotenv context. * Stores the context on the instance under a symbol.
2291
- */
2292
- async resolveAndLoad(customOptions = {}) {
2293
- // Resolve defaults, then validate strictly under the new host.
2294
- const optionsResolved = await resolveGetDotenvOptions(customOptions);
2295
- getDotenvOptionsSchemaResolved.parse(optionsResolved);
2296
- // Delegate the heavy lifting to the shared helper (guarded path supported).
2297
- const ctx = await computeContext(optionsResolved, this._plugins, HOST_META_URL);
2298
- // Persist context on the instance for later access.
2299
- this[CTX_SYMBOL] =
2300
- ctx;
2301
- // Ensure plugins are installed exactly once, then run afterResolve.
2302
- await this.install();
2303
- await this._runAfterResolve(ctx);
2304
- return ctx;
2305
- }
2306
- /**
2307
- * Retrieve the current invocation context (if any).
2308
- */
2309
- getCtx() {
2310
- return this[CTX_SYMBOL];
2311
- }
2312
- /**
2313
- * Retrieve the merged root CLI options bag (if set by passOptions()).
2314
- * Downstream-safe: no generics required.
2315
- */
2316
- getOptions() {
2317
- return this[OPTS_SYMBOL];
2318
- }
2319
- /** Internal: set the merged root options bag for this run. */
2320
- _setOptionsBag(bag) {
2321
- this[OPTS_SYMBOL] = bag;
2322
- }
2323
- /** * Convenience helper to create a namespaced subcommand.
2324
- */
2325
- ns(name) {
2326
- return this.command(name);
2327
- }
2328
- /**
2329
- * Tag options added during the provided callback as 'app' for grouped help.
2330
- * Allows downstream apps to demarcate their root-level options.
2331
- */
2332
- tagAppOptions(fn) {
2333
- const root = this;
2334
- const originalAddOption = root.addOption.bind(root);
2335
- const originalOption = root.option.bind(root);
2336
- const tagLatest = (cmd, group) => {
2337
- const optsArr = cmd.options;
2338
- if (Array.isArray(optsArr) && optsArr.length > 0) {
2339
- const last = optsArr[optsArr.length - 1];
2340
- last.__group = group;
2341
- }
2342
- };
2343
- root.addOption = function patchedAdd(opt) {
2344
- opt.__group = 'app';
2345
- return originalAddOption(opt);
2346
- };
2347
- root.option = function patchedOption(...args) {
2348
- const ret = originalOption(...args);
2349
- tagLatest(this, 'app');
2350
- return ret;
2351
- };
2352
- try {
2353
- return fn(root);
2354
- }
2355
- finally {
2356
- root.addOption = originalAddOption;
2357
- root.option = originalOption;
2358
- }
2359
- }
2360
- /**
2361
- * Branding helper: set CLI name/description/version and optional help header.
2362
- * If version is omitted and importMetaUrl is provided, attempts to read the
2363
- * nearest package.json version (best-effort; non-fatal on failure).
2364
- */
2365
- async brand(args) {
2366
- const { name, description, version, importMetaUrl, helpHeader } = args;
2367
- if (typeof name === 'string' && name.length > 0)
2368
- this.name(name);
2369
- if (typeof description === 'string')
2370
- this.description(description);
2371
- let v = version;
2372
- if (!v && importMetaUrl) {
2373
- try {
2374
- const fromUrl = fileURLToPath(importMetaUrl);
2375
- const pkgDir = await packageDirectory({ cwd: fromUrl });
2376
- if (pkgDir) {
2377
- const txt = await fs.readFile(`${pkgDir}/package.json`, 'utf-8');
2378
- const pkg = JSON.parse(txt);
2379
- if (pkg.version)
2380
- v = pkg.version;
2381
- }
2382
- }
2383
- catch {
2384
- // best-effort only
2385
- }
2386
- }
2387
- if (v)
2388
- this.version(v);
2389
- // Help header:
2390
- // - If caller provides helpHeader, use it.
2391
- // - Otherwise, when a version is known, default to "<name> v<version>".
2392
- if (typeof helpHeader === 'string') {
2393
- this[HELP_HEADER_SYMBOL] = helpHeader;
2394
- }
2395
- else if (v) {
2396
- // Use the current command name (possibly overridden by 'name' above).
2397
- const header = `${this.name()} v${v}`;
2398
- this[HELP_HEADER_SYMBOL] = header;
2399
- }
2400
- return this;
2401
- }
2402
- /**
2403
- * Register a plugin for installation (parent level).
2404
- * Installation occurs on first resolveAndLoad() (or explicit install()).
2405
- */
2406
- use(plugin) {
2407
- this._plugins.push(plugin);
2408
- // Immediately run setup so subcommands exist before parsing.
2409
- const setupOne = (p) => {
2410
- p.setup(this);
2411
- for (const child of p.children)
2412
- setupOne(child);
2413
- };
2414
- setupOne(plugin);
2415
- return this;
2416
- }
2417
- /**
2418
- * Install all registered plugins in parent → children (pre-order).
2419
- * Runs only once per CLI instance.
2420
- */
2421
- async install() {
2422
- // Setup is performed immediately in use(); here we only guard for afterResolve.
2423
- this._installed = true;
2424
- // Satisfy require-await without altering behavior.
2425
- await Promise.resolve();
2426
- }
1430
+ const getDotenvCliOptions2Options = ({ paths, pathsDelimiter, pathsDelimiterPattern, vars, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, ...rest }) => {
2427
1431
  /**
2428
- * Run afterResolve hooks for all plugins (parent → children).
1432
+ * Convert CLI-facing string options into {@link GetDotenvOptions}.
1433
+ *
1434
+ * - 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`
1435
+ * pairs (configurable delimiters) into a {@link ProcessEnv}.
1436
+ * - Drops CLI-only keys that have no programmatic equivalent.
1437
+ *
1438
+ * @remarks
1439
+ * Follows exact-optional semantics by not emitting undefined-valued entries.
2429
1440
  */
2430
- async _runAfterResolve(ctx) {
2431
- const run = async (p) => {
2432
- if (p.afterResolve)
2433
- await p.afterResolve(this, ctx);
2434
- for (const child of p.children)
2435
- await run(child);
2436
- };
2437
- for (const p of this._plugins)
2438
- await run(p);
2439
- }
2440
- // Render App/Plugin grouped options appended after default help.
2441
- #renderOptionGroups(cmd) {
2442
- const all = cmd.options ?? [];
2443
- const byGroup = new Map();
2444
- for (const o of all) {
2445
- const opt = o;
2446
- const g = opt.__group;
2447
- if (!g || g === 'base')
2448
- continue; // base handled by default help
2449
- const rows = byGroup.get(g) ?? [];
2450
- rows.push({
2451
- flags: opt.flags ?? '',
2452
- description: opt.description ?? '',
2453
- });
2454
- byGroup.set(g, rows);
2455
- }
2456
- if (byGroup.size === 0)
2457
- return '';
2458
- const renderRows = (title, rows) => {
2459
- const width = Math.min(40, rows.reduce((m, r) => Math.max(m, r.flags.length), 0));
2460
- // Sort within group: short-aliased flags first
2461
- rows.sort((a, b) => {
2462
- const aS = /(^|\s|,)-[A-Za-z]/.test(a.flags) ? 1 : 0;
2463
- const bS = /(^|\s|,)-[A-Za-z]/.test(b.flags) ? 1 : 0;
2464
- return bS - aS || a.flags.localeCompare(b.flags);
2465
- });
2466
- const lines = rows
2467
- .map((r) => {
2468
- const pad = ' '.repeat(Math.max(2, width - r.flags.length + 2));
2469
- return ` ${r.flags}${pad}${r.description}`.trimEnd();
2470
- })
2471
- .join('\n');
2472
- return `\n${title}:\n${lines}\n`;
2473
- };
2474
- let out = '';
2475
- // App options (if any)
2476
- const app = byGroup.get('app');
2477
- if (app && app.length > 0) {
2478
- out += renderRows('App options', app);
2479
- }
2480
- // Plugin groups sorted by id
2481
- const pluginKeys = Array.from(byGroup.keys()).filter((k) => k.startsWith('plugin:'));
2482
- pluginKeys.sort((a, b) => a.localeCompare(b));
2483
- for (const k of pluginKeys) {
2484
- const id = k.slice('plugin:'.length) || '(unknown)';
2485
- const rows = byGroup.get(k) ?? [];
2486
- if (rows.length > 0) {
2487
- out += renderRows(`Plugin options — ${id}`, rows);
2488
- }
2489
- }
2490
- return out;
1441
+ // Drop CLI-only keys (debug/scripts) without relying on Record casts.
1442
+ // Create a shallow copy then delete optional CLI-only keys if present.
1443
+ const restObj = { ...rest };
1444
+ delete restObj.debug;
1445
+ delete restObj.scripts;
1446
+ const splitBy = (value, delim, pattern) => (value ? value.split(pattern ? RegExp(pattern) : (delim ?? ' ')) : []);
1447
+ // Tolerate vars as either a CLI string ("A=1 B=2") or an object map.
1448
+ let parsedVars;
1449
+ if (typeof vars === 'string') {
1450
+ const kvPairs = splitBy(vars, varsDelimiter, varsDelimiterPattern).map((v) => v.split(varsAssignorPattern
1451
+ ? RegExp(varsAssignorPattern)
1452
+ : (varsAssignor ?? '=')));
1453
+ parsedVars = Object.fromEntries(kvPairs);
2491
1454
  }
2492
- }
2493
-
2494
- /**
2495
- * Validate a composed env against config-provided validation surfaces.
2496
- * Precedence for validation definitions:
2497
- * project.local -\> project.public -\> packaged
2498
- *
2499
- * Behavior:
2500
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
2501
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
2502
- * - Returns a flat list of issue strings; caller decides warn vs fail.
2503
- */
2504
- const validateEnvAgainstSources = (finalEnv, sources) => {
2505
- const pick = (getter) => {
2506
- const pl = sources.project?.local;
2507
- const pp = sources.project?.public;
2508
- const pk = sources.packaged;
2509
- return ((pl && getter(pl)) ||
2510
- (pp && getter(pp)) ||
2511
- (pk && getter(pk)) ||
2512
- undefined);
2513
- };
2514
- const schema = pick((cfg) => cfg['schema']);
2515
- if (schema &&
2516
- typeof schema.safeParse === 'function') {
2517
- try {
2518
- const parsed = schema.safeParse(finalEnv);
2519
- if (!parsed.success) {
2520
- // Try to render zod-style issues when available.
2521
- const err = parsed.error;
2522
- const issues = Array.isArray(err.issues) && err.issues.length > 0
2523
- ? err.issues.map((i) => {
2524
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
2525
- const msg = i.message ?? 'Invalid value';
2526
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
2527
- })
2528
- : ['[schema] validation failed'];
2529
- return issues;
2530
- }
2531
- return [];
2532
- }
2533
- catch {
2534
- // If schema invocation fails, surface a single diagnostic.
2535
- return [
2536
- '[schema] validation failed (unable to execute schema.safeParse)',
2537
- ];
2538
- }
1455
+ else if (vars && typeof vars === 'object' && !Array.isArray(vars)) {
1456
+ // Keep only string or undefined values to match ProcessEnv.
1457
+ const entries = Object.entries(vars).filter(([k, v]) => typeof k === 'string' && (typeof v === 'string' || v === undefined));
1458
+ parsedVars = Object.fromEntries(entries);
2539
1459
  }
2540
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
2541
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
2542
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
2543
- if (missing.length > 0) {
2544
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
2545
- }
1460
+ // Drop undefined-valued entries at the converter stage to match ProcessEnv
1461
+ // expectations and the compat test assertions.
1462
+ if (parsedVars) {
1463
+ parsedVars = Object.fromEntries(Object.entries(parsedVars).filter(([, v]) => v !== undefined));
2546
1464
  }
2547
- return [];
2548
- };
2549
-
2550
- /**
2551
- * Attach legacy root flags to a Commander program.
2552
- * Uses provided defaults to render help labels without coupling to generators.
2553
- */
2554
- const attachRootOptions = (program, defaults, opts) => {
2555
- // Install temporary wrappers to tag all options added here as "base".
2556
- const GROUP = 'base';
2557
- const tagLatest = (cmd, group) => {
2558
- const optsArr = cmd.options;
2559
- if (Array.isArray(optsArr) && optsArr.length > 0) {
2560
- const last = optsArr[optsArr.length - 1];
2561
- last.__group = group;
2562
- }
2563
- };
2564
- const originalAddOption = program.addOption.bind(program);
2565
- const originalOption = program.option.bind(program);
2566
- program.addOption = function patchedAdd(opt) {
2567
- // Tag before adding, in case consumers inspect the Option directly.
2568
- opt.__group = GROUP;
2569
- const ret = originalAddOption(opt);
2570
- return ret;
2571
- };
2572
- program.option = function patchedOption(...args) {
2573
- const ret = originalOption(...args);
2574
- tagLatest(this, GROUP);
2575
- return ret;
1465
+ // Tolerate paths as either a delimited string or string[]
1466
+ // Use a locally cast union type to avoid lint warnings about always-falsy conditions
1467
+ // under the RootOptionsShape (which declares paths as string | undefined).
1468
+ const pathsAny = paths;
1469
+ const pathsOut = Array.isArray(pathsAny)
1470
+ ? pathsAny.filter((p) => typeof p === 'string')
1471
+ : splitBy(pathsAny, pathsDelimiter, pathsDelimiterPattern);
1472
+ // Preserve exactOptionalPropertyTypes: only include keys when defined.
1473
+ return {
1474
+ ...restObj,
1475
+ ...(pathsOut.length > 0 ? { paths: pathsOut } : {}),
1476
+ ...(parsedVars !== undefined ? { vars: parsedVars } : {}),
2576
1477
  };
2577
- const { defaultEnv, dotenvToken, dynamicPath, env, excludeDynamic, excludeEnv, excludeGlobal, excludePrivate, excludePublic, loadProcess, log, outputPath, paths, pathsDelimiter, pathsDelimiterPattern, privateToken, scripts, shell, varsAssignor, varsAssignorPattern, varsDelimiter, varsDelimiterPattern, } = defaults ?? {};
2578
- const va = typeof defaults?.varsAssignor === 'string' ? defaults.varsAssignor : '=';
2579
- const vd = typeof defaults?.varsDelimiter === 'string' ? defaults.varsDelimiter : ' ';
2580
- // Build initial chain.
2581
- let p = program
2582
- .enablePositionalOptions()
2583
- .passThroughOptions()
2584
- .option('-e, --env <string>', `target environment (dotenv-expanded)`, dotenvExpandFromProcessEnv, env);
2585
- p = p.option('-v, --vars <string>', `extra variables expressed as delimited key-value pairs (dotenv-expanded): ${[
2586
- ['KEY1', 'VAL1'],
2587
- ['KEY2', 'VAL2'],
2588
- ]
2589
- .map((v) => v.join(va))
2590
- .join(vd)}`, dotenvExpandFromProcessEnv);
2591
- // Optional legacy root command flag (kept for generated CLI compatibility).
2592
- // Default is OFF; the generator opts in explicitly.
2593
- if (opts?.includeCommandOption === true) {
2594
- p = p.option('-c, --command <string>', 'command executed according to the --shell option, conflicts with cmd subcommand (dotenv-expanded)', dotenvExpandFromProcessEnv);
2595
- }
2596
- p = p
2597
- .option('-o, --output-path <string>', 'consolidated output file (dotenv-expanded)', dotenvExpandFromProcessEnv, outputPath)
2598
- .addOption(new Option('-s, --shell [string]', (() => {
2599
- let defaultLabel = '';
2600
- if (shell !== undefined) {
2601
- if (typeof shell === 'boolean') {
2602
- defaultLabel = ' (default OS shell)';
2603
- }
2604
- else if (typeof shell === 'string') {
2605
- // Safe string interpolation
2606
- defaultLabel = ` (default ${shell})`;
2607
- }
2608
- }
2609
- return `command execution shell, no argument for default OS shell or provide shell string${defaultLabel}`;
2610
- })()).conflicts('shellOff'))
2611
- .addOption(new Option('-S, --shell-off', `command execution shell OFF${!shell ? ' (default)' : ''}`).conflicts('shell'))
2612
- .addOption(new Option('-p, --load-process', `load variables to process.env ON${loadProcess ? ' (default)' : ''}`).conflicts('loadProcessOff'))
2613
- .addOption(new Option('-P, --load-process-off', `load variables to process.env OFF${!loadProcess ? ' (default)' : ''}`).conflicts('loadProcess'))
2614
- .addOption(new Option('-a, --exclude-all', `exclude all dotenv variables from loading ON${excludeDynamic &&
2615
- ((excludeEnv && excludeGlobal) || (excludePrivate && excludePublic))
2616
- ? ' (default)'
2617
- : ''}`).conflicts('excludeAllOff'))
2618
- .addOption(new Option('-A, --exclude-all-off', `exclude all dotenv variables from loading OFF (default)`).conflicts('excludeAll'))
2619
- .addOption(new Option('-z, --exclude-dynamic', `exclude dynamic dotenv variables from loading ON${excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamicOff'))
2620
- .addOption(new Option('-Z, --exclude-dynamic-off', `exclude dynamic dotenv variables from loading OFF${!excludeDynamic ? ' (default)' : ''}`).conflicts('excludeDynamic'))
2621
- .addOption(new Option('-n, --exclude-env', `exclude environment-specific dotenv variables from loading${excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnvOff'))
2622
- .addOption(new Option('-N, --exclude-env-off', `exclude environment-specific dotenv variables from loading OFF${!excludeEnv ? ' (default)' : ''}`).conflicts('excludeEnv'))
2623
- .addOption(new Option('-g, --exclude-global', `exclude global dotenv variables from loading ON${excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobalOff'))
2624
- .addOption(new Option('-G, --exclude-global-off', `exclude global dotenv variables from loading OFF${!excludeGlobal ? ' (default)' : ''}`).conflicts('excludeGlobal'))
2625
- .addOption(new Option('-r, --exclude-private', `exclude private dotenv variables from loading ON${excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivateOff'))
2626
- .addOption(new Option('-R, --exclude-private-off', `exclude private dotenv variables from loading OFF${!excludePrivate ? ' (default)' : ''}`).conflicts('excludePrivate'))
2627
- .addOption(new Option('-u, --exclude-public', `exclude public dotenv variables from loading ON${excludePublic ? ' (default)' : ''}`).conflicts('excludePublicOff'))
2628
- .addOption(new Option('-U, --exclude-public-off', `exclude public dotenv variables from loading OFF${!excludePublic ? ' (default)' : ''}`).conflicts('excludePublic'))
2629
- .addOption(new Option('-l, --log', `console log loaded variables ON${log ? ' (default)' : ''}`).conflicts('logOff'))
2630
- .addOption(new Option('-L, --log-off', `console log loaded variables OFF${!log ? ' (default)' : ''}`).conflicts('log'))
2631
- .option('--capture', 'capture child process stdio for commands (tests/CI)')
2632
- .option('--redact', 'mask secret-like values in logs/trace (presentation-only)')
2633
- .option('--default-env <string>', 'default target environment', dotenvExpandFromProcessEnv, defaultEnv)
2634
- .option('--dotenv-token <string>', 'dotenv-expanded token indicating a dotenv file', dotenvExpandFromProcessEnv, dotenvToken)
2635
- .option('--dynamic-path <string>', 'dynamic variables path (.js or .ts; .ts is auto-compiled when esbuild is available, otherwise precompile)', dotenvExpandFromProcessEnv, dynamicPath)
2636
- .option('--paths <string>', 'dotenv-expanded delimited list of paths to dotenv directory', dotenvExpandFromProcessEnv, paths)
2637
- .option('--paths-delimiter <string>', 'paths delimiter string', pathsDelimiter)
2638
- .option('--paths-delimiter-pattern <string>', 'paths delimiter regex pattern', pathsDelimiterPattern)
2639
- .option('--private-token <string>', 'dotenv-expanded token indicating private variables', dotenvExpandFromProcessEnv, privateToken)
2640
- .option('--vars-delimiter <string>', 'vars delimiter string', varsDelimiter)
2641
- .option('--vars-delimiter-pattern <string>', 'vars delimiter regex pattern', varsDelimiterPattern)
2642
- .option('--vars-assignor <string>', 'vars assignment operator string', varsAssignor)
2643
- .option('--vars-assignor-pattern <string>', 'vars assignment operator regex pattern', varsAssignorPattern)
2644
- // Hidden scripts pipe-through (stringified)
2645
- .addOption(new Option('--scripts <string>')
2646
- .default(JSON.stringify(scripts))
2647
- .hideHelp());
2648
- // Diagnostics: opt-in tracing; optional variadic keys after the flag.
2649
- p = p.option('--trace [keys...]', 'emit diagnostics for child env composition (optional keys)');
2650
- // Validation: strict mode fails on env validation issues (warn by default).
2651
- p = p.option('--strict', 'fail on env validation errors (schema/requiredKeys)');
2652
- // Entropy diagnostics (presentation-only)
2653
- p = p
2654
- .addOption(new Option('--entropy-warn', 'enable entropy warnings (default on)').conflicts('entropyWarnOff'))
2655
- .addOption(new Option('--entropy-warn-off', 'disable entropy warnings').conflicts('entropyWarn'))
2656
- .option('--entropy-threshold <number>', 'entropy bits/char threshold (default 3.8)')
2657
- .option('--entropy-min-length <number>', 'min length to examine for entropy (default 16)')
2658
- .option('--entropy-whitelist <pattern...>', 'suppress entropy warnings when key matches any regex pattern')
2659
- .option('--redact-pattern <pattern...>', 'additional key-match regex patterns to trigger redaction');
2660
- // Restore original methods to avoid tagging future additions outside base.
2661
- program.addOption = originalAddOption;
2662
- program.option = originalOption;
2663
- return p;
2664
- };
2665
-
2666
- /**
2667
- * Resolve a tri-state optional boolean flag under exactOptionalPropertyTypes.
2668
- * - If the user explicitly enabled the flag, return true.
2669
- * - If the user explicitly disabled (the "...-off" variant), return undefined (unset).
2670
- * - Otherwise, adopt the default (true → set; false/undefined → unset).
2671
- *
2672
- * @param exclude - The "on" flag value as parsed by Commander.
2673
- * @param excludeOff - The "off" toggle (present when specified) as parsed by Commander.
2674
- * @param defaultValue - The generator default to adopt when no explicit toggle is present.
2675
- * @returns boolean | undefined — use `undefined` to indicate "unset" (do not emit).
2676
- *
2677
- * @example
2678
- * ```ts
2679
- * resolveExclusion(undefined, undefined, true); // => true
2680
- * ```
2681
- */
2682
- const resolveExclusion = (exclude, excludeOff, defaultValue) => exclude ? true : excludeOff ? undefined : defaultValue ? true : undefined;
2683
- /**
2684
- * Resolve an optional flag with "--exclude-all" overrides.
2685
- * If excludeAll is set and the individual "...-off" is not, force true.
2686
- * If excludeAllOff is set and the individual flag is not explicitly set, unset.
2687
- * Otherwise, adopt the default (true → set; false/undefined → unset).
2688
- *
2689
- * @param exclude - Individual include/exclude flag.
2690
- * @param excludeOff - Individual "...-off" flag.
2691
- * @param defaultValue - Default for the individual flag.
2692
- * @param excludeAll - Global "exclude-all" flag.
2693
- * @param excludeAllOff - Global "exclude-all-off" flag.
2694
- *
2695
- * @example
2696
- * resolveExclusionAll(undefined, undefined, false, true, undefined) =\> true
2697
- */
2698
- const resolveExclusionAll = (exclude, excludeOff, defaultValue, excludeAll, excludeAllOff) =>
2699
- // Order of precedence:
2700
- // 1) Individual explicit "on" wins outright.
2701
- // 2) Individual explicit "off" wins over any global.
2702
- // 3) Global exclude-all forces true when not explicitly turned off.
2703
- // 4) Global exclude-all-off unsets when the individual wasn't explicitly enabled.
2704
- // 5) Fall back to the default (true => set; false/undefined => unset).
2705
- (() => {
2706
- // Individual "on"
2707
- if (exclude === true)
2708
- return true;
2709
- // Individual "off"
2710
- if (excludeOff === true)
2711
- return undefined;
2712
- // Global "exclude-all" ON (unless explicitly turned off)
2713
- if (excludeAll === true)
2714
- return true;
2715
- // Global "exclude-all-off" (unless explicitly enabled)
2716
- if (excludeAllOff === true)
2717
- return undefined;
2718
- // Default
2719
- return defaultValue ? true : undefined;
2720
- })();
2721
- /**
2722
- * exactOptionalPropertyTypes-safe setter for optional boolean flags:
2723
- * delete when undefined; assign when defined — without requiring an index signature on T.
2724
- *
2725
- * @typeParam T - Target object type.
2726
- * @param obj - The object to write to.
2727
- * @param key - The optional boolean property key of {@link T}.
2728
- * @param value - The value to set or `undefined` to unset.
2729
- *
2730
- * @remarks
2731
- * Writes through a local `Record<string, unknown>` view to avoid requiring an index signature on {@link T}.
2732
- */
2733
- const setOptionalFlag = (obj, key, value) => {
2734
- const target = obj;
2735
- const k = key;
2736
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
2737
- if (value === undefined)
2738
- delete target[k];
2739
- else
2740
- target[k] = value;
2741
- };
2742
-
2743
- /**
2744
- * Merge and normalize raw Commander options (current + parent + defaults)
2745
- * into a GetDotenvCliOptions-like object. Types are intentionally wide to
2746
- * avoid cross-layer coupling; callers may cast as needed.
2747
- */
2748
- const resolveCliOptions = (rawCliOptions, defaults, parentJson) => {
2749
- const parent = typeof parentJson === 'string' && parentJson.length > 0
2750
- ? JSON.parse(parentJson)
2751
- : undefined;
2752
- const { command, debugOff, excludeAll, excludeAllOff, excludeDynamicOff, excludeEnvOff, excludeGlobalOff, excludePrivateOff, excludePublicOff, loadProcessOff, logOff, entropyWarn, entropyWarnOff, scripts, shellOff, ...rest } = rawCliOptions;
2753
- const current = { ...rest };
2754
- if (typeof scripts === 'string') {
2755
- try {
2756
- current.scripts = JSON.parse(scripts);
2757
- }
2758
- catch {
2759
- // ignore parse errors; leave scripts undefined
2760
- }
2761
- }
2762
- const merged = defaultsDeep({}, defaults, parent ?? {}, current);
2763
- const d = defaults;
2764
- setOptionalFlag(merged, 'debug', resolveExclusion(merged.debug, debugOff, d.debug));
2765
- setOptionalFlag(merged, 'excludeDynamic', resolveExclusionAll(merged.excludeDynamic, excludeDynamicOff, d.excludeDynamic, excludeAll, excludeAllOff));
2766
- setOptionalFlag(merged, 'excludeEnv', resolveExclusionAll(merged.excludeEnv, excludeEnvOff, d.excludeEnv, excludeAll, excludeAllOff));
2767
- setOptionalFlag(merged, 'excludeGlobal', resolveExclusionAll(merged.excludeGlobal, excludeGlobalOff, d.excludeGlobal, excludeAll, excludeAllOff));
2768
- setOptionalFlag(merged, 'excludePrivate', resolveExclusionAll(merged.excludePrivate, excludePrivateOff, d.excludePrivate, excludeAll, excludeAllOff));
2769
- setOptionalFlag(merged, 'excludePublic', resolveExclusionAll(merged.excludePublic, excludePublicOff, d.excludePublic, excludeAll, excludeAllOff));
2770
- setOptionalFlag(merged, 'log', resolveExclusion(merged.log, logOff, d.log));
2771
- setOptionalFlag(merged, 'loadProcess', resolveExclusion(merged.loadProcess, loadProcessOff, d.loadProcess));
2772
- // warnEntropy (tri-state)
2773
- setOptionalFlag(merged, 'warnEntropy', resolveExclusion(merged.warnEntropy, entropyWarnOff, d.warnEntropy));
2774
- // Normalize shell for predictability: explicit default shell per OS.
2775
- const defaultShell = process.platform === 'win32' ? 'powershell.exe' : '/bin/bash';
2776
- let resolvedShell = merged.shell;
2777
- if (shellOff)
2778
- resolvedShell = false;
2779
- else if (resolvedShell === true || resolvedShell === undefined) {
2780
- resolvedShell = defaultShell;
2781
- }
2782
- else if (typeof resolvedShell !== 'string' &&
2783
- typeof defaults.shell === 'string') {
2784
- resolvedShell = defaults.shell;
2785
- }
2786
- merged.shell = resolvedShell;
2787
- const cmd = typeof command === 'string' ? command : undefined;
2788
- return cmd !== undefined ? { merged, command: cmd } : { merged };
2789
- };
2790
-
2791
- GetDotenvCli.prototype.attachRootOptions = function (defaults, opts) {
2792
- const d = (defaults ?? baseRootOptionDefaults);
2793
- attachRootOptions(this, d, opts);
2794
- return this;
2795
- };
2796
- GetDotenvCli.prototype.passOptions = function (defaults) {
2797
- const d = (defaults ?? baseRootOptionDefaults);
2798
- this.hook('preSubcommand', async (thisCommand) => {
2799
- const raw = thisCommand.opts();
2800
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2801
- // Persist merged options for nested invocations (batch exec).
2802
- thisCommand.getDotenvCliOptions =
2803
- merged;
2804
- // Also store on the host for downstream ergonomic accessors.
2805
- this._setOptionsBag(merged);
2806
- // Build service options and compute context (always-on config loader path).
2807
- const serviceOptions = getDotenvCliOptions2Options(merged);
2808
- await this.resolveAndLoad(serviceOptions);
2809
- // Global validation: once after Phase C using config sources.
2810
- try {
2811
- const ctx = this.getCtx();
2812
- const dotenv = (ctx?.dotenv ?? {});
2813
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
2814
- const issues = validateEnvAgainstSources(dotenv, sources);
2815
- if (Array.isArray(issues) && issues.length > 0) {
2816
- const logger = (merged.logger ??
2817
- console);
2818
- const emit = logger.error ?? logger.log;
2819
- issues.forEach((m) => {
2820
- emit(m);
2821
- });
2822
- if (merged.strict) {
2823
- // Deterministic failure under strict mode
2824
- process.exit(1);
2825
- }
2826
- }
2827
- }
2828
- catch {
2829
- // Be tolerant: validation errors reported above; unexpected failures here
2830
- // should not crash non-strict flows.
2831
- }
2832
- });
2833
- // Also handle root-level flows (no subcommand) so option-aliases can run
2834
- // with the same merged options and context without duplicating logic.
2835
- this.hook('preAction', async (thisCommand) => {
2836
- const raw = thisCommand.opts();
2837
- const { merged } = resolveCliOptions(raw, d, process.env.getDotenvCliOptions);
2838
- thisCommand.getDotenvCliOptions =
2839
- merged;
2840
- this._setOptionsBag(merged);
2841
- // Avoid duplicate heavy work if a context is already present.
2842
- if (!this.getCtx()) {
2843
- const serviceOptions = getDotenvCliOptions2Options(merged);
2844
- await this.resolveAndLoad(serviceOptions);
2845
- try {
2846
- const ctx = this.getCtx();
2847
- const dotenv = (ctx?.dotenv ?? {});
2848
- const sources = await resolveGetDotenvConfigSources(import.meta.url);
2849
- const issues = validateEnvAgainstSources(dotenv, sources);
2850
- if (Array.isArray(issues) && issues.length > 0) {
2851
- const logger = (merged
2852
- .logger ?? console);
2853
- const emit = logger.error ?? logger.log;
2854
- issues.forEach((m) => {
2855
- emit(m);
2856
- });
2857
- if (merged.strict) {
2858
- process.exit(1);
2859
- }
2860
- }
2861
- }
2862
- catch {
2863
- // Tolerate validation side-effects in non-strict mode
2864
- }
2865
- }
2866
- });
2867
- return this;
2868
1478
  };
2869
1479
 
2870
1480
  const dbg = (...args) => {
@@ -3163,7 +1773,7 @@ const cmdPlugin = (options = {}) => definePlugin({
3163
1773
  const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
3164
1774
  const cmd = new Command()
3165
1775
  .name('cmd')
3166
- .description('Batch execute command according to the --shell option, conflicts with --command option (default subcommand)')
1776
+ .description('Execute command according to the --shell option, conflicts with --command option (default subcommand)')
3167
1777
  .configureHelp({ showGlobalOptions: true })
3168
1778
  .enablePositionalOptions()
3169
1779
  .passThroughOptions()