@antelopejs/tooling-configs 0.5.0 → 0.5.2

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,18 +1,19 @@
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 { a as packageManager, c as templatePackage, i as managedPackage, l as toolingVersions, n as bootstrapDependencies, o as parseManifest, s as repositoryTools, t as addedDevDependencies, u as withDevDependencies } from "../package-DxxcxOzp.mjs";
4
+ import { i as presetConfig, n as SETUP_SCRIPT, r as lefthook, t as PRESET_CONFIGS } from "../templates-BiXgdsRN.mjs";
5
5
  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
6
  import { t as runCli } from "../cli-4Tv71vYk.mjs";
7
+ 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-B0FmthGv.mjs";
7
8
  import { a as gitFiles, c as repositoryRoot } from "../files-DJ0TeaTU.mjs";
8
- import { i as recordedRelease, t as measureBaseline } from "../ratchet-BTiPMqam.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";
9
+ import { i as recordedRelease, t as measureBaseline } from "../ratchet--WWa_w2O.mjs";
10
10
  import { n as SUPPRESSIONS_FILE, r as adoptedBudget } from "../suppression-budget-Dvb_IqBo.mjs";
11
+ import { n as stepsOf, r as planDocs, t as matchingScripts } from "../script-steps-CgH2DSsp.mjs";
11
12
  import { t as DEFAULT_SHARED } from "../map-DRyYz_Fw.mjs";
13
+ import { createRequire } from "node:module";
12
14
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
13
15
  import { basename, dirname, join, posix, resolve } from "node:path";
14
- import { execFileSync } from "node:child_process";
15
- import { isMap, isScalar, isSeq, parseDocument } from "yaml";
16
+ import { execFileSync, spawnSync } from "node:child_process";
16
17
  import ts from "typescript";
17
18
  import { parseArgs } from "node:util";
18
19
  //#region src/guardrails/agents-block.ts
@@ -67,6 +68,7 @@ const SHARED_RULES = [
67
68
  ["String-keyed object tables are read through own keys only", "`antelopejs/no-inherited-key-lookup`"],
68
69
  ["A type guard checks each member it narrows to; keys with `Object.hasOwn`", "`antelopejs/no-presence-only-type-guard`"],
69
70
  ["A type guard checks the nested elements and values it claims", "review; no tool"],
71
+ ["A startup read does not decide an insert another replica can race", "`antelopejs/no-read-then-insert`"],
70
72
  ["`Object.assign` writes no `unknown`, `any` or mistyped value over a field", "`antelopejs/no-unsafe-object-assign`"],
71
73
  ["Every file type-aware lint reads is listed by a tsconfig", "`antelopejs/require-tsconfig-include`"],
72
74
  ["Params ≤ 5, function ≤ 120 lines, file ≤ 500 lines, depth ≤ 4, complexity ≤ 20", "`eslint/max-*`, `eslint/complexity`"],
@@ -96,9 +98,9 @@ const FULL_RULES = [
96
98
  ["A CI gate reads `needs.<id>` only of jobs in its `needs`", "`antelopejs-sync --check`"],
97
99
  ["Entry-only rules exempt no tracked outsider", "`antelopejs-sync --check`"],
98
100
  ["A DMS layer's `build/backend-boundary.ts` is the pack's plugin", "`antelopejs-sync --check`"],
99
- ["No `skipLibCheck` in the root tsconfig or one `typecheck` or `build` uses", "Reported by `antelopejs-sync` (note only)"],
100
- ["`build` skips the lib check only over what `typecheck` checks", "Reported by `antelopejs-sync` (note only)"],
101
- ["`release` runs `typecheck`", "Reported by `antelopejs-sync` (note only)"],
101
+ ["No `skipLibCheck` in the root tsconfig or one `typecheck` or `build` uses", "`antelopejs-sync --check`"],
102
+ ["`build` skips the lib check only over what `typecheck` checks", "`antelopejs-sync --check`"],
103
+ ["`release` runs `typecheck`", "`antelopejs-sync --check`"],
102
104
  ["A test names the wrong implementation it catches", "review; no tool"]
103
105
  ];
104
106
  /** Pads each column the way oxfmt does, so formatting AGENTS.md never reports sync drift. */
@@ -425,283 +427,6 @@ function checkEntryOnlyConfiguration(root) {
425
427
  };
426
428
  }
427
429
  //#endregion
