@subramanyaks/env-drift 1.0.1 → 1.2.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.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { realpathSync } from "fs";
5
- import { resolve as resolve2 } from "path";
5
+ import { resolve as resolve5 } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  import { parseArgs } from "util";
8
8
  import pc2 from "picocolors";
@@ -10,7 +10,7 @@ import pc2 from "picocolors";
10
10
  // package.json
11
11
  var package_default = {
12
12
  name: "@subramanyaks/env-drift",
13
- version: "1.0.1",
13
+ version: "1.2.0",
14
14
  description: "Zero-config CLI and library to detect environment variable drift, missing keys, dead vars, and accidental public secret exposure.",
15
15
  type: "module",
16
16
  publishConfig: {
@@ -32,6 +32,7 @@ var package_default = {
32
32
  files: [
33
33
  "dist",
34
34
  "README.md",
35
+ "CHANGELOG.md",
35
36
  "LICENSE"
36
37
  ],
37
38
  engines: {
@@ -84,28 +85,31 @@ import { resolve } from "path";
84
85
  // src/envParser.ts
85
86
  import { existsSync, readFileSync, writeFileSync } from "fs";
86
87
  var ENV_LINE_REGEX = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
88
+ function parseDoubleQuotedValue(raw) {
89
+ let result = "";
90
+ for (let i = 1; i < raw.length; i++) {
91
+ const ch = raw[i];
92
+ if (ch === "\\" && i + 1 < raw.length) {
93
+ const next = raw[i + 1];
94
+ if (next === "n") result += "\n";
95
+ else if (next === "r") result += "\r";
96
+ else if (next === "t") result += " ";
97
+ else result += next;
98
+ i++;
99
+ } else if (ch === '"') {
100
+ return { value: result, closed: true };
101
+ } else {
102
+ result += ch;
103
+ }
104
+ }
105
+ return { value: result, closed: false };
106
+ }
87
107
  function parseValue(raw) {
88
108
  const trimmed = raw.trim();
89
109
  if (!trimmed) return "";
90
110
  const quote = trimmed[0];
91
111
  if (quote === '"') {
92
- let result = "";
93
- for (let i = 1; i < trimmed.length; i++) {
94
- const ch = trimmed[i];
95
- if (ch === "\\" && i + 1 < trimmed.length) {
96
- const next = trimmed[i + 1];
97
- if (next === "n") result += "\n";
98
- else if (next === "r") result += "\r";
99
- else if (next === "t") result += " ";
100
- else result += next;
101
- i++;
102
- } else if (ch === '"') {
103
- return result;
104
- } else {
105
- result += ch;
106
- }
107
- }
108
- return result;
112
+ return parseDoubleQuotedValue(trimmed).value;
109
113
  }
110
114
  if (quote === "'") {
111
115
  const closingIdx = trimmed.indexOf("'", 1);
@@ -125,8 +129,10 @@ function parseEnvContent(content) {
125
129
  const seen = /* @__PURE__ */ new Set();
126
130
  const duplicateSet = /* @__PURE__ */ new Set();
127
131
  const values = {};
132
+ const keyLines = {};
128
133
  const lines = content.split(/\r?\n/);
129
- for (const rawLine of lines) {
134
+ for (let i = 0; i < lines.length; i++) {
135
+ const rawLine = lines[i];
130
136
  const line = rawLine.trim();
131
137
  if (!line || line.startsWith("#")) continue;
132
138
  const match = ENV_LINE_REGEX.exec(line);
@@ -134,17 +140,33 @@ function parseEnvContent(content) {
134
140
  const key = match[1];
135
141
  const rawValue = match[2] ?? "";
136
142
  if (!key) continue;
143
+ const startLine = i + 1;
137
144
  if (seen.has(key)) {
138
145
  duplicateSet.add(key);
139
146
  } else {
140
147
  seen.add(key);
141
148
  keys.push(key);
142
149
  }
143
- values[key] = parseValue(rawValue);
150
+ const trimmedVal = rawValue.trimStart();
151
+ if (trimmedVal.startsWith('"')) {
152
+ let combined = trimmedVal;
153
+ let parsed = parseDoubleQuotedValue(combined);
154
+ while (!parsed.closed && i + 1 < lines.length) {
155
+ i++;
156
+ combined += `
157
+ ${lines[i]}`;
158
+ parsed = parseDoubleQuotedValue(combined);
159
+ }
160
+ values[key] = parsed.value;
161
+ } else {
162
+ values[key] = parseValue(rawValue);
163
+ }
164
+ keyLines[key] = startLine;
144
165
  }
145
166
  return {
146
167
  keys,
147
168
  values,
169
+ lines: keyLines,
148
170
  duplicates: Array.from(duplicateSet)
149
171
  };
150
172
  }
@@ -155,16 +177,18 @@ function parseEnvFile(filePath) {
155
177
  exists: false,
156
178
  keys: [],
157
179
  values: {},
180
+ lines: {},
158
181
  duplicates: []
159
182
  };
160
183
  }
161
184
  const content = readFileSync(filePath, "utf-8");
162
- const { keys, values, duplicates } = parseEnvContent(content);
185
+ const { keys, values, lines, duplicates } = parseEnvContent(content);
163
186
  return {
164
187
  filePath,
165
188
  exists: true,
166
189
  keys,
167
190
  values,
191
+ lines,
168
192
  duplicates
169
193
  };
170
194
  }
@@ -222,12 +246,109 @@ var DEFAULT_EXTENSIONS = /* @__PURE__ */ new Set([
222
246
  ".svelte",
223
247
  ".astro"
224
248
  ]);
249
+ var REGEX_PRECEDING_KEYWORDS = /* @__PURE__ */ new Set([
250
+ "return",
251
+ "case",
252
+ "throw",
253
+ "in",
254
+ "of",
255
+ "typeof",
256
+ "void",
257
+ "delete",
258
+ "await",
259
+ "yield",
260
+ "else",
261
+ "do"
262
+ ]);
225
263
  function stripCommentsPreservingLines(source) {
226
- const tokenRegex = /("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g;
227
- return source.replace(tokenRegex, (match, stringLiteral) => {
228
- if (stringLiteral) return match;
229
- return match.replace(/[^\r\n]/g, " ");
230
- });
264
+ const out = [];
265
+ const len = source.length;
266
+ let i = 0;
267
+ let prevSignificant = "";
268
+ let prevWord = "";
269
+ while (i < len) {
270
+ const ch = source[i];
271
+ const next = i + 1 < len ? source[i + 1] : "";
272
+ if (ch === '"' || ch === "'" || ch === "`") {
273
+ const quote = ch;
274
+ out.push(ch);
275
+ i++;
276
+ while (i < len) {
277
+ const c = source[i];
278
+ out.push(c);
279
+ i++;
280
+ if (c === "\\" && i < len) {
281
+ out.push(source[i]);
282
+ i++;
283
+ } else if (c === quote) {
284
+ break;
285
+ }
286
+ }
287
+ prevSignificant = quote;
288
+ prevWord = "";
289
+ continue;
290
+ }
291
+ if (ch === "/" && next === "/") {
292
+ out.push(" ", " ");
293
+ i += 2;
294
+ while (i < len && source[i] !== "\n" && source[i] !== "\r") {
295
+ out.push(" ");
296
+ i++;
297
+ }
298
+ continue;
299
+ }
300
+ if (ch === "/" && next === "*") {
301
+ out.push(" ", " ");
302
+ i += 2;
303
+ while (i < len) {
304
+ if (source[i] === "*" && i + 1 < len && source[i + 1] === "/") {
305
+ out.push(" ", " ");
306
+ i += 2;
307
+ break;
308
+ }
309
+ const c = source[i];
310
+ out.push(c === "\n" || c === "\r" ? c : " ");
311
+ i++;
312
+ }
313
+ continue;
314
+ }
315
+ if (ch === "/" && (prevSignificant === "" || "=([{,;:!&|?+-*%^~<>".includes(prevSignificant) || REGEX_PRECEDING_KEYWORDS.has(prevWord))) {
316
+ out.push(ch);
317
+ i++;
318
+ let inCharClass = false;
319
+ while (i < len) {
320
+ const c = source[i];
321
+ out.push(c);
322
+ i++;
323
+ if (c === "\\" && i < len) {
324
+ out.push(source[i]);
325
+ i++;
326
+ } else if (c === "[") {
327
+ inCharClass = true;
328
+ } else if (c === "]") {
329
+ inCharClass = false;
330
+ } else if (c === "/" && !inCharClass) {
331
+ break;
332
+ } else if (c === "\n" || c === "\r") {
333
+ break;
334
+ }
335
+ }
336
+ prevSignificant = "/";
337
+ prevWord = "";
338
+ continue;
339
+ }
340
+ out.push(ch);
341
+ if (!/\s/.test(ch)) {
342
+ if (/[A-Za-z0-9_$]/.test(ch)) {
343
+ prevWord = /[A-Za-z0-9_$]/.test(prevSignificant) ? prevWord + ch : ch;
344
+ } else {
345
+ prevWord = "";
346
+ }
347
+ prevSignificant = ch;
348
+ }
349
+ i++;
350
+ }
351
+ return out.join("");
231
352
  }
232
353
  function getLineNumber(source, index) {
233
354
  let line = 1;
@@ -236,35 +357,48 @@ function getLineNumber(source, index) {
236
357
  }
237
358
  return line;
238
359
  }
360
+ function collectIgnoredLines(source) {
361
+ const ignored = /* @__PURE__ */ new Set();
362
+ const lines = source.split(/\r?\n/);
363
+ for (let i = 0; i < lines.length; i++) {
364
+ const line = lines[i];
365
+ if (/(?:\/\/|\/\*)\s*env-drift-ignore-next-line\b/.test(line)) {
366
+ ignored.add(i + 2);
367
+ } else if (/(?:\/\/|\/\*)\s*env-drift-ignore\b/.test(line)) {
368
+ ignored.add(i + 1);
369
+ }
370
+ }
371
+ return ignored;
372
+ }
239
373
  function extractEnvReferences(content, filePath) {
374
+ const ignoredLines = collectIgnoredLines(content);
240
375
  const cleaned = stripCommentsPreservingLines(content);
241
376
  const refs = [];
242
377
  const normalizedFile = filePath.replace(/\\/g, "/");
243
- const dotRegex = /\b(process\.env|import\.meta\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
244
- for (const match of cleaned.matchAll(dotRegex)) {
245
- const source = match[1];
246
- const name = match[2];
247
- if (!name || match.index === void 0) continue;
378
+ const addRef = (name, line, source) => {
379
+ if (ignoredLines.has(line)) return;
248
380
  refs.push({
249
381
  name,
250
382
  file: normalizedFile,
251
- line: getLineNumber(cleaned, match.index),
383
+ line,
252
384
  source
253
385
  });
386
+ };
387
+ const dotRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*\??\.\s*([A-Za-z_][A-Za-z0-9_]*)\b/g;
388
+ for (const match of cleaned.matchAll(dotRegex)) {
389
+ const source = match[1];
390
+ const name = match[2];
391
+ if (!name || match.index === void 0) continue;
392
+ addRef(name, getLineNumber(cleaned, match.index), source);
254
393
  }
255
- const bracketRegex = /\b(process\.env|import\.meta\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
394
+ const bracketRegex = /\b(process\.env|import\.meta\.env|Bun\.env)\s*(?:\?\.)?\s*\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g;
256
395
  for (const match of cleaned.matchAll(bracketRegex)) {
257
396
  const source = match[1];
258
397
  const name = match[2];
259
398
  if (!name || match.index === void 0) continue;
260
- refs.push({
261
- name,
262
- file: normalizedFile,
263
- line: getLineNumber(cleaned, match.index),
264
- source
265
- });
399
+ addRef(name, getLineNumber(cleaned, match.index), source);
266
400
  }
267
- const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env)\b/g;
401
+ const destructureRegex = /\{([^}]+)\}\s*=\s*(process\.env|import\.meta\.env|Bun\.env)\b/g;
268
402
  for (const match of cleaned.matchAll(destructureRegex)) {
269
403
  const body = match[1];
270
404
  const source = match[2];
@@ -281,14 +415,15 @@ function extractEnvReferences(content, filePath) {
281
415
  if (!name) continue;
282
416
  const leadingWs = part.indexOf(name);
283
417
  const absoluteIdx = bodyStart + partIdx + Math.max(0, leadingWs);
284
- refs.push({
285
- name,
286
- file: normalizedFile,
287
- line: getLineNumber(cleaned, absoluteIdx),
288
- source
289
- });
418
+ addRef(name, getLineNumber(cleaned, absoluteIdx), source);
290
419
  }
291
420
  }
421
+ const denoRegex = /\bDeno\.env\s*\??\.\s*get\s*\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g;
422
+ for (const match of cleaned.matchAll(denoRegex)) {
423
+ const name = match[1];
424
+ if (!name || match.index === void 0) continue;
425
+ addRef(name, getLineNumber(cleaned, match.index), "Deno.env");
426
+ }
292
427
  refs.sort((a, b) => a.line - b.line);
293
428
  return refs;
294
429
  }
@@ -356,12 +491,87 @@ var SENSITIVE_KEYWORDS = [
356
491
  "SERVICE_ROLE",
357
492
  "CREDENTIALS"
358
493
  ];
359
- function detectSecretExposure(name) {
494
+ var PLACEHOLDER_VALUE_PATTERNS = [
495
+ /^your[_-]/i,
496
+ /^my[_-]/i,
497
+ /^change[_-]?me$/i,
498
+ /^replace[_-]?me$/i,
499
+ /^placeholder$/i,
500
+ /^example$/i,
501
+ /^dummy$/i,
502
+ /^test$/i,
503
+ /^todo$/i,
504
+ /^<[^>]+>$/,
505
+ /^\$\{[^}]+\}$/,
506
+ /^[xX*]{4,}$/
507
+ ];
508
+ var PLACEHOLDER_URL_PASSWORDS = /* @__PURE__ */ new Set([
509
+ "password",
510
+ "pass",
511
+ "passwd",
512
+ "postgres",
513
+ "root",
514
+ "admin",
515
+ "changeme",
516
+ "change_me",
517
+ "secret",
518
+ "example",
519
+ "dummy",
520
+ "test",
521
+ "1234",
522
+ "123456",
523
+ "your_password",
524
+ "<password>"
525
+ ]);
526
+ var EXAMPLE_SECRET_PATTERNS = [
527
+ { pattern: /^sk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe live secret key" },
528
+ { pattern: /^rk_live_[A-Za-z0-9]{16,}$/, reason: "Stripe restricted live key" },
529
+ { pattern: /^whsec_[A-Za-z0-9]{16,}$/, reason: "Stripe webhook secret" },
530
+ { pattern: /^gh[pous]_[A-Za-z0-9]{20,}$/, reason: "GitHub access token" },
531
+ { pattern: /^github_pat_[A-Za-z0-9_]{20,}$/, reason: "GitHub fine-grained token" },
532
+ { pattern: /^AKIA[0-9A-Z]{16}$/, reason: "AWS Access Key ID" },
533
+ { pattern: /^sk-(?:proj|ant)-[A-Za-z0-9_-]{20,}$/, reason: "AI provider API key" },
534
+ { pattern: /^sk-[A-Za-z0-9]{32,}$/, reason: "Secret API key (sk-...)" },
535
+ { pattern: /^xox[baprs]-[A-Za-z0-9-]{10,}$/, reason: "Slack token" },
536
+ { pattern: /^AIza[0-9A-Za-z_-]{35}$/, reason: "Google API key" },
537
+ {
538
+ pattern: /^eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}$/,
539
+ reason: "JWT token"
540
+ },
541
+ {
542
+ pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
543
+ reason: "PEM private key"
544
+ }
545
+ ];
546
+ var CONNECTION_URL_PASSWORD_REGEX = /^(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^:\s/]+:([^@\s/]+)@/i;
547
+ function detectExampleSecretLeak(_name, value) {
548
+ const trimmed = value.trim();
549
+ if (!trimmed) return null;
550
+ if (PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(trimmed))) {
551
+ return null;
552
+ }
553
+ for (const { pattern, reason } of EXAMPLE_SECRET_PATTERNS) {
554
+ if (pattern.test(trimmed)) {
555
+ return reason;
556
+ }
557
+ }
558
+ const urlMatch = CONNECTION_URL_PASSWORD_REGEX.exec(trimmed);
559
+ if (urlMatch) {
560
+ const password = urlMatch[1] ?? "";
561
+ if (password && !PLACEHOLDER_URL_PASSWORDS.has(password.toLowerCase()) && !PLACEHOLDER_VALUE_PATTERNS.some((re) => re.test(password))) {
562
+ return "Connection URL with embedded password";
563
+ }
564
+ }
565
+ return null;
566
+ }
567
+ function detectSecretExposure(name, options) {
360
568
  const upper = name.toUpperCase();
361
- const prefix = PUBLIC_ENV_PREFIXES.find((p) => upper.startsWith(p));
569
+ const prefixes = options?.publicPrefixes?.length ? [...PUBLIC_ENV_PREFIXES, ...options.publicPrefixes.map((p) => p.toUpperCase())] : PUBLIC_ENV_PREFIXES;
570
+ const keywords = options?.sensitiveKeywords?.length ? [...SENSITIVE_KEYWORDS, ...options.sensitiveKeywords.map((k) => k.toUpperCase())] : SENSITIVE_KEYWORDS;
571
+ const prefix = prefixes.find((p) => upper.startsWith(p));
362
572
  if (!prefix) return null;
363
573
  const rest = upper.slice(prefix.length);
364
- const matchedKeyword = SENSITIVE_KEYWORDS.find((kw) => rest.includes(kw));
574
+ const matchedKeyword = keywords.find((kw) => rest.includes(kw));
365
575
  if (!matchedKeyword) return null;
366
576
  return { prefix, matchedKeyword };
367
577
  }
@@ -370,7 +580,8 @@ function auditEnv(options = {}) {
370
580
  const envFileName = options.envFile ?? ".env";
371
581
  const exampleFileName = options.exampleFile ?? ".env.example";
372
582
  const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
373
- const { scannedFiles, references } = scanFiles(rootDir);
583
+ const ignoreDirs = options.ignoreDirs?.length ? [...DEFAULT_IGNORE_DIRS, ...options.ignoreDirs] : void 0;
584
+ const { scannedFiles, references } = scanFiles(rootDir, { ignoreDirs });
374
585
  const usedInCode = {};
375
586
  for (const ref of references) {
376
587
  if (!usedInCode[ref.name]) {
@@ -382,6 +593,7 @@ function auditEnv(options = {}) {
382
593
  const parsedExample = parseEnvFile(resolve(rootDir, exampleFileName));
383
594
  let envFileExists = parsedEnv.exists;
384
595
  const localEnvKeys = new Set(parsedEnv.keys);
596
+ const localEnvValues = { ...parsedEnv.values };
385
597
  if (!options.envFile) {
386
598
  const parsedLocal = parseEnvFile(resolve(rootDir, ".env.local"));
387
599
  if (parsedLocal.exists) {
@@ -389,6 +601,7 @@ function auditEnv(options = {}) {
389
601
  }
390
602
  for (const key of parsedLocal.keys) {
391
603
  localEnvKeys.add(key);
604
+ localEnvValues[key] = parsedLocal.values[key] ?? "";
392
605
  }
393
606
  }
394
607
  const exampleKeys = new Set(parsedExample.keys);
@@ -396,6 +609,9 @@ function auditEnv(options = {}) {
396
609
  const codeKeySet = new Set(codeKeys);
397
610
  const missingInEnv = codeKeys.filter((k) => !ignoreSet.has(k) && !localEnvKeys.has(k)).sort();
398
611
  const missingInExample = codeKeys.filter((k) => !ignoreSet.has(k) && !exampleKeys.has(k)).sort();
612
+ const emptyInEnv = codeKeys.filter(
613
+ (k) => !ignoreSet.has(k) && localEnvKeys.has(k) && (localEnvValues[k] ?? "").trim() === ""
614
+ ).sort();
399
615
  const unusedInEnv = parsedEnv.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
400
616
  const unusedInExample = parsedExample.keys.filter((k) => !ignoreSet.has(k) && !codeKeySet.has(k)).sort();
401
617
  const allKnownKeys = /* @__PURE__ */ new Set([
@@ -406,7 +622,10 @@ function auditEnv(options = {}) {
406
622
  const secretExposures = [];
407
623
  for (const key of Array.from(allKnownKeys).sort()) {
408
624
  if (ignoreSet.has(key)) continue;
409
- const hit = detectSecretExposure(key);
625
+ const hit = detectSecretExposure(key, {
626
+ publicPrefixes: options.publicPrefixes,
627
+ sensitiveKeywords: options.sensitiveKeywords
628
+ });
410
629
  if (hit) {
411
630
  secretExposures.push({
412
631
  name: key,
@@ -416,6 +635,19 @@ function auditEnv(options = {}) {
416
635
  });
417
636
  }
418
637
  }
638
+ const exampleSecretLeaks = [];
639
+ for (const key of [...parsedExample.keys].sort()) {
640
+ if (ignoreSet.has(key)) continue;
641
+ const reason = detectExampleSecretLeak(key, parsedExample.values[key] ?? "");
642
+ if (reason) {
643
+ exampleSecretLeaks.push({
644
+ name: key,
645
+ reason,
646
+ file: exampleFileName,
647
+ line: parsedExample.lines[key] ?? 1
648
+ });
649
+ }
650
+ }
419
651
  return {
420
652
  rootDir,
421
653
  scannedFiles,
@@ -424,9 +656,11 @@ function auditEnv(options = {}) {
424
656
  usedInCode,
425
657
  missingInEnv,
426
658
  missingInExample,
659
+ emptyInEnv,
427
660
  unusedInEnv,
428
661
  unusedInExample,
429
662
  secretExposures,
663
+ exampleSecretLeaks,
430
664
  duplicateKeys: {
431
665
  env: parsedEnv.duplicates,
432
666
  example: parsedExample.duplicates
@@ -434,7 +668,99 @@ function auditEnv(options = {}) {
434
668
  };
435
669
  }
436
670
 
671
+ // src/config.ts
672
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
673
+ import { resolve as resolve2 } from "path";
674
+ function toStringArray(val) {
675
+ if (!Array.isArray(val)) return void 0;
676
+ return val.filter((item) => typeof item === "string" && item.trim().length > 0);
677
+ }
678
+ function normalizeConfig(raw) {
679
+ if (!raw || typeof raw !== "object") return {};
680
+ const obj = raw;
681
+ const config = {};
682
+ if (typeof obj.envFile === "string" && obj.envFile.trim()) {
683
+ config.envFile = obj.envFile.trim();
684
+ }
685
+ if (typeof obj.exampleFile === "string" && obj.exampleFile.trim()) {
686
+ config.exampleFile = obj.exampleFile.trim();
687
+ }
688
+ const ignore = toStringArray(obj.ignore);
689
+ if (ignore) config.ignore = ignore;
690
+ const ignoreDirs = toStringArray(obj.ignoreDirs);
691
+ if (ignoreDirs) config.ignoreDirs = ignoreDirs;
692
+ const publicPrefixes = toStringArray(obj.publicPrefixes);
693
+ if (publicPrefixes) config.publicPrefixes = publicPrefixes;
694
+ const sensitiveKeywords = toStringArray(obj.sensitiveKeywords);
695
+ if (sensitiveKeywords) config.sensitiveKeywords = sensitiveKeywords;
696
+ if (typeof obj.strict === "boolean") {
697
+ config.strict = obj.strict;
698
+ }
699
+ return config;
700
+ }
701
+ function loadConfig(rootDir) {
702
+ const rcPath = resolve2(rootDir, ".envdriftrc.json");
703
+ if (existsSync2(rcPath)) {
704
+ try {
705
+ const parsed = JSON.parse(readFileSync3(rcPath, "utf-8"));
706
+ return normalizeConfig(parsed);
707
+ } catch (err) {
708
+ const msg = err instanceof Error ? err.message : String(err);
709
+ throw new Error(`Failed to parse .envdriftrc.json: ${msg}`);
710
+ }
711
+ }
712
+ const pkgPath = resolve2(rootDir, "package.json");
713
+ if (existsSync2(pkgPath)) {
714
+ try {
715
+ const parsed = JSON.parse(readFileSync3(pkgPath, "utf-8"));
716
+ if (parsed && typeof parsed === "object" && parsed["env-drift"]) {
717
+ return normalizeConfig(parsed["env-drift"]);
718
+ }
719
+ } catch {
720
+ }
721
+ }
722
+ return {};
723
+ }
724
+
725
+ // src/diff.ts
726
+ import { resolve as resolve3 } from "path";
727
+ function diffEnvFiles(fileA, fileB, options = {}) {
728
+ const rootDir = resolve3(options.rootDir ?? process.cwd());
729
+ const ignoreSet = /* @__PURE__ */ new Set([...BUILTIN_ENV_VARS, ...options.ignore ?? []]);
730
+ const parsedA = parseEnvFile(resolve3(rootDir, fileA));
731
+ const parsedB = parseEnvFile(resolve3(rootDir, fileB));
732
+ const keysA = parsedA.keys.filter((k) => !ignoreSet.has(k));
733
+ const keysB = parsedB.keys.filter((k) => !ignoreSet.has(k));
734
+ const setA = new Set(keysA);
735
+ const setB = new Set(keysB);
736
+ const onlyInA = keysA.filter((k) => !setB.has(k)).sort();
737
+ const onlyInB = keysB.filter((k) => !setA.has(k)).sort();
738
+ const inBoth = keysA.filter((k) => setB.has(k)).sort();
739
+ const emptyInA = keysA.filter((k) => (parsedA.values[k] ?? "").trim() === "").sort();
740
+ const emptyInB = keysB.filter((k) => (parsedB.values[k] ?? "").trim() === "").sort();
741
+ return {
742
+ fileA,
743
+ fileB,
744
+ fileAExists: parsedA.exists,
745
+ fileBExists: parsedB.exists,
746
+ onlyInA,
747
+ onlyInB,
748
+ inBoth,
749
+ emptyInA,
750
+ emptyInB
751
+ };
752
+ }
753
+ function hasDiffIssues(diff, options = {}) {
754
+ if (!diff.fileAExists || !diff.fileBExists) return true;
755
+ if (diff.onlyInA.length > 0 || diff.onlyInB.length > 0) return true;
756
+ if (options.strict && (diff.emptyInA.length > 0 || diff.emptyInB.length > 0)) {
757
+ return true;
758
+ }
759
+ return false;
760
+ }
761
+
437
762
  // src/reporter.ts
763
+ import { relative as relative2 } from "path";
438
764
  import pc from "picocolors";
439
765
  function formatRefs(refs) {
440
766
  if (!refs || refs.length === 0) return "";
@@ -444,7 +770,12 @@ function formatRefs(refs) {
444
770
  }
445
771
  function hasBlockingIssues(result, options = {}) {
446
772
  const checkMissingInEnv = options.requireEnvFile ? true : result.envFileExists;
447
- return checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0;
773
+ const baseBlocking = checkMissingInEnv && result.missingInEnv.length > 0 || result.missingInExample.length > 0 || result.secretExposures.length > 0 || result.exampleSecretLeaks.length > 0;
774
+ if (baseBlocking) return true;
775
+ if (options.strict) {
776
+ return result.emptyInEnv.length > 0 || result.unusedInEnv.length > 0 || result.unusedInExample.length > 0 || result.duplicateKeys.env.length > 0 || result.duplicateKeys.example.length > 0;
777
+ }
778
+ return false;
448
779
  }
449
780
  function formatAuditReport(result, options = {}) {
450
781
  const envFile = options.envFile ?? ".env";
@@ -458,7 +789,7 @@ function formatAuditReport(result, options = {}) {
458
789
  )}`
459
790
  );
460
791
  lines.push("");
461
- const totalIssues = result.secretExposures.length + (skipMissingInEnv ? 0 : result.missingInEnv.length) + result.missingInExample.length + result.unusedInEnv.length + result.unusedInExample.length + result.duplicateKeys.env.length + result.duplicateKeys.example.length;
792
+ const totalIssues = result.secretExposures.length + result.exampleSecretLeaks.length + (skipMissingInEnv ? 0 : result.missingInEnv.length) + result.missingInExample.length + result.emptyInEnv.length + result.unusedInEnv.length + result.unusedInExample.length + result.duplicateKeys.env.length + result.duplicateKeys.example.length;
462
793
  if (totalIssues === 0) {
463
794
  lines.push(pc.green("\u2714 No environment drift detected. Everything is in sync!"));
464
795
  if (skipMissingInEnv && result.missingInEnv.length > 0) {
@@ -480,6 +811,19 @@ function formatAuditReport(result, options = {}) {
480
811
  }
481
812
  lines.push("");
482
813
  }
814
+ if (result.exampleSecretLeaks.length > 0) {
815
+ lines.push(
816
+ pc.bold(pc.red(`\u2716 Possible Real Secret in ${exampleFile} (${result.exampleSecretLeaks.length})`))
817
+ );
818
+ for (const item of result.exampleSecretLeaks) {
819
+ lines.push(
820
+ ` ${pc.red("\u2022")} ${pc.bold(item.name)} ${pc.dim(
821
+ `(${item.reason}) \u2190 ${item.file}:${item.line}`
822
+ )}`
823
+ );
824
+ }
825
+ lines.push("");
826
+ }
483
827
  if (!skipMissingInEnv && result.missingInEnv.length > 0) {
484
828
  lines.push(pc.bold(pc.red(`\u2716 Missing in ${envFile} (${result.missingInEnv.length})`)));
485
829
  for (const key of result.missingInEnv) {
@@ -499,6 +843,13 @@ function formatAuditReport(result, options = {}) {
499
843
  }
500
844
  lines.push("");
501
845
  }
846
+ if (result.emptyInEnv.length > 0) {
847
+ lines.push(pc.bold(pc.yellow(`\u26A0 Empty Value in ${envFile} (${result.emptyInEnv.length})`)));
848
+ for (const key of result.emptyInEnv) {
849
+ lines.push(` ${pc.yellow("\u2022")} ${key}${formatRefs(result.usedInCode[key])}`);
850
+ }
851
+ lines.push("");
852
+ }
502
853
  if (result.unusedInEnv.length > 0) {
503
854
  lines.push(pc.bold(pc.cyan(`\u25CB Unused in ${envFile} (${result.unusedInEnv.length})`)));
504
855
  for (const key of result.unusedInEnv) {
@@ -531,10 +882,285 @@ function formatAuditReport(result, options = {}) {
531
882
  }
532
883
  return lines.join("\n");
533
884
  }
885
+ function escapeGitHubData(value) {
886
+ return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
887
+ }
888
+ function escapeGitHubProperty(value) {
889
+ return escapeGitHubData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
890
+ }
891
+ function buildAnnotation(level, title, message, file, line) {
892
+ const props = [];
893
+ if (file) props.push(`file=${escapeGitHubProperty(file)}`);
894
+ if (line !== void 0) props.push(`line=${line}`);
895
+ props.push(`title=${escapeGitHubProperty(title)}`);
896
+ return `::${level} ${props.join(",")}::${escapeGitHubData(message)}`;
897
+ }
898
+ function formatGitHubAnnotations(result, options = {}) {
899
+ const envFile = options.envFile ?? ".env";
900
+ const exampleFile = options.exampleFile ?? ".env.example";
901
+ const skipMissingInEnv = Boolean(options.ci && !result.envFileExists);
902
+ const lines = [];
903
+ for (const item of result.secretExposures) {
904
+ const firstRef = item.references[0];
905
+ lines.push(
906
+ buildAnnotation(
907
+ "error",
908
+ "Public Secret Exposure",
909
+ `${item.name} uses client-exposed prefix "${item.prefix}" with sensitive keyword "${item.matchedKeyword}"`,
910
+ firstRef?.file,
911
+ firstRef?.line
912
+ )
913
+ );
914
+ }
915
+ for (const leak of result.exampleSecretLeaks) {
916
+ lines.push(
917
+ buildAnnotation(
918
+ "error",
919
+ `Secret Leak in ${exampleFile}`,
920
+ `${leak.name} appears to contain a real secret (${leak.reason}). Replace it with an empty placeholder.`,
921
+ leak.file,
922
+ leak.line
923
+ )
924
+ );
925
+ }
926
+ if (!skipMissingInEnv) {
927
+ for (const key of result.missingInEnv) {
928
+ const firstRef = result.usedInCode[key]?.[0];
929
+ lines.push(
930
+ buildAnnotation(
931
+ "error",
932
+ `Missing in ${envFile}`,
933
+ `Environment variable ${key} is referenced in code but missing in ${envFile}`,
934
+ firstRef?.file,
935
+ firstRef?.line
936
+ )
937
+ );
938
+ }
939
+ }
940
+ for (const key of result.missingInExample) {
941
+ const firstRef = result.usedInCode[key]?.[0];
942
+ lines.push(
943
+ buildAnnotation(
944
+ "error",
945
+ `Missing in ${exampleFile}`,
946
+ `Environment variable ${key} is referenced in code but missing in ${exampleFile}. Run \`env-drift --sync\` to update.`,
947
+ firstRef?.file,
948
+ firstRef?.line
949
+ )
950
+ );
951
+ }
952
+ for (const key of result.emptyInEnv) {
953
+ const firstRef = result.usedInCode[key]?.[0];
954
+ lines.push(
955
+ buildAnnotation(
956
+ "warning",
957
+ `Empty Value in ${envFile}`,
958
+ `Environment variable ${key} is defined in ${envFile} with an empty value`,
959
+ firstRef?.file,
960
+ firstRef?.line
961
+ )
962
+ );
963
+ }
964
+ for (const key of result.unusedInEnv) {
965
+ lines.push(
966
+ buildAnnotation(
967
+ "warning",
968
+ `Unused in ${envFile}`,
969
+ `Environment variable ${key} is defined in ${envFile} but not referenced in code`,
970
+ envFile
971
+ )
972
+ );
973
+ }
974
+ for (const key of result.unusedInExample) {
975
+ lines.push(
976
+ buildAnnotation(
977
+ "warning",
978
+ `Unused in ${exampleFile}`,
979
+ `Environment variable ${key} is defined in ${exampleFile} but not referenced in code`,
980
+ exampleFile
981
+ )
982
+ );
983
+ }
984
+ for (const key of result.duplicateKeys.env) {
985
+ lines.push(
986
+ buildAnnotation(
987
+ "warning",
988
+ `Duplicate Key in ${envFile}`,
989
+ `Environment variable ${key} is defined multiple times in ${envFile}`,
990
+ envFile
991
+ )
992
+ );
993
+ }
994
+ for (const key of result.duplicateKeys.example) {
995
+ lines.push(
996
+ buildAnnotation(
997
+ "warning",
998
+ `Duplicate Key in ${exampleFile}`,
999
+ `Environment variable ${key} is defined multiple times in ${exampleFile}`,
1000
+ exampleFile
1001
+ )
1002
+ );
1003
+ }
1004
+ return lines.join("\n");
1005
+ }
1006
+ function formatDiffReport(diff) {
1007
+ const lines = [];
1008
+ lines.push("");
1009
+ lines.push(
1010
+ `${pc.bold(pc.cyan("env-drift diff"))} ${pc.dim(`\u2014 ${diff.fileA} \u2194 ${diff.fileB}`)}`
1011
+ );
1012
+ lines.push("");
1013
+ if (!diff.fileAExists) {
1014
+ lines.push(pc.red(`\u2716 File not found: ${diff.fileA}`));
1015
+ }
1016
+ if (!diff.fileBExists) {
1017
+ lines.push(pc.red(`\u2716 File not found: ${diff.fileB}`));
1018
+ }
1019
+ if (!diff.fileAExists || !diff.fileBExists) {
1020
+ lines.push("");
1021
+ return lines.join("\n");
1022
+ }
1023
+ const totalIssues = diff.onlyInA.length + diff.onlyInB.length + diff.emptyInA.length + diff.emptyInB.length;
1024
+ if (totalIssues === 0) {
1025
+ lines.push(
1026
+ pc.green(
1027
+ `\u2714 No drift between ${diff.fileA} and ${diff.fileB} (${diff.inBoth.length} shared key${diff.inBoth.length === 1 ? "" : "s"}).`
1028
+ )
1029
+ );
1030
+ lines.push("");
1031
+ return lines.join("\n");
1032
+ }
1033
+ if (diff.onlyInA.length > 0) {
1034
+ lines.push(
1035
+ pc.bold(pc.red(`\u2716 Only in ${diff.fileA} (missing in ${diff.fileB}) (${diff.onlyInA.length})`))
1036
+ );
1037
+ for (const key of diff.onlyInA) {
1038
+ lines.push(` ${pc.red("\u2022")} ${key}`);
1039
+ }
1040
+ lines.push("");
1041
+ }
1042
+ if (diff.onlyInB.length > 0) {
1043
+ lines.push(
1044
+ pc.bold(pc.red(`\u2716 Only in ${diff.fileB} (missing in ${diff.fileA}) (${diff.onlyInB.length})`))
1045
+ );
1046
+ for (const key of diff.onlyInB) {
1047
+ lines.push(` ${pc.red("\u2022")} ${key}`);
1048
+ }
1049
+ lines.push("");
1050
+ }
1051
+ if (diff.emptyInA.length > 0) {
1052
+ lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileA} (${diff.emptyInA.length})`)));
1053
+ for (const key of diff.emptyInA) {
1054
+ lines.push(` ${pc.yellow("\u2022")} ${key}`);
1055
+ }
1056
+ lines.push("");
1057
+ }
1058
+ if (diff.emptyInB.length > 0) {
1059
+ lines.push(pc.bold(pc.yellow(`\u26A0 Empty in ${diff.fileB} (${diff.emptyInB.length})`)));
1060
+ for (const key of diff.emptyInB) {
1061
+ lines.push(` ${pc.yellow("\u2022")} ${key}`);
1062
+ }
1063
+ lines.push("");
1064
+ }
1065
+ lines.push(pc.dim(`Shared keys in both files: ${diff.inBoth.length}`));
1066
+ lines.push("");
1067
+ return lines.join("\n");
1068
+ }
1069
+ function formatWorkspaceReport(wsResult, options = {}) {
1070
+ const lines = [];
1071
+ lines.push("");
1072
+ lines.push(
1073
+ `${pc.bold(pc.cyan("env-drift workspaces"))} ${pc.dim(
1074
+ `\u2014 audited ${wsResult.workspaces.length} workspace${wsResult.workspaces.length === 1 ? "" : "s"}`
1075
+ )}`
1076
+ );
1077
+ if (wsResult.workspaces.length === 0) {
1078
+ lines.push("");
1079
+ lines.push(pc.yellow("\u26A0 No workspaces found in package.json or pnpm-workspace.yaml."));
1080
+ lines.push("");
1081
+ return lines.join("\n");
1082
+ }
1083
+ for (const ws of wsResult.workspaces) {
1084
+ const rel = relative2(wsResult.rootDir, ws.path).replace(/\\/g, "/");
1085
+ lines.push("");
1086
+ lines.push(pc.bold(pc.white(`\u25B8 ${ws.name}`)) + pc.dim(` (${rel})`));
1087
+ lines.push(formatAuditReport(ws.result, options).trimEnd());
1088
+ }
1089
+ lines.push("");
1090
+ return lines.join("\n");
1091
+ }
534
1092
 
535
- // src/typegen.ts
1093
+ // src/schemagen.ts
536
1094
  import { mkdirSync, writeFileSync as writeFileSync2 } from "fs";
537
1095
  import { dirname } from "path";
1096
+ function inferZodRule(key) {
1097
+ if (key === "NODE_ENV") {
1098
+ return 'z.enum(["development", "production", "test"]).default("development")';
1099
+ }
1100
+ if (/(?:^|_)(?:URL|URI|ENDPOINT)$/i.test(key)) {
1101
+ return "z.string().url()";
1102
+ }
1103
+ if (/^(?:PORT|.*_PORT|.*_TIMEOUT|.*_MS|.*_SECONDS)$/i.test(key)) {
1104
+ return "z.coerce.number()";
1105
+ }
1106
+ if (/^(?:ENABLE|DISABLE|IS|HAS|USE)_|_(?:ENABLED|DISABLED)$/i.test(key)) {
1107
+ return "z.coerce.boolean()";
1108
+ }
1109
+ return "z.string().min(1)";
1110
+ }
1111
+ function generateZodSchema(result) {
1112
+ const keys = /* @__PURE__ */ new Set();
1113
+ let hasProcessOrServer = false;
1114
+ let hasImportMeta = false;
1115
+ for (const [key, refs] of Object.entries(result.usedInCode)) {
1116
+ if (BUILTIN_ENV_VARS.has(key)) continue;
1117
+ keys.add(key);
1118
+ for (const ref of refs) {
1119
+ if (ref.source === "import.meta.env") {
1120
+ hasImportMeta = true;
1121
+ } else {
1122
+ hasProcessOrServer = true;
1123
+ }
1124
+ }
1125
+ }
1126
+ for (const key of result.unusedInExample) {
1127
+ if (!BUILTIN_ENV_VARS.has(key)) {
1128
+ keys.add(key);
1129
+ }
1130
+ }
1131
+ const sortedKeys = Array.from(keys).sort();
1132
+ const sourceExpr = hasImportMeta && !hasProcessOrServer ? "import.meta.env" : "process.env";
1133
+ const lines = [
1134
+ "// Auto-generated by env-drift. Customize validators as needed.",
1135
+ 'import { z } from "zod";',
1136
+ "",
1137
+ "export const envSchema = z.object({"
1138
+ ];
1139
+ for (const key of sortedKeys) {
1140
+ lines.push(` ${key}: ${inferZodRule(key)},`);
1141
+ }
1142
+ lines.push("});");
1143
+ lines.push("");
1144
+ lines.push("export type Env = z.infer<typeof envSchema>;");
1145
+ lines.push("");
1146
+ lines.push(`export const env = envSchema.parse(${sourceExpr});`);
1147
+ lines.push("");
1148
+ return lines.join("\n");
1149
+ }
1150
+ function writeZodSchema(outputPath, result) {
1151
+ const content = generateZodSchema(result);
1152
+ mkdirSync(dirname(outputPath), { recursive: true });
1153
+ writeFileSync2(outputPath, content, "utf-8");
1154
+ const uniqueKeys = /* @__PURE__ */ new Set([
1155
+ ...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
1156
+ ...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
1157
+ ]);
1158
+ return { outputPath, count: uniqueKeys.size };
1159
+ }
1160
+
1161
+ // src/typegen.ts
1162
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
1163
+ import { dirname as dirname2 } from "path";
538
1164
  function generateEnvTypes(result) {
539
1165
  const processKeys = /* @__PURE__ */ new Set();
540
1166
  const importMetaKeys = /* @__PURE__ */ new Set();
@@ -589,8 +1215,8 @@ function generateEnvTypes(result) {
589
1215
  }
590
1216
  function writeEnvTypes(outputPath, result) {
591
1217
  const content = generateEnvTypes(result);
592
- mkdirSync(dirname(outputPath), { recursive: true });
593
- writeFileSync2(outputPath, content, "utf-8");
1218
+ mkdirSync2(dirname2(outputPath), { recursive: true });
1219
+ writeFileSync3(outputPath, content, "utf-8");
594
1220
  const uniqueKeys = /* @__PURE__ */ new Set([
595
1221
  ...Object.keys(result.usedInCode).filter((k) => !BUILTIN_ENV_VARS.has(k)),
596
1222
  ...result.unusedInExample.filter((k) => !BUILTIN_ENV_VARS.has(k))
@@ -598,6 +1224,167 @@ function writeEnvTypes(outputPath, result) {
598
1224
  return { outputPath, count: uniqueKeys.size };
599
1225
  }
600
1226
 
1227
+ // src/workspaces.ts
1228
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
1229
+ import { join as join2, relative as relative3, resolve as resolve4 } from "path";
1230
+ function readWorkspacePatterns(rootDir) {
1231
+ const pkgPath = resolve4(rootDir, "package.json");
1232
+ if (existsSync3(pkgPath)) {
1233
+ try {
1234
+ const parsed = JSON.parse(readFileSync4(pkgPath, "utf-8"));
1235
+ if (Array.isArray(parsed.workspaces)) {
1236
+ return parsed.workspaces.filter((p) => typeof p === "string");
1237
+ }
1238
+ if (parsed.workspaces && typeof parsed.workspaces === "object" && Array.isArray(parsed.workspaces.packages)) {
1239
+ return parsed.workspaces.packages.filter((p) => typeof p === "string");
1240
+ }
1241
+ } catch {
1242
+ }
1243
+ }
1244
+ const pnpmPath = resolve4(rootDir, "pnpm-workspace.yaml");
1245
+ if (existsSync3(pnpmPath)) {
1246
+ const content = readFileSync4(pnpmPath, "utf-8");
1247
+ const patterns = [];
1248
+ let inPackages = false;
1249
+ for (const rawLine of content.split(/\r?\n/)) {
1250
+ const line = rawLine.trim();
1251
+ if (!line || line.startsWith("#")) continue;
1252
+ if (/^packages\s*:/.test(line)) {
1253
+ inPackages = true;
1254
+ continue;
1255
+ }
1256
+ if (inPackages) {
1257
+ if (line.startsWith("-")) {
1258
+ const item = line.slice(1).trim().replace(/^["']|["']$/g, "");
1259
+ if (item) patterns.push(item);
1260
+ } else if (/^[A-Za-z0-9_-]+\s*:/.test(line)) {
1261
+ inPackages = false;
1262
+ }
1263
+ }
1264
+ }
1265
+ if (patterns.length > 0) return patterns;
1266
+ }
1267
+ return [];
1268
+ }
1269
+ function expandPattern(rootDir, pattern) {
1270
+ const cleaned = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
1271
+ const segments = cleaned.split("/").filter(Boolean);
1272
+ let currentDirs = [rootDir];
1273
+ for (const seg of segments) {
1274
+ const nextDirs = [];
1275
+ if (seg === "*" || seg === "**") {
1276
+ for (const dir of currentDirs) {
1277
+ if (!existsSync3(dir)) continue;
1278
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1279
+ if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
1280
+ nextDirs.push(join2(dir, entry.name));
1281
+ }
1282
+ }
1283
+ }
1284
+ } else if (seg.includes("*")) {
1285
+ const regex = new RegExp(
1286
+ "^" + seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"
1287
+ );
1288
+ for (const dir of currentDirs) {
1289
+ if (!existsSync3(dir)) continue;
1290
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1291
+ if (entry.isDirectory() && regex.test(entry.name)) {
1292
+ nextDirs.push(join2(dir, entry.name));
1293
+ }
1294
+ }
1295
+ }
1296
+ } else {
1297
+ for (const dir of currentDirs) {
1298
+ const candidate = join2(dir, seg);
1299
+ if (existsSync3(candidate) && statSync2(candidate).isDirectory()) {
1300
+ nextDirs.push(candidate);
1301
+ }
1302
+ }
1303
+ }
1304
+ currentDirs = nextDirs;
1305
+ }
1306
+ return currentDirs;
1307
+ }
1308
+ function discoverWorkspaces(rootDir) {
1309
+ const resolvedRoot = resolve4(rootDir);
1310
+ const patterns = readWorkspacePatterns(resolvedRoot);
1311
+ if (patterns.length === 0) return [];
1312
+ const included = /* @__PURE__ */ new Set();
1313
+ const excluded = /* @__PURE__ */ new Set();
1314
+ for (const pattern of patterns) {
1315
+ if (pattern.startsWith("!")) {
1316
+ for (const dir of expandPattern(resolvedRoot, pattern.slice(1))) {
1317
+ excluded.add(resolve4(dir));
1318
+ }
1319
+ } else {
1320
+ for (const dir of expandPattern(resolvedRoot, pattern)) {
1321
+ included.add(resolve4(dir));
1322
+ }
1323
+ }
1324
+ }
1325
+ const results = [];
1326
+ for (const dir of included) {
1327
+ if (excluded.has(dir)) continue;
1328
+ const relPath = relative3(resolvedRoot, dir).replace(/\\/g, "/");
1329
+ let name = relPath;
1330
+ const pkgPath = join2(dir, "package.json");
1331
+ if (existsSync3(pkgPath)) {
1332
+ try {
1333
+ const pkg = JSON.parse(readFileSync4(pkgPath, "utf-8"));
1334
+ if (typeof pkg.name === "string" && pkg.name.trim()) {
1335
+ name = pkg.name.trim();
1336
+ }
1337
+ } catch {
1338
+ }
1339
+ }
1340
+ results.push({ name, path: dir });
1341
+ }
1342
+ results.sort((a, b) => a.path.localeCompare(b.path));
1343
+ return results;
1344
+ }
1345
+ function auditWorkspaces(rootDir, options = {}) {
1346
+ const resolvedRoot = resolve4(rootDir);
1347
+ const discovered = discoverWorkspaces(resolvedRoot);
1348
+ const workspaces = [];
1349
+ for (const ws of discovered) {
1350
+ const wsConfig = loadConfig(ws.path);
1351
+ const mergedIgnore = [
1352
+ ...options.ignore ?? [],
1353
+ ...wsConfig.ignore ?? []
1354
+ ];
1355
+ const mergedIgnoreDirs = [
1356
+ ...options.ignoreDirs ?? [],
1357
+ ...wsConfig.ignoreDirs ?? []
1358
+ ];
1359
+ const mergedPrefixes = [
1360
+ ...options.publicPrefixes ?? [],
1361
+ ...wsConfig.publicPrefixes ?? []
1362
+ ];
1363
+ const mergedKeywords = [
1364
+ ...options.sensitiveKeywords ?? [],
1365
+ ...wsConfig.sensitiveKeywords ?? []
1366
+ ];
1367
+ const result = auditEnv({
1368
+ rootDir: ws.path,
1369
+ envFile: options.envFile ?? wsConfig.envFile,
1370
+ exampleFile: options.exampleFile ?? wsConfig.exampleFile,
1371
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
1372
+ ignoreDirs: mergedIgnoreDirs.length > 0 ? mergedIgnoreDirs : void 0,
1373
+ publicPrefixes: mergedPrefixes.length > 0 ? mergedPrefixes : void 0,
1374
+ sensitiveKeywords: mergedKeywords.length > 0 ? mergedKeywords : void 0
1375
+ });
1376
+ workspaces.push({
1377
+ name: ws.name,
1378
+ path: ws.path,
1379
+ result
1380
+ });
1381
+ }
1382
+ return {
1383
+ rootDir: resolvedRoot,
1384
+ workspaces
1385
+ };
1386
+ }
1387
+
601
1388
  // src/cli.ts
602
1389
  var VERSION = package_default.version;
603
1390
  var HELP_TEXT = `
@@ -605,22 +1392,30 @@ ${pc2.bold(pc2.cyan("@subramanyaks/env-drift"))} v${VERSION} \u2014 Detect envir
605
1392
 
606
1393
  ${pc2.bold("Usage:")}
607
1394
  npx @subramanyaks/env-drift [options]
1395
+ npx @subramanyaks/env-drift --diff <fileA> <fileB> [options]
608
1396
 
609
1397
  ${pc2.bold("Options:")}
610
- -d, --dir <path> Project directory to scan (default: ".")
611
- --env <file> Local env file name (default: ".env")
612
- --example <file> Example env file name (default: ".env.example")
613
- --ignore <vars> Comma-separated env var names to ignore
614
- --sync Safely append missing keys to .env.example as KEY=
615
- --types Generate env.d.ts for detected env variables
616
- --types-out <path> Output path for --types (default: "env.d.ts")
617
- --ci Exit with code 1 if missing vars or secret leaks are found
618
- --json Output audit results as JSON
619
- -v, --version Show version
620
- -h, --help Show this help message
1398
+ -d, --dir <path> Project directory to scan (default: ".")
1399
+ --env <file> Local env file name (default: ".env")
1400
+ --example <file> Example env file name (default: ".env.example")
1401
+ --ignore <vars> Comma-separated env var names to ignore
1402
+ --sync Safely append missing keys to .env.example as KEY=
1403
+ --types Generate env.d.ts for detected env variables
1404
+ --types-out <path> Output path for --types (default: "env.d.ts")
1405
+ --schema Generate Zod validation schema (env.schema.ts)
1406
+ --schema-out <path> Output path for --schema (default: "env.schema.ts")
1407
+ --diff Compare keys across two env files (e.g. --diff .env.staging .env.production)
1408
+ --workspaces Audit all monorepo workspaces (package.json / pnpm-workspace.yaml)
1409
+ --ci Exit with code 1 if blocking issues are found
1410
+ --strict In --ci mode, also fail on empty values, unused keys, and duplicates
1411
+ --format <type> Output format: text, json, or github (default: "text")
1412
+ --json Output audit results as JSON (alias for --format json)
1413
+ -v, --version Show version
1414
+ -h, --help Show this help message
621
1415
  `;
622
1416
  function runCli(argv = process.argv.slice(2)) {
623
1417
  let values;
1418
+ let positionals;
624
1419
  try {
625
1420
  const parsed = parseArgs({
626
1421
  args: argv,
@@ -632,14 +1427,22 @@ function runCli(argv = process.argv.slice(2)) {
632
1427
  sync: { type: "boolean", default: false },
633
1428
  types: { type: "boolean", default: false },
634
1429
  "types-out": { type: "string" },
1430
+ schema: { type: "boolean", default: false },
1431
+ "schema-out": { type: "string" },
1432
+ diff: { type: "boolean", default: false },
1433
+ workspaces: { type: "boolean", default: false },
635
1434
  ci: { type: "boolean", default: false },
1435
+ strict: { type: "boolean", default: false },
1436
+ format: { type: "string" },
636
1437
  json: { type: "boolean", default: false },
637
1438
  version: { type: "boolean", short: "v", default: false },
638
1439
  help: { type: "boolean", short: "h", default: false }
639
1440
  },
1441
+ allowPositionals: true,
640
1442
  strict: true
641
1443
  });
642
1444
  values = parsed.values;
1445
+ positionals = parsed.positionals;
643
1446
  } catch (err) {
644
1447
  const msg = err instanceof Error ? err.message : String(err);
645
1448
  console.error(pc2.red(`Error: ${msg}`));
@@ -654,24 +1457,101 @@ function runCli(argv = process.argv.slice(2)) {
654
1457
  console.log(VERSION);
655
1458
  return 0;
656
1459
  }
657
- const rootDir = resolve2(typeof values.dir === "string" ? values.dir : process.cwd());
658
- const envFile = typeof values.env === "string" ? values.env : void 0;
659
- const exampleFile = typeof values.example === "string" ? values.example : ".env.example";
660
- const ignore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
1460
+ const format = values.json ? "json" : typeof values.format === "string" ? values.format.toLowerCase() : "text";
1461
+ if (format !== "text" && format !== "json" && format !== "github") {
1462
+ console.error(
1463
+ pc2.red(`Error: Invalid --format "${format}". Expected "text", "json", or "github".`)
1464
+ );
1465
+ return 1;
1466
+ }
1467
+ const rootDir = resolve5(typeof values.dir === "string" ? values.dir : process.cwd());
1468
+ let fileConfig;
1469
+ try {
1470
+ fileConfig = loadConfig(rootDir);
1471
+ } catch (err) {
1472
+ const msg = err instanceof Error ? err.message : String(err);
1473
+ console.error(pc2.red(`Error: ${msg}`));
1474
+ return 1;
1475
+ }
1476
+ const envFile = typeof values.env === "string" ? values.env : fileConfig.envFile;
1477
+ const exampleFile = typeof values.example === "string" ? values.example : fileConfig.exampleFile ?? ".env.example";
1478
+ const strict = Boolean(values.strict || fileConfig.strict);
1479
+ const cliIgnore = typeof values.ignore === "string" ? values.ignore.split(",").map((s) => s.trim()).filter(Boolean) : [];
1480
+ const mergedIgnore = [...fileConfig.ignore ?? [], ...cliIgnore];
1481
+ if (values.diff) {
1482
+ if (positionals.length < 2) {
1483
+ console.error(
1484
+ pc2.red("Error: --diff requires two file paths (e.g. `env-drift --diff .env.staging .env.production`).")
1485
+ );
1486
+ return 1;
1487
+ }
1488
+ const diffResult = diffEnvFiles(positionals[0], positionals[1], {
1489
+ rootDir,
1490
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0
1491
+ });
1492
+ if (format === "json") {
1493
+ console.log(JSON.stringify(diffResult, null, 2));
1494
+ } else {
1495
+ console.log(formatDiffReport(diffResult));
1496
+ }
1497
+ if (values.ci && hasDiffIssues(diffResult, { strict })) {
1498
+ return 1;
1499
+ }
1500
+ return 0;
1501
+ }
1502
+ if (values.workspaces) {
1503
+ const wsResult = auditWorkspaces(rootDir, {
1504
+ envFile,
1505
+ exampleFile,
1506
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
1507
+ ignoreDirs: fileConfig.ignoreDirs,
1508
+ publicPrefixes: fileConfig.publicPrefixes,
1509
+ sensitiveKeywords: fileConfig.sensitiveKeywords
1510
+ });
1511
+ if (format === "json") {
1512
+ console.log(JSON.stringify(wsResult, null, 2));
1513
+ } else if (format === "github") {
1514
+ const blocks = wsResult.workspaces.map(
1515
+ (ws) => formatGitHubAnnotations(ws.result, {
1516
+ envFile: envFile ?? ".env",
1517
+ exampleFile,
1518
+ ci: Boolean(values.ci)
1519
+ })
1520
+ ).filter(Boolean);
1521
+ if (blocks.length > 0) {
1522
+ console.log(blocks.join("\n"));
1523
+ }
1524
+ } else {
1525
+ console.log(
1526
+ formatWorkspaceReport(wsResult, {
1527
+ envFile: envFile ?? ".env",
1528
+ exampleFile,
1529
+ ci: Boolean(values.ci)
1530
+ })
1531
+ );
1532
+ }
1533
+ if (values.ci && wsResult.workspaces.some((ws) => hasBlockingIssues(ws.result, { strict }))) {
1534
+ return 1;
1535
+ }
1536
+ return 0;
1537
+ }
661
1538
  const result = auditEnv({
662
1539
  rootDir,
663
1540
  envFile,
664
1541
  exampleFile,
665
- ignore
1542
+ ignore: mergedIgnore.length > 0 ? mergedIgnore : void 0,
1543
+ ignoreDirs: fileConfig.ignoreDirs,
1544
+ publicPrefixes: fileConfig.publicPrefixes,
1545
+ sensitiveKeywords: fileConfig.sensitiveKeywords
666
1546
  });
667
1547
  if (values.sync && result.missingInExample.length > 0) {
668
- const examplePath = resolve2(rootDir, exampleFile);
1548
+ const examplePath = resolve5(rootDir, exampleFile);
669
1549
  const synced = syncEnvExample(examplePath, result.missingInExample);
670
1550
  if (synced.added.length > 0) {
671
1551
  const addedSet = new Set(synced.added);
672
1552
  result.missingInExample = result.missingInExample.filter((k) => !addedSet.has(k));
673
1553
  result.exampleFileExists = true;
674
- if (!values.json) {
1554
+ if (format === "text") {
675
1555
  const action = synced.created ? "Created" : "Updated";
676
1556
  console.log(
677
1557
  pc2.green(`\u2714 ${action} ${exampleFile} with ${synced.added.length} key(s): ${synced.added.join(", ")}`)
@@ -681,14 +1561,31 @@ function runCli(argv = process.argv.slice(2)) {
681
1561
  }
682
1562
  if (values.types || typeof values["types-out"] === "string") {
683
1563
  const outFile = typeof values["types-out"] === "string" ? values["types-out"] : "env.d.ts";
684
- const outputPath = resolve2(rootDir, outFile);
1564
+ const outputPath = resolve5(rootDir, outFile);
685
1565
  const generated = writeEnvTypes(outputPath, result);
686
- if (!values.json) {
1566
+ if (format === "text") {
687
1567
  console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
688
1568
  }
689
1569
  }
690
- if (values.json) {
1570
+ if (values.schema || typeof values["schema-out"] === "string") {
1571
+ const outFile = typeof values["schema-out"] === "string" ? values["schema-out"] : "env.schema.ts";
1572
+ const outputPath = resolve5(rootDir, outFile);
1573
+ const generated = writeZodSchema(outputPath, result);
1574
+ if (format === "text") {
1575
+ console.log(pc2.green(`\u2714 Generated ${outFile} (${generated.count} env var(s))`));
1576
+ }
1577
+ }
1578
+ if (format === "json") {
691
1579
  console.log(JSON.stringify(result, null, 2));
1580
+ } else if (format === "github") {
1581
+ const annotations = formatGitHubAnnotations(result, {
1582
+ envFile: envFile ?? ".env",
1583
+ exampleFile,
1584
+ ci: Boolean(values.ci)
1585
+ });
1586
+ if (annotations) {
1587
+ console.log(annotations);
1588
+ }
692
1589
  } else {
693
1590
  console.log(
694
1591
  formatAuditReport(result, {
@@ -698,7 +1595,7 @@ function runCli(argv = process.argv.slice(2)) {
698
1595
  })
699
1596
  );
700
1597
  }
701
- if (values.ci && hasBlockingIssues(result)) {
1598
+ if (values.ci && hasBlockingIssues(result, { strict })) {
702
1599
  return 1;
703
1600
  }
704
1601
  return 0;