@open-document/core 0.11.0 → 0.12.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-BHFGY8eF.js → build-DfUfpeTR.js} +1 -1
- package/dist/{check-UEBmDfT_.js → check-CHxiOkQG.js} +3 -3
- package/dist/cli/bin.js +20 -33
- package/dist/{config-B_pdNbYg.js → config-9IdbhVuT.js} +1402 -675
- package/dist/{context-BM9_-u9P.js → context-BLI1-64_.js} +2 -2
- package/dist/{dev-DX3QMIRi.js → dev-yNYKv5mm.js} +1 -1
- package/dist/{diff-DayvbXfX.js → diff-Bs205mOx.js} +2 -2
- package/dist/{export-BPsXj1i6.js → export-tkquS5O5.js} +11 -4
- package/dist/{import-71wlAsrd.js → import-D1hIKIr3.js} +3 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +63 -28
- package/dist/ops/index.d.ts +111 -2
- package/dist/ops/index.js +3 -3
- package/dist/{ops-BUo67DaP.js → ops-Dgqujq5a.js} +85 -164
- package/dist/package-version-C89gtYSk.js +36 -0
- package/dist/{preview-D3m1-gUL.js → preview-BImdTH6K.js} +1 -1
- package/dist/{sdk-CpDEGRIo.d.ts → sdk-CHEGeINh.d.ts} +46 -1
- package/dist/templates-DT5zzqHq.js +34 -0
- package/dist/vite/index.js +1 -1
- package/package.json +2 -1
- package/skills/apply-comments/SKILL.md +3 -1
- package/skills/create-doc/SKILL.md +2 -0
- package/skills/doc-authoring/SKILL.md +2 -0
- package/src/app/components/browser/browser-ui.tsx +21 -0
- package/src/app/components/browser/new-document-dialog.tsx +208 -0
- package/src/app/components/changes/changes-overlay.tsx +68 -0
- package/src/app/components/changes/changes-panel.tsx +341 -0
- package/src/app/components/changes/use-changes.ts +85 -0
- package/src/app/components/comments/comments-overlay.tsx +50 -0
- package/src/app/components/comments/comments-panel.tsx +272 -0
- package/src/app/components/comments/use-comments.ts +61 -0
- package/src/app/components/doc-sidebar.tsx +32 -2
- package/src/app/components/inspector/field-source.tsx +41 -0
- package/src/app/components/inspector/inspector.tsx +64 -65
- package/src/app/components/overlay-frame.tsx +79 -0
- package/src/app/components/page-frame.tsx +4 -0
- package/src/app/components/page-placement.ts +68 -0
- package/src/app/components/record-picker.tsx +79 -0
- package/src/app/components/themes/theme-preview.tsx +5 -4
- package/src/app/lib/agent-bridge.ts +29 -1
- package/src/app/lib/docx/ooxml.test.ts +24 -1
- package/src/app/lib/docx/ooxml.ts +27 -1
- package/src/app/lib/export-docx.ts +3 -1
- package/src/app/lib/export-dom.ts +2 -1
- package/src/app/lib/export-html.ts +4 -2
- package/src/app/lib/export-image.ts +2 -1
- package/src/app/lib/flow-measure.test.ts +30 -0
- package/src/app/lib/flow-measure.ts +35 -10
- package/src/app/lib/i18n-ja/browser.ts +10 -0
- package/src/app/lib/i18n-ja/doc.ts +4 -0
- package/src/app/lib/i18n-ja/panels.ts +40 -0
- package/src/app/lib/i18n-ko/browser.ts +10 -0
- package/src/app/lib/i18n-ko/doc.ts +4 -0
- package/src/app/lib/i18n-ko/panels.ts +39 -0
- package/src/app/lib/i18n-zh-cn/browser.ts +10 -0
- package/src/app/lib/i18n-zh-cn/doc.ts +4 -0
- package/src/app/lib/i18n-zh-cn/panels.ts +38 -0
- package/src/app/lib/i18n-zh-tw/browser.ts +10 -0
- package/src/app/lib/i18n-zh-tw/doc.ts +4 -0
- package/src/app/lib/i18n-zh-tw/panels.ts +38 -0
- package/src/app/lib/records.test.ts +38 -0
- package/src/app/lib/records.ts +127 -0
- package/src/app/lib/sdk.ts +29 -0
- package/src/app/lib/use-doc-module.ts +7 -0
- package/src/app/lib/use-doc-pages.ts +15 -9
- package/src/app/routes/doc.tsx +274 -13
- package/src/app/routes/home.tsx +30 -5
- package/src/app/styles.css +23 -0
- package/templates/blank/index.tsx +63 -0
- package/templates/blank/template.json +6 -0
- package/templates/certificate/data/recipients.csv +4 -0
- package/templates/certificate/index.tsx +128 -0
- package/templates/certificate/template.json +6 -0
- package/templates/letter/index.tsx +106 -0
- package/templates/letter/template.json +5 -0
- package/templates/meeting-notes/index.tsx +194 -0
- package/templates/meeting-notes/template.json +6 -0
- package/templates/proposal/index.tsx +264 -0
- package/templates/proposal/template.json +6 -0
- package/templates/report/data/metrics.csv +5 -0
- package/templates/report/index.tsx +224 -0
- package/templates/report/template.json +6 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
|
|
2
|
+
import { t as corePackageRoot } from "./package-version-C89gtYSk.js";
|
|
2
3
|
import chalk from "chalk";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -6,10 +7,12 @@ import fs from "node:fs/promises";
|
|
|
6
7
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
8
|
import fg from "fast-glob";
|
|
8
9
|
import { loadConfigFromFile, normalizePath } from "vite";
|
|
10
|
+
import { execFile } from "node:child_process";
|
|
11
|
+
import { promisify } from "node:util";
|
|
12
|
+
import { parse } from "@babel/parser";
|
|
13
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
9
14
|
import tailwindcss from "@tailwindcss/vite";
|
|
10
15
|
import react from "@vitejs/plugin-react";
|
|
11
|
-
import { parse } from "@babel/parser";
|
|
12
|
-
import { randomUUID } from "node:crypto";
|
|
13
16
|
//#region src/vite/open-doc-plugin.ts
|
|
14
17
|
const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
15
18
|
const CONFIG_FILE = "open-doc.config.ts";
|
|
@@ -169,6 +172,7 @@ function openDocPlugin(opts) {
|
|
|
169
172
|
const docsRoot = path.resolve(userCwd, docsDir);
|
|
170
173
|
const foldersManifestPath = path.join(docsRoot, ".folders.json");
|
|
171
174
|
let isDev = false;
|
|
175
|
+
let listedIds = "";
|
|
172
176
|
const docIdForEntry = (p) => {
|
|
173
177
|
const rel = path.relative(docsRoot, p);
|
|
174
178
|
if (rel.startsWith("..") || path.isAbsolute(rel)) return null;
|
|
@@ -209,7 +213,9 @@ function openDocPlugin(opts) {
|
|
|
209
213
|
},
|
|
210
214
|
async load(id) {
|
|
211
215
|
if (id === resolved$1(DOCS_VMOD)) {
|
|
212
|
-
const
|
|
216
|
+
const files = await findDocs(userCwd, docsDir);
|
|
217
|
+
listedIds = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort());
|
|
218
|
+
const { code, ignored } = await generateDocsModule(files, docsRoot, isDev);
|
|
213
219
|
for (const docId of ignored) {
|
|
214
220
|
if (warnedInvalidDocIds.has(docId)) continue;
|
|
215
221
|
warnedInvalidDocIds.add(docId);
|
|
@@ -260,6 +266,13 @@ function openDocPlugin(opts) {
|
|
|
260
266
|
server.watcher.on("add", (p) => {
|
|
261
267
|
if (isDocEntry(p)) reload();
|
|
262
268
|
});
|
|
269
|
+
server.middlewares.use("/__docs-rescan", async (_req, res) => {
|
|
270
|
+
const files = await findDocs(userCwd, docsDir);
|
|
271
|
+
const changed = JSON.stringify(files.map((file) => toId(file, docsRoot)).sort()) !== listedIds;
|
|
272
|
+
if (changed) reload();
|
|
273
|
+
res.setHeader("content-type", "application/json");
|
|
274
|
+
res.end(JSON.stringify({ changed }));
|
|
275
|
+
});
|
|
263
276
|
server.watcher.on("unlink", (p) => {
|
|
264
277
|
if (isDocEntry(p)) reload();
|
|
265
278
|
});
|
|
@@ -363,144 +376,927 @@ function resolveDocEntry(docsRoot, docId) {
|
|
|
363
376
|
return null;
|
|
364
377
|
}
|
|
365
378
|
//#endregion
|
|
366
|
-
//#region src/
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
ico: "image/x-icon",
|
|
378
|
-
pdf: "application/pdf",
|
|
379
|
-
woff: "font/woff",
|
|
380
|
-
woff2: "font/woff2",
|
|
381
|
-
ttf: "font/ttf",
|
|
382
|
-
otf: "font/otf",
|
|
383
|
-
csv: "text/csv; charset=utf-8",
|
|
384
|
-
json: "application/json",
|
|
385
|
-
txt: "text/plain; charset=utf-8",
|
|
386
|
-
md: "text/markdown; charset=utf-8"
|
|
387
|
-
};
|
|
388
|
-
function mimeForFilename(name) {
|
|
389
|
-
const dot = name.lastIndexOf(".");
|
|
390
|
-
if (dot < 0) return "application/octet-stream";
|
|
391
|
-
return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
|
|
392
|
-
}
|
|
393
|
-
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
394
|
-
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
395
|
-
}
|
|
396
|
-
function validateAssetName(v) {
|
|
397
|
-
if (typeof v !== "string") return null;
|
|
398
|
-
const trimmed = v.trim();
|
|
399
|
-
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
400
|
-
if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
|
|
401
|
-
if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
|
|
402
|
-
if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
|
|
403
|
-
const dot = trimmed.lastIndexOf(".");
|
|
404
|
-
if (dot <= 0 || dot === trimmed.length - 1) return null;
|
|
405
|
-
return trimmed;
|
|
406
|
-
}
|
|
407
|
-
function resolveAssetsDir(docsRoot, docId) {
|
|
408
|
-
if (!DOC_ID_RE.test(docId)) return null;
|
|
409
|
-
const docDir = path.resolve(docsRoot, docId);
|
|
410
|
-
if (!docDir.startsWith(docsRoot + path.sep)) return null;
|
|
411
|
-
const assetsDir = path.resolve(docDir, "assets");
|
|
412
|
-
if (assetsDir !== path.join(docDir, "assets")) return null;
|
|
413
|
-
return assetsDir;
|
|
379
|
+
//#region src/editing/babel-walk.ts
|
|
380
|
+
function parseSource(code) {
|
|
381
|
+
try {
|
|
382
|
+
return parse(code, {
|
|
383
|
+
sourceType: "module",
|
|
384
|
+
plugins: ["typescript", "jsx"],
|
|
385
|
+
errorRecovery: true
|
|
386
|
+
});
|
|
387
|
+
} catch {
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
414
390
|
}
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
391
|
+
/**
|
|
392
|
+
* `parseSource`, but a source with any recovered error is refused. Reading
|
|
393
|
+
* tolerates a document mid-edit; writing splices text in by AST offset, and a
|
|
394
|
+
* best-guess tree recovered from a syntax error must never decide where.
|
|
395
|
+
*/
|
|
396
|
+
function parseStrict(code) {
|
|
397
|
+
const ast = parseSource(code);
|
|
398
|
+
if (!ast) return null;
|
|
399
|
+
return ast.errors && ast.errors.length > 0 ? null : ast;
|
|
418
400
|
}
|
|
419
|
-
function
|
|
420
|
-
|
|
421
|
-
const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
|
|
422
|
-
if (!dir) return null;
|
|
423
|
-
const file = path.resolve(dir, filename);
|
|
424
|
-
if (!file.startsWith(dir + path.sep)) return null;
|
|
425
|
-
return file;
|
|
401
|
+
function isNode(value) {
|
|
402
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
426
403
|
}
|
|
427
|
-
/**
|
|
428
|
-
function
|
|
429
|
-
|
|
404
|
+
/** Depth-first walk over every node; the visitor decides what it cares about. */
|
|
405
|
+
function walkAst(node, visit) {
|
|
406
|
+
if (Array.isArray(node)) {
|
|
407
|
+
for (const child of node) walkAst(child, visit);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (!isNode(node)) return;
|
|
411
|
+
visit(node);
|
|
412
|
+
for (const key of Object.keys(node)) {
|
|
413
|
+
if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
|
|
414
|
+
walkAst(node[key], visit);
|
|
415
|
+
}
|
|
430
416
|
}
|
|
431
|
-
function
|
|
432
|
-
|
|
417
|
+
function walkJsx(ast, visit) {
|
|
418
|
+
walkAst(ast, (node) => {
|
|
419
|
+
if (node.type === "JSXElement") visit(node);
|
|
420
|
+
});
|
|
433
421
|
}
|
|
434
422
|
/**
|
|
435
|
-
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
423
|
+
* The JSX element whose opening tag starts at this source position.
|
|
424
|
+
*
|
|
425
|
+
* The match is exact on both line and column. Anything looser can resolve to a
|
|
426
|
+
* different element on the same line, and this location decides where an edit
|
|
427
|
+
* gets written — a near miss silently rewrites the wrong text.
|
|
438
428
|
*/
|
|
439
|
-
function
|
|
440
|
-
|
|
441
|
-
|
|
429
|
+
function findJsxAt(ast, line, column) {
|
|
430
|
+
let found = null;
|
|
431
|
+
walkJsx(ast, (node) => {
|
|
432
|
+
if (found) return;
|
|
433
|
+
const start = node.loc?.start;
|
|
434
|
+
if (start && start.line === line && start.column === column) found = node;
|
|
435
|
+
});
|
|
436
|
+
return found;
|
|
442
437
|
}
|
|
443
|
-
|
|
444
|
-
|
|
438
|
+
/**
|
|
439
|
+
* Every JSX element that starts on a line, nearest column first.
|
|
440
|
+
*
|
|
441
|
+
* Columns cannot be trusted for locations derived from React's `_debugSource`:
|
|
442
|
+
* injecting the loc attribute shifts the columns of anything later on the same
|
|
443
|
+
* line, so the offset differs per element. The line survives that, so callers
|
|
444
|
+
* scan the line and pick by content instead.
|
|
445
|
+
*/
|
|
446
|
+
function findJsxOnLine(ast, line, column) {
|
|
447
|
+
const hits = [];
|
|
448
|
+
walkJsx(ast, (node) => {
|
|
449
|
+
const start = node.loc?.start;
|
|
450
|
+
if (!start || start.line !== line) return;
|
|
451
|
+
hits.push({
|
|
452
|
+
node,
|
|
453
|
+
distance: Math.abs(start.column - column)
|
|
454
|
+
});
|
|
455
|
+
});
|
|
456
|
+
return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
|
|
445
457
|
}
|
|
446
458
|
//#endregion
|
|
447
|
-
//#region src/
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
459
|
+
//#region src/vite/loc-tags-plugin.ts
|
|
460
|
+
const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
|
|
461
|
+
"ImagePlaceholder",
|
|
462
|
+
"Figure",
|
|
463
|
+
"DataTable",
|
|
464
|
+
"Footnote"
|
|
465
|
+
]);
|
|
466
|
+
function taggableName(opening) {
|
|
467
|
+
const name = opening.name;
|
|
468
|
+
if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
|
|
469
|
+
if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
|
|
470
|
+
return null;
|
|
451
471
|
}
|
|
452
|
-
function
|
|
453
|
-
return
|
|
472
|
+
function alreadyTagged(opening) {
|
|
473
|
+
return (opening.attributes ?? []).some((attr) => {
|
|
474
|
+
if (attr.type !== "JSXAttribute") return false;
|
|
475
|
+
return attr.name?.name === "data-od-loc";
|
|
476
|
+
});
|
|
454
477
|
}
|
|
455
|
-
function
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
478
|
+
function injectLocTags(code) {
|
|
479
|
+
const ast = parseSource(code);
|
|
480
|
+
if (!ast) return null;
|
|
481
|
+
const insertions = [];
|
|
482
|
+
walkJsx(ast, (node) => {
|
|
483
|
+
const opening = node.openingElement;
|
|
484
|
+
if (!opening || !node.loc) return;
|
|
485
|
+
if (!taggableName(opening) || alreadyTagged(opening)) return;
|
|
486
|
+
const nameNode = opening.name;
|
|
487
|
+
insertions.push({
|
|
488
|
+
offset: nameNode.end,
|
|
489
|
+
text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
|
|
490
|
+
});
|
|
491
|
+
});
|
|
492
|
+
if (insertions.length === 0) return null;
|
|
493
|
+
insertions.sort((a, b) => b.offset - a.offset);
|
|
494
|
+
let next = code;
|
|
495
|
+
for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
|
|
496
|
+
return next;
|
|
459
497
|
}
|
|
460
|
-
function
|
|
461
|
-
const
|
|
462
|
-
if (
|
|
463
|
-
|
|
498
|
+
function isDocSourceFile(id, docsRootPosix) {
|
|
499
|
+
const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
|
|
500
|
+
if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
|
|
501
|
+
if (!filePath.endsWith(".tsx")) return false;
|
|
502
|
+
if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
|
|
503
|
+
return filePath.slice(docsRootPosix.length + 1).includes("/");
|
|
464
504
|
}
|
|
465
|
-
function
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
505
|
+
function locTagsPlugin(opts) {
|
|
506
|
+
const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
|
|
507
|
+
return {
|
|
508
|
+
name: "open-doc:loc-tags",
|
|
509
|
+
apply: "serve",
|
|
510
|
+
enforce: "pre",
|
|
511
|
+
transform(code, id) {
|
|
512
|
+
if (!isDocSourceFile(id, docsRoot)) return null;
|
|
513
|
+
const next = injectLocTags(code);
|
|
514
|
+
return next === null ? null : {
|
|
515
|
+
code: next,
|
|
516
|
+
map: null
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
};
|
|
472
520
|
}
|
|
521
|
+
//#endregion
|
|
522
|
+
//#region src/ops/changes-diff.ts
|
|
523
|
+
const REVIEW_MARKER = /^\s*\{\/\*\s*@doc-comment\s.*\*\/\}\s*$/;
|
|
473
524
|
/**
|
|
474
|
-
*
|
|
475
|
-
*
|
|
525
|
+
* Drops hunks that only add or remove review comments. A comment is a marker
|
|
526
|
+
* in the source, but it is a note about the document, not a change to it —
|
|
527
|
+
* counting it would put every note left in review on the changes list too.
|
|
476
528
|
*/
|
|
477
|
-
function
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
const
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
error: "invalid origin header"
|
|
529
|
+
function withoutReviewMarkers(files) {
|
|
530
|
+
return files.map((file) => ({
|
|
531
|
+
...file,
|
|
532
|
+
hunks: file.hunks.filter((hunk) => ![...hunk.removed, ...hunk.added].every((line) => REVIEW_MARKER.test(line)))
|
|
533
|
+
}));
|
|
534
|
+
}
|
|
535
|
+
const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
|
|
536
|
+
function hunkId(file, oldStart, removed, added) {
|
|
537
|
+
return createHash("sha1").update(`${file}\0${oldStart}\0${removed.join("\n")}\0${added.join("\n")}`).digest("hex").slice(0, 12);
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* `git diff --unified=0 --relative` output, file by file. Paths come back
|
|
541
|
+
* relative to `prefix` — the document's folder — and anything outside it is
|
|
542
|
+
* dropped.
|
|
543
|
+
*/
|
|
544
|
+
function parseUnifiedDiff(text, prefix) {
|
|
545
|
+
const files = [];
|
|
546
|
+
let file = null;
|
|
547
|
+
let hunk = null;
|
|
548
|
+
let oldPath = null;
|
|
549
|
+
const strip = (raw) => {
|
|
550
|
+
if (raw === "/dev/null") return null;
|
|
551
|
+
const path = raw.replace(/^[ab]\//, "");
|
|
552
|
+
return path.startsWith(prefix) ? path.slice(prefix.length) : null;
|
|
502
553
|
};
|
|
503
|
-
const
|
|
554
|
+
for (const line of text.split("\n")) {
|
|
555
|
+
if (line.startsWith("diff --git ")) {
|
|
556
|
+
file = null;
|
|
557
|
+
hunk = null;
|
|
558
|
+
oldPath = null;
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (line.startsWith("--- ")) {
|
|
562
|
+
oldPath = line.slice(4);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (line.startsWith("+++ ")) {
|
|
566
|
+
const before = oldPath === null ? null : strip(oldPath);
|
|
567
|
+
const path = strip(line.slice(4)) ?? before;
|
|
568
|
+
if (path === null) continue;
|
|
569
|
+
file = {
|
|
570
|
+
path,
|
|
571
|
+
status: oldPath === "/dev/null" ? "added" : line.slice(4) === "/dev/null" ? "deleted" : "modified",
|
|
572
|
+
binary: false,
|
|
573
|
+
hunks: []
|
|
574
|
+
};
|
|
575
|
+
files.push(file);
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
if (line.startsWith("Binary files ")) {
|
|
579
|
+
const match = / and (\S+) differ$/.exec(line);
|
|
580
|
+
const path = match ? strip(match[1]) : null;
|
|
581
|
+
if (path !== null) files.push({
|
|
582
|
+
path,
|
|
583
|
+
status: "modified",
|
|
584
|
+
binary: true,
|
|
585
|
+
hunks: []
|
|
586
|
+
});
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
const header = HUNK_HEADER.exec(line);
|
|
590
|
+
if (header && file) {
|
|
591
|
+
hunk = {
|
|
592
|
+
id: "",
|
|
593
|
+
oldStart: Number(header[1]),
|
|
594
|
+
oldLines: header[2] === void 0 ? 1 : Number(header[2]),
|
|
595
|
+
newStart: Number(header[3]),
|
|
596
|
+
newLines: header[4] === void 0 ? 1 : Number(header[4]),
|
|
597
|
+
removed: [],
|
|
598
|
+
added: [],
|
|
599
|
+
targets: []
|
|
600
|
+
};
|
|
601
|
+
file.hunks.push(hunk);
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (!hunk || !file) continue;
|
|
605
|
+
if (line.startsWith("-")) hunk.removed.push(line.slice(1));
|
|
606
|
+
else if (line.startsWith("+")) hunk.added.push(line.slice(1));
|
|
607
|
+
}
|
|
608
|
+
for (const changed of files) for (const h of changed.hunks) h.id = hunkId(changed.path, h.oldStart, h.removed, h.added);
|
|
609
|
+
return files;
|
|
610
|
+
}
|
|
611
|
+
/** A file that git does not know yet: one hunk that adds every line. */
|
|
612
|
+
function untrackedFile(path, source) {
|
|
613
|
+
const lines = source.endsWith("\n") ? source.slice(0, -1).split("\n") : source.split("\n");
|
|
614
|
+
return {
|
|
615
|
+
path,
|
|
616
|
+
status: "added",
|
|
617
|
+
binary: false,
|
|
618
|
+
hunks: [{
|
|
619
|
+
id: hunkId(path, 0, [], lines),
|
|
620
|
+
oldStart: 0,
|
|
621
|
+
oldLines: 0,
|
|
622
|
+
newStart: 1,
|
|
623
|
+
newLines: lines.length,
|
|
624
|
+
removed: [],
|
|
625
|
+
added: lines,
|
|
626
|
+
targets: []
|
|
627
|
+
}]
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
/** Every element the loc-tags plugin stamps, with its extent in the source. */
|
|
631
|
+
function taggedElements(ast) {
|
|
632
|
+
const out = [];
|
|
633
|
+
walkJsx(ast, (node) => {
|
|
634
|
+
const opening = node.openingElement;
|
|
635
|
+
if (!opening || !node.loc || !taggableName(opening)) return;
|
|
636
|
+
out.push({
|
|
637
|
+
loc: `${node.loc.start.line}:${node.loc.start.column}`,
|
|
638
|
+
line: node.loc.start.line,
|
|
639
|
+
endLine: node.loc.end.line,
|
|
640
|
+
start: node.start,
|
|
641
|
+
end: node.end
|
|
642
|
+
});
|
|
643
|
+
});
|
|
644
|
+
return out;
|
|
645
|
+
}
|
|
646
|
+
const contains = (outer, inner) => outer !== inner && outer.start <= inner.start && outer.end >= inner.end;
|
|
647
|
+
function innermost(elements, from, to) {
|
|
648
|
+
let best = null;
|
|
649
|
+
for (const el of elements) {
|
|
650
|
+
if (el.line > from || el.endLine < to) continue;
|
|
651
|
+
if (!best || contains(best, el)) best = el;
|
|
652
|
+
}
|
|
653
|
+
return best;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Puts each hunk of the document's own source on the elements it touches.
|
|
657
|
+
* Elements that start inside the hunk are the change, outermost first; a
|
|
658
|
+
* hunk inside one element's text marks that element; a deletion marks the
|
|
659
|
+
* element that now stands where the removed lines were.
|
|
660
|
+
*/
|
|
661
|
+
function placeHunks(source, hunks) {
|
|
662
|
+
const ast = parseSource(source);
|
|
663
|
+
if (!ast) return;
|
|
664
|
+
const elements = taggedElements(ast);
|
|
665
|
+
for (const hunk of hunks) {
|
|
666
|
+
if (hunk.newLines === 0) {
|
|
667
|
+
const point = hunk.newStart;
|
|
668
|
+
const parent = innermost(elements, point, point + 1);
|
|
669
|
+
const next = elements.find((el) => el.line > point && (!parent || contains(parent, el)) && !elements.some((other) => other !== el && other.line > point && contains(other, el) && (!parent || contains(parent, other))));
|
|
670
|
+
if (next) hunk.targets = [{
|
|
671
|
+
loc: next.loc,
|
|
672
|
+
mark: "removed-before"
|
|
673
|
+
}];
|
|
674
|
+
else if (parent) hunk.targets = [{
|
|
675
|
+
loc: parent.loc,
|
|
676
|
+
mark: "changed"
|
|
677
|
+
}];
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
const from = hunk.newStart;
|
|
681
|
+
const to = hunk.newStart + hunk.newLines - 1;
|
|
682
|
+
const mark = hunk.oldLines === 0 ? "added" : "changed";
|
|
683
|
+
const starting = elements.filter((el) => el.line >= from && el.line <= to);
|
|
684
|
+
const outermost = starting.filter((el) => !starting.some((other) => contains(other, el)));
|
|
685
|
+
if (outermost.length > 0) {
|
|
686
|
+
hunk.targets = outermost.map((el) => ({
|
|
687
|
+
loc: el.loc,
|
|
688
|
+
mark
|
|
689
|
+
}));
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
const around = innermost(elements, from, to);
|
|
693
|
+
if (around) hunk.targets = [{
|
|
694
|
+
loc: around.loc,
|
|
695
|
+
mark: "changed"
|
|
696
|
+
}];
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* The file with one hunk taken back. The lines the hunk added have to still be
|
|
701
|
+
* where it put them — otherwise the file moved on since the viewer looked, and
|
|
702
|
+
* the revert is refused rather than guessed.
|
|
703
|
+
*/
|
|
704
|
+
function revertHunkIn(source, hunk) {
|
|
705
|
+
const trailing = source.endsWith("\n");
|
|
706
|
+
const lines = (trailing ? source.slice(0, -1) : source).split("\n");
|
|
707
|
+
const at = hunk.newLines === 0 ? hunk.newStart : hunk.newStart - 1;
|
|
708
|
+
const current = lines.slice(at, at + hunk.newLines);
|
|
709
|
+
if (current.length !== hunk.added.length || current.some((line, i) => line !== hunk.added[i])) return null;
|
|
710
|
+
lines.splice(at, hunk.newLines, ...hunk.removed);
|
|
711
|
+
const next = lines.join("\n");
|
|
712
|
+
return trailing || next === "" ? `${next}\n` : next;
|
|
713
|
+
}
|
|
714
|
+
//#endregion
|
|
715
|
+
//#region src/editing/doc-ops.ts
|
|
716
|
+
function programBody$1(ast) {
|
|
717
|
+
return ast.program?.body ?? [];
|
|
718
|
+
}
|
|
719
|
+
function metaObjectOf(node) {
|
|
720
|
+
if (node.type !== "ExportNamedDeclaration") return null;
|
|
721
|
+
const decl = node.declaration;
|
|
722
|
+
if (decl?.type !== "VariableDeclaration") return null;
|
|
723
|
+
const declarations = decl.declarations ?? [];
|
|
724
|
+
for (const d of declarations) {
|
|
725
|
+
const id = d.id;
|
|
726
|
+
if (id?.type !== "Identifier" || id.name !== "meta") continue;
|
|
727
|
+
let init = d.init;
|
|
728
|
+
if (!init) return null;
|
|
729
|
+
if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
|
|
730
|
+
const expr = init.expression;
|
|
731
|
+
if (expr) init = expr;
|
|
732
|
+
}
|
|
733
|
+
return init.type === "ObjectExpression" ? init : null;
|
|
734
|
+
}
|
|
735
|
+
return null;
|
|
736
|
+
}
|
|
737
|
+
function findMetaObject(ast) {
|
|
738
|
+
for (const node of programBody$1(ast)) {
|
|
739
|
+
const object = metaObjectOf(node);
|
|
740
|
+
if (object) return object;
|
|
741
|
+
}
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
744
|
+
function jsString$1(value) {
|
|
745
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
|
|
746
|
+
}
|
|
747
|
+
function validateDocTitle(v) {
|
|
748
|
+
if (typeof v !== "string") return null;
|
|
749
|
+
const trimmed = v.trim();
|
|
750
|
+
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
751
|
+
return trimmed;
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Rewrites `meta.title` in place, adding the property when the meta object
|
|
755
|
+
* exists without one. Returns null when there is no meta object to edit —
|
|
756
|
+
* the caller reports that rather than inventing an export.
|
|
757
|
+
*/
|
|
758
|
+
function setMetaTitle(source, title) {
|
|
759
|
+
return setMetaString(source, "title", title);
|
|
760
|
+
}
|
|
761
|
+
/** Sets one string field of `export const meta`, adding it first when it is missing. */
|
|
762
|
+
function setMetaString(source, field, value) {
|
|
763
|
+
const ast = parseStrict(source);
|
|
764
|
+
if (!ast) return null;
|
|
765
|
+
const object = findMetaObject(ast);
|
|
766
|
+
if (!object) return null;
|
|
767
|
+
const properties = object.properties ?? [];
|
|
768
|
+
for (const prop of properties) {
|
|
769
|
+
if (prop.type !== "ObjectProperty") continue;
|
|
770
|
+
const p = prop;
|
|
771
|
+
if (p.computed) continue;
|
|
772
|
+
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== field) continue;
|
|
773
|
+
return source.slice(0, p.value.start) + jsString$1(value) + source.slice(p.value.end);
|
|
774
|
+
}
|
|
775
|
+
const open = object.start + 1;
|
|
776
|
+
const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n ${field}: ${jsString$1(value)},\n` : `\n ${field}: ${jsString$1(value)},`;
|
|
777
|
+
return source.slice(0, open) + inserted + source.slice(open);
|
|
778
|
+
}
|
|
779
|
+
function readMetaTitle(source) {
|
|
780
|
+
const ast = parseSource(source);
|
|
781
|
+
if (!ast) return null;
|
|
782
|
+
const object = findMetaObject(ast);
|
|
783
|
+
if (!object) return null;
|
|
784
|
+
const properties = object.properties ?? [];
|
|
785
|
+
for (const prop of properties) {
|
|
786
|
+
if (prop.type !== "ObjectProperty") continue;
|
|
787
|
+
const p = prop;
|
|
788
|
+
if (p.computed) continue;
|
|
789
|
+
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
|
|
790
|
+
if (p.value.type !== "StringLiteral") return null;
|
|
791
|
+
return typeof p.value.value === "string" ? p.value.value : null;
|
|
792
|
+
}
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
/** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
|
|
796
|
+
function nextCopyId(baseId, taken) {
|
|
797
|
+
const stem = baseId.replace(/-copy(-\d+)?$/, "");
|
|
798
|
+
let candidate = `${stem}-copy`;
|
|
799
|
+
let n = 2;
|
|
800
|
+
while (taken.has(candidate)) {
|
|
801
|
+
candidate = `${stem}-copy-${n}`;
|
|
802
|
+
n++;
|
|
803
|
+
}
|
|
804
|
+
return candidate;
|
|
805
|
+
}
|
|
806
|
+
function copyTitle(title) {
|
|
807
|
+
return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
|
|
808
|
+
}
|
|
809
|
+
//#endregion
|
|
810
|
+
//#region src/files/folders.ts
|
|
811
|
+
const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
|
|
812
|
+
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
|
813
|
+
function emptyManifest() {
|
|
814
|
+
return {
|
|
815
|
+
folders: [],
|
|
816
|
+
assignments: {}
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
async function readManifest(file) {
|
|
820
|
+
try {
|
|
821
|
+
const raw = await fs.readFile(file, "utf8");
|
|
822
|
+
const parsed = JSON.parse(raw);
|
|
823
|
+
return {
|
|
824
|
+
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
|
825
|
+
assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
|
|
826
|
+
};
|
|
827
|
+
} catch (err) {
|
|
828
|
+
if (err.code === "ENOENT") return emptyManifest();
|
|
829
|
+
throw err;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
async function writeManifest(file, manifest) {
|
|
833
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
834
|
+
await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
835
|
+
}
|
|
836
|
+
function newFolderId() {
|
|
837
|
+
return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
838
|
+
}
|
|
839
|
+
function validateName(v) {
|
|
840
|
+
if (typeof v !== "string") return null;
|
|
841
|
+
const trimmed = v.trim();
|
|
842
|
+
if (trimmed.length < 1 || trimmed.length > 40) return null;
|
|
843
|
+
return trimmed;
|
|
844
|
+
}
|
|
845
|
+
function validateReorder(v, current) {
|
|
846
|
+
if (!Array.isArray(v) || v.length !== current.length) return null;
|
|
847
|
+
const known = new Set(current.map((f) => f.id));
|
|
848
|
+
const seen = /* @__PURE__ */ new Set();
|
|
849
|
+
const out = [];
|
|
850
|
+
for (const id of v) {
|
|
851
|
+
if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
|
|
852
|
+
if (!known.has(id) || seen.has(id)) return null;
|
|
853
|
+
seen.add(id);
|
|
854
|
+
out.push(id);
|
|
855
|
+
}
|
|
856
|
+
return out;
|
|
857
|
+
}
|
|
858
|
+
function validateIcon(v) {
|
|
859
|
+
if (!v || typeof v !== "object") return null;
|
|
860
|
+
const icon = v;
|
|
861
|
+
if (icon.type === "emoji") {
|
|
862
|
+
if (typeof icon.value !== "string") return null;
|
|
863
|
+
if (icon.value.length < 1 || icon.value.length > 8) return null;
|
|
864
|
+
return {
|
|
865
|
+
type: "emoji",
|
|
866
|
+
value: icon.value
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
if (icon.type === "color") {
|
|
870
|
+
if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
|
|
871
|
+
return {
|
|
872
|
+
type: "color",
|
|
873
|
+
value: icon.value
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
//#endregion
|
|
879
|
+
//#region src/ops/documents.ts
|
|
880
|
+
/**
|
|
881
|
+
* Operations shared by the dev API and the MCP server. Everything here takes an
|
|
882
|
+
* `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
|
|
883
|
+
* and a browser calling `/__docs` end up in exactly the same code.
|
|
884
|
+
*/
|
|
885
|
+
var OpsError = class extends Error {
|
|
886
|
+
status;
|
|
887
|
+
constructor(status, message) {
|
|
888
|
+
super(message);
|
|
889
|
+
this.status = status;
|
|
890
|
+
this.name = "OpsError";
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
const ENTRY_NAMES = [
|
|
894
|
+
"index.tsx",
|
|
895
|
+
"index.jsx",
|
|
896
|
+
"index.ts",
|
|
897
|
+
"index.js"
|
|
898
|
+
];
|
|
899
|
+
function docDir(ctx, docId) {
|
|
900
|
+
if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
901
|
+
const dir = path.resolve(ctx.docsRoot, docId);
|
|
902
|
+
if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
903
|
+
return dir;
|
|
904
|
+
}
|
|
905
|
+
function resolveEntry(ctx, docId) {
|
|
906
|
+
const dir = docDir(ctx, docId);
|
|
907
|
+
for (const name of ENTRY_NAMES) {
|
|
908
|
+
const file = path.join(dir, name);
|
|
909
|
+
if (existsSync(file)) return file;
|
|
910
|
+
}
|
|
911
|
+
return null;
|
|
912
|
+
}
|
|
913
|
+
async function listDocIds$1(ctx) {
|
|
914
|
+
try {
|
|
915
|
+
return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
916
|
+
} catch {
|
|
917
|
+
return [];
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
/** Reads what the doc declares without executing it — a regex over `export const meta`. */
|
|
921
|
+
function readMetaField(source, field) {
|
|
922
|
+
const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
|
|
923
|
+
return source.slice(source.indexOf("export const meta")).match(re)?.[2];
|
|
924
|
+
}
|
|
925
|
+
async function listDocuments(ctx) {
|
|
926
|
+
const ids = await listDocIds$1(ctx);
|
|
927
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
928
|
+
const out = [];
|
|
929
|
+
for (const id of ids) {
|
|
930
|
+
const entry = resolveEntry(ctx, id);
|
|
931
|
+
const source = entry ? await fs.readFile(entry, "utf8") : "";
|
|
932
|
+
out.push({
|
|
933
|
+
id,
|
|
934
|
+
title: source ? readMetaTitle(source) : null,
|
|
935
|
+
subtitle: source ? readMetaField(source, "subtitle") : void 0,
|
|
936
|
+
theme: source ? readMetaField(source, "theme") : void 0,
|
|
937
|
+
createdAt: source ? readMetaField(source, "createdAt") : void 0,
|
|
938
|
+
folder: manifest.assignments[id],
|
|
939
|
+
entry: entry ? path.relative(ctx.userCwd, entry) : null
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
return out;
|
|
943
|
+
}
|
|
944
|
+
async function readDocument(ctx, docId) {
|
|
945
|
+
const entry = resolveEntry(ctx, docId);
|
|
946
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
947
|
+
return {
|
|
948
|
+
id: docId,
|
|
949
|
+
entry: path.relative(ctx.userCwd, entry),
|
|
950
|
+
source: await fs.readFile(entry, "utf8")
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
async function createDocument(ctx, docId, source) {
|
|
954
|
+
const dir = docDir(ctx, docId);
|
|
955
|
+
if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
|
|
956
|
+
await fs.mkdir(dir, { recursive: true });
|
|
957
|
+
const entry = path.join(dir, "index.tsx");
|
|
958
|
+
await fs.writeFile(entry, source, "utf8");
|
|
959
|
+
return {
|
|
960
|
+
id: docId,
|
|
961
|
+
entry: path.relative(ctx.userCwd, entry)
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Whole-file overwrite. `expected` is the source the caller believes is on
|
|
966
|
+
* disk; passing it turns a blind overwrite into a conflict check, which is what
|
|
967
|
+
* keeps two agents (or an agent and a person) from clobbering each other.
|
|
968
|
+
*/
|
|
969
|
+
async function writeDocument(ctx, docId, source, expected) {
|
|
970
|
+
const entry = resolveEntry(ctx, docId);
|
|
971
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
972
|
+
if (expected !== void 0) {
|
|
973
|
+
if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
|
|
974
|
+
}
|
|
975
|
+
await fs.writeFile(entry, source, "utf8");
|
|
976
|
+
return {
|
|
977
|
+
id: docId,
|
|
978
|
+
entry: path.relative(ctx.userCwd, entry)
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
async function renameDocument(ctx, docId, rawTitle) {
|
|
982
|
+
const title = validateDocTitle(rawTitle);
|
|
983
|
+
if (!title) throw new OpsError(400, "invalid title");
|
|
984
|
+
const entry = resolveEntry(ctx, docId);
|
|
985
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
986
|
+
const source = await fs.readFile(entry, "utf8");
|
|
987
|
+
const next = setMetaTitle(source, title);
|
|
988
|
+
if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
|
|
989
|
+
if (next !== source) await fs.writeFile(entry, next, "utf8");
|
|
990
|
+
return {
|
|
991
|
+
id: docId,
|
|
992
|
+
title
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
async function duplicateDocument(ctx, docId, newId) {
|
|
996
|
+
const dir = docDir(ctx, docId);
|
|
997
|
+
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
998
|
+
const taken = new Set(await listDocIds$1(ctx));
|
|
999
|
+
let targetId;
|
|
1000
|
+
if (newId) {
|
|
1001
|
+
if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
|
|
1002
|
+
if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
|
|
1003
|
+
targetId = newId;
|
|
1004
|
+
} else targetId = nextCopyId(docId, taken);
|
|
1005
|
+
await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
|
|
1006
|
+
const entry = resolveEntry(ctx, targetId);
|
|
1007
|
+
if (entry) {
|
|
1008
|
+
const source = await fs.readFile(entry, "utf8");
|
|
1009
|
+
const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
|
|
1010
|
+
if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
|
|
1011
|
+
}
|
|
1012
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1013
|
+
const folderId = manifest.assignments[docId];
|
|
1014
|
+
if (folderId) {
|
|
1015
|
+
manifest.assignments[targetId] = folderId;
|
|
1016
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1017
|
+
}
|
|
1018
|
+
return { id: targetId };
|
|
1019
|
+
}
|
|
1020
|
+
async function deleteDocument(ctx, docId) {
|
|
1021
|
+
const dir = docDir(ctx, docId);
|
|
1022
|
+
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
1023
|
+
await fs.rm(dir, {
|
|
1024
|
+
recursive: true,
|
|
1025
|
+
force: true
|
|
1026
|
+
});
|
|
1027
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1028
|
+
if (manifest.assignments[docId]) {
|
|
1029
|
+
delete manifest.assignments[docId];
|
|
1030
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
//#endregion
|
|
1034
|
+
//#region src/ops/changes.ts
|
|
1035
|
+
const run = promisify(execFile);
|
|
1036
|
+
async function git(cwd, args) {
|
|
1037
|
+
const { stdout } = await run("git", args, {
|
|
1038
|
+
cwd,
|
|
1039
|
+
maxBuffer: 33554432
|
|
1040
|
+
});
|
|
1041
|
+
return stdout;
|
|
1042
|
+
}
|
|
1043
|
+
/** The document folder relative to the workspace, POSIX-style, with a trailing slash. */
|
|
1044
|
+
function folderOf(ctx, docId) {
|
|
1045
|
+
return `${path.relative(ctx.userCwd, path.join(ctx.docsRoot, docId)).split(path.sep).join("/")}/`;
|
|
1046
|
+
}
|
|
1047
|
+
async function inRepo(ctx) {
|
|
1048
|
+
try {
|
|
1049
|
+
return (await git(ctx.userCwd, ["rev-parse", "--is-inside-work-tree"])).trim() === "true" ? "yes" : "no-repo";
|
|
1050
|
+
} catch (err) {
|
|
1051
|
+
return err.code === "ENOENT" ? "no-git" : "no-repo";
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* What changed in one document's folder since a revision — the working tree
|
|
1056
|
+
* against `since`, untracked files included — with each hunk of the document's
|
|
1057
|
+
* own source placed on the elements it touches, so the viewer can mark them.
|
|
1058
|
+
*/
|
|
1059
|
+
async function readChanges(ctx, docId, since = "HEAD") {
|
|
1060
|
+
const entry = resolveEntry(ctx, docId);
|
|
1061
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1062
|
+
const repo = await inRepo(ctx);
|
|
1063
|
+
if (repo !== "yes") return {
|
|
1064
|
+
available: false,
|
|
1065
|
+
reason: repo
|
|
1066
|
+
};
|
|
1067
|
+
const folder = folderOf(ctx, docId);
|
|
1068
|
+
let commit = null;
|
|
1069
|
+
try {
|
|
1070
|
+
commit = (await git(ctx.userCwd, [
|
|
1071
|
+
"rev-parse",
|
|
1072
|
+
"--verify",
|
|
1073
|
+
"--quiet",
|
|
1074
|
+
`${since}^{commit}`
|
|
1075
|
+
])).trim();
|
|
1076
|
+
} catch {
|
|
1077
|
+
if (since !== "HEAD") throw new OpsError(400, `not a revision in this repository: ${since}`);
|
|
1078
|
+
}
|
|
1079
|
+
let files = commit ? parseUnifiedDiff(await git(ctx.userCwd, [
|
|
1080
|
+
"diff",
|
|
1081
|
+
"--unified=0",
|
|
1082
|
+
"--no-color",
|
|
1083
|
+
"--no-ext-diff",
|
|
1084
|
+
"--relative",
|
|
1085
|
+
commit,
|
|
1086
|
+
"--",
|
|
1087
|
+
folder
|
|
1088
|
+
]), folder) : [];
|
|
1089
|
+
const untracked = (await git(ctx.userCwd, [
|
|
1090
|
+
"ls-files",
|
|
1091
|
+
"--others",
|
|
1092
|
+
"--exclude-standard",
|
|
1093
|
+
"--",
|
|
1094
|
+
folder
|
|
1095
|
+
])).split("\n").filter((file) => file.startsWith(folder));
|
|
1096
|
+
for (const file of untracked) {
|
|
1097
|
+
const rel = file.slice(folder.length);
|
|
1098
|
+
const buffer = await fs.readFile(path.join(ctx.userCwd, file));
|
|
1099
|
+
files.push(buffer.includes(0) ? {
|
|
1100
|
+
path: rel,
|
|
1101
|
+
status: "added",
|
|
1102
|
+
binary: true,
|
|
1103
|
+
hunks: []
|
|
1104
|
+
} : untrackedFile(rel, buffer.toString("utf8")));
|
|
1105
|
+
}
|
|
1106
|
+
files = withoutReviewMarkers(files);
|
|
1107
|
+
const own = files.find((file) => file.path === path.basename(entry));
|
|
1108
|
+
if (own && !own.binary) placeHunks(await fs.readFile(entry, "utf8"), own.hunks);
|
|
1109
|
+
files.sort((a, b) => a === own ? -1 : b === own ? 1 : a.path.localeCompare(b.path));
|
|
1110
|
+
return {
|
|
1111
|
+
available: true,
|
|
1112
|
+
since,
|
|
1113
|
+
commit,
|
|
1114
|
+
files
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
/** Recent commits that touched the document, newest first, for choosing what to compare against. */
|
|
1118
|
+
async function listRevisions(ctx, docId, limit = 15) {
|
|
1119
|
+
if (!resolveEntry(ctx, docId)) throw new OpsError(404, `document not found: ${docId}`);
|
|
1120
|
+
if (await inRepo(ctx) !== "yes") return [];
|
|
1121
|
+
try {
|
|
1122
|
+
return (await git(ctx.userCwd, [
|
|
1123
|
+
"log",
|
|
1124
|
+
`-n${limit}`,
|
|
1125
|
+
"--format=%H%x1f%h%x1f%s%x1f%cr",
|
|
1126
|
+
"--",
|
|
1127
|
+
folderOf(ctx, docId)
|
|
1128
|
+
])).split("\n").filter(Boolean).map((line) => {
|
|
1129
|
+
const [commit = "", short = "", subject = "", when = ""] = line.split("");
|
|
1130
|
+
return {
|
|
1131
|
+
commit,
|
|
1132
|
+
short,
|
|
1133
|
+
subject,
|
|
1134
|
+
when
|
|
1135
|
+
};
|
|
1136
|
+
});
|
|
1137
|
+
} catch {
|
|
1138
|
+
return [];
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Takes one hunk back out of the working tree. The hunk is found again by id
|
|
1143
|
+
* in a fresh diff, never trusted from the request, and a source file must still
|
|
1144
|
+
* parse afterwards — hunks can depend on each other, and a revert that leaves
|
|
1145
|
+
* half a JSX tag behind is refused rather than written.
|
|
1146
|
+
*/
|
|
1147
|
+
async function revertChange(ctx, docId, opts) {
|
|
1148
|
+
const changes = await readChanges(ctx, docId, opts.since);
|
|
1149
|
+
if (!changes.available) throw new OpsError(409, "this workspace is not under git");
|
|
1150
|
+
const file = changes.files.find((candidate) => candidate.path === opts.file);
|
|
1151
|
+
const hunk = file?.hunks.find((candidate) => candidate.id === opts.hunk);
|
|
1152
|
+
if (!file || !hunk) throw new OpsError(409, "that change is no longer there — reload the changes");
|
|
1153
|
+
if (file.binary) throw new OpsError(422, "a binary file cannot be reverted here");
|
|
1154
|
+
const target = path.join(ctx.docsRoot, docId, file.path);
|
|
1155
|
+
const next = revertHunkIn(await fs.readFile(target, "utf8"), hunk);
|
|
1156
|
+
if (next === null) throw new OpsError(409, "the file changed since the diff was read");
|
|
1157
|
+
if (/\.(tsx?|jsx?)$/.test(file.path) && !parseStrict(next)) throw new OpsError(422, "reverting this change alone would break the source — revert the changes around it too");
|
|
1158
|
+
await fs.writeFile(target, next, "utf8");
|
|
1159
|
+
return { ok: true };
|
|
1160
|
+
}
|
|
1161
|
+
//#endregion
|
|
1162
|
+
//#region src/files/assets.ts
|
|
1163
|
+
const GLOBAL_SCOPE = "@global";
|
|
1164
|
+
const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
|
|
1165
|
+
const MIME_BY_EXT = {
|
|
1166
|
+
png: "image/png",
|
|
1167
|
+
jpg: "image/jpeg",
|
|
1168
|
+
jpeg: "image/jpeg",
|
|
1169
|
+
gif: "image/gif",
|
|
1170
|
+
svg: "image/svg+xml",
|
|
1171
|
+
webp: "image/webp",
|
|
1172
|
+
avif: "image/avif",
|
|
1173
|
+
ico: "image/x-icon",
|
|
1174
|
+
pdf: "application/pdf",
|
|
1175
|
+
woff: "font/woff",
|
|
1176
|
+
woff2: "font/woff2",
|
|
1177
|
+
ttf: "font/ttf",
|
|
1178
|
+
otf: "font/otf",
|
|
1179
|
+
csv: "text/csv; charset=utf-8",
|
|
1180
|
+
json: "application/json",
|
|
1181
|
+
txt: "text/plain; charset=utf-8",
|
|
1182
|
+
md: "text/markdown; charset=utf-8"
|
|
1183
|
+
};
|
|
1184
|
+
function mimeForFilename(name) {
|
|
1185
|
+
const dot = name.lastIndexOf(".");
|
|
1186
|
+
if (dot < 0) return "application/octet-stream";
|
|
1187
|
+
return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
|
|
1188
|
+
}
|
|
1189
|
+
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
1190
|
+
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
1191
|
+
}
|
|
1192
|
+
function validateAssetName(v) {
|
|
1193
|
+
if (typeof v !== "string") return null;
|
|
1194
|
+
const trimmed = v.trim();
|
|
1195
|
+
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
1196
|
+
if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
|
|
1197
|
+
if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
|
|
1198
|
+
if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
|
|
1199
|
+
const dot = trimmed.lastIndexOf(".");
|
|
1200
|
+
if (dot <= 0 || dot === trimmed.length - 1) return null;
|
|
1201
|
+
return trimmed;
|
|
1202
|
+
}
|
|
1203
|
+
function resolveAssetsDir(docsRoot, docId) {
|
|
1204
|
+
if (!DOC_ID_RE.test(docId)) return null;
|
|
1205
|
+
const docDir = path.resolve(docsRoot, docId);
|
|
1206
|
+
if (!docDir.startsWith(docsRoot + path.sep)) return null;
|
|
1207
|
+
const assetsDir = path.resolve(docDir, "assets");
|
|
1208
|
+
if (assetsDir !== path.join(docDir, "assets")) return null;
|
|
1209
|
+
return assetsDir;
|
|
1210
|
+
}
|
|
1211
|
+
function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
|
|
1212
|
+
if (scope === "@global") return globalAssetsRoot;
|
|
1213
|
+
return resolveAssetsDir(docsRoot, scope);
|
|
1214
|
+
}
|
|
1215
|
+
function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
|
|
1216
|
+
if (!validateAssetName(filename)) return null;
|
|
1217
|
+
const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
|
|
1218
|
+
if (!dir) return null;
|
|
1219
|
+
const file = path.resolve(dir, filename);
|
|
1220
|
+
if (!file.startsWith(dir + path.sep)) return null;
|
|
1221
|
+
return file;
|
|
1222
|
+
}
|
|
1223
|
+
/** How a document imports an asset — the string we look for when counting usages. */
|
|
1224
|
+
function assetImportPath(scope, filename) {
|
|
1225
|
+
return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
|
|
1226
|
+
}
|
|
1227
|
+
function escapeRegExp(value) {
|
|
1228
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Counts references to an asset in a document's source. Matches the quoted path
|
|
1232
|
+
* in both import statements and `new URL('./assets/x.png', import.meta.url)`,
|
|
1233
|
+
* which is every form the authoring skill sanctions.
|
|
1234
|
+
*/
|
|
1235
|
+
function countAssetUsages(source, importPath) {
|
|
1236
|
+
const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
|
|
1237
|
+
return source.match(quoted)?.length ?? 0;
|
|
1238
|
+
}
|
|
1239
|
+
function findReferencedAssets(source, importPaths) {
|
|
1240
|
+
return importPaths.filter((p) => countAssetUsages(source, p) > 0);
|
|
1241
|
+
}
|
|
1242
|
+
//#endregion
|
|
1243
|
+
//#region src/http/request-guard.ts
|
|
1244
|
+
function firstHeaderValue(value) {
|
|
1245
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
1246
|
+
return value ?? null;
|
|
1247
|
+
}
|
|
1248
|
+
function headerValue(req, name) {
|
|
1249
|
+
return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
|
|
1250
|
+
}
|
|
1251
|
+
function firstCommaToken(value) {
|
|
1252
|
+
if (!value) return null;
|
|
1253
|
+
const [first] = value.split(",", 1);
|
|
1254
|
+
return first?.trim() || null;
|
|
1255
|
+
}
|
|
1256
|
+
function requestProto(req) {
|
|
1257
|
+
const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
|
|
1258
|
+
if (forwarded === "http" || forwarded === "https") return forwarded;
|
|
1259
|
+
return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
1260
|
+
}
|
|
1261
|
+
function normalizedOrigin(origin) {
|
|
1262
|
+
try {
|
|
1263
|
+
const url = new URL(origin);
|
|
1264
|
+
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
1265
|
+
} catch {
|
|
1266
|
+
return null;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* The dev server writes to the user's filesystem, so every mutating endpoint is
|
|
1271
|
+
* guarded against a page on another origin driving it through the browser.
|
|
1272
|
+
*/
|
|
1273
|
+
function validateMutationRequest(req, opts = {}) {
|
|
1274
|
+
if (opts.requireJsonBody) {
|
|
1275
|
+
if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
|
|
1276
|
+
ok: false,
|
|
1277
|
+
status: 415,
|
|
1278
|
+
error: "content-type must be application/json"
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
|
|
1282
|
+
ok: false,
|
|
1283
|
+
status: 403,
|
|
1284
|
+
error: "cross-site request blocked"
|
|
1285
|
+
};
|
|
1286
|
+
const originRaw = headerValue(req, "origin");
|
|
1287
|
+
if (!originRaw) return { ok: true };
|
|
1288
|
+
if (originRaw.toLowerCase() === "null") return {
|
|
1289
|
+
ok: false,
|
|
1290
|
+
status: 403,
|
|
1291
|
+
error: "opaque origin is not allowed"
|
|
1292
|
+
};
|
|
1293
|
+
const actualOrigin = normalizedOrigin(originRaw);
|
|
1294
|
+
if (!actualOrigin) return {
|
|
1295
|
+
ok: false,
|
|
1296
|
+
status: 403,
|
|
1297
|
+
error: "invalid origin header"
|
|
1298
|
+
};
|
|
1299
|
+
const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
|
|
504
1300
|
if (!host) return {
|
|
505
1301
|
ok: false,
|
|
506
1302
|
status: 400,
|
|
@@ -515,7 +1311,7 @@ function validateMutationRequest(req, opts = {}) {
|
|
|
515
1311
|
}
|
|
516
1312
|
//#endregion
|
|
517
1313
|
//#region src/vite/routes/assets.ts
|
|
518
|
-
async function listDocIds
|
|
1314
|
+
async function listDocIds(docsRoot) {
|
|
519
1315
|
try {
|
|
520
1316
|
return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
|
|
521
1317
|
} catch {
|
|
@@ -546,7 +1342,7 @@ function registerAssetRoutes(server, ctx) {
|
|
|
546
1342
|
const isGlobal = scope === GLOBAL_SCOPE;
|
|
547
1343
|
if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
|
|
548
1344
|
const importPath = assetImportPath(scope, filename);
|
|
549
|
-
const docIds = isGlobal ? await listDocIds
|
|
1345
|
+
const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
|
|
550
1346
|
const usages = [];
|
|
551
1347
|
let totalCount = 0;
|
|
552
1348
|
for (const docId of docIds) {
|
|
@@ -595,7 +1391,7 @@ function registerAssetRoutes(server, ctx) {
|
|
|
595
1391
|
}
|
|
596
1392
|
assets.sort((a, b) => a.name.localeCompare(b.name));
|
|
597
1393
|
if (assets.length > 0) {
|
|
598
|
-
const scanIds = scope === "@global" ? await listDocIds
|
|
1394
|
+
const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
|
|
599
1395
|
const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
|
|
600
1396
|
const paths = assets.map((a) => a.importPath);
|
|
601
1397
|
for (const docId of scanIds) {
|
|
@@ -714,399 +1510,453 @@ function registerAssetRoutes(server, ctx) {
|
|
|
714
1510
|
});
|
|
715
1511
|
}
|
|
716
1512
|
//#endregion
|
|
717
|
-
//#region src/
|
|
718
|
-
function
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
}
|
|
739
|
-
|
|
740
|
-
|
|
1513
|
+
//#region src/vite/routes/changes.ts
|
|
1514
|
+
function registerChangesRoutes(server, ctx) {
|
|
1515
|
+
server.middlewares.use("/__changes", async (req, res, next) => {
|
|
1516
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
1517
|
+
const method = req.method ?? "GET";
|
|
1518
|
+
try {
|
|
1519
|
+
if (method === "GET" && url.pathname === "/") return json(res, 200, await readChanges(ctx, url.searchParams.get("docId") ?? "", url.searchParams.get("since") || "HEAD"));
|
|
1520
|
+
if (method === "GET" && url.pathname === "/revisions") return json(res, 200, { revisions: await listRevisions(ctx, url.searchParams.get("docId") ?? "") });
|
|
1521
|
+
if (method === "POST" && url.pathname === "/revert") {
|
|
1522
|
+
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
1523
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1524
|
+
const body = await readBody(req);
|
|
1525
|
+
if (typeof body.docId !== "string" || typeof body.file !== "string" || typeof body.hunk !== "string") return json(res, 400, { error: "invalid payload" });
|
|
1526
|
+
return json(res, 200, await revertChange(ctx, body.docId, {
|
|
1527
|
+
file: body.file,
|
|
1528
|
+
hunk: body.hunk,
|
|
1529
|
+
...typeof body.since === "string" ? { since: body.since } : {}
|
|
1530
|
+
}));
|
|
1531
|
+
}
|
|
1532
|
+
return next();
|
|
1533
|
+
} catch (err) {
|
|
1534
|
+
if (err instanceof OpsError) return json(res, err.status, { error: err.message });
|
|
1535
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
//#endregion
|
|
1540
|
+
//#region src/vite/themes-plugin.ts
|
|
1541
|
+
const THEMES_VMOD = "virtual:open-doc/themes";
|
|
1542
|
+
function resolved(id) {
|
|
1543
|
+
return `\0${id}`;
|
|
741
1544
|
}
|
|
742
|
-
|
|
743
|
-
function
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
1545
|
+
const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
|
|
1546
|
+
function parseFrontmatter(raw, themeId) {
|
|
1547
|
+
const match = raw.match(FM_RE);
|
|
1548
|
+
const fmText = match ? match[1] : "";
|
|
1549
|
+
const body = match ? match[2] : raw;
|
|
1550
|
+
const data = {};
|
|
1551
|
+
for (const line of fmText.split(/\r?\n/)) {
|
|
1552
|
+
const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
1553
|
+
if (!m) continue;
|
|
1554
|
+
let value = m[2].trim();
|
|
1555
|
+
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
1556
|
+
data[m[1]] = value;
|
|
753
1557
|
}
|
|
1558
|
+
return {
|
|
1559
|
+
fm: {
|
|
1560
|
+
name: data.name || themeId,
|
|
1561
|
+
description: data.description || "",
|
|
1562
|
+
pageSize: data.pageSize || "",
|
|
1563
|
+
mode: data.mode || ""
|
|
1564
|
+
},
|
|
1565
|
+
body: body.trim()
|
|
1566
|
+
};
|
|
754
1567
|
}
|
|
755
|
-
function
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
* The match is exact on both line and column. Anything looser can resolve to a
|
|
764
|
-
* different element on the same line, and this location decides where an edit
|
|
765
|
-
* gets written — a near miss silently rewrites the wrong text.
|
|
766
|
-
*/
|
|
767
|
-
function findJsxAt(ast, line, column) {
|
|
768
|
-
let found = null;
|
|
769
|
-
walkJsx(ast, (node) => {
|
|
770
|
-
if (found) return;
|
|
771
|
-
const start = node.loc?.start;
|
|
772
|
-
if (start && start.line === line && start.column === column) found = node;
|
|
773
|
-
});
|
|
774
|
-
return found;
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* Every JSX element that starts on a line, nearest column first.
|
|
778
|
-
*
|
|
779
|
-
* Columns cannot be trusted for locations derived from React's `_debugSource`:
|
|
780
|
-
* injecting the loc attribute shifts the columns of anything later on the same
|
|
781
|
-
* line, so the offset differs per element. The line survives that, so callers
|
|
782
|
-
* scan the line and pick by content instead.
|
|
783
|
-
*/
|
|
784
|
-
function findJsxOnLine(ast, line, column) {
|
|
785
|
-
const hits = [];
|
|
786
|
-
walkJsx(ast, (node) => {
|
|
787
|
-
const start = node.loc?.start;
|
|
788
|
-
if (!start || start.line !== line) return;
|
|
789
|
-
hits.push({
|
|
790
|
-
node,
|
|
791
|
-
distance: Math.abs(start.column - column)
|
|
792
|
-
});
|
|
793
|
-
});
|
|
794
|
-
return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
|
|
795
|
-
}
|
|
796
|
-
//#endregion
|
|
797
|
-
//#region src/editing/doc-ops.ts
|
|
798
|
-
function programBody$1(ast) {
|
|
799
|
-
return ast.program?.body ?? [];
|
|
1568
|
+
async function findThemes(userCwd, themesDir) {
|
|
1569
|
+
const abs = path.resolve(userCwd, themesDir);
|
|
1570
|
+
if (!existsSync(abs)) return [];
|
|
1571
|
+
return (await fg("*.md", {
|
|
1572
|
+
cwd: abs,
|
|
1573
|
+
absolute: true,
|
|
1574
|
+
onlyFiles: true
|
|
1575
|
+
})).sort();
|
|
800
1576
|
}
|
|
801
|
-
function
|
|
802
|
-
|
|
803
|
-
const
|
|
804
|
-
|
|
805
|
-
const
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
1577
|
+
async function readTheme$1(mdAbs, themesRoot) {
|
|
1578
|
+
const id = path.basename(mdAbs, ".md");
|
|
1579
|
+
const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
|
|
1580
|
+
let demoAbs = null;
|
|
1581
|
+
for (const cand of [
|
|
1582
|
+
`${id}.demo.tsx`,
|
|
1583
|
+
`${id}.demo.jsx`,
|
|
1584
|
+
`${id}.demo.ts`,
|
|
1585
|
+
`${id}.demo.js`
|
|
1586
|
+
]) {
|
|
1587
|
+
const p = path.join(themesRoot, cand);
|
|
1588
|
+
if (existsSync(p)) {
|
|
1589
|
+
demoAbs = p;
|
|
1590
|
+
break;
|
|
814
1591
|
}
|
|
815
|
-
return init.type === "ObjectExpression" ? init : null;
|
|
816
|
-
}
|
|
817
|
-
return null;
|
|
818
|
-
}
|
|
819
|
-
function findMetaObject(ast) {
|
|
820
|
-
for (const node of programBody$1(ast)) {
|
|
821
|
-
const object = metaObjectOf(node);
|
|
822
|
-
if (object) return object;
|
|
823
|
-
}
|
|
824
|
-
return null;
|
|
825
|
-
}
|
|
826
|
-
function jsString$1(value) {
|
|
827
|
-
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, " ")}'`;
|
|
828
|
-
}
|
|
829
|
-
function validateDocTitle(v) {
|
|
830
|
-
if (typeof v !== "string") return null;
|
|
831
|
-
const trimmed = v.trim();
|
|
832
|
-
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
833
|
-
return trimmed;
|
|
834
|
-
}
|
|
835
|
-
/**
|
|
836
|
-
* Rewrites `meta.title` in place, adding the property when the meta object
|
|
837
|
-
* exists without one. Returns null when there is no meta object to edit —
|
|
838
|
-
* the caller reports that rather than inventing an export.
|
|
839
|
-
*/
|
|
840
|
-
function setMetaTitle(source, title) {
|
|
841
|
-
const ast = parseStrict(source);
|
|
842
|
-
if (!ast) return null;
|
|
843
|
-
const object = findMetaObject(ast);
|
|
844
|
-
if (!object) return null;
|
|
845
|
-
const properties = object.properties ?? [];
|
|
846
|
-
for (const prop of properties) {
|
|
847
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
848
|
-
const p = prop;
|
|
849
|
-
if (p.computed) continue;
|
|
850
|
-
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
|
|
851
|
-
return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
|
|
852
|
-
}
|
|
853
|
-
const open = object.start + 1;
|
|
854
|
-
const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
|
|
855
|
-
return source.slice(0, open) + inserted + source.slice(open);
|
|
856
|
-
}
|
|
857
|
-
function readMetaTitle(source) {
|
|
858
|
-
const ast = parseSource(source);
|
|
859
|
-
if (!ast) return null;
|
|
860
|
-
const object = findMetaObject(ast);
|
|
861
|
-
if (!object) return null;
|
|
862
|
-
const properties = object.properties ?? [];
|
|
863
|
-
for (const prop of properties) {
|
|
864
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
865
|
-
const p = prop;
|
|
866
|
-
if (p.computed) continue;
|
|
867
|
-
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
|
|
868
|
-
if (p.value.type !== "StringLiteral") return null;
|
|
869
|
-
return typeof p.value.value === "string" ? p.value.value : null;
|
|
870
1592
|
}
|
|
871
|
-
return
|
|
1593
|
+
return {
|
|
1594
|
+
id,
|
|
1595
|
+
frontmatter: fm,
|
|
1596
|
+
body,
|
|
1597
|
+
demoAbs
|
|
1598
|
+
};
|
|
872
1599
|
}
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
1600
|
+
function generateThemesModule(themes, isDev) {
|
|
1601
|
+
const meta = themes.map((t) => ({
|
|
1602
|
+
id: t.id,
|
|
1603
|
+
name: t.frontmatter.name,
|
|
1604
|
+
description: t.frontmatter.description,
|
|
1605
|
+
pageSize: t.frontmatter.pageSize,
|
|
1606
|
+
mode: t.frontmatter.mode,
|
|
1607
|
+
body: t.body,
|
|
1608
|
+
hasDemo: t.demoAbs !== null
|
|
1609
|
+
}));
|
|
1610
|
+
const cases = themes.flatMap((t) => {
|
|
1611
|
+
const abs = t.demoAbs;
|
|
1612
|
+
if (!abs) return [];
|
|
1613
|
+
const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
|
|
1614
|
+
const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
|
|
1615
|
+
return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
|
|
1616
|
+
}).join("\n");
|
|
1617
|
+
return `// virtual:open-doc/themes — generated
|
|
1618
|
+
export const themes = ${JSON.stringify(meta)};
|
|
1619
|
+
|
|
1620
|
+
export async function loadThemeDemo(id) {
|
|
1621
|
+
switch (id) {
|
|
1622
|
+
${cases}
|
|
1623
|
+
default: throw new Error('Theme demo not found: ' + id);
|
|
1624
|
+
}
|
|
883
1625
|
}
|
|
884
|
-
|
|
885
|
-
return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
|
|
1626
|
+
`;
|
|
886
1627
|
}
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
const
|
|
890
|
-
const
|
|
891
|
-
|
|
1628
|
+
function themesPlugin(opts) {
|
|
1629
|
+
const { userCwd, config } = opts;
|
|
1630
|
+
const themesDir = config.themesDir ?? "themes";
|
|
1631
|
+
const themesRoot = path.resolve(userCwd, themesDir);
|
|
1632
|
+
let isDev = false;
|
|
892
1633
|
return {
|
|
893
|
-
|
|
894
|
-
|
|
1634
|
+
name: "open-doc:themes",
|
|
1635
|
+
config(_c, env) {
|
|
1636
|
+
isDev = env.command === "serve";
|
|
1637
|
+
},
|
|
1638
|
+
resolveId(id) {
|
|
1639
|
+
if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
|
|
1640
|
+
return null;
|
|
1641
|
+
},
|
|
1642
|
+
async load(id) {
|
|
1643
|
+
if (id !== resolved(THEMES_VMOD)) return null;
|
|
1644
|
+
const files = await findThemes(userCwd, themesDir);
|
|
1645
|
+
return generateThemesModule(await Promise.all(files.map((f) => readTheme$1(f, themesRoot))), isDev);
|
|
1646
|
+
},
|
|
1647
|
+
configureServer(server) {
|
|
1648
|
+
const isThemeFile = (p) => {
|
|
1649
|
+
const rel = path.relative(themesRoot, p);
|
|
1650
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
|
|
1651
|
+
if (rel.includes(path.sep)) return false;
|
|
1652
|
+
return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
|
|
1653
|
+
};
|
|
1654
|
+
let reloadTimer = null;
|
|
1655
|
+
const reload = () => {
|
|
1656
|
+
if (reloadTimer) clearTimeout(reloadTimer);
|
|
1657
|
+
reloadTimer = setTimeout(() => {
|
|
1658
|
+
reloadTimer = null;
|
|
1659
|
+
const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
|
|
1660
|
+
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
1661
|
+
server.ws.send({ type: "full-reload" });
|
|
1662
|
+
}, 150);
|
|
1663
|
+
};
|
|
1664
|
+
server.watcher.add(themesRoot);
|
|
1665
|
+
for (const event of [
|
|
1666
|
+
"add",
|
|
1667
|
+
"unlink",
|
|
1668
|
+
"change"
|
|
1669
|
+
]) server.watcher.on(event, (p) => {
|
|
1670
|
+
if (isThemeFile(p)) reload();
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
895
1673
|
};
|
|
896
1674
|
}
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
return {
|
|
902
|
-
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
|
903
|
-
assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
|
|
904
|
-
};
|
|
905
|
-
} catch (err) {
|
|
906
|
-
if (err.code === "ENOENT") return emptyManifest();
|
|
907
|
-
throw err;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
async function writeManifest(file, manifest) {
|
|
911
|
-
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
912
|
-
await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
1675
|
+
//#endregion
|
|
1676
|
+
//#region src/ops/library.ts
|
|
1677
|
+
function themesRoot(ctx, themesDir = "themes") {
|
|
1678
|
+
return path.resolve(ctx.userCwd, themesDir);
|
|
913
1679
|
}
|
|
914
|
-
function
|
|
915
|
-
|
|
1680
|
+
async function themeFiles(root) {
|
|
1681
|
+
if (!existsSync(root)) return [];
|
|
1682
|
+
return (await fg("*.md", {
|
|
1683
|
+
cwd: root,
|
|
1684
|
+
absolute: true,
|
|
1685
|
+
onlyFiles: true
|
|
1686
|
+
})).sort();
|
|
916
1687
|
}
|
|
917
|
-
function
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1688
|
+
function demoFor(root, id) {
|
|
1689
|
+
for (const cand of [
|
|
1690
|
+
`${id}.demo.tsx`,
|
|
1691
|
+
`${id}.demo.jsx`,
|
|
1692
|
+
`${id}.demo.ts`,
|
|
1693
|
+
`${id}.demo.js`
|
|
1694
|
+
]) {
|
|
1695
|
+
const p = path.join(root, cand);
|
|
1696
|
+
if (existsSync(p)) return p;
|
|
1697
|
+
}
|
|
1698
|
+
return null;
|
|
922
1699
|
}
|
|
923
|
-
function
|
|
924
|
-
|
|
925
|
-
const known = new Set(current.map((f) => f.id));
|
|
926
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1700
|
+
async function listThemes(ctx, themesDir) {
|
|
1701
|
+
const root = themesRoot(ctx, themesDir);
|
|
927
1702
|
const out = [];
|
|
928
|
-
for (const
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
1703
|
+
for (const file of await themeFiles(root)) {
|
|
1704
|
+
const id = path.basename(file, ".md");
|
|
1705
|
+
const { fm } = parseFrontmatter(await fs.readFile(file, "utf8"), id);
|
|
1706
|
+
out.push({
|
|
1707
|
+
id,
|
|
1708
|
+
name: fm.name,
|
|
1709
|
+
description: fm.description,
|
|
1710
|
+
pageSize: fm.pageSize,
|
|
1711
|
+
mode: fm.mode,
|
|
1712
|
+
hasDemo: demoFor(root, id) !== null
|
|
1713
|
+
});
|
|
933
1714
|
}
|
|
934
1715
|
return out;
|
|
935
1716
|
}
|
|
936
|
-
function validateIcon(v) {
|
|
937
|
-
if (!v || typeof v !== "object") return null;
|
|
938
|
-
const icon = v;
|
|
939
|
-
if (icon.type === "emoji") {
|
|
940
|
-
if (typeof icon.value !== "string") return null;
|
|
941
|
-
if (icon.value.length < 1 || icon.value.length > 8) return null;
|
|
942
|
-
return {
|
|
943
|
-
type: "emoji",
|
|
944
|
-
value: icon.value
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
if (icon.type === "color") {
|
|
948
|
-
if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
|
|
949
|
-
return {
|
|
950
|
-
type: "color",
|
|
951
|
-
value: icon.value
|
|
952
|
-
};
|
|
953
|
-
}
|
|
954
|
-
return null;
|
|
955
|
-
}
|
|
956
|
-
//#endregion
|
|
957
|
-
//#region src/ops/documents.ts
|
|
958
1717
|
/**
|
|
959
|
-
*
|
|
960
|
-
*
|
|
961
|
-
* and a browser calling `/__docs` end up in exactly the same code.
|
|
1718
|
+
* The full theme document. This is what an agent reads before writing a doc —
|
|
1719
|
+
* the palette, type scale, and paste-ready components live in the body.
|
|
962
1720
|
*/
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
"index.js"
|
|
976
|
-
];
|
|
977
|
-
function docDir(ctx, docId) {
|
|
978
|
-
if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
979
|
-
const dir = path.resolve(ctx.docsRoot, docId);
|
|
980
|
-
if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
981
|
-
return dir;
|
|
1721
|
+
async function readTheme(ctx, themeId, themesDir) {
|
|
1722
|
+
const root = themesRoot(ctx, themesDir);
|
|
1723
|
+
const file = path.join(root, `${themeId}.md`);
|
|
1724
|
+
if (!file.startsWith(root + path.sep) || !existsSync(file)) throw new OpsError(404, `theme not found: ${themeId}`);
|
|
1725
|
+
const { fm, body } = parseFrontmatter(await fs.readFile(file, "utf8"), themeId);
|
|
1726
|
+
const demoAbs = demoFor(root, themeId);
|
|
1727
|
+
return {
|
|
1728
|
+
id: themeId,
|
|
1729
|
+
frontmatter: fm,
|
|
1730
|
+
body,
|
|
1731
|
+
demo: demoAbs ? await fs.readFile(demoAbs, "utf8") : void 0
|
|
1732
|
+
};
|
|
982
1733
|
}
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1734
|
+
/** `scope` is a document id, or `global` for the shared assets directory. */
|
|
1735
|
+
async function listAssets(ctx, scope) {
|
|
1736
|
+
const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
1737
|
+
if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
|
|
1738
|
+
if (!existsSync(dir)) return [];
|
|
1739
|
+
const names = await fs.readdir(dir);
|
|
1740
|
+
const out = [];
|
|
1741
|
+
for (const filename of names.sort()) {
|
|
1742
|
+
const stat = await fs.stat(path.join(dir, filename)).catch(() => null);
|
|
1743
|
+
if (!stat?.isFile()) continue;
|
|
1744
|
+
out.push({
|
|
1745
|
+
scope,
|
|
1746
|
+
filename,
|
|
1747
|
+
bytes: stat.size,
|
|
1748
|
+
importPath: assetImportPath(scope, filename)
|
|
1749
|
+
});
|
|
988
1750
|
}
|
|
989
|
-
return
|
|
1751
|
+
return out;
|
|
990
1752
|
}
|
|
991
|
-
async function
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
}
|
|
1753
|
+
async function writeAsset(ctx, scope, filename, data) {
|
|
1754
|
+
const name = validateAssetName(filename);
|
|
1755
|
+
if (!name) throw new OpsError(400, "invalid filename");
|
|
1756
|
+
const dir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
1757
|
+
if (!dir) throw new OpsError(400, `invalid scope: ${scope}`);
|
|
1758
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1759
|
+
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, name);
|
|
1760
|
+
if (!file) throw new OpsError(400, "invalid filename");
|
|
1761
|
+
await fs.writeFile(file, data);
|
|
1762
|
+
return {
|
|
1763
|
+
scope,
|
|
1764
|
+
filename: name,
|
|
1765
|
+
bytes: data.byteLength,
|
|
1766
|
+
importPath: assetImportPath(scope, name)
|
|
1767
|
+
};
|
|
997
1768
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1769
|
+
async function deleteAsset(ctx, scope, filename) {
|
|
1770
|
+
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
|
|
1771
|
+
if (!file) throw new OpsError(400, "invalid filename");
|
|
1772
|
+
if (!existsSync(file)) throw new OpsError(404, `asset not found: ${scope}/${filename}`);
|
|
1773
|
+
await fs.rm(file);
|
|
1002
1774
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
const
|
|
1775
|
+
/** Which documents import this asset — check before deleting one. */
|
|
1776
|
+
async function findAssetUsages(ctx, scope, filename) {
|
|
1777
|
+
const importPath = assetImportPath(scope, filename);
|
|
1006
1778
|
const out = [];
|
|
1007
|
-
for (const id of
|
|
1779
|
+
for (const id of await listDocIds$1(ctx)) {
|
|
1008
1780
|
const entry = resolveEntry(ctx, id);
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
theme: source ? readMetaField(source, "theme") : void 0,
|
|
1015
|
-
createdAt: source ? readMetaField(source, "createdAt") : void 0,
|
|
1016
|
-
folder: manifest.assignments[id],
|
|
1017
|
-
entry: entry ? path.relative(ctx.userCwd, entry) : null
|
|
1781
|
+
if (!entry) continue;
|
|
1782
|
+
const count = countAssetUsages(await fs.readFile(entry, "utf8"), importPath);
|
|
1783
|
+
if (count > 0) out.push({
|
|
1784
|
+
docId: id,
|
|
1785
|
+
count
|
|
1018
1786
|
});
|
|
1019
1787
|
}
|
|
1020
1788
|
return out;
|
|
1021
1789
|
}
|
|
1022
|
-
async function
|
|
1023
|
-
const
|
|
1024
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1790
|
+
async function listFolders(ctx) {
|
|
1791
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1025
1792
|
return {
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
source: await fs.readFile(entry, "utf8")
|
|
1793
|
+
folders: manifest.folders,
|
|
1794
|
+
assignments: manifest.assignments
|
|
1029
1795
|
};
|
|
1030
1796
|
}
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1797
|
+
/** Folders always carry an icon; agents rarely care, so this is the fallback. */
|
|
1798
|
+
const DEFAULT_FOLDER_ICON = {
|
|
1799
|
+
type: "color",
|
|
1800
|
+
value: "#6b7280"
|
|
1801
|
+
};
|
|
1802
|
+
async function createFolder(ctx, rawName, rawIcon) {
|
|
1803
|
+
const name = validateName(rawName);
|
|
1804
|
+
if (!name) throw new OpsError(400, "invalid folder name");
|
|
1805
|
+
const icon = validateIcon(rawIcon ?? DEFAULT_FOLDER_ICON);
|
|
1806
|
+
if (!icon) throw new OpsError(400, "invalid icon");
|
|
1807
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1808
|
+
const folder = {
|
|
1809
|
+
id: newFolderId(),
|
|
1810
|
+
name,
|
|
1811
|
+
icon
|
|
1040
1812
|
};
|
|
1813
|
+
manifest.folders.push(folder);
|
|
1814
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1815
|
+
return folder;
|
|
1041
1816
|
}
|
|
1042
|
-
/**
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1050
|
-
if (expected !== void 0) {
|
|
1051
|
-
if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
|
|
1052
|
-
}
|
|
1053
|
-
await fs.writeFile(entry, source, "utf8");
|
|
1054
|
-
return {
|
|
1055
|
-
id: docId,
|
|
1056
|
-
entry: path.relative(ctx.userCwd, entry)
|
|
1057
|
-
};
|
|
1817
|
+
/** Filing only edits assignments — a document id never moves on disk. */
|
|
1818
|
+
async function fileDocument(ctx, docId, folderId) {
|
|
1819
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1820
|
+
if (folderId !== null && !manifest.folders.some((f) => f.id === folderId)) throw new OpsError(404, `folder not found: ${folderId}`);
|
|
1821
|
+
if (folderId === null) delete manifest.assignments[docId];
|
|
1822
|
+
else manifest.assignments[docId] = folderId;
|
|
1823
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1058
1824
|
}
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1825
|
+
//#endregion
|
|
1826
|
+
//#region src/ops/templates.ts
|
|
1827
|
+
const TEMPLATE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
1828
|
+
const MANIFEST = "template.json";
|
|
1829
|
+
async function readTemplateDir(dir, name, source) {
|
|
1830
|
+
if (!TEMPLATE_NAME_RE.test(name) || !existsSync(path.join(dir, "index.tsx"))) return null;
|
|
1831
|
+
let manifest = {};
|
|
1832
|
+
try {
|
|
1833
|
+
manifest = JSON.parse(await fs.readFile(path.join(dir, MANIFEST), "utf8"));
|
|
1834
|
+
} catch {}
|
|
1835
|
+
const text = (value, fallback) => typeof value === "string" && value.trim() ? value.trim() : fallback;
|
|
1068
1836
|
return {
|
|
1069
|
-
|
|
1070
|
-
title
|
|
1837
|
+
name,
|
|
1838
|
+
title: text(manifest.title, name),
|
|
1839
|
+
description: text(manifest.description, ""),
|
|
1840
|
+
category: text(manifest.category, "general"),
|
|
1841
|
+
source,
|
|
1842
|
+
...typeof manifest.placeholder === "string" && manifest.placeholder.trim() ? { placeholder: manifest.placeholder.trim() } : {}
|
|
1071
1843
|
};
|
|
1072
1844
|
}
|
|
1073
|
-
async function
|
|
1074
|
-
const
|
|
1075
|
-
if (!existsSync(
|
|
1076
|
-
const
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
if (
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
const entry = resolveEntry(ctx, targetId);
|
|
1085
|
-
if (entry) {
|
|
1086
|
-
const source = await fs.readFile(entry, "utf8");
|
|
1087
|
-
const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
|
|
1088
|
-
if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
|
|
1089
|
-
}
|
|
1090
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
1091
|
-
const folderId = manifest.assignments[docId];
|
|
1092
|
-
if (folderId) {
|
|
1093
|
-
manifest.assignments[targetId] = folderId;
|
|
1094
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
1845
|
+
async function templatesIn(root, source) {
|
|
1846
|
+
const found = /* @__PURE__ */ new Map();
|
|
1847
|
+
if (!root || !existsSync(root)) return found;
|
|
1848
|
+
for (const entry of await fs.readdir(root, { withFileTypes: true })) {
|
|
1849
|
+
if (!entry.isDirectory()) continue;
|
|
1850
|
+
const dir = path.join(root, entry.name);
|
|
1851
|
+
const summary = await readTemplateDir(dir, entry.name, source);
|
|
1852
|
+
if (summary) found.set(entry.name, {
|
|
1853
|
+
dir,
|
|
1854
|
+
summary
|
|
1855
|
+
});
|
|
1095
1856
|
}
|
|
1096
|
-
return
|
|
1857
|
+
return found;
|
|
1097
1858
|
}
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1859
|
+
/**
|
|
1860
|
+
* Every template a document can start from: the ones open-doc ships, then the
|
|
1861
|
+
* workspace's own `templates/<name>/`, which win on a shared name — a team's
|
|
1862
|
+
* `report` is the report they mean.
|
|
1863
|
+
*/
|
|
1864
|
+
async function allTemplates(ctx) {
|
|
1865
|
+
const root = await corePackageRoot();
|
|
1866
|
+
const builtin = await templatesIn(root && path.join(root, "templates"), "builtin");
|
|
1867
|
+
const workspace = await templatesIn(path.join(ctx.userCwd, "templates"), "workspace");
|
|
1868
|
+
return new Map([...builtin, ...workspace]);
|
|
1869
|
+
}
|
|
1870
|
+
async function listTemplates(ctx) {
|
|
1871
|
+
return [...(await allTemplates(ctx)).values()].map(({ summary: { placeholder: _, ...summary } }) => summary).sort((a, b) => Number(a.name === "blank") - Number(b.name === "blank") || a.category.localeCompare(b.category) || a.name.localeCompare(b.name));
|
|
1872
|
+
}
|
|
1873
|
+
const slugOf = (text) => text.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
|
|
1874
|
+
/**
|
|
1875
|
+
* A free id from a title, else the template's name — a title in Chinese has
|
|
1876
|
+
* no letters to make one from: `quarterly-report`, then `quarterly-report-2`.
|
|
1877
|
+
*/
|
|
1878
|
+
function suggestDocId(bases, taken) {
|
|
1879
|
+
const slug = bases.map(slugOf).find(Boolean) || "document";
|
|
1880
|
+
if (!taken.has(slug)) return slug;
|
|
1881
|
+
for (let n = 2;; n++) if (!taken.has(`${slug}-${n}`)) return `${slug}-${n}`;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* A new document copied from a template: its folder as it is, minus the
|
|
1885
|
+
* manifest, with the title it was given and today as its creation date — so
|
|
1886
|
+
* it sorts as new, not as old as the template.
|
|
1887
|
+
*/
|
|
1888
|
+
async function createFromTemplate(ctx, opts) {
|
|
1889
|
+
const template = (await allTemplates(ctx)).get(opts.template);
|
|
1890
|
+
if (!template) throw new OpsError(404, `no template named "${opts.template}" — see \`open-doc templates\``);
|
|
1891
|
+
const title = opts.title === void 0 ? void 0 : validateDocTitle(opts.title);
|
|
1892
|
+
if (opts.title !== void 0 && !title) throw new OpsError(400, "invalid title");
|
|
1893
|
+
const taken = new Set(await listDocIds$1(ctx));
|
|
1894
|
+
const id = opts.docId ?? suggestDocId([title ?? "", template.summary.name], taken);
|
|
1895
|
+
if (!DOC_ID_RE.test(id)) throw new OpsError(400, `invalid document id: ${id}`);
|
|
1896
|
+
if (taken.has(id)) throw new OpsError(409, `document already exists: ${id}`);
|
|
1897
|
+
const dir = path.join(ctx.docsRoot, id);
|
|
1898
|
+
await fs.cp(template.dir, dir, {
|
|
1102
1899
|
recursive: true,
|
|
1103
|
-
|
|
1900
|
+
filter: (src) => path.basename(src) !== MANIFEST
|
|
1104
1901
|
});
|
|
1105
|
-
const
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1902
|
+
const entry = path.join(dir, "index.tsx");
|
|
1903
|
+
let source = await fs.readFile(entry, "utf8");
|
|
1904
|
+
source = setMetaString(source, "createdAt", (/* @__PURE__ */ new Date()).toISOString()) ?? source;
|
|
1905
|
+
if (title) {
|
|
1906
|
+
const placeholder = template.summary.placeholder;
|
|
1907
|
+
if (placeholder && !/[{}<>'"\\\n]/.test(title)) source = source.split(placeholder).join(title);
|
|
1908
|
+
source = setMetaString(source, "title", title) ?? source;
|
|
1109
1909
|
}
|
|
1910
|
+
await fs.writeFile(entry, source, "utf8");
|
|
1911
|
+
return {
|
|
1912
|
+
id,
|
|
1913
|
+
entry: path.relative(ctx.userCwd, entry)
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1916
|
+
//#endregion
|
|
1917
|
+
//#region src/vite/routes/templates.ts
|
|
1918
|
+
/**
|
|
1919
|
+
* Tells the dev server a document was just written, instead of waiting for the
|
|
1920
|
+
* file watcher. On Linux the watcher can be late to a folder created and
|
|
1921
|
+
* filled in one go, and the browser, already sent to the new document, finds
|
|
1922
|
+
* none until it notices.
|
|
1923
|
+
*/
|
|
1924
|
+
function announceDocument(server, ctx, docId) {
|
|
1925
|
+
server.watcher.emit("add", path.join(ctx.docsRoot, docId, "index.tsx"));
|
|
1926
|
+
}
|
|
1927
|
+
function registerTemplateRoutes(server, ctx) {
|
|
1928
|
+
server.middlewares.use("/__templates", async (req, res, next) => {
|
|
1929
|
+
const url = new URL(req.url ?? "/", "http://local");
|
|
1930
|
+
const method = req.method ?? "GET";
|
|
1931
|
+
try {
|
|
1932
|
+
if (method === "GET" && url.pathname === "/") return json(res, 200, { templates: await listTemplates(ctx) });
|
|
1933
|
+
const create = url.pathname.match(/^\/([^/]+)\/create$/);
|
|
1934
|
+
if (create && method === "POST") {
|
|
1935
|
+
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
1936
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
1937
|
+
const body = await readBody(req);
|
|
1938
|
+
const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
1939
|
+
const docId = text(body.docId);
|
|
1940
|
+
const title = text(body.title);
|
|
1941
|
+
const result = await createFromTemplate(ctx, {
|
|
1942
|
+
template: decodeURIComponent(create[1]),
|
|
1943
|
+
...docId ? { docId } : {},
|
|
1944
|
+
...title ? { title } : {}
|
|
1945
|
+
});
|
|
1946
|
+
const folderId = text(body.folderId);
|
|
1947
|
+
if (folderId) await fileDocument(ctx, result.id, folderId);
|
|
1948
|
+
announceDocument(server, ctx, result.id);
|
|
1949
|
+
return json(res, 200, {
|
|
1950
|
+
ok: true,
|
|
1951
|
+
docId: result.id
|
|
1952
|
+
});
|
|
1953
|
+
}
|
|
1954
|
+
return next();
|
|
1955
|
+
} catch (err) {
|
|
1956
|
+
if (err instanceof OpsError) return json(res, err.status, { error: err.message });
|
|
1957
|
+
json(res, 500, { error: String(err.message ?? err) });
|
|
1958
|
+
}
|
|
1959
|
+
});
|
|
1110
1960
|
}
|
|
1111
1961
|
//#endregion
|
|
1112
1962
|
//#region src/vite/routes/docs.ts
|
|
@@ -1122,9 +1972,11 @@ function registerDocRoutes(server, ctx) {
|
|
|
1122
1972
|
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
1123
1973
|
const docId = decodeURIComponent(duplicateMatch[1]);
|
|
1124
1974
|
const body = await readBody(req).catch(() => ({}));
|
|
1975
|
+
const result = await duplicateDocument(ctx, docId, typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0);
|
|
1976
|
+
announceDocument(server, ctx, result.id);
|
|
1125
1977
|
return json(res, 200, {
|
|
1126
1978
|
ok: true,
|
|
1127
|
-
docId:
|
|
1979
|
+
docId: result.id
|
|
1128
1980
|
});
|
|
1129
1981
|
}
|
|
1130
1982
|
if (idMatch) {
|
|
@@ -1180,6 +2032,32 @@ function parseMarkers(source) {
|
|
|
1180
2032
|
});
|
|
1181
2033
|
return comments;
|
|
1182
2034
|
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Where each marker's element starts. A marker is always an element's first
|
|
2037
|
+
* child, so the element holding it is the one the note is about; its start is
|
|
2038
|
+
* the `data-od-loc` the page stamps on it, which is how the viewer pins a note
|
|
2039
|
+
* to what it printed.
|
|
2040
|
+
*/
|
|
2041
|
+
function locateMarkers(source, comments) {
|
|
2042
|
+
const ast = parseSource(source);
|
|
2043
|
+
if (!ast) return comments;
|
|
2044
|
+
const owner = /* @__PURE__ */ new Map();
|
|
2045
|
+
walkJsx(ast, (element) => {
|
|
2046
|
+
if (!element.loc) return;
|
|
2047
|
+
for (const child of element.children ?? []) {
|
|
2048
|
+
if (child.type !== "JSXExpressionContainer") continue;
|
|
2049
|
+
const id = /@doc-comment\s+id="(c-[a-f0-9]+)"/.exec(source.slice(child.start, child.end))?.[1];
|
|
2050
|
+
if (id) owner.set(id, `${element.loc.start.line}:${element.loc.start.column}`);
|
|
2051
|
+
}
|
|
2052
|
+
});
|
|
2053
|
+
return comments.map((comment) => {
|
|
2054
|
+
const loc = owner.get(comment.id);
|
|
2055
|
+
return loc ? {
|
|
2056
|
+
...comment,
|
|
2057
|
+
loc
|
|
2058
|
+
} : comment;
|
|
2059
|
+
});
|
|
2060
|
+
}
|
|
1183
2061
|
function newCommentId() {
|
|
1184
2062
|
return `c-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
1185
2063
|
}
|
|
@@ -1764,7 +2642,52 @@ function dataSource(element, ast) {
|
|
|
1764
2642
|
});
|
|
1765
2643
|
return found;
|
|
1766
2644
|
}
|
|
2645
|
+
/** The data file behind `export const records = <name>`, when it is an import. */
|
|
2646
|
+
function recordsSource(ast) {
|
|
2647
|
+
let local = null;
|
|
2648
|
+
walkAst(ast, (node) => {
|
|
2649
|
+
if (local || node.type !== "VariableDeclarator") return;
|
|
2650
|
+
const id = node.id;
|
|
2651
|
+
const init = node.init;
|
|
2652
|
+
if (id.type === "Identifier" && id.name === "records" && init?.type === "Identifier") local = init.name;
|
|
2653
|
+
});
|
|
2654
|
+
if (!local) return null;
|
|
2655
|
+
let found = null;
|
|
2656
|
+
walkAst(ast, (node) => {
|
|
2657
|
+
if (found || node.type !== "ImportDeclaration") return;
|
|
2658
|
+
if ((node.specifiers ?? []).some((specifier) => specifier.local.name === local)) found = node.source.value;
|
|
2659
|
+
});
|
|
2660
|
+
return found;
|
|
2661
|
+
}
|
|
2662
|
+
/** The columns `<Field name="…">` prints anywhere inside the element. */
|
|
2663
|
+
function fieldNames(element) {
|
|
2664
|
+
const names = [];
|
|
2665
|
+
walkJsx(element, (node) => {
|
|
2666
|
+
const opening = node.openingElement;
|
|
2667
|
+
if (opening.name.name !== "Field") return;
|
|
2668
|
+
for (const attribute of opening.attributes ?? []) {
|
|
2669
|
+
if (attribute.type !== "JSXAttribute" || attribute.name.name !== "name") continue;
|
|
2670
|
+
const value = attribute.value;
|
|
2671
|
+
if (value?.type === "StringLiteral" && !names.includes(value.value)) names.push(value.value);
|
|
2672
|
+
}
|
|
2673
|
+
});
|
|
2674
|
+
return names;
|
|
2675
|
+
}
|
|
1767
2676
|
function describe(element, ctx) {
|
|
2677
|
+
const info = describeText(element, ctx);
|
|
2678
|
+
const names = fieldNames(element);
|
|
2679
|
+
if (names.length === 0) return info;
|
|
2680
|
+
const file = ctx ? recordsSource(ctx.ast) : null;
|
|
2681
|
+
return {
|
|
2682
|
+
...info,
|
|
2683
|
+
fields: {
|
|
2684
|
+
names,
|
|
2685
|
+
file
|
|
2686
|
+
},
|
|
2687
|
+
...info.editable ? {} : { reason: file ? `the values come from ${file} — edit that file, or leave a comment for the agent` : "the values come from the document’s records" }
|
|
2688
|
+
};
|
|
2689
|
+
}
|
|
2690
|
+
function describeText(element, ctx) {
|
|
1768
2691
|
const { parts } = resolve(element, ctx);
|
|
1769
2692
|
const texts = parts.filter((part) => part.kind === "text");
|
|
1770
2693
|
if (texts.length === 0) {
|
|
@@ -2759,7 +3682,8 @@ function registerEditRoutes(server, ctx) {
|
|
|
2759
3682
|
try {
|
|
2760
3683
|
if (method === "GET") {
|
|
2761
3684
|
if (!entry) return json(res, 200, { comments: [] });
|
|
2762
|
-
|
|
3685
|
+
const source = await fs.readFile(entry, "utf8");
|
|
3686
|
+
return json(res, 200, { comments: locateMarkers(source, parseMarkers(source)) });
|
|
2763
3687
|
}
|
|
2764
3688
|
if (method === "DELETE") {
|
|
2765
3689
|
const check = validateMutationRequest(req);
|
|
@@ -2886,6 +3810,8 @@ function apiPlugin(opts) {
|
|
|
2886
3810
|
registerFolderRoutes(server, ctx);
|
|
2887
3811
|
registerDocRoutes(server, ctx);
|
|
2888
3812
|
registerEditRoutes(server, ctx);
|
|
3813
|
+
registerChangesRoutes(server, ctx);
|
|
3814
|
+
registerTemplateRoutes(server, ctx);
|
|
2889
3815
|
}
|
|
2890
3816
|
};
|
|
2891
3817
|
}
|
|
@@ -3389,69 +4315,6 @@ function diagramPlugin() {
|
|
|
3389
4315
|
};
|
|
3390
4316
|
}
|
|
3391
4317
|
//#endregion
|
|
3392
|
-
//#region src/vite/loc-tags-plugin.ts
|
|
3393
|
-
const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set([
|
|
3394
|
-
"ImagePlaceholder",
|
|
3395
|
-
"Figure",
|
|
3396
|
-
"DataTable",
|
|
3397
|
-
"Footnote"
|
|
3398
|
-
]);
|
|
3399
|
-
function taggableName(opening) {
|
|
3400
|
-
const name = opening.name;
|
|
3401
|
-
if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
|
|
3402
|
-
if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
|
|
3403
|
-
return null;
|
|
3404
|
-
}
|
|
3405
|
-
function alreadyTagged(opening) {
|
|
3406
|
-
return (opening.attributes ?? []).some((attr) => {
|
|
3407
|
-
if (attr.type !== "JSXAttribute") return false;
|
|
3408
|
-
return attr.name?.name === "data-od-loc";
|
|
3409
|
-
});
|
|
3410
|
-
}
|
|
3411
|
-
function injectLocTags(code) {
|
|
3412
|
-
const ast = parseSource(code);
|
|
3413
|
-
if (!ast) return null;
|
|
3414
|
-
const insertions = [];
|
|
3415
|
-
walkJsx(ast, (node) => {
|
|
3416
|
-
const opening = node.openingElement;
|
|
3417
|
-
if (!opening || !node.loc) return;
|
|
3418
|
-
if (!taggableName(opening) || alreadyTagged(opening)) return;
|
|
3419
|
-
const nameNode = opening.name;
|
|
3420
|
-
insertions.push({
|
|
3421
|
-
offset: nameNode.end,
|
|
3422
|
-
text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
|
|
3423
|
-
});
|
|
3424
|
-
});
|
|
3425
|
-
if (insertions.length === 0) return null;
|
|
3426
|
-
insertions.sort((a, b) => b.offset - a.offset);
|
|
3427
|
-
let next = code;
|
|
3428
|
-
for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
|
|
3429
|
-
return next;
|
|
3430
|
-
}
|
|
3431
|
-
function isDocSourceFile(id, docsRootPosix) {
|
|
3432
|
-
const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
|
|
3433
|
-
if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
|
|
3434
|
-
if (!filePath.endsWith(".tsx")) return false;
|
|
3435
|
-
if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
|
|
3436
|
-
return filePath.slice(docsRootPosix.length + 1).includes("/");
|
|
3437
|
-
}
|
|
3438
|
-
function locTagsPlugin(opts) {
|
|
3439
|
-
const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
|
|
3440
|
-
return {
|
|
3441
|
-
name: "open-doc:loc-tags",
|
|
3442
|
-
apply: "serve",
|
|
3443
|
-
enforce: "pre",
|
|
3444
|
-
transform(code, id) {
|
|
3445
|
-
if (!isDocSourceFile(id, docsRoot)) return null;
|
|
3446
|
-
const next = injectLocTags(code);
|
|
3447
|
-
return next === null ? null : {
|
|
3448
|
-
code: next,
|
|
3449
|
-
map: null
|
|
3450
|
-
};
|
|
3451
|
-
}
|
|
3452
|
-
};
|
|
3453
|
-
}
|
|
3454
|
-
//#endregion
|
|
3455
4318
|
//#region src/vite/mcp-plugin.ts
|
|
3456
4319
|
/**
|
|
3457
4320
|
* Finds a package's ESM entry by walking `node_modules` up from the user's
|
|
@@ -3521,142 +4384,6 @@ function mcpPlugin(opts) {
|
|
|
3521
4384
|
};
|
|
3522
4385
|
}
|
|
3523
4386
|
//#endregion
|
|
3524
|
-
//#region src/vite/themes-plugin.ts
|
|
3525
|
-
const THEMES_VMOD = "virtual:open-doc/themes";
|
|
3526
|
-
function resolved(id) {
|
|
3527
|
-
return `\0${id}`;
|
|
3528
|
-
}
|
|
3529
|
-
const FM_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
|
|
3530
|
-
function parseFrontmatter(raw, themeId) {
|
|
3531
|
-
const match = raw.match(FM_RE);
|
|
3532
|
-
const fmText = match ? match[1] : "";
|
|
3533
|
-
const body = match ? match[2] : raw;
|
|
3534
|
-
const data = {};
|
|
3535
|
-
for (const line of fmText.split(/\r?\n/)) {
|
|
3536
|
-
const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
3537
|
-
if (!m) continue;
|
|
3538
|
-
let value = m[2].trim();
|
|
3539
|
-
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
3540
|
-
data[m[1]] = value;
|
|
3541
|
-
}
|
|
3542
|
-
return {
|
|
3543
|
-
fm: {
|
|
3544
|
-
name: data.name || themeId,
|
|
3545
|
-
description: data.description || "",
|
|
3546
|
-
pageSize: data.pageSize || "",
|
|
3547
|
-
mode: data.mode || ""
|
|
3548
|
-
},
|
|
3549
|
-
body: body.trim()
|
|
3550
|
-
};
|
|
3551
|
-
}
|
|
3552
|
-
async function findThemes(userCwd, themesDir) {
|
|
3553
|
-
const abs = path.resolve(userCwd, themesDir);
|
|
3554
|
-
if (!existsSync(abs)) return [];
|
|
3555
|
-
return (await fg("*.md", {
|
|
3556
|
-
cwd: abs,
|
|
3557
|
-
absolute: true,
|
|
3558
|
-
onlyFiles: true
|
|
3559
|
-
})).sort();
|
|
3560
|
-
}
|
|
3561
|
-
async function readTheme(mdAbs, themesRoot) {
|
|
3562
|
-
const id = path.basename(mdAbs, ".md");
|
|
3563
|
-
const { fm, body } = parseFrontmatter(await fs.readFile(mdAbs, "utf8"), id);
|
|
3564
|
-
let demoAbs = null;
|
|
3565
|
-
for (const cand of [
|
|
3566
|
-
`${id}.demo.tsx`,
|
|
3567
|
-
`${id}.demo.jsx`,
|
|
3568
|
-
`${id}.demo.ts`,
|
|
3569
|
-
`${id}.demo.js`
|
|
3570
|
-
]) {
|
|
3571
|
-
const p = path.join(themesRoot, cand);
|
|
3572
|
-
if (existsSync(p)) {
|
|
3573
|
-
demoAbs = p;
|
|
3574
|
-
break;
|
|
3575
|
-
}
|
|
3576
|
-
}
|
|
3577
|
-
return {
|
|
3578
|
-
id,
|
|
3579
|
-
frontmatter: fm,
|
|
3580
|
-
body,
|
|
3581
|
-
demoAbs
|
|
3582
|
-
};
|
|
3583
|
-
}
|
|
3584
|
-
function generateThemesModule(themes, isDev) {
|
|
3585
|
-
const meta = themes.map((t) => ({
|
|
3586
|
-
id: t.id,
|
|
3587
|
-
name: t.frontmatter.name,
|
|
3588
|
-
description: t.frontmatter.description,
|
|
3589
|
-
pageSize: t.frontmatter.pageSize,
|
|
3590
|
-
mode: t.frontmatter.mode,
|
|
3591
|
-
body: t.body,
|
|
3592
|
-
hasDemo: t.demoAbs !== null
|
|
3593
|
-
}));
|
|
3594
|
-
const cases = themes.flatMap((t) => {
|
|
3595
|
-
const abs = t.demoAbs;
|
|
3596
|
-
if (!abs) return [];
|
|
3597
|
-
const importPath = isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs;
|
|
3598
|
-
const importExpr = isDev ? `import(/* @vite-ignore */ import.meta.env.BASE_URL + ${JSON.stringify(importPath)})` : `import(${JSON.stringify(importPath)})`;
|
|
3599
|
-
return [` case ${JSON.stringify(t.id)}: return ${importExpr};`];
|
|
3600
|
-
}).join("\n");
|
|
3601
|
-
return `// virtual:open-doc/themes — generated
|
|
3602
|
-
export const themes = ${JSON.stringify(meta)};
|
|
3603
|
-
|
|
3604
|
-
export async function loadThemeDemo(id) {
|
|
3605
|
-
switch (id) {
|
|
3606
|
-
${cases}
|
|
3607
|
-
default: throw new Error('Theme demo not found: ' + id);
|
|
3608
|
-
}
|
|
3609
|
-
}
|
|
3610
|
-
`;
|
|
3611
|
-
}
|
|
3612
|
-
function themesPlugin(opts) {
|
|
3613
|
-
const { userCwd, config } = opts;
|
|
3614
|
-
const themesDir = config.themesDir ?? "themes";
|
|
3615
|
-
const themesRoot = path.resolve(userCwd, themesDir);
|
|
3616
|
-
let isDev = false;
|
|
3617
|
-
return {
|
|
3618
|
-
name: "open-doc:themes",
|
|
3619
|
-
config(_c, env) {
|
|
3620
|
-
isDev = env.command === "serve";
|
|
3621
|
-
},
|
|
3622
|
-
resolveId(id) {
|
|
3623
|
-
if (id === THEMES_VMOD) return resolved(THEMES_VMOD);
|
|
3624
|
-
return null;
|
|
3625
|
-
},
|
|
3626
|
-
async load(id) {
|
|
3627
|
-
if (id !== resolved(THEMES_VMOD)) return null;
|
|
3628
|
-
const files = await findThemes(userCwd, themesDir);
|
|
3629
|
-
return generateThemesModule(await Promise.all(files.map((f) => readTheme(f, themesRoot))), isDev);
|
|
3630
|
-
},
|
|
3631
|
-
configureServer(server) {
|
|
3632
|
-
const isThemeFile = (p) => {
|
|
3633
|
-
const rel = path.relative(themesRoot, p);
|
|
3634
|
-
if (rel.startsWith("..") || path.isAbsolute(rel)) return false;
|
|
3635
|
-
if (rel.includes(path.sep)) return false;
|
|
3636
|
-
return /\.(md|demo\.(tsx|jsx|ts|js))$/.test(rel);
|
|
3637
|
-
};
|
|
3638
|
-
let reloadTimer = null;
|
|
3639
|
-
const reload = () => {
|
|
3640
|
-
if (reloadTimer) clearTimeout(reloadTimer);
|
|
3641
|
-
reloadTimer = setTimeout(() => {
|
|
3642
|
-
reloadTimer = null;
|
|
3643
|
-
const mod = server.moduleGraph.getModuleById(resolved(THEMES_VMOD));
|
|
3644
|
-
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
3645
|
-
server.ws.send({ type: "full-reload" });
|
|
3646
|
-
}, 150);
|
|
3647
|
-
};
|
|
3648
|
-
server.watcher.add(themesRoot);
|
|
3649
|
-
for (const event of [
|
|
3650
|
-
"add",
|
|
3651
|
-
"unlink",
|
|
3652
|
-
"change"
|
|
3653
|
-
]) server.watcher.on(event, (p) => {
|
|
3654
|
-
if (isThemeFile(p)) reload();
|
|
3655
|
-
});
|
|
3656
|
-
}
|
|
3657
|
-
};
|
|
3658
|
-
}
|
|
3659
|
-
//#endregion
|
|
3660
4387
|
//#region src/vite/config.ts
|
|
3661
4388
|
function findPackageRoot(fromFile) {
|
|
3662
4389
|
let dir = path.dirname(fromFile);
|
|
@@ -3773,4 +4500,4 @@ async function createViteConfig(opts) {
|
|
|
3773
4500
|
};
|
|
3774
4501
|
}
|
|
3775
4502
|
//#endregion
|
|
3776
|
-
export {
|
|
4503
|
+
export { renameDocument as A, createDocument as C, listDocIds$1 as D, duplicateDocument as E, loadUserConfig as F, openDocPlugin as I, writeDocument as M, makeContext as N, listDocuments as O, DOC_ID_RE as P, OpsError as S, docDir as T, writeAsset as _, writeTexts as a, readChanges as b, suggestDocId as c, fileDocument as d, findAssetUsages as f, readTheme as g, listThemes as h, writeText as i, resolveEntry as j, readDocument as k, createFolder as l, listFolders as m, addComment as n, createFromTemplate as o, listAssets as p, readText as r, listTemplates as s, createViteConfig as t, deleteAsset as u, validateAssetName as v, deleteDocument as w, revertChange as x, listRevisions as y };
|