@antelopejs/tooling-configs 0.5.3 → 0.5.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.
@@ -1,5 +1,5 @@
1
1
  import { t as CEILINGS_FILE } from "./ceilings-B7KayYIG.mjs";
2
- import { o as packageManager, s as parseManifest } from "./package-DiaBP7bI.mjs";
2
+ import { o as packageManager, s as parseManifest } from "./package-DnxZ2CXZ.mjs";
3
3
  import { a as gitFiles } from "./files-DJ0TeaTU.mjs";
4
4
  import { t as accepting } from "./ports-DGP6bPJy.mjs";
5
5
  import { createRequire } from "node:module";
@@ -11,981 +11,1095 @@ import ts from "typescript";
11
11
  import { createHash } from "node:crypto";
12
12
  import { tmpdir } from "node:os";
13
13
  import { minimatch } from "minimatch";
14
- //#region src/guardrails/run-command.ts
15
- const KILL_GRACE_MS = 5e3;
16
- function stopGroup(child, signal) {
17
- if (child.pid === void 0 || child.exitCode !== null) return;
18
- try {
19
- if (process.platform === "win32") child.kill(signal);
20
- else process.kill(-child.pid, signal);
21
- } catch {
22
- child.kill(signal);
23
- }
14
+ //#region src/guardrails/marker-block.ts
15
+ /** The comment pair sync writes a generated block between. */
16
+ function markers(name) {
17
+ return {
18
+ name,
19
+ start: `<!-- ${name}:start -->`,
20
+ end: `<!-- ${name}:end -->`
21
+ };
24
22
  }
25
- /**
26
- * Runs `command` in its own process group and collects stdout and stderr together. When `signal` aborts, the group
27
- * gets SIGTERM, then SIGKILL after a grace period, so a step's own children stop with it. On Windows the command runs
28
- * through a shell, so `npm` and `pnpm` resolve to their `.cmd` shims, unless `shell` is `false`: pass that for an
29
- * executable path and arguments that a shell must not split, such as paths with spaces.
30
- */
31
- function runCommand(command, args, options) {
32
- const { cwd, env = process.env, signal, shell = process.platform === "win32" } = options;
33
- return new Promise((resolve) => {
34
- const child = spawn(command, args, {
35
- cwd,
36
- env,
37
- shell,
38
- detached: process.platform !== "win32",
39
- stdio: [
40
- "ignore",
41
- "pipe",
42
- "pipe"
43
- ]
44
- });
45
- const chunks = [];
46
- const stdout = [];
47
- child.stdout.on("data", (chunk) => {
48
- chunks.push(chunk);
49
- stdout.push(chunk);
50
- });
51
- child.stderr.on("data", (chunk) => chunks.push(chunk));
52
- const interrupt = () => {
53
- stopGroup(child, "SIGTERM");
54
- setTimeout(() => stopGroup(child, "SIGKILL"), KILL_GRACE_MS).unref();
55
- };
56
- if (signal?.aborted) interrupt();
57
- else signal?.addEventListener("abort", interrupt, { once: true });
58
- child.once("error", (error) => {
59
- signal?.removeEventListener("abort", interrupt);
60
- resolve({
61
- status: null,
62
- stdout: "",
63
- output: `${error.message}\n`
64
- });
65
- });
66
- child.once("close", (code, killed) => {
67
- signal?.removeEventListener("abort", interrupt);
68
- const text = Buffer.concat(chunks).toString("utf8");
69
- resolve({
70
- status: code,
71
- stdout: Buffer.concat(stdout).toString("utf8"),
72
- output: `${text}${killed ? `Terminated by ${killed}\n` : ""}`
73
- });
74
- });
75
- });
23
+ /** The README with `block` between its markers. A README without markers comes back as it is. */
24
+ function placeMarkedBlock(current, { name, start, end }, block) {
25
+ const starts = current.split(start).length - 1;
26
+ const ends = current.split(end).length - 1;
27
+ if (starts === 0 && ends === 0) return current;
28
+ const from = current.indexOf(start);
29
+ const to = current.indexOf(end);
30
+ if (starts !== 1 || ends !== 1 || to < from) throw new Error(`invalid ${name} markers: a README holds exactly one start marker followed by one end marker. Repair or delete them, then rerun antelopejs-sync.`);
31
+ return `${current.slice(0, from)}${block}${current.slice(to + end.length).replace(/^\r?\n/, "")}`;
76
32
  }
77
33
  //#endregion
78
- //#region src/guardrails/git-identity.ts
79
- /** Config scopes stored inside the repository, which every checkout and agent sharing it commits under. */
80
- const SHARED_SCOPES = /* @__PURE__ */ new Set(["local", "worktree"]);
81
- /** Whether `root` is a git checkout, a `.git` folder or a linked worktree's `.git` file. */
82
- function isGitCheckout(root) {
83
- return existsSync(join(root, ".git"));
84
- }
85
- /**
86
- * Fails when the repository's own git config, its `.git/config` shared by every worktree or a worktree's
87
- * `config.worktree`, sets `user.name` or `user.email`: whoever commits in any checkout of it then signs as that identity.
88
- * Global, system and command-line settings pass. Returns what failed, naming each file and value, empty when it passed.
89
- */
90
- async function checkGitIdentity(root, signal) {
91
- const result = await runCommand("git", [
92
- "config",
93
- "--show-scope",
94
- "--show-origin",
95
- "--get-regexp",
96
- String.raw`^user\.(name|email)$`
97
- ], {
98
- cwd: root,
99
- signal,
100
- shell: false
101
- });
102
- if (result.status === 1) return "";
103
- if (result.status !== 0) return result.output;
104
- const shared = result.stdout.split("\n").filter((line) => SHARED_SCOPES.has(line.split(" ")[0] ?? ""));
105
- if (!shared.length) return "";
106
- return `The repository's git config sets a commit identity, so every checkout and agent sharing it commits as that identity:\n${shared.map((line) => ` ${line.split(" ").slice(1).join(" ")}\n`).join("")}Remove it with git config --local --unset-all user.name and git config --local --unset-all user.email (--worktree for a config.worktree), and set an identity with --global or per command with git -c.\n`;
34
+ //#region src/guardrails/markdown-table.ts
35
+ /** The lines of a Markdown table whose first row is the header, columns padded as oxfmt leaves them. */
36
+ function tableLines(table) {
37
+ const widths = table[0].map((_, column) => Math.max(3, ...table.map((row) => row[column].length)));
38
+ const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
39
+ return [
40
+ line(table[0]),
41
+ line(widths.map((width) => "-".repeat(width))),
42
+ ...table.slice(1).map(line)
43
+ ];
107
44
  }
108
45
  //#endregion
109
- //#region src/guardrails/services.ts
110
- /** The compose file the shared CI starts through its `services-compose-file` input, relative to the repository root. */
111
- const COMPOSE_FILE = ".github/compose.yml";
112
- function shortPort(text) {
113
- const parts = text.replace(/\/\w+$/, "").split(":");
114
- return parts.length < 2 ? void 0 : wholePort(parts.at(-2));
115
- }
116
- function wholePort(text) {
117
- return text !== void 0 && /^\d+$/.test(text) ? Number(text) : void 0;
118
- }
119
- /**
120
- * The host ports the compose file publishes, or `undefined` when a service publishes none or one this cannot read
121
- * (a range, an interpolation, a container-only port), since such a service cannot be probed.
122
- */
123
- function publishedPorts(text) {
124
- const services = parseDocument(text).get("services");
125
- if (!isMap(services) || services.items.length === 0) return void 0;
126
- const ports = [];
127
- for (const { value } of services.items) {
128
- const entries = isMap(value) ? value.get("ports") : void 0;
129
- if (!isSeq(entries) || entries.items.length === 0) return void 0;
130
- for (const entry of entries.items) {
131
- const published = isMap(entry) ? entry.get("published") : void 0;
132
- const port = isScalar(entry) ? shortPort(String(entry.value)) : wholePort(published === void 0 ? void 0 : String(published));
133
- if (port === void 0) return void 0;
134
- ports.push(port);
135
- }
46
+ //#region src/guardrails/docs-framework-modules.ts
47
+ const FRAMEWORK_MODULES = markers("antelopejs-framework-modules");
48
+ const FRAMEWORK_MODULES_START = FRAMEWORK_MODULES.start;
49
+ const FRAMEWORK_MODULES_END = FRAMEWORK_MODULES.end;
50
+ const ORGANIZATION$1 = "https://github.com/AntelopeJS";
51
+ const SCOPE$1 = "@antelopejs/";
52
+ /** The framework areas in display order. Every README holding the markers lists exactly these. */
53
+ const AREAS = [
54
+ {
55
+ area: "API",
56
+ contracts: [
57
+ "interface-api",
58
+ "interface-api-util",
59
+ "interface-data-api"
60
+ ],
61
+ providers: ["api"]
62
+ },
63
+ {
64
+ area: "Auth",
65
+ contracts: ["interface-auth"],
66
+ providers: ["auth-jwt"]
67
+ },
68
+ {
69
+ area: "Database",
70
+ contracts: [
71
+ "interface-database",
72
+ "interface-database-decorators",
73
+ "interface-database-catalog",
74
+ "interface-mongodb",
75
+ "interface-rethinkdb"
76
+ ],
77
+ providers: [
78
+ "postgres",
79
+ "mongodb",
80
+ "rethinkdb"
81
+ ]
82
+ },
83
+ {
84
+ area: "Redis",
85
+ contracts: ["interface-redis", "interface-redis-scheduler"],
86
+ providers: ["redis"]
87
+ },
88
+ {
89
+ area: "Email",
90
+ contracts: ["interface-email"],
91
+ providers: ["nodemailer", "brevo"]
92
+ },
93
+ {
94
+ area: "File storage",
95
+ contracts: ["interface-file-storage"],
96
+ providers: ["file-storage-local", "file-storage-s3"]
97
+ },
98
+ {
99
+ area: "Payments",
100
+ contracts: [
101
+ "interface-payment",
102
+ "interface-subscriptions",
103
+ "interface-stripe"
104
+ ],
105
+ providers: [
106
+ "stripe",
107
+ "mollie",
108
+ "checkout-com",
109
+ "payment-subscriptions"
110
+ ]
136
111
  }
137
- return ports;
112
+ ];
113
+ function cell(repos, current) {
114
+ return repos.map((repo) => repo === current ? `**\`${repo}\`**` : `[\`${repo}\`](${ORGANIZATION$1}/${repo})`).join(" · ");
138
115
  }
139
- /**
140
- * The environment compose runs in. A project named by `COMPOSE_PROJECT_NAME` or by the compose file's own `name:` is
141
- * kept; otherwise the project is named after the repository root, since compose would name every repository's project
142
- * `github` after the compose file's directory and a run could adopt or remove another checkout's containers.
143
- */
144
- function composeEnv(root) {
145
- if (process.env.COMPOSE_PROJECT_NAME) return process.env;
146
- if (parseDocument(readFileSync(join(root, COMPOSE_FILE), "utf8")).has("name")) return process.env;
147
- const slug = basename(root).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "");
148
- const digest = createHash("sha256").update(root).digest("hex").slice(0, 8);
149
- return {
150
- ...process.env,
151
- COMPOSE_PROJECT_NAME: `${slug || "repo"}-${digest}`
152
- };
116
+ /** The generated block, the README's own repository in bold, formatted as oxfmt leaves it. */
117
+ function frameworkModulesBlock(current) {
118
+ return [
119
+ FRAMEWORK_MODULES_START,
120
+ "",
121
+ ...tableLines([[
122
+ "Area",
123
+ "Contracts",
124
+ "Providers"
125
+ ], ...AREAS.map(({ area, contracts, providers }) => [
126
+ area,
127
+ cell(contracts, current),
128
+ cell(providers, current)
129
+ ])]),
130
+ "",
131
+ FRAMEWORK_MODULES_END,
132
+ ""
133
+ ].join("\n");
153
134
  }
154
- async function compose(root, args, signal) {
155
- const result = await runCommand("docker", [
156
- "compose",
157
- "-f",
158
- COMPOSE_FILE,
159
- ...args
160
- ], {
161
- cwd: root,
162
- env: composeEnv(root),
163
- signal
164
- });
165
- if (result.status === 0) return {
166
- failure: "",
167
- stdout: result.stdout
168
- };
169
- const outcome = result.status === null ? "did not finish" : `exited with status ${result.status}`;
170
- return {
171
- failure: `${result.output}docker compose -f ${COMPOSE_FILE} ${args.join(" ")}: ${outcome}\n`,
172
- stdout: result.stdout
173
- };
135
+ /** The repository a package lives in: its name without the `@antelopejs/` scope, as every framework package is named. */
136
+ function frameworkRepo(packageName) {
137
+ return packageName?.startsWith(SCOPE$1) ? packageName.slice(12) : void 0;
174
138
  }
175
- /**
176
- * Decides whether the checks start the services of `.github/compose.yml`: not when the file is absent or every port
177
- * it publishes already accepts connections, and fail at once when Docker Compose cannot run, because the
178
- * tests that need those services would wait for them forever.
179
- */
180
- async function planServices(root) {
181
- if (!existsSync(join(root, COMPOSE_FILE))) return { kind: "none" };
182
- const ports = publishedPorts(readFileSync(join(root, COMPOSE_FILE), "utf8"));
183
- if (ports && (await Promise.all(ports.map(accepting))).every(Boolean)) return { kind: "none" };
184
- const probe = await compose(root, ["version"]);
185
- if (!probe.failure) return { kind: "start" };
186
- return {
187
- kind: "unavailable",
188
- output: `Docker Compose is not available, so the services in ${COMPOSE_FILE} cannot start and the tests that need them would hang. Start Docker, start the services yourself, or pass --no-services.\n${probe.failure}`
189
- };
139
+ /** The README with the block between its markers rewritten for the package named `packageName`. A README without markers comes back as it is. */
140
+ function placeFrameworkModulesBlock(current, packageName) {
141
+ return placeMarkedBlock(current, FRAMEWORK_MODULES, frameworkModulesBlock(frameworkRepo(packageName)));
190
142
  }
191
- /**
192
- * Runs `docker compose up -d --wait` on the compose file, stopping it when `signal` aborts. `failure` is empty on
193
- * success; `owned` is true when the project had no container before, so the run may remove it afterwards without
194
- * taking a stack the developer started.
195
- */
196
- async function startServices(root, signal) {
197
- const before = await compose(root, [
198
- "ps",
199
- "--all",
200
- "--quiet"
201
- ], signal);
202
- if (before.failure) return {
203
- failure: before.failure,
204
- owned: false
205
- };
206
- const owned = before.stdout.trim() === "";
207
- return {
208
- failure: (await compose(root, [
209
- "up",
210
- "-d",
211
- "--wait"
212
- ], signal)).failure,
213
- owned
214
- };
143
+ //#endregion
144
+ //#region src/guardrails/docs-modules.ts
145
+ const DMS_MODULES = markers("antelopejs-dms-modules");
146
+ const DMS_MODULES_START = DMS_MODULES.start;
147
+ const DMS_MODULES_END = DMS_MODULES.end;
148
+ const ORGANIZATION = "https://github.com/AntelopeJS";
149
+ /** The AntelopeJS DMS modules in display order. Every README holding the markers lists exactly these. */
150
+ const MODULES = [
151
+ {
152
+ repo: "dms-builder",
153
+ row: "Edit pages, tables and data sources by clicking, as TypeScript that compiles"
154
+ },
155
+ {
156
+ repo: "dms-ai",
157
+ row: "An assistant chat in the dashboard, on your own Claude Code or Codex"
158
+ },
159
+ {
160
+ repo: "dms-database",
161
+ row: "Schemas, relation diagrams, a data browser and a query console"
162
+ },
163
+ {
164
+ repo: "dms-api",
165
+ row: "API health, request logs, per-route statistics and a request tester"
166
+ },
167
+ {
168
+ repo: "dms-automation",
169
+ row: "Node-graph automations on schedules, webhooks and DMS events, with a trace for every run"
170
+ },
171
+ {
172
+ repo: "dms-mailing",
173
+ row: "E-mail templates in a block editor, versions, a send log and delivery metrics"
174
+ },
175
+ {
176
+ repo: "dms-lang",
177
+ row: "Translation coverage, a translation matrix and a translation queue"
178
+ },
179
+ {
180
+ repo: "dms-media",
181
+ row: "A media library with folders, per-folder permissions, image sizes and light editing"
182
+ },
183
+ {
184
+ repo: "dms-saas",
185
+ row: "Self-service sign-up, plans that gate features, and Stripe billing"
186
+ },
187
+ {
188
+ repo: "dms-marketing",
189
+ row: "Traffic, conversion funnels with A/B splits and click heatmaps, without cookies"
190
+ },
191
+ {
192
+ repo: "dms-frontend",
193
+ row: "The `ajs dms` CLI, the Vue renderer and the SDK every frontend module builds on"
194
+ }
195
+ ];
196
+ /** The generated block, formatted as oxfmt leaves it. */
197
+ function modulesBlock() {
198
+ return [
199
+ DMS_MODULES_START,
200
+ "",
201
+ ...tableLines([["Module", "What it adds"], ...MODULES.map(({ repo, row }) => [`[\`${repo}\`](${ORGANIZATION}/${repo})`, row])]),
202
+ "",
203
+ DMS_MODULES_END,
204
+ ""
205
+ ].join("\n");
215
206
  }
216
- /** Runs `docker compose down -v` on the compose file; returns the failure output, empty on success. */
217
- async function stopServices(root) {
218
- return (await compose(root, ["down", "-v"])).failure;
207
+ /** The README with the block between its markers rewritten. A README without markers comes back as it is. */
208
+ function placeModulesBlock(current) {
209
+ return placeMarkedBlock(current, DMS_MODULES, modulesBlock());
219
210
  }
220
211
  //#endregion
221
- //#region src/guardrails/verify-layers.ts
222
- const SKILLS_FOLDER = ".agents/skills";
223
- const LAYER_PREFIX = "verify-";
224
- const TSCONFIG = "tsconfig.json";
225
- /** Folders of a layer that are not the layer's own code: verify builds its playground with the playground's own tsconfig. */
226
- const NOT_LAYER_CODE = /* @__PURE__ */ new Set(["node_modules", "dist"]);
227
- const LAYER_PLAYGROUND = "playground";
228
- const VERIFY_CONFIG = "verify.config.ts";
229
- /**
230
- * Options the generated config sets over the layer's: nothing is emitted, and each declaration or build-cache option the
231
- * layer may inherit is unset with `null`, so no `.tsbuildinfo` is written, no option is left needing `declaration` or
232
- * `composite`, and the declaration checks of files that are never emitted are not run.
233
- */
234
- const NO_OUTPUT = {
235
- noEmit: true,
236
- declaration: null,
237
- composite: null,
238
- incremental: null,
239
- tsBuildInfoFile: null,
240
- declarationDir: null,
241
- declarationMap: null,
242
- emitDeclarationOnly: null,
243
- isolatedDeclarations: null
244
- };
245
- /** The verify layers of a repository, relative to its root: each `.agents/skills/verify-*` folder that holds a `tsconfig.json` or a `verify.config.ts`. */
246
- function verifyLayers(root) {
247
- const skills = join(root, SKILLS_FOLDER);
248
- if (!existsSync(skills)) return [];
249
- return readdirSync(skills, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.startsWith(LAYER_PREFIX) && [TSCONFIG, VERIFY_CONFIG].some((file) => existsSync(join(skills, entry.name, file)))).map((entry) => `${SKILLS_FOLDER}/${entry.name}`).sort();
212
+ //#region src/guardrails/docs-compat.ts
213
+ const DOCS_COMPAT_START = "<!-- antelopejs-docs-compat:start -->";
214
+ const DOCS_COMPAT_END = "<!-- antelopejs-docs-compat:end -->";
215
+ const DOCS_NODE_START = "<!-- antelopejs-docs-node:start -->";
216
+ const DOCS_NODE_END = "<!-- antelopejs-docs-node:end -->";
217
+ const LOCKFILE = "pnpm-lock.yaml";
218
+ const REQUIREMENTS_HEADING = /^##\s+Requirements\s*$/i;
219
+ const SCOPE = "@antelopejs/";
220
+ const UNRESOLVED = "—";
221
+ const WORKSPACE = "workspace";
222
+ const LEGACY_MARKER = /^<!--\s*docs-compat:\s*\.\/package\.json#\w+\s*-->\s*$/;
223
+ const COMPATIBILITY_HEADING = /^##\s+Compatibility\s*$/i;
224
+ const RESOLVED_SECTIONS = [
225
+ "dependencies",
226
+ "optionalDependencies",
227
+ "devDependencies"
228
+ ];
229
+ /** The generated block, rows sorted by package name, formatted as oxfmt leaves it. */
230
+ function compatBlock(rows) {
231
+ const sorted = [...rows].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
232
+ return [
233
+ DOCS_COMPAT_START,
234
+ "",
235
+ ...tableLines([[
236
+ "Package",
237
+ "Supported",
238
+ "Tested with"
239
+ ], ...sorted.map(({ name, supported, tested }) => [
240
+ `\`${name}\``,
241
+ `\`${supported.replaceAll("|", "\\|")}\``,
242
+ tested === void 0 ? UNRESOLVED : `\`${tested}\``
243
+ ])]),
244
+ "",
245
+ DOCS_COMPAT_END,
246
+ ""
247
+ ].join("\n");
250
248
  }
251
- /** Whether a file the layer's tsconfig includes is the layer's own code, not its playground, a dependency or a build output. */
252
- function isLayerCode(layer, file) {
253
- const segments = relative(layer, file).split(sep);
254
- return segments[0] !== LAYER_PLAYGROUND && !segments.some((segment) => NOT_LAYER_CODE.has(segment));
249
+ function legacySpanEnd(lines, marker) {
250
+ let index = marker + 1;
251
+ while (index < lines.length && !lines[index].trim()) index++;
252
+ while (index < lines.length && lines[index].trimStart().startsWith("|")) index++;
253
+ while (index < lines.length && !lines[index].trim()) index++;
254
+ return index;
255
255
  }
256
- /**
257
- * The repository's own `tsc` entry, run with Node so no shell parses its path. It is found through the `bin.tsc` field of
258
- * `typescript/package.json`, a subpath every TypeScript version exports, because TypeScript 7 declares an `exports` map that
259
- * leaves `typescript/bin/tsc` out.
260
- */
261
- function compilerOf(root) {
262
- try {
263
- const manifestPath = createRequire(join(root, "package.json")).resolve("typescript/package.json");
264
- const tsc = parseManifest(readFileSync(manifestPath, "utf8")).bin?.tsc;
265
- return tsc === void 0 ? void 0 : join(dirname(manifestPath), tsc);
266
- } catch {
267
- return;
256
+ function replaceLegacyTables(lines, block) {
257
+ const placed = [];
258
+ let replaced = false;
259
+ for (let index = 0; index < lines.length;) {
260
+ if (!LEGACY_MARKER.test(lines[index])) {
261
+ placed.push(lines[index]);
262
+ index++;
263
+ continue;
264
+ }
265
+ if (!replaced) placed.push(...block.split("\n"));
266
+ replaced = true;
267
+ index = legacySpanEnd(lines, index);
268
268
  }
269
+ return replaced ? placed : void 0;
269
270
  }
270
- async function typecheckLayer(root, compiler, layer, signal) {
271
- const configPath = join(root, layer, TSCONFIG);
272
- if (!existsSync(configPath)) return `${layer}: has a verify.config.ts and no tsconfig.json. Add a tsconfig.json that includes its TypeScript files; antelopejs-sync writes one for the shared kinds.\n`;
273
- const ts = (await import("typescript")).default;
274
- const parsed = ts.getParsedCommandLineOfConfigFile(configPath, void 0, {
275
- ...ts.sys,
276
- onUnRecoverableConfigFileDiagnostic: () => void 0
277
- });
278
- if (parsed === void 0) return `${layer}/${TSCONFIG}: could not read it.\n`;
279
- const verifyConfig = join(root, layer, VERIFY_CONFIG);
280
- if (existsSync(verifyConfig) && !parsed.fileNames.some((file) => resolve(file) === verifyConfig)) return `${layer}/${TSCONFIG}: does not include ${VERIFY_CONFIG}, so it is never type-checked. Add it to the tsconfig's "include" or "files".\n`;
281
- const files = parsed.fileNames.filter((file) => isLayerCode(join(root, layer), resolve(file)));
282
- if (files.length === 0) return "";
283
- const folder = mkdtempSync(join(tmpdir(), "antelopejs-verify-types-"));
284
- try {
285
- const generated = join(folder, TSCONFIG);
286
- writeFileSync(generated, JSON.stringify({
287
- extends: configPath,
288
- compilerOptions: {
289
- ...NO_OUTPUT,
290
- typeRoots: ts.getEffectiveTypeRoots(parsed.options, ts.sys)
291
- },
292
- files,
293
- include: []
294
- }));
295
- const result = await runCommand(process.execPath, [
296
- compiler,
297
- "-p",
298
- generated,
299
- "--pretty",
300
- "false"
301
- ], {
302
- cwd: root,
303
- env: {
304
- ...process.env,
305
- CI: "1"
306
- },
307
- signal,
308
- shell: false
309
- });
310
- return result.status === 0 ? "" : result.output;
311
- } finally {
312
- rmSync(folder, {
313
- recursive: true,
314
- force: true
315
- });
271
+ function finalNewline(text) {
272
+ return text.endsWith("\n") ? text : `${text}\n`;
273
+ }
274
+ /** The README with the block in place: replacing the markers, a legacy `docs-compat` table, or under `## Compatibility`. */
275
+ function placeCompatBlock(current, block) {
276
+ const text = current ?? "";
277
+ const start = text.indexOf(DOCS_COMPAT_START);
278
+ const end = text.indexOf(DOCS_COMPAT_END);
279
+ if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-compat markers. Repair or delete them, then rerun antelopejs-sync.");
280
+ if (start !== -1) return `${text.slice(0, start)}${block}${text.slice(end + 35).replace(/^\r?\n/, "")}`;
281
+ const lines = text.split("\n");
282
+ const legacy = replaceLegacyTables(lines, block);
283
+ if (legacy) return finalNewline(legacy.join("\n"));
284
+ const heading = lines.findIndex((line) => COMPATIBILITY_HEADING.test(line));
285
+ if (heading !== -1) {
286
+ let rest = heading + 1;
287
+ while (rest < lines.length && !lines[rest].trim()) rest++;
288
+ return finalNewline([
289
+ ...lines.slice(0, heading + 1),
290
+ "",
291
+ ...block.split("\n"),
292
+ ...lines.slice(rest)
293
+ ].join("\n"));
294
+ }
295
+ const before = text.trimEnd();
296
+ return `${before}${before ? "\n\n" : ""}## Compatibility\n\n${block}`;
297
+ }
298
+ /** The generated Node prerequisite block for an `engines.node` range, formatted as oxfmt leaves it. */
299
+ function nodeBlock(range) {
300
+ return `${DOCS_NODE_START}\n\nThis package requires Node.js \`${range}\`.\n${DOCS_NODE_END}\n`;
301
+ }
302
+ /** The README with the Node block in place: between its markers, under `## Requirements`, or in a new `## Requirements` section at the end. */
303
+ function placeNodeBlock(current, block) {
304
+ const start = current.indexOf(DOCS_NODE_START);
305
+ const end = current.indexOf(DOCS_NODE_END);
306
+ if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-node markers. Repair or delete them, then rerun antelopejs-sync.");
307
+ if (start !== -1) return `${current.slice(0, start)}${block}${current.slice(end + 33).replace(/^\r?\n/, "")}`;
308
+ const lines = current.split("\n");
309
+ const heading = lines.findIndex((line) => REQUIREMENTS_HEADING.test(line));
310
+ if (heading !== -1) {
311
+ let rest = heading + 1;
312
+ while (rest < lines.length && !lines[rest].trim()) rest++;
313
+ return finalNewline([
314
+ ...lines.slice(0, heading + 1),
315
+ "",
316
+ ...block.trimEnd().split("\n"),
317
+ ...rest < lines.length ? ["", ...lines.slice(rest)] : []
318
+ ].join("\n"));
316
319
  }
320
+ return `${current.trimEnd()}\n\n## Requirements\n\n${block}`;
321
+ }
322
+ function relative$1(directory, name) {
323
+ return directory ? `${directory}/${name}` : name;
317
324
  }
318
- /**
319
- * Type-checks the own code of each verify layer with the repository's own TypeScript. The files are those the layer's
320
- * `tsconfig.json` includes, minus its `playground` folder, which verify compiles with the playground's own config after
321
- * installing it, and any `node_modules` or `dist` folder. A config generated in the system temp folder extends the layer's,
322
- * lists those files, turns off emit and unsets the emit and build-cache options in `NO_OUTPUT`, so nothing is written in the
323
- * repository and no package is fetched. A layer whose `tsconfig.json` does not include its `verify.config.ts` fails. Returns the compiler output of the layers that fail, empty when all pass.
324
- */
325
- async function typecheckLayers(root, signal) {
326
- const layers = verifyLayers(root);
327
- if (layers.length === 0) return "";
328
- const compiler = compilerOf(root);
329
- if (compiler === void 0) return "TypeScript is not installed in the repository root: run the package manager's install first.\n";
330
- return (await Promise.all(layers.map((layer) => typecheckLayer(root, compiler, layer, signal)))).join("");
325
+ function isDirectory(root, path) {
326
+ return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
331
327
  }
332
- //#endregion
333
- //#region src/guardrails/verify-lockfiles.ts
334
- /** The folder a repository's playground lives in; verify installs a fixture project from it. */
335
- const PLAYGROUND = "playground";
336
- const PNPM_LOCK$1 = "pnpm-lock.yaml";
337
- const NPM_LOCK = "package-lock.json";
338
- const MANIFEST = "package.json";
339
- const PNPM_WORKSPACE = "pnpm-workspace.yaml";
340
- /** Lockfiles this check does not compare, which still mean a folder is locked. */
341
- const OTHER_LOCKS = [
342
- "npm-shrinkwrap.json",
343
- "yarn.lock",
344
- "bun.lock",
345
- "bun.lockb"
346
- ];
347
- /** The manifest fields both package managers record as a project's direct dependencies. */
348
- const DIRECT_FIELDS = [
349
- "dependencies",
350
- "devDependencies",
351
- "optionalDependencies"
352
- ];
353
- /** A lockfile or manifest this check cannot read as a version it knows. */
354
- var Unreadable = class extends Error {};
355
- /** Parses a JSON or YAML file whose top level is a mapping; throws `Unreadable` otherwise. */
356
- function readMapping(path) {
357
- const document = parseDocument(readFileSync(path, "utf8"), {
358
- schema: "failsafe",
359
- uniqueKeys: false
360
- });
361
- const { contents } = document;
362
- if (document.errors.length > 0 || !isMap(contents)) throw new Unreadable(path);
363
- return contents;
328
+ function subdirectories(root, directory) {
329
+ return readdirSync(join(root, directory), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith(".")).map((entry) => relative$1(directory, entry.name));
364
330
  }
365
- /** The mapping under `key`; `undefined` when absent or not a mapping. */
366
- function mapping(map, key) {
367
- const value = map?.get(key, true);
368
- return isMap(value) ? value : void 0;
331
+ function descendants(root, directory) {
332
+ return subdirectories(root, directory).flatMap((child) => [child, ...descendants(root, child)]);
369
333
  }
370
- /** The source text of the scalar under `key`; `undefined` when absent or not a scalar. */
371
- function scalar(map, key) {
372
- const value = map?.get(key, true);
373
- return isScalar(value) ? String(value.value) : void 0;
334
+ function globExpression(pattern) {
335
+ const source = pattern.split("/").map((segment) => segment === "**" ? "(?:.*)" : segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*").replaceAll("?", "[^/]")).join("/").replaceAll("(?:.*)/", "(?:.*/)?");
336
+ return new RegExp(`^${source}$`);
374
337
  }
375
- /** The scalar keys of a mapping, in order; none when it is absent. */
376
- function keys(map) {
377
- return (map?.items ?? []).flatMap((pair) => isScalar(pair.key) ? [String(pair.key.value)] : []);
338
+ function expand(root, pattern) {
339
+ let directories = [""];
340
+ for (const segment of pattern.split("/")) if (segment === "**") directories = directories.flatMap((directory) => [directory, ...descendants(root, directory)]);
341
+ else if (/[*?]/.test(segment)) {
342
+ const expression = globExpression(segment);
343
+ directories = directories.flatMap((directory) => subdirectories(root, directory).filter((child) => expression.test(child.slice(child.lastIndexOf("/") + 1))));
344
+ } else directories = directories.map((directory) => relative$1(directory, segment)).filter((directory) => isDirectory(root, directory));
345
+ return directories;
378
346
  }
379
- /** Reads a project's direct dependencies, with `specifierOf` reading the specifier of one name from its field. */
380
- function directOf(node, specifierOf) {
381
- const direct = /* @__PURE__ */ new Map();
382
- for (const field of DIRECT_FIELDS) {
383
- const entries = mapping(node, field);
384
- for (const name of keys(entries)) {
385
- const specifier = specifierOf(entries, name);
386
- if (specifier === void 0) throw new Unreadable(name);
387
- direct.set(name, /* @__PURE__ */ new Set([...direct.get(name) ?? [], specifier]));
388
- }
389
- }
390
- return direct;
347
+ function normalizePattern(pattern) {
348
+ return pattern.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "");
391
349
  }
392
- /** A `package.json` or a `package-lock.json` root entry, where each name maps to its specifier. */
393
- function declared(node) {
394
- return directOf(node, scalar);
350
+ function scalarItems(document, path) {
351
+ const node = document.getIn(path, true);
352
+ return isSeq(node) ? node.items.flatMap((item) => isScalar(item) ? [String(item.value)] : []) : [];
395
353
  }
396
- /** A `pnpm-lock.yaml` importer, where each name maps to its `specifier` and resolved `version`. */
397
- function pnpmLocked(node) {
398
- return directOf(node, (field, name) => scalar(mapping(field, name), "specifier"));
354
+ /** pnpm-workspace.yaml `packages`, else package.json `workspaces` as an array or as `{ packages }`; JSON parses as YAML. */
355
+ function workspacePatterns(root) {
356
+ const pnpm = join(root, "pnpm-workspace.yaml");
357
+ if (existsSync(pnpm)) return scalarItems(parseDocument(readFileSync(pnpm, "utf8")), ["packages"]);
358
+ const manifest = parseDocument(readFileSync(join(root, "package.json"), "utf8"));
359
+ return scalarItems(manifest, isMap(manifest.get("workspaces", true)) ? ["workspaces", "packages"] : ["workspaces"]);
399
360
  }
400
- function listed(specifiers) {
401
- return specifiers === void 0 ? "none" : [...specifiers].map((specifier) => `"${specifier}"`).join(" or ");
361
+ /** The workspace package directories, relative to `root` and sorted, that `pnpm-workspace.yaml` or package.json `workspaces` list. */
362
+ function workspaceDirectories(root) {
363
+ const patterns = workspacePatterns(root);
364
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => globExpression(normalizePattern(pattern.slice(1))));
365
+ const found = /* @__PURE__ */ new Set();
366
+ for (const pattern of patterns.filter((item) => !item.startsWith("!"))) {
367
+ const normalized = normalizePattern(pattern);
368
+ for (const directory of normalized ? expand(root, normalized) : [""]) if (directory && !excluded.some((expression) => expression.test(directory)) && existsSync(join(root, directory, "package.json"))) found.add(directory);
369
+ }
370
+ return [...found].sort();
402
371
  }
403
- /**
404
- * The names whose specifiers differ between a manifest and what its lockfile records, in either direction. A name counts as
405
- * present whichever of the three fields records it, and matches when the two sides share a specifier. A name the lockfile
406
- * records and the manifest declares only as a peer passes, since the package manager may or may not install peers. `skip`
407
- * names the manifest entries the lockfile may leave out or record with another specifier.
408
- */
409
- function differences(manifest, locked, skip) {
410
- const wanted = declared(manifest);
411
- const peers = new Set(keys(mapping(manifest, "peerDependencies")));
412
- const line = (name) => `"${name}": package.json asks for ${listed(wanted.get(name))}, the lockfile has ${listed(locked.get(name))}.`;
413
- const stale = [...wanted].filter(([name, specifiers]) => ![...locked.get(name) ?? []].some((specifier) => specifiers.has(specifier)) && !skip(name, specifiers)).map(([name]) => line(name));
414
- const extra = [...locked.keys()].filter((name) => !wanted.has(name) && !peers.has(name)).map(line);
415
- return [...stale, ...extra].sort();
372
+ function declaredRanges(manifest) {
373
+ const ranges = /* @__PURE__ */ new Map();
374
+ for (const field of [
375
+ manifest.optionalDependencies,
376
+ manifest.dependencies,
377
+ manifest.peerDependencies
378
+ ]) for (const [name, range] of Object.entries(field ?? {})) if (name.startsWith(SCOPE)) ranges.set(name, range);
379
+ return ranges;
416
380
  }
417
- /** Every package name an override selector such as `foo`, `@scope/foo@^1` or `bar@1>foo@2` mentions, its target among them. */
418
- function overrideNames(selector) {
419
- return selector.split(">").flatMap((segment) => /^(?:@[^/@]+\/)?[^@]+/u.exec(segment) ?? []);
381
+ function readManifest(root, directory) {
382
+ return parseManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
420
383
  }
421
- function pnpmDifferences(path) {
422
- const lockfile = readMapping(join(path, PNPM_LOCK$1));
423
- if (Number(scalar(lockfile, "lockfileVersion") ?? "0") < 6) throw new Unreadable(path);
424
- const overridden = new Set(keys(mapping(lockfile, "overrides")).flatMap(overrideNames));
425
- const linksLeftOut = scalar(mapping(lockfile, "settings"), "excludeLinksFromLockfile") === "true";
426
- const skip = (name, specifiers) => overridden.has(name) || linksLeftOut && [...specifiers].every((specifier) => specifier.startsWith("link:"));
427
- const importers = mapping(lockfile, "importers");
428
- return (importers ? keys(importers) : ["."]).flatMap((importer) => {
429
- const manifest = join(path, importer, MANIFEST);
430
- if (!existsSync(manifest)) return [];
431
- const node = importers ? mapping(importers, importer) : lockfile;
432
- return differences(readMapping(manifest), pnpmLocked(node), skip).map((line) => `importer "${importer}" ${line}`);
433
- });
384
+ /** The version the lockfile resolves for a dependency; a `link:` resolves to `workspace`, so a release that bumps the linked package leaves this README unchanged. */
385
+ function resolvedVersion({ document, importer }, name) {
386
+ for (const section of RESOLVED_SECTIONS) {
387
+ const entry = document.getIn([
388
+ "importers",
389
+ importer,
390
+ section,
391
+ name
392
+ ], true);
393
+ const version = isMap(entry) ? entry.get("version", true) : entry;
394
+ if (!isScalar(version)) continue;
395
+ const resolved = String(version.value).split("(")[0];
396
+ return resolved.startsWith("link:") ? WORKSPACE : resolved;
397
+ }
434
398
  }
435
- function npmDifferences(path) {
436
- const lockfile = readMapping(join(path, NPM_LOCK));
437
- const rootEntry = mapping(mapping(lockfile, "packages"), "");
438
- if (Number(scalar(lockfile, "lockfileVersion") ?? "0") < 2 || rootEntry === void 0) throw new Unreadable(path);
439
- const manifest = join(path, MANIFEST);
440
- if (!existsSync(manifest)) return [];
441
- return differences(readMapping(manifest), declared(rootEntry), () => false);
399
+ const UNSHARED_NPMRC = /^\s*shared-workspace-lockfile\s*=\s*false\s*(?:[#;].*)?$/m;
400
+ /** Whether the workspace keeps one root lockfile, or `shared-workspace-lockfile=false` gives each package its own. */
401
+ function sharesLockfile(root) {
402
+ const npmrc = join(root, ".npmrc");
403
+ if (existsSync(npmrc) && UNSHARED_NPMRC.test(readFileSync(npmrc, "utf8"))) return false;
404
+ const workspace = join(root, "pnpm-workspace.yaml");
405
+ return !(existsSync(workspace) && parseDocument(readFileSync(workspace, "utf8")).get("sharedWorkspaceLockfile") === false);
442
406
  }
443
- function lockfileIn(path) {
444
- if (existsSync(join(path, PNPM_LOCK$1))) return PNPM_LOCK$1;
445
- if (existsSync(join(path, NPM_LOCK))) return NPM_LOCK;
446
- return OTHER_LOCKS.some((name) => existsSync(join(path, name))) ? "other" : void 0;
407
+ /** The lockfile path of a package, relative to the root. A shared lockfile is the root's, indexed by the package directory. */
408
+ function lockPath(shared, directory) {
409
+ return shared ? LOCKFILE : relative$1(directory, LOCKFILE);
447
410
  }
448
- /** Each folder at or under `folder`, `node_modules` and `dist` aside, that holds a lockfile. */
449
- function lockedFolders(root, folder) {
450
- const path = join(root, folder);
451
- if (!existsSync(path)) return [];
452
- const lockfile = lockfileIn(path);
453
- return [...lockfile === void 0 ? [] : [{
454
- folder,
455
- lockfile
456
- }], ...readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && entry.name !== "dist").flatMap((entry) => lockedFolders(root, `${folder}/${entry.name}`))];
411
+ function readLock(root, shared, directory, documents) {
412
+ const path = join(root, lockPath(shared, directory));
413
+ if (!documents.has(path) && existsSync(path)) documents.set(path, parseDocument(readFileSync(path, "utf8")));
414
+ const document = documents.get(path);
415
+ return document && {
416
+ document,
417
+ importer: shared ? directory || "." : "."
418
+ };
419
+ }
420
+ /** Adds one package's `docs-files` lines and, when it needs one, its README with the generated blocks. */
421
+ function planPackage(root, plan, lock, standard, { directory, name, ranges, published, node }) {
422
+ const readme = relative$1(directory, "README.md");
423
+ const docs = relative$1(directory, "docs");
424
+ if (!published) return;
425
+ if (ranges.size > 0 || existsSync(join(root, readme))) plan.docsFiles.push(readme);
426
+ if (isDirectory(root, docs)) plan.docsFiles.push(docs);
427
+ const current = existsSync(join(root, readme)) ? readFileSync(join(root, readme), "utf8") : void 0;
428
+ const nodeRange = standard && current !== void 0 ? node : void 0;
429
+ if (ranges.size === 0 && current === void 0) return;
430
+ const rows = [...ranges].map(([name, supported]) => ({
431
+ name,
432
+ supported,
433
+ tested: lock && resolvedVersion(lock, name)
434
+ }));
435
+ try {
436
+ const withRequirements = nodeRange !== void 0 && current !== void 0 ? placeNodeBlock(current, nodeBlock(nodeRange)) : current;
437
+ plan.readmes.push({
438
+ path: readme,
439
+ current,
440
+ content: placeFrameworkModulesBlock(placeModulesBlock(rows.length > 0 ? placeCompatBlock(withRequirements, compatBlock(rows)) : withRequirements ?? ""), name)
441
+ });
442
+ } catch (error) {
443
+ plan.errors.push(`${readme}: ${error instanceof Error ? error.message : String(error)}`);
444
+ }
445
+ }
446
+ /**
447
+ * Plans the docs-compat block of the root and of every workspace package that is not private and declares an
448
+ * `@antelopejs/*` peer, runtime or optional dependency, and the `docs-files` lines covering the root and every workspace
449
+ * package that is not private.
450
+ * Tested with comes from pnpm-lock.yaml, each package's own when `shared-workspace-lockfile=false`, and is `workspace` for a `link:` dependency; other package managers get a dash.
451
+ */
452
+ function planDocs(root, manager) {
453
+ const rootManifest = readManifest(root, "");
454
+ const packages = ["", ...workspaceDirectories(root)].map((directory) => {
455
+ const manifest = directory ? readManifest(root, directory) : rootManifest;
456
+ return {
457
+ directory,
458
+ name: manifest.name,
459
+ published: !directory || !manifest.private,
460
+ node: manifest.engines?.node,
461
+ ranges: manifest.private ? /* @__PURE__ */ new Map() : declaredRanges(manifest)
462
+ };
463
+ });
464
+ const qualifying = packages.filter(({ ranges }) => ranges.size > 0);
465
+ const plan = {
466
+ readmes: [],
467
+ docsFiles: [],
468
+ errors: [],
469
+ exists: (path) => existsSync(join(root, path))
470
+ };
471
+ const shared = sharesLockfile(root);
472
+ const documents = /* @__PURE__ */ new Map();
473
+ const locks = new Map(qualifying.map(({ directory }) => [directory, manager === "pnpm" ? readLock(root, shared, directory, documents) : void 0]));
474
+ const missing = manager === "pnpm" ? qualifying.filter(({ directory }) => !locks.get(directory)) : [];
475
+ if (missing.length) {
476
+ for (const path of new Set(missing.map(({ directory }) => lockPath(shared, directory)))) plan.errors.push(`${path} is missing, and the docs-compat block reads Tested with from it: run pnpm install, then rerun antelopejs-sync.`);
477
+ return plan;
478
+ }
479
+ const standard = rootManifest.antelopeJs?.docs?.standard === true;
480
+ for (const item of packages) planPackage(root, plan, locks.get(item.directory), standard, item);
481
+ return plan;
457
482
  }
458
- /** Whether a `package.json` declares a direct dependency; `false` when it is missing or cannot be read, so this check cannot tell. */
459
- function hasDependencies(path) {
483
+ //#endregion
484
+ //#region src/guardrails/run-command.ts
485
+ const KILL_GRACE_MS = 5e3;
486
+ function stopGroup(child, signal) {
487
+ if (child.pid === void 0 || child.exitCode !== null) return;
460
488
  try {
461
- if (!existsSync(path)) return false;
462
- const manifest = readMapping(path);
463
- return DIRECT_FIELDS.some((field) => keys(mapping(manifest, field)).length > 0);
464
- } catch (error) {
465
- if (error instanceof Unreadable) return false;
466
- throw error;
489
+ if (process.platform === "win32") child.kill(signal);
490
+ else process.kill(-child.pid, signal);
491
+ } catch {
492
+ child.kill(signal);
467
493
  }
468
494
  }
469
495
  /**
470
- * The folders this check reads, when a layer exists: each folder under a layer, `node_modules` and `dist` aside, and the
471
- * root `playground`, that holds a lockfile; and each layer's `playground` and the root `playground`, the folders verify
472
- * installs from, when its `package.json` has dependencies and it holds no lockfile.
496
+ * Runs `command` in its own process group and collects stdout and stderr together. When `signal` aborts, the group
497
+ * gets SIGTERM, then SIGKILL after a grace period, so a step's own children stop with it. On Windows the command runs
498
+ * through a shell, so `npm` and `pnpm` resolve to their `.cmd` shims, unless `shell` is `false`: pass that for an
499
+ * executable path and arguments that a shell must not split, such as paths with spaces.
473
500
  */
474
- function verifyInstallFolders(root) {
475
- const layers = verifyLayers(root);
476
- if (layers.length === 0) return [];
477
- const playgrounds = [...layers.map((layer) => `${layer}/${PLAYGROUND}`), PLAYGROUND];
478
- const rootPlayground = lockfileIn(join(root, PLAYGROUND));
479
- return [
480
- ...layers.flatMap((layer) => lockedFolders(root, layer)),
481
- ...rootPlayground === void 0 ? [] : [{
482
- folder: PLAYGROUND,
483
- lockfile: rootPlayground
484
- }],
485
- ...playgrounds.filter((folder) => lockfileIn(join(root, folder)) === void 0 && hasDependencies(join(root, folder, MANIFEST))).map((folder) => ({
486
- folder,
487
- lockfile: void 0
488
- }))
489
- ];
490
- }
491
- /** The folders above `folder`, nearest first, up to the repository root. */
492
- function ancestors(folder) {
493
- const parent = posix.dirname(folder);
494
- return parent === folder ? [] : [parent, ...ancestors(parent)];
501
+ function runCommand(command, args, options) {
502
+ const { cwd, env = process.env, signal, shell = process.platform === "win32" } = options;
503
+ return new Promise((resolve) => {
504
+ const child = spawn(command, args, {
505
+ cwd,
506
+ env,
507
+ shell,
508
+ detached: process.platform !== "win32",
509
+ stdio: [
510
+ "ignore",
511
+ "pipe",
512
+ "pipe"
513
+ ]
514
+ });
515
+ const chunks = [];
516
+ const stdout = [];
517
+ child.stdout.on("data", (chunk) => {
518
+ chunks.push(chunk);
519
+ stdout.push(chunk);
520
+ });
521
+ child.stderr.on("data", (chunk) => chunks.push(chunk));
522
+ const interrupt = () => {
523
+ stopGroup(child, "SIGTERM");
524
+ setTimeout(() => stopGroup(child, "SIGKILL"), KILL_GRACE_MS).unref();
525
+ };
526
+ if (signal?.aborted) interrupt();
527
+ else signal?.addEventListener("abort", interrupt, { once: true });
528
+ child.once("error", (error) => {
529
+ signal?.removeEventListener("abort", interrupt);
530
+ resolve({
531
+ status: null,
532
+ stdout: "",
533
+ output: `${error.message}\n`
534
+ });
535
+ });
536
+ child.once("close", (code, killed) => {
537
+ signal?.removeEventListener("abort", interrupt);
538
+ const text = Buffer.concat(chunks).toString("utf8");
539
+ resolve({
540
+ status: code,
541
+ stdout: Buffer.concat(stdout).toString("utf8"),
542
+ output: `${text}${killed ? `Terminated by ${killed}\n` : ""}`
543
+ });
544
+ });
545
+ });
495
546
  }
496
- /** Whether a manifest declares workspaces, or cannot be read and so might. */
497
- function declaresWorkspaces(path) {
498
- try {
499
- return existsSync(path) && readMapping(path).has("workspaces");
500
- } catch (error) {
501
- if (error instanceof Unreadable) return true;
502
- throw error;
503
- }
547
+ //#endregion
548
+ //#region src/guardrails/git-identity.ts
549
+ /** Config scopes stored inside the repository, which every checkout and agent sharing it commits under. */
550
+ const SHARED_SCOPES = /* @__PURE__ */ new Set(["local", "worktree"]);
551
+ /** Whether `root` is a git checkout, a `.git` folder or a linked worktree's `.git` file. */
552
+ function isGitCheckout(root) {
553
+ return existsSync(join(root, ".git"));
504
554
  }
505
555
  /**
506
- * Whether a folder above `folder` holds a workspace that may list it, a `pnpm-workspace.yaml` or a `package.json` with
507
- * `workspaces`: its membership then follows patterns this check does not evaluate, and that workspace's lockfile may hold it.
556
+ * Fails when the repository's own git config, its `.git/config` shared by every worktree or a worktree's
557
+ * `config.worktree`, sets `user.name` or `user.email`: whoever commits in any checkout of it then signs as that identity.
558
+ * Global, system and command-line settings pass. Returns what failed, naming each file and value, empty when it passed.
508
559
  */
509
- function inWorkspace(root, folder) {
510
- return ancestors(folder).some((above) => existsSync(join(root, above, PNPM_WORKSPACE)) || declaresWorkspaces(join(root, above, MANIFEST)));
560
+ async function checkGitIdentity(root, signal) {
561
+ const result = await runCommand("git", [
562
+ "config",
563
+ "--show-scope",
564
+ "--show-origin",
565
+ "--get-regexp",
566
+ String.raw`^user\.(name|email)$`
567
+ ], {
568
+ cwd: root,
569
+ signal,
570
+ shell: false
571
+ });
572
+ if (result.status === 1) return "";
573
+ if (result.status !== 0) return result.output;
574
+ const shared = result.stdout.split("\n").filter((line) => SHARED_SCOPES.has(line.split(" ")[0] ?? ""));
575
+ if (!shared.length) return "";
576
+ return `The repository's git config sets a commit identity, so every checkout and agent sharing it commits as that identity:\n${shared.map((line) => ` ${line.split(" ").slice(1).join(" ")}\n`).join("")}Remove it with git config --local --unset-all user.name and git config --local --unset-all user.email (--worktree for a config.worktree), and set an identity with --global or per command with git -c.\n`;
511
577
  }
512
- function fixCommand(root, folder, lockfile) {
513
- if (lockfile === NPM_LOCK) return `npm install --package-lock-only --prefix ${folder}`;
514
- return existsSync(join(root, folder, PNPM_WORKSPACE)) ? `pnpm install --dir ${folder} --lockfile-only` : `pnpm install --dir ${folder} --ignore-workspace --lockfile-only`;
578
+ //#endregion
579
+ //#region src/guardrails/services.ts
580
+ /** The compose file the shared CI starts through its `services-compose-file` input, relative to the repository root. */
581
+ const COMPOSE_FILE = ".github/compose.yml";
582
+ function shortPort(text) {
583
+ const parts = text.replace(/\/\w+$/, "").split(":");
584
+ return parts.length < 2 ? void 0 : wholePort(parts.at(-2));
515
585
  }
516
- function unlocked(root, folder) {
517
- if (inWorkspace(root, folder)) return "";
518
- const manager = ancestors(folder).some((above) => existsSync(join(root, above, NPM_LOCK))) ? NPM_LOCK : PNPM_LOCK$1;
519
- return `${folder}/${MANIFEST} has dependencies and no lockfile: run \`${fixCommand(root, folder, manager)}\`.\n`;
586
+ function wholePort(text) {
587
+ return text !== void 0 && /^\d+$/.test(text) ? Number(text) : void 0;
520
588
  }
521
- function checkFolder(root, { folder, lockfile }) {
522
- if (lockfile === "other") return "";
523
- try {
524
- if (lockfile === void 0) return unlocked(root, folder);
525
- const path = join(root, folder);
526
- const found = lockfile === PNPM_LOCK$1 ? pnpmDifferences(path) : npmDifferences(path);
527
- return found.length === 0 ? "" : `${folder}/${lockfile} does not match ${folder}/${MANIFEST}: run \`${fixCommand(root, folder, lockfile)}\`.\n${found.map((line) => ` ${line}\n`).join("")}`;
528
- } catch (error) {
529
- if (error instanceof Unreadable) return `${folder}/${lockfile ?? MANIFEST}: could not read it, or a ${MANIFEST} it locks, as a version this check knows.\n`;
530
- throw error;
589
+ /**
590
+ * The host ports the compose file publishes, or `undefined` when a service publishes none or one this cannot read
591
+ * (a range, an interpolation, a container-only port), since such a service cannot be probed.
592
+ */
593
+ function publishedPorts(text) {
594
+ const services = parseDocument(text).get("services");
595
+ if (!isMap(services) || services.items.length === 0) return void 0;
596
+ const ports = [];
597
+ for (const { value } of services.items) {
598
+ const entries = isMap(value) ? value.get("ports") : void 0;
599
+ if (!isSeq(entries) || entries.items.length === 0) return void 0;
600
+ for (const entry of entries.items) {
601
+ const published = isMap(entry) ? entry.get("published") : void 0;
602
+ const port = isScalar(entry) ? shortPort(String(entry.value)) : wholePort(published === void 0 ? void 0 : String(published));
603
+ if (port === void 0) return void 0;
604
+ ports.push(port);
605
+ }
531
606
  }
607
+ return ports;
532
608
  }
533
609
  /**
534
- * Compares, in code, the direct dependencies each lockfile records with the `package.json` files it locks, and fails on a
535
- * difference in either direction. A `pnpm-lock.yaml` is compared importer by importer, for each importer it lists that has a
536
- * `package.json` on disk; a `package-lock.json` by its root entry. Only `dependencies`, `devDependencies` and
537
- * `optionalDependencies` are compared, by name and specifier: a name counts as present whichever of the three fields records
538
- * it, and specifiers such as `catalog:` or `workspace:^` compare as written. A name the lockfile records that `package.json`
539
- * declares only in `peerDependencies` passes. A `package.json` name that an override selector in the `pnpm-lock.yaml`
540
- * mentions, or a `link:` one the lockfile leaves out under `excludeLinksFromLockfile`, is not compared. A missing lockfile fails only in a layer's
541
- * `playground` or the root `playground` whose `package.json` has dependencies, unless a folder above it holds a workspace.
542
- *
543
- * It spawns no package manager, writes no file and fetches nothing. It does not check workspace membership, overrides,
544
- * settings, catalogs, `.npmrc` or user configuration, resolved versions, integrity hashes, transitive entries, npm workspace
545
- * members, or `yarn.lock` and `bun.lock`: verify's own frozen install still rejects a lockfile stale there. Returns what
546
- * failed, empty when every lockfile matches.
610
+ * The environment compose runs in. A project named by `COMPOSE_PROJECT_NAME` or by the compose file's own `name:` is
611
+ * kept; otherwise the project is named after the repository root, since compose would name every repository's project
612
+ * `github` after the compose file's directory and a run could adopt or remove another checkout's containers.
547
613
  */
548
- function checkLockfiles(root) {
549
- return verifyInstallFolders(root).map((install) => checkFolder(root, install)).join("");
550
- }
551
- //#endregion
552
- //#region src/guardrails/singleton-packages.ts
553
- const PNPM_LOCK = "pnpm-lock.yaml";
554
- /** Packages one process must load once: every AntelopeJS interface package shares one runtime with its peers. */
555
- const SINGLETON = /^@antelopejs\/interface-/u;
556
- /** The fields of a lockfile package entry that point at the copy each dependency resolves to. */
557
- const PACKAGE_FIELDS = ["dependencies", "optionalDependencies"];
558
- /** How to move every importer onto one copy while pnpm keeps every other locked version, which `pnpm dedupe` does not. */
559
- const REPAIR = " Set the direct specifier that locks the older copy to the newer version, run `pnpm install --lockfile-only`, then restore the specifier.\n";
560
- /** A `name@version` key or a resolved version without its peer suffix, `(peer@1)`, which names no other copy. */
561
- function withoutPeers(reference) {
562
- const open = reference.indexOf("(");
563
- return open === -1 ? reference : reference.slice(0, open);
564
- }
565
- /** The name and version of a `packages` key: `@scope/name@1.0.0` in version 9, `/@scope/name@1.0.0` in version 6. */
566
- function packageKey(key) {
567
- const match = /^\/?((?:@[^/@]+\/)?[^@]+)@(.+)$/u.exec(withoutPeers(key));
568
- return match?.[1] && match[2] ? {
569
- name: match[1],
570
- version: match[2]
571
- } : void 0;
614
+ function composeEnv(root) {
615
+ if (process.env.COMPOSE_PROJECT_NAME) return process.env;
616
+ if (parseDocument(readFileSync(join(root, COMPOSE_FILE), "utf8")).has("name")) return process.env;
617
+ const slug = basename(root).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "");
618
+ const digest = createHash("sha256").update(root).digest("hex").slice(0, 8);
619
+ return {
620
+ ...process.env,
621
+ COMPOSE_PROJECT_NAME: `${slug || "repo"}-${digest}`
622
+ };
572
623
  }
573
- /** Records `by` as a puller of the copy a dependency resolves to: `version`, or the `name@version` an `npm:` alias resolves to. */
574
- function pull(copies, name, version, by) {
575
- if (version === void 0) return;
576
- const alias = packageKey(version);
577
- const target = alias && copies.has(alias.name) ? alias : {
578
- name,
579
- version: withoutPeers(version)
624
+ async function compose(root, args, signal) {
625
+ const result = await runCommand("docker", [
626
+ "compose",
627
+ "-f",
628
+ COMPOSE_FILE,
629
+ ...args
630
+ ], {
631
+ cwd: root,
632
+ env: composeEnv(root),
633
+ signal
634
+ });
635
+ if (result.status === 0) return {
636
+ failure: "",
637
+ stdout: result.stdout
638
+ };
639
+ const outcome = result.status === null ? "did not finish" : `exited with status ${result.status}`;
640
+ return {
641
+ failure: `${result.output}docker compose -f ${COMPOSE_FILE} ${args.join(" ")}: ${outcome}\n`,
642
+ stdout: result.stdout
580
643
  };
581
- copies.get(target.name)?.get(target.version)?.add(by);
582
644
  }
583
- function addPullers(copies, node, fields, by) {
584
- for (const field of fields) {
585
- const entries = mapping(node, field);
586
- for (const name of keys(entries)) pull(copies, name, scalar(entries, name) ?? scalar(mapping(entries, name), "version"), by);
587
- }
645
+ /**
646
+ * Decides whether the checks start the services of `.github/compose.yml`: not when the file is absent or every port
647
+ * it publishes already accepts connections, and fail at once when Docker Compose cannot run, because the
648
+ * tests that need those services would wait for them forever.
649
+ */
650
+ async function planServices(root) {
651
+ if (!existsSync(join(root, COMPOSE_FILE))) return { kind: "none" };
652
+ const ports = publishedPorts(readFileSync(join(root, COMPOSE_FILE), "utf8"));
653
+ if (ports && (await Promise.all(ports.map(accepting))).every(Boolean)) return { kind: "none" };
654
+ const probe = await compose(root, ["version"]);
655
+ if (!probe.failure) return { kind: "start" };
656
+ return {
657
+ kind: "unavailable",
658
+ output: `Docker Compose is not available, so the services in ${COMPOSE_FILE} cannot start and the tests that need them would hang. Start Docker, start the services yourself, or pass --no-services.\n${probe.failure}`
659
+ };
588
660
  }
589
- /** Each document of a lockfile: pnpm 11 writes its config dependencies, installed apart from the project, as a document before the project's. */
590
- function lockfileDocuments(path) {
591
- return parseAllDocuments(readFileSync(path, "utf8"), {
592
- schema: "failsafe",
593
- uniqueKeys: false
594
- }).map((document) => {
595
- const { contents } = document;
596
- if (document.errors.length > 0 || !isMap(contents) || !(Number.parseFloat(scalar(contents, "lockfileVersion") ?? "") >= 6)) throw new Unreadable(path);
597
- return contents;
598
- });
661
+ /**
662
+ * Runs `docker compose up -d --wait` on the compose file, stopping it when `signal` aborts. `failure` is empty on
663
+ * success; `owned` is true when the project had no container before, so the run may remove it afterwards without
664
+ * taking a stack the developer started.
665
+ */
666
+ async function startServices(root, signal) {
667
+ const before = await compose(root, [
668
+ "ps",
669
+ "--all",
670
+ "--quiet"
671
+ ], signal);
672
+ if (before.failure) return {
673
+ failure: before.failure,
674
+ owned: false
675
+ };
676
+ const owned = before.stdout.trim() === "";
677
+ return {
678
+ failure: (await compose(root, [
679
+ "up",
680
+ "-d",
681
+ "--wait"
682
+ ], signal)).failure,
683
+ owned
684
+ };
599
685
  }
600
- function documentCopies(lockfile) {
601
- const copies = /* @__PURE__ */ new Map();
602
- const packages = mapping(lockfile, "packages");
603
- for (const parsed of keys(packages).map(packageKey)) if (parsed && SINGLETON.test(parsed.name)) copies.set(parsed.name, (copies.get(parsed.name) ?? /* @__PURE__ */ new Map()).set(parsed.version, /* @__PURE__ */ new Set()));
604
- const importers = mapping(lockfile, "importers");
605
- for (const importer of importers ? keys(importers) : ["."]) addPullers(copies, importers ? mapping(importers, importer) : lockfile, DIRECT_FIELDS, `importer "${importer}"`);
606
- const resolved = mapping(lockfile, "snapshots") ?? packages;
607
- for (const key of keys(resolved)) addPullers(copies, mapping(resolved, key), PACKAGE_FIELDS, withoutPeers(key.replace(/^\//u, "")));
608
- return copies;
686
+ /** Runs `docker compose down -v` on the compose file; returns the failure output, empty on success. */
687
+ async function stopServices(root) {
688
+ return (await compose(root, ["down", "-v"])).failure;
609
689
  }
610
- function report(file, copies) {
611
- return [...copies].filter(([, versions]) => versions.size > 1).map(([name, versions]) => `${file} resolves "${name}" at ${versions.size} versions, and an interface package must load once:\n${[...versions].map(([version, by]) => ` ${version}, pulled by ${[...by].join(", ") || "nothing"}\n`).join("")}${REPAIR}`).join("");
690
+ //#endregion
691
+ //#region src/guardrails/verify-layers.ts
692
+ const SKILLS_FOLDER = ".agents/skills";
693
+ const LAYER_PREFIX = "verify-";
694
+ const TSCONFIG = "tsconfig.json";
695
+ /** Folders of a layer that are not the layer's own code: verify builds its playground with the playground's own tsconfig. */
696
+ const NOT_LAYER_CODE = /* @__PURE__ */ new Set(["node_modules", "dist"]);
697
+ const LAYER_PLAYGROUND = "playground";
698
+ const VERIFY_CONFIG = "verify.config.ts";
699
+ /**
700
+ * Options the generated config sets over the layer's: nothing is emitted, and each declaration or build-cache option the
701
+ * layer may inherit is unset with `null`, so no `.tsbuildinfo` is written, no option is left needing `declaration` or
702
+ * `composite`, and the declaration checks of files that are never emitted are not run.
703
+ */
704
+ const NO_OUTPUT = {
705
+ noEmit: true,
706
+ declaration: null,
707
+ composite: null,
708
+ incremental: null,
709
+ tsBuildInfoFile: null,
710
+ declarationDir: null,
711
+ declarationMap: null,
712
+ emitDeclarationOnly: null,
713
+ isolatedDeclarations: null
714
+ };
715
+ /** The verify layers of a repository, relative to its root: each `.agents/skills/verify-*` folder that holds a `tsconfig.json` or a `verify.config.ts`. */
716
+ function verifyLayers(root) {
717
+ const skills = join(root, SKILLS_FOLDER);
718
+ if (!existsSync(skills)) return [];
719
+ return readdirSync(skills, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name.startsWith(LAYER_PREFIX) && [TSCONFIG, VERIFY_CONFIG].some((file) => existsSync(join(skills, entry.name, file)))).map((entry) => `${SKILLS_FOLDER}/${entry.name}`).sort();
612
720
  }
613
- /** The `pnpm-lock.yaml` files on disk in the repository, tracked or not yet added, outside what `.gitignore` leaves out. */
614
- function pnpmLockfiles(root) {
615
- return gitFiles(root).filter((file) => (file === PNPM_LOCK || file.endsWith(`/${PNPM_LOCK}`)) && existsSync(join(root, file)));
721
+ /** Whether a file the layer's tsconfig includes is the layer's own code, not its playground, a dependency or a build output. */
722
+ function isLayerCode(layer, file) {
723
+ const segments = relative(layer, file).split(sep);
724
+ return segments[0] !== LAYER_PLAYGROUND && !segments.some((segment) => NOT_LAYER_CODE.has(segment));
616
725
  }
617
726
  /**
618
- * Fails when a `pnpm-lock.yaml` of the repository resolves an AntelopeJS interface package, any `@antelopejs/interface-*`,
619
- * at more than one version: each copy carries its own runtime, so two copies in one process break the contract between
620
- * modules, or throw on a runtime protocol mismatch. Names, for each version, the importers and packages that pull it.
621
- * Reads the lockfiles only: it spawns no package manager, writes no file and fetches nothing. Returns what failed, empty
622
- * when every interface package resolves once.
727
+ * The repository's own `tsc` entry, run with Node so no shell parses its path. It is found through the `bin.tsc` field of
728
+ * `typescript/package.json`, a subpath every TypeScript version exports, because TypeScript 7 declares an `exports` map that
729
+ * leaves `typescript/bin/tsc` out.
623
730
  */
624
- function checkSingletonPackages(root) {
625
- return pnpmLockfiles(root).map((file) => {
626
- try {
627
- return lockfileDocuments(join(root, file)).map((document) => report(file, documentCopies(document))).join("");
628
- } catch (error) {
629
- if (error instanceof Unreadable) return `${file}: could not read it as a lockfile version this check knows.\n`;
630
- throw error;
631
- }
632
- }).join("");
633
- }
634
- //#endregion
635
- //#region src/guardrails/markdown-table.ts
636
- /** The lines of a Markdown table whose first row is the header, columns padded as oxfmt leaves them. */
637
- function tableLines(table) {
638
- const widths = table[0].map((_, column) => Math.max(3, ...table.map((row) => row[column].length)));
639
- const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
640
- return [
641
- line(table[0]),
642
- line(widths.map((width) => "-".repeat(width))),
643
- ...table.slice(1).map(line)
644
- ];
731
+ function compilerOf(root) {
732
+ try {
733
+ const manifestPath = createRequire(join(root, "package.json")).resolve("typescript/package.json");
734
+ const tsc = parseManifest(readFileSync(manifestPath, "utf8")).bin?.tsc;
735
+ return tsc === void 0 ? void 0 : join(dirname(manifestPath), tsc);
736
+ } catch {
737
+ return;
738
+ }
645
739
  }
646
- //#endregion
647
- //#region src/guardrails/docs-modules.ts
648
- const DMS_MODULES_START = "<!-- antelopejs-dms-modules:start -->";
649
- const DMS_MODULES_END = "<!-- antelopejs-dms-modules:end -->";
650
- const ORGANIZATION = "https://github.com/AntelopeJS";
651
- /** The AntelopeJS DMS modules in display order. Every README holding the markers lists exactly these. */
652
- const DMS_MODULES = [
653
- {
654
- repo: "dms-builder",
655
- row: "Edit pages, tables and data sources by clicking, as TypeScript that compiles"
656
- },
657
- {
658
- repo: "dms-ai",
659
- row: "An assistant chat in the dashboard, on your own Claude Code or Codex"
660
- },
661
- {
662
- repo: "dms-database",
663
- row: "Schemas, relation diagrams, a data browser and a query console"
664
- },
665
- {
666
- repo: "dms-api",
667
- row: "API health, request logs, per-route statistics and a request tester"
668
- },
669
- {
670
- repo: "dms-automation",
671
- row: "Node-graph automations on schedules, webhooks and DMS events, with a trace for every run"
672
- },
673
- {
674
- repo: "dms-mailing",
675
- row: "E-mail templates in a block editor, versions, a send log and delivery metrics"
676
- },
677
- {
678
- repo: "dms-lang",
679
- row: "Translation coverage, a translation matrix and a translation queue"
680
- },
681
- {
682
- repo: "dms-media",
683
- row: "A media library with folders, per-folder permissions, image sizes and light editing"
684
- },
685
- {
686
- repo: "dms-saas",
687
- row: "Self-service sign-up, plans that gate features, and Stripe billing"
688
- },
689
- {
690
- repo: "dms-marketing",
691
- row: "Traffic, conversion funnels with A/B splits and click heatmaps, without cookies"
692
- },
693
- {
694
- repo: "dms-frontend",
695
- row: "The `ajs dms` CLI, the Vue renderer and the SDK every frontend module builds on"
740
+ async function typecheckLayer(root, compiler, layer, signal) {
741
+ const configPath = join(root, layer, TSCONFIG);
742
+ if (!existsSync(configPath)) return `${layer}: has a verify.config.ts and no tsconfig.json. Add a tsconfig.json that includes its TypeScript files; antelopejs-sync writes one for the shared kinds.\n`;
743
+ const ts = (await import("typescript")).default;
744
+ const parsed = ts.getParsedCommandLineOfConfigFile(configPath, void 0, {
745
+ ...ts.sys,
746
+ onUnRecoverableConfigFileDiagnostic: () => void 0
747
+ });
748
+ if (parsed === void 0) return `${layer}/${TSCONFIG}: could not read it.\n`;
749
+ const verifyConfig = join(root, layer, VERIFY_CONFIG);
750
+ if (existsSync(verifyConfig) && !parsed.fileNames.some((file) => resolve(file) === verifyConfig)) return `${layer}/${TSCONFIG}: does not include ${VERIFY_CONFIG}, so it is never type-checked. Add it to the tsconfig's "include" or "files".\n`;
751
+ const files = parsed.fileNames.filter((file) => isLayerCode(join(root, layer), resolve(file)));
752
+ if (files.length === 0) return "";
753
+ const folder = mkdtempSync(join(tmpdir(), "antelopejs-verify-types-"));
754
+ try {
755
+ const generated = join(folder, TSCONFIG);
756
+ writeFileSync(generated, JSON.stringify({
757
+ extends: configPath,
758
+ compilerOptions: {
759
+ ...NO_OUTPUT,
760
+ typeRoots: ts.getEffectiveTypeRoots(parsed.options, ts.sys)
761
+ },
762
+ files,
763
+ include: []
764
+ }));
765
+ const result = await runCommand(process.execPath, [
766
+ compiler,
767
+ "-p",
768
+ generated,
769
+ "--pretty",
770
+ "false"
771
+ ], {
772
+ cwd: root,
773
+ env: {
774
+ ...process.env,
775
+ CI: "1"
776
+ },
777
+ signal,
778
+ shell: false
779
+ });
780
+ return result.status === 0 ? "" : result.output;
781
+ } finally {
782
+ rmSync(folder, {
783
+ recursive: true,
784
+ force: true
785
+ });
696
786
  }
697
- ];
698
- /** The generated block, formatted as oxfmt leaves it. */
699
- function modulesBlock() {
700
- return [
701
- DMS_MODULES_START,
702
- "",
703
- ...tableLines([["Module", "What it adds"], ...DMS_MODULES.map(({ repo, row }) => [`[\`${repo}\`](${ORGANIZATION}/${repo})`, row])]),
704
- "",
705
- DMS_MODULES_END,
706
- ""
707
- ].join("\n");
708
787
  }
709
- /** The README with the block between its markers rewritten. A README without markers comes back as it is. */
710
- function placeModulesBlock(current) {
711
- const start = current.indexOf(DMS_MODULES_START);
712
- const end = current.indexOf(DMS_MODULES_END);
713
- const starts = current.split(DMS_MODULES_START).length - 1;
714
- const ends = current.split(DMS_MODULES_END).length - 1;
715
- if (starts === 0 && ends === 0) return current;
716
- if (starts !== 1 || ends !== 1 || end < start) throw new Error("invalid antelopejs-dms-modules markers: a README holds exactly one start marker followed by one end marker. Repair or delete them, then rerun antelopejs-sync.");
717
- return `${current.slice(0, start)}${modulesBlock()}${current.slice(end + 35).replace(/^\r?\n/, "")}`;
788
+ /**
789
+ * Type-checks the own code of each verify layer with the repository's own TypeScript. The files are those the layer's
790
+ * `tsconfig.json` includes, minus its `playground` folder, which verify compiles with the playground's own config after
791
+ * installing it, and any `node_modules` or `dist` folder. A config generated in the system temp folder extends the layer's,
792
+ * lists those files, turns off emit and unsets the emit and build-cache options in `NO_OUTPUT`, so nothing is written in the
793
+ * repository and no package is fetched. A layer whose `tsconfig.json` does not include its `verify.config.ts` fails. Returns the compiler output of the layers that fail, empty when all pass.
794
+ */
795
+ async function typecheckLayers(root, signal) {
796
+ const layers = verifyLayers(root);
797
+ if (layers.length === 0) return "";
798
+ const compiler = compilerOf(root);
799
+ if (compiler === void 0) return "TypeScript is not installed in the repository root: run the package manager's install first.\n";
800
+ return (await Promise.all(layers.map((layer) => typecheckLayer(root, compiler, layer, signal)))).join("");
718
801
  }
719
802
  //#endregion
720
- //#region src/guardrails/docs-compat.ts
721
- const DOCS_COMPAT_START = "<!-- antelopejs-docs-compat:start -->";
722
- const DOCS_COMPAT_END = "<!-- antelopejs-docs-compat:end -->";
723
- const DOCS_NODE_START = "<!-- antelopejs-docs-node:start -->";
724
- const DOCS_NODE_END = "<!-- antelopejs-docs-node:end -->";
725
- const LOCKFILE = "pnpm-lock.yaml";
726
- const REQUIREMENTS_HEADING = /^##\s+Requirements\s*$/i;
727
- const SCOPE = "@antelopejs/";
728
- const UNRESOLVED = "—";
729
- const WORKSPACE = "workspace";
730
- const LEGACY_MARKER = /^<!--\s*docs-compat:\s*\.\/package\.json#\w+\s*-->\s*$/;
731
- const COMPATIBILITY_HEADING = /^##\s+Compatibility\s*$/i;
732
- const RESOLVED_SECTIONS = [
803
+ //#region src/guardrails/verify-lockfiles.ts
804
+ /** The folder a repository's playground lives in; verify installs a fixture project from it. */
805
+ const PLAYGROUND = "playground";
806
+ const PNPM_LOCK$1 = "pnpm-lock.yaml";
807
+ const NPM_LOCK = "package-lock.json";
808
+ const MANIFEST = "package.json";
809
+ const PNPM_WORKSPACE = "pnpm-workspace.yaml";
810
+ /** Lockfiles this check does not compare, which still mean a folder is locked. */
811
+ const OTHER_LOCKS = [
812
+ "npm-shrinkwrap.json",
813
+ "yarn.lock",
814
+ "bun.lock",
815
+ "bun.lockb"
816
+ ];
817
+ /** The manifest fields both package managers record as a project's direct dependencies. */
818
+ const DIRECT_FIELDS = [
733
819
  "dependencies",
734
- "optionalDependencies",
735
- "devDependencies"
820
+ "devDependencies",
821
+ "optionalDependencies"
736
822
  ];
737
- /** The generated block, rows sorted by package name, formatted as oxfmt leaves it. */
738
- function compatBlock(rows) {
739
- const sorted = [...rows].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
740
- return [
741
- DOCS_COMPAT_START,
742
- "",
743
- ...tableLines([[
744
- "Package",
745
- "Supported",
746
- "Tested with"
747
- ], ...sorted.map(({ name, supported, tested }) => [
748
- `\`${name}\``,
749
- `\`${supported.replaceAll("|", "\\|")}\``,
750
- tested === void 0 ? UNRESOLVED : `\`${tested}\``
751
- ])]),
752
- "",
753
- DOCS_COMPAT_END,
754
- ""
755
- ].join("\n");
823
+ /** A lockfile or manifest this check cannot read as a version it knows. */
824
+ var Unreadable = class extends Error {};
825
+ /** Parses a JSON or YAML file whose top level is a mapping; throws `Unreadable` otherwise. */
826
+ function readMapping(path) {
827
+ const document = parseDocument(readFileSync(path, "utf8"), {
828
+ schema: "failsafe",
829
+ uniqueKeys: false
830
+ });
831
+ const { contents } = document;
832
+ if (document.errors.length > 0 || !isMap(contents)) throw new Unreadable(path);
833
+ return contents;
756
834
  }
757
- function legacySpanEnd(lines, marker) {
758
- let index = marker + 1;
759
- while (index < lines.length && !lines[index].trim()) index++;
760
- while (index < lines.length && lines[index].trimStart().startsWith("|")) index++;
761
- while (index < lines.length && !lines[index].trim()) index++;
762
- return index;
835
+ /** The mapping under `key`; `undefined` when absent or not a mapping. */
836
+ function mapping(map, key) {
837
+ const value = map?.get(key, true);
838
+ return isMap(value) ? value : void 0;
763
839
  }
764
- function replaceLegacyTables(lines, block) {
765
- const placed = [];
766
- let replaced = false;
767
- for (let index = 0; index < lines.length;) {
768
- if (!LEGACY_MARKER.test(lines[index])) {
769
- placed.push(lines[index]);
770
- index++;
771
- continue;
840
+ /** The source text of the scalar under `key`; `undefined` when absent or not a scalar. */
841
+ function scalar(map, key) {
842
+ const value = map?.get(key, true);
843
+ return isScalar(value) ? String(value.value) : void 0;
844
+ }
845
+ /** The scalar keys of a mapping, in order; none when it is absent. */
846
+ function keys(map) {
847
+ return (map?.items ?? []).flatMap((pair) => isScalar(pair.key) ? [String(pair.key.value)] : []);
848
+ }
849
+ /** Reads a project's direct dependencies, with `specifierOf` reading the specifier of one name from its field. */
850
+ function directOf(node, specifierOf) {
851
+ const direct = /* @__PURE__ */ new Map();
852
+ for (const field of DIRECT_FIELDS) {
853
+ const entries = mapping(node, field);
854
+ for (const name of keys(entries)) {
855
+ const specifier = specifierOf(entries, name);
856
+ if (specifier === void 0) throw new Unreadable(name);
857
+ direct.set(name, /* @__PURE__ */ new Set([...direct.get(name) ?? [], specifier]));
772
858
  }
773
- if (!replaced) placed.push(...block.split("\n"));
774
- replaced = true;
775
- index = legacySpanEnd(lines, index);
776
859
  }
777
- return replaced ? placed : void 0;
860
+ return direct;
778
861
  }
779
- function finalNewline(text) {
780
- return text.endsWith("\n") ? text : `${text}\n`;
862
+ /** A `package.json` or a `package-lock.json` root entry, where each name maps to its specifier. */
863
+ function declared(node) {
864
+ return directOf(node, scalar);
781
865
  }
782
- /** The README with the block in place: replacing the markers, a legacy `docs-compat` table, or under `## Compatibility`. */
783
- function placeCompatBlock(current, block) {
784
- const text = current ?? "";
785
- const start = text.indexOf(DOCS_COMPAT_START);
786
- const end = text.indexOf(DOCS_COMPAT_END);
787
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-compat markers. Repair or delete them, then rerun antelopejs-sync.");
788
- if (start !== -1) return `${text.slice(0, start)}${block}${text.slice(end + 35).replace(/^\r?\n/, "")}`;
789
- const lines = text.split("\n");
790
- const legacy = replaceLegacyTables(lines, block);
791
- if (legacy) return finalNewline(legacy.join("\n"));
792
- const heading = lines.findIndex((line) => COMPATIBILITY_HEADING.test(line));
793
- if (heading !== -1) {
794
- let rest = heading + 1;
795
- while (rest < lines.length && !lines[rest].trim()) rest++;
796
- return finalNewline([
797
- ...lines.slice(0, heading + 1),
798
- "",
799
- ...block.split("\n"),
800
- ...lines.slice(rest)
801
- ].join("\n"));
802
- }
803
- const before = text.trimEnd();
804
- return `${before}${before ? "\n\n" : ""}## Compatibility\n\n${block}`;
866
+ /** A `pnpm-lock.yaml` importer, where each name maps to its `specifier` and resolved `version`. */
867
+ function pnpmLocked(node) {
868
+ return directOf(node, (field, name) => scalar(mapping(field, name), "specifier"));
805
869
  }
806
- /** The generated Node prerequisite block for an `engines.node` range, formatted as oxfmt leaves it. */
807
- function nodeBlock(range) {
808
- return `${DOCS_NODE_START}\n\nThis package requires Node.js \`${range}\`.\n${DOCS_NODE_END}\n`;
870
+ function listed(specifiers) {
871
+ return specifiers === void 0 ? "none" : [...specifiers].map((specifier) => `"${specifier}"`).join(" or ");
809
872
  }
810
- /** The README with the Node block in place: between its markers, under `## Requirements`, or in a new `## Requirements` section at the end. */
811
- function placeNodeBlock(current, block) {
812
- const start = current.indexOf(DOCS_NODE_START);
813
- const end = current.indexOf(DOCS_NODE_END);
814
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-node markers. Repair or delete them, then rerun antelopejs-sync.");
815
- if (start !== -1) return `${current.slice(0, start)}${block}${current.slice(end + 33).replace(/^\r?\n/, "")}`;
816
- const lines = current.split("\n");
817
- const heading = lines.findIndex((line) => REQUIREMENTS_HEADING.test(line));
818
- if (heading !== -1) {
819
- let rest = heading + 1;
820
- while (rest < lines.length && !lines[rest].trim()) rest++;
821
- return finalNewline([
822
- ...lines.slice(0, heading + 1),
823
- "",
824
- ...block.trimEnd().split("\n"),
825
- ...rest < lines.length ? ["", ...lines.slice(rest)] : []
826
- ].join("\n"));
827
- }
828
- return `${current.trimEnd()}\n\n## Requirements\n\n${block}`;
873
+ /**
874
+ * The names whose specifiers differ between a manifest and what its lockfile records, in either direction. A name counts as
875
+ * present whichever of the three fields records it, and matches when the two sides share a specifier. A name the lockfile
876
+ * records and the manifest declares only as a peer passes, since the package manager may or may not install peers. `skip`
877
+ * names the manifest entries the lockfile may leave out or record with another specifier.
878
+ */
879
+ function differences(manifest, locked, skip) {
880
+ const wanted = declared(manifest);
881
+ const peers = new Set(keys(mapping(manifest, "peerDependencies")));
882
+ const line = (name) => `"${name}": package.json asks for ${listed(wanted.get(name))}, the lockfile has ${listed(locked.get(name))}.`;
883
+ const stale = [...wanted].filter(([name, specifiers]) => ![...locked.get(name) ?? []].some((specifier) => specifiers.has(specifier)) && !skip(name, specifiers)).map(([name]) => line(name));
884
+ const extra = [...locked.keys()].filter((name) => !wanted.has(name) && !peers.has(name)).map(line);
885
+ return [...stale, ...extra].sort();
829
886
  }
830
- function relative$1(directory, name) {
831
- return directory ? `${directory}/${name}` : name;
887
+ /** Every package name an override selector such as `foo`, `@scope/foo@^1` or `bar@1>foo@2` mentions, its target among them. */
888
+ function overrideNames(selector) {
889
+ return selector.split(">").flatMap((segment) => /^(?:@[^/@]+\/)?[^@]+/u.exec(segment) ?? []);
832
890
  }
833
- function isDirectory(root, path) {
834
- return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
891
+ function pnpmDifferences(path) {
892
+ const lockfile = readMapping(join(path, PNPM_LOCK$1));
893
+ if (Number(scalar(lockfile, "lockfileVersion") ?? "0") < 6) throw new Unreadable(path);
894
+ const overridden = new Set(keys(mapping(lockfile, "overrides")).flatMap(overrideNames));
895
+ const linksLeftOut = scalar(mapping(lockfile, "settings"), "excludeLinksFromLockfile") === "true";
896
+ const skip = (name, specifiers) => overridden.has(name) || linksLeftOut && [...specifiers].every((specifier) => specifier.startsWith("link:"));
897
+ const importers = mapping(lockfile, "importers");
898
+ return (importers ? keys(importers) : ["."]).flatMap((importer) => {
899
+ const manifest = join(path, importer, MANIFEST);
900
+ if (!existsSync(manifest)) return [];
901
+ const node = importers ? mapping(importers, importer) : lockfile;
902
+ return differences(readMapping(manifest), pnpmLocked(node), skip).map((line) => `importer "${importer}" ${line}`);
903
+ });
835
904
  }
836
- function subdirectories(root, directory) {
837
- return readdirSync(join(root, directory), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith(".")).map((entry) => relative$1(directory, entry.name));
905
+ function npmDifferences(path) {
906
+ const lockfile = readMapping(join(path, NPM_LOCK));
907
+ const rootEntry = mapping(mapping(lockfile, "packages"), "");
908
+ if (Number(scalar(lockfile, "lockfileVersion") ?? "0") < 2 || rootEntry === void 0) throw new Unreadable(path);
909
+ const manifest = join(path, MANIFEST);
910
+ if (!existsSync(manifest)) return [];
911
+ return differences(readMapping(manifest), declared(rootEntry), () => false);
838
912
  }
839
- function descendants(root, directory) {
840
- return subdirectories(root, directory).flatMap((child) => [child, ...descendants(root, child)]);
913
+ function lockfileIn(path) {
914
+ if (existsSync(join(path, PNPM_LOCK$1))) return PNPM_LOCK$1;
915
+ if (existsSync(join(path, NPM_LOCK))) return NPM_LOCK;
916
+ return OTHER_LOCKS.some((name) => existsSync(join(path, name))) ? "other" : void 0;
917
+ }
918
+ /** Each folder at or under `folder`, `node_modules` and `dist` aside, that holds a lockfile. */
919
+ function lockedFolders(root, folder) {
920
+ const path = join(root, folder);
921
+ if (!existsSync(path)) return [];
922
+ const lockfile = lockfileIn(path);
923
+ return [...lockfile === void 0 ? [] : [{
924
+ folder,
925
+ lockfile
926
+ }], ...readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && entry.name !== "dist").flatMap((entry) => lockedFolders(root, `${folder}/${entry.name}`))];
927
+ }
928
+ /** Whether a `package.json` declares a direct dependency; `false` when it is missing or cannot be read, so this check cannot tell. */
929
+ function hasDependencies(path) {
930
+ try {
931
+ if (!existsSync(path)) return false;
932
+ const manifest = readMapping(path);
933
+ return DIRECT_FIELDS.some((field) => keys(mapping(manifest, field)).length > 0);
934
+ } catch (error) {
935
+ if (error instanceof Unreadable) return false;
936
+ throw error;
937
+ }
938
+ }
939
+ /**
940
+ * The folders this check reads, when a layer exists: each folder under a layer, `node_modules` and `dist` aside, and the
941
+ * root `playground`, that holds a lockfile; and each layer's `playground` and the root `playground`, the folders verify
942
+ * installs from, when its `package.json` has dependencies and it holds no lockfile.
943
+ */
944
+ function verifyInstallFolders(root) {
945
+ const layers = verifyLayers(root);
946
+ if (layers.length === 0) return [];
947
+ const playgrounds = [...layers.map((layer) => `${layer}/${PLAYGROUND}`), PLAYGROUND];
948
+ const rootPlayground = lockfileIn(join(root, PLAYGROUND));
949
+ return [
950
+ ...layers.flatMap((layer) => lockedFolders(root, layer)),
951
+ ...rootPlayground === void 0 ? [] : [{
952
+ folder: PLAYGROUND,
953
+ lockfile: rootPlayground
954
+ }],
955
+ ...playgrounds.filter((folder) => lockfileIn(join(root, folder)) === void 0 && hasDependencies(join(root, folder, MANIFEST))).map((folder) => ({
956
+ folder,
957
+ lockfile: void 0
958
+ }))
959
+ ];
841
960
  }
842
- function globExpression(pattern) {
843
- const source = pattern.split("/").map((segment) => segment === "**" ? "(?:.*)" : segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*").replaceAll("?", "[^/]")).join("/").replaceAll("(?:.*)/", "(?:.*/)?");
844
- return new RegExp(`^${source}$`);
961
+ /** The folders above `folder`, nearest first, up to the repository root. */
962
+ function ancestors(folder) {
963
+ const parent = posix.dirname(folder);
964
+ return parent === folder ? [] : [parent, ...ancestors(parent)];
845
965
  }
846
- function expand(root, pattern) {
847
- let directories = [""];
848
- for (const segment of pattern.split("/")) if (segment === "**") directories = directories.flatMap((directory) => [directory, ...descendants(root, directory)]);
849
- else if (/[*?]/.test(segment)) {
850
- const expression = globExpression(segment);
851
- directories = directories.flatMap((directory) => subdirectories(root, directory).filter((child) => expression.test(child.slice(child.lastIndexOf("/") + 1))));
852
- } else directories = directories.map((directory) => relative$1(directory, segment)).filter((directory) => isDirectory(root, directory));
853
- return directories;
966
+ /** Whether a manifest declares workspaces, or cannot be read and so might. */
967
+ function declaresWorkspaces(path) {
968
+ try {
969
+ return existsSync(path) && readMapping(path).has("workspaces");
970
+ } catch (error) {
971
+ if (error instanceof Unreadable) return true;
972
+ throw error;
973
+ }
854
974
  }
855
- function normalizePattern(pattern) {
856
- return pattern.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "");
975
+ /**
976
+ * Whether a folder above `folder` holds a workspace that may list it, a `pnpm-workspace.yaml` or a `package.json` with
977
+ * `workspaces`: its membership then follows patterns this check does not evaluate, and that workspace's lockfile may hold it.
978
+ */
979
+ function inWorkspace(root, folder) {
980
+ return ancestors(folder).some((above) => existsSync(join(root, above, PNPM_WORKSPACE)) || declaresWorkspaces(join(root, above, MANIFEST)));
857
981
  }
858
- function scalarItems(document, path) {
859
- const node = document.getIn(path, true);
860
- return isSeq(node) ? node.items.flatMap((item) => isScalar(item) ? [String(item.value)] : []) : [];
982
+ function fixCommand(root, folder, lockfile) {
983
+ if (lockfile === NPM_LOCK) return `npm install --package-lock-only --prefix ${folder}`;
984
+ return existsSync(join(root, folder, PNPM_WORKSPACE)) ? `pnpm install --dir ${folder} --lockfile-only` : `pnpm install --dir ${folder} --ignore-workspace --lockfile-only`;
861
985
  }
862
- /** pnpm-workspace.yaml `packages`, else package.json `workspaces` as an array or as `{ packages }`; JSON parses as YAML. */
863
- function workspacePatterns(root) {
864
- const pnpm = join(root, "pnpm-workspace.yaml");
865
- if (existsSync(pnpm)) return scalarItems(parseDocument(readFileSync(pnpm, "utf8")), ["packages"]);
866
- const manifest = parseDocument(readFileSync(join(root, "package.json"), "utf8"));
867
- return scalarItems(manifest, isMap(manifest.get("workspaces", true)) ? ["workspaces", "packages"] : ["workspaces"]);
986
+ function unlocked(root, folder) {
987
+ if (inWorkspace(root, folder)) return "";
988
+ const manager = ancestors(folder).some((above) => existsSync(join(root, above, NPM_LOCK))) ? NPM_LOCK : PNPM_LOCK$1;
989
+ return `${folder}/${MANIFEST} has dependencies and no lockfile: run \`${fixCommand(root, folder, manager)}\`.\n`;
868
990
  }
869
- /** The workspace package directories, relative to `root` and sorted, that `pnpm-workspace.yaml` or package.json `workspaces` list. */
870
- function workspaceDirectories(root) {
871
- const patterns = workspacePatterns(root);
872
- const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => globExpression(normalizePattern(pattern.slice(1))));
873
- const found = /* @__PURE__ */ new Set();
874
- for (const pattern of patterns.filter((item) => !item.startsWith("!"))) {
875
- const normalized = normalizePattern(pattern);
876
- for (const directory of normalized ? expand(root, normalized) : [""]) if (directory && !excluded.some((expression) => expression.test(directory)) && existsSync(join(root, directory, "package.json"))) found.add(directory);
991
+ function checkFolder(root, { folder, lockfile }) {
992
+ if (lockfile === "other") return "";
993
+ try {
994
+ if (lockfile === void 0) return unlocked(root, folder);
995
+ const path = join(root, folder);
996
+ const found = lockfile === PNPM_LOCK$1 ? pnpmDifferences(path) : npmDifferences(path);
997
+ return found.length === 0 ? "" : `${folder}/${lockfile} does not match ${folder}/${MANIFEST}: run \`${fixCommand(root, folder, lockfile)}\`.\n${found.map((line) => ` ${line}\n`).join("")}`;
998
+ } catch (error) {
999
+ if (error instanceof Unreadable) return `${folder}/${lockfile ?? MANIFEST}: could not read it, or a ${MANIFEST} it locks, as a version this check knows.\n`;
1000
+ throw error;
877
1001
  }
878
- return [...found].sort();
879
1002
  }
880
- function declaredRanges(manifest) {
881
- const ranges = /* @__PURE__ */ new Map();
882
- for (const field of [
883
- manifest.optionalDependencies,
884
- manifest.dependencies,
885
- manifest.peerDependencies
886
- ]) for (const [name, range] of Object.entries(field ?? {})) if (name.startsWith(SCOPE)) ranges.set(name, range);
887
- return ranges;
1003
+ /**
1004
+ * Compares, in code, the direct dependencies each lockfile records with the `package.json` files it locks, and fails on a
1005
+ * difference in either direction. A `pnpm-lock.yaml` is compared importer by importer, for each importer it lists that has a
1006
+ * `package.json` on disk; a `package-lock.json` by its root entry. Only `dependencies`, `devDependencies` and
1007
+ * `optionalDependencies` are compared, by name and specifier: a name counts as present whichever of the three fields records
1008
+ * it, and specifiers such as `catalog:` or `workspace:^` compare as written. A name the lockfile records that `package.json`
1009
+ * declares only in `peerDependencies` passes. A `package.json` name that an override selector in the `pnpm-lock.yaml`
1010
+ * mentions, or a `link:` one the lockfile leaves out under `excludeLinksFromLockfile`, is not compared. A missing lockfile fails only in a layer's
1011
+ * `playground` or the root `playground` whose `package.json` has dependencies, unless a folder above it holds a workspace.
1012
+ *
1013
+ * It spawns no package manager, writes no file and fetches nothing. It does not check workspace membership, overrides,
1014
+ * settings, catalogs, `.npmrc` or user configuration, resolved versions, integrity hashes, transitive entries, npm workspace
1015
+ * members, or `yarn.lock` and `bun.lock`: verify's own frozen install still rejects a lockfile stale there. Returns what
1016
+ * failed, empty when every lockfile matches.
1017
+ */
1018
+ function checkLockfiles(root) {
1019
+ return verifyInstallFolders(root).map((install) => checkFolder(root, install)).join("");
888
1020
  }
889
- function readManifest(root, directory) {
890
- return parseManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
1021
+ //#endregion
1022
+ //#region src/guardrails/singleton-packages.ts
1023
+ const PNPM_LOCK = "pnpm-lock.yaml";
1024
+ /** Packages one process must load once: every AntelopeJS interface package shares one runtime with its peers. */
1025
+ const SINGLETON = /^@antelopejs\/interface-/u;
1026
+ /** The fields of a lockfile package entry that point at the copy each dependency resolves to. */
1027
+ const PACKAGE_FIELDS = ["dependencies", "optionalDependencies"];
1028
+ /** How to move every importer onto one copy while pnpm keeps every other locked version, which `pnpm dedupe` does not. */
1029
+ const REPAIR = " Set the direct specifier that locks the older copy to the newer version, run `pnpm install --lockfile-only`, then restore the specifier.\n";
1030
+ /** A `name@version` key or a resolved version without its peer suffix, `(peer@1)`, which names no other copy. */
1031
+ function withoutPeers(reference) {
1032
+ const open = reference.indexOf("(");
1033
+ return open === -1 ? reference : reference.slice(0, open);
891
1034
  }
892
- /** The version the lockfile resolves for a dependency; a `link:` resolves to `workspace`, so a release that bumps the linked package leaves this README unchanged. */
893
- function resolvedVersion({ document, importer }, name) {
894
- for (const section of RESOLVED_SECTIONS) {
895
- const entry = document.getIn([
896
- "importers",
897
- importer,
898
- section,
899
- name
900
- ], true);
901
- const version = isMap(entry) ? entry.get("version", true) : entry;
902
- if (!isScalar(version)) continue;
903
- const resolved = String(version.value).split("(")[0];
904
- return resolved.startsWith("link:") ? WORKSPACE : resolved;
1035
+ /** The name and version of a `packages` key: `@scope/name@1.0.0` in version 9, `/@scope/name@1.0.0` in version 6. */
1036
+ function packageKey(key) {
1037
+ const match = /^\/?((?:@[^/@]+\/)?[^@]+)@(.+)$/u.exec(withoutPeers(key));
1038
+ return match?.[1] && match[2] ? {
1039
+ name: match[1],
1040
+ version: match[2]
1041
+ } : void 0;
1042
+ }
1043
+ /** Records `by` as a puller of the copy a dependency resolves to: `version`, or the `name@version` an `npm:` alias resolves to. */
1044
+ function pull(copies, name, version, by) {
1045
+ if (version === void 0) return;
1046
+ const alias = packageKey(version);
1047
+ const target = alias && copies.has(alias.name) ? alias : {
1048
+ name,
1049
+ version: withoutPeers(version)
1050
+ };
1051
+ copies.get(target.name)?.get(target.version)?.add(by);
1052
+ }
1053
+ function addPullers(copies, node, fields, by) {
1054
+ for (const field of fields) {
1055
+ const entries = mapping(node, field);
1056
+ for (const name of keys(entries)) pull(copies, name, scalar(entries, name) ?? scalar(mapping(entries, name), "version"), by);
905
1057
  }
906
1058
  }
907
- const UNSHARED_NPMRC = /^\s*shared-workspace-lockfile\s*=\s*false\s*(?:[#;].*)?$/m;
908
- /** Whether the workspace keeps one root lockfile, or `shared-workspace-lockfile=false` gives each package its own. */
909
- function sharesLockfile(root) {
910
- const npmrc = join(root, ".npmrc");
911
- if (existsSync(npmrc) && UNSHARED_NPMRC.test(readFileSync(npmrc, "utf8"))) return false;
912
- const workspace = join(root, "pnpm-workspace.yaml");
913
- return !(existsSync(workspace) && parseDocument(readFileSync(workspace, "utf8")).get("sharedWorkspaceLockfile") === false);
1059
+ /** Each document of a lockfile: pnpm 11 writes its config dependencies, installed apart from the project, as a document before the project's. */
1060
+ function lockfileDocuments(path) {
1061
+ return parseAllDocuments(readFileSync(path, "utf8"), {
1062
+ schema: "failsafe",
1063
+ uniqueKeys: false
1064
+ }).map((document) => {
1065
+ const { contents } = document;
1066
+ if (document.errors.length > 0 || !isMap(contents) || !(Number.parseFloat(scalar(contents, "lockfileVersion") ?? "") >= 6)) throw new Unreadable(path);
1067
+ return contents;
1068
+ });
914
1069
  }
915
- /** The lockfile path of a package, relative to the root. A shared lockfile is the root's, indexed by the package directory. */
916
- function lockPath(shared, directory) {
917
- return shared ? LOCKFILE : relative$1(directory, LOCKFILE);
1070
+ function documentCopies(lockfile) {
1071
+ const copies = /* @__PURE__ */ new Map();
1072
+ const packages = mapping(lockfile, "packages");
1073
+ for (const parsed of keys(packages).map(packageKey)) if (parsed && SINGLETON.test(parsed.name)) copies.set(parsed.name, (copies.get(parsed.name) ?? /* @__PURE__ */ new Map()).set(parsed.version, /* @__PURE__ */ new Set()));
1074
+ const importers = mapping(lockfile, "importers");
1075
+ for (const importer of importers ? keys(importers) : ["."]) addPullers(copies, importers ? mapping(importers, importer) : lockfile, DIRECT_FIELDS, `importer "${importer}"`);
1076
+ const resolved = mapping(lockfile, "snapshots") ?? packages;
1077
+ for (const key of keys(resolved)) addPullers(copies, mapping(resolved, key), PACKAGE_FIELDS, withoutPeers(key.replace(/^\//u, "")));
1078
+ return copies;
918
1079
  }
919
- function readLock(root, shared, directory, documents) {
920
- const path = join(root, lockPath(shared, directory));
921
- if (!documents.has(path) && existsSync(path)) documents.set(path, parseDocument(readFileSync(path, "utf8")));
922
- const document = documents.get(path);
923
- return document && {
924
- document,
925
- importer: shared ? directory || "." : "."
926
- };
1080
+ function report(file, copies) {
1081
+ return [...copies].filter(([, versions]) => versions.size > 1).map(([name, versions]) => `${file} resolves "${name}" at ${versions.size} versions, and an interface package must load once:\n${[...versions].map(([version, by]) => ` ${version}, pulled by ${[...by].join(", ") || "nothing"}\n`).join("")}${REPAIR}`).join("");
927
1082
  }
928
- /** Adds one package's `docs-files` lines and, when it needs one, its README with the generated blocks. */
929
- function planPackage(root, plan, lock, standard, { directory, ranges, published, node }) {
930
- const readme = relative$1(directory, "README.md");
931
- const docs = relative$1(directory, "docs");
932
- if (!published) return;
933
- if (ranges.size > 0 || existsSync(join(root, readme))) plan.docsFiles.push(readme);
934
- if (isDirectory(root, docs)) plan.docsFiles.push(docs);
935
- const current = existsSync(join(root, readme)) ? readFileSync(join(root, readme), "utf8") : void 0;
936
- const nodeRange = standard && current !== void 0 ? node : void 0;
937
- if (ranges.size === 0 && current === void 0) return;
938
- const rows = [...ranges].map(([name, supported]) => ({
939
- name,
940
- supported,
941
- tested: lock && resolvedVersion(lock, name)
942
- }));
943
- try {
944
- const withRequirements = nodeRange !== void 0 && current !== void 0 ? placeNodeBlock(current, nodeBlock(nodeRange)) : current;
945
- plan.readmes.push({
946
- path: readme,
947
- current,
948
- content: placeModulesBlock(rows.length > 0 ? placeCompatBlock(withRequirements, compatBlock(rows)) : withRequirements ?? "")
949
- });
950
- } catch (error) {
951
- plan.errors.push(`${readme}: ${error instanceof Error ? error.message : String(error)}`);
952
- }
1083
+ /** The `pnpm-lock.yaml` files on disk in the repository, tracked or not yet added, outside what `.gitignore` leaves out. */
1084
+ function pnpmLockfiles(root) {
1085
+ return gitFiles(root).filter((file) => (file === PNPM_LOCK || file.endsWith(`/${PNPM_LOCK}`)) && existsSync(join(root, file)));
953
1086
  }
954
1087
  /**
955
- * Plans the docs-compat block of the root and of every workspace package that is not private and declares an
956
- * `@antelopejs/*` peer, runtime or optional dependency, and the `docs-files` lines covering the root and every workspace
957
- * package that is not private.
958
- * Tested with comes from pnpm-lock.yaml, each package's own when `shared-workspace-lockfile=false`, and is `workspace` for a `link:` dependency; other package managers get a dash.
1088
+ * Fails when a `pnpm-lock.yaml` of the repository resolves an AntelopeJS interface package, any `@antelopejs/interface-*`,
1089
+ * at more than one version: each copy carries its own runtime, so two copies in one process break the contract between
1090
+ * modules, or throw on a runtime protocol mismatch. Names, for each version, the importers and packages that pull it.
1091
+ * Reads the lockfiles only: it spawns no package manager, writes no file and fetches nothing. Returns what failed, empty
1092
+ * when every interface package resolves once.
959
1093
  */
960
- function planDocs(root, manager) {
961
- const rootManifest = readManifest(root, "");
962
- const packages = ["", ...workspaceDirectories(root)].map((directory) => {
963
- const manifest = directory ? readManifest(root, directory) : rootManifest;
964
- return {
965
- directory,
966
- published: !directory || !manifest.private,
967
- node: manifest.engines?.node,
968
- ranges: manifest.private ? /* @__PURE__ */ new Map() : declaredRanges(manifest)
969
- };
970
- });
971
- const qualifying = packages.filter(({ ranges }) => ranges.size > 0);
972
- const plan = {
973
- readmes: [],
974
- docsFiles: [],
975
- errors: [],
976
- exists: (path) => existsSync(join(root, path))
977
- };
978
- const shared = sharesLockfile(root);
979
- const documents = /* @__PURE__ */ new Map();
980
- const locks = new Map(qualifying.map(({ directory }) => [directory, manager === "pnpm" ? readLock(root, shared, directory, documents) : void 0]));
981
- const missing = manager === "pnpm" ? qualifying.filter(({ directory }) => !locks.get(directory)) : [];
982
- if (missing.length) {
983
- for (const path of new Set(missing.map(({ directory }) => lockPath(shared, directory)))) plan.errors.push(`${path} is missing, and the docs-compat block reads Tested with from it: run pnpm install, then rerun antelopejs-sync.`);
984
- return plan;
985
- }
986
- const standard = rootManifest.antelopeJs?.docs?.standard === true;
987
- for (const item of packages) planPackage(root, plan, locks.get(item.directory), standard, item);
988
- return plan;
1094
+ function checkSingletonPackages(root) {
1095
+ return pnpmLockfiles(root).map((file) => {
1096
+ try {
1097
+ return lockfileDocuments(join(root, file)).map((document) => report(file, documentCopies(document))).join("");
1098
+ } catch (error) {
1099
+ if (error instanceof Unreadable) return `${file}: could not read it as a lockfile version this check knows.\n`;
1100
+ throw error;
1101
+ }
1102
+ }).join("");
989
1103
  }
990
1104
  //#endregion
991
1105
  //#region src/guardrails/script-steps.ts
@@ -1503,4 +1617,4 @@ async function runChecks(root, options = {}) {
1503
1617
  };
1504
1618
  }
1505
1619
  //#endregion
1506
- export { stepsOf as a, matchingScripts as i, droppedChecksSteps as n, planDocs as o, runChecks as r, workspaceDirectories as s, CHECKS_SKIP_ENV as t };
1620
+ export { stepsOf as a, workspacePatterns as c, matchingScripts as i, droppedChecksSteps as n, planDocs as o, runChecks as r, workspaceDirectories as s, CHECKS_SKIP_ENV as t };