@antelopejs/tooling-configs 0.2.7 → 0.2.9
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/README.md +31 -18
- package/dist/bin/api-diff.mjs +15 -8
- package/dist/bin/check-size.mjs +4 -3
- package/dist/bin/checks.mjs +2 -1
- package/dist/bin/comment-proof.mjs +3 -2
- package/dist/bin/garden.d.mts +1 -0
- package/dist/bin/garden.mjs +1480 -0
- package/dist/bin/ratchet.mjs +4 -3
- package/dist/bin/suppressions.mjs +11 -5
- package/dist/bin/sync.mjs +37 -34
- package/dist/ci-workflow-BDy6hQJ6.mjs +164 -0
- package/dist/cli-4Tv71vYk.mjs +19 -0
- package/dist/{files-BMxKg5IR.mjs → files-2FikHZ9F.mjs} +1 -11
- package/dist/{ratchet-zzo2tT74.mjs → ratchet-B2qYUs51.mjs} +3 -3
- package/dist/{size-Fp3aWSkN.mjs → size-BVgNbLO6.mjs} +1 -1
- package/dist/{staged-ratchet-CJHjp2kx.mjs → staged-ratchet-BNfjcbih.mjs} +1 -1
- package/dist/suppression-budget-Bq30tJDS.mjs +282 -0
- package/dist/{suppressions-CgGa-kh7.mjs → suppressions-BJAngUxo.mjs} +104 -18
- package/dist/{typescript-DIXhKgXR.mjs → typescript-C54ONh9m.mjs} +63 -14
- package/package.json +2 -1
- package/dist/suppression-budget-N5ONsh2g.mjs +0 -144
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
|
|
2
|
+
import { n as changedFiles } from "./files-2FikHZ9F.mjs";
|
|
3
|
+
import { t as stagedAdditions } from "./staged-ratchet-BNfjcbih.mjs";
|
|
4
|
+
import { a as revisionSuppressions, i as openDisablesIn, n as countSuppressions, o as worktreeSuppressions, r as inWorktree, t as atRevision } from "./suppressions-BJAngUxo.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 };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
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-
|
|
2
|
+
import { i as gitFiles, r as generatedOutput } from "./files-2FikHZ9F.mjs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { existsSync, lstatSync, readFileSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
@@ -12,6 +12,8 @@ const DESCRIPTION = /\s-{2,}\s|\s-{2,}$/u;
|
|
|
12
12
|
/** The comment `anti-slop/require-safety-comment-for-type-assertion` accepts as a justification. */
|
|
13
13
|
const SAFETY_COMMENT = markerPattern(DEFAULT_SAFETY_MARKERS);
|
|
14
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;
|
|
15
17
|
let compiler;
|
|
16
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). */
|
|
17
19
|
function typescript() {
|
|
@@ -64,14 +66,28 @@ function vueComments(text) {
|
|
|
64
66
|
});
|
|
65
67
|
return comments;
|
|
66
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
|
+
}
|
|
67
82
|
function lintDirective(value) {
|
|
68
83
|
const text = value.replace(/^\s*\*?\s*/u, "");
|
|
69
84
|
const directive = LINT_DIRECTIVE.exec(text);
|
|
70
85
|
if (directive === null) return [];
|
|
71
|
-
const rules = directive[2]
|
|
72
|
-
return
|
|
86
|
+
const { rules, reason } = directiveParts(directive[2]);
|
|
87
|
+
return rules.map((rule) => ({
|
|
73
88
|
directive: directive[1],
|
|
74
|
-
rule
|
|
89
|
+
rule,
|
|
90
|
+
reason
|
|
75
91
|
}));
|
|
76
92
|
}
|
|
77
93
|
/** TypeScript reads a directive from a line comment, or from the last line of a block comment. */
|
|
@@ -79,48 +95,114 @@ function tsDirective(comment) {
|
|
|
79
95
|
const text = comment.line ? comment.value : comment.value.slice(comment.value.lastIndexOf("\n") + 1);
|
|
80
96
|
const match = TS_DIRECTIVE.exec(text);
|
|
81
97
|
if (match === null) return void 0;
|
|
82
|
-
return
|
|
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;
|
|
83
116
|
}
|
|
84
117
|
/** The suppressions in one code file's text; `file` decides the language and labels each entry. */
|
|
85
118
|
function suppressionsIn(file, text) {
|
|
86
119
|
if (!CODE_FILE.test(file) || !(CANDIDATE.test(text) || SAFETY_COMMENT.test(text))) return [];
|
|
87
|
-
const comments = file.endsWith(".vue") ? vueComments(text) : scriptComments(text, scriptKind(file.slice(file.lastIndexOf(".") + 1)), 0);
|
|
88
120
|
const found = [];
|
|
89
|
-
for (const comment of
|
|
90
|
-
const line = text
|
|
91
|
-
for (const { directive, rule } of lintDirective(comment.value)) found.push({
|
|
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({
|
|
92
124
|
kind: "rule",
|
|
93
125
|
rule,
|
|
94
126
|
directive,
|
|
127
|
+
reason,
|
|
95
128
|
file,
|
|
96
129
|
line
|
|
97
130
|
});
|
|
98
131
|
const typeDirective = tsDirective(comment);
|
|
99
132
|
if (typeDirective !== void 0) found.push({
|
|
100
|
-
|
|
133
|
+
...typeDirective,
|
|
101
134
|
file,
|
|
102
135
|
line
|
|
103
136
|
});
|
|
104
137
|
if (SAFETY_COMMENT.test(comment.value)) found.push({
|
|
105
138
|
kind: "safety",
|
|
139
|
+
reason: normalized(SAFETY_REASON.exec(comment.value)?.[1] ?? ""),
|
|
106
140
|
file,
|
|
107
141
|
line
|
|
108
142
|
});
|
|
109
143
|
}
|
|
110
144
|
return found;
|
|
111
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
|
+
}
|
|
112
190
|
function authoredCode(root, files) {
|
|
113
|
-
const generated =
|
|
191
|
+
const generated = generatedIn(root);
|
|
114
192
|
return files.filter((file) => CODE_FILE.test(file) && !generated(file));
|
|
115
193
|
}
|
|
116
|
-
/**
|
|
117
|
-
function
|
|
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)) {
|
|
118
196
|
return authoredCode(root, files).flatMap((file) => {
|
|
119
197
|
const path = join(root, file);
|
|
120
198
|
if (!existsSync(path) || !lstatSync(path).isFile()) return [];
|
|
121
|
-
return
|
|
199
|
+
return read(file, readFileSync(path, "utf8"));
|
|
122
200
|
});
|
|
123
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
|
+
}
|
|
124
206
|
function blobs(root, specs) {
|
|
125
207
|
if (!specs.length) return [];
|
|
126
208
|
const output = execFileSync("git", ["cat-file", "--batch"], {
|
|
@@ -145,11 +227,11 @@ function blobs(root, specs) {
|
|
|
145
227
|
return texts;
|
|
146
228
|
}
|
|
147
229
|
/**
|
|
148
|
-
*
|
|
230
|
+
* What `read` finds in authored code files at a committed revision, or in the
|
|
149
231
|
* index when `revision` is the empty string. Without `files` every file of
|
|
150
232
|
* that tree is read.
|
|
151
233
|
*/
|
|
152
|
-
function
|
|
234
|
+
function atRevision(root, revision, read, files) {
|
|
153
235
|
const code = authoredCode(root, files ?? execFileSync("git", revision === "" ? ["ls-files", "-z"] : [
|
|
154
236
|
"ls-tree",
|
|
155
237
|
"-r",
|
|
@@ -164,9 +246,13 @@ function revisionSuppressions(root, revision, files) {
|
|
|
164
246
|
const texts = blobs(root, code.map((file) => `${revision}:${file}`));
|
|
165
247
|
return code.flatMap((file, index) => {
|
|
166
248
|
const text = texts[index];
|
|
167
|
-
return text === void 0 ? [] :
|
|
249
|
+
return text === void 0 ? [] : read(file, text);
|
|
168
250
|
});
|
|
169
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
|
+
}
|
|
170
256
|
/** Totals by budget key, rules sorted by id. */
|
|
171
257
|
function countSuppressions(suppressions) {
|
|
172
258
|
const counts = {
|
|
@@ -181,4 +267,4 @@ function countSuppressions(suppressions) {
|
|
|
181
267
|
return counts;
|
|
182
268
|
}
|
|
183
269
|
//#endregion
|
|
184
|
-
export { revisionSuppressions as n, worktreeSuppressions as r,
|
|
270
|
+
export { revisionSuppressions as a, openDisablesIn as i, countSuppressions as n, worktreeSuppressions as o, inWorktree as r, atRevision as t };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { c as trackedManifests, s as resolveRevision } from "./files-
|
|
2
|
-
import {
|
|
1
|
+
import { c as trackedManifests, s as resolveRevision } from "./files-2FikHZ9F.mjs";
|
|
2
|
+
import { i as parseManifest } from "./package-Dtjt_lSa.mjs";
|
|
3
|
+
import { a as revisionSuppressions, n as countSuppressions } from "./suppressions-BJAngUxo.mjs";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
4
5
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
5
6
|
import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
|
|
@@ -82,10 +83,10 @@ function applyAllowance(policy, base, head, remove) {
|
|
|
82
83
|
}
|
|
83
84
|
return removed;
|
|
84
85
|
}
|
|
85
|
-
/** The "Added (allowed)" list with its count,
|
|
86
|
+
/** The "Added (allowed)" list with its count when anything was allowed, and the problems that kept additions from passing; empty when there is nothing to report. */
|
|
86
87
|
function describeAllowance(policy) {
|
|
87
88
|
const lines = [...policy.allowed.values()].map(({ directory, subpath }) => ` ${directory}: ./${subpath}\n`).sort();
|
|
88
|
-
return `Added (allowed): ${lines.length}\n${lines.join("")}${[...policy.problems].map((problem) => `Not internal: ${problem}\n`).join("")}`;
|
|
89
|
+
return `${lines.length ? `Added (allowed): ${lines.length}\n${lines.join("")}` : ""}${[...policy.problems].map((problem) => `Not internal: ${problem}\n`).join("")}`;
|
|
89
90
|
}
|
|
90
91
|
//#endregion
|
|
91
92
|
//#region src/guardrails/revisions.ts
|
|
@@ -217,6 +218,43 @@ function revisionCounts(root, baseRef) {
|
|
|
217
218
|
return `\nSuppressions in authored code files (${baseRef} and committed HEAD). A lint directive counts once per rule it names; \`*\` is a directive naming none.\n| Suppressions | base | HEAD |\n| --- | ---: | ---: |\n${countRows(base, head).map(([label, before, after]) => `| ${label} | ${before} | ${after} |`).join("\n")}\n`;
|
|
218
219
|
}
|
|
219
220
|
//#endregion
|
|
221
|
+
//#region src/guardrails/declared-typescript.ts
|
|
222
|
+
const DEPENDENCY_FIELDS = [
|
|
223
|
+
"dependencies",
|
|
224
|
+
"devDependencies",
|
|
225
|
+
"peerDependencies",
|
|
226
|
+
"optionalDependencies"
|
|
227
|
+
];
|
|
228
|
+
function readManifest(directory) {
|
|
229
|
+
const file = join(directory, "package.json");
|
|
230
|
+
return existsSync(file) ? parseManifest(readFileSync(file, "utf8")) : void 0;
|
|
231
|
+
}
|
|
232
|
+
function declares(manifest) {
|
|
233
|
+
return DEPENDENCY_FIELDS.some((field) => manifest?.[field]?.typescript !== void 0);
|
|
234
|
+
}
|
|
235
|
+
/** The nearest manifest at or above `directory` that configures a workspace, never leaving the repository that contains it. */
|
|
236
|
+
function workspaceManifest(directory) {
|
|
237
|
+
for (let current = directory;; current = dirname(current)) {
|
|
238
|
+
const manifest = readManifest(current);
|
|
239
|
+
if (manifest !== void 0 && (manifest.workspaces !== void 0 || existsSync(join(current, "pnpm-workspace.yaml")))) return manifest;
|
|
240
|
+
if (existsSync(join(current, ".git")) || dirname(current) === current) return void 0;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** Whether the package at `directory`, or the workspace root above it, declares `typescript` as a dependency of any kind. */
|
|
244
|
+
function declaresTypeScript(directory) {
|
|
245
|
+
return declares(readManifest(directory)) || declares(workspaceManifest(directory));
|
|
246
|
+
}
|
|
247
|
+
/** The directory of the package relative to the repository that contains it, `.` for the repository root; the same for every revision of the repository. */
|
|
248
|
+
function repositoryDirectory(directory) {
|
|
249
|
+
for (let current = directory;; current = dirname(current)) if (existsSync(join(current, ".git")) || dirname(current) === current) return relative(current, directory).split("\\").join("/") || ".";
|
|
250
|
+
}
|
|
251
|
+
/** The package as an error names it: its `name` when it has one, and its directory. */
|
|
252
|
+
function describePackage(directory) {
|
|
253
|
+
const name = readManifest(directory)?.name;
|
|
254
|
+
const where = repositoryDirectory(directory);
|
|
255
|
+
return name === void 0 ? where : `${name} (${where})`;
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
220
258
|
//#region src/guardrails/typescript.ts
|
|
221
259
|
/** A proof analyses only packages that publish something: not private, and declaring at least one of `exports`, `main`, `types`, `typings` or `typesVersions`. */
|
|
222
260
|
function unpublishedReason(manifest) {
|
|
@@ -261,21 +299,30 @@ function packageRoot(file) {
|
|
|
261
299
|
}
|
|
262
300
|
return directory;
|
|
263
301
|
}
|
|
264
|
-
|
|
265
|
-
function loadTypeScript(directory) {
|
|
266
|
-
const own = createRequire(import.meta.url);
|
|
267
|
-
let file;
|
|
302
|
+
function resolveTypeScript(directory) {
|
|
268
303
|
try {
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
304
|
+
return {
|
|
305
|
+
file: createRequire(join(directory, "package.json")).resolve("typescript"),
|
|
306
|
+
fallback: false
|
|
307
|
+
};
|
|
308
|
+
} catch (error) {
|
|
309
|
+
if (declaresTypeScript(directory)) throw new Error(`${describePackage(directory)} declares typescript but it cannot be resolved from the package directory, so the compiler it builds with is not available. Install dependencies (run pnpm install) and retry.`, { cause: error });
|
|
310
|
+
return {
|
|
311
|
+
file: createRequire(createRequire(import.meta.url).resolve("dts-bundle-generator")).resolve("typescript"),
|
|
312
|
+
fallback: true
|
|
313
|
+
};
|
|
272
314
|
}
|
|
315
|
+
}
|
|
316
|
+
/** Loads the compiler a package builds with, including a package-local installation in a workspace. A package that declares `typescript` (itself or through its workspace root) but cannot resolve it is an error; only a package that declares none falls back to the one `dts-bundle-generator` brings, with a `notice`. A TypeScript without the programmatic API (7 and later) is an error rather than a crash. */
|
|
317
|
+
function loadTypeScript(directory) {
|
|
318
|
+
const { file, fallback } = resolveTypeScript(directory);
|
|
273
319
|
const compiler = createRequire(file)("typescript");
|
|
274
320
|
const root = packageRoot(file);
|
|
275
321
|
if (compiler.sys === void 0 || !("createProgram" in compiler)) throw new Error(`TypeScript ${compiler.version} at ${root} has no programmatic compiler API (sys, createProgram), so this package cannot be analysed. Build it with a TypeScript that has one, or mark the package private.`);
|
|
276
322
|
return {
|
|
277
323
|
compiler,
|
|
278
|
-
root
|
|
324
|
+
root,
|
|
325
|
+
notice: fallback ? `${repositoryDirectory(directory)}: declares no typescript; using the pack's TypeScript ${compiler.version}\n` : void 0
|
|
279
326
|
};
|
|
280
327
|
}
|
|
281
328
|
const TEST_SOURCE_GLOBS = [
|
|
@@ -317,7 +364,7 @@ function copyDeclarations(program, directory, output) {
|
|
|
317
364
|
return files;
|
|
318
365
|
}
|
|
319
366
|
function parseConfig(directory) {
|
|
320
|
-
const { compiler, root } = loadTypeScript(directory);
|
|
367
|
+
const { compiler, root, notice } = loadTypeScript(directory);
|
|
321
368
|
const config = compiler.readConfigFile(join(directory, "tsconfig.json"), compiler.sys.readFile);
|
|
322
369
|
if (config.error) failDiagnostics(compiler, [config.error]);
|
|
323
370
|
const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, directory);
|
|
@@ -325,6 +372,7 @@ function parseConfig(directory) {
|
|
|
325
372
|
return {
|
|
326
373
|
compiler,
|
|
327
374
|
root,
|
|
375
|
+
notice,
|
|
328
376
|
parsed
|
|
329
377
|
};
|
|
330
378
|
}
|
|
@@ -334,7 +382,7 @@ function outputRoot(directory) {
|
|
|
334
382
|
}
|
|
335
383
|
/** Emits with the package's compiler and config; test roots and outputs never enter either proof. `modules` maps each emitted file to its source module. */
|
|
336
384
|
function emitPackage(directory, output, declarations) {
|
|
337
|
-
const { compiler, root, parsed } = parseConfig(directory);
|
|
385
|
+
const { compiler, root, notice, parsed } = parseConfig(directory);
|
|
338
386
|
const options = {
|
|
339
387
|
...parsed.options,
|
|
340
388
|
rootDir: parsed.options.rootDir ?? (parsed.options.outDir ? void 0 : directory),
|
|
@@ -375,6 +423,7 @@ function emitPackage(directory, output, declarations) {
|
|
|
375
423
|
return {
|
|
376
424
|
compiler,
|
|
377
425
|
compilerRoot: root,
|
|
426
|
+
notice,
|
|
378
427
|
files,
|
|
379
428
|
modules,
|
|
380
429
|
options: parsed.options
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@antelopejs/tooling-configs",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.9",
|
|
4
4
|
"description": "Shared tooling presets for AntelopeJS repositories: oxlint (with the vendored anti-slop rules), oxfmt, ESLint for Nuxt layers, Knip, and an interface range check",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"antelopejs",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"antelopejs-check-size": "./dist/bin/check-size.mjs",
|
|
27
27
|
"antelopejs-checks": "./dist/bin/checks.mjs",
|
|
28
28
|
"antelopejs-comment-proof": "./dist/bin/comment-proof.mjs",
|
|
29
|
+
"antelopejs-garden": "./dist/bin/garden.mjs",
|
|
29
30
|
"antelopejs-ratchet": "./dist/bin/ratchet.mjs",
|
|
30
31
|
"antelopejs-suppressions": "./dist/bin/suppressions.mjs",
|
|
31
32
|
"antelopejs-sync": "./dist/bin/sync.mjs"
|