@spzxg/cli-ui 0.6.18 → 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.
@@ -1,5 +1,5 @@
1
- import { g as ms, a as vs } from "./cli-ui-embed-Dsw7A8BQ.js";
2
- import { r as ys } from "./cli-ui-jszip.min-DDRprLiN.js";
1
+ import { g as ms, a as vs } from "./cli-ui-embed-CqlqLmqo.js";
2
+ import { r as ys } from "./cli-ui-jszip.min-sxxjuGID.js";
3
3
  function gs(e, t) {
4
4
  for (var n = 0; n < t.length; n++) {
5
5
  const r = t[n];
@@ -1,5 +1,5 @@
1
- import { a } from "./cli-ui-embed-Dsw7A8BQ.js";
2
- import { r as p } from "./cli-ui-jszip.min-DDRprLiN.js";
1
+ import { a } from "./cli-ui-embed-CqlqLmqo.js";
2
+ import { r as p } from "./cli-ui-jszip.min-sxxjuGID.js";
3
3
  function f(t, n) {
4
4
  for (var o = 0; o < n.length; o++) {
5
5
  const e = n[o];
@@ -1,4 +1,4 @@
1
- import { c as bt } from "./cli-ui-embed-Dsw7A8BQ.js";
1
+ import { c as bt } from "./cli-ui-embed-CqlqLmqo.js";
2
2
  function vt(yt) {
3
3
  throw new Error('Could not dynamically require "' + yt + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
4
4
  }
@@ -28,7 +28,7 @@ function v(e) {
28
28
  }
29
29
  async function R(e) {
30
30
  var E;
31
- const t = await import("./cli-ui-jszip.min-Dw9DMuD5.js").then((s) => s.j), o = await (t.default ?? t).loadAsync(e), m = async (s) => {
31
+ const t = await import("./cli-ui-jszip.min-CRpifsVf.js").then((s) => s.j), o = await (t.default ?? t).loadAsync(e), m = async (s) => {
32
32
  const a = o.file(s);
33
33
  return a ? a.async("string") : null;
34
34
  }, S = await m("xl/workbook.xml");
package/dist/cli-ui.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-Dsw7A8BQ.js";
1
+ import { C as a, b as i, d as r, e as t, f as o, h as C, i as l, j as n, k as m, m as d, l as u, n as w, o as B, p as f } from "./cli-ui-embed-CqlqLmqo.js";
2
2
  export {
3
3
  a as CliBoard,
4
4
  i as CliBrowserView,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spzxg/cli-ui",
3
- "version": "0.6.18",
3
+ "version": "0.6.19",
4
4
  "type": "module",
5
5
  "description": "相互联动的 CliMsgList、CliChat、CliBoard,支持任务中枢和完整 Operator 工作区。",
6
6
  "main": "src/index.ts",
@@ -23,6 +23,8 @@ import { bridgeDoc, frameToken, type FrameSelMessage } from "./frameQuote";
23
23
  import { syncFile } from "./fileSync";
24
24
  import { retainFileScope } from "./fileScope";
25
25
  import { isTaskUploadPath } from "../core/documentUpload";
26
+ import { deleteCachedPreview, getCachedPreview, setCachedPreview } from "./previewCache";
27
+ import { prepareWorkspaceHtml, readWorkspaceAsset, resolveWorkspaceAssetPath } from "./htmlWorkspace";
26
28
 
27
29
  export { downloadFile };
28
30
 
@@ -171,7 +173,8 @@ export function FileViewer(props:FileViewerProps) {
171
173
  function FileViewerInner({ backend, jobId, path, displayName, size, mtime, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText, resolveMissing, onResolved, resolvedFrom }: FileViewerProps) {
172
174
  const name = displayName || path.split("/").pop() || path;
173
175
  const kind: PreviewKind = previewKind(path);
174
- const [loaded, setLoaded] = useState<Loaded | null>(null);
176
+ const initialCached = useMemo(() => getCachedPreview(backend, jobId, path), [backend, jobId, path]);
177
+ const [loaded, setLoaded] = useState<Loaded | null>(() => initialCached?.kind === "text" ? { kind: "text", ...initialCached.loaded } : null);
175
178
  const [error, setError] = useState<string | null>(null);
176
179
  const [downloadError, setDownloadError] = useState<string | null>(null);
177
180
  const [copied, setCopied] = useState(false);
@@ -185,20 +188,23 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
185
188
  const [htmlPresentation, setHtmlPresentation] = useState<"reading" | "original">("original");
186
189
  const htmlReading = kind === "html" && mode === "preview" && htmlPresentation === "reading";
187
190
  // 超大文本:看开头还是看末尾(日志看末尾)。
188
- const [tail, setTail] = useState(false);
191
+ const [tail, setTail] = useState(() => initialCached?.kind === "text" ? initialCached.tail : false);
189
192
  const progressiveText = kind === "csv" || !!backend.fileSync && (kind === "text" || kind === "code");
190
- const [textLimit, setTextLimit] = useState(kind === "html" || progressiveText || backend.fileSync && kind === "markdown" ? MARKDOWN_STEP : TEXT_MAX);
193
+ const [textLimit, setTextLimit] = useState(() => initialCached?.kind === "text" ? initialCached.textLimit : (kind === "html" || progressiveText || backend.fileSync && kind === "markdown" ? MARKDOWN_STEP : TEXT_MAX));
191
194
  const [syncing, setSyncing] = useState(false);
192
195
  const [parsing, setParsing] = useState(false);
193
196
  const [cancelled, setCancelled] = useState(false);
194
197
  const sourceBusy = useCallback((value: boolean) => { setSyncing(value); if (value) setCancelled(false); }, []);
195
198
  const readingBusy = useCallback((value: boolean) => { setParsing(value); if (value) setCancelled(false); }, []);
196
- const revisionRef = useRef<string | undefined>(undefined);
199
+ const revisionRef = useRef<string | undefined>(initialCached?.kind === "text" ? initialCached.loaded.revision : initialCached?.kind === "html" ? initialCached.revision : undefined);
200
+ const openPathRef = useRef(onOpenPath);
201
+ openPathRef.current = onOpenPath;
197
202
  const fileReadAbort = useRef<AbortController | null>(null);
198
203
  const readingAbort = useRef<AbortController | null>(null);
199
204
  const cancelRead = () => { fileReadAbort.current?.abort(); readingAbort.current?.abort(); setSyncing(false); setParsing(false); setCancelled(true); };
200
205
  useEffect(() => retainFileScope(backend, jobId, { paths: [path], dirs: [], onDenied: message => {
201
206
  fileReadAbort.current?.abort(); readingAbort.current?.abort(); revisionRef.current = undefined;
207
+ deleteCachedPreview(backend, jobId, path);
202
208
  setLoaded(null); setHtmlDoc(null); setSyncing(false); setParsing(false); setError(message || "文件访问受限,请检查任务文件目录或访问权限");
203
209
  } }), [backend, jobId, path]);
204
210
  // 放大:盖住页面看(看板窄的时候看报告、表格、图片)。Esc 还原。
@@ -224,7 +230,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
224
230
  // 这个预览的口令:iframe 里的选区桥报上来的消息只认它(见 frameQuote.ts)。
225
231
  const token = useMemo(frameToken, []);
226
232
  const links = useFileLinks(backend, jobId, path, version, attempt, reloadKey, !!backend.fileSync && isTaskUploadPath(path));
227
- const knownSize = size ?? (loaded?.kind === "text" ? loaded.size : undefined);
233
+ const knownSize = size ?? (loaded?.kind === "text" ? loaded.size : initialCached?.kind === "html" ? initialCached.size : undefined);
228
234
  // 读大文件时的进度(已收到的字节数)。
229
235
  const [progress, setProgress] = useState(0);
230
236
  // HTML 默认原样预览,完整重组后插选区桥;加载或排版较慢时可切分段阅读。
@@ -233,8 +239,12 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
233
239
  const linksRef = useRef(links);
234
240
  linksRef.current = links;
235
241
  const htmlTooBig = size !== undefined && size > HTML_QUOTE_MAX;
236
- const htmlBridge = (!!backend.fileSync || !!onQuoteText) && kind === "html" && mode === "preview" && !htmlReading && !links.pending && !htmlTooBig;
237
- const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string } | "fallback" | "toobig" | null>(null);
242
+ const htmlBridge = (!!backend.fileSync || !!onQuoteText || links.blob) && kind === "html" && mode === "preview" && !htmlReading && !links.pending && !htmlTooBig;
243
+ const [htmlDoc, setHtmlDoc] = useState<{ srcDoc: string; token: string; revision?: string } | "fallback" | "toobig" | null>(() => {
244
+ if (initialCached?.kind !== "html" || htmlTooBig || kind !== "html") return null;
245
+ const bridgeToken = frameToken();
246
+ return { srcDoc: bridgeDoc(initialCached.preparedHtml, { token: bridgeToken, allowScripts: true }), token: bridgeToken, revision: initialCached.revision };
247
+ });
238
248
  useEffect(() => { if (htmlReading || mode === "source") setHtmlDoc(null); }, [htmlReading, mode]);
239
249
  const [frameState, setFrameState] = useState<"rendering" | "slow" | "ready">("rendering");
240
250
  // 走 srcdoc 时不用再按地址取(中枢太旧时那是又整个读一遍)。
@@ -242,6 +252,18 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
242
252
  const src = useFileSrc(backend, jobId, path, needsSrc && !bridged && !(kind === "html" && mode === "source"), version, knownSize, links, attempt);
243
253
  useEffect(() => {
244
254
  if (!htmlBridge) return;
255
+ const cached = getCachedPreview(backend, jobId, path);
256
+ if (attempt === 0 && cached?.kind === "html" && cached.version === version && cached.reloadKey === reloadKey) {
257
+ revisionRef.current = cached.revision;
258
+ const url = linksRef.current.url?.(path);
259
+ const base = url ? new URL(url, window.location.href).href : undefined;
260
+ setHtmlDoc(previous => {
261
+ if (previous && typeof previous === "object" && previous.revision === cached.revision) return previous;
262
+ const bridgeToken = frameToken();
263
+ return { srcDoc: bridgeDoc(cached.preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: cached.revision };
264
+ });
265
+ return;
266
+ }
245
267
  const ctl = new AbortController();
246
268
  fileReadAbort.current = ctl;
247
269
  setError(null); setCancelled(false); setSyncing(true); setProgress(0);
@@ -251,21 +273,58 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
251
273
  const result = await syncFile(transport, jobId, path, options);
252
274
  return { text: result.text ?? decodeText(result.bytes).text, revision: result.revision, size: result.size };
253
275
  })()
254
- : readBoundedBuffer(backend, jobId, path, HTML_QUOTE_MAX, { signal: ctl.signal, onBytes: setProgress }).then(buffer => ({ text: decodeText(new Uint8Array(buffer)).text, revision: undefined }));
255
- loading.then(result => {
276
+ : readBoundedBuffer(backend, jobId, path, HTML_QUOTE_MAX, { signal: ctl.signal, onBytes: setProgress }).then(buffer => ({ text: decodeText(new Uint8Array(buffer)).text, revision: undefined, size: buffer.byteLength }));
277
+ loading.then(async result => {
256
278
  if (ctl.signal.aborted) return;
279
+ const latestCached = getCachedPreview(backend, jobId, path);
280
+ let preparedHtml: string;
281
+ let blobUrls: string[];
282
+ if (result.revision && latestCached?.kind === "html" && latestCached.revision === result.revision) {
283
+ preparedHtml = latestCached.preparedHtml;
284
+ blobUrls = latestCached.blobUrls;
285
+ } else {
286
+ const prepared = await prepareWorkspaceHtml({
287
+ html: result.text,
288
+ htmlPath: path,
289
+ backend,
290
+ jobId,
291
+ signal: ctl.signal,
292
+ fresh: attempt > 0,
293
+ });
294
+ preparedHtml = prepared.html;
295
+ blobUrls = prepared.blobUrls;
296
+ }
297
+ if (ctl.signal.aborted) {
298
+ for (const u of blobUrls) { try { URL.revokeObjectURL(u); } catch { /* ignore */ } }
299
+ return;
300
+ }
301
+ setCachedPreview(backend, jobId, path, {
302
+ kind: "html",
303
+ text: result.text,
304
+ preparedHtml,
305
+ blobUrls,
306
+ revision: result.revision,
307
+ size: result.size,
308
+ version,
309
+ reloadKey,
310
+ chars: result.text.length + (preparedHtml === result.text ? 0 : preparedHtml.length),
311
+ });
257
312
  const url = linksRef.current.url?.(path);
258
313
  const base = url ? new URL(url, window.location.href).href : undefined;
259
314
  revisionRef.current = result.revision;
260
315
  setHtmlDoc(previous => {
261
316
  if (result.revision && previous && typeof previous === "object" && previous.revision === result.revision) return previous;
262
317
  const bridgeToken = frameToken();
263
- return { srcDoc: bridgeDoc(result.text, { token: bridgeToken, base }), token: bridgeToken, revision: result.revision };
318
+ return { srcDoc: bridgeDoc(preparedHtml, { token: bridgeToken, base, allowScripts: true }), token: bridgeToken, revision: result.revision };
264
319
  });
265
- }, (error: unknown) => {
320
+ }).catch((error: unknown) => {
266
321
  if (ctl.signal.aborted) return;
267
322
  if (backend.fileSync) {
268
- if ([401, 403, 404].includes((error as { status?: number }).status ?? 0)) { setHtmlDoc(null); revisionRef.current = undefined; }
323
+ if ([401, 403, 404].includes((error as { status?: number }).status ?? 0)) {
324
+ deleteCachedPreview(backend, jobId, path);
325
+ setHtmlDoc(null);
326
+ revisionRef.current = undefined;
327
+ }
269
328
  setError(error instanceof Error ? error.message : String(error));
270
329
  } else if (error instanceof FileReadLimitError) setHtmlDoc("toobig");
271
330
  else setHtmlDoc("fallback");
@@ -297,12 +356,41 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
297
356
  useEffect(() => { setSel(null); }, [htmlDoc, loaded, mode]);
298
357
  const sourceRevision = useCallback((revision: string | undefined) => { revisionRef.current = revision; setSel(null); }, []);
299
358
  useEffect(() => {
359
+ let disposed = false;
300
360
  const onMessage = (e: MessageEvent) => {
301
361
  const frame = frameRef.current;
302
362
  const root = rootRef.current;
303
363
  const data = e.data as FrameSelMessage | null;
304
364
  if (!frame || !root || e.source !== frame.contentWindow || !data || data.cliUiSel !== activeToken) return;
305
365
  if (data.ready) { setFrameState("ready"); return; }
366
+ if (typeof data.assetReq === "string" && typeof data.relUrl === "string") {
367
+ const sourceWin = frame.contentWindow;
368
+ const reqId = data.assetReq;
369
+ const relUrl = data.relUrl;
370
+ const target = resolveWorkspaceAssetPath(path, relUrl);
371
+ if (!target) {
372
+ sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: false, error: "路径无效" }, "*");
373
+ return;
374
+ }
375
+ void readWorkspaceAsset(backend, jobId, target).then(
376
+ asset => {
377
+ if (!disposed && sourceWin === frameRef.current?.contentWindow) {
378
+ sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: true, bytes: asset.bytes, mime: asset.mime }, "*");
379
+ }
380
+ },
381
+ err => {
382
+ if (!disposed && sourceWin === frameRef.current?.contentWindow) {
383
+ sourceWin?.postMessage({ cliUiAsset: activeToken, assetReq: reqId, relUrl, ok: false, error: err instanceof Error ? err.message : String(err) }, "*");
384
+ }
385
+ },
386
+ );
387
+ return;
388
+ }
389
+ if (typeof data.openPath === "string") {
390
+ const target = resolveWorkspaceAssetPath(path, data.openPath);
391
+ if (target && openPathRef.current) openPathRef.current(target);
392
+ return;
393
+ }
306
394
  if (data.scroll) frameScroll.current = { top: Math.max(0, data.top ?? 0), left: Math.max(0, data.left ?? 0) };
307
395
  if (!onQuoteText) return;
308
396
  const text = data.scroll ? "" : (data.text ?? "").trim();
@@ -313,8 +401,8 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
313
401
  setSel({ text, frame: true, revision: revisionRef.current, x: Math.min(Math.max(8, fr.left - box.left + r.left + r.width / 2), box.width - 8), y: Math.max(40, fr.top - box.top + r.top) });
314
402
  };
315
403
  window.addEventListener("message", onMessage);
316
- return () => window.removeEventListener("message", onMessage);
317
- }, [onQuoteText, activeToken]);
404
+ return () => { disposed = true; window.removeEventListener("message", onMessage); };
405
+ }, [backend, jobId, path, onQuoteText, activeToken]);
318
406
  useEffect(() => {
319
407
  if (!onQuoteText) return;
320
408
  const read = () => {
@@ -404,13 +492,19 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
404
492
  if (alive) setLoaded({ kind: "docx", html: out.value });
405
493
  }).catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : String(e)); });
406
494
  } else {
495
+ const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
496
+ const cached = getCachedPreview(backend, jobId, path);
497
+ if (attempt === 0 && cached?.kind === "text" && cached.version === version && cached.reloadKey === reloadKey && cached.tail === tail && (cached.textLimit >= max || !cached.loaded.truncated)) {
498
+ revisionRef.current = cached.loaded.revision;
499
+ setLoaded(previous => previous?.kind === "text" && previous.revision === cached.loaded.revision && previous.text === cached.loaded.text ? previous : { kind: "text", ...cached.loaded });
500
+ return () => { alive = false; ctl.abort(); };
501
+ }
407
502
  // A refresh verifies the immutable revision and reuses matching blocks.
408
503
  const key = `${path}|${tail}|${attempt}|${reloadKey??""}`;
409
504
  const prev = loadedRef.current?.kind === "text" && textKey.current === key ? loadedRef.current : null;
410
505
  textKey.current = key;
411
506
  if (!prev) setProgress(0);
412
507
  setSyncing(true);
413
- const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
414
508
  const full = () => loadText(backend, jobId, path, { max, tail, preview: true, fresh: attempt > 0, signal: ctl.signal, onBytes: (n) => { if (alive && !prev) setProgress(n); } });
415
509
  (prev ? refreshText(backend, jobId, path, prev, max, { signal: ctl.signal, preview: true, fresh: attempt > 0 }).then((r) => r ?? full()) : full()).then(
416
510
  (r) => {
@@ -418,10 +512,15 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
418
512
  const box = bodyRef.current;
419
513
  stick.current = tail || (!!box && box.scrollHeight > box.clientHeight && box.scrollHeight - box.scrollTop - box.clientHeight < 40);
420
514
  revisionRef.current = r.revision;
515
+ setCachedPreview(backend, jobId, path, { kind: "text", loaded: r, tail, textLimit: max, version, reloadKey, chars: r.text.length });
421
516
  setLoaded({ kind: "text", ...r });
422
517
  },
423
518
  (e: unknown) => { if (alive && !ctl.signal.aborted) {
424
- if ([401, 403, 404].includes((e as { status?: number }).status ?? 0)) { setLoaded(null); revisionRef.current = undefined; }
519
+ if ([401, 403, 404].includes((e as { status?: number }).status ?? 0)) {
520
+ deleteCachedPreview(backend, jobId, path);
521
+ setLoaded(null);
522
+ revisionRef.current = undefined;
523
+ }
425
524
  setError(e instanceof Error ? e.message : String(e));
426
525
  } },
427
526
  ).finally(() => { if (alive) setSyncing(false); });
@@ -6,14 +6,43 @@
6
6
  // · 相对路径的样式 / 图片按文件原地址解析(<base>),文档里的 #锚点 在页内滚动(不然会按 <base> 整页跳走)。
7
7
 
8
8
  /** iframe → 宿主:选区(text 为空 = 取消了选择)或滚动了(收起按钮)。 */
9
- export interface FrameSelMessage { cliUiSel: string; text?: string; rect?: { left: number; top: number; width: number } | null; scroll?: boolean; top?: number; left?: number; ready?: boolean }
9
+ export interface FrameSelMessage {
10
+ cliUiSel: string;
11
+ text?: string;
12
+ rect?: { left: number; top: number; width: number } | null;
13
+ scroll?: boolean;
14
+ top?: number;
15
+ left?: number;
16
+ ready?: boolean;
17
+ openPath?: string;
18
+ assetReq?: string;
19
+ relUrl?: string;
20
+ }
10
21
 
11
22
  const randomId = () => Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
12
23
 
13
24
  /** 每个预览一个口令 / nonce。 */
14
25
  export const frameToken = randomId;
15
26
 
16
- function bridgeScript(token: string) {
27
+ function runtimeAssetBridge() {
28
+ return `var pending=new Map(),blobs=new Map(),seq=0,ext=/^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#)/i;
29
+ function isRel(u){return typeof u==="string"&&!!u.trim()&&!ext.test(u.trim())}
30
+ function askAsset(u){var k=u.trim();if(blobs.has(k))return blobs.get(k);var p=new Promise(function(res,rej){var id="r"+(++seq);var tm=setTimeout(function(){pending.delete(id);rej(new Error("资源加载超时"))},30000);pending.set(id,{res:res,rej:rej,tm:tm});post({assetReq:id,relUrl:k})});blobs.set(k,p);return p}
31
+ addEventListener("message",function(e){if(e.source!==parent||!e.data||e.data.cliUiAsset!==t)return;var w=pending.get(e.data.assetReq);if(!w)return;pending.delete(e.data.assetReq);clearTimeout(w.tm);if(e.data.ok&&e.data.bytes){var b=new Blob([e.data.bytes],{type:e.data.mime||"application/octet-stream"});w.res({url:URL.createObjectURL(b),bytes:e.data.bytes,mime:e.data.mime||"application/octet-stream"})}else{blobs.delete(e.data.relUrl);w.rej(new Error(e.data.error||"资源不存在"))}});
32
+ function patchNode(n){if(!n||n.nodeType!==1)return false;var tag=n.tagName;
33
+ if(tag==="SCRIPT"){var s=n.getAttribute("src");if(isRel(s)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";n.removeAttribute("src");askAsset(s).then(function(r){var sc=document.createElement("script");sc.dataset.cliBridged="1";if(n.type)sc.type=n.type;sc.src=r.url;sc.onload=function(){n.dispatchEvent(new Event("load"))};sc.onerror=function(){n.dispatchEvent(new Event("error"))};(n.parentNode||document.head).appendChild(sc)},function(){n.dispatchEvent(new Event("error"))});return true}}
34
+ if(tag==="LINK"&&String(n.rel||n.getAttribute("rel")||"").toLowerCase().indexOf("stylesheet")>=0){var h=n.getAttribute("href");if(isRel(h)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";askAsset(h).then(function(r){n.href=r.url;n.dispatchEvent(new Event("load"))},function(){n.dispatchEvent(new Event("error"))});return false}}
35
+ if(tag==="IMG"){var g=n.getAttribute("src");if(isRel(g)&&!n.dataset.cliBridged){n.dataset.cliBridged="1";askAsset(g).then(function(r){n.src=r.url},function(){})}}
36
+ return false}
37
+ var origAppendChild=Node.prototype.appendChild,origInsertBefore=Node.prototype.insertBefore;
38
+ Node.prototype.appendChild=function(c){if(patchNode(c))return c;return origAppendChild.call(this,c)};
39
+ Node.prototype.insertBefore=function(c,r){if(patchNode(c))return c;return origInsertBefore.call(this,c,r)};
40
+ if(typeof MutationObserver!=="undefined"){new MutationObserver(function(ms){for(var i=0;i<ms.length;i++){var m=ms[i];if(m.type==="attributes"&&m.target)patchNode(m.target);else if(m.addedNodes)for(var j=0;j<m.addedNodes.length;j++){var nd=m.addedNodes[j];if(nd.nodeType===1){patchNode(nd);if(nd.querySelectorAll){var imgs=nd.querySelectorAll("img[src],link[href]");for(var k=0;k<imgs.length;k++)patchNode(imgs[k])}}}}}).observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:["src"]})}
41
+ if(typeof window.fetch==="function"){var origFetch=window.fetch.bind(window);window.fetch=function(input,init){var u=typeof input==="string"?input:input&&typeof input.url==="string"?input.url:"";if(isRel(u))return askAsset(u).then(function(r){return new Response(r.bytes,{status:200,headers:{"Content-Type":r.mime}})},function(){return new Response("Not Found",{status:404})});return origFetch(input,init)}}
42
+ document.addEventListener("click",function(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;var a=e.target&&e.target.closest&&e.target.closest("a[href]");if(!a)return;var hr=a.getAttribute("href")||"";if(!isRel(hr))return;var clean=hr.split(/[?#]/)[0]||"";if(/\\.(?:html|htm)$/i.test(clean)){e.preventDefault();post({openPath:clean})}});`;
43
+ }
44
+
45
+ function bridgeScript(token: string, allowScripts = false) {
17
46
  const t = JSON.stringify(token);
18
47
  return `(function(){var t=${t};function post(m){m.cliUiSel=t;try{parent.postMessage(m,"*")}catch(e){}}
19
48
  function ready(){requestAnimationFrame(function(){requestAnimationFrame(function(){post({ready:true})})})}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',ready,{once:true});else ready();
@@ -26,23 +55,25 @@ addEventListener("scroll",function(){post({scroll:true,top:scrollY,left:scrollX}
26
55
  addEventListener("message",function(e){if(e.source===parent&&e.data&&e.data.cliUiClear===t){var s=getSelection();s&&s.removeAllRanges()}});
27
56
  addEventListener("message",function(e){if(e.source===parent&&e.data&&e.data.cliUiRestore===t)scrollTo(Number(e.data.left)||0,Number(e.data.top)||0)});
28
57
  document.addEventListener("click",function(e){var a=e.target&&e.target.closest&&e.target.closest('a[href^="#"]');if(!a)return;e.preventDefault();
29
- var id=decodeURIComponent(a.getAttribute("href").slice(1)),el=id?document.getElementById(id)||document.getElementsByName(id)[0]:document.body;el&&el.scrollIntoView()});})();`;
58
+ var id=decodeURIComponent(a.getAttribute("href").slice(1)),el=id?document.getElementById(id)||document.getElementsByName(id)[0]:document.body;el&&el.scrollIntoView()});${allowScripts ? runtimeAssetBridge() : ""}})();`;
30
59
  }
31
60
 
32
61
  const escAttr = (s: string) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
33
62
 
34
63
  /**
35
- * 给 HTML 文档插上选区桥:CSP(页面脚本不跑、只能从文件所在地址取资源)、<base>、桥脚本。
36
- * base = 文件的绝对地址(相对资源按它解析);不给(Word 转出来的,图片都内嵌)时只允许 data: 资源。
64
+ * 给 HTML 文档插上选区桥:默认仅放行桥脚本(如 Word 转换文档);allowScripts=true 时在无同源权限的沙箱 iframe 内
65
+ * 放行页面自身脚本及工作区依赖(通过 Blob URL / 运行时资源桥加载),仍禁止直连外部网络与表单提交。
37
66
  */
38
- export function bridgeDoc(html: string, opts: { token: string; base?: string }) {
67
+ export function bridgeDoc(html: string, opts: { token: string; base?: string; allowScripts?: boolean }) {
39
68
  let origin = "";
40
69
  if (opts.base) { try { origin = new URL(opts.base).origin; } catch { origin = ""; } }
41
70
  const src = origin ? `${origin} ` : "";
42
- const csp = `default-src 'none'; script-src 'nonce-${opts.token}'; img-src ${src}data: blob:; style-src ${src}'unsafe-inline'; font-src ${src}data:; media-src ${src}data: blob:`;
71
+ const csp = opts.allowScripts
72
+ ? `default-src 'none'; script-src 'nonce-${opts.token}' 'unsafe-inline' 'unsafe-eval' blob: data: ${src}; img-src ${src}data: blob:; style-src ${src}blob: data: 'unsafe-inline'; font-src ${src}data: blob:; media-src ${src}data: blob:; connect-src ${src}data: blob:; frame-src ${src}data: blob:; worker-src blob:; form-action 'none'`
73
+ : `default-src 'none'; script-src 'nonce-${opts.token}'; img-src ${src}data: blob:; style-src ${src}'unsafe-inline'; font-src ${src}data:; media-src ${src}data: blob:`;
43
74
  const head = `<meta http-equiv="Content-Security-Policy" content="${escAttr(csp)}">`
44
75
  + (opts.base ? `<base href="${escAttr(opts.base)}">` : "")
45
- + `<script nonce="${opts.token}">${bridgeScript(opts.token)}</script>`;
76
+ + `<script nonce="${opts.token}">${bridgeScript(opts.token, opts.allowScripts)}</script>`;
46
77
  // 只保留首部完整、常见的 doctype;其他原件内容必须全部位于 CSP 和桥之后。
47
78
  // 不搜索原件中的 <head>:它可能在注释 / 脚本字符串中,未闭合标签也会令全文正则反复回溯。
48
79
  // 有界首部匹配同时避开带引号的异常 doctype 把策略吞进声明里的情况。