@open-document/core 0.2.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.
Files changed (46) hide show
  1. package/dist/{build-U81g9Hnk.js → build-C3pMGxJN.js} +1 -1
  2. package/dist/check-Dtwb1wvU.js +42 -0
  3. package/dist/cli/bin.js +24 -3
  4. package/dist/config-Dg1AMP0r.js +2461 -0
  5. package/dist/context-FoX0afRf.js +26 -0
  6. package/dist/{dev-DwwFT6uX.js → dev-Cdd7NZRQ.js} +1 -1
  7. package/dist/diagram-xlVDekYk.js +763 -0
  8. package/dist/export-ClJ4T1uU.js +36 -0
  9. package/dist/import-D7Psi8WK.js +25 -0
  10. package/dist/index.d.ts +235 -90
  11. package/dist/index.js +515 -49
  12. package/dist/ops/index.d.ts +96 -1
  13. package/dist/ops/index.js +3 -199
  14. package/dist/ops-Ci5Xw6QG.js +1270 -0
  15. package/dist/{preview-C_jbySle.js → preview-BhbCiAKC.js} +1 -1
  16. package/dist/sdk-CWMsH9Ms.d.ts +123 -0
  17. package/dist/vite/index.d.ts +6 -0
  18. package/dist/vite/index.js +1 -2
  19. package/env.d.ts +33 -1
  20. package/package.json +10 -1
  21. package/skills/create-doc/SKILL.md +6 -2
  22. package/skills/doc-authoring/SKILL.md +79 -0
  23. package/skills/doc-authoring/references/long-form.md +131 -0
  24. package/src/app/components/data-table.tsx +196 -0
  25. package/src/app/components/diagram.tsx +76 -0
  26. package/src/app/components/flow-page.tsx +20 -3
  27. package/src/app/components/footnote.tsx +196 -0
  28. package/src/app/components/numbering.tsx +208 -0
  29. package/src/app/lib/agent-bridge.ts +128 -0
  30. package/src/app/lib/diagnostics.ts +282 -0
  31. package/src/app/lib/export-html.ts +35 -11
  32. package/src/app/lib/export-pdf.ts +54 -19
  33. package/src/app/lib/flow-measure.ts +100 -31
  34. package/src/app/lib/flow.test.ts +46 -0
  35. package/src/app/lib/flow.ts +28 -3
  36. package/src/app/lib/footnotes.test.tsx +102 -0
  37. package/src/app/lib/footnotes.ts +94 -0
  38. package/src/app/lib/labels.ts +175 -0
  39. package/src/app/lib/page-context.tsx +6 -1
  40. package/src/app/lib/scan.ts +26 -0
  41. package/src/app/lib/sdk.ts +3 -0
  42. package/src/app/lib/use-doc-pages.ts +50 -15
  43. package/src/app/routes/doc.tsx +7 -4
  44. package/dist/config-8zkUElGq.js +0 -1169
  45. package/dist/design-IyRSwCtK.js +0 -52
  46. package/dist/edit-ops-D2W2plpc.js +0 -1190
