@morgan9668/dsh-llm-gateway 1.2.1 → 1.3.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/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "@morgan9668/dsh-llm-gateway",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
- "description": "Local OpenAI-compatible gateway that exposes every model registered on the DSH llm service (DeepSeek, WorkBuddy, our-free-model) so external clients such as Codex can use them.",
5
+ "description": "本地 OpenAI 兼容网关,把 DSH 里注册的每个模型暴露给 Codex 等外部客户端;同时接管任务完成通知(飞书 / 钉钉 / 企业微信 / 微信,含 DSH 界面闪动)。",
6
6
  "author": "chenzhao",
7
7
  "exports": {
8
8
  ".": "./index.js",
9
+ "./client": "./client.js",
9
10
  "./package.json": "./package.json",
10
11
  "./locale/*.json": "./locale/*.json",
11
12
  "./icon": "./icon.svg"
12
13
  },
13
14
  "files": [
14
15
  "index.js",
16
+ "client.js",
17
+ "src",
15
18
  "cordis.patch.yml",
16
19
  "locale",
17
20
  "docs",
@@ -24,14 +27,18 @@
24
27
  "dsh": {
25
28
  "bundle": {
26
29
  "patch": "./cordis.patch.yml"
30
+ },
31
+ "client": {
32
+ "platform": "web",
33
+ "immediately": true
27
34
  }
28
35
  },
29
36
  "license": "MIT",
30
37
  "repository": {
31
38
  "type": "git",
32
- "url": "https://gitee.com/pcbaby/dsh-llm-gateway.git"
39
+ "url": "git+https://github.com/pinb9668/dsh-llm-gateway.git"
33
40
  },
34
- "homepage": "https://gitee.com/pcbaby/dsh-llm-gateway#readme",
41
+ "homepage": "https://github.com/pinb9668/dsh-llm-gateway#readme",
35
42
  "engines": {
36
43
  "node": ">=22.14.0",
37
44
  "dsh": ">=0.2.2-rc.1 <0.3.0-0"
@@ -42,12 +49,21 @@
42
49
  "openai-compatible",
43
50
  "gateway",
44
51
  "codex",
45
- "workbuddy"
52
+ "workbuddy",
53
+ "notification",
54
+ "webhook",
55
+ "feishu",
56
+ "dingtalk",
57
+ "wecom",
58
+ "token-usage"
46
59
  ],
47
60
  "publishConfig": {
48
61
  "access": "public"
49
62
  },
50
63
  "scripts": {
51
- "test": "node tests/stream-failure.mjs && node tests/body-limit.mjs && node tests/image-budget.mjs && node tests/auth.mjs"
64
+ "test": "node tests/stream-failure.mjs && node tests/body-limit.mjs && node tests/image-budget.mjs && node tests/auth.mjs && node tests/notify.mjs && node tests/notify-api.mjs && node tests/client.mjs"
65
+ },
66
+ "bugs": {
67
+ "url": "https://github.com/pinb9668/dsh-llm-gateway/issues"
52
68
  }
53
69
  }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * 渠道适配层:把一条结构化通知渲染成各平台自己的消息形状并发送。
