@open-document/core 0.10.0 → 0.12.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 (86) hide show
  1. package/dist/{build-DJMLK50m.js → build-DfUfpeTR.js} +1 -1
  2. package/dist/{check-CUKuufBm.js → check-CHxiOkQG.js} +3 -3
  3. package/dist/cli/bin.js +20 -33
  4. package/dist/{config-CvzpyAUA.js → config-9IdbhVuT.js} +2015 -725
  5. package/dist/{context-B4ip7SoI.js → context-BLI1-64_.js} +2 -2
  6. package/dist/{dev-dnH7DTlD.js → dev-yNYKv5mm.js} +1 -1
  7. package/dist/{diff-QTo0A5Rx.js → diff-Bs205mOx.js} +2 -2
  8. package/dist/{export-BrRFrexj.js → export-tkquS5O5.js} +11 -4
  9. package/dist/{import-C14Vn9ER.js → import-D1hIKIr3.js} +3 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +63 -28
  12. package/dist/ops/index.d.ts +111 -2
  13. package/dist/ops/index.js +3 -3
  14. package/dist/{ops-DKidjLXP.js → ops-Dgqujq5a.js} +85 -164
  15. package/dist/package-version-C89gtYSk.js +36 -0
  16. package/dist/{preview-wKM4C6Uk.js → preview-BImdTH6K.js} +1 -1
  17. package/dist/{sdk-CpDEGRIo.d.ts → sdk-CHEGeINh.d.ts} +46 -1
  18. package/dist/templates-DT5zzqHq.js +34 -0
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +2 -1
  21. package/skills/apply-comments/SKILL.md +3 -1
  22. package/skills/create-doc/SKILL.md +2 -0
  23. package/skills/doc-authoring/SKILL.md +2 -0
  24. package/src/app/components/browser/browser-ui.tsx +21 -0
  25. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  26. package/src/app/components/changes/changes-overlay.tsx +68 -0
  27. package/src/app/components/changes/changes-panel.tsx +341 -0
  28. package/src/app/components/changes/use-changes.ts +85 -0
  29. package/src/app/components/comments/comments-overlay.tsx +50 -0
  30. package/src/app/components/comments/comments-panel.tsx +272 -0
  31. package/src/app/components/comments/use-comments.ts +61 -0
  32. package/src/app/components/doc-sidebar.tsx +32 -2
  33. package/src/app/components/inspector/field-source.tsx +41 -0
  34. package/src/app/components/inspector/format-section.tsx +434 -0
  35. package/src/app/components/inspector/inspector.tsx +311 -118
  36. package/src/app/components/inspector/use-style-edits.ts +210 -0
  37. package/src/app/components/overlay-frame.tsx +79 -0
  38. package/src/app/components/page-frame.tsx +4 -0
  39. package/src/app/components/page-placement.ts +68 -0
  40. package/src/app/components/panel/fields.tsx +95 -7
  41. package/src/app/components/record-picker.tsx +79 -0
  42. package/src/app/components/themes/theme-preview.tsx +5 -4
  43. package/src/app/lib/agent-bridge.ts +29 -1
  44. package/src/app/lib/docx/ooxml.test.ts +24 -1
  45. package/src/app/lib/docx/ooxml.ts +27 -1
  46. package/src/app/lib/export-docx.ts +3 -1
  47. package/src/app/lib/export-dom.ts +2 -1
  48. package/src/app/lib/export-html.ts +4 -2
  49. package/src/app/lib/export-image.ts +2 -1
  50. package/src/app/lib/flow-measure.test.ts +30 -0
  51. package/src/app/lib/flow-measure.ts +35 -10
  52. package/src/app/lib/i18n-ja/browser.ts +10 -0
  53. package/src/app/lib/i18n-ja/doc.ts +4 -0
  54. package/src/app/lib/i18n-ja/panels.ts +92 -5
  55. package/src/app/lib/i18n-ko/browser.ts +10 -0
  56. package/src/app/lib/i18n-ko/doc.ts +4 -0
  57. package/src/app/lib/i18n-ko/panels.ts +90 -5
  58. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  59. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  60. package/src/app/lib/i18n-zh-cn/panels.ts +88 -5
  61. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  62. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  63. package/src/app/lib/i18n-zh-tw/panels.ts +88 -5
  64. package/src/app/lib/inspector/format.ts +156 -0
  65. package/src/app/lib/records.test.ts +38 -0
  66. package/src/app/lib/records.ts +127 -0
  67. package/src/app/lib/sdk.ts +29 -0
  68. package/src/app/lib/use-doc-module.ts +7 -0
  69. package/src/app/lib/use-doc-pages.ts +15 -9
  70. package/src/app/routes/doc.tsx +274 -11
  71. package/src/app/routes/home.tsx +30 -5
  72. package/src/app/styles.css +23 -0
  73. package/templates/blank/index.tsx +63 -0
  74. package/templates/blank/template.json +6 -0
  75. package/templates/certificate/data/recipients.csv +4 -0
  76. package/templates/certificate/index.tsx +128 -0
  77. package/templates/certificate/template.json +6 -0
  78. package/templates/letter/index.tsx +106 -0
  79. package/templates/letter/template.json +5 -0
  80. package/templates/meeting-notes/index.tsx +194 -0
  81. package/templates/meeting-notes/template.json +6 -0
  82. package/templates/proposal/index.tsx +264 -0
  83. package/templates/proposal/template.json +6 -0
  84. package/templates/report/data/metrics.csv +5 -0
  85. package/templates/report/index.tsx +224 -0
  86. package/templates/report/template.json +6 -0
@@ -1,4 +1,5 @@
1
1
  import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
2
+ import { t as corePackageRoot } from "./package-version-C89gtYSk.js";
2
3
  import chalk from "chalk";
3
4
  import path from "node:path";
4
5
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -6,10 +7,12 @@ import fs from "node:fs/promises";
6
7
  import { existsSync, readFileSync } from "node:fs";
7
8
  import fg from "fast-glob";
8
9
  import { loadConfigFromFile, normalizePath } from "vite";
10
+ import { execFile } from "node:child_process";
11
+ import { promisify } from "node:util";
12
+ import { parse } from "@babel/parser";
13
+ import { createHash, randomUUID } from "node:crypto";
9
14
  import tailwindcss from "@tailwindcss/vite";
10
15
  import react from "@vitejs/plugin-react";
11
- import { parse } from "@babel/parser";
12
- import { randomUUID } from "node:crypto";
13
16
  //#region src/vite/open-doc-plugin.ts
14
17
  const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
15
18
  const CONFIG_FILE = "open-doc.config.ts";
