@open-document/core 0.13.2 → 0.14.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 (70) hide show
  1. package/dist/{build-CvsOak5B.js → build-CyBlmrjS.js} +1 -1
  2. package/dist/{check-CbUBwYmf.js → check-DUKDEem-.js} +3 -3
  3. package/dist/cli/bin.js +10 -21
  4. package/dist/{config-BWtOZ1jc.d.ts → config-cAV1OCuY.d.ts} +9 -1
  5. package/dist/{config-CltJJVsw.js → config-cNpYUpF6.js} +2746 -369
  6. package/dist/{context-CWgfsHoE.js → context-BPApOW9n.js} +1 -1
  7. package/dist/{dev-B8H2qT6G.js → dev-DrnOvsX3.js} +1 -1
  8. package/dist/{diff-BvIjjgnc.js → diff-BPMD2Knh.js} +2 -2
  9. package/dist/{export-DX30_s2q.js → export-DeVtL8aX.js} +3 -3
  10. package/dist/{import-DgsdJT5e.js → import-WAgWsuOv.js} +3 -2
  11. package/dist/index.d.ts +2 -2
  12. package/dist/ops/index.d.ts +3 -1
  13. package/dist/ops/index.js +2 -2
  14. package/dist/{ops-CSR5RlrE.js → ops-raK6424A.js} +2 -854
  15. package/dist/{preview-DYMUNjXL.js → preview-B8Vw9QCh.js} +1 -1
  16. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  17. package/dist/{templates-B5Tz0AKb.js → templates-D9jAFJ8R.js} +3 -3
  18. package/dist/vite/index.d.ts +1 -1
  19. package/dist/vite/index.js +1 -1
  20. package/package.json +1 -1
  21. package/skills/create-doc/SKILL.md +1 -1
  22. package/skills/doc-authoring/SKILL.md +6 -0
  23. package/src/app/app.tsx +2 -0
  24. package/src/app/components/agent/agent-dock.tsx +75 -0
  25. package/src/app/components/agent/agent-markdown.tsx +45 -0
  26. package/src/app/components/agent/agent-panel.tsx +690 -0
  27. package/src/app/components/agent/agent-presence.tsx +74 -0
  28. package/src/app/components/agent/composer.tsx +120 -0
  29. package/src/app/components/agent/connect-view.tsx +183 -0
  30. package/src/app/components/agent/history-view.tsx +134 -0
  31. package/src/app/components/agent/provider-logo.tsx +23 -0
  32. package/src/app/components/agent/transcript.tsx +609 -0
  33. package/src/app/components/comments/comments-panel.tsx +26 -2
  34. package/src/app/components/inspector/inspector.tsx +17 -0
  35. package/src/app/components/note-markdown.tsx +85 -0
  36. package/src/app/components/page-error-boundary.tsx +84 -0
  37. package/src/app/components/page-frame.tsx +2 -1
  38. package/src/app/components/panel/resize-handle.tsx +129 -0
  39. package/src/app/components/ui/button.tsx +97 -0
  40. package/src/app/components/ui/popover.tsx +144 -0
  41. package/src/app/components/ui/tooltip.tsx +123 -0
  42. package/src/app/lib/agent/use-agent.ts +543 -0
  43. package/src/app/lib/diagnostics.ts +13 -0
  44. package/src/app/lib/docx/from-dom.ts +91 -6
  45. package/src/app/lib/docx/ooxml.test.ts +58 -0
  46. package/src/app/lib/docx/ooxml.ts +58 -9
  47. package/src/app/lib/export-dom.ts +2 -1
  48. package/src/app/lib/export-pdf.ts +2 -1
  49. package/src/app/lib/i18n-ja/agent-panel.ts +107 -0
  50. package/src/app/lib/i18n-ja/agent.ts +9 -0
  51. package/src/app/lib/i18n-ja/index.ts +9 -1
  52. package/src/app/lib/i18n-ko/agent-panel.ts +106 -0
  53. package/src/app/lib/i18n-ko/agent.ts +9 -0
  54. package/src/app/lib/i18n-ko/index.ts +9 -1
  55. package/src/app/lib/i18n-zh-cn/agent-panel.ts +105 -0
  56. package/src/app/lib/i18n-zh-cn/agent.ts +9 -0
  57. package/src/app/lib/i18n-zh-cn/index.ts +9 -1
  58. package/src/app/lib/i18n-zh-tw/agent-panel.ts +105 -0
  59. package/src/app/lib/i18n-zh-tw/agent.ts +9 -0
  60. package/src/app/lib/i18n-zh-tw/index.ts +9 -1
  61. package/src/app/lib/note-markdown.ts +116 -0
  62. package/src/app/lib/toast.ts +50 -0
  63. package/src/app/lib/use-auto-grow.ts +15 -0
  64. package/src/app/lib/use-doc-titles.ts +28 -0
  65. package/src/app/lib/use-locale.ts +144 -0
  66. package/src/app/lib/utils.ts +4 -0
  67. package/src/app/routes/doc-preview.tsx +103 -0
  68. package/src/app/routes/doc.tsx +118 -11
  69. package/src/app/routes/home.tsx +43 -8
  70. package/src/app/styles.css +193 -0
