@jutaru-dev/envsonar 0.1.0 → 0.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/src/cli.js CHANGED
@@ -1,298 +1,303 @@
1
- // @ts-check
2
- import { appendFileSync, existsSync, readFileSync } from "node:fs";
3
- import { relative, resolve, sep } from "node:path";
4
- import { parseArgs } from "node:util";
5
- import { check, fixText } from "./check.js";
6
- import { parseEnv } from "./parse.js";
7
- import { scanProject } from "./scan.js";
8
-
9
- export const VERSION = "0.1.0";
10
-
11
- const HELP = `envsonar ${VERSION} — find env vars your code reads but .env.example forgot. Never prints a value.
12
-
13
- Usage
14
- envsonar [dir] [options]
15
-
16
- Checks
17
- ✗ undocumented read in code, missing from .env.example
18
- ✗ missing in .env.example, not set in .env (only when .env exists)
19
- ! unused in .env.example, read by nothing: not your code, not a framework, SDK or image
20
- ! defaulted read with a fallback, missing from .env.example (shown with --optional)
21
- ! empty / extra / duplicate keys in .env
22
-
23
- Understands .NET IConfiguration and appsettings.json, pydantic-settings, Go env tags,
24
- envalid and zod env schemas, Prisma, SvelteKit $env, Docker Compose, and the variables
25
- SDKs read on their own (AWS, OpenAI, Anthropic, Sentry, Auth.js, postgres image, …).
26
-
27
- Options
28
- --fix add undocumented keys to .env.example (creates it if needed)
29
- --optional also report (and --fix) keys that have a default in code
30
- --list print every env var the code reads, with where
31
- --example <path> default: .env.example
32
- --env <path> default: .env — checked only if it exists, unless set explicitly
33
- --no-code skip scanning source files, only compare the env files
34
- --ignore <dir> skip a directory (repeatable)
35
- --ignore-key <KEY> skip a key; PREFIX_* works too (repeatable)
36
- --strict warnings fail too
37
- --json machine-readable report
38
- --format <pretty|github> github prints workflow annotations (auto on GitHub Actions)
39
- --no-color, -h/--help, -v/--version
40
-
41
- Config: an "envsonar" object in package.json or .envsonarrc.json with the same names
42
- (example, env, ignore, ignoreKeys, strict, optional).
43
-
44
- Exit codes: 0 clean · 1 problems found · 2 bad usage or unreadable file`;
45
-
46
- /**
47
- * @typedef {{ out: (s: string) => void, err: (s: string) => void, cwd: string, color: boolean, githubActions?: boolean }} Io
48
- * @typedef {{ example?: string, env?: string, ignore?: string[], ignoreKeys?: string[], strict?: boolean, optional?: boolean }} Config
49
- */
50
-
51
- /**
52
- * Runs the CLI and returns the exit code; all output goes through `io`, so tests can capture it.
53
- *
54
- * @param {string[]} argv
55
- * @param {Io} io
56
- * @returns {number}
57
- */
58
- export function run(argv, io) {
59
- let parsed;
60
- try {
61
- parsed = parseArgs({
62
- args: argv,
63
- allowPositionals: true,
64
- options: {
65
- example: { type: "string" },
66
- env: { type: "string" },
67
- ignore: { type: "string", multiple: true },
68
- "ignore-key": { type: "string", multiple: true },
69
- "no-code": { type: "boolean", default: false },
70
- fix: { type: "boolean", default: false },
71
- optional: { type: "boolean" },
72
- list: { type: "boolean", default: false },
73
- strict: { type: "boolean" },
74
- json: { type: "boolean", default: false },
75
- format: { type: "string" },
76
- "no-color": { type: "boolean", default: false },
77
- help: { type: "boolean", short: "h", default: false },
78
- version: { type: "boolean", short: "v", default: false },
79
- },
80
- });
81
- } catch (e) {
82
- return usage(io, e instanceof Error ? e.message : String(e));
83
- }
84
- const { values: opt, positionals } = parsed;
85
- if (opt.help) return io.out(HELP), 0;
86
- if (opt.version) return io.out(VERSION), 0;
87
- if (positionals.length > 1) return usage(io, `expected one directory, got "${positionals.join(" ")}"`);
88
- if (opt.format && !["pretty", "github"].includes(opt.format)) return usage(io, `unknown --format "${opt.format}"`);
89
-
90
- const root = resolve(io.cwd, positionals[0] ?? ".");
91
- if (!existsSync(root)) return fail(io, `directory not found: ${positionals[0]}`);
92
- const config = loadConfig(root, io);
93
- if (config === null) return 2;
94
-
95
- const exampleName = opt.example ?? config.example ?? ".env.example";
96
- const envName = opt.env ?? config.env ?? ".env";
97
- const envRequired = Boolean(opt.env);
98
- const strict = opt.strict ?? config.strict ?? false;
99
- const showDefaulted = opt.optional ?? config.optional ?? false;
100
- const paint = painter(io.color && !opt["no-color"] && !opt.json);
101
- const display = (/** @type {string} */ p) => relative(io.cwd, resolve(root, p)).split(sep).join("/") || p;
102
-
103
- const scan = opt["no-code"]
104
- ? null
105
- : scanProject(root, {
106
- ignoreDirs: [...(config.ignore ?? []), ...(opt.ignore ?? [])],
107
- ignoreKeys: [...(config.ignoreKeys ?? []), ...(opt["ignore-key"] ?? [])],
108
- });
109
-
110
- if (opt.list) {
111
- if (!scan) return usage(io, "--list needs the code scan, drop --no-code");
112
- return list(scan, opt.json, paint, io, display);
113
- }
114
-
115
- const examplePath = resolve(root, exampleName);
116
- let exampleText = readOptional(examplePath, io);
117
- if (exampleText === undefined) return 2;
118
- if (exampleText === null && !opt.fix) {
119
- return fail(io, `${display(exampleName)} not found — run "envsonar --fix" to create it from your code`);
120
- }
121
- const example = parseEnv(exampleText ?? "");
122
-
123
- const envText = readOptional(resolve(root, envName), io);
124
- if (envText === undefined) return 2;
125
- if (envText === null && envRequired) return fail(io, `${display(envName)} not found`);
126
- const env = envText === null ? null : parseEnv(envText);
127
-
128
- // scan paths are relative to the scanned dir; reports use paths relative to where envsonar runs, like the env files
129
- const runCheck = (/** @type {import("./parse.js").ParsedEnv} */ ex) =>
130
- check({ example: ex, exampleFile: display(exampleName), env, envFile: display(envName), scan, strict }).map((f) =>
131
- f.usages ? { ...f, file: display(f.file), usages: f.usages.map((u) => ({ ...u, file: display(u.file) })) } : f,
132
- );
133
- let all = runCheck(example);
134
- const shown = (/** @type {import("./check.js").Finding[]} */ list) => (showDefaulted ? list : list.filter((f) => f.code !== "defaulted"));
135
- let findings = shown(all);
136
-
137
- if (opt.fix) {
138
- const added = findings.filter((f) => f.code === "undocumented" || f.code === "defaulted");
139
- if (added.length) {
140
- appendFileSync(examplePath, fixText(added, !exampleText?.trim()));
141
- io.out(`${paint.green("✓")} added ${plural(added.length, "key")} to ${display(exampleName)}: ${added.map((f) => f.key).join(", ")}`);
142
- exampleText = readFileSync(examplePath, "utf8");
143
- all = runCheck(parseEnv(exampleText));
144
- findings = shown(all);
145
- } else {
146
- io.out(`${paint.green("✓")} ${display(exampleName)} already documents every key the code reads`);
147
- }
148
- }
149
-
150
- const errors = findings.filter((f) => f.severity === "error").length;
151
- const warnings = findings.length - errors;
152
- const files = scan ? scan.files : 0;
153
- const hiddenDefaulted = all.length - findings.length;
154
- const frameworks = scan ? scan.implicit.map((i) => i.source) : [];
155
-
156
- if (opt.json) {
157
- const dynamic = (scan?.dynamic ?? []).map((d) => ({ ...d, file: display(d.file) }));
158
- const report = { ok: errors === 0, errors, warnings, scannedFiles: files, frameworks, hiddenDefaulted, findings, dynamic };
159
- io.out(JSON.stringify(report, null, 2));
160
- return errors ? 1 : 0;
161
- }
162
-
163
- const format = opt.format ?? (io.githubActions ? "github" : "pretty");
164
- if (format === "github") {
165
- for (const f of findings) {
166
- const level = f.severity === "error" ? "error" : "warning";
167
- const where = `file=${f.file}${f.line ? `,line=${f.line}` : ""}`;
168
- io.out(`::${level} ${where},title=envsonar ${f.code}::${f.key ? `${f.key} ` : ""}${f.message}`);
169
- }
170
- }
171
-
172
- const header = scan
173
- ? paint.dim(`envsonar · ${files} files scanned · ${scan.usages.size} keys in code · ${example.entries.size} in ${display(exampleName)}${env ? ` · ${display(envName)} checked` : ""}`)
174
- : paint.dim(`envsonar · ${display(exampleName)}${env ? ` vs ${display(envName)}` : ""}`);
175
- io.out(header);
176
- if (frameworks.length) io.out(paint.dim(`also read by: ${frameworks.join(", ")}`));
177
- const notes = () => {
178
- if (hiddenDefaulted) io.out(paint.dim(`${plural(hiddenDefaulted, "key")} with a default in code not in ${display(exampleName)} — show with --optional`));
179
- if (scan?.dynamic.length) {
180
- const where = scan.dynamic.slice(0, 3).map((d) => `${display(d.file)}:${d.line}`).join(", ");
181
- io.out(paint.dim(`${plural(scan.dynamic.length, "dynamic read")} can't be checked: ${where}${scan.dynamic.length > 3 ? ", …" : ""}`));
182
- }
183
- };
184
-
185
- if (findings.length === 0) {
186
- io.out(`${paint.green("✓")} all in sync`);
187
- notes();
188
- return 0;
189
- }
190
-
191
- io.out("");
192
- const width = Math.max(...findings.map((f) => (f.key ?? "").length), 3);
193
- const msgWidth = Math.max(...findings.map((f) => f.message.length));
194
- for (const f of findings) {
195
- const mark = f.severity === "error" ? paint.red("✗") : paint.yellow("!");
196
- const more = f.usages && f.usages.length > 1 ? paint.dim(` (+${f.usages.length - 1})`) : "";
197
- const where = paint.dim(`${f.file}${f.line ? `:${f.line}` : ""}`) + more;
198
- io.out(` ${mark} ${paint.bold((f.key ?? "").padEnd(width))} ${f.message.padEnd(msgWidth)} ${where}`);
199
- }
200
- const summary = [errors && paint.red(plural(errors, "error")), warnings && paint.yellow(plural(warnings, "warning"))].filter(Boolean).join(", ");
201
- const undocumented = findings.filter((f) => f.code === "undocumented").length;
202
- const hint = undocumented ? paint.dim(` · run envsonar --fix to add ${plural(undocumented, "key")} to ${display(exampleName)}`) : "";
203
- io.out(`\n${summary}${hint}`);
204
- notes();
205
- return errors ? 1 : 0;
206
- }
207
-
208
- /**
209
- * @param {import("./scan.js").ScanResult} scan
210
- * @param {boolean} json
211
- * @param {ReturnType<typeof painter>} paint
212
- * @param {Io} io
213
- * @param {(p: string) => string} display
214
- */
215
- function list(scan, json, paint, io, display) {
216
- const keys = [...scan.usages].sort(([a], [b]) => a.localeCompare(b));
217
- const frameworks = scan.implicit.map((i) => i.source);
218
- if (json) {
219
- const report = { keys: Object.fromEntries(keys), sections: Object.fromEntries(scan.sections), dynamic: scan.dynamic, frameworks };
220
- io.out(JSON.stringify(report, null, 2));
221
- return 0;
222
- }
223
- io.out(paint.dim(`envsonar · ${scan.files} files scanned · ${keys.length} keys`));
224
- if (frameworks.length) io.out(paint.dim(`also read by: ${frameworks.join(", ")}`));
225
- const width = Math.max(...keys.map(([k]) => k.length), 3);
226
- for (const [key, uses] of keys) {
227
- const more = uses.length > 1 ? paint.dim(` (+${uses.length - 1})`) : "";
228
- const tag = uses.every((u) => u.optional) ? paint.dim(" default") : "";
229
- io.out(` ${paint.bold(key.padEnd(width))} ${paint.dim(`${display(uses[0].file)}:${uses[0].line}`)}${more}${tag}`);
230
- }
231
- for (const [prefix, uses] of scan.sections) io.out(` ${paint.bold(`${prefix}*`.padEnd(width))} ${paint.dim(`${display(uses[0].file)}:${uses[0].line} section`)}`);
232
- for (const d of scan.dynamic) io.out(` ${paint.yellow("?")} ${paint.dim(`${d.expr} ${display(d.file)}:${d.line} dynamic, not checked`)}`);
233
- return 0;
234
- }
235
-
236
- /**
237
- * @param {string} root
238
- * @param {Io} io
239
- * @returns {Config | null}
240
- */
241
- function loadConfig(root, io) {
242
- for (const [file, pick] of /** @type {const} */ ([
243
- [".envsonarrc.json", (/** @type {any} */ j) => j],
244
- ["package.json", (/** @type {any} */ j) => j.envsonar],
245
- ])) {
246
- const text = readOptional(resolve(root, file), io);
247
- if (text === undefined) return null;
248
- if (text === null) continue;
249
- try {
250
- const config = pick(JSON.parse(text));
251
- if (config === undefined) continue;
252
- if (typeof config !== "object" || config === null || Array.isArray(config)) throw new Error("expected an object");
253
- return /** @type {Config} */ (config);
254
- } catch (e) {
255
- io.err(`envsonar: invalid config in ${file}: ${e instanceof Error ? e.message : String(e)}`);
256
- return null;
257
- }
258
- }
259
- return {};
260
- }
261
-
262
- /**
263
- * @param {string} path
264
- * @param {Io} io
265
- * @returns {string | null | undefined} null when the file doesn't exist, undefined when it can't be read
266
- */
267
- function readOptional(path, io) {
268
- try {
269
- return readFileSync(path, "utf8");
270
- } catch (e) {
271
- const code = /** @type {NodeJS.ErrnoException} */ (e).code;
272
- if (code === "ENOENT") return null;
273
- io.err(`envsonar: cannot read ${path} (${code ?? "unknown error"})`);
274
- return undefined;
275
- }
276
- }
277
-
278
- /** @param {Io} io @param {string} message */
279
- function usage(io, message) {
280
- io.err(`envsonar: ${message}\nRun "envsonar --help" for usage.`);
281
- return 2;
282
- }
283
-
284
- /** @param {Io} io @param {string} message */
285
- function fail(io, message) {
286
- io.err(`envsonar: ${message}`);
287
- return 2;
288
- }
289
-
290
- /** @param {number} n @param {string} word */
291
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
292
-
293
- /** @param {boolean} on */
294
- function painter(on) {
295
- /** @param {number} a @param {number} b */
296
- const wrap = (a, b) => (/** @type {string} */ s) => (on ? `\x1b[${a}m${s}\x1b[${b}m` : s);
297
- return { red: wrap(31, 39), green: wrap(32, 39), yellow: wrap(33, 39), dim: wrap(2, 22), bold: wrap(1, 22) };
298
- }
1
+ // @ts-check
2
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
3
+ import { relative, resolve, sep } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { check, fixText } from "./check.js";
6
+ import { parseEnv } from "./parse.js";
7
+ import { scanProject } from "./scan.js";
8
+
9
+ export const VERSION = "0.2.0";
10
+
11
+ const HELP = `envsonar ${VERSION} — find env vars your code reads but .env.example forgot. Never prints a value.
12
+
13
+ Usage
14
+ envsonar [dir] [options]
15
+
16
+ Checks
17
+ ✗ undocumented read in code, missing from .env.example
18
+ ✗ missing in .env.example, not set in .env (only when .env exists)
19
+ ! unused in .env.example, read by nothing: not your code, not a framework, SDK or image
20
+ ! defaulted read with a fallback, missing from .env.example (shown with --optional)
21
+ ! empty / extra / duplicate keys in .env
22
+
23
+ Understands .NET IConfiguration and appsettings.json, pydantic-settings, Go env tags,
24
+ envalid and zod env schemas, Prisma, SvelteKit $env, Docker Compose, and the variables
25
+ SDKs read on their own (AWS, OpenAI, Anthropic, Sentry, Auth.js, postgres image, …).
26
+
27
+ Options
28
+ --fix add undocumented keys to .env.example (creates it if needed)
29
+ --optional also report (and --fix) keys that have a default in code
30
+ --list print every env var the code reads, with where
31
+ --example <path> default: .env.example
32
+ --env <path> default: .env — checked only if it exists, unless set explicitly
33
+ --no-code skip scanning source files, only compare the env files
34
+ --ignore <dir> skip a directory (repeatable)
35
+ --ignore-key <KEY> skip a key; PREFIX_* works too (repeatable)
36
+ --include-tests also scan test files and dirs (test/, *.test.ts, test_*.py, …)
37
+ --strict warnings fail too
38
+ --json machine-readable report
39
+ --format <pretty|github> github prints workflow annotations (auto on GitHub Actions)
40
+ --no-color, -h/--help, -v/--version
41
+
42
+ Config: an "envsonar" object in package.json or .envsonarrc.json with the same names
43
+ (example, env, ignore, ignoreKeys, includeTests, strict, optional).
44
+
45
+ Exit codes: 0 clean · 1 problems found · 2 bad usage or unreadable file`;
46
+
47
+ /**
48
+ * @typedef {{ out: (s: string) => void, err: (s: string) => void, cwd: string, color: boolean, githubActions?: boolean, githubOutput?: (s: string) => void }} Io
49
+ * githubOutput — appends step outputs (`errors=…`) on GitHub Actions
50
+ * @typedef {{ example?: string, env?: string, ignore?: string[], ignoreKeys?: string[], includeTests?: boolean, strict?: boolean, optional?: boolean }} Config
51
+ */
52
+
53
+ /**
54
+ * Runs the CLI and returns the exit code; all output goes through `io`, so tests can capture it.
55
+ *
56
+ * @param {string[]} argv
57
+ * @param {Io} io
58
+ * @returns {number}
59
+ */
60
+ export function run(argv, io) {
61
+ let parsed;
62
+ try {
63
+ parsed = parseArgs({
64
+ args: argv,
65
+ allowPositionals: true,
66
+ options: {
67
+ example: { type: "string" },
68
+ env: { type: "string" },
69
+ ignore: { type: "string", multiple: true },
70
+ "ignore-key": { type: "string", multiple: true },
71
+ "no-code": { type: "boolean", default: false },
72
+ "include-tests": { type: "boolean" },
73
+ fix: { type: "boolean", default: false },
74
+ optional: { type: "boolean" },
75
+ list: { type: "boolean", default: false },
76
+ strict: { type: "boolean" },
77
+ json: { type: "boolean", default: false },
78
+ format: { type: "string" },
79
+ "no-color": { type: "boolean", default: false },
80
+ help: { type: "boolean", short: "h", default: false },
81
+ version: { type: "boolean", short: "v", default: false },
82
+ },
83
+ });
84
+ } catch (e) {
85
+ return usage(io, e instanceof Error ? e.message : String(e));
86
+ }
87
+ const { values: opt, positionals } = parsed;
88
+ if (opt.help) return io.out(HELP), 0;
89
+ if (opt.version) return io.out(VERSION), 0;
90
+ if (positionals.length > 1) return usage(io, `expected one directory, got "${positionals.join(" ")}"`);
91
+ if (opt.format && !["pretty", "github"].includes(opt.format)) return usage(io, `unknown --format "${opt.format}"`);
92
+
93
+ const root = resolve(io.cwd, positionals[0] ?? ".");
94
+ if (!existsSync(root)) return fail(io, `directory not found: ${positionals[0]}`);
95
+ const config = loadConfig(root, io);
96
+ if (config === null) return 2;
97
+
98
+ const exampleName = opt.example ?? config.example ?? ".env.example";
99
+ const envName = opt.env ?? config.env ?? ".env";
100
+ const envRequired = Boolean(opt.env);
101
+ const strict = opt.strict ?? config.strict ?? false;
102
+ const showDefaulted = opt.optional ?? config.optional ?? false;
103
+ const paint = painter(io.color && !opt["no-color"] && !opt.json);
104
+ const display = (/** @type {string} */ p) => relative(io.cwd, resolve(root, p)).split(sep).join("/") || p;
105
+
106
+ const scan = opt["no-code"]
107
+ ? null
108
+ : scanProject(root, {
109
+ ignoreDirs: [...(config.ignore ?? []), ...(opt.ignore ?? [])],
110
+ ignoreKeys: [...(config.ignoreKeys ?? []), ...(opt["ignore-key"] ?? [])],
111
+ includeTests: opt["include-tests"] ?? config.includeTests ?? false,
112
+ });
113
+
114
+ if (opt.list) {
115
+ if (!scan) return usage(io, "--list needs the code scan, drop --no-code");
116
+ return list(scan, opt.json, paint, io, display);
117
+ }
118
+
119
+ const examplePath = resolve(root, exampleName);
120
+ let exampleText = readOptional(examplePath, io);
121
+ if (exampleText === undefined) return 2;
122
+ if (exampleText === null && !opt.fix) {
123
+ return fail(io, `${display(exampleName)} not found — run "envsonar --fix" to create it from your code`);
124
+ }
125
+ const example = parseEnv(exampleText ?? "");
126
+
127
+ const envText = readOptional(resolve(root, envName), io);
128
+ if (envText === undefined) return 2;
129
+ if (envText === null && envRequired) return fail(io, `${display(envName)} not found`);
130
+ const env = envText === null ? null : parseEnv(envText);
131
+
132
+ // scan paths are relative to the scanned dir; reports use paths relative to where envsonar runs, like the env files
133
+ const runCheck = (/** @type {import("./parse.js").ParsedEnv} */ ex) =>
134
+ check({ example: ex, exampleFile: display(exampleName), env, envFile: display(envName), scan, strict }).map((f) =>
135
+ f.usages ? { ...f, file: display(f.file), usages: f.usages.map((u) => ({ ...u, file: display(u.file) })) } : f,
136
+ );
137
+ let all = runCheck(example);
138
+ const shown = (/** @type {import("./check.js").Finding[]} */ list) => (showDefaulted ? list : list.filter((f) => f.code !== "defaulted"));
139
+ let findings = shown(all);
140
+
141
+ if (opt.fix) {
142
+ const added = findings.filter((f) => f.code === "undocumented" || f.code === "defaulted");
143
+ if (added.length) {
144
+ appendFileSync(examplePath, fixText(added, !exampleText?.trim()));
145
+ io.out(`${paint.green("✓")} added ${plural(added.length, "key")} to ${display(exampleName)}: ${added.map((f) => f.key).join(", ")}`);
146
+ exampleText = readFileSync(examplePath, "utf8");
147
+ all = runCheck(parseEnv(exampleText));
148
+ findings = shown(all);
149
+ } else {
150
+ io.out(`${paint.green("✓")} ${display(exampleName)} already documents every key the code reads`);
151
+ }
152
+ }
153
+
154
+ const errors = findings.filter((f) => f.severity === "error").length;
155
+ const warnings = findings.length - errors;
156
+ const files = scan ? scan.files : 0;
157
+ const hiddenDefaulted = all.length - findings.length;
158
+ const frameworks = scan ? scan.implicit.map((i) => i.source) : [];
159
+ io.githubOutput?.(`errors=${errors}\nwarnings=${warnings}`);
160
+
161
+ if (opt.json) {
162
+ const dynamic = (scan?.dynamic ?? []).map((d) => ({ ...d, file: display(d.file) }));
163
+ const report = { ok: errors === 0, errors, warnings, scannedFiles: files, frameworks, hiddenDefaulted, findings, dynamic };
164
+ io.out(JSON.stringify(report, null, 2));
165
+ return errors ? 1 : 0;
166
+ }
167
+
168
+ const format = opt.format ?? (io.githubActions ? "github" : "pretty");
169
+ if (format === "github") {
170
+ for (const f of findings) {
171
+ const level = f.severity === "error" ? "error" : "warning";
172
+ const where = `file=${f.file}${f.line ? `,line=${f.line}` : ""}`;
173
+ io.out(`::${level} ${where},title=envsonar ${f.code}::${f.key ? `${f.key} ` : ""}${f.message}`);
174
+ }
175
+ }
176
+
177
+ const header = scan
178
+ ? paint.dim(`envsonar · ${files} files scanned · ${scan.usages.size} keys in code · ${example.entries.size} in ${display(exampleName)}${env ? ` · ${display(envName)} checked` : ""}`)
179
+ : paint.dim(`envsonar · ${display(exampleName)}${env ? ` vs ${display(envName)}` : ""}`);
180
+ io.out(header);
181
+ if (frameworks.length) io.out(paint.dim(`also read by: ${frameworks.join(", ")}`));
182
+ const notes = () => {
183
+ if (hiddenDefaulted) io.out(paint.dim(`${plural(hiddenDefaulted, "key")} with a default in code not in ${display(exampleName)} — show with --optional`));
184
+ if (scan?.dynamic.length) {
185
+ const where = scan.dynamic.slice(0, 3).map((d) => `${display(d.file)}:${d.line}`).join(", ");
186
+ io.out(paint.dim(`${plural(scan.dynamic.length, "dynamic read")} can't be checked: ${where}${scan.dynamic.length > 3 ? ", …" : ""}`));
187
+ }
188
+ };
189
+
190
+ if (findings.length === 0) {
191
+ io.out(`${paint.green("✓")} all in sync`);
192
+ notes();
193
+ return 0;
194
+ }
195
+
196
+ io.out("");
197
+ const width = Math.max(...findings.map((f) => (f.key ?? "").length), 3);
198
+ const msgWidth = Math.max(...findings.map((f) => f.message.length));
199
+ for (const f of findings) {
200
+ const mark = f.severity === "error" ? paint.red("✗") : paint.yellow("!");
201
+ const more = f.usages && f.usages.length > 1 ? paint.dim(` (+${f.usages.length - 1})`) : "";
202
+ const where = paint.dim(`${f.file}${f.line ? `:${f.line}` : ""}`) + more;
203
+ io.out(` ${mark} ${paint.bold((f.key ?? "").padEnd(width))} ${f.message.padEnd(msgWidth)} ${where}`);
204
+ }
205
+ const summary = [errors && paint.red(plural(errors, "error")), warnings && paint.yellow(plural(warnings, "warning"))].filter(Boolean).join(", ");
206
+ const undocumented = findings.filter((f) => f.code === "undocumented").length;
207
+ const hint = undocumented ? paint.dim(` · run envsonar --fix to add ${plural(undocumented, "key")} to ${display(exampleName)}`) : "";
208
+ io.out(`\n${summary}${hint}`);
209
+ notes();
210
+ return errors ? 1 : 0;
211
+ }
212
+
213
+ /**
214
+ * @param {import("./scan.js").ScanResult} scan
215
+ * @param {boolean} json
216
+ * @param {ReturnType<typeof painter>} paint
217
+ * @param {Io} io
218
+ * @param {(p: string) => string} display
219
+ */
220
+ function list(scan, json, paint, io, display) {
221
+ const keys = [...scan.usages].sort(([a], [b]) => a.localeCompare(b));
222
+ const frameworks = scan.implicit.map((i) => i.source);
223
+ if (json) {
224
+ const report = { keys: Object.fromEntries(keys), sections: Object.fromEntries(scan.sections), dynamic: scan.dynamic, frameworks };
225
+ io.out(JSON.stringify(report, null, 2));
226
+ return 0;
227
+ }
228
+ io.out(paint.dim(`envsonar · ${scan.files} files scanned · ${keys.length} keys`));
229
+ if (frameworks.length) io.out(paint.dim(`also read by: ${frameworks.join(", ")}`));
230
+ const width = Math.max(...keys.map(([k]) => k.length), 3);
231
+ for (const [key, uses] of keys) {
232
+ const more = uses.length > 1 ? paint.dim(` (+${uses.length - 1})`) : "";
233
+ const tag = uses.every((u) => u.optional) ? paint.dim(" default") : "";
234
+ io.out(` ${paint.bold(key.padEnd(width))} ${paint.dim(`${display(uses[0].file)}:${uses[0].line}`)}${more}${tag}`);
235
+ }
236
+ for (const [prefix, uses] of scan.sections) io.out(` ${paint.bold(`${prefix}*`.padEnd(width))} ${paint.dim(`${display(uses[0].file)}:${uses[0].line} section`)}`);
237
+ for (const d of scan.dynamic) io.out(` ${paint.yellow("?")} ${paint.dim(`${d.expr} ${display(d.file)}:${d.line} dynamic, not checked`)}`);
238
+ return 0;
239
+ }
240
+
241
+ /**
242
+ * @param {string} root
243
+ * @param {Io} io
244
+ * @returns {Config | null}
245
+ */
246
+ function loadConfig(root, io) {
247
+ for (const [file, pick] of /** @type {const} */ ([
248
+ [".envsonarrc.json", (/** @type {any} */ j) => j],
249
+ ["package.json", (/** @type {any} */ j) => j.envsonar],
250
+ ])) {
251
+ const text = readOptional(resolve(root, file), io);
252
+ if (text === undefined) return null;
253
+ if (text === null) continue;
254
+ try {
255
+ const config = pick(JSON.parse(text));
256
+ if (config === undefined) continue;
257
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new Error("expected an object");
258
+ return /** @type {Config} */ (config);
259
+ } catch (e) {
260
+ io.err(`envsonar: invalid config in ${file}: ${e instanceof Error ? e.message : String(e)}`);
261
+ return null;
262
+ }
263
+ }
264
+ return {};
265
+ }
266
+
267
+ /**
268
+ * @param {string} path
269
+ * @param {Io} io
270
+ * @returns {string | null | undefined} null when the file doesn't exist, undefined when it can't be read
271
+ */
272
+ function readOptional(path, io) {
273
+ try {
274
+ return readFileSync(path, "utf8");
275
+ } catch (e) {
276
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code;
277
+ if (code === "ENOENT") return null;
278
+ io.err(`envsonar: cannot read ${path} (${code ?? "unknown error"})`);
279
+ return undefined;
280
+ }
281
+ }
282
+
283
+ /** @param {Io} io @param {string} message */
284
+ function usage(io, message) {
285
+ io.err(`envsonar: ${message}\nRun "envsonar --help" for usage.`);
286
+ return 2;
287
+ }
288
+
289
+ /** @param {Io} io @param {string} message */
290
+ function fail(io, message) {
291
+ io.err(`envsonar: ${message}`);
292
+ return 2;
293
+ }
294
+
295
+ /** @param {number} n @param {string} word */
296
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
297
+
298
+ /** @param {boolean} on */
299
+ function painter(on) {
300
+ /** @param {number} a @param {number} b */
301
+ const wrap = (a, b) => (/** @type {string} */ s) => (on ? `\x1b[${a}m${s}\x1b[${b}m` : s);
302
+ return { red: wrap(31, 39), green: wrap(32, 39), yellow: wrap(33, 39), dim: wrap(2, 22), bold: wrap(1, 22) };
303
+ }