@antelopejs/tooling-configs 0.2.16 → 0.2.18

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.
Files changed (51) hide show
  1. package/README.md +101 -52
  2. package/dist/bin/api-diff.mjs +430 -107
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/capture.d.mts +1 -0
  6. package/dist/bin/capture.mjs +559 -0
  7. package/dist/bin/check-size.mjs +3 -3
  8. package/dist/bin/checks.mjs +3 -3
  9. package/dist/bin/comment-proof.mjs +4 -3
  10. package/dist/bin/garden.mjs +6 -6
  11. package/dist/bin/ratchet.mjs +316 -10
  12. package/dist/bin/suppressions.mjs +118 -80
  13. package/dist/bin/sync.mjs +554 -153
  14. package/dist/bin/verify.mjs +240 -127
  15. package/dist/capture/index.d.mts +50 -0
  16. package/dist/capture/index.mjs +2 -0
  17. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  18. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  19. package/dist/{ci-workflow-DIsoEgMd.mjs → ci-workflow-ChW4He0r.mjs} +84 -3
  20. package/dist/{files-2FikHZ9F.mjs → files-DJ0TeaTU.mjs} +11 -5
  21. package/dist/formal/index.d.mts +40 -0
  22. package/dist/formal/index.mjs +205 -0
  23. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  24. package/dist/oxc/anti-slop/index.mjs +869 -21
  25. package/dist/oxc/fmt.mjs +1 -1
  26. package/dist/oxc/guardrails/index.d.mts +1 -1
  27. package/dist/oxc/guardrails/index.mjs +736 -4
  28. package/dist/oxc/lint.d.mts +20 -3
  29. package/dist/oxc/lint.mjs +34 -10
  30. package/dist/oxlint-DIV-lLSS.mjs +98 -0
  31. package/dist/{package-Dtjt_lSa.mjs → package-BRTjkzt5.mjs} +29 -3
  32. package/dist/proof-stamp-DDDC0J6l.mjs +279 -0
  33. package/dist/ratchet-BAcLRYuM.mjs +448 -0
  34. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  35. package/dist/scenes-DZVXkcxS.mjs +104 -0
  36. package/dist/shared-igPpEDpS.mjs +622 -0
  37. package/dist/{size-BVgNbLO6.mjs → size-DBatLT-F.mjs} +4 -4
  38. package/dist/suppression-base-9L8dlMQK.mjs +120 -0
  39. package/dist/suppression-budget-C0SkPO5R.mjs +535 -0
  40. package/dist/{suppressions-BJAngUxo.mjs → suppressions-DM60NkvL.mjs} +180 -18
  41. package/dist/templates-CypDm-j9.mjs +121 -0
  42. package/dist/typescript-CM0LrVP7.mjs +222 -0
  43. package/dist/verify/index.d.mts +6 -1
  44. package/dist/verify/index.mjs +1 -1
  45. package/package.json +31 -5
  46. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  47. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  48. package/dist/shared-CsXIMK3I.mjs +0 -34
  49. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  50. package/dist/suppression-budget-Yyf5_J5l.mjs +0 -283
  51. package/dist/typescript-C54ONh9m.mjs +0 -433
@@ -1,12 +1,316 @@
1
1
  #!/usr/bin/env node
2
- import { t as CEILINGS_FILE } from "../ceilings-BSw9p4YB.mjs";
2
+ import { c as parseCeilings, l as readCeilings, t as CEILINGS_FILE } from "../ceilings-B7KayYIG.mjs";
3
+ import { n as renamedPaths } from "../renames-L2owF5GD.mjs";
3
4
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
4
- import { a as repositoryPath, o as repositoryRoot, s as resolveRevision } from "../files-2FikHZ9F.mjs";
5
- import { n as stagedRatchet } from "../staged-ratchet-CjoRfZaM.mjs";
6
- import { n as ratchet } from "../ratchet-DRdIYwmv.mjs";
7
- import { resolve } from "node:path";
5
+ import { c as repositoryRoot, l as resolveRevision, s as repositoryPath, t as LINT_CONFIG } from "../files-DJ0TeaTU.mjs";
6
+ import { n as ratchet, r as withPreviousTree } from "../ratchet-BAcLRYuM.mjs";
7
+ import { t as lintDiagnostics } from "../oxlint-DIV-lLSS.mjs";
8
+ import { d as stagedAdditions, f as stagedChanges, u as previousLine } from "../suppression-budget-C0SkPO5R.mjs";
9
+ import { n as suppressionBase } from "../suppression-base-9L8dlMQK.mjs";
10
+ import { existsSync } from "node:fs";
11
+ import { join, resolve } from "node:path";
12
+ import { execFileSync, spawnSync } from "node:child_process";
8
13
  import { parseArgs } from "node:util";
