@zhin.js/adapter-lark 1.1.18 → 1.1.20

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/lib/endpoint.js CHANGED
@@ -1,678 +1,33 @@
1
- import { createLarkWebApiTransport } from './web-api-proxy.js';
2
- import { EndpointDeliveryError } from '@zhin.js/im-contract';
3
- /**
4
- * LarkEndpoint — lifecycle, outbound, admit, OpenAPI helpers for agent tools.
5
- */
6
- import { readFile } from 'node:fs/promises';
7
- import { basename } from 'node:path';
8
- import { Endpoint, createEndpointLifecycle, createRecallEndpointControl, } from 'zhin.js/adapter';
9
- import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
10
- import { buildImageUploadForm, readOutboundImageMedia, resolveMediaBinary, } from './media-upload.js';
11
- import { formatInboundContent, formatOutboundBody, generateMessageId, larkInboundConversation, resolveChatType, resolveSender, } from './protocol.js';
12
- import { normalizeLarkSenderForPermit } from './platform-permit.js';
13
- import { registerLarkWebhookRoutes } from './webhook.js';
14
- import { createLarkLongConnection } from './long-connection.js';
15
- /** 出站 HTTP 调用统一 30s 超时。 */
16
- const OUTBOUND_TIMEOUT_MS = 30_000;
17
- /** Feishu/Lark OpenAPI client surface carried by every Endpoint event. */
18
- export class LarkClient {
19
- api;
20
- constructor(api) {
21
- this.api = api;
22
- }
23
- getUserInfo = (id, type) => this.api.getUserInfo(id, type);
24
- getChatInfo = (id) => this.api.getChatInfo(id);
25
- uploadFile = (path, type) => this.api.uploadFile(path, type);
26
- createChat = (name, users, owner) => this.api.createChat(name, users, owner);
27
- updateChatInfo = (id, options) => this.api.updateChatInfo(id, options);
28
- addChatMembers = (id, users) => this.api.addChatMembers(id, users);
29
- removeChatMembers = (id, users) => this.api.removeChatMembers(id, users);
30
- getChatMembers = (id) => this.api.getChatMembers(id);
31
- dissolveChat = (id) => this.api.dissolveChat(id);
32
- setChatManagers = (id, users) => this.api.setChatManagers(id, users);
33
- removeChatManagers = (id, users) => this.api.removeChatManagers(id, users);
34
- }
35
- const LARK_CHAT_MANAGER_CACHE_TTL_MS = 60_000;
36
- export class LarkEndpoint extends Endpoint {
37
- client = new LarkClient({
38
- getUserInfo: (id, type) => this.getUserInfo(id, type),
39
- getChatInfo: (id) => this.getChatInfo(id),
40
- uploadFile: (path, type) => this.uploadFile(path, type),
41
- createChat: (name, users, owner) => this.createChat(name, users, owner),
42
- updateChatInfo: (id, options) => this.updateChatInfo(id, options),
43
- addChatMembers: (id, users) => this.addChatMembers(id, users),
44
- removeChatMembers: (id, users) => this.removeChatMembers(id, users),
45
- getChatMembers: (id) => this.getChatMembers(id),
46
- dissolveChat: (id) => this.dissolveChat(id),
47
- setChatManagers: (id, users) => this.setChatManagers(id, users),
48
- removeChatManagers: (id, users) => this.removeChatManagers(id, users),
49
- });
50
- #logger;
51
- #options;
52
- #fetch;
53
- #webApiTransport;
54
- /**
55
- * Console 社交面语义端口。Lark OpenAPI 仅接读取类列表能力:
56
- * - listGroups:GET /im/v1/chats(bot 所在群列表,分页归一为 {group_id: chat_id, name})
57
- * - listGroupMembers:GET /im/v1/chats/:chat_id/members(open_id 分页,返回平台原生成员形状)
58
- * 不接的项:listFriends(Lark 无好友概念,contact API 为组织通讯录而非社交关系)、
59
- * listChannels(无频道/guild 概念)、写操作(审批/踢人/禁言等本轮不在范围内)。
60
- */
61
- management = Object.freeze({
62
- listGroups: async () => {
63
- const items = await this.#listAllPages('/im/v1/chats');
64
- const groups = [];
65
- for (const item of items) {
66
- const chatId = typeof item.chat_id === 'string' ? item.chat_id : '';
67
- if (!chatId)
68
- continue;
69
- groups.push({
70
- group_id: chatId,
71
- name: typeof item.name === 'string' && item.name ? item.name : chatId,
72
- });
73
- }
74
- return groups;
75
- },
76
- listGroupMembers: (groupId) => this.#listAllPages(`/im/v1/chats/${encodeURIComponent(groupId)}/members`, { member_id_type: 'open_id' }),
77
- });
78
- control = createRecallEndpointControl((id) => this.recallMessage(id));
79
- #routeReleases = [];
80
- #accessToken = { token: '', expires_in: 0, timestamp: 0 };
81
- #refreshPromise = null;
82
- #open = false;
83
- #started = false;
84
- #lifecycle;
85
- #cardSources = new Map();
86
- #seen = new Map();
87
- #chatManagers = new Map();
88
- /** One chat.get per chat at a time: concurrent messages on a cache miss share the lookup. */
89
- #chatManagerLookups = new Map();
90
- #startupGeneration = 0;
91
- #pendingInbound = [];
92
- constructor(options) {
93
- super();
94
- this.#logger = getAdapterLogger('lark', options.config.id);
95
- this.#options = options;
96
- if (options.config.webApiProxy && options.fetch)
97
- throw new TypeError('Lark webApiProxy cannot be combined with an injected fetch');
98
- this.#webApiTransport = options.config.webApiProxy ? createLarkWebApiTransport(options.config.webApiProxy) : undefined;
99
- this.#fetch = this.#webApiTransport?.fetch ?? options.fetch ?? globalThis.fetch;
100
- this.#lifecycle = createEndpointLifecycle({ name: options.config.id });
101
- }
102
- /** Used by webhook handler. */
103
- get isOpen() {
104
- return this.#open;
105
- }
106
- get config() {
107
- return this.#options.config;
108
- }
109
- get transportState() {
110
- return this.config.mode === 'websocket' ? this.#lifecycle.state : undefined;
111
- }
112
- async start() {
113
- if (this.#started)
114
- return;
115
- this.#webApiTransport?.reopen();
116
- this.#started = true;
117
- const generation = ++this.#startupGeneration;
118
- try {
119
- if (this.config.mode === 'websocket') {
120
- await this.#lifecycle.start(async (handle) => {
121
- let active = true;
122
- const transport = (this.#options.longConnectionFactory ?? createLarkLongConnection)({
123
- config: this.config,
124
- receive: (message) => {
125
- if (!active || !this.#started || generation !== this.#startupGeneration)
126
- return;
127
- if (this.#open)
128
- this.admit(message);
129
- else if (this.#pendingInbound.length < 100)
130
- this.#pendingInbound.push(message);
131
- else
132
- this.#logger.warn('lark_inbound_startup_buffer_full');
133
- },
134
- cardAction: (event) => { if (active && this.#open && generation === this.#startupGeneration)
135
- this.admitCardAction(event); },
136
- disconnected: () => { if (!active)
137
- return; active = false; transport.close(); handle.notifyClosed(); },
138
- });
139
- handle.onForceClose(() => { active = false; transport.close(); });
140
- await transport.connect();
141
- });
142
- return;
143
- }
144
- if (!this.#options.config.encryptKey && !this.#options.config.verificationToken) {
145
- // encryptKey / verificationToken 都未配置时 webhook 完全无鉴权,任何人可伪造事件
146
- this.#logger.warn(formatCompact({
147
- endpoint: this.#options.config.id,
148
- op: 'webhook',
149
- ok: false,
150
- error: 'neither encryptKey nor verificationToken configured; webhook is unauthenticated',
151
- }));
152
- }
153
- await this.#refreshAccessToken();
154
- if (!this.#started || generation !== this.#startupGeneration)
155
- return;
156
- if (!this.#options.http)
157
- throw new Error('Lark webhook mode requires HttpHost');
158
- this.#routeReleases.push(...registerLarkWebhookRoutes(this.#options.http, this));
159
- this.#logger.debug(formatCompact({
160
- endpoint: this.#options.config.id,
161
- op: 'webhook',
162
- path: this.#options.config.webhookPath,
163
- }));
164
- }
165
- catch (error) {
166
- await this.stop();
167
- this.#logger.error('Failed to connect Lark endpoint:', error);
168
- throw error;
169
- }
170
- }
171
- open() {
172
- this.#open = true;
173
- for (const message of this.#pendingInbound.splice(0))
174
- this.admit(message);
175
- }
176
- close() {
177
- this.#open = false;
178
- }
179
- async stop() {
180
- this.#open = false;
181
- this.#pendingInbound.length = 0;
182
- this.#cardSources.clear();
183
- this.#started = false;
184
- ++this.#startupGeneration;
185
- await this.#lifecycle.stop();
186
- await this.#webApiTransport?.close();
187
- for (const release of this.#routeReleases.splice(0))
188
- release();
189
- this.#started = false;
190
- this.#logger.debug(formatCompact({ op: 'disconnect' }));
191
- }
192
- async send({ conversation, payload, locale }) {
193
- try {
194
- const materialized = await this.#materializeOutboundMedia(payload);
195
- const content = formatOutboundBody(materialized, locale);
196
- const data = await this.#request(content.replyTo
197
- ? `/im/v1/messages/${encodeURIComponent(content.replyTo)}/reply`
198
- : '/im/v1/messages', {
199
- method: 'POST',
200
- ...(content.replyTo ? {} : { params: { receive_id_type: 'chat_id' } }),
201
- body: {
202
- ...(content.replyTo ? {} : { receive_id: conversation.id }),
203
- msg_type: content.msg_type,
204
- content: content.content,
205
- },
206
- });
207
- if (typeof data.code === 'number' && data.code !== 0) {
208
- throw new EndpointDeliveryError('platform_rejected', `Lark rejected message (code=${data.code})`, 'rejected');
209
- }
210
- if (data.code !== 0)
211
- throw new EndpointDeliveryError('delivery_unconfirmed', 'Malformed platform response', 'unknown');
212
- const messageId = requireMessageId(data.data?.message_id);
213
- if (content.msg_type === 'interactive') {
214
- const now = Date.now();
215
- for (const [id, source] of this.#cardSources)
216
- if (now - source.time > 300_000)
217
- this.#cardSources.delete(id);
218
- this.#cardSources.set(messageId, { conversation, time: now });
219
- if (this.#cardSources.size > 10_000)
220
- this.#cardSources.delete(this.#cardSources.keys().next().value);
221
- }
222
- this.#logger.debug(formatCompact({ op: 'send', to: conversation.id,
223
- id: messageId,
224
- }));
225
- return messageId;
226
- }
227
- catch (error) {
228
- this.#logger.warn(formatCompact({
229
- op: 'lark_send_failed',
230
- status: error instanceof LarkRequestError ? error.status : undefined,
231
- platform_code: error instanceof LarkRequestError ? error.platformCode : undefined,
232
- outcome: error instanceof EndpointDeliveryError ? error.disposition : 'unknown',
233
- }));
234
- if (error instanceof EndpointDeliveryError)
235
- throw error;
236
- throw new EndpointDeliveryError('delivery_unconfirmed', 'Outbound request outcome is unknown', 'unknown', { cause: error });
237
- }
238
- }
239
- async recallMessage(messageId) {
240
- if (!messageId || messageId.startsWith('outbound:'))
241
- return;
242
- await this.#request(`/im/v1/messages/${encodeURIComponent(messageId)}`, { method: 'DELETE' });
243
- }
244
- /**
245
- * im/v1 消息 image 段只接受 image_key:canonical MediaRef(base64/本地路径/URL)
246
- * 先经 /im/v1/images 物化,产物回写为 MediaRef kind=file(平台不透明引用);
247
- * 上传失败阻止消息发送并保留拒绝或未知分类。
248
- */
249
- async #materializeOutboundMedia(payload) {
250
- if (!Array.isArray(payload))
251
- return payload;
252
- return Promise.all(payload.map(async (item) => {
253
- if (typeof item === 'string' || !item || typeof item !== 'object')
254
- return item;
255
- const seg = item;
256
- if (seg.type !== 'image')
257
- return item;
258
- const data = seg.data ?? {};
259
- const media = readOutboundImageMedia(data);
260
- if (!media)
261
- return item;
262
- const imageKey = await this.uploadImage(media);
263
- if (!imageKey)
264
- throw new EndpointDeliveryError('delivery_unconfirmed', 'Lark image upload returned no image key', 'unknown');
265
- return {
266
- type: 'image',
267
- data: { media: { kind: 'file', value: imageKey } },
268
- };
269
- }));
270
- }
271
- /** Upload must succeed before issuing a message; dropped media is never confirmed. */
272
- async uploadImage(media) {
273
- await this.#ensureAccessToken();
274
- const binary = await resolveMediaBinary(media);
275
- const form = buildImageUploadForm(binary);
276
- const response = await this.#fetch(`${this.#options.config.apiBaseUrl}/im/v1/images`, {
277
- method: 'POST',
278
- headers: { Authorization: `Bearer ${this.#accessToken.token}` },
279
- body: form,
280
- signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
281
- });
282
- const data = await response.json().catch(() => undefined);
283
- const code = typeof data?.code === 'number' && Number.isFinite(data.code) ? data.code : undefined;
284
- if (!response.ok)
285
- throw new LarkRequestError(response.status, code, response.status >= 400 && response.status < 500 && response.status !== 408);
286
- if (code !== 0)
287
- throw new LarkRequestError(response.status, code, code !== undefined);
288
- const key = data?.data?.image_key;
289
- if (typeof key !== 'string' || !key.trim())
290
- throw new LarkRequestError(response.status, code, false);
291
- return key;
292
- }
293
- /** Test / internal: admit a parsed message when open (non-webhook path). */
294
- admit(msg) {
295
- if (!this.#open)
296
- return;
297
- if (msg.message_id) {
298
- const now = Date.now();
299
- for (const [id, time] of this.#seen)
300
- if (now - time > 300_000)
301
- this.#seen.delete(id);
302
- if (this.#seen.has(msg.message_id))
303
- return;
304
- this.#seen.set(msg.message_id, now);
305
- if (this.#seen.size > 10_000)
306
- this.#seen.delete(this.#seen.keys().next().value);
307
- }
308
- const conversation = larkInboundConversation(String(this.#options.id), msg);
309
- void this.#emitInbound(msg, conversation).catch((err) => {
310
- this.#logger.warn(formatCompact({
311
- op: 'lark_gateway_receive_failed',
312
- conversation: conversation.id,
313
- error: err instanceof Error ? err.message : String(err),
314
- }));
315
- });
316
- }
317
- async #emitInbound(msg, conversation) {
318
- const chatType = resolveChatType(msg.chat_id, msg.chat_type);
319
- const senderId = resolveSender(msg);
320
- const permit = chatType === 'group' && msg.chat_id
321
- ? normalizeLarkSenderForPermit(await this.#resolveChatRole(msg.chat_id, senderId))
322
- : undefined;
323
- // 规范角色 owner / admin 进 roles;细粒度能力放 senderPermissions
324
- const role = permit?.role === 'owner' || permit?.role === 'admin' ? permit.role : undefined;
325
- await this.emit('message.receive', {
326
- conversation,
327
- message: { conversation, id: generateMessageId(msg) },
328
- content: formatInboundContent(msg),
329
- sender: { id: senderId, ...(role ? { roles: [role] } : {}) },
330
- endpointId: this.#options.config.id,
331
- metadata: Object.freeze({
332
- messageType: msg.message_type,
333
- chatType,
334
- ...(role ? { senderRole: role } : {}),
335
- ...(role && permit?.permissions?.length ? { senderPermissions: [...permit.permissions] } : {}),
336
- }),
337
- });
338
- }
339
- /** 群主 / 群管理员来自 chat.get(owner_id + 管理员列表),按群缓存;失败时保守地视为普通成员。 */
340
- async #resolveChatRole(chatId, senderId) {
341
- const now = Date.now();
342
- for (const [id, entry] of this.#chatManagers)
343
- if (now - entry.at > LARK_CHAT_MANAGER_CACHE_TTL_MS)
344
- this.#chatManagers.delete(id);
345
- let entry = this.#chatManagers.get(chatId);
346
- if (!entry) {
347
- let lookup = this.#chatManagerLookups.get(chatId);
348
- if (!lookup) {
349
- lookup = (async () => {
350
- const info = await this.getChatInfo(chatId);
351
- const admins = Array.isArray(info?.user_manager_id_list) ? info.user_manager_id_list.map(String) : [];
352
- const fetched = {
353
- at: Date.now(),
354
- ...(typeof info?.owner_id === 'string' && info.owner_id ? { owner: info.owner_id } : {}),
355
- admins: new Set(admins),
356
- };
357
- this.#chatManagers.set(chatId, fetched);
358
- return fetched;
359
- })().finally(() => this.#chatManagerLookups.delete(chatId));
360
- this.#chatManagerLookups.set(chatId, lookup);
361
- }
362
- entry = await lookup;
363
- }
364
- return {
365
- isOwner: entry.owner !== undefined && entry.owner === senderId,
366
- isAdmin: entry.admins.has(senderId),
1
+ import { createEndpointSpecification, endpointSpec } from 'zhin.js/adapter';
2
+ import { LarkClient } from './client.js';
3
+ /** Actual protocol Client; framework lifecycle and admission stay in their symbol namespace. */
4
+ export class LarkEndpoint extends LarkClient {
5
+ [endpointSpec] = this.#createSpecification();
6
+ constructor(options) { super(options); }
7
+ #createSpecification() {
8
+ const hooks = {
9
+ start: (signal) => this.#startFramework(signal),
10
+ open: () => this.openInput(), close: () => this.closeInput(), stop: () => this.disconnectTransport(),
11
+ send: (request) => this.sendPayload(request),
12
+ name: this.configName(),
13
+ control: this.endpointControl,
14
+ management: this.endpointManagement,
367
15
  };
16
+ Object.defineProperty(hooks, 'transportState', { get: () => this.transportState });
17
+ return createEndpointSpecification(this, hooks);
368
18
  }
369
- /** Only correlate callbacks to a card actually sent by this endpoint. */
370
- admitCardAction(event) {
371
- if (!this.#open)
372
- return;
373
- const sourceId = event.context?.open_message_id ?? event.open_message_id;
374
- const chatId = event.context?.open_chat_id ?? event.open_chat_id;
375
- const sender = event.operator?.open_id ?? event.operator?.user_id;
376
- const payload = event.action?.value?.zhin_payload;
377
- if (!sourceId || !chatId || !sender || typeof payload !== 'string' || event.action?.tag !== 'button')
378
- return;
379
- const source = this.#cardSources.get(sourceId);
380
- if (!source || source.conversation.id !== chatId || Date.now() - source.time > 300_000)
381
- return;
382
- const dedup = `card:${event.token ?? `${sourceId}:${sender}:${payload}`}`;
383
- if (this.#seen.has(dedup))
384
- return;
385
- this.#seen.set(dedup, Date.now());
386
- if (this.#seen.size > 10_000)
387
- this.#seen.delete(this.#seen.keys().next().value);
388
- const conversation = source.conversation;
389
- void this.emit('message.receive', {
390
- conversation, message: { conversation, id: dedup }, content: '',
391
- segments: [{ type: 'action', data: { payload } }], sender: { id: sender }, endpointId: this.config.id,
392
- metadata: Object.freeze({ eventType: 'card.action.trigger', sourceMessageId: sourceId }),
393
- }).catch(() => this.#logger.warn('lark_card_action_receive_failed'));
19
+ #startFramework(signal) { return this.connectTransport(signal); }
20
+ receiveInboundCallback(receive) {
21
+ return this[endpointSpec].events.run(receive);
394
22
  }
395
- admitPlatform(name, event) {
396
- if (!this.#open)
397
- return;
398
- void this.emitPlatform(name, event).catch((error) => {
399
- this.#logger.warn(formatCompact({
400
- op: 'lark_platform_event_failed',
401
- event: name,
402
- error: error instanceof Error ? error.message : String(error),
403
- }));
404
- });
23
+ publishEvent(name, payload) {
24
+ return this[endpointSpec].events.emit(name, payload);
405
25
  }
406
- async getUserInfo(userId, userIdType = 'open_id') {
407
- try {
408
- const data = await this.#request(`/contact/v3/users/${userId}`, {
409
- method: 'GET',
410
- params: { user_id_type: userIdType },
411
- });
412
- return data.data?.user ?? null;
413
- }
414
- catch (error) {
415
- this.#logger.error('Failed to get user info:', error);
416
- return null;
417
- }
26
+ publishAccepted(name, payload) {
27
+ return this[endpointSpec].events.emitAccepted(name, payload).then(() => undefined);
418
28
  }
419
- async getChatInfo(chatId) {
420
- try {
421
- const data = await this.#request(`/im/v1/chats/${chatId}`, { method: 'GET' });
422
- return data.data ?? null;
423
- }
424
- catch (error) {
425
- this.#logger.error('Failed to get chat info:', error);
426
- return null;
427
- }
428
- }
429
- async uploadFile(filePath, fileType = 'file') {
430
- try {
431
- await this.#ensureAccessToken();
432
- const buf = await readFile(filePath);
433
- const form = new FormData();
434
- form.append('file', new Blob([buf]), basename(filePath));
435
- form.append('file_type', fileType);
436
- const url = `${this.#options.config.apiBaseUrl}/im/v1/files`;
437
- const response = await this.#fetch(url, {
438
- method: 'POST',
439
- headers: { Authorization: `Bearer ${this.#accessToken.token}` },
440
- body: form,
441
- });
442
- const data = await response.json();
443
- if (data.code === 0) {
444
- return data.data?.file_key || null;
445
- }
446
- throw new Error(`Upload failed: ${data.msg}`);
447
- }
448
- catch (error) {
449
- this.#logger.error('Failed to upload file:', error);
450
- return null;
451
- }
452
- }
453
- async createChat(name, userIds, ownerId) {
454
- try {
455
- const data = await this.#request('/im/v1/chats', {
456
- method: 'POST',
457
- body: {
458
- name,
459
- user_id_list: userIds,
460
- ...(ownerId ? { owner_id: ownerId } : {}),
461
- },
462
- });
463
- if (data.code === 0)
464
- return data.data?.chat_id || null;
465
- throw new Error(`Failed to create chat: ${data.msg}`);
466
- }
467
- catch (error) {
468
- this.#logger.error('Failed to create chat:', error);
469
- return null;
470
- }
471
- }
472
- async updateChatInfo(chatId, options) {
473
- try {
474
- const data = await this.#request(`/im/v1/chats/${chatId}`, {
475
- method: 'PUT',
476
- body: options,
477
- });
478
- if (data.code === 0)
479
- return true;
480
- throw new Error(`Failed to update chat: ${data.msg}`);
481
- }
482
- catch (error) {
483
- this.#logger.error('Failed to update chat:', error);
484
- return false;
485
- }
486
- }
487
- async addChatMembers(chatId, userIds) {
488
- try {
489
- const data = await this.#request(`/im/v1/chats/${chatId}/members`, {
490
- method: 'POST',
491
- body: { id_list: userIds },
492
- });
493
- if (data.code === 0)
494
- return true;
495
- throw new Error(`Failed to add members: ${data.msg}`);
496
- }
497
- catch (error) {
498
- this.#logger.error('Failed to add chat members:', error);
499
- return false;
500
- }
501
- }
502
- async removeChatMembers(chatId, userIds) {
503
- try {
504
- const data = await this.#request(`/im/v1/chats/${chatId}/members`, {
505
- method: 'DELETE',
506
- body: { id_list: userIds },
507
- });
508
- if (data.code === 0)
509
- return true;
510
- throw new Error(`Failed to remove members: ${data.msg}`);
511
- }
512
- catch (error) {
513
- this.#logger.error('Failed to remove chat members:', error);
514
- return false;
515
- }
516
- }
517
- async getChatMembers(chatId) {
518
- try {
519
- const data = await this.#request(`/im/v1/chats/${chatId}/members`, { method: 'GET' });
520
- if (data.code === 0)
521
- return data.data?.items || [];
522
- throw new Error(`Failed to get members: ${data.msg}`);
523
- }
524
- catch (error) {
525
- this.#logger.error('Failed to get chat members:', error);
526
- return [];
527
- }
528
- }
529
- async dissolveChat(chatId) {
530
- try {
531
- const data = await this.#request(`/im/v1/chats/${chatId}`, { method: 'DELETE' });
532
- if (data.code === 0)
533
- return true;
534
- throw new Error(`Failed to dissolve chat: ${data.msg}`);
535
- }
536
- catch (error) {
537
- this.#logger.error('Failed to dissolve chat:', error);
538
- return false;
539
- }
540
- }
541
- async setChatManagers(chatId, userIds) {
542
- try {
543
- const data = await this.#request(`/im/v1/chats/${chatId}/managers/add_managers`, {
544
- method: 'POST',
545
- body: { manager_ids: userIds },
546
- });
547
- if (data.code === 0)
548
- return true;
549
- throw new Error(`Failed to set managers: ${data.msg}`);
550
- }
551
- catch (error) {
552
- this.#logger.error('Failed to set chat managers:', error);
553
- return false;
554
- }
555
- }
556
- async removeChatManagers(chatId, userIds) {
557
- try {
558
- const data = await this.#request(`/im/v1/chats/${chatId}/managers/delete_managers`, {
559
- method: 'POST',
560
- body: { manager_ids: userIds },
561
- });
562
- if (data.code === 0)
563
- return true;
564
- throw new Error(`Failed to remove managers: ${data.msg}`);
565
- }
566
- catch (error) {
567
- this.#logger.error('Failed to remove chat managers:', error);
568
- return false;
569
- }
570
- }
571
- /** 拉取分页列表(items + has_more/page_token);code!==0 时抛错交由 RPC 层透出。 */
572
- async #listAllPages(path, params = {}) {
573
- const items = [];
574
- let pageToken = '';
575
- do {
576
- const data = await this.#request(path, {
577
- method: 'GET',
578
- params: {
579
- ...params,
580
- page_size: 100,
581
- ...(pageToken ? { page_token: pageToken } : {}),
582
- },
583
- });
584
- if (data.code !== 0) {
585
- throw new Error(`Lark API ${path} failed: ${data.msg ?? 'unknown'} (${data.code})`);
586
- }
587
- const page = data.data ?? {};
588
- if (Array.isArray(page.items)) {
589
- for (const item of page.items) {
590
- if (item !== null && typeof item === 'object') {
591
- items.push(item);
592
- }
593
- }
594
- }
595
- pageToken = page.has_more === true && typeof page.page_token === 'string'
596
- ? page.page_token
597
- : '';
598
- } while (pageToken);
599
- return items;
600
- }
601
- async #request(path, options = {}) {
602
- await this.#ensureAccessToken();
603
- const { method = 'GET', params = {}, body } = options;
604
- const urlParams = new URLSearchParams(Object.fromEntries(Object.entries(params).map(([key, value]) => [key, String(value)])));
605
- const query = urlParams.toString();
606
- const url = `${this.#options.config.apiBaseUrl}${path}${query ? `?${query}` : ''}`;
607
- const response = await this.#fetch(url, {
608
- method,
609
- headers: {
610
- 'Content-Type': 'application/json; charset=utf-8',
611
- Authorization: `Bearer ${this.#accessToken.token}`,
612
- },
613
- body: body && method !== 'GET' ? JSON.stringify(body) : undefined,
614
- signal: AbortSignal.timeout(OUTBOUND_TIMEOUT_MS),
615
- });
616
- const data = await response.json().catch(() => undefined);
617
- const platformCode = typeof data?.code === 'number' && Number.isFinite(data.code) ? data.code : undefined;
618
- if (!response.ok) {
619
- const rejected = response.status >= 400 && response.status < 500 && response.status !== 408;
620
- throw new LarkRequestError(response.status, platformCode, rejected);
621
- }
622
- if (platformCode === undefined)
623
- throw new LarkRequestError(response.status, undefined, false);
624
- if (platformCode !== 0)
625
- throw new LarkRequestError(response.status, platformCode, true);
626
- return data;
627
- }
628
- async #ensureAccessToken() {
629
- const now = Date.now();
630
- if (this.#accessToken.token
631
- && now < this.#accessToken.timestamp + (this.#accessToken.expires_in - 300) * 1000) {
632
- return;
633
- }
634
- if (this.#refreshPromise) {
635
- await this.#refreshPromise;
636
- return;
637
- }
638
- this.#refreshPromise = this.#refreshAccessToken()
639
- .then(() => this.#accessToken.token)
640
- .finally(() => { this.#refreshPromise = null; });
641
- await this.#refreshPromise;
642
- }
643
- async #refreshAccessToken() {
644
- const { appId, appSecret, apiBaseUrl } = this.#options.config;
645
- const url = `${apiBaseUrl}/auth/v3/tenant_access_token/internal`;
646
- const response = await this.#fetch(url, {
647
- method: 'POST',
648
- headers: { 'Content-Type': 'application/json; charset=utf-8' },
649
- body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
650
- });
651
- const data = await response.json();
652
- if (data.code === 0 && data.tenant_access_token) {
653
- this.#accessToken = {
654
- token: data.tenant_access_token,
655
- expires_in: data.expire ?? 7200,
656
- timestamp: Date.now(),
657
- };
658
- this.#logger.debug('Access token refreshed successfully');
659
- return;
660
- }
661
- throw new LarkRequestError(response.status, typeof data.code === 'number' ? data.code : undefined, response.ok && typeof data.code === 'number' && data.code !== 0 || response.status >= 400 && response.status < 500 && response.status !== 408);
662
- }
663
- }
664
- function requireMessageId(value) {
665
- if (typeof value === 'string' && value.trim().length > 0)
666
- return value;
667
- throw new EndpointDeliveryError('delivery_unconfirmed', 'Platform did not return a real message ID', 'unknown');
668
- }
669
- /** Carries only safe numerical diagnostics, never response bodies or credentials. */
670
- class LarkRequestError extends EndpointDeliveryError {
671
- status;
672
- platformCode;
673
- constructor(status, platformCode, rejected) {
674
- super(rejected ? 'platform_rejected' : 'delivery_unconfirmed', `Lark request failed (status=${status}${platformCode === undefined ? '' : `, code=${platformCode}`})`, rejected ? 'rejected' : 'unknown');
675
- this.status = status;
676
- this.platformCode = platformCode;
29
+ async publishPlatform(name, event) {
30
+ await super.publishPlatform(name, event);
31
+ return this[endpointSpec].events.platform(name, event);
677
32
  }
678
33
  }