dsh-xinqi-live2d 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 panmaci4676
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # dsh-live2d-emotion
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH 情绪 Live2D 挂件:每轮回复打一个情绪标签,屏幕右上角模型实时换表情。
4
+
5
+ ```sh
6
+ dsh plugin --profile web add dsh-live2d-emotion
7
+ ```
8
+
9
+ ## v2.0.0 重写说明
10
+
11
+ **挂件跑在独立 iframe 里。** 这是与 v1 的根本区别:
12
+
13
+ | | v1 | v2 |
14
+ | --- | --- | --- |
15
+ | 渲染位置 | 宿主 `shell.overlay` | **独立 iframe** |
16
+ | WebGL 崩了 | 整个 DSH 白屏 | **只影响那块区域** |
17
+ | CDN 挂了 | 拖垮宿主渲染树 | iframe 显示错误,宿主无感 |
18
+ | 宿主端依赖 | pixi + live2d + WebGL | **只有一个 iframe 标签** |
19
+
20
+ ## 装模型
21
+
22
+ 把模型放到(插件不带模型,通常几十 MB):
23
+
24
+ ```
25
+ ~/.dsh/live2d/<模型名>/<模型名>.model3.json
26
+ ```
27
+
28
+ 插件会在该目录及一级子目录里找唯一一个 `*.model3.json`。
29
+
30
+ ## 情绪标签
31
+
32
+ `live2d_report_emotion` 工具接受:`happy/开心`、`love/爱`、`shy/害羞`、`sad/难过`、
33
+ `cry/哭`、`angry/生气`、`confused/困惑`、`dizzy`、`nervous/紧张`、`excited/兴奋`、
34
+ `sleepy/困`、`neutral/平静`。
35
+
36
+ 表情 8 秒后自动回默认。
37
+
38
+ ## 配置
39
+
40
+ ```yaml
41
+ - id: live2d-emotion
42
+ config:
43
+ modelDir: /root/.dsh/live2d
44
+ modelFile: 大肥鱼.model3.json
45
+ size: 220
46
+ defaultEmotion: 默认
47
+ enabled: true
48
+ ```
49
+
50
+ ## 接口
51
+
52
+ | 方法 | 路径 | 说明 |
53
+ | --- | --- | --- |
54
+ | GET | `/-/live2d/frame` | 挂件页面(iframe src) |
55
+ | GET | `/-/live2d/state` | 状态 + 模型信息 |
56
+ | POST | `/-/live2d/emotion` | 上报情绪 |
57
+ | GET | `/-/live2d/events` | SSE |
58
+ | GET | `/-/live2d/model/*` | 模型文件(防穿越) |
59
+ | GET | `/-/live2d/info` | 诊断 |
60
+
61
+ ## 依赖
62
+
63
+ 需要浏览器能访问 `cdn.jsdelivr.net`(pixi / pixi-live2d-display / cubism core 都在 iframe 内加载)。
64
+
65
+ ## License
66
+
67
+ MIT
@@ -0,0 +1,14 @@
1
+ # dsh-xinqi-live2d — bundle patch
2
+ #
3
+ # v2.0.0 重写:挂件渲染在**独立 iframe** 里,与宿主前端渲染树完全隔离。
4
+ # 即便 Live2D/WebGL 在 iframe 里彻底崩掉,也不会影响 DSH 本体。
5
+ #
6
+ # 配置(全部有默认值):
7
+ # modelDir 模型根目录(默认 <DSH_HOME>/live2d)
8
+ # modelFile 指定入口 .model3.json(默认自动找)
9
+ # size 挂件边长 px(默认 220)
10
+ # defaultEmotion 无情绪时的表情名(默认「默认」)
11
+ # enabled 总开关(默认 true)
12
+ - insert:
13
+ - id: live2d-emotion
14
+ name: './lib/index.js'
package/lib/client.js ADDED
@@ -0,0 +1,223 @@
1
+ /**
2
+ * dsh-xinqi-live2d v2 — browser half
3
+ *
4
+ * **极简**:只渲染一个 iframe + 拖动条。
5
+ * 所有 Live2D / WebGL / CDN 的活都在 iframe 内部完成,
6
+ * 与宿主前端渲染树完全隔离 —— iframe 里彻底崩掉也不会影响 DSH。
7
+ *
8
+ * v1 的教训:把 pixi 塞进 shell.overlay 会让整个页面 "Failed to load plugins"。
9
+ */
10
+ window.__ModuleLoader__.load({
11
+ id: 'dsh-xinqi-live2d',
12
+ factory: require => {
13
+ const module = { exports: {} }
14
+ const exports = module.exports
15
+ const React = require('react')
16
+ const { createElement: h, useState, useEffect, useRef, useCallback } = React
17
+
18
+ const NS = 'live2d-emotion'
19
+ const API = '/-/live2d'
20
+ const POS_KEY = 'dsh-xinqi-live2d.pos.v2'
21
+ const HIDE_KEY = 'dsh-xinqi-live2d.hidden.v2'
22
+
23
+ const C = {
24
+ fg: 'var(--dsw-alias-label-primary, #e6edf3)',
25
+ fgDim: 'var(--dsw-alias-label-secondary, #8b949e)',
26
+ border: 'var(--dsw-alias-border-l2, rgba(128,128,128,.32))',
27
+ bg: 'var(--dsw-alias-bg-layer-2, rgba(22,27,34,.94))',
28
+ }
29
+
30
+ function loadPos() {
31
+ try {
32
+ const raw = window.localStorage.getItem(POS_KEY)
33
+ if (raw) {
34
+ const p = JSON.parse(raw)
35
+ if (typeof p.x === 'number' && typeof p.y === 'number') return p
36
+ }
37
+ } catch {}
38
+ return null
39
+ }
40
+ function savePos(p) { try { window.localStorage.setItem(POS_KEY, JSON.stringify(p)) } catch {} }
41
+ function loadHidden() { try { return window.localStorage.getItem(HIDE_KEY) === '1' } catch { return false } }
42
+ function saveHidden(v) { try { window.localStorage.setItem(HIDE_KEY, v ? '1' : '0') } catch {} }
43
+
44
+ function Widget() {
45
+ const [hidden, setHidden] = useState(loadHidden)
46
+ const [pos, setPos] = useState(() => loadPos() || { x: 16, y: 72 })
47
+ const [collapsed, setCollapsed] = useState(false)
48
+ const [size, setSize] = useState(220)
49
+ const [label, setLabel] = useState('平静')
50
+ const [ready, setReady] = useState(false)
51
+ const dragRef = useRef(null)
52
+ const posRef = useRef(pos)
53
+ posRef.current = pos
54
+
55
+ // 拉一次尺寸 + 情绪标签
56
+ useEffect(() => {
57
+ if (hidden) return undefined
58
+ let stop = false
59
+ fetch(`${API}/state`, { credentials: 'same-origin', cache: 'no-store' })
60
+ .then((r) => r.json())
61
+ .then((d) => {
62
+ if (stop || !d || d.ok === false) return
63
+ const v = d.value || {}
64
+ if (typeof v.size === 'number') setSize(v.size)
65
+ if (v.label) setLabel(v.label)
66
+ setReady(true)
67
+ })
68
+ .catch(() => setReady(true))
69
+ return () => { stop = true }
70
+ }, [hidden])
71
+
72
+ // 情绪标签(轮询,轻量)
73
+ useEffect(() => {
74
+ if (hidden) return undefined
75
+ const tick = () => {
76
+ if (document.visibilityState === 'hidden') return
77
+ fetch(`${API}/state`, { credentials: 'same-origin', cache: 'no-store' })
78
+ .then((r) => r.json())
79
+ .then((d) => {
80
+ const v = d && d.value
81
+ if (v && v.label) setLabel(v.label)
82
+ if (v && typeof v.size === 'number') setSize(v.size)
83
+ })
84
+ .catch(() => {})
85
+ }
86
+ const iv = setInterval(tick, 4000)
87
+ return () => clearInterval(iv)
88
+ }, [hidden])
89
+
90
+ const onDown = useCallback((e) => {
91
+ if (e.target.closest('[data-nodrag]')) return
92
+ const r = e.currentTarget.getBoundingClientRect()
93
+ dragRef.current = { dx: e.clientX - r.left, dy: e.clientY - r.top }
94
+ e.currentTarget.setPointerCapture?.(e.pointerId)
95
+ }, [])
96
+ const onMove = useCallback((e) => {
97
+ const d = dragRef.current
98
+ if (!d) return
99
+ setPos({
100
+ x: Math.max(0, Math.min(window.innerWidth - 100, e.clientX - d.dx)),
101
+ y: Math.max(0, Math.min(window.innerHeight - 80, e.clientY - d.dy)),
102
+ })
103
+ }, [])
104
+ const onUp = useCallback(() => {
105
+ if (dragRef.current) savePos(posRef.current)
106
+ dragRef.current = null
107
+ }, [])
108
+
109
+ if (hidden) {
110
+ return h('button', {
111
+ type: 'button',
112
+ title: '显示 Live2D',
113
+ onClick: () => { saveHidden(false); setHidden(false) },
114
+ style: {
115
+ position: 'absolute', right: '12px', top: '12px', zIndex: 30,
116
+ width: '34px', height: '34px', borderRadius: '10px',
117
+ border: `1px solid ${C.border}`, background: C.bg, color: C.fg,
118
+ cursor: 'pointer', fontSize: '15px', lineHeight: 1,
119
+ boxShadow: '0 4px 14px rgba(0,0,0,.24)',
120
+ },
121
+ }, '🐟')
122
+ }
123
+
124
+ const btn = {
125
+ width: '22px', height: '22px', borderRadius: '6px', border: 'none',
126
+ background: 'transparent', color: C.fgDim, cursor: 'pointer',
127
+ fontSize: '12px', lineHeight: 1, display: 'grid', placeItems: 'center',
128
+ }
129
+
130
+ const w = collapsed ? 120 : size
131
+ const hgt = collapsed ? 32 : size + 28
132
+
133
+ return h('div', {
134
+ onPointerDown: onDown,
135
+ onPointerMove: onMove,
136
+ onPointerUp: onUp,
137
+ style: {
138
+ position: 'absolute',
139
+ left: pos.x + 'px',
140
+ top: pos.y + 'px',
141
+ zIndex: 30,
142
+ width: w + 'px',
143
+ height: hgt + 'px',
144
+ borderRadius: '14px',
145
+ background: C.bg,
146
+ border: `1px solid ${C.border}`,
147
+ boxShadow: '0 10px 30px rgba(0,0,0,.30)',
148
+ backdropFilter: 'blur(10px)',
149
+ overflow: 'hidden',
150
+ cursor: 'grab',
151
+ userSelect: 'none',
152
+ touchAction: 'none',
153
+ display: 'flex',
154
+ flexDirection: 'column',
155
+ },
156
+ },
157
+ // 标题栏
158
+ h('div', {
159
+ style: {
160
+ display: 'flex', alignItems: 'center', gap: '4px',
161
+ padding: '5px 7px', flex: 'none',
162
+ borderBottom: collapsed ? 'none' : `1px solid ${C.border}`,
163
+ },
164
+ },
165
+ h('span', {
166
+ style: {
167
+ flex: 1, minWidth: 0, fontSize: '11px', color: C.fgDim,
168
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
169
+ },
170
+ }, (collapsed ? '🐟 ' : '') + label),
171
+ h('button', {
172
+ type: 'button', 'data-nodrag': true, title: collapsed ? '展开' : '收起',
173
+ onClick: () => setCollapsed(!collapsed), style: btn,
174
+ }, collapsed ? '▢' : '—'),
175
+ h('button', {
176
+ type: 'button', 'data-nodrag': true, title: '隐藏',
177
+ onClick: () => { saveHidden(true); setHidden(true) }, style: btn,
178
+ }, '✕'),
179
+ ),
180
+
181
+ // iframe 区域:Live2D 全部跑在这里,与宿主隔离
182
+ !collapsed && h('iframe', {
183
+ 'data-nodrag': true,
184
+ src: ready ? `${API}/frame2` : 'about:blank',
185
+ title: 'Live2D',
186
+ sandbox: 'allow-scripts allow-same-origin',
187
+ style: {
188
+ flex: 1,
189
+ width: '100%',
190
+ border: 'none',
191
+ background: 'transparent',
192
+ display: 'block',
193
+ },
194
+ }),
195
+ )
196
+ }
197
+
198
+ const name = 'dsh-xinqi-live2d'
199
+ const inject = ['slots']
200
+
201
+ function apply(ctx) {
202
+ // 照抄 access-gate / console-hm 的写法:inject 的回调直接返回 register 的结果。
203
+ // 不要在中间再包一层 ctx.effect —— 那会让注册时机和声明生命周期错位。
204
+ try {
205
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
206
+ name: 'shell.overlay',
207
+ id: 'live2d-emotion-widget',
208
+ order: 90,
209
+ label: () => 'Live2D',
210
+ locale: NS,
211
+ inject: () => ({}),
212
+ }, Widget))
213
+ } catch (e) {
214
+ try { console.warn('[live2d-emotion] 挂件注册失败(已忽略):', e) } catch {}
215
+ }
216
+ }
217
+
218
+ exports.name = name
219
+ exports.inject = inject
220
+ exports.apply = apply
221
+ return module.exports
222
+ },
223
+ })
package/lib/index.js ADDED
@@ -0,0 +1,536 @@
1
+ /**
2
+ * dsh-xinqi-live2d v2 — host half
3
+ *
4
+ * 与 v1 的根本区别:**挂件跑在独立 iframe 里**。
5
+ *
6
+ * v1 把 pixi 的 WebGL 上下文塞进宿主的 shell.overlay,一旦渲染异常
7
+ * (CDN 失败、WebGL 初始化失败、模型坏)就会污染宿主渲染树,表现就是
8
+ * 整个页面 "Failed to load plugins"。v2 把这一切关进 iframe:
9
+ * · iframe 里的脚本崩了 → 只是那块区域白,DSH 本体不受影响
10
+ * · iframe 用 sandbox 限制,拿不到宿主 DOM
11
+ * · 宿主端只剩一个 <div> + <iframe>,零 WebGL、零 CDN
12
+ *
13
+ * 路由:
14
+ * GET /-/live2d/frame 挂件页面(iframe src,完整自包含 HTML)
15
+ * GET /-/live2d/model/* 模型文件(流式,防穿越)
16
+ * GET /-/live2d/state 当前情绪 + 模型信息
17
+ * POST /-/live2d/emotion 上报情绪
18
+ * GET /-/live2d/events SSE
19
+ * GET /-/live2d/info 诊断
20
+ */
21
+
22
+ import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
23
+ import { join, extname, normalize, sep, basename } from 'node:path'
24
+ import { homedir } from 'node:os'
25
+
26
+ export const name = 'dsh-xinqi-live2d'
27
+ export const inject = ['webServer']
28
+
29
+ const PREFIX = '/-/live2d'
30
+
31
+ /** 情绪 → 候选表情名。按模型里真实存在的挑。 */
32
+ const EMOTION_MAP = {
33
+ happy: ['爱心眼', '><', '默认'],
34
+ 开心: ['爱心眼', '><', '默认'],
35
+ love: ['爱心眼', '脸红'],
36
+ 爱: ['爱心眼', '脸红'],
37
+ shy: ['脸红', '><'],
38
+ 害羞: ['脸红', '><'],
39
+ sad: ['流泪', '><'],
40
+ 难过: ['流泪', '><'],
41
+ cry: ['流泪'],
42
+ 哭: ['流泪'],
43
+ angry: ['黑脸', '><'],
44
+ 生气: ['黑脸', '><'],
45
+ confused: ['圈圈眼', '屑屑眼'],
46
+ 困惑: ['圈圈眼', '屑屑眼'],
47
+ dizzy: ['圈圈眼'],
48
+ nervous: ['流冷汗'],
49
+ 紧张: ['流冷汗'],
50
+ excited: ['><', '爱心眼'],
51
+ 兴奋: ['><', '爱心眼'],
52
+ sleepy: ['默认'],
53
+ 困: ['默认'],
54
+ neutral: ['默认'],
55
+ 平静: ['默认'],
56
+ }
57
+
58
+ const HOLD_MS = 8000
59
+
60
+ const MIME = {
61
+ '.json': 'application/json; charset=utf-8',
62
+ '.moc3': 'application/octet-stream',
63
+ '.png': 'image/png',
64
+ '.jpg': 'image/jpeg',
65
+ '.webp': 'image/webp',
66
+ '.mp3': 'audio/mpeg',
67
+ '.wav': 'audio/wav',
68
+ }
69
+
70
+ function dshHome() {
71
+ return process.env.DSH_HOME ? process.env.DSH_HOME : join(homedir(), '.dsh')
72
+ }
73
+
74
+ function modelDirOf(config) {
75
+ const c = config && typeof config.modelDir === 'string' ? config.modelDir.trim() : ''
76
+ return c || join(dshHome(), 'live2d')
77
+ }
78
+
79
+ function listDirs(dir) {
80
+ try {
81
+ return readdirSync(dir)
82
+ .map((n) => join(dir, n))
83
+ .filter((p) => {
84
+ try { return statSync(p).isDirectory() } catch { return false }
85
+ })
86
+ } catch { return [] }
87
+ }
88
+
89
+ /** 找 .model3.json。返回 { dir, file } 或 null。 */
90
+ function findModel(root, prefer) {
91
+ if (prefer && typeof prefer === 'string' && prefer.trim()) {
92
+ const f = prefer.trim()
93
+ if (existsSync(join(root, f))) return { dir: root, file: f }
94
+ for (const d of listDirs(root)) {
95
+ if (existsSync(join(d, f))) return { dir: d, file: f }
96
+ }
97
+ }
98
+ for (const d of [root, ...listDirs(root)]) {
99
+ let hits = []
100
+ try { hits = readdirSync(d).filter((n) => n.endsWith('.model3.json')) } catch { continue }
101
+ if (hits.length === 1) return { dir: d, file: hits[0] }
102
+ if (hits.length > 1) {
103
+ const same = hits.find((h) => h.startsWith(basename(d)))
104
+ return { dir: d, file: same || hits[0] }
105
+ }
106
+ }
107
+ return null
108
+ }
109
+
110
+ /** 读模型元信息。失败返回 null(绝不抛)。 */
111
+ function readModelMeta(found) {
112
+ try {
113
+ const j = JSON.parse(readFileSync(join(found.dir, found.file), 'utf8'))
114
+ const fr = j.FileReferences || {}
115
+ return {
116
+ file: found.file,
117
+ expressions: (fr.Expressions || []).map((e) => e.Name).filter(Boolean),
118
+ textures: (fr.Textures || []).length,
119
+ hasMoc: !!fr.Moc,
120
+ }
121
+ } catch {
122
+ return null
123
+ }
124
+ }
125
+
126
+ /* 情绪单例 */
127
+ const emotion = { tag: 'neutral', label: '平静', expression: '默认', at: Date.now(), subs: new Set() }
128
+
129
+ function snap(config, modelMeta) {
130
+ const fresh = Date.now() - emotion.at <= HOLD_MS
131
+ const def = (config && typeof config.defaultEmotion === 'string' && config.defaultEmotion.trim()) || '默认'
132
+ return {
133
+ tag: fresh ? emotion.tag : 'neutral',
134
+ label: fresh ? emotion.label : '平静',
135
+ expression: fresh ? emotion.expression : def,
136
+ at: emotion.at,
137
+ msLeft: fresh ? Math.max(0, HOLD_MS - (Date.now() - emotion.at)) : 0,
138
+ holdMs: HOLD_MS,
139
+ }
140
+ }
141
+
142
+ function exprFor(tag, config, modelMeta) {
143
+ const t = String(tag || '').trim()
144
+ const cands = EMOTION_MAP[t] || EMOTION_MAP[t.toLowerCase()] || []
145
+ const def = (config && typeof config.defaultEmotion === 'string' && config.defaultEmotion.trim()) || '默认'
146
+ if (modelMeta && modelMeta.expressions.length) {
147
+ for (const c of cands) if (modelMeta.expressions.includes(c)) return c
148
+ }
149
+ return cands[0] || def
150
+ }
151
+
152
+ /** 一套默认表情列表:模型不在时也能让 iframe 有东西可画。 */
153
+ const DEFAULT_EXPRESSIONS = ['默认']
154
+
155
+ /* ── HTTP ─────────────────────────────────────────────── */
156
+
157
+ function send(res, code, type, body) {
158
+ res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store' })
159
+ res.end(body)
160
+ }
161
+ const json = (res, code, obj) => send(res, code, 'application/json; charset=utf-8', JSON.stringify(obj))
162
+
163
+ function readBody(req, limit = 65536) {
164
+ return new Promise((resolve) => {
165
+ const chunks = []
166
+ let n = 0
167
+ req.on('data', (c) => {
168
+ n += c.length
169
+ if (n > limit) { try { req.destroy() } catch {} ; resolve({}) }
170
+ else chunks.push(c)
171
+ })
172
+ req.on('end', () => {
173
+ try { const s = Buffer.concat(chunks).toString('utf8'); resolve(s ? JSON.parse(s) : {}) }
174
+ catch { resolve({}) }
175
+ })
176
+ req.on('error', () => resolve({}))
177
+ })
178
+ }
179
+
180
+ /** URL → 模型目录下的真实文件路径,防穿越。 */
181
+ function resolveSafe(rootDir, urlPath) {
182
+ let rel
183
+ try { rel = decodeURIComponent(urlPath) } catch { return null }
184
+ rel = rel.replace(/^\/+/, '')
185
+ if (!rel || rel.includes('\0')) return null
186
+ const norm = normalize(rel)
187
+ if (norm.startsWith('..') || norm.includes(`..${sep}`) || rel.startsWith('/')) return null
188
+ const abs = normalize(join(rootDir, norm))
189
+ if (!abs.startsWith(normalize(rootDir + sep))) return null
190
+ return abs
191
+ }
192
+
193
+ /* ── iframe 页面(完全自包含,与宿主隔离) ────────────── */
194
+
195
+ function frameHtml(config) {
196
+ const size = typeof config.size === 'number' && config.size > 0 ? config.size : 220
197
+ return `<!doctype html><html lang="zh"><head><meta charset="utf-8">
198
+ <meta name="viewport" content="width=device-width,initial-scale=1">
199
+ <title>Live2D</title>
200
+ <style>
201
+ html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:transparent}
202
+ #c{display:block;width:100%;height:100%}
203
+ #tip{
204
+ position:absolute;inset:0;display:flex;flex-direction:column;gap:8px;
205
+ align-items:center;justify-content:center;text-align:center;
206
+ font:12px/1.6 system-ui,-apple-system,"PingFang SC",sans-serif;color:#8b949e;
207
+ padding:12px;box-sizing:border-box
208
+ }
209
+ #tip .e{color:#f85149}
210
+ button{
211
+ font:inherit;font-size:11px;padding:4px 10px;border-radius:8px;cursor:pointer;
212
+ border:1px solid rgba(128,128,128,.32);background:transparent;color:#e6edf3
213
+ }
214
+ </style></head><body>
215
+ <canvas id="c"></canvas>
216
+ <div id="tip">准备中…</div>
217
+ <script type="module">
218
+ const SIZE = ${size};
219
+ const tip = document.getElementById('tip');
220
+ const canvas = document.getElementById('c');
221
+
222
+ function show(msg, isErr, retry) {
223
+ tip.innerHTML = '';
224
+ const s = document.createElement('span');
225
+ if (isErr) s.className = 'e';
226
+ s.textContent = msg;
227
+ tip.appendChild(s);
228
+ if (retry) {
229
+ const b = document.createElement('button');
230
+ b.textContent = '重试';
231
+ b.onclick = () => location.reload();
232
+ tip.appendChild(b);
233
+ }
234
+ tip.style.display = 'flex';
235
+ }
236
+ function hide() { tip.style.display = 'none'; }
237
+
238
+ /* 加载外部脚本 */
239
+ function loadScript(src) {
240
+ return new Promise((res, rej) => {
241
+ const el = document.createElement('script');
242
+ el.src = src;
243
+ el.onload = res;
244
+ el.onerror = () => rej(new Error('加载失败: ' + src));
245
+ document.head.appendChild(el);
246
+ });
247
+ }
248
+
249
+ let app = null, model = null;
250
+
251
+ async function boot() {
252
+ show('加载引擎…');
253
+ // ① Cubism Core(必须先于 display)
254
+ if (!window.Live2DCubismCore) {
255
+ await loadScript('https://cdn.jsdelivr.net/npm/live2dcubismcore@1.0.0/live2dcubismcore.min.js');
256
+ }
257
+ // ② pixi 7 —— 用 **UMD** 版(挂到 window.PIXI)。
258
+ // 不能用 .mjs:cubism4 的 UMD 构建只认 window.PIXI,
259
+ // 而 cubism4 的 .es.js 又引用了 @pixi/utils 这类裸模块名,浏览器解析不了。
260
+ if (!window.PIXI) {
261
+ await loadScript('https://cdn.jsdelivr.net/npm/pixi.js@7.4.2/dist/pixi.min.js');
262
+ }
263
+ if (!window.PIXI) throw new Error('pixi 加载失败');
264
+
265
+ // ③ display 的 cubism4 **UMD** 构建(依赖已内联,且会挂到 window.PIXI.live2d)
266
+ await loadScript('https://cdn.jsdelivr.net/npm/pixi-live2d-display@0.4.0/dist/cubism4.min.js');
267
+ const L2D = window.PIXI?.live2d;
268
+ if (!L2D || typeof L2D.Live2DModel?.from !== 'function') {
269
+ throw new Error('pixi-live2d-display 未就绪');
270
+ }
271
+ // ④ 显式启动框架
272
+ if (typeof L2D.startUpCubism4 === 'function') await L2D.startUpCubism4();
273
+ const pixi = window.PIXI;
274
+
275
+ // ⑤ 拿模型路径
276
+ const info = await fetch('./info', { cache: 'no-store' }).then(r => r.json());
277
+ const file = info?.value?.model?.file;
278
+ if (!file) throw new Error('服务器上没找到模型');
279
+
280
+ show('加载模型…');
281
+ app = new pixi.Application({
282
+ view: canvas,
283
+ backgroundAlpha: 0,
284
+ antialias: true,
285
+ resolution: Math.min(window.devicePixelRatio || 1, 1.5),
286
+ autoDensity: true,
287
+ width: SIZE,
288
+ height: SIZE,
289
+ });
290
+
291
+ model = await L2D.Live2DModel.from('./model/' + encodeURIComponent(file), { autoInteract: false });
292
+ app.stage.addChild(model);
293
+
294
+ // 缩放居中
295
+ const w = model.internalModel?.originalWidth || model.width;
296
+ const h = model.internalModel?.originalHeight || model.height;
297
+ const s = Math.min(SIZE / w, SIZE / h) * 0.98;
298
+ model.scale.set(s);
299
+ model.x = (SIZE - w * s) / 2;
300
+ model.y = (SIZE - h * s) / 2;
301
+
302
+ hide();
303
+
304
+ // ⑥ 订阅情绪
305
+ try {
306
+ const es = new EventSource('./events');
307
+ es.onmessage = (ev) => {
308
+ try {
309
+ const d = JSON.parse(ev.data);
310
+ if (d && d.expression) model.expression(d.expression);
311
+ } catch {}
312
+ };
313
+ } catch {}
314
+ }
315
+
316
+ boot().catch(e => {
317
+ show('⚠ ' + (e && e.message ? e.message : e), true, true);
318
+ // 把错误抛给宿主控制台,便于排查(不影响宿主)
319
+ try { console.error('[live2d]', e); } catch {}
320
+ });
321
+ </script></body></html>`
322
+ }
323
+
324
+ /* ── 路由注册 ─────────────────────────────────────────── */
325
+
326
+ export function registerRoutes(server, config = {}) {
327
+ if (!server || typeof server.register !== 'function') return () => {}
328
+
329
+ const root = modelDirOf(config)
330
+ const found = findModel(root, config.modelFile)
331
+ const meta = found ? readModelMeta(found) : null
332
+
333
+ const route = (path, kind, handler) =>
334
+ server.register({ kind: kind || 'exact', path: `${PREFIX}${path}`, handler })
335
+
336
+ const disposers = [
337
+ /** iframe 页面(/frame2 是刻意换的新路径,避开浏览器对旧 /frame 的缓存) */
338
+ route('/frame2', 'exact', async (_req, res) => {
339
+ const html = frameHtml(config)
340
+ res.writeHead(200, {
341
+ 'content-type': 'text/html; charset=utf-8',
342
+ 'cache-control': 'no-store, no-cache, must-revalidate, max-age=0',
343
+ pragma: 'no-cache',
344
+ expires: '0',
345
+ 'x-frame-options': 'SAMEORIGIN',
346
+ })
347
+ res.end(html)
348
+ }),
349
+
350
+ /** iframe 页面 */
351
+ route('/frame', 'exact', async (_req, res) => {
352
+ const html = frameHtml(config)
353
+ res.writeHead(200, {
354
+ 'content-type': 'text/html; charset=utf-8',
355
+ // 三重禁缓存:iframe 页面改版后必须立刻生效,不能吃到旧副本
356
+ 'cache-control': 'no-store, no-cache, must-revalidate, max-age=0',
357
+ pragma: 'no-cache',
358
+ expires: '0',
359
+ 'x-frame-options': 'SAMEORIGIN',
360
+ })
361
+ res.end(html)
362
+ }),
363
+
364
+ /** 状态 */
365
+ route('/state', 'exact', async (_req, res) => {
366
+ json(res, 200, {
367
+ ok: true,
368
+ value: {
369
+ ...snap(config, meta),
370
+ model: meta,
371
+ modelDir: root,
372
+ size: typeof config.size === 'number' ? config.size : 220,
373
+ },
374
+ })
375
+ }),
376
+
377
+ /** 上报情绪 */
378
+ route('/emotion', 'exact', async (req, res) => {
379
+ if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'POST only' })
380
+ const body = await readBody(req)
381
+ const tag = typeof body.tag === 'string' ? body.tag.trim() : ''
382
+ if (!tag) return json(res, 400, { ok: false, error: 'tag required' })
383
+ emotion.tag = tag
384
+ emotion.label = (typeof body.label === 'string' && body.label.trim()) || tag
385
+ emotion.expression = exprFor(tag, config, meta)
386
+ emotion.at = Date.now()
387
+ const s = snap(config, meta)
388
+ for (const fn of emotion.subs) { try { fn(s) } catch {} }
389
+ json(res, 200, { ok: true, value: s })
390
+ }),
391
+
392
+ /** SSE */
393
+ route('/events', 'exact', async (req, res) => {
394
+ res.writeHead(200, {
395
+ 'content-type': 'text/event-stream; charset=utf-8',
396
+ 'cache-control': 'no-store',
397
+ connection: 'keep-alive',
398
+ 'x-accel-buffering': 'no',
399
+ })
400
+ const push = (s) => { try { res.write(`data: ${JSON.stringify(s)}\n\n`) } catch {} }
401
+ push(snap(config, meta))
402
+ emotion.subs.add(push)
403
+ const ping = setInterval(() => { try { res.write(': ping\n\n') } catch {} }, 20000)
404
+ const bye = () => {
405
+ clearInterval(ping)
406
+ emotion.subs.delete(push)
407
+ try { res.end() } catch {}
408
+ }
409
+ req.on('close', bye)
410
+ req.on('error', bye)
411
+ }),
412
+
413
+ /** 模型文件 */
414
+ route('/model', 'prefix', async (req, res) => {
415
+ if (!found) return json(res, 503, { ok: false, error: '没有模型' })
416
+ let pn
417
+ try { pn = new URL(req.url, 'http://x').pathname } catch { return json(res, 400, { ok: false }) }
418
+ const rel = pn.slice(`${PREFIX}/model`.length)
419
+ const abs = resolveSafe(found.dir, rel)
420
+ if (!abs) return json(res, 403, { ok: false, error: 'forbidden' })
421
+ let st
422
+ try { st = statSync(abs) } catch { return json(res, 404, { ok: false, error: 'not found' }) }
423
+ if (!st.isFile()) return json(res, 404, { ok: false })
424
+ res.writeHead(200, {
425
+ 'content-type': MIME[extname(abs).toLowerCase()] || 'application/octet-stream',
426
+ 'content-length': st.size,
427
+ 'cache-control': 'public, max-age=3600',
428
+ })
429
+ createReadStream(abs).pipe(res)
430
+ }),
431
+
432
+ /** 诊断 */
433
+ route('/info', 'exact', async (_req, res) => {
434
+ json(res, 200, {
435
+ ok: true,
436
+ value: { modelDir: root, model: meta, emotion: snap(config, meta), hasModel: !!found },
437
+ })
438
+ }),
439
+ ]
440
+
441
+ return () => { for (const d of disposers) { try { d() } catch {} } }
442
+ }
443
+
444
+ /* ── 情绪工具(给预设调用) ───────────────────────────── */
445
+
446
+ function registerTool(ctx, config, getMeta) {
447
+ ctx.inject(['tools'], (tctx) => {
448
+ try {
449
+ tctx.tools.register({
450
+ name: 'live2d_report_emotion',
451
+ description:
452
+ '上报你此刻的情绪,屏幕右上角的 Live2D 挂件会换成对应表情(8 秒后回默认)。' +
453
+ '每轮回复前调用一次。可用标签:happy/开心、love/爱、shy/害羞、sad/难过、cry/哭、' +
454
+ 'angry/生气、confused/困惑、dizzy、nervous/紧张、sleepy/困、excited/兴奋、neutral/平静。',
455
+ parameters: {
456
+ type: 'object',
457
+ additionalProperties: false,
458
+ properties: {
459
+ tag: { type: 'string', required: true, description: '情绪标签,如 happy / 害羞' },
460
+ label: { type: 'string', description: '给用户看的中文短语(可省略)' },
461
+ },
462
+ },
463
+ output: {
464
+ schema: {
465
+ type: 'object',
466
+ additionalProperties: false,
467
+ properties: {
468
+ ok: { type: 'boolean', required: true },
469
+ expression: { type: 'string' },
470
+ label: { type: 'string' },
471
+ error: { type: 'string' },
472
+ },
473
+ },
474
+ render: (_a, v) => [{
475
+ type: 'text',
476
+ text: v.ok ? `情绪已上报:${v.label || ''}(${v.expression || '默认'})` : `上报失败:${v.error || ''}`,
477
+ }],
478
+ },
479
+ async execute(args) {
480
+ const tag = String(args?.tag || '').trim()
481
+ if (!tag) return { ok: false, error: 'tag 不能为空' }
482
+ emotion.tag = tag
483
+ emotion.label = String(args?.label || '').trim() || tag
484
+ emotion.expression = exprFor(tag, config, getMeta())
485
+ emotion.at = Date.now()
486
+ const s = snap(config, getMeta())
487
+ for (const fn of emotion.subs) { try { fn(s) } catch {} }
488
+ return { ok: true, expression: s.expression, label: s.label }
489
+ },
490
+ })
491
+ } catch (e) {
492
+ ctx.logger?.warn?.(`[live2d-emotion] 工具注册失败(已忽略):${e?.message || e}`)
493
+ }
494
+ })
495
+ }
496
+
497
+ /* ── 插件入口 ─────────────────────────────────────────── */
498
+
499
+ export function apply(ctx, config = {}) {
500
+ if (config && config.enabled === false) return
501
+
502
+ const root = modelDirOf(config)
503
+ let found = null
504
+ let meta = null
505
+ try {
506
+ found = findModel(root, config.modelFile)
507
+ meta = found ? readModelMeta(found) : null
508
+ } catch {}
509
+
510
+ try { registerTool(ctx, config, () => (found ? meta : null)) } catch (e) {
511
+ ctx.logger?.warn?.(`[live2d-emotion] 工具挂载异常(已忽略):${e?.message || e}`)
512
+ }
513
+
514
+ ctx.inject(['webServer'], (webCtx) => {
515
+ webCtx.effect(() => {
516
+ try {
517
+ const server = webCtx.get('webServer')
518
+ const dispose = registerRoutes(server, config)
519
+ return () => { try { dispose() } catch {} }
520
+ } catch (e) {
521
+ webCtx.logger?.warn?.(`[live2d-emotion] 路由挂载失败(已忽略):${e?.message || e}`)
522
+ return () => {}
523
+ }
524
+ }, 'live2d-emotion: routes')
525
+
526
+ try {
527
+ if (meta) {
528
+ webCtx.logger?.info?.(`[live2d-emotion] 模型就绪:${meta.file}(${meta.expressions.length} 表情 / ${meta.textures} 贴图)`)
529
+ } else {
530
+ webCtx.logger?.warn?.(`[live2d-emotion] 未找到模型,请放到 ${root}/<名字>/<名字>.model3.json`)
531
+ }
532
+ } catch {}
533
+ })
534
+ }
535
+
536
+ export default { name, inject, apply }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "dsh-xinqi-live2d",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "DSH 情绪 Live2D 挂件:每轮回复打情绪标签,右上角模型换表情。挂件渲染在独立 iframe 里,与宿主前端完全隔离,不会因渲染异常拖垮 DSH。",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./client": "./lib/client.js",
11
+ "./cordis.patch.yml": "./cordis.patch.yml",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "lib",
16
+ "cordis.patch.yml",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "dsh",
21
+ "dsh-plugin",
22
+ "deepseek-harness",
23
+ "live2d",
24
+ "emotion"
25
+ ],
26
+ "author": {
27
+ "name": "panmaci4676",
28
+ "url": "https://github.com/panmaci4676"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/panmaci4676/dsh-xinqi-live2d.git"
33
+ },
34
+ "homepage": "https://github.com/panmaci4676/dsh-xinqi-live2d#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/panmaci4676/dsh-xinqi-live2d/issues"
37
+ },
38
+ "dsh": {
39
+ "bundle": {
40
+ "patch": "./cordis.patch.yml"
41
+ },
42
+ "client": {
43
+ "platform": "web",
44
+ "external": [
45
+ "react"
46
+ ]
47
+ }
48
+ },
49
+ "peerDependencies": {
50
+ "react": "^18.2.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "react": {
54
+ "optional": true
55
+ }
56
+ }
57
+ }