spatial-views 0.1.0 → 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 (223) hide show
  1. package/README.md +201 -19
  2. package/dist/app/assets/{abnfDiagram-S7VZAUFO-BVgtb0Hw.js → abnfDiagram-S7VZAUFO-CFbb_Sz2.js} +1 -1
  3. package/dist/app/assets/{architecture-WOLXFQ4H-DxylGHqT.js → architecture-WOLXFQ4H-CsBD__5a.js} +1 -1
  4. package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
  5. package/dist/app/assets/{blockDiagram-APKKGZFW-C7fb3MCE.js → blockDiagram-APKKGZFW-BZDPbzAG.js} +1 -1
  6. package/dist/app/assets/{c4Diagram-KJ2TOQU5-Bkb_0fbd.js → c4Diagram-KJ2TOQU5-BilBWuq5.js} +1 -1
  7. package/dist/app/assets/{chunk-6MUBBAK2-DU4vZ03M.js → chunk-6MUBBAK2-BBl-4tQr.js} +1 -1
  8. package/dist/app/assets/{chunk-AXFCVDMN-De96BVTB.js → chunk-AXFCVDMN-BhsttQ-k.js} +1 -1
  9. package/dist/app/assets/{chunk-BG4553SI-J33jsRLV.js → chunk-BG4553SI-mWcPcFZr.js} +2 -2
  10. package/dist/app/assets/{chunk-DQASFODM-Bh85SSGO.js → chunk-DQASFODM-7FKe2gLt.js} +1 -1
  11. package/dist/app/assets/{chunk-HFQBQIA3-CCklgplR.js → chunk-HFQBQIA3-nXrQ08BL.js} +1 -1
  12. package/dist/app/assets/{chunk-KQLB2F66-B04qR8ED.js → chunk-KQLB2F66-swukhFmZ.js} +1 -1
  13. package/dist/app/assets/{chunk-KS47KZWR-BsqDyyAt.js → chunk-KS47KZWR-DkDkwO82.js} +1 -1
  14. package/dist/app/assets/{chunk-LEVMRMFU-DwxrBz2u.js → chunk-LEVMRMFU-DXH6iXv3.js} +1 -1
  15. package/dist/app/assets/{chunk-M57EVK23-D9YIHjps.js → chunk-M57EVK23-B-kEyOJF.js} +1 -1
  16. package/dist/app/assets/{chunk-OY52VR5R-WB63DeTA.js → chunk-OY52VR5R-DweG7qYw.js} +1 -1
  17. package/dist/app/assets/{chunk-QB3YPZ4I-cHzzKdtb.js → chunk-QB3YPZ4I-DyozK3lV.js} +1 -1
  18. package/dist/app/assets/{chunk-R3KSYZAL-C7rDagaa.js → chunk-R3KSYZAL-BEXCUN6J.js} +1 -1
  19. package/dist/app/assets/{chunk-STOXU5M4-CG6pnJtH.js → chunk-STOXU5M4-BaTlty4O.js} +1 -1
  20. package/dist/app/assets/{chunk-TU62E6Q5-BbcGYfy_.js → chunk-TU62E6Q5-_rcUP1Fh.js} +1 -1
  21. package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
  22. package/dist/app/assets/{chunk-X4PVCEUW-BUI1Oi3q.js → chunk-X4PVCEUW-DGxTL3kB.js} +1 -1
  23. package/dist/app/assets/{chunk-XXDRQBXY-DYhK5YW-.js → chunk-XXDRQBXY-C02Gpej2.js} +1 -1
  24. package/dist/app/assets/{classDiagram-v2-L25IHNXF-K-k5GTUn.js → classDiagram-v2-L25IHNXF-DLEBwpvk.js} +1 -1
  25. package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
  26. package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
  27. package/dist/app/assets/{cynefinDiagram-L36ESFBY-mkV33_Xx.js → cynefinDiagram-L36ESFBY-CLFstukD.js} +1 -1
  28. package/dist/app/assets/{d3-scale-ygdFCUH8.js → d3-scale-CaJQQYkF.js} +1 -1
  29. package/dist/app/assets/{dagre-SPEB5RXH-BNIymLsu.js → dagre-SPEB5RXH-BaSAny1T.js} +1 -1
  30. package/dist/app/assets/{diagram-3B7GL73J-CGOiolFW.js → diagram-3B7GL73J-DJNlt5Sg.js} +1 -1
  31. package/dist/app/assets/{diagram-DNEMPZML-DZFkHNly.js → diagram-DNEMPZML-DEHeuILB.js} +1 -1
  32. package/dist/app/assets/{diagram-L3MUGCDN-B42GAYLq.js → diagram-L3MUGCDN-ob5Ka2Xc.js} +1 -1
  33. package/dist/app/assets/{diagram-LA4NIPWU-BYuLRYId.js → diagram-LA4NIPWU-DNESzFAc.js} +1 -1
  34. package/dist/app/assets/{diagram-MHCOC4E2-DGzI6TJG.js → diagram-MHCOC4E2-CVi9zKjG.js} +1 -1
  35. package/dist/app/assets/{diagram-XPFHEONP-CTBEgDQ8.js → diagram-XPFHEONP-DInT4C7e.js} +1 -1
  36. package/dist/app/assets/dist-CjvHN74u.js +1 -0
  37. package/dist/app/assets/{ebnfDiagram-UZSYDL2S-GuMdOCvL.js → ebnfDiagram-UZSYDL2S-CRCZNsji.js} +1 -1
  38. package/dist/app/assets/{elk-XV6XMXQE-BpY3loT5.js → elk-XV6XMXQE-D4fsWI2l.js} +1 -1
  39. package/dist/app/assets/{erDiagram-EYBAPDEH-nDZ2PMGl.js → erDiagram-EYBAPDEH-YQNM5StV.js} +1 -1
  40. package/dist/app/assets/{eventmodeling-K75KTNOO-BN42Mgwh.js → eventmodeling-K75KTNOO-Bev08J2F.js} +1 -1
  41. package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
  42. package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
  43. package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
  44. package/dist/app/assets/{gitGraphDiagram-STJD7YCW-CDkKLrvO.js → gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js} +1 -1
  45. package/dist/app/assets/index-Bn6_wHEp.js +98 -0
  46. package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
  47. package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
  48. package/dist/app/assets/{infoDiagram-KBXO4MBG-B92P8pjY.js → infoDiagram-KBXO4MBG-DT7LbBRQ.js} +1 -1
  49. package/dist/app/assets/{ishikawaDiagram-M35NCXHK-BRZsbCvK.js → ishikawaDiagram-M35NCXHK-CF51lhjB.js} +1 -1
  50. package/dist/app/assets/{journeyDiagram-OPLOXDXO-Bppwb1oF.js → journeyDiagram-OPLOXDXO-_36FonKk.js} +1 -1
  51. package/dist/app/assets/{kanban-definition-BZKZHSQY-ByD_x5cm.js → kanban-definition-BZKZHSQY-tLk_OlQ-.js} +1 -1
  52. package/dist/app/assets/{mermaid-parser.core-CKmnV0Md.js → mermaid-parser.core-_3Vo8x6b.js} +3 -3
  53. package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
  54. package/dist/app/assets/{mindmap-definition-I2QAS2VK-fRbUh23C.js → mindmap-definition-I2QAS2VK-BCI4HRX3.js} +1 -1
  55. package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
  56. package/dist/app/assets/{pegDiagram-FD4XPPHP-qIABf6H8.js → pegDiagram-FD4XPPHP-BOzSoNji.js} +1 -1
  57. package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
  58. package/dist/app/assets/{pieDiagram-J4AKIIQI-Bb4RBdrc.js → pieDiagram-J4AKIIQI-PlHpwT_c.js} +1 -1
  59. package/dist/app/assets/{quadrantDiagram-XTYBLID2-B0CpcVWE.js → quadrantDiagram-XTYBLID2-CdxZ0ael.js} +1 -1
  60. package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
  61. package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
  62. package/dist/app/assets/{railroad-abnf-LNEFI6M7-BUhw7Iuo.js → railroad-abnf-LNEFI6M7-C49jJE4Y.js} +1 -1
  63. package/dist/app/assets/{railroad-ebnf-DWYD2UWJ-nQNF56LJ.js → railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js} +1 -1
  64. package/dist/app/assets/{railroad-peg-JR7BVNR7-CwvbVIo6.js → railroad-peg-JR7BVNR7-DjBPSCKV.js} +1 -1
  65. package/dist/app/assets/{railroadDiagram-MRQ6NCDL-Dwr-mPZL.js → railroadDiagram-MRQ6NCDL-wGcmIMqq.js} +1 -1
  66. package/dist/app/assets/{requirementDiagram-Y7LWUY3S-Ctv2DKJM.js → requirementDiagram-Y7LWUY3S-DprFI03z.js} +1 -1
  67. package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  68. package/dist/app/assets/{sankeyDiagram-WGJFYUXA-BvKX0eIe.js → sankeyDiagram-WGJFYUXA-DygYWLTR.js} +1 -1
  69. package/dist/app/assets/{sequenceDiagram-5NDRBG5M-Y4YqU2Xt.js → sequenceDiagram-5NDRBG5M-BzIr2DBO.js} +1 -1
  70. package/dist/app/assets/{stateDiagram-v2-FJ4FJNEA-DmjIjn4u.js → stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js} +1 -1
  71. package/dist/app/assets/{swimlanes-UMQ2AFYF-B2O5JCjs.js → swimlanes-UMQ2AFYF-CIEH82Zt.js} +1 -1
  72. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
  73. package/dist/app/assets/{timeline-definition-SEUHKTQE-DJJdixAI.js → timeline-definition-SEUHKTQE-BGYSqup2.js} +1 -1
  74. package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
  75. package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
  76. package/dist/app/assets/{usecaseDiagram-AFA6YXN4-Bp8pXgvR.js → usecaseDiagram-AFA6YXN4-dy6oVOke.js} +1 -1
  77. package/dist/app/assets/{vennDiagram-NNMJR3RB-DYSfZMWT.js → vennDiagram-NNMJR3RB-CUyuhcAk.js} +1 -1
  78. package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
  79. package/dist/app/assets/{wardleyDiagram-S7YFUSEH-CGJ8qg76.js → wardleyDiagram-S7YFUSEH-DYtxYUHe.js} +1 -1
  80. package/dist/app/assets/{xychartDiagram-GGNKY7IX-CRSvraFc.js → xychartDiagram-GGNKY7IX-ClR06AlB.js} +1 -1
  81. package/dist/app/index.html +3 -2
  82. package/dist/cli/index.js +281 -53
  83. package/dist/core/api.js +262 -51
  84. package/dist/core/approvals.js +426 -0
  85. package/dist/core/context.js +68 -3
  86. package/dist/core/diff.js +156 -0
  87. package/dist/core/docs.js +9 -3
  88. package/dist/core/doctor.js +152 -0
  89. package/dist/core/doctypes.js +79 -0
  90. package/dist/core/edit.js +25 -0
  91. package/dist/core/flags.js +13 -0
  92. package/dist/core/gaps.js +7 -2
  93. package/dist/core/heading.js +4 -0
  94. package/dist/core/history.js +36 -5
  95. package/dist/core/home.js +345 -0
  96. package/dist/core/lanes.js +134 -0
  97. package/dist/core/launch.js +34 -0
  98. package/dist/core/layout.js +362 -0
  99. package/dist/core/newdoc.js +66 -0
  100. package/dist/core/open-folder.js +30 -0
  101. package/dist/core/openspec.js +6 -6
  102. package/dist/core/paths.js +71 -4
  103. package/dist/core/project.js +392 -0
  104. package/dist/core/route.js +420 -0
  105. package/dist/core/scan.js +514 -0
  106. package/dist/core/schema.js +170 -1
  107. package/dist/core/scope.js +126 -0
  108. package/dist/core/setup.js +134 -0
  109. package/dist/core/skills.js +92 -14
  110. package/dist/core/storage/config.js +74 -0
  111. package/dist/core/storage/events.js +54 -0
  112. package/dist/core/storage/folder-watch.js +147 -0
  113. package/dist/core/storage/folder.js +469 -0
  114. package/dist/core/storage/index.js +8 -0
  115. package/dist/core/storage/local.js +22 -0
  116. package/dist/core/storage/migrate.js +48 -0
  117. package/dist/core/storage/postgres.js +290 -0
  118. package/dist/core/storage/types.js +101 -0
  119. package/dist/core/storage.js +483 -77
  120. package/dist/core/suggest.js +283 -0
  121. package/dist/core/tree.js +254 -0
  122. package/dist/core/types.js +583 -0
  123. package/dist/core/version.js +1 -1
  124. package/dist/core/versions.js +245 -0
  125. package/dist/core/watch.js +2 -136
  126. package/dist/core/xml.js +23 -5
  127. package/dist/demo/args.js +58 -0
  128. package/dist/demo/browser.js +301 -0
  129. package/dist/demo/platform.js +147 -0
  130. package/dist/demo/run.js +198 -0
  131. package/dist/demo/steps.js +328 -0
  132. package/dist/mcp/project-tools.js +193 -0
  133. package/dist/mcp/server.js +493 -65
  134. package/examples/platform/README.md +33 -0
  135. package/examples/platform/api/package.json +8 -0
  136. package/examples/platform/api/src/auth-middleware.js +16 -0
  137. package/examples/platform/api/src/proxy.js +7 -0
  138. package/examples/platform/api/src/rate-limit.js +13 -0
  139. package/examples/platform/api/src/server.js +40 -0
  140. package/examples/platform/auth/package.json +9 -0
  141. package/examples/platform/auth/src/server.js +24 -0
  142. package/examples/platform/auth/src/tokens.js +19 -0
  143. package/examples/platform/auth/src/users.js +16 -0
  144. package/examples/platform/docs/api/PRD.md +10 -0
  145. package/examples/platform/docs/api/SDD.md +15 -0
  146. package/examples/platform/docs/auth/PRD.md +10 -0
  147. package/examples/platform/docs/auth/SDD.md +8 -0
  148. package/examples/platform/docs/frontend/PRD.md +18 -0
  149. package/examples/platform/docs/frontend/SDD.md +13 -0
  150. package/examples/platform/docs/pricing/PRD.md +9 -0
  151. package/examples/platform/docs/pricing/SDD.md +8 -0
  152. package/examples/platform/docs/products/PRD.md +9 -0
  153. package/examples/platform/docs/products/SDD.md +8 -0
  154. package/examples/platform/frontend/package.json +8 -0
  155. package/examples/platform/frontend/src/api-client.js +21 -0
  156. package/examples/platform/frontend/src/main.js +21 -0
  157. package/examples/platform/frontend/src/pages/products.js +12 -0
  158. package/examples/platform/frontend/src/pages/sign-in.js +14 -0
  159. package/examples/platform/frontend/src/session.js +11 -0
  160. package/examples/platform/pricing/package.json +9 -0
  161. package/examples/platform/pricing/src/cache.js +19 -0
  162. package/examples/platform/pricing/src/product-events.js +17 -0
  163. package/examples/platform/pricing/src/rules.js +19 -0
  164. package/examples/platform/pricing/src/server.js +32 -0
  165. package/examples/platform/products/package.json +9 -0
  166. package/examples/platform/products/src/catalog.js +20 -0
  167. package/examples/platform/products/src/events.js +11 -0
  168. package/examples/platform/products/src/search.js +9 -0
  169. package/examples/platform/products/src/server.js +31 -0
  170. package/migrations/postgres/001_init.sql +55 -0
  171. package/migrations/postgres/002_view_versions.sql +18 -0
  172. package/package.json +18 -2
  173. package/schema/approval.schema.json +173 -0
  174. package/schema/gap.schema.json +3 -0
  175. package/schema/project.schema.json +93 -0
  176. package/schema/settings.schema.json +86 -0
  177. package/schema/toolbox.schema.json +206 -0
  178. package/schema/type.schema.json +121 -0
  179. package/schema/view.schema.json +106 -0
  180. package/skills/claude/build-gap/SKILL.md +7 -0
  181. package/skills/claude/check-ui/SKILL.md +40 -0
  182. package/skills/claude/draw-system/SKILL.md +24 -9
  183. package/skills/claude/gap-from-view/SKILL.md +7 -0
  184. package/skills/claude/post-audit/SKILL.md +58 -0
  185. package/skills/claude/pre-audit/SKILL.md +82 -0
  186. package/skills/claude/update-state/SKILL.md +56 -0
  187. package/skills/cursor/check-ui.mdc +40 -0
  188. package/skills/cursor/draw-system.mdc +24 -9
  189. package/skills/cursor/post-audit.mdc +44 -0
  190. package/skills/cursor/pre-audit.mdc +49 -0
  191. package/skills/cursor/update-state.mdc +45 -0
  192. package/skills/windsurf/spatial-views.md +182 -36
  193. package/toolboxes/aws.yaml +43 -0
  194. package/toolboxes/azure.yaml +41 -0
  195. package/toolboxes/cloud.yaml +95 -0
  196. package/toolboxes/docs.yaml +111 -0
  197. package/toolboxes/software.yaml +114 -0
  198. package/toolboxes/types/docs/gap.yaml +15 -0
  199. package/toolboxes/types/docs/mdd.yaml +19 -0
  200. package/toolboxes/types/docs/plain.yaml +7 -0
  201. package/toolboxes/types/docs/prd.yaml +17 -0
  202. package/dist/app/assets/architectureDiagram-YGSQEFNW-BrBCHqUH.js +0 -36
  203. package/dist/app/assets/chunk-X3CZISLH-FMl4PpWt.js +0 -1
  204. package/dist/app/assets/cose-bilkent-JH36ORCC-BJmLLpaN.js +0 -1
  205. package/dist/app/assets/cynefin-EF2NZ3EQ-DrzwMKdm.js +0 -1
  206. package/dist/app/assets/dist-1Q8ng3tu.js +0 -1
  207. package/dist/app/assets/flowDiagram-MALGAFMO-BCwwiLzb.js +0 -1
  208. package/dist/app/assets/ganttDiagram-23REXITY-xMRHaU3y.js +0 -292
  209. package/dist/app/assets/gitGraph-VSP46ZUC-DyGq5mdd.js +0 -1
  210. package/dist/app/assets/index-BY66fc8Q.js +0 -95
  211. package/dist/app/assets/index-ByetEVbs.css +0 -1
  212. package/dist/app/assets/info-OHQRW6UA-DOBf-fQH.js +0 -1
  213. package/dist/app/assets/mermaid.core-BoRvk1Q-.js +0 -44
  214. package/dist/app/assets/packet-JDAUHWVQ-CgHq03Zj.js +0 -1
  215. package/dist/app/assets/pie-XZMESJXO-DtNh3cDE.js +0 -1
  216. package/dist/app/assets/radar-ABXABTNO-BS0FcsIX.js +0 -1
  217. package/dist/app/assets/railroad-I3PHUGI6-lO8vfGdI.js +0 -1
  218. package/dist/app/assets/swimlanesDiagram-OMPLPG4O-DhCl-Cjg.js +0 -8
  219. package/dist/app/assets/treeView-D4JQ5SDB-Dd1no4eE.js +0 -1
  220. package/dist/app/assets/treemap-SAJKECNS-t6wtsaki.js +0 -1
  221. package/dist/app/assets/wardley-7MLQ67FV-Bx60QTuu.js +0 -1
  222. package/skills/cursor/build-gap.mdc +0 -21
  223. package/skills/cursor/gap-from-view.mdc +0 -22
