archidocs 1.2.0 → 1.3.1

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 (119) hide show
  1. package/README.md +62 -13
  2. package/dist/cli/commands.d.ts +231 -10
  3. package/dist/cli/commands.js +134 -9
  4. package/dist/cli/dev.d.ts +5 -6
  5. package/dist/cli/dev.js +12 -14
  6. package/dist/cli/diff-format.d.ts +1 -5
  7. package/dist/cli/init.d.ts +1 -1
  8. package/dist/cli/init.js +2 -2
  9. package/dist/cli/main.js +2 -329
  10. package/dist/cli/run.d.ts +18 -0
  11. package/dist/cli/run.js +283 -0
  12. package/dist/commands/build.d.ts +51 -0
  13. package/dist/commands/build.js +39 -0
  14. package/dist/commands/check.d.ts +8 -0
  15. package/dist/commands/check.js +5 -0
  16. package/dist/commands/diff.d.ts +29 -0
  17. package/dist/commands/diff.js +25 -0
  18. package/dist/commands/export.d.ts +41 -0
  19. package/dist/commands/export.js +47 -0
  20. package/dist/commands/history.d.ts +18 -0
  21. package/dist/commands/history.js +9 -0
  22. package/dist/commands/index.d.ts +11 -0
  23. package/dist/commands/index.js +11 -0
  24. package/dist/core/compare.d.ts +2 -13
  25. package/dist/core/compare.js +2 -35
  26. package/dist/core/index.d.ts +3 -6
  27. package/dist/core/index.js +3 -6
  28. package/dist/core/load.d.ts +0 -2
  29. package/dist/core/load.js +5 -6
  30. package/dist/core/rules.d.ts +10 -0
  31. package/dist/core/rules.js +186 -7
  32. package/dist/core/views/compare.d.ts +12 -0
  33. package/dist/core/views/compare.js +37 -0
  34. package/dist/core/{deployment-views.d.ts → views/deployment.d.ts} +4 -5
  35. package/dist/core/{deployment-views.js → views/deployment.js} +5 -7
  36. package/dist/core/{dynamic-views.d.ts → views/dynamic.d.ts} +1 -3
  37. package/dist/core/{dynamic-views.js → views/dynamic.js} +4 -8
  38. package/dist/core/views/generated.d.ts +18 -0
  39. package/dist/core/views/generated.js +92 -0
  40. package/dist/core/views/ids.d.ts +36 -0
  41. package/dist/core/views/ids.js +51 -0
  42. package/dist/core/views/index.d.ts +13 -0
  43. package/dist/core/views/index.js +12 -0
  44. package/dist/core/views/lens.d.ts +27 -0
  45. package/dist/core/views/lens.js +112 -0
  46. package/dist/core/views/model.d.ts +21 -0
  47. package/dist/core/views/model.js +69 -0
  48. package/dist/core/views/resolve.d.ts +42 -0
  49. package/dist/core/views/resolve.js +81 -0
  50. package/dist/core/{save-as-view.d.ts → views/save-as-view.d.ts} +2 -2
  51. package/dist/core/{save-as-view.js → views/save-as-view.js} +13 -10
  52. package/dist/core/{saved-views.d.ts → views/saved.d.ts} +4 -18
  53. package/dist/core/{saved-views.js → views/saved.js} +8 -103
  54. package/dist/core/views/types.d.ts +91 -0
  55. package/dist/core/views/types.js +2 -0
  56. package/dist/core/workspace-files.d.ts +13 -0
  57. package/dist/core/workspace-files.js +20 -0
  58. package/dist/git.d.ts +2 -0
  59. package/dist/git.js +14 -4
  60. package/dist/history/git.d.ts +0 -10
  61. package/dist/history/git.js +1 -30
  62. package/dist/history/index.d.ts +15 -31
  63. package/dist/history/index.js +47 -43
  64. package/dist/history/points.d.ts +23 -0
  65. package/dist/history/points.js +28 -0
  66. package/dist/history/site.d.ts +30 -0
  67. package/dist/history/site.js +37 -0
  68. package/dist/mcp/errors.d.ts +37 -0
  69. package/dist/mcp/errors.js +35 -0
  70. package/dist/mcp/history.d.ts +4 -4
  71. package/dist/mcp/history.js +56 -116
  72. package/dist/mcp/index.d.ts +2 -1
  73. package/dist/mcp/index.js +1 -0
  74. package/dist/mcp/server.d.ts +1 -2
  75. package/dist/mcp/server.js +30 -29
  76. package/dist/mcp/site.d.ts +12 -0
  77. package/dist/mcp/site.js +46 -0
  78. package/dist/mcp/source.d.ts +14 -7
  79. package/dist/mcp/source.js +25 -99
  80. package/dist/render/layout.d.ts +20 -3
  81. package/dist/render/layout.js +49 -12
  82. package/dist/render/sequence-svg.d.ts +1 -1
  83. package/dist/render/sequence.d.ts +1 -1
  84. package/dist/render/svg.d.ts +1 -1
  85. package/dist/render/svg.js +4 -4
  86. package/dist/revisions/find.d.ts +64 -0
  87. package/dist/revisions/find.js +85 -0
  88. package/dist/revisions/index.d.ts +57 -0
  89. package/dist/revisions/index.js +24 -0
  90. package/dist/revisions/site.d.ts +82 -0
  91. package/dist/revisions/site.js +157 -0
  92. package/dist/revisions/text.d.ts +8 -0
  93. package/dist/revisions/text.js +17 -0
  94. package/dist/revisions/touching.d.ts +7 -0
  95. package/dist/revisions/touching.js +7 -0
  96. package/dist/schema/adr.js +18 -13
  97. package/dist/schema/workspace.js +226 -130
  98. package/dist/viewer/assets/index-C0lIIm8V.js +138 -0
  99. package/dist/viewer/assets/index-YFA-pYjQ.css +1 -0
  100. package/dist/viewer/assets/{layout.worker-Bg-OaLVN.js → layout.worker-BRHAGJrD.js} +1 -1
  101. package/dist/viewer/assets/{png-BDKIXtm5.js → png-DMwnpRCt.js} +1 -1
  102. package/dist/viewer/assets/{svg-Bulv5YWn.js → svg-DN6lMeZo.js} +2 -2
  103. package/dist/viewer/index.html +2 -2
  104. package/dist/workspace/index.d.ts +37 -0
  105. package/dist/workspace/index.js +52 -0
  106. package/guide/SKILL.md +1 -1
  107. package/guide/topics/bootstrap.md +1 -1
  108. package/guide/topics/relationships.md +1 -1
  109. package/package.json +4 -3
  110. package/schemas/adr.schema.json +18 -15
  111. package/schemas/model.schema.json +637 -1144
  112. package/schemas/project.schema.json +8 -4
  113. package/schemas/workspace.schema.json +39 -20
  114. package/dist/core/views.d.ts +0 -126
  115. package/dist/core/views.js +0 -217
  116. package/dist/viewer/assets/index-DvKgCpBr.css +0 -1
  117. package/dist/viewer/assets/index-gucix3xm.js +0 -113
  118. /package/dist/{history → revisions}/migrate.d.ts +0 -0
  119. /package/dist/{history → revisions}/migrate.js +0 -0
