@antelopejs/tooling-configs 0.2.16 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +88 -48
  2. package/dist/bin/api-diff.mjs +409 -97
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/check-size.mjs +3 -3
  6. package/dist/bin/checks.mjs +3 -3
  7. package/dist/bin/comment-proof.mjs +4 -3
  8. package/dist/bin/garden.mjs +5 -5
  9. package/dist/bin/ratchet.mjs +267 -7
  10. package/dist/bin/suppressions.mjs +118 -80
  11. package/dist/bin/sync.mjs +490 -35
  12. package/dist/bin/verify.mjs +5 -5
  13. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  14. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  15. package/dist/{ci-workflow-DIsoEgMd.mjs → ci-workflow-ChW4He0r.mjs} +84 -3
  16. package/dist/{files-2FikHZ9F.mjs → files-Bc036sJW.mjs} +2 -2
  17. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  18. package/dist/oxc/anti-slop/index.mjs +160 -13
  19. package/dist/oxc/fmt.mjs +1 -1
  20. package/dist/oxc/guardrails/index.d.mts +1 -1
  21. package/dist/oxc/guardrails/index.mjs +645 -1
  22. package/dist/oxc/lint.d.mts +11 -3
  23. package/dist/oxc/lint.mjs +21 -8
  24. package/dist/oxlint-Bltmk8-6.mjs +94 -0
  25. package/dist/{package-Dtjt_lSa.mjs → package-DTxLPNDu.mjs} +3 -2
  26. package/dist/proof-stamp-w-3j47A-.mjs +279 -0
  27. package/dist/ratchet-DwRj9h4L.mjs +275 -0
  28. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  29. package/dist/shared-CoUt4GUm.mjs +73 -0
  30. package/dist/{size-BVgNbLO6.mjs → size-DNtWruCO.mjs} +3 -3
  31. package/dist/suppression-base-DAfCXwjL.mjs +95 -0
  32. package/dist/{suppression-budget-Yyf5_J5l.mjs → suppression-budget-Bd2GqMYb.mjs} +248 -33
  33. package/dist/{suppressions-BJAngUxo.mjs → suppressions-BD_f8f7L.mjs} +180 -18
  34. package/dist/typescript-BmS5BmrS.mjs +222 -0
  35. package/dist/verify/index.mjs +1 -1
  36. package/package.json +4 -2
  37. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  38. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  39. package/dist/shared-CsXIMK3I.mjs +0 -34
  40. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  41. package/dist/typescript-C54ONh9m.mjs +0 -433
