@open-document/core 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/{build-BHFGY8eF.js → build-CbgIk6bA.js} +1 -1
  2. package/dist/{check-UEBmDfT_.js → check-BTroj-5Z.js} +3 -3
  3. package/dist/cli/bin.js +58 -34
  4. package/dist/config-BWtOZ1jc.d.ts +45 -0
  5. package/dist/{config-B_pdNbYg.js → config-DKKNIbvO.js} +1458 -983
  6. package/dist/{context-BM9_-u9P.js → context-DXNP8v9I.js} +3 -2
  7. package/dist/deploy-gcp-BUiSuqz7.js +758 -0
  8. package/dist/{dev-DX3QMIRi.js → dev-YXumw5iX.js} +1 -1
  9. package/dist/{diagram-BK4jTZr4.js → diagram-CKf3ptOE.js} +293 -13
  10. package/dist/{diff-DayvbXfX.js → diff-CTFfU4Tz.js} +2 -2
  11. package/dist/{export-BPsXj1i6.js → export-D2QLtF84.js} +11 -4
  12. package/dist/flow-CS5apebG.d.ts +252 -0
  13. package/dist/{import-71wlAsrd.js → import-CcmrFetU.js} +3 -2
  14. package/dist/index.d.ts +155 -59
  15. package/dist/index.js +945 -104
  16. package/dist/open-doc-plugin-DnX5usgI.js +320 -0
  17. package/dist/ops/index.d.ts +112 -3
  18. package/dist/ops/index.js +3 -3
  19. package/dist/{ops-BUo67DaP.js → ops-DmEecq1k.js} +86 -164
  20. package/dist/package-version-C89gtYSk.js +36 -0
  21. package/dist/{preview-D3m1-gUL.js → preview-_mHpBhMk.js} +1 -1
  22. package/dist/templates-MMblHwmT.js +34 -0
  23. package/dist/vite/index.d.ts +1 -1
  24. package/dist/vite/index.js +2 -1
  25. package/package.json +2 -1
  26. package/skills/apply-comments/SKILL.md +3 -1
  27. package/skills/create-doc/SKILL.md +2 -0
  28. package/skills/doc-authoring/SKILL.md +17 -16
  29. package/skills/doc-authoring/references/long-form.md +43 -2
  30. package/skills/doc-authoring/references/pagination.md +14 -2
  31. package/skills/doc-authoring/references/tables-and-charts.md +21 -17
  32. package/src/app/components/browser/browser-ui.tsx +21 -0
  33. package/src/app/components/browser/new-document-dialog.tsx +208 -0
  34. package/src/app/components/callout.tsx +101 -0
  35. package/src/app/components/changes/changes-overlay.tsx +68 -0
  36. package/src/app/components/changes/changes-panel.tsx +341 -0
  37. package/src/app/components/changes/use-changes.ts +85 -0
  38. package/src/app/components/chart.tsx +191 -33
  39. package/src/app/components/code-block.tsx +249 -0
  40. package/src/app/components/comments/comments-overlay.tsx +50 -0
  41. package/src/app/components/comments/comments-panel.tsx +272 -0
  42. package/src/app/components/comments/use-comments.ts +61 -0
  43. package/src/app/components/data-table.tsx +146 -18
  44. package/src/app/components/doc-sidebar.tsx +32 -2
  45. package/src/app/components/flow-page.tsx +57 -8
  46. package/src/app/components/inspector/field-source.tsx +41 -0
  47. package/src/app/components/inspector/inspector.tsx +64 -65
  48. package/src/app/components/numbering.tsx +226 -12
  49. package/src/app/components/overlay-frame.tsx +79 -0
  50. package/src/app/components/page-frame.tsx +46 -0
  51. package/src/app/components/page-placement.ts +68 -0
  52. package/src/app/components/record-picker.tsx +79 -0
  53. package/src/app/components/themes/theme-preview.tsx +5 -4
  54. package/src/app/lib/agent-bridge.ts +29 -1
  55. package/src/app/lib/chart.test.ts +15 -0
  56. package/src/app/lib/chart.ts +134 -9
  57. package/src/app/lib/diagnostics.ts +45 -1
  58. package/src/app/lib/docx/ooxml.test.ts +24 -1
  59. package/src/app/lib/docx/ooxml.ts +27 -1
  60. package/src/app/lib/export-docx.ts +3 -1
  61. package/src/app/lib/export-dom.ts +17 -3
  62. package/src/app/lib/export-html.ts +4 -2
  63. package/src/app/lib/export-image.ts +2 -1
  64. package/src/app/lib/export-pdf.ts +9 -1
  65. package/src/app/lib/flow-measure.test.ts +30 -0
  66. package/src/app/lib/flow-measure.ts +68 -14
  67. package/src/app/lib/flow.test.ts +20 -1
  68. package/src/app/lib/flow.ts +120 -20
  69. package/src/app/lib/i18n-ja/browser.ts +10 -0
  70. package/src/app/lib/i18n-ja/doc.ts +4 -0
  71. package/src/app/lib/i18n-ja/panels.ts +40 -0
  72. package/src/app/lib/i18n-ko/browser.ts +10 -0
  73. package/src/app/lib/i18n-ko/doc.ts +4 -0
  74. package/src/app/lib/i18n-ko/panels.ts +39 -0
  75. package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
  76. package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
  77. package/src/app/lib/i18n-zh-cn/panels.ts +38 -0
  78. package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
  79. package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
  80. package/src/app/lib/i18n-zh-tw/panels.ts +38 -0
  81. package/src/app/lib/labels.ts +29 -10
  82. package/src/app/lib/records.test.ts +38 -0
  83. package/src/app/lib/records.ts +127 -0
  84. package/src/app/lib/sdk.ts +35 -0
  85. package/src/app/lib/use-doc-module.ts +7 -0
  86. package/src/app/lib/use-doc-pages.ts +38 -17
  87. package/src/app/routes/doc.tsx +275 -13
  88. package/src/app/routes/home.tsx +30 -5
  89. package/src/app/styles.css +23 -0
  90. package/templates/blank/index.tsx +63 -0
  91. package/templates/blank/template.json +6 -0
  92. package/templates/certificate/data/recipients.csv +4 -0
  93. package/templates/certificate/index.tsx +128 -0
  94. package/templates/certificate/template.json +6 -0
  95. package/templates/letter/index.tsx +106 -0
  96. package/templates/letter/template.json +5 -0
  97. package/templates/meeting-notes/index.tsx +194 -0
  98. package/templates/meeting-notes/template.json +6 -0
  99. package/templates/proposal/index.tsx +264 -0
  100. package/templates/proposal/template.json +6 -0
  101. package/templates/report/data/metrics.csv +5 -0
  102. package/templates/report/index.tsx +224 -0
  103. package/templates/report/template.json +6 -0
  104. package/dist/config-P61niZMf.d.ts +0 -24
  105. package/dist/sdk-CpDEGRIo.d.ts +0 -138