package/dist/cli/main.js CHANGED
@@ -1,330 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync } from "node:fs";
3
- import { cp, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
4
- import { basename, join, resolve } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { findWorkspaceRoot, load, nodeFileSystem, resolveDynamicView, resolveView, serializeBundle } from "../core/index.js";
7
- import { directions, layoutView, renderSequenceSvg, renderSvg, themes } from "../render/index.js";
8
- import { renderPngInNode } from "../render/node.js";
9
- import { serveStdio } from "@modelcontextprotocol/server/stdio";
10
- import { gitHead, gitTopLevel } from "../git.js";
11
- import { bundleSource, checkoutSource, createServer, DEFAULT_PORT, serveHttp } from "../mcp/index.js";
12
- import { authoringGuide } from "../guide/index.js";
13
- import { parseCommand, usageText } from "./commands.js";
14
- import { init } from "./init.js";
15
- import { DEFAULT_DEV_PORT, serveDev } from "./dev.js";
16
- import { exitCodeFor, formatIssues, formats, formatText } from "./format.js";
17
- import { diff } from "../core/index.js";
18
- import { bundleAt, buildHistory, DEFAULT_KEEP, defaultBaseBranch, history, previewSides, publishHistory, publishPreview, resolvePoint } from "../history/index.js";
19
- import { SCHEMA_VERSION } from "../schema/bundle.js";
20
- import { diffFormats, formatDiff } from "./diff-format.js";
21
- /** Exit codes: 0 no errors, 1 errors found (or any warning with `--strict`), 2 could not run. */
22
- const OK = 0;
23
- const FOUND_ERRORS = 1;
24
- const COULD_NOT_RUN = 2;
25
- class UsageError extends Error {
26
- }
27
- /**
28
- * The prebuilt viewer, which `build --out` copies as is. The CLI runs from
29
- * dist/cli/ when installed and from src/cli/ in this repo; both sit two
30
- * levels below the package root, whose dist/viewer/ holds the viewer.
31
- */
32
- const VIEWER_DIR = fileURLToPath(new URL("../../dist/viewer/", import.meta.url));
33
- /** The package's own package.json, two levels up from dist/cli/ or src/cli/ like the viewer. */
34
- const PACKAGE_JSON = fileURLToPath(new URL("../../package.json", import.meta.url));
35
- const usage = usageText();
36
- async function main(argv) {
37
- const [command, ...rest] = argv;
38
- if (command === "init") {
39
- const { values } = parseCommand("init", rest);
40
- if (values.workspace !== undefined && !values.skill)
41
- throw new UsageError("--workspace only applies with --skill; without it, init uses or creates this repo's Workspace.");
42
- const cwd = await realpath(process.cwd());
43
- const repoRoot = (await gitTopLevel(cwd)) ?? cwd;
44
- const lines = await init({ repoRoot, cwd, skillOnly: values.skill, ...(values.workspace === undefined ? {} : { workspace: values.workspace }) });
45
- process.stdout.write(lines.join("\n") + "\n");
46
- return OK;
47
- }
48
- if (command === "version") {
49
- const { values } = parseCommand("version", rest);
50
- if (values.format !== "text" && values.format !== "json")
51
- throw new UsageError(`Unknown format "${values.format}"; use text or json.`);
52
- const { version } = JSON.parse(await readFile(PACKAGE_JSON, "utf8"));
53
- process.stdout.write(values.format === "json" ? JSON.stringify({ version, schemaVersion: SCHEMA_VERSION }) + "\n" : `archidocs ${version} (Bundle schemaVersion ${SCHEMA_VERSION})\n`);
54
- return OK;
55
- }
56
- if (command === "guide") {
57
- const { positionals } = parseCommand("guide", rest);
58
- if (positionals.length > 1)
59
- throw new UsageError(`Give one topic at a time; got ${positionals.join(", ")}.`);
60
- const guide = await authoringGuide(positionals[0]);
61
- if (!guide.ok)
62
- throw new UsageError(guide.message);
63
- process.stdout.write(guide.text);
64
- return OK;
65
- }
66
- if (command === "check") {
67
- const { values } = parseCommand("check", rest);
68
- const format = values.format;
69
- if (!formats.includes(format))
70
- throw new UsageError(`Unknown format "${values.format}"; use ${formats.join(", ")}.`);
71
- const { issues } = await loadFromCwd();
72
- process.stdout.write(formatIssues(issues, format, { color: useColor() }));
73
- return exitCodeFor(issues, { strict: values.strict });
74
- }
75
- if (command === "build") {
76
- const { values } = parseCommand("build", rest);
77
- if (values.preview && values.keep !== undefined)
78
- throw new UsageError("--keep doesn't apply to --preview, whose site holds just the base and the PR head.");
79
- if (values.preview && values["bundle-only"])
80
- throw new UsageError("--bundle-only doesn't apply to --preview, which writes a site.");
81
- if (values.base !== undefined && !values.preview)
82
- throw new UsageError("--base only applies with --preview.");
83
- const keep = values.keep === undefined ? DEFAULT_KEEP : values.keep === "all" ? "all" : Number(values.keep);
84
- if (keep !== "all" && !(Number.isInteger(keep) && keep >= 0))
85
- throw new UsageError(`--keep "${values.keep}" is not a count or all.`);
86
- if (values["bundle-only"] && values.keep !== undefined)
87
- throw new UsageError("--keep only applies to a site; --bundle-only writes no past Bundles.");
88
- const { bundle, issues } = await loadFromCwd();
89
- if (issues.some((i) => i.severity === "error")) {
90
- process.stdout.write(formatText(issues, { color: useColor() }));
91
- process.stderr.write(`Not writing the ${values["bundle-only"] ? "Bundle" : "site"}: the Workspace has errors.\n`);
92
- return FOUND_ERRORS;
93
- }
94
- // A preview finds both sides before writing anything, so a missing base writes no site.
95
- let preview;
96
- if (values.preview) {
97
- const h = await historyFromCwd();
98
- preview = { h, sides: await previewSides(h, values.base ?? (await defaultBaseBranch(h.repoRoot))) };
99
- }
100
- const out = resolve(values.out);
101
- if (!values["bundle-only"]) {
102
- if (!existsSync(join(VIEWER_DIR, "index.html")))
103
- throw new Error(`The viewer is not built (no ${VIEWER_DIR}); run \`pnpm build\` first.`);
104
- await cp(VIEWER_DIR, out, { recursive: true });
105
- // The viewer's exports name the Workspace as `archidocs export` does: by its repo's folder.
106
- const root = await workspaceRoot(process.cwd());
107
- await writeFile(join(out, "site.json"), JSON.stringify({ workspace: await workspaceName(root) }) + "\n");
108
- }
109
- await mkdir(out, { recursive: true });
110
- await writeFile(join(out, "workspace.bundle.json"), serializeBundle(bundle));
111
- if (preview) {
112
- const { base, baseSha, headSha } = await publishPreview(preview.h, out, preview.sides, bundle);
113
- process.stdout.write(`Wrote the preview site to ${values.out}: Compare origin/${base} (${baseSha.slice(0, 7)}) → PR (${headSha.slice(0, 7)})\n`);
114
- return OK;
115
- }
116
- if (!values["bundle-only"])
117
- await writeSiteHistory(out, keep);
118
- process.stdout.write(values["bundle-only"] ? `Wrote ${join(values.out, "workspace.bundle.json")}\n` : `Wrote the site to ${values.out}\n`);
119
- return OK;
120
- }
121
- if (command === "dev") {
122
- const { values } = parseCommand("dev", rest);
123
- const port = values.port === undefined ? DEFAULT_DEV_PORT : Number(values.port);
124
- if (!Number.isInteger(port) || port < 0 || port > 65535)
125
- throw new UsageError(`--port "${values.port}" is not a port.`);
126
- if (!existsSync(join(VIEWER_DIR, "index.html")))
127
- throw new Error(`The viewer is not built (no ${VIEWER_DIR}); run \`pnpm build\` first.`);
128
- const root = await workspaceRoot(values.workspace === undefined ? process.cwd() : resolve(values.workspace));
129
- const color = useColor();
130
- const dev = await serveDev({
131
- root,
132
- viewerDir: VIEWER_DIR,
133
- workspace: await workspaceName(root),
134
- port,
135
- ...(values.host === undefined ? {} : { host: values.host }),
136
- onLoad: ({ issues, kept, first }) => {
137
- const shown = issues.filter((i) => i.severity === "error" || first);
138
- if (shown.length > 0)
139
- process.stdout.write(formatText(shown, { color }));
140
- if (kept)
141
- process.stderr.write("The Workspace has errors; still serving the last good Bundle.\n");
142
- else if (!first)
143
- process.stderr.write(`Reloaded the Workspace (${new Date().toLocaleTimeString()})\n`);
144
- },
145
- }).catch((e) => {
146
- if (e.code === "EADDRINUSE")
147
- throw new UsageError(`Port ${port} is in use; pick another with --port.`);
148
- throw e;
149
- });
150
- process.stderr.write(`Archidocs dev server on ${dev.url} (watching ${root}; Ctrl+C to stop)\n`);
151
- return OK;
152
- }
153
- if (command === "export") {
154
- const { values, positionals } = parseCommand("export", rest);
155
- const allSaved = values["all-saved"];
156
- const [viewId, ...extra] = positionals;
157
- if (allSaved && viewId !== undefined)
158
- throw new UsageError("Give a View or --all-saved, not both.");
159
- if (allSaved && values.out === undefined)
160
- throw new UsageError("--all-saved needs --out <dir> for the pictures.");
161
- if (!allSaved && viewId === undefined)
162
- throw new UsageError("Give the View to export, such as c1 or c2/<system>, or --all-saved.");
163
- if (extra.length > 0)
164
- throw new UsageError(`Export one View at a time; got ${positionals.join(", ")}.`);
165
- const format = values.format;
166
- if (format !== "svg" && format !== "png")
167
- throw new UsageError(`Unknown format "${format}"; use svg or png.`);
168
- const direction = values.direction;
169
- if (direction !== undefined && !directions.includes(direction))
170
- throw new UsageError(`Unknown direction "${direction}"; use ${directions.join(", ")}.`);
171
- const theme = values.theme;
172
- if (!themes.includes(theme))
173
- throw new UsageError(`Unknown theme "${values.theme}"; use ${themes.join(" or ")}.`);
174
- const { label } = values;
175
- const root = await workspaceRoot(process.cwd());
176
- const { bundle, issues } = await loadFromCwd();
177
- if (issues.some((i) => i.severity === "error")) {
178
- process.stdout.write(formatText(issues, { color: useColor() }));
179
- process.stderr.write("Not exporting: the Workspace has errors.\n");
180
- return FOUND_ERRORS;
181
- }
182
- const workspace = await workspaceName(root);
183
- const fileName = (id) => `${id.replace(/[/:]/g, "-")}.${format}`;
184
- /** Lays out and draws one View; `--direction` wins over a Saved View's own. */
185
- const source = { workspace, commit: bundle.commit, date: bundle.builtAt };
186
- const write = async (svg, out) => {
187
- await writeFile(resolve(out), format === "svg" ? svg : await renderPngInNode(svg));
188
- process.stdout.write(`Wrote ${out}\n`);
189
- };
190
- /** Lays out and draws one View: a Dynamic View as a sequence chart, any other as a diagram. */
191
- const draw = async (view, out) => {
192
- if (view.kind === "dynamic")
193
- return write(renderSequenceSvg({ bundle, view, source, theme, label }), out);
194
- const chosen = direction ?? view.direction;
195
- const layout = await layoutView(view, chosen === undefined ? {} : { direction: chosen });
196
- await write(renderSvg({ bundle, view, layout, source, theme, label }), out);
197
- };
198
- const resolveAny = (id) => resolveDynamicView(bundle, id) ?? resolveView(bundle, id);
199
- if (allSaved) {
200
- await mkdir(resolve(values.out), { recursive: true });
201
- for (const saved of bundle.views) {
202
- const view = resolveAny(saved.id);
203
- if (view)
204
- await draw(view, join(values.out, fileName(saved.id)));
205
- }
206
- return OK;
207
- }
208
- const view = resolveAny(viewId);
209
- if (!view)
210
- throw new UsageError(`Unknown View "${viewId}"; Views are c1, c2, c2/<system>, c3/<service with Components>, deployment/<environment> and Saved Views (project:view-id).`);
211
- await draw(view, values.out ?? fileName(viewId));
212
- return OK;
213
- }
214
- if (command === "diff") {
215
- const { values, positionals } = parseCommand("diff", rest);
216
- const format = values.format;
217
- if (!diffFormats.includes(format))
218
- throw new UsageError(`Unknown format "${values.format}"; use ${diffFormats.join(", ")}.`);
219
- const [fromPoint, toPoint, ...extra] = positionals;
220
- if (fromPoint === undefined)
221
- throw new UsageError("Give the point to diff from: a ref or a date.");
222
- if (extra.length > 0)
223
- throw new UsageError(`Give at most two points; got ${positionals.join(", ")}.`);
224
- const h = await historyFromCwd();
225
- /** A point's Bundle; with no point, the working tree's. */
226
- const side = async (point) => {
227
- if (point === undefined)
228
- return [{ point: "working tree", commit: null }, (await loadFromCwd()).bundle];
229
- const commit = await resolvePoint(h.repoRoot, point);
230
- if (!commit)
231
- throw new UsageError(`Unknown ref or date "${point}"; a date resolves to the last default-branch commit at or before it.`);
232
- return [{ point, commit }, (await bundleAt(h, commit)).bundle];
233
- };
234
- const [from, before] = await side(fromPoint);
235
- const [to, after] = await side(toPoint);
236
- process.stdout.write(formatDiff(diff(before, after), from, to, format));
237
- return OK;
238
- }
239
- if (command === "history") {
240
- const [sub, ...args] = rest;
241
- if (sub !== "build")
242
- throw new UsageError(sub ? `Unknown history command "${sub}".` : "Give a history command: build.");
243
- const { values } = parseCommand("history build", args);
244
- const h = await historyFromCwd();
245
- const { revisions, built } = await buildHistory(h, values.since === undefined ? {} : { since: values.since });
246
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
247
- process.stdout.write(`Built ${plural(built, "Revision")}; ${revisions - built} of ${revisions} already built.\n`);
248
- return OK;
249
- }
250
- if (command === "mcp") {
251
- const { values } = parseCommand("mcp", rest);
252
- const viewerUrl = values["viewer-url"];
253
- if (viewerUrl !== undefined && !URL.canParse(viewerUrl))
254
- throw new UsageError(`--viewer-url "${viewerUrl}" is not a URL.`);
255
- if (values.workspace !== undefined && values.bundle !== undefined)
256
- throw new UsageError("Give --workspace or --bundle, not both.");
257
- if (!values.http && values["allow-writes"])
258
- throw new UsageError("--allow-writes only applies with --http; over stdio a checkout already takes writes.");
259
- if (!values.http && (values.host !== undefined || values.port !== undefined))
260
- throw new UsageError("--host and --port only apply with --http.");
261
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
262
- if (!Number.isInteger(port) || port < 0 || port > 65535)
263
- throw new UsageError(`--port "${values.port}" is not a port.`);
264
- const source = values.bundle !== undefined
265
- ? bundleSource({ location: values.bundle })
266
- : checkoutSource({ root: await workspaceRoot(values.workspace === undefined ? process.cwd() : resolve(values.workspace)) });
267
- const options = { source, ...(viewerUrl === undefined ? {} : { viewerUrl }) };
268
- if (values.http) {
269
- const http = await serveHttp({ ...options, port, allowWrites: values["allow-writes"], ...(values.host === undefined ? {} : { host: values.host }) });
270
- process.stderr.write(`Archidocs MCP server on ${http.url} (writes ${values["allow-writes"] && source.writesAllowed ? "allowed" : "off"})\n`);
271
- return OK;
272
- }
273
- // stdout carries the protocol; the server runs until the client closes stdin.
274
- serveStdio(() => createServer(options));
275
- return OK;
276
- }
277
- throw new UsageError(command ? `Unknown command "${command}".` : "No command given.");
278
- }
279
- /** Colour only on a terminal; `NO_COLOR` turns it off and `FORCE_COLOR` on. */
280
- function useColor() {
281
- const { NO_COLOR, FORCE_COLOR } = process.env;
282
- if (NO_COLOR)
283
- return false;
284
- if (FORCE_COLOR !== undefined)
285
- return FORCE_COLOR !== "0";
286
- return process.stdout.isTTY === true;
287
- }
288
- /** How a picture's source line names the Workspace: its git repo's folder, else the Workspace root's. */
289
- async function workspaceName(root) {
290
- return basename((await gitTopLevel(root)) ?? root);
291
- }
292
- async function workspaceRoot(start) {
293
- const root = await findWorkspaceRoot(nodeFileSystem(), start);
294
- if (!root)
295
- throw new UsageError("No workspace.yaml found in this folder, its archidocs/ folder, or any folder above.");
296
- return root;
297
- }
298
- /** The history of the Workspace found from the current folder; it must be in a git repo. */
299
- async function historyFromCwd() {
300
- const root = await workspaceRoot(process.cwd());
301
- const repoRoot = await gitTopLevel(root);
302
- if (!repoRoot)
303
- throw new UsageError("History needs the Workspace in a git repository.");
304
- return history(repoRoot, await realpath(root));
305
- }
306
- /** The site's past Bundles and Revision index; outside git, an empty index, so the viewer knows there is no history. */
307
- async function writeSiteHistory(out, keep) {
308
- const root = await workspaceRoot(process.cwd());
309
- const repoRoot = await gitTopLevel(root);
310
- if (repoRoot)
311
- await publishHistory(history(repoRoot, await realpath(root)), out, { keep });
312
- else {
313
- await mkdir(join(out, "bundles"), { recursive: true });
314
- await writeFile(join(out, "bundles", "index.json"), JSON.stringify({ schemaVersion: SCHEMA_VERSION, revisions: [] }, null, 2) + "\n");
315
- }
316
- }
317
- async function loadFromCwd() {
318
- const root = await workspaceRoot(process.cwd());
319
- const { commit, builtAt } = await gitHead(root);
320
- return load({ fs: nodeFileSystem(), root, commit, builtAt });
321
- }
322
- main(process.argv.slice(2)).then((code) => {
323
- process.exitCode = code;
324
- }, (error) => {
325
- const message = error instanceof Error ? error.message : String(error);
326
- process.stderr.write(`archidocs: ${message}\n`);
327
- if (error instanceof UsageError || error.code?.startsWith("ERR_PARSE_ARGS"))
328
- process.stderr.write(usage);
329
- process.exitCode = COULD_NOT_RUN;
330
- });
2
+ import { run } from "./run.js";
3
+ process.exitCode = await run(process.argv.slice(2), { cwd: process.cwd(), env: process.env, stdout: process.stdout, stderr: process.stderr });
@@ -0,0 +1,18 @@
1
+ /** Where a run of the CLI writes and what it reads instead of `process`: its folder, environment and output streams. */
2
+ export interface Io {
3
+ cwd: string;
4
+ env: Record<string, string | undefined>;
5
+ stdout: {
6
+ write(chunk: string): unknown;
7
+ isTTY?: boolean;
8
+ };
9
+ stderr: {
10
+ write(chunk: string): unknown;
11
+ };
12
+ }
13
+ /**
14
+ * Runs one CLI command and returns its exit code. It never throws: an error is
15
+ * written to `io.stderr` as `archidocs: <message>`, with the usage text for a
16
+ * usage error, and returns the could-not-run code.
17
+ */
18
+ export declare function run(argv: string[], io: Io): Promise<number>;
@@ -0,0 +1,283 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, realpath } from "node:fs/promises";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { directions } from "../render/layout.js";
6
+ import { themes } from "../render/tokens.js";
7
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
8
+ import { gitTopLevel } from "../git.js";
9
+ import { findCheckout } from "../workspace/index.js";
10
+ import { build, buildHistory, check, diff, exportViews } from "../commands/index.js";
11
+ import { bundleSource, checkoutSource, createServer, DEFAULT_PORT, serveHttp } from "../mcp/index.js";
12
+ import { authoringGuide } from "../guide/index.js";
13
+ import { EXIT, NO_WORKSPACE, parseCommand, usageText } from "./commands.js";
14
+ import { init } from "./init.js";
15
+ import { DEFAULT_DEV_PORT, serveDev } from "./dev.js";
16
+ import { exitCodeFor, formatIssues, formats, formatText } from "./format.js";
17
+ import { DEFAULT_KEEP, pointMessage } from "../history/index.js";
18
+ import { LATEST_BUNDLE_PATH } from "../revisions/index.js";
19
+ import { SCHEMA_VERSION } from "../schema/bundle.js";
20
+ import { diffFormats, formatDiff } from "./diff-format.js";
21
+ /** Exit codes, shared with the command definitions that document them: 0 no errors, 1 errors found (or any warning with `--strict`), 2 could not run. */
22
+ const { ok: OK, foundErrors: FOUND_ERRORS, couldNotRun: COULD_NOT_RUN } = EXIT;
23
+ class UsageError extends Error {
24
+ }
25
+ /**
26
+ * The prebuilt viewer, which `build --out` copies as is. The CLI runs from
27
+ * dist/cli/ when installed and from src/cli/ in this repo; both sit two
28
+ * levels below the package root, whose dist/viewer/ holds the viewer.
29
+ */
30
+ const VIEWER_DIR = fileURLToPath(new URL("../../dist/viewer/", import.meta.url));
31
+ /** The package's own package.json, two levels up from dist/cli/ or src/cli/ like the viewer. */
32
+ const PACKAGE_JSON = fileURLToPath(new URL("../../package.json", import.meta.url));
33
+ const usage = usageText();
34
+ const NOT_IN_GIT = "History needs the Workspace in a git repository.";
35
+ const viewerMissing = (viewerDir) => `The viewer is not built (no ${viewerDir}); run \`pnpm build\` first.`;
36
+ /**
37
+ * Runs one CLI command and returns its exit code. It never throws: an error is
38
+ * written to `io.stderr` as `archidocs: <message>`, with the usage text for a
39
+ * usage error, and returns the could-not-run code.
40
+ */
41
+ export async function run(argv, io) {
42
+ try {
43
+ return await main(argv, io);
44
+ }
45
+ catch (error) {
46
+ const message = error instanceof Error ? error.message : String(error);
47
+ io.stderr.write(`archidocs: ${message}\n`);
48
+ if (error instanceof UsageError || error.code?.startsWith("ERR_PARSE_ARGS"))
49
+ io.stderr.write(usage);
50
+ return COULD_NOT_RUN;
51
+ }
52
+ }
53
+ async function main(argv, io) {
54
+ const [command, ...rest] = argv;
55
+ if (command === "init") {
56
+ const { values } = parseCommand("init", rest);
57
+ if (values.workspace !== undefined && !values.skill)
58
+ throw new UsageError("--workspace only applies with --skill; without it, init uses or creates this repo's Workspace.");
59
+ const cwd = await realpath(io.cwd);
60
+ const repoRoot = (await gitTopLevel(cwd)) ?? cwd;
61
+ const lines = await init({ repoRoot, cwd, skillOnly: values.skill, ...(values.workspace === undefined ? {} : { workspace: values.workspace }) });
62
+ io.stdout.write(lines.join("\n") + "\n");
63
+ return OK;
64
+ }
65
+ if (command === "version") {
66
+ const { values } = parseCommand("version", rest);
67
+ if (values.format !== "text" && values.format !== "json")
68
+ throw new UsageError(`Unknown format "${values.format}"; use text or json.`);
69
+ const { version } = JSON.parse(await readFile(PACKAGE_JSON, "utf8"));
70
+ io.stdout.write(values.format === "json" ? JSON.stringify({ version, schemaVersion: SCHEMA_VERSION }) + "\n" : `archidocs ${version} (Bundle schemaVersion ${SCHEMA_VERSION})\n`);
71
+ return OK;
72
+ }
73
+ if (command === "guide") {
74
+ const { positionals } = parseCommand("guide", rest);
75
+ if (positionals.length > 1)
76
+ throw new UsageError(`Give one topic at a time; got ${positionals.join(", ")}.`);
77
+ const guide = await authoringGuide(positionals[0]);
78
+ if (!guide.ok)
79
+ throw new UsageError(guide.message);
80
+ io.stdout.write(guide.text);
81
+ return OK;
82
+ }
83
+ if (command === "check") {
84
+ const { values } = parseCommand("check", rest);
85
+ const format = values.format;
86
+ if (!formats.includes(format))
87
+ throw new UsageError(`Unknown format "${values.format}"; use ${formats.join(", ")}.`);
88
+ const { issues } = await check(await checkoutFrom(io.cwd));
89
+ io.stdout.write(formatIssues(issues, format, { color: useColor(io) }));
90
+ return exitCodeFor(issues, { strict: values.strict });
91
+ }
92
+ if (command === "build") {
93
+ const { values } = parseCommand("build", rest);
94
+ if (values.preview && values.keep !== undefined)
95
+ throw new UsageError("--keep doesn't apply to --preview, whose site holds just the base and the PR head.");
96
+ if (values.preview && values["bundle-only"])
97
+ throw new UsageError("--bundle-only doesn't apply to --preview, which writes a site.");
98
+ if (values.base !== undefined && !values.preview)
99
+ throw new UsageError("--base only applies with --preview.");
100
+ const keep = values.keep === undefined ? DEFAULT_KEEP : values.keep === "all" ? "all" : Number(values.keep);
101
+ if (keep !== "all" && !(Number.isInteger(keep) && keep >= 0))
102
+ throw new UsageError(`--keep "${values.keep}" is not a count or all.`);
103
+ if (values["bundle-only"] && values.keep !== undefined)
104
+ throw new UsageError("--keep only applies to a site; --bundle-only writes no past Bundles.");
105
+ const result = await build(await checkoutFrom(io.cwd), {
106
+ out: resolve(io.cwd, values.out),
107
+ viewerDir: VIEWER_DIR,
108
+ keep,
109
+ bundleOnly: values["bundle-only"],
110
+ ...(values.preview ? { preview: values.base === undefined ? {} : { base: values.base } } : {}),
111
+ });
112
+ switch (result.kind) {
113
+ case "errors":
114
+ io.stdout.write(formatText(result.issues, { color: useColor(io) }));
115
+ io.stderr.write(`Not writing the ${values["bundle-only"] ? "Bundle" : "site"}: the Workspace has errors.\n`);
116
+ return FOUND_ERRORS;
117
+ case "not-in-git":
118
+ throw new UsageError(NOT_IN_GIT);
119
+ case "viewer-missing":
120
+ throw new Error(viewerMissing(result.viewerDir));
121
+ case "preview":
122
+ io.stdout.write(`Wrote the preview site to ${values.out}: Compare origin/${result.base} (${result.baseSha.slice(0, 7)}) → PR (${result.headSha.slice(0, 7)})\n`);
123
+ return OK;
124
+ case "bundle":
125
+ io.stdout.write(`Wrote ${join(values.out, LATEST_BUNDLE_PATH)}\n`);
126
+ return OK;
127
+ case "site":
128
+ io.stdout.write(`Wrote the site to ${values.out}\n`);
129
+ return OK;
130
+ }
131
+ }
132
+ if (command === "dev") {
133
+ const { values } = parseCommand("dev", rest);
134
+ const port = values.port === undefined ? DEFAULT_DEV_PORT : Number(values.port);
135
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
136
+ throw new UsageError(`--port "${values.port}" is not a port.`);
137
+ if (!existsSync(join(VIEWER_DIR, "index.html")))
138
+ throw new Error(viewerMissing(VIEWER_DIR));
139
+ const checkout = await checkoutFrom(values.workspace === undefined ? io.cwd : resolve(io.cwd, values.workspace));
140
+ const color = useColor(io);
141
+ const dev = await serveDev({
142
+ checkout,
143
+ viewerDir: VIEWER_DIR,
144
+ port,
145
+ ...(values.host === undefined ? {} : { host: values.host }),
146
+ onLoad: ({ issues, kept, first }) => {
147
+ const shown = issues.filter((i) => i.severity === "error" || first);
148
+ if (shown.length > 0)
149
+ io.stdout.write(formatText(shown, { color }));
150
+ if (kept)
151
+ io.stderr.write("The Workspace has errors; still serving the last good Bundle.\n");
152
+ else if (!first)
153
+ io.stderr.write(`Reloaded the Workspace (${new Date().toLocaleTimeString()})\n`);
154
+ },
155
+ }).catch((e) => {
156
+ if (e.code === "EADDRINUSE")
157
+ throw new UsageError(`Port ${port} is in use; pick another with --port.`);
158
+ throw e;
159
+ });
160
+ io.stderr.write(`Archidocs dev server on ${dev.url} (watching ${checkout.root}; Ctrl+C to stop)\n`);
161
+ return OK;
162
+ }
163
+ if (command === "export") {
164
+ const { values, positionals } = parseCommand("export", rest);
165
+ const allSaved = values["all-saved"];
166
+ const [viewId, ...extra] = positionals;
167
+ if (allSaved && viewId !== undefined)
168
+ throw new UsageError("Give a View or --all-saved, not both.");
169
+ if (allSaved && values.out === undefined)
170
+ throw new UsageError("--all-saved needs --out <dir> for the pictures.");
171
+ if (!allSaved && viewId === undefined)
172
+ throw new UsageError("Give the View to export, such as c1 or c2/<system>, or --all-saved.");
173
+ if (extra.length > 0)
174
+ throw new UsageError(`Export one View at a time; got ${positionals.join(", ")}.`);
175
+ const format = values.format;
176
+ if (format !== "svg" && format !== "png")
177
+ throw new UsageError(`Unknown format "${format}"; use svg or png.`);
178
+ const direction = values.direction;
179
+ if (direction !== undefined && !directions.includes(direction))
180
+ throw new UsageError(`Unknown direction "${direction}"; use ${directions.join(", ")}.`);
181
+ const theme = values.theme;
182
+ if (!themes.includes(theme))
183
+ throw new UsageError(`Unknown theme "${values.theme}"; use ${themes.join(" or ")}.`);
184
+ const { label } = values;
185
+ const result = await exportViews(await checkoutFrom(io.cwd), {
186
+ views: allSaved ? "all-saved" : [viewId],
187
+ format,
188
+ ...(direction === undefined ? {} : { direction }),
189
+ theme,
190
+ ...(label === undefined ? {} : { label }),
191
+ out: allSaved ? resolve(io.cwd, values.out) : io.cwd,
192
+ ...(!allSaved && values.out !== undefined ? { file: resolve(io.cwd, values.out) } : {}),
193
+ });
194
+ switch (result.kind) {
195
+ case "errors":
196
+ io.stdout.write(formatText(result.issues, { color: useColor(io) }));
197
+ io.stderr.write("Not exporting: the Workspace has errors.\n");
198
+ return FOUND_ERRORS;
199
+ case "unknown-view":
200
+ throw new UsageError(`Unknown View "${result.id}"; Views are c1, c2, c2/<system>, c3/<service with Components>, deployment/<environment> and Saved Views (project:view-id).`);
201
+ case "written":
202
+ // Each picture as the user named it: under --out, or --out itself, or its own name in the current folder.
203
+ for (const { path } of result.files)
204
+ io.stdout.write(`Wrote ${allSaved ? join(values.out, basename(path)) : (values.out ?? basename(path))}\n`);
205
+ return OK;
206
+ }
207
+ }
208
+ if (command === "diff") {
209
+ const { values, positionals } = parseCommand("diff", rest);
210
+ const format = values.format;
211
+ if (!diffFormats.includes(format))
212
+ throw new UsageError(`Unknown format "${values.format}"; use ${diffFormats.join(", ")}.`);
213
+ const [fromPoint, toPoint, ...extra] = positionals;
214
+ if (fromPoint === undefined)
215
+ throw new UsageError("Give the point to diff from: a ref or a date.");
216
+ if (extra.length > 0)
217
+ throw new UsageError(`Give at most two points; got ${positionals.join(", ")}.`);
218
+ const result = await diff(await checkoutFrom(io.cwd), toPoint === undefined ? { from: fromPoint } : { from: fromPoint, to: toPoint });
219
+ if (result.kind === "not-in-git")
220
+ throw new UsageError(NOT_IN_GIT);
221
+ if (result.kind === "unknown-point")
222
+ throw new UsageError(pointMessage(result.point, result.failure));
223
+ io.stdout.write(formatDiff(result.changes, result.from, result.to, format));
224
+ return OK;
225
+ }
226
+ if (command === "history") {
227
+ const [sub, ...args] = rest;
228
+ if (sub !== "build")
229
+ throw new UsageError(sub ? `Unknown history command "${sub}".` : "Give a history command: build.");
230
+ const { values } = parseCommand("history build", args);
231
+ const result = await buildHistory(await checkoutFrom(io.cwd), values.since === undefined ? {} : { since: values.since });
232
+ if (result.kind === "not-in-git")
233
+ throw new UsageError(NOT_IN_GIT);
234
+ const { revisions, built } = result;
235
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
236
+ io.stdout.write(`Built ${plural(built, "Revision")}; ${revisions - built} of ${revisions} already built.\n`);
237
+ return OK;
238
+ }
239
+ if (command === "mcp") {
240
+ const { values } = parseCommand("mcp", rest);
241
+ const viewerUrl = values["viewer-url"];
242
+ if (viewerUrl !== undefined && !URL.canParse(viewerUrl))
243
+ throw new UsageError(`--viewer-url "${viewerUrl}" is not a URL.`);
244
+ if (values.workspace !== undefined && values.bundle !== undefined)
245
+ throw new UsageError("Give --workspace or --bundle, not both.");
246
+ if (!values.http && values["allow-writes"])
247
+ throw new UsageError("--allow-writes only applies with --http; over stdio a checkout already takes writes.");
248
+ if (!values.http && (values.host !== undefined || values.port !== undefined))
249
+ throw new UsageError("--host and --port only apply with --http.");
250
+ const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
251
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
252
+ throw new UsageError(`--port "${values.port}" is not a port.`);
253
+ const source = values.bundle !== undefined
254
+ ? bundleSource({ location: /^https?:\/\//i.test(values.bundle) ? values.bundle : resolve(io.cwd, values.bundle) })
255
+ : checkoutSource({ root: (await checkoutFrom(values.workspace === undefined ? io.cwd : resolve(io.cwd, values.workspace))).root });
256
+ const options = { source, ...(viewerUrl === undefined ? {} : { viewerUrl }) };
257
+ if (values.http) {
258
+ const http = await serveHttp({ ...options, port, allowWrites: values["allow-writes"], ...(values.host === undefined ? {} : { host: values.host }) });
259
+ io.stderr.write(`Archidocs MCP server on ${http.url} (writes ${values["allow-writes"] && source.writesAllowed ? "allowed" : "off"})\n`);
260
+ return OK;
261
+ }
262
+ // The one command bound to the process: stdout carries the protocol; the server runs until the client closes stdin.
263
+ serveStdio(() => createServer(options));
264
+ return OK;
265
+ }
266
+ throw new UsageError(command ? `Unknown command "${command}".` : "No command given.");
267
+ }
268
+ /** Colour only on a terminal; `NO_COLOR` turns it off and `FORCE_COLOR` on. */
269
+ function useColor(io) {
270
+ const { NO_COLOR, FORCE_COLOR } = io.env;
271
+ if (NO_COLOR)
272
+ return false;
273
+ if (FORCE_COLOR !== undefined)
274
+ return FORCE_COLOR !== "0";
275
+ return io.stdout.isTTY === true;
276
+ }
277
+ /** The Checkout whose Workspace holds `start`, found by walking up from it. */
278
+ async function checkoutFrom(start) {
279
+ const checkout = await findCheckout(start);
280
+ if (!checkout)
281
+ throw new UsageError(NO_WORKSPACE);
282
+ return checkout;
283
+ }