@@ -0,0 +1,222 @@
1
+ import { c as trackedManifests } from "./files-Bc036sJW.mjs";
2
+ import { i as parseManifest } from "./package-DTxLPNDu.mjs";
3
+ import { createRequire } from "node:module";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
6
+ //#region src/guardrails/declared-typescript.ts
7
+ const DEPENDENCY_FIELDS = [
8
+ "dependencies",
9
+ "devDependencies",
10
+ "peerDependencies",
11
+ "optionalDependencies"
12
+ ];
13
+ function readManifest(directory) {
14
+ const file = join(directory, "package.json");
15
+ return existsSync(file) ? parseManifest(readFileSync(file, "utf8")) : void 0;
16
+ }
17
+ function declares(manifest) {
18
+ return DEPENDENCY_FIELDS.some((field) => manifest?.[field]?.typescript !== void 0);
19
+ }
20
+ /** The nearest manifest at or above `directory` that configures a workspace, never leaving the repository that contains it. */
21
+ function workspaceManifest(directory) {
22
+ for (let current = directory;; current = dirname(current)) {
23
+ const manifest = readManifest(current);
24
+ if (manifest !== void 0 && (manifest.workspaces !== void 0 || existsSync(join(current, "pnpm-workspace.yaml")))) return manifest;
25
+ if (existsSync(join(current, ".git")) || dirname(current) === current) return void 0;
26
+ }
27
+ }
28
+ /** Whether the package at `directory`, or the workspace root above it, declares `typescript` as a dependency of any kind. */
29
+ function declaresTypeScript(directory) {
30
+ return declares(readManifest(directory)) || declares(workspaceManifest(directory));
31
+ }
32
+ /** The directory of the package relative to the repository that contains it, `.` for the repository root; the same for every revision of the repository. */
33
+ function repositoryDirectory(directory) {
34
+ for (let current = directory;; current = dirname(current)) if (existsSync(join(current, ".git")) || dirname(current) === current) return relative(current, directory).split("\\").join("/") || ".";
35
+ }
36
+ /** The package as an error names it: its `name` when it has one, and its directory. */
37
+ function describePackage(directory) {
38
+ const name = readManifest(directory)?.name;
39
+ const where = repositoryDirectory(directory);
40
+ return name === void 0 ? where : `${name} (${where})`;
41
+ }
42
+ //#endregion
43
+ //#region src/guardrails/typescript.ts
44
+ /** A package `exports` leaf: a path rather than a fallback list or a condition map. */
45
+ function isExportPath(target) {
46
+ return typeof target === "string";
47
+ }
48
+ /** A proof analyses only packages that publish something: not private, and declaring at least one of `exports`, `main`, `types`, `typings` or `typesVersions`. */
49
+ function unpublishedReason(manifest) {
50
+ if (manifest.private === true) return "private";
51
+ return [
52
+ manifest.exports,
53
+ manifest.main,
54
+ manifest.types,
55
+ manifest.typings,
56
+ manifest.typesVersions
57
+ ].some((field) => field != null) ? void 0 : "no exports, main or types";
58
+ }
59
+ function trackedPackages(root) {
60
+ return trackedManifests(root).flatMap((file) => {
61
+ const directory = dirname(file);
62
+ if (!existsSync(join(root, directory, "tsconfig.json"))) return [];
63
+ return [{
64
+ directory,
65
+ manifest: JSON.parse(readFileSync(join(root, file), "utf8"))
66
+ }];
67
+ });
68
+ }
69
+ function packagesAt(root, publishedOnly) {
70
+ return trackedPackages(root).filter(({ manifest }) => !publishedOnly || unpublishedReason(manifest) === void 0);
71
+ }
72
+ /** The packages a published-only proof leaves out, each with the reason, so a skip is reported rather than silent. */
73
+ function unpublishedAt(root) {
74
+ return trackedPackages(root).flatMap(({ directory, manifest }) => {
75
+ const reason = unpublishedReason(manifest);
76
+ return reason === void 0 ? [] : [{
77
+ directory,
78
+ reason
79
+ }];
80
+ });
81
+ }
82
+ function packageRoot(file) {
83
+ let directory = dirname(file);
84
+ while (!existsSync(join(directory, "package.json"))) {
85
+ const parent = dirname(directory);
86
+ if (parent === directory) return dirname(file);
87
+ directory = parent;
88
+ }
89
+ return directory;
90
+ }
91
+ function resolveTypeScript(directory) {
92
+ try {
93
+ return {
94
+ file: createRequire(join(directory, "package.json")).resolve("typescript"),
95
+ fallback: false
96
+ };
97
+ } catch (error) {
98
+ 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 });
99
+ return {
100
+ file: createRequire(createRequire(import.meta.url).resolve("dts-bundle-generator")).resolve("typescript"),
101
+ fallback: true
102
+ };
103
+ }
104
+ }
105
+ /** 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. */
106
+ function loadTypeScript(directory) {
107
+ const { file, fallback } = resolveTypeScript(directory);
108
+ const compiler = createRequire(file)("typescript");
109
+ const root = packageRoot(file);
110
+ 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.`);
111
+ return {
112
+ compiler,
113
+ root,
114
+ notice: fallback ? `${repositoryDirectory(directory)}: declares no typescript; using the pack's TypeScript ${compiler.version}\n` : void 0
115
+ };
116
+ }
117
+ const TEST_SOURCE_GLOBS = [
118
+ "**/*.test.*",
119
+ "**/*.spec.*",
120
+ "**/__tests__/**",
121
+ "test/**",
122
+ "tests/**"
123
+ ];
124
+ function isTestSource(root, file) {
125
+ const path = relative(root, file).split("\\").join("/");
126
+ return TEST_SOURCE_GLOBS.some((pattern) => matchesGlob(path, pattern));
127
+ }
128
+ function failDiagnostics(compiler, diagnostics) {
129
+ const errors = diagnostics.filter((item) => item.category === compiler.DiagnosticCategory.Error);
130
+ if (errors.length) throw new Error(compiler.formatDiagnostics(errors, {
131
+ getCanonicalFileName: (file) => file,
132
+ getCurrentDirectory: () => process.cwd(),
133
+ getNewLine: () => "\n"
134
+ }));
135
+ }
136
+ /** Declaration inputs are part of the local closure but TypeScript does not emit copies of them. */
137
+ function copyDeclarations(program, directory, output) {
138
+ const sources = program.getSourceFiles().filter((source) => !program.isSourceFileDefaultLibrary(source) && !program.isSourceFileFromExternalLibrary(source) && !relative(directory, source.fileName).startsWith(`..${sep}`) && !isTestSource(directory, source.fileName));
139
+ const authored = sources.filter((source) => !source.isDeclarationFile);
140
+ let root = dirname((authored[0] ?? sources[0])?.fileName ?? join(directory, "index.ts"));
141
+ for (const source of authored.length ? authored : sources) while (relative(root, source.fileName).startsWith(`..${sep}`)) root = dirname(root);
142
+ root = program.getCompilerOptions().rootDir ?? root;
143
+ const files = [];
144
+ for (const source of sources) {
145
+ if (!source.isDeclarationFile) continue;
146
+ const path = relative(root, source.fileName);
147
+ if (path.startsWith(`..${sep}`)) continue;
148
+ const target = join(output, path);
149
+ mkdirSync(dirname(target), { recursive: true });
150
+ writeFileSync(target, source.text);
151
+ files.push(target);
152
+ }
153
+ return files;
154
+ }
155
+ function parseConfig(directory) {
156
+ const { compiler, root, notice } = loadTypeScript(directory);
157
+ const config = compiler.readConfigFile(join(directory, "tsconfig.json"), compiler.sys.readFile);
158
+ if (config.error) failDiagnostics(compiler, [config.error]);
159
+ const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, directory);
160
+ failDiagnostics(compiler, parsed.errors);
161
+ return {
162
+ compiler,
163
+ root,
164
+ notice,
165
+ parsed
166
+ };
167
+ }
168
+ /** The configured `outDir`, the root under which the declaration half already judges a built path as test output. */
169
+ function outputRoot(directory) {
170
+ return resolve(directory, parseConfig(directory).parsed.options.outDir ?? ".");
171
+ }
172
+ /** 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. */
173
+ function emitPackage(directory, output, declarations) {
174
+ const { compiler, root, notice, parsed } = parseConfig(directory);
175
+ const options = {
176
+ ...parsed.options,
177
+ rootDir: parsed.options.rootDir ?? (parsed.options.outDir ? void 0 : directory),
178
+ outDir: output,
179
+ declarationDir: declarations ? output : void 0,
180
+ declaration: declarations,
181
+ emitDeclarationOnly: declarations,
182
+ removeComments: true,
183
+ declarationMap: false,
184
+ sourceMap: false,
185
+ inlineSourceMap: false,
186
+ noEmit: false,
187
+ noEmitOnError: false,
188
+ composite: false,
189
+ incremental: false,
190
+ tsBuildInfoFile: void 0,
191
+ outFile: void 0,
192
+ allowImportingTsExtensions: declarations ? parsed.options.allowImportingTsExtensions : false
193
+ };
194
+ const program = compiler.createProgram({
195
+ rootNames: parsed.fileNames.filter((file) => !isTestSource(directory, file)),
196
+ options,
197
+ projectReferences: parsed.projectReferences
198
+ });
199
+ if (declarations) failDiagnostics(compiler, compiler.getPreEmitDiagnostics(program));
200
+ const files = [];
201
+ const modules = /* @__PURE__ */ new Map();
202
+ const result = program.emit(void 0, (file, text, _bom, _onError, sources) => {
203
+ if (sources?.some((source) => isTestSource(directory, source.fileName))) return;
204
+ if (declarations ? !/\.d\.[cm]?ts$/.test(file) : !/\.[cm]?jsx?$/.test(file)) return;
205
+ mkdirSync(dirname(file), { recursive: true });
206
+ writeFileSync(file, text);
207
+ files.push(file);
208
+ if (sources?.[0] !== void 0) modules.set(resolve(file), sources[0].fileName);
209
+ });
210
+ if (declarations) failDiagnostics(compiler, result.diagnostics);
211
+ if (declarations) files.push(...copyDeclarations(program, directory, output));
212
+ return {
213
+ compiler,
214
+ compilerRoot: root,
215
+ notice,
216
+ files,
217
+ modules,
218
+ options: parsed.options
219
+ };
220
+ }
221
+ //#endregion
222
+ export { outputRoot as a, loadTypeScript as i, isExportPath as n, packagesAt as o, isTestSource as r, unpublishedAt as s, emitPackage as t };
@@ -1,2 +1,2 @@
1
- import { a as exitIs, c as interrupted, i as exists, l as lacks, n as answers, o as fileHas, r as equal, s as has, t as answered, u as refused } from "../checks-BlWDFYio.mjs";
1
+ import { a as exitIs, c as interrupted, i as exists, l as lacks, n as answers, o as fileHas, r as equal, s as has, t as answered, u as refused } from "../checks-CxkSu2E6.mjs";
2
2
  export { answered, answers, equal, exists, exitIs, fileHas, has, interrupted, lacks, refused };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/tooling-configs",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
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",
@@ -22,6 +22,7 @@
22
22
  },