@@ -169,6 +172,7 @@ function openDocPlugin(opts) {
169
172
  const docsRoot = path.resolve(userCwd, docsDir);
170
173
  const foldersManifestPath = path.join(docsRoot, ".folders.json");
171
174
  let isDev = false;
175
+ let listedIds = "";
172
176
  const docIdForEntry = (p) => {
173
177
  const rel = path.relative(docsRoot, p);
174
178
  if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
@@ -209,7 +213,9 @@ function openDocPlugin(opts) {
209
213
  },
210
214
  async load(id) {
211
215
  if (id === resolved$1(DOCS_VMOD)) {
212
- const { code, ignored } = await generateDocsModule(await findDocs(userCwd, docsDir), docsRoot, isDev);
216
+ const files = await findDocs(userCwd, docsDir);
217
+ listedIds = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort());
218
+ const { code, ignored } = await generateDocsModule(files, docsRoot, isDev);
213
219
  for (const docId of ignored) {
214
220
  if (warnedInvalidDocIds.has(docId)) continue;
215
221
  warnedInvalidDocIds.add(docId);
@@ -260,6 +266,13 @@ function openDocPlugin(opts) {
260
266
  server.watcher.on("add", (p) => {
261
267
  if (isDocEntry(p)) reload();
262
268
  });
269
+ server.middlewares.use("/__docs-rescan", async (_req, res) => {
270
+ const files = await findDocs(userCwd, docsDir);
271
+ const changed = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort()) !== listedIds;
272
+ if (changed) reload();
273
+ res.setHeader("content-type", "application/json");
274
+ res.end(JSON.stringify({ changed }));
275
+ });
263
276
  server.watcher.on("unlink", (p) => {
264
277
  if (isDocEntry(p)) reload();
265
278
  });
@@ -363,144 +376,927 @@ function resolveDocEntry(docsRoot, docId) {
363
376
  return null;
364
377
  }
365
378
  //#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;
379
+ //#region src/editing/babel-walk.ts
380
+ function parseSource(code) {
381
+ try {
382
+ return parse(code, {
383
+ sourceType: "module",
384
+ plugins: ["typescript", "jsx"],
385
+ errorRecovery: true
386
+ });
387
+ } catch {
388
+ return null;
389
+ }
414
390
  }
415
- function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
416
- if (scope === "@global") return globalAssetsRoot;
417
- return resolveAssetsDir(docsRoot, scope);
391
+ /**
392
+ * `parseSource`, but a source with any recovered error is refused. Reading
393
+ * tolerates a document mid-edit; writing splices text in by AST offset, and a
394
+ * best-guess tree recovered from a syntax error must never decide where.
395
+ */
396
+ function parseStrict(code) {
397
+ const ast = parseSource(code);
398
+ if (!ast) return null;
399
+ return ast.errors && ast.errors.length > 0 ? null : ast;
418
400
  }
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;
401
+ function isNode(value) {
402
+ return typeof value === "object" && value !== null && typeof value.type === "string";
426
403
  }
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}`;
404
+ /** Depth-first walk over every node; the visitor decides what it cares about. */
405
+ function walkAst(node, visit) {
406
+ if (Array.isArray(node)) {
407
+ for (const child of node) walkAst(child, visit);
408
+ return;
409
+ }
410
+ if (!isNode(node)) return;
411
+ visit(node);
412
+ for (const key of Object.keys(node)) {
413
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
414
+ walkAst(node[key], visit);
415
+ }
430
416
  }
431
- function escapeRegExp(value) {
432
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
417
+ function walkJsx(ast, visit) {
418
+ walkAst(ast, (node) => {
419
+ if (node.type === "JSXElement") visit(node);
420
+ });
433
421
  }
434
422
  /**
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.
423
+ * The JSX element whose opening tag starts at this source position.
424
+ *
425
+ * The match is exact on both line and column. Anything looser can resolve to a
426
+ * different element on the same line, and this location decides where an edit
427
+ * gets written — a near miss silently rewrites the wrong text.
438
428
  */
439
- function countAssetUsages(source, importPath) {
440
- const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
441
- return source.match(quoted)?.length ?? 0;
429
+ function findJsxAt(ast, line, column) {
430
+ let found = null;
431
+ walkJsx(ast, (node) => {
432
+ if (found) return;
433
+ const start = node.loc?.start;
434
+ if (start && start.line === line && start.column === column) found = node;
435
+ });
436
+ return found;
442
437
  }
443
- function findReferencedAssets(source, importPaths) {
444
- return importPaths.filter((p) => countAssetUsages(source, p) > 0);
438
+ /**
439
+ * Every JSX element that starts on a line, nearest column first.
440
+ *
441
+ * Columns cannot be trusted for locations derived from React's `_debugSource`:
442
+ * injecting the loc attribute shifts the columns of anything later on the same
443
+ * line, so the offset differs per element. The line survives that, so callers
444
+ * scan the line and pick by content instead.
445
+ */
446
+ function findJsxOnLine(ast, line, column) {
447
+ const hits = [];
448
+ walkJsx(ast, (node) => {
449
+ const start = node.loc?.start;
450
+ if (!start || start.line !== line) return;
451
+ hits.push({
452
+ node,
453
+ distance: Math.abs(start.column - column)
454
+ });
455
+ });
456
+ return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
445
457
  }
446
458
  //#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;
459
+ //#region src/vite/loc-tags-plugin.ts
460
+ const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
461
+ "ImagePlaceholder",
462
+ "Figure",
463
+ "DataTable",
464
+ "Footnote"
465
+ ]);
466
+ function taggableName(opening) {
467
+ const name = opening.name;
468
+ if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
469
+ if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
470
+ return null;
451
471
  }
452
- function headerValue(req, name) {
453
- return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
472
+ function alreadyTagged(opening) {
473
+ return (opening.attributes ?? []).some((attr) => {
474
+ if (attr.type !== "JSXAttribute") return false;
475
+ return attr.name?.name === "data-od-loc";
476
+ });
454
477
  }
455
- function firstCommaToken(value) {
456
- if (!value) return null;
457
- const [first] = value.split(",", 1);
458
- return first?.trim() || null;
478
+ function injectLocTags(code) {
479
+ const ast = parseSource(code);
480
+ if (!ast) return null;
481
+ const insertions = [];
482
+ walkJsx(ast, (node) => {
483
+ const opening = node.openingElement;
484
+ if (!opening || !node.loc) return;
485
+ if (!taggableName(opening) || alreadyTagged(opening)) return;
486
+ const nameNode = opening.name;
487
+ insertions.push({
488
+ offset: nameNode.end,
489
+ text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
490
+ });
491
+ });
492
+ if (insertions.length === 0) return null;
493
+ insertions.sort((a, b) => b.offset - a.offset);
494
+ let next = code;
495
+ for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
496
+ return next;
459
497
  }
460
- function requestProto(req) {
461
- const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
462
- if (forwarded === "http" || forwarded === "https") return forwarded;
463
- return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
498
+ function isDocSourceFile(id, docsRootPosix) {
499
+ const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
500
+ if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
501
+ if (!filePath.endsWith(".tsx")) return false;
502
+ if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
503
+ return filePath.slice(docsRootPosix.length + 1).includes("/");
464
504
  }
465
- function normalizedOrigin(origin) {
466
- try {
467
- const url = new URL(origin);
468
- return `${url.protocol}//${url.host}`.toLowerCase();
469
- } catch {
470
- return null;
471
- }
505
+ function locTagsPlugin(opts) {
506
+ const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
507
+ return {
508
+ name: "open-doc:loc-tags",
509
+ apply: "serve",
510
+ enforce: "pre",
511
+ transform(code, id) {
512
+ if (!isDocSourceFile(id, docsRoot)) return null;
513
+ const next = injectLocTags(code);
514
+ return next === null ? null : {
515
+ code: next,
516
+ map: null
517
+ };
518
+ }
519
+ };
472
520
  }
521
+ //#endregion
522
+ //#region src/ops/changes-diff.ts
523
+ const REVIEW_MARKER = /^\s*\{\/\*\s*@doc-comment\s.*\*\/\}\s*$/;
473
524
  /**
474
- * The dev server writes to the user's filesystem, so every mutating endpoint is
475
- * guarded against a page on another origin driving it through the browser.
525
+ * Drops hunks that only add or remove review comments. A comment is a marker
526
+ * in the source, but it is a note about the document, not a change to it —
527
+ * counting it would put every note left in review on the changes list too.
476
528
  */
477
- function validateMutationRequest(req, opts = {}) {
478
- if (opts.requireJsonBody) {
479
- if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
480
- ok: false,
481
- status: 415,
482
- error: "content-type must be application/json"
483
- };
484
- }
485
- if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
486
- ok: false,
487
- status: 403,
488
- error: "cross-site request blocked"
489
- };
490
- const originRaw = headerValue(req, "origin");
491
- if (!originRaw) return { ok: true };
492
- if (originRaw.toLowerCase() === "null") return {
493
- ok: false,
494
- status: 403,
495
- error: "opaque origin is not allowed"
496
- };
497
- const actualOrigin = normalizedOrigin(originRaw);
498
- if (!actualOrigin) return {
499
- ok: false,
500
- status: 403,
501
- error: "invalid origin header"
529
+ function withoutReviewMarkers(files) {
530
+ return files.map((file) => ({
531
+ ...file,
532
+ hunks: file.hunks.filter((hunk) => ![...hunk.removed, ...hunk.added].every((line) => REVIEW_MARKER.test(line)))
533
+ }));
534
+ }
535
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
536
+ function hunkId(file, oldStart, removed, added) {
537
+ return createHash("sha1").update(`${file}\0${oldStart}\0${removed.join("\n")}\0${added.join("\n")}`).digest("hex").slice(0, 12);
538
+ }
539
+ /**
540
+ * `git diff --unified=0 --relative` output, file by file. Paths come back
541
+ * relative to `prefix` — the document's folder — and anything outside it is
542
+ * dropped.
543
+ */
544
+ function parseUnifiedDiff(text, prefix) {
545
+ const files = [];
546
+ let file = null;
547
+ let hunk = null;
548
+ let oldPath = null;
549
+ const strip = (raw) => {
550
+ if (raw === "/dev/null") return null;
551
+ const path = raw.replace(/^[ab]\//, "");
552
+ return path.startsWith(prefix) ? path.slice(prefix.length) : null;
502
553
  };
503
- const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
554
+ for (const line of text.split("\n")) {
555
+ if (line.startsWith("diff --git ")) {
556
+ file = null;
557
+ hunk = null;
558
+ oldPath = null;
559
+ continue;
560
+ }
561
+ if (line.startsWith("--- ")) {
562
+ oldPath = line.slice(4);
563
+ continue;
564
+ }
565
+ if (line.startsWith("+++ ")) {
566
+ const before = oldPath === null ? null : strip(oldPath);
567
+ const path = strip(line.slice(4)) ?? before;
568
+ if (path === null) continue;
569
+ file = {
570
+ path,
571
+ status: oldPath === "/dev/null" ? "added" : line.slice(4) === "/dev/null" ? "deleted" : "modified",
572
+ binary: false,
573
+ hunks: []
574
+ };
575
+ files.push(file);
576
+ continue;
577
+ }
578
+ if (line.startsWith("Binary files ")) {
579
+ const match = / and (\S+) differ$/.exec(line);
580
+ const path = match ? strip(match[1]) : null;
581
+ if (path !== null) files.push({
582
+ path,
583
+ status: "modified",
584
+ binary: true,
585
+ hunks: []
586
+ });
587
+ continue;
588
+ }
589
+ const header = HUNK_HEADER.exec(line);
590
+ if (header && file) {
591
+ hunk = {
592
+ id: "",
593
+ oldStart: Number(header[1]),
594
+ oldLines: header[2] === void 0 ? 1 : Number(header[2]),
595
+ newStart: Number(header[3]),
596
+ newLines: header[4] === void 0 ? 1 : Number(header[4]),
597
+ removed: [],
598
+ added: [],
599
+ targets: []
600
+ };
601
+ file.hunks.push(hunk);
602
+ continue;
603
+ }
604
+ if (!hunk || !file) continue;
605
+ if (line.startsWith("-")) hunk.removed.push(line.slice(1));
606
+ else if (line.startsWith("+")) hunk.added.push(line.slice(1));
607
+ }
608
+ for (const changed of files) for (const h of changed.hunks) h.id = hunkId(changed.path, h.oldStart, h.removed, h.added);
609
+ return files;
610
+ }
611
+ /** A file that git does not know yet: one hunk that adds every line. */
612
+ function untrackedFile(path, source) {
613
+ const lines = source.endsWith("\n") ? source.slice(0, -1).split("\n") : source.split("\n");
614
+ return {
615
+ path,
616
+ status: "added",
617
+ binary: false,
618
+ hunks: [{
619
+ id: hunkId(path, 0, [], lines),
620
+ oldStart: 0,
621
+ oldLines: 0,
622
+ newStart: 1,
623
+ newLines: lines.length,
624
+ removed: [],
625
+ added: lines,
626
+ targets: []
627
+ }]
628
+ };
629
+ }
630
+ /** Every element the loc-tags plugin stamps, with its extent in the source. */
631
+ function taggedElements(ast) {
632
+ const out = [];
633
+ walkJsx(ast, (node) => {
634
+ const opening = node.openingElement;
635
+ if (!opening || !node.loc || !taggableName(opening)) return;
636
+ out.push({
637
+ loc: `${node.loc.start.line}:${node.loc.start.column}`,
638
+ line: node.loc.start.line,
639
+ endLine: node.loc.end.line,
640
+ start: node.start,
641
+ end: node.end
642
+ });
643
+ });
644
+ return out;
645
+ }
646
+ const contains = (outer, inner) => outer !== inner && outer.start <= inner.start && outer.end >= inner.end;
647
+ function innermost(elements, from, to) {
648
+ let best = null;
649
+ for (const el of elements) {
650
+ if (el.line > from || el.endLine < to) continue;
651
+ if (!best || contains(best, el)) best = el;
652
+ }
653
+ return best;
654
+ }
655
+ /**
656
+ * Puts each hunk of the document's own source on the elements it touches.
657
+ * Elements that start inside the hunk are the change, outermost first; a
658
+ * hunk inside one element's text marks that element; a deletion marks the
659
+ * element that now stands where the removed lines were.
660
+ */
661
+ function placeHunks(source, hunks) {
662
+ const ast = parseSource(source);
663
+ if (!ast) return;
664
+ const elements = taggedElements(ast);
665
+ for (const hunk of hunks) {
666
+ if (hunk.newLines === 0) {
667
+ const point = hunk.newStart;
668
+ const parent = innermost(elements, point, point + 1);
669
+ 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))));
670
+ if (next) hunk.targets = [{
671
+ loc: next.loc,
672
+ mark: "removed-before"
673
+ }];
674
+ else if (parent) hunk.targets = [{
675
+ loc: parent.loc,
676
+ mark: "changed"
677
+ }];
678
+ continue;
679
+ }
680
+ const from = hunk.newStart;
681
+ const to = hunk.newStart + hunk.newLines - 1;
682
+ const mark = hunk.oldLines === 0 ? "added" : "changed";
683
+ const starting = elements.filter((el) => el.line >= from && el.line <= to);
684
+ const outermost = starting.filter((el) => !starting.some((other) => contains(other, el)));
685
+ if (outermost.length > 0) {
686
+ hunk.targets = outermost.map((el) => ({
687
+ loc: el.loc,
688
+ mark
689
+ }));
690
+ continue;
691
+ }
692
+ const around = innermost(elements, from, to);
693
+ if (around) hunk.targets = [{
694
+ loc: around.loc,
695
+ mark: "changed"
696
+ }];
697
+ }
698
+ }
699
+ /**
700
+ * The file with one hunk taken back. The lines the hunk added have to still be
701
+ * where it put them — otherwise the file moved on since the viewer looked, and
702
+ * the revert is refused rather than guessed.
703
+ */
704
+ function revertHunkIn(source, hunk) {
705
+ const trailing = source.endsWith("\n");
706
+ const lines = (trailing ? source.slice(0, -1) : source).split("\n");
707
+ const at = hunk.newLines === 0 ? hunk.newStart : hunk.newStart - 1;
708
+ const current = lines.slice(at, at + hunk.newLines);
709
+ if (current.length !== hunk.added.length || current.some((line, i) => line !== hunk.added[i])) return null;
710
+ lines.splice(at, hunk.newLines, ...hunk.removed);
711
+ const next = lines.join("\n");
712
+ return trailing || next === "" ? `${next}\n` : next;
713
+ }
714
+ //#endregion
715
+ //#region src/editing/doc-ops.ts
716
+ function programBody$1(ast) {
717
+ return ast.program?.body ?? [];
718
+ }
719
+ function metaObjectOf(node) {
720
+ if (node.type !== "ExportNamedDeclaration") return null;
721
+ const decl = node.declaration;
722
+ if (decl?.type !== "VariableDeclaration") return null;
723
+ const declarations = decl.declarations ?? [];
724
+ for (const d of declarations) {
725
+ const id = d.id;
726
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
727
+ let init = d.init;
728
+ if (!init) return null;
729
+ if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
730
+ const expr = init.expression;
731
+ if (expr) init = expr;
732
+ }
733
+ return init.type === "ObjectExpression" ? init : null;
734
+ }
735
+ return null;
736
+ }
737
+ function findMetaObject(ast) {
738
+ for (const node of programBody$1(ast)) {
739
+ const object = metaObjectOf(node);
740
+ if (object) return object;
741
+ }
742
+ return null;
743
+ }
744
+ function jsString$1(value) {
745
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
746
+ }
747
+ function validateDocTitle(v) {
748
+ if (typeof v !== "string") return null;
749
+ const trimmed = v.trim();
750
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
751
+ return trimmed;
752
+ }
753
+ /**
754
+ * Rewrites `meta.title` in place, adding the property when the meta object
755
+ * exists without one. Returns null when there is no meta object to edit —
756
+ * the caller reports that rather than inventing an export.
757
+ */
758
+ function setMetaTitle(source, title) {
759
+ return setMetaString(source, "title", title);
760
+ }
761
+ /** Sets one string field of `export const meta`, adding it first when it is missing. */
762
+ function setMetaString(source, field, value) {
763
+ const ast = parseStrict(source);
764
+ if (!ast) return null;
765
+ const object = findMetaObject(ast);
766
+ if (!object) return null;
767
+ const properties = object.properties ?? [];
768
+ for (const prop of properties) {
769
+ if (prop.type !== "ObjectProperty") continue;
770
+ const p = prop;
771
+ if (p.computed) continue;
772
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== field) continue;
773
+ return source.slice(0, p.value.start) + jsString$1(value) + source.slice(p.value.end);
774
+ }
775
+ const open = object.start + 1;
776
+ const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$1(value)},\n` : `\n ${field}: ${jsString$1(value)},`;
777
+ return source.slice(0, open) + inserted + source.slice(open);
778
+ }
779
+ function readMetaTitle(source) {
780
+ const ast = parseSource(source);
781
+ if (!ast) return null;
782
+ const object = findMetaObject(ast);
783
+ if (!object) return null;
784
+ const properties = object.properties ?? [];
785
+ for (const prop of properties) {
786
+ if (prop.type !== "ObjectProperty") continue;
787
+ const p = prop;
788
+ if (p.computed) continue;
789
+ if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
790
+ if (p.value.type !== "StringLiteral") return null;
791
+ return typeof p.value.value === "string" ? p.value.value : null;
792
+ }
793
+ return null;
794
+ }
795
+ /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
796
+ function nextCopyId(baseId, taken) {
797
+ const stem = baseId.replace(/-copy(-\d+)?$/, "");
798
+ let candidate = `${stem}-copy`;
799
+ let n = 2;
800
+ while (taken.has(candidate)) {
801
+ candidate = `${stem}-copy-${n}`;
802
+ n++;
803
+ }
804
+ return candidate;
805
+ }
806
+ function copyTitle(title) {
807
+ return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
808
+ }
809
+ //#endregion
810
+ //#region src/files/folders.ts
811
+ const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
812
+ const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
813
+ function emptyManifest() {
814
+ return {
815
+ folders: [],
816
+ assignments: {}
817
+ };
818
+ }
819
+ async function readManifest(file) {
820
+ try {
821
+ const raw = await fs.readFile(file, "utf8");
822
+ const parsed = JSON.parse(raw);
823
+ return {
824
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
825
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
826
+ };
827
+ } catch (err) {
828
+ if (err.code === "ENOENT") return emptyManifest();
829
+ throw err;
830
+ }
831
+ }
832
+ async function writeManifest(file, manifest) {
833
+ await fs.mkdir(path.dirname(file), { recursive: true });
834
+ await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
835
+ }
836
+ function newFolderId() {
837
+ return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
838
+ }
839
+ function validateName(v) {
840
+ if (typeof v !== "string") return null;
841
+ const trimmed = v.trim();
842
+ if (trimmed.length < 1 || trimmed.length > 40) return null;
843
+ return trimmed;
844
+ }
845
+ function validateReorder(v, current) {
846
+ if (!Array.isArray(v) || v.length !== current.length) return null;
847
+ const known = new Set(current.map((f) => f.id));
848
+ const seen = /* @__PURE__ */ new Set();
849
+ const out = [];
850
+ for (const id of v) {
851
+ if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
852
+ if (!known.has(id) || seen.has(id)) return null;
853
+ seen.add(id);
854
+ out.push(id);
855
+ }
856
+ return out;
857
+ }
858
+ function validateIcon(v) {
859
+ if (!v || typeof v !== "object") return null;
860
+ const icon = v;
861
+ if (icon.type === "emoji") {
862
+ if (typeof icon.value !== "string") return null;
863
+ if (icon.value.length < 1 || icon.value.length > 8) return null;
864
+ return {
865
+ type: "emoji",
866
+ value: icon.value
867
+ };
868
+ }
869
+ if (icon.type === "color") {
870
+ if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
871
+ return {
872
+ type: "color",
873
+ value: icon.value
874
+ };
875
+ }
876
+ return null;
877
+ }
878
+ //#endregion
879
+ //#region src/ops/documents.ts
880
+ /**
881
+ * Operations shared by the dev API and the MCP server. Everything here takes an
882
+ * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
883
+ * and a browser calling `/__docs` end up in exactly the same code.
884
+ */
885
+ var OpsError = class extends Error {
886
+ status;
887
+ constructor(status, message) {
888
+ super(message);
889
+ this.status = status;
890
+ this.name = "OpsError";
891
+ }
892
+ };
893
+ const ENTRY_NAMES = [
894
+ "index.tsx",
895
+ "index.jsx",
896
+ "index.ts",
897
+ "index.js"
898
+ ];
899
+ function docDir(ctx, docId) {
900
+ if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
901
+ const dir = path.resolve(ctx.docsRoot, docId);
902
+ if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
903
+ return dir;
904
+ }
905
+ function resolveEntry(ctx, docId) {
906
+ const dir = docDir(ctx, docId);
907
+ for (const name of ENTRY_NAMES) {
908
+ const file = path.join(dir, name);
909
+ if (existsSync(file)) return file;
910
+ }
911
+ return null;
912
+ }
913
+ async function listDocIds$1(ctx) {
914
+ try {
915
+ return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
916
+ } catch {
917
+ return [];
918
+ }
919
+ }
920
+ /** Reads what the doc declares without executing it — a regex over `export const meta`. */
921
+ function readMetaField(source, field) {
922
+ const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
923
+ return source.slice(source.indexOf("export const meta")).match(re)?.[2];
924
+ }
925
+ async function listDocuments(ctx) {
926
+ const ids = await listDocIds$1(ctx);
927
+ const manifest = await readManifest(ctx.manifestPath);
928
+ const out = [];
929
+ for (const id of ids) {
930
+ const entry = resolveEntry(ctx, id);
931
+ const source = entry ? await fs.readFile(entry, "utf8") : "";
932
+ out.push({
933
+ id,
934
+ title: source ? readMetaTitle(source) : null,
935
+ subtitle: source ? readMetaField(source, "subtitle") : void 0,
936
+ theme: source ? readMetaField(source, "theme") : void 0,
937
+ createdAt: source ? readMetaField(source, "createdAt") : void 0,
938
+ folder: manifest.assignments[id],
939
+ entry: entry ? path.relative(ctx.userCwd, entry) : null
940
+ });
941
+ }
942
+ return out;
943
+ }
944
+ async function readDocument(ctx, docId) {
945
+ const entry = resolveEntry(ctx, docId);
946
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
947
+ return {
948
+ id: docId,
949
+ entry: path.relative(ctx.userCwd, entry),
950
+ source: await fs.readFile(entry, "utf8")
951
+ };
952
+ }
953
+ async function createDocument(ctx, docId, source) {
954
+ const dir = docDir(ctx, docId);
955
+ if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
956
+ await fs.mkdir(dir, { recursive: true });
957
+ const entry = path.join(dir, "index.tsx");
958
+ await fs.writeFile(entry, source, "utf8");
959
+ return {
960
+ id: docId,
961
+ entry: path.relative(ctx.userCwd, entry)
962
+ };
963
+ }
964
+ /**
965
+ * Whole-file overwrite. `expected` is the source the caller believes is on
966
+ * disk; passing it turns a blind overwrite into a conflict check, which is what
967
+ * keeps two agents (or an agent and a person) from clobbering each other.
968
+ */
969
+ async function writeDocument(ctx, docId, source, expected) {
970
+ const entry = resolveEntry(ctx, docId);
971
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
972
+ if (expected !== void 0) {
973
+ if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
974
+ }
975
+ await fs.writeFile(entry, source, "utf8");
976
+ return {
977
+ id: docId,
978
+ entry: path.relative(ctx.userCwd, entry)
979
+ };
980
+ }
981
+ async function renameDocument(ctx, docId, rawTitle) {
982
+ const title = validateDocTitle(rawTitle);
983
+ if (!title) throw new OpsError(400, "invalid title");
984
+ const entry = resolveEntry(ctx, docId);
985
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
986
+ const source = await fs.readFile(entry, "utf8");
987
+ const next = setMetaTitle(source, title);
988
+ if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
989
+ if (next !== source) await fs.writeFile(entry, next, "utf8");
990
+ return {
991
+ id: docId,
992
+ title
993
+ };
994
+ }
995
+ async function duplicateDocument(ctx, docId, newId) {
996
+ const dir = docDir(ctx, docId);
997
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
998
+ const taken = new Set(await listDocIds$1(ctx));
999
+ let targetId;
1000
+ if (newId) {
1001
+ if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
1002
+ if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
1003
+ targetId = newId;
1004
+ } else targetId = nextCopyId(docId, taken);
1005
+ await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
1006
+ const entry = resolveEntry(ctx, targetId);
1007
+ if (entry) {
1008
+ const source = await fs.readFile(entry, "utf8");
1009
+ const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
1010
+ if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
1011
+ }
1012
+ const manifest = await readManifest(ctx.manifestPath);
1013
+ const folderId = manifest.assignments[docId];
1014
+ if (folderId) {
1015
+ manifest.assignments[targetId] = folderId;
1016
+ await writeManifest(ctx.manifestPath, manifest);
1017
+ }
1018
+ return { id: targetId };
1019
+ }
1020
+ async function deleteDocument(ctx, docId) {
1021
+ const dir = docDir(ctx, docId);
1022
+ if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
1023
+ await fs.rm(dir, {
1024
+ recursive: true,
1025
+ force: true
1026
+ });
1027
+ const manifest = await readManifest(ctx.manifestPath);
1028
+ if (manifest.assignments[docId]) {
1029
+ delete manifest.assignments[docId];
1030
+ await writeManifest(ctx.manifestPath, manifest);
1031
+ }
1032
+ }
1033
+ //#endregion
1034
+ //#region src/ops/changes.ts
1035
+ const run = promisify(execFile);
1036
+ async function git(cwd, args) {
1037
+ const { stdout } = await run("git", args, {
1038
+ cwd,
1039
+ maxBuffer: 33554432
1040
+ });
1041
+ return stdout;
1042
+ }
1043
+ /** The document folder relative to the workspace, POSIX-style, with a trailing slash. */
1044
+ function folderOf(ctx, docId) {
1045
+ return `${path.relative(ctx.userCwd, path.join(ctx.docsRoot, docId)).split(path.sep).join("/")}/`;
1046
+ }
1047
+ async function inRepo(ctx) {
1048
+ try {
1049
+ return (await git(ctx.userCwd, ["rev-parse", "--is-inside-work-tree"])).trim() === "true" ? "yes" : "no-repo";
1050
+ } catch (err) {
1051
+ return err.code === "ENOENT" ? "no-git" : "no-repo";
1052
+ }
1053
+ }
1054
+ /**
1055
+ * What changed in one document's folder since a revision — the working tree
1056
+ * against `since`, untracked files included — with each hunk of the document's
1057
+ * own source placed on the elements it touches, so the viewer can mark them.
1058
+ */
1059
+ async function readChanges(ctx, docId, since = "HEAD") {
1060
+ const entry = resolveEntry(ctx, docId);
1061
+ if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1062
+ const repo = await inRepo(ctx);
1063
+ if (repo !== "yes") return {
1064
+ available: false,
1065
+ reason: repo
1066
+ };
1067
+ const folder = folderOf(ctx, docId);
1068
+ let commit = null;
1069
+ try {
1070
+ commit = (await git(ctx.userCwd, [
1071
+ "rev-parse",
1072
+ "--verify",
1073
+ "--quiet",
1074
+ `${since}^{commit}`
1075
+ ])).trim();
1076
+ } catch {
1077
+ if (since !== "HEAD") throw new OpsError(400, `not a revision in this repository: ${since}`);
1078
+ }
1079
+ let files = commit ? parseUnifiedDiff(await git(ctx.userCwd, [
1080
+ "diff",
1081
+ "--unified=0",
1082
+ "--no-color",
1083
+ "--no-ext-diff",
1084
+ "--relative",
1085
+ commit,
1086
+ "--",
1087
+ folder
1088
+ ]), folder) : [];
1089
+ const untracked = (await git(ctx.userCwd, [
1090
+ "ls-files",
1091
+ "--others",
1092
+ "--exclude-standard",
1093
+ "--",
1094
+ folder
1095
+ ])).split("\n").filter((file) => file.startsWith(folder));
1096
+ for (const file of untracked) {
1097
+ const rel = file.slice(folder.length);
1098
+ const buffer = await fs.readFile(path.join(ctx.userCwd, file));
1099
+ files.push(buffer.includes(0) ? {
1100
+ path: rel,
1101
+ status: "added",
1102
+ binary: true,
1103
+ hunks: []
1104
+ } : untrackedFile(rel, buffer.toString("utf8")));
1105
+ }
1106
+ files = withoutReviewMarkers(files);
1107
+ const own = files.find((file) => file.path === path.basename(entry));
1108
+ if (own && !own.binary) placeHunks(await fs.readFile(entry, "utf8"), own.hunks);
1109
+ files.sort((a, b) => a === own ? -1 : b === own ? 1 : a.path.localeCompare(b.path));
1110
+ return {
1111
+ available: true,
1112
+ since,
1113
+ commit,
1114
+ files
1115
+ };
1116
+ }
1117
+ /** Recent commits that touched the document, newest first, for choosing what to compare against. */
1118
+ async function listRevisions(ctx, docId, limit = 15) {
1119
+ if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
1120
+ if (await inRepo(ctx) !== "yes") return [];
1121
+ try {
1122
+ return (await git(ctx.userCwd, [
1123
+ "log",
1124
+ `-n${limit}`,
1125
+ "--format=%H%x1f%h%x1f%s%x1f%cr",
1126
+ "--",
1127
+ folderOf(ctx, docId)
1128
+ ])).split("\n").filter(Boolean).map((line) => {
1129
+ const [commit = "", short = "", subject = "", when = ""] = line.split("");
1130
+ return {
1131
+ commit,
1132
+ short,
1133
+ subject,
1134
+ when
1135
+ };
1136
+ });
1137
+ } catch {
1138
+ return [];
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Takes one hunk back out of the working tree. The hunk is found again by id
1143
+ * in a fresh diff, never trusted from the request, and a source file must still
1144
+ * parse afterwards — hunks can depend on each other, and a revert that leaves
1145
+ * half a JSX tag behind is refused rather than written.
1146
+ */
1147
+ async function revertChange(ctx, docId, opts) {
1148
+ const changes = await readChanges(ctx, docId, opts.since);
1149
+ if (!changes.available) throw new OpsError(409, "this workspace is not under git");
1150
+ const file = changes.files.find((candidate) => candidate.path === opts.file);
1151
+ const hunk = file?.hunks.find((candidate) => candidate.id === opts.hunk);
1152
+ if (!file || !hunk) throw new OpsError(409, "that change is no longer there — reload the changes");
1153
+ if (file.binary) throw new OpsError(422, "a binary file cannot be reverted here");
1154
+ const target = path.join(ctx.docsRoot, docId, file.path);
1155
+ const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
1156
+ if (next === null) throw new OpsError(409, "the file changed since the diff was read");
1157
+ 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");
1158
+ await fs.writeFile(target, next, "utf8");
1159
+ return { ok: true };
1160
+ }
1161
+ //#endregion
1162
+ //#region src/files/assets.ts
1163
+ const GLOBAL_SCOPE = "@global";
1164
+ const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
1165
+ const MIME_BY_EXT = {
1166
+ png: "image/png",
1167
+ jpg: "image/jpeg",
1168
+ jpeg: "image/jpeg",
1169
+ gif: "image/gif",
1170
+ svg: "image/svg+xml",
1171
+ webp: "image/webp",
1172
+ avif: "image/avif",
1173
+ ico: "image/x-icon",
1174
+ pdf: "application/pdf",
1175
+ woff: "font/woff",
1176
+ woff2: "font/woff2",
1177
+ ttf: "font/ttf",
1178
+ otf: "font/otf",
1179
+ csv: "text/csv; charset=utf-8",
1180
+ json: "application/json",
1181
+ txt: "text/plain; charset=utf-8",
1182
+ md: "text/markdown; charset=utf-8"
1183
+ };
1184
+ function mimeForFilename(name) {
1185
+ const dot = name.lastIndexOf(".");
1186
+ if (dot < 0) return "application/octet-stream";
1187
+ return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
1188
+ }
1189
+ function assetCreatedAt(birthtimeMs, mtimeMs) {
1190
+ return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
1191
+ }
1192
+ function validateAssetName(v) {
1193
+ if (typeof v !== "string") return null;
1194
+ const trimmed = v.trim();
1195
+ if (trimmed.length < 1 || trimmed.length > 120) return null;
1196
+ if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
1197
+ if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
1198
+ if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
1199
+ const dot = trimmed.lastIndexOf(".");
1200
+ if (dot <= 0 || dot === trimmed.length - 1) return null;
1201
+ return trimmed;
1202
+ }
1203
+ function resolveAssetsDir(docsRoot, docId) {
1204
+ if (!DOC_ID_RE.test(docId)) return null;
1205
+ const docDir = path.resolve(docsRoot, docId);
1206
+ if (!docDir.startsWith(docsRoot + path.sep)) return null;
1207
+ const assetsDir = path.resolve(docDir, "assets");
1208
+ if (assetsDir !== path.join(docDir, "assets")) return null;
1209
+ return assetsDir;
1210
+ }
1211
+ function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
1212
+ if (scope === "@global") return globalAssetsRoot;
1213
+ return resolveAssetsDir(docsRoot, scope);
1214
+ }
1215
+ function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
1216
+ if (!validateAssetName(filename)) return null;
1217
+ const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
1218
+ if (!dir) return null;
1219
+ const file = path.resolve(dir, filename);
1220
+ if (!file.startsWith(dir + path.sep)) return null;
1221
+ return file;
1222
+ }
1223
+ /** How a document imports an asset — the string we look for when counting usages. */
1224
+ function assetImportPath(scope, filename) {
1225
+ return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
1226
+ }
1227
+ function escapeRegExp(value) {
1228
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1229
+ }
1230
+ /**
1231
+ * Counts references to an asset in a document's source. Matches the quoted path
1232
+ * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
1233
+ * which is every form the authoring skill sanctions.
1234
+ */
1235
+ function countAssetUsages(source, importPath) {
1236
+ const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
1237
+ return source.match(quoted)?.length ?? 0;
1238
+ }
1239
+ function findReferencedAssets(source, importPaths) {
1240
+ return importPaths.filter((p) => countAssetUsages(source, p) > 0);
1241
+ }
1242
+ //#endregion
1243
+ //#region src/http/request-guard.ts
1244
+ function firstHeaderValue(value) {
1245
+ if (Array.isArray(value)) return value[0] ?? null;
1246
+ return value ?? null;
1247
+ }
1248
+ function headerValue(req, name) {
1249
+ return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
1250
+ }
1251
+ function firstCommaToken(value) {
1252
+ if (!value) return null;
1253
+ const [first] = value.split(",", 1);
1254
+ return first?.trim() || null;
1255
+ }
1256
+ function requestProto(req) {
1257
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
1258
+ if (forwarded === "http" || forwarded === "https") return forwarded;
1259
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
1260
+ }
1261
+ function normalizedOrigin(origin) {
1262
+ try {
1263
+ const url = new URL(origin);
1264
+ return `${url.protocol}//${url.host}`.toLowerCase();
1265
+ } catch {
1266
+ return null;
1267
+ }
1268
+ }
1269
+ /**
1270
+ * The dev server writes to the user's filesystem, so every mutating endpoint is
1271
+ * guarded against a page on another origin driving it through the browser.
1272
+ */
1273
+ function validateMutationRequest(req, opts = {}) {
1274
+ if (opts.requireJsonBody) {
1275
+ if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
1276
+ ok: false,
1277
+ status: 415,
1278
+ error: "content-type must be application/json"
1279
+ };
1280
+ }
1281
+ if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
1282
+ ok: false,
1283
+ status: 403,
1284
+ error: "cross-site request blocked"
1285
+ };
1286
+ const originRaw = headerValue(req, "origin");
1287
+ if (!originRaw) return { ok: true };
1288
+ if (originRaw.toLowerCase() === "null") return {
1289
+ ok: false,
1290
+ status: 403,
1291
+ error: "opaque origin is not allowed"
1292
+ };
1293
+ const actualOrigin = normalizedOrigin(originRaw);
1294
+ if (!actualOrigin) return {
1295
+ ok: false,
1296
+ status: 403,
1297
+ error: "invalid origin header"
1298
+ };
1299
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
504
1300
  if (!host) return {
505
1301
  ok: false,
506
1302
  status: 400,
@@ -515,7 +1311,7 @@ function validateMutationRequest(req, opts = {}) {
515
1311
  }
516
1312
  //#endregion
517
1313
  //#region src/vite/routes/assets.ts
518
- async function listDocIds$1(docsRoot) {
1314
+ async function listDocIds(docsRoot) {
519
1315
  try {
520
1316
  return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
521
1317
  } catch {
@@ -546,7 +1342,7 @@ function registerAssetRoutes(server, ctx) {
546
1342
  const isGlobal = scope === GLOBAL_SCOPE;
547
1343
  if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
548
1344
  const importPath = assetImportPath(scope, filename);
549
- const docIds = isGlobal ? await listDocIds$1(ctx.docsRoot) : [scope];
1345
+ const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
550
1346
  const usages = [];
551
1347
  let totalCount = 0;
552
1348
  for (const docId of docIds) {
@@ -595,7 +1391,7 @@ function registerAssetRoutes(server, ctx) {
595
1391
  }
596
1392
  assets.sort((a, b) => a.name.localeCompare(b.name));
597
1393
  if (assets.length > 0) {
598
- const scanIds = scope === "@global" ? await listDocIds$1(ctx.docsRoot) : [scope];
1394
+ const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
599
1395
  const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
600
1396
  const paths = assets.map((a) => a.importPath);
601
1397
  for (const docId of scanIds) {
@@ -714,399 +1510,453 @@ function registerAssetRoutes(server, ctx) {
714
1510
  });
715
1511
  }
716
1512
  //#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;
773
- });
774
- return found;
775
- }
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
- });
1513
+ //#region src/vite/routes/changes.ts
1514
+ function registerChangesRoutes(server, ctx) {
1515
+ server.middlewares.use("/__changes", async (req, res, next) => {
1516
+ const url = new URL(req.url ?? "/", "http://local");
1517
+ const method = req.method ?? "GET";
1518
+ try {
1519
+ if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
1520
+ if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
1521
+ if (method === "POST" && url.pathname === "/revert") {
1522
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1523
+ if (!check.ok) return json(res, check.status, { error: check.error });
1524
+ const body = await readBody(req);
1525
+ if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
1526
+ return json(res, 200, await revertChange(ctx, body.docId, {
1527
+ file: body.file,
1528
+ hunk: body.hunk,
1529
+ ...typeof body.since === "string" ? { since: body.since } : {}
1530
+ }));
1531
+ }
1532
+ return next();
1533
+ } catch (err) {
1534
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1535
+ json(res, 500, { error: String(err.message ?? err) });
1536
+ }
793
1537
  });
794
- return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
795
1538
  }
796
1539
  //#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;
1540
+ //#region src/vite/themes-plugin.ts
1541
+ const THEMES_VMOD = "virtual:open-doc/themes";
1542
+ function resolved(id) {
1543
+ return `\0${id}`;
818
1544
  }
819
- function findMetaObject(ast) {
820
- for (const node of programBody$1(ast)) {
821
- const object = metaObjectOf(node);
822
- if (object) return object;
1545
+ const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
1546
+ function parseFrontmatter(raw, themeId) {
1547
+ const match = raw.match(FM_RE);
1548
+ const fmText = match ? match[1] : "";
1549
+ const body = match ? match[2] : raw;
1550
+ const data = {};
1551
+ for (const line of fmText.split(/\r?\n/)) {
1552
+ const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
1553
+ if (!m) continue;
1554
+ let value = m[2].trim();
1555
+ if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
1556
+ data[m[1]] = value;
823
1557
  }
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;
1558
+ return {
1559
+ fm: {
1560
+ name: data.name || themeId,
1561
+ description: data.description || "",
1562
+ pageSize: data.pageSize || "",
1563
+ mode: data.mode || ""
1564
+ },
1565
+ body: body.trim()
1566
+ };
834
1567
  }
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);
1568
+ async function findThemes(userCwd, themesDir) {
1569
+ const abs = path.resolve(userCwd, themesDir);
1570
+ if (!existsSync(abs)) return [];
1571
+ return (await fg("*.md", {
1572
+ cwd: abs,
1573
+ absolute: true,
1574
+ onlyFiles: true
1575
+ })).sort();
856
1576
  }
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;
1577
+ async function readTheme$1(mdAbs, themesRoot) {
1578
+ const id = path.basename(mdAbs, ".md");
1579
+ const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
1580
+ let demoAbs = null;
1581
+ for (const cand of [
1582
+ `${id}.demo.tsx`,
1583
+ `${id}.demo.jsx`,
1584
+ `${id}.demo.ts`,
1585
+ `${id}.demo.js`
1586
+ ]) {
1587
+ const p = path.join(themesRoot, cand);
1588
+ if (existsSync(p)) {
1589
+ demoAbs = p;
1590
+ break;
1591
+ }
870
1592
  }
871
- return null;
1593
+ return {
1594
+ id,
1595
+ frontmatter: fm,
1596
+ body,
1597
+ demoAbs
1598
+ };
872
1599
  }
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;
1600
+ function generateThemesModule(themes, isDev) {
1601
+ const meta = themes.map((t) => ({
1602
+ id: t.id,
1603
+ name: t.frontmatter.name,
1604
+ description: t.frontmatter.description,
1605
+ pageSize: t.frontmatter.pageSize,
1606
+ mode: t.frontmatter.mode,
1607
+ body: t.body,
1608
+ hasDemo: t.demoAbs !== null
1609
+ }));
1610
+ const cases = themes.flatMap((t) => {
1611
+ const abs = t.demoAbs;
1612
+ if (!abs) return [];
1613
+ const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
1614
+ const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
1615
+ return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
1616
+ }).join("\n");
1617
+ return `// virtual:open-doc/themes — generated
1618
+ export const themes = ${JSON.stringify(meta)};
1619
+
1620
+ export async function loadThemeDemo(id) {
1621
+ switch (id) {
1622
+ ${cases}
1623
+ default: throw new Error('Theme demo not found: ' + id);
1624
+ }
883
1625
  }
884
- function copyTitle(title) {
885
- return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
1626
+ `;
886
1627
  }
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() {
1628
+ function themesPlugin(opts) {
1629
+ const { userCwd, config } = opts;
1630
+ const themesDir = config.themesDir ?? "themes";
1631
+ const themesRoot = path.resolve(userCwd, themesDir);
1632
+ let isDev = false;
892
1633
  return {
893
- folders: [],
894
- assignments: {}
1634
+ name: "open-doc:themes",
1635
+ config(_c, env) {
1636
+ isDev = env.command === "serve";
1637
+ },
1638
+ resolveId(id) {
1639
+ if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
1640
+ return null;
1641
+ },
1642
+ async load(id) {
1643
+ if (id !== resolved(THEMES_VMOD)) return null;
1644
+ const files = await findThemes(userCwd, themesDir);
1645
+ return generateThemesModule(await Promise.all(files.map((f) => readTheme$1(f, themesRoot))), isDev);
1646
+ },
1647
+ configureServer(server) {
1648
+ const isThemeFile = (p) => {
1649
+ const rel = path.relative(themesRoot, p);
1650
+ if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
1651
+ if (rel.includes(path.sep)) return false;
1652
+ return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
1653
+ };
1654
+ let reloadTimer = null;
1655
+ const reload = () => {
1656
+ if (reloadTimer) clearTimeout(reloadTimer);
1657
+ reloadTimer = setTimeout(() => {
1658
+ reloadTimer = null;
1659
+ const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
1660
+ if (mod) server.moduleGraph.invalidateModule(mod);
1661
+ server.ws.send({ type: "full-reload" });
1662
+ }, 150);
1663
+ };
1664
+ server.watcher.add(themesRoot);
1665
+ for (const event of [
1666
+ "add",
1667
+ "unlink",
1668
+ "change"
1669
+ ]) server.watcher.on(event, (p) => {
1670
+ if (isThemeFile(p)) reload();
1671
+ });
1672
+ }
895
1673
  };
896
1674
  }
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");
1675
+ //#endregion
1676
+ //#region src/ops/library.ts
1677
+ function themesRoot(ctx, themesDir = "themes") {
1678
+ return path.resolve(ctx.userCwd, themesDir);
913
1679
  }
914
- function newFolderId() {
915
- return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1680
+ async function themeFiles(root) {
1681
+ if (!existsSync(root)) return [];
1682
+ return (await fg("*.md", {
1683
+ cwd: root,
1684
+ absolute: true,
1685
+ onlyFiles: true
1686
+ })).sort();
916
1687
  }
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;
1688
+ function demoFor(root, id) {
1689
+ for (const cand of [
1690
+ `${id}.demo.tsx`,
1691
+ `${id}.demo.jsx`,
1692
+ `${id}.demo.ts`,
1693
+ `${id}.demo.js`
1694
+ ]) {
1695
+ const p = path.join(root, cand);
1696
+ if (existsSync(p)) return p;
1697
+ }
1698
+ return null;
922
1699
  }
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();
1700
+ async function listThemes(ctx, themesDir) {
1701
+ const root = themesRoot(ctx, themesDir);
927
1702
  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);
1703
+ for (const file of await themeFiles(root)) {
1704
+ const id = path.basename(file, ".md");
1705
+ const { fm } = parseFrontmatter(await fs.readFile(file, "utf8"), id);
1706
+ out.push({
1707
+ id,
1708
+ name: fm.name,
1709
+ description: fm.description,
1710
+ pageSize: fm.pageSize,
1711
+ mode: fm.mode,
1712
+ hasDemo: demoFor(root, id) !== null
1713
+ });
933
1714
  }
934
1715
  return out;
935
1716
  }
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
1717
  /**
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.
1718
+ * The full theme document. This is what an agent reads before writing a doc —
1719
+ * the palette, type scale, and paste-ready components live in the body.
962
1720
  */
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;
1721
+ async function readTheme(ctx, themeId, themesDir) {
1722
+ const root = themesRoot(ctx, themesDir);
1723
+ const file = path.join(root, `${themeId}.md`);
1724
+ if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
1725
+ const { fm, body } = parseFrontmatter(await fs.readFile(file, "utf8"), themeId);
1726
+ const demoAbs = demoFor(root, themeId);
1727
+ return {
1728
+ id: themeId,
1729
+ frontmatter: fm,
1730
+ body,
1731
+ demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
1732
+ };
982
1733
  }
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;
1734
+ /** `scope` is a document id, or `global` for the shared assets directory. */
1735
+ async function listAssets(ctx, scope) {
1736
+ const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1737
+ if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1738
+ if (!existsSync(dir)) return [];
1739
+ const names = await fs.readdir(dir);
1740
+ const out = [];
1741
+ for (const filename of names.sort()) {
1742
+ const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
1743
+ if (!stat?.isFile()) continue;
1744
+ out.push({
1745
+ scope,
1746
+ filename,
1747
+ bytes: stat.size,
1748
+ importPath: assetImportPath(scope, filename)
1749
+ });
988
1750
  }
989
- return null;
1751
+ return out;
990
1752
  }
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
- }
1753
+ async function writeAsset(ctx, scope, filename, data) {
1754
+ const name = validateAssetName(filename);
1755
+ if (!name) throw new OpsError(400, "invalid filename");
1756
+ const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1757
+ if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1758
+ await fs.mkdir(dir, { recursive: true });
1759
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1760
+ if (!file) throw new OpsError(400, "invalid filename");
1761
+ await fs.writeFile(file, data);
1762
+ return {
1763
+ scope,
1764
+ filename: name,
1765
+ bytes: data.byteLength,
1766
+ importPath: assetImportPath(scope, name)
1767
+ };
997
1768
  }
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];
1769
+ async function deleteAsset(ctx, scope, filename) {
1770
+ const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1771
+ if (!file) throw new OpsError(400, "invalid filename");
1772
+ if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1773
+ await fs.rm(file);
1002
1774
  }
1003
- async function listDocuments(ctx) {
1004
- const ids = await listDocIds(ctx);
1005
- const manifest = await readManifest(ctx.manifestPath);
1775
+ /** Which documents import this asset — check before deleting one. */
1776
+ async function findAssetUsages(ctx, scope, filename) {
1777
+ const importPath = assetImportPath(scope, filename);
1006
1778
  const out = [];
1007
- for (const id of ids) {
1779
+ for (const id of await listDocIds$1(ctx)) {
1008
1780
  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
1781
+ if (!entry) continue;
1782
+ const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
1783
+ if (count > 0) out.push({
1784
+ docId: id,
1785
+ count
1018
1786
  });
1019
1787
  }
1020
1788
  return out;
1021
1789
  }
1022
- async function readDocument(ctx, docId) {
1023
- const entry = resolveEntry(ctx, docId);
1024
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
1790
+ async function listFolders(ctx) {
1791
+ const manifest = await readManifest(ctx.manifestPath);
1025
1792
  return {
1026
- id: docId,
1027
- entry: path.relative(ctx.userCwd, entry),
1028
- source: await fs.readFile(entry, "utf8")
1793
+ folders: manifest.folders,
1794
+ assignments: manifest.assignments
1029
1795
  };
1030
1796
  }
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");
1797
+ /** Folders always carry an icon; agents rarely care, so this is the fallback. */
1798
+ const DEFAULT_FOLDER_ICON = {
1799
+ type: "color",
1800
+ value: "#6b7280"
1801
+ };
1802
+ async function createFolder(ctx, rawName, rawIcon) {
1803
+ const name = validateName(rawName);
1804
+ if (!name) throw new OpsError(400, "invalid folder name");
1805
+ const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1806
+ if (!icon) throw new OpsError(400, "invalid icon");
1807
+ const manifest = await readManifest(ctx.manifestPath);
1808
+ const folder = {
1809
+ id: newFolderId(),
1810
+ name,
1811
+ icon
1812
+ };
1813
+ manifest.folders.push(folder);
1814
+ await writeManifest(ctx.manifestPath, manifest);
1815
+ return folder;
1816
+ }
1817
+ /** Filing only edits assignments — a document id never moves on disk. */
1818
+ async function fileDocument(ctx, docId, folderId) {
1819
+ const manifest = await readManifest(ctx.manifestPath);
1820
+ if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1821
+ if (folderId === null) delete manifest.assignments[docId];
1822
+ else manifest.assignments[docId] = folderId;
1823
+ await writeManifest(ctx.manifestPath, manifest);
1824
+ }
1825
+ //#endregion
1826
+ //#region src/ops/templates.ts
1827
+ const TEMPLATE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
1828
+ const MANIFEST = "template.json";
1829
+ async function readTemplateDir(dir, name, source) {
1830
+ if (!TEMPLATE_NAME_RE.test(name) || !existsSync(path.join(dir, "index.tsx"))) return null;
1831
+ let manifest = {};
1832
+ try {
1833
+ manifest = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), "utf8"));
1834
+ } catch {}
1835
+ const text = (value, fallback) => typeof value === "string" && value.trim() ? value.trim() : fallback;
1037
1836
  return {
1038
- id: docId,
1039
- entry: path.relative(ctx.userCwd, entry)
1837
+ name,
1838
+ title: text(manifest.title, name),
1839
+ description: text(manifest.description, ""),
1840
+ category: text(manifest.category, "general"),
1841
+ source,
1842
+ ...typeof manifest.placeholder === "string" && manifest.placeholder.trim() ? { placeholder: manifest.placeholder.trim() } : {}
1040
1843
  };
1041
1844
  }
1845
+ async function templatesIn(root, source) {
1846
+ const found = /* @__PURE__ */ new Map();
1847
+ if (!root || !existsSync(root)) return found;
1848
+ for (const entry of await fs.readdir(root, { withFileTypes: true })) {
1849
+ if (!entry.isDirectory()) continue;
1850
+ const dir = path.join(root, entry.name);
1851
+ const summary = await readTemplateDir(dir, entry.name, source);
1852
+ if (summary) found.set(entry.name, {
1853
+ dir,
1854
+ summary
1855
+ });
1856
+ }
1857
+ return found;
1858
+ }
1042
1859
  /**
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.
1860
+ * Every template a document can start from: the ones open-doc ships, then the
1861
+ * workspace's own `templates/<name>/`, which win on a shared name — a team's
1862
+ * `report` is the report they mean.
1046
1863
  */
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");
1864
+ async function allTemplates(ctx) {
1865
+ const root = await corePackageRoot();
1866
+ const builtin = await templatesIn(root && path.join(root, "templates"), "builtin");
1867
+ const workspace = await templatesIn(path.join(ctx.userCwd, "templates"), "workspace");
1868
+ return new Map([...builtin, ...workspace]);
1869
+ }
1870
+ async function listTemplates(ctx) {
1871
+ 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));
1872
+ }
1873
+ const slugOf = (text) => text.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
1874
+ /**
1875
+ * A free id from a title, else the template's name — a title in Chinese has
1876
+ * no letters to make one from: `quarterly-report`, then `quarterly-report-2`.
1877
+ */
1878
+ function suggestDocId(bases, taken) {
1879
+ const slug = bases.map(slugOf).find(Boolean) || "document";
1880
+ if (!taken.has(slug)) return slug;
1881
+ for (let n = 2;; n++) if (!taken.has(`${slug}-${n}`)) return `${slug}-${n}`;
1882
+ }
1883
+ /**
1884
+ * A new document copied from a template: its folder as it is, minus the
1885
+ * manifest, with the title it was given and today as its creation date — so
1886
+ * it sorts as new, not as old as the template.
1887
+ */
1888
+ async function createFromTemplate(ctx, opts) {
1889
+ const template = (await allTemplates(ctx)).get(opts.template);
1890
+ if (!template) throw new OpsError(404, `no template named "${opts.template}" — see \`open-doc templates\``);
1891
+ const title = opts.title === void 0 ? void 0 : validateDocTitle(opts.title);
1892
+ if (opts.title !== void 0 && !title) throw new OpsError(400, "invalid title");
1893
+ const taken = new Set(await listDocIds$1(ctx));
1894
+ const id = opts.docId ?? suggestDocId([title ?? "", template.summary.name], taken);
1895
+ if (!DOC_ID_RE.test(id)) throw new OpsError(400, `invalid document id: ${id}`);
1896
+ if (taken.has(id)) throw new OpsError(409, `document already exists: ${id}`);
1897
+ const dir = path.join(ctx.docsRoot, id);
1898
+ await fs.cp(template.dir, dir, {
1899
+ recursive: true,
1900
+ filter: (src) => path.basename(src) !== MANIFEST
1901
+ });
1902
+ const entry = path.join(dir, "index.tsx");
1903
+ let source = await fs.readFile(entry, "utf8");
1904
+ source = setMetaString(source, "createdAt", (/* @__PURE__ */ new Date()).toISOString()) ?? source;
1905
+ if (title) {
1906
+ const placeholder = template.summary.placeholder;
1907
+ if (placeholder && !/[{}<>'"\\\n]/.test(title)) source = source.split(placeholder).join(title);
1908
+ source = setMetaString(source, "title", title) ?? source;
1052
1909
  }
1053
1910
  await fs.writeFile(entry, source, "utf8");
1054
1911
  return {
1055
- id: docId,
1912
+ id,
1056
1913
  entry: path.relative(ctx.userCwd, entry)
1057
1914
  };
1058
1915
  }
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 };
1916
+ //#endregion
1917
+ //#region src/vite/routes/templates.ts
1918
+ /**
1919
+ * Tells the dev server a document was just written, instead of waiting for the
1920
+ * file watcher. On Linux the watcher can be late to a folder created and
1921
+ * filled in one go, and the browser, already sent to the new document, finds
1922
+ * none until it notices.
1923
+ */
1924
+ function announceDocument(server, ctx, docId) {
1925
+ server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
1097
1926
  }
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
1927
+ function registerTemplateRoutes(server, ctx) {
1928
+ server.middlewares.use("/__templates", async (req, res, next) => {
1929
+ const url = new URL(req.url ?? "/", "http://local");
1930
+ const method = req.method ?? "GET";
1931
+ try {
1932
+ if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
1933
+ const create = url.pathname.match(/^\/([^/]+)\/create$/);
1934
+ if (create && method === "POST") {
1935
+ const check = validateMutationRequest(req, { requireJsonBody: true });
1936
+ if (!check.ok) return json(res, check.status, { error: check.error });
1937
+ const body = await readBody(req);
1938
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1939
+ const docId = text(body.docId);
1940
+ const title = text(body.title);
1941
+ const result = await createFromTemplate(ctx, {
1942
+ template: decodeURIComponent(create[1]),
1943
+ ...docId ? { docId } : {},
1944
+ ...title ? { title } : {}
1945
+ });
1946
+ const folderId = text(body.folderId);
1947
+ if (folderId) await fileDocument(ctx, result.id, folderId);
1948
+ announceDocument(server, ctx, result.id);
1949
+ return json(res, 200, {
1950
+ ok: true,
1951
+ docId: result.id
1952
+ });
1953
+ }
1954
+ return next();
1955
+ } catch (err) {
1956
+ if (err instanceof OpsError) return json(res, err.status, { error: err.message });
1957
+ json(res, 500, { error: String(err.message ?? err) });
1958
+ }
1104
1959
  });
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
1960
  }
1111
1961
  //#endregion
1112
1962
  //#region src/vite/routes/docs.ts
@@ -1122,9 +1972,11 @@ function registerDocRoutes(server, ctx) {
1122
1972
  if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
1123
1973
  const docId = decodeURIComponent(duplicateMatch[1]);
1124
1974
  const body = await readBody(req).catch(() => ({}));
1975
+ const result = await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0);
1976
+ announceDocument(server, ctx, result.id);
1125
1977
  return json(res, 200, {
1126
1978
  ok: true,
1127
- docId: (await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0)).id
1979
+ docId: result.id
1128
1980
  });
