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