@@ -1,9 +1,6 @@
1
- import { c as isPageSizeName, i as ORIENTATIONS, o as PAGE_SIZE_NAMES, s as isOrientation } from "./sdk-CqNZzbkz.js";
2
- import { t as DOC_ID_RE } from "./open-doc-plugin-DnX5usgI.js";
3
- import { D as createDocument, E as OpsError, F as resolveEntry, j as listDocIds, t as createViteConfig, y as validateAssetName } from "./config-CltJJVsw.js";
1
+ import { D as OpsError, I as resolveEntry, t as createViteConfig } from "./config-cNpYUpF6.js";
4
2
  import path from "node:path";
5
3
  import fs from "node:fs/promises";
6
- import { existsSync } from "node:fs";
7
4
  import { createServer, mergeConfig } from "vite";
8
5
  import { execFile } from "node:child_process";
9
6
  import { promisify } from "node:util";
@@ -653,855 +650,6 @@ async function diffDocument(ctx, docId, opts = {}) {
653
650
  }
654
651
  }
655
652
  //#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
685
- //#region src/import/markdown.ts
686
- const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
687
- const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
688
- const HR_RE = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
689
- const QUOTE_RE = /^ {0,3}> ?(.*)$/;
690
- const UL_RE = /^(\s*)([-*+])\s+(.*)$/;
691
- const OL_RE = /^(\s*)(\d{1,9})[.)]\s+(.*)$/;
692
- const SETEXT_RE = /^ {0,3}(=+|-+)\s*$/;
693
- const TABLE_DELIM_RE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
694
- function splitLines(source) {
695
- return source.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
696
- }
697
- function parseFrontmatter(lines) {
698
- if (lines[0]?.trim() !== "---") return {
699
- frontmatter: {},
700
- rest: lines
701
- };
702
- const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
703
- if (end === -1) return {
704
- frontmatter: {},
705
- rest: lines
706
- };
707
- const frontmatter = {};
708
- for (const line of lines.slice(1, end)) {
709
- const match = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
710
- if (!match) continue;
711
- frontmatter[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
712
- }
713
- return {
714
- frontmatter,
715
- rest: lines.slice(end + 1)
716
- };
717
- }
718
- function splitRow(line) {
719
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
720
- const cells = [];
721
- let current = "";
722
- for (let i = 0; i < trimmed.length; i++) {
723
- const char = trimmed[i];
724
- if (char === "\\" && trimmed[i + 1] === "|") {
725
- current += "|";
726
- i++;
727
- continue;
728
- }
729
- if (char === "|") {
730
- cells.push(current.trim());
731
- current = "";
732
- continue;
733
- }
734
- current += char;
735
- }
736
- cells.push(current.trim());
737
- return cells;
738
- }
739
- function parseAlign(line) {
740
- return splitRow(line).map((cell) => {
741
- const left = cell.startsWith(":");
742
- const right = cell.endsWith(":");
743
- if (left && right) return "center";
744
- if (right) return "right";
745
- if (left) return "left";
746
- return null;
747
- });
748
- }
749
- function indentOf(line) {
750
- return line.length - line.trimStart().length;
751
- }
752
- function isBlockStart(line) {
753
- return ATX_RE.test(line) || HR_RE.test(line) || QUOTE_RE.test(line) || UL_RE.test(line) || OL_RE.test(line) || FENCE_RE.test(line);
754
- }
755
- function parseMarkdown(source) {
756
- const { frontmatter, rest } = parseFrontmatter(splitLines(source));
757
- return {
758
- frontmatter,
759
- blocks: parseBlocks(rest)
760
- };
761
- }
762
- function parseBlocks(lines) {
763
- const blocks = [];
764
- let i = 0;
765
- while (i < lines.length) {
766
- const line = lines[i];
767
- if (line.trim() === "") {
768
- i++;
769
- continue;
770
- }
771
- const fence = line.match(FENCE_RE);
772
- if (fence) {
773
- const marker = fence[1];
774
- const value = [];
775
- i++;
776
- while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
777
- value.push(lines[i]);
778
- i++;
779
- }
780
- i++;
781
- blocks.push({
782
- type: "code",
783
- lang: fence[2] || null,
784
- value: value.join("\n")
785
- });
786
- continue;
787
- }
788
- const atx = line.match(ATX_RE);
789
- if (atx) {
790
- blocks.push({
791
- type: "heading",
792
- level: atx[1].length,
793
- children: parseInline(atx[2])
794
- });
795
- i++;
796
- continue;
797
- }
798
- if (HR_RE.test(line)) {
799
- blocks.push({ type: "hr" });
800
- i++;
801
- continue;
802
- }
803
- if (QUOTE_RE.test(line)) {
804
- const inner = [];
805
- while (i < lines.length && (QUOTE_RE.test(lines[i]) || lines[i].trim() !== "")) {
806
- const match = lines[i].match(QUOTE_RE);
807
- if (!match && lines[i].trim() === "") break;
808
- inner.push(match ? match[1] : lines[i]);
809
- i++;
810
- }
811
- blocks.push({
812
- type: "quote",
813
- children: parseBlocks(inner)
814
- });
815
- continue;
816
- }
817
- if (UL_RE.test(line) || OL_RE.test(line)) {
818
- const { block, next } = parseList(lines, i);
819
- blocks.push(block);
820
- i = next;
821
- continue;
822
- }
823
- if (line.includes("|") && lines[i + 1] !== void 0 && TABLE_DELIM_RE.test(lines[i + 1])) {
824
- const head = splitRow(line).map(parseInline);
825
- const align = parseAlign(lines[i + 1]);
826
- const rows = [];
827
- i += 2;
828
- while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
829
- rows.push(splitRow(lines[i]).map(parseInline));
830
- i++;
831
- }
832
- blocks.push({
833
- type: "table",
834
- head,
835
- rows,
836
- align
837
- });
838
- continue;
839
- }
840
- const paragraph = [];
841
- while (i < lines.length && lines[i].trim() !== "") {
842
- const next = lines[i + 1];
843
- if (next !== void 0 && SETEXT_RE.test(next)) {
844
- paragraph.push(lines[i]);
845
- i += 2;
846
- blocks.push({
847
- type: "heading",
848
- level: next.trim().startsWith("=") ? 1 : 2,
849
- children: parseInline(paragraph.join(" "))
850
- });
851
- paragraph.length = 0;
852
- break;
853
- }
854
- if (paragraph.length > 0 && isBlockStart(lines[i])) break;
855
- paragraph.push(lines[i]);
856
- i++;
857
- }
858
- if (paragraph.length > 0) {
859
- const text = paragraph.join("\n");
860
- const figure = asStandaloneImage(text);
861
- blocks.push(figure ?? {
862
- type: "paragraph",
863
- children: parseInline(text)
864
- });
865
- }
866
- }
867
- return blocks;
868
- }
869
- /** An image alone in its paragraph is a figure, not a run of inline content. */
870
- function asStandaloneImage(text) {
871
- const match = text.trim().match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
872
- if (!match) return null;
873
- return {
874
- type: "figure",
875
- alt: match[1],
876
- src: match[2]
877
- };
878
- }
879
- function parseList(lines, start) {
880
- const first = lines[start];
881
- const ordered = OL_RE.test(first);
882
- const startNumber = ordered ? Number(first.match(OL_RE)?.[2] ?? 1) : 1;
883
- const baseIndent = indentOf(first);
884
- const items = [];
885
- let i = start;
886
- let current = null;
887
- const flush = () => {
888
- if (current) items.push(parseBlocks(current));
889
- current = null;
890
- };
891
- while (i < lines.length) {
892
- const line = lines[i];
893
- if (line.trim() === "") {
894
- const next = lines[i + 1];
895
- if (next === void 0 || next.trim() !== "" && indentOf(next) <= baseIndent && !isItem(next)) break;
896
- current?.push("");
897
- i++;
898
- continue;
899
- }
900
- const match = line.match(ordered ? OL_RE : UL_RE) ?? line.match(ordered ? UL_RE : OL_RE);
901
- if (match && indentOf(line) <= baseIndent) {
902
- flush();
903
- current = [match[3]];
904
- i++;
905
- continue;
906
- }
907
- if (indentOf(line) > baseIndent && current) {
908
- current.push(line.slice(Math.min(indentOf(line), baseIndent + 2)));
909
- i++;
910
- continue;
911
- }
912
- break;
913
- }
914
- flush();
915
- return {
916
- block: {
917
- type: "list",
918
- ordered,
919
- start: startNumber,
920
- items
921
- },
922
- next: i
923
- };
924
- function isItem(line) {
925
- return UL_RE.test(line) || OL_RE.test(line);
926
- }
927
- }
928
- const INLINE_RE = /(!\[[^\]]*\]\([^)\s]+(?:\s+"[^"]*")?\))|(\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\))|(`+)([^`]*?)\3|(\*\*|__)(?=\S)([\s\S]*?\S)\5|(\*|_)(?=\S)([\s\S]*?\S)\7|(<[^>\s]+@[^>\s]+>)|(https?:\/\/[^\s<>"')\]]+)/;
929
- function parseInline(source) {
930
- const out = [];
931
- let rest = maskEscapes(source);
932
- const pushText = (value) => {
933
- if (value === "") return;
934
- value.split(/(?: {2}|\\)\n|\n/).forEach((part, index) => {
935
- if (index > 0) out.push({ type: "break" });
936
- const text = unmask(part);
937
- if (text !== "") out.push({
938
- type: "text",
939
- value: text
940
- });
941
- });
942
- };
943
- while (rest.length > 0) {
944
- const match = rest.match(INLINE_RE);
945
- if (!match || match.index === void 0) break;
946
- pushText(rest.slice(0, match.index));
947
- const token = match[0];
948
- if (match[1]) {
949
- const image = token.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
950
- if (image) out.push({
951
- type: "image",
952
- alt: unmask(image[1]),
953
- src: unmask(image[2])
954
- });
955
- } else if (match[2]) {
956
- const link = token.match(/^\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)$/);
957
- if (link) out.push({
958
- type: "link",
959
- href: unmask(link[2]),
960
- children: parseInline(link[1])
961
- });
962
- } else if (match[3]) out.push({
963
- type: "code",
964
- value: unmask(match[4].trim())
965
- });
966
- else if (match[5]) out.push({
967
- type: "strong",
968
- children: parseInline(match[6])
969
- });
970
- else if (match[7]) out.push({
971
- type: "em",
972
- children: parseInline(match[8])
973
- });
974
- else if (match[9]) {
975
- const address = token.slice(1, -1);
976
- out.push({
977
- type: "link",
978
- href: `mailto:${address}`,
979
- children: [{
980
- type: "text",
981
- value: address
982
- }]
983
- });
984
- } else if (match[10]) {
985
- const url = unmask(token);
986
- out.push({
987
- type: "link",
988
- href: url,
989
- children: [{
990
- type: "text",
991
- value: url
992
- }]
993
- });
994
- }
995
- rest = rest.slice(match.index + token.length);
996
- }
997
- pushText(rest);
998
- return out;
999
- }
1000
- const ESCAPE_RE = /\\([\\`*_{}[\]()#+\-.!|>~])/g;
1001
- const MASK_RE = /\u0000(\d+)\u0000/g;
1002
- /**
1003
- * The inline scanner is a regex over delimiters, which cannot see a preceding
1004
- * backslash. Escaped characters are swapped for a sentinel before scanning and
1005
- * restored on the way out, so `\*not emphasis\*` survives as literal text.
1006
- */
1007
- function maskEscapes(value) {
1008
- return value.replace(ESCAPE_RE, (_, char) => `\u0000${char.charCodeAt(0)}\u0000`);
1009
- }
1010
- function unmask(value) {
1011
- return value.replace(MASK_RE, (_, code) => String.fromCharCode(Number(code)));
1012
- }
1013
- /** Flattens inline content to plain text — for titles, alt text, and outline labels. */
1014
- function inlineText(nodes) {
1015
- return nodes.map((node) => {
1016
- switch (node.type) {
1017
- case "text":
1018
- case "code": return node.value;
1019
- case "strong":
1020
- case "em":
1021
- case "link": return inlineText(node.children);
1022
- case "image": return node.alt;
1023
- case "break": return " ";
1024
- default: return "";
1025
- }
1026
- }).join("").replace(/\s+/g, " ").trim();
1027
- }
1028
- //#endregion
1029
- //#region src/import/to-tsx.ts
1030
- /** JSX text is written literally; only these characters have to be escaped. */
1031
- function jsxText(text) {
1032
- return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
1033
- }
1034
- function jsString(value) {
1035
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
1036
- }
1037
- function attr(value) {
1038
- return `"${value.replace(/"/g, "&quot;")}"`;
1039
- }
1040
- function collectImageSources(blocks) {
1041
- const out = [];
1042
- const walkInline = (nodes) => {
1043
- for (const node of nodes) if (node.type === "image") out.push(node.src);
1044
- else if (node.type === "strong" || node.type === "em" || node.type === "link") walkInline(node.children);
1045
- };
1046
- const walk = (list) => {
1047
- for (const block of list) switch (block.type) {
1048
- case "figure":
1049
- out.push(block.src);
1050
- break;
1051
- case "heading":
1052
- case "paragraph":
1053
- walkInline(block.children);
1054
- break;
1055
- case "quote":
1056
- walk(block.children);
1057
- break;
1058
- case "list":
1059
- for (const item of block.items) walk(item);
1060
- break;
1061
- case "table":
1062
- for (const cell of block.head) walkInline(cell);
1063
- for (const row of block.rows) for (const cell of row) walkInline(cell);
1064
- }
1065
- };
1066
- walk(blocks);
1067
- return out;
1068
- }
1069
- function imageSrc(src, images) {
1070
- const known = images?.get(src);
1071
- return known ? `{${known.ident}}` : attr(src);
1072
- }
1073
- function renderInline(nodes, images) {
1074
- return nodes.map((node) => {
1075
- switch (node.type) {
1076
- case "text": return jsxText(node.value);
1077
- case "strong": return `<strong>${renderInline(node.children, images)}</strong>`;
1078
- case "em": return `<em>${renderInline(node.children, images)}</em>`;
1079
- case "code": return `<code style={codeInline}>${jsxText(node.value)}</code>`;
1080
- case "link": return `<a href=${attr(node.href)} style={link}>${renderInline(node.children, images)}</a>`;
1081
- case "image": return `<img src=${imageSrc(node.src, images)} alt=${attr(node.alt)} style={inlineImg} />`;
1082
- case "break": return "<br />";
1083
- default: return "";
1084
- }
1085
- }).join("");
1086
- }
1087
- const HEADING_STYLE = {
1088
- 1: "h1",
1089
- 2: "h2",
1090
- 3: "h3",
1091
- 4: "h4"
1092
- };
1093
- function alignStyle(align) {
1094
- return align && align !== "left" ? ` align={${jsString(align)}}` : "";
1095
- }
1096
- function renderBlock(block, images, indent) {
1097
- const pad = indent;
1098
- switch (block.type) {
1099
- case "heading": {
1100
- const level = Math.min(block.level, 4);
1101
- const tag = level >= 4 ? "h4" : `h${level}`;
1102
- return `${pad}<${tag} style={${HEADING_STYLE[level] ?? "h3"}}>${renderInline(block.children, images)}</${tag}>`;
1103
- }
1104
- case "paragraph": return `${pad}<p style={p}>${renderInline(block.children, images)}</p>`;
1105
- case "hr": return `${pad}<hr style={rule} />`;
1106
- case "code": return `${pad}<pre style={pre}>{${jsString(block.value)}}</pre>`;
1107
- case "quote": return [
1108
- `${pad}<blockquote style={quote}>`,
1109
- ...block.children.map((child) => renderBlock(child, images, `${pad} `)),
1110
- `${pad}</blockquote>`
1111
- ].join("\n");
1112
- case "figure": {
1113
- const caption = block.alt ? `\n${pad} <figcaption style={caption}>${jsxText(block.alt)}</figcaption>` : "";
1114
- return [
1115
- `${pad}<figure style={figure}>`,
1116
- `${pad} <img src=${imageSrc(block.src, images)} alt=${attr(block.alt)} style={img} />${caption}`,
1117
- `${pad}</figure>`
1118
- ].join("\n");
1119
- }
1120
- case "list": {
1121
- const tag = block.ordered ? "ol" : "ul";
1122
- const startAttr = block.ordered && block.start !== 1 ? ` start={${block.start}}` : "";
1123
- const items = block.items.map((item) => {
1124
- const inner = item.map((child, index) => child.type === "paragraph" && index === 0 ? `${renderInline(child.children, images)}` : `\n${renderBlock(child, images, `${pad} `)}`).join("");
1125
- return `${pad} <li style={li}>${inner.startsWith("\n") ? `${inner}\n${pad} ` : inner}</li>`;
1126
- });
1127
- return [
1128
- `${pad}<${tag} style={${tag}}${startAttr}>`,
1129
- ...items,
1130
- `${pad}</${tag}>`
1131
- ].join("\n");
1132
- }
1133
- case "table": {
1134
- const head = block.head.map((cell, i) => `${pad} <Th${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Th>`).join("\n");
1135
- const rows = block.rows.map((row) => [
1136
- `${pad} <tr>`,
1137
- ...row.map((cell, i) => `${pad} <Td${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Td>`),
1138
- `${pad} </tr>`
1139
- ].join("\n")).join("\n");
1140
- return [
1141
- `${pad}<table style={table}>`,
1142
- `${pad} <thead>`,
1143
- `${pad} <tr>`,
1144
- head,
1145
- `${pad} </tr>`,
1146
- `${pad} </thead>`,
1147
- `${pad} <tbody>`,
1148
- rows,
1149
- `${pad} </tbody>`,
1150
- `${pad}</table>`
1151
- ].join("\n");
1152
- }
1153
- }
1154
- }
1155
- function titleFrom(parsed, opts) {
1156
- if (opts.title) return opts.title;
1157
- if (parsed.frontmatter.title) return parsed.frontmatter.title;
1158
- const heading = parsed.blocks.find((block) => block.type === "heading" && block.level === 1);
1159
- if (heading && heading.type === "heading") return inlineText(heading.children);
1160
- return opts.docId.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
1161
- }
1162
- const STYLES = `const page = {
1163
- width: '100%',
1164
- height: '100%',
1165
- boxSizing: 'border-box' as const,
1166
- padding: 'var(--od-margin)',
1167
- background: 'var(--od-bg)',
1168
- color: 'var(--od-text)',
1169
- fontFamily: 'var(--od-font-body)',
1170
- fontSize: 'var(--od-size-body)',
1171
- lineHeight: 'var(--od-leading)',
1172
- position: 'relative' as const,
1173
- };
1174
-
1175
- const h1 = {
1176
- fontFamily: 'var(--od-font-heading)',
1177
- fontSize: 'var(--od-size-h1)',
1178
- lineHeight: 1.2,
1179
- fontWeight: 650,
1180
- margin: '0 0 18px',
1181
- };
1182
-
1183
- const h2 = { ...h1, fontSize: 'var(--od-size-h2)', margin: '26px 0 12px' };
1184
- const h3 = { ...h1, fontSize: 'var(--od-size-h3)', fontWeight: 600, margin: '20px 0 8px' };
1185
- const h4 = { ...h3, fontSize: 'var(--od-size-body)', margin: '16px 0 6px' };
1186
- const p = { margin: '0 0 12px' };
1187
- // The viewer's CSS reset strips list markers, so both are set back explicitly.
1188
- const ul = { margin: '0 0 12px', paddingLeft: 22, listStyle: 'disc outside' };
1189
- const ol = { ...ul, listStyle: 'decimal outside' };
1190
- const li = { margin: '0 0 5px' };
1191
- const link = { color: 'var(--od-accent)', textDecoration: 'none' };
1192
- const rule = { border: 0, borderTop: '1px solid var(--od-rule)', margin: '20px 0' };
1193
-
1194
- const codeInline = {
1195
- fontFamily: 'var(--od-font-mono)',
1196
- fontSize: '0.92em',
1197
- background: 'var(--od-rule)',
1198
- borderRadius: 3,
1199
- padding: '1px 4px',
1200
- };
1201
-
1202
- const pre = {
1203
- fontFamily: 'var(--od-font-mono)',
1204
- fontSize: 11,
1205
- lineHeight: 1.5,
1206
- background: 'var(--od-rule)',
1207
- borderRadius: 'var(--od-radius)',
1208
- padding: '10px 12px',
1209
- margin: '0 0 14px',
1210
- whiteSpace: 'pre-wrap' as const,
1211
- overflowWrap: 'anywhere' as const,
1212
- };
1213
-
1214
- const quote = {
1215
- margin: '0 0 14px',
1216
- padding: '2px 0 2px 14px',
1217
- borderLeft: '2px solid var(--od-accent)',
1218
- color: 'var(--od-muted)',
1219
- };
1220
-
1221
- const table = {
1222
- width: '100%',
1223
- borderCollapse: 'collapse' as const,
1224
- tableLayout: 'fixed' as const,
1225
- margin: '0 0 16px',
1226
- };
1227
-
1228
- const figure = { margin: '0 0 16px' };
1229
- const img = { width: '100%', display: 'block' as const };
1230
- const inlineImg = { maxWidth: '100%', verticalAlign: 'middle' as const };
1231
- const caption = { fontSize: 'var(--od-size-caption)', color: 'var(--od-muted)', margin: '6px 0 0' };
1232
-
1233
- const Th = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
1234
- <th
1235
- style={{
1236
- textAlign: align,
1237
- fontFamily: 'var(--od-font-heading)',
1238
- fontSize: 11,
1239
- fontWeight: 600,
1240
- letterSpacing: '0.04em',
1241
- textTransform: 'uppercase',
1242
- color: 'var(--od-muted)',
1243
- borderBottom: '1px solid var(--od-rule)',
1244
- padding: '0 8px 6px',
1245
- }}
1246
- >
1247
- {children}
1248
- </th>
1249
- );
1250
-
1251
- const Td = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
1252
- <td
1253
- style={{
1254
- textAlign: align,
1255
- fontSize: 12,
1256
- padding: '7px 8px',
1257
- borderBottom: '1px solid var(--od-rule)',
1258
- fontVariantNumeric: align === 'right' ? 'tabular-nums' : undefined,
1259
- }}
1260
- >
1261
- {children}
1262
- </td>
1263
- );
1264
-
1265
- const Footer = () => {
1266
- const n = useDocPageNumber();
1267
- const total = useDocPageCount();
1268
- return (
1269
- <div
1270
- style={{
1271
- position: 'absolute',
1272
- left: 'var(--od-margin)',
1273
- right: 'var(--od-margin)',
1274
- bottom: 40,
1275
- display: 'flex',
1276
- justifyContent: 'space-between',
1277
- fontSize: 'var(--od-size-caption)',
1278
- color: 'var(--od-muted)',
1279
- }}
1280
- >
1281
- <span>{DOC_TITLE}</span>
1282
- <span style={{ fontVariantNumeric: 'tabular-nums' }}>
1283
- {n} / {total}
1284
- </span>
1285
- </div>
1286
- );
1287
- };`;
1288
- const DESIGN = `export const design: DesignSystem = {
1289
- palette: {
1290
- bg: '#ffffff',
1291
- text: '#16181d',
1292
- muted: '#6b7280',
1293
- accent: '#2563eb',
1294
- rule: '#e5e7eb',
1295
- },
1296
- fonts: {
1297
- heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
1298
- body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
1299
- mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
1300
- },
1301
- typeScale: { title: 44, h1: 28, h2: 20, h3: 16, body: 14, caption: 10 },
1302
- margin: 76,
1303
- leading: 1.55,
1304
- radius: 6,
1305
- };`;
1306
- /**
1307
- * Turns parsed markdown into a document module. The output is ordinary authored
1308
- * TSX — inline styles, real heading tags, plain JSX text — so the outline, the
1309
- * inspector, and the design panel all work on an imported document exactly as
1310
- * they do on a hand-written one.
1311
- */
1312
- function generateDocumentSource(parsed, opts) {
1313
- const title = titleFrom(parsed, opts);
1314
- const subtitle = opts.subtitle ?? parsed.frontmatter.subtitle;
1315
- const author = opts.author ?? parsed.frontmatter.author;
1316
- const theme = opts.theme ?? parsed.frontmatter.theme;
1317
- const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1318
- const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1319
- const lang = opts.lang ?? parsed.frontmatter.lang;
1320
- const cover = opts.cover !== false;
1321
- let blocks = parsed.blocks;
1322
- const first = blocks[0];
1323
- if (cover && first?.type === "heading" && first.level === 1 && inlineText(first.children) === title) blocks = blocks.slice(1);
1324
- const images = opts.images;
1325
- const imports = images ? [...images.values()] : [];
1326
- const head = [
1327
- `import type { ReactNode } from 'react';`,
1328
- `import {\n${[
1329
- "type DesignSystem",
1330
- "type DocEntry",
1331
- "type DocMeta",
1332
- ...cover || opts.contents ? ["type DocPage"] : [],
1333
- ...opts.contents ? ["TableOfContents"] : [],
1334
- "flow",
1335
- "useDocPageCount",
1336
- "useDocPageNumber"
1337
- ].map((name) => ` ${name},`).join("\n")}\n} from '@open-document/core';`,
1338
- ...imports.map((image) => `import ${image.ident} from './assets/${image.filename}';`)
1339
- ].join("\n");
1340
- const styles = STYLES.replace("{DOC_TITLE}", jsxText(title));
1341
- const coverPage = cover ? `const Cover: DocPage = () => (
1342
- <div style={{ ...page, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
1343
- ${subtitle ? ` <p style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--od-accent)', margin: 0 }}>
1344
- ${jsxText(subtitle)}
1345
- </p>\n` : ""} <h1 style={{ ...h1, fontSize: 'var(--od-size-title)', margin: '16px 0 12px' }} data-od-outline="skip">
1346
- ${jsxText(title)}
1347
- </h1>
1348
- ${author ? ` <p style={{ color: 'var(--od-muted)', margin: 0 }}>${jsxText(author)}</p>\n` : ""} </div>
1349
- );` : "";
1350
- const contentsPage = opts.contents ? `const Contents: DocPage = () => (
1351
- <div style={page}>
1352
- <h1 style={h1} data-od-outline="skip">
1353
- Contents
1354
- </h1>
1355
- <TableOfContents maxLevel={2} />
1356
- </div>
1357
- );` : "";
1358
- const body = `const Body = flow(
1359
- <>
1360
- ${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
1361
- </>,
1362
- { footer: Footer },
1363
- );`;
1364
- const metaFields = [
1365
- ` title: ${jsString(title)},`,
1366
- ...subtitle ? [` subtitle: ${jsString(subtitle)},`] : [],
1367
- ...author ? [` author: ${jsString(author)},`] : [],
1368
- ...pageSize ? [` pageSize: ${jsString(pageSize)},`] : [],
1369
- ...orientation ? [` orientation: ${jsString(orientation)},`] : [],
1370
- ...theme ? [` theme: ${jsString(theme)},`] : [],
1371
- ...lang ? [` lang: ${jsString(lang)},`] : [],
1372
- ` createdAt: ${jsString(opts.createdAt)},`
1373
- ];
1374
- const entries = [
1375
- ...cover ? ["Cover"] : [],
1376
- ...opts.contents ? ["Contents"] : [],
1377
- "Body"
1378
- ];
1379
- return {
1380
- source: [
1381
- head,
1382
- "",
1383
- DESIGN,
1384
- "",
1385
- styles,
1386
- "",
1387
- ...coverPage ? [coverPage, ""] : [],
1388
- ...contentsPage ? [contentsPage, ""] : [],
1389
- body,
1390
- "",
1391
- `export const meta: DocMeta = {\n${metaFields.join("\n")}\n};`,
1392
- `export default [${entries.join(", ")}] satisfies DocEntry[];`,
1393
- ""
1394
- ].join("\n"),
1395
- title,
1396
- blockCount: blocks.length
1397
- };
1398
- }
1399
- //#endregion
1400
- //#region src/ops/import.ts
1401
- const REMOTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1402
- function slugify(value, fallback = "document") {
1403
- const slug = value.normalize("NFKD").toLowerCase().replace(/['"]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
1404
- return DOC_ID_RE.test(slug) ? slug : fallback;
1405
- }
1406
- function uniqueId(base, taken) {
1407
- if (!taken.has(base)) return base;
1408
- for (let n = 2; n < 1e3; n++) {
1409
- const candidate = `${base}-${n}`;
1410
- if (!taken.has(candidate)) return candidate;
1411
- }
1412
- throw new OpsError(409, `could not find a free id for ${base}`);
1413
- }
1414
- function identFor(index) {
1415
- return `figure${index + 1}`;
1416
- }
1417
- /**
1418
- * Reads markdown and writes a real open-doc document: `flow()` body, inline
1419
- * styles, a cover, and any local images copied into the document's own assets
1420
- * folder. Nothing about the result is special-cased — it is the same shape an
1421
- * agent would have written by hand, and every editing surface works on it.
1422
- */
1423
- async function importMarkdown(ctx, opts) {
1424
- const sourceFile = opts.file ? path.resolve(ctx.userCwd, opts.file) : null;
1425
- if (sourceFile && !sourceFile.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `file must sit inside the workspace: ${opts.file}`);
1426
- let markdown = opts.markdown;
1427
- if (markdown === void 0) {
1428
- if (!sourceFile) throw new OpsError(400, "pass either `markdown` or `file`");
1429
- try {
1430
- markdown = await fs.readFile(sourceFile, "utf8");
1431
- } catch {
1432
- throw new OpsError(404, `file not found: ${opts.file}`);
1433
- }
1434
- }
1435
- if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
1436
- const parsed = parseMarkdown(markdown);
1437
- const language = opts.lang ?? (parsed.frontmatter.lang ? void 0 : detectLang(markdown));
1438
- const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
1439
- if (pageSize !== void 0 && !isPageSizeName(pageSize)) throw new OpsError(422, `unsupported pageSize \`${pageSize}\` — use ${PAGE_SIZE_NAMES.join(", ")}`);
1440
- const orientation = opts.orientation ?? parsed.frontmatter.orientation;
1441
- if (orientation !== void 0 && !isOrientation(orientation)) throw new OpsError(422, `unsupported orientation \`${orientation}\` — use ${ORIENTATIONS.join(", ")}`);
1442
- const fallbackName = sourceFile ? path.basename(sourceFile).replace(/\.mdx?$/i, "") : "document";
1443
- const requestedId = opts.docId ?? slugify(opts.title ?? parsed.frontmatter.title ?? fallbackName);
1444
- if (opts.docId && !DOC_ID_RE.test(opts.docId)) throw new OpsError(400, `invalid document id: ${opts.docId}`);
1445
- const docId = opts.docId ?? uniqueId(requestedId, new Set(await listDocIds(ctx)));
1446
- const baseDir = sourceFile ? path.dirname(sourceFile) : ctx.userCwd;
1447
- const images = /* @__PURE__ */ new Map();
1448
- const missing = [];
1449
- const staged = [];
1450
- const usedNames = /* @__PURE__ */ new Set();
1451
- for (const src of new Set(collectImageSources(parsed.blocks))) {
1452
- if (REMOTE_RE.test(src)) continue;
1453
- const from = path.resolve(baseDir, src.split(/[?#]/)[0]);
1454
- if (!from.startsWith(ctx.userCwd + path.sep) || !existsSync(from)) {
1455
- missing.push(src);
1456
- continue;
1457
- }
1458
- const safe = validateAssetName(path.basename(from));
1459
- if (!safe) {
1460
- missing.push(src);
1461
- continue;
1462
- }
1463
- const filename = usedNames.has(safe) ? `${images.size + 1}-${safe}` : safe;
1464
- usedNames.add(filename);
1465
- images.set(src, {
1466
- source: src,
1467
- ident: identFor(images.size),
1468
- filename
1469
- });
1470
- staged.push({
1471
- from,
1472
- filename
1473
- });
1474
- }
1475
- const generated = generateDocumentSource(parsed, {
1476
- docId,
1477
- ...opts.title !== void 0 ? { title: opts.title } : {},
1478
- ...opts.subtitle !== void 0 ? { subtitle: opts.subtitle } : {},
1479
- ...opts.author !== void 0 ? { author: opts.author } : {},
1480
- ...opts.theme !== void 0 ? { theme: opts.theme } : {},
1481
- ...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
1482
- ...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
1483
- ...language ? { lang: language } : {},
1484
- ...opts.cover !== void 0 ? { cover: opts.cover } : {},
1485
- ...opts.contents !== void 0 ? { contents: opts.contents } : {},
1486
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1487
- images
1488
- });
1489
- const created = await createDocument(ctx, docId, generated.source);
1490
- if (staged.length > 0) {
1491
- const assetsDir = path.join(ctx.docsRoot, docId, "assets");
1492
- await fs.mkdir(assetsDir, { recursive: true });
1493
- for (const { from, filename } of staged) await fs.copyFile(from, path.join(assetsDir, filename));
1494
- }
1495
- return {
1496
- id: created.id,
1497
- entry: created.entry,
1498
- title: generated.title,
1499
- blocks: generated.blockCount,
1500
- assets: staged.map((asset) => asset.filename),
1501
- missingAssets: missing
1502
- };
1503
- }
1504
- //#endregion
1505
653
  //#region src/ops/layout.ts
1506
654
  /**
1507
655
  * Chromium and a Vite server are expensive to start, and an agent checking its
@@ -1670,4 +818,4 @@ async function exportDocument(ctx, docId, opts = {}) {
1670
818
  });
1671
819
  }
1672
820
  //#endregion
1673
- export { importMarkdown as a, renderDocPage as i, closeRenderSession as n, slugify as o, exportDocument as r, diffDocument as s, checkLayout as t };
821
+ export { diffDocument as a, renderDocPage as i, closeRenderSession as n, exportDocument as r, checkLayout as t };