1129
1981
  }
1130
1982
  if (idMatch) {
@@ -1180,6 +2032,32 @@ function parseMarkers(source) {
1180
2032
  });
1181
2033
  return comments;
1182
2034
  }
2035
+ /**
2036
+ * Where each marker's element starts. A marker is always an element's first
2037
+ * child, so the element holding it is the one the note is about; its start is
2038
+ * the `data-od-loc` the page stamps on it, which is how the viewer pins a note
2039
+ * to what it printed.
2040
+ */
2041
+ function locateMarkers(source, comments) {
2042
+ const ast = parseSource(source);
2043
+ if (!ast) return comments;
2044
+ const owner = /* @__PURE__ */ new Map();
2045
+ walkJsx(ast, (element) => {
2046
+ if (!element.loc) return;
2047
+ for (const child of element.children ?? []) {
2048
+ if (child.type !== "JSXExpressionContainer") continue;
2049
+ const id = /@doc-comment\s+id="(c-[a-f0-9]+)"/.exec(source.slice(child.start, child.end))?.[1];
2050
+ if (id) owner.set(id, `${element.loc.start.line}:${element.loc.start.column}`);
2051
+ }
2052
+ });
2053
+ return comments.map((comment) => {
2054
+ const loc = owner.get(comment.id);
2055
+ return loc ? {
2056
+ ...comment,
2057
+ loc
2058
+ } : comment;
2059
+ });
2060
+ }
1183
2061
  function newCommentId() {
1184
2062
  return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
1185
2063
  }
