@antelopejs/tooling-configs 0.2.3 → 0.2.5

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 CHANGED
@@ -188,10 +188,16 @@ Pass paths to check only those files, as the pre-commit hook does. The command a
188
188
 
189
189
  ### Cleanup proof
190
190
 
191
- A behaviour-preserving cleanup PR shows `antelopejs-api-diff <base-ref>` passing. It checks each tracked, non-private package with a `tsconfig.json`, using that package's installed TypeScript. 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. Compiler errors fail the proof.
191
+ 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 has none; 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.
192
192
 
193
193
  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.
194
194
 
195
+ 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>`. 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.
196
+
197
+ ```bash
198
+ pnpm exec antelopejs-api-diff origin/main --allow-added '**/internal/**'
199
+ ```
200
+
195
201
  Both commands compare **committed HEAD**, not staged or working-tree edits. They check out the base and HEAD in temporary detached worktrees, reuse the current checkout's root and package `node_modules`, and remove the worktrees afterwards. Install the consumer's dependencies before running them.
196
202
 
197
203
  ```bash
@@ -1,11 +1,178 @@
1
1
  #!/usr/bin/env node
2
- import { c as revisionCounts, i as repositoryRoot, o as DIRECTORY_LINK, s as compareRevisions, u as runCli } from "../files-jKlueTMd.mjs";
2
+ import { c as revisionCounts, d as createAddedPolicy, f as describeAllowance, h as runCli, i as repositoryRoot, m as recordVerdict, o as DIRECTORY_LINK, p as fillStars, s as compareRevisions, u as allowedByGlob } from "../files-CaMy-5ne.mjs";
3
3
  import { i as parseManifest, r as packageManager } from "../package-Ckd7e4tA.mjs";
4
- import { i as packagesAt, n as isTestSource, r as outputRoot, t as emitPackage } from "../typescript-aLCrMi2y.mjs";
5
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
- import { dirname, join, relative, resolve } from "node:path";
4
+ import { a as unpublishedAt, i as packagesAt, n as isTestSource, r as outputRoot, t as emitPackage } from "../typescript-BlNlyAhQ.mjs";
5
+ import { createRequire } from "node:module";
6
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname, join, relative, resolve } from "node:path";
7
8
  import { execFileSync, spawnSync } from "node:child_process";
