@zhin.js/adapter-weixin-ilink 1.0.0 → 1.1.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.
Files changed (187) hide show
  1. package/CHANGELOG.md +453 -0
  2. package/README.md +18 -41
  3. package/adapters/weixin-ilink.js +32 -0
  4. package/adapters/weixin-ilink.ts +43 -0
  5. package/commands/endpoint/add/[id].js +3 -0
  6. package/commands/endpoint/add/[id].ts +3 -0
  7. package/commands/endpoint/list.js +3 -0
  8. package/commands/endpoint/list.ts +3 -0
  9. package/commands/endpoint/remove/[id].js +3 -0
  10. package/commands/endpoint/remove/[id].ts +3 -0
  11. package/lib/aes-ecb.d.ts +0 -1
  12. package/lib/aes-ecb.js +0 -1
  13. package/lib/cdn-upload.d.ts +0 -1
  14. package/lib/cdn-upload.js +0 -1
  15. package/lib/cdn-url.d.ts +0 -1
  16. package/lib/cdn-url.js +0 -1
  17. package/lib/client.d.ts +34 -0
  18. package/lib/client.js +72 -0
  19. package/lib/context-store.d.ts +1 -2
  20. package/lib/context-store.js +1 -2
  21. package/lib/credentials.d.ts +6 -7
  22. package/lib/credentials.js +12 -13
  23. package/lib/endpoint.d.ts +37 -0
  24. package/lib/endpoint.js +418 -0
  25. package/lib/ilink-api.d.ts +1 -1
  26. package/lib/ilink-api.js +5 -2
  27. package/lib/ilink-config-cache.d.ts +0 -1
  28. package/lib/ilink-config-cache.js +0 -1
  29. package/lib/ilink-logger.d.ts +0 -1
  30. package/lib/ilink-logger.js +0 -1
  31. package/lib/ilink-meta.d.ts +0 -1
  32. package/lib/ilink-meta.js +0 -1
  33. package/lib/ilink-random.d.ts +0 -1
  34. package/lib/ilink-random.js +0 -1
  35. package/lib/ilink-redact.d.ts +0 -1
  36. package/lib/ilink-redact.js +0 -1
  37. package/lib/ilink-session-guard.d.ts +0 -1
  38. package/lib/ilink-session-guard.js +0 -1
  39. package/lib/ilink-types.d.ts +0 -1
  40. package/lib/ilink-types.js +0 -1
  41. package/lib/index.d.ts +5 -20
  42. package/lib/index.js +3 -38
  43. package/lib/login.d.ts +4 -6
  44. package/lib/login.js +73 -68
  45. package/lib/media-download.d.ts +1 -2
  46. package/lib/media-download.js +1 -2
  47. package/lib/mime.d.ts +0 -1
  48. package/lib/mime.js +0 -1
  49. package/lib/outbound-media.d.ts +4 -5
  50. package/lib/outbound-media.js +85 -86
  51. package/lib/pic-decrypt.d.ts +0 -1
  52. package/lib/pic-decrypt.js +0 -1
  53. package/lib/protocol.d.ts +63 -0
  54. package/lib/protocol.js +127 -0
  55. package/lib/silk-transcode.d.ts +0 -1
  56. package/lib/silk-transcode.js +0 -1
  57. package/lib/types.d.ts +2 -26
  58. package/lib/types.js +0 -1
  59. package/lib/upload.d.ts +1 -2
  60. package/lib/upload.js +1 -2
  61. package/lib/weixin-ilink-endpoint-commands.d.ts +1 -0
  62. package/lib/weixin-ilink-endpoint-commands.js +16 -0
  63. package/lib/weixin-ilink-runtime-state.d.ts +1 -0
  64. package/lib/weixin-ilink-runtime-state.js +6 -0
  65. package/lib/weixin-inbound.d.ts +10 -3
  66. package/lib/weixin-inbound.js +46 -23
  67. package/lib/weixin-send-media.d.ts +0 -1
  68. package/lib/weixin-send-media.js +0 -1
  69. package/lib/weixin-send.d.ts +1 -2
  70. package/lib/weixin-send.js +2 -3
  71. package/package.json +48 -35
  72. package/plugin.js +14 -0
  73. package/schema.json +88 -0
  74. package/src/client.ts +85 -0
  75. package/src/context-store.ts +2 -0
  76. package/src/credentials.ts +12 -12
  77. package/src/endpoint.ts +531 -0
  78. package/src/ilink-api.ts +5 -1
  79. package/src/index.ts +28 -56
  80. package/src/login.ts +89 -75
  81. package/src/media-download.ts +1 -2
  82. package/src/outbound-media.ts +97 -97
  83. package/src/protocol.ts +189 -0
  84. package/src/silk-wasm.d.ts +6 -2
  85. package/src/types.ts +6 -25
  86. package/src/upload.ts +2 -2
  87. package/src/weixin-ilink-endpoint-commands.ts +17 -0
  88. package/src/weixin-ilink-runtime-state.ts +7 -0
  89. package/src/weixin-inbound.ts +48 -18
  90. package/src/weixin-send.ts +4 -4
  91. package/client/LoginAssistPanel.tsx +0 -200
  92. package/client/WeixinIlinkManagement.tsx +0 -139
  93. package/client/index.tsx +0 -11
  94. package/client/tsconfig.json +0 -13
  95. package/client/utils/api.ts +0 -30
  96. package/dist/index.js +0 -29
  97. package/lib/adapter.d.ts +0 -11
  98. package/lib/adapter.d.ts.map +0 -1
  99. package/lib/adapter.js +0 -14
  100. package/lib/adapter.js.map +0 -1
  101. package/lib/aes-ecb.d.ts.map +0 -1
  102. package/lib/aes-ecb.js.map +0 -1
  103. package/lib/bot.d.ts +0 -37
  104. package/lib/bot.d.ts.map +0 -1
  105. package/lib/bot.js +0 -383
  106. package/lib/bot.js.map +0 -1
  107. package/lib/cdn-upload.d.ts.map +0 -1
  108. package/lib/cdn-upload.js.map +0 -1
  109. package/lib/cdn-upload.test.d.ts +0 -2
  110. package/lib/cdn-upload.test.d.ts.map +0 -1
  111. package/lib/cdn-upload.test.js +0 -150
  112. package/lib/cdn-upload.test.js.map +0 -1
  113. package/lib/cdn-url.d.ts.map +0 -1
  114. package/lib/cdn-url.js.map +0 -1
  115. package/lib/context-store.d.ts.map +0 -1
  116. package/lib/context-store.js.map +0 -1
  117. package/lib/credentials.d.ts.map +0 -1
  118. package/lib/credentials.js.map +0 -1
  119. package/lib/ilink-api.d.ts.map +0 -1
  120. package/lib/ilink-api.js.map +0 -1
  121. package/lib/ilink-config-cache.d.ts.map +0 -1
  122. package/lib/ilink-config-cache.js.map +0 -1
  123. package/lib/ilink-logger.d.ts.map +0 -1
  124. package/lib/ilink-logger.js.map +0 -1
  125. package/lib/ilink-meta.d.ts.map +0 -1
  126. package/lib/ilink-meta.js.map +0 -1
  127. package/lib/ilink-random.d.ts.map +0 -1
  128. package/lib/ilink-random.js.map +0 -1
  129. package/lib/ilink-redact.d.ts.map +0 -1
  130. package/lib/ilink-redact.js.map +0 -1
  131. package/lib/ilink-session-guard.d.ts.map +0 -1
  132. package/lib/ilink-session-guard.js.map +0 -1
  133. package/lib/ilink-types.d.ts.map +0 -1
  134. package/lib/ilink-types.js.map +0 -1
  135. package/lib/index.d.ts.map +0 -1
  136. package/lib/index.js.map +0 -1
  137. package/lib/login-assist-routes.d.ts +0 -7
  138. package/lib/login-assist-routes.d.ts.map +0 -1
  139. package/lib/login-assist-routes.js +0 -29
  140. package/lib/login-assist-routes.js.map +0 -1
  141. package/lib/login.d.ts.map +0 -1
  142. package/lib/login.js.map +0 -1
  143. package/lib/media-download.d.ts.map +0 -1
  144. package/lib/media-download.js.map +0 -1
  145. package/lib/mime.d.ts.map +0 -1
  146. package/lib/mime.js.map +0 -1
  147. package/lib/mime.test.d.ts +0 -2
  148. package/lib/mime.test.d.ts.map +0 -1
  149. package/lib/mime.test.js +0 -62
  150. package/lib/mime.test.js.map +0 -1
  151. package/lib/outbound-media.d.ts.map +0 -1
  152. package/lib/outbound-media.js.map +0 -1
  153. package/lib/pic-decrypt.d.ts.map +0 -1
  154. package/lib/pic-decrypt.js.map +0 -1
  155. package/lib/routes.d.ts +0 -8
  156. package/lib/routes.d.ts.map +0 -1
  157. package/lib/routes.js +0 -29
  158. package/lib/routes.js.map +0 -1
  159. package/lib/silk-transcode.d.ts.map +0 -1
  160. package/lib/silk-transcode.js.map +0 -1
  161. package/lib/silk-transcode.test.d.ts +0 -2
  162. package/lib/silk-transcode.test.d.ts.map +0 -1
  163. package/lib/silk-transcode.test.js +0 -53
  164. package/lib/silk-transcode.test.js.map +0 -1
  165. package/lib/types.d.ts.map +0 -1
  166. package/lib/types.js.map +0 -1
  167. package/lib/typing-indicator.d.ts +0 -32
  168. package/lib/typing-indicator.d.ts.map +0 -1
  169. package/lib/typing-indicator.js +0 -95
  170. package/lib/typing-indicator.js.map +0 -1
  171. package/lib/upload.d.ts.map +0 -1
  172. package/lib/upload.js.map +0 -1
  173. package/lib/upload.test.d.ts +0 -2
  174. package/lib/upload.test.d.ts.map +0 -1
  175. package/lib/upload.test.js +0 -250
  176. package/lib/upload.test.js.map +0 -1
  177. package/lib/weixin-inbound.d.ts.map +0 -1
  178. package/lib/weixin-inbound.js.map +0 -1
  179. package/lib/weixin-send-media.d.ts.map +0 -1
  180. package/lib/weixin-send-media.js.map +0 -1
  181. package/lib/weixin-send.d.ts.map +0 -1
  182. package/lib/weixin-send.js.map +0 -1
  183. package/src/adapter.ts +0 -16
  184. package/src/bot.ts +0 -483
  185. package/src/login-assist-routes.ts +0 -36
  186. package/src/routes.ts +0 -39
  187. package/src/typing-indicator.ts +0 -139
