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