@karmaniverous/get-dotenv 6.2.3 → 6.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/chunks/AwsRestJsonProtocol-Bq1HE-Ln.mjs +932 -0
  2. package/dist/chunks/createCli-BY6_cfZr.mjs +439 -0
  3. package/dist/chunks/externalDataInterceptor-CbsdEYa-.mjs +19 -0
  4. package/dist/chunks/getSSOTokenFromFile-hUSpR7Wf.mjs +22 -0
  5. package/dist/chunks/helpConfig-CGejgwWW.mjs +12 -0
  6. package/dist/chunks/index-B5JKTBOL.mjs +443 -0
  7. package/dist/chunks/index-BEJFiHMX.mjs +522 -0
  8. package/dist/chunks/index-BPYF6K_G.mjs +82 -0
  9. package/dist/chunks/index-Bc3h0a95.mjs +374 -0
  10. package/dist/chunks/index-BpCF5UKx.mjs +272 -0
  11. package/dist/chunks/index-C_wqbTwI.mjs +187 -0
  12. package/dist/chunks/index-CeCufHlm.mjs +9374 -0
  13. package/dist/chunks/index-Cu7rdyqN.mjs +102 -0
  14. package/dist/chunks/index-DWAtHEA-.mjs +379 -0
  15. package/dist/chunks/index-Dp1Ip6Ra.mjs +354 -0
  16. package/dist/chunks/index-DyU5pKKi.mjs +24 -0
  17. package/dist/chunks/index-c7zKtEuy.mjs +578 -0
  18. package/dist/chunks/index-cIunyiUQ.mjs +702 -0
  19. package/dist/chunks/invoke-DuRPU1oC.mjs +60 -0
  20. package/dist/chunks/loadModuleDefault-Dj8B3Stt.mjs +123 -0
  21. package/dist/chunks/loadSso-w1eTVg0O.mjs +412 -0
  22. package/dist/chunks/loader-DnhPeGfq.mjs +346 -0
  23. package/dist/chunks/overlayEnv-Bs2kVayG.mjs +234 -0
  24. package/dist/chunks/package-boo9EyYs.mjs +5 -0
  25. package/dist/chunks/parseKnownFiles-B9cDK21V.mjs +23 -0
  26. package/dist/chunks/readMergedOptions-Nt0TR7dX.mjs +1626 -0
  27. package/dist/chunks/resolveCliOptions-TFRzhB2c.mjs +138 -0
  28. package/dist/chunks/sdk-stream-mixin-BZoJ5jy9.mjs +167 -0
  29. package/dist/chunks/spawnEnv-CN8a7cNR.mjs +306 -0
  30. package/dist/chunks/types-DJ-BGABd.mjs +59 -0
  31. package/dist/chunks/validate-CDl0rE6k.mjs +61 -0
  32. package/dist/cli.mjs +39 -19307
  33. package/dist/cliHost.mjs +20 -2800
  34. package/dist/config.mjs +10 -509
  35. package/dist/env-overlay.mjs +6 -337
  36. package/dist/getdotenv.cli.mjs +39 -19305
  37. package/dist/index.mjs +39 -19396
  38. package/dist/plugins-aws.d.ts +1 -4
  39. package/dist/plugins-aws.mjs +65 -2568
  40. package/dist/plugins-batch.mjs +16 -2573
  41. package/dist/plugins-cmd.mjs +19 -3094
  42. package/dist/plugins-init.d.ts +8 -0
  43. package/dist/plugins-init.mjs +85 -2297
  44. package/dist/plugins.mjs +36 -18817
  45. package/package.json +1 -2
  46. package/dist/templates/cli/index.ts +0 -25
  47. package/dist/templates/cli/plugins/hello/defaultAction.ts +0 -27
  48. package/dist/templates/cli/plugins/hello/index.ts +0 -26
  49. package/dist/templates/cli/plugins/hello/options.ts +0 -31
  50. package/dist/templates/cli/plugins/hello/strangerAction.ts +0 -20
  51. package/dist/templates/cli/plugins/hello/types.ts +0 -13
  52. package/dist/templates/config/js/getdotenv.config.js +0 -20
  53. package/dist/templates/config/json/local/getdotenv.config.local.json +0 -7
  54. package/dist/templates/config/json/public/getdotenv.config.json +0 -9
  55. package/dist/templates/config/public/getdotenv.config.json +0 -8
  56. package/dist/templates/config/ts/getdotenv.config.ts +0 -28
  57. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +0 -7
  58. package/dist/templates/config/yaml/public/getdotenv.config.yaml +0 -7
  59. package/dist/templates/defaultAction.ts +0 -27
  60. package/dist/templates/getdotenv.config.js +0 -20
  61. package/dist/templates/getdotenv.config.json +0 -9
  62. package/dist/templates/getdotenv.config.local.json +0 -7
  63. package/dist/templates/getdotenv.config.local.yaml +0 -7
  64. package/dist/templates/getdotenv.config.ts +0 -28
  65. package/dist/templates/getdotenv.config.yaml +0 -7
  66. package/dist/templates/hello/defaultAction.ts +0 -27
  67. package/dist/templates/hello/index.ts +0 -26
  68. package/dist/templates/hello/options.ts +0 -31
  69. package/dist/templates/hello/strangerAction.ts +0 -20
  70. package/dist/templates/hello/types.ts +0 -13
  71. package/dist/templates/index.ts +0 -26
  72. package/dist/templates/js/getdotenv.config.js +0 -20
  73. package/dist/templates/json/local/getdotenv.config.local.json +0 -7
  74. package/dist/templates/json/public/getdotenv.config.json +0 -9
  75. package/dist/templates/local/getdotenv.config.local.json +0 -7
  76. package/dist/templates/local/getdotenv.config.local.yaml +0 -7
  77. package/dist/templates/options.ts +0 -31
  78. package/dist/templates/plugins/hello/defaultAction.ts +0 -27
  79. package/dist/templates/plugins/hello/index.ts +0 -26
  80. package/dist/templates/plugins/hello/options.ts +0 -31
  81. package/dist/templates/plugins/hello/strangerAction.ts +0 -20
  82. package/dist/templates/plugins/hello/types.ts +0 -13
  83. package/dist/templates/public/getdotenv.config.json +0 -9
  84. package/dist/templates/public/getdotenv.config.yaml +0 -7
  85. package/dist/templates/strangerAction.ts +0 -20
  86. package/dist/templates/ts/getdotenv.config.ts +0 -28
  87. package/dist/templates/types.ts +0 -13
  88. package/dist/templates/yaml/local/getdotenv.config.local.yaml +0 -7
  89. package/dist/templates/yaml/public/getdotenv.config.yaml +0 -7
