@antelopejs/tooling-configs 0.2.6 → 0.2.8

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.
@@ -0,0 +1,119 @@
1
+ import { r as MEASURE_ENV, s as readCeilings } from "./ceilings-BSw9p4YB.mjs";
2
+ import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
3
+ import { a as repositoryPath } from "./files-BMxKg5IR.mjs";
4
+ import { createRequire } from "node:module";
5
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ //#region src/guardrails/oxlint.ts
9
+ function resolveOxlint(root) {
10
+ try {
11
+ const require = createRequire(join(root, "package.json"));
12
+ return join(dirname(require.resolve("oxlint/package.json")), "bin/oxlint");
13
+ } catch {
14
+ throw new Error("oxlint is not installed in this repository. Install dependencies first.");
15
+ }
16
+ }
17
+ function ruleId(code) {
18
+ const match = /^([^()]+)\(([^()]+)\)$/.exec(code);
19
+ if (!match) throw new Error(`Cannot measure oxlint diagnostic code ${JSON.stringify(code)}. Fix parser or configuration errors before recording a baseline.`);
20
+ const [, plugin, rule] = match;
21
+ return `${plugin === "typescript-eslint" ? "typescript" : plugin}/${rule}`;
22
+ }
23
+ function parseDiagnostics(text, root) {
24
+ const report = JSON.parse(text);
25
+ if (!Array.isArray(report?.diagnostics)) throw new Error("oxlint did not return a JSON diagnostics array.");
26
+ return report.diagnostics.map((item) => {
27
+ const file = repositoryPath(root, item.filename);
28
+ const span = item.labels?.[0]?.span;
29
+ return {
30
+ rule: ruleId(item.code),
31
+ file,
32
+ location: span ? `${file}:${span.line}:${span.column}` : file,
33
+ message: item.message,
34
+ line: span?.line,
35
+ help: item.help
36
+ };
37
+ });
38
+ }
39
+ function lintDiagnostics(root, config, files) {
40
+ const binary = resolveOxlint(root);
41
+ const temporary = config === void 0 ? void 0 : mkdtempSync(join(root, ".antelopejs-measure.generated."));
42
+ try {
43
+ const args = [
44
+ binary,
45
+ "-f",
46
+ "json"
47
+ ];
48
+ if (temporary) {
49
+ const path = join(temporary, "oxlint.config.ts");
50
+ writeFileSync(path, config ?? "");
51
+ args.push("--config", path, "--ignore-pattern", `${basename(temporary)}/**`);
52
+ }
53
+ if (files) args.push("--no-error-on-unmatched-pattern", "--", ...files);
54
+ const result = spawnSync(process.execPath, args, {
55
+ cwd: root,
56
+ encoding: "utf8",
57
+ env: {
58
+ ...process.env,
59
+ [MEASURE_ENV]: "1"
60
+ },
61
+ maxBuffer: 67108864
62
+ });
63
+ if (result.error) throw result.error;
64
+ if (result.status !== 0 && result.status !== 1) throw new Error(`oxlint failed (${result.status ?? result.signal}): ${result.stderr || result.stdout}`);
65
+ const diagnostics = parseDiagnostics(result.stdout, root);
66
+ if (result.status !== 0 && diagnostics.length === 0) throw new Error(`oxlint failed without diagnostics: ${result.stderr || result.stdout}`);
67
+ return diagnostics;
68
+ } finally {
69
+ if (temporary) rmSync(temporary, {
70
+ recursive: true,
71
+ force: true
72
+ });
73
+ }
74
+ }
75
+ //#endregion
76
+ //#region src/guardrails/staged-ratchet.ts
77
+ /** The line ranges each staged file adds against HEAD, following renames. */
78
+ function stagedAdditions(root, targets) {
79
+ const renames = renamedPaths(root, true);
80
+ const additions = /* @__PURE__ */ new Map();
81
+ for (const file of targets) {
82
+ const diff = execFileSync("git", [
83
+ "diff",
84
+ "--cached",
85
+ "--no-ext-diff",
86
+ "--no-color",
87
+ "--unified=0",
88
+ "--find-renames",
89
+ "--",
90
+ ...[renames.get(file), file].filter((path) => path !== void 0)
91
+ ], {
92
+ cwd: root,
93
+ encoding: "utf8"
94
+ });
95
+ additions.set(file, Array.from(diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm), ([, line, count]) => ({
96
+ start: Number(line),
97
+ end: Number(line) + Number(count ?? 1) - 1
98
+ })));
99
+ }
100
+ return additions;
101
+ }
102
+ function stagedRatchet(root, files) {
103
+ const targets = files ?? execFileSync("git", [
104
+ "diff",
105
+ "--cached",
106
+ "--name-only",
107
+ "--diff-filter=ACMR",
108
+ "-z"
109
+ ], {
110
+ cwd: root,
111
+ encoding: "utf8"
112
+ }).split("\0").filter(Boolean);
113
+ if (!targets.length) return [];
114
+ const additions = stagedAdditions(root, targets);
115
+ const ceilings = readCeilings(root);
116
+ return lintDiagnostics(root, void 0, targets).filter(({ rule, file, line }) => Object.hasOwn(ceilings.rules, rule) && line !== void 0 && additions.get(file)?.some(({ start, end }) => line >= start && line <= end)).map((diagnostic) => `${diagnostic.location}: ${diagnostic.message} [${diagnostic.rule}]\n Fix: ${diagnostic.help ?? "Resolve this finding on the added line; the ceiling covers only legacy findings on untouched lines."}`);
117
+ }
118
+ //#endregion
119
+ export { stagedRatchet as n, lintDiagnostics as r, stagedAdditions as t };
@@ -0,0 +1,282 @@
1
+ import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
2
+ import { n as changedFiles } from "./files-BMxKg5IR.mjs";
3
+ import { t as stagedAdditions } from "./staged-ratchet-CJHjp2kx.mjs";
4
+ import { a as revisionSuppressions, i as openDisablesIn, n as countSuppressions, o as worktreeSuppressions, r as inWorktree, t as atRevision } from "./suppressions-C3AE6_I-.mjs";
5
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { execFileSync, spawnSync } from "node:child_process";
8
+ //#region src/guardrails/suppression-policy.ts
9
+ /** Rules a directive may never name, each with what to do instead. */
10
+ const NEVER_SUPPRESSED = /* @__PURE__ */ new Map([
11
+ ["anti-slop/require-safety-comment-for-type-assertion", "remove the assertion (a type guard, a schema parse at the boundary, an inferred or owner-derived type), or, where it really holds, write `SAFETY: <why it holds>` above it"],
12
+ ["antelopejs/no-comments", "say it in code, move a public contract into TSDoc, or delete the comment"],
13
+ ["antelopejs/no-constant-value-assertion", "assert on a value the code under test computes, or delete the test"],
14
+ ["antelopejs/no-fs-read-in-tests", "drive the behaviour through the public interface, or read from fixtures/"],
15
+ ["antelopejs/no-typeof-function-only-test", "assert on what the function returns or does, or delete the test"],
16
+ ["antelopejs/require-assertion", "assert on the behaviour, or delete the test"],
17
+ ["typescript/ban-ts-comment", "use `@ts-expect-error <reason>`"]
18
+ ]);
19
+ const MIN_REASON_WORDS = 3;
20
+ /** Words that say a suppression is wanted without saying why the code needs it. */
21
+ const VAGUE_WORDS = new Set(`a an the this that it its is are be was here there we for of to as and or not no
22
+ ok okay fine safe safely correct valid works working intended intentional intentionally
23
+ needed necessary required expected known false positive legacy existing old behavior behaviour
24
+ preserve preserved preserves preserving keep kept compat compatibility workaround hack
25
+ temporary todo fixme later ignore ignored disable disabled suppress suppressed lint rule
26
+ type types typing typescript cast casting assert assertion by design trust trusted me`.split(/\s+/u));
27
+ function words(text) {
28
+ return text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
29
+ }
30
+ /** A reason too short or too vague to tell a reader why this code needs its suppression. */
31
+ function genericReason(suppression) {
32
+ const said = words(suppression.reason);
33
+ if (said.length < MIN_REASON_WORDS) return true;
34
+ const named = new Set(suppression.kind === "rule" ? words(suppression.rule) : []);
35
+ return said.every((word) => VAGUE_WORDS.has(word) || named.has(word));
36
+ }
37
+ function identity(suppression) {
38
+ return [
39
+ suppression.kind,
40
+ suppression.kind === "rule" ? suppression.rule : "",
41
+ suppression.reason
42
+ ].join("\0");
43
+ }
44
+ /** Takes one occurrence of `key` from `counts`, reporting whether one was left. */
45
+ function take(counts, key) {
46
+ const left = counts.get(key) ?? 0;
47
+ if (left > 0) counts.set(key, left - 1);
48
+ return left > 0;
49
+ }
50
+ /**
51
+ * The items of `after` that `before` does not account for, as multisets of
52
+ * `key`: an item is matched first in its own file, then in any file, so a
53
+ * moved item is not added and an added one is reported where it was added.
54
+ */
55
+ function unmatched(before, after, key) {
56
+ const sameFile = /* @__PURE__ */ new Map();
57
+ for (const item of before) {
58
+ const local = `${item.file}\0${key(item)}`;
59
+ sameFile.set(local, (sameFile.get(local) ?? 0) + 1);
60
+ }
61
+ const elsewhere = after.filter((item) => !take(sameFile, `${item.file}\0${key(item)}`));
62
+ const anyFile = /* @__PURE__ */ new Map();
63
+ for (const [local, count] of sameFile) {
64
+ const global = local.slice(local.indexOf("\0") + 1);
65
+ anyFile.set(global, (anyFile.get(global) ?? 0) + count);
66
+ }
67
+ return elsewhere.filter((item) => !take(anyFile, key(item)));
68
+ }
69
+ /**
70
+ * The suppressions of `after` that `before` does not account for, by kind,
71
+ * rule and reason, so a suppression moved to another file with its reason is
72
+ * not added, and one whose reason changed is.
73
+ */
74
+ function addedSuppressions(before, after) {
75
+ return unmatched(before, after, identity);
76
+ }
77
+ function label(suppression) {
78
+ if (suppression.kind === "rule") return `\`${suppression.directive} ${suppression.rule}\``;
79
+ if (suppression.kind === "safety") return "`SAFETY:`";
80
+ return suppression.kind === "tsIgnore" ? "`@ts-ignore`" : "`@ts-expect-error`";
81
+ }
82
+ /**
83
+ * Fails each added suppression that names a rule no directive may name, and
84
+ * each whose reason is empty or generic. Suppressions already on the base
85
+ * are left to the burn-down the budget tracks.
86
+ */
87
+ function policyFailures(added) {
88
+ return added.flatMap((suppression) => {
89
+ const at = `${suppression.file}:${suppression.line}`;
90
+ const instead = suppression.kind === "rule" ? NEVER_SUPPRESSED.get(suppression.rule) : void 0;
91
+ if (instead !== void 0) return [`${at}: ${label(suppression)}: this rule is never suppressed. Fix: ${instead}.`];
92
+ if (suppression.kind === "rule" && suppression.rule === "*") return [];
93
+ if (!genericReason(suppression)) return [];
94
+ const quoted = suppression.reason ? `"${suppression.reason}"` : "none";
95
+ return [`${at}: ${label(suppression)} reason ${quoted} does not say why this code needs it. Fix: state the fact about this line that makes the suppression hold (at least ${MIN_REASON_WORDS} words${suppression.kind === "rule" ? ", after ` -- `" : ""}), or fix the code.`];
96
+ });
97
+ }
98
+ /** Fails each block disable left open at the end of its file. */
99
+ function openDisableFailures(open) {
100
+ return open.map(({ directive, rule, file, line }) => `${file}:${line}: \`${directive}${rule === "*" ? "" : ` ${rule}`}\` is never closed, so it also silences every line added below it. Fix: add \`${directive.replace("disable", "enable")}${rule === "*" ? "" : ` ${rule}`}\` right after the last line that needs it, or use \`${directive}-next-line\`.`);
101
+ }
102
+ /** The open blocks of `after` beyond those of `before`, by directive and rule. */
103
+ function addedOpenDisables(before, after) {
104
+ return unmatched(before, after, ({ directive, rule }) => [directive, rule].join("\0"));
105
+ }
106
+ function hasCommit(root, revision) {
107
+ return spawnSync("git", [
108
+ "rev-parse",
109
+ "--verify",
110
+ "--quiet",
111
+ `${revision}^{commit}`
112
+ ], { cwd: root }).status === 0;
113
+ }
114
+ /**
115
+ * Fails what the working tree adds against `revision` (HEAD when none is
116
+ * given): a suppression that names a never-suppressed rule or gives no
117
+ * specific reason, and a block disable left open.
118
+ */
119
+ function checkPolicy(root, revision = "HEAD") {
120
+ if (!hasCommit(root, revision)) return [];
121
+ return [...policyFailures(addedSuppressions(revisionSuppressions(root, revision), worktreeSuppressions(root))), ...openDisableFailures(addedOpenDisables(atRevision(root, revision, openDisablesIn), inWorktree(root, openDisablesIn)))];
122
+ }
123
+ /** The same policy for a commit: the staged files against their HEAD versions, rename sources and deleted files included. */
124
+ function checkStagedPolicy(root, staged, previous) {
125
+ if (!hasCommit(root, "HEAD")) return [];
126
+ return [...policyFailures(addedSuppressions(revisionSuppressions(root, "HEAD", previous), revisionSuppressions(root, "", staged))), ...openDisableFailures(addedOpenDisables(atRevision(root, "HEAD", openDisablesIn, previous), atRevision(root, "", openDisablesIn, staged)))];
127
+ }
128
+ //#endregion
129
+ //#region src/guardrails/suppression-budget.ts
130
+ /** The per-repository suppression budget, at the repository root. It is permanent: nothing deletes it, even at zero. */
131
+ const SUPPRESSIONS_FILE = "guardrails.suppressions.json";
132
+ /** What a failure tells the author to do. */
133
+ const SUPPRESSION_FIX = "Fix: fix the code, or remove another suppression of the same kind; a rule that keeps needing suppressions should be changed in the preset.";
134
+ const LABELS = {
135
+ tsExpectError: "`@ts-expect-error`",
136
+ tsIgnore: "`@ts-ignore`",
137
+ safety: "`SAFETY:` comments"
138
+ };
139
+ function labelOf(suppression) {
140
+ return suppression.kind === "rule" ? `lint rule \`${suppression.rule}\`` : LABELS[suppression.kind];
141
+ }
142
+ /** The rule a SAFETY comment satisfies, so a directive disabling it may become a SAFETY comment without a raise. */
143
+ const SAFETY_RULE = "anti-slop/require-safety-comment-for-type-assertion";
144
+ /** The safety ceiling plus the room the directives disabling the SAFETY rule leave below theirs, so the two only ever shrink together. */
145
+ function safetyCeiling(budget, disables) {
146
+ return budget.safety + Math.max(0, (budget.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0) - disables);
147
+ }
148
+ function limitOf(budget, suppression) {
149
+ return suppression.kind === "rule" ? budget.rules[suppression.rule] ?? 0 : budget[suppression.kind];
150
+ }
151
+ function count(value, source) {
152
+ if (value === void 0) throw new Error(`${source} is missing`);
153
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${source} must be a non-negative integer`);
154
+ return value;
155
+ }
156
+ /** Parses a budget, rejecting a missing field and anything but non-negative integer ceilings. */
157
+ function parseBudget(text, source) {
158
+ const parsed = JSON.parse(text);
159
+ if (parsed === null || Array.isArray(parsed)) throw new Error(`${source}: expected an object with "rules"`);
160
+ const rules = parsed.rules ?? {};
161
+ if (rules === null || Array.isArray(rules)) throw new Error(`${source}: rules must be an object of counts`);
162
+ return {
163
+ rules: Object.fromEntries(Object.entries(rules).map(([rule, limit]) => [rule, count(limit, `${source}: rules "${rule}"`)])),
164
+ tsExpectError: count(parsed.tsExpectError, `${source}: tsExpectError`),
165
+ tsIgnore: count(parsed.tsIgnore, `${source}: tsIgnore`),
166
+ safety: count(parsed.safety, `${source}: safety`)
167
+ };
168
+ }
169
+ /** Serializes a budget with sorted rules, zero ceilings kept, so rewriting an unchanged budget is a no-op. */
170
+ function formatBudget(budget) {
171
+ const rules = Object.fromEntries(Object.entries(budget.rules).sort(([a], [b]) => a.localeCompare(b)));
172
+ return `${JSON.stringify({
173
+ ...budget,
174
+ rules
175
+ }, null, 2)}\n`;
176
+ }
177
+ /** The budget sync writes at adoption: the committed one when the file was only deleted, so recreating it never raises a ceiling, else the current counts. */
178
+ function adoptedBudget(root) {
179
+ const committed = spawnSync("git", ["show", `HEAD:${SUPPRESSIONS_FILE}`], {
180
+ cwd: root,
181
+ encoding: "utf8"
182
+ });
183
+ if (committed.status === 0) return committed.stdout;
184
+ return formatBudget(countSuppressions(worktreeSuppressions(root)));
185
+ }
186
+ function groupByKey(suppressions) {
187
+ const groups = /* @__PURE__ */ new Map();
188
+ for (const suppression of suppressions) {
189
+ const key = labelOf(suppression);
190
+ groups.set(key, [...groups.get(key) ?? [], suppression]);
191
+ }
192
+ return groups;
193
+ }
194
+ function lowered(budget, current) {
195
+ return {
196
+ rules: Object.fromEntries(Object.entries(budget.rules).map(([rule, limit]) => [rule, Math.min(limit, current.rules[rule] ?? 0)])),
197
+ tsExpectError: Math.min(budget.tsExpectError, current.tsExpectError),
198
+ tsIgnore: Math.min(budget.tsIgnore, current.tsIgnore),
199
+ safety: Math.min(safetyCeiling(budget, current.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0), current.safety)
200
+ };
201
+ }
202
+ /**
203
+ * Fails each budget key whose count in the working tree is above its ceiling,
204
+ * listing the suppressions in the files this change touches (all of them when
205
+ * it touches none). SAFETY comments may also use the room the
206
+ * directives disabling the SAFETY rule leave below their ceiling. `update`
207
+ * lowers every ceiling to its current count, moving that room to `safety`;
208
+ * no command ever raises the two together.
209
+ */
210
+ function checkSuppressions(root, update = false) {
211
+ const path = join(root, SUPPRESSIONS_FILE);
212
+ if (!existsSync(path)) throw new Error(`${SUPPRESSIONS_FILE} is missing. Run antelopejs-sync.`);
213
+ const budget = parseBudget(readFileSync(path, "utf8"), SUPPRESSIONS_FILE);
214
+ const suppressions = worktreeSuppressions(root);
215
+ const counts = countSuppressions(suppressions);
216
+ const changed = changedFiles(root);
217
+ const failures = [];
218
+ for (const [key, found] of groupByKey(suppressions)) {
219
+ const limit = found[0].kind === "safety" ? safetyCeiling(budget, counts.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0) : limitOf(budget, found[0]);
220
+ if (found.length <= limit) continue;
221
+ const inChanged = found.filter(({ file }) => changed.has(file));
222
+ const shown = inChanged.length ? inChanged : found;
223
+ failures.push(`${SUPPRESSIONS_FILE}: ${key}: ${found.length} exceeds ceiling ${limit}.`, ...shown.map(({ file, line }) => ` ${file}:${line}`), ...shown.length < found.length ? [` ...and ${found.length - shown.length} in files this change does not touch.`] : []);
224
+ }
225
+ if (update) writeFileSync(path, formatBudget(lowered(budget, counts)));
226
+ return failures.length ? [...failures, SUPPRESSION_FIX] : [];
227
+ }
228
+ function budgetAt(root, revision) {
229
+ const result = spawnSync("git", ["show", `${revision}:${SUPPRESSIONS_FILE}`], {
230
+ cwd: root,
231
+ encoding: "utf8"
232
+ });
233
+ return result.status === 0 ? parseBudget(result.stdout, `${revision || "index"}:${SUPPRESSIONS_FILE}`) : void 0;
234
+ }
235
+ function stagedNames(root, filter) {
236
+ return execFileSync("git", [
237
+ "diff",
238
+ "--cached",
239
+ "--name-only",
240
+ "--find-renames",
241
+ `--diff-filter=${filter}`,
242
+ "-z"
243
+ ], {
244
+ cwd: root,
245
+ encoding: "utf8"
246
+ }).split("\0").filter(Boolean);
247
+ }
248
+ /**
249
+ * Compares the staged files' suppressions with those files at HEAD, rename
250
+ * sources and deleted files included, and fails each key that rises by more
251
+ * than the staged budget raises its ceiling, then applies the suppression
252
+ * policy to what the commit adds. A commit that first adds the budget is
253
+ * not compared.
254
+ */
255
+ function stagedSuppressions(root) {
256
+ const renames = renamedPaths(root, true);
257
+ const staged = stagedNames(root, "ACMR");
258
+ const previous = [...staged.map((file) => renames.get(file) ?? file), ...stagedNames(root, "D")];
259
+ return [...stagedBudget(root, staged, previous), ...checkStagedPolicy(root, staged, previous)];
260
+ }
261
+ function stagedBudget(root, staged, previous) {
262
+ const head = budgetAt(root, "HEAD");
263
+ if (head === void 0) return [];
264
+ const index = budgetAt(root, "") ?? head;
265
+ const before = groupByKey(revisionSuppressions(root, "HEAD", previous));
266
+ const after = groupByKey(revisionSuppressions(root, "", staged));
267
+ const additions = stagedAdditions(root, [...new Set([...after.values()].flat().map(({ file }) => file))]);
268
+ const failures = [];
269
+ const safetyRule = `lint rule \`${SAFETY_RULE}\``;
270
+ const converted = Math.max(0, (before.get(safetyRule)?.length ?? 0) - (after.get(safetyRule)?.length ?? 0));
271
+ const freed = (head.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0) - (index.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0);
272
+ for (const [key, found] of after) {
273
+ const rise = found.length - (before.get(key)?.length ?? 0);
274
+ const raised = limitOf(index, found[0]) - limitOf(head, found[0]);
275
+ if (rise <= (found[0].kind === "safety" ? converted + Math.max(0, raised - Math.max(0, freed)) : Math.max(0, raised))) continue;
276
+ const added = found.filter(({ file, line }) => additions.get(file)?.some(({ start, end }) => line >= start && line <= end));
277
+ failures.push(`${key}: this commit adds ${rise} to the staged files.`, ...(added.length ? added : found).map(({ file, line }) => ` ${file}:${line}`));
278
+ }
279
+ return failures.length ? [...failures, SUPPRESSION_FIX] : [];
280
+ }
281
+ //#endregion
282
+ export { parseBudget as a, checkPolicy as c, checkSuppressions as i, SUPPRESSIONS_FILE as n, safetyCeiling as o, adoptedBudget as r, stagedSuppressions as s, SAFETY_RULE as t };
@@ -0,0 +1,270 @@
1
+ import { n as markerPattern, t as DEFAULT_SAFETY_MARKERS } from "./require-safety-comment-for-type-assertion-BBQ669kj.mjs";
2
+ import { i as gitFiles, r as generatedOutput } from "./files-BMxKg5IR.mjs";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ //#region src/guardrails/suppressions.ts
8
+ const CODE_FILE = /\.(?:[cm]?[jt]sx?|vue)$/u;
9
+ const CANDIDATE = /(?:oxlint|eslint)-disable|@ts-(?:expect-error|ignore)/u;
10
+ const LINT_DIRECTIVE = /^((?:oxlint|eslint)-disable(?:-line|-next-line)?)(?=\s|$)([\s\S]*)$/u;
11
+ const DESCRIPTION = /\s-{2,}\s|\s-{2,}$/u;
12
+ /** The comment `anti-slop/require-safety-comment-for-type-assertion` accepts as a justification. */
13
+ const SAFETY_COMMENT = markerPattern(DEFAULT_SAFETY_MARKERS);
14
+ const TS_DIRECTIVE = /^[/*\s]*@ts-(expect-error|ignore)(?![\w-])/u;
15
+ const SAFETY_REASON = /SAFETY\s*:([\s\S]*)$/u;
16
+ const ENABLE_DIRECTIVE = /^((?:oxlint|eslint)-enable)(?=\s|$)([\s\S]*)$/u;
17
+ let compiler;
18
+ /** This package's own TypeScript 5, loaded on first use, so the count never depends on the compiler a repository installs (TypeScript 7 has no parser API). */
19
+ function typescript() {
20
+ compiler ??= createRequire(import.meta.url)("typescript");
21
+ return compiler;
22
+ }
23
+ function scriptKind(lang) {
24
+ const kinds = typescript().ScriptKind;
25
+ if (/^[cm]?tsx$/u.test(lang)) return kinds.TSX;
26
+ if (/^[cm]?ts$/u.test(lang)) return kinds.TS;
27
+ return lang.endsWith("x") ? kinds.JSX : kinds.JS;
28
+ }
29
+ /** Every comment the parser sees, so string, template and JSX text that only looks like a comment is never read. */
30
+ function scriptComments(text, kind, offset) {
31
+ const compiler = typescript();
32
+ const source = compiler.createSourceFile("suppressions", text, compiler.ScriptTarget.Latest, false, kind);
33
+ const ranges = /* @__PURE__ */ new Map();
34
+ const visit = (node) => {
35
+ if (node.kind === compiler.SyntaxKind.JsxText) return;
36
+ if (node.kind !== compiler.SyntaxKind.SyntaxList) for (const range of [...compiler.getTrailingCommentRanges(text, node.pos) ?? [], ...compiler.getLeadingCommentRanges(text, node.pos) ?? []]) ranges.set(range.pos, range);
37
+ for (const child of node.getChildren(source)) visit(child);
38
+ };
39
+ visit(source);
40
+ return [...ranges.values()].map((range) => {
41
+ const line = range.kind === compiler.SyntaxKind.SingleLineCommentTrivia;
42
+ return {
43
+ value: text.slice(range.pos + 2, line ? range.end : range.end - 2),
44
+ line,
45
+ start: offset + range.pos
46
+ };
47
+ });
48
+ }
49
+ function blank(text) {
50
+ return text.replaceAll(/[^\n]/gu, " ");
51
+ }
52
+ /** Script blocks are parsed; outside script and style blocks, HTML comments carry template directives. */
53
+ function vueComments(text) {
54
+ const comments = [];
55
+ let template = text;
56
+ for (const block of text.matchAll(/(<script\b([^>]*)>)([\s\S]*?)<\/script\s*>|<style\b[^>]*>[\s\S]*?<\/style\s*>/gu)) {
57
+ template = template.slice(0, block.index) + blank(block[0]) + template.slice(block.index + block[0].length);
58
+ if (block[1] === void 0) continue;
59
+ const lang = /\blang\s*=\s*["']?([\w-]+)/u.exec(block[2])?.[1] ?? "js";
60
+ comments.push(...scriptComments(block[3], scriptKind(lang), block.index + block[1].length));
61
+ }
62
+ for (const comment of template.matchAll(/<!--([\s\S]*?)-->/gu)) comments.push({
63
+ value: comment[1],
64
+ line: false,
65
+ start: comment.index
66
+ });
67
+ return comments;
68
+ }
69
+ /** Collapses whitespace and the leading `*` of block comment lines. */
70
+ function normalized(text) {
71
+ return text.replaceAll(/\n\s*\*(?!\/)/gu, "\n").replaceAll(/\s+/gu, " ").trim();
72
+ }
73
+ /** The rules a directive's text names, `*` for none, and the reason after its ` -- `. */
74
+ function directiveParts(rest) {
75
+ const separator = DESCRIPTION.exec(rest);
76
+ const rules = (separator === null ? rest : rest.slice(0, separator.index)).split(",").map((rule) => rule.trim()).filter(Boolean);
77
+ return {
78
+ rules: rules.length ? rules : ["*"],
79
+ reason: separator === null ? "" : normalized(rest.slice(separator.index + separator[0].length))
80
+ };
81
+ }
82
+ function lintDirective(value) {
83
+ const text = value.replace(/^\s*\*?\s*/u, "");
84
+ const directive = LINT_DIRECTIVE.exec(text);
85
+ if (directive === null) return [];
86
+ const { rules, reason } = directiveParts(directive[2]);
87
+ return rules.map((rule) => ({
88
+ directive: directive[1],
89
+ rule,
90
+ reason
91
+ }));
92
+ }
93
+ /** TypeScript reads a directive from a line comment, or from the last line of a block comment. */
94
+ function tsDirective(comment) {
95
+ const text = comment.line ? comment.value : comment.value.slice(comment.value.lastIndexOf("\n") + 1);
96
+ const match = TS_DIRECTIVE.exec(text);
97
+ if (match === null) return void 0;
98
+ return {
99
+ kind: match[1] === "ignore" ? "tsIgnore" : "tsExpectError",
100
+ reason: normalized(text.slice(match[0].length))
101
+ };
102
+ }
103
+ /** Parsed comments by language and text, so a file unchanged between the base and the working tree is parsed once per run. */
104
+ const parsedComments = /* @__PURE__ */ new Map();
105
+ function fileComments(file, text) {
106
+ const language = file.endsWith(".vue") ? "vue" : file.slice(file.lastIndexOf(".") + 1);
107
+ const key = `${language}\0${text}`;
108
+ const cached = parsedComments.get(key);
109
+ if (cached !== void 0) return cached;
110
+ const comments = (language === "vue" ? vueComments(text) : scriptComments(text, scriptKind(language), 0)).sort((a, b) => a.start - b.start);
111
+ parsedComments.set(key, comments);
112
+ return comments;
113
+ }
114
+ function lineOf(text, offset) {
115
+ return text.slice(0, offset).split("\n").length;
116
+ }
117
+ /** The suppressions in one code file's text; `file` decides the language and labels each entry. */
118
+ function suppressionsIn(file, text) {
119
+ if (!CODE_FILE.test(file) || !(CANDIDATE.test(text) || SAFETY_COMMENT.test(text))) return [];
120
+ const found = [];
121
+ for (const comment of fileComments(file, text)) {
122
+ const line = lineOf(text, comment.start);
123
+ for (const { directive, rule, reason } of lintDirective(comment.value)) found.push({
124
+ kind: "rule",
125
+ rule,
126
+ directive,
127
+ reason,
128
+ file,
129
+ line
130
+ });
131
+ const typeDirective = tsDirective(comment);
132
+ if (typeDirective !== void 0) found.push({
133
+ ...typeDirective,
134
+ file,
135
+ line
136
+ });
137
+ if (SAFETY_COMMENT.test(comment.value)) found.push({
138
+ kind: "safety",
139
+ reason: normalized(SAFETY_REASON.exec(comment.value)?.[1] ?? ""),
140
+ file,
141
+ line
142
+ });
143
+ }
144
+ return found;
145
+ }
146
+ /**
147
+ * The block disables in one code file's text that are still open at its end.
148
+ * An `-enable` naming rules closes those rules; one naming none closes every
149
+ * open block.
150
+ */
151
+ function openDisablesIn(file, text) {
152
+ if (!CODE_FILE.test(file) || !CANDIDATE.test(text)) return [];
153
+ const open = /* @__PURE__ */ new Map();
154
+ for (const comment of fileComments(file, text)) {
155
+ const value = comment.value.replace(/^\s*\*?\s*/u, "");
156
+ const disable = LINT_DIRECTIVE.exec(value);
157
+ if (disable !== null && !disable[1].endsWith("line")) {
158
+ const line = lineOf(text, comment.start);
159
+ for (const rule of directiveParts(disable[2]).rules) open.set(rule, {
160
+ rule,
161
+ directive: disable[1],
162
+ file,
163
+ line
164
+ });
165
+ continue;
166
+ }
167
+ const enable = ENABLE_DIRECTIVE.exec(value);
168
+ if (enable === null) continue;
169
+ const { rules } = directiveParts(enable[2]);
170
+ if (rules[0] === "*") open.clear();
171
+ else for (const rule of rules) open.delete(rule);
172
+ }
173
+ return [...open.values()];
174
+ }
175
+ /** Each repository's generated-output test, remembered per path, since the base and the working tree list mostly the same files. */
176
+ const generatedPaths = /* @__PURE__ */ new Map();
177
+ function generatedIn(root) {
178
+ const known = generatedPaths.get(root);
179
+ if (known !== void 0) return known;
180
+ const test = generatedOutput(root);
181
+ const verdicts = /* @__PURE__ */ new Map();
182
+ const generated = (file) => {
183
+ const verdict = verdicts.get(file) ?? test(file);
184
+ verdicts.set(file, verdict);
185
+ return verdict;
186
+ };
187
+ generatedPaths.set(root, generated);
188
+ return generated;
189
+ }
190
+ function authoredCode(root, files) {
191
+ const generated = generatedIn(root);
192
+ return files.filter((file) => CODE_FILE.test(file) && !generated(file));
193
+ }
194
+ /** What `read` finds in the working tree's authored code files: tracked and untracked, ignored files and generated output left out. */
195
+ function inWorktree(root, read, files = gitFiles(root)) {
196
+ return authoredCode(root, files).flatMap((file) => {
197
+ const path = join(root, file);
198
+ if (!existsSync(path) || !lstatSync(path).isFile()) return [];
199
+ return read(file, readFileSync(path, "utf8"));
200
+ });
201
+ }
202
+ /** Suppressions in the working tree's authored code files. */
203
+ function worktreeSuppressions(root, files = gitFiles(root)) {
204
+ return inWorktree(root, suppressionsIn, files);
205
+ }
206
+ function blobs(root, specs) {
207
+ if (!specs.length) return [];
208
+ const output = execFileSync("git", ["cat-file", "--batch"], {
209
+ cwd: root,
210
+ input: `${specs.join("\n")}\n`,
211
+ maxBuffer: 1073741824
212
+ });
213
+ const texts = [];
214
+ let offset = 0;
215
+ for (let index = 0; index < specs.length; index++) {
216
+ const newline = output.indexOf(10, offset);
217
+ const [, type, size] = output.subarray(offset, newline).toString().split(" ");
218
+ offset = newline + 1;
219
+ if (size === void 0) {
220
+ texts.push(void 0);
221
+ continue;
222
+ }
223
+ const end = offset + Number(size);
224
+ texts.push(type === "blob" ? output.subarray(offset, end).toString() : void 0);
225
+ offset = end + 1;
226
+ }
227
+ return texts;
228
+ }
229
+ /**
230
+ * What `read` finds in authored code files at a committed revision, or in the
231
+ * index when `revision` is the empty string. Without `files` every file of
232
+ * that tree is read.
233
+ */
234
+ function atRevision(root, revision, read, files) {
235
+ const code = authoredCode(root, files ?? execFileSync("git", revision === "" ? ["ls-files", "-z"] : [
236
+ "ls-tree",
237
+ "-r",
238
+ "-z",
239
+ "--name-only",
240
+ revision
241
+ ], {
242
+ cwd: root,
243
+ encoding: "utf8",
244
+ maxBuffer: 67108864
245
+ }).split("\0").filter(Boolean));
246
+ const texts = blobs(root, code.map((file) => `${revision}:${file}`));
247
+ return code.flatMap((file, index) => {
248
+ const text = texts[index];
249
+ return text === void 0 ? [] : read(file, text);
250
+ });
251
+ }
252
+ /** Suppressions in authored code files at a committed revision, or in the index when `revision` is the empty string. */
253
+ function revisionSuppressions(root, revision, files) {
254
+ return atRevision(root, revision, suppressionsIn, files);
255
+ }
256
+ /** Totals by budget key, rules sorted by id. */
257
+ function countSuppressions(suppressions) {
258
+ const counts = {
259
+ rules: {},
260
+ tsExpectError: 0,
261
+ tsIgnore: 0,
262
+ safety: 0
263
+ };
264
+ for (const suppression of suppressions) if (suppression.kind === "rule") counts.rules[suppression.rule] = (counts.rules[suppression.rule] ?? 0) + 1;
265
+ else counts[suppression.kind]++;
266
+ counts.rules = Object.fromEntries(Object.entries(counts.rules).sort(([a], [b]) => a.localeCompare(b)));
267
+ return counts;
268
+ }
269
+ //#endregion
270
+ export { revisionSuppressions as a, openDisablesIn as i, countSuppressions as n, worktreeSuppressions as o, inWorktree as r, atRevision as t };