@open-document/core 0.17.1 → 0.17.3

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 (37) hide show
  1. package/dist/{build-C7nHUUXO.js → build-CryLx-8O.js} +1 -1
  2. package/dist/{check--Cbkdqw3.js → check-BU86QFnH.js} +3 -3
  3. package/dist/cli/bin.js +11 -11
  4. package/dist/{context-DRXgt6Je.js → context-DHCqEAue.js} +1 -1
  5. package/dist/{dev-D_j2ykSa.js → dev-Dmi2PnqI.js} +1 -1
  6. package/dist/{diff-C1RDK_I5.js → diff-HVSJapV4.js} +2 -2
  7. package/dist/{export-BFxKPa0W.js → export-CDobz0UO.js} +3 -3
  8. package/dist/{import-TLuMXkou.js → import-BUHNpf-a.js} +3 -3
  9. package/dist/ops/index.js +2 -2
  10. package/dist/{ops-BG9hfBwQ.js → ops-DKEhE_su.js} +1 -1
  11. package/dist/{preview-rlMPuRZV.js → preview-Do-31RB6.js} +1 -1
  12. package/dist/{proofread-Dtj9OlWX.js → proofread-C0crhm3C.js} +3 -3
  13. package/dist/{session-CPFLe6BT.js → session-CcIBEiIB.js} +168 -110
  14. package/dist/{templates-BmSuBmj3.js → templates-hcl2pb6n.js} +3 -3
  15. package/dist/{translations-BmTXOhx9.js → translations-x2NwYrcj.js} +2 -2
  16. package/dist/vite/index.js +1 -1
  17. package/package.json +1 -1
  18. package/skills/doc-authoring/SKILL.md +10 -12
  19. package/src/app/components/agent/transcript.tsx +2 -4
  20. package/src/app/components/comments/comments-panel.tsx +9 -5
  21. package/src/app/components/doc-assets.tsx +9 -5
  22. package/src/app/lib/ask.ts +113 -0
  23. package/src/app/lib/clipboard.ts +26 -0
  24. package/src/app/lib/export-pdf.ts +18 -0
  25. package/src/app/lib/host.ts +4 -1
  26. package/src/app/lib/i18n-ja/browser.ts +1 -0
  27. package/src/app/lib/i18n-ja/doc.ts +11 -0
  28. package/src/app/lib/i18n-ko/browser.ts +1 -0
  29. package/src/app/lib/i18n-ko/doc.ts +9 -0
  30. package/src/app/lib/i18n-zh-cn/browser.ts +1 -0
  31. package/src/app/lib/i18n-zh-cn/doc.ts +9 -0
  32. package/src/app/lib/i18n-zh-tw/browser.ts +1 -0
  33. package/src/app/lib/i18n-zh-tw/doc.ts +9 -0
  34. package/src/app/lib/toast.ts +16 -2
  35. package/src/app/routes/assets.tsx +19 -12
  36. package/src/app/routes/doc.tsx +78 -20
  37. package/src/app/routes/home.tsx +16 -12
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-CPFLe6BT.js";
1
+ import { r as createViteConfig } from "./session-CcIBEiIB.js";
2
2
  import path from "node:path";
3
3
  import { build as build$1, mergeConfig } from "vite";
4
4
  //#region src/cli/build.ts