@@ -1,1190 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { existsSync } from "node:fs";
4
- import fg from "fast-glob";
5
- import { loadConfigFromFile, normalizePath } from "vite";
6
- import { parse } from "@babel/parser";
7
- import { randomUUID } from "node:crypto";
8
- //#region src/vite/open-doc-plugin.ts
9
- const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
10
- const CONFIG_FILE = "open-doc.config.ts";
11
- const DOCS_VMOD = "virtual:open-doc/docs";
12
- const CONFIG_VMOD = "virtual:open-doc/config";
13
- const FOLDERS_VMOD = "virtual:open-doc/folders";
14
- async function readFoldersManifest(file) {
15
- try {
16
- const parsed = JSON.parse(await fs.readFile(file, "utf8"));
17
- return {
18
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
19
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
20
- };
21
- } catch (err) {
22
- if (err.code === "ENOENT") return {
23
- folders: [],
24
- assignments: {}
25
- };
26
- throw err;
27
- }
28
- }
29
- function resolved$1(id) {
30
- return `\0${id}`;
31
- }
32
- async function findDocs(userCwd, docsDir) {
33
- const abs = path.resolve(userCwd, docsDir);
34
- if (!existsSync(abs)) return [];
35
- return (await fg("*/index.{tsx,jsx,ts,js}", {
36
- cwd: abs,
37
- absolute: true,
38
- onlyFiles: true
39
- })).sort();
40
- }
41
- function toId(absFile, docsRoot) {
42
- return path.relative(docsRoot, absFile).split(path.sep)[0];
43
- }
44
- const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
45
- const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
46
- /**
47
- * Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
48
- * every discovery pass, and the two fields it needs (sort order, theme back-link)
49
- * are contractually string literals.
50
- */
51
- function extractMeta(src) {
52
- const empty = {
53
- theme: null,
54
- createdAt: null
55
- };
56
- const metaStart = src.search(/export\s+const\s+meta\b/);
57
- if (metaStart === -1) return empty;
58
- const openBrace = src.indexOf("{", src.indexOf("=", metaStart));
59
- if (openBrace === -1) return empty;
60
- let depth = 0;
61
- let closeBrace = -1;
62
- for (let i = openBrace; i < src.length; i++) {
63
- const ch = src[i];
64
- if (ch === "{") depth++;
65
- else if (ch === "}") {
66
- depth--;
67
- if (depth === 0) {
68
- closeBrace = i;
69
- break;
70
- }
71
- }
72
- }
73
- if (closeBrace === -1) return empty;
74
- const body = src.slice(openBrace + 1, closeBrace);
75
- return {
76
- theme: body.match(META_THEME_RE)?.[1] ?? null,
77
- createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null
78
- };
79
- }
80
- function parseCreatedAtMs(iso) {
81
- if (!iso) return null;
82
- const ms = Date.parse(iso);
83
- return Number.isFinite(ms) ? ms : null;
84
- }
85
- async function readMeta(abs) {
86
- try {
87
- return extractMeta(await fs.readFile(abs, "utf8"));
88
- } catch {
89
- return {
90
- theme: null,
91
- createdAt: null
92
- };
93
- }
94
- }
95
- const warnedInvalidDocIds = /* @__PURE__ */ new Set();
96
- async function generateDocsModule(files, docsRoot, isDev) {
97
- const scanned = await Promise.all(files.map(async (abs) => {
98
- const meta = await readMeta(abs);
99
- return {
100
- id: toId(abs, docsRoot),
101
- importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
102
- theme: meta.theme,
103
- createdAt: parseCreatedAtMs(meta.createdAt)
104
- };
105
- }));
106
- const entries = scanned.filter((e) => DOC_ID_RE.test(e.id));
107
- const ignored = scanned.filter((e) => !DOC_ID_RE.test(e.id)).map((e) => e.id);
108
- const ids = JSON.stringify(entries.map((e) => e.id).sort());
109
- const createdAtMap = {};
110
- const themesMap = {};
111
- for (const e of entries) {
112
- if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
113
- if (e.theme) themesMap[e.id] = e.theme;
114
- }
115
- const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
116
- const devRuntime = isDev ? `
117
- const docImportTokens = ${importTokens};
118
- if (import.meta.hot) {
119
- import.meta.hot.on('open-doc:doc-changed', (data) => {
120
- const ids = Array.isArray(data?.docIds) ? data.docIds : data?.docId ? [data.docId] : [];
121
- const token = Date.now();
122
- for (const id of ids) {
123
- if (Object.prototype.hasOwnProperty.call(docImportTokens, id)) docImportTokens[id] = token;
124
- }
125
- });
126
- }
127
- ` : "";
128
- const cases = entries.map((e) => {
129
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(`${e.importPath}?t=`)} + docImportTokens[${JSON.stringify(e.id)}])` : `import(${JSON.stringify(e.importPath)})`;
130
- return ` case ${JSON.stringify(e.id)}: return ${importExpr};`;
131
- }).join("\n");
132
- return {
133
- code: `// virtual:open-doc/docs — generated
134
- export const docIds = ${ids};
135
- export const docCreatedAt = ${JSON.stringify(createdAtMap)};
136
- export const docThemes = ${JSON.stringify(themesMap)};
137
- ${devRuntime}
138
-
139
- export async function loadDoc(id) {
140
- switch (id) {
141
- ${cases}
142
- default: throw new Error('Document not found: ' + id);
143
- }
144
- }
145
- `,
146
- ignored
147
- };
148
- }
149
- function openDocPlugin(opts) {
150
- const { userCwd, config, coreVersion } = opts;
151
- const docsDir = config.docsDir ?? "docs";
152
- const docsRoot = path.resolve(userCwd, docsDir);
153
- const foldersManifestPath = path.join(docsRoot, ".folders.json");
154
- let isDev = false;
155
- const docIdForEntry = (p) => {
156
- const rel = path.relative(docsRoot, p);
157
- if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
158
- const parts = rel.split(path.sep);
159
- if (parts.length !== 2) return null;
160
- if (!/^index\.(tsx|jsx|ts|js)$/.test(parts[1])) return null;
161
- return parts[0];
162
- };
163
- let docChangeTimer = null;
164
- const pendingDocChanges = /* @__PURE__ */ new Set();
165
- const queueDocChanged = (server, id) => {
166
- pendingDocChanges.add(id);
167
- if (docChangeTimer) clearTimeout(docChangeTimer);
168
- docChangeTimer = setTimeout(() => {
169
- docChangeTimer = null;
170
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
171
- if (mod) server.moduleGraph.invalidateModule(mod);
172
- const docIds = Array.from(pendingDocChanges);
173
- pendingDocChanges.clear();
174
- server.ws.send({
175
- type: "custom",
176
- event: "open-doc:doc-changed",
177
- data: { docIds }
178
- });
179
- }, 100);
180
- };
181
- return {
182
- name: "open-doc",
183
- config(_c, env) {
184
- isDev = env.command === "serve";
185
- return { server: { fs: { allow: [userCwd] } } };
186
- },
187
- resolveId(id) {
188
- if (id === DOCS_VMOD) return resolved$1(DOCS_VMOD);
189
- if (id === CONFIG_VMOD) return resolved$1(CONFIG_VMOD);
190
- if (id === FOLDERS_VMOD) return resolved$1(FOLDERS_VMOD);
191
- return null;
192
- },
193
- async load(id) {
194
- if (id === resolved$1(DOCS_VMOD)) {
195
- const { code, ignored } = await generateDocsModule(await findDocs(userCwd, docsDir), docsRoot, isDev);
196
- for (const docId of ignored) {
197
- if (warnedInvalidDocIds.has(docId)) continue;
198
- warnedInvalidDocIds.add(docId);
199
- this.warn(`Ignoring document folder "${docId}": ids must match ${DOC_ID_RE} (letters, digits, "-", "_"). Rename it under "${docsDir}/" to a kebab-case id so it shows up.`);
200
- }
201
- return code;
202
- }
203
- if (id === resolved$1(CONFIG_VMOD)) {
204
- const userBuild = config.build ?? {};
205
- const build = isDev ? {
206
- showDocBrowser: true,
207
- allowHtmlExport: true
208
- } : {
209
- showDocBrowser: userBuild.showDocBrowser ?? true,
210
- allowHtmlExport: userBuild.allowHtmlExport ?? true
211
- };
212
- return `export default ${JSON.stringify({
213
- ...config,
214
- build,
215
- version: coreVersion
216
- })};\n`;
217
- }
218
- if (id === resolved$1(FOLDERS_VMOD)) {
219
- const manifest = await readFoldersManifest(foldersManifestPath);
220
- return `export default ${JSON.stringify(manifest)};\n`;
221
- }
222
- return null;
223
- },
224
- handleHotUpdate(ctx) {
225
- const docId = docIdForEntry(ctx.file);
226
- if (!docId) return;
227
- queueDocChanged(ctx.server, docId);
228
- return [];
229
- },
230
- configureServer(server) {
231
- const isDocEntry = (p) => docIdForEntry(p) !== null;
232
- let reloadTimer = null;
233
- const reload = () => {
234
- if (reloadTimer) clearTimeout(reloadTimer);
235
- reloadTimer = setTimeout(() => {
236
- reloadTimer = null;
237
- const mod = server.moduleGraph.getModuleById(resolved$1(DOCS_VMOD));
238
- if (mod) server.moduleGraph.invalidateModule(mod);
239
- server.ws.send({ type: "full-reload" });
240
- }, 150);
241
- };
242
- server.watcher.add(docsRoot);
243
- server.watcher.on("add", (p) => {
244
- if (isDocEntry(p)) reload();
245
- });
246
- server.watcher.on("unlink", (p) => {
247
- if (isDocEntry(p)) reload();
248
- });
249
- server.watcher.on("unlinkDir", (p) => {
250
- if (path.dirname(p) === docsRoot) reload();
251
- });
252
- let foldersTimer = null;
253
- const foldersChanged = () => {
254
- if (foldersTimer) clearTimeout(foldersTimer);
255
- foldersTimer = setTimeout(() => {
256
- foldersTimer = null;
257
- const mod = server.moduleGraph.getModuleById(resolved$1(FOLDERS_VMOD));
258
- if (mod) server.moduleGraph.invalidateModule(mod);
259
- server.ws.send({
260
- type: "custom",
261
- event: "open-doc:files-changed",
262
- data: {}
263
- });
264
- }, 100);
265
- };
266
- server.watcher.add(foldersManifestPath);
267
- for (const event of [
268
- "add",
269
- "change",
270
- "unlink"
271
- ]) server.watcher.on(event, (p) => {
272
- if (p === foldersManifestPath) foldersChanged();
273
- });
274
- }
275
- };
276
- }
277
- async function loadUserConfig(userCwd) {
278
- const file = path.join(userCwd, CONFIG_FILE);
279
- if (!existsSync(file)) return {};
280
- return (await loadConfigFromFile({
281
- command: "serve",
282
- mode: "development"
283
- }, file, userCwd, "silent"))?.config ?? {};
284
- }
285
- //#endregion
286
- //#region src/vite/routes/context.ts
287
- function makeContext(opts) {
288
- const userCwd = opts.userCwd;
289
- const docsDir = opts.docsDir ?? "docs";
290
- const assetsDir = opts.assetsDir ?? "assets";
291
- const docsRoot = path.resolve(userCwd, docsDir);
292
- return {
293
- userCwd,
294
- docsDir,
295
- docsRoot,
296
- globalAssetsRoot: path.resolve(userCwd, assetsDir),
297
- manifestPath: path.join(docsRoot, ".folders.json"),
298
- coreVersion: opts.coreVersion
299
- };
300
- }
301
- async function readBody(req) {
302
- return await new Promise((resolve, reject) => {
303
- const chunks = [];
304
- req.on("data", (c) => chunks.push(c));
305
- req.on("end", () => {
306
- const raw = Buffer.concat(chunks).toString("utf8");
307
- if (!raw) return resolve({});
308
- try {
309
- resolve(JSON.parse(raw));
310
- } catch (e) {
311
- reject(e);
312
- }
313
- });
314
- req.on("error", reject);
315
- });
316
- }
317
- function json(res, status, body) {
318
- res.statusCode = status;
319
- res.setHeader("content-type", "application/json");
320
- res.end(JSON.stringify(body));
321
- }
322
- const ENTRY_NAMES$1 = [
323
- "index.tsx",
324
- "index.jsx",
325
- "index.ts",
326
- "index.js"
327
- ];
328
- /** Absolute path of a document's entry file, or null when the id is unusable. */
329
- function resolveDocPath(userCwd, docsDir, docId) {
330
- if (!DOC_ID_RE.test(docId)) return null;
331
- const docsRoot = path.resolve(userCwd, docsDir);
332
- const full = path.resolve(docsRoot, docId, ENTRY_NAMES$1[0]);
333
- if (!full.startsWith(docsRoot + path.sep)) return null;
334
- return full;
335
- }
336
- /** The entry file that actually exists on disk for a document, or null. */
337
- function resolveDocEntry(docsRoot, docId) {
338
- if (!DOC_ID_RE.test(docId)) return null;
339
- const docDir = path.resolve(docsRoot, docId);
340
- if (!docDir.startsWith(docsRoot + path.sep)) return null;
341
- for (const name of ENTRY_NAMES$1) {
342
- const candidate = path.join(docDir, name);
343
- if (existsSync(candidate)) return candidate;
344
- }
345
- return null;
346
- }
347
- //#endregion
348
- //#region src/editing/doc-ops.ts
349
- function parseSource$1(source) {
350
- try {
351
- return parse(source, {
352
- sourceType: "module",
353
- plugins: ["typescript", "jsx"],
354
- errorRecovery: true
355
- });
356
- } catch {
357
- return null;
358
- }
359
- }
360
- function programBody(ast) {
361
- return ast.program?.body ?? [];
362
- }
363
- function metaObjectOf(node) {
364
- if (node.type !== "ExportNamedDeclaration") return null;
365
- const decl = node.declaration;
366
- if (decl?.type !== "VariableDeclaration") return null;
367
- const declarations = decl.declarations ?? [];
368
- for (const d of declarations) {
369
- const id = d.id;
370
- if (id?.type !== "Identifier" || id.name !== "meta") continue;
371
- let init = d.init;
372
- if (!init) return null;
373
- if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
374
- const expr = init.expression;
375
- if (expr) init = expr;
376
- }
377
- return init.type === "ObjectExpression" ? init : null;
378
- }
379
- return null;
380
- }
381
- function findMetaObject(ast) {
382
- for (const node of programBody(ast)) {
383
- const object = metaObjectOf(node);
384
- if (object) return object;
385
- }
386
- return null;
387
- }
388
- function jsString(value) {
389
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
390
- }
391
- function validateDocTitle(v) {
392
- if (typeof v !== "string") return null;
393
- const trimmed = v.trim();
394
- if (trimmed.length < 1 || trimmed.length > 120) return null;
395
- return trimmed;
396
- }
397
- /**
398
- * Rewrites `meta.title` in place, adding the property when the meta object
399
- * exists without one. Returns null when there is no meta object to edit —
400
- * the caller reports that rather than inventing an export.
401
- */
402
- function setMetaTitle(source, title) {
403
- const ast = parseSource$1(source);
404
- if (!ast) return null;
405
- const object = findMetaObject(ast);
406
- if (!object) return null;
407
- const properties = object.properties ?? [];
408
- for (const prop of properties) {
409
- if (prop.type !== "ObjectProperty") continue;
410
- const p = prop;
411
- if (p.computed) continue;
412
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
413
- return source.slice(0, p.value.start) + jsString(title) + source.slice(p.value.end);
414
- }
415
- const open = object.start + 1;
416
- const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString(title)},\n` : `\n title: ${jsString(title)},`;
417
- return source.slice(0, open) + inserted + source.slice(open);
418
- }
419
- function readMetaTitle(source) {
420
- const ast = parseSource$1(source);
421
- if (!ast) return null;
422
- const object = findMetaObject(ast);
423
- if (!object) return null;
424
- const properties = object.properties ?? [];
425
- for (const prop of properties) {
426
- if (prop.type !== "ObjectProperty") continue;
427
- const p = prop;
428
- if (p.computed) continue;
429
- if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
430
- if (p.value.type !== "StringLiteral") return null;
431
- return typeof p.value.value === "string" ? p.value.value : null;
432
- }
433
- return null;
434
- }
435
- /** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
436
- function nextCopyId(baseId, taken) {
437
- const stem = baseId.replace(/-copy(-\d+)?$/, "");
438
- let candidate = `${stem}-copy`;
439
- let n = 2;
440
- while (taken.has(candidate)) {
441
- candidate = `${stem}-copy-${n}`;
442
- n++;
443
- }
444
- return candidate;
445
- }
446
- function copyTitle(title) {
447
- return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
448
- }
449
- //#endregion
450
- //#region src/files/folders.ts
451
- const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
452
- const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
453
- function emptyManifest() {
454
- return {
455
- folders: [],
456
- assignments: {}
457
- };
458
- }
459
- async function readManifest(file) {
460
- try {
461
- const raw = await fs.readFile(file, "utf8");
462
- const parsed = JSON.parse(raw);
463
- return {
464
- folders: Array.isArray(parsed.folders) ? parsed.folders : [],
465
- assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
466
- };
467
- } catch (err) {
468
- if (err.code === "ENOENT") return emptyManifest();
469
- throw err;
470
- }
471
- }
472
- async function writeManifest(file, manifest) {
473
- await fs.mkdir(path.dirname(file), { recursive: true });
474
- await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
475
- }
476
- function newFolderId() {
477
- return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
478
- }
479
- function validateName(v) {
480
- if (typeof v !== "string") return null;
481
- const trimmed = v.trim();
482
- if (trimmed.length < 1 || trimmed.length > 40) return null;
483
- return trimmed;
484
- }
485
- function validateReorder(v, current) {
486
- if (!Array.isArray(v) || v.length !== current.length) return null;
487
- const known = new Set(current.map((f) => f.id));
488
- const seen = /* @__PURE__ */ new Set();
489
- const out = [];
490
- for (const id of v) {
491
- if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
492
- if (!known.has(id) || seen.has(id)) return null;
493
- seen.add(id);
494
- out.push(id);
495
- }
496
- return out;
497
- }
498
- function validateIcon(v) {
499
- if (!v || typeof v !== "object") return null;
500
- const icon = v;
501
- if (icon.type === "emoji") {
502
- if (typeof icon.value !== "string") return null;
503
- if (icon.value.length < 1 || icon.value.length > 8) return null;
504
- return {
505
- type: "emoji",
506
- value: icon.value
507
- };
508
- }
509
- if (icon.type === "color") {
510
- if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
511
- return {
512
- type: "color",
513
- value: icon.value
514
- };
515
- }
516
- return null;
517
- }
518
- //#endregion
519
- //#region src/ops/documents.ts
520
- /**
521
- * Operations shared by the dev API and the MCP server. Everything here takes an
522
- * `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
523
- * and a browser calling `/__docs` end up in exactly the same code.
524
- */
525
- var OpsError = class extends Error {
526
- status;
527
- constructor(status, message) {
528
- super(message);
529
- this.status = status;
530
- this.name = "OpsError";
531
- }
532
- };
533
- const ENTRY_NAMES = [
534
- "index.tsx",
535
- "index.jsx",
536
- "index.ts",
537
- "index.js"
538
- ];
539
- function docDir(ctx, docId) {
540
- if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
541
- const dir = path.resolve(ctx.docsRoot, docId);
542
- if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
543
- return dir;
544
- }
545
- function resolveEntry(ctx, docId) {
546
- const dir = docDir(ctx, docId);
547
- for (const name of ENTRY_NAMES) {
548
- const file = path.join(dir, name);
549
- if (existsSync(file)) return file;
550
- }
551
- return null;
552
- }
553
- async function listDocIds(ctx) {
554
- try {
555
- return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
556
- } catch {
557
- return [];
558
- }
559
- }
560
- /** Reads what the doc declares without executing it — a regex over `export const meta`. */
561
- function readMetaField(source, field) {
562
- const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
563
- return source.slice(source.indexOf("export const meta")).match(re)?.[2];
564
- }
565
- async function listDocuments(ctx) {
566
- const ids = await listDocIds(ctx);
567
- const manifest = await readManifest(ctx.manifestPath);
568
- const out = [];
569
- for (const id of ids) {
570
- const entry = resolveEntry(ctx, id);
571
- const source = entry ? await fs.readFile(entry, "utf8") : "";
572
- out.push({
573
- id,
574
- title: source ? readMetaTitle(source) : null,
575
- subtitle: source ? readMetaField(source, "subtitle") : void 0,
576
- theme: source ? readMetaField(source, "theme") : void 0,
577
- createdAt: source ? readMetaField(source, "createdAt") : void 0,
578
- folder: manifest.assignments[id],
579
- entry: entry ? path.relative(ctx.userCwd, entry) : null
580
- });
581
- }
582
- return out;
583
- }
584
- async function readDocument(ctx, docId) {
585
- const entry = resolveEntry(ctx, docId);
586
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
587
- return {
588
- id: docId,
589
- entry: path.relative(ctx.userCwd, entry),
590
- source: await fs.readFile(entry, "utf8")
591
- };
592
- }
593
- async function createDocument(ctx, docId, source) {
594
- const dir = docDir(ctx, docId);
595
- if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
596
- await fs.mkdir(dir, { recursive: true });
597
- const entry = path.join(dir, "index.tsx");
598
- await fs.writeFile(entry, source, "utf8");
599
- return {
600
- id: docId,
601
- entry: path.relative(ctx.userCwd, entry)
602
- };
603
- }
604
- /**
605
- * Whole-file overwrite. `expected` is the source the caller believes is on
606
- * disk; passing it turns a blind overwrite into a conflict check, which is what
607
- * keeps two agents (or an agent and a person) from clobbering each other.
608
- */
609
- async function writeDocument(ctx, docId, source, expected) {
610
- const entry = resolveEntry(ctx, docId);
611
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
612
- if (expected !== void 0) {
613
- if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
614
- }
615
- await fs.writeFile(entry, source, "utf8");
616
- return {
617
- id: docId,
618
- entry: path.relative(ctx.userCwd, entry)
619
- };
620
- }
621
- async function renameDocument(ctx, docId, rawTitle) {
622
- const title = validateDocTitle(rawTitle);
623
- if (!title) throw new OpsError(400, "invalid title");
624
- const entry = resolveEntry(ctx, docId);
625
- if (!entry) throw new OpsError(404, `document not found: ${docId}`);
626
- const source = await fs.readFile(entry, "utf8");
627
- const next = setMetaTitle(source, title);
628
- if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
629
- if (next !== source) await fs.writeFile(entry, next, "utf8");
630
- return {
631
- id: docId,
632
- title
633
- };
634
- }
635
- async function duplicateDocument(ctx, docId, newId) {
636
- const dir = docDir(ctx, docId);
637
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
638
- const taken = new Set(await listDocIds(ctx));
639
- let targetId;
640
- if (newId) {
641
- if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
642
- if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
643
- targetId = newId;
644
- } else targetId = nextCopyId(docId, taken);
645
- await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
646
- const entry = resolveEntry(ctx, targetId);
647
- if (entry) {
648
- const source = await fs.readFile(entry, "utf8");
649
- const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
650
- if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
651
- }
652
- const manifest = await readManifest(ctx.manifestPath);
653
- const folderId = manifest.assignments[docId];
654
- if (folderId) {
655
- manifest.assignments[targetId] = folderId;
656
- await writeManifest(ctx.manifestPath, manifest);
657
- }
658
- return { id: targetId };
659
- }
660
- async function deleteDocument(ctx, docId) {
661
- const dir = docDir(ctx, docId);
662
- if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
663
- await fs.rm(dir, {
664
- recursive: true,
665
- force: true
666
- });
667
- const manifest = await readManifest(ctx.manifestPath);
668
- if (manifest.assignments[docId]) {
669
- delete manifest.assignments[docId];
670
- await writeManifest(ctx.manifestPath, manifest);
671
- }
672
- }
673
- //#endregion
674
- //#region src/files/assets.ts
675
- const GLOBAL_SCOPE = "@global";
676
- const ASSET_MAX_BYTES = 26214400;
677
- const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
678
- const MIME_BY_EXT = {
679
- png: "image/png",
680
- jpg: "image/jpeg",
681
- jpeg: "image/jpeg",
682
- gif: "image/gif",
683
- svg: "image/svg+xml",
684
- webp: "image/webp",
685
- avif: "image/avif",
686
- ico: "image/x-icon",
687
- pdf: "application/pdf",
688
- woff: "font/woff",
689
- woff2: "font/woff2",
690
- ttf: "font/ttf",
691
- otf: "font/otf",
692
- csv: "text/csv; charset=utf-8",
693
- json: "application/json",
694
- txt: "text/plain; charset=utf-8",
695
- md: "text/markdown; charset=utf-8"
696
- };
697
- function mimeForFilename(name) {
698
- const dot = name.lastIndexOf(".");
699
- if (dot < 0) return "application/octet-stream";
700
- return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
701
- }
702
- function assetCreatedAt(birthtimeMs, mtimeMs) {
703
- return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
704
- }
705
- function validateAssetName(v) {
706
- if (typeof v !== "string") return null;
707
- const trimmed = v.trim();
708
- if (trimmed.length < 1 || trimmed.length > 120) return null;
709
- if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
710
- if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
711
- if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
712
- const dot = trimmed.lastIndexOf(".");
713
- if (dot <= 0 || dot === trimmed.length - 1) return null;
714
- return trimmed;
715
- }
716
- function resolveAssetsDir(docsRoot, docId) {
717
- if (!DOC_ID_RE.test(docId)) return null;
718
- const docDir = path.resolve(docsRoot, docId);
719
- if (!docDir.startsWith(docsRoot + path.sep)) return null;
720
- const assetsDir = path.resolve(docDir, "assets");
721
- if (assetsDir !== path.join(docDir, "assets")) return null;
722
- return assetsDir;
723
- }
724
- function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
725
- if (scope === "@global") return globalAssetsRoot;
726
- return resolveAssetsDir(docsRoot, scope);
727
- }
728
- function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
729
- if (!validateAssetName(filename)) return null;
730
- const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
731
- if (!dir) return null;
732
- const file = path.resolve(dir, filename);
733
- if (!file.startsWith(dir + path.sep)) return null;
734
- return file;
735
- }
736
- /** How a document imports an asset — the string we look for when counting usages. */
737
- function assetImportPath(scope, filename) {
738
- return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
739
- }
740
- function escapeRegExp(value) {
741
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
742
- }
743
- /**
744
- * Counts references to an asset in a document's source. Matches the quoted path
745
- * in both import statements and `new URL('./assets/x.png', import.meta.url)`,
746
- * which is every form the authoring skill sanctions.
747
- */
748
- function countAssetUsages(source, importPath) {
749
- const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
750
- return source.match(quoted)?.length ?? 0;
751
- }
752
- function findReferencedAssets(source, importPaths) {
753
- return importPaths.filter((p) => countAssetUsages(source, p) > 0);
754
- }
755
- //#endregion
756
- //#region src/vite/themes-plugin.ts
757
- const THEMES_VMOD = "virtual:open-doc/themes";
758
- function resolved(id) {
759
- return `\0${id}`;
760
- }
761
- const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
762
- function parseFrontmatter(raw, themeId) {
763
- const match = raw.match(FM_RE);
764
- const fmText = match ? match[1] : "";
765
- const body = match ? match[2] : raw;
766
- const data = {};
767
- for (const line of fmText.split(/\r?\n/)) {
768
- const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
769
- if (!m) continue;
770
- let value = m[2].trim();
771
- if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
772
- data[m[1]] = value;
773
- }
774
- return {
775
- fm: {
776
- name: data.name || themeId,
777
- description: data.description || "",
778
- pageSize: data.pageSize || "",
779
- mode: data.mode || ""
780
- },
781
- body: body.trim()
782
- };
783
- }
784
- async function findThemes(userCwd, themesDir) {
785
- const abs = path.resolve(userCwd, themesDir);
786
- if (!existsSync(abs)) return [];
787
- return (await fg("*.md", {
788
- cwd: abs,
789
- absolute: true,
790
- onlyFiles: true
791
- })).sort();
792
- }
793
- async function readTheme(mdAbs, themesRoot) {
794
- const id = path.basename(mdAbs, ".md");
795
- const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
796
- let demoAbs = null;
797
- for (const cand of [
798
- `${id}.demo.tsx`,
799
- `${id}.demo.jsx`,
800
- `${id}.demo.ts`,
801
- `${id}.demo.js`
802
- ]) {
803
- const p = path.join(themesRoot, cand);
804
- if (existsSync(p)) {
805
- demoAbs = p;
806
- break;
807
- }
808
- }
809
- return {
810
- id,
811
- frontmatter: fm,
812
- body,
813
- demoAbs
814
- };
815
- }
816
- function generateThemesModule(themes, isDev) {
817
- const meta = themes.map((t) => ({
818
- id: t.id,
819
- name: t.frontmatter.name,
820
- description: t.frontmatter.description,
821
- pageSize: t.frontmatter.pageSize,
822
- mode: t.frontmatter.mode,
823
- body: t.body,
824
- hasDemo: t.demoAbs !== null
825
- }));
826
- const cases = themes.flatMap((t) => {
827
- const abs = t.demoAbs;
828
- if (!abs) return [];
829
- const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
830
- const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
831
- return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
832
- }).join("\n");
833
- return `// virtual:open-doc/themes — generated
834
- export const themes = ${JSON.stringify(meta)};
835
-
836
- export async function loadThemeDemo(id) {
837
- switch (id) {
838
- ${cases}
839
- default: throw new Error('Theme demo not found: ' + id);
840
- }
841
- }
842
- `;
843
- }
844
- function themesPlugin(opts) {
845
- const { userCwd, config } = opts;
846
- const themesDir = config.themesDir ?? "themes";
847
- const themesRoot = path.resolve(userCwd, themesDir);
848
- let isDev = false;
849
- return {
850
- name: "open-doc:themes",
851
- config(_c, env) {
852
- isDev = env.command === "serve";
853
- },
854
- resolveId(id) {
855
- if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
856
- return null;
857
- },
858
- async load(id) {
859
- if (id !== resolved(THEMES_VMOD)) return null;
860
- const files = await findThemes(userCwd, themesDir);
861
- return generateThemesModule(await Promise.all(files.map((f) => readTheme(f, themesRoot))), isDev);
862
- },
863
- configureServer(server) {
864
- const isThemeFile = (p) => {
865
- const rel = path.relative(themesRoot, p);
866
- if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
867
- if (rel.includes(path.sep)) return false;
868
- return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
869
- };
870
- let reloadTimer = null;
871
- const reload = () => {
872
- if (reloadTimer) clearTimeout(reloadTimer);
873
- reloadTimer = setTimeout(() => {
874
- reloadTimer = null;
875
- const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
876
- if (mod) server.moduleGraph.invalidateModule(mod);
877
- server.ws.send({ type: "full-reload" });
878
- }, 150);
879
- };
880
- server.watcher.add(themesRoot);
881
- for (const event of [
882
- "add",
883
- "unlink",
884
- "change"
885
- ]) server.watcher.on(event, (p) => {
886
- if (isThemeFile(p)) reload();
887
- });
888
- }
889
- };
890
- }
891
- //#endregion
892
- //#region src/editing/babel-walk.ts
893
- function parseSource(code) {
894
- try {
895
- return parse(code, {
896
- sourceType: "module",
897
- plugins: ["typescript", "jsx"],
898
- errorRecovery: true
899
- });
900
- } catch {
901
- return null;
902
- }
903
- }
904
- function isNode(value) {
905
- return typeof value === "object" && value !== null && typeof value.type === "string";
906
- }
907
- /** Depth-first walk over every node; the visitor decides what it cares about. */
908
- function walkAst(node, visit) {
909
- if (Array.isArray(node)) {
910
- for (const child of node) walkAst(child, visit);
911
- return;
912
- }
913
- if (!isNode(node)) return;
914
- visit(node);
915
- for (const key of Object.keys(node)) {
916
- if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
917
- walkAst(node[key], visit);
918
- }
919
- }
920
- function walkJsx(ast, visit) {
921
- walkAst(ast, (node) => {
922
- if (node.type === "JSXElement") visit(node);
923
- });
924
- }
925
- /**
926
- * The JSX element whose opening tag starts at this source position.
927
- *
928
- * The match is exact on both line and column. Anything looser can resolve to a
929
- * different element on the same line, and this location decides where an edit
930
- * gets written — a near miss silently rewrites the wrong text.
931
- */
932
- function findJsxAt(ast, line, column) {
933
- let found = null;
934
- walkJsx(ast, (node) => {
935
- if (found) return;
936
- const start = node.loc?.start;
937
- if (start && start.line === line && start.column === column) found = node;
938
- });
939
- return found;
940
- }
941
- /**
942
- * Every JSX element that starts on a line, nearest column first.
943
- *
944
- * Columns cannot be trusted for locations derived from React's `_debugSource`:
945
- * injecting the loc attribute shifts the columns of anything later on the same
946
- * line, so the offset differs per element. The line survives that, so callers
947
- * scan the line and pick by content instead.
948
- */
949
- function findJsxOnLine(ast, line, column) {
950
- const hits = [];
951
- walkJsx(ast, (node) => {
952
- const start = node.loc?.start;
953
- if (!start || start.line !== line) return;
954
- hits.push({
955
- node,
956
- distance: Math.abs(start.column - column)
957
- });
958
- });
959
- return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
960
- }
961
- //#endregion
962
- //#region src/editing/comments.ts
963
- const MARKER_RE = /\{\/\*\s*@doc-comment\s+id="(c-[a-f0-9]+)"\s+ts="([^"]+)"\s+text="([A-Za-z0-9_-]+={0,2})"\s*\*\/\}/;
964
- function b64urlEncode(value) {
965
- return Buffer.from(value, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
966
- }
967
- function b64urlDecode(value) {
968
- const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - value.length % 4);
969
- return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
970
- }
971
- function parseMarkers(source) {
972
- const comments = [];
973
- source.split("\n").forEach((line, index) => {
974
- const match = MARKER_RE.exec(line);
975
- if (!match) return;
976
- const [, id, ts, payload] = match;
977
- try {
978
- const decoded = JSON.parse(b64urlDecode(payload));
979
- comments.push({
980
- id,
981
- line: index + 1,
982
- ts,
983
- note: decoded.note,
984
- hint: decoded.hint
985
- });
986
- } catch {}
987
- });
988
- return comments;
989
- }
990
- function newCommentId() {
991
- return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
992
- }
993
- function markerFor(id, ts, note, hint) {
994
- return `{/* @doc-comment id="${id}" ts="${ts}" text="${b64urlEncode(JSON.stringify(hint ? {
995
- note,
996
- hint
997
- } : { note }))}" */}`;
998
- }
999
- function markerPattern(id) {
1000
- return `\\{\\/\\*\\s*@doc-comment\\s+id="${id}"\\s+ts="[^"]+"\\s+text="[A-Za-z0-9_\\-]+={0,2}"\\s*\\*\\/\\}`;
1001
- }
1002
- /**
1003
- * Removes a marker and the whitespace the insertion added — whichever side it
1004
- * landed on — so deleting a comment restores the file byte for byte.
1005
- */
1006
- function removeMarker(source, id) {
1007
- const pattern = markerPattern(id);
1008
- for (const re of [
1009
- new RegExp(`[ \\t]*${pattern}\\n`),
1010
- new RegExp(`\\n[ \\t]*${pattern}`),
1011
- new RegExp(pattern)
1012
- ]) if (re.test(source)) return source.replace(re, "");
1013
- return null;
1014
- }
1015
- function indentOfLine(source, offset) {
1016
- const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
1017
- return /^[ \t]*/.exec(source.slice(lineStart, offset))?.[0] ?? "";
1018
- }
1019
- /**
1020
- * Splices the marker in as the **first child** of the target element. A
1021
- * JSX-comment token outside a JSX child position parses as an empty object
1022
- * literal and breaks the surrounding expression, so this never puts one before
1023
- * an element.
1024
- */
1025
- function insertMarker(source, target, note, hint) {
1026
- const ast = parseSource(source);
1027
- if (!ast) return null;
1028
- const element = findJsxAt(ast, target.line, target.column);
1029
- if (!element) return null;
1030
- const opening = element.openingElement;
1031
- if (!opening) return null;
1032
- if (opening.selfClosing === true) return null;
1033
- const offset = opening.end;
1034
- const id = newCommentId();
1035
- const marker = markerFor(id, (/* @__PURE__ */ new Date()).toISOString(), note, hint);
1036
- const indent = indentOfLine(source, element.start ?? offset);
1037
- return {
1038
- source: `${source.slice(0, offset)}\n${indent} ${marker}${source.slice(offset)}`,
1039
- id
1040
- };
1041
- }
1042
- //#endregion
1043
- //#region src/editing/edit-ops.ts
1044
- /** JSX text is written literally; only these characters have to be escaped. */
1045
- function escapeJsxText(text) {
1046
- return text.replace(/[{}<>]/g, (char) => `{'${char}'}`);
1047
- }
1048
- function normalizeText(value) {
1049
- return value.replace(/\s+/g, " ").trim();
1050
- }
1051
- function jsxChildren(element) {
1052
- return element.children ?? [];
1053
- }
1054
- function labelOf(node) {
1055
- if (node.type === "JSXExpressionContainer") return "{…}";
1056
- if (node.type === "JSXElement") return `<${(node.openingElement?.name)?.name ?? "element"}>`;
1057
- return "…";
1058
- }
1059
- /** Text children with content, in document order. */
1060
- function textNodes(element) {
1061
- return jsxChildren(element).filter((child) => child.type === "JSXText" && child.value.trim() !== "");
1062
- }
1063
- function partsOf(element) {
1064
- const parts = [];
1065
- let index = 0;
1066
- for (const child of jsxChildren(element)) {
1067
- if (child.type === "JSXText") {
1068
- const value = child.value;
1069
- if (value.trim() === "") continue;
1070
- parts.push({
1071
- kind: "text",
1072
- index: index++,
1073
- value: value.trim()
1074
- });
1075
- continue;
1076
- }
1077
- parts.push({
1078
- kind: "markup",
1079
- label: labelOf(child)
1080
- });
1081
- }
1082
- return parts;
1083
- }
1084
- function describe(element) {
1085
- const parts = partsOf(element);
1086
- const texts = parts.filter((part) => part.kind === "text");
1087
- if (texts.length === 0) return {
1088
- editable: false,
1089
- text: "",
1090
- parts,
1091
- reason: parts.some((part) => part.kind === "markup" && part.label === "{…}") ? "text is produced by code — edit whatever feeds it" : "element has no text of its own"
1092
- };
1093
- return {
1094
- editable: true,
1095
- text: texts.map((part) => part.value).join(" "),
1096
- parts
1097
- };
1098
- }
1099
- /**
1100
- * Picks the element an inspector click meant.
1101
- *
1102
- * Coordinates alone are not enough: fallback candidates come from React's
1103
- * `_debugSource`, whose columns drift once the loc-tag transform has widened
1104
- * the line. The rendered text the user is looking at is the tiebreaker — an
1105
- * element only wins if its source text is part of what is on screen.
1106
- */
1107
- function resolveTextTarget(source, candidates, expected) {
1108
- const ast = parseSource(source);
1109
- if (!ast) return null;
1110
- const shown = expected ? normalizeText(expected) : null;
1111
- const matches = (info) => {
1112
- if (!shown) return true;
1113
- const runs = info.parts.filter((part) => part.kind === "text");
1114
- if (runs.length === 0) return false;
1115
- return runs.every((part) => part.kind === "text" && shown.includes(normalizeText(part.value)));
1116
- };
1117
- for (const candidate of candidates) {
1118
- const exact = findJsxAt(ast, candidate.line, candidate.column);
1119
- if (exact) {
1120
- const info = describe(exact);
1121
- if (info.editable && matches(info)) return {
1122
- ...info,
1123
- ...candidate
1124
- };
1125
- }
1126
- if (!shown) continue;
1127
- for (const node of findJsxOnLine(ast, candidate.line, candidate.column)) {
1128
- const info = describe(node);
1129
- const start = node.loc?.start;
1130
- if (!info.editable || !matches(info) || !start) continue;
1131
- return {
1132
- ...info,
1133
- line: start.line,
1134
- column: start.column
1135
- };
1136
- }
1137
- }
1138
- const first = candidates[0];
1139
- if (!first) return null;
1140
- const clicked = findJsxAt(ast, first.line, first.column);
1141
- return clicked ? {
1142
- ...describe(clicked),
1143
- ...first
1144
- } : null;
1145
- }
1146
- /**
1147
- * Replaces one text run of an element, leaving its markup and every other run
1148
- * untouched. `expected` is the text the caller believes is there; a mismatch
1149
- * means the source moved under us and the write is refused.
1150
- */
1151
- function replaceTextAt(source, target, text, opts = {}) {
1152
- const ast = parseSource(source);
1153
- if (!ast) return {
1154
- ok: false,
1155
- status: 422,
1156
- error: "could not parse document source"
1157
- };
1158
- const element = findJsxAt(ast, target.line, target.column);
1159
- if (!element) return {
1160
- ok: false,
1161
- status: 404,
1162
- error: "no element at that source location"
1163
- };
1164
- const nodes = textNodes(element);
1165
- if (nodes.length === 0) return {
1166
- ok: false,
1167
- status: 422,
1168
- error: "element has no text to replace"
1169
- };
1170
- const child = nodes[opts.index ?? 0];
1171
- if (!child) return {
1172
- ok: false,
1173
- status: 404,
1174
- error: "no such text run in this element"
1175
- };
1176
- const raw = child.value;
1177
- if (opts.expected !== void 0 && normalizeText(raw) !== normalizeText(opts.expected)) return {
1178
- ok: false,
1179
- status: 409,
1180
- error: "source changed since this was opened — reselect it"
1181
- };
1182
- const leading = raw.match(/^\s*/)?.[0] ?? "";
1183
- const trailing = raw.match(/\s*$/)?.[0] ?? "";
1184
- return {
1185
- ok: true,
1186
- source: source.slice(0, child.start) + leading + escapeJsxText(text) + trailing + source.slice(child.end)
1187
- };
1188
- }
1189
- //#endregion
1190
- export { writeDocument as A, readBody as B, docDir as C, readDocument as D, listDocuments as E, validateName as F, openDocPlugin as G, resolveDocPath as H, validateReorder as I, writeManifest as L, newFolderId as M, readManifest as N, renameDocument as O, validateIcon as P, json as R, deleteDocument as S, listDocIds as T, DOC_ID_RE as U, resolveDocEntry as V, loadUserConfig as W, resolveScopedAssetFile as _, removeMarker as a, OpsError as b, parseFrontmatter as c, GLOBAL_SCOPE as d, assetCreatedAt as f, mimeForFilename as g, findReferencedAssets as h, parseMarkers as i, FOLDER_ID_RE as j, resolveEntry as k, themesPlugin as l, countAssetUsages as m, resolveTextTarget as n, parseSource as o, assetImportPath as p, insertMarker as r, walkJsx as s, replaceTextAt as t, ASSET_MAX_BYTES as u, resolveScopedAssetsDir as v, duplicateDocument as w, createDocument as x, validateAssetName as y, makeContext as z };