@@ -1,9 +1,9 @@
1
1
  import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
- import { C as assetImportPath, D as validateAssetName, E as resolveScopedAssetsDir, S as writeManifest, T as resolveScopedAssetFile, b as validateIcon, c as createDocument, f as listDocIds, g as resolveEntry, k as DOC_ID_RE, n as parseFrontmatter$1, s as OpsError, t as createViteConfig, v as newFolderId, w as countAssetUsages, x as validateName, y as readManifest } from "./config-B_pdNbYg.js";
2
+ import { t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
+ import { C as createDocument, D as listDocIds, S as OpsError, j as resolveEntry, t as createViteConfig, v as validateAssetName } from "./config-DKKNIbvO.js";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs/promises";
5
6
  import { existsSync } from "node:fs";
6
- import fg from "fast-glob";
7
7
  import { createServer, mergeConfig } from "vite";
8
8
  import { execFile } from "node:child_process";
9
9
  import { promisify } from "node:util";
@@ -91,7 +91,7 @@ async function createRenderSession(opts) {
91
91
  throw new Error(`Document "${docId}" never finished rendering.${detail}`);
92
92
  }
93
93
  const status = await page.evaluate("globalThis.__openDoc.status()");
94
- return {
94
+ const renderer = {
95
95
  status,
96
96
  diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
97
97
  async pdf() {
@@ -144,8 +144,15 @@ async function createRenderSession(opts) {
144
144
  },
145
145
  html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
146
146
  docx: () => page.evaluate("globalThis.__openDoc.docxBundle()"),
147
+ async setRecord(index, pattern) {
148
+ const { name } = await page.evaluate(`globalThis.__openDoc.setRecord(${JSON.stringify(index)}, ${pattern === void 0 ? "undefined" : JSON.stringify(pattern)})`);
149
+ await page.waitForFunction(`(() => { const s = globalThis.__openDoc.status(); return s.ready && s.record === ${JSON.stringify(index)}; })()`, void 0, { timeout });
150
+ renderer.status = await page.evaluate("globalThis.__openDoc.status()");
151
+ return name;
152
+ },
147
153
  close: () => page.close()
148
154
  };
155
+ return renderer;
149
156
  },
150
157
  async compareImages(before, after) {
151
158
  const page = await browser.newPage();
@@ -646,6 +653,35 @@ async function diffDocument(ctx, docId, opts = {}) {
646
653
  }
647
654
  }
648
655
  //#endregion
656
+ //#region src/import/lang.ts
657
+ const TRADITIONAL = "們這個說為國來會時對過還後點經學發應麼與實體關開種現當於從際";
658
+ const SIMPLIFIED = "们这个说为国来会时对过还后点经学发应么与实体关开种现当于从际";
659
+ const count = (text, re) => text.match(re)?.length ?? 0;
660
+ /**
661
+ * The language a Markdown file is written in, when it is one whose sheets
662
+ * need to say so — Chinese, Japanese, Korean — or `undefined` for anything
663
+ * else, which the document then leaves at its default.
664
+ */
665
+ function detectLang(text) {
666
+ const han = count(text, /\p{Script=Han}/gu);
667
+ const kana = count(text, /[\p{Script=Hiragana}\p{Script=Katakana}]/gu);
668
+ const hangul = count(text, /\p{Script=Hangul}/gu);
669
+ const latin = count(text, /\p{Script=Latin}/gu);
670
+ const cjk = han + kana + hangul;
671
+ if (cjk === 0 || cjk < latin * .25) return void 0;
672
+ if (hangul > han + kana) return "ko";
673
+ if (kana > 0 && kana >= han * .05) return "ja";
674
+ let traditional = 0;
675
+ let simplified = 0;
676
+ for (const char of text) {
677
+ const t = TRADITIONAL.indexOf(char);
678
+ const s = SIMPLIFIED.indexOf(char);
679
+ if (t !== -1 && SIMPLIFIED[t] !== char) traditional++;
680
+ if (s !== -1 && TRADITIONAL[s] !== char) simplified++;
681
+ }
682
+ return simplified > traditional ? "zh-Hans" : "zh-Hant";
683
+ }
684
+ //#endregion
649
685
  //#region src/import/markdown.ts
650
686
  const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
651
687
  const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
@@ -1280,6 +1316,7 @@ function generateDocumentSource(parsed, opts) {
1280
1316
  const theme = opts.theme ?? parsed.frontmatter.theme;
1281
1317
  const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1282
1318
  const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1319
+ const lang = opts.lang ?? parsed.frontmatter.lang;
1283
1320
  const cover = opts.cover !== false;
1284
1321
  let blocks = parsed.blocks;
1285
1322
  const first = blocks[0];
@@ -1331,6 +1368,7 @@ ${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
1331
1368
  ...pageSize ? [` pageSize: ${jsString(pageSize)},`] : [],
1332
1369
  ...orientation ? [` orientation: ${jsString(orientation)},`] : [],
1333
1370
  ...theme ? [` theme: ${jsString(theme)},`] : [],
1371
+ ...lang ? [` lang: ${jsString(lang)},`] : [],
1334
1372
  ` createdAt: ${jsString(opts.createdAt)},`
1335
1373
  ];
1336
1374
  const entries = [
@@ -1396,6 +1434,7 @@ async function importMarkdown(ctx, opts) {
1396
1434
  }
1397
1435
  if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
1398
1436
  const parsed = parseMarkdown(markdown);
1437
+ const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
1399
1438
  const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1400
1439
  if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
1401
1440
  const orientation = opts.orientation ?? parsed.frontmatter.orientation;
@@ -1441,6 +1480,7 @@ async function importMarkdown(ctx, opts) {
1441
1480
  ...opts.theme !== void 0 ? { theme: opts.theme } : {},
1442
1481
  ...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
1443
1482
  ...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
1483
+ ...language ? { lang: language } : {},
1444
1484
  ...opts.cover !== void 0 ? { cover: opts.cover } : {},
1445
1485
  ...opts.contents !== void 0 ? { contents: opts.contents } : {},
1446
1486
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -1569,183 +1609,65 @@ function resolveOutDir(ctx, outDir) {
1569
1609
  if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
1570
1610
  return resolved;
1571
1611
  }
1612
+ /**
1613
+ * Writes the document's files. With `each`, a document that exports
1614
+ * `records` is laid out and written once per row — `name` (or
1615
+ * `meta.recordName`) names each row's files.
1616
+ */
1572
1617
  async function exportDocument(ctx, docId, opts = {}) {
1573
1618
  const format = opts.format ?? "pdf";
1574
1619
  const dir = resolveOutDir(ctx, opts.outDir ?? "out");
1575
1620
  return withDoc(ctx, docId, async (renderer) => {
1576
1621
  await fs.mkdir(dir, { recursive: true });
1577
1622
  const written = [];
1623
+ const taken = /* @__PURE__ */ new Set();
1578
1624
  const write = async (name, bytes) => {
1579
1625
  const file = path.join(dir, name);
1580
1626
  await fs.writeFile(file, bytes);
1581
1627
  written.push(path.relative(ctx.userCwd, file));
1582
1628
  };
1583
- if (format === "pdf") await write(`${docId}.pdf`, await renderer.pdf());
1584
- else if (format === "html" || format === "docx") {
1585
- const bundle = format === "html" ? await renderer.html() : await renderer.docx();
1586
- if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
1587
- await write(bundle.filename, Buffer.from(bundle.base64, "base64"));
1588
- } else {
1589
- const width = String(renderer.status.pageCount).length;
1590
- for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${docId}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1629
+ const free = (base) => {
1630
+ let name = base;
1631
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
1632
+ taken.add(name);
1633
+ return name;
1634
+ };
1635
+ const writeCopy = async (base) => {
1636
+ if (format === "pdf") await write(`${base}.pdf`, await renderer.pdf());
1637
+ else if (format === "html" || format === "docx") {
1638
+ const bundle = format === "html" ? await renderer.html() : await renderer.docx();
1639
+ if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
1640
+ await write(`${base}${path.extname(bundle.filename)}`, Buffer.from(bundle.base64, "base64"));
1641
+ } else {
1642
+ const width = String(renderer.status.pageCount).length;
1643
+ for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${base}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
1644
+ }
1645
+ };
1646
+ if (!opts.each) {
1647
+ await writeCopy(docId);
1648
+ return {
1649
+ docId,
1650
+ format,
1651
+ pageCount: renderer.status.pageCount,
1652
+ files: written
1653
+ };
1654
+ }
1655
+ const records = renderer.status.records;
1656
+ if (records === 0) throw new OpsError(422, `${docId} has no records — export \`records\` (rows from a .csv) to write one copy per row`);
1657
+ let pageCount = 0;
1658
+ for (let index = 0; index < records; index++) {
1659
+ const name = await renderer.setRecord(index, opts.name);
1660
+ pageCount += renderer.status.pageCount;
1661
+ await writeCopy(free(name));
1591
1662
  }
1592
1663
  return {
1593
1664
  docId,
1594
1665
  format,
1595
- pageCount: renderer.status.pageCount,
1596
- files: written
1666
+ pageCount,
1667
+ files: written,
1668
+ records
1597
1669
  };
1598
1670
  });
1599
1671
  }
1600
1672
  //#endregion
1601
- //#region src/ops/library.ts
1602
- function themesRoot(ctx, themesDir = "themes") {
1603
- return path.resolve(ctx.userCwd, themesDir);
1604
- }
1605
- async function themeFiles(root) {
1606
- if (!existsSync(root)) return [];
1607
- return (await fg("*.md", {
1608
- cwd: root,
1609
- absolute: true,
1610
- onlyFiles: true
1611
- })).sort();
1612
- }
1613
- function demoFor(root, id) {
1614
- for (const cand of [
1615
- `${id}.demo.tsx`,
1616
- `${id}.demo.jsx`,
1617
- `${id}.demo.ts`,
1618
- `${id}.demo.js`
1619
- ]) {
1620
- const p = path.join(root, cand);
1621
- if (existsSync(p)) return p;
1622
- }
1623
- return null;
1624
- }
1625
- async function listThemes(ctx, themesDir) {
1626
- const root = themesRoot(ctx, themesDir);
1627
- const out = [];
1628
- for (const file of await themeFiles(root)) {
1629
- const id = path.basename(file, ".md");
1630
- const { fm } = parseFrontmatter$1(await fs.readFile(file, "utf8"), id);
1631
- out.push({
1632
- id,
1633
- name: fm.name,
1634
- description: fm.description,
1635
- pageSize: fm.pageSize,
1636
- mode: fm.mode,
1637
- hasDemo: demoFor(root, id) !== null
1638
- });
1639
- }
1640
- return out;
1641
- }
1642
- /**
1643
- * The full theme document. This is what an agent reads before writing a doc —
1644
- * the palette, type scale, and paste-ready components live in the body.
1645
- */
1646
- async function readTheme(ctx, themeId, themesDir) {
1647
- const root = themesRoot(ctx, themesDir);
1648
- const file = path.join(root, `${themeId}.md`);
1649
- if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
1650
- const { fm, body } = parseFrontmatter$1(await fs.readFile(file, "utf8"), themeId);
1651
- const demoAbs = demoFor(root, themeId);
1652
- return {
1653
- id: themeId,
1654
- frontmatter: fm,
1655
- body,
1656
- demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
1657
- };
1658
- }
1659
- /** `scope` is a document id, or `global` for the shared assets directory. */
1660
- async function listAssets(ctx, scope) {
1661
- const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1662
- if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1663
- if (!existsSync(dir)) return [];
1664
- const names = await fs.readdir(dir);
1665
- const out = [];
1666
- for (const filename of names.sort()) {
1667
- const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
1668
- if (!stat?.isFile()) continue;
1669
- out.push({
1670
- scope,
1671
- filename,
1672
- bytes: stat.size,
1673
- importPath: assetImportPath(scope, filename)
1674
- });
1675
- }
1676
- return out;
1677
- }
1678
- async function writeAsset(ctx, scope, filename, data) {
1679
- const name = validateAssetName(filename);
1680
- if (!name) throw new OpsError(400, "invalid filename");
1681
- const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
1682
- if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
1683
- await fs.mkdir(dir, { recursive: true });
1684
- const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
1685
- if (!file) throw new OpsError(400, "invalid filename");
1686
- await fs.writeFile(file, data);
1687
- return {
1688
- scope,
1689
- filename: name,
1690
- bytes: data.byteLength,
1691
- importPath: assetImportPath(scope, name)
1692
- };
1693
- }
1694
- async function deleteAsset(ctx, scope, filename) {
1695
- const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
1696
- if (!file) throw new OpsError(400, "invalid filename");
1697
- if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
1698
- await fs.rm(file);
1699
- }
1700
- /** Which documents import this asset — check before deleting one. */
1701
- async function findAssetUsages(ctx, scope, filename) {
1702
- const importPath = assetImportPath(scope, filename);
1703
- const out = [];
1704
- for (const id of await listDocIds(ctx)) {
1705
- const entry = resolveEntry(ctx, id);
1706
- if (!entry) continue;
1707
- const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
1708
- if (count > 0) out.push({
1709
- docId: id,
1710
- count
1711
- });
1712
- }
1713
- return out;
1714
- }
1715
- async function listFolders(ctx) {
1716
- const manifest = await readManifest(ctx.manifestPath);
1717
- return {
1718
- folders: manifest.folders,
1719
- assignments: manifest.assignments
1720
- };
1721
- }
1722
- /** Folders always carry an icon; agents rarely care, so this is the fallback. */
1723
- const DEFAULT_FOLDER_ICON = {
1724
- type: "color",
1725
- value: "#6b7280"
1726
- };
1727
- async function createFolder(ctx, rawName, rawIcon) {
1728
- const name = validateName(rawName);
1729
- if (!name) throw new OpsError(400, "invalid folder name");
1730
- const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
1731
- if (!icon) throw new OpsError(400, "invalid icon");
1732
- const manifest = await readManifest(ctx.manifestPath);
1733
- const folder = {
1734
- id: newFolderId(),
1735
- name,
1736
- icon
1737
- };
1738
- manifest.folders.push(folder);
1739
- await writeManifest(ctx.manifestPath, manifest);
1740
- return folder;
1741
- }
1742
- /** Filing only edits assignments — a document id never moves on disk. */
1743
- async function fileDocument(ctx, docId, folderId) {
1744
- const manifest = await readManifest(ctx.manifestPath);
1745
- if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
1746
- if (folderId === null) delete manifest.assignments[docId];
1747
- else manifest.assignments[docId] = folderId;
1748
- await writeManifest(ctx.manifestPath, manifest);
1749
- }
1750
- //#endregion
1751
- export { listAssets as a, readTheme as c, closeRenderSession as d, exportDocument as f, diffDocument as g, slugify as h, findAssetUsages as i, writeAsset as l, importMarkdown as m, deleteAsset as n, listFolders as o, renderDocPage as p, fileDocument as r, listThemes as s, createFolder as t, checkLayout as u };
1673
+ export { importMarkdown as a, renderDocPage as i, closeRenderSession as n, slugify as o, exportDocument as r, diffDocument as s, checkLayout as t };
@@ -0,0 +1,36 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { readFile } from "node:fs/promises";
4
+ //#region src/cli/package-version.ts
5
+ const PACKAGE_NAME = "@open-document/core";
6
+ /**
7
+ * Walks up for this package's own `package.json` instead of assuming a fixed
8
+ * depth: the bundler decides which chunk a module lands in, so `../../` is
9
+ * right from `dist/cli/` and wrong from `dist/`. Getting that wrong is silent —
10
+ * it reports `0.0.0`, or finds no templates, rather than failing.
11
+ */
12
+ async function findCorePackage() {
13
+ let dir = path.dirname(fileURLToPath(import.meta.url));
14
+ for (let up = 0; up < 6; up += 1) {
15
+ try {
16
+ const pkg = JSON.parse(await readFile(path.join(dir, "package.json"), "utf8"));
17
+ if (pkg.name === PACKAGE_NAME && pkg.version !== void 0) return {
18
+ root: dir,
19
+ version: pkg.version
20
+ };
21
+ } catch {}
22
+ const parent = path.dirname(dir);
23
+ if (parent === dir) break;
24
+ dir = parent;
25
+ }
26
+ return null;
27
+ }
28
+ async function readCoreVersion() {
29
+ return (await findCorePackage())?.version ?? "0.0.0";
30
+ }
31
+ /** The installed package's root — where `skills/` and `templates/` ship. */
32
+ async function corePackageRoot() {
33
+ return (await findCorePackage())?.root ?? null;
34
+ }
35
+ //#endregion
36
+ export { readCoreVersion as n, corePackageRoot as t };
@@ -1,4 +1,4 @@
1
- import { t as createViteConfig } from "./config-B_pdNbYg.js";
1
+ import { t as createViteConfig } from "./config-DKKNIbvO.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -0,0 +1,34 @@
1
+ import { o as createFromTemplate, s as listTemplates } from "./config-DKKNIbvO.js";
2
+ import "./ops-DmEecq1k.js";
3
+ import { t as cliContext } from "./context-DXNP8v9I.js";
4
+ import chalk from "chalk";
5
+ //#region src/cli/templates.ts
6
+ /**
7
+ * Every template a document can start from, with the name `new --template`
8
+ * takes in the first column — the list is the documentation of the names.
9
+ */
10
+ async function printTemplates(opts = {}) {
11
+ const ctx = await cliContext();
12
+ const templates = await listTemplates(ctx);
13
+ if (opts.json) {
14
+ process.stdout.write(`${JSON.stringify(templates, null, 2)}\n`);
15
+ return;
16
+ }
17
+ const width = Math.max(...templates.map((t) => t.name.length), 4);
18
+ for (const template of templates) {
19
+ const where = template.source === "workspace" ? chalk.cyan(" (this workspace)") : "";
20
+ process.stdout.write(` ${chalk.bold(template.name.padEnd(width))} ${template.title}${where}\n` + (template.description ? ` ${" ".repeat(width)} ${chalk.dim(template.description)}\n` : ""));
21
+ }
22
+ process.stdout.write(chalk.dim(`\nopen-doc new <id> --template <name> · your own: templates/<name>/index.tsx\n`));
23
+ }
24
+ async function newDoc(docId, opts = {}) {
25
+ const ctx = await cliContext();
26
+ const result = await createFromTemplate(ctx, {
27
+ template: opts.template ?? "blank",
28
+ ...docId ? { docId } : {},
29
+ ...opts.title !== void 0 ? { title: opts.title } : {}
30
+ });
31
+ process.stdout.write(`${chalk.green("✓")} ${chalk.bold(result.id)} → ${result.entry} ${chalk.dim(`(from ${opts.template ?? "blank"})`)}\n`);
32
+ }
33
+ //#endregion
34
+ export { newDoc, printTemplates };
@@ -1,4 +1,4 @@
1
- import { n as OpenDocConfig } from "../config-P61niZMf.js";
1
+ import { n as OpenDocConfig } from "../config-BWtOZ1jc.js";
2
2
  import { InlineConfig, Plugin } from "vite";
3
3
  //#region src/vite/open-doc-plugin.d.ts
4
4
  type OpenDocPluginOptions = {
@@ -1,2 +1,3 @@
1
- import { j as openDocPlugin, t as createViteConfig } from "../config-B_pdNbYg.js";
1
+ import { r as openDocPlugin } from "../open-doc-plugin-DnX5usgI.js";
2
+ import { t as createViteConfig } from "../config-DKKNIbvO.js";
2
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -29,6 +29,7 @@
29
29
  "env.d.ts",
30
30
  "src/app",
31
31
  "skills",
32
+ "templates",
32
33
  "README.md",
33
34
  "README.zh-TW.md"
34
35
  ],
@@ -5,7 +5,7 @@ description: Use this skill when the user asks to apply, process, or clear the c
5
5
 
6
6
  # Apply inspector comments
7
7
 
8
- The dev UI's **Inspect** mode lets the user click any element on a page and leave a note. Each note is written into the document source as a marker:
8
+ In the viewer the user leaves notes from the **Comments** panel (`M`) or the element panel in edit mode, and the panel's **Copy request for the agent** button hands you `/apply-comments docs/<id>` — when a path is given, work on that document only. Each note is written into the document source as a marker:
9
9
 
10
10
  ```tsx
11
11
  <p style={p}>
@@ -18,6 +18,8 @@ The marker is always the **first child of the element the note is about** — th
18
18
 
19
19
  ## Step 1 — Find the pending comments
20
20
 
21
+ If the request named a document (`docs/<id>`), look only there.
22
+
21
23
  ```bash
22
24
  grep -rn "@doc-comment" docs/
23
25
  ```
@@ -11,6 +11,8 @@ You only write files under `docs/<id>/`. Never modify `package.json`, `open-doc.
11
11
 
12
12
  **If the user already has the content written as Markdown, don't retype it into JSX.** `open-doc import <file.md> --id <id>` produces a real document — `flow()` body, cover, contents, local images copied into the document's assets — which you then refine. Steps 0–2 still apply for the parts the import cannot know (theme, page size, visual direction).
13
13
 
14
+ **If a template fits the kind of document, start from it.** `open-doc templates` lists them — built-in (`report`, `proposal`, `meeting-notes`, `letter`, `certificate`, `blank`) and the workspace's own under `templates/<name>/` — with the name to pass on. `open-doc new <id> --template <name> --title "<title>"` copies one into `docs/<id>/`, retitled and dated today, and you then replace its stand-in content with the real substance (Steps 1–2 still apply). Over MCP, the same is `list_templates` and `create_from_template`.
15
+
14
16
  ## Step 0 — Pick a theme
15
17
 
16
18
  List files under `themes/`. If any theme markdown exists (anything other than `README.md`), call `AskUserQuestion` with each theme id as an option plus a final **"no theme — design from scratch"** option. (`AskUserQuestion` holds at most 4 options — with 4+ themes, offer the 3 most relevant plus "no theme"; the auto-added "Other" lets the user name an omitted one.)
@@ -17,11 +17,11 @@ Read the matching reference **before** using a primitive:
17
17
  | Primitive | Read before | File |
18
18
  | --- | --- | --- |
19
19
  | `design` const + `var(--od-*)` tokens | writing any new document | `references/design-system.md` |
20
- | `flow()` auto-pagination | any body content (the default) | `references/pagination.md` |
20
+ | `flow()` auto-pagination & multi-column | any body content (the default) | `references/pagination.md` |
21
21
  | Vertical budget (fixed pages) | laying out a cover or divider by hand | `references/pagination.md` |
22
- | Tables, stat rows, inline charts | rendering data of any kind | `references/tables-and-charts.md` |
22
+ | Tables, stat rows, `<Chart>`, `<Sparkline>`, `<Callout>` | rendering data or callouts | `references/tables-and-charts.md` |
23
23
  | Assets + `<ImagePlaceholder>` | importing images or leaving a placeholder | `references/assets.md` |
24
- | Footnotes, `<Figure>`, `<Ref>`, `<DataTable>` | any note, numbered figure, cross-reference, or `.csv` | `references/long-form.md` |
24
+ | Footnotes, `<Figure>`, `<Ref>`, `<DataTable>`, `<Cite>`, `<Bibliography>`, `<CodeBlock>` | notes, figures, cross-references, citations, code blocks, or `.csv` | `references/long-form.md` |
25
25
 
26
26
  ## Themes
27
27
 
@@ -60,6 +60,9 @@ export default [Cover, Body] satisfies DocPage[];
60
60
  - `export default` is a **non-empty array of entries**. An entry is either a zero-prop React component (one fixed page) or a `flow(<>…</>)` section the framework paginates by measuring. Mix them freely — the usual shape is a fixed cover, a fixed contents page, then one flow section for the body.
61
61
  - **Default to `flow()` for body content.** Hand-splitting prose into fixed pages produces documents where every heading starts a half-empty page. Read `references/pagination.md` before writing either kind.
62
62
  - `meta.pageSize` is `'A4' | 'B4' | 'A3'` (default `'A4'`) and `meta.orientation` is `'portrait' | 'landscape'` (default portrait). **These six combinations are the only sheets there are** — there is no Letter, no A5, no custom size, and no way to set a page's dimensions by hand. The same value drives the on-screen page, the `@page` size when printing, and the HTML export.
63
+ - `meta.lang` is the document's language as a BCP 47 tag — **set it for anything not in English**: `'zh-Hant-TW'`, `'zh-Hans'`, `'ja'`, `'ko'`. Every sheet carries it, so it decides the glyph shapes of shared Han characters, the line-breaking rules (no `,。」` at the start of a line), and the language exported HTML and Word declare. The sheet already sets CJK text properly — strict kinsoku, and an eighth-em gap where a CJK character meets a Latin letter or digit with no space typed — so don't hand-insert spaces for that; a block that must not get the gap takes `textAutospace: 'no-autospace'`.
64
+ - **One document per row of data** (certificates, letters, quotes): `export const records = rows` (an imported `.csv`) makes the document print once per row. Pages read the current row with `useRecord()` or print one value with `<Field name="company" />`; `meta.recordName: 'certificate-{name}'` names each row's file (`{#}` is the row number) and `meta.recordLabel` names rows in the viewer's picker. `open-doc export <id> --each` writes one file per row. A flow section's blocks are fixed when the module loads, so content that varies by row goes **inside** blocks — a block can render nothing for a row — never as a different number of blocks.
65
+ - `meta.watermark` (optional string, e.g. `'CONFIDENTIAL'` or `'DRAFT'`) renders a subtle diagonal watermark across every sheet in the viewer and exports.
63
66
  - `meta.createdAt` is an **ISO 8601 string literal** set once when the doc is scaffolded — the home page sorts on it. **Immediately before writing the file, run `node -e "console.log(new Date().toISOString())"` and paste the exact output.** It must stay a plain string literal (no `new Date(...)`): the framework reads it with a regex at build time, it never evaluates the module.
64
67
 
65
68
  ## Two ways to fill pages
@@ -152,11 +155,12 @@ contents list does. Read `references/long-form.md` before using any of them.
152
155
  content in one unbreakable block. `<ListOfFigures />` / `<ListOfTables />`
153
156
  build the lists.
154
157
  - **`<Ref to="id" />`** — "Figure 3", plus the page when the target is elsewhere.
155
- - **`<DataTable rows={…}>`** — a print-shaped table from an imported `.csv`.
156
- - **`<Diagram chart={…} caption>`** — an architecture or flow drawing from an
157
- imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
158
- - **`<Chart data x y caption>`** — a bar, line or pie chart from rows, in the
159
- document's colours; numbers as a figure. See `references/tables-and-charts.md`.
158
+ - **`<Cite id="…" source="…" />` & `<Bibliography />`** — academic/report citations numbered in order of first appearance (`[1]`), deduplicated by `id`, and listed by `<Bibliography />`.
159
+ - **`<DataTable rows={…} splittable summaryRow>`** — a print-shaped table from an imported `.csv` (supports automatic multi-page splitting with repeated headers when `splittable` is set, plus `summaryRow`, `dataBar`, `'currency'`, and `'delta'` formats).
160
+ - **`<CodeBlock code={…} lang="ts" lineNumbers highlightLines={[…]} caption="…" />`** — zero-dependency syntax-highlighted code block with optional line numbers, highlighted lines, and figure numbering when given `caption`.
161
+ - **`<Callout type="note|tip|warning|danger" title="…">`** — semantic callout box styled with `--od-*` tokens.
162
+ - **`<Diagram chart={…} caption>`** — an architecture, flow, or sequence drawing from an imported `.mmd`. Given a caption it numbers as a figure, like `<Figure>`.
163
+ - **`<Chart data x y caption>` & `<Sparkline data={…} />`** — `bar`, `horizontal-bar`, `line`, `area`, or `pie` charts from rows, plus inline SVG `<Sparkline>` for tables and stat cards. See `references/tables-and-charts.md`.
160
164
 
161
165
  `meta.labels` sets what they are called (`圖`, `表`) — the numbering itself is
162
166
  structural.
@@ -186,13 +190,10 @@ It is compiled to SVG at build time and drawn with the document's own theme
186
190
  variables, so it prints with the same ink and faces as the prose around it.
187
191
  Never reach for an image of a diagram when the diagram can be written.
188
192
 
189
- Supported: `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`,
190
- `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`,
191
- `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `%%`
192
- comments. A link back to an earlier step is drawn round the side, clear of the
193
- steps in between. Anything else
194
- in Mermaid's syntax — subgraphs, class diagrams, sequence diagrams — is not
195
- supported, and a bad diagram fails the build with the line to fix.
193
+ Supported:
194
+ - `flowchart`/`graph` with `TD` or `LR`; nodes as `A[box]`, `A(round)`, `A([stadium])`, `A[(database)]`, `A{decision}`, `A((circle))`; links `-->`, `---`, `-.->`, `==>` with optional `|labels|`; chains `A --> B --> C`; `subgraph id [Title] ... end` clusters; `%%` comments. A link back to an earlier step is drawn round the side, clear of the steps in between.
195
+ - `sequenceDiagram` with `participant Id as Label`, message arrows (`->>`, `-->>`, `->`, `-->`), and `Note over A,B: text` (or `Note left of` / `Note right of`).
196
+ - Anything else in Mermaid's syntax is not supported, and a bad diagram fails the build with the line to fix.
196
197
 
197
198
  Keep `width` inside the text block: a drawing wider than the column is a layout
198
199
  fault, and `open-doc check` reports it as one.
@@ -414,7 +415,7 @@ confirms it.
414
415
  - [ ] `docs/<id>/index.tsx` `export default`s a non-empty `DocEntry[]`, with body content in a `flow()` section rather than hand-split pages.
415
416
  - [ ] Every page's root fills `100% × 100%` and sets `boxSizing: 'border-box'` with the margin as padding.
416
417
  - [ ] **For every fixed page, sum (font_size × line_height × lines) + gaps + 2×margin ≤ page height.** If close, split — or move the content into the flow section. No `overflow: auto` escape hatches.
417
- - [ ] No block inside a `flow()` section is taller than one page (a long table has to be split by hand — the framework never splits a block).
418
+ - [ ] No unbreakable block inside a `flow()` section is taller than one page (pass `splittable` on long `<DataTable>` instances so the framework splits rows across pages with repeated headers).
418
419
  - [ ] Body type ≥ 13px; nothing on the page under 9px.
419
420
  - [ ] Section titles are real `h1`/`h2`/`h3` elements, so the outline and TOC pick them up.
420
421
  - [ ] Contents page uses `<TableOfContents />`, not a hand-written list.
@@ -120,8 +120,10 @@ import services from './data/services.csv';
120
120
  arrives after the layout is decided.
121
121
  - Columns default to the keys of the first row. A column whose values are all
122
122
  numbers aligns right and gets `tabular-nums` without being told.
123
- - `format`: `'integer'`, `'number'`, `'percent'`, `'text'`, or your own
124
- `(value, row) => ReactNode`.
123
+ - `format`: `'integer'`, `'number'`, `'percent'`, `'currency'` (uses `column.currency ?? 'USD'`), `'delta'` (`+` prefix for positives, `−` for negatives), `'text'`, or your own `(value, row) => ReactNode`.
124
+ - `dataBar`: `true` or `{ color?: string; max?: number }` on a numeric column draws an inline proportional bar behind the cell's number.
125
+ - `summaryRow`: `'sum' | 'avg'` (aggregates all numeric columns automatically) or a custom record `{ service: 'Total', requests: 'sum', error_rate: 'avg' }` rendered in `<tfoot>`.
126
+ - `splittable`: when `true` inside a `flow()` section, automatically splits long tables across pages, repeating `<thead>` and appending `meta.labels?.continued ?? ' (continued)'` to the caption on continuation sheets.
125
127
  - `caption` numbers the table and prints the caption above it; without one you
126
128
  get a plain table.
127
129
  - `limit` prints the first N rows and says how many were left out — never
@@ -129,3 +131,42 @@ import services from './data/services.csv';
129
131
 
130
132
  **Retyping numbers into JSX is the thing this replaces.** If the user has the
131
133
  data in a file, import the file.
134
+
135
+ ## Citations and bibliography (`<Cite>` & `<Bibliography>`)
136
+
137
+ ```tsx
138
+ import { Bibliography, Cite } from '@open-document/core';
139
+
140
+ <p style={p}>
141
+ Tail latency dominates fan-out services <Cite id="dean2013" label="p. 75" source="J. Dean and L. A. Barroso, 'The Tail at Scale,' Communications of the ACM, vol. 56, no. 2, pp. 74–80, 2013." />.
142
+ </p>
143
+
144
+ <Bibliography title="References" />
145
+ ```
146
+
147
+ - `<Cite id="…" />` numbers citations `[1]`, `[2]` in order of first appearance across the entire document. Citing the same `id` again reuses the same number; pass `source` on at least the first occurrence, and optional `label` (e.g. `"p. 42"`) to render `[1, p. 42]`.
148
+ - `<Bibliography />` prints the numbered reference list in order of appearance. An entry cited without any `source` renders `[?id]` so missing bibliography text is immediately visible.
149
+
150
+ ## Syntax-highlighted code (`<CodeBlock>`)
151
+
152
+ ```tsx
153
+ import { CodeBlock } from '@open-document/core';
154
+
155
+ <CodeBlock
156
+ id="retry-policy"
157
+ caption="Exponential backoff retry policy"
158
+ lang="ts"
159
+ lineNumbers
160
+ highlightLines={[3, 4]}
161
+ code={`export async function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
162
+ for (let i = 0; i < retries; i++) {
163
+ try { return await fn(); }
164
+ catch (err) { if (i === retries - 1) throw err; }
165
+ }
166
+ throw new Error('Unreachable');
167
+ }`}
168
+ />
169
+ ```
170
+
171
+ - Highlights keywords, strings, comments, numbers, and types at render time with zero external dependencies using `--od-*` variables.
172
+ - Passing `caption` numbers the code block as a figure (retrievable via `<Ref to="retry-policy" />`).
@@ -41,13 +41,25 @@ export default [Cover, Contents, Body] satisfies DocEntry[];
41
41
  | Heading never last on a page | `data-od-keep-with-next` | **on** for `h1`–`h4` |
42
42
  | Caption stays with its figure | `data-od-keep-with-previous` on the caption | off |
43
43
  | Force a new page here | `data-od-break-before` | off |
44
+ | Span all columns in multi-column flow | `data-od-column-span="all"` | **on** for `h1` |
44
45
 
45
46
  Set `data-od-keep-with-next="false"` on a heading if you deliberately want it to end a page.
46
47
 
48
+ ### Multi-column flow (`columns` & `columnGap`)
49
+
50
+ Pass `columns: 2` (or `3`) and optional `columnGap` (default `24`) to `flow(children, { columns: 2, columnGap: 24, footer: Footer })` to pack blocks into balanced newspaper/academic columns on each page:
51
+
52
+ - Blocks flow down column 1 first, then column 2, then open a new page.
53
+ - `<h1>` elements (and any block carrying `data-od-column-span="all"`) span the full text-block width across all columns and flush the columns above them.
54
+ - Footnotes lifted from any column on a page share the single page-wide footnote area at the bottom of the sheet.
55
+
56
+ ### Splittable tables (`<DataTable splittable />`)
57
+
58
+ By default, blocks in `flow()` are atomic. However, `<DataTable splittable rows={…} />` is measured row-by-row and automatically sliced across as many flow pages as needed, repeating `<thead>` on every continuation page and appending the continuation suffix (`meta.labels?.continued ?? ' (continued)'`) to the caption.
59
+
47
60
  ### What flow does not do
48
61
 
49
- - **It never splits a block.** A 40-row table taller than one page stays whole and overflows — split it yourself into two tables with a repeated header.
50
- - **It does not balance pages.** Content fills top-down; the last page can be short.
62
+ - **It never splits an arbitrary block** unless it is a `<DataTable splittable />` (or bears `data-od-splittable="table"`).
51
63
  - **It does not reorder anything.** Blocks keep the order you wrote them in.
52
64
 
53
65
  ## Fixed pages and the vertical budget