envclinic 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,3348 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/run.ts
4
+ import { Command, CommanderError } from "commander";
5
+
6
+ // package.json
7
+ var package_default = {
8
+ name: "envclinic",
9
+ version: "0.1.0",
10
+ description: "Audit, validate and secure environment configurations",
11
+ keywords: [
12
+ "env",
13
+ "dotenv",
14
+ "environment",
15
+ "audit",
16
+ "cli",
17
+ "validation",
18
+ "secrets"
19
+ ],
20
+ license: "MIT",
21
+ type: "module",
22
+ main: "./dist/index.cjs",
23
+ module: "./dist/index.js",
24
+ types: "./dist/index.d.ts",
25
+ exports: {
26
+ ".": {
27
+ import: {
28
+ types: "./dist/index.d.ts",
29
+ default: "./dist/index.js"
30
+ },
31
+ require: {
32
+ types: "./dist/index.d.cts",
33
+ default: "./dist/index.cjs"
34
+ }
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ bin: {
39
+ envclinic: "./dist/cli/index.js"
40
+ },
41
+ files: [
42
+ "dist",
43
+ "README.md",
44
+ "LICENSE",
45
+ "CHANGELOG.md"
46
+ ],
47
+ engines: {
48
+ node: ">=18"
49
+ },
50
+ scripts: {
51
+ clean: `node -e "require('node:fs').rmSync('dist',{recursive:true,force:true})"`,
52
+ build: "npm run clean && tsup",
53
+ dev: "tsup --watch",
54
+ test: "vitest run",
55
+ typecheck: "tsc --noEmit",
56
+ prepublishOnly: "npm run build && npm run test && npm run typecheck",
57
+ changeset: "changeset",
58
+ version: "changeset version",
59
+ release: "npm run build && changeset publish"
60
+ },
61
+ dependencies: {
62
+ commander: "^12.1.0",
63
+ "fast-glob": "^3.3.2",
64
+ picocolors: "^1.1.0"
65
+ },
66
+ devDependencies: {
67
+ "@changesets/cli": "^3.0.3",
68
+ "@types/node": "^22.0.0",
69
+ tsup: "^8.3.0",
70
+ typescript: "^5.6.0",
71
+ vitest: "^2.1.0"
72
+ },
73
+ publishConfig: {
74
+ access: "public"
75
+ },
76
+ sideEffects: false,
77
+ repository: {
78
+ type: "git",
79
+ url: "git+https://github.com/reda-trouki/envclinic.git"
80
+ }
81
+ };
82
+
83
+ // src/analyzers/duplicates.ts
84
+ function findDuplicates(file, entries) {
85
+ const lines = /* @__PURE__ */ new Map();
86
+ for (const entry of entries) {
87
+ const existing = lines.get(entry.key);
88
+ if (existing) existing.push(entry.line);
89
+ else lines.set(entry.key, [entry.line]);
90
+ }
91
+ const issues = [];
92
+ for (const [variable, where] of [...lines].sort(([a], [b]) => a.localeCompare(b))) {
93
+ if (where.length < 2) continue;
94
+ issues.push({
95
+ code: "duplicate-variable",
96
+ rule: "duplicates",
97
+ file,
98
+ variable,
99
+ line: where[0],
100
+ message: `${variable} is declared ${where.length} times in ${file} (lines ${where.join(", ")})`,
101
+ recommendation: `Keep a single declaration of ${variable}. Environment loaders disagree about which duplicate wins.`
102
+ });
103
+ }
104
+ return issues;
105
+ }
106
+
107
+ // src/analyzers/empty.ts
108
+ function findEmpty(file, entries) {
109
+ const seen = /* @__PURE__ */ new Set();
110
+ const issues = [];
111
+ for (const entry of entries) {
112
+ if (entry.value !== "" || seen.has(entry.key)) continue;
113
+ seen.add(entry.key);
114
+ issues.push({
115
+ code: "empty-variable",
116
+ rule: "empty",
117
+ file,
118
+ variable: entry.key,
119
+ line: entry.line,
120
+ message: `${entry.key} has an empty value in ${file}`,
121
+ recommendation: `Set a value for ${entry.key}, or remove it if it is not needed.`
122
+ });
123
+ }
124
+ return issues;
125
+ }
126
+
127
+ // src/analyzers/missing.ts
128
+ function sorted(keys) {
129
+ return [...keys].sort((a, b) => a.localeCompare(b));
130
+ }
131
+ function findMissing(exampleFile, exampleKeys, sourceFile, sourceKeys) {
132
+ return sorted(exampleKeys).filter((key) => !sourceKeys.has(key)).map((variable) => ({
133
+ code: "missing-variable",
134
+ rule: "missing",
135
+ file: sourceFile,
136
+ variable,
137
+ message: `${variable} is declared in ${exampleFile} but missing from ${sourceFile}`,
138
+ recommendation: `Add ${variable} to ${sourceFile}, or remove it from ${exampleFile} if it is no longer needed.`
139
+ }));
140
+ }
141
+ function findUndocumented(exampleFile, exampleKeys, sourceFile, sourceKeys) {
142
+ return sorted(sourceKeys).filter((key) => !exampleKeys.has(key)).map((variable) => ({
143
+ code: "undocumented-variable",
144
+ rule: "undocumented",
145
+ file: sourceFile,
146
+ variable,
147
+ message: `${variable} is set in ${sourceFile} but not documented in ${exampleFile}`,
148
+ recommendation: `Add ${variable}= (without a value) to ${exampleFile} so other developers know it exists.`
149
+ }));
150
+ }
151
+
152
+ // src/core/secrets-detector.ts
153
+ var BUILTIN_PATTERNS = [
154
+ {
155
+ id: "aws-access-key-id",
156
+ description: "AWS access key ID",
157
+ pattern: /\b(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}\b/,
158
+ severity: "error"
159
+ },
160
+ {
161
+ id: "aws-secret-access-key",
162
+ description: "AWS secret access key",
163
+ pattern: /^[A-Za-z0-9/+=]{40}$/,
164
+ name: /AWS_SECRET_ACCESS_KEY|AWS_SECRET_KEY/i,
165
+ envOnly: true,
166
+ severity: "error"
167
+ },
168
+ {
169
+ id: "github-token",
170
+ description: "GitHub token",
171
+ pattern: /\bgh[pousr]_[A-Za-z0-9]{36,255}\b/,
172
+ severity: "error"
173
+ },
174
+ {
175
+ id: "github-fine-grained-token",
176
+ description: "GitHub fine-grained token",
177
+ pattern: /\bgithub_pat_[A-Za-z0-9_]{22,255}\b/,
178
+ severity: "error"
179
+ },
180
+ {
181
+ id: "slack-token",
182
+ description: "Slack token",
183
+ pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/,
184
+ severity: "error"
185
+ },
186
+ {
187
+ id: "stripe-secret-key",
188
+ description: "Stripe secret key",
189
+ pattern: /\b(?:sk|rk)_live_[0-9a-zA-Z]{16,}\b/,
190
+ severity: "error"
191
+ },
192
+ {
193
+ id: "google-api-key",
194
+ description: "Google API key",
195
+ pattern: /\bAIza[0-9A-Za-z_-]{35}\b/,
196
+ severity: "error"
197
+ },
198
+ {
199
+ id: "private-key",
200
+ description: "private key",
201
+ pattern: /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/,
202
+ severity: "error"
203
+ },
204
+ {
205
+ id: "sendgrid-api-key",
206
+ description: "SendGrid API key",
207
+ pattern: /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/,
208
+ severity: "error"
209
+ },
210
+ {
211
+ id: "npm-token",
212
+ description: "npm access token",
213
+ pattern: /\bnpm_[A-Za-z0-9]{36}\b/,
214
+ severity: "error"
215
+ },
216
+ {
217
+ id: "anthropic-api-key",
218
+ description: "Anthropic API key",
219
+ pattern: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/,
220
+ severity: "error"
221
+ },
222
+ {
223
+ id: "openai-api-key",
224
+ description: "OpenAI API key",
225
+ pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{40,}\b/,
226
+ severity: "error"
227
+ },
228
+ {
229
+ id: "twilio-api-key",
230
+ description: "Twilio API key",
231
+ pattern: /\bSK[0-9a-f]{32}\b/,
232
+ severity: "error"
233
+ },
234
+ {
235
+ id: "json-web-token",
236
+ description: "JSON Web Token",
237
+ pattern: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
238
+ severity: "warning"
239
+ },
240
+ {
241
+ id: "credentialed-url",
242
+ description: "URL with embedded credentials",
243
+ pattern: /\b[a-z][a-z0-9+.-]*:\/\/[^\s:@/'"`<>]+:([^\s@/'"`<>]+)@[^\s'"`<>]+/i,
244
+ severity: "warning"
245
+ }
246
+ ];
247
+ function buildPatterns(custom = []) {
248
+ return [
249
+ ...BUILTIN_PATTERNS,
250
+ ...custom.map(
251
+ (entry) => ({
252
+ id: entry.id,
253
+ description: entry.description ?? entry.id,
254
+ pattern: new RegExp(entry.pattern),
255
+ severity: entry.severity ?? "error"
256
+ })
257
+ )
258
+ ];
259
+ }
260
+ var URL_PASSWORD_PLACEHOLDER = /^(?:pass(?:word)?|pwd|secret|changeme|change[-_]?me|example|xxx+|\*+|\.\.\.|<.*>|\$\{.*\}|\{\{.*\}\}|%.*%|your[-_ ].*|password\d*|postgres|root|admin|test|user|db|mysql)$/i;
261
+ function isPlaceholderUrlPassword(value, pattern) {
262
+ const match = pattern.exec(value);
263
+ const password = match?.[1];
264
+ return password === void 0 || URL_PASSWORD_PLACEHOLDER.test(password);
265
+ }
266
+ function findValueMatch(value, name, patterns) {
267
+ for (const pattern of patterns) {
268
+ if (pattern.name !== void 0 && !pattern.name.test(name)) continue;
269
+ if (!pattern.pattern.test(value)) continue;
270
+ if (pattern.id === "credentialed-url" && isPlaceholderUrlPassword(value, pattern.pattern))
271
+ continue;
272
+ return pattern;
273
+ }
274
+ return void 0;
275
+ }
276
+ var MAX_LINE_LENGTH = 1e4;
277
+ var SUPPRESS_COMMENT = "envclinic-ignore";
278
+ function scanTextForSecrets(content, patterns) {
279
+ const usable = patterns.filter(
280
+ (pattern) => !pattern.envOnly && pattern.name === void 0
281
+ );
282
+ const matches = [];
283
+ const lines = content.split("\n");
284
+ for (let i = 0; i < lines.length; i++) {
285
+ const line = lines[i];
286
+ if (line.length > MAX_LINE_LENGTH || line.includes(SUPPRESS_COMMENT))
287
+ continue;
288
+ for (const pattern of usable) {
289
+ if (!pattern.pattern.test(line)) continue;
290
+ if (pattern.id === "credentialed-url" && isPlaceholderUrlPassword(line, pattern.pattern))
291
+ continue;
292
+ matches.push({ pattern, line: i + 1 });
293
+ }
294
+ }
295
+ return matches;
296
+ }
297
+ var SECRET_NAME = /(?:^|_)(?:SECRET|PASSWORD|PASSWD|PASSPHRASE|TOKEN|PRIVATE_KEY|API_KEY|APIKEY|ACCESS_KEY|SECRET_KEY|SIGNING_KEY|ENCRYPTION_KEY|AUTH_KEY|CREDENTIALS?)(?:_|$)/i;
298
+ var NOT_A_SECRET_SUFFIX = /_(?:URL|URI|PATH|FILE|DIR|ENABLED|ENDPOINT|HEADER|TTL|EXPIRES|EXPIRES_IN|EXPIRY|ALGORITHM|TYPE|NAME|ID|LENGTH|ROUNDS|COST|PREFIX|FORMAT|REGION|HOST|PORT)$/i;
299
+ var PUBLIC_NAME = /PUBLIC|PUBLISHABLE/i;
300
+ function isSecretName(name) {
301
+ return SECRET_NAME.test(name) && !NOT_A_SECRET_SUFFIX.test(name) && !PUBLIC_NAME.test(name);
302
+ }
303
+ var PLACEHOLDER_EXACT = /^(?:secret|password|passwd|pass|admin|root|test|testing|changeme|change[-_ ]?me|default|example|token|key|none|null|undefined|todo|xxx+|\*+|1234\d*|abc\d*|qwerty|letmein|postgres|mysql|redis|dev|development)$/i;
304
+ var PLACEHOLDER_CONTAINS = /(?:change[-_ ]?me|your[-_ ]?(?:secret|key|token|password|api)|<[^>]+>|placeholder|replace[-_ ]?(?:me|this)|xxxxxx|dummy|\.\.\.)/i;
305
+ var BOOLEANISH = /^(?:true|false|yes|no|on|off)$/i;
306
+ var REFERENCE = /^\$\{.*\}$|^\$[A-Za-z_]\w*$/;
307
+ function isPlaceholder(value) {
308
+ return PLACEHOLDER_EXACT.test(value) || PLACEHOLDER_CONTAINS.test(value);
309
+ }
310
+ function isReferenceOrFlag(value) {
311
+ return REFERENCE.test(value) || BOOLEANISH.test(value);
312
+ }
313
+ function shannonEntropy(value) {
314
+ if (value.length === 0) return 0;
315
+ const counts = /* @__PURE__ */ new Map();
316
+ for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
317
+ let entropy = 0;
318
+ for (const count of counts.values()) {
319
+ const p = count / value.length;
320
+ entropy -= p * Math.log2(p);
321
+ }
322
+ return entropy;
323
+ }
324
+ var MIN_SECRET_LENGTH = 12;
325
+ var MIN_SECRET_ENTROPY = 3;
326
+ function weakSecretReason(value) {
327
+ if (value === "" || isReferenceOrFlag(value)) return void 0;
328
+ if (isPlaceholder(value)) return "looks like a placeholder or common default";
329
+ if (value.length < MIN_SECRET_LENGTH)
330
+ return `shorter than ${MIN_SECRET_LENGTH} characters`;
331
+ if (shannonEntropy(value) < MIN_SECRET_ENTROPY) return "low entropy";
332
+ return void 0;
333
+ }
334
+
335
+ // src/analyzers/security.ts
336
+ var PUBLIC_SECRET_NAME = /SECRET|PASSWORD|PASSWD|PRIVATE/i;
337
+ var ROTATE = "Remove it, store the value outside version control, and rotate it if it may ever have been committed or shared.";
338
+ function analyzeEnvFileSecrets(file, git, options) {
339
+ const issues = [];
340
+ const example = file.role === "example";
341
+ const reportedPublic = /* @__PURE__ */ new Set();
342
+ for (const entry of file.entries) {
343
+ const name = entry.key;
344
+ if (options.isIgnored(name) || options.isAllowed(name)) continue;
345
+ const prefix = options.publicPrefixes.find(
346
+ (candidate) => name.startsWith(candidate)
347
+ );
348
+ const match = entry.value === "" ? void 0 : findValueMatch(entry.value, name, options.patterns);
349
+ if (prefix !== void 0 && !reportedPublic.has(name)) {
350
+ const nameLooksSecret = PUBLIC_SECRET_NAME.test(
351
+ name.slice(prefix.length)
352
+ );
353
+ if (match !== void 0 || nameLooksSecret) {
354
+ reportedPublic.add(name);
355
+ issues.push({
356
+ code: "public-secret",
357
+ rule: "secrets",
358
+ severity: match !== void 0 ? "error" : "warning",
359
+ file: file.path,
360
+ line: entry.line,
361
+ variable: name,
362
+ message: `${name} looks like a secret but its ${prefix} prefix exposes it to the browser bundle`,
363
+ recommendation: `Rename it without the ${prefix} prefix and read it only on the server, or confirm that it is meant to be public.`
364
+ });
365
+ }
366
+ }
367
+ if (entry.value === "") continue;
368
+ if (match !== void 0) {
369
+ const severity = example || git === "not-ignored" ? match.severity : git === "ignored" ? "info" : match.severity === "error" ? "warning" : "info";
370
+ const where = example ? "in a template file that is normally committed" : git === "ignored" ? "in a git-ignored local file" : git === "not-ignored" ? "in a file that is not git-ignored" : "in an environment file";
371
+ issues.push({
372
+ code: "exposed-credential",
373
+ rule: "secrets",
374
+ severity,
375
+ file: file.path,
376
+ line: entry.line,
377
+ variable: name,
378
+ message: `Potential exposed credential (${match.description}) ${where}`,
379
+ recommendation: example ? `Replace it with an empty value. ${ROTATE}` : git === "ignored" ? "Expected for local development. Make sure this file is never committed." : ROTATE
380
+ });
381
+ continue;
382
+ }
383
+ if (example) {
384
+ if (isSecretName(name) && !isPlaceholder(entry.value) && !isReferenceOrFlag(entry.value) && entry.value.length >= 8) {
385
+ issues.push({
386
+ code: "secret-in-example",
387
+ rule: "secrets",
388
+ severity: "warning",
389
+ file: file.path,
390
+ line: entry.line,
391
+ variable: name,
392
+ message: `${name} has a value in a template file that is normally committed`,
393
+ recommendation: "Template files should list names only. Replace the value with an empty one or an obvious placeholder."
394
+ });
395
+ }
396
+ continue;
397
+ }
398
+ if (isSecretName(name)) {
399
+ const reason = weakSecretReason(entry.value);
400
+ if (reason !== void 0) {
401
+ issues.push({
402
+ code: "weak-secret",
403
+ rule: "weak",
404
+ severity: "warning",
405
+ file: file.path,
406
+ line: entry.line,
407
+ variable: name,
408
+ message: `Weak secret (${reason})`,
409
+ recommendation: `Use a long random value, for example from \`openssl rand -base64 32\`.`
410
+ });
411
+ }
412
+ }
413
+ }
414
+ const hasValues = file.entries.some(
415
+ (entry) => entry.value !== "" && !options.isIgnored(entry.key)
416
+ );
417
+ if (!example && git === "not-ignored" && hasValues) {
418
+ issues.push({
419
+ code: "env-file-not-ignored",
420
+ rule: "secrets",
421
+ severity: "error",
422
+ file: file.path,
423
+ message: `${file.path} contains values but is not listed in .gitignore, so it may be committed`,
424
+ recommendation: `Add ${file.path} to .gitignore. If it was already committed, rotate its secrets and remove it from history.`
425
+ });
426
+ }
427
+ return issues;
428
+ }
429
+ function analyzeCodeSecrets(file, content, patterns) {
430
+ const seen = /* @__PURE__ */ new Set();
431
+ const issues = [];
432
+ for (const match of scanTextForSecrets(content, patterns)) {
433
+ const key = `${match.line}:${match.pattern.id}`;
434
+ if (seen.has(key)) continue;
435
+ seen.add(key);
436
+ issues.push({
437
+ code: "exposed-credential",
438
+ rule: "secrets",
439
+ severity: match.pattern.severity,
440
+ file,
441
+ line: match.line,
442
+ message: `Potential exposed credential (${match.pattern.description}) in source code`,
443
+ recommendation: "Load it from an environment variable instead, and rotate it if it was ever committed. If this is a false positive, add `envclinic-ignore` to the line or the file to secrets.ignoreFiles."
444
+ });
445
+ }
446
+ return issues;
447
+ }
448
+
449
+ // src/analyzers/syntax.ts
450
+ var VALID_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
451
+ function isValidName(key) {
452
+ return VALID_NAME.test(key);
453
+ }
454
+ function findSyntaxIssues(file, parsed) {
455
+ const issues = [];
456
+ for (const problem of parsed.problems) {
457
+ if (problem.kind === "malformed-line") {
458
+ issues.push({
459
+ code: "malformed-line",
460
+ rule: "syntax",
461
+ file,
462
+ line: problem.line,
463
+ message: `Line ${problem.line} of ${file} is not a valid KEY=value declaration`,
464
+ recommendation: "Use KEY=value, or start the line with # to make it a comment."
465
+ });
466
+ } else {
467
+ issues.push({
468
+ code: "unterminated-quote",
469
+ rule: "syntax",
470
+ file,
471
+ line: problem.line,
472
+ message: `Line ${problem.line} of ${file} has a quoted value that is never closed`,
473
+ recommendation: "Add the closing quote."
474
+ });
475
+ }
476
+ }
477
+ for (const entry of parsed.entries) {
478
+ if (!isValidName(entry.key)) {
479
+ issues.push({
480
+ code: "invalid-variable-name",
481
+ rule: "names",
482
+ file,
483
+ line: entry.line,
484
+ message: `Line ${entry.line} of ${file} has an invalid variable name`,
485
+ recommendation: "Use only letters, digits and underscores, and do not start with a digit (for example MY_VARIABLE)."
486
+ });
487
+ }
488
+ }
489
+ return issues.sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
490
+ }
491
+
492
+ // src/config/defaults.ts
493
+ var DEFAULT_SOURCE_FILES = [".env"];
494
+ var EXAMPLE_FILE_CANDIDATES = [".env.example", ".env.sample"];
495
+ var DEFAULT_RULES = {
496
+ missing: "error",
497
+ undocumented: "warning",
498
+ empty: "warning",
499
+ duplicates: "error",
500
+ names: "warning",
501
+ syntax: "warning",
502
+ unused: "warning",
503
+ undeclared: "warning",
504
+ secrets: "error",
505
+ weak: "warning",
506
+ validation: "error",
507
+ types: "warning"
508
+ };
509
+ var DEFAULT_TYPES_OUTPUT = "env.d.ts";
510
+ var DEFAULT_EXAMPLE_OUTPUT = ".env.example";
511
+ var BUILTIN_VARIABLES = /* @__PURE__ */ new Set([
512
+ "NODE_ENV",
513
+ "CI",
514
+ "HOME",
515
+ "PATH",
516
+ "PWD",
517
+ "USER",
518
+ "SHELL",
519
+ "TERM",
520
+ "TZ",
521
+ "LANG",
522
+ "TMPDIR",
523
+ "NEXT_RUNTIME",
524
+ "MODE",
525
+ "BASE_URL",
526
+ "PROD",
527
+ "DEV",
528
+ "SSR"
529
+ ]);
530
+ function isBuiltinVariable(name) {
531
+ return BUILTIN_VARIABLES.has(name) || name.startsWith("npm_") || name.startsWith("VERCEL_");
532
+ }
533
+
534
+ // src/analyzers/unused.ts
535
+ var INTERPOLATION = /\$\{([A-Za-z_]\w*)\}/g;
536
+ function interpolatedNames(project) {
537
+ const used = /* @__PURE__ */ new Set();
538
+ const files = project.example ? [...project.sourceFiles, project.example] : project.sourceFiles;
539
+ for (const file of files) {
540
+ for (const entry of file.entries) {
541
+ if (entry.quote === "single") continue;
542
+ for (const match of entry.value.matchAll(INTERPOLATION)) used.add(match[1]);
543
+ }
544
+ }
545
+ return used;
546
+ }
547
+ function findUnused(project, usage) {
548
+ if (usage.filesScanned === 0) return [];
549
+ const used = interpolatedNames(project);
550
+ const declared = /* @__PURE__ */ new Map();
551
+ for (const file of [...project.sourceFiles, ...project.example ? [project.example] : []]) {
552
+ for (const key of file.keys) if (!declared.has(key)) declared.set(key, file.path);
553
+ }
554
+ const issues = [];
555
+ for (const [variable, file] of [...declared].sort(([a], [b]) => a.localeCompare(b))) {
556
+ if (usage.references.has(variable) || used.has(variable) || project.isIgnored(variable)) continue;
557
+ issues.push({
558
+ code: "unused-variable",
559
+ rule: "unused",
560
+ file,
561
+ variable,
562
+ message: `${variable} is declared in ${file} but was not found in ${usage.filesScanned} scanned source file${usage.filesScanned === 1 ? "" : "s"} (potentially unused)`,
563
+ recommendation: `Check whether ${variable} is still needed. It may be read dynamically or by a tool outside the scanned code. If it is, add it to ignore.variables.`
564
+ });
565
+ }
566
+ if (issues.length > 0 && usage.dynamic.length > 0) {
567
+ const where = [...new Set(usage.dynamic.map((location) => location.file))];
568
+ issues.push({
569
+ code: "dynamic-env-access",
570
+ severity: "info",
571
+ message: `${usage.dynamic.length} dynamic environment access${usage.dynamic.length === 1 ? "" : "es"} found in ${where.length} file${where.length === 1 ? "" : "s"} (for example ${where[0]}), so some variables reported as unused may still be read`,
572
+ recommendation: "Review the potentially unused variables before removing anything."
573
+ });
574
+ }
575
+ return issues;
576
+ }
577
+ function findUndeclared(project, usage) {
578
+ const known = /* @__PURE__ */ new Set();
579
+ for (const file of [...project.sourceFiles, ...project.example ? [project.example] : []]) {
580
+ for (const key of file.keys) known.add(key);
581
+ }
582
+ if (project.sourceFiles.length === 0 && project.example === void 0) return [];
583
+ const reference = project.example?.path ?? project.sourceFiles[0]?.path ?? ".env.example";
584
+ const issues = [];
585
+ for (const [variable, locations] of [...usage.references].sort(([a], [b]) => a.localeCompare(b))) {
586
+ if (known.has(variable) || project.isIgnored(variable) || isBuiltinVariable(variable)) continue;
587
+ const first = locations[0];
588
+ issues.push({
589
+ code: "undeclared-variable",
590
+ rule: "undeclared",
591
+ file: first.file,
592
+ line: first.line,
593
+ variable,
594
+ message: `${variable} is used in ${first.file}${locations.length > 1 ? ` (and ${locations.length - 1} more place${locations.length === 2 ? "" : "s"})` : ""} but is not set in any env file or documented in ${reference}`,
595
+ recommendation: `Add ${variable}= to ${reference} so other developers know it is required, or add it to ignore.variables if the platform provides it.`
596
+ });
597
+ }
598
+ return issues;
599
+ }
600
+
601
+ // src/core/project.ts
602
+ import path5 from "path";
603
+
604
+ // src/config/loader.ts
605
+ import { promises as fs3 } from "fs";
606
+ import path3 from "path";
607
+ import { pathToFileURL } from "url";
608
+
609
+ // src/core/files.ts
610
+ import { promises as fs } from "fs";
611
+ import path from "path";
612
+ var MAX_ENV_FILE_BYTES = 5 * 1024 * 1024;
613
+ function decodeText(buf) {
614
+ if (buf.length >= 2 && buf[0] === 255 && buf[1] === 254) {
615
+ return { text: buf.subarray(2).toString("utf16le"), encoding: "utf-16le" };
616
+ }
617
+ if (buf.length >= 2 && buf[0] === 254 && buf[1] === 255) {
618
+ return { text: Buffer.from(buf.subarray(2)).swap16().toString("utf16le"), encoding: "utf-16be" };
619
+ }
620
+ if (buf.length >= 4 && buf.length % 2 === 0) {
621
+ const sample = Math.min(buf.length, 512) & ~1;
622
+ let evenZero = 0;
623
+ let oddZero = 0;
624
+ for (let i = 0; i < sample; i += 2) {
625
+ if (buf[i] === 0) evenZero++;
626
+ if (buf[i + 1] === 0) oddZero++;
627
+ }
628
+ const pairs = sample / 2;
629
+ if (oddZero > pairs * 0.4 && evenZero === 0) return { text: buf.toString("utf16le"), encoding: "utf-16le" };
630
+ if (evenZero > pairs * 0.4 && oddZero === 0) return { text: Buffer.from(buf).swap16().toString("utf16le"), encoding: "utf-16be" };
631
+ }
632
+ return { text: buf.toString("utf8"), encoding: "utf-8" };
633
+ }
634
+ function isInside(root, target) {
635
+ const rel = path.relative(root, target);
636
+ if (rel === "") return true;
637
+ if (rel === ".." || rel.startsWith(".." + path.sep)) return false;
638
+ return !path.isAbsolute(rel);
639
+ }
640
+ function displayPath(root, absolute) {
641
+ const rel = path.relative(root, absolute);
642
+ return (rel === "" ? "." : rel).split(path.sep).join("/");
643
+ }
644
+ async function readEnvFile(root, relative) {
645
+ const absolute = path.resolve(root, relative);
646
+ if (!isInside(root, absolute)) {
647
+ return { status: "unsafe", reason: "the path is outside the project directory" };
648
+ }
649
+ try {
650
+ await fs.lstat(absolute);
651
+ } catch (error) {
652
+ const code = error.code;
653
+ return code === "ENOENT" || code === "ENOTDIR" ? { status: "missing" } : { status: "unreadable" };
654
+ }
655
+ let real;
656
+ let realRoot;
657
+ try {
658
+ real = await fs.realpath(absolute);
659
+ realRoot = await fs.realpath(root);
660
+ } catch {
661
+ return { status: "unsafe", reason: "the path is a broken symbolic link" };
662
+ }
663
+ if (!isInside(realRoot, real)) {
664
+ return { status: "unsafe", reason: "the file is a symbolic link that points outside the project directory" };
665
+ }
666
+ try {
667
+ const stat = await fs.stat(real);
668
+ if (!stat.isFile()) return { status: "unsafe", reason: "the path is not a regular file" };
669
+ if (stat.size > MAX_ENV_FILE_BYTES) return { status: "too-large" };
670
+ const decoded = decodeText(await fs.readFile(real));
671
+ return { status: "ok", content: decoded.text, encoding: decoded.encoding };
672
+ } catch {
673
+ return { status: "unreadable" };
674
+ }
675
+ }
676
+
677
+ // src/frameworks/detector.ts
678
+ import { promises as fs2 } from "fs";
679
+ import path2 from "path";
680
+ var DEFINITIONS = [
681
+ {
682
+ id: "nextjs",
683
+ name: "Next.js",
684
+ dependencies: ["next"],
685
+ files: ["next.config.js", "next.config.mjs", "next.config.cjs", "next.config.ts"],
686
+ accessPatterns: ["process.env"],
687
+ publicPrefixes: ["NEXT_PUBLIC_"],
688
+ notes: "Variables prefixed with NEXT_PUBLIC_ are inlined into the browser bundle."
689
+ },
690
+ {
691
+ id: "astro",
692
+ name: "Astro",
693
+ dependencies: ["astro"],
694
+ files: ["astro.config.mjs", "astro.config.js", "astro.config.ts", "astro.config.cjs"],
695
+ accessPatterns: ["import.meta.env"],
696
+ publicPrefixes: ["PUBLIC_"],
697
+ notes: "Variables prefixed with PUBLIC_ are available in client-side code."
698
+ },
699
+ {
700
+ id: "nestjs",
701
+ name: "NestJS",
702
+ dependencies: ["@nestjs/core"],
703
+ files: ["nest-cli.json"],
704
+ accessPatterns: ["process.env"],
705
+ publicPrefixes: [],
706
+ notes: "Server-side only. Variables are normally read through process.env or @nestjs/config."
707
+ },
708
+ {
709
+ id: "vite",
710
+ name: "Vite",
711
+ dependencies: ["vite"],
712
+ files: ["vite.config.js", "vite.config.mjs", "vite.config.cjs", "vite.config.ts", "vite.config.mts"],
713
+ accessPatterns: ["import.meta.env"],
714
+ publicPrefixes: ["VITE_"],
715
+ notes: "Only variables prefixed with VITE_ (or your envPrefix setting) are exposed to client code."
716
+ },
717
+ {
718
+ id: "react",
719
+ name: "React",
720
+ dependencies: ["react", "react-scripts"],
721
+ files: [],
722
+ accessPatterns: ["process.env", "import.meta.env"],
723
+ publicPrefixes: [],
724
+ notes: "Depends on the build tool. Create React App exposes REACT_APP_ variables."
725
+ },
726
+ {
727
+ id: "express",
728
+ name: "Express",
729
+ dependencies: ["express"],
730
+ files: [],
731
+ accessPatterns: ["process.env"],
732
+ publicPrefixes: [],
733
+ notes: "Server-side only. Variables are read through process.env."
734
+ }
735
+ ];
736
+ var NODE = {
737
+ id: "node",
738
+ name: "Node.js",
739
+ dependencies: [],
740
+ files: [],
741
+ accessPatterns: ["process.env"],
742
+ publicPrefixes: [],
743
+ notes: "Plain Node.js conventions: variables are read through process.env."
744
+ };
745
+ async function readDependencies(cwd) {
746
+ try {
747
+ const stat = await fs2.stat(path2.join(cwd, "package.json"));
748
+ if (stat.size > 1024 * 1024) return { present: true, names: /* @__PURE__ */ new Set() };
749
+ const parsed = JSON.parse(await fs2.readFile(path2.join(cwd, "package.json"), "utf8"));
750
+ const names = /* @__PURE__ */ new Set();
751
+ if (typeof parsed === "object" && parsed !== null) {
752
+ for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
753
+ const section = parsed[field];
754
+ if (typeof section === "object" && section !== null) {
755
+ for (const name of Object.keys(section)) names.add(name);
756
+ }
757
+ }
758
+ }
759
+ return { present: true, names };
760
+ } catch {
761
+ return { present: false, names: /* @__PURE__ */ new Set() };
762
+ }
763
+ }
764
+ async function exists(file) {
765
+ try {
766
+ await fs2.access(file);
767
+ return true;
768
+ } catch {
769
+ return false;
770
+ }
771
+ }
772
+ async function detectFramework(cwd, config = {}) {
773
+ const { present, names } = await readDependencies(cwd);
774
+ const evidence = [];
775
+ const matched = [];
776
+ for (const definition of DEFINITIONS) {
777
+ const reasons = [];
778
+ for (const dependency of definition.dependencies) {
779
+ if (names.has(dependency)) reasons.push(`dependency "${dependency}"`);
780
+ }
781
+ for (const file of definition.files) {
782
+ if (await exists(path2.join(cwd, file))) reasons.push(`file ${file}`);
783
+ }
784
+ if (reasons.length > 0) {
785
+ matched.push(definition);
786
+ evidence.push(...reasons.map((reason) => `${definition.name}: ${reason}`));
787
+ }
788
+ }
789
+ const notes = [];
790
+ let primary = matched[0] ?? NODE;
791
+ if (matched.length === 0) {
792
+ evidence.push(
793
+ present ? "No framework dependency found; assuming plain Node.js conventions." : "No package.json found; assuming plain Node.js conventions."
794
+ );
795
+ }
796
+ let forced = false;
797
+ if (config.framework !== void 0 && config.framework !== "auto") {
798
+ const requested = config.framework;
799
+ primary = [...DEFINITIONS, NODE].find((definition) => definition.id === requested) ?? primary;
800
+ forced = true;
801
+ evidence.unshift(`${primary.name}: forced by the "framework" config option`);
802
+ }
803
+ const reactScripts = names.has("react-scripts");
804
+ let prefixes;
805
+ if (forced) {
806
+ prefixes = [...primary.publicPrefixes];
807
+ if (primary.id === "react" && reactScripts) prefixes.push("REACT_APP_");
808
+ } else {
809
+ prefixes = [.../* @__PURE__ */ new Set([...matched.flatMap((definition) => definition.publicPrefixes), ...reactScripts ? ["REACT_APP_"] : []])];
810
+ }
811
+ if (config.publicPrefixes !== void 0) prefixes = [...config.publicPrefixes];
812
+ notes.push(primary.notes);
813
+ if (primary.id === "react" && !reactScripts) {
814
+ notes.push("react-scripts was not found, so no client prefix is assumed. Set publicPrefixes if your build tool exposes one.");
815
+ }
816
+ if (config.publicPrefixes !== void 0) {
817
+ notes.push("Public prefixes come from the publicPrefixes config option.");
818
+ }
819
+ const detected = [.../* @__PURE__ */ new Set([primary.id, ...matched.map((definition) => definition.id)])];
820
+ return {
821
+ id: primary.id,
822
+ name: primary.name,
823
+ accessPatterns: [...primary.accessPatterns],
824
+ publicPrefixes: prefixes,
825
+ evidence,
826
+ detected,
827
+ forced,
828
+ notes
829
+ };
830
+ }
831
+ var FRAMEWORK_IDS = [...DEFINITIONS.map((definition) => definition.id), "node"];
832
+
833
+ // src/config/schema.ts
834
+ var ConfigError = class extends Error {
835
+ constructor(message) {
836
+ super(message);
837
+ this.name = "ConfigError";
838
+ }
839
+ };
840
+ var TOP_LEVEL_KEYS = [
841
+ "files",
842
+ "scan",
843
+ "rules",
844
+ "ignore",
845
+ "secrets",
846
+ "schema",
847
+ "framework",
848
+ "publicPrefixes",
849
+ "types",
850
+ "generate"
851
+ ];
852
+ var LEVELS = ["error", "warning", "off"];
853
+ var SCHEMA_TYPES = ["string", "number", "boolean", "url", "email", "enum", "integer", "custom"];
854
+ var SCHEMA_FIELD_KEYS = [
855
+ "type",
856
+ "required",
857
+ "default",
858
+ "description",
859
+ "secret",
860
+ "minLength",
861
+ "maxLength",
862
+ "min",
863
+ "max",
864
+ "pattern",
865
+ "values",
866
+ "protocols",
867
+ "validate"
868
+ ];
869
+ var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
870
+ function isObject(value) {
871
+ return typeof value === "object" && value !== null && !Array.isArray(value);
872
+ }
873
+ var Validator = class {
874
+ constructor(origin) {
875
+ this.origin = origin;
876
+ }
877
+ origin;
878
+ fail(message) {
879
+ throw new ConfigError(`Invalid config in ${this.origin}: ${message}`);
880
+ }
881
+ object(value, name) {
882
+ if (!isObject(value)) this.fail(`"${name}" must be an object.`);
883
+ return value;
884
+ }
885
+ known(obj, allowed, prefix) {
886
+ for (const key of Object.keys(obj)) {
887
+ if (!allowed.includes(key)) {
888
+ this.fail(`unknown option "${prefix}${key}". Allowed: ${allowed.map((k) => prefix + k).join(", ")}.`);
889
+ }
890
+ }
891
+ }
892
+ strings(value, name) {
893
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string" || v === "")) {
894
+ this.fail(`"${name}" must be an array of non-empty strings.`);
895
+ }
896
+ return value;
897
+ }
898
+ string(value, name) {
899
+ if (typeof value !== "string" || value === "") this.fail(`"${name}" must be a non-empty string.`);
900
+ return value;
901
+ }
902
+ boolean(value, name) {
903
+ if (typeof value !== "boolean") this.fail(`"${name}" must be true or false.`);
904
+ return value;
905
+ }
906
+ number(value, name) {
907
+ if (typeof value !== "number" || !Number.isFinite(value)) this.fail(`"${name}" must be a number.`);
908
+ return value;
909
+ }
910
+ regex(value, name) {
911
+ const source = this.string(value, name);
912
+ try {
913
+ new RegExp(source);
914
+ } catch {
915
+ this.fail(`"${name}" is not a valid regular expression.`);
916
+ }
917
+ return source;
918
+ }
919
+ };
920
+ function validateSchema(v, raw) {
921
+ const input = v.object(raw, "schema");
922
+ const schema = {};
923
+ for (const [name, entry] of Object.entries(input)) {
924
+ const where = `schema.${name}`;
925
+ if (!VARIABLE_NAME.test(name)) v.fail(`"${where}" is not a valid variable name.`);
926
+ const obj = v.object(entry, where);
927
+ v.known(obj, SCHEMA_FIELD_KEYS, `${where}.`);
928
+ const type = obj.type;
929
+ if (typeof type !== "string" || !SCHEMA_TYPES.includes(type)) {
930
+ v.fail(`"${where}.type" must be one of ${SCHEMA_TYPES.map((t) => `"${t}"`).join(", ")}.`);
931
+ }
932
+ const field = { type };
933
+ if (obj.required !== void 0) field.required = v.boolean(obj.required, `${where}.required`);
934
+ if (obj.secret !== void 0) field.secret = v.boolean(obj.secret, `${where}.secret`);
935
+ if (obj.description !== void 0) field.description = v.string(obj.description, `${where}.description`);
936
+ for (const key of ["minLength", "maxLength", "min", "max"]) {
937
+ if (obj[key] !== void 0) field[key] = v.number(obj[key], `${where}.${key}`);
938
+ }
939
+ if (field.minLength !== void 0 && field.maxLength !== void 0 && field.minLength > field.maxLength) {
940
+ v.fail(`"${where}.minLength" cannot be greater than "${where}.maxLength".`);
941
+ }
942
+ if (field.min !== void 0 && field.max !== void 0 && field.min > field.max) {
943
+ v.fail(`"${where}.min" cannot be greater than "${where}.max".`);
944
+ }
945
+ if (obj.pattern !== void 0) field.pattern = v.regex(obj.pattern, `${where}.pattern`);
946
+ if (obj.protocols !== void 0) field.protocols = v.strings(obj.protocols, `${where}.protocols`);
947
+ if (obj.values !== void 0) field.values = v.strings(obj.values, `${where}.values`);
948
+ if (field.type === "enum" && (field.values === void 0 || field.values.length === 0)) {
949
+ v.fail(`"${where}.values" is required for enum variables and must not be empty.`);
950
+ }
951
+ if (obj.validate !== void 0) {
952
+ if (typeof obj.validate !== "function") v.fail(`"${where}.validate" must be a function.`);
953
+ field.validate = obj.validate;
954
+ }
955
+ if (field.type === "custom" && field.validate === void 0) {
956
+ v.fail(`"${where}.validate" is required for custom variables (custom validators need a JavaScript config file).`);
957
+ }
958
+ if (obj.default !== void 0) {
959
+ const d = obj.default;
960
+ const expected = field.type === "number" || field.type === "integer" ? "number" : field.type === "boolean" ? "boolean" : "string";
961
+ if (typeof d !== expected) v.fail(`"${where}.default" must be a ${expected} for ${field.type} variables.`);
962
+ field.default = d;
963
+ }
964
+ schema[name] = field;
965
+ }
966
+ return schema;
967
+ }
968
+ function validateConfig(raw, origin) {
969
+ const v = new Validator(origin);
970
+ const input = v.object(raw, "config");
971
+ v.known(input, TOP_LEVEL_KEYS, "");
972
+ const config = {};
973
+ if (input.files !== void 0) {
974
+ const files = v.object(input.files, "files");
975
+ v.known(files, ["source", "example"], "files.");
976
+ config.files = {};
977
+ if (files.source !== void 0) config.files.source = v.strings(files.source, "files.source");
978
+ if (files.example !== void 0) config.files.example = v.string(files.example, "files.example");
979
+ }
980
+ if (input.scan !== void 0) {
981
+ const scan = v.object(input.scan, "scan");
982
+ v.known(scan, ["directories", "ignore", "extensions"], "scan.");
983
+ config.scan = {};
984
+ if (scan.directories !== void 0) config.scan.directories = v.strings(scan.directories, "scan.directories");
985
+ if (scan.ignore !== void 0) config.scan.ignore = v.strings(scan.ignore, "scan.ignore");
986
+ if (scan.extensions !== void 0) {
987
+ config.scan.extensions = v.strings(scan.extensions, "scan.extensions").map((e) => e.replace(/^\./, ""));
988
+ }
989
+ }
990
+ if (input.rules !== void 0) {
991
+ const rules = v.object(input.rules, "rules");
992
+ v.known(rules, Object.keys(DEFAULT_RULES), "rules.");
993
+ config.rules = {};
994
+ for (const [name, level] of Object.entries(rules)) {
995
+ if (typeof level !== "string" || !LEVELS.includes(level)) {
996
+ v.fail(`"rules.${name}" must be one of ${LEVELS.map((l) => `"${l}"`).join(", ")}.`);
997
+ }
998
+ config.rules[name] = level;
999
+ }
1000
+ }
1001
+ if (input.ignore !== void 0) {
1002
+ const ignore = v.object(input.ignore, "ignore");
1003
+ v.known(ignore, ["variables"], "ignore.");
1004
+ config.ignore = {};
1005
+ if (ignore.variables !== void 0) config.ignore.variables = v.strings(ignore.variables, "ignore.variables");
1006
+ }
1007
+ if (input.secrets !== void 0) {
1008
+ const secrets = v.object(input.secrets, "secrets");
1009
+ v.known(secrets, ["allow", "ignoreFiles", "patterns"], "secrets.");
1010
+ config.secrets = {};
1011
+ if (secrets.allow !== void 0) config.secrets.allow = v.strings(secrets.allow, "secrets.allow");
1012
+ if (secrets.ignoreFiles !== void 0) config.secrets.ignoreFiles = v.strings(secrets.ignoreFiles, "secrets.ignoreFiles");
1013
+ if (secrets.patterns !== void 0) {
1014
+ const list = secrets.patterns;
1015
+ if (!Array.isArray(list)) return v.fail(`"secrets.patterns" must be an array.`);
1016
+ config.secrets.patterns = list.map((entry, index) => {
1017
+ const where = `secrets.patterns[${index}]`;
1018
+ const obj = v.object(entry, where);
1019
+ v.known(obj, ["id", "description", "pattern", "severity"], `${where}.`);
1020
+ const pattern = {
1021
+ id: v.string(obj.id, `${where}.id`),
1022
+ pattern: v.regex(obj.pattern, `${where}.pattern`)
1023
+ };
1024
+ if (obj.description !== void 0) pattern.description = v.string(obj.description, `${where}.description`);
1025
+ if (obj.severity !== void 0) {
1026
+ const severity = obj.severity;
1027
+ if (severity !== "error" && severity !== "warning") {
1028
+ return v.fail(`"${where}.severity" must be "error" or "warning".`);
1029
+ }
1030
+ pattern.severity = severity;
1031
+ }
1032
+ return pattern;
1033
+ });
1034
+ }
1035
+ }
1036
+ if (input.schema !== void 0) config.schema = validateSchema(v, input.schema);
1037
+ if (input.framework !== void 0) {
1038
+ const allowed = ["auto", ...FRAMEWORK_IDS];
1039
+ if (typeof input.framework !== "string" || !allowed.includes(input.framework)) {
1040
+ v.fail(`"framework" must be one of ${allowed.map((f) => `"${f}"`).join(", ")}.`);
1041
+ }
1042
+ config.framework = input.framework;
1043
+ }
1044
+ if (input.publicPrefixes !== void 0) {
1045
+ config.publicPrefixes = v.strings(input.publicPrefixes, "publicPrefixes");
1046
+ }
1047
+ if (input.types !== void 0) {
1048
+ const types = v.object(input.types, "types");
1049
+ v.known(types, ["enabled", "output"], "types.");
1050
+ config.types = {};
1051
+ if (types.enabled !== void 0) config.types.enabled = v.boolean(types.enabled, "types.enabled");
1052
+ if (types.output !== void 0) config.types.output = v.string(types.output, "types.output");
1053
+ }
1054
+ if (input.generate !== void 0) {
1055
+ const generate = v.object(input.generate, "generate");
1056
+ v.known(generate, ["output", "exclude"], "generate.");
1057
+ config.generate = {};
1058
+ if (generate.output !== void 0) config.generate.output = v.string(generate.output, "generate.output");
1059
+ if (generate.exclude !== void 0) config.generate.exclude = v.strings(generate.exclude, "generate.exclude");
1060
+ }
1061
+ return config;
1062
+ }
1063
+
1064
+ // src/config/loader.ts
1065
+ var CONFIG_FILE_NAMES = [
1066
+ "envclinic.config.json",
1067
+ "envclinic.config.mjs",
1068
+ "envclinic.config.js",
1069
+ "envclinic.config.cjs",
1070
+ "envclinic.config.ts"
1071
+ ];
1072
+ async function loadConfig(cwd, explicitPath) {
1073
+ let absolute;
1074
+ if (explicitPath !== void 0) {
1075
+ absolute = path3.resolve(cwd, explicitPath);
1076
+ if (!await exists2(absolute)) {
1077
+ throw new ConfigError(
1078
+ `Config file not found: ${displayPath(cwd, absolute)}`
1079
+ );
1080
+ }
1081
+ } else {
1082
+ for (const name of CONFIG_FILE_NAMES) {
1083
+ const candidate = path3.join(cwd, name);
1084
+ if (await exists2(candidate)) {
1085
+ absolute = candidate;
1086
+ break;
1087
+ }
1088
+ }
1089
+ }
1090
+ if (absolute === void 0) return { config: {} };
1091
+ const shown = displayPath(cwd, absolute);
1092
+ const raw = await readRaw(absolute, shown);
1093
+ return { config: validateConfig(raw, shown), file: shown };
1094
+ }
1095
+ async function readRaw(absolute, shown) {
1096
+ const ext = path3.extname(absolute).toLowerCase();
1097
+ if (ext === ".json") {
1098
+ let text;
1099
+ try {
1100
+ text = await fs3.readFile(absolute, "utf8");
1101
+ } catch (error) {
1102
+ throw new ConfigError(
1103
+ `Could not read config file ${shown}: ${error.message}`
1104
+ );
1105
+ }
1106
+ try {
1107
+ return JSON.parse(text);
1108
+ } catch (error) {
1109
+ throw new ConfigError(
1110
+ `Config file ${shown} is not valid JSON: ${error.message}`
1111
+ );
1112
+ }
1113
+ }
1114
+ try {
1115
+ const mod = await import(pathToFileURL(absolute).href);
1116
+ return mod.default ?? mod;
1117
+ } catch (error) {
1118
+ const hint = ext === ".ts" ? " TypeScript config files need a Node.js version that can import .ts files; use envclinic.config.json or .mjs instead." : "";
1119
+ throw new ConfigError(
1120
+ `Could not load config file ${shown}: ${error.message}.${hint}`
1121
+ );
1122
+ }
1123
+ }
1124
+ async function exists2(file) {
1125
+ try {
1126
+ await fs3.access(file);
1127
+ return true;
1128
+ } catch {
1129
+ return false;
1130
+ }
1131
+ }
1132
+
1133
+ // src/core/glob.ts
1134
+ var SPECIAL = /[\\^$.|+(){}[\]]/g;
1135
+ function escapeRegex(text) {
1136
+ return text.replace(SPECIAL, "\\$&");
1137
+ }
1138
+ function globToRegexSource(glob) {
1139
+ let out = "";
1140
+ for (let i = 0; i < glob.length; i++) {
1141
+ const c = glob[i];
1142
+ if (c === "*") {
1143
+ if (glob[i + 1] === "*") {
1144
+ i++;
1145
+ if (glob[i + 1] === "/") {
1146
+ i++;
1147
+ out += "(?:.*/)?";
1148
+ } else {
1149
+ out += ".*";
1150
+ }
1151
+ } else {
1152
+ out += "[^/]*";
1153
+ }
1154
+ } else if (c === "?") {
1155
+ out += "[^/]";
1156
+ } else {
1157
+ out += escapeRegex(c);
1158
+ }
1159
+ }
1160
+ return out;
1161
+ }
1162
+ function matchesGlob(glob, relativePath) {
1163
+ const normalized = glob.replace(/^\.\//, "");
1164
+ return new RegExp(`^${globToRegexSource(normalized)}$`).test(relativePath);
1165
+ }
1166
+ function createNameMatcher(patterns) {
1167
+ const exact = /* @__PURE__ */ new Set();
1168
+ const regexes = [];
1169
+ for (const pattern of patterns) {
1170
+ if (pattern.includes("*")) {
1171
+ regexes.push(new RegExp(`^${pattern.split("*").map(escapeRegex).join(".*")}$`));
1172
+ } else {
1173
+ exact.add(pattern);
1174
+ }
1175
+ }
1176
+ return (name) => exact.has(name) || regexes.some((regex) => regex.test(name));
1177
+ }
1178
+
1179
+ // src/core/parser.ts
1180
+ var LINE_RE = /^[ \t]*(export[ \t]+)?([^\s=]+)[ \t]*=/;
1181
+ var QUOTES = {
1182
+ '"': "double",
1183
+ "'": "single",
1184
+ "`": "backtick"
1185
+ };
1186
+ function parseEnv(source) {
1187
+ const text = source.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
1188
+ const entries = [];
1189
+ const problems = [];
1190
+ let i = 0;
1191
+ let line = 1;
1192
+ while (i < text.length) {
1193
+ let eol = text.indexOf("\n", i);
1194
+ if (eol === -1) eol = text.length;
1195
+ const raw = text.slice(i, eol);
1196
+ const trimmed = raw.trim();
1197
+ let next = eol + 1;
1198
+ if (trimmed !== "" && !trimmed.startsWith("#")) {
1199
+ const match = LINE_RE.exec(raw);
1200
+ if (!match) {
1201
+ problems.push({ kind: "malformed-line", line });
1202
+ } else {
1203
+ const key = match[2];
1204
+ const exported = match[1] !== void 0;
1205
+ let p = i + match[0].length;
1206
+ while (text[p] === " " || text[p] === " ") p++;
1207
+ const quoteChar = text[p];
1208
+ const style = quoteChar !== void 0 ? QUOTES[quoteChar] : void 0;
1209
+ if (style && quoteChar !== void 0) {
1210
+ const end = findClosingQuote(text, p, quoteChar);
1211
+ if (end === -1) {
1212
+ problems.push({ kind: "unterminated-quote", line });
1213
+ entries.push({
1214
+ key,
1215
+ value: text.slice(p + 1, eol),
1216
+ line,
1217
+ quote: style,
1218
+ exported
1219
+ });
1220
+ } else {
1221
+ let value = text.slice(p + 1, end);
1222
+ if (style === "double") value = unescapeDouble(value);
1223
+ entries.push({ key, value, line, quote: style, exported });
1224
+ let eol2 = text.indexOf("\n", end + 1);
1225
+ if (eol2 === -1) eol2 = text.length;
1226
+ next = eol2 + 1;
1227
+ }
1228
+ } else if (text[p] === "=") {
1229
+ problems.push({ kind: "malformed-line", line });
1230
+ } else {
1231
+ entries.push({
1232
+ key,
1233
+ value: parseUnquoted(text.slice(p, eol)),
1234
+ line,
1235
+ quote: null,
1236
+ exported
1237
+ });
1238
+ }
1239
+ }
1240
+ }
1241
+ line += countNewlines(text, i, Math.min(next, text.length));
1242
+ i = next;
1243
+ }
1244
+ return { entries, problems };
1245
+ }
1246
+ function findClosingQuote(text, start, quote) {
1247
+ for (let j = start + 1; j < text.length; j++) {
1248
+ const c = text[j];
1249
+ if (quote === '"' && c === "\\") {
1250
+ j++;
1251
+ continue;
1252
+ }
1253
+ if (c === quote) return j;
1254
+ }
1255
+ return -1;
1256
+ }
1257
+ function unescapeDouble(value) {
1258
+ return value.replace(/\\([nrt"\\])/g, (_, c) => {
1259
+ if (c === "n") return "\n";
1260
+ if (c === "r") return "\r";
1261
+ if (c === "t") return " ";
1262
+ return c;
1263
+ });
1264
+ }
1265
+ function parseUnquoted(rest) {
1266
+ if (rest.startsWith("#")) return "";
1267
+ const comment2 = /[ \t]#/.exec(rest);
1268
+ return (comment2 ? rest.slice(0, comment2.index) : rest).trim();
1269
+ }
1270
+ function countNewlines(text, from, to) {
1271
+ let count = 0;
1272
+ for (let k = from; k < to; k++) {
1273
+ if (text.charCodeAt(k) === 10) count++;
1274
+ }
1275
+ return count;
1276
+ }
1277
+
1278
+ // src/core/scanner.ts
1279
+ import { promises as fs4 } from "fs";
1280
+ import path4 from "path";
1281
+ import fg from "fast-glob";
1282
+ var DEFAULT_EXTENSIONS = [
1283
+ "js",
1284
+ "jsx",
1285
+ "mjs",
1286
+ "cjs",
1287
+ "ts",
1288
+ "tsx",
1289
+ "mts",
1290
+ "cts",
1291
+ "vue",
1292
+ "svelte",
1293
+ "astro"
1294
+ ];
1295
+ var DEFAULT_SCAN_IGNORE = [
1296
+ "node_modules",
1297
+ ".git",
1298
+ "dist",
1299
+ "build",
1300
+ "out",
1301
+ "coverage",
1302
+ ".next",
1303
+ ".nuxt",
1304
+ ".svelte-kit",
1305
+ ".output",
1306
+ ".turbo",
1307
+ ".cache",
1308
+ ".vercel",
1309
+ ".netlify",
1310
+ ".parcel-cache",
1311
+ ".yarn",
1312
+ ".pnpm-store"
1313
+ ];
1314
+ var MAX_SOURCE_FILE_BYTES = 1024 * 1024;
1315
+ function ignoreToGlob(entry) {
1316
+ const cleaned = entry.replace(/^\.\//, "").replace(/\/+$/, "");
1317
+ if (/[*?]/.test(cleaned)) return cleaned;
1318
+ if (cleaned.includes("/")) return `${cleaned}/**`;
1319
+ return `**/${cleaned}/**`;
1320
+ }
1321
+ async function discoverSourceFiles(cwd, options) {
1322
+ const realRoot = await fs4.realpath(cwd);
1323
+ const extensions = options.extensions.length === 1 ? options.extensions[0] : `{${options.extensions.join(",")}}`;
1324
+ const ignore = [
1325
+ ...DEFAULT_SCAN_IGNORE.map(ignoreToGlob),
1326
+ ...options.ignore.map(ignoreToGlob),
1327
+ "**/*.d.ts",
1328
+ "**/*.min.js",
1329
+ "**/envclinic.config.*"
1330
+ ];
1331
+ const found = /* @__PURE__ */ new Set();
1332
+ for (const directory of options.directories) {
1333
+ const absolute = path4.resolve(cwd, directory);
1334
+ if (!isInside(cwd, absolute)) {
1335
+ throw new ConfigError(
1336
+ `scan.directories entry "${directory}" is outside the project directory.`
1337
+ );
1338
+ }
1339
+ let real;
1340
+ try {
1341
+ real = await fs4.realpath(absolute);
1342
+ } catch {
1343
+ continue;
1344
+ }
1345
+ if (!isInside(realRoot, real)) continue;
1346
+ const relative = displayPath(cwd, absolute);
1347
+ const base = relative === "." ? "" : `${fg.escapePath(relative)}/`;
1348
+ const entries = await fg(`${base}**/*.${extensions}`, {
1349
+ cwd,
1350
+ ignore,
1351
+ onlyFiles: true,
1352
+ followSymbolicLinks: false,
1353
+ dot: false,
1354
+ unique: true
1355
+ });
1356
+ for (const entry of entries) found.add(entry);
1357
+ }
1358
+ return [...found].sort();
1359
+ }
1360
+ async function scanSources(cwd, options, visit) {
1361
+ const files = await discoverSourceFiles(cwd, options);
1362
+ let filesScanned = 0;
1363
+ let skipped = 0;
1364
+ const BATCH = 64;
1365
+ for (let i = 0; i < files.length; i += BATCH) {
1366
+ const batch = files.slice(i, i + BATCH);
1367
+ const loaded = await Promise.all(
1368
+ batch.map(async (relative) => {
1369
+ const absolute = path4.join(cwd, relative);
1370
+ try {
1371
+ const stat = await fs4.lstat(absolute);
1372
+ if (!stat.isFile() || stat.size > MAX_SOURCE_FILE_BYTES)
1373
+ return void 0;
1374
+ return {
1375
+ path: relative,
1376
+ content: await fs4.readFile(absolute, "utf8")
1377
+ };
1378
+ } catch {
1379
+ return void 0;
1380
+ }
1381
+ })
1382
+ );
1383
+ for (const file of loaded) {
1384
+ if (file === void 0) {
1385
+ skipped++;
1386
+ } else {
1387
+ filesScanned++;
1388
+ visit(file);
1389
+ }
1390
+ }
1391
+ }
1392
+ return { filesScanned, skipped };
1393
+ }
1394
+ var ENV_OBJECT = /(?<![\w$])(?<![\w$)\]]\s*\.)(?:process\.env|import\.meta\.env|Bun\.env)(?![\w$])/g;
1395
+ var MEMBER = /^\s*\??\.\s*([A-Za-z_$][\w$]*)/;
1396
+ var BRACKET_LITERAL = /^\s*\??\.?\s*\[\s*(["'`])([A-Za-z_][\w]*)\1\s*\]/;
1397
+ var BRACKET_ANY = /^\s*\??\.?\s*\[/;
1398
+ var CAST_MEMBER = /^\s+as\s+[^)]*\)\s*\??\.\s*([A-Za-z_$][\w$]*)/;
1399
+ var DENO_GET = /\bDeno\.env\.get\(\s*(["'`])([A-Za-z_]\w*)\1\s*\)/g;
1400
+ var DESTRUCTURE = /\{([^{}]*)\}\s*=\s*$/;
1401
+ function extractReferences(content) {
1402
+ const result = { names: [], dynamic: [] };
1403
+ if (!/process\.env|import\.meta\.env|Bun\.env|Deno\.env/.test(content))
1404
+ return result;
1405
+ let lineStarts;
1406
+ const lineAt = (index) => {
1407
+ if (lineStarts === void 0) {
1408
+ lineStarts = [0];
1409
+ for (let i = 0; i < content.length; i++) {
1410
+ if (content.charCodeAt(i) === 10) lineStarts.push(i + 1);
1411
+ }
1412
+ }
1413
+ let low = 0;
1414
+ let high = lineStarts.length - 1;
1415
+ while (low < high) {
1416
+ const mid = low + high + 1 >> 1;
1417
+ if (lineStarts[mid] <= index) low = mid;
1418
+ else high = mid - 1;
1419
+ }
1420
+ return low + 1;
1421
+ };
1422
+ for (const match of content.matchAll(ENV_OBJECT)) {
1423
+ const start = match.index;
1424
+ const end = start + match[0].length;
1425
+ const rest = content.slice(end, end + 200);
1426
+ const line = lineAt(start);
1427
+ const member = MEMBER.exec(rest);
1428
+ if (member) {
1429
+ result.names.push({ name: member[1], line });
1430
+ continue;
1431
+ }
1432
+ const literal = BRACKET_LITERAL.exec(rest);
1433
+ if (literal) {
1434
+ result.names.push({ name: literal[2], line });
1435
+ continue;
1436
+ }
1437
+ if (BRACKET_ANY.test(rest)) {
1438
+ result.dynamic.push({ line });
1439
+ continue;
1440
+ }
1441
+ const cast = CAST_MEMBER.exec(rest);
1442
+ if (cast) {
1443
+ result.names.push({ name: cast[1], line });
1444
+ continue;
1445
+ }
1446
+ const before = content.slice(Math.max(0, start - 1e3), start);
1447
+ const destructure = DESTRUCTURE.exec(before);
1448
+ if (destructure) {
1449
+ let dynamic = false;
1450
+ for (const part of destructure[1].split(",")) {
1451
+ const piece = part.trim();
1452
+ if (piece === "") continue;
1453
+ if (piece.startsWith("...")) {
1454
+ dynamic = true;
1455
+ continue;
1456
+ }
1457
+ const name = /^([A-Za-z_$][\w$]*)/.exec(piece);
1458
+ if (name) result.names.push({ name: name[1], line });
1459
+ }
1460
+ if (dynamic) result.dynamic.push({ line });
1461
+ continue;
1462
+ }
1463
+ result.dynamic.push({ line });
1464
+ }
1465
+ for (const match of content.matchAll(DENO_GET)) {
1466
+ result.names.push({
1467
+ name: match[2],
1468
+ line: lineAt(match.index)
1469
+ });
1470
+ }
1471
+ return result;
1472
+ }
1473
+
1474
+ // src/core/project.ts
1475
+ var ALL_CHECKS = [
1476
+ "files",
1477
+ "unused",
1478
+ "secrets",
1479
+ "validation",
1480
+ "types"
1481
+ ];
1482
+ async function load(cwd, relative) {
1483
+ const absolute = path5.resolve(cwd, relative);
1484
+ return {
1485
+ shown: displayPath(cwd, absolute),
1486
+ absolute,
1487
+ result: await readEnvFile(cwd, relative)
1488
+ };
1489
+ }
1490
+ function reportUnreadable(file, issues) {
1491
+ const { result, shown } = file;
1492
+ switch (result.status) {
1493
+ case "ok":
1494
+ if (result.encoding !== "utf-8") {
1495
+ issues.push({
1496
+ code: "non-utf8-file",
1497
+ rule: "syntax",
1498
+ severity: "warning",
1499
+ file: shown,
1500
+ message: `${shown} is saved as ${result.encoding.toUpperCase()}, not UTF-8`,
1501
+ recommendation: "It was read correctly, but most dotenv loaders expect UTF-8. Re-save it as UTF-8 (in PowerShell: `Set-Content -Encoding utf8 .env`, or use `Out-File -Encoding utf8` instead of `>`)."
1502
+ });
1503
+ }
1504
+ return true;
1505
+ case "unsafe":
1506
+ issues.push({
1507
+ code: "unsafe-path",
1508
+ severity: "error",
1509
+ file: shown,
1510
+ message: `${shown} was skipped: ${result.reason}`,
1511
+ recommendation: "Only files inside the project directory can be audited."
1512
+ });
1513
+ return false;
1514
+ case "too-large":
1515
+ issues.push({
1516
+ code: "file-too-large",
1517
+ severity: "error",
1518
+ file: shown,
1519
+ message: `${shown} was skipped because it is larger than 5 MB`,
1520
+ recommendation: "Environment files should be small. Check that this is really an env file."
1521
+ });
1522
+ return false;
1523
+ case "unreadable":
1524
+ issues.push({
1525
+ code: "file-unreadable",
1526
+ severity: "error",
1527
+ file: shown,
1528
+ message: `${shown} could not be read`,
1529
+ recommendation: "Check the file permissions."
1530
+ });
1531
+ return false;
1532
+ case "missing":
1533
+ return false;
1534
+ }
1535
+ }
1536
+ function toFileData(shown, absolute, role, content) {
1537
+ const parsed = parseEnv(content);
1538
+ const entries = parsed.entries.filter((entry) => isValidName(entry.key));
1539
+ return {
1540
+ path: shown,
1541
+ absolute,
1542
+ role,
1543
+ parsed,
1544
+ entries,
1545
+ keys: new Set(entries.map((entry) => entry.key))
1546
+ };
1547
+ }
1548
+ async function loadProject(options = {}) {
1549
+ const cwd = path5.resolve(options.cwd ?? process.cwd());
1550
+ let config;
1551
+ let configFile;
1552
+ if (options.config !== void 0) {
1553
+ config = validateConfig(options.config, "the config option");
1554
+ } else {
1555
+ const loaded = await loadConfig(cwd, options.configPath);
1556
+ config = loaded.config;
1557
+ configFile = loaded.file;
1558
+ }
1559
+ const rules = { ...DEFAULT_RULES, ...config.rules };
1560
+ const isIgnored = createNameMatcher([
1561
+ ...config.ignore?.variables ?? [],
1562
+ ...options.ignore ?? []
1563
+ ]);
1564
+ const sourceExplicit = options.files !== void 0;
1565
+ const sourcePaths = options.files ?? config.files?.source ?? DEFAULT_SOURCE_FILES;
1566
+ const exampleExplicit = options.example !== void 0;
1567
+ const exampleCandidates = options.example !== void 0 ? [options.example] : config.files?.example !== void 0 ? [config.files.example] : EXAMPLE_FILE_CANDIDATES;
1568
+ const loadIssues = [];
1569
+ const sourceFiles = [];
1570
+ let example;
1571
+ let exampleLoaded;
1572
+ for (const candidate of exampleCandidates) {
1573
+ const file = await load(cwd, candidate);
1574
+ if (file.result.status !== "missing") {
1575
+ exampleLoaded = file;
1576
+ break;
1577
+ }
1578
+ }
1579
+ if (exampleLoaded) {
1580
+ if (reportUnreadable(exampleLoaded, loadIssues) && exampleLoaded.result.status === "ok") {
1581
+ example = toFileData(
1582
+ exampleLoaded.shown,
1583
+ exampleLoaded.absolute,
1584
+ "example",
1585
+ exampleLoaded.result.content
1586
+ );
1587
+ }
1588
+ } else {
1589
+ const named = exampleExplicit || config.files?.example !== void 0;
1590
+ loadIssues.push({
1591
+ code: "example-file-missing",
1592
+ severity: exampleExplicit ? "error" : "warning",
1593
+ message: named ? `Example file ${displayPath(cwd, path5.resolve(cwd, exampleCandidates[0]))} was not found` : "No .env.example or .env.sample file was found",
1594
+ recommendation: "Create one that lists every variable your project needs (names only, never real values) so new developers know what to configure. `envclinic generate` can create it."
1595
+ });
1596
+ }
1597
+ const seen = new Set(example ? [example.absolute] : []);
1598
+ for (const relative of sourcePaths) {
1599
+ const absolute = path5.resolve(cwd, relative);
1600
+ if (seen.has(absolute)) continue;
1601
+ seen.add(absolute);
1602
+ const file = await load(cwd, relative);
1603
+ if (file.result.status === "missing") {
1604
+ loadIssues.push({
1605
+ code: "source-file-missing",
1606
+ severity: sourceExplicit ? "error" : "info",
1607
+ file: file.shown,
1608
+ message: sourceExplicit ? `${file.shown} was not found` : `${file.shown} was not found, so no values were compared`,
1609
+ recommendation: `Create ${file.shown} (for example by copying ${example?.path ?? ".env.example"}), or pass --file to audit a different file.`
1610
+ });
1611
+ continue;
1612
+ }
1613
+ if (!reportUnreadable(file, loadIssues) || file.result.status !== "ok")
1614
+ continue;
1615
+ sourceFiles.push(
1616
+ toFileData(file.shown, file.absolute, "source", file.result.content)
1617
+ );
1618
+ }
1619
+ if (sourceFiles.length === 0 && example === void 0 && !loadIssues.some((issue) => issue.severity === "error")) {
1620
+ loadIssues.push({
1621
+ code: "no-env-files",
1622
+ severity: "error",
1623
+ message: "No environment files were found to audit",
1624
+ recommendation: "Create a .env file and a .env.example that documents it, or point to a file with --file."
1625
+ });
1626
+ }
1627
+ const framework = await detectFramework(cwd, config);
1628
+ const scanOptions = {
1629
+ directories: options.scanDirectories ?? config.scan?.directories ?? ["."],
1630
+ ignore: config.scan?.ignore ?? [],
1631
+ extensions: config.scan?.extensions ?? DEFAULT_EXTENSIONS
1632
+ };
1633
+ const env = {
1634
+ ...options.processEnv ? process.env : {},
1635
+ ...options.env ?? {}
1636
+ };
1637
+ const project = {
1638
+ cwd,
1639
+ config,
1640
+ rules,
1641
+ strict: options.strict ?? false,
1642
+ checks: new Set(options.checks ?? ALL_CHECKS),
1643
+ isIgnored,
1644
+ framework,
1645
+ sourceFiles,
1646
+ loadIssues,
1647
+ scanOptions,
1648
+ env
1649
+ };
1650
+ if (configFile !== void 0) project.configFile = configFile;
1651
+ if (example !== void 0) project.example = example;
1652
+ if (config.schema !== void 0) project.schema = config.schema;
1653
+ return project;
1654
+ }
1655
+ function allFiles(project) {
1656
+ return project.example ? [...project.sourceFiles, project.example] : [...project.sourceFiles];
1657
+ }
1658
+ function mergedEnvironment(project) {
1659
+ const values = {};
1660
+ const origin = /* @__PURE__ */ new Map();
1661
+ for (const file of project.sourceFiles) {
1662
+ for (const entry of file.entries) {
1663
+ values[entry.key] = entry.value;
1664
+ origin.set(entry.key, { file: file.path, line: entry.line });
1665
+ }
1666
+ }
1667
+ for (const [name, value] of Object.entries(project.env)) {
1668
+ if (value !== void 0) {
1669
+ values[name] = value;
1670
+ origin.delete(name);
1671
+ }
1672
+ }
1673
+ return { values, origin };
1674
+ }
1675
+
1676
+ // src/core/validator.ts
1677
+ var TRUE_VALUES = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
1678
+ var FALSE_VALUES = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
1679
+ var EMAIL = /^[^\s@]+@[^\s@.]+(?:\.[^\s@.]+)+$/;
1680
+ function isRequired(field) {
1681
+ return field.required ?? field.default === void 0;
1682
+ }
1683
+ function parseOne(name, field, raw) {
1684
+ const fail = (code, message) => ({ error: { variable: name, code, message } });
1685
+ switch (field.type) {
1686
+ case "string": {
1687
+ if (field.minLength !== void 0 && raw.length < field.minLength) {
1688
+ return fail("too-short", `${name} must be at least ${field.minLength} characters long`);
1689
+ }
1690
+ if (field.maxLength !== void 0 && raw.length > field.maxLength) {
1691
+ return fail("too-long", `${name} must be at most ${field.maxLength} characters long`);
1692
+ }
1693
+ if (field.pattern !== void 0 && !new RegExp(field.pattern).test(raw)) {
1694
+ return fail("pattern-mismatch", `${name} does not match the required pattern`);
1695
+ }
1696
+ return { value: raw };
1697
+ }
1698
+ case "number":
1699
+ case "integer": {
1700
+ const text = raw.trim();
1701
+ const integer = field.type === "integer";
1702
+ const valid = integer ? /^[+-]?\d+$/.test(text) : text !== "" && Number.isFinite(Number(text));
1703
+ const number = Number(text);
1704
+ if (!valid || integer && !Number.isSafeInteger(number)) {
1705
+ return fail("invalid-type", `${name} must be ${integer ? "an integer" : "a number"}`);
1706
+ }
1707
+ if (field.min !== void 0 && number < field.min) {
1708
+ return fail("out-of-range", `${name} must be at least ${field.min}`);
1709
+ }
1710
+ if (field.max !== void 0 && number > field.max) {
1711
+ return fail("out-of-range", `${name} must be at most ${field.max}`);
1712
+ }
1713
+ return { value: number };
1714
+ }
1715
+ case "boolean": {
1716
+ const lowered = raw.trim().toLowerCase();
1717
+ if (TRUE_VALUES.has(lowered)) return { value: true };
1718
+ if (FALSE_VALUES.has(lowered)) return { value: false };
1719
+ return fail("invalid-type", `${name} must be a boolean (true, false, 1, 0, yes, no, on or off)`);
1720
+ }
1721
+ case "url": {
1722
+ let url;
1723
+ try {
1724
+ url = new URL(raw);
1725
+ } catch {
1726
+ return fail("invalid-type", `${name} must be a valid URL`);
1727
+ }
1728
+ if (field.protocols !== void 0) {
1729
+ const protocol = url.protocol.replace(/:$/, "").toLowerCase();
1730
+ if (!field.protocols.map((p) => p.toLowerCase()).includes(protocol)) {
1731
+ return fail("invalid-protocol", `${name} must use one of these protocols: ${field.protocols.join(", ")}`);
1732
+ }
1733
+ }
1734
+ return { value: raw };
1735
+ }
1736
+ case "email":
1737
+ return EMAIL.test(raw) ? { value: raw } : fail("invalid-type", `${name} must be a valid email address`);
1738
+ case "enum": {
1739
+ const values = field.values ?? [];
1740
+ return values.includes(raw) ? { value: raw } : fail("invalid-enum", `${name} must be one of: ${values.join(", ")}`);
1741
+ }
1742
+ case "custom": {
1743
+ let outcome;
1744
+ try {
1745
+ outcome = field.validate?.(raw);
1746
+ } catch {
1747
+ return fail("custom-failed", `${name} failed custom validation`);
1748
+ }
1749
+ if (outcome === void 0 || outcome === true) return { value: raw };
1750
+ return fail("custom-failed", typeof outcome === "string" && outcome !== "" ? outcome : `${name} failed custom validation`);
1751
+ }
1752
+ }
1753
+ }
1754
+ function validateEnv(schema, env = process.env) {
1755
+ const values = {};
1756
+ const errors = [];
1757
+ for (const [name, field] of Object.entries(schema)) {
1758
+ const raw = env[name];
1759
+ if (raw === void 0 || raw === "") {
1760
+ if (field.default !== void 0) {
1761
+ values[name] = field.default;
1762
+ } else if (isRequired(field)) {
1763
+ errors.push({ variable: name, code: "missing-required", message: `${name} is required but not set` });
1764
+ }
1765
+ continue;
1766
+ }
1767
+ const parsed = parseOne(name, field, raw);
1768
+ if ("error" in parsed) errors.push(parsed.error);
1769
+ else values[name] = parsed.value;
1770
+ }
1771
+ return { success: errors.length === 0, values, errors };
1772
+ }
1773
+
1774
+ // src/analyzers/validation.ts
1775
+ function findSchemaIssues(project, skip) {
1776
+ const schema = project.schema;
1777
+ if (schema === void 0) return [];
1778
+ const { values, origin } = mergedEnvironment(project);
1779
+ const hasInput = project.sourceFiles.length > 0 || Object.keys(project.env).length > 0;
1780
+ if (!hasInput) {
1781
+ return [
1782
+ {
1783
+ code: "validation-skipped",
1784
+ severity: "info",
1785
+ message: "Schema validation was skipped because no environment files were found",
1786
+ recommendation: "Create the env file, pass --file, or use --process-env to validate the process environment."
1787
+ }
1788
+ ];
1789
+ }
1790
+ const issues = [];
1791
+ for (const error of validateEnv(schema, values).errors) {
1792
+ if (project.isIgnored(error.variable)) continue;
1793
+ if (error.code === "missing-required" && skip.has(error.variable)) continue;
1794
+ const where = origin.get(error.variable);
1795
+ const issue = {
1796
+ code: `schema-${error.code}`,
1797
+ rule: "validation",
1798
+ variable: error.variable,
1799
+ message: error.message,
1800
+ recommendation: error.code === "missing-required" ? `Set ${error.variable} in your environment, or mark it as required: false (or give it a default) in the schema.` : `Fix the value of ${error.variable} or update the schema if the rule is wrong.`
1801
+ };
1802
+ if (where) {
1803
+ issue.file = where.file;
1804
+ issue.line = where.line;
1805
+ }
1806
+ issues.push(issue);
1807
+ }
1808
+ return issues;
1809
+ }
1810
+
1811
+ // src/core/gitignore.ts
1812
+ import { promises as fs5 } from "fs";
1813
+ import path6 from "path";
1814
+ function parseGitignore(text) {
1815
+ const rules = [];
1816
+ for (const rawLine of text.replace(/\r\n?/g, "\n").split("\n")) {
1817
+ let line = rawLine.replace(/(?<!\\)\s+$/, "");
1818
+ if (line === "" || line.startsWith("#")) continue;
1819
+ let negated = false;
1820
+ if (line.startsWith("!")) {
1821
+ negated = true;
1822
+ line = line.slice(1);
1823
+ } else if (line.startsWith("\\#") || line.startsWith("\\!")) {
1824
+ line = line.slice(1);
1825
+ }
1826
+ let dirOnly = false;
1827
+ if (line.endsWith("/")) {
1828
+ dirOnly = true;
1829
+ line = line.slice(0, -1);
1830
+ }
1831
+ if (line === "") continue;
1832
+ const anchored = line.includes("/");
1833
+ if (line.startsWith("/")) line = line.slice(1);
1834
+ const body = globToRegexSource(line);
1835
+ const tail = dirOnly ? "/.*" : "(?:/.*)?";
1836
+ const head = anchored ? "^" : "^(?:.*/)?";
1837
+ rules.push({ negated, dirOnly, regex: new RegExp(`${head}${body}${tail}$`) });
1838
+ }
1839
+ return rules;
1840
+ }
1841
+ function evaluate(rules, relativePath) {
1842
+ let result;
1843
+ for (const rule of rules) {
1844
+ if (rule.regex.test(relativePath)) result = !rule.negated;
1845
+ }
1846
+ return result;
1847
+ }
1848
+ async function findGitRoot(start) {
1849
+ let dir = start;
1850
+ for (; ; ) {
1851
+ try {
1852
+ await fs5.stat(path6.join(dir, ".git"));
1853
+ return dir;
1854
+ } catch {
1855
+ }
1856
+ const parent = path6.dirname(dir);
1857
+ if (parent === dir) return void 0;
1858
+ dir = parent;
1859
+ }
1860
+ }
1861
+ async function readIfExists(file) {
1862
+ try {
1863
+ return await fs5.readFile(file, "utf8");
1864
+ } catch {
1865
+ return void 0;
1866
+ }
1867
+ }
1868
+ function createGitChecker(cwd) {
1869
+ let rootPromise;
1870
+ const cache = /* @__PURE__ */ new Map();
1871
+ const rulesFor = (file) => {
1872
+ let cached = cache.get(file);
1873
+ if (!cached) {
1874
+ cached = readIfExists(file).then((text) => text === void 0 ? [] : parseGitignore(text));
1875
+ cache.set(file, cached);
1876
+ }
1877
+ return cached;
1878
+ };
1879
+ return {
1880
+ async status(absoluteFile) {
1881
+ rootPromise ??= findGitRoot(cwd);
1882
+ const root = await rootPromise;
1883
+ if (root === void 0) return "no-repo";
1884
+ const rel = path6.relative(root, absoluteFile).split(path6.sep).join("/");
1885
+ if (rel.startsWith("..")) return "no-repo";
1886
+ let ignored;
1887
+ const exclude = evaluate(await rulesFor(path6.join(root, ".git", "info", "exclude")), rel);
1888
+ if (exclude !== void 0) ignored = exclude;
1889
+ const parts = rel.split("/");
1890
+ let dir = root;
1891
+ for (let i = 0; i < parts.length; i++) {
1892
+ const sub = parts.slice(i).join("/");
1893
+ const result = evaluate(await rulesFor(path6.join(dir, ".gitignore")), sub);
1894
+ if (result !== void 0) ignored = result;
1895
+ if (i < parts.length - 1) dir = path6.join(dir, parts[i]);
1896
+ }
1897
+ return ignored ? "ignored" : "not-ignored";
1898
+ }
1899
+ };
1900
+ }
1901
+
1902
+ // src/core/generator.ts
1903
+ var CATEGORIES = [
1904
+ "Database configuration",
1905
+ "Authentication",
1906
+ "External services",
1907
+ "Application",
1908
+ "Client-exposed variables",
1909
+ "Other"
1910
+ ];
1911
+ var DATABASE = /(DATABASE|(^|_)DB(_|$)|POSTGRES|MYSQL|MONGO|REDIS|SQLITE|PRISMA|PGHOST|PGUSER|PGPASSWORD|PGDATABASE|PGPORT)/i;
1912
+ var AUTH = /(JWT|AUTH|SESSION|OAUTH|COOKIE|CSRF|SALT|BCRYPT|(^|_)SECRET$)/i;
1913
+ var EXTERNAL = /(STRIPE|AWS|(^|_)S3(_|$)|SENDGRID|TWILIO|SMTP|MAIL|SENTRY|OPENAI|ANTHROPIC|GITHUB|GOOGLE|FIREBASE|CLOUDINARY|SLACK|DISCORD|PAYPAL|MAPBOX|ALGOLIA|DATADOG|VERCEL|NETLIFY|AZURE|GCP|(^|_)R2(_|$)|SUPABASE)/i;
1914
+ var APPLICATION = /(^PORT$|HOST|NODE_ENV|^APP_|(^|_)URL$|ORIGIN|CORS|LOG|DEBUG|(^|_)ENV$)/i;
1915
+ function categorize(name, publicPrefixes) {
1916
+ if (publicPrefixes.some((prefix) => name.startsWith(prefix)))
1917
+ return "Client-exposed variables";
1918
+ if (DATABASE.test(name)) return "Database configuration";
1919
+ if (AUTH.test(name)) return "Authentication";
1920
+ if (EXTERNAL.test(name)) return "External services";
1921
+ if (APPLICATION.test(name)) return "Application";
1922
+ return "Other";
1923
+ }
1924
+ function describe(info) {
1925
+ const field = info.schema;
1926
+ if (field === void 0) return [];
1927
+ const lines = [];
1928
+ if (field.description) lines.push(`# ${field.description}`);
1929
+ const facts = [
1930
+ field.type === "enum" && field.values ? `one of: ${field.values.join(", ")}` : field.type
1931
+ ];
1932
+ facts.push(
1933
+ field.default !== void 0 || field.required === false ? "optional" : "required"
1934
+ );
1935
+ if (field.default !== void 0 && !field.secret)
1936
+ facts.push(`default: ${String(field.default)}`);
1937
+ lines.push(`# ${facts.join(", ")}`);
1938
+ return lines;
1939
+ }
1940
+ function renderVariable(info) {
1941
+ return [...describe(info), `${info.name}=`];
1942
+ }
1943
+ function renderExample(variables, publicPrefixes) {
1944
+ if (variables.length === 0) return "";
1945
+ const groups = /* @__PURE__ */ new Map();
1946
+ for (const info of variables) {
1947
+ const category = categorize(info.name, publicPrefixes);
1948
+ const list = groups.get(category);
1949
+ if (list) list.push(info);
1950
+ else groups.set(category, [info]);
1951
+ }
1952
+ const blocks = [];
1953
+ for (const category of CATEGORIES) {
1954
+ const list = groups.get(category);
1955
+ if (!list) continue;
1956
+ blocks.push([`# ${category}`, ...list.flatMap(renderVariable)].join("\n"));
1957
+ }
1958
+ return blocks.join("\n\n") + "\n";
1959
+ }
1960
+ function renderMerge(existing, variables) {
1961
+ const present = new Set(parseEnv(existing).entries.map((entry) => entry.key));
1962
+ const missing = variables.filter((info) => !present.has(info.name));
1963
+ if (missing.length === 0) return { content: existing, added: [] };
1964
+ const base = existing.replace(/\s+$/, "");
1965
+ const addition = [
1966
+ "# Added by envclinic",
1967
+ ...missing.flatMap(renderVariable)
1968
+ ].join("\n");
1969
+ return {
1970
+ content: `${base}${base === "" ? "" : "\n\n"}${addition}
1971
+ `,
1972
+ added: missing.map((info) => info.name)
1973
+ };
1974
+ }
1975
+
1976
+ // src/core/type-generator.ts
1977
+ var GENERATED_MARKER = "// Generated by envclinic";
1978
+ var RESERVED = /* @__PURE__ */ new Set(["NODE_ENV", "TZ"]);
1979
+ function isRequiredVariable(info, hasSource, hasExample) {
1980
+ if (info.schema) return isRequired(info.schema);
1981
+ if (hasSource && hasExample) return info.inSource && info.inExample;
1982
+ if (hasSource) return info.inSource;
1983
+ if (hasExample) return info.inExample;
1984
+ return false;
1985
+ }
1986
+ function tsType(info) {
1987
+ const field = info.schema;
1988
+ if (field?.type === "enum" && field.values && field.values.length > 0) {
1989
+ return field.values.map((value) => JSON.stringify(value)).join(" | ");
1990
+ }
1991
+ return "string";
1992
+ }
1993
+ function comment(info, indent) {
1994
+ const field = info.schema;
1995
+ if (field === void 0) return [];
1996
+ const parts = [];
1997
+ if (field.description) parts.push(field.description.replace(/\*\//g, "*\\/"));
1998
+ if (field.type === "number" || field.type === "integer" || field.type === "boolean") {
1999
+ parts.push(`Parse as ${field.type} (the value is a string at runtime).`);
2000
+ }
2001
+ return parts.length === 0 ? [] : [`${indent}/** ${parts.join(" ")} */`];
2002
+ }
2003
+ function renderTypes(input) {
2004
+ const { framework } = input;
2005
+ const useImportMeta = framework.id === "vite" || framework.id === "astro";
2006
+ const processEnv = [];
2007
+ const importMetaEnv = [];
2008
+ for (const info of input.variables) {
2009
+ if (RESERVED.has(info.name) && !info.schema) continue;
2010
+ const required = isRequiredVariable(
2011
+ info,
2012
+ input.hasSourceFiles,
2013
+ input.hasExample
2014
+ );
2015
+ const isPublic = framework.publicPrefixes.some(
2016
+ (prefix) => info.name.startsWith(prefix)
2017
+ );
2018
+ if (useImportMeta && isPublic) {
2019
+ importMetaEnv.push(
2020
+ ...comment(info, " "),
2021
+ ` readonly ${info.name}${required ? "" : "?"}: ${tsType(info)};`
2022
+ );
2023
+ } else {
2024
+ processEnv.push(
2025
+ ...comment(info, " "),
2026
+ ` ${info.name}${required ? "" : "?"}: ${tsType(info)};`
2027
+ );
2028
+ }
2029
+ }
2030
+ const out = [
2031
+ `${GENERATED_MARKER}. Do not edit by hand; run \`npx envclinic types\` to regenerate.`,
2032
+ "// These declarations improve editor autocomplete only. They do not validate values at runtime."
2033
+ ];
2034
+ if (processEnv.length > 0) {
2035
+ out.push(
2036
+ "",
2037
+ "declare namespace NodeJS {",
2038
+ " interface ProcessEnv {",
2039
+ ...processEnv,
2040
+ " }",
2041
+ "}"
2042
+ );
2043
+ }
2044
+ if (importMetaEnv.length > 0) {
2045
+ out.push(
2046
+ "",
2047
+ "interface ImportMetaEnv {",
2048
+ ...importMetaEnv,
2049
+ "}",
2050
+ "",
2051
+ "interface ImportMeta {",
2052
+ " readonly env: ImportMetaEnv;",
2053
+ "}"
2054
+ );
2055
+ }
2056
+ if (processEnv.length === 0 && importMetaEnv.length === 0) {
2057
+ out.push("", "export {};");
2058
+ }
2059
+ return out.join("\n") + "\n";
2060
+ }
2061
+
2062
+ // src/core/variables.ts
2063
+ function collectVariables(project, usage, exclude = () => false) {
2064
+ const map = /* @__PURE__ */ new Map();
2065
+ const get = (name) => {
2066
+ let info = map.get(name);
2067
+ if (!info) {
2068
+ info = { name, inSource: false, inExample: false, usedInCode: false };
2069
+ map.set(name, info);
2070
+ }
2071
+ return info;
2072
+ };
2073
+ for (const file of project.sourceFiles) for (const key of file.keys) get(key).inSource = true;
2074
+ if (project.example) for (const key of project.example.keys) get(key).inExample = true;
2075
+ for (const [name, field] of Object.entries(project.schema ?? {})) get(name).schema = field;
2076
+ if (usage) {
2077
+ for (const name of usage.references.keys()) {
2078
+ const existing = map.get(name);
2079
+ if (!existing && isBuiltinVariable(name)) continue;
2080
+ get(name).usedInCode = true;
2081
+ }
2082
+ }
2083
+ return [...map.values()].filter((info) => !project.isIgnored(info.name) && !exclude(info.name)).sort((a, b) => a.name.localeCompare(b.name));
2084
+ }
2085
+
2086
+ // src/core/outputs.ts
2087
+ function typesOutputPath(project, override) {
2088
+ return override ?? project.config.types?.output ?? DEFAULT_TYPES_OUTPUT;
2089
+ }
2090
+ function exampleOutputPath(project, override) {
2091
+ return override ?? project.config.generate?.output ?? DEFAULT_EXAMPLE_OUTPUT;
2092
+ }
2093
+ function exampleVariables(project, usage, exclude = []) {
2094
+ const matcher = createNameMatcher([...project.config.generate?.exclude ?? [], ...exclude]);
2095
+ return collectVariables(project, usage, matcher);
2096
+ }
2097
+ function buildTypesContent(project, usage) {
2098
+ return renderTypes({
2099
+ variables: collectVariables(project, usage),
2100
+ framework: project.framework,
2101
+ hasSourceFiles: project.sourceFiles.length > 0,
2102
+ hasExample: project.example !== void 0
2103
+ });
2104
+ }
2105
+
2106
+ // src/core/auditor.ts
2107
+ var SEVERITY_RANK = {
2108
+ error: 0,
2109
+ warning: 1,
2110
+ info: 2
2111
+ };
2112
+ var FILE_PRESENCE_CODES = /* @__PURE__ */ new Set([
2113
+ "source-file-missing",
2114
+ "example-file-missing",
2115
+ "no-env-files",
2116
+ "non-utf8-file"
2117
+ ]);
2118
+ async function scanProject(project, options) {
2119
+ const patterns = buildPatterns(project.config.secrets?.patterns);
2120
+ const ignoreFiles = project.config.secrets?.ignoreFiles ?? [];
2121
+ const references = /* @__PURE__ */ new Map();
2122
+ const dynamic = [];
2123
+ const secrets = [];
2124
+ const summary = await scanSources(
2125
+ project.cwd,
2126
+ project.scanOptions,
2127
+ (file) => {
2128
+ const extracted = extractReferences(file.content);
2129
+ for (const { name, line } of extracted.names) {
2130
+ const list = references.get(name);
2131
+ const location = { file: file.path, line };
2132
+ if (list) list.push(location);
2133
+ else references.set(name, [location]);
2134
+ }
2135
+ for (const { line } of extracted.dynamic)
2136
+ dynamic.push({ file: file.path, line });
2137
+ if (options.secrets && !ignoreFiles.some((glob) => matchesGlob(glob, file.path))) {
2138
+ secrets.push(...analyzeCodeSecrets(file.path, file.content, patterns));
2139
+ }
2140
+ }
2141
+ );
2142
+ return {
2143
+ usage: { filesScanned: summary.filesScanned, references, dynamic },
2144
+ secrets
2145
+ };
2146
+ }
2147
+ function normalize(text) {
2148
+ return text.replace(/\r\n/g, "\n");
2149
+ }
2150
+ async function checkTypesFile(project, usage) {
2151
+ const output = typesOutputPath(project);
2152
+ const expected = buildTypesContent(project, usage);
2153
+ const current = await readEnvFile(project.cwd, output);
2154
+ if (current.status === "missing") {
2155
+ return [
2156
+ {
2157
+ code: "types-missing",
2158
+ rule: "types",
2159
+ severity: "warning",
2160
+ file: output,
2161
+ message: `types.enabled is set but ${output} does not exist`,
2162
+ recommendation: "Run `npx envclinic types` to generate it."
2163
+ }
2164
+ ];
2165
+ }
2166
+ if (current.status !== "ok") {
2167
+ return [
2168
+ {
2169
+ code: "types-unreadable",
2170
+ rule: "types",
2171
+ severity: "warning",
2172
+ file: output,
2173
+ message: `${output} could not be checked (${current.status === "unsafe" ? current.reason : current.status})`
2174
+ }
2175
+ ];
2176
+ }
2177
+ if (normalize(current.content) !== expected) {
2178
+ return [
2179
+ {
2180
+ code: "types-outdated",
2181
+ rule: "types",
2182
+ severity: "warning",
2183
+ file: output,
2184
+ message: `${output} is out of date with your environment variables`,
2185
+ recommendation: "Run `npx envclinic types` to regenerate it."
2186
+ }
2187
+ ];
2188
+ }
2189
+ return [];
2190
+ }
2191
+ async function collectIssues(project, options = {}) {
2192
+ const { checks } = project;
2193
+ const raw = project.loadIssues.filter(
2194
+ (issue) => checks.has("files") || !FILE_PRESENCE_CODES.has(issue.code)
2195
+ );
2196
+ const files = allFiles(project);
2197
+ if (checks.has("files")) {
2198
+ for (const file of files) {
2199
+ raw.push(
2200
+ ...findSyntaxIssues(file.path, file.parsed),
2201
+ ...findDuplicates(file.path, file.entries)
2202
+ );
2203
+ }
2204
+ for (const file of project.sourceFiles) {
2205
+ raw.push(...findEmpty(file.path, file.entries));
2206
+ if (project.example) {
2207
+ raw.push(
2208
+ ...findMissing(
2209
+ project.example.path,
2210
+ project.example.keys,
2211
+ file.path,
2212
+ file.keys
2213
+ ),
2214
+ ...findUndocumented(
2215
+ project.example.path,
2216
+ project.example.keys,
2217
+ file.path,
2218
+ file.keys
2219
+ )
2220
+ );
2221
+ }
2222
+ }
2223
+ }
2224
+ const scanEnabled = options.scan !== false;
2225
+ const codeSecrets = scanEnabled && options.codeSecrets !== false && checks.has("secrets");
2226
+ const needsUsage = scanEnabled && (checks.has("unused") || checks.has("types") && project.config.types?.enabled === true);
2227
+ let usage;
2228
+ let codeSecretIssues = [];
2229
+ if (needsUsage || codeSecrets) {
2230
+ const outcome = await scanProject(project, { secrets: codeSecrets });
2231
+ usage = outcome.usage;
2232
+ codeSecretIssues = outcome.secrets;
2233
+ }
2234
+ if (checks.has("unused") && usage) {
2235
+ raw.push(...findUnused(project, usage), ...findUndeclared(project, usage));
2236
+ }
2237
+ if (checks.has("secrets")) {
2238
+ const git = createGitChecker(project.cwd);
2239
+ const securityOptions = {
2240
+ patterns: buildPatterns(project.config.secrets?.patterns),
2241
+ isAllowed: createNameMatcher(project.config.secrets?.allow ?? []),
2242
+ isIgnored: project.isIgnored,
2243
+ publicPrefixes: project.framework.publicPrefixes
2244
+ };
2245
+ const reportedPublic = /* @__PURE__ */ new Set();
2246
+ for (const file of files) {
2247
+ for (const issue of analyzeEnvFileSecrets(
2248
+ file,
2249
+ await git.status(file.absolute),
2250
+ securityOptions
2251
+ )) {
2252
+ if (issue.code === "public-secret" && issue.variable !== void 0) {
2253
+ if (reportedPublic.has(issue.variable)) continue;
2254
+ reportedPublic.add(issue.variable);
2255
+ }
2256
+ raw.push(issue);
2257
+ }
2258
+ }
2259
+ raw.push(...codeSecretIssues);
2260
+ }
2261
+ if (checks.has("validation")) {
2262
+ const already = new Set(
2263
+ raw.filter(
2264
+ (issue) => issue.code === "missing-variable" || issue.code === "empty-variable"
2265
+ ).map((issue) => issue.variable)
2266
+ );
2267
+ raw.push(...findSchemaIssues(project, already));
2268
+ }
2269
+ if (checks.has("types") && project.config.types?.enabled === true && scanEnabled) {
2270
+ raw.push(...await checkTypesFile(project, usage));
2271
+ }
2272
+ return usage === void 0 ? { raw } : { raw, usage };
2273
+ }
2274
+ function resolveIssues(project, raw) {
2275
+ const issues = [];
2276
+ for (const item of raw) {
2277
+ if (item.variable !== void 0 && project.isIgnored(item.variable))
2278
+ continue;
2279
+ let severity;
2280
+ if (item.rule !== void 0) {
2281
+ const level = project.rules[item.rule];
2282
+ if (level === "off") continue;
2283
+ const natural = item.severity ?? "error";
2284
+ severity = SEVERITY_RANK[level] > SEVERITY_RANK[natural] ? level : natural;
2285
+ } else {
2286
+ severity = item.severity ?? "info";
2287
+ }
2288
+ if (project.strict && severity === "warning") severity = "error";
2289
+ const { rule: _rule, severity: _severity, ...rest } = item;
2290
+ issues.push({ ...rest, severity });
2291
+ }
2292
+ return issues.sort(
2293
+ (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]
2294
+ );
2295
+ }
2296
+ async function auditProject(project, options = {}) {
2297
+ const { raw, usage } = await collectIssues(project, options);
2298
+ const issues = resolveIssues(project, raw);
2299
+ const files = allFiles(project).map((file) => ({
2300
+ path: file.path,
2301
+ role: file.role,
2302
+ variables: file.keys.size
2303
+ })).sort(
2304
+ (a, b) => Number(a.role === "example") - Number(b.role === "example")
2305
+ );
2306
+ const variables = new Set(
2307
+ allFiles(project).flatMap((file) => [...file.keys])
2308
+ );
2309
+ const errors = issues.filter((issue) => issue.severity === "error").length;
2310
+ const warnings = issues.filter(
2311
+ (issue) => issue.severity === "warning"
2312
+ ).length;
2313
+ const result = {
2314
+ success: errors === 0,
2315
+ summary: {
2316
+ filesScanned: files.length,
2317
+ sourceFilesScanned: usage?.filesScanned ?? 0,
2318
+ variablesFound: variables.size,
2319
+ errors,
2320
+ warnings,
2321
+ infos: issues.length - errors - warnings
2322
+ },
2323
+ files,
2324
+ issues,
2325
+ framework: {
2326
+ id: project.framework.id,
2327
+ name: project.framework.name,
2328
+ evidence: project.framework.evidence
2329
+ }
2330
+ };
2331
+ if (project.configFile !== void 0) result.configFile = project.configFile;
2332
+ return result;
2333
+ }
2334
+
2335
+ // src/core/writer.ts
2336
+ import { promises as fs6 } from "fs";
2337
+ import path7 from "path";
2338
+ var TEMPLATE_NAME = /(example|sample|template|dist|defaults?)/i;
2339
+ function isProtectedEnvFileName(file) {
2340
+ const base = path7.basename(file);
2341
+ const looksLikeEnv = /^\.env(\.|$)/i.test(base) || /\.env$/i.test(base);
2342
+ return looksLikeEnv && !TEMPLATE_NAME.test(base);
2343
+ }
2344
+ async function resolveWriteTarget(cwd, relative) {
2345
+ const absolute = path7.resolve(cwd, relative);
2346
+ if (!isInside(cwd, absolute) || absolute === path7.resolve(cwd)) {
2347
+ return { ok: false, reason: "the path is outside the project directory" };
2348
+ }
2349
+ if (isProtectedEnvFileName(absolute)) {
2350
+ return {
2351
+ ok: false,
2352
+ reason: "envclinic never writes to real environment files; choose a template name such as .env.example"
2353
+ };
2354
+ }
2355
+ const realRoot = await fs6.realpath(cwd);
2356
+ let ancestor = path7.dirname(absolute);
2357
+ for (; ; ) {
2358
+ try {
2359
+ const real = await fs6.realpath(ancestor);
2360
+ if (!isInside(realRoot, real))
2361
+ return {
2362
+ ok: false,
2363
+ reason: "the directory resolves outside the project directory"
2364
+ };
2365
+ break;
2366
+ } catch {
2367
+ const parent = path7.dirname(ancestor);
2368
+ if (parent === ancestor)
2369
+ return { ok: false, reason: "the directory could not be resolved" };
2370
+ ancestor = parent;
2371
+ }
2372
+ }
2373
+ return { ok: true, absolute };
2374
+ }
2375
+ async function readExisting(absolute) {
2376
+ try {
2377
+ const stat = await fs6.lstat(absolute);
2378
+ if (!stat.isFile()) return void 0;
2379
+ return decodeText(await fs6.readFile(absolute)).text;
2380
+ } catch {
2381
+ return void 0;
2382
+ }
2383
+ }
2384
+ async function writeProjectFile(cwd, relative, content, options) {
2385
+ const shown = displayPath(cwd, path7.resolve(cwd, relative));
2386
+ const target = await resolveWriteTarget(cwd, relative);
2387
+ if (!target.ok)
2388
+ return { status: "refused", path: shown, reason: target.reason };
2389
+ const { absolute } = target;
2390
+ let exists3 = false;
2391
+ try {
2392
+ const stat = await fs6.lstat(absolute);
2393
+ exists3 = true;
2394
+ if (stat.isSymbolicLink())
2395
+ return {
2396
+ status: "refused",
2397
+ path: shown,
2398
+ reason: "the target is a symbolic link"
2399
+ };
2400
+ if (!stat.isFile())
2401
+ return {
2402
+ status: "refused",
2403
+ path: shown,
2404
+ reason: "the target is not a regular file"
2405
+ };
2406
+ } catch {
2407
+ }
2408
+ if (exists3) {
2409
+ const current = await fs6.readFile(absolute, "utf8");
2410
+ if (current.replace(/\r\n/g, "\n") === content)
2411
+ return { status: "unchanged", path: shown };
2412
+ if (!options.overwrite)
2413
+ return {
2414
+ status: "refused",
2415
+ path: shown,
2416
+ reason: "the file already exists"
2417
+ };
2418
+ }
2419
+ await fs6.mkdir(path7.dirname(absolute), { recursive: true });
2420
+ const temporary = `${absolute}.${process.pid}.${Date.now()}.tmp`;
2421
+ try {
2422
+ await fs6.writeFile(temporary, content, { flag: "wx" });
2423
+ await fs6.rename(temporary, absolute);
2424
+ } catch (error) {
2425
+ await fs6.rm(temporary, { force: true });
2426
+ return {
2427
+ status: "refused",
2428
+ path: shown,
2429
+ reason: `could not write the file (${error.code ?? "unknown error"})`
2430
+ };
2431
+ }
2432
+ return { status: "written", path: shown };
2433
+ }
2434
+
2435
+ // src/cli/output/github.ts
2436
+ function escapeData(text) {
2437
+ return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
2438
+ }
2439
+ function escapeProperty(text) {
2440
+ return escapeData(text).replace(/:/g, "%3A").replace(/,/g, "%2C");
2441
+ }
2442
+ var LEVEL = { error: "error", warning: "warning", info: "notice" };
2443
+ function formatAnnotation(issue) {
2444
+ const properties = [];
2445
+ if (issue.file !== void 0) {
2446
+ properties.push(`file=${escapeProperty(issue.file)}`);
2447
+ if (issue.line !== void 0) properties.push(`line=${issue.line}`);
2448
+ }
2449
+ properties.push(`title=${escapeProperty(`envclinic: ${issue.code}`)}`);
2450
+ return `::${LEVEL[issue.severity]} ${properties.join(",")}::${escapeData(issue.message)}`;
2451
+ }
2452
+ function formatGithub(result) {
2453
+ return result.issues.map((issue) => formatAnnotation(issue) + "\n").join("");
2454
+ }
2455
+
2456
+ // src/cli/output/terminal.ts
2457
+ import { createColors } from "picocolors";
2458
+ var oneOf = (...codes) => (code) => codes.includes(code);
2459
+ var SECTIONS = [
2460
+ {
2461
+ title: "Files",
2462
+ match: oneOf(
2463
+ "no-env-files",
2464
+ "source-file-missing",
2465
+ "example-file-missing",
2466
+ "unsafe-path",
2467
+ "file-too-large",
2468
+ "file-unreadable",
2469
+ "non-utf8-file"
2470
+ )
2471
+ },
2472
+ { title: "Missing variables", match: oneOf("missing-variable") },
2473
+ { title: "Undocumented variables", match: oneOf("undocumented-variable") },
2474
+ { title: "Empty variables", match: oneOf("empty-variable") },
2475
+ { title: "Duplicate declarations", match: oneOf("duplicate-variable") },
2476
+ {
2477
+ title: "Invalid names and syntax",
2478
+ match: oneOf(
2479
+ "invalid-variable-name",
2480
+ "malformed-line",
2481
+ "unterminated-quote"
2482
+ )
2483
+ },
2484
+ {
2485
+ title: "Potentially unused variables",
2486
+ match: oneOf("unused-variable", "dynamic-env-access")
2487
+ },
2488
+ { title: "Undeclared variables", match: oneOf("undeclared-variable") },
2489
+ {
2490
+ title: "Security audit",
2491
+ security: true,
2492
+ match: oneOf(
2493
+ "exposed-credential",
2494
+ "weak-secret",
2495
+ "public-secret",
2496
+ "env-file-not-ignored",
2497
+ "secret-in-example"
2498
+ )
2499
+ },
2500
+ {
2501
+ title: "Schema validation",
2502
+ match: (code) => code.startsWith("schema-") || code === "validation-skipped"
2503
+ },
2504
+ {
2505
+ title: "TypeScript declarations",
2506
+ match: oneOf("types-missing", "types-outdated", "types-unreadable")
2507
+ }
2508
+ ];
2509
+ var BOX_WIDTH = 38;
2510
+ function plural(count, word) {
2511
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
2512
+ }
2513
+ function center(text, width) {
2514
+ const total = Math.max(0, width - text.length);
2515
+ const left = Math.floor(total / 2);
2516
+ return " ".repeat(left) + text + " ".repeat(total - left);
2517
+ }
2518
+ function header() {
2519
+ return [
2520
+ `\u256D${"\u2500".repeat(BOX_WIDTH)}\u256E`,
2521
+ `\u2502${center("ENV DOCTOR", BOX_WIDTH)}\u2502`,
2522
+ `\u2502${center("Environment Configuration", BOX_WIDTH)}\u2502`,
2523
+ `\u2570${"\u2500".repeat(BOX_WIDTH)}\u256F`
2524
+ ];
2525
+ }
2526
+ function formatTerminal(result, options) {
2527
+ const pc = createColors(options.color);
2528
+ const icon = {
2529
+ error: pc.red("\u2718"),
2530
+ warning: pc.yellow("\u26A0"),
2531
+ info: pc.cyan("\u2139")
2532
+ };
2533
+ const label = {
2534
+ error: pc.red(pc.bold("[CRITICAL]")),
2535
+ warning: pc.yellow(pc.bold("[WARNING]")),
2536
+ info: pc.cyan(pc.bold("[INFO]"))
2537
+ };
2538
+ const { summary } = result;
2539
+ const lines = [];
2540
+ const summaryLine = summary.errors === 0 && summary.warnings === 0 ? `${pc.green("\u2714")} No problems found` : [
2541
+ plural(summary.errors, "error"),
2542
+ plural(summary.warnings, "warning")
2543
+ ].join(", ");
2544
+ if (options.quiet) {
2545
+ for (const issue of result.issues.filter((i) => i.severity === "error")) {
2546
+ lines.push(`${icon.error} ${issue.message}`);
2547
+ }
2548
+ lines.push(summaryLine);
2549
+ return lines.join("\n") + "\n";
2550
+ }
2551
+ lines.push(...header(), "");
2552
+ if (result.framework) {
2553
+ lines.push(`${pc.green("\u2714")} Framework detected: ${result.framework.name}`);
2554
+ lines.push("");
2555
+ }
2556
+ if (result.files.length > 0) {
2557
+ lines.push(pc.bold("Files analyzed"));
2558
+ for (const file of result.files) {
2559
+ lines.push(
2560
+ ` ${pc.green("\u2714")} ${file.path} ${pc.dim(`(${file.role}, ${plural(file.variables, "variable")})`)}`
2561
+ );
2562
+ }
2563
+ lines.push("");
2564
+ }
2565
+ const claimed = /* @__PURE__ */ new Set();
2566
+ const sections = [];
2567
+ for (const section of SECTIONS) {
2568
+ const issues = result.issues.filter((issue) => section.match(issue.code));
2569
+ issues.forEach((issue) => claimed.add(issue));
2570
+ if (issues.length > 0)
2571
+ sections.push({
2572
+ title: section.title,
2573
+ issues,
2574
+ security: section.security === true
2575
+ });
2576
+ }
2577
+ const other = result.issues.filter((issue) => !claimed.has(issue));
2578
+ if (other.length > 0)
2579
+ sections.push({ title: "Other", issues: other, security: false });
2580
+ for (const section of sections) {
2581
+ lines.push(pc.bold(`${section.title} (${section.issues.length})`));
2582
+ for (const issue of section.issues) {
2583
+ if (section.security) {
2584
+ lines.push(` ${label[issue.severity]} ${issue.message}`);
2585
+ if (issue.file)
2586
+ lines.push(
2587
+ ` File: ${issue.file}${issue.line !== void 0 ? `:${issue.line}` : ""}`
2588
+ );
2589
+ if (issue.variable) lines.push(` Variable: ${issue.variable}`);
2590
+ if (issue.variable && issue.code !== "env-file-not-ignored")
2591
+ lines.push(" Value: ********");
2592
+ } else {
2593
+ lines.push(` ${icon[issue.severity]} ${issue.message}`);
2594
+ }
2595
+ if (issue.recommendation)
2596
+ lines.push(` ${pc.dim(`\u2192 ${issue.recommendation}`)}`);
2597
+ }
2598
+ lines.push("");
2599
+ }
2600
+ lines.push(pc.bold("Summary"));
2601
+ const scanned = summary.sourceFilesScanned > 0 ? `, ${plural(summary.sourceFilesScanned, "source file")} scanned` : "";
2602
+ lines.push(
2603
+ ` ${plural(summary.filesScanned, "env file")} analyzed, ${plural(summary.variablesFound, "variable")} found${scanned}`
2604
+ );
2605
+ lines.push(` ${summaryLine}`);
2606
+ lines.push("", pc.dim("Run envclinic audit --help for options."));
2607
+ return lines.join("\n") + "\n";
2608
+ }
2609
+
2610
+ // src/cli/commands/common.ts
2611
+ var UsageError = class extends Error {
2612
+ constructor(message) {
2613
+ super(message);
2614
+ this.name = "UsageError";
2615
+ }
2616
+ };
2617
+ function resolveFormat(options) {
2618
+ if (options.json) return "json";
2619
+ const format = options.format ?? "terminal";
2620
+ if (format !== "terminal" && format !== "json" && format !== "github") {
2621
+ throw new UsageError(`Unknown format "${format}". Use terminal, json or github.`);
2622
+ }
2623
+ return format;
2624
+ }
2625
+ function toAuditOptions(options, checks) {
2626
+ const result = { strict: options.strict ?? false };
2627
+ if (checks !== void 0) result.checks = checks;
2628
+ if (options.cwd !== void 0) result.cwd = options.cwd;
2629
+ if (options.config !== void 0) result.configPath = options.config;
2630
+ if (options.file !== void 0 && options.file.length > 0) result.files = options.file;
2631
+ if (options.example !== void 0) result.example = options.example;
2632
+ if (options.ignore !== void 0 && options.ignore.length > 0) result.ignore = options.ignore;
2633
+ if (options.scan === false) result.scan = false;
2634
+ if (options.envOnly) result.codeSecrets = false;
2635
+ if (options.dir !== void 0 && options.dir.length > 0) result.scanDirectories = options.dir;
2636
+ if (options.processEnv) result.processEnv = true;
2637
+ return result;
2638
+ }
2639
+ function note(io, options, text) {
2640
+ if (resolveFormat(options) === "terminal") io.out(text + "\n");
2641
+ else io.err(text + "\n");
2642
+ }
2643
+ function printAudit(result, options, io) {
2644
+ const format = resolveFormat(options);
2645
+ if (format === "json") {
2646
+ io.out(JSON.stringify(result, null, 2) + "\n");
2647
+ return;
2648
+ }
2649
+ if (format === "github") {
2650
+ io.out(formatGithub(result));
2651
+ return;
2652
+ }
2653
+ const color = options.color !== false && !options.ci && io.color;
2654
+ io.out(formatTerminal(result, { color, quiet: Boolean(options.quiet) }));
2655
+ if (options.ci && io.env.GITHUB_ACTIONS === "true") io.out(formatGithub(result));
2656
+ }
2657
+ function exitCodeFor(result) {
2658
+ return result.success ? 0 : 1;
2659
+ }
2660
+
2661
+ // src/cli/commands/audit.ts
2662
+ var ALL = void 0;
2663
+ async function applyFix(project, options, io) {
2664
+ const { raw, usage } = await collectIssues(
2665
+ project,
2666
+ options.scan === false ? { scan: false } : {}
2667
+ );
2668
+ const issues = resolveIssues(project, raw);
2669
+ const names = [
2670
+ ...new Set(
2671
+ issues.filter(
2672
+ (issue) => issue.code === "undocumented-variable" || issue.code === "undeclared-variable"
2673
+ ).map((issue) => issue.variable)
2674
+ )
2675
+ ].sort();
2676
+ if (names.length === 0) {
2677
+ note(io, options, "Nothing to fix automatically.");
2678
+ return void 0;
2679
+ }
2680
+ if (project.example === void 0) {
2681
+ note(
2682
+ io,
2683
+ options,
2684
+ "--fix needs an existing example file. Run `envclinic generate` to create one."
2685
+ );
2686
+ return void 0;
2687
+ }
2688
+ const example = project.example;
2689
+ const variables = collectVariables(project, usage).filter(
2690
+ (info) => names.includes(info.name)
2691
+ );
2692
+ const target = await resolveWriteTarget(project.cwd, example.path);
2693
+ if (!target.ok)
2694
+ throw new UsageError(`Cannot modify ${example.path}: ${target.reason}.`);
2695
+ const existing = await readExisting(target.absolute);
2696
+ if (existing === void 0)
2697
+ throw new UsageError(`Cannot read ${example.path}.`);
2698
+ const merged = renderMerge(existing, variables);
2699
+ note(
2700
+ io,
2701
+ options,
2702
+ `Fix: add ${names.length} variable${names.length === 1 ? "" : "s"} to ${example.path} (names only, empty values): ${names.join(", ")}`
2703
+ );
2704
+ if (options.dryRun) {
2705
+ note(io, options, "Dry run: no files were changed.");
2706
+ return void 0;
2707
+ }
2708
+ if (!options.yes) {
2709
+ if (!io.prompter.interactive) {
2710
+ throw new UsageError(
2711
+ "--fix modifies files. Re-run with --yes to apply it without a prompt, or use --dry-run to preview."
2712
+ );
2713
+ }
2714
+ if (!await io.prompter.confirm(
2715
+ `Apply this change to ${example.path}?`,
2716
+ false
2717
+ )) {
2718
+ note(io, options, "Cancelled. No files were changed.");
2719
+ return 1;
2720
+ }
2721
+ }
2722
+ const written = await writeProjectFile(
2723
+ project.cwd,
2724
+ example.path,
2725
+ merged.content,
2726
+ { overwrite: true }
2727
+ );
2728
+ if (written.status === "refused")
2729
+ throw new UsageError(
2730
+ `Could not update ${example.path}: ${written.reason}.`
2731
+ );
2732
+ note(io, options, `Updated ${example.path}.`);
2733
+ return void 0;
2734
+ }
2735
+ async function auditCommand(options, io) {
2736
+ const auditOptions = toAuditOptions(options, ALL);
2737
+ let project = await loadProject(auditOptions);
2738
+ if (options.fix || options.dryRun) {
2739
+ if (options.fix) {
2740
+ const early = await applyFix(project, options, io);
2741
+ if (early !== void 0) return early;
2742
+ if (!options.dryRun) project = await loadProject(auditOptions);
2743
+ }
2744
+ }
2745
+ const result = await auditProject(project, auditOptions);
2746
+ if (options.verbose && !options.json) {
2747
+ io.err(`cwd: ${project.cwd}
2748
+ `);
2749
+ io.err(`config: ${project.configFile ?? "none (using defaults)"}
2750
+ `);
2751
+ io.err(`framework: ${project.framework.name}
2752
+ `);
2753
+ io.err(`strict: ${options.strict ? "yes" : "no"}
2754
+ `);
2755
+ }
2756
+ printAudit(result, options, io);
2757
+ return exitCodeFor(result);
2758
+ }
2759
+
2760
+ // src/cli/commands/framework.ts
2761
+ import { createColors as createColors2 } from "picocolors";
2762
+ async function frameworkCommand(options, io) {
2763
+ const project = await loadProject(toAuditOptions(options, []));
2764
+ const info = project.framework;
2765
+ if (resolveFormat(options) === "json") {
2766
+ io.out(JSON.stringify(info, null, 2) + "\n");
2767
+ return 0;
2768
+ }
2769
+ const pc = createColors2(options.color !== false && io.color);
2770
+ const lines = [
2771
+ `${pc.green("\u2714")} Framework detected: ${pc.bold(info.name)}${info.forced ? " (set in config)" : ""}`,
2772
+ "",
2773
+ ` Access patterns: ${info.accessPatterns.join(", ")}`,
2774
+ ` Public prefixes: ${info.publicPrefixes.length > 0 ? info.publicPrefixes.join(", ") : "none (nothing is assumed to reach the browser)"}`
2775
+ ];
2776
+ if (info.detected.length > 1) lines.push(` Also detected: ${info.detected.slice(1).join(", ")}`);
2777
+ lines.push("", pc.bold("Evidence"), ...info.evidence.map((item) => ` - ${item}`));
2778
+ if (info.notes.length > 0) lines.push("", pc.bold("Notes"), ...info.notes.map((note2) => ` - ${note2}`));
2779
+ io.out(lines.join("\n") + "\n");
2780
+ return 0;
2781
+ }
2782
+
2783
+ // src/cli/commands/generate.ts
2784
+ async function generateCommand(options, io) {
2785
+ const project = await loadProject(toAuditOptions(options, []));
2786
+ const usage = options.scan === false ? void 0 : (await scanProject(project, { secrets: false })).usage;
2787
+ const variables = exampleVariables(project, usage, options.exclude ?? []);
2788
+ if (variables.length === 0) {
2789
+ note(
2790
+ io,
2791
+ options,
2792
+ "Nothing to generate: no environment variables were found in env files, the schema or source code."
2793
+ );
2794
+ return 1;
2795
+ }
2796
+ const output = exampleOutputPath(project, options.output);
2797
+ const target = await resolveWriteTarget(project.cwd, output);
2798
+ if (!target.ok)
2799
+ throw new UsageError(`Cannot write ${output}: ${target.reason}.`);
2800
+ const existing = await readExisting(target.absolute);
2801
+ let mode = "create";
2802
+ if (existing !== void 0) {
2803
+ if (options.force) mode = "overwrite";
2804
+ else if (options.merge) mode = "merge";
2805
+ else if (options.dryRun) mode = "merge";
2806
+ else if (io.prompter.interactive) {
2807
+ const choice = await io.prompter.select(
2808
+ `${output} already exists. What should envclinic do?`,
2809
+ [
2810
+ {
2811
+ value: "merge",
2812
+ label: "Add only the missing variables (keeps your comments and order)"
2813
+ },
2814
+ { value: "overwrite", label: "Replace the file" },
2815
+ { value: "cancel", label: "Cancel" }
2816
+ ],
2817
+ "merge"
2818
+ );
2819
+ if (choice === "cancel") {
2820
+ note(io, options, "Cancelled. No files were changed.");
2821
+ return 1;
2822
+ }
2823
+ mode = choice;
2824
+ } else {
2825
+ throw new UsageError(
2826
+ `${output} already exists. Use --merge to add missing variables, --force to replace it, or --dry-run to preview.`
2827
+ );
2828
+ }
2829
+ }
2830
+ let content;
2831
+ let summary;
2832
+ if (mode === "merge" && existing !== void 0) {
2833
+ const merged = renderMerge(existing, variables);
2834
+ content = merged.content;
2835
+ summary = merged.added.length === 0 ? `${output} already lists every variable.` : `Added ${merged.added.length} variable${merged.added.length === 1 ? "" : "s"} to ${output}: ${merged.added.join(", ")}`;
2836
+ } else {
2837
+ content = renderExample(variables, project.framework.publicPrefixes);
2838
+ summary = `${mode === "overwrite" ? "Replaced" : "Created"} ${output} with ${variables.length} variable${variables.length === 1 ? "" : "s"}.`;
2839
+ }
2840
+ if (options.dryRun) {
2841
+ io.out(content);
2842
+ io.err(`Dry run: ${output} was not written.
2843
+ `);
2844
+ return 0;
2845
+ }
2846
+ const written = await writeProjectFile(project.cwd, output, content, {
2847
+ overwrite: mode !== "create"
2848
+ });
2849
+ if (written.status === "refused")
2850
+ throw new UsageError(`Could not write ${output}: ${written.reason}.`);
2851
+ note(
2852
+ io,
2853
+ options,
2854
+ written.status === "unchanged" ? `${output} is already up to date.` : summary
2855
+ );
2856
+ return 0;
2857
+ }
2858
+
2859
+ // src/cli/commands/init.ts
2860
+ import { promises as fs7 } from "fs";
2861
+ import path8 from "path";
2862
+ var SOURCE_DIRECTORIES = [
2863
+ "src",
2864
+ "app",
2865
+ "pages",
2866
+ "lib",
2867
+ "server",
2868
+ "components"
2869
+ ];
2870
+ var PRESETS = {
2871
+ recommended: {},
2872
+ strict: {
2873
+ undocumented: "error",
2874
+ empty: "error",
2875
+ unused: "error",
2876
+ undeclared: "error",
2877
+ weak: "error"
2878
+ },
2879
+ minimal: {
2880
+ undocumented: "off",
2881
+ empty: "off",
2882
+ unused: "off",
2883
+ undeclared: "off",
2884
+ weak: "off",
2885
+ names: "off",
2886
+ syntax: "off"
2887
+ }
2888
+ };
2889
+ async function existingEnvFiles(cwd) {
2890
+ try {
2891
+ const entries = await fs7.readdir(cwd, { withFileTypes: true });
2892
+ return entries.filter((entry) => entry.isFile() && /^\.env(\.|$)/.test(entry.name)).map((entry) => entry.name).sort();
2893
+ } catch {
2894
+ return [];
2895
+ }
2896
+ }
2897
+ async function existingDirectories(cwd) {
2898
+ const found = [];
2899
+ for (const name of SOURCE_DIRECTORIES) {
2900
+ try {
2901
+ if ((await fs7.stat(path8.join(cwd, name))).isDirectory()) found.push(name);
2902
+ } catch {
2903
+ }
2904
+ }
2905
+ return found;
2906
+ }
2907
+ var csv = (text) => text.split(",").map((part) => part.trim()).filter(Boolean);
2908
+ function renderConfig(config, format) {
2909
+ const body = JSON.stringify(config, null, 2);
2910
+ if (format === "json") return body + "\n";
2911
+ return `/** @type {import("envclinic").EnvDoctorConfig} */
2912
+ export default ${body};
2913
+ `;
2914
+ }
2915
+ async function initCommand(options, io) {
2916
+ const format = options.configFormat ?? "json";
2917
+ if (format !== "json" && format !== "mjs")
2918
+ throw new UsageError(`Unknown config format "${format}". Use json or mjs.`);
2919
+ if (!options.yes && !io.prompter.interactive) {
2920
+ throw new UsageError(
2921
+ "init asks questions, but there is no terminal. Re-run with --yes to accept the defaults."
2922
+ );
2923
+ }
2924
+ const project = await loadProject(toAuditOptions(options, []));
2925
+ const envFiles = await existingEnvFiles(project.cwd);
2926
+ const directories = await existingDirectories(project.cwd);
2927
+ const sourceDefault = envFiles.filter(
2928
+ (name) => !/(example|sample|template)/i.test(name)
2929
+ );
2930
+ const exampleDefault = project.example?.path ?? envFiles.find((name) => /example|sample/i.test(name)) ?? ".env.example";
2931
+ let sources = sourceDefault.length > 0 ? sourceDefault.filter((name) => name === ".env" || name === ".env.local") : [".env"];
2932
+ if (sources.length === 0) sources = [".env"];
2933
+ let example = exampleDefault;
2934
+ let scanDirectories = directories.length > 0 ? directories : ["."];
2935
+ let preset = "recommended";
2936
+ let typesEnabled = false;
2937
+ if (!options.yes) {
2938
+ const ask = io.prompter;
2939
+ note(
2940
+ io,
2941
+ options,
2942
+ `Detected framework: ${project.framework.name}. Env files found: ${envFiles.length > 0 ? envFiles.join(", ") : "none"}.`
2943
+ );
2944
+ sources = csv(
2945
+ await ask.input(
2946
+ "Env files to audit (comma separated)",
2947
+ sources.join(", ")
2948
+ )
2949
+ );
2950
+ if (sources.length === 0) sources = [".env"];
2951
+ example = await ask.input(
2952
+ "Example file that documents your variables",
2953
+ example
2954
+ );
2955
+ scanDirectories = csv(
2956
+ await ask.input(
2957
+ "Directories with source code to scan (comma separated)",
2958
+ scanDirectories.join(", ")
2959
+ )
2960
+ );
2961
+ if (scanDirectories.length === 0) scanDirectories = ["."];
2962
+ preset = await ask.select(
2963
+ "How strict should the audit be?",
2964
+ [
2965
+ {
2966
+ value: "recommended",
2967
+ label: "Recommended: missing and duplicate variables fail, the rest warn"
2968
+ },
2969
+ {
2970
+ value: "strict",
2971
+ label: "Strict: unused, undeclared, empty and weak secrets fail too"
2972
+ },
2973
+ {
2974
+ value: "minimal",
2975
+ label: "Minimal: only missing variables, duplicates and secrets"
2976
+ }
2977
+ ],
2978
+ "recommended"
2979
+ );
2980
+ typesEnabled = await ask.confirm(
2981
+ "Report when the generated TypeScript declarations (env.d.ts) are out of date?",
2982
+ false
2983
+ );
2984
+ }
2985
+ const config = {
2986
+ files: { source: sources, example },
2987
+ scan: { directories: scanDirectories },
2988
+ rules: { ...DEFAULT_RULES, ...PRESETS[preset] },
2989
+ ignore: { variables: [] }
2990
+ };
2991
+ if (typesEnabled) config.types = { enabled: true, output: "env.d.ts" };
2992
+ const file = `envclinic.config.${format}`;
2993
+ const target = await resolveWriteTarget(project.cwd, file);
2994
+ if (!target.ok)
2995
+ throw new UsageError(`Cannot write ${file}: ${target.reason}.`);
2996
+ let overwrite = false;
2997
+ if (await readExisting(target.absolute) !== void 0) {
2998
+ if (options.force) overwrite = true;
2999
+ else if (!options.yes && io.prompter.interactive && await io.prompter.confirm(`${file} already exists. Replace it?`, false))
3000
+ overwrite = true;
3001
+ else
3002
+ throw new UsageError(
3003
+ `${file} already exists. Use --force to replace it.`
3004
+ );
3005
+ }
3006
+ const written = await writeProjectFile(
3007
+ project.cwd,
3008
+ file,
3009
+ renderConfig(config, format),
3010
+ { overwrite }
3011
+ );
3012
+ if (written.status === "refused")
3013
+ throw new UsageError(`Could not write ${file}: ${written.reason}.`);
3014
+ note(
3015
+ io,
3016
+ options,
3017
+ `Created ${file}.
3018
+ Next: run \`npx envclinic\` to audit your project.`
3019
+ );
3020
+ return 0;
3021
+ }
3022
+
3023
+ // src/cli/commands/subsets.ts
3024
+ async function runSubset(options, io, checks) {
3025
+ const auditOptions = toAuditOptions(options, checks);
3026
+ const result = await auditProject(
3027
+ await loadProject(auditOptions),
3028
+ auditOptions
3029
+ );
3030
+ printAudit(result, options, io);
3031
+ return exitCodeFor(result);
3032
+ }
3033
+ function checkCommand(options, io) {
3034
+ return runSubset(options, io, ["files", "validation"]);
3035
+ }
3036
+ function secretsCommand(options, io) {
3037
+ return runSubset(options, io, ["secrets"]);
3038
+ }
3039
+ function unusedCommand(options, io) {
3040
+ if (options.scan === false)
3041
+ throw new UsageError(
3042
+ "`unused` needs to scan source code, so --no-scan cannot be used with it."
3043
+ );
3044
+ return runSubset(options, io, ["unused"]);
3045
+ }
3046
+ async function validateCommand(options, io) {
3047
+ const auditOptions = toAuditOptions(options, ["validation"]);
3048
+ const project = await loadProject(auditOptions);
3049
+ if (project.schema === void 0) {
3050
+ throw new UsageError(
3051
+ "No schema found. Add a `schema` to your envclinic config file (see docs/configuration.md)."
3052
+ );
3053
+ }
3054
+ if (project.sourceFiles.length === 0 && Object.keys(project.env).length === 0) {
3055
+ throw new UsageError(
3056
+ "Nothing to validate: no environment file was found. Pass --file, or use --process-env to validate the process environment."
3057
+ );
3058
+ }
3059
+ const result = await auditProject(project, auditOptions);
3060
+ printAudit(result, options, io);
3061
+ return exitCodeFor(result);
3062
+ }
3063
+
3064
+ // src/cli/commands/types.ts
3065
+ async function typesCommand(options, io) {
3066
+ const project = await loadProject(toAuditOptions(options, []));
3067
+ const usage = options.scan === false ? void 0 : (await scanProject(project, { secrets: false })).usage;
3068
+ const content = buildTypesContent(project, usage);
3069
+ const output = typesOutputPath(project, options.output);
3070
+ const target = await resolveWriteTarget(project.cwd, output);
3071
+ if (!target.ok)
3072
+ throw new UsageError(`Cannot write ${output}: ${target.reason}.`);
3073
+ const existing = await readExisting(target.absolute);
3074
+ if (options.check) {
3075
+ if (existing === void 0) {
3076
+ note(
3077
+ io,
3078
+ options,
3079
+ `${output} does not exist. Run \`envclinic types\` to generate it.`
3080
+ );
3081
+ return 1;
3082
+ }
3083
+ if (existing.replace(/\r\n/g, "\n") !== content) {
3084
+ note(
3085
+ io,
3086
+ options,
3087
+ `${output} is out of date. Run \`envclinic types\` to regenerate it.`
3088
+ );
3089
+ return 1;
3090
+ }
3091
+ note(io, options, `${output} is up to date.`);
3092
+ return 0;
3093
+ }
3094
+ if (existing !== void 0 && !options.force && !existing.trimStart().startsWith(GENERATED_MARKER)) {
3095
+ throw new UsageError(
3096
+ `${output} was not generated by envclinic, so it will not be overwritten. Use --output to pick another path or --force to replace it.`
3097
+ );
3098
+ }
3099
+ if (options.dryRun) {
3100
+ io.out(content);
3101
+ io.err(`Dry run: ${output} was not written.
3102
+ `);
3103
+ return 0;
3104
+ }
3105
+ const written = await writeProjectFile(project.cwd, output, content, {
3106
+ overwrite: true
3107
+ });
3108
+ if (written.status === "refused")
3109
+ throw new UsageError(`Could not write ${output}: ${written.reason}.`);
3110
+ note(
3111
+ io,
3112
+ options,
3113
+ written.status === "unchanged" ? `${output} is already up to date.` : `Wrote ${output}.`
3114
+ );
3115
+ return 0;
3116
+ }
3117
+
3118
+ // src/cli/io.ts
3119
+ import { createInterface } from "readline/promises";
3120
+ var nonInteractivePrompter = {
3121
+ interactive: false,
3122
+ confirm: async (_message, defaultValue = false) => defaultValue,
3123
+ select: async (_message, _choices, defaultValue) => defaultValue,
3124
+ input: async (_message, defaultValue = "") => defaultValue
3125
+ };
3126
+ function createReadlinePrompter() {
3127
+ const ask = async (question) => {
3128
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
3129
+ try {
3130
+ return (await rl.question(question)).trim();
3131
+ } finally {
3132
+ rl.close();
3133
+ }
3134
+ };
3135
+ return {
3136
+ interactive: true,
3137
+ async confirm(message, defaultValue = false) {
3138
+ const answer = (await ask(`${message} ${defaultValue ? "[Y/n]" : "[y/N]"} `)).toLowerCase();
3139
+ if (answer === "") return defaultValue;
3140
+ return answer === "y" || answer === "yes";
3141
+ },
3142
+ async select(message, choices, defaultValue) {
3143
+ const lines = choices.map((choice, index) => ` ${index + 1}) ${choice.label}${choice.value === defaultValue ? " (default)" : ""}`);
3144
+ const answer = await ask(`${message}
3145
+ ${lines.join("\n")}
3146
+ > `);
3147
+ const byNumber = choices[Number(answer) - 1];
3148
+ if (byNumber) return byNumber.value;
3149
+ const byValue = choices.find((choice) => choice.value === answer.toLowerCase());
3150
+ return byValue ? byValue.value : defaultValue;
3151
+ },
3152
+ async input(message, defaultValue = "") {
3153
+ const answer = await ask(`${message}${defaultValue ? ` (${defaultValue})` : ""}: `);
3154
+ return answer === "" ? defaultValue : answer;
3155
+ }
3156
+ };
3157
+ }
3158
+ var canPrompt = Boolean(process.stdin.isTTY) && Boolean(process.stderr.isTTY) && !process.env.CI;
3159
+ var processIO = {
3160
+ out: (text) => {
3161
+ process.stdout.write(text);
3162
+ },
3163
+ err: (text) => {
3164
+ process.stderr.write(text);
3165
+ },
3166
+ color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && process.env.TERM !== "dumb",
3167
+ env: process.env,
3168
+ prompter: canPrompt ? createReadlinePrompter() : nonInteractivePrompter
3169
+ };
3170
+
3171
+ // src/cli/run.ts
3172
+ var EXIT_OK = 0;
3173
+ var EXIT_FAILURE = 2;
3174
+ function collect(value, previous) {
3175
+ return [
3176
+ ...previous,
3177
+ ...value.split(",").map((part) => part.trim()).filter(Boolean)
3178
+ ];
3179
+ }
3180
+ async function run(argv, io = processIO) {
3181
+ let exitCode = EXIT_OK;
3182
+ let wantsJson = argv.includes("--json") || argv.some((arg, i) => arg === "json" && argv[i - 1] === "--format");
3183
+ const program = new Command();
3184
+ program.name("envclinic").description("Audit, validate and secure environment configurations").version(package_default.version).option("--cwd <dir>", "project directory (default: current directory)").option("--config <path>", "path to an envclinic config file").option("--json", "print machine-readable JSON").option("--format <format>", "output format: terminal, json or github").option("--quiet", "only print errors and a summary").option("--verbose", "print the resolved settings").option("--no-color", "disable colored output").exitOverride().configureOutput({
3185
+ writeOut: (text) => io.out(text),
3186
+ writeErr: (text) => io.err(text)
3187
+ });
3188
+ const register = (command, handler) => command.allowExcessArguments(false).action(async (_options, self) => {
3189
+ const all = self.optsWithGlobals();
3190
+ wantsJson = Boolean(all.json) || all.format === "json";
3191
+ exitCode = await handler(all, io);
3192
+ });
3193
+ const strict = (c) => c.option("--strict", "treat warnings as errors");
3194
+ const ci = (c) => c.option(
3195
+ "--ci",
3196
+ "non-interactive mode: no colors, GitHub annotations when running in Actions"
3197
+ );
3198
+ const files = (c) => c.option(
3199
+ "-f, --file <path>",
3200
+ "env file to audit; repeatable (default: .env)",
3201
+ collect,
3202
+ []
3203
+ );
3204
+ const ignore = (c) => c.option(
3205
+ "--ignore <names>",
3206
+ "variable names to ignore, comma-separated; repeatable",
3207
+ collect,
3208
+ []
3209
+ );
3210
+ const processEnv = (c) => c.option(
3211
+ "--process-env",
3212
+ "also validate the real process environment (it wins over env files)"
3213
+ );
3214
+ register(
3215
+ processEnv(
3216
+ ignore(
3217
+ files(
3218
+ ci(
3219
+ strict(
3220
+ program.command("audit", { isDefault: true }).description("Run the complete environment audit").option(
3221
+ "--example <path>",
3222
+ "example file to compare against (default: .env.example or .env.sample)"
3223
+ ).option(
3224
+ "--no-scan",
3225
+ "do not scan source code (skips unused variables and hardcoded credentials)"
3226
+ ).option(
3227
+ "--fix",
3228
+ "add undocumented variables to the example file (asks for confirmation)"
3229
+ ).option(
3230
+ "--dry-run",
3231
+ "with --fix: show what would change without writing"
3232
+ ).option("--yes", "with --fix: apply without asking")
3233
+ )
3234
+ )
3235
+ )
3236
+ )
3237
+ ),
3238
+ auditCommand
3239
+ );
3240
+ register(
3241
+ processEnv(
3242
+ ignore(
3243
+ files(
3244
+ ci(
3245
+ strict(
3246
+ program.command("check").description(
3247
+ "Check for missing, empty, duplicate and invalid variables, and validate the schema"
3248
+ ).option("--example <path>", "example file to compare against")
3249
+ )
3250
+ )
3251
+ )
3252
+ )
3253
+ ),
3254
+ checkCommand
3255
+ );
3256
+ register(
3257
+ ignore(
3258
+ ci(
3259
+ strict(
3260
+ program.command("secrets").description("Detect potentially exposed secrets and weak secrets").option("--env-only", "only check env files, not source code")
3261
+ )
3262
+ )
3263
+ ),
3264
+ secretsCommand
3265
+ );
3266
+ register(
3267
+ ignore(
3268
+ ci(
3269
+ strict(
3270
+ program.command("unused").description("Detect potentially unused and undeclared variables").option(
3271
+ "--dir <path>",
3272
+ "directory to scan; repeatable (default: project root)",
3273
+ collect,
3274
+ []
3275
+ )
3276
+ )
3277
+ )
3278
+ ),
3279
+ unusedCommand
3280
+ );
3281
+ register(
3282
+ processEnv(
3283
+ files(
3284
+ ci(
3285
+ strict(
3286
+ program.command("validate").description(
3287
+ "Validate environment values against the schema in your config"
3288
+ )
3289
+ )
3290
+ )
3291
+ )
3292
+ ),
3293
+ validateCommand
3294
+ );
3295
+ register(
3296
+ program.command("generate").description("Generate or update .env.example (names only, never values)").option("-o, --output <path>", "file to write (default: .env.example)").option("--dry-run", "print the result without writing").option("--force", "replace the file if it exists").option("--merge", "add missing variables to the file if it exists").option(
3297
+ "--exclude <names>",
3298
+ "variables to leave out, comma-separated; repeatable",
3299
+ collect,
3300
+ []
3301
+ ).option("--no-scan", "do not detect variables from source code"),
3302
+ generateCommand
3303
+ );
3304
+ register(
3305
+ program.command("types").description("Generate TypeScript declarations for environment variables").option("-o, --output <path>", "file to write (default: env.d.ts)").option("--dry-run", "print the result without writing").option("--force", "overwrite a file that was not generated by envclinic").option(
3306
+ "--check",
3307
+ "exit with code 1 if the file is missing or out of date, without writing"
3308
+ ).option("--no-scan", "do not detect variables from source code"),
3309
+ typesCommand
3310
+ );
3311
+ register(
3312
+ program.command("framework").description("Detect the framework and its environment conventions"),
3313
+ frameworkCommand
3314
+ );
3315
+ register(
3316
+ program.command("init").description("Create an envclinic config file").option("--yes", "accept the defaults without asking questions").option("--force", "replace an existing config file").option(
3317
+ "--config-format <format>",
3318
+ "config file format: json or mjs",
3319
+ "json"
3320
+ ),
3321
+ initCommand
3322
+ );
3323
+ try {
3324
+ await program.parseAsync(argv, { from: "user" });
3325
+ return exitCode;
3326
+ } catch (error) {
3327
+ if (error instanceof CommanderError) {
3328
+ const informational = error.code === "commander.helpDisplayed" || error.code === "commander.version" || error.code === "commander.help";
3329
+ return informational ? EXIT_OK : EXIT_FAILURE;
3330
+ }
3331
+ const message = error instanceof Error ? error.message : "Unexpected error";
3332
+ if (wantsJson) {
3333
+ io.out(
3334
+ JSON.stringify({ success: false, error: message }, null, 2) + "\n"
3335
+ );
3336
+ } else {
3337
+ io.err(`envclinic: ${message}
3338
+ `);
3339
+ }
3340
+ return EXIT_FAILURE;
3341
+ }
3342
+ }
3343
+
3344
+ // src/cli/index.ts
3345
+ run(process.argv.slice(2)).then((code) => {
3346
+ process.exitCode = code;
3347
+ });
3348
+ //# sourceMappingURL=index.js.map