@open-document/core 0.1.0 → 0.3.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.
- package/dist/{build-BWZJ1gvL.js → build-C3pMGxJN.js} +2 -6
- package/dist/check-Dtwb1wvU.js +42 -0
- package/dist/cli/bin.d.ts +1 -1
- package/dist/cli/bin.js +124 -13
- package/dist/{config-EBFfKtWH.d.ts → config-CSC5lHsR.d.ts} +3 -2
- package/dist/config-Dg1AMP0r.js +2461 -0
- package/dist/context-FoX0afRf.js +26 -0
- package/dist/{dev-CZtw1oqs.js → dev-Cdd7NZRQ.js} +2 -6
- package/dist/diagram-xlVDekYk.js +763 -0
- package/dist/export-ClJ4T1uU.js +36 -0
- package/dist/import-D7Psi8WK.js +25 -0
- package/dist/index.d.ts +238 -117
- package/dist/index.js +516 -57
- package/dist/ops/index.d.ts +98 -8
- package/dist/ops/index.js +3 -202
- package/dist/ops-Ci5Xw6QG.js +1270 -0
- package/dist/{preview-DUfQl7Ij.js → preview-BhbCiAKC.js} +2 -6
- package/dist/sdk-CWMsH9Ms.d.ts +123 -0
- package/dist/vite/index.d.ts +9 -4
- package/dist/vite/index.js +2 -5
- package/env.d.ts +33 -1
- package/package.json +17 -6
- package/skills/create-doc/SKILL.md +6 -2
- package/skills/current-doc/SKILL.md +120 -0
- package/skills/doc-authoring/SKILL.md +79 -0
- package/skills/doc-authoring/references/long-form.md +131 -0
- package/src/app/components/data-table.tsx +196 -0
- package/src/app/components/diagram.tsx +76 -0
- package/src/app/components/flow-page.tsx +20 -3
- package/src/app/components/footnote.tsx +196 -0
- package/src/app/components/inspector/inspector.tsx +16 -0
- package/src/app/components/numbering.tsx +208 -0
- package/src/app/lib/agent-bridge.ts +128 -0
- package/src/app/lib/diagnostics.ts +282 -0
- package/src/app/lib/export-html.ts +35 -11
- package/src/app/lib/export-pdf.ts +54 -19
- package/src/app/lib/flow-measure.ts +100 -31
- package/src/app/lib/flow.test.ts +46 -0
- package/src/app/lib/flow.ts +28 -3
- package/src/app/lib/footnotes.test.tsx +102 -0
- package/src/app/lib/footnotes.ts +94 -0
- package/src/app/lib/labels.ts +175 -0
- package/src/app/lib/page-context.tsx +6 -1
- package/src/app/lib/scan.ts +26 -0
- package/src/app/lib/sdk.ts +3 -0
- package/src/app/lib/use-doc-pages.ts +50 -15
- package/src/app/routes/doc.tsx +25 -5
- package/dist/config-DBp4mOOf.js +0 -1121
- package/dist/design-BJLvOcCO.js +0 -53
- package/dist/edit-ops-DSdUroVO.js +0 -1225
- package/dist/sync-6GTPAt2t.js +0 -86
- package/dist/sync-C6CsPmyK.js +0 -3
|
@@ -0,0 +1,1270 @@
|
|
|
1
|
+
import { C as readManifest, E as writeManifest, O as DOC_ID_RE, S as newFolderId, T as validateName, a as insertMarker, b as resolveEntry, c as resolveScopedAssetFile, d as OpsError, f as createDocument, g as listDocIds, i as resolveTextTarget, l as resolveScopedAssetsDir, n as parseFrontmatter$1, o as assetImportPath, r as replaceTextAt, s as countAssetUsages, t as createViteConfig, u as validateAssetName, w as validateIcon } from "./config-Dg1AMP0r.js";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import fg from "fast-glob";
|
|
6
|
+
import { createServer, mergeConfig } from "vite";
|
|
7
|
+
import { Buffer } from "node:buffer";
|
|
8
|
+
//#region src/import/markdown.ts
|
|
9
|
+
const FENCE_RE = /^(```|~~~)\s*([^\s`]*)\s*$/;
|
|
10
|
+
const ATX_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
|
|
11
|
+
const HR_RE = /^ {0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/;
|
|
12
|
+
const QUOTE_RE = /^ {0,3}> ?(.*)$/;
|
|
13
|
+
const UL_RE = /^(\s*)([-*+])\s+(.*)$/;
|
|
14
|
+
const OL_RE = /^(\s*)(\d{1,9})[.)]\s+(.*)$/;
|
|
15
|
+
const SETEXT_RE = /^ {0,3}(=+|-+)\s*$/;
|
|
16
|
+
const TABLE_DELIM_RE = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/;
|
|
17
|
+
function splitLines(source) {
|
|
18
|
+
return source.replace(/^/, "").replace(/\r\n?/g, "\n").split("\n");
|
|
19
|
+
}
|
|
20
|
+
function parseFrontmatter(lines) {
|
|
21
|
+
if (lines[0]?.trim() !== "---") return {
|
|
22
|
+
frontmatter: {},
|
|
23
|
+
rest: lines
|
|
24
|
+
};
|
|
25
|
+
const end = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
|
|
26
|
+
if (end === -1) return {
|
|
27
|
+
frontmatter: {},
|
|
28
|
+
rest: lines
|
|
29
|
+
};
|
|
30
|
+
const frontmatter = {};
|
|
31
|
+
for (const line of lines.slice(1, end)) {
|
|
32
|
+
const match = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
33
|
+
if (!match) continue;
|
|
34
|
+
frontmatter[match[1]] = match[2].trim().replace(/^['"]|['"]$/g, "");
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
frontmatter,
|
|
38
|
+
rest: lines.slice(end + 1)
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function splitRow(line) {
|
|
42
|
+
const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
|
|
43
|
+
const cells = [];
|
|
44
|
+
let current = "";
|
|
45
|
+
for (let i = 0; i < trimmed.length; i++) {
|
|
46
|
+
const char = trimmed[i];
|
|
47
|
+
if (char === "\\" && trimmed[i + 1] === "|") {
|
|
48
|
+
current += "|";
|
|
49
|
+
i++;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (char === "|") {
|
|
53
|
+
cells.push(current.trim());
|
|
54
|
+
current = "";
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
current += char;
|
|
58
|
+
}
|
|
59
|
+
cells.push(current.trim());
|
|
60
|
+
return cells;
|
|
61
|
+
}
|
|
62
|
+
function parseAlign(line) {
|
|
63
|
+
return splitRow(line).map((cell) => {
|
|
64
|
+
const left = cell.startsWith(":");
|
|
65
|
+
const right = cell.endsWith(":");
|
|
66
|
+
if (left && right) return "center";
|
|
67
|
+
if (right) return "right";
|
|
68
|
+
if (left) return "left";
|
|
69
|
+
return null;
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
function indentOf(line) {
|
|
73
|
+
return line.length - line.trimStart().length;
|
|
74
|
+
}
|
|
75
|
+
function isBlockStart(line) {
|
|
76
|
+
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);
|
|
77
|
+
}
|
|
78
|
+
function parseMarkdown(source) {
|
|
79
|
+
const { frontmatter, rest } = parseFrontmatter(splitLines(source));
|
|
80
|
+
return {
|
|
81
|
+
frontmatter,
|
|
82
|
+
blocks: parseBlocks(rest)
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function parseBlocks(lines) {
|
|
86
|
+
const blocks = [];
|
|
87
|
+
let i = 0;
|
|
88
|
+
while (i < lines.length) {
|
|
89
|
+
const line = lines[i];
|
|
90
|
+
if (line.trim() === "") {
|
|
91
|
+
i++;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const fence = line.match(FENCE_RE);
|
|
95
|
+
if (fence) {
|
|
96
|
+
const marker = fence[1];
|
|
97
|
+
const value = [];
|
|
98
|
+
i++;
|
|
99
|
+
while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
|
|
100
|
+
value.push(lines[i]);
|
|
101
|
+
i++;
|
|
102
|
+
}
|
|
103
|
+
i++;
|
|
104
|
+
blocks.push({
|
|
105
|
+
type: "code",
|
|
106
|
+
lang: fence[2] || null,
|
|
107
|
+
value: value.join("\n")
|
|
108
|
+
});
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const atx = line.match(ATX_RE);
|
|
112
|
+
if (atx) {
|
|
113
|
+
blocks.push({
|
|
114
|
+
type: "heading",
|
|
115
|
+
level: atx[1].length,
|
|
116
|
+
children: parseInline(atx[2])
|
|
117
|
+
});
|
|
118
|
+
i++;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (HR_RE.test(line)) {
|
|
122
|
+
blocks.push({ type: "hr" });
|
|
123
|
+
i++;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (QUOTE_RE.test(line)) {
|
|
127
|
+
const inner = [];
|
|
128
|
+
while (i < lines.length && (QUOTE_RE.test(lines[i]) || lines[i].trim() !== "")) {
|
|
129
|
+
const match = lines[i].match(QUOTE_RE);
|
|
130
|
+
if (!match && lines[i].trim() === "") break;
|
|
131
|
+
inner.push(match ? match[1] : lines[i]);
|
|
132
|
+
i++;
|
|
133
|
+
}
|
|
134
|
+
blocks.push({
|
|
135
|
+
type: "quote",
|
|
136
|
+
children: parseBlocks(inner)
|
|
137
|
+
});
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (UL_RE.test(line) || OL_RE.test(line)) {
|
|
141
|
+
const { block, next } = parseList(lines, i);
|
|
142
|
+
blocks.push(block);
|
|
143
|
+
i = next;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (line.includes("|") && lines[i + 1] !== void 0 && TABLE_DELIM_RE.test(lines[i + 1])) {
|
|
147
|
+
const head = splitRow(line).map(parseInline);
|
|
148
|
+
const align = parseAlign(lines[i + 1]);
|
|
149
|
+
const rows = [];
|
|
150
|
+
i += 2;
|
|
151
|
+
while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
|
|
152
|
+
rows.push(splitRow(lines[i]).map(parseInline));
|
|
153
|
+
i++;
|
|
154
|
+
}
|
|
155
|
+
blocks.push({
|
|
156
|
+
type: "table",
|
|
157
|
+
head,
|
|
158
|
+
rows,
|
|
159
|
+
align
|
|
160
|
+
});
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
const paragraph = [];
|
|
164
|
+
while (i < lines.length && lines[i].trim() !== "") {
|
|
165
|
+
const next = lines[i + 1];
|
|
166
|
+
if (next !== void 0 && SETEXT_RE.test(next)) {
|
|
167
|
+
paragraph.push(lines[i]);
|
|
168
|
+
i += 2;
|
|
169
|
+
blocks.push({
|
|
170
|
+
type: "heading",
|
|
171
|
+
level: next.trim().startsWith("=") ? 1 : 2,
|
|
172
|
+
children: parseInline(paragraph.join(" "))
|
|
173
|
+
});
|
|
174
|
+
paragraph.length = 0;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
if (paragraph.length > 0 && isBlockStart(lines[i])) break;
|
|
178
|
+
paragraph.push(lines[i]);
|
|
179
|
+
i++;
|
|
180
|
+
}
|
|
181
|
+
if (paragraph.length > 0) {
|
|
182
|
+
const text = paragraph.join("\n");
|
|
183
|
+
const figure = asStandaloneImage(text);
|
|
184
|
+
blocks.push(figure ?? {
|
|
185
|
+
type: "paragraph",
|
|
186
|
+
children: parseInline(text)
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return blocks;
|
|
191
|
+
}
|
|
192
|
+
/** An image alone in its paragraph is a figure, not a run of inline content. */
|
|
193
|
+
function asStandaloneImage(text) {
|
|
194
|
+
const match = text.trim().match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
|
|
195
|
+
if (!match) return null;
|
|
196
|
+
return {
|
|
197
|
+
type: "figure",
|
|
198
|
+
alt: match[1],
|
|
199
|
+
src: match[2]
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
function parseList(lines, start) {
|
|
203
|
+
const first = lines[start];
|
|
204
|
+
const ordered = OL_RE.test(first);
|
|
205
|
+
const startNumber = ordered ? Number(first.match(OL_RE)?.[2] ?? 1) : 1;
|
|
206
|
+
const baseIndent = indentOf(first);
|
|
207
|
+
const items = [];
|
|
208
|
+
let i = start;
|
|
209
|
+
let current = null;
|
|
210
|
+
const flush = () => {
|
|
211
|
+
if (current) items.push(parseBlocks(current));
|
|
212
|
+
current = null;
|
|
213
|
+
};
|
|
214
|
+
while (i < lines.length) {
|
|
215
|
+
const line = lines[i];
|
|
216
|
+
if (line.trim() === "") {
|
|
217
|
+
const next = lines[i + 1];
|
|
218
|
+
if (next === void 0 || next.trim() !== "" && indentOf(next) <= baseIndent && !isItem(next)) break;
|
|
219
|
+
current?.push("");
|
|
220
|
+
i++;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const match = line.match(ordered ? OL_RE : UL_RE) ?? line.match(ordered ? UL_RE : OL_RE);
|
|
224
|
+
if (match && indentOf(line) <= baseIndent) {
|
|
225
|
+
flush();
|
|
226
|
+
current = [match[3]];
|
|
227
|
+
i++;
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (indentOf(line) > baseIndent && current) {
|
|
231
|
+
current.push(line.slice(Math.min(indentOf(line), baseIndent + 2)));
|
|
232
|
+
i++;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
flush();
|
|
238
|
+
return {
|
|
239
|
+
block: {
|
|
240
|
+
type: "list",
|
|
241
|
+
ordered,
|
|
242
|
+
start: startNumber,
|
|
243
|
+
items
|
|
244
|
+
},
|
|
245
|
+
next: i
|
|
246
|
+
};
|
|
247
|
+
function isItem(line) {
|
|
248
|
+
return UL_RE.test(line) || OL_RE.test(line);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
const INLINE_RE = /(!\[[^\]]*\]\([^)\s]+(?:\s+"[^"]*")?\))|(\[[^\]]*\]\([^)\s]*(?:\s+"[^"]*")?\))|(`+)([^`]*?)\3|(\*\*|__)(?=\S)([\s\S]*?\S)\5|(\*|_)(?=\S)([\s\S]*?\S)\7|(<[^>\s]+@[^>\s]+>)|(https?:\/\/[^\s<>"')\]]+)/;
|
|
252
|
+
function parseInline(source) {
|
|
253
|
+
const out = [];
|
|
254
|
+
let rest = maskEscapes(source);
|
|
255
|
+
const pushText = (value) => {
|
|
256
|
+
if (value === "") return;
|
|
257
|
+
value.split(/(?: {2}|\\)\n|\n/).forEach((part, index) => {
|
|
258
|
+
if (index > 0) out.push({ type: "break" });
|
|
259
|
+
const text = unmask(part);
|
|
260
|
+
if (text !== "") out.push({
|
|
261
|
+
type: "text",
|
|
262
|
+
value: text
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
};
|
|
266
|
+
while (rest.length > 0) {
|
|
267
|
+
const match = rest.match(INLINE_RE);
|
|
268
|
+
if (!match || match.index === void 0) break;
|
|
269
|
+
pushText(rest.slice(0, match.index));
|
|
270
|
+
const token = match[0];
|
|
271
|
+
if (match[1]) {
|
|
272
|
+
const image = token.match(/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)$/);
|
|
273
|
+
if (image) out.push({
|
|
274
|
+
type: "image",
|
|
275
|
+
alt: unmask(image[1]),
|
|
276
|
+
src: unmask(image[2])
|
|
277
|
+
});
|
|
278
|
+
} else if (match[2]) {
|
|
279
|
+
const link = token.match(/^\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)$/);
|
|
280
|
+
if (link) out.push({
|
|
281
|
+
type: "link",
|
|
282
|
+
href: unmask(link[2]),
|
|
283
|
+
children: parseInline(link[1])
|
|
284
|
+
});
|
|
285
|
+
} else if (match[3]) out.push({
|
|
286
|
+
type: "code",
|
|
287
|
+
value: unmask(match[4].trim())
|
|
288
|
+
});
|
|
289
|
+
else if (match[5]) out.push({
|
|
290
|
+
type: "strong",
|
|
291
|
+
children: parseInline(match[6])
|
|
292
|
+
});
|
|
293
|
+
else if (match[7]) out.push({
|
|
294
|
+
type: "em",
|
|
295
|
+
children: parseInline(match[8])
|
|
296
|
+
});
|
|
297
|
+
else if (match[9]) {
|
|
298
|
+
const address = token.slice(1, -1);
|
|
299
|
+
out.push({
|
|
300
|
+
type: "link",
|
|
301
|
+
href: `mailto:${address}`,
|
|
302
|
+
children: [{
|
|
303
|
+
type: "text",
|
|
304
|
+
value: address
|
|
305
|
+
}]
|
|
306
|
+
});
|
|
307
|
+
} else if (match[10]) {
|
|
308
|
+
const url = unmask(token);
|
|
309
|
+
out.push({
|
|
310
|
+
type: "link",
|
|
311
|
+
href: url,
|
|
312
|
+
children: [{
|
|
313
|
+
type: "text",
|
|
314
|
+
value: url
|
|
315
|
+
}]
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
rest = rest.slice(match.index + token.length);
|
|
319
|
+
}
|
|
320
|
+
pushText(rest);
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
const ESCAPE_RE = /\\([\\`*_{}[\]()#+\-.!|>~])/g;
|
|
324
|
+
const MASK_RE = /\u0000(\d+)\u0000/g;
|
|
325
|
+
/**
|
|
326
|
+
* The inline scanner is a regex over delimiters, which cannot see a preceding
|
|
327
|
+
* backslash. Escaped characters are swapped for a sentinel before scanning and
|
|
328
|
+
* restored on the way out, so `\*not emphasis\*` survives as literal text.
|
|
329
|
+
*/
|
|
330
|
+
function maskEscapes(value) {
|
|
331
|
+
return value.replace(ESCAPE_RE, (_, char) => `\u0000${char.charCodeAt(0)}\u0000`);
|
|
332
|
+
}
|
|
333
|
+
function unmask(value) {
|
|
334
|
+
return value.replace(MASK_RE, (_, code) => String.fromCharCode(Number(code)));
|
|
335
|
+
}
|
|
336
|
+
/** Flattens inline content to plain text — for titles, alt text, and outline labels. */
|
|
337
|
+
function inlineText(nodes) {
|
|
338
|
+
return nodes.map((node) => {
|
|
339
|
+
switch (node.type) {
|
|
340
|
+
case "text":
|
|
341
|
+
case "code": return node.value;
|
|
342
|
+
case "strong":
|
|
343
|
+
case "em":
|
|
344
|
+
case "link": return inlineText(node.children);
|
|
345
|
+
case "image": return node.alt;
|
|
346
|
+
case "break": return " ";
|
|
347
|
+
default: return "";
|
|
348
|
+
}
|
|
349
|
+
}).join("").replace(/\s+/g, " ").trim();
|
|
350
|
+
}
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/import/to-tsx.ts
|
|
353
|
+
/** JSX text is written literally; only these characters have to be escaped. */
|
|
354
|
+
function jsxText(text) {
|
|
355
|
+
return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
|
|
356
|
+
}
|
|
357
|
+
function jsString(value) {
|
|
358
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
|
|
359
|
+
}
|
|
360
|
+
function attr(value) {
|
|
361
|
+
return `"${value.replace(/"/g, """)}"`;
|
|
362
|
+
}
|
|
363
|
+
function collectImageSources(blocks) {
|
|
364
|
+
const out = [];
|
|
365
|
+
const walkInline = (nodes) => {
|
|
366
|
+
for (const node of nodes) if (node.type === "image") out.push(node.src);
|
|
367
|
+
else if (node.type === "strong" || node.type === "em" || node.type === "link") walkInline(node.children);
|
|
368
|
+
};
|
|
369
|
+
const walk = (list) => {
|
|
370
|
+
for (const block of list) switch (block.type) {
|
|
371
|
+
case "figure":
|
|
372
|
+
out.push(block.src);
|
|
373
|
+
break;
|
|
374
|
+
case "heading":
|
|
375
|
+
case "paragraph":
|
|
376
|
+
walkInline(block.children);
|
|
377
|
+
break;
|
|
378
|
+
case "quote":
|
|
379
|
+
walk(block.children);
|
|
380
|
+
break;
|
|
381
|
+
case "list":
|
|
382
|
+
for (const item of block.items) walk(item);
|
|
383
|
+
break;
|
|
384
|
+
case "table":
|
|
385
|
+
for (const cell of block.head) walkInline(cell);
|
|
386
|
+
for (const row of block.rows) for (const cell of row) walkInline(cell);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
walk(blocks);
|
|
390
|
+
return out;
|
|
391
|
+
}
|
|
392
|
+
function imageSrc(src, images) {
|
|
393
|
+
const known = images?.get(src);
|
|
394
|
+
return known ? `{${known.ident}}` : attr(src);
|
|
395
|
+
}
|
|
396
|
+
function renderInline(nodes, images) {
|
|
397
|
+
return nodes.map((node) => {
|
|
398
|
+
switch (node.type) {
|
|
399
|
+
case "text": return jsxText(node.value);
|
|
400
|
+
case "strong": return `<strong>${renderInline(node.children, images)}</strong>`;
|
|
401
|
+
case "em": return `<em>${renderInline(node.children, images)}</em>`;
|
|
402
|
+
case "code": return `<code style={codeInline}>${jsxText(node.value)}</code>`;
|
|
403
|
+
case "link": return `<a href=${attr(node.href)} style={link}>${renderInline(node.children, images)}</a>`;
|
|
404
|
+
case "image": return `<img src=${imageSrc(node.src, images)} alt=${attr(node.alt)} style={inlineImg} />`;
|
|
405
|
+
case "break": return "<br />";
|
|
406
|
+
default: return "";
|
|
407
|
+
}
|
|
408
|
+
}).join("");
|
|
409
|
+
}
|
|
410
|
+
const HEADING_STYLE = {
|
|
411
|
+
1: "h1",
|
|
412
|
+
2: "h2",
|
|
413
|
+
3: "h3",
|
|
414
|
+
4: "h4"
|
|
415
|
+
};
|
|
416
|
+
function alignStyle(align) {
|
|
417
|
+
return align && align !== "left" ? ` align={${jsString(align)}}` : "";
|
|
418
|
+
}
|
|
419
|
+
function renderBlock(block, images, indent) {
|
|
420
|
+
const pad = indent;
|
|
421
|
+
switch (block.type) {
|
|
422
|
+
case "heading": {
|
|
423
|
+
const level = Math.min(block.level, 4);
|
|
424
|
+
const tag = level >= 4 ? "h4" : `h${level}`;
|
|
425
|
+
return `${pad}<${tag} style={${HEADING_STYLE[level] ?? "h3"}}>${renderInline(block.children, images)}</${tag}>`;
|
|
426
|
+
}
|
|
427
|
+
case "paragraph": return `${pad}<p style={p}>${renderInline(block.children, images)}</p>`;
|
|
428
|
+
case "hr": return `${pad}<hr style={rule} />`;
|
|
429
|
+
case "code": return `${pad}<pre style={pre}>{${jsString(block.value)}}</pre>`;
|
|
430
|
+
case "quote": return [
|
|
431
|
+
`${pad}<blockquote style={quote}>`,
|
|
432
|
+
...block.children.map((child) => renderBlock(child, images, `${pad} `)),
|
|
433
|
+
`${pad}</blockquote>`
|
|
434
|
+
].join("\n");
|
|
435
|
+
case "figure": {
|
|
436
|
+
const caption = block.alt ? `\n${pad} <figcaption style={caption}>${jsxText(block.alt)}</figcaption>` : "";
|
|
437
|
+
return [
|
|
438
|
+
`${pad}<figure style={figure}>`,
|
|
439
|
+
`${pad} <img src=${imageSrc(block.src, images)} alt=${attr(block.alt)} style={img} />${caption}`,
|
|
440
|
+
`${pad}</figure>`
|
|
441
|
+
].join("\n");
|
|
442
|
+
}
|
|
443
|
+
case "list": {
|
|
444
|
+
const tag = block.ordered ? "ol" : "ul";
|
|
445
|
+
const startAttr = block.ordered && block.start !== 1 ? ` start={${block.start}}` : "";
|
|
446
|
+
const items = block.items.map((item) => {
|
|
447
|
+
const inner = item.map((child, index) => child.type === "paragraph" && index === 0 ? `${renderInline(child.children, images)}` : `\n${renderBlock(child, images, `${pad} `)}`).join("");
|
|
448
|
+
return `${pad} <li style={li}>${inner.startsWith("\n") ? `${inner}\n${pad} ` : inner}</li>`;
|
|
449
|
+
});
|
|
450
|
+
return [
|
|
451
|
+
`${pad}<${tag} style={${tag}}${startAttr}>`,
|
|
452
|
+
...items,
|
|
453
|
+
`${pad}</${tag}>`
|
|
454
|
+
].join("\n");
|
|
455
|
+
}
|
|
456
|
+
case "table": {
|
|
457
|
+
const head = block.head.map((cell, i) => `${pad} <Th${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Th>`).join("\n");
|
|
458
|
+
const rows = block.rows.map((row) => [
|
|
459
|
+
`${pad} <tr>`,
|
|
460
|
+
...row.map((cell, i) => `${pad} <Td${alignStyle(block.align[i] ?? null)}>${renderInline(cell, images)}</Td>`),
|
|
461
|
+
`${pad} </tr>`
|
|
462
|
+
].join("\n")).join("\n");
|
|
463
|
+
return [
|
|
464
|
+
`${pad}<table style={table}>`,
|
|
465
|
+
`${pad} <thead>`,
|
|
466
|
+
`${pad} <tr>`,
|
|
467
|
+
head,
|
|
468
|
+
`${pad} </tr>`,
|
|
469
|
+
`${pad} </thead>`,
|
|
470
|
+
`${pad} <tbody>`,
|
|
471
|
+
rows,
|
|
472
|
+
`${pad} </tbody>`,
|
|
473
|
+
`${pad}</table>`
|
|
474
|
+
].join("\n");
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
function titleFrom(parsed, opts) {
|
|
479
|
+
if (opts.title) return opts.title;
|
|
480
|
+
if (parsed.frontmatter.title) return parsed.frontmatter.title;
|
|
481
|
+
const heading = parsed.blocks.find((block) => block.type === "heading" && block.level === 1);
|
|
482
|
+
if (heading && heading.type === "heading") return inlineText(heading.children);
|
|
483
|
+
return opts.docId.replace(/-/g, " ").replace(/^\w/, (c) => c.toUpperCase());
|
|
484
|
+
}
|
|
485
|
+
const STYLES = `const page = {
|
|
486
|
+
width: '100%',
|
|
487
|
+
height: '100%',
|
|
488
|
+
boxSizing: 'border-box' as const,
|
|
489
|
+
padding: 'var(--od-margin)',
|
|
490
|
+
background: 'var(--od-bg)',
|
|
491
|
+
color: 'var(--od-text)',
|
|
492
|
+
fontFamily: 'var(--od-font-body)',
|
|
493
|
+
fontSize: 'var(--od-size-body)',
|
|
494
|
+
lineHeight: 'var(--od-leading)',
|
|
495
|
+
position: 'relative' as const,
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
const h1 = {
|
|
499
|
+
fontFamily: 'var(--od-font-heading)',
|
|
500
|
+
fontSize: 'var(--od-size-h1)',
|
|
501
|
+
lineHeight: 1.2,
|
|
502
|
+
fontWeight: 650,
|
|
503
|
+
margin: '0 0 18px',
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
const h2 = { ...h1, fontSize: 'var(--od-size-h2)', margin: '26px 0 12px' };
|
|
507
|
+
const h3 = { ...h1, fontSize: 'var(--od-size-h3)', fontWeight: 600, margin: '20px 0 8px' };
|
|
508
|
+
const h4 = { ...h3, fontSize: 'var(--od-size-body)', margin: '16px 0 6px' };
|
|
509
|
+
const p = { margin: '0 0 12px' };
|
|
510
|
+
// The viewer's CSS reset strips list markers, so both are set back explicitly.
|
|
511
|
+
const ul = { margin: '0 0 12px', paddingLeft: 22, listStyle: 'disc outside' };
|
|
512
|
+
const ol = { ...ul, listStyle: 'decimal outside' };
|
|
513
|
+
const li = { margin: '0 0 5px' };
|
|
514
|
+
const link = { color: 'var(--od-accent)', textDecoration: 'none' };
|
|
515
|
+
const rule = { border: 0, borderTop: '1px solid var(--od-rule)', margin: '20px 0' };
|
|
516
|
+
|
|
517
|
+
const codeInline = {
|
|
518
|
+
fontFamily: 'var(--od-font-mono)',
|
|
519
|
+
fontSize: '0.92em',
|
|
520
|
+
background: 'var(--od-rule)',
|
|
521
|
+
borderRadius: 3,
|
|
522
|
+
padding: '1px 4px',
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const pre = {
|
|
526
|
+
fontFamily: 'var(--od-font-mono)',
|
|
527
|
+
fontSize: 11,
|
|
528
|
+
lineHeight: 1.5,
|
|
529
|
+
background: 'var(--od-rule)',
|
|
530
|
+
borderRadius: 'var(--od-radius)',
|
|
531
|
+
padding: '10px 12px',
|
|
532
|
+
margin: '0 0 14px',
|
|
533
|
+
whiteSpace: 'pre-wrap' as const,
|
|
534
|
+
overflowWrap: 'anywhere' as const,
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
const quote = {
|
|
538
|
+
margin: '0 0 14px',
|
|
539
|
+
padding: '2px 0 2px 14px',
|
|
540
|
+
borderLeft: '2px solid var(--od-accent)',
|
|
541
|
+
color: 'var(--od-muted)',
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
const table = {
|
|
545
|
+
width: '100%',
|
|
546
|
+
borderCollapse: 'collapse' as const,
|
|
547
|
+
tableLayout: 'fixed' as const,
|
|
548
|
+
margin: '0 0 16px',
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
const figure = { margin: '0 0 16px' };
|
|
552
|
+
const img = { width: '100%', display: 'block' as const };
|
|
553
|
+
const inlineImg = { maxWidth: '100%', verticalAlign: 'middle' as const };
|
|
554
|
+
const caption = { fontSize: 'var(--od-size-caption)', color: 'var(--od-muted)', margin: '6px 0 0' };
|
|
555
|
+
|
|
556
|
+
const Th = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
|
|
557
|
+
<th
|
|
558
|
+
style={{
|
|
559
|
+
textAlign: align,
|
|
560
|
+
fontFamily: 'var(--od-font-heading)',
|
|
561
|
+
fontSize: 11,
|
|
562
|
+
fontWeight: 600,
|
|
563
|
+
letterSpacing: '0.04em',
|
|
564
|
+
textTransform: 'uppercase',
|
|
565
|
+
color: 'var(--od-muted)',
|
|
566
|
+
borderBottom: '1px solid var(--od-rule)',
|
|
567
|
+
padding: '0 8px 6px',
|
|
568
|
+
}}
|
|
569
|
+
>
|
|
570
|
+
{children}
|
|
571
|
+
</th>
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
const Td = ({ children, align = 'left' }: { children?: ReactNode; align?: 'left' | 'center' | 'right' }) => (
|
|
575
|
+
<td
|
|
576
|
+
style={{
|
|
577
|
+
textAlign: align,
|
|
578
|
+
fontSize: 12,
|
|
579
|
+
padding: '7px 8px',
|
|
580
|
+
borderBottom: '1px solid var(--od-rule)',
|
|
581
|
+
fontVariantNumeric: align === 'right' ? 'tabular-nums' : undefined,
|
|
582
|
+
}}
|
|
583
|
+
>
|
|
584
|
+
{children}
|
|
585
|
+
</td>
|
|
586
|
+
);
|
|
587
|
+
|
|
588
|
+
const Footer = () => {
|
|
589
|
+
const n = useDocPageNumber();
|
|
590
|
+
const total = useDocPageCount();
|
|
591
|
+
return (
|
|
592
|
+
<div
|
|
593
|
+
style={{
|
|
594
|
+
position: 'absolute',
|
|
595
|
+
left: 'var(--od-margin)',
|
|
596
|
+
right: 'var(--od-margin)',
|
|
597
|
+
bottom: 40,
|
|
598
|
+
display: 'flex',
|
|
599
|
+
justifyContent: 'space-between',
|
|
600
|
+
fontSize: 'var(--od-size-caption)',
|
|
601
|
+
color: 'var(--od-muted)',
|
|
602
|
+
}}
|
|
603
|
+
>
|
|
604
|
+
<span>{DOC_TITLE}</span>
|
|
605
|
+
<span style={{ fontVariantNumeric: 'tabular-nums' }}>
|
|
606
|
+
{n} / {total}
|
|
607
|
+
</span>
|
|
608
|
+
</div>
|
|
609
|
+
);
|
|
610
|
+
};`;
|
|
611
|
+
const DESIGN = `export const design: DesignSystem = {
|
|
612
|
+
palette: {
|
|
613
|
+
bg: '#ffffff',
|
|
614
|
+
text: '#16181d',
|
|
615
|
+
muted: '#6b7280',
|
|
616
|
+
accent: '#2563eb',
|
|
617
|
+
rule: '#e5e7eb',
|
|
618
|
+
},
|
|
619
|
+
fonts: {
|
|
620
|
+
heading: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
|
|
621
|
+
body: '-apple-system, BlinkMacSystemFont, "Inter", system-ui, sans-serif',
|
|
622
|
+
mono: 'ui-monospace, "SF Mono", "JetBrains Mono", Menlo, monospace',
|
|
623
|
+
},
|
|
624
|
+
typeScale: { title: 44, h1: 28, h2: 20, h3: 16, body: 14, caption: 10 },
|
|
625
|
+
margin: 76,
|
|
626
|
+
leading: 1.55,
|
|
627
|
+
radius: 6,
|
|
628
|
+
};`;
|
|
629
|
+
/**
|
|
630
|
+
* Turns parsed markdown into a document module. The output is ordinary authored
|
|
631
|
+
* TSX — inline styles, real heading tags, plain JSX text — so the outline, the
|
|
632
|
+
* inspector, and the design panel all work on an imported document exactly as
|
|
633
|
+
* they do on a hand-written one.
|
|
634
|
+
*/
|
|
635
|
+
function generateDocumentSource(parsed, opts) {
|
|
636
|
+
const title = titleFrom(parsed, opts);
|
|
637
|
+
const subtitle = opts.subtitle ?? parsed.frontmatter.subtitle;
|
|
638
|
+
const author = opts.author ?? parsed.frontmatter.author;
|
|
639
|
+
const theme = opts.theme ?? parsed.frontmatter.theme;
|
|
640
|
+
const pageSize = opts.pageSize ?? parsed.frontmatter.pageSize;
|
|
641
|
+
const orientation = opts.orientation ?? parsed.frontmatter.orientation;
|
|
642
|
+
const cover = opts.cover !== false;
|
|
643
|
+
let blocks = parsed.blocks;
|
|
644
|
+
const first = blocks[0];
|
|
645
|
+
if (cover && first?.type === "heading" && first.level === 1 && inlineText(first.children) === title) blocks = blocks.slice(1);
|
|
646
|
+
const images = opts.images;
|
|
647
|
+
const imports = images ? [...images.values()] : [];
|
|
648
|
+
const head = [
|
|
649
|
+
`import type { ReactNode } from 'react';`,
|
|
650
|
+
`import {\n${[
|
|
651
|
+
"type DesignSystem",
|
|
652
|
+
"type DocEntry",
|
|
653
|
+
"type DocMeta",
|
|
654
|
+
...cover || opts.contents ? ["type DocPage"] : [],
|
|
655
|
+
...opts.contents ? ["TableOfContents"] : [],
|
|
656
|
+
"flow",
|
|
657
|
+
"useDocPageCount",
|
|
658
|
+
"useDocPageNumber"
|
|
659
|
+
].map((name) => ` ${name},`).join("\n")}\n} from '@open-document/core';`,
|
|
660
|
+
...imports.map((image) => `import ${image.ident} from './assets/${image.filename}';`)
|
|
661
|
+
].join("\n");
|
|
662
|
+
const styles = STYLES.replace("{DOC_TITLE}", jsxText(title));
|
|
663
|
+
const coverPage = cover ? `const Cover: DocPage = () => (
|
|
664
|
+
<div style={{ ...page, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
|
|
665
|
+
${subtitle ? ` <p style={{ fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--od-accent)', margin: 0 }}>
|
|
666
|
+
${jsxText(subtitle)}
|
|
667
|
+
</p>\n` : ""} <h1 style={{ ...h1, fontSize: 'var(--od-size-title)', margin: '16px 0 12px' }} data-od-outline="skip">
|
|
668
|
+
${jsxText(title)}
|
|
669
|
+
</h1>
|
|
670
|
+
${author ? ` <p style={{ color: 'var(--od-muted)', margin: 0 }}>${jsxText(author)}</p>\n` : ""} </div>
|
|
671
|
+
);` : "";
|
|
672
|
+
const contentsPage = opts.contents ? `const Contents: DocPage = () => (
|
|
673
|
+
<div style={page}>
|
|
674
|
+
<h1 style={h1} data-od-outline="skip">
|
|
675
|
+
Contents
|
|
676
|
+
</h1>
|
|
677
|
+
<TableOfContents maxLevel={2} />
|
|
678
|
+
</div>
|
|
679
|
+
);` : "";
|
|
680
|
+
const body = `const Body = flow(
|
|
681
|
+
<>
|
|
682
|
+
${blocks.map((block) => renderBlock(block, images, " ")).join("\n")}
|
|
683
|
+
</>,
|
|
684
|
+
{ footer: Footer },
|
|
685
|
+
);`;
|
|
686
|
+
const metaFields = [
|
|
687
|
+
` title: ${jsString(title)},`,
|
|
688
|
+
...subtitle ? [` subtitle: ${jsString(subtitle)},`] : [],
|
|
689
|
+
...author ? [` author: ${jsString(author)},`] : [],
|
|
690
|
+
...pageSize ? [` pageSize: ${jsString(pageSize)},`] : [],
|
|
691
|
+
...orientation ? [` orientation: ${jsString(orientation)},`] : [],
|
|
692
|
+
...theme ? [` theme: ${jsString(theme)},`] : [],
|
|
693
|
+
` createdAt: ${jsString(opts.createdAt)},`
|
|
694
|
+
];
|
|
695
|
+
const entries = [
|
|
696
|
+
...cover ? ["Cover"] : [],
|
|
697
|
+
...opts.contents ? ["Contents"] : [],
|
|
698
|
+
"Body"
|
|
699
|
+
];
|
|
700
|
+
return {
|
|
701
|
+
source: [
|
|
702
|
+
head,
|
|
703
|
+
"",
|
|
704
|
+
DESIGN,
|
|
705
|
+
"",
|
|
706
|
+
styles,
|
|
707
|
+
"",
|
|
708
|
+
...coverPage ? [coverPage, ""] : [],
|
|
709
|
+
...contentsPage ? [contentsPage, ""] : [],
|
|
710
|
+
body,
|
|
711
|
+
"",
|
|
712
|
+
`export const meta: DocMeta = {\n${metaFields.join("\n")}\n};`,
|
|
713
|
+
`export default [${entries.join(", ")}] satisfies DocEntry[];`,
|
|
714
|
+
""
|
|
715
|
+
].join("\n"),
|
|
716
|
+
title,
|
|
717
|
+
blockCount: blocks.length
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
//#endregion
|
|
721
|
+
//#region src/ops/import.ts
|
|
722
|
+
const REMOTE_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
|
|
723
|
+
function slugify(value, fallback = "document") {
|
|
724
|
+
const slug = value.normalize("NFKD").toLowerCase().replace(/['"]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
725
|
+
return DOC_ID_RE.test(slug) ? slug : fallback;
|
|
726
|
+
}
|
|
727
|
+
function uniqueId(base, taken) {
|
|
728
|
+
if (!taken.has(base)) return base;
|
|
729
|
+
for (let n = 2; n < 1e3; n++) {
|
|
730
|
+
const candidate = `${base}-${n}`;
|
|
731
|
+
if (!taken.has(candidate)) return candidate;
|
|
732
|
+
}
|
|
733
|
+
throw new OpsError(409, `could not find a free id for ${base}`);
|
|
734
|
+
}
|
|
735
|
+
function identFor(index) {
|
|
736
|
+
return `figure${index + 1}`;
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Reads markdown and writes a real open-doc document: `flow()` body, inline
|
|
740
|
+
* styles, a cover, and any local images copied into the document's own assets
|
|
741
|
+
* folder. Nothing about the result is special-cased — it is the same shape an
|
|
742
|
+
* agent would have written by hand, and every editing surface works on it.
|
|
743
|
+
*/
|
|
744
|
+
async function importMarkdown(ctx, opts) {
|
|
745
|
+
const sourceFile = opts.file ? path.resolve(ctx.userCwd, opts.file) : null;
|
|
746
|
+
if (sourceFile && !sourceFile.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `file must sit inside the workspace: ${opts.file}`);
|
|
747
|
+
let markdown = opts.markdown;
|
|
748
|
+
if (markdown === void 0) {
|
|
749
|
+
if (!sourceFile) throw new OpsError(400, "pass either `markdown` or `file`");
|
|
750
|
+
try {
|
|
751
|
+
markdown = await fs.readFile(sourceFile, "utf8");
|
|
752
|
+
} catch {
|
|
753
|
+
throw new OpsError(404, `file not found: ${opts.file}`);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
if (markdown.trim() === "") throw new OpsError(422, "the markdown is empty");
|
|
757
|
+
const parsed = parseMarkdown(markdown);
|
|
758
|
+
const fallbackName = sourceFile ? path.basename(sourceFile).replace(/\.mdx?$/i, "") : "document";
|
|
759
|
+
const requestedId = opts.docId ?? slugify(opts.title ?? parsed.frontmatter.title ?? fallbackName);
|
|
760
|
+
if (opts.docId && !DOC_ID_RE.test(opts.docId)) throw new OpsError(400, `invalid document id: ${opts.docId}`);
|
|
761
|
+
const docId = opts.docId ?? uniqueId(requestedId, new Set(await listDocIds(ctx)));
|
|
762
|
+
const baseDir = sourceFile ? path.dirname(sourceFile) : ctx.userCwd;
|
|
763
|
+
const images = /* @__PURE__ */ new Map();
|
|
764
|
+
const missing = [];
|
|
765
|
+
const staged = [];
|
|
766
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
767
|
+
for (const src of new Set(collectImageSources(parsed.blocks))) {
|
|
768
|
+
if (REMOTE_RE.test(src)) continue;
|
|
769
|
+
const from = path.resolve(baseDir, src.split(/[?#]/)[0]);
|
|
770
|
+
if (!from.startsWith(ctx.userCwd + path.sep) || !existsSync(from)) {
|
|
771
|
+
missing.push(src);
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
const safe = validateAssetName(path.basename(from));
|
|
775
|
+
if (!safe) {
|
|
776
|
+
missing.push(src);
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
const filename = usedNames.has(safe) ? `${images.size + 1}-${safe}` : safe;
|
|
780
|
+
usedNames.add(filename);
|
|
781
|
+
images.set(src, {
|
|
782
|
+
source: src,
|
|
783
|
+
ident: identFor(images.size),
|
|
784
|
+
filename
|
|
785
|
+
});
|
|
786
|
+
staged.push({
|
|
787
|
+
from,
|
|
788
|
+
filename
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
const generated = generateDocumentSource(parsed, {
|
|
792
|
+
docId,
|
|
793
|
+
...opts.title !== void 0 ? { title: opts.title } : {},
|
|
794
|
+
...opts.subtitle !== void 0 ? { subtitle: opts.subtitle } : {},
|
|
795
|
+
...opts.author !== void 0 ? { author: opts.author } : {},
|
|
796
|
+
...opts.theme !== void 0 ? { theme: opts.theme } : {},
|
|
797
|
+
...opts.pageSize !== void 0 ? { pageSize: opts.pageSize } : {},
|
|
798
|
+
...opts.orientation !== void 0 ? { orientation: opts.orientation } : {},
|
|
799
|
+
...opts.cover !== void 0 ? { cover: opts.cover } : {},
|
|
800
|
+
...opts.contents !== void 0 ? { contents: opts.contents } : {},
|
|
801
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
802
|
+
images
|
|
803
|
+
});
|
|
804
|
+
const created = await createDocument(ctx, docId, generated.source);
|
|
805
|
+
if (staged.length > 0) {
|
|
806
|
+
const assetsDir = path.join(ctx.docsRoot, docId, "assets");
|
|
807
|
+
await fs.mkdir(assetsDir, { recursive: true });
|
|
808
|
+
for (const { from, filename } of staged) await fs.copyFile(from, path.join(assetsDir, filename));
|
|
809
|
+
}
|
|
810
|
+
return {
|
|
811
|
+
id: created.id,
|
|
812
|
+
entry: created.entry,
|
|
813
|
+
title: generated.title,
|
|
814
|
+
blocks: generated.blockCount,
|
|
815
|
+
assets: staged.map((asset) => asset.filename),
|
|
816
|
+
missingAssets: missing
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
//#endregion
|
|
820
|
+
//#region src/render/session.ts
|
|
821
|
+
var RenderUnavailableError = class extends Error {
|
|
822
|
+
constructor(message) {
|
|
823
|
+
super(message);
|
|
824
|
+
this.name = "RenderUnavailableError";
|
|
825
|
+
}
|
|
826
|
+
};
|
|
827
|
+
const INSTALL_HINT = "Headless rendering needs Playwright. Install it in this workspace:\n pnpm add -D playwright && pnpm exec playwright install chromium";
|
|
828
|
+
async function loadPlaywright() {
|
|
829
|
+
try {
|
|
830
|
+
return await import("playwright");
|
|
831
|
+
} catch {
|
|
832
|
+
throw new RenderUnavailableError(INSTALL_HINT);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
const DEFAULT_TIMEOUT = 6e4;
|
|
836
|
+
const PRINT_PAGE_SELECTOR = "#od-print-root .od-print-page";
|
|
837
|
+
async function bootServer(userCwd) {
|
|
838
|
+
const base = await createViteConfig({
|
|
839
|
+
userCwd,
|
|
840
|
+
headless: true
|
|
841
|
+
});
|
|
842
|
+
const config = mergeConfig(base, {
|
|
843
|
+
logLevel: "silent",
|
|
844
|
+
server: {
|
|
845
|
+
port: 0,
|
|
846
|
+
strictPort: false,
|
|
847
|
+
open: false
|
|
848
|
+
}
|
|
849
|
+
});
|
|
850
|
+
const server = await createServer(config);
|
|
851
|
+
await server.listen();
|
|
852
|
+
const origin = server.resolvedUrls?.local?.[0]?.replace(/\/$/, "");
|
|
853
|
+
if (!origin) {
|
|
854
|
+
await server.close();
|
|
855
|
+
throw new Error("Could not determine the dev server URL");
|
|
856
|
+
}
|
|
857
|
+
return {
|
|
858
|
+
server,
|
|
859
|
+
origin
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
async function createRenderSession(opts) {
|
|
863
|
+
const { chromium } = await loadPlaywright();
|
|
864
|
+
const timeout = opts.timeoutMs ?? DEFAULT_TIMEOUT;
|
|
865
|
+
let server = null;
|
|
866
|
+
let origin = opts.origin?.replace(/\/$/, "") ?? "";
|
|
867
|
+
if (!origin) {
|
|
868
|
+
const booted = await bootServer(opts.userCwd);
|
|
869
|
+
server = booted.server;
|
|
870
|
+
origin = booted.origin;
|
|
871
|
+
}
|
|
872
|
+
let browser;
|
|
873
|
+
try {
|
|
874
|
+
browser = await chromium.launch({ headless: true });
|
|
875
|
+
} catch (err) {
|
|
876
|
+
await server?.close();
|
|
877
|
+
throw new RenderUnavailableError(`${INSTALL_HINT}\n\nChromium failed to launch: ${err.message}`);
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
origin,
|
|
881
|
+
async open(docId) {
|
|
882
|
+
const page = await browser.newPage({
|
|
883
|
+
viewport: {
|
|
884
|
+
width: 1280,
|
|
885
|
+
height: 1024
|
|
886
|
+
},
|
|
887
|
+
...opts.deviceScaleFactor !== void 0 ? { deviceScaleFactor: opts.deviceScaleFactor } : {}
|
|
888
|
+
});
|
|
889
|
+
const errors = [];
|
|
890
|
+
page.on("pageerror", (err) => errors.push(String(err?.message ?? err)));
|
|
891
|
+
await page.goto(`${origin}/d/${encodeURIComponent(docId)}`, {
|
|
892
|
+
waitUntil: "load",
|
|
893
|
+
timeout
|
|
894
|
+
});
|
|
895
|
+
try {
|
|
896
|
+
await page.waitForFunction("globalThis.__openDoc ? globalThis.__openDoc.status().ready : false", void 0, { timeout });
|
|
897
|
+
} catch {
|
|
898
|
+
await page.close();
|
|
899
|
+
const detail = errors.length ? `\n${errors.join("\n")}` : "";
|
|
900
|
+
throw new Error(`Document "${docId}" never finished rendering.${detail}`);
|
|
901
|
+
}
|
|
902
|
+
const status = await page.evaluate("globalThis.__openDoc.status()");
|
|
903
|
+
return {
|
|
904
|
+
status,
|
|
905
|
+
diagnose: () => page.evaluate("globalThis.__openDoc.diagnose()"),
|
|
906
|
+
async pdf() {
|
|
907
|
+
await page.evaluate("globalThis.__openDoc.preparePrint()");
|
|
908
|
+
try {
|
|
909
|
+
return await page.pdf({
|
|
910
|
+
printBackground: true,
|
|
911
|
+
preferCSSPageSize: true
|
|
912
|
+
});
|
|
913
|
+
} finally {
|
|
914
|
+
await page.evaluate("globalThis.__openDoc.releasePrint()");
|
|
915
|
+
}
|
|
916
|
+
},
|
|
917
|
+
async screenshot(pageNumber) {
|
|
918
|
+
if (pageNumber < 1 || pageNumber > status.pageCount) throw new Error(`page ${pageNumber} is out of range — "${docId}" has ${status.pageCount}`);
|
|
919
|
+
await page.evaluate("globalThis.__openDoc.preparePrint()");
|
|
920
|
+
await page.emulateMedia({ media: "print" });
|
|
921
|
+
try {
|
|
922
|
+
const sheet = await page.$(`${PRINT_PAGE_SELECTOR}:nth-child(${pageNumber})`);
|
|
923
|
+
if (!sheet) throw new Error(`page ${pageNumber} did not render`);
|
|
924
|
+
return await sheet.screenshot({ type: "png" });
|
|
925
|
+
} finally {
|
|
926
|
+
await page.emulateMedia({ media: null });
|
|
927
|
+
await page.evaluate("globalThis.__openDoc.releasePrint()");
|
|
928
|
+
}
|
|
929
|
+
},
|
|
930
|
+
html: () => page.evaluate("globalThis.__openDoc.htmlBundle()"),
|
|
931
|
+
close: () => page.close()
|
|
932
|
+
};
|
|
933
|
+
},
|
|
934
|
+
async close() {
|
|
935
|
+
await browser.close();
|
|
936
|
+
await server?.close();
|
|
937
|
+
}
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
//#endregion
|
|
941
|
+
//#region src/ops/layout.ts
|
|
942
|
+
/**
|
|
943
|
+
* Chromium and a Vite server are expensive to start, and an agent checking its
|
|
944
|
+
* work calls these back to back. One session is kept warm and closed once
|
|
945
|
+
* nobody has asked for a while.
|
|
946
|
+
*/
|
|
947
|
+
const IDLE_MS = 12e4;
|
|
948
|
+
let shared = null;
|
|
949
|
+
let pending = null;
|
|
950
|
+
let idleTimer = null;
|
|
951
|
+
let leases = 0;
|
|
952
|
+
function armIdleClose() {
|
|
953
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
954
|
+
idleTimer = setTimeout(() => {
|
|
955
|
+
if (leases > 0) return;
|
|
956
|
+
const current = shared;
|
|
957
|
+
shared = null;
|
|
958
|
+
idleTimer = null;
|
|
959
|
+
current?.session.close().catch(() => {});
|
|
960
|
+
}, IDLE_MS);
|
|
961
|
+
idleTimer.unref?.();
|
|
962
|
+
}
|
|
963
|
+
async function acquire(ctx) {
|
|
964
|
+
if (shared && shared.origin === ctx.serverOrigin) return shared.session;
|
|
965
|
+
if (!pending) {
|
|
966
|
+
const origin = ctx.serverOrigin;
|
|
967
|
+
pending = createRenderSession({
|
|
968
|
+
userCwd: ctx.userCwd,
|
|
969
|
+
origin,
|
|
970
|
+
deviceScaleFactor: 2
|
|
971
|
+
}).then((session) => {
|
|
972
|
+
shared = {
|
|
973
|
+
session,
|
|
974
|
+
origin
|
|
975
|
+
};
|
|
976
|
+
return session;
|
|
977
|
+
}).finally(() => {
|
|
978
|
+
pending = null;
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
return pending;
|
|
982
|
+
}
|
|
983
|
+
async function withDoc(ctx, docId, fn) {
|
|
984
|
+
if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
|
|
985
|
+
let session;
|
|
986
|
+
try {
|
|
987
|
+
session = await acquire(ctx);
|
|
988
|
+
} catch (err) {
|
|
989
|
+
if (err instanceof RenderUnavailableError) throw new OpsError(501, err.message);
|
|
990
|
+
throw new OpsError(500, err.message);
|
|
991
|
+
}
|
|
992
|
+
leases++;
|
|
993
|
+
let renderer = null;
|
|
994
|
+
try {
|
|
995
|
+
renderer = await session.open(docId);
|
|
996
|
+
return await fn(renderer);
|
|
997
|
+
} catch (err) {
|
|
998
|
+
if (err instanceof OpsError) throw err;
|
|
999
|
+
throw new OpsError(422, err.message);
|
|
1000
|
+
} finally {
|
|
1001
|
+
await renderer?.close().catch(() => {});
|
|
1002
|
+
leases--;
|
|
1003
|
+
armIdleClose();
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
/** Closes the warm browser. Call before the process exits so nothing lingers. */
|
|
1007
|
+
async function closeRenderSession() {
|
|
1008
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1009
|
+
idleTimer = null;
|
|
1010
|
+
const current = shared;
|
|
1011
|
+
shared = null;
|
|
1012
|
+
await current?.session.close().catch(() => {});
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Renders the document headlessly at true page size and reports what is wrong
|
|
1016
|
+
* with the layout — the part of a document an agent writing React cannot see.
|
|
1017
|
+
*/
|
|
1018
|
+
async function checkLayout(ctx, docId) {
|
|
1019
|
+
return withDoc(ctx, docId, async (renderer) => {
|
|
1020
|
+
const report = await renderer.diagnose();
|
|
1021
|
+
return {
|
|
1022
|
+
docId: report.docId || docId,
|
|
1023
|
+
title: report.title,
|
|
1024
|
+
pageCount: report.pageCount,
|
|
1025
|
+
errors: report.findings.filter((f) => f.severity === "error").length,
|
|
1026
|
+
warnings: report.findings.filter((f) => f.severity === "warn").length,
|
|
1027
|
+
findings: report.findings
|
|
1028
|
+
};
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
async function renderDocPage(ctx, docId, page) {
|
|
1032
|
+
return withDoc(ctx, docId, async (renderer) => {
|
|
1033
|
+
const bytes = await renderer.screenshot(page);
|
|
1034
|
+
return {
|
|
1035
|
+
docId,
|
|
1036
|
+
page,
|
|
1037
|
+
pageCount: renderer.status.pageCount,
|
|
1038
|
+
mimeType: "image/png",
|
|
1039
|
+
base64: Buffer.from(bytes).toString("base64")
|
|
1040
|
+
};
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
function resolveOutDir(ctx, outDir) {
|
|
1044
|
+
const resolved = path.resolve(ctx.userCwd, outDir);
|
|
1045
|
+
if (resolved !== ctx.userCwd && !resolved.startsWith(ctx.userCwd + path.sep)) throw new OpsError(400, `outDir must stay inside the workspace: ${outDir}`);
|
|
1046
|
+
return resolved;
|
|
1047
|
+
}
|
|
1048
|
+
async function exportDocument(ctx, docId, opts = {}) {
|
|
1049
|
+
const format = opts.format ?? "pdf";
|
|
1050
|
+
const dir = resolveOutDir(ctx, opts.outDir ?? "out");
|
|
1051
|
+
return withDoc(ctx, docId, async (renderer) => {
|
|
1052
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1053
|
+
const written = [];
|
|
1054
|
+
const write = async (name, bytes) => {
|
|
1055
|
+
const file = path.join(dir, name);
|
|
1056
|
+
await fs.writeFile(file, bytes);
|
|
1057
|
+
written.push(path.relative(ctx.userCwd, file));
|
|
1058
|
+
};
|
|
1059
|
+
if (format === "pdf") await write(`${docId}.pdf`, await renderer.pdf());
|
|
1060
|
+
else if (format === "html") {
|
|
1061
|
+
const bundle = await renderer.html();
|
|
1062
|
+
if (!bundle) throw new OpsError(422, `document has no pages: ${docId}`);
|
|
1063
|
+
await write(bundle.filename, Buffer.from(bundle.base64, "base64"));
|
|
1064
|
+
} else {
|
|
1065
|
+
const width = String(renderer.status.pageCount).length;
|
|
1066
|
+
for (let page = 1; page <= renderer.status.pageCount; page++) await write(`${docId}-${String(page).padStart(width, "0")}.png`, await renderer.screenshot(page));
|
|
1067
|
+
}
|
|
1068
|
+
return {
|
|
1069
|
+
docId,
|
|
1070
|
+
format,
|
|
1071
|
+
pageCount: renderer.status.pageCount,
|
|
1072
|
+
files: written
|
|
1073
|
+
};
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
//#endregion
|
|
1077
|
+
//#region src/ops/library.ts
|
|
1078
|
+
function themesRoot(ctx, themesDir = "themes") {
|
|
1079
|
+
return path.resolve(ctx.userCwd, themesDir);
|
|
1080
|
+
}
|
|
1081
|
+
async function themeFiles(root) {
|
|
1082
|
+
if (!existsSync(root)) return [];
|
|
1083
|
+
return (await fg("*.md", {
|
|
1084
|
+
cwd: root,
|
|
1085
|
+
absolute: true,
|
|
1086
|
+
onlyFiles: true
|
|
1087
|
+
})).sort();
|
|
1088
|
+
}
|
|
1089
|
+
function demoFor(root, id) {
|
|
1090
|
+
for (const cand of [
|
|
1091
|
+
`${id}.demo.tsx`,
|
|
1092
|
+
`${id}.demo.jsx`,
|
|
1093
|
+
`${id}.demo.ts`,
|
|
1094
|
+
`${id}.demo.js`
|
|
1095
|
+
]) {
|
|
1096
|
+
const p = path.join(root, cand);
|
|
1097
|
+
if (existsSync(p)) return p;
|
|
1098
|
+
}
|
|
1099
|
+
return null;
|
|
1100
|
+
}
|
|
1101
|
+
async function listThemes(ctx, themesDir) {
|
|
1102
|
+
const root = themesRoot(ctx, themesDir);
|
|
1103
|
+
const out = [];
|
|
1104
|
+
for (const file of await themeFiles(root)) {
|
|
1105
|
+
const id = path.basename(file, ".md");
|
|
1106
|
+
const { fm } = parseFrontmatter$1(await fs.readFile(file, "utf8"), id);
|
|
1107
|
+
out.push({
|
|
1108
|
+
id,
|
|
1109
|
+
name: fm.name,
|
|
1110
|
+
description: fm.description,
|
|
1111
|
+
pageSize: fm.pageSize,
|
|
1112
|
+
mode: fm.mode,
|
|
1113
|
+
hasDemo: demoFor(root, id) !== null
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
return out;
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* The full theme document. This is what an agent reads before writing a doc —
|
|
1120
|
+
* the palette, type scale, and paste-ready components live in the body.
|
|
1121
|
+
*/
|
|
1122
|
+
async function readTheme(ctx, themeId, themesDir) {
|
|
1123
|
+
const root = themesRoot(ctx, themesDir);
|
|
1124
|
+
const file = path.join(root, `${themeId}.md`);
|
|
1125
|
+
if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
|
|
1126
|
+
const { fm, body } = parseFrontmatter$1(await fs.readFile(file, "utf8"), themeId);
|
|
1127
|
+
const demoAbs = demoFor(root, themeId);
|
|
1128
|
+
return {
|
|
1129
|
+
id: themeId,
|
|
1130
|
+
frontmatter: fm,
|
|
1131
|
+
body,
|
|
1132
|
+
demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
/** `scope` is a document id, or `global` for the shared assets directory. */
|
|
1136
|
+
async function listAssets(ctx, scope) {
|
|
1137
|
+
const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
1138
|
+
if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
|
|
1139
|
+
if (!existsSync(dir)) return [];
|
|
1140
|
+
const names = await fs.readdir(dir);
|
|
1141
|
+
const out = [];
|
|
1142
|
+
for (const filename of names.sort()) {
|
|
1143
|
+
const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
|
|
1144
|
+
if (!stat?.isFile()) continue;
|
|
1145
|
+
out.push({
|
|
1146
|
+
scope,
|
|
1147
|
+
filename,
|
|
1148
|
+
bytes: stat.size,
|
|
1149
|
+
importPath: assetImportPath(scope, filename)
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
return out;
|
|
1153
|
+
}
|
|
1154
|
+
async function writeAsset(ctx, scope, filename, data) {
|
|
1155
|
+
const name = validateAssetName(filename);
|
|
1156
|
+
if (!name) throw new OpsError(400, "invalid filename");
|
|
1157
|
+
const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
1158
|
+
if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
|
|
1159
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1160
|
+
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
|
|
1161
|
+
if (!file) throw new OpsError(400, "invalid filename");
|
|
1162
|
+
await fs.writeFile(file, data);
|
|
1163
|
+
return {
|
|
1164
|
+
scope,
|
|
1165
|
+
filename: name,
|
|
1166
|
+
bytes: data.byteLength,
|
|
1167
|
+
importPath: assetImportPath(scope, name)
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
async function deleteAsset(ctx, scope, filename) {
|
|
1171
|
+
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
|
|
1172
|
+
if (!file) throw new OpsError(400, "invalid filename");
|
|
1173
|
+
if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
|
|
1174
|
+
await fs.rm(file);
|
|
1175
|
+
}
|
|
1176
|
+
/** Which documents import this asset — check before deleting one. */
|
|
1177
|
+
async function findAssetUsages(ctx, scope, filename) {
|
|
1178
|
+
const importPath = assetImportPath(scope, filename);
|
|
1179
|
+
const out = [];
|
|
1180
|
+
for (const id of await listDocIds(ctx)) {
|
|
1181
|
+
const entry = resolveEntry(ctx, id);
|
|
1182
|
+
if (!entry) continue;
|
|
1183
|
+
const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
|
|
1184
|
+
if (count > 0) out.push({
|
|
1185
|
+
docId: id,
|
|
1186
|
+
count
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1189
|
+
return out;
|
|
1190
|
+
}
|
|
1191
|
+
async function listFolders(ctx) {
|
|
1192
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1193
|
+
return {
|
|
1194
|
+
folders: manifest.folders,
|
|
1195
|
+
assignments: manifest.assignments
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
/** Folders always carry an icon; agents rarely care, so this is the fallback. */
|
|
1199
|
+
const DEFAULT_FOLDER_ICON = {
|
|
1200
|
+
type: "color",
|
|
1201
|
+
value: "#6b7280"
|
|
1202
|
+
};
|
|
1203
|
+
async function createFolder(ctx, rawName, rawIcon) {
|
|
1204
|
+
const name = validateName(rawName);
|
|
1205
|
+
if (!name) throw new OpsError(400, "invalid folder name");
|
|
1206
|
+
const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
|
|
1207
|
+
if (!icon) throw new OpsError(400, "invalid icon");
|
|
1208
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1209
|
+
const folder = {
|
|
1210
|
+
id: newFolderId(),
|
|
1211
|
+
name,
|
|
1212
|
+
icon
|
|
1213
|
+
};
|
|
1214
|
+
manifest.folders.push(folder);
|
|
1215
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1216
|
+
return folder;
|
|
1217
|
+
}
|
|
1218
|
+
/** Filing only edits assignments — a document id never moves on disk. */
|
|
1219
|
+
async function fileDocument(ctx, docId, folderId) {
|
|
1220
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1221
|
+
if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
|
|
1222
|
+
if (folderId === null) delete manifest.assignments[docId];
|
|
1223
|
+
else manifest.assignments[docId] = folderId;
|
|
1224
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1225
|
+
}
|
|
1226
|
+
//#endregion
|
|
1227
|
+
//#region src/ops/text.ts
|
|
1228
|
+
async function sourceOf(ctx, docId) {
|
|
1229
|
+
const entry = resolveEntry(ctx, docId);
|
|
1230
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1231
|
+
return {
|
|
1232
|
+
entry,
|
|
1233
|
+
source: await fs.readFile(entry, "utf8")
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Resolves a `line:column` (or several candidates) to the editable text runs at
|
|
1238
|
+
* that spot. `shown` is the rendered text — when a clicked element belongs to a
|
|
1239
|
+
* local helper component, it is what decides which candidate was really meant.
|
|
1240
|
+
*/
|
|
1241
|
+
async function readText(ctx, docId, locs, shown) {
|
|
1242
|
+
if (locs.length === 0) throw new OpsError(400, "at least one loc is required");
|
|
1243
|
+
const { source } = await sourceOf(ctx, docId);
|
|
1244
|
+
const resolved = resolveTextTarget(source, locs, shown);
|
|
1245
|
+
if (!resolved) throw new OpsError(404, "no editable text at that location");
|
|
1246
|
+
return resolved;
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* `expected` is the text the caller believes is there; when it no longer
|
|
1250
|
+
* matches the write is refused rather than silently overwriting someone else's
|
|
1251
|
+
* edit. `index` picks a run when the element mixes text and markup.
|
|
1252
|
+
*/
|
|
1253
|
+
async function writeText(ctx, docId, loc, text, opts = {}) {
|
|
1254
|
+
const { entry, source } = await sourceOf(ctx, docId);
|
|
1255
|
+
const result = replaceTextAt(source, loc, text, opts);
|
|
1256
|
+
if (!result.ok) throw new OpsError(result.status, result.error);
|
|
1257
|
+
if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
|
|
1258
|
+
return { ok: true };
|
|
1259
|
+
}
|
|
1260
|
+
/** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
|
|
1261
|
+
async function addComment(ctx, docId, loc, note, hint) {
|
|
1262
|
+
if (note.trim() === "") throw new OpsError(400, "note is empty");
|
|
1263
|
+
const { entry, source } = await sourceOf(ctx, docId);
|
|
1264
|
+
const inserted = insertMarker(source, loc, note.trim(), hint);
|
|
1265
|
+
if (!inserted) throw new OpsError(422, "cannot anchor a comment here — pick the surrounding element");
|
|
1266
|
+
await fs.writeFile(entry, inserted.source, "utf8");
|
|
1267
|
+
return { id: inserted.id };
|
|
1268
|
+
}
|
|
1269
|
+
//#endregion
|
|
1270
|
+
export { importMarkdown as _, deleteAsset as a, listAssets as c, readTheme as d, writeAsset as f, renderDocPage as g, exportDocument as h, createFolder as i, listFolders as l, closeRenderSession as m, readText as n, fileDocument as o, checkLayout as p, writeText as r, findAssetUsages as s, addComment as t, listThemes as u, slugify as v };
|