428
- //#region src/guardrails/docs-compat.ts
429
- const DOCS_COMPAT_START = "<!-- antelopejs-docs-compat:start -->";
430
- const DOCS_COMPAT_END = "<!-- antelopejs-docs-compat:end -->";
431
- const DOCS_NODE_START = "<!-- antelopejs-docs-node:start -->";
432
- const DOCS_NODE_END = "<!-- antelopejs-docs-node:end -->";
433
- const LOCKFILE = "pnpm-lock.yaml";
434
- const REQUIREMENTS_HEADING = /^##\s+Requirements\s*$/i;
435
- const SCOPE = "@antelopejs/";
436
- const UNRESOLVED = "—";
437
- const LEGACY_MARKER = /^<!--\s*docs-compat:\s*\.\/package\.json#\w+\s*-->\s*$/;
438
- const COMPATIBILITY_HEADING = /^##\s+Compatibility\s*$/i;
439
- const RESOLVED_SECTIONS = [
440
- "dependencies",
441
- "optionalDependencies",
442
- "devDependencies"
443
- ];
444
- /** The generated block, rows sorted by package name, formatted as oxfmt leaves it. */
445
- function compatBlock(rows) {
446
- const table = [[
447
- "Package",
448
- "Supported",
449
- "Tested with"
450
- ], ...[...rows].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(({ name, supported, tested }) => [
451
- `\`${name}\``,
452
- `\`${supported.replaceAll("|", "\\|")}\``,
453
- tested === void 0 ? UNRESOLVED : `\`${tested}\``
454
- ])];
455
- const widths = [
456
- 0,
457
- 1,
458
- 2
459
- ].map((column) => Math.max(3, ...table.map((row) => row[column].length)));
460
- const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
461
- return [
462
- DOCS_COMPAT_START,
463
- "",
464
- line(table[0]),
465
- line(widths.map((width) => "-".repeat(width))),
466
- ...table.slice(1).map(line),
467
- "",
468
- DOCS_COMPAT_END,
469
- ""
470
- ].join("\n");
471
- }
472
- function legacySpanEnd(lines, marker) {
473
- let index = marker + 1;
474
- while (index < lines.length && !lines[index].trim()) index++;
475
- while (index < lines.length && lines[index].trimStart().startsWith("|")) index++;
476
- while (index < lines.length && !lines[index].trim()) index++;
477
- return index;
478
- }
479
- function replaceLegacyTables(lines, block) {
480
- const placed = [];
481
- let replaced = false;
482
- for (let index = 0; index < lines.length;) {
483
- if (!LEGACY_MARKER.test(lines[index])) {
484
- placed.push(lines[index]);
485
- index++;
486
- continue;
487
- }
488
- if (!replaced) placed.push(...block.split("\n"));
489
- replaced = true;
490
- index = legacySpanEnd(lines, index);
491
- }
492
- return replaced ? placed : void 0;
493
- }
494
- function finalNewline(text) {
495
- return text.endsWith("\n") ? text : `${text}\n`;
496
- }
497
- /** The README with the block in place: replacing the markers, a legacy `docs-compat` table, or under `## Compatibility`. */
498
- function placeCompatBlock(current, block) {
499
- const text = current ?? "";
500
- const start = text.indexOf(DOCS_COMPAT_START);
501
- const end = text.indexOf(DOCS_COMPAT_END);
502
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-compat markers. Repair or delete them, then rerun antelopejs-sync.");
503
- if (start !== -1) return `${text.slice(0, start)}${block}${text.slice(end + 35).replace(/^\r?\n/, "")}`;
504
- const lines = text.split("\n");
505
- const legacy = replaceLegacyTables(lines, block);
506
- if (legacy) return finalNewline(legacy.join("\n"));
507
- const heading = lines.findIndex((line) => COMPATIBILITY_HEADING.test(line));
508
- if (heading !== -1) {
509
- let rest = heading + 1;
510
- while (rest < lines.length && !lines[rest].trim()) rest++;
511
- return finalNewline([
512
- ...lines.slice(0, heading + 1),
513
- "",
514
- ...block.split("\n"),
515
- ...lines.slice(rest)
516
- ].join("\n"));
517
- }
518
- const before = text.trimEnd();
519
- return `${before}${before ? "\n\n" : ""}## Compatibility\n\n${block}`;
520
- }
521
- /** The generated Node prerequisite block for an `engines.node` range, formatted as oxfmt leaves it. */
522
- function nodeBlock(range) {
523
- return `${DOCS_NODE_START}\n\nThis package requires Node.js \`${range}\`.\n${DOCS_NODE_END}\n`;
524
- }
525
- /** The README with the Node block in place: between its markers, under `## Requirements`, or in a new `## Requirements` section at the end. */
526
- function placeNodeBlock(current, block) {
527
- const start = current.indexOf(DOCS_NODE_START);
528
- const end = current.indexOf(DOCS_NODE_END);
529
- if (start === -1 !== (end === -1) || end < start) throw new Error("incomplete antelopejs-docs-node markers. Repair or delete them, then rerun antelopejs-sync.");
530
- if (start !== -1) return `${current.slice(0, start)}${block}${current.slice(end + 33).replace(/^\r?\n/, "")}`;
531
- const lines = current.split("\n");
532
- const heading = lines.findIndex((line) => REQUIREMENTS_HEADING.test(line));
533
- if (heading !== -1) {
534
- let rest = heading + 1;
535
- while (rest < lines.length && !lines[rest].trim()) rest++;
536
- return finalNewline([
537
- ...lines.slice(0, heading + 1),
538
- "",
539
- ...block.trimEnd().split("\n"),
540
- ...rest < lines.length ? ["", ...lines.slice(rest)] : []
541
- ].join("\n"));
542
- }
543
- return `${current.trimEnd()}\n\n## Requirements\n\n${block}`;
544
- }
545
- function relative$1(directory, name) {
546
- return directory ? `${directory}/${name}` : name;
547
- }
548
- function isDirectory(root, path) {
549
- return statSync(join(root, path), { throwIfNoEntry: false })?.isDirectory() === true;
550
- }
551
- function subdirectories(root, directory) {
552
- 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));
553
- }
554
- function descendants(root, directory) {
555
- return subdirectories(root, directory).flatMap((child) => [child, ...descendants(root, child)]);
556
- }
557
- function globExpression(pattern) {
558
- const source = pattern.split("/").map((segment) => segment === "**" ? "(?:.*)" : segment.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", "[^/]*").replaceAll("?", "[^/]")).join("/").replaceAll("(?:.*)/", "(?:.*/)?");
559
- return new RegExp(`^${source}$`);
560
- }
561
- function expand(root, pattern) {
562
- let directories = [""];
563
- for (const segment of pattern.split("/")) if (segment === "**") directories = directories.flatMap((directory) => [directory, ...descendants(root, directory)]);
564
- else if (/[*?]/.test(segment)) {
565
- const expression = globExpression(segment);
566
- directories = directories.flatMap((directory) => subdirectories(root, directory).filter((child) => expression.test(child.slice(child.lastIndexOf("/") + 1))));
567
- } else directories = directories.map((directory) => relative$1(directory, segment)).filter((directory) => isDirectory(root, directory));
568
- return directories;
569
- }
570
- function normalizePattern(pattern) {
571
- return pattern.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "");
572
- }
573
- function scalarItems(document, path) {
574
- const node = document.getIn(path, true);
575
- return isSeq(node) ? node.items.flatMap((item) => isScalar(item) ? [String(item.value)] : []) : [];
576
- }
577
- /** pnpm-workspace.yaml `packages`, else package.json `workspaces` as an array or as `{ packages }`; JSON parses as YAML. */
578
- function workspacePatterns(root) {
579
- const pnpm = join(root, "pnpm-workspace.yaml");
580
- if (existsSync(pnpm)) return scalarItems(parseDocument(readFileSync(pnpm, "utf8")), ["packages"]);
581
- const manifest = parseDocument(readFileSync(join(root, "package.json"), "utf8"));
582
- return scalarItems(manifest, isMap(manifest.get("workspaces", true)) ? ["workspaces", "packages"] : ["workspaces"]);
583
- }
584
- function workspaceDirectories(root) {
585
- const patterns = workspacePatterns(root);
586
- const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => globExpression(normalizePattern(pattern.slice(1))));
587
- const found = /* @__PURE__ */ new Set();
588
- for (const pattern of patterns.filter((item) => !item.startsWith("!"))) {
589
- const normalized = normalizePattern(pattern);
590
- 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);
591
- }
592
- return [...found].sort();
593
- }
594
- function declaredRanges(manifest) {
595
- const ranges = /* @__PURE__ */ new Map();
596
- for (const field of [
597
- manifest.optionalDependencies,
598
- manifest.dependencies,
599
- manifest.peerDependencies
600
- ]) for (const [name, range] of Object.entries(field ?? {})) if (name.startsWith(SCOPE)) ranges.set(name, range);
601
- return ranges;
602
- }
603
- function readManifest(root, directory) {
604
- return parseManifest(readFileSync(join(root, directory, "package.json"), "utf8"));
605
- }
606
- function linkedVersion(root, directory, link) {
607
- const target = join(root, directory, link);
608
- return existsSync(join(target, "package.json")) ? parseManifest(readFileSync(join(target, "package.json"), "utf8")).version : void 0;
609
- }
610
- function resolvedVersion(root, { document, importer }, directory, name) {
611
- for (const section of RESOLVED_SECTIONS) {
612
- const entry = document.getIn([
613
- "importers",
614
- importer,
615
- section,
616
- name
617
- ], true);
618
- const version = isMap(entry) ? entry.get("version", true) : entry;
619
- if (!isScalar(version)) continue;
620
- const resolved = String(version.value).split("(")[0];
621
- return resolved.startsWith("link:") ? linkedVersion(root, directory, resolved.slice(5)) : resolved;
622
- }
623
- }
624
- const UNSHARED_NPMRC = /^\s*shared-workspace-lockfile\s*=\s*false\s*(?:[#;].*)?$/m;
625
- /** Whether the workspace keeps one root lockfile, or `shared-workspace-lockfile=false` gives each package its own. */
626
- function sharesLockfile(root) {
627
- const npmrc = join(root, ".npmrc");
628
- if (existsSync(npmrc) && UNSHARED_NPMRC.test(readFileSync(npmrc, "utf8"))) return false;
629
- const workspace = join(root, "pnpm-workspace.yaml");
630
- return !(existsSync(workspace) && parseDocument(readFileSync(workspace, "utf8")).get("sharedWorkspaceLockfile") === false);
631
- }
632
- /** The lockfile path of a package, relative to the root. A shared lockfile is the root's, indexed by the package directory. */
633
- function lockPath(shared, directory) {
634
- return shared ? LOCKFILE : relative$1(directory, LOCKFILE);
635
- }
636
- function readLock(root, shared, directory) {
637
- const path = join(root, lockPath(shared, directory));
638
- return existsSync(path) ? {
639
- document: parseDocument(readFileSync(path, "utf8")),
640
- importer: shared ? directory || "." : "."
641
- } : void 0;
642
- }
643
- /** Adds one package's `docs-files` lines and, when it needs one, its README with the generated blocks. */
644
- function planPackage(root, plan, lock, standard, { directory, ranges, published, node }) {
645
- const readme = relative$1(directory, "README.md");
646
- const docs = relative$1(directory, "docs");
647
- if (!published) return;
648
- if (ranges.size > 0 || existsSync(join(root, readme))) plan.docsFiles.push(readme);
649
- if (isDirectory(root, docs)) plan.docsFiles.push(docs);
650
- const current = existsSync(join(root, readme)) ? readFileSync(join(root, readme), "utf8") : void 0;
651
- const nodeRange = standard && current !== void 0 ? node : void 0;
652
- if (ranges.size === 0 && nodeRange === void 0) return;
653
- const rows = [...ranges].map(([name, supported]) => ({
654
- name,
655
- supported,
656
- tested: lock && resolvedVersion(root, lock, directory, name)
657
- }));
658
- try {
659
- const withRequirements = nodeRange !== void 0 && current !== void 0 ? placeNodeBlock(current, nodeBlock(nodeRange)) : current;
660
- plan.readmes.push({
661
- path: readme,
662
- current,
663
- content: rows.length > 0 ? placeCompatBlock(withRequirements, compatBlock(rows)) : withRequirements ?? ""
664
- });
665
- } catch (error) {
666
- plan.errors.push(`${readme}: ${error instanceof Error ? error.message : String(error)}`);
667
- }
668
- }
669
- /**
670
- * Plans the docs-compat block of the root and of every workspace package that is not private and declares an
671
- * `@antelopejs/*` peer, runtime or optional dependency, and the `docs-files` lines covering the root and every workspace
672
- * package that is not private.
673
- * Tested with comes from pnpm-lock.yaml, each package's own when `shared-workspace-lockfile=false`; other package managers get a dash.
674
- */
675
- function planDocs(root, manager) {
676
- const rootManifest = readManifest(root, "");
677
- const packages = ["", ...workspaceDirectories(root)].map((directory) => {
678
- const manifest = directory ? readManifest(root, directory) : rootManifest;
679
- return {
680
- directory,
681
- published: !directory || !manifest.private,
682
- node: manifest.engines?.node,
683
- ranges: manifest.private ? /* @__PURE__ */ new Map() : declaredRanges(manifest)
684
- };
685
- });
686
- const qualifying = packages.filter(({ ranges }) => ranges.size > 0);
687
- const plan = {
688
- readmes: [],
689
- docsFiles: [],
690
- errors: [],
691
- exists: (path) => existsSync(join(root, path))
692
- };
693
- const shared = sharesLockfile(root);
694
- const locks = new Map(packages.map(({ directory }) => [directory, manager === "pnpm" ? readLock(root, shared, directory) : void 0]));
695
- const missing = manager === "pnpm" ? qualifying.filter(({ directory }) => !locks.get(directory)) : [];
696
- if (missing.length) {
697
- 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.`);
698
- return plan;
699
- }
700
- const standard = rootManifest.antelopeJs?.docs?.standard === true;
701
- for (const item of packages) planPackage(root, plan, locks.get(item.directory), standard, item);
702
- return plan;
703
- }
704
- //#endregion
705
430
  //#region src/guardrails/template-agent-layer.ts
706
431
  /** The folders a project scaffolded from a template does not get, as `ajs project init` excludes them. */
707
432
  const SCAFFOLD_EXCLUDED_PATHS = [".agents/", ".claude/skills/"];
@@ -786,182 +511,6 @@ function releaseHooks(files) {
786
511
  return [...hooksIn(files, ".release-it.json", ["hooks"]), ...hooksIn(files, "package.json", ["release-it", "hooks"])];
787
512
  }
788
513
  //#endregion
789
- //#region src/guardrails/script-steps.ts
790
- const SEPARATORS = /&&|\|\||[;|\n]|(?<![>&])&(?!&)/u;
791
- const ENV_ASSIGNMENT = /^[A-Za-z_]\w*=/u;
792
- const TSC_COMMAND = /(?:^|[\\/])tsc(?:\.js)?$/u;
793
- const MANAGERS = /* @__PURE__ */ new Set([
794
- "pnpm",
795
- "npm",
796
- "yarn",
797
- "bun"
798
- ]);
799
- const NPM_BUILTINS = /* @__PURE__ */ new Set([
800
- "test",
801
- "start",
802
- "stop",
803
- "restart"
804
- ]);
805
- const WRAPPERS = /* @__PURE__ */ new Set([
806
- "cross-env",
807
- "cross-env-shell",
808
- "env",
809
- "corepack"
810
- ]);
811
- const EXEC_RUNNERS = /* @__PURE__ */ new Set([
812
- "npx",
813
- "bunx",
814
- "pnpx"
815
- ]);
816
- const EXEC_VERBS = /* @__PURE__ */ new Set([
817
- "exec",
818
- "x",
819
- "dlx"
820
- ]);
821
- const RUN_ALL = /* @__PURE__ */ new Set([
822
- "run-s",
823
- "run-p",
824
- "npm-run-all",
825
- "npm-run-all2"
826
- ]);
827
- const RUN_ALL_VALUED = /* @__PURE__ */ new Set(["--max-parallel", "--npm-path"]);
828
- const EXEC_VALUED = /* @__PURE__ */ new Set([
829
- "-p",
830
- "--package",
831
- "-c",
832
- "--call"
833
- ]);
834
- const TARGET_VALUED = /* @__PURE__ */ new Set([
835
- "--filter",
836
- "-F",
837
- "--dir",
838
- "-C",
839
- "--prefix",
840
- "--cwd",
841
- "--workspace"
842
- ]);
843
- const TARGET_FLAGS = /* @__PURE__ */ new Set([
844
- "-r",
845
- "--recursive",
846
- "--workspaces",
847
- "-ws"
848
- ]);
849
- function words(segment) {
850
- return segment.replace(/[()]/gu, " ").split(/\s+/u).map((word) => word.replace(/^["']|["']$/gu, "")).filter(Boolean);
851
- }
852
- /** The simple commands of a script: `&&`, `||`, `;`, `|`, `&`, newlines and parentheses all end one. */
853
- function lines(script) {
854
- return script.split(SEPARATORS).map(words).filter((list) => list.length > 0);
855
- }
856
- /** Skips the options from `from`, and the values of those that take one; `elsewhere` when one points at another package. */
857
- function skipOptions(args, from, valued) {
858
- let index = from;
859
- let elsewhere = false;
860
- while (index < args.length && args[index].startsWith("-")) {
861
- const [name, ...value] = args[index].split("=");
862
- elsewhere ||= TARGET_VALUED.has(name) || TARGET_FLAGS.has(name);
863
- index += valued.has(name) && value.length === 0 ? 2 : 1;
864
- }
865
- return {
866
- index,
867
- elsewhere
868
- };
869
- }
870
- function isTsc(word) {
871
- return TSC_COMMAND.test(word);
872
- }
873
- /** `tsc`, a path to it, or `node` running one. */
874
- function programSteps(line) {
875
- const [head, ...rest] = line;
876
- if (head === void 0) return [];
877
- if (isTsc(head)) return [{
878
- kind: "tsc",
879
- args: rest
880
- }];
881
- if (head !== "node") return [];
882
- if (rest[0] === "--run" && rest[1] !== void 0) return [{
883
- kind: "script",
884
- names: [rest[1]],
885
- elsewhere: false
886
- }];
887
- const at = rest.findIndex((word) => !word.startsWith("-"));
888
- return at !== -1 && isTsc(rest[at]) ? [{
889
- kind: "tsc",
890
- args: rest.slice(at + 1)
891
- }] : [];
892
- }
893
- /** What `npx`, `pnpm exec` and `npm exec` run: the command after the options and the packages they name. */
894
- function execSteps(args) {
895
- return programSteps(args.slice(skipOptions(args, 0, EXEC_VALUED).index));
896
- }
897
- function managerSteps(manager, args) {
898
- const valued = new Set(TARGET_VALUED);
899
- if (manager === "npm") valued.add("-w");
900
- const first = skipOptions(args, 0, valued);
901
- const verb = args[first.index];
902
- if (verb === void 0) return [];
903
- if (EXEC_VERBS.has(verb)) return execSteps(args.slice(first.index + 1));
904
- if (verb === "run" || verb === "run-script") {
905
- const second = skipOptions(args, first.index + 1, valued);
906
- const name = args[second.index];
907
- return name === void 0 ? [] : [{
908
- kind: "script",
909
- names: [name],
910
- elsewhere: first.elsewhere || second.elsewhere
911
- }];
912
- }
913
- if (isTsc(verb)) return programSteps(args.slice(first.index));
914
- if (manager === "npm" && !NPM_BUILTINS.has(verb)) return [];
915
- return [{
916
- kind: "script",
917
- names: [verb],
918
- elsewhere: first.elsewhere
919
- }];
920
- }
921
- function runAllSteps(args) {
922
- const names = [];
923
- for (let index = 0; index < args.length && args[index] !== "--"; index++) if (!args[index].startsWith("-")) names.push(args[index]);
924
- else if (RUN_ALL_VALUED.has(args[index])) index++;
925
- return names.length === 0 ? [] : [{
926
- kind: "script",
927
- names,
928
- elsewhere: false
929
- }];
930
- }
931
- /** The line without its leading environment assignments and wrappers (`cross-env A=1`, `env`, `corepack`). */
932
- function unwrapped(line) {
933
- let index = 0;
934
- let wrapped = false;
935
- while (index < line.length) {
936
- const word = line[index];
937
- if (WRAPPERS.has(word)) wrapped = true;
938
- else if (!ENV_ASSIGNMENT.test(word) && !(wrapped && word.startsWith("-"))) break;
939
- index++;
940
- }
941
- return line.slice(index);
942
- }
943
- function lineSteps(line) {
944
- const [head, ...args] = unwrapped(line);
945
- if (head === void 0) return [];
946
- if (RUN_ALL.has(head)) return runAllSteps(args);
947
- if (MANAGERS.has(head)) return managerSteps(head, args);
948
- if (EXEC_RUNNERS.has(head)) return execSteps(args);
949
- return programSteps([head, ...args]);
950
- }
951
- /** The scripts and `tsc` runs a script's command lines start. */
952
- function stepsOf(script) {
953
- return lines(script).flatMap(lineSteps);
954
- }
955
- /** The script names a `run-s` pattern list selects among `available`. */
956
- function matchingScripts(names, available) {
957
- const all = [...available];
958
- return names.flatMap((name) => {
959
- if (!name.includes("*")) return [name];
960
- const pattern = new RegExp(`^${name.split("**").map((part) => part.split("*").map((piece) => piece.replace(/[.+?^${}()|[\]\\]/gu, "\\$&")).join("[^:]*")).join(".*")}$`, "u");
961
- return all.filter((script) => pattern.test(script));
962
- });
963
- }
964
- //#endregion
965
514
  //#region src/guardrails/tsc-invocation.ts
966
515
  const ROOT_PROGRAM = "tsconfig.json";
967
516
  function normalizeProgram(project) {
@@ -1100,7 +649,7 @@ function reach(scripts, name, extra = []) {
1100
649
  })));
1101
650
  for (const { text, depth } of queue) for (const step of stepsOf(text)) {
1102
651
  if (step.kind !== "script") continue;
1103
- for (const script of matchingScripts(step.names, scripts.keys())) if (step.elsewhere) reached.elsewhere.add(script);
652
+ for (const script of matchingScripts(step.names, scripts.keys())) if (step.targets.length) reached.elsewhere.add(script);
1104
653
  else enter(script, depth + 1);
1105
654
  }
1106
655
  return reached;
@@ -1165,17 +714,20 @@ function scriptsOf(files) {
1165
714
  return;
1166
715
  }
1167
716
  }
1168
- /** The package.json and tsconfig facts that keep `typecheck` the lib check no other script skips: `build` skips the lib check only over a program `typecheck` checks in full, no tsconfig a script uses or the root one sets `skipLibCheck: true`, and `release` runs `typecheck`. A file that cannot be read yields a note and never an error. */
1169
- function checkTypecheckCoverage(root) {
717
+ /** The package.json and tsconfig facts that keep `typecheck` the lib check no other script skips: `build` skips the lib check only over a program `typecheck` checks in full, no tsconfig a script uses or the root one sets `skipLibCheck: true`, and `release` runs `typecheck`. Under `check` a broken fact is an error; otherwise it is a `Note:` advisory. A file that cannot be read yields a `Note:` advisory and never an error. */
718
+ function checkTypecheckCoverage(root, check) {
1170
719
  const files = coverageFiles(root);
1171
720
  const scripts = scriptsOf(files);
1172
- if (scripts === void 0) return unreadableNotes(files);
1173
- return [
721
+ const findings = scripts === void 0 ? [] : [
1174
722
  ...skipCoverageErrors(scripts),
1175
723
  ...skipLibCheckErrors(files, scripts),
1176
- ...releaseErrors(files, scripts),
1177
- ...unreadableNotes(files)
724
+ ...releaseErrors(files, scripts)
1178
725
  ];
726
+ const notes = check ? unreadableNotes(files) : [...findings, ...unreadableNotes(files)];
727
+ return {
728
+ errors: check ? findings : [],
729
+ advisories: notes.map((note) => `Note: ${note}`)
730
+ };
1179
731
  }
1180
732
  /** The kind-specific text of each shared skill. */
1181
733
  const KIND_TEXT = {
@@ -1337,7 +889,7 @@ ${BIN} map
1337
889
  6. **One-way doors.** The section comes right after the result line and is mandatory. \`${BIN} doors\` prints the \`One-way-door:\` line of the diff. Every file the path rules flag needs a door row or a false positive with its reason.
1338
890
  7. **Result.** FAIL if any rule fails. NOT VERIFIED when any journey of a required feature is NOT VERIFIED, for example a SaaS module run without its sandbox keys, however many other journeys passed. PASS+NOTES when everything required ran and passed but the judgement lists something no journey reached or something the owner should look at. PASS otherwise.
1339
891
 
1340
- Write your judgement to \`<run>/evidence/judgement.json\`:
892
+ Write your judgement to a JSON file:
1341
893
 
1342
894
  \`\`\`json
1343
895
  {
@@ -1353,13 +905,13 @@ Write your judgement to \`<run>/evidence/judgement.json\`:
1353
905
  }
1354
906
  \`\`\`
1355
907
 
1356
- A door row is \`{ "kind", "location", "irreversible", "containment" }\`, where \`containment\` says what limits the damage. Then render the verdict:
908
+ A door row is \`{ "kind", "location", "irreversible", "containment" }\`, where \`containment\` says what limits the damage. Pass it to \`verdict\` in the same step:
1357
909
 
1358
910
  \`\`\`bash
1359
- ${BIN} verdict <run> --pr <n>
911
+ ${BIN} verdict <run> --pr <n> --judgement <file>
1360
912
  \`\`\`
1361
913
 
1362
- \`verdict\` writes \`evidence/verdict.md\` and exits 1 unless the result is PASS or PASS+NOTES. Report the verdict and what you saw in your own reply, from a thread that did not write the change.
914
+ \`verdict\` stores it as \`evidence/judgement.json\`, writes \`evidence/verdict.md\` and exits 1 when an input is missing or the result is not PASS or PASS+NOTES. Read \`verdict.md\` only after it exits. Report the verdict and what you saw in your own reply, from a thread that did not write the change.
1363
915
 
1364
916
  ## Trust
1365
917
 
@@ -1835,7 +1387,9 @@ function syncRepository(root, options = {}) {
1835
1387
  let plan = [...planSync(current, modes, context), ...standalone];
1836
1388
  const errors = plan.filter((artifact) => artifact.kind === "error").map(({ message }) => message);
1837
1389
  const entryOnly = checkEntryOnlyConfiguration(root);
1390
+ const coverage = checkTypecheckCoverage(root, Boolean(options.check));
1838
1391
  errors.push(...entryOnly.errors, ...verify.errors, ...writing.errors);
1392
+ errors.push(...coverage.errors);
1839
1393
  const notes = plan.flatMap((artifact) => artifact.kind === "migrated" ? artifact.notes : []);
1840
1394
  (options.check ? errors : notes).push(...repositoryNotices(root, context));
1841
1395
  if (!errors.length && profile === "full" && !options.check && !current.has("guardrails.ratchet.json") && manifest.scripts?.["sync:check"] === void 0) {
@@ -1864,15 +1418,181 @@ function syncRepository(root, options = {}) {
1864
1418
  errors,
1865
1419
  notes,
1866
1420
  verifyNotes: options.check || errors.length ? [] : verify.notes,
1867
- advisories: [...entryOnly.advisories, ...checkTypecheckCoverage(root).map((finding) => `Note: ${finding}`)],
1421
+ advisories: [...entryOnly.advisories, ...coverage.advisories],
1868
1422
  dependenciesAdded
1869
1423
  };
1870
1424
  }
1871
1425
  //#endregion
1426
+ //#region src/guardrails/init.ts
1427
+ /** The `gh` arguments that turn `delete_branch_on_merge` on; `gh` fills `{owner}/{repo}` from the git remote. */
1428
+ const ENABLE_ARGS = [
1429
+ "api",
1430
+ "-X",
1431
+ "PATCH",
1432
+ "repos/{owner}/{repo}",
1433
+ "-F",
1434
+ "delete_branch_on_merge=true"
1435
+ ];
1436
+ /** The command a person runs when `--init` could not turn `delete_branch_on_merge` on. */
1437
+ const ENABLE_BRANCH_CLEANUP = `gh ${ENABLE_ARGS.join(" ")}`;
1438
+ const NODE_MODULES_LINE = /^(?:\*\*\/|\/)?node_modules\/?$/;
1439
+ /** Creates `.gitignore` or appends `node_modules` to it, keeping every existing line; returns whether it wrote. */
1440
+ function ensureGitignore(root) {
1441
+ const path = join(root, ".gitignore");
1442
+ const current = existsSync(path) ? readFileSync(path, "utf8") : "";
1443
+ if (current.split(/\r?\n/).some((line) => NODE_MODULES_LINE.test(line.trim()))) return false;
1444
+ const newline = current.includes("\r\n") ? "\r\n" : "\n";
1445
+ const separator = current === "" || current.endsWith("\n") ? "" : newline;
1446
+ writeFileSync(path, `${current}${separator}node_modules${newline}`);
1447
+ return true;
1448
+ }
1449
+ function failureText(result) {
1450
+ if (result.error) return "code" in result.error && result.error.code === "ENOENT" ? "gh is not installed" : result.error.message;
1451
+ return result.stderr.trim().split("\n")[0] || `gh exited with ${result.status ?? result.signal}`;
1452
+ }
1453
+ function gh(root, args) {
1454
+ return spawnSync("gh", args, {
1455
+ cwd: root,
1456
+ encoding: "utf8"
1457
+ });
1458
+ }
1459
+ /** Turns `delete_branch_on_merge` on through `gh`, reading it first so a repository that has it on is never written. */
1460
+ function ensureBranchCleanup(root) {
1461
+ const read = gh(root, [
1462
+ "api",
1463
+ "repos/{owner}/{repo}",
1464
+ "--jq",
1465
+ ".delete_branch_on_merge"
1466
+ ]);
1467
+ if (read.error || read.status !== 0) return {
1468
+ kind: "unavailable",
1469
+ reason: failureText(read)
1470
+ };
1471
+ const state = read.stdout.trim();
1472
+ if (state === "true") return { kind: "on" };
1473
+ if (state !== "false") return {
1474
+ kind: "unavailable",
1475
+ reason: `gh answered ${JSON.stringify(state)}`
1476
+ };
1477
+ const write = gh(root, ENABLE_ARGS);
1478
+ return write.error || write.status !== 0 ? {
1479
+ kind: "unavailable",
1480
+ reason: failureText(write)
1481
+ } : { kind: "enabled" };
1482
+ }
1483
+ /** Runs the package manager's install quietly; returns its output only when it failed. */
1484
+ function install(root, manager) {
1485
+ const result = spawnSync(manager, ["install"], {
1486
+ cwd: root,
1487
+ encoding: "utf8"
1488
+ });
1489
+ if (result.error) return `${manager} install failed: ${result.error.message}`;
1490
+ if (result.status === 0) return void 0;
1491
+ return `${manager} install failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1492
+ }
1493
+ function resolveOxfmt(root) {
1494
+ const require = createRequire(join(root, "package.json"));
1495
+ return join(dirname(require.resolve("oxfmt/package.json")), "bin/oxfmt");
1496
+ }
1497
+ /** Formats `package.json` with the repository's installed oxfmt, which sorts the keys init and sync append out of order; returns its output only when it failed. */
1498
+ function formatManifest(root) {
1499
+ let binary;
1500
+ try {
1501
+ binary = resolveOxfmt(root);
1502
+ } catch {
1503
+ return "oxfmt is not installed in this repository, so package.json is not formatted.";
1504
+ }
1505
+ const result = spawnSync(process.execPath, [
1506
+ binary,
1507
+ "--no-error-on-unmatched-pattern",
1508
+ "package.json"
1509
+ ], {
1510
+ cwd: root,
1511
+ encoding: "utf8"
1512
+ });
1513
+ if (result.error) return `oxfmt failed: ${result.error.message}`;
1514
+ if (result.status === 0) return void 0;
1515
+ return `oxfmt failed (exit ${result.status}).\n${result.stdout}${result.stderr}`.trimEnd();
1516
+ }
1517
+ /**
1518
+ * Onboards a repository in one run: `node_modules` in `.gitignore`, the pack,
1519
+ * oxlint and oxfmt as devDependencies, an install, a full-profile sync, a second
1520
+ * install when sync added devDependencies, `package.json` formatted by oxfmt,
1521
+ * and `delete_branch_on_merge` on GitHub, which runs whatever the file steps did.
1522
+ * Every step is idempotent, so a second run changes nothing.
1523
+ */
1524
+ function initRepository(root, options = {}) {
1525
+ const path = join(root, "package.json");
1526
+ if (!existsSync(path)) throw new Error("package.json is missing. antelopejs-sync --init needs a repository that already has one.");
1527
+ const current = readFileSync(path, "utf8");
1528
+ const manifest = parseManifest(current);
1529
+ const manager = packageManager(manifest);
1530
+ const paths = [];
1531
+ if (ensureGitignore(root)) paths.push(".gitignore");
1532
+ const added = bootstrapDependencies(manifest, toolingVersions());
1533
+ if (added.length) {
1534
+ writeFileSync(path, withDevDependencies(current, added));
1535
+ paths.push("package.json");
1536
+ }
1537
+ const first = install(root, manager);
1538
+ if (first !== void 0) return {
1539
+ paths,
1540
+ failure: first,
1541
+ sync: void 0,
1542
+ branchCleanup: ensureBranchCleanup(root)
1543
+ };
1544
+ const sync = syncRepository(root, {
1545
+ profile: "full",
1546
+ verify: options.verify
1547
+ });
1548
+ let failure;
1549
+ if (!sync.errors.length) {
1550
+ failure = sync.dependenciesAdded ? install(root, manager) : void 0;
1551
+ const unformatted = readFileSync(path, "utf8");
1552
+ failure ??= formatManifest(root);
1553
+ if (readFileSync(path, "utf8") !== unformatted && !paths.includes("package.json")) paths.push("package.json");
1554
+ }
1555
+ return {
1556
+ paths,
1557
+ failure,
1558
+ sync,
1559
+ branchCleanup: ensureBranchCleanup(root)
1560
+ };
1561
+ }
1562
+ //#endregion
1872
1563
  //#region src/bin/sync.ts
1564
+ function printSync(result, { check, installed }) {
1565
+ for (const note of result.notes) process.stdout.write(`Note: ${check || result.errors.length ? "Planned migration. " : ""}${note}\n`);
1566
+ for (const note of result.verifyNotes) process.stdout.write(`Note: ${note}\n`);
1567
+ for (const advisory of result.advisories) process.stdout.write(`${advisory}\n`);
1568
+ for (const error of result.errors) process.stderr.write(`${error}\n`);
1569
+ if (result.errors.length) return 1;
1570
+ for (const path of result.paths) process.stdout.write(check ? `Drift: ${path}; run antelopejs-sync\n` : `${result.removed.includes(path) ? "Removed" : "Updated"}: ${path}\n`);
1571
+ if (!result.paths.length) process.stdout.write("Guardrails are in sync.\n");
1572
+ if (!check && !installed && result.dependenciesAdded) process.stdout.write("Added devDependencies. Run install with your package manager before using the hooks or checks.\n");
1573
+ return check && result.paths.length ? 1 : 0;
1574
+ }
1575
+ function init(verify) {
1576
+ const result = initRepository(repositoryRoot(), { verify });
1577
+ const reportedBySync = result.sync && !result.sync.errors.length ? result.sync.paths : [];
1578
+ for (const path of result.paths) if (!reportedBySync.includes(path)) process.stdout.write(`Updated: ${path}\n`);
1579
+ const synced = result.sync ? printSync(result.sync, {
1580
+ check: false,
1581
+ installed: true
1582
+ }) : 0;
1583
+ if (result.failure !== void 0) process.stderr.write(`${result.failure}\n`);
1584
+ const failed = synced !== 0 || result.failure !== void 0;
1585
+ if (failed) process.stderr.write("Fix the errors above, then rerun antelopejs-sync --init.\n");
1586
+ else process.stdout.write(`Commit and push to the default branch so ${CI_CONTEXT} is reported.\n`);
1587
+ const cleanup = result.branchCleanup;
1588
+ if (cleanup.kind === "enabled") process.stdout.write("Updated: delete_branch_on_merge on GitHub\n");
1589
+ if (cleanup.kind === "unavailable") process.stderr.write(`delete_branch_on_merge is not on (${cleanup.reason}). Run: ${ENABLE_BRANCH_CLEANUP}\n`);
1590
+ return failed || cleanup.kind === "unavailable" ? 1 : 0;
1591
+ }
1873
1592
  runCli(() => {
1874
1593
  const { values } = parseArgs({ options: {
1875
1594
  check: { type: "boolean" },
1595
+ init: { type: "boolean" },
1876
1596
  profile: {
1877
1597
  type: "string",
1878
1598
  default: "full"
@@ -1881,20 +1601,16 @@ runCli(() => {
1881
1601
  } });
1882
1602
  if (values.profile !== "full" && values.profile !== "template") throw new Error("--profile must be full or template.");
1883
1603
  if (values.verify !== void 0 && !isVerifyChoice(values.verify)) throw new Error("--verify must be interface, module, template, or custom.");
1884
- const result = syncRepository(repositoryRoot(), {
1604
+ 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.");
1605
+ if (values.init) return init(values.verify);
1606
+ return printSync(syncRepository(repositoryRoot(), {
1885
1607
  check: values.check,
1886
1608
  profile: values.profile,
1887
1609
  verify: values.verify
1610
+ }), {
1611
+ check: Boolean(values.check),
1612
+ installed: false
1888
1613
  });
1889
- for (const note of result.notes) process.stdout.write(`Note: ${values.check || result.errors.length ? "Planned migration. " : ""}${note}\n`);
1890
- for (const note of result.verifyNotes) process.stdout.write(`Note: ${note}\n`);
1891
- for (const advisory of result.advisories) process.stdout.write(`${advisory}\n`);
1892
- for (const error of result.errors) process.stderr.write(`${error}\n`);
1893
- if (result.errors.length) return 1;
1894
- 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`);
1895
- if (!result.paths.length) process.stdout.write("Guardrails are in sync.\n");
1896
- if (!values.check && result.dependenciesAdded) process.stdout.write("Added devDependencies. Run install with your package manager before using the hooks or checks.\n");
1897
- return values.check && result.paths.length ? 1 : 0;
1898
1614
  });
1899
1615
  //#endregion
1900
1616
  export {};