@hyprnos/dsh-remote-plugin 0.0.0-stage → 0.8.8

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/README.en.md +61 -0
  2. package/README.md +60 -2
  3. package/apk/dsh-remote.apk +0 -0
  4. package/approval-summary.mjs +115 -0
  5. package/client.js +197 -0
  6. package/cordis.patch.yml +5 -0
  7. package/doctor-skill.mjs +99 -0
  8. package/doctor-target.mjs +24 -0
  9. package/file-delivery.mjs +84 -0
  10. package/gateway-stats.cjs +501 -0
  11. package/gateway.cjs +8451 -0
  12. package/index.mjs +1784 -0
  13. package/insights.mjs +111 -0
  14. package/market.mjs +86 -0
  15. package/package.json +71 -4
  16. package/peak-reminders.mjs +50 -0
  17. package/plugin-center.mjs +777 -0
  18. package/plugin-transaction.mjs +300 -0
  19. package/public/activity.js +188 -0
  20. package/public/admin.html +820 -0
  21. package/public/admin.js +1167 -0
  22. package/public/announcement-forms.js +89 -0
  23. package/public/announcements.json +464 -0
  24. package/public/app.js +8826 -0
  25. package/public/approval-records.js +301 -0
  26. package/public/approval-summary.js +78 -0
  27. package/public/build.json +5 -0
  28. package/public/cache-upgrade.js +51 -0
  29. package/public/chat-copy.js +59 -0
  30. package/public/chat-files.js +87 -0
  31. package/public/desktop/desktop.css +816 -0
  32. package/public/desktop/desktop.html +871 -0
  33. package/public/desktop/desktop.js +4548 -0
  34. package/public/desktop/i18n.js +85 -0
  35. package/public/diagnostics.js +203 -0
  36. package/public/doctor-entry.js +94 -0
  37. package/public/doctor.css +205 -0
  38. package/public/doctor.js +769 -0
  39. package/public/donate.png +0 -0
  40. package/public/e2ee-transport.js +219 -0
  41. package/public/extensions.css +109 -0
  42. package/public/extensions.js +215 -0
  43. package/public/file-inbox.css +66 -0
  44. package/public/file-inbox.js +289 -0
  45. package/public/genui.css +8 -0
  46. package/public/genui.js +254 -0
  47. package/public/history.js +304 -0
  48. package/public/i18n.js +57 -0
  49. package/public/icon.svg +12 -0
  50. package/public/image-cache.js +141 -0
  51. package/public/image-preview.js +290 -0
  52. package/public/index.html +1548 -0
  53. package/public/insights.css +28 -0
  54. package/public/insights.js +290 -0
  55. package/public/jsqr.min.js +10104 -0
  56. package/public/lan-discovery.js +94 -0
  57. package/public/link-check.js +109 -0
  58. package/public/manifest.webmanifest +16 -0
  59. package/public/md.js +333 -0
  60. package/public/morphicons-init.js +41 -0
  61. package/public/motion.js +557 -0
  62. package/public/network.js +100 -0
  63. package/public/onboarding.css +36 -0
  64. package/public/onboarding.js +253 -0
  65. package/public/operations.js +141 -0
  66. package/public/permission-presets.js +159 -0
  67. package/public/plugin-center.css +120 -0
  68. package/public/plugin-center.js +666 -0
  69. package/public/plugin-icon.svg +5 -0
  70. package/public/plugin.html +68 -0
  71. package/public/plugin.js +211 -0
  72. package/public/qrcode.min.js +2297 -0
  73. package/public/relay-autopair.js +251 -0
  74. package/public/relay-devices.js +80 -0
  75. package/public/relay-settings.css +24 -0
  76. package/public/relay-settings.js +194 -0
  77. package/public/remote-state.js +27 -0
  78. package/public/remote-ui.css +148 -0
  79. package/public/remote-ui.js +243 -0
  80. package/public/session-deck.css +79 -0
  81. package/public/session-deck.js +180 -0
  82. package/public/session-presets.js +47 -0
  83. package/public/setup.css +18 -0
  84. package/public/setup.js +213 -0
  85. package/public/sha256.js +119 -0
  86. package/public/skills.css +81 -0
  87. package/public/skills.js +202 -0
  88. package/public/skins/blue-fish/DESIGN.md +24 -0
  89. package/public/skins/blue-fish/face.png +0 -0
  90. package/public/skins/blue-fish/icon-blush.png +0 -0
  91. package/public/skins/blue-fish/icon-sleep.png +0 -0
  92. package/public/skins/blue-fish/icon-smile.png +0 -0
  93. package/public/skins/blue-fish/icon-star.png +0 -0
  94. package/public/skins/blue-fish/icon-wink.png +0 -0
  95. package/public/skins/blue-fish/icon.png +0 -0
  96. package/public/skins/blue-fish/mascot.png +0 -0
  97. package/public/skins/blue-fish/pattern.png +0 -0
  98. package/public/skins/blue-fish/preview.html +12 -0
  99. package/public/skins/blue-fish/skin.css +122 -0
  100. package/public/skins/blue-fish/sparkles.svg +18 -0
  101. package/public/skins/bocchi/DESIGN.md +99 -0
  102. package/public/skins/bocchi/face.png +0 -0
  103. package/public/skins/bocchi/grain.png +0 -0
  104. package/public/skins/bocchi/icon-blush.png +0 -0
  105. package/public/skins/bocchi/icon-sleep.png +0 -0
  106. package/public/skins/bocchi/icon-smile.png +0 -0
  107. package/public/skins/bocchi/icon-star.png +0 -0
  108. package/public/skins/bocchi/icon-wink.png +0 -0
  109. package/public/skins/bocchi/icon.png +0 -0
  110. package/public/skins/bocchi/pattern-soft.png +0 -0
  111. package/public/skins/bocchi/pattern.png +0 -0
  112. package/public/skins/bocchi/preview.html +55 -0
  113. package/public/skins/bocchi/skin.css +233 -0
  114. package/public/skins/bocchi/stage-bg.png +0 -0
  115. package/public/skins/bocchi/stage-soft.png +0 -0
  116. package/public/skins/bocchi/stand.png +0 -0
  117. package/public/skins/bocchi/sticker-guitar.png +0 -0
  118. package/public/skins/kessoku/DESIGN.md +38 -0
  119. package/public/skins/kessoku/grain.png +0 -0
  120. package/public/skins/kessoku/skin.css +212 -0
  121. package/public/skins/kita/SOURCES.json +51 -0
  122. package/public/skins/kita/face.png +0 -0
  123. package/public/skins/kita/icon-live.png +0 -0
  124. package/public/skins/kita/icon-reddress.png +0 -0
  125. package/public/skins/kita/icon-seifuku.png +0 -0
  126. package/public/skins/kita/pattern.png +0 -0
  127. package/public/skins/kita/preview.html +56 -0
  128. package/public/skins/kita/skin.css +26 -0
  129. package/public/skins/kita/stand.png +0 -0
  130. package/public/skins/kita/sticker-live.png +0 -0
  131. package/public/skins/nijika/SOURCES.json +51 -0
  132. package/public/skins/nijika/face.png +0 -0
  133. package/public/skins/nijika/icon-live.png +0 -0
  134. package/public/skins/nijika/icon-reddress.png +0 -0
  135. package/public/skins/nijika/icon-seifuku.png +0 -0
  136. package/public/skins/nijika/pattern.png +0 -0
  137. package/public/skins/nijika/preview.html +56 -0
  138. package/public/skins/nijika/skin.css +25 -0
  139. package/public/skins/nijika/stand.png +0 -0
  140. package/public/skins/nijika/sticker-live.png +0 -0
  141. package/public/skins/penguin/DESIGN.md +33 -0
  142. package/public/skins/penguin/SOURCES.json +22 -0
  143. package/public/skins/penguin/aic-blueprint.svg +24 -0
  144. package/public/skins/penguin/endfield-triangles.svg +4 -0
  145. package/public/skins/penguin/face.png +0 -0
  146. package/public/skins/penguin/icon-blush.png +0 -0
  147. package/public/skins/penguin/icon-dizzy.png +0 -0
  148. package/public/skins/penguin/icon-laugh.png +0 -0
  149. package/public/skins/penguin/icon-sleep.png +0 -0
  150. package/public/skins/penguin/icon-smile.png +0 -0
  151. package/public/skins/penguin/icon-star.png +0 -0
  152. package/public/skins/penguin/icon-wink.png +0 -0
  153. package/public/skins/penguin/icon.png +0 -0
  154. package/public/skins/penguin/mascot.png +0 -0
  155. package/public/skins/penguin/pattern-night.png +0 -0
  156. package/public/skins/penguin/pattern.png +0 -0
  157. package/public/skins/penguin/preview.html +12 -0
  158. package/public/skins/penguin/skin.css +212 -0
  159. package/public/skins/ryo/SOURCES.json +51 -0
  160. package/public/skins/ryo/face.png +0 -0
  161. package/public/skins/ryo/icon-live.png +0 -0
  162. package/public/skins/ryo/icon-reddress.png +0 -0
  163. package/public/skins/ryo/icon-seifuku.png +0 -0
  164. package/public/skins/ryo/pattern.png +0 -0
  165. package/public/skins/ryo/preview.html +56 -0
  166. package/public/skins/ryo/skin.css +25 -0
  167. package/public/skins/ryo/stand.png +0 -0
  168. package/public/skins/ryo/sticker-live.png +0 -0
  169. package/public/sponsor-entry.js +21 -0
  170. package/public/styles.css +1494 -0
  171. package/public/subagents.css +61 -0
  172. package/public/subagents.js +275 -0
  173. package/public/task-board.js +109 -0
  174. package/public/teams.js +98 -0
  175. package/public/theme-picker.css +58 -0
  176. package/public/theme-vars.css +1044 -0
  177. package/public/theme.js +166 -0
  178. package/public/transcribe-core.js +74 -0
  179. package/public/turn-results.js +121 -0
  180. package/public/update.json +49 -0
  181. package/public/vendor/gsap/NOTICE.md +10 -0
  182. package/public/vendor/gsap/gsap.min.js +11 -0
  183. package/public/vendor/morphicons/LICENSE +21 -0
  184. package/public/vendor/morphicons/README.md +10 -0
  185. package/public/vendor/morphicons/controller-CXZuwJ_M.js +152 -0
  186. package/public/vendor/morphicons/dom.js +206 -0
  187. package/public/vendor/morphicons/element.js +261 -0
  188. package/public/vendor/morphicons/normalize-CYnN3Npw.js +540 -0
  189. package/public/vendor/morphicons/spring-CFHloqPP.js +623 -0
  190. package/public/version.json +3 -0
  191. package/public/voice-input.js +739 -0
  192. package/public/workflow.css +365 -0
  193. package/public/workflow.js +409 -0
  194. package/session-file.mjs +39 -0
  195. package/skills/dsh-remote-doctor/SKILL.md +186 -0
  196. package/skills/dsh-remote-doctor/references/wiki/README.md +40 -0
  197. package/skills/dsh-remote-doctor/references/wiki/ai-guide.md +61 -0
  198. package/skills/dsh-remote-doctor/references/wiki/connection.md +76 -0
  199. package/skills/dsh-remote-doctor/references/wiki/errors.md +26 -0
  200. package/skills/dsh-remote-doctor/references/wiki/evidence.md +44 -0
  201. package/skills/dsh-remote-doctor/references/wiki/files.md +31 -0
  202. package/skills/dsh-remote-doctor/references/wiki/maintenance.md +30 -0
  203. package/skills/dsh-remote-doctor/references/wiki/notifications.md +33 -0
  204. package/skills/dsh-remote-doctor/references/wiki/operations.md +32 -0
  205. package/skills/dsh-remote-doctor/references/wiki/plugins.md +90 -0
  206. package/skills/dsh-remote-doctor/references/wiki/sessions.md +45 -0
  207. package/skills/dsh-remote-doctor/references/wiki/sources.md +27 -0
  208. package/skills.mjs +53 -0
  209. package/task-board.mjs +57 -0
  210. package/teams.mjs +58 -0
