@antelopejs/tooling-configs 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +101 -52
  2. package/dist/bin/api-diff.mjs +430 -107
  3. package/dist/bin/body-check.d.mts +1 -0
  4. package/dist/bin/body-check.mjs +344 -0
  5. package/dist/bin/capture.d.mts +1 -0
  6. package/dist/bin/capture.mjs +559 -0
  7. package/dist/bin/check-size.mjs +3 -3
  8. package/dist/bin/checks.mjs +3 -3
  9. package/dist/bin/comment-proof.mjs +4 -3
  10. package/dist/bin/garden.mjs +6 -6
  11. package/dist/bin/ratchet.mjs +316 -10
  12. package/dist/bin/suppressions.mjs +118 -80
  13. package/dist/bin/sync.mjs +554 -153
  14. package/dist/bin/verify.mjs +240 -127
  15. package/dist/capture/index.d.mts +50 -0
  16. package/dist/capture/index.mjs +2 -0
  17. package/dist/{ceilings-BSw9p4YB.mjs → ceilings-B7KayYIG.mjs} +11 -3
  18. package/dist/{checks-BlWDFYio.mjs → checks-CxkSu2E6.mjs} +1 -1
  19. package/dist/{ci-workflow-DIsoEgMd.mjs → ci-workflow-ChW4He0r.mjs} +84 -3
  20. package/dist/{files-2FikHZ9F.mjs → files-DJ0TeaTU.mjs} +11 -5
  21. package/dist/formal/index.d.mts +40 -0
  22. package/dist/formal/index.mjs +205 -0
  23. package/dist/{json-BqvuCkqr.mjs → json-CG2L7YFl.mjs} +12 -8
  24. package/dist/oxc/anti-slop/index.mjs +869 -21
  25. package/dist/oxc/fmt.mjs +1 -1
  26. package/dist/oxc/guardrails/index.d.mts +1 -1
  27. package/dist/oxc/guardrails/index.mjs +736 -4
  28. package/dist/oxc/lint.d.mts +20 -3
  29. package/dist/oxc/lint.mjs +34 -10
  30. package/dist/oxlint-DIV-lLSS.mjs +98 -0
  31. package/dist/{package-Dtjt_lSa.mjs → package-BRTjkzt5.mjs} +29 -3
  32. package/dist/proof-stamp-DDDC0J6l.mjs +279 -0
  33. package/dist/ratchet-BAcLRYuM.mjs +448 -0
  34. package/dist/{renames-BGO4dWJ8.mjs → renames-L2owF5GD.mjs} +2 -2
  35. package/dist/scenes-DZVXkcxS.mjs +104 -0
  36. package/dist/shared-igPpEDpS.mjs +622 -0
  37. package/dist/{size-BVgNbLO6.mjs → size-DBatLT-F.mjs} +4 -4
  38. package/dist/suppression-base-9L8dlMQK.mjs +120 -0
  39. package/dist/suppression-budget-C0SkPO5R.mjs +535 -0
  40. package/dist/{suppressions-BJAngUxo.mjs → suppressions-DM60NkvL.mjs} +180 -18
  41. package/dist/templates-CypDm-j9.mjs +121 -0
  42. package/dist/typescript-CM0LrVP7.mjs +222 -0
  43. package/dist/verify/index.d.mts +6 -1
  44. package/dist/verify/index.mjs +1 -1
  45. package/package.json +31 -5
  46. package/dist/kinds-Bzyyi9yk.mjs +0 -25
  47. package/dist/ratchet-DRdIYwmv.mjs +0 -80
  48. package/dist/shared-CsXIMK3I.mjs +0 -34
  49. package/dist/staged-ratchet-CjoRfZaM.mjs +0 -236
  50. package/dist/suppression-budget-Yyf5_J5l.mjs +0 -283
  51. package/dist/typescript-C54ONh9m.mjs +0 -433
@@ -1,8 +1,8 @@
1
1
  import { n as TEST_FILE_GLOBS, t as ASSERTION_FUNCTION_NAMES } from "../shared-BG0Nkzh0.mjs";
2
2
  //#region src/oxc/lint.d.ts
3
3
  /**
4
- * oxlint replaces rather than merges ignorePatterns across extends.
5
- * Spread these patterns when adding repository-specific ignores.
4
+ * Generated output and the agent files `antelopejs-sync` writes. oxlint reads ignorePatterns only from the root config,
5
+ * never from extends: set them there, and spread them when adding repository-specific ignores.
6
6
  */
7
7
  declare const ANTELOPE_IGNORE_PATTERNS: string[];
