@jutaru-dev/envsonar 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/envsonar.js +13 -0
- package/package.json +55 -4
- package/src/check.js +157 -0
- package/src/cli.js +303 -0
- package/src/index.js +5 -0
- package/src/parse.js +99 -0
- package/src/profiles.js +80 -0
- package/src/scan.js +796 -0
- package/types/check.d.ts +66 -0
- package/types/cli.d.ts +34 -0
- package/types/index.d.ts +4 -0
- package/types/parse.d.ts +26 -0
- package/types/profiles.d.ts +15 -0
- package/types/scan.d.ts +156 -0
package/src/scan.js
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, extname, join, relative, sep } from "node:path";
|
|
4
|
+
import { PROFILES } from "./profiles.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {{ optional?: boolean, ci?: boolean, schema?: boolean }} Flags
|
|
8
|
+
* optional — the code has a fallback value; ci — the name is matched case-insensitively (.NET config, pydantic)
|
|
9
|
+
* @typedef {{ file: string, line: number } & Flags} Usage
|
|
10
|
+
* @typedef {{ key: string, line: number } & Flags} Found
|
|
11
|
+
* @typedef {{ file: string, line: number, expr: string }} DynamicRead
|
|
12
|
+
* @typedef {{ source: string, keys: string[] }} Implicit
|
|
13
|
+
* @typedef {{ key: string, source: string, base: boolean }} Provided
|
|
14
|
+
* base — the value applies in every environment (appsettings.json, compose); false for appsettings.<Environment>.json
|
|
15
|
+
* @typedef {{ cls: string, line: number, section?: string, sectionOf?: string }} Binding
|
|
16
|
+
* @typedef {{ name: string, line: number, optional: boolean }} OptionProp
|
|
17
|
+
* @typedef {{ props: OptionProp[], sectionName?: string }} OptionClass
|
|
18
|
+
* @typedef {{
|
|
19
|
+
* files: number,
|
|
20
|
+
* usages: Map<string, Usage[]>,
|
|
21
|
+
* sections: Map<string, Usage[]>,
|
|
22
|
+
* dynamic: DynamicRead[],
|
|
23
|
+
* provided: Map<string, Provided>,
|
|
24
|
+
* implicit: Implicit[],
|
|
25
|
+
* }} ScanResult
|
|
26
|
+
* @typedef {{
|
|
27
|
+
* add: (key: string, line: number, flags?: Flags) => void,
|
|
28
|
+
* section: (prefix: string, line: number) => void,
|
|
29
|
+
* dynamic: (expr: string, line: number) => void,
|
|
30
|
+
* provide: (key: string, source: string, base?: boolean) => void,
|
|
31
|
+
* bind: (binding: Binding) => void,
|
|
32
|
+
* optionClass: (name: string, cls: OptionClass) => void,
|
|
33
|
+
* mark: (marker: string) => void,
|
|
34
|
+
* lineAt: (offset: number) => number,
|
|
35
|
+
* }} Sink
|
|
36
|
+
* @typedef {{ re: RegExp, call?: boolean, member?: boolean, optional?: boolean }} Pattern
|
|
37
|
+
* @typedef {{ line: string[], block: [string, string][], quotes: string, multiline?: string, triple?: boolean, lineAfterSpace?: boolean }} CommentStyle
|
|
38
|
+
* @typedef {{ name: string, test: (file: string) => boolean, comments?: CommentStyle, patterns: Pattern[], extra?: (text: string, sink: Sink, file: string) => void }} Language
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
const K = String.raw`(?<key>[A-Za-z_][A-Za-z0-9_]*)`;
|
|
42
|
+
const Q = String.raw`(?<q>['"\x60])`;
|
|
43
|
+
const QS = String.raw`\k<q>`;
|
|
44
|
+
const JS_ENV = String.raw`(?:process\.env|import\.meta\.env|Bun\.env)`;
|
|
45
|
+
const NET_PATH = String.raw`(?<path>[A-Za-z_][\w.-]*(?::[\w.-]+)*)`;
|
|
46
|
+
|
|
47
|
+
/** @param {string} source */
|
|
48
|
+
const re = (source) => new RegExp(source, "g");
|
|
49
|
+
/** @param {...string} exts */
|
|
50
|
+
const byExt = (...exts) => (/** @type {string} */ file) => exts.includes(extname(file).toLowerCase());
|
|
51
|
+
/** @param {RegExp} pattern */
|
|
52
|
+
const byName = (pattern) => (/** @type {string} */ file) => pattern.test(basename(file));
|
|
53
|
+
|
|
54
|
+
/** a fallback right after a call: `getenv("X", 1)`, `GetEnvironmentVariable("X") ?? "a"`, `env::var("X").unwrap_or(..)`, `ENV.fetch("X") { }` */
|
|
55
|
+
const CALL_DEFAULT = /^\s*(?:,\s*[^\s)]|\)\s*(?:\?\?|\|\||or\b|\.unwrap_or|\.or\b|\{))/;
|
|
56
|
+
/** a fallback after a property read: `process.env.X ?? "a"`, `ENV["X"] || "a"` */
|
|
57
|
+
const MEMBER_DEFAULT = /^\s*(?:\?\?|\|\|)/;
|
|
58
|
+
/** a write, not a read: `process.env.X = "1"`, `os.environ["X"] += ...`, `process.env.X ??= ...` */
|
|
59
|
+
const ASSIGNMENT = /^\s*(?:=(?![=>])|[-+*%&|^]=|\/=|\?\?=|\|\|=|&&=|\+\+|--)/;
|
|
60
|
+
/** `delete process.env.X`, `del os.environ["X"]` */
|
|
61
|
+
const DELETION = /\b(?:delete|del)\s+(?:os\.)?$/;
|
|
62
|
+
|
|
63
|
+
/** @type {Record<string, CommentStyle>} */
|
|
64
|
+
export const COMMENT_STYLES = {
|
|
65
|
+
c: { line: ["//"], block: [["/*", "*/"]], quotes: "'\"`", multiline: "`" },
|
|
66
|
+
rust: { line: ["//"], block: [["/*", "*/"]], quotes: '"' },
|
|
67
|
+
python: { line: ["#"], block: [], quotes: "'\"", triple: true },
|
|
68
|
+
ruby: { line: ["#"], block: [], quotes: "'\"" },
|
|
69
|
+
php: { line: ["//", "#"], block: [["/*", "*/"]], quotes: "'\"" },
|
|
70
|
+
yaml: { line: ["#"], block: [], quotes: "'\"", lineAfterSpace: true },
|
|
71
|
+
html: { line: [], block: [["<!--", "-->"]], quotes: "" },
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Blanks out comments (and Python docstrings) so reads inside them don't count. Strings are kept, so
|
|
76
|
+
* `"http://x"` isn't mistaken for a comment; newlines are kept, so line numbers don't move.
|
|
77
|
+
*
|
|
78
|
+
* @param {string} text
|
|
79
|
+
* @param {CommentStyle} style
|
|
80
|
+
*/
|
|
81
|
+
export function stripComments(text, style) {
|
|
82
|
+
const n = text.length;
|
|
83
|
+
let out = "";
|
|
84
|
+
let start = 0;
|
|
85
|
+
let i = 0;
|
|
86
|
+
const blank = (/** @type {number} */ from, /** @type {number} */ to) => {
|
|
87
|
+
out += text.slice(start, from) + text.slice(from, to).replace(/[^\n]/g, " ");
|
|
88
|
+
start = to;
|
|
89
|
+
};
|
|
90
|
+
scan: while (i < n) {
|
|
91
|
+
const ch = text[i];
|
|
92
|
+
if (style.triple && (text.startsWith('"""', i) || text.startsWith("'''", i))) {
|
|
93
|
+
const end = text.indexOf(text.slice(i, i + 3), i + 3);
|
|
94
|
+
const to = end < 0 ? n : end + 3;
|
|
95
|
+
blank(i, to);
|
|
96
|
+
i = to;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (style.quotes.includes(ch)) {
|
|
100
|
+
const multi = style.multiline?.includes(ch);
|
|
101
|
+
let j = i + 1;
|
|
102
|
+
while (j < n && text[j] !== ch && (multi || text[j] !== "\n")) j += text[j] === "\\" ? 2 : 1;
|
|
103
|
+
i = j + 1;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
for (const open of style.line) {
|
|
107
|
+
if (text.startsWith(open, i) && (!style.lineAfterSpace || i === 0 || /\s/.test(text[i - 1]))) {
|
|
108
|
+
const end = text.indexOf("\n", i);
|
|
109
|
+
const to = end < 0 ? n : end;
|
|
110
|
+
blank(i, to);
|
|
111
|
+
i = to;
|
|
112
|
+
continue scan;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const [open, close] of style.block) {
|
|
116
|
+
if (text.startsWith(open, i)) {
|
|
117
|
+
const end = text.indexOf(close, i + open.length);
|
|
118
|
+
const to = end < 0 ? n : end + close.length;
|
|
119
|
+
blank(i, to);
|
|
120
|
+
i = to;
|
|
121
|
+
continue scan;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
i++;
|
|
125
|
+
}
|
|
126
|
+
return out + text.slice(start);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The expression that starts at `from` and runs to the next top-level `,` or the closing bracket:
|
|
131
|
+
* `z.coerce\n .number()\n .default(3000)` as one piece, however a formatter wrapped it.
|
|
132
|
+
*
|
|
133
|
+
* @param {string} text
|
|
134
|
+
* @param {number} from
|
|
135
|
+
*/
|
|
136
|
+
function expressionAt(text, from) {
|
|
137
|
+
let depth = 0;
|
|
138
|
+
const limit = Math.min(text.length, from + 2000);
|
|
139
|
+
for (let i = from; i < limit; i++) {
|
|
140
|
+
const ch = text[i];
|
|
141
|
+
if (ch === "(" || ch === "[" || ch === "{") depth++;
|
|
142
|
+
else if (ch === ")" || ch === "]" || ch === "}") {
|
|
143
|
+
if (depth === 0) return text.slice(from, i);
|
|
144
|
+
depth--;
|
|
145
|
+
} else if (ch === "," && depth === 0) return text.slice(from, i);
|
|
146
|
+
}
|
|
147
|
+
return text.slice(from, limit);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Reads through a local alias of the environment: `const env = process.env; env.KEY`, `env = dict(os.environ); env.get("KEY")`.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} text
|
|
154
|
+
* @param {string} alias
|
|
155
|
+
* @param {Sink} sink
|
|
156
|
+
* @param {"js" | "py"} lang
|
|
157
|
+
*/
|
|
158
|
+
function readsVia(text, alias, sink, lang) {
|
|
159
|
+
const n = alias.replace(/\$/g, "\\$");
|
|
160
|
+
/** @type {Pattern[]} */
|
|
161
|
+
const patterns = [
|
|
162
|
+
{ re: re(String.raw`(?<![\w$.])${n}\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
163
|
+
{ re: re(String.raw`(?<![\w$.])${n}\.(?:get|setdefault|pop)\(\s*${Q}${K}${QS}`), call: true },
|
|
164
|
+
];
|
|
165
|
+
if (lang === "js") patterns.push({ re: re(String.raw`(?<![\w$.])${n}\.${K}\b(?!\s*\()`), member: true });
|
|
166
|
+
applyPatterns(text, patterns, sink);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** @param {string} text @param {Sink} sink */
|
|
170
|
+
function jsExtra(text, sink) {
|
|
171
|
+
// const { A, B: alias, C = "x" } = process.env
|
|
172
|
+
for (const m of text.matchAll(re(String.raw`\{([^{}]*)\}\s*=\s*${JS_ENV}\b`))) {
|
|
173
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
174
|
+
for (const part of m[1].split(",")) {
|
|
175
|
+
const name = part.trim().split(/[:=\s]/)[0];
|
|
176
|
+
if (/^[A-Za-z_]\w*$/.test(name)) sink.add(name, line, { optional: part.includes("=") });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const aliases = [...text.matchAll(re(String.raw`\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*${JS_ENV}\s*(?=[;\n]|$)`))].map((m) => m[1]);
|
|
181
|
+
|
|
182
|
+
// SvelteKit: import { PUBLIC_API } from "$env/static/public"; import { env } from "$env/dynamic/private"
|
|
183
|
+
for (const m of text.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]\$env\/(static|dynamic)\/(?:public|private)['"]/g)) {
|
|
184
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
185
|
+
for (const part of m[1].split(",")) {
|
|
186
|
+
const [name, , local] = part.trim().split(/\s+/);
|
|
187
|
+
if (m[2] === "dynamic" && name === "env") aliases.push(local ?? "env");
|
|
188
|
+
else if (name && /^[A-Za-z_]\w*$/.test(name)) sink.add(name, line);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
for (const alias of aliases) readsVia(text, alias, sink, "js");
|
|
192
|
+
|
|
193
|
+
for (const m of text.matchAll(re(String.raw`\b${JS_ENV}\[([^\]\n]{1,80})\]`))) {
|
|
194
|
+
if (!/^\s*(['"`])[A-Za-z_]\w*\1\s*$/.test(m[1])) sink.dynamic(m[0], sink.lineAt(m.index ?? 0));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// envalid: cleanEnv(process.env, { PORT: port({ default: 3000 }) })
|
|
198
|
+
if (/\bcleanEnv\s*\(/.test(text)) {
|
|
199
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*(?:str|num|bool|port|url|email|host|json)\s*\(/g)) {
|
|
200
|
+
const expr = expressionAt(text, (m.index ?? 0) + m[0].length);
|
|
201
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\bdefault\s*:/.test(expr), schema: true });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// zod schemas parsed from the environment, and @t3-oss/env: createEnv({ server: { DATABASE_URL: z.string() } })
|
|
205
|
+
if (/\bcreateEnv\s*\(|\b(?:safeParse|parse)\(\s*(?:process\.env|import\.meta\.env)\b/.test(text)) {
|
|
206
|
+
for (const m of text.matchAll(/\b([A-Z][A-Z0-9_]*)\s*:\s*z\s*\./g)) {
|
|
207
|
+
const expr = expressionAt(text, (m.index ?? 0) + m[0].length);
|
|
208
|
+
// the schema decides: t3-env's `runtimeEnv: { PORT: process.env.PORT }` only passes the value through
|
|
209
|
+
sink.add(m[1], sink.lineAt(m.index ?? 0), { optional: /\.\s*(?:default|optional)\s*\(/.test(expr), schema: true });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** @param {string} text @param {Sink} sink */
|
|
215
|
+
function pyExtra(text, sink) {
|
|
216
|
+
for (const m of text.matchAll(/^[ \t]*([A-Za-z_]\w*)\s*=\s*(?:dict\(\s*)?(?:os\.)?environ\b(?:\.copy\(\))?\s*\)?[ \t]*(?:#.*)?$/gm)) {
|
|
217
|
+
readsVia(text, m[1], sink, "py");
|
|
218
|
+
}
|
|
219
|
+
for (const m of text.matchAll(/\b(?:getenv|environ\.get)\(\s*[A-Za-z_][\w.]*\s*[,)]|\benviron\[\s*[A-Za-z_][\w.]*\s*\]/g)) {
|
|
220
|
+
sink.dynamic(m[0].replace(/\s*,$/, ")"), sink.lineAt(m.index ?? 0));
|
|
221
|
+
}
|
|
222
|
+
pydanticSettings(text, sink);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* pydantic-settings: every field of a `BaseSettings` class is an environment variable,
|
|
227
|
+
* named after the field (case-insensitive) with the class's `env_prefix`, unless it has an alias.
|
|
228
|
+
*
|
|
229
|
+
* @param {string} text
|
|
230
|
+
* @param {Sink} sink
|
|
231
|
+
*/
|
|
232
|
+
function pydanticSettings(text, sink) {
|
|
233
|
+
if (!text.includes("BaseSettings")) return;
|
|
234
|
+
const lines = text.split(/\r?\n/);
|
|
235
|
+
const indentOf = (/** @type {string} */ l) => l.length - l.trimStart().length;
|
|
236
|
+
for (let i = 0; i < lines.length; i++) {
|
|
237
|
+
const head = /^([ \t]*)class\s+\w+\s*\(([^)]*)\)\s*:/.exec(lines[i]);
|
|
238
|
+
if (!head || !/\bBaseSettings\b/.test(head[2])) continue;
|
|
239
|
+
/** @type {[number, string][]} */
|
|
240
|
+
const body = [];
|
|
241
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
242
|
+
const l = lines[j];
|
|
243
|
+
if (!l.trim() || l.trim().startsWith("#")) continue;
|
|
244
|
+
if (indentOf(l) <= head[1].length) break;
|
|
245
|
+
body.push([j, l]);
|
|
246
|
+
}
|
|
247
|
+
if (!body.length) continue;
|
|
248
|
+
const fieldIndent = indentOf(body[0][1]);
|
|
249
|
+
const prefix = /env_prefix\s*[=:]\s*['"]([^'"]*)['"]/.exec(body.map(([, l]) => l).join("\n"))?.[1] ?? "";
|
|
250
|
+
for (const [j, l] of body) {
|
|
251
|
+
if (indentOf(l) !== fieldIndent) continue;
|
|
252
|
+
const f = /^\s*([A-Za-z_]\w*)\s*:\s*([^=]*?)\s*(?:=\s*(.*))?$/.exec(l);
|
|
253
|
+
if (!f || f[1] === "model_config" || f[1].startsWith("_") || /\bClassVar\b/.test(f[2])) continue;
|
|
254
|
+
let value = f[3]?.trim();
|
|
255
|
+
// Field( spread over several lines by a formatter: read on until the parentheses balance
|
|
256
|
+
for (let k = j + 1; value !== undefined && k < lines.length && balance(value) > 0; k++) value = `${value} ${lines[k].trim()}`;
|
|
257
|
+
const alias = /\b(?:validation_)?alias\s*=\s*['"]([^'"]+)['"]/.exec(value ?? "")?.[1];
|
|
258
|
+
const optional =
|
|
259
|
+
value !== undefined &&
|
|
260
|
+
(!value.startsWith("Field(") || /\bdefault(?:_factory)?\s*=/.test(value) || /^Field\(\s*(?=[^\s.)])(?!\w+\s*=)/.test(value));
|
|
261
|
+
sink.add(alias ?? (prefix + f[1]).toUpperCase(), j + 1, { ci: true, optional });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** @param {string} s */
|
|
267
|
+
const balance = (s) => (s.match(/\(/g)?.length ?? 0) - (s.match(/\)/g)?.length ?? 0);
|
|
268
|
+
|
|
269
|
+
/** @param {string} path */
|
|
270
|
+
const netKey = (path) => path.replace(/:/g, "__");
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* .NET configuration: `config["Jwt:Key"]`, `GetValue<T>("Jwt:Key")`, `GetConnectionString("Db")` read the
|
|
274
|
+
* environment variables `Jwt__Key` and `ConnectionStrings__Db`; `GetSection("Jwt")` binds everything under `Jwt__`.
|
|
275
|
+
*
|
|
276
|
+
* @param {string} text
|
|
277
|
+
* @param {Sink} sink
|
|
278
|
+
*/
|
|
279
|
+
function csExtra(text, sink) {
|
|
280
|
+
/** @type {[RegExp, (m: RegExpMatchArray) => string][]} */
|
|
281
|
+
const reads = [
|
|
282
|
+
[re(String.raw`\b(?:[\w.]*[Cc]onfig\w*|Configuration)\s*\[\s*"${NET_PATH}"\s*\]`), (m) => netKey(m.groups?.path ?? "")],
|
|
283
|
+
[re(String.raw`\.GetValue(?:<[^>()]+>)?\(\s*"${NET_PATH}"`), (m) => netKey(m.groups?.path ?? "")],
|
|
284
|
+
[/\.GetConnectionString\(\s*"(?<name>[\w.-]+)"/g, (m) => `ConnectionStrings__${m.groups?.name}`],
|
|
285
|
+
];
|
|
286
|
+
for (const [pattern, keyOf] of reads) {
|
|
287
|
+
for (const m of text.matchAll(pattern)) {
|
|
288
|
+
const end = (m.index ?? 0) + m[0].length;
|
|
289
|
+
const after = text.slice(end, end + 40);
|
|
290
|
+
sink.add(keyOf(m), sink.lineAt(m.index ?? 0), { ci: true, optional: CALL_DEFAULT.test(after) || MEMBER_DEFAULT.test(after) });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
for (const m of text.matchAll(re(String.raw`\.(?:GetSection|GetRequiredSection|BindConfiguration)\(\s*"${NET_PATH}"`))) {
|
|
294
|
+
sink.section(`${netKey(m.groups?.path ?? "")}__`, sink.lineAt(m.index ?? 0));
|
|
295
|
+
}
|
|
296
|
+
optionsPattern(text, sink);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** @param {string} suffix */
|
|
300
|
+
const sectionArg = (suffix) => String.raw`(?:"(?<path${suffix}>[A-Za-z_][\w.:-]*)"|(?<owner${suffix}>\w+)\.SectionName)`;
|
|
301
|
+
/** non-nullable value types have a default (0, false) even without an initializer */
|
|
302
|
+
const VALUE_TYPE = /^(?:int|long|short|byte|bool|double|float|decimal|TimeSpan|DateTime|DateTimeOffset|Guid)$/;
|
|
303
|
+
const SIMPLE_TYPE = /^(?:string|String|int|long|short|byte|bool|double|float|decimal|TimeSpan|DateTime|DateTimeOffset|Guid|Uri)\??$/;
|
|
304
|
+
/** `= ""`, `= string.Empty`, `= null!` mean "must be configured", not a real default */
|
|
305
|
+
const PLACEHOLDER = /^(?:""|string\.Empty|String\.Empty|null!?|default!?)$/;
|
|
306
|
+
const OPTION_BINDINGS = [
|
|
307
|
+
re(String.raw`\bConfigure<(?<cls>\w+)>\([^;]*?\bGet(?:Required)?Section\(\s*${sectionArg("")}\s*\)`),
|
|
308
|
+
re(String.raw`\bGet(?:Required)?Section\(\s*${sectionArg("")}\s*\)\s*\.\s*Get<(?<cls>\w+)>`),
|
|
309
|
+
re(String.raw`\bAddOptions<(?<cls>\w+)>\(\s*\)[^;]*?\.\s*(?:BindConfiguration\(\s*${sectionArg("")}|Bind\([^;]*?\bGet(?:Required)?Section\(\s*${sectionArg("2")})`),
|
|
310
|
+
];
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The options pattern: `Configure<JwtOptions>(config.GetSection("Jwt"))`, `GetSection("Jwt").Get<JwtOptions>()`,
|
|
314
|
+
* `AddOptions<JwtOptions>().BindConfiguration("Jwt")` read every property of JwtOptions as `Jwt__<Property>`.
|
|
315
|
+
* Bindings and classes usually live in different files; scanProject matches them up.
|
|
316
|
+
*
|
|
317
|
+
* @param {string} text
|
|
318
|
+
* @param {Sink} sink
|
|
319
|
+
*/
|
|
320
|
+
function optionsPattern(text, sink) {
|
|
321
|
+
for (const pattern of OPTION_BINDINGS) {
|
|
322
|
+
for (const m of text.matchAll(pattern)) {
|
|
323
|
+
const g = m.groups ?? {};
|
|
324
|
+
const path = g.path ?? g.path2;
|
|
325
|
+
const line = sink.lineAt(m.index ?? 0);
|
|
326
|
+
sink.bind(path ? { cls: g.cls, line, section: netKey(path) } : { cls: g.cls, line, sectionOf: g.owner ?? g.owner2 });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const classes = [...text.matchAll(/\b(?:class|record)\s+(\w+)/g)];
|
|
330
|
+
for (let c = 0; c < classes.length; c++) {
|
|
331
|
+
const begin = classes[c].index ?? 0;
|
|
332
|
+
const body = text.slice(begin, classes[c + 1]?.index ?? text.length);
|
|
333
|
+
/** @type {OptionProp[]} */
|
|
334
|
+
const props = [];
|
|
335
|
+
for (const m of body.matchAll(/(?<attrs>(?:\[[^\]]*\]\s*)*)\bpublic\s+(?<req>required\s+)?(?<type>[\w.?]+)\s+(?<name>[A-Z]\w*)\s*\{\s*get;\s*(?:set|init);\s*\}(?:\s*=\s*(?<init>[^;]+);)?/g)) {
|
|
336
|
+
const g = m.groups ?? {};
|
|
337
|
+
if (!SIMPLE_TYPE.test(g.type)) continue; // nested option classes and collections aren't followed
|
|
338
|
+
const init = g.init?.trim();
|
|
339
|
+
const required = Boolean(g.req) || /\bRequired\b/.test(g.attrs);
|
|
340
|
+
const optional = !required && (g.type.endsWith("?") || VALUE_TYPE.test(g.type) || (init !== undefined && !PLACEHOLDER.test(init)));
|
|
341
|
+
props.push({ name: g.name, line: sink.lineAt(begin + (m.index ?? 0) + g.attrs.length), optional });
|
|
342
|
+
}
|
|
343
|
+
// positional records: record JwtOptions(string Key, int Ttl = 60)
|
|
344
|
+
const positional = /^record\s+\w+\s*\(([^)]*)\)/.exec(body);
|
|
345
|
+
for (const param of positional?.[1].split(",") ?? []) {
|
|
346
|
+
const pm = /^\s*(?:\[[^\]]*\]\s*)*([\w.?]+)\s+([A-Z]\w*)\s*(=\s*.+)?$/.exec(param);
|
|
347
|
+
if (pm && SIMPLE_TYPE.test(pm[1])) props.push({ name: pm[2], line: sink.lineAt(begin), optional: Boolean(pm[3]) || pm[1].endsWith("?") });
|
|
348
|
+
}
|
|
349
|
+
const sectionName = /\bconst\s+string\s+SectionName\s*=\s*"([^"]+)"/.exec(body)?.[1];
|
|
350
|
+
if (props.length || sectionName) sink.optionClass(classes[c][1], { props, ...(sectionName ? { sectionName: netKey(sectionName) } : {}) });
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Struct tags of caarlos0/env and kelseyhightower/envconfig: `env:"PORT" envDefault:"3000"`. @param {string} text @param {Sink} sink */
|
|
355
|
+
function goExtra(text, sink) {
|
|
356
|
+
for (const m of text.matchAll(/`([^`\n]*)`/g)) {
|
|
357
|
+
const tag = /(?:^|\s)(?:env|envconfig):"([A-Za-z_][A-Za-z0-9_]*)/.exec(m[1]);
|
|
358
|
+
if (tag) sink.add(tag[1], sink.lineAt(m.index ?? 0), { optional: /\b(?:envDefault|default):"/.test(m[1]) });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Compose files: `environment:` entries give the container a value, so the app needs no .env entry for them;
|
|
364
|
+
* the images in use tell which variables are read implicitly (postgres reads POSTGRES_PASSWORD).
|
|
365
|
+
*
|
|
366
|
+
* @param {string} text
|
|
367
|
+
* @param {Sink} sink
|
|
368
|
+
* @param {string} file
|
|
369
|
+
*/
|
|
370
|
+
function composeExtra(text, sink, file) {
|
|
371
|
+
sink.mark("compose");
|
|
372
|
+
for (const m of text.matchAll(/^\s*image:\s*["']?([^\s"'#]+)/gm)) {
|
|
373
|
+
const name = m[1].split("/").pop()?.split(/[:@]/)[0];
|
|
374
|
+
if (name) sink.mark(`image:${name.toLowerCase()}`);
|
|
375
|
+
}
|
|
376
|
+
const lines = text.split(/\r?\n/);
|
|
377
|
+
for (let i = 0; i < lines.length; i++) {
|
|
378
|
+
const head = /^(\s*)environment\s*:\s*(?:#.*)?$/.exec(lines[i]);
|
|
379
|
+
if (!head) continue;
|
|
380
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
381
|
+
const l = lines[j];
|
|
382
|
+
if (!l.trim() || l.trim().startsWith("#")) continue;
|
|
383
|
+
if (l.length - l.trimStart().length <= head[1].length) break;
|
|
384
|
+
const entry = /^\s*-?\s*["']?([A-Za-z_][\w.]*)["']?\s*[:=]\s*\S/.exec(l);
|
|
385
|
+
if (entry) sink.provide(entry[1], file, true);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** @type {Language[]} */
|
|
391
|
+
export const LANGUAGES = [
|
|
392
|
+
{
|
|
393
|
+
name: "JavaScript / TypeScript",
|
|
394
|
+
test: byExt(".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte", ".astro"),
|
|
395
|
+
comments: COMMENT_STYLES.c,
|
|
396
|
+
patterns: [
|
|
397
|
+
{ re: re(String.raw`\b${JS_ENV}\.${K}\b(?!\s*\()`), member: true },
|
|
398
|
+
{ re: re(String.raw`\b${JS_ENV}\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
399
|
+
{ re: re(String.raw`\bDeno\.env\.get\(\s*${Q}${K}${QS}`), call: true },
|
|
400
|
+
],
|
|
401
|
+
extra: jsExtra,
|
|
402
|
+
},
|
|
403
|
+
{ name: "Vite index.html", test: byName(/^index\.html$/i), comments: COMMENT_STYLES.html, patterns: [{ re: /%(?<key>[A-Z][A-Z0-9_]*)%/g }] },
|
|
404
|
+
{
|
|
405
|
+
name: "Python",
|
|
406
|
+
test: byExt(".py"),
|
|
407
|
+
comments: COMMENT_STYLES.python,
|
|
408
|
+
patterns: [
|
|
409
|
+
{ re: re(String.raw`\b(?:getenv|environ\.get|environ\.setdefault|environ\.pop)\(\s*${Q}${K}${QS}`), call: true },
|
|
410
|
+
{ re: re(String.raw`\benviron\[\s*${Q}${K}${QS}\s*\]`) },
|
|
411
|
+
],
|
|
412
|
+
extra: pyExtra,
|
|
413
|
+
},
|
|
414
|
+
{
|
|
415
|
+
name: "C# / .NET",
|
|
416
|
+
test: byExt(".cs"),
|
|
417
|
+
comments: COMMENT_STYLES.c,
|
|
418
|
+
patterns: [{ re: re(String.raw`\bGetEnvironmentVariable\(\s*@?"${K}"`), call: true }],
|
|
419
|
+
extra: csExtra,
|
|
420
|
+
},
|
|
421
|
+
{
|
|
422
|
+
name: "PHP / Laravel",
|
|
423
|
+
test: byExt(".php"),
|
|
424
|
+
comments: COMMENT_STYLES.php,
|
|
425
|
+
patterns: [
|
|
426
|
+
{ re: re(String.raw`(?<![\w$>:])(?:env|getenv)\(\s*${Q}${K}${QS}`), call: true },
|
|
427
|
+
{ re: re(String.raw`\$_ENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
428
|
+
],
|
|
429
|
+
},
|
|
430
|
+
{
|
|
431
|
+
name: "Go",
|
|
432
|
+
test: byExt(".go"),
|
|
433
|
+
comments: COMMENT_STYLES.c,
|
|
434
|
+
patterns: [{ re: re(String.raw`\bos\.Getenv\(\s*"${K}"`) }, { re: re(String.raw`\bos\.LookupEnv\(\s*"${K}"`), optional: true }],
|
|
435
|
+
extra: goExtra,
|
|
436
|
+
},
|
|
437
|
+
{
|
|
438
|
+
name: "Ruby",
|
|
439
|
+
test: byExt(".rb", ".rake"),
|
|
440
|
+
comments: COMMENT_STYLES.ruby,
|
|
441
|
+
patterns: [
|
|
442
|
+
{ re: re(String.raw`\bENV\[\s*${Q}${K}${QS}\s*\]`), member: true },
|
|
443
|
+
{ re: re(String.raw`\bENV\.fetch\(\s*${Q}${K}${QS}`), call: true },
|
|
444
|
+
],
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
name: "Rust",
|
|
448
|
+
test: byExt(".rs"),
|
|
449
|
+
comments: COMMENT_STYLES.rust,
|
|
450
|
+
patterns: [
|
|
451
|
+
{ re: re(String.raw`\b(?:env|dotenvy?)::var(?:_os)?\(\s*"${K}"`), call: true },
|
|
452
|
+
{ re: re(String.raw`\benv!\(\s*"${K}"`) },
|
|
453
|
+
{ re: re(String.raw`\boption_env!\(\s*"${K}"`), optional: true },
|
|
454
|
+
],
|
|
455
|
+
},
|
|
456
|
+
{
|
|
457
|
+
name: "Prisma",
|
|
458
|
+
test: (file) => extname(file).toLowerCase() === ".prisma" || /^prisma\.config\.[cm]?[jt]s$/i.test(basename(file)),
|
|
459
|
+
comments: COMMENT_STYLES.c,
|
|
460
|
+
patterns: [{ re: re(String.raw`\benv\(\s*${Q}${K}${QS}\s*\)`) }],
|
|
461
|
+
},
|
|
462
|
+
{
|
|
463
|
+
name: "Docker Compose",
|
|
464
|
+
test: byName(/^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i),
|
|
465
|
+
comments: COMMENT_STYLES.yaml,
|
|
466
|
+
patterns: [{ re: /\$\{(?<key>[A-Za-z_][A-Za-z0-9_]*)(?:(?<def>:?[-?+])|(?=}))/g }, { re: /(?<![$\w])\$(?<key>[A-Za-z_][A-Za-z0-9_]*)/g }],
|
|
467
|
+
extra: composeExtra,
|
|
468
|
+
},
|
|
469
|
+
];
|
|
470
|
+
|
|
471
|
+
export const DEFAULT_IGNORE_DIRS = [
|
|
472
|
+
"node_modules", ".git", ".hg", ".svn", "dist", "build", "out", ".next", ".nuxt", ".output", ".svelte-kit",
|
|
473
|
+
".vercel", ".netlify", ".turbo", ".cache", "coverage", "vendor", "target", ".venv", "venv",
|
|
474
|
+
"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".tox", ".idea", ".vscode", ".worktrees",
|
|
475
|
+
".claude", ".pnpm-store", ".yarn", ".expo", ".angular", ".gradle", "Pods", "DerivedData",
|
|
476
|
+
];
|
|
477
|
+
|
|
478
|
+
/** Keys set by the OS, runtimes and CI — nobody documents them in .env.example. */
|
|
479
|
+
export const DEFAULT_IGNORE_KEYS = [
|
|
480
|
+
"NODE_ENV", "CI", "HOME", "PATH", "PWD", "USER", "USERNAME", "SHELL", "TERM", "TZ", "LANG", "HOSTNAME",
|
|
481
|
+
"TMPDIR", "TEMP", "TMP", "APPDATA", "LOCALAPPDATA", "USERPROFILE", "MODE", "DEV", "PROD", "SSR", "BASE_URL",
|
|
482
|
+
"GITHUB_*", "RUNNER_*", "VERCEL_*", "NETLIFY_*", "npm_*", "ASPNETCORE_ENVIRONMENT", "DOTNET_ENVIRONMENT",
|
|
483
|
+
];
|
|
484
|
+
|
|
485
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024;
|
|
486
|
+
|
|
487
|
+
/** Test code sets and mocks variables; it isn't what the app needs at runtime. `--include-tests` scans it anyway. */
|
|
488
|
+
export const TEST_DIRS = ["test", "tests", "__tests__", "__mocks__", "spec", "specs", "e2e", "cypress"];
|
|
489
|
+
const TEST_PROJECT = /\.Tests?$/; // .NET test projects: Api.Tests
|
|
490
|
+
const TEST_FILE = /(?:\.(?:test|spec)\.[^.]+$|_test\.(?:go|py)$|^test_.*\.py$|^conftest\.py$|Tests?\.cs$)/;
|
|
491
|
+
/** .NET build output; skipped only next to a project file, so a Node or Go `bin/` is still read */
|
|
492
|
+
const NET_OUTPUT = new Set(["bin", "obj"]);
|
|
493
|
+
const NET_PROJECT = /\.(?:cs|fs|vb)proj$/i;
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* @param {string[]} patterns exact names or prefixes ending with `*`
|
|
497
|
+
* @returns {(key: string) => boolean}
|
|
498
|
+
*/
|
|
499
|
+
export function keyMatcher(patterns) {
|
|
500
|
+
const exact = new Set(patterns.filter((p) => !p.endsWith("*")));
|
|
501
|
+
const prefixes = patterns.filter((p) => p.endsWith("*")).map((p) => p.slice(0, -1));
|
|
502
|
+
return (key) => exact.has(key) || prefixes.some((p) => key.startsWith(p));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* @param {string} text
|
|
507
|
+
* @param {Pattern[]} patterns
|
|
508
|
+
* @param {Sink} sink
|
|
509
|
+
*/
|
|
510
|
+
function applyPatterns(text, patterns, sink) {
|
|
511
|
+
for (const p of patterns) {
|
|
512
|
+
for (const m of text.matchAll(p.re)) {
|
|
513
|
+
const key = m.groups?.key;
|
|
514
|
+
if (!key) continue;
|
|
515
|
+
const end = (m.index ?? 0) + m[0].length;
|
|
516
|
+
const after = text.slice(end, end + 40);
|
|
517
|
+
const def = m.groups?.def;
|
|
518
|
+
if (ASSIGNMENT.test(after) || DELETION.test(text.slice(Math.max(0, (m.index ?? 0) - 12), m.index ?? 0))) continue;
|
|
519
|
+
const optional =
|
|
520
|
+
Boolean(p.optional) || (def !== undefined && /^:?[-+]/.test(def)) || (p.call === true && CALL_DEFAULT.test(after)) || (p.member === true && MEMBER_DEFAULT.test(after));
|
|
521
|
+
sink.add(key, sink.lineAt(m.index ?? 0), { optional });
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Everything envsonar learns from one file.
|
|
528
|
+
*
|
|
529
|
+
* @param {string} text
|
|
530
|
+
* @param {string} file path used to pick the language
|
|
531
|
+
*/
|
|
532
|
+
export function extractFile(text, file) {
|
|
533
|
+
/** @type {Map<string, Found>} */
|
|
534
|
+
const found = new Map();
|
|
535
|
+
/** @type {{ key: string, line: number }[]} */
|
|
536
|
+
const sections = [];
|
|
537
|
+
/** @type {{ expr: string, line: number }[]} */
|
|
538
|
+
const dynamic = [];
|
|
539
|
+
/** @type {Provided[]} */
|
|
540
|
+
const provided = [];
|
|
541
|
+
/** @type {Binding[]} */
|
|
542
|
+
const bindings = [];
|
|
543
|
+
/** @type {Map<string, OptionClass>} */
|
|
544
|
+
const optionClasses = new Map();
|
|
545
|
+
/** @type {Set<string>} */
|
|
546
|
+
const markers = new Set();
|
|
547
|
+
const langs = LANGUAGES.filter((l) => l.test(file));
|
|
548
|
+
if (langs.length) {
|
|
549
|
+
/** @type {Sink} */
|
|
550
|
+
const sink = {
|
|
551
|
+
add(key, line, flags = {}) {
|
|
552
|
+
const id = `${key}:${line}`;
|
|
553
|
+
if (found.has(id)) return;
|
|
554
|
+
found.set(id, { key, line, ...(flags.optional ? { optional: true } : {}), ...(flags.ci ? { ci: true } : {}), ...(flags.schema ? { schema: true } : {}) });
|
|
555
|
+
},
|
|
556
|
+
section: (key, line) => sections.push({ key, line }),
|
|
557
|
+
dynamic: (expr, line) => dynamic.push({ expr, line }),
|
|
558
|
+
provide: (key, source, base = true) => provided.push({ key, source, base }),
|
|
559
|
+
bind: (binding) => bindings.push(binding),
|
|
560
|
+
optionClass: (name, cls) => optionClasses.set(name, cls),
|
|
561
|
+
mark: (marker) => markers.add(marker),
|
|
562
|
+
lineAt: lineIndex(text),
|
|
563
|
+
};
|
|
564
|
+
for (const lang of langs) {
|
|
565
|
+
const code = lang.comments ? stripComments(text, lang.comments) : text;
|
|
566
|
+
applyPatterns(code, lang.patterns, sink);
|
|
567
|
+
lang.extra?.(code, sink, file);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
// a key defined by an env schema (zod, envalid, t3-env) takes its optionality from the schema alone
|
|
571
|
+
const fromSchema = new Set([...found.values()].filter((f) => f.schema).map((f) => f.key));
|
|
572
|
+
const result = [...found.values()]
|
|
573
|
+
.filter((f) => f.schema || !fromSchema.has(f.key))
|
|
574
|
+
.map(({ key, line, optional, ci }) => ({ key, line, ...(optional ? { optional } : {}), ...(ci ? { ci } : {}) }))
|
|
575
|
+
.sort((a, b) => a.line - b.line);
|
|
576
|
+
return { found: result, sections, dynamic, provided, markers, bindings, optionClasses };
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Every statically named environment variable read in one file.
|
|
581
|
+
*
|
|
582
|
+
* @param {string} text
|
|
583
|
+
* @param {string} file used to pick the language
|
|
584
|
+
* @returns {Found[]}
|
|
585
|
+
*/
|
|
586
|
+
export function extractKeys(text, file) {
|
|
587
|
+
return extractFile(text, file).found;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Walks `root`: collects every environment variable the code reads, plus what frameworks,
|
|
592
|
+
* SDKs, compose files and appsettings.json provide or read on their own.
|
|
593
|
+
*
|
|
594
|
+
* @param {string} root
|
|
595
|
+
* @param {{ ignoreDirs?: string[], ignoreKeys?: string[], includeTests?: boolean }} [options]
|
|
596
|
+
* @returns {ScanResult}
|
|
597
|
+
*/
|
|
598
|
+
export function scanProject(root, options = {}) {
|
|
599
|
+
const gitignore = gitignoreRules(root);
|
|
600
|
+
const ignoreDirs = new Set([...DEFAULT_IGNORE_DIRS, ...gitignore.names, ...(options.ignoreDirs ?? []), ...(options.includeTests ? [] : TEST_DIRS)]);
|
|
601
|
+
const skipDir = (/** @type {string} */ name, /** @type {string} */ rel, /** @type {boolean} */ netProject) =>
|
|
602
|
+
ignoreDirs.has(name) || gitignore.paths.has(rel) || (netProject && NET_OUTPUT.has(name)) || (!options.includeTests && TEST_PROJECT.test(name));
|
|
603
|
+
const ignored = keyMatcher([...DEFAULT_IGNORE_KEYS, ...(options.ignoreKeys ?? [])]);
|
|
604
|
+
/** @type {ScanResult} */
|
|
605
|
+
const result = { files: 0, usages: new Map(), sections: new Map(), dynamic: [], provided: new Map(), implicit: [] };
|
|
606
|
+
/** @type {Set<string>} */
|
|
607
|
+
const markers = new Set();
|
|
608
|
+
/** @type {(Binding & { file: string })[]} */
|
|
609
|
+
const bindings = [];
|
|
610
|
+
/** @type {Map<string, OptionClass & { file: string }>} */
|
|
611
|
+
const optionClasses = new Map();
|
|
612
|
+
|
|
613
|
+
/** @param {Map<string, Usage[]>} map @param {string} key @param {Usage} usage */
|
|
614
|
+
const push = (map, key, usage) => {
|
|
615
|
+
const list = map.get(key) ?? [];
|
|
616
|
+
if (!list.some((u) => u.file === usage.file && u.line === usage.line)) list.push(usage);
|
|
617
|
+
map.set(key, list);
|
|
618
|
+
};
|
|
619
|
+
|
|
620
|
+
/** @param {string} dir */
|
|
621
|
+
const walk = (dir) => {
|
|
622
|
+
let entries;
|
|
623
|
+
try {
|
|
624
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
625
|
+
} catch {
|
|
626
|
+
return; // unreadable directory: skip it rather than fail the whole scan
|
|
627
|
+
}
|
|
628
|
+
const netProject = entries.some((e) => e.isFile() && NET_PROJECT.test(e.name));
|
|
629
|
+
for (const entry of entries) {
|
|
630
|
+
const full = join(dir, entry.name);
|
|
631
|
+
const rel = relative(root, full).split(sep).join("/");
|
|
632
|
+
if (entry.isDirectory()) {
|
|
633
|
+
if (!skipDir(entry.name, rel, netProject) && !existsSync(join(full, "pyvenv.cfg"))) walk(full);
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
if (!entry.isFile()) continue;
|
|
637
|
+
readManifest(entry.name, full, rel, markers, result.provided);
|
|
638
|
+
if (entry.name.includes(".min.") || !LANGUAGES.some((l) => l.test(entry.name))) continue;
|
|
639
|
+
if (!options.includeTests && TEST_FILE.test(entry.name)) continue;
|
|
640
|
+
if (statSync(full).size > MAX_FILE_BYTES) continue;
|
|
641
|
+
result.files++;
|
|
642
|
+
const r = extractFile(readFileSync(full, "utf8"), rel);
|
|
643
|
+
for (const { key, line, ...flags } of r.found) if (!ignored(key)) push(result.usages, key, { file: rel, line, ...flags });
|
|
644
|
+
for (const { key, line } of r.sections) push(result.sections, key, { file: rel, line });
|
|
645
|
+
for (const { expr, line } of r.dynamic) result.dynamic.push({ file: rel, line, expr });
|
|
646
|
+
for (const p of r.provided) provide(result.provided, p);
|
|
647
|
+
for (const m of r.markers) markers.add(m);
|
|
648
|
+
for (const b of r.bindings) bindings.push({ ...b, file: rel });
|
|
649
|
+
for (const [name, cls] of r.optionClasses) optionClasses.set(name, { ...cls, file: rel });
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
walk(root);
|
|
653
|
+
|
|
654
|
+
// options classes bound to a section: every property is a key under it
|
|
655
|
+
for (const b of bindings) {
|
|
656
|
+
const cls = optionClasses.get(b.cls);
|
|
657
|
+
const section = b.section ?? (b.sectionOf ? optionClasses.get(b.sectionOf)?.sectionName : undefined);
|
|
658
|
+
if (!cls || !section) continue;
|
|
659
|
+
push(result.sections, `${section}__`, { file: b.file, line: b.line });
|
|
660
|
+
for (const prop of cls.props) {
|
|
661
|
+
const key = `${section}__${prop.name}`;
|
|
662
|
+
if (!ignored(key)) push(result.usages, key, { file: cls.file, line: prop.line, ci: true, ...(prop.optional ? { optional: true } : {}) });
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const all = [...markers];
|
|
667
|
+
for (const profile of PROFILES) {
|
|
668
|
+
const hit = keyMatcher(profile.markers);
|
|
669
|
+
if (all.some(hit)) result.implicit.push({ source: profile.source, keys: profile.keys });
|
|
670
|
+
}
|
|
671
|
+
return result;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Dependency manifests tell which SDKs are in use; appsettings.json provides .NET config values.
|
|
676
|
+
* A manifest that can't be parsed is skipped: it only refines the result.
|
|
677
|
+
*
|
|
678
|
+
* @param {string} name
|
|
679
|
+
* @param {string} full
|
|
680
|
+
* @param {string} rel
|
|
681
|
+
* @param {Set<string>} markers
|
|
682
|
+
* @param {Map<string, Provided>} provided
|
|
683
|
+
*/
|
|
684
|
+
function readManifest(name, full, rel, markers, provided) {
|
|
685
|
+
const lower = name.toLowerCase();
|
|
686
|
+
const isManifest =
|
|
687
|
+
lower === "package.json" || lower === "composer.json" || lower === "pyproject.toml" || lower === "pipfile" ||
|
|
688
|
+
/^requirements.*\.txt$/.test(lower) || /\.(?:cs|fs|vb)proj$/.test(lower) || /^appsettings(?:\.[\w-]+)?\.json$/.test(lower);
|
|
689
|
+
if (!isManifest) return;
|
|
690
|
+
let text;
|
|
691
|
+
try {
|
|
692
|
+
text = readFileSync(full, "utf8");
|
|
693
|
+
} catch {
|
|
694
|
+
return; // unreadable manifest: the code scan still works without it
|
|
695
|
+
}
|
|
696
|
+
if (lower === "package.json" || lower === "composer.json") {
|
|
697
|
+
const json = parseJson(text);
|
|
698
|
+
const kind = lower === "package.json" ? "npm" : "composer";
|
|
699
|
+
for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies", "require", "require-dev"]) {
|
|
700
|
+
for (const dep of Object.keys(json?.[field] ?? {})) markers.add(`${kind}:${dep}`);
|
|
701
|
+
}
|
|
702
|
+
} else if (/\.(?:cs|fs|vb)proj$/.test(lower)) {
|
|
703
|
+
markers.add("dotnet");
|
|
704
|
+
for (const m of text.matchAll(/<PackageReference\s+Include="([^"]+)"/g)) markers.add(`nuget:${m[1]}`);
|
|
705
|
+
} else if (lower.startsWith("appsettings")) {
|
|
706
|
+
/** @type {string[]} */
|
|
707
|
+
const keys = [];
|
|
708
|
+
flatten(parseJson(text.replace(/^\s*\/\/.*$/gm, "")), "", keys);
|
|
709
|
+
// appsettings.Development.json / .Local.json don't exist in production: they don't excuse a missing .env.example entry
|
|
710
|
+
const base = lower === "appsettings.json";
|
|
711
|
+
for (const key of keys) provide(provided, { key, source: rel, base });
|
|
712
|
+
} else {
|
|
713
|
+
for (const dep of pythonDeps(text)) markers.add(`py:${dep}`);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* A value that applies everywhere wins over one for a single environment.
|
|
719
|
+
*
|
|
720
|
+
* @param {Map<string, Provided>} map
|
|
721
|
+
* @param {Provided} entry
|
|
722
|
+
*/
|
|
723
|
+
function provide(map, entry) {
|
|
724
|
+
const lower = entry.key.toLowerCase();
|
|
725
|
+
const prev = map.get(lower);
|
|
726
|
+
if (!prev || (!prev.base && entry.base)) map.set(lower, entry);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** @param {string} text @returns {any} */
|
|
730
|
+
function parseJson(text) {
|
|
731
|
+
try {
|
|
732
|
+
return JSON.parse(text.replace(/^/, ""));
|
|
733
|
+
} catch {
|
|
734
|
+
return null; // not valid JSON (or JSON with comments we can't strip): treat as empty
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** @param {unknown} value @param {string} prefix @param {string[]} out */
|
|
739
|
+
function flatten(value, prefix, out) {
|
|
740
|
+
if (value && typeof value === "object") {
|
|
741
|
+
for (const [k, v] of Object.entries(value)) flatten(v, prefix ? `${prefix}__${k}` : k, out);
|
|
742
|
+
} else if (prefix && value !== null && value !== "") {
|
|
743
|
+
out.push(prefix);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** @param {string} text */
|
|
748
|
+
function pythonDeps(text) {
|
|
749
|
+
/** @type {Set<string>} */
|
|
750
|
+
const names = new Set();
|
|
751
|
+
for (const m of text.matchAll(/^[ \t]*([A-Za-z0-9][A-Za-z0-9._-]*)/gm)) names.add(m[1]);
|
|
752
|
+
for (const m of text.matchAll(/["']([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@][^"']*)?["']/g)) names.add(m[1]);
|
|
753
|
+
return [...names].map((n) => n.toLowerCase().replace(/[._]/g, "-"));
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Plain directories listed in the root .gitignore; glob patterns are left alone.
|
|
758
|
+
* `dist/` matches a directory of that name anywhere; `/storage` and `app/cache` only that path from the root, as git does.
|
|
759
|
+
*
|
|
760
|
+
* @param {string} root
|
|
761
|
+
*/
|
|
762
|
+
function gitignoreRules(root) {
|
|
763
|
+
/** @type {{ names: string[], paths: Set<string> }} */
|
|
764
|
+
const rules = { names: [], paths: new Set() };
|
|
765
|
+
let text;
|
|
766
|
+
try {
|
|
767
|
+
text = readFileSync(join(root, ".gitignore"), "utf8");
|
|
768
|
+
} catch {
|
|
769
|
+
return rules; // no .gitignore
|
|
770
|
+
}
|
|
771
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
772
|
+
const line = raw.trim();
|
|
773
|
+
if (!line || line.startsWith("#") || line.startsWith("!") || line.startsWith(".env")) continue;
|
|
774
|
+
const path = line.replace(/\/$/, "");
|
|
775
|
+
if (!/^\/?[\w.-]+(?:\/[\w.-]+)*$/.test(path)) continue;
|
|
776
|
+
if (path.includes("/")) rules.paths.add(path.replace(/^\//, ""));
|
|
777
|
+
else rules.names.push(path);
|
|
778
|
+
}
|
|
779
|
+
return rules;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** @param {string} text */
|
|
783
|
+
function lineIndex(text) {
|
|
784
|
+
const starts = [0];
|
|
785
|
+
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
|
|
786
|
+
return (/** @type {number} */ offset) => {
|
|
787
|
+
let lo = 0;
|
|
788
|
+
let hi = starts.length - 1;
|
|
789
|
+
while (lo < hi) {
|
|
790
|
+
const mid = (lo + hi + 1) >> 1;
|
|
791
|
+
if (starts[mid] <= offset) lo = mid;
|
|
792
|
+
else hi = mid - 1;
|
|
793
|
+
}
|
|
794
|
+
return lo + 1;
|
|
795
|
+
};
|
|
796
|
+
}
|