@linxin666/dsh-client-ui-diagrams 0.4.22 → 0.4.23
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.i18n.yaml +2 -2
- package/README.md +7 -7
- package/README.zh.md +7 -7
- package/lib/client.js +213 -49
- package/lib/client.js.map +1 -1
- package/lib/index.js +24 -8
- package/lib/types/client/MermaidFenceLayer.d.ts +30 -0
- package/lib/types/client/enhance.d.ts +6 -2
- package/lib/types/client/index.d.ts +16 -6
- package/lib/types/client/render.d.ts +34 -0
- package/lib/types/core/contract.d.ts +17 -6
- package/lib/types/host/pair-access.d.ts +17 -8
- package/package.json +19 -7
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
3
|
# after editing either side, bring the other along and re-record with:
|
|
4
4
|
# node scripts/verify-docs.mjs --write <dir>
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: 6b8bb82de85e4c7c0068923e8049ef5443ea84ca
|
|
6
|
+
README.zh.md: 5f026f5033e4326ca72933e136380a4abc9e9405
|
package/README.md
CHANGED
|
@@ -6,10 +6,10 @@ Mermaid diagram rendering for the DeepSeek Harness Web GUI: a fenced ```mermaid
|
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
9
|
-
- **Renders where you read**: the chat transcript and the document preview pane
|
|
9
|
+
- **Renders where you read**: the chat transcript renders through the official `conversation.chat.markdown.fence` hoc slot (`key: 'mermaid'`), keeping the raw code block while streaming and replacing it with SVG once settled; Markdown surfaces that do not pass `renderCode` (such as the document preview pane) remain covered by the scoped DOM observer, which explicitly skips blocks owned by the official fence slot.
|
|
10
10
|
- **Renders on demand**: the mermaid runtime is served by this package's own host route and fetched only when a page actually shows a mermaid block, so a session without diagrams downloads nothing extra.
|
|
11
|
-
- **Follows the shell theme**: a light/dark switch re-renders
|
|
12
|
-
- **Never damages the document**: a missing runtime, a
|
|
11
|
+
- **Follows the shell theme**: a light/dark switch re-renders diagrams from their stored source with an LRU cache, because mermaid paints colors into the SVG itself.
|
|
12
|
+
- **Never damages the document**: a missing runtime, a streaming fence, or a diagram the parser rejects all fall back to the untouched official code block.
|
|
13
13
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
@@ -23,17 +23,17 @@ Installing the family bundle (`@linxin666/dsh-web-all`) mounts this package too;
|
|
|
23
23
|
|
|
24
24
|
## Config
|
|
25
25
|
|
|
26
|
-
No settings. The package registers one read-only host route and one
|
|
26
|
+
No settings. The package registers one read-only host route, one official `conversation.chat.markdown.fence` slot layer, and one document-preview fallback observer; there is nothing to configure.
|
|
27
27
|
|
|
28
28
|
## Known limitations
|
|
29
29
|
|
|
30
|
-
- **The
|
|
31
|
-
- **Streaming fences render
|
|
30
|
+
- **The document-preview fallback still reads renderer DOM hooks.** The chat transcript uses the official `conversation.chat.markdown.fence` contract slot; Markdown surfaces that do not pass `renderCode` (such as the document preview pane) still rely on the `md-code-block` class and the banner hooks (`_infostring` / `_language`). The span shows a localized placeholder (for example `代码块` / `Code block`) for languages the highlighter does not know, mermaid among them, so the fallback falls back to the source's first mermaid keyword when the label is not a real language token; real language labels are never claimed. The pinned constants live in `src/core/contract.ts` with a contract test beside them.
|
|
31
|
+
- **Streaming fences render once settled.** While a reply is streaming, the official fence layer returns the source code block directly instead of parsing partial diagrams; on the document-preview fallback path, a rejected fence is retried only after a short quiet period and only once its source actually changes.
|
|
32
32
|
- **No diagram theme choice.** Diagrams follow the shell's light/dark state; mermaid's own theme variables are not exposed as settings.
|
|
33
33
|
|
|
34
34
|
## Security model
|
|
35
35
|
|
|
36
|
-
- The vendor route (`/api/dsh-diagrams/vendor/mermaid.js`) passes the
|
|
36
|
+
- The vendor route (`/api/dsh-diagrams/vendor/mermaid.js`) passes the trust fence first: loopback and host-authenticated remote connections (`connection.admit`) pass; any other unauthenticated client is refused with 403 before the asset is read.
|
|
37
37
|
- The route is read-only: only `GET` and `HEAD` are answered, everything else is 405.
|
|
38
38
|
- The runtime is served same-origin from the installed package; no CDN is contacted.
|
|
39
39
|
- Rendered SVG passes a second sanitizing pass (beyond mermaid's own strict security level): script-capable elements, `on*` handlers and `javascript:` URLs are stripped, and markup that still carries an executable token after cleaning is rejected — the block then stays a code block.
|
package/README.zh.md
CHANGED
|
@@ -6,10 +6,10 @@ DeepSeek Harness Web GUI 的 mermaid 图示渲染:会话正文或文档预览
|
|
|
6
6
|
|
|
7
7
|
## 功能
|
|
8
8
|
|
|
9
|
-
-
|
|
9
|
+
- **在你阅读的地方出图**:会话正文接入官方 `conversation.chat.markdown.fence` hoc 槽位(`key: 'mermaid'`),流式写入期间直接展示源码代码块、落定后替换为 SVG 图;尚未传入 `renderCode` 的文档预览面板由受控 DOM 观察器兜底覆盖,并自动跳过已由官方槽位托管的区域。
|
|
10
10
|
- **按需加载**:mermaid 运行库由本包自己的宿主路由伺服,只有在页面真的出现 mermaid 块时才拉取,因此没有图示的会话不会多下载任何东西。
|
|
11
|
-
-
|
|
12
|
-
-
|
|
11
|
+
- **跟随界面主题**:明暗切换时按保存的源码重绘并复用缓存——mermaid 把颜色画进 SVG 本身,CSS 改不动它。
|
|
12
|
+
- **绝不破坏文档**:运行库缺失、围栏还在流式写入、或图示被解析器拒绝,都会原样回退显示官方代码块。
|
|
13
13
|
|
|
14
14
|
## 安装
|
|
15
15
|
|
|
@@ -23,17 +23,17 @@ dsh web
|
|
|
23
23
|
|
|
24
24
|
## 配置
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
没有设置项。本包只注册一条只读宿主路由、一个官方 `conversation.chat.markdown.fence` 槽位层与一个文档预览兜底观察器,没有可配置项。
|
|
27
27
|
|
|
28
28
|
## 已知限制
|
|
29
29
|
|
|
30
|
-
-
|
|
31
|
-
-
|
|
30
|
+
- **文档预览兜底仍依赖渲染器 DOM 钩子**:会话正文已迁移至官方 `conversation.chat.markdown.fence` 契约槽位;文档预览面板等未传 `renderCode` 的 Markdown 视图继续通过 `md-code-block` 类名与 banner 钩子(`_infostring` / `_language`)兜底识别。高亮器不认识的语言(mermaid 即其中之一)在 span 里显示本地化占位符(如 `代码块` / `Code block`),因此兜底路径在标签不是真实语言 token 时回退到源码首个 mermaid 关键字判定;真实语言标签一律不接管。被钉住的常量集中在 `src/core/contract.ts`,旁边有契约测试。
|
|
31
|
+
- **流式围栏落定后出图**:回复仍在流式写入时,官方槽位层直接返回源码代码块,避免反复解析半截围栏;文档预览兜底路径对被拒围栏只在短暂静默期后、且源码确实变化时才重试。
|
|
32
32
|
- **不提供图示主题选择**:图跟随界面的明暗状态,mermaid 自身的主题变量没有暴露成设置项。
|
|
33
33
|
|
|
34
34
|
## 安全模型
|
|
35
35
|
|
|
36
|
-
- vendor 路由(`/api/dsh-diagrams/vendor/mermaid.js
|
|
36
|
+
- vendor 路由(`/api/dsh-diagrams/vendor/mermaid.js`)先过信任围栏:本机(loopback)及官方宿主已认证连接(`connection.admit`)通过;其它未认证客户端在读资产之前就被 403 拒绝。
|
|
37
37
|
- 路由只读:只应答 `GET` 与 `HEAD`,其余方法 405。
|
|
38
38
|
- 运行库同源来自已安装的包,不访问任何 CDN。
|
|
39
39
|
- 渲染出的 SVG 在 mermaid 自身 strict 等级之外再走一遍消毒:可执行元素、`on*` 事件属性与 `javascript:` URL 一律剥除;清理后仍带可执行 token 的标记被拒——该块保持为代码块。
|
package/lib/client.js
CHANGED
|
@@ -4,8 +4,44 @@ window.__ModuleLoader__.load({
|
|
|
4
4
|
var module = { exports: {} };
|
|
5
5
|
var exports = module.exports;
|
|
6
6
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
7
|
+
let react = require("react");
|
|
8
|
+
let react_jsx_runtime = require("react/jsx-runtime");
|
|
9
|
+
//#region src/core/contract.ts
|
|
10
|
+
/**
|
|
11
|
+
* The one place the diagram feature's external names live: the host route the
|
|
12
|
+
* browser half loads the vendored runtime from, the official chat fence slot
|
|
13
|
+
* seam, and the DOM fallback hooks the official markdown renderer exposes.
|
|
14
|
+
* Both halves and the tests read these constants, so a host upgrade that
|
|
15
|
+
* renames a hook fails one contract test instead of silently disabling the
|
|
16
|
+
* feature.
|
|
17
|
+
*
|
|
18
|
+
* In the chat transcript, official `ui-chat` (DSH 0.2.3-alpha.2+) dispatches
|
|
19
|
+
* fenced code blocks through the session-scoped `conversation.chat.markdown.fence`
|
|
20
|
+
* hoc slot keyed by lowercased language name (`mermaid`). Surfaces that still
|
|
21
|
+
* render Markdown without passing `renderCode` (such as the document preview
|
|
22
|
+
* pane) fall back to the DOM observer using the hooks below.
|
|
23
|
+
*
|
|
24
|
+
* `md-code-block` is a literal class name in the renderer's JSX. The banner has
|
|
25
|
+
* two known shapes across legacy `_<local>_<hash>` and 0.2.3-alpha.2
|
|
26
|
+
* `<hash>_<local>` CSS Module class patterns: an `_infostring` element carrying
|
|
27
|
+
* the raw fence infostring, and a `_language` span, which shows the language
|
|
28
|
+
* only when the highlighter knows it - an unsupported language (mermaid among
|
|
29
|
+
* them) renders a localized placeholder such as `代码块` or `Code block`
|
|
30
|
+
* instead.
|
|
31
|
+
* @module @linxin666/dsh-client-ui-diagrams/core/contract
|
|
32
|
+
*/
|
|
33
|
+
/** Host route serving the vendored mermaid runtime (same origin, no CDN). */
|
|
34
|
+
const RUNTIME_ROUTE = "/api/dsh-diagrams/vendor/mermaid.js";
|
|
35
|
+
/** Official chat markdown fence hoc slot name (DSH 0.2.3-alpha.2+). */
|
|
36
|
+
const FENCE_SLOT_NAME = "conversation.chat.markdown.fence";
|
|
37
|
+
/** Stable slot occupant id for the mermaid fence layer. */
|
|
38
|
+
const FENCE_LAYER_ID = "@linxin666/dsh-client-ui-diagrams/fence/mermaid";
|
|
39
|
+
/** Selector matching blocks already owned by the official chat fence slot. */
|
|
40
|
+
const FENCE_SLOT_SELECTOR = `[data-slot="${FENCE_SLOT_NAME}"]`;
|
|
7
41
|
/** Class the official markdown renderer puts on every fenced code block. */
|
|
8
42
|
const CODE_BLOCK_CLASS = "md-code-block";
|
|
43
|
+
/** Fence language this package renders. Everything else is left untouched. */
|
|
44
|
+
const RENDERED_LANGUAGE = "mermaid";
|
|
9
45
|
/** Class the rendered diagram container carries (styled by the theme). */
|
|
10
46
|
const DIAGRAM_CLASS = "dsh-diagrams-figure";
|
|
11
47
|
/** `pending` | `rendering` | `done` — the container's render life cycle. */
|
|
@@ -65,6 +101,7 @@ window.__ModuleLoader__.load({
|
|
|
65
101
|
const found = [];
|
|
66
102
|
const seen = /* @__PURE__ */ new Set();
|
|
67
103
|
for (const block of blocks) {
|
|
104
|
+
if (block.closest(FENCE_SLOT_SELECTOR) !== null) continue;
|
|
68
105
|
const pre = block.querySelector("pre");
|
|
69
106
|
if (!(pre instanceof HTMLPreElement) || seen.has(pre)) continue;
|
|
70
107
|
seen.add(pre);
|
|
@@ -245,6 +282,71 @@ window.__ModuleLoader__.load({
|
|
|
245
282
|
return cleaned;
|
|
246
283
|
}
|
|
247
284
|
//#endregion
|
|
285
|
+
//#region src/client/render.ts
|
|
286
|
+
/**
|
|
287
|
+
* Shared mermaid renderer with LRU memoization and single-init theme tracking.
|
|
288
|
+
*
|
|
289
|
+
* Both the official `conversation.chat.markdown.fence` slot layer and the
|
|
290
|
+
* document-preview DOM fallback render through this cache so theme switches
|
|
291
|
+
* and re-mounts reuse sanitized SVG without re-parsing identical sources.
|
|
292
|
+
* @module @linxin666/dsh-client-ui-diagrams/client/render
|
|
293
|
+
*/
|
|
294
|
+
/** How many rendered diagrams one renderer keeps for reuse (oldest evicted first). */
|
|
295
|
+
const CACHE_LIMIT = 32;
|
|
296
|
+
/** Monotonic id source: mermaid keys its `<svg>` by the id it is handed. */
|
|
297
|
+
let renderSeq = 0;
|
|
298
|
+
/**
|
|
299
|
+
* Create a mermaid renderer owning its own LRU cache and initialization state.
|
|
300
|
+
* @returns An isolated renderer instance.
|
|
301
|
+
*/
|
|
302
|
+
function createMermaidRenderer() {
|
|
303
|
+
const painted = /* @__PURE__ */ new Map();
|
|
304
|
+
let initialized;
|
|
305
|
+
const cacheKey = (theme, source) => `${theme}\u0000${source}`;
|
|
306
|
+
const remember = (key, svg) => {
|
|
307
|
+
if (painted.has(key)) painted.delete(key);
|
|
308
|
+
painted.set(key, svg);
|
|
309
|
+
for (const oldest of painted.keys()) {
|
|
310
|
+
if (painted.size <= CACHE_LIMIT) break;
|
|
311
|
+
painted.delete(oldest);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const ensureInitialized = (runtime, theme) => {
|
|
315
|
+
if (initialized?.runtime === runtime && initialized.theme === theme) return;
|
|
316
|
+
runtime.initialize({
|
|
317
|
+
startOnLoad: false,
|
|
318
|
+
theme,
|
|
319
|
+
securityLevel: "strict",
|
|
320
|
+
suppressErrorRendering: true,
|
|
321
|
+
htmlLabels: false,
|
|
322
|
+
fontFamily: "inherit"
|
|
323
|
+
});
|
|
324
|
+
initialized = {
|
|
325
|
+
runtime,
|
|
326
|
+
theme
|
|
327
|
+
};
|
|
328
|
+
};
|
|
329
|
+
const getCached = (source, theme) => painted.get(cacheKey(theme, source));
|
|
330
|
+
const render = async (source, theme, options = {}) => {
|
|
331
|
+
const key = cacheKey(theme, source);
|
|
332
|
+
const cached = painted.get(key);
|
|
333
|
+
if (cached !== void 0) return cached;
|
|
334
|
+
const runtime = options.runtime ?? await (options.load ?? loadRuntime)(options.runtimeUrl ?? "/api/dsh-diagrams/vendor/mermaid.js");
|
|
335
|
+
ensureInitialized(runtime, theme);
|
|
336
|
+
const { svg } = await runtime.render(`dsh-diagrams-${renderSeq += 1}`, source);
|
|
337
|
+
const cleaned = sanitizeSvg(svg);
|
|
338
|
+
remember(key, cleaned);
|
|
339
|
+
return cleaned;
|
|
340
|
+
};
|
|
341
|
+
return {
|
|
342
|
+
getCached,
|
|
343
|
+
ensureInitialized,
|
|
344
|
+
render
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/** Default page-wide renderer shared by the fence slot layer. */
|
|
348
|
+
const sharedMermaidRenderer = createMermaidRenderer();
|
|
349
|
+
//#endregion
|
|
248
350
|
//#region src/client/theme.ts
|
|
249
351
|
/**
|
|
250
352
|
* Shell theme signal for diagram rendering.
|
|
@@ -306,17 +408,14 @@ window.__ModuleLoader__.load({
|
|
|
306
408
|
* broken node behind and never throws into the caller.
|
|
307
409
|
* @module @linxin666/dsh-client-ui-diagrams/client/enhance
|
|
308
410
|
*/
|
|
309
|
-
/** Monotonic id source: mermaid keys its `<svg>` by the id it is handed. */
|
|
310
|
-
let renderSeq = 0;
|
|
311
|
-
/** How many rendered diagrams one page keeps for reuse (oldest is evicted first). */
|
|
312
|
-
const CACHE_LIMIT = 32;
|
|
313
411
|
/** Quiet period before a fence whose source changed since its last rejection retries. */
|
|
314
412
|
const RETRY_DELAY_MS = 400;
|
|
315
413
|
/**
|
|
316
414
|
* Map one mutation batch to the minimal DOM scopes that can hold a new fence.
|
|
317
415
|
* Removal-only records contribute nothing (removing a node never introduces a
|
|
318
|
-
* block), and records inside an already-rendered figure
|
|
319
|
-
*
|
|
416
|
+
* block), and records inside an already-rendered figure or inside an official
|
|
417
|
+
* `conversation.chat.markdown.fence` slot are ignored so writing the sanitized
|
|
418
|
+
* SVG or streaming chat fences cannot trigger fallback scans.
|
|
320
419
|
* @param records - The batch the observer delivered.
|
|
321
420
|
* @returns Connected elements to scan, deduped by identity.
|
|
322
421
|
*/
|
|
@@ -325,6 +424,7 @@ window.__ModuleLoader__.load({
|
|
|
325
424
|
const consider = (element) => {
|
|
326
425
|
if (element === null || !element.isConnected) return;
|
|
327
426
|
if (element.closest(`.dsh-diagrams-figure`) !== null) return;
|
|
427
|
+
if (element.closest(FENCE_SLOT_SELECTOR) !== null) return;
|
|
328
428
|
scopes.add(element.closest(`.md-code-block`) ?? element);
|
|
329
429
|
};
|
|
330
430
|
for (const record of records) {
|
|
@@ -383,43 +483,15 @@ window.__ModuleLoader__.load({
|
|
|
383
483
|
const root = options.root ?? document.body;
|
|
384
484
|
const runtimeUrl = options.runtimeUrl ?? "/api/dsh-diagrams/vendor/mermaid.js";
|
|
385
485
|
const load = options.load ?? loadRuntime;
|
|
486
|
+
const renderer = options.renderer ?? createMermaidRenderer();
|
|
386
487
|
let disposed = false;
|
|
387
488
|
/** Cancels the queued flush, while one is scheduled. */
|
|
388
489
|
let cancelFlush;
|
|
389
490
|
const queued = /* @__PURE__ */ new Set();
|
|
390
|
-
/** Sanitized SVG per `theme + source`, oldest entry evicted past the limit. */
|
|
391
|
-
const painted = /* @__PURE__ */ new Map();
|
|
392
491
|
/** The source that last made a block fail; the same source is never retried. */
|
|
393
492
|
const rejected = /* @__PURE__ */ new WeakMap();
|
|
394
493
|
/** Pending quiet-period retries, cleared on dispose. */
|
|
395
494
|
const retries = /* @__PURE__ */ new Set();
|
|
396
|
-
/** The runtime and palette the shared runtime was last initialized for. */
|
|
397
|
-
let initialized;
|
|
398
|
-
/** Remember one rendered diagram, evicting the oldest entry past the limit. */
|
|
399
|
-
const remember = (key, svg) => {
|
|
400
|
-
if (painted.has(key)) painted.delete(key);
|
|
401
|
-
painted.set(key, svg);
|
|
402
|
-
for (const oldest of painted.keys()) {
|
|
403
|
-
if (painted.size <= CACHE_LIMIT) break;
|
|
404
|
-
painted.delete(oldest);
|
|
405
|
-
}
|
|
406
|
-
};
|
|
407
|
-
/** Apply the runtime options once per runtime and palette (mermaid re-inits are expensive). */
|
|
408
|
-
const ensureInitialized = (runtime, theme) => {
|
|
409
|
-
if (initialized?.runtime === runtime && initialized.theme === theme) return;
|
|
410
|
-
runtime.initialize({
|
|
411
|
-
startOnLoad: false,
|
|
412
|
-
theme,
|
|
413
|
-
securityLevel: "strict",
|
|
414
|
-
suppressErrorRendering: true,
|
|
415
|
-
htmlLabels: false,
|
|
416
|
-
fontFamily: "inherit"
|
|
417
|
-
});
|
|
418
|
-
initialized = {
|
|
419
|
-
runtime,
|
|
420
|
-
theme
|
|
421
|
-
};
|
|
422
|
-
};
|
|
423
495
|
/**
|
|
424
496
|
* Paint one claimed container, reusing a memoized diagram when possible.
|
|
425
497
|
* @param container - The container claimed for this fence.
|
|
@@ -429,13 +501,7 @@ window.__ModuleLoader__.load({
|
|
|
429
501
|
*/
|
|
430
502
|
const paint = async (container, runtime, theme) => {
|
|
431
503
|
const source = container.getAttribute("data-diagram-source") ?? "";
|
|
432
|
-
|
|
433
|
-
const cached = painted.get(key);
|
|
434
|
-
if (cached !== void 0) return cached;
|
|
435
|
-
const { svg } = await runtime.render(`dsh-diagrams-${renderSeq += 1}`, source);
|
|
436
|
-
const cleaned = sanitizeSvg(svg);
|
|
437
|
-
remember(key, cleaned);
|
|
438
|
-
return cleaned;
|
|
504
|
+
return renderer.render(source, theme, { runtime });
|
|
439
505
|
};
|
|
440
506
|
/**
|
|
441
507
|
* Retry one fence after the quiet period, but only when its source changed:
|
|
@@ -456,7 +522,7 @@ window.__ModuleLoader__.load({
|
|
|
456
522
|
}
|
|
457
523
|
if (disposed || !pre.isConnected || pre.hasAttribute("data-diagram-claimed")) return;
|
|
458
524
|
const theme = currentTheme();
|
|
459
|
-
ensureInitialized(runtime, theme);
|
|
525
|
+
renderer.ensureInitialized(runtime, theme);
|
|
460
526
|
await renderBlock(pre, runtime, theme);
|
|
461
527
|
})();
|
|
462
528
|
}, RETRY_DELAY_MS);
|
|
@@ -488,7 +554,7 @@ window.__ModuleLoader__.load({
|
|
|
488
554
|
const enhanceScope = async (scope, runtime, theme) => {
|
|
489
555
|
const blocks = findMermaidBlocks(scope).filter((pre) => rejected.get(pre) !== (pre.textContent ?? ""));
|
|
490
556
|
if (blocks.length === 0) return;
|
|
491
|
-
ensureInitialized(runtime, theme);
|
|
557
|
+
renderer.ensureInitialized(runtime, theme);
|
|
492
558
|
for (const pre of blocks) {
|
|
493
559
|
if (disposed) return;
|
|
494
560
|
if (!pre.isConnected || pre.hasAttribute("data-diagram-claimed")) continue;
|
|
@@ -499,7 +565,7 @@ window.__ModuleLoader__.load({
|
|
|
499
565
|
};
|
|
500
566
|
/** Repaint finished diagrams for the current shell theme, reusing what is cached. */
|
|
501
567
|
const retheme = async () => {
|
|
502
|
-
const containers = finishedContainers(root);
|
|
568
|
+
const containers = finishedContainers(root).filter((el) => el.closest(FENCE_SLOT_SELECTOR) === null);
|
|
503
569
|
if (containers.length === 0) return;
|
|
504
570
|
let runtime;
|
|
505
571
|
try {
|
|
@@ -509,7 +575,7 @@ window.__ModuleLoader__.load({
|
|
|
509
575
|
}
|
|
510
576
|
if (disposed) return;
|
|
511
577
|
const theme = currentTheme();
|
|
512
|
-
ensureInitialized(runtime, theme);
|
|
578
|
+
renderer.ensureInitialized(runtime, theme);
|
|
513
579
|
for (const container of containers) {
|
|
514
580
|
if (disposed) return;
|
|
515
581
|
if (!container.isConnected) continue;
|
|
@@ -568,22 +634,120 @@ window.__ModuleLoader__.load({
|
|
|
568
634
|
};
|
|
569
635
|
}
|
|
570
636
|
//#endregion
|
|
637
|
+
//#region src/client/MermaidFenceLayer.tsx
|
|
638
|
+
/**
|
|
639
|
+
* Official `conversation.chat.markdown.fence` hoc layer for `mermaid` fences.
|
|
640
|
+
*
|
|
641
|
+
* While a message is streaming, the layer returns the inner plain code block
|
|
642
|
+
* untouched so half-written diagrams never trigger parse errors or layout
|
|
643
|
+
* churn. Once settled, it loads the vendored runtime on demand, renders and
|
|
644
|
+
* sanitizes the SVG for the current shell theme, and replaces the code block;
|
|
645
|
+
* any parse, sanitizer, or runtime failure falls back to the untouched code
|
|
646
|
+
* block.
|
|
647
|
+
* @module @linxin666/dsh-client-ui-diagrams/client/MermaidFenceLayer
|
|
648
|
+
*/
|
|
649
|
+
function initialTheme() {
|
|
650
|
+
if (typeof document === "undefined" || document.body === null) return "default";
|
|
651
|
+
return mermaidTheme(shellIsDark());
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Render settled `mermaid` markdown fences in the official chat flow as
|
|
655
|
+
* sanitized SVG diagrams, falling back to `children` while streaming or on any
|
|
656
|
+
* error.
|
|
657
|
+
*/
|
|
658
|
+
function MermaidFenceLayer({ code, streaming, children, runtimeUrl = RUNTIME_ROUTE, load, renderer = sharedMermaidRenderer }) {
|
|
659
|
+
const [theme, setTheme] = (0, react.useState)(initialTheme);
|
|
660
|
+
const trimmed = code.trim();
|
|
661
|
+
const cached = !streaming && trimmed !== "" ? renderer.getCached(code, theme) : void 0;
|
|
662
|
+
const [rendered, setRendered] = (0, react.useState)(() => cached !== void 0 ? {
|
|
663
|
+
key: `${theme}\u0000${code}`,
|
|
664
|
+
svg: cached
|
|
665
|
+
} : null);
|
|
666
|
+
(0, react.useEffect)(() => {
|
|
667
|
+
if (typeof document === "undefined" || document.body === null) return void 0;
|
|
668
|
+
setTheme(mermaidTheme(shellIsDark()));
|
|
669
|
+
return watchTheme((isDark) => {
|
|
670
|
+
setTheme(mermaidTheme(isDark));
|
|
671
|
+
});
|
|
672
|
+
}, []);
|
|
673
|
+
const targetKey = `${theme}\u0000${code}`;
|
|
674
|
+
(0, react.useEffect)(() => {
|
|
675
|
+
if (streaming || trimmed === "") return void 0;
|
|
676
|
+
const hit = renderer.getCached(code, theme);
|
|
677
|
+
if (hit !== void 0) {
|
|
678
|
+
setRendered({
|
|
679
|
+
key: targetKey,
|
|
680
|
+
svg: hit
|
|
681
|
+
});
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
let cancelled = false;
|
|
685
|
+
renderer.render(code, theme, {
|
|
686
|
+
runtimeUrl,
|
|
687
|
+
load
|
|
688
|
+
}).then((svg) => {
|
|
689
|
+
if (!cancelled) setRendered({
|
|
690
|
+
key: targetKey,
|
|
691
|
+
svg
|
|
692
|
+
});
|
|
693
|
+
}, () => {
|
|
694
|
+
if (!cancelled) setRendered((prev) => prev?.key === targetKey ? null : prev);
|
|
695
|
+
});
|
|
696
|
+
return () => {
|
|
697
|
+
cancelled = true;
|
|
698
|
+
};
|
|
699
|
+
}, [
|
|
700
|
+
code,
|
|
701
|
+
trimmed,
|
|
702
|
+
streaming,
|
|
703
|
+
theme,
|
|
704
|
+
targetKey,
|
|
705
|
+
runtimeUrl,
|
|
706
|
+
load,
|
|
707
|
+
renderer
|
|
708
|
+
]);
|
|
709
|
+
if (streaming || trimmed === "") return children;
|
|
710
|
+
const svg = cached ?? (rendered?.key === targetKey ? rendered.svg : void 0);
|
|
711
|
+
if (svg === void 0) return children;
|
|
712
|
+
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
|
713
|
+
className: DIAGRAM_CLASS,
|
|
714
|
+
"data-dsh-plugin": PLUGIN_NAME,
|
|
715
|
+
"data-dsh-part": PART_NAME,
|
|
716
|
+
[DATA_STATE]: "done",
|
|
717
|
+
[DATA_SOURCE]: code,
|
|
718
|
+
dangerouslySetInnerHTML: { __html: svg }
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
//#endregion
|
|
571
722
|
//#region src/client/index.ts
|
|
723
|
+
/** Optional service declaration: slots is present in standard web shells. */
|
|
724
|
+
const inject = { slots: { required: false } };
|
|
572
725
|
/**
|
|
573
|
-
*
|
|
574
|
-
*
|
|
726
|
+
* Register the official chat fence layer (when `ctx.slots` is available) and
|
|
727
|
+
* start the document-preview fallback enhancement for the plugin lifetime.
|
|
728
|
+
* @param ctx - Client context; effects dispose the slot and observer on unload.
|
|
575
729
|
*/
|
|
576
730
|
function apply(ctx) {
|
|
577
|
-
ctx.
|
|
731
|
+
const slots = typeof ctx.get === "function" ? ctx.get("slots", false) : void 0;
|
|
732
|
+
if (slots !== void 0) slots.inject(FENCE_SLOT_NAME, () => slots.register({
|
|
733
|
+
name: FENCE_SLOT_NAME,
|
|
734
|
+
key: RENDERED_LANGUAGE,
|
|
735
|
+
id: FENCE_LAYER_ID
|
|
736
|
+
}, MermaidFenceLayer));
|
|
737
|
+
ctx.effect(() => startEnhancement({ renderer: sharedMermaidRenderer }), "diagrams: render mermaid fences");
|
|
578
738
|
}
|
|
579
739
|
//#endregion
|
|
740
|
+
exports.MermaidFenceLayer = MermaidFenceLayer;
|
|
580
741
|
exports.apply = apply;
|
|
742
|
+
exports.createMermaidRenderer = createMermaidRenderer;
|
|
581
743
|
exports.findMermaidBlocks = findMermaidBlocks;
|
|
744
|
+
exports.inject = inject;
|
|
582
745
|
exports.loadRuntime = loadRuntime;
|
|
583
746
|
exports.mermaidTheme = mermaidTheme;
|
|
584
747
|
exports.runtimeIfLoaded = runtimeIfLoaded;
|
|
585
748
|
exports.sanitizeSvg = sanitizeSvg;
|
|
586
749
|
exports.scopesForRecords = scopesForRecords;
|
|
750
|
+
exports.sharedMermaidRenderer = sharedMermaidRenderer;
|
|
587
751
|
exports.shellIsDark = shellIsDark;
|
|
588
752
|
exports.startEnhancement = startEnhancement;
|
|
589
753
|
exports.watchTheme = watchTheme;
|
package/lib/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../../packages/dsh-diagrams/src/core/contract.ts","../../../packages/dsh-diagrams/src/client/blocks.ts","../../../packages/dsh-diagrams/src/client/runtime.ts","../../../packages/dsh-diagrams/src/client/sanitize.ts","../../../packages/dsh-diagrams/src/client/theme.ts","../../../packages/dsh-diagrams/src/client/enhance.ts","../../../packages/dsh-diagrams/src/client/index.ts"],"sourcesContent":["/**\n * The one place the diagram feature's external names live: the host route the\n * browser half loads the vendored runtime from, and the DOM hooks the official\n * markdown renderer exposes. Both halves and the tests read these constants, so\n * a host upgrade that renames a hook fails one contract test instead of\n * silently disabling the feature.\n *\n * The DOM hooks are NOT a published contract: the renderer has no code-block\n * extension seam (see the Agent Note), so they are read off its elements.\n * `md-code-block` is a literal class name in the renderer's JSX. The banner has\n * two known shapes across legacy `_<local>_<hash>` and 0.2.3-alpha.2\n * `<hash>_<local>` CSS Module class patterns: an `_infostring` element carrying\n * the raw fence infostring, and a `_language` span, which shows the language\n * only when the highlighter knows it - an unsupported language (mermaid among\n * them) renders a localized placeholder such as `代码块` or `Code block`\n * instead.\n * @module @linxin666/dsh-client-ui-diagrams/core/contract\n */\n\n/** Host route serving the vendored mermaid runtime (same origin, no CDN). */\nexport const RUNTIME_ROUTE = '/api/dsh-diagrams/vendor/mermaid.js'\n\n/** Class the official markdown renderer puts on every fenced code block. */\nexport const CODE_BLOCK_CLASS = 'md-code-block'\n\n/** Class-name fragment of the banner element carrying the fence infostring. */\nexport const INFOSTRING_CLASS_FRAGMENT = '_infostring'\n\n/** Class-name fragment of the banner span carrying the language label. */\nexport const LANGUAGE_CLASS_FRAGMENT = '_language'\n\n/** Fence language this package renders. Everything else is left untouched. */\nexport const RENDERED_LANGUAGE = 'mermaid'\n\n/** Class the rendered diagram container carries (styled by the theme). */\nexport const DIAGRAM_CLASS = 'dsh-diagrams-figure'\n\n/** `pending` | `rendering` | `done` — the container's render life cycle. */\nexport const DATA_STATE = 'data-diagram-state'\n\n/** The verbatim fence source, kept for theme re-renders. */\nexport const DATA_SOURCE = 'data-diagram-source'\n\n/** Marks the code block this package already claimed (one render per block). */\nexport const DATA_CLAIMED = 'data-diagram-claimed'\n\n/** Semantic-attribute values from the family contract (`data-dsh-plugin` / `data-dsh-part`). */\nexport const PLUGIN_NAME = 'diagrams'\n\n/** Semantic part value for the rendered figure. */\nexport const PART_NAME = 'diagram'\n","/**\n * Finding, claiming and restoring mermaid code blocks in the official markdown\n * DOM, and the container that replaces them.\n *\n * The renderer's fenced code block is a `div.md-code-block`; its `<pre>` has no\n * language class. The banner has two known shapes (see core/contract.ts): an\n * `_infostring_` element carrying the raw fence infostring, or a `_language_`\n * span that shows a localized placeholder when the highlighter does not know\n * the language. Mermaid is never a highlighter language, so on that shape the\n * label alone cannot identify the fence and the source's first keyword decides.\n * A real language label (js, bash, json, ...) always wins: those fences are\n * never claimed, whatever their source looks like.\n * The original `<pre>` is therefore HIDDEN, never removed: the block's own copy\n * button keeps reading the source from it.\n * @module @linxin666/dsh-client-ui-diagrams/client/blocks\n */\n\nimport {\n CODE_BLOCK_CLASS,\n DATA_CLAIMED,\n DATA_SOURCE,\n DATA_STATE,\n DIAGRAM_CLASS,\n INFOSTRING_CLASS_FRAGMENT,\n LANGUAGE_CLASS_FRAGMENT,\n PART_NAME,\n PLUGIN_NAME,\n RENDERED_LANGUAGE,\n} from '../core/contract.ts'\n\n/**\n * First-keyword signature of the mermaid diagram types. Consulted only when the\n * banner label is a localized placeholder (or absent), never to override a real\n * language label. Issue #2056: the rc.3 renderer hides the fence infostring\n * behind `i.codeLabel` for every language the highlighter does not know.\n */\nconst MERMAID_HEAD = /^\\s*(?:flowchart|graph|sequenceDiagram|classDiagram|stateDiagram(?:-v2)?|erDiagram|journey|gantt|pie|quadrantChart|requirementDiagram|gitGraph|mindmap|timeline|sankey-beta|xychart-beta|block-beta|packet-beta|architecture-beta|C4Context|C4Container|C4Component|C4Dynamic|C4Deployment)\\b/\n\n/** Generic labels that are not a fence language: placeholders and mermaid itself. */\nconst NON_LANGUAGE_LABEL = /^(?:code|text|plain|plaintext|snippet|mermaid)$/i\n\n/**\n * Whether a banner label is a real fence language rather than a localized\n * placeholder. A placeholder carries CJK text or spaces; a real language is a\n * short ASCII token. The generic non-language labels are excluded so a fence\n * the highlighter does not know still falls through to the source signature.\n * Enumerating placeholder words per locale is deliberately avoided: the set\n * grows with every renderer language (#2056).\n */\nfunction isRealLanguageLabel(label: string): boolean {\n if (!/^[A-Za-z0-9+#._-]{1,24}$/.test(label)) return false\n return !NON_LANGUAGE_LABEL.test(label)\n}\n\n/** The mermaid blocks under one scope that this package has not claimed yet. */\nexport function findMermaidBlocks(scope: ParentNode): HTMLPreElement[] {\n const blocks: Element[] = []\n if (scope instanceof Element && scope.classList.contains(CODE_BLOCK_CLASS)) blocks.push(scope)\n blocks.push(...Array.from(scope.querySelectorAll(`.${CODE_BLOCK_CLASS}`)))\n\n const found: HTMLPreElement[] = []\n const seen = new Set<Element>()\n for (const block of blocks) {\n const pre = block.querySelector('pre')\n if (!(pre instanceof HTMLPreElement) || seen.has(pre)) continue\n seen.add(pre)\n if (pre.hasAttribute(DATA_CLAIMED)) continue\n if ((pre.textContent ?? '').trim() === '') continue\n const label = (block.querySelector(\n `[class*=\"${INFOSTRING_CLASS_FRAGMENT}\"], [class*=\"${LANGUAGE_CLASS_FRAGMENT}\"]`,\n )?.textContent ?? '').trim()\n if (label.toLowerCase() === RENDERED_LANGUAGE) {\n found.push(pre)\n continue\n }\n if (isRealLanguageLabel(label)) continue\n if (!MERMAID_HEAD.test(pre.textContent ?? '')) continue\n found.push(pre)\n }\n return found\n}\n\n/**\n * Create the diagram container for one block and mark the block claimed.\n * @param pre - The block's `<pre>` (kept in the tree, hidden once rendered).\n * @returns The container to fill with the sanitized SVG.\n */\nexport function claimBlock(pre: HTMLPreElement): HTMLElement {\n pre.setAttribute(DATA_CLAIMED, '1')\n const container = document.createElement('div')\n container.className = DIAGRAM_CLASS\n container.setAttribute(DATA_STATE, 'pending')\n container.setAttribute(DATA_SOURCE, pre.textContent ?? '')\n container.setAttribute('data-dsh-plugin', PLUGIN_NAME)\n container.setAttribute('data-dsh-part', PART_NAME)\n pre.insertAdjacentElement('afterend', container)\n return container\n}\n\n/**\n * Undo one claim: drop the container and free the block for a later attempt\n * (a streaming fence becomes renderable once it closes).\n * @param pre - The block's `<pre>`.\n * @param container - The container created for it.\n */\nexport function restoreBlock(pre: HTMLPreElement, container: HTMLElement): void {\n container.remove()\n pre.removeAttribute(DATA_CLAIMED)\n pre.style.removeProperty('display')\n}\n\n/** Hide the source block once its diagram landed (the copy button still reads it). */\nexport function hideSourceBlock(pre: HTMLPreElement): void {\n pre.style.display = 'none'\n}\n\n/** Every finished container under one scope (retheme input). */\nexport function finishedContainers(scope: ParentNode): HTMLElement[] {\n return Array.from(scope.querySelectorAll<HTMLElement>(`.${DIAGRAM_CLASS}[data-diagram-state=\"done\"]`))\n}\n","/**\n * On-demand loader for the vendored mermaid runtime.\n *\n * The bundle is a third-party IIFE that leaves a `window.mermaid` global, so\n * the handle is validated structurally (never trusted) and one `<script>` is\n * injected per page no matter how many blocks ask for it. A failed load clears\n * the memo so a later block can retry after a transient failure.\n * @module @linxin666/dsh-client-ui-diagrams/client/runtime\n */\n\n/** The slice of the mermaid API this package consumes. */\nexport interface MermaidRuntime {\n /** Apply global render options (called once per render batch). */\n initialize: (config: Record<string, unknown>) => void\n /** Render one diagram source to SVG markup. */\n render: (id: string, text: string) => Promise<{ svg: string }>\n}\n\n/** Resolve the runtime global, or null while it is absent or malformed. */\nexport function runtimeIfLoaded(): MermaidRuntime | null {\n const candidate = (globalThis as Record<string, unknown>).mermaid\n if (typeof candidate !== 'object' || candidate === null) return null\n const checked = candidate as Record<string, unknown>\n if (typeof checked.initialize !== 'function' || typeof checked.render !== 'function') return null\n return checked as unknown as MermaidRuntime\n}\n\n/** Shared in-flight load, so concurrent batches inject one script. */\nlet pending: Promise<MermaidRuntime> | undefined\n\n/**\n * Load the runtime once per page from the host route.\n * @param url - Same-origin vendor route serving the IIFE bundle.\n * @returns The validated runtime; rejects when the script cannot load.\n */\nexport function loadRuntime(url: string): Promise<MermaidRuntime> {\n const loaded = runtimeIfLoaded()\n if (loaded !== null) return Promise.resolve(loaded)\n if (pending !== undefined) return pending\n pending = new Promise<MermaidRuntime>((resolve, reject) => {\n const script = document.createElement('script')\n script.src = url\n script.async = true\n script.addEventListener('load', () => {\n const runtime = runtimeIfLoaded()\n if (runtime === null) {\n pending = undefined\n reject(new Error('diagrams: the vendor script loaded but left no mermaid global'))\n return\n }\n resolve(runtime)\n })\n script.addEventListener('error', () => {\n pending = undefined\n reject(new Error(`diagrams: failed to load ${url}`))\n })\n document.head.appendChild(script)\n })\n return pending\n}\n","/**\n * Defence in depth for the rendered SVG.\n *\n * Mermaid's strict security level already escapes label content, but the SVG is\n * third-party output injected into the page, so it is parsed in a detached\n * document first and stripped of anything executable: script-ish elements,\n * `on*` handlers and URL attributes with an executable scheme. Cleaned markup is\n * returned; input that still carries a dangerous token after cleaning throws, and\n * the caller falls back to the untouched code block.\n *\n * One walk does both removals: dropping a disallowed element drops everything\n * beneath it, so a second pass would only re-examine nodes that are already\n * detached. The suspicious-token check runs as a case-insensitive pattern over\n * the markup rather than over a lowercased copy of it, because a large diagram\n * is hundreds of kilobytes of markup and that copy is pure garbage.\n * @module @linxin666/dsh-client-ui-diagrams/client/sanitize\n */\n\n/** Elements that must never reach the page from a diagram's markup. */\nconst DISALLOWED_ELEMENTS = new Set(['script', 'foreignobject', 'iframe', 'object', 'embed'])\n\n/** A token that may not survive sanitizing: a script open tag or a javascript: URL. */\nconst SUSPICIOUS_CONTENT = /<script|javascript:/i\n\n/** An attribute name that is an event handler (`onclick`, `onload`, ...). */\nfunction isEventHandler(name: string): boolean {\n return /^on/i.test(name)\n}\n\n/**\n * URL schemes that can carry or turn into executable content.\n *\n * `javascript:` and `vbscript:` run script when the link is followed; `data:` can\n * navigate to attacker-authored markup (`data:text/html,...`), and the mermaid\n * runtime's own `@braintree/sanitize-url` already blocks all three, so nothing it\n * renders depends on a `data:` target.\n */\nconst EXECUTABLE_SCHEMES = new Set(['javascript:', 'vbscript:', 'data:'])\n\n/**\n * A URL attribute value whose scheme is executable once the browser parses it.\n *\n * The value is parsed instead of prefix-matched: a browser removes ASCII tab, line\n * feed and carriage return characters anywhere in a URL and leading C0 controls and\n * spaces before it reads the scheme, so `java<TAB>script:` and ` javascript:` both\n * execute while a `^\\s*javascript:` test sees neither. Parsing also sees the\n * entity-decoded form, because the attribute is already decoded by the time the\n * template parses the markup. A value without a colon carries no scheme, so it skips\n * the parse; the base only makes a relative value absolute and is never fetched.\n */\nfunction isExecutableUrl(value: string): boolean {\n if (!value.includes(':')) {\n return false\n }\n try {\n return EXECUTABLE_SCHEMES.has(new URL(value, 'https://diagram.invalid/').protocol)\n } catch {\n return false\n }\n}\n\n/**\n * Strip executable content from one rendered diagram.\n * @param svg - Markup returned by the mermaid runtime.\n * @returns The cleaned markup, safe to assign as `innerHTML`.\n * @throws When the markup cannot be parsed or still carries a dangerous token.\n */\nexport function sanitizeSvg(svg: string): string {\n const template = document.createElement('template')\n template.innerHTML = svg\n const root = template.content\n\n for (const element of Array.from(root.querySelectorAll('*'))) {\n if (DISALLOWED_ELEMENTS.has(element.tagName.toLowerCase())) {\n element.remove()\n continue\n }\n for (const attribute of Array.from(element.attributes)) {\n if (isEventHandler(attribute.name) || isExecutableUrl(attribute.value)) {\n element.removeAttribute(attribute.name)\n }\n }\n }\n\n const cleaned = template.innerHTML\n if (SUSPICIOUS_CONTENT.test(cleaned)) {\n throw new Error('diagrams: rendered SVG still carries executable content after sanitizing')\n }\n return cleaned\n}\n","/**\n * Shell theme signal for diagram rendering.\n *\n * The shell marks a dark palette with `data-ds-dark-theme` on `<body>`; mermaid\n * renders colors into the SVG itself, so a theme flip must re-render the\n * diagrams rather than recolor them with CSS.\n * @module @linxin666/dsh-client-ui-diagrams/client/theme\n */\n\n/** Mermaid theme name for the shell palette. */\nexport function mermaidTheme(isDark: boolean): 'default' | 'dark' {\n return isDark ? 'dark' : 'default'\n}\n\n/** Whether the shell currently carries the dark-palette marker. */\nexport function shellIsDark(): boolean {\n return document.body.hasAttribute('data-ds-dark-theme')\n}\n\n/**\n * Watch the dark-palette marker.\n * @param onChange - Called with the new state on every flip.\n * @returns The disposer.\n */\nexport function watchTheme(onChange: (isDark: boolean) => void): () => void {\n const observer = new MutationObserver(() => { onChange(shellIsDark()) })\n observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme'] })\n return () => { observer.disconnect() }\n}\n","/**\n * The DOM enhancement: watch the page for markdown code blocks whose fence\n * language is `mermaid`, render each one with the vendored runtime, and keep\n * the diagrams in step with the shell theme.\n *\n * Why an observer instead of a render hook: the official markdown renderer has\n * no code-block extension seam (see the Agent Note), so the only integration\n * point is its output DOM. The observer is scoped to mutated subtrees (mapped to\n * the owning code block) and coalesced to one animation frame per batch, so a\n * long streaming transcript never re-scans the whole document.\n *\n * Cost control: mermaid parses and lays out synchronously on the page's main\n * thread, so the work here is scheduled rather than fired at once. Diagrams are\n * painted one per frame (a document with twelve diagrams stays scrollable while\n * they land), the sanitized SVG is memoized per theme and source (a palette\n * flip back, or a host re-render that re-claims a block, costs nothing), the\n * runtime is initialized only when the palette actually changes, and a fence the\n * parser rejects is never retried with the same source — its own rollback\n * mutates the DOM, so retrying on every mutation would spin the page forever.\n *\n * Failure policy: every failure restores the untouched code block — a missing\n * runtime, a half-streamed fence, or a diagram the parser rejects never leaves a\n * broken node behind and never throws into the caller.\n * @module @linxin666/dsh-client-ui-diagrams/client/enhance\n */\n\nimport { CODE_BLOCK_CLASS, DIAGRAM_CLASS, DATA_STATE, RUNTIME_ROUTE } from '../core/contract.ts'\nimport { claimBlock, findMermaidBlocks, finishedContainers, hideSourceBlock, restoreBlock } from './blocks.ts'\nimport { loadRuntime, type MermaidRuntime } from './runtime.ts'\nimport { sanitizeSvg } from './sanitize.ts'\nimport { mermaidTheme, shellIsDark, watchTheme } from './theme.ts'\n\n/** Options for {@link startEnhancement} (tests override the loader and root). */\nexport interface EnhancementOptions {\n /** Same-origin route serving the runtime bundle. */\n runtimeUrl?: string\n /** Observation root; defaults to `document.body`. */\n root?: HTMLElement\n /** Runtime loader override; defaults to the script-injecting loader. */\n load?: (url: string) => Promise<MermaidRuntime>\n}\n\n/** Monotonic id source: mermaid keys its `<svg>` by the id it is handed. */\nlet renderSeq = 0\n\n/** How many rendered diagrams one page keeps for reuse (oldest is evicted first). */\nconst CACHE_LIMIT = 32\n\n/** Quiet period before a fence whose source changed since its last rejection retries. */\nconst RETRY_DELAY_MS = 400\n\n/**\n * Map one mutation batch to the minimal DOM scopes that can hold a new fence.\n * Removal-only records contribute nothing (removing a node never introduces a\n * block), and records inside an already-rendered figure are ignored so writing\n * the sanitized SVG cannot re-trigger the pass.\n * @param records - The batch the observer delivered.\n * @returns Connected elements to scan, deduped by identity.\n */\nexport function scopesForRecords(records: MutationRecord[]): Element[] {\n const scopes = new Set<Element>()\n const consider = (element: Element | null): void => {\n if (element === null || !element.isConnected) return\n if (element.closest(`.${DIAGRAM_CLASS}`) !== null) return\n scopes.add(element.closest(`.${CODE_BLOCK_CLASS}`) ?? element)\n }\n for (const record of records) {\n if (record.addedNodes.length === 0) continue\n if (record.target instanceof Element) consider(record.target)\n for (const node of Array.from(record.addedNodes)) {\n consider(node instanceof Element ? node : node.parentElement)\n }\n }\n return [...scopes]\n}\n\n/** The mermaid palette the shell currently asks for. */\nfunction currentTheme(): string {\n return mermaidTheme(shellIsDark())\n}\n\n/** Upper bound on one scheduling hop, so a throttled tab cannot stall the queue. */\nconst FRAME_BACKSTOP_MS = 48\n\n/**\n * Run one callback on the next frame, or after a short timeout when frames do\n * not arrive (a hidden tab throttles `requestAnimationFrame` to nothing).\n * @param run - The callback to run once.\n * @returns The cancelling callback: runs (or marks) the callback once only.\n */\nfunction afterNextFrame(run: () => void): () => void {\n let frame = 0\n let timer: ReturnType<typeof setTimeout> | undefined\n let done = false\n const once = (): void => {\n if (done) return\n done = true\n if (timer !== undefined) clearTimeout(timer)\n if (frame !== 0 && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame)\n run()\n }\n if (typeof requestAnimationFrame === 'function') frame = requestAnimationFrame(once)\n timer = setTimeout(once, FRAME_BACKSTOP_MS)\n return once\n}\n\n/** Let the page paint between two diagrams so a long document stays responsive. */\nfunction nextPaint(): Promise<void> {\n return new Promise<void>((resolve) => { afterNextFrame(() => { resolve() }) })\n}\n\n/**\n * Start the enhancement and return its disposer.\n *\n * The first pass scans the whole observation root (the transcript usually\n * mounted before this plugin), then only mutated subtrees are scanned. A theme\n * flip repaints every finished diagram from its stored source.\n * @param options - Root, route and loader overrides.\n * @returns Disposer: disconnect the observer, stop the theme watch, drop timers.\n */\nexport function startEnhancement(options: EnhancementOptions = {}): () => void {\n if (typeof document === 'undefined') return () => {}\n const root = options.root ?? document.body\n const runtimeUrl = options.runtimeUrl ?? RUNTIME_ROUTE\n const load = options.load ?? loadRuntime\n\n let disposed = false\n /** Cancels the queued flush, while one is scheduled. */\n let cancelFlush: (() => void) | undefined\n const queued = new Set<Element>()\n\n /** Sanitized SVG per `theme + source`, oldest entry evicted past the limit. */\n const painted = new Map<string, string>()\n /** The source that last made a block fail; the same source is never retried. */\n const rejected = new WeakMap<HTMLPreElement, string>()\n /** Pending quiet-period retries, cleared on dispose. */\n const retries = new Set<ReturnType<typeof setTimeout>>()\n /** The runtime and palette the shared runtime was last initialized for. */\n let initialized: { runtime: MermaidRuntime; theme: string } | undefined\n\n /** Remember one rendered diagram, evicting the oldest entry past the limit. */\n const remember = (key: string, svg: string): void => {\n if (painted.has(key)) painted.delete(key)\n painted.set(key, svg)\n for (const oldest of painted.keys()) {\n if (painted.size <= CACHE_LIMIT) break\n painted.delete(oldest)\n }\n }\n\n /** Apply the runtime options once per runtime and palette (mermaid re-inits are expensive). */\n const ensureInitialized = (runtime: MermaidRuntime, theme: string): void => {\n if (initialized?.runtime === runtime && initialized.theme === theme) return\n runtime.initialize({\n startOnLoad: false,\n theme,\n securityLevel: 'strict',\n // Mermaid otherwise leaves its error diagram under body when render throws;\n // the rollback below owns the failure UI and restores the source block.\n suppressErrorRendering: true,\n // Labels must be SVG text: mermaid's HTML labels live in <foreignObject>,\n // which the sanitizer strips, so an HTML label renders as an empty box.\n htmlLabels: false,\n fontFamily: 'inherit',\n })\n initialized = { runtime, theme }\n }\n\n /**\n * Paint one claimed container, reusing a memoized diagram when possible.\n * @param container - The container claimed for this fence.\n * @param runtime - Loaded mermaid runtime.\n * @param theme - Palette the diagram must be painted for.\n * @returns The sanitized SVG for that container.\n */\n const paint = async (container: HTMLElement, runtime: MermaidRuntime, theme: string): Promise<string> => {\n const source = container.getAttribute('data-diagram-source') ?? ''\n const key = `${theme}\\u0000${source}`\n const cached = painted.get(key)\n if (cached !== undefined) return cached\n const { svg } = await runtime.render(`dsh-diagrams-${(renderSeq += 1)}`, source)\n const cleaned = sanitizeSvg(svg)\n remember(key, cleaned)\n return cleaned\n }\n\n /**\n * Retry one fence after the quiet period, but only when its source changed:\n * the source that already failed is final until the fence grows.\n * @param pre - The source block whose render was rejected.\n */\n const scheduleRetry = (pre: HTMLPreElement): void => {\n const timer = setTimeout(() => {\n retries.delete(timer)\n if (disposed || !pre.isConnected || pre.hasAttribute('data-diagram-claimed')) return\n if (rejected.get(pre) === (pre.textContent ?? '')) return\n void (async () => {\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return // A vendor route that cannot answer leaves the fence as an ordinary block.\n }\n if (disposed || !pre.isConnected || pre.hasAttribute('data-diagram-claimed')) return\n const theme = currentTheme()\n ensureInitialized(runtime, theme)\n await renderBlock(pre, runtime, theme)\n })()\n }, RETRY_DELAY_MS)\n retries.add(timer)\n }\n\n /**\n * Render one source block in place, restoring it on any failure.\n * @param pre - The fence's source block.\n * @param runtime - Loaded mermaid runtime.\n * @param theme - Palette to paint for.\n */\n const renderBlock = async (pre: HTMLPreElement, runtime: MermaidRuntime, theme: string): Promise<void> => {\n const container = claimBlock(pre)\n try {\n container.setAttribute(DATA_STATE, 'rendering')\n const cleaned = await paint(container, runtime, theme)\n if (disposed || !container.isConnected) return\n container.innerHTML = cleaned\n container.setAttribute(DATA_STATE, 'done')\n hideSourceBlock(pre)\n } catch {\n // Syntax error, missing runtime support or a half-streamed fence: put the\n // code block back untouched and never retry this exact source again.\n const source = container.getAttribute('data-diagram-source') ?? ''\n restoreBlock(pre, container)\n rejected.set(pre, source)\n scheduleRetry(pre)\n }\n }\n\n /** Render every unclaimed mermaid block under one scope, one diagram per frame. */\n const enhanceScope = async (scope: ParentNode, runtime: MermaidRuntime, theme: string): Promise<void> => {\n const blocks = findMermaidBlocks(scope).filter(pre => rejected.get(pre) !== (pre.textContent ?? ''))\n if (blocks.length === 0) return\n ensureInitialized(runtime, theme)\n for (const pre of blocks) {\n if (disposed) return\n if (!pre.isConnected || pre.hasAttribute('data-diagram-claimed')) continue\n // oxlint-disable-next-line eslint/no-await-in-loop -- one diagram per frame is the point of this loop.\n await renderBlock(pre, runtime, theme)\n if (disposed) return\n // oxlint-disable-next-line eslint/no-await-in-loop -- the painted frame between diagrams is the point of this loop.\n await nextPaint()\n }\n }\n\n /** Repaint finished diagrams for the current shell theme, reusing what is cached. */\n const retheme = async (): Promise<void> => {\n const containers = finishedContainers(root)\n if (containers.length === 0) return\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return\n }\n if (disposed) return\n const theme = currentTheme()\n ensureInitialized(runtime, theme)\n for (const container of containers) {\n if (disposed) return\n if (!container.isConnected) continue\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one repaint per frame is the point of this loop.\n const cleaned = await paint(container, runtime, theme)\n if (disposed || !container.isConnected) return\n container.innerHTML = cleaned\n container.setAttribute(DATA_STATE, 'done')\n } catch {\n // A theme flip must never blank a diagram that already rendered.\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- the painted frame between repaints is the point of this loop.\n await nextPaint()\n }\n }\n\n /** One coalesced pass over the queued scopes. */\n const flush = async (): Promise<void> => {\n cancelFlush = undefined\n const scopes = [...queued]\n queued.clear()\n if (disposed || scopes.length === 0) return\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return // no vendor route: leave every fence as an ordinary code block\n }\n const theme = currentTheme()\n for (const scope of scopes) {\n if (disposed) return\n // oxlint-disable-next-line eslint/no-await-in-loop -- scopes are scanned one at a time so each can yield.\n await enhanceScope(scope, runtime, theme)\n }\n }\n\n const schedule = (scopes: readonly Element[]): void => {\n for (const scope of scopes) queued.add(scope)\n if (queued.size === 0 || cancelFlush !== undefined) return\n cancelFlush = afterNextFrame(() => {\n cancelFlush = undefined\n void flush()\n })\n }\n\n if (typeof MutationObserver === 'function') {\n const observer = new MutationObserver((records) => { schedule(scopesForRecords(records)) })\n observer.observe(root, { childList: true, subtree: true })\n }\n const stopThemeWatch = watchTheme(() => { void retheme() })\n schedule([root])\n\n return () => {\n disposed = true\n cancelFlush?.()\n cancelFlush = undefined\n for (const timer of retries) clearTimeout(timer)\n retries.clear()\n stopThemeWatch()\n }\n}\n","/**\n * Browser entry of the diagrams plugin.\n *\n * The enhancement needs no slot and no service: it observes the page for the\n * official markdown renderer's mermaid fences (chat transcript and document\n * preview alike) and renders them itself. `apply` therefore only owns the\n * effect's lifetime.\n * @module @linxin666/dsh-client-ui-diagrams/client\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport { startEnhancement } from './enhance.ts'\n\n/**\n * Start the diagram enhancement for the lifetime of this client plugin.\n * @param ctx - Client context; the effect disposes the observer on unload.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => startEnhancement(), 'diagrams: render mermaid fences')\n}\n\nexport { startEnhancement } from './enhance.ts'\nexport { scopesForRecords } from './enhance.ts'\nexport { findMermaidBlocks } from './blocks.ts'\nexport { sanitizeSvg } from './sanitize.ts'\nexport { mermaidTheme, shellIsDark, watchTheme } from './theme.ts'\nexport { loadRuntime, runtimeIfLoaded, type MermaidRuntime } from './runtime.ts'\n"],"mappings":";;;;;;;EAuBA,MAAa,mBAAmB;;EAYhC,MAAa,gBAAgB;;EAG7B,MAAa,aAAa;;EAG1B,MAAa,cAAc;;EAG3B,MAAa,eAAe;;EAG5B,MAAa,cAAc;;EAG3B,MAAa,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;ECdzB,MAAM,eAAe;;EAGrB,MAAM,qBAAqB;;;;;;;;;EAU3B,SAAS,oBAAoB,OAAwB;GACnD,IAAI,CAAC,2BAA2B,KAAK,KAAK,GAAG,OAAO;GACpD,OAAO,CAAC,mBAAmB,KAAK,KAAK;EACvC;;EAGA,SAAgB,kBAAkB,OAAqC;GACrE,MAAM,SAAoB,CAAC;GAC3B,IAAI,iBAAiB,WAAW,MAAM,UAAU,SAAA,eAAyB,GAAG,OAAO,KAAK,KAAK;GAC7F,OAAO,KAAK,GAAG,MAAM,KAAK,MAAM,iBAAiB,IAAI,kBAAkB,CAAC,CAAC;GAEzE,MAAM,QAA0B,CAAC;GACjC,MAAM,uBAAO,IAAI,IAAa;GAC9B,KAAK,MAAM,SAAS,QAAQ;IAC1B,MAA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IAClB;GACF;;GAGA,MAAM,QAAQ,YAA2B;IACvC,cAAc,KAAA;IACd,MAAM,SAAS,CAAC,GAAG,MAAM;IACzB,OAAO,MAAM;IACb,IAAI,YAAY,OAAO,WAAW,GAAG;IACrC,IAAI;IACJ,IAAI;KACF,UAAU,MAAM,KAAK,UAAU;IACjC,QAAQ;KACN;IACF;IACA,MAAM,QAAQ,aAAa;IAC3B,KAAK,MAAM,SAAS,QAAQ;KAC1B,IAAI,UAAU;KAEd,MAAM,aAAa,OAAO,SAAS,KAAK;IAC1C;GACF;GAEA,MAAM,YAAY,WAAqC;IACrD,KAAK,MAAM,SAAS,QAAQ,OAAO,IAAI,KAAK;IAC5C,IAAI,OAAO,SAAS,KAAK,gBAAgB,KAAA,GAAW;IACpD,cAAc,qBAAqB;KACjC,cAAc,KAAA;KACd,MAAW;IACb,CAAC;GACH;GAEA,IAAI,OAAO,qBAAqB,YAE9B,IADqB,kBAAkB,YAAY;IAAE,SAAS,iBAAiB,OAAO,CAAC;GAAE,CAClF,CAAC,CAAC,QAAQ,MAAM;IAAE,WAAW;IAAM,SAAS;GAAK,CAAC;GAE3D,MAAM,iBAAiB,iBAAiB;IAAE,QAAa;GAAE,CAAC;GAC1D,SAAS,CAAC,IAAI,CAAC;GAEf,aAAa;IACX,WAAW;IACX,cAAc;IACd,cAAc,KAAA;IACd,KAAK,MAAM,SAAS,SAAS,aAAa,KAAK;IAC/C,QAAQ,MAAM;IACd,eAAe;GACjB;EACF;;;;;;;ECtTA,SAAgB,MAAM,KAA0B;GAC9C,IAAI,aAAa,iBAAiB,GAAG,iCAAiC;EACxE"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../../packages/dsh-diagrams/src/core/contract.ts","../../../packages/dsh-diagrams/src/client/blocks.ts","../../../packages/dsh-diagrams/src/client/runtime.ts","../../../packages/dsh-diagrams/src/client/sanitize.ts","../../../packages/dsh-diagrams/src/client/render.ts","../../../packages/dsh-diagrams/src/client/theme.ts","../../../packages/dsh-diagrams/src/client/enhance.ts","../../../packages/dsh-diagrams/src/client/MermaidFenceLayer.tsx","../../../packages/dsh-diagrams/src/client/index.ts"],"sourcesContent":["/**\n * The one place the diagram feature's external names live: the host route the\n * browser half loads the vendored runtime from, the official chat fence slot\n * seam, and the DOM fallback hooks the official markdown renderer exposes.\n * Both halves and the tests read these constants, so a host upgrade that\n * renames a hook fails one contract test instead of silently disabling the\n * feature.\n *\n * In the chat transcript, official `ui-chat` (DSH 0.2.3-alpha.2+) dispatches\n * fenced code blocks through the session-scoped `conversation.chat.markdown.fence`\n * hoc slot keyed by lowercased language name (`mermaid`). Surfaces that still\n * render Markdown without passing `renderCode` (such as the document preview\n * pane) fall back to the DOM observer using the hooks below.\n *\n * `md-code-block` is a literal class name in the renderer's JSX. The banner has\n * two known shapes across legacy `_<local>_<hash>` and 0.2.3-alpha.2\n * `<hash>_<local>` CSS Module class patterns: an `_infostring` element carrying\n * the raw fence infostring, and a `_language` span, which shows the language\n * only when the highlighter knows it - an unsupported language (mermaid among\n * them) renders a localized placeholder such as `代码块` or `Code block`\n * instead.\n * @module @linxin666/dsh-client-ui-diagrams/core/contract\n */\n\n/** Host route serving the vendored mermaid runtime (same origin, no CDN). */\nexport const RUNTIME_ROUTE = '/api/dsh-diagrams/vendor/mermaid.js'\n\n/** Official chat markdown fence hoc slot name (DSH 0.2.3-alpha.2+). */\nexport const FENCE_SLOT_NAME = 'conversation.chat.markdown.fence'\n\n/** Stable slot occupant id for the mermaid fence layer. */\nexport const FENCE_LAYER_ID = '@linxin666/dsh-client-ui-diagrams/fence/mermaid'\n\n/** Selector matching blocks already owned by the official chat fence slot. */\nexport const FENCE_SLOT_SELECTOR = `[data-slot=\"${FENCE_SLOT_NAME}\"]`\n\n/** Class the official markdown renderer puts on every fenced code block. */\nexport const CODE_BLOCK_CLASS = 'md-code-block'\n\n/** Class-name fragment of the banner element carrying the fence infostring. */\nexport const INFOSTRING_CLASS_FRAGMENT = '_infostring'\n\n/** Class-name fragment of the banner span carrying the language label. */\nexport const LANGUAGE_CLASS_FRAGMENT = '_language'\n\n/** Fence language this package renders. Everything else is left untouched. */\nexport const RENDERED_LANGUAGE = 'mermaid'\n\n/** Class the rendered diagram container carries (styled by the theme). */\nexport const DIAGRAM_CLASS = 'dsh-diagrams-figure'\n\n/** `pending` | `rendering` | `done` — the container's render life cycle. */\nexport const DATA_STATE = 'data-diagram-state'\n\n/** The verbatim fence source, kept for theme re-renders. */\nexport const DATA_SOURCE = 'data-diagram-source'\n\n/** Marks the code block this package already claimed (one render per block). */\nexport const DATA_CLAIMED = 'data-diagram-claimed'\n\n/** Semantic-attribute values from the family contract (`data-dsh-plugin` / `data-dsh-part`). */\nexport const PLUGIN_NAME = 'diagrams'\n\n/** Semantic part value for the rendered figure. */\nexport const PART_NAME = 'diagram'\n","/**\n * Finding, claiming and restoring mermaid code blocks in the official markdown\n * DOM, and the container that replaces them.\n *\n * The renderer's fenced code block is a `div.md-code-block`; its `<pre>` has no\n * language class. The banner has two known shapes (see core/contract.ts): an\n * `_infostring_` element carrying the raw fence infostring, or a `_language_`\n * span that shows a localized placeholder when the highlighter does not know\n * the language. Mermaid is never a highlighter language, so on that shape the\n * label alone cannot identify the fence and the source's first keyword decides.\n * A real language label (js, bash, json, ...) always wins: those fences are\n * never claimed, whatever their source looks like.\n * The original `<pre>` is therefore HIDDEN, never removed: the block's own copy\n * button keeps reading the source from it.\n * @module @linxin666/dsh-client-ui-diagrams/client/blocks\n */\n\nimport {\n CODE_BLOCK_CLASS,\n DATA_CLAIMED,\n DATA_SOURCE,\n DATA_STATE,\n DIAGRAM_CLASS,\n FENCE_SLOT_SELECTOR,\n INFOSTRING_CLASS_FRAGMENT,\n LANGUAGE_CLASS_FRAGMENT,\n PART_NAME,\n PLUGIN_NAME,\n RENDERED_LANGUAGE,\n} from '../core/contract.ts'\n\n/**\n * First-keyword signature of the mermaid diagram types. Consulted only when the\n * banner label is a localized placeholder (or absent), never to override a real\n * language label. Issue #2056: the rc.3 renderer hides the fence infostring\n * behind `i.codeLabel` for every language the highlighter does not know.\n */\nconst MERMAID_HEAD = /^\\s*(?:flowchart|graph|sequenceDiagram|classDiagram|stateDiagram(?:-v2)?|erDiagram|journey|gantt|pie|quadrantChart|requirementDiagram|gitGraph|mindmap|timeline|sankey-beta|xychart-beta|block-beta|packet-beta|architecture-beta|C4Context|C4Container|C4Component|C4Dynamic|C4Deployment)\\b/\n\n/** Generic labels that are not a fence language: placeholders and mermaid itself. */\nconst NON_LANGUAGE_LABEL = /^(?:code|text|plain|plaintext|snippet|mermaid)$/i\n\n/**\n * Whether a banner label is a real fence language rather than a localized\n * placeholder. A placeholder carries CJK text or spaces; a real language is a\n * short ASCII token. The generic non-language labels are excluded so a fence\n * the highlighter does not know still falls through to the source signature.\n * Enumerating placeholder words per locale is deliberately avoided: the set\n * grows with every renderer language (#2056).\n */\nfunction isRealLanguageLabel(label: string): boolean {\n if (!/^[A-Za-z0-9+#._-]{1,24}$/.test(label)) return false\n return !NON_LANGUAGE_LABEL.test(label)\n}\n\n/** The mermaid blocks under one scope that this package has not claimed yet. */\nexport function findMermaidBlocks(scope: ParentNode): HTMLPreElement[] {\n const blocks: Element[] = []\n if (scope instanceof Element && scope.classList.contains(CODE_BLOCK_CLASS)) blocks.push(scope)\n blocks.push(...Array.from(scope.querySelectorAll(`.${CODE_BLOCK_CLASS}`)))\n\n const found: HTMLPreElement[] = []\n const seen = new Set<Element>()\n for (const block of blocks) {\n // Official chat markdown fences are rendered natively by the\n // `conversation.chat.markdown.fence` hoc layer; never claim or mutate them\n // from the DOM fallback observer (whether streaming, rendered, or fallen back).\n if (block.closest(FENCE_SLOT_SELECTOR) !== null) continue\n const pre = block.querySelector('pre')\n if (!(pre instanceof HTMLPreElement) || seen.has(pre)) continue\n seen.add(pre)\n if (pre.hasAttribute(DATA_CLAIMED)) continue\n if ((pre.textContent ?? '').trim() === '') continue\n const label = (block.querySelector(\n `[class*=\"${INFOSTRING_CLASS_FRAGMENT}\"], [class*=\"${LANGUAGE_CLASS_FRAGMENT}\"]`,\n )?.textContent ?? '').trim()\n if (label.toLowerCase() === RENDERED_LANGUAGE) {\n found.push(pre)\n continue\n }\n if (isRealLanguageLabel(label)) continue\n if (!MERMAID_HEAD.test(pre.textContent ?? '')) continue\n found.push(pre)\n }\n return found\n}\n\n/**\n * Create the diagram container for one block and mark the block claimed.\n * @param pre - The block's `<pre>` (kept in the tree, hidden once rendered).\n * @returns The container to fill with the sanitized SVG.\n */\nexport function claimBlock(pre: HTMLPreElement): HTMLElement {\n pre.setAttribute(DATA_CLAIMED, '1')\n const container = document.createElement('div')\n container.className = DIAGRAM_CLASS\n container.setAttribute(DATA_STATE, 'pending')\n container.setAttribute(DATA_SOURCE, pre.textContent ?? '')\n container.setAttribute('data-dsh-plugin', PLUGIN_NAME)\n container.setAttribute('data-dsh-part', PART_NAME)\n pre.insertAdjacentElement('afterend', container)\n return container\n}\n\n/**\n * Undo one claim: drop the container and free the block for a later attempt\n * (a streaming fence becomes renderable once it closes).\n * @param pre - The block's `<pre>`.\n * @param container - The container created for it.\n */\nexport function restoreBlock(pre: HTMLPreElement, container: HTMLElement): void {\n container.remove()\n pre.removeAttribute(DATA_CLAIMED)\n pre.style.removeProperty('display')\n}\n\n/** Hide the source block once its diagram landed (the copy button still reads it). */\nexport function hideSourceBlock(pre: HTMLPreElement): void {\n pre.style.display = 'none'\n}\n\n/** Every finished container under one scope (retheme input). */\nexport function finishedContainers(scope: ParentNode): HTMLElement[] {\n return Array.from(scope.querySelectorAll<HTMLElement>(`.${DIAGRAM_CLASS}[data-diagram-state=\"done\"]`))\n}\n","/**\n * On-demand loader for the vendored mermaid runtime.\n *\n * The bundle is a third-party IIFE that leaves a `window.mermaid` global, so\n * the handle is validated structurally (never trusted) and one `<script>` is\n * injected per page no matter how many blocks ask for it. A failed load clears\n * the memo so a later block can retry after a transient failure.\n * @module @linxin666/dsh-client-ui-diagrams/client/runtime\n */\n\n/** The slice of the mermaid API this package consumes. */\nexport interface MermaidRuntime {\n /** Apply global render options (called once per render batch). */\n initialize: (config: Record<string, unknown>) => void\n /** Render one diagram source to SVG markup. */\n render: (id: string, text: string) => Promise<{ svg: string }>\n}\n\n/** Resolve the runtime global, or null while it is absent or malformed. */\nexport function runtimeIfLoaded(): MermaidRuntime | null {\n const candidate = (globalThis as Record<string, unknown>).mermaid\n if (typeof candidate !== 'object' || candidate === null) return null\n const checked = candidate as Record<string, unknown>\n if (typeof checked.initialize !== 'function' || typeof checked.render !== 'function') return null\n return checked as unknown as MermaidRuntime\n}\n\n/** Shared in-flight load, so concurrent batches inject one script. */\nlet pending: Promise<MermaidRuntime> | undefined\n\n/**\n * Load the runtime once per page from the host route.\n * @param url - Same-origin vendor route serving the IIFE bundle.\n * @returns The validated runtime; rejects when the script cannot load.\n */\nexport function loadRuntime(url: string): Promise<MermaidRuntime> {\n const loaded = runtimeIfLoaded()\n if (loaded !== null) return Promise.resolve(loaded)\n if (pending !== undefined) return pending\n pending = new Promise<MermaidRuntime>((resolve, reject) => {\n const script = document.createElement('script')\n script.src = url\n script.async = true\n script.addEventListener('load', () => {\n const runtime = runtimeIfLoaded()\n if (runtime === null) {\n pending = undefined\n reject(new Error('diagrams: the vendor script loaded but left no mermaid global'))\n return\n }\n resolve(runtime)\n })\n script.addEventListener('error', () => {\n pending = undefined\n reject(new Error(`diagrams: failed to load ${url}`))\n })\n document.head.appendChild(script)\n })\n return pending\n}\n","/**\n * Defence in depth for the rendered SVG.\n *\n * Mermaid's strict security level already escapes label content, but the SVG is\n * third-party output injected into the page, so it is parsed in a detached\n * document first and stripped of anything executable: script-ish elements,\n * `on*` handlers and URL attributes with an executable scheme. Cleaned markup is\n * returned; input that still carries a dangerous token after cleaning throws, and\n * the caller falls back to the untouched code block.\n *\n * One walk does both removals: dropping a disallowed element drops everything\n * beneath it, so a second pass would only re-examine nodes that are already\n * detached. The suspicious-token check runs as a case-insensitive pattern over\n * the markup rather than over a lowercased copy of it, because a large diagram\n * is hundreds of kilobytes of markup and that copy is pure garbage.\n * @module @linxin666/dsh-client-ui-diagrams/client/sanitize\n */\n\n/** Elements that must never reach the page from a diagram's markup. */\nconst DISALLOWED_ELEMENTS = new Set(['script', 'foreignobject', 'iframe', 'object', 'embed'])\n\n/** A token that may not survive sanitizing: a script open tag or a javascript: URL. */\nconst SUSPICIOUS_CONTENT = /<script|javascript:/i\n\n/** An attribute name that is an event handler (`onclick`, `onload`, ...). */\nfunction isEventHandler(name: string): boolean {\n return /^on/i.test(name)\n}\n\n/**\n * URL schemes that can carry or turn into executable content.\n *\n * `javascript:` and `vbscript:` run script when the link is followed; `data:` can\n * navigate to attacker-authored markup (`data:text/html,...`), and the mermaid\n * runtime's own `@braintree/sanitize-url` already blocks all three, so nothing it\n * renders depends on a `data:` target.\n */\nconst EXECUTABLE_SCHEMES = new Set(['javascript:', 'vbscript:', 'data:'])\n\n/**\n * A URL attribute value whose scheme is executable once the browser parses it.\n *\n * The value is parsed instead of prefix-matched: a browser removes ASCII tab, line\n * feed and carriage return characters anywhere in a URL and leading C0 controls and\n * spaces before it reads the scheme, so `java<TAB>script:` and ` javascript:` both\n * execute while a `^\\s*javascript:` test sees neither. Parsing also sees the\n * entity-decoded form, because the attribute is already decoded by the time the\n * template parses the markup. A value without a colon carries no scheme, so it skips\n * the parse; the base only makes a relative value absolute and is never fetched.\n */\nfunction isExecutableUrl(value: string): boolean {\n if (!value.includes(':')) {\n return false\n }\n try {\n return EXECUTABLE_SCHEMES.has(new URL(value, 'https://diagram.invalid/').protocol)\n } catch {\n return false\n }\n}\n\n/**\n * Strip executable content from one rendered diagram.\n * @param svg - Markup returned by the mermaid runtime.\n * @returns The cleaned markup, safe to assign as `innerHTML`.\n * @throws When the markup cannot be parsed or still carries a dangerous token.\n */\nexport function sanitizeSvg(svg: string): string {\n const template = document.createElement('template')\n template.innerHTML = svg\n const root = template.content\n\n for (const element of Array.from(root.querySelectorAll('*'))) {\n if (DISALLOWED_ELEMENTS.has(element.tagName.toLowerCase())) {\n element.remove()\n continue\n }\n for (const attribute of Array.from(element.attributes)) {\n if (isEventHandler(attribute.name) || isExecutableUrl(attribute.value)) {\n element.removeAttribute(attribute.name)\n }\n }\n }\n\n const cleaned = template.innerHTML\n if (SUSPICIOUS_CONTENT.test(cleaned)) {\n throw new Error('diagrams: rendered SVG still carries executable content after sanitizing')\n }\n return cleaned\n}\n","/**\n * Shared mermaid renderer with LRU memoization and single-init theme tracking.\n *\n * Both the official `conversation.chat.markdown.fence` slot layer and the\n * document-preview DOM fallback render through this cache so theme switches\n * and re-mounts reuse sanitized SVG without re-parsing identical sources.\n * @module @linxin666/dsh-client-ui-diagrams/client/render\n */\n\nimport { RUNTIME_ROUTE } from '../core/contract.ts'\nimport { loadRuntime, type MermaidRuntime } from './runtime.ts'\nimport { sanitizeSvg } from './sanitize.ts'\n\n/** How many rendered diagrams one renderer keeps for reuse (oldest evicted first). */\nconst CACHE_LIMIT = 32\n\n/** Monotonic id source: mermaid keys its `<svg>` by the id it is handed. */\nlet renderSeq = 0\n\n/** Options for rendering one mermaid diagram source. */\nexport interface RenderMermaidOptions {\n /** Same-origin route serving the vendored runtime bundle. */\n runtimeUrl?: string\n /** Runtime loader override (tests inject fakes). */\n load?: (url: string) => Promise<MermaidRuntime>\n /** Already-loaded runtime handle, skipping the loader when provided. */\n runtime?: MermaidRuntime\n}\n\n/** Stateful mermaid renderer instance (shared in production, isolated in tests). */\nexport interface MermaidRenderer {\n /** Read a previously rendered, sanitized SVG from the LRU cache, if present. */\n getCached(source: string, theme: string): string | undefined\n /** Initialize the runtime once per `(runtime, theme)` pair. */\n ensureInitialized(runtime: MermaidRuntime, theme: string): void\n /** Render and sanitize one mermaid source for the requested theme. */\n render(source: string, theme: string, options?: RenderMermaidOptions): Promise<string>\n}\n\n/**\n * Create a mermaid renderer owning its own LRU cache and initialization state.\n * @returns An isolated renderer instance.\n */\nexport function createMermaidRenderer(): MermaidRenderer {\n const painted = new Map<string, string>()\n let initialized: { runtime: MermaidRuntime; theme: string } | undefined\n\n const cacheKey = (theme: string, source: string): string => `${theme}\\u0000${source}`\n\n const remember = (key: string, svg: string): void => {\n if (painted.has(key)) painted.delete(key)\n painted.set(key, svg)\n for (const oldest of painted.keys()) {\n if (painted.size <= CACHE_LIMIT) break\n painted.delete(oldest)\n }\n }\n\n const ensureInitialized = (runtime: MermaidRuntime, theme: string): void => {\n if (initialized?.runtime === runtime && initialized.theme === theme) return\n runtime.initialize({\n startOnLoad: false,\n theme,\n securityLevel: 'strict',\n // Mermaid otherwise leaves its error diagram under body when render throws;\n // callers own the failure UI and fall back to the source block.\n suppressErrorRendering: true,\n // Labels must be SVG text: mermaid's HTML labels live in <foreignObject>,\n // which the sanitizer strips, so an HTML label renders as an empty box.\n htmlLabels: false,\n fontFamily: 'inherit',\n })\n initialized = { runtime, theme }\n }\n\n const getCached = (source: string, theme: string): string | undefined => painted.get(cacheKey(theme, source))\n\n const render = async (\n source: string,\n theme: string,\n options: RenderMermaidOptions = {},\n ): Promise<string> => {\n const key = cacheKey(theme, source)\n const cached = painted.get(key)\n if (cached !== undefined) return cached\n const runtime = options.runtime ?? await (options.load ?? loadRuntime)(options.runtimeUrl ?? RUNTIME_ROUTE)\n ensureInitialized(runtime, theme)\n const { svg } = await runtime.render(`dsh-diagrams-${(renderSeq += 1)}`, source)\n const cleaned = sanitizeSvg(svg)\n remember(key, cleaned)\n return cleaned\n }\n\n return { getCached, ensureInitialized, render }\n}\n\n/** Default page-wide renderer shared by the fence slot layer. */\nexport const sharedMermaidRenderer: MermaidRenderer = createMermaidRenderer()\n","/**\n * Shell theme signal for diagram rendering.\n *\n * The shell marks a dark palette with `data-ds-dark-theme` on `<body>`; mermaid\n * renders colors into the SVG itself, so a theme flip must re-render the\n * diagrams rather than recolor them with CSS.\n * @module @linxin666/dsh-client-ui-diagrams/client/theme\n */\n\n/** Mermaid theme name for the shell palette. */\nexport function mermaidTheme(isDark: boolean): 'default' | 'dark' {\n return isDark ? 'dark' : 'default'\n}\n\n/** Whether the shell currently carries the dark-palette marker. */\nexport function shellIsDark(): boolean {\n return document.body.hasAttribute('data-ds-dark-theme')\n}\n\n/**\n * Watch the dark-palette marker.\n * @param onChange - Called with the new state on every flip.\n * @returns The disposer.\n */\nexport function watchTheme(onChange: (isDark: boolean) => void): () => void {\n const observer = new MutationObserver(() => { onChange(shellIsDark()) })\n observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme'] })\n return () => { observer.disconnect() }\n}\n","/**\n * The DOM enhancement: watch the page for markdown code blocks whose fence\n * language is `mermaid`, render each one with the vendored runtime, and keep\n * the diagrams in step with the shell theme.\n *\n * Why an observer instead of a render hook: the official markdown renderer has\n * no code-block extension seam (see the Agent Note), so the only integration\n * point is its output DOM. The observer is scoped to mutated subtrees (mapped to\n * the owning code block) and coalesced to one animation frame per batch, so a\n * long streaming transcript never re-scans the whole document.\n *\n * Cost control: mermaid parses and lays out synchronously on the page's main\n * thread, so the work here is scheduled rather than fired at once. Diagrams are\n * painted one per frame (a document with twelve diagrams stays scrollable while\n * they land), the sanitized SVG is memoized per theme and source (a palette\n * flip back, or a host re-render that re-claims a block, costs nothing), the\n * runtime is initialized only when the palette actually changes, and a fence the\n * parser rejects is never retried with the same source — its own rollback\n * mutates the DOM, so retrying on every mutation would spin the page forever.\n *\n * Failure policy: every failure restores the untouched code block — a missing\n * runtime, a half-streamed fence, or a diagram the parser rejects never leaves a\n * broken node behind and never throws into the caller.\n * @module @linxin666/dsh-client-ui-diagrams/client/enhance\n */\n\nimport { CODE_BLOCK_CLASS, DIAGRAM_CLASS, DATA_STATE, FENCE_SLOT_SELECTOR, RUNTIME_ROUTE } from '../core/contract.ts'\nimport { claimBlock, findMermaidBlocks, finishedContainers, hideSourceBlock, restoreBlock } from './blocks.ts'\nimport { createMermaidRenderer, type MermaidRenderer } from './render.ts'\nimport { loadRuntime, type MermaidRuntime } from './runtime.ts'\nimport { mermaidTheme, shellIsDark, watchTheme } from './theme.ts'\n\n/** Options for {@link startEnhancement} (tests override the loader and root). */\nexport interface EnhancementOptions {\n /** Same-origin route serving the runtime bundle. */\n runtimeUrl?: string\n /** Observation root; defaults to `document.body`. */\n root?: HTMLElement\n /** Runtime loader override; defaults to the script-injecting loader. */\n load?: (url: string) => Promise<MermaidRuntime>\n /** Shared or isolated mermaid renderer instance. */\n renderer?: MermaidRenderer\n}\n\n/** Quiet period before a fence whose source changed since its last rejection retries. */\nconst RETRY_DELAY_MS = 400\n\n/**\n * Map one mutation batch to the minimal DOM scopes that can hold a new fence.\n * Removal-only records contribute nothing (removing a node never introduces a\n * block), and records inside an already-rendered figure or inside an official\n * `conversation.chat.markdown.fence` slot are ignored so writing the sanitized\n * SVG or streaming chat fences cannot trigger fallback scans.\n * @param records - The batch the observer delivered.\n * @returns Connected elements to scan, deduped by identity.\n */\nexport function scopesForRecords(records: MutationRecord[]): Element[] {\n const scopes = new Set<Element>()\n const consider = (element: Element | null): void => {\n if (element === null || !element.isConnected) return\n if (element.closest(`.${DIAGRAM_CLASS}`) !== null) return\n if (element.closest(FENCE_SLOT_SELECTOR) !== null) return\n scopes.add(element.closest(`.${CODE_BLOCK_CLASS}`) ?? element)\n }\n for (const record of records) {\n if (record.addedNodes.length === 0) continue\n if (record.target instanceof Element) consider(record.target)\n for (const node of Array.from(record.addedNodes)) {\n consider(node instanceof Element ? node : node.parentElement)\n }\n }\n return [...scopes]\n}\n\n/** The mermaid palette the shell currently asks for. */\nfunction currentTheme(): string {\n return mermaidTheme(shellIsDark())\n}\n\n/** Upper bound on one scheduling hop, so a throttled tab cannot stall the queue. */\nconst FRAME_BACKSTOP_MS = 48\n\n/**\n * Run one callback on the next frame, or after a short timeout when frames do\n * not arrive (a hidden tab throttles `requestAnimationFrame` to nothing).\n * @param run - The callback to run once.\n * @returns The cancelling callback: runs (or marks) the callback once only.\n */\nfunction afterNextFrame(run: () => void): () => void {\n let frame = 0\n let timer: ReturnType<typeof setTimeout> | undefined\n let done = false\n const once = (): void => {\n if (done) return\n done = true\n if (timer !== undefined) clearTimeout(timer)\n if (frame !== 0 && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame)\n run()\n }\n if (typeof requestAnimationFrame === 'function') frame = requestAnimationFrame(once)\n timer = setTimeout(once, FRAME_BACKSTOP_MS)\n return once\n}\n\n/** Let the page paint between two diagrams so a long document stays responsive. */\nfunction nextPaint(): Promise<void> {\n return new Promise<void>((resolve) => { afterNextFrame(() => { resolve() }) })\n}\n\n/**\n * Start the enhancement and return its disposer.\n *\n * The first pass scans the whole observation root (the transcript usually\n * mounted before this plugin), then only mutated subtrees are scanned. A theme\n * flip repaints every finished diagram from its stored source.\n * @param options - Root, route and loader overrides.\n * @returns Disposer: disconnect the observer, stop the theme watch, drop timers.\n */\nexport function startEnhancement(options: EnhancementOptions = {}): () => void {\n if (typeof document === 'undefined') return () => {}\n const root = options.root ?? document.body\n const runtimeUrl = options.runtimeUrl ?? RUNTIME_ROUTE\n const load = options.load ?? loadRuntime\n const renderer = options.renderer ?? createMermaidRenderer()\n\n let disposed = false\n /** Cancels the queued flush, while one is scheduled. */\n let cancelFlush: (() => void) | undefined\n const queued = new Set<Element>()\n\n /** The source that last made a block fail; the same source is never retried. */\n const rejected = new WeakMap<HTMLPreElement, string>()\n /** Pending quiet-period retries, cleared on dispose. */\n const retries = new Set<ReturnType<typeof setTimeout>>()\n\n /**\n * Paint one claimed container, reusing a memoized diagram when possible.\n * @param container - The container claimed for this fence.\n * @param runtime - Loaded mermaid runtime.\n * @param theme - Palette the diagram must be painted for.\n * @returns The sanitized SVG for that container.\n */\n const paint = async (container: HTMLElement, runtime: MermaidRuntime, theme: string): Promise<string> => {\n const source = container.getAttribute('data-diagram-source') ?? ''\n return renderer.render(source, theme, { runtime })\n }\n\n /**\n * Retry one fence after the quiet period, but only when its source changed:\n * the source that already failed is final until the fence grows.\n * @param pre - The source block whose render was rejected.\n */\n const scheduleRetry = (pre: HTMLPreElement): void => {\n const timer = setTimeout(() => {\n retries.delete(timer)\n if (disposed || !pre.isConnected || pre.hasAttribute('data-diagram-claimed')) return\n if (rejected.get(pre) === (pre.textContent ?? '')) return\n void (async () => {\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return // A vendor route that cannot answer leaves the fence as an ordinary block.\n }\n if (disposed || !pre.isConnected || pre.hasAttribute('data-diagram-claimed')) return\n const theme = currentTheme()\n renderer.ensureInitialized(runtime, theme)\n await renderBlock(pre, runtime, theme)\n })()\n }, RETRY_DELAY_MS)\n retries.add(timer)\n }\n\n /**\n * Render one source block in place, restoring it on any failure.\n * @param pre - The fence's source block.\n * @param runtime - Loaded mermaid runtime.\n * @param theme - Palette to paint for.\n */\n const renderBlock = async (pre: HTMLPreElement, runtime: MermaidRuntime, theme: string): Promise<void> => {\n const container = claimBlock(pre)\n try {\n container.setAttribute(DATA_STATE, 'rendering')\n const cleaned = await paint(container, runtime, theme)\n if (disposed || !container.isConnected) return\n container.innerHTML = cleaned\n container.setAttribute(DATA_STATE, 'done')\n hideSourceBlock(pre)\n } catch {\n // Syntax error, missing runtime support or a half-streamed fence: put the\n // code block back untouched and never retry this exact source again.\n const source = container.getAttribute('data-diagram-source') ?? ''\n restoreBlock(pre, container)\n rejected.set(pre, source)\n scheduleRetry(pre)\n }\n }\n\n /** Render every unclaimed mermaid block under one scope, one diagram per frame. */\n const enhanceScope = async (scope: ParentNode, runtime: MermaidRuntime, theme: string): Promise<void> => {\n const blocks = findMermaidBlocks(scope).filter(pre => rejected.get(pre) !== (pre.textContent ?? ''))\n if (blocks.length === 0) return\n renderer.ensureInitialized(runtime, theme)\n for (const pre of blocks) {\n if (disposed) return\n if (!pre.isConnected || pre.hasAttribute('data-diagram-claimed')) continue\n // oxlint-disable-next-line eslint/no-await-in-loop -- one diagram per frame is the point of this loop.\n await renderBlock(pre, runtime, theme)\n if (disposed) return\n // oxlint-disable-next-line eslint/no-await-in-loop -- the painted frame between diagrams is the point of this loop.\n await nextPaint()\n }\n }\n\n /** Repaint finished diagrams for the current shell theme, reusing what is cached. */\n const retheme = async (): Promise<void> => {\n const containers = finishedContainers(root).filter(el => el.closest(FENCE_SLOT_SELECTOR) === null)\n if (containers.length === 0) return\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return\n }\n if (disposed) return\n const theme = currentTheme()\n renderer.ensureInitialized(runtime, theme)\n for (const container of containers) {\n if (disposed) return\n if (!container.isConnected) continue\n try {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one repaint per frame is the point of this loop.\n const cleaned = await paint(container, runtime, theme)\n if (disposed || !container.isConnected) return\n container.innerHTML = cleaned\n container.setAttribute(DATA_STATE, 'done')\n } catch {\n // A theme flip must never blank a diagram that already rendered.\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- the painted frame between repaints is the point of this loop.\n await nextPaint()\n }\n }\n\n /** One coalesced pass over the queued scopes. */\n const flush = async (): Promise<void> => {\n cancelFlush = undefined\n const scopes = [...queued]\n queued.clear()\n if (disposed || scopes.length === 0) return\n let runtime: MermaidRuntime\n try {\n runtime = await load(runtimeUrl)\n } catch {\n return // no vendor route: leave every fence as an ordinary code block\n }\n const theme = currentTheme()\n for (const scope of scopes) {\n if (disposed) return\n // oxlint-disable-next-line eslint/no-await-in-loop -- scopes are scanned one at a time so each can yield.\n await enhanceScope(scope, runtime, theme)\n }\n }\n\n const schedule = (scopes: readonly Element[]): void => {\n for (const scope of scopes) queued.add(scope)\n if (queued.size === 0 || cancelFlush !== undefined) return\n cancelFlush = afterNextFrame(() => {\n cancelFlush = undefined\n void flush()\n })\n }\n\n if (typeof MutationObserver === 'function') {\n const observer = new MutationObserver((records) => { schedule(scopesForRecords(records)) })\n observer.observe(root, { childList: true, subtree: true })\n }\n const stopThemeWatch = watchTheme(() => { void retheme() })\n schedule([root])\n\n return () => {\n disposed = true\n cancelFlush?.()\n cancelFlush = undefined\n for (const timer of retries) clearTimeout(timer)\n retries.clear()\n stopThemeWatch()\n }\n}\n","/**\n * Official `conversation.chat.markdown.fence` hoc layer for `mermaid` fences.\n *\n * While a message is streaming, the layer returns the inner plain code block\n * untouched so half-written diagrams never trigger parse errors or layout\n * churn. Once settled, it loads the vendored runtime on demand, renders and\n * sanitizes the SVG for the current shell theme, and replaces the code block;\n * any parse, sanitizer, or runtime failure falls back to the untouched code\n * block.\n * @module @linxin666/dsh-client-ui-diagrams/client/MermaidFenceLayer\n */\n\nimport { useEffect, useState, type ReactNode } from 'react'\nimport type {} from '@deepseek-ai/dsh-client-ui-chat/client'\nimport type { HocShare, PropsRuntime, SlotMap } from '@deepseek-ai/dsh-client-ui-slots/client'\nimport {\n DATA_SOURCE,\n DATA_STATE,\n DIAGRAM_CLASS,\n PART_NAME,\n PLUGIN_NAME,\n RUNTIME_ROUTE,\n} from '../core/contract.ts'\nimport { sharedMermaidRenderer, type MermaidRenderer } from './render.ts'\nimport type { MermaidRuntime } from './runtime.ts'\nimport { mermaidTheme, shellIsDark, watchTheme } from './theme.ts'\n\n/** Props delivered by the official fence slot plus optional test overrides. */\nexport type MermaidFenceLayerProps =\n & Partial<PropsRuntime<'conversation.chat.markdown.fence'>>\n & Pick<PropsRuntime<'conversation.chat.markdown.fence'>, 'lang' | 'code' | 'streaming'>\n & HocShare<SlotMap['conversation.chat.markdown.fence']>\n & {\n /** Same-origin vendor route override. */\n runtimeUrl?: string\n /** Runtime loader override (tests inject fakes). */\n load?: (url: string) => Promise<MermaidRuntime>\n /** Isolated renderer cache override (tests inject fresh instances). */\n renderer?: MermaidRenderer\n }\n\nfunction initialTheme(): 'default' | 'dark' {\n if (typeof document === 'undefined' || document.body === null) return 'default'\n return mermaidTheme(shellIsDark())\n}\n\n/**\n * Render settled `mermaid` markdown fences in the official chat flow as\n * sanitized SVG diagrams, falling back to `children` while streaming or on any\n * error.\n */\nexport function MermaidFenceLayer({\n code,\n streaming,\n children,\n runtimeUrl = RUNTIME_ROUTE,\n load,\n renderer = sharedMermaidRenderer,\n}: MermaidFenceLayerProps): ReactNode {\n const [theme, setTheme] = useState<'default' | 'dark'>(initialTheme)\n const trimmed = code.trim()\n const cached = !streaming && trimmed !== '' ? renderer.getCached(code, theme) : undefined\n const [rendered, setRendered] = useState<{ key: string; svg: string } | null>(() => (\n cached !== undefined ? { key: `${theme}\\u0000${code}`, svg: cached } : null\n ))\n\n useEffect(() => {\n if (typeof document === 'undefined' || document.body === null) return undefined\n setTheme(mermaidTheme(shellIsDark()))\n return watchTheme((isDark) => {\n setTheme(mermaidTheme(isDark))\n })\n }, [])\n\n const targetKey = `${theme}\\u0000${code}`\n\n useEffect(() => {\n if (streaming || trimmed === '') return undefined\n const hit = renderer.getCached(code, theme)\n if (hit !== undefined) {\n setRendered({ key: targetKey, svg: hit })\n return undefined\n }\n let cancelled = false\n void renderer.render(code, theme, { runtimeUrl, load }).then(\n (svg) => {\n if (!cancelled) setRendered({ key: targetKey, svg })\n },\n () => {\n if (!cancelled) {\n setRendered((prev) => (prev?.key === targetKey ? null : prev))\n }\n },\n )\n return () => {\n cancelled = true\n }\n }, [code, trimmed, streaming, theme, targetKey, runtimeUrl, load, renderer])\n\n if (streaming || trimmed === '') return children\n\n const svg = cached ?? (rendered?.key === targetKey ? rendered.svg : undefined)\n if (svg === undefined) return children\n\n return (\n <div\n className={DIAGRAM_CLASS}\n data-dsh-plugin={PLUGIN_NAME}\n data-dsh-part={PART_NAME}\n {...{\n [DATA_STATE]: 'done',\n [DATA_SOURCE]: code,\n }}\n dangerouslySetInnerHTML={{ __html: svg }}\n />\n )\n}\n","/**\n * Browser entry of the diagrams plugin.\n *\n * In the chat transcript, mermaid fences render through the official\n * `conversation.chat.markdown.fence` hoc slot (`key: 'mermaid'`). Surfaces that\n * render Markdown without passing `renderCode` (such as the document preview\n * pane) fall back to the scoped DOM observer, which explicitly ignores blocks\n * already inside a `conversation.chat.markdown.fence` slot.\n * @module @linxin666/dsh-client-ui-diagrams/client\n */\n\nimport type { Context as ClientContext } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-chat/client'\nimport { FENCE_LAYER_ID, FENCE_SLOT_NAME, RENDERED_LANGUAGE } from '../core/contract.ts'\nimport { startEnhancement } from './enhance.ts'\nimport { MermaidFenceLayer } from './MermaidFenceLayer.tsx'\nimport { sharedMermaidRenderer } from './render.ts'\n\n/** Optional service declaration: slots is present in standard web shells. */\nexport const inject = {\n slots: { required: false },\n}\n\n/**\n * Register the official chat fence layer (when `ctx.slots` is available) and\n * start the document-preview fallback enhancement for the plugin lifetime.\n * @param ctx - Client context; effects dispose the slot and observer on unload.\n */\nexport function apply(ctx: ClientContext): void {\n const slots = typeof ctx.get === 'function' ? ctx.get('slots', false) : undefined\n if (slots !== undefined) {\n slots.inject(FENCE_SLOT_NAME, () => slots.register({\n name: FENCE_SLOT_NAME,\n key: RENDERED_LANGUAGE,\n id: FENCE_LAYER_ID,\n }, MermaidFenceLayer))\n }\n ctx.effect(() => startEnhancement({ renderer: sharedMermaidRenderer }), 'diagrams: render mermaid fences')\n}\n\nexport { MermaidFenceLayer, type MermaidFenceLayerProps } from './MermaidFenceLayer.tsx'\nexport { createMermaidRenderer, sharedMermaidRenderer, type MermaidRenderer, type RenderMermaidOptions } from './render.ts'\nexport { startEnhancement } from './enhance.ts'\nexport { scopesForRecords } from './enhance.ts'\nexport { findMermaidBlocks } from './blocks.ts'\nexport { sanitizeSvg } from './sanitize.ts'\nexport { mermaidTheme, shellIsDark, watchTheme } from './theme.ts'\nexport { loadRuntime, runtimeIfLoaded, type MermaidRuntime } from './runtime.ts'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyBA,MAAa,gBAAgB;;EAG7B,MAAa,kBAAkB;;EAG/B,MAAa,iBAAiB;;EAG9B,MAAa,sBAAsB,eAAe,gBAAgB;;EAGlE,MAAa,mBAAmB;;EAShC,MAAa,oBAAoB;;EAGjC,MAAa,gBAAgB;;EAG7B,MAAa,aAAa;;EAG1B,MAAa,cAAc;;EAG3B,MAAa,eAAe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,aAAa;KACb,cAAc;IAEjB,yBAAyB,EAAE,QAAQ,IAAI;GACxC,CAAA;EAEL;;;;EChGA,MAAa,SAAS,EACpB,OAAO,EAAE,UAAU,MAAM,EAC3B;;;;;;EAOA,SAAgB,MAAM,KAA0B;GAC9C,MAAM,QAAQ,OAAO,IAAI,QAAQ,aAAa,IAAI,IAAI,SAAS,KAAK,IAAI,KAAA;GACxE,IAAI,UAAU,KAAA,GACZ,MAAM,OAAO,uBAAuB,MAAM,SAAS;IACjD,MAAM;IACN,KAAK;IACL,IAAI;GACN,GAAG,iBAAiB,CAAC;GAEvB,IAAI,aAAa,iBAAiB,EAAE,UAAU,sBAAsB,CAAC,GAAG,iCAAiC;EAC3G"}
|
package/lib/index.js
CHANGED
|
@@ -63,14 +63,25 @@ function isLoopbackRequest(request) {
|
|
|
63
63
|
//#region src/host/pair-access.ts
|
|
64
64
|
/**
|
|
65
65
|
* Whether this request may enter the plugin's host routes.
|
|
66
|
-
* @param ctx - host context; may expose remoteWebUiPairing
|
|
66
|
+
* @param ctx - host context; may expose `connection` or legacy `remoteWebUiPairing`.
|
|
67
67
|
* @param request - the incoming HTTP request.
|
|
68
|
-
* @returns true for loopback, or a
|
|
68
|
+
* @returns true for loopback, an official host-admitted connection, or a paired-device cookie.
|
|
69
69
|
*/
|
|
70
70
|
function isPairedOrLoopbackAllowed(ctx, request) {
|
|
71
71
|
if (isLoopbackRequest(request)) return true;
|
|
72
|
+
if (admittedByConnection(ctx, request)) return true;
|
|
72
73
|
return lookupPairing(ctx)?.isPairedDevice(request) === true;
|
|
73
74
|
}
|
|
75
|
+
function admittedByConnection(ctx, request) {
|
|
76
|
+
try {
|
|
77
|
+
const candidate = typeof ctx.get === "function" ? ctx.get("connection", false) : ctx.connection;
|
|
78
|
+
if (candidate === void 0 || candidate === null || typeof candidate.admit !== "function") return false;
|
|
79
|
+
const admission = candidate.admit(request);
|
|
80
|
+
return admission !== void 0 && admission !== null && admission.rejection === void 0 && admission.peer !== void 0;
|
|
81
|
+
} catch {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
74
85
|
/**
|
|
75
86
|
* The pairing service, or undefined when this composition does not expose it.
|
|
76
87
|
*
|
|
@@ -102,13 +113,18 @@ function isPairingAccess(value) {
|
|
|
102
113
|
//#region src/core/contract.ts
|
|
103
114
|
/**
|
|
104
115
|
* The one place the diagram feature's external names live: the host route the
|
|
105
|
-
* browser half loads the vendored runtime from,
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
* silently disabling the
|
|
116
|
+
* browser half loads the vendored runtime from, the official chat fence slot
|
|
117
|
+
* seam, and the DOM fallback hooks the official markdown renderer exposes.
|
|
118
|
+
* Both halves and the tests read these constants, so a host upgrade that
|
|
119
|
+
* renames a hook fails one contract test instead of silently disabling the
|
|
120
|
+
* feature.
|
|
121
|
+
*
|
|
122
|
+
* In the chat transcript, official `ui-chat` (DSH 0.2.3-alpha.2+) dispatches
|
|
123
|
+
* fenced code blocks through the session-scoped `conversation.chat.markdown.fence`
|
|
124
|
+
* hoc slot keyed by lowercased language name (`mermaid`). Surfaces that still
|
|
125
|
+
* render Markdown without passing `renderCode` (such as the document preview
|
|
126
|
+
* pane) fall back to the DOM observer using the hooks below.
|
|
109
127
|
*
|
|
110
|
-
* The DOM hooks are NOT a published contract: the renderer has no code-block
|
|
111
|
-
* extension seam (see the Agent Note), so they are read off its elements.
|
|
112
128
|
* `md-code-block` is a literal class name in the renderer's JSX. The banner has
|
|
113
129
|
* two known shapes across legacy `_<local>_<hash>` and 0.2.3-alpha.2
|
|
114
130
|
* `<hash>_<local>` CSS Module class patterns: an `_infostring` element carrying
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Official `conversation.chat.markdown.fence` hoc layer for `mermaid` fences.
|
|
3
|
+
*
|
|
4
|
+
* While a message is streaming, the layer returns the inner plain code block
|
|
5
|
+
* untouched so half-written diagrams never trigger parse errors or layout
|
|
6
|
+
* churn. Once settled, it loads the vendored runtime on demand, renders and
|
|
7
|
+
* sanitizes the SVG for the current shell theme, and replaces the code block;
|
|
8
|
+
* any parse, sanitizer, or runtime failure falls back to the untouched code
|
|
9
|
+
* block.
|
|
10
|
+
* @module @linxin666/dsh-client-ui-diagrams/client/MermaidFenceLayer
|
|
11
|
+
*/
|
|
12
|
+
import { type ReactNode } from 'react';
|
|
13
|
+
import type { HocShare, PropsRuntime, SlotMap } from '@deepseek-ai/dsh-client-ui-slots/client';
|
|
14
|
+
import { type MermaidRenderer } from './render.ts';
|
|
15
|
+
import type { MermaidRuntime } from './runtime.ts';
|
|
16
|
+
/** Props delivered by the official fence slot plus optional test overrides. */
|
|
17
|
+
export type MermaidFenceLayerProps = Partial<PropsRuntime<'conversation.chat.markdown.fence'>> & Pick<PropsRuntime<'conversation.chat.markdown.fence'>, 'lang' | 'code' | 'streaming'> & HocShare<SlotMap['conversation.chat.markdown.fence']> & {
|
|
18
|
+
/** Same-origin vendor route override. */
|
|
19
|
+
runtimeUrl?: string;
|
|
20
|
+
/** Runtime loader override (tests inject fakes). */
|
|
21
|
+
load?: (url: string) => Promise<MermaidRuntime>;
|
|
22
|
+
/** Isolated renderer cache override (tests inject fresh instances). */
|
|
23
|
+
renderer?: MermaidRenderer;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Render settled `mermaid` markdown fences in the official chat flow as
|
|
27
|
+
* sanitized SVG diagrams, falling back to `children` while streaming or on any
|
|
28
|
+
* error.
|
|
29
|
+
*/
|
|
30
|
+
export declare function MermaidFenceLayer({ code, streaming, children, runtimeUrl, load, renderer, }: MermaidFenceLayerProps): ReactNode;
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* broken node behind and never throws into the caller.
|
|
24
24
|
* @module @linxin666/dsh-client-ui-diagrams/client/enhance
|
|
25
25
|
*/
|
|
26
|
+
import { type MermaidRenderer } from './render.ts';
|
|
26
27
|
import { type MermaidRuntime } from './runtime.ts';
|
|
27
28
|
/** Options for {@link startEnhancement} (tests override the loader and root). */
|
|
28
29
|
export interface EnhancementOptions {
|
|
@@ -32,12 +33,15 @@ export interface EnhancementOptions {
|
|
|
32
33
|
root?: HTMLElement;
|
|
33
34
|
/** Runtime loader override; defaults to the script-injecting loader. */
|
|
34
35
|
load?: (url: string) => Promise<MermaidRuntime>;
|
|
36
|
+
/** Shared or isolated mermaid renderer instance. */
|
|
37
|
+
renderer?: MermaidRenderer;
|
|
35
38
|
}
|
|
36
39
|
/**
|
|
37
40
|
* Map one mutation batch to the minimal DOM scopes that can hold a new fence.
|
|
38
41
|
* Removal-only records contribute nothing (removing a node never introduces a
|
|
39
|
-
* block), and records inside an already-rendered figure
|
|
40
|
-
*
|
|
42
|
+
* block), and records inside an already-rendered figure or inside an official
|
|
43
|
+
* `conversation.chat.markdown.fence` slot are ignored so writing the sanitized
|
|
44
|
+
* SVG or streaming chat fences cannot trigger fallback scans.
|
|
41
45
|
* @param records - The batch the observer delivered.
|
|
42
46
|
* @returns Connected elements to scan, deduped by identity.
|
|
43
47
|
*/
|
|
@@ -1,18 +1,28 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Browser entry of the diagrams plugin.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* In the chat transcript, mermaid fences render through the official
|
|
5
|
+
* `conversation.chat.markdown.fence` hoc slot (`key: 'mermaid'`). Surfaces that
|
|
6
|
+
* render Markdown without passing `renderCode` (such as the document preview
|
|
7
|
+
* pane) fall back to the scoped DOM observer, which explicitly ignores blocks
|
|
8
|
+
* already inside a `conversation.chat.markdown.fence` slot.
|
|
8
9
|
* @module @linxin666/dsh-client-ui-diagrams/client
|
|
9
10
|
*/
|
|
10
11
|
import type { Context as ClientContext } from '@deepseek-ai/cordis';
|
|
12
|
+
/** Optional service declaration: slots is present in standard web shells. */
|
|
13
|
+
export declare const inject: {
|
|
14
|
+
slots: {
|
|
15
|
+
required: boolean;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
11
18
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
19
|
+
* Register the official chat fence layer (when `ctx.slots` is available) and
|
|
20
|
+
* start the document-preview fallback enhancement for the plugin lifetime.
|
|
21
|
+
* @param ctx - Client context; effects dispose the slot and observer on unload.
|
|
14
22
|
*/
|
|
15
23
|
export declare function apply(ctx: ClientContext): void;
|
|
24
|
+
export { MermaidFenceLayer, type MermaidFenceLayerProps } from './MermaidFenceLayer.tsx';
|
|
25
|
+
export { createMermaidRenderer, sharedMermaidRenderer, type MermaidRenderer, type RenderMermaidOptions } from './render.ts';
|
|
16
26
|
export { startEnhancement } from './enhance.ts';
|
|
17
27
|
export { scopesForRecords } from './enhance.ts';
|
|
18
28
|
export { findMermaidBlocks } from './blocks.ts';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared mermaid renderer with LRU memoization and single-init theme tracking.
|
|
3
|
+
*
|
|
4
|
+
* Both the official `conversation.chat.markdown.fence` slot layer and the
|
|
5
|
+
* document-preview DOM fallback render through this cache so theme switches
|
|
6
|
+
* and re-mounts reuse sanitized SVG without re-parsing identical sources.
|
|
7
|
+
* @module @linxin666/dsh-client-ui-diagrams/client/render
|
|
8
|
+
*/
|
|
9
|
+
import { type MermaidRuntime } from './runtime.ts';
|
|
10
|
+
/** Options for rendering one mermaid diagram source. */
|
|
11
|
+
export interface RenderMermaidOptions {
|
|
12
|
+
/** Same-origin route serving the vendored runtime bundle. */
|
|
13
|
+
runtimeUrl?: string;
|
|
14
|
+
/** Runtime loader override (tests inject fakes). */
|
|
15
|
+
load?: (url: string) => Promise<MermaidRuntime>;
|
|
16
|
+
/** Already-loaded runtime handle, skipping the loader when provided. */
|
|
17
|
+
runtime?: MermaidRuntime;
|
|
18
|
+
}
|
|
19
|
+
/** Stateful mermaid renderer instance (shared in production, isolated in tests). */
|
|
20
|
+
export interface MermaidRenderer {
|
|
21
|
+
/** Read a previously rendered, sanitized SVG from the LRU cache, if present. */
|
|
22
|
+
getCached(source: string, theme: string): string | undefined;
|
|
23
|
+
/** Initialize the runtime once per `(runtime, theme)` pair. */
|
|
24
|
+
ensureInitialized(runtime: MermaidRuntime, theme: string): void;
|
|
25
|
+
/** Render and sanitize one mermaid source for the requested theme. */
|
|
26
|
+
render(source: string, theme: string, options?: RenderMermaidOptions): Promise<string>;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Create a mermaid renderer owning its own LRU cache and initialization state.
|
|
30
|
+
* @returns An isolated renderer instance.
|
|
31
|
+
*/
|
|
32
|
+
export declare function createMermaidRenderer(): MermaidRenderer;
|
|
33
|
+
/** Default page-wide renderer shared by the fence slot layer. */
|
|
34
|
+
export declare const sharedMermaidRenderer: MermaidRenderer;
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The one place the diagram feature's external names live: the host route the
|
|
3
|
-
* browser half loads the vendored runtime from,
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* silently disabling the
|
|
3
|
+
* browser half loads the vendored runtime from, the official chat fence slot
|
|
4
|
+
* seam, and the DOM fallback hooks the official markdown renderer exposes.
|
|
5
|
+
* Both halves and the tests read these constants, so a host upgrade that
|
|
6
|
+
* renames a hook fails one contract test instead of silently disabling the
|
|
7
|
+
* feature.
|
|
8
|
+
*
|
|
9
|
+
* In the chat transcript, official `ui-chat` (DSH 0.2.3-alpha.2+) dispatches
|
|
10
|
+
* fenced code blocks through the session-scoped `conversation.chat.markdown.fence`
|
|
11
|
+
* hoc slot keyed by lowercased language name (`mermaid`). Surfaces that still
|
|
12
|
+
* render Markdown without passing `renderCode` (such as the document preview
|
|
13
|
+
* pane) fall back to the DOM observer using the hooks below.
|
|
7
14
|
*
|
|
8
|
-
* The DOM hooks are NOT a published contract: the renderer has no code-block
|
|
9
|
-
* extension seam (see the Agent Note), so they are read off its elements.
|
|
10
15
|
* `md-code-block` is a literal class name in the renderer's JSX. The banner has
|
|
11
16
|
* two known shapes across legacy `_<local>_<hash>` and 0.2.3-alpha.2
|
|
12
17
|
* `<hash>_<local>` CSS Module class patterns: an `_infostring` element carrying
|
|
@@ -18,6 +23,12 @@
|
|
|
18
23
|
*/
|
|
19
24
|
/** Host route serving the vendored mermaid runtime (same origin, no CDN). */
|
|
20
25
|
export declare const RUNTIME_ROUTE = "/api/dsh-diagrams/vendor/mermaid.js";
|
|
26
|
+
/** Official chat markdown fence hoc slot name (DSH 0.2.3-alpha.2+). */
|
|
27
|
+
export declare const FENCE_SLOT_NAME = "conversation.chat.markdown.fence";
|
|
28
|
+
/** Stable slot occupant id for the mermaid fence layer. */
|
|
29
|
+
export declare const FENCE_LAYER_ID = "@linxin666/dsh-client-ui-diagrams/fence/mermaid";
|
|
30
|
+
/** Selector matching blocks already owned by the official chat fence slot. */
|
|
31
|
+
export declare const FENCE_SLOT_SELECTOR = "[data-slot=\"conversation.chat.markdown.fence\"]";
|
|
21
32
|
/** Class the official markdown renderer puts on every fenced code block. */
|
|
22
33
|
export declare const CODE_BLOCK_CLASS = "md-code-block";
|
|
23
34
|
/** Class-name fragment of the banner element carrying the fence infostring. */
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* Trust fence shared by plugins that expose host routes: loopback (the
|
|
3
|
+
* desktop) always passes; requests admitted by the official Host `connection`
|
|
4
|
+
* service (`admit(request)`, covering official remote-connection paired
|
|
5
|
+
* browsers and trusted hosts) pass; a legacy paired-device cookie service is
|
|
6
|
+
* also accepted when present. Without either service the fence stays
|
|
6
7
|
* loopback-only.
|
|
7
8
|
*
|
|
8
9
|
* Per-package wrappers (access.ts) call this with their own name so each
|
|
@@ -10,25 +11,33 @@
|
|
|
10
11
|
* here.
|
|
11
12
|
*/
|
|
12
13
|
import type { IncomingMessage } from 'node:http';
|
|
13
|
-
/** Structural pairing lookup (
|
|
14
|
+
/** Structural pairing lookup (legacy compatibility). */
|
|
14
15
|
interface PairingAccess {
|
|
15
16
|
isPairedDevice(request: IncomingMessage): boolean;
|
|
16
17
|
}
|
|
18
|
+
/** Structural official host connection admission lookup (`admit`). */
|
|
19
|
+
interface ConnectionAdmitAccess {
|
|
20
|
+
admit(request: IncomingMessage): {
|
|
21
|
+
readonly peer?: unknown;
|
|
22
|
+
readonly rejection?: unknown;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
17
25
|
/**
|
|
18
26
|
* Structural host-context shape: shared sources carry no @deepseek-ai
|
|
19
27
|
* dependency (the shared package must typecheck standalone), so the fence
|
|
20
|
-
* reads only the
|
|
28
|
+
* reads only the members it needs; cordis Context satisfies this.
|
|
21
29
|
* ctx.get is optional on the test harness; production Context always has it.
|
|
22
30
|
*/
|
|
23
31
|
interface LookupCtx {
|
|
24
32
|
get?(name: string, strict?: boolean): unknown;
|
|
33
|
+
connection?: ConnectionAdmitAccess;
|
|
25
34
|
remoteWebUiPairing?: PairingAccess;
|
|
26
35
|
}
|
|
27
36
|
/**
|
|
28
37
|
* Whether this request may enter the plugin's host routes.
|
|
29
|
-
* @param ctx - host context; may expose remoteWebUiPairing
|
|
38
|
+
* @param ctx - host context; may expose `connection` or legacy `remoteWebUiPairing`.
|
|
30
39
|
* @param request - the incoming HTTP request.
|
|
31
|
-
* @returns true for loopback, or a
|
|
40
|
+
* @returns true for loopback, an official host-admitted connection, or a paired-device cookie.
|
|
32
41
|
*/
|
|
33
42
|
export declare function isPairedOrLoopbackAllowed(ctx: LookupCtx, request: IncomingMessage): boolean;
|
|
34
43
|
export {};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linxin666/dsh-client-ui-diagrams",
|
|
3
3
|
"description": "Mermaid diagram rendering for the DSH Web GUI: fenced mermaid blocks in the chat transcript and the document preview are rendered in place as SVG, from a runtime the host serves on demand.",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.23",
|
|
5
5
|
"icon": "icon.svg",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
|
@@ -22,28 +22,40 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dsh": {
|
|
24
24
|
"engines": {
|
|
25
|
-
"dsh": ">=0.2.3-alpha.
|
|
25
|
+
"dsh": ">=0.2.3-alpha.4"
|
|
26
26
|
},
|
|
27
27
|
"bundle": {
|
|
28
28
|
"patch": "./cordis.patch.yml"
|
|
29
29
|
},
|
|
30
30
|
"client": {
|
|
31
31
|
"inject": [
|
|
32
|
-
"@deepseek-ai/dsh-client-locale"
|
|
32
|
+
"@deepseek-ai/dsh-client-locale",
|
|
33
|
+
"@deepseek-ai/dsh-client-ui-renderer",
|
|
34
|
+
"@deepseek-ai/dsh-client-ui-slots"
|
|
33
35
|
],
|
|
34
36
|
"platform": "web"
|
|
35
37
|
}
|
|
36
38
|
},
|
|
37
39
|
"peerDependencies": {
|
|
38
|
-
"@deepseek-ai/dsh": ">=0.2.3-alpha.
|
|
40
|
+
"@deepseek-ai/dsh": ">=0.2.3-alpha.4",
|
|
41
|
+
"react": "^19.3.1"
|
|
39
42
|
},
|
|
40
43
|
"devDependencies": {
|
|
41
|
-
"@deepseek-ai/cordis": "~4.2.0-alpha.
|
|
42
|
-
"@deepseek-ai/dsh-client-locale": "^0.2.3-alpha.
|
|
43
|
-
"@deepseek-ai/dsh-
|
|
44
|
+
"@deepseek-ai/cordis": "~4.2.0-alpha.3",
|
|
45
|
+
"@deepseek-ai/dsh-client-locale": "^0.2.3-alpha.4",
|
|
46
|
+
"@deepseek-ai/dsh-client-ui-chat": "^0.2.3-alpha.4",
|
|
47
|
+
"@deepseek-ai/dsh-client-ui-renderer": "^0.2.3-alpha.4",
|
|
48
|
+
"@deepseek-ai/dsh-client-ui-slots": "^0.2.3-alpha.4",
|
|
49
|
+
"@deepseek-ai/dsh-host-webserver": "^0.2.3-alpha.4",
|
|
50
|
+
"@testing-library/dom": "^10.4.1",
|
|
51
|
+
"@testing-library/react": "^16.3.3",
|
|
44
52
|
"@types/node": "^22.20.0",
|
|
53
|
+
"@types/react": "~19.3.2",
|
|
54
|
+
"@types/react-dom": "~19.3.0",
|
|
45
55
|
"jsdom": "29.1.1",
|
|
46
56
|
"mermaid": "^12.2.0",
|
|
57
|
+
"react": "^19.3.1",
|
|
58
|
+
"react-dom": "^19.3.1",
|
|
47
59
|
"tsdown": "0.22.2",
|
|
48
60
|
"typescript": "~5.7.2",
|
|
49
61
|
"vite-tsconfig-paths": "^6.1.1",
|