@antelopejs/tooling-configs 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/sync.mjs CHANGED
@@ -1,20 +1,92 @@
1
1
  #!/usr/bin/env node
2
2
  import { a as formatCeilings, l as readCeilings, s as isRetired, t as CEILINGS_FILE } from "../ceilings-B7KayYIG.mjs";
3
- import { a as parseManifest, c as toolingVersions, i as packageManager, o as repositoryTools, r as managedPackage, s as templatePackage, t as addedDevDependencies } from "../package-Dn7VTFUW.mjs";
4
- import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-lJBZFskp.mjs";
3
+ import { t as admits } from "../semver-BDxeEcP_.mjs";
4
+ import { a as managedPackage, c as repositoryTools, d as toolingVersions, f as usesNuxt, l as serializeManifest, n as bootstrapDependencies, o as packageManager, r as bootstrappedManifest, s as parseManifest, t as addedDevDependencies, u as templatePackage } from "../package-DiaBP7bI.mjs";
5
+ import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-C6cfOd2H.mjs";
5
6
  import { a as VERIFY_KINDS, c as isVerifyKind, i as SYNCED_SKILL_FILES, l as skillFolder, o as claudeLink, s as claudeLinkTarget, u as planDocsSkills } from "../shared-igPpEDpS.mjs";
6
7
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
8
+ import { c as CI_CONTEXT, f as ciWorkflow, i as hasChecksWorkflow, n as ciNodeCallers, p as placeholderTestScript, r as ciRenovateSyncCallers, s as renovateArtifacts, t as MISSING_CHECKS_WORKFLOW, u as CI_PATH } from "../workflow-CPcNc8KL.mjs";
7
9
  import { a as gitFiles, c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
8
- import { i as recordedRelease, t as measureBaseline } from "../ratchet-ClfblHNJ.mjs";
9
- import { a as ciWorkflow, c as ciNodeCallers, l as ciRenovateSyncCallers, o as placeholderTestScript, p as renovateArtifacts, r as CI_PATH, s as MISSING_CHECKS_WORKFLOW, u as hasChecksWorkflow } from "../ci-workflow-COJUT12b.mjs";
10
- import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Dvb_IqBo.mjs";
10
+ import { i as recordedRelease, t as measureBaseline } from "../ratchet-BZvlFCWL.mjs";
11
+ import { a as stepsOf, i as matchingScripts, n as droppedChecksSteps, o as planDocs, s as workspaceDirectories } from "../checks-BFGuy1KI.mjs";
12
+ import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-DgYdu6JK.mjs";
13
+ import { u as typescript } from "../suppressions-CQTcKCi1.mjs";
11
14
  import { t as DEFAULT_SHARED } from "../map-DRyYz_Fw.mjs";
15
+ import { createRequire } from "node:module";
12
16
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
13
17
  import { basename, dirname, join, posix, resolve } from "node:path";
14
- import { execFileSync } from "node:child_process";
15
- import { isMap, isScalar, isSeq, parseDocument } from "yaml";
18
+ import { execFileSync, spawnSync } from "node:child_process";
19
+ import { isMap, isScalar, parseDocument } from "yaml";
16
20
  import ts from "typescript";
17
21
  import { parseArgs } from "node:util";
22
+ //#region src/guardrails/docs-typescript.ts
23
+ const MARKDOWN = /\.(?:md|mdc)$/i;
24
+ const UNPUBLISHED_FOLDER = "design";
25
+ const UNPUBLISHED_FILE = /grill.*\.md$/;
26
+ const FENCE = /^[\s>]*(`{3,}|~{3,})\s*([^\s[{`]*)(.*)$/;
27
+ const TYPESCRIPT_LANGUAGES = /* @__PURE__ */ new Set([
28
+ "ts",
29
+ "typescript",
30
+ "tsx",
31
+ "mts",
32
+ "cts"
33
+ ]);
34
+ const FRAGMENT = "fragment";
35
+ const DOCS_API = /<!--\s*docs-api:/;
36
+ /** Whether one fence opener is a TypeScript fence the docs check typechecks: a TypeScript language not flagged `fragment`. */
37
+ function checkedFence(language, info) {
38
+ if (!TYPESCRIPT_LANGUAGES.has(language.toLowerCase())) return false;
39
+ return !info.replace(/\[[^\]]*\]|\{[^}]*\}/g, " ").split(/\s+/).includes(FRAGMENT);
40
+ }
41
+ /** Whether a Markdown file needs a tsconfig in the docs check: it holds a checked TypeScript fence or a `docs-api` page. */
42
+ function typed(text) {
43
+ if (DOCS_API.test(text)) return true;
44
+ let open;
45
+ for (const line of text.split(/\r?\n/)) {
46
+ const fence = FENCE.exec(line);
47
+ if (!fence) continue;
48
+ const [, marker, language, info] = fence;
49
+ if (open === void 0) {
50
+ open = marker;
51
+ if (checkedFence(language, info)) return true;
52
+ } else if (marker.startsWith(open) && language === "" && info.trim() === "") open = void 0;
53
+ }
54
+ return false;
55
+ }
56
+ /** The Markdown files a `docs-files` entry selects, as the docs check walks it. */
57
+ function markdownFiles(root, path, base = path) {
58
+ const absolute = join(root, path);
59
+ const stat = statSync(absolute, { throwIfNoEntry: false });
60
+ if (!stat) return [];
61
+ if (!stat.isDirectory()) return MARKDOWN.test(path) ? [path] : [];
62
+ return readdirSync(absolute).flatMap((name) => `${path}/${name}` === `${base}/${UNPUBLISHED_FOLDER}` || UNPUBLISHED_FILE.test(name) ? [] : markdownFiles(root, `${path}/${name}`, base));
63
+ }
64
+ /**
65
+ * The docs files, relative to `root`, that hold TypeScript fences or `docs-api`
66
+ * pages the docs check typechecks, under a CI caller job that lists them in
67
+ * `docs-files` but sets no `docs-typescript-project`.
68
+ */
69
+ function untypedDocsFiles(root) {
70
+ const path = join(root, CI_PATH);
71
+ if (!existsSync(path)) return [];
72
+ const jobs = parseDocument(readFileSync(path, "utf8")).get("jobs", true);
73
+ if (!isMap(jobs)) return [];
74
+ const found = /* @__PURE__ */ new Set();
75
+ for (const { value: job } of jobs.items) {
76
+ const inputs = isMap(job) ? job.get("with", true) : void 0;
77
+ if (!isMap(inputs)) continue;
78
+ const project = inputs.get("docs-typescript-project", true);
79
+ const files = inputs.get("docs-files", true);
80
+ if (isScalar(project) && String(project.value).trim() || !isScalar(files)) continue;
81
+ for (const entry of String(files.value).split("\n")) {
82
+ const trimmed = entry.trim().replace(/\/+$/, "");
83
+ if (!trimmed) continue;
84
+ for (const file of markdownFiles(root, trimmed)) if (typed(readFileSync(join(root, file), "utf8"))) found.add(file);
85
+ }
86
+ }
87
+ return [...found];
88
+ }
89
+ //#endregion
18
90
  //#region src/guardrails/agents-block.ts
19
91
  const AGENTS_BLOCK_START = "<!-- antelopejs-guardrails:start -->";
20
92
  const AGENTS_BLOCK_END = "<!-- antelopejs-guardrails:end -->";
@@ -184,6 +256,63 @@ function agentsBlock(context) {
184
256
  ].join("\n");
185
257
  }
186
258
  //#endregion
