@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,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache `file_info` values returned by the QQ Bot API so identical uploads
|
|
3
|
+
* can be reused before the server-side TTL expires.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import * as crypto from "node:crypto";
|
|
7
|
+
import type { ChatScope, Logger } from "../types.js";
|
|
8
|
+
|
|
9
|
+
interface CacheEntry {
|
|
10
|
+
fileInfo: string;
|
|
11
|
+
fileUuid: string;
|
|
12
|
+
expiresAt: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const MAX_CACHE_SIZE = 500;
|
|
16
|
+
|
|
17
|
+
/** Compute an MD5 hash used as part of the cache key. */
|
|
18
|
+
export function computeFileHash(data: string | Buffer): string {
|
|
19
|
+
return crypto.createHash("md5").update(data).digest("hex");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function buildCacheKey(
|
|
23
|
+
contentHash: string,
|
|
24
|
+
scope: string,
|
|
25
|
+
targetId: string,
|
|
26
|
+
fileType: number,
|
|
27
|
+
): string {
|
|
28
|
+
return `${contentHash}:${scope}:${targetId}:${fileType}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* In-memory upload cache. Each {@link QQBot} instance owns its own
|
|
33
|
+
* cache so multiple concurrent bots do not compete for the same map.
|
|
34
|
+
*/
|
|
35
|
+
export class UploadCache {
|
|
36
|
+
private readonly cache = new Map<string, CacheEntry>();
|
|
37
|
+
private readonly logger?: Logger;
|
|
38
|
+
|
|
39
|
+
constructor(options?: { logger?: Logger }) {
|
|
40
|
+
this.logger = options?.logger;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
computeHash(data: string | Buffer): string {
|
|
44
|
+
return computeFileHash(data);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
get(contentHash: string, scope: ChatScope, targetId: string, fileType: number): string | null {
|
|
48
|
+
const key = buildCacheKey(contentHash, scope, targetId, fileType);
|
|
49
|
+
const entry = this.cache.get(key);
|
|
50
|
+
if (!entry) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
if (Date.now() >= entry.expiresAt) {
|
|
54
|
+
this.cache.delete(key);
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
this.logger?.debug?.(
|
|
58
|
+
`[upload-cache] HIT key=${key.slice(0, 40)}... uuid=${entry.fileUuid}`,
|
|
59
|
+
);
|
|
60
|
+
return entry.fileInfo;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
set(
|
|
64
|
+
contentHash: string,
|
|
65
|
+
scope: ChatScope,
|
|
66
|
+
targetId: string,
|
|
67
|
+
fileType: number,
|
|
68
|
+
fileInfo: string,
|
|
69
|
+
fileUuid: string,
|
|
70
|
+
ttl: number,
|
|
71
|
+
): void {
|
|
72
|
+
if (this.cache.size >= MAX_CACHE_SIZE) {
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
for (const [k, v] of this.cache) {
|
|
75
|
+
if (now >= v.expiresAt) {
|
|
76
|
+
this.cache.delete(k);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (this.cache.size >= MAX_CACHE_SIZE) {
|
|
80
|
+
const keys = Array.from(this.cache.keys());
|
|
81
|
+
for (let i = 0; i < keys.length / 2; i++) {
|
|
82
|
+
this.cache.delete(keys[i]);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const key = buildCacheKey(contentHash, scope, targetId, fileType);
|
|
87
|
+
const safetyMargin = 60;
|
|
88
|
+
const effectiveTtl = Math.max(ttl - safetyMargin, 10);
|
|
89
|
+
this.cache.set(key, {
|
|
90
|
+
fileInfo,
|
|
91
|
+
fileUuid,
|
|
92
|
+
expiresAt: Date.now() + effectiveTtl * 1000,
|
|
93
|
+
});
|
|
94
|
+
this.logger?.debug?.(
|
|
95
|
+
`[upload-cache] SET key=${key.slice(0, 40)}... ttl=${effectiveTtl}s uuid=${fileUuid}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
stats(): { size: number; maxSize: number } {
|
|
100
|
+
return { size: this.cache.size, maxSize: MAX_CACHE_SIZE };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
clear(): void {
|
|
104
|
+
this.cache.clear();
|
|
105
|
+
this.logger?.debug?.(`[upload-cache] cleared`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Voice transcript formatting for QQ Bot agent context.
|
|
3
|
+
*
|
|
4
|
+
* Pure string formatting — used to render STT-transcribed voice
|
|
5
|
+
* messages into the model's input.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Format voice transcripts into user-visible text. */
|
|
9
|
+
export function formatVoiceText(transcripts: string[]): string {
|
|
10
|
+
if (transcripts.length === 0) {
|
|
11
|
+
return "";
|
|
12
|
+
}
|
|
13
|
+
return transcripts.length === 1
|
|
14
|
+
? `[Voice message] ${transcripts[0]}`
|
|
15
|
+
: transcripts.map((t, i) => `[Voice ${i + 1}] ${t}`).join("\n");
|
|
16
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pluggable storage backends for the SDK.
|
|
3
|
+
*
|
|
4
|
+
* The SDK ships:
|
|
5
|
+
* - {@link MemoryKVStore} — in-memory (default for tests)
|
|
6
|
+
* - {@link FileKVStore} — JSON-file backed (single-process)
|
|
7
|
+
*
|
|
8
|
+
* Anything that implements {@link KVStore} can be plugged in:
|
|
9
|
+
* - Redis: `new RedisKVStore(redisClient)` (user-provided)
|
|
10
|
+
* - SQL: `new SqlKVStore(db)` (user-provided)
|
|
11
|
+
* - Cloud: `new D1KVStore(d1)` (user-provided)
|
|
12
|
+
*
|
|
13
|
+
* Use {@link kvSessionPersistence} to plug a KVStore into the gateway's
|
|
14
|
+
* session persistence slot. For ref-index storage, the SDK's existing
|
|
15
|
+
* {@link JsonlRefIndexStore} (in `protocol/utils/ref-index-store.js`) is
|
|
16
|
+
* still recommended for file-based deployments — but you can implement
|
|
17
|
+
* the same interface against any backend.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export { MemoryKVStore, FileKVStore } from "./kv-store.js";
|
|
21
|
+
export type { KVStore, FileKVStoreOptions } from "./kv-store.js";
|
|
22
|
+
|
|
23
|
+
export { kvSessionPersistence } from "./session-adapter.js";
|
|
24
|
+
export type { KVSessionPersistenceOptions } from "./session-adapter.js";
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic key-value store interface — used by built-in pluggable backends.
|
|
3
|
+
*
|
|
4
|
+
* The SDK ships:
|
|
5
|
+
* - {@link MemoryKVStore}: in-memory (default for tests / simple deployments)
|
|
6
|
+
* - {@link FileKVStore}: JSON-file backed (single-process, simple deployments)
|
|
7
|
+
*
|
|
8
|
+
* Users can plug in Redis / SQL / cloud KV by implementing this same
|
|
9
|
+
* interface. See `examples/storage-redis/` for a Redis adapter sketch.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
// ============ Interface ============
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Generic async KV store with optional TTL support.
|
|
19
|
+
*
|
|
20
|
+
* All methods may be sync or async; callers always `await` them.
|
|
21
|
+
*/
|
|
22
|
+
export interface KVStore {
|
|
23
|
+
/** Get a value. Returns `undefined` if missing or expired. */
|
|
24
|
+
get<T = unknown>(key: string): Promise<T | undefined> | T | undefined;
|
|
25
|
+
/** Set a value with optional TTL (milliseconds). */
|
|
26
|
+
set<T = unknown>(key: string, value: T, ttlMs?: number): Promise<void> | void;
|
|
27
|
+
/** Delete a value. Returns true if it existed. */
|
|
28
|
+
delete(key: string): Promise<boolean> | boolean;
|
|
29
|
+
/** Check key existence (cheaper than `get` on some backends). */
|
|
30
|
+
has?(key: string): Promise<boolean> | boolean;
|
|
31
|
+
/** Iterate keys matching a prefix. Optional. */
|
|
32
|
+
keys?(prefix?: string): Promise<string[]> | string[];
|
|
33
|
+
/** Clear all keys (or those matching a prefix). Optional. */
|
|
34
|
+
clear?(prefix?: string): Promise<void> | void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// ============ Memory ============
|
|
38
|
+
|
|
39
|
+
interface MemoryEntry {
|
|
40
|
+
value: unknown;
|
|
41
|
+
expireAt?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* In-memory KV store. Suitable for single-process deployments and tests.
|
|
46
|
+
*/
|
|
47
|
+
export class MemoryKVStore implements KVStore {
|
|
48
|
+
private readonly map = new Map<string, MemoryEntry>();
|
|
49
|
+
|
|
50
|
+
get<T = unknown>(key: string): T | undefined {
|
|
51
|
+
const entry = this.map.get(key);
|
|
52
|
+
if (!entry) return undefined;
|
|
53
|
+
if (entry.expireAt && entry.expireAt <= Date.now()) {
|
|
54
|
+
this.map.delete(key);
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
return entry.value as T;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
set<T = unknown>(key: string, value: T, ttlMs?: number): void {
|
|
61
|
+
this.map.set(key, {
|
|
62
|
+
value,
|
|
63
|
+
expireAt: ttlMs && ttlMs > 0 ? Date.now() + ttlMs : undefined,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
delete(key: string): boolean {
|
|
68
|
+
return this.map.delete(key);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
has(key: string): boolean {
|
|
72
|
+
const entry = this.map.get(key);
|
|
73
|
+
if (!entry) return false;
|
|
74
|
+
if (entry.expireAt && entry.expireAt <= Date.now()) {
|
|
75
|
+
this.map.delete(key);
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
keys(prefix?: string): string[] {
|
|
82
|
+
const all = [...this.map.keys()];
|
|
83
|
+
return prefix ? all.filter((k) => k.startsWith(prefix)) : all;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
clear(prefix?: string): void {
|
|
87
|
+
if (!prefix) {
|
|
88
|
+
this.map.clear();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
for (const k of this.map.keys()) {
|
|
92
|
+
if (k.startsWith(prefix)) this.map.delete(k);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Diagnostic: number of keys (incl. expired-but-not-yet-cleaned). */
|
|
97
|
+
size(): number {
|
|
98
|
+
return this.map.size;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ============ File-backed ============
|
|
103
|
+
|
|
104
|
+
export interface FileKVStoreOptions {
|
|
105
|
+
/** Directory holding the JSON file. */
|
|
106
|
+
dir: string;
|
|
107
|
+
/** File name. Defaults to `kv-store.json`. */
|
|
108
|
+
fileName?: string;
|
|
109
|
+
/** Save throttle window, ms. Defaults to 1000. */
|
|
110
|
+
saveThrottleMs?: number;
|
|
111
|
+
/** Optional logger. */
|
|
112
|
+
logger?: { error?: (msg: string) => void };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
interface FileEntry {
|
|
116
|
+
value: unknown;
|
|
117
|
+
expireAt?: number;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* JSON-file backed KV store.
|
|
122
|
+
*
|
|
123
|
+
* Loads on construct, throttles writes. Suitable for single-process bots
|
|
124
|
+
* with light persistence needs (e.g. session id, refIdx).
|
|
125
|
+
*
|
|
126
|
+
* Not safe for multi-process / multi-instance use — use a real KV
|
|
127
|
+
* (Redis, SQLite, ...) for that.
|
|
128
|
+
*/
|
|
129
|
+
export class FileKVStore implements KVStore {
|
|
130
|
+
private readonly map = new Map<string, FileEntry>();
|
|
131
|
+
private readonly filePath: string;
|
|
132
|
+
private readonly saveThrottleMs: number;
|
|
133
|
+
private saveTimer: ReturnType<typeof setTimeout> | null = null;
|
|
134
|
+
private dirty = false;
|
|
135
|
+
private readonly logger: NonNullable<FileKVStoreOptions["logger"]>;
|
|
136
|
+
|
|
137
|
+
constructor(opts: FileKVStoreOptions) {
|
|
138
|
+
this.filePath = path.join(opts.dir, opts.fileName ?? "kv-store.json");
|
|
139
|
+
this.saveThrottleMs = opts.saveThrottleMs ?? 1000;
|
|
140
|
+
this.logger = opts.logger ?? {};
|
|
141
|
+
this.load();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
get<T = unknown>(key: string): T | undefined {
|
|
145
|
+
const entry = this.map.get(key);
|
|
146
|
+
if (!entry) return undefined;
|
|
147
|
+
if (entry.expireAt && entry.expireAt <= Date.now()) {
|
|
148
|
+
this.map.delete(key);
|
|
149
|
+
this.scheduleSave();
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
return entry.value as T;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
set<T = unknown>(key: string, value: T, ttlMs?: number): void {
|
|
156
|
+
this.map.set(key, {
|
|
157
|
+
value,
|
|
158
|
+
expireAt: ttlMs && ttlMs > 0 ? Date.now() + ttlMs : undefined,
|
|
159
|
+
});
|
|
160
|
+
this.scheduleSave();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
delete(key: string): boolean {
|
|
164
|
+
const removed = this.map.delete(key);
|
|
165
|
+
if (removed) this.scheduleSave();
|
|
166
|
+
return removed;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
has(key: string): boolean {
|
|
170
|
+
return this.get(key) !== undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
keys(prefix?: string): string[] {
|
|
174
|
+
const all = [...this.map.keys()];
|
|
175
|
+
return prefix ? all.filter((k) => k.startsWith(prefix)) : all;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
clear(prefix?: string): void {
|
|
179
|
+
if (!prefix) {
|
|
180
|
+
this.map.clear();
|
|
181
|
+
} else {
|
|
182
|
+
for (const k of this.map.keys()) {
|
|
183
|
+
if (k.startsWith(prefix)) this.map.delete(k);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
this.scheduleSave();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Force flush pending writes. Call before process exit. */
|
|
190
|
+
flush(): void {
|
|
191
|
+
if (this.saveTimer) {
|
|
192
|
+
clearTimeout(this.saveTimer);
|
|
193
|
+
this.saveTimer = null;
|
|
194
|
+
}
|
|
195
|
+
if (this.dirty) {
|
|
196
|
+
this.doSave();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ============ Internal ============
|
|
201
|
+
|
|
202
|
+
private load(): void {
|
|
203
|
+
try {
|
|
204
|
+
if (!fs.existsSync(this.filePath)) return;
|
|
205
|
+
const raw = fs.readFileSync(this.filePath, "utf-8");
|
|
206
|
+
const data = JSON.parse(raw) as Record<string, FileEntry>;
|
|
207
|
+
const now = Date.now();
|
|
208
|
+
for (const [k, e] of Object.entries(data)) {
|
|
209
|
+
if (e.expireAt && e.expireAt <= now) continue;
|
|
210
|
+
this.map.set(k, e);
|
|
211
|
+
}
|
|
212
|
+
} catch (err) {
|
|
213
|
+
this.logger.error?.(
|
|
214
|
+
`[file-kv-store] load failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private scheduleSave(): void {
|
|
220
|
+
this.dirty = true;
|
|
221
|
+
if (this.saveTimer) return;
|
|
222
|
+
this.saveTimer = setTimeout(() => {
|
|
223
|
+
this.saveTimer = null;
|
|
224
|
+
this.doSave();
|
|
225
|
+
}, this.saveThrottleMs);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
private doSave(): void {
|
|
229
|
+
try {
|
|
230
|
+
fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
|
|
231
|
+
const obj: Record<string, FileEntry> = {};
|
|
232
|
+
for (const [k, e] of this.map) obj[k] = e;
|
|
233
|
+
const tmp = this.filePath + ".tmp";
|
|
234
|
+
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2), "utf-8");
|
|
235
|
+
fs.renameSync(tmp, this.filePath);
|
|
236
|
+
this.dirty = false;
|
|
237
|
+
} catch (err) {
|
|
238
|
+
this.logger.error?.(
|
|
239
|
+
`[file-kv-store] save failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge `KVStore` → `SessionPersistencePort`.
|
|
3
|
+
*
|
|
4
|
+
* Lets users plug any KV backend (Memory / File / Redis / ...) into the
|
|
5
|
+
* gateway session persistence slot via a single line:
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { QQBot, kvSessionPersistence, FileKVStore } from "@tencent-connect/qqbot-nodejs";
|
|
9
|
+
*
|
|
10
|
+
* const bot = new QQBot({
|
|
11
|
+
* appId, appSecret,
|
|
12
|
+
* sessionPersistence: kvSessionPersistence({
|
|
13
|
+
* store: new FileKVStore({ dir: "./data" }),
|
|
14
|
+
* accountId: "my-bot",
|
|
15
|
+
* }),
|
|
16
|
+
* });
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type {
|
|
21
|
+
PersistedSession,
|
|
22
|
+
SessionPersistencePort,
|
|
23
|
+
} from "../protocol/gateway/gateway-connection.js";
|
|
24
|
+
import type { KVStore } from "./kv-store.js";
|
|
25
|
+
|
|
26
|
+
export interface KVSessionPersistenceOptions {
|
|
27
|
+
/** Underlying KV store. */
|
|
28
|
+
store: KVStore;
|
|
29
|
+
/** Stable account id used as the storage key. */
|
|
30
|
+
accountId: string;
|
|
31
|
+
/** Optional key prefix. Defaults to `qqbot:session:`. */
|
|
32
|
+
prefix?: string;
|
|
33
|
+
/** Optional TTL for the entry, ms. Defaults to 5 min (matches QQ session expiry). */
|
|
34
|
+
ttlMs?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Build a {@link SessionPersistencePort} backed by any {@link KVStore}.
|
|
39
|
+
*/
|
|
40
|
+
export function kvSessionPersistence(opts: KVSessionPersistenceOptions): SessionPersistencePort {
|
|
41
|
+
const prefix = opts.prefix ?? "qqbot:session:";
|
|
42
|
+
const key = `${prefix}${opts.accountId}`;
|
|
43
|
+
const ttlMs = opts.ttlMs ?? 5 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
load() {
|
|
47
|
+
const v = opts.store.get<PersistedSession>(key);
|
|
48
|
+
// Note: KVStore.get may return Promise<>. The gateway port expects
|
|
49
|
+
// a sync result, so callers using async stores should await
|
|
50
|
+
// separately during startup (or use `awaitable` adapter, see TODO).
|
|
51
|
+
if (v && typeof (v as Promise<PersistedSession>).then === "function") {
|
|
52
|
+
// Async store — we can't synchronously resolve here; warn and
|
|
53
|
+
// return null. Users should provide a sync store or warm-up
|
|
54
|
+
// the session via `await kvWarmup(...)` before `bot.start()`.
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
return (v as PersistedSession) ?? null;
|
|
58
|
+
},
|
|
59
|
+
save(session) {
|
|
60
|
+
void opts.store.set(key, session, ttlMs);
|
|
61
|
+
},
|
|
62
|
+
clear() {
|
|
63
|
+
void opts.store.delete(key);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|