@@ -1764,7 +2642,52 @@ function dataSource(element, ast) {
1764
2642
  });
1765
2643
  return found;
1766
2644
  }
2645
+ /** The data file behind `export const records = <name>`, when it is an import. */
2646
+ function recordsSource(ast) {
2647
+ let local = null;
2648
+ walkAst(ast, (node) => {
2649
+ if (local || node.type !== "VariableDeclarator") return;
2650
+ const id = node.id;
2651
+ const init = node.init;
2652
+ if (id.type === "Identifier" && id.name === "records" && init?.type === "Identifier") local = init.name;
2653
+ });
2654
+ if (!local) return null;
2655
+ let found = null;
2656
+ walkAst(ast, (node) => {
2657
+ if (found || node.type !== "ImportDeclaration") return;
2658
+ if ((node.specifiers ?? []).some((specifier) => specifier.local.name === local)) found = node.source.value;
2659
+ });
2660
+ return found;
2661
+ }
2662
+ /** The columns `<Field name="…">` prints anywhere inside the element. */
2663
+ function fieldNames(element) {
2664
+ const names = [];
2665
+ walkJsx(element, (node) => {
2666
+ const opening = node.openingElement;
2667
+ if (opening.name.name !== "Field") return;
2668
+ for (const attribute of opening.attributes ?? []) {
2669
+ if (attribute.type !== "JSXAttribute" || attribute.name.name !== "name") continue;
2670
+ const value = attribute.value;
2671
+ if (value?.type === "StringLiteral" && !names.includes(value.value)) names.push(value.value);
2672
+ }
2673
+ });
2674
+ return names;
2675
+ }
1767
2676
  function describe(element, ctx) {
2677
+ const info = describeText(element, ctx);
2678
+ const names = fieldNames(element);
2679
+ if (names.length === 0) return info;
2680
+ const file = ctx ? recordsSource(ctx.ast) : null;
2681
+ return {
2682
+ ...info,
2683
+ fields: {
2684
+ names,
2685
+ file
2686
+ },
2687
+ ...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" }
2688
+ };
2689
+ }
2690
+ function describeText(element, ctx) {
1768
2691
  const { parts } = resolve(element, ctx);
1769
2692
  const texts = parts.filter((part) => part.kind === "text");
1770
2693
  if (texts.length === 0) {
@@ -1935,32 +2858,31 @@ function slotText(slot, edit) {
1935
2858
  if (!slot.jsx || !edit.segments) return slot.escape(edit.text);
1936
2859
  return renderSegments(mergeSegments(edit.segments), slot.escape);
1937
2860
  }
1938
- /**
1939
- * Applies several run replacements as one write.
1940
- *
1941
- * Every edit is located against the source as the caller last saw it, before
1942
- * any of them lands: an edit's `line:column` is only true of that source, and
1943
- * resolving each against the output of the previous one would find elements
1944
- * shifted by whatever was typed above them. The splices then go in back to
1945
- * front so none moves another.
1946
- *
1947
- * A failed edit is reported and skipped; the rest still land. Two edits that
1948
- * reach the same span — one prop rendered by two elements — must agree, or the
1949
- * later one is refused rather than silently winning.
1950
- */
2861
+ const SYNTAX_ERROR = {
2862
+ ok: false,
2863
+ status: 422,
2864
+ error: "the document has a syntax error — fix it in source before editing here"
2865
+ };
2866
+ /** Applies non-overlapping splices, all located against the same source, back to front. */
2867
+ function applySplices(source, splices) {
2868
+ let next = source;
2869
+ for (const splice of [...splices].sort((a, b) => b.start - a.start)) next = next.slice(0, splice.start) + splice.text + next.slice(splice.end);
2870
+ return next;
2871
+ }
1951
2872
  function replaceTextsAt(source, edits) {
1952
2873
  const ast = parseStrict(source);
1953
- if (!ast) {
1954
- const error = {
1955
- ok: false,
1956
- status: 422,
1957
- error: "the document has a syntax error — fix it in source before editing here"
1958
- };
1959
- return {
1960
- source,
1961
- results: edits.map(() => error)
1962
- };
1963
- }
2874
+ if (!ast) return {
2875
+ source,
2876
+ results: edits.map(() => SYNTAX_ERROR)
2877
+ };
2878
+ const { splices, results } = planTextEdits(ast, source, edits);
2879
+ return {
2880
+ source: applySplices(source, splices),
2881
+ results
2882
+ };
2883
+ }
2884
+ /** Where each text edit lands in `source`, without writing any of them. */
2885
+ function planTextEdits(ast, source, edits) {
1964
2886
  const results = [];
1965
2887
  const planned = [];
1966
2888
  for (const edit of edits) {
@@ -1994,27 +2916,519 @@ function replaceTextsAt(source, edits) {
1994
2916
  });
1995
2917
  continue;
1996
2918
  }
1997
- const text = slotText(found.slot, edit);
1998
- const same = planned.find((other) => other.slot.start === found.slot.start && other.slot.end === found.slot.end);
1999
- if (same && same.text !== text) {
2919
+ const text = slotText(found.slot, edit);
2920
+ const same = planned.find((other) => other.slot.start === found.slot.start && other.slot.end === found.slot.end);
2921
+ if (same && same.text !== text) {
2922
+ results.push({
2923
+ ok: false,
2924
+ status: 409,
2925
+ error: "another edit in this save rewrites the same text"
2926
+ });
2927
+ continue;
2928
+ }
2929
+ if (!same) planned.push({
2930
+ slot: found.slot,
2931
+ text
2932
+ });
2933
+ results.push({ ok: true });
2934
+ }
2935
+ return {
2936
+ splices: planned.map(({ slot, text }) => ({
2937
+ start: slot.start,
2938
+ end: slot.end,
2939
+ text
2940
+ })),
2941
+ results
2942
+ };
2943
+ }
2944
+ //#endregion
2945
+ //#region src/app/lib/inspector/format.ts
2946
+ /**
2947
+ * The element panel's Format section, shared by the viewer and the dev server:
2948
+ * which style keys it may write, which design tokens each one offers, and what
2949
+ * a value has to look like before it is spliced into a document's source.
2950
+ */
2951
+ const STYLE_PROPS = [
2952
+ "fontFamily",
2953
+ "fontSize",
2954
+ "fontWeight",
2955
+ "fontStyle",
2956
+ "textAlign",
2957
+ "lineHeight",
2958
+ "letterSpacing",
2959
+ "color",
2960
+ "background"
2961
+ ];
2962
+ function isStyleProp(value) {
2963
+ return typeof value === "string" && STYLE_PROPS.includes(value);
2964
+ }
2965
+ /** The `--od-*` variables a document's design const defines, by what they can stand for. */
2966
+ const TOKENS = {
2967
+ font: [
2968
+ {
2969
+ token: "font-heading",
2970
+ label: "Heading"
2971
+ },
2972
+ {
2973
+ token: "font-body",
2974
+ label: "Body"
2975
+ },
2976
+ {
2977
+ token: "font-mono",
2978
+ label: "Mono"
2979
+ }
2980
+ ],
2981
+ size: [
2982
+ {
2983
+ token: "size-title",
2984
+ label: "Title"
2985
+ },
2986
+ {
2987
+ token: "size-h1",
2988
+ label: "H1"
2989
+ },
2990
+ {
2991
+ token: "size-h2",
2992
+ label: "H2"
2993
+ },
2994
+ {
2995
+ token: "size-h3",
2996
+ label: "H3"
2997
+ },
2998
+ {
2999
+ token: "size-body",
3000
+ label: "Body"
3001
+ },
3002
+ {
3003
+ token: "size-caption",
3004
+ label: "Caption"
3005
+ }
3006
+ ],
3007
+ color: [
3008
+ {
3009
+ token: "text",
3010
+ label: "Text"
3011
+ },
3012
+ {
3013
+ token: "muted",
3014
+ label: "Muted"
3015
+ },
3016
+ {
3017
+ token: "accent",
3018
+ label: "Accent"
3019
+ },
3020
+ {
3021
+ token: "rule",
3022
+ label: "Rule"
3023
+ },
3024
+ {
3025
+ token: "bg",
3026
+ label: "Background"
3027
+ }
3028
+ ],
3029
+ leading: [{
3030
+ token: "leading",
3031
+ label: "Leading"
3032
+ }]
3033
+ };
3034
+ const PROP_TOKENS = {
3035
+ fontFamily: "font",
3036
+ fontSize: "size",
3037
+ color: "color",
3038
+ background: "color",
3039
+ lineHeight: "leading"
3040
+ };
3041
+ const TOKEN_VALUE = /^var\(\s*--od-([a-z0-9-]+)\s*\)$/;
3042
+ /** `var(--od-accent)` → `accent`; anything else is not a token reference. */
3043
+ function tokenOf(value) {
3044
+ return TOKEN_VALUE.exec(value.trim())?.[1] ?? null;
3045
+ }
3046
+ function isToken(prop, value) {
3047
+ const group = PROP_TOKENS[prop];
3048
+ const token = tokenOf(value);
3049
+ return group !== void 0 && token !== null && TOKENS[group].some((t) => t.token === token);
3050
+ }
3051
+ const LENGTH = /^-?\d+(\.\d+)?(px|em|rem)$/;
3052
+ const HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
3053
+ const PLAIN = /^[^;{}<>\\\n\r]{1,200}$/;
3054
+ /** Whether the panel may write this value for this key — the server's check, run again in the viewer. */
3055
+ function isValidStyleValue(prop, value) {
3056
+ if (value === null) return true;
3057
+ if (typeof value === "number") {
3058
+ if (!Number.isFinite(value)) return false;
3059
+ if (prop === "fontWeight") return value >= 100 && value <= 900 && value % 100 === 0;
3060
+ if (prop === "lineHeight") return value > 0 && value <= 10;
3061
+ return false;
3062
+ }
3063
+ if (!PLAIN.test(value)) return false;
3064
+ if (isToken(prop, value)) return true;
3065
+ switch (prop) {
3066
+ case "fontFamily": return tokenOf(value) === null;
3067
+ case "fontSize": return LENGTH.test(value) && !value.startsWith("-");
3068
+ case "letterSpacing": return LENGTH.test(value) || value === "normal";
3069
+ case "fontWeight": return value === "normal" || value === "bold";
3070
+ case "fontStyle": return value === "normal" || value === "italic";
3071
+ case "textAlign": return [
3072
+ "left",
3073
+ "center",
3074
+ "right",
3075
+ "justify",
3076
+ "start",
3077
+ "end"
3078
+ ].includes(value);
3079
+ case "lineHeight": return value === "normal";
3080
+ case "color":
3081
+ case "background": return HEX.test(value) || value === "transparent";
3082
+ }
3083
+ }
3084
+ //#endregion
3085
+ //#region src/editing/style-ops.ts
3086
+ function unwrap(node) {
3087
+ let current = node;
3088
+ while (current && (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "ParenthesizedExpression")) current = current.expression;
3089
+ return current;
3090
+ }
3091
+ function keyOf(property) {
3092
+ if (property.type !== "ObjectProperty" || property.computed) return null;
3093
+ const key = property.key;
3094
+ if (key.type === "Identifier") return key.name;
3095
+ if (key.type === "StringLiteral") return key.value;
3096
+ return null;
3097
+ }
3098
+ function sourceOf$1(value, source) {
3099
+ const node = unwrap(value) ?? value;
3100
+ if (node.type === "StringLiteral") {
3101
+ const text = node.value;
3102
+ const token = tokenOf(text);
3103
+ return token ? {
3104
+ kind: "token",
3105
+ token
3106
+ } : {
3107
+ kind: "literal",
3108
+ value: text
3109
+ };
3110
+ }
3111
+ if (node.type === "NumericLiteral") return {
3112
+ kind: "literal",
3113
+ value: node.value
3114
+ };
3115
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) {
3116
+ const text = (node.quasis[0]?.value)?.cooked ?? "";
3117
+ const token = tokenOf(text);
3118
+ return token ? {
3119
+ kind: "token",
3120
+ token
3121
+ } : {
3122
+ kind: "literal",
3123
+ value: text
3124
+ };
3125
+ }
3126
+ return {
3127
+ kind: "code",
3128
+ code: source.slice(value.start, value.end)
3129
+ };
3130
+ }
3131
+ /** A top-level `const name = { … }` — the shared style objects documents are written with. */
3132
+ function sharedObject(ast, name) {
3133
+ const body = ast.program?.body ?? [];
3134
+ for (const statement of body) {
3135
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
3136
+ if (declaration?.type !== "VariableDeclaration") continue;
3137
+ for (const declarator of declaration.declarations) {
3138
+ const id = declarator.id;
3139
+ if (id.type !== "Identifier" || id.name !== name) continue;
3140
+ const init = unwrap(declarator.init);
3141
+ return init?.type === "ObjectExpression" ? init : null;
3142
+ }
3143
+ }
3144
+ return null;
3145
+ }
3146
+ /** Folds an object's keys into `props`, later keys over earlier ones, as the spread would. */
3147
+ function readObject(ast, object, source, from, props, depth) {
3148
+ for (const property of object.properties) {
3149
+ if (property.type === "SpreadElement") {
3150
+ const argument = unwrap(property.argument);
3151
+ if (argument?.type !== "Identifier" || depth > 3) continue;
3152
+ const shared = sharedObject(ast, argument.name);
3153
+ if (shared) readObject(ast, shared, source, argument.name, props, depth + 1);
3154
+ continue;
3155
+ }
3156
+ const key = keyOf(property);
3157
+ const prop = key === "backgroundColor" ? "background" : key;
3158
+ if (!isStyleProp(prop)) continue;
3159
+ const origin = sourceOf$1(property.value, source);
3160
+ props[prop] = from ? {
3161
+ ...origin,
3162
+ from
3163
+ } : origin;
3164
+ }
3165
+ }
3166
+ function locate(ast, loc, tag) {
3167
+ const element = findJsxAt(ast, loc.line, loc.column);
3168
+ if (!element) return {
3169
+ ok: false,
3170
+ status: 404,
3171
+ error: "element not found"
3172
+ };
3173
+ const opening = element.openingElement;
3174
+ const name = opening.name;
3175
+ if (name.type !== "JSXIdentifier" || !/^[a-z]/.test(name.name)) return {
3176
+ ok: false,
3177
+ status: 422,
3178
+ error: "This is a component — its styles are set inside it, not here."
3179
+ };
3180
+ if (name.name !== tag) return {
3181
+ ok: false,
3182
+ status: 409,
3183
+ error: "source does not match this element"
3184
+ };
3185
+ const attrs = opening.attributes.filter((attr) => attr.type === "JSXAttribute" && attr.name.name === "style");
3186
+ const attr = attrs[attrs.length - 1] ?? null;
3187
+ if (!attr) return {
3188
+ ok: true,
3189
+ opening,
3190
+ attr: null,
3191
+ expression: null
3192
+ };
3193
+ const value = attr.value;
3194
+ if (value?.type !== "JSXExpressionContainer") return {
3195
+ ok: false,
3196
+ status: 422,
3197
+ error: "This element’s style is not written as an object."
3198
+ };
3199
+ return {
3200
+ ok: true,
3201
+ opening,
3202
+ attr,
3203
+ expression: value.expression
3204
+ };
3205
+ }
3206
+ function readProps(ast, source, expression) {
3207
+ const props = {};
3208
+ const node = unwrap(expression ?? void 0);
3209
+ if (node?.type === "ObjectExpression") readObject(ast, node, source, void 0, props, 0);
3210
+ else if (node?.type === "Identifier") {
3211
+ const shared = sharedObject(ast, node.name);
3212
+ if (shared) readObject(ast, shared, source, node.name, props, 1);
3213
+ }
3214
+ return props;
3215
+ }
3216
+ /** What the element at `loc` sets, key by key, for the panel to show before anything is written. */
3217
+ function readStyleAt(source, loc, tag) {
3218
+ const ast = parseSource(source);
3219
+ if (!ast) return {
3220
+ editable: false,
3221
+ reason: "could not read source"
3222
+ };
3223
+ const found = locate(ast, loc, tag);
3224
+ if (!found.ok) return {
3225
+ editable: false,
3226
+ reason: found.error
3227
+ };
3228
+ return {
3229
+ editable: true,
3230
+ props: readProps(ast, source, found.expression)
3231
+ };
3232
+ }
3233
+ function literal(value) {
3234
+ if (typeof value === "number") return String(value);
3235
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
3236
+ }
3237
+ function lineIndent(source, offset) {
3238
+ const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
3239
+ return /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? "";
3240
+ }
3241
+ function lineOf(source, offset) {
3242
+ let line = 0;
3243
+ for (let i = source.indexOf("\n"); i !== -1 && i < offset; i = source.indexOf("\n", i + 1)) line++;
3244
+ return line;
3245
+ }
3246
+ /** Writes the keys into an object literal, touching only what changes. */
3247
+ function planObject(source, object, sets, removes, attr) {
3248
+ const properties = object.properties;
3249
+ const lastSpread = properties.reduce((at, property, index) => property.type === "SpreadElement" ? index : at, -1);
3250
+ const ownIndex = (prop) => {
3251
+ for (let i = properties.length - 1; i > lastSpread; i--) {
3252
+ const key = keyOf(properties[i]);
3253
+ if (key === prop || prop === "background" && key === "backgroundColor") return i;
3254
+ }
3255
+ return -1;
3256
+ };
3257
+ const replaced = /* @__PURE__ */ new Map();
3258
+ const appended = [];
3259
+ for (const [prop, value] of sets) {
3260
+ const index = ownIndex(prop);
3261
+ if (index === -1) appended.push(`${prop}: ${literal(value)}`);
3262
+ else replaced.set(index, literal(value));
3263
+ }
3264
+ const removed = new Set(removes.map(ownIndex).filter((index) => index !== -1));
3265
+ if (removed.size === 0) {
3266
+ const splices = [];
3267
+ for (const [index, text] of replaced) {
3268
+ const value = properties[index].value;
3269
+ const shorthand = properties[index].shorthand === true;
3270
+ splices.push(shorthand ? {
3271
+ start: properties[index].start,
3272
+ end: properties[index].end,
3273
+ text: `${keyOf(properties[index])}: ${text}`
3274
+ } : {
3275
+ start: value.start,
3276
+ end: value.end,
3277
+ text
3278
+ });
3279
+ }
3280
+ if (appended.length > 0) {
3281
+ const last = properties[properties.length - 1];
3282
+ if (!last) splices.push({
3283
+ start: object.start,
3284
+ end: object.end,
3285
+ text: `{ ${appended.join(", ")} }`
3286
+ });
3287
+ else if (lineOf(source, last.start) > lineOf(source, object.start)) {
3288
+ const indent = lineIndent(source, last.start);
3289
+ const after = /^\s*,/.exec(source.slice(last.end));
3290
+ splices.push(after ? {
3291
+ start: last.end + after[0].length,
3292
+ end: last.end + after[0].length,
3293
+ text: appended.map((item) => `\n${indent}${item},`).join("")
3294
+ } : {
3295
+ start: last.end,
3296
+ end: last.end,
3297
+ text: appended.map((item) => `,\n${indent}${item}`).join("")
3298
+ });
3299
+ } else splices.push({
3300
+ start: last.end,
3301
+ end: last.end,
3302
+ text: `, ${appended.join(", ")}`
3303
+ });
3304
+ }
3305
+ return splices;
3306
+ }
3307
+ const items = [];
3308
+ properties.forEach((property, index) => {
3309
+ if (removed.has(index)) return;
3310
+ const text = replaced.get(index);
3311
+ items.push(text === void 0 ? source.slice(property.start, property.end) : `${keyOf(property)}: ${text}`);
3312
+ });
3313
+ items.push(...appended);
3314
+ if (items.length === 0) return [{
3315
+ start: /\s*$/.exec(source.slice(0, attr.start))?.index ?? attr.start,
3316
+ end: attr.end,
3317
+ text: ""
3318
+ }];
3319
+ const first = properties[0];
3320
+ if (lineOf(source, first.start) > lineOf(source, object.start)) {
3321
+ const indent = lineIndent(source, first.start);
3322
+ const closing = lineIndent(source, object.end - 1);
3323
+ return [{
3324
+ start: object.start,
3325
+ end: object.end,
3326
+ text: `{\n${items.map((item) => `${indent}${item},\n`).join("")}${closing}}`
3327
+ }];
3328
+ }
3329
+ return [{
3330
+ start: object.start,
3331
+ end: object.end,
3332
+ text: `{ ${items.join(", ")} }`
3333
+ }];
3334
+ }
3335
+ function planStyle(ast, source, edit) {
3336
+ const found = locate(ast, edit, edit.tag);
3337
+ if (!found.ok) return found;
3338
+ const sets = [];
3339
+ const removes = [];
3340
+ const current = readProps(ast, source, found.expression);
3341
+ for (const [prop, value] of Object.entries(edit.changes)) {
3342
+ if (!isStyleProp(prop)) return {
3343
+ ok: false,
3344
+ status: 400,
3345
+ error: `not a style the panel writes: ${prop}`
3346
+ };
3347
+ if (!isValidStyleValue(prop, value)) return {
3348
+ ok: false,
3349
+ status: 422,
3350
+ error: `not a value ${prop} can take: ${String(value)}`
3351
+ };
3352
+ if (edit.expected && prop in edit.expected) {
3353
+ if (JSON.stringify(current[prop] ?? null) !== JSON.stringify(edit.expected[prop] ?? null)) return {
3354
+ ok: false,
3355
+ status: 409,
3356
+ error: "this element’s style changed in source since it was selected"
3357
+ };
3358
+ }
3359
+ if (value === null) removes.push(prop);
3360
+ else sets.push([prop, value]);
3361
+ }
3362
+ const { opening, attr, expression } = found;
3363
+ const object = unwrap(expression ?? void 0);
3364
+ if (attr && object?.type === "ObjectExpression") return {
3365
+ ok: true,
3366
+ splices: planObject(source, object, sets, removes, attr)
3367
+ };
3368
+ if (sets.length === 0) return {
3369
+ ok: true,
3370
+ splices: []
3371
+ };
3372
+ const items = sets.map(([prop, value]) => `${prop}: ${literal(value)}`).join(", ");
3373
+ if (attr && expression) return {
3374
+ ok: true,
3375
+ splices: [{
3376
+ start: expression.start,
3377
+ end: expression.end,
3378
+ text: `{ ...${source.slice(expression.start, expression.end)}, ${items} }`
3379
+ }]
3380
+ };
3381
+ const attributes = opening.attributes;
3382
+ const after = attributes[attributes.length - 1] ?? opening.name;
3383
+ return {
3384
+ ok: true,
3385
+ splices: [{
3386
+ start: after.end,
3387
+ end: after.end,
3388
+ text: ` style={{ ${items} }}`
3389
+ }]
3390
+ };
3391
+ }
3392
+ function overlaps(a, b) {
3393
+ return a.start < b.end && b.start < a.end;
3394
+ }
3395
+ /**
3396
+ * Text and style changes from one save, located against the same source and
3397
+ * written as one splice pass — so a save that retyped a heading and resized it
3398
+ * is one write and one hot reload, and neither edit's location is moved by
3399
+ * the other before it is found.
3400
+ */
3401
+ function replaceEditsAt(source, texts, styles) {
3402
+ const ast = parseStrict(source);
3403
+ if (!ast) return {
3404
+ source,
3405
+ texts: texts.map(() => SYNTAX_ERROR),
3406
+ styles: styles.map(() => SYNTAX_ERROR)
3407
+ };
3408
+ const text = planTextEdits(ast, source, texts);
3409
+ const splices = [...text.splices];
3410
+ const results = [];
3411
+ for (const edit of styles) {
3412
+ const planned = planStyle(ast, source, edit);
3413
+ if (!planned.ok) {
3414
+ results.push(planned);
3415
+ continue;
3416
+ }
3417
+ if (planned.splices.some((splice) => splices.some((other) => overlaps(splice, other)))) {
2000
3418
  results.push({
2001
3419
  ok: false,
2002
3420
  status: 409,
2003
- error: "another edit in this save rewrites the same text"
3421
+ error: "another edit in this save rewrites the same source"
2004
3422
  });
2005
3423
  continue;
2006
3424
  }
2007
- if (!same) planned.push({
2008
- slot: found.slot,
2009
- text
2010
- });
3425
+ splices.push(...planned.splices);
2011
3426
  results.push({ ok: true });
2012
3427
  }
2013
- let next = source;
2014
- for (const { slot, text } of [...planned].sort((a, b) => b.slot.start - a.slot.start)) next = next.slice(0, slot.start) + text + next.slice(slot.end);
2015
3428
  return {
2016
- source: next,
2017
- results
3429
+ source: applySplices(source, splices),
3430
+ texts: text.results,
3431
+ styles: results
2018
3432
  };
2019
3433
  }
