pi-wechat-session-hub 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,390 +1,386 @@
1
- import { randomBytes, randomUUID } from "node:crypto";
2
- import type { IlinkGetUpdatesResponse } from "../channel-types.ts";
3
-
4
- /**
5
- * iLink bot 凭证, 由外部调用方显式注入且不会由客户端持久化。
6
- */
7
- export interface IlinkCredentials {
8
- token: string;
9
- baseUrl: string;
10
- }
11
-
12
- export interface IlinkTypingConfig {
13
- typingTicket?: string;
14
- }
15
-
16
- export type IlinkTypingStatus = 1 | 2;
17
-
18
- /**
19
- * iLink API client 的可选网络和协议配置。
20
- */
21
- export interface IlinkApiClientOptions {
22
- credentials: IlinkCredentials;
23
- fetcher?: typeof fetch;
24
- channelVersion?: string;
25
- apiTimeoutMs?: number;
26
- longPollTimeoutMs?: number;
27
- allowCustomBaseUrl?: boolean;
28
- }
29
-
30
- /**
31
- * iLink API 错误代码, 不包含服务端原始响应正文。
32
- */
33
- export type IlinkApiErrorCode =
34
- | "invalid_credentials"
35
- | "invalid_base_url"
36
- | "network_error"
37
- | "request_timeout"
38
- | "http_error"
39
- | "invalid_response"
40
- | "api_error"
41
- | "session_expired"
42
- | "context_token_missing"
43
- | "message_too_long";
44
-
45
- /**
46
- * 表示 iLink API 请求或协议响应失败。
47
- */
48
- export class IlinkApiError extends Error {
49
- /**
50
- * 创建 iLink API 错误, 不包含 token 或原始响应正文。
51
- *
52
- * @param code 稳定错误代码。
53
- * @param message 面向用户的中文说明。
54
- */
55
- constructor(
56
- readonly code: IlinkApiErrorCode,
57
- message: string,
58
- ) {
59
- super(message);
60
- this.name = "IlinkApiError";
61
- }
62
- }
63
-
64
- /**
65
- * 以注入的独立 Bot 凭证调用 iLink text/getUpdates API; QR 登录由独立登录服务处理。
66
- */
67
- export class IlinkApiClient {
68
- private readonly token: string;
69
- private readonly baseUrl: string;
70
- private readonly fetcher: typeof fetch;
71
- private readonly channelVersion: string;
72
- private readonly apiTimeoutMs: number;
73
- private readonly longPollTimeoutMs: number;
74
-
75
- /**
76
- * 创建 iLink API 客户端。
77
- *
78
- * @param options 独立凭证、endpoint 和网络实现。
79
- * @throws {IlinkApiError} 凭证或 baseUrl 非法时抛出。
80
- */
81
- constructor(options: IlinkApiClientOptions) {
82
- if (!options.credentials.token.trim()) {
83
- throw new IlinkApiError("invalid_credentials", "iLink bot token 不能为空。");
84
- }
85
- let endpoint: URL;
86
- try {
87
- endpoint = new URL(options.credentials.baseUrl);
88
- } catch {
89
- throw new IlinkApiError("invalid_base_url", "iLink baseUrl 不是有效 URL。");
90
- }
91
- const loopbackHttp = endpoint.protocol === "http:" &&
92
- (endpoint.hostname === "127.0.0.1" || endpoint.hostname === "localhost" || endpoint.hostname === "::1");
93
- const knownIlinkHost = endpoint.hostname === "ilinkai.weixin.qq.com" ||
94
- endpoint.hostname.endsWith(".ilinkai.weixin.qq.com");
95
- if (
96
- (endpoint.protocol !== "https:" && !loopbackHttp) ||
97
- (endpoint.protocol === "https:" && !knownIlinkHost && !options.allowCustomBaseUrl) ||
98
- endpoint.username ||
99
- endpoint.password ||
100
- endpoint.search ||
101
- endpoint.hash
102
- ) {
103
- throw new IlinkApiError(
104
- "invalid_base_url",
105
- "iLink baseUrl 必须是受支持的 HTTPS endpoint, 且不能包含用户信息或 query。",
106
- );
107
- }
108
-
109
- this.token = options.credentials.token;
110
- this.baseUrl = options.credentials.baseUrl.replace(/\/+$/, "");
111
- this.fetcher = options.fetcher ?? fetch;
112
- this.channelVersion = options.channelVersion ?? "pi-wechat-session-hub/0.1.0";
113
- this.apiTimeoutMs = options.apiTimeoutMs ?? 15000;
114
- this.longPollTimeoutMs = options.longPollTimeoutMs ?? 35000;
115
- }
116
-
117
- /**
118
- * 读取指定微信用户的 typing_ticket。
119
- *
120
- * @param recipientId 微信用户 ID。
121
- * @param contextToken 当前入站消息的 context_token。
122
- * @returns typing_ticket, 服务端未提供时为空。
123
- * @throws {IlinkApiError} iLink 请求或业务响应失败时抛出。
124
- */
125
- async getTypingConfig(recipientId: string, contextToken: string): Promise<IlinkTypingConfig> {
126
- if (!recipientId.trim() || !contextToken.trim()) {
127
- throw new IlinkApiError("context_token_missing", "获取 typing_ticket 必须提供微信用户和 context_token。");
128
- }
129
- const response = await this.post<Record<string, unknown>>(
130
- "getconfig",
131
- {
132
- ilink_user_id: recipientId,
133
- context_token: contextToken,
134
- base_info: { channel_version: this.channelVersion },
135
- },
136
- this.apiTimeoutMs,
137
- );
138
- this.assertApiSuccess(
139
- typeof response.ret === "number" ? response.ret : undefined,
140
- typeof response.errcode === "number" ? response.errcode : undefined,
141
- typeof response.errmsg === "string" ? response.errmsg : undefined,
142
- );
143
- if (response.typing_ticket !== undefined && typeof response.typing_ticket !== "string") {
144
- throw new IlinkApiError("invalid_response", "iLink getconfig 返回了无效 typing_ticket。");
145
- }
146
- return typeof response.typing_ticket === "string" && response.typing_ticket.trim()
147
- ? { typingTicket: response.typing_ticket }
148
- : {};
149
- }
150
-
151
- /**
152
- * 开始或取消微信端的原生“正在输入”状态。
153
- *
154
- * @param recipientId 微信用户 ID。
155
- * @param typingTicket getconfig 返回的 typing_ticket。
156
- * @param status 1 表示正在输入, 2 表示取消。
157
- * @returns 业务成功时正常结束。
158
- * @throws {IlinkApiError} typing_ticket 无效或 API 请求失败时抛出。
159
- */
160
- async sendTyping(
161
- recipientId: string,
162
- typingTicket: string,
163
- status: IlinkTypingStatus,
164
- ): Promise<void> {
165
- if (!recipientId.trim() || !typingTicket.trim()) {
166
- throw new IlinkApiError("invalid_credentials", "sendtyping 必须提供微信用户和 typing_ticket。");
167
- }
168
- const response = await this.post<Record<string, unknown>>(
169
- "sendtyping",
170
- {
171
- ilink_user_id: recipientId,
172
- typing_ticket: typingTicket,
173
- status,
174
- base_info: { channel_version: this.channelVersion },
175
- },
176
- this.apiTimeoutMs,
177
- );
178
- this.assertApiSuccess(
179
- typeof response.ret === "number" ? response.ret : undefined,
180
- typeof response.errcode === "number" ? response.errcode : undefined,
181
- typeof response.errmsg === "string" ? response.errmsg : undefined,
182
- );
183
- }
184
-
185
- /**
186
- * 发起一次 iLink getupdates 长轮询。
187
- *
188
- * @param cursor 上次服务端返回的 get_updates_buf; 首次传空字符串。
189
- * @param signal 用于 Gateway 优雅停止的 AbortSignal。
190
- * @returns 更新响应, 包含新游标和消息批次。
191
- * @throws {IlinkApiError} 网络、协议或 session 过期时抛出。
192
- */
193
- async getUpdates(
194
- cursor: string,
195
- signal?: AbortSignal,
196
- longPollTimeoutMs = this.longPollTimeoutMs,
197
- ): Promise<IlinkGetUpdatesResponse> {
198
- const response = await this.post<IlinkGetUpdatesResponse>(
199
- "getupdates",
200
- {
201
- get_updates_buf: cursor,
202
- base_info: { channel_version: this.channelVersion },
203
- },
204
- longPollTimeoutMs + 10000,
205
- signal,
206
- );
207
- this.assertApiSuccess(response.ret, response.errcode, response.errmsg);
208
- if (response.msgs !== undefined && !Array.isArray(response.msgs)) {
209
- throw new IlinkApiError("invalid_response", "iLink getupdates 返回了无效 msgs 字段。");
210
- }
211
- if (response.get_updates_buf !== undefined && typeof response.get_updates_buf !== "string") {
212
- throw new IlinkApiError("invalid_response", "iLink getupdates 返回了无效同步游标。");
213
- }
214
- return response;
215
- }
216
-
217
- /**
218
- * 在指定微信会话上下文中发送一条文本回复。
219
- *
220
- * @param recipientId 微信用户 ID。
221
- * @param text 回复正文, 每条 text item 最多 2000 个 Unicode 字符。
222
- * @param contextToken 对应入站消息的 context_token。
223
- * @param clientId 可选幂等发送 ID。
224
- * @returns 用于排查的 clientId。
225
- * @throws {IlinkApiError} context、正文或 API 请求不合法时抛出。
226
- */
227
- async sendText(
228
- recipientId: string,
229
- text: string,
230
- contextToken: string,
231
- clientId: string = randomUUID(),
232
- ): Promise<{ clientId: string }> {
233
- if (!recipientId.trim() || !contextToken.trim()) {
234
- throw new IlinkApiError(
235
- "context_token_missing",
236
- "发送 iLink 回复必须提供 recipientId 和对应的 context_token。",
237
- );
238
- }
239
- if (!text.trim()) {
240
- throw new IlinkApiError("invalid_response", "不能发送空的 iLink 文本消息。");
241
- }
242
- if (Array.from(text).length > 32000) {
243
- throw new IlinkApiError(
244
- "message_too_long",
245
- "iLink 回复超过单次 sendmessage 的 32000 字符上限。",
246
- );
247
- }
248
- const textItems = splitTextItems(text, 2000);
249
-
250
- const response = await this.post<Record<string, unknown>>(
251
- "sendmessage",
252
- {
253
- msg: {
254
- from_user_id: "",
255
- to_user_id: recipientId,
256
- client_id: clientId,
257
- message_type: 2,
258
- message_state: 2,
259
- context_token: contextToken,
260
- item_list: textItems.map((textItem) => ({ type: 1, text_item: { text: textItem } })),
261
- },
262
- base_info: { channel_version: this.channelVersion },
263
- },
264
- this.apiTimeoutMs,
265
- );
266
- this.assertApiSuccess(
267
- typeof response.ret === "number" ? response.ret : undefined,
268
- typeof response.errcode === "number" ? response.errcode : undefined,
269
- typeof response.errmsg === "string" ? response.errmsg : undefined,
270
- );
271
- return { clientId };
272
- }
273
-
274
- /**
275
- * 发送一个 iLink POST 请求并校验 JSON 响应。
276
- *
277
- * @param endpoint iLink bot API 端点名。
278
- * @param body JSON 请求体。
279
- * @param timeoutMs 请求超时。
280
- * @param signal 可选外部取消信号。
281
- * @returns 解码后的 JSON 响应。
282
- */
283
- private async post<T extends object>(
284
- endpoint: string,
285
- body: Record<string, unknown>,
286
- timeoutMs: number,
287
- signal?: AbortSignal,
288
- ): Promise<T> {
289
- const controller = new AbortController();
290
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
291
- timeout.unref();
292
- const abortFromCaller = (): void => controller.abort();
293
- if (signal?.aborted) {
294
- controller.abort();
295
- } else {
296
- signal?.addEventListener("abort", abortFromCaller, { once: true });
297
- }
298
-
299
- try {
300
- const response = await this.fetcher(`${this.baseUrl}/ilink/bot/${endpoint}`, {
301
- method: "POST",
302
- headers: {
303
- "Content-Type": "application/json",
304
- AuthorizationType: "ilink_bot_token",
305
- Authorization: `Bearer ${this.token}`,
306
- "X-WECHAT-UIN": randomWechatUin(),
307
- "iLink-App-Id": "bot",
308
- "iLink-App-ClientVersion": "1",
309
- },
310
- body: JSON.stringify(body),
311
- signal: controller.signal,
312
- });
313
- if (!response.ok) {
314
- throw new IlinkApiError("http_error", `iLink API HTTP ${response.status}。`);
315
- }
316
- let parsed: unknown;
317
- try {
318
- parsed = await response.json() as unknown;
319
- } catch {
320
- throw new IlinkApiError("invalid_response", "iLink API 返回了无效 JSON。");
321
- }
322
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
323
- throw new IlinkApiError("invalid_response", "iLink API 响应根节点必须是对象。");
324
- }
325
- return parsed as T;
326
- } catch (error) {
327
- if (error instanceof IlinkApiError) {
328
- throw error;
329
- }
330
- if (controller.signal.aborted) {
331
- throw new IlinkApiError("request_timeout", "iLink API 请求超时或已取消。");
332
- }
333
- throw new IlinkApiError("network_error", "iLink API 网络请求失败。");
334
- } finally {
335
- clearTimeout(timeout);
336
- signal?.removeEventListener("abort", abortFromCaller);
337
- }
338
- }
339
-
340
- /**
341
- * 校验 iLink 业务响应状态。
342
- *
343
- * @param ret 响应 ret。
344
- * @param errorCode 响应 errcode。
345
- * @param errorMessage 响应 errmsg, 不会原样输出。
346
- * @returns 无返回值。
347
- * @throws {IlinkApiError} iLink 返回业务错误时抛出。
348
- */
349
- private assertApiSuccess(
350
- ret: number | undefined,
351
- errorCode: number | undefined,
352
- errorMessage: string | undefined,
353
- ): void {
354
- const code = [errorCode, ret].find((value) => typeof value === "number" && value !== 0);
355
- if (code === undefined) {
356
- return;
357
- }
358
- if (code === -14) {
359
- throw new IlinkApiError("session_expired", "iLink session 已过期; 不会自动重新登录或修改凭证。");
360
- }
361
- const suffix = typeof errorMessage === "string" && errorMessage.trim() ? " 服务端返回业务错误。" : "";
362
- throw new IlinkApiError("api_error", `iLink API 业务请求失败 (${code}).${suffix}`);
363
- }
364
- }
365
-
366
- /**
367
- * 将回复文本切分为多个 text item, 由单次 sendmessage 顺序提交。
368
- *
369
- * @param text 回复正文。
370
- * @param maxChars 每个 text item 的最大 Unicode 字符数。
371
- * @returns 有序文本片段列表。
372
- */
373
- function splitTextItems(text: string, maxChars: number): string[] {
374
- const characters = Array.from(text);
375
- const chunks: string[] = [];
376
- for (let offset = 0; offset < characters.length; offset += maxChars) {
377
- chunks.push(characters.slice(offset, offset + maxChars).join(""));
378
- }
379
- return chunks;
380
- }
381
-
382
- /**
383
- * 为每次 iLink 请求生成随机 X-WECHAT-UIN。
384
- *
385
- * @returns 随机 uint32 十进制文本的 Base64 编码。
386
- */
387
- function randomWechatUin(): string {
388
- const value = randomBytes(4).readUInt32BE(0);
389
- return Buffer.from(String(value), "utf8").toString("base64");
390
- }
1
+ import { randomBytes, randomUUID } from "node:crypto";
2
+ import type { IlinkGetUpdatesResponse } from "../channel-types.ts";
3
+
4
+ /**
5
+ * iLink bot 凭证, 由外部调用方显式注入且不会由客户端持久化。
6
+ */
7
+ export interface IlinkCredentials {
8
+ token: string;
9
+ baseUrl: string;
10
+ }
11
+
12
+ export interface IlinkTypingConfig {
13
+ typingTicket?: string;
14
+ }
15
+
16
+ export type IlinkTypingStatus = 1 | 2;
17
+
18
+ /**
19
+ * iLink API client 的可选网络和协议配置。
20
+ */
21
+ export interface IlinkApiClientOptions {
22
+ credentials: IlinkCredentials;
23
+ fetcher?: typeof fetch;
24
+ channelVersion?: string;
25
+ apiTimeoutMs?: number;
26
+ longPollTimeoutMs?: number;
27
+ allowCustomBaseUrl?: boolean;
28
+ }
29
+
30
+ /**
31
+ * iLink API 错误代码, 不包含服务端原始响应正文。
32
+ */
33
+ export type IlinkApiErrorCode =
34
+ | "invalid_credentials"
35
+ | "invalid_base_url"
36
+ | "network_error"
37
+ | "request_timeout"
38
+ | "http_error"
39
+ | "invalid_response"
40
+ | "api_error"
41
+ | "session_expired"
42
+ | "context_token_missing"
43
+ | "message_too_long";
44
+
45
+ /**
46
+ * 表示 iLink API 请求或协议响应失败。
47
+ */
48
+ export class IlinkApiError extends Error {
49
+ /**
50
+ * 创建 iLink API 错误, 不包含 token 或原始响应正文。
51
+ *
52
+ * @param code 稳定错误代码。
53
+ * @param message 面向用户的中文说明。
54
+ */
55
+ constructor(
56
+ readonly code: IlinkApiErrorCode,
57
+ message: string,
58
+ ) {
59
+ super(message);
60
+ this.name = "IlinkApiError";
61
+ }
62
+ }
63
+
64
+ /**
65
+ * 以注入的独立 Bot 凭证调用 iLink text/getUpdates API; QR 登录由独立登录服务处理。
66
+ */
67
+ export class IlinkApiClient {
68
+ private readonly token: string;
69
+ private readonly baseUrl: string;
70
+ private readonly fetcher: typeof fetch;
71
+ private readonly channelVersion: string;
72
+ private readonly apiTimeoutMs: number;
73
+ private readonly longPollTimeoutMs: number;
74
+
75
+ /**
76
+ * 创建 iLink API 客户端。
77
+ *
78
+ * @param options 独立凭证、endpoint 和网络实现。
79
+ * @throws {IlinkApiError} 凭证或 baseUrl 非法时抛出。
80
+ */
81
+ constructor(options: IlinkApiClientOptions) {
82
+ if (!options.credentials.token.trim()) {
83
+ throw new IlinkApiError("invalid_credentials", "iLink bot token 不能为空。");
84
+ }
85
+ let endpoint: URL;
86
+ try {
87
+ endpoint = new URL(options.credentials.baseUrl);
88
+ } catch {
89
+ throw new IlinkApiError("invalid_base_url", "iLink baseUrl 不是有效 URL。");
90
+ }
91
+ const loopbackHttp = endpoint.protocol === "http:" &&
92
+ (endpoint.hostname === "127.0.0.1" || endpoint.hostname === "localhost" || endpoint.hostname === "::1");
93
+ const knownIlinkHost = endpoint.hostname === "ilinkai.weixin.qq.com" ||
94
+ endpoint.hostname.endsWith(".ilinkai.weixin.qq.com");
95
+ if (
96
+ (endpoint.protocol !== "https:" && !loopbackHttp) ||
97
+ (endpoint.protocol === "https:" && !knownIlinkHost && !options.allowCustomBaseUrl) ||
98
+ endpoint.username ||
99
+ endpoint.password ||
100
+ endpoint.search ||
101
+ endpoint.hash
102
+ ) {
103
+ throw new IlinkApiError(
104
+ "invalid_base_url",
105
+ "iLink baseUrl 必须是受支持的 HTTPS endpoint, 且不能包含用户信息或 query。",
106
+ );
107
+ }
108
+
109
+ this.token = options.credentials.token;
110
+ this.baseUrl = options.credentials.baseUrl.replace(/\/+$/, "");
111
+ this.fetcher = options.fetcher ?? fetch;
112
+ this.channelVersion = options.channelVersion ?? "pi-wechat-session-hub/0.1.0";
113
+ this.apiTimeoutMs = options.apiTimeoutMs ?? 15000;
114
+ this.longPollTimeoutMs = options.longPollTimeoutMs ?? 35000;
115
+ }
116
+
117
+ /**
118
+ * 读取指定微信用户的 typing_ticket。
119
+ *
120
+ * @param recipientId 微信用户 ID。
121
+ * @param contextToken 当前入站消息的 context_token。
122
+ * @returns typing_ticket, 服务端未提供时为空。
123
+ * @throws {IlinkApiError} iLink 请求或业务响应失败时抛出。
124
+ */
125
+ async getTypingConfig(recipientId: string, contextToken: string): Promise<IlinkTypingConfig> {
126
+ if (!recipientId.trim() || !contextToken.trim()) {
127
+ throw new IlinkApiError("context_token_missing", "获取 typing_ticket 必须提供微信用户和 context_token。");
128
+ }
129
+ const response = await this.post<Record<string, unknown>>(
130
+ "getconfig",
131
+ {
132
+ ilink_user_id: recipientId,
133
+ context_token: contextToken,
134
+ base_info: { channel_version: this.channelVersion },
135
+ },
136
+ this.apiTimeoutMs,
137
+ );
138
+ this.assertApiSuccess(
139
+ typeof response.ret === "number" ? response.ret : undefined,
140
+ typeof response.errcode === "number" ? response.errcode : undefined,
141
+ typeof response.errmsg === "string" ? response.errmsg : undefined,
142
+ );
143
+ if (response.typing_ticket !== undefined && typeof response.typing_ticket !== "string") {
144
+ throw new IlinkApiError("invalid_response", "iLink getconfig 返回了无效 typing_ticket。");
145
+ }
146
+ return typeof response.typing_ticket === "string" && response.typing_ticket.trim()
147
+ ? { typingTicket: response.typing_ticket }
148
+ : {};
149
+ }
150
+
151
+ /**
152
+ * 开始或取消微信端的原生“正在输入”状态。
153
+ *
154
+ * @param recipientId 微信用户 ID。
155
+ * @param typingTicket getconfig 返回的 typing_ticket。
156
+ * @param status 1 表示正在输入, 2 表示取消。
157
+ * @returns 业务成功时正常结束。
158
+ * @throws {IlinkApiError} typing_ticket 无效或 API 请求失败时抛出。
159
+ */
160
+ async sendTyping(
161
+ recipientId: string,
162
+ typingTicket: string,
163
+ status: IlinkTypingStatus,
164
+ ): Promise<void> {
165
+ if (!recipientId.trim() || !typingTicket.trim()) {
166
+ throw new IlinkApiError("invalid_credentials", "sendtyping 必须提供微信用户和 typing_ticket。");
167
+ }
168
+ const response = await this.post<Record<string, unknown>>(
169
+ "sendtyping",
170
+ {
171
+ ilink_user_id: recipientId,
172
+ typing_ticket: typingTicket,
173
+ status,
174
+ base_info: { channel_version: this.channelVersion },
175
+ },
176
+ this.apiTimeoutMs,
177
+ );
178
+ this.assertApiSuccess(
179
+ typeof response.ret === "number" ? response.ret : undefined,
180
+ typeof response.errcode === "number" ? response.errcode : undefined,
181
+ typeof response.errmsg === "string" ? response.errmsg : undefined,
182
+ );
183
+ }
184
+
185
+ /**
186
+ * 发起一次 iLink getupdates 长轮询。
187
+ *
188
+ * @param cursor 上次服务端返回的 get_updates_buf; 首次传空字符串。
189
+ * @param signal 用于 Gateway 优雅停止的 AbortSignal。
190
+ * @returns 更新响应, 包含新游标和消息批次。
191
+ * @throws {IlinkApiError} 网络、协议或 session 过期时抛出。
192
+ */
193
+ async getUpdates(
194
+ cursor: string,
195
+ signal?: AbortSignal,
196
+ longPollTimeoutMs = this.longPollTimeoutMs,
197
+ ): Promise<IlinkGetUpdatesResponse> {
198
+ const response = await this.post<IlinkGetUpdatesResponse>(
199
+ "getupdates",
200
+ {
201
+ get_updates_buf: cursor,
202
+ base_info: { channel_version: this.channelVersion },
203
+ },
204
+ longPollTimeoutMs + 10000,
205
+ signal,
206
+ );
207
+ this.assertApiSuccess(response.ret, response.errcode, response.errmsg);
208
+ if (response.msgs !== undefined && !Array.isArray(response.msgs)) {
209
+ throw new IlinkApiError("invalid_response", "iLink getupdates 返回了无效 msgs 字段。");
210
+ }
211
+ if (response.get_updates_buf !== undefined && typeof response.get_updates_buf !== "string") {
212
+ throw new IlinkApiError("invalid_response", "iLink getupdates 返回了无效同步游标。");
213
+ }
214
+ return response;
215
+ }
216
+
217
+ /**
218
+ * 在指定微信会话上下文中发送一条文本回复。
219
+ *
220
+ * @param recipientId 微信用户 ID。
221
+ * @param text 回复正文, 每条 text item 最多 2000 个 Unicode 字符。
222
+ * @param contextToken 对应入站消息的 context_token。
223
+ * @param clientId 可选幂等发送 ID。
224
+ * @returns 用于排查的 clientId。
225
+ * @throws {IlinkApiError} context、正文或 API 请求不合法时抛出。
226
+ */
227
+ async sendText(
228
+ recipientId: string,
229
+ text: string,
230
+ contextToken: string,
231
+ clientId: string = randomUUID(),
232
+ ): Promise<{ clientId: string }> {
233
+ if (!recipientId.trim() || !contextToken.trim()) {
234
+ throw new IlinkApiError(
235
+ "context_token_missing",
236
+ "发送 iLink 回复必须提供 recipientId 和对应的 context_token。",
237
+ );
238
+ }
239
+ if (!text.trim()) {
240
+ throw new IlinkApiError("invalid_response", "不能发送空的 iLink 文本消息。");
241
+ }
242
+ // iLink 只接受单 text_item 消息: 实测 item_list 含 2 项时即使总长只有 30 字
243
+ // 也会返回 ret=-2 prepare failed, 所以绝不拆分正文。
244
+ const body = {
245
+ msg: {
246
+ from_user_id: "",
247
+ to_user_id: recipientId,
248
+ client_id: clientId,
249
+ message_type: 2,
250
+ message_state: 2,
251
+ context_token: contextToken,
252
+ item_list: [{ type: 1, text_item: { text } }],
253
+ },
254
+ base_info: { channel_version: this.channelVersion },
255
+ };
256
+ const bodyBytes = Buffer.byteLength(JSON.stringify(body), "utf8");
257
+ if (bodyBytes > MAX_SENDMESSAGE_BODY_BYTES) {
258
+ throw new IlinkApiError(
259
+ "message_too_long",
260
+ `iLink 回复请求体 ${bodyBytes} 字节, 超过实测上限 ${MAX_SENDMESSAGE_BODY_BYTES} 字节。`,
261
+ );
262
+ }
263
+
264
+ const response = await this.post<Record<string, unknown>>(
265
+ "sendmessage",
266
+ body,
267
+ this.apiTimeoutMs,
268
+ );
269
+ this.assertApiSuccess(
270
+ typeof response.ret === "number" ? response.ret : undefined,
271
+ typeof response.errcode === "number" ? response.errcode : undefined,
272
+ typeof response.errmsg === "string" ? response.errmsg : undefined,
273
+ );
274
+ return { clientId };
275
+ }
276
+
277
+ /**
278
+ * 发送一个 iLink POST 请求并校验 JSON 响应。
279
+ *
280
+ * @param endpoint iLink bot API 端点名。
281
+ * @param body JSON 请求体。
282
+ * @param timeoutMs 请求超时。
283
+ * @param signal 可选外部取消信号。
284
+ * @returns 解码后的 JSON 响应。
285
+ */
286
+ private async post<T extends object>(
287
+ endpoint: string,
288
+ body: Record<string, unknown>,
289
+ timeoutMs: number,
290
+ signal?: AbortSignal,
291
+ ): Promise<T> {
292
+ const controller = new AbortController();
293
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
294
+ timeout.unref();
295
+ const abortFromCaller = (): void => controller.abort();
296
+ if (signal?.aborted) {
297
+ controller.abort();
298
+ } else {
299
+ signal?.addEventListener("abort", abortFromCaller, { once: true });
300
+ }
301
+
302
+ try {
303
+ const response = await this.fetcher(`${this.baseUrl}/ilink/bot/${endpoint}`, {
304
+ method: "POST",
305
+ headers: {
306
+ "Content-Type": "application/json",
307
+ AuthorizationType: "ilink_bot_token",
308
+ Authorization: `Bearer ${this.token}`,
309
+ "X-WECHAT-UIN": randomWechatUin(),
310
+ "iLink-App-Id": "bot",
311
+ "iLink-App-ClientVersion": "1",
312
+ },
313
+ body: JSON.stringify(body),
314
+ signal: controller.signal,
315
+ });
316
+ if (!response.ok) {
317
+ throw new IlinkApiError("http_error", `iLink API HTTP ${response.status}。`);
318
+ }
319
+ let parsed: unknown;
320
+ try {
321
+ parsed = await response.json() as unknown;
322
+ } catch {
323
+ throw new IlinkApiError("invalid_response", "iLink API 返回了无效 JSON。");
324
+ }
325
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
326
+ throw new IlinkApiError("invalid_response", "iLink API 响应根节点必须是对象。");
327
+ }
328
+ return parsed as T;
329
+ } catch (error) {
330
+ if (error instanceof IlinkApiError) {
331
+ throw error;
332
+ }
333
+ if (controller.signal.aborted) {
334
+ throw new IlinkApiError("request_timeout", "iLink API 请求超时或已取消。");
335
+ }
336
+ throw new IlinkApiError("network_error", "iLink API 网络请求失败。");
337
+ } finally {
338
+ clearTimeout(timeout);
339
+ signal?.removeEventListener("abort", abortFromCaller);
340
+ }
341
+ }
342
+
343
+ /**
344
+ * 校验 iLink 业务响应状态。
345
+ *
346
+ * @param ret 响应 ret。
347
+ * @param errorCode 响应 errcode。
348
+ * @param errorMessage 响应 errmsg, 不会原样输出。
349
+ * @returns 无返回值。
350
+ * @throws {IlinkApiError} iLink 返回业务错误时抛出。
351
+ */
352
+ private assertApiSuccess(
353
+ ret: number | undefined,
354
+ errorCode: number | undefined,
355
+ errorMessage: string | undefined,
356
+ ): void {
357
+ const code = [errorCode, ret].find((value) => typeof value === "number" && value !== 0);
358
+ if (code === undefined) {
359
+ return;
360
+ }
361
+ if (code === -14) {
362
+ throw new IlinkApiError("session_expired", "iLink session 已过期; 不会自动重新登录或修改凭证。");
363
+ }
364
+ const suffix = typeof errorMessage === "string" && errorMessage.trim() ? " 服务端返回业务错误。" : "";
365
+ throw new IlinkApiError("api_error", `iLink API 业务请求失败 (${code}).${suffix}`);
366
+ }
367
+ }
368
+
369
+ /**
370
+ * 单次 `sendmessage` 请求体的最大 UTF-8 字节数。
371
+ *
372
+ * 2026-11-11 用真实 iLink 服务端二分实测: 16791 字节时返回成功,
373
+ * 16926 字节时返回 `ret=-2`. 这里取 16500 字节保留余量。
374
+ * 注意限制的是字节数而非字符数, 一个汉字占 3 字节。
375
+ */
376
+ const MAX_SENDMESSAGE_BODY_BYTES = 16500;
377
+
378
+ /**
379
+ * 为每次 iLink 请求生成随机 X-WECHAT-UIN。
380
+ *
381
+ * @returns 随机 uint32 十进制文本的 Base64 编码。
382
+ */
383
+ function randomWechatUin(): string {
384
+ const value = randomBytes(4).readUInt32BE(0);
385
+ return Buffer.from(String(value), "utf8").toString("base64");
386
+ }