@@ -0,0 +1,418 @@
1
+ import { Endpoint } from 'zhin.js/adapter';
2
+ /**
3
+ * WeixinIlinkEndpoint — lifecycle, long-poll inbound, outbound send.
4
+ */
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
9
+ import { getUpdates, notifyStart, notifyStop } from './ilink-api.js';
10
+ import { configureIlinkMeta } from './ilink-meta.js';
11
+ import { loadSyncBuf, resolveStateDir, saveSyncBuf, } from './credentials.js';
12
+ import { resolveCredentials } from './login.js';
13
+ import { listContextTokenUserIds, restoreContextTokens, setContextToken, flushContextTokenPersist, } from './context-store.js';
14
+ import { WeixinConfigManager } from './ilink-config-cache.js';
15
+ import { getRemainingPauseMs, isSessionPaused, pauseSession, SESSION_EXPIRED_ERRCODE, } from './ilink-session-guard.js';
16
+ import { downloadMediaFromItem } from './media-download.js';
17
+ import { sendMessageWeixin } from './weixin-send.js';
18
+ import { materializeOutboundMedia } from './outbound-media.js';
19
+ import { MessageItemType } from './ilink-types.js';
20
+ import { getExtensionFromMime, sniffMimeFromBuffer } from './mime.js';
21
+ import { formatInboundContent, weixinInboundSegments, weixinReplyTo, formatOutboundSegments, inboundMessageId, segmentLocalPath, sleep, weixinIlinkInboundConversation, } from './protocol.js';
22
+ import { WeixinIlinkClient } from './client.js';
23
+ const MAX_CONSECUTIVE_FAILURES = 3;
24
+ const BACKOFF_DELAY_MS = 30_000;
25
+ const RETRY_DELAY_MS = 2_000;
26
+ const WEIXIN_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
27
+ /** 入站媒体保留 24h,每小时清扫一次。 */
28
+ const INBOUND_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
29
+ const MEDIA_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
30
+ export class WeixinIlinkEndpoint extends Endpoint {
31
+ client;
32
+ #logger;
33
+ #options;
34
+ #resolveCredentials;
35
+ #notifyStart;
36
+ #notifyStop;
37
+ #getUpdates;
38
+ #sendText;
39
+ #creds = null;
40
+ #pollAbort;
41
+ #pollPromise;
42
+ #loginAbort;
43
+ #configManager;
44
+ #mediaSweepTimer;
45
+ #open = false;
46
+ #started = false;
47
+ management = createWeixinIlinkEndpointManagement(() => this.client);
48
+ control = Object.freeze({
49
+ typing: async (conversation, active) => {
50
+ await this.client.sendTyping(conversation.id, active === false ? 2 : 1);
51
+ },
52
+ });
53
+ constructor(options) {
54
+ super();
55
+ this.#logger = getAdapterLogger('weixin-ilink', options.config.id);
56
+ this.#options = options;
57
+ this.#resolveCredentials = options.resolveCredentials ?? resolveCredentials;
58
+ this.#notifyStart = options.notifyStart ?? notifyStart;
59
+ this.#notifyStop = options.notifyStop ?? notifyStop;
60
+ this.#getUpdates = options.getUpdates ?? getUpdates;
61
+ this.#sendText = options.sendText ?? sendMessageWeixin;
62
+ this.client = new WeixinIlinkClient(options.config, () => this.#creds, () => this.#configManager, this.#sendText);
63
+ }
64
+ get hasCredentials() {
65
+ return this.client.authenticated;
66
+ }
67
+ async start() {
68
+ if (this.#started)
69
+ return;
70
+ this.#started = true;
71
+ try {
72
+ configureIlinkMeta({ botAgent: this.#options.config.botAgent });
73
+ // QR 登录最长 8 分钟:stop() 必须能打断
74
+ this.#loginAbort = new AbortController();
75
+ this.#creds = await this.#resolveCredentials(this.#options.config, this.#loginAbort.signal);
76
+ restoreContextTokens(this.#options.config.id);
77
+ await this.#notifyStart({
78
+ baseUrl: this.client.apiBaseUrl,
79
+ token: this.#creds.botToken,
80
+ });
81
+ this.#configManager = new WeixinConfigManager({ baseUrl: this.client.apiBaseUrl, token: this.#creds.botToken }, (msg) => this.#logger.debug(msg));
82
+ this.#pollAbort = new AbortController();
83
+ this.#pollPromise = this.#pollLoop(this.#pollAbort.signal);
84
+ this.#startMediaSweep();
85
+ this.#logger.info(formatCompact({
86
+ op: 'connect',
87
+ endpoint: this.#options.config.id,
88
+ }));
89
+ void this.#emitPlatformEvent('system.online', {
90
+ account: this.#options.config.id,
91
+ });
92
+ }
93
+ catch (error) {
94
+ await this.stop();
95
+ this.#logger.error('Failed to connect weixin-ilink bot:', error);
96
+ throw error;
97
+ }
98
+ }
99
+ open() {
100
+ this.#open = true;
101
+ }
102
+ close() {
103
+ this.#open = false;
104
+ }
105
+ async stop() {
106
+ this.#open = false;
107
+ this.#loginAbort?.abort();
108
+ this.#pollAbort?.abort();
109
+ try {
110
+ await this.#pollPromise;
111
+ }
112
+ catch {
113
+ /* poll loop exit */
114
+ }
115
+ this.#stopMediaSweep();
116
+ // 防抖中的 context token 落盘,避免 stop 丢尾部写入
117
+ flushContextTokenPersist(this.#options.config.id);
118
+ if (this.#creds?.botToken) {
119
+ try {
120
+ await this.#notifyStop({ baseUrl: this.client.apiBaseUrl, token: this.#creds.botToken });
121
+ }
122
+ catch (err) {
123
+ this.#logger.warn(formatCompact({
124
+ op: 'notify_stop',
125
+ ok: false,
126
+ error: err instanceof Error ? err.message : String(err),
127
+ }));
128
+ }
129
+ }
130
+ this.#started = false;
131
+ void this.#emitPlatformEvent('system.offline', {
132
+ account: this.#options.config.id,
133
+ });
134
+ this.#logger.debug(formatCompact({
135
+ op: 'disconnect',
136
+ }));
137
+ }
138
+ async send({ conversation, payload }) {
139
+ if (!this.#creds?.botToken) {
140
+ throw new Error('weixin-ilink bot not authenticated');
141
+ }
142
+ // 个人微信仅 private 会话,对端 user_id 即 conversation.id
143
+ const target = conversation.id;
144
+ const contextToken = this.client.contextToken(target);
145
+ if (!contextToken) {
146
+ this.#logger.warn(formatCompact({
147
+ op: 'send',
148
+ ok: false,
149
+ reason: 'missing_context_token',
150
+ target,
151
+ }));
152
+ throw new Error(`missing context_token for peer ${target}`);
153
+ }
154
+ const outboundDir = path.join(resolveStateDir(), 'media', 'outbound');
155
+ const wire = formatOutboundSegments(payload);
156
+ const materialized = await materializeOutboundMedia(wire, outboundDir);
157
+ const segments = Array.isArray(materialized) ? materialized : [materialized];
158
+ let lastId = '';
159
+ let pendingText = '';
160
+ for (const raw of segments) {
161
+ if (typeof raw === 'string') {
162
+ pendingText += raw;
163
+ continue;
164
+ }
165
+ if (typeof raw !== 'object' || raw === null || !('type' in raw))
166
+ continue;
167
+ const seg = raw;
168
+ if (seg.type === 'text' || seg.type === 'markdown') {
169
+ pendingText += String(seg.data?.text ?? '');
170
+ continue;
171
+ }
172
+ const filePath = segmentLocalPath(seg);
173
+ if (filePath && fs.existsSync(filePath)) {
174
+ // 微信限制:单条消息不能图文混排 → 先单独发文本,再发纯媒体
175
+ if (pendingText.trim()) {
176
+ const textResult = await this.client.sendText(target, pendingText);
177
+ pendingText = '';
178
+ lastId = textResult.messageId;
179
+ }
180
+ const result = await this.client.sendMedia(target, filePath);
181
+ lastId = result.messageId;
182
+ continue;
183
+ }
184
+ if (seg.type === 'image' || seg.type === 'video' || seg.type === 'file' || seg.type === 'record') {
185
+ this.#logger.warn(formatCompact({
186
+ op: 'send',
187
+ skip: 'no_local_file',
188
+ type: seg.type,
189
+ }));
190
+ }
191
+ }
192
+ if (pendingText.trim()) {
193
+ const result = await this.client.sendText(target, pendingText);
194
+ lastId = result.messageId;
195
+ }
196
+ return lastId || `weixin-ilink-${Date.now()}`;
197
+ }
198
+ /** Test / internal: admit a parsed message when the endpoint is open. */
199
+ admit(msg) {
200
+ if (!this.#open)
201
+ return;
202
+ const userId = msg.from_user_id ?? '';
203
+ if (msg.context_token && userId) {
204
+ setContextToken(this.#options.config.id, userId, msg.context_token);
205
+ }
206
+ const conversation = weixinIlinkInboundConversation(String(this.#options.id), userId);
207
+ const replyTo = weixinReplyTo(msg);
208
+ void this.emit('message.receive', {
209
+ conversation,
210
+ message: { conversation, id: inboundMessageId(msg) },
211
+ content: formatInboundContent(msg),
212
+ segments: weixinInboundSegments(msg),
213
+ ...(replyTo ? { replyTo } : {}),
214
+ sender: { id: userId },
215
+ endpointId: this.#options.config.id,
216
+ metadata: Object.freeze({
217
+ messageType: msg.message_type,
218
+ createTimeMs: msg.create_time_ms,
219
+ }),
220
+ }).catch((err) => {
221
+ this.#logger.warn(formatCompact({
222
+ op: 'weixin_ilink_gateway_receive_failed',
223
+ target: userId,
224
+ error: err instanceof Error ? err.message : String(err),
225
+ }));
226
+ });
227
+ }
228
+ async #pollLoop(abortSignal) {
229
+ if (!this.#creds?.botToken)
230
+ return;
231
+ const endpointId = this.#options.config.id;
232
+ let getUpdatesBuf = loadSyncBuf(endpointId);
233
+ let nextTimeoutMs = this.#options.config.longPollTimeoutMs;
234
+ let consecutiveFailures = 0;
235
+ while (!abortSignal.aborted) {
236
+ if (isSessionPaused(endpointId)) {
237
+ await sleep(getRemainingPauseMs(endpointId), abortSignal);
238
+ continue;
239
+ }
240
+ try {
241
+ const resp = await this.#getUpdates({
242
+ baseUrl: this.client.apiBaseUrl,
243
+ token: this.#creds.botToken,
244
+ get_updates_buf: getUpdatesBuf,
245
+ timeoutMs: nextTimeoutMs,
246
+ abortSignal,
247
+ });
248
+ if (resp.longpolling_timeout_ms != null && resp.longpolling_timeout_ms > 0) {
249
+ nextTimeoutMs = resp.longpolling_timeout_ms;
250
+ }
251
+ const isApiError = (resp.ret !== undefined && resp.ret !== 0)
252
+ || (resp.errcode !== undefined && resp.errcode !== 0);
253
+ if (isApiError) {
254
+ const sessionExpired = resp.errcode === SESSION_EXPIRED_ERRCODE || resp.ret === SESSION_EXPIRED_ERRCODE;
255
+ if (sessionExpired) {
256
+ pauseSession(endpointId);
257
+ consecutiveFailures = 0;
258
+ await sleep(getRemainingPauseMs(endpointId), abortSignal);
259
+ continue;
260
+ }
261
+ consecutiveFailures += 1;
262
+ // 退避后不清零:对端持续挂时清零会让重试固定打满 RETRY_DELAY_MS。
263
+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
264
+ await sleep(BACKOFF_DELAY_MS, abortSignal);
265
+ }
266
+ else {
267
+ await sleep(RETRY_DELAY_MS, abortSignal);
268
+ }
269
+ continue;
270
+ }
271
+ consecutiveFailures = 0;
272
+ // 先分发再推进 buf:分发途中崩溃时 buf 未推进,下一轮重拉不丢消息。
273
+ const nextBuf = resp.get_updates_buf;
274
+ for (const inbound of resp.msgs ?? []) {
275
+ await this.#handleInboundMessage(inbound);
276
+ }
277
+ if (nextBuf) {
278
+ getUpdatesBuf = nextBuf;
279
+ saveSyncBuf(endpointId, getUpdatesBuf);
280
+ }
281
+ }
282
+ catch (err) {
283
+ if (abortSignal.aborted)
284
+ return;
285
+ consecutiveFailures += 1;
286
+ this.#logger.error(formatCompact({
287
+ op: 'poll',
288
+ ok: false,
289
+ error: err instanceof Error ? err.message : String(err),
290
+ }));
291
+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
292
+ await sleep(BACKOFF_DELAY_MS, abortSignal);
293
+ }
294
+ else {
295
+ await sleep(RETRY_DELAY_MS, abortSignal);
296
+ }
297
+ }
298
+ }
299
+ }
300
+ async #handleInboundMessage(full) {
301
+ void this.#emitPlatformEvent(`message.${full.message_type ?? 'unknown'}`, full);
302
+ const fromUserId = full.from_user_id ?? '';
303
+ if (full.context_token && fromUserId) {
304
+ setContextToken(this.#options.config.id, fromUserId, full.context_token);
305
+ }
306
+ const mediaOpts = await this.#downloadInboundMedia(full);
307
+ this.admit({ ...full, _media: mediaOpts });
308
+ this.#logger.debug(formatCompact({
309
+ op: 'recv',
310
+ endpoint: this.#options.config.id,
311
+ target: fromUserId,
312
+ preview: formatInboundContent({ ...full, _media: mediaOpts }).slice(0, 80),
313
+ }));
314
+ }
315
+ async #emitPlatformEvent(name, event) {
316
+ await this.emitPlatform(name, event).catch((error) => {
317
+ this.#logger.warn(formatCompact({
318
+ op: 'weixin_ilink_platform_event_failed',
319
+ event: name,
320
+ error: error instanceof Error ? error.message : String(error),
321
+ }));
322
+ });
323
+ }
324
+ async #downloadInboundMedia(full) {
325
+ const hasDownloadableMedia = (m) => Boolean(m?.encrypt_query_param || m?.full_url);
326
+ const mediaItem = full.item_list?.find((i) => i.type === MessageItemType.IMAGE && hasDownloadableMedia(i.image_item?.media))
327
+ ?? full.item_list?.find((i) => i.type === MessageItemType.VIDEO && hasDownloadableMedia(i.video_item?.media))
328
+ ?? full.item_list?.find((i) => i.type === MessageItemType.FILE && hasDownloadableMedia(i.file_item?.media))
329
+ ?? full.item_list?.find((i) => i.type === MessageItemType.VOICE && hasDownloadableMedia(i.voice_item?.media));
330
+ if (!mediaItem)
331
+ return {};
332
+ return downloadMediaFromItem(mediaItem, {
333
+ cdnBaseUrl: this.client.cdnBaseUrl,
334
+ saveMedia: (buffer, contentType, subdir, maxBytes, originalFilename) => this.#saveInboundMedia(buffer, contentType, subdir, maxBytes, originalFilename),
335
+ log: (msg) => this.#logger.debug(msg),
336
+ errLog: (msg) => this.#logger.warn(msg),
337
+ label: `inbound:${full.from_user_id ?? 'unknown'}`,
338
+ });
339
+ }
340
+ async #saveInboundMedia(buffer, contentType, subdir = 'inbound', maxBytes = WEIXIN_MEDIA_MAX_BYTES, originalFilename) {
341
+ if (buffer.length > maxBytes) {
342
+ throw new Error(`media exceeds max size ${maxBytes}`);
343
+ }
344
+ const dir = path.join(resolveStateDir(), 'media', subdir);
345
+ fs.mkdirSync(dir, { recursive: true });
346
+ const resolvedMime = contentType ?? sniffMimeFromBuffer(buffer);
347
+ const ext = originalFilename
348
+ ? path.extname(originalFilename)
349
+ : resolvedMime
350
+ ? getExtensionFromMime(resolvedMime)
351
+ : '.bin';
352
+ const base = originalFilename
353
+ ? path.basename(originalFilename, ext)
354
+ : 'media';
355
+ const fileName = `${base}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}${ext}`;
356
+ const filePath = path.join(dir, fileName);
357
+ fs.writeFileSync(filePath, buffer);
358
+ return { path: filePath };
359
+ }
360
+ /** 入站媒体 TTL 清扫:start 时立即扫一次,之后每小时扫一次。 */
361
+ #startMediaSweep() {
362
+ this.#stopMediaSweep();
363
+ const sweep = () => this.#sweepInboundMedia();
364
+ sweep();
365
+ this.#mediaSweepTimer = setInterval(sweep, MEDIA_SWEEP_INTERVAL_MS);
366
+ this.#mediaSweepTimer.unref?.();
367
+ }
368
+ #stopMediaSweep() {
369
+ if (this.#mediaSweepTimer) {
370
+ clearInterval(this.#mediaSweepTimer);
371
+ this.#mediaSweepTimer = undefined;
372
+ }
373
+ }
374
+ #sweepInboundMedia() {
375
+ const dir = path.join(resolveStateDir(), 'media', 'inbound');
376
+ let entries;
377
+ try {
378
+ entries = fs.readdirSync(dir, { withFileTypes: true });
379
+ }
380
+ catch {
381
+ return;
382
+ }
383
+ const now = Date.now();
384
+ for (const entry of entries) {
385
+ if (!entry.isFile())
386
+ continue;
387
+ const filePath = path.join(dir, entry.name);
388
+ try {
389
+ const stat = fs.statSync(filePath);
390
+ if (now - stat.mtimeMs <= INBOUND_MEDIA_TTL_MS)
391
+ continue;
392
+ fs.unlinkSync(filePath);
393
+ this.#logger.debug(formatCompact({
394
+ op: 'media_sweep',
395
+ endpoint: this.#options.config.id,
396
+ file: entry.name,
397
+ }));
398
+ }
399
+ catch {
400
+ /* 单个文件失败不阻塞整体清扫 */
401
+ }
402
+ }
403
+ }
404
+ }
405
+ function createWeixinIlinkEndpointManagement(requireClient) {
406
+ return Object.freeze({
407
+ // 个人微信无群概念(listGroups/listGroupMembers 不接),也没有通讯录/资料接口。
408
+ // "好友"只能从会话推导:凡持有 context_token 的对端(来过消息,含重启后从磁盘恢复的)
409
+ // 即为可达私聊对端;昵称不可得,用 user_id 占位并在 remark 注明来源。
410
+ async listFriends() {
411
+ return listContextTokenUserIds(requireClient().config.id).map((userId) => ({
412
+ user_id: userId,
413
+ nickname: userId,
414
+ remark: 'ilink: 从会话 context_token 推导,非通讯录',
415
+ }));
416
+ },
417
+ });
418
+ }
@@ -18,6 +18,7 @@ export declare function apiGetFetch(params: {
18
18
  endpoint: string;
19
19
  timeoutMs?: number;
20
20
  label: string;
21
+ abortSignal?: AbortSignal;
21
22
  }): Promise<string>;