14
+ //#region src/guardrails/approved-raises.ts
15
+ /** The environment variable that carries the raises the operator approved. */
16
+ const APPROVED_RAISES_ENV = "APPROVED_RAISES";
17
+ const ENTRY = /^([^=]+)=([0-9]{1,15})$/u;
18
+ /**
19
+ * Parses `APPROVED_RAISES`, a space-separated list of `<rule>=<max>` entries
20
+ * where `<max>` is the ceiling the same commit writes for `<rule>`.
21
+ * Entries are split on space and tab only. The bash reader stops at the first
22
+ * line, so a newline anywhere makes the list malformed, as does a non-breaking
23
+ * space inside an entry.
24
+ * An unset or blank variable approves nothing. A bare rule, a non-numeric or
25
+ * oversized max, or a rule listed twice makes the whole list malformed, and
26
+ * a malformed list throws instead of approving any of its entries.
27
+ */
28
+ function parseApprovedRaises(value = process.env[APPROVED_RAISES_ENV]) {
29
+ const approved = /* @__PURE__ */ new Map();
30
+ if (value?.includes("\n")) throw new Error(`${APPROVED_RAISES_ENV} is malformed: it holds a newline, which the shell reader would stop at, so nothing is approved.`);
31
+ for (const entry of (value ?? "").split(/[ \t]+/u).filter(Boolean)) {
32
+ const match = ENTRY.exec(entry);
33
+ if (match === null || approved.has(match[1])) throw new Error(`${APPROVED_RAISES_ENV} is malformed at ${JSON.stringify(entry)}: expected space-separated <rule>=<max> entries with a whole-number max and each rule once, so nothing is approved.`);
34
+ approved.set(match[1], Number(match[2]));
35
+ }
36
+ return approved;
37
+ }
38
+ //#endregion
39
+ //#region src/guardrails/staged-ratchet.ts
40
+ /** The staged hook measures the real tree and a scratch checkout, so a project that fails to load in either must stop it. */
41
+ const STAGED_LINT = { rejectBrokenProject: true };
42
+ function stagedNames(root, filter) {
43
+ return execFileSync("git", [
44
+ "diff",
45
+ "--cached",
46
+ "--name-only",
47
+ `--diff-filter=${filter}`,
48
+ "-z"
49
+ ], {
50
+ cwd: root,
51
+ encoding: "utf8"
52
+ }).split("\0").filter(Boolean);
53
+ }
54
+ function countByRule(diagnostics) {
55
+ const counts = /* @__PURE__ */ new Map();
56
+ for (const { rule } of diagnostics) counts.set(rule, (counts.get(rule) ?? 0) + 1);
57
+ return counts;
58
+ }
59
+ function comparisonBase(root) {
60
+ const base = suppressionBase(root);
61
+ const name = process.env.GITHUB_BASE_REF ? `origin/${process.env.GITHUB_BASE_REF}` : "origin/HEAD";
62
+ if (base === void 0) return {
63
+ revision: void 0,
64
+ note: "No pull request base resolved (GITHUB_BASE_REF or origin/HEAD), so this compared with HEAD only. Run `git remote set-head origin --auto` to also compare with the merge-base, as CI does."
65
+ };
66
+ const result = spawnSync("git", [
67
+ "merge-base",
68
+ base,
69
+ "HEAD"
70
+ ], {
71
+ cwd: root,
72
+ encoding: "utf8"
73
+ });
74
+ if (result.status !== 0) return {
75
+ revision: void 0,
76
+ note: `HEAD has no merge-base with ${name}, so this compared with HEAD only. Run \`git fetch --unshallow origin\` (or \`git fetch origin <default-branch>\` when HEAD is not shallow) to also compare with the merge-base, as CI does.`
77
+ };
78
+ const revision = result.stdout.trim();
79
+ return {
80
+ revision,
81
+ label: `merge-base ${revision.slice(0, 12)} with ${name}`
82
+ };
83
+ }
84
+ function previousDiagnostics(root, targets, revision) {
85
+ const renames = renamedPaths(root, true, revision === void 0 ? [] : [revision]);
86
+ const deletedFrom = revision === void 0 ? /* @__PURE__ */ new Map() : renamedPaths(root, false, [revision, "HEAD"]);
87
+ const previous = [.../* @__PURE__ */ new Set([...targets.map((file) => renames.get(file) ?? file), ...stagedNames(root, "D").map((file) => deletedFrom.get(file) ?? file)])];
88
+ return withPreviousTree(root, revision ?? "HEAD", previous.filter((file) => !LINT_CONFIG.test(file)), (tree) => {
89
+ const existing = previous.filter((file) => existsSync(join(tree, file)));
90
+ return existing.length ? lintDiagnostics(tree, void 0, existing, STAGED_LINT) : [];
91
+ });
92
+ }
93
+ /**
94
+ * How many of `staged` sit on a line unchanged since the base and match a
95
+ * finding `previous` reports on that line of the base, each base finding
96
+ * matched once.
97
+ */
98
+ function keptFindings(staged, previous, changes) {
99
+ const pool = /* @__PURE__ */ new Map();
100
+ for (const { file, line } of previous) {
101
+ const key = `${file}:${line}`;
102
+ pool.set(key, (pool.get(key) ?? 0) + 1);
103
+ }
104
+ let kept = 0;
105
+ for (const { file, line } of staged) {
106
+ const change = changes.get(file);
107
+ if (line === void 0 || change === void 0) continue;
108
+ const from = previousLine(change.hunks, line);
109
+ const key = `${change.previous}:${from}`;
110
+ const left = pool.get(key) ?? 0;
111
+ if (from === void 0 || left === 0) continue;
112
+ pool.set(key, left - 1);
113
+ kept += 1;
114
+ }
115
+ return kept;
116
+ }
117
+ /**
118
+ * Per rule, the findings in the files the branch changed since `revision`, at
119
+ * `revision` and in the index, so a merge-base credit is only paid while the
120
+ * branch as a whole does not raise the rule.
121
+ */
122
+ function branchCounts(root, revision) {
123
+ const paths = execFileSync("git", [
124
+ "diff",
125
+ "--cached",
126
+ "--name-only",
127
+ "--no-renames",
128
+ "-z",
129
+ revision
130
+ ], {
131
+ cwd: root,
132
+ encoding: "utf8"
133
+ }).split("\0").filter((file) => file && !LINT_CONFIG.test(file));
134
+ const lint = (tree) => {
135
+ const existing = paths.filter((file) => existsSync(join(tree, file)));
136
+ return countByRule(existing.length ? lintDiagnostics(tree, void 0, existing, STAGED_LINT) : []);
137
+ };
138
+ return {
139
+ before: withPreviousTree(root, revision, paths, lint),
140
+ after: withPreviousTree(root, revision, [], lint)
141
+ };
142
+ }
143
+ /** The ceilings `revision` (`:` for the index, which is what the commit will write; `HEAD:`) records; none when it has no ceilings file. */
144
+ function ceilingsAt(root, revision) {
145
+ const result = spawnSync("git", ["show", `${revision}${CEILINGS_FILE}`], {
146
+ cwd: root,
147
+ encoding: "utf8"
148
+ });
149
+ if (result.status !== 0) return {};
150
+ return parseCeilings(result.stdout, `${revision}${CEILINGS_FILE}`).rules;
151
+ }
152
+ /** Failures for each ceiling this commit raises that the variable does not list, so an approval for one rule cannot carry another. */
153
+ function unlistedRaises(root, approved) {
154
+ if (!approved.size) return [];
155
+ const head = ceilingsAt(root, "HEAD:");
156
+ return Object.entries(ceilingsAt(root, ":")).flatMap(([rule, count]) => approved.has(rule) || count <= (head[rule] ?? 0) ? [] : [`${rule}: this commit raises its ceiling from ${head[rule] ?? 0} to ${count}; APPROVED_RAISES does not list ${rule}.`]);
157
+ }
158
+ function unlisted(rule, approved) {
159
+ return approved.size ? [` APPROVED_RAISES does not list ${rule}.`] : [];
160
+ }
161
+ /** Tracked files git is told not to look at (`S` skip-worktree, lowercase assume-unchanged), whose working copy can differ from the index unseen. */
162
+ function hiddenTracked(root) {
163
+ return execFileSync("git", [
164
+ "ls-files",
165
+ "-v",
166
+ "-z"
167
+ ], {
168
+ cwd: root,
169
+ encoding: "utf8"
170
+ }).split("\0").filter((line) => /^(S|[a-z]) /u.test(line)).map((line) => line.slice(2));
171
+ }
172
+ function approvalRefusal(root, rule, max, holds) {
173
+ const unstaged = execFileSync("git", [
174
+ "diff",
175
+ "--name-only",
176
+ "-z"
177
+ ], {
178
+ cwd: root,
179
+ encoding: "utf8"
180
+ }).split("\0").filter(Boolean);
181
+ if (unstaged.length) return `${rule}: an approved raise is refused while ${unstaged.length} tracked file(s) have unstaged changes (${unstaged[0]}); stage or stash them first.`;
182
+ const hidden = hiddenTracked(root);
183
+ if (hidden.length) return `${rule}: an approved raise is refused while ${hidden.length} tracked file(s) are skip-worktree or assume-unchanged (${hidden[0]}); disable the sparse checkout or clear the bit first.`;
184
+ const staged = ceilingsAt(root, ":")[rule];
185
+ const head = ceilingsAt(root, "HEAD:")[rule] ?? 0;
186
+ if (staged !== max) return `${rule}: APPROVED_RAISES approves ${max}, but the staged ${CEILINGS_FILE} records ${staged ?? "no ceiling"}; the commit must write exactly ${max}.`;
187
+ if (max <= head) return `${rule}: APPROVED_RAISES approves ${max}, but this commit does not raise the ceiling above ${head} at HEAD.`;
188
+ return holds > max ? `${rule}: the repository holds ${holds} findings, but APPROVED_RAISES approves at most ${max}.` : void 0;
189
+ }
190
+ /**
191
+ * Settles `rule` against its approved `max`: it passes while this commit
192
+ * raises the ceiling from HEAD's to exactly `max` and the repository holds no
193
+ * more than `max`, so an approval left set accepts nothing in a later commit.
194
+ */
195
+ function settleApproved(root, rule, max, { holds, rise, shown }) {
196
+ const refusal = approvalRefusal(root, rule, max, holds);
197
+ if (refusal === void 0) return {
198
+ accepted: [`${rule} raised to ${max} (this commit adds ${rise}, ${holds} in the repository, ceiling ${max}), approved through APPROVED_RAISES`],
199
+ failures: []
200
+ };
201
+ return {
202
+ accepted: [],
203
+ failures: [refusal, ...shown.map((diagnostic) => ` ${diagnostic.location}: ${diagnostic.message}`)]
204
+ };
205
+ }
206
+ function higherCounts(first, second) {
207
+ const higher = new Map(first);
208
+ for (const [rule, count] of second) higher.set(rule, Math.max(count, higher.get(rule) ?? 0));
209
+ return higher;
210
+ }
211
+ function inRanges(ranges, file, line) {
212
+ return ranges.get(file)?.some(({ start, end }) => line >= start && line <= end) ?? false;
213
+ }
214
+ /**
215
+ * Fails each ceilinged rule whose findings in the staged files outnumber both
216
+ * what the same files, rename sources and deleted files had at HEAD and the
217
+ * staged findings that sit, on a line unchanged since the merge-base of HEAD
218
+ * with the pull request base (`GITHUB_BASE_REF`, else `origin/HEAD`), where
219
+ * the merge-base has a finding of the same rule, while the files the branch
220
+ * changed hold no more findings of that rule than at the merge-base; without a
221
+ * merge-base, HEAD alone.
222
+ * The count is net across the staged files, so a block moved between them, a
223
+ * legacy line that is reformatted, a line restored to its base form, or an
224
+ * edit of a file a legacy finding moved into earlier on the branch passes; a
225
+ * rise above both fails, and lists the findings on the lines that differ from
226
+ * HEAD and from the base.
227
+ */
228
+ function stagedRatchet(root, files) {
229
+ const approved = parseApprovedRaises();
230
+ const raised = unlistedRaises(root, approved);
231
+ const accepted = [];
232
+ const targets = files ?? stagedNames(root, "ACMR");
233
+ if (!targets.length) return {
234
+ failures: raised,
235
+ accepted
236
+ };
237
+ const ceilings = readCeilings(root);
238
+ const after = lintDiagnostics(root, void 0, targets, STAGED_LINT).filter(({ rule }) => Object.hasOwn(ceilings.rules, rule) || approved.has(rule));
239
+ if (!after.length) return {
240
+ failures: raised,
241
+ accepted
242
+ };
243
+ const base = comparisonBase(root);
244
+ const atHead = countByRule(previousDiagnostics(root, targets, void 0));
245
+ const headAdditions = stagedAdditions(root, targets);
246
+ const atBase = base.revision === void 0 ? void 0 : previousDiagnostics(root, targets, base.revision);
247
+ const baseChanges = base.revision === void 0 ? void 0 : stagedChanges(root, targets, base.revision);
248
+ let branch;
249
+ const measure = (rule, matches, head, total) => {
250
+ const kept = atBase === void 0 || baseChanges === void 0 ? void 0 : keptFindings(matches, atBase.filter((diagnostic) => diagnostic.rule === rule), baseChanges);
251
+ const rise = total - Math.max(head, kept ?? 0);
252
+ if (kept === void 0 || kept <= head || base.revision === void 0) return {
253
+ kept,
254
+ rise,
255
+ raised: void 0
256
+ };
257
+ branch ??= branchCounts(root, base.revision);
258
+ const from = branch.before.get(rule) ?? 0;
259
+ const to = branch.after.get(rule) ?? 0;
260
+ if (to <= from) return {
261
+ kept,
262
+ rise,
263
+ raised: void 0
264
+ };
265
+ return {
266
+ kept,
267
+ rise: Math.min(total - head, Math.max(to - from, rise)),
268
+ raised: `the files this branch changed hold ${to} at the index against ${from} at that merge-base, so the merge-base credit covers no added finding`
269
+ };
270
+ };
271
+ const failures = [];
272
+ let repository;
273
+ for (const [rule, total] of countByRule(after)) {
274
+ const head = atHead.get(rule) ?? 0;
275
+ if (total <= head) continue;
276
+ const matches = after.filter((diagnostic) => diagnostic.rule === rule);
277
+ const { kept, rise, raised } = measure(rule, matches, head, total);
278
+ if (rise <= 0) continue;
279
+ const added = matches.filter(({ file, line }) => line !== void 0 && inRanges(headAdditions, file, line) && (baseChanges === void 0 || previousLine(baseChanges.get(file)?.hunks ?? [], line) === void 0));
280
+ const max = approved.get(rule);
281
+ if (max !== void 0) {
282
+ repository ??= higherCounts(withPreviousTree(root, "HEAD", [], (tree) => countByRule(lintDiagnostics(tree, void 0, void 0, STAGED_LINT)), { wholeIndex: true }), countByRule(lintDiagnostics(root, void 0, void 0, STAGED_LINT)));
283
+ const settled = settleApproved(root, rule, max, {
284
+ holds: repository.get(rule) ?? 0,
285
+ rise,
286
+ shown: added.length ? added : matches
287
+ });
288
+ accepted.push(...settled.accepted);
289
+ failures.push(...settled.failures);
290
+ continue;
291
+ }
292
+ const counts = kept === void 0 || base.revision === void 0 ? `${head} at HEAD` : `${head} at HEAD, ${kept} unchanged since ${base.label}`;
293
+ failures.push(`${rule}: this commit adds ${rise} to the staged files (${counts}, ${total} staged)${raised === void 0 ? "" : `; ${raised}`}; the ceiling covers only legacy findings.`, ...unlisted(rule, approved), ...(added.length ? added : matches).map((diagnostic) => ` ${diagnostic.location}: ${diagnostic.message}\n Fix: ${diagnostic.help ?? "Resolve this finding; moving, reformatting or restoring a legacy finding to its base form is allowed, adding one is not."}`));
294
+ }
295
+ failures.unshift(...raised);
296
+ return {
297
+ failures: failures.length && base.revision === void 0 ? [...failures, base.note] : failures,
298
+ accepted
299
+ };
300
+ }
301
+ //#endregion
9
302
  //#region src/bin/ratchet.ts
