@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.2

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.
Files changed (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,106 @@
1
+ /** Shared rich text for GenUI labels and content. Data values stay unchanged. */
2
+ import { createElement, useLayoutEffect, useRef, type ReactNode } from 'react'
3
+ import katex from 'katex'
4
+ import css from './GenuiBlock.module.css'
5
+ import { safeHref } from './genui-runtime/value-utils.ts'
6
+
7
+ /** KaTeX owns this span's children; React owns the span and its lifecycle.
8
+ * The host's ui-primitives already supplies KaTeX CSS/fonts, including embeds. */
9
+ function InlineMath({ source, display }: { source: string; display: boolean }) {
10
+ const ref = useRef<HTMLSpanElement>(null)
11
+ useLayoutEffect(() => {
12
+ if (ref.current === null) return
13
+ katex.render(source, ref.current, {
14
+ displayMode: display, throwOnError: false, trust: false,
15
+ maxExpand: 1000, maxSize: 20, output: 'htmlAndMathml',
16
+ })
17
+ }, [source, display])
18
+ return createElement('span', { ref, className: css.inlineMath })
19
+ }
20
+
21
+ // Code is literal. TeX tokens are opaque to emphasis/link parsing; the other
22
+ // rich-text tokens recurse so **$x$** and ==\\(x\\)== work without nested DOM roots.
23
+ // A real newline in the string stays a REAL newline in the DOM — not a `<br>`.
24
+ // A `<br>` paints a visual break but contributes nothing to `textContent`, so
25
+ // selecting and copying a multi-line cell yielded one run-on line: a pasted
26
+ // `python - <<'PY' … PY` heredoc lost its line structure and could no longer
27
+ // run. Real newlines survive both the paint and the copy path; containers that
28
+ // can carry them declare `white-space: pre-line` (prose) or `pre-wrap` (code).
29
+ // No HTML parsing happens here, only the model's `\n`.
30
+ const INLINE = /(?<!`)`[^`\n]+`(?!`)|\\\\|\\\$|(?<![\\$])\$\$(?:\\.|[^\\])*?\$\$|\\\[(?:\\(?!\])[^]|[^\\])*?\\\]|\\\((?:\\(?!\))[^]|[^\\])*?\\\)|(?<![\\$])\$(?!\s|\$)(?:\\.|[^$\\\n])+(?<!\s)\$(?!\d|\$)|\*\*[\s\S]+?\*\*|==[\s\S]+?==|\[[^\]\n]+\]\([^)\s]+\)|\r?\n/g
31
+ const FENCE_MARKER = /`{3,}|~{3,}/g
32
+
33
+ export function hasInlineMarkup(text: string): boolean {
34
+ return typeof text === 'string' && /[`*=$\\\n\r]|\[/.test(text)
35
+ }
36
+
37
+ /** Render safe phrasing content, usable in headings, buttons and labels too. */
38
+ export function renderInline(text: string, allowLinks = true, depth = 0): ReactNode {
39
+ if (typeof text !== 'string' || text === '' || !hasInlineMarkup(text) || depth >= 8) return text
40
+ const segments: ReactNode[] = []
41
+ let fenceEnd = 0
42
+ for (const opening of text.matchAll(FENCE_MARKER)) {
43
+ const openingStart = opening.index ?? 0
44
+ if (openingStart < fenceEnd) continue
45
+ const marker = opening[0]
46
+ const contentStart = openingStart + marker.length
47
+ let closingEnd: number | undefined
48
+ for (const candidate of text.slice(contentStart).matchAll(FENCE_MARKER)) {
49
+ if (candidate[0][0] === marker[0] && candidate[0].length >= marker.length) {
50
+ closingEnd = contentStart + (candidate.index ?? 0) + candidate[0].length
51
+ break
52
+ }
53
+ }
54
+ if (openingStart > fenceEnd) segments.push(renderInline(text.slice(fenceEnd, openingStart), allowLinks, depth))
55
+ // 围栏及其中的代码、换行和行内标记都保持原文。
56
+ fenceEnd = closingEnd ?? text.length
57
+ segments.push(text.slice(openingStart, fenceEnd))
58
+ if (closingEnd === undefined) break
59
+ }
60
+ if (segments.length > 0) {
61
+ if (fenceEnd < text.length) segments.push(renderInline(text.slice(fenceEnd), allowLinks, depth))
62
+ return segments
63
+ }
64
+ const out: ReactNode[] = []
65
+ let last = 0
66
+ let key = 0
67
+ for (const match of text.matchAll(INLINE)) {
68
+ const index = match.index ?? 0
69
+ const token = match[0]
70
+ if (index > last) out.push(text.slice(last, index))
71
+ if (token === '\n' || token === '\r\n') {
72
+ // Keep the newline character itself: it is what `textContent`,
73
+ // `Selection.toString()` and the clipboard carry. `pre-line`/`pre-wrap`
74
+ // on the owning container turns it into a visible line break.
75
+ out.push('\n')
76
+ } else if (token.startsWith('`')) {
77
+ out.push(createElement('code', { key: key++, className: css.inlineCode }, token.slice(1, -1)))
78
+ } else if (token === '\\$' || token === '\\\\') {
79
+ // Escaped markers: the regex consumed the backslash to keep the literal
80
+ // character from opening math/emphasis, so render it without the escape.
81
+ out.push(token.slice(1))
82
+ } else if (token.startsWith('$') || token.startsWith('\\(') || token.startsWith('\\[')) {
83
+ const display = token.startsWith('$$') || token.startsWith('\\[')
84
+ const width = token.startsWith('$') && !display ? 1 : 2
85
+ out.push(createElement(InlineMath, { key: key++, source: token.slice(width, -width), display }))
86
+ } else if (token.startsWith('**') || token.startsWith('==')) {
87
+ const bold = token.startsWith('**')
88
+ out.push(createElement(bold ? 'strong' : 'mark', {
89
+ key: key++, className: bold ? css.inlineStrong : css.inlineMark,
90
+ }, renderInline(token.slice(2, -2), allowLinks, depth + 1)))
91
+ } else {
92
+ const parts = /^\[([^\]\n]+)\]\(([^)\s]+)\)$/.exec(token)
93
+ if (parts === null) {
94
+ out.push(token)
95
+ } else {
96
+ const href = safeHref(parts[2])
97
+ out.push(href === undefined || !allowLinks ? renderInline(parts[1]!, false, depth + 1) : createElement('a', {
98
+ key: key++, className: css.inlineLink, href, target: '_blank', rel: 'noreferrer noopener',
99
+ }, renderInline(parts[1]!, false, depth + 1)))
100
+ }
101
+ }
102
+ last = index + token.length
103
+ }
104
+ if (last < text.length) out.push(text.slice(last))
105
+ return out.length === 0 ? text : out
106
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Interaction-state store: durable per-block GenUI interaction state
3
+ * (radio answers, checkbox groups, submit lock, input/textarea values) in
4
+ * localStorage.
5
+ *
6
+ * LOCAL-FIRST persistence: a ```dsh-ui block's interactive state survives
7
+ * page refresh and session reopen because it is keyed by
8
+ * `session + block slot + content fingerprint` — replaying the same message
9
+ * (same content) restores the exact state, while NEW content (换题, edited
10
+ * spec) gets a fresh key and thus a clean slate. Different messages never
11
+ * share state because their content fingerprints differ.
12
+ *
13
+ * Bounded: at most MAX_BLOCKS entries, LRU-evicted on write; each block's
14
+ * payload is small (answer maps + a few field values).
15
+ * @module @changfenhuang/dsh-genui/client/interaction-store
16
+ */
17
+
18
+ /** Durable state of one UI block. */
19
+ export interface BlockInteractionState {
20
+ /** group → chosen option label (radio aggregation answers). */
21
+ answers?: Record<string, string>
22
+ /** group → chosen option labels (checkbox aggregation answers). Empty arrays
23
+ * are retained so an explicitly cleared group wins over `checked` defaults
24
+ * after refresh. */
25
+ multiAnswers?: Record<string, string[]>
26
+ /** True after a local grading: the paper stays graded across refresh. */
27
+ locked?: boolean
28
+ /** field id → current value (input/textarea with an `id`). */
29
+ fields?: Record<string, string>
30
+ }
31
+
32
+ const STORE_KEY = 'dsh.genui.interaction'
33
+ /** Max tracked blocks; LRU eviction keeps the store bounded. */
34
+ const MAX_BLOCKS = 200
35
+
36
+ interface StoreShape {
37
+ /** Block keys in most-recently-written order (index 0 = newest). */
38
+ order: string[]
39
+ blocks: Record<string, BlockInteractionState>
40
+ }
41
+
42
+ function emptyStore(): StoreShape {
43
+ return { order: [], blocks: {} }
44
+ }
45
+
46
+ function readStore(): StoreShape {
47
+ try {
48
+ const raw = localStorage.getItem(STORE_KEY)
49
+ if (raw === null) return emptyStore()
50
+ const parsed = JSON.parse(raw) as Partial<StoreShape>
51
+ if (!Array.isArray(parsed.order) || typeof parsed.blocks !== 'object' || parsed.blocks === null) {
52
+ return emptyStore()
53
+ }
54
+ return { order: parsed.order.filter(k => typeof k === 'string'), blocks: parsed.blocks as Record<string, BlockInteractionState> }
55
+ } catch {
56
+ return emptyStore()
57
+ }
58
+ }
59
+
60
+ function writeStore(store: StoreShape): void {
61
+ try {
62
+ localStorage.setItem(STORE_KEY, JSON.stringify(store))
63
+ } catch {
64
+ // Quota / privacy-mode failures are non-fatal: interaction stays live
65
+ // in memory, only the persistence is lost.
66
+ }
67
+ }
68
+
69
+ /** Load a block's durable state, or null when absent/corrupt. */
70
+ export function loadBlockState(stateKey: string): BlockInteractionState | null {
71
+ if (stateKey === '') return null
72
+ const store = readStore()
73
+ return store.blocks[stateKey] ?? null
74
+ }
75
+
76
+ /** Save a block's durable state (LRU: touched keys move to the front). */
77
+ export function saveBlockState(stateKey: string, state: BlockInteractionState): void {
78
+ if (stateKey === '') return
79
+ const store = readStore()
80
+ const order = store.order.filter(k => k !== stateKey)
81
+ order.unshift(stateKey)
82
+ const blocks = { ...store.blocks, [stateKey]: state }
83
+ while (order.length > MAX_BLOCKS) {
84
+ const evicted = order.pop()
85
+ if (evicted !== undefined) delete blocks[evicted]
86
+ }
87
+ writeStore({ order, blocks })
88
+ }
89
+
90
+ /** Forget a block's durable state (e.g. after a reset-to-empty). */
91
+ export function clearBlockState(stateKey: string): void {
92
+ if (stateKey === '') return
93
+ const store = readStore()
94
+ if (!(stateKey in store.blocks)) return
95
+ const blocks = { ...store.blocks }
96
+ delete blocks[stateKey]
97
+ writeStore({ order: store.order.filter(k => k !== stateKey), blocks })
98
+ }
99
+
100
+ /**
101
+ * Deterministic content fingerprint (djb2) for a block's raw fence body.
102
+ * Two render passes of the SAME content share a fingerprint (state restores);
103
+ * edited content gets a new one (fresh state). Not a security hash — the
104
+ * store only uses it for equality/identity.
105
+ */
106
+ export function fingerprint(raw: string): string {
107
+ let h = 5381
108
+ for (let i = 0; i < raw.length; i++) {
109
+ h = ((h << 5) + h + raw.charCodeAt(i)) >>> 0
110
+ }
111
+ return h.toString(36)
112
+ }
113
+
114
+ /** Build the durable state key for a fence block: session + fence slot + content fingerprint. */
115
+ export function fenceStateKey(sessionId: string, fenceKey: number | string, raw: string): string {
116
+ return `f:${sessionId}:${String(fenceKey)}:${fingerprint(raw)}`
117
+ }
118
+
119
+ /** Build the durable state key for a panel publish (content-keyed). */
120
+ export function panelStateKey(sessionId: string, raw: string): string {
121
+ return `p:${sessionId}:${fingerprint(raw)}`
122
+ }
123
+
124
+ /** Build the durable state key for a render_ui tool card (call-keyed). */
125
+ export function toolStateKey(sessionId: string, callId: string): string {
126
+ return `t:${sessionId}:${callId}`
127
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Mermaid render engine — the HEAVY half. This module imports mermaid and is
3
+ * bundled ONLY into the lazy asset bundle `lib/assets/mermaid.js`, loaded on
4
+ * demand by the mermaid-lazy loader when a spec contains a `mermaid` node;
5
+ * the main client bundle stays small.
6
+ *
7
+ * Whitelist: only a fixed set of diagram kinds render; anything else throws
8
+ * so the caller shows its fallback — except undeclared flowchart bodies
9
+ * (model-generated sources missing the `graph TD` header line), which get
10
+ * the declaration prepended via ensureFlowchartKind and render normally.
11
+ * mermaid runs client-side with its own sanitizer; we additionally refuse `securityLevel: 'loose'`-style inputs by
12
+ * only initializing with the strict default, AND we re-check the rendered SVG
13
+ * before it is injected (see `assertSafeSvg` in mermaid-safe): the injection
14
+ * point is the only place in GenUI that uses `dangerouslySetInnerHTML`, so
15
+ * the last line of defense lives here, not inside mermaid.
16
+ * @module @changfenhuang/dsh-genui/client/mermaid-core
17
+ */
18
+ import { assertSafeSvg, ensureFlowchartKind, repairMermaidSource } from './mermaid-safe.ts'
19
+
20
+ let mermaidPromise: Promise<typeof import('mermaid')> | null = null
21
+
22
+ /** Monotonic render id (replaces Math.random): no collisions, no entropy. */
23
+ let renderSeq = 0
24
+
25
+ function loadMermaid(): Promise<typeof import('mermaid')> {
26
+ mermaidPromise ??= import('mermaid').then(async m => {
27
+ const api = m.default
28
+ // Theme the diagram from the HOST tokens instead of a built-in mermaid
29
+ // palette: the stock themes render grey boxes with sharp corners, dark
30
+ // strokes and their own font, which sat next to our components as a
31
+ // visibly foreign object. `base` + themeVariables is the supported way to
32
+ // drive every colour (the dark/light branch is gone with it).
33
+ const token = (name: string, fallback: string): string => {
34
+ if (typeof document === 'undefined') return fallback
35
+ const value = getComputedStyle(document.body).getPropertyValue(name).trim()
36
+ return value === '' ? fallback : value
37
+ }
38
+ api.initialize({
39
+ startOnLoad: false,
40
+ // Strict default: mermaid escapes/sanitizes; we never enable htmlLabels.
41
+ securityLevel: 'strict',
42
+ theme: 'base',
43
+ themeVariables: {
44
+ background: 'transparent',
45
+ fontFamily: 'inherit',
46
+ fontSize: '13px',
47
+ primaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
48
+ primaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
49
+ primaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
50
+ secondaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
51
+ secondaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
52
+ secondaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
53
+ tertiaryColor: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
54
+ tertiaryTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
55
+ tertiaryBorderColor: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
56
+ mainBkg: token('--dsw-alias-bg-layer-2', '#2c2c2e'),
57
+ nodeBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
58
+ nodeTextColor: token('--dsw-alias-label-primary', '#e6e6e6'),
59
+ lineColor: token('--dsw-alias-label-tertiary', '#8a8a92'),
60
+ textColor: token('--dsw-alias-label-primary', '#e6e6e6'),
61
+ edgeLabelBackground: 'transparent',
62
+ clusterBkg: 'transparent',
63
+ clusterBorder: token('--dsw-alias-border-l2', 'rgba(255,255,255,0.12)'),
64
+ titleColor: token('--dsw-alias-label-primary', '#e6e6e6'),
65
+ },
66
+ // Sharp corners and heavy strokes were the loudest mismatch; the radius
67
+ // is set here because mermaid emits plain <rect> geometry.
68
+ themeCSS: [
69
+ '.node rect, .node polygon, .node circle, .node ellipse { rx: 8px; ry: 8px; stroke-width: 1px; }',
70
+ '.cluster rect { rx: 10px; ry: 10px; }',
71
+ '.edgePath .path { stroke-width: 1.4px; }',
72
+ '.label { color: inherit; }',
73
+ ].join(' '),
74
+ // Fail loudly: with suppressErrorRendering false (the default) mermaid
75
+ // renders an "error" diagram on parse/draw failure — the caller then
76
+ // receives a normal-looking SVG whose text is the raw engine error
77
+ // ("Syntax error in text / mermaid version …"), which lands on the page
78
+ // with no exception ever thrown. Suppressing the error diagram makes
79
+ // every failure throw so the caller shows its own fallback instead.
80
+ suppressErrorRendering: true,
81
+ })
82
+ return m
83
+ })
84
+ return mermaidPromise
85
+ }
86
+
87
+ /** Diagram kinds allowed through to the renderer. */
88
+ const ALLOWED_KINDS = [
89
+ 'flowchart', 'graph', 'sequenceDiagram', 'classDiagram', 'stateDiagram',
90
+ 'gantt', 'pie', 'erDiagram', 'journey', 'gitGraph',
91
+ ]
92
+
93
+ /** One render attempt into a private container. mermaid ≥ 11.16 resolves the
94
+ * diagram element via `document.body` while drawing flowcharts
95
+ * (`getDiagramElement`), so a DETACHED container makes every flowchart/graph
96
+ * render throw on an empty d3 selection ("Cannot read properties of null").
97
+ * The container is therefore mounted off-screen for the duration of the
98
+ * render — NOT `display:none`, which zeroes label measurements and makes
99
+ * dagre fail with "Could not find a suitable point" — and removed when done. */
100
+ async function renderInto(m: typeof import('mermaid'), id: string, code: string, container: HTMLDivElement): Promise<string> {
101
+ container.style.position = 'fixed'
102
+ container.style.left = '-100000px'
103
+ container.style.top = '0'
104
+ container.style.margin = '0'
105
+ document.body?.appendChild(container)
106
+ try {
107
+ const { svg } = await m.default.render(id, code, container)
108
+ assertSafeSvg(svg)
109
+ return svg
110
+ } finally {
111
+ container.remove()
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Render mermaid source to an SVG string.
117
+ * @param code - the mermaid diagram source.
118
+ * @returns the rendered SVG markup (verified free of script/event handlers).
119
+ * @throws when the kind is not whitelisted, rendering fails, or the output
120
+ * fails the sanitization check.
121
+ */
122
+ export async function renderMermaid(code: string): Promise<string> {
123
+ let trimmed = code.trim()
124
+ const firstLine = trimmed.split('\n', 1)[0] ?? ''
125
+ let kind = /^([A-Za-z]+)/.exec(firstLine)?.[1] ?? ''
126
+ if (!ALLOWED_KINDS.includes(kind)) {
127
+ // Lenient: model-generated sources frequently omit the mandatory
128
+ // diagram-type declaration line (`A --> B` with no leading
129
+ // `graph TD`). Detect a flowchart body by its edge arrows and prepend
130
+ // the declaration instead of throwing straight to the raw-source
131
+ // fallback; genuinely unclassifiable input still fails as before.
132
+ const lenient = ensureFlowchartKind(trimmed)
133
+ if (lenient !== trimmed) {
134
+ trimmed = lenient
135
+ kind = 'graph'
136
+ }
137
+ }
138
+ if (!ALLOWED_KINDS.includes(kind)) {
139
+ throw new Error(`mermaid kind '${kind}' is not allowed`)
140
+ }
141
+ const m = await loadMermaid()
142
+ const container = document.createElement('div')
143
+ try {
144
+ try {
145
+ return await renderInto(m, `genui-mermaid-${renderSeq++}`, trimmed, container)
146
+ } catch (error) {
147
+ // Retry once with the label-repair pass; a repaired source rendering
148
+ // successfully beats a syntax-error fallback for the same content.
149
+ const repaired = repairMermaidSource(trimmed)
150
+ if (repaired !== trimmed) {
151
+ return await renderInto(m, `genui-mermaid-${renderSeq++}`, repaired, container)
152
+ }
153
+ throw error
154
+ }
155
+ } finally {
156
+ container.remove()
157
+ }
158
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Runtime loader for the mermaid engine. The heavy mermaid bundle ships as a
3
+ * separate asset (`lib/assets/mermaid.js`, served by the plugin's own HTTP
4
+ * route) and is fetched ONLY when a spec contains a `mermaid` node — the
5
+ * main client bundle stays small and most conversations never download
6
+ * mermaid at all. On a host that does not serve the asset (older harness) the
7
+ * load rejects and the MermaidNode shows its plain-source fallback.
8
+ *
9
+ * The pure source utilities stay statically exported from mermaid-safe so
10
+ * tests (and any consumer) can use them without the engine.
11
+ * @module @changfenhuang/dsh-genui/client/mermaid-lazy
12
+ */
13
+ import { loadGenuiAsset } from './asset-loader.ts'
14
+ export { assertSafeSvg, ensureFlowchartKind, repairMermaidSource } from './mermaid-safe.ts'
15
+
16
+ /** The engine surface registered by the mermaid asset bundle. */
17
+ interface MermaidAssetApi {
18
+ renderMermaid: (code: string) => Promise<string>
19
+ }
20
+
21
+ /**
22
+ * Render mermaid source to an SVG string (engine loaded on demand).
23
+ * @param code - the mermaid diagram source.
24
+ * @returns the rendered SVG markup (verified free of script/event handlers).
25
+ * @throws when the asset cannot load, the kind is not whitelisted, rendering
26
+ * fails, or the output fails the sanitization check.
27
+ */
28
+ export async function renderMermaid(code: string): Promise<string> {
29
+ const api = await loadGenuiAsset<MermaidAssetApi>('mermaid')
30
+ return api.renderMermaid(code)
31
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Pure mermaid source utilities — no mermaid import, so this module can ship
3
+ * in the main client bundle while the heavy mermaid engine lives in a lazy
4
+ * asset bundle (`lib/assets/mermaid.js`, loaded on demand by mermaid-lazy).
5
+ * @module @changfenhuang/dsh-genui/client/mermaid-safe
6
+ */
7
+
8
+ /** Reject any rendered SVG that carries script, event-handler attributes, or
9
+ * `javascript:` URIs. Under mermaid's strict security level a legitimate
10
+ * diagram never contains these, so a hit means the sanitizer failed (a
11
+ * mermaid regression or a bypass): throw and let the caller show the plain
12
+ * source fallback instead of injecting the markup. Cheap linear scan over
13
+ * the SVG string; happens once per diagram.
14
+ */
15
+ const SVG_INJECTION = /<script|[\s"']on[a-z]+\s*=|javascript:/i
16
+
17
+ /** Throws when `svg` carries script, event-handler attributes, or
18
+ * `javascript:` URIs. Exported for tests; `renderMermaid` is the only caller
19
+ * in production. */
20
+ export function assertSafeSvg(svg: string): void {
21
+ if (SVG_INJECTION.test(svg)) {
22
+ throw new Error('mermaid output failed the sanitization check; refusing to render')
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Best-effort repair of common model-authored label mistakes in graph /
28
+ * flowchart sources, used only when the original fails to render:
29
+ * - drop backticks — lexically illegal in mermaid labels (models embed
30
+ * ```dsh-ui style fences, which break the parser with "Lexical error");
31
+ * - strip `<br/>` tags, which require htmlLabels (never enabled here);
32
+ * - quote unquoted node labels containing CJK, spaces, or other characters
33
+ * mermaid's bare-label grammar rejects (observed live: `A[模型生成 spec]`).
34
+ * Conservative by design: already-quoted labels, plain ASCII labels without
35
+ * spaces, and non-flowchart kinds are left untouched (apart from the
36
+ * backtick/`<br/>` sanitation above, which is harmless everywhere in a
37
+ * flowchart).
38
+ *
39
+ * Labeled-edge spans (`-- 文本 -->`, `== 文本 ==>`, `-. 文本 .->`) are free
40
+ * text and must never be quoted: wrapping them breaks the parser
41
+ * ("Expecting 'LINK' … got 'STR'"), observed live with
42
+ * `H -- 否(流式中) --> J`. Each span is swapped for a bracket-free
43
+ * placeholder before quoting and restored verbatim afterwards, so the quote
44
+ * pass can neither corrupt it nor be thrown off by inserted quotes
45
+ * elsewhere on the line.
46
+ *
47
+ * Pipe-style edge labels (`-->|文本|`) are the opposite: an UNQUOTED pipe
48
+ * label containing `[` or `]` breaks the parser ("Parse error", observed
49
+ * live with `-->|6. 用户交互 → [genui-action]|`) because the brackets are
50
+ * node grammar. Quoting the label text is display-neutral (mermaid renders
51
+ * `-->|"文本"|` without the quotes) and parses. These spans are masked too,
52
+ * so the node-label quote pass below cannot reach inside them and produce
53
+ * nested quotes, and restored last.
54
+ */
55
+ export function repairMermaidSource(code: string): string {
56
+ const kind = /^([A-Za-z]+)/.exec(code.trim())?.[1] ?? ''
57
+ if (kind !== 'graph' && kind !== 'flowchart') return code
58
+ const cleaned = code.replace(/`/g, '').replace(/<br\s*\/?>/gi, ' ')
59
+ // A labeled edge is `--`/`==`/`-.` (not immediately `-->`/`==>`), a label
60
+ // made of non-dash chars or single dashes (never `--`, which would start a
61
+ // new edge), then the arrow. `[ \t]*` — never newlines — keeps the span on
62
+ // one line.
63
+ const EDGE = /(--|==|-\.)(?!>)[ \t]*([^-\n]|-(?!--))*?[ \t]*(-->|==>|\.->)/g
64
+ const spans: string[] = []
65
+ const masked = cleaned.replace(EDGE, (span) => {
66
+ spans.push(span)
67
+ return `\uE000${spans.length - 1}\uE001`
68
+ })
69
+ // Pipe label spans whose text carries at least one bracket char. The
70
+ // bracket requirement keeps legitimate pipe characters inside node labels
71
+ // (e.g. `A[a | b | c]`) untouched. Already-quoted labels (any `"` in the
72
+ // text) are left alone. The placeholder must be bracket-free so the
73
+ // node-label quote pass below cannot match inside it.
74
+ const PIPE = /\|([^|\n]*[\[\]][^|\n]*)\|/g
75
+ const pipeSpans: string[] = []
76
+ const maskedPipes = masked.replace(PIPE, (whole, text: string) => {
77
+ const trimmed = text.trim()
78
+ if (trimmed.includes('"')) return whole
79
+ pipeSpans.push(trimmed)
80
+ return `\uE002${pipeSpans.length - 1}\uE003`
81
+ })
82
+ const quoted = maskedPipes.replace(
83
+ /([\[\(])([^\[\]\(\)\{\}"'\n]*)([\]\)])/g,
84
+ (whole, open: string, label: string, close: string) => {
85
+ const trimmed = label.trim()
86
+ if (trimmed === '') return whole
87
+ if (/[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/.test(trimmed) || /\s/.test(trimmed)) {
88
+ return `${open}"${trimmed}"${close}`
89
+ }
90
+ return whole
91
+ },
92
+ )
93
+ return quoted
94
+ .replace(/\uE000(\d+)\uE001/g, (whole, i: string) => spans[Number(i)] ?? whole)
95
+ .replace(/\uE002(\d+)\uE003/g, (whole, i: string) => {
96
+ const text = pipeSpans[Number(i)]
97
+ return text === undefined ? whole : `|"${text}"|`
98
+ })
99
+ }
100
+
101
+ /** Flowchart edge arrows. The negative lookahead on `-->(?!>)` keeps
102
+ * sequence-diagram message arrows (`-->>`) from matching. */
103
+ const FLOWCHART_EDGE = /-->(?!>)|==>|-\.->/
104
+
105
+ /**
106
+ * Lenient repair for sources that omit the mandatory diagram-type
107
+ * declaration line — the #1 failure mode of model-generated mermaid (chat
108
+ * assistants routinely emit `A --> B` without the leading `graph TD`).
109
+ *
110
+ * When the first token is not an already-declared `graph`/`flowchart` kind
111
+ * but the body contains flowchart edge arrows, prepend `graph TD` so the
112
+ * diagram renders instead of tripping the kind gate. Anything else — an
113
+ * explicitly declared kind, a sequence/gantt/pie body (no flowchart edges),
114
+ * or plain text — is returned unchanged: we never guess at the diagram type.
115
+ */
116
+ export function ensureFlowchartKind(code: string): string {
117
+ const trimmed = code.trim()
118
+ const kind = /^([A-Za-z]+)/.exec(trimmed)?.[1] ?? ''
119
+ if (kind === 'graph' || kind === 'flowchart') return code
120
+ if (!FLOWCHART_EDGE.test(trimmed)) return code
121
+ return `graph TD\n${trimmed}`
122
+ }