8
- import { generateDtsBundle } from "dts-bundle-generator";
9
+ import { parseArgs } from "node:util";
10
+ import { availableParallelism, freemem } from "node:os";
11
+ //#region src/guardrails/declaration-bundle.ts
12
+ const ENTRIES_PER_WORKER = 16;
13
+ const MAX_WORKERS = 8;
14
+ const WORKER_MEMORY = 1.5 * 1024 ** 3;
15
+ const WORKER = `
16
+ const { readFileSync, writeFileSync } = require("node:fs");
17
+ const { createRequire } = require("node:module");
18
+ try {
19
+ const job = JSON.parse(readFileSync(process.argv[2], "utf8"));
20
+ const generate = createRequire(job.loader)("dts-bundle-generator").generateDtsBundle;
21
+ writeFileSync(job.result, JSON.stringify(generate(job.entries, job.options)));
22
+ } catch (error) {
23
+ process.stderr.write(String(error instanceof Error ? error.message : error));
24
+ process.exit(1);
25
+ }
26
+ `;
27
+ const DRIVER = `
28
+ const { spawn } = require("node:child_process");
29
+ const [worker, ...jobs] = process.argv.slice(1);
30
+ let failed = false;
31
+ let pending = jobs.length;
32
+ for (const job of jobs) {
33
+ spawn(process.execPath, [worker, job], { stdio: ["ignore", "inherit", "inherit"] }).on("exit", (code) => {
34
+ failed ||= code !== 0;
35
+ pending -= 1;
36
+ if (pending === 0) process.exit(failed ? 1 : 0);
37
+ });
38
+ }
39
+ `;
40
+ /** Places a copy of `dts-bundle-generator` beside a `typescript` link to the package at `compilerRoot`, the compiler the target repository builds with. The generator requires `typescript` by name, so this makes it drive that compiler instead of the one it was installed with. Returns a path to require the copy from. */
41
+ function installGenerator(compilerRoot, scratch) {
42
+ const source = dirname(createRequire(import.meta.url).resolve("dts-bundle-generator/package.json"));
43
+ const modules = join(scratch, "generator", "node_modules");
44
+ mkdirSync(modules, { recursive: true });
45
+ cpSync(source, join(modules, "dts-bundle-generator"), {
46
+ recursive: true,
47
+ filter: (path) => basename(path) !== "node_modules"
48
+ });
49
+ symlinkSync(compilerRoot, join(modules, "typescript"), DIRECTORY_LINK);
50
+ return join(modules, "index.js");
51
+ }
52
+ /** Workers for `count` entries: each builds its own program, so a worker needs enough entries to repay that, and the bound keeps their combined heap inside the memory that is free. */
53
+ function workerCount(count, cpus = availableParallelism(), free = freemem()) {
54
+ return Math.max(1, Math.min(Math.floor(count / ENTRIES_PER_WORKER), cpus, MAX_WORKERS, Math.floor(free / WORKER_MEMORY)));
55
+ }
56
+ function generateInWorkers(loader, directory, entries, options, workers) {
57
+ const jobs = Array.from({ length: workers }, (_, worker) => ({
58
+ indices: entries.flatMap((_entry, index) => index % workers === worker ? [index] : []),
59
+ file: join(directory, `job-${worker}.json`),
60
+ result: join(directory, `result-${worker}.json`)
61
+ }));
62
+ for (const { indices, file, result } of jobs) writeFileSync(file, JSON.stringify({
63
+ loader,
64
+ result,
65
+ options,
66
+ entries: indices.map((index) => entries[index])
67
+ }));
68
+ const worker = join(directory, "worker.cjs");
69
+ writeFileSync(worker, WORKER);
70
+ const run = spawnSync(process.execPath, [
71
+ "-e",
72
+ DRIVER,
73
+ worker,
74
+ ...jobs.map(({ file }) => file)
75
+ ], {
76
+ encoding: "utf8",
77
+ stdio: [
78
+ "ignore",
79
+ "ignore",
80
+ "pipe"
81
+ ]
82
+ });
83
+ if (run.error) throw run.error;
84
+ if (run.status !== 0) throw new Error(run.stderr || "A declaration bundling worker failed.");
85
+ const bundles = [];
86
+ for (const { indices, result } of jobs) for (const [position, bundle] of JSON.parse(readFileSync(result, "utf8")).entries()) bundles[indices[position]] = bundle;
87
+ return bundles;
88
+ }
89
+ /** Bundles every entry's declarations with the compiler at `compilerRoot`. Large packages are split across worker processes by entry; each bundle depends only on its own entry, so the output is the same as one sequential call. */
90
+ function bundleDeclarations(compilerRoot, scratch, entries, options, workers = workerCount(entries.length)) {
91
+ const loader = installGenerator(compilerRoot, scratch);
92
+ if (workers > 1) return generateInWorkers(loader, join(scratch, "generator"), entries, options, workers);
93
+ const generate = createRequire(loader)("dts-bundle-generator").generateDtsBundle;
94
+ return generate(entries, options);
95
+ }
96
+ //#endregion
97
+ //#region src/guardrails/declaration-order.ts
98
+ const CALL = 0;
99
+ const CONSTRUCT = 1;
100
+ const INDEX = 2;
101
+ const CONSTRUCTOR = 3;
102
+ const INSTANCE = 4;
103
+ const STATIC = 5;
104
+ function nameText(compiler, name, source) {
105
+ return compiler.isIdentifier(name) || compiler.isStringLiteral(name) || compiler.isNumericLiteral(name) || compiler.isPrivateIdentifier(name) ? name.text : name.getText(source);
106
+ }
107
+ function memberKey(compiler, member, source) {
108
+ if (compiler.isCallSignatureDeclaration(member)) return {
109
+ rank: CALL,
110
+ name: ""
111
+ };
112
+ if (compiler.isConstructSignatureDeclaration(member)) return {
113
+ rank: CONSTRUCT,
114
+ name: ""
115
+ };
116
+ if (compiler.isConstructorDeclaration(member)) return {
117
+ rank: CONSTRUCTOR,
118
+ name: ""
119
+ };
120
+ if (compiler.isIndexSignatureDeclaration(member)) return {
121
+ rank: INDEX,
122
+ name: member.parameters[0]?.type?.getText(source) ?? ""
123
+ };
124
+ return {
125
+ rank: compiler.canHaveModifiers(member) && (compiler.getModifiers(member) ?? []).some(({ kind }) => kind === compiler.SyntaxKind.StaticKeyword) ? STATIC : INSTANCE,
126
+ name: member.name === void 0 ? "" : nameText(compiler, member.name, source)
127
+ };
128
+ }
129
+ function compareKeys(a, b) {
130
+ if (a.rank !== b.rank) return a.rank - b.rank;
131
+ if (a.name === b.name) return 0;
132
+ return a.name < b.name ? -1 : 1;
133
+ }
134
+ /** Orders `visited` by keys read from `original`, the same members before their children were rewritten. The sort is stable, so overloads of one name, call signatures and construct signatures keep their written order. */
135
+ function sortMembers(compiler, visited, original, source) {
136
+ const keyed = visited.map((member, index) => ({
137
+ member,
138
+ key: memberKey(compiler, original[index], source)
139
+ }));
140
+ keyed.sort((a, b) => compareKeys(a.key, b.key));
141
+ return compiler.factory.createNodeArray(keyed.map(({ member }) => member));
142
+ }
143
+ /** Rewrites every object type literal, interface and class in `file`, whose nodes were parsed from `source`, so its members appear in a canonical order. Member order does not change a type, so two declaration texts that differ only in it print identically. Tuple elements, parameters, overloads of one name, enum members, union and intersection constituents and statement bodies of namespaces keep the order they were written in. */
144
+ function sortDeclarationMembers(compiler, file, source) {
145
+ const { factory } = compiler;
146
+ const result = compiler.transform(file, [(context) => {
147
+ const visit = (node) => {
148
+ const visited = compiler.visitEachChild(node, visit, context);
149
+ if (compiler.isTypeLiteralNode(node) && compiler.isTypeLiteralNode(visited)) return factory.updateTypeLiteralNode(visited, sortMembers(compiler, visited.members, node.members, source));
150
+ if (compiler.isInterfaceDeclaration(node) && compiler.isInterfaceDeclaration(visited)) return factory.updateInterfaceDeclaration(visited, visited.modifiers, visited.name, visited.typeParameters, visited.heritageClauses, sortMembers(compiler, visited.members, node.members, source));
151
+ if (compiler.isClassDeclaration(node) && compiler.isClassDeclaration(visited)) return factory.updateClassDeclaration(visited, visited.modifiers, visited.name, visited.typeParameters, visited.heritageClauses, sortMembers(compiler, visited.members, node.members, source));
152
+ return visited;
153
+ };
154
+ return (root) => visit(root);
155
+ }]);
156
+ const [transformed] = result.transformed;
157
+ result.dispose();
158
+ return transformed;
159
+ }
160
+ function statementName(compiler, statement, source) {
161
+ if (compiler.isVariableStatement(statement)) return statement.declarationList.declarations[0]?.name.getText(source) ?? "";
162
+ if (compiler.isFunctionDeclaration(statement) || compiler.isClassDeclaration(statement) || compiler.isInterfaceDeclaration(statement) || compiler.isTypeAliasDeclaration(statement) || compiler.isEnumDeclaration(statement) || compiler.isModuleDeclaration(statement) || compiler.isImportEqualsDeclaration(statement)) return statement.name?.getText(source) ?? "default";
163
+ return statement.getText(source);
164
+ }
165
+ /** Prints a bundle in canonical form: top-level statements by name and object members in a fixed order. */
166
+ function normalizeBundle(compiler, text) {
167
+ const source = compiler.createSourceFile("bundle.d.ts", text, compiler.ScriptTarget.Latest, true);
168
+ const statements = [...source.statements].sort((a, b) => statementName(compiler, a, source).localeCompare(statementName(compiler, b, source)));
169
+ const normalized = sortDeclarationMembers(compiler, compiler.factory.updateSourceFile(source, statements), source);
170
+ return compiler.createPrinter({
171
+ removeComments: true,
172
+ newLine: compiler.NewLineKind.LineFeed
173
+ }).printFile(normalized);
174
+ }
175
+ //#endregion
9
176
  //#region src/guardrails/runtime-diff.ts
10
177
  const DESCRIBE = `
11
178
  const { readFileSync, existsSync } = require("node:fs");
@@ -44,12 +211,13 @@ function properties(object, observe) {
44
211
  process.stdout.write(JSON.stringify({ kind: esm ? "esm" : "cjs", value: valueInfo(value), properties: typeof value === "function" ? [] : properties(value, true) }));
45
212
  })().catch(error => { process.stderr.write(String(error.stack)); process.exitCode = 1; });
46
213
  `;