22
23
  /**
23
24
  * Common fetch wrapper: POST JSON to a Weixin API endpoint.
@@ -78,4 +79,3 @@ export declare function notifyStop(params: WeixinApiOptions): Promise<NotifyStop
78
79
  * Notify Weixin that this channel client is starting (gateway startup / channel start).
79
80
  */
80
81
  export declare function notifyStart(params: WeixinApiOptions): Promise<NotifyStartResp>;
81
- //# sourceMappingURL=ilink-api.d.ts.map
package/lib/ilink-api.js CHANGED
@@ -54,11 +54,12 @@ export async function apiGetFetch(params) {
54
54
  const t = controller != null && timeoutMs != null
55
55
  ? setTimeout(() => controller.abort(), timeoutMs)
56
56
  : undefined;
57
+ const { signal, cleanup } = combineAbortSignals(controller, params.abortSignal);
57
58
  try {
58
59
  const res = await fetch(url.toString(), {
59
60
  method: "GET",
60
61
  headers: hdrs,
61
- ...(controller ? { signal: controller.signal } : {}),
62
+ ...(signal ? { signal } : {}),
62
63
  });
63
64
  if (t !== undefined)
64
65
  clearTimeout(t);
@@ -74,6 +75,9 @@ export async function apiGetFetch(params) {
74
75
  clearTimeout(t);
75
76
  throw err;
76
77
  }
78
+ finally {
79
+ cleanup();
80
+ }
77
81
  }
78
82
  function combineAbortSignals(internal, external) {
79
83
  if (!internal && !external)
@@ -270,4 +274,3 @@ export async function notifyStart(params) {
270
274
  });
271
275
  return JSON.parse(rawText);
272
276
  }