259
+ //#region src/guardrails/pnpm-workspace.ts
260
+ const PATH = "pnpm-workspace.yaml";
261
+ /** Whether the pinned pnpm reads settings from a `pnpm-workspace.yaml` without `packages`, which pnpm before 10.5 rejects. An unpinned pnpm counts as current. */
262
+ function readsSettings(manifest) {
263
+ const pinned = manifest.packageManager?.split("@")[1];
264
+ return pinned === void 0 || admits(">=10.5.0", pinned);
265
+ }
266
+ /**
267
+ * `current` with `allowBuilds.lefthook` set to `false` unless the repository already decides it.
268
+ * pnpm 11 fails an install on a dependency build it was not told about, and the synced `prepare` script runs `lefthook install` itself.
269
+ */
270
+ function withLefthookDecided(current = "") {
271
+ const document = parseDocument(current);
272
+ if (document.errors.length) throw new Error(`${PATH}: ${document.errors.map(({ message }) => message).join("; ")}`);
273
+ if (document.toJS() == null) {
274
+ const kept = current.trimStart();
275
+ return `${kept}${kept === "" || kept.endsWith("\n") ? "" : "\n"}allowBuilds:\n lefthook: false\n`;
276
+ }
277
+ if (!isMap(document.contents)) throw new Error(`${PATH} must contain a YAML mapping.`);
278
+ if (document.get("allowBuilds") == null) document.set("allowBuilds", document.createNode({}));
279
+ const builds = document.get("allowBuilds");
280
+ if (!isMap(builds)) throw new Error(`${PATH}: allowBuilds must be a mapping.`);
281
+ if (builds.get("lefthook") != null) return current;
282
+ document.contents.flow = false;
283
+ builds.flow = false;
284
+ builds.set("lefthook", false);
285
+ return document.toString({
286
+ lineWidth: 0,
287
+ flowCollectionPadding: false
288
+ });
289
+ }
290
+ /** The `pnpm-workspace.yaml` a full-profile pnpm repository needs so pnpm 11 and later install lefthook without `ERR_PNPM_IGNORED_BUILDS`. */
291
+ function pnpmWorkspaceArtifacts(root, manifest, managed) {
292
+ if (!managed || packageManager(manifest) !== "pnpm") return [];
293
+ const file = join(root, PATH);
294
+ const current = existsSync(file) ? readFileSync(file, "utf8") : void 0;
295
+ if (current === void 0 && !readsSettings(manifest)) return [];
296
+ try {
297
+ const content = withLefthookDecided(current);
298
+ return [content === current ? {
299
+ kind: "unchanged",
300
+ path: PATH
301
+ } : {
302
+ kind: "write",
303
+ path: PATH,
304
+ content,
305
+ mode: void 0
306
+ }];
307
+ } catch (error) {
308
+ return [{
309
+ kind: "error",
310
+ path: PATH,
311
+ message: `${error instanceof Error ? error.message : String(error)} Add \`allowBuilds: { lefthook: false }\` to it, then rerun antelopejs-sync.`
312
+ }];
313
+ }
314
+ }
315
+ //#endregion
187
316
  //#region src/guardrails/backend-boundary.ts
188
317
  /** Where a DMS frontend layer keeps its backend boundary plugin, relative to the layer. */
189
318
  const BACKEND_BOUNDARY_FILE = "build/backend-boundary.ts";
@@ -426,363 +555,6 @@ function checkEntryOnlyConfiguration(root) {
426
555
  };
427
556
  }
428
557
  //#endregion