package/dist/config.mjs CHANGED
@@ -1,509 +1,10 @@
1
- import fs from 'fs-extra';
2
- import { packageDirectory } from 'package-directory';
3
- import path, { join, extname } from 'path';
4
- import url, { pathToFileURL, fileURLToPath } from 'url';
5
- import YAML from 'yaml';
6
- import { z } from 'zod';
7
- import { createHash } from 'crypto';
8
-
9
- /**
10
- * Zod schemas for programmatic GetDotenv options.
11
- *
12
- * Canonical source of truth for options shape. Public types are derived
13
- * from these schemas (see consumers via z.output\<\>).
14
- */
15
- /**
16
- * Minimal process env representation used by options and helpers.
17
- * Values may be `undefined` to indicate "unset".
18
- */
19
- /**
20
- * Schema for an env-like record.
21
- *
22
- * Keys are environment variable names and values are either strings or `undefined`
23
- * (to represent “unset”).
24
- *
25
- * @public
26
- */
27
- const processEnvSchema = z.record(z.string(), z.string().optional());
28
- // RAW: all fields optional — undefined means "inherit" from lower layers.
29
- /**
30
- * Programmatic options schema (raw).
31
- *
32
- * This schema is the canonical runtime source of truth for the `getDotenv()` programmatic API.
33
- * All fields are optional; `undefined` generally means “inherit default/lower layer”.
34
- *
35
- * @public
36
- */
37
- const getDotenvOptionsSchemaRaw = z.object({
38
- /** Default environment name when `env` is not provided. */
39
- defaultEnv: z.string().optional(),
40
- /** Base dotenv filename token (default `.env`). */
41
- dotenvToken: z.string().optional(),
42
- /** Path to a dynamic variables module (JS/TS) to load and apply. */
43
- dynamicPath: z.string().optional(),
44
- /** Dynamic map is intentionally wide for now; refine once sources are normalized. */
45
- dynamic: z.record(z.string(), z.unknown()).optional(),
46
- /** Selected environment name for this invocation (for env-scoped files and overlays). */
47
- env: z.string().optional(),
48
- /** When true, skip applying dynamic variables. */
49
- excludeDynamic: z.boolean().optional(),
50
- /** When true, skip environment-scoped dotenv files. */
51
- excludeEnv: z.boolean().optional(),
52
- /** When true, skip global dotenv files. */
53
- excludeGlobal: z.boolean().optional(),
54
- /** When true, skip private dotenv files. */
55
- excludePrivate: z.boolean().optional(),
56
- /** When true, skip public dotenv files. */
57
- excludePublic: z.boolean().optional(),
58
- /** When true, merge the final composed environment into `process.env`. */
59
- loadProcess: z.boolean().optional(),
60
- /** When true, log the final environment map via `logger`. */
61
- log: z.boolean().optional(),
62
- /** Logger used when `log` is enabled (console-compatible). */
63
- logger: z.unknown().default(console),
64
- /** Optional output dotenv file path to write after composition. */
65
- outputPath: z.string().optional(),
66
- /** Dotenv search paths (ordered). */
67
- paths: z.array(z.string()).optional(),
68
- /** Private token suffix for private dotenv files (default `local`). */
69
- privateToken: z.string().optional(),
70
- /** Explicit variables to overlay onto the composed dotenv map. */
71
- vars: processEnvSchema.optional(),
72
- });
73
-
74
- /**
75
- * Zod schemas for CLI-facing GetDotenv options (raw/resolved stubs).
76
- *
77
- * RAW allows stringly inputs (paths/vars + splitters). RESOLVED will later
78
- * reflect normalized types (paths: string[], vars: ProcessEnv), applied in the
79
- * CLI resolution pipeline.
80
- */
81
- /**
82
- * CLI options schema (raw).
83
- *
84
- * Extends the programmatic options schema with CLI-only flags and stringly inputs
85
- * which are normalized later by the host resolution pipeline.
86
- *
87
- * @public
88
- */
89
- const getDotenvCliOptionsSchemaRaw = getDotenvOptionsSchemaRaw.extend({
90
- // CLI-specific fields (stringly inputs before preprocessing)
91
- /** Enable verbose debug output (host-specific). */
92
- debug: z.boolean().optional(),
93
- /** Fail on validation errors (schema/requiredKeys). */
94
- strict: z.boolean().optional(),
95
- /** Capture child process stdio (useful for CI/tests). */
96
- capture: z.boolean().optional(),
97
- /** Emit child env diagnostics (boolean or selected keys). */
98
- trace: z.union([z.boolean(), z.array(z.string())]).optional(),
99
- /** Enable presentation-time redaction in trace/log output. */
100
- redact: z.boolean().optional(),
101
- /** Enable entropy warnings in trace/log output. */
102
- warnEntropy: z.boolean().optional(),
103
- /** Entropy threshold (bits/char) for warnings. */
104
- entropyThreshold: z.number().optional(),
105
- /** Minimum value length to consider for entropy warnings. */
106
- entropyMinLength: z.number().optional(),
107
- /** Regex patterns (strings) to suppress entropy warnings by key. */
108
- entropyWhitelist: z.array(z.string()).optional(),
109
- /** Additional key-match patterns (strings) for redaction. */
110
- redactPatterns: z.array(z.string()).optional(),
111
- /** Dotenv search paths provided as a single delimited string. */
112
- paths: z.string().optional(),
113
- /** Delimiter string used to split `paths`. */
114
- pathsDelimiter: z.string().optional(),
115
- /** Regex pattern used to split `paths` (takes precedence over delimiter). */
116
- pathsDelimiterPattern: z.string().optional(),
117
- /** Scripts table in a permissive shape at parse time (validated elsewhere). */
118
- scripts: z.record(z.string(), z.unknown()).optional(),
119
- /** Shell selection (`false` for shell-off, string for explicit shell). */
120
- shell: z.union([z.boolean(), z.string()]).optional(),
121
- /** Extra variables expressed as a single delimited string of assignments. */
122
- vars: z.string().optional(),
123
- /** Assignment operator used when parsing `vars`. */
124
- varsAssignor: z.string().optional(),
125
- /** Regex pattern used as the assignment operator for `vars` parsing. */
126
- varsAssignorPattern: z.string().optional(),
127
- /** Delimiter string used to split `vars`. */
128
- varsDelimiter: z.string().optional(),
129
- /** Regex pattern used to split `vars` (takes precedence over delimiter). */
130
- varsDelimiterPattern: z.string().optional(),
131
- });
132
-
133
- const visibilityMap = z.record(z.string(), z.boolean());
134
- /**
135
- * Zod schemas for configuration files discovered by the new loader.
136
- *
137
- * Notes:
138
- * - RAW: all fields optional; only allowed top-level keys are:
139
- * - rootOptionDefaults, rootOptionVisibility
140
- * - scripts, vars, envVars
141
- * - dynamic (JS/TS only), schema (JS/TS only)
142
- * - plugins, requiredKeys
143
- * - RESOLVED: mirrors RAW (no path normalization).
144
- * - For JSON/YAML configs, the loader rejects "dynamic" and "schema" (JS/TS only).
145
- */
146
- // String-only env value map
147
- const stringMap = z.record(z.string(), z.string());
148
- const envStringMap = z.record(z.string(), stringMap);
149
- /**
150
- * Raw configuration schema for get‑dotenv config files (JSON/YAML/JS/TS).
151
- * Validates allowed top‑level keys without performing path normalization.
152
- */
153
- /**
154
- * Config schema for discovered get-dotenv configuration documents (raw).
155
- *
156
- * This schema validates the allowed top-level keys for configuration files.
157
- * It does not normalize paths or coerce types beyond Zod’s parsing.
158
- *
159
- * @public
160
- */
161
- const getDotenvConfigSchemaRaw = z.object({
162
- /** Root option defaults applied by the host (CLI-like, collapsed families). */
163
- rootOptionDefaults: getDotenvCliOptionsSchemaRaw.optional(),
164
- /** Help-time visibility map for root flags (false hides). */
165
- rootOptionVisibility: visibilityMap.optional(),
166
- /** Scripts table used by cmd/batch resolution (validation intentionally permissive here). */
167
- scripts: z.record(z.string(), z.unknown()).optional(),
168
- /** Keys required to be present in the final composed environment. */
169
- requiredKeys: z.array(z.string()).optional(),
170
- /** Validation schema (JS/TS only; JSON/YAML loader rejects). */
171
- schema: z.unknown().optional(), // JS/TS-only; loader rejects in JSON/YAML
172
- /** Public global variables (string-only). */
173
- vars: stringMap.optional(), // public, global
174
- /** Public per-environment variables (string-only). */
175
- envVars: envStringMap.optional(), // public, per-env
176
- // Dynamic in config (JS/TS only). JSON/YAML loader will reject if set.
177
- /** Dynamic variable definitions (JS/TS only). */
178
- dynamic: z.unknown().optional(),
179
- // Per-plugin config bag; validated by plugins/host when used.
180
- /** Per-plugin config slices keyed by realized mount path (for example, `aws/whoami`). */
181
- plugins: z.record(z.string(), z.unknown()).optional(),
182
- });
183
- /**
184
- * Resolved configuration schema which preserves the raw shape while narrowing
185
- * the output to {@link GetDotenvConfigResolved}. Consumers get a strongly typed
186
- * object, while the underlying validation remains Zod‑driven.
187
- */
188
- const getDotenvConfigSchemaResolved = getDotenvConfigSchemaRaw.transform((raw) => raw);
189
-
190
- const importDefault = async (fileUrl) => {
191
- const mod = (await import(fileUrl));
192
- return mod.default;
193
- };
194
- const cacheHash = (absPath, mtimeMs) => createHash('sha1')
195
- .update(absPath)
196
- .update(String(mtimeMs))
197
- .digest('hex')
198
- .slice(0, 12);
199
- /**
200
- * Remove older compiled cache files for a given source base name, keeping
201
- * at most `keep` most-recent files. Errors are ignored by design.
202
- */
203
- const cleanupOldCacheFiles = async (cacheDir, baseName, keep = Math.max(1, Number.parseInt(process.env.GETDOTENV_CACHE_KEEP ?? '2'))) => {
204
- try {
205
- const entries = await fs.readdir(cacheDir);
206
- const mine = entries
207
- .filter((f) => f.startsWith(`${baseName}.`) && f.endsWith('.mjs'))
208
- .map((f) => path.join(cacheDir, f));
209
- if (mine.length <= keep)
210
- return;
211
- const stats = await Promise.all(mine.map(async (p) => ({ p, mtimeMs: (await fs.stat(p)).mtimeMs })));
212
- stats.sort((a, b) => b.mtimeMs - a.mtimeMs);
213
- const toDelete = stats.slice(keep).map((s) => s.p);
214
- await Promise.all(toDelete.map(async (p) => {
215
- try {
216
- await fs.remove(p);
217
- }
218
- catch {
219
- // best-effort cleanup
220
- }
221
- }));
222
- }
223
- catch {
224
- // best-effort cleanup
225
- }
226
- };
227
- /**
228
- * Load a module default export from a JS/TS file with robust fallbacks.
229
- *
230
- * Behavior by extension:
231
- *
232
- * - `.js`/`.mjs`/`.cjs`: direct dynamic import.
233
- * - `.ts`/`.mts`/`.cts`/`.tsx`:
234
- * - try direct dynamic import (when a TS loader is active),
235
- * - else compile via `esbuild` to a cached `.mjs` file and import,
236
- * - else fallback to `typescript.transpileModule` for simple modules.
237
- *
238
- * @typeParam T - Type of the expected default export.
239
- * @param absPath - Absolute path to the source file.
240
- * @param cacheDirName - Cache subfolder under `.tsbuild/`.
241
- * @returns A `Promise\<T | undefined\>` resolving to the default export (if any).
242
- */
243
- const loadModuleDefault = async (absPath, cacheDirName) => {
244
- const ext = path.extname(absPath).toLowerCase();
245
- const fileUrl = url.pathToFileURL(absPath).toString();
246
- if (!['.ts', '.mts', '.cts', '.tsx'].includes(ext)) {
247
- return importDefault(fileUrl);
248
- }
249
- // Try direct import first (TS loader active)
250
- try {
251
- const dyn = await importDefault(fileUrl);
252
- if (dyn)
253
- return dyn;
254
- }
255
- catch {
256
- /* fall through */
257
- }
258
- const stat = await fs.stat(absPath);
259
- const hash = cacheHash(absPath, stat.mtimeMs);
260
- const cacheDir = path.resolve('.tsbuild', cacheDirName);
261
- await fs.ensureDir(cacheDir);
262
- const cacheFile = path.join(cacheDir, `${path.basename(absPath)}.${hash}.mjs`);
263
- // Try esbuild
264
- try {
265
- const esbuild = (await import('esbuild'));
266
- await esbuild.build({
267
- entryPoints: [absPath],
268
- bundle: true,
269
- platform: 'node',
270
- format: 'esm',
271
- target: 'node20',
272
- outfile: cacheFile,
273
- sourcemap: false,
274
- logLevel: 'silent',
275
- });
276
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
277
- // Best-effort: trim older cache files for this source.
278
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
279
- return result;
280
- }
281
- catch {
282
- /* fall through to TS transpile */
283
- }
284
- // TypeScript transpile fallback
285
- try {
286
- const ts = (await import('typescript'));
287
- const code = await fs.readFile(absPath, 'utf-8');
288
- const out = ts.transpileModule(code, {
289
- compilerOptions: {
290
- module: 'ESNext',
291
- target: 'ES2022',
292
- moduleResolution: 'NodeNext',
293
- },
294
- }).outputText;
295
- await fs.writeFile(cacheFile, out, 'utf-8');
296
- const result = await importDefault(url.pathToFileURL(cacheFile).toString());
297
- // Best-effort: trim older cache files for this source.
298
- await cleanupOldCacheFiles(cacheDir, path.basename(absPath));
299
- return result;
300
- }
301
- catch {
302
- // Caller decides final error wording; rethrow for upstream mapping.
303
- throw new Error(`Unable to load JS/TS module: ${absPath}. Install 'esbuild' or ensure a TS loader.`);
304
- }
305
- };
306
-
307
- /**
308
- * @packageDocumentation
309
- * Configuration discovery and loading for get‑dotenv. Discovers config files
310
- * in the packaged root and project root, loads JSON/YAML/JS/TS documents, and
311
- * validates them against Zod schemas.
312
- */
313
- // Discovery candidates (first match wins per scope/privacy).
314
- // Order preserves historical JSON/YAML precedence; JS/TS added afterwards.
315
- const PUBLIC_FILENAMES = [
316
- 'getdotenv.config.json',
317
- 'getdotenv.config.yaml',
318
- 'getdotenv.config.yml',
319
- 'getdotenv.config.js',
320
- 'getdotenv.config.mjs',
321
- 'getdotenv.config.cjs',
322
- 'getdotenv.config.ts',
323
- 'getdotenv.config.mts',
324
- 'getdotenv.config.cts',
325
- ];
326
- const LOCAL_FILENAMES = [
327
- 'getdotenv.config.local.json',
328
- 'getdotenv.config.local.yaml',
329
- 'getdotenv.config.local.yml',
330
- 'getdotenv.config.local.js',
331
- 'getdotenv.config.local.mjs',
332
- 'getdotenv.config.local.cjs',
333
- 'getdotenv.config.local.ts',
334
- 'getdotenv.config.local.mts',
335
- 'getdotenv.config.local.cts',
336
- ];
337
- const isYaml = (p) => ['.yaml', '.yml'].includes(extname(p).toLowerCase());
338
- const isJson = (p) => extname(p).toLowerCase() === '.json';
339
- const isJsOrTs = (p) => ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'].includes(extname(p).toLowerCase());
340
- /**
341
- * Discover JSON/YAML config files in the packaged root and project root.
342
- * Order: packaged public → project public → project local. */
343
- const discoverConfigFiles = async (importMetaUrl) => {
344
- const files = [];
345
- // Packaged root via importMetaUrl (optional)
346
- if (importMetaUrl) {
347
- const fromUrl = fileURLToPath(importMetaUrl);
348
- const packagedRoot = await packageDirectory({ cwd: fromUrl });
349
- if (packagedRoot) {
350
- for (const name of PUBLIC_FILENAMES) {
351
- const p = join(packagedRoot, name);
352
- if (await fs.pathExists(p)) {
353
- files.push({ path: p, privacy: 'public', scope: 'packaged' });
354
- break; // only one public file expected per scope
355
- }
356
- }
357
- // By policy, packaged .local is not expected; skip even if present.
358
- }
359
- }
360
- // Project root (from current working directory)
361
- const projectRoot = await packageDirectory();
362
- if (projectRoot) {
363
- for (const name of PUBLIC_FILENAMES) {
364
- const p = join(projectRoot, name);
365
- if (await fs.pathExists(p)) {
366
- files.push({ path: p, privacy: 'public', scope: 'project' });
367
- break;
368
- }
369
- }
370
- for (const name of LOCAL_FILENAMES) {
371
- const p = join(projectRoot, name);
372
- if (await fs.pathExists(p)) {
373
- files.push({ path: p, privacy: 'local', scope: 'project' });
374
- break;
375
- }
376
- }
377
- }
378
- return files;
379
- };
380
- /**
381
- * Load a single config file (JSON/YAML). JS/TS is not supported in this step.
382
- * Validates with Zod RAW schema, then normalizes to RESOLVED.
383
- *
384
- * For JSON/YAML: if a "dynamic" property is present, throws with guidance.
385
- * For JS/TS: default export is loaded; "dynamic" is allowed.
386
- */
387
- const loadConfigFile = async (filePath) => {
388
- let raw = {};
389
- try {
390
- const abs = path.resolve(filePath);
391
- if (isJsOrTs(abs)) {
392
- // JS/TS support: load default export via shared robust pipeline.
393
- const mod = await loadModuleDefault(abs, 'getdotenv-config');
394
- raw = mod ?? {};
395
- }
396
- else {
397
- const txt = await fs.readFile(abs, 'utf-8');
398
- raw = isJson(abs) ? JSON.parse(txt) : isYaml(abs) ? YAML.parse(txt) : {};
399
- }
400
- }
401
- catch (err) {
402
- throw new Error(`Failed to read/parse config: ${filePath}. ${String(err)}`);
403
- }
404
- // Validate RAW
405
- const parsed = getDotenvConfigSchemaRaw.safeParse(raw);
406
- if (!parsed.success) {
407
- const msgs = parsed.error.issues
408
- .map((i) => `${i.path.join('.')}: ${i.message}`)
409
- .join('\n');
410
- throw new Error(`Invalid config ${filePath}:\n${msgs}`);
411
- }
412
- // Disallow dynamic and schema in JSON/YAML; allow both in JS/TS.
413
- if (!isJsOrTs(filePath) &&
414
- (parsed.data.dynamic !== undefined || parsed.data.schema !== undefined)) {
415
- throw new Error(`Config ${filePath} specifies unsupported keys for JSON/YAML. ` +
416
- `Use JS/TS config for "dynamic" or "schema".`);
417
- }
418
- return getDotenvConfigSchemaResolved.parse(parsed.data);
419
- };
420
- /**
421
- * Discover and load configs into resolved shapes, ordered by scope/privacy.
422
- * JSON/YAML/JS/TS supported; first match per scope/privacy applies.
423
- */
424
- const resolveGetDotenvConfigSources = async (importMetaUrl) => {
425
- const discovered = await discoverConfigFiles(importMetaUrl);
426
- const result = {};
427
- for (const f of discovered) {
428
- const cfg = await loadConfigFile(f.path);
429
- if (f.scope === 'packaged') {
430
- // packaged public only
431
- result.packaged = cfg;
432
- }
433
- else {
434
- result.project ??= {};
435
- if (f.privacy === 'public')
436
- result.project.public = cfg;
437
- else
438
- result.project.local = cfg;
439
- }
440
- }
441
- return result;
442
- };
443
- /**
444
- * Utility primarily for tests: create a file: URL string from a path.
445
- * @param p - File path.
446
- */
447
- const toFileUrl = (p) => pathToFileURL(path.resolve(p)).toString();
448
-
449
- /**
450
- * Validate a composed env against config-provided validation surfaces.
451
- * Precedence for validation definitions:
452
- * project.local -\> project.public -\> packaged
453
- *
454
- * Behavior:
455
- * - If a JS/TS `schema` is present, use schema.safeParse(finalEnv).
456
- * - Else if `requiredKeys` is present, check presence (value !== undefined).
457
- * - Returns a flat list of issue strings; caller decides warn vs fail.
458
- *
459
- * @param finalEnv - Final composed environment to validate.
460
- * @param sources - Resolved config sources providing `schema` and/or `requiredKeys`.
461
- * @returns A list of human-readable issue strings (empty when valid).
462
- */
463
- const validateEnvAgainstSources = (finalEnv, sources) => {
464
- const pick = (getter) => {
465
- const pl = sources.project?.local;
466
- const pp = sources.project?.public;
467
- const pk = sources.packaged;
468
- return ((pl && getter(pl)) ||
469
- (pp && getter(pp)) ||
470
- (pk && getter(pk)) ||
471
- undefined);
472
- };
473
- const schema = pick((cfg) => cfg['schema']);
474
- if (schema &&
475
- typeof schema.safeParse === 'function') {
476
- try {
477
- const parsed = schema.safeParse(finalEnv);
478
- if (!parsed.success) {
479
- // Try to render zod-style issues when available.
480
- const err = parsed.error;
481
- const issues = Array.isArray(err.issues) && err.issues.length > 0
482
- ? err.issues.map((i) => {
483
- const path = Array.isArray(i.path) ? i.path.join('.') : '';
484
- const msg = i.message ?? 'Invalid value';
485
- return path ? `[schema] ${path}: ${msg}` : `[schema] ${msg}`;
486
- })
487
- : ['[schema] validation failed'];
488
- return issues;
489
- }
490
- return [];
491
- }
492
- catch {
493
- // If schema invocation fails, surface a single diagnostic.
494
- return [
495
- '[schema] validation failed (unable to execute schema.safeParse)',
496
- ];
497
- }
498
- }
499
- const requiredKeys = pick((cfg) => cfg['requiredKeys']);
500
- if (Array.isArray(requiredKeys) && requiredKeys.length > 0) {
501
- const missing = requiredKeys.filter((k) => finalEnv[k] === undefined);
502
- if (missing.length > 0) {
503
- return missing.map((k) => `[requiredKeys] missing: ${k}`);
504
- }
505
- }
506
- return [];
507
- };
508
-
509
- export { discoverConfigFiles, loadConfigFile, resolveGetDotenvConfigSources, toFileUrl, validateEnvAgainstSources };
1
+ export { d as discoverConfigFiles, l as loadConfigFile, r as resolveGetDotenvConfigSources, t as toFileUrl } from './chunks/loader-DnhPeGfq.mjs';
2
+ export { v as validateEnvAgainstSources } from './chunks/validate-CDl0rE6k.mjs';
3
+ import 'fs-extra';
4
+ import 'package-directory';
5
+ import 'path';
6
+ import 'url';
7
+ import 'yaml';
8
+ import 'zod';
9
+ import './chunks/loadModuleDefault-Dj8B3Stt.mjs';
10
+ import 'crypto';