@open-document/core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/{build-BHFGY8eF.js → build-CbgIk6bA.js} +1 -1
  2. package/dist/{check-UEBmDfT_.js → check-BTroj-5Z.js} +3 -3
  3. package/dist/cli/bin.js +58 -34
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-B_pdNbYg.js → config-DKKNIbvO.js} +1458 -983
  6. package/dist/{context-BM9_-u9P.js → context-DXNP8v9I.js} +3 -2
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-DX3QMIRi.js → dev-YXumw5iX.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-DayvbXfX.js → diff-CTFfU4Tz.js} +2 -2
  11. package/dist/{export-BPsXj1i6.js → export-D2QLtF84.js} +11 -4
  12. package/dist/flow-CS5apebG.d.ts +252 -0
  13. package/dist/{import-71wlAsrd.js → import-CcmrFetU.js} +3 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +945 -104
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +112 -3
  18. package/dist/ops/index.js +3 -3
  19. package/dist/{ops-BUo67DaP.js → ops-DmEecq1k.js} +86 -164
  20. package/dist/package-version-C89gtYSk.js +36 -0
  21. package/dist/{preview-D3m1-gUL.js → preview-_mHpBhMk.js} +1 -1
  22. package/dist/templates-MMblHwmT.js +34 -0
  23. package/dist/vite/index.d.ts +1 -1
  24. package/dist/vite/index.js +2 -1
  25. package/package.json +2 -1
  26. package/skills/apply-comments/SKILL.md +3 -1
  27. package/skills/create-doc/SKILL.md +2 -0
  28. package/skills/doc-authoring/SKILL.md +17 -16
  29. package/skills/doc-authoring/references/long-form.md +43 -2
  30. package/skills/doc-authoring/references/pagination.md +14 -2
  31. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  32. package/src/app/components/browser/browser-ui.tsx +21 -0
  33. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  34. package/src/app/components/callout.tsx +101 -0
  35. package/src/app/components/changes/changes-overlay.tsx +68 -0
  36. package/src/app/components/changes/changes-panel.tsx +341 -0
  37. package/src/app/components/changes/use-changes.ts +85 -0
  38. package/src/app/components/chart.tsx +191 -33
  39. package/src/app/components/code-block.tsx +249 -0
  40. package/src/app/components/comments/comments-overlay.tsx +50 -0
  41. package/src/app/components/comments/comments-panel.tsx +272 -0
  42. package/src/app/components/comments/use-comments.ts +61 -0
  43. package/src/app/components/data-table.tsx +146 -18
  44. package/src/app/components/doc-sidebar.tsx +32 -2
  45. package/src/app/components/flow-page.tsx +57 -8
  46. package/src/app/components/inspector/field-source.tsx +41 -0
  47. package/src/app/components/inspector/inspector.tsx +64 -65
  48. package/src/app/components/numbering.tsx +226 -12
  49. package/src/app/components/overlay-frame.tsx +79 -0
  50. package/src/app/components/page-frame.tsx +46 -0
  51. package/src/app/components/page-placement.ts +68 -0
  52. package/src/app/components/record-picker.tsx +79 -0
  53. package/src/app/components/themes/theme-preview.tsx +5 -4
  54. package/src/app/lib/agent-bridge.ts +29 -1
  55. package/src/app/lib/chart.test.ts +15 -0
  56. package/src/app/lib/chart.ts +134 -9
  57. package/src/app/lib/diagnostics.ts +45 -1
  58. package/src/app/lib/docx/ooxml.test.ts +24 -1
  59. package/src/app/lib/docx/ooxml.ts +27 -1
  60. package/src/app/lib/export-docx.ts +3 -1
  61. package/src/app/lib/export-dom.ts +17 -3
  62. package/src/app/lib/export-html.ts +4 -2
  63. package/src/app/lib/export-image.ts +2 -1
  64. package/src/app/lib/export-pdf.ts +9 -1
  65. package/src/app/lib/flow-measure.test.ts +30 -0
  66. package/src/app/lib/flow-measure.ts +68 -14
  67. package/src/app/lib/flow.test.ts +20 -1
  68. package/src/app/lib/flow.ts +120 -20
  69. package/src/app/lib/i18n-ja/browser.ts +10 -0
  70. package/src/app/lib/i18n-ja/doc.ts +4 -0
  71. package/src/app/lib/i18n-ja/panels.ts +40 -0
  72. package/src/app/lib/i18n-ko/browser.ts +10 -0
  73. package/src/app/lib/i18n-ko/doc.ts +4 -0
  74. package/src/app/lib/i18n-ko/panels.ts +39 -0
  75. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  76. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  77. package/src/app/lib/i18n-zh-cn/panels.ts +38 -0
  78. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  79. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  80. package/src/app/lib/i18n-zh-tw/panels.ts +38 -0
  81. package/src/app/lib/labels.ts +29 -10
  82. package/src/app/lib/records.test.ts +38 -0
  83. package/src/app/lib/records.ts +127 -0
  84. package/src/app/lib/sdk.ts +35 -0
  85. package/src/app/lib/use-doc-module.ts +7 -0
  86. package/src/app/lib/use-doc-pages.ts +38 -17
  87. package/src/app/routes/doc.tsx +275 -13
  88. package/src/app/routes/home.tsx +30 -5
  89. package/src/app/styles.css +23 -0
  90. package/templates/blank/index.tsx +63 -0
  91. package/templates/blank/template.json +6 -0
  92. package/templates/certificate/data/recipients.csv +4 -0
  93. package/templates/certificate/index.tsx +128 -0
  94. package/templates/certificate/template.json +6 -0
  95. package/templates/letter/index.tsx +106 -0
  96. package/templates/letter/template.json +5 -0
  97. package/templates/meeting-notes/index.tsx +194 -0
  98. package/templates/meeting-notes/template.json +6 -0
  99. package/templates/proposal/index.tsx +264 -0
  100. package/templates/proposal/template.json +6 -0
  101. package/templates/report/data/metrics.csv +5 -0
  102. package/templates/report/index.tsx +224 -0
  103. package/templates/report/template.json +6 -0
  104. package/dist/config-P61niZMf.d.ts +0 -24
  105. package/dist/sdk-CpDEGRIo.d.ts +0 -138