3
+ *
4
+ * 四个渠道的差异集中在这里,上层(index.js)只负责收集数据与调度:
5
+ *
6
+ * 企业微信 群机器人 webhook,POST {"msgtype":"markdown","markdown":{"content":...}}
7
+ * 飞书 群机器人 webhook,POST {"msg_type":"interactive",...},可选签名
8
+ * 钉钉 群机器人 webhook,POST {"msgtype":"markdown",...},加签必填
9
+ * 微信 预留(Server酱 / WxPusher 两种凭据形态)
10
+ *
11
+ * 所有发送都是 fire-and-forget:失败只写日志,永不向上抛,绝不阻塞 agent 主循环。
12
+ */
13
+
14
+ import { createHmac, createHash } from 'node:crypto';
15
+
16
+ /** 各渠道对单条正文的安全上限;超长先截断再发,避免整条被拒。 */
17
+ export const BODY_LIMITS = {
18
+ wecom: 3800,
19
+ feishu: 3800,
20
+ dingtalk: 4800,
21
+ wechat: 3000,
22
+ };
23
+
24
+ /**
25
+ * 钉钉加签:HmacSHA256(timestamp + "\n" + secret, secret) 再 base64。
26
+ * 签名必须放在 query 上,且 timestamp 与签名的组合有效期只有 1 小时。
27
+ */
28
+ export function dingtalkSignature(timestamp, secret) {
29
+ const stringToSign = `${timestamp}\n${secret}`;
30
+ return createHmac('sha256', secret).update(stringToSign, 'utf8').digest('base64');
31
+ }
32
+
33
+ /** 飞书加签:HmacSHA256(key = timestamp + "\n" + secret, data = ""),结果 base64。 */
34
+ export function feishuSignature(timestamp, secret) {
35
+ const key = `${timestamp}\n${secret}`;
36
+ return createHmac('sha256', key).update('', 'utf8').digest('base64');
37
+ }
38
+
39
+ /** 拼接带签名的钉钉地址;未配 secret 时原样返回(钉钉会拒绝,如实报错)。 */
40
+ export function signedDingtalkUrl(webhook, secret, now = Date.now()) {
41
+ if (!secret) return webhook;
42
+ const timestamp = String(now);
43
+ const sign = dingtalkSignature(timestamp, secret);
44
+ const url = new URL(webhook);
45
+ url.searchParams.set('timestamp', timestamp);
46
+ url.searchParams.set('sign', sign);
47
+ return url.toString();
48
+ }
49
+
50
+ /** 把任意 Markdown 裁到渠道上限,附加一行截断说明。 */
51
+ export function clampBody(text, limit) {
52
+ if (typeof text !== 'string') return '';
53
+ if (text.length <= limit) return text;
54
+ const note = '\n\n> 内容过长,已截断';
55
+ return `${text.slice(0, Math.max(0, limit - note.length)).trimEnd()}${note}`;
56
+ }
57
+
58
+ /** 飞书的富文本卡片体:比纯 Markdown 更能保证中文换行与层级。 */
59
+ function feishuCard(title, body) {
60
+ return {
61
+ msg_type: 'interactive',
62
+ card: {
63
+ config: { wide_screen_mode: true },
64
+ header: {
65
+ title: { tag: 'plain_text', content: title },
66
+ template: 'green',
67
+ },
68
+ elements: [
69
+ {
70
+ tag: 'div',
71
+ text: { tag: 'lark_md', content: body },
72
+ },
73
+ ],
74
+ },
75
+ };
76
+ }
77
+
78
+ /**
79
+ * 渲染并发送一条通知。
80
+ *
81
+ * @param {object} channel - 该渠道的配置片段(含 enabled / webhook / secret …)
82
+ * @param {'wecom'|'feishu'|'dingtalk'|'wechat'} kind - 渠道种类
83
+ * @param {{title: string, body: string}} message - 已渲染好的标题与正文
84
+ * @param {{timeoutMs: number, log: (msg: string) => void, fetchImpl?: Function}} runtime
85
+ * @returns {Promise<{ok: boolean, channel: string, detail?: string}>}
86
+ */
87
+ export async function sendToChannel(channel, kind, message, runtime) {
88
+ const { timeoutMs, log } = runtime;
89
+ const doFetch = runtime.fetchImpl ?? globalThis.fetch;
90
+ const limit = BODY_LIMITS[kind] ?? 3800;
91
+ const body = clampBody(message.body, limit);
92
+ const title = message.title;
93
+
94
+ try {
95
+ if (kind === 'wechat') {
96
+ // 预留通道:两种凭据都支持,但当前不内置自建服务号。
97
+ const sendKey = channel?.serverchanSendKey ?? '';
98
+ const appToken = channel?.wxpusherAppToken ?? '';
99
+ if (sendKey) {
100
+ const url = sendKey.startsWith('sctp')
101
+ ? `https://${sendKey.slice(4).match(/^\d+/)?.[0] ?? ''}.push.ft07.com/send/${sendKey}.send`
102
+ : `https://sctapi.ftqq.com/${sendKey}.send`;
103
+ const response = await doFetch(url, {
104
+ method: 'POST',
105
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
106
+ body: new URLSearchParams({ title, desp: body }),
107
+ signal: AbortSignal.timeout(timeoutMs),
108
+ });
109
+ return await judge(response, kind, log);
110
+ }
111
+ if (appToken) {
112
+ const response = await doFetch('https://wxpusher.zjiecode.com/api/send/message', {
113
+ method: 'POST',
114
+ headers: { 'content-type': 'application/json' },
115
+ body: JSON.stringify({
116
+ appToken,
117
+ content: body,
118
+ summary: title.slice(0, 20),
119
+ contentType: 3,
120
+ }),
121
+ signal: AbortSignal.timeout(timeoutMs),
122
+ });
123
+ return await judge(response, kind, log);
124
+ }
125
+ return { ok: false, channel: kind, detail: '微信通道未配置凭据' };
126
+ }
127
+
128
+ if (kind === 'wecom') {
129
+ if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
130
+ const response = await doFetch(channel.webhook, {
131
+ method: 'POST',
132
+ headers: { 'content-type': 'application/json' },
133
+ body: JSON.stringify({
134
+ msgtype: 'markdown',
135
+ markdown: { content: `${title}\n${body}` },
136
+ }),
137
+ signal: AbortSignal.timeout(timeoutMs),
138
+ });
139
+ return await judge(response, kind, log);
140
+ }
141
+
142
+ if (kind === 'feishu') {
143
+ if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
144
+ const payload = feishuCard(title, body);
145
+ if (channel.secret) {
146
+ const timestamp = String(Math.floor(Date.now() / 1000));
147
+ payload.timestamp = timestamp;
148
+ payload.sign = feishuSignature(timestamp, channel.secret);
149
+ }
150
+ const response = await doFetch(channel.webhook, {
151
+ method: 'POST',
152
+ headers: { 'content-type': 'application/json' },
153
+ body: JSON.stringify(payload),
154
+ signal: AbortSignal.timeout(timeoutMs),
155
+ });
156
+ return await judge(response, kind, log);
157
+ }
158
+
159
+ if (kind === 'dingtalk') {
160
+ if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
161
+ const url = signedDingtalkUrl(channel.webhook, channel.secret);
162
+ const response = await doFetch(url, {
163
+ method: 'POST',
164
+ headers: { 'content-type': 'application/json' },
165
+ body: JSON.stringify({
166
+ msgtype: 'markdown',
167
+ markdown: { title, text: `${title}\n${body}` },
168
+ }),
169
+ signal: AbortSignal.timeout(timeoutMs),
170
+ });
171
+ return await judge(response, kind, log);
172
+ }
173
+
174
+ return { ok: false, channel: kind, detail: `未知渠道 ${kind}` };
175
+ } catch (error) {
176
+ const detail = error instanceof Error ? error.message : String(error);
177
+ log(`gateway 通知:${kind} 发送失败 — ${detail}`);
178
+ return { ok: false, channel: kind, detail };
179
+ }
180
+ }
181
+
182
+ /**
183
+ * 判定一次响应是否真的成功。
184
+ *
185
+ * 这三个平台都会用 HTTP 200 + 业务错误码回话,只看 status 会把「webhook
186
+ * 已失效」当成成功,所以必须读错误码:
187
+ * 企业微信 errcode === 0
188
+ * 钉钉 errcode === 0
189
+ * 飞书 code === 0(旧版 StatusCode === 0)
190
+ */
191
+ async function judge(response, kind, log) {
192
+ let text = '';
193
+ try {
194
+ text = await response.text();
195
+ } catch {
196
+ text = '';
197
+ }
198
+
199
+ if (!response.ok) {
200
+ const detail = `HTTP ${response.status} ${text.slice(0, 200)}`;
201
+ log(`gateway 通知:${kind} 发送失败 — ${detail}`);
202
+ return { ok: false, channel: kind, detail };
203
+ }
204
+
205
+ let payload;
206
+ try {
207
+ payload = text === '' ? {} : JSON.parse(text);
208
+ } catch {
209
+ // 200 但正文不是 JSON:如实记为「已送出不可确认」,不冒充成功。
210
+ return { ok: true, channel: kind, detail: '已送出,响应非 JSON,结果不可确认' };
211
+ }
212
+
213
+ const code = payload?.errcode ?? payload?.code ?? payload?.StatusCode;
214
+ if (code === undefined) return { ok: true, channel: kind, detail: '已送出' };
215
+ if (Number(code) === 0) return { ok: true, channel: kind };
216
+
217
+ const message = payload?.errmsg ?? payload?.msg ?? payload?.StatusMessage ?? '';
218
+ const detail = `业务错误码 ${code}${message ? `:${message}` : ''}`;
219
+ log(`gateway 通知:${kind} 发送失败 — ${detail}`);
220
+ return { ok: false, channel: kind, detail };
221
+ }
222
+
223
+ /** 渠道是否具备发送条件(用于「有没有可用渠道」的判断,不发请求)。 */
224
+ export function isChannelReady(channel, kind) {
225
+ if (!channel || channel.enabled !== true) return false;
226
+ if (kind === 'wechat') {
227
+ return Boolean(channel.serverchanSendKey) || Boolean(channel.wxpusherAppToken);
228
+ }
229
+ if (!channel.webhook) return false;
230
+ return true;
231
+ }
232
+
233
+ /** 稳定标识,用于日志去重与「同一事件只发一次」。 */
234
+ export function eventFingerprint(sessionId, turn, reason) {
235
+ return createHash('sha256')
236
+ .update(`${sessionId}\u0000${turn ?? ''}\u0000${reason ?? ''}`)
237
+ .digest('hex')
238
+ .slice(0, 16);
239
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * 任务完成通知的配置形状、取值边界与收敛。
3
+ *
4
+ * 这一层是**纯函数**:没有 IO、没有 ctx,所以测试可以只喂对象。
5
+ * 三个使用方共用同一份定义:
6
+ * · Host 侧 apply() 读配置;
7
+ * · 设置页的读写路由;
8
+ * · 单元测试。
9
+ *
10
+ * 边界数字只在这里写一次。上一版把它们散在 Config 校验、normalizeConfig
11
+ * 和设置页的 min/max 三处,改了一处忘了另一处就会出现「输入 61 被拒绝,
12
+ * 但界面写着 60」这种事。
13
+ */
14
+
15
+ /** DSH 内部通知(界面闪动)的边界。 */
16
+ export const IN_APP_MIN_FLASHES = 1;
17
+ export const IN_APP_MAX_FLASHES = 60;
18
+ export const IN_APP_MIN_SECONDS = 1;
19
+ export const IN_APP_MAX_SECONDS = 80;
20
+ export const DEFAULT_FLASH_FLASHES = 18;
21
+ export const DEFAULT_FLASH_SECONDS = 6;
22
+ export const DEFAULT_FLASH_COLOR = '#22c55e';
23
+
24
+ /** 默认只在这些回合结局下通知。 */
25
+ export const DEFAULT_REASONS = ['completed', 'error', 'blocked'];
26
+
27
+ /** 允许出现在 reasons 里的结局。设置页按这个列表画勾选框。 */
28
+ export const REASON_CHOICES = [
29
+ 'completed',
30
+ 'error',
31
+ 'blocked',
32
+ 'max-tokens',
33
+ 'aborted',
34
+ ];
35
+
36
+ /**
37
+ * 网关请求的「静默窗口」默认值(秒)。
38
+ *
39
+ * Codex 这类客户端跑一个任务会连发几十个请求(每个工具调用一轮),
40
+ * 逐个请求通知等于刷屏。所以默认等这麼久没有新请求才发一条,
41
+ * 把整个任务压成一条通知。设成 0 就是每个请求都发。
42
+ */
43
+ export const DEFAULT_SETTLE_SECONDS = 12;
44
+ export const MAX_SETTLE_SECONDS = 300;
45
+
46
+ /**
47
+ * 允许写进 CSS 的颜色形状。
48
+ *
49
+ * 这个值最终作为 `background-color` 落进浏览器,正则在字符集上刻意排除了
50
+ * `;`、`{`、`}`、`url(`,所以拼不出第二段声明。不认裸单词(`green`)是
51
+ * 有意的:写错了不会报错,只会静默不着色,比回落到默认绿更难懂。
52
+ */
53
+ const COLOR_SHAPES = [
54
+ /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,
55
+ /^(?:rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s/+-]+\)$/i,
56
+ ];
57
+
58
+ /** 把用户填的颜色收敛成可以安全交给 CSS 的字符串。 */
59
+ export function normalizeColor(raw, fallback = DEFAULT_FLASH_COLOR) {
60
+ const value = typeof raw === 'string' ? raw.trim() : '';
61
+ if (value === '') return fallback;
62
+ return COLOR_SHAPES.some((shape) => shape.test(value)) ? value.toLowerCase() : fallback;
63
+ }
64
+
65
+ /** 数值收敛:非数字用默认值,越界夹到边界,而不是整块退回默认。 */
66
+ export function clampNumber(value, min, max, fallback) {
67
+ const numeric = typeof value === 'number' ? value : Number(value);
68
+ if (!Number.isFinite(numeric)) return fallback;
69
+ return Math.min(max, Math.max(min, numeric));
70
+ }
71
+
72
+ /**
73
+ * 一次闪动(彩色相位 + 白色相位)占多少毫秒。
74
+ *
75
+ * 语义写死在这里:**闪动次数 = 明暗切换的完整周期数**,总时长按次数均分,
76
+ * 所以 6 秒 18 次 ≈ 每 333 毫秒一次。设置页把这句话原样显示出来,用户不必猜。
77
+ */
78
+ export function flashPeriodMs(durationSeconds, flashes) {
79
+ const seconds = clampNumber(durationSeconds, IN_APP_MIN_SECONDS, IN_APP_MAX_SECONDS, DEFAULT_FLASH_SECONDS);
80
+ const count = Math.round(clampNumber(flashes, IN_APP_MIN_FLASHES, IN_APP_MAX_FLASHES, DEFAULT_FLASH_FLASHES));
81
+ return Math.round((seconds * 1000) / count);
82
+ }
83
+
84
+ /** DSH 内部通知的配置收敛。 */
85
+ export function normalizeInApp(raw) {
86
+ const source = raw && typeof raw === 'object' ? raw : {};
87
+ return {
88
+ enabled: source.enabled === true,
89
+ flashes: Math.round(
90
+ clampNumber(source.flashes, IN_APP_MIN_FLASHES, IN_APP_MAX_FLASHES, DEFAULT_FLASH_FLASHES),
91
+ ),
92
+ durationSeconds: Math.round(
93
+ clampNumber(source.durationSeconds, IN_APP_MIN_SECONDS, IN_APP_MAX_SECONDS, DEFAULT_FLASH_SECONDS),
94
+ ),
95
+ color: normalizeColor(source.color),
96
+ };
97
+ }
98
+
99
+ const pickString = (value) => (typeof value === 'string' ? value.trim() : '');
100
+
101
+ /**
102
+ * 通知配置的整体收敛。
103
+ *
104
+ * 缺字段 = 取默认值;写错的字段 = 收敛到最近的合法值,而不是抛错。
105
+ * 通知是「锦上添花」的旁路,它没有资格因为一个拼错的字段让网关起不来。
106
+ */
107
+ export function normalizeNotify(raw) {
108
+ const config = raw && typeof raw === 'object' ? raw : {};
109
+ const sources = config.sources && typeof config.sources === 'object' ? config.sources : {};
110
+ const gateway = config.gateway && typeof config.gateway === 'object' ? config.gateway : {};
111
+ const channels = config.channels && typeof config.channels === 'object' ? config.channels : {};
112
+
113
+ return {
114
+ enabled: config.enabled !== false,
115
+ reasons: Array.isArray(config.reasons) && config.reasons.length > 0
116
+ ? config.reasons.filter((entry) => typeof entry === 'string')
117
+ : [...DEFAULT_REASONS],
118
+ notifySubagents: config.notifySubagents === true,
119
+ maxExcerptChars: Number.isSafeInteger(config.maxExcerptChars) && config.maxExcerptChars > 0
120
+ ? Math.min(2000, Math.max(50, config.maxExcerptChars))
121
+ : 400,
122
+ timeoutMs: Number.isSafeInteger(config.timeoutMs) && config.timeoutMs > 0
123
+ ? Math.min(30000, Math.max(1000, config.timeoutMs))
124
+ : 8000,
125
+ /**
126
+ * 两个触发源互相独立:
127
+ * gateway —— 外部客户端(Codex / SDK / 脚本)打完一个请求;
128
+ * session —— DSH 自己的会话回合结束。
129
+ * 后者与 @morgan9668/dsh-task-notify 重叠,两个插件同时开就会各发一条。
130
+ */
131
+ sources: {
132
+ gateway: sources.gateway !== false,
133
+ session: sources.session !== false,
134
+ },
135
+ gateway: {
136
+ settleSeconds: Math.round(
137
+ clampNumber(gateway.settleSeconds, 0, MAX_SETTLE_SECONDS, DEFAULT_SETTLE_SECONDS),
138
+ ),
139
+ // 通知里是否带上客户端标识(User-Agent 的第一段)。默认带,便于区分
140
+ // Codex / SDK / 脚本各自的调用。
141
+ showClient: gateway.showClient !== false,
142
+ },
143
+ inApp: normalizeInApp(config.inApp),
144
+ channels: {
145
+ wechat: {
146
+ enabled: channels.wechat?.enabled === true,
147
+ serverchanSendKey: pickString(channels.wechat?.serverchanSendKey),
148
+ wxpusherAppToken: pickString(channels.wechat?.wxpusherAppToken),
149
+ },
150
+ wecom: {
151
+ enabled: channels.wecom?.enabled === true,
152
+ webhook: pickString(channels.wecom?.webhook),
153
+ },
154
+ feishu: {
155
+ enabled: channels.feishu?.enabled === true,
156
+ webhook: pickString(channels.feishu?.webhook),
157
+ secret: pickString(channels.feishu?.secret),
158
+ },
159
+ dingtalk: {
160
+ enabled: channels.dingtalk?.enabled === true,
161
+ webhook: pickString(channels.dingtalk?.webhook),
162
+ secret: pickString(channels.dingtalk?.secret),
163
+ },
164
+ },
165
+ };
166
+ }
167
+
168
+ /** 一条通知是否值得发:总开关开着,且这个结局在列表里。 */
169
+ export function shouldNotify(config, reasonKind) {
170
+ return config.enabled === true && config.reasons.includes(reasonKind);
171
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * 应用内通知的推送通道:一条 Server-Sent-Events 路由,所有打开的 DSH 页面都订阅它。
3
+ *
4
+ * 为什么需要它:群机器人的推送是「出站」的,浏览器收不到;而「DSH 内部通知」
5
+ * 要的是本机界面上的反馈。Host 半身在回合结束时广播一条事件,每个打开的
6
+ * 页面据此让整个程序闪动。
7
+ *
8
+ * 实现参考 DSH 自己的 client-HMR 与 dsh-our-free-model 的 push 通道:
9
+ * 一条保持打开的 `text/event-stream` 响应、一个防御空闲超时的注释心跳、
10
+ * 客户端断开时逐个摘除。`webServer` 明确允许 handler 把响应一直开着,
11
+ * 它的 gzip 层也会跳过事件流。
12
+ *
13
+ * 事件是「快照」而不是队列:连上之前的广播不会补发,新连上的页面只拿到
14
+ * 一次 `hello`,这让 hub 完全不存状态,插件热重载后也不会残留半开连接。
15
+ */
16
+
17
+ const HEARTBEAT_MS = 25_000;
18
+
19
+ export function createNoticeHub({ log = () => {}, heartbeatMs = HEARTBEAT_MS } = {}) {
20
+ /** @type {Set<import('node:http').ServerResponse>} */
21
+ const clients = new Set();
22
+ let heartbeat;
23
+
24
+ function stopHeartbeat() {
25
+ if (heartbeat === undefined) return;
26
+ clearInterval(heartbeat);
27
+ heartbeat = undefined;
28
+ }
29
+
30
+ function startHeartbeat() {
31
+ if (heartbeat !== undefined || clients.size === 0) return;
32
+ heartbeat = setInterval(() => {
33
+ for (const res of clients) {
34
+ if (res.writableEnded === true || res.destroyed === true) {
35
+ clients.delete(res);
36
+ continue;
37
+ }
38
+ try {
39
+ res.write(': ping\n\n');
40
+ } catch {
41
+ clients.delete(res);
42
+ }
43
+ }
44
+ if (clients.size === 0) stopHeartbeat();
45
+ }, heartbeatMs);
46
+ // 心跳不该把进程钉住:宿主退出时这里不能成为最后一个活句柄。
47
+ heartbeat.unref?.();
48
+ }
49
+
50
+ const forget = (res) => {
51
+ clients.delete(res);
52
+ if (clients.size === 0) stopHeartbeat();
53
+ };
54
+
55
+ return {
56
+ /** 当前有几个页面正连着。设置页用它告诉用户「有没有页面在听」。 */
57
+ get size() {
58
+ return clients.size;
59
+ },
60
+
61
+ /** 接管一个请求,把它变成常开的事件流。 */
62
+ attach(req, res, hello) {
63
+ res.writeHead(200, {
64
+ 'content-type': 'text/event-stream; charset=utf-8',
65
+ 'cache-control': 'no-cache, no-transform',
66
+ connection: 'keep-alive',
67
+ 'x-accel-buffering': 'no',
68
+ });
69
+ /**
70
+ * 头写完之后,任何一次 write 都可能立刻失败(对端刚关掉、代理断开)。
71
+ *
72
+ * 这几次写入也在 try 里:失败就是「这个页面根本连上又走了」,
73
+ * 直接不登记即可。不包起来的话,一个已经消失的标签页会在插件里
74
+ * 抛一个没人接的 EPIPE——对调用方来说是回合结束的处理被炸掉了。
75
+ */
76
+ try {
77
+ res.write(': connected\n\n');
78
+ if (hello !== undefined) this.sendTo(res, 'hello', hello);
79
+ } catch (error) {
80
+ log(`通知流握手失败:${error instanceof Error ? error.message : String(error)}`);
81
+ try {
82
+ res.end();
83
+ } catch {
84
+ /* 已经断了 */
85
+ }
86
+ return;
87
+ }
88
+ clients.add(res);
89
+ startHeartbeat();
90
+ req.on?.('close', () => forget(res));
91
+ res.on?.('close', () => forget(res));
92
+ },
93
+
94
+ sendTo(res, event, data) {
95
+ if (res.writableEnded === true || res.destroyed === true) {
96
+ clients.delete(res);
97
+ return false;
98
+ }
99
+ try {
100
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data ?? {})}\n\n`);
101
+ return true;
102
+ } catch (error) {
103
+ forget(res);
104
+ log(`通知流已断:${error instanceof Error ? error.message : String(error)}`);
105
+ return false;
106
+ }
107
+ },
108
+
109
+ /**
110
+ * 向所有连着的页面广播一条事件。
111
+ * @returns {number} 实际送达的页面数(设置页用它回报预览结果)。
112
+ */
113
+ emit(event, data) {
114
+ let delivered = 0;
115
+ for (const res of [...clients]) {
116
+ if (this.sendTo(res, event, data)) delivered += 1;
117
+ }
118
+ return delivered;
119
+ },
120
+
121
+ /**
122
+ * 关掉所有流。插件卸载、热重载、profile 重排都会走到这里;
123
+ * 不关的话留下的是永远不再有数据的半开响应。
124
+ */
125
+ dispose() {
126
+ for (const res of [...clients]) {
127
+ try {
128
+ res.end();
129
+ } catch {
130
+ /* 已经断了 */
131
+ }
132
+ }
133
+ clients.clear();
134
+ stopHeartbeat();
135
+ },
136
+ };
137
+ }