@suwenguang/pi-feishu-bridge 0.0.0-stage → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/extensions/feishu/index.ts +11 -0
- package/.pi/feishu/debug.pi.log +81 -0
- package/.pi/feishu/state.pi.json +12 -0
- package/README.md +210 -2
- package/package.json +57 -4
- package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
- package/src/adapters/pi/index.ts +1169 -0
- package/src/adapters/pi/setup.ts +108 -0
- package/src/feishu/app-register.ts +50 -0
- package/src/feishu/ask.ts +388 -0
- package/src/feishu/attachment-processor.ts +198 -0
- package/src/feishu/attachments.ts +192 -0
- package/src/feishu/bridge-runtime.ts +129 -0
- package/src/feishu/bridge-store.ts +92 -0
- package/src/feishu/card-action-webhook.ts +141 -0
- package/src/feishu/card-actions.ts +241 -0
- package/src/feishu/card-builder.ts +277 -0
- package/src/feishu/cardkit-stream.ts +483 -0
- package/src/feishu/cards.ts +413 -0
- package/src/feishu/config.ts +427 -0
- package/src/feishu/daemon-spec.ts +43 -0
- package/src/feishu/debug.ts +51 -0
- package/src/feishu/dedupe-store.ts +150 -0
- package/src/feishu/delivery.ts +185 -0
- package/src/feishu/gateway-lock.ts +256 -0
- package/src/feishu/group-trigger.ts +128 -0
- package/src/feishu/image-send.ts +256 -0
- package/src/feishu/instance.ts +170 -0
- package/src/feishu/instances.ts +148 -0
- package/src/feishu/interactive-card.ts +236 -0
- package/src/feishu/learn-approval.ts +321 -0
- package/src/feishu/live-cards.ts +128 -0
- package/src/feishu/message-handler.ts +512 -0
- package/src/feishu/messages.ts +356 -0
- package/src/feishu/oversize-progress-card.ts +101 -0
- package/src/feishu/progress-channel.ts +154 -0
- package/src/feishu/progress-note.ts +371 -0
- package/src/feishu/prompt-timeout.ts +81 -0
- package/src/feishu/reply-card-options.ts +73 -0
- package/src/feishu/reply-card.ts +498 -0
- package/src/feishu/restart.ts +286 -0
- package/src/feishu/retry.ts +102 -0
- package/src/feishu/rich-text.ts +387 -0
- package/src/feishu/runtime-config.ts +286 -0
- package/src/feishu/runtime.ts +110 -0
- package/src/feishu/slash-commands.ts +239 -0
- package/src/feishu/thinking.ts +24 -0
- package/src/feishu/transport.ts +792 -0
- package/src/feishu/types.ts +183 -0
- package/src/feishu/ui-notify.ts +44 -0
- package/src/feishu/user-name.ts +121 -0
- package/src/feishu/workspace.ts +42 -0
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
import type { FeishuCardAction, FeishuConfig, FeishuMessage } from "./types.ts";
|
|
2
|
+
import { loadConfig } from "./config.ts";
|
|
3
|
+
import { debugLog } from "./debug.ts";
|
|
4
|
+
import {
|
|
5
|
+
extractPlainTextForTrigger,
|
|
6
|
+
shouldAcceptGroupMessage,
|
|
7
|
+
} from "./group-trigger.ts";
|
|
8
|
+
import { buildMarkdownCardParts, buildPostMessages, chooseMessageMode } from "./rich-text.ts";
|
|
9
|
+
import { withRetry } from "./retry.ts";
|
|
10
|
+
import { extractTextFromMsgType } from "./interactive-card.ts";
|
|
11
|
+
import { FeishuCardActionWebhook } from "./card-action-webhook.ts";
|
|
12
|
+
import { sendLocalImage } from "./image-send.ts";
|
|
13
|
+
import { autoSyncSlashCommands } from "./slash-commands.ts";
|
|
14
|
+
|
|
15
|
+
const TEXT_CHUNK_MAX_BYTES = 120 * 1024;
|
|
16
|
+
|
|
17
|
+
export class BotUnavailableError extends Error {
|
|
18
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
19
|
+
super(message, options);
|
|
20
|
+
this.name = "BotUnavailableError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class FeishuTransport {
|
|
25
|
+
private sdkClient: any;
|
|
26
|
+
private wsClient: any;
|
|
27
|
+
private cardActionWebhook: FeishuCardActionWebhook | undefined;
|
|
28
|
+
private running = false;
|
|
29
|
+
private botOpenId: string | undefined;
|
|
30
|
+
private readonly chatModeCache = new Map<string, "p2p" | "group" | "topic">();
|
|
31
|
+
/** 本 bot 发出的消息 id,用于 alsoOnReply 判定 parent/root */
|
|
32
|
+
private readonly botOutboundMessageIds = new Set<string>();
|
|
33
|
+
private readonly botOutboundMessageOrder: string[] = [];
|
|
34
|
+
private readonly markdownCopySources = new Map<string, string>();
|
|
35
|
+
private readonly markdownCopySourceOrder: string[] = [];
|
|
36
|
+
private markdownCopySeq = 0;
|
|
37
|
+
/**
|
|
38
|
+
* messageId → 本 bot 给这条消息贴上的 reaction_id。
|
|
39
|
+
* 用于本轮结束时把「收到」的 reaction 换成结果标记(DONE / CRY)。
|
|
40
|
+
*/
|
|
41
|
+
private readonly pendingReactions = new Map<string, string>();
|
|
42
|
+
private readonly config: FeishuConfig;
|
|
43
|
+
private readonly onMessage: (msg: FeishuMessage) => Promise<void>;
|
|
44
|
+
private readonly onCardAction: (action: FeishuCardAction) => Promise<object | undefined | void>;
|
|
45
|
+
|
|
46
|
+
private sendRetries() {
|
|
47
|
+
return this.config.sendMaxRetries ?? 2;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private async apiCall<T = any>(label: string, fn: () => Promise<T>): Promise<T> {
|
|
51
|
+
return withRetry(fn, { maxRetries: this.sendRetries(), label });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
constructor(
|
|
55
|
+
config: FeishuConfig,
|
|
56
|
+
onMessage: (msg: FeishuMessage) => Promise<void>,
|
|
57
|
+
onCardAction: (action: FeishuCardAction) => Promise<object | undefined | void>,
|
|
58
|
+
) {
|
|
59
|
+
this.config = config;
|
|
60
|
+
this.onMessage = onMessage;
|
|
61
|
+
this.onCardAction = onCardAction;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 热读有效配置(含 runtime-overrides);失败回退 constructor 快照 */
|
|
65
|
+
private effectiveConfig(): FeishuConfig {
|
|
66
|
+
return loadConfig() || this.config;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 通用飞书 API 调用入口(供 learn-approval 等模块复用已建好的 SDK client)。
|
|
71
|
+
* 未启动时直接报错:没 client 就调不出结果,静默失败只会更难排。
|
|
72
|
+
*/
|
|
73
|
+
async requestApi<T = any>(args: { url: string; method: string; params?: unknown; data?: unknown }): Promise<T> {
|
|
74
|
+
if (!this.sdkClient) throw new Error("飞书连接未启动,无法调用 API");
|
|
75
|
+
return this.sdkClient.request(args) as Promise<T>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async start() {
|
|
79
|
+
if (this.running) return;
|
|
80
|
+
const lark = await import("@larksuiteoapi/node-sdk");
|
|
81
|
+
const domain = this.config.domain === "lark" ? lark.Domain.Lark : lark.Domain.Feishu;
|
|
82
|
+
|
|
83
|
+
this.sdkClient = new lark.Client({
|
|
84
|
+
appId: this.config.appId,
|
|
85
|
+
appSecret: this.config.appSecret,
|
|
86
|
+
appType: lark.AppType.SelfBuild,
|
|
87
|
+
domain,
|
|
88
|
+
loggerLevel: lark.LoggerLevel.error,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
await this.probeBotOpenId();
|
|
92
|
+
|
|
93
|
+
// 注册飞书「斜杠指令」:输入框敲 / 可看到命令提示面板。
|
|
94
|
+
// 后台执行、失败静默降级(缺 application:app_slash_command:write 权限时只记日志)。
|
|
95
|
+
autoSyncSlashCommands(this.sdkClient, this.config);
|
|
96
|
+
|
|
97
|
+
const dispatcher = new lark.EventDispatcher({ loggerLevel: lark.LoggerLevel.error }).register({
|
|
98
|
+
"im.message.receive_v1": async (data: unknown) => this.handleRawMessage(data),
|
|
99
|
+
"im.message.reaction.created_v1": async () => undefined,
|
|
100
|
+
"im.chat.member.bot.added_v1": async () => undefined,
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Always register the WS card action handler. When the app is connected
|
|
104
|
+
// via WebSocket (which is always the case with WSClient), the Feishu
|
|
105
|
+
// platform delivers card action callbacks through the WS channel.
|
|
106
|
+
// Without this handler the EventDispatcher returns an invalid response
|
|
107
|
+
// to the platform, causing error 200672 on the client.
|
|
108
|
+
dispatcher.register({
|
|
109
|
+
"card.action.trigger": async (data: unknown) => this.handleCardAction(data),
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Optional webhook server as a backup delivery channel (only used when
|
|
113
|
+
// the developer console is explicitly configured for webhook delivery).
|
|
114
|
+
if (this.cardActionMode() === "webhook") {
|
|
115
|
+
this.cardActionWebhook = new FeishuCardActionWebhook(this.config, async (action) => this.handleCardActionAction(action, "webhook"));
|
|
116
|
+
await this.cardActionWebhook.start();
|
|
117
|
+
debugLog("feishu.card.webhook.endpoint", {
|
|
118
|
+
endpoint: this.cardActionWebhook.getEndpointLabel(),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
this.wsClient = new lark.WSClient({
|
|
123
|
+
appId: this.config.appId,
|
|
124
|
+
appSecret: this.config.appSecret,
|
|
125
|
+
domain,
|
|
126
|
+
loggerLevel: lark.LoggerLevel.error,
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
this.running = true;
|
|
130
|
+
try {
|
|
131
|
+
this.wsClient.start({ eventDispatcher: dispatcher });
|
|
132
|
+
} catch (error) {
|
|
133
|
+
this.running = false;
|
|
134
|
+
try { await this.cardActionWebhook?.stop(); } catch {}
|
|
135
|
+
this.cardActionWebhook = undefined;
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async stop() {
|
|
141
|
+
this.running = false;
|
|
142
|
+
try { await this.wsClient?.stop?.(); } catch {}
|
|
143
|
+
try { await this.cardActionWebhook?.stop(); } catch {}
|
|
144
|
+
this.cardActionWebhook = undefined;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
isRunning() {
|
|
148
|
+
return this.running;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
getBotOpenId() {
|
|
152
|
+
return this.botOpenId;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async probeBotOpenId() {
|
|
156
|
+
try {
|
|
157
|
+
// 探活这一步最容易撞上启动瞬间的瞬时断连(ECONNRESET / socket hang up):
|
|
158
|
+
// 带重试再抛,避免一次抖动就让整个 daemon 放弃启动。
|
|
159
|
+
const res = await withRetry<any>(
|
|
160
|
+
() =>
|
|
161
|
+
this.sdkClient.request({
|
|
162
|
+
url: "/open-apis/bot/v3/info",
|
|
163
|
+
method: "GET",
|
|
164
|
+
}),
|
|
165
|
+
{ maxRetries: 2, baseDelayMs: 500, label: "feishu.bot.probe" },
|
|
166
|
+
);
|
|
167
|
+
this.botOpenId = res?.bot?.open_id || res?.data?.bot?.open_id || res?.data?.open_id;
|
|
168
|
+
if (!this.botOpenId) {
|
|
169
|
+
throw new Error(`bot/v3/info response missing open_id: ${JSON.stringify(res).slice(0, 200)}`);
|
|
170
|
+
}
|
|
171
|
+
} catch (error) {
|
|
172
|
+
// 保留原始错误当 cause:上层用 isRetriableError 判断「瞬时断连 vs 凭证错」时需要它。
|
|
173
|
+
throw new BotUnavailableError(error instanceof Error ? error.message : String(error), { cause: error });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private async handleRawMessage(data: any) {
|
|
178
|
+
const event = data?.event || data;
|
|
179
|
+
const message = event?.message;
|
|
180
|
+
const sender = event?.sender;
|
|
181
|
+
if (!message) return;
|
|
182
|
+
|
|
183
|
+
const cfg = this.effectiveConfig();
|
|
184
|
+
if (sender?.sender_type === "bot" && cfg.ignoreBotMessages !== false) {
|
|
185
|
+
debugLog("feishu.message.ignored_bot", {
|
|
186
|
+
messageId: message.message_id,
|
|
187
|
+
messageType: message.message_type,
|
|
188
|
+
});
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
debugLog("feishu.message.received", {
|
|
193
|
+
messageId: message.message_id,
|
|
194
|
+
chatType: message.chat_type,
|
|
195
|
+
messageType: message.message_type,
|
|
196
|
+
senderType: sender?.sender_type || "unknown",
|
|
197
|
+
hasRootId: Boolean(message.root_id),
|
|
198
|
+
hasParentId: Boolean(message.parent_id),
|
|
199
|
+
hasThreadId: Boolean(message.thread_id),
|
|
200
|
+
content: message.content || "",
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
if (message.chat_type === "group") {
|
|
204
|
+
const text = extractPlainTextForTrigger(message.message_type || "text", message.content || "");
|
|
205
|
+
const mentioned = this.isMentioned(message);
|
|
206
|
+
const replyToBot = this.isReplyToBot(message);
|
|
207
|
+
const decision = shouldAcceptGroupMessage({
|
|
208
|
+
chatType: "group",
|
|
209
|
+
groupPolicy: cfg.groupPolicy,
|
|
210
|
+
mentioned,
|
|
211
|
+
mentionAllOnly: !mentioned && this.hasMentionAll(message),
|
|
212
|
+
text,
|
|
213
|
+
keywords: cfg.groupKeywords || [],
|
|
214
|
+
alsoOnReply: Boolean(cfg.groupAlsoOnReply),
|
|
215
|
+
replyToBot,
|
|
216
|
+
});
|
|
217
|
+
if (!decision.accept) {
|
|
218
|
+
debugLog(`feishu.message.ignored_${decision.reason}`, {
|
|
219
|
+
messageId: message.message_id,
|
|
220
|
+
reason: decision.reason,
|
|
221
|
+
mentioned,
|
|
222
|
+
replyToBot,
|
|
223
|
+
keywords: cfg.groupKeywords || [],
|
|
224
|
+
});
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (decision.reason !== "open") {
|
|
228
|
+
debugLog("feishu.message.trigger", {
|
|
229
|
+
messageId: message.message_id,
|
|
230
|
+
reason: decision.reason,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const chatMode = await this.getChatMode(message.chat_id, message.chat_type);
|
|
236
|
+
const msg: FeishuMessage = {
|
|
237
|
+
messageId: message.message_id,
|
|
238
|
+
chatId: message.chat_id,
|
|
239
|
+
chatType: message.chat_type,
|
|
240
|
+
chatMode,
|
|
241
|
+
senderOpenId: sender?.sender_id?.open_id || "unknown",
|
|
242
|
+
msgType: message.message_type,
|
|
243
|
+
content: message.content || "",
|
|
244
|
+
rootId: message.root_id,
|
|
245
|
+
parentId: message.parent_id,
|
|
246
|
+
threadId: message.thread_id,
|
|
247
|
+
mentions: message.mentions,
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
if (cfg.reactEmoji) {
|
|
251
|
+
void this.addReaction(msg.messageId, cfg.reactEmoji);
|
|
252
|
+
}
|
|
253
|
+
debugLog("feishu.message.dispatch", { messageId: msg.messageId });
|
|
254
|
+
void this.onMessage(msg).catch((error) => {
|
|
255
|
+
debugLog("feishu.message.dispatch_error", {
|
|
256
|
+
messageId: msg.messageId,
|
|
257
|
+
error: error instanceof Error ? error.message : String(error),
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private async handleCardAction(data: any) {
|
|
263
|
+
// After EventDispatcher/RequestHandle.parse() the event fields are
|
|
264
|
+
// flattened to the top level. data.event is gone; use data directly.
|
|
265
|
+
const messageId = data?.context?.open_message_id || data?.open_message_id;
|
|
266
|
+
const chatId = data?.context?.open_chat_id || data?.open_chat_id;
|
|
267
|
+
const operatorOpenId = data?.operator?.open_id;
|
|
268
|
+
if (!messageId || !operatorOpenId) return;
|
|
269
|
+
debugLog("feishu.card.action", {
|
|
270
|
+
messageId,
|
|
271
|
+
chatId,
|
|
272
|
+
hasToken: Boolean(data?.token),
|
|
273
|
+
value: data?.action?.value,
|
|
274
|
+
hasFormValue: Boolean(data?.action?.form_value),
|
|
275
|
+
});
|
|
276
|
+
const result = await this.handleCardActionAction({
|
|
277
|
+
messageId,
|
|
278
|
+
chatId,
|
|
279
|
+
operatorOpenId,
|
|
280
|
+
token: typeof data?.token === "string" ? data.token : undefined,
|
|
281
|
+
value: data?.action?.value,
|
|
282
|
+
formValue: data?.action?.form_value,
|
|
283
|
+
}, "ws");
|
|
284
|
+
// The WSClient sends the return value back to the Feishu platform as
|
|
285
|
+
// the card callback response. It must use the wrapped format:
|
|
286
|
+
// { "card": { "type": "raw", "data": { ... card JSON ... } } }
|
|
287
|
+
if (result) {
|
|
288
|
+
return { card: { type: "raw", data: result } };
|
|
289
|
+
}
|
|
290
|
+
return result;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private async handleCardActionAction(action: FeishuCardAction, mode: "ws" | "webhook") {
|
|
294
|
+
// 仅返回回调响应即可;不要再 im.message.patch 一份 schema 1.0,
|
|
295
|
+
// 否则会把 CardKit schema 2.0 卡改坏(200830 / 前端 200671)。
|
|
296
|
+
return this.onCardAction(action);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private cardActionMode() {
|
|
300
|
+
return this.config.cardActionMode || "webhook";
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private isMentioned(message: any): boolean {
|
|
304
|
+
const mentions = Array.isArray(message.mentions) ? message.mentions : [];
|
|
305
|
+
if (!mentions.length) return false;
|
|
306
|
+
const botOpenId = this.botOpenId;
|
|
307
|
+
if (!botOpenId) return true;
|
|
308
|
+
return mentions.some((m: any) => m?.id?.open_id === botOpenId || m?.id?.union_id === botOpenId);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** 消息里是否 @ 了所有人(@_all),用于「@所有人不算 @ 机器人」的过滤 */
|
|
312
|
+
private hasMentionAll(message: any): boolean {
|
|
313
|
+
const mentions = Array.isArray(message.mentions) ? message.mentions : [];
|
|
314
|
+
const hit = mentions.some(
|
|
315
|
+
(m: any) =>
|
|
316
|
+
m?.key === "@_all" ||
|
|
317
|
+
m?.id?.open_id === "@_all" ||
|
|
318
|
+
m?.id?.union_id === "@_all",
|
|
319
|
+
);
|
|
320
|
+
if (hit) return true;
|
|
321
|
+
const raw = typeof message.content === "string" ? message.content : "";
|
|
322
|
+
return raw.includes("\"@_all\"") || raw.includes("@_all");
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 是否回复/跟帖到本 bot 发出的消息 */
|
|
326
|
+
private isReplyToBot(message: any): boolean {
|
|
327
|
+
const parentId = typeof message.parent_id === "string" ? message.parent_id : "";
|
|
328
|
+
const rootId = typeof message.root_id === "string" ? message.root_id : "";
|
|
329
|
+
if (parentId && this.botOutboundMessageIds.has(parentId)) return true;
|
|
330
|
+
if (rootId && this.botOutboundMessageIds.has(rootId)) return true;
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 供 ReplyCard / CardKit 登记出站消息 id */
|
|
335
|
+
rememberOutboundMessageId(messageId: string) {
|
|
336
|
+
this.rememberBotOutboundMessageId(messageId);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private rememberBotOutboundMessageId(messageId: string | undefined) {
|
|
340
|
+
if (!messageId) return;
|
|
341
|
+
if (this.botOutboundMessageIds.has(messageId)) return;
|
|
342
|
+
this.botOutboundMessageIds.add(messageId);
|
|
343
|
+
this.botOutboundMessageOrder.push(messageId);
|
|
344
|
+
while (this.botOutboundMessageOrder.length > 500) {
|
|
345
|
+
const oldest = this.botOutboundMessageOrder.shift();
|
|
346
|
+
if (oldest) this.botOutboundMessageIds.delete(oldest);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private async getChatMode(chatId: string, chatType: "p2p" | "group"): Promise<"p2p" | "group" | "topic"> {
|
|
351
|
+
if (chatType === "p2p") return "p2p";
|
|
352
|
+
const cached = this.chatModeCache.get(chatId);
|
|
353
|
+
if (cached) return cached;
|
|
354
|
+
try {
|
|
355
|
+
const res = await this.sdkClient.im.v1.chat.get({ path: { chat_id: chatId } });
|
|
356
|
+
const mode = res?.data?.chat_mode === "topic" ? "topic" : "group";
|
|
357
|
+
this.chatModeCache.set(chatId, mode);
|
|
358
|
+
debugLog("feishu.chat.mode", { chatId, mode });
|
|
359
|
+
return mode;
|
|
360
|
+
} catch (error) {
|
|
361
|
+
debugLog("feishu.chat.mode_error", {
|
|
362
|
+
chatId,
|
|
363
|
+
error: error instanceof Error ? error.message : String(error),
|
|
364
|
+
});
|
|
365
|
+
return "group";
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 给消息贴表情。
|
|
371
|
+
* 实测飞书 emoji_type:DONE / CRY 有效,Sad / NO 报 231001 invalid。
|
|
372
|
+
* @returns 服务端返回的 reaction_id(删除时需要),失败返回 undefined
|
|
373
|
+
*/
|
|
374
|
+
private async addReaction(messageId: string, emojiType: string): Promise<string | undefined> {
|
|
375
|
+
try {
|
|
376
|
+
const res: any = await this.sdkClient.im.messageReaction.create({
|
|
377
|
+
path: { message_id: messageId },
|
|
378
|
+
data: { reaction_type: { emoji_type: emojiType } },
|
|
379
|
+
});
|
|
380
|
+
const reactionId: string | undefined = res?.data?.reaction_id;
|
|
381
|
+
if (reactionId) {
|
|
382
|
+
this.pendingReactions.set(messageId, reactionId);
|
|
383
|
+
// 简单上限保护:长期运行不会无限增长(Map 保持插入顺序)
|
|
384
|
+
if (this.pendingReactions.size > 2000) {
|
|
385
|
+
for (const key of [...this.pendingReactions.keys()].slice(0, 500)) {
|
|
386
|
+
this.pendingReactions.delete(key);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return reactionId;
|
|
391
|
+
} catch {
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** 删除本 bot 自己贴的表情(飞书只允许删自己加的) */
|
|
397
|
+
private async removeReaction(messageId: string, reactionId: string) {
|
|
398
|
+
try {
|
|
399
|
+
await this.sdkClient.im.messageReaction.delete({
|
|
400
|
+
path: { message_id: messageId, reaction_id: reactionId },
|
|
401
|
+
});
|
|
402
|
+
} catch {
|
|
403
|
+
// 表情清理失败不影响主流程
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* 本轮结束:把收消息时贴的「收到」表情换成结果标记。
|
|
409
|
+
* - done:换成 DONE
|
|
410
|
+
* - failed:换成 CRY
|
|
411
|
+
* - ignored(去重命中 / 空消息):直接摘掉,不留痕
|
|
412
|
+
* 由 message-handler 的 finally 统一调用,保证任何出口都会收尾。
|
|
413
|
+
*/
|
|
414
|
+
async settleReaction(messageId: string, outcome: "done" | "failed" | "ignored") {
|
|
415
|
+
const pending = this.pendingReactions.get(messageId);
|
|
416
|
+
if (pending) {
|
|
417
|
+
this.pendingReactions.delete(messageId);
|
|
418
|
+
await this.removeReaction(messageId, pending);
|
|
419
|
+
}
|
|
420
|
+
const emoji = outcome === "done" ? "DONE" : outcome === "failed" ? "CRY" : undefined;
|
|
421
|
+
if (emoji) {
|
|
422
|
+
debugLog("feishu.reaction.settled", { messageId, outcome, emoji });
|
|
423
|
+
await this.addReaction(messageId, emoji);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
async replyText(messageId: string, text: string) {
|
|
428
|
+
const mode = chooseMessageMode(text);
|
|
429
|
+
if (mode === "interactive") {
|
|
430
|
+
await this.replyMarkdownCard(messageId, text);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (mode === "post") {
|
|
434
|
+
await this.replyPost(messageId, text);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
debugLog("feishu.reply.text", { messageId, length: text.length });
|
|
438
|
+
const chunks = splitText(text, TEXT_CHUNK_MAX_BYTES);
|
|
439
|
+
for (const chunk of chunks) {
|
|
440
|
+
const res = await this.apiCall("feishu.reply.text", () => this.sdkClient.im.message.reply({
|
|
441
|
+
path: { message_id: messageId },
|
|
442
|
+
data: { msg_type: "text", content: JSON.stringify({ text: chunk }) },
|
|
443
|
+
}));
|
|
444
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async replyPlainText(messageId: string, text: string): Promise<string | undefined> {
|
|
449
|
+
debugLog("feishu.reply.plain_text", { messageId, length: text.length });
|
|
450
|
+
const chunks = splitText(text, TEXT_CHUNK_MAX_BYTES);
|
|
451
|
+
let lastId: string | undefined;
|
|
452
|
+
for (const chunk of chunks) {
|
|
453
|
+
const res = await this.apiCall("feishu.reply.plain_text", () => this.sdkClient.im.message.reply({
|
|
454
|
+
path: { message_id: messageId },
|
|
455
|
+
data: { msg_type: "text", content: JSON.stringify({ text: chunk }) },
|
|
456
|
+
}));
|
|
457
|
+
lastId = (res as any)?.data?.message_id as string | undefined;
|
|
458
|
+
this.rememberBotOutboundMessageId(lastId);
|
|
459
|
+
}
|
|
460
|
+
return lastId;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** 更新已发出的 text 消息正文 */
|
|
464
|
+
async updateText(messageId: string, text: string) {
|
|
465
|
+
debugLog("feishu.update.text", { messageId, length: text.length });
|
|
466
|
+
const chunk = splitText(text || "…", TEXT_CHUNK_MAX_BYTES)[0] || "…";
|
|
467
|
+
await this.apiCall("feishu.update.text", () => this.sdkClient.im.v1.message.patch({
|
|
468
|
+
path: { message_id: messageId },
|
|
469
|
+
data: { content: JSON.stringify({ text: chunk }) },
|
|
470
|
+
}));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
async sendText(chatId: string, text: string) {
|
|
474
|
+
const mode = chooseMessageMode(text);
|
|
475
|
+
if (mode === "interactive") {
|
|
476
|
+
await this.sendMarkdownCard(chatId, text);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (mode === "post") {
|
|
480
|
+
await this.sendPost(chatId, text);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
debugLog("feishu.send.text", { chatId, length: text.length });
|
|
484
|
+
const chunks = splitText(text, TEXT_CHUNK_MAX_BYTES);
|
|
485
|
+
for (const chunk of chunks) {
|
|
486
|
+
const res = await this.apiCall("feishu.send.text", () => this.sdkClient.im.message.create({
|
|
487
|
+
params: { receive_id_type: "chat_id" },
|
|
488
|
+
data: {
|
|
489
|
+
receive_id: chatId,
|
|
490
|
+
msg_type: "text",
|
|
491
|
+
content: JSON.stringify({ text: chunk }),
|
|
492
|
+
},
|
|
493
|
+
}));
|
|
494
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async replyMarkdownCard(messageId: string, text: string) {
|
|
499
|
+
debugLog("feishu.reply.markdown_card", { messageId, length: text.length });
|
|
500
|
+
for (const { card } of this.buildMarkdownCardPartsWithCopySources(text)) {
|
|
501
|
+
const res = await this.apiCall("feishu.reply.markdown_card", () => this.sdkClient.im.message.reply({
|
|
502
|
+
path: { message_id: messageId },
|
|
503
|
+
data: { msg_type: "interactive", content: JSON.stringify(card) },
|
|
504
|
+
}));
|
|
505
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
async sendMarkdownCard(chatId: string, text: string) {
|
|
510
|
+
debugLog("feishu.send.markdown_card", { chatId, length: text.length });
|
|
511
|
+
for (const { card } of this.buildMarkdownCardPartsWithCopySources(text)) {
|
|
512
|
+
const res = await this.apiCall("feishu.send.markdown_card", () => this.sdkClient.im.message.create({
|
|
513
|
+
params: { receive_id_type: "chat_id" },
|
|
514
|
+
data: {
|
|
515
|
+
receive_id: chatId,
|
|
516
|
+
msg_type: "interactive",
|
|
517
|
+
content: JSON.stringify(card),
|
|
518
|
+
},
|
|
519
|
+
}));
|
|
520
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
getMarkdownCopySource(copySourceId: string) {
|
|
525
|
+
return this.markdownCopySources.get(copySourceId);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
private buildMarkdownCardPartsWithCopySources(text: string) {
|
|
529
|
+
return buildMarkdownCardParts(text, this.config.language, () => this.createMarkdownCopySourceId())
|
|
530
|
+
.map((part) => {
|
|
531
|
+
const copySourceId = extractCopySourceId(part.card);
|
|
532
|
+
if (copySourceId) this.rememberMarkdownCopySource(copySourceId, part.markdown);
|
|
533
|
+
return part;
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
private rememberMarkdownCopySource(copySourceId: string, markdown: string) {
|
|
538
|
+
this.markdownCopySources.set(copySourceId, markdown);
|
|
539
|
+
this.markdownCopySourceOrder.push(copySourceId);
|
|
540
|
+
while (this.markdownCopySourceOrder.length > 200) {
|
|
541
|
+
const oldest = this.markdownCopySourceOrder.shift();
|
|
542
|
+
if (oldest) this.markdownCopySources.delete(oldest);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
private createMarkdownCopySourceId() {
|
|
547
|
+
this.markdownCopySeq += 1;
|
|
548
|
+
return `${Date.now().toString(36)}-${this.markdownCopySeq.toString(36)}`;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async replyPost(messageId: string, text: string) {
|
|
552
|
+
debugLog("feishu.reply.post", { messageId, length: text.length });
|
|
553
|
+
for (const post of buildPostMessages(text, this.config.language)) {
|
|
554
|
+
const res = await this.sdkClient.im.message.reply({
|
|
555
|
+
path: { message_id: messageId },
|
|
556
|
+
data: { msg_type: "post", content: JSON.stringify(post) },
|
|
557
|
+
});
|
|
558
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async sendPost(chatId: string, text: string) {
|
|
563
|
+
debugLog("feishu.send.post", { chatId, length: text.length });
|
|
564
|
+
for (const post of buildPostMessages(text, this.config.language)) {
|
|
565
|
+
const res = await this.sdkClient.im.message.create({
|
|
566
|
+
params: { receive_id_type: "chat_id" },
|
|
567
|
+
data: {
|
|
568
|
+
receive_id: chatId,
|
|
569
|
+
msg_type: "post",
|
|
570
|
+
content: JSON.stringify(post),
|
|
571
|
+
},
|
|
572
|
+
});
|
|
573
|
+
this.rememberBotOutboundMessageId((res as any)?.data?.message_id as string | undefined);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async replyCard(messageId: string, card: object) {
|
|
578
|
+
debugLog("feishu.reply.card", { messageId });
|
|
579
|
+
// 必须带重试:一次 read ETIMEDOUT 就让选择题卡片发不出去,
|
|
580
|
+
// 上游会把它当成「用户没作答」,模型接着往下答(看起来像秒超时)。
|
|
581
|
+
const res = await this.apiCall("feishu.reply.card", () => this.sdkClient.im.message.reply({
|
|
582
|
+
path: { message_id: messageId },
|
|
583
|
+
data: { msg_type: "interactive", content: JSON.stringify(card) },
|
|
584
|
+
}));
|
|
585
|
+
const id = res?.data?.message_id as string | undefined;
|
|
586
|
+
this.rememberBotOutboundMessageId(id);
|
|
587
|
+
return id;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* 平铺发送一张卡片(不挂到回复链上)。
|
|
592
|
+
*
|
|
593
|
+
* 回归背景:一輪里的回答卡与选择题卡如果都 reply 同一条用户消息,飞书会把它们
|
|
594
|
+
* 归成同一个回复簇,主聊天流只留最后一条预览,先到的那张看起来被「刷掉」了。
|
|
595
|
+
*/
|
|
596
|
+
async createCard(chatId: string, card: object): Promise<string | undefined> {
|
|
597
|
+
debugLog("feishu.send.card", { chatId });
|
|
598
|
+
const res = await this.apiCall("feishu.send.card", () => this.sdkClient.im.message.create({
|
|
599
|
+
params: { receive_id_type: "chat_id" },
|
|
600
|
+
data: {
|
|
601
|
+
receive_id: chatId,
|
|
602
|
+
msg_type: "interactive",
|
|
603
|
+
content: JSON.stringify(card),
|
|
604
|
+
},
|
|
605
|
+
}));
|
|
606
|
+
const id = res?.data?.message_id as string | undefined;
|
|
607
|
+
this.rememberBotOutboundMessageId(id);
|
|
608
|
+
return id;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* 发一张本地图片到回复链上。
|
|
613
|
+
* 模型在正文里写 `` 时由 ReplyCard 收尾调用。
|
|
614
|
+
* 失败不抛:图发不出去不该让整轮回复报错。
|
|
615
|
+
*/
|
|
616
|
+
async replyLocalImage(
|
|
617
|
+
messageId: string,
|
|
618
|
+
filePath: string,
|
|
619
|
+
replyInThread?: boolean,
|
|
620
|
+
): Promise<string | undefined> {
|
|
621
|
+
debugLog("feishu.reply.local_image", { messageId, filePath, replyInThread: Boolean(replyInThread) });
|
|
622
|
+
const id = await this.apiCall("feishu.reply.local_image", () =>
|
|
623
|
+
sendLocalImage(this.sdkClient, { replyToMessageId: messageId, replyInThread }, filePath),
|
|
624
|
+
);
|
|
625
|
+
this.rememberBotOutboundMessageId(id);
|
|
626
|
+
return id;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** 平铺发一张本地图片(不挂回复链) */
|
|
630
|
+
async sendLocalImage(chatId: string, filePath: string): Promise<string | undefined> {
|
|
631
|
+
debugLog("feishu.send.local_image", { chatId, filePath });
|
|
632
|
+
const id = await this.apiCall("feishu.send.local_image", () =>
|
|
633
|
+
sendLocalImage(this.sdkClient, { chatId }, filePath),
|
|
634
|
+
);
|
|
635
|
+
this.rememberBotOutboundMessageId(id);
|
|
636
|
+
return id;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
async updateCard(messageId: string, card: object) {
|
|
640
|
+
debugLog("feishu.update.card", { messageId });
|
|
641
|
+
await this.sdkClient.im.v1.message.patch({
|
|
642
|
+
path: { message_id: messageId },
|
|
643
|
+
data: { content: JSON.stringify(card) },
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** 拉取单条消息(用于展开 parent/root 引用卡片) */
|
|
648
|
+
async getMessage(messageId: string): Promise<{ messageId: string; msgType: string; content: string; chatId?: string } | undefined> {
|
|
649
|
+
if (!messageId) return undefined;
|
|
650
|
+
try {
|
|
651
|
+
const res = await this.apiCall<any>("feishu.get_message", () =>
|
|
652
|
+
this.sdkClient.im.message.get({ path: { message_id: messageId } }),
|
|
653
|
+
);
|
|
654
|
+
const item = res?.data?.items?.[0] || res?.data?.message || res?.data;
|
|
655
|
+
if (!item) return undefined;
|
|
656
|
+
const body = item.body || item;
|
|
657
|
+
const msgType = body.message_type || body.msg_type || item.message_type || item.msg_type || "unknown";
|
|
658
|
+
const content = typeof body.content === "string" ? body.content : JSON.stringify(body.content || {});
|
|
659
|
+
return {
|
|
660
|
+
messageId: body.message_id || item.message_id || messageId,
|
|
661
|
+
msgType,
|
|
662
|
+
content,
|
|
663
|
+
chatId: body.chat_id || item.chat_id,
|
|
664
|
+
};
|
|
665
|
+
} catch (error) {
|
|
666
|
+
debugLog("feishu.get_message.error", {
|
|
667
|
+
messageId,
|
|
668
|
+
error: error instanceof Error ? error.message : String(error),
|
|
669
|
+
});
|
|
670
|
+
return undefined;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
async getQuotedContext(msg: { parentId?: string; rootId?: string }, botOpenId?: string, maxChars = 8000) {
|
|
675
|
+
const targetId = msg.parentId || msg.rootId;
|
|
676
|
+
if (!targetId) return null;
|
|
677
|
+
const parent = await this.getMessage(targetId);
|
|
678
|
+
if (!parent) return null;
|
|
679
|
+
const extracted = extractTextFromMsgType(parent.msgType, parent.content, botOpenId);
|
|
680
|
+
let text = extracted.text.trim();
|
|
681
|
+
if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n…(truncated)`;
|
|
682
|
+
return { msgType: parent.msgType, text, attachments: extracted.attachments };
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
async downloadMessageResource(messageId: string, fileKey: string, type: "image" | "file"): Promise<{ bytes: Buffer; mimeType?: string }> {
|
|
686
|
+
debugLog("feishu.download.resource.start", { messageId, fileKey, type });
|
|
687
|
+
const result = await this.sdkClient.im.v1.messageResource.get({
|
|
688
|
+
params: { type },
|
|
689
|
+
path: { message_id: messageId, file_key: fileKey },
|
|
690
|
+
});
|
|
691
|
+
const bytes = await streamToBuffer(readableFromDownload(result));
|
|
692
|
+
const rawContentType = result.headers?.["content-type"] || result.headers?.["Content-Type"];
|
|
693
|
+
const mimeType = typeof rawContentType === "string" ? rawContentType.split(";")[0]?.trim() : undefined;
|
|
694
|
+
debugLog("feishu.download.resource.done", { messageId, fileKey, type, bytes: bytes.length, mimeType });
|
|
695
|
+
return { bytes, mimeType: mimeType || undefined };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async downloadImage(messageId: string, imageKey: string): Promise<{ bytes: Buffer; mimeType?: string }> {
|
|
699
|
+
try {
|
|
700
|
+
return await this.downloadMessageResource(messageId, imageKey, "image");
|
|
701
|
+
} catch (resourceError) {
|
|
702
|
+
debugLog("feishu.download.image.resource_failed", {
|
|
703
|
+
messageId,
|
|
704
|
+
imageKey,
|
|
705
|
+
error: resourceError instanceof Error ? resourceError.message : String(resourceError),
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
debugLog("feishu.download.image.fallback_start", { messageId, imageKey });
|
|
710
|
+
const result = await this.sdkClient.im.v1.image.get({
|
|
711
|
+
path: { image_key: imageKey },
|
|
712
|
+
});
|
|
713
|
+
const bytes = await streamToBuffer(readableFromDownload(result));
|
|
714
|
+
debugLog("feishu.download.image.fallback_done", { messageId, imageKey, bytes: bytes.length });
|
|
715
|
+
return { bytes, mimeType: "image/jpeg" };
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function splitText(text: string, maxBytes: number) {
|
|
720
|
+
const out: string[] = [];
|
|
721
|
+
let rest = text.trim() || "(empty response)";
|
|
722
|
+
while (textPayloadSize(rest) > maxBytes) {
|
|
723
|
+
const cut = findCutIndexByBytes(rest, maxBytes);
|
|
724
|
+
out.push(rest.slice(0, cut));
|
|
725
|
+
rest = rest.slice(cut);
|
|
726
|
+
}
|
|
727
|
+
out.push(rest);
|
|
728
|
+
return out;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function findCutIndexByBytes(text: string, maxBytes: number) {
|
|
732
|
+
let low = 1;
|
|
733
|
+
let high = text.length;
|
|
734
|
+
let best = 1;
|
|
735
|
+
while (low <= high) {
|
|
736
|
+
const mid = Math.floor((low + high) / 2);
|
|
737
|
+
const safeMid = avoidHalfSurrogate(text, mid);
|
|
738
|
+
if (safeMid > 0 && textPayloadSize(text.slice(0, safeMid)) <= maxBytes) {
|
|
739
|
+
best = safeMid;
|
|
740
|
+
low = mid + 1;
|
|
741
|
+
} else {
|
|
742
|
+
high = mid - 1;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
const newline = text.lastIndexOf("\n", best);
|
|
747
|
+
if (newline > 0 && newline >= Math.floor(best * 0.6)) return newline + 1;
|
|
748
|
+
return Math.max(1, best);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function avoidHalfSurrogate(text: string, index: number) {
|
|
752
|
+
if (index <= 0 || index >= text.length) return index;
|
|
753
|
+
const prev = text.charCodeAt(index - 1);
|
|
754
|
+
if (prev >= 0xd800 && prev <= 0xdbff) return index - 1;
|
|
755
|
+
return index;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function byteSize(text: string) {
|
|
759
|
+
return Buffer.byteLength(text, "utf8");
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function textPayloadSize(text: string) {
|
|
763
|
+
return byteSize(JSON.stringify({ text }));
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function extractCopySourceId(card: object) {
|
|
767
|
+
const elements = (card as any)?.body?.elements;
|
|
768
|
+
if (!Array.isArray(elements)) return undefined;
|
|
769
|
+
for (const element of elements) {
|
|
770
|
+
const behaviors = element?.behaviors;
|
|
771
|
+
if (!Array.isArray(behaviors)) continue;
|
|
772
|
+
for (const behavior of behaviors) {
|
|
773
|
+
const value = behavior?.value;
|
|
774
|
+
if (value?.action === "pi_feishu_copy_markdown" && typeof value.copySourceId === "string") {
|
|
775
|
+
return value.copySourceId;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return undefined;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function streamToBuffer(readable: NodeJS.ReadableStream): Promise<Buffer> {
|
|
783
|
+
const chunks: Buffer[] = [];
|
|
784
|
+
for await (const chunk of readable as AsyncIterable<Buffer | string>) {
|
|
785
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
786
|
+
}
|
|
787
|
+
return Buffer.concat(chunks);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function readableFromDownload(result: any): NodeJS.ReadableStream {
|
|
791
|
+
return typeof result?.getReadableStream === "function" ? result.getReadableStream() : result;
|
|
792
|
+
}
|