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.
- package/README.md +201 -19
- package/dist/app/assets/{abnfDiagram-S7VZAUFO-BVgtb0Hw.js → abnfDiagram-S7VZAUFO-CFbb_Sz2.js} +1 -1
- package/dist/app/assets/{architecture-WOLXFQ4H-DxylGHqT.js → architecture-WOLXFQ4H-CsBD__5a.js} +1 -1
- package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
- package/dist/app/assets/{blockDiagram-APKKGZFW-C7fb3MCE.js → blockDiagram-APKKGZFW-BZDPbzAG.js} +1 -1
- package/dist/app/assets/{c4Diagram-KJ2TOQU5-Bkb_0fbd.js → c4Diagram-KJ2TOQU5-BilBWuq5.js} +1 -1
- package/dist/app/assets/{chunk-6MUBBAK2-DU4vZ03M.js → chunk-6MUBBAK2-BBl-4tQr.js} +1 -1
- package/dist/app/assets/{chunk-AXFCVDMN-De96BVTB.js → chunk-AXFCVDMN-BhsttQ-k.js} +1 -1
- package/dist/app/assets/{chunk-BG4553SI-J33jsRLV.js → chunk-BG4553SI-mWcPcFZr.js} +2 -2
- package/dist/app/assets/{chunk-DQASFODM-Bh85SSGO.js → chunk-DQASFODM-7FKe2gLt.js} +1 -1
- package/dist/app/assets/{chunk-HFQBQIA3-CCklgplR.js → chunk-HFQBQIA3-nXrQ08BL.js} +1 -1
- package/dist/app/assets/{chunk-KQLB2F66-B04qR8ED.js → chunk-KQLB2F66-swukhFmZ.js} +1 -1
- package/dist/app/assets/{chunk-KS47KZWR-BsqDyyAt.js → chunk-KS47KZWR-DkDkwO82.js} +1 -1
- package/dist/app/assets/{chunk-LEVMRMFU-DwxrBz2u.js → chunk-LEVMRMFU-DXH6iXv3.js} +1 -1
- package/dist/app/assets/{chunk-M57EVK23-D9YIHjps.js → chunk-M57EVK23-B-kEyOJF.js} +1 -1
- package/dist/app/assets/{chunk-OY52VR5R-WB63DeTA.js → chunk-OY52VR5R-DweG7qYw.js} +1 -1
- package/dist/app/assets/{chunk-QB3YPZ4I-cHzzKdtb.js → chunk-QB3YPZ4I-DyozK3lV.js} +1 -1
- package/dist/app/assets/{chunk-R3KSYZAL-C7rDagaa.js → chunk-R3KSYZAL-BEXCUN6J.js} +1 -1
- package/dist/app/assets/{chunk-STOXU5M4-CG6pnJtH.js → chunk-STOXU5M4-BaTlty4O.js} +1 -1
- package/dist/app/assets/{chunk-TU62E6Q5-BbcGYfy_.js → chunk-TU62E6Q5-_rcUP1Fh.js} +1 -1
- package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
- package/dist/app/assets/{chunk-X4PVCEUW-BUI1Oi3q.js → chunk-X4PVCEUW-DGxTL3kB.js} +1 -1
- package/dist/app/assets/{chunk-XXDRQBXY-DYhK5YW-.js → chunk-XXDRQBXY-C02Gpej2.js} +1 -1
- package/dist/app/assets/{classDiagram-v2-L25IHNXF-K-k5GTUn.js → classDiagram-v2-L25IHNXF-DLEBwpvk.js} +1 -1
- package/dist/app/assets/cose-bilkent-JH36ORCC-kNCXOm8k.js +1 -0
- package/dist/app/assets/cynefin-EF2NZ3EQ-6MWNLbuF.js +1 -0
- package/dist/app/assets/{cynefinDiagram-L36ESFBY-mkV33_Xx.js → cynefinDiagram-L36ESFBY-CLFstukD.js} +1 -1
- package/dist/app/assets/{d3-scale-ygdFCUH8.js → d3-scale-CaJQQYkF.js} +1 -1
- package/dist/app/assets/{dagre-SPEB5RXH-BNIymLsu.js → dagre-SPEB5RXH-BaSAny1T.js} +1 -1
- package/dist/app/assets/{diagram-3B7GL73J-CGOiolFW.js → diagram-3B7GL73J-DJNlt5Sg.js} +1 -1
- package/dist/app/assets/{diagram-DNEMPZML-DZFkHNly.js → diagram-DNEMPZML-DEHeuILB.js} +1 -1
- package/dist/app/assets/{diagram-L3MUGCDN-B42GAYLq.js → diagram-L3MUGCDN-ob5Ka2Xc.js} +1 -1
- package/dist/app/assets/{diagram-LA4NIPWU-BYuLRYId.js → diagram-LA4NIPWU-DNESzFAc.js} +1 -1
- package/dist/app/assets/{diagram-MHCOC4E2-DGzI6TJG.js → diagram-MHCOC4E2-CVi9zKjG.js} +1 -1
- package/dist/app/assets/{diagram-XPFHEONP-CTBEgDQ8.js → diagram-XPFHEONP-DInT4C7e.js} +1 -1
- package/dist/app/assets/dist-CjvHN74u.js +1 -0
- package/dist/app/assets/{ebnfDiagram-UZSYDL2S-GuMdOCvL.js → ebnfDiagram-UZSYDL2S-CRCZNsji.js} +1 -1
- package/dist/app/assets/{elk-XV6XMXQE-BpY3loT5.js → elk-XV6XMXQE-D4fsWI2l.js} +1 -1
- package/dist/app/assets/{erDiagram-EYBAPDEH-nDZ2PMGl.js → erDiagram-EYBAPDEH-YQNM5StV.js} +1 -1
- package/dist/app/assets/{eventmodeling-K75KTNOO-BN42Mgwh.js → eventmodeling-K75KTNOO-Bev08J2F.js} +1 -1
- package/dist/app/assets/flowDiagram-MALGAFMO-BhJ554DH.js +1 -0
- package/dist/app/assets/ganttDiagram-23REXITY-CkaBMYM4.js +292 -0
- package/dist/app/assets/gitGraph-VSP46ZUC-CtbZ0sIS.js +1 -0
- package/dist/app/assets/{gitGraphDiagram-STJD7YCW-CDkKLrvO.js → gitGraphDiagram-STJD7YCW-D15ZdQ-Z.js} +1 -1
- package/dist/app/assets/index-Bn6_wHEp.js +98 -0
- package/dist/app/assets/index-H-Z7MFhZ.css +1 -0
- package/dist/app/assets/info-OHQRW6UA-CfUW1XFR.js +1 -0
- package/dist/app/assets/{infoDiagram-KBXO4MBG-B92P8pjY.js → infoDiagram-KBXO4MBG-DT7LbBRQ.js} +1 -1
- package/dist/app/assets/{ishikawaDiagram-M35NCXHK-BRZsbCvK.js → ishikawaDiagram-M35NCXHK-CF51lhjB.js} +1 -1
- package/dist/app/assets/{journeyDiagram-OPLOXDXO-Bppwb1oF.js → journeyDiagram-OPLOXDXO-_36FonKk.js} +1 -1
- package/dist/app/assets/{kanban-definition-BZKZHSQY-ByD_x5cm.js → kanban-definition-BZKZHSQY-tLk_OlQ-.js} +1 -1
- package/dist/app/assets/{mermaid-parser.core-CKmnV0Md.js → mermaid-parser.core-_3Vo8x6b.js} +3 -3
- package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
- package/dist/app/assets/{mindmap-definition-I2QAS2VK-fRbUh23C.js → mindmap-definition-I2QAS2VK-BCI4HRX3.js} +1 -1
- package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
- package/dist/app/assets/{pegDiagram-FD4XPPHP-qIABf6H8.js → pegDiagram-FD4XPPHP-BOzSoNji.js} +1 -1
- package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
- package/dist/app/assets/{pieDiagram-J4AKIIQI-Bb4RBdrc.js → pieDiagram-J4AKIIQI-PlHpwT_c.js} +1 -1
- package/dist/app/assets/{quadrantDiagram-XTYBLID2-B0CpcVWE.js → quadrantDiagram-XTYBLID2-CdxZ0ael.js} +1 -1
- package/dist/app/assets/radar-ABXABTNO-DfCl8uV2.js +1 -0
- package/dist/app/assets/railroad-I3PHUGI6-4s14UyW1.js +1 -0
- package/dist/app/assets/{railroad-abnf-LNEFI6M7-BUhw7Iuo.js → railroad-abnf-LNEFI6M7-C49jJE4Y.js} +1 -1
- package/dist/app/assets/{railroad-ebnf-DWYD2UWJ-nQNF56LJ.js → railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js} +1 -1
- package/dist/app/assets/{railroad-peg-JR7BVNR7-CwvbVIo6.js → railroad-peg-JR7BVNR7-DjBPSCKV.js} +1 -1
- package/dist/app/assets/{railroadDiagram-MRQ6NCDL-Dwr-mPZL.js → railroadDiagram-MRQ6NCDL-wGcmIMqq.js} +1 -1
- package/dist/app/assets/{requirementDiagram-Y7LWUY3S-Ctv2DKJM.js → requirementDiagram-Y7LWUY3S-DprFI03z.js} +1 -1
- package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/app/assets/{sankeyDiagram-WGJFYUXA-BvKX0eIe.js → sankeyDiagram-WGJFYUXA-DygYWLTR.js} +1 -1
- package/dist/app/assets/{sequenceDiagram-5NDRBG5M-Y4YqU2Xt.js → sequenceDiagram-5NDRBG5M-BzIr2DBO.js} +1 -1
- package/dist/app/assets/{stateDiagram-v2-FJ4FJNEA-DmjIjn4u.js → stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js} +1 -1
- package/dist/app/assets/{swimlanes-UMQ2AFYF-B2O5JCjs.js → swimlanes-UMQ2AFYF-CIEH82Zt.js} +1 -1
- package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
- package/dist/app/assets/{timeline-definition-SEUHKTQE-DJJdixAI.js → timeline-definition-SEUHKTQE-BGYSqup2.js} +1 -1
- package/dist/app/assets/treeView-D4JQ5SDB-B39o1sJo.js +1 -0
- package/dist/app/assets/treemap-SAJKECNS-BoGxrUH4.js +1 -0
- package/dist/app/assets/{usecaseDiagram-AFA6YXN4-Bp8pXgvR.js → usecaseDiagram-AFA6YXN4-dy6oVOke.js} +1 -1
- package/dist/app/assets/{vennDiagram-NNMJR3RB-DYSfZMWT.js → vennDiagram-NNMJR3RB-CUyuhcAk.js} +1 -1
- package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
- package/dist/app/assets/{wardleyDiagram-S7YFUSEH-CGJ8qg76.js → wardleyDiagram-S7YFUSEH-DYtxYUHe.js} +1 -1
- package/dist/app/assets/{xychartDiagram-GGNKY7IX-CRSvraFc.js → xychartDiagram-GGNKY7IX-ClR06AlB.js} +1 -1
- package/dist/app/index.html +3 -2
- package/dist/cli/index.js +281 -53
- package/dist/core/api.js +262 -51
- package/dist/core/approvals.js +426 -0
- package/dist/core/context.js +68 -3
- package/dist/core/diff.js +156 -0
- package/dist/core/docs.js +9 -3
- package/dist/core/doctor.js +152 -0
- package/dist/core/doctypes.js +79 -0
- package/dist/core/edit.js +25 -0
- package/dist/core/flags.js +13 -0
- package/dist/core/gaps.js +7 -2
- package/dist/core/heading.js +4 -0
- package/dist/core/history.js +36 -5
- package/dist/core/home.js +345 -0
- package/dist/core/lanes.js +134 -0
- package/dist/core/launch.js +34 -0
- package/dist/core/layout.js +362 -0
- package/dist/core/newdoc.js +66 -0
- package/dist/core/open-folder.js +30 -0
- package/dist/core/openspec.js +6 -6
- package/dist/core/paths.js +71 -4
- package/dist/core/project.js +392 -0
- package/dist/core/route.js +420 -0
- package/dist/core/scan.js +514 -0
- package/dist/core/schema.js +170 -1
- package/dist/core/scope.js +126 -0
- package/dist/core/setup.js +134 -0
- package/dist/core/skills.js +92 -14
- package/dist/core/storage/config.js +74 -0
- package/dist/core/storage/events.js +54 -0
- package/dist/core/storage/folder-watch.js +147 -0
- package/dist/core/storage/folder.js +469 -0
- package/dist/core/storage/index.js +8 -0
- package/dist/core/storage/local.js +22 -0
- package/dist/core/storage/migrate.js +48 -0
- package/dist/core/storage/postgres.js +290 -0
- package/dist/core/storage/types.js +101 -0
- package/dist/core/storage.js +483 -77
- package/dist/core/suggest.js +283 -0
- package/dist/core/tree.js +254 -0
- package/dist/core/types.js +583 -0
- package/dist/core/version.js +1 -1
- package/dist/core/versions.js +245 -0
- package/dist/core/watch.js +2 -136
- package/dist/core/xml.js +23 -5
- package/dist/demo/args.js +58 -0
- package/dist/demo/browser.js +301 -0
- package/dist/demo/platform.js +147 -0
- package/dist/demo/run.js +198 -0
- package/dist/demo/steps.js +328 -0
- package/dist/mcp/project-tools.js +193 -0
- package/dist/mcp/server.js +493 -65
- package/examples/platform/README.md +33 -0
- package/examples/platform/api/package.json +8 -0
- package/examples/platform/api/src/auth-middleware.js +16 -0
- package/examples/platform/api/src/proxy.js +7 -0
- package/examples/platform/api/src/rate-limit.js +13 -0
- package/examples/platform/api/src/server.js +40 -0
- package/examples/platform/auth/package.json +9 -0
- package/examples/platform/auth/src/server.js +24 -0
- package/examples/platform/auth/src/tokens.js +19 -0
- package/examples/platform/auth/src/users.js +16 -0
- package/examples/platform/docs/api/PRD.md +10 -0
- package/examples/platform/docs/api/SDD.md +15 -0
- package/examples/platform/docs/auth/PRD.md +10 -0
- package/examples/platform/docs/auth/SDD.md +8 -0
- package/examples/platform/docs/frontend/PRD.md +18 -0
- package/examples/platform/docs/frontend/SDD.md +13 -0
- package/examples/platform/docs/pricing/PRD.md +9 -0
- package/examples/platform/docs/pricing/SDD.md +8 -0
- package/examples/platform/docs/products/PRD.md +9 -0
- package/examples/platform/docs/products/SDD.md +8 -0
- package/examples/platform/frontend/package.json +8 -0
- package/examples/platform/frontend/src/api-client.js +21 -0
- package/examples/platform/frontend/src/main.js +21 -0
- package/examples/platform/frontend/src/pages/products.js +12 -0
- package/examples/platform/frontend/src/pages/sign-in.js +14 -0
- package/examples/platform/frontend/src/session.js +11 -0
- package/examples/platform/pricing/package.json +9 -0
- package/examples/platform/pricing/src/cache.js +19 -0
- package/examples/platform/pricing/src/product-events.js +17 -0
- package/examples/platform/pricing/src/rules.js +19 -0
- package/examples/platform/pricing/src/server.js +32 -0
- package/examples/platform/products/package.json +9 -0
- package/examples/platform/products/src/catalog.js +20 -0
- package/examples/platform/products/src/events.js +11 -0
- package/examples/platform/products/src/search.js +9 -0
- package/examples/platform/products/src/server.js +31 -0
- package/migrations/postgres/001_init.sql +55 -0
- package/migrations/postgres/002_view_versions.sql +18 -0
- package/package.json +18 -2
- package/schema/approval.schema.json +173 -0
- package/schema/gap.schema.json +3 -0
- package/schema/project.schema.json +93 -0
- package/schema/settings.schema.json +86 -0
- package/schema/toolbox.schema.json +206 -0
- package/schema/type.schema.json +121 -0
- package/schema/view.schema.json +106 -0
- package/skills/claude/build-gap/SKILL.md +7 -0
- package/skills/claude/check-ui/SKILL.md +40 -0
- package/skills/claude/draw-system/SKILL.md +24 -9
- package/skills/claude/gap-from-view/SKILL.md +7 -0
- package/skills/claude/post-audit/SKILL.md +58 -0
- package/skills/claude/pre-audit/SKILL.md +82 -0
- package/skills/claude/update-state/SKILL.md +56 -0
- package/skills/cursor/check-ui.mdc +40 -0
- package/skills/cursor/draw-system.mdc +24 -9
- package/skills/cursor/post-audit.mdc +44 -0
- package/skills/cursor/pre-audit.mdc +49 -0
- package/skills/cursor/update-state.mdc +45 -0
- package/skills/windsurf/spatial-views.md +182 -36
- package/toolboxes/aws.yaml +43 -0
- package/toolboxes/azure.yaml +41 -0
- package/toolboxes/cloud.yaml +95 -0
- package/toolboxes/docs.yaml +111 -0
- package/toolboxes/software.yaml +114 -0
- package/toolboxes/types/docs/gap.yaml +15 -0
- package/toolboxes/types/docs/mdd.yaml +19 -0
- package/toolboxes/types/docs/plain.yaml +7 -0
- package/toolboxes/types/docs/prd.yaml +17 -0
- package/dist/app/assets/architectureDiagram-YGSQEFNW-BrBCHqUH.js +0 -36
- package/dist/app/assets/chunk-X3CZISLH-FMl4PpWt.js +0 -1
- package/dist/app/assets/cose-bilkent-JH36ORCC-BJmLLpaN.js +0 -1
- package/dist/app/assets/cynefin-EF2NZ3EQ-DrzwMKdm.js +0 -1
- package/dist/app/assets/dist-1Q8ng3tu.js +0 -1
- package/dist/app/assets/flowDiagram-MALGAFMO-BCwwiLzb.js +0 -1
- package/dist/app/assets/ganttDiagram-23REXITY-xMRHaU3y.js +0 -292
- package/dist/app/assets/gitGraph-VSP46ZUC-DyGq5mdd.js +0 -1
- package/dist/app/assets/index-BY66fc8Q.js +0 -95
- package/dist/app/assets/index-ByetEVbs.css +0 -1
- package/dist/app/assets/info-OHQRW6UA-DOBf-fQH.js +0 -1
- package/dist/app/assets/mermaid.core-BoRvk1Q-.js +0 -44
- package/dist/app/assets/packet-JDAUHWVQ-CgHq03Zj.js +0 -1
- package/dist/app/assets/pie-XZMESJXO-DtNh3cDE.js +0 -1
- package/dist/app/assets/radar-ABXABTNO-BS0FcsIX.js +0 -1
- package/dist/app/assets/railroad-I3PHUGI6-lO8vfGdI.js +0 -1
- package/dist/app/assets/swimlanesDiagram-OMPLPG4O-DhCl-Cjg.js +0 -8
- package/dist/app/assets/treeView-D4JQ5SDB-Dd1no4eE.js +0 -1
- package/dist/app/assets/treemap-SAJKECNS-t6wtsaki.js +0 -1
- package/dist/app/assets/wardley-7MLQ67FV-Bx60QTuu.js +0 -1
- package/skills/cursor/build-gap.mdc +0 -21
- package/skills/cursor/gap-from-view.mdc +0 -22
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { ViewWatcher, jsonId, only } from "./folder-watch.js";
|
|
5
|
+
import { checkId, ConflictError, SINGLETON_ID, TEXT_KINDS, } from "./types.js";
|
|
6
|
+
/**
|
|
7
|
+
* FolderStore (the default backend): one file per object, in today's layout.
|
|
8
|
+
*
|
|
9
|
+
* <home>/projects.json {projects: [{slug, name, created}]}
|
|
10
|
+
* <home>/projects/<slug>/
|
|
11
|
+
* project.json pins.json settings.json
|
|
12
|
+
* views/<id>.json gaps/<id>.json approvals/<id>.json toolboxes/<id>.json
|
|
13
|
+
* views/<id>/versions/<n>.json every saved version of a View
|
|
14
|
+
* reports/<name>.md
|
|
15
|
+
* doc-versions/<path, url-encoded>/<n>.json
|
|
16
|
+
* <path>.md docs, by their path in the project
|
|
17
|
+
*
|
|
18
|
+
* A single-repo project (0.1.0 `init`) is the same with `<repo>/.spatial/` as
|
|
19
|
+
* the data folder and docs at their path in the repo (FolderStore.single).
|
|
20
|
+
*
|
|
21
|
+
* Live updates come from fs.watch with a slow poll behind it (see folder-watch.ts).
|
|
22
|
+
* The only fs calls on project data are here and in folder-watch.ts.
|
|
23
|
+
*/
|
|
24
|
+
/** The file text a JSON object is saved as: 2-space JSON so it diffs cleanly. */
|
|
25
|
+
export const jsonText = (data) => JSON.stringify(data, null, 2) + "\n";
|
|
26
|
+
/** Write through a temp file then rename. */
|
|
27
|
+
export async function writeText(file, text) {
|
|
28
|
+
await mkdir(dirname(file), { recursive: true });
|
|
29
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
30
|
+
await writeFile(tmp, text, "utf8");
|
|
31
|
+
await rename(tmp, file);
|
|
32
|
+
}
|
|
33
|
+
export async function writeJson(file, data) {
|
|
34
|
+
await writeText(file, jsonText(data));
|
|
35
|
+
}
|
|
36
|
+
export async function readText(file) {
|
|
37
|
+
return readFile(file, "utf8").catch(() => null);
|
|
38
|
+
}
|
|
39
|
+
const DIRS = { view: "views", gap: "gaps", approval: "approvals", toolbox: "toolboxes" };
|
|
40
|
+
const SKIP_DIRS = new Set(["node_modules", ".git", ".spatial", ".spatial-local", ".local", "dist"]);
|
|
41
|
+
const MAX_DOCS = 5000;
|
|
42
|
+
const versionOf = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
|
|
43
|
+
export class FolderStore {
|
|
44
|
+
backend = "folder";
|
|
45
|
+
/** The home folder, or null for a single-project store. */
|
|
46
|
+
home;
|
|
47
|
+
single;
|
|
48
|
+
locks = new Map();
|
|
49
|
+
constructor(opts) {
|
|
50
|
+
if ("single" in opts) {
|
|
51
|
+
this.home = null;
|
|
52
|
+
this.single = { ...opts.single, root: opts.single.root ?? opts.single.dataDir };
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
this.home = resolve(opts.home);
|
|
56
|
+
this.single = null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** A store over one project's folder (a repo's `.spatial/`, or one home project). */
|
|
60
|
+
static single(opts) {
|
|
61
|
+
return new FolderStore({ single: opts });
|
|
62
|
+
}
|
|
63
|
+
/** The folders of one project. */
|
|
64
|
+
place(project) {
|
|
65
|
+
if (this.single) {
|
|
66
|
+
if (project !== this.single.slug)
|
|
67
|
+
throw new Error(`project ${project} is not in this folder store`);
|
|
68
|
+
return { dataDir: this.single.dataDir, docRoot: this.single.root };
|
|
69
|
+
}
|
|
70
|
+
checkId("project", project);
|
|
71
|
+
const dir = join(this.home, "projects", project);
|
|
72
|
+
return { dataDir: dir, docRoot: dir };
|
|
73
|
+
}
|
|
74
|
+
/** Whether `project` is this single-project store's project (a multi-project store has them all). */
|
|
75
|
+
holds(project) {
|
|
76
|
+
return !this.single || this.single.slug === project;
|
|
77
|
+
}
|
|
78
|
+
/** The file an object is in. */
|
|
79
|
+
file(kind, project, id) {
|
|
80
|
+
checkId(kind, id);
|
|
81
|
+
const { dataDir, docRoot } = this.place(project);
|
|
82
|
+
if (kind === "project")
|
|
83
|
+
return join(dataDir, "project.json");
|
|
84
|
+
if (SINGLETON_ID[kind])
|
|
85
|
+
return join(dataDir, `${SINGLETON_ID[kind]}.json`);
|
|
86
|
+
if (kind === "report")
|
|
87
|
+
return join(dataDir, "reports", `${id}.md`);
|
|
88
|
+
if (kind === "doc")
|
|
89
|
+
return resolve(docRoot, id);
|
|
90
|
+
if (kind === "doc_version") {
|
|
91
|
+
const at = id.lastIndexOf("@");
|
|
92
|
+
return join(dataDir, "doc-versions", encodeURIComponent(id.slice(0, at)), `${id.slice(at + 1)}.json`);
|
|
93
|
+
}
|
|
94
|
+
if (kind === "view_version") {
|
|
95
|
+
const at = id.lastIndexOf("@");
|
|
96
|
+
return join(dataDir, "views", id.slice(0, at), "versions", `${id.slice(at + 1)}.json`);
|
|
97
|
+
}
|
|
98
|
+
return join(dataDir, DIRS[kind], `${id}.json`);
|
|
99
|
+
}
|
|
100
|
+
decode(kind, text) {
|
|
101
|
+
return TEXT_KINDS.has(kind) ? text : JSON.parse(text);
|
|
102
|
+
}
|
|
103
|
+
encode(kind, data) {
|
|
104
|
+
if (TEXT_KINDS.has(kind)) {
|
|
105
|
+
if (typeof data !== "string")
|
|
106
|
+
throw new TypeError(`${kind} data is markdown text`);
|
|
107
|
+
return data;
|
|
108
|
+
}
|
|
109
|
+
return jsonText(data);
|
|
110
|
+
}
|
|
111
|
+
async readItem(kind, project, id, file) {
|
|
112
|
+
const text = await readText(file);
|
|
113
|
+
if (text === null)
|
|
114
|
+
return null;
|
|
115
|
+
const st = await stat(file).catch(() => null);
|
|
116
|
+
return {
|
|
117
|
+
kind,
|
|
118
|
+
project,
|
|
119
|
+
id,
|
|
120
|
+
data: this.decode(kind, text),
|
|
121
|
+
version: versionOf(text),
|
|
122
|
+
updated_at: st ? st.mtime.toISOString() : new Date(0).toISOString(),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async get(kind, project, id) {
|
|
126
|
+
if (!this.holds(project))
|
|
127
|
+
return null;
|
|
128
|
+
if (kind === "project" && id !== project)
|
|
129
|
+
return null;
|
|
130
|
+
return this.readItem(kind, project, id, this.file(kind, project, id));
|
|
131
|
+
}
|
|
132
|
+
async list(kind, project, opts = {}) {
|
|
133
|
+
const keep = (id) => !opts.prefix || id.startsWith(opts.prefix);
|
|
134
|
+
if (kind === "project") {
|
|
135
|
+
const slugs = this.single ? [this.single.slug] : (await this.index()).map((e) => e.slug);
|
|
136
|
+
const out = [];
|
|
137
|
+
for (const slug of slugs.filter(keep)) {
|
|
138
|
+
const hit = await this.get("project", slug, slug).catch(() => null);
|
|
139
|
+
if (hit)
|
|
140
|
+
out.push(hit);
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
if (!this.holds(project))
|
|
145
|
+
return [];
|
|
146
|
+
const ids = await this.ids(kind, project, opts.prefix);
|
|
147
|
+
const out = [];
|
|
148
|
+
for (const id of ids.filter(keep).sort()) {
|
|
149
|
+
try {
|
|
150
|
+
const hit = await this.get(kind, project, id);
|
|
151
|
+
if (hit)
|
|
152
|
+
out.push(hit);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
// A broken file is left alone; it must not hide the others.
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
async listIds(kind, project, opts = {}) {
|
|
161
|
+
if (kind === "project")
|
|
162
|
+
return (await this.list(kind, project, opts)).map((x) => x.id);
|
|
163
|
+
if (!this.holds(project))
|
|
164
|
+
return [];
|
|
165
|
+
return (await this.ids(kind, project, opts.prefix)).filter((id) => !opts.prefix || id.startsWith(opts.prefix)).sort();
|
|
166
|
+
}
|
|
167
|
+
async ids(kind, project, prefix) {
|
|
168
|
+
const { dataDir, docRoot } = this.place(project);
|
|
169
|
+
const ls = (d) => readdir(d).catch(() => []);
|
|
170
|
+
if (SINGLETON_ID[kind])
|
|
171
|
+
return (await stat(join(dataDir, `${SINGLETON_ID[kind]}.json`)).catch(() => null)) ? [SINGLETON_ID[kind]] : [];
|
|
172
|
+
if (kind === "report")
|
|
173
|
+
return (await ls(join(dataDir, "reports"))).filter((f) => f.endsWith(".md")).map((f) => f.slice(0, -3));
|
|
174
|
+
if (kind === "doc_version") {
|
|
175
|
+
const base = join(dataDir, "doc-versions");
|
|
176
|
+
const at = prefix?.lastIndexOf("@") ?? -1;
|
|
177
|
+
const docs = prefix && at > 0 ? [encodeURIComponent(prefix.slice(0, at))] : await ls(base);
|
|
178
|
+
const out = [];
|
|
179
|
+
for (const d of docs)
|
|
180
|
+
for (const f of await ls(join(base, d)))
|
|
181
|
+
if (/^\d+\.json$/.test(f))
|
|
182
|
+
out.push(`${decodeURIComponent(d)}@${f.slice(0, -5)}`);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
if (kind === "view_version") {
|
|
186
|
+
const base = join(dataDir, "views");
|
|
187
|
+
const at = prefix?.lastIndexOf("@") ?? -1;
|
|
188
|
+
const views = prefix && at > 0 ? [prefix.slice(0, at)] : (await readdir(base, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
189
|
+
const out = [];
|
|
190
|
+
for (const v of views)
|
|
191
|
+
for (const f of await ls(join(base, v, "versions")))
|
|
192
|
+
if (/^\d+\.json$/.test(f))
|
|
193
|
+
out.push(`${v}@${f.slice(0, -5)}`);
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
if (kind === "doc") {
|
|
197
|
+
const out = [];
|
|
198
|
+
const walk = async (rel) => {
|
|
199
|
+
const entries = await readdir(join(docRoot, rel), { withFileTypes: true }).catch(() => []);
|
|
200
|
+
for (const e of entries) {
|
|
201
|
+
if (out.length >= MAX_DOCS)
|
|
202
|
+
return;
|
|
203
|
+
const p = rel ? `${rel}/${e.name}` : e.name;
|
|
204
|
+
if (e.isDirectory() && !SKIP_DIRS.has(e.name))
|
|
205
|
+
await walk(p);
|
|
206
|
+
else if (e.isFile() && e.name.toLowerCase().endsWith(".md"))
|
|
207
|
+
out.push(p);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
await walk("");
|
|
211
|
+
// The data folder's own files are not docs (a repo's .spatial/ is skipped by name).
|
|
212
|
+
const own = relative(resolve(docRoot), resolve(dataDir)).split(sep).join("/");
|
|
213
|
+
const skip = (own ? [own] : []).concat(own ? [] : ["reports", "doc-versions"]);
|
|
214
|
+
return out.filter((p) => !skip.some((d) => p.startsWith(`${d}/`)));
|
|
215
|
+
}
|
|
216
|
+
return (await ls(join(dataDir, DIRS[kind]))).map(jsonId).filter((x) => x !== null);
|
|
217
|
+
}
|
|
218
|
+
// ---- Writes ----------------------------------------------------------------------
|
|
219
|
+
/** One writer per file in this process, and a lock file across processes. */
|
|
220
|
+
async locked(files, fn) {
|
|
221
|
+
const keys = [...new Set(files)].sort();
|
|
222
|
+
const prev = Promise.all(keys.map((k) => this.locks.get(k)));
|
|
223
|
+
const run = prev.then(async () => {
|
|
224
|
+
const held = [];
|
|
225
|
+
try {
|
|
226
|
+
for (const f of keys)
|
|
227
|
+
held.push(await lockFile(f));
|
|
228
|
+
return await fn();
|
|
229
|
+
}
|
|
230
|
+
finally {
|
|
231
|
+
for (const h of held)
|
|
232
|
+
await rm(h, { force: true }).catch(() => undefined);
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
const settled = run.catch(() => undefined);
|
|
236
|
+
for (const k of keys)
|
|
237
|
+
this.locks.set(k, settled);
|
|
238
|
+
void settled.then(() => {
|
|
239
|
+
for (const k of keys)
|
|
240
|
+
if (this.locks.get(k) === settled)
|
|
241
|
+
this.locks.delete(k);
|
|
242
|
+
});
|
|
243
|
+
return run;
|
|
244
|
+
}
|
|
245
|
+
async check(kind, project, id, file, expected) {
|
|
246
|
+
if (expected === undefined)
|
|
247
|
+
return;
|
|
248
|
+
const text = await readText(file);
|
|
249
|
+
const have = text === null ? null : versionOf(text);
|
|
250
|
+
if (have !== expected)
|
|
251
|
+
throw new ConflictError(kind, project, id);
|
|
252
|
+
}
|
|
253
|
+
async put(kind, project, id, data, opts = {}) {
|
|
254
|
+
if (kind === "project" && id !== project)
|
|
255
|
+
throw new TypeError("a project's id is its slug");
|
|
256
|
+
const file = this.file(kind, project, id);
|
|
257
|
+
const text = this.encode(kind, data);
|
|
258
|
+
await this.locked([file], async () => {
|
|
259
|
+
await this.check(kind, project, id, file, opts.expected);
|
|
260
|
+
await writeText(file, text);
|
|
261
|
+
if (kind === "project")
|
|
262
|
+
await this.indexPut(project, data);
|
|
263
|
+
});
|
|
264
|
+
return { kind, project, id, data, version: versionOf(text), updated_at: new Date().toISOString(), ...(opts.by ? { updated_by: opts.by } : {}) };
|
|
265
|
+
}
|
|
266
|
+
async delete(kind, project, id, opts = {}) {
|
|
267
|
+
if (!this.holds(project))
|
|
268
|
+
return false;
|
|
269
|
+
const file = this.file(kind, project, id);
|
|
270
|
+
return this.locked([file], async () => {
|
|
271
|
+
await this.check(kind, project, id, file, opts.expected);
|
|
272
|
+
const had = (await stat(file).catch(() => null)) !== null;
|
|
273
|
+
if (had)
|
|
274
|
+
await rm(file);
|
|
275
|
+
if (kind === "project")
|
|
276
|
+
await this.indexDelete(project);
|
|
277
|
+
return had;
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* All or nothing: every expected version is checked first, every new file is
|
|
282
|
+
* written beside its target, then they are swapped in; if a swap fails, every
|
|
283
|
+
* file already swapped is put back.
|
|
284
|
+
*/
|
|
285
|
+
async transact(ops) {
|
|
286
|
+
if (!ops.length)
|
|
287
|
+
return;
|
|
288
|
+
const steps = ops.map((o) => {
|
|
289
|
+
return { o, file: this.file(o.kind, o.project, o.id), text: o.op === "put" ? this.encode(o.kind, o.data) : null };
|
|
290
|
+
});
|
|
291
|
+
if (new Set(steps.map((s) => s.file)).size !== steps.length)
|
|
292
|
+
throw new TypeError("one write per object in a transaction");
|
|
293
|
+
await this.locked(steps.map((s) => s.file), async () => {
|
|
294
|
+
for (const s of steps)
|
|
295
|
+
await this.check(s.o.kind, s.o.project, s.o.id, s.file, s.o.expected);
|
|
296
|
+
const tag = `${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
|
|
297
|
+
const backups = [];
|
|
298
|
+
const temps = [];
|
|
299
|
+
try {
|
|
300
|
+
for (const s of steps) {
|
|
301
|
+
if (s.text === null)
|
|
302
|
+
continue;
|
|
303
|
+
const tmp = `${s.file}.${tag}.tmp`;
|
|
304
|
+
await mkdir(dirname(s.file), { recursive: true });
|
|
305
|
+
await writeFile(tmp, s.text, "utf8");
|
|
306
|
+
temps.push(tmp);
|
|
307
|
+
}
|
|
308
|
+
for (const s of steps) {
|
|
309
|
+
const old = await readText(s.file);
|
|
310
|
+
backups.push({ file: s.file, old });
|
|
311
|
+
if (s.text === null) {
|
|
312
|
+
if (old !== null)
|
|
313
|
+
await rm(s.file);
|
|
314
|
+
}
|
|
315
|
+
else
|
|
316
|
+
await rename(`${s.file}.${tag}.tmp`, s.file);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
catch (err) {
|
|
320
|
+
for (const b of backups.reverse()) {
|
|
321
|
+
if (b.old === null)
|
|
322
|
+
await rm(b.file, { force: true }).catch(() => undefined);
|
|
323
|
+
else
|
|
324
|
+
await writeText(b.file, b.old).catch(() => undefined);
|
|
325
|
+
}
|
|
326
|
+
for (const t of temps)
|
|
327
|
+
await rm(t, { force: true }).catch(() => undefined);
|
|
328
|
+
throw err;
|
|
329
|
+
}
|
|
330
|
+
for (const s of steps) {
|
|
331
|
+
if (s.o.kind !== "project")
|
|
332
|
+
continue;
|
|
333
|
+
if (s.o.op === "put")
|
|
334
|
+
await this.indexPut(s.o.project, s.o.data);
|
|
335
|
+
else
|
|
336
|
+
await this.indexDelete(s.o.project);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
// ---- projects.json -------------------------------------------------------------
|
|
341
|
+
get indexFile() {
|
|
342
|
+
return this.home ? join(this.home, "projects.json") : null;
|
|
343
|
+
}
|
|
344
|
+
async index() {
|
|
345
|
+
if (!this.indexFile)
|
|
346
|
+
return [];
|
|
347
|
+
const raw = await readText(this.indexFile);
|
|
348
|
+
if (!raw)
|
|
349
|
+
return [];
|
|
350
|
+
try {
|
|
351
|
+
const data = JSON.parse(raw);
|
|
352
|
+
return Array.isArray(data.projects) ? data.projects : [];
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
async indexPut(slug, data) {
|
|
359
|
+
if (!this.indexFile)
|
|
360
|
+
return;
|
|
361
|
+
const p = (data ?? {});
|
|
362
|
+
await this.locked([this.indexFile], async () => {
|
|
363
|
+
const all = await this.index();
|
|
364
|
+
const entry = { slug, name: p.name ?? slug, created: p.created ?? "" };
|
|
365
|
+
const at = all.findIndex((e) => e.slug === slug);
|
|
366
|
+
if (at >= 0 && all[at].name === entry.name && all[at].created === entry.created)
|
|
367
|
+
return;
|
|
368
|
+
if (at >= 0)
|
|
369
|
+
all[at] = entry;
|
|
370
|
+
else
|
|
371
|
+
all.push(entry);
|
|
372
|
+
await writeJson(this.indexFile, { projects: all });
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
async indexDelete(slug) {
|
|
376
|
+
if (!this.indexFile)
|
|
377
|
+
return;
|
|
378
|
+
await this.locked([this.indexFile], async () => {
|
|
379
|
+
const all = await this.index();
|
|
380
|
+
if (all.some((e) => e.slug === slug))
|
|
381
|
+
await writeJson(this.indexFile, { projects: all.filter((e) => e.slug !== slug) });
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
// ---- Watch -----------------------------------------------------------------------
|
|
385
|
+
/** The watcher channels of one project's data folder. */
|
|
386
|
+
channels(project) {
|
|
387
|
+
const { dataDir } = this.place(project);
|
|
388
|
+
return [
|
|
389
|
+
{ type: "view", dir: join(dataDir, "views"), match: jsonId },
|
|
390
|
+
{ type: "gap", dir: join(dataDir, "gaps"), match: jsonId },
|
|
391
|
+
{ type: "approval", dir: join(dataDir, "approvals"), match: jsonId },
|
|
392
|
+
{ type: "toolbox", dir: join(dataDir, "toolboxes"), match: jsonId },
|
|
393
|
+
{ type: "pins", dir: dataDir, match: only("pins.json", "pins") },
|
|
394
|
+
{ type: "settings", dir: dataDir, match: only("settings.json", "settings") },
|
|
395
|
+
{ type: "project", dir: dataDir, match: only("project.json", project) },
|
|
396
|
+
{ type: "report", dir: join(dataDir, "reports"), match: (f) => (f.endsWith(".md") ? f.slice(0, -3) : null) },
|
|
397
|
+
// Docs live in the repo, anywhere: every write keeps a version, so a doc's versions folder changes with it.
|
|
398
|
+
{ type: "doc", dir: join(dataDir, "doc-versions"), match: docVersionsId },
|
|
399
|
+
];
|
|
400
|
+
}
|
|
401
|
+
watch(project, fn, pollMs) {
|
|
402
|
+
const watchers = new Map();
|
|
403
|
+
let closed = false;
|
|
404
|
+
const add = (slug) => {
|
|
405
|
+
if (closed || watchers.has(slug))
|
|
406
|
+
return watchers.get(slug).whenReady();
|
|
407
|
+
const w = new ViewWatcher(this.channels(slug), pollMs);
|
|
408
|
+
w.subscribe((e) => fn({ kind: e.type, project: slug, id: e.id, removed: e.removed }));
|
|
409
|
+
watchers.set(slug, w);
|
|
410
|
+
return w.whenReady();
|
|
411
|
+
};
|
|
412
|
+
let index = null;
|
|
413
|
+
let ready;
|
|
414
|
+
if (project !== null || this.single) {
|
|
415
|
+
ready = add(project ?? this.single.slug).then(() => undefined);
|
|
416
|
+
}
|
|
417
|
+
else {
|
|
418
|
+
// Every project: watch the index, and each project in it.
|
|
419
|
+
index = new ViewWatcher([{ type: "project", dir: this.home, match: only("projects.json", "*") }], pollMs);
|
|
420
|
+
index.subscribe(() => void this.index().then((all) => all.forEach((e) => void add(e.slug))));
|
|
421
|
+
ready = Promise.all([index.whenReady(), this.index().then((all) => Promise.all(all.map((e) => add(e.slug))))]).then(() => undefined);
|
|
422
|
+
}
|
|
423
|
+
return {
|
|
424
|
+
ready,
|
|
425
|
+
close: () => {
|
|
426
|
+
closed = true;
|
|
427
|
+
index?.close();
|
|
428
|
+
for (const w of watchers.values())
|
|
429
|
+
w.close();
|
|
430
|
+
watchers.clear();
|
|
431
|
+
},
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
async close() {
|
|
435
|
+
// Nothing held open: watches are closed by their owners.
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
/** Take `<file>.lock` (create-exclusive), waiting for another process's; a lock older than 10s is stale. */
|
|
439
|
+
async function lockFile(file) {
|
|
440
|
+
const lock = `${file}.lock`;
|
|
441
|
+
await mkdir(dirname(file), { recursive: true });
|
|
442
|
+
for (let n = 0;; n++) {
|
|
443
|
+
try {
|
|
444
|
+
const h = await open(lock, "wx");
|
|
445
|
+
await h.close();
|
|
446
|
+
return lock;
|
|
447
|
+
}
|
|
448
|
+
catch (err) {
|
|
449
|
+
if (err.code !== "EEXIST")
|
|
450
|
+
throw err;
|
|
451
|
+
const st = await stat(lock).catch(() => null);
|
|
452
|
+
if (st && Date.now() - st.mtimeMs > 10_000)
|
|
453
|
+
await rm(lock, { force: true }).catch(() => undefined);
|
|
454
|
+
else if (n > 400)
|
|
455
|
+
throw new Error(`${file} is locked by another process`);
|
|
456
|
+
else
|
|
457
|
+
await new Promise((r) => setTimeout(r, 5 + Math.random() * 10));
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
/** A doc's path from its versions folder's name (doc-versions/<encoded path>/). */
|
|
462
|
+
function docVersionsId(name) {
|
|
463
|
+
try {
|
|
464
|
+
return decodeURIComponent(name);
|
|
465
|
+
}
|
|
466
|
+
catch {
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Storage backends: the interface, the folder and Postgres stores, config and migrate. */
|
|
2
|
+
export * from "./types.js";
|
|
3
|
+
export { FolderStore, jsonText, readText, writeJson, writeText } from "./folder.js";
|
|
4
|
+
export { PostgresStore, describeUrl, migrate, MIGRATIONS_DIR } from "./postgres.js";
|
|
5
|
+
export { openStorage, readStorageConfig, storageInfo, writeStorageConfig, configFile, StorageKindSchema } from "./config.js";
|
|
6
|
+
export { census, migrateStore } from "./migrate.js";
|
|
7
|
+
export { ProjectEvents } from "./events.js";
|
|
8
|
+
export { readOpen, writeOpen, openFile } from "./local.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { readText, writeJson } from "./folder.js";
|
|
3
|
+
/**
|
|
4
|
+
* The never-committed, per-machine UI hand-off: open_view writes `<local>/open.json`
|
|
5
|
+
* and the canvas on this machine follows it. It is not project data, so it stays
|
|
6
|
+
* a local file whichever backend holds the project.
|
|
7
|
+
*/
|
|
8
|
+
export const openFile = (localDir) => join(localDir, "open.json");
|
|
9
|
+
export async function writeOpen(localDir, viewId, now = new Date()) {
|
|
10
|
+
await writeJson(openFile(localDir), { view_id: viewId, at: now.toISOString() });
|
|
11
|
+
}
|
|
12
|
+
export async function readOpen(localDir) {
|
|
13
|
+
const raw = await readText(openFile(localDir));
|
|
14
|
+
if (!raw)
|
|
15
|
+
return {};
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(raw);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { UserError } from "../errors.js";
|
|
3
|
+
import { canonical, KINDS } from "./types.js";
|
|
4
|
+
/** The kinds held inside a project (everything but the project itself). */
|
|
5
|
+
const INNER = KINDS.filter((k) => k !== "project");
|
|
6
|
+
function digest(items) {
|
|
7
|
+
const h = createHash("sha256");
|
|
8
|
+
for (const line of items.map((i) => `${i.id}\t${canonical(i.data)}`).sort())
|
|
9
|
+
h.update(line).update("\n");
|
|
10
|
+
return h.digest("hex");
|
|
11
|
+
}
|
|
12
|
+
/** Per kind: how many objects one project holds, and a hash of them all. */
|
|
13
|
+
export async function census(store, slug) {
|
|
14
|
+
const out = [];
|
|
15
|
+
for (const kind of KINDS) {
|
|
16
|
+
const items = kind === "project" ? (await store.list("project", slug)).filter((p) => p.id === slug) : await store.list(kind, slug);
|
|
17
|
+
out.push({ kind, count: items.length, hash: digest(items) });
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
export async function migrateStore(source, target, opts = {}) {
|
|
22
|
+
if (source === target)
|
|
23
|
+
throw new UserError("the source and the target are the same store");
|
|
24
|
+
const projects = await source.list("project", "");
|
|
25
|
+
const there = new Set((await target.list("project", "")).map((p) => p.id));
|
|
26
|
+
const clash = projects.filter((p) => there.has(p.id)).map((p) => p.id);
|
|
27
|
+
if (clash.length)
|
|
28
|
+
throw new UserError(`the target already has ${clash.join(", ")}; nothing copied (it is never overwritten)`);
|
|
29
|
+
const report = { projects: [], total: 0 };
|
|
30
|
+
for (const p of projects) {
|
|
31
|
+
opts.onProject?.(p.id);
|
|
32
|
+
const ops = [];
|
|
33
|
+
for (const kind of INNER)
|
|
34
|
+
for (const it of await source.list(kind, p.id))
|
|
35
|
+
ops.push({ op: "put", kind, project: p.id, id: it.id, data: it.data, expected: null });
|
|
36
|
+
// The project row last: until it is there, the project is not listed.
|
|
37
|
+
ops.push({ op: "put", kind: "project", project: p.id, id: p.id, data: p.data, expected: null });
|
|
38
|
+
await target.transact(ops, opts.by ? { by: opts.by } : {});
|
|
39
|
+
const want = await census(source, p.id);
|
|
40
|
+
const got = await census(target, p.id);
|
|
41
|
+
const bad = want.filter((w, i) => w.count !== got[i].count || w.hash !== got[i].hash);
|
|
42
|
+
if (bad.length)
|
|
43
|
+
throw new UserError(`verify failed for ${p.id}: ${bad.map((b) => `${b.kind} (${b.count} in the source, ${got.find((g) => g.kind === b.kind).count} copied)`).join(", ")}`);
|
|
44
|
+
report.projects.push({ slug: p.id, kinds: want });
|
|
45
|
+
report.total += ops.length;
|
|
46
|
+
}
|
|
47
|
+
return report;
|
|
48
|
+
}
|