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