@spzxg/cli-ui 0.6.17 → 0.6.19

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.
@@ -0,0 +1,489 @@
1
+ import type { BoardBackend } from "../core/client";
2
+ import { decodeText } from "../core/textDecode";
3
+ import { extOf } from "./fileKind";
4
+ import { readBoundedBuffer } from "./fileOps";
5
+ import { syncFile } from "./fileSync";
6
+ import { getCachedAsset, setCachedAsset } from "./previewCache";
7
+
8
+ const ASSET_MAX_BYTES = 64 * 1024 * 1024;
9
+ const EXTERNAL_SCHEME = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i;
10
+ const WIN_ABS = /^[a-z]:[\\/]/i;
11
+
12
+ const ASSET_MIME: Record<string, string> = {
13
+ css: "text/css;charset=utf-8",
14
+ js: "text/javascript;charset=utf-8",
15
+ mjs: "text/javascript;charset=utf-8",
16
+ cjs: "text/javascript;charset=utf-8",
17
+ json: "application/json;charset=utf-8",
18
+ html: "text/html;charset=utf-8",
19
+ htm: "text/html;charset=utf-8",
20
+ svg: "image/svg+xml",
21
+ png: "image/png",
22
+ jpg: "image/jpeg",
23
+ jpeg: "image/jpeg",
24
+ gif: "image/gif",
25
+ webp: "image/webp",
26
+ avif: "image/avif",
27
+ bmp: "image/bmp",
28
+ ico: "image/x-icon",
29
+ woff: "font/woff",
30
+ woff2: "font/woff2",
31
+ ttf: "font/ttf",
32
+ otf: "font/otf",
33
+ mp4: "video/mp4",
34
+ webm: "video/webm",
35
+ mp3: "audio/mpeg",
36
+ wav: "audio/wav",
37
+ wasm: "application/wasm",
38
+ txt: "text/plain;charset=utf-8",
39
+ csv: "text/csv;charset=utf-8",
40
+ xml: "application/xml;charset=utf-8",
41
+ };
42
+
43
+ export function assetMimeOf(path: string): string {
44
+ return ASSET_MIME[extOf(path)] ?? "application/octet-stream";
45
+ }
46
+
47
+ function decodeSegment(segment: string): string {
48
+ try { return decodeURIComponent(segment); } catch { return segment; }
49
+ }
50
+
51
+ /**
52
+ * Resolve a relative asset URL referenced from `fromFile` within the same workspace.
53
+ * Returns null for external URLs (`http:`, `data:`, `blob:`, `#hash`, etc.) or directory traversal outside root.
54
+ */
55
+ export function resolveWorkspaceAssetPath(fromFile: string, rawRef: string | null | undefined, workspaceRoot?: string): string | null {
56
+ if (!rawRef) return null;
57
+ const trimmed = rawRef.trim();
58
+ if (!trimmed || EXTERNAL_SCHEME.test(trimmed)) return null;
59
+ const cleanRef = trimmed.split(/[?#]/)[0]?.replace(/\\/g, "/") ?? "";
60
+ if (!cleanRef || cleanRef.includes("\0")) return null;
61
+
62
+ const normalizedFrom = fromFile.replace(/\\/g, "/");
63
+ const isAbsFrom = normalizedFrom.startsWith("/");
64
+ const isHomeFrom = normalizedFrom.startsWith("~/");
65
+ if (WIN_ABS.test(cleanRef) || cleanRef.startsWith("~/")) return null;
66
+
67
+ const normalizedRoot = workspaceRoot ? workspaceRoot.replace(/\\/g, "/").replace(/\/+$/, "") : undefined;
68
+ if (cleanRef.startsWith("/")) {
69
+ if (!normalizedRoot) return null;
70
+ const rel = cleanRef.replace(/^\/+/, "");
71
+ const resolved = normalizeSegments(rel.split("/"));
72
+ return resolved ? `${normalizedRoot}/${resolved.join("/")}` : null;
73
+ }
74
+
75
+ const prefix = isAbsFrom ? "/" : isHomeFrom ? "~/" : "";
76
+ const bodyFrom = isAbsFrom ? normalizedFrom.slice(1) : isHomeFrom ? normalizedFrom.slice(2) : normalizedFrom;
77
+ const baseSegments = bodyFrom.split("/").filter(Boolean).slice(0, -1);
78
+ const minDepth = normalizedRoot && isAbsFrom && normalizedFrom.startsWith(`${normalizedRoot}/`)
79
+ ? normalizedRoot.slice(1).split("/").filter(Boolean).length
80
+ : 0;
81
+
82
+ const stack = [...baseSegments];
83
+ for (const rawSeg of cleanRef.split("/")) {
84
+ if (!rawSeg || rawSeg === ".") continue;
85
+ const seg = decodeSegment(rawSeg);
86
+ if (!seg || seg === ".") continue;
87
+ if (seg === "..") {
88
+ if (stack.length <= minDepth) return null;
89
+ stack.pop();
90
+ } else {
91
+ if (seg.includes("/") || seg.includes("\\") || seg.includes("\0")) return null;
92
+ stack.push(seg);
93
+ }
94
+ }
95
+ if (!stack.length) return null;
96
+ return `${prefix}${stack.join("/")}`;
97
+ }
98
+
99
+ function normalizeSegments(parts: string[]): string[] | null {
100
+ const stack: string[] = [];
101
+ for (const raw of parts) {
102
+ if (!raw || raw === ".") continue;
103
+ const seg = decodeSegment(raw);
104
+ if (!seg || seg === ".") continue;
105
+ if (seg === "..") {
106
+ if (!stack.length) return null;
107
+ stack.pop();
108
+ } else {
109
+ if (seg.includes("/") || seg.includes("\\") || seg.includes("\0")) return null;
110
+ stack.push(seg);
111
+ }
112
+ }
113
+ return stack.length ? stack : null;
114
+ }
115
+
116
+ export async function readWorkspaceAsset(
117
+ backend: BoardBackend,
118
+ jobId: string,
119
+ assetPath: string,
120
+ options: { signal?: AbortSignal; fresh?: boolean } = {},
121
+ ): Promise<{ bytes: Uint8Array<ArrayBuffer>; mime: string; revision?: string }> {
122
+ const cached = !options.fresh ? getCachedAsset(backend, jobId, assetPath) : undefined;
123
+ if (backend.fileSync) {
124
+ const synced = await syncFile(backend.fileSync, jobId, assetPath, {
125
+ signal: options.signal,
126
+ decode: false,
127
+ fresh: options.fresh,
128
+ });
129
+ if (cached && cached.revision === synced.revision) return cached;
130
+ const entry = { bytes: synced.bytes, mime: assetMimeOf(assetPath), revision: synced.revision };
131
+ setCachedAsset(backend, jobId, assetPath, entry);
132
+ return entry;
133
+ }
134
+ if (cached) return cached;
135
+ const buffer = await readBoundedBuffer(backend, jobId, assetPath, ASSET_MAX_BYTES, { signal: options.signal });
136
+ const entry = { bytes: new Uint8Array(buffer), mime: assetMimeOf(assetPath) };
137
+ setCachedAsset(backend, jobId, assetPath, entry);
138
+ return entry;
139
+ }
140
+
141
+ /**
142
+ * Fast linear check outside <script>...</script> to skip DOMParser on multi-MB self-contained HTML
143
+ * reports that already inline all CSS/JS/data.
144
+ */
145
+ export function mayHaveExternalHtmlAssets(html: string): boolean {
146
+ let cursor = 0;
147
+ const lower = html.length <= 256 * 1024 ? html.toLowerCase() : null;
148
+ const len = html.length;
149
+ while (cursor < len) {
150
+ const lt = html.indexOf("<", cursor);
151
+ if (lt < 0 || lt + 1 >= len) return false;
152
+ const c1 = html.charCodeAt(lt + 1);
153
+ // Skip comments <!-- ... -->
154
+ if (c1 === 33 && html.startsWith("!--", lt + 1)) {
155
+ const endComment = html.indexOf("-->", lt + 4);
156
+ cursor = endComment < 0 ? len : endComment + 3;
157
+ continue;
158
+ }
159
+ const gt = html.indexOf(">", lt + 1);
160
+ if (gt < 0) return false;
161
+ const rawTag = (lower ? lower.slice(lt + 1, Math.min(gt, lt + 24)) : html.slice(lt + 1, Math.min(gt, lt + 24)).toLowerCase());
162
+ const nameMatch = /^([a-z0-9]+)/.exec(rawTag);
163
+ const tag = nameMatch?.[1] ?? "";
164
+ if (tag === "script") {
165
+ const openTag = html.slice(lt + 1, gt);
166
+ if (/\bsrc\s*=/i.test(openTag)) return true;
167
+ const closeIdx = findClosingTag(html, lower, gt + 1, "script");
168
+ cursor = closeIdx < 0 ? len : closeIdx;
169
+ continue;
170
+ }
171
+ if (tag === "style") {
172
+ const closeIdx = findClosingTag(html, lower, gt + 1, "style");
173
+ const styleEnd = closeIdx < 0 ? len : closeIdx;
174
+ const cssBody = html.slice(gt + 1, styleEnd);
175
+ if (/url\s*\(|@import\b/i.test(cssBody)) return true;
176
+ cursor = styleEnd;
177
+ continue;
178
+ }
179
+ if (tag === "link" || tag === "img" || tag === "source" || tag === "video" || tag === "audio" || tag === "image" || tag === "iframe") {
180
+ const openTag = html.slice(lt + 1, gt);
181
+ if (/\b(?:src|href|srcset|poster)\s*=/i.test(openTag)) return true;
182
+ }
183
+ cursor = gt + 1;
184
+ }
185
+ return false;
186
+ }
187
+
188
+ function findClosingTag(html: string, lower: string | null, from: number, tag: string): number {
189
+ const needle = `</${tag}`;
190
+ if (lower) {
191
+ const at = lower.indexOf(needle, from);
192
+ if (at < 0) return -1;
193
+ const gt = lower.indexOf(">", at + needle.length);
194
+ return gt < 0 ? -1 : gt + 1;
195
+ }
196
+ const re = new RegExp(`</${tag}[\\s>]`, "gi");
197
+ re.lastIndex = from;
198
+ const m = re.exec(html);
199
+ if (!m) return -1;
200
+ const gt = html.indexOf(">", m.index + needle.length);
201
+ return gt < 0 ? -1 : gt + 1;
202
+ }
203
+
204
+ async function rewriteCssDependencies(
205
+ cssText: string,
206
+ cssPath: string,
207
+ loadBlobUrl: (resolvedPath: string) => Promise<string | null>,
208
+ loadCssText: (resolvedPath: string, depth: number) => Promise<string | null>,
209
+ workspaceRoot: string | undefined,
210
+ depth: number,
211
+ ): Promise<string> {
212
+ if (depth > 4) return cssText;
213
+ let result = cssText;
214
+
215
+ // Resolve @import "..." or @import url(...)
216
+ const importRegex = /@import\s+(?:url\(\s*(?:"([^"]+)"|'([^']+)'|([^)"'\s]+))\s*\)|"([^"]+)"|'([^']+)')\s*([^;]*);/gi;
217
+ const imports = [...result.matchAll(importRegex)];
218
+ if (imports.length) {
219
+ const replacements = await Promise.all(imports.map(async (match) => {
220
+ const rawUrl = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5] ?? "";
221
+ const media = (match[6] ?? "").trim();
222
+ const target = resolveWorkspaceAssetPath(cssPath, rawUrl, workspaceRoot);
223
+ if (!target) return match[0];
224
+ const imported = await loadCssText(target, depth + 1);
225
+ if (imported === null) return match[0];
226
+ return media ? `@media ${media} {\n${imported}\n}` : imported;
227
+ }));
228
+ let offset = 0;
229
+ let out = "";
230
+ imports.forEach((match, idx) => {
231
+ out += result.slice(offset, match.index!) + replacements[idx];
232
+ offset = match.index! + match[0].length;
233
+ });
234
+ result = out + result.slice(offset);
235
+ }
236
+
237
+ // Resolve url(...) references (fonts, background images, SVGs)
238
+ const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|([^)"'\s]+))\s*\)/gi;
239
+ const urls = [...result.matchAll(urlRegex)];
240
+ if (!urls.length) return result;
241
+ const uniqueTargets = new Map<string, Promise<string | null>>();
242
+ for (const match of urls) {
243
+ const rawUrl = match[1] ?? match[2] ?? match[3] ?? "";
244
+ const target = resolveWorkspaceAssetPath(cssPath, rawUrl, workspaceRoot);
245
+ if (target && !uniqueTargets.has(target)) uniqueTargets.set(target, loadBlobUrl(target));
246
+ }
247
+ const resolvedMap = new Map<string, string | null>();
248
+ await Promise.all([...uniqueTargets.entries()].map(async ([target, p]) => {
249
+ resolvedMap.set(target, await p);
250
+ }));
251
+ return result.replace(urlRegex, (full, q1, q2, bare) => {
252
+ const rawUrl = q1 ?? q2 ?? bare ?? "";
253
+ const hashIdx = rawUrl.indexOf("#");
254
+ const suffix = hashIdx >= 0 ? rawUrl.slice(hashIdx) : "";
255
+ const target = resolveWorkspaceAssetPath(cssPath, rawUrl, workspaceRoot);
256
+ const blobUrl = target ? resolvedMap.get(target) : null;
257
+ return blobUrl ? `url("${blobUrl}${suffix}")` : full;
258
+ });
259
+ }
260
+
261
+ async function rewriteModuleImports(
262
+ jsText: string,
263
+ jsPath: string,
264
+ loadModuleUrl: (resolvedPath: string, depth: number) => Promise<string | null>,
265
+ workspaceRoot: string | undefined,
266
+ depth: number,
267
+ ): Promise<string> {
268
+ if (depth > 6) return jsText;
269
+ const importRegex = /(\b(?:import|export)\s+(?:[^"'();]*?\s+from\s+)?|\bimport\s*\(\s*)(["'])(\.{1,2}\/[^"']+)\2/g;
270
+ const matches = [...jsText.matchAll(importRegex)];
271
+ if (!matches.length) return jsText;
272
+ const targets = new Map<string, Promise<string | null>>();
273
+ for (const m of matches) {
274
+ const target = resolveWorkspaceAssetPath(jsPath, m[3], workspaceRoot);
275
+ if (target && !targets.has(target)) targets.set(target, loadModuleUrl(target, depth + 1));
276
+ }
277
+ const resolved = new Map<string, string | null>();
278
+ await Promise.all([...targets.entries()].map(async ([target, p]) => { resolved.set(target, await p); }));
279
+ return jsText.replace(importRegex, (full, prefix, quote, spec) => {
280
+ const target = resolveWorkspaceAssetPath(jsPath, spec, workspaceRoot);
281
+ const blobUrl = target ? resolved.get(target) : null;
282
+ return blobUrl ? `${prefix}${quote}${blobUrl}${quote}` : full;
283
+ });
284
+ }
285
+
286
+ const LEADING_DOCTYPE = /^(?:\uFEFF)?[ \t\r\n\f]*(<!doctype[ \t\r\n\f]+html(?:[ \t\r\n\f]+(?:public[ \t\r\n\f]+(?:"[^"<>\0]*"|'[^'<>\0]*')(?:[ \t\r\n\f]+(?:"[^"<>\0]*"|'[^'<>\0]*'))?|system[ \t\r\n\f]+(?:"[^"<>\0]*"|'[^'<>\0]*')))?[ \t\r\n\f]*>)/i;
287
+
288
+ /**
289
+ * Resolve cross-directory and sibling static dependencies (<link>, <script src>, <img src>, CSS url(), etc.)
290
+ * of a workspace HTML document into cached Blob URLs / inline styles so multi-file HTML packages render standalone.
291
+ */
292
+ export async function prepareWorkspaceHtml(options: {
293
+ html: string;
294
+ htmlPath: string;
295
+ backend: BoardBackend;
296
+ jobId: string;
297
+ workspaceRoot?: string;
298
+ signal?: AbortSignal;
299
+ fresh?: boolean;
300
+ nestDepth?: number;
301
+ }): Promise<{ html: string; blobUrls: string[] }> {
302
+ const { html, htmlPath, backend, jobId, workspaceRoot, signal, fresh, nestDepth = 0 } = options;
303
+ if (!mayHaveExternalHtmlAssets(html) || typeof DOMParser === "undefined") {
304
+ return { html, blobUrls: [] };
305
+ }
306
+
307
+ const createdBlobs: string[] = [];
308
+ const blobByPath = new Map<string, Promise<string | null>>();
309
+ const moduleByPath = new Map<string, Promise<string | null>>();
310
+
311
+ const trackBlob = (bytes: BlobPart, type: string) => {
312
+ const url = URL.createObjectURL(new Blob([bytes], { type }));
313
+ createdBlobs.push(url);
314
+ return url;
315
+ };
316
+
317
+ const loadRaw = async (resolvedPath: string) => {
318
+ try {
319
+ return await readWorkspaceAsset(backend, jobId, resolvedPath, { signal, fresh });
320
+ } catch (error) {
321
+ if (signal?.aborted || (error instanceof Error && error.name === "AbortError")) throw error;
322
+ return null;
323
+ }
324
+ };
325
+
326
+ const loadBlobUrl = (resolvedPath: string): Promise<string | null> => {
327
+ let existing = blobByPath.get(resolvedPath);
328
+ if (!existing) {
329
+ existing = loadRaw(resolvedPath).then(asset => asset ? trackBlob(asset.bytes, asset.mime) : null);
330
+ blobByPath.set(resolvedPath, existing);
331
+ }
332
+ return existing;
333
+ };
334
+
335
+ const loadCssText = async (resolvedPath: string, depth: number): Promise<string | null> => {
336
+ const asset = await loadRaw(resolvedPath);
337
+ if (!asset) return null;
338
+ const rawCss = decodeText(asset.bytes).text;
339
+ return rewriteCssDependencies(rawCss, resolvedPath, loadBlobUrl, loadCssText, workspaceRoot, depth);
340
+ };
341
+
342
+ const loadModuleUrl = (resolvedPath: string, depth: number): Promise<string | null> => {
343
+ let existing = moduleByPath.get(resolvedPath);
344
+ if (!existing) {
345
+ existing = (async () => {
346
+ const asset = await loadRaw(resolvedPath);
347
+ if (!asset) return null;
348
+ const rewritten = await rewriteModuleImports(decodeText(asset.bytes).text, resolvedPath, loadModuleUrl, workspaceRoot, depth);
349
+ return trackBlob(rewritten, "text/javascript;charset=utf-8");
350
+ })();
351
+ moduleByPath.set(resolvedPath, existing);
352
+ }
353
+ return existing;
354
+ };
355
+
356
+ try {
357
+ const doc = new DOMParser().parseFromString(html, "text/html");
358
+ const tasks: Promise<void>[] = [];
359
+
360
+ // 1. External stylesheets: <link rel="stylesheet" href="...">
361
+ for (const link of Array.from(doc.querySelectorAll("link[href]"))) {
362
+ const rel = (link.getAttribute("rel") ?? "").toLowerCase();
363
+ const href = link.getAttribute("href");
364
+ const target = resolveWorkspaceAssetPath(htmlPath, href, workspaceRoot);
365
+ if (!target) continue;
366
+ if (rel.split(/\s+/).includes("stylesheet")) {
367
+ tasks.push((async () => {
368
+ const css = await loadCssText(target, 0);
369
+ if (css === null) return;
370
+ const style = doc.createElement("style");
371
+ style.setAttribute("data-cli-resolved-href", href ?? "");
372
+ const media = link.getAttribute("media");
373
+ if (media) style.setAttribute("media", media);
374
+ style.textContent = css;
375
+ link.replaceWith(style);
376
+ })());
377
+ } else {
378
+ tasks.push((async () => {
379
+ const blobUrl = await loadBlobUrl(target);
380
+ if (blobUrl) link.setAttribute("href", blobUrl);
381
+ })());
382
+ }
383
+ }
384
+
385
+ // 2. Inline <style> blocks with url(...) or @import
386
+ for (const style of Array.from(doc.querySelectorAll("style"))) {
387
+ const css = style.textContent ?? "";
388
+ if (!/url\s*\(|@import\b/i.test(css)) continue;
389
+ tasks.push((async () => {
390
+ style.textContent = await rewriteCssDependencies(css, htmlPath, loadBlobUrl, loadCssText, workspaceRoot, 0);
391
+ })());
392
+ }
393
+
394
+ // 3. External scripts: <script src="...">
395
+ for (const script of Array.from(doc.querySelectorAll("script[src]"))) {
396
+ const src = script.getAttribute("src");
397
+ const target = resolveWorkspaceAssetPath(htmlPath, src, workspaceRoot);
398
+ if (!target) continue;
399
+ const isModule = (script.getAttribute("type") ?? "").trim().toLowerCase() === "module";
400
+ tasks.push((async () => {
401
+ const blobUrl = isModule ? await loadModuleUrl(target, 0) : await loadBlobUrl(target);
402
+ if (!blobUrl) return;
403
+ script.setAttribute("data-cli-resolved-src", src ?? "");
404
+ script.setAttribute("src", blobUrl);
405
+ script.removeAttribute("integrity");
406
+ script.removeAttribute("crossorigin");
407
+ })());
408
+ }
409
+
410
+ // 4. Media & image attributes: src, poster, SVG href, srcset
411
+ for (const el of Array.from(doc.querySelectorAll("img[src], source[src], video[src], audio[src], image[href], image[xlink\\:href]"))) {
412
+ for (const attr of ["src", "href", "xlink:href"]) {
413
+ const val = el.getAttribute(attr);
414
+ const target = resolveWorkspaceAssetPath(htmlPath, val, workspaceRoot);
415
+ if (!target) continue;
416
+ tasks.push((async () => {
417
+ const blobUrl = await loadBlobUrl(target);
418
+ if (blobUrl) el.setAttribute(attr, blobUrl);
419
+ })());
420
+ }
421
+ }
422
+ for (const video of Array.from(doc.querySelectorAll("video[poster]"))) {
423
+ const target = resolveWorkspaceAssetPath(htmlPath, video.getAttribute("poster"), workspaceRoot);
424
+ if (!target) continue;
425
+ tasks.push((async () => {
426
+ const blobUrl = await loadBlobUrl(target);
427
+ if (blobUrl) video.setAttribute("poster", blobUrl);
428
+ })());
429
+ }
430
+ for (const el of Array.from(doc.querySelectorAll("[srcset]"))) {
431
+ const srcset = el.getAttribute("srcset") ?? "";
432
+ const candidates = srcset.split(",").map(part => part.trim()).filter(Boolean);
433
+ if (!candidates.length) continue;
434
+ tasks.push((async () => {
435
+ const resolved = await Promise.all(candidates.map(async (item) => {
436
+ const space = item.search(/\s/);
437
+ const urlPart = space < 0 ? item : item.slice(0, space);
438
+ const desc = space < 0 ? "" : item.slice(space);
439
+ const target = resolveWorkspaceAssetPath(htmlPath, urlPart, workspaceRoot);
440
+ if (!target) return item;
441
+ const blobUrl = await loadBlobUrl(target);
442
+ return blobUrl ? `${blobUrl}${desc}` : item;
443
+ }));
444
+ el.setAttribute("srcset", resolved.join(", "));
445
+ })());
446
+ }
447
+
448
+ // 5. One-level nested workspace HTML <iframe src="../other.html"> (e.g. shell/index frames)
449
+ if (nestDepth < 1) {
450
+ for (const frame of Array.from(doc.querySelectorAll("iframe[src]"))) {
451
+ const rawSrc = frame.getAttribute("src") ?? "";
452
+ const target = resolveWorkspaceAssetPath(htmlPath, rawSrc, workspaceRoot);
453
+ if (!target || !/\.(?:html|htm)$/i.test(target)) continue;
454
+ const hashIdx = rawSrc.indexOf("#");
455
+ const hashSuffix = hashIdx >= 0 ? rawSrc.slice(hashIdx) : "";
456
+ tasks.push((async () => {
457
+ const asset = await loadRaw(target);
458
+ if (!asset) return;
459
+ const child = await prepareWorkspaceHtml({
460
+ html: decodeText(asset.bytes).text,
461
+ htmlPath: target,
462
+ backend,
463
+ jobId,
464
+ workspaceRoot,
465
+ signal,
466
+ fresh,
467
+ nestDepth: nestDepth + 1,
468
+ });
469
+ createdBlobs.push(...child.blobUrls);
470
+ const blobUrl = trackBlob(child.html, "text/html;charset=utf-8");
471
+ frame.setAttribute("src", `${blobUrl}${hashSuffix}`);
472
+ })());
473
+ }
474
+ }
475
+
476
+ if (!tasks.length) return { html, blobUrls: [] };
477
+ await Promise.all(tasks);
478
+ if (signal?.aborted) throw new DOMException("文件同步已取消", "AbortError");
479
+
480
+ const doctypeMatch = LEADING_DOCTYPE.exec(html.slice(0, 4096));
481
+ const doctype = doctypeMatch ? doctypeMatch[1] : "<!doctype html>";
482
+ return { html: `${doctype}${doc.documentElement.outerHTML}`, blobUrls: createdBlobs };
483
+ } catch (error) {
484
+ for (const url of createdBlobs) {
485
+ try { URL.revokeObjectURL(url); } catch { /* ignore */ }
486
+ }
487
+ throw error;
488
+ }
489
+ }
@@ -0,0 +1,134 @@
1
+ import type { BoardBackend } from "../core/client";
2
+ import type { LoadedText } from "./textLoad";
3
+
4
+ export interface CachedHtmlPreview {
5
+ kind: "html";
6
+ text: string;
7
+ preparedHtml: string;
8
+ blobUrls: string[];
9
+ revision?: string;
10
+ size?: number;
11
+ version: number;
12
+ reloadKey?: number | string;
13
+ chars: number;
14
+ }
15
+
16
+ export interface CachedTextPreview {
17
+ kind: "text";
18
+ loaded: LoadedText;
19
+ tail: boolean;
20
+ textLimit: number;
21
+ version: number;
22
+ reloadKey?: number | string;
23
+ chars: number;
24
+ }
25
+
26
+ export type CachedPreviewEntry = CachedHtmlPreview | CachedTextPreview;
27
+
28
+ export interface CachedAssetEntry {
29
+ bytes: Uint8Array<ArrayBuffer>;
30
+ mime: string;
31
+ revision?: string;
32
+ }
33
+
34
+ const MAX_PREVIEW_ENTRIES = 12;
35
+ const MAX_PREVIEW_CHARS = 64 * 1024 * 1024;
36
+ const MAX_ASSET_ENTRIES = 64;
37
+ const MAX_ASSET_BYTES = 48 * 1024 * 1024;
38
+
39
+ interface BackendCache {
40
+ previews: Map<string, CachedPreviewEntry>;
41
+ assets: Map<string, CachedAssetEntry>;
42
+ }
43
+
44
+ const caches = new WeakMap<BoardBackend, BackendCache>();
45
+
46
+ function bucketFor(backend: BoardBackend): BackendCache {
47
+ let bucket = caches.get(backend);
48
+ if (!bucket) {
49
+ bucket = { previews: new Map(), assets: new Map() };
50
+ caches.set(backend, bucket);
51
+ }
52
+ return bucket;
53
+ }
54
+
55
+ const cacheKey = (jobId: string, path: string) => `${jobId}\0${path}`;
56
+
57
+ function revokeEntryBlobs(entry: CachedPreviewEntry | undefined) {
58
+ if (entry?.kind !== "html" || !entry.blobUrls.length) return;
59
+ for (const url of entry.blobUrls) {
60
+ try { URL.revokeObjectURL(url); } catch { /* ignore */ }
61
+ }
62
+ }
63
+
64
+ export function getCachedPreview(backend: BoardBackend, jobId: string, path: string): CachedPreviewEntry | undefined {
65
+ const map = bucketFor(backend).previews;
66
+ const key = cacheKey(jobId, path);
67
+ const found = map.get(key);
68
+ if (!found) return undefined;
69
+ map.delete(key);
70
+ map.set(key, found);
71
+ return found;
72
+ }
73
+
74
+ export function setCachedPreview(backend: BoardBackend, jobId: string, path: string, entry: CachedPreviewEntry): void {
75
+ const map = bucketFor(backend).previews;
76
+ const key = cacheKey(jobId, path);
77
+ const previous = map.get(key);
78
+ if (previous && previous !== entry) {
79
+ const shared = entry.kind === "html" ? new Set(entry.blobUrls) : null;
80
+ if (previous.kind === "html") {
81
+ for (const url of previous.blobUrls) {
82
+ if (!shared?.has(url)) {
83
+ try { URL.revokeObjectURL(url); } catch { /* ignore */ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ map.delete(key);
89
+ map.set(key, entry);
90
+ let totalChars = 0;
91
+ for (const item of map.values()) totalChars += item.chars;
92
+ while (map.size > 1 && (map.size > MAX_PREVIEW_ENTRIES || totalChars > MAX_PREVIEW_CHARS)) {
93
+ const oldestKey = map.keys().next().value!;
94
+ const oldest = map.get(oldestKey)!;
95
+ map.delete(oldestKey);
96
+ totalChars -= oldest.chars;
97
+ revokeEntryBlobs(oldest);
98
+ }
99
+ }
100
+
101
+ export function deleteCachedPreview(backend: BoardBackend, jobId: string, path: string): void {
102
+ const map = bucketFor(backend).previews;
103
+ const key = cacheKey(jobId, path);
104
+ const previous = map.get(key);
105
+ if (previous) {
106
+ map.delete(key);
107
+ revokeEntryBlobs(previous);
108
+ }
109
+ }
110
+
111
+ export function getCachedAsset(backend: BoardBackend, jobId: string, path: string): CachedAssetEntry | undefined {
112
+ const map = bucketFor(backend).assets;
113
+ const key = cacheKey(jobId, path);
114
+ const found = map.get(key);
115
+ if (!found) return undefined;
116
+ map.delete(key);
117
+ map.set(key, found);
118
+ return found;
119
+ }
120
+
121
+ export function setCachedAsset(backend: BoardBackend, jobId: string, path: string, entry: CachedAssetEntry): void {
122
+ const map = bucketFor(backend).assets;
123
+ const key = cacheKey(jobId, path);
124
+ map.delete(key);
125
+ map.set(key, entry);
126
+ let totalBytes = 0;
127
+ for (const item of map.values()) totalBytes += item.bytes.byteLength;
128
+ while (map.size > 1 && (map.size > MAX_ASSET_ENTRIES || totalBytes > MAX_ASSET_BYTES)) {
129
+ const oldestKey = map.keys().next().value!;
130
+ const oldest = map.get(oldestKey)!;
131
+ map.delete(oldestKey);
132
+ totalBytes -= oldest.bytes.byteLength;
133
+ }
134
+ }
@@ -677,9 +677,19 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
677
677
  if (text.trim() === "/clear" && onClearRef.current) { onClearRef.current(); return; }
678
678
  const sentFrom = key;
679
679
  const wasBusy = busyRef.current;
680
- await send(text);
681
- if (!wasBusy && latest.current.key === sentFrom) scrollToBottom("auto");
682
- }, [key, send, scrollToBottom]);
680
+ const currentConv = latest.current.conv;
681
+ const canInterrupt = !readOnly && !batch && cfg.composer.stop && !!sentFrom && !isNew && !!store.client.cancelTurn && !!currentConv;
682
+ const prevRunning = canInterrupt ? runningTurn(currentConv) : null;
683
+ const prevQueued = canInterrupt ? currentConv.turns.filter(turn => turn.status === "queued") : [];
684
+ for (const oldQueued of prevQueued) {
685
+ await store.cancelTurn(sentFrom!, oldQueued.turn_id).catch(() => undefined);
686
+ }
687
+ const target = await send(text);
688
+ if (prevRunning) {
689
+ await store.cancelTurn(target, prevRunning.turn_id).catch(() => undefined);
690
+ }
691
+ if ((!wasBusy || !!prevRunning) && latest.current.key === sentFrom) scrollToBottom("auto");
692
+ }, [key, isNew, readOnly, batch, cfg.composer.stop, store, send, scrollToBottom]);
683
693
  const pauseResume = useMemo(() => cfg.composer.stop && !readOnlyProp && controlTask && jobId && store.client.pauseTask && store.client.resumeTask ? {
684
694
  paused: controlTask.status === "paused",
685
695
  onToggle: async () => {
@@ -228,7 +228,7 @@ export const Composer = memo(function Composer({ draft, placeholder, disabled, d
228
228
  </button>}
229
229
  {showStop ? stopButton : (!running || options.queue) && <button type="button" className={`send cli-send${running ? " queue" : ""}`} disabled={disabled || !canSend} aria-busy={sending}
230
230
  onClick={() => void submit()} aria-label={sending ? "正在发送" : running ? "排队发送" : "发送消息"}
231
- title={sending ? "发送中…" : taskControl?.paused ? "排队发送,继续任务后依次执行" : running ? "排队发送,当前轮次结束后执行" : "发送消息(Enter)"}>
231
+ title={sending ? "发送中…" : taskControl?.paused ? "排队发送,继续任务后依次执行" : running ? (onStop ? "停止当前轮次并立即发送" : "排队发送,当前轮次结束后执行") : "发送消息(Enter)"}>
232
232
  {sending ? <span className="spinner" /> : Icon.send()}
233
233
  </button>}
234
234
  </div>
@@ -110,7 +110,7 @@ export const DEFAULT_CHAT_CONFIG: ResolvedChatConfig = {
110
110
  show: true,
111
111
  placeholder: "回复 {agent}…",
112
112
  placeholderNew: "输入消息,开始新对话…",
113
- placeholderRunning: "排队一条后续消息…(本轮结束后发送)",
113
+ placeholderRunning: "输入新消息,发送将停止当前轮次并立即执行…",
114
114
  placeholderDisabled: null,
115
115
  hints: false, charCount: false, fileUpload: true, agentSelector: true, executionMode: true, fileButtonText: "", stop: true, queue: true,
116
116
  },
package/src/index.ts CHANGED
@@ -54,3 +54,4 @@ export type { WorkspaceHandlers } from "./core/provider";
54
54
  export type { BoardFile } from "./board/workspace";
55
55
 
56
56
  export { syncFile, clearFileSyncNamespace, FILE_SYNC_MAX, type FileSyncTransport, type FileSyncManifest, type FileSyncProgress } from "./board/fileSync";
57
+ export { prepareWorkspaceHtml, readWorkspaceAsset, resolveWorkspaceAssetPath, assetMimeOf } from "./board/htmlWorkspace";