47
- function runtimeTargets(target, entry = "exports") {
214
+ function runtimeTargets(target, entry = "exports", subpath = ".") {
48
215
  if (target == null) return [];
49
- if (Array.isArray(target)) return target.flatMap((value, index) => runtimeTargets(value, `${entry}/${index}`));
216
+ if (Array.isArray(target)) return target.flatMap((value, index) => runtimeTargets(value, `${entry}/${index}`, subpath));
50
217
  if (target.constructor === String) return [{
51
218
  entry,
52
- target: String(target)
219
+ target: String(target),
220
+ subpath
53
221
  }];
54
222
  return Object.entries(target).flatMap(([key, value]) => {
55
223
  if (key === "types") return [];
@@ -58,23 +226,25 @@ function runtimeTargets(target, entry = "exports") {
58
226
  "deno",
59
227
  "react-native"
60
228
  ].includes(key)) throw new Error(`${entry}/${key}: unsupported runtime environment.`);
61
- return runtimeTargets(value, `${entry}/${key}`);
229
+ return runtimeTargets(value, `${entry}/${key}`, key.startsWith(".") ? key.slice(2) || "." : subpath);
62
230
  });
63
231
  }
64
232
  function builtEntries(directory, manifest) {
65
233
  const targets = runtimeTargets(manifest.exports);
66
234
  if (manifest.main) targets.push({
67
235
  entry: "main",
68
- target: manifest.main
236
+ target: manifest.main,
237
+ subpath: "main"
69
238
  });
70
239
  if (!targets.length) throw new Error(`${directory}: no published runtime entry.`);
71
- return targets.filter(({ target }) => !target.endsWith(".json")).flatMap(({ entry, target }) => {
240
+ return targets.filter(({ target }) => !target.endsWith(".json")).flatMap(({ entry, target, subpath }) => {
72
241
  if (!target.includes("*")) {
73
242
  const file = resolve(directory, target);
74
243
  if (!existsSync(file)) throw new Error(`${directory}: missing built runtime entry ${target}.`);
75
244
  return [{
76
245
  entry,
77
- file
246
+ file,
247
+ subpath
78
248
  }];
79
249
  }
80
250
  const prefix = resolve(directory, target.slice(0, target.indexOf("*")));
@@ -91,7 +261,8 @@ function builtEntries(directory, manifest) {
91
261
  const capture = pattern.exec(file)?.[1] ?? relative(directory, file);
92
262
  return {
93
263
  entry: entry.replaceAll("*", capture),
94
- file
264
+ file,
265
+ subpath: fillStars(subpath, [capture])
95
266
  };
96
267
  });
97
268
  });
@@ -146,23 +317,37 @@ function buildPackage(directory, output, manifest) {
146
317
  mkdirSync(dirname(destination), { recursive: true });
147
318
  writeFileSync(destination, metadata);
148
319
  }
149
- return entries.length;
320
+ return {
321
+ count: entries.length,
322
+ entries
323
+ };
150
324
  }
151
325
  /** Builds both committed revisions and compares published runtime metadata and one captured optional probe. */
152
- function runtimeDiff(root, baseRef, probe) {
326
+ function runtimeDiff(root, baseRef, probe, policy) {
153
327
  const errors = [];
154
328
  const failedPackages = /* @__PURE__ */ new Set();
155
329
  const skippedPackages = /* @__PURE__ */ new Set();
156
330
  const result = compareRevisions(root, baseRef, "Runtime API", (worktree, output, scratch) => {
157
331
  const packages = packagesAt(worktree, true);
332
+ const published = [];
158
333
  let entries = 0;
159
- for (const { directory, manifest } of packages) try {
160
- const built = buildPackage(join(worktree, directory), join(output, encodeURIComponent(directory).replaceAll(".", "%2E")), manifest);
161
- if (built === void 0) skippedPackages.add(directory);
162
- else entries += built;
163
- } catch (error) {
164
- failedPackages.add(directory);
165
- errors.push(`Execution error: ${directory}: ${error instanceof Error ? error.message : String(error)}\n`);
334
+ for (const { directory, manifest } of packages) {
335
+ const folder = encodeURIComponent(directory).replaceAll(".", "%2E");
336
+ try {
337
+ const built = buildPackage(join(worktree, directory), join(output, folder), manifest);
338
+ if (built === void 0) skippedPackages.add(directory);
339
+ else {
340
+ entries += built.count;
341
+ published.push(...built.entries.map(({ entry, subpath }) => ({
342
+ path: `${folder}/${encodeURIComponent(entry)}.json`,
343
+ directory,
344
+ subpath
345
+ })));
346
+ }
347
+ } catch (error) {
348
+ failedPackages.add(directory);
349
+ errors.push(`Execution error: ${directory}: ${error instanceof Error ? error.message : String(error)}\n`);
350
+ }
166
351
  }
167
352
  for (const directory of failedPackages) for (const side of ["base", "head"]) rmSync(join(dirname(output), side, encodeURIComponent(directory).replaceAll(".", "%2E")), {
168
353
  recursive: true,
@@ -176,9 +361,10 @@ function runtimeDiff(root, baseRef, probe) {
176
361
  }
177
362
  return {
178
363
  packages: packages.map(({ directory }) => directory),
179
- entries
364
+ entries,
365
+ published
180
366
  };
181
- });
367
+ }, policy);
182
368
  return {
183
369
  different: result.different || errors.length > 0,
184
370
  output: (errors.length && !result.different ? result.output.replace(/^Runtime API:[^\n]*\n/u, "Runtime API: comparison incomplete due to execution errors.\n") : result.output) + [...skippedPackages].map((directory) => `Runtime API: skipped ${directory}, which has no build script and no committed runtime entry.\n`).join("") + errors.join("")
@@ -192,16 +378,17 @@ function entrySegment(value) {
192
378
  function entryPattern(value) {
193
379
  return value.split("*").map(entrySegment).join("*");
194
380
  }
195
- function exportTargets(target, entry = "exports/root") {
381
+ function exportTargets(target, entry = "exports/root", subpath = ".") {
196
382
  if (typeof target === "string") return [{
197
383
  entry,
198
- target
384
+ target,
385
+ subpath
199
386
  }];
200
387
  if (target == null) return [];
201
- if (Array.isArray(target)) return target.flatMap((value, index) => exportTargets(value, `${entry}/fallback/${index}`));
202
- if (target.types !== void 0) return exportTargets(target.types, entry);
388
+ if (Array.isArray(target)) return target.flatMap((value, index) => exportTargets(value, `${entry}/fallback/${index}`, subpath));
389
+ if (target.types !== void 0) return exportTargets(target.types, entry, subpath);
203
390
  return Object.entries(target).flatMap(([key, value]) => {
204
- return exportTargets(value, key.startsWith(".") ? key === "." ? "exports/root" : `exports/subpath/${entryPattern(key.slice(2))}` : `${entry}/condition/${entrySegment(key)}`);
391
+ return exportTargets(value, key.startsWith(".") ? key === "." ? "exports/root" : `exports/subpath/${entryPattern(key.slice(2))}` : `${entry}/condition/${entrySegment(key)}`, key.startsWith(".") ? key.slice(2) || "." : subpath);
205
392
  });
206
393
  }
207
394
  function declarationTarget(target) {
@@ -221,16 +408,18 @@ function entryPatterns(manifest) {
221
408
  const target = manifest[key];
222
409
  if (target !== void 0) targets.push({
223
410
  entry: key,
224
- target
411
+ target,
412
+ subpath: key
225
413
  });
226
414
  }
227
415
  for (const [version, mappings] of Object.entries(manifest.typesVersions ?? {})) for (const [entry, paths] of Object.entries(mappings)) for (const [index, target] of paths.entries()) targets.push({
228
416
  entry: `typesVersions/${entrySegment(version)}/${entryPattern(entry)}/${index}`,
229
- target
417
+ target,
418
+ subpath: entry
230
419
  });
231
- return targets.map(({ entry, target }) => ({
232
- entry,
233
- target: declarationTarget(target)
420
+ return targets.map((published) => ({
421
+ ...published,
422
+ target: declarationTarget(published.target)
234
423
  })).filter(({ target }) => /\.d\.[cm]?ts$/u.test(target) || target.includes("*"));
235
424
  }
236
425
  /** Export stars are substitutions rather than path globs and can span directory separators. */
@@ -241,7 +430,7 @@ function publishedEntries(directory, manifest, emitted, scratch) {
241
430
  const outputRoot = resolve(directory, emitted.options.outDir ?? ".");
242
431
  const files = emitted.files.map((file) => relative(scratch, file).split("\\").join("/"));
243
432
  const entries = [];
244
- for (const { entry, target } of entryPatterns(manifest)) {
433
+ for (const { entry, target, subpath } of entryPatterns(manifest)) {
245
434
  if (isTestSource(outputRoot, resolve(directory, target))) continue;
246
435
  const path = relative(outputRoot, resolve(directory, target)).split("\\").join("/");
247
436
  const pattern = targetPattern(path);
@@ -249,30 +438,16 @@ function publishedEntries(directory, manifest, emitted, scratch) {
249
438
  if (!matches.length && !path.includes("*")) throw new Error(`${directory}: published target ${target} has no emitted declaration.`);
250
439
  for (const file of matches) {
251
440
  const captures = pattern.exec(file)?.slice(1) ?? [];
252
- let index = 0;
253
- const name = entry.includes("*") ? entry.replaceAll("*", () => entrySegment(captures[index++] ?? captures[0] ?? "")) : `${entry}${captures.length ? `/file/${entrySegment(file)}` : ""}`;
441
+ const name = entry.includes("*") ? fillStars(entry, captures, entrySegment) : `${entry}${captures.length ? `/file/${entrySegment(file)}` : ""}`;
254
442
  entries.push({
255
443
  entry: `${name}.d.ts`,
256
- file
444
+ file,
445
+ subpath: subpath.includes("*") ? fillStars(subpath, captures) : captures.length ? `${subpath}/${captures[0]}` : subpath
257
446
  });
258
447
  }
259
448
  }
260
449
  return entries.sort((a, b) => a.entry.localeCompare(b.entry));
261
450
  }
262
- function statementName(compiler, statement, source) {
263
- if (compiler.isVariableStatement(statement)) return statement.declarationList.declarations[0]?.name.getText(source) ?? "";
264
- if (compiler.isFunctionDeclaration(statement) || compiler.isClassDeclaration(statement) || compiler.isInterfaceDeclaration(statement) || compiler.isTypeAliasDeclaration(statement) || compiler.isEnumDeclaration(statement) || compiler.isModuleDeclaration(statement) || compiler.isImportEqualsDeclaration(statement)) return statement.name?.getText(source) ?? "default";
265
- return statement.getText(source);
266
- }
267
- function normalizeBundle(compiler, text) {
268
- const source = compiler.createSourceFile("bundle.d.ts", text, compiler.ScriptTarget.Latest, true);
269
- const statements = [...source.statements].sort((a, b) => statementName(compiler, a, source).localeCompare(statementName(compiler, b, source)));
270
- const normalized = compiler.factory.updateSourceFile(source, statements);
271
- return compiler.createPrinter({
272
- removeComments: true,
273
- newLine: compiler.NewLineKind.LineFeed
274
- }).printFile(normalized);
275
- }
276
451
  function bundleDependencies(directory, scratch) {
277
452
  let current = directory;
278
453
  while (!existsSync(join(current, "node_modules"))) {
@@ -288,10 +463,14 @@ function generatorEntry(file) {
288
463
  if (alias !== file) copyFileSync(file, alias);
289
464
  return alias;
290
465
  }
291
- function bundlePackage(directory, output, scratch, manifest) {
466
+ function bundlePackage(paths, manifest, policy) {
467
+ const { directory, output, scratch } = paths;
292
468
  const emitted = emitPackage(directory, scratch, true);
293
469
  const entries = publishedEntries(directory, manifest, emitted, scratch);
294
- if (!entries.length) return 0;
470
+ if (!entries.length) return {
471
+ count: 0,
472
+ published: []
473
+ };
295
474
  bundleDependencies(directory, scratch);
296
475
  writeFileSync(join(scratch, "package.json"), readFileSync(join(directory, "package.json")));
297
476
  const config = join(scratch, "tsconfig.json");
@@ -306,7 +485,7 @@ function bundlePackage(directory, output, scratch, manifest) {
306
485
  files: entries.map(({ file }) => join(scratch, file)),
307
486
  include: []
308
487
  }));
309
- const bundles = generateDtsBundle(entries.map(({ file }) => ({
488
+ const bundles = bundleDeclarations(emitted.compilerRoot, scratch, entries.map(({ file }) => ({
310
489
  filePath: generatorEntry(join(scratch, file)),
311
490
  output: {
312
491
  exportReferencedTypes: false,
@@ -319,40 +498,111 @@ function bundlePackage(directory, output, scratch, manifest) {
319
498
  mkdirSync(dirname(path), { recursive: true });
320
499
  writeFileSync(path, normalizeBundle(emitted.compiler, bundles[index]));
321
500
  }
322
- return entries.length;
501
+ if (policy !== void 0) for (const { file, subpath } of entries) {
502
+ if (!allowedByGlob(policy, subpath)) continue;
503
+ const emittedFile = join(scratch, file);
504
+ const module = emitted.modules.get(resolve(emittedFile)) ?? emittedFile;
505
+ recordVerdict(policy, emitted.compiler, {
506
+ directory: paths.name,
507
+ subpath,
508
+ module,
509
+ label: relative(paths.root, module).split("\\").join("/")
510
+ });
511
+ }
512
+ return {
513
+ count: entries.length,
514
+ published: entries.map(({ entry, subpath }) => ({
515
+ path: `${paths.name === "." ? "_root" : paths.name}/${entry}`,
516
+ directory: paths.name,
517
+ subpath
518
+ }))
519
+ };
323
520
  }
324
- function declarationDiff(root, baseRef) {
325
- return compareRevisions(root, baseRef, "API", (worktree, output, scratch) => {
521
+ function declarationDiff(root, baseRef, policy) {
522
+ const errors = /* @__PURE__ */ new Set();
523
+ const failedPackages = /* @__PURE__ */ new Set();
524
+ const unpublished = /* @__PURE__ */ new Map();
525
+ const result = compareRevisions(root, baseRef, "API", (worktree, output, scratch) => {
326
526
  const packages = packagesAt(worktree, true);
527
+ for (const { directory, reason } of unpublishedAt(worktree)) unpublished.set(directory, reason);
528
+ const published = [];
327
529
  let entries = 0;
328
- for (const { directory, manifest } of packages) entries += bundlePackage(join(worktree, directory), join(output, directory === "." ? "_root" : directory), join(scratch, directory === "." ? "_root" : directory), manifest);
530
+ for (const { directory, manifest } of packages) {
531
+ const key = directory === "." ? "_root" : directory;
532
+ try {
533
+ const bundled = bundlePackage({
534
+ root: worktree,
535
+ name: directory,
536
+ directory: join(worktree, directory),
537
+ output: join(output, key),
538
+ scratch: join(scratch, key)
539
+ }, manifest, policy);
540
+ entries += bundled.count;
541
+ published.push(...bundled.published);
542
+ } catch (error) {
543
+ failedPackages.add(directory);
544
+ errors.add(`Execution error: ${directory}${manifest.name === void 0 ? "" : ` (${manifest.name})`}: ${error instanceof Error ? error.message : String(error)}\n`);
545
+ }
546
+ }
547
+ for (const directory of failedPackages) for (const side of ["base", "head"]) rmSync(join(dirname(output), side, directory === "." ? "_root" : directory), {
548
+ recursive: true,
549
+ force: true
550
+ });
329
551
  return {
330
552
  packages: packages.map(({ directory }) => directory),
331
- entries
553
+ entries,
554
+ published
332
555
  };
333
- });
556
+ }, policy);
557
+ return {
558
+ 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("")
560
+ };
334
561
  }
335
- /** Compares declarations and built runtime exports, with an optional behavioral probe captured before either build. */
336
- function apiDiff(root, baseRef, probeFile) {
562
+ /** 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`. */
563
+ function apiDiff(root, baseRef, probeFile, allowAdded = []) {
564
+ const policy = allowAdded.length ? createAddedPolicy(allowAdded) : void 0;
337
565
  const probe = probeFile === void 0 ? void 0 : readFileSync(resolve(root, probeFile));
338
566
  const results = [];
339
567
  const errors = [];
340
- for (const compare of [() => declarationDiff(root, baseRef), () => runtimeDiff(root, baseRef, probe)]) try {
568
+ for (const compare of [() => declarationDiff(root, baseRef, policy), () => runtimeDiff(root, baseRef, probe, policy)]) try {
341
569
  results.push(compare());
342
570
  } catch (error) {
343
571
  errors.push(`Execution error: ${error instanceof Error ? error.message : String(error)}\n`);
344
572
  }
345
573
  return {
346
- different: errors.length > 0 || results.some((result) => result.different),
347
- output: results.map((result) => result.output).join("") + errors.join("") + (probe === void 0 ? "No behavioural probe ran.\n" : "Behavioural probe supplied.\n") + revisionCounts(root, baseRef)
574
+ different: errors.length > 0 || results.some((result) => result.different) || (policy?.problems.size ?? 0) > 0,
575
+ output: results.map((result) => result.output).join("") + (policy === void 0 ? "" : describeAllowance(policy)) + errors.join("") + (probe === void 0 ? "No behavioural probe ran.\n" : "Behavioural probe supplied.\n") + revisionCounts(root, baseRef)
348
576
  };
349
577
  }
350
578
  //#endregion
351
579
  //#region src/bin/api-diff.ts
580
+ const USAGE = "Usage: antelopejs-api-diff <base-ref> [--probe <file.cjs>] [--allow-added <glob>]...";
581
+ function parse(args) {
582
+ try {
583
+ const { positionals, values } = parseArgs({
584
+ args,
585
+ allowPositionals: true,
586
+ options: {
587
+ probe: { type: "string" },
588
+ "allow-added": {
589
+ type: "string",
590
+ multiple: true
591
+ }
592
+ }
593
+ });
594
+ if (positionals.length !== 1) throw new Error(USAGE);
595
+ return {
596
+ baseRef: positionals[0],
597
+ ...values
598
+ };
599
+ } catch {
600
+ throw new Error(USAGE);
601
+ }
602
+ }
352
603
  runCli(() => {
353
- const args = process.argv.slice(2);
354
- if (args.length !== 1 && !(args.length === 3 && args[1] === "--probe")) throw new Error("Usage: antelopejs-api-diff <base-ref> [--probe <file.cjs>]");
355
- const result = apiDiff(repositoryRoot(), args[0], args[2]);
604
+ const { baseRef, probe, "allow-added": allowAdded } = parse(process.argv.slice(2));
605
+ const result = apiDiff(repositoryRoot(), baseRef, probe, allowAdded);
356
606
  process.stdout.write(result.output);
357
607
  return result.different ? 1 : 0;
358
608
  });
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { i as repositoryRoot, r as repositoryPath, t as authoredSizes, u as runCli } from "../files-jKlueTMd.mjs";
3
- import { t as checkSize } from "../size-BdYmv57u.mjs";
2
+ import { h as runCli, i as repositoryRoot, r as repositoryPath, t as authoredSizes } from "../files-CaMy-5ne.mjs";
3
+ import { t as checkSize } from "../size-DYVe2pXo.mjs";
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { join, resolve } from "node:path";
6
6
  import { spawnSync } from "node:child_process";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import "../ceilings-BSw9p4YB.mjs";
3
- import { i as repositoryRoot, u as runCli } from "../files-jKlueTMd.mjs";
3
+ import { h as runCli, i as repositoryRoot } from "../files-CaMy-5ne.mjs";
4
4
  import { i as parseManifest, r as packageManager } from "../package-Ckd7e4tA.mjs";
5
5
  import { existsSync, readFileSync } from "node:fs";
6
6
  import { join } from "node:path";
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { c as revisionCounts, i as repositoryRoot, s as compareRevisions, u as runCli } from "../files-jKlueTMd.mjs";
3
- import { i as packagesAt, t as emitPackage } from "../typescript-aLCrMi2y.mjs";
2
+ import { c as revisionCounts, h as runCli, i as repositoryRoot, s as compareRevisions } from "../files-CaMy-5ne.mjs";
3
+ import { i as packagesAt, t as emitPackage } from "../typescript-BlNlyAhQ.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,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { s as readCeilings, t as CEILINGS_FILE } from "../ceilings-BSw9p4YB.mjs";
3
3
  import { n as renamedPaths } from "../renames-BGO4dWJ8.mjs";
4
- import { a as resolveRevision, i as repositoryRoot, r as repositoryPath, u as runCli } from "../files-jKlueTMd.mjs";
5
- import { n as ratchet, r as lintDiagnostics } from "../ratchet-CNbpU42F.mjs";
4
+ import { a as resolveRevision, h as runCli, i as repositoryRoot, r as repositoryPath } from "../files-CaMy-5ne.mjs";
5
+ import { n as ratchet, r as lintDiagnostics } from "../ratchet-Bz4Rl3_r.mjs";
6
6
  import { resolve } from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
8
  import { parseArgs } from "node:util";
package/dist/bin/sync.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { a as formatCeilings, o as isRetired, s as readCeilings, t as CEILINGS_FILE } from "../ceilings-BSw9p4YB.mjs";
3
- import { i as repositoryRoot, u as runCli } from "../files-jKlueTMd.mjs";
3
+ import { h as runCli, i as repositoryRoot } from "../files-CaMy-5ne.mjs";
4
4
  import { a as repositoryTools, i as parseManifest, n as managedPackage, o as toolingVersions, r as packageManager, t as execCommand } from "../package-Ckd7e4tA.mjs";
5
- import { t as measureBaseline } from "../ratchet-CNbpU42F.mjs";
5
+ import { t as measureBaseline } from "../ratchet-Bz4Rl3_r.mjs";
6
6
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { dirname, join, resolve } from "node:path";
8
8
  import { execFileSync } from "node:child_process";
@@ -27,7 +27,7 @@ Hold every test you write or keep to this checklist:
27
27
  - An invariant over many files is a lint rule, not a test.`;
28
28
  const CLEANUP_PROOF = `### Cleanup proof
29
29
 
30
- A behaviour-preserving cleanup PR shows \`antelopejs-api-diff <base-ref>\` passing. Published declarations and built runtime exports stay unchanged. A comment-only PR shows \`antelopejs-comment-proof <base-ref>\` passing instead of a verifier. Both compare committed HEAD.
30
+ A behaviour-preserving cleanup PR shows \`antelopejs-api-diff <base-ref>\` passing. Published declarations and built runtime exports stay unchanged; pass \`--allow-added <glob>\` (repeatable, e.g. \`'**/internal/**'\`) to let added entries under that glob pass when their module is \`@internal\`, and copy its "Added (allowed)" list. A comment-only PR shows \`antelopejs-comment-proof <base-ref>\` passing instead of a verifier. Both compare committed HEAD.
31
31
 
32
32
  Copy counts from the proof's base and HEAD table. Never type counts by hand. Keep the command and the committed head beside the copied output. Directive lines are not individual suppressed rules.
33
33
 
@@ -1,6 +1,6 @@
1
1
  import "./ceilings-BSw9p4YB.mjs";
2
2
  import { n as IGNORE_PATTERNS, t as AGENT_IGNORE_PATTERNS } from "./shared-CsXIMK3I.mjs";
3
- import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, symlinkSync } from "node:fs";
3
+ import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, symlinkSync } from "node:fs";
4
4
  import { dirname, join, matchesGlob, relative, resolve } from "node:path";
5
5
  import { execFileSync, spawnSync } from "node:child_process";
6
6
  import { tmpdir } from "node:os";
@@ -14,6 +14,89 @@ function runCli(main) {
14
14
  }
15
15
  }
16
16
  //#endregion
17
+ //#region src/guardrails/added-entries.ts
18
+ function createAddedPolicy(globs) {
19
+ return {
20
+ globs,
21
+ verdicts: /* @__PURE__ */ new Map(),
22
+ allowed: /* @__PURE__ */ new Map(),
23
+ problems: /* @__PURE__ */ new Set()
24
+ };
25
+ }
26
+ function entryKey(directory, subpath) {
27
+ return `${directory}\0${subpath}`;
28
+ }
29
+ function allowedByGlob(policy, subpath) {
30
+ return policy.globs.some((glob) => matchesGlob(subpath, glob));
31
+ }
32
+ /** Substitutes each export star in order with its capture, as the published target pattern did. */
33
+ function fillStars(pattern, captures, format = (capture) => capture) {
34
+ let index = 0;
35
+ return pattern.replaceAll("*", () => format(captures[index++] ?? captures[0] ?? ""));
36
+ }
37
+ const INTERNAL_TAG = /@internal\b/u;
38
+ const MODULE_TAG = /@(?:packageDocumentation|module|fileoverview)\b/u;
39
+ function exportedLocalNames(compiler, source) {
40
+ const names = /* @__PURE__ */ new Set();
41
+ for (const statement of source.statements) {
42
+ 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);
43
+ if (compiler.isExportAssignment(statement) && compiler.isIdentifier(statement.expression)) names.add(statement.expression.text);
44
+ }
45
+ return names;
46
+ }
47
+ function declaredNames(compiler, statement) {
48
+ if (compiler.isVariableStatement(statement)) return statement.declarationList.declarations.flatMap((declaration) => compiler.isIdentifier(declaration.name) ? [declaration.name.text] : []);
49
+ 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];
50
+ return [];
51
+ }
52
+ function isExportedDeclaration(compiler, statement, locals) {
53
+ if (compiler.isExportAssignment(statement)) return !compiler.isIdentifier(statement.expression);
54
+ if ((compiler.canHaveModifiers(statement) ? compiler.getModifiers(statement) : void 0)?.some((modifier) => modifier.kind === compiler.SyntaxKind.ExportKeyword)) return true;
55
+ return declaredNames(compiler, statement).some((name) => locals.has(name));
56
+ }
57
+ function hasInternalTag(compiler, statement) {
58
+ return compiler.getJSDocTags(statement).some((tag) => tag.tagName.text === "internal");
59
+ }
60
+ /** Whether a module's text carries `@internal` on the module (with `@packageDocumentation`, `@module` or `@fileoverview`) or on every exported declaration. */
61
+ function isInternalModule(compiler, text) {
62
+ const source = compiler.createSourceFile("module.ts", text, compiler.ScriptTarget.Latest, true);
63
+ 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;
64
+ const locals = exportedLocalNames(compiler, source);
65
+ const exported = source.statements.filter((statement) => isExportedDeclaration(compiler, statement, locals));
66
+ return exported.length > 0 && exported.every((statement) => hasInternalTag(compiler, statement));
67
+ }
68
+ /** Records why an allowed added entry is not internal, or `undefined` when its module is. */
69
+ function recordVerdict(policy, compiler, entry) {
70
+ const internal = isInternalModule(compiler, readFileSync(entry.module, "utf8"));
71
+ 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 */".`);
72
+ }
73
+ /** Lets matching, `@internal` additions through by removing them from the head output; returns how many files were removed. */
74
+ function applyAllowance(policy, base, head, remove) {
75
+ const existing = new Set(base.map(({ path }) => path));
76
+ let removed = 0;
77
+ for (const entry of head) {
78
+ if (existing.has(entry.path) || !allowedByGlob(policy, entry.subpath)) continue;
79
+ const key = entryKey(entry.directory, entry.subpath);
80
+ 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.`;
81
+ if (problem !== void 0) {
82
+ policy.problems.add(problem);
83
+ continue;
84
+ }
85
+ remove(entry.path);
86
+ removed += 1;
87
+ policy.allowed.set(key, {
88
+ directory: entry.directory,
89
+ subpath: entry.subpath
90
+ });
91
+ }
92
+ return removed;
93
+ }
94
+ /** The "Added (allowed)" list with its count, or the problems that kept additions from passing. */
95
+ function describeAllowance(policy) {
96
+ const lines = [...policy.allowed.values()].map(({ directory, subpath }) => ` ${directory}: ./${subpath}\n`).sort();
97
+ return `Added (allowed): ${lines.length}\n${lines.join("")}${[...policy.problems].map((problem) => `Not internal: ${problem}\n`).join("")}`;
98
+ }
99
+ //#endregion
17
100
  //#region src/guardrails/revisions.ts
18
101
  function trackedManifests(root) {
19
102
  return execFileSync("git", ["ls-files", "-z"], {
@@ -30,8 +113,8 @@ function linkDependencies(root, worktree) {
30
113
  if (existsSync(source) && existsSync(dirname(target)) && !existsSync(target)) symlinkSync(source, target, DIRECTORY_LINK);
31
114
  }
32
115
  }
33
- /** Compares isolated committed revisions and removes both worktrees even when compilation fails. */
34
- function compareRevisions(root, baseRef, label, emit) {
116
+ /** Compares isolated committed revisions and removes both worktrees even when compilation fails; a policy lets matching `@internal` additions through. */
117
+ function compareRevisions(root, baseRef, label, emit, policy) {
35
118
  const temporary = mkdtempSync(join(tmpdir(), "antelope-proof-"));
36
119
  const worktrees = [];
37
120
  const results = [];
@@ -73,6 +156,7 @@ function compareRevisions(root, baseRef, label, emit) {
73
156
  mkdirSync(output, { recursive: true });
74
157
  results.push(emit(worktree, output, join(temporary, "emit", side)));
75
158
  }
159
+ const allowedAdditions = policy === void 0 ? 0 : applyAllowance(policy, results[0].published ?? [], results[1].published ?? [], (path) => rmSync(join(temporary, "head", path), { force: true }));
76
160
  const diff = spawnSync("git", [
77
161
  "diff",
78
162
  "--no-index",
@@ -93,7 +177,7 @@ function compareRevisions(root, baseRef, label, emit) {
93
177
  const packages = new Set(results.flatMap((result) => result.packages)).size;
94
178
  return {
95
179
  different: diff.status === 1,
96
- output: diff.status === 1 ? `${label}: differences against ${baseRef} (committed HEAD).\n${diff.stdout}` : `${label}: ${packages} packages, ${results[1].entries} entries unchanged against ${baseRef} (committed HEAD).\n`
180
+ 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`
97
181
  };
98
182
  } finally {
99
183
  for (const worktree of worktrees.reverse()) execFileSync("git", [
@@ -295,4 +379,4 @@ function authoredSizes(root, files = gitFiles(root), staged = false) {
295
379
  return sizes;
296
380
  }
297
381
  //#endregion
298
- export { resolveRevision as a, revisionCounts as c, repositoryRoot as i, trackedManifests as l, gitFiles as n, DIRECTORY_LINK as o, repositoryPath as r, compareRevisions as s, authoredSizes as t, runCli as u };
382
+ export { resolveRevision as a, revisionCounts as c, createAddedPolicy as d, describeAllowance as f, runCli as h, repositoryRoot as i, trackedManifests as l, recordVerdict as m, gitFiles as n, DIRECTORY_LINK as o, fillStars as p, repositoryPath as r, compareRevisions as s, authoredSizes as t, allowedByGlob as u };
@@ -1,7 +1,7 @@
1
1
  import { a as formatCeilings, n as MAX_FILE_BYTES, o as isRetired, r as MEASURE_ENV, t as CEILINGS_FILE } from "./ceilings-BSw9p4YB.mjs";
2
2
  import { t as readCarriedCeilings } from "./renames-BGO4dWJ8.mjs";
3
- import { n as gitFiles, r as repositoryPath, t as authoredSizes } from "./files-jKlueTMd.mjs";
4
- import { n as sizeFailure } from "./size-BdYmv57u.mjs";
3
+ import { n as gitFiles, r as repositoryPath, t as authoredSizes } from "./files-CaMy-5ne.mjs";
4
+ import { n as sizeFailure } from "./size-DYVe2pXo.mjs";
5
5
  import { createRequire } from "node:module";
6
6
  import { existsSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { basename, dirname, join } from "node:path";
@@ -1,6 +1,6 @@
1
1
  import "./ceilings-BSw9p4YB.mjs";
2
2
  import { t as readCarriedCeilings } from "./renames-BGO4dWJ8.mjs";
3
- import { t as authoredSizes } from "./files-jKlueTMd.mjs";
3
+ import { t as authoredSizes } from "./files-CaMy-5ne.mjs";
4
4
  //#region src/guardrails/size.ts
5
5
  function sizeFailure(file, size, limit) {
6
6
  return `${file}: ${size} bytes, ${size - limit} bytes over the ${limit}-byte ceiling. Split by responsibility into sibling modules, one cohesive group of exports each; keep the original path re-exporting only if it is a public entry point. Split a test file by behaviour under test, one file per describe. Do not minify, strip whitespace, or move code under an excluded path to pass.`;
@@ -1,23 +1,67 @@
1
- import { l as trackedManifests } from "./files-jKlueTMd.mjs";
1
+ import { l as trackedManifests } from "./files-CaMy-5ne.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join, matchesGlob, relative, resolve, sep } from "node:path";
5
5
  //#region src/guardrails/typescript.ts
6
- function packagesAt(root, publishedOnly) {
6
+ /** A proof analyses only packages that publish something: not private, and declaring at least one of `exports`, `main`, `types`, `typings` or `typesVersions`. */
7
+ function unpublishedReason(manifest) {
8
+ if (manifest.private === true) return "private";
9
+ return [
10
+ manifest.exports,
11
+ manifest.main,
12
+ manifest.types,
13
+ manifest.typings,
14
+ manifest.typesVersions
15
+ ].some((field) => field != null) ? void 0 : "no exports, main or types";
16
+ }
17
+ function trackedPackages(root) {
7
18
  return trackedManifests(root).flatMap((file) => {
8
19
  const directory = dirname(file);
9
20
  if (!existsSync(join(root, directory, "tsconfig.json"))) return [];
10
- const manifest = JSON.parse(readFileSync(join(root, file), "utf8"));
11
- if (publishedOnly && manifest.private === true) return [];
12
21
  return [{
13
22
  directory,
14
- manifest
23
+ manifest: JSON.parse(readFileSync(join(root, file), "utf8"))
24
+ }];
25
+ });
26
+ }
27
+ function packagesAt(root, publishedOnly) {
28
+ return trackedPackages(root).filter(({ manifest }) => !publishedOnly || unpublishedReason(manifest) === void 0);
29
+ }
30
+ /** The packages a published-only proof leaves out, each with the reason, so a skip is reported rather than silent. */
31
+ function unpublishedAt(root) {
32
+ return trackedPackages(root).flatMap(({ directory, manifest }) => {
33
+ const reason = unpublishedReason(manifest);
34
+ return reason === void 0 ? [] : [{
35
+ directory,
36
+ reason
15
37
  }];
16
38
  });
17
39
  }
18
- /** Loads the consumer's compiler, including a package-local installation in a workspace. */
40
+ function packageRoot(file) {
41
+ let directory = dirname(file);
42
+ while (!existsSync(join(directory, "package.json"))) {
43
+ const parent = dirname(directory);
44
+ if (parent === directory) return dirname(file);
45
+ directory = parent;
46
+ }
47
+ return directory;
48
+ }
49
+ /** Loads the compiler a package builds with, including a package-local installation in a workspace, falling back to the one `dts-bundle-generator` brings. A TypeScript without the programmatic API (7 and later) is an error rather than a crash. */
19
50
  function loadTypeScript(directory) {
20
- return createRequire(join(directory, "package.json"))("typescript");
51
+ const own = createRequire(import.meta.url);
52
+ let file;
53
+ try {
54
+ file = createRequire(join(directory, "package.json")).resolve("typescript");
55
+ } catch {
56
+ file = createRequire(own.resolve("dts-bundle-generator")).resolve("typescript");
57
+ }
58
+ const compiler = createRequire(file)("typescript");
59
+ const root = packageRoot(file);
60
+ 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.`);
61
+ return {
62
+ compiler,
63
+ root
64
+ };
21
65
  }
22
66
  const TEST_SOURCE_GLOBS = [
23
67
  "**/*.test.*",
@@ -58,13 +102,14 @@ function copyDeclarations(program, directory, output) {
58
102
  return files;
59
103
  }
60
104
  function parseConfig(directory) {
61
- const compiler = loadTypeScript(directory);
105
+ const { compiler, root } = loadTypeScript(directory);
62
106
  const config = compiler.readConfigFile(join(directory, "tsconfig.json"), compiler.sys.readFile);
63
107
  if (config.error) failDiagnostics(compiler, [config.error]);
64
108
  const parsed = compiler.parseJsonConfigFileContent(config.config, compiler.sys, directory);
65
109
  failDiagnostics(compiler, parsed.errors);
66
110
  return {
67
111
  compiler,
112
+ root,
68
113
  parsed
69
114
  };
70
115
  }
@@ -72,9 +117,9 @@ function parseConfig(directory) {
72
117
  function outputRoot(directory) {
73
118
  return resolve(directory, parseConfig(directory).parsed.options.outDir ?? ".");
74
119
  }
75
- /** Emits with the package's compiler and config; test roots and outputs never enter either proof. */
120
+ /** 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. */
76
121
  function emitPackage(directory, output, declarations) {
77
- const { compiler, parsed } = parseConfig(directory);
122
+ const { compiler, root, parsed } = parseConfig(directory);
78
123
  const options = {
79
124
  ...parsed.options,
80
125
  rootDir: parsed.options.rootDir ?? (parsed.options.outDir ? void 0 : directory),
@@ -101,20 +146,24 @@ function emitPackage(directory, output, declarations) {
101
146
  });
102
147
  if (declarations) failDiagnostics(compiler, compiler.getPreEmitDiagnostics(program));
103
148
  const files = [];
149
+ const modules = /* @__PURE__ */ new Map();
104
150
  const result = program.emit(void 0, (file, text, _bom, _onError, sources) => {
105
151
  if (sources?.some((source) => isTestSource(directory, source.fileName))) return;
106
152
  if (declarations ? !/\.d\.[cm]?ts$/.test(file) : !/\.[cm]?jsx?$/.test(file)) return;
107
153
  mkdirSync(dirname(file), { recursive: true });
108
154
  writeFileSync(file, text);
109
155
  files.push(file);
156
+ if (sources?.[0] !== void 0) modules.set(resolve(file), sources[0].fileName);
110
157
  });
111
158
  if (declarations) failDiagnostics(compiler, result.diagnostics);
112
159
  if (declarations) files.push(...copyDeclarations(program, directory, output));
113
160
  return {
114
161
  compiler,
162
+ compilerRoot: root,
115
163
  files,
164
+ modules,
116
165
  options: parsed.options
117
166
  };
118
167
  }
119
168
  //#endregion
120
- export { packagesAt as i, isTestSource as n, outputRoot as r, emitPackage as t };
169
+ export { unpublishedAt as a, packagesAt as i, isTestSource as n, outputRoot as r, emitPackage as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@antelopejs/tooling-configs",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
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",