2020
3434
  //#endregion
@@ -2066,6 +3480,26 @@ async function writeTexts(ctx, docId, edits) {
2066
3480
  if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
2067
3481
  return { results: result.results };
2068
3482
  }
3483
+ /** What the element at `loc` sets in its `style`, key by key, for the element panel's Format section. */
3484
+ async function readStyle(ctx, docId, loc, tag) {
3485
+ const { source } = await sourceOf(ctx, docId);
3486
+ return readStyleAt(source, loc, tag);
3487
+ }
3488
+ /**
3489
+ * One save from the element panel: retyped text and style changes, located
3490
+ * against the same read of the file and written once. Per-edit failures are
3491
+ * reported, not thrown, like `writeTexts`.
3492
+ */
3493
+ async function writeEdits(ctx, docId, texts, styles) {
3494
+ if (texts.length + styles.length === 0) throw new OpsError(400, "at least one edit is required");
3495
+ const { entry, source } = await sourceOf(ctx, docId);
3496
+ const result = replaceEditsAt(source, texts, styles);
3497
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
3498
+ return {
3499
+ texts: result.texts,
3500
+ styles: result.styles
3501
+ };
3502
+ }
2069
3503
  /** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
2070
3504
  async function addComment(ctx, docId, loc, note, hint) {
2071
3505
  if (note.trim() === "") throw new OpsError(400, "note is empty");
@@ -2102,6 +3536,54 @@ function readSegments(value) {
2102
3536
  }
2103
3537
  return segments;
2104
3538
  }
3539
+ function readTextEdits(docId, value) {
3540
+ if (!Array.isArray(value)) return null;
3541
+ const edits = [];
3542
+ for (const raw of value) {
3543
+ const loc = readLoc({
3544
+ ...raw,
3545
+ docId
3546
+ });
3547
+ if (!loc || typeof raw.text !== "string") return null;
3548
+ edits.push({
3549
+ line: loc.line,
3550
+ column: loc.column,
3551
+ text: raw.text,
3552
+ segments: readSegments(raw.segments),
3553
+ index: typeof raw.index === "number" ? raw.index : void 0,
3554
+ prop: typeof raw.prop === "string" ? raw.prop : void 0,
3555
+ expected: typeof raw.expected === "string" ? raw.expected : void 0,
3556
+ shown: typeof raw.shown === "string" ? raw.shown : void 0
3557
+ });
3558
+ }
3559
+ return edits;
3560
+ }
3561
+ function readStyleEdits(docId, value) {
3562
+ if (!Array.isArray(value)) return null;
3563
+ const edits = [];
3564
+ for (const raw of value) {
3565
+ const loc = readLoc({
3566
+ ...raw,
3567
+ docId
3568
+ });
3569
+ const changes = raw.changes;
3570
+ if (!loc || typeof raw.tag !== "string" || typeof changes !== "object" || !changes) return null;
3571
+ const clean = {};
3572
+ for (const [key, change] of Object.entries(changes)) {
3573
+ if (change !== null && typeof change !== "string" && typeof change !== "number") return null;
3574
+ clean[key] = change;
3575
+ }
3576
+ const expected = typeof raw.expected === "object" && raw.expected !== null ? raw.expected : void 0;
3577
+ edits.push({
3578
+ line: loc.line,
3579
+ column: loc.column,
3580
+ tag: raw.tag,
3581
+ changes: clean,
3582
+ ...expected ? { expected } : {}
3583
+ });
3584
+ }
3585
+ return edits;
3586
+ }
2105
3587
  function registerEditRoutes(server, ctx) {
2106
3588
  const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
2107
3589
  server.middlewares.use("/__edit", async (req, res, next) => {
@@ -2145,26 +3627,30 @@ function registerEditRoutes(server, ctx) {
2145
3627
  if (!check.ok) return json(res, check.status, { error: check.error });
2146
3628
  const body = await readBody(req);
2147
3629
  if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
2148
- const edits = [];
2149
- for (const raw of body.edits) {
2150
- const loc = readLoc({
2151
- ...raw,
2152
- docId: body.docId
2153
- });
2154
- if (!loc || typeof raw.text !== "string") return json(res, 400, { error: "invalid payload" });
2155
- edits.push({
2156
- line: loc.line,
2157
- column: loc.column,
2158
- text: raw.text,
2159
- segments: readSegments(raw.segments),
2160
- index: typeof raw.index === "number" ? raw.index : void 0,
2161
- prop: typeof raw.prop === "string" ? raw.prop : void 0,
2162
- expected: typeof raw.expected === "string" ? raw.expected : void 0,
2163
- shown: typeof raw.shown === "string" ? raw.shown : void 0
2164
- });
2165
- }
3630
+ const edits = readTextEdits(body.docId, body.edits);
3631
+ if (!edits) return json(res, 400, { error: "invalid payload" });
2166
3632
  return json(res, 200, await writeTexts(ctx, body.docId, edits));
2167
3633
  }
3634
+ if (method === "GET" && url.pathname === "/style") {
3635
+ const loc = readLoc({
3636
+ docId: url.searchParams.get("docId"),
3637
+ line: Number(url.searchParams.get("line")),
3638
+ column: Number(url.searchParams.get("column"))
3639
+ });
3640
+ const tag = url.searchParams.get("tag") ?? "";
3641
+ if (!loc || !Number.isFinite(loc.line) || !Number.isFinite(loc.column) || tag === "") return json(res, 400, { error: "invalid target" });
3642
+ return json(res, 200, await readStyle(ctx, loc.docId, loc, tag));
3643
+ }
3644
+ if (method === "PUT" && url.pathname === "/batch") {
3645
+ const check = validateMutationRequest(req, { requireJsonBody: true });
3646
+ if (!check.ok) return json(res, check.status, { error: check.error });
3647
+ const body = await readBody(req);
3648
+ if (typeof body.docId !== "string") return json(res, 400, { error: "invalid payload" });
3649
+ const texts = readTextEdits(body.docId, body.texts ?? []);
3650
+ const styles = readStyleEdits(body.docId, body.styles ?? []);
3651
+ if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
3652
+ return json(res, 200, await writeEdits(ctx, body.docId, texts, styles));
3653
+ }
2168
3654
  if (method === "POST" && url.pathname === "/comment") {
2169
3655
  const check = validateMutationRequest(req, { requireJsonBody: true });
2170
3656
  if (!check.ok) return json(res, check.status, { error: check.error });
@@ -2196,7 +3682,8 @@ function registerEditRoutes(server, ctx) {
2196
3682
  try {
2197
3683
  if (method === "GET") {
2198
3684
  if (!entry) return json(res, 200, { comments: [] });
2199
- return json(res, 200, { comments: parseMarkers(await fs.readFile(entry, "utf8")) });
3685
+ const source = await fs.readFile(entry, "utf8");
3686
+ return json(res, 200, { comments: locateMarkers(source, parseMarkers(source)) });
2200
3687
  }
2201
3688
  if (method === "DELETE") {
2202
3689
  const check = validateMutationRequest(req);
@@ -2323,6 +3810,8 @@ function apiPlugin(opts) {
2323
3810
  registerFolderRoutes(server, ctx);
2324
3811
  registerDocRoutes(server, ctx);
2325
3812
  registerEditRoutes(server, ctx);
3813
+ registerChangesRoutes(server, ctx);
3814
+ registerTemplateRoutes(server, ctx);
2326
3815
  }
2327
3816
  };
2328
3817
  }
@@ -2826,69 +4315,6 @@ function diagramPlugin() {
2826
4315
  };
2827
4316
  }
2828
4317
  //#endregion
2829
- //#region src/vite/loc-tags-plugin.ts
2830
- const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
2831
- "ImagePlaceholder",
2832
- "Figure",
2833
- "DataTable",
2834
- "Footnote"
2835
- ]);
2836
- function taggableName(opening) {
2837
- const name = opening.name;
2838
- if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
2839
- if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
2840
- return null;
2841
- }
2842
- function alreadyTagged(opening) {
2843
- return (opening.attributes ?? []).some((attr) => {
2844
- if (attr.type !== "JSXAttribute") return false;
2845
- return attr.name?.name === "data-od-loc";
2846
- });
2847
- }
2848
- function injectLocTags(code) {
2849
- const ast = parseSource(code);
2850
- if (!ast) return null;
2851
- const insertions = [];
2852
- walkJsx(ast, (node) => {
2853
- const opening = node.openingElement;
2854
- if (!opening || !node.loc) return;
2855
- if (!taggableName(opening) || alreadyTagged(opening)) return;
2856
- const nameNode = opening.name;
2857
- insertions.push({
2858
- offset: nameNode.end,
2859
- text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
2860
- });
2861
- });
2862
- if (insertions.length === 0) return null;
2863
- insertions.sort((a, b) => b.offset - a.offset);
2864
- let next = code;
2865
- for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
2866
- return next;
2867
- }
2868
- function isDocSourceFile(id, docsRootPosix) {
2869
- const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
2870
- if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
2871
- if (!filePath.endsWith(".tsx")) return false;
2872
- if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
2873
- return filePath.slice(docsRootPosix.length + 1).includes("/");
2874
- }
2875
- function locTagsPlugin(opts) {
2876
- const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
2877
- return {
2878
- name: "open-doc:loc-tags",
2879
- apply: "serve",
2880
- enforce: "pre",
2881
- transform(code, id) {
2882
- if (!isDocSourceFile(id, docsRoot)) return null;
2883
- const next = injectLocTags(code);
2884
- return next === null ? null : {
2885
- code: next,
2886
- map: null
2887
- };
2888
- }
2889
- };
2890
- }
2891
- //#endregion
2892
4318
  //#region src/vite/mcp-plugin.ts
2893
4319
  /**
2894
4320
  * Finds a package's ESM entry by walking `node_modules` up from the user's
@@ -2958,142 +4384,6 @@ function mcpPlugin(opts) {
2958
4384
  };
2959
4385
  }
2960
4386
  //#endregion
2961
- //#region src/vite/themes-plugin.ts
2962
- const THEMES_VMOD = "virtual:open-doc/themes";
2963
- function resolved(id) {
2964
- return `\0${id}`;
2965
- }
2966
- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
2967
- function parseFrontmatter(raw, themeId) {
2968
- const match = raw.match(FM_RE);
2969
- const fmText = match ? match[1] : "";
2970
- const body = match ? match[2] : raw;
2971
- const data = {};
2972
- for (const line of fmText.split(/\r?\n/)) {
2973
- const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
2974
- if (!m) continue;
2975
- let value = m[2].trim();
2976
- if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
2977
- data[m[1]] = value;
2978
- }
2979
- return {
2980
- fm: {
2981
- name: data.name || themeId,
2982
- description: data.description || "",
2983
- pageSize: data.pageSize || "",
2984
- mode: data.mode || ""
2985
- },
2986
- body: body.trim()
2987
- };
2988
- }
2989
- async function findThemes(userCwd, themesDir) {
2990
- const abs = path.resolve(userCwd, themesDir);
2991
- if (!existsSync(abs)) return [];
2992
- return (await fg("*.md", {
2993
- cwd: abs,
2994
- absolute: true,
2995
- onlyFiles: true
2996
- })).sort();
2997
- }
2998
- async function readTheme(mdAbs, themesRoot) {
2999
- const id = path.basename(mdAbs, ".md");
3000
- const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
3001
- let demoAbs = null;
3002
- for (const cand of [
3003
- `${id}.demo.tsx`,
3004
- `${id}.demo.jsx`,
3005
- `${id}.demo.ts`,
3006
- `${id}.demo.js`
3007
- ]) {
3008
- const p = path.join(themesRoot, cand);
3009
- if (existsSync(p)) {
3010
- demoAbs = p;
3011
- break;
3012
- }
3013
- }
3014
- return {
3015
- id,
3016
- frontmatter: fm,
3017
- body,
3018
- demoAbs
3019
- };
3020
- }
3021
- function generateThemesModule(themes, isDev) {
3022
- const meta = themes.map((t) => ({
3023
- id: t.id,
3024
- name: t.frontmatter.name,
3025
- description: t.frontmatter.description,
3026
- pageSize: t.frontmatter.pageSize,
3027
- mode: t.frontmatter.mode,
3028
- body: t.body,
3029
- hasDemo: t.demoAbs !== null
3030
- }));
3031
- const cases = themes.flatMap((t) => {
3032
- const abs = t.demoAbs;
3033
- if (!abs) return [];
3034
- const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
3035
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
3036
- return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
3037
- }).join("\n");
3038
- return `// virtual:open-doc/themes — generated
3039
- export const themes = ${JSON.stringify(meta)};
3040
-
3041
- export async function loadThemeDemo(id) {
3042
- switch (id) {
3043
- ${cases}
3044
- default: throw new Error('Theme demo not found: ' + id);
3045
- }
3046
- }
3047
- `;
3048
- }
3049
- function themesPlugin(opts) {
3050
- const { userCwd, config } = opts;
3051
- const themesDir = config.themesDir ?? "themes";
3052
- const themesRoot = path.resolve(userCwd, themesDir);
3053
- let isDev = false;
3054
- return {
3055
- name: "open-doc:themes",
3056
- config(_c, env) {
3057
- isDev = env.command === "serve";
3058
- },
3059
- resolveId(id) {
3060
- if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
3061
- return null;
3062
- },
3063
- async load(id) {
3064
- if (id !== resolved(THEMES_VMOD)) return null;
3065
- const files = await findThemes(userCwd, themesDir);
3066
- return generateThemesModule(await Promise.all(files.map((f) => readTheme(f, themesRoot))), isDev);
3067
- },
3068
- configureServer(server) {
3069
- const isThemeFile = (p) => {
3070
- const rel = path.relative(themesRoot, p);
3071
- if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
3072
- if (rel.includes(path.sep)) return false;
3073
- return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
3074
- };
3075
- let reloadTimer = null;
3076
- const reload = () => {
3077
- if (reloadTimer) clearTimeout(reloadTimer);
3078
- reloadTimer = setTimeout(() => {
3079
- reloadTimer = null;
3080
- const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
3081
- if (mod) server.moduleGraph.invalidateModule(mod);
3082
- server.ws.send({ type: "full-reload" });
3083
- }, 150);
3084
- };
3085
- server.watcher.add(themesRoot);
3086
- for (const event of [
3087
- "add",
3088
- "unlink",
3089
- "change"
3090
- ]) server.watcher.on(event, (p) => {
3091
- if (isThemeFile(p)) reload();
3092
- });
3093
- }
3094
- };
3095
- }
3096
- //#endregion
3097
4387
  //#region src/vite/config.ts
3098
4388
  function findPackageRoot(fromFile) {
3099
4389
  let dir = path.dirname(fromFile);
@@ -3210,4 +4500,4 @@ async function createViteConfig(opts) {
3210
4500
  };
3211
4501
  }
3212
4502
  //#endregion
3213
- 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 };
4503
+ export { renameDocument as A, createDocument as C, listDocIds$1 as D, duplicateDocument as E, loadUserConfig as F, openDocPlugin as I, writeDocument as M, makeContext as N, listDocuments as O, DOC_ID_RE as P, 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 };