@open-document/core 0.2.0 → 0.4.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/README.md +1 -0
- package/README.zh-TW.md +1 -0
- package/dist/{build-U81g9Hnk.js → build-BzhYQKev.js} +1 -1
- package/dist/check-CCAaXofH.js +42 -0
- package/dist/cli/bin.js +45 -12
- package/dist/config-CNr8hd5X.js +2461 -0
- package/dist/{config-CSC5lHsR.d.ts → config-P61niZMf.d.ts} +6 -0
- package/dist/context-CJpdjYfU.js +15 -0
- package/dist/{dev-DwwFT6uX.js → dev-BhXgunme.js} +1 -1
- package/dist/diagram-xlVDekYk.js +763 -0
- package/dist/export-B69kDkyp.js +36 -0
- package/dist/import-DBhCpUsl.js +26 -0
- package/dist/index.d.ts +236 -91
- package/dist/index.js +516 -88
- package/dist/ops/index.d.ts +96 -1
- package/dist/ops/index.js +4 -199
- package/dist/ops-BCBmRMCS.js +1275 -0
- package/dist/{preview-C_jbySle.js → preview-Da4Aq9yF.js} +1 -1
- package/dist/sdk-C9nl30dW.d.ts +129 -0
- package/dist/sdk-DhcqZdAw.js +50 -0
- package/dist/vite/index.d.ts +7 -1
- package/dist/vite/index.js +1 -2
- package/env.d.ts +33 -1
- package/package.json +10 -1
- package/skills/create-doc/SKILL.md +7 -3
- package/skills/create-theme/SKILL.md +1 -1
- package/skills/doc-authoring/SKILL.md +86 -6
- package/skills/doc-authoring/references/long-form.md +131 -0
- package/skills/doc-authoring/references/pagination.md +2 -1
- package/src/app/components/data-table.tsx +196 -0
- package/src/app/components/diagram.tsx +76 -0
- package/src/app/components/flow-page.tsx +20 -3
- package/src/app/components/footnote.tsx +196 -0
- package/src/app/components/numbering.tsx +208 -0
- package/src/app/components/themes/theme-preview.tsx +2 -2
- package/src/app/lib/agent-bridge.ts +128 -0
- package/src/app/lib/diagnostics.ts +282 -0
- package/src/app/lib/export-html.ts +35 -11
- package/src/app/lib/export-pdf.ts +54 -19
- package/src/app/lib/flow-measure.ts +100 -31
- package/src/app/lib/flow.test.ts +46 -0
- package/src/app/lib/flow.ts +28 -3
- package/src/app/lib/footnotes.test.tsx +102 -0
- package/src/app/lib/footnotes.ts +94 -0
- package/src/app/lib/labels.ts +175 -0
- package/src/app/lib/page-context.tsx +6 -1
- package/src/app/lib/scan.ts +26 -0
- package/src/app/lib/sdk.test.ts +15 -9
- package/src/app/lib/sdk.ts +37 -11
- package/src/app/lib/use-doc-pages.ts +50 -15
- package/src/app/routes/doc.tsx +158 -115
- package/dist/config-8zkUElGq.js +0 -1169
- package/dist/design-IyRSwCtK.js +0 -52
- package/dist/edit-ops-D2W2plpc.js +0 -1190
package/dist/config-8zkUElGq.js
DELETED
|
@@ -1,1169 +0,0 @@
|
|
|
1
|
-
import { n as defaultDesign } from "./design-IyRSwCtK.js";
|
|
2
|
-
import { B as readBody, F as validateName, G as openDocPlugin, H as resolveDocPath, I as validateReorder, L as writeManifest, M as newFolderId, N as readManifest, O as renameDocument, P as validateIcon, R as json, S as deleteDocument, U as DOC_ID_RE, V as resolveDocEntry, W as loadUserConfig, _ as resolveScopedAssetFile, a as removeMarker, b as OpsError, d as GLOBAL_SCOPE, f as assetCreatedAt, g as mimeForFilename, h as findReferencedAssets, i as parseMarkers, j as FOLDER_ID_RE, l as themesPlugin, m as countAssetUsages, n as resolveTextTarget, o as parseSource$1, p as assetImportPath, r as insertMarker, s as walkJsx, t as replaceTextAt, v as resolveScopedAssetsDir, w as duplicateDocument, y as validateAssetName, z as makeContext } from "./edit-ops-D2W2plpc.js";
|
|
3
|
-
import chalk from "chalk";
|
|
4
|
-
import fs from "node:fs/promises";
|
|
5
|
-
import path from "node:path";
|
|
6
|
-
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
8
|
-
import { parse } from "@babel/parser";
|
|
9
|
-
import tailwindcss from "@tailwindcss/vite";
|
|
10
|
-
import react from "@vitejs/plugin-react";
|
|
11
|
-
//#region src/http/request-guard.ts
|
|
12
|
-
function firstHeaderValue(value) {
|
|
13
|
-
if (Array.isArray(value)) return value[0] ?? null;
|
|
14
|
-
return value ?? null;
|
|
15
|
-
}
|
|
16
|
-
function headerValue(req, name) {
|
|
17
|
-
return firstHeaderValue(req.headers[name.toLowerCase()])?.trim() ?? null;
|
|
18
|
-
}
|
|
19
|
-
function firstCommaToken(value) {
|
|
20
|
-
if (!value) return null;
|
|
21
|
-
const [first] = value.split(",", 1);
|
|
22
|
-
return first?.trim() || null;
|
|
23
|
-
}
|
|
24
|
-
function requestProto(req) {
|
|
25
|
-
const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
|
|
26
|
-
if (forwarded === "http" || forwarded === "https") return forwarded;
|
|
27
|
-
return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
|
|
28
|
-
}
|
|
29
|
-
function normalizedOrigin(origin) {
|
|
30
|
-
try {
|
|
31
|
-
const url = new URL(origin);
|
|
32
|
-
return `${url.protocol}//${url.host}`.toLowerCase();
|
|
33
|
-
} catch {
|
|
34
|
-
return null;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* The dev server writes to the user's filesystem, so every mutating endpoint is
|
|
39
|
-
* guarded against a page on another origin driving it through the browser.
|
|
40
|
-
*/
|
|
41
|
-
function validateMutationRequest(req, opts = {}) {
|
|
42
|
-
if (opts.requireJsonBody) {
|
|
43
|
-
if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
|
|
44
|
-
ok: false,
|
|
45
|
-
status: 415,
|
|
46
|
-
error: "content-type must be application/json"
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
|
|
50
|
-
ok: false,
|
|
51
|
-
status: 403,
|
|
52
|
-
error: "cross-site request blocked"
|
|
53
|
-
};
|
|
54
|
-
const originRaw = headerValue(req, "origin");
|
|
55
|
-
if (!originRaw) return { ok: true };
|
|
56
|
-
if (originRaw.toLowerCase() === "null") return {
|
|
57
|
-
ok: false,
|
|
58
|
-
status: 403,
|
|
59
|
-
error: "opaque origin is not allowed"
|
|
60
|
-
};
|
|
61
|
-
const actualOrigin = normalizedOrigin(originRaw);
|
|
62
|
-
if (!actualOrigin) return {
|
|
63
|
-
ok: false,
|
|
64
|
-
status: 403,
|
|
65
|
-
error: "invalid origin header"
|
|
66
|
-
};
|
|
67
|
-
const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
|
|
68
|
-
if (!host) return {
|
|
69
|
-
ok: false,
|
|
70
|
-
status: 400,
|
|
71
|
-
error: "missing host header"
|
|
72
|
-
};
|
|
73
|
-
if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
|
|
74
|
-
ok: false,
|
|
75
|
-
status: 403,
|
|
76
|
-
error: "origin mismatch"
|
|
77
|
-
};
|
|
78
|
-
return { ok: true };
|
|
79
|
-
}
|
|
80
|
-
//#endregion
|
|
81
|
-
//#region src/vite/routes/assets.ts
|
|
82
|
-
async function listDocIds(docsRoot) {
|
|
83
|
-
try {
|
|
84
|
-
return (await fs.readdir(docsRoot, { withFileTypes: true })).filter((e) => e.isDirectory() && DOC_ID_RE.test(e.name)).map((e) => e.name);
|
|
85
|
-
} catch {
|
|
86
|
-
return [];
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
async function readDocSource(docsRoot, docId) {
|
|
90
|
-
const entry = resolveDocEntry(docsRoot, docId);
|
|
91
|
-
if (!entry) return null;
|
|
92
|
-
try {
|
|
93
|
-
return await fs.readFile(entry, "utf8");
|
|
94
|
-
} catch {
|
|
95
|
-
return null;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
function registerAssetRoutes(server, ctx) {
|
|
99
|
-
server.middlewares.use("/__assets", async (req, res, next) => {
|
|
100
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
101
|
-
const method = req.method ?? "GET";
|
|
102
|
-
try {
|
|
103
|
-
const listMatch = url.pathname.match(/^\/([^/]+)\/?$/);
|
|
104
|
-
const fileMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)$/);
|
|
105
|
-
const usagesMatch = url.pathname.match(/^\/([^/]+)\/([^/]+)\/usages$/);
|
|
106
|
-
if (usagesMatch && method === "GET") {
|
|
107
|
-
const scope = decodeURIComponent(usagesMatch[1]);
|
|
108
|
-
const filename = decodeURIComponent(usagesMatch[2]);
|
|
109
|
-
if (!validateAssetName(filename)) return json(res, 400, { error: "invalid path" });
|
|
110
|
-
const isGlobal = scope === GLOBAL_SCOPE;
|
|
111
|
-
if (!isGlobal && !DOC_ID_RE.test(scope)) return json(res, 400, { error: "invalid scope" });
|
|
112
|
-
const importPath = assetImportPath(scope, filename);
|
|
113
|
-
const docIds = isGlobal ? await listDocIds(ctx.docsRoot) : [scope];
|
|
114
|
-
const usages = [];
|
|
115
|
-
let totalCount = 0;
|
|
116
|
-
for (const docId of docIds) {
|
|
117
|
-
const source = await readDocSource(ctx.docsRoot, docId);
|
|
118
|
-
if (source === null) continue;
|
|
119
|
-
const count = countAssetUsages(source, importPath);
|
|
120
|
-
if (count > 0) {
|
|
121
|
-
usages.push({
|
|
122
|
-
docId,
|
|
123
|
-
count
|
|
124
|
-
});
|
|
125
|
-
totalCount += count;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
return json(res, 200, {
|
|
129
|
-
usages,
|
|
130
|
-
totalCount
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
if (listMatch && method === "GET") {
|
|
134
|
-
const scope = decodeURIComponent(listMatch[1]);
|
|
135
|
-
const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
136
|
-
if (!scopedDir) return json(res, 400, { error: "invalid scope" });
|
|
137
|
-
let entries;
|
|
138
|
-
try {
|
|
139
|
-
entries = await fs.readdir(scopedDir);
|
|
140
|
-
} catch (err) {
|
|
141
|
-
if (err.code === "ENOENT") return json(res, 200, { assets: [] });
|
|
142
|
-
throw err;
|
|
143
|
-
}
|
|
144
|
-
const assets = [];
|
|
145
|
-
for (const name of entries) {
|
|
146
|
-
if (!validateAssetName(name)) continue;
|
|
147
|
-
const stat = await fs.stat(path.join(scopedDir, name));
|
|
148
|
-
if (!stat.isFile()) continue;
|
|
149
|
-
assets.push({
|
|
150
|
-
name,
|
|
151
|
-
size: stat.size,
|
|
152
|
-
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
153
|
-
mtime: stat.mtimeMs,
|
|
154
|
-
mime: mimeForFilename(name),
|
|
155
|
-
url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(name)}`,
|
|
156
|
-
importPath: assetImportPath(scope, name),
|
|
157
|
-
unused: true
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
assets.sort((a, b) => a.name.localeCompare(b.name));
|
|
161
|
-
if (assets.length > 0) {
|
|
162
|
-
const scanIds = scope === "@global" ? await listDocIds(ctx.docsRoot) : [scope];
|
|
163
|
-
const pathToAsset = new Map(assets.map((a) => [a.importPath, a]));
|
|
164
|
-
const paths = assets.map((a) => a.importPath);
|
|
165
|
-
for (const docId of scanIds) {
|
|
166
|
-
const source = await readDocSource(ctx.docsRoot, docId);
|
|
167
|
-
if (source === null) continue;
|
|
168
|
-
for (const p of findReferencedAssets(source, paths)) {
|
|
169
|
-
const asset = pathToAsset.get(p);
|
|
170
|
-
if (asset) asset.unused = false;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return json(res, 200, { assets });
|
|
175
|
-
}
|
|
176
|
-
if (fileMatch) {
|
|
177
|
-
const scope = decodeURIComponent(fileMatch[1]);
|
|
178
|
-
const filename = decodeURIComponent(fileMatch[2]);
|
|
179
|
-
const file = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, filename);
|
|
180
|
-
if (!file) return json(res, 400, { error: "invalid path" });
|
|
181
|
-
if (method === "GET") try {
|
|
182
|
-
const buf = await fs.readFile(file);
|
|
183
|
-
res.statusCode = 200;
|
|
184
|
-
res.setHeader("content-type", mimeForFilename(filename));
|
|
185
|
-
res.setHeader("cache-control", "no-store");
|
|
186
|
-
res.end(buf);
|
|
187
|
-
return;
|
|
188
|
-
} catch (err) {
|
|
189
|
-
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
190
|
-
throw err;
|
|
191
|
-
}
|
|
192
|
-
if (method === "POST") {
|
|
193
|
-
const requestCheck = validateMutationRequest(req);
|
|
194
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
195
|
-
const overwrite = url.searchParams.get("overwrite") === "1";
|
|
196
|
-
const lenHeader = req.headers["content-length"];
|
|
197
|
-
const len = typeof lenHeader === "string" ? Number(lenHeader) : NaN;
|
|
198
|
-
if (Number.isFinite(len) && len > 26214400) return json(res, 413, { error: "file too large" });
|
|
199
|
-
if (!overwrite) try {
|
|
200
|
-
await fs.access(file);
|
|
201
|
-
return json(res, 409, { error: "asset exists" });
|
|
202
|
-
} catch {}
|
|
203
|
-
const scopedDir = resolveScopedAssetsDir(ctx.docsRoot, ctx.globalAssetsRoot, scope);
|
|
204
|
-
if (!scopedDir) return json(res, 400, { error: "invalid scope" });
|
|
205
|
-
await fs.mkdir(scopedDir, { recursive: true });
|
|
206
|
-
const chunks = [];
|
|
207
|
-
let total = 0;
|
|
208
|
-
let oversized = false;
|
|
209
|
-
await new Promise((resolve, reject) => {
|
|
210
|
-
req.on("data", (c) => {
|
|
211
|
-
total += c.length;
|
|
212
|
-
if (total > 26214400) {
|
|
213
|
-
oversized = true;
|
|
214
|
-
req.destroy();
|
|
215
|
-
return;
|
|
216
|
-
}
|
|
217
|
-
chunks.push(c);
|
|
218
|
-
});
|
|
219
|
-
req.on("end", () => resolve());
|
|
220
|
-
req.on("error", reject);
|
|
221
|
-
});
|
|
222
|
-
if (oversized) return json(res, 413, { error: "file too large" });
|
|
223
|
-
await fs.writeFile(file, Buffer.concat(chunks));
|
|
224
|
-
const stat = await fs.stat(file);
|
|
225
|
-
return json(res, 200, {
|
|
226
|
-
ok: true,
|
|
227
|
-
name: filename,
|
|
228
|
-
size: stat.size,
|
|
229
|
-
createdAt: assetCreatedAt(stat.birthtimeMs, stat.mtimeMs),
|
|
230
|
-
mtime: stat.mtimeMs,
|
|
231
|
-
mime: mimeForFilename(filename),
|
|
232
|
-
url: `/__assets/${encodeURIComponent(scope)}/${encodeURIComponent(filename)}`,
|
|
233
|
-
importPath: assetImportPath(scope, filename)
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
if (method === "PATCH") {
|
|
237
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
238
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
239
|
-
const body = await readBody(req);
|
|
240
|
-
const target = validateAssetName(body.name);
|
|
241
|
-
if (!target) return json(res, 400, { error: "invalid name" });
|
|
242
|
-
if (target === filename) return json(res, 200, {
|
|
243
|
-
ok: true,
|
|
244
|
-
name: filename
|
|
245
|
-
});
|
|
246
|
-
const dest = resolveScopedAssetFile(ctx.docsRoot, ctx.globalAssetsRoot, scope, target);
|
|
247
|
-
if (!dest) return json(res, 400, { error: "invalid name" });
|
|
248
|
-
try {
|
|
249
|
-
await fs.access(dest);
|
|
250
|
-
return json(res, 409, { error: "target exists" });
|
|
251
|
-
} catch {}
|
|
252
|
-
try {
|
|
253
|
-
await fs.rename(file, dest);
|
|
254
|
-
} catch (err) {
|
|
255
|
-
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
256
|
-
throw err;
|
|
257
|
-
}
|
|
258
|
-
return json(res, 200, {
|
|
259
|
-
ok: true,
|
|
260
|
-
name: target
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
if (method === "DELETE") {
|
|
264
|
-
const requestCheck = validateMutationRequest(req);
|
|
265
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
266
|
-
try {
|
|
267
|
-
await fs.unlink(file);
|
|
268
|
-
} catch (err) {
|
|
269
|
-
if (err.code === "ENOENT") return json(res, 404, { error: "asset not found" });
|
|
270
|
-
throw err;
|
|
271
|
-
}
|
|
272
|
-
return json(res, 200, { ok: true });
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
return next();
|
|
276
|
-
} catch (err) {
|
|
277
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
278
|
-
}
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
//#endregion
|
|
282
|
-
//#region src/vite/routes/docs.ts
|
|
283
|
-
function registerDocRoutes(server, ctx) {
|
|
284
|
-
server.middlewares.use("/__docs", async (req, res, next) => {
|
|
285
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
286
|
-
const method = req.method ?? "GET";
|
|
287
|
-
try {
|
|
288
|
-
const duplicateMatch = url.pathname.match(/^\/([^/]+)\/duplicate$/);
|
|
289
|
-
const idMatch = url.pathname.match(/^\/([^/]+)$/);
|
|
290
|
-
if (duplicateMatch && method === "POST") {
|
|
291
|
-
const requestCheck = validateMutationRequest(req);
|
|
292
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
293
|
-
const docId = decodeURIComponent(duplicateMatch[1]);
|
|
294
|
-
const body = await readBody(req).catch(() => ({}));
|
|
295
|
-
const newId = typeof body.newId === "string" && body.newId !== "" ? body.newId : void 0;
|
|
296
|
-
const result = await duplicateDocument(ctx, docId, newId);
|
|
297
|
-
return json(res, 200, {
|
|
298
|
-
ok: true,
|
|
299
|
-
docId: result.id
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
if (idMatch) {
|
|
303
|
-
const docId = decodeURIComponent(idMatch[1]);
|
|
304
|
-
if (method === "PATCH") {
|
|
305
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
306
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
307
|
-
const body = await readBody(req);
|
|
308
|
-
const result = await renameDocument(ctx, docId, body.title);
|
|
309
|
-
return json(res, 200, {
|
|
310
|
-
ok: true,
|
|
311
|
-
title: result.title
|
|
312
|
-
});
|
|
313
|
-
}
|
|
314
|
-
if (method === "DELETE") {
|
|
315
|
-
const requestCheck = validateMutationRequest(req);
|
|
316
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
317
|
-
await deleteDocument(ctx, docId);
|
|
318
|
-
return json(res, 200, { ok: true });
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
next();
|
|
322
|
-
} catch (err) {
|
|
323
|
-
if (err instanceof OpsError) return json(res, err.status, { error: err.message });
|
|
324
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
325
|
-
}
|
|
326
|
-
});
|
|
327
|
-
}
|
|
328
|
-
//#endregion
|
|
329
|
-
//#region src/vite/routes/edit.ts
|
|
330
|
-
function readLoc(body) {
|
|
331
|
-
const { docId, line, column } = body;
|
|
332
|
-
if (typeof docId !== "string") return null;
|
|
333
|
-
if (typeof line !== "number" || typeof column !== "number") return null;
|
|
334
|
-
return {
|
|
335
|
-
docId,
|
|
336
|
-
line,
|
|
337
|
-
column
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
function registerEditRoutes(server, ctx) {
|
|
341
|
-
const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
|
|
342
|
-
server.middlewares.use("/__edit", async (req, res, next) => {
|
|
343
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
344
|
-
const method = req.method ?? "GET";
|
|
345
|
-
try {
|
|
346
|
-
if (method === "GET" && url.pathname === "/text") {
|
|
347
|
-
const docId = url.searchParams.get("docId") ?? "";
|
|
348
|
-
const entry = entryFor(docId);
|
|
349
|
-
const locs = (url.searchParams.get("locs") ?? "").split(",").map((pair) => pair.split(":").map(Number)).filter(([line, column]) => Number.isFinite(line) && Number.isFinite(column)).map(([line, column]) => ({
|
|
350
|
-
line,
|
|
351
|
-
column
|
|
352
|
-
}));
|
|
353
|
-
if (!entry || locs.length === 0) return json(res, 400, { error: "invalid target" });
|
|
354
|
-
const source = await fs.readFile(entry, "utf8");
|
|
355
|
-
const resolved = resolveTextTarget(source, locs, url.searchParams.get("shown") ?? void 0);
|
|
356
|
-
if (!resolved) return json(res, 404, { error: "element not found" });
|
|
357
|
-
return json(res, 200, resolved);
|
|
358
|
-
}
|
|
359
|
-
if (method === "PUT" && url.pathname === "/text") {
|
|
360
|
-
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
361
|
-
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
362
|
-
const body = await readBody(req);
|
|
363
|
-
const loc = readLoc(body);
|
|
364
|
-
const text = body.text;
|
|
365
|
-
if (!loc || typeof text !== "string") return json(res, 400, { error: "invalid payload" });
|
|
366
|
-
const entry = entryFor(loc.docId);
|
|
367
|
-
if (!entry) return json(res, 404, { error: "document not found" });
|
|
368
|
-
const source = await fs.readFile(entry, "utf8");
|
|
369
|
-
const result = replaceTextAt(source, loc, text, {
|
|
370
|
-
index: typeof body.index === "number" ? body.index : void 0,
|
|
371
|
-
expected: typeof body.expected === "string" ? body.expected : void 0
|
|
372
|
-
});
|
|
373
|
-
if (!result.ok) return json(res, result.status, { error: result.error });
|
|
374
|
-
if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
|
|
375
|
-
return json(res, 200, { ok: true });
|
|
376
|
-
}
|
|
377
|
-
if (method === "POST" && url.pathname === "/comment") {
|
|
378
|
-
const check = validateMutationRequest(req, { requireJsonBody: true });
|
|
379
|
-
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
380
|
-
const body = await readBody(req);
|
|
381
|
-
const loc = readLoc(body);
|
|
382
|
-
const note = body.note;
|
|
383
|
-
if (!loc || typeof note !== "string" || note.trim() === "") return json(res, 400, { error: "invalid payload" });
|
|
384
|
-
const entry = entryFor(loc.docId);
|
|
385
|
-
if (!entry) return json(res, 404, { error: "document not found" });
|
|
386
|
-
const source = await fs.readFile(entry, "utf8");
|
|
387
|
-
const inserted = insertMarker(source, loc, note.trim(), typeof body.hint === "string" ? body.hint : void 0);
|
|
388
|
-
if (!inserted) return json(res, 422, { error: "cannot anchor a comment here — pick the surrounding element" });
|
|
389
|
-
await fs.writeFile(entry, inserted.source, "utf8");
|
|
390
|
-
return json(res, 200, {
|
|
391
|
-
ok: true,
|
|
392
|
-
id: inserted.id
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
return next();
|
|
396
|
-
} catch (err) {
|
|
397
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
398
|
-
}
|
|
399
|
-
});
|
|
400
|
-
server.middlewares.use("/__comments", async (req, res, next) => {
|
|
401
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
402
|
-
const method = req.method ?? "GET";
|
|
403
|
-
const docId = url.searchParams.get("docId") ?? "";
|
|
404
|
-
const entry = entryFor(docId);
|
|
405
|
-
try {
|
|
406
|
-
if (method === "GET") {
|
|
407
|
-
if (!entry) return json(res, 200, { comments: [] });
|
|
408
|
-
return json(res, 200, { comments: parseMarkers(await fs.readFile(entry, "utf8")) });
|
|
409
|
-
}
|
|
410
|
-
if (method === "DELETE") {
|
|
411
|
-
const check = validateMutationRequest(req);
|
|
412
|
-
if (!check.ok) return json(res, check.status, { error: check.error });
|
|
413
|
-
const id = url.searchParams.get("id") ?? "";
|
|
414
|
-
if (!entry || !/^c-[a-f0-9]+$/.test(id)) return json(res, 400, { error: "invalid id" });
|
|
415
|
-
const source = await fs.readFile(entry, "utf8");
|
|
416
|
-
const next = removeMarker(source, id);
|
|
417
|
-
if (next === null) return json(res, 404, { error: "comment not found" });
|
|
418
|
-
await fs.writeFile(entry, next, "utf8");
|
|
419
|
-
return json(res, 200, { ok: true });
|
|
420
|
-
}
|
|
421
|
-
return next();
|
|
422
|
-
} catch (err) {
|
|
423
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
424
|
-
}
|
|
425
|
-
});
|
|
426
|
-
}
|
|
427
|
-
//#endregion
|
|
428
|
-
//#region src/vite/routes/folders.ts
|
|
429
|
-
function registerFolderRoutes(server, ctx) {
|
|
430
|
-
server.middlewares.use("/__folders", async (req, res, next) => {
|
|
431
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
432
|
-
const method = req.method ?? "GET";
|
|
433
|
-
try {
|
|
434
|
-
if (method === "GET" && url.pathname === "/") return json(res, 200, await readManifest(ctx.manifestPath));
|
|
435
|
-
if (method === "POST" && url.pathname === "/") {
|
|
436
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
437
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
438
|
-
const body = await readBody(req);
|
|
439
|
-
const name = validateName(body.name);
|
|
440
|
-
if (!name) return json(res, 400, { error: "invalid name" });
|
|
441
|
-
const icon = validateIcon(body.icon);
|
|
442
|
-
if (!icon) return json(res, 400, { error: "invalid icon" });
|
|
443
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
444
|
-
const folder = {
|
|
445
|
-
id: newFolderId(),
|
|
446
|
-
name,
|
|
447
|
-
icon
|
|
448
|
-
};
|
|
449
|
-
manifest.folders.push(folder);
|
|
450
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
451
|
-
return json(res, 200, folder);
|
|
452
|
-
}
|
|
453
|
-
if (method === "PUT" && url.pathname === "/assign") {
|
|
454
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
455
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
456
|
-
const body = await readBody(req);
|
|
457
|
-
if (typeof body.docId !== "string" || !DOC_ID_RE.test(body.docId)) return json(res, 400, { error: "invalid docId" });
|
|
458
|
-
const docId = body.docId;
|
|
459
|
-
let folderId;
|
|
460
|
-
if (body.folderId === null) folderId = null;
|
|
461
|
-
else if (typeof body.folderId === "string" && FOLDER_ID_RE.test(body.folderId)) folderId = body.folderId;
|
|
462
|
-
else return json(res, 400, { error: "invalid folderId" });
|
|
463
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
464
|
-
if (folderId && !manifest.folders.some((f) => f.id === folderId)) return json(res, 404, { error: "folder not found" });
|
|
465
|
-
if (folderId === null) delete manifest.assignments[docId];
|
|
466
|
-
else manifest.assignments[docId] = folderId;
|
|
467
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
468
|
-
return json(res, 200, { ok: true });
|
|
469
|
-
}
|
|
470
|
-
if (method === "PUT" && url.pathname === "/reorder") {
|
|
471
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
472
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
473
|
-
const body = await readBody(req);
|
|
474
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
475
|
-
const ids = validateReorder(body.ids, manifest.folders);
|
|
476
|
-
if (!ids) return json(res, 400, { error: "invalid ids" });
|
|
477
|
-
const byId = new Map(manifest.folders.map((f) => [f.id, f]));
|
|
478
|
-
manifest.folders = ids.map((id) => byId.get(id));
|
|
479
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
480
|
-
return json(res, 200, { ok: true });
|
|
481
|
-
}
|
|
482
|
-
const idMatch = url.pathname.match(/^\/([^/]+)$/);
|
|
483
|
-
if (idMatch) {
|
|
484
|
-
const id = idMatch[1];
|
|
485
|
-
if (!FOLDER_ID_RE.test(id)) return json(res, 400, { error: "invalid id" });
|
|
486
|
-
if (method === "PATCH") {
|
|
487
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
488
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
489
|
-
const body = await readBody(req);
|
|
490
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
491
|
-
const folder = manifest.folders.find((f) => f.id === id);
|
|
492
|
-
if (!folder) return json(res, 404, { error: "folder not found" });
|
|
493
|
-
if (body.name !== void 0) {
|
|
494
|
-
const name = validateName(body.name);
|
|
495
|
-
if (!name) return json(res, 400, { error: "invalid name" });
|
|
496
|
-
folder.name = name;
|
|
497
|
-
}
|
|
498
|
-
if (body.icon !== void 0) {
|
|
499
|
-
const icon = validateIcon(body.icon);
|
|
500
|
-
if (!icon) return json(res, 400, { error: "invalid icon" });
|
|
501
|
-
folder.icon = icon;
|
|
502
|
-
}
|
|
503
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
504
|
-
return json(res, 200, folder);
|
|
505
|
-
}
|
|
506
|
-
if (method === "DELETE") {
|
|
507
|
-
const requestCheck = validateMutationRequest(req);
|
|
508
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
509
|
-
const manifest = await readManifest(ctx.manifestPath);
|
|
510
|
-
const before = manifest.folders.length;
|
|
511
|
-
manifest.folders = manifest.folders.filter((f) => f.id !== id);
|
|
512
|
-
if (manifest.folders.length === before) return json(res, 404, { error: "folder not found" });
|
|
513
|
-
for (const [docId, folderId] of Object.entries(manifest.assignments)) if (folderId === id) delete manifest.assignments[docId];
|
|
514
|
-
await writeManifest(ctx.manifestPath, manifest);
|
|
515
|
-
return json(res, 200, { ok: true });
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
next();
|
|
519
|
-
} catch (err) {
|
|
520
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
}
|
|
524
|
-
//#endregion
|
|
525
|
-
//#region src/vite/api-plugin.ts
|
|
526
|
-
function apiPlugin(opts) {
|
|
527
|
-
return {
|
|
528
|
-
name: "open-doc:api",
|
|
529
|
-
apply: "serve",
|
|
530
|
-
configureServer(server) {
|
|
531
|
-
const ctx = makeContext(opts);
|
|
532
|
-
registerAssetRoutes(server, ctx);
|
|
533
|
-
registerFolderRoutes(server, ctx);
|
|
534
|
-
registerDocRoutes(server, ctx);
|
|
535
|
-
registerEditRoutes(server, ctx);
|
|
536
|
-
}
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
//#endregion
|
|
540
|
-
//#region src/vite/current-plugin.ts
|
|
541
|
-
const TEXT_SNIPPET_MAX = 120;
|
|
542
|
-
function parseSelection(raw) {
|
|
543
|
-
if (raw == null || typeof raw !== "object") return null;
|
|
544
|
-
const sel = raw;
|
|
545
|
-
if (typeof sel.line !== "number" || !Number.isFinite(sel.line)) return null;
|
|
546
|
-
if (typeof sel.column !== "number" || !Number.isFinite(sel.column)) return null;
|
|
547
|
-
const tagName = typeof sel.tagName === "string" ? sel.tagName.toLowerCase().slice(0, 32) : "unknown";
|
|
548
|
-
const text = typeof sel.text === "string" ? sel.text.replace(/\s+/g, " ").trim().slice(0, TEXT_SNIPPET_MAX) : "";
|
|
549
|
-
return {
|
|
550
|
-
line: Math.max(1, Math.floor(sel.line)),
|
|
551
|
-
column: Math.max(0, Math.floor(sel.column)),
|
|
552
|
-
tagName,
|
|
553
|
-
text
|
|
554
|
-
};
|
|
555
|
-
}
|
|
556
|
-
/**
|
|
557
|
-
* Writes `node_modules/.open-doc/current.json` whenever the viewer navigates or
|
|
558
|
-
* the inspector picks an element, so an agent can resolve "this page" without
|
|
559
|
-
* asking. Dev only — a static build has no cursor to report.
|
|
560
|
-
*/
|
|
561
|
-
function currentPlugin(opts) {
|
|
562
|
-
const userCwd = opts.userCwd;
|
|
563
|
-
const docsDir = opts.docsDir ?? "docs";
|
|
564
|
-
const outDir = path.join(userCwd, "node_modules", ".open-doc");
|
|
565
|
-
const outFile = path.join(outDir, "current.json");
|
|
566
|
-
const tmpFile = `${outFile}.tmp`;
|
|
567
|
-
let cached = null;
|
|
568
|
-
return {
|
|
569
|
-
name: "open-doc:current",
|
|
570
|
-
apply: "serve",
|
|
571
|
-
configureServer(server) {
|
|
572
|
-
server.ws.on("open-doc:current", async (raw) => {
|
|
573
|
-
const next = cached ? { ...cached } : {
|
|
574
|
-
docId: "",
|
|
575
|
-
pageIndex: 0,
|
|
576
|
-
pageNumber: 1,
|
|
577
|
-
totalPages: 1,
|
|
578
|
-
docTitle: "",
|
|
579
|
-
pagePath: "",
|
|
580
|
-
selection: null
|
|
581
|
-
};
|
|
582
|
-
if (typeof raw?.docId === "string") {
|
|
583
|
-
if (!DOC_ID_RE.test(raw.docId)) return;
|
|
584
|
-
const totalPages = typeof raw.totalPages === "number" && Number.isFinite(raw.totalPages) && raw.totalPages > 0 ? Math.floor(raw.totalPages) : 1;
|
|
585
|
-
const rawIndex = typeof raw.pageIndex === "number" && Number.isFinite(raw.pageIndex) ? Math.floor(raw.pageIndex) : 0;
|
|
586
|
-
const pageIndex = Math.max(0, Math.min(totalPages - 1, rawIndex));
|
|
587
|
-
const docTitle = typeof raw.docTitle === "string" ? raw.docTitle : raw.docId;
|
|
588
|
-
const pagePath = path.join(docsDir, raw.docId, "index.tsx").split(path.sep).join("/");
|
|
589
|
-
if (cached?.docId !== raw.docId || cached?.pageIndex !== pageIndex) next.selection = null;
|
|
590
|
-
next.docId = raw.docId;
|
|
591
|
-
next.pageIndex = pageIndex;
|
|
592
|
-
next.pageNumber = pageIndex + 1;
|
|
593
|
-
next.totalPages = totalPages;
|
|
594
|
-
next.docTitle = docTitle;
|
|
595
|
-
next.pagePath = pagePath;
|
|
596
|
-
}
|
|
597
|
-
if ("selection" in raw) next.selection = parseSelection(raw.selection);
|
|
598
|
-
if (!next.docId) return;
|
|
599
|
-
cached = next;
|
|
600
|
-
const body = {
|
|
601
|
-
...next,
|
|
602
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
603
|
-
};
|
|
604
|
-
try {
|
|
605
|
-
await fs.mkdir(outDir, { recursive: true });
|
|
606
|
-
await fs.writeFile(tmpFile, `${JSON.stringify(body, null, 2)}\n`, "utf8");
|
|
607
|
-
await fs.rename(tmpFile, outFile);
|
|
608
|
-
} catch {}
|
|
609
|
-
});
|
|
610
|
-
}
|
|
611
|
-
};
|
|
612
|
-
}
|
|
613
|
-
//#endregion
|
|
614
|
-
//#region src/vite/design-plugin.ts
|
|
615
|
-
function parseSource(source) {
|
|
616
|
-
try {
|
|
617
|
-
return parse(source, {
|
|
618
|
-
sourceType: "module",
|
|
619
|
-
plugins: ["typescript", "jsx"],
|
|
620
|
-
errorRecovery: true
|
|
621
|
-
});
|
|
622
|
-
} catch {
|
|
623
|
-
return null;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
function programBody(ast) {
|
|
627
|
-
return ast.program?.body ?? [];
|
|
628
|
-
}
|
|
629
|
-
function designObjectOf(node) {
|
|
630
|
-
let varDecl = null;
|
|
631
|
-
if (node.type === "VariableDeclaration") varDecl = node;
|
|
632
|
-
else if (node.type === "ExportNamedDeclaration") {
|
|
633
|
-
const decl = node.declaration;
|
|
634
|
-
if (decl?.type === "VariableDeclaration") varDecl = decl;
|
|
635
|
-
}
|
|
636
|
-
if (!varDecl) return null;
|
|
637
|
-
const declarations = varDecl.declarations ?? [];
|
|
638
|
-
for (const d of declarations) {
|
|
639
|
-
const id = d.id;
|
|
640
|
-
if (id?.type !== "Identifier" || id.name !== "design") continue;
|
|
641
|
-
const init = d.init;
|
|
642
|
-
if (!init) return "unsupported";
|
|
643
|
-
let inner = init;
|
|
644
|
-
if (inner.type === "TSSatisfiesExpression" || inner.type === "TSAsExpression") {
|
|
645
|
-
const expr = inner.expression;
|
|
646
|
-
if (expr) inner = expr;
|
|
647
|
-
}
|
|
648
|
-
if (inner.type !== "ObjectExpression") return "unsupported";
|
|
649
|
-
return {
|
|
650
|
-
decl: node,
|
|
651
|
-
object: inner
|
|
652
|
-
};
|
|
653
|
-
}
|
|
654
|
-
return null;
|
|
655
|
-
}
|
|
656
|
-
function findDesign(ast) {
|
|
657
|
-
for (const node of programBody(ast)) {
|
|
658
|
-
const hit = designObjectOf(node);
|
|
659
|
-
if (hit === null) continue;
|
|
660
|
-
if (hit === "unsupported") return null;
|
|
661
|
-
return {
|
|
662
|
-
loc: {
|
|
663
|
-
declStart: hit.decl.start,
|
|
664
|
-
declEnd: hit.decl.end,
|
|
665
|
-
objectStart: hit.object.start,
|
|
666
|
-
objectEnd: hit.object.end
|
|
667
|
-
},
|
|
668
|
-
object: hit.object
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
return null;
|
|
672
|
-
}
|
|
673
|
-
function literalToValue(node) {
|
|
674
|
-
switch (node.type) {
|
|
675
|
-
case "StringLiteral": return node.value;
|
|
676
|
-
case "NumericLiteral": return node.value;
|
|
677
|
-
case "BooleanLiteral": return node.value;
|
|
678
|
-
case "NullLiteral": return null;
|
|
679
|
-
case "UnaryExpression": {
|
|
680
|
-
const op = node.operator;
|
|
681
|
-
const arg = node.argument;
|
|
682
|
-
const v = literalToValue(arg);
|
|
683
|
-
if (op === "-" && typeof v === "number") return -v;
|
|
684
|
-
if (op === "+" && typeof v === "number") return v;
|
|
685
|
-
throw new Error(`unsupported unary operator ${op}`);
|
|
686
|
-
}
|
|
687
|
-
case "TemplateLiteral": {
|
|
688
|
-
const quasis = node.quasis;
|
|
689
|
-
if (node.expressions.length > 0) throw new Error("template literal has expressions");
|
|
690
|
-
const value = quasis[0].value;
|
|
691
|
-
return value.cooked ?? value.raw;
|
|
692
|
-
}
|
|
693
|
-
case "ObjectExpression": {
|
|
694
|
-
const properties = node.properties;
|
|
695
|
-
const out = {};
|
|
696
|
-
for (const prop of properties) {
|
|
697
|
-
if (prop.type !== "ObjectProperty") throw new Error("object has spread or method");
|
|
698
|
-
const p = prop;
|
|
699
|
-
if (p.computed) throw new Error("object has computed key");
|
|
700
|
-
let key;
|
|
701
|
-
if (p.key.type === "Identifier" && typeof p.key.name === "string") key = p.key.name;
|
|
702
|
-
else if (p.key.type === "StringLiteral" && typeof p.key.value === "string") key = p.key.value;
|
|
703
|
-
else throw new Error("unsupported object key");
|
|
704
|
-
out[key] = literalToValue(p.value);
|
|
705
|
-
}
|
|
706
|
-
return out;
|
|
707
|
-
}
|
|
708
|
-
default: throw new Error(`unsupported node type ${node.type}`);
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
function isPlainObject(v) {
|
|
712
|
-
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
713
|
-
}
|
|
714
|
-
function mergeDesign(base, patch) {
|
|
715
|
-
const out = JSON.parse(JSON.stringify(base));
|
|
716
|
-
const apply = (target, src) => {
|
|
717
|
-
for (const [k, v] of Object.entries(src)) if (isPlainObject(v) && isPlainObject(target[k])) apply(target[k], v);
|
|
718
|
-
else target[k] = v;
|
|
719
|
-
};
|
|
720
|
-
if (isPlainObject(patch)) apply(out, patch);
|
|
721
|
-
return out;
|
|
722
|
-
}
|
|
723
|
-
function indent(level) {
|
|
724
|
-
return " ".repeat(level);
|
|
725
|
-
}
|
|
726
|
-
function jsString(s) {
|
|
727
|
-
return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
|
|
728
|
-
}
|
|
729
|
-
function isValidIdentifier(name) {
|
|
730
|
-
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
|
|
731
|
-
}
|
|
732
|
-
function serializeValue(value, level) {
|
|
733
|
-
if (value === null) return "null";
|
|
734
|
-
if (typeof value === "string") return jsString(value);
|
|
735
|
-
if (typeof value === "number") {
|
|
736
|
-
if (!Number.isFinite(value)) throw new Error("non-finite number");
|
|
737
|
-
return String(value);
|
|
738
|
-
}
|
|
739
|
-
if (typeof value === "boolean") return value ? "true" : "false";
|
|
740
|
-
if (isPlainObject(value)) {
|
|
741
|
-
const entries = Object.entries(value);
|
|
742
|
-
if (entries.length === 0) return "{}";
|
|
743
|
-
const childIndent = indent(level + 1);
|
|
744
|
-
return `{\n${entries.map(([k, v]) => {
|
|
745
|
-
const key = isValidIdentifier(k) ? k : jsString(k);
|
|
746
|
-
return `${childIndent}${key}: ${serializeValue(v, level + 1)},`;
|
|
747
|
-
}).join("\n")}\n${indent(level)}}`;
|
|
748
|
-
}
|
|
749
|
-
throw new Error(`unsupported value type ${typeof value}`);
|
|
750
|
-
}
|
|
751
|
-
function serializeDesign(design) {
|
|
752
|
-
return serializeValue(design, 0);
|
|
753
|
-
}
|
|
754
|
-
function parseDocDesign(source) {
|
|
755
|
-
const ast = parseSource(source);
|
|
756
|
-
if (!ast) return {
|
|
757
|
-
ok: false,
|
|
758
|
-
exists: true,
|
|
759
|
-
error: "could not parse document source"
|
|
760
|
-
};
|
|
761
|
-
const found = findDesign(ast);
|
|
762
|
-
if (!found) {
|
|
763
|
-
if (programBody(ast).some((node) => designObjectOf(node) !== null)) return {
|
|
764
|
-
ok: false,
|
|
765
|
-
exists: true,
|
|
766
|
-
error: "design has an unsupported initializer"
|
|
767
|
-
};
|
|
768
|
-
return {
|
|
769
|
-
ok: false,
|
|
770
|
-
exists: false
|
|
771
|
-
};
|
|
772
|
-
}
|
|
773
|
-
let value;
|
|
774
|
-
try {
|
|
775
|
-
value = literalToValue(found.object);
|
|
776
|
-
} catch (err) {
|
|
777
|
-
return {
|
|
778
|
-
ok: false,
|
|
779
|
-
exists: true,
|
|
780
|
-
error: err.message
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
return {
|
|
784
|
-
ok: true,
|
|
785
|
-
design: mergeDesign(defaultDesign, value),
|
|
786
|
-
loc: found.loc
|
|
787
|
-
};
|
|
788
|
-
}
|
|
789
|
-
function findImports(ast) {
|
|
790
|
-
const out = [];
|
|
791
|
-
for (const node of programBody(ast)) {
|
|
792
|
-
if (node.type !== "ImportDeclaration") continue;
|
|
793
|
-
const src = node.source?.value;
|
|
794
|
-
if (typeof src !== "string") continue;
|
|
795
|
-
out.push({
|
|
796
|
-
node,
|
|
797
|
-
source: src,
|
|
798
|
-
specifiers: node.specifiers ?? []
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
return out;
|
|
802
|
-
}
|
|
803
|
-
function ensureDesignSystemImport(source, ast) {
|
|
804
|
-
const imports = findImports(ast);
|
|
805
|
-
const coreImport = imports.find((imp) => imp.source === "@open-document/core");
|
|
806
|
-
if (coreImport) {
|
|
807
|
-
if (coreImport.specifiers.some((spec) => {
|
|
808
|
-
if (spec.type !== "ImportSpecifier") return false;
|
|
809
|
-
return spec.imported?.name === "DesignSystem";
|
|
810
|
-
})) return source;
|
|
811
|
-
const node = coreImport.node;
|
|
812
|
-
const braceClose = source.slice(node.start, node.end).lastIndexOf("}");
|
|
813
|
-
if (braceClose === -1) return source;
|
|
814
|
-
const absoluteBrace = node.start + braceClose;
|
|
815
|
-
const insertText = coreImport.specifiers.length > 0 ? ", type DesignSystem" : "type DesignSystem";
|
|
816
|
-
return source.slice(0, absoluteBrace) + insertText + source.slice(absoluteBrace);
|
|
817
|
-
}
|
|
818
|
-
const stmt = `import type { DesignSystem } from '@open-document/core';\n`;
|
|
819
|
-
if (imports.length > 0) {
|
|
820
|
-
const insertAt = imports[imports.length - 1].node.end;
|
|
821
|
-
const trail = source[insertAt] === "\n" ? "" : "\n";
|
|
822
|
-
return `${source.slice(0, insertAt)}\n${stmt.slice(0, -1)}${trail}${source.slice(insertAt)}`;
|
|
823
|
-
}
|
|
824
|
-
return `${stmt}\n${source}`;
|
|
825
|
-
}
|
|
826
|
-
function findInsertionPoint(source, ast) {
|
|
827
|
-
const imports = findImports(ast);
|
|
828
|
-
if (imports.length === 0) return 0;
|
|
829
|
-
let off = imports[imports.length - 1].node.end;
|
|
830
|
-
while (off < source.length && source[off] !== "\n") off++;
|
|
831
|
-
if (off < source.length) off++;
|
|
832
|
-
return off;
|
|
833
|
-
}
|
|
834
|
-
function applyDesignWrite(source, next) {
|
|
835
|
-
let body;
|
|
836
|
-
try {
|
|
837
|
-
body = serializeDesign(next);
|
|
838
|
-
} catch (err) {
|
|
839
|
-
return {
|
|
840
|
-
ok: false,
|
|
841
|
-
status: 422,
|
|
842
|
-
error: `serialize failed: ${err.message}`
|
|
843
|
-
};
|
|
844
|
-
}
|
|
845
|
-
const ast = parseSource(source);
|
|
846
|
-
if (!ast) return {
|
|
847
|
-
ok: false,
|
|
848
|
-
status: 422,
|
|
849
|
-
error: "could not parse document source"
|
|
850
|
-
};
|
|
851
|
-
const found = findDesign(ast);
|
|
852
|
-
if (found) return {
|
|
853
|
-
ok: true,
|
|
854
|
-
source: source.slice(0, found.loc.objectStart) + body + source.slice(found.loc.objectEnd),
|
|
855
|
-
created: false
|
|
856
|
-
};
|
|
857
|
-
const withImport = ensureDesignSystemImport(source, ast);
|
|
858
|
-
const ast2 = parseSource(withImport);
|
|
859
|
-
if (!ast2) return {
|
|
860
|
-
ok: false,
|
|
861
|
-
status: 422,
|
|
862
|
-
error: "failed to re-parse after adding import"
|
|
863
|
-
};
|
|
864
|
-
const insertAt = findInsertionPoint(withImport, ast2);
|
|
865
|
-
const block = `\nexport const design: DesignSystem = ${body};\n`;
|
|
866
|
-
return {
|
|
867
|
-
ok: true,
|
|
868
|
-
source: withImport.slice(0, insertAt) + block + withImport.slice(insertAt),
|
|
869
|
-
created: true
|
|
870
|
-
};
|
|
871
|
-
}
|
|
872
|
-
function designPlugin(opts) {
|
|
873
|
-
const userCwd = opts.userCwd;
|
|
874
|
-
const docsDir = opts.docsDir ?? "docs";
|
|
875
|
-
return {
|
|
876
|
-
name: "open-doc:design",
|
|
877
|
-
apply: "serve",
|
|
878
|
-
configureServer(server) {
|
|
879
|
-
server.middlewares.use("/__design", async (req, res, next) => {
|
|
880
|
-
const url = new URL(req.url ?? "/", "http://local");
|
|
881
|
-
const method = req.method ?? "GET";
|
|
882
|
-
const docId = url.searchParams.get("docId") ?? "";
|
|
883
|
-
const file = resolveDocPath(userCwd, docsDir, docId);
|
|
884
|
-
if (!file) return json(res, 400, { error: "invalid docId" });
|
|
885
|
-
try {
|
|
886
|
-
if (method === "GET" && url.pathname === "/") {
|
|
887
|
-
let source;
|
|
888
|
-
try {
|
|
889
|
-
source = await fs.readFile(file, "utf8");
|
|
890
|
-
} catch {
|
|
891
|
-
return json(res, 404, { error: "document not found" });
|
|
892
|
-
}
|
|
893
|
-
const parsed = parseDocDesign(source);
|
|
894
|
-
if (parsed.ok) return json(res, 200, {
|
|
895
|
-
design: parsed.design,
|
|
896
|
-
exists: true,
|
|
897
|
-
warning: null
|
|
898
|
-
});
|
|
899
|
-
if (parsed.exists === false) return json(res, 200, {
|
|
900
|
-
design: defaultDesign,
|
|
901
|
-
exists: false,
|
|
902
|
-
warning: null
|
|
903
|
-
});
|
|
904
|
-
return json(res, 200, {
|
|
905
|
-
design: defaultDesign,
|
|
906
|
-
exists: true,
|
|
907
|
-
warning: parsed.error
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
if (method === "PUT" && url.pathname === "/") {
|
|
911
|
-
const requestCheck = validateMutationRequest(req, { requireJsonBody: true });
|
|
912
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
913
|
-
const patch = (await readBody(req)).patch;
|
|
914
|
-
if (!patch || typeof patch !== "object") return json(res, 400, { error: "missing patch object" });
|
|
915
|
-
let source;
|
|
916
|
-
try {
|
|
917
|
-
source = await fs.readFile(file, "utf8");
|
|
918
|
-
} catch {
|
|
919
|
-
return json(res, 404, { error: "document not found" });
|
|
920
|
-
}
|
|
921
|
-
const parsed = parseDocDesign(source);
|
|
922
|
-
if (!parsed.ok && parsed.exists) return json(res, 422, { error: parsed.error });
|
|
923
|
-
const merged = mergeDesign(parsed.ok ? parsed.design : defaultDesign, patch);
|
|
924
|
-
const written = applyDesignWrite(source, merged);
|
|
925
|
-
if (!written.ok) return json(res, written.status, { error: written.error });
|
|
926
|
-
if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
|
|
927
|
-
return json(res, 200, {
|
|
928
|
-
ok: true,
|
|
929
|
-
design: merged,
|
|
930
|
-
created: written.created
|
|
931
|
-
});
|
|
932
|
-
}
|
|
933
|
-
if (method === "POST" && url.pathname === "/reset") {
|
|
934
|
-
const requestCheck = validateMutationRequest(req);
|
|
935
|
-
if (!requestCheck.ok) return json(res, requestCheck.status, { error: requestCheck.error });
|
|
936
|
-
let source;
|
|
937
|
-
try {
|
|
938
|
-
source = await fs.readFile(file, "utf8");
|
|
939
|
-
} catch {
|
|
940
|
-
return json(res, 404, { error: "document not found" });
|
|
941
|
-
}
|
|
942
|
-
const written = applyDesignWrite(source, defaultDesign);
|
|
943
|
-
if (!written.ok) return json(res, written.status, { error: written.error });
|
|
944
|
-
if (written.source !== source) await fs.writeFile(file, written.source, "utf8");
|
|
945
|
-
return json(res, 200, {
|
|
946
|
-
ok: true,
|
|
947
|
-
design: defaultDesign,
|
|
948
|
-
created: written.created
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
return next();
|
|
952
|
-
} catch (err) {
|
|
953
|
-
json(res, 500, { error: String(err.message ?? err) });
|
|
954
|
-
}
|
|
955
|
-
});
|
|
956
|
-
}
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
//#endregion
|
|
960
|
-
//#region src/vite/loc-tags-plugin.ts
|
|
961
|
-
const FORWARDING_COMPONENTS = /* @__PURE__ */ new Set(["ImagePlaceholder"]);
|
|
962
|
-
function taggableName(opening) {
|
|
963
|
-
const name = opening.name;
|
|
964
|
-
if (name?.type !== "JSXIdentifier" || typeof name.name !== "string") return null;
|
|
965
|
-
if (/^[a-z]/.test(name.name) || FORWARDING_COMPONENTS.has(name.name)) return name.name;
|
|
966
|
-
return null;
|
|
967
|
-
}
|
|
968
|
-
function alreadyTagged(opening) {
|
|
969
|
-
return (opening.attributes ?? []).some((attr) => {
|
|
970
|
-
if (attr.type !== "JSXAttribute") return false;
|
|
971
|
-
return attr.name?.name === "data-od-loc";
|
|
972
|
-
});
|
|
973
|
-
}
|
|
974
|
-
function injectLocTags(code) {
|
|
975
|
-
const ast = parseSource$1(code);
|
|
976
|
-
if (!ast) return null;
|
|
977
|
-
const insertions = [];
|
|
978
|
-
walkJsx(ast, (node) => {
|
|
979
|
-
const opening = node.openingElement;
|
|
980
|
-
if (!opening || !node.loc) return;
|
|
981
|
-
if (!taggableName(opening) || alreadyTagged(opening)) return;
|
|
982
|
-
const nameNode = opening.name;
|
|
983
|
-
insertions.push({
|
|
984
|
-
offset: nameNode.end,
|
|
985
|
-
text: ` data-od-loc="${node.loc.start.line}:${node.loc.start.column}"`
|
|
986
|
-
});
|
|
987
|
-
});
|
|
988
|
-
if (insertions.length === 0) return null;
|
|
989
|
-
insertions.sort((a, b) => b.offset - a.offset);
|
|
990
|
-
let next = code;
|
|
991
|
-
for (const insertion of insertions) next = next.slice(0, insertion.offset) + insertion.text + next.slice(insertion.offset);
|
|
992
|
-
return next;
|
|
993
|
-
}
|
|
994
|
-
function isDocSourceFile(id, docsRootPosix) {
|
|
995
|
-
const filePath = id.split(/[?#]/)[0].replace(/\\/g, "/");
|
|
996
|
-
if (!filePath.startsWith(`${docsRootPosix}/`)) return false;
|
|
997
|
-
if (!filePath.endsWith(".tsx")) return false;
|
|
998
|
-
if (filePath.endsWith(".d.ts") || filePath.endsWith(".test.tsx")) return false;
|
|
999
|
-
return filePath.slice(docsRootPosix.length + 1).includes("/");
|
|
1000
|
-
}
|
|
1001
|
-
function locTagsPlugin(opts) {
|
|
1002
|
-
const docsRoot = path.resolve(opts.userCwd, opts.docsDir ?? "docs").replace(/\\/g, "/");
|
|
1003
|
-
return {
|
|
1004
|
-
name: "open-doc:loc-tags",
|
|
1005
|
-
apply: "serve",
|
|
1006
|
-
enforce: "pre",
|
|
1007
|
-
transform(code, id) {
|
|
1008
|
-
if (!isDocSourceFile(id, docsRoot)) return null;
|
|
1009
|
-
const next = injectLocTags(code);
|
|
1010
|
-
return next === null ? null : {
|
|
1011
|
-
code: next,
|
|
1012
|
-
map: null
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
};
|
|
1016
|
-
}
|
|
1017
|
-
//#endregion
|
|
1018
|
-
//#region src/vite/mcp-plugin.ts
|
|
1019
|
-
/**
|
|
1020
|
-
* Mounts `@open-document/mcp` on the dev server so an agent and the browser act on
|
|
1021
|
-
* one workspace — a tool call lands on disk and the page hot-reloads.
|
|
1022
|
-
*
|
|
1023
|
-
* The package is imported dynamically and is *not* a dependency of core: the
|
|
1024
|
-
* MCP SDK is sizeable and only matters to people wiring up agents, so it stays
|
|
1025
|
-
* opt-in. A missing install is reported, never fatal.
|
|
1026
|
-
*/
|
|
1027
|
-
function mcpPlugin(opts) {
|
|
1028
|
-
const endpoint = opts.endpoint ?? "/mcp";
|
|
1029
|
-
return {
|
|
1030
|
-
name: "open-doc:mcp",
|
|
1031
|
-
apply: "serve",
|
|
1032
|
-
async configureServer(server) {
|
|
1033
|
-
let middleware;
|
|
1034
|
-
try {
|
|
1035
|
-
middleware = (await import("@open-document/mcp")).createOpenDocMcpMiddleware({
|
|
1036
|
-
userCwd: opts.userCwd,
|
|
1037
|
-
docsDir: opts.docsDir,
|
|
1038
|
-
assetsDir: opts.assetsDir,
|
|
1039
|
-
version: opts.coreVersion
|
|
1040
|
-
});
|
|
1041
|
-
} catch {
|
|
1042
|
-
server.config.logger.warn(chalk.yellow(" MCP endpoint disabled — run `pnpm add -D @open-document/mcp` to enable it.\n"));
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
server.middlewares.use(endpoint, middleware);
|
|
1046
|
-
server.httpServer?.once("listening", () => {
|
|
1047
|
-
const address = server.httpServer?.address();
|
|
1048
|
-
const port = typeof address === "object" && address ? address.port : "";
|
|
1049
|
-
server.config.logger.info(` ${chalk.green("➜")} ${chalk.bold("MCP")}: ${chalk.cyan(`http://localhost:${port}${endpoint}`)}`);
|
|
1050
|
-
});
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
//#endregion
|
|
1055
|
-
//#region src/vite/config.ts
|
|
1056
|
-
function findPackageRoot(fromFile) {
|
|
1057
|
-
let dir = path.dirname(fromFile);
|
|
1058
|
-
while (dir !== path.dirname(dir)) {
|
|
1059
|
-
if (existsSync(path.join(dir, "package.json"))) return dir;
|
|
1060
|
-
dir = path.dirname(dir);
|
|
1061
|
-
}
|
|
1062
|
-
throw new Error(`Could not find package.json walking up from ${fromFile}`);
|
|
1063
|
-
}
|
|
1064
|
-
const PKG_ROOT = findPackageRoot(fileURLToPath(import.meta.url));
|
|
1065
|
-
const APP_ROOT = path.join(PKG_ROOT, "src", "app");
|
|
1066
|
-
function readCoreVersion() {
|
|
1067
|
-
try {
|
|
1068
|
-
const raw = readFileSync(path.join(PKG_ROOT, "package.json"), "utf8");
|
|
1069
|
-
return JSON.parse(raw).version ?? "0.0.0";
|
|
1070
|
-
} catch {
|
|
1071
|
-
return "0.0.0";
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
const CORE_VERSION = readCoreVersion();
|
|
1075
|
-
async function createViteConfig(opts) {
|
|
1076
|
-
const userCwd = path.resolve(opts.userCwd);
|
|
1077
|
-
const config = opts.config ?? await loadUserConfig(userCwd);
|
|
1078
|
-
const docsDir = config.docsDir ?? "docs";
|
|
1079
|
-
const assetsDir = config.assetsDir ?? "assets";
|
|
1080
|
-
const docsAbs = path.resolve(userCwd, docsDir);
|
|
1081
|
-
const themesAbs = path.resolve(userCwd, config.themesDir ?? "themes");
|
|
1082
|
-
const assetsAbs = path.resolve(userCwd, assetsDir);
|
|
1083
|
-
return {
|
|
1084
|
-
base: config.base ?? "/",
|
|
1085
|
-
root: APP_ROOT,
|
|
1086
|
-
configFile: false,
|
|
1087
|
-
envDir: userCwd,
|
|
1088
|
-
plugins: [
|
|
1089
|
-
locTagsPlugin({
|
|
1090
|
-
userCwd,
|
|
1091
|
-
docsDir
|
|
1092
|
-
}),
|
|
1093
|
-
react(),
|
|
1094
|
-
tailwindcss(),
|
|
1095
|
-
openDocPlugin({
|
|
1096
|
-
userCwd,
|
|
1097
|
-
config,
|
|
1098
|
-
coreVersion: CORE_VERSION
|
|
1099
|
-
}),
|
|
1100
|
-
themesPlugin({
|
|
1101
|
-
userCwd,
|
|
1102
|
-
config
|
|
1103
|
-
}),
|
|
1104
|
-
designPlugin({
|
|
1105
|
-
userCwd,
|
|
1106
|
-
docsDir
|
|
1107
|
-
}),
|
|
1108
|
-
apiPlugin({
|
|
1109
|
-
userCwd,
|
|
1110
|
-
docsDir,
|
|
1111
|
-
assetsDir,
|
|
1112
|
-
coreVersion: CORE_VERSION
|
|
1113
|
-
}),
|
|
1114
|
-
currentPlugin({
|
|
1115
|
-
userCwd,
|
|
1116
|
-
docsDir
|
|
1117
|
-
}),
|
|
1118
|
-
...opts.mcp ? [mcpPlugin({
|
|
1119
|
-
userCwd,
|
|
1120
|
-
docsDir,
|
|
1121
|
-
assetsDir,
|
|
1122
|
-
coreVersion: CORE_VERSION
|
|
1123
|
-
})] : []
|
|
1124
|
-
],
|
|
1125
|
-
resolve: { alias: {
|
|
1126
|
-
"@": APP_ROOT,
|
|
1127
|
-
"@assets": assetsAbs
|
|
1128
|
-
} },
|
|
1129
|
-
optimizeDeps: {
|
|
1130
|
-
entries: [path.join(APP_ROOT, "main.tsx")],
|
|
1131
|
-
include: [
|
|
1132
|
-
"react",
|
|
1133
|
-
"react-dom",
|
|
1134
|
-
"react-dom/client",
|
|
1135
|
-
"react-router-dom",
|
|
1136
|
-
"next-themes",
|
|
1137
|
-
"lucide-react",
|
|
1138
|
-
"clsx",
|
|
1139
|
-
"tailwind-merge"
|
|
1140
|
-
],
|
|
1141
|
-
esbuildOptions: { plugins: [{
|
|
1142
|
-
name: "open-doc:virtual-externals",
|
|
1143
|
-
setup(build) {
|
|
1144
|
-
build.onResolve({ filter: /^virtual:open-doc\// }, (args) => ({
|
|
1145
|
-
path: args.path,
|
|
1146
|
-
external: true
|
|
1147
|
-
}));
|
|
1148
|
-
}
|
|
1149
|
-
}] }
|
|
1150
|
-
},
|
|
1151
|
-
server: {
|
|
1152
|
-
port: config.port ?? 5273,
|
|
1153
|
-
...config.allowedHosts !== void 0 ? { allowedHosts: config.allowedHosts } : {},
|
|
1154
|
-
fs: { allow: [
|
|
1155
|
-
APP_ROOT,
|
|
1156
|
-
userCwd,
|
|
1157
|
-
docsAbs,
|
|
1158
|
-
themesAbs,
|
|
1159
|
-
assetsAbs
|
|
1160
|
-
] }
|
|
1161
|
-
},
|
|
1162
|
-
build: {
|
|
1163
|
-
outDir: path.resolve(userCwd, "dist"),
|
|
1164
|
-
emptyOutDir: true
|
|
1165
|
-
}
|
|
1166
|
-
};
|
|
1167
|
-
}
|
|
1168
|
-
//#endregion
|
|
1169
|
-
export { createViteConfig as t };
|