8
8
  type Severity = "off" | "error";
@@ -68,6 +68,8 @@ declare function guardrailsRules(): {
68
68
  rules: {
69
69
  "jest/expect-expect": "off";
70
70
  "antelopejs/no-comments": "error";
71
+ "antelopejs/no-inherited-key-lookup": "error";
72
+ "antelopejs/no-presence-only-type-guard": "error";
71
73
  "jest/no-conditional-expect": "off";
72
74
  "jest/no-export": "off";
73
75
  "jest/no-standalone-expect": "off";
@@ -102,7 +104,6 @@ declare function antelopePreset(options?: AntelopePresetOptions): {
102
104
  categories: {
103
105
  correctness: "error";
104
106
  };
105
- ignorePatterns: string[];
106
107
  plugins: ("eslint" | "typescript" | "oxc" | "import" | "promise" | "node")[];
107
108
  rules: {
108
109
  "eslint/no-unused-vars": ["error", {
@@ -128,6 +129,11 @@ declare function antelopePreset(options?: AntelopePresetOptions): {
128
129
  };
129
130
  } | {
130
131
  rules: {
132
+ "typescript/no-unnecessary-type-parameters": "error";
133
+ "typescript/no-unsafe-argument": "error";
134
+ "typescript/no-unsafe-assignment": "error";
135
+ "typescript/no-unsafe-return": "error";
136
+ "typescript/use-unknown-in-catch-callback-variable": "error";
131
137
  "typescript/no-floating-promises": "error";
132
138
  "typescript/await-thenable": "error";
133
139
  "typescript/unbound-method": "error";
@@ -154,6 +160,8 @@ declare function antelopePreset(options?: AntelopePresetOptions): {
154
160
  rules: {
155
161
  "jest/expect-expect": "off";
156
162
  "antelopejs/no-comments": "error";
163
+ "antelopejs/no-inherited-key-lookup": "error";
164
+ "antelopejs/no-presence-only-type-guard": "error";
157
165
  "jest/no-conditional-expect": "off";
158
166
  "jest/no-export": "off";
159
167
  "jest/no-standalone-expect": "off";
@@ -186,6 +194,15 @@ declare function antelopePreset(options?: AntelopePresetOptions): {
186
194
  name: string;
187
195
  specifier: string;
188
196
  }[];
197
+ rules: {
198
+ "antelopejs/require-tsconfig-include": "off" | "error";
199
+ };
200
+ overrides: {
201
+ files: ("oxlint.config.ts" | "oxfmt.config.ts" | "knip.config.ts")[];
202
+ rules: {
203
+ "antelopejs/require-tsconfig-include": "off";
204
+ };
205
+ }[];
189
206
  } | {
190
207
  rules: {
191
208
  "eslint/max-params": ["error", {
package/dist/oxc/lint.mjs CHANGED
@@ -1,14 +1,15 @@
1
- import { i as findGitRoot } from "../ceilings-BSw9p4YB.mjs";
2
- import { t as readCarriedCeilings } from "../renames-BGO4dWJ8.mjs";
1
+ import { i as findGitRoot } from "../ceilings-B7KayYIG.mjs";
2
+ import { t as readCarriedCeilings } from "../renames-L2owF5GD.mjs";
3
+ import { t as PRESET_CONFIGS } from "../templates-CypDm-j9.mjs";
3
4
  import { n as TEST_FILE_GLOBS, t as ASSERTION_FUNCTION_NAMES } from "../shared-WC0z3y9F.mjs";
4
- import { n as IGNORE_PATTERNS, t as AGENT_IGNORE_PATTERNS } from "../shared-CsXIMK3I.mjs";
5
+ import { n as IGNORE_PATTERNS, r as SYNCED_AGENT_PATTERNS } from "../shared-igPpEDpS.mjs";
5
6
  import { defineConfig } from "oxlint";
6
7
  //#region src/oxc/lint.ts
7
8
  /**
8
- * oxlint replaces rather than merges ignorePatterns across extends.
9
- * Spread these patterns when adding repository-specific ignores.
9
+ * Generated output and the agent files `antelopejs-sync` writes. oxlint reads ignorePatterns only from the root config,
10
+ * never from extends: set them there, and spread them when adding repository-specific ignores.
10
11
  */
11
- const ANTELOPE_IGNORE_PATTERNS = [...IGNORE_PATTERNS, ...AGENT_IGNORE_PATTERNS];
12
+ const ANTELOPE_IGNORE_PATTERNS = [...IGNORE_PATTERNS, ...SYNCED_AGENT_PATTERNS];
12
13
  const DEFAULT_COMPLEXITY_THRESHOLDS = {
13
14
  maxParams: 5,
14
15
  maxLinesPerFunction: 120,
@@ -38,7 +39,6 @@ const ANTI_SLOP_RULES = [
38
39
  function basePreset(importCycles) {
39
40
  return defineConfig({
40
41
  categories: { correctness: "error" },
41
- ignorePatterns: ANTELOPE_IGNORE_PATTERNS,
42
42
  plugins: [
43
43
  "eslint",
44
44
  "typescript",
@@ -107,7 +107,9 @@ function guardrailsRules() {
107
107
  rules: {
108
108
  ...FRAMEWORK_SPECIFIC_JEST_RULES,
109
109
  "jest/expect-expect": "off",
110
- "antelopejs/no-comments": "error"
110
+ "antelopejs/no-comments": "error",
111
+ "antelopejs/no-inherited-key-lookup": "error",
112
+ "antelopejs/no-presence-only-type-guard": "error"
111
113
  },
112
114
  overrides: [{
113
115
  files: TEST_FILE_GLOBS,
@@ -128,12 +130,22 @@ function guardrailsRules() {
128
130
  }]
129
131
  });
130
132
  }
131
- function guardrailsPreset() {
133
+ /**
134
+ * With type-aware lint, a file no tsconfig lists is reported. The root configs
135
+ * `antelopejs-sync` writes are exempt: a tsconfig that builds `src` reaches them
136
+ * only through a referenced composite tsconfig, which every repository would need.
137
+ */
138
+ function guardrailsPreset(typeAware) {
132
139
  return defineConfig({
133
140
  extends: [guardrailsRules()],
134
141
  jsPlugins: [{
135
142
  name: "antelopejs",
136
143
  specifier: "@antelopejs/tooling-configs/oxc/guardrails"
144
+ }],
145
+ rules: { "antelopejs/require-tsconfig-include": typeAware ? "error" : "off" },
146
+ overrides: [{
147
+ files: PRESET_CONFIGS.map(({ path }) => path),
148
+ rules: { "antelopejs/require-tsconfig-include": "off" }
137
149
  }]
138
150
  });
139
151
  }
@@ -154,8 +166,20 @@ function complexityPreset(thresholds) {
154
166
  "eslint/complexity": ["error", { max: thresholds.complexity }]
155
167
  } });
156
168
  }
169
+ /**
170
+ * Besides the base set, five rules reject an `any` or a type parameter that
171
+ * stands in for `unknown`, which the anti-slop `unknown` and assertion rules
172
+ * never see: a once-used type parameter, `any` passed as a typed argument,
173
+ * assigned to a typed binding or returned as a typed result, and an untyped
174
+ * `.catch` callback variable.
175
+ */
157
176
  function typeAwarePreset() {
158
177
  return defineConfig({ rules: {
178
+ "typescript/no-unnecessary-type-parameters": "error",
179
+ "typescript/no-unsafe-argument": "error",
180
+ "typescript/no-unsafe-assignment": "error",
181
+ "typescript/no-unsafe-return": "error",
182
+ "typescript/use-unknown-in-catch-callback-variable": "error",
159
183
  "typescript/no-floating-promises": "error",
160
184
  "typescript/await-thenable": "error",
161
185
  "typescript/unbound-method": "error",
@@ -213,7 +237,7 @@ function antelopePreset(options = {}) {
213
237
  basePreset(options.importCycles !== false),
214
238
  options.typeAware === false ? null : typeAwarePreset(),
215
239
  options.antiSlop === false ? null : antiSlopPreset(),
216
- options.guardrails === false ? null : guardrailsPreset(),
240
+ options.guardrails === false ? null : guardrailsPreset(options.typeAware !== false),
217
241
  options.complexity === false ? null : complexityPreset(thresholds),
218
242
  options.importSorting === true ? importSortingPreset() : null
219
243
  ].filter((config) => config !== null),
@@ -0,0 +1,98 @@
1
+ import { r as MEASURE_ENV } from "./ceilings-B7KayYIG.mjs";
2
+ import { s as repositoryPath } from "./files-DJ0TeaTU.mjs";
3
+ import { createRequire } from "node:module";
4
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ //#region src/guardrails/oxlint.ts
8
+ const TSCONFIG_ERROR = "typescript/tsconfig-error";
9
+ function resolveOxlint(root) {
10
+ try {
11
+ const require = createRequire(join(root, "package.json"));
12
+ return join(dirname(require.resolve("oxlint/package.json")), "bin/oxlint");
13
+ } catch {
14
+ throw new Error("oxlint is not installed in this repository. Install dependencies first.");
15
+ }
16
+ }
17
+ function ruleId(code) {
18
+ const match = /^([^()]+)\(([^()]+)\)$/.exec(code);
19
+ if (!match) throw new Error(`Cannot measure oxlint diagnostic code ${JSON.stringify(code)}. Fix parser or configuration errors before recording a baseline.`);
20
+ const [, plugin, rule] = match;
21
+ return `${plugin === "typescript-eslint" ? "typescript" : plugin}/${rule}`;
22
+ }
23
+ function parseReport(text) {
24
+ const report = JSON.parse(text);
25
+ if (!Array.isArray(report?.diagnostics)) throw new Error("oxlint did not return a JSON diagnostics array.");
26
+ return report.diagnostics;
27
+ }
28
+ function toDiagnostic(item, root) {
29
+ const file = repositoryPath(root, item.filename);
30
+ const span = item.labels?.[0]?.span;
31
+ return {
32
+ rule: ruleId(item.code ?? ""),
33
+ file,
34
+ location: span ? `${file}:${span.line}:${span.column}` : file,
35
+ message: item.message,
36
+ line: span?.line,
37
+ help: item.help
38
+ };
39
+ }
40
+ function runOxlint(root, config, files, flags) {
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
+ ...flags
49
+ ];
50
+ if (temporary) {
51
+ const path = join(temporary, "oxlint.config.ts");
52
+ writeFileSync(path, config ?? "");
53
+ args.push("--config", path, "--ignore-pattern", `${basename(temporary)}/**`);
54
+ }
55
+ if (files) args.push("--no-error-on-unmatched-pattern", "--", ...files);
56
+ const result = spawnSync(process.execPath, args, {
57
+ cwd: root,
58
+ encoding: "utf8",
59
+ env: {
60
+ ...process.env,
61
+ [MEASURE_ENV]: "1"
62
+ },
63
+ maxBuffer: 67108864
64
+ });
65
+ if (result.error) throw result.error;
66
+ if (result.status !== 0 && result.status !== 1) throw new Error(`oxlint failed (${result.status ?? result.signal}): ${result.stderr || result.stdout}`);
67
+ const diagnostics = parseReport(result.stdout);
68
+ if (result.status !== 0 && diagnostics.length === 0) throw new Error(`oxlint failed without diagnostics: ${result.stderr || result.stdout}`);
69
+ return diagnostics;
70
+ } finally {
71
+ if (temporary) rmSync(temporary, {
72
+ recursive: true,
73
+ force: true
74
+ });
75
+ }
76
+ }
77
+ function lintDiagnostics(root, config, files, { rejectBrokenProject = false } = {}) {
78
+ const diagnostics = runOxlint(root, config, files, []).map((item) => toDiagnostic(item, root));
79
+ const broken = rejectBrokenProject ? diagnostics.find(({ rule }) => rule === TSCONFIG_ERROR) : void 0;
80
+ if (broken) throw new Error(`${broken.location}: ${broken.message}${broken.help ? ` ${broken.help}` : ""}. The type-aware rules cannot be measured until the TypeScript project loads.`);
81
+ return diagnostics;
82
+ }
83
+ const UNUSED_RULES = /\(no problems were reported from (.+)\)/u;
84
+ /**
85
+ * The disable directives in `files` that suppress nothing, with every ratchet
86
+ * rule enabled as in a measurement. `files` must not be empty, which would
87
+ * lint the whole repository.
88
+ */
89
+ function unusedDirectives(root, files) {
90
+ return runOxlint(root, void 0, files, ["--report-unused-disable-directives"]).filter(({ code, message }) => code === void 0 && message.startsWith("Unused ") && message.includes("-disable directive")).map((item) => ({
91
+ file: repositoryPath(root, item.filename),
92
+ line: item.labels?.[0]?.span.line ?? 0,
93
+ message: item.message,
94
+ rules: UNUSED_RULES.exec(item.message)?.[1].split(/,\s*/u)
95
+ }));
96
+ }
97
+ //#endregion
98
+ export { unusedDirectives as n, lintDiagnostics as t };
@@ -32,11 +32,12 @@ function toolingVersions() {
32
32
  const lefthook = manifest.devDependencies?.lefthook;
33
33
  const knip = manifest.devDependencies?.knip;
34
34
  const tsgolint = manifest.devDependencies?.["oxlint-tsgolint"];
35
- if (!lefthook || !knip || !tsgolint) throw new Error("tooling-configs must declare lefthook, knip and oxlint-tsgolint devDependencies.");
35
+ if (!lefthook || !knip || !tsgolint || !manifest.version) throw new Error("tooling-configs must declare its version and lefthook, knip and oxlint-tsgolint devDependencies.");
36
36
  return {
37
37
  lefthook,
38
38
  knip,
39
- tsgolint
39
+ tsgolint,
40
+ pack: manifest.version
40
41
  };
41
42
  }
42
43
  }
@@ -114,9 +115,34 @@ function managedPackage(current, versions, options = {}) {
114
115
  dependencies.knip ??= versions.knip;
115
116
  if (options.typeAware) dependencies["oxlint-tsgolint"] ??= versions.tsgolint;
116
117
  manifest.devDependencies = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b)));
118
+ return serializeManifest(manifest, current);
119
+ }
120
+ /**
121
+ * The template profile owns only the scripts `antelopejs-checks` requires and
122
+ * the profile's `sync` scripts do not provide. An already complete manifest is
123
+ * returned unchanged, so a template is never reformatted for nothing.
124
+ */
125
+ function templatePackage(current, options) {
126
+ if (current === void 0) throw new Error("package.json is missing.");
127
+ const manifest = parseManifest(current);
128
+ const commands = repositoryTools(manifest).commands;
129
+ const wanted = {
130
+ suppressions: commands.suppressions,
131
+ "suppressions:update": `${commands.suppressions} --update`,
132
+ ...options.ratchet && {
133
+ ratchet: commands.ratchet,
134
+ "ratchet:update": `${commands.ratchet} --update`
135
+ }
136
+ };
137
+ const scripts = manifest.scripts ??= {};
138
+ if (Object.entries(wanted).every(([name, command]) => scripts[name] === command)) return current;
139
+ Object.assign(scripts, wanted);
140
+ return serializeManifest(manifest, current);
141
+ }
142
+ function serializeManifest(manifest, current) {
117
143
  const indent = /^([\t ]+)"/m.exec(current)?.[1] ?? " ";
118
144
  const newline = current.includes("\r\n") ? "\r\n" : "\n";
119
145
  return `${JSON.stringify(manifest, null, indent).replaceAll("\n", newline)}${newline}`;
120
146
  }
121
147
  //#endregion
122
- export { repositoryTools as a, parseManifest as i, managedPackage as n, toolingVersions as o, packageManager as r, execCommand as t };
148
+ export { repositoryTools as a, parseManifest as i, managedPackage as n, templatePackage as o, packageManager as r, toolingVersions as s, execCommand as t };
@@ -0,0 +1,279 @@
1
+ import { l as resolveRevision, u as trackedManifests } from "./files-DJ0TeaTU.mjs";
2
+ import { o as revisionSuppressions, r as countSuppressions } from "./suppressions-DM60NkvL.mjs";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
4
+ import { dirname, join, matchesGlob } from "node:path";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+ import { createHash } from "node:crypto";
7
+ import { tmpdir } from "node:os";
8
+ //#region src/guardrails/added-entries.ts
9
+ function createAddedPolicy(globs) {
10
+ return {
11
+ globs,
12
+ verdicts: /* @__PURE__ */ new Map(),
13
+ allowed: /* @__PURE__ */ new Map(),
14
+ problems: /* @__PURE__ */ new Set()
15
+ };
16
+ }
17
+ function entryKey(directory, subpath) {
18
+ return `${directory}\0${subpath}`;
19
+ }
20
+ function allowedByGlob(policy, subpath) {
21
+ return policy.globs.some((glob) => matchesGlob(subpath, glob));
22
+ }
23
+ /** Substitutes each export star in order with its capture, as the published target pattern did. */
24
+ function fillStars(pattern, captures, format = (capture) => capture) {
25
+ let index = 0;
26
+ return pattern.replaceAll("*", () => format(captures[index++] ?? captures[0] ?? ""));
27
+ }
28
+ const INTERNAL_TAG = /@internal\b/u;
29
+ const MODULE_TAG = /@(?:packageDocumentation|module|fileoverview)\b/u;
30
+ function exportedLocalNames(compiler, source) {
31
+ const names = /* @__PURE__ */ new Set();
32
+ for (const statement of source.statements) {
33
+ if (compiler.isExportDeclaration(statement) && statement.moduleSpecifier === void 0 && statement.exportClause !== void 0 && compiler.isNamedExports(statement.exportClause)) for (const element of statement.exportClause.elements) names.add((element.propertyName ?? element.name).text);
34
+ if (compiler.isExportAssignment(statement) && compiler.isIdentifier(statement.expression)) names.add(statement.expression.text);
35
+ }
36
+ return names;
37
+ }
38
+ function declaredNames(compiler, statement) {
39
+ if (compiler.isVariableStatement(statement)) return statement.declarationList.declarations.flatMap((declaration) => compiler.isIdentifier(declaration.name) ? [declaration.name.text] : []);
40
+ if ((compiler.isFunctionDeclaration(statement) || compiler.isClassDeclaration(statement) || compiler.isInterfaceDeclaration(statement) || compiler.isTypeAliasDeclaration(statement) || compiler.isEnumDeclaration(statement) || compiler.isModuleDeclaration(statement)) && statement.name !== void 0 && compiler.isIdentifier(statement.name)) return [statement.name.text];
41
+ return [];
42
+ }
43
+ function isExportedDeclaration(compiler, statement, locals) {
44
+ if (compiler.isExportAssignment(statement)) return !compiler.isIdentifier(statement.expression);
45
+ if ((compiler.canHaveModifiers(statement) ? compiler.getModifiers(statement) : void 0)?.some((modifier) => modifier.kind === compiler.SyntaxKind.ExportKeyword)) return true;
46
+ return declaredNames(compiler, statement).some((name) => locals.has(name));
47
+ }
48
+ function hasInternalTag(compiler, statement) {
49
+ return compiler.getJSDocTags(statement).some((tag) => tag.tagName.text === "internal");
50
+ }
51
+ /** Whether a module's text carries `@internal` on the module (with `@packageDocumentation`, `@module` or `@fileoverview`) or on every exported declaration. */
52
+ function isInternalModule(compiler, text) {
53
+ const source = compiler.createSourceFile("module.ts", text, compiler.ScriptTarget.Latest, true);
54
+ if ((compiler.getLeadingCommentRanges(text, 0) ?? []).map((range) => text.slice(range.pos, range.end)).some((comment) => comment.startsWith("/**") && INTERNAL_TAG.test(comment) && MODULE_TAG.test(comment))) return true;
55
+ const locals = exportedLocalNames(compiler, source);
56
+ const exported = source.statements.filter((statement) => isExportedDeclaration(compiler, statement, locals));
57
+ return exported.length > 0 && exported.every((statement) => hasInternalTag(compiler, statement));
58
+ }
59
+ /** Records why an allowed added entry is not internal, or `undefined` when its module is. */
60
+ function recordVerdict(policy, compiler, entry) {
61
+ const internal = isInternalModule(compiler, readFileSync(entry.module, "utf8"));
62
+ policy.verdicts.set(entryKey(entry.directory, entry.subpath), internal ? void 0 : `${entry.label}: added entry ./${entry.subpath} is allowed by --allow-added but is not marked @internal. Add a leading "/** @internal @packageDocumentation */" comment to the file, or tag every exported declaration with "/** @internal */".`);
63
+ }
64
+ /** Lets matching, `@internal` additions through by removing them from the head output; returns how many files were removed. */
65
+ function applyAllowance(policy, base, head, remove) {
66
+ const existing = new Set(base.map(({ path }) => path));
67
+ let removed = 0;
68
+ for (const entry of head) {
69
+ if (existing.has(entry.path) || !allowedByGlob(policy, entry.subpath)) continue;
70
+ const key = entryKey(entry.directory, entry.subpath);
71
+ const problem = policy.verdicts.has(key) ? policy.verdicts.get(key) : `${entry.directory}: added entry ./${entry.subpath} has no emitted declaration, so @internal cannot be verified.`;
72
+ if (problem !== void 0) {
73
+ policy.problems.add(problem);
74
+ continue;
75
+ }
76
+ remove(entry.path);
77
+ removed += 1;
78
+ policy.allowed.set(key, {
79
+ directory: entry.directory,
80
+ subpath: entry.subpath
81
+ });
82
+ }
83
+ return removed;
84
+ }
85
+ /** 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
+ function describeAllowance(policy) {
87
+ const lines = [...policy.allowed.values()].map(({ directory, subpath }) => ` ${directory}: ./${subpath}\n`).sort();
88
+ return `${lines.length ? `Added (allowed): ${lines.length}\n${lines.join("")}` : ""}${[...policy.problems].map((problem) => `Not internal: ${problem}\n`).join("")}`;
89
+ }
90
+ //#endregion
91
+ //#region src/guardrails/revisions.ts
92
+ const DIRECTORY_LINK = process.platform === "win32" ? "junction" : "dir";
93
+ function linkDependencies(root, worktree) {
94
+ const directories = /* @__PURE__ */ new Set([".", ...trackedManifests(root).map(dirname)]);
95
+ for (const directory of directories) {
96
+ const source = join(root, directory, "node_modules");
97
+ const target = join(worktree, directory, "node_modules");
98
+ if (existsSync(source) && existsSync(dirname(target)) && !existsSync(target)) symlinkSync(source, target, DIRECTORY_LINK);
99
+ }
100
+ }
101
+ /** Compares isolated committed revisions and removes both worktrees even when compilation fails; a policy lets matching `@internal` additions through. */
102
+ function compareRevisions(root, baseRef, label, emit, policy) {
103
+ const temporary = mkdtempSync(join(tmpdir(), "antelope-proof-"));
104
+ const worktrees = [];
105
+ const results = [];
106
+ try {
107
+ for (const [side, ref] of [["base", baseRef], ["head", "HEAD"]]) {
108
+ const revision = execFileSync("git", [
109
+ "rev-parse",
110
+ "--verify",
111
+ "--end-of-options",
112
+ `${ref}^{commit}`
113
+ ], {
114
+ cwd: root,
115
+ encoding: "utf8",
116
+ stdio: [
117
+ "ignore",
118
+ "pipe",
119
+ "pipe"
120
+ ]
121
+ }).trim();
122
+ const worktree = join(temporary, "worktrees", side);
123
+ execFileSync("git", [
124
+ "worktree",
125
+ "add",
126
+ "--quiet",
127
+ "--detach",
128
+ worktree,
129
+ revision
130
+ ], {
131
+ cwd: root,
132
+ stdio: [
133
+ "ignore",
134
+ "pipe",
135
+ "pipe"
136
+ ]
137
+ });
138
+ worktrees.push(worktree);
139
+ linkDependencies(root, worktree);
140
+ const output = join(temporary, side);
141
+ mkdirSync(output, { recursive: true });
142
+ results.push(emit(worktree, output, join(temporary, "emit", side)));
143
+ }
144
+ const allowedAdditions = policy === void 0 ? 0 : applyAllowance(policy, results[0].published ?? [], results[1].published ?? [], (path) => rmSync(join(temporary, "head", path), { force: true }));
145
+ const diff = spawnSync("git", [
146
+ "diff",
147
+ "--no-index",
148
+ "--no-color",
149
+ "--no-renames",
150
+ "--no-ext-diff",
151
+ "--no-textconv",
152
+ "--",
153
+ "base",
154
+ "head"
155
+ ], {
156
+ cwd: temporary,
157
+ encoding: "utf8",
158
+ maxBuffer: 67108864
159
+ });
160
+ if (diff.error) throw diff.error;
161
+ if (diff.status !== 0 && diff.status !== 1) throw new Error(diff.stderr || "Could not compare revision outputs.");
162
+ const packages = new Set(results.flatMap((result) => result.packages)).size;
163
+ return {
164
+ different: diff.status === 1,
165
+ output: diff.status === 1 ? `${label}: differences against ${baseRef} (committed HEAD).\n${diff.stdout}` : `${label}: ${packages} packages, ${results[1].entries - allowedAdditions} entries unchanged against ${baseRef} (committed HEAD).\n`
166
+ };
167
+ } finally {
168
+ for (const worktree of worktrees.reverse()) execFileSync("git", [
169
+ "worktree",
170
+ "remove",
171
+ "--force",
172
+ worktree
173
+ ], {
174
+ cwd: root,
175
+ stdio: "pipe"
176
+ });
177
+ rmSync(temporary, {
178
+ recursive: true,
179
+ force: true
180
+ });
181
+ }
182
+ }
183
+ function countRows(base, head) {
184
+ const total = (counts) => Object.values(counts.rules).reduce((sum, count) => sum + count, 0);
185
+ const rules = [.../* @__PURE__ */ new Set([...Object.keys(base.rules), ...Object.keys(head.rules)])].sort((a, b) => a.localeCompare(b));
186
+ const configTotal = (counts) => Object.values(counts.config ?? {}).reduce((sum, count) => sum + count, 0);
187
+ const configRules = [.../* @__PURE__ */ new Set([...Object.keys(base.config ?? {}), ...Object.keys(head.config ?? {})])].sort((a, b) => a.localeCompare(b));
188
+ return [
189
+ [
190
+ "Lint suppressions, all rules",
191
+ total(base),
192
+ total(head)
193
+ ],
194
+ ...rules.map((rule) => [
195
+ `Lint suppressions, \`${rule}\``,
196
+ base.rules[rule] ?? 0,
197
+ head.rules[rule] ?? 0
198
+ ]),
199
+ [
200
+ "`@ts-expect-error`",
201
+ base.tsExpectError,
202
+ head.tsExpectError
203
+ ],
204
+ [
205
+ "`@ts-ignore`",
206
+ base.tsIgnore,
207
+ head.tsIgnore
208
+ ],
209
+ [
210
+ "`SAFETY:` comments",
211
+ base.safety,
212
+ head.safety
213
+ ],
214
+ [
215
+ "Lint config rule-offs, all rules",
216
+ configTotal(base),
217
+ configTotal(head)
218
+ ],
219
+ ...configRules.map((rule) => [
220
+ `Lint config rule-offs, \`${rule}\``,
221
+ base.config?.[rule] ?? 0,
222
+ head.config?.[rule] ?? 0
223
+ ])
224
+ ];
225
+ }
226
+ /** The suppression table rows, `| label | base | head |`, counted in authored code files at both revisions with the shared suppression counter. */
227
+ function revisionCountRows(root, baseRef, headRef = "HEAD") {
228
+ const [base, head] = [baseRef, headRef].map((ref) => countSuppressions(revisionSuppressions(root, resolveRevision(root, ref))));
229
+ return countRows(base, head).map(([label, before, after]) => `| ${label} | ${before} | ${after} |`);
230
+ }
231
+ /** Counts suppressions in authored code files at the base and at committed HEAD, so a PR body copies them instead of typing them. */
232
+ function revisionCounts(root, baseRef) {
233
+ 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${revisionCountRows(root, baseRef).join("\n")}\n`;
234
+ }
235
+ //#endregion
236
+ //#region src/guardrails/proof-stamp.ts
237
+ const PROOF_STAMP = /^<!-- antelopejs-proof base=([0-9a-f]{40}) head=([0-9a-f]{40}) lines=(\d+) digest=([0-9a-f]{16}) command: (.+) -->$/u;
238
+ function tableRow(line) {
239
+ return `| ${line.replace(/^\|/u, "").replace(/\|$/u, "").split("|").map((cell) => cell.trim()).map((cell) => /^:?-+:?$/u.test(cell) ? cell.replace(/-+/u, "---") : cell).join(" | ")} |`;
240
+ }
241
+ /** The lines a digest covers: trimmed, blank lines and code fences dropped, table cells re-padded, so indenting or reformatting a copy keeps it valid. */
242
+ function proofLines(lines) {
243
+ return lines.map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("```")).map((line) => line.startsWith("|") ? tableRow(line) : line);
244
+ }
245
+ /** Hashes the stamp's revisions and command with the normalised output lines. */
246
+ function proofDigest(stamp, lines) {
247
+ return createHash("sha256").update(JSON.stringify([
248
+ stamp.command,
249
+ stamp.base,
250
+ stamp.head,
251
+ ...proofLines(lines)
252
+ ])).digest("hex").slice(0, 16);
253
+ }
254
+ /** Reads a stamp line, or `undefined` when the line is not one. */
255
+ function parseProofStamp(line) {
256
+ const match = PROOF_STAMP.exec(line.trim());
257
+ if (!match) return void 0;
258
+ const [, base, head, lines, digest, command] = match;
259
+ return {
260
+ base,
261
+ head,
262
+ lines: Number(lines),
263
+ digest,
264
+ command
265
+ };
266
+ }
267
+ /** Appends a stamp line to a proof bin's output: the base and committed head it compared, the command, how many lines it printed, and a digest of them. */
268
+ function stampProof(root, command, baseRef, output) {
269
+ const stamp = {
270
+ base: resolveRevision(root, baseRef),
271
+ head: resolveRevision(root, "HEAD"),
272
+ command
273
+ };
274
+ const text = output.endsWith("\n") ? output : `${output}\n`;
275
+ const lines = text.split("\n");
276
+ return `${text}<!-- antelopejs-proof base=${stamp.base} head=${stamp.head} lines=${proofLines(lines).length} digest=${proofDigest(stamp, lines)} command: ${command} -->\n`;
277
+ }
278
+ //#endregion
279
+ export { DIRECTORY_LINK as a, revisionCounts as c, describeAllowance as d, fillStars as f, stampProof as i, allowedByGlob as l, proofDigest as n, compareRevisions as o, recordVerdict as p, proofLines as r, revisionCountRows as s, parseProofStamp as t, createAddedPolicy as u };