@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/check.js CHANGED
@@ -1,146 +1,157 @@
1
- // @ts-check
2
- import { keyMatcher } from "./scan.js";
3
-
4
- /**
5
- * @typedef {import("./parse.js").ParsedEnv} ParsedEnv
6
- * @typedef {import("./scan.js").Usage} Usage
7
- * @typedef {import("./scan.js").ScanResult} ScanResult
8
- * @typedef {"error" | "warning"} Severity
9
- * @typedef {"undocumented" | "defaulted" | "unused" | "missing" | "empty" | "extra" | "duplicate" | "syntax"} Code
10
- * @typedef {{
11
- * severity: Severity,
12
- * code: Code,
13
- * key?: string,
14
- * file: string,
15
- * line?: number,
16
- * message: string,
17
- * usages?: Usage[],
18
- * }} Finding
19
- * @typedef {{
20
- * example: ParsedEnv,
21
- * exampleFile: string,
22
- * env?: ParsedEnv | null,
23
- * envFile?: string,
24
- * scan?: ScanResult | null,
25
- * strict?: boolean,
26
- * }} CheckInput
27
- */
28
-
29
- /**
30
- * Cross-checks three sources of truth: the code, .env.example and (when present) .env.
31
- * Findings carry key names, files and line numbers only — values are never copied,
32
- * so a report can't leak a secret.
33
- *
34
- * Reads with a fallback in code come back as `defaulted` (a warning) instead of `undocumented`;
35
- * callers decide whether to show them.
36
- *
37
- * @param {CheckInput} input
38
- * @returns {Finding[]}
39
- */
40
- export function check({ example, exampleFile, env = null, envFile = ".env", scan = null, strict = false }) {
41
- /** @type {Severity} */
42
- const warn = strict ? "error" : "warning";
43
- /** @type {Finding[]} */
44
- const findings = [];
45
-
46
- /** @type {[ParsedEnv, string][]} */
47
- const files = [[example, exampleFile]];
48
- if (env) files.push([env, envFile]);
49
- for (const [parsed, file] of files) {
50
- for (const e of parsed.errors) findings.push({ severity: "error", code: "syntax", file, line: e.line, message: e.message });
51
- for (const d of parsed.duplicates) {
52
- findings.push({
53
- severity: warn,
54
- code: "duplicate",
55
- key: d.key,
56
- file,
57
- line: d.lines[d.lines.length - 1],
58
- message: `defined ${d.lines.length} times (lines ${d.lines.join(", ")})`,
59
- });
60
- }
61
- }
62
-
63
- if (scan) {
64
- const exampleLower = new Set([...example.entries.keys()].map((k) => k.toLowerCase()));
65
- for (const [key, uses] of [...scan.usages].sort(([a], [b]) => a.localeCompare(b))) {
66
- const ci = uses.every((u) => u.ci);
67
- if (example.entries.has(key) || (ci && exampleLower.has(key.toLowerCase()))) continue;
68
- const provided = scan.provided.get(key.toLowerCase());
69
- if (provided && (ci || provided.key === key)) continue;
70
- const defaulted = uses.every((u) => u.optional);
71
- findings.push({
72
- severity: defaulted ? warn : "error",
73
- code: defaulted ? "defaulted" : "undocumented",
74
- key,
75
- file: uses[0].file,
76
- line: uses[0].line,
77
- message: defaulted ? `has a default in code, missing from ${exampleFile}` : `used in code, missing from ${exampleFile}`,
78
- usages: uses,
79
- });
80
- }
81
-
82
- const consumed = consumedBy(scan);
83
- for (const [key, entry] of example.entries) {
84
- if (!consumed(key)) {
85
- findings.push({ severity: warn, code: "unused", key, file: exampleFile, line: entry.line, message: "documented but never read in code" });
86
- }
87
- }
88
- }
89
-
90
- if (env) {
91
- // a key the code reads with a fallback (or not at all) can be left out of .env: that's a warning, not an error
92
- const needed = (/** @type {string} */ key) => !scan || Boolean(scan.usages.get(key)?.some((u) => !u.optional));
93
- for (const [key, entry] of example.entries) {
94
- const actual = env.entries.get(key);
95
- if (!actual) {
96
- const severity = needed(key) ? "error" : warn;
97
- findings.push({ severity, code: "missing", key, file: exampleFile, line: entry.line, message: `not set in ${envFile}` });
98
- } else if (actual.value === "") {
99
- findings.push({ severity: warn, code: "empty", key, file: envFile, line: actual.line, message: "is empty" });
100
- }
101
- }
102
- for (const [key, entry] of env.entries) {
103
- if (!example.entries.has(key)) {
104
- findings.push({ severity: warn, code: "extra", key, file: envFile, line: entry.line, message: `not documented in ${exampleFile}` });
105
- }
106
- }
107
- }
108
-
109
- // errors first; sort is stable, so the order inside each group is kept
110
- return findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
111
- }
112
-
113
- /**
114
- * Does anything read this key: the code, a bound .NET config section, appsettings.json, or an SDK / framework / image?
115
- *
116
- * @param {ScanResult} scan
117
- * @returns {(key: string) => boolean}
118
- */
119
- function consumedBy(scan) {
120
- const ciKeys = new Set([...scan.usages].filter(([, uses]) => uses.some((u) => u.ci)).map(([k]) => k.toLowerCase()));
121
- const sections = [...scan.sections.keys()].map((p) => p.toLowerCase());
122
- const implicit = keyMatcher(scan.implicit.flatMap((i) => i.keys));
123
- return (key) => {
124
- const lower = key.toLowerCase();
125
- if (scan.usages.has(key) || ciKeys.has(lower) || implicit(key)) return true;
126
- if (sections.some((p) => lower.startsWith(p))) return true;
127
- return /(^|\/)appsettings[^/]*\.json$/i.test(scan.provided.get(lower)?.source ?? "");
128
- };
129
- }
130
-
131
- /**
132
- * Text to append to .env.example so every given key gets an empty entry,
133
- * each with a comment pointing at where the code reads it.
134
- *
135
- * @param {Finding[]} findings `undocumented` (and, if wanted, `defaulted`) findings
136
- * @param {boolean} fileIsEmpty
137
- */
138
- export function fixText(findings, fileIsEmpty) {
139
- const add = findings.filter((f) => (f.code === "undocumented" || f.code === "defaulted") && f.key);
140
- if (add.length === 0) return "";
141
- const lines = fileIsEmpty ? [] : [""];
142
- lines.push("# added by envsonar");
143
- // the hint goes on its own line: Docker's env_file and some loaders treat inline `#` as part of the value
144
- for (const f of add) lines.push(`# read in ${f.file}:${f.line}${f.code === "defaulted" ? " (has a default)" : ""}`, `${f.key}=`);
145
- return lines.join("\n") + "\n";
146
- }
1
+ // @ts-check
2
+ import { keyMatcher } from "./scan.js";
3
+
4
+ /**
5
+ * @typedef {import("./parse.js").ParsedEnv} ParsedEnv
6
+ * @typedef {import("./scan.js").Usage} Usage
7
+ * @typedef {import("./scan.js").ScanResult} ScanResult
8
+ * @typedef {"error" | "warning"} Severity
9
+ * @typedef {"undocumented" | "defaulted" | "unused" | "missing" | "empty" | "extra" | "duplicate" | "syntax"} Code
10
+ * @typedef {{
11
+ * severity: Severity,
12
+ * code: Code,
13
+ * key?: string,
14
+ * file: string,
15
+ * line?: number,
16
+ * message: string,
17
+ * usages?: Usage[],
18
+ * }} Finding
19
+ * @typedef {{
20
+ * example: ParsedEnv,
21
+ * exampleFile: string,
22
+ * env?: ParsedEnv | null,
23
+ * envFile?: string,
24
+ * scan?: ScanResult | null,
25
+ * strict?: boolean,
26
+ * }} CheckInput
27
+ */
28
+
29
+ /**
30
+ * Cross-checks three sources of truth: the code, .env.example and (when present) .env.
31
+ * Findings carry key names, files and line numbers only — values are never copied,
32
+ * so a report can't leak a secret.
33
+ *
34
+ * Reads with a fallback in code come back as `defaulted` (a warning) instead of `undocumented`;
35
+ * callers decide whether to show them.
36
+ *
37
+ * @param {CheckInput} input
38
+ * @returns {Finding[]}
39
+ */
40
+ export function check({ example, exampleFile, env = null, envFile = ".env", scan = null, strict = false }) {
41
+ /** @type {Severity} */
42
+ const warn = strict ? "error" : "warning";
43
+ /** @type {Finding[]} */
44
+ const findings = [];
45
+
46
+ /** @type {[ParsedEnv, string][]} */
47
+ const files = [[example, exampleFile]];
48
+ if (env) files.push([env, envFile]);
49
+ for (const [parsed, file] of files) {
50
+ for (const e of parsed.errors) findings.push({ severity: "error", code: "syntax", file, line: e.line, message: e.message });
51
+ for (const d of parsed.duplicates) {
52
+ findings.push({
53
+ severity: warn,
54
+ code: "duplicate",
55
+ key: d.key,
56
+ file,
57
+ line: d.lines[d.lines.length - 1],
58
+ message: `defined ${d.lines.length} times (lines ${d.lines.join(", ")})`,
59
+ });
60
+ }
61
+ }
62
+
63
+ if (scan) {
64
+ const exampleLower = new Set([...example.entries.keys()].map((k) => k.toLowerCase()));
65
+ for (const [key, uses] of [...scan.usages].sort(([a], [b]) => a.localeCompare(b))) {
66
+ const ci = uses.every((u) => u.ci);
67
+ if (example.entries.has(key) || (ci && exampleLower.has(key.toLowerCase()))) continue;
68
+ const provided = scan.provided.get(key.toLowerCase());
69
+ if (provided?.base && (ci || provided.key === key)) continue;
70
+ const defaulted = uses.every((u) => u.optional);
71
+ findings.push({
72
+ severity: defaulted ? warn : "error",
73
+ code: defaulted ? "defaulted" : "undocumented",
74
+ key,
75
+ file: uses[0].file,
76
+ line: uses[0].line,
77
+ message: defaulted ? `has a default in code, missing from ${exampleFile}` : `used in code, missing from ${exampleFile}`,
78
+ usages: uses,
79
+ });
80
+ }
81
+
82
+ const consumed = consumedBy(scan);
83
+ for (const [key, entry] of example.entries) {
84
+ if (!consumed(key)) {
85
+ findings.push({ severity: warn, code: "unused", key, file: exampleFile, line: entry.line, message: "documented but never read in code" });
86
+ }
87
+ }
88
+ }
89
+
90
+ if (env) {
91
+ // .NET config and pydantic match names case-insensitively, so `Jwt__Key` in code is `JWT__KEY` in the env files
92
+ /** @type {Map<string, Usage[]>} */
93
+ const ciUsages = new Map();
94
+ for (const [key, uses] of scan?.usages ?? []) {
95
+ if (uses.some((u) => u.ci)) ciUsages.set(key.toLowerCase(), [...(ciUsages.get(key.toLowerCase()) ?? []), ...uses]);
96
+ }
97
+ const usesOf = (/** @type {string} */ key) => scan?.usages.get(key) ?? ciUsages.get(key.toLowerCase());
98
+ const envLower = new Map([...env.entries].map(([k, e]) => [k.toLowerCase(), e]));
99
+ const lookup = (/** @type {string} */ key) => env.entries.get(key) ?? (ciUsages.has(key.toLowerCase()) ? envLower.get(key.toLowerCase()) : undefined);
100
+ // a key the code reads with a fallback (or not at all) can be left out of .env: that's a warning, not an error
101
+ const needed = (/** @type {string} */ key) => !scan || Boolean(usesOf(key)?.some((u) => !u.optional));
102
+ for (const [key, entry] of example.entries) {
103
+ const actual = lookup(key);
104
+ if (!actual) {
105
+ const severity = needed(key) ? "error" : warn;
106
+ findings.push({ severity, code: "missing", key, file: exampleFile, line: entry.line, message: `not set in ${envFile}` });
107
+ } else if (actual.value === "") {
108
+ findings.push({ severity: warn, code: "empty", key, file: envFile, line: actual.line, message: "is empty" });
109
+ }
110
+ }
111
+ const exampleKeysLower = new Set([...example.entries.keys()].map((k) => k.toLowerCase()));
112
+ for (const [key, entry] of env.entries) {
113
+ const lower = key.toLowerCase();
114
+ if (!example.entries.has(key) && !(ciUsages.has(lower) && exampleKeysLower.has(lower))) {
115
+ findings.push({ severity: warn, code: "extra", key, file: envFile, line: entry.line, message: `not documented in ${exampleFile}` });
116
+ }
117
+ }
118
+ }
119
+
120
+ // errors first; sort is stable, so the order inside each group is kept
121
+ return findings.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
122
+ }
123
+
124
+ /**
125
+ * Does anything read this key: the code, a bound .NET config section, appsettings.json, or an SDK / framework / image?
126
+ *
127
+ * @param {ScanResult} scan
128
+ * @returns {(key: string) => boolean}
129
+ */
130
+ function consumedBy(scan) {
131
+ const ciKeys = new Set([...scan.usages].filter(([, uses]) => uses.some((u) => u.ci)).map(([k]) => k.toLowerCase()));
132
+ const sections = [...scan.sections.keys()].map((p) => p.toLowerCase());
133
+ const implicit = keyMatcher(scan.implicit.flatMap((i) => i.keys));
134
+ return (key) => {
135
+ const lower = key.toLowerCase();
136
+ if (scan.usages.has(key) || ciKeys.has(lower) || implicit(key)) return true;
137
+ if (sections.some((p) => lower.startsWith(p))) return true;
138
+ return /(^|\/)appsettings[^/]*\.json$/i.test(scan.provided.get(lower)?.source ?? "");
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Text to append to .env.example so every given key gets an empty entry,
144
+ * each with a comment pointing at where the code reads it.
145
+ *
146
+ * @param {Finding[]} findings `undocumented` (and, if wanted, `defaulted`) findings
147
+ * @param {boolean} fileIsEmpty
148
+ */
149
+ export function fixText(findings, fileIsEmpty) {
150
+ const add = findings.filter((f) => (f.code === "undocumented" || f.code === "defaulted") && f.key);
151
+ if (add.length === 0) return "";
152
+ const lines = fileIsEmpty ? [] : [""];
153
+ lines.push("# added by envsonar");
154
+ // the hint goes on its own line: Docker's env_file and some loaders treat inline `#` as part of the value
155
+ for (const f of add) lines.push(`# read in ${f.file}:${f.line}${f.code === "defaulted" ? " (has a default)" : ""}`, `${f.key}=`);
156
+ return lines.join("\n") + "\n";
157
+ }