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,392 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { basename, join, posix, relative, resolve, sep, win32 } from "node:path";
3
+ import { ProjectSchema } from "./schema.js";
4
+ import { UserError } from "./errors.js";
5
+ import { absPath, isAnyAbs, isFsRoot, nativeAbs, repoPath, samePath } from "./paths.js";
6
+ import { describeRoots, isInside, realInside, realPath, rootOf, ScopeError } from "./scope.js";
7
+ import { ConflictError, folderRef, NotFoundError, Spatial } from "./storage.js";
8
+ /**
9
+ * A Project (PRD §9.1): its `project.json` lists the sources it reads (repos,
10
+ * docs folders, diagram folders). Views, Gaps, pins and audit reports live in
11
+ * the project's storage (the folder store: the project's data folder (`~/SpatialViews/projects/<slug>/`, or a repo's
12
+ * `.spatial/` for a single-repo project; or Postgres). Sources stay where they
13
+ * are on disk and are only ever read (they are not project data).
14
+ */
15
+ export { AuditKindSchema, AuditSchema, ProjectSchema, SourceKindSchema, SourceSchema, } from "./schema.js";
16
+ /**
17
+ * Where a source path is on this machine. Both spellings work everywhere: on
18
+ * WSL / Linux a drive path `c:\git\api` maps to `/mnt/c/git/api`, and on
19
+ * Windows `/mnt/c/git/api` maps to `c:\git\api`. Relative paths are taken
20
+ * from the project folder.
21
+ */
22
+ export function localPath(projectRoot, p, platform = process.platform) {
23
+ const raw = p.trim();
24
+ if (!raw)
25
+ throw new UserError("a path is needed");
26
+ const abs = nativeAbs(raw, platform);
27
+ if (abs)
28
+ return abs;
29
+ if (platform === "win32")
30
+ return win32.resolve(projectRoot, raw);
31
+ return posix.resolve(projectRoot, raw.replace(/\\/g, "/"));
32
+ }
33
+ /** The last path segment, for Windows or POSIX paths alike. */
34
+ function lastSegment(p) {
35
+ const parts = p.trim().split(/[\\/]+/).filter(Boolean);
36
+ return parts[parts.length - 1] ?? "source";
37
+ }
38
+ function slug(s) {
39
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "source";
40
+ }
41
+ async function isDir(p) {
42
+ return (await stat(p).catch(() => null))?.isDirectory() === true;
43
+ }
44
+ /** Guess a source's kind: a repo has `.git`; a folder named like diagrams is diagrams; else docs. */
45
+ export async function detectKind(abs) {
46
+ if (await stat(join(abs, ".git")).catch(() => null))
47
+ return "repo";
48
+ return /diagram|drawio|miro|design/i.test(basename(abs)) ? "diagrams" : "docs";
49
+ }
50
+ /** The current commit of a git repo, read from `.git` without running git. */
51
+ export async function gitHead(repo) {
52
+ let gitDir = join(repo, ".git");
53
+ const dotGit = await stat(gitDir).catch(() => null);
54
+ if (!dotGit)
55
+ return undefined;
56
+ const read = (f) => readFile(f, "utf8").then((s) => s.trim(), () => undefined);
57
+ if (dotGit.isFile()) {
58
+ // A worktree or submodule: `.git` is `gitdir: <path>`.
59
+ const m = /^gitdir:\s*(.+)$/m.exec((await read(gitDir)) ?? "");
60
+ if (!m)
61
+ return undefined;
62
+ gitDir = resolve(repo, m[1].trim());
63
+ }
64
+ const head = await read(join(gitDir, "HEAD"));
65
+ if (!head)
66
+ return undefined;
67
+ if (/^[0-9a-f]{40}$/.test(head))
68
+ return head;
69
+ const ref = /^ref:\s*(.+)$/.exec(head)?.[1];
70
+ if (!ref)
71
+ return undefined;
72
+ const common = (await read(join(gitDir, "commondir"))) ?? ".";
73
+ for (const dir of [gitDir, resolve(gitDir, common)]) {
74
+ const loose = await read(join(dir, ref));
75
+ if (loose && /^[0-9a-f]{40}$/.test(loose))
76
+ return loose;
77
+ const packed = await read(join(dir, "packed-refs"));
78
+ const line = packed?.split("\n").find((l) => l.endsWith(` ${ref}`));
79
+ if (line)
80
+ return line.split(" ")[0];
81
+ }
82
+ return undefined;
83
+ }
84
+ const REPORT = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
85
+ /** The project (`<data>/project.json` in the folder store), its sources and audits, and its reports. */
86
+ export class ProjectStore {
87
+ root;
88
+ opts;
89
+ file;
90
+ reportsDir;
91
+ dataDir;
92
+ /** The reports folder as stored in pins and audits: `reports` (home) or `.spatial/reports` (repo). */
93
+ reportsRel;
94
+ ref;
95
+ constructor(root, dataDir = join(root, ".spatial"), opts = {}) {
96
+ this.root = root;
97
+ this.opts = opts;
98
+ this.ref = opts.ref ?? folderRef(dataDir, root);
99
+ this.dataDir = dataDir;
100
+ this.file = join(dataDir, "project.json");
101
+ this.reportsDir = join(dataDir, "reports");
102
+ this.reportsRel = relative(resolve(root), resolve(this.reportsDir)).split(sep).join("/");
103
+ }
104
+ /** The store for a project's data. */
105
+ static of(spatial) {
106
+ return new ProjectStore(spatial.root, spatial.dataDir, {
107
+ ...(spatial.mode === "repo" ? { fallbackName: basename(resolve(spatial.root)) } : { absoluteSources: true }),
108
+ ref: spatial.ref,
109
+ });
110
+ }
111
+ async exists() {
112
+ return (await this.ref.storage.get("project", this.ref.project, this.ref.project)) !== null;
113
+ }
114
+ async item() {
115
+ const it = await this.ref.storage.get("project", this.ref.project, this.ref.project);
116
+ if (!it) {
117
+ if (this.opts.fallbackName)
118
+ return { value: { name: this.opts.fallbackName, created: "", sources: [], audits: [] }, version: null };
119
+ throw new NotFoundError(`no project here: ${this.file} is missing (create_project or npx spatial-views new <name>)`);
120
+ }
121
+ return { value: ProjectSchema.parse(it.data), version: it.version };
122
+ }
123
+ async get() {
124
+ return (await this.item()).value;
125
+ }
126
+ async save(p, opts = {}) {
127
+ const clean = ProjectSchema.parse(p);
128
+ await this.ref.storage.put("project", this.ref.project, this.ref.project, clean, opts);
129
+ return clean;
130
+ }
131
+ /** Read, change and save, retrying if another client saved in between. */
132
+ async change(fn) {
133
+ for (let n = 1;; n++) {
134
+ const cur = await this.item();
135
+ const out = await fn(cur.value);
136
+ try {
137
+ await this.save(cur.value, { expected: cur.version });
138
+ return out;
139
+ }
140
+ catch (err) {
141
+ if (!(err instanceof ConflictError) || n >= 5)
142
+ throw err;
143
+ }
144
+ }
145
+ }
146
+ async create(name, now = new Date(), slug, rootViewId) {
147
+ if (!name.trim())
148
+ throw new UserError("a project needs a name");
149
+ if (await this.exists())
150
+ throw new UserError(`a project already exists in ${this.dataDir}`);
151
+ try {
152
+ return await this.save({ name: name.trim(), ...(slug ? { slug } : {}), created: now.toISOString(), ...(rootViewId ? { root_view_id: rootViewId } : {}), sources: [], audits: [] }, { expected: null });
153
+ }
154
+ catch (err) {
155
+ if (err instanceof ConflictError)
156
+ throw new UserError(`a project already exists in ${this.dataDir}`);
157
+ throw err;
158
+ }
159
+ }
160
+ /** Each source as a scope root: its id and where it is on this machine. */
161
+ async roots() {
162
+ return (await this.get()).sources.map((s) => ({ id: s.id, abs: resolve(this.sourcePath(s)) }));
163
+ }
164
+ /** Where a source is on this machine. */
165
+ sourcePath(s) {
166
+ return localPath(this.root, s.path);
167
+ }
168
+ async source(id) {
169
+ const p = await this.get();
170
+ const s = p.sources.find((x) => x.id === id) ?? p.sources.find((x) => x.path === id);
171
+ if (!s)
172
+ throw new NotFoundError(`no source ${id} (have: ${p.sources.map((x) => x.id).join(", ") || "none"})`);
173
+ return s;
174
+ }
175
+ /**
176
+ * Register a folder as a source. It must exist, and must not be the project
177
+ * itself or inside it, nor a drive root (`/`, `C:\`, `D:\`) or a folder that
178
+ * holds the project. Adding the same path again returns the existing source.
179
+ */
180
+ async addSource(input, now = new Date()) {
181
+ if (this.opts.absoluteSources && !isAnyAbs(input.path))
182
+ throw new UserError(`${input.path}: give the full path of the folder (c:\\git\\api or /home/me/api)`);
183
+ const abs = localPath(this.root, input.path);
184
+ if (!(await isDir(abs)))
185
+ throw new UserError(`${input.path} is not a folder (looked at ${abs})`);
186
+ const real = await realPath(abs);
187
+ if (isFsRoot(abs) || isFsRoot(real))
188
+ throw new UserError(`${input.path} is the root of a drive; a source must be a folder inside it`);
189
+ const project = await realPath(this.root);
190
+ if (isInside(project, real))
191
+ throw new UserError(`${input.path} is the project folder or inside it; a source must be outside the project`);
192
+ if (isInside(real, project) || isInside(real, await realPath(this.dataDir)))
193
+ throw new UserError(`${input.path} holds the project's own data; a source must be a folder the project only reads`);
194
+ const kind = input.kind ?? (await detectKind(abs));
195
+ const first = await this.get();
196
+ const known = await this.sourceAt(first, abs, real);
197
+ if (known)
198
+ return { source: known, added: false };
199
+ return this.change((p) => this.addTo(p, input, abs, real, kind, now));
200
+ }
201
+ /** The source that is this folder, as written or by its real path. */
202
+ async sourceAt(p, abs, real) {
203
+ for (const s of p.sources) {
204
+ const at = resolve(this.sourcePath(s));
205
+ if (samePath(at, resolve(abs)) || samePath(await realPath(at), real))
206
+ return s;
207
+ }
208
+ return undefined;
209
+ }
210
+ async addTo(p, input, abs, real, kind, now) {
211
+ const same = await this.sourceAt(p, abs, real);
212
+ if (same)
213
+ return { source: same, added: false };
214
+ let id = input.id ?? slug(lastSegment(input.path));
215
+ if (!/^[A-Za-z0-9_-]+$/.test(id))
216
+ throw new UserError(`${id}: an id is letters, digits, - and _`);
217
+ if (input.id && p.sources.some((s) => s.id === id))
218
+ throw new UserError(`a source ${id} already exists`);
219
+ for (let n = 2; p.sources.some((s) => s.id === id); n++)
220
+ id = `${slug(lastSegment(input.path))}-${n}`;
221
+ const source = {
222
+ id,
223
+ name: input.name?.trim() || lastSegment(input.path),
224
+ kind,
225
+ path: input.path.trim(),
226
+ added: now.toISOString(),
227
+ };
228
+ p.sources.push(source);
229
+ return { source, added: true };
230
+ }
231
+ /** Take a source off the project. The folder itself is not touched. */
232
+ async removeSource(ref) {
233
+ const s = await this.source(ref);
234
+ await this.change((p) => {
235
+ p.sources = p.sources.filter((x) => x.id !== s.id);
236
+ });
237
+ return s;
238
+ }
239
+ /**
240
+ * Record an audit run. Each source read by it gets its `last_audit_sha`: the
241
+ * sha given, else the repo's current commit, else the audit time (non-git).
242
+ */
243
+ async recordAudit(input, now = new Date()) {
244
+ const at = now.toISOString();
245
+ if (input.report)
246
+ this.reportName(input.report);
247
+ return this.change(async (p) => {
248
+ const ids = input.sources ?? p.sources.map((s) => s.id);
249
+ for (const id of [...ids, ...Object.keys(input.shas ?? {})])
250
+ if (!p.sources.some((s) => s.id === id))
251
+ throw new NotFoundError(`no source ${id}`);
252
+ const touched = [];
253
+ for (const s of p.sources) {
254
+ if (!ids.includes(s.id) && !input.shas?.[s.id])
255
+ continue;
256
+ s.last_audit_sha = input.shas?.[s.id] ?? (s.kind === "repo" ? await gitHead(this.sourcePath(s)) : undefined) ?? at;
257
+ touched.push(s);
258
+ }
259
+ const audit = { kind: input.kind, at, ...(input.report ? { report: this.reportRel(input.report) } : {}) };
260
+ p.audits.push(audit);
261
+ // The pre-audit fixes where the project opens (its System Overview), whatever is saved later.
262
+ if (input.root_view_id)
263
+ p.root_view_id = input.root_view_id;
264
+ return { audit, sources: touched };
265
+ });
266
+ }
267
+ /** A report's id in the store: its name without `.md`. */
268
+ reportId(name) {
269
+ return this.reportName(name).slice(0, -3);
270
+ }
271
+ reportName(name) {
272
+ let n = name.trim();
273
+ for (const pre of [`${this.reportsRel}/`, ".spatial/reports/", "reports/"])
274
+ if (n.startsWith(pre))
275
+ n = n.slice(pre.length);
276
+ n = n.replace(/\.md$/i, "");
277
+ if (!REPORT.test(n) || n.includes(".."))
278
+ throw new UserError(`${name}: a report name is letters, digits, ., - and _`);
279
+ return `${n}.md`;
280
+ }
281
+ /** The stored path of a report (`reports/<name>.md`, or `.spatial/reports/<name>.md` in a repo). */
282
+ reportRel(name) {
283
+ return `${this.reportsRel}/${this.reportName(name)}`;
284
+ }
285
+ async reportPath(name) {
286
+ return join(this.reportsDir, this.reportName(name));
287
+ }
288
+ /** Write a report into the project's reports, never anywhere else. */
289
+ async saveReport(name, markdown) {
290
+ await this.get();
291
+ await this.ref.storage.put("report", this.ref.project, this.reportId(name), markdown.endsWith("\n") ? markdown : markdown + "\n");
292
+ return this.reportRel(name);
293
+ }
294
+ /** A report's markdown, or null. */
295
+ async readReport(name) {
296
+ return (await this.ref.storage.get("report", this.ref.project, this.reportId(name)))?.data ?? null;
297
+ }
298
+ }
299
+ /** `<source_id>:<path>`: a file in a source (a drive letter like `c:\` is not one). */
300
+ const SOURCE_REF = /^([A-Za-z0-9_-]{2,}):(?![\\/]{2})(.+)$/;
301
+ /**
302
+ * Where a pinned, pointed-at or served file is, if the active project may read it.
303
+ *
304
+ * - `<source_id>:<path>` is a file in one of the project's sources (read-only):
305
+ * `docs:prd.md`, `api:src/server.ts`.
306
+ * - A full path inside a source is turned into that form.
307
+ * - A plain relative path is in the project itself: repo-relative for a
308
+ * single-repo project, or the project's own `reports/` for a home project.
309
+ *
310
+ * Symlinks and `..` are resolved before the check, so neither can reach outside.
311
+ * Anything else is refused with the list of allowed sources. Returns the stored
312
+ * form and the real absolute path.
313
+ */
314
+ export async function resolveDocPath(at, path) {
315
+ const spatial = typeof at === "string" ? new Spatial(at) : at;
316
+ const raw = path.trim();
317
+ if (!raw)
318
+ throw new UserError("a path is needed");
319
+ const store = ProjectStore.of(spatial);
320
+ const sources = await store.roots();
321
+ const own = spatial.mode === "repo" ? { id: "repo", abs: resolve(spatial.root) } : { id: "reports", abs: store.reportsDir };
322
+ const allowed = spatial.mode === "repo" ? [own, ...sources] : sources;
323
+ const inSource = async (src, rest) => {
324
+ const base = await realPath(src.abs);
325
+ const abs = resolve(base, rest.replace(/\\/g, "/").replace(/^\/+/, ""));
326
+ if (!isInside(base, abs))
327
+ throw new ScopeError(`${path} is outside source ${src.id}. Allowed: ${describeRoots(allowed)}`);
328
+ const real = await realInside(src, abs, allowed);
329
+ const rel = relative(base, real).split(/[\\/]/).join("/") || ".";
330
+ return { rel: `${src.id}:${rel}`, abs: real, source: src.id };
331
+ };
332
+ const m = SOURCE_REF.exec(raw);
333
+ if (m) {
334
+ const src = sources.find((s) => s.id === m[1]);
335
+ if (src)
336
+ return inSource(src, m[2]);
337
+ if (spatial.mode === "home")
338
+ throw new ScopeError(`${path}: no source ${m[1]}. Allowed: ${describeRoots(allowed)}`);
339
+ }
340
+ if (isAnyAbs(raw)) {
341
+ const abs = localPath(spatial.root, raw);
342
+ const hit = await rootOf(sources, abs);
343
+ if (hit)
344
+ return inSource(hit.root, hit.rel);
345
+ if (spatial.mode === "home")
346
+ throw new ScopeError(`${path} is outside the project's sources. Allowed: ${describeRoots(allowed)}`);
347
+ if (!(await rootOf([own], abs)))
348
+ throw new ScopeError(`${path} is outside the repo and the project's sources. Allowed: ${describeRoots(allowed)}`);
349
+ }
350
+ if (spatial.mode === "home") {
351
+ const rel = raw.replace(/\\/g, "/");
352
+ if (!rel.startsWith(`${store.reportsRel}/`))
353
+ throw new ScopeError(`${path}: say which source it is in, as <source_id>:<path>. Allowed: ${describeRoots(allowed)}`);
354
+ const abs = resolve(spatial.root, rel);
355
+ if (!isInside(resolve(store.reportsDir), abs))
356
+ throw new ScopeError(`${path} is outside the project's reports`);
357
+ if (spatial.storage.backend === "folder")
358
+ await realInside(own, abs, allowed);
359
+ const out = relative(resolve(spatial.root), abs).split(sep).join("/");
360
+ const name = out.slice(store.reportsRel.length + 1);
361
+ // A report is project data: read it through the store (readDoc), not from disk.
362
+ return { rel: out, abs, ...(/^[^/]+\.md$/i.test(name) ? { report: store.reportId(name) } : {}) };
363
+ }
364
+ let rel;
365
+ try {
366
+ rel = repoPath(spatial.root, raw);
367
+ }
368
+ catch {
369
+ throw new ScopeError(`${path} is outside the repo and the project's sources. Allowed: ${describeRoots(allowed)}`);
370
+ }
371
+ const abs = absPath(spatial.root, rel);
372
+ await realInside(own, abs, allowed);
373
+ return { rel, abs };
374
+ }
375
+ /**
376
+ * The text of a path from resolveDocPath: a report through the project's store,
377
+ * anything else (a file in a source, or in the repo) from where it is. Null when
378
+ * there is nothing there.
379
+ */
380
+ export async function readDoc(spatial, doc) {
381
+ if (doc.report)
382
+ return ProjectStore.of(spatial).readReport(doc.report);
383
+ if (!(await stat(doc.abs).catch(() => null))?.isFile())
384
+ return null;
385
+ return readFile(doc.abs, "utf8").catch(() => null);
386
+ }
387
+ /** Whether a path from resolveDocPath is there (a report in the store, or a file or folder on disk). */
388
+ export async function docExists(spatial, doc) {
389
+ if (doc.report)
390
+ return (await ProjectStore.of(spatial).readReport(doc.report)) !== null;
391
+ return (await stat(doc.abs).catch(() => null)) !== null;
392
+ }
@@ -0,0 +1,35 @@
1
+ import { LinkError } from "./links.js";
2
+ /** Find a View by id, or else by name (case-insensitive). */
3
+ export function resolveView(views, ref) {
4
+ const byId = views.find((v) => v.id === ref);
5
+ if (byId)
6
+ return byId;
7
+ const byName = views.filter((v) => v.name.toLowerCase() === ref.toLowerCase());
8
+ if (byName.length === 1)
9
+ return byName[0];
10
+ if (byName.length > 1)
11
+ throw new LinkError(`more than one View is named "${ref}": ${byName.map((v) => v.id).join(", ")}; use the id`);
12
+ throw new LinkError(`no View "${ref}"`);
13
+ }
14
+ /**
15
+ * Find a module by id, or else by name, across every View (or only `inView`).
16
+ * An ambiguous name is refused with the Views it is in, so the caller can say which.
17
+ */
18
+ export function resolveModule(views, ref, inView) {
19
+ const scope = inView ? [resolveView(views, inView)] : views;
20
+ const hits = [];
21
+ for (const view of scope)
22
+ for (const m of view.modules)
23
+ if (m.id === ref)
24
+ hits.push({ view, module: m });
25
+ if (hits.length === 0)
26
+ for (const view of scope)
27
+ for (const m of view.modules)
28
+ if (m.name.toLowerCase() === ref.toLowerCase())
29
+ hits.push({ view, module: m });
30
+ if (hits.length === 1)
31
+ return hits[0];
32
+ if (hits.length > 1)
33
+ throw new LinkError(`module "${ref}" is in more than one View (${hits.map((h) => h.view.id).join(", ")}); pass in_view`);
34
+ throw new LinkError(`no module "${ref}"${inView ? ` in View ${inView}` : ""}`);
35
+ }