spatial-views 0.0.0-stage → 0.2.0

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.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +245 -2
  3. package/dist/app/assets/abnfDiagram-S7VZAUFO-CFbb_Sz2.js +1 -0
  4. package/dist/app/assets/architecture-WOLXFQ4H-CsBD__5a.js +1 -0
  5. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  6. package/dist/app/assets/blockDiagram-APKKGZFW-BZDPbzAG.js +140 -0
  7. package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
  8. package/dist/app/assets/c4Diagram-KJ2TOQU5-BilBWuq5.js +38 -0
  9. package/dist/app/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  10. package/dist/app/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  11. package/dist/app/assets/chunk-6MUBBAK2-BBl-4tQr.js +2 -0
  12. package/dist/app/assets/chunk-AXFCVDMN-BhsttQ-k.js +62 -0
  13. package/dist/app/assets/chunk-BG4553SI-mWcPcFZr.js +127 -0
  14. package/dist/app/assets/chunk-DQASFODM-7FKe2gLt.js +10 -0
  15. package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  16. package/dist/app/assets/chunk-HFQBQIA3-nXrQ08BL.js +1 -0
  17. package/dist/app/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  18. package/dist/app/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  19. package/dist/app/assets/chunk-KQLB2F66-swukhFmZ.js +2 -0
  20. package/dist/app/assets/chunk-KS47KZWR-DkDkwO82.js +1 -0
  21. package/dist/app/assets/chunk-LEVMRMFU-DXH6iXv3.js +1 -0
  22. package/dist/app/assets/chunk-M57EVK23-B-kEyOJF.js +1 -0
  23. package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  24. package/dist/app/assets/chunk-OY52VR5R-DweG7qYw.js +88 -0
  25. package/dist/app/assets/chunk-QB3YPZ4I-DyozK3lV.js +213 -0
  26. package/dist/app/assets/chunk-R3KSYZAL-BEXCUN6J.js +1 -0
  27. package/dist/app/assets/chunk-STOXU5M4-BaTlty4O.js +72 -0
  28. package/dist/app/assets/chunk-TU62E6Q5-_rcUP1Fh.js +1 -0
  29. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  30. package/dist/app/assets/chunk-X4PVCEUW-DGxTL3kB.js +1 -0
  31. package/dist/app/assets/chunk-XXDRQBXY-C02Gpej2.js +1 -0
  32. package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  33. package/dist/app/assets/classDiagram-v2-L25IHNXF-DLEBwpvk.js +217 -0
  34. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  35. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  36. package/dist/app/assets/cynefinDiagram-L36ESFBY-CLFstukD.js +62 -0
  37. package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  38. package/dist/app/assets/d3-scale-CaJQQYkF.js +1 -0
  39. package/dist/app/assets/dagre-SPEB5RXH-BaSAny1T.js +4 -0
  40. package/dist/app/assets/diagram-3B7GL73J-DJNlt5Sg.js +200 -0
  41. package/dist/app/assets/diagram-DNEMPZML-DEHeuILB.js +24 -0
  42. package/dist/app/assets/diagram-L3MUGCDN-ob5Ka2Xc.js +41 -0
  43. package/dist/app/assets/diagram-LA4NIPWU-DNESzFAc.js +24 -0
  44. package/dist/app/assets/diagram-MHCOC4E2-CVi9zKjG.js +3 -0
  45. package/dist/app/assets/diagram-XPFHEONP-DInT4C7e.js +30 -0
  46. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  47. package/dist/app/assets/ebnfDiagram-UZSYDL2S-CRCZNsji.js +1 -0
  48. package/dist/app/assets/elk-XV6XMXQE-D4fsWI2l.js +2 -0
  49. package/dist/app/assets/erDiagram-EYBAPDEH-YQNM5StV.js +99 -0
  50. package/dist/app/assets/eventmodeling-K75KTNOO-Bev08J2F.js +1 -0
  51. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  52. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  53. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  54. package/dist/app/assets/gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js +106 -0
  55. package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
  56. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  57. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  58. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  59. package/dist/app/assets/infoDiagram-KBXO4MBG-DT7LbBRQ.js +2 -0
  60. package/dist/app/assets/ishikawaDiagram-M35NCXHK-CF51lhjB.js +70 -0
  61. package/dist/app/assets/journeyDiagram-OPLOXDXO-_36FonKk.js +139 -0
  62. package/dist/app/assets/kanban-definition-BZKZHSQY-tLk_OlQ-.js +89 -0
  63. package/dist/app/assets/katex-MEuSR36T.js +257 -0
  64. package/dist/app/assets/mermaid-parser.core-_3Vo8x6b.js +7 -0
  65. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  66. package/dist/app/assets/mindmap-definition-I2QAS2VK-BCI4HRX3.js +98 -0
  67. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  68. package/dist/app/assets/pegDiagram-FD4XPPHP-BOzSoNji.js +1 -0
  69. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  70. package/dist/app/assets/pieDiagram-J4AKIIQI-PlHpwT_c.js +39 -0
  71. package/dist/app/assets/quadrantDiagram-XTYBLID2-CdxZ0ael.js +7 -0
  72. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  73. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  74. package/dist/app/assets/railroad-abnf-LNEFI6M7-C49jJE4Y.js +1 -0
  75. package/dist/app/assets/railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js +1 -0
  76. package/dist/app/assets/railroad-peg-JR7BVNR7-DjBPSCKV.js +1 -0
  77. package/dist/app/assets/railroadDiagram-MRQ6NCDL-wGcmIMqq.js +1 -0
  78. package/dist/app/assets/requirementDiagram-Y7LWUY3S-DprFI03z.js +84 -0
  79. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  80. package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
  81. package/dist/app/assets/sankeyDiagram-WGJFYUXA-DygYWLTR.js +40 -0
  82. package/dist/app/assets/sequenceDiagram-5NDRBG5M-BzIr2DBO.js +169 -0
  83. package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  84. package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js +291 -0
  85. package/dist/app/assets/swimlanes-UMQ2AFYF-CIEH82Zt.js +1 -0
  86. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  87. package/dist/app/assets/timeline-definition-SEUHKTQE-BGYSqup2.js +120 -0
  88. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  89. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  90. package/dist/app/assets/usecaseDiagram-AFA6YXN4-dy6oVOke.js +328 -0
  91. package/dist/app/assets/vennDiagram-NNMJR3RB-CUyuhcAk.js +34 -0
  92. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  93. package/dist/app/assets/wardleyDiagram-S7YFUSEH-DYtxYUHe.js +78 -0
  94. package/dist/app/assets/xychartDiagram-GGNKY7IX-ClR06AlB.js +7 -0
  95. package/dist/app/index.html +14 -0
  96. package/dist/cli/index.js +338 -0
  97. package/dist/core/api.js +420 -0
  98. package/dist/core/approvals.js +426 -0
  99. package/dist/core/context.js +259 -0
  100. package/dist/core/diff.js +156 -0
  101. package/dist/core/docs.js +140 -0
  102. package/dist/core/doctor.js +152 -0
  103. package/dist/core/doctypes.js +79 -0
  104. package/dist/core/edit.js +130 -0
  105. package/dist/core/errors.js +3 -0
  106. package/dist/core/flags.js +13 -0
  107. package/dist/core/gaps.js +119 -0
  108. package/dist/core/heading.js +4 -0
  109. package/dist/core/history.js +50 -0
  110. package/dist/core/home.js +345 -0
  111. package/dist/core/lanes.js +134 -0
  112. package/dist/core/launch.js +34 -0
  113. package/dist/core/layout.js +362 -0
  114. package/dist/core/links.js +68 -0
  115. package/dist/core/mermaid.js +175 -0
  116. package/dist/core/newdoc.js +66 -0
  117. package/dist/core/open-folder.js +30 -0
  118. package/dist/core/openspec.js +120 -0
  119. package/dist/core/paths.js +90 -0
  120. package/dist/core/project.js +392 -0
  121. package/dist/core/resolve.js +35 -0
  122. package/dist/core/route.js +420 -0
  123. package/dist/core/scan.js +514 -0
  124. package/dist/core/schema.js +270 -0
  125. package/dist/core/scope.js +126 -0
  126. package/dist/core/setup.js +134 -0
  127. package/dist/core/skills.js +181 -0
  128. package/dist/core/storage/config.js +74 -0
  129. package/dist/core/storage/events.js +54 -0
  130. package/dist/core/storage/folder-watch.js +147 -0
  131. package/dist/core/storage/folder.js +469 -0
  132. package/dist/core/storage/index.js +8 -0
  133. package/dist/core/storage/local.js +22 -0
  134. package/dist/core/storage/migrate.js +48 -0
  135. package/dist/core/storage/postgres.js +290 -0
  136. package/dist/core/storage/types.js +101 -0
  137. package/dist/core/storage.js +589 -0
  138. package/dist/core/suggest.js +283 -0
  139. package/dist/core/tree.js +254 -0
  140. package/dist/core/types.js +583 -0
  141. package/dist/core/version.js +1 -0
  142. package/dist/core/versions.js +245 -0
  143. package/dist/core/watch.js +2 -0
  144. package/dist/core/xml.js +68 -0
  145. package/dist/demo/args.js +58 -0
  146. package/dist/demo/browser.js +301 -0
  147. package/dist/demo/platform.js +147 -0
  148. package/dist/demo/run.js +198 -0
  149. package/dist/demo/steps.js +328 -0
  150. package/dist/mcp/project-tools.js +193 -0
  151. package/dist/mcp/server.js +785 -0
  152. package/examples/platform/README.md +33 -0
  153. package/examples/platform/api/package.json +8 -0
  154. package/examples/platform/api/src/auth-middleware.js +16 -0
  155. package/examples/platform/api/src/proxy.js +7 -0
  156. package/examples/platform/api/src/rate-limit.js +13 -0
  157. package/examples/platform/api/src/server.js +40 -0
  158. package/examples/platform/auth/package.json +9 -0
  159. package/examples/platform/auth/src/server.js +24 -0
  160. package/examples/platform/auth/src/tokens.js +19 -0
  161. package/examples/platform/auth/src/users.js +16 -0
  162. package/examples/platform/docs/api/PRD.md +10 -0
  163. package/examples/platform/docs/api/SDD.md +15 -0
  164. package/examples/platform/docs/auth/PRD.md +10 -0
  165. package/examples/platform/docs/auth/SDD.md +8 -0
  166. package/examples/platform/docs/frontend/PRD.md +18 -0
  167. package/examples/platform/docs/frontend/SDD.md +13 -0
  168. package/examples/platform/docs/pricing/PRD.md +9 -0
  169. package/examples/platform/docs/pricing/SDD.md +8 -0
  170. package/examples/platform/docs/products/PRD.md +9 -0
  171. package/examples/platform/docs/products/SDD.md +8 -0
  172. package/examples/platform/frontend/package.json +8 -0
  173. package/examples/platform/frontend/src/api-client.js +21 -0
  174. package/examples/platform/frontend/src/main.js +21 -0
  175. package/examples/platform/frontend/src/pages/products.js +12 -0
  176. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  177. package/examples/platform/frontend/src/session.js +11 -0
  178. package/examples/platform/pricing/package.json +9 -0
  179. package/examples/platform/pricing/src/cache.js +19 -0
  180. package/examples/platform/pricing/src/product-events.js +17 -0
  181. package/examples/platform/pricing/src/rules.js +19 -0
  182. package/examples/platform/pricing/src/server.js +32 -0
  183. package/examples/platform/products/package.json +9 -0
  184. package/examples/platform/products/src/catalog.js +20 -0
  185. package/examples/platform/products/src/events.js +11 -0
  186. package/examples/platform/products/src/search.js +9 -0
  187. package/examples/platform/products/src/server.js +31 -0
  188. package/migrations/postgres/001_init.sql +55 -0
  189. package/migrations/postgres/002_view_versions.sql +18 -0
  190. package/package.json +69 -4
  191. package/schema/approval.schema.json +173 -0
  192. package/schema/gap.schema.json +56 -0
  193. package/schema/pins.schema.json +122 -0
  194. package/schema/project.schema.json +93 -0
  195. package/schema/settings.schema.json +86 -0
  196. package/schema/toolbox.schema.json +206 -0
  197. package/schema/type.schema.json +121 -0
  198. package/schema/view.schema.json +240 -0
  199. package/skills/claude/build-gap/SKILL.md +28 -0
  200. package/skills/claude/check-ui/SKILL.md +40 -0
  201. package/skills/claude/draw-system/SKILL.md +38 -0
  202. package/skills/claude/gap-from-view/SKILL.md +29 -0
  203. package/skills/claude/post-audit/SKILL.md +58 -0
  204. package/skills/claude/pre-audit/SKILL.md +82 -0
  205. package/skills/claude/update-state/SKILL.md +56 -0
  206. package/skills/cursor/check-ui.mdc +40 -0
  207. package/skills/cursor/draw-system.mdc +38 -0
  208. package/skills/cursor/post-audit.mdc +44 -0
  209. package/skills/cursor/pre-audit.mdc +49 -0
  210. package/skills/cursor/update-state.mdc +45 -0
  211. package/skills/windsurf/spatial-views.md +212 -0
  212. package/toolboxes/aws.yaml +43 -0
  213. package/toolboxes/azure.yaml +41 -0
  214. package/toolboxes/cloud.yaml +95 -0
  215. package/toolboxes/docs.yaml +111 -0
  216. package/toolboxes/software.yaml +114 -0
  217. package/toolboxes/types/docs/gap.yaml +15 -0
  218. package/toolboxes/types/docs/mdd.yaml +19 -0
  219. package/toolboxes/types/docs/plain.yaml +7 -0
  220. package/toolboxes/types/docs/prd.yaml +17 -0