273
- //# sourceMappingURL=ilink-api.js.map
@@ -16,4 +16,3 @@ export declare class WeixinConfigManager {
16
16
  }, log: (msg: string) => void);
17
17
  getForUser(userId: string, contextToken?: string): Promise<CachedConfig>;
18
18
  }
19
- //# sourceMappingURL=ilink-config-cache.d.ts.map
@@ -61,4 +61,3 @@ export class WeixinConfigManager {
61
61
  return this.cache.get(userId)?.config ?? { typingTicket: "" };
62
62
  }
63
63
  }
64
- //# sourceMappingURL=ilink-config-cache.js.map
@@ -7,4 +7,3 @@ export type IlinkLogger = {
7
7
  };
8
8
  export declare function setIlinkLogger(next: IlinkLogger): void;
9
9
  export declare const logger: IlinkLogger;
10
- //# sourceMappingURL=ilink-logger.d.ts.map
@@ -24,4 +24,3 @@ export const logger = {
24
24
  error: (msg) => sink.error(msg),
25
25
  withAccount: (accountId) => sink.withAccount(accountId),
26
26
  };
27
- //# sourceMappingURL=ilink-logger.js.map
@@ -10,4 +10,3 @@ export declare function buildClientVersion(version: string): number;
10
10
  export declare const ILINK_APP_CLIENT_VERSION: number;
