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.
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/dist/app/assets/abnfDiagram-S7VZAUFO-CFbb_Sz2.js +1 -0
- package/dist/app/assets/architecture-WOLXFQ4H-CsBD__5a.js +1 -0
- package/dist/app/assets/architectureDiagram-YGSQEFNW-C0ic4ib1.js +36 -0
- package/dist/app/assets/blockDiagram-APKKGZFW-BZDPbzAG.js +140 -0
- package/dist/app/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +1 -0
- package/dist/app/assets/c4Diagram-KJ2TOQU5-BilBWuq5.js +38 -0
- package/dist/app/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/app/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/dist/app/assets/chunk-6MUBBAK2-BBl-4tQr.js +2 -0
- package/dist/app/assets/chunk-AXFCVDMN-BhsttQ-k.js +62 -0
- package/dist/app/assets/chunk-BG4553SI-mWcPcFZr.js +127 -0
- package/dist/app/assets/chunk-DQASFODM-7FKe2gLt.js +10 -0
- package/dist/app/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/dist/app/assets/chunk-HFQBQIA3-nXrQ08BL.js +1 -0
- package/dist/app/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/dist/app/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/app/assets/chunk-KQLB2F66-swukhFmZ.js +2 -0
- package/dist/app/assets/chunk-KS47KZWR-DkDkwO82.js +1 -0
- package/dist/app/assets/chunk-LEVMRMFU-DXH6iXv3.js +1 -0
- package/dist/app/assets/chunk-M57EVK23-B-kEyOJF.js +1 -0
- package/dist/app/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
- package/dist/app/assets/chunk-OY52VR5R-DweG7qYw.js +88 -0
- package/dist/app/assets/chunk-QB3YPZ4I-DyozK3lV.js +213 -0
- package/dist/app/assets/chunk-R3KSYZAL-BEXCUN6J.js +1 -0
- package/dist/app/assets/chunk-STOXU5M4-BaTlty4O.js +72 -0
- package/dist/app/assets/chunk-TU62E6Q5-_rcUP1Fh.js +1 -0
- package/dist/app/assets/chunk-X3CZISLH-NOpCnvgE.js +1 -0
- package/dist/app/assets/chunk-X4PVCEUW-DGxTL3kB.js +1 -0
- package/dist/app/assets/chunk-XXDRQBXY-C02Gpej2.js +1 -0
- package/dist/app/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/app/assets/classDiagram-v2-L25IHNXF-DLEBwpvk.js +217 -0
- 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-CLFstukD.js +62 -0
- package/dist/app/assets/cytoscape.esm-nTrd5EVq.js +321 -0
- package/dist/app/assets/d3-scale-CaJQQYkF.js +1 -0
- package/dist/app/assets/dagre-SPEB5RXH-BaSAny1T.js +4 -0
- package/dist/app/assets/diagram-3B7GL73J-DJNlt5Sg.js +200 -0
- package/dist/app/assets/diagram-DNEMPZML-DEHeuILB.js +24 -0
- package/dist/app/assets/diagram-L3MUGCDN-ob5Ka2Xc.js +41 -0
- package/dist/app/assets/diagram-LA4NIPWU-DNESzFAc.js +24 -0
- package/dist/app/assets/diagram-MHCOC4E2-CVi9zKjG.js +3 -0
- package/dist/app/assets/diagram-XPFHEONP-DInT4C7e.js +30 -0
- package/dist/app/assets/dist-CjvHN74u.js +1 -0
- package/dist/app/assets/ebnfDiagram-UZSYDL2S-CRCZNsji.js +1 -0
- package/dist/app/assets/elk-XV6XMXQE-D4fsWI2l.js +2 -0
- package/dist/app/assets/erDiagram-EYBAPDEH-YQNM5StV.js +99 -0
- package/dist/app/assets/eventmodeling-K75KTNOO-Bev08J2F.js +1 -0
- 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-D15ZdQ-Z.js +106 -0
- package/dist/app/assets/graphlib-DS17s2tU.js +1 -0
- 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-DT7LbBRQ.js +2 -0
- package/dist/app/assets/ishikawaDiagram-M35NCXHK-CF51lhjB.js +70 -0
- package/dist/app/assets/journeyDiagram-OPLOXDXO-_36FonKk.js +139 -0
- package/dist/app/assets/kanban-definition-BZKZHSQY-tLk_OlQ-.js +89 -0
- package/dist/app/assets/katex-MEuSR36T.js +257 -0
- package/dist/app/assets/mermaid-parser.core-_3Vo8x6b.js +7 -0
- package/dist/app/assets/mermaid.core-y-x1CYxC.js +44 -0
- package/dist/app/assets/mindmap-definition-I2QAS2VK-BCI4HRX3.js +98 -0
- package/dist/app/assets/packet-JDAUHWVQ-Cco3UoaI.js +1 -0
- package/dist/app/assets/pegDiagram-FD4XPPHP-BOzSoNji.js +1 -0
- package/dist/app/assets/pie-XZMESJXO-reOB2GXn.js +1 -0
- package/dist/app/assets/pieDiagram-J4AKIIQI-PlHpwT_c.js +39 -0
- package/dist/app/assets/quadrantDiagram-XTYBLID2-CdxZ0ael.js +7 -0
- 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-C49jJE4Y.js +1 -0
- package/dist/app/assets/railroad-ebnf-DWYD2UWJ-Bx-pcPc7.js +1 -0
- package/dist/app/assets/railroad-peg-JR7BVNR7-DjBPSCKV.js +1 -0
- package/dist/app/assets/railroadDiagram-MRQ6NCDL-wGcmIMqq.js +1 -0
- package/dist/app/assets/requirementDiagram-Y7LWUY3S-DprFI03z.js +84 -0
- package/dist/app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/app/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/app/assets/sankeyDiagram-WGJFYUXA-DygYWLTR.js +40 -0
- package/dist/app/assets/sequenceDiagram-5NDRBG5M-BzIr2DBO.js +169 -0
- package/dist/app/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
- package/dist/app/assets/stateDiagram-v2-FJ4FJNEA-MGCqKnm_.js +291 -0
- package/dist/app/assets/swimlanes-UMQ2AFYF-CIEH82Zt.js +1 -0
- package/dist/app/assets/swimlanesDiagram-OMPLPG4O-YWNJjl0g.js +8 -0
- package/dist/app/assets/timeline-definition-SEUHKTQE-BGYSqup2.js +120 -0
- 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-dy6oVOke.js +328 -0
- package/dist/app/assets/vennDiagram-NNMJR3RB-CUyuhcAk.js +34 -0
- package/dist/app/assets/wardley-7MLQ67FV-sYPAvQ06.js +1 -0
- package/dist/app/assets/wardleyDiagram-S7YFUSEH-DYtxYUHe.js +78 -0
- package/dist/app/assets/xychartDiagram-GGNKY7IX-ClR06AlB.js +7 -0
- package/dist/app/index.html +14 -0
- package/dist/cli/index.js +338 -0
- package/dist/core/api.js +420 -0
- package/dist/core/approvals.js +426 -0
- package/dist/core/context.js +259 -0
- package/dist/core/diff.js +156 -0
- package/dist/core/docs.js +140 -0
- package/dist/core/doctor.js +152 -0
- package/dist/core/doctypes.js +79 -0
- package/dist/core/edit.js +130 -0
- package/dist/core/errors.js +3 -0
- package/dist/core/flags.js +13 -0
- package/dist/core/gaps.js +119 -0
- package/dist/core/heading.js +4 -0
- package/dist/core/history.js +50 -0
- 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/links.js +68 -0
- package/dist/core/mermaid.js +175 -0
- package/dist/core/newdoc.js +66 -0
- package/dist/core/open-folder.js +30 -0
- package/dist/core/openspec.js +120 -0
- package/dist/core/paths.js +90 -0
- package/dist/core/project.js +392 -0
- package/dist/core/resolve.js +35 -0
- package/dist/core/route.js +420 -0
- package/dist/core/scan.js +514 -0
- package/dist/core/schema.js +270 -0
- package/dist/core/scope.js +126 -0
- package/dist/core/setup.js +134 -0
- package/dist/core/skills.js +181 -0
- 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 +589 -0
- 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 -0
- package/dist/core/versions.js +245 -0
- package/dist/core/watch.js +2 -0
- package/dist/core/xml.js +68 -0
- 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 +785 -0
- 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 +69 -4
- package/schema/approval.schema.json +173 -0
- package/schema/gap.schema.json +56 -0
- package/schema/pins.schema.json +122 -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 +240 -0
- package/skills/claude/build-gap/SKILL.md +28 -0
- package/skills/claude/check-ui/SKILL.md +40 -0
- package/skills/claude/draw-system/SKILL.md +38 -0
- package/skills/claude/gap-from-view/SKILL.md +29 -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 +38 -0
- 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 +212 -0
- 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
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { isMap, isSeq, LineCounter, parseDocument, stringify } from "yaml";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { UserError } from "./errors.js";
|
|
8
|
+
/**
|
|
9
|
+
* Toolboxes, in YAML: one file per toolbox (`toolboxes/<id>.yaml`), holding its
|
|
10
|
+
* module types and doc types. Each toolbox is one icon on the canvas's
|
|
11
|
+
* right-hand bar.
|
|
12
|
+
*
|
|
13
|
+
* Load order (later files override or extend earlier ones, by id):
|
|
14
|
+
* 1. built-in: the package's toolboxes/ (Software, Cloud, AWS, Azure, Docs)
|
|
15
|
+
* 2. user: ~/SpatialViews/toolboxes/*.yaml (SPATIAL_VIEWS_HOME moves it)
|
|
16
|
+
* 3. project: <project>/toolboxes/*.yaml (the project's data folder: .spatial/ in a repo)
|
|
17
|
+
*
|
|
18
|
+
* A later file with the same toolbox id changes only the fields it gives; a
|
|
19
|
+
* type with the same id (in that toolbox) likewise. So a user file with
|
|
20
|
+
* `id: aws` and `types: [{ id: aws-ec2, icon: ./icons/ec2.svg }]` swaps one icon.
|
|
21
|
+
* An icon is `lucide:<name>` (lucide.dev/icons) or `./icons/<file>.svg`,
|
|
22
|
+
* relative to the YAML file. People and the AI (list_toolboxes, list_types,
|
|
23
|
+
* create_type, create_toolbox) see the same toolboxes.
|
|
24
|
+
*/
|
|
25
|
+
const Id = z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, "an id is lower-case letters, digits, - and _");
|
|
26
|
+
/** The colour tokens a type can use (the canvas maps each to a light and a dark colour). */
|
|
27
|
+
export const COLOR_TOKENS = ["slate", "gray", "blue", "indigo", "violet", "pink", "red", "orange", "amber", "green", "teal", "cyan"];
|
|
28
|
+
export const ColorTokenSchema = z.enum(COLOR_TOKENS);
|
|
29
|
+
/** `lucide:<name>`, `./icons/<file>.svg` (next to the YAML), or a bare lucide name. */
|
|
30
|
+
export const IconSchema = z
|
|
31
|
+
.string()
|
|
32
|
+
.regex(/^(lucide:[a-z0-9]+(-[a-z0-9]+)*|\.\/([A-Za-z0-9_ -]+\/)*[A-Za-z0-9_ .-]+\.svg|[a-z0-9]+(-[a-z0-9]+)*)$/, "an icon is lucide:<name> (lucide.dev/icons) or ./icons/<file>.svg")
|
|
33
|
+
.refine((s) => !s.split("/").includes(".."), "an icon file is inside the toolbox's folder (no ..)")
|
|
34
|
+
.describe("lucide:<name> (https://lucide.dev/icons), or ./icons/<file>.svg relative to this YAML file");
|
|
35
|
+
/** The tiers, top to bottom (see ModuleTypeSchema.tier). */
|
|
36
|
+
export const TIERS = ["client", "frontend", "edge", "api", "service", "worker", "data"];
|
|
37
|
+
export const TIER_MAX = TIERS.length - 1;
|
|
38
|
+
export const PropertyTypeSchema = z.enum(["string", "text", "number", "boolean", "enum", "url"]);
|
|
39
|
+
export const PropertyValueSchema = z.union([z.string(), z.number(), z.boolean()]);
|
|
40
|
+
export const PropertyDefSchema = z
|
|
41
|
+
.object({
|
|
42
|
+
name: z.string().regex(/^[a-z][a-z0-9_]*$/, "a property name is lower_snake_case"),
|
|
43
|
+
label: z.string().optional(),
|
|
44
|
+
type: PropertyTypeSchema.default("string"),
|
|
45
|
+
default: PropertyValueSchema.optional(),
|
|
46
|
+
/** The choices, for type enum. */
|
|
47
|
+
options: z.array(z.string()).optional(),
|
|
48
|
+
})
|
|
49
|
+
.strict();
|
|
50
|
+
export const SizeSchema = z.object({ w: z.number().min(60).max(600), h: z.number().min(28).max(400) }).strict();
|
|
51
|
+
const DocFolder = z
|
|
52
|
+
.string()
|
|
53
|
+
.regex(/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/, "a folder is a repo-relative path like docs or docs/adr");
|
|
54
|
+
/** A module type as written in a toolbox file. Only `id` is needed when it changes a type an earlier file made. */
|
|
55
|
+
export const TypeEntrySchema = z
|
|
56
|
+
.object({
|
|
57
|
+
id: Id.describe("unique across toolboxes; prefix it with the toolbox id (aws-ec2, gcp-run)"),
|
|
58
|
+
name: z.string().min(1).optional(),
|
|
59
|
+
description: z.string().optional(),
|
|
60
|
+
icon: IconSchema.optional(),
|
|
61
|
+
color: ColorTokenSchema.optional(),
|
|
62
|
+
size: SizeSchema.optional(),
|
|
63
|
+
/** Its row in the layout, top to bottom: 0 users, 1 frontend, 2 gateway, 3 API, 4 service, 5 worker or queue, 6 data. */
|
|
64
|
+
tier: z.number().int().min(0).max(TIER_MAX).optional(),
|
|
65
|
+
/** right: drawn in a column to the right of the rest (externals). */
|
|
66
|
+
side: z.enum(["right"]).optional(),
|
|
67
|
+
properties: z.array(PropertyDefSchema).optional(),
|
|
68
|
+
})
|
|
69
|
+
.strict();
|
|
70
|
+
/** A doc type as written in a toolbox file: a markdown template ({{title}}, {{module}}, {{view}}, {{date}}). */
|
|
71
|
+
export const DocEntrySchema = z
|
|
72
|
+
.object({
|
|
73
|
+
id: Id,
|
|
74
|
+
name: z.string().min(1).optional(),
|
|
75
|
+
description: z.string().optional(),
|
|
76
|
+
icon: IconSchema.optional(),
|
|
77
|
+
color: ColorTokenSchema.optional(),
|
|
78
|
+
/** Where new docs of this type go, under the repo (default docs/). */
|
|
79
|
+
folder: DocFolder.optional(),
|
|
80
|
+
/** The title a new doc gets ({{module}}, {{view}}, {{type}}). */
|
|
81
|
+
title: z.string().optional(),
|
|
82
|
+
template: z.string().optional(),
|
|
83
|
+
})
|
|
84
|
+
.strict();
|
|
85
|
+
/** One toolbox file: `toolboxes/<id>.yaml`. */
|
|
86
|
+
export const ToolboxFileSchema = z
|
|
87
|
+
.object({
|
|
88
|
+
id: Id.optional().describe("default: the file name. The same id in a later file (user, project) overrides or extends this toolbox"),
|
|
89
|
+
name: z.string().min(1).optional().describe("the toolbox's name on the bar (default: from the id)"),
|
|
90
|
+
icon: IconSchema.optional(),
|
|
91
|
+
description: z.string().optional(),
|
|
92
|
+
/** Where it sits on the bar: lower first (built-in: Software 10, Cloud 20, AWS 30, Azure 40, Docs 90). */
|
|
93
|
+
order: z.number().optional(),
|
|
94
|
+
types: z.array(TypeEntrySchema).optional(),
|
|
95
|
+
docs: z.array(DocEntrySchema).optional(),
|
|
96
|
+
})
|
|
97
|
+
.strict();
|
|
98
|
+
/** A module type, ready to use (defaults filled in). */
|
|
99
|
+
export const ModuleTypeSchema = z.object({
|
|
100
|
+
id: Id,
|
|
101
|
+
name: z.string().min(1),
|
|
102
|
+
description: z.string().optional(),
|
|
103
|
+
icon: IconSchema.default("lucide:box"),
|
|
104
|
+
color: ColorTokenSchema.default("slate"),
|
|
105
|
+
size: SizeSchema.default({ w: 170, h: 48 }),
|
|
106
|
+
/**
|
|
107
|
+
* The row it is drawn in, top to bottom, as an architect would: 0 client or
|
|
108
|
+
* users, 1 frontend, 2 edge or gateway, 3 API, 4 service, 5 worker or queue,
|
|
109
|
+
* 6 data. The auto-layout keeps each tier in its own row (empty tiers take no room).
|
|
110
|
+
*/
|
|
111
|
+
tier: z.number().int().min(0).max(TIER_MAX).optional(),
|
|
112
|
+
/** right: drawn in a column to the right of the rest (externals), not in a row. */
|
|
113
|
+
side: z.enum(["right"]).optional(),
|
|
114
|
+
properties: z.array(PropertyDefSchema).default([]),
|
|
115
|
+
});
|
|
116
|
+
/** A doc type, ready to use (defaults filled in). */
|
|
117
|
+
export const DocTypeSchema = z.object({
|
|
118
|
+
id: Id,
|
|
119
|
+
name: z.string().min(1),
|
|
120
|
+
description: z.string().optional(),
|
|
121
|
+
icon: IconSchema.default("lucide:file-text"),
|
|
122
|
+
color: ColorTokenSchema.default("gray"),
|
|
123
|
+
folder: DocFolder.default("docs"),
|
|
124
|
+
title: z.string().default("{{module}} {{type}}"),
|
|
125
|
+
template: z.string().default("# {{title}}\n"),
|
|
126
|
+
});
|
|
127
|
+
export const formatError = (e) => `${e.file}${e.line ? `:${e.line}${e.column ? `:${e.column}` : ""}` : ""}: ${e.message}`;
|
|
128
|
+
/** The package's own toolboxes/ folder (the built-in toolboxes). */
|
|
129
|
+
export const BUILTIN_DIR = fileURLToPath(new URL("../../toolboxes/", import.meta.url));
|
|
130
|
+
/** The user's toolboxes: ~/SpatialViews/toolboxes (SPATIAL_VIEWS_HOME moves the home folder). */
|
|
131
|
+
export const userToolboxDir = (home) => join(resolve(home ?? (process.env.SPATIAL_VIEWS_HOME?.trim() || join(homedir(), "SpatialViews"))), "toolboxes");
|
|
132
|
+
/** A project's toolboxes: <data>/toolboxes. */
|
|
133
|
+
export const projectToolboxDir = (dataDir) => join(dataDir, "toolboxes");
|
|
134
|
+
// ---- Reading one file, with line numbers ---------------------------------------
|
|
135
|
+
const MAX_SVG = 256 * 1024;
|
|
136
|
+
function posOf(doc, lc, path, key) {
|
|
137
|
+
// The deepest node on the path that exists (a missing key points at its parent).
|
|
138
|
+
for (let n = path.length; n >= 0; n--) {
|
|
139
|
+
let node = doc.getIn(path.slice(0, n), true);
|
|
140
|
+
if (n === 0)
|
|
141
|
+
node = doc.contents;
|
|
142
|
+
if (key && n === path.length && isMap(node)) {
|
|
143
|
+
const pair = node.items.find((p) => p.key?.value === key);
|
|
144
|
+
const k = pair?.key;
|
|
145
|
+
if (k?.range)
|
|
146
|
+
node = k;
|
|
147
|
+
}
|
|
148
|
+
if (node?.range) {
|
|
149
|
+
const p = lc.linePos(node.range[0]);
|
|
150
|
+
return { line: p.line, column: p.col };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return {};
|
|
154
|
+
}
|
|
155
|
+
const issueText = (i) => {
|
|
156
|
+
const where = i.path.length ? `${i.path.map((p) => (typeof p === "number" ? `[${p}]` : `.${String(p)}`)).join("").replace(/^\./, "")}: ` : "";
|
|
157
|
+
if (i.code === "unrecognized_keys")
|
|
158
|
+
return `${where}unknown field ${i.keys.map((k) => `"${k}"`).join(", ")}`;
|
|
159
|
+
return `${where}${i.message}`;
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* Check a toolbox file's text against the schema. Errors name the file and the
|
|
163
|
+
* line. A bad type or doc entry is left out and the rest of the file is kept.
|
|
164
|
+
*/
|
|
165
|
+
export function checkToolboxText(text, file) {
|
|
166
|
+
const lines = new Map();
|
|
167
|
+
const lc = new LineCounter();
|
|
168
|
+
const doc = parseDocument(text, { lineCounter: lc, prettyErrors: false, uniqueKeys: true });
|
|
169
|
+
if (doc.errors.length) {
|
|
170
|
+
return {
|
|
171
|
+
toolbox: null,
|
|
172
|
+
lines,
|
|
173
|
+
// linePos is only filled with prettyErrors, so the line comes from the error's offset.
|
|
174
|
+
errors: doc.errors.map((e) => {
|
|
175
|
+
const p = e.linePos?.[0] ?? (typeof e.pos?.[0] === "number" ? lc.linePos(e.pos[0]) : null);
|
|
176
|
+
return { file, ...(p ? { line: p.line, column: p.col } : {}), message: e.message.split("\n")[0] };
|
|
177
|
+
}),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
let raw = (doc.toJS() ?? {});
|
|
181
|
+
if (typeof raw !== "object" || Array.isArray(raw))
|
|
182
|
+
return { toolbox: null, lines, errors: [{ file, line: 1, message: "a toolbox file is a YAML mapping (name, icon, types, docs)" }] };
|
|
183
|
+
const errors = [];
|
|
184
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
185
|
+
const r = ToolboxFileSchema.safeParse(raw);
|
|
186
|
+
if (r.success) {
|
|
187
|
+
// Where each entry is, so a problem found when the files are merged can name its line too.
|
|
188
|
+
for (const list of ["types", "docs"]) {
|
|
189
|
+
const seq = doc.get(list, true);
|
|
190
|
+
if (!isSeq(seq))
|
|
191
|
+
continue;
|
|
192
|
+
for (const n of seq.items) {
|
|
193
|
+
if (!isMap(n) || !n.range)
|
|
194
|
+
continue;
|
|
195
|
+
const p = lc.linePos(n.range[0]);
|
|
196
|
+
lines.set(`${list}:${String(n.get("id"))}`, { line: p.line, column: p.col });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return { toolbox: r.data, errors, lines };
|
|
200
|
+
}
|
|
201
|
+
const drop = { types: new Set(), docs: new Set() };
|
|
202
|
+
let fatal = false;
|
|
203
|
+
const said = new Set();
|
|
204
|
+
for (const i of r.error.issues) {
|
|
205
|
+
const key = i.code === "unrecognized_keys" ? i.keys[0] : undefined;
|
|
206
|
+
// One problem per field (an icon can fail two checks).
|
|
207
|
+
const where = `${i.path.join(".")}:${key ?? ""}`;
|
|
208
|
+
if (tries === 0 && !said.has(where))
|
|
209
|
+
errors.push({ file, ...posOf(doc, lc, i.path, key), message: issueText(i) });
|
|
210
|
+
said.add(where);
|
|
211
|
+
const [list, at] = i.path;
|
|
212
|
+
if ((list === "types" || list === "docs") && typeof at === "number")
|
|
213
|
+
drop[list].add(at);
|
|
214
|
+
else
|
|
215
|
+
fatal = true;
|
|
216
|
+
}
|
|
217
|
+
if (fatal)
|
|
218
|
+
return { toolbox: null, errors, lines };
|
|
219
|
+
raw = { ...raw };
|
|
220
|
+
for (const list of ["types", "docs"])
|
|
221
|
+
if (Array.isArray(raw[list]))
|
|
222
|
+
raw[list] = raw[list].filter((_, n) => !drop[list].has(n));
|
|
223
|
+
}
|
|
224
|
+
return { toolbox: null, errors, lines };
|
|
225
|
+
}
|
|
226
|
+
/** Read an icon file (./icons/x.svg, next to the YAML) as a data: URL. */
|
|
227
|
+
async function readIcon(icon, yamlFile, errors, at) {
|
|
228
|
+
if (!icon?.startsWith("./"))
|
|
229
|
+
return undefined;
|
|
230
|
+
const base = resolve(dirname(yamlFile));
|
|
231
|
+
const abs = resolve(base, icon);
|
|
232
|
+
if (!abs.startsWith(base + sep))
|
|
233
|
+
return undefined;
|
|
234
|
+
try {
|
|
235
|
+
const s = await stat(abs);
|
|
236
|
+
if (s.size > MAX_SVG)
|
|
237
|
+
throw new Error(`is over ${MAX_SVG / 1024} KB`);
|
|
238
|
+
const svg = await readFile(abs, "utf8");
|
|
239
|
+
if (!/<svg[\s>]/i.test(svg))
|
|
240
|
+
throw new Error("is not an SVG");
|
|
241
|
+
return `data:image/svg+xml;base64,${Buffer.from(svg, "utf8").toString("base64")}`;
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
const code = e.code;
|
|
245
|
+
errors.push({ file: yamlFile, ...at, message: `icon ${icon} ${code === "ENOENT" ? "was not found" : e.message} (the lucide box icon is shown instead)` });
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async function yamlFilesIn(dir) {
|
|
250
|
+
if (!dir)
|
|
251
|
+
return [];
|
|
252
|
+
const names = await readdir(dir).catch(() => []);
|
|
253
|
+
return names.filter((f) => /\.ya?ml$/.test(f)).sort().map((f) => join(dir, f));
|
|
254
|
+
}
|
|
255
|
+
const fileId = (file) => basename(file).replace(/\.ya?ml$/, "");
|
|
256
|
+
const titleOf = (id) => id.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
257
|
+
const lucideName = (icon) => (icon.startsWith("lucide:") || icon.startsWith("./") ? icon : `lucide:${icon}`);
|
|
258
|
+
const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
259
|
+
async function readDisabled(dataDir) {
|
|
260
|
+
if (!dataDir)
|
|
261
|
+
return [];
|
|
262
|
+
try {
|
|
263
|
+
const s = JSON.parse(await readFile(join(dataDir, "settings.json"), "utf8"));
|
|
264
|
+
return Array.isArray(s.disabled_toolboxes) ? s.disabled_toolboxes.filter((x) => typeof x === "string") : [];
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return [];
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Every toolbox: built-in, then the user's, then the project's, merged by id.
|
|
272
|
+
* Broken files and entries are left out and reported in `errors`.
|
|
273
|
+
*/
|
|
274
|
+
export async function loadToolbox(dataDir, dirs = {}) {
|
|
275
|
+
const levels = [
|
|
276
|
+
["built-in", dirs.builtin ?? BUILTIN_DIR],
|
|
277
|
+
["user", dirs.user === undefined ? userToolboxDir() : dirs.user],
|
|
278
|
+
["project", dataDir ? projectToolboxDir(dataDir) : null],
|
|
279
|
+
];
|
|
280
|
+
const errors = [];
|
|
281
|
+
const acc = new Map();
|
|
282
|
+
let seen = 0;
|
|
283
|
+
const loaded = new Set();
|
|
284
|
+
for (const [level, dir] of levels) {
|
|
285
|
+
const files = await yamlFilesIn(dir);
|
|
286
|
+
if (level === "project" && dirs.extra)
|
|
287
|
+
files.push(...dirs.extra.map((f) => resolve(f)));
|
|
288
|
+
for (const file of files) {
|
|
289
|
+
if (loaded.has(file))
|
|
290
|
+
continue;
|
|
291
|
+
loaded.add(file);
|
|
292
|
+
const text = await readFile(file, "utf8").catch(() => null);
|
|
293
|
+
if (text == null)
|
|
294
|
+
continue;
|
|
295
|
+
const checked = checkToolboxText(text, file);
|
|
296
|
+
errors.push(...checked.errors);
|
|
297
|
+
const f = checked.toolbox;
|
|
298
|
+
if (!f)
|
|
299
|
+
continue;
|
|
300
|
+
const id = f.id ?? fileId(file);
|
|
301
|
+
let a = acc.get(id);
|
|
302
|
+
if (!a)
|
|
303
|
+
acc.set(id, (a = { id, source: level, files: [], firstSeen: seen++, types: new Map(), docs: new Map() }));
|
|
304
|
+
a.files.push(file);
|
|
305
|
+
if (f.name !== undefined)
|
|
306
|
+
a.name = f.name;
|
|
307
|
+
if (f.description !== undefined)
|
|
308
|
+
a.description = f.description;
|
|
309
|
+
if (f.order !== undefined)
|
|
310
|
+
a.order = f.order;
|
|
311
|
+
if (f.icon !== undefined) {
|
|
312
|
+
a.icon = lucideName(f.icon);
|
|
313
|
+
const svg = await readIcon(f.icon, file, errors);
|
|
314
|
+
if (svg)
|
|
315
|
+
a.icon_svg = svg;
|
|
316
|
+
else
|
|
317
|
+
delete a.icon_svg;
|
|
318
|
+
}
|
|
319
|
+
for (const [list, entries] of [["types", f.types ?? []], ["docs", f.docs ?? []]]) {
|
|
320
|
+
const into = a[list];
|
|
321
|
+
for (const e of entries) {
|
|
322
|
+
const at = checked.lines.get(`${list}:${e.id}`);
|
|
323
|
+
const prev = into.get(e.id) ?? { file };
|
|
324
|
+
const next = { ...prev, ...defined(e), file, ...(at ? { at } : {}) };
|
|
325
|
+
if (!at)
|
|
326
|
+
delete next.at;
|
|
327
|
+
if (e.icon !== undefined) {
|
|
328
|
+
next.icon = lucideName(e.icon);
|
|
329
|
+
const svg = await readIcon(e.icon, file, errors, at);
|
|
330
|
+
if (svg)
|
|
331
|
+
next.icon_svg = svg;
|
|
332
|
+
else
|
|
333
|
+
delete next.icon_svg;
|
|
334
|
+
}
|
|
335
|
+
into.set(e.id, next);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const disabled = new Set(dirs.disabled ?? (await readDisabled(dataDir)));
|
|
341
|
+
const typeOwner = new Map();
|
|
342
|
+
const docOwner = new Map();
|
|
343
|
+
const finish = (a, entries, schema, owners, what) => {
|
|
344
|
+
const out = [];
|
|
345
|
+
for (const [id, { file, at, icon_svg, ...e }] of entries) {
|
|
346
|
+
const owner = owners.get(id);
|
|
347
|
+
if (owner) {
|
|
348
|
+
errors.push({ file, ...at, message: `${what} ${id} is already in toolbox ${owner}; give it another id (e.g. ${a.id}-${id})` });
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const r = schema.safeParse(e);
|
|
352
|
+
if (!r.success) {
|
|
353
|
+
const why = r.error.issues.map((i) => (i.path[0] === "name" ? "name is needed (a new type needs one; to change a type, use the id of one in an earlier file)" : issueText(i)));
|
|
354
|
+
errors.push({ file, ...at, message: `${what} ${id}: ${why.join("; ")}` });
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
owners.set(id, a.id);
|
|
358
|
+
out.push({ ...r.data, toolbox: a.id, ...(icon_svg ? { icon_svg } : {}) });
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
};
|
|
362
|
+
const toolboxes = [...acc.values()]
|
|
363
|
+
.sort((x, y) => (x.order ?? 100) - (y.order ?? 100) || x.firstSeen - y.firstSeen)
|
|
364
|
+
.map((a) => ({
|
|
365
|
+
id: a.id,
|
|
366
|
+
name: a.name ?? titleOf(a.id),
|
|
367
|
+
icon: a.icon ?? "lucide:shapes",
|
|
368
|
+
...(a.icon_svg ? { icon_svg: a.icon_svg } : {}),
|
|
369
|
+
...(a.description ? { description: a.description } : {}),
|
|
370
|
+
order: a.order ?? 100,
|
|
371
|
+
source: a.source,
|
|
372
|
+
files: a.files,
|
|
373
|
+
enabled: !disabled.has(a.id),
|
|
374
|
+
types: finish(a, a.types, ModuleTypeSchema, typeOwner, "type"),
|
|
375
|
+
docs: finish(a, a.docs, DocTypeSchema, docOwner, "doc type"),
|
|
376
|
+
}));
|
|
377
|
+
return { toolboxes, types: toolboxes.flatMap((t) => t.types), docs: toolboxes.flatMap((t) => t.docs), errors };
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Check toolbox files (spatial-views toolbox check): each against the schema,
|
|
381
|
+
* then loaded on top of the built-in and the user's toolboxes, so a missing
|
|
382
|
+
* name, a clash of ids or a missing icon file shows too. Errors are this file's only.
|
|
383
|
+
*/
|
|
384
|
+
export async function checkToolboxFiles(files, dirs = {}) {
|
|
385
|
+
const abs = files.map((f) => resolve(f));
|
|
386
|
+
const toolbox = await loadToolbox(null, { ...dirs, extra: abs, disabled: [] });
|
|
387
|
+
const missing = [];
|
|
388
|
+
for (const f of abs)
|
|
389
|
+
if (!(await stat(f).catch(() => null)))
|
|
390
|
+
missing.push({ file: f, message: "no such file" });
|
|
391
|
+
return { toolbox, errors: [...missing, ...toolbox.errors.filter((e) => abs.includes(e.file))] };
|
|
392
|
+
}
|
|
393
|
+
/** Every module type (in every toolbox, on or off). */
|
|
394
|
+
export async function loadTypes(dataDir, dirs) {
|
|
395
|
+
return (await loadToolbox(dataDir, dirs)).types;
|
|
396
|
+
}
|
|
397
|
+
/** Every doc type (in every toolbox, on or off). */
|
|
398
|
+
export async function loadDocTypes(dataDir, dirs) {
|
|
399
|
+
return (await loadToolbox(dataDir, dirs)).docs;
|
|
400
|
+
}
|
|
401
|
+
/** A type as the AI is shown it: the icon file's SVG data is left out (the icon path stays). */
|
|
402
|
+
export const leanType = ({ icon_svg: _svg, ...t }) => t;
|
|
403
|
+
// ---- Finding and checking -------------------------------------------------------
|
|
404
|
+
/** A doc type by id or name (case-insensitive). */
|
|
405
|
+
export function findDocType(docs, ref) {
|
|
406
|
+
const hit = docs.find((t) => t.id === ref) ?? docs.find((t) => t.name.toLowerCase() === ref.toLowerCase());
|
|
407
|
+
if (!hit)
|
|
408
|
+
throw new UserError(`no doc type "${ref}"; list_types shows them (${docs.map((t) => t.id).join(", ")})`);
|
|
409
|
+
return hit;
|
|
410
|
+
}
|
|
411
|
+
/** Fill a doc type's template: {{title}}, {{type}}, {{module}}, {{view}}, {{date}} (one pass; unknown names are left as they are). */
|
|
412
|
+
export function fillTemplate(template, vars) {
|
|
413
|
+
const values = {
|
|
414
|
+
title: vars.title ?? "",
|
|
415
|
+
type: vars.type ?? "",
|
|
416
|
+
module: vars.module ?? "",
|
|
417
|
+
view: vars.view ?? "",
|
|
418
|
+
date: vars.date ?? new Date().toISOString().slice(0, 10),
|
|
419
|
+
};
|
|
420
|
+
return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (all, k) => values[k] ?? all);
|
|
421
|
+
}
|
|
422
|
+
/** A type by id or name (case-insensitive). */
|
|
423
|
+
export function findType(types, ref) {
|
|
424
|
+
const hit = types.find((t) => t.id === ref) ?? types.find((t) => t.name.toLowerCase() === ref.toLowerCase());
|
|
425
|
+
if (!hit)
|
|
426
|
+
throw new UserError(`no module type "${ref}"; list_types shows them`);
|
|
427
|
+
return hit;
|
|
428
|
+
}
|
|
429
|
+
/** Check one module's property values against its type: unknown names and wrong kinds are refused. */
|
|
430
|
+
export function checkProperties(type, values) {
|
|
431
|
+
const out = {};
|
|
432
|
+
for (const [k, v] of Object.entries(values)) {
|
|
433
|
+
const def = type?.properties.find((p) => p.name === k);
|
|
434
|
+
if (!def) {
|
|
435
|
+
// A property the type doesn't declare (or no type): kept as text, so nothing a person typed is lost.
|
|
436
|
+
out[k] = typeof v === "string" ? v : String(v);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (def.type === "number") {
|
|
440
|
+
const n = typeof v === "number" ? v : Number(v);
|
|
441
|
+
if (!Number.isFinite(n))
|
|
442
|
+
throw new UserError(`${k} is a number`);
|
|
443
|
+
out[k] = n;
|
|
444
|
+
}
|
|
445
|
+
else if (def.type === "boolean") {
|
|
446
|
+
if (typeof v === "boolean")
|
|
447
|
+
out[k] = v;
|
|
448
|
+
else if (v === "true" || v === "false")
|
|
449
|
+
out[k] = v === "true";
|
|
450
|
+
else
|
|
451
|
+
throw new UserError(`${k} is true or false`);
|
|
452
|
+
}
|
|
453
|
+
else if (def.type === "enum") {
|
|
454
|
+
const s = String(v);
|
|
455
|
+
if (def.options?.length && !def.options.includes(s))
|
|
456
|
+
throw new UserError(`${k} is one of ${def.options.join(", ")}`);
|
|
457
|
+
out[k] = s;
|
|
458
|
+
}
|
|
459
|
+
else
|
|
460
|
+
out[k] = String(v);
|
|
461
|
+
}
|
|
462
|
+
return out;
|
|
463
|
+
}
|
|
464
|
+
export const slug = (name) => name
|
|
465
|
+
.toLowerCase()
|
|
466
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
467
|
+
.replace(/^-+|-+$/g, "") || "type";
|
|
468
|
+
// ---- Writing: create_type, create_toolbox, toolbox new -----------------------------
|
|
469
|
+
/** The published JSON Schema for toolbox files (spatial-views schema writes it). */
|
|
470
|
+
export const TOOLBOX_SCHEMA_URL = "https://raw.githubusercontent.com/Hotchilli-Cloud/spatial-views/main/schema/toolbox.schema.json";
|
|
471
|
+
const HEADER = `# yaml-language-server: $schema=${TOOLBOX_SCHEMA_URL}\n`;
|
|
472
|
+
/** The file in `dir` that holds toolbox `id` (its own id, else the file name), or null. */
|
|
473
|
+
async function fileFor(dir, id) {
|
|
474
|
+
for (const file of await yamlFilesIn(dir)) {
|
|
475
|
+
const text = await readFile(file, "utf8").catch(() => "");
|
|
476
|
+
const doc = parseDocument(text);
|
|
477
|
+
const own = doc.get("id") ?? fileId(file);
|
|
478
|
+
if (own === id)
|
|
479
|
+
return file;
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
function failIfBad(text, file) {
|
|
484
|
+
const { errors } = checkToolboxText(text, file);
|
|
485
|
+
if (errors.length)
|
|
486
|
+
throw new UserError(errors.map(formatError).join("\n"));
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Add (or change) a type in a toolbox, in the project's toolboxes folder (or the
|
|
490
|
+
* user's, with `dir`). The toolbox may be a built-in one: the project file then
|
|
491
|
+
* extends it by id. A new toolbox id makes a new toolbox.
|
|
492
|
+
*/
|
|
493
|
+
export async function createType(dataDir, input, opts = {}) {
|
|
494
|
+
const kind = opts.kind ?? "module";
|
|
495
|
+
const { toolbox: tbRef, ...rest } = input;
|
|
496
|
+
const toolbox = tbRef ?? (kind === "doc" ? "docs" : "custom");
|
|
497
|
+
if (!Id.safeParse(toolbox).success)
|
|
498
|
+
throw new UserError(`toolbox ${toolbox}: an id is lower-case letters, digits, - and _`);
|
|
499
|
+
const id = rest.id ?? slug(rest.name);
|
|
500
|
+
const full = (kind === "doc" ? DocTypeSchema : ModuleTypeSchema).safeParse({ ...rest, id });
|
|
501
|
+
if (!full.success)
|
|
502
|
+
throw new UserError(full.error.issues.map(issueText).join("; "));
|
|
503
|
+
// Only what was given is written, so the file stays as short as a person would write it.
|
|
504
|
+
const entry = defined({ ...rest, id });
|
|
505
|
+
const dir = opts.dir ?? projectToolboxDir(dataDir);
|
|
506
|
+
await mkdir(dir, { recursive: true });
|
|
507
|
+
const file = (await fileFor(dir, toolbox)) ?? join(dir, `${toolbox}.yaml`);
|
|
508
|
+
const text = await readFile(file, "utf8").catch(() => null);
|
|
509
|
+
const doc = text != null ? parseDocument(text) : parseDocument(`${HEADER}id: ${toolbox}\n`);
|
|
510
|
+
const list = kind === "doc" ? "docs" : "types";
|
|
511
|
+
let seq = doc.get(list, true);
|
|
512
|
+
if (!isSeq(seq)) {
|
|
513
|
+
doc.set(list, doc.createNode([]));
|
|
514
|
+
seq = doc.get(list, true);
|
|
515
|
+
}
|
|
516
|
+
const items = seq.items;
|
|
517
|
+
const at = items.findIndex((n) => isMap(n) && n.get("id") === id);
|
|
518
|
+
const node = doc.createNode(entry);
|
|
519
|
+
if (at >= 0)
|
|
520
|
+
items[at] = node;
|
|
521
|
+
else
|
|
522
|
+
items.push(node);
|
|
523
|
+
const out = doc.toString({ lineWidth: 0 });
|
|
524
|
+
failIfBad(out, file);
|
|
525
|
+
await writeFile(file, out, "utf8");
|
|
526
|
+
const made = (kind === "doc" ? DocTypeSchema : ModuleTypeSchema).parse({ ...rest, id });
|
|
527
|
+
return { ...made, toolbox };
|
|
528
|
+
}
|
|
529
|
+
/** Make a new toolbox file (refused when this folder already has one with that id: add types to it with createType). */
|
|
530
|
+
export async function createToolbox(dataDir, input, opts = {}) {
|
|
531
|
+
const id = input.id ?? slug(input.name);
|
|
532
|
+
const dir = opts.dir ?? projectToolboxDir(dataDir);
|
|
533
|
+
if (await fileFor(dir, id))
|
|
534
|
+
throw new UserError(`toolbox ${id} is already in ${dir}; add types to it with create_type`);
|
|
535
|
+
const body = defined({ name: input.name, icon: input.icon, description: input.description, order: input.order, types: input.types, docs: input.docs });
|
|
536
|
+
const file = join(dir, `${id}.yaml`);
|
|
537
|
+
const text = HEADER + stringify(body, { lineWidth: 0 });
|
|
538
|
+
failIfBad(text, file);
|
|
539
|
+
await mkdir(dir, { recursive: true });
|
|
540
|
+
await writeFile(file, text, { encoding: "utf8", flag: "wx" });
|
|
541
|
+
return { file, id };
|
|
542
|
+
}
|
|
543
|
+
/** The YAML `spatial-views toolbox new <name>` writes: a toolbox with one example type, commented. */
|
|
544
|
+
export function scaffoldToolbox(name) {
|
|
545
|
+
const id = slug(name);
|
|
546
|
+
return `${HEADER}# The ${name} toolbox for Spatial Views: one icon on the canvas's right-hand bar.
|
|
547
|
+
# Check it with: npx spatial-views toolbox check ${id}.yaml
|
|
548
|
+
# Send it upstream: see CONTRIBUTING.md, "Add a toolbox".
|
|
549
|
+
name: ${name}
|
|
550
|
+
icon: lucide:shapes # lucide:<name> (https://lucide.dev/icons), or ./icons/<file>.svg next to this file
|
|
551
|
+
description: What this toolbox is for.
|
|
552
|
+
types:
|
|
553
|
+
- id: ${id}-example # unique across toolboxes: start it with the toolbox id
|
|
554
|
+
name: Example
|
|
555
|
+
description: What it is, in one line.
|
|
556
|
+
icon: lucide:box
|
|
557
|
+
color: blue # slate gray blue indigo violet pink red orange amber green teal cyan
|
|
558
|
+
size: { w: 170, h: 48 }
|
|
559
|
+
properties: # type: string text number boolean enum url
|
|
560
|
+
- { name: region, type: string }
|
|
561
|
+
- { name: tier, type: enum, options: [Free, Standard, Premium], default: Standard }
|
|
562
|
+
# docs: # doc types, too: a markdown template ({{title}}, {{module}}, {{view}}, {{date}})
|
|
563
|
+
# - id: ${id}-design
|
|
564
|
+
# name: Design note
|
|
565
|
+
# icon: lucide:file-text
|
|
566
|
+
# template: |
|
|
567
|
+
# # {{title}}
|
|
568
|
+
`;
|
|
569
|
+
}
|
|
570
|
+
/** Write a new toolbox scaffold into `dir` (never overwriting a file). */
|
|
571
|
+
export async function newToolboxFile(dir, name) {
|
|
572
|
+
const file = join(dir, `${slug(name)}.yaml`);
|
|
573
|
+
await mkdir(dir, { recursive: true });
|
|
574
|
+
try {
|
|
575
|
+
await writeFile(file, scaffoldToolbox(name), { encoding: "utf8", flag: "wx" });
|
|
576
|
+
}
|
|
577
|
+
catch (e) {
|
|
578
|
+
if (e.code === "EEXIST")
|
|
579
|
+
throw new UserError(`${file} already exists`);
|
|
580
|
+
throw e;
|
|
581
|
+
}
|
|
582
|
+
return file;
|
|
583
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.2.0";
|