@tencent-connect/qqbot-nodejs 1.0.3
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/README.md +205 -0
- package/USAGE.md +804 -0
- package/dist/QQBot.d.ts +536 -0
- package/dist/QQBot.d.ts.map +1 -0
- package/dist/QQBot.js +752 -0
- package/dist/QQBot.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +66 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/access-policy.d.ts +54 -0
- package/dist/middleware/access-policy.d.ts.map +1 -0
- package/dist/middleware/access-policy.js +93 -0
- package/dist/middleware/access-policy.js.map +1 -0
- package/dist/middleware/concurrency-guard.d.ts +105 -0
- package/dist/middleware/concurrency-guard.d.ts.map +1 -0
- package/dist/middleware/concurrency-guard.js +325 -0
- package/dist/middleware/concurrency-guard.js.map +1 -0
- package/dist/middleware/content-sanitizer.d.ts +47 -0
- package/dist/middleware/content-sanitizer.d.ts.map +1 -0
- package/dist/middleware/content-sanitizer.js +85 -0
- package/dist/middleware/content-sanitizer.js.map +1 -0
- package/dist/middleware/envelope-formatter.d.ts +51 -0
- package/dist/middleware/envelope-formatter.d.ts.map +1 -0
- package/dist/middleware/envelope-formatter.js +97 -0
- package/dist/middleware/envelope-formatter.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +36 -0
- package/dist/middleware/error-handler.d.ts.map +1 -0
- package/dist/middleware/error-handler.js +59 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/history-buffer.d.ts +84 -0
- package/dist/middleware/history-buffer.d.ts.map +1 -0
- package/dist/middleware/history-buffer.js +113 -0
- package/dist/middleware/history-buffer.js.map +1 -0
- package/dist/middleware/index.d.ts +71 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +48 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/mention-gate.d.ts +99 -0
- package/dist/middleware/mention-gate.d.ts.map +1 -0
- package/dist/middleware/mention-gate.js +117 -0
- package/dist/middleware/mention-gate.js.map +1 -0
- package/dist/middleware/message-filter.d.ts +38 -0
- package/dist/middleware/message-filter.d.ts.map +1 -0
- package/dist/middleware/message-filter.js +60 -0
- package/dist/middleware/message-filter.js.map +1 -0
- package/dist/middleware/quote-ref.d.ts +106 -0
- package/dist/middleware/quote-ref.d.ts.map +1 -0
- package/dist/middleware/quote-ref.js +168 -0
- package/dist/middleware/quote-ref.js.map +1 -0
- package/dist/middleware/rate-limiter.d.ts +43 -0
- package/dist/middleware/rate-limiter.d.ts.map +1 -0
- package/dist/middleware/rate-limiter.js +77 -0
- package/dist/middleware/rate-limiter.js.map +1 -0
- package/dist/middleware/slash-command.d.ts +112 -0
- package/dist/middleware/slash-command.d.ts.map +1 -0
- package/dist/middleware/slash-command.js +203 -0
- package/dist/middleware/slash-command.js.map +1 -0
- package/dist/middleware/types.d.ts +175 -0
- package/dist/middleware/types.d.ts.map +1 -0
- package/dist/middleware/types.js +138 -0
- package/dist/middleware/types.js.map +1 -0
- package/dist/middleware/typing-indicator.d.ts +54 -0
- package/dist/middleware/typing-indicator.d.ts.map +1 -0
- package/dist/middleware/typing-indicator.js +68 -0
- package/dist/middleware/typing-indicator.js.map +1 -0
- package/dist/protocol/api/api-client.d.ts +27 -0
- package/dist/protocol/api/api-client.d.ts.map +1 -0
- package/dist/protocol/api/api-client.js +119 -0
- package/dist/protocol/api/api-client.js.map +1 -0
- package/dist/protocol/api/media-chunked.d.ts +68 -0
- package/dist/protocol/api/media-chunked.d.ts.map +1 -0
- package/dist/protocol/api/media-chunked.js +298 -0
- package/dist/protocol/api/media-chunked.js.map +1 -0
- package/dist/protocol/api/media.d.ts +46 -0
- package/dist/protocol/api/media.d.ts.map +1 -0
- package/dist/protocol/api/media.js +101 -0
- package/dist/protocol/api/media.js.map +1 -0
- package/dist/protocol/api/messages.d.ts +86 -0
- package/dist/protocol/api/messages.d.ts.map +1 -0
- package/dist/protocol/api/messages.js +200 -0
- package/dist/protocol/api/messages.js.map +1 -0
- package/dist/protocol/api/retry.d.ts +23 -0
- package/dist/protocol/api/retry.d.ts.map +1 -0
- package/dist/protocol/api/retry.js +102 -0
- package/dist/protocol/api/retry.js.map +1 -0
- package/dist/protocol/api/routes.d.ts +23 -0
- package/dist/protocol/api/routes.d.ts.map +1 -0
- package/dist/protocol/api/routes.js +50 -0
- package/dist/protocol/api/routes.js.map +1 -0
- package/dist/protocol/api/token.d.ts +38 -0
- package/dist/protocol/api/token.d.ts.map +1 -0
- package/dist/protocol/api/token.js +191 -0
- package/dist/protocol/api/token.js.map +1 -0
- package/dist/protocol/gateway/codec.d.ts +9 -0
- package/dist/protocol/gateway/codec.d.ts.map +1 -0
- package/dist/protocol/gateway/codec.js +32 -0
- package/dist/protocol/gateway/codec.js.map +1 -0
- package/dist/protocol/gateway/constants.d.ts +71 -0
- package/dist/protocol/gateway/constants.d.ts.map +1 -0
- package/dist/protocol/gateway/constants.js +91 -0
- package/dist/protocol/gateway/constants.js.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts +97 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.js +155 -0
- package/dist/protocol/gateway/event-dispatcher.js.map +1 -0
- package/dist/protocol/gateway/gateway-connection.d.ts +73 -0
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -0
- package/dist/protocol/gateway/gateway-connection.js +293 -0
- package/dist/protocol/gateway/gateway-connection.js.map +1 -0
- package/dist/protocol/gateway/reconnect.d.ts +25 -0
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -0
- package/dist/protocol/gateway/reconnect.js +118 -0
- package/dist/protocol/gateway/reconnect.js.map +1 -0
- package/dist/protocol/index.d.ts +41 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +46 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/protocol/transport/index.d.ts +8 -0
- package/dist/protocol/transport/index.d.ts.map +1 -0
- package/dist/protocol/transport/index.js +4 -0
- package/dist/protocol/transport/index.js.map +1 -0
- package/dist/protocol/transport/types.d.ts +109 -0
- package/dist/protocol/transport/types.d.ts.map +1 -0
- package/dist/protocol/transport/types.js +15 -0
- package/dist/protocol/transport/types.js.map +1 -0
- package/dist/protocol/transport/webhook-server-node.d.ts +14 -0
- package/dist/protocol/transport/webhook-server-node.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-server-node.js +57 -0
- package/dist/protocol/transport/webhook-server-node.js.map +1 -0
- package/dist/protocol/transport/webhook-verify.d.ts +49 -0
- package/dist/protocol/transport/webhook-verify.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-verify.js +98 -0
- package/dist/protocol/transport/webhook-verify.js.map +1 -0
- package/dist/protocol/transport/webhook.d.ts +37 -0
- package/dist/protocol/transport/webhook.d.ts.map +1 -0
- package/dist/protocol/transport/webhook.js +183 -0
- package/dist/protocol/transport/webhook.js.map +1 -0
- package/dist/protocol/types.d.ts +270 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +59 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/protocol/utils/audio.d.ts +79 -0
- package/dist/protocol/utils/audio.d.ts.map +1 -0
- package/dist/protocol/utils/audio.js +501 -0
- package/dist/protocol/utils/audio.js.map +1 -0
- package/dist/protocol/utils/decode-media-path.d.ts +26 -0
- package/dist/protocol/utils/decode-media-path.d.ts.map +1 -0
- package/dist/protocol/utils/decode-media-path.js +79 -0
- package/dist/protocol/utils/decode-media-path.js.map +1 -0
- package/dist/protocol/utils/ffmpeg.d.ts +38 -0
- package/dist/protocol/utils/ffmpeg.d.ts.map +1 -0
- package/dist/protocol/utils/ffmpeg.js +119 -0
- package/dist/protocol/utils/ffmpeg.js.map +1 -0
- package/dist/protocol/utils/file-utils.d.ts +42 -0
- package/dist/protocol/utils/file-utils.d.ts.map +1 -0
- package/dist/protocol/utils/file-utils.js +108 -0
- package/dist/protocol/utils/file-utils.js.map +1 -0
- package/dist/protocol/utils/format.d.ts +10 -0
- package/dist/protocol/utils/format.d.ts.map +1 -0
- package/dist/protocol/utils/format.js +68 -0
- package/dist/protocol/utils/format.js.map +1 -0
- package/dist/protocol/utils/image-size.d.ts +56 -0
- package/dist/protocol/utils/image-size.d.ts.map +1 -0
- package/dist/protocol/utils/image-size.js +185 -0
- package/dist/protocol/utils/image-size.js.map +1 -0
- package/dist/protocol/utils/media-source.d.ts +145 -0
- package/dist/protocol/utils/media-source.d.ts.map +1 -0
- package/dist/protocol/utils/media-source.js +175 -0
- package/dist/protocol/utils/media-source.js.map +1 -0
- package/dist/protocol/utils/media-tags.d.ts +15 -0
- package/dist/protocol/utils/media-tags.d.ts.map +1 -0
- package/dist/protocol/utils/media-tags.js +150 -0
- package/dist/protocol/utils/media-tags.js.map +1 -0
- package/dist/protocol/utils/media-type.d.ts +41 -0
- package/dist/protocol/utils/media-type.d.ts.map +1 -0
- package/dist/protocol/utils/media-type.js +89 -0
- package/dist/protocol/utils/media-type.js.map +1 -0
- package/dist/protocol/utils/payload.d.ts +52 -0
- package/dist/protocol/utils/payload.d.ts.map +1 -0
- package/dist/protocol/utils/payload.js +100 -0
- package/dist/protocol/utils/payload.js.map +1 -0
- package/dist/protocol/utils/ref-attachments.d.ts +80 -0
- package/dist/protocol/utils/ref-attachments.d.ts.map +1 -0
- package/dist/protocol/utils/ref-attachments.js +121 -0
- package/dist/protocol/utils/ref-attachments.js.map +1 -0
- package/dist/protocol/utils/ref-index-store.d.ts +69 -0
- package/dist/protocol/utils/ref-index-store.d.ts.map +1 -0
- package/dist/protocol/utils/ref-index-store.js +227 -0
- package/dist/protocol/utils/ref-index-store.js.map +1 -0
- package/dist/protocol/utils/reply-limiter.d.ts +75 -0
- package/dist/protocol/utils/reply-limiter.d.ts.map +1 -0
- package/dist/protocol/utils/reply-limiter.js +123 -0
- package/dist/protocol/utils/reply-limiter.js.map +1 -0
- package/dist/protocol/utils/session-store.d.ts +73 -0
- package/dist/protocol/utils/session-store.d.ts.map +1 -0
- package/dist/protocol/utils/session-store.js +274 -0
- package/dist/protocol/utils/session-store.js.map +1 -0
- package/dist/protocol/utils/target.d.ts +53 -0
- package/dist/protocol/utils/target.d.ts.map +1 -0
- package/dist/protocol/utils/target.js +104 -0
- package/dist/protocol/utils/target.js.map +1 -0
- package/dist/protocol/utils/text-chunk.d.ts +21 -0
- package/dist/protocol/utils/text-chunk.d.ts.map +1 -0
- package/dist/protocol/utils/text-chunk.js +25 -0
- package/dist/protocol/utils/text-chunk.js.map +1 -0
- package/dist/protocol/utils/text-parsing.d.ts +40 -0
- package/dist/protocol/utils/text-parsing.d.ts.map +1 -0
- package/dist/protocol/utils/text-parsing.js +126 -0
- package/dist/protocol/utils/text-parsing.js.map +1 -0
- package/dist/protocol/utils/upload-cache.d.ts +27 -0
- package/dist/protocol/utils/upload-cache.d.ts.map +1 -0
- package/dist/protocol/utils/upload-cache.js +73 -0
- package/dist/protocol/utils/upload-cache.js.map +1 -0
- package/dist/protocol/utils/voice-text.d.ts +9 -0
- package/dist/protocol/utils/voice-text.d.ts.map +1 -0
- package/dist/protocol/utils/voice-text.js +16 -0
- package/dist/protocol/utils/voice-text.js.map +1 -0
- package/dist/storage/index.d.ts +23 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +21 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/kv-store.d.ts +85 -0
- package/dist/storage/kv-store.d.ts.map +1 -0
- package/dist/storage/kv-store.js +184 -0
- package/dist/storage/kv-store.js.map +1 -0
- package/dist/storage/session-adapter.d.ts +35 -0
- package/dist/storage/session-adapter.d.ts.map +1 -0
- package/dist/storage/session-adapter.js +48 -0
- package/dist/storage/session-adapter.js.map +1 -0
- package/dist/streaming.d.ts +67 -0
- package/dist/streaming.d.ts.map +1 -0
- package/dist/streaming.js +207 -0
- package/dist/streaming.js.map +1 -0
- package/package.json +90 -0
- package/src/QQBot.ts +1123 -0
- package/src/index.ts +175 -0
- package/src/middleware/access-policy.ts +139 -0
- package/src/middleware/concurrency-guard.ts +450 -0
- package/src/middleware/content-sanitizer.ts +125 -0
- package/src/middleware/envelope-formatter.ts +140 -0
- package/src/middleware/error-handler.ts +77 -0
- package/src/middleware/history-buffer.ts +169 -0
- package/src/middleware/index.ts +129 -0
- package/src/middleware/mention-gate.ts +227 -0
- package/src/middleware/message-filter.ts +82 -0
- package/src/middleware/quote-ref.ts +237 -0
- package/src/middleware/rate-limiter.ts +112 -0
- package/src/middleware/slash-command.ts +307 -0
- package/src/middleware/types.ts +273 -0
- package/src/middleware/typing-indicator.ts +107 -0
- package/src/protocol/api/api-client.ts +170 -0
- package/src/protocol/api/media-chunked.ts +517 -0
- package/src/protocol/api/media.ts +188 -0
- package/src/protocol/api/messages.ts +345 -0
- package/src/protocol/api/retry.ts +157 -0
- package/src/protocol/api/routes.ts +62 -0
- package/src/protocol/api/token.ts +250 -0
- package/src/protocol/gateway/codec.ts +33 -0
- package/src/protocol/gateway/constants.ts +98 -0
- package/src/protocol/gateway/event-dispatcher.ts +275 -0
- package/src/protocol/gateway/gateway-connection.ts +375 -0
- package/src/protocol/gateway/reconnect.ts +155 -0
- package/src/protocol/index.ts +238 -0
- package/src/protocol/transport/index.ts +17 -0
- package/src/protocol/transport/types.ts +121 -0
- package/src/protocol/transport/webhook-server-node.ts +64 -0
- package/src/protocol/transport/webhook-verify.ts +118 -0
- package/src/protocol/transport/webhook.ts +237 -0
- package/src/protocol/types.ts +305 -0
- package/src/protocol/utils/audio.ts +663 -0
- package/src/protocol/utils/decode-media-path.ts +88 -0
- package/src/protocol/utils/ffmpeg.ts +131 -0
- package/src/protocol/utils/file-utils.ts +121 -0
- package/src/protocol/utils/format.ts +69 -0
- package/src/protocol/utils/image-size.ts +236 -0
- package/src/protocol/utils/media-source.ts +243 -0
- package/src/protocol/utils/media-tags.ts +177 -0
- package/src/protocol/utils/media-type.ts +102 -0
- package/src/protocol/utils/payload.ts +157 -0
- package/src/protocol/utils/ref-attachments.ts +190 -0
- package/src/protocol/utils/ref-index-store.ts +279 -0
- package/src/protocol/utils/reply-limiter.ts +164 -0
- package/src/protocol/utils/session-store.ts +346 -0
- package/src/protocol/utils/target.ts +121 -0
- package/src/protocol/utils/text-chunk.ts +29 -0
- package/src/protocol/utils/text-parsing.ts +153 -0
- package/src/protocol/utils/upload-cache.ts +107 -0
- package/src/protocol/utils/voice-text.ts +16 -0
- package/src/storage/index.ts +24 -0
- package/src/storage/kv-store.ts +243 -0
- package/src/storage/session-adapter.ts +66 -0
- package/src/streaming.ts +255 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typing-indicator middleware — auto-send a `typing` notification for C2C
|
|
3
|
+
* messages so the user sees a visual hint while the bot is processing.
|
|
4
|
+
*
|
|
5
|
+
* Supports keepalive mode: periodically re-send typing every `intervalSec`
|
|
6
|
+
* to cover long-running AI inference (QQ platform typing window is ~60s).
|
|
7
|
+
*
|
|
8
|
+
* QQ Open Platform restriction: `sendInputNotify` only works for C2C
|
|
9
|
+
* (private chat) targets. Group / Guild messages are silently skipped.
|
|
10
|
+
*/
|
|
11
|
+
import type { Middleware } from "./types.js";
|
|
12
|
+
export interface TypingIndicatorOptions {
|
|
13
|
+
/** Indicator duration per send, in seconds. Defaults to 60. */
|
|
14
|
+
durationSec?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Only send typing for messages that pass `predicate(ctx)`. Defaults to
|
|
17
|
+
* always (returns true).
|
|
18
|
+
*/
|
|
19
|
+
predicate?: (ctx: import("./types.js").MiddlewareContext) => boolean;
|
|
20
|
+
/**
|
|
21
|
+
* If `true`, the typing call is awaited before continuing the chain.
|
|
22
|
+
* Defaults to `false` (fire-and-forget).
|
|
23
|
+
*/
|
|
24
|
+
awaitTyping?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Enable keepalive: re-send typing every `keepAliveIntervalMs` until
|
|
27
|
+
* the downstream middleware chain completes. Defaults to `true`.
|
|
28
|
+
*/
|
|
29
|
+
keepAlive?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Keepalive interval in milliseconds. Defaults to 50_000 (50s).
|
|
32
|
+
* Should be less than the platform's typing window (~60s).
|
|
33
|
+
*/
|
|
34
|
+
keepAliveIntervalMs?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Auto-send `typing` notification for inbound C2C messages.
|
|
38
|
+
*
|
|
39
|
+
* With keepalive enabled (default), typing is refreshed periodically
|
|
40
|
+
* throughout the entire middleware chain + message handler execution,
|
|
41
|
+
* covering long-running AI inference that may take 30s+.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* bot.use(typingIndicator()); // keepalive enabled by default
|
|
46
|
+
* bot.on("message", async (msg) => {
|
|
47
|
+
* // User sees "typing…" continuously while the LLM is generating
|
|
48
|
+
* const reply = await llm.chat(msg.content);
|
|
49
|
+
* await bot.sendText(msg.replyTarget, reply);
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare function typingIndicator(options?: TypingIndicatorOptions): Middleware;
|
|
54
|
+
//# sourceMappingURL=typing-indicator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typing-indicator.d.ts","sourceRoot":"","sources":["../../src/middleware/typing-indicator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAI7C,MAAM,WAAW,sBAAsB;IACrC,+DAA+D;IAC/D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,YAAY,EAAE,iBAAiB,KAAK,OAAO,CAAC;IACrE;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AASD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,UAAU,CA0ChF"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typing-indicator middleware — auto-send a `typing` notification for C2C
|
|
3
|
+
* messages so the user sees a visual hint while the bot is processing.
|
|
4
|
+
*
|
|
5
|
+
* Supports keepalive mode: periodically re-send typing every `intervalSec`
|
|
6
|
+
* to cover long-running AI inference (QQ platform typing window is ~60s).
|
|
7
|
+
*
|
|
8
|
+
* QQ Open Platform restriction: `sendInputNotify` only works for C2C
|
|
9
|
+
* (private chat) targets. Group / Guild messages are silently skipped.
|
|
10
|
+
*/
|
|
11
|
+
// ============ Constants ============
|
|
12
|
+
const DEFAULT_DURATION_SEC = 60;
|
|
13
|
+
const DEFAULT_KEEPALIVE_INTERVAL_MS = 50_000;
|
|
14
|
+
// ============ Middleware ============
|
|
15
|
+
/**
|
|
16
|
+
* Auto-send `typing` notification for inbound C2C messages.
|
|
17
|
+
*
|
|
18
|
+
* With keepalive enabled (default), typing is refreshed periodically
|
|
19
|
+
* throughout the entire middleware chain + message handler execution,
|
|
20
|
+
* covering long-running AI inference that may take 30s+.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* bot.use(typingIndicator()); // keepalive enabled by default
|
|
25
|
+
* bot.on("message", async (msg) => {
|
|
26
|
+
* // User sees "typing…" continuously while the LLM is generating
|
|
27
|
+
* const reply = await llm.chat(msg.content);
|
|
28
|
+
* await bot.sendText(msg.replyTarget, reply);
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function typingIndicator(options = {}) {
|
|
33
|
+
const durationSec = options.durationSec ?? DEFAULT_DURATION_SEC;
|
|
34
|
+
const predicate = options.predicate ?? (() => true);
|
|
35
|
+
const awaitTyping = options.awaitTyping ?? false;
|
|
36
|
+
const keepAlive = options.keepAlive ?? true;
|
|
37
|
+
const keepAliveIntervalMs = options.keepAliveIntervalMs ?? DEFAULT_KEEPALIVE_INTERVAL_MS;
|
|
38
|
+
return async (ctx, next) => {
|
|
39
|
+
if (ctx.message.kind !== "c2c" || !predicate(ctx)) {
|
|
40
|
+
await next();
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const sendTyping = () => ctx.bot.sendTyping(ctx.replyTarget, durationSec).catch((err) => {
|
|
44
|
+
ctx.log.debug?.(`[typing] failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
45
|
+
});
|
|
46
|
+
// Send initial typing
|
|
47
|
+
const promise = sendTyping();
|
|
48
|
+
if (awaitTyping) {
|
|
49
|
+
await promise;
|
|
50
|
+
}
|
|
51
|
+
// Setup keepalive timer
|
|
52
|
+
let timer = null;
|
|
53
|
+
if (keepAlive) {
|
|
54
|
+
timer = setInterval(() => {
|
|
55
|
+
sendTyping();
|
|
56
|
+
}, keepAliveIntervalMs);
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
await next();
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
if (timer) {
|
|
63
|
+
clearInterval(timer);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=typing-indicator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typing-indicator.js","sourceRoot":"","sources":["../../src/middleware/typing-indicator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AA+BH,sCAAsC;AAEtC,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,MAAM,6BAA6B,GAAG,MAAM,CAAC;AAE7C,uCAAuC;AAEvC;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,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BAAS,CAAC;YACT,IAAI,KAAK,EAAE,CAAC;gBACV,aAAa,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core HTTP client for the QQ Open Platform REST API.
|
|
3
|
+
*
|
|
4
|
+
* - `ApiClient` is an instance — config (baseUrl, timeout, logger, UA)
|
|
5
|
+
* is injected via the constructor, eliminating module-level globals.
|
|
6
|
+
* - Throws structured `ApiError` with httpStatus, bizCode, and path fields.
|
|
7
|
+
* - Detects HTML error pages from CDN/gateway and returns user-friendly messages.
|
|
8
|
+
*/
|
|
9
|
+
import { type ApiClientConfig } from "../types.js";
|
|
10
|
+
export interface RequestOptions {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
redactBodyKeys?: string[];
|
|
13
|
+
uploadRequest?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Stateful HTTP client for the QQ Open Platform.
|
|
17
|
+
*/
|
|
18
|
+
export declare class ApiClient {
|
|
19
|
+
private readonly baseUrl;
|
|
20
|
+
private readonly defaultTimeoutMs;
|
|
21
|
+
private readonly fileUploadTimeoutMs;
|
|
22
|
+
private readonly logger?;
|
|
23
|
+
private readonly resolveUserAgent;
|
|
24
|
+
constructor(config?: ApiClientConfig);
|
|
25
|
+
request<T = unknown>(accessToken: string, method: string, path: string, body?: unknown, options?: RequestOptions): Promise<T>;
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=api-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client.d.ts","sourceRoot":"","sources":["../../../src/protocol/api/api-client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAY,KAAK,eAAe,EAAe,MAAM,aAAa,CAAC;AAO1E,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAED;;GAEG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAS;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAe;gBAEpC,MAAM,GAAE,eAAoB;IASlC,OAAO,CAAC,CAAC,GAAG,OAAO,EACvB,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,cAAc,GACvB,OAAO,CAAC,CAAC,CAAC;CA0Hd"}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core HTTP client for the QQ Open Platform REST API.
|
|
3
|
+
*
|
|
4
|
+
* - `ApiClient` is an instance — config (baseUrl, timeout, logger, UA)
|
|
5
|
+
* is injected via the constructor, eliminating module-level globals.
|
|
6
|
+
* - Throws structured `ApiError` with httpStatus, bizCode, and path fields.
|
|
7
|
+
* - Detects HTML error pages from CDN/gateway and returns user-friendly messages.
|
|
8
|
+
*/
|
|
9
|
+
import { ApiError } from "../types.js";
|
|
10
|
+
import { formatErrorMessage } from "../utils/format.js";
|
|
11
|
+
const DEFAULT_BASE_URL = "https://api.sgroup.qq.com";
|
|
12
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
13
|
+
const FILE_UPLOAD_TIMEOUT_MS = 120_000;
|
|
14
|
+
/**
|
|
15
|
+
* Stateful HTTP client for the QQ Open Platform.
|
|
16
|
+
*/
|
|
17
|
+
export class ApiClient {
|
|
18
|
+
baseUrl;
|
|
19
|
+
defaultTimeoutMs;
|
|
20
|
+
fileUploadTimeoutMs;
|
|
21
|
+
logger;
|
|
22
|
+
resolveUserAgent;
|
|
23
|
+
constructor(config = {}) {
|
|
24
|
+
this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
25
|
+
this.defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
26
|
+
this.fileUploadTimeoutMs = config.fileUploadTimeoutMs ?? FILE_UPLOAD_TIMEOUT_MS;
|
|
27
|
+
this.logger = config.logger;
|
|
28
|
+
const ua = config.userAgent ?? "qqbot-nodejs/unknown";
|
|
29
|
+
this.resolveUserAgent = typeof ua === "function" ? ua : () => ua;
|
|
30
|
+
}
|
|
31
|
+
async request(accessToken, method, path, body, options) {
|
|
32
|
+
const url = `${this.baseUrl}${path}`;
|
|
33
|
+
const headers = {
|
|
34
|
+
Authorization: `QQBot ${accessToken}`,
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
"User-Agent": this.resolveUserAgent(),
|
|
37
|
+
};
|
|
38
|
+
const isFileUpload = options?.uploadRequest === true ||
|
|
39
|
+
path.includes("/files") ||
|
|
40
|
+
path.includes("/upload_prepare") ||
|
|
41
|
+
path.includes("/upload_part_finish");
|
|
42
|
+
const timeout = options?.timeoutMs ?? (isFileUpload ? this.fileUploadTimeoutMs : this.defaultTimeoutMs);
|
|
43
|
+
const controller = new AbortController();
|
|
44
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
45
|
+
const fetchInit = { method, headers, signal: controller.signal };
|
|
46
|
+
if (body) {
|
|
47
|
+
fetchInit.body = JSON.stringify(body);
|
|
48
|
+
}
|
|
49
|
+
this.logger?.debug?.(`[qqbot:api] >>> ${method} ${url} (timeout: ${timeout}ms)`);
|
|
50
|
+
if (body && this.logger?.debug) {
|
|
51
|
+
const logBody = { ...body };
|
|
52
|
+
for (const key of options?.redactBodyKeys ?? ["file_data"]) {
|
|
53
|
+
if (typeof logBody[key] === "string") {
|
|
54
|
+
logBody[key] = `<redacted ${logBody[key].length} chars>`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
this.logger.debug(`[qqbot:api] >>> Body: ${JSON.stringify(logBody)}`);
|
|
58
|
+
}
|
|
59
|
+
let res;
|
|
60
|
+
try {
|
|
61
|
+
res = await fetch(url, fetchInit);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
clearTimeout(timeoutId);
|
|
65
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
66
|
+
this.logger?.error?.(`[qqbot:api] <<< Timeout after ${timeout}ms`);
|
|
67
|
+
throw new ApiError(`Request timeout [${path}]: exceeded ${timeout}ms`, 0, path);
|
|
68
|
+
}
|
|
69
|
+
this.logger?.error?.(`[qqbot:api] <<< Network error: ${formatErrorMessage(err)}`);
|
|
70
|
+
throw new ApiError(`Network error [${path}]: ${formatErrorMessage(err)}`, 0, path);
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
clearTimeout(timeoutId);
|
|
74
|
+
}
|
|
75
|
+
const traceId = res.headers.get("x-tps-trace-id") ?? "";
|
|
76
|
+
this.logger?.info?.(`[qqbot:api] <<< Status: ${res.status} ${res.statusText}${traceId ? ` | TraceId: ${traceId}` : ""}`);
|
|
77
|
+
let rawBody;
|
|
78
|
+
try {
|
|
79
|
+
rawBody = await res.text();
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
throw new ApiError(`Failed to read response [${path}]: ${formatErrorMessage(err)}`, res.status, path);
|
|
83
|
+
}
|
|
84
|
+
this.logger?.debug?.(`[qqbot:api] <<< Body: ${rawBody}`);
|
|
85
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
86
|
+
const isHtmlResponse = contentType.includes("text/html") || rawBody.trimStart().startsWith("<");
|
|
87
|
+
if (!res.ok) {
|
|
88
|
+
if (isHtmlResponse) {
|
|
89
|
+
const statusHint = res.status === 502 || res.status === 503 || res.status === 504
|
|
90
|
+
? "调用发生异常,请稍候重试"
|
|
91
|
+
: res.status === 429
|
|
92
|
+
? "请求过于频繁,已被限流"
|
|
93
|
+
: `开放平台返回 HTTP ${res.status}`;
|
|
94
|
+
throw new ApiError(`${statusHint}(${path}),请稍后重试`, res.status, path);
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const error = JSON.parse(rawBody);
|
|
98
|
+
const bizCode = error.code ?? error.err_code;
|
|
99
|
+
throw new ApiError(`API Error [${path}]: ${error.message ?? rawBody}`, res.status, path, bizCode, error.message);
|
|
100
|
+
}
|
|
101
|
+
catch (parseErr) {
|
|
102
|
+
if (parseErr instanceof ApiError) {
|
|
103
|
+
throw parseErr;
|
|
104
|
+
}
|
|
105
|
+
throw new ApiError(`API Error [${path}] HTTP ${res.status}: ${rawBody.slice(0, 200)}`, res.status, path);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (isHtmlResponse) {
|
|
109
|
+
throw new ApiError(`QQ 服务端返回了非 JSON 响应(${path}),可能是临时故障,请稍后重试`, res.status, path);
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(rawBody);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
throw new ApiError(`开放平台响应格式异常(${path}),请稍后重试`, res.status, path);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=api-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-client.js","sourceRoot":"","sources":["../../../src/protocol/api/api-client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAqC,MAAM,aAAa,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AACrD,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAClC,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAQvC;;GAEG;AACH,MAAM,OAAO,S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IAAI,CACL,CAAC;YACJ,CAAC;QACH,CAAC;QAED,IAAI,cAAc,EAAE,CAAC;YACnB,MAAM,IAAI,QAAQ,CAChB,sBAAsB,IAAI,iBAAiB,EAC3C,GAAG,CAAC,MAAM,EACV,IAAI,CACL,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAM,CAAC;QAClC,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,QAAQ,CAAC,cAAc,IAAI,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACpE,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chunked media upload for the QQ Open Platform (large files > 5MB).
|
|
3
|
+
*
|
|
4
|
+
* Flow:
|
|
5
|
+
* 1. `upload_prepare` — submit file metadata + (md5/sha1/md5_10m) hashes,
|
|
6
|
+
* receive `{ upload_id, block_size, parts[], concurrency? }`.
|
|
7
|
+
* 2. For every part:
|
|
8
|
+
* a. PUT bytes to the pre-signed COS URL.
|
|
9
|
+
* b. POST `upload_part_finish` with persistent retry.
|
|
10
|
+
* 3. POST `complete_upload` — returns `{ file_uuid, file_info, ttl }`.
|
|
11
|
+
*/
|
|
12
|
+
import { MediaFileType, type ChatScope, type Credentials, type Logger, type UploadMediaResponse } from "../types.js";
|
|
13
|
+
import type { ApiClient } from "./api-client.js";
|
|
14
|
+
import type { SanitizeFileNameFn, UploadCacheAdapter } from "./media.js";
|
|
15
|
+
import type { TokenManager } from "./token.js";
|
|
16
|
+
/**
|
|
17
|
+
* Raised when `upload_prepare` returns {@link UPLOAD_PREPARE_FALLBACK_CODE}.
|
|
18
|
+
*/
|
|
19
|
+
export declare class UploadDailyLimitExceededError extends Error {
|
|
20
|
+
readonly filePath: string;
|
|
21
|
+
readonly fileSize: number;
|
|
22
|
+
readonly name = "UploadDailyLimitExceededError";
|
|
23
|
+
constructor(filePath: string, fileSize: number, originalMessage: string);
|
|
24
|
+
}
|
|
25
|
+
export interface ChunkedUploadProgress {
|
|
26
|
+
completedParts: number;
|
|
27
|
+
totalParts: number;
|
|
28
|
+
uploadedBytes: number;
|
|
29
|
+
totalBytes: number;
|
|
30
|
+
}
|
|
31
|
+
/** Source of bytes for a chunked upload. */
|
|
32
|
+
export type ChunkedMediaSource = {
|
|
33
|
+
kind: "localPath";
|
|
34
|
+
path: string;
|
|
35
|
+
size: number;
|
|
36
|
+
} | {
|
|
37
|
+
kind: "buffer";
|
|
38
|
+
buffer: Buffer;
|
|
39
|
+
fileName?: string;
|
|
40
|
+
};
|
|
41
|
+
export interface UploadChunkedOptions {
|
|
42
|
+
scope: ChatScope;
|
|
43
|
+
targetId: string;
|
|
44
|
+
fileType: MediaFileType;
|
|
45
|
+
source: ChunkedMediaSource;
|
|
46
|
+
creds: Credentials;
|
|
47
|
+
fileName?: string;
|
|
48
|
+
onProgress?: (progress: ChunkedUploadProgress) => void;
|
|
49
|
+
logPrefix?: string;
|
|
50
|
+
}
|
|
51
|
+
export interface ChunkedMediaApiConfig {
|
|
52
|
+
logger?: Logger;
|
|
53
|
+
uploadCache?: UploadCacheAdapter;
|
|
54
|
+
sanitizeFileName?: SanitizeFileNameFn;
|
|
55
|
+
}
|
|
56
|
+
export declare class ChunkedMediaApi {
|
|
57
|
+
private readonly client;
|
|
58
|
+
private readonly tokenManager;
|
|
59
|
+
private readonly logger?;
|
|
60
|
+
private readonly cache?;
|
|
61
|
+
private readonly sanitize;
|
|
62
|
+
constructor(client: ApiClient, tokenManager: TokenManager, config?: ChunkedMediaApiConfig);
|
|
63
|
+
uploadChunked(opts: UploadChunkedOptions): Promise<UploadMediaResponse>;
|
|
64
|
+
private callUploadPrepare;
|
|
65
|
+
private callUploadPartFinish;
|
|
66
|
+
private callCompleteUpload;
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=media-chunked.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
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CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,qBAAqB,KAAK,IAAI,CAAC;IACvD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,qBAAqB;IACpC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,gBAAgB,CAAC,EAAE,kBAAkB,CAAC;CACvC;AAQD,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;gBAElC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,GAAE,qBAA0B;IAQvF,aAAa,CAAC,IAAI,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC;YAoH/D,iBAAiB;YAgCjB,oBAAoB;YAmCpB,kBAAkB;CAwBjC"}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chunked media upload for the QQ Open Platform (large files > 5MB).
|
|
3
|
+
*
|
|
4
|
+
* Flow:
|
|
5
|
+
* 1. `upload_prepare` — submit file metadata + (md5/sha1/md5_10m) hashes,
|
|
6
|
+
* receive `{ upload_id, block_size, parts[], concurrency? }`.
|
|
7
|
+
* 2. For every part:
|
|
8
|
+
* a. PUT bytes to the pre-signed COS URL.
|
|
9
|
+
* b. POST `upload_part_finish` with persistent retry.
|
|
10
|
+
* 3. POST `complete_upload` — returns `{ file_uuid, file_info, ttl }`.
|
|
11
|
+
*/
|
|
12
|
+
import * as crypto from "node:crypto";
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
import * as https from "node:https";
|
|
15
|
+
import { ApiError, MediaFileType, } from "../types.js";
|
|
16
|
+
import { formatFileSize } from "../utils/format.js";
|
|
17
|
+
import { buildPartFinishPersistentPolicy, COMPLETE_UPLOAD_RETRY_POLICY, PART_FINISH_RETRY_POLICY, UPLOAD_PREPARE_FALLBACK_CODE, withRetry, } from "./retry.js";
|
|
18
|
+
import { uploadCompletePath, uploadPartFinishPath, uploadPreparePath } from "./routes.js";
|
|
19
|
+
/**
|
|
20
|
+
* Raised when `upload_prepare` returns {@link UPLOAD_PREPARE_FALLBACK_CODE}.
|
|
21
|
+
*/
|
|
22
|
+
export class UploadDailyLimitExceededError extends Error {
|
|
23
|
+
filePath;
|
|
24
|
+
fileSize;
|
|
25
|
+
name = "UploadDailyLimitExceededError";
|
|
26
|
+
constructor(filePath, fileSize, originalMessage) {
|
|
27
|
+
super(originalMessage);
|
|
28
|
+
this.filePath = filePath;
|
|
29
|
+
this.fileSize = fileSize;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const DEFAULT_CONCURRENT_PARTS = 1;
|
|
33
|
+
const MAX_CONCURRENT_PARTS = 10;
|
|
34
|
+
const MAX_PART_FINISH_RETRY_TIMEOUT_MS = 10 * 60 * 1000;
|
|
35
|
+
const PART_UPLOAD_TIMEOUT_MS = 300_000;
|
|
36
|
+
const MD5_10M_SIZE = 10_002_432;
|
|
37
|
+
export class ChunkedMediaApi {
|
|
38
|
+
client;
|
|
39
|
+
tokenManager;
|
|
40
|
+
logger;
|
|
41
|
+
cache;
|
|
42
|
+
sanitize;
|
|
43
|
+
constructor(client, tokenManager, config = {}) {
|
|
44
|
+
this.client = client;
|
|
45
|
+
this.tokenManager = tokenManager;
|
|
46
|
+
this.logger = config.logger;
|
|
47
|
+
this.cache = config.uploadCache;
|
|
48
|
+
this.sanitize = config.sanitizeFileName ?? ((n) => n);
|
|
49
|
+
}
|
|
50
|
+
async uploadChunked(opts) {
|
|
51
|
+
const prefix = opts.logPrefix ?? "[qqbot:chunked-upload]";
|
|
52
|
+
const input = resolveSource(opts.source, opts.fileName);
|
|
53
|
+
const displayName = input.fileName;
|
|
54
|
+
const fileSize = input.size;
|
|
55
|
+
const pathLabel = input.kind === "localPath" ? input.path : "<buffer>";
|
|
56
|
+
this.logger?.info?.(`${prefix} Start: file=${displayName} size=${formatFileSize(fileSize)} type=${opts.fileType}`);
|
|
57
|
+
const hashes = await computeHashes(input);
|
|
58
|
+
this.logger?.debug?.(`${prefix} hashes: md5=${hashes.md5} sha1=${hashes.sha1} md5_10m=${hashes.md5_10m}`);
|
|
59
|
+
if (this.cache) {
|
|
60
|
+
const cached = this.cache.get(hashes.md5, opts.scope, opts.targetId, opts.fileType);
|
|
61
|
+
if (cached) {
|
|
62
|
+
this.logger?.info?.(`${prefix} cache HIT (md5=${hashes.md5.slice(0, 8)}) — skipping chunked upload`);
|
|
63
|
+
return { file_uuid: "", file_info: cached, ttl: 0 };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const fileNameForPrepare = opts.fileType === MediaFileType.FILE ? this.sanitize(displayName) : displayName;
|
|
67
|
+
const prepareResp = await this.callUploadPrepare(opts, fileNameForPrepare, fileSize, hashes, pathLabel);
|
|
68
|
+
const { upload_id, parts } = prepareResp;
|
|
69
|
+
const block_size = prepareResp.block_size;
|
|
70
|
+
const maxConcurrent = Math.min(prepareResp.concurrency ? prepareResp.concurrency : DEFAULT_CONCURRENT_PARTS, MAX_CONCURRENT_PARTS);
|
|
71
|
+
const retryTimeoutMs = prepareResp.retry_timeout
|
|
72
|
+
? Math.min(prepareResp.retry_timeout * 1000, MAX_PART_FINISH_RETRY_TIMEOUT_MS)
|
|
73
|
+
: undefined;
|
|
74
|
+
this.logger?.info?.(`${prefix} prepared: upload_id=${upload_id} block=${formatFileSize(block_size)} parts=${parts.length} concurrency=${maxConcurrent}`);
|
|
75
|
+
let completedParts = 0;
|
|
76
|
+
let uploadedBytes = 0;
|
|
77
|
+
const uploadPart = async (part) => {
|
|
78
|
+
const partIndex = part.index;
|
|
79
|
+
const offset = (partIndex - 1) * block_size;
|
|
80
|
+
const length = Math.min(block_size, fileSize - offset);
|
|
81
|
+
const partBuffer = await readPart(input, offset, length);
|
|
82
|
+
const md5Hex = crypto.createHash("md5").update(partBuffer).digest("hex");
|
|
83
|
+
this.logger?.debug?.(`${prefix} part ${partIndex}/${parts.length}: ${formatFileSize(length)} offset=${offset} md5=${md5Hex}`);
|
|
84
|
+
await putToPresignedUrl(part.presigned_url, partBuffer, partIndex, parts.length, this.logger, prefix);
|
|
85
|
+
await this.callUploadPartFinish(opts, upload_id, partIndex, length, md5Hex, retryTimeoutMs);
|
|
86
|
+
completedParts++;
|
|
87
|
+
uploadedBytes += length;
|
|
88
|
+
this.logger?.info?.(`${prefix} part ${partIndex}/${parts.length} done (${completedParts}/${parts.length})`);
|
|
89
|
+
opts.onProgress?.({
|
|
90
|
+
completedParts,
|
|
91
|
+
totalParts: parts.length,
|
|
92
|
+
uploadedBytes,
|
|
93
|
+
totalBytes: fileSize,
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
await runWithConcurrency(parts.map((part) => () => uploadPart(part)), maxConcurrent);
|
|
97
|
+
this.logger?.info?.(`${prefix} all parts uploaded, completing...`);
|
|
98
|
+
const result = await this.callCompleteUpload(opts, upload_id);
|
|
99
|
+
this.logger?.info?.(`${prefix} completed: file_uuid=${result.file_uuid} ttl=${result.ttl}s`);
|
|
100
|
+
if (this.cache && result.file_info && result.ttl > 0) {
|
|
101
|
+
this.cache.set(hashes.md5, opts.scope, opts.targetId, opts.fileType, result.file_info, result.file_uuid, result.ttl);
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
async callUploadPrepare(opts, fileName, fileSize, hashes, pathLabel) {
|
|
106
|
+
const token = await this.tokenManager.getAccessToken(opts.creds.appId, opts.creds.clientSecret);
|
|
107
|
+
const path = uploadPreparePath(opts.scope, opts.targetId);
|
|
108
|
+
try {
|
|
109
|
+
return await this.client.request(token, "POST", path, {
|
|
110
|
+
file_type: opts.fileType,
|
|
111
|
+
file_name: fileName,
|
|
112
|
+
file_size: fileSize,
|
|
113
|
+
md5: hashes.md5,
|
|
114
|
+
sha1: hashes.sha1,
|
|
115
|
+
md5_10m: hashes.md5_10m,
|
|
116
|
+
}, { uploadRequest: true });
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
if (err instanceof ApiError && err.bizCode === UPLOAD_PREPARE_FALLBACK_CODE) {
|
|
120
|
+
throw new UploadDailyLimitExceededError(pathLabel, fileSize, err.message);
|
|
121
|
+
}
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async callUploadPartFinish(opts, uploadId, partIndex, blockSize, md5, retryTimeoutMs) {
|
|
126
|
+
const persistentPolicy = buildPartFinishPersistentPolicy(retryTimeoutMs);
|
|
127
|
+
const path = uploadPartFinishPath(opts.scope, opts.targetId);
|
|
128
|
+
await withRetry(async () => {
|
|
129
|
+
const token = await this.tokenManager.getAccessToken(opts.creds.appId, opts.creds.clientSecret);
|
|
130
|
+
return this.client.request(token, "POST", path, {
|
|
131
|
+
upload_id: uploadId,
|
|
132
|
+
part_index: partIndex,
|
|
133
|
+
block_size: blockSize,
|
|
134
|
+
md5,
|
|
135
|
+
}, { uploadRequest: true });
|
|
136
|
+
}, PART_FINISH_RETRY_POLICY, persistentPolicy, this.logger);
|
|
137
|
+
}
|
|
138
|
+
async callCompleteUpload(opts, uploadId) {
|
|
139
|
+
const path = uploadCompletePath(opts.scope, opts.targetId);
|
|
140
|
+
return withRetry(async () => {
|
|
141
|
+
const token = await this.tokenManager.getAccessToken(opts.creds.appId, opts.creds.clientSecret);
|
|
142
|
+
return this.client.request(token, "POST", path, { upload_id: uploadId }, { uploadRequest: true });
|
|
143
|
+
}, COMPLETE_UPLOAD_RETRY_POLICY, undefined, this.logger);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function resolveSource(source, fileNameOverride) {
|
|
147
|
+
if (source.kind === "localPath") {
|
|
148
|
+
const inferredName = source.path.split(/[/\\]/).pop() || "file";
|
|
149
|
+
return {
|
|
150
|
+
kind: "localPath",
|
|
151
|
+
path: source.path,
|
|
152
|
+
size: source.size,
|
|
153
|
+
fileName: fileNameOverride ?? inferredName,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
kind: "buffer",
|
|
158
|
+
buffer: source.buffer,
|
|
159
|
+
size: source.buffer.length,
|
|
160
|
+
fileName: fileNameOverride ?? source.fileName ?? "file",
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
async function readPart(input, offset, length) {
|
|
164
|
+
if (input.kind === "buffer") {
|
|
165
|
+
return input.buffer.subarray(offset, offset + length);
|
|
166
|
+
}
|
|
167
|
+
const handle = await fs.promises.open(input.path, "r");
|
|
168
|
+
try {
|
|
169
|
+
const buf = Buffer.alloc(length);
|
|
170
|
+
const { bytesRead } = await handle.read(buf, 0, length, offset);
|
|
171
|
+
return bytesRead < length ? buf.subarray(0, bytesRead) : buf;
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
await handle.close();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async function computeHashes(input) {
|
|
178
|
+
if (input.kind === "buffer") {
|
|
179
|
+
const md5 = crypto.createHash("md5").update(input.buffer).digest("hex");
|
|
180
|
+
const sha1 = crypto.createHash("sha1").update(input.buffer).digest("hex");
|
|
181
|
+
const md5_10m = input.size > MD5_10M_SIZE
|
|
182
|
+
? crypto.createHash("md5").update(input.buffer.subarray(0, MD5_10M_SIZE)).digest("hex")
|
|
183
|
+
: md5;
|
|
184
|
+
return { md5, sha1, md5_10m };
|
|
185
|
+
}
|
|
186
|
+
return new Promise((resolve, reject) => {
|
|
187
|
+
const md5 = crypto.createHash("md5");
|
|
188
|
+
const sha1 = crypto.createHash("sha1");
|
|
189
|
+
const md5_10m = crypto.createHash("md5");
|
|
190
|
+
let consumed = 0;
|
|
191
|
+
const needsMd5_10m = input.size > MD5_10M_SIZE;
|
|
192
|
+
const stream = fs.createReadStream(input.path);
|
|
193
|
+
stream.on("data", (chunk) => {
|
|
194
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
195
|
+
md5.update(buf);
|
|
196
|
+
sha1.update(buf);
|
|
197
|
+
if (needsMd5_10m) {
|
|
198
|
+
const remaining = MD5_10M_SIZE - consumed;
|
|
199
|
+
if (remaining > 0) {
|
|
200
|
+
md5_10m.update(remaining >= buf.length ? buf : buf.subarray(0, remaining));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
consumed += buf.length;
|
|
204
|
+
});
|
|
205
|
+
stream.on("end", () => {
|
|
206
|
+
const md5Hex = md5.digest("hex");
|
|
207
|
+
const sha1Hex = sha1.digest("hex");
|
|
208
|
+
resolve({
|
|
209
|
+
md5: md5Hex,
|
|
210
|
+
sha1: sha1Hex,
|
|
211
|
+
md5_10m: needsMd5_10m ? md5_10m.digest("hex") : md5Hex,
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
stream.on("error", reject);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
// ============ COS PUT ============
|
|
218
|
+
const PART_UPLOAD_MAX_RETRIES = 2;
|
|
219
|
+
/**
|
|
220
|
+
* PUT data to COS via raw https.request, bypassing fetch/undici.
|
|
221
|
+
* Used because Node.js fetch can fail unpredictably in long-running processes.
|
|
222
|
+
*/
|
|
223
|
+
function putToCOS(presignedUrl, data, signal) {
|
|
224
|
+
return new Promise((resolve, reject) => {
|
|
225
|
+
const parsed = new URL(presignedUrl);
|
|
226
|
+
const req = https.request(parsed, {
|
|
227
|
+
method: "PUT",
|
|
228
|
+
headers: { "Content-Length": String(data.length) },
|
|
229
|
+
signal,
|
|
230
|
+
}, (res) => {
|
|
231
|
+
const chunks = [];
|
|
232
|
+
res.on("data", (c) => chunks.push(c));
|
|
233
|
+
res.on("end", () => {
|
|
234
|
+
const etag = (res.headers.etag ?? "").replace(/"/g, "");
|
|
235
|
+
const requestId = res.headers["x-cos-request-id"]?.toString() ?? "-";
|
|
236
|
+
if (res.statusCode && res.statusCode >= 200 && res.statusCode < 300) {
|
|
237
|
+
resolve({ status: res.statusCode, etag, requestId });
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
reject(new Error(`COS PUT failed: ${res.statusCode} ${res.statusMessage ?? ""} - ${Buffer.concat(chunks).toString().slice(0, 120)}`));
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
res.on("error", reject);
|
|
244
|
+
});
|
|
245
|
+
req.on("error", (err) => {
|
|
246
|
+
// Suppress DOMException typings from AbortSignal error events
|
|
247
|
+
reject(err);
|
|
248
|
+
});
|
|
249
|
+
req.end(data);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async function putToPresignedUrl(presignedUrl, data, partIndex, totalParts, logger, prefix) {
|
|
253
|
+
let lastError = null;
|
|
254
|
+
for (let attempt = 0; attempt <= PART_UPLOAD_MAX_RETRIES; attempt++) {
|
|
255
|
+
const controller = new AbortController();
|
|
256
|
+
const timeoutId = setTimeout(() => controller.abort(), PART_UPLOAD_TIMEOUT_MS);
|
|
257
|
+
try {
|
|
258
|
+
const startTime = Date.now();
|
|
259
|
+
const { etag, requestId } = await putToCOS(presignedUrl, data, controller.signal);
|
|
260
|
+
const elapsed = Date.now() - startTime;
|
|
261
|
+
logger?.debug?.(`${prefix} PUT part ${partIndex}/${totalParts} OK (${elapsed}ms ETag=${etag} requestId=${requestId})`);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
catch (err) {
|
|
265
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
266
|
+
const code = err.code ?? "none";
|
|
267
|
+
const causeMsg = (() => {
|
|
268
|
+
const c = err instanceof Error ? err.cause : undefined;
|
|
269
|
+
return c instanceof Error ? c.message : "none";
|
|
270
|
+
})();
|
|
271
|
+
if (lastError.name === "AbortError") {
|
|
272
|
+
lastError = new Error(`Part ${partIndex}/${totalParts} upload timeout after ${PART_UPLOAD_TIMEOUT_MS}ms`);
|
|
273
|
+
}
|
|
274
|
+
if (attempt < PART_UPLOAD_MAX_RETRIES) {
|
|
275
|
+
const delay = 1000 * 2 ** attempt;
|
|
276
|
+
(logger?.warn ?? logger?.error)?.(`${prefix} PUT part ${partIndex}/${totalParts} attempt ${attempt + 1} failed (${lastError.message.slice(0, 120)} code=${code} cause=${causeMsg}), retrying in ${delay}ms`);
|
|
277
|
+
await sleep(delay);
|
|
278
|
+
}
|
|
279
|
+
else {
|
|
280
|
+
(logger?.error)?.(`${prefix} PUT part ${partIndex}/${totalParts} all retries exhausted (code=${code} cause=${causeMsg})`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
clearTimeout(timeoutId);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
throw lastError ?? new Error(`Part ${partIndex}/${totalParts} upload failed`);
|
|
288
|
+
}
|
|
289
|
+
async function runWithConcurrency(tasks, maxConcurrent) {
|
|
290
|
+
for (let i = 0; i < tasks.length; i += maxConcurrent) {
|
|
291
|
+
const batch = tasks.slice(i, i + maxConcurrent);
|
|
292
|
+
await Promise.all(batch.map((task) => task()));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function sleep(ms) {
|
|
296
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
297
|
+
}
|
|
298
|
+
//# sourceMappingURL=media-chunked.js.map
|