@tencent-connect/qqbot-nodejs 1.0.3 → 1.0.5

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/LICENSE +21 -0
  3. package/README.md +168 -85
  4. package/README.zh-CN.md +280 -0
  5. package/USAGE.md +87 -32
  6. package/dist/QQBot.d.ts +33 -3
  7. package/dist/QQBot.d.ts.map +1 -1
  8. package/dist/QQBot.js +84 -34
  9. package/dist/QQBot.js.map +1 -1
  10. package/dist/index.d.ts +3 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +2 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/protocol/api/token.d.ts.map +1 -1
  15. package/dist/protocol/api/token.js +29 -9
  16. package/dist/protocol/api/token.js.map +1 -1
  17. package/dist/protocol/gateway/constants.d.ts +6 -1
  18. package/dist/protocol/gateway/constants.d.ts.map +1 -1
  19. package/dist/protocol/gateway/constants.js +6 -1
  20. package/dist/protocol/gateway/constants.js.map +1 -1
  21. package/dist/protocol/gateway/errors.d.ts +22 -0
  22. package/dist/protocol/gateway/errors.d.ts.map +1 -0
  23. package/dist/protocol/gateway/errors.js +24 -0
  24. package/dist/protocol/gateway/errors.js.map +1 -0
  25. package/dist/protocol/gateway/gateway-connection.d.ts +45 -4
  26. package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
  27. package/dist/protocol/gateway/gateway-connection.js +252 -143
  28. package/dist/protocol/gateway/gateway-connection.js.map +1 -1
  29. package/dist/protocol/gateway/reconnect.d.ts +24 -1
  30. package/dist/protocol/gateway/reconnect.d.ts.map +1 -1
  31. package/dist/protocol/gateway/reconnect.js +42 -6
  32. package/dist/protocol/gateway/reconnect.js.map +1 -1
  33. package/dist/protocol/index.d.ts +4 -3
  34. package/dist/protocol/index.d.ts.map +1 -1
  35. package/dist/protocol/index.js +3 -2
  36. package/dist/protocol/index.js.map +1 -1
  37. package/dist/protocol/utils/file-utils.d.ts +2 -2
  38. package/dist/protocol/utils/file-utils.js +2 -2
  39. package/dist/protocol/utils/image-size.d.ts +3 -3
  40. package/dist/protocol/utils/image-size.js +3 -3
  41. package/dist/protocol/utils/ref-index-store.d.ts +1 -1
  42. package/dist/protocol/utils/ref-index-store.js +1 -1
  43. package/package.json +23 -7
  44. package/src/QQBot.ts +93 -37
  45. package/src/index.ts +5 -0
  46. package/src/protocol/api/token.ts +34 -9
  47. package/src/protocol/gateway/constants.ts +6 -1
  48. package/src/protocol/gateway/errors.ts +32 -0
  49. package/src/protocol/gateway/gateway-connection.ts +288 -157
  50. package/src/protocol/gateway/reconnect.ts +61 -7
  51. package/src/protocol/index.ts +10 -1
  52. package/src/protocol/utils/file-utils.ts +2 -2
  53. package/src/protocol/utils/image-size.ts +3 -3
  54. package/src/protocol/utils/ref-index-store.ts +1 -1
@@ -10,6 +10,8 @@ import { formatErrorMessage } from "../utils/format.js";
10
10
 
11
11
  const DEFAULT_TOKEN_BASE_URL = "https://bots.qq.com";
12
12
  const TOKEN_PATH = "/app/getAppAccessToken";
13
+ const DEFAULT_TOKEN_TIMEOUT_MS = 10_000;
14
+ const FIVE_MINUTES_MS = 5 * 60 * 1000;
13
15
 
14
16
  interface CachedToken {
15
17
  token: string;
@@ -44,7 +46,7 @@ export class TokenManager {
44
46
  const cached = this.cache.get(normalizedId);
45
47
 
46
48
  const refreshAheadMs = cached
47
- ? Math.min(5 * 60 * 1000, (cached.expiresAt - Date.now()) / 3)
49
+ ? Math.min(FIVE_MINUTES_MS, (cached.expiresAt - Date.now()) / 3)
48
50
  : 0;
49
51
 
50
52
  if (cached && Date.now() < cached.expiresAt - refreshAheadMs) {
@@ -91,7 +93,7 @@ export class TokenManager {
91
93
  return { status: "none", expiresAt: null };
92
94
  }
93
95
  const remaining = cached.expiresAt - Date.now();
94
- const isValid = remaining > Math.min(5 * 60 * 1000, remaining / 3);
96
+ const isValid = remaining > Math.min(FIVE_MINUTES_MS, remaining / 3);
95
97
  return { status: isValid ? "valid" : "expired", expiresAt: cached.expiresAt };
96
98
  }
97
99
 
@@ -149,13 +151,21 @@ export class TokenManager {
149
151
  }
150
152
  }
151
153
 
152
- this.refreshControllers.delete(appId);
154
+ // Only release the slot we own: a stop→start cycle may already have
155
+ // registered a replacement loop for the same appId.
156
+ if (this.refreshControllers.get(appId) === controller) {
157
+ this.refreshControllers.delete(appId);
158
+ }
153
159
  this.logger?.info?.(`[qqbot:token:${appId}] Background refresh stopped`);
154
160
  };
155
161
 
156
162
  loop().catch((err) => {
157
- this.refreshControllers.delete(appId);
158
- this.logger?.error?.(`[qqbot:token:${appId}] Background refresh crashed: ${err}`);
163
+ if (this.refreshControllers.get(appId) === controller) {
164
+ this.refreshControllers.delete(appId);
165
+ this.logger?.error?.(
166
+ `[qqbot:token:${appId}] Background refresh crashed: ${formatErrorMessage(err)}`,
167
+ );
168
+ }
159
169
  });