@@ -0,0 +1,289 @@
1
+ /* Foreground file inbox. Confirmation precedes every download; zero dependencies. */
2
+ ;(function(root) {
3
+ 'use strict'
4
+ const MAX = 50 * 1024 * 1024
5
+ const zh = () => root.I18N?.lang !== 'en'
6
+ const label = (cn, en) => zh() ? cn : en
7
+ async function hash(bytes) {
8
+ if (root.crypto?.subtle) return [...new Uint8Array(await root.crypto.subtle.digest('SHA-256', bytes))].map(n => n.toString(16).padStart(2, '0')).join('')
9
+ if (typeof root.SHA256 === 'function') return new root.SHA256().update(new Uint8Array(bytes)).hex()
10
+ throw Error(label('当前环境无法校验文件', 'File verification is unavailable'))
11
+ }
12
+ function createClient(config) {
13
+ let current = null, epoch = 0
14
+ const requests = new Set()
15
+ const stored = key => { try { return JSON.parse(root.localStorage.getItem(key) || 'null') } catch { return null } }
16
+ const persist = ctx => { if (ctx.valid()) root.localStorage.setItem(ctx.storage, JSON.stringify(ctx.prefs)) }
17
+ const requireCurrent = ctx => { if (!ctx.valid()) throw Error(label('连接已改变,请重新打开收件箱', 'Connection changed. Reopen the inbox.')) }
18
+ async function identity() {
19
+ const connection = config.capture(), generation = epoch
20
+ if (!connection.token) throw Error(label('请先连接主机', 'Connect to a host first'))
21
+ if (current?.valid()) return current
22
+ const scope = await hash(new TextEncoder().encode(config.url('/api/file-inbox') + '\0' + connection.token))
23
+ if (generation !== epoch || !connection.valid()) throw Error('connection-changed')
24
+ const storage = 'dshRemoteFileInboxV1:' + scope
25
+ let prefs = stored(storage)
26
+ if (!/^[a-f0-9]{64}$/.test(prefs?.key || '')) {
27
+ prefs = { key: [...root.crypto.getRandomValues(new Uint8Array(32))].map(n => n.toString(16).padStart(2, '0')).join(''), name: config.native?.() ? 'Android' : label('浏览器', 'Browser'), jobs: {}, receipts: {} }
28
+ }
29
+ prefs.jobs ||= {}; prefs.receipts ||= {}
30
+ const ctx = { connection, storage, prefs, lastRegister: 0, valid: () => generation === epoch && connection.valid() }
31
+ persist(ctx); current = ctx
32
+ return ctx
33
+ }
34
+ async function read(ctx, url, options, timeoutMs, decode) {
35
+ requireCurrent(ctx)
36
+ const controller = new AbortController(), timeout = AbortSignal.timeout(timeoutMs), abort = () => controller.abort()
37
+ requests.add(controller); timeout.addEventListener('abort', abort, { once: true })
38
+ try {
39
+ const response = await root.fetch(url, { ...options, signal: controller.signal, redirect: 'error' })
40
+ requireCurrent(ctx)
41
+ const data = await decode(response)
42
+ requireCurrent(ctx)
43
+ return data
44
+ } finally { requests.delete(controller); timeout.removeEventListener('abort', abort) }
45
+ }
46
+ async function api(ctx, body) {
47
+ const { response, data } = await read(ctx, config.url('/api/file-inbox'), { method: body ? 'POST' : 'GET', headers: { ...config.headers(ctx.connection), 'content-type': 'application/json', 'x-dsh-remote-inbox-key': ctx.prefs.key }, ...(body ? { body: JSON.stringify(body) } : {}) }, 12000, async response => ({ response, data: await response.json() }))
48
+ requireCurrent(ctx)
49
+ if (!response.ok) throw Error(response.status === 404 ? label('主机尚不支持文件收件箱,请升级 Remote 插件', 'Update the host Remote plugin to use the file inbox') : String(data.error || 'HTTP ' + response.status))
50
+ return data
51
+ }
52
+ async function acknowledge(ctx, id, phase) {
53
+ requireCurrent(ctx)
54
+ ctx.prefs.receipts[id] = phase; persist(ctx)
55
+ await api(ctx, { action: 'receipt', id, phase })
56
+ delete ctx.prefs.receipts[id]; persist(ctx)
57
+ }
58
+ async function sync() {
59
+ const ctx = await identity()
60
+ if (Date.now() - ctx.lastRegister > 20000) { ctx.device = await api(ctx, { action: 'register', name: ctx.prefs.name }); ctx.lastRegister = Date.now() }
61
+ const before = await api(ctx)
62
+ for (const id of Object.keys(ctx.prefs.jobs)) {
63
+ const row = before.transfers.find(row => row.id === id)
64
+ if (!row || ['expired', 'rejected', 'complete', 'downloaded'].includes(row.phase)) { delete ctx.prefs.jobs[id]; delete ctx.prefs.receipts[id]; persist(ctx) }
65
+ }
66
+ for (const id of Object.keys(ctx.prefs.receipts)) {
67
+ const row = before.transfers.find(row => row.id === id)
68
+ if (!row || ['expired', 'rejected', 'complete', 'downloaded'].includes(row.phase)) { delete ctx.prefs.receipts[id]; persist(ctx) }
69
+ }
70
+ for (const [id, job] of Object.entries(ctx.prefs.jobs)) {
71
+ requireCurrent(ctx)
72
+ let status
73
+ try { status = JSON.parse(config.native()?.getFileDownloadStatus(job)) } catch { continue }
74
+ // DownloadManager returns unknown after its record is removed. Let the
75
+ // user retry instead of retaining a job that can never finish.
76
+ if (!['complete', 'error', 'unknown'].includes(status?.phase)) continue
77
+ try { await acknowledge(ctx, id, status.phase === 'complete' ? 'complete' : 'failed'); delete ctx.prefs.jobs[id]; persist(ctx) } catch {}
78
+ }
79
+ for (const [id, phase] of Object.entries(ctx.prefs.receipts)) { try { await acknowledge(ctx, id, phase) } catch {} }
80
+ const value = await api(ctx)
81
+ return { ...value, device: ctx.device, name: ctx.prefs.name, jobs: { ...ctx.prefs.jobs } }
82
+ }
83
+ return {
84
+ sync,
85
+ reset() { epoch++; current = null; for (const request of requests) request.abort(); requests.clear() },
86
+ async rename(name) { const ctx = await identity(); requireCurrent(ctx); ctx.prefs.name = String(name).trim().slice(0, 60) || 'Remote'; persist(ctx); ctx.lastRegister = 0; return sync() },
87
+ async reject(row) { const ctx = await identity(); return api(ctx, { action: 'reject', id: row.id }) },
88
+ async receive(row) {
89
+ const ctx = await identity()
90
+ const accepted = await api(ctx, { action: 'accept', id: row.id })
91
+ requireCurrent(ctx)
92
+ const url = new URL(config.url('/fs/inbox-file'), root.location.href)
93
+ url.searchParams.set('id', row.id); url.searchParams.set('ticket', accepted.ticket)
94
+ const native = config.native?.()
95
+ try {
96
+ if (native?.downloadToDownloads && native?.getFileDownloadStatus) {
97
+ const job = native.downloadToDownloads(url.href, accepted.fileName, ctx.connection.token)
98
+ if (!/^\d+$/.test(String(job))) throw Error(label('系统下载未启动', 'System download did not start'))
99
+ ctx.prefs.jobs[row.id] = String(job); persist(ctx)
100
+ return { native: true }
101
+ }
102
+ const bytes = await read(ctx, url.href, { headers: config.headers(ctx.connection) }, 20 * 60 * 1000, async response => {
103
+ if (!response.ok || accepted.size > MAX) throw Error(label('文件下载失败', 'Download failed'))
104
+ return response.arrayBuffer()
105
+ })
106
+ requireCurrent(ctx)
107
+ if (bytes.byteLength !== accepted.size || await hash(bytes) !== accepted.sha256) throw Error(label('文件校验失败', 'File verification failed'))
108
+ requireCurrent(ctx)
109
+ return { native: false, blob: new Blob([bytes], { type: 'application/octet-stream' }), name: accepted.fileName, id: row.id, valid: ctx.valid,
110
+ handedOff: () => acknowledge(ctx, row.id, 'downloaded') }
111
+ } catch (error) {
112
+ if (ctx.valid()) { try { await acknowledge(ctx, row.id, 'failed') } catch {} }
113
+ throw error
114
+ }
115
+ },
116
+ }
117
+ }
118
+
119
+ const actionable = row => ['pending', 'accepted', 'downloading', 'failed'].includes(row.phase)
120
+ const sessionTransfers = (rows, sessionId) => sessionId ? rows.filter(row => row.sessionId === sessionId && actionable(row)) : []
121
+ let mounted
122
+ function mount(config) {
123
+ if (mounted || !root.document) return mounted
124
+ const client = createClient(config), doc = root.document
125
+ const node = (tag, text, cls) => { const el = doc.createElement(tag); if (text != null) el.textContent = text; if (cls) el.className = cls; return el }
126
+ const button = (text, action, key, primary = false) => {
127
+ const el = node('button', text, 'file-inbox-button' + (primary ? ' primary' : ''))
128
+ el.type = 'button'; el.dataset.inboxFocus = key; el.addEventListener('click', action); return el
129
+ }
130
+ const files = doc.getElementById('file-inbox-files'), session = doc.getElementById('file-inbox-session')
131
+ const slots = [files, session].filter(Boolean)
132
+ let snapshot, busy = false, polling = false, note = '', noteId = '', lastSignature = '', destroyed = false, generation = 0, revision = 0
133
+ let historyOpen = false, deviceOpen = false
134
+ const expanded = new Set(), ready = new Map()
135
+ const context = () => config.context?.() || { sessionId: '', inChat: false }
136
+ const releasePrepared = () => { ready.forEach(item => URL.revokeObjectURL(item.url)); ready.clear() }
137
+ const phases = () => ({ pending: label('等待接收', 'Awaiting acceptance'), accepted: label('准备下载', 'Preparing download'), downloading: label('下载中 / 等待回执', 'Downloading / awaiting receipt'), downloaded: label('已交给浏览器保存', 'Handed to browser'), complete: label('设备报告已保存', 'Device reports saved'), failed: label('接收失败', 'Receive failed'), rejected: label('已拒绝', 'Rejected'), expired: label('已过期', 'Expired') })
138
+ function reset() { generation++; client.reset(); snapshot = null; note = ''; noteId = ''; busy = false; polling = false; lastSignature = ''; historyOpen = false; deviceOpen = false; expanded.clear(); releasePrepared(); render() }
139
+ async function action(id, work) {
140
+ if (busy) return
141
+ const start = generation, scope = context(), active = doc.activeElement
142
+ const focusKey = slots.some(slot => slot.contains(active)) ? active?.dataset?.inboxFocus : ''
143
+ const actionRevision = ++revision
144
+ busy = true; noteId = id; note = label('处理中…', 'Working…'); render()
145
+ try { await work(); if (start !== generation) return; const value = await client.sync(); if (start !== generation) return; snapshot = value; note = ''; noteId = '' }
146
+ catch (error) { if (start === generation) note = error.message }
147
+ finally { if (start === generation) { busy = false; render(); restoreActionFocus(focusKey, scope, start, actionRevision) } }
148
+ }
149
+ function restoreActionFocus(key, scope, start, actionRevision) {
150
+ if (!key) return
151
+ // Wait for the session deck to select and reveal the replacement card.
152
+ root.requestAnimationFrame(() => {
153
+ const current = context(), active = doc.activeElement
154
+ if (destroyed || start !== generation || actionRevision !== revision || busy ||
155
+ current.sessionId !== scope.sessionId || current.inChat !== scope.inChat ||
156
+ (active && active !== doc.body && active !== doc.documentElement)) return
157
+ const visible = el => el && !el.disabled && !el.closest('[hidden],.hidden,[inert]') && el.getClientRects().length
158
+ const candidates = slots.flatMap(slot => [...slot.querySelectorAll('[data-inbox-focus]')])
159
+ const keys = [key.replace(/:accept$/, ':save'), key, key.replace(/:[^:]+$/, ':card')]
160
+ const target = keys.map(value => candidates.find(el => el.dataset.inboxFocus === value && visible(el))).find(Boolean)
161
+ || candidates.find(el => el.dataset.inboxFocus.startsWith('session:') && visible(el))
162
+ || (scope.inChat ? [doc.getElementById('session-deck-stage'), doc.getElementById('composer-input'), doc.getElementById('composer')].find(visible)
163
+ : candidates.find(el => el.dataset.inboxFocus === 'files:heading' && visible(el)))
164
+ target?.focus({ preventScroll: true })
165
+ })
166
+ }
167
+ function card(row, placement) {
168
+ const compact = placement === 'session', prepared = ready.get(row.id)
169
+ const el = node('article', null, 'file-inbox-card' + (compact ? ' is-compact' : '') + (actionable(row) ? ' needs-action' : ''))
170
+ el.dataset.transferId = row.id
171
+ const key = action => placement + ':' + row.id + ':' + action
172
+ el.tabIndex = -1; el.dataset.inboxFocus = key('card')
173
+ const head = node('div', null, 'file-inbox-card-head'), icon = node('span', '↓', 'file-inbox-icon'), names = node('div', null, 'file-inbox-names')
174
+ icon.setAttribute('aria-hidden', 'true')
175
+ const size = row.size < 1024 ? row.size + ' B' : row.size < 1048576 ? (row.size / 1024).toFixed(1) + ' KiB' : (row.size / 1048576).toFixed(2) + ' MiB'
176
+ const purpose = [row.title && row.title !== row.fileName ? row.title : '', row.message].filter(Boolean).join(' · ')
177
+ if (compact) {
178
+ names.append(node('strong', row.fileName, 'file-inbox-filename'))
179
+ const extension = /\.([a-z0-9]{1,10})$/i.exec(row.fileName)?.[1]?.toUpperCase()
180
+ const meta = node('div', null, 'file-inbox-inline-meta'); meta.append(node('span', (extension ? extension + ' · ' : '') + size, 'file-inbox-size'))
181
+ if (prepared || row.phase !== 'pending') meta.append(node('span', prepared ? label('传输校验通过', 'Transfer verified') : phases()[row.phase] || row.phase, 'file-inbox-phase ' + row.phase))
182
+ head.append(names, meta); el.append(head, node('p', purpose || label('未附文件说明', 'No file description provided'), 'file-inbox-message'))
183
+ } else {
184
+ names.append(node('span', label('文件接收请求', 'File delivery'), 'file-inbox-eyebrow'), node('strong', row.fileName, 'file-inbox-filename'))
185
+ head.append(icon, names, node('span', phases()[row.phase] || row.phase, 'file-inbox-phase ' + row.phase)); el.append(head)
186
+ el.append(node('p', size + (row.title && row.title !== row.fileName ? ' · ' + row.title : ''), 'file-inbox-meta'))
187
+ if (row.message) el.append(node('p', row.message, 'file-inbox-message'))
188
+ }
189
+ const details = node('details', null, 'file-inbox-details'); details.open = expanded.has(key('details'))
190
+ details.append(node('summary', compact ? label('详情', 'Details') : label('查看详情', 'Details')))
191
+ if (compact) details.append(node('p', label('文件:', 'File: ') + row.fileName), node('p', label('说明:', 'Description: ') + (purpose || label('未提供', 'Not provided'))))
192
+ details.append(node('p', label('来源会话:', 'Session: ') + (config.sessionTitle?.(row.sessionId) || row.sessionId)), node('p', label('到期:', 'Expires: ') + new Date(row.expiresAt).toLocaleString()))
193
+ details.addEventListener('toggle', () => details.open ? expanded.add(key('details')) : expanded.delete(key('details')))
194
+ if (!compact) el.append(details)
195
+ const actions = node('div', null, 'file-inbox-actions')
196
+ if (prepared) {
197
+ if (!compact) el.append(node('p', label('已校验,点击保存文件。', 'Verified. Save the file to continue.'), 'file-inbox-meta'))
198
+ actions.append(button(label('保存文件', 'Save file'), () => action(row.id, async () => {
199
+ if (!prepared.valid()) throw Error(label('连接已改变', 'Connection changed'))
200
+ const anchor = node('a'); anchor.href = prepared.url; anchor.download = prepared.name; doc.body.append(anchor); anchor.click(); anchor.remove()
201
+ await prepared.handedOff(); URL.revokeObjectURL(prepared.url); ready.delete(row.id)
202
+ }), key('save'), true))
203
+ } else if (actionable(row) && !snapshot.jobs?.[row.id]) {
204
+ actions.append(button(row.phase === 'pending' ? label('接收文件', 'Accept file') : label('重新接收', 'Receive again'), () => action(row.id, async () => {
205
+ const out = await client.receive(row)
206
+ if (!out.native) ready.set(row.id, { ...out, url: URL.createObjectURL(out.blob) })
207
+ }), key('accept'), true))
208
+ if (row.phase === 'pending') actions.append(button(label('拒绝', 'Reject'), () => action(row.id, () => client.reject(row)), key('reject')))
209
+ }
210
+ if (compact) actions.append(details)
211
+ if (actions.children.length) el.append(actions)
212
+ if (note && noteId === row.id) el.append(node('p', note, 'file-inbox-note'))
213
+ return el
214
+ }
215
+ function render() {
216
+ if (destroyed) return
217
+ const active = doc.activeElement, focused = active?.dataset?.inboxFocus, hadFocus = slots.some(slot => slot.contains(active))
218
+ const rows = snapshot?.transfers || [], current = context()
219
+ if (session) {
220
+ const selected = current.inChat ? sessionTransfers(rows, current.sessionId) : []
221
+ session.hidden = !selected.length
222
+ session.replaceChildren()
223
+ if (selected.length) {
224
+ const header = node('div', null, 'file-inbox-head'), heading = node('h3', label('待接收文件', 'Incoming files'))
225
+ header.append(heading, node('span', String(selected.length), 'file-inbox-count'))
226
+ const list = node('div', null, 'file-inbox-list'); for (const row of selected) list.append(card(row, 'session'))
227
+ session.append(header, list)
228
+ }
229
+ }
230
+ if (files) {
231
+ files.replaceChildren()
232
+ const header = node('header', null, 'file-inbox-head'), heading = node('h2', label('文件收件箱', 'File inbox'))
233
+ heading.tabIndex = -1; heading.dataset.inboxFocus = 'files:heading'
234
+ const count = rows.filter(actionable).length
235
+ header.append(heading, node('span', String(count), 'file-inbox-count'), button(label('刷新', 'Refresh'), tick, 'files:refresh'))
236
+ files.append(header)
237
+ files.append(node('p', label('DSH 发来的文件,确认后才会接收。', 'Files sent by DSH are downloaded only after you accept.'), 'file-inbox-intro'))
238
+ if (note && !noteId) files.append(node('p', note, 'file-inbox-note'))
239
+ const incoming = rows.filter(actionable), list = node('div', null, 'file-inbox-list')
240
+ for (const row of incoming) list.append(card(row, 'files'))
241
+ if (!incoming.length) list.append(node('p', snapshot ? label('暂无待接收文件', 'No incoming files') : label('连接主机后可接收文件', 'Connect to a host to receive files'), 'file-inbox-empty'))
242
+ files.append(list)
243
+ const history = rows.filter(row => !actionable(row))
244
+ if (history.length) {
245
+ const group = node('details', null, 'file-inbox-history'); group.open = historyOpen
246
+ group.append(node('summary', label('已处理', 'History') + ' (' + history.length + ')'))
247
+ const items = node('div', null, 'file-inbox-list'); for (const row of history) items.append(card(row, 'history'))
248
+ group.append(items); group.addEventListener('toggle', () => { historyOpen = group.open }); files.append(group)
249
+ }
250
+ if (snapshot) {
251
+ const device = node('details', null, 'file-inbox-device'); device.open = deviceOpen
252
+ device.append(node('summary', label('接收设备 · ', 'Receiving device · ') + snapshot.name))
253
+ const field = node('label', label('设备名称 ', 'Device name ')), input = node('input'); input.value = snapshot.name; input.maxLength = 60; input.dataset.inboxFocus = 'files:name'
254
+ field.append(input); device.append(field, button(label('保存名称', 'Save name'), () => action('', async () => { await client.rename(input.value) }), 'files:rename'), node('small', label('设备编号:', 'Device id: ') + (snapshot.device?.id || '—')))
255
+ device.addEventListener('toggle', () => { deviceOpen = device.open }); files.append(device)
256
+ }
257
+ }
258
+ for (const slot of slots) for (const el of slot.querySelectorAll('button,input')) el.disabled = busy
259
+ if (hadFocus && focused) {
260
+ const target = slots.flatMap(slot => [...slot.querySelectorAll('[data-inbox-focus]')]).find(el => el.dataset.inboxFocus === focused)
261
+ if (target?.tagName === 'INPUT') target.value = active.value
262
+ if (target && !target.disabled) target.focus()
263
+ }
264
+ }
265
+ async function tick() {
266
+ if (destroyed || polling || busy || doc.visibilityState === 'hidden') return
267
+ const start = generation, readRevision = revision
268
+ polling = true
269
+ try {
270
+ const next = await client.sync(), signature = JSON.stringify(next)
271
+ if (start !== generation || readRevision !== revision) return
272
+ snapshot = next; note = ''; noteId = ''
273
+ for (const [id, item] of ready) if (!next.transfers.some(row => row.id === id && row.phase === 'downloading')) { URL.revokeObjectURL(item.url); ready.delete(id) }
274
+ if (signature !== lastSignature && doc.activeElement?.tagName !== 'INPUT') { render(); lastSignature = signature }
275
+ } catch (error) { if (start === generation && readRevision === revision) { note = error.message; noteId = ''; render() } }
276
+ finally { if (start === generation) polling = false }
277
+ }
278
+ async function open() { config.openFiles?.(); render(); files?.querySelector('h2')?.focus(); await tick() }
279
+ const entries = [...doc.querySelectorAll('[data-file-inbox-open]')]
280
+ for (const el of entries) el.addEventListener('click', open)
281
+ const timer = root.setInterval(tick, 10000)
282
+ doc.addEventListener('visibilitychange', tick)
283
+ mounted = { open, render, reset, close: () => false, refresh: tick, destroy() { client.reset(); releasePrepared(); root.clearInterval(timer); doc.removeEventListener('visibilitychange', tick); for (const el of entries) el.removeEventListener('click', open); for (const slot of slots) slot.replaceChildren(); if (session) session.hidden = true; destroyed = true; mounted = null } }
284
+ render(); void tick()
285
+ return mounted
286
+ }
287
+ root.DshFileInbox = { createClient, sessionTransfers, mount, reset: () => mounted?.reset(), refresh: () => mounted?.refresh(), render: () => mounted?.render(), open: () => mounted?.open(), close: () => mounted?.close() }
288
+ if (typeof module !== 'undefined') module.exports = root.DshFileInbox
289
+ })(typeof window !== 'undefined' ? window : globalThis)
@@ -0,0 +1,8 @@
1
+ .genui{margin:14px 0;padding:14px;border:1px solid #8884;border-radius:12px;line-height:1.65;overflow:hidden;color:inherit;background:#88808;font-size:14px}
2
+ .genui *{box-sizing:border-box}.genui h1,.genui h2,.genui h3,.genui h4,.genui p{margin:0 0 10px}.genui-caption{font-size:11px;opacity:.65;margin-bottom:12px}.genui-row{display:flex;flex-wrap:wrap;gap:12px}.genui-row>*{flex:1;min-width:120px}.genui-col{display:grid;gap:12px}.genui-grid{display:grid;grid-template-columns:repeat(var(--genui-cols,2),minmax(0,1fr));gap:12px}.genui-card{border:1px solid #8884;border-radius:8px;padding:12px;min-width:0}.genui-card>h4{font-size:16px}.genui-stat{display:flex;flex-direction:column;min-width:0;padding:8px 0}.genui-stat strong{font-size:28px;line-height:1.25;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.genui-stat small,.genui-stat span{opacity:.75}.genui-badge{display:inline-block;padding:2px 9px;border:1px solid #8885;border-radius:20px}.genui progress{display:block;width:100%;accent-color:#2563eb;height:10px;margin:7px 0}.genui-spacer{height:12px}.genui-callout{border-left:3px solid #2563eb;padding:10px 12px;background:#2563eb12}.genui-chart{margin:10px 0}.genui-chart figcaption{font-weight:600}.genui-chart svg{display:block;width:100%;height:auto;max-height:520px}.genui-chart svg text{fill:currentColor;font:11px system-ui}.genui-gridline{stroke:currentColor;opacity:.15;fill:none}.genui-legend{display:flex;flex-wrap:wrap;gap:7px 14px;font-size:12px}.genui-legend i{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:5px}.genui-scroll{overflow:auto;max-height:420px}.genui table{width:100%;border-collapse:collapse;font-size:12px}.genui td,.genui th{text-align:left;padding:7px;border-bottom:1px solid #8884;white-space:nowrap}.genui-source{margin-top:12px}.genui summary{cursor:pointer;font-size:12px}.genui pre{max-height:320px;overflow:auto;white-space:pre-wrap;word-break:break-word}.genui-unsupported{border-left:2px solid #d97706;padding:8px;margin:8px 0}.genui-html{display:block;width:100%;height:440px;border:1px solid #8884;border-radius:7px;background:white}.genui dl{display:grid;grid-template-columns:auto 1fr;gap:6px 12px}.genui dd{margin:0}.genui li{margin:4px 0}@media(max-width:520px){.genui{padding:10px}.genui-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.genui-stat strong{font-size:23px}.genui-html{height:380px}}
3
+ .genui-tabs>[role=tablist]{display:flex;gap:5px;overflow-x:auto;margin-bottom:12px;border-bottom:1px solid #8884;padding-bottom:6px}
4
+ .genui button{font:inherit;color:inherit;background:transparent;border:1px solid #8884;border-radius:6px;padding:5px 9px;cursor:pointer}
5
+ .genui button:focus-visible{outline:2px solid #2563eb;outline-offset:2px}.genui [role=tab][aria-selected=true]{background:#2563eb20;border-color:#2563eb}.genui [hidden]{display:none!important}
6
+ .genui .genui-spark{display:block;width:120px;height:30px;max-width:100%;color:#2563eb}.genui-ring{display:inline-flex;gap:8px;align-items:center}.genui-ring svg{width:40px;height:40px;flex:none;color:#2563eb}
7
+ .genui-positive{color:#059669}.genui-negative{color:#dc2626}.genui-table tfoot{font-weight:600}.genui-table th[aria-sort=ascending] button::after{content:' ↑'}.genui-table th[aria-sort=descending] button::after{content:' ↓'}
8
+ .genui-tree{list-style:none;padding-left:16px;border-left:1px solid #8884}.genui-diff{margin:10px 0}.genui-diff section{min-width:0}.genui-diff pre{white-space:pre;overflow:auto}.genui-diff .genui-grid{gap:12px;margin-top:8px}@media(max-width:520px){.genui-diff .genui-grid{grid-template-columns:1fr}}
@@ -0,0 +1,254 @@
1
+ /* DSH Remote: dependency-free, read-only dsh-ui subset. Never executes model code. */
2
+ (function (root, factory) {
3
+ if (typeof module === 'object' && module.exports) module.exports = factory()
4
+ else root.DshGenUi = factory()
5
+ })(typeof self !== 'undefined' ? self : this, function () {
6
+ 'use strict'
7
+ const esc = value => String(value == null ? '' : value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
8
+ const palette = ['#2563eb', '#059669', '#d97706', '#db2777', '#7c3aed', '#0891b2']
9
+ const array = value => Array.isArray(value) ? value : []
10
+ const number = value => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= 1e12
11
+ const color = (value, i) => /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(value || '') ? value : palette[i % palette.length]
12
+ const raw = value => '<pre><code>' + esc(typeof value === 'string' ? value : JSON.stringify(value, null, 2)) + '</code></pre>'
13
+ const details = value => '<details class="genui-source"><summary>JSON / 源码</summary>' + raw(value) + '</details>'
14
+ let uid = 0
15
+ function spark(values) {
16
+ if (!Array.isArray(values) || values.length < 2 || values.length > 100 || !values.every(number)) return ''
17
+ const low = Math.min(...values), span = Math.max(...values) - low || 1
18
+ return '<svg class="genui-spark" viewBox="0 0 120 30" role="img" aria-label="趋势"><title>' + esc(values.join(', ')) + '</title><polyline fill="none" stroke="currentColor" stroke-width="2" points="' + values.map((v, i) => (2 + i * 116 / (values.length - 1)) + ',' + (28 - (v - low) / span * 26)).join(' ') + '"/></svg>'
19
+ }
20
+ function ring(value, label) {
21
+ const pct = Math.max(0, Math.min(100, value))
22
+ return '<span class="genui-ring"><svg viewBox="0 0 40 40" aria-hidden="true"><circle cx="20" cy="20" r="16" fill="none" stroke="currentColor" opacity=".15" stroke-width="4"/><circle cx="20" cy="20" r="16" fill="none" stroke="currentColor" stroke-width="4" pathLength="100" stroke-dasharray="' + pct + ' 100" transform="rotate(-90 20 20)"/></svg><span>' + esc(label) + '</span></span>'
23
+ }
24
+ function numeric(value) {
25
+ if (typeof value === 'number') return Number.isFinite(value) ? value : NaN
26
+ let s = String(value ?? '').trim().replace(/^[¥$€£]/, '').replace(/%$/, '')
27
+ if (!s) return NaN
28
+ let factor = 1
29
+ const unit = s.slice(-1).toLowerCase()
30
+ if ('kmb万亿'.includes(unit)) { factor = ({ k: 1e3, m: 1e6, b: 1e9, 万: 1e4, 亿: 1e8 })[unit]; s = s.slice(0, -1) }
31
+ return s.trim() ? Number(s.replace(/[,,\s]/g, '')) * factor : NaN
32
+ }
33
+ function unsupported(node, reason) {
34
+ return '<div class="genui-unsupported">暂不支持 / Unsupported: ' + esc(reason || node?.type || 'spec') + details(node) + '</div>'
35
+ }
36
+
37
+ function chart(node) {
38
+ const kind = node.kind || 'bars'
39
+ if (!['bars', 'line', 'donut'].includes(kind) || (node.stacked && kind !== 'bars') || node.filter || node.sortField) return unsupported(node, 'chart options')
40
+ const series = array(node.series).length ? node.series : [{ label: node.title || '', data: node.data }]
41
+ if (series.length > 6 || (kind === 'donut' && series.length !== 1)) return unsupported(node, 'chart series')
42
+ if (series.some(s => !s || !Array.isArray(s.data) || !s.data.length || s.data.length > 100 || s.data.some(d => !d || !number(d.value)))) return unsupported(node, 'chart data')
43
+ const data = series[0].data
44
+ if (series.some(s => s.data.length !== data.length || s.data.some((d, i) => d.label !== data[i].label))) return unsupported(node, 'unaligned series')
45
+ const colors = series.map((s, i) => color(s.color || array(node.palette)[i], i))
46
+ const table = '<div class="genui-scroll"><table><thead><tr><th></th>' + series.map(s => '<th>' + esc(s.label || 'Value') + '</th>').join('') + '</tr></thead><tbody>' + data.map((d, i) => '<tr><th>' + esc(d.label) + '</th>' + series.map(s => '<td>' + esc(s.data[i].value) + '</td>').join('') + '</tr>').join('') + '</tbody></table></div>'
47
+ let svg = ''
48
+ if (kind === 'donut') {
49
+ const total = data.reduce((sum, d) => sum + d.value, 0)
50
+ if (data.some(d => d.value < 0) || total <= 0) return unsupported(node, 'donut requires non-negative values and positive total')
51
+ let offset = 0
52
+ svg = data.map((d, i) => {
53
+ const fraction = d.value / total * 100
54
+ const segment = '<circle cx="160" cy="120" r="75" fill="none" stroke="' + color(d.color || array(node.palette)[i], i) + '" stroke-width="34" pathLength="100" stroke-dasharray="' + fraction + ' ' + (100 - fraction) + '" stroke-dashoffset="' + (-offset) + '" transform="rotate(-90 160 120)"><title>' + esc(d.label) + ': ' + esc(d.value) + ' (' + fraction.toFixed(1) + '%)</title></circle>'
55
+ offset += fraction
56
+ return segment
57
+ }).join('') + '<text x="160" y="124" text-anchor="middle" fill="currentColor">' + esc(total) + '</text>'
58
+ svg = '<svg viewBox="0 0 320 240" role="img" aria-label="' + esc(node.title || 'Donut chart') + '">' + svg + '</svg>'
59
+ svg += '<div class="genui-legend">' + data.map((d, i) => '<span><i style="background:' + color(d.color || array(node.palette)[i], i) + '"></i>' + esc(d.label) + ' · ' + (d.value / total * 100).toFixed(1) + '%</span>').join('') + '</div>'
60
+ } else {
61
+ const values = series.flatMap(s => s.data.map(d => d.value))
62
+ const stacked = node.stacked === true && kind === 'bars'
63
+ if (stacked) data.forEach((_, i) => {
64
+ values.push(series.reduce((sum, s) => sum + Math.max(0, s.data[i].value), 0))
65
+ values.push(series.reduce((sum, s) => sum + Math.min(0, s.data[i].value), 0))
66
+ })
67
+ let min = Math.min(0, ...values), max = Math.max(0, ...values)
68
+ if (min === max) max = min + 1
69
+ const horizontal = kind === 'bars' && node.horizontal === true
70
+ const width = 560, height = horizontal ? Math.max(240, data.length * 35 + 50) : 270
71
+ const left = horizontal ? 110 : 64, right = 20, top = 20, bottom = 45
72
+ const w = width - left - right, h = height - top - bottom
73
+ const scale = value => horizontal ? left + (value - min) / (max - min) * w : top + (max - value) / (max - min) * h
74
+ for (let i = 0; i <= 4; i++) {
75
+ const value = min + (max - min) * i / 4, p = scale(value)
76
+ svg += horizontal
77
+ ? '<path d="M' + p + ' ' + top + 'V' + (top + h) + '" class="genui-gridline"/><text x="' + p + '" y="' + (height - 12) + '" text-anchor="middle">' + esc(Number(value.toPrecision(4))) + '</text>'
78
+ : '<path d="M' + left + ' ' + p + 'H' + (left + w) + '" class="genui-gridline"/><text x="' + (left - 7) + '" y="' + (p + 4) + '" text-anchor="end">' + esc(Number(value.toPrecision(4))) + '</text>'
79
+ }
80
+ const step = (horizontal ? h : w) / data.length
81
+ series.forEach((s, si) => {
82
+ const points = []
83
+ s.data.forEach((d, i) => {
84
+ const base = stacked ? series.slice(0, si).reduce((sum, prev) => sum + (d.value >= 0 ? Math.max(0, prev.data[i].value) : Math.min(0, prev.data[i].value)), 0) : 0
85
+ const center = (horizontal ? top : left) + step * (i + 0.5), pos = scale(base + d.value)
86
+ const hint = '<title>' + esc((s.label ? s.label + ' · ' : '') + d.label + ': ' + d.value) + '</title>'
87
+ if (kind === 'line') {
88
+ points.push(center + ',' + pos)
89
+ svg += '<circle cx="' + center + '" cy="' + pos + '" r="3" fill="' + colors[si] + '">' + hint + '</circle>'
90
+ } else {
91
+ const size = step * 0.7 / (stacked ? 1 : series.length), lane = center - step * 0.35 + (stacked ? 0 : si * size)
92
+ const zero = scale(base)
93
+ svg += '<rect x="' + (horizontal ? Math.min(zero, pos) : lane) + '" y="' + (horizontal ? lane : Math.min(zero, pos)) + '" width="' + (horizontal ? Math.abs(zero - pos) : size) + '" height="' + (horizontal ? size : Math.abs(zero - pos)) + '" fill="' + (series.length === 1 ? color(d.color || array(node.palette)[i], i) : colors[si]) + '">' + hint + '</rect>'
94
+ }
95
+ })
96
+ if (kind === 'line') svg += '<polyline points="' + points.join(' ') + '" fill="none" stroke="' + colors[si] + '" stroke-width="2.5"/>'
97
+ })
98
+ data.forEach((d, i) => {
99
+ if (!horizontal && i % Math.ceil(data.length / 8) !== 0) return
100
+ const text = String(d.label || '')
101
+ svg += '<text x="' + (horizontal ? left - 6 : left + step * (i + 0.5)) + '" y="' + (horizontal ? top + step * (i + 0.5) + 4 : height - 21) + '" text-anchor="' + (horizontal ? 'end' : 'middle') + '">' + esc(text.length > 12 ? text.slice(0, 11) + '…' : text) + '</text>'
102
+ })
103
+ svg = '<svg viewBox="0 0 ' + width + ' ' + height + '" role="img" aria-label="' + esc(node.title || kind + ' chart') + '">' + svg + '</svg>'
104
+ if (series.length > 1) svg += '<div class="genui-legend">' + series.map((s, i) => '<span><i style="background:' + colors[i] + '"></i>' + esc(s.label) + '</span>').join('') + '</div>'
105
+ }
106
+ return '<figure class="genui-chart">' + (node.title ? '<figcaption>' + esc(node.title) + '</figcaption>' : '') + svg + '<details><summary>数据 / Data</summary>' + table + '</details></figure>'
107
+ }
108
+
109
+ function render(spec) {
110
+ if (!spec || typeof spec !== 'object') throw Error('Invalid spec')
111
+ let count = 0
112
+ function nodes(items, depth) { return array(items).map(n => node(n, depth)).join('') }
113
+ function fileTree(items, depth) {
114
+ if (depth > 12 || (count += array(items).length) > 240) throw Error('Component limit')
115
+ return '<ul class="genui-tree">' + array(items).map(v => !v || typeof v !== 'object' ? '<li>' + esc(v) + '</li>' : '<li>' + (v.type === 'dir' || Array.isArray(v.children) ? '<details open><summary>' + esc(v.name) + '</summary>' + fileTree(v.children, depth + 1) + '</details>' : '<span>' + esc(v.name) + '</span>') + '</li>').join('') + '</ul>'
116
+ }
117
+ function table(n, depth) {
118
+ const columns = array(n.columns), rows = array(n.rows), types = array(n.types)
119
+ if (!columns.length || rows.some(r => !Array.isArray(r)) || types.some(t => !['text', 'num', 'delta', 'bar', 'badge', 'spark', 'ring', 'index'].includes(t))) return unsupported(n, 'table shape/types')
120
+ const cell = (v, type, i) => {
121
+ const num = numeric(v)
122
+ if (type === 'index') return String(i + 1)
123
+ if (type === 'spark') return spark(String(v).split(/[\s,;]+/).map(Number)) || esc(v)
124
+ if (type === 'ring' && Number.isFinite(num)) return ring(num, v)
125
+ if (type === 'bar' && Number.isFinite(num)) return '<span>' + esc(v) + '</span><progress max="100" value="' + Math.max(0, Math.min(100, num)) + '"></progress>'
126
+ if (type === 'badge') return '<span class="genui-badge">' + esc(v) + '</span>'
127
+ if (type === 'delta') return '<span class="genui-' + (num > 0 ? 'positive' : num < 0 ? 'negative' : 'neutral') + '">' + esc(v) + '</span>'
128
+ return esc(v)
129
+ }
130
+ let foot = ''
131
+ if (n.total) foot = '<tfoot><tr>' + columns.map((_, j) => {
132
+ const values = rows.map(r => numeric(r[j]))
133
+ return '<td>' + (j === 0 ? '合计 / Total' : values.length && values.every(Number.isFinite) && !['index', 'spark', 'ring', 'bar'].includes(types[j]) ? esc(Number(values.reduce((a, b) => a + b, 0).toPrecision(12))) : '') + '</td>'
134
+ }).join('') + '</tr></tfoot>'
135
+ return '<div class="genui-scroll"><table class="genui-table"><thead><tr>' + columns.map((v, j) => '<th aria-sort="none"><button type="button" data-genui-sort="' + j + '">' + esc(v) + ' ↕</button></th>').join('') + '</tr></thead>' + rows.map((r, i) => '<tbody data-genui-order="' + i + '"><tr>' + columns.map((_, j) => '<td data-genui-value="' + esc(r[j]) + '">' + cell(r[j], types[j], i) + '</td>').join('') + '</tr>' + (array(n.details?.[i]).length ? '<tr><td colspan="' + columns.length + '"><details><summary>详情 / Details</summary>' + nodes(n.details[i], depth + 1) + '</details></td></tr>' : '') + '</tbody>').join('') + foot + '</table></div>' + (n.export ? '<details><summary>导出数据 / CSV</summary>' + raw([columns, ...rows].map(r => r.map(v => '"' + String(v ?? '').replace(/"/g, '""') + '"').join(',')).join('\n')) + '</details>' : '')
136
+ }
137
+ function node(n, depth) {
138
+ if (++count > 240 || depth > 12) throw Error('Component limit')
139
+ if (!n || typeof n !== 'object' || Array.isArray(n)) return unsupported(n)
140
+ // 插件公开的常用字段别名。
141
+ n = { ...n }
142
+ if (n.type === 'text' && n.content === undefined) n.content = n.text
143
+ if (n.type === 'table') { n.columns ??= n.headers; n.rows ??= n.data }
144
+ if (n.type === 'card') { n.title ??= n.label; n.items ??= n.content }
145
+ const type = n.type
146
+ // Reject data-transforming options rather than silently displaying different data.
147
+ if (n.filter || n.sortField) return unsupported(n, type + ' filter/sort')
148
+ if ((type === 'table' && (array(n.rows).length > 200 || array(n.columns).length > 30)) ||
149
+ (['list', 'timeline', 'steps', 'keyvalue'].includes(type) && array(n.items || n.steps || n.pairs).length > 100)) return unsupported(n, type + ' size limit')
150
+ if (['row', 'col', 'grid', 'card'].includes(type)) {
151
+ const cols = Math.max(1, Math.min(4, Math.floor(Number(n.cols) || 2)))
152
+ return '<section class="genui-' + type + '"' + (type === 'grid' ? ' style="--genui-cols:' + cols + '"' : '') + '>' + (n.title ? '<h4>' + esc(n.title) + '</h4>' : '') + nodes(n.items, depth + 1) + '</section>'
153
+ }
154
+ if (type === 'text') { const tag = ['h1', 'h2', 'h3'].includes(n.size) ? n.size : 'p'; return '<' + tag + '>' + esc(n.content) + '</' + tag + '>' }
155
+ if (type === 'hero') return '<div class="genui-stat"><small>' + esc(n.label) + '</small><strong>' + esc(n.value) + '</strong><h4>' + esc(n.title) + '</h4><span>' + esc(n.subtitle) + '</span><span>' + esc(n.delta) + '</span>' + spark(n.spark) + '</div>'
156
+ if (type === 'stat') return '<div class="genui-stat"><small>' + esc(n.label) + '</small><strong>' + esc(n.value) + '</strong><span>' + esc(n.delta) + '</span>' + spark(n.spark) + '</div>'
157
+ if (type === 'badge') return '<span class="genui-badge">' + esc(n.label) + '</span>'
158
+ if (type === 'divider') return '<hr>'
159
+ if (type === 'spacer') return '<div class="genui-spacer"></div>'
160
+ if (type === 'progress' && !number(n.value)) return unsupported(n, 'progress value')
161
+ if (type === 'progress' && n.variant === 'ring') return '<div>' + esc(n.label) + ring(n.value, n.valueLabel || n.value + '%') + (number(n.target) ? '<small>目标 / Target: ' + esc(n.target) + '%</small>' : '') + '</div>'
162
+ if (type === 'progress') return '<div>' + esc(n.label) + '<progress max="100" value="' + Math.max(0, Math.min(100, Number(n.value) || 0)) + '"></progress><small>' + esc(n.valueLabel || String(n.value || 0) + '%') + '</small>' + (number(n.target) ? '<small> · 目标 / Target: ' + esc(n.target) + '%</small>' : '') + '</div>'
163
+ if (type === 'callout') return '<aside class="genui-callout"><strong>' + esc(n.title) + '</strong><p>' + esc(n.content) + '</p></aside>'
164
+ if (type === 'code' || type === 'json') return raw(type === 'code' ? n.code : n.value)
165
+ if (type === 'list' || type === 'timeline' || type === 'steps') return '<ul>' + array(n.items || n.steps).slice(0, 100).map(v => '<li>' + (v && typeof v === 'object' ? (v.type ? node(v, depth + 1) : '<strong>' + esc(v.title) + '</strong> ' + esc(v.desc) + ' ' + esc(v.time)) : esc(v)) + '</li>').join('') + '</ul>'
166
+ if (type === 'keyvalue') return '<dl>' + array(n.pairs).slice(0, 100).map(v => '<dt>' + esc(v?.key) + '</dt><dd>' + esc(v?.value) + '</dd>').join('') + '</dl>'
167
+ if (type === 'table') return table(n, depth)
168
+ if (type === 'file-tree') return fileTree(n.items, depth + 1)
169
+ if (type === 'breadcrumb') return '<nav aria-label="路径">' + array(n.items).map(esc).join(' › ') + '</nav>'
170
+ if (type === 'avatar') return '<span class="genui-badge">' + esc(n.name) + '</span>'
171
+ if (type === 'diff') {
172
+ if (array(n.diffs).length > 30) return unsupported(n, 'diff size limit')
173
+ return array(n.diffs).map(d => '<details class="genui-diff" open><summary>' + esc(d?.path) + '</summary><div class="genui-grid">' + (d?.oldText == null ? '<section>新增文件 / New file</section>' : '<section><strong>修改前 / Before</strong>' + raw(d.oldText) + '</section>') + '<section><strong>修改后 / After</strong>' + raw(d?.newText) + '</section></div></details>').join('')
174
+ }
175
+ if (type === 'chart') return chart(n)
176
+ if (type === 'echart' && !n.option && ['bar', 'line', 'pie'].includes(n.preset)) return '<small>ECharts 基础数据预览 / Basic preview</small>' + chart({ ...n, type: 'chart', kind: { bar: 'bars', line: 'line', pie: 'donut' }[n.preset] })
177
+ if (type === 'tabs') {
178
+ const id = 'genui-tabs-' + (++uid), tabs = array(n.tabs).slice(0, 30)
179
+ return '<div class="genui-tabs"><div role="tablist" aria-label="' + esc(n.title || '标签页') + '">' + tabs.map((v, i) => '<button type="button" role="tab" id="' + id + '-tab-' + i + '" aria-controls="' + id + '-panel-' + i + '" aria-selected="' + (i === 0) + '" tabindex="' + (i === 0 ? 0 : -1) + '" data-genui-tab="' + i + '">' + esc(v?.label) + '</button>').join('') + '</div>' + tabs.map((v, i) => '<div role="tabpanel" id="' + id + '-panel-' + i + '" aria-labelledby="' + id + '-tab-' + i + '"' + (i ? ' hidden' : '') + '>' + nodes(v?.items || v?.content, depth + 1) + '</div>').join('') + '</div>'
180
+ }
181
+ if (type === 'accordion') return array(n.items).slice(0, 30).map(v => '<details><summary>' + esc(v?.title) + '</summary>' + nodes(v?.items, depth + 1) + '</details>').join('')
182
+ return unsupported(n)
183
+ }
184
+ const body = Array.isArray(spec) ? nodes(spec, 0) : spec.type ? node(spec, 0) : nodes(spec.items, 0)
185
+ if (!body) throw Error('No components')
186
+ return '<section class="genui"><div class="genui-caption">DSH UI · 只读预览 / Read-only</div>' + (spec.title ? '<h3>' + esc(spec.title) + '</h3>' : '') + body + details(spec) + '</section>'
187
+ }
188
+
189
+ function html(source) {
190
+ if (typeof document === 'undefined' || String(source).length > 200000) return raw(source)
191
+ // Template contents are inert: source images cannot start fetching during sanitization.
192
+ const template = document.createElement('template')
193
+ template.innerHTML = String(source)
194
+ const allowed = new Set('title style div span p br hr h1 h2 h3 h4 h5 h6 strong em b i u s small sub sup pre code blockquote ul ol li dl dt dd table thead tbody tfoot tr td th caption colgroup col section article header footer main aside figure figcaption details summary progress'.split(' '))
195
+ function clean(parent) {
196
+ for (const child of Array.from(parent.children)) {
197
+ if (!allowed.has(child.localName)) { child.remove(); continue }
198
+ for (const attr of Array.from(child.attributes)) {
199
+ if (!['style', 'class', 'colspan', 'rowspan', 'value', 'max'].includes(attr.name)) child.removeAttribute(attr.name)
200
+ }
201
+ clean(child)
202
+ }
203
+ }
204
+ clean(template.content)
205
+ const policy = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'none'; connect-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'"
206
+ const srcDoc = '<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="' + policy + '"><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font:14px/1.6 system-ui;margin:16px;overflow-wrap:anywhere}table{border-collapse:collapse}td,th{padding:6px;border:1px solid #ccc}pre{white-space:pre-wrap}*{max-width:100%;box-sizing:border-box}</style></head><body>' + template.innerHTML + '</body></html>'
207
+ return '<section class="genui"><div class="genui-caption">HTML · 只读预览(脚本及外部资源已禁用)</div><iframe class="genui-html" sandbox="" referrerpolicy="no-referrer" title="HTML preview" srcdoc="' + esc(srcDoc) + '"></iframe></section>'
208
+ }
209
+ function activateTab(button, focus = false) {
210
+ const list = button.parentElement, tabs = Array.from(list.children)
211
+ tabs.forEach(tab => {
212
+ const active = tab === button
213
+ tab.setAttribute('aria-selected', String(active)); tab.tabIndex = active ? 0 : -1
214
+ const panel = Array.from(list.parentElement.children).find(p => p.id === tab.getAttribute('aria-controls'))
215
+ if (panel) panel.hidden = !active
216
+ })
217
+ if (focus) button.focus()
218
+ }
219
+ function compareCells(a, b) {
220
+ const x = numeric(a), y = numeric(b)
221
+ if (Number.isFinite(x) && Number.isFinite(y)) return x - y
222
+ if (Number.isFinite(x)) return -1
223
+ if (Number.isFinite(y)) return 1
224
+ return String(a ?? '').localeCompare(String(b ?? ''))
225
+ }
226
+ if (typeof document !== 'undefined') {
227
+ document.addEventListener('click', event => {
228
+ const button = event.target.closest?.('.genui button')
229
+ if (!button) return
230
+ if (button.hasAttribute('data-genui-tab')) activateTab(button)
231
+ if (button.hasAttribute('data-genui-sort')) {
232
+ const table = button.closest('table'), th = button.parentElement
233
+ const col = Number(button.dataset.genuiSort)
234
+ const previous = th.getAttribute('aria-sort'), direction = previous === 'ascending' ? 'descending' : previous === 'descending' ? 'none' : 'ascending'
235
+ Array.from(table.tHead.rows[0].cells).forEach(cell => cell.setAttribute('aria-sort', 'none'))
236
+ th.setAttribute('aria-sort', direction)
237
+ Array.from(table.tBodies).sort((a, b) => {
238
+ const order = Number(a.dataset.genuiOrder) - Number(b.dataset.genuiOrder)
239
+ if (direction === 'none') return order
240
+ const compared = compareCells(a.rows[0].cells[col]?.dataset.genuiValue, b.rows[0].cells[col]?.dataset.genuiValue)
241
+ return (direction === 'ascending' ? compared : -compared) || order
242
+ }).forEach(body => table.insertBefore(body, table.tFoot))
243
+ }
244
+ })
245
+ document.addEventListener('keydown', event => {
246
+ const button = event.target.closest?.('.genui [data-genui-tab]')
247
+ if (!button || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
248
+ const tabs = Array.from(button.parentElement.children), i = tabs.indexOf(button)
249
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? tabs.length - 1 : (i + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length
250
+ event.preventDefault(); activateTab(tabs[next], true)
251
+ })
252
+ }
253
+ return { render, html, compareCells }
254
+ })