11
11
  export declare function sanitizeBotAgent(raw: string | undefined): string;
12
12
  export declare function buildBaseInfo(): BaseInfo;
13
- //# sourceMappingURL=ilink-meta.d.ts.map
package/lib/ilink-meta.js CHANGED
@@ -54,4 +54,3 @@ export function buildBaseInfo() {
54
54
  bot_agent: sanitizeBotAgent(configuredBotAgent),
55
55
  };
56
56
  }
57
- //# sourceMappingURL=ilink-meta.js.map
@@ -8,4 +8,3 @@ export declare function generateId(prefix: string): string;
8
8
  * Format: `{prefix}-{timestamp}-{8-char hex}{ext}`
9
9
  */
10
10
  export declare function tempFileName(prefix: string, ext: string): string;
11
- //# sourceMappingURL=ilink-random.d.ts.map
@@ -13,4 +13,3 @@ export function generateId(prefix) {
13
13
  export function tempFileName(prefix, ext) {
14
14
  return `${prefix}-${Date.now()}-${crypto.randomBytes(4).toString("hex")}${ext}`;
15
15
  }
16
- //# sourceMappingURL=ilink-random.js.map
@@ -18,4 +18,3 @@ export declare function redactBody(body: string | undefined, maxLen?: number): s
18
18
  * keeping only origin + pathname.
19
19
  */
20
20
  export declare function redactUrl(rawUrl: string): string;
21
- //# sourceMappingURL=ilink-redact.d.ts.map
@@ -51,4 +51,3 @@ export function redactUrl(rawUrl) {
51
51
  return truncate(rawUrl, 80);
52
52
  }
53
53
  }