@@ -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,66 @@
1
+ import { mkdir, stat, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { DEFAULT_SOURCES } from "./docs.js";
4
+ import { UserError } from "./errors.js";
5
+ import { resolveDocPath, ProjectStore } from "./project.js";
6
+ import { fillTemplate, findDocType, loadDocTypes, slug } from "./types.js";
7
+ const exists = async (abs) => !!(await stat(abs).catch(() => null));
8
+ /**
9
+ * Make a doc from a doc type's template (a toolbox's docs) and pin it to a
10
+ * module or a View. In a repo it goes in the type's folder (docs/ by default),
11
+ * named from the title; in a project (home mode) it goes in the project's
12
+ * reports. An existing file is never overwritten: the name gets -2, -3...
13
+ */
14
+ export async function createDoc(spatial, input) {
15
+ const type = findDocType(await loadDocTypes(spatial.dataDir, input.dirs), input.type);
16
+ const owner = input.module?.name ?? input.view?.name ?? "";
17
+ const title = input.title?.trim() ||
18
+ fillTemplate(type.title, { type: type.name, module: owner, view: input.view?.name ?? "" }).replace(/\s+/g, " ").trim() ||
19
+ type.name;
20
+ const text = fillTemplate(type.template, { title, module: input.module?.name ?? "", view: input.view?.name ?? "" });
21
+ let path;
22
+ if (spatial.mode === "home") {
23
+ const store = ProjectStore.of(spatial);
24
+ const base = slug(input.path?.replace(/\.md$/i, "") ?? title);
25
+ let name = base;
26
+ for (let n = 2; await exists(await store.reportPath(name)); n++)
27
+ name = `${base}-${n}`;
28
+ path = await store.saveReport(name, text);
29
+ }
30
+ else {
31
+ let rel;
32
+ if (input.path) {
33
+ rel = input.path.trim();
34
+ if (!rel.toLowerCase().endsWith(".md"))
35
+ throw new UserError(`${rel}: a doc is a .md file`);
36
+ const doc = await resolveDocPath(spatial, rel);
37
+ if (doc.source)
38
+ throw new UserError(`${rel}: new docs go in the repo, not in a source`);
39
+ if (await exists(doc.abs))
40
+ throw new UserError(`${doc.rel} already exists`);
41
+ rel = doc.rel;
42
+ }
43
+ else {
44
+ const base = `${type.folder}/${slug(title)}`;
45
+ rel = `${base}.md`;
46
+ for (let n = 2; await exists((await resolveDocPath(spatial, rel)).abs); n++)
47
+ rel = `${base}-${n}.md`;
48
+ }
49
+ const doc = await resolveDocPath(spatial, rel);
50
+ await mkdir(dirname(doc.abs), { recursive: true });
51
+ await writeFile(doc.abs, text.endsWith("\n") ? text : `${text}\n`, { encoding: "utf8", flag: "wx" });
52
+ path = doc.rel;
53
+ // A folder outside docs/ and openspec/ becomes a doc source, so the Docs panel lists it.
54
+ const top = path.split("/")[0];
55
+ if (path.includes("/") && !DEFAULT_SOURCES.includes(top))
56
+ await spatial.pins.addSource(top);
57
+ }
58
+ let pin;
59
+ if (input.view && input.module)
60
+ pin = { path, kind: "module", view_id: input.view.id, module_id: input.module.id };
61
+ else if (input.view)
62
+ pin = { path, kind: "view", view_id: input.view.id };
63
+ if (pin)
64
+ await spatial.pins.add(pin);
65
+ return { path, type, title, ...(pin ? { pin } : {}) };
66
+ }
@@ -0,0 +1,30 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { detectWsl } from "./skills.js";
3
+ /** How to open a folder in the system's file manager, for this platform. */
4
+ export function folderCommand(dir, platform = process.platform, wsl = detectWsl()) {
5
+ if (platform === "win32")
6
+ return ["explorer.exe", [dir]];
7
+ if (platform === "darwin")
8
+ return ["open", [dir]];
9
+ if (wsl) {
10
+ // Windows Explorer, on the folder's \\wsl$ path.
11
+ let win = dir;
12
+ try {
13
+ win = execFileSync("wslpath", ["-w", dir], { encoding: "utf8" }).trim() || dir;
14
+ }
15
+ catch {
16
+ // wslpath missing: Explorer still opens on the Linux path's parent, if at all.
17
+ }
18
+ return ["explorer.exe", [win]];
19
+ }
20
+ return ["xdg-open", [dir]];
21
+ }
22
+ /** Open `dir` in the file manager. Resolves once launched; rejects if the command can't start. */
23
+ export function openFolder(dir) {
24
+ const [cmd, args] = folderCommand(dir);
25
+ return new Promise((resolve, reject) => {
26
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
27
+ child.once("error", (e) => reject(new Error(`could not open ${dir} (${cmd}: ${e.message})`)));
28
+ child.once("spawn", () => (child.unref(), resolve()));
29
+ });
30
+ }
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { UserError } from "./errors.js";
4
4
  const isDir = async (p) => (await stat(p).catch(() => null))?.isDirectory() === true;
@@ -107,14 +107,14 @@ export async function readChange(root, entry) {
107
107
  * Start a change for a Gap: openspec/changes/<id>/ with a proposal and a
108
108
  * tasks list, in the shape OpenSpec's own commands read and fill in.
109
109
  */
110
- export async function createChange(root, input) {
110
+ export async function createChange(root, input,
111
+ /** Writes a doc into the project's store (Spatial.docs.write). */
112
+ write) {
111
113
  const rel = `openspec/changes/${input.id}`;
112
114
  if (await findChange(root, input.id))
113
115
  throw new UserError(`an OpenSpec change ${input.id} already exists`);
114
- const dir = join(root, rel);
115
- await mkdir(dir, { recursive: true });
116
116
  const where = input.modules.map((m) => `- ${m} (View: ${input.view})`).join("\n");
117
- await writeFile(join(dir, "proposal.md"), `# ${input.title}\n\n## Why\n${input.intent || "TBD"}\n\n## What Changes\n- TBD\n\n## Impact\n${where || "- TBD"}\n`, "utf8");
118
- await writeFile(join(dir, "tasks.md"), `## 1. Implementation\n- [ ] 1.1 TBD\n`, "utf8");
117
+ await write(`${rel}/proposal.md`, `# ${input.title}\n\n## Why\n${input.intent || "TBD"}\n\n## What Changes\n- TBD\n\n## Impact\n${where || "- TBD"}\n`);
118
+ await write(`${rel}/tasks.md`, `## 1. Implementation\n- [ ] 1.1 TBD\n`);
119
119
  return rel;
120
120
  }
@@ -1,5 +1,68 @@
1
- import { isAbsolute, relative, resolve, sep } from "node:path";
1
+ import { realpathSync } from "node:fs";
2
+ import { isAbsolute, posix, relative, resolve, sep, win32 } from "node:path";
2
3
  import { UserError } from "./errors.js";
4
+ /** A Windows drive path (`c:\git\x`, `D:/docs`) or a network path (`\\server\share`). */
5
+ export const WIN_ABS = /^[A-Za-z]:[\\/]|^\\\\/;
6
+ /** A Windows drive as WSL mounts it: `/mnt/c/git/x`. */
7
+ const MNT = /^\/mnt\/([A-Za-z])(?:\/(.*))?$/;
8
+ /**
9
+ * An absolute path in this OS's spelling, or null when `p` is not absolute in
10
+ * either spelling. A Windows path made in WSL and a WSL path made on Windows
11
+ * both work: `c:\git\x` is `/mnt/c/git/x` in WSL and Linux, and `/mnt/c/git/x`
12
+ * is `c:\git\x` on Windows.
13
+ */
14
+ export function nativeAbs(p, platform = process.platform) {
15
+ const raw = p.trim();
16
+ if (platform === "win32") {
17
+ const m = MNT.exec(raw.replace(/\\/g, "/"));
18
+ if (m)
19
+ return win32.join(`${m[1].toLowerCase()}:\\`, ...(m[2] ?? "").split("/").filter(Boolean));
20
+ return win32.isAbsolute(raw) ? win32.resolve(raw) : null;
21
+ }
22
+ if (WIN_ABS.test(raw)) {
23
+ if (raw.startsWith("\\\\"))
24
+ throw new UserError(`${p}: network paths are not supported here`);
25
+ return posix.join("/mnt", raw[0].toLowerCase(), ...raw.slice(3).split(/[\\/]+/).filter(Boolean));
26
+ }
27
+ return posix.isAbsolute(raw) ? posix.resolve(raw) : null;
28
+ }
29
+ /**
30
+ * macOS keeps /var, /tmp and /etc as links into /private. The real spelling of
31
+ * such a path, worked out from the text alone (nothing on disk is looked at).
32
+ */
33
+ export function macReal(p, platform = process.platform) {
34
+ return platform === "darwin" && /^\/(?:var|tmp|etc)(?:\/|$)/.test(p) ? `/private${p}` : p;
35
+ }
36
+ /** True when `p` is a file system root: `/`, a drive (`C:\`, `D:\`) or a share (`\\server\share\`). */
37
+ export function isFsRoot(p, platform = process.platform) {
38
+ const path = platform === "win32" ? win32 : posix;
39
+ const r = path.resolve(p);
40
+ return r === path.parse(r).root;
41
+ }
42
+ /** True when `p` is absolute in either spelling (`c:\git\x` or `/mnt/c/git/x`). */
43
+ export function isAnyAbs(p) {
44
+ const raw = p.trim();
45
+ return WIN_ABS.test(raw) || isAbsolute(raw) || raw.startsWith("/");
46
+ }
47
+ /**
48
+ * The same folder, compared as written: Windows paths ignore case (the file
49
+ * system does), both spellings of a drive path are equal, and so are /var and
50
+ * /private/var on macOS.
51
+ */
52
+ export function samePath(a, b, platform = process.platform) {
53
+ const na = nativeAbs(a, platform) ?? a;
54
+ const nb = nativeAbs(b, platform) ?? b;
55
+ return platform === "win32" ? na.toLowerCase() === nb.toLowerCase() : macReal(na, platform) === macReal(nb, platform);
56
+ }
57
+ /** The root's real path (the root itself is always in scope). */
58
+ function realRoot(root) {
59
+ try {
60
+ return realpathSync.native(root);
61
+ }
62
+ catch {
63
+ return resolve(root);
64
+ }
65
+ }
3
66
  /**
4
67
  * A repo-relative, forward-slash path for `p`, refusing anything outside the
5
68
  * repo (absolute paths elsewhere, `..` escapes). Pins and pointers are stored
@@ -9,11 +72,15 @@ export function repoPath(root, p) {
9
72
  const raw = p.trim();
10
73
  if (!raw)
11
74
  throw new UserError("a path is needed");
12
- const abs = isAbsolute(raw) ? resolve(raw) : resolve(root, raw);
13
- const rel = relative(resolve(root), abs);
75
+ const abs = nativeAbs(raw) ?? resolve(root, raw);
76
+ const out = (r) => r.startsWith("..") || isAbsolute(r);
77
+ let rel = relative(resolve(root), abs);
78
+ // The root may be given through a symlink and the path by its real name.
79
+ if (out(rel))
80
+ rel = relative(realRoot(root), macReal(abs));
14
81
  if (rel === "")
15
82
  return ".";
16
- if (rel.startsWith("..") || isAbsolute(rel))
83
+ if (out(rel))
17
84
  throw new UserError(`${p} is outside the repo`);
18
85
  return rel.split(sep).join("/");
19
86
  }