23
23
  "bin": {
24
24
  "antelopejs-api-diff": "./dist/bin/api-diff.mjs",
25
+ "antelopejs-body-check": "./dist/bin/body-check.mjs",
25
26
  "antelopejs-check-interface-ranges": "./dist/bin/check-interface-ranges.mjs",
26
27
  "antelopejs-check-size": "./dist/bin/check-size.mjs",
27
28
  "antelopejs-checks": "./dist/bin/checks.mjs",
@@ -85,7 +86,8 @@
85
86
  "oxlint-tsgolint": "^7.0.2001",
86
87
  "release-it": "^19.2.4",
87
88
  "release-it-changelogen": "^0.1.0",
88
- "tsdown": "^0.22.14"
89
+ "tsdown": "^0.22.14",
90
+ "vite": "^8.3.4"
89
91
  },
90
92
  "peerDependencies": {
91
93
  "@nuxt/eslint-config": ">=1.2.0",
@@ -1,25 +0,0 @@
1
- //#region src/verify/kinds.ts
2
- /** The repository kinds whose verification skill is synced from this pack. */
3
- const VERIFY_KINDS = [
4
- "interface",
5
- "module",
6
- "template"
7
- ];
8
- /** Whether `value` names a shared verification kind. */
9
- function isVerifyKind(value) {
10
- return VERIFY_KINDS.some((kind) => kind === value);
11
- }
12
- /** The skill folder of a kind, relative to the repository root. */
13
- function skillFolder(kind) {
14
- return `.agents/skills/verify-${kind}`;
15
- }
16
- /** The `.claude/skills` link that exposes a kind's skill folder to Claude Code. */
17
- function claudeLink(kind) {
18
- return `.claude/skills/verify-${kind}`;
19
- }
20
- /** Where the link points, relative to the link's own folder. */
21
- function claudeLinkTarget(kind) {
22
- return `../../${skillFolder(kind)}`;
23
- }
24
- //#endregion
25
- export { skillFolder as a, isVerifyKind as i, claudeLink as n, claudeLinkTarget as r, VERIFY_KINDS as t };
@@ -1,80 +0,0 @@
1
- import { a as formatCeilings, n as MAX_FILE_BYTES, o as isRetired, t as CEILINGS_FILE } from "./ceilings-BSw9p4YB.mjs";
2
- import { t as readCarriedCeilings } from "./renames-BGO4dWJ8.mjs";
3
- import { n as changedFiles, t as authoredSizes } from "./files-2FikHZ9F.mjs";
4
- import { r as lintDiagnostics } from "./staged-ratchet-CjoRfZaM.mjs";
5
- import { n as sizeFailure } from "./size-BVgNbLO6.mjs";
6
- import { existsSync, unlinkSync, writeFileSync } from "node:fs";
7
- import { join } from "node:path";
8
- //#region src/guardrails/ratchet.ts
9
- function baseline(root, diagnostics) {
10
- const rules = {};
11
- const oversizeFiles = {};
12
- const sizes = authoredSizes(root);
13
- for (const diagnostic of diagnostics) if (diagnostic.rule === "eslint/max-lines") {
14
- const size = sizes.get(diagnostic.file);
15
- if (size !== void 0) oversizeFiles[diagnostic.file] = size;
16
- } else rules[diagnostic.rule] = (rules[diagnostic.rule] ?? 0) + 1;
17
- for (const [file, size] of sizes) if (size > 2e4) oversizeFiles[file] = size;
18
- return {
19
- rules,
20
- oversizeFiles
21
- };
22
- }
23
- function measureBaseline(root, config) {
24
- return baseline(root, lintDiagnostics(root, config));
25
- }
26
- function lowerCeilings(ceilings, current) {
27
- const lowered = [];
28
- for (const [rule, limit] of Object.entries(ceilings.rules)) {
29
- const count = current.rules[rule] ?? 0;
30
- if (count === 0) delete ceilings.rules[rule];
31
- else if (count < limit) ceilings.rules[rule] = count;
32
- if (count < limit) lowered.push(`${rule}: ${limit} -> ${count}`);
33
- }
34
- for (const [file, limit] of Object.entries(ceilings.oversizeFiles)) if (current.oversizeFiles[file] === void 0) {
35
- delete ceilings.oversizeFiles[file];
36
- lowered.push(`${file}: removed oversize allowance`);
37
- } else if (current.oversizeFiles[file] < limit) {
38
- ceilings.oversizeFiles[file] = current.oversizeFiles[file];
39
- lowered.push(`${file}: ${limit} -> ${current.oversizeFiles[file]} bytes`);
40
- }
41
- return lowered;
42
- }
43
- function ratchet(root, update = false, base = "HEAD") {
44
- if (!existsSync(join(root, "guardrails.ratchet.json"))) throw new Error(`${CEILINGS_FILE} is missing. Run antelopejs-sync first.`);
45
- const ceilings = readCarriedCeilings(root, false, [base]);
46
- const diagnostics = lintDiagnostics(root);
47
- const current = baseline(root, diagnostics);
48
- const changed = changedFiles(root);
49
- const failures = [];
50
- for (const [rule, count] of Object.entries(current.rules)) {
51
- const limit = ceilings.rules[rule] ?? 0;
52
- if (count <= limit) continue;
53
- failures.push(`${rule}: ${count} diagnostics exceeds ceiling ${limit}.`);
54
- const matches = diagnostics.filter((diagnostic) => diagnostic.rule === rule);
55
- const inChanged = matches.filter(({ file }) => changed.has(file));
56
- const shown = inChanged.length > 0 ? inChanged : matches;
57
- for (const diagnostic of shown) failures.push(` ${diagnostic.location}: ${diagnostic.message}`);
58
- if (shown.length < matches.length) failures.push(` ...and ${matches.length - shown.length} recorded in files this change does not touch.`);
59
- }
60
- for (const [file, size] of Object.entries(current.oversizeFiles)) if (ceilings.oversizeFiles[file] === void 0) failures.push(size > 2e4 ? sizeFailure(file, size, MAX_FILE_BYTES) : `${file}: ${size} bytes and an eslint/max-lines diagnostic; this file has no oversize allowance. Split by responsibility into sibling modules, or split tests by behaviour under test, one file per describe.`);
61
- const sizes = authoredSizes(root, Object.keys(ceilings.oversizeFiles));
62
- for (const [file, limit] of Object.entries(ceilings.oversizeFiles)) {
63
- const size = sizes.get(file);
64
- if (size !== void 0 && size > limit) failures.push(sizeFailure(file, size, limit));
65
- }
66
- const lowered = update ? lowerCeilings(ceilings, current) : [];
67
- const retired = update && isRetired(ceilings);
68
- if (update) {
69
- const path = join(root, CEILINGS_FILE);
70
- if (retired) unlinkSync(path);
71
- else writeFileSync(path, formatCeilings(ceilings));
72
- }
73
- return {
74
- failures,
75
- lowered,
76
- retired
77
- };
78
- }
79
- //#endregion
80
- export { ratchet as n, measureBaseline as t };
@@ -1,34 +0,0 @@
1
- //#region src/oxc/shared.ts
2
- /**
3
- * Paths every AntelopeJS project generates or vendors, and that no linter should read.
4
- * `.github/ISSUE_TEMPLATE/**` holds GitHub's legacy issue templates: Markdown with
5
- * YAML frontmatter saved under a .yml extension, which a YAML formatter cannot parse.
6
- * `build/**` and `output/**` match only at the repository root: a directory with
7
- * either name under `src/` or another authored root is source, not build output.
8
- */
9
- const IGNORE_PATTERNS = [
10
- "**/node_modules/**",
11
- "**/dist/**",
12
- "**/coverage/**",
13
- "**/.antelope/**",
14
- "**/.nuxt/**",
15
- "**/.output/**",
16
- "build/**",
17
- "output/**",
18
- "**/i18n-registry.generated.ts",
19
- ".github/ISSUE_TEMPLATE/**"
20
- ];
21
- /** Agent tooling directories: assets we install, not source we own. */
22
- const AGENT_IGNORE_PATTERNS = [
23
- ".agent/**",
24
- ".agents/**",
25
- ".amp/**",
26
- ".claude/**",
27
- ".codex/**",
28
- ".cursor/**",
29
- ".gemini/**",
30
- ".opencode/**",
31
- ".windsurf/**"
32
- ];
33
- //#endregion
34
- export { IGNORE_PATTERNS as n, AGENT_IGNORE_PATTERNS as t };
@@ -1,236 +0,0 @@
1
- import { r as MEASURE_ENV, s as readCeilings } from "./ceilings-BSw9p4YB.mjs";
2
- import { n as renamedPaths } from "./renames-BGO4dWJ8.mjs";
3
- import { a as repositoryPath } from "./files-2FikHZ9F.mjs";
4
- import { createRequire } from "node:module";
5
- import { copyFileSync, existsSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, join } from "node:path";
7
- import { execFileSync, spawnSync } from "node:child_process";
8
- import { tmpdir } from "node:os";
9
- //#region src/guardrails/oxlint.ts
10
- function resolveOxlint(root) {
11
- try {
12
- const require = createRequire(join(root, "package.json"));
13
- return join(dirname(require.resolve("oxlint/package.json")), "bin/oxlint");
14
- } catch {
15
- throw new Error("oxlint is not installed in this repository. Install dependencies first.");
16
- }
17
- }
18
- function ruleId(code) {
19
- const match = /^([^()]+)\(([^()]+)\)$/.exec(code);
20
- if (!match) throw new Error(`Cannot measure oxlint diagnostic code ${JSON.stringify(code)}. Fix parser or configuration errors before recording a baseline.`);
21
- const [, plugin, rule] = match;
22
- return `${plugin === "typescript-eslint" ? "typescript" : plugin}/${rule}`;
23
- }
24
- function parseDiagnostics(text, root) {
25
- const report = JSON.parse(text);
26
- if (!Array.isArray(report?.diagnostics)) throw new Error("oxlint did not return a JSON diagnostics array.");
27
- return report.diagnostics.map((item) => {
28
- const file = repositoryPath(root, item.filename);
29
- const span = item.labels?.[0]?.span;
30
- return {
31
- rule: ruleId(item.code),
32
- file,
33
- location: span ? `${file}:${span.line}:${span.column}` : file,
34
- message: item.message,
35
- line: span?.line,
36
- help: item.help
37
- };
38
- });
39
- }
40
- function lintDiagnostics(root, config, files) {
41
- const binary = resolveOxlint(root);
42
- const temporary = config === void 0 ? void 0 : mkdtempSync(join(root, ".antelopejs-measure.generated."));
43
- try {
44
- const args = [
45
- binary,
46
- "-f",
47
- "json"
48
- ];
49
- if (temporary) {
50
- const path = join(temporary, "oxlint.config.ts");
51
- writeFileSync(path, config ?? "");
52
- args.push("--config", path, "--ignore-pattern", `${basename(temporary)}/**`);
53
- }
54
- if (files) args.push("--no-error-on-unmatched-pattern", "--", ...files);
55
- const result = spawnSync(process.execPath, args, {
56
- cwd: root,
57
- encoding: "utf8",
58
- env: {
59
- ...process.env,
60
- [MEASURE_ENV]: "1"
61
- },
62
- maxBuffer: 67108864
63
- });
64
- if (result.error) throw result.error;
65
- if (result.status !== 0 && result.status !== 1) throw new Error(`oxlint failed (${result.status ?? result.signal}): ${result.stderr || result.stdout}`);
66
- const diagnostics = parseDiagnostics(result.stdout, root);
67
- if (result.status !== 0 && diagnostics.length === 0) throw new Error(`oxlint failed without diagnostics: ${result.stderr || result.stdout}`);
68
- return diagnostics;
69
- } finally {
70
- if (temporary) rmSync(temporary, {
71
- recursive: true,
72
- force: true
73
- });
74
- }
75
- }
76
- //#endregion
77
- //#region src/guardrails/previous-tree.ts
78
- function git(root, args, env, input = "") {
79
- return execFileSync("git", args, {
80
- cwd: root,
81
- encoding: "utf8",
82
- env: {
83
- ...process.env,
84
- ...env
85
- },
86
- input,
87
- maxBuffer: 268435456
88
- });
89
- }
90
- function headEntries(root) {
91
- const entries = /* @__PURE__ */ new Map();
92
- for (const entry of git(root, [
93
- "ls-tree",
94
- "-r",
95
- "-z",
96
- "HEAD"
97
- ], {}).split("\0")) {
98
- const tab = entry.indexOf(" ");
99
- if (tab > 0) entries.set(entry.slice(tab + 1), entry.slice(0, tab));
100
- }
101
- return entries;
102
- }
103
- /**
104
- * Runs `use` on a checkout of the index in which each of `paths` holds its
105
- * HEAD content, or is absent when HEAD does not have it, so the files are
106
- * linted under the staged configuration. The checkout is deleted afterwards.
107
- */
108
- function withPreviousTree(root, paths, use) {
109
- const scratch = mkdtempSync(join(tmpdir(), "antelopejs-previous."));
110
- try {
111
- const hasHead = spawnSync("git", [
112
- "rev-parse",
113
- "--verify",
114
- "HEAD"
115
- ], {
116
- cwd: root,
117
- stdio: "ignore"
118
- }).status === 0;
119
- const index = join(scratch, "index");
120
- copyFileSync(git(root, [
121
- "rev-parse",
122
- "--path-format=absolute",
123
- "--git-path",
124
- "index"
125
- ], {}).trim(), index);
126
- const env = { GIT_INDEX_FILE: index };
127
- const head = hasHead ? headEntries(root) : /* @__PURE__ */ new Map();
128
- const restored = paths.filter((path) => head.has(path));
129
- const removed = paths.filter((path) => !head.has(path));
130
- if (restored.length) git(root, [
131
- "update-index",
132
- "-z",
133
- "--index-info"
134
- ], env, restored.map((path) => `${head.get(path)}\t${path}\0`).join(""));
135
- if (removed.length) git(root, [
136
- "update-index",
137
- "-z",
138
- "--force-remove",
139
- "--stdin"
140
- ], env, removed.map((path) => `${path}\0`).join(""));
141
- const tree = join(scratch, "tree");
142
- git(root, [
143
- "checkout-index",
144
- "-a",
145
- "-f",
146
- `--prefix=${tree}/`
147
- ], env);
148
- if (existsSync(join(root, "node_modules"))) symlinkSync(join(root, "node_modules"), join(tree, "node_modules"), "dir");
149
- return use(tree);
150
- } finally {
151
- rmSync(scratch, {
152
- recursive: true,
153
- force: true
154
- });
155
- }
156
- }
157
- //#endregion
158
- //#region src/guardrails/staged-ratchet.ts
159
- /** The line ranges each staged file adds against HEAD, following renames. */
160
- function stagedAdditions(root, targets) {
161
- const renames = renamedPaths(root, true);
162
- const additions = /* @__PURE__ */ new Map();
163
- for (const file of targets) {
164
- const diff = execFileSync("git", [
165
- "diff",
166
- "--cached",
167
- "--no-ext-diff",
168
- "--no-color",
169
- "--unified=0",
170
- "--find-renames",
171
- "--",
172
- ...[renames.get(file), file].filter((path) => path !== void 0)
173
- ], {
174
- cwd: root,
175
- encoding: "utf8"
176
- });
177
- additions.set(file, Array.from(diff.matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm), ([, line, count]) => ({
178
- start: Number(line),
179
- end: Number(line) + Number(count ?? 1) - 1
180
- })));
181
- }
182
- return additions;
183
- }
184
- function stagedNames(root, filter) {
185
- return execFileSync("git", [
186
- "diff",
187
- "--cached",
188
- "--name-only",
189
- `--diff-filter=${filter}`,
190
- "-z"
191
- ], {
192
- cwd: root,
193
- encoding: "utf8"
194
- }).split("\0").filter(Boolean);
195
- }
196
- function countByRule(diagnostics) {
197
- const counts = /* @__PURE__ */ new Map();
198
- for (const { rule } of diagnostics) counts.set(rule, (counts.get(rule) ?? 0) + 1);
199
- return counts;
200
- }
201
- const LINT_CONFIG = /(?:^|\/)(?:oxlint\.config\.[cm]?[jt]s|\.oxlintrc\.jsonc?)$/u;
202
- function headCounts(root, targets) {
203
- const renames = renamedPaths(root, true);
204
- const previous = [.../* @__PURE__ */ new Set([...targets.map((file) => renames.get(file) ?? file), ...stagedNames(root, "D")])];
205
- return countByRule(withPreviousTree(root, previous.filter((file) => !LINT_CONFIG.test(file)), (tree) => {
206
- const existing = previous.filter((file) => existsSync(join(tree, file)));
207
- return existing.length ? lintDiagnostics(tree, void 0, existing) : [];
208
- }));
209
- }
210
- /**
211
- * Fails each ceilinged rule whose findings in the staged files outnumber those
212
- * the same files, rename sources and deleted files had at HEAD. The count is
213
- * net across the staged files, so a block moved between them, or a legacy line
214
- * that is reformatted, passes; any net rise fails, and lists the findings on
215
- * the lines the commit adds.
216
- */
217
- function stagedRatchet(root, files) {
218
- const targets = files ?? stagedNames(root, "ACMR");
219
- if (!targets.length) return [];
220
- const ceilings = readCeilings(root);
221
- const after = lintDiagnostics(root, void 0, targets).filter(({ rule }) => Object.hasOwn(ceilings.rules, rule));
222
- if (!after.length) return [];
223
- const before = headCounts(root, targets);
224
- const additions = stagedAdditions(root, targets);
225
- const failures = [];
226
- for (const [rule, total] of countByRule(after)) {
227
- const rise = total - (before.get(rule) ?? 0);
228
- if (rise <= 0) continue;
229
- const matches = after.filter((diagnostic) => diagnostic.rule === rule);
230
- const added = matches.filter(({ file, line }) => line !== void 0 && additions.get(file)?.some(({ start, end }) => line >= start && line <= end));
231
- failures.push(`${rule}: this commit adds ${rise} to the staged files (${before.get(rule) ?? 0} at HEAD, ${total} staged); the ceiling covers only legacy findings.`, ...(added.length ? added : matches).map((diagnostic) => ` ${diagnostic.location}: ${diagnostic.message}\n Fix: ${diagnostic.help ?? "Resolve this finding; moving or reformatting a legacy finding is allowed, adding one is not."}`));
232
- }
233
- return failures;
234
- }
235
- //#endregion
236
- export { stagedRatchet as n, lintDiagnostics as r, stagedAdditions as t };