54
- //# sourceMappingURL=ilink-redact.js.map
@@ -13,4 +13,3 @@ export declare function assertSessionActive(accountId: string): void;
13
13
  * @internal
14
14
  */
15
15
  export declare function _resetForTest(): void;
16
- //# sourceMappingURL=ilink-session-guard.d.ts.map
@@ -46,4 +46,3 @@ export function assertSessionActive(accountId) {
46
46
  export function _resetForTest() {
47
47
  pauseUntilMap.clear();
48
48
  }
49
- //# sourceMappingURL=ilink-session-guard.js.map
@@ -230,4 +230,3 @@ export interface NotifyStartResp {
230
230
  ret?: number;
231
231
  errmsg?: string;
232
232
  }
233
- //# sourceMappingURL=ilink-types.d.ts.map
@@ -32,4 +32,3 @@ export const TypingStatus = {
32
32
  TYPING: 1,
33
33
  CANCEL: 2,
34
34
  };
35
- //# sourceMappingURL=ilink-types.js.map
package/lib/index.d.ts CHANGED
@@ -1,20 +1,5 @@
1
- import type { Router } from "@zhin.js/host-router";
2
- import { PageManager } from "@zhin.js/host-api";
3
- import { WeixinIlinkAdapter } from "./adapter.js";
4
- declare module "zhin.js" {
5
- namespace Plugin {
6
- interface Contexts {
7
- web: PageManager;
8
- router: Router;
9
- }
10
- }
11
- interface Adapters {
12
- "weixin-ilink": WeixinIlinkAdapter;
13
- }
14
- }
15
- export * from "./types.js";
16
- export { WeixinIlinkBot } from "./bot.js";
17
- export { WeixinIlinkAdapter } from "./adapter.js";
18
- export { WeixinIlinkTypingIndicatorManager, enableTypingIndicator, type WeixinIlinkTypingIndicatorConfig, } from "./typing-indicator.js";
19
- export { registerLoginAssistRoutes } from "./login-assist-routes.js";
20
- //# sourceMappingURL=index.d.ts.map
1
+ export { formatInboundContent, formatOutboundSegments, inboundMessageId, resolveWeixinIlinkConfig, segmentLocalPath, sleep, type ResolvedWeixinIlinkConfig, type WeixinIlinkAdapterConfig, type WeixinIlinkEndpointConfig, type WeixinInboundMediaPaths, type WeixinMessageWithMedia, type WeixinWireSegment, } from './protocol.js';
2
+ export type { WeixinMessage, MessageItem } from './ilink-types.js';
3
+ export type { WeixinIlinkCredentials } from './credentials.js';
4
+ export { WeixinIlinkClient, weixinIlinkClient, type WeixinIlinkClientEventMap, } from './client.js';
5
+ export { WeixinIlinkEndpoint, type WeixinIlinkEndpointOptions, type WeixinIlinkGetUpdates, type WeixinIlinkNotifyStart, type WeixinIlinkNotifyStop, type WeixinIlinkSendText, } from './endpoint.js';
package/lib/index.js CHANGED
@@ -1,38 +1,3 @@
1
- /**
2
- * 微信 iLink(ClawBot)适配器入口
3
- */
4
- import path from "node:path";
5
- import { usePlugin } from "zhin.js";
6
- import { WeixinIlinkAdapter } from "./adapter.js";
7
- import { registerRoutes } from "./routes.js";
8
- export * from "./types.js";
9
- export { WeixinIlinkBot } from "./bot.js";
10
- export { WeixinIlinkAdapter } from "./adapter.js";
11
- export { WeixinIlinkTypingIndicatorManager, enableTypingIndicator, } from "./typing-indicator.js";
12
- export { registerLoginAssistRoutes } from "./login-assist-routes.js";
13
- const plugin = usePlugin();
14
- const { provide, useContext, root } = plugin;
15
- provide({
16
- name: "weixin-ilink",
17
- description: "WeChat personal account via Tencent iLink Bot API (ClawBot)",
18
- mounted: async (p) => {
19
- const adapter = new WeixinIlinkAdapter(p);
20
- await adapter.start();
21
- return adapter;
22
- },
23
- dispose: async (adapter) => {
24
- await adapter.stop();
25
- },
26
- });
27
- useContext("web", (pageManager) => {
28
- pageManager.addEntry({
29
- id: "weixin-ilink",
30
- development: path.resolve(import.meta.dirname, "../client/index.tsx"),
31
- production: path.resolve(import.meta.dirname, "../dist/index.js"),
32
- meta: { name: "微信 iLink" },
33
- });
34
- });
35
- useContext("router", "weixin-ilink", async (router, adapter) => {
36
- registerRoutes(router, adapter, root);
37
- });
38
- //# sourceMappingURL=index.js.map
1
+ export { formatInboundContent, formatOutboundSegments, inboundMessageId, resolveWeixinIlinkConfig, segmentLocalPath, sleep, } from './protocol.js';
2
+ export { WeixinIlinkClient, weixinIlinkClient, } from './client.js';
3
+ export { WeixinIlinkEndpoint, } from './endpoint.js';
package/lib/login.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import type { Plugin } from "zhin.js";
2
- import { type WeixinIlinkCredentials } from "./credentials.js";
3
- import type { WeixinIlinkBotConfig } from "./types.js";
4
- export declare function resolveCredentials(plugin: Plugin, config: WeixinIlinkBotConfig): Promise<WeixinIlinkCredentials>;
5
- export declare function loginWithQr(plugin: Plugin, config: WeixinIlinkBotConfig): Promise<WeixinIlinkCredentials>;
6
- //# sourceMappingURL=login.d.ts.map
1
+ import { type WeixinIlinkCredentials } from './credentials.js';
2
+ import type { ResolvedWeixinIlinkConfig } from './protocol.js';
3
+ export declare function resolveCredentials(config: ResolvedWeixinIlinkConfig, signal?: AbortSignal): Promise<WeixinIlinkCredentials>;
4
+ export declare function loginWithQr(config: ResolvedWeixinIlinkConfig, signal?: AbortSignal): Promise<WeixinIlinkCredentials>;