429
- //#region src/guardrails/markdown-table.ts
430
- /** The lines of a Markdown table whose first row is the header, columns padded as oxfmt leaves them. */
431
- function tableLines(table) {
432
- const widths = table[0].map((_, column) => Math.max(3, ...table.map((row) => row[column].length)));
433
- const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
434
- return [
435
- line(table[0]),
436
- line(widths.map((width) => "-".repeat(width))),
437
- ...table.slice(1).map(line)
438
- ];
439
- }
440
- //#endregion
441
- //#region src/guardrails/docs-modules.ts
442
- const DMS_MODULES_START = "<!-- antelopejs-dms-modules:start -->";
443
- const DMS_MODULES_END = "<!-- antelopejs-dms-modules:end -->";
444
- const ORGANIZATION = "https://github.com/AntelopeJS";
445
- /** The AntelopeJS DMS modules in display order. Every README holding the markers lists exactly these. */
446
- const DMS_MODULES = [
447
- {
448
- repo: "dms-builder",
449
- row: "Edit pages, tables and data sources by clicking, as TypeScript that compiles"
450
- },
451
- {
452
- repo: "dms-ai",
453
- row: "An assistant chat in the dashboard, on your own Claude Code or Codex"
454
- },
455
- {
456
- repo: "dms-database",
457
- row: "Schemas, relation diagrams, a data browser and a query console"
458
- },
459
- {
460
- repo: "dms-api",
461
- row: "API health, request logs, per-route statistics and a request tester"
462
- },
463
- {
464
- repo: "dms-automation",
465
- row: "Node-graph automations on schedules, webhooks and DMS events, with a trace for every run"
466
- },
467
- {
468
- repo: "dms-mailing",
469
- row: "E-mail templates in a block editor, versions, a send log and delivery metrics"
470
- },
471
- {
472
- repo: "dms-lang",
473
- row: "Translation coverage, a translation matrix and a translation queue"
474
- },
475
- {
476
- repo: "dms-media",
477
- row: "A media library with folders, per-folder permissions, image sizes and light editing"
478
- },
479
- {
480
- repo: "dms-saas",
481
- row: "Self-service sign-up, plans that gate features, and Stripe billing"
482
- },
483
- {
484
- repo: "dms-marketing",
485
- row: "Traffic, conversion funnels with A/B splits and click heatmaps, without cookies"
486
- },
487
- {
488
- repo: "dms-frontend",
489
- row: "The `ajs dms` CLI, the Vue renderer and the SDK every frontend module builds on"
490
- }
491
- ];
492
- /** The generated block, formatted as oxfmt leaves it. */
493
- function modulesBlock() {
494
- return [
495
- DMS_MODULES_START,
496
- "",
497
- ...tableLines([["Module", "What it adds"], ...DMS_MODULES.map(({ repo, row }) => [`[\`${repo}\`](${ORGANIZATION}/${repo})`, row])]),
498
- "",
499
- DMS_MODULES_END,
500
- ""
501
- ].join("\n");
502
- }
503
- /** The README with the block between its markers rewritten. A README without markers comes back as it is. */
504
- function placeModulesBlock(current) {
505
- const start = current.indexOf(DMS_MODULES_START);
506
- const end = current.indexOf(DMS_MODULES_END);
507
- const starts = current.split(DMS_MODULES_START).length - 1;
508
- const ends = current.split(DMS_MODULES_END).length - 1;
509
- if (starts === 0 && ends === 0) return current;
510
- 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.");
511
- return `${current.slice(0, start)}${modulesBlock()}${current.slice(end + 35).replace(/^\r?\n/, "")}`;
512
- }
513
- //#endregion
514
- //#region src/guardrails/docs-compat.ts
515
- const DOCS_COMPAT_START = "<!-- antelopejs-docs-compat:start -->";
516
- const DOCS_COMPAT_END = "<!-- antelopejs-docs-compat:end -->";
517
- const DOCS_NODE_START = "<!-- antelopejs-docs-node:start -->";
518
- const DOCS_NODE_END = "<!-- antelopejs-docs-node:end -->";
519
- const LOCKFILE = "pnpm-lock.yaml";
520
- const REQUIREMENTS_HEADING = /^##\s+Requirements\s*$/i;
521
- const SCOPE = "@antelopejs/";
522
- const UNRESOLVED = "—";
523
- const LEGACY_MARKER = /^<!--\s*docs-compat:\s*\.\/package\.json#\w+\s*-->\s*$/;
524
- const COMPATIBILITY_HEADING = /^##\s+Compatibility\s*$/i;
525
- const RESOLVED_SECTIONS = [
526
- "dependencies",
527
- "optionalDependencies",
528
- "devDependencies"
529
- ];
530
- /** The generated block, rows sorted by package name, formatted as oxfmt leaves it. */
531
- function compatBlock(rows) {
532
- const sorted = [...rows].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
533
- return [
534
- DOCS_COMPAT_START,
535
- "",
536
- ...tableLines([[
537
- "Package",
538
- "Supported",
539
- "Tested with"
540
- ], ...sorted.map(({ name, supported, tested }) => [
541
- `\`${name}\``,
542
- `\`${supported.replaceAll("|", "\\|")}\``,
543
- tested === void 0 ? UNRESOLVED : `\`${tested}\``
544
- ])]),
545
- "",
546
- DOCS_COMPAT_END,
547
- ""
548
- ].join("\n");
549
- }
550
- function legacySpanEnd(lines, marker) {
551
- let index = marker + 1;
552
- while (index < lines.length && !lines[index].trim()) index++;
553
- while (index < lines.length && lines[index].trimStart().startsWith("|")) index++;
554
- while (index < lines.length && !lines[index].trim()) index++;
555
- return index;
556
- }
557
- function replaceLegacyTables(lines, block) {
558
- const placed = [];
559
- let replaced = false;
560
- for (let index = 0; index < lines.length;) {
561
- if (!LEGACY_MARKER.test(lines[index])) {
562
- placed.push(lines[index]);
563
- index++;
564
- continue;
565
- }
566
- if (!replaced) placed.push(...block.split("\n"));
567
- replaced = true;
568
- index = legacySpanEnd(lines, index);
569
- }
570
- return replaced ? placed : void 0;
571
- }
572
- function finalNewline(text) {
573
- return text.endsWith("\n") ? text : `${text}\n`;
574
- }
575
- /** The README with the block in place: replacing the markers, a legacy `docs-compat` table, or under `## Compatibility`. */
576
- function placeCompatBlock(current, block) {
577
- const text = current ?? "";
578
- const start = text.indexOf(DOCS_COMPAT_START);
579
- const end = text.indexOf(DOCS_COMPAT_END);
580
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-compat markers. Repair or delete them, then rerun antelopejs-sync.");
581
- if (start !== -1) return `${text.slice(0, start)}${block}${text.slice(end + 35).replace(/^\r?\n/, "")}`;
582
- const lines = text.split("\n");
583
- const legacy = replaceLegacyTables(lines, block);
584
- if (legacy) return finalNewline(legacy.join("\n"));
585
- const heading = lines.findIndex((line) => COMPATIBILITY_HEADING.test(line));
586
- if (heading !== -1) {
587
- let rest = heading + 1;
588
- while (rest < lines.length && !lines[rest].trim()) rest++;
589
- return finalNewline([
590
- ...lines.slice(0, heading + 1),
591
- "",
592
- ...block.split("\n"),
593
- ...lines.slice(rest)
594
- ].join("\n"));
595
- }
596
- const before = text.trimEnd();
597
- return `${before}${before ? "\n\n" : ""}## Compatibility\n\n${block}`;
598
- }
599
- /** The generated Node prerequisite block for an `engines.node` range, formatted as oxfmt leaves it. */
600
- function nodeBlock(range) {
601
- return `${DOCS_NODE_START}\n\nThis package requires Node.js \`${range}\`.\n${DOCS_NODE_END}\n`;
602
- }
603
- /** The README with the Node block in place: between its markers, under `## Requirements`, or in a new `## Requirements` section at the end. */
604
- function placeNodeBlock(current, block) {
605
- const start = current.indexOf(DOCS_NODE_START);
606
- const end = current.indexOf(DOCS_NODE_END);
607
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-node markers. Repair or delete them, then rerun antelopejs-sync.");
608
- if (start !== -1) return `${current.slice(0, start)}${block}${current.slice(end + 33).replace(/^\r?\n/, "")}`;
609
- const lines = current.split("\n");
610
- const heading = lines.findIndex((line) => REQUIREMENTS_HEADING.test(line));
611
- if (heading !== -1) {
612
- let rest = heading + 1;
613
- while (rest < lines.length && !lines[rest].trim()) rest++;
614
- return finalNewline([
615
- ...lines.slice(0, heading + 1),
616
- "",
617
- ...block.trimEnd().split("\n"),
618
- ...rest < lines.length ? ["", ...lines.slice(rest)] : []
619
- ].join("\n"));
620
- }
621
- return `${current.trimEnd()}\n\n## Requirements\n\n${block}`;
622
- }
623
- function relative$1(directory, name) {
624
- return directory ? `${directory}/${name}` : name;
625
- }
626
- function isDirectory(root, path) {
627
- return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
628
- }
629
- function subdirectories(root, directory) {
630
- 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));
631
- }
632
- function descendants(root, directory) {
633
- return subdirectories(root, directory).flatMap((child) => [child, ...descendants(root, child)]);
634
- }
635
- function globExpression(pattern) {
636
- const source = pattern.split("/").map((segment) => segment === "**" ? "(?:.*)" : segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*").replaceAll("?", "[^/]")).join("/").replaceAll("(?:.*)/", "(?:.*/)?");
637
- return new RegExp(`^${source}$`);
638
- }
639
- function expand(root, pattern) {
640
- let directories = [""];
641
- for (const segment of pattern.split("/")) if (segment === "**") directories = directories.flatMap((directory) => [directory, ...descendants(root, directory)]);
642
- else if (/[*?]/.test(segment)) {
643
- const expression = globExpression(segment);
644
- directories = directories.flatMap((directory) => subdirectories(root, directory).filter((child) => expression.test(child.slice(child.lastIndexOf("/") + 1))));
645
- } else directories = directories.map((directory) => relative$1(directory, segment)).filter((directory) => isDirectory(root, directory));
646
- return directories;
647
- }
648
- function normalizePattern(pattern) {
649
- return pattern.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "");
650
- }
651
- function scalarItems(document, path) {
652
- const node = document.getIn(path, true);
653
- return isSeq(node) ? node.items.flatMap((item) => isScalar(item) ? [String(item.value)] : []) : [];
654
- }
655
- /** pnpm-workspace.yaml `packages`, else package.json `workspaces` as an array or as `{ packages }`; JSON parses as YAML. */
656
- function workspacePatterns(root) {
657
- const pnpm = join(root, "pnpm-workspace.yaml");
658
- if (existsSync(pnpm)) return scalarItems(parseDocument(readFileSync(pnpm, "utf8")), ["packages"]);
659
- const manifest = parseDocument(readFileSync(join(root, "package.json"), "utf8"));
660
- return scalarItems(manifest, isMap(manifest.get("workspaces", true)) ? ["workspaces", "packages"] : ["workspaces"]);
661
- }
662
- function workspaceDirectories(root) {
663
- const patterns = workspacePatterns(root);
664
- const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => globExpression(normalizePattern(pattern.slice(1))));
665
- const found = /* @__PURE__ */ new Set();
666
- for (const pattern of patterns.filter((item) => !item.startsWith("!"))) {
667
- const normalized = normalizePattern(pattern);
668
- 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);
669
- }
670
- return [...found].sort();
671
- }
672
- function declaredRanges(manifest) {
673
- const ranges = /* @__PURE__ */ new Map();
674
- for (const field of [
675
- manifest.optionalDependencies,
676
- manifest.dependencies,
677
- manifest.peerDependencies
678
- ]) for (const [name, range] of Object.entries(field ?? {})) if (name.startsWith(SCOPE)) ranges.set(name, range);
679
- return ranges;
680
- }
681
- function readManifest(root, directory) {
682
- return parseManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
683
- }
684
- function linkedVersion(root, directory, link) {
685
- const target = join(root, directory, link);
686
- return existsSync(join(target, "package.json")) ? parseManifest(readFileSync(join(target, "package.json"), "utf8")).version : void 0;
687
- }
688
- function resolvedVersion(root, { document, importer }, directory, name) {
689
- for (const section of RESOLVED_SECTIONS) {
690
- const entry = document.getIn([
691
- "importers",
692
- importer,
693
- section,
694
- name
695
- ], true);
696
- const version = isMap(entry) ? entry.get("version", true) : entry;
697
- if (!isScalar(version)) continue;
698
- const resolved = String(version.value).split("(")[0];
699
- return resolved.startsWith("link:") ? linkedVersion(root, directory, resolved.slice(5)) : resolved;
700
- }
701
- }
702
- const UNSHARED_NPMRC = /^\s*shared-workspace-lockfile\s*=\s*false\s*(?:[#;].*)?$/m;
703
- /** Whether the workspace keeps one root lockfile, or `shared-workspace-lockfile=false` gives each package its own. */
704
- function sharesLockfile(root) {
705
- const npmrc = join(root, ".npmrc");
706
- if (existsSync(npmrc) && UNSHARED_NPMRC.test(readFileSync(npmrc, "utf8"))) return false;
707
- const workspace = join(root, "pnpm-workspace.yaml");
708
- return !(existsSync(workspace) && parseDocument(readFileSync(workspace, "utf8")).get("sharedWorkspaceLockfile") === false);
709
- }
710
- /** The lockfile path of a package, relative to the root. A shared lockfile is the root's, indexed by the package directory. */
711
- function lockPath(shared, directory) {
712
- return shared ? LOCKFILE : relative$1(directory, LOCKFILE);
713
- }
714
- function readLock(root, shared, directory, documents) {
715
- const path = join(root, lockPath(shared, directory));
716
- if (!documents.has(path) && existsSync(path)) documents.set(path, parseDocument(readFileSync(path, "utf8")));
717
- const document = documents.get(path);
718
- return document && {
719
- document,
720
- importer: shared ? directory || "." : "."
721
- };
722
- }
723
- /** Adds one package's `docs-files` lines and, when it needs one, its README with the generated blocks. */
724
- function planPackage(root, plan, lock, standard, { directory, ranges, published, node }) {
725
- const readme = relative$1(directory, "README.md");
726
- const docs = relative$1(directory, "docs");
727
- if (!published) return;
728
- if (ranges.size > 0 || existsSync(join(root, readme))) plan.docsFiles.push(readme);
729
- if (isDirectory(root, docs)) plan.docsFiles.push(docs);
730
- const current = existsSync(join(root, readme)) ? readFileSync(join(root, readme), "utf8") : void 0;
731
- const nodeRange = standard && current !== void 0 ? node : void 0;
732
- if (ranges.size === 0 && current === void 0) return;
733
- const rows = [...ranges].map(([name, supported]) => ({
734
- name,
735
- supported,
736
- tested: lock && resolvedVersion(root, lock, directory, name)
737
- }));
738
- try {
739
- const withRequirements = nodeRange !== void 0 && current !== void 0 ? placeNodeBlock(current, nodeBlock(nodeRange)) : current;
740
- plan.readmes.push({
741
- path: readme,
742
- current,
743
- content: placeModulesBlock(rows.length > 0 ? placeCompatBlock(withRequirements, compatBlock(rows)) : withRequirements ?? "")
744
- });
745
- } catch (error) {
746
- plan.errors.push(`${readme}: ${error instanceof Error ? error.message : String(error)}`);
747
- }
748
- }
749
- /**
750
- * Plans the docs-compat block of the root and of every workspace package that is not private and declares an
751
- * `@antelopejs/*` peer, runtime or optional dependency, and the `docs-files` lines covering the root and every workspace
752
- * package that is not private.
753
- * Tested with comes from pnpm-lock.yaml, each package's own when `shared-workspace-lockfile=false`; other package managers get a dash.
754
- */
755
- function planDocs(root, manager) {
756
- const rootManifest = readManifest(root, "");
757
- const packages = ["", ...workspaceDirectories(root)].map((directory) => {
758
- const manifest = directory ? readManifest(root, directory) : rootManifest;
759
- return {
760
- directory,
761
- published: !directory || !manifest.private,
762
- node: manifest.engines?.node,
763
- ranges: manifest.private ? /* @__PURE__ */ new Map() : declaredRanges(manifest)
764
- };
765
- });
766
- const qualifying = packages.filter(({ ranges }) => ranges.size > 0);
767
- const plan = {
768
- readmes: [],
769
- docsFiles: [],
770
- errors: [],
771
- exists: (path) => existsSync(join(root, path))
772
- };
773
- const shared = sharesLockfile(root);
774
- const documents = /* @__PURE__ */ new Map();
775
- const locks = new Map(qualifying.map(({ directory }) => [directory, manager === "pnpm" ? readLock(root, shared, directory, documents) : void 0]));
776
- const missing = manager === "pnpm" ? qualifying.filter(({ directory }) => !locks.get(directory)) : [];
777
- if (missing.length) {
778
- 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.`);
779
- return plan;
780
- }
781
- const standard = rootManifest.antelopeJs?.docs?.standard === true;
782
- for (const item of packages) planPackage(root, plan, locks.get(item.directory), standard, item);
783
- return plan;
784
- }
785
- //#endregion
786
558
  //#region src/guardrails/template-agent-layer.ts
787
559
  /** The folders a project scaffolded from a template does not get, as `ajs project init` excludes them. */
788
560
  const SCAFFOLD_EXCLUDED_PATHS = [".agents/", ".claude/skills/"];
@@ -867,182 +639,6 @@ function releaseHooks(files) {
867
639
  return [...hooksIn(files, ".release-it.json", ["hooks"]), ...hooksIn(files, "package.json", ["release-it", "hooks"])];
868
640
  }
869
641
  //#endregion
870
- //#region src/guardrails/script-steps.ts
871
- const SEPARATORS = /&&|\|\||[;|\n]|(?<![>&])&(?!&)/u;
872
- const ENV_ASSIGNMENT = /^[A-Za-z_]\w*=/u;
873
- const TSC_COMMAND = /(?:^|[\\/])tsc(?:\.js)?$/u;
874
- const MANAGERS = /* @__PURE__ */ new Set([
875
- "pnpm",
876
- "npm",
877
- "yarn",
878
- "bun"
879
- ]);
880
- const NPM_BUILTINS = /* @__PURE__ */ new Set([
881
- "test",
882
- "start",
883
- "stop",
884
- "restart"
885
- ]);
886
- const WRAPPERS = /* @__PURE__ */ new Set([
887
- "cross-env",
888
- "cross-env-shell",
889
- "env",
890
- "corepack"
891
- ]);
892
- const EXEC_RUNNERS = /* @__PURE__ */ new Set([
893
- "npx",
894
- "bunx",
895
- "pnpx"
896
- ]);
897
- const EXEC_VERBS = /* @__PURE__ */ new Set([
898
- "exec",
899
- "x",
900
- "dlx"
901
- ]);
902
- const RUN_ALL = /* @__PURE__ */ new Set([
903
- "run-s",
904
- "run-p",
905
- "npm-run-all",
906
- "npm-run-all2"
907
- ]);
908
- const RUN_ALL_VALUED = /* @__PURE__ */ new Set(["--max-parallel", "--npm-path"]);
909
- const EXEC_VALUED = /* @__PURE__ */ new Set([
910
- "-p",
911
- "--package",
912
- "-c",
913
- "--call"
914
- ]);
915
- const TARGET_VALUED = /* @__PURE__ */ new Set([
916
- "--filter",
917
- "-F",
918
- "--dir",
919
- "-C",
920
- "--prefix",
921
- "--cwd",
922
- "--workspace"
923
- ]);
924
- const TARGET_FLAGS = /* @__PURE__ */ new Set([
925
- "-r",
926
- "--recursive",
927
- "--workspaces",
928
- "-ws"
929
- ]);
930
- function words(segment) {
931
- return segment.replace(/[()]/gu, " ").split(/\s+/u).map((word) => word.replace(/^["']|["']$/gu, "")).filter(Boolean);
932
- }
933
- /** The simple commands of a script: `&&`, `||`, `;`, `|`, `&`, newlines and parentheses all end one. */
934
- function lines(script) {
935
- return script.split(SEPARATORS).map(words).filter((list) => list.length > 0);
936
- }
937
- /** Skips the options from `from`, and the values of those that take one; `elsewhere` when one points at another package. */
938
- function skipOptions(args, from, valued) {
939
- let index = from;
940
- let elsewhere = false;
941
- while (index < args.length && args[index].startsWith("-")) {
942
- const [name, ...value] = args[index].split("=");
943
- elsewhere ||= TARGET_VALUED.has(name) || TARGET_FLAGS.has(name);
944
- index += valued.has(name) && value.length === 0 ? 2 : 1;
945
- }
946
- return {
947
- index,
948
- elsewhere
949
- };
950
- }
951
- function isTsc(word) {
952
- return TSC_COMMAND.test(word);
953
- }
954
- /** `tsc`, a path to it, or `node` running one. */
955
- function programSteps(line) {
956
- const [head, ...rest] = line;
957
- if (head === void 0) return [];
958
- if (isTsc(head)) return [{
959
- kind: "tsc",
960
- args: rest
961
- }];
962
- if (head !== "node") return [];
963
- if (rest[0] === "--run" && rest[1] !== void 0) return [{
964
- kind: "script",
965
- names: [rest[1]],
966
- elsewhere: false
967
- }];
968
- const at = rest.findIndex((word) => !word.startsWith("-"));
969
- return at !== -1 && isTsc(rest[at]) ? [{
970
- kind: "tsc",
971
- args: rest.slice(at + 1)
972
- }] : [];
973
- }
974
- /** What `npx`, `pnpm exec` and `npm exec` run: the command after the options and the packages they name. */
975
- function execSteps(args) {
976
- return programSteps(args.slice(skipOptions(args, 0, EXEC_VALUED).index));
977
- }
978
- function managerSteps(manager, args) {
979
- const valued = new Set(TARGET_VALUED);
980
- if (manager === "npm") valued.add("-w");
981
- const first = skipOptions(args, 0, valued);
982
- const verb = args[first.index];
983
- if (verb === void 0) return [];
984
- if (EXEC_VERBS.has(verb)) return execSteps(args.slice(first.index + 1));
985
- if (verb === "run" || verb === "run-script") {
986
- const second = skipOptions(args, first.index + 1, valued);
987
- const name = args[second.index];
988
- return name === void 0 ? [] : [{
989
- kind: "script",
990
- names: [name],
991
- elsewhere: first.elsewhere || second.elsewhere
992
- }];
993
- }
994
- if (isTsc(verb)) return programSteps(args.slice(first.index));
995
- if (manager === "npm" && !NPM_BUILTINS.has(verb)) return [];
996
- return [{
997
- kind: "script",
998
- names: [verb],
999
- elsewhere: first.elsewhere
1000
- }];
1001
- }
1002
- function runAllSteps(args) {
1003
- const names = [];
1004
- for (let index = 0; index < args.length && args[index] !== "--"; index++) if (!args[index].startsWith("-")) names.push(args[index]);
1005
- else if (RUN_ALL_VALUED.has(args[index])) index++;
1006
- return names.length === 0 ? [] : [{
1007
- kind: "script",
1008
- names,
1009
- elsewhere: false
1010
- }];
1011
- }
1012
- /** The line without its leading environment assignments and wrappers (`cross-env A=1`, `env`, `corepack`). */
1013
- function unwrapped(line) {
1014
- let index = 0;
1015
- let wrapped = false;
1016
- while (index < line.length) {
1017
- const word = line[index];
1018
- if (WRAPPERS.has(word)) wrapped = true;
1019
- else if (!ENV_ASSIGNMENT.test(word) && !(wrapped && word.startsWith("-"))) break;
1020
- index++;
1021
- }
1022
- return line.slice(index);
1023
- }
1024
- function lineSteps(line) {
1025
- const [head, ...args] = unwrapped(line);
1026
- if (head === void 0) return [];
1027
- if (RUN_ALL.has(head)) return runAllSteps(args);
1028
- if (MANAGERS.has(head)) return managerSteps(head, args);
1029
- if (EXEC_RUNNERS.has(head)) return execSteps(args);
1030
- return programSteps([head, ...args]);
1031
- }
1032
- /** The scripts and `tsc` runs a script's command lines start. */
1033
- function stepsOf(script) {
1034
- return lines(script).flatMap(lineSteps);
1035
- }
1036
- /** The script names a `run-s` pattern list selects among `available`. */
1037
- function matchingScripts(names, available) {
1038
- const all = [...available];
1039
- return names.flatMap((name) => {
1040
- if (!name.includes("*")) return [name];
1041
- const pattern = new RegExp(`^${name.split("**").map((part) => part.split("*").map((piece) => piece.replace(/[.+?^${}()|[\]\\]/gu, "\\$&")).join("[^:]*")).join(".*")}$`, "u");
1042
- return all.filter((script) => pattern.test(script));
1043
- });
1044
- }
1045
- //#endregion
1046
642
  //#region src/guardrails/tsc-invocation.ts
1047
643
  const ROOT_PROGRAM = "tsconfig.json";
1048
644
  function normalizeProgram(project) {
@@ -1181,7 +777,7 @@ function reach(scripts, name, extra = []) {
1181
777
  })));
1182
778
  for (const { text, depth } of queue) for (const step of stepsOf(text)) {
1183
779
  if (step.kind !== "script") continue;
1184
- for (const script of matchingScripts(step.names, scripts.keys())) if (step.elsewhere) reached.elsewhere.add(script);
780
+ for (const script of matchingScripts(step.names, scripts.keys())) if (step.targets.length) reached.elsewhere.add(script);
1185
781
  else enter(script, depth + 1);
1186
782
  }
1187
783
  return reached;
@@ -1723,10 +1319,13 @@ const MANAGED_ARTIFACTS = [
1723
1319
  {
1724
1320
  path: "package.json",
1725
1321
  profiles: ["full", "template"],
1726
- desired: (current, context) => ({
1727
- content: context.profile === "full" ? managedPackage(current, context.versions, context) : templatePackage(current, context.versions, context),
1728
- notes: []
1729
- })
1322
+ desired: (current, context) => {
1323
+ const content = context.profile === "full" ? managedPackage(current, context.versions, context) : templatePackage(current, context.versions, context);
1324
+ return {
1325
+ content,
1326
+ notes: droppedChecksSteps(current, content)
1327
+ };
1328
+ }
1730
1329
  },
1731
1330
  {
1732
1331
  path: ".nvmrc",
@@ -1870,7 +1469,7 @@ function repositoryContext(root, current, profile, verificationSkill) {
1870
1469
  versions: toolingVersions(),
1871
1470
  tools: repositoryTools(manifest),
1872
1471
  typeAware: /\btypeAware["']?\s*:\s*true\b/.test(desiredLint),
1873
- nuxt: Boolean(manifest.dependencies?.nuxt || manifest.devDependencies?.nuxt || readdirSync(root).some((name) => name.startsWith("nuxt.config."))),
1472
+ nuxt: usesNuxt(root, manifest),
1874
1473
  claude: profile === "full" ? claudeProse(root, current) : "",
1875
1474
  baseline: "",
1876
1475
  suppressionBudget: adoptedBudget(root, current.get(SUPPRESSIONS_FILE)),
@@ -1915,7 +1514,11 @@ function syncRepository(root, options = {}) {
1915
1514
  const writing = planWritingSkills(root, profile, verify.kind);
1916
1515
  const actions = [...verify.actions, ...writing.actions];
1917
1516
  const context = repositoryContext(root, current, profile, verify.verificationSkill);
1918
- const standalone = [...backendBoundaryArtifacts(root), ...renovateArtifacts(root, manifest, profile === "full" || verify.kind === "template")];
1517
+ const standalone = [
1518
+ ...backendBoundaryArtifacts(root),
1519
+ ...renovateArtifacts(root, manifest, profile === "full" || verify.kind === "template"),
1520
+ ...pnpmWorkspaceArtifacts(root, manifest, profile === "full")
1521
+ ];
1919
1522
  let plan = [...planSync(current, modes, context), ...standalone];
1920
1523
  const errors = plan.filter((artifact) => artifact.kind === "error").map(({ message }) => message);
1921
1524
  const entryOnly = checkEntryOnlyConfiguration(root);
@@ -1955,10 +1558,478 @@ function syncRepository(root, options = {}) {
1955
1558
  };
1956
1559
  }
1957
1560
  //#endregion
1561
+ //#region src/guardrails/workspace-members.ts
1562
+ /** Each oxlint `options` key, which oxlint reads only from the root config, and the flag that carries it on a member's own oxlint run. */
1563
+ const OPTION_FLAGS = /* @__PURE__ */ new Map([
1564
+ ["typeAware", {
1565
+ kind: "switch",
1566
+ flag: "--type-aware"
1567
+ }],
1568
+ ["typeCheck", {
1569
+ kind: "switch",
1570
+ flag: "--type-check"
1571
+ }],
1572
+ ["denyWarnings", {
1573
+ kind: "switch",
1574
+ flag: "--deny-warnings"
1575
+ }],
1576
+ ["maxWarnings", {
1577
+ kind: "count",
1578
+ flag: "--max-warnings"
1579
+ }],
1580
+ ["reportUnusedDisableDirectives", {
1581
+ kind: "severity",
1582
+ flag: "--report-unused-disable-directives-severity"
1583
+ }]
1584
+ ]);
1585
+ /** The oxlint config names oxlint discovers in a nested directory. */
1586
+ const LINT_CONFIGS = [
1587
+ "oxlint.config.ts",
1588
+ "oxlint.config.mts",
1589
+ "oxlint.config.cts",
1590
+ "oxlint.config.js",
1591
+ "oxlint.config.mjs",
1592
+ "oxlint.config.cjs",
1593
+ ".oxlintrc.json",
1594
+ ".oxlintrc.jsonc"
1595
+ ];
1596
+ /** A command word `oxlint` in a script, not `oxlint-tsgolint` or a path ending in it. */
1597
+ const OXLINT_COMMAND = /(^|[\s;&|(])oxlint(?=$|[\s;&|)])/g;
1598
+ function unwrapped(node) {
1599
+ const compiler = typescript();
1600
+ let current = node;
1601
+ while (compiler.isParenthesizedExpression(current) || compiler.isAsExpression(current) || compiler.isSatisfiesExpression(current)) current = current.expression;
1602
+ return current;
1603
+ }
1604
+ function variableInitializer(source, name) {
1605
+ const compiler = typescript();
1606
+ for (const statement of source.statements) if (compiler.isVariableStatement(statement)) {
1607
+ for (const declaration of statement.declarationList.declarations) if (compiler.isIdentifier(declaration.name) && declaration.name.text === name) return declaration.initializer;
1608
+ }
1609
+ }
1610
+ /** The object literal a config exports: itself, the first argument of `defineConfig(...)`, or a same-file variable holding either. */
1611
+ function configLiteral(source, node, seen = /* @__PURE__ */ new Set()) {
1612
+ const compiler = typescript();
1613
+ if (node === void 0) return void 0;
1614
+ const value = unwrapped(node);
1615
+ if (compiler.isObjectLiteralExpression(value)) return value;
1616
+ if (compiler.isCallExpression(value)) return configLiteral(source, value.arguments[0], seen);
1617
+ if (!compiler.isIdentifier(value) || seen.has(value.text)) return void 0;
1618
+ seen.add(value.text);
1619
+ return configLiteral(source, variableInitializer(source, value.text), seen);
1620
+ }
1621
+ function exportedConfig(path, text) {
1622
+ const compiler = typescript();
1623
+ if (path.endsWith(".json") || path.endsWith(".jsonc")) {
1624
+ const source = compiler.parseJsonText(path, text);
1625
+ const [statement] = source.statements;
1626
+ return statement && configLiteral(source, statement.expression);
1627
+ }
1628
+ const source = compiler.createSourceFile(path, text, compiler.ScriptTarget.Latest, true);
1629
+ return configLiteral(source, source.statements.find((statement) => compiler.isExportAssignment(statement) && !statement.isExportEquals)?.expression);
1630
+ }
1631
+ function propertyName(element) {
1632
+ const compiler = typescript();
1633
+ const name = element.name;
1634
+ return name !== void 0 && (compiler.isIdentifier(name) || compiler.isStringLiteralLike(name)) ? name.text : void 0;
1635
+ }
1636
+ /** The flag that carries one option value, `""` for a switch set to `false`, or undefined when the value has no flag. */
1637
+ function optionFlag(entry, value) {
1638
+ const compiler = typescript();
1639
+ switch (entry.kind) {
1640
+ case "switch":
1641
+ if (value.kind === compiler.SyntaxKind.TrueKeyword) return entry.flag;
1642
+ return value.kind === compiler.SyntaxKind.FalseKeyword ? "" : void 0;
1643
+ case "count": return compiler.isNumericLiteral(value) ? `${entry.flag}=${value.text}` : void 0;
1644
+ case "severity": return compiler.isStringLiteralLike(value) ? `${entry.flag}=${value.text}` : void 0;
1645
+ }
1646
+ }
1647
+ /** The flags an `options` literal stands for, or the keys no flag can carry. */
1648
+ function optionFlags(options) {
1649
+ const compiler = typescript();
1650
+ const literal = unwrapped(options);
1651
+ if (!compiler.isObjectLiteralExpression(literal)) return { unsupported: ["options"] };
1652
+ const flags = [];
1653
+ const unsupported = [];
1654
+ for (const element of literal.properties) {
1655
+ const name = propertyName(element) ?? element.getText();
1656
+ const entry = OPTION_FLAGS.get(name);
1657
+ const flag = entry && compiler.isPropertyAssignment(element) ? optionFlag(entry, unwrapped(element.initializer)) : void 0;
1658
+ if (flag === void 0) unsupported.push(name);
1659
+ else if (flag) flags.push(flag);
1660
+ }
1661
+ return unsupported.length ? { unsupported } : { flags };
1662
+ }
1663
+ /** `text` without `property`, its separating comma and the line it sat on. */
1664
+ function withoutProperty(text, config, property) {
1665
+ const elements = config.properties;
1666
+ const index = elements.indexOf(property);
1667
+ const next = elements[index + 1];
1668
+ const previous = elements[index - 1];
1669
+ if (next) return text.slice(0, property.getFullStart()) + text.slice(next.getFullStart());
1670
+ if (previous) return text.slice(0, previous.end) + text.slice(property.end);
1671
+ return text.slice(0, config.getStart()) + "{}" + text.slice(config.end);
1672
+ }
1673
+ /** The config without its root-only `options`, and the flags that keep the member's own run the same. */
1674
+ function moveOptions(path, text) {
1675
+ const config = exportedConfig(path, text);
1676
+ const options = config?.properties.find((element) => propertyName(element) === "options");
1677
+ if (config === void 0 || options === void 0) return { kind: "none" };
1678
+ if (!typescript().isPropertyAssignment(options)) return {
1679
+ kind: "unsupported",
1680
+ keys: ["options"]
1681
+ };
1682
+ const result = optionFlags(options.initializer);
1683
+ if ("unsupported" in result) return {
1684
+ kind: "unsupported",
1685
+ keys: result.unsupported
1686
+ };
1687
+ return {
1688
+ kind: "moved",
1689
+ text: withoutProperty(text, config, options),
1690
+ flags: result.flags
1691
+ };
1692
+ }
1693
+ /** A shell separator that ends one command of a script. */
1694
+ const COMMAND_END = /&&|\|\||[;|]/;
1695
+ /** `script` with `flags` after each `oxlint` command word, skipping a flag that command already passes. */
1696
+ function withFlags(script, flags) {
1697
+ return script.replace(OXLINT_COMMAND, (match, before, offset) => {
1698
+ const rest = script.slice(offset + match.length);
1699
+ const command = rest.split(COMMAND_END)[0] ?? rest;
1700
+ const missing = flags.filter((flag) => !command.includes(flag.split("=")[0] ?? flag));
1701
+ return missing.length ? `${before}oxlint ${missing.join(" ")}` : match;
1702
+ });
1703
+ }
1704
+ const ALIGNED_TOOLS = [
1705
+ "@antelopejs/tooling-configs",
1706
+ "oxlint",
1707
+ "oxlint-tsgolint",
1708
+ "oxfmt",
1709
+ "knip",
1710
+ "lefthook"
1711
+ ];
1712
+ /** The range each pack tool resolves to at the root: the one it declares, else the one `--init` and sync add. A protocol or path spec stays root-only, since a member would resolve it elsewhere. */
1713
+ function rootRanges(root, versions) {
1714
+ const ranges = /* @__PURE__ */ new Map([
1715
+ ["@antelopejs/tooling-configs", `^${versions.pack}`],
1716
+ ["oxlint", versions.oxlint],
1717
+ ["oxlint-tsgolint", versions.tsgolint],
1718
+ ["oxfmt", versions.oxfmt],
1719
+ ["knip", versions.knip],
1720
+ ["lefthook", versions.lefthook]
1721
+ ]);
1722
+ for (const field of [root.dependencies, root.devDependencies]) for (const [name, range] of Object.entries(field ?? {})) if (ranges.has(name)) ranges.set(name, range);
1723
+ for (const [name, range] of ranges) if (/[:/]/.test(range)) ranges.delete(name);
1724
+ return ranges;
1725
+ }
1726
+ /** Sets each pack tool the member declares to the root's range, so the workspace installs one copy of the pack; returns whether it changed one. */
1727
+ function alignRanges(member, ranges) {
1728
+ let changed = false;
1729
+ for (const field of [member.dependencies, member.devDependencies]) for (const name of ALIGNED_TOOLS) {
1730
+ const declared = field && Object.hasOwn(field, name) ? field[name] : void 0;
1731
+ const wanted = ranges.get(name);
1732
+ if (!field || declared === void 0 || wanted === void 0 || declared === wanted || declared.includes(":")) continue;
1733
+ field[name] = wanted;
1734
+ changed = true;
1735
+ }
1736
+ return changed;
1737
+ }
1738
+ function alignMember(root, directory, ranges, result) {
1739
+ const manifestPath = join(root, directory, "package.json");
1740
+ const current = readFileSync(manifestPath, "utf8");
1741
+ const member = parseManifest(current);
1742
+ let changed = alignRanges(member, ranges);
1743
+ for (const name of LINT_CONFIGS) {
1744
+ const relative = `${directory}/${name}`;
1745
+ const path = join(root, relative);
1746
+ if (!existsSync(path)) continue;
1747
+ const move = moveOptions(relative, readFileSync(path, "utf8"));
1748
+ if (move.kind === "unsupported") result.failures.push(`${relative} sets oxlint options that oxlint reads only from the root config and that no command-line flag carries (${move.keys.join(", ")}). Move them to the root config or remove them, then rerun antelopejs-sync --init.`);
1749
+ if (move.kind !== "moved") continue;
1750
+ writeFileSync(path, move.text);
1751
+ result.paths.push(relative);
1752
+ for (const [script, command] of Object.entries(member.scripts ?? {})) {
1753
+ const flagged = withFlags(command, move.flags);
1754
+ if (flagged === command || !member.scripts) continue;
1755
+ member.scripts[script] = flagged;
1756
+ changed = true;
1757
+ }
1758
+ }
1759
+ if (!changed) return;
1760
+ writeFileSync(manifestPath, serializeManifest(member, current));
1761
+ result.paths.push(`${directory}/package.json`);
1762
+ }
1763
+ /**
1764
+ * Prepares each workspace member for the root's lint and install: the pack
1765
+ * tools it declares move to the root's ranges, and the `options` of its oxlint
1766
+ * config, which oxlint accepts only in the root config, move to the same flags
1767
+ * on the member's `oxlint` scripts.
1768
+ */
1769
+ function alignWorkspaceMembers(root, manifest, versions) {
1770
+ const ranges = rootRanges(manifest, versions);
1771
+ const result = {
1772
+ paths: [],
1773
+ failures: []
1774
+ };
1775
+ for (const directory of workspaceDirectories(root)) alignMember(root, directory, ranges, result);
1776
+ return result;
1777
+ }
1778
+ //#endregion
1779
+ //#region src/guardrails/init.ts
1780
+ /** The `gh` arguments that turn `delete_branch_on_merge` on; `gh` fills `{owner}/{repo}` from the git remote. */
1781
+ const ENABLE_ARGS = [
1782
+ "api",
1783
+ "-X",
1784
+ "PATCH",
1785
+ "repos/{owner}/{repo}",
1786
+ "-F",
1787
+ "delete_branch_on_merge=true"
1788
+ ];
1789
+ /** The command a person runs when `--init` could not turn `delete_branch_on_merge` on. */
1790
+ const ENABLE_BRANCH_CLEANUP = `gh ${ENABLE_ARGS.join(" ")}`;
1791
+ const NODE_MODULES_LINE = /^(?:\*\*\/|\/)?node_modules\/?$/;
1792
+ /** Creates `.gitignore` or appends `node_modules` to it, keeping every existing line; returns whether it wrote. */
1793
+ function ensureGitignore(root) {
1794
+ const path = join(root, ".gitignore");
1795
+ const current = existsSync(path) ? readFileSync(path, "utf8") : "";
1796
+ if (current.split(/\r?\n/).some((line) => NODE_MODULES_LINE.test(line.trim()))) return false;
1797
+ const newline = current.includes("\r\n") ? "\r\n" : "\n";
1798
+ const separator = current === "" || current.endsWith("\n") ? "" : newline;
1799
+ writeFileSync(path, `${current}${separator}node_modules${newline}`);
1800
+ return true;
1801
+ }
1802
+ function failureText(result) {
1803
+ if (result.error) return "code" in result.error && result.error.code === "ENOENT" ? "gh is not installed" : result.error.message;
1804
+ return result.stderr.trim().split("\n")[0] || `gh exited with ${result.status ?? result.signal}`;
1805
+ }
1806
+ function gh(root, args) {
1807
+ return spawnSync("gh", args, {
1808
+ cwd: root,
1809
+ encoding: "utf8"
1810
+ });
1811
+ }
1812
+ /** Turns `delete_branch_on_merge` on through `gh`, reading it first so a repository that has it on is never written. */
1813
+ function ensureBranchCleanup(root) {
1814
+ const read = gh(root, [
1815
+ "api",
1816
+ "repos/{owner}/{repo}",
1817
+ "--jq",
1818
+ ".delete_branch_on_merge"
1819
+ ]);
1820
+ if (read.error || read.status !== 0) return {
1821
+ kind: "unavailable",
1822
+ reason: failureText(read)
1823
+ };
1824
+ const state = read.stdout.trim();
1825
+ if (state === "true") return { kind: "on" };
1826
+ if (state !== "false") return {
1827
+ kind: "unavailable",
1828
+ reason: `gh answered ${JSON.stringify(state)}`
1829
+ };
1830
+ const write = gh(root, ENABLE_ARGS);
1831
+ return write.error || write.status !== 0 ? {
1832
+ kind: "unavailable",
1833
+ reason: failureText(write)
1834
+ } : { kind: "enabled" };
1835
+ }
1836
+ /** Runs `manager` with `args` quietly; returns its output only when it failed. */
1837
+ function run(root, manager, args) {
1838
+ const command = [manager, ...args].join(" ");
1839
+ const result = spawnSync(manager, args, {
1840
+ cwd: root,
1841
+ encoding: "utf8"
1842
+ });
1843
+ if (result.error) return `${command} failed: ${result.error.message}`;
1844
+ if (result.status === 0) return void 0;
1845
+ return `${command} failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1846
+ }
1847
+ function install(root, manager) {
1848
+ return run(root, manager, ["install"]);
1849
+ }
1850
+ function resolveOxfmt(root) {
1851
+ const require = createRequire(join(root, "package.json"));
1852
+ return join(dirname(require.resolve("oxfmt/package.json")), "bin/oxfmt");
1853
+ }
1854
+ /** Formats the repository with its installed oxfmt, as its `format` script does, so `format:check` passes on the keys init and sync append out of order and on source the repository never formatted. */
1855
+ function formatRepository(root) {
1856
+ let binary;
1857
+ try {
1858
+ binary = resolveOxfmt(root);
1859
+ } catch {
1860
+ return {
1861
+ rewritten: [],
1862
+ failure: "oxfmt is not installed in this repository, so it is not formatted."
1863
+ };
1864
+ }
1865
+ const oxfmt = (flags) => spawnSync(process.execPath, [
1866
+ binary,
1867
+ ...flags,
1868
+ "--no-error-on-unmatched-pattern",
1869
+ "."
1870
+ ], {
1871
+ cwd: root,
1872
+ encoding: "utf8"
1873
+ });
1874
+ const rewritten = oxfmt(["--list-different"]).stdout.split("\n").map((line) => line.trim()).filter(Boolean);
1875
+ const result = oxfmt([]);
1876
+ if (result.error) return {
1877
+ rewritten: [],
1878
+ failure: `oxfmt failed: ${result.error.message}`
1879
+ };
1880
+ if (result.status === 0) return {
1881
+ rewritten,
1882
+ failure: void 0
1883
+ };
1884
+ return {
1885
+ rewritten: [],
1886
+ failure: `oxfmt failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd()
1887
+ };
1888
+ }
1889
+ /** The tsconfig `--init` writes for a Node repository with none, so the synced `typecheck` checks its JavaScript and TypeScript under Node's module rules. */
1890
+ const NODE_TSCONFIG = `{
1891
+ "compilerOptions": {
1892
+ "target": "ES2024",
1893
+ "module": "NodeNext",
1894
+ "moduleResolution": "NodeNext",
1895
+ "allowJs": true,
1896
+ "checkJs": true,
1897
+ "noEmit": true,
1898
+ "types": ["node"]
1899
+ }
1900
+ }
1901
+ `;
1902
+ const NPM_LOCKFILE = "package-lock.json";
1903
+ /**
1904
+ * The file steps before the first install: `node_modules` ignored, the pnpm version the pack's CI runs pinned when
1905
+ * `packageManager` is unset, the bootstrap devDependencies, a tsconfig for a Node repository without one or its own
1906
+ * `typecheck`, the pack's oxfmt config when there is none, each workspace member on the root's tool ranges with its
1907
+ * oxlint `options` moved to flags, and npm's lockfile replaced by a pnpm lockfile holding the versions it resolved.
1908
+ */
1909
+ function bootstrap(root) {
1910
+ const path = join(root, "package.json");
1911
+ if (!existsSync(path)) throw new Error("package.json is missing. antelopejs-sync --init needs a repository that already has one.");
1912
+ const current = readFileSync(path, "utf8");
1913
+ const manifest = parseManifest(current);
1914
+ const manager = packageManager(manifest);
1915
+ const versions = toolingVersions();
1916
+ const paths = [];
1917
+ if (ensureGitignore(root)) paths.push(".gitignore");
1918
+ const nodeProject = !existsSync(join(root, "tsconfig.json")) && manifest.scripts?.typecheck === void 0 && !usesNuxt(root, manifest);
1919
+ const next = bootstrappedManifest(current, bootstrapDependencies(manifest, versions, nodeProject), versions.packageManager);
1920
+ if (next !== current) {
1921
+ writeFileSync(path, next);
1922
+ paths.push("package.json");
1923
+ }
1924
+ if (nodeProject) {
1925
+ writeFileSync(join(root, "tsconfig.json"), NODE_TSCONFIG);
1926
+ paths.push("tsconfig.json");
1927
+ }
1928
+ const fmt = PRESET_CONFIGS[1];
1929
+ if (![fmt.path, ...fmt.legacy].some((file) => existsSync(join(root, file)))) {
1930
+ writeFileSync(join(root, fmt.path), presetConfig(void 0, fmt, repositoryTools(manifest)));
1931
+ paths.push(fmt.path);
1932
+ }
1933
+ const members = alignWorkspaceMembers(root, manifest, versions);
1934
+ paths.push(...members.paths);
1935
+ if (members.failures.length) return {
1936
+ manager,
1937
+ paths,
1938
+ removed: [],
1939
+ failure: members.failures.join("\n")
1940
+ };
1941
+ const npmLock = manager === "pnpm" && existsSync(join(root, NPM_LOCKFILE));
1942
+ const imported = npmLock && !existsSync(join(root, "pnpm-lock.yaml")) ? run(root, manager, ["import"]) : void 0;
1943
+ if (imported !== void 0) return {
1944
+ manager,
1945
+ paths,
1946
+ removed: [],
1947
+ failure: imported
1948
+ };
1949
+ if (npmLock) unlinkSync(join(root, NPM_LOCKFILE));
1950
+ return {
1951
+ manager,
1952
+ paths,
1953
+ removed: npmLock ? [NPM_LOCKFILE] : [],
1954
+ failure: install(root, manager)
1955
+ };
1956
+ }
1957
+ /**
1958
+ * Onboards a repository in one run: the bootstrap file steps and an install, the repository formatted by oxfmt before
1959
+ * sync measures its lint and size baseline, a full-profile sync, a second install when sync added devDependencies, a
1960
+ * second oxfmt pass over what sync wrote, and `delete_branch_on_merge` on GitHub, which runs whatever the file steps
1961
+ * did. Every step is idempotent, so a second run changes nothing.
1962
+ */
1963
+ function initRepository(root, options = {}) {
1964
+ const { manager, paths, removed, failure: installed } = bootstrap(root);
1965
+ const format = () => {
1966
+ const formatted = formatRepository(root);
1967
+ for (const file of formatted.rewritten) if (!paths.includes(file)) paths.push(file);
1968
+ return formatted.failure;
1969
+ };
1970
+ const first = installed ?? (existsSync(join(root, PRESET_CONFIGS[1].path)) ? format() : void 0);
1971
+ if (first !== void 0) return {
1972
+ paths,
1973
+ removed,
1974
+ failure: first,
1975
+ sync: void 0,
1976
+ branchCleanup: ensureBranchCleanup(root),
1977
+ untypedDocs: []
1978
+ };
1979
+ const sync = syncRepository(root, {
1980
+ profile: "full",
1981
+ verify: options.verify
1982
+ });
1983
+ let failure;
1984
+ if (!sync.errors.length) {
1985
+ failure = sync.dependenciesAdded ? install(root, manager) : void 0;
1986
+ failure ??= format();
1987
+ }
1988
+ return {
1989
+ paths,
1990
+ removed,
1991
+ failure,
1992
+ sync,
1993
+ branchCleanup: ensureBranchCleanup(root),
1994
+ untypedDocs: sync.errors.length ? [] : untypedDocsFiles(root)
1995
+ };
1996
+ }
1997
+ //#endregion
1958
1998
  //#region src/bin/sync.ts
1999
+ function printSync(result, { check, installed }) {
2000
+ for (const note of result.notes) process.stdout.write(`Note: ${check || result.errors.length ? "Planned migration. " : ""}${note}\n`);
2001
+ for (const note of result.verifyNotes) process.stdout.write(`Note: ${note}\n`);
2002
+ for (const advisory of result.advisories) process.stdout.write(`${advisory}\n`);
2003
+ for (const error of result.errors) process.stderr.write(`${error}\n`);
2004
+ if (result.errors.length) return 1;
2005
+ for (const path of result.paths) process.stdout.write(check ? `Drift: ${path}; run antelopejs-sync\n` : `${result.removed.includes(path) ? "Removed" : "Updated"}: ${path}\n`);
2006
+ if (!result.paths.length) process.stdout.write("Guardrails are in sync.\n");
2007
+ if (!check && !installed && result.dependenciesAdded) process.stdout.write("Added devDependencies. Run install with your package manager before using the hooks or checks.\n");
2008
+ return check && result.paths.length ? 1 : 0;
2009
+ }
2010
+ function init(verify) {
2011
+ const result = initRepository(repositoryRoot(), { verify });
2012
+ const reportedBySync = result.sync && !result.sync.errors.length ? result.sync.paths : [];
2013
+ for (const path of result.paths) if (!reportedBySync.includes(path)) process.stdout.write(`Updated: ${path}\n`);
2014
+ for (const path of result.removed) process.stdout.write(`Removed: ${path}\n`);
2015
+ const synced = result.sync ? printSync(result.sync, {
2016
+ check: false,
2017
+ installed: true
2018
+ }) : 0;
2019
+ if (result.untypedDocs.length) process.stdout.write(`Note: ${result.untypedDocs.join(", ")} hold TypeScript fences or docs-api pages the docs check typechecks. Set docs-typescript-project in ${CI_PATH} to a tsconfig whose program resolves their imports, or mark illustrative fences \`fragment\`. Without it the check uses the root tsconfig.json and fails when there is none.\n`);
2020
+ if (result.failure !== void 0) process.stderr.write(`${result.failure}\n`);
2021
+ const failed = synced !== 0 || result.failure !== void 0;
2022
+ if (failed) process.stderr.write("Fix the errors above, then rerun antelopejs-sync --init.\n");
2023
+ else process.stdout.write(`Commit and push to the default branch so ${CI_CONTEXT} is reported.\n`);
2024
+ const cleanup = result.branchCleanup;
2025
+ if (cleanup.kind === "enabled") process.stdout.write("Updated: delete_branch_on_merge on GitHub\n");
2026
+ if (cleanup.kind === "unavailable") process.stderr.write(`delete_branch_on_merge is not on (${cleanup.reason}). Run: ${ENABLE_BRANCH_CLEANUP}\n`);
2027
+ return failed || cleanup.kind === "unavailable" ? 1 : 0;
2028
+ }
1959
2029
  runCli(() => {
1960
2030
  const { values } = parseArgs({ options: {
1961
2031
  check: { type: "boolean" },
2032
+ init: { type: "boolean" },
1962
2033
  profile: {
1963
2034
  type: "string",
1964
2035
  default: "full"
@@ -1967,20 +2038,16 @@ runCli(() => {
1967
2038
  } });
1968
2039
  if (values.profile !== "full" && values.profile !== "template") throw new Error("--profile must be full or template.");
1969
2040
  if (values.verify !== void 0 && !isVerifyChoice(values.verify)) throw new Error("--verify must be interface, module, template, or custom.");
1970
- const result = syncRepository(repositoryRoot(), {
2041
+ if (values.init && (values.check || values.profile === "template")) throw new Error("--init sets up a full-profile repository; it cannot be combined with --check or --profile template.");
2042
+ if (values.init) return init(values.verify);
2043
+ return printSync(syncRepository(repositoryRoot(), {
1971
2044
  check: values.check,
1972
2045
  profile: values.profile,
1973
2046
  verify: values.verify
2047
+ }), {
2048
+ check: Boolean(values.check),
2049
+ installed: false
1974
2050
  });
1975
- for (const note of result.notes) process.stdout.write(`Note: ${values.check || result.errors.length ? "Planned migration. " : ""}${note}\n`);
1976
- for (const note of result.verifyNotes) process.stdout.write(`Note: ${note}\n`);
1977
- for (const advisory of result.advisories) process.stdout.write(`${advisory}\n`);
1978
- for (const error of result.errors) process.stderr.write(`${error}\n`);
1979
- if (result.errors.length) return 1;
1980
- for (const path of result.paths) process.stdout.write(values.check ? `Drift: ${path}; run antelopejs-sync\n` : `${result.removed.includes(path) ? "Removed" : "Updated"}: ${path}\n`);
1981
- if (!result.paths.length) process.stdout.write("Guardrails are in sync.\n");
1982
- if (!values.check && result.dependenciesAdded) process.stdout.write("Added devDependencies. Run install with your package manager before using the hooks or checks.\n");
1983
- return values.check && result.paths.length ? 1 : 0;
1984
2051
  });
1985
2052
  //#endregion
1986
2053
  export {};