303
+ function stagedResult(root, files) {
304
+ const staged = stagedRatchet(root, files.length ? files.map((file) => repositoryPath(root, resolve(file))) : void 0);
305
+ return {
306
+ failures: staged.failures,
307
+ accepted: staged.accepted,
308
+ lowered: [],
309
+ adoptions: [],
310
+ retired: false,
311
+ created: false
312
+ };
313
+ }
10
314
  runCli(() => {
11
315
  const { values, positionals } = parseArgs({
12
316
  options: {
@@ -20,13 +324,15 @@ runCli(() => {
20
324
  if (values.base !== void 0 && values.staged) throw new Error("--base cannot be combined with --staged.");
21
325
  if (values.update && values.staged) throw new Error("--staged cannot be combined with --update.");
22
326
  if (positionals.length && !values.staged) throw new Error("File arguments require --staged.");
23
- const result = values.staged ? {
24
- failures: stagedRatchet(root, positionals.length ? positionals.map((file) => repositoryPath(root, resolve(file))) : void 0),
25
- lowered: [],
26
- retired: false
27
- } : ratchet(root, values.update, values.base === void 0 ? void 0 : resolveRevision(root, values.base));
327
+ const result = values.staged ? stagedResult(root, positionals) : {
328
+ ...ratchet(root, values.update, values.base === void 0 ? void 0 : resolveRevision(root, values.base), suppressionBase(root, values.base)),
329
+ accepted: []
330
+ };
331
+ if (result.created) process.stdout.write(`Created ${CEILINGS_FILE} for the rules the pack newly enabled. Run antelopejs-sync.\n`);
332
+ for (const message of result.adoptions) process.stdout.write(`Adopted ${message}\n`);
28
333
  if (result.retired) process.stdout.write(`Deleted ${CEILINGS_FILE}: no debt left. Run antelopejs-sync.\n`);
29
334
  for (const message of result.lowered) process.stdout.write(`Lowered ${message}\n`);
335
+ for (const message of result.accepted) process.stderr.write(`APPROVED RAISE ACCEPTED: ${message}. APPROVED_RAISES is set in this environment, and only that lets this commit pass.\n`);
30
336
  for (const message of result.failures) process.stderr.write(`${message}\n`);
31
337
  if (!result.failures.length) process.stdout.write("Ratchet: within ceilings.\n");
32
338
  return result.failures.length ? 1 : 0;
@@ -1,103 +1,141 @@
1
1
  #!/usr/bin/env node
2
2
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
3
- import { o as repositoryRoot, s as resolveRevision } from "../files-2FikHZ9F.mjs";
4
- import { a as parseBudget, c as checkPolicy, i as checkSuppressions, n as SUPPRESSIONS_FILE, o as safetyCeiling, s as stagedSuppressions } from "../suppression-budget-Yyf5_J5l.mjs";
5
- import { readFileSync } from "node:fs";
6
- import { join } from "node:path";
7
- import { spawnSync } from "node:child_process";
3
+ import { c as repositoryRoot, r as changedFiles } from "../files-DJ0TeaTU.mjs";
4
+ import { n as unusedDirectives } from "../oxlint-DIV-lLSS.mjs";
5
+ import { c as stagedSuppressions, i as checkSuppressions, l as checkPolicy, s as stagedNames } from "../suppression-budget-C0SkPO5R.mjs";
6
+ import { c as suppressionsIn, i as inWorktree } from "../suppressions-DM60NkvL.mjs";
7
+ import { n as suppressionBase, t as raisedCeilings } from "../suppression-base-9L8dlMQK.mjs";
8
+ import { readdirSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import { execFileSync, spawnSync } from "node:child_process";
8
11
  import { parseArgs } from "node:util";
9
- //#region src/guardrails/suppression-base.ts
10
- function verified(root, ref) {
11
- const result = spawnSync("git", [
12
- "rev-parse",
13
- "--verify",
14
- "--quiet",
15
- "--end-of-options",
16
- `${ref}^{commit}`
17
- ], {
18
- cwd: root,
19
- encoding: "utf8"
20
- });
21
- return result.status === 0 ? result.stdout.trim() : void 0;
12
+ //#region src/guardrails/dead-directives.ts
13
+ const BLOCK_DISABLE = /-disable$/u;
14
+ const ESLINT_CONFIG = /^(?:eslint\.config\.[cm]?[jt]s|\.eslintrc(?:\..+)?)$/u;
15
+ function directivesIn(file, text) {
16
+ const grouped = /* @__PURE__ */ new Map();
17
+ for (const found of suppressionsIn(file, text)) {
18
+ if (found.kind !== "rule") continue;
19
+ const key = `${found.line}\0${found.directive}`;
20
+ const known = grouped.get(key);
21
+ if (known === void 0) grouped.set(key, entry(found));
22
+ else known.rules.push(found.rule);
23
+ }
24
+ return [...grouped.values()];
22
25
  }
23
- function fetchBase(root, branch, remote) {
24
- const result = spawnSync("git", [
25
- "fetch",
26
- "--quiet",
27
- "--no-tags",
28
- "--depth=1",
29
- "origin",
30
- `+refs/heads/${branch}:${remote}`
31
- ], {
32
- cwd: root,
33
- encoding: "utf8",
34
- env: {
35
- ...process.env,
36
- GIT_TERMINAL_PROMPT: "0"
37
- },
38
- stdio: [
39
- "ignore",
40
- "ignore",
41
- "pipe"
42
- ]
43
- });
44
- if (result.status === 0) return;
45
- const detail = result.error?.message ?? result.stderr.trim();
46
- throw new Error(`Cannot compare with the pull request base: ${remote} is missing and fetching ${branch} from origin failed${detail ? ` (${detail})` : ""}. In CI, fetch the base branch before this check with credentials, or pass --base.`);
26
+ function entry(found) {
27
+ return {
28
+ file: found.file,
29
+ line: found.line,
30
+ directive: found.directive,
31
+ rules: [found.rule],
32
+ reason: found.reason
33
+ };
34
+ }
35
+ function written(directive, rules = directive.rules) {
36
+ const named = rules.filter((rule) => rule !== "*");
37
+ return `\`${[directive.directive, ...named.length ? [named.join(", ")] : []].join(" ")}\``;
38
+ }
39
+ /** Whether an ESLint config sits in the file's directory or above it, so ESLint may run the rules an `eslint-` directive names. */
40
+ function lintedByEslint(root, file) {
41
+ for (let directory = dirname(join(root, file)); directory.startsWith(root); directory = dirname(directory)) {
42
+ if (readdirSync(directory).some((name) => ESLINT_CONFIG.test(name))) return true;
43
+ if (directory === root) break;
44
+ }
45
+ return false;
46
+ }
47
+ /** The directive oxlint's report is about: on its line, else the nearest earlier block disable it ends at an `-enable` on that line, naming the dead rule when oxlint names one. */
48
+ function reported(directives, unused) {
49
+ const named = (directive) => unused.rules === void 0 || unused.rules.every((rule) => directive.rules.includes(rule));
50
+ const here = directives.filter((directive) => directive.file === unused.file && directive.line === unused.line && named(directive));
51
+ if (here.length) return here[0];
52
+ return directives.filter((directive) => directive.file === unused.file && directive.line < unused.line && BLOCK_DISABLE.test(directive.directive) && named(directive)).at(-1);
53
+ }
54
+ function deadFailure(directive, dead) {
55
+ const at = `${directive.file}:${directive.line}`;
56
+ if (directive.rules.every((rule) => dead.has(rule))) return [`${at}: ${written(directive)} suppresses nothing. Fix: delete the directive.`];
57
+ const closing = BLOCK_DISABLE.test(directive.directive) ? " and from its enable" : "";
58
+ return [...dead].map((rule) => `${at}: ${written(directive, [rule])} suppresses nothing. Fix: drop \`${rule}\` from the directive${closing}.`);
59
+ }
60
+ function reasonlessFailure(directive) {
61
+ if (directive.reason !== "" || directive.rules.includes("*")) return [];
62
+ return [`${directive.file}:${directive.line}: ${written(directive)} gives no reason. Fix: add \` -- <why this line needs it>\` after the rules, or delete the directive.`];
47
63
  }
48
64
  /**
49
- * The commit a pull request merges into: `base` when given; in CI the
50
- * `GITHUB_BASE_REF` branch, taken from the local `origin/<branch>` ref when
51
- * present and otherwise fetched from `origin`, an error naming the missing ref
52
- * when the fetch fails; otherwise `origin/HEAD`, the remote's default branch.
53
- * A requested base that cannot be resolved is an error; without one, a
54
- * repository with no `origin/HEAD` has no base.
65
+ * Fails, in each of `files`, every lint directive that suppresses nothing
66
+ * under the repository's own lint configuration with its ratchet rules
67
+ * enabled, and every directive naming rules that gives no reason. Directives
68
+ * in other files are left alone, so adopting the check changes no existing
69
+ * file until a change touches it. `eslint-` directives under an ESLint config
70
+ * are left to ESLint, and `.vue` files are not linted by oxlint.
55
71
  */
56
- function suppressionBase(root, base) {
57
- if (base !== void 0) return resolveRevision(root, base);
58
- const branch = process.env.GITHUB_BASE_REF;
59
- if (branch) {
60
- const remote = `refs/remotes/origin/${branch}`;
61
- if (verified(root, remote) === void 0) fetchBase(root, branch, remote);
62
- return resolveRevision(root, remote);
72
+ function deadDirectiveFailures(root, files) {
73
+ const directives = inWorktree(root, directivesIn, files);
74
+ const readByOxlint = directives.filter(({ file, directive }) => !file.endsWith(".vue") && !(directive.startsWith("eslint-") && lintedByEslint(root, file)));
75
+ const lintable = [...new Set(readByOxlint.map(({ file }) => file))];
76
+ const dead = /* @__PURE__ */ new Map();
77
+ const unplaced = [];
78
+ for (const item of lintable.length ? unusedDirectives(root, lintable) : []) {
79
+ const directive = reported(readByOxlint, item);
80
+ if (directive === void 0) {
81
+ unplaced.push(`${item.file}:${item.line}: ${item.message} Fix: delete the directive.`);
82
+ continue;
83
+ }
84
+ const rules = dead.get(directive) ?? /* @__PURE__ */ new Set();
85
+ for (const rule of item.rules ?? directive.rules) rules.add(rule);
86
+ dead.set(directive, rules);
63
87
  }
64
- return verified(root, "refs/remotes/origin/HEAD");
88
+ return [...unplaced, ...directives.flatMap((directive) => {
89
+ const rules = dead.get(directive);
90
+ return rules === void 0 ? reasonlessFailure(directive) : deadFailure(directive, rules);
91
+ })];
92
+ }
93
+ function mergeBase(root, revision) {
94
+ const result = spawnSync("git", [
95
+ "merge-base",
96
+ revision,
97
+ "HEAD"
98
+ ], {
99
+ cwd: root,
100
+ encoding: "utf8"
101
+ });
102
+ return result.status === 0 ? result.stdout.trim() : revision;
65
103
  }
66
104
  /**
67
- * Fails each ceiling of the working-tree budget that is higher than on
68
- * `revision`, and each rule that `revision` lists but the working tree
69
- * dropped. The safety ceiling may rise by what the SAFETY rule's own
70
- * ceiling falls. A base without a budget, a first adoption, passes.
105
+ * The files a pull request changes: the working tree against the merge-base
106
+ * of `revision` and HEAD (`revision` itself when they have none, as in a
107
+ * shallow checkout), untracked files included; against HEAD without one.
71
108
  */
72
- function raisedCeilings(root, revision) {
73
- const committed = spawnSync("git", ["show", `${revision}:${SUPPRESSIONS_FILE}`], {
109
+ function touchedFiles(root, revision) {
110
+ if (revision === void 0) return [...changedFiles(root)];
111
+ const tracked = execFileSync("git", [
112
+ "diff",
113
+ "--name-only",
114
+ "--no-renames",
115
+ "-z",
116
+ mergeBase(root, revision)
117
+ ], {
74
118
  cwd: root,
75
- encoding: "utf8"
119
+ encoding: "utf8",
120
+ maxBuffer: 67108864
76
121
  });
77
- if (committed.status !== 0) return [];
78
- const label = `${revision.slice(0, 12)}:${SUPPRESSIONS_FILE}`;
79
- const base = parseBudget(committed.stdout, label);
80
- const current = parseBudget(readFileSync(join(root, SUPPRESSIONS_FILE), "utf8"), SUPPRESSIONS_FILE);
81
- const failures = [];
82
- const compare = (key, before, after) => {
83
- if (after === void 0) failures.push(`${SUPPRESSIONS_FILE}: removes ${key}, which has ceiling ${before} on the base. Keep the key; lower it with suppressions:update.`);
84
- else if (after > before) failures.push(`${SUPPRESSIONS_FILE}: raises ${key} from ${before} on the base to ${after}.`);
85
- };
86
- for (const rule of /* @__PURE__ */ new Set([...Object.keys(base.rules), ...Object.keys(current.rules)])) compare(`lint rule \`${rule}\``, base.rules[rule] ?? 0, Object.hasOwn(base.rules, rule) ? current.rules[rule] : current.rules[rule] ?? 0);
87
- compare("`@ts-expect-error`", base.tsExpectError, current.tsExpectError);
88
- compare("`@ts-ignore`", base.tsIgnore, current.tsIgnore);
89
- compare("`SAFETY:` comments", safetyCeiling(base, current.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0), current.safety);
90
- return failures.length ? [...failures, "Ceilings only go down. Fix the code, or remove another suppression of the same kind; raising a ceiling needs the operator's approval through the ruleset bypass."] : [];
122
+ return [.../* @__PURE__ */ new Set([...tracked.split("\0"), ...changedFiles(root)])].filter(Boolean);
91
123
  }
92
124
  //#endregion
93
125
  //#region src/bin/suppressions.ts
94
126
  function fullCheck(root, update, base) {
95
127
  const failures = checkSuppressions(root, update);
96
128
  const revision = suppressionBase(root, base);
97
- return revision === void 0 ? [...failures, ...checkPolicy(root)] : [
129
+ const dead = deadDirectiveFailures(root, touchedFiles(root, revision));
130
+ return revision === void 0 ? [
131
+ ...failures,
132
+ ...checkPolicy(root),
133
+ ...dead
134
+ ] : [
98
135
  ...raisedCeilings(root, revision),
99
136
  ...failures,
100
- ...checkPolicy(root, revision)
137
+ ...checkPolicy(root, revision),
138
+ ...dead
101
139
  ];
102
140
  }
103
141
  runCli(() => {
@@ -111,7 +149,7 @@ runCli(() => {
111
149
  });
112
150
  if (values.staged && (values.update || values.base !== void 0)) throw new Error("--staged cannot be combined with --update or --base.");
113
151
  const root = repositoryRoot();
114
- const failures = values.staged ? stagedSuppressions(root) : fullCheck(root, values.update, values.base);
152
+ const failures = values.staged ? [...stagedSuppressions(root), ...deadDirectiveFailures(root, stagedNames(root, "ACMR"))] : fullCheck(root, values.update, values.base);
115
153
  for (const failure of failures) process.stderr.write(`${failure}\n`);
116
154
  return failures.length ? 1 : 0;
117
155
  });