160
170
  }
161
171
 
@@ -185,6 +195,9 @@ export class TokenManager {
185
195
  const url = `${this.baseUrl}${TOKEN_PATH}`;
186
196
  this.logger?.debug?.(`[qqbot:token:${appId}] >>> POST ${url}`);
187
197
 
198
+ const controller = new AbortController();
199
+ const timeout = setTimeout(() => controller.abort(), DEFAULT_TOKEN_TIMEOUT_MS);
200
+
188
201
  let response: Response;
189
202
  try {
190
203
  response = await fetch(url, {
@@ -194,12 +207,15 @@ export class TokenManager {
194
207
  "User-Agent": this.resolveUserAgent(),
195
208
  },
196
209
  body: JSON.stringify({ appId, clientSecret }),
210
+ signal: controller.signal,
197
211
  });
198
212
  } catch (err) {
199
213
  this.logger?.error?.(`[qqbot:token:${appId}] Network error: ${formatErrorMessage(err)}`);
200
214
  throw new Error(`Network error getting access_token: ${formatErrorMessage(err)}`, {
201
215
  cause: err,
202
216
  });
217
+ } finally {
218
+ clearTimeout(timeout);
203
219
  }
204
220
 
205
221
  const traceId = response.headers.get("x-tps-trace-id") ?? "";
@@ -207,6 +223,13 @@ export class TokenManager {
207
223
  `[qqbot:token:${appId}] <<< ${response.status}${traceId ? ` | TraceId: ${traceId}` : ""}`,
208
224
  );
209
225
 
226
+ if (!response.ok) {
227
+ const errorBody = await response.text().catch(() => "");
228
+ throw new Error(
229
+ `Token fetch failed: HTTP ${response.status}${errorBody ? ` — ${errorBody.slice(0, 200)}` : ""}`,
230
+ );
231
+ }
232
+
210
233
  let data: { access_token?: string; expires_in?: number };
211
234
  try {
212
235
  const rawBody = await response.text();
@@ -234,15 +257,17 @@ export class TokenManager {
234
257
 
235
258
  private abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
236
259
  return new Promise((resolve, reject) => {
237
- const timer = setTimeout(resolve, ms);
238
260
  if (signal.aborted) {
239
- clearTimeout(timer);
240
- reject(new Error("Aborted"));
261
+ reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
241
262
  return;
242
263
  }
264
+ const timer = setTimeout(() => {
265
+ signal.removeEventListener("abort", onAbort);
266
+ resolve();
267
+ }, ms);
243
268
  const onAbort = () => {
244
269
  clearTimeout(timer);
245
- reject(new Error("Aborted"));
270
+ reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
246
271
  };
247
272
  signal.addEventListener("abort", onAbort, { once: true });
248
273
  });
@@ -25,9 +25,14 @@ export const FULL_INTENTS =
25
25
 
26
26
  export const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000] as const;
27
27
  export const RATE_LIMIT_DELAY = 60000;
28
- export const MAX_RECONNECT_ATTEMPTS = 100;
28
+ /** Default reconnect budget: unlimited. Set `reconnect.maxAttempts` to bound it. */
29
+ export const MAX_RECONNECT_ATTEMPTS = Number.POSITIVE_INFINITY;
29
30
  export const MAX_QUICK_DISCONNECT_COUNT = 3;
30
31
  export const QUICK_DISCONNECT_THRESHOLD = 5000;
32
+ /** Delay before reconnecting after opcode 9 (INVALID_SESSION). */
33
+ export const INVALID_SESSION_DELAY = 3000;
34
+ /** Default WebSocket upgrade timeout; bounds black-holed handshakes. */
35
+ export const HANDSHAKE_TIMEOUT_MS = 30_000;
31
36
 
32
37
  /** Gateway opcodes used by the QQ Bot WebSocket protocol. */
33
38
  export const GatewayOp = {
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Terminal gateway errors — the reasons a {@link GatewayConnection} stops
3
+ * retrying and rejects its `start()` promise.
4
+ */
5
+
6
+ /** Stable error codes. Match on `code` rather than `instanceof` across module copies. */
7
+ export const GatewayErrorCode = {
8
+ /** A finite `reconnect.maxAttempts` was exhausted (never raised with the unlimited default). */
9
+ RETRY_EXHAUSTED: "GATEWAY_RETRY_EXHAUSTED",
10
+ /** Non-retryable close (4914 offline/sandbox-only, 4915 banned). Needs operator action. */
11
+ FATAL_CLOSE: "GATEWAY_FATAL_CLOSE",
12
+ } as const;
13
+ export type GatewayErrorCode = (typeof GatewayErrorCode)[keyof typeof GatewayErrorCode];
14
+
15
+ /** Error used to reject `GatewayConnection.start()` / `QQBot.start()`. */
16
+ export class GatewayError extends Error {
17
+ readonly code: GatewayErrorCode;
18
+ /** Remote WebSocket close code that caused the failure, when known. */
19
+ readonly closeCode?: number;
20
+
21
+ constructor(
22
+ message: string,
23
+ code: GatewayErrorCode,
24
+ closeCode?: number,
25
+ options?: { cause?: unknown },
26
+ ) {
27
+ super(message, options);
28
+ this.name = "GatewayError";
29
+ this.code = code;
30
+ this.closeCode = closeCode;
31
+ }
32
+ }