@@ -1,305 +1,19 @@
1
- import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
1
+ import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-CKf3ptOE.js";
2
+ import { t as corePackageRoot } from "./package-version-C89gtYSk.js";
3
+ import { n as loadUserConfig, r as openDocPlugin, t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
2
4
  import chalk from "chalk";
3
5
  import path from "node:path";
4
6
  import { fileURLToPath, pathToFileURL } from "node:url";
5
7
  import fs from "node:fs/promises";
6
- import { existsSync, readFileSync } from "node:fs";
8
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
7
9
  import fg from "fast-glob";
8
- import { loadConfigFromFile, normalizePath } from "vite";
10
+ import { normalizePath } from "vite";
11
+ import { execFile } from "node:child_process";
12
+ import { promisify } from "node:util";
13
+ import { parse } from "@babel/parser";
14
+ import { createHash, randomUUID } from "node:crypto";
9
15
  import tailwindcss from "@tailwindcss/vite";
10
16
  import react from "@vitejs/plugin-react";
11
- import { parse } from "@babel/parser";
12
- import { randomUUID } from "node:crypto";
13
- //#region src/vite/open-doc-plugin.ts
14
- const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
15
- const CONFIG_FILE = "open-doc.config.ts";
16
- const DOCS_VMOD = "virtual:open-doc/docs";
17
- const CONFIG_VMOD = "virtual:open-doc/config";
18
- const FOLDERS_VMOD = "virtual:open-doc/folders";
19
- async function readFoldersManifest(file) {
20
- try {
21
- const parsed = JSON.parse(await fs.readFile(file, "utf8"));
22
- return {
23
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
24
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
25
- };
26
- } catch (err) {
27
- if (err.code === "ENOENT") return {
28
- folders: [],
29
- assignments: {}
30
- };
31
- throw err;
32
- }
33
- }
34
- function resolved$1(id) {
35
- return `\0${id}`;
36
- }
37
- async function findDocs(userCwd, docsDir) {
38
- const abs = path.resolve(userCwd, docsDir);
39
- if (!existsSync(abs)) return [];
40
- return (await fg("*/index.{tsx,jsx,ts,js}", {
41
- cwd: abs,
42
- absolute: true,
43
- onlyFiles: true
44
- })).sort();
45
- }
46
- function toId(absFile, docsRoot) {
47
- return path.relative(docsRoot, absFile).split(path.sep)[0];
48
- }
49
- const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
50
- const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
51
- const META_TITLE_RE = /(?:^|[\s,{])title\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/;
52
- /**
53
- * Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
54
- * every discovery pass, and the fields it needs (sort order, theme back-link,
55
- * the title search and sorting use without loading every document) are
56
- * contractually string literals.
57
- */
58
- function extractMeta(src) {
59
- const empty = {
60
- theme: null,
61
- createdAt: null,
62
- title: null
63
- };
64
- const metaStart = src.search(/export\s+const\s+meta\b/);
65
- if (metaStart === -1) return empty;
66
- const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
67
- if (openBrace === -1) return empty;
68
- let depth = 0;
69
- let closeBrace = -1;
70
- for (let i = openBrace; i < src.length; i++) {
71
- const ch = src[i];
72
- if (ch === "{") depth++;
73
- else if (ch === "}") {
74
- depth--;
75
- if (depth === 0) {
76
- closeBrace = i;
77
- break;
78
- }
79
- }
80
- }
81
- if (closeBrace === -1) return empty;
82
- const body = src.slice(openBrace + 1, closeBrace);
83
- return {
84
- theme: body.match(META_THEME_RE)?.[1] ?? null,
85
- createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null,
86
- title: unescapeLiteral(body.match(META_TITLE_RE)?.[2] ?? null)
87
- };
88
- }
89
- function unescapeLiteral(raw) {
90
- return raw === null ? null : raw.replace(/\\(.)/g, "$1");
91
- }
92
- function parseCreatedAtMs(iso) {
93
- if (!iso) return null;
94
- const ms = Date.parse(iso);
95
- return Number.isFinite(ms) ? ms : null;
96
- }
97
- async function readMeta(abs) {
98
- try {
99
- return extractMeta(await fs.readFile(abs, "utf8"));
100
- } catch {
101
- return {
102
- theme: null,
103
- createdAt: null,
104
- title: null
105
- };
106
- }
107
- }
108
- const warnedInvalidDocIds = /* @__PURE__ */ new Set();
109
- async function generateDocsModule(files, docsRoot, isDev) {
110
- const scanned = await Promise.all(files.map(async (abs) => {
111
- const meta = await readMeta(abs);
112
- return {
113
- id: toId(abs, docsRoot),
114
- importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
115
- theme: meta.theme,
116
- title: meta.title,
117
- createdAt: parseCreatedAtMs(meta.createdAt)
118
- };
119
- }));
120
- const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
121
- const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
122
- const ids = JSON.stringify(entries.map((e) => e.id).sort());
123
- const createdAtMap = {};
124
- const themesMap = {};
125
- const titlesMap = {};
126
- for (const e of entries) {
127
- if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
128
- if (e.theme) themesMap[e.id] = e.theme;
129
- if (e.title) titlesMap[e.id] = e.title;
130
- }
131
- const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
132
- const devRuntime = isDev ? `
133
- const docImportTokens = ${importTokens};
134
- if (import.meta.hot) {
135
- import.meta.hot.on('open-doc:doc-changed', (data) => {
136
- const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
137
- const token = Date.now();
138
- for (const id of ids) {
139
- if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
140
- }
141
- });
142
- }
143
- ` : "";
144
- const cases = entries.map((e) => {
145
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + docImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
146
- return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
147
- }).join("\n");
148
- return {
149
- code: `// virtual:open-doc/docs — generated
150
- export const docIds = ${ids};
151
- export const docCreatedAt = ${JSON.stringify(createdAtMap)};
152
- export const docThemes = ${JSON.stringify(themesMap)};
153
- export const docTitles = ${JSON.stringify(titlesMap)};
154
- ${devRuntime}
155
-
156
- export async function loadDoc(id) {
157
- switch (id) {
158
- ${cases}
159
- default: throw new Error('Document not found: ' + id);
160
- }
161
- }
162
- `,
163
- ignored
164
- };
165
- }
166
- function openDocPlugin(opts) {
167
- const { userCwd, config, coreVersion } = opts;
168
- const docsDir = config.docsDir ?? "docs";
169
- const docsRoot = path.resolve(userCwd, docsDir);
170
- const foldersManifestPath = path.join(docsRoot, ".folders.json");
171
- let isDev = false;
172
- const docIdForEntry = (p) => {
173
- const rel = path.relative(docsRoot, p);
174
- if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
175
- const parts = rel.split(path.sep);
176
- if (parts.length !== 2) return null;
177
- if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
178
- return parts[0];
179
- };
180
- let docChangeTimer = null;
181
- const pendingDocChanges = /* @__PURE__ */ new Set();
182
- const queueDocChanged = (server, id) => {
183
- pendingDocChanges.add(id);
184
- if (docChangeTimer) clearTimeout(docChangeTimer);
185
- docChangeTimer = setTimeout(() => {
186
- docChangeTimer = null;
187
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
188
- if (mod) server.moduleGraph.invalidateModule(mod);
189
- const docIds = Array.from(pendingDocChanges);
190
- pendingDocChanges.clear();
191
- server.ws.send({
192
- type: "custom",
193
- event: "open-doc:doc-changed",
194
- data: { docIds }
195
- });
196
- }, 100);
197
- };
198
- return {
199
- name: "open-doc",
200
- config(_c, env) {
201
- isDev = env.command === "serve";
202
- return { server: { fs: { allow: [userCwd] } } };
203
- },
204
- resolveId(id) {
205
- if (id === DOCS_VMOD) return resolved$1(DOCS_VMOD);
206
- if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
207
- if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
208
- return null;
209
- },
210
- async load(id) {
211
- if (id === resolved$1(DOCS_VMOD)) {
212
- const { code, ignored } = await generateDocsModule(await findDocs(userCwd, docsDir), docsRoot, isDev);
213
- for (const docId of ignored) {
214
- if (warnedInvalidDocIds.has(docId)) continue;
215
- warnedInvalidDocIds.add(docId);
216
- this.warn(`Ignoring document folder "${docId}": ids must match ${DOC_ID_RE} (letters, digits, "-", "_"). Rename it under "${docsDir}/" to a kebab-case id so it shows up.`);
217
- }
218
- return code;
219
- }
220
- if (id === resolved$1(CONFIG_VMOD)) {
221
- const userBuild = config.build ?? {};
222
- const build = isDev ? {
223
- showDocBrowser: true,
224
- allowHtmlExport: true
225
- } : {
226
- showDocBrowser: userBuild.showDocBrowser ?? true,
227
- allowHtmlExport: userBuild.allowHtmlExport ?? true
228
- };
229
- return `export default ${JSON.stringify({
230
- ...config,
231
- build,
232
- version: coreVersion
233
- })};\n`;
234
- }
235
- if (id === resolved$1(FOLDERS_VMOD)) {
236
- const manifest = await readFoldersManifest(foldersManifestPath);
237
- return `export default ${JSON.stringify(manifest)};\n`;
238
- }
239
- return null;
240
- },
241
- handleHotUpdate(ctx) {
242
- const docId = docIdForEntry(ctx.file);
243
- if (!docId) return;
244
- queueDocChanged(ctx.server, docId);
245
- return [];
246
- },
247
- configureServer(server) {
248
- const isDocEntry = (p) => docIdForEntry(p) !== null;
249
- let reloadTimer = null;
250
- const reload = () => {
251
- if (reloadTimer) clearTimeout(reloadTimer);
252
- reloadTimer = setTimeout(() => {
253
- reloadTimer = null;
254
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
255
- if (mod) server.moduleGraph.invalidateModule(mod);
256
- server.ws.send({ type: "full-reload" });
257
- }, 150);
258
- };
259
- server.watcher.add(docsRoot);
260
- server.watcher.on("add", (p) => {
261
- if (isDocEntry(p)) reload();
262
- });
263
- server.watcher.on("unlink", (p) => {
264
- if (isDocEntry(p)) reload();
265
- });
266
- server.watcher.on("unlinkDir", (p) => {
267
- if (path.dirname(p) === docsRoot) reload();
268
- });
269
- let foldersTimer = null;
270
- const foldersChanged = () => {
271
- if (foldersTimer) clearTimeout(foldersTimer);
272
- foldersTimer = setTimeout(() => {
273
- foldersTimer = null;
274
- const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
275
- if (mod) server.moduleGraph.invalidateModule(mod);
276
- server.ws.send({
277
- type: "custom",
278
- event: "open-doc:files-changed",
279
- data: {}
280
- });
281
- }, 100);
282
- };
283
- server.watcher.add(foldersManifestPath);
284
- for (const event of [
285
- "add",
286
- "change",
287
- "unlink"
288
- ]) server.watcher.on(event, (p) => {
289
- if (p === foldersManifestPath) foldersChanged();
290
- });
291
- }
292
- };
293
- }
294
- async function loadUserConfig(userCwd) {
295
- const file = path.join(userCwd, CONFIG_FILE);
296
- if (!existsSync(file)) return {};
297
- return (await loadConfigFromFile({
298
- command: "serve",
299
- mode: "development"
300
- }, file, userCwd, "silent"))?.config ?? {};
301
- }
302
- //#endregion
303
17
  //#region src/vite/routes/context.ts
304
18
  function makeContext(opts) {
305
19
  const userCwd = opts.userCwd;
@@ -363,96 +77,881 @@ function resolveDocEntry(docsRoot, docId) {
363
77
  return null;
364
78
  }
365
79
  //#endregion
366
- //#region src/files/assets.ts
367
- const GLOBAL_SCOPE = "@global";
368
- const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
369
- const MIME_BY_EXT = {
370
- png: "image/png",
371
- jpg: "image/jpeg",
372
- jpeg: "image/jpeg",
373
- gif: "image/gif",
374
- svg: "image/svg+xml",
375
- webp: "image/webp",
376
- avif: "image/avif",
377
- ico: "image/x-icon",
378
- pdf: "application/pdf",
379
- woff: "font/woff",
380
- woff2: "font/woff2",
381
- ttf: "font/ttf",
382
- otf: "font/otf",
383
- csv: "text/csv; charset=utf-8",
384
- json: "application/json",
385
- txt: "text/plain; charset=utf-8",
386
- md: "text/markdown; charset=utf-8"
387
- };
388
- function mimeForFilename(name) {
389
- const dot = name.lastIndexOf(".");
390
- if (dot < 0) return "application/octet-stream";
391
- return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
392
- }
393
- function assetCreatedAt(birthtimeMs, mtimeMs) {
394
- return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
395
- }
396
- function validateAssetName(v) {
397
- if (typeof v !== "string") return null;
398
- const trimmed = v.trim();
399
- if (trimmed.length < 1 || trimmed.length > 120) return null;
400
- if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
401
- if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
402
- if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
403
- const dot = trimmed.lastIndexOf(".");
404
- if (dot <= 0 || dot === trimmed.length - 1) return null;
405
- return trimmed;
406
- }
407
- function resolveAssetsDir(docsRoot, docId) {
408
- if (!DOC_ID_RE.test(docId)) return null;
409
- const docDir = path.resolve(docsRoot, docId);
410
- if (!docDir.startsWith(docsRoot + path.sep)) return null;
411
- const assetsDir = path.resolve(docDir, "assets");
412
- if (assetsDir !== path.join(docDir, "assets")) return null;
413
- return assetsDir;
80
+ //#region src/editing/babel-walk.ts
81
+ function parseSource(code) {
82
+ try {
83
+ return parse(code, {
84
+ sourceType: "module",
85
+ plugins: ["typescript", "jsx"],
86
+ errorRecovery: true
87
+ });
88
+ } catch {
89
+ return null;
90
+ }
414
91
  }
415
- function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
416
- if (scope === "@global") return globalAssetsRoot;
417
- return resolveAssetsDir(docsRoot, scope);
92
+ /**
93
+ * `parseSource`, but a source with any recovered error is refused. Reading
94
+ * tolerates a document mid-edit; writing splices text in by AST offset, and a
95
+ * best-guess tree recovered from a syntax error must never decide where.
96
+ */
97
+ function parseStrict(code) {
98
+ const ast = parseSource(code);
99
+ if (!ast) return null;
100
+ return ast.errors && ast.errors.length > 0 ? null : ast;
418
101
  }
419
- function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
420
- if (!validateAssetName(filename)) return null;
421
- const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
422
- if (!dir) return null;
423
- const file = path.resolve(dir, filename);
424
- if (!file.startsWith(dir + path.sep)) return null;
425
- return file;
102
+ function isNode(value) {
103
+ return typeof value === "object" && value !== null && typeof value.type === "string";
426
104
  }
427
- /** How a document imports an asset — the string we look for when counting usages. */
428
- function assetImportPath(scope, filename) {
429
- return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
105
+ /** Depth-first walk over every node; the visitor decides what it cares about. */
106
+ function walkAst(node, visit) {
107
+ if (Array.isArray(node)) {
108
+ for (const child of node) walkAst(child, visit);
109
+ return;
110
+ }
111
+ if (!isNode(node)) return;
112
+ visit(node);
113
+ for (const key of Object.keys(node)) {
114
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
115
+ walkAst(node[key], visit);
116
+ }
430
117
  }
431
- function escapeRegExp(value) {
432
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
118
+ function walkJsx(ast, visit) {
119
+ walkAst(ast, (node) => {
120
+ if (node.type === "JSXElement") visit(node);
121
+ });
433
122
  }
434
123
  /**
435
- * Counts references to an asset in a document's source. Matches the quoted path
436
- * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
437
- * which is every form the authoring skill sanctions.
124
+ * The JSX element whose opening tag starts at this source position.
125
+ *
126
+ * The match is exact on both line and column. Anything looser can resolve to a
127
+ * different element on the same line, and this location decides where an edit
128
+ * gets written — a near miss silently rewrites the wrong text.
438
129
  */
439
- function countAssetUsages(source, importPath) {
440
- const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
441
- return source.match(quoted)?.length ?? 0;
130
+ function findJsxAt(ast, line, column) {
131
+ let found = null;
132
+ walkJsx(ast, (node) => {
133
+ if (found) return;
134
+ const start = node.loc?.start;
135
+ if (start && start.line === line && start.column === column) found = node;
136
+ });
137
+ return found;
442
138
  }
443
- function findReferencedAssets(source, importPaths) {
444
- return importPaths.filter((p) => countAssetUsages(source, p) > 0);
139
+ /**
140
+ * Every JSX element that starts on a line, nearest column first.
141
+ *
142
+ * Columns cannot be trusted for locations derived from React's `_debugSource`:
143
+ * injecting the loc attribute shifts the columns of anything later on the same
144
+ * line, so the offset differs per element. The line survives that, so callers
145
+ * scan the line and pick by content instead.
146
+ */
147
+ function findJsxOnLine(ast, line, column) {
148
+ const hits = [];
149
+ walkJsx(ast, (node) => {
150
+ const start = node.loc?.start;
151
+ if (!start || start.line !== line) return;
152
+ hits.push({
153
+ node,
154
+ distance: Math.abs(start.column - column)
155
+ });
156
+ });
157
+ return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
445
158
  }
446
159
  //#endregion
447
- //#region src/http/request-guard.ts
448
- function firstHeaderValue(value) {
449
- if (Array.isArray(value)) return value[0] ?? null;
450
- return value ?? null;
451
- }
452
- function headerValue(req, name) {
453
- return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
160
+ //#region src/vite/loc-tags-plugin.ts
161
+ const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
162
+ "ImagePlaceholder",
163
+ "Figure",
164
+ "DataTable",
165
+ "Footnote",
166
+ "CodeBlock",
167
+ "Callout"
168
+ ]);
169
+ function taggableName(opening) {
170
+ const name = opening.name;
171
+ if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
172
+ if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
173
+ return null;
454
174
  }
455
- function firstCommaToken(value) {
175
+ function alreadyTagged(opening) {
176
+ return (opening.attributes ?? []).some((attr) => {
177
+ if (attr.type !== "JSXAttribute") return false;
178
+ return attr.name?.name === "data-od-loc";
179
+ });
180
+ }
181
+ function injectLocTags(code) {
182
+ const ast = parseSource(code);
183
+ if (!ast) return null;
184
+ const insertions = [];
185
+ walkJsx(ast, (node) => {
186
+ const opening = node.openingElement;
187
+ if (!opening || !node.loc) return;
188
+ if (!taggableName(opening) || alreadyTagged(opening)) return;
189
+ const nameNode = opening.name;
190
+ insertions.push({
191
+ offset: nameNode.end,
192
+ text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
193
+ });
194
+ });
195
+ if (insertions.length === 0) return null;
196
+ insertions.sort((a, b) => b.offset - a.offset);
197
+ let next = code;
198
+ for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
199
+ return next;
200
+ }
201
+ function isDocSourceFile(id, docsRootPosix) {
202
+ const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
203
+ if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
204
+ if (!filePath.endsWith(".tsx")) return false;
205
+ if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
206
+ return filePath.slice(docsRootPosix.length + 1).includes("/");
207
+ }
208
+ function locTagsPlugin(opts) {
209
+ const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
210
+ return {
211
+ name: "open-doc:loc-tags",
212
+ apply: "serve",
213
+ enforce: "pre",
214
+ transform(code, id) {
215
+ if (!isDocSourceFile(id, docsRoot)) return null;
216
+ const next = injectLocTags(code);
217
+ return next === null ? null : {
218
+ code: next,
219
+ map: null
220
+ };
221
+ }
222
+ };
223
+ }
224
+ //#endregion
225
+ //#region src/ops/changes-diff.ts
226
+ const REVIEW_MARKER = /^\s*\{\/\*\s*@doc-comment\s.*\*\/\}\s*$/;
227
+ /**
228
+ * Drops hunks that only add or remove review comments. A comment is a marker
229
+ * in the source, but it is a note about the document, not a change to it —
230
+ * counting it would put every note left in review on the changes list too.
231
+ */
232
+ function withoutReviewMarkers(files) {
233
+ return files.map((file) => ({
234
+ ...file,
235
+ hunks: file.hunks.filter((hunk) => ![...hunk.removed, ...hunk.added].every((line) => REVIEW_MARKER.test(line)))
236
+ }));
237
+ }
238
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
239
+ function hunkId(file, oldStart, removed, added) {
240
+ return createHash("sha1").update(`${file}\0${oldStart}\0${removed.join("\n")}\0${added.join("\n")}`).digest("hex").slice(0, 12);
241
+ }
242
+ /**
243
+ * `git diff --unified=0 --relative` output, file by file. Paths come back
244
+ * relative to `prefix` — the document's folder — and anything outside it is
245
+ * dropped.
246
+ */
247
+ function parseUnifiedDiff(text, prefix) {
248
+ const files = [];
249
+ let file = null;
250
+ let hunk = null;
251
+ let oldPath = null;
252
+ const strip = (raw) => {
253
+ if (raw === "/dev/null") return null;
254
+ const path = raw.replace(/^[ab]\//, "");
255
+ return path.startsWith(prefix) ? path.slice(prefix.length) : null;
256
+ };
257
+ for (const line of text.split("\n")) {
258
+ if (line.startsWith("diff --git ")) {
259
+ file = null;
260
+ hunk = null;
261
+ oldPath = null;
262
+ continue;
263
+ }
264
+ if (line.startsWith("--- ")) {
265
+ oldPath = line.slice(4);
266
+ continue;
267
+ }
268
+ if (line.startsWith("+++ ")) {
269
+ const before = oldPath === null ? null : strip(oldPath);
270
+ const path = strip(line.slice(4)) ?? before;
271
+ if (path === null) continue;
272
+ file = {
273
+ path,
274
+ status: oldPath === "/dev/null" ? "added" : line.slice(4) === "/dev/null" ? "deleted" : "modified",
275
+ binary: false,
276
+ hunks: []
277
+ };
278
+ files.push(file);
279
+ continue;
280
+ }
281
+ if (line.startsWith("Binary files ")) {
282
+ const match = / and (\S+) differ$/.exec(line);
283
+ const path = match ? strip(match[1]) : null;
284
+ if (path !== null) files.push({
285
+ path,
286
+ status: "modified",
287
+ binary: true,
288
+ hunks: []
289
+ });
290
+ continue;
291
+ }
292
+ const header = HUNK_HEADER.exec(line);
293
+ if (header && file) {
294
+ hunk = {
295
+ id: "",
296
+ oldStart: Number(header[1]),
297
+ oldLines: header[2] === void 0 ? 1 : Number(header[2]),
298
+ newStart: Number(header[3]),
299
+ newLines: header[4] === void 0 ? 1 : Number(header[4]),
300
+ removed: [],
301
+ added: [],
302
+ targets: []
303
+ };
304
+ file.hunks.push(hunk);
305
+ continue;
306
+ }
307
+ if (!hunk || !file) continue;
308
+ if (line.startsWith("-")) hunk.removed.push(line.slice(1));
309
+ else if (line.startsWith("+")) hunk.added.push(line.slice(1));
310
+ }
311
+ for (const changed of files) for (const h of changed.hunks) h.id = hunkId(changed.path, h.oldStart, h.removed, h.added);
312
+ return files;
313
+ }
314
+ /** A file that git does not know yet: one hunk that adds every line. */
315
+ function untrackedFile(path, source) {
316
+ const lines = source.endsWith("\n") ? source.slice(0, -1).split("\n") : source.split("\n");
317
+ return {
318
+ path,
319
+ status: "added",
320
+ binary: false,
321
+ hunks: [{
322
+ id: hunkId(path, 0, [], lines),
323
+ oldStart: 0,
324
+ oldLines: 0,
325
+ newStart: 1,
326
+ newLines: lines.length,
327
+ removed: [],
328
+ added: lines,
329
+ targets: []
330
+ }]
331
+ };
332
+ }
333
+ /** Every element the loc-tags plugin stamps, with its extent in the source. */
334
+ function taggedElements(ast) {
335
+ const out = [];
336
+ walkJsx(ast, (node) => {
337
+ const opening = node.openingElement;
338
+ if (!opening || !node.loc || !taggableName(opening)) return;
339
+ out.push({
340
+ loc: `${node.loc.start.line}:${node.loc.start.column}`,
341
+ line: node.loc.start.line,
342
+ endLine: node.loc.end.line,
343
+ start: node.start,
344
+ end: node.end
345
+ });
346
+ });
347
+ return out;
348
+ }
349
+ const contains = (outer, inner) => outer !== inner && outer.start <= inner.start && outer.end >= inner.end;
350
+ function innermost(elements, from, to) {
351
+ let best = null;
352
+ for (const el of elements) {
353
+ if (el.line > from || el.endLine < to) continue;
354
+ if (!best || contains(best, el)) best = el;
355
+ }
356
+ return best;
357
+ }
358
+ /**
359
+ * Puts each hunk of the document's own source on the elements it touches.
360
+ * Elements that start inside the hunk are the change, outermost first; a
361
+ * hunk inside one element's text marks that element; a deletion marks the
362
+ * element that now stands where the removed lines were.
363
+ */
364
+ function placeHunks(source, hunks) {
365
+ const ast = parseSource(source);
366
+ if (!ast) return;
367
+ const elements = taggedElements(ast);
368
+ for (const hunk of hunks) {
369
+ if (hunk.newLines === 0) {
370
+ const point = hunk.newStart;
371
+ const parent = innermost(elements, point, point + 1);
372
+ const next = elements.find((el) => el.line > point && (!parent || contains(parent, el)) && !elements.some((other) => other !== el && other.line > point && contains(other, el) && (!parent || contains(parent, other))));
373
+ if (next) hunk.targets = [{
374
+ loc: next.loc,
375
+ mark: "removed-before"
376
+ }];
377
+ else if (parent) hunk.targets = [{
378
+ loc: parent.loc,
379
+ mark: "changed"
380
+ }];
381
+ continue;
382
+ }
383
+ const from = hunk.newStart;
384
+ const to = hunk.newStart + hunk.newLines - 1;
385
+ const mark = hunk.oldLines === 0 ? "added" : "changed";
386
+ const starting = elements.filter((el) => el.line >= from && el.line <= to);
387
+ const outermost = starting.filter((el) => !starting.some((other) => contains(other, el)));
388
+ if (outermost.length > 0) {
389
+ hunk.targets = outermost.map((el) => ({
390
+ loc: el.loc,
391
+ mark
392
+ }));
393
+ continue;
394
+ }
395
+ const around = innermost(elements, from, to);
396
+ if (around) hunk.targets = [{
397
+ loc: around.loc,
398
+ mark: "changed"
399
+ }];
400
+ }
401
+ }
402
+ /**
403
+ * The file with one hunk taken back. The lines the hunk added have to still be
404
+ * where it put them — otherwise the file moved on since the viewer looked, and
405
+ * the revert is refused rather than guessed.
406
+ */
407
+ function revertHunkIn(source, hunk) {
408
+ const trailing = source.endsWith("\n");
409
+ const lines = (trailing ? source.slice(0, -1) : source).split("\n");
410
+ const at = hunk.newLines === 0 ? hunk.newStart : hunk.newStart - 1;
411
+ const current = lines.slice(at, at + hunk.newLines);
412
+ if (current.length !== hunk.added.length || current.some((line, i) => line !== hunk.added[i])) return null;
413
+ lines.splice(at, hunk.newLines, ...hunk.removed);
414
+ const next = lines.join("\n");
415
+ return trailing || next === "" ? `${next}\n` : next;
416
+ }
417
+ //#endregion
418
+ //#region src/editing/doc-ops.ts
419
+ function programBody$1(ast) {
420
+ return ast.program?.body ?? [];
421
+ }
422
+ function metaObjectOf(node) {
423
+ if (node.type !== "ExportNamedDeclaration") return null;
424
+ const decl = node.declaration;
425
+ if (decl?.type !== "VariableDeclaration") return null;
426
+ const declarations = decl.declarations ?? [];
427
+ for (const d of declarations) {
428
+ const id = d.id;
429
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
430
+ let init = d.init;
431
+ if (!init) return null;
432
+ if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
433
+ const expr = init.expression;
434
+ if (expr) init = expr;
435
+ }
436
+ return init.type === "ObjectExpression" ? init : null;
437
+ }
438
+ return null;
439
+ }
440
+ function findMetaObject(ast) {
441
+ for (const node of programBody$1(ast)) {
442
+ const object = metaObjectOf(node);
443
+ if (object) return object;
444
+ }
445
+ return null;
446
+ }
447
+ function jsString$1(value) {
448
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
449
+ }
450
+ function validateDocTitle(v) {
451
+ if (typeof v !== "string") return null;
452
+ const trimmed = v.trim();
453
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
454
+ return trimmed;
455
+ }
456
+ /**
457
+ * Rewrites `meta.title` in place, adding the property when the meta object
458
+ * exists without one. Returns null when there is no meta object to edit —
459
+ * the caller reports that rather than inventing an export.
460
+ */
461
+ function setMetaTitle(source, title) {
462
+ return setMetaString(source, "title", title);
463
+ }
464
+ /** Sets one string field of `export const meta`, adding it first when it is missing. */
465
+ function setMetaString(source, field, value) {
466
+ const ast = parseStrict(source);
467
+ if (!ast) return null;
468
+ const object = findMetaObject(ast);
469
+ if (!object) return null;
470
+ const properties = object.properties ?? [];
471
+ for (const prop of properties) {
472
+ if (prop.type !== "ObjectProperty") continue;
473
+ const p = prop;
474
+ if (p.computed) continue;
475
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== field) continue;
476
+ return source.slice(0, p.value.start) + jsString$1(value) + source.slice(p.value.end);
477
+ }
478
+ const open = object.start + 1;
479
+ const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$1(value)},\n` : `\n ${field}: ${jsString$1(value)},`;
480
+ return source.slice(0, open) + inserted + source.slice(open);
481
+ }
482
+ function readMetaTitle(source) {
483
+ const ast = parseSource(source);
484
+ if (!ast) return null;
485
+ const object = findMetaObject(ast);
486
+ if (!object) return null;
487
+ const properties = object.properties ?? [];
488
+ for (const prop of properties) {
489
+ if (prop.type !== "ObjectProperty") continue;
490
+ const p = prop;
491
+ if (p.computed) continue;
492
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
493
+ if (p.value.type !== "StringLiteral") return null;
494
+ return typeof p.value.value === "string" ? p.value.value : null;
495
+ }
496
+ return null;
497
+ }
498
+ /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
499
+ function nextCopyId(baseId, taken) {
500
+ const stem = baseId.replace(/-copy(-\d+)?$/, "");
501
+ let candidate = `${stem}-copy`;
502
+ let n = 2;
503
+ while (taken.has(candidate)) {
504
+ candidate = `${stem}-copy-${n}`;
505
+ n++;
506
+ }
507
+ return candidate;
508
+ }
509
+ function copyTitle(title) {
510
+ return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
511
+ }
512
+ //#endregion
513
+ //#region src/files/folders.ts
514
+ const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
515
+ const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
516
+ function emptyManifest() {
517
+ return {
518
+ folders: [],
519
+ assignments: {}
520
+ };
521
+ }
522
+ async function readManifest(file) {
523
+ try {
524
+ const raw = await fs.readFile(file, "utf8");
525
+ const parsed = JSON.parse(raw);
526
+ return {
527
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
528
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
529
+ };
530
+ } catch (err) {
531
+ if (err.code === "ENOENT") return emptyManifest();
532
+ throw err;
533
+ }
534
+ }
535
+ async function writeManifest(file, manifest) {
536
+ await fs.mkdir(path.dirname(file), { recursive: true });
537
+ await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
538
+ }
539
+ function newFolderId() {
540
+ return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
541
+ }
542
+ function validateName(v) {
543
+ if (typeof v !== "string") return null;
544
+ const trimmed = v.trim();
545
+ if (trimmed.length < 1 || trimmed.length > 40) return null;
546
+ return trimmed;
547
+ }
548
+ function validateReorder(v, current) {
549
+ if (!Array.isArray(v) || v.length !== current.length) return null;
550
+ const known = new Set(current.map((f) => f.id));
551
+ const seen = /* @__PURE__ */ new Set();
552
+ const out = [];
553
+ for (const id of v) {
554
+ if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
555
+ if (!known.has(id) || seen.has(id)) return null;
556
+ seen.add(id);
557
+ out.push(id);
558
+ }
559
+ return out;
560
+ }
561
+ function validateIcon(v) {
562
+ if (!v || typeof v !== "object") return null;
563
+ const icon = v;
564
+ if (icon.type === "emoji") {
565
+ if (typeof icon.value !== "string") return null;
566
+ if (icon.value.length < 1 || icon.value.length > 8) return null;
567
+ return {
568
+ type: "emoji",
569
+ value: icon.value
570
+ };
571
+ }
572
+ if (icon.type === "color") {
573
+ if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
574
+ return {
575
+ type: "color",
576
+ value: icon.value
577
+ };
578
+ }
579
+ return null;
580
+ }
581
+ //#endregion
582
+ //#region src/ops/documents.ts
583
+ /**
584
+ * Operations shared by the dev API and the MCP server. Everything here takes an
585
+ * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
586
+ * and a browser calling `/__docs` end up in exactly the same code.
587
+ */
588
+ var OpsError = class extends Error {
589
+ status;
590
+ constructor(status, message) {
591
+ super(message);
592
+ this.status = status;
593
+ this.name = "OpsError";
594
+ }
595
+ };
596
+ const ENTRY_NAMES = [
597
+ "index.tsx",
598
+ "index.jsx",
599
+ "index.ts",
600
+ "index.js"
601
+ ];
602
+ function docDir(ctx, docId) {
603
+ if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
604
+ const dir = path.resolve(ctx.docsRoot, docId);
605
+ if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
606
+ return dir;
607
+ }
608
+ function resolveEntry(ctx, docId) {
609
+ const dir = docDir(ctx, docId);
610
+ for (const name of ENTRY_NAMES) {
611
+ const file = path.join(dir, name);
612
+ if (existsSync(file)) return file;
613
+ }
614
+ return null;
615
+ }
616
+ async function listDocIds$1(ctx) {
617
+ try {
618
+ return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
619
+ } catch {
620
+ return [];
621
+ }
622
+ }
623
+ /** Reads what the doc declares without executing it — a regex over `export const meta`. */
624
+ function readMetaField(source, field) {
625
+ const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
626
+ return source.slice(source.indexOf("export const meta")).match(re)?.[2];
627
+ }
628
+ async function listDocuments(ctx) {
629
+ const ids = await listDocIds$1(ctx);
630
+ const manifest = await readManifest(ctx.manifestPath);
631
+ const out = [];
632
+ for (const id of ids) {
633
+ const entry = resolveEntry(ctx, id);
634
+ const source = entry ? await fs.readFile(entry, "utf8") : "";
635
+ out.push({
636
+ id,
637
+ title: source ? readMetaTitle(source) : null,
638
+ subtitle: source ? readMetaField(source, "subtitle") : void 0,
639
+ theme: source ? readMetaField(source, "theme") : void 0,
640
+ createdAt: source ? readMetaField(source, "createdAt") : void 0,
641
+ folder: manifest.assignments[id],
642
+ entry: entry ? path.relative(ctx.userCwd, entry) : null
643
+ });
644
+ }
645
+ return out;
646
+ }
647
+ async function readDocument(ctx, docId) {
648
+ const entry = resolveEntry(ctx, docId);
649
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
650
+ return {
651
+ id: docId,
652
+ entry: path.relative(ctx.userCwd, entry),
653
+ source: await fs.readFile(entry, "utf8")
654
+ };
655
+ }
656
+ async function createDocument(ctx, docId, source) {
657
+ const dir = docDir(ctx, docId);
658
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
659
+ await fs.mkdir(dir, { recursive: true });
660
+ const entry = path.join(dir, "index.tsx");
661
+ await fs.writeFile(entry, source, "utf8");
662
+ return {
663
+ id: docId,
664
+ entry: path.relative(ctx.userCwd, entry)
665
+ };
666
+ }
667
+ /**
668
+ * Whole-file overwrite. `expected` is the source the caller believes is on
669
+ * disk; passing it turns a blind overwrite into a conflict check, which is what
670
+ * keeps two agents (or an agent and a person) from clobbering each other.
671
+ */
672
+ async function writeDocument(ctx, docId, source, expected) {
673
+ const entry = resolveEntry(ctx, docId);
674
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
675
+ if (expected !== void 0) {
676
+ if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
677
+ }
678
+ await fs.writeFile(entry, source, "utf8");
679
+ return {
680
+ id: docId,
681
+ entry: path.relative(ctx.userCwd, entry)
682
+ };
683
+ }
684
+ async function renameDocument(ctx, docId, rawTitle) {
685
+ const title = validateDocTitle(rawTitle);
686
+ if (!title) throw new OpsError(400, "invalid title");
687
+ const entry = resolveEntry(ctx, docId);
688
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
689
+ const source = await fs.readFile(entry, "utf8");
690
+ const next = setMetaTitle(source, title);
691
+ if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
692
+ if (next !== source) await fs.writeFile(entry, next, "utf8");
693
+ return {
694
+ id: docId,
695
+ title
696
+ };
697
+ }
698
+ async function duplicateDocument(ctx, docId, newId) {
699
+ const dir = docDir(ctx, docId);
700
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
701
+ const taken = new Set(await listDocIds$1(ctx));
702
+ let targetId;
703
+ if (newId) {
704
+ if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
705
+ if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
706
+ targetId = newId;
707
+ } else targetId = nextCopyId(docId, taken);
708
+ await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
709
+ const entry = resolveEntry(ctx, targetId);
710
+ if (entry) {
711
+ const source = await fs.readFile(entry, "utf8");
712
+ const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
713
+ if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
714
+ }
715
+ const manifest = await readManifest(ctx.manifestPath);
716
+ const folderId = manifest.assignments[docId];
717
+ if (folderId) {
718
+ manifest.assignments[targetId] = folderId;
719
+ await writeManifest(ctx.manifestPath, manifest);
720
+ }
721
+ return { id: targetId };
722
+ }
723
+ async function deleteDocument(ctx, docId) {
724
+ const dir = docDir(ctx, docId);
725
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
726
+ await fs.rm(dir, {
727
+ recursive: true,
728
+ force: true
729
+ });
730
+ const manifest = await readManifest(ctx.manifestPath);
731
+ if (manifest.assignments[docId]) {
732
+ delete manifest.assignments[docId];
733
+ await writeManifest(ctx.manifestPath, manifest);
734
+ }
735
+ }
736
+ //#endregion
737
+ //#region src/ops/changes.ts
738
+ const run = promisify(execFile);
739
+ async function git(cwd, args) {
740
+ const { stdout } = await run("git", args, {
741
+ cwd,
742
+ maxBuffer: 33554432
743
+ });
744
+ return stdout;
745
+ }
746
+ /** The document folder relative to the workspace, POSIX-style, with a trailing slash. */
747
+ function folderOf(ctx, docId) {
748
+ return `${path.relative(ctx.userCwd, path.join(ctx.docsRoot, docId)).split(path.sep).join("/")}/`;
749
+ }
750
+ async function inRepo(ctx) {
751
+ try {
752
+ return (await git(ctx.userCwd, ["rev-parse", "--is-inside-work-tree"])).trim() === "true" ? "yes" : "no-repo";
753
+ } catch (err) {
754
+ return err.code === "ENOENT" ? "no-git" : "no-repo";
755
+ }
756
+ }
757
+ /**
758
+ * What changed in one document's folder since a revision — the working tree
759
+ * against `since`, untracked files included — with each hunk of the document's
760
+ * own source placed on the elements it touches, so the viewer can mark them.
761
+ */
762
+ async function readChanges(ctx, docId, since = "HEAD") {
763
+ const entry = resolveEntry(ctx, docId);
764
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
765
+ const repo = await inRepo(ctx);
766
+ if (repo !== "yes") return {
767
+ available: false,
768
+ reason: repo
769
+ };
770
+ const folder = folderOf(ctx, docId);
771
+ let commit = null;
772
+ try {
773
+ commit = (await git(ctx.userCwd, [
774
+ "rev-parse",
775
+ "--verify",
776
+ "--quiet",
777
+ `${since}^{commit}`
778
+ ])).trim();
779
+ } catch {
780
+ if (since !== "HEAD") throw new OpsError(400, `not a revision in this repository: ${since}`);
781
+ }
782
+ let files = commit ? parseUnifiedDiff(await git(ctx.userCwd, [
783
+ "diff",
784
+ "--unified=0",
785
+ "--no-color",
786
+ "--no-ext-diff",
787
+ "--relative",
788
+ commit,
789
+ "--",
790
+ folder
791
+ ]), folder) : [];
792
+ const untracked = (await git(ctx.userCwd, [
793
+ "ls-files",
794
+ "--others",
795
+ "--exclude-standard",
796
+ "--",
797
+ folder
798
+ ])).split("\n").filter((file) => file.startsWith(folder));
799
+ for (const file of untracked) {
800
+ const rel = file.slice(folder.length);
801
+ const buffer = await fs.readFile(path.join(ctx.userCwd, file));
802
+ files.push(buffer.includes(0) ? {
803
+ path: rel,
804
+ status: "added",
805
+ binary: true,
806
+ hunks: []
807
+ } : untrackedFile(rel, buffer.toString("utf8")));
808
+ }
809
+ files = withoutReviewMarkers(files);
810
+ const own = files.find((file) => file.path === path.basename(entry));
811
+ if (own && !own.binary) placeHunks(await fs.readFile(entry, "utf8"), own.hunks);
812
+ files.sort((a, b) => a === own ? -1 : b === own ? 1 : a.path.localeCompare(b.path));
813
+ return {
814
+ available: true,
815
+ since,
816
+ commit,
817
+ files
818
+ };
819
+ }
820
+ /** Recent commits that touched the document, newest first, for choosing what to compare against. */
821
+ async function listRevisions(ctx, docId, limit = 15) {
822
+ if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
823
+ if (await inRepo(ctx) !== "yes") return [];
824
+ try {
825
+ return (await git(ctx.userCwd, [
826
+ "log",
827
+ `-n${limit}`,
828
+ "--format=%H%x1f%h%x1f%s%x1f%cr",
829
+ "--",
830
+ folderOf(ctx, docId)
831
+ ])).split("\n").filter(Boolean).map((line) => {
832
+ const [commit = "", short = "", subject = "", when = ""] = line.split("");
833
+ return {
834
+ commit,
835
+ short,
836
+ subject,
837
+ when
838
+ };
839
+ });
840
+ } catch {
841
+ return [];
842
+ }
843
+ }
844
+ /**
845
+ * Takes one hunk back out of the working tree. The hunk is found again by id
846
+ * in a fresh diff, never trusted from the request, and a source file must still
847
+ * parse afterwards — hunks can depend on each other, and a revert that leaves
848
+ * half a JSX tag behind is refused rather than written.
849
+ */
850
+ async function revertChange(ctx, docId, opts) {
851
+ const changes = await readChanges(ctx, docId, opts.since);
852
+ if (!changes.available) throw new OpsError(409, "this workspace is not under git");
853
+ const file = changes.files.find((candidate) => candidate.path === opts.file);
854
+ const hunk = file?.hunks.find((candidate) => candidate.id === opts.hunk);
855
+ if (!file || !hunk) throw new OpsError(409, "that change is no longer there — reload the changes");
856
+ if (file.binary) throw new OpsError(422, "a binary file cannot be reverted here");
857
+ const target = path.join(ctx.docsRoot, docId, file.path);
858
+ const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
859
+ if (next === null) throw new OpsError(409, "the file changed since the diff was read");
860
+ if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
861
+ await fs.writeFile(target, next, "utf8");
862
+ return { ok: true };
863
+ }
864
+ //#endregion
865
+ //#region src/files/assets.ts
866
+ const GLOBAL_SCOPE = "@global";
867
+ const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
868
+ const MIME_BY_EXT = {
869
+ png: "image/png",
870
+ jpg: "image/jpeg",
871
+ jpeg: "image/jpeg",
872
+ gif: "image/gif",
873
+ svg: "image/svg+xml",
874
+ webp: "image/webp",
875
+ avif: "image/avif",
876
+ ico: "image/x-icon",
877
+ pdf: "application/pdf",
878
+ woff: "font/woff",
879
+ woff2: "font/woff2",
880
+ ttf: "font/ttf",
881
+ otf: "font/otf",
882
+ csv: "text/csv; charset=utf-8",
883
+ json: "application/json",
884
+ txt: "text/plain; charset=utf-8",
885
+ md: "text/markdown; charset=utf-8"
886
+ };
887
+ function mimeForFilename(name) {
888
+ const dot = name.lastIndexOf(".");
889
+ if (dot < 0) return "application/octet-stream";
890
+ return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
891
+ }
892
+ function assetCreatedAt(birthtimeMs, mtimeMs) {
893
+ return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
894
+ }
895
+ function validateAssetName(v) {
896
+ if (typeof v !== "string") return null;
897
+ const trimmed = v.trim();
898
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
899
+ if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
900
+ if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
901
+ if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
902
+ const dot = trimmed.lastIndexOf(".");
903
+ if (dot <= 0 || dot === trimmed.length - 1) return null;
904
+ return trimmed;
905
+ }
906
+ function resolveAssetsDir(docsRoot, docId) {
907
+ if (!DOC_ID_RE.test(docId)) return null;
908
+ const docDir = path.resolve(docsRoot, docId);
909
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
910
+ const assetsDir = path.resolve(docDir, "assets");
911
+ if (assetsDir !== path.join(docDir, "assets")) return null;
912
+ return assetsDir;
913
+ }
914
+ function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
915
+ if (scope === "@global") return globalAssetsRoot;
916
+ return resolveAssetsDir(docsRoot, scope);
917
+ }
918
+ function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
919
+ if (!validateAssetName(filename)) return null;
920
+ const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
921
+ if (!dir) return null;
922
+ const file = path.resolve(dir, filename);
923
+ if (!file.startsWith(dir + path.sep)) return null;
924
+ return file;
925
+ }
926
+ /** How a document imports an asset — the string we look for when counting usages. */
927
+ function assetImportPath(scope, filename) {
928
+ return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
929
+ }
930
+ function escapeRegExp(value) {
931
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
932
+ }
933
+ /**
934
+ * Counts references to an asset in a document's source. Matches the quoted path
935
+ * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
936
+ * which is every form the authoring skill sanctions.
937
+ */
938
+ function countAssetUsages(source, importPath) {
939
+ const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
940
+ return source.match(quoted)?.length ?? 0;
941
+ }
942
+ function findReferencedAssets(source, importPaths) {
943
+ return importPaths.filter((p) => countAssetUsages(source, p) > 0);
944
+ }
945
+ //#endregion
946
+ //#region src/http/request-guard.ts
947
+ function firstHeaderValue(value) {
948
+ if (Array.isArray(value)) return value[0] ?? null;
949
+ return value ?? null;
950
+ }
951
+ function headerValue(req, name) {
952
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
953
+ }
954
+ function firstCommaToken(value) {
456
955
  if (!value) return null;
457
956
  const [first] = value.split(",", 1);
458
957
  return first?.trim() || null;
@@ -515,7 +1014,7 @@ function validateMutationRequest(req, opts = {}) {
515
1014
  }
516
1015
  //#endregion
517
1016
  //#region src/vite/routes/assets.ts
518
- async function listDocIds$1(docsRoot) {
1017
+ async function listDocIds(docsRoot) {
519
1018
  try {
520
1019
  return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
521
1020
  } catch {
@@ -546,7 +1045,7 @@ function registerAssetRoutes(server, ctx) {
546
1045
  const isGlobal = scope === GLOBAL_SCOPE;
547
1046
  if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
548
1047
  const importPath = assetImportPath(scope, filename);
549
- const docIds = isGlobal ? await listDocIds$1(ctx.docsRoot) : [scope];
1048
+ const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
550
1049
  const usages = [];
551
1050
  let totalCount = 0;
552
1051
  for (const docId of docIds) {
@@ -595,7 +1094,7 @@ function registerAssetRoutes(server, ctx) {
595
1094
  }
596
1095
  assets.sort((a, b) => a.name.localeCompare(b.name));
597
1096
  if (assets.length > 0) {
598
- const scanIds = scope === "@global" ? await listDocIds$1(ctx.docsRoot) : [scope];
1097
+ const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
599
1098
  const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
600
1099
  const paths = assets.map((a) => a.importPath);
601
1100
  for (const docId of scanIds) {
@@ -667,446 +1166,500 @@ function registerAssetRoutes(server, ctx) {
667
1166
  mime: mimeForFilename(filename),
668
1167
  url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
669
1168
  importPath: assetImportPath(scope, filename)
670
- });
671
- }
672
- if (method === "PATCH") {
673
- const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
674
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
675
- const target = validateAssetName((await readBody(req)).name);
676
- if (!target) return json(res, 400, { error: "invalid name" });
677
- if (target === filename) return json(res, 200, {
678
- ok: true,
679
- name: filename
680
- });
681
- const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
682
- if (!dest) return json(res, 400, { error: "invalid name" });
683
- try {
684
- await fs.access(dest);
685
- return json(res, 409, { error: "target exists" });
686
- } catch {}
687
- try {
688
- await fs.rename(file, dest);
689
- } catch (err) {
690
- if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
691
- throw err;
692
- }
693
- return json(res, 200, {
694
- ok: true,
695
- name: target
696
- });
697
- }
698
- if (method === "DELETE") {
699
- const requestCheck = validateMutationRequest(req);
700
- if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
701
- try {
702
- await fs.unlink(file);
703
- } catch (err) {
704
- if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
705
- throw err;
706
- }
707
- return json(res, 200, { ok: true });
708
- }
709
- }
710
- return next();
711
- } catch (err) {
712
- json(res, 500, { error: String(err.message ?? err) });
713
- }
714
- });
715
- }
716
- //#endregion
717
- //#region src/editing/babel-walk.ts
718
- function parseSource(code) {
719
- try {
720
- return parse(code, {
721
- sourceType: "module",
722
- plugins: ["typescript", "jsx"],
723
- errorRecovery: true
724
- });
725
- } catch {
726
- return null;
727
- }
728
- }
729
- /**
730
- * `parseSource`, but a source with any recovered error is refused. Reading
731
- * tolerates a document mid-edit; writing splices text in by AST offset, and a
732
- * best-guess tree recovered from a syntax error must never decide where.
733
- */
734
- function parseStrict(code) {
735
- const ast = parseSource(code);
736
- if (!ast) return null;
737
- return ast.errors && ast.errors.length > 0 ? null : ast;
738
- }
739
- function isNode(value) {
740
- return typeof value === "object" && value !== null && typeof value.type === "string";
741
- }
742
- /** Depth-first walk over every node; the visitor decides what it cares about. */
743
- function walkAst(node, visit) {
744
- if (Array.isArray(node)) {
745
- for (const child of node) walkAst(child, visit);
746
- return;
747
- }
748
- if (!isNode(node)) return;
749
- visit(node);
750
- for (const key of Object.keys(node)) {
751
- if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
752
- walkAst(node[key], visit);
753
- }
754
- }
755
- function walkJsx(ast, visit) {
756
- walkAst(ast, (node) => {
757
- if (node.type === "JSXElement") visit(node);
758
- });
759
- }
760
- /**
761
- * The JSX element whose opening tag starts at this source position.
762
- *
763
- * The match is exact on both line and column. Anything looser can resolve to a
764
- * different element on the same line, and this location decides where an edit
765
- * gets written — a near miss silently rewrites the wrong text.
766
- */
767
- function findJsxAt(ast, line, column) {
768
- let found = null;
769
- walkJsx(ast, (node) => {
770
- if (found) return;
771
- const start = node.loc?.start;
772
- if (start && start.line === line && start.column === column) found = node;
1169
+ });
1170
+ }
1171
+ if (method === "PATCH") {
1172
+ const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1173
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1174
+ const target = validateAssetName((await readBody(req)).name);
1175
+ if (!target) return json(res, 400, { error: "invalid name" });
1176
+ if (target === filename) return json(res, 200, {
1177
+ ok: true,
1178
+ name: filename
1179
+ });
1180
+ const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
1181
+ if (!dest) return json(res, 400, { error: "invalid name" });
1182
+ try {
1183
+ await fs.access(dest);
1184
+ return json(res, 409, { error: "target exists" });
1185
+ } catch {}
1186
+ try {
1187
+ await fs.rename(file, dest);
1188
+ } catch (err) {
1189
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1190
+ throw err;
1191
+ }
1192
+ return json(res, 200, {
1193
+ ok: true,
1194
+ name: target
1195
+ });
1196
+ }
1197
+ if (method === "DELETE") {
1198
+ const requestCheck = validateMutationRequest(req);
1199
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1200
+ try {
1201
+ await fs.unlink(file);
1202
+ } catch (err) {
1203
+ if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
1204
+ throw err;
1205
+ }
1206
+ return json(res, 200, { ok: true });
1207
+ }
1208
+ }
1209
+ return next();
1210
+ } catch (err) {
1211
+ json(res, 500, { error: String(err.message ?? err) });
1212
+ }
773
1213
  });
774
- return found;
775
1214
  }
776
- /**
777
- * Every JSX element that starts on a line, nearest column first.
778
- *
779
- * Columns cannot be trusted for locations derived from React's `_debugSource`:
780
- * injecting the loc attribute shifts the columns of anything later on the same
781
- * line, so the offset differs per element. The line survives that, so callers
782
- * scan the line and pick by content instead.
783
- */
784
- function findJsxOnLine(ast, line, column) {
785
- const hits = [];
786
- walkJsx(ast, (node) => {
787
- const start = node.loc?.start;
788
- if (!start || start.line !== line) return;
789
- hits.push({
790
- node,
791
- distance: Math.abs(start.column - column)
792
- });
1215
+ //#endregion
1216
+ //#region src/vite/routes/changes.ts
1217
+ function registerChangesRoutes(server, ctx) {
1218
+ server.middlewares.use("/__changes", async (req, res, next) => {
1219
+ const url = new URL(req.url ?? "/", "http://local");
1220
+ const method = req.method ?? "GET";
1221
+ try {
1222
+ if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
1223
+ if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
1224
+ if (method === "POST" && url.pathname === "/revert") {
1225
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1226
+ if (!check.ok) return json(res, check.status, { error: check.error });
1227
+ const body = await readBody(req);
1228
+ if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
1229
+ return json(res, 200, await revertChange(ctx, body.docId, {
1230
+ file: body.file,
1231
+ hunk: body.hunk,
1232
+ ...typeof body.since === "string" ? { since: body.since } : {}
1233
+ }));
1234
+ }
1235
+ return next();
1236
+ } catch (err) {
1237
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1238
+ json(res, 500, { error: String(err.message ?? err) });
1239
+ }
793
1240
  });
794
- return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
795
1241
  }
796
1242
  //#endregion
797
- //#region src/editing/doc-ops.ts
798
- function programBody$1(ast) {
799
- return ast.program?.body ?? [];
800
- }
801
- function metaObjectOf(node) {
802
- if (node.type !== "ExportNamedDeclaration") return null;
803
- const decl = node.declaration;
804
- if (decl?.type !== "VariableDeclaration") return null;
805
- const declarations = decl.declarations ?? [];
806
- for (const d of declarations) {
807
- const id = d.id;
808
- if (id?.type !== "Identifier" || id.name !== "meta") continue;
809
- let init = d.init;
810
- if (!init) return null;
811
- if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
812
- const expr = init.expression;
813
- if (expr) init = expr;
814
- }
815
- return init.type === "ObjectExpression" ? init : null;
816
- }
817
- return null;
1243
+ //#region src/vite/themes-plugin.ts
1244
+ const THEMES_VMOD = "virtual:open-doc/themes";
1245
+ function resolved(id) {
1246
+ return `\0${id}`;
818
1247
  }
819
- function findMetaObject(ast) {
820
- for (const node of programBody$1(ast)) {
821
- const object = metaObjectOf(node);
822
- if (object) return object;
1248
+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
1249
+ function parseFrontmatter(raw, themeId) {
1250
+ const match = raw.match(FM_RE);
1251
+ const fmText = match ? match[1] : "";
1252
+ const body = match ? match[2] : raw;
1253
+ const data = {};
1254
+ for (const line of fmText.split(/\r?\n/)) {
1255
+ const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
1256
+ if (!m) continue;
1257
+ let value = m[2].trim();
1258
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
1259
+ data[m[1]] = value;
823
1260
  }
824
- return null;
825
- }
826
- function jsString$1(value) {
827
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
828
- }
829
- function validateDocTitle(v) {
830
- if (typeof v !== "string") return null;
831
- const trimmed = v.trim();
832
- if (trimmed.length < 1 || trimmed.length > 120) return null;
833
- return trimmed;
1261
+ return {
1262
+ fm: {
1263
+ name: data.name || themeId,
1264
+ description: data.description || "",
1265
+ pageSize: data.pageSize || "",
1266
+ mode: data.mode || ""
1267
+ },
1268
+ body: body.trim()
1269
+ };
834
1270
  }
835
- /**
836
- * Rewrites `meta.title` in place, adding the property when the meta object
837
- * exists without one. Returns null when there is no meta object to edit —
838
- * the caller reports that rather than inventing an export.
839
- */
840
- function setMetaTitle(source, title) {
841
- const ast = parseStrict(source);
842
- if (!ast) return null;
843
- const object = findMetaObject(ast);
844
- if (!object) return null;
845
- const properties = object.properties ?? [];
846
- for (const prop of properties) {
847
- if (prop.type !== "ObjectProperty") continue;
848
- const p = prop;
849
- if (p.computed) continue;
850
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
851
- return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
852
- }
853
- const open = object.start + 1;
854
- const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
855
- return source.slice(0, open) + inserted + source.slice(open);
1271
+ async function findThemes(userCwd, themesDir) {
1272
+ const abs = path.resolve(userCwd, themesDir);
1273
+ if (!existsSync(abs)) return [];
1274
+ return (await fg("*.md", {
1275
+ cwd: abs,
1276
+ absolute: true,
1277
+ onlyFiles: true
1278
+ })).sort();
856
1279
  }
857
- function readMetaTitle(source) {
858
- const ast = parseSource(source);
859
- if (!ast) return null;
860
- const object = findMetaObject(ast);
861
- if (!object) return null;
862
- const properties = object.properties ?? [];
863
- for (const prop of properties) {
864
- if (prop.type !== "ObjectProperty") continue;
865
- const p = prop;
866
- if (p.computed) continue;
867
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
868
- if (p.value.type !== "StringLiteral") return null;
869
- return typeof p.value.value === "string" ? p.value.value : null;
1280
+ async function readTheme$1(mdAbs, themesRoot) {
1281
+ const id = path.basename(mdAbs, ".md");
1282
+ const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
1283
+ let demoAbs = null;
1284
+ for (const cand of [
1285
+ `${id}.demo.tsx`,
1286
+ `${id}.demo.jsx`,
1287
+ `${id}.demo.ts`,
1288
+ `${id}.demo.js`
1289
+ ]) {
1290
+ const p = path.join(themesRoot, cand);
1291
+ if (existsSync(p)) {
1292
+ demoAbs = p;
1293
+ break;
1294
+ }
870
1295
  }
871
- return null;
1296
+ return {
1297
+ id,
1298
+ frontmatter: fm,
1299
+ body,
1300
+ demoAbs
1301
+ };
872
1302
  }
873
- /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
874
- function nextCopyId(baseId, taken) {
875
- const stem = baseId.replace(/-copy(-\d+)?$/, "");
876
- let candidate = `${stem}-copy`;
877
- let n = 2;
878
- while (taken.has(candidate)) {
879
- candidate = `${stem}-copy-${n}`;
880
- n++;
881
- }
882
- return candidate;
1303
+ function generateThemesModule(themes, isDev) {
1304
+ const meta = themes.map((t) => ({
1305
+ id: t.id,
1306
+ name: t.frontmatter.name,
1307
+ description: t.frontmatter.description,
1308
+ pageSize: t.frontmatter.pageSize,
1309
+ mode: t.frontmatter.mode,
1310
+ body: t.body,
1311
+ hasDemo: t.demoAbs !== null
1312
+ }));
1313
+ const cases = themes.flatMap((t) => {
1314
+ const abs = t.demoAbs;
1315
+ if (!abs) return [];
1316
+ const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
1317
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
1318
+ return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
1319
+ }).join("\n");
1320
+ return `// virtual:open-doc/themes — generated
1321
+ export const themes = ${JSON.stringify(meta)};
1322
+
1323
+ export async function loadThemeDemo(id) {
1324
+ switch (id) {
1325
+ ${cases}
1326
+ default: throw new Error('Theme demo not found: ' + id);
1327
+ }
883
1328
  }
884
- function copyTitle(title) {
885
- return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
1329
+ `;
886
1330
  }
887
- //#endregion
888
- //#region src/files/folders.ts
889
- const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
890
- const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
891
- function emptyManifest() {
1331
+ function themesPlugin(opts) {
1332
+ const { userCwd, config } = opts;
1333
+ const themesDir = config.themesDir ?? "themes";
1334
+ const themesRoot = path.resolve(userCwd, themesDir);
1335
+ let isDev = false;
892
1336
  return {
893
- folders: [],
894
- assignments: {}
1337
+ name: "open-doc:themes",
1338
+ config(_c, env) {
1339
+ isDev = env.command === "serve";
1340
+ },
1341
+ resolveId(id) {
1342
+ if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
1343
+ return null;
1344
+ },
1345
+ async load(id) {
1346
+ if (id !== resolved(THEMES_VMOD)) return null;
1347
+ const files = await findThemes(userCwd, themesDir);
1348
+ return generateThemesModule(await Promise.all(files.map((f) => readTheme$1(f, themesRoot))), isDev);
1349
+ },
1350
+ configureServer(server) {
1351
+ const isThemeFile = (p) => {
1352
+ const rel = path.relative(themesRoot, p);
1353
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
1354
+ if (rel.includes(path.sep)) return false;
1355
+ return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
1356
+ };
1357
+ let reloadTimer = null;
1358
+ const reload = () => {
1359
+ if (reloadTimer) clearTimeout(reloadTimer);
1360
+ reloadTimer = setTimeout(() => {
1361
+ reloadTimer = null;
1362
+ const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
1363
+ if (mod) server.moduleGraph.invalidateModule(mod);
1364
+ server.ws.send({ type: "full-reload" });
1365
+ }, 150);
1366
+ };
1367
+ server.watcher.add(themesRoot);
1368
+ for (const event of [
1369
+ "add",
1370
+ "unlink",
1371
+ "change"
1372
+ ]) server.watcher.on(event, (p) => {
1373
+ if (isThemeFile(p)) reload();
1374
+ });
1375
+ }
895
1376
  };
896
1377
  }
897
- async function readManifest(file) {
898
- try {
899
- const raw = await fs.readFile(file, "utf8");
900
- const parsed = JSON.parse(raw);
901
- return {
902
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
903
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
904
- };
905
- } catch (err) {
906
- if (err.code === "ENOENT") return emptyManifest();
907
- throw err;
908
- }
909
- }
910
- async function writeManifest(file, manifest) {
911
- await fs.mkdir(path.dirname(file), { recursive: true });
912
- await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
1378
+ //#endregion
1379
+ //#region src/ops/library.ts
1380
+ function themesRoot(ctx, themesDir = "themes") {
1381
+ return path.resolve(ctx.userCwd, themesDir);
913
1382
  }
914
- function newFolderId() {
915
- return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1383
+ async function themeFiles(root) {
1384
+ if (!existsSync(root)) return [];
1385
+ return (await fg("*.md", {
1386
+ cwd: root,
1387
+ absolute: true,
1388
+ onlyFiles: true
1389
+ })).sort();
916
1390
  }
917
- function validateName(v) {
918
- if (typeof v !== "string") return null;
919
- const trimmed = v.trim();
920
- if (trimmed.length < 1 || trimmed.length > 40) return null;
921
- return trimmed;
1391
+ function demoFor(root, id) {
1392
+ for (const cand of [
1393
+ `${id}.demo.tsx`,
1394
+ `${id}.demo.jsx`,
1395
+ `${id}.demo.ts`,
1396
+ `${id}.demo.js`
1397
+ ]) {
1398
+ const p = path.join(root, cand);
1399
+ if (existsSync(p)) return p;
1400
+ }
1401
+ return null;
922
1402
  }
923
- function validateReorder(v, current) {
924
- if (!Array.isArray(v) || v.length !== current.length) return null;
925
- const known = new Set(current.map((f) => f.id));
926
- const seen = /* @__PURE__ */ new Set();
1403
+ async function listThemes(ctx, themesDir) {
1404
+ const root = themesRoot(ctx, themesDir);
927
1405
  const out = [];
928
- for (const id of v) {
929
- if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
930
- if (!known.has(id) || seen.has(id)) return null;
931
- seen.add(id);
932
- out.push(id);
1406
+ for (const file of await themeFiles(root)) {
1407
+ const id = path.basename(file, ".md");
1408
+ const { fm } = parseFrontmatter(await fs.readFile(file, "utf8"), id);
1409
+ out.push({
1410
+ id,
1411
+ name: fm.name,
1412
+ description: fm.description,
1413
+ pageSize: fm.pageSize,
1414
+ mode: fm.mode,
1415
+ hasDemo: demoFor(root, id) !== null
1416
+ });
933
1417
  }
934
1418
  return out;
935
1419
  }
936
- function validateIcon(v) {
937
- if (!v || typeof v !== "object") return null;
938
- const icon = v;
939
- if (icon.type === "emoji") {
940
- if (typeof icon.value !== "string") return null;
941
- if (icon.value.length < 1 || icon.value.length > 8) return null;
942
- return {
943
- type: "emoji",
944
- value: icon.value
945
- };
946
- }
947
- if (icon.type === "color") {
948
- if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
949
- return {
950
- type: "color",
951
- value: icon.value
952
- };
953
- }
954
- return null;
955
- }
956
- //#endregion
957
- //#region src/ops/documents.ts
958
1420
  /**
959
- * Operations shared by the dev API and the MCP server. Everything here takes an
960
- * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
961
- * and a browser calling `/__docs` end up in exactly the same code.
1421
+ * The full theme document. This is what an agent reads before writing a doc —
1422
+ * the palette, type scale, and paste-ready components live in the body.
962
1423
  */
963
- var OpsError = class extends Error {
964
- status;
965
- constructor(status, message) {
966
- super(message);
967
- this.status = status;
968
- this.name = "OpsError";
969
- }
970
- };
971
- const ENTRY_NAMES = [
972
- "index.tsx",
973
- "index.jsx",
974
- "index.ts",
975
- "index.js"
976
- ];
977
- function docDir(ctx, docId) {
978
- if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
979
- const dir = path.resolve(ctx.docsRoot, docId);
980
- if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
981
- return dir;
1424
+ async function readTheme(ctx, themeId, themesDir) {
1425
+ const root = themesRoot(ctx, themesDir);
1426
+ const file = path.join(root, `${themeId}.md`);
1427
+ if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
1428
+ const { fm, body } = parseFrontmatter(await fs.readFile(file, "utf8"), themeId);
1429
+ const demoAbs = demoFor(root, themeId);
1430
+ return {
1431
+ id: themeId,
1432
+ frontmatter: fm,
1433
+ body,
1434
+ demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
1435
+ };
982
1436
  }
983
- function resolveEntry(ctx, docId) {
984
- const dir = docDir(ctx, docId);
985
- for (const name of ENTRY_NAMES) {
986
- const file = path.join(dir, name);
987
- if (existsSync(file)) return file;
1437
+ /** `scope` is a document id, or `global` for the shared assets directory. */
1438
+ async function listAssets(ctx, scope) {
1439
+ const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1440
+ if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1441
+ if (!existsSync(dir)) return [];
1442
+ const names = await fs.readdir(dir);
1443
+ const out = [];
1444
+ for (const filename of names.sort()) {
1445
+ const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
1446
+ if (!stat?.isFile()) continue;
1447
+ out.push({
1448
+ scope,
1449
+ filename,
1450
+ bytes: stat.size,
1451
+ importPath: assetImportPath(scope, filename)
1452
+ });
988
1453
  }
989
- return null;
1454
+ return out;
990
1455
  }
991
- async function listDocIds(ctx) {
992
- try {
993
- return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
994
- } catch {
995
- return [];
996
- }
1456
+ async function writeAsset(ctx, scope, filename, data) {
1457
+ const name = validateAssetName(filename);
1458
+ if (!name) throw new OpsError(400, "invalid filename");
1459
+ const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1460
+ if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1461
+ await fs.mkdir(dir, { recursive: true });
1462
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1463
+ if (!file) throw new OpsError(400, "invalid filename");
1464
+ await fs.writeFile(file, data);
1465
+ return {
1466
+ scope,
1467
+ filename: name,
1468
+ bytes: data.byteLength,
1469
+ importPath: assetImportPath(scope, name)
1470
+ };
997
1471
  }
998
- /** Reads what the doc declares without executing it — a regex over `export const meta`. */
999
- function readMetaField(source, field) {
1000
- const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
1001
- return source.slice(source.indexOf("export const meta")).match(re)?.[2];
1472
+ async function deleteAsset(ctx, scope, filename) {
1473
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1474
+ if (!file) throw new OpsError(400, "invalid filename");
1475
+ if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1476
+ await fs.rm(file);
1002
1477
  }
1003
- async function listDocuments(ctx) {
1004
- const ids = await listDocIds(ctx);
1005
- const manifest = await readManifest(ctx.manifestPath);
1478
+ /** Which documents import this asset — check before deleting one. */
1479
+ async function findAssetUsages(ctx, scope, filename) {
1480
+ const importPath = assetImportPath(scope, filename);
1006
1481
  const out = [];
1007
- for (const id of ids) {
1482
+ for (const id of await listDocIds$1(ctx)) {
1008
1483
  const entry = resolveEntry(ctx, id);
1009
- const source = entry ? await fs.readFile(entry, "utf8") : "";
1010
- out.push({
1011
- id,
1012
- title: source ? readMetaTitle(source) : null,
1013
- subtitle: source ? readMetaField(source, "subtitle") : void 0,
1014
- theme: source ? readMetaField(source, "theme") : void 0,
1015
- createdAt: source ? readMetaField(source, "createdAt") : void 0,
1016
- folder: manifest.assignments[id],
1017
- entry: entry ? path.relative(ctx.userCwd, entry) : null
1484
+ if (!entry) continue;
1485
+ const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
1486
+ if (count > 0) out.push({
1487
+ docId: id,
1488
+ count
1018
1489
  });
1019
1490
  }
1020
1491
  return out;
1021
1492
  }
1022
- async function readDocument(ctx, docId) {
1023
- const entry = resolveEntry(ctx, docId);
1024
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1493
+ async function listFolders(ctx) {
1494
+ const manifest = await readManifest(ctx.manifestPath);
1025
1495
  return {
1026
- id: docId,
1027
- entry: path.relative(ctx.userCwd, entry),
1028
- source: await fs.readFile(entry, "utf8")
1496
+ folders: manifest.folders,
1497
+ assignments: manifest.assignments
1029
1498
  };
1030
1499
  }
1031
- async function createDocument(ctx, docId, source) {
1032
- const dir = docDir(ctx, docId);
1033
- if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
1034
- await fs.mkdir(dir, { recursive: true });
1035
- const entry = path.join(dir, "index.tsx");
1036
- await fs.writeFile(entry, source, "utf8");
1500
+ /** Folders always carry an icon; agents rarely care, so this is the fallback. */
1501
+ const DEFAULT_FOLDER_ICON = {
1502
+ type: "color",
1503
+ value: "#6b7280"
1504
+ };
1505
+ async function createFolder(ctx, rawName, rawIcon) {
1506
+ const name = validateName(rawName);
1507
+ if (!name) throw new OpsError(400, "invalid folder name");
1508
+ const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1509
+ if (!icon) throw new OpsError(400, "invalid icon");
1510
+ const manifest = await readManifest(ctx.manifestPath);
1511
+ const folder = {
1512
+ id: newFolderId(),
1513
+ name,
1514
+ icon
1515
+ };
1516
+ manifest.folders.push(folder);
1517
+ await writeManifest(ctx.manifestPath, manifest);
1518
+ return folder;
1519
+ }
1520
+ /** Filing only edits assignments — a document id never moves on disk. */
1521
+ async function fileDocument(ctx, docId, folderId) {
1522
+ const manifest = await readManifest(ctx.manifestPath);
1523
+ if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1524
+ if (folderId === null) delete manifest.assignments[docId];
1525
+ else manifest.assignments[docId] = folderId;
1526
+ await writeManifest(ctx.manifestPath, manifest);
1527
+ }
1528
+ //#endregion
1529
+ //#region src/ops/templates.ts
1530
+ const TEMPLATE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
1531
+ const MANIFEST = "template.json";
1532
+ async function readTemplateDir(dir, name, source) {
1533
+ if (!TEMPLATE_NAME_RE.test(name) || !existsSync(path.join(dir, "index.tsx"))) return null;
1534
+ let manifest = {};
1535
+ try {
1536
+ manifest = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), "utf8"));
1537
+ } catch {}
1538
+ const text = (value, fallback) => typeof value === "string" && value.trim() ? value.trim() : fallback;
1037
1539
  return {
1038
- id: docId,
1039
- entry: path.relative(ctx.userCwd, entry)
1540
+ name,
1541
+ title: text(manifest.title, name),
1542
+ description: text(manifest.description, ""),
1543
+ category: text(manifest.category, "general"),
1544
+ source,
1545
+ ...typeof manifest.placeholder === "string" && manifest.placeholder.trim() ? { placeholder: manifest.placeholder.trim() } : {}
1040
1546
  };
1041
1547
  }
1548
+ async function templatesIn(root, source) {
1549
+ const found = /* @__PURE__ */ new Map();
1550
+ if (!root || !existsSync(root)) return found;
1551
+ for (const entry of await fs.readdir(root, { withFileTypes: true })) {
1552
+ if (!entry.isDirectory()) continue;
1553
+ const dir = path.join(root, entry.name);
1554
+ const summary = await readTemplateDir(dir, entry.name, source);
1555
+ if (summary) found.set(entry.name, {
1556
+ dir,
1557
+ summary
1558
+ });
1559
+ }
1560
+ return found;
1561
+ }
1042
1562
  /**
1043
- * Whole-file overwrite. `expected` is the source the caller believes is on
1044
- * disk; passing it turns a blind overwrite into a conflict check, which is what
1045
- * keeps two agents (or an agent and a person) from clobbering each other.
1563
+ * Every template a document can start from: the ones open-doc ships, then the
1564
+ * workspace's own `templates/<name>/`, which win on a shared name — a team's
1565
+ * `report` is the report they mean.
1046
1566
  */
1047
- async function writeDocument(ctx, docId, source, expected) {
1048
- const entry = resolveEntry(ctx, docId);
1049
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1050
- if (expected !== void 0) {
1051
- if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
1567
+ async function allTemplates(ctx) {
1568
+ const root = await corePackageRoot();
1569
+ const builtin = await templatesIn(root && path.join(root, "templates"), "builtin");
1570
+ const workspace = await templatesIn(path.join(ctx.userCwd, "templates"), "workspace");
1571
+ return new Map([...builtin, ...workspace]);
1572
+ }
1573
+ async function listTemplates(ctx) {
1574
+ return [...(await allTemplates(ctx)).values()].map(({ summary: { placeholder: _, ...summary } }) => summary).sort((a, b) => Number(a.name === "blank") - Number(b.name === "blank") || a.category.localeCompare(b.category) || a.name.localeCompare(b.name));
1575
+ }
1576
+ const slugOf = (text) => text.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
1577
+ /**
1578
+ * A free id from a title, else the template's name — a title in Chinese has
1579
+ * no letters to make one from: `quarterly-report`, then `quarterly-report-2`.
1580
+ */
1581
+ function suggestDocId(bases, taken) {
1582
+ const slug = bases.map(slugOf).find(Boolean) || "document";
1583
+ if (!taken.has(slug)) return slug;
1584
+ for (let n = 2;; n++) if (!taken.has(`${slug}-${n}`)) return `${slug}-${n}`;
1585
+ }
1586
+ /**
1587
+ * A new document copied from a template: its folder as it is, minus the
1588
+ * manifest, with the title it was given and today as its creation date — so
1589
+ * it sorts as new, not as old as the template.
1590
+ */
1591
+ async function createFromTemplate(ctx, opts) {
1592
+ const template = (await allTemplates(ctx)).get(opts.template);
1593
+ if (!template) throw new OpsError(404, `no template named "${opts.template}" — see \`open-doc templates\``);
1594
+ const title = opts.title === void 0 ? void 0 : validateDocTitle(opts.title);
1595
+ if (opts.title !== void 0 && !title) throw new OpsError(400, "invalid title");
1596
+ const taken = new Set(await listDocIds$1(ctx));
1597
+ const id = opts.docId ?? suggestDocId([title ?? "", template.summary.name], taken);
1598
+ if (!DOC_ID_RE.test(id)) throw new OpsError(400, `invalid document id: ${id}`);
1599
+ if (taken.has(id)) throw new OpsError(409, `document already exists: ${id}`);
1600
+ const dir = path.join(ctx.docsRoot, id);
1601
+ await fs.cp(template.dir, dir, {
1602
+ recursive: true,
1603
+ filter: (src) => path.basename(src) !== MANIFEST
1604
+ });
1605
+ const entry = path.join(dir, "index.tsx");
1606
+ let source = await fs.readFile(entry, "utf8");
1607
+ source = setMetaString(source, "createdAt", (/* @__PURE__ */ new Date()).toISOString()) ?? source;
1608
+ if (title) {
1609
+ const placeholder = template.summary.placeholder;
1610
+ if (placeholder && !/[{}<>'"\\\n]/.test(title)) source = source.split(placeholder).join(title);
1611
+ source = setMetaString(source, "title", title) ?? source;
1052
1612
  }
1053
1613
  await fs.writeFile(entry, source, "utf8");
1054
1614
  return {
1055
- id: docId,
1615
+ id,
1056
1616
  entry: path.relative(ctx.userCwd, entry)
1057
1617
  };
1058
1618
  }
1059
- async function renameDocument(ctx, docId, rawTitle) {
1060
- const title = validateDocTitle(rawTitle);
1061
- if (!title) throw new OpsError(400, "invalid title");
1062
- const entry = resolveEntry(ctx, docId);
1063
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1064
- const source = await fs.readFile(entry, "utf8");
1065
- const next = setMetaTitle(source, title);
1066
- if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
1067
- if (next !== source) await fs.writeFile(entry, next, "utf8");
1068
- return {
1069
- id: docId,
1070
- title
1071
- };
1072
- }
1073
- async function duplicateDocument(ctx, docId, newId) {
1074
- const dir = docDir(ctx, docId);
1075
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
1076
- const taken = new Set(await listDocIds(ctx));
1077
- let targetId;
1078
- if (newId) {
1079
- if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
1080
- if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
1081
- targetId = newId;
1082
- } else targetId = nextCopyId(docId, taken);
1083
- await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
1084
- const entry = resolveEntry(ctx, targetId);
1085
- if (entry) {
1086
- const source = await fs.readFile(entry, "utf8");
1087
- const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
1088
- if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
1089
- }
1090
- const manifest = await readManifest(ctx.manifestPath);
1091
- const folderId = manifest.assignments[docId];
1092
- if (folderId) {
1093
- manifest.assignments[targetId] = folderId;
1094
- await writeManifest(ctx.manifestPath, manifest);
1095
- }
1096
- return { id: targetId };
1097
- }
1098
- async function deleteDocument(ctx, docId) {
1099
- const dir = docDir(ctx, docId);
1100
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
1101
- await fs.rm(dir, {
1102
- recursive: true,
1103
- force: true
1619
+ //#endregion
1620
+ //#region src/vite/routes/templates.ts
1621
+ /**
1622
+ * Tells the dev server a document was just written, instead of waiting for the
1623
+ * file watcher. On Linux the watcher can be late to a folder created and
1624
+ * filled in one go, and the browser, already sent to the new document, finds
1625
+ * none until it notices.
1626
+ */
1627
+ function announceDocument(server, ctx, docId) {
1628
+ server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
1629
+ }
1630
+ function registerTemplateRoutes(server, ctx) {
1631
+ server.middlewares.use("/__templates", async (req, res, next) => {
1632
+ const url = new URL(req.url ?? "/", "http://local");
1633
+ const method = req.method ?? "GET";
1634
+ try {
1635
+ if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
1636
+ const create = url.pathname.match(/^\/([^/]+)\/create$/);
1637
+ if (create && method === "POST") {
1638
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1639
+ if (!check.ok) return json(res, check.status, { error: check.error });
1640
+ const body = await readBody(req);
1641
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1642
+ const docId = text(body.docId);
1643
+ const title = text(body.title);
1644
+ const result = await createFromTemplate(ctx, {
1645
+ template: decodeURIComponent(create[1]),
1646
+ ...docId ? { docId } : {},
1647
+ ...title ? { title } : {}
1648
+ });
1649
+ const folderId = text(body.folderId);
1650
+ if (folderId) await fileDocument(ctx, result.id, folderId);
1651
+ announceDocument(server, ctx, result.id);
1652
+ return json(res, 200, {
1653
+ ok: true,
1654
+ docId: result.id
1655
+ });
1656
+ }
1657
+ return next();
1658
+ } catch (err) {
1659
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1660
+ json(res, 500, { error: String(err.message ?? err) });
1661
+ }
1104
1662
  });
1105
- const manifest = await readManifest(ctx.manifestPath);
1106
- if (manifest.assignments[docId]) {
1107
- delete manifest.assignments[docId];
1108
- await writeManifest(ctx.manifestPath, manifest);
1109
- }
1110
1663
  }
1111
1664
  //#endregion
1112
1665
  //#region src/vite/routes/docs.ts
@@ -1122,9 +1675,11 @@ function registerDocRoutes(server, ctx) {
1122
1675
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1123
1676
  const docId = decodeURIComponent(duplicateMatch[1]);
1124
1677
  const body = await readBody(req).catch(() => ({}));
1678
+ const result = await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0);
1679
+ announceDocument(server, ctx, result.id);
1125
1680
  return json(res, 200, {
1126
1681
  ok: true,
1127
- docId: (await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0)).id
1682
+ docId: result.id
1128
1683
  });
1129
1684
  }
1130
1685
  if (idMatch) {
@@ -1132,15 +1687,18 @@ function registerDocRoutes(server, ctx) {
1132
1687
  if (method === "PATCH") {
1133
1688
  const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
1134
1689
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1690
+ const result = await renameDocument(ctx, docId, (await readBody(req)).title);
1691
+ server.watcher.emit("change", `${ctx.docsRoot}/${docId}/index.tsx`);
1135
1692
  return json(res, 200, {
1136
1693
  ok: true,
1137
- title: (await renameDocument(ctx, docId, (await readBody(req)).title)).title
1694
+ title: result.title
1138
1695
  });
1139
1696
  }
1140
1697
  if (method === "DELETE") {
1141
1698
  const requestCheck = validateMutationRequest(req);
1142
1699
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1143
1700
  await deleteDocument(ctx, docId);
1701
+ server.watcher.emit("unlink", `${ctx.docsRoot}/${docId}/index.tsx`);
1144
1702
  return json(res, 200, { ok: true });
1145
1703
  }
1146
1704
  }
@@ -1180,6 +1738,32 @@ function parseMarkers(source) {
1180
1738
  });
1181
1739
  return comments;
1182
1740
  }
1741
+ /**
1742
+ * Where each marker's element starts. A marker is always an element's first
1743
+ * child, so the element holding it is the one the note is about; its start is
1744
+ * the `data-od-loc` the page stamps on it, which is how the viewer pins a note
1745
+ * to what it printed.
1746
+ */
1747
+ function locateMarkers(source, comments) {
1748
+ const ast = parseSource(source);
1749
+ if (!ast) return comments;
1750
+ const owner = /* @__PURE__ */ new Map();
1751
+ walkJsx(ast, (element) => {
1752
+ if (!element.loc) return;
1753
+ for (const child of element.children ?? []) {
1754
+ if (child.type !== "JSXExpressionContainer") continue;
1755
+ const id = /@doc-comment\s+id="(c-[a-f0-9]+)"/.exec(source.slice(child.start, child.end))?.[1];
1756
+ if (id) owner.set(id, `${element.loc.start.line}:${element.loc.start.column}`);
1757
+ }
1758
+ });
1759
+ return comments.map((comment) => {
1760
+ const loc = owner.get(comment.id);
1761
+ return loc ? {
1762
+ ...comment,
1763
+ loc
1764
+ } : comment;
1765
+ });
1766
+ }
1183
1767
  function newCommentId() {
1184
1768
  return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1185
1769
  }
@@ -1764,7 +2348,52 @@ function dataSource(element, ast) {
1764
2348
  });
1765
2349
  return found;
1766
2350
  }
2351
+ /** The data file behind `export const records = <name>`, when it is an import. */
2352
+ function recordsSource(ast) {
2353
+ let local = null;
2354
+ walkAst(ast, (node) => {
2355
+ if (local || node.type !== "VariableDeclarator") return;
2356
+ const id = node.id;
2357
+ const init = node.init;
2358
+ if (id.type === "Identifier" && id.name === "records" && init?.type === "Identifier") local = init.name;
2359
+ });
2360
+ if (!local) return null;
2361
+ let found = null;
2362
+ walkAst(ast, (node) => {
2363
+ if (found || node.type !== "ImportDeclaration") return;
2364
+ if ((node.specifiers ?? []).some((specifier) => specifier.local.name === local)) found = node.source.value;
2365
+ });
2366
+ return found;
2367
+ }
2368
+ /** The columns `<Field name="…">` prints anywhere inside the element. */
2369
+ function fieldNames(element) {
2370
+ const names = [];
2371
+ walkJsx(element, (node) => {
2372
+ const opening = node.openingElement;
2373
+ if (opening.name.name !== "Field") return;
2374
+ for (const attribute of opening.attributes ?? []) {
2375
+ if (attribute.type !== "JSXAttribute" || attribute.name.name !== "name") continue;
2376
+ const value = attribute.value;
2377
+ if (value?.type === "StringLiteral" && !names.includes(value.value)) names.push(value.value);
2378
+ }
2379
+ });
2380
+ return names;
2381
+ }
1767
2382
  function describe(element, ctx) {
2383
+ const info = describeText(element, ctx);
2384
+ const names = fieldNames(element);
2385
+ if (names.length === 0) return info;
2386
+ const file = ctx ? recordsSource(ctx.ast) : null;
2387
+ return {
2388
+ ...info,
2389
+ fields: {
2390
+ names,
2391
+ file
2392
+ },
2393
+ ...info.editable ? {} : { reason: file ? `the values come from ${file} — edit that file, or leave a comment for the agent` : "the values come from the document’s records" }
2394
+ };
2395
+ }
2396
+ function describeText(element, ctx) {
1768
2397
  const { parts } = resolve(element, ctx);
1769
2398
  const texts = parts.filter((part) => part.kind === "text");
1770
2399
  if (texts.length === 0) {
@@ -2696,7 +3325,10 @@ function registerEditRoutes(server, ctx) {
2696
3325
  prop: typeof body.prop === "string" ? body.prop : void 0
2697
3326
  });
2698
3327
  if (!result.ok) return json(res, result.status, { error: result.error });
2699
- if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3328
+ if (result.source !== source) {
3329
+ await fs.writeFile(entry, result.source, "utf8");
3330
+ server.watcher.emit("change", entry);
3331
+ }
2700
3332
  return json(res, 200, { ok: true });
2701
3333
  }
2702
3334
  if (method === "PUT" && url.pathname === "/texts") {
@@ -2706,7 +3338,10 @@ function registerEditRoutes(server, ctx) {
2706
3338
  if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
2707
3339
  const edits = readTextEdits(body.docId, body.edits);
2708
3340
  if (!edits) return json(res, 400, { error: "invalid payload" });
2709
- return json(res, 200, await writeTexts(ctx, body.docId, edits));
3341
+ const out = await writeTexts(ctx, body.docId, edits);
3342
+ const entry = entryFor(body.docId);
3343
+ if (entry) server.watcher.emit("change", entry);
3344
+ return json(res, 200, out);
2710
3345
  }
2711
3346
  if (method === "GET" && url.pathname === "/style") {
2712
3347
  const loc = readLoc({
@@ -2726,7 +3361,10 @@ function registerEditRoutes(server, ctx) {
2726
3361
  const texts = readTextEdits(body.docId, body.texts ?? []);
2727
3362
  const styles = readStyleEdits(body.docId, body.styles ?? []);
2728
3363
  if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
2729
- return json(res, 200, await writeEdits(ctx, body.docId, texts, styles));
3364
+ const out = await writeEdits(ctx, body.docId, texts, styles);
3365
+ const entry = entryFor(body.docId);
3366
+ if (entry) server.watcher.emit("change", entry);
3367
+ return json(res, 200, out);
2730
3368
  }
2731
3369
  if (method === "POST" && url.pathname === "/comment") {
2732
3370
  const check = validateMutationRequest(req, { requireJsonBody: true });
@@ -2740,6 +3378,7 @@ function registerEditRoutes(server, ctx) {
2740
3378
  const inserted = insertMarker(await fs.readFile(entry, "utf8"), loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
2741
3379
  if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
2742
3380
  await fs.writeFile(entry, inserted.source, "utf8");
3381
+ server.watcher.emit("change", entry);
2743
3382
  return json(res, 200, {
2744
3383
  ok: true,
2745
3384
  id: inserted.id
@@ -2759,7 +3398,8 @@ function registerEditRoutes(server, ctx) {
2759
3398
  try {
2760
3399
  if (method === "GET") {
2761
3400
  if (!entry) return json(res, 200, { comments: [] });
2762
- return json(res, 200, { comments: parseMarkers(await fs.readFile(entry, "utf8")) });
3401
+ const source = await fs.readFile(entry, "utf8");
3402
+ return json(res, 200, { comments: locateMarkers(source, parseMarkers(source)) });
2763
3403
  }
2764
3404
  if (method === "DELETE") {
2765
3405
  const check = validateMutationRequest(req);
@@ -2769,6 +3409,7 @@ function registerEditRoutes(server, ctx) {
2769
3409
  const next = removeMarker(await fs.readFile(entry, "utf8"), id);
2770
3410
  if (next === null) return json(res, 404, { error: "comment not found" });
2771
3411
  await fs.writeFile(entry, next, "utf8");
3412
+ server.watcher.emit("change", entry);
2772
3413
  return json(res, 200, { ok: true });
2773
3414
  }
2774
3415
  return next();
@@ -2886,6 +3527,8 @@ function apiPlugin(opts) {
2886
3527
  registerFolderRoutes(server, ctx);
2887
3528
  registerDocRoutes(server, ctx);
2888
3529
  registerEditRoutes(server, ctx);
3530
+ registerChangesRoutes(server, ctx);
3531
+ registerTemplateRoutes(server, ctx);
2889
3532
  }
2890
3533
  };
2891
3534
  }
@@ -3389,69 +4032,6 @@ function diagramPlugin() {
3389
4032
  };
3390
4033
  }
3391
4034
  //#endregion
3392
- //#region src/vite/loc-tags-plugin.ts
3393
- const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
3394
- "ImagePlaceholder",
3395
- "Figure",
3396
- "DataTable",
3397
- "Footnote"
3398
- ]);
3399
- function taggableName(opening) {
3400
- const name = opening.name;
3401
- if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
3402
- if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
3403
- return null;
3404
- }
3405
- function alreadyTagged(opening) {
3406
- return (opening.attributes ?? []).some((attr) => {
3407
- if (attr.type !== "JSXAttribute") return false;
3408
- return attr.name?.name === "data-od-loc";
3409
- });
3410
- }
3411
- function injectLocTags(code) {
3412
- const ast = parseSource(code);
3413
- if (!ast) return null;
3414
- const insertions = [];
3415
- walkJsx(ast, (node) => {
3416
- const opening = node.openingElement;
3417
- if (!opening || !node.loc) return;
3418
- if (!taggableName(opening) || alreadyTagged(opening)) return;
3419
- const nameNode = opening.name;
3420
- insertions.push({
3421
- offset: nameNode.end,
3422
- text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
3423
- });
3424
- });
3425
- if (insertions.length === 0) return null;
3426
- insertions.sort((a, b) => b.offset - a.offset);
3427
- let next = code;
3428
- for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
3429
- return next;
3430
- }
3431
- function isDocSourceFile(id, docsRootPosix) {
3432
- const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
3433
- if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
3434
- if (!filePath.endsWith(".tsx")) return false;
3435
- if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
3436
- return filePath.slice(docsRootPosix.length + 1).includes("/");
3437
- }
3438
- function locTagsPlugin(opts) {
3439
- const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
3440
- return {
3441
- name: "open-doc:loc-tags",
3442
- apply: "serve",
3443
- enforce: "pre",
3444
- transform(code, id) {
3445
- if (!isDocSourceFile(id, docsRoot)) return null;
3446
- const next = injectLocTags(code);
3447
- return next === null ? null : {
3448
- code: next,
3449
- map: null
3450
- };
3451
- }
3452
- };
3453
- }
3454
- //#endregion
3455
4035
  //#region src/vite/mcp-plugin.ts
3456
4036
  /**
3457
4037
  * Finds a package's ESM entry by walking `node_modules` up from the user's
@@ -3508,7 +4088,11 @@ function mcpPlugin(opts) {
3508
4088
  docsDir: opts.docsDir,
3509
4089
  assetsDir: opts.assetsDir,
3510
4090
  version: opts.coreVersion,
3511
- serverOrigin: originOf()
4091
+ serverOrigin: originOf(),
4092
+ ...opts.allowedHosts !== void 0 ? { allowedHosts: opts.allowedHosts } : {},
4093
+ onFileChange: (event, filePath) => {
4094
+ server.watcher.emit(event, filePath);
4095
+ }
3512
4096
  });
3513
4097
  return middleware(req, res, next);
3514
4098
  });
@@ -3521,142 +4105,6 @@ function mcpPlugin(opts) {
3521
4105
  };
3522
4106
  }
3523
4107
  //#endregion
3524
- //#region src/vite/themes-plugin.ts
3525
- const THEMES_VMOD = "virtual:open-doc/themes";
3526
- function resolved(id) {
3527
- return `\0${id}`;
3528
- }
3529
- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
3530
- function parseFrontmatter(raw, themeId) {
3531
- const match = raw.match(FM_RE);
3532
- const fmText = match ? match[1] : "";
3533
- const body = match ? match[2] : raw;
3534
- const data = {};
3535
- for (const line of fmText.split(/\r?\n/)) {
3536
- const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
3537
- if (!m) continue;
3538
- let value = m[2].trim();
3539
- if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
3540
- data[m[1]] = value;
3541
- }
3542
- return {
3543
- fm: {
3544
- name: data.name || themeId,
3545
- description: data.description || "",
3546
- pageSize: data.pageSize || "",
3547
- mode: data.mode || ""
3548
- },
3549
- body: body.trim()
3550
- };
3551
- }
3552
- async function findThemes(userCwd, themesDir) {
3553
- const abs = path.resolve(userCwd, themesDir);
3554
- if (!existsSync(abs)) return [];
3555
- return (await fg("*.md", {
3556
- cwd: abs,
3557
- absolute: true,
3558
- onlyFiles: true
3559
- })).sort();
3560
- }
3561
- async function readTheme(mdAbs, themesRoot) {
3562
- const id = path.basename(mdAbs, ".md");
3563
- const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
3564
- let demoAbs = null;
3565
- for (const cand of [
3566
- `${id}.demo.tsx`,
3567
- `${id}.demo.jsx`,
3568
- `${id}.demo.ts`,
3569
- `${id}.demo.js`
3570
- ]) {
3571
- const p = path.join(themesRoot, cand);
3572
- if (existsSync(p)) {
3573
- demoAbs = p;
3574
- break;
3575
- }
3576
- }
3577
- return {
3578
- id,
3579
- frontmatter: fm,
3580
- body,
3581
- demoAbs
3582
- };
3583
- }
3584
- function generateThemesModule(themes, isDev) {
3585
- const meta = themes.map((t) => ({
3586
- id: t.id,
3587
- name: t.frontmatter.name,
3588
- description: t.frontmatter.description,
3589
- pageSize: t.frontmatter.pageSize,
3590
- mode: t.frontmatter.mode,
3591
- body: t.body,
3592
- hasDemo: t.demoAbs !== null
3593
- }));
3594
- const cases = themes.flatMap((t) => {
3595
- const abs = t.demoAbs;
3596
- if (!abs) return [];
3597
- const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
3598
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
3599
- return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
3600
- }).join("\n");
3601
- return `// virtual:open-doc/themes — generated
3602
- export const themes = ${JSON.stringify(meta)};
3603
-
3604
- export async function loadThemeDemo(id) {
3605
- switch (id) {
3606
- ${cases}
3607
- default: throw new Error('Theme demo not found: ' + id);
3608
- }
3609
- }
3610
- `;
3611
- }
3612
- function themesPlugin(opts) {
3613
- const { userCwd, config } = opts;
3614
- const themesDir = config.themesDir ?? "themes";
3615
- const themesRoot = path.resolve(userCwd, themesDir);
3616
- let isDev = false;
3617
- return {
3618
- name: "open-doc:themes",
3619
- config(_c, env) {
3620
- isDev = env.command === "serve";
3621
- },
3622
- resolveId(id) {
3623
- if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
3624
- return null;
3625
- },
3626
- async load(id) {
3627
- if (id !== resolved(THEMES_VMOD)) return null;
3628
- const files = await findThemes(userCwd, themesDir);
3629
- return generateThemesModule(await Promise.all(files.map((f) => readTheme(f, themesRoot))), isDev);
3630
- },
3631
- configureServer(server) {
3632
- const isThemeFile = (p) => {
3633
- const rel = path.relative(themesRoot, p);
3634
- if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
3635
- if (rel.includes(path.sep)) return false;
3636
- return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
3637
- };
3638
- let reloadTimer = null;
3639
- const reload = () => {
3640
- if (reloadTimer) clearTimeout(reloadTimer);
3641
- reloadTimer = setTimeout(() => {
3642
- reloadTimer = null;
3643
- const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
3644
- if (mod) server.moduleGraph.invalidateModule(mod);
3645
- server.ws.send({ type: "full-reload" });
3646
- }, 150);
3647
- };
3648
- server.watcher.add(themesRoot);
3649
- for (const event of [
3650
- "add",
3651
- "unlink",
3652
- "change"
3653
- ]) server.watcher.on(event, (p) => {
3654
- if (isThemeFile(p)) reload();
3655
- });
3656
- }
3657
- };
3658
- }
3659
- //#endregion
3660
4108
  //#region src/vite/config.ts
3661
4109
  function findPackageRoot(fromFile) {
3662
4110
  let dir = path.dirname(fromFile);
@@ -3677,6 +4125,13 @@ function readCoreVersion() {
3677
4125
  }
3678
4126
  }
3679
4127
  const CORE_VERSION = readCoreVersion();
4128
+ function safeRealpath(target) {
4129
+ try {
4130
+ return existsSync(target) ? realpathSync(target) : null;
4131
+ } catch {
4132
+ return null;
4133
+ }
4134
+ }
3680
4135
  async function createViteConfig(opts) {
3681
4136
  const userCwd = path.resolve(opts.userCwd);
3682
4137
  const config = opts.config ?? await loadUserConfig(userCwd);
@@ -3685,6 +4140,25 @@ async function createViteConfig(opts) {
3685
4140
  const docsAbs = path.resolve(userCwd, docsDir);
3686
4141
  const themesAbs = path.resolve(userCwd, config.themesDir ?? "themes");
3687
4142
  const assetsAbs = path.resolve(userCwd, assetsDir);
4143
+ const isCloud = process.env.OPEN_DOC_CLOUD === "1" || Boolean(process.env.K_SERVICE);
4144
+ const allowedHosts = config.allowedHosts ?? (isCloud ? true : void 0);
4145
+ const fsAllow = /* @__PURE__ */ new Set([
4146
+ APP_ROOT,
4147
+ userCwd,
4148
+ docsAbs,
4149
+ themesAbs,
4150
+ assetsAbs
4151
+ ]);
4152
+ for (const candidate of [
4153
+ userCwd,
4154
+ docsAbs,
4155
+ themesAbs,
4156
+ assetsAbs
4157
+ ]) {
4158
+ const real = safeRealpath(candidate);
4159
+ if (real) fsAllow.add(real);
4160
+ }
4161
+ if (process.env.OPEN_DOC_MOUNT_DIR) fsAllow.add(path.resolve(process.env.OPEN_DOC_MOUNT_DIR));
3688
4162
  return {
3689
4163
  base: config.base ?? "/",
3690
4164
  root: APP_ROOT,
@@ -3726,7 +4200,8 @@ async function createViteConfig(opts) {
3726
4200
  userCwd,
3727
4201
  docsDir,
3728
4202
  assetsDir,
3729
- coreVersion: CORE_VERSION
4203
+ coreVersion: CORE_VERSION,
4204
+ ...allowedHosts !== void 0 ? { allowedHosts } : {}
3730
4205
  })] : []
3731
4206
  ],
3732
4207
  resolve: { alias: {
@@ -3737,6 +4212,8 @@ async function createViteConfig(opts) {
3737
4212
  entries: [path.join(APP_ROOT, "main.tsx")],
3738
4213
  include: [
3739
4214
  "react",
4215
+ "react/jsx-runtime",
4216
+ "react/jsx-dev-runtime",
3740
4217
  "react-dom",
3741
4218
  "react-dom/client",
3742
4219
  "react-router-dom",
@@ -3756,15 +4233,13 @@ async function createViteConfig(opts) {
3756
4233
  }] }
3757
4234
  },
3758
4235
  server: {
3759
- port: config.port ?? 5273,
3760
- ...config.allowedHosts !== void 0 ? { allowedHosts: config.allowedHosts } : {},
3761
- fs: { allow: [
3762
- APP_ROOT,
3763
- userCwd,
3764
- docsAbs,
3765
- themesAbs,
3766
- assetsAbs
3767
- ] }
4236
+ port: config.port ?? (process.env.PORT ? Number(process.env.PORT) : 5273),
4237
+ ...allowedHosts !== void 0 ? { allowedHosts } : {},
4238
+ ...isCloud ? { watch: {
4239
+ usePolling: true,
4240
+ interval: 1500
4241
+ } } : {},
4242
+ fs: { allow: [...fsAllow] }
3768
4243
  },
3769
4244
  build: {
3770
4245
  outDir: path.resolve(userCwd, "dist"),
@@ -3773,4 +4248,4 @@ async function createViteConfig(opts) {
3773
4248
  };
3774
4249
  }
3775
4250
  //#endregion
3776
- export { loadUserConfig as A, assetImportPath as C, validateAssetName as D, resolveScopedAssetsDir as E, makeContext as O, writeManifest as S, resolveScopedAssetFile as T, writeDocument as _, writeText as a, validateIcon as b, createDocument as c, duplicateDocument as d, listDocIds as f, resolveEntry as g, renameDocument as h, readText as i, openDocPlugin as j, DOC_ID_RE as k, deleteDocument as l, readDocument as m, parseFrontmatter as n, writeTexts as o, listDocuments as p, addComment as r, OpsError as s, createViteConfig as t, docDir as u, newFolderId as v, countAssetUsages as w, validateName as x, readManifest as y };
4251
+ export { renameDocument as A, createDocument as C, listDocIds$1 as D, duplicateDocument as E, writeDocument as M, makeContext as N, listDocuments as O, OpsError as S, docDir as T, writeAsset as _, writeTexts as a, readChanges as b, suggestDocId as c, fileDocument as d, findAssetUsages as f, readTheme as g, listThemes as h, writeText as i, resolveEntry as j, readDocument as k, createFolder as l, listFolders as m, addComment as n, createFromTemplate as o, listAssets as p, readText as r, listTemplates as s, createViteConfig as t, deleteAsset as u, validateAssetName as v, deleteDocument as w, revertChange as x, listRevisions as y };