@@ -1,6 +1,6 @@
1
- import { B as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-CPFLe6BT.js";
2
- import "./ops-BG9hfBwQ.js";
3
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { B as listDocIds, S as closeRenderSession, x as checkLayout } from "./session-CcIBEiIB.js";
2
+ import "./ops-DKEhE_su.js";
3
+ import { t as cliContext } from "./context-DHCqEAue.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/check.ts
6
6
  function line(finding) {
package/dist/cli/bin.js CHANGED
@@ -148,47 +148,47 @@ async function run(argv) {
148
148
  program.name("open-doc").description("Author documents — we handle the Vite/React stack, pagination, and export.").version(version, "-v, --version", "print version").helpOption("-h, --help", "show help").showHelpAfterError(chalk.dim("(run `open-doc --help` for usage)"));
149
149
  program.command("dev").description("Start the dev server").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").option("--no-skills-check", "skip the built-in skills drift check").option("--mcp", "serve an MCP endpoint at /mcp (requires @open-document/mcp)").action(async (flags) => {
150
150
  if (flags.skillsCheck !== false) await runSkillsDriftCheck(resolveBuiltinSkillsDir());
151
- const { dev } = await import("../dev-D_j2ykSa.js");
151
+ const { dev } = await import("../dev-Dmi2PnqI.js");
152
152
  await dev(flags);
153
153
  });
154
154
  program.command("build").description("Build a static site").option("--out-dir <dir>", "output directory (defaults to `dist`)").action(async (flags) => {
155
- const { build } = await import("../build-C7nHUUXO.js");
155
+ const { build } = await import("../build-CryLx-8O.js");
156
156
  await build(flags);
157
157
  });
158
158
  program.command("preview").description("Preview the production build").addOption(new Option("-p, --port <port>", "port to listen on").argParser(parsePort)).addOption(new Option("--host [host]", "expose on the network (optional host)")).option("--open", "open the browser on start").action(async (flags) => {
159
- const { preview } = await import("../preview-rlMPuRZV.js");
159
+ const { preview } = await import("../preview-Do-31RB6.js");
160
160
  await preview(flags);
161
161
  });
162
162
  program.command("export [docIds...]").description("Render documents headlessly to PDF, HTML, PNG, or DOCX").addOption(new Option("-f, --format <format>", "output format").choices([...EXPORT_FORMATS])).option("-o, --out-dir <dir>", "directory to write into (defaults to `out`)").option("--all", "export every document under docs/").option("--each", "one copy per row of the document's `records`").option("--name <pattern>", "with --each: file name, e.g. \"certificate-{name}\" ({#} is the row number)").action(async (docIds, flags) => {
163
- const { exportDocs } = await import("../export-BFxKPa0W.js");
163
+ const { exportDocs } = await import("../export-CDobz0UO.js");
164
164
  await exportDocs(docIds, flags);
165
165
  });
166
166
  program.command("diff <docId>").description("Show what changed in a document since a git revision, page by page").option("-s, --since <rev>", "revision to compare against (defaults to HEAD)").option("-o, --out-dir <dir>", "directory to write the report into (defaults to `out`)").option("--json", "print the result as JSON").action(async (docId, flags) => {
167
- const { diffDoc } = await import("../diff-C1RDK_I5.js");
167
+ const { diffDoc } = await import("../diff-HVSJapV4.js");
168
168
  await diffDoc(docId, flags);
169
169
  });
170
170
  program.command("check [docIds...]").description("Report layout faults — clipped content, blank sheets, stranded headings").option("--json", "print the full report as JSON").addOption(new Option("--max-pages <n>", "fail when a document runs past n pages, and say where the length is").argParser(parsePositiveInt)).action(async (docIds, flags) => {
171
- const { checkDocs } = await import("../check--Cbkdqw3.js");
171
+ const { checkDocs } = await import("../check-BU86QFnH.js");
172
172
  await checkDocs(docIds, flags);
173
173
  });
174
174
  program.command("translations [docId]").description("List translations (meta.translationOf) and what changed in their source since").option("--diff", "print the source's changes since each translation's translatedAt").option("--mark <docId>", "record that a translation now matches its source").option("--at <rev>", "with --mark: the source commit it matches (defaults to the last one)").option("--json", "print the result as JSON").action(async (docId, flags) => {
175
- const { translations } = await import("../translations-BmTXOhx9.js");
175
+ const { translations } = await import("../translations-x2NwYrcj.js");
176
176
  await translations(docId, flags);
177
177
  });
178
178
  program.command("proofread [docIds...]").description("Report text slips — full-width letters, wrong-width punctuation, mixed scripts").option("--json", "print the full report as JSON").action(async (docIds, flags) => {
179
- const { proofreadDocs } = await import("../proofread-Dtj9OlWX.js");
179
+ const { proofreadDocs } = await import("../proofread-C0crhm3C.js");
180
180
  await proofreadDocs(docIds, flags);
181
181
  });
182
182
  program.command("templates").description("List the templates a new document can start from").option("--json", "print them as JSON").action(async (flags) => {
183
- const { printTemplates } = await import("../templates-BmSuBmj3.js");
183
+ const { printTemplates } = await import("../templates-hcl2pb6n.js");
184
184
  await printTemplates(flags);
185
185
  });
186
186
  program.command("new [docId]").description("Create a document under docs/ from a template (see `open-doc templates`)").option("-t, --template <name>", "template to start from (defaults to blank)").option("--title <title>", "title of the new document").action(async (docId, flags) => {
187
- const { newDoc } = await import("../templates-BmSuBmj3.js");
187
+ const { newDoc } = await import("../templates-hcl2pb6n.js");
188
188
  await newDoc(docId, flags);
189
189
  });
190
190
  program.command("import <file>").description("Turn a Markdown (.md) or Word (.docx) file into a document under docs/ — Word keeps its page look").option("--id <id>", "document id (defaults to a slug of the title)").option("--title <title>", "override the title").option("--subtitle <subtitle>", "subtitle, also used as the cover eyebrow").option("--lang <tag>", "language of the text, e.g. zh-Hant-TW (detected for CJK when omitted)").option("--author <author>", "author line on the cover").option("--theme <theme>", "theme id to back-link from meta.theme").addOption(new Option("--page-size <size>", "page size").choices(PAGE_SIZE_NAMES)).addOption(new Option("--orientation <orientation>", "page orientation").choices(ORIENTATIONS)).option("--no-cover", "skip the title page (Markdown, or Word with --plain)").option("--contents", "add a self-filling contents page (Markdown, or Word with --plain)").option("--plain", "Word only: structure in the house style (headings, lists, tables, a cover) instead of Word's own page look").action(async (file, flags) => {
191
- const { importDoc } = await import("../import-TLuMXkou.js");
191
+ const { importDoc } = await import("../import-BUHNpf-a.js");
192
192
  await importDoc(file, flags);
193
193
  });
194
194
  program.command("sync:skills").description("Sync built-in skills from @open-document/core into this workspace").option("--dry-run", "show what would change without writing").action(async (flags) => {
@@ -1,6 +1,6 @@
1
1
  import { n as readCoreVersion } from "./package-version-C89gtYSk.js";
2
2
  import { n as loadUserConfig } from "./open-doc-plugin-DE1sJXK_.js";
3
- import { J as makeContext } from "./session-CPFLe6BT.js";
3
+ import { J as makeContext } from "./session-CcIBEiIB.js";
4
4
  //#region src/cli/context.ts
5
5
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
6
6
  async function cliContext(userCwd = process.cwd()) {
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-CPFLe6BT.js";
1
+ import { r as createViteConfig } from "./session-CcIBEiIB.js";
2
2
  import { createServer, mergeConfig } from "vite";
3
3
  //#region src/cli/dev.ts
4
4
  async function dev(opts = {}) {
@@ -1,5 +1,5 @@
1
- import { c as diffDocument } from "./ops-BG9hfBwQ.js";
2
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { c as diffDocument } from "./ops-DKEhE_su.js";
2
+ import { t as cliContext } from "./context-DHCqEAue.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/diff.ts
5
5
  const MARK = {
@@ -1,7 +1,7 @@
1
1
  import { r as EXPORT_FORMATS } from "./sdk-CqNZzbkz.js";
2
- import { B as listDocIds, C as exportDocument, S as closeRenderSession } from "./session-CPFLe6BT.js";
3
- import "./ops-BG9hfBwQ.js";
4
- import { t as cliContext } from "./context-DRXgt6Je.js";
2
+ import { B as listDocIds, C as exportDocument, S as closeRenderSession } from "./session-CcIBEiIB.js";
3
+ import "./ops-DKEhE_su.js";
4
+ import { t as cliContext } from "./context-DHCqEAue.js";
5
5
  import chalk from "chalk";
6
6
  //#region src/cli/export.ts
7
7
  const FORMATS = EXPORT_FORMATS;
@@ -1,6 +1,6 @@
1
- import { D as importMarkdown, E as importDocx } from "./session-CPFLe6BT.js";
2
- import "./ops-BG9hfBwQ.js";
3
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { D as importMarkdown, E as importDocx } from "./session-CcIBEiIB.js";
2
+ import "./ops-DKEhE_su.js";
3
+ import { t as cliContext } from "./context-DHCqEAue.js";
4
4
  import chalk from "chalk";
5
5
  import path from "node:path";
6
6
  //#region src/cli/import.ts
package/dist/ops/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { i as ORIENTATIONS, o as PAGE_SIZE_NAMES, r as EXPORT_FORMATS } from "../sdk-CqNZzbkz.js";
2
- import { A as readChanges, B as listDocIds, C as exportDocument, D as importMarkdown, E as importDocx, F as OpsError, G as resolveEntry, H as readDocument, I as createDocument, J as makeContext, K as writeDocument, L as deleteDocument, M as assertExpectedSource, N as hashSource, O as slugify, P as withFileLock, R as docDir, S as closeRenderSession, T as renderDocPage, V as listDocuments, W as renameDocument, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as revertChange, k as listRevisions, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as proofreadDocument, x as checkLayout, y as readTheme, z as duplicateDocument } from "../session-CPFLe6BT.js";
3
- import { a as outlineSource, c as diffDocument, i as outlineDocument, n as translationStatus, o as readDocumentLines, r as editDocument, s as searchDocument, t as markTranslated } from "../ops-BG9hfBwQ.js";
2
+ import { A as readChanges, B as listDocIds, C as exportDocument, D as importMarkdown, E as importDocx, F as OpsError, G as resolveEntry, H as readDocument, I as createDocument, J as makeContext, K as writeDocument, L as deleteDocument, M as assertExpectedSource, N as hashSource, O as slugify, P as withFileLock, R as docDir, S as closeRenderSession, T as renderDocPage, V as listDocuments, W as renameDocument, _ as listFolders, a as readText, b as writeAsset, c as writeTexts, d as suggestDocId, f as createFolder, g as listAssets, h as findAssetUsages, i as addComment, j as revertChange, k as listRevisions, l as createFromTemplate, m as fileDocument, o as writeEdits, p as deleteAsset, s as writeText, u as listTemplates, v as listThemes, w as proofreadDocument, x as checkLayout, y as readTheme, z as duplicateDocument } from "../session-CcIBEiIB.js";
3
+ import { a as outlineSource, c as diffDocument, i as outlineDocument, n as translationStatus, o as readDocumentLines, r as editDocument, s as searchDocument, t as markTranslated } from "../ops-DKEhE_su.js";
4
4
  export { EXPORT_FORMATS, ORIENTATIONS, OpsError, PAGE_SIZE_NAMES, addComment, assertExpectedSource, checkLayout, closeRenderSession, createDocument, createFolder, createFromTemplate, deleteAsset, deleteDocument, diffDocument, docDir, duplicateDocument, editDocument, exportDocument, fileDocument, findAssetUsages, hashSource, importDocx, importMarkdown, listAssets, listDocIds, listDocuments, listFolders, listRevisions, listTemplates, listThemes, makeContext, markTranslated, outlineDocument, outlineSource, proofreadDocument, readChanges, readDocument, readDocumentLines, readText, readTheme, renameDocument, renderDocPage, resolveEntry, revertChange, searchDocument, slugify, suggestDocId, translationStatus, withFileLock, writeAsset, writeDocument, writeEdits, writeText, writeTexts };
@@ -1,4 +1,4 @@
1
- import { B as listDocIds, F as OpsError, G as resolveEntry, M as assertExpectedSource, N as hashSource, P as withFileLock, U as readMetaField, n as createRenderSession, q as setMetaString, t as RenderUnavailableError } from "./session-CPFLe6BT.js";
1
+ import { B as listDocIds, F as OpsError, G as resolveEntry, M as assertExpectedSource, N as hashSource, P as withFileLock, U as readMetaField, n as createRenderSession, q as setMetaString, t as RenderUnavailableError } from "./session-CcIBEiIB.js";
2
2
  import path from "node:path";
3
3
  import fs from "node:fs/promises";
4
4
  import { execFile } from "node:child_process";
@@ -1,4 +1,4 @@
1
- import { r as createViteConfig } from "./session-CPFLe6BT.js";
1
+ import { r as createViteConfig } from "./session-CcIBEiIB.js";
2
2
  import { mergeConfig, preview as preview$1 } from "vite";
3
3
  //#region src/cli/preview.ts
4
4
  async function preview(opts = {}) {
@@ -1,6 +1,6 @@
1
- import { B as listDocIds, S as closeRenderSession, w as proofreadDocument } from "./session-CPFLe6BT.js";
2
- import "./ops-BG9hfBwQ.js";
3
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { B as listDocIds, S as closeRenderSession, w as proofreadDocument } from "./session-CcIBEiIB.js";
2
+ import "./ops-DKEhE_su.js";
3
+ import { t as cliContext } from "./context-DHCqEAue.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/proofread.ts
6
6
  function line(finding) {
@@ -6778,9 +6778,12 @@ var LayoutReader = class {
6778
6778
  case "w:endnoteReference":
6779
6779
  this.readNote(node, css, out());
6780
6780
  break;
6781
- case "w:commentReference":
6782
- this.count("comment");
6781
+ case "w:commentReference": {
6782
+ const comment = this.readComment(node);
6783
+ if (comment) out().push(comment);
6784
+ else this.count("comment");
6783
6785
  break;
6786
+ }
6784
6787
  case "w:fldChar": {
6785
6788
  const type = node.attrs["w:fldCharType"];
6786
6789
  if (type === "begin") this.fields.push({
@@ -6848,6 +6851,21 @@ var LayoutReader = class {
6848
6851
  if (tabPx && em) return `calc(${round$1(em)}em + ${round$1(tabPx)}px)`;
6849
6852
  return tabPx ? `${round$1(tabPx)}px` : `${round$1(em)}em`;
6850
6853
  }
6854
+ readComment(node) {
6855
+ const part = this.pkg.partOf("/comments", "comments.xml");
6856
+ const comment = part && elements(part, "w:comment").find((el) => el.attrs["w:id"] === node.attrs["w:id"]);
6857
+ if (!comment) return void 0;
6858
+ const text = elements(comment, "w:p").map((p) => descendants(p, "w:t").map(textContent).join("")).join("\n").trim();
6859
+ if (!text) return void 0;
6860
+ const author = comment.attrs["w:author"]?.trim();
6861
+ const date = comment.attrs["w:date"];
6862
+ return {
6863
+ kind: "comment",
6864
+ text,
6865
+ ...author ? { author } : {},
6866
+ ...date && !Number.isNaN(Date.parse(date)) ? { date: new Date(date).toISOString() } : {}
6867
+ };
6868
+ }
6851
6869
  readNote(node, css, out) {
6852
6870
  const endnote = node.name === "w:endnoteReference";
6853
6871
  const part = endnote ? this.pkg.partOf("/endnotes", "endnotes.xml") : this.pkg.partOf("/footnotes", "footnotes.xml");
@@ -7785,6 +7803,113 @@ function detectLang(text) {
7785
7803
  return simplified > traditional ? "zh-Hans" : "zh-Hant";
7786
7804
  }
7787
7805
  //#endregion
7806
+ //#region src/editing/comments.ts
7807
+ const MARKER_RE = /\{\/\*\s*@doc-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
7808
+ function b64urlEncode(value) {
7809
+ return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
7810
+ }
7811
+ function b64urlDecode(value) {
7812
+ const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
7813
+ return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
7814
+ }
7815
+ function parseMarkers(source) {
7816
+ const comments = [];
7817
+ source.split("\n").forEach((line, index) => {
7818
+ const match = MARKER_RE.exec(line);
7819
+ if (!match) return;
7820
+ const [, id, ts, payload] = match;
7821
+ try {
7822
+ const decoded = JSON.parse(b64urlDecode(payload));
7823
+ comments.push({
7824
+ id,
7825
+ line: index + 1,
7826
+ ts,
7827
+ note: decoded.note,
7828
+ hint: decoded.hint
7829
+ });
7830
+ } catch {}
7831
+ });
7832
+ return comments;
7833
+ }
7834
+ /**
7835
+ * Where each marker's element starts. A marker is always an element's first
7836
+ * child, so the element holding it is the one the note is about; its start is
7837
+ * the `data-od-loc` the page stamps on it, which is how the viewer pins a note
7838
+ * to what it printed.
7839
+ */
7840
+ function locateMarkers(source, comments) {
7841
+ const ast = parseSource(source);
7842
+ if (!ast) return comments;
7843
+ const owner = /* @__PURE__ */ new Map();
7844
+ walkJsx(ast, (element) => {
7845
+ if (!element.loc) return;
7846
+ for (const child of element.children ?? []) {
7847
+ if (child.type !== "JSXExpressionContainer") continue;
7848
+ const id = /@doc-comment\s+id="(c-[a-f0-9]+)"/.exec(source.slice(child.start, child.end))?.[1];
7849
+ if (id) owner.set(id, `${element.loc.start.line}:${element.loc.start.column}`);
7850
+ }
7851
+ });
7852
+ return comments.map((comment) => {
7853
+ const loc = owner.get(comment.id);
7854
+ return loc ? {
7855
+ ...comment,
7856
+ loc
7857
+ } : comment;
7858
+ });
7859
+ }
7860
+ function newCommentId() {
7861
+ return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
7862
+ }
7863
+ function markerFor(id, ts, note, hint) {
7864
+ return `{/* @doc-comment id="${id}" ts="${ts}" text="${b64urlEncode(JSON.stringify(hint ? {
7865
+ note,
7866
+ hint
7867
+ } : { note }))}" */}`;
7868
+ }
7869
+ function markerPattern(id) {
7870
+ return `\\{\\/\\*\\s*@doc-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text="[A-Za-z0-9_\\-]+={0,2}"\\s*\\*\\/\\}`;
7871
+ }
7872
+ /**
7873
+ * Removes a marker and the whitespace the insertion added — whichever side it
7874
+ * landed on — so deleting a comment restores the file byte for byte.
7875
+ */
7876
+ function removeMarker(source, id) {
7877
+ const pattern = markerPattern(id);
7878
+ for (const re of [
7879
+ new RegExp(`[ \\t]*${pattern}\\n`),
7880
+ new RegExp(`\\n[ \\t]*${pattern}`),
7881
+ new RegExp(pattern)
7882
+ ]) if (re.test(source)) return source.replace(re, "");
7883
+ return null;
7884
+ }
7885
+ function indentOfLine(source, offset) {
7886
+ const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
7887
+ return /^[ \t]*/.exec(source.slice(lineStart, offset))?.[0] ?? "";
7888
+ }
7889
+ /**
7890
+ * Splices the marker in as the **first child** of the target element. A
7891
+ * JSX-comment token outside a JSX child position parses as an empty object
7892
+ * literal and breaks the surrounding expression, so this never puts one before
7893
+ * an element.
7894
+ */
7895
+ function insertMarker(source, target, note, hint) {
7896
+ const ast = parseStrict(source);
7897
+ if (!ast) return null;
7898
+ const element = findJsxAt(ast, target.line, target.column);
7899
+ if (!element) return null;
7900
+ const opening = element.openingElement;
7901
+ if (!opening) return null;
7902
+ if (opening.selfClosing === true) return null;
7903
+ const offset = opening.end;
7904
+ const id = newCommentId();
7905
+ const marker = markerFor(id, (/* @__PURE__ */ new Date()).toISOString(), note, hint);
7906
+ const indent = indentOfLine(source, element.start ?? offset);
7907
+ return {
7908
+ source: `${source.slice(0, offset)}\n${indent} ${marker}${source.slice(offset)}`,
7909
+ id
7910
+ };
7911
+ }
7912
+ //#endregion
7788
7913
  //#region src/import/markdown.ts
7789
7914
  const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
7790
7915
  const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
@@ -8614,6 +8739,7 @@ function renderRuns(p, base, ctx) {
8614
8739
  return runs.map((run, index) => {
8615
8740
  if (run.kind === "text") written += run.text;
8616
8741
  switch (run.kind) {
8742
+ case "comment": return "";
8617
8743
  case "break": return "<br />";
8618
8744
  case "image": {
8619
8745
  if (!run.src) return `<span${styleAttr({
@@ -8804,6 +8930,18 @@ function pick(css, keys) {
8804
8930
  function flags(block) {
8805
8931
  return [block.keepNext ? " data-od-keep-with-next=\"true\"" : "", block.breakBefore ? " data-od-break-before=\"true\"" : ""].join("");
8806
8932
  }
8933
+ /**
8934
+ * Word's comments on a paragraph, as one `@doc-comment` marker first in its element, where the
8935
+ * Comments panel pins it and the apply-comments skill reads it. One, because markers are read
8936
+ * one to a line. The id comes from the comments, so the same file imports to the same source.
8937
+ */
8938
+ function commentMarkers(p) {
8939
+ const comments = p.runs.filter((run) => run.kind === "comment");
8940
+ if (comments.length === 0) return "";
8941
+ const note = comments.map((run) => run.author ? `${run.author}: ${run.text}` : run.text).join("\n\n");
8942
+ const ts = comments.map((run) => run.date).filter((date) => !!date).sort()[0] ?? "1970-01-01T00:00:00.000Z";
8943
+ return `{/* @doc-comment id="${`c-${createHash("sha256").update(`${ts}\n${note}`).digest("hex").slice(0, 12)}`}" ts="${ts}" text="${b64urlEncode(JSON.stringify({ note }))}" */}`;
8944
+ }
8807
8945
  function renderParagraph(p, ctx, pad) {
8808
8946
  const heading = !!p.heading;
8809
8947
  const boxed = p.runs.some((run) => run.kind === "box" || run.kind === "chart" || run.kind === "image" && run.place?.mode === "over");
@@ -8819,7 +8957,7 @@ function renderParagraph(p, ctx, pad) {
8819
8957
  const after = Math.max(0, ...p.runs.map((run) => run.kind === "box" ? run.after ?? 0 : 0));
8820
8958
  if (after > 0) css.paddingBottom = after;
8821
8959
  const inline = p.runs.some((run) => run.kind !== "box");
8822
- const content = `${renderRuns(p, base, ctx)}${inline ? "" : "<br />"}`;
8960
+ const content = `${commentMarkers(p)}${renderRuns(p, base, ctx)}${inline ? "" : "<br />"}`;
8823
8961
  return `${pad}<${tag}${styleAttr(css)}${flags(p)}>${content}</${tag}>`;
8824
8962
  }
8825
8963
  function renderCell(cell, ctx, pad) {
@@ -10447,6 +10585,33 @@ function registerDocRoutes(server, ctx) {
10447
10585
  const method = req.method ?? "GET";
10448
10586
  try {
10449
10587
  const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
10588
+ const pdfMatch = url.pathname.match(/^\/([^/]+)\/pdf$/);
10589
+ if (pdfMatch && method === "POST") {
10590
+ const requestCheck = validateMutationRequest(req);
10591
+ if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
10592
+ const docId = decodeURIComponent(pdfMatch[1]);
10593
+ const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
10594
+ const outDir = path.join("node_modules", ".open-doc", "pdf", randomBytes(6).toString("hex"));
10595
+ try {
10596
+ const result = await exportDocument({
10597
+ ...ctx,
10598
+ ...origin ? { serverOrigin: origin } : {}
10599
+ }, docId, {
10600
+ format: "pdf",
10601
+ outDir
10602
+ });
10603
+ const bytes = await fs.readFile(path.resolve(ctx.userCwd, result.files[0]));
10604
+ res.statusCode = 200;
10605
+ res.setHeader("Content-Type", "application/pdf");
10606
+ res.setHeader("Cache-Control", "no-store");
10607
+ return res.end(bytes);
10608
+ } finally {
10609
+ await fs.rm(path.resolve(ctx.userCwd, outDir), {
10610
+ recursive: true,
10611
+ force: true
10612
+ });
10613
+ }
10614
+ }
10450
10615
  const idMatch = url.pathname.match(/^\/([^/]+)$/);
10451
10616
  if (url.pathname === "/" && method === "POST") {
10452
10617
  const requestCheck = validateMutationRequest(req);
@@ -10498,113 +10663,6 @@ function registerDocRoutes(server, ctx) {
10498
10663
  });
10499
10664
  }
10500
10665
  //#endregion
10501
- //#region src/editing/comments.ts
10502
- const MARKER_RE = /\{\/\*\s*@doc-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
10503
- function b64urlEncode(value) {
10504
- return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
10505
- }
10506
- function b64urlDecode(value) {
10507
- const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
10508
- return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
10509
- }
10510
- function parseMarkers(source) {
10511
- const comments = [];
10512
- source.split("\n").forEach((line, index) => {
10513
- const match = MARKER_RE.exec(line);
10514
- if (!match) return;
10515
- const [, id, ts, payload] = match;
10516
- try {
10517
- const decoded = JSON.parse(b64urlDecode(payload));
10518
- comments.push({
10519
- id,
10520
- line: index + 1,
10521
- ts,
10522
- note: decoded.note,
10523
- hint: decoded.hint
10524
- });
10525
- } catch {}
10526
- });
10527
- return comments;
10528
- }
10529
- /**
10530
- * Where each marker's element starts. A marker is always an element's first
10531
- * child, so the element holding it is the one the note is about; its start is
10532
- * the `data-od-loc` the page stamps on it, which is how the viewer pins a note
10533
- * to what it printed.
10534
- */
10535
- function locateMarkers(source, comments) {
10536
- const ast = parseSource(source);
10537
- if (!ast) return comments;
10538
- const owner = /* @__PURE__ */ new Map();
10539
- walkJsx(ast, (element) => {
10540
- if (!element.loc) return;
10541
- for (const child of element.children ?? []) {
10542
- if (child.type !== "JSXExpressionContainer") continue;
10543
- const id = /@doc-comment\s+id="(c-[a-f0-9]+)"/.exec(source.slice(child.start, child.end))?.[1];
10544
- if (id) owner.set(id, `${element.loc.start.line}:${element.loc.start.column}`);
10545
- }
10546
- });
10547
- return comments.map((comment) => {
10548
- const loc = owner.get(comment.id);
10549
- return loc ? {
10550
- ...comment,
10551
- loc
10552
- } : comment;
10553
- });
10554
- }
10555
- function newCommentId() {
10556
- return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
10557
- }
10558
- function markerFor(id, ts, note, hint) {
10559
- return `{/* @doc-comment id="${id}" ts="${ts}" text="${b64urlEncode(JSON.stringify(hint ? {
10560
- note,
10561
- hint
10562
- } : { note }))}" */}`;
10563
- }
10564
- function markerPattern(id) {
10565
- return `\\{\\/\\*\\s*@doc-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text="[A-Za-z0-9_\\-]+={0,2}"\\s*\\*\\/\\}`;
10566
- }
10567
- /**
10568
- * Removes a marker and the whitespace the insertion added — whichever side it
10569
- * landed on — so deleting a comment restores the file byte for byte.
10570
- */
10571
- function removeMarker(source, id) {
10572
- const pattern = markerPattern(id);
10573
- for (const re of [
10574
- new RegExp(`[ \\t]*${pattern}\\n`),
10575
- new RegExp(`\\n[ \\t]*${pattern}`),
10576
- new RegExp(pattern)
10577
- ]) if (re.test(source)) return source.replace(re, "");
10578
- return null;
10579
- }
10580
- function indentOfLine(source, offset) {
10581
- const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
10582
- return /^[ \t]*/.exec(source.slice(lineStart, offset))?.[0] ?? "";
10583
- }
10584
- /**
10585
- * Splices the marker in as the **first child** of the target element. A
10586
- * JSX-comment token outside a JSX child position parses as an empty object
10587
- * literal and breaks the surrounding expression, so this never puts one before
10588
- * an element.
10589
- */
10590
- function insertMarker(source, target, note, hint) {
10591
- const ast = parseStrict(source);
10592
- if (!ast) return null;
10593
- const element = findJsxAt(ast, target.line, target.column);
10594
- if (!element) return null;
10595
- const opening = element.openingElement;
10596
- if (!opening) return null;
10597
- if (opening.selfClosing === true) return null;
10598
- const offset = opening.end;
10599
- const id = newCommentId();
10600
- const marker = markerFor(id, (/* @__PURE__ */ new Date()).toISOString(), note, hint);
10601
- const indent = indentOfLine(source, element.start ?? offset);
10602
- return {
10603
- source: `${source.slice(0, offset)}\n${indent} ${marker}${source.slice(offset)}`,
10604
- id
10605
- };
10606
- }
10607
- //#endregion
10608
10666
  //#region src/editing/edit-ops.ts
10609
10667
  function escapeJsxText(text) {
10610
10668
  return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
@@ -1,6 +1,6 @@
1
- import { l as createFromTemplate, u as listTemplates } from "./session-CPFLe6BT.js";
2
- import "./ops-BG9hfBwQ.js";
3
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { l as createFromTemplate, u as listTemplates } from "./session-CcIBEiIB.js";
2
+ import "./ops-DKEhE_su.js";
3
+ import { t as cliContext } from "./context-DHCqEAue.js";
4
4
  import chalk from "chalk";
5
5
  //#region src/cli/templates.ts
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { n as translationStatus, t as markTranslated } from "./ops-BG9hfBwQ.js";
2
- import { t as cliContext } from "./context-DRXgt6Je.js";
1
+ import { n as translationStatus, t as markTranslated } from "./ops-DKEhE_su.js";
2
+ import { t as cliContext } from "./context-DHCqEAue.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/cli/translations.ts
5
5
  const STATE = {
@@ -1,3 +1,3 @@
1
1
  import { r as openDocPlugin } from "../open-doc-plugin-DE1sJXK_.js";
2
- import { r as createViteConfig } from "../session-CPFLe6BT.js";
2
+ import { r as createViteConfig } from "../session-CcIBEiIB.js";
3
3
  export { createViteConfig, openDocPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-document/core",
3
- "version": "0.17.1",
3
+ "version": "0.17.3",
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": {
@@ -10,6 +10,16 @@ This skill is the **technical reference** for everything inside `docs/<id>/index
10
10
  - `create-doc` owns "draft a new document" — it asks the scoping questions, then delegates the *how* to this skill.
11
11
  - Any ad-hoc edit (fix a table, retitle a section, adjust margins) should also read this first.
12
12
 
13
+ ## Changing an existing document
14
+
15
+ Change the lines that change, not the file; most requests touch a few, even big-sounding ones:
16
+
17
+ - **A title, a sentence, a table row, one style**: edit those lines (your edit tool, or `edit_document` over MCP). Reports run 800–2000 lines: find the part first (`grep -n ": DocPage = "` or `outline_document`) and read ~150 lines around it.
18
+ - **A new look** (other colours, fonts or spacing): change the `design` const or its theme, not every element. A quoted value turned into a token or constant loses its quotes: `color: '#1A1A1A'` becomes `color: 'var(--od-ink)'` or `color: INK`, never `color: 'INK'`.
19
+ - **A variant** ("a shorter version of X"): duplicate the document, then edit the copy.
20
+ - **Write the whole file** only for a new document, or when more than half of its lines change (a new structure). Rewriting a long file is slow, and every copied line can break.
21
+ - **Renumbering costs**: a section inserted among numbered headings ("3.2") means editing every later one; prefer appending.
22
+
13
23
  ## Primitive references
14
24
 
15
25
  Read the matching reference **before** using a primitive:
@@ -296,18 +306,6 @@ export const meta: DocMeta = {
296
306
  export default [Cover, Section] satisfies DocPage[];
297
307
  ```
298
308
 
299
- ## Editing an existing document
300
-
301
- A finished report commonly runs 800–2000 lines. When you only need one page, **don't read the whole file** — locate it first:
302
-
303
- ```bash
304
- grep -n ": DocPage = " docs/<id>/index.tsx
305
- ```
306
-
307
- Then `Read` with `offset` + `limit` (~150 lines covers a page plus its helpers). Read the whole file only for cross-page work (renumbering sections, palette audit, reordering).
308
-
309
- **Renumbering is a real cost.** If sections are numbered ("3.2 Findings"), inserting a page means editing every downstream heading. Prefer appending, or use unnumbered headings when the document is still churning.
310
-
311
309
  ## Prose discipline
312
310
 
313
311
  A document is not a slide deck. Long-form copy is the point — but it still has rules:
@@ -6,6 +6,7 @@ import { format, plural, useLocale } from '@/lib/use-locale';
6
6
  import { cn } from '@/lib/utils';
7
7
  import { checkFixPrompt, stripDocSlug } from '../../../agent/prompt';
8
8
  import type { AgentItem, AgentQuestion, AgentSession, RespondPayload } from '../../../agent/types';
9
+ import { copyText } from '../../lib/clipboard';
9
10
  import { AgentMarkdown } from './agent-markdown';
10
11
 
11
12
  export function Transcript({
@@ -178,10 +179,7 @@ function CopyButton({ text }: { text: string }) {
178
179
  <ActionButton
179
180
  label={copied ? t.agent.copied : t.agent.copyMessage}
180
181
  onClick={() => {
181
- navigator.clipboard.writeText(text).then(
182
- () => setCopied(true),
183
- () => {},
184
- );
182
+ void copyText(text).then((ok) => ok && setCopied(true));
185
183
  }}
186
184
  >
187
185
  {copied ? <Check /> : <Copy />}
@@ -8,7 +8,9 @@ import {
8
8
  X,
9
9
  } from 'lucide-react';
10
10
  import { useState } from 'react';
11
+ import { copyText } from '../../lib/clipboard';
11
12
  import { useLocale, useT } from '../../lib/i18n';
13
+ import { toast } from '../../lib/toast';
12
14
  import { PanelIconButton, PanelShell } from '../panel/panel-shell';
13
15
  import type { CommentsState, DocComment } from './use-comments';
14
16
 
@@ -189,11 +191,13 @@ export function CommentsPanel({
189
191
  const comments = state.status === 'ready' ? state.comments : [];
190
192
 
191
193
  const copy = async () => {
192
- try {
193
- await navigator.clipboard.writeText(`/apply-comments docs/${docId}`);
194
- setCopied(true);
195
- window.setTimeout(() => setCopied(false), 1600);
196
- } catch {}
194
+ const command = `/apply-comments docs/${docId}`;
195
+ if (!(await copyText(command))) {
196
+ toast.error(t('Copying is blocked here'), { description: command });
197
+ return;
198
+ }
199
+ setCopied(true);
200
+ window.setTimeout(() => setCopied(false), 1600);
197
201
  };
198
202
 
199
203
  return (