@pavol-baker/envaudit 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.
package/src/cli.js ADDED
@@ -0,0 +1,187 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { audit } from './analyze.js';
3
+ import { formatGithub, formatJson, formatPretty, makeColors, shouldUseColor } from './report.js';
4
+ import { applySync, planSync } from './sync.js';
5
+
6
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
7
+
8
+ const HELP = `
9
+ envaudit ${VERSION} - catch environment variable drift before it breaks prod
10
+
11
+ Usage
12
+ envaudit [check] [dir] Audit code against .env.example (default command)
13
+ envaudit sync [dir] Add undocumented variables to .env.example
14
+ envaudit list [dir] List every env var the code reads, and where
15
+
16
+ Options
17
+ -e, --example <file> Use this example file (disables monorepo detection)
18
+ --env <file> Local env file to compare against (default: .env)
19
+ --strict Also fail on unused / duplicate variables
20
+ --ignore-var <names> Never report these vars (comma-separated, globs ok: AWS_*)
21
+ --no-builtins Also report OS/CI/framework vars like NODE_ENV, CI, HOME
22
+ -f, --format <fmt> pretty | json | github (auto: github on GitHub Actions)
23
+ --json Shortcut for --format json
24
+ -v, --verbose Show every location, not just the first two
25
+ --no-color Disable colors (NO_COLOR is respected too)
26
+
27
+ Sync options
28
+ --prune Also remove unused variables from the example file
29
+ --dry-run Show what would change without writing
30
+
31
+ Exit codes
32
+ 0 everything is in sync
33
+ 1 problems found (undocumented vars, leaked secrets, committed .env...)
34
+ 2 usage or runtime error
35
+
36
+ Config: envaudit.config.json, .envauditrc.json, or "envaudit" in package.json
37
+ Docs: https://github.com/pavol-baker/envaudit
38
+ `;
39
+
40
+ export function parseArgs(argv) {
41
+ const opts = { command: 'check', dir: '.', ignoreVars: [], color: undefined };
42
+ const positional = [];
43
+ const take = (i, flag) => {
44
+ if (i + 1 >= argv.length || argv[i + 1].startsWith('-')) throw new UsageError(`${flag} needs a value`);
45
+ return argv[i + 1];
46
+ };
47
+ for (let i = 0; i < argv.length; i++) {
48
+ let a = argv[i];
49
+ let inline;
50
+ if (a.startsWith('--') && a.includes('=')) [a, inline] = [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)];
51
+ const val = (flag) => {
52
+ if (inline !== undefined) return inline;
53
+ const v = take(i, flag);
54
+ i++;
55
+ return v;
56
+ };
57
+ switch (a) {
58
+ case '-h': case '--help': opts.help = true; break;
59
+ case '-V': case '--version': opts.version = true; break;
60
+ case '-e': case '--example': opts.example = val(a); break;
61
+ case '--env': opts.env = val(a); break;
62
+ case '--strict': opts.strict = true; break;
63
+ case '--ignore-var': opts.ignoreVars.push(...val(a).split(',').map((s) => s.trim()).filter(Boolean)); break;
64
+ case '--no-builtins': opts.builtins = false; break;
65
+ case '-f': case '--format': opts.format = val(a); break;
66
+ case '--json': opts.format = 'json'; break;
67
+ case '-v': case '--verbose': opts.verbose = true; break;
68
+ case '--color': opts.color = true; break;
69
+ case '--no-color': opts.color = false; break;
70
+ case '--prune': opts.prune = true; break;
71
+ case '--dry-run': opts.dryRun = true; break;
72
+ default:
73
+ if (a.startsWith('-')) throw new UsageError(`Unknown option: ${a}`);
74
+ positional.push(a);
75
+ }
76
+ }
77
+ if (positional.length && ['check', 'sync', 'list', 'help'].includes(positional[0])) opts.command = positional.shift();
78
+ if (positional.length > 1) throw new UsageError(`Unexpected argument: ${positional[1]}`);
79
+ if (positional.length) opts.dir = positional[0];
80
+ if (opts.command === 'help') opts.help = true;
81
+ if (opts.format && !['pretty', 'json', 'github'].includes(opts.format)) throw new UsageError(`Unknown format: ${opts.format}`);
82
+ return opts;
83
+ }
84
+
85
+ class UsageError extends Error {}
86
+
87
+ /**
88
+ * @param {string[]} argv
89
+ * @param {{ stdout?: NodeJS.WriteStream, stderr?: NodeJS.WriteStream }} io
90
+ * @returns {number} exit code
91
+ */
92
+ export function main(argv, { stdout = process.stdout, stderr = process.stderr } = {}) {
93
+ let opts;
94
+ try {
95
+ opts = parseArgs(argv);
96
+ } catch (e) {
97
+ stderr.write(`envaudit: ${e.message}\nRun "envaudit --help" for usage.\n`);
98
+ return 2;
99
+ }
100
+ if (opts.help) return stdout.write(HELP.trimStart()), 0;
101
+ if (opts.version) return stdout.write(`${VERSION}\n`), 0;
102
+
103
+ const color = shouldUseColor(stdout, opts.color);
104
+ const c = makeColors(color);
105
+ const format = opts.format ?? (process.env.GITHUB_ACTIONS === 'true' ? 'github' : 'pretty');
106
+
107
+ let result;
108
+ try {
109
+ result = audit(opts.dir, {
110
+ example: opts.example,
111
+ env: opts.env,
112
+ strict: opts.strict,
113
+ builtins: opts.builtins,
114
+ ignoreVars: opts.ignoreVars,
115
+ });
116
+ } catch (e) {
117
+ stderr.write(`envaudit: ${e.message}\n`);
118
+ return 2;
119
+ }
120
+
121
+ if (opts.command === 'list') return list(result, { stdout, format, c });
122
+ if (opts.command === 'sync') return sync(result, { stdout, c, prune: opts.prune, dryRun: opts.dryRun });
123
+
124
+ if (format === 'json') stdout.write(formatJson(result));
125
+ else {
126
+ if (format === 'github') stdout.write(formatGithub(result));
127
+ stdout.write(formatPretty(result, { color, verbose: opts.verbose }));
128
+ }
129
+ return result.ok ? 0 : 1;
130
+ }
131
+
132
+ function list(result, { stdout, format, c }) {
133
+ const rows = [];
134
+ for (const s of result.scopes) {
135
+ const inheritedDocs = result.scopes.filter((t) => t.dir === '' || s.dir.startsWith(t.dir + '/'));
136
+ for (const [name, refs] of s.refs) {
137
+ const documented = s.documented.has(name) || inheritedDocs.some((t) => t.documented.has(name));
138
+ rows.push({ name, scope: s.dir, documented, refs });
139
+ }
140
+ }
141
+ for (const u of result.uncovered) rows.push({ name: u.name, scope: null, documented: false, refs: u.refs });
142
+ rows.sort((a, b) => a.name.localeCompare(b.name) || String(a.scope).localeCompare(String(b.scope)));
143
+
144
+ if (format === 'json') {
145
+ stdout.write(JSON.stringify(rows, null, 2) + '\n');
146
+ return 0;
147
+ }
148
+ if (!rows.length) {
149
+ stdout.write('No environment variable references found.\n');
150
+ return 0;
151
+ }
152
+ const multi = result.scopes.length > 1;
153
+ const w = Math.min(Math.max(...rows.map((r) => r.name.length)) + 2, 40);
154
+ for (const r of rows) {
155
+ const mark = r.documented ? c.green('✔') : c.red('✖');
156
+ const scope = multi ? c.gray(`[${r.scope ?? 'uncovered'}] `) : '';
157
+ const where = r.refs.slice(0, 3).map((l) => `${l.file}:${l.line}`).join(', ');
158
+ const more = r.refs.length > 3 ? c.gray(` +${r.refs.length - 3}`) : '';
159
+ stdout.write(`${mark} ${r.name.padEnd(w)}${scope}${c.gray(where)}${more}\n`);
160
+ }
161
+ const undoc = rows.filter((r) => !r.documented).length;
162
+ stdout.write(`\n${rows.length} variables, ${undoc ? c.red(`${undoc} undocumented`) : c.green('all documented')}\n`);
163
+ return 0;
164
+ }
165
+
166
+ function sync(result, { stdout, c, prune, dryRun }) {
167
+ const changes = planSync(result, { prune });
168
+ if (!changes.length) {
169
+ stdout.write(c.green('✔ Example files are already in sync.\n'));
170
+ return 0;
171
+ }
172
+ for (const ch of changes) {
173
+ stdout.write(`${c.bold(ch.file)}${ch.created ? c.gray(' (new file)') : ''}\n`);
174
+ for (const n of ch.added) stdout.write(` ${c.green('+')} ${n}\n`);
175
+ for (const n of ch.removed) stdout.write(` ${c.red('-')} ${n}\n`);
176
+ }
177
+ if (dryRun) {
178
+ stdout.write(c.gray('\nDry run: nothing was written.\n'));
179
+ return 0;
180
+ }
181
+ applySync(result.root, changes);
182
+ const added = changes.reduce((n, ch) => n + ch.added.length, 0);
183
+ const removed = changes.reduce((n, ch) => n + ch.removed.length, 0);
184
+ stdout.write(c.green(`\n✔ Updated ${changes.length} file${changes.length === 1 ? '' : 's'}: ${added} added, ${removed} removed.\n`));
185
+ if (added) stdout.write(c.gray(' Fill in placeholder values or add a short comment describing each new variable.\n'));
186
+ return 0;
187
+ }
package/src/config.js ADDED
@@ -0,0 +1,110 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ // Variables set by the OS, shells, CI providers and frameworks. Nobody puts
5
+ // these in .env.example, so we never report them as undocumented.
6
+ export const BUILTIN_VARS = [
7
+ // OS / shell
8
+ 'PATH', 'HOME', 'USER', 'USERNAME', 'LOGNAME', 'PWD', 'OLDPWD', 'SHELL', 'TERM', 'LANG',
9
+ 'LC_ALL', 'TZ', 'TMPDIR', 'TEMP', 'TMP', 'HOSTNAME', 'EDITOR', 'VISUAL', 'PAGER',
10
+ 'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMFILES', 'SYSTEMROOT', 'COMSPEC', 'WINDIR',
11
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_RUNTIME_DIR',
12
+ 'NO_COLOR', 'FORCE_COLOR', 'COLORTERM', 'TERM_PROGRAM', 'COLUMNS', 'LINES',
13
+ // runtimes
14
+ 'NODE_ENV', 'NODE_OPTIONS', 'NODE_DEBUG', 'npm_lifecycle_event', 'npm_package_version',
15
+ 'npm_config_user_agent', 'PYTHONPATH', 'VIRTUAL_ENV', 'GOPATH', 'GOROOT', 'CARGO_MANIFEST_DIR',
16
+ 'CARGO_PKG_VERSION', 'CARGO_PKG_NAME', 'CARGO_PKG_AUTHORS', 'CARGO_PKG_DESCRIPTION', 'OUT_DIR',
17
+ 'JAVA_HOME', 'RUBYOPT', 'RAILS_ENV', 'RACK_ENV', 'MIX_ENV',
18
+ // CI
19
+ 'CI', 'GITHUB_ACTIONS', 'GITHUB_SHA', 'GITHUB_REF', 'GITHUB_REPOSITORY', 'GITHUB_WORKSPACE',
20
+ 'GITHUB_RUN_ID', 'GITHUB_EVENT_NAME', 'GITLAB_CI', 'CIRCLECI', 'BUILDKITE',
21
+ 'VERCEL', 'VERCEL_ENV', 'VERCEL_URL', 'NETLIFY', 'RENDER', 'RAILWAY_ENVIRONMENT', 'FLY_APP_NAME',
22
+ // Vite / Astro built-ins on import.meta.env
23
+ 'MODE', 'DEV', 'PROD', 'SSR', 'BASE_URL',
24
+ ];
25
+
26
+ export const CONFIG_FILES = ['envaudit.config.json', '.envauditrc.json', '.envauditrc'];
27
+
28
+ /**
29
+ * @typedef {Object} Config
30
+ * @property {string[]} ignoreVars variable names or globs (e.g. `AWS_*`) to never report
31
+ * @property {string[]} ignoreUnused example vars that are used by libraries, not your code
32
+ * @property {string[]} ignore path globs to skip while scanning
33
+ * @property {string|null} example force a single example file (disables monorepo mode)
34
+ * @property {string} env local env file name to compare against (default `.env`)
35
+ * @property {boolean} strict fail on unused variables too
36
+ * @property {boolean} builtins skip well-known OS/CI/framework variables (default true)
37
+ */
38
+
39
+ /** @returns {Config} */
40
+ export function defaultConfig() {
41
+ return {
42
+ ignoreVars: [],
43
+ ignoreUnused: [],
44
+ ignore: [],
45
+ example: null,
46
+ env: '.env',
47
+ strict: false,
48
+ builtins: true,
49
+ };
50
+ }
51
+
52
+ export function loadConfig(root) {
53
+ const cfg = defaultConfig();
54
+ let fileCfg = null;
55
+ let source = null;
56
+ for (const name of CONFIG_FILES) {
57
+ const p = join(root, name);
58
+ if (existsSync(p)) {
59
+ fileCfg = parseJson(readFileSync(p, 'utf8'), p);
60
+ source = name;
61
+ break;
62
+ }
63
+ }
64
+ if (!fileCfg) {
65
+ const pkgPath = join(root, 'package.json');
66
+ if (existsSync(pkgPath)) {
67
+ try {
68
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
69
+ if (pkg.envaudit) {
70
+ fileCfg = pkg.envaudit;
71
+ source = 'package.json#envaudit';
72
+ }
73
+ } catch {
74
+ /* a broken package.json is not our problem */
75
+ }
76
+ }
77
+ }
78
+ if (fileCfg) Object.assign(cfg, pick(fileCfg));
79
+ return { config: cfg, source };
80
+ }
81
+
82
+ function pick(obj) {
83
+ const out = {};
84
+ for (const k of ['ignoreVars', 'ignoreUnused', 'ignore']) if (Array.isArray(obj[k])) out[k] = obj[k].map(String);
85
+ if (typeof obj.example === 'string') out.example = obj.example;
86
+ if (typeof obj.env === 'string') out.env = obj.env;
87
+ if (typeof obj.strict === 'boolean') out.strict = obj.strict;
88
+ if (typeof obj.builtins === 'boolean') out.builtins = obj.builtins;
89
+ return out;
90
+ }
91
+
92
+ function parseJson(text, path) {
93
+ try {
94
+ // tolerate // comments in config files
95
+ return JSON.parse(text.replace(/^\s*\/\/.*$/gm, ''));
96
+ } catch (e) {
97
+ throw new Error(`Could not parse ${path}: ${e.message}`);
98
+ }
99
+ }
100
+
101
+ /** Build a predicate from names/globs like `AWS_*`. */
102
+ export function nameMatcher(patterns) {
103
+ const exact = new Set();
104
+ const res = [];
105
+ for (const p of patterns) {
106
+ if (/[*?]/.test(p)) res.push(new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`));
107
+ else exact.add(p);
108
+ }
109
+ return (name) => exact.has(name) || res.some((r) => r.test(name));
110
+ }
package/src/dotenv.js ADDED
@@ -0,0 +1,80 @@
1
+ // A small, forgiving .env parser that keeps line numbers and recognises
2
+ // commented-out keys (`# SENTRY_DSN=`) as "documented but optional".
3
+
4
+ const KEY_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/;
5
+ const COMMENTED_KEY_LINE = /^\s*#+\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
6
+
7
+ /**
8
+ * @typedef {{ name: string, value: string, line: number, endLine: number, optional: boolean }} EnvEntry
9
+ * @param {string} text
10
+ * @returns {{ entries: EnvEntry[], keys: Map<string, EnvEntry> }}
11
+ */
12
+ export function parseDotenv(text) {
13
+ const lines = text.replace(/^/, '').split(/\r?\n/);
14
+ /** @type {EnvEntry[]} */
15
+ const entries = [];
16
+
17
+ for (let i = 0; i < lines.length; i++) {
18
+ const raw = lines[i];
19
+ const m = KEY_LINE.exec(raw);
20
+ if (m) {
21
+ const name = m[1];
22
+ let rest = m[2];
23
+ const startLine = i + 1;
24
+ let value;
25
+ const q = rest[0];
26
+ if (q === '"' || q === "'" || q === '`') {
27
+ // quoted value, possibly spanning multiple lines
28
+ let body = rest.slice(1);
29
+ let close = findClosingQuote(body, q);
30
+ while (close === -1 && i + 1 < lines.length) {
31
+ i++;
32
+ body += '\n' + lines[i];
33
+ close = findClosingQuote(body, q);
34
+ }
35
+ value = close === -1 ? body : body.slice(0, close);
36
+ if (q === '"') value = value.replace(/\\n/g, '\n').replace(/\\"/g, '"');
37
+ } else {
38
+ value = rest.replace(/\s+#.*$/, '').trim();
39
+ }
40
+ entries.push({ name, value, line: startLine, endLine: i + 1, optional: false });
41
+ continue;
42
+ }
43
+ const c = COMMENTED_KEY_LINE.exec(raw);
44
+ if (c) {
45
+ entries.push({ name: c[1], value: c[2].trim(), line: i + 1, endLine: i + 1, optional: true });
46
+ }
47
+ }
48
+
49
+ /** @type {Map<string, EnvEntry>} */
50
+ const keys = new Map();
51
+ for (const e of entries) {
52
+ const prev = keys.get(e.name);
53
+ // a real assignment wins over a commented-out one
54
+ if (!prev || (prev.optional && !e.optional)) keys.set(e.name, e);
55
+ }
56
+ return { entries, keys };
57
+ }
58
+
59
+ function findClosingQuote(s, q) {
60
+ for (let i = 0; i < s.length; i++) {
61
+ if (s[i] === '\\' && q === '"') {
62
+ i++;
63
+ continue;
64
+ }
65
+ if (s[i] === q) return i;
66
+ }
67
+ return -1;
68
+ }
69
+
70
+ /** Find duplicate (non-optional) keys, a common copy-paste bug. */
71
+ export function findDuplicates(entries) {
72
+ const seen = new Map();
73
+ const dups = [];
74
+ for (const e of entries) {
75
+ if (e.optional) continue;
76
+ if (seen.has(e.name)) dups.push({ name: e.name, line: e.line, firstLine: seen.get(e.name) });
77
+ else seen.set(e.name, e.line);
78
+ }
79
+ return dups;
80
+ }
@@ -0,0 +1,295 @@
1
+ // Language-aware extraction of environment variable references.
2
+ // Each language has a list of regexes with a named group `name`.
3
+ // Matches that are assignments (`process.env.X = 1`) are skipped.
4
+
5
+ const N = '(?<name>[A-Za-z_][A-Za-z0-9_]*)';
6
+ const UPPER_N = '(?<name>[A-Z_][A-Z0-9_]*)';
7
+ const Q = `(?<q>['"\`])`;
8
+ const QN = `${Q}${N}\\k<q>`; // quoted name, same quote on both sides
9
+ const DQN = `"${N}"`;
10
+
11
+ const JS_OBJECTS = String.raw`(?:process\.env|import\.meta\.env|Bun\.env)`;
12
+
13
+ /** @type {Record<string, { test: (path: string) => boolean, patterns: RegExp[], custom?: Function[] }>} */
14
+ export const LANGUAGES = {
15
+ javascript: {
16
+ comments: 'c',
17
+ test: ext(['js', 'mjs', 'cjs', 'jsx', 'ts', 'mts', 'cts', 'tsx', 'vue', 'svelte', 'astro']),
18
+ patterns: [
19
+ re(String.raw`\b${JS_OBJECTS}\??\.${N}\b`),
20
+ re(String.raw`\b${JS_OBJECTS}\??\.?\[\s*${QN}\s*\]`),
21
+ re(String.raw`\bDeno\.env\.get\(\s*${QN}`),
22
+ ],
23
+ custom: [jsDestructuring, svelteKitEnvImports],
24
+ },
25
+ python: {
26
+ comments: 'hash',
27
+ test: ext(['py', 'pyi']),
28
+ patterns: [
29
+ re(String.raw`\b(?:os\.)?environ\s*\[\s*${QN}\s*\]`),
30
+ re(String.raw`\b(?:os\.)?environ\.(?:get|pop|setdefault)\(\s*${QN}`),
31
+ re(String.raw`\b(?:os\.)?getenv\(\s*${QN}`),
32
+ ],
33
+ },
34
+ go: {
35
+ comments: 'c',
36
+ test: ext(['go']),
37
+ patterns: [re(String.raw`\bos\.(?:Getenv|LookupEnv)\(\s*${DQN}`)],
38
+ },
39
+ rust: {
40
+ comments: 'c',
41
+ test: ext(['rs']),
42
+ patterns: [
43
+ re(String.raw`\b(?:std::)?env::var(?:_os)?\(\s*${DQN}`),
44
+ re(String.raw`\b(?:option_)?env!\(\s*${DQN}`),
45
+ re(String.raw`\bdotenvy?::var\(\s*${DQN}`),
46
+ ],
47
+ },
48
+ ruby: {
49
+ comments: 'hash',
50
+ test: (p) => ext(['rb', 'rake', 'erb', 'ru'])(p) || /(^|\/)(Gemfile|Rakefile)$/.test(p),
51
+ patterns: [
52
+ re(String.raw`\bENV\s*\[\s*${QN}\s*\]`),
53
+ re(String.raw`\bENV\.(?:fetch|key\?|has_key\?|include\?)\(?\s*${QN}`),
54
+ ],
55
+ },
56
+ php: {
57
+ comments: 'php',
58
+ test: ext(['php']),
59
+ patterns: [
60
+ re(String.raw`\bgetenv\(\s*${QN}`),
61
+ re(String.raw`\$_ENV\s*\[\s*${QN}\s*\]`),
62
+ re(String.raw`\benv\(\s*${QN}`), // Laravel
63
+ ],
64
+ },
65
+ jvm: {
66
+ comments: 'c',
67
+ test: ext(['java', 'kt', 'kts', 'scala', 'groovy', 'gradle']),
68
+ patterns: [re(String.raw`\bSystem\.getenv\(\s*${DQN}`)],
69
+ },
70
+ spring: {
71
+ comments: 'hash',
72
+ // Spring placeholders: only UPPER_CASE names are treated as env vars
73
+ test: (p) => /\.properties$/.test(p) || /(^|\/)application[^/]*\.ya?ml$/.test(p),
74
+ patterns: [re(String.raw`\$\{${UPPER_N}(?::[^}]*)?\}`)],
75
+ },
76
+ csharp: {
77
+ comments: 'c',
78
+ test: ext(['cs', 'fs', 'vb']),
79
+ patterns: [re(String.raw`\bEnvironment\.GetEnvironmentVariable\(\s*${DQN}`)],
80
+ },
81
+ elixir: {
82
+ comments: 'hash',
83
+ test: ext(['ex', 'exs']),
84
+ patterns: [re(String.raw`\bSystem\.(?:get_env|fetch_env!?)\(\s*${DQN}`)],
85
+ },
86
+ swift: {
87
+ comments: 'c',
88
+ test: ext(['swift']),
89
+ patterns: [re(String.raw`\bProcessInfo\.processInfo\.environment\[\s*${DQN}\s*\]`)],
90
+ },
91
+ dart: {
92
+ comments: 'c',
93
+ test: ext(['dart']),
94
+ patterns: [
95
+ re(String.raw`\bPlatform\.environment\[\s*${QN}\s*\]`),
96
+ re(String.raw`\b(?:String|int|bool)\.fromEnvironment\(\s*${QN}`),
97
+ ],
98
+ },
99
+ prisma: {
100
+ comments: 'c',
101
+ test: ext(['prisma']),
102
+ patterns: [re(String.raw`\benv\(\s*${DQN}\s*\)`)],
103
+ },
104
+ compose: {
105
+ comments: 'hash',
106
+ test: (p) => /(^|\/)(docker-)?compose[^/]*\.ya?ml$/.test(p),
107
+ patterns: [
108
+ re(String.raw`(?<!\$)\$\{${N}(?:[:?+-][^}]*)?\}`),
109
+ re(String.raw`(?<!\$)\$${UPPER_N}\b`),
110
+ ],
111
+ },
112
+ };
113
+
114
+ function ext(list) {
115
+ const set = new Set(list);
116
+ return (p) => {
117
+ const i = p.lastIndexOf('.');
118
+ return i !== -1 && set.has(p.slice(i + 1).toLowerCase());
119
+ };
120
+ }
121
+
122
+ function re(src) {
123
+ return new RegExp(src, 'gd'); // d = match indices, for exact columns
124
+ }
125
+
126
+ /** Returns the language key for a path, or null if we don't extract from it. */
127
+ export function languageFor(relPath) {
128
+ const p = relPath.replace(/\\/g, '/');
129
+ for (const [key, lang] of Object.entries(LANGUAGES)) {
130
+ if (lang.test(p)) return key;
131
+ }
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * @typedef {{ name: string, line: number, column: number }} Reference
137
+ * @param {string} text
138
+ * @param {string} relPath
139
+ * @returns {Reference[]}
140
+ */
141
+ export function extract(text, relPath) {
142
+ const key = languageFor(relPath);
143
+ if (!key) return [];
144
+ const lang = LANGUAGES[key];
145
+ const lineStarts = computeLineStarts(text);
146
+ const lines = text.split('\n'); // original lines, for ignore comments
147
+ const code = maskComments(text, lang.comments, key);
148
+ /** @type {Reference[]} */
149
+ const refs = [];
150
+ const seen = new Set();
151
+
152
+ const push = (name, index) => {
153
+ const line = lineAt(lineStarts, index);
154
+ if (isIgnored(lines, line)) return;
155
+ const id = `${name}:${index}`;
156
+ if (seen.has(id)) return;
157
+ seen.add(id);
158
+ refs.push({ name, line, column: index - lineStarts[line - 1] + 1 });
159
+ };
160
+
161
+ for (const pattern of lang.patterns) {
162
+ pattern.lastIndex = 0;
163
+ let m;
164
+ while ((m = pattern.exec(code))) {
165
+ const after = code.slice(pattern.lastIndex, pattern.lastIndex + 8);
166
+ if (/^\s*=(?![=>])/.test(after)) continue; // assignment, not a read
167
+ push(m.groups.name, m.indices.groups.name[0]);
168
+ }
169
+ }
170
+ for (const fn of lang.custom ?? []) {
171
+ for (const { name, index } of fn(code)) push(name, index);
172
+ }
173
+
174
+ refs.sort((a, b) => a.line - b.line || a.column - b.column);
175
+ return refs;
176
+ }
177
+
178
+ // const { API_KEY, DB_URL: dbUrl, PORT = 3000, ...rest } = process.env
179
+ function* jsDestructuring(text) {
180
+ const r = new RegExp(String.raw`(?:const|let|var)\s*\{([^}]*)\}\s*=\s*${JS_OBJECTS}\b(?!\s*\.)`, 'g');
181
+ let m;
182
+ while ((m = r.exec(text))) {
183
+ const bodyStart = m.index + m[0].indexOf('{') + 1;
184
+ yield* namesInBraces(m[1], bodyStart);
185
+ }
186
+ }
187
+
188
+ // import { API_KEY } from '$env/static/private'
189
+ function* svelteKitEnvImports(text) {
190
+ const r = /import\s*\{([^}]*)\}\s*from\s*['"]\$env\/static\/(?:private|public)['"]/g;
191
+ let m;
192
+ while ((m = r.exec(text))) {
193
+ const bodyStart = m.index + m[0].indexOf('{') + 1;
194
+ yield* namesInBraces(m[1].replace(/\bas\s+\w+/g, (s) => ' '.repeat(s.length)), bodyStart);
195
+ }
196
+ }
197
+
198
+ function* namesInBraces(body, offset) {
199
+ let pos = 0;
200
+ for (const part of body.split(',')) {
201
+ const nm = /^\s*([A-Za-z_][A-Za-z0-9_]*)/.exec(part);
202
+ if (nm && !part.trim().startsWith('...')) {
203
+ yield { name: nm[1], index: offset + pos + part.indexOf(nm[1]) };
204
+ }
205
+ pos += part.length + 1;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Replace comment contents with spaces (keeping newlines, so positions are
211
+ * unchanged) so commented-out code isn't reported. String-aware, so that
212
+ * `"http://x"` or `"#fff"` are left alone. Deliberately simple: single/double
213
+ * quoted strings end at a newline, so a mis-detected quote can't swallow a file.
214
+ */
215
+ export function maskComments(text, style, lang) {
216
+ if (!style) return text;
217
+ const slash = style === 'c' || style === 'php';
218
+ const hash = style === 'hash' || style === 'php';
219
+ const quotes = lang === 'rust' ? '"' : lang === 'go' || lang === 'javascript' ? `'"\`` : `'"`;
220
+ const out = text.split('');
221
+ const n = text.length;
222
+ const blank = (from, to) => {
223
+ for (let k = from; k < to; k++) if (out[k] !== '\n' && out[k] !== '\r') out[k] = ' ';
224
+ };
225
+ const lineEnd = (from) => {
226
+ const e = text.indexOf('\n', from);
227
+ return e === -1 ? n : e;
228
+ };
229
+ let i = 0;
230
+ while (i < n) {
231
+ const ch = text[i];
232
+ if (quotes.includes(ch)) {
233
+ if (lang === 'python' && text.startsWith(ch.repeat(3), i)) {
234
+ // triple-quoted string
235
+ const end = text.indexOf(ch.repeat(3), i + 3);
236
+ i = end === -1 ? n : end + 3;
237
+ continue;
238
+ }
239
+ let j = i + 1;
240
+ while (j < n && text[j] !== ch) {
241
+ if (text.charCodeAt(j) === 92) j++; // backslash escape
242
+ else if (text[j] === '\n' && ch !== '`') break;
243
+ j++;
244
+ }
245
+ i = j + 1;
246
+ continue;
247
+ }
248
+ if (slash && ch === '/' && text[i + 1] === '/') {
249
+ const e = lineEnd(i);
250
+ blank(i, e);
251
+ i = e;
252
+ continue;
253
+ }
254
+ if (slash && ch === '/' && text[i + 1] === '*') {
255
+ const end = text.indexOf('*/', i + 2);
256
+ const stop = end === -1 ? n : end + 2;
257
+ blank(i, stop);
258
+ i = stop;
259
+ continue;
260
+ }
261
+ // in YAML a `#` only starts a comment at line start or after whitespace
262
+ if (hash && ch === '#' && (lang !== 'compose' || i === 0 || /\s/.test(text[i - 1]))) {
263
+ const e = lineEnd(i);
264
+ blank(i, e);
265
+ i = e;
266
+ continue;
267
+ }
268
+ i++;
269
+ }
270
+ return out.join('');
271
+ }
272
+
273
+ function computeLineStarts(text) {
274
+ const starts = [0];
275
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
276
+ return starts;
277
+ }
278
+
279
+ function lineAt(starts, index) {
280
+ let lo = 0;
281
+ let hi = starts.length - 1;
282
+ while (lo < hi) {
283
+ const mid = (lo + hi + 1) >> 1;
284
+ if (starts[mid] <= index) lo = mid;
285
+ else hi = mid - 1;
286
+ }
287
+ return lo + 1;
288
+ }
289
+
290
+ function isIgnored(lines, line) {
291
+ const cur = lines[line - 1] ?? '';
292
+ if (/envaudit-ignore(?!-next-line)/.test(cur)) return true;
293
+ const prev = lines[line - 2] ?? '';
294
+ return /envaudit-ignore-next-line/.test(prev);
295
+ }