slateboard 0.1.0 → 0.1.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/README.md +33 -192
- package/dist/arch-3JZTL2DJ.js +1842 -0
- package/dist/bin.js +93 -17
- package/dist/{chunk-ONZFKR4I.js → chunk-6CR2V7P7.js} +172 -22
- package/dist/chunk-6YTKJKSG.js +129 -0
- package/dist/{chunk-SQHGMBUM.js → chunk-KA7Z72FC.js} +3 -2
- package/dist/{chunk-WXM4BB4D.js → chunk-OJOVDYIZ.js} +1400 -873
- package/dist/{chunk-BWNUX4FT.js → chunk-WREOGLK6.js} +4 -4
- package/dist/{chunk-FMO5B2KJ.js → chunk-ZCFHR5VG.js} +5 -5
- package/dist/{client-JHI2EG6J.js → client-BFKANUSM.js} +4 -4
- package/dist/{commands-ONES545N.js → commands-IB76RJGP.js} +1 -1
- package/dist/{doctor-H5Y5L2JZ.js → doctor-RPN73UNG.js} +3 -3
- package/dist/{hooks-2TI5OLAU.js → hooks-QJ4XG42C.js} +13 -1
- package/dist/{lifecycle-ZB5HEO5P.js → lifecycle-O7LDC735.js} +4 -4
- package/dist/{service-command-26BPMBK3.js → service-command-WG4TAU2T.js} +5 -5
- package/dist/shipped-7D2LNTAK.js +153 -0
- package/dist/{src-QZIVUACM.js → src-2MHSOXLY.js} +12 -2
- package/dist/{src-YVFB3ZLM.js → src-QB7VJHQH.js} +21 -1
- package/dist/ui/assets/abnfDiagram-XWFEHMT6-DAC8TnbO.js +1 -0
- package/dist/ui/assets/architecture-WOLXFQ4H-X8k0-LVf.js +1 -0
- package/dist/ui/assets/architectureDiagram-CSQXQB3N-CVoxvA0s.js +36 -0
- package/dist/ui/assets/blockDiagram-BEDRHYPZ-DGf5VAwB.js +140 -0
- package/dist/ui/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
- package/dist/ui/assets/c4Diagram-M2UUVUY5-PB5quCOl.js +38 -0
- package/dist/ui/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/ui/assets/chunk-3GCGMST5-RRiusQp9.js +1 -0
- package/dist/ui/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/dist/ui/assets/chunk-7U7NFRK5-CSOOpKZT.js +88 -0
- package/dist/ui/assets/chunk-CNRTWJTD-DJuDnaYn.js +1 -0
- package/dist/ui/assets/chunk-D5HYT7QG-imLQxbAy.js +1 -0
- package/dist/ui/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/dist/ui/assets/chunk-DZSZGQHW-BCXsfFfT.js +1 -0
- package/dist/ui/assets/chunk-EBZ3SEQC-CdDips7b.js +2 -0
- package/dist/ui/assets/chunk-F3AE6A5H-DTVcMSk7.js +1 -0
- package/dist/ui/assets/chunk-FGVZ23HU-BEVs0fgA.js +213 -0
- package/dist/ui/assets/chunk-GZTWQ64R-CKGVWw4I.js +62 -0
- package/dist/ui/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/dist/ui/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/ui/assets/chunk-KTR4FSNJ-DSr3q0Xy.js +1 -0
- package/dist/ui/assets/chunk-MDAHDJXZ-YMIkXJ0O.js +10 -0
- package/dist/ui/assets/chunk-MPYPSXSE-C-CxVwa7.js +1 -0
- package/dist/ui/assets/chunk-ND7LMLKX-lfusdDHU.js +72 -0
- package/dist/ui/assets/chunk-NGNAAXSQ-DqoPQk1a.js +136 -0
- package/dist/ui/assets/chunk-OWCVCYLK-4-W-ynqW.js +2 -0
- package/dist/ui/assets/chunk-QDWOWVBQ-Du0KmhW4.js +129 -0
- package/dist/ui/assets/chunk-T47YP6PS-CKli33QU.js +1 -0
- package/dist/ui/assets/chunk-XXDRQBXY-DSL17ZTh.js +1 -0
- package/dist/ui/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/ui/assets/classDiagram-v2-KXABOMEV-CYc2BZ2y.js +217 -0
- package/dist/ui/assets/cose-bilkent-JH36ORCC-81nUs0at.js +1 -0
- package/dist/ui/assets/cynefin-EF2NZ3EQ-Clvwy422.js +1 -0
- package/dist/ui/assets/cynefinDiagram-NJNITYFG-CsgTQqAC.js +62 -0
- package/dist/ui/assets/cytoscape.esm-BPveszXl.js +321 -0
- package/dist/ui/assets/d3-scale-lXtN6-Od.js +1 -0
- package/dist/ui/assets/d3-selection-BFzs9NTX.js +1 -0
- package/dist/ui/assets/dagre-KIHZ2IZ3--BpWd3hW.js +4 -0
- package/dist/ui/assets/diagram-7YQZDPLS-Dp_m-C1a.js +41 -0
- package/dist/ui/assets/diagram-QBROCOUO-Bt-Lp7vq.js +200 -0
- package/dist/ui/assets/diagram-RJJCUUZO-DLsG2Tej.js +30 -0
- package/dist/ui/assets/diagram-WERXNKYE-D31SLp70.js +24 -0
- package/dist/ui/assets/diagram-YHHI257C-CVMeUILe.js +3 -0
- package/dist/ui/assets/diagram-YR4HJLHV-Bz9qvIhJ.js +24 -0
- package/dist/ui/assets/dist-YCovsM_S.js +1 -0
- package/dist/ui/assets/ebnfDiagram-N527522P-_FIZSf8P.js +1 -0
- package/dist/ui/assets/elk-O5DQBFGD-BK3qD3UW.js +27 -0
- package/dist/ui/assets/erDiagram-K3K3BIDK-Dmpdi5Ob.js +99 -0
- package/dist/ui/assets/eventmodeling-K75KTNOO-Dt-51L4s.js +1 -0
- package/dist/ui/assets/flowDiagram-Z6JWZHQI-Cn2ZVzvO.js +1 -0
- package/dist/ui/assets/ganttDiagram-3PRQTZWP-BaZof7eT.js +292 -0
- package/dist/ui/assets/gitGraph-VSP46ZUC-ezyaB0jQ.js +1 -0
- package/dist/ui/assets/gitGraphDiagram-VXDFKS5L-DRNdClPw.js +106 -0
- package/dist/ui/assets/graphlib-DS17s2tU.js +1 -0
- package/dist/ui/assets/grid-E2QIVN74--djCUwdI.js +1 -0
- package/dist/ui/assets/index-Bly281F6.css +1 -0
- package/dist/ui/assets/index-CXK8WmR8.js +45 -0
- package/dist/ui/assets/info-OHQRW6UA-DsFXrFWI.js +1 -0
- package/dist/ui/assets/infoDiagram-EZ3ZOAHP-e8qx3eqc.js +2 -0
- package/dist/ui/assets/ishikawaDiagram-S3EKX5GW-CuKExPKN.js +70 -0
- package/dist/ui/assets/journeyDiagram-POQNLL5X-D0GE8iji.js +139 -0
- package/dist/ui/assets/kanban-definition-BH5XI6FM-NL5dOF_0.js +89 -0
- package/dist/ui/assets/katex-BXIx1Jgr.js +257 -0
- package/dist/ui/assets/mermaid-parser.core-0pE4JCc_.js +7 -0
- package/dist/ui/assets/mermaid.core-BVgUieVU.js +44 -0
- package/dist/ui/assets/mindmap-definition-WVAN44T4-BLTtjuVH.js +98 -0
- package/dist/ui/assets/packet-JDAUHWVQ-C-7DeilZ.js +1 -0
- package/dist/ui/assets/pegDiagram-D4NLKWP3-F2SSXiqv.js +1 -0
- package/dist/ui/assets/pie-XZMESJXO-B4BkiWTy.js +1 -0
- package/dist/ui/assets/pieDiagram-36ENHN4W-BB5uEdtB.js +39 -0
- package/dist/ui/assets/quadrantDiagram-ZQUDMS73-B5iPooYO.js +7 -0
- package/dist/ui/assets/radar-ABXABTNO-Dx3jkQdr.js +1 -0
- package/dist/ui/assets/railroad-I3PHUGI6-BSh47OT_.js +1 -0
- package/dist/ui/assets/railroad-abnf-LNEFI6M7-BWFvDxOj.js +1 -0
- package/dist/ui/assets/railroad-ebnf-DWYD2UWJ-GBoLzumA.js +1 -0
- package/dist/ui/assets/railroad-peg-JR7BVNR7-DByw5Orh.js +1 -0
- package/dist/ui/assets/railroadDiagram-JIZHGYPL--ptGd2NR.js +1 -0
- package/dist/ui/assets/render-VIF2ZAQL-CzNp-J42.js +2 -0
- package/dist/ui/assets/requirementDiagram-AXW2TVFA-DBh9Dt63.js +84 -0
- package/dist/ui/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/ui/assets/sankeyDiagram-FBCJTAIF-CjJtGyu8.js +40 -0
- package/dist/ui/assets/sequenceDiagram-3LA2ROMG-BzeMVuzG.js +169 -0
- package/dist/ui/assets/sizeCapture-2Q2CQKSF-DSY_W0YL.js +1 -0
- package/dist/ui/assets/stateDiagram-v2-ATKHQDJO-DYavre2v.js +291 -0
- package/dist/ui/assets/swimlanes-YQL5WMAO-CUTCsfPM.js +1 -0
- package/dist/ui/assets/swimlanesDiagram-UCCPES4V-B7bXxKVr.js +8 -0
- package/dist/ui/assets/timeline-definition-7Z437IG3-HWrtH0QT.js +120 -0
- package/dist/ui/assets/treeView-D4JQ5SDB-B5lbyI_M.js +1 -0
- package/dist/ui/assets/treemap-SAJKECNS-Ckfi-DGc.js +1 -0
- package/dist/ui/assets/usecaseDiagram-RDK6N6HP-BuKN2NAW.js +328 -0
- package/dist/ui/assets/vennDiagram-SHRQU5PJ-s2gljkjP.js +34 -0
- package/dist/ui/assets/wardley-7MLQ67FV-CjAqYBcP.js +1 -0
- package/dist/ui/assets/wardleyDiagram-F3OXNVQS-Ba_SoMTx.js +78 -0
- package/dist/ui/assets/xychartDiagram-GDYJKCDI-FsxUUoqL.js +7 -0
- package/dist/ui/index.html +2 -2
- package/dist/{upgrade-FND3UBJR.js → upgrade-M6TR3IBW.js} +15 -15
- package/migrations/0006_arch_auto.sql +8 -0
- package/package.json +1 -1
- package/dist/chunk-3ZLMW2RI.js +0 -74
- package/dist/ui/assets/index-4WzXlYHs.css +0 -1
- package/dist/ui/assets/index-ZKfByx7Q.js +0 -42
|
@@ -0,0 +1,1842 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import "./chunk-KPOE4I3O.js";
|
|
3
|
+
|
|
4
|
+
// src/arch.ts
|
|
5
|
+
import { execFileSync as execFileSync2 } from "node:child_process";
|
|
6
|
+
import { existsSync as existsSync8, readFileSync as readFileSync9, realpathSync as realpathSync3 } from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
// ../arch/src/cli.ts
|
|
10
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
11
|
+
import { dirname as dirname4, join as join10, relative, resolve as resolve2 } from "node:path";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import { parseArgs } from "node:util";
|
|
14
|
+
|
|
15
|
+
// ../arch/src/check.ts
|
|
16
|
+
import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
|
|
17
|
+
import { join as join8 } from "node:path";
|
|
18
|
+
|
|
19
|
+
// ../arch/src/components.ts
|
|
20
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
21
|
+
import { join as join2, posix as posix2 } from "node:path";
|
|
22
|
+
|
|
23
|
+
// ../arch/src/config.ts
|
|
24
|
+
var CONFIG_FILE = ".slate/arch.json";
|
|
25
|
+
var DEFAULT_COMMANDS = { generate: "slate arch generate", check: "slate arch check", verify: "slate arch verify" };
|
|
26
|
+
var commandsOf = (config) => config.commands ?? DEFAULT_COMMANDS;
|
|
27
|
+
var manifestGlob = (pkg) => pkg === "." ? "package.json" : `${pkg}/package.json`;
|
|
28
|
+
|
|
29
|
+
// ../arch/src/json.ts
|
|
30
|
+
function prettyJson(value, width = 150) {
|
|
31
|
+
return `${format(value, "", 0, width)}
|
|
32
|
+
`;
|
|
33
|
+
}
|
|
34
|
+
function oneLine(value) {
|
|
35
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
36
|
+
if (Array.isArray(value)) return `[${value.map(oneLine).join(", ")}]`;
|
|
37
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
38
|
+
return entries.length ? `{ ${entries.map(([k, v]) => `${JSON.stringify(k)}: ${oneLine(v)}`).join(", ")} }` : "{}";
|
|
39
|
+
}
|
|
40
|
+
function format(value, indent, used, width) {
|
|
41
|
+
const flat = oneLine(value);
|
|
42
|
+
if (value === null || typeof value !== "object" || indent.length + used + flat.length <= width) return flat;
|
|
43
|
+
const inner = `${indent} `;
|
|
44
|
+
if (Array.isArray(value)) {
|
|
45
|
+
if (value.length === 0) return "[]";
|
|
46
|
+
return `[
|
|
47
|
+
${value.map((v) => inner + format(v, inner, 0, width)).join(",\n")}
|
|
48
|
+
${indent}]`;
|
|
49
|
+
}
|
|
50
|
+
const entries = Object.entries(value).filter(([, v]) => v !== void 0);
|
|
51
|
+
const body = entries.map(([k, v]) => `${inner}${JSON.stringify(k)}: ${format(v, inner, JSON.stringify(k).length + 2, width)}`);
|
|
52
|
+
return `{
|
|
53
|
+
${body.join(",\n")}
|
|
54
|
+
${indent}}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ../arch/src/sources.ts
|
|
58
|
+
import { execFileSync } from "node:child_process";
|
|
59
|
+
import { createHash } from "node:crypto";
|
|
60
|
+
import { globSync, readFileSync } from "node:fs";
|
|
61
|
+
import { join } from "node:path";
|
|
62
|
+
function globToRegExp(glob) {
|
|
63
|
+
let re = "";
|
|
64
|
+
for (let i = 0; i < glob.length; i++) {
|
|
65
|
+
const c = glob[i];
|
|
66
|
+
if (c === "*" && glob[i + 1] === "*") {
|
|
67
|
+
const slash = glob[i + 2] === "/";
|
|
68
|
+
re += slash ? "(?:.*/)?" : ".*";
|
|
69
|
+
i += slash ? 2 : 1;
|
|
70
|
+
} else if (c === "*") re += "[^/]*";
|
|
71
|
+
else if (c === "?") re += "[^/]";
|
|
72
|
+
else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
73
|
+
}
|
|
74
|
+
return new RegExp(`^${re}$`);
|
|
75
|
+
}
|
|
76
|
+
function matchesAny(path2, globs) {
|
|
77
|
+
return globs.some((g) => globToRegExp(g).test(path2));
|
|
78
|
+
}
|
|
79
|
+
function listFiles(root, globs, ignore) {
|
|
80
|
+
const found = /* @__PURE__ */ new Set();
|
|
81
|
+
const exclude = (p) => /(^|[\\/])node_modules$/.test(p);
|
|
82
|
+
for (const g of globs) for (const f of globSync(g, { cwd: root, ...g.includes("node_modules") ? {} : { exclude } })) found.add(f.split("\\").join("/"));
|
|
83
|
+
return [...found].filter((f) => !matchesAny(f, ignore)).sort();
|
|
84
|
+
}
|
|
85
|
+
function hashFile(root, file) {
|
|
86
|
+
return createHash("sha256").update(readFileSync(join(root, file))).digest("hex").slice(0, 16);
|
|
87
|
+
}
|
|
88
|
+
function hashFiles(root, files) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const f of [...files].sort()) out[f] = hashFile(root, f);
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
function aggregateHash(files) {
|
|
94
|
+
const h = createHash("sha256");
|
|
95
|
+
for (const f of Object.keys(files).sort()) h.update(`${f}\0${files[f]}
|
|
96
|
+
`);
|
|
97
|
+
return h.digest("hex");
|
|
98
|
+
}
|
|
99
|
+
function lastCommit(root, globs, ignore) {
|
|
100
|
+
try {
|
|
101
|
+
const specs = [...globs.map((g) => `:(glob)${g}`), ...ignore.map((g) => `:(glob,exclude)${g}`)];
|
|
102
|
+
const out = execFileSync("git", ["-C", root, "log", "-1", "--format=%H", "--", ...specs], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
103
|
+
return out || null;
|
|
104
|
+
} catch {
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function diffSources(recorded, current) {
|
|
109
|
+
const added = Object.keys(current).filter((f) => !(f in recorded)).sort();
|
|
110
|
+
const removed = Object.keys(recorded).filter((f) => !(f in current)).sort();
|
|
111
|
+
const changed = Object.keys(current).filter((f) => f in recorded && recorded[f] !== current[f]).sort();
|
|
112
|
+
return { added, removed, changed };
|
|
113
|
+
}
|
|
114
|
+
function describeDiff(d, limit = 10) {
|
|
115
|
+
const parts = [
|
|
116
|
+
...d.changed.map((f) => `${f} (changed)`),
|
|
117
|
+
...d.added.map((f) => `${f} (added)`),
|
|
118
|
+
...d.removed.map((f) => `${f} (removed)`)
|
|
119
|
+
];
|
|
120
|
+
const shown = parts.slice(0, limit).join(", ");
|
|
121
|
+
return parts.length > limit ? `${shown}, and ${parts.length - limit} more` : shown;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ../arch/src/views.ts
|
|
125
|
+
import { dirname, posix } from "node:path";
|
|
126
|
+
function selects(sel, n) {
|
|
127
|
+
if (sel.exclude?.includes(n.id)) return false;
|
|
128
|
+
if (sel.ids?.includes(n.id)) return true;
|
|
129
|
+
if (sel.package === void 0 || n.package !== sel.package) return false;
|
|
130
|
+
if (sel.kinds && !sel.kinds.includes(n.kind)) return false;
|
|
131
|
+
if (sel.dir !== void 0 && (!n.file || dirname(n.file) !== sel.dir)) return false;
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
var ENTRY_KINDS = [
|
|
135
|
+
["cli-command", "CLI command", "CLI commands"],
|
|
136
|
+
["http-route", "HTTP route", "HTTP routes"],
|
|
137
|
+
["mcp-tool", "MCP tool", "MCP tools"],
|
|
138
|
+
["sse-event", "SSE event type", "SSE event types"],
|
|
139
|
+
["db-table", "table", "tables"]
|
|
140
|
+
];
|
|
141
|
+
var plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
142
|
+
function mermaidId(prefix, raw) {
|
|
143
|
+
return `${prefix}_${raw.replace(/^@/, "").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_|_$/g, "")}`;
|
|
144
|
+
}
|
|
145
|
+
function cmp(a, b) {
|
|
146
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
147
|
+
}
|
|
148
|
+
function entryCounts(nodes) {
|
|
149
|
+
return ENTRY_KINDS.map(([kind, one, many]) => [nodes.filter((n) => n.kind === kind).length, one, many]).filter(([n]) => n > 0).map(([n, one, many]) => plural(n, one, many));
|
|
150
|
+
}
|
|
151
|
+
function aggregate(facts, nodes, kinds, category, label) {
|
|
152
|
+
const owner = /* @__PURE__ */ new Map();
|
|
153
|
+
for (const fn of facts.nodes) {
|
|
154
|
+
const vn = nodes.find((v) => selects(v.selector, fn));
|
|
155
|
+
if (vn) owner.set(fn.id, vn.id);
|
|
156
|
+
}
|
|
157
|
+
const groups = /* @__PURE__ */ new Map();
|
|
158
|
+
for (const e of facts.edges) {
|
|
159
|
+
if (!kinds.includes(e.kind)) continue;
|
|
160
|
+
const from = owner.get(e.from);
|
|
161
|
+
const to = owner.get(e.to);
|
|
162
|
+
if (!from || !to || from === to) continue;
|
|
163
|
+
const c = category(e);
|
|
164
|
+
const key = `${from}\0${to}\0${c}`;
|
|
165
|
+
if (!groups.has(key)) groups.set(key, { from, to, category: c, edges: [] });
|
|
166
|
+
groups.get(key).edges.push(e);
|
|
167
|
+
}
|
|
168
|
+
return [...groups.values()].map((g) => ({
|
|
169
|
+
from: g.from,
|
|
170
|
+
to: g.to,
|
|
171
|
+
...label(g.category, g.edges),
|
|
172
|
+
kinds: [...new Set(g.edges.map((e) => e.kind))].sort(),
|
|
173
|
+
facts: g.edges.length,
|
|
174
|
+
evidence: g.edges.map((e) => e.evidence[0]).sort()[0]
|
|
175
|
+
})).sort((a, b) => cmp(a.from, b.from) || cmp(a.to, b.to) || cmp(a.label, b.label));
|
|
176
|
+
}
|
|
177
|
+
var pkgDir = (n) => String(n.attrs?.dir ?? dirname(n.file ?? "."));
|
|
178
|
+
var SYSTEM_INTRO = "The workspace packages and the outside world they meet: the actors that drive the code and the resources it drives. Package edges come from package.json dependencies and module imports; surface edges from the imports and call sites listed in facts.json.";
|
|
179
|
+
function systemView(facts, maxNodes, intro = SYSTEM_INTRO) {
|
|
180
|
+
const pkgs = facts.nodes.filter((n) => n.kind === "package");
|
|
181
|
+
const nodes = pkgs.map((p) => {
|
|
182
|
+
const owned = facts.nodes.filter((n) => n.package === p.label);
|
|
183
|
+
const modules = owned.filter((n) => n.kind === "module").length;
|
|
184
|
+
return {
|
|
185
|
+
id: mermaidId("pkg", p.label),
|
|
186
|
+
label: p.label,
|
|
187
|
+
detail: [plural(modules, "module", "modules"), ...entryCounts(owned)].join(" \xB7 "),
|
|
188
|
+
shape: "box",
|
|
189
|
+
target: `${pkgDir(p)}/`,
|
|
190
|
+
what: `workspace package in \`${pkgDir(p)}\``,
|
|
191
|
+
selector: { package: p.label }
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
for (const s of facts.nodes.filter((n) => n.kind === "surface")) {
|
|
195
|
+
const ev = s.evidence[0];
|
|
196
|
+
const i = ev.lastIndexOf(":");
|
|
197
|
+
nodes.push({
|
|
198
|
+
id: mermaidId("ext", s.id.slice("surface:".length)),
|
|
199
|
+
label: s.label,
|
|
200
|
+
shape: s.attrs?.direction === "out" ? "cylinder" : "stadium",
|
|
201
|
+
target: `${ev.slice(0, i)}#L${ev.slice(i + 1)}`,
|
|
202
|
+
what: s.attrs?.direction === "out" ? "external resource the code drives" : "external actor that drives the code",
|
|
203
|
+
selector: { ids: [s.id] }
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const edgeKinds = ["depends", "http", "imports", "invokes", "uses"];
|
|
207
|
+
const edges = aggregate(
|
|
208
|
+
facts,
|
|
209
|
+
nodes,
|
|
210
|
+
edgeKinds,
|
|
211
|
+
(e) => e.kind === "http" ? "http" : e.kind === "invokes" || e.kind === "uses" ? "surface" : "code",
|
|
212
|
+
(category, es) => {
|
|
213
|
+
if (category === "http") {
|
|
214
|
+
const paths = [...new Set(es.flatMap((e) => e.detail ?? []).map((d) => d.split("?")[0]))].sort();
|
|
215
|
+
return { label: `HTTP ${paths.filter((p) => !paths.some((q) => q !== p && p.startsWith(q))).join(", ")}`, dashed: false };
|
|
216
|
+
}
|
|
217
|
+
if (category === "surface") {
|
|
218
|
+
const files = [...new Set(es.map((e) => posix.basename((e.kind === "invokes" ? e.to : e.from).replace(/^module:/, ""))))].sort();
|
|
219
|
+
return { label: files.length > 3 ? plural(files.length, "module", "modules") : `via ${files.join(", ")}`, dashed: false };
|
|
220
|
+
}
|
|
221
|
+
const imports = es.filter((e) => e.kind === "imports");
|
|
222
|
+
if (imports.length === 0) return { label: "package.json only", dashed: true };
|
|
223
|
+
const typeOnly = imports.every((e) => e.typeOnly);
|
|
224
|
+
return { label: `${typeOnly ? "type imports" : "imports"} \xD7${imports.length}`, dashed: typeOnly };
|
|
225
|
+
}
|
|
226
|
+
);
|
|
227
|
+
return {
|
|
228
|
+
name: "system",
|
|
229
|
+
title: "System view",
|
|
230
|
+
intro,
|
|
231
|
+
direction: "LR",
|
|
232
|
+
subgraphs: [],
|
|
233
|
+
nodes,
|
|
234
|
+
edges,
|
|
235
|
+
edgeKinds,
|
|
236
|
+
grouping: [
|
|
237
|
+
"One node per workspace package; it stands for every module, migration and entry point the package owns.",
|
|
238
|
+
`One node per external surface found in the code (the \`surfaces\` rules of \`${CONFIG_FILE}\`, or the defaults \`slate arch\` derives).`,
|
|
239
|
+
"npm dependencies are left out; they are in facts.json as `external:` nodes.",
|
|
240
|
+
"Edges between the same two nodes are merged per category (code, HTTP, surface); the label counts the module-level facts behind it."
|
|
241
|
+
],
|
|
242
|
+
maxNodes
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function packagesView(facts, maxNodes, intro) {
|
|
246
|
+
const pkgs = facts.nodes.filter((n) => n.kind === "package");
|
|
247
|
+
const modules = facts.nodes.filter((n) => n.kind === "module" && n.package && n.file);
|
|
248
|
+
const groupOf = (n) => `${n.package}\0${dirname(n.file)}`;
|
|
249
|
+
const groups = /* @__PURE__ */ new Map();
|
|
250
|
+
for (const m of modules) {
|
|
251
|
+
if (!groups.has(groupOf(m))) groups.set(groupOf(m), []);
|
|
252
|
+
groups.get(groupOf(m)).push(m);
|
|
253
|
+
}
|
|
254
|
+
const byId = new Map(modules.map((m) => [m.id, m]));
|
|
255
|
+
const importers = /* @__PURE__ */ new Map();
|
|
256
|
+
for (const e of facts.edges) {
|
|
257
|
+
const from = byId.get(e.from);
|
|
258
|
+
const to = byId.get(e.to);
|
|
259
|
+
if (e.kind !== "imports" || !from || !to || groupOf(from) === groupOf(to)) continue;
|
|
260
|
+
if (!importers.has(to.id)) importers.set(to.id, /* @__PURE__ */ new Set());
|
|
261
|
+
importers.get(to.id).add(from.id);
|
|
262
|
+
}
|
|
263
|
+
const fanIn = (m) => importers.get(m.id)?.size ?? 0;
|
|
264
|
+
const remaining = new Map([...groups].map(([k, v]) => [k, v.length]));
|
|
265
|
+
const promoted = [];
|
|
266
|
+
const declaring = new Set(facts.edges.filter((e) => e.kind === "declares" && byId.has(e.from)).map((e) => e.from));
|
|
267
|
+
const candidates = [
|
|
268
|
+
...modules.filter((m) => declaring.has(m.id)).sort((a, b) => cmp(a.id, b.id)),
|
|
269
|
+
...modules.filter((m) => !declaring.has(m.id) && fanIn(m) > 0).sort((a, b) => fanIn(b) - fanIn(a) || cmp(a.id, b.id))
|
|
270
|
+
];
|
|
271
|
+
for (const m of candidates) {
|
|
272
|
+
if (groups.size + promoted.length >= maxNodes) break;
|
|
273
|
+
if (remaining.get(groupOf(m)) < 2) continue;
|
|
274
|
+
promoted.push(m);
|
|
275
|
+
remaining.set(groupOf(m), remaining.get(groupOf(m)) - 1);
|
|
276
|
+
}
|
|
277
|
+
const promotedIds = promoted.map((m) => m.id).sort();
|
|
278
|
+
const declared = (memberIds) => {
|
|
279
|
+
const ids = new Set(facts.edges.filter((e) => e.kind === "declares" && memberIds.has(e.from)).map((e) => e.to));
|
|
280
|
+
return facts.nodes.filter((n) => ids.has(n.id));
|
|
281
|
+
};
|
|
282
|
+
const nodes = [];
|
|
283
|
+
for (const p of pkgs) {
|
|
284
|
+
const sg = mermaidId("sg", p.label);
|
|
285
|
+
const base = pkgDir(p);
|
|
286
|
+
const pkgGroups = [...groups.keys()].filter((k) => k.startsWith(`${p.label}\0`)).sort();
|
|
287
|
+
for (const key of pkgGroups) {
|
|
288
|
+
const dir = key.slice(key.indexOf("\0") + 1);
|
|
289
|
+
const members = groups.get(key).filter((m) => !promotedIds.includes(m.id));
|
|
290
|
+
const exclude = groups.get(key).filter((m) => promotedIds.includes(m.id)).map((m) => m.id);
|
|
291
|
+
nodes.push({
|
|
292
|
+
id: mermaidId("dir", dir),
|
|
293
|
+
label: `${posix.relative(base, dir)}/`,
|
|
294
|
+
detail: [plural(members.length, "module", "modules"), ...entryCounts(declared(new Set(members.map((m) => m.id))))].join(" \xB7 "),
|
|
295
|
+
shape: "box",
|
|
296
|
+
target: `${dir}/`,
|
|
297
|
+
what: exclude.length ? `modules in \`${dir}\` other than the ones drawn on their own` : `modules in \`${dir}\``,
|
|
298
|
+
selector: { package: p.label, kinds: ["module"], dir, ...exclude.length ? { exclude } : {} },
|
|
299
|
+
subgraph: sg
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
for (const m of promoted.filter((x) => x.package === p.label).sort((a, b) => cmp(a.id, b.id))) {
|
|
303
|
+
const entries = entryCounts(declared(/* @__PURE__ */ new Set([m.id])));
|
|
304
|
+
nodes.push({
|
|
305
|
+
id: mermaidId("mod", m.file),
|
|
306
|
+
label: posix.relative(base, m.file),
|
|
307
|
+
detail: (entries.length ? entries : [`imported by ${plural(fanIn(m), "module", "modules")} elsewhere`]).join(" \xB7 "),
|
|
308
|
+
shape: "box",
|
|
309
|
+
target: m.file,
|
|
310
|
+
what: entries.length ? "module drawn on its own: it declares entry points" : "module drawn on its own: among the most imported from other directories",
|
|
311
|
+
selector: { ids: [m.id] },
|
|
312
|
+
subgraph: sg
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const edgeKinds = ["imports"];
|
|
317
|
+
const edges = aggregate(
|
|
318
|
+
facts,
|
|
319
|
+
nodes,
|
|
320
|
+
edgeKinds,
|
|
321
|
+
() => "imports",
|
|
322
|
+
(_c, es) => {
|
|
323
|
+
const typeOnly = es.every((e) => e.typeOnly);
|
|
324
|
+
return { label: `${es.length}`, dashed: typeOnly };
|
|
325
|
+
}
|
|
326
|
+
);
|
|
327
|
+
return {
|
|
328
|
+
name: "packages",
|
|
329
|
+
title: "Package view",
|
|
330
|
+
intro: intro ?? "The modules inside each package, grouped by directory, with the most imported modules drawn on their own. Edges are module imports (resolved by the TypeScript compiler); the label is the number of importing module pairs, and a dashed edge carries type-only imports.",
|
|
331
|
+
direction: "LR",
|
|
332
|
+
subgraphs: pkgs.map((p) => ({ id: mermaidId("sg", p.label), label: p.label })),
|
|
333
|
+
nodes,
|
|
334
|
+
edges,
|
|
335
|
+
edgeKinds,
|
|
336
|
+
grouping: [
|
|
337
|
+
"One subgraph per workspace package, one node per source directory in it.",
|
|
338
|
+
`While the view has fewer than ${maxNodes} nodes, modules are drawn on their own: first those that declare entry points (CLI commands, routes, MCP tools, event types), then those with the most importers from other directories (ties by path; only from directories that keep at least one other module).`,
|
|
339
|
+
"Only imports between workspace modules are drawn; npm and node: imports are in facts.json. HTTP calls between packages are in the system view.",
|
|
340
|
+
"This grouping is deterministic, not an agent's judgement: the same facts always give the same view."
|
|
341
|
+
],
|
|
342
|
+
maxNodes
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
var META_START = "<!-- arch:view";
|
|
346
|
+
var META_END = "-->";
|
|
347
|
+
function relLink(fromDir, target) {
|
|
348
|
+
const [path2, anchor] = target.split("#");
|
|
349
|
+
const rel = posix.relative(fromDir, path2.replace(/\/$/, "")) + (path2.endsWith("/") ? "/" : "");
|
|
350
|
+
return anchor ? `${rel}#${anchor}` : rel;
|
|
351
|
+
}
|
|
352
|
+
function shapeOf(n) {
|
|
353
|
+
const text = n.detail ? `${n.label}<br/>${n.detail}` : n.label;
|
|
354
|
+
const q = `"${text.replace(/"/g, "'")}"`;
|
|
355
|
+
return n.shape === "stadium" ? `([${q}])` : n.shape === "cylinder" ? `[(${q})]` : `[${q}]`;
|
|
356
|
+
}
|
|
357
|
+
function renderView(view, outDir, sources, commands = DEFAULT_COMMANDS) {
|
|
358
|
+
const link = (t) => relLink(outDir, t);
|
|
359
|
+
const m = [`flowchart ${view.direction}`];
|
|
360
|
+
const loose = view.nodes.filter((n) => !n.subgraph);
|
|
361
|
+
for (const sg of view.subgraphs) {
|
|
362
|
+
const inside = view.nodes.filter((n) => n.subgraph === sg.id);
|
|
363
|
+
if (!inside.length) continue;
|
|
364
|
+
m.push(` subgraph ${sg.id}["${sg.label}"]`);
|
|
365
|
+
for (const n of inside) m.push(` ${n.id}${shapeOf(n)}`);
|
|
366
|
+
m.push(" end");
|
|
367
|
+
}
|
|
368
|
+
for (const n of loose) m.push(` ${n.id}${shapeOf(n)}`);
|
|
369
|
+
for (const e of view.edges) m.push(` ${e.from} ${e.dashed ? "-.->" : "-->"}|"${e.label}"| ${e.to}`);
|
|
370
|
+
for (const n of view.nodes) m.push(` click ${n.id} "${link(n.target)}" "${n.target}"`);
|
|
371
|
+
const nodeName = new Map(view.nodes.map((n) => [n.id, n.subgraph ? `${n.label} (${view.subgraphs.find((s) => s.id === n.subgraph)?.label})` : n.label]));
|
|
372
|
+
const evLink = (ref) => {
|
|
373
|
+
const i = ref.lastIndexOf(":");
|
|
374
|
+
return `[${ref}](${link(ref.slice(0, i))}#L${ref.slice(i + 1)})`;
|
|
375
|
+
};
|
|
376
|
+
const meta = {
|
|
377
|
+
view: view.name,
|
|
378
|
+
...sources ? { sources } : {},
|
|
379
|
+
maxNodes: view.maxNodes,
|
|
380
|
+
edgeKinds: view.edgeKinds,
|
|
381
|
+
nodes: Object.fromEntries(view.nodes.map((n) => [n.id, n.selector]))
|
|
382
|
+
};
|
|
383
|
+
return [
|
|
384
|
+
`# ${view.title}`,
|
|
385
|
+
"",
|
|
386
|
+
`> Generated by \`${commands.generate}\` from [facts.json](facts.json); do not edit by hand.`,
|
|
387
|
+
`> \`${commands.check}\` says whether it is current.`,
|
|
388
|
+
...sources ? [
|
|
389
|
+
`> Sources: ${sources.globs.map((g) => `\`${g}\``).join(", ")} (${sources.files} files, content hash \`${sources.hash.slice(0, 12)}\`${sources.commit ? `, last changed in ${sources.commit.slice(0, 7)}` : ""}).`
|
|
390
|
+
] : [],
|
|
391
|
+
"",
|
|
392
|
+
view.intro,
|
|
393
|
+
"",
|
|
394
|
+
"```mermaid",
|
|
395
|
+
...m,
|
|
396
|
+
"```",
|
|
397
|
+
"",
|
|
398
|
+
"## Nodes",
|
|
399
|
+
"",
|
|
400
|
+
"| Node | What | Links to |",
|
|
401
|
+
"| --- | --- | --- |",
|
|
402
|
+
...view.nodes.map((n) => `| ${nodeName.get(n.id)}${n.detail ? ` (${n.detail})` : ""} | ${n.what} | [${n.target}](${link(n.target)}) |`),
|
|
403
|
+
"",
|
|
404
|
+
"## Edges",
|
|
405
|
+
"",
|
|
406
|
+
"| From | To | Label | Facts | First evidence |",
|
|
407
|
+
"| --- | --- | --- | --- | --- |",
|
|
408
|
+
...view.edges.map((e) => `| ${nodeName.get(e.from)} | ${nodeName.get(e.to)} | ${e.label} | ${e.facts} \xD7 ${e.kinds.join(", ")} | ${evLink(e.evidence)} |`),
|
|
409
|
+
"",
|
|
410
|
+
"## Grouping",
|
|
411
|
+
"",
|
|
412
|
+
...view.grouping.map((g) => `- ${g}`),
|
|
413
|
+
"",
|
|
414
|
+
META_START,
|
|
415
|
+
JSON.stringify(meta, null, 2),
|
|
416
|
+
META_END,
|
|
417
|
+
""
|
|
418
|
+
].join("\n");
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ../arch/src/components.ts
|
|
422
|
+
var COMPONENTS_JSON = "components.json";
|
|
423
|
+
var COMPONENTS_MD = "components.md";
|
|
424
|
+
var KINDS = /* @__PURE__ */ new Set(["imports", "http", "invokes", "uses"]);
|
|
425
|
+
var ID = /^[a-z][a-z0-9-]*$/;
|
|
426
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
427
|
+
var strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
428
|
+
function parseComponents(text, file = COMPONENTS_JSON) {
|
|
429
|
+
let doc;
|
|
430
|
+
try {
|
|
431
|
+
doc = JSON.parse(text);
|
|
432
|
+
} catch (err) {
|
|
433
|
+
throw new Error(`${file}: not JSON (${err.message})`);
|
|
434
|
+
}
|
|
435
|
+
const fail = (where, what) => {
|
|
436
|
+
throw new Error(`${file}: ${where} ${what}`);
|
|
437
|
+
};
|
|
438
|
+
if (!isObject(doc)) return fail("the document", "must be an object");
|
|
439
|
+
if (doc.schema !== 1) fail("schema", "must be 1");
|
|
440
|
+
if (!Array.isArray(doc.components)) fail("components", "must be an array");
|
|
441
|
+
if (!Array.isArray(doc.edges)) fail("edges", "must be an array");
|
|
442
|
+
doc.components.forEach((c, i) => {
|
|
443
|
+
const at2 = `components[${i}]`;
|
|
444
|
+
if (!isObject(c)) return fail(at2, "must be an object");
|
|
445
|
+
for (const k of ["id", "label", "purpose"]) if (typeof c[k] !== "string" || !c[k]) fail(`${at2}.${k}`, "must be a non-empty string");
|
|
446
|
+
if (c.package !== void 0 && typeof c.package !== "string") fail(`${at2}.package`, "must be a string");
|
|
447
|
+
if (!strings(c.files) || c.files.length === 0) fail(`${at2}.files`, "must be a non-empty array of globs");
|
|
448
|
+
});
|
|
449
|
+
doc.edges.forEach((e, i) => {
|
|
450
|
+
const at2 = `edges[${i}]`;
|
|
451
|
+
if (!isObject(e)) return fail(at2, "must be an object");
|
|
452
|
+
for (const k of ["from", "to", "label"]) if (typeof e[k] !== "string" || !e[k]) fail(`${at2}.${k}`, "must be a non-empty string");
|
|
453
|
+
if (!strings(e.evidence)) fail(`${at2}.evidence`, "must be an array of file:line references");
|
|
454
|
+
});
|
|
455
|
+
return doc;
|
|
456
|
+
}
|
|
457
|
+
function verifyComponents(doc, facts) {
|
|
458
|
+
const problems = [];
|
|
459
|
+
const modules = facts.nodes.filter((n) => n.kind === "module" && n.file);
|
|
460
|
+
const byId = new Map(facts.nodes.map((n) => [n.id, n]));
|
|
461
|
+
const members = /* @__PURE__ */ new Map();
|
|
462
|
+
const claimedBy = /* @__PURE__ */ new Map();
|
|
463
|
+
const packages = new Set(facts.nodes.filter((n) => n.kind === "package").map((n) => n.label));
|
|
464
|
+
for (const c of doc.components) {
|
|
465
|
+
if (!ID.test(c.id)) problems.push(`component ${c.id}: the id must be lowercase letters, digits and -`);
|
|
466
|
+
if (members.has(c.id) || byId.has(c.id)) {
|
|
467
|
+
problems.push(`component ${c.id}: the id is used twice`);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (c.package !== void 0 && !packages.has(c.package)) problems.push(`component ${c.id}: package ${c.package} is not in facts.json`);
|
|
471
|
+
const own = /* @__PURE__ */ new Set();
|
|
472
|
+
for (const glob of c.files) {
|
|
473
|
+
const hit = modules.filter((m) => matchesAny(m.file, [glob]));
|
|
474
|
+
if (hit.length === 0) problems.push(`component ${c.id}: ${glob} matches no module in facts.json`);
|
|
475
|
+
for (const m of hit) own.add(m.id);
|
|
476
|
+
}
|
|
477
|
+
for (const id of own) {
|
|
478
|
+
const m = byId.get(id);
|
|
479
|
+
if (c.package !== void 0 && m.package !== c.package) problems.push(`component ${c.id}: ${m.file} is in ${m.package ?? "no package"}, not ${c.package}`);
|
|
480
|
+
const other = claimedBy.get(id);
|
|
481
|
+
if (other) problems.push(`component ${c.id}: ${m.file} is also in component ${other}`);
|
|
482
|
+
else claimedBy.set(id, c.id);
|
|
483
|
+
}
|
|
484
|
+
members.set(c.id, own);
|
|
485
|
+
}
|
|
486
|
+
const ends = (id) => {
|
|
487
|
+
const own = members.get(id);
|
|
488
|
+
if (own) return { ids: own, pkgs: new Set([...own].map((m) => byId.get(m)?.package).filter((p) => !!p)) };
|
|
489
|
+
const node = byId.get(id);
|
|
490
|
+
if (!node) return `${id} is neither a component nor a node of facts.json`;
|
|
491
|
+
if (node.kind === "package") return { ids: /* @__PURE__ */ new Set([id, ...modules.filter((m) => m.package === node.label).map((m) => m.id)]), pkgs: /* @__PURE__ */ new Set([node.label]) };
|
|
492
|
+
if (node.kind !== "surface" && node.kind !== "external") return `${id} is a ${node.kind}; name a component, surface, external or package`;
|
|
493
|
+
return { ids: /* @__PURE__ */ new Set([id]), pkgs: /* @__PURE__ */ new Set() };
|
|
494
|
+
};
|
|
495
|
+
const reaches = (e, to) => to.ids.has(e.to) || e.kind === "http" && to.pkgs.has(byId.get(e.to)?.label ?? "");
|
|
496
|
+
const edges = doc.edges.map((edge) => {
|
|
497
|
+
const a = ends(edge.from);
|
|
498
|
+
const b = ends(edge.to);
|
|
499
|
+
const bad = [a, b].filter((x) => typeof x === "string");
|
|
500
|
+
if (bad.length) return { edge, supported: false, problems: bad, evidence: [], facts: 0 };
|
|
501
|
+
if (edge.from === edge.to) return { edge, supported: false, problems: ["an edge from a component to itself"], evidence: [], facts: 0 };
|
|
502
|
+
const from = a;
|
|
503
|
+
const to = b;
|
|
504
|
+
if ([...from.ids].some((id) => to.ids.has(id))) return { edge, supported: false, problems: [`${edge.from} and ${edge.to} overlap (a component and its own package?)`], evidence: [], facts: 0 };
|
|
505
|
+
const backing = facts.edges.filter((e) => KINDS.has(e.kind) && from.ids.has(e.from) && reaches(e, to));
|
|
506
|
+
if (backing.length === 0) return { edge, supported: false, problems: [`no fact edge from ${edge.from} to ${edge.to} in facts.json`], evidence: [], facts: 0 };
|
|
507
|
+
const known = new Set(backing.flatMap((e) => e.evidence));
|
|
508
|
+
const cited = edge.evidence.filter((ev) => known.has(ev));
|
|
509
|
+
const problems2 = edge.evidence.filter((ev) => !known.has(ev)).map((ev) => `evidence ${ev} is not on a fact edge from ${edge.from} to ${edge.to}`);
|
|
510
|
+
if (edge.evidence.length === 0) problems2.push("no evidence");
|
|
511
|
+
const evidence = cited.length ? cited : [...new Set(backing.flatMap((e) => e.evidence))].sort().slice(0, 3);
|
|
512
|
+
return { edge, supported: true, problems: problems2, evidence, facts: backing.length };
|
|
513
|
+
});
|
|
514
|
+
return { problems, edges, members };
|
|
515
|
+
}
|
|
516
|
+
var cmp2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
517
|
+
function cleanComponents(doc, verdict, facts) {
|
|
518
|
+
const components = [...doc.components].map((c) => ({ id: c.id, label: c.label, ...c.package !== void 0 ? { package: c.package } : {}, purpose: c.purpose, files: [...c.files] })).sort((a, b) => cmp2(a.package ?? "", b.package ?? "") || cmp2(a.id, b.id));
|
|
519
|
+
const edges = verdict.edges.filter((v) => v.supported).map((v) => ({ from: v.edge.from, to: v.edge.to, label: v.edge.label, evidence: v.evidence })).sort((a, b) => cmp2(a.from, b.from) || cmp2(a.to, b.to) || cmp2(a.label, b.label));
|
|
520
|
+
return { schema: 1, facts: facts.sources.hash, components, edges };
|
|
521
|
+
}
|
|
522
|
+
var serializeComponents = (doc) => prettyJson(doc);
|
|
523
|
+
function componentProblems(verdict) {
|
|
524
|
+
return [
|
|
525
|
+
...verdict.problems,
|
|
526
|
+
...verdict.edges.flatMap((v) => v.problems.map((p) => `edge ${v.edge.from} -> ${v.edge.to}${v.supported ? "" : " (unsupported)"}: ${p}`))
|
|
527
|
+
];
|
|
528
|
+
}
|
|
529
|
+
var cell = (s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
|
|
530
|
+
var quote = (s) => `"${s.replace(/"/g, "'")}"`;
|
|
531
|
+
function renderComponents(doc, verdict, facts, outDir, commands = DEFAULT_COMMANDS) {
|
|
532
|
+
const byId = new Map(facts.nodes.map((n) => [n.id, n]));
|
|
533
|
+
const link = (file, line) => `${posix2.relative(outDir, file)}${line ? `#L${line}` : ""}`;
|
|
534
|
+
const evLink = (ref) => {
|
|
535
|
+
const i = ref.lastIndexOf(":");
|
|
536
|
+
return `[${ref}](${link(ref.slice(0, i), Number(ref.slice(i + 1)))})`;
|
|
537
|
+
};
|
|
538
|
+
const firstFile = (id) => [...verdict.members.get(id) ?? []].map((m2) => byId.get(m2).file).sort()[0];
|
|
539
|
+
const nid = (id) => verdict.members.has(id) ? mermaidId("c", id) : mermaidId("x", id);
|
|
540
|
+
const kept = verdict.edges.filter((v) => v.supported);
|
|
541
|
+
const outside = [...new Set(kept.flatMap((v) => [v.edge.from, v.edge.to]).filter((id) => !verdict.members.has(id)))].sort();
|
|
542
|
+
const name = (id) => doc.components.find((c) => c.id === id)?.label ?? byId.get(id)?.label ?? id;
|
|
543
|
+
const m = ["flowchart LR"];
|
|
544
|
+
const groups = [...new Set(doc.components.map((c) => c.package ?? ""))].sort();
|
|
545
|
+
for (const g of groups) {
|
|
546
|
+
const inside = doc.components.filter((c) => (c.package ?? "") === g);
|
|
547
|
+
const pad = g ? " " : " ";
|
|
548
|
+
if (g) m.push(` subgraph ${mermaidId("sg", g)}[${quote(g)}]`);
|
|
549
|
+
for (const c of inside) m.push(`${pad}${nid(c.id)}[${quote(c.label)}]`);
|
|
550
|
+
if (g) m.push(" end");
|
|
551
|
+
}
|
|
552
|
+
for (const id of outside) {
|
|
553
|
+
const n = byId.get(id);
|
|
554
|
+
const shape = n.kind === "surface" ? n.attrs?.direction === "out" ? ["[(", ")]"] : ["([", "])"] : ["[[", "]]"];
|
|
555
|
+
m.push(` ${nid(id)}${shape[0]}${quote(n.label)}${shape[1]}`);
|
|
556
|
+
}
|
|
557
|
+
for (const v of kept) m.push(` ${nid(v.edge.from)} -->|${quote(v.edge.label)}| ${nid(v.edge.to)}`);
|
|
558
|
+
for (const c of doc.components) {
|
|
559
|
+
const f = firstFile(c.id);
|
|
560
|
+
if (f) m.push(` click ${nid(c.id)} "${link(f)}"`);
|
|
561
|
+
}
|
|
562
|
+
return [
|
|
563
|
+
"# Components",
|
|
564
|
+
"",
|
|
565
|
+
`> Proposed by agents (the \`/slate:arch\` skill) in [${COMPONENTS_JSON}](${COMPONENTS_JSON}) and rendered by \`${commands.verify} --write\`; edit ${COMPONENTS_JSON}, not this file.`,
|
|
566
|
+
`> Every edge is backed by a fact edge in [facts.json](facts.json); \`${commands.check}\` drops nothing but reports any edge the code no longer supports.`,
|
|
567
|
+
"",
|
|
568
|
+
"```mermaid",
|
|
569
|
+
...m,
|
|
570
|
+
"```",
|
|
571
|
+
"",
|
|
572
|
+
"## Components",
|
|
573
|
+
"",
|
|
574
|
+
"| Component | Package | Purpose | Files |",
|
|
575
|
+
"| --- | --- | --- | --- |",
|
|
576
|
+
...doc.components.map((c) => {
|
|
577
|
+
const n = verdict.members.get(c.id)?.size ?? 0;
|
|
578
|
+
return `| ${cell(c.label)} | ${c.package ? cell(c.package) : "-"} | ${cell(c.purpose)} | ${c.files.map((g) => `\`${g}\``).join(", ")} (${n} module${n === 1 ? "" : "s"}) |`;
|
|
579
|
+
}),
|
|
580
|
+
"",
|
|
581
|
+
"## Edges",
|
|
582
|
+
"",
|
|
583
|
+
"| From | To | What | Facts | Evidence |",
|
|
584
|
+
"| --- | --- | --- | --- | --- |",
|
|
585
|
+
...kept.map((v) => `| ${cell(name(v.edge.from))} | ${cell(name(v.edge.to))} | ${cell(v.edge.label)} | ${v.facts} | ${v.evidence.map(evLink).join(", ")} |`),
|
|
586
|
+
""
|
|
587
|
+
].join("\n");
|
|
588
|
+
}
|
|
589
|
+
var componentsPaths = (outDir) => ({ json: `${outDir}/${COMPONENTS_JSON}`, md: `${outDir}/${COMPONENTS_MD}` });
|
|
590
|
+
function checkComponents(root, outDir, facts, commands, fix) {
|
|
591
|
+
const paths = componentsPaths(outDir);
|
|
592
|
+
if (!existsSync(join2(root, paths.json))) return [];
|
|
593
|
+
let doc;
|
|
594
|
+
try {
|
|
595
|
+
doc = parseComponents(readFileSync2(join2(root, paths.json), "utf8"), paths.json);
|
|
596
|
+
} catch (err) {
|
|
597
|
+
return [{ file: paths.json, reason: err.message.replace(`${paths.json}: `, "") }];
|
|
598
|
+
}
|
|
599
|
+
const verdict = verifyComponents(doc, facts);
|
|
600
|
+
const out = componentProblems(verdict).map((reason) => ({ file: paths.json, reason: `${reason}; ${fix}` }));
|
|
601
|
+
if (out.length) return out;
|
|
602
|
+
const md = existsSync(join2(root, paths.md)) ? readFileSync2(join2(root, paths.md), "utf8") : void 0;
|
|
603
|
+
if (md === void 0) out.push({ file: paths.md, reason: `missing; ${fix}` });
|
|
604
|
+
else if (md !== renderComponents(doc, verdict, facts, outDir, commands)) out.push({ file: paths.md, reason: `differs from what ${COMPONENTS_JSON} renders (edited by hand?); ${fix}` });
|
|
605
|
+
return out;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// ../arch/src/extract.ts
|
|
609
|
+
import { readFileSync as readFileSync3, realpathSync } from "node:fs";
|
|
610
|
+
import { isBuiltin } from "node:module";
|
|
611
|
+
import { dirname as dirname2, join as join4, resolve } from "node:path";
|
|
612
|
+
|
|
613
|
+
// ../arch/src/ts.ts
|
|
614
|
+
import { createRequire } from "node:module";
|
|
615
|
+
import { join as join3 } from "node:path";
|
|
616
|
+
var TypeScriptMissing = class extends Error {
|
|
617
|
+
};
|
|
618
|
+
var cache = /* @__PURE__ */ new Map();
|
|
619
|
+
function loadFrom(require2) {
|
|
620
|
+
let manifest;
|
|
621
|
+
try {
|
|
622
|
+
manifest = require2.resolve("typescript/package.json");
|
|
623
|
+
} catch {
|
|
624
|
+
return "not installed";
|
|
625
|
+
}
|
|
626
|
+
const version = require2(manifest).version;
|
|
627
|
+
if (Number(version.split(".")[0]) < 7) return `version ${version}`;
|
|
628
|
+
const cached = cache.get(manifest);
|
|
629
|
+
if (cached) return cached;
|
|
630
|
+
const ast = require2("typescript/unstable/ast");
|
|
631
|
+
const sync = require2("typescript/unstable/sync");
|
|
632
|
+
const ts2 = { ...ast, API: sync.API, version, from: manifest };
|
|
633
|
+
cache.set(manifest, ts2);
|
|
634
|
+
return ts2;
|
|
635
|
+
}
|
|
636
|
+
function loadTypeScript(root) {
|
|
637
|
+
const tried = [];
|
|
638
|
+
for (const [where, require2] of [
|
|
639
|
+
[root, createRequire(join3(root, "package.json"))],
|
|
640
|
+
["slate's install", createRequire(import.meta.url)]
|
|
641
|
+
]) {
|
|
642
|
+
const got = loadFrom(require2);
|
|
643
|
+
if (typeof got !== "string") return got;
|
|
644
|
+
tried.push(`${where}: ${got}`);
|
|
645
|
+
}
|
|
646
|
+
throw new TypeScriptMissing(
|
|
647
|
+
`the architecture extractor needs TypeScript 7 or later (${tried.join("; ")}); install it in the repository (npm i -D typescript@7), or next to slate (npm i -g typescript@7 for a global slate, npx -p slateboard -p typescript@7 slate \u2026 with npx)`
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ../arch/src/extract.ts
|
|
652
|
+
var ts;
|
|
653
|
+
var formatEvidence = (e) => `${e.file}:${e.line}`;
|
|
654
|
+
var METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete"]);
|
|
655
|
+
var DEP_SECTIONS = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
|
|
656
|
+
var moduleId = (file) => `module:${file}`;
|
|
657
|
+
var packageId = (name) => `package:${name}`;
|
|
658
|
+
function sourceGlobs(config) {
|
|
659
|
+
return [...config.packages.map(manifestGlob), ...config.modules, ...config.migrations, ...config.extraSources];
|
|
660
|
+
}
|
|
661
|
+
function lines(text) {
|
|
662
|
+
return text.split(/\r?\n/);
|
|
663
|
+
}
|
|
664
|
+
function sortEvidence(ev) {
|
|
665
|
+
const seen = /* @__PURE__ */ new Set();
|
|
666
|
+
return ev.filter((e) => {
|
|
667
|
+
const k = `${e.file}:${e.line}`;
|
|
668
|
+
if (seen.has(k)) return false;
|
|
669
|
+
seen.add(k);
|
|
670
|
+
return true;
|
|
671
|
+
}).sort((a, b) => a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1);
|
|
672
|
+
}
|
|
673
|
+
function findLine(text, re, from = 0) {
|
|
674
|
+
const ls = lines(text);
|
|
675
|
+
for (let i = from; i < ls.length; i++) if (re.test(ls[i])) return i + 1;
|
|
676
|
+
return void 0;
|
|
677
|
+
}
|
|
678
|
+
function escapeRe(s) {
|
|
679
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
680
|
+
}
|
|
681
|
+
function externalName(spec) {
|
|
682
|
+
if (spec.startsWith("node:")) return spec;
|
|
683
|
+
const parts = spec.split("/");
|
|
684
|
+
const name = spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
685
|
+
return isBuiltin(name) ? `node:${name}` : name;
|
|
686
|
+
}
|
|
687
|
+
var Graph = class {
|
|
688
|
+
nodes = /* @__PURE__ */ new Map();
|
|
689
|
+
edges = /* @__PURE__ */ new Map();
|
|
690
|
+
node(n) {
|
|
691
|
+
const existing = this.nodes.get(n.id);
|
|
692
|
+
if (existing) {
|
|
693
|
+
existing.evidence.push(...n.evidence);
|
|
694
|
+
return existing;
|
|
695
|
+
}
|
|
696
|
+
this.nodes.set(n.id, n);
|
|
697
|
+
return n;
|
|
698
|
+
}
|
|
699
|
+
edge(e) {
|
|
700
|
+
const key = `${e.from}\0${e.to}\0${e.kind}`;
|
|
701
|
+
const existing = this.edges.get(key);
|
|
702
|
+
if (!existing) {
|
|
703
|
+
this.edges.set(key, { ...e, evidence: [...e.evidence], ...e.detail ? { detail: [...e.detail] } : {} });
|
|
704
|
+
return this.edges.get(key);
|
|
705
|
+
}
|
|
706
|
+
existing.evidence.push(...e.evidence);
|
|
707
|
+
if (e.detail) existing.detail = [.../* @__PURE__ */ new Set([...existing.detail ?? [], ...e.detail])];
|
|
708
|
+
if (existing.typeOnly && !e.typeOnly) delete existing.typeOnly;
|
|
709
|
+
if (e.dynamic) existing.dynamic = true;
|
|
710
|
+
return existing;
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
function lineFinder(sf) {
|
|
714
|
+
const starts = ts.computeLineStarts(sf.text);
|
|
715
|
+
return (node) => {
|
|
716
|
+
const pos = node.getStart(sf);
|
|
717
|
+
let lo = 0;
|
|
718
|
+
let hi = starts.length - 1;
|
|
719
|
+
while (lo < hi) {
|
|
720
|
+
const mid = lo + hi + 1 >> 1;
|
|
721
|
+
if (starts[mid] <= pos) lo = mid;
|
|
722
|
+
else hi = mid - 1;
|
|
723
|
+
}
|
|
724
|
+
return lo + 1;
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
function walk(node, visit) {
|
|
728
|
+
visit(node);
|
|
729
|
+
node.forEachChild((child) => {
|
|
730
|
+
walk(child, visit);
|
|
731
|
+
return void 0;
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
function stringValue(node) {
|
|
735
|
+
if (!node) return void 0;
|
|
736
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
|
737
|
+
return void 0;
|
|
738
|
+
}
|
|
739
|
+
function urlCandidates(arg) {
|
|
740
|
+
if (!arg) return [];
|
|
741
|
+
if (ts.isConditionalExpression(arg)) return [...urlCandidates(arg.whenTrue), ...urlCandidates(arg.whenFalse)];
|
|
742
|
+
let path2 = stringValue(arg);
|
|
743
|
+
let prefixOnly = false;
|
|
744
|
+
if (path2 === void 0 && ts.isTemplateExpression(arg)) {
|
|
745
|
+
path2 = arg.head.text || arg.templateSpans[0]?.literal.text;
|
|
746
|
+
prefixOnly = arg.head.text ? true : arg.templateSpans.length > 1;
|
|
747
|
+
}
|
|
748
|
+
return path2?.startsWith("/") ? [{ path: path2, prefixOnly }] : [];
|
|
749
|
+
}
|
|
750
|
+
function collectImports(sf, lineOf) {
|
|
751
|
+
const sites = [];
|
|
752
|
+
const add = (specNode, at2, typeOnly, dynamic) => {
|
|
753
|
+
const spec = stringValue(specNode);
|
|
754
|
+
if (spec === void 0 || !specNode) return;
|
|
755
|
+
sites.push({ spec, node: specNode, line: lineOf(at2), typeOnly, dynamic });
|
|
756
|
+
};
|
|
757
|
+
walk(sf, (n) => {
|
|
758
|
+
if (ts.isImportDeclaration(n)) {
|
|
759
|
+
const clause = n.importClause;
|
|
760
|
+
const named = clause?.namedBindings;
|
|
761
|
+
const allTypeSpecifiers = !!named && ts.isNamedImports(named) && named.elements.length > 0 && !clause?.name && named.elements.every((e) => e.isTypeOnly);
|
|
762
|
+
add(n.moduleSpecifier, n, clause?.phaseModifier === ts.SyntaxKind.TypeKeyword || allTypeSpecifiers, false);
|
|
763
|
+
} else if (ts.isExportDeclaration(n)) {
|
|
764
|
+
add(n.moduleSpecifier, n, n.isTypeOnly, false);
|
|
765
|
+
} else if (ts.isCallExpression(n) && n.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
766
|
+
add(n.arguments[0], n, false, true);
|
|
767
|
+
} else if (ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument)) {
|
|
768
|
+
add(n.argument.literal, n, true, false);
|
|
769
|
+
}
|
|
770
|
+
});
|
|
771
|
+
return sites;
|
|
772
|
+
}
|
|
773
|
+
function readPackages(root, config) {
|
|
774
|
+
const manifests = listFiles(root, config.packages.map(manifestGlob), config.ignore);
|
|
775
|
+
return manifests.map((manifest) => {
|
|
776
|
+
const json = JSON.parse(readFileSync3(join4(root, manifest), "utf8"));
|
|
777
|
+
return { name: json.name ?? dirname2(manifest), dir: dirname2(manifest), manifest };
|
|
778
|
+
}).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
779
|
+
}
|
|
780
|
+
function packageOf(pkgs, file) {
|
|
781
|
+
return pkgs.filter((p) => p.dir === "." || file.startsWith(`${p.dir}/`)).sort((a, b) => b.dir.length - a.dir.length)[0];
|
|
782
|
+
}
|
|
783
|
+
function extractFacts(root, config) {
|
|
784
|
+
root = realpathSync(resolve(root));
|
|
785
|
+
ts = loadTypeScript(root);
|
|
786
|
+
const g = new Graph();
|
|
787
|
+
const unresolved = [];
|
|
788
|
+
const pkgs = readPackages(root, config);
|
|
789
|
+
const pkgByName = new Map(pkgs.map((p) => [p.name, p]));
|
|
790
|
+
for (const p of pkgs) {
|
|
791
|
+
const text = readFileSync3(join4(root, p.manifest), "utf8");
|
|
792
|
+
g.node({
|
|
793
|
+
id: packageId(p.name),
|
|
794
|
+
kind: "package",
|
|
795
|
+
label: p.name,
|
|
796
|
+
package: p.name,
|
|
797
|
+
file: p.manifest,
|
|
798
|
+
attrs: { dir: p.dir },
|
|
799
|
+
evidence: [{ file: p.manifest, line: findLine(text, /^\s*"name"\s*:/) ?? 1 }]
|
|
800
|
+
});
|
|
801
|
+
const json = JSON.parse(text);
|
|
802
|
+
for (const section of DEP_SECTIONS) {
|
|
803
|
+
const deps = json[section];
|
|
804
|
+
if (!deps) continue;
|
|
805
|
+
const sectionLine = findLine(text, new RegExp(`^\\s*"${section}"\\s*:`)) ?? 1;
|
|
806
|
+
for (const dep of Object.keys(deps).sort()) {
|
|
807
|
+
if (!pkgByName.has(dep)) continue;
|
|
808
|
+
const line = findLine(text, new RegExp(`^\\s*"${escapeRe(dep)}"\\s*:`), sectionLine) ?? sectionLine;
|
|
809
|
+
g.edge({ from: packageId(p.name), to: packageId(dep), kind: "depends", section, evidence: [{ file: p.manifest, line }] });
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const moduleFiles = listFiles(root, config.modules, config.ignore);
|
|
814
|
+
const byLowerAbs = new Map(moduleFiles.map((f) => [join4(root, f).toLowerCase(), f]));
|
|
815
|
+
const parsed = /* @__PURE__ */ new Map();
|
|
816
|
+
const api = new ts.API({ cwd: root });
|
|
817
|
+
try {
|
|
818
|
+
const abs = moduleFiles.map((f) => join4(root, f));
|
|
819
|
+
const snapshot = api.updateSnapshot({ openFiles: abs });
|
|
820
|
+
for (const file of moduleFiles) {
|
|
821
|
+
const absFile = join4(root, file);
|
|
822
|
+
const project = snapshot.getDefaultProjectForFile(absFile);
|
|
823
|
+
const sf = project?.program.getSourceFile(absFile);
|
|
824
|
+
if (!project || !sf) throw new Error(`the compiler did not load ${file}`);
|
|
825
|
+
const lineOf = lineFinder(sf);
|
|
826
|
+
const imports = collectImports(sf, lineOf);
|
|
827
|
+
const symbols = imports.length ? project.checker.getSymbolAtLocation(imports.map((i) => i.node)) : [];
|
|
828
|
+
const resolved = symbols.map((s) => {
|
|
829
|
+
const decl = s?.declarations?.[0];
|
|
830
|
+
return decl ? byLowerAbs.get(String(decl.path).toLowerCase()) : void 0;
|
|
831
|
+
});
|
|
832
|
+
parsed.set(file, { file, sf, lineOf, imports, resolved });
|
|
833
|
+
}
|
|
834
|
+
} finally {
|
|
835
|
+
api.close();
|
|
836
|
+
}
|
|
837
|
+
for (const file of moduleFiles) {
|
|
838
|
+
const pkg = packageOf(pkgs, file);
|
|
839
|
+
g.node({ id: moduleId(file), kind: "module", label: file, ...pkg ? { package: pkg.name } : {}, file, evidence: [{ file, line: 1 }] });
|
|
840
|
+
if (pkg) g.edge({ from: packageId(pkg.name), to: moduleId(file), kind: "contains", evidence: [{ file, line: 1 }] });
|
|
841
|
+
}
|
|
842
|
+
for (const m of parsed.values()) {
|
|
843
|
+
m.imports.forEach((site, i) => {
|
|
844
|
+
const target = m.resolved[i];
|
|
845
|
+
const ev = [{ file: m.file, line: site.line }];
|
|
846
|
+
const flags = { detail: [site.spec], ...site.typeOnly ? { typeOnly: true } : {}, ...site.dynamic ? { dynamic: true } : {} };
|
|
847
|
+
if (target) {
|
|
848
|
+
g.edge({ from: moduleId(m.file), to: moduleId(target), kind: "imports", ...flags, evidence: ev });
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
if (site.spec.startsWith(".")) {
|
|
852
|
+
if (/\.(css|scss|svg|png|jpe?g|gif|webp|woff2?|json)$/.test(site.spec)) return;
|
|
853
|
+
unresolved.push({ file: m.file, line: site.line, specifier: site.spec });
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
const ws = pkgs.find((p) => site.spec === p.name || site.spec.startsWith(`${p.name}/`));
|
|
857
|
+
if (ws) {
|
|
858
|
+
g.edge({ from: moduleId(m.file), to: packageId(ws.name), kind: "imports", ...flags, evidence: ev });
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const name = externalName(site.spec);
|
|
862
|
+
g.node({ id: `external:${name}`, kind: "external", label: name, evidence: [...ev] });
|
|
863
|
+
g.edge({ from: moduleId(m.file), to: `external:${name}`, kind: "imports", ...flags, evidence: ev });
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
const moduleOf = (file) => parsed.get(file);
|
|
867
|
+
const declare = (owner, node) => {
|
|
868
|
+
g.node(node);
|
|
869
|
+
g.edge({ from: owner, to: node.id, kind: "declares", evidence: [...node.evidence] });
|
|
870
|
+
};
|
|
871
|
+
const pkgName = (file) => packageOf(pkgs, file)?.name;
|
|
872
|
+
const withPkg = (file) => pkgName(file) ? { package: pkgName(file) } : {};
|
|
873
|
+
const cli = config.entries.cli;
|
|
874
|
+
const cliMod = cli && moduleOf(cli.file);
|
|
875
|
+
if (cli && cliMod) {
|
|
876
|
+
const names = [];
|
|
877
|
+
for (const st of cliMod.sf.statements) {
|
|
878
|
+
if (!ts.isTypeAliasDeclaration(st) || st.name.text !== cli.typeName || !ts.isUnionTypeNode(st.type)) continue;
|
|
879
|
+
for (const member of st.type.types) {
|
|
880
|
+
if (!ts.isTypeLiteralNode(member)) continue;
|
|
881
|
+
for (const prop of member.members) {
|
|
882
|
+
if (!ts.isPropertySignatureDeclaration(prop) || !ts.isIdentifier(prop.name) || prop.name.text !== "name" || !prop.type || !ts.isLiteralTypeNode(prop.type)) continue;
|
|
883
|
+
const value = stringValue(prop.type.literal);
|
|
884
|
+
if (value !== void 0) names.push({ name: value, line: cliMod.lineOf(prop.type.literal) });
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
const dispatch = /* @__PURE__ */ new Map();
|
|
889
|
+
const dispatchMod = cli.dispatchFile ? moduleOf(cli.dispatchFile) : void 0;
|
|
890
|
+
if (dispatchMod) {
|
|
891
|
+
walk(dispatchMod.sf, (n) => {
|
|
892
|
+
const v = ts.isCaseClause(n) ? stringValue(n.expression) : void 0;
|
|
893
|
+
if (v !== void 0 && !dispatch.has(v)) dispatch.set(v, dispatchMod.lineOf(n));
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
for (const { name, line } of names) {
|
|
897
|
+
const ev = [{ file: cli.file, line }];
|
|
898
|
+
const handled = dispatch.get(name);
|
|
899
|
+
if (handled !== void 0 && cli.dispatchFile) ev.push({ file: cli.dispatchFile, line: handled });
|
|
900
|
+
declare(moduleId(cli.file), { id: `cli:${name}`, kind: "cli-command", label: name, ...withPkg(cli.file), file: cli.file, evidence: ev });
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
const routes = [];
|
|
904
|
+
for (const src of config.entries.routes) {
|
|
905
|
+
const mod = moduleOf(src.file);
|
|
906
|
+
if (!mod) continue;
|
|
907
|
+
walk(mod.sf, (n) => {
|
|
908
|
+
if (!ts.isCallExpression(n) || !ts.isPropertyAccessExpression(n.expression)) return;
|
|
909
|
+
const recv = n.expression.expression;
|
|
910
|
+
const method = ts.isIdentifier(n.expression.name) ? n.expression.name.text : void 0;
|
|
911
|
+
if (!ts.isIdentifier(recv) || recv.text !== src.receiver || !method || !METHODS.has(method)) return;
|
|
912
|
+
const path2 = stringValue(n.arguments[0]);
|
|
913
|
+
if (path2 === void 0 || path2.includes("*")) return;
|
|
914
|
+
const full = path2 === "/" && src.prefix ? src.prefix : `${src.prefix}${path2}`;
|
|
915
|
+
const label = `${method.toUpperCase()} ${full}`;
|
|
916
|
+
routes.push({ path: full, pkg: pkgName(src.file) });
|
|
917
|
+
declare(moduleId(src.file), {
|
|
918
|
+
id: `route:${label}`,
|
|
919
|
+
kind: "http-route",
|
|
920
|
+
label,
|
|
921
|
+
...withPkg(src.file),
|
|
922
|
+
file: src.file,
|
|
923
|
+
attrs: { method: method.toUpperCase(), path: full },
|
|
924
|
+
evidence: [{ file: src.file, line: mod.lineOf(n) }]
|
|
925
|
+
});
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
const tools = config.entries.mcpTools;
|
|
929
|
+
const toolsMod = tools && moduleOf(tools.file);
|
|
930
|
+
if (tools && toolsMod) {
|
|
931
|
+
walk(toolsMod.sf, (n) => {
|
|
932
|
+
if (!ts.isCallExpression(n) || !ts.isIdentifier(n.expression) || n.expression.text !== tools.callee) return;
|
|
933
|
+
const name = stringValue(n.arguments[0]);
|
|
934
|
+
if (name === void 0) return;
|
|
935
|
+
declare(moduleId(tools.file), { id: `mcp:${name}`, kind: "mcp-tool", label: name, ...withPkg(tools.file), file: tools.file, evidence: [{ file: tools.file, line: toolsMod.lineOf(n.arguments[0]) }] });
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
const events = config.entries.events;
|
|
939
|
+
const eventsMod = events && moduleOf(events.file);
|
|
940
|
+
if (events && eventsMod) {
|
|
941
|
+
for (const st of eventsMod.sf.statements) {
|
|
942
|
+
if (!ts.isTypeAliasDeclaration(st) || st.name.text !== events.typeName) continue;
|
|
943
|
+
const members = ts.isUnionTypeNode(st.type) ? st.type.types : [st.type];
|
|
944
|
+
for (const t of members) {
|
|
945
|
+
const value = ts.isLiteralTypeNode(t) ? stringValue(t.literal) : void 0;
|
|
946
|
+
if (value === void 0) continue;
|
|
947
|
+
declare(moduleId(events.file), { id: `event:${value}`, kind: "sse-event", label: value, ...withPkg(events.file), file: events.file, evidence: [{ file: events.file, line: eventsMod.lineOf(t) }] });
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
for (const file of listFiles(root, config.migrations, config.ignore)) {
|
|
952
|
+
const pkg = packageOf(pkgs, file);
|
|
953
|
+
const id = `migration:${file}`;
|
|
954
|
+
g.node({ id, kind: "migration", label: file, ...pkg ? { package: pkg.name } : {}, file, evidence: [{ file, line: 1 }] });
|
|
955
|
+
if (pkg) g.edge({ from: packageId(pkg.name), to: id, kind: "contains", evidence: [{ file, line: 1 }] });
|
|
956
|
+
lines(readFileSync3(join4(root, file), "utf8")).forEach((text, i) => {
|
|
957
|
+
const m = /^\s*CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?(\w+)/i.exec(text);
|
|
958
|
+
if (m) declare(id, { id: `table:${m[1]}`, kind: "db-table", label: m[1], ...pkg ? { package: pkg.name } : {}, file, evidence: [{ file, line: i + 1 }] });
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
for (const m of parsed.values()) {
|
|
962
|
+
walk(m.sf, (n) => {
|
|
963
|
+
const isFetch = ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === "fetch";
|
|
964
|
+
const isSse = ts.isNewExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === "EventSource";
|
|
965
|
+
if (!isFetch && !isSse) return;
|
|
966
|
+
const arg = n.arguments?.[0];
|
|
967
|
+
for (const url of urlCandidates(arg)) {
|
|
968
|
+
const bare = url.path.split("?")[0];
|
|
969
|
+
const targets = new Set(routes.filter((r) => url.prefixOnly ? r.path.startsWith(bare) : r.path === bare).map((r) => r.pkg));
|
|
970
|
+
for (const t of [...targets].sort()) {
|
|
971
|
+
if (!t || t === pkgName(m.file)) continue;
|
|
972
|
+
g.edge({ from: moduleId(m.file), to: packageId(t), kind: "http", detail: [url.path], evidence: [{ file: m.file, line: m.lineOf(n) }] });
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
for (const s of config.surfaces) {
|
|
978
|
+
const id = `surface:${s.id}`;
|
|
979
|
+
const hits = [];
|
|
980
|
+
for (const m of parsed.values()) {
|
|
981
|
+
for (const site of m.imports) if (s.imports?.includes(site.spec)) hits.push({ module: m.file, ev: { file: m.file, line: site.line } });
|
|
982
|
+
if (s.pattern) {
|
|
983
|
+
const re = new RegExp(s.pattern);
|
|
984
|
+
lines(m.sf.text).forEach((text, i) => {
|
|
985
|
+
if (re.test(text)) hits.push({ module: m.file, ev: { file: m.file, line: i + 1 } });
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
if (s.file && parsed.has(s.file.module)) {
|
|
990
|
+
const line = findLine(readFileSync3(join4(root, s.file.path), "utf8"), new RegExp(s.file.pattern));
|
|
991
|
+
if (line !== void 0) hits.push({ module: s.file.module, ev: { file: s.file.path, line } });
|
|
992
|
+
}
|
|
993
|
+
if (hits.length === 0) continue;
|
|
994
|
+
const sorted = sortEvidence(hits.map((h) => h.ev));
|
|
995
|
+
g.node({ id, kind: "surface", label: s.label, attrs: { direction: s.direction }, evidence: [sorted[0]] });
|
|
996
|
+
for (const h of hits) {
|
|
997
|
+
const [from, to] = s.direction === "in" ? [id, moduleId(h.module)] : [moduleId(h.module), id];
|
|
998
|
+
g.edge({ from, to, kind: s.direction === "in" ? "invokes" : "uses", evidence: [h.ev] });
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
const nodes = [...g.nodes.values()].map((n) => {
|
|
1002
|
+
const out = { id: n.id, kind: n.kind, label: n.label };
|
|
1003
|
+
if (n.package) out.package = n.package;
|
|
1004
|
+
if (n.file) out.file = n.file;
|
|
1005
|
+
if (n.attrs) out.attrs = Object.fromEntries(Object.entries(n.attrs).sort(([a], [b]) => a < b ? -1 : 1));
|
|
1006
|
+
out.evidence = (n.kind === "external" ? sortEvidence(n.evidence).slice(0, 1) : sortEvidence(n.evidence)).map(formatEvidence);
|
|
1007
|
+
return out;
|
|
1008
|
+
}).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
1009
|
+
const edges = [...g.edges.values()].map((e) => {
|
|
1010
|
+
const out = { from: e.from, to: e.to, kind: e.kind };
|
|
1011
|
+
if (e.detail) out.detail = [...new Set(e.detail)].sort();
|
|
1012
|
+
if (e.typeOnly) out.typeOnly = true;
|
|
1013
|
+
if (e.dynamic) out.dynamic = true;
|
|
1014
|
+
if (e.section) out.section = e.section;
|
|
1015
|
+
out.evidence = sortEvidence(e.evidence).map(formatEvidence);
|
|
1016
|
+
return out;
|
|
1017
|
+
}).sort((a, b) => cmp3(a.from, b.from) || cmp3(a.to, b.to) || cmp3(a.kind, b.kind));
|
|
1018
|
+
const count = (xs, key) => {
|
|
1019
|
+
const c = {};
|
|
1020
|
+
for (const x of xs) c[key(x)] = (c[key(x)] ?? 0) + 1;
|
|
1021
|
+
return Object.fromEntries(Object.entries(c).sort(([a], [b]) => cmp3(a, b)));
|
|
1022
|
+
};
|
|
1023
|
+
const globs = sourceGlobs(config);
|
|
1024
|
+
const files = hashFiles(root, listFiles(root, globs, config.ignore));
|
|
1025
|
+
return {
|
|
1026
|
+
schema: 1,
|
|
1027
|
+
generator: "@slate/arch",
|
|
1028
|
+
sources: { globs, ignore: [...config.ignore], commit: lastCommit(root, globs, config.ignore), hash: aggregateHash(files), files },
|
|
1029
|
+
counts: { nodes: count(nodes, (n) => n.kind), edges: count(edges, (e) => e.kind) },
|
|
1030
|
+
nodes,
|
|
1031
|
+
edges,
|
|
1032
|
+
unresolved: unresolved.sort((a, b) => cmp3(a.file, b.file) || a.line - b.line)
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
function cmp3(a, b) {
|
|
1036
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
1037
|
+
}
|
|
1038
|
+
function serializeFacts(graph) {
|
|
1039
|
+
const list = (xs) => xs.length ? `[
|
|
1040
|
+
${xs.map((x) => ` ${JSON.stringify(x)}`).join(",\n")}
|
|
1041
|
+
]` : "[]";
|
|
1042
|
+
const head = JSON.stringify({ schema: graph.schema, generator: graph.generator, sources: graph.sources, counts: graph.counts }, null, 2);
|
|
1043
|
+
return `${head.slice(0, -2)},
|
|
1044
|
+
"nodes": ${list(graph.nodes)},
|
|
1045
|
+
"edges": ${list(graph.edges)},
|
|
1046
|
+
"unresolved": ${list(graph.unresolved)}
|
|
1047
|
+
}
|
|
1048
|
+
`;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// ../arch/src/flows.ts
|
|
1052
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1053
|
+
import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
|
|
1054
|
+
import { join as join5, posix as posix3 } from "node:path";
|
|
1055
|
+
var RESERVED = /* @__PURE__ */ new Set(["facts", "system", "packages"]);
|
|
1056
|
+
var ID2 = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
1057
|
+
var UNSAFE = /[;#\n\r]/;
|
|
1058
|
+
var flowFile = (outDir, flow) => `${outDir}/${flow.name}.md`;
|
|
1059
|
+
var specHash = (flow) => createHash2("sha256").update(JSON.stringify(flow)).digest("hex");
|
|
1060
|
+
var kindOf = (s) => s.kind ?? "call";
|
|
1061
|
+
var short = (file) => file.replace(/^packages\//, "").replace("/src/", "/");
|
|
1062
|
+
function evidenceRegExp(ev) {
|
|
1063
|
+
if (ev.pattern !== void 0) return new RegExp(ev.pattern);
|
|
1064
|
+
const s = ev.symbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1065
|
+
const declaration = `\\b(?:function\\*?|class|const|let|var|interface|type|enum)\\s+${s}\\b`;
|
|
1066
|
+
const method = `^\\s*(?:(?:public|private|protected|static|async)\\s+)*${s}\\s*(?:<[^>]*>)?\\(`;
|
|
1067
|
+
return new RegExp(`(?:${declaration})|(?:${method})`);
|
|
1068
|
+
}
|
|
1069
|
+
function validateFlowSpec(flow) {
|
|
1070
|
+
const problems = [];
|
|
1071
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(flow.name)) problems.push(`flow name '${flow.name}' must be lowercase letters, digits and dashes`);
|
|
1072
|
+
if (RESERVED.has(flow.name)) problems.push(`flow name '${flow.name}' is taken by a generated file`);
|
|
1073
|
+
if (!flow.sources.length) problems.push("a flow needs source globs");
|
|
1074
|
+
if (!flow.steps.length) problems.push("a flow needs at least one step");
|
|
1075
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1076
|
+
const boxes = [];
|
|
1077
|
+
for (const p of flow.participants) {
|
|
1078
|
+
if (!ID2.test(p.id)) problems.push(`participant id '${p.id}' must be a letter followed by letters, digits or _`);
|
|
1079
|
+
if (byId.has(p.id)) problems.push(`participant ${p.id} is declared twice`);
|
|
1080
|
+
else byId.set(p.id, p);
|
|
1081
|
+
if (UNSAFE.test(p.label)) problems.push(`participant ${p.id}: the label may not contain ; # or a line break`);
|
|
1082
|
+
if (!!p.modules?.length === !!p.surface) problems.push(`participant ${p.id} must name either modules or a surface`);
|
|
1083
|
+
if (p.modules?.length && !p.process) problems.push(`participant ${p.id} has modules but no process`);
|
|
1084
|
+
if (p.process && boxes.at(-1) !== p.process) {
|
|
1085
|
+
if (boxes.includes(p.process)) problems.push(`participants of process '${p.process}' must be listed together`);
|
|
1086
|
+
boxes.push(p.process);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
const owners = /* @__PURE__ */ new Map();
|
|
1090
|
+
for (const p of flow.participants) {
|
|
1091
|
+
for (const m of p.modules ?? []) {
|
|
1092
|
+
if (owners.has(m)) problems.push(`module ${m} belongs to both ${owners.get(m)} and ${p.id}`);
|
|
1093
|
+
else owners.set(m, p.id);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
flow.steps.forEach((s, i) => {
|
|
1097
|
+
const at2 = `step ${i + 1} (${s.from} \u2192 ${s.to})`;
|
|
1098
|
+
const from = byId.get(s.from);
|
|
1099
|
+
const to = byId.get(s.to);
|
|
1100
|
+
if (!from) problems.push(`${at2}: unknown participant ${s.from}`);
|
|
1101
|
+
if (!to) problems.push(`${at2}: unknown participant ${s.to}`);
|
|
1102
|
+
if (UNSAFE.test(s.label)) problems.push(`${at2}: the label may not contain ; # or a line break`);
|
|
1103
|
+
if (s.kind !== void 0 && !["call", "reply", "callback"].includes(s.kind)) problems.push(`${at2}: unknown kind '${s.kind}'`);
|
|
1104
|
+
if (from?.surface && to?.surface) problems.push(`${at2}: a step needs a module on at least one end`);
|
|
1105
|
+
if (s.evidence.pattern === void 0 === (s.evidence.symbol === void 0)) problems.push(`${at2}: evidence needs exactly one of pattern or symbol`);
|
|
1106
|
+
for (const [name, p] of [["pattern", s.evidence.pattern], ["anchor", s.evidence.after]]) {
|
|
1107
|
+
if (p === void 0) continue;
|
|
1108
|
+
try {
|
|
1109
|
+
new RegExp(p);
|
|
1110
|
+
} catch (e) {
|
|
1111
|
+
problems.push(`${at2}: evidence ${name} is not a regular expression (${e.message})`);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
if (from && to && ![...from.modules ?? [], ...to.modules ?? []].includes(s.evidence.file)) {
|
|
1115
|
+
problems.push(`${at2}: evidence ${s.evidence.file} is not a module of ${s.from} or ${s.to}`);
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
return problems;
|
|
1119
|
+
}
|
|
1120
|
+
function importPath(facts, starts, goal) {
|
|
1121
|
+
const out = /* @__PURE__ */ new Map();
|
|
1122
|
+
for (const e of facts.edges) {
|
|
1123
|
+
if (e.kind !== "imports" || !e.from.startsWith("module:") || !e.to.startsWith("module:")) continue;
|
|
1124
|
+
if (!out.has(e.from)) out.set(e.from, []);
|
|
1125
|
+
out.get(e.from).push({ to: e.to, typeOnly: !!e.typeOnly });
|
|
1126
|
+
}
|
|
1127
|
+
const less = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
1128
|
+
const best = /* @__PURE__ */ new Map();
|
|
1129
|
+
starts.map(moduleId).forEach((s, rank) => {
|
|
1130
|
+
if (facts.nodes.some((n) => n.id === s) && !best.has(s)) best.set(s, { cost: [0, 0, rank], from: null, typeOnly: false });
|
|
1131
|
+
});
|
|
1132
|
+
const done = /* @__PURE__ */ new Set();
|
|
1133
|
+
for (; ; ) {
|
|
1134
|
+
let cur;
|
|
1135
|
+
for (const [id, b] of best) {
|
|
1136
|
+
if (done.has(id)) continue;
|
|
1137
|
+
if (cur === void 0 || less(b.cost, best.get(cur).cost) < 0 || less(b.cost, best.get(cur).cost) === 0 && id < cur) cur = id;
|
|
1138
|
+
}
|
|
1139
|
+
if (cur === void 0) return null;
|
|
1140
|
+
done.add(cur);
|
|
1141
|
+
if (goal(cur)) {
|
|
1142
|
+
const files = [];
|
|
1143
|
+
let typeOnly = false;
|
|
1144
|
+
for (let at2 = cur; at2; at2 = best.get(at2).from) {
|
|
1145
|
+
files.unshift(at2.slice("module:".length));
|
|
1146
|
+
typeOnly ||= best.get(at2).typeOnly;
|
|
1147
|
+
}
|
|
1148
|
+
return { files, typeOnly };
|
|
1149
|
+
}
|
|
1150
|
+
const c = best.get(cur).cost;
|
|
1151
|
+
for (const next of out.get(cur) ?? []) {
|
|
1152
|
+
const cost = [c[0] + (next.typeOnly ? 1 : 0), c[1] + 1, c[2]];
|
|
1153
|
+
const known = best.get(next.to);
|
|
1154
|
+
if (!done.has(next.to) && (!known || less(cost, known.cost) < 0)) best.set(next.to, { cost, from: cur, typeOnly: next.typeOnly });
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
var describePath = (p) => p.files.length === 1 ? `same module ${short(p.files[0])}` : `imports ${p.files.map(short).join(" \u2192 ")}${p.typeOnly ? " (type-only hop)" : ""}`;
|
|
1159
|
+
function verifyFlow(flow, facts, root) {
|
|
1160
|
+
const structural = validateFlowSpec(flow);
|
|
1161
|
+
if (structural.length) return { steps: flow.steps.map(() => ({ evidence: null, backing: "" })), problems: structural };
|
|
1162
|
+
const problems = [];
|
|
1163
|
+
const byId = new Map(flow.participants.map((p) => [p.id, p]));
|
|
1164
|
+
const nodeIds = new Set(facts.nodes.map((n) => n.id));
|
|
1165
|
+
for (const p of flow.participants) {
|
|
1166
|
+
for (const m of p.modules ?? []) if (!nodeIds.has(moduleId(m))) problems.push(`participant ${p.id}: ${m} is not a module in facts.json`);
|
|
1167
|
+
if (p.surface && !nodeIds.has(`surface:${p.surface}`)) problems.push(`participant ${p.id}: surface ${p.surface} is not in facts.json`);
|
|
1168
|
+
}
|
|
1169
|
+
const texts = /* @__PURE__ */ new Map();
|
|
1170
|
+
const linesOf = (file) => {
|
|
1171
|
+
if (!texts.has(file)) texts.set(file, existsSync2(join5(root, file)) ? readFileSync4(join5(root, file), "utf8").split(/\r?\n/) : null);
|
|
1172
|
+
return texts.get(file);
|
|
1173
|
+
};
|
|
1174
|
+
const steps = flow.steps.map((s, i) => {
|
|
1175
|
+
const at2 = `step ${i + 1} (${s.from} \u2192 ${s.to})`;
|
|
1176
|
+
const from = byId.get(s.from);
|
|
1177
|
+
const to = byId.get(s.to);
|
|
1178
|
+
let evidence = null;
|
|
1179
|
+
const re = evidenceRegExp(s.evidence);
|
|
1180
|
+
const what = s.evidence.pattern !== void 0 ? `/${s.evidence.pattern}/` : `symbol ${s.evidence.symbol}`;
|
|
1181
|
+
const ls = linesOf(s.evidence.file);
|
|
1182
|
+
if (!ls) problems.push(`${at2}: evidence file ${s.evidence.file} does not exist`);
|
|
1183
|
+
else {
|
|
1184
|
+
const matching = (r, from2 = 0) => ls.flatMap((l, n) => n >= from2 && r.test(l) ? [n + 1] : []);
|
|
1185
|
+
const several = (w, hits) => `${at2}: ${w} matches ${hits.length} lines of ${s.evidence.file} (${hits.slice(0, 5).join(", ")}); make it match one`;
|
|
1186
|
+
if (s.evidence.after !== void 0) {
|
|
1187
|
+
const anchors = matching(evidenceRegExp({ file: s.evidence.file, pattern: s.evidence.after }));
|
|
1188
|
+
const hit = anchors.length === 1 ? matching(re, anchors[0] - 1)[0] : void 0;
|
|
1189
|
+
if (anchors.length === 0) problems.push(`${at2}: evidence anchor /${s.evidence.after}/ matches no line of ${s.evidence.file}`);
|
|
1190
|
+
else if (anchors.length > 1) problems.push(several(`evidence anchor /${s.evidence.after}/`, anchors));
|
|
1191
|
+
else if (hit === void 0) problems.push(`${at2}: evidence ${what} matches no line of ${s.evidence.file} after line ${anchors[0]}`);
|
|
1192
|
+
else evidence = `${s.evidence.file}:${hit}`;
|
|
1193
|
+
} else {
|
|
1194
|
+
const hits = matching(re);
|
|
1195
|
+
if (hits.length === 1) evidence = `${s.evidence.file}:${hits[0]}`;
|
|
1196
|
+
else if (hits.length === 0) problems.push(`${at2}: evidence ${what} matches no line of ${s.evidence.file}`);
|
|
1197
|
+
else problems.push(several(`evidence ${what}`, hits));
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
const backing = [];
|
|
1201
|
+
const firstEvidence = (mods) => [...mods].sort((a, b) => Number(b === s.evidence.file) - Number(a === s.evidence.file));
|
|
1202
|
+
if (s.from === s.to) backing.push("within one participant");
|
|
1203
|
+
else if (from.surface || to.surface) {
|
|
1204
|
+
const surface = `surface:${from.surface ?? to.surface}`;
|
|
1205
|
+
const mods = (from.surface ? to : from).modules;
|
|
1206
|
+
const invoked = facts.edges.find((e) => e.kind === "invokes" && e.from === surface && mods.some((m) => e.to === moduleId(m)));
|
|
1207
|
+
const usesSurface = (id) => facts.edges.some((e) => e.kind === "uses" && e.from === id && e.to === surface);
|
|
1208
|
+
const path2 = invoked ? null : importPath(facts, firstEvidence(mods), usesSurface);
|
|
1209
|
+
if (invoked) backing.push(`${surface} drives ${short(invoked.to.slice("module:".length))}`);
|
|
1210
|
+
else if (path2) backing.push(`${describePath(path2)}, which uses ${surface}`);
|
|
1211
|
+
else problems.push(`${at2}: no fact edge connects ${surface} to ${mods.join(", ")} (directly, or through their imports)`);
|
|
1212
|
+
} else if (from.process === to.process) {
|
|
1213
|
+
const [importer, importee] = kindOf(s) === "call" ? [from, to] : [to, from];
|
|
1214
|
+
const goal = new Set(importee.modules.map(moduleId));
|
|
1215
|
+
const path2 = importPath(facts, firstEvidence(importer.modules), (id) => goal.has(id));
|
|
1216
|
+
if (path2) backing.push(describePath(path2));
|
|
1217
|
+
else {
|
|
1218
|
+
const ends = `from ${importer.modules.join(", ")} to ${importee.modules.join(", ")}`;
|
|
1219
|
+
problems.push(`${at2}: no import path in facts.json ${ends}, so this in-process ${kindOf(s)} is not backed`);
|
|
1220
|
+
}
|
|
1221
|
+
} else {
|
|
1222
|
+
const pkgs = (p) => new Set(facts.nodes.filter((n) => p.modules.some((m) => n.id === moduleId(m))).map((n) => `package:${n.package}`));
|
|
1223
|
+
const calls = (a, b) => (e) => a.modules.some((m) => e.from === moduleId(m)) && pkgs(b).has(e.to);
|
|
1224
|
+
const http = facts.edges.filter((e) => e.kind === "http" && (calls(from, to)(e) || calls(to, from)(e)));
|
|
1225
|
+
const called = [...new Set(http.flatMap((e) => e.detail ?? []).map((d) => d.split("?")[0]))].sort();
|
|
1226
|
+
const route = s.declares?.startsWith("route:") ? s.declares.slice(s.declares.indexOf(" ") + 1) : void 0;
|
|
1227
|
+
const prefix = route ? called.filter((d) => route.startsWith(d)).sort((a, b) => b.length - a.length)[0] : void 0;
|
|
1228
|
+
const shown = prefix ? [prefix] : called;
|
|
1229
|
+
if (shown.length) backing.push(`crosses processes; HTTP call in facts.json: ${shown.join(", ")}`);
|
|
1230
|
+
else backing.push(`crosses processes (${from.process} \u2192 ${to.process}); evidence only`);
|
|
1231
|
+
}
|
|
1232
|
+
if (s.declares) {
|
|
1233
|
+
const ends = new Set([...from.modules ?? [], ...to.modules ?? []].map(moduleId));
|
|
1234
|
+
const decl = facts.edges.find((e) => e.kind === "declares" && e.to === s.declares && ends.has(e.from));
|
|
1235
|
+
if (decl) backing.push(`${short(decl.from.slice("module:".length))} declares ${s.declares}`);
|
|
1236
|
+
else problems.push(`${at2}: ${s.declares} is not declared by a module of ${s.from} or ${s.to} in facts.json`);
|
|
1237
|
+
}
|
|
1238
|
+
return { evidence, backing: backing.join("; ") };
|
|
1239
|
+
});
|
|
1240
|
+
return { steps, problems };
|
|
1241
|
+
}
|
|
1242
|
+
function relLink2(fromDir, file, line) {
|
|
1243
|
+
return `${posix3.relative(fromDir, file)}${line ? `#L${line}` : ""}`;
|
|
1244
|
+
}
|
|
1245
|
+
var cell2 = (s) => s.replace(/\|/g, "\\|");
|
|
1246
|
+
function renderFlow(flow, verified, outDir, sources, commands = DEFAULT_COMMANDS) {
|
|
1247
|
+
const byId = new Map(flow.participants.map((p) => [p.id, p]));
|
|
1248
|
+
const m = ["sequenceDiagram", " autonumber"];
|
|
1249
|
+
let box;
|
|
1250
|
+
for (const p of flow.participants) {
|
|
1251
|
+
if (p.process !== box) {
|
|
1252
|
+
if (box) m.push(" end");
|
|
1253
|
+
if (p.process) m.push(` box transparent ${p.process}`);
|
|
1254
|
+
box = p.process;
|
|
1255
|
+
}
|
|
1256
|
+
const actor = p.surface && !p.process && flow.steps.some((s) => s.from === p.id && kindOf(s) !== "reply");
|
|
1257
|
+
m.push(`${box ? " " : " "}${actor ? "actor" : "participant"} ${p.id} as ${p.label}`);
|
|
1258
|
+
}
|
|
1259
|
+
if (box) m.push(" end");
|
|
1260
|
+
for (const s of flow.steps) m.push(` ${s.from}${kindOf(s) === "reply" ? "-->>" : "->>"}${s.to}: ${s.label}`);
|
|
1261
|
+
const stands = (p) => p.modules ? p.modules.map((f) => `[${f}](${relLink2(outDir, f)})`).join(", ") : `external surface \`${p.surface}\` (facts.json)`;
|
|
1262
|
+
const evLink = (ref, file) => {
|
|
1263
|
+
if (!ref) return `${file} (no single match)`;
|
|
1264
|
+
const line = Number(ref.slice(ref.lastIndexOf(":") + 1));
|
|
1265
|
+
return `[${ref}](${relLink2(outDir, file, line)})`;
|
|
1266
|
+
};
|
|
1267
|
+
const meta = {
|
|
1268
|
+
view: flow.name,
|
|
1269
|
+
flow: true,
|
|
1270
|
+
...sources ? { sources } : {},
|
|
1271
|
+
spec: specHash(flow),
|
|
1272
|
+
steps: flow.steps.map((s, i) => ({ from: s.from, to: s.to, evidence: verified.steps[i]?.evidence ?? null }))
|
|
1273
|
+
};
|
|
1274
|
+
return [
|
|
1275
|
+
`# ${flow.title}`,
|
|
1276
|
+
"",
|
|
1277
|
+
`> Generated by \`${commands.generate}\` from the flow spec in \`${CONFIG_FILE}\` and [facts.json](facts.json); do not edit by hand.`,
|
|
1278
|
+
`> \`${commands.check}\` says whether it is current: each step's evidence must match one line, and each call inside one process must follow an import path in facts.json.`,
|
|
1279
|
+
...sources ? [
|
|
1280
|
+
`> Sources: ${sources.globs.map((g) => `\`${g}\``).join(", ")} (${sources.files} files, content hash \`${sources.hash.slice(0, 12)}\`${sources.commit ? `, last changed in ${sources.commit.slice(0, 7)}` : ""}).`
|
|
1281
|
+
] : [],
|
|
1282
|
+
"",
|
|
1283
|
+
flow.intro,
|
|
1284
|
+
"",
|
|
1285
|
+
"```mermaid",
|
|
1286
|
+
...m,
|
|
1287
|
+
"```",
|
|
1288
|
+
"",
|
|
1289
|
+
"## Participants",
|
|
1290
|
+
"",
|
|
1291
|
+
"| Participant | Process | Stands for |",
|
|
1292
|
+
"| --- | --- | --- |",
|
|
1293
|
+
...flow.participants.map((p) => `| ${cell2(p.label)} | ${p.process ? cell2(p.process) : "outside"} | ${stands(p)} |`),
|
|
1294
|
+
"",
|
|
1295
|
+
"## Steps",
|
|
1296
|
+
"",
|
|
1297
|
+
"| # | From | To | Message | Evidence | Backed by |",
|
|
1298
|
+
"| --- | --- | --- | --- | --- | --- |",
|
|
1299
|
+
...flow.steps.map((s, i) => {
|
|
1300
|
+
const r = verified.steps[i];
|
|
1301
|
+
const arrow = kindOf(s) === "call" ? "" : ` (${kindOf(s)})`;
|
|
1302
|
+
const ends = `${cell2(byId.get(s.from).label)} | ${cell2(byId.get(s.to).label)}`;
|
|
1303
|
+
return `| ${i + 1} | ${ends} | ${cell2(s.label)}${arrow} | ${evLink(r.evidence, s.evidence.file)} | ${cell2(r.backing)} |`;
|
|
1304
|
+
}),
|
|
1305
|
+
"",
|
|
1306
|
+
"## How it is checked",
|
|
1307
|
+
"",
|
|
1308
|
+
"- Each step's evidence is a pattern that must match exactly one line of a module of one of its ends; the line is resolved when the view is generated.",
|
|
1309
|
+
"- A call between two modules of the same process must follow an import path in facts.json (a reply or callback, the reverse path); type-only hops count, since services are passed in rather than imported.",
|
|
1310
|
+
"- A step to or from an external surface needs the surface's fact edge, from the module or from one it imports.",
|
|
1311
|
+
"- A step that names an entry point (route, MCP tool, event) needs a module of one of its ends to declare it.",
|
|
1312
|
+
"- Steps between processes are backed by their evidence (and the HTTP call in facts.json, where the extractor finds one).",
|
|
1313
|
+
"",
|
|
1314
|
+
META_START,
|
|
1315
|
+
JSON.stringify(meta, null, 2),
|
|
1316
|
+
META_END,
|
|
1317
|
+
""
|
|
1318
|
+
].join("\n");
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// ../arch/src/generate.ts
|
|
1322
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync5, writeFileSync } from "node:fs";
|
|
1323
|
+
import { join as join6 } from "node:path";
|
|
1324
|
+
var VIEW_FILES = { system: "system.md", packages: "packages.md" };
|
|
1325
|
+
function buildViews(facts, config) {
|
|
1326
|
+
return {
|
|
1327
|
+
system: systemView(facts, config.views.system.maxNodes, config.views.system.intro),
|
|
1328
|
+
packages: packagesView(facts, config.views.packages.maxNodes, config.views.packages.intro)
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
function viewSources(root, facts, config, name) {
|
|
1332
|
+
return sourcesFor(root, facts, config.views[name].sources);
|
|
1333
|
+
}
|
|
1334
|
+
function sourcesFor(root, facts, globs) {
|
|
1335
|
+
const files = Object.fromEntries(Object.entries(facts.sources.files).filter(([f]) => matchesAny(f, globs)));
|
|
1336
|
+
return {
|
|
1337
|
+
globs: [...globs],
|
|
1338
|
+
ignore: [...facts.sources.ignore],
|
|
1339
|
+
commit: lastCommit(root, globs, facts.sources.ignore),
|
|
1340
|
+
hash: aggregateHash(files),
|
|
1341
|
+
files: Object.keys(files).length
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
function generate(root, config) {
|
|
1345
|
+
const facts = extractFacts(root, config);
|
|
1346
|
+
const views = buildViews(facts, config);
|
|
1347
|
+
const files = { [`${config.outDir}/facts.json`]: serializeFacts(facts) };
|
|
1348
|
+
for (const name of Object.keys(VIEW_FILES)) {
|
|
1349
|
+
files[`${config.outDir}/${VIEW_FILES[name]}`] = renderView(views[name], config.outDir, viewSources(root, facts, config, name), commandsOf(config));
|
|
1350
|
+
}
|
|
1351
|
+
const flows = (config.flows ?? []).map((spec) => ({ spec, verified: verifyFlow(spec, facts, root) }));
|
|
1352
|
+
for (const { spec, verified } of flows) files[flowFile(config.outDir, spec)] = renderFlow(spec, verified, config.outDir, sourcesFor(root, facts, spec.sources), commandsOf(config));
|
|
1353
|
+
return { facts, views, flows, files };
|
|
1354
|
+
}
|
|
1355
|
+
var unstamped = (text) => text.replace(/last changed in [0-9a-f]{7,40}/g, "last changed in _").replace(/"commit":(\s*)"[0-9a-f]{40}"/g, '"commit":$1"_"');
|
|
1356
|
+
function writeGenerated(root, generated) {
|
|
1357
|
+
for (const [path2, text] of Object.entries(generated.files)) {
|
|
1358
|
+
const abs = join6(root, path2);
|
|
1359
|
+
if (existsSync3(abs) && unstamped(readFileSync5(abs, "utf8")) === unstamped(text)) continue;
|
|
1360
|
+
mkdirSync(join6(abs, ".."), { recursive: true });
|
|
1361
|
+
writeFileSync(abs, text);
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
// ../arch/src/validate.ts
|
|
1366
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
1367
|
+
import { join as join7, posix as posix4 } from "node:path";
|
|
1368
|
+
var KEYWORDS = /* @__PURE__ */ new Set(["flowchart", "graph", "subgraph", "end", "click", "classDef", "class", "style", "linkStyle", "direction"]);
|
|
1369
|
+
function parseMermaid(md) {
|
|
1370
|
+
const block = /```mermaid\n([\s\S]*?)\n```/.exec(md)?.[1];
|
|
1371
|
+
if (block === void 0) return void 0;
|
|
1372
|
+
const out = { nodes: [], subgraphs: [], edges: [], clicks: /* @__PURE__ */ new Map() };
|
|
1373
|
+
for (const raw of block.split("\n")) {
|
|
1374
|
+
const line = raw.trim();
|
|
1375
|
+
if (!line || line.startsWith("%%")) continue;
|
|
1376
|
+
const edge = /^(\w+)\s*(?:-->|-\.->|==>)\s*(?:\|[^|]*\|\s*)?(\w+)$/.exec(line);
|
|
1377
|
+
if (edge) {
|
|
1378
|
+
out.edges.push({ from: edge[1], to: edge[2] });
|
|
1379
|
+
continue;
|
|
1380
|
+
}
|
|
1381
|
+
const click = /^click\s+(\w+)\s+(?:href\s+)?"([^"]+)"/.exec(line);
|
|
1382
|
+
if (click) {
|
|
1383
|
+
out.clicks.set(click[1], click[2]);
|
|
1384
|
+
continue;
|
|
1385
|
+
}
|
|
1386
|
+
const sg = /^subgraph\s+(\w+)/.exec(line);
|
|
1387
|
+
if (sg) {
|
|
1388
|
+
out.subgraphs.push(sg[1]);
|
|
1389
|
+
continue;
|
|
1390
|
+
}
|
|
1391
|
+
const node = /^(\w+)\s*[[({>]/.exec(line);
|
|
1392
|
+
if (node && !KEYWORDS.has(node[1])) out.nodes.push(node[1]);
|
|
1393
|
+
}
|
|
1394
|
+
return out;
|
|
1395
|
+
}
|
|
1396
|
+
function readMeta(md) {
|
|
1397
|
+
const start = md.lastIndexOf(META_START);
|
|
1398
|
+
if (start < 0) return void 0;
|
|
1399
|
+
const end = md.indexOf(META_END, start);
|
|
1400
|
+
try {
|
|
1401
|
+
return JSON.parse(md.slice(start + META_START.length, end));
|
|
1402
|
+
} catch {
|
|
1403
|
+
return void 0;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
function validateView(md, viewPath, facts, root) {
|
|
1407
|
+
const problems = [];
|
|
1408
|
+
const mermaid = parseMermaid(md);
|
|
1409
|
+
const meta = readMeta(md);
|
|
1410
|
+
if (!mermaid) return ["no mermaid diagram"];
|
|
1411
|
+
if (!meta) return ["no arch:view metadata block"];
|
|
1412
|
+
if (mermaid.nodes.length > meta.maxNodes) problems.push(`${mermaid.nodes.length} nodes, more than the limit of ${meta.maxNodes}`);
|
|
1413
|
+
const declared = new Set(mermaid.nodes);
|
|
1414
|
+
const dupes = mermaid.nodes.filter((n, i) => mermaid.nodes.indexOf(n) !== i);
|
|
1415
|
+
if (dupes.length) problems.push(`nodes declared twice: ${[...new Set(dupes)].join(", ")}`);
|
|
1416
|
+
const members = /* @__PURE__ */ new Map();
|
|
1417
|
+
const owner = /* @__PURE__ */ new Map();
|
|
1418
|
+
for (const id of mermaid.nodes) {
|
|
1419
|
+
const sel = meta.nodes[id];
|
|
1420
|
+
if (!sel) {
|
|
1421
|
+
problems.push(`node ${id} has no selector in the metadata`);
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
const ids = new Set(facts.nodes.filter((n) => selects(sel, n)).map((n) => n.id));
|
|
1425
|
+
if (ids.size === 0) problems.push(`node ${id} stands for no node of the fact graph`);
|
|
1426
|
+
for (const f of ids) {
|
|
1427
|
+
if (owner.has(f)) problems.push(`fact node ${f} is drawn by both ${owner.get(f)} and ${id}`);
|
|
1428
|
+
else owner.set(f, id);
|
|
1429
|
+
}
|
|
1430
|
+
members.set(id, ids);
|
|
1431
|
+
}
|
|
1432
|
+
const viewDir = posix4.dirname(viewPath);
|
|
1433
|
+
for (const id of mermaid.nodes) {
|
|
1434
|
+
const href = mermaid.clicks.get(id);
|
|
1435
|
+
if (!href) {
|
|
1436
|
+
problems.push(`node ${id} has no click link`);
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
if (/^[a-z]+:/i.test(href) || href.startsWith("/")) problems.push(`node ${id} links to ${href}, which is not a relative link`);
|
|
1440
|
+
else if (root && !existsSync4(join7(root, posix4.normalize(posix4.join(viewDir, href.split("#")[0]))))) problems.push(`node ${id} links to ${href}, which does not exist`);
|
|
1441
|
+
}
|
|
1442
|
+
for (const id of mermaid.clicks.keys()) if (!declared.has(id)) problems.push(`click on undeclared node ${id}`);
|
|
1443
|
+
const allowed = new Set(meta.edgeKinds);
|
|
1444
|
+
for (const { from, to } of mermaid.edges) {
|
|
1445
|
+
if (!declared.has(from) || !declared.has(to)) {
|
|
1446
|
+
problems.push(`edge ${from} --> ${to} has an undeclared end`);
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
1449
|
+
const a = members.get(from) ?? /* @__PURE__ */ new Set();
|
|
1450
|
+
const b = members.get(to) ?? /* @__PURE__ */ new Set();
|
|
1451
|
+
if (!facts.edges.some((e) => allowed.has(e.kind) && a.has(e.from) && b.has(e.to))) problems.push(`edge ${from} --> ${to} is not in the fact graph`);
|
|
1452
|
+
}
|
|
1453
|
+
return problems;
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
// ../arch/src/check.ts
|
|
1457
|
+
var sameList = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
1458
|
+
var at = (commit) => commit ? ` (generated when the sources were at ${commit.slice(0, 7)})` : "";
|
|
1459
|
+
function staleness(root, src, globs, recorded, regenerate) {
|
|
1460
|
+
if (!src) return [`stale: it does not record the sources it was generated from; ${regenerate}`];
|
|
1461
|
+
const reasons = [];
|
|
1462
|
+
if (!sameList(src.globs, globs)) reasons.push(`stale: the view's source globs changed since generation; ${regenerate}`);
|
|
1463
|
+
const now = hashFiles(root, listFiles(root, src.globs, src.ignore));
|
|
1464
|
+
const baseline = Object.fromEntries(Object.entries(recorded.files).filter(([f]) => matchesAny(f, src.globs) && !matchesAny(f, src.ignore)));
|
|
1465
|
+
const fromTheseFacts = aggregateHash(baseline) === src.hash;
|
|
1466
|
+
if (aggregateHash(now) !== src.hash) {
|
|
1467
|
+
const why = fromTheseFacts ? describeDiff(diffSources(baseline, now)) : "it was drawn from an older or newer facts.json than the one committed";
|
|
1468
|
+
reasons.push(`stale: sources changed since generation${at(src.commit)}: ${why}`);
|
|
1469
|
+
} else if (!fromTheseFacts) {
|
|
1470
|
+
reasons.push("stale: facts.json was regenerated without this view");
|
|
1471
|
+
}
|
|
1472
|
+
return reasons;
|
|
1473
|
+
}
|
|
1474
|
+
function check(root, config) {
|
|
1475
|
+
const commands = commandsOf(config);
|
|
1476
|
+
const regenerate = `run \`${commands.generate}\``;
|
|
1477
|
+
const factsPath = `${config.outDir}/facts.json`;
|
|
1478
|
+
if (!existsSync5(join8(root, factsPath))) return [{ file: factsPath, reason: `missing; ${regenerate}` }];
|
|
1479
|
+
const facts = JSON.parse(readFileSync6(join8(root, factsPath), "utf8"));
|
|
1480
|
+
const problems = [];
|
|
1481
|
+
const recorded = facts.sources;
|
|
1482
|
+
if (!sameList(recorded.globs, sourceGlobs(config)) || !sameList(recorded.ignore, config.ignore)) {
|
|
1483
|
+
problems.push({ file: factsPath, reason: `stale: the extractor's source globs changed since generation; ${regenerate}` });
|
|
1484
|
+
}
|
|
1485
|
+
const current = hashFiles(root, listFiles(root, recorded.globs, recorded.ignore));
|
|
1486
|
+
if (aggregateHash(current) !== recorded.hash) {
|
|
1487
|
+
problems.push({ file: factsPath, reason: `stale: sources changed since generation${at(recorded.commit)}: ${describeDiff(diffSources(recorded.files, current))}` });
|
|
1488
|
+
}
|
|
1489
|
+
for (const name of Object.keys(VIEW_FILES)) {
|
|
1490
|
+
const file = `${config.outDir}/${VIEW_FILES[name]}`;
|
|
1491
|
+
if (!existsSync5(join8(root, file))) {
|
|
1492
|
+
problems.push({ file, reason: `missing; ${regenerate}` });
|
|
1493
|
+
continue;
|
|
1494
|
+
}
|
|
1495
|
+
const md = readFileSync6(join8(root, file), "utf8");
|
|
1496
|
+
for (const reason of staleness(root, readMeta(md)?.sources, config.views[name].sources, recorded, regenerate)) problems.push({ file, reason });
|
|
1497
|
+
for (const reason of validateView(md, file, facts, root)) problems.push({ file, reason });
|
|
1498
|
+
}
|
|
1499
|
+
const flows = config.flows ?? [];
|
|
1500
|
+
for (const [i, flow] of flows.entries()) {
|
|
1501
|
+
const file = flowFile(config.outDir, flow);
|
|
1502
|
+
if (flows.findIndex((f) => f.name === flow.name) !== i) {
|
|
1503
|
+
problems.push({ file, reason: `two flows are named ${flow.name}` });
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
1506
|
+
if (!existsSync5(join8(root, file))) {
|
|
1507
|
+
problems.push({ file, reason: `missing; ${regenerate}` });
|
|
1508
|
+
continue;
|
|
1509
|
+
}
|
|
1510
|
+
const md = readFileSync6(join8(root, file), "utf8");
|
|
1511
|
+
const meta = readMeta(md);
|
|
1512
|
+
const stale = staleness(root, meta?.sources, flow.sources, recorded, regenerate);
|
|
1513
|
+
if (meta?.spec !== specHash(flow)) stale.push(`stale: its flow spec in the arch config changed since generation; ${regenerate}`);
|
|
1514
|
+
const verified = verifyFlow(flow, facts, root);
|
|
1515
|
+
for (const reason of [...stale, ...verified.problems]) problems.push({ file, reason });
|
|
1516
|
+
if (!stale.length && !verified.problems.length && renderFlow(flow, verified, config.outDir, meta.sources, commands) !== md) {
|
|
1517
|
+
problems.push({ file, reason: `differs from what its spec renders (edited by hand?); ${regenerate}` });
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
problems.push(...checkComponents(root, config.outDir, facts, commands, `fix it or run \`${commands.verify} --write\``));
|
|
1521
|
+
return problems;
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
// ../arch/src/load.ts
|
|
1525
|
+
import { existsSync as existsSync6, readFileSync as readFileSync7 } from "node:fs";
|
|
1526
|
+
import { dirname as dirname3, join as join9 } from "node:path";
|
|
1527
|
+
var EXTENSIONS = ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
|
|
1528
|
+
var DEFAULT_IGNORE = [
|
|
1529
|
+
"**/node_modules/**",
|
|
1530
|
+
"**/dist/**",
|
|
1531
|
+
"**/build/**",
|
|
1532
|
+
"**/coverage/**",
|
|
1533
|
+
"**/*.d.ts",
|
|
1534
|
+
"**/*.test.*",
|
|
1535
|
+
"**/*.spec.*",
|
|
1536
|
+
"**/__tests__/**",
|
|
1537
|
+
"**/test/**",
|
|
1538
|
+
"**/tests/**",
|
|
1539
|
+
"**/fixtures/**"
|
|
1540
|
+
];
|
|
1541
|
+
var DEFAULT_SURFACES = [
|
|
1542
|
+
{
|
|
1543
|
+
id: "mcp-client",
|
|
1544
|
+
label: "MCP client",
|
|
1545
|
+
direction: "in",
|
|
1546
|
+
imports: ["@modelcontextprotocol/sdk/server/stdio.js", "@modelcontextprotocol/sdk/server/streamableHttp.js", "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"]
|
|
1547
|
+
},
|
|
1548
|
+
{ id: "sqlite", label: "SQLite database", direction: "out", imports: ["node:sqlite", "better-sqlite3", "sqlite3", "bun:sqlite"] },
|
|
1549
|
+
{ id: "postgres", label: "PostgreSQL database", direction: "out", imports: ["pg", "postgres", "@neondatabase/serverless"] },
|
|
1550
|
+
{ id: "mysql", label: "MySQL database", direction: "out", imports: ["mysql2", "mysql2/promise", "mysql"] },
|
|
1551
|
+
{ id: "redis", label: "Redis", direction: "out", imports: ["redis", "ioredis"] },
|
|
1552
|
+
{ id: "git", label: "Git repositories", direction: "out", imports: ["isomorphic-git", "simple-git"] }
|
|
1553
|
+
];
|
|
1554
|
+
var unquote = (s) => s.replace(/\s+#.*$/, "").trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
1555
|
+
var trimGlob = (g) => g.replace(/^(\.\/)+/, "").replace(/\/+$/, "").replace(/^\.$/, "") || ".";
|
|
1556
|
+
function pnpmWorkspaceGlobs(yaml) {
|
|
1557
|
+
const lines2 = yaml.split(/\r?\n/);
|
|
1558
|
+
const start = lines2.findIndex((l) => /^packages\s*:/.test(l));
|
|
1559
|
+
if (start < 0) return void 0;
|
|
1560
|
+
const rest = lines2[start].replace(/^packages\s*:/, "").replace(/\s+#.*$/, "").trim();
|
|
1561
|
+
if (rest.startsWith("[")) {
|
|
1562
|
+
let flow = rest;
|
|
1563
|
+
for (let i = start + 1; !flow.includes("]") && i < lines2.length; i++) flow += ` ${lines2[i].replace(/\s+#.*$/, "")}`;
|
|
1564
|
+
return flow.slice(1, flow.indexOf("]")).split(",").map(unquote).filter(Boolean);
|
|
1565
|
+
}
|
|
1566
|
+
const globs = [];
|
|
1567
|
+
for (const line of lines2.slice(start + 1)) {
|
|
1568
|
+
if (/^\s*(#.*)?$/.test(line)) continue;
|
|
1569
|
+
const item = /^\s*-\s+(.+)$/.exec(line);
|
|
1570
|
+
if (!item) break;
|
|
1571
|
+
globs.push(unquote(item[1]));
|
|
1572
|
+
}
|
|
1573
|
+
return globs;
|
|
1574
|
+
}
|
|
1575
|
+
function readJson(root, file) {
|
|
1576
|
+
try {
|
|
1577
|
+
return JSON.parse(readFileSync7(join9(root, file), "utf8"));
|
|
1578
|
+
} catch (err) {
|
|
1579
|
+
throw new Error(`${file}: not JSON (${err.message})`);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
function splitGlobs(globs, from) {
|
|
1583
|
+
return {
|
|
1584
|
+
globs: [...new Set(globs.filter((g) => !g.startsWith("!")).map(trimGlob))],
|
|
1585
|
+
ignore: globs.filter((g) => g.startsWith("!")).map((g) => `${trimGlob(g.slice(1))}/**`),
|
|
1586
|
+
from
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
function detectWorkspaces(root) {
|
|
1590
|
+
if (existsSync6(join9(root, "pnpm-workspace.yaml"))) {
|
|
1591
|
+
const globs = pnpmWorkspaceGlobs(readFileSync7(join9(root, "pnpm-workspace.yaml"), "utf8"));
|
|
1592
|
+
if (globs?.length) return splitGlobs(globs, "pnpm-workspace.yaml");
|
|
1593
|
+
}
|
|
1594
|
+
if (existsSync6(join9(root, "package.json"))) {
|
|
1595
|
+
const ws = readJson(root, "package.json").workspaces;
|
|
1596
|
+
const globs = Array.isArray(ws) ? ws : ws?.packages;
|
|
1597
|
+
if (globs?.length) return splitGlobs(globs, "package.json");
|
|
1598
|
+
}
|
|
1599
|
+
return { globs: ["."], ignore: [], from: "single package" };
|
|
1600
|
+
}
|
|
1601
|
+
var under = (pkg, rest) => pkg === "." ? rest : `${pkg}/${rest}`;
|
|
1602
|
+
var any = (root, globs, ignore) => listFiles(root, globs, ignore).length > 0;
|
|
1603
|
+
var hasSources = (root, dir, ignore) => any(root, EXTENSIONS.map((ext) => under(dir, `src/**/*.${ext}`)), ignore);
|
|
1604
|
+
function moduleGlobs(root, glob, ignore) {
|
|
1605
|
+
const dirs = listFiles(root, [manifestGlob(glob)], ignore).map((m) => dirname3(m));
|
|
1606
|
+
const withSrc = dirs.filter((d) => hasSources(root, d, ignore));
|
|
1607
|
+
const bases = withSrc.length === dirs.length && dirs.length > 0 ? [under(glob, "src/**")] : withSrc.length === 0 ? [under(glob, "**")] : dirs.map((d) => withSrc.includes(d) ? under(d, "src/**") : under(d, "**"));
|
|
1608
|
+
const out = [];
|
|
1609
|
+
for (const base of bases) for (const ext of EXTENSIONS) if (any(root, [`${base}/*.${ext}`], ignore)) out.push(`${base}/*.${ext}`);
|
|
1610
|
+
return out;
|
|
1611
|
+
}
|
|
1612
|
+
function binSurface(root, manifests, modules, ignore) {
|
|
1613
|
+
const sources = new Set(listFiles(root, modules, ignore));
|
|
1614
|
+
for (const manifest of manifests) {
|
|
1615
|
+
const json = readJson(root, manifest);
|
|
1616
|
+
const entry = typeof json.bin === "string" ? ["bin", json.bin] : json.bin ? Object.entries(json.bin).sort(([a], [b]) => a < b ? -1 : 1)[0] : void 0;
|
|
1617
|
+
if (!entry) continue;
|
|
1618
|
+
const [name, target] = entry;
|
|
1619
|
+
const dir = manifest === "package.json" ? "" : manifest.slice(0, -"package.json".length);
|
|
1620
|
+
const rel = target.replace(/^\.\//, "");
|
|
1621
|
+
const bare = rel.replace(/\.[cm]?js$/, "");
|
|
1622
|
+
const stems = [bare.replace(/^(dist|build|lib|out)\//, "src/"), bare.replace(/^(dist|build|lib|out)\/(src\/)?/, ""), bare];
|
|
1623
|
+
const candidates = [...stems.flatMap((s) => ["ts", "mts", "cts", "tsx", "js", "mjs", "cjs"].map((ext) => `${dir}${s}.${ext}`)), `${dir}${rel}`];
|
|
1624
|
+
const module = candidates.find((f) => sources.has(f));
|
|
1625
|
+
if (!module) continue;
|
|
1626
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1627
|
+
return { id: "cli-user", label: "CLI user", direction: "in", file: { path: manifest, pattern: `"${esc(name)}":\\s*"${esc(target)}"`, module } };
|
|
1628
|
+
}
|
|
1629
|
+
return void 0;
|
|
1630
|
+
}
|
|
1631
|
+
function deriveConfig(root, workspaces = detectWorkspaces(root), ignore = [...DEFAULT_IGNORE, ...workspaces.ignore]) {
|
|
1632
|
+
const manifests = workspaces.globs.map(manifestGlob);
|
|
1633
|
+
const modules = workspaces.globs.flatMap((glob) => moduleGlobs(root, glob, ignore));
|
|
1634
|
+
const migrations = workspaces.globs.map((pkg) => under(pkg, "migrations/*.sql")).filter((g) => any(root, [g], ignore));
|
|
1635
|
+
const extraSources = [.../* @__PURE__ */ new Set(["tsconfig.json", ...workspaces.globs.map((pkg) => under(pkg, "tsconfig.json"))])];
|
|
1636
|
+
const cli = binSurface(root, listFiles(root, manifests, ignore), modules, ignore);
|
|
1637
|
+
return {
|
|
1638
|
+
packages: workspaces.globs,
|
|
1639
|
+
modules,
|
|
1640
|
+
migrations,
|
|
1641
|
+
extraSources,
|
|
1642
|
+
ignore,
|
|
1643
|
+
entries: { routes: [] },
|
|
1644
|
+
surfaces: [...cli ? [cli] : [], ...DEFAULT_SURFACES],
|
|
1645
|
+
outDir: "docs/architecture",
|
|
1646
|
+
views: {
|
|
1647
|
+
system: { sources: [...manifests, ...modules, ...migrations], maxNodes: 15 },
|
|
1648
|
+
packages: { sources: [...manifests, ...modules], maxNodes: 15 }
|
|
1649
|
+
},
|
|
1650
|
+
commands: DEFAULT_COMMANDS
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
var KEYS = /* @__PURE__ */ new Set(["packages", "modules", "migrations", "extraSources", "ignore", "entries", "surfaces", "outDir", "views", "flows", "commands"]);
|
|
1654
|
+
var LISTS = ["packages", "modules", "migrations", "extraSources", "ignore"];
|
|
1655
|
+
var OBJECTS = ["entries", "views", "commands"];
|
|
1656
|
+
var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1657
|
+
function validate(file, name) {
|
|
1658
|
+
if (!isObject2(file)) throw new Error(`${name}: must be a JSON object`);
|
|
1659
|
+
const f = file;
|
|
1660
|
+
const unknown = Object.keys(f).filter((k) => !KEYS.has(k) && !k.startsWith("$"));
|
|
1661
|
+
if (unknown.length) throw new Error(`${name}: unknown key${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")} (known: ${[...KEYS].join(", ")})`);
|
|
1662
|
+
for (const k of LISTS) {
|
|
1663
|
+
const v = f[k];
|
|
1664
|
+
if (v !== void 0 && !(Array.isArray(v) && v.every((x) => typeof x === "string"))) throw new Error(`${name}: ${k} must be an array of globs`);
|
|
1665
|
+
}
|
|
1666
|
+
for (const k of OBJECTS) if (f[k] !== void 0 && !isObject2(f[k])) throw new Error(`${name}: ${k} must be an object`);
|
|
1667
|
+
for (const k of ["surfaces", "flows"]) if (f[k] !== void 0 && !Array.isArray(f[k])) throw new Error(`${name}: ${k} must be an array`);
|
|
1668
|
+
if (f.outDir !== void 0 && typeof f.outDir !== "string") throw new Error(`${name}: outDir must be a string`);
|
|
1669
|
+
}
|
|
1670
|
+
function mergeConfig(derived, file, name = CONFIG_FILE) {
|
|
1671
|
+
validate(file, name);
|
|
1672
|
+
const own = Object.fromEntries(Object.entries(file).filter(([k]) => !k.startsWith("$")));
|
|
1673
|
+
const views = own.views ?? {};
|
|
1674
|
+
return {
|
|
1675
|
+
...derived,
|
|
1676
|
+
...own,
|
|
1677
|
+
entries: { ...derived.entries, ...own.entries },
|
|
1678
|
+
views: { system: { ...derived.views.system, ...views.system }, packages: { ...derived.views.packages, ...views.packages } },
|
|
1679
|
+
commands: { ...DEFAULT_COMMANDS, ...own.commands }
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
function loadConfig(root) {
|
|
1683
|
+
if (!existsSync6(join9(root, CONFIG_FILE))) return { config: deriveConfig(root), file: null };
|
|
1684
|
+
const file = readJson(root, CONFIG_FILE);
|
|
1685
|
+
validate(file, CONFIG_FILE);
|
|
1686
|
+
const ws = Array.isArray(file.packages) ? splitGlobs(file.packages, CONFIG_FILE) : detectWorkspaces(root);
|
|
1687
|
+
const derived = deriveConfig(root, ws, Array.isArray(file.ignore) ? file.ignore : void 0);
|
|
1688
|
+
const config = mergeConfig(derived, file);
|
|
1689
|
+
if (!config.extraSources.includes(CONFIG_FILE)) config.extraSources = [...config.extraSources, CONFIG_FILE];
|
|
1690
|
+
return { config, file: CONFIG_FILE };
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
// ../arch/src/cli.ts
|
|
1694
|
+
var USAGE = "usage: arch [generate|check|verify [file] [--write]] [--root <dir>]";
|
|
1695
|
+
var OWN_ROOT = join10(dirname4(fileURLToPath(import.meta.url)), "../../..");
|
|
1696
|
+
function run(argv, config, out = { log: console.log, error: console.error }, defaultRoot = OWN_ROOT) {
|
|
1697
|
+
let parsed;
|
|
1698
|
+
try {
|
|
1699
|
+
parsed = parseArgs({ args: argv, options: { root: { type: "string" }, write: { type: "boolean" } }, allowPositionals: true, strict: true });
|
|
1700
|
+
} catch (err) {
|
|
1701
|
+
out.error(`${err.message.split("\n")[0]}; ${USAGE}`);
|
|
1702
|
+
return 2;
|
|
1703
|
+
}
|
|
1704
|
+
const { values, positionals } = parsed;
|
|
1705
|
+
const command = positionals[0] ?? "generate";
|
|
1706
|
+
const known = ["generate", "check", "verify"];
|
|
1707
|
+
if (!known.includes(command)) {
|
|
1708
|
+
out.error(`unknown command: ${command} (expected generate, check or verify)`);
|
|
1709
|
+
return 2;
|
|
1710
|
+
}
|
|
1711
|
+
if (positionals.length > (command === "verify" ? 2 : 1) || values.write && command !== "verify") {
|
|
1712
|
+
out.error(USAGE);
|
|
1713
|
+
return 2;
|
|
1714
|
+
}
|
|
1715
|
+
const root = resolve2(values.root ?? defaultRoot);
|
|
1716
|
+
if (!existsSync7(root)) {
|
|
1717
|
+
out.error(`no such directory: ${root}`);
|
|
1718
|
+
return 2;
|
|
1719
|
+
}
|
|
1720
|
+
try {
|
|
1721
|
+
const cfg = config ?? loaded(root, out, command === "generate");
|
|
1722
|
+
if (command === "generate") return generateCommand(root, cfg, out);
|
|
1723
|
+
if (command === "check") return checkCommand(root, cfg, out);
|
|
1724
|
+
return verifyCommand(root, cfg, out, positionals[1], values.write === true);
|
|
1725
|
+
} catch (err) {
|
|
1726
|
+
out.error(err.message);
|
|
1727
|
+
return 1;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
function loaded(root, out, say) {
|
|
1731
|
+
const { config, file } = loadConfig(root);
|
|
1732
|
+
if (say && !file) out.log(`no ${CONFIG_FILE}; using the config derived from the layout: packages ${config.packages.join(", ")}, modules ${config.modules.join(", ") || "(none)"}`);
|
|
1733
|
+
return config;
|
|
1734
|
+
}
|
|
1735
|
+
function report(root, config, out) {
|
|
1736
|
+
const problems = check(root, config);
|
|
1737
|
+
for (const p of problems) out.error(`${p.file}: ${p.reason}`);
|
|
1738
|
+
return problems;
|
|
1739
|
+
}
|
|
1740
|
+
function generateCommand(root, config, out) {
|
|
1741
|
+
const generated = generate(root, config);
|
|
1742
|
+
writeGenerated(root, generated);
|
|
1743
|
+
const { facts, views, flows } = generated;
|
|
1744
|
+
const n = Object.entries(facts.counts.nodes).map(([k, v]) => `${v} ${k}`).join(", ");
|
|
1745
|
+
out.log(`wrote ${config.outDir}/facts.json: ${facts.nodes.length} nodes (${n}), ${facts.edges.length} edges`);
|
|
1746
|
+
for (const v of Object.values(views)) out.log(`wrote ${config.outDir}/${v.name}.md: ${v.nodes.length} nodes, ${v.edges.length} edges`);
|
|
1747
|
+
for (const f of flows) out.log(`wrote ${config.outDir}/${f.spec.name}.md: ${f.spec.participants.length} participants, ${f.spec.steps.length} steps`);
|
|
1748
|
+
for (const u of facts.unresolved) out.error(`unresolved import ${u.specifier} at ${u.file}:${u.line}`);
|
|
1749
|
+
return report(root, config, out).length ? 1 : 0;
|
|
1750
|
+
}
|
|
1751
|
+
function checkCommand(root, config, out) {
|
|
1752
|
+
const problems = report(root, config, out);
|
|
1753
|
+
if (problems.length) {
|
|
1754
|
+
const paths = componentsPaths(config.outDir);
|
|
1755
|
+
const onlyComponents = problems.every((p) => p.file === paths.json || p.file === paths.md);
|
|
1756
|
+
const fix = onlyComponents ? `fix components.json or run \`${commandsOf(config).verify} --write\`` : `run \`${commandsOf(config).generate}\` to regenerate`;
|
|
1757
|
+
out.error(`architecture docs: ${problems.length} problem${problems.length === 1 ? "" : "s"}; ${fix}`);
|
|
1758
|
+
return 1;
|
|
1759
|
+
}
|
|
1760
|
+
out.log("architecture docs are current");
|
|
1761
|
+
return 0;
|
|
1762
|
+
}
|
|
1763
|
+
function verifyCommand(root, config, out, file, write) {
|
|
1764
|
+
const paths = componentsPaths(config.outDir);
|
|
1765
|
+
const factsPath = `${config.outDir}/facts.json`;
|
|
1766
|
+
const stale = check(root, config).filter((p) => p.file === factsPath);
|
|
1767
|
+
if (stale.length) {
|
|
1768
|
+
for (const p of stale) out.error(`${p.file}: ${p.reason}`);
|
|
1769
|
+
out.error(`verify needs a current facts.json; run \`${commandsOf(config).generate}\` first`);
|
|
1770
|
+
return 1;
|
|
1771
|
+
}
|
|
1772
|
+
const source = file ? resolve2(file) : join10(root, paths.json);
|
|
1773
|
+
const shown = relative(root, source) || source;
|
|
1774
|
+
if (!existsSync7(source)) {
|
|
1775
|
+
out.error(`${shown}: no such file`);
|
|
1776
|
+
return 1;
|
|
1777
|
+
}
|
|
1778
|
+
const facts = JSON.parse(readFileSync8(join10(root, factsPath), "utf8"));
|
|
1779
|
+
const doc = parseComponents(readFileSync8(source, "utf8"), shown);
|
|
1780
|
+
const verdict = verifyComponents(doc, facts);
|
|
1781
|
+
for (const p of verdict.problems) out.error(`${shown}: ${p}`);
|
|
1782
|
+
for (const v of verdict.edges) {
|
|
1783
|
+
const name = `${v.edge.from} -> ${v.edge.to}`;
|
|
1784
|
+
if (!v.supported) out.error(`${write ? "dropped" : "unsupported"}: ${name}: ${v.problems.join("; ")}`);
|
|
1785
|
+
else if (v.problems.length) out.error(`${write ? "evidence corrected" : "evidence"}: ${name}: ${v.problems.join("; ")}${write ? ` (now ${v.evidence.join(", ")})` : ""}`);
|
|
1786
|
+
}
|
|
1787
|
+
const kept = verdict.edges.filter((v) => v.supported).length;
|
|
1788
|
+
const summary = `${doc.components.length} components, ${kept} of ${verdict.edges.length} edges supported by facts.json`;
|
|
1789
|
+
if (!write) {
|
|
1790
|
+
const n = componentProblems(verdict).length;
|
|
1791
|
+
out.log(n ? `${summary}; ${n} problem${n === 1 ? "" : "s"}` : `${summary}; no problems`);
|
|
1792
|
+
return n ? 1 : 0;
|
|
1793
|
+
}
|
|
1794
|
+
if (verdict.problems.length) {
|
|
1795
|
+
out.error(`${summary}; fix the components above (edges are dropped for you, components are not); nothing written`);
|
|
1796
|
+
return 1;
|
|
1797
|
+
}
|
|
1798
|
+
const clean = cleanComponents(doc, verdict, facts);
|
|
1799
|
+
const cleanVerdict = verifyComponents(clean, facts);
|
|
1800
|
+
mkdirSync2(join10(root, config.outDir), { recursive: true });
|
|
1801
|
+
writeFileSync2(join10(root, paths.json), serializeComponents(clean));
|
|
1802
|
+
writeFileSync2(join10(root, paths.md), renderComponents(clean, cleanVerdict, facts, config.outDir, commandsOf(config)));
|
|
1803
|
+
out.log(`wrote ${paths.json} and ${paths.md}: ${summary}`);
|
|
1804
|
+
return 0;
|
|
1805
|
+
}
|
|
1806
|
+
if (process.argv[1] && realpathSync2(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
1807
|
+
process.exitCode = run(process.argv.slice(2));
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
// src/arch.ts
|
|
1811
|
+
function gitTop(cwd) {
|
|
1812
|
+
try {
|
|
1813
|
+
return execFileSync2("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || void 0;
|
|
1814
|
+
} catch {
|
|
1815
|
+
return void 0;
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
function isWorkspaceRoot(dir) {
|
|
1819
|
+
if (existsSync8(path.join(dir, CONFIG_FILE)) || existsSync8(path.join(dir, "pnpm-workspace.yaml"))) return true;
|
|
1820
|
+
try {
|
|
1821
|
+
return "workspaces" in JSON.parse(readFileSync9(path.join(dir, "package.json"), "utf8"));
|
|
1822
|
+
} catch {
|
|
1823
|
+
return false;
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
function archRoot(cwd, root) {
|
|
1827
|
+
if (root) return root;
|
|
1828
|
+
const top = gitTop(cwd);
|
|
1829
|
+
if (!top) return cwd;
|
|
1830
|
+
for (let dir = realpathSync3(path.resolve(cwd)); ; dir = path.dirname(dir)) {
|
|
1831
|
+
if (isWorkspaceRoot(dir)) return dir;
|
|
1832
|
+
if (path.relative(top, dir) === "" || path.dirname(dir) === dir || path.relative(top, dir).startsWith("..")) return top;
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
function archCommand(cmd, cwd = process.cwd(), out) {
|
|
1836
|
+
const argv = [cmd.action, ...cmd.file ? [cmd.file] : [], ...cmd.write ? ["--write"] : [], "--root", archRoot(cwd, cmd.root)];
|
|
1837
|
+
return run(argv, void 0, out, cwd);
|
|
1838
|
+
}
|
|
1839
|
+
export {
|
|
1840
|
+
archCommand,
|
|
1841
|
+
archRoot
|
|
1842
|
+
};
|