@antelopejs/tooling-configs 0.2.7 → 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.
- package/README.md +20 -18
- package/dist/bin/api-diff.mjs +13 -7
- package/dist/bin/check-size.mjs +1 -1
- package/dist/bin/comment-proof.mjs +1 -1
- package/dist/bin/suppressions.mjs +9 -4
- package/dist/bin/sync.mjs +12 -4
- package/dist/suppression-budget-Cu0wOmFO.mjs +282 -0
- package/dist/{suppressions-CgGa-kh7.mjs → suppressions-C3AE6_I-.mjs} +103 -17
- package/dist/{typescript-DIXhKgXR.mjs → typescript-YufoJnck.mjs} +62 -13
- package/package.json +1 -1
- package/dist/suppression-budget-N5ONsh2g.mjs +0 -144
package/README.md
CHANGED
|
@@ -17,22 +17,22 @@ The AntelopeJS guardrail pack: shared lint, format and dead-code presets, the co
|
|
|
17
17
|
|
|
18
18
|
## What's in the box
|
|
19
19
|
|
|
20
|
-
| Export | Import | What it gives
|
|
21
|
-
| ------------------ | ------------------------------------------------------------------------- |
|
|
22
|
-
| `./oxc/lint` | `import { antelopePreset } from "@antelopejs/tooling-configs/oxc/lint"` | The oxlint preset
|
|
23
|
-
| `./oxc/fmt` | `import { antelopeFmtPreset } from "@antelopejs/tooling-configs/oxc/fmt"` | The oxfmt preset (house style)
|
|
24
|
-
| `./eslint` | `import { antelopeNuxtConfig } from "@antelopejs/tooling-configs/eslint"` | ESLint for Nuxt layers
|
|
25
|
-
| `./knip` | `import { antelopeKnipConfig } from "@antelopejs/tooling-configs/knip"` | Knip for AntelopeJS modules
|
|
26
|
-
| `./oxc/anti-slop` | Loaded by the oxlint preset as a JS plugin | The vendored [anti-slop](https://github.com/dmmulroy/anti-slop) rules
|
|
27
|
-
| `./oxc/guardrails` | Loaded by the oxlint preset as a JS plugin | The `antelopejs` comment and test-quality rules
|
|
28
|
-
| bin | `antelopejs-sync` | Writes the guardrail pack into a repository; `--check` reports drift
|
|
29
|
-
| bin | `antelopejs-checks` | Runs every check and prints only the failures
|
|
30
|
-
| bin | `antelopejs-ratchet` | Fails when recorded debt grows; `--update` lowers the record
|
|
31
|
-
| bin | `antelopejs-suppressions` | Fails when suppressions exceed their budget; `--update` lowers the budget
|
|
32
|
-
| bin | `antelopejs-check-size` | Fails on authored files over 20,000 bytes and on blanket disable directives
|
|
33
|
-
| bin | `antelopejs-api-diff <base-ref>` | Compares published declaration bundles against committed HEAD
|
|
34
|
-
| bin | `antelopejs-comment-proof <base-ref>` | Compares comment-free JavaScript emit against committed HEAD
|
|
35
|
-
| bin | `antelopejs-check-interface-ranges` | Fails on interface ranges that break module startup
|
|
20
|
+
| Export | Import | What it gives |
|
|
21
|
+
| ------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `./oxc/lint` | `import { antelopePreset } from "@antelopejs/tooling-configs/oxc/lint"` | The oxlint preset |
|
|
23
|
+
| `./oxc/fmt` | `import { antelopeFmtPreset } from "@antelopejs/tooling-configs/oxc/fmt"` | The oxfmt preset (house style) |
|
|
24
|
+
| `./eslint` | `import { antelopeNuxtConfig } from "@antelopejs/tooling-configs/eslint"` | ESLint for Nuxt layers |
|
|
25
|
+
| `./knip` | `import { antelopeKnipConfig } from "@antelopejs/tooling-configs/knip"` | Knip for AntelopeJS modules |
|
|
26
|
+
| `./oxc/anti-slop` | Loaded by the oxlint preset as a JS plugin | The vendored [anti-slop](https://github.com/dmmulroy/anti-slop) rules |
|
|
27
|
+
| `./oxc/guardrails` | Loaded by the oxlint preset as a JS plugin | The `antelopejs` comment and test-quality rules |
|
|
28
|
+
| bin | `antelopejs-sync` | Writes the guardrail pack into a repository; `--check` reports drift |
|
|
29
|
+
| bin | `antelopejs-checks` | Runs every check and prints only the failures |
|
|
30
|
+
| bin | `antelopejs-ratchet` | Fails when recorded debt grows; `--update` lowers the record |
|
|
31
|
+
| bin | `antelopejs-suppressions` | Fails when suppressions exceed their budget or an added one breaks policy; `--update` lowers the budget |
|
|
32
|
+
| bin | `antelopejs-check-size` | Fails on authored files over 20,000 bytes and on blanket disable directives |
|
|
33
|
+
| bin | `antelopejs-api-diff <base-ref>` | Compares published declaration bundles against committed HEAD |
|
|
34
|
+
| bin | `antelopejs-comment-proof <base-ref>` | Compares comment-free JavaScript emit against committed HEAD |
|
|
35
|
+
| bin | `antelopejs-check-interface-ranges` | Fails on interface ranges that break module startup |
|
|
36
36
|
|
|
37
37
|
## Install
|
|
38
38
|
|
|
@@ -198,9 +198,11 @@ When every rule count is zero and `oversizeFiles` is empty, the ratchet is retir
|
|
|
198
198
|
- `rules` holds lint directives (`oxlint-disable`, `eslint-disable`, their `-line` and `-next-line` forms, in line or block comments, after code too) per rule they name; a directive naming several rules counts once per rule, and one naming none counts under `*`. A rule missing from `rules` has ceiling 0. The other fields count `@ts-expect-error`, `@ts-ignore` and `SAFETY:` comments. The counter is the one behind the proof tables: it reads comments from the parser, so strings and template literals are never counted, and it skips generated output as the size guard does.
|
|
199
199
|
- `antelopejs-suppressions` fails when a count is above its ceiling, printing each `file:line` in the files the change touched and the fix: fix the code, or remove another suppression of the same kind; a rule that keeps needing suppressions should be changed in the preset. It prints nothing on success.
|
|
200
200
|
- `antelopejs-suppressions --update` lowers each ceiling to the current count and keeps rules at zero. No command raises a ceiling.
|
|
201
|
+
- `SAFETY:` comments and directives disabling `anti-slop/require-safety-comment-for-type-assertion` share their room: a `SAFETY:` comment may use what those directives leave below their ceiling, in the full, base and staged checks, and `--update` moves that room to `safety`. Replacing such a directive with a `SAFETY:` comment needs no raise; their sum never rises.
|
|
201
202
|
- `antelopejs-suppressions` also compares the budget with the one on the pull request base: `--base <ref>` when given, else the `GITHUB_BASE_REF` branch in CI (fetched from `origin` into a shallow checkout), else `origin/HEAD`. It fails when a ceiling is higher than on the base or a rule the base lists is removed, so a raise merges only through the operator's ruleset bypass. A base without a budget, a first adoption, passes. Without a base the comparison is skipped.
|
|
202
203
|
- The pre-commit hook runs `antelopejs-suppressions --staged`: it compares the suppressions in the staged files with those files at HEAD, following renames and counting deleted files, and fails a kind that rises by more than the staged budget raises its ceiling. A suppression moved between staged files nets out.
|
|
203
204
|
- `@ts-ignore` is also a lint error (`typescript/ban-ts-comment`); `@ts-expect-error` fails once its error is gone.
|
|
205
|
+
- Both modes also judge what the change adds, whatever the budget allows: the full check against the same base (HEAD when there is none), the staged check against HEAD. A suppression counts as added when its kind, rule and reason occur more often than on the base, so one moved to another file with its reason is not added, and one whose reason a comment pass rewrote or stripped is. An added directive fails when it names a rule no directive may name (`anti-slop/require-safety-comment-for-type-assertion`, `antelopejs/no-comments`, the four `antelopejs` test rules, `typescript/ban-ts-comment`); the failure names what to do instead. An added directive naming its rules, `@ts-expect-error` or `SAFETY:` comment fails when its reason has fewer than three words, or only words like "safe", "intentional", "legacy" and the rule's own name. A block `oxlint-disable` or `eslint-disable` that no `-enable` closes before the end of its file fails when the change adds it. Suppressions already on the base stay under the budget until a burn-down removes them.
|
|
204
206
|
|
|
205
207
|
### Size
|
|
206
208
|
|
|
@@ -210,11 +212,11 @@ Pass paths to check only those files, as the pre-commit hook does. The command a
|
|
|
210
212
|
|
|
211
213
|
### Cleanup proof
|
|
212
214
|
|
|
213
|
-
A behaviour-preserving cleanup PR shows `antelopejs-api-diff <base-ref>` passing. It checks each tracked package with a `tsconfig.json` that publishes something (not private, and declaring `exports`, `main`, `types`, `typings` or `typesVersions`) and lists the others as `API: skipped <directory>, <reason>.`. Each package is analysed and bundled with its own installed TypeScript, falling back to the one `dts-bundle-generator` brings when the package
|
|
215
|
+
A behaviour-preserving cleanup PR shows `antelopejs-api-diff <base-ref>` passing. It checks each tracked package with a `tsconfig.json` that publishes something (not private, and declaring `exports`, `main`, `types`, `typings` or `typesVersions`) and lists the others as `API: skipped <directory>, <reason>.`. Each package is analysed and bundled with its own installed TypeScript, falling back to the one `dts-bundle-generator` brings only when neither the package nor its workspace root declares `typescript` (the proof then prints `<directory>: declares no typescript; using the pack's TypeScript <version>`). A package that declares `typescript` but cannot resolve it fails with an execution error naming the package and asking for an install, because its declaration half would otherwise pass on a broken install; a TypeScript without the programmatic compiler API (7 and later) is reported as an execution error naming the package, and the other packages are still analysed. Large packages are bundled by several worker processes (up to 8, bounded by cpus and free memory); the output is the same as a single process. It emits declarations without comments, resolves published entries from `exports` (preferring `types`), `main`, `types`/`typings` and `typesVersions`, and bundles each entry's local declaration closure. External packages stay external. Stable top-level ordering ignores declaration moves between internal files while preserving overload order. Members of object type literals, interfaces and classes are compared in a canonical order, because TypeScript can emit an inferred object type's properties in another order after a refactor; overloads, call and construct signatures, tuple elements, parameters, enum members and union constituents keep their written order. Compiler errors fail the proof.
|
|
214
216
|
|
|
215
217
|
A comment-only PR shows `antelopejs-comment-proof <base-ref>` passing instead of a verifier. It includes private packages, ignores type diagnostics and compares comment-free JavaScript emit byte for byte. Both commands exclude test sources, fail on added or removed outputs, and print unified diffs for changes.
|
|
216
218
|
|
|
217
|
-
Pass `--allow-added <glob>` (repeatable) to `antelopejs-api-diff` when a refactor adds helper files that a wildcard export publishes, such as an `internal/` directory under `"./*"`. An added entry passes, in both the declaration and the runtime half, when its published subpath matches a glob (for example `--allow-added '**/internal/**'`, matched against `base/table-view/internal/helper` for `./base/table-view/internal/helper`) and its source module is marked `@internal`: a leading `/** @internal @packageDocumentation */` comment on the module (`@module` and `@fileoverview` also qualify), or an `@internal` tag on every exported declaration. Allowed entries are printed under `Added (allowed): <count
|
|
219
|
+
Pass `--allow-added <glob>` (repeatable) to `antelopejs-api-diff` when a refactor adds helper files that a wildcard export publishes, such as an `internal/` directory under `"./*"`. An added entry passes, in both the declaration and the runtime half, when its published subpath matches a glob (for example `--allow-added '**/internal/**'`, matched against `base/table-view/internal/helper` for `./base/table-view/internal/helper`) and its source module is marked `@internal`: a leading `/** @internal @packageDocumentation */` comment on the module (`@module` and `@fileoverview` also qualify), or an `@internal` tag on every exported declaration. Allowed entries are printed under `Added (allowed): <count>`; nothing is printed when no entry was added. An added entry that matches but is not marked `@internal` fails with the file and the fix. Added entries matching no glob, removed entries and changed entries still fail, matching or not. Without the flag nothing changes.
|
|
218
220
|
|
|
219
221
|
```bash
|
|
220
222
|
pnpm exec antelopejs-api-diff origin/main --allow-added '**/internal/**'
|
package/dist/bin/api-diff.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { l as runCli, o as repositoryRoot } from "../files-BMxKg5IR.mjs";
|
|
3
3
|
import { i as parseManifest, r as packageManager } from "../package-Dtjt_lSa.mjs";
|
|
4
|
-
import { a as unpublishedAt, c as revisionCounts, d as describeAllowance, f as fillStars, i as packagesAt, l as allowedByGlob, n as isTestSource, o as DIRECTORY_LINK, p as recordVerdict, r as outputRoot, s as compareRevisions, t as emitPackage, u as createAddedPolicy } from "../typescript-
|
|
4
|
+
import { a as unpublishedAt, c as revisionCounts, d as describeAllowance, f as fillStars, i as packagesAt, l as allowedByGlob, n as isTestSource, o as DIRECTORY_LINK, p as recordVerdict, r as outputRoot, s as compareRevisions, t as emitPackage, u as createAddedPolicy } from "../typescript-YufoJnck.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
@@ -11,7 +11,10 @@ import { availableParallelism, freemem } from "node:os";
|
|
|
11
11
|
//#region src/guardrails/declaration-bundle.ts
|
|
12
12
|
const ENTRIES_PER_WORKER = 16;
|
|
13
13
|
const MAX_WORKERS = 8;
|
|
14
|
-
const
|
|
14
|
+
const MIB = 1024 ** 2;
|
|
15
|
+
const WORKER_MEMORY = 1536 * MIB;
|
|
16
|
+
/** Node options that keep a worker inside `WORKER_MEMORY`: the old-space cap leaves room for the memory V8 holds outside the heap, so a worker's resident size stays under the budget that `workerCount` assumes. */
|
|
17
|
+
const WORKER_NODE_ARGS = [`--max-old-space-size=${(WORKER_MEMORY - 256 * MIB) / MIB}`];
|
|
15
18
|
const WORKER = `
|
|
16
19
|
const { readFileSync, writeFileSync } = require("node:fs");
|
|
17
20
|
const { createRequire } = require("node:module");
|
|
@@ -26,11 +29,11 @@ try {
|
|
|
26
29
|
`;
|
|
27
30
|
const DRIVER = `
|
|
28
31
|
const { spawn } = require("node:child_process");
|
|
29
|
-
const [worker, ...jobs] = process.argv.slice(1);
|
|
32
|
+
const [flags, worker, ...jobs] = process.argv.slice(1);
|
|
30
33
|
let failed = false;
|
|
31
34
|
let pending = jobs.length;
|
|
32
35
|
for (const job of jobs) {
|
|
33
|
-
spawn(process.execPath, [worker, job], { stdio: ["ignore", "inherit", "inherit"] }).on("exit", (code) => {
|
|
36
|
+
spawn(process.execPath, [...JSON.parse(flags), worker, job], { stdio: ["ignore", "inherit", "inherit"] }).on("exit", (code) => {
|
|
34
37
|
failed ||= code !== 0;
|
|
35
38
|
pending -= 1;
|
|
36
39
|
if (pending === 0) process.exit(failed ? 1 : 0);
|
|
@@ -70,6 +73,7 @@ function generateInWorkers(loader, directory, entries, options, workers) {
|
|
|
70
73
|
const run = spawnSync(process.execPath, [
|
|
71
74
|
"-e",
|
|
72
75
|
DRIVER,
|
|
76
|
+
JSON.stringify(WORKER_NODE_ARGS),
|
|
73
77
|
worker,
|
|
74
78
|
...jobs.map(({ file }) => file)
|
|
75
79
|
], {
|
|
@@ -463,9 +467,10 @@ function generatorEntry(file) {
|
|
|
463
467
|
if (alias !== file) copyFileSync(file, alias);
|
|
464
468
|
return alias;
|
|
465
469
|
}
|
|
466
|
-
function bundlePackage(paths, manifest, policy) {
|
|
470
|
+
function bundlePackage(paths, manifest, policy, notices) {
|
|
467
471
|
const { directory, output, scratch } = paths;
|
|
468
472
|
const emitted = emitPackage(directory, scratch, true);
|
|
473
|
+
if (emitted.notice !== void 0) notices?.add(emitted.notice);
|
|
469
474
|
const entries = publishedEntries(directory, manifest, emitted, scratch);
|
|
470
475
|
if (!entries.length) return {
|
|
471
476
|
count: 0,
|
|
@@ -520,6 +525,7 @@ function bundlePackage(paths, manifest, policy) {
|
|
|
520
525
|
}
|
|
521
526
|
function declarationDiff(root, baseRef, policy) {
|
|
522
527
|
const errors = /* @__PURE__ */ new Set();
|
|
528
|
+
const notices = /* @__PURE__ */ new Set();
|
|
523
529
|
const failedPackages = /* @__PURE__ */ new Set();
|
|
524
530
|
const unpublished = /* @__PURE__ */ new Map();
|
|
525
531
|
const result = compareRevisions(root, baseRef, "API", (worktree, output, scratch) => {
|
|
@@ -536,7 +542,7 @@ function declarationDiff(root, baseRef, policy) {
|
|
|
536
542
|
directory: join(worktree, directory),
|
|
537
543
|
output: join(output, key),
|
|
538
544
|
scratch: join(scratch, key)
|
|
539
|
-
}, manifest, policy);
|
|
545
|
+
}, manifest, policy, notices);
|
|
540
546
|
entries += bundled.count;
|
|
541
547
|
published.push(...bundled.published);
|
|
542
548
|
} catch (error) {
|
|
@@ -556,7 +562,7 @@ function declarationDiff(root, baseRef, policy) {
|
|
|
556
562
|
}, policy);
|
|
557
563
|
return {
|
|
558
564
|
different: result.different || errors.size > 0,
|
|
559
|
-
output: (errors.size > 0 && !result.different ? result.output.replace(/^API:[^\n]*\n/u, "API: comparison incomplete due to execution errors.\n") : result.output) + [...unpublished].sort(([a], [b]) => a.localeCompare(b)).map(([directory, reason]) => `API: skipped ${directory}, ${reason}.\n`).join("") + [...errors].join("")
|
|
565
|
+
output: (errors.size > 0 && !result.different ? result.output.replace(/^API:[^\n]*\n/u, "API: comparison incomplete due to execution errors.\n") : result.output) + [...unpublished].sort(([a], [b]) => a.localeCompare(b)).map(([directory, reason]) => `API: skipped ${directory}, ${reason}.\n`).join("") + [...notices].sort().join("") + [...errors].join("")
|
|
560
566
|
};
|
|
561
567
|
}
|
|
562
568
|
/** Compares declarations and built runtime exports, with an optional behavioral probe captured before either build. Added entries whose subpath matches an `allowAdded` glob pass when their module is `@internal`. */
|
package/dist/bin/check-size.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { a as repositoryPath, l as runCli, o as repositoryRoot, t as authoredSizes } from "../files-BMxKg5IR.mjs";
|
|
3
3
|
import { t as checkSize } from "../size-Fp3aWSkN.mjs";
|
|
4
|
-
import {
|
|
4
|
+
import { a as revisionSuppressions, o as worktreeSuppressions } from "../suppressions-C3AE6_I-.mjs";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
7
|
//#region src/guardrails/directives.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { l as runCli, o as repositoryRoot } from "../files-BMxKg5IR.mjs";
|
|
3
|
-
import { c as revisionCounts, i as packagesAt, s as compareRevisions, t as emitPackage } from "../typescript-
|
|
3
|
+
import { c as revisionCounts, i as packagesAt, s as compareRevisions, t as emitPackage } from "../typescript-YufoJnck.mjs";
|
|
4
4
|
import { copyFileSync, mkdirSync } from "node:fs";
|
|
5
5
|
import { dirname, join, relative } from "node:path";
|
|
6
6
|
//#region src/guardrails/comment-proof.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { l as runCli, o as repositoryRoot, s as resolveRevision } from "../files-BMxKg5IR.mjs";
|
|
3
|
-
import { a as
|
|
3
|
+
import { a as parseBudget, c as checkPolicy, i as checkSuppressions, n as SUPPRESSIONS_FILE, o as safetyCeiling, s as stagedSuppressions } from "../suppression-budget-Cu0wOmFO.mjs";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
@@ -53,7 +53,8 @@ function suppressionBase(root, base) {
|
|
|
53
53
|
/**
|
|
54
54
|
* Fails each ceiling of the working-tree budget that is higher than on
|
|
55
55
|
* `revision`, and each rule that `revision` lists but the working tree
|
|
56
|
-
* dropped.
|
|
56
|
+
* dropped. The safety ceiling may rise by what the SAFETY rule's own
|
|
57
|
+
* ceiling falls. A base without a budget, a first adoption, passes.
|
|
57
58
|
*/
|
|
58
59
|
function raisedCeilings(root, revision) {
|
|
59
60
|
const committed = spawnSync("git", ["show", `${revision}:${SUPPRESSIONS_FILE}`], {
|
|
@@ -72,7 +73,7 @@ function raisedCeilings(root, revision) {
|
|
|
72
73
|
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);
|
|
73
74
|
compare("`@ts-expect-error`", base.tsExpectError, current.tsExpectError);
|
|
74
75
|
compare("`@ts-ignore`", base.tsIgnore, current.tsIgnore);
|
|
75
|
-
compare("`SAFETY:` comments", base.safety, current.safety);
|
|
76
|
+
compare("`SAFETY:` comments", safetyCeiling(base, current.rules["anti-slop/require-safety-comment-for-type-assertion"] ?? 0), current.safety);
|
|
76
77
|
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."] : [];
|
|
77
78
|
}
|
|
78
79
|
//#endregion
|
|
@@ -80,7 +81,11 @@ function raisedCeilings(root, revision) {
|
|
|
80
81
|
function fullCheck(root, update, base) {
|
|
81
82
|
const failures = checkSuppressions(root, update);
|
|
82
83
|
const revision = suppressionBase(root, base);
|
|
83
|
-
return revision === void 0 ? failures
|
|
84
|
+
return revision === void 0 ? [...failures, ...checkPolicy(root)] : [
|
|
85
|
+
...raisedCeilings(root, revision),
|
|
86
|
+
...failures,
|
|
87
|
+
...checkPolicy(root, revision)
|
|
88
|
+
];
|
|
84
89
|
}
|
|
85
90
|
runCli(() => {
|
|
86
91
|
const { values } = parseArgs({
|
package/dist/bin/sync.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { a as formatCeilings, o as isRetired, s as readCeilings, t as CEILINGS_F
|
|
|
3
3
|
import { l as runCli, o as repositoryRoot } from "../files-BMxKg5IR.mjs";
|
|
4
4
|
import { a as repositoryTools, i as parseManifest, n as managedPackage, o as toolingVersions, r as packageManager, t as execCommand } from "../package-Dtjt_lSa.mjs";
|
|
5
5
|
import { t as measureBaseline } from "../ratchet-zzo2tT74.mjs";
|
|
6
|
-
import { n as
|
|
6
|
+
import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Cu0wOmFO.mjs";
|
|
7
7
|
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { dirname, join, resolve } from "node:path";
|
|
9
9
|
import { execFileSync } from "node:child_process";
|
|
@@ -34,10 +34,14 @@ Copy counts from the proof's base and HEAD table. Never type counts by hand. Kee
|
|
|
34
34
|
|
|
35
35
|
Pass \`--probe <file.cjs>\` to api-diff when changing receivers, positional calls, or modules that no published entry reaches. The same captured script runs against both worktree roots, supplied as \`argv[2]\`, and prints JSON observations. Matching metadata alone does not prove those behaviours.
|
|
36
36
|
|
|
37
|
-
An entry-only rule exempts only its own module. Add a second module entry rather than exempting another importer. A no-upward rule must reject peers in the same tier as well as higher tiers. Probe the rank decision with an import, not just a reading of the configuration
|
|
37
|
+
An entry-only rule exempts only its own module. Add a second module entry rather than exempting another importer. A no-upward rule must reject peers in the same tier as well as higher tiers. Probe the rank decision with an import, not just a reading of the configuration.
|
|
38
|
+
|
|
39
|
+
Moving a method body into a function keeps how it is called: the same receiver, argument count, read order and laziness.
|
|
40
|
+
|
|
41
|
+
Verify a boundary against the imports a developer or agent would plausibly write: static and dynamic imports, re-exports, Vue \`src\`, CSS \`@import\`, and worker or child-process entries in normally named files. A construction only an evasion would write, an edit to resolution configuration (\`package.json\` \`browser\`, \`exports\`, \`main\` or \`imports\`, bundler aliases, tsconfig \`paths\`), and a difference observable only by patching private fields or internal methods go under Attention and never block. Public API and ordinary subclass behaviour stay part of the contract.`;
|
|
38
42
|
const SUPPRESSION_BUDGET = `### Suppression budget
|
|
39
43
|
|
|
40
|
-
\`guardrails.suppressions.json\` caps the suppressions in authored code: lint directives per rule they name (\`*\` for none), \`@ts-expect-error\`, \`@ts-ignore\` and \`SAFETY:\` comments. A suppression over its ceiling fails: fix the code, or remove another suppression of the same kind. A rule that keeps needing suppressions should be changed in the preset. Never raise or remove a number in that file: the check fails a ceiling higher than on the pull request base, and only the operator approves a raise. After you remove suppressions, run \`pnpm run suppressions:update\` and commit the lowered file.`;
|
|
44
|
+
\`guardrails.suppressions.json\` caps the suppressions in authored code: lint directives per rule they name (\`*\` for none), \`@ts-expect-error\`, \`@ts-ignore\` and \`SAFETY:\` comments. A suppression over its ceiling fails: fix the code, or remove another suppression of the same kind. A rule that keeps needing suppressions should be changed in the preset. Never raise or remove a number in that file: the check fails a ceiling higher than on the pull request base, and only the operator approves a raise. A directive disabling \`anti-slop/require-safety-comment-for-type-assertion\` is burn-down debt: remove the assertion, or, where it holds, replace the directive with \`SAFETY: <why it holds>\`, which takes over its room without a raise. After you remove suppressions, run \`pnpm run suppressions:update\` and commit the lowered file.`;
|
|
41
45
|
const SHARED_RULES = [
|
|
42
46
|
["Formatting", "oxfmt"],
|
|
43
47
|
["Lint findings are errors; no rule warns", "oxlint preset"],
|
|
@@ -51,13 +55,17 @@ const SHARED_RULES = [
|
|
|
51
55
|
["Comment-only changes preserve JavaScript emit", "`antelopejs-comment-proof <base-ref>`"],
|
|
52
56
|
["PR-body counts come from tracked code files", "api-diff and comment-proof tables"],
|
|
53
57
|
["Receiver, positional and unpublished-module behaviour", "`antelopejs-api-diff <base-ref> --probe <file.cjs>`"],
|
|
54
|
-
["
|
|
58
|
+
["Directive and `SAFETY:` reasons are true of the code", "review; no tool"],
|
|
59
|
+
["Evasion-only and patched-internal findings go under Attention", "review; no tool"],
|
|
55
60
|
["No-upward rules reject same-tier peers", "review and import probes"],
|
|
56
61
|
["No `@ts-ignore`", "`typescript/ban-ts-comment`"]
|
|
57
62
|
];
|
|
58
63
|
const FULL_RULES = [
|
|
59
64
|
["Files ≤ 20,000 bytes, tests included", "`antelopejs-check-size` (pre-commit)"],
|
|
60
65
|
["Suppressions stay within `guardrails.suppressions.json`", "`antelopejs-suppressions` (pre-commit, checks)"],
|
|
66
|
+
["No added directive disables the `SAFETY:`, comment or test rules", "`antelopejs-suppressions` (pre-commit, checks)"],
|
|
67
|
+
["An added suppression gives a specific reason", "`antelopejs-suppressions` (pre-commit, checks)"],
|
|
68
|
+
["A block disable is closed in its file", "`antelopejs-suppressions` (pre-commit, checks)"],
|
|
61
69
|
["Types check", "`tsc` (pre-push)"],
|
|
62
70
|
["No dead files, exports, or dependencies", "knip"],
|
|
63
71
|
["Managed files match the pack", "`antelopejs-sync --check`"],
|
|
@@ -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 };
|
|
@@ -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
1
|
import { c as trackedManifests, s as resolveRevision } from "./files-BMxKg5IR.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { i as parseManifest } from "./package-Dtjt_lSa.mjs";
|
|
3
|
+
import { a as revisionSuppressions, n as countSuppressions } from "./suppressions-C3AE6_I-.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.8",
|
|
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",
|
|
@@ -1,144 +0,0 @@
|
|
|
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 { n as revisionSuppressions, r as worktreeSuppressions, t as countSuppressions } from "./suppressions-CgGa-kh7.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-budget.ts
|
|
9
|
-
/** The per-repository suppression budget, at the repository root. It is permanent: nothing deletes it, even at zero. */
|
|
10
|
-
const SUPPRESSIONS_FILE = "guardrails.suppressions.json";
|
|
11
|
-
/** What a failure tells the author to do. */
|
|
12
|
-
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.";
|
|
13
|
-
const LABELS = {
|
|
14
|
-
tsExpectError: "`@ts-expect-error`",
|
|
15
|
-
tsIgnore: "`@ts-ignore`",
|
|
16
|
-
safety: "`SAFETY:` comments"
|
|
17
|
-
};
|
|
18
|
-
function labelOf(suppression) {
|
|
19
|
-
return suppression.kind === "rule" ? `lint rule \`${suppression.rule}\`` : LABELS[suppression.kind];
|
|
20
|
-
}
|
|
21
|
-
function limitOf(budget, suppression) {
|
|
22
|
-
return suppression.kind === "rule" ? budget.rules[suppression.rule] ?? 0 : budget[suppression.kind];
|
|
23
|
-
}
|
|
24
|
-
function count(value, source) {
|
|
25
|
-
if (value === void 0) throw new Error(`${source} is missing`);
|
|
26
|
-
if (!Number.isInteger(value) || value < 0) throw new Error(`${source} must be a non-negative integer`);
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
29
|
-
/** Parses a budget, rejecting a missing field and anything but non-negative integer ceilings. */
|
|
30
|
-
function parseBudget(text, source) {
|
|
31
|
-
const parsed = JSON.parse(text);
|
|
32
|
-
if (parsed === null || Array.isArray(parsed)) throw new Error(`${source}: expected an object with "rules"`);
|
|
33
|
-
const rules = parsed.rules ?? {};
|
|
34
|
-
if (rules === null || Array.isArray(rules)) throw new Error(`${source}: rules must be an object of counts`);
|
|
35
|
-
return {
|
|
36
|
-
rules: Object.fromEntries(Object.entries(rules).map(([rule, limit]) => [rule, count(limit, `${source}: rules "${rule}"`)])),
|
|
37
|
-
tsExpectError: count(parsed.tsExpectError, `${source}: tsExpectError`),
|
|
38
|
-
tsIgnore: count(parsed.tsIgnore, `${source}: tsIgnore`),
|
|
39
|
-
safety: count(parsed.safety, `${source}: safety`)
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
/** Serializes a budget with sorted rules, zero ceilings kept, so rewriting an unchanged budget is a no-op. */
|
|
43
|
-
function formatBudget(budget) {
|
|
44
|
-
const rules = Object.fromEntries(Object.entries(budget.rules).sort(([a], [b]) => a.localeCompare(b)));
|
|
45
|
-
return `${JSON.stringify({
|
|
46
|
-
...budget,
|
|
47
|
-
rules
|
|
48
|
-
}, null, 2)}\n`;
|
|
49
|
-
}
|
|
50
|
-
/** 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. */
|
|
51
|
-
function adoptedBudget(root) {
|
|
52
|
-
const committed = spawnSync("git", ["show", `HEAD:${SUPPRESSIONS_FILE}`], {
|
|
53
|
-
cwd: root,
|
|
54
|
-
encoding: "utf8"
|
|
55
|
-
});
|
|
56
|
-
if (committed.status === 0) return committed.stdout;
|
|
57
|
-
return formatBudget(countSuppressions(worktreeSuppressions(root)));
|
|
58
|
-
}
|
|
59
|
-
function groupByKey(suppressions) {
|
|
60
|
-
const groups = /* @__PURE__ */ new Map();
|
|
61
|
-
for (const suppression of suppressions) {
|
|
62
|
-
const key = labelOf(suppression);
|
|
63
|
-
groups.set(key, [...groups.get(key) ?? [], suppression]);
|
|
64
|
-
}
|
|
65
|
-
return groups;
|
|
66
|
-
}
|
|
67
|
-
function lowered(budget, current) {
|
|
68
|
-
return {
|
|
69
|
-
rules: Object.fromEntries(Object.entries(budget.rules).map(([rule, limit]) => [rule, Math.min(limit, current.rules[rule] ?? 0)])),
|
|
70
|
-
tsExpectError: Math.min(budget.tsExpectError, current.tsExpectError),
|
|
71
|
-
tsIgnore: Math.min(budget.tsIgnore, current.tsIgnore),
|
|
72
|
-
safety: Math.min(budget.safety, current.safety)
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Fails each budget key whose count in the working tree is above its ceiling,
|
|
77
|
-
* listing the suppressions in the files this change touches (all of them when
|
|
78
|
-
* it touches none). `update` lowers every ceiling to its current count; no
|
|
79
|
-
* command ever raises one.
|
|
80
|
-
*/
|
|
81
|
-
function checkSuppressions(root, update = false) {
|
|
82
|
-
const path = join(root, SUPPRESSIONS_FILE);
|
|
83
|
-
if (!existsSync(path)) throw new Error(`${SUPPRESSIONS_FILE} is missing. Run antelopejs-sync.`);
|
|
84
|
-
const budget = parseBudget(readFileSync(path, "utf8"), SUPPRESSIONS_FILE);
|
|
85
|
-
const suppressions = worktreeSuppressions(root);
|
|
86
|
-
const changed = changedFiles(root);
|
|
87
|
-
const failures = [];
|
|
88
|
-
for (const [key, found] of groupByKey(suppressions)) {
|
|
89
|
-
const limit = limitOf(budget, found[0]);
|
|
90
|
-
if (found.length <= limit) continue;
|
|
91
|
-
const inChanged = found.filter(({ file }) => changed.has(file));
|
|
92
|
-
const shown = inChanged.length ? inChanged : found;
|
|
93
|
-
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.`] : []);
|
|
94
|
-
}
|
|
95
|
-
if (update) writeFileSync(path, formatBudget(lowered(budget, countSuppressions(suppressions))));
|
|
96
|
-
return failures.length ? [...failures, SUPPRESSION_FIX] : [];
|
|
97
|
-
}
|
|
98
|
-
function budgetAt(root, revision) {
|
|
99
|
-
const result = spawnSync("git", ["show", `${revision}:${SUPPRESSIONS_FILE}`], {
|
|
100
|
-
cwd: root,
|
|
101
|
-
encoding: "utf8"
|
|
102
|
-
});
|
|
103
|
-
return result.status === 0 ? parseBudget(result.stdout, `${revision || "index"}:${SUPPRESSIONS_FILE}`) : void 0;
|
|
104
|
-
}
|
|
105
|
-
function stagedNames(root, filter) {
|
|
106
|
-
return execFileSync("git", [
|
|
107
|
-
"diff",
|
|
108
|
-
"--cached",
|
|
109
|
-
"--name-only",
|
|
110
|
-
"--find-renames",
|
|
111
|
-
`--diff-filter=${filter}`,
|
|
112
|
-
"-z"
|
|
113
|
-
], {
|
|
114
|
-
cwd: root,
|
|
115
|
-
encoding: "utf8"
|
|
116
|
-
}).split("\0").filter(Boolean);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Compares the staged files' suppressions with those files at HEAD, rename
|
|
120
|
-
* sources and deleted files included, and fails each key that rises by more
|
|
121
|
-
* than the staged budget raises its ceiling. A commit that first adds the
|
|
122
|
-
* budget is not compared.
|
|
123
|
-
*/
|
|
124
|
-
function stagedSuppressions(root) {
|
|
125
|
-
const head = budgetAt(root, "HEAD");
|
|
126
|
-
if (head === void 0) return [];
|
|
127
|
-
const index = budgetAt(root, "") ?? head;
|
|
128
|
-
const renames = renamedPaths(root, true);
|
|
129
|
-
const staged = stagedNames(root, "ACMR");
|
|
130
|
-
const previous = [...staged.map((file) => renames.get(file) ?? file), ...stagedNames(root, "D")];
|
|
131
|
-
const before = groupByKey(revisionSuppressions(root, "HEAD", previous));
|
|
132
|
-
const after = groupByKey(revisionSuppressions(root, "", staged));
|
|
133
|
-
const additions = stagedAdditions(root, [...new Set([...after.values()].flat().map(({ file }) => file))]);
|
|
134
|
-
const failures = [];
|
|
135
|
-
for (const [key, found] of after) {
|
|
136
|
-
const rise = found.length - (before.get(key)?.length ?? 0);
|
|
137
|
-
if (rise <= Math.max(0, limitOf(index, found[0]) - limitOf(head, found[0]))) continue;
|
|
138
|
-
const added = found.filter(({ file, line }) => additions.get(file)?.some(({ start, end }) => line >= start && line <= end));
|
|
139
|
-
failures.push(`${key}: this commit adds ${rise} to the staged files.`, ...(added.length ? added : found).map(({ file, line }) => ` ${file}:${line}`));
|
|
140
|
-
}
|
|
141
|
-
return failures.length ? [...failures, SUPPRESSION_FIX] : [];
|
|
142
|
-
}
|
|
143
|
-
//#endregion
|
|
144
|
-
export { stagedSuppressions as a, parseBudget as i, adoptedBudget as n, checkSuppressions as r, SUPPRESSIONS_FILE as t };
|