@open-document/core 0.9.1 → 0.11.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-B0GJXy8I.js → build-BHFGY8eF.js} +1 -1
- package/dist/{check-CuDIWsPT.js → check-UEBmDfT_.js} +3 -3
- package/dist/cli/bin.js +10 -6
- package/dist/{config-CAZ7Z_va.js → config-B_pdNbYg.js} +1166 -591
- package/dist/{context-PWAh9qbf.js → context-BM9_-u9P.js} +1 -1
- package/dist/{dev-CYqppXDI.js → dev-DX3QMIRi.js} +1 -1
- package/dist/{diagram-CCaUUnRe.js → diagram-BK4jTZr4.js} +146 -146
- package/dist/diff-DayvbXfX.js +44 -0
- package/dist/{export-1JtO2OMC.js → export-BPsXj1i6.js} +3 -3
- package/dist/{import-CsrdBOZ8.js → import-71wlAsrd.js} +2 -2
- package/dist/index.d.ts +53 -2
- package/dist/index.js +457 -18
- package/dist/ops/index.d.ts +72 -17
- package/dist/ops/index.js +3 -3
- package/dist/{ops-B2y9BMpk.js → ops-BUo67DaP.js} +642 -124
- package/dist/{preview-DW3PM-JV.js → preview-D3m1-gUL.js} +1 -1
- package/dist/{sdk-BqU6mwD_.d.ts → sdk-CpDEGRIo.d.ts} +2 -0
- package/dist/vite/index.js +1 -1
- package/package.json +2 -2
- package/skills/doc-authoring/SKILL.md +9 -4
- package/skills/doc-authoring/references/pagination.md +1 -1
- package/skills/doc-authoring/references/tables-and-charts.md +18 -1
- package/src/app/components/browser/browser-ui.tsx +105 -0
- package/src/app/components/chart.tsx +239 -0
- package/src/app/components/command-palette.tsx +284 -0
- package/src/app/components/design-panel/design-panel.tsx +22 -20
- package/src/app/components/design-panel/design-provider.tsx +4 -2
- package/src/app/components/diagram.tsx +11 -1
- package/src/app/components/doc-assets.tsx +6 -5
- package/src/app/components/doc-search.tsx +12 -10
- package/src/app/components/doc-sidebar.tsx +24 -18
- package/src/app/components/flow-page.tsx +2 -0
- package/src/app/components/inspector/format-section.tsx +434 -0
- package/src/app/components/inspector/inspector.tsx +310 -89
- package/src/app/components/inspector/use-style-edits.ts +210 -0
- package/src/app/components/language-toggle.tsx +38 -0
- package/src/app/components/palette-items.ts +128 -0
- package/src/app/components/panel/edit-save-card.tsx +4 -2
- package/src/app/components/panel/fields.tsx +100 -9
- package/src/app/components/panel/save-card.tsx +18 -10
- package/src/app/components/sidebar/folder-item.tsx +10 -8
- package/src/app/components/sidebar/icon-picker.tsx +3 -1
- package/src/app/components/sidebar/sidebar.tsx +44 -13
- package/src/app/components/theme-toggle.tsx +5 -3
- package/src/app/components/ui/menu.tsx +5 -0
- package/src/app/lib/agent-bridge.ts +8 -2
- package/src/app/lib/chart.test.ts +108 -0
- package/src/app/lib/chart.ts +343 -0
- package/src/app/lib/doc-preview.tsx +0 -10
- package/src/app/lib/docs.ts +3 -0
- package/src/app/lib/docx/from-dom.ts +11 -11
- package/src/app/lib/docx/ooxml.test.ts +25 -9
- package/src/app/lib/docx/ooxml.ts +58 -37
- package/src/app/lib/export-docx.ts +13 -8
- package/src/app/lib/flow.ts +1 -1
- package/src/app/lib/i18n-ja/browser.ts +88 -0
- package/src/app/lib/i18n-ja/doc.ts +65 -0
- package/src/app/lib/i18n-ja/index.ts +5 -0
- package/src/app/lib/i18n-ja/panels.ts +151 -0
- package/src/app/lib/i18n-ko/browser.ts +87 -0
- package/src/app/lib/i18n-ko/doc.ts +65 -0
- package/src/app/lib/i18n-ko/index.ts +5 -0
- package/src/app/lib/i18n-ko/panels.ts +148 -0
- package/src/app/lib/i18n-zh-cn/browser.ts +84 -0
- package/src/app/lib/i18n-zh-cn/doc.ts +64 -0
- package/src/app/lib/i18n-zh-cn/index.ts +5 -0
- package/src/app/lib/i18n-zh-cn/panels.ts +143 -0
- package/src/app/lib/i18n-zh-tw/browser.ts +84 -0
- package/src/app/lib/i18n-zh-tw/doc.ts +64 -0
- package/src/app/lib/i18n-zh-tw/index.ts +5 -0
- package/src/app/lib/i18n-zh-tw/panels.ts +144 -0
- package/src/app/lib/i18n.test.ts +24 -0
- package/src/app/lib/i18n.tsx +109 -0
- package/src/app/lib/inspector/format.ts +156 -0
- package/src/app/lib/outline.ts +23 -0
- package/src/app/lib/page-range.test.ts +10 -1
- package/src/app/lib/page-range.ts +26 -0
- package/src/app/lib/sdk.ts +2 -0
- package/src/app/main.tsx +4 -1
- package/src/app/routes/assets.tsx +193 -132
- package/src/app/routes/doc.tsx +668 -310
- package/src/app/routes/home-shell.tsx +115 -88
- package/src/app/routes/home.tsx +200 -67
- package/src/app/routes/themes.tsx +42 -35
- package/src/app/styles.css +84 -5
- package/src/app/virtual.d.ts +1 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-
|
|
1
|
+
import { a as defaultDesign, n as DiagramSyntaxError, r as parseDelimited, t as compileDiagram } from "./diagram-BK4jTZr4.js";
|
|
2
2
|
import chalk from "chalk";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -6,10 +6,10 @@ import fs from "node:fs/promises";
|
|
|
6
6
|
import { existsSync, readFileSync } from "node:fs";
|
|
7
7
|
import fg from "fast-glob";
|
|
8
8
|
import { loadConfigFromFile, normalizePath } from "vite";
|
|
9
|
-
import { parse } from "@babel/parser";
|
|
10
|
-
import { randomUUID } from "node:crypto";
|
|
11
9
|
import tailwindcss from "@tailwindcss/vite";
|
|
12
10
|
import react from "@vitejs/plugin-react";
|
|
11
|
+
import { parse } from "@babel/parser";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
13
|
//#region src/vite/open-doc-plugin.ts
|
|
14
14
|
const DOC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
15
15
|
const CONFIG_FILE = "open-doc.config.ts";
|
|
@@ -48,15 +48,18 @@ function toId(absFile, docsRoot) {
|
|
|
48
48
|
}
|
|
49
49
|
const META_CREATED_AT_RE = /(?:^|[\s,{])createdAt\s*:\s*['"]([^'"]+)['"]/;
|
|
50
50
|
const META_THEME_RE = /(?:^|[\s,{])theme\s*:\s*['"]([^'"]+)['"]/;
|
|
51
|
+
const META_TITLE_RE = /(?:^|[\s,{])title\s*:\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/;
|
|
51
52
|
/**
|
|
52
53
|
* Reads `meta` with a brace-matched regex instead of parsing: the plugin runs on
|
|
53
|
-
* every discovery pass, and the
|
|
54
|
-
*
|
|
54
|
+
* every discovery pass, and the fields it needs (sort order, theme back-link,
|
|
55
|
+
* the title search and sorting use without loading every document) are
|
|
56
|
+
* contractually string literals.
|
|
55
57
|
*/
|
|
56
58
|
function extractMeta(src) {
|
|
57
59
|
const empty = {
|
|
58
60
|
theme: null,
|
|
59
|
-
createdAt: null
|
|
61
|
+
createdAt: null,
|
|
62
|
+
title: null
|
|
60
63
|
};
|
|
61
64
|
const metaStart = src.search(/export\s+const\s+meta\b/);
|
|
62
65
|
if (metaStart === -1) return empty;
|
|
@@ -79,9 +82,13 @@ function extractMeta(src) {
|
|
|
79
82
|
const body = src.slice(openBrace + 1, closeBrace);
|
|
80
83
|
return {
|
|
81
84
|
theme: body.match(META_THEME_RE)?.[1] ?? null,
|
|
82
|
-
createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null
|
|
85
|
+
createdAt: body.match(META_CREATED_AT_RE)?.[1] ?? null,
|
|
86
|
+
title: unescapeLiteral(body.match(META_TITLE_RE)?.[2] ?? null)
|
|
83
87
|
};
|
|
84
88
|
}
|
|
89
|
+
function unescapeLiteral(raw) {
|
|
90
|
+
return raw === null ? null : raw.replace(/\\(.)/g, "$1");
|
|
91
|
+
}
|
|
85
92
|
function parseCreatedAtMs(iso) {
|
|
86
93
|
if (!iso) return null;
|
|
87
94
|
const ms = Date.parse(iso);
|
|
@@ -93,7 +100,8 @@ async function readMeta(abs) {
|
|
|
93
100
|
} catch {
|
|
94
101
|
return {
|
|
95
102
|
theme: null,
|
|
96
|
-
createdAt: null
|
|
103
|
+
createdAt: null,
|
|
104
|
+
title: null
|
|
97
105
|
};
|
|
98
106
|
}
|
|
99
107
|
}
|
|
@@ -105,6 +113,7 @@ async function generateDocsModule(files, docsRoot, isDev) {
|
|
|
105
113
|
id: toId(abs, docsRoot),
|
|
106
114
|
importPath: isDev ? `@fs/${normalizePath(abs).replace(/^\/+/, "")}` : abs,
|
|
107
115
|
theme: meta.theme,
|
|
116
|
+
title: meta.title,
|
|
108
117
|
createdAt: parseCreatedAtMs(meta.createdAt)
|
|
109
118
|
};
|
|
110
119
|
}));
|
|
@@ -113,9 +122,11 @@ async function generateDocsModule(files, docsRoot, isDev) {
|
|
|
113
122
|
const ids = JSON.stringify(entries.map((e) => e.id).sort());
|
|
114
123
|
const createdAtMap = {};
|
|
115
124
|
const themesMap = {};
|
|
125
|
+
const titlesMap = {};
|
|
116
126
|
for (const e of entries) {
|
|
117
127
|
if (e.createdAt !== null) createdAtMap[e.id] = e.createdAt;
|
|
118
128
|
if (e.theme) themesMap[e.id] = e.theme;
|
|
129
|
+
if (e.title) titlesMap[e.id] = e.title;
|
|
119
130
|
}
|
|
120
131
|
const importTokens = JSON.stringify(Object.fromEntries(entries.map((e) => [e.id, 0])));
|
|
121
132
|
const devRuntime = isDev ? `
|
|
@@ -139,6 +150,7 @@ if (import.meta.hot) {
|
|
|
139
150
|
export const docIds = ${ids};
|
|
140
151
|
export const docCreatedAt = ${JSON.stringify(createdAtMap)};
|
|
141
152
|
export const docThemes = ${JSON.stringify(themesMap)};
|
|
153
|
+
export const docTitles = ${JSON.stringify(titlesMap)};
|
|
142
154
|
${devRuntime}
|
|
143
155
|
|
|
144
156
|
export async function loadDoc(id) {
|
|
@@ -351,567 +363,172 @@ function resolveDocEntry(docsRoot, docId) {
|
|
|
351
363
|
return null;
|
|
352
364
|
}
|
|
353
365
|
//#endregion
|
|
354
|
-
//#region src/
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
366
|
+
//#region src/files/assets.ts
|
|
367
|
+
const GLOBAL_SCOPE = "@global";
|
|
368
|
+
const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
|
|
369
|
+
const MIME_BY_EXT = {
|
|
370
|
+
png: "image/png",
|
|
371
|
+
jpg: "image/jpeg",
|
|
372
|
+
jpeg: "image/jpeg",
|
|
373
|
+
gif: "image/gif",
|
|
374
|
+
svg: "image/svg+xml",
|
|
375
|
+
webp: "image/webp",
|
|
376
|
+
avif: "image/avif",
|
|
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";
|
|
365
392
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
* tolerates a document mid-edit; writing splices text in by AST offset, and a
|
|
369
|
-
* best-guess tree recovered from a syntax error must never decide where.
|
|
370
|
-
*/
|
|
371
|
-
function parseStrict(code) {
|
|
372
|
-
const ast = parseSource(code);
|
|
373
|
-
if (!ast) return null;
|
|
374
|
-
return ast.errors && ast.errors.length > 0 ? null : ast;
|
|
393
|
+
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
394
|
+
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
375
395
|
}
|
|
376
|
-
function
|
|
377
|
-
|
|
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;
|
|
378
406
|
}
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
visit(node);
|
|
387
|
-
for (const key of Object.keys(node)) {
|
|
388
|
-
if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
|
|
389
|
-
walkAst(node[key], visit);
|
|
390
|
-
}
|
|
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;
|
|
391
414
|
}
|
|
392
|
-
function
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
});
|
|
415
|
+
function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
|
|
416
|
+
if (scope === "@global") return globalAssetsRoot;
|
|
417
|
+
return resolveAssetsDir(docsRoot, scope);
|
|
396
418
|
}
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
});
|
|
411
|
-
return found;
|
|
419
|
+
function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
|
|
420
|
+
if (!validateAssetName(filename)) return null;
|
|
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;
|
|
426
|
+
}
|
|
427
|
+
/** How a document imports an asset — the string we look for when counting usages. */
|
|
428
|
+
function assetImportPath(scope, filename) {
|
|
429
|
+
return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
|
|
430
|
+
}
|
|
431
|
+
function escapeRegExp(value) {
|
|
432
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
412
433
|
}
|
|
413
434
|
/**
|
|
414
|
-
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
* injecting the loc attribute shifts the columns of anything later on the same
|
|
418
|
-
* line, so the offset differs per element. The line survives that, so callers
|
|
419
|
-
* scan the line and pick by content instead.
|
|
435
|
+
* Counts references to an asset in a document's source. Matches the quoted path
|
|
436
|
+
* in both import statements and `new URL('./assets/x.png', import.meta.url)`,
|
|
437
|
+
* which is every form the authoring skill sanctions.
|
|
420
438
|
*/
|
|
421
|
-
function
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
node,
|
|
428
|
-
distance: Math.abs(start.column - column)
|
|
429
|
-
});
|
|
430
|
-
});
|
|
431
|
-
return hits.sort((a, b) => a.distance - b.distance).map((hit) => hit.node);
|
|
439
|
+
function countAssetUsages(source, importPath) {
|
|
440
|
+
const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
|
|
441
|
+
return source.match(quoted)?.length ?? 0;
|
|
442
|
+
}
|
|
443
|
+
function findReferencedAssets(source, importPaths) {
|
|
444
|
+
return importPaths.filter((p) => countAssetUsages(source, p) > 0);
|
|
432
445
|
}
|
|
433
446
|
//#endregion
|
|
434
|
-
//#region src/
|
|
435
|
-
function
|
|
436
|
-
|
|
447
|
+
//#region src/http/request-guard.ts
|
|
448
|
+
function firstHeaderValue(value) {
|
|
449
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
450
|
+
return value ?? null;
|
|
437
451
|
}
|
|
438
|
-
function
|
|
439
|
-
|
|
440
|
-
const decl = node.declaration;
|
|
441
|
-
if (decl?.type !== "VariableDeclaration") return null;
|
|
442
|
-
const declarations = decl.declarations ?? [];
|
|
443
|
-
for (const d of declarations) {
|
|
444
|
-
const id = d.id;
|
|
445
|
-
if (id?.type !== "Identifier" || id.name !== "meta") continue;
|
|
446
|
-
let init = d.init;
|
|
447
|
-
if (!init) return null;
|
|
448
|
-
if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
|
|
449
|
-
const expr = init.expression;
|
|
450
|
-
if (expr) init = expr;
|
|
451
|
-
}
|
|
452
|
-
return init.type === "ObjectExpression" ? init : null;
|
|
453
|
-
}
|
|
454
|
-
return null;
|
|
452
|
+
function headerValue(req, name) {
|
|
453
|
+
return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
|
|
455
454
|
}
|
|
456
|
-
function
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
}
|
|
461
|
-
return null;
|
|
455
|
+
function firstCommaToken(value) {
|
|
456
|
+
if (!value) return null;
|
|
457
|
+
const [first] = value.split(",", 1);
|
|
458
|
+
return first?.trim() || null;
|
|
462
459
|
}
|
|
463
|
-
function
|
|
464
|
-
|
|
460
|
+
function requestProto(req) {
|
|
461
|
+
const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
|
|
462
|
+
if (forwarded === "http" || forwarded === "https") return forwarded;
|
|
463
|
+
return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
465
464
|
}
|
|
466
|
-
function
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
465
|
+
function normalizedOrigin(origin) {
|
|
466
|
+
try {
|
|
467
|
+
const url = new URL(origin);
|
|
468
|
+
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
469
|
+
} catch {
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
471
472
|
}
|
|
472
473
|
/**
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
* the caller reports that rather than inventing an export.
|
|
474
|
+
* The dev server writes to the user's filesystem, so every mutating endpoint is
|
|
475
|
+
* guarded against a page on another origin driving it through the browser.
|
|
476
476
|
*/
|
|
477
|
-
function
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
485
|
-
const p = prop;
|
|
486
|
-
if (p.computed) continue;
|
|
487
|
-
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
|
|
488
|
-
return source.slice(0, p.value.start) + jsString$1(title) + source.slice(p.value.end);
|
|
489
|
-
}
|
|
490
|
-
const open = object.start + 1;
|
|
491
|
-
const inserted = source.slice(open, object.end - 1).trim() === "" ? `\n title: ${jsString$1(title)},\n` : `\n title: ${jsString$1(title)},`;
|
|
492
|
-
return source.slice(0, open) + inserted + source.slice(open);
|
|
493
|
-
}
|
|
494
|
-
function readMetaTitle(source) {
|
|
495
|
-
const ast = parseSource(source);
|
|
496
|
-
if (!ast) return null;
|
|
497
|
-
const object = findMetaObject(ast);
|
|
498
|
-
if (!object) return null;
|
|
499
|
-
const properties = object.properties ?? [];
|
|
500
|
-
for (const prop of properties) {
|
|
501
|
-
if (prop.type !== "ObjectProperty") continue;
|
|
502
|
-
const p = prop;
|
|
503
|
-
if (p.computed) continue;
|
|
504
|
-
if ((p.key.type === "Identifier" ? p.key.name : p.key.value) !== "title") continue;
|
|
505
|
-
if (p.value.type !== "StringLiteral") return null;
|
|
506
|
-
return typeof p.value.value === "string" ? p.value.value : null;
|
|
507
|
-
}
|
|
508
|
-
return null;
|
|
509
|
-
}
|
|
510
|
-
/** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
|
|
511
|
-
function nextCopyId(baseId, taken) {
|
|
512
|
-
const stem = baseId.replace(/-copy(-\d+)?$/, "");
|
|
513
|
-
let candidate = `${stem}-copy`;
|
|
514
|
-
let n = 2;
|
|
515
|
-
while (taken.has(candidate)) {
|
|
516
|
-
candidate = `${stem}-copy-${n}`;
|
|
517
|
-
n++;
|
|
477
|
+
function validateMutationRequest(req, opts = {}) {
|
|
478
|
+
if (opts.requireJsonBody) {
|
|
479
|
+
if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
|
|
480
|
+
ok: false,
|
|
481
|
+
status: 415,
|
|
482
|
+
error: "content-type must be application/json"
|
|
483
|
+
};
|
|
518
484
|
}
|
|
519
|
-
return
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
}
|
|
524
|
-
//#endregion
|
|
525
|
-
//#region src/files/folders.ts
|
|
526
|
-
const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
|
|
527
|
-
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
|
528
|
-
function emptyManifest() {
|
|
529
|
-
return {
|
|
530
|
-
folders: [],
|
|
531
|
-
assignments: {}
|
|
485
|
+
if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
|
|
486
|
+
ok: false,
|
|
487
|
+
status: 403,
|
|
488
|
+
error: "cross-site request blocked"
|
|
532
489
|
};
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
|
540
|
-
assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
|
|
541
|
-
};
|
|
542
|
-
} catch (err) {
|
|
543
|
-
if (err.code === "ENOENT") return emptyManifest();
|
|
544
|
-
throw err;
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
async function writeManifest(file, manifest) {
|
|
548
|
-
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
549
|
-
await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
550
|
-
}
|
|
551
|
-
function newFolderId() {
|
|
552
|
-
return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
553
|
-
}
|
|
554
|
-
function validateName(v) {
|
|
555
|
-
if (typeof v !== "string") return null;
|
|
556
|
-
const trimmed = v.trim();
|
|
557
|
-
if (trimmed.length < 1 || trimmed.length > 40) return null;
|
|
558
|
-
return trimmed;
|
|
559
|
-
}
|
|
560
|
-
function validateReorder(v, current) {
|
|
561
|
-
if (!Array.isArray(v) || v.length !== current.length) return null;
|
|
562
|
-
const known = new Set(current.map((f) => f.id));
|
|
563
|
-
const seen = /* @__PURE__ */ new Set();
|
|
564
|
-
const out = [];
|
|
565
|
-
for (const id of v) {
|
|
566
|
-
if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
|
|
567
|
-
if (!known.has(id) || seen.has(id)) return null;
|
|
568
|
-
seen.add(id);
|
|
569
|
-
out.push(id);
|
|
570
|
-
}
|
|
571
|
-
return out;
|
|
572
|
-
}
|
|
573
|
-
function validateIcon(v) {
|
|
574
|
-
if (!v || typeof v !== "object") return null;
|
|
575
|
-
const icon = v;
|
|
576
|
-
if (icon.type === "emoji") {
|
|
577
|
-
if (typeof icon.value !== "string") return null;
|
|
578
|
-
if (icon.value.length < 1 || icon.value.length > 8) return null;
|
|
579
|
-
return {
|
|
580
|
-
type: "emoji",
|
|
581
|
-
value: icon.value
|
|
582
|
-
};
|
|
583
|
-
}
|
|
584
|
-
if (icon.type === "color") {
|
|
585
|
-
if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
|
|
586
|
-
return {
|
|
587
|
-
type: "color",
|
|
588
|
-
value: icon.value
|
|
589
|
-
};
|
|
590
|
-
}
|
|
591
|
-
return null;
|
|
592
|
-
}
|
|
593
|
-
//#endregion
|
|
594
|
-
//#region src/ops/documents.ts
|
|
595
|
-
/**
|
|
596
|
-
* Operations shared by the dev API and the MCP server. Everything here takes an
|
|
597
|
-
* `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
|
|
598
|
-
* and a browser calling `/__docs` end up in exactly the same code.
|
|
599
|
-
*/
|
|
600
|
-
var OpsError = class extends Error {
|
|
601
|
-
status;
|
|
602
|
-
constructor(status, message) {
|
|
603
|
-
super(message);
|
|
604
|
-
this.status = status;
|
|
605
|
-
this.name = "OpsError";
|
|
606
|
-
}
|
|
607
|
-
};
|
|
608
|
-
const ENTRY_NAMES = [
|
|
609
|
-
"index.tsx",
|
|
610
|
-
"index.jsx",
|
|
611
|
-
"index.ts",
|
|
612
|
-
"index.js"
|
|
613
|
-
];
|
|
614
|
-
function docDir(ctx, docId) {
|
|
615
|
-
if (!DOC_ID_RE.test(docId)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
616
|
-
const dir = path.resolve(ctx.docsRoot, docId);
|
|
617
|
-
if (!dir.startsWith(ctx.docsRoot + path.sep)) throw new OpsError(400, `invalid document id: ${docId}`);
|
|
618
|
-
return dir;
|
|
619
|
-
}
|
|
620
|
-
function resolveEntry(ctx, docId) {
|
|
621
|
-
const dir = docDir(ctx, docId);
|
|
622
|
-
for (const name of ENTRY_NAMES) {
|
|
623
|
-
const file = path.join(dir, name);
|
|
624
|
-
if (existsSync(file)) return file;
|
|
625
|
-
}
|
|
626
|
-
return null;
|
|
627
|
-
}
|
|
628
|
-
async function listDocIds$1(ctx) {
|
|
629
|
-
try {
|
|
630
|
-
return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
631
|
-
} catch {
|
|
632
|
-
return [];
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
/** Reads what the doc declares without executing it — a regex over `export const meta`. */
|
|
636
|
-
function readMetaField(source, field) {
|
|
637
|
-
const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
|
|
638
|
-
return source.slice(source.indexOf("export const meta")).match(re)?.[2];
|
|
639
|
-
}
|
|
640
|
-
async function listDocuments(ctx) {
|
|
641
|
-
const ids = await listDocIds$1(ctx);
|
|
642
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
643
|
-
const out = [];
|
|
644
|
-
for (const id of ids) {
|
|
645
|
-
const entry = resolveEntry(ctx, id);
|
|
646
|
-
const source = entry ? await fs.readFile(entry, "utf8") : "";
|
|
647
|
-
out.push({
|
|
648
|
-
id,
|
|
649
|
-
title: source ? readMetaTitle(source) : null,
|
|
650
|
-
subtitle: source ? readMetaField(source, "subtitle") : void 0,
|
|
651
|
-
theme: source ? readMetaField(source, "theme") : void 0,
|
|
652
|
-
createdAt: source ? readMetaField(source, "createdAt") : void 0,
|
|
653
|
-
folder: manifest.assignments[id],
|
|
654
|
-
entry: entry ? path.relative(ctx.userCwd, entry) : null
|
|
655
|
-
});
|
|
656
|
-
}
|
|
657
|
-
return out;
|
|
658
|
-
}
|
|
659
|
-
async function readDocument(ctx, docId) {
|
|
660
|
-
const entry = resolveEntry(ctx, docId);
|
|
661
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
662
|
-
return {
|
|
663
|
-
id: docId,
|
|
664
|
-
entry: path.relative(ctx.userCwd, entry),
|
|
665
|
-
source: await fs.readFile(entry, "utf8")
|
|
490
|
+
const originRaw = headerValue(req, "origin");
|
|
491
|
+
if (!originRaw) return { ok: true };
|
|
492
|
+
if (originRaw.toLowerCase() === "null") return {
|
|
493
|
+
ok: false,
|
|
494
|
+
status: 403,
|
|
495
|
+
error: "opaque origin is not allowed"
|
|
666
496
|
};
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
const entry = path.join(dir, "index.tsx");
|
|
673
|
-
await fs.writeFile(entry, source, "utf8");
|
|
674
|
-
return {
|
|
675
|
-
id: docId,
|
|
676
|
-
entry: path.relative(ctx.userCwd, entry)
|
|
497
|
+
const actualOrigin = normalizedOrigin(originRaw);
|
|
498
|
+
if (!actualOrigin) return {
|
|
499
|
+
ok: false,
|
|
500
|
+
status: 403,
|
|
501
|
+
error: "invalid origin header"
|
|
677
502
|
};
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
*/
|
|
684
|
-
async function writeDocument(ctx, docId, source, expected) {
|
|
685
|
-
const entry = resolveEntry(ctx, docId);
|
|
686
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
687
|
-
if (expected !== void 0) {
|
|
688
|
-
if (await fs.readFile(entry, "utf8") !== expected) throw new OpsError(409, "document changed on disk since it was read");
|
|
689
|
-
}
|
|
690
|
-
await fs.writeFile(entry, source, "utf8");
|
|
691
|
-
return {
|
|
692
|
-
id: docId,
|
|
693
|
-
entry: path.relative(ctx.userCwd, entry)
|
|
503
|
+
const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
|
|
504
|
+
if (!host) return {
|
|
505
|
+
ok: false,
|
|
506
|
+
status: 400,
|
|
507
|
+
error: "missing host header"
|
|
694
508
|
};
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
const entry = resolveEntry(ctx, docId);
|
|
700
|
-
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
701
|
-
const source = await fs.readFile(entry, "utf8");
|
|
702
|
-
const next = setMetaTitle(source, title);
|
|
703
|
-
if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
|
|
704
|
-
if (next !== source) await fs.writeFile(entry, next, "utf8");
|
|
705
|
-
return {
|
|
706
|
-
id: docId,
|
|
707
|
-
title
|
|
509
|
+
if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
|
|
510
|
+
ok: false,
|
|
511
|
+
status: 403,
|
|
512
|
+
error: "origin mismatch"
|
|
708
513
|
};
|
|
514
|
+
return { ok: true };
|
|
709
515
|
}
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
|
|
718
|
-
targetId = newId;
|
|
719
|
-
} else targetId = nextCopyId(docId, taken);
|
|
720
|
-
await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
|
|
721
|
-
const entry = resolveEntry(ctx, targetId);
|
|
722
|
-
if (entry) {
|
|
723
|
-
const source = await fs.readFile(entry, "utf8");
|
|
724
|
-
const renamed = setMetaTitle(source, copyTitle(readMetaTitle(source) ?? docId));
|
|
725
|
-
if (renamed && renamed !== source) await fs.writeFile(entry, renamed, "utf8");
|
|
726
|
-
}
|
|
727
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
728
|
-
const folderId = manifest.assignments[docId];
|
|
729
|
-
if (folderId) {
|
|
730
|
-
manifest.assignments[targetId] = folderId;
|
|
731
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region src/vite/routes/assets.ts
|
|
518
|
+
async function listDocIds$1(docsRoot) {
|
|
519
|
+
try {
|
|
520
|
+
return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
|
|
521
|
+
} catch {
|
|
522
|
+
return [];
|
|
732
523
|
}
|
|
733
|
-
return { id: targetId };
|
|
734
524
|
}
|
|
735
|
-
async function
|
|
736
|
-
const
|
|
737
|
-
if (!
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
743
|
-
if (manifest.assignments[docId]) {
|
|
744
|
-
delete manifest.assignments[docId];
|
|
745
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
//#endregion
|
|
749
|
-
//#region src/files/assets.ts
|
|
750
|
-
const GLOBAL_SCOPE = "@global";
|
|
751
|
-
const ASSET_FORBIDDEN_RE = /[\x00-\x1F\x7F/\\:*?"<>|]/;
|
|
752
|
-
const MIME_BY_EXT = {
|
|
753
|
-
png: "image/png",
|
|
754
|
-
jpg: "image/jpeg",
|
|
755
|
-
jpeg: "image/jpeg",
|
|
756
|
-
gif: "image/gif",
|
|
757
|
-
svg: "image/svg+xml",
|
|
758
|
-
webp: "image/webp",
|
|
759
|
-
avif: "image/avif",
|
|
760
|
-
ico: "image/x-icon",
|
|
761
|
-
pdf: "application/pdf",
|
|
762
|
-
woff: "font/woff",
|
|
763
|
-
woff2: "font/woff2",
|
|
764
|
-
ttf: "font/ttf",
|
|
765
|
-
otf: "font/otf",
|
|
766
|
-
csv: "text/csv; charset=utf-8",
|
|
767
|
-
json: "application/json",
|
|
768
|
-
txt: "text/plain; charset=utf-8",
|
|
769
|
-
md: "text/markdown; charset=utf-8"
|
|
770
|
-
};
|
|
771
|
-
function mimeForFilename(name) {
|
|
772
|
-
const dot = name.lastIndexOf(".");
|
|
773
|
-
if (dot < 0) return "application/octet-stream";
|
|
774
|
-
return MIME_BY_EXT[name.slice(dot + 1).toLowerCase()] ?? "application/octet-stream";
|
|
775
|
-
}
|
|
776
|
-
function assetCreatedAt(birthtimeMs, mtimeMs) {
|
|
777
|
-
return Number.isFinite(birthtimeMs) && birthtimeMs > 0 ? birthtimeMs : mtimeMs;
|
|
778
|
-
}
|
|
779
|
-
function validateAssetName(v) {
|
|
780
|
-
if (typeof v !== "string") return null;
|
|
781
|
-
const trimmed = v.trim();
|
|
782
|
-
if (trimmed.length < 1 || trimmed.length > 120) return null;
|
|
783
|
-
if (ASSET_FORBIDDEN_RE.test(trimmed)) return null;
|
|
784
|
-
if (trimmed.startsWith(".") || trimmed.startsWith("~")) return null;
|
|
785
|
-
if (trimmed === ".." || trimmed.split(/[/\\]/).includes("..")) return null;
|
|
786
|
-
const dot = trimmed.lastIndexOf(".");
|
|
787
|
-
if (dot <= 0 || dot === trimmed.length - 1) return null;
|
|
788
|
-
return trimmed;
|
|
789
|
-
}
|
|
790
|
-
function resolveAssetsDir(docsRoot, docId) {
|
|
791
|
-
if (!DOC_ID_RE.test(docId)) return null;
|
|
792
|
-
const docDir = path.resolve(docsRoot, docId);
|
|
793
|
-
if (!docDir.startsWith(docsRoot + path.sep)) return null;
|
|
794
|
-
const assetsDir = path.resolve(docDir, "assets");
|
|
795
|
-
if (assetsDir !== path.join(docDir, "assets")) return null;
|
|
796
|
-
return assetsDir;
|
|
797
|
-
}
|
|
798
|
-
function resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope) {
|
|
799
|
-
if (scope === "@global") return globalAssetsRoot;
|
|
800
|
-
return resolveAssetsDir(docsRoot, scope);
|
|
801
|
-
}
|
|
802
|
-
function resolveScopedAssetFile(docsRoot, globalAssetsRoot, scope, filename) {
|
|
803
|
-
if (!validateAssetName(filename)) return null;
|
|
804
|
-
const dir = resolveScopedAssetsDir(docsRoot, globalAssetsRoot, scope);
|
|
805
|
-
if (!dir) return null;
|
|
806
|
-
const file = path.resolve(dir, filename);
|
|
807
|
-
if (!file.startsWith(dir + path.sep)) return null;
|
|
808
|
-
return file;
|
|
809
|
-
}
|
|
810
|
-
/** How a document imports an asset — the string we look for when counting usages. */
|
|
811
|
-
function assetImportPath(scope, filename) {
|
|
812
|
-
return scope === "@global" ? `@assets/${filename}` : `./assets/${filename}`;
|
|
813
|
-
}
|
|
814
|
-
function escapeRegExp(value) {
|
|
815
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
816
|
-
}
|
|
817
|
-
/**
|
|
818
|
-
* Counts references to an asset in a document's source. Matches the quoted path
|
|
819
|
-
* in both import statements and `new URL('./assets/x.png', import.meta.url)`,
|
|
820
|
-
* which is every form the authoring skill sanctions.
|
|
821
|
-
*/
|
|
822
|
-
function countAssetUsages(source, importPath) {
|
|
823
|
-
const quoted = new RegExp(`(['"\`])${escapeRegExp(importPath)}\\1`, "g");
|
|
824
|
-
return source.match(quoted)?.length ?? 0;
|
|
825
|
-
}
|
|
826
|
-
function findReferencedAssets(source, importPaths) {
|
|
827
|
-
return importPaths.filter((p) => countAssetUsages(source, p) > 0);
|
|
828
|
-
}
|
|
829
|
-
//#endregion
|
|
830
|
-
//#region src/http/request-guard.ts
|
|
831
|
-
function firstHeaderValue(value) {
|
|
832
|
-
if (Array.isArray(value)) return value[0] ?? null;
|
|
833
|
-
return value ?? null;
|
|
834
|
-
}
|
|
835
|
-
function headerValue(req, name) {
|
|
836
|
-
return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
|
|
837
|
-
}
|
|
838
|
-
function firstCommaToken(value) {
|
|
839
|
-
if (!value) return null;
|
|
840
|
-
const [first] = value.split(",", 1);
|
|
841
|
-
return first?.trim() || null;
|
|
842
|
-
}
|
|
843
|
-
function requestProto(req) {
|
|
844
|
-
const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
|
|
845
|
-
if (forwarded === "http" || forwarded === "https") return forwarded;
|
|
846
|
-
return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
847
|
-
}
|
|
848
|
-
function normalizedOrigin(origin) {
|
|
849
|
-
try {
|
|
850
|
-
const url = new URL(origin);
|
|
851
|
-
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
852
|
-
} catch {
|
|
853
|
-
return null;
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* The dev server writes to the user's filesystem, so every mutating endpoint is
|
|
858
|
-
* guarded against a page on another origin driving it through the browser.
|
|
859
|
-
*/
|
|
860
|
-
function validateMutationRequest(req, opts = {}) {
|
|
861
|
-
if (opts.requireJsonBody) {
|
|
862
|
-
if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
|
|
863
|
-
ok: false,
|
|
864
|
-
status: 415,
|
|
865
|
-
error: "content-type must be application/json"
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
|
|
869
|
-
ok: false,
|
|
870
|
-
status: 403,
|
|
871
|
-
error: "cross-site request blocked"
|
|
872
|
-
};
|
|
873
|
-
const originRaw = headerValue(req, "origin");
|
|
874
|
-
if (!originRaw) return { ok: true };
|
|
875
|
-
if (originRaw.toLowerCase() === "null") return {
|
|
876
|
-
ok: false,
|
|
877
|
-
status: 403,
|
|
878
|
-
error: "opaque origin is not allowed"
|
|
879
|
-
};
|
|
880
|
-
const actualOrigin = normalizedOrigin(originRaw);
|
|
881
|
-
if (!actualOrigin) return {
|
|
882
|
-
ok: false,
|
|
883
|
-
status: 403,
|
|
884
|
-
error: "invalid origin header"
|
|
885
|
-
};
|
|
886
|
-
const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
|
|
887
|
-
if (!host) return {
|
|
888
|
-
ok: false,
|
|
889
|
-
status: 400,
|
|
890
|
-
error: "missing host header"
|
|
891
|
-
};
|
|
892
|
-
if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
|
|
893
|
-
ok: false,
|
|
894
|
-
status: 403,
|
|
895
|
-
error: "origin mismatch"
|
|
896
|
-
};
|
|
897
|
-
return { ok: true };
|
|
898
|
-
}
|
|
899
|
-
//#endregion
|
|
900
|
-
//#region src/vite/routes/assets.ts
|
|
901
|
-
async function listDocIds(docsRoot) {
|
|
902
|
-
try {
|
|
903
|
-
return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
|
|
904
|
-
} catch {
|
|
905
|
-
return [];
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
async function readDocSource(docsRoot, docId) {
|
|
909
|
-
const entry = resolveDocEntry(docsRoot, docId);
|
|
910
|
-
if (!entry) return null;
|
|
911
|
-
try {
|
|
912
|
-
return await fs.readFile(entry, "utf8");
|
|
913
|
-
} catch {
|
|
914
|
-
return null;
|
|
525
|
+
async function readDocSource(docsRoot, docId) {
|
|
526
|
+
const entry = resolveDocEntry(docsRoot, docId);
|
|
527
|
+
if (!entry) return null;
|
|
528
|
+
try {
|
|
529
|
+
return await fs.readFile(entry, "utf8");
|
|
530
|
+
} catch {
|
|
531
|
+
return null;
|
|
915
532
|
}
|
|
916
533
|
}
|
|
917
534
|
function registerAssetRoutes(server, ctx) {
|
|
@@ -929,7 +546,7 @@ function registerAssetRoutes(server, ctx) {
|
|
|
929
546
|
const isGlobal = scope === GLOBAL_SCOPE;
|
|
930
547
|
if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
|
|
931
548
|
const importPath = assetImportPath(scope, filename);
|
|
932
|
-
const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
|
|
549
|
+
const docIds = isGlobal ? await listDocIds$1(ctx.docsRoot) : [scope];
|
|
933
550
|
const usages = [];
|
|
934
551
|
let totalCount = 0;
|
|
935
552
|
for (const docId of docIds) {
|
|
@@ -978,7 +595,7 @@ function registerAssetRoutes(server, ctx) {
|
|
|
978
595
|
}
|
|
979
596
|
assets.sort((a, b) => a.name.localeCompare(b.name));
|
|
980
597
|
if (assets.length > 0) {
|
|
981
|
-
const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
|
|
598
|
+
const scanIds = scope === "@global" ? await listDocIds$1(ctx.docsRoot) : [scope];
|
|
982
599
|
const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
|
|
983
600
|
const paths = assets.map((a) => a.importPath);
|
|
984
601
|
for (const docId of scanIds) {
|
|
@@ -1097,6 +714,401 @@ function registerAssetRoutes(server, ctx) {
|
|
|
1097
714
|
});
|
|
1098
715
|
}
|
|
1099
716
|
//#endregion
|
|
717
|
+
//#region src/editing/babel-walk.ts
|
|
718
|
+
function parseSource(code) {
|
|
719
|
+
try {
|
|
720
|
+
return parse(code, {
|
|
721
|
+
sourceType: "module",
|
|
722
|
+
plugins: ["typescript", "jsx"],
|
|
723
|
+
errorRecovery: true
|
|
724
|
+
});
|
|
725
|
+
} catch {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* `parseSource`, but a source with any recovered error is refused. Reading
|
|
731
|
+
* tolerates a document mid-edit; writing splices text in by AST offset, and a
|
|
732
|
+
* best-guess tree recovered from a syntax error must never decide where.
|
|
733
|
+
*/
|
|
734
|
+
function parseStrict(code) {
|
|
735
|
+
const ast = parseSource(code);
|
|
736
|
+
if (!ast) return null;
|
|
737
|
+
return ast.errors && ast.errors.length > 0 ? null : ast;
|
|
738
|
+
}
|
|
739
|
+
function isNode(value) {
|
|
740
|
+
return typeof value === "object" && value !== null && typeof value.type === "string";
|
|
741
|
+
}
|
|
742
|
+
/** Depth-first walk over every node; the visitor decides what it cares about. */
|
|
743
|
+
function walkAst(node, visit) {
|
|
744
|
+
if (Array.isArray(node)) {
|
|
745
|
+
for (const child of node) walkAst(child, visit);
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
if (!isNode(node)) return;
|
|
749
|
+
visit(node);
|
|
750
|
+
for (const key of Object.keys(node)) {
|
|
751
|
+
if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
|
|
752
|
+
walkAst(node[key], visit);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
function walkJsx(ast, visit) {
|
|
756
|
+
walkAst(ast, (node) => {
|
|
757
|
+
if (node.type === "JSXElement") visit(node);
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* The JSX element whose opening tag starts at this source position.
|
|
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 ?? [];
|
|
800
|
+
}
|
|
801
|
+
function metaObjectOf(node) {
|
|
802
|
+
if (node.type !== "ExportNamedDeclaration") return null;
|
|
803
|
+
const decl = node.declaration;
|
|
804
|
+
if (decl?.type !== "VariableDeclaration") return null;
|
|
805
|
+
const declarations = decl.declarations ?? [];
|
|
806
|
+
for (const d of declarations) {
|
|
807
|
+
const id = d.id;
|
|
808
|
+
if (id?.type !== "Identifier" || id.name !== "meta") continue;
|
|
809
|
+
let init = d.init;
|
|
810
|
+
if (!init) return null;
|
|
811
|
+
if (init.type === "TSSatisfiesExpression" || init.type === "TSAsExpression") {
|
|
812
|
+
const expr = init.expression;
|
|
813
|
+
if (expr) init = expr;
|
|
814
|
+
}
|
|
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
|
+
}
|
|
871
|
+
return null;
|
|
872
|
+
}
|
|
873
|
+
/** `q3-review` → `q3-review-copy`, `q3-review-copy` → `q3-review-copy-2`, … */
|
|
874
|
+
function nextCopyId(baseId, taken) {
|
|
875
|
+
const stem = baseId.replace(/-copy(-\d+)?$/, "");
|
|
876
|
+
let candidate = `${stem}-copy`;
|
|
877
|
+
let n = 2;
|
|
878
|
+
while (taken.has(candidate)) {
|
|
879
|
+
candidate = `${stem}-copy-${n}`;
|
|
880
|
+
n++;
|
|
881
|
+
}
|
|
882
|
+
return candidate;
|
|
883
|
+
}
|
|
884
|
+
function copyTitle(title) {
|
|
885
|
+
return /\(copy( \d+)?\)$/.test(title) ? title : `${title} (copy)`;
|
|
886
|
+
}
|
|
887
|
+
//#endregion
|
|
888
|
+
//#region src/files/folders.ts
|
|
889
|
+
const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
|
|
890
|
+
const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
|
|
891
|
+
function emptyManifest() {
|
|
892
|
+
return {
|
|
893
|
+
folders: [],
|
|
894
|
+
assignments: {}
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
async function readManifest(file) {
|
|
898
|
+
try {
|
|
899
|
+
const raw = await fs.readFile(file, "utf8");
|
|
900
|
+
const parsed = JSON.parse(raw);
|
|
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");
|
|
913
|
+
}
|
|
914
|
+
function newFolderId() {
|
|
915
|
+
return `f-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
|
916
|
+
}
|
|
917
|
+
function validateName(v) {
|
|
918
|
+
if (typeof v !== "string") return null;
|
|
919
|
+
const trimmed = v.trim();
|
|
920
|
+
if (trimmed.length < 1 || trimmed.length > 40) return null;
|
|
921
|
+
return trimmed;
|
|
922
|
+
}
|
|
923
|
+
function validateReorder(v, current) {
|
|
924
|
+
if (!Array.isArray(v) || v.length !== current.length) return null;
|
|
925
|
+
const known = new Set(current.map((f) => f.id));
|
|
926
|
+
const seen = /* @__PURE__ */ new Set();
|
|
927
|
+
const out = [];
|
|
928
|
+
for (const id of v) {
|
|
929
|
+
if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
|
|
930
|
+
if (!known.has(id) || seen.has(id)) return null;
|
|
931
|
+
seen.add(id);
|
|
932
|
+
out.push(id);
|
|
933
|
+
}
|
|
934
|
+
return out;
|
|
935
|
+
}
|
|
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
|
+
/**
|
|
959
|
+
* Operations shared by the dev API and the MCP server. Everything here takes an
|
|
960
|
+
* `ApiContext` and touches disk directly — no HTTP, so an agent calling a tool
|
|
961
|
+
* and a browser calling `/__docs` end up in exactly the same code.
|
|
962
|
+
*/
|
|
963
|
+
var OpsError = class extends Error {
|
|
964
|
+
status;
|
|
965
|
+
constructor(status, message) {
|
|
966
|
+
super(message);
|
|
967
|
+
this.status = status;
|
|
968
|
+
this.name = "OpsError";
|
|
969
|
+
}
|
|
970
|
+
};
|
|
971
|
+
const ENTRY_NAMES = [
|
|
972
|
+
"index.tsx",
|
|
973
|
+
"index.jsx",
|
|
974
|
+
"index.ts",
|
|
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;
|
|
982
|
+
}
|
|
983
|
+
function resolveEntry(ctx, docId) {
|
|
984
|
+
const dir = docDir(ctx, docId);
|
|
985
|
+
for (const name of ENTRY_NAMES) {
|
|
986
|
+
const file = path.join(dir, name);
|
|
987
|
+
if (existsSync(file)) return file;
|
|
988
|
+
}
|
|
989
|
+
return null;
|
|
990
|
+
}
|
|
991
|
+
async function listDocIds(ctx) {
|
|
992
|
+
try {
|
|
993
|
+
return (await fs.readdir(ctx.docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name).sort();
|
|
994
|
+
} catch {
|
|
995
|
+
return [];
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
/** Reads what the doc declares without executing it — a regex over `export const meta`. */
|
|
999
|
+
function readMetaField(source, field) {
|
|
1000
|
+
const re = new RegExp(`${field}\\s*:\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`);
|
|
1001
|
+
return source.slice(source.indexOf("export const meta")).match(re)?.[2];
|
|
1002
|
+
}
|
|
1003
|
+
async function listDocuments(ctx) {
|
|
1004
|
+
const ids = await listDocIds(ctx);
|
|
1005
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1006
|
+
const out = [];
|
|
1007
|
+
for (const id of ids) {
|
|
1008
|
+
const entry = resolveEntry(ctx, id);
|
|
1009
|
+
const source = entry ? await fs.readFile(entry, "utf8") : "";
|
|
1010
|
+
out.push({
|
|
1011
|
+
id,
|
|
1012
|
+
title: source ? readMetaTitle(source) : null,
|
|
1013
|
+
subtitle: source ? readMetaField(source, "subtitle") : void 0,
|
|
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
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
return out;
|
|
1021
|
+
}
|
|
1022
|
+
async function readDocument(ctx, docId) {
|
|
1023
|
+
const entry = resolveEntry(ctx, docId);
|
|
1024
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1025
|
+
return {
|
|
1026
|
+
id: docId,
|
|
1027
|
+
entry: path.relative(ctx.userCwd, entry),
|
|
1028
|
+
source: await fs.readFile(entry, "utf8")
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
async function createDocument(ctx, docId, source) {
|
|
1032
|
+
const dir = docDir(ctx, docId);
|
|
1033
|
+
if (existsSync(dir)) throw new OpsError(409, `document already exists: ${docId}`);
|
|
1034
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1035
|
+
const entry = path.join(dir, "index.tsx");
|
|
1036
|
+
await fs.writeFile(entry, source, "utf8");
|
|
1037
|
+
return {
|
|
1038
|
+
id: docId,
|
|
1039
|
+
entry: path.relative(ctx.userCwd, entry)
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Whole-file overwrite. `expected` is the source the caller believes is on
|
|
1044
|
+
* disk; passing it turns a blind overwrite into a conflict check, which is what
|
|
1045
|
+
* keeps two agents (or an agent and a person) from clobbering each other.
|
|
1046
|
+
*/
|
|
1047
|
+
async function writeDocument(ctx, docId, source, expected) {
|
|
1048
|
+
const entry = resolveEntry(ctx, docId);
|
|
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
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
async function renameDocument(ctx, docId, rawTitle) {
|
|
1060
|
+
const title = validateDocTitle(rawTitle);
|
|
1061
|
+
if (!title) throw new OpsError(400, "invalid title");
|
|
1062
|
+
const entry = resolveEntry(ctx, docId);
|
|
1063
|
+
if (!entry) throw new OpsError(404, `document not found: ${docId}`);
|
|
1064
|
+
const source = await fs.readFile(entry, "utf8");
|
|
1065
|
+
const next = setMetaTitle(source, title);
|
|
1066
|
+
if (next === null) throw new OpsError(422, "document has no `export const meta` object to rename");
|
|
1067
|
+
if (next !== source) await fs.writeFile(entry, next, "utf8");
|
|
1068
|
+
return {
|
|
1069
|
+
id: docId,
|
|
1070
|
+
title
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
async function duplicateDocument(ctx, docId, newId) {
|
|
1074
|
+
const dir = docDir(ctx, docId);
|
|
1075
|
+
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
1076
|
+
const taken = new Set(await listDocIds(ctx));
|
|
1077
|
+
let targetId;
|
|
1078
|
+
if (newId) {
|
|
1079
|
+
if (!DOC_ID_RE.test(newId)) throw new OpsError(400, `invalid newId: ${newId}`);
|
|
1080
|
+
if (taken.has(newId)) throw new OpsError(409, `document already exists: ${newId}`);
|
|
1081
|
+
targetId = newId;
|
|
1082
|
+
} else targetId = nextCopyId(docId, taken);
|
|
1083
|
+
await fs.cp(dir, docDir(ctx, targetId), { recursive: true });
|
|
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);
|
|
1095
|
+
}
|
|
1096
|
+
return { id: targetId };
|
|
1097
|
+
}
|
|
1098
|
+
async function deleteDocument(ctx, docId) {
|
|
1099
|
+
const dir = docDir(ctx, docId);
|
|
1100
|
+
if (!existsSync(dir)) throw new OpsError(404, `document not found: ${docId}`);
|
|
1101
|
+
await fs.rm(dir, {
|
|
1102
|
+
recursive: true,
|
|
1103
|
+
force: true
|
|
1104
|
+
});
|
|
1105
|
+
const manifest = await readManifest(ctx.manifestPath);
|
|
1106
|
+
if (manifest.assignments[docId]) {
|
|
1107
|
+
delete manifest.assignments[docId];
|
|
1108
|
+
await writeManifest(ctx.manifestPath, manifest);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
//#endregion
|
|
1100
1112
|
//#region src/vite/routes/docs.ts
|
|
1101
1113
|
function registerDocRoutes(server, ctx) {
|
|
1102
1114
|
server.middlewares.use("/__docs", async (req, res, next) => {
|
|
@@ -1923,32 +1935,31 @@ function slotText(slot, edit) {
|
|
|
1923
1935
|
if (!slot.jsx || !edit.segments) return slot.escape(edit.text);
|
|
1924
1936
|
return renderSegments(mergeSegments(edit.segments), slot.escape);
|
|
1925
1937
|
}
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
* later one is refused rather than silently winning.
|
|
1938
|
-
*/
|
|
1938
|
+
const SYNTAX_ERROR = {
|
|
1939
|
+
ok: false,
|
|
1940
|
+
status: 422,
|
|
1941
|
+
error: "the document has a syntax error — fix it in source before editing here"
|
|
1942
|
+
};
|
|
1943
|
+
/** Applies non-overlapping splices, all located against the same source, back to front. */
|
|
1944
|
+
function applySplices(source, splices) {
|
|
1945
|
+
let next = source;
|
|
1946
|
+
for (const splice of [...splices].sort((a, b) => b.start - a.start)) next = next.slice(0, splice.start) + splice.text + next.slice(splice.end);
|
|
1947
|
+
return next;
|
|
1948
|
+
}
|
|
1939
1949
|
function replaceTextsAt(source, edits) {
|
|
1940
1950
|
const ast = parseStrict(source);
|
|
1941
|
-
if (!ast) {
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1951
|
+
if (!ast) return {
|
|
1952
|
+
source,
|
|
1953
|
+
results: edits.map(() => SYNTAX_ERROR)
|
|
1954
|
+
};
|
|
1955
|
+
const { splices, results } = planTextEdits(ast, source, edits);
|
|
1956
|
+
return {
|
|
1957
|
+
source: applySplices(source, splices),
|
|
1958
|
+
results
|
|
1959
|
+
};
|
|
1960
|
+
}
|
|
1961
|
+
/** Where each text edit lands in `source`, without writing any of them. */
|
|
1962
|
+
function planTextEdits(ast, source, edits) {
|
|
1952
1963
|
const results = [];
|
|
1953
1964
|
const planned = [];
|
|
1954
1965
|
for (const edit of edits) {
|
|
@@ -1998,14 +2009,506 @@ function replaceTextsAt(source, edits) {
|
|
|
1998
2009
|
});
|
|
1999
2010
|
results.push({ ok: true });
|
|
2000
2011
|
}
|
|
2001
|
-
let next = source;
|
|
2002
|
-
for (const { slot, text } of [...planned].sort((a, b) => b.slot.start - a.slot.start)) next = next.slice(0, slot.start) + text + next.slice(slot.end);
|
|
2003
2012
|
return {
|
|
2004
|
-
|
|
2013
|
+
splices: planned.map(({ slot, text }) => ({
|
|
2014
|
+
start: slot.start,
|
|
2015
|
+
end: slot.end,
|
|
2016
|
+
text
|
|
2017
|
+
})),
|
|
2005
2018
|
results
|
|
2006
2019
|
};
|
|
2007
2020
|
}
|
|
2008
2021
|
//#endregion
|
|
2022
|
+
//#region src/app/lib/inspector/format.ts
|
|
2023
|
+
/**
|
|
2024
|
+
* The element panel's Format section, shared by the viewer and the dev server:
|
|
2025
|
+
* which style keys it may write, which design tokens each one offers, and what
|
|
2026
|
+
* a value has to look like before it is spliced into a document's source.
|
|
2027
|
+
*/
|
|
2028
|
+
const STYLE_PROPS = [
|
|
2029
|
+
"fontFamily",
|
|
2030
|
+
"fontSize",
|
|
2031
|
+
"fontWeight",
|
|
2032
|
+
"fontStyle",
|
|
2033
|
+
"textAlign",
|
|
2034
|
+
"lineHeight",
|
|
2035
|
+
"letterSpacing",
|
|
2036
|
+
"color",
|
|
2037
|
+
"background"
|
|
2038
|
+
];
|
|
2039
|
+
function isStyleProp(value) {
|
|
2040
|
+
return typeof value === "string" && STYLE_PROPS.includes(value);
|
|
2041
|
+
}
|
|
2042
|
+
/** The `--od-*` variables a document's design const defines, by what they can stand for. */
|
|
2043
|
+
const TOKENS = {
|
|
2044
|
+
font: [
|
|
2045
|
+
{
|
|
2046
|
+
token: "font-heading",
|
|
2047
|
+
label: "Heading"
|
|
2048
|
+
},
|
|
2049
|
+
{
|
|
2050
|
+
token: "font-body",
|
|
2051
|
+
label: "Body"
|
|
2052
|
+
},
|
|
2053
|
+
{
|
|
2054
|
+
token: "font-mono",
|
|
2055
|
+
label: "Mono"
|
|
2056
|
+
}
|
|
2057
|
+
],
|
|
2058
|
+
size: [
|
|
2059
|
+
{
|
|
2060
|
+
token: "size-title",
|
|
2061
|
+
label: "Title"
|
|
2062
|
+
},
|
|
2063
|
+
{
|
|
2064
|
+
token: "size-h1",
|
|
2065
|
+
label: "H1"
|
|
2066
|
+
},
|
|
2067
|
+
{
|
|
2068
|
+
token: "size-h2",
|
|
2069
|
+
label: "H2"
|
|
2070
|
+
},
|
|
2071
|
+
{
|
|
2072
|
+
token: "size-h3",
|
|
2073
|
+
label: "H3"
|
|
2074
|
+
},
|
|
2075
|
+
{
|
|
2076
|
+
token: "size-body",
|
|
2077
|
+
label: "Body"
|
|
2078
|
+
},
|
|
2079
|
+
{
|
|
2080
|
+
token: "size-caption",
|
|
2081
|
+
label: "Caption"
|
|
2082
|
+
}
|
|
2083
|
+
],
|
|
2084
|
+
color: [
|
|
2085
|
+
{
|
|
2086
|
+
token: "text",
|
|
2087
|
+
label: "Text"
|
|
2088
|
+
},
|
|
2089
|
+
{
|
|
2090
|
+
token: "muted",
|
|
2091
|
+
label: "Muted"
|
|
2092
|
+
},
|
|
2093
|
+
{
|
|
2094
|
+
token: "accent",
|
|
2095
|
+
label: "Accent"
|
|
2096
|
+
},
|
|
2097
|
+
{
|
|
2098
|
+
token: "rule",
|
|
2099
|
+
label: "Rule"
|
|
2100
|
+
},
|
|
2101
|
+
{
|
|
2102
|
+
token: "bg",
|
|
2103
|
+
label: "Background"
|
|
2104
|
+
}
|
|
2105
|
+
],
|
|
2106
|
+
leading: [{
|
|
2107
|
+
token: "leading",
|
|
2108
|
+
label: "Leading"
|
|
2109
|
+
}]
|
|
2110
|
+
};
|
|
2111
|
+
const PROP_TOKENS = {
|
|
2112
|
+
fontFamily: "font",
|
|
2113
|
+
fontSize: "size",
|
|
2114
|
+
color: "color",
|
|
2115
|
+
background: "color",
|
|
2116
|
+
lineHeight: "leading"
|
|
2117
|
+
};
|
|
2118
|
+
const TOKEN_VALUE = /^var\(\s*--od-([a-z0-9-]+)\s*\)$/;
|
|
2119
|
+
/** `var(--od-accent)` → `accent`; anything else is not a token reference. */
|
|
2120
|
+
function tokenOf(value) {
|
|
2121
|
+
return TOKEN_VALUE.exec(value.trim())?.[1] ?? null;
|
|
2122
|
+
}
|
|
2123
|
+
function isToken(prop, value) {
|
|
2124
|
+
const group = PROP_TOKENS[prop];
|
|
2125
|
+
const token = tokenOf(value);
|
|
2126
|
+
return group !== void 0 && token !== null && TOKENS[group].some((t) => t.token === token);
|
|
2127
|
+
}
|
|
2128
|
+
const LENGTH = /^-?\d+(\.\d+)?(px|em|rem)$/;
|
|
2129
|
+
const HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
|
2130
|
+
const PLAIN = /^[^;{}<>\\\n\r]{1,200}$/;
|
|
2131
|
+
/** Whether the panel may write this value for this key — the server's check, run again in the viewer. */
|
|
2132
|
+
function isValidStyleValue(prop, value) {
|
|
2133
|
+
if (value === null) return true;
|
|
2134
|
+
if (typeof value === "number") {
|
|
2135
|
+
if (!Number.isFinite(value)) return false;
|
|
2136
|
+
if (prop === "fontWeight") return value >= 100 && value <= 900 && value % 100 === 0;
|
|
2137
|
+
if (prop === "lineHeight") return value > 0 && value <= 10;
|
|
2138
|
+
return false;
|
|
2139
|
+
}
|
|
2140
|
+
if (!PLAIN.test(value)) return false;
|
|
2141
|
+
if (isToken(prop, value)) return true;
|
|
2142
|
+
switch (prop) {
|
|
2143
|
+
case "fontFamily": return tokenOf(value) === null;
|
|
2144
|
+
case "fontSize": return LENGTH.test(value) && !value.startsWith("-");
|
|
2145
|
+
case "letterSpacing": return LENGTH.test(value) || value === "normal";
|
|
2146
|
+
case "fontWeight": return value === "normal" || value === "bold";
|
|
2147
|
+
case "fontStyle": return value === "normal" || value === "italic";
|
|
2148
|
+
case "textAlign": return [
|
|
2149
|
+
"left",
|
|
2150
|
+
"center",
|
|
2151
|
+
"right",
|
|
2152
|
+
"justify",
|
|
2153
|
+
"start",
|
|
2154
|
+
"end"
|
|
2155
|
+
].includes(value);
|
|
2156
|
+
case "lineHeight": return value === "normal";
|
|
2157
|
+
case "color":
|
|
2158
|
+
case "background": return HEX.test(value) || value === "transparent";
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
//#endregion
|
|
2162
|
+
//#region src/editing/style-ops.ts
|
|
2163
|
+
function unwrap(node) {
|
|
2164
|
+
let current = node;
|
|
2165
|
+
while (current && (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "ParenthesizedExpression")) current = current.expression;
|
|
2166
|
+
return current;
|
|
2167
|
+
}
|
|
2168
|
+
function keyOf(property) {
|
|
2169
|
+
if (property.type !== "ObjectProperty" || property.computed) return null;
|
|
2170
|
+
const key = property.key;
|
|
2171
|
+
if (key.type === "Identifier") return key.name;
|
|
2172
|
+
if (key.type === "StringLiteral") return key.value;
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
function sourceOf$1(value, source) {
|
|
2176
|
+
const node = unwrap(value) ?? value;
|
|
2177
|
+
if (node.type === "StringLiteral") {
|
|
2178
|
+
const text = node.value;
|
|
2179
|
+
const token = tokenOf(text);
|
|
2180
|
+
return token ? {
|
|
2181
|
+
kind: "token",
|
|
2182
|
+
token
|
|
2183
|
+
} : {
|
|
2184
|
+
kind: "literal",
|
|
2185
|
+
value: text
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
if (node.type === "NumericLiteral") return {
|
|
2189
|
+
kind: "literal",
|
|
2190
|
+
value: node.value
|
|
2191
|
+
};
|
|
2192
|
+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) {
|
|
2193
|
+
const text = (node.quasis[0]?.value)?.cooked ?? "";
|
|
2194
|
+
const token = tokenOf(text);
|
|
2195
|
+
return token ? {
|
|
2196
|
+
kind: "token",
|
|
2197
|
+
token
|
|
2198
|
+
} : {
|
|
2199
|
+
kind: "literal",
|
|
2200
|
+
value: text
|
|
2201
|
+
};
|
|
2202
|
+
}
|
|
2203
|
+
return {
|
|
2204
|
+
kind: "code",
|
|
2205
|
+
code: source.slice(value.start, value.end)
|
|
2206
|
+
};
|
|
2207
|
+
}
|
|
2208
|
+
/** A top-level `const name = { … }` — the shared style objects documents are written with. */
|
|
2209
|
+
function sharedObject(ast, name) {
|
|
2210
|
+
const body = ast.program?.body ?? [];
|
|
2211
|
+
for (const statement of body) {
|
|
2212
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
2213
|
+
if (declaration?.type !== "VariableDeclaration") continue;
|
|
2214
|
+
for (const declarator of declaration.declarations) {
|
|
2215
|
+
const id = declarator.id;
|
|
2216
|
+
if (id.type !== "Identifier" || id.name !== name) continue;
|
|
2217
|
+
const init = unwrap(declarator.init);
|
|
2218
|
+
return init?.type === "ObjectExpression" ? init : null;
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
return null;
|
|
2222
|
+
}
|
|
2223
|
+
/** Folds an object's keys into `props`, later keys over earlier ones, as the spread would. */
|
|
2224
|
+
function readObject(ast, object, source, from, props, depth) {
|
|
2225
|
+
for (const property of object.properties) {
|
|
2226
|
+
if (property.type === "SpreadElement") {
|
|
2227
|
+
const argument = unwrap(property.argument);
|
|
2228
|
+
if (argument?.type !== "Identifier" || depth > 3) continue;
|
|
2229
|
+
const shared = sharedObject(ast, argument.name);
|
|
2230
|
+
if (shared) readObject(ast, shared, source, argument.name, props, depth + 1);
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
const key = keyOf(property);
|
|
2234
|
+
const prop = key === "backgroundColor" ? "background" : key;
|
|
2235
|
+
if (!isStyleProp(prop)) continue;
|
|
2236
|
+
const origin = sourceOf$1(property.value, source);
|
|
2237
|
+
props[prop] = from ? {
|
|
2238
|
+
...origin,
|
|
2239
|
+
from
|
|
2240
|
+
} : origin;
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
function locate(ast, loc, tag) {
|
|
2244
|
+
const element = findJsxAt(ast, loc.line, loc.column);
|
|
2245
|
+
if (!element) return {
|
|
2246
|
+
ok: false,
|
|
2247
|
+
status: 404,
|
|
2248
|
+
error: "element not found"
|
|
2249
|
+
};
|
|
2250
|
+
const opening = element.openingElement;
|
|
2251
|
+
const name = opening.name;
|
|
2252
|
+
if (name.type !== "JSXIdentifier" || !/^[a-z]/.test(name.name)) return {
|
|
2253
|
+
ok: false,
|
|
2254
|
+
status: 422,
|
|
2255
|
+
error: "This is a component — its styles are set inside it, not here."
|
|
2256
|
+
};
|
|
2257
|
+
if (name.name !== tag) return {
|
|
2258
|
+
ok: false,
|
|
2259
|
+
status: 409,
|
|
2260
|
+
error: "source does not match this element"
|
|
2261
|
+
};
|
|
2262
|
+
const attrs = opening.attributes.filter((attr) => attr.type === "JSXAttribute" && attr.name.name === "style");
|
|
2263
|
+
const attr = attrs[attrs.length - 1] ?? null;
|
|
2264
|
+
if (!attr) return {
|
|
2265
|
+
ok: true,
|
|
2266
|
+
opening,
|
|
2267
|
+
attr: null,
|
|
2268
|
+
expression: null
|
|
2269
|
+
};
|
|
2270
|
+
const value = attr.value;
|
|
2271
|
+
if (value?.type !== "JSXExpressionContainer") return {
|
|
2272
|
+
ok: false,
|
|
2273
|
+
status: 422,
|
|
2274
|
+
error: "This element’s style is not written as an object."
|
|
2275
|
+
};
|
|
2276
|
+
return {
|
|
2277
|
+
ok: true,
|
|
2278
|
+
opening,
|
|
2279
|
+
attr,
|
|
2280
|
+
expression: value.expression
|
|
2281
|
+
};
|
|
2282
|
+
}
|
|
2283
|
+
function readProps(ast, source, expression) {
|
|
2284
|
+
const props = {};
|
|
2285
|
+
const node = unwrap(expression ?? void 0);
|
|
2286
|
+
if (node?.type === "ObjectExpression") readObject(ast, node, source, void 0, props, 0);
|
|
2287
|
+
else if (node?.type === "Identifier") {
|
|
2288
|
+
const shared = sharedObject(ast, node.name);
|
|
2289
|
+
if (shared) readObject(ast, shared, source, node.name, props, 1);
|
|
2290
|
+
}
|
|
2291
|
+
return props;
|
|
2292
|
+
}
|
|
2293
|
+
/** What the element at `loc` sets, key by key, for the panel to show before anything is written. */
|
|
2294
|
+
function readStyleAt(source, loc, tag) {
|
|
2295
|
+
const ast = parseSource(source);
|
|
2296
|
+
if (!ast) return {
|
|
2297
|
+
editable: false,
|
|
2298
|
+
reason: "could not read source"
|
|
2299
|
+
};
|
|
2300
|
+
const found = locate(ast, loc, tag);
|
|
2301
|
+
if (!found.ok) return {
|
|
2302
|
+
editable: false,
|
|
2303
|
+
reason: found.error
|
|
2304
|
+
};
|
|
2305
|
+
return {
|
|
2306
|
+
editable: true,
|
|
2307
|
+
props: readProps(ast, source, found.expression)
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
function literal(value) {
|
|
2311
|
+
if (typeof value === "number") return String(value);
|
|
2312
|
+
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
2313
|
+
}
|
|
2314
|
+
function lineIndent(source, offset) {
|
|
2315
|
+
const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
|
|
2316
|
+
return /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? "";
|
|
2317
|
+
}
|
|
2318
|
+
function lineOf(source, offset) {
|
|
2319
|
+
let line = 0;
|
|
2320
|
+
for (let i = source.indexOf("\n"); i !== -1 && i < offset; i = source.indexOf("\n", i + 1)) line++;
|
|
2321
|
+
return line;
|
|
2322
|
+
}
|
|
2323
|
+
/** Writes the keys into an object literal, touching only what changes. */
|
|
2324
|
+
function planObject(source, object, sets, removes, attr) {
|
|
2325
|
+
const properties = object.properties;
|
|
2326
|
+
const lastSpread = properties.reduce((at, property, index) => property.type === "SpreadElement" ? index : at, -1);
|
|
2327
|
+
const ownIndex = (prop) => {
|
|
2328
|
+
for (let i = properties.length - 1; i > lastSpread; i--) {
|
|
2329
|
+
const key = keyOf(properties[i]);
|
|
2330
|
+
if (key === prop || prop === "background" && key === "backgroundColor") return i;
|
|
2331
|
+
}
|
|
2332
|
+
return -1;
|
|
2333
|
+
};
|
|
2334
|
+
const replaced = /* @__PURE__ */ new Map();
|
|
2335
|
+
const appended = [];
|
|
2336
|
+
for (const [prop, value] of sets) {
|
|
2337
|
+
const index = ownIndex(prop);
|
|
2338
|
+
if (index === -1) appended.push(`${prop}: ${literal(value)}`);
|
|
2339
|
+
else replaced.set(index, literal(value));
|
|
2340
|
+
}
|
|
2341
|
+
const removed = new Set(removes.map(ownIndex).filter((index) => index !== -1));
|
|
2342
|
+
if (removed.size === 0) {
|
|
2343
|
+
const splices = [];
|
|
2344
|
+
for (const [index, text] of replaced) {
|
|
2345
|
+
const value = properties[index].value;
|
|
2346
|
+
const shorthand = properties[index].shorthand === true;
|
|
2347
|
+
splices.push(shorthand ? {
|
|
2348
|
+
start: properties[index].start,
|
|
2349
|
+
end: properties[index].end,
|
|
2350
|
+
text: `${keyOf(properties[index])}: ${text}`
|
|
2351
|
+
} : {
|
|
2352
|
+
start: value.start,
|
|
2353
|
+
end: value.end,
|
|
2354
|
+
text
|
|
2355
|
+
});
|
|
2356
|
+
}
|
|
2357
|
+
if (appended.length > 0) {
|
|
2358
|
+
const last = properties[properties.length - 1];
|
|
2359
|
+
if (!last) splices.push({
|
|
2360
|
+
start: object.start,
|
|
2361
|
+
end: object.end,
|
|
2362
|
+
text: `{ ${appended.join(", ")} }`
|
|
2363
|
+
});
|
|
2364
|
+
else if (lineOf(source, last.start) > lineOf(source, object.start)) {
|
|
2365
|
+
const indent = lineIndent(source, last.start);
|
|
2366
|
+
const after = /^\s*,/.exec(source.slice(last.end));
|
|
2367
|
+
splices.push(after ? {
|
|
2368
|
+
start: last.end + after[0].length,
|
|
2369
|
+
end: last.end + after[0].length,
|
|
2370
|
+
text: appended.map((item) => `\n${indent}${item},`).join("")
|
|
2371
|
+
} : {
|
|
2372
|
+
start: last.end,
|
|
2373
|
+
end: last.end,
|
|
2374
|
+
text: appended.map((item) => `,\n${indent}${item}`).join("")
|
|
2375
|
+
});
|
|
2376
|
+
} else splices.push({
|
|
2377
|
+
start: last.end,
|
|
2378
|
+
end: last.end,
|
|
2379
|
+
text: `, ${appended.join(", ")}`
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
return splices;
|
|
2383
|
+
}
|
|
2384
|
+
const items = [];
|
|
2385
|
+
properties.forEach((property, index) => {
|
|
2386
|
+
if (removed.has(index)) return;
|
|
2387
|
+
const text = replaced.get(index);
|
|
2388
|
+
items.push(text === void 0 ? source.slice(property.start, property.end) : `${keyOf(property)}: ${text}`);
|
|
2389
|
+
});
|
|
2390
|
+
items.push(...appended);
|
|
2391
|
+
if (items.length === 0) return [{
|
|
2392
|
+
start: /\s*$/.exec(source.slice(0, attr.start))?.index ?? attr.start,
|
|
2393
|
+
end: attr.end,
|
|
2394
|
+
text: ""
|
|
2395
|
+
}];
|
|
2396
|
+
const first = properties[0];
|
|
2397
|
+
if (lineOf(source, first.start) > lineOf(source, object.start)) {
|
|
2398
|
+
const indent = lineIndent(source, first.start);
|
|
2399
|
+
const closing = lineIndent(source, object.end - 1);
|
|
2400
|
+
return [{
|
|
2401
|
+
start: object.start,
|
|
2402
|
+
end: object.end,
|
|
2403
|
+
text: `{\n${items.map((item) => `${indent}${item},\n`).join("")}${closing}}`
|
|
2404
|
+
}];
|
|
2405
|
+
}
|
|
2406
|
+
return [{
|
|
2407
|
+
start: object.start,
|
|
2408
|
+
end: object.end,
|
|
2409
|
+
text: `{ ${items.join(", ")} }`
|
|
2410
|
+
}];
|
|
2411
|
+
}
|
|
2412
|
+
function planStyle(ast, source, edit) {
|
|
2413
|
+
const found = locate(ast, edit, edit.tag);
|
|
2414
|
+
if (!found.ok) return found;
|
|
2415
|
+
const sets = [];
|
|
2416
|
+
const removes = [];
|
|
2417
|
+
const current = readProps(ast, source, found.expression);
|
|
2418
|
+
for (const [prop, value] of Object.entries(edit.changes)) {
|
|
2419
|
+
if (!isStyleProp(prop)) return {
|
|
2420
|
+
ok: false,
|
|
2421
|
+
status: 400,
|
|
2422
|
+
error: `not a style the panel writes: ${prop}`
|
|
2423
|
+
};
|
|
2424
|
+
if (!isValidStyleValue(prop, value)) return {
|
|
2425
|
+
ok: false,
|
|
2426
|
+
status: 422,
|
|
2427
|
+
error: `not a value ${prop} can take: ${String(value)}`
|
|
2428
|
+
};
|
|
2429
|
+
if (edit.expected && prop in edit.expected) {
|
|
2430
|
+
if (JSON.stringify(current[prop] ?? null) !== JSON.stringify(edit.expected[prop] ?? null)) return {
|
|
2431
|
+
ok: false,
|
|
2432
|
+
status: 409,
|
|
2433
|
+
error: "this element’s style changed in source since it was selected"
|
|
2434
|
+
};
|
|
2435
|
+
}
|
|
2436
|
+
if (value === null) removes.push(prop);
|
|
2437
|
+
else sets.push([prop, value]);
|
|
2438
|
+
}
|
|
2439
|
+
const { opening, attr, expression } = found;
|
|
2440
|
+
const object = unwrap(expression ?? void 0);
|
|
2441
|
+
if (attr && object?.type === "ObjectExpression") return {
|
|
2442
|
+
ok: true,
|
|
2443
|
+
splices: planObject(source, object, sets, removes, attr)
|
|
2444
|
+
};
|
|
2445
|
+
if (sets.length === 0) return {
|
|
2446
|
+
ok: true,
|
|
2447
|
+
splices: []
|
|
2448
|
+
};
|
|
2449
|
+
const items = sets.map(([prop, value]) => `${prop}: ${literal(value)}`).join(", ");
|
|
2450
|
+
if (attr && expression) return {
|
|
2451
|
+
ok: true,
|
|
2452
|
+
splices: [{
|
|
2453
|
+
start: expression.start,
|
|
2454
|
+
end: expression.end,
|
|
2455
|
+
text: `{ ...${source.slice(expression.start, expression.end)}, ${items} }`
|
|
2456
|
+
}]
|
|
2457
|
+
};
|
|
2458
|
+
const attributes = opening.attributes;
|
|
2459
|
+
const after = attributes[attributes.length - 1] ?? opening.name;
|
|
2460
|
+
return {
|
|
2461
|
+
ok: true,
|
|
2462
|
+
splices: [{
|
|
2463
|
+
start: after.end,
|
|
2464
|
+
end: after.end,
|
|
2465
|
+
text: ` style={{ ${items} }}`
|
|
2466
|
+
}]
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
function overlaps(a, b) {
|
|
2470
|
+
return a.start < b.end && b.start < a.end;
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Text and style changes from one save, located against the same source and
|
|
2474
|
+
* written as one splice pass — so a save that retyped a heading and resized it
|
|
2475
|
+
* is one write and one hot reload, and neither edit's location is moved by
|
|
2476
|
+
* the other before it is found.
|
|
2477
|
+
*/
|
|
2478
|
+
function replaceEditsAt(source, texts, styles) {
|
|
2479
|
+
const ast = parseStrict(source);
|
|
2480
|
+
if (!ast) return {
|
|
2481
|
+
source,
|
|
2482
|
+
texts: texts.map(() => SYNTAX_ERROR),
|
|
2483
|
+
styles: styles.map(() => SYNTAX_ERROR)
|
|
2484
|
+
};
|
|
2485
|
+
const text = planTextEdits(ast, source, texts);
|
|
2486
|
+
const splices = [...text.splices];
|
|
2487
|
+
const results = [];
|
|
2488
|
+
for (const edit of styles) {
|
|
2489
|
+
const planned = planStyle(ast, source, edit);
|
|
2490
|
+
if (!planned.ok) {
|
|
2491
|
+
results.push(planned);
|
|
2492
|
+
continue;
|
|
2493
|
+
}
|
|
2494
|
+
if (planned.splices.some((splice) => splices.some((other) => overlaps(splice, other)))) {
|
|
2495
|
+
results.push({
|
|
2496
|
+
ok: false,
|
|
2497
|
+
status: 409,
|
|
2498
|
+
error: "another edit in this save rewrites the same source"
|
|
2499
|
+
});
|
|
2500
|
+
continue;
|
|
2501
|
+
}
|
|
2502
|
+
splices.push(...planned.splices);
|
|
2503
|
+
results.push({ ok: true });
|
|
2504
|
+
}
|
|
2505
|
+
return {
|
|
2506
|
+
source: applySplices(source, splices),
|
|
2507
|
+
texts: text.results,
|
|
2508
|
+
styles: results
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2511
|
+
//#endregion
|
|
2009
2512
|
//#region src/ops/text.ts
|
|
2010
2513
|
async function sourceOf(ctx, docId) {
|
|
2011
2514
|
const entry = resolveEntry(ctx, docId);
|
|
@@ -2054,6 +2557,26 @@ async function writeTexts(ctx, docId, edits) {
|
|
|
2054
2557
|
if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
|
|
2055
2558
|
return { results: result.results };
|
|
2056
2559
|
}
|
|
2560
|
+
/** What the element at `loc` sets in its `style`, key by key, for the element panel's Format section. */
|
|
2561
|
+
async function readStyle(ctx, docId, loc, tag) {
|
|
2562
|
+
const { source } = await sourceOf(ctx, docId);
|
|
2563
|
+
return readStyleAt(source, loc, tag);
|
|
2564
|
+
}
|
|
2565
|
+
/**
|
|
2566
|
+
* One save from the element panel: retyped text and style changes, located
|
|
2567
|
+
* against the same read of the file and written once. Per-edit failures are
|
|
2568
|
+
* reported, not thrown, like `writeTexts`.
|
|
2569
|
+
*/
|
|
2570
|
+
async function writeEdits(ctx, docId, texts, styles) {
|
|
2571
|
+
if (texts.length + styles.length === 0) throw new OpsError(400, "at least one edit is required");
|
|
2572
|
+
const { entry, source } = await sourceOf(ctx, docId);
|
|
2573
|
+
const result = replaceEditsAt(source, texts, styles);
|
|
2574
|
+
if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
|
|
2575
|
+
return {
|
|
2576
|
+
texts: result.texts,
|
|
2577
|
+
styles: result.styles
|
|
2578
|
+
};
|
|
2579
|
+
}
|
|
2057
2580
|
/** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
|
|
2058
2581
|
async function addComment(ctx, docId, loc, note, hint) {
|
|
2059
2582
|
if (note.trim() === "") throw new OpsError(400, "note is empty");
|
|
@@ -2090,6 +2613,54 @@ function readSegments(value) {
|
|
|
2090
2613
|
}
|
|
2091
2614
|
return segments;
|
|
2092
2615
|
}
|
|
2616
|
+
function readTextEdits(docId, value) {
|
|
2617
|
+
if (!Array.isArray(value)) return null;
|
|
2618
|
+
const edits = [];
|
|
2619
|
+
for (const raw of value) {
|
|
2620
|
+
const loc = readLoc({
|
|
2621
|
+
...raw,
|
|
2622
|
+
docId
|
|
2623
|
+
});
|
|
2624
|
+
if (!loc || typeof raw.text !== "string") return null;
|
|
2625
|
+
edits.push({
|
|
2626
|
+
line: loc.line,
|
|
2627
|
+
column: loc.column,
|
|
2628
|
+
text: raw.text,
|
|
2629
|
+
segments: readSegments(raw.segments),
|
|
2630
|
+
index: typeof raw.index === "number" ? raw.index : void 0,
|
|
2631
|
+
prop: typeof raw.prop === "string" ? raw.prop : void 0,
|
|
2632
|
+
expected: typeof raw.expected === "string" ? raw.expected : void 0,
|
|
2633
|
+
shown: typeof raw.shown === "string" ? raw.shown : void 0
|
|
2634
|
+
});
|
|
2635
|
+
}
|
|
2636
|
+
return edits;
|
|
2637
|
+
}
|
|
2638
|
+
function readStyleEdits(docId, value) {
|
|
2639
|
+
if (!Array.isArray(value)) return null;
|
|
2640
|
+
const edits = [];
|
|
2641
|
+
for (const raw of value) {
|
|
2642
|
+
const loc = readLoc({
|
|
2643
|
+
...raw,
|
|
2644
|
+
docId
|
|
2645
|
+
});
|
|
2646
|
+
const changes = raw.changes;
|
|
2647
|
+
if (!loc || typeof raw.tag !== "string" || typeof changes !== "object" || !changes) return null;
|
|
2648
|
+
const clean = {};
|
|
2649
|
+
for (const [key, change] of Object.entries(changes)) {
|
|
2650
|
+
if (change !== null && typeof change !== "string" && typeof change !== "number") return null;
|
|
2651
|
+
clean[key] = change;
|
|
2652
|
+
}
|
|
2653
|
+
const expected = typeof raw.expected === "object" && raw.expected !== null ? raw.expected : void 0;
|
|
2654
|
+
edits.push({
|
|
2655
|
+
line: loc.line,
|
|
2656
|
+
column: loc.column,
|
|
2657
|
+
tag: raw.tag,
|
|
2658
|
+
changes: clean,
|
|
2659
|
+
...expected ? { expected } : {}
|
|
2660
|
+
});
|
|
2661
|
+
}
|
|
2662
|
+
return edits;
|
|
2663
|
+
}
|
|
2093
2664
|
function registerEditRoutes(server, ctx) {
|
|
2094
2665
|
const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
|
|
2095
2666
|
server.middlewares.use("/__edit", async (req, res, next) => {
|
|
@@ -2133,26 +2704,30 @@ function registerEditRoutes(server, ctx) {
|
|
|
2133
2704
|
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
2134
2705
|
const body = await readBody(req);
|
|
2135
2706
|
if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
|
|
2136
|
-
const edits =
|
|
2137
|
-
|
|
2138
|
-
const loc = readLoc({
|
|
2139
|
-
...raw,
|
|
2140
|
-
docId: body.docId
|
|
2141
|
-
});
|
|
2142
|
-
if (!loc || typeof raw.text !== "string") return json(res, 400, { error: "invalid payload" });
|
|
2143
|
-
edits.push({
|
|
2144
|
-
line: loc.line,
|
|
2145
|
-
column: loc.column,
|
|
2146
|
-
text: raw.text,
|
|
2147
|
-
segments: readSegments(raw.segments),
|
|
2148
|
-
index: typeof raw.index === "number" ? raw.index : void 0,
|
|
2149
|
-
prop: typeof raw.prop === "string" ? raw.prop : void 0,
|
|
2150
|
-
expected: typeof raw.expected === "string" ? raw.expected : void 0,
|
|
2151
|
-
shown: typeof raw.shown === "string" ? raw.shown : void 0
|
|
2152
|
-
});
|
|
2153
|
-
}
|
|
2707
|
+
const edits = readTextEdits(body.docId, body.edits);
|
|
2708
|
+
if (!edits) return json(res, 400, { error: "invalid payload" });
|
|
2154
2709
|
return json(res, 200, await writeTexts(ctx, body.docId, edits));
|
|
2155
2710
|
}
|
|
2711
|
+
if (method === "GET" && url.pathname === "/style") {
|
|
2712
|
+
const loc = readLoc({
|
|
2713
|
+
docId: url.searchParams.get("docId"),
|
|
2714
|
+
line: Number(url.searchParams.get("line")),
|
|
2715
|
+
column: Number(url.searchParams.get("column"))
|
|
2716
|
+
});
|
|
2717
|
+
const tag = url.searchParams.get("tag") ?? "";
|
|
2718
|
+
if (!loc || !Number.isFinite(loc.line) || !Number.isFinite(loc.column) || tag === "") return json(res, 400, { error: "invalid target" });
|
|
2719
|
+
return json(res, 200, await readStyle(ctx, loc.docId, loc, tag));
|
|
2720
|
+
}
|
|
2721
|
+
if (method === "PUT" && url.pathname === "/batch") {
|
|
2722
|
+
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
2723
|
+
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
2724
|
+
const body = await readBody(req);
|
|
2725
|
+
if (typeof body.docId !== "string") return json(res, 400, { error: "invalid payload" });
|
|
2726
|
+
const texts = readTextEdits(body.docId, body.texts ?? []);
|
|
2727
|
+
const styles = readStyleEdits(body.docId, body.styles ?? []);
|
|
2728
|
+
if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
|
|
2729
|
+
return json(res, 200, await writeEdits(ctx, body.docId, texts, styles));
|
|
2730
|
+
}
|
|
2156
2731
|
if (method === "POST" && url.pathname === "/comment") {
|
|
2157
2732
|
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
2158
2733
|
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
@@ -3198,4 +3773,4 @@ async function createViteConfig(opts) {
|
|
|
3198
3773
|
};
|
|
3199
3774
|
}
|
|
3200
3775
|
//#endregion
|
|
3201
|
-
export { loadUserConfig as A,
|
|
3776
|
+
export { loadUserConfig as A, assetImportPath as C, validateAssetName as D, resolveScopedAssetsDir as E, makeContext as O, writeManifest as S, resolveScopedAssetFile as T, writeDocument as _, writeText as a, validateIcon as b, createDocument as c, duplicateDocument as d, listDocIds as f, resolveEntry as g, renameDocument as h, readText as i, openDocPlugin as j, DOC_ID_RE as k, deleteDocument as l, readDocument as m, parseFrontmatter as n, writeTexts as o, listDocuments as p, addComment as r, OpsError as s, createViteConfig as t, docDir as u, newFolderId as v, countAssetUsages as w, validateName as x, readManifest as y };
|