@@ -0,0 +1,34 @@
1
+ import { existsSync } from "node:fs";
2
+ import { posix } from "node:path";
3
+ /** Run through npx: the CLI is in npx's cache, which is not a place to point an IDE at. */
4
+ export const viaNpx = (cli) => /[\\/]_npx[\\/]/.test(cli);
5
+ export function resolveLaunch(i) {
6
+ const npx = viaNpx(i.cli);
7
+ if (i.platform === "win32")
8
+ return { argv: npx ? ["cmd", "/c", "npx", "-y", "spatial-views"] : [i.execPath, i.cli] };
9
+ if (!npx)
10
+ return { argv: [i.execPath, i.cli] };
11
+ const exists = i.exists ?? existsSync;
12
+ const bin = posix.dirname(i.execPath);
13
+ const path = [bin, ...(i.platform === "darwin" ? ["/opt/homebrew/bin"] : []), "/usr/local/bin", "/usr/bin", "/bin"];
14
+ const env = { PATH: [...new Set(path)].join(":") };
15
+ const npxCli = posix.join(bin, "..", "lib", "node_modules", "npm", "bin", "npx-cli.js");
16
+ if (exists(npxCli))
17
+ return { argv: [i.execPath, npxCli, "-y", "spatial-views"], env };
18
+ if (exists(posix.join(bin, "npx")))
19
+ return { argv: [posix.join(bin, "npx"), "-y", "spatial-views"], env };
20
+ // No npm next to node: point at this copy (it may go when npx's cache is cleared).
21
+ return { argv: [i.execPath, i.cli] };
22
+ }
23
+ /** The command line of an entry, for messages. */
24
+ export function commandLine(command, args) {
25
+ return [command, ...args].map((a) => (/[\s"]/.test(a) ? JSON.stringify(a) : a)).join(" ");
26
+ }
27
+ /** Why the canvas could not listen, and what to do about it. */
28
+ export function portError(port, err) {
29
+ if (err.code === "EADDRINUSE")
30
+ return `port ${port} is in use: Spatial Views (or something else) is already running there. Open http://127.0.0.1:${port}, or start on another port: spatial-views --port ${port + 1}`;
31
+ if (err.code === "EACCES")
32
+ return `port ${port} is not allowed here: start on another port: spatial-views --port ${port >= 1024 ? port + 1 : 4317}`;
33
+ return `Spatial Views could not start on port ${port}: ${err.message}`;
34
+ }
@@ -0,0 +1,362 @@
1
+ import { createRequire } from "node:module";
2
+ import { labelSize, routeAll } from "./route.js";
3
+ /** The size a module is drawn at: its type's size, wider for a long name (14px text, padding, the icon). */
4
+ export function moduleSize(m, type) {
5
+ const text = Math.round(m.name.length * 8.4 + (type ? 72 : 44));
6
+ return { w: Math.max(type?.size.w ?? 140, text), h: type?.size.h ?? 44 };
7
+ }
8
+ /** Each module's size from its type, for the layout. */
9
+ export function typeSizes(view, types) {
10
+ const byId = new Map(types.map((t) => [t.id, t]));
11
+ return new Map(view.modules.map((m) => [m.id, moduleSize(m, m.type ? byId.get(m.type) : undefined)]));
12
+ }
13
+ /** What the layout needs from the module types: sizes, tiers and the externals that go to the side. */
14
+ export function typeLayout(view, types) {
15
+ const byId = new Map(types.map((t) => [t.id, t]));
16
+ const tiers = new Map();
17
+ const aside = new Set();
18
+ for (const m of view.modules) {
19
+ const t = m.type ? byId.get(m.type) : undefined;
20
+ if (t?.side === "right")
21
+ aside.add(m.id);
22
+ else if (t?.tier !== undefined)
23
+ tiers.set(m.id, t.tier);
24
+ }
25
+ return { sizes: typeSizes(view, types), tiers, aside };
26
+ }
27
+ const get = (m, id) => m instanceof Map ? m.get(id) : m?.[id];
28
+ const asideOf = (opts) => new Set(opts.aside ?? []);
29
+ /**
30
+ * The row of each module (not the ones aside), top to bottom, or null when no
31
+ * module has a tier. Untyped modules take a tier from what they connect to:
32
+ * one below their lowest caller, else one above their highest callee, else a
33
+ * service. Tiers no module uses take no row.
34
+ */
35
+ export function rows(view, opts) {
36
+ const aside = asideOf(opts);
37
+ const main = view.modules.filter((m) => !aside.has(m.id));
38
+ const tier = new Map();
39
+ for (const m of main) {
40
+ const t = get(opts.tiers, m.id);
41
+ if (t !== undefined)
42
+ tier.set(m.id, t);
43
+ }
44
+ if (!tier.size)
45
+ return null;
46
+ const ids = new Set(main.map((m) => m.id));
47
+ const conns = view.connections.filter((c) => ids.has(c.from) && ids.has(c.to) && c.from !== c.to);
48
+ for (let pass = 0; pass < main.length && tier.size < main.length; pass++) {
49
+ let changed = false;
50
+ for (const m of main) {
51
+ if (tier.has(m.id))
52
+ continue;
53
+ const callers = conns.filter((c) => c.to === m.id && tier.has(c.from)).map((c) => tier.get(c.from));
54
+ const callees = conns.filter((c) => c.from === m.id && tier.has(c.to)).map((c) => tier.get(c.to));
55
+ if (callers.length)
56
+ tier.set(m.id, Math.min(6, Math.max(...callers) + 1));
57
+ else if (callees.length)
58
+ tier.set(m.id, Math.max(0, Math.min(...callees) - 1));
59
+ else
60
+ continue;
61
+ changed = true;
62
+ }
63
+ if (!changed)
64
+ break;
65
+ }
66
+ for (const m of main)
67
+ if (!tier.has(m.id))
68
+ tier.set(m.id, 4);
69
+ const used = [...new Set(tier.values())].sort((a, b) => a - b);
70
+ return new Map([...tier].map(([id, t]) => [id, used.indexOf(t)]));
71
+ }
72
+ const sizeOf = (opts, m) => {
73
+ const s = opts.sizes instanceof Map ? opts.sizes.get(m.id) : opts.sizes?.[m.id];
74
+ return s ?? moduleSize(m);
75
+ };
76
+ const GRID = 10;
77
+ /** The gap between two rows, top down. */
78
+ const ROW_GAP = 100;
79
+ const snap = (v) => Math.round(v / GRID) * GRID;
80
+ // elkjs is CommonJS; load it from node_modules as it ships (never bundled).
81
+ const require = createRequire(import.meta.url);
82
+ let elk = null;
83
+ const newElk = () => {
84
+ const Ctor = require("elkjs/lib/elk.bundled.js");
85
+ return new Ctor();
86
+ };
87
+ /** ELK's layered layout of the modules and connections: top-left positions, and bend points per connection. */
88
+ async function elkLayout(view, opts) {
89
+ elk ??= newElk();
90
+ const down = opts.direction !== "right";
91
+ const aside = asideOf(opts);
92
+ const main = view.modules.filter((m) => !aside.has(m.id));
93
+ const ids = new Set(main.map((m) => m.id));
94
+ const row = rows(view, opts);
95
+ const siblings = row ? new Set() : siblingEdges(view);
96
+ // Tiered: only connections down the rows shape the layering; one within a row, or back up, is routed after.
97
+ const layered = (c) => ids.has(c.from) && ids.has(c.to) && c.from !== c.to && (row ? row.get(c.from) < row.get(c.to) : !siblings.has(c.id));
98
+ const inRow = (c) => ids.has(c.from) && ids.has(c.to) && !layered(c);
99
+ const longest = Math.max(0, ...view.connections.filter((c) => layered(c) && c.label).map((c) => labelSize(c.label).w));
100
+ const between = down ? ROW_GAP : Math.min(220, Math.max(90, longest + 50));
101
+ const graph = {
102
+ id: "root",
103
+ layoutOptions: {
104
+ "elk.algorithm": "layered",
105
+ "elk.direction": down ? "DOWN" : "RIGHT",
106
+ "elk.edgeRouting": "ORTHOGONAL",
107
+ // More room in a row when a labelled connection runs between two modules in it: room for its label.
108
+ "elk.spacing.nodeNode": String(down
109
+ ? Math.max(60, ...view.connections.filter((c) => inRow(c) && c.label).map((c) => labelSize(c.label).w + 40))
110
+ : view.connections.some((c) => inRow(c) && c.label)
111
+ ? 80
112
+ : 60),
113
+ // Room between layers for the longest label, so a label never sits on a module.
114
+ "elk.layered.spacing.nodeNodeBetweenLayers": String(between),
115
+ "elk.spacing.edgeNode": "25",
116
+ "elk.spacing.edgeEdge": "16",
117
+ "elk.layered.spacing.edgeNodeBetweenLayers": "25",
118
+ "elk.layered.nodePlacement.strategy": "BRANDES_KOEPF",
119
+ "elk.layered.nodePlacement.bk.fixedAlignment": "BALANCED",
120
+ "elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
121
+ "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",
122
+ // Tiers: each module's row comes from its position (below), and every row spans the whole drawing.
123
+ ...(row ? { "elk.layered.layering.strategy": "INTERACTIVE", "elk.separateConnectedComponents": "false" } : { "elk.separateConnectedComponents": "true" }),
124
+ "elk.spacing.componentComponent": "70",
125
+ "elk.padding": "[top=0,left=0,bottom=0,right=0]",
126
+ },
127
+ children: orderForRows(main, view, row).map((m) => {
128
+ const s = sizeOf(opts, m);
129
+ const r = row?.get(m.id);
130
+ return { id: m.id, width: s.w, height: s.h, ...(r !== undefined ? (down ? { x: 0, y: r * 1000 } : { x: r * 1000, y: 0 }) : {}) };
131
+ }),
132
+ edges: view.connections.filter(layered).map((c) => ({ id: c.id, sources: [c.from], targets: [c.to] })),
133
+ };
134
+ const out = await elk.layout(graph);
135
+ const pos = new Map();
136
+ for (const n of out.children ?? [])
137
+ pos.set(n.id, { x: snap(n.x ?? 0), y: snap(n.y ?? 0) });
138
+ const mapY = row && down ? evenRows(pos, main, row, opts) : (y) => y;
139
+ placeAside(view, opts, pos);
140
+ const bends = new Map();
141
+ for (const e of (out.edges ?? [])) {
142
+ const pts = (e.sections ?? []).flatMap((s) => s.bendPoints ?? []);
143
+ if (pts.length)
144
+ bends.set(e.id, pts.map((p) => ({ x: Math.round(p.x), y: Math.round(mapY(p.y)) })));
145
+ }
146
+ return { pos, bends };
147
+ }
148
+ /** Modules joined by a connection within one row go next to each other in the model order ELK keeps. */
149
+ function orderForRows(main, view, row) {
150
+ if (!row)
151
+ return [...main];
152
+ const out = [];
153
+ const seen = new Set();
154
+ const add = (m) => {
155
+ if (seen.has(m.id))
156
+ return;
157
+ seen.add(m.id);
158
+ out.push(m);
159
+ for (const c of view.connections) {
160
+ const other = c.from === m.id ? c.to : c.to === m.id ? c.from : null;
161
+ const o = other ? main.find((x) => x.id === other) : undefined;
162
+ if (o && row.get(o.id) === row.get(m.id))
163
+ add(o);
164
+ }
165
+ };
166
+ for (const m of main)
167
+ add(m);
168
+ return out;
169
+ }
170
+ /**
171
+ * Even rows: every module in a row sits on the same line, centred on the
172
+ * row's tallest module, and the rows are the same distance apart. Returns
173
+ * the map from ELK's y to the new one (for the bends ELK routed).
174
+ */
175
+ function evenRows(pos, main, row, opts) {
176
+ const byRow = new Map();
177
+ for (const m of main)
178
+ if (pos.has(m.id))
179
+ byRow.set(row.get(m.id), [...(byRow.get(row.get(m.id)) ?? []), m]);
180
+ // Each row's band, before and after: [old top, old bottom, new top, new bottom].
181
+ const bands = [];
182
+ let y = 0;
183
+ for (const k of [...byRow.keys()].sort((p, q) => p - q)) {
184
+ const ms = byRow.get(k);
185
+ const h = Math.max(...ms.map((m) => sizeOf(opts, m).h));
186
+ const top = Math.min(...ms.map((m) => pos.get(m.id).y));
187
+ const bottom = Math.max(...ms.map((m) => pos.get(m.id).y + sizeOf(opts, m).h));
188
+ for (const m of ms)
189
+ pos.set(m.id, { x: pos.get(m.id).x, y: snap(y + (h - sizeOf(opts, m).h) / 2) });
190
+ bands.push([top, bottom, y, y + h]);
191
+ y += h + ROW_GAP;
192
+ }
193
+ return (v) => {
194
+ for (let i = 0; i < bands.length; i++) {
195
+ const [ot, ob, nt, nb] = bands[i];
196
+ if (v <= ob)
197
+ return v < ot && i > 0 ? lerp(v, bands[i - 1][1], ot, bands[i - 1][3], nt) : nt + Math.max(0, v - ot) * ((nb - nt) / Math.max(1, ob - ot));
198
+ const next = bands[i + 1];
199
+ if (next && v < next[0])
200
+ return lerp(v, ob, next[0], nb, next[2]);
201
+ }
202
+ const last = bands[bands.length - 1];
203
+ return last[3] + (v - last[1]);
204
+ };
205
+ }
206
+ const lerp = (v, a, b, c, d) => (b === a ? c : c + ((v - a) * (d - c)) / (b - a));
207
+ /**
208
+ * Externals: a column to the right of the rest, each level with what it
209
+ * connects to (on average), none overlapping.
210
+ */
211
+ function placeAside(view, opts, pos) {
212
+ const aside = view.modules.filter((m) => asideOf(opts).has(m.id));
213
+ if (!aside.length)
214
+ return;
215
+ const placed = view.modules.filter((m) => pos.has(m.id));
216
+ const right = placed.length ? Math.max(...placed.map((m) => pos.get(m.id).x + sizeOf(opts, m).w)) : -120;
217
+ const x = snap(right + 120);
218
+ const want = aside.map((m) => {
219
+ const ys = view.connections
220
+ .map((c) => (c.from === m.id ? c.to : c.to === m.id ? c.from : null))
221
+ .filter((o) => !!o && pos.has(o))
222
+ .map((o) => pos.get(o).y + sizeOf(opts, view.modules.find((v) => v.id === o)).h / 2);
223
+ const centre = ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : Infinity;
224
+ return { m, centre };
225
+ });
226
+ // Unconnected ones go after the connected ones.
227
+ want.sort((a, b) => a.centre - b.centre);
228
+ let floor = -Infinity;
229
+ for (const { m, centre } of want) {
230
+ const h = sizeOf(opts, m).h;
231
+ const y = snap(Math.max(Number.isFinite(centre) ? centre - h / 2 : floor === -Infinity ? 0 : floor, floor));
232
+ pos.set(m.id, { x, y });
233
+ floor = y + h + 40;
234
+ }
235
+ }
236
+ /**
237
+ * Connections between two modules that share a caller (API calls both
238
+ * Products and Pricing, and Products tells Pricing): the layout keeps the two
239
+ * side by side in one column, as people draw it, rather than pushing one a
240
+ * layer further. These connections are left out of the layering and routed
241
+ * between the two.
242
+ */
243
+ export function siblingEdges(view) {
244
+ const into = new Map();
245
+ for (const c of view.connections) {
246
+ if (c.from === c.to)
247
+ continue;
248
+ into.set(c.to, (into.get(c.to) ?? new Set()).add(c.from));
249
+ }
250
+ const out = new Set();
251
+ for (const c of view.connections) {
252
+ const a = into.get(c.from);
253
+ const b = into.get(c.to);
254
+ if (!a || !b || c.from === c.to)
255
+ continue;
256
+ if ([...a].some((p) => p !== c.to && b.has(p)))
257
+ out.add(c.id);
258
+ }
259
+ return out;
260
+ }
261
+ /** Does any segment of a path cross a module other than its two ends? */
262
+ function crossesModule(points, rects, from, to) {
263
+ for (const [id, r] of rects) {
264
+ if (id === from || id === to)
265
+ continue;
266
+ for (let i = 0; i < points.length - 1; i++) {
267
+ const a = points[i];
268
+ const b = points[i + 1];
269
+ const x1 = Math.min(a.x, b.x);
270
+ const x2 = Math.max(a.x, b.x);
271
+ const y1 = Math.min(a.y, b.y);
272
+ const y2 = Math.max(a.y, b.y);
273
+ if (x2 > r.x + 1 && x1 < r.x + r.w - 1 && y2 > r.y + 1 && y1 < r.y + r.h - 1)
274
+ return true;
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+ const rectsOf = (view, opts) => new Map(view.modules.map((m) => [m.id, { x: m.x, y: m.y, ...sizeOf(opts, m) }]));
280
+ /**
281
+ * The bends a laid-out connection keeps: none when the plain route is clean;
282
+ * ELK's bends, lined up with the route's ports, when the plain route would cross a module.
283
+ */
284
+ function keepBends(view, opts, elkBends, direction) {
285
+ const rects = rectsOf(view, opts);
286
+ const plain = routeAll(rects, view.connections.map((c) => ({ id: c.id, from: c.from, to: c.to })));
287
+ const connections = view.connections.map((c) => {
288
+ const { bends: _old, ...rest } = c;
289
+ const route = plain.get(c.id);
290
+ const eb = elkBends.get(c.id);
291
+ if (!route || !eb?.length || !crossesModule(route.points, rects, c.from, c.to))
292
+ return rest;
293
+ // Line ELK's first and last bends up with where the route leaves and arrives, so there is no jog.
294
+ const routed = routeAll(rects, [{ id: c.id, from: c.from, to: c.to, bends: eb }]).get(c.id);
295
+ const s = routed.points[0];
296
+ const t = routed.points[routed.points.length - 1];
297
+ const bends = eb.map((p) => ({ ...p }));
298
+ if (direction === "right")
299
+ (bends[0].y = s.y), (bends[bends.length - 1].y = t.y);
300
+ else
301
+ (bends[0].x = s.x), (bends[bends.length - 1].x = t.x);
302
+ return { ...rest, bends };
303
+ });
304
+ return { ...view, connections };
305
+ }
306
+ /** Lay out every module ("Tidy layout", or a View whose positions are still the layout's). */
307
+ export async function layoutView(view, opts = {}) {
308
+ if (view.kind === "sequence" || view.modules.length === 0)
309
+ return view;
310
+ const direction = opts.direction ?? "down";
311
+ const { pos, bends } = await elkLayout(view, { ...opts, direction });
312
+ const laid = { ...view, modules: view.modules.map((m) => ({ ...m, ...(pos.get(m.id) ?? { x: m.x, y: m.y }) })) };
313
+ return keepBends(laid, opts, bends, direction);
314
+ }
315
+ const overlaps = (a, b, gap) => a.x < b.x + b.w + gap && a.x + a.w + gap > b.x && a.y < b.y + b.h + gap && a.y + a.h + gap > b.y;
316
+ /**
317
+ * Place only the modules in `fresh` (the AI added them without a position),
318
+ * where the layout would put them relative to the modules already placed.
319
+ * Nothing else moves. A placed module that would overlap another is nudged down.
320
+ */
321
+ export async function placeNew(view, fresh, opts = {}) {
322
+ if (view.kind === "sequence" || !fresh.size)
323
+ return view;
324
+ const kept = view.modules.filter((m) => !fresh.has(m.id));
325
+ if (!kept.length)
326
+ return layoutView(view, opts);
327
+ const { pos } = await elkLayout(view, { ...opts, direction: opts.direction ?? "down" });
328
+ // Map the layout onto the canvas: the mean shift of the modules that stay.
329
+ let dx = 0;
330
+ let dy = 0;
331
+ for (const m of kept) {
332
+ const p = pos.get(m.id);
333
+ dx += m.x - p.x;
334
+ dy += m.y - p.y;
335
+ }
336
+ dx /= kept.length;
337
+ dy /= kept.length;
338
+ const placed = kept.map((m) => ({ x: m.x, y: m.y, ...sizeOf(opts, m) }));
339
+ const modules = view.modules.map((m) => {
340
+ if (!fresh.has(m.id))
341
+ return m;
342
+ const p = pos.get(m.id);
343
+ const r = { x: snap(p.x + dx), y: snap(p.y + dy), ...sizeOf(opts, m) };
344
+ for (let i = 0; i < 200 && placed.some((o) => overlaps(r, o, 30)); i++)
345
+ r.y += GRID * 2;
346
+ placed.push(r);
347
+ return { ...m, x: r.x, y: r.y };
348
+ });
349
+ return { ...view, modules };
350
+ }
351
+ /**
352
+ * After an AI change to a View: with `auto`, a View whose positions are the
353
+ * layout's is laid out again; on any other View only the modules in `fresh`
354
+ * are placed. With `keep`, nothing moves.
355
+ */
356
+ export async function afterAiChange(view, mode, fresh = new Set(), opts = {}) {
357
+ if (mode === "keep" || view.kind === "sequence")
358
+ return view;
359
+ if (view.auto_layout)
360
+ return layoutView(view, opts);
361
+ return placeNew(view, fresh, opts);
362
+ }
@@ -0,0 +1,68 @@
1
+ import { UserError } from "./errors.js";
2
+ /**
3
+ * Module to sub-view links: pure functions shared by the canvas, the HTTP API
4
+ * and the MCP tools. Every change returns a new View; nothing is mutated, so
5
+ * the canvas can keep the previous View for undo.
6
+ */
7
+ export class LinkError extends UserError {
8
+ }
9
+ function findModule(view, moduleId) {
10
+ const mod = view.modules.find((m) => m.id === moduleId);
11
+ if (!mod)
12
+ throw new LinkError(`module ${moduleId} is not in View ${view.id}`);
13
+ return mod;
14
+ }
15
+ function withModule(view, moduleId, change) {
16
+ findModule(view, moduleId);
17
+ return { ...view, modules: view.modules.map((m) => (m.id === moduleId ? change(m) : m)) };
18
+ }
19
+ /** Link a module to a View. Linking again changes the link. */
20
+ export function linkModule(view, moduleId, targetViewId) {
21
+ if (!targetViewId)
22
+ throw new LinkError("a link needs a target View id");
23
+ if (targetViewId === view.id)
24
+ throw new LinkError("a module cannot link to its own View");
25
+ return withModule(view, moduleId, (m) => ({ ...m, linked_view_id: targetViewId }));
26
+ }
27
+ /** Remove a module's link. Removing a link that isn't there is a no-op. */
28
+ export function unlinkModule(view, moduleId) {
29
+ return withModule(view, moduleId, ({ linked_view_id: _drop, ...rest }) => rest);
30
+ }
31
+ /** Is the module linked, and does its target still exist? */
32
+ export function linkState(mod, views) {
33
+ if (!mod.linked_view_id)
34
+ return { kind: "none" };
35
+ const target = views.find((v) => v.id === mod.linked_view_id);
36
+ return target ? { kind: "linked", view: target } : { kind: "missing", view_id: mod.linked_view_id };
37
+ }
38
+ /** A file-safe id from a name, unique among `taken`. */
39
+ export function slugId(name, taken) {
40
+ const base = name
41
+ .toLowerCase()
42
+ .replace(/[^a-z0-9]+/g, "-")
43
+ .replace(/^-+|-+$/g, "")
44
+ .slice(0, 48) || "view";
45
+ let id = base;
46
+ for (let n = 2; taken.includes(id); n++)
47
+ id = `${base}-${n}`;
48
+ return id;
49
+ }
50
+ /** "+ New sub-view": an empty View named after the module, and the parent linked to it. */
51
+ export function newSubView(parent, moduleId, takenIds) {
52
+ const mod = findModule(parent, moduleId);
53
+ const child = {
54
+ id: slugId(mod.name, [...takenIds, parent.id]),
55
+ name: mod.name,
56
+ type: "sub-view",
57
+ modules: [],
58
+ connections: [],
59
+ };
60
+ return { parent: linkModule(parent, moduleId, child.id), child };
61
+ }
62
+ /** Case-insensitive search for the View picker, current View left out. */
63
+ export function filterViews(views, query, excludeId) {
64
+ const q = query.trim().toLowerCase();
65
+ return views
66
+ .filter((v) => v.id !== excludeId)
67
+ .filter((v) => !q || v.name.toLowerCase().includes(q) || v.id.toLowerCase().includes(q));
68
+ }
@@ -0,0 +1,175 @@
1
+ const SKIP = /^(subgraph|end|classDef|class|style|linkStyle|click|direction|%%)\b/;
2
+ // Longest openers first, so `((x))` isn't read as `(` ... `)`.
3
+ const SHAPES = [
4
+ ["(((", ")))"],
5
+ ["((", "))"],
6
+ ["([", "])"],
7
+ ["[[", "]]"],
8
+ ["[(", ")]"],
9
+ ["{{", "}}"],
10
+ ["[/", "]"],
11
+ ["[\\", "]"],
12
+ ["[", "]"],
13
+ ["(", ")"],
14
+ ["{", "}"],
15
+ [">", "]"],
16
+ ];
17
+ const unquote = (s) => s.trim().replace(/^"(.*)"$/s, "$1").replace(/[/\\]$/, "").trim();
18
+ function ws(c) {
19
+ while (c.i < c.s.length && /\s/.test(c.s[c.i]))
20
+ c.i++;
21
+ }
22
+ function readNode(c, labels) {
23
+ ws(c);
24
+ const m = /^[\w$]+/.exec(c.s.slice(c.i));
25
+ if (!m)
26
+ return null;
27
+ const id = m[0];
28
+ c.i += id.length;
29
+ for (const [open, close] of SHAPES) {
30
+ if (!c.s.startsWith(open, c.i))
31
+ continue;
32
+ const end = c.s.indexOf(close, c.i + open.length);
33
+ if (end < 0)
34
+ return null;
35
+ labels.set(id, unquote(c.s.slice(c.i + open.length, end)));
36
+ c.i = end + close.length;
37
+ break;
38
+ }
39
+ const cls = /^:::[\w-]+/.exec(c.s.slice(c.i));
40
+ if (cls)
41
+ c.i += cls[0].length;
42
+ if (!labels.has(id))
43
+ labels.set(id, "");
44
+ return id;
45
+ }
46
+ function readGroup(c, labels) {
47
+ const first = readNode(c, labels);
48
+ if (!first)
49
+ return null;
50
+ const ids = [first];
51
+ for (;;) {
52
+ const save = c.i;
53
+ ws(c);
54
+ if (c.s[c.i] !== "&")
55
+ return (c.i = save), ids;
56
+ c.i++;
57
+ const next = readNode(c, labels);
58
+ if (!next)
59
+ return null;
60
+ ids.push(next);
61
+ }
62
+ }
63
+ /** An edge at the cursor; returns its label ("" for none), or null if there is no edge. */
64
+ function readEdge(c) {
65
+ const rest = c.s.slice(c.i);
66
+ // A -- text --> B, A -. text .-> B, A == text ==> B
67
+ const texted = /^\s*[<ox]?(--|==|-\.)\s+(.+?)\s+(-{2,}[>ox]|={2,}[>ox]|\.-[>ox]?|-{3,}|={3,})/.exec(rest);
68
+ if (texted) {
69
+ c.i += texted[0].length;
70
+ return unquote(texted[2]);
71
+ }
72
+ const piped = /^\s*[<ox]?(-{2,}[>ox-]?|={2,}[>ox=]?|-\.+-[>ox]?|~~~)\s*(?:\|([^|]*)\|)?/.exec(rest);
73
+ if (!piped)
74
+ return null;
75
+ c.i += piped[0].length;
76
+ return piped[2] ? unquote(piped[2]) : "";
77
+ }
78
+ export function isFlowchart(code) {
79
+ return /^\s*(flowchart|graph)\b/.test(code.replace(/^\s*%%.*$/gm, "").trimStart());
80
+ }
81
+ export function parseFlowchart(code) {
82
+ const stmts = code
83
+ .split("\n")
84
+ .flatMap((l) => l.split(";"))
85
+ .map((l) => l.trim())
86
+ .filter((l) => l && !l.startsWith("%%"));
87
+ const head = /^(flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?\s*$/.exec(stmts[0] ?? "");
88
+ if (!head)
89
+ return null;
90
+ const d = head[2] ?? "TB";
91
+ const direction = d === "TD" ? "TB" : d;
92
+ const labels = new Map();
93
+ const edges = [];
94
+ for (const stmt of stmts.slice(1)) {
95
+ if (SKIP.test(stmt))
96
+ continue;
97
+ const c = { s: stmt, i: 0 };
98
+ const local = new Map(labels);
99
+ const found = [];
100
+ let left = readGroup(c, local);
101
+ if (!left)
102
+ continue;
103
+ let ok = true;
104
+ for (;;) {
105
+ ws(c);
106
+ if (c.i >= c.s.length)
107
+ break;
108
+ const label = readEdge(c);
109
+ const right = label === null ? null : readGroup(c, local);
110
+ if (!right) {
111
+ ok = false;
112
+ break;
113
+ }
114
+ for (const from of left)
115
+ for (const to of right)
116
+ found.push({ from, to, ...(label ? { label } : {}) });
117
+ left = right;
118
+ }
119
+ if (!ok)
120
+ continue;
121
+ for (const [k, v] of local)
122
+ if (!labels.has(k) || (v && !labels.get(k)))
123
+ labels.set(k, v);
124
+ edges.push(...found);
125
+ }
126
+ if (labels.size === 0)
127
+ return null;
128
+ return { direction, nodes: [...labels].map(([id, label]) => ({ id, label: label || id })), edges };
129
+ }
130
+ /** Lay a flow out in ranks along its direction (a longest-path layering). */
131
+ export function layout(flow) {
132
+ const rank = new Map(flow.nodes.map((n) => [n.id, 0]));
133
+ for (let pass = 0; pass < flow.nodes.length; pass++) {
134
+ let changed = false;
135
+ for (const e of flow.edges) {
136
+ if (e.from === e.to)
137
+ continue;
138
+ const r = rank.get(e.from) + 1;
139
+ if (r > rank.get(e.to) && r < flow.nodes.length)
140
+ (rank.set(e.to, r), (changed = true));
141
+ }
142
+ if (!changed)
143
+ break;
144
+ }
145
+ const maxRank = Math.max(0, ...rank.values());
146
+ const slot = new Map();
147
+ const pos = new Map();
148
+ for (const n of flow.nodes) {
149
+ let r = rank.get(n.id);
150
+ if (flow.direction === "RL" || flow.direction === "BT")
151
+ r = maxRank - r;
152
+ const k = slot.get(r) ?? 0;
153
+ slot.set(r, k + 1);
154
+ const across = flow.direction === "LR" || flow.direction === "RL";
155
+ pos.set(n.id, across ? { x: r * 240, y: k * 120 } : { x: k * 240, y: r * 140 });
156
+ }
157
+ return pos;
158
+ }
159
+ export function flowToView(flow, meta) {
160
+ const pos = layout(flow);
161
+ return {
162
+ id: meta.id,
163
+ name: meta.name,
164
+ type: "sub-view",
165
+ draft: true,
166
+ source: meta.source,
167
+ modules: flow.nodes.map((n) => ({ id: n.id, name: n.label, ...pos.get(n.id) })),
168
+ connections: flow.edges.map((e, i) => ({
169
+ id: `c${i + 1}`,
170
+ from: e.from,
171
+ to: e.to,
172
+ ...(e.label ? { label: e.label } : {}),
173
+ })),
174
+ };
175
+ }