@im-more/dsh-kook 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/cordis.patch.yml +12 -0
- package/lib/index.js +2380 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +53 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +138 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +46 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +52 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +88 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +564 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +46 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +159 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +17 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +24 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +15 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +15 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/kmarkdown.d.ts +76 -0
- package/lib/types/kmarkdown.d.ts.map +1 -0
- package/lib/types/kmarkdown.js +201 -0
- package/lib/types/kmarkdown.js.map +1 -0
- package/lib/types/modes/kmarkdown.d.ts +17 -0
- package/lib/types/modes/kmarkdown.d.ts.map +1 -0
- package/lib/types/modes/kmarkdown.js +166 -0
- package/lib/types/modes/kmarkdown.js.map +1 -0
- package/lib/types/modes/shared.d.ts +192 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +371 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +53 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +147 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +57 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +141 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/types.d.ts +807 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +168 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/webhook.d.ts +35 -0
- package/lib/types/webhook.d.ts.map +1 -0
- package/lib/types/webhook.js +132 -0
- package/lib/types/webhook.js.map +1 -0
- package/lib/types/ws.d.ts +54 -0
- package/lib/types/ws.d.ts.map +1 -0
- package/lib/types/ws.js +358 -0
- package/lib/types/ws.js.map +1 -0
- package/package.json +61 -3
- package/src/bot.ts +217 -0
- package/src/config.ts +84 -0
- package/src/decode.ts +660 -0
- package/src/errors.ts +188 -0
- package/src/identity.ts +32 -0
- package/src/index.ts +80 -0
- package/src/kmarkdown.ts +246 -0
- package/src/modes/kmarkdown.ts +204 -0
- package/src/modes/shared.ts +498 -0
- package/src/request.ts +196 -0
- package/src/send.ts +216 -0
- package/src/types.ts +764 -0
- package/src/webhook.ts +170 -0
- package/src/ws.ts +431 -0
- package/README.md +0 -3
package/src/webhook.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webhook transport (`protocol: 'http'`).
|
|
3
|
+
*
|
|
4
|
+
* The profile's `webServer` owns the listener, so this transport only registers one anonymous route at `path` and
|
|
5
|
+
* checks every request itself: `verify_token` must match the platform-issued token, and the challenge handshake is
|
|
6
|
+
* answered within the one second KOOK allows.
|
|
7
|
+
*
|
|
8
|
+
* The platform is confirmed only after `bot.receive` accepted the frame; a failure answers `500`, which makes KOOK
|
|
9
|
+
* redeliver (2/4/8/16/32/64 s, at most five times). The cost is that a slow intake occasionally exceeds the one-second
|
|
10
|
+
* challenge budget and triggers a redelivery, which the host de-duplicates on `msg_id`.
|
|
11
|
+
*
|
|
12
|
+
* KOOK only configures callbacks in the developer console, so there is nothing to register with the platform here and
|
|
13
|
+
* no `publicUrl` option; the operator must append `?compress=0` to the callback URL because v1 does not decompress
|
|
14
|
+
* bodies.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
18
|
+
import type { KookBot } from './bot.ts'
|
|
19
|
+
import { routePath } from './config.ts'
|
|
20
|
+
import { decodeEvent } from './decode.ts'
|
|
21
|
+
|
|
22
|
+
/** The part of `ctx.webServer` this adapter uses. */
|
|
23
|
+
interface WebServerLike {
|
|
24
|
+
register(route: {
|
|
25
|
+
kind: 'exact'
|
|
26
|
+
path: string
|
|
27
|
+
auth: 'anonymous'
|
|
28
|
+
handler: (
|
|
29
|
+
request: IncomingMessage,
|
|
30
|
+
response: ServerResponse,
|
|
31
|
+
) => void | Promise<void>
|
|
32
|
+
}): () => void
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One JSON object of an inbound body. */
|
|
36
|
+
type Dict = Record<string, unknown>
|
|
37
|
+
|
|
38
|
+
function asRecord(value: unknown): Dict | undefined {
|
|
39
|
+
return typeof value === 'object' && value !== null
|
|
40
|
+
? (value as Dict)
|
|
41
|
+
: undefined
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function asString(value: unknown): string | undefined {
|
|
45
|
+
return typeof value === 'string' ? value : undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not. */
|
|
49
|
+
async function readBody(request: IncomingMessage): Promise<string> {
|
|
50
|
+
const chunks: Buffer[] = []
|
|
51
|
+
for await (const chunk of request) {
|
|
52
|
+
chunks.push(
|
|
53
|
+
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array),
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Answer one request without a body. */
|
|
60
|
+
function writeStatus(
|
|
61
|
+
response: ServerResponse,
|
|
62
|
+
status: number,
|
|
63
|
+
headers: Record<string, string> = {},
|
|
64
|
+
): void {
|
|
65
|
+
response.writeHead(status, headers)
|
|
66
|
+
response.end()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Message of any caught value, for a log line. */
|
|
70
|
+
function messageOf(error: unknown): string {
|
|
71
|
+
return error instanceof Error ? error.message : String(error)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The Webhook transport of one bot. */
|
|
75
|
+
export class KookWebhook {
|
|
76
|
+
private dispose: (() => void) | undefined
|
|
77
|
+
|
|
78
|
+
constructor(private readonly bot: KookBot) {}
|
|
79
|
+
|
|
80
|
+
/** Register the route; a profile without a web server fails with an actionable message. */
|
|
81
|
+
async start(): Promise<void> {
|
|
82
|
+
const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
|
|
83
|
+
if (webServer === undefined) {
|
|
84
|
+
throw this.failStart(
|
|
85
|
+
'kook: protocol "http" needs a profile-provided webServer; use protocol "ws" instead',
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
this.dispose = webServer.register({
|
|
89
|
+
kind: 'exact',
|
|
90
|
+
path: routePath(this.bot.config.path),
|
|
91
|
+
auth: 'anonymous',
|
|
92
|
+
handler: (request, response) => this.handle(request, response),
|
|
93
|
+
})
|
|
94
|
+
// A webhook bot is online as soon as its callback URL is configured on the platform; there is no HELLO.
|
|
95
|
+
this.bot.online()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Release the route. The platform keeps posting to it until the console's callback URL changes. */
|
|
99
|
+
async stop(): Promise<void> {
|
|
100
|
+
this.dispose?.()
|
|
101
|
+
this.dispose = undefined
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Log a fatal start failure before the caller throws it, because `Bot.start` only stores a connect failure on
|
|
106
|
+
* `bot.error`.
|
|
107
|
+
* @param message - error text that also names the corrective action.
|
|
108
|
+
* @returns the error for the caller to throw.
|
|
109
|
+
*/
|
|
110
|
+
private failStart(message: string): Error {
|
|
111
|
+
this.bot.ctx.logger.error(message)
|
|
112
|
+
return new Error(message)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private async handle(
|
|
116
|
+
request: IncomingMessage,
|
|
117
|
+
response: ServerResponse,
|
|
118
|
+
): Promise<void> {
|
|
119
|
+
try {
|
|
120
|
+
if (request.method !== 'POST') {
|
|
121
|
+
writeStatus(response, 405, { allow: 'POST' })
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
const body = await readBody(request)
|
|
125
|
+
// The platform's JSON is untyped wire data; the fields this handler reads are narrowed one by one below.
|
|
126
|
+
let parsed: any
|
|
127
|
+
try {
|
|
128
|
+
parsed = JSON.parse(body)
|
|
129
|
+
} catch (error) {
|
|
130
|
+
// A compressed body (the callback URL without `?compress=0`) lands here; the status is the diagnosis.
|
|
131
|
+
this.bot.ctx.logger.warn(
|
|
132
|
+
'kook: cannot parse a webhook body: %s',
|
|
133
|
+
messageOf(error),
|
|
134
|
+
)
|
|
135
|
+
writeStatus(response, 400)
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
const frame = asRecord(parsed)
|
|
139
|
+
const data = asRecord(frame?.d)
|
|
140
|
+
if (frame === undefined || data === undefined) {
|
|
141
|
+
writeStatus(response, 400)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
const verifyToken = asString(data.verify_token)
|
|
145
|
+
if (verifyToken !== this.bot.config.verifyToken) {
|
|
146
|
+
writeStatus(response, 403)
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
const challenge = asString(data.challenge)
|
|
150
|
+
if (challenge !== undefined && challenge !== '') {
|
|
151
|
+
// The platform's one-time handshake: answer in under a second with the same string.
|
|
152
|
+
response.writeHead(200, { 'content-type': 'application/json' })
|
|
153
|
+
response.end(JSON.stringify({ challenge }))
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
// `data` is the same object narrowed field by field; the decoder takes the untyped payload whole.
|
|
157
|
+
const rawData: any = frame.d
|
|
158
|
+
const session = decodeEvent(this.bot, rawData)
|
|
159
|
+
if (session !== undefined) await this.bot.receive(session)
|
|
160
|
+
writeStatus(response, 200)
|
|
161
|
+
} catch (error) {
|
|
162
|
+
this.bot.ctx.logger.warn(
|
|
163
|
+
'kook: webhook delivery failed: %s',
|
|
164
|
+
messageOf(error),
|
|
165
|
+
)
|
|
166
|
+
if (!response.headersSent) writeStatus(response, 500)
|
|
167
|
+
else response.end()
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
package/src/ws.ts
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gateway WebSocket transport (`protocol: 'ws'`).
|
|
3
|
+
*
|
|
4
|
+
* The adapter fetches `/gateway/index?compress=0` before **every** dial (KOOK hands out a fresh gateway URL), dials it
|
|
5
|
+
* with the `http` service and keeps dialing forever: `ws.retryTimes` is a fast-retry budget, not a give-up count.
|
|
6
|
+
* Resume is not implemented — the platform would replay the offline window only for a client that keeps its session,
|
|
7
|
+
* and the upstream adapter never did — so a dropped connection loses the events it missed and the bot says so in its
|
|
8
|
+
* logs.
|
|
9
|
+
*
|
|
10
|
+
* The `sn` heartbeat confirmation is the platform's ACK: the `sn` a PING carries is the last message `bot.receive`
|
|
11
|
+
* accepted, so a receive that fails leaves the event unconfirmed and the platform retransmits it on the next heartbeat.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { Status } from '@deepseek-ai/cordis-plugin-im-core'
|
|
15
|
+
import type {} from '@deepseek-ai/cordis-plugin-http'
|
|
16
|
+
import type { KookBot } from './bot.ts'
|
|
17
|
+
import { decodeEvent } from './decode.ts'
|
|
18
|
+
import { isPermanentHelloCode, isResumeCode } from './errors.ts'
|
|
19
|
+
import { invoke } from './request.ts'
|
|
20
|
+
import { Signal } from './types.ts'
|
|
21
|
+
import type { Data } from './types.ts'
|
|
22
|
+
|
|
23
|
+
/** The platform requires HELLO within 6 s of the connection opening. */
|
|
24
|
+
const HELLO_TIMEOUT = 6_000
|
|
25
|
+
/** The platform requires PONG within 6 s of a PING. */
|
|
26
|
+
const PONG_TIMEOUT = 6_000
|
|
27
|
+
/** Heartbeat interval, 30 s plus a random ±5 s as the platform asks. */
|
|
28
|
+
const HEARTBEAT_BASE = 30_000
|
|
29
|
+
const HEARTBEAT_JITTER = 5_000
|
|
30
|
+
|
|
31
|
+
/** One received frame. `d` is untyped wire JSON: its shape depends on `s`. */
|
|
32
|
+
interface Frame {
|
|
33
|
+
s?: number
|
|
34
|
+
sn?: number
|
|
35
|
+
// The signalled payload is wire JSON; the decoder validates the fields it reads.
|
|
36
|
+
d?: any
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The WebSocket the `http` service opens (Node's global `WebSocket`). */
|
|
40
|
+
type KookSocket = ReturnType<KookBot['ctx']['http']['ws']>
|
|
41
|
+
|
|
42
|
+
/** Waitable sleep that resolves early on abort. */
|
|
43
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
if (signal.aborted) {
|
|
46
|
+
resolve()
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
const timer = setTimeout(() => {
|
|
50
|
+
signal.removeEventListener('abort', onAbort)
|
|
51
|
+
resolve()
|
|
52
|
+
}, ms)
|
|
53
|
+
const onAbort = (): void => {
|
|
54
|
+
clearTimeout(timer)
|
|
55
|
+
resolve()
|
|
56
|
+
}
|
|
57
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Text of one WebSocket frame. */
|
|
62
|
+
function frameText(data: unknown): string {
|
|
63
|
+
return typeof data === 'string' ? data : String(data)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One JSON field of one frame, when it is an object. */
|
|
67
|
+
function recordOf(value: unknown): Record<string, unknown> | undefined {
|
|
68
|
+
return typeof value === 'object' && value !== null
|
|
69
|
+
? (value as Record<string, unknown>)
|
|
70
|
+
: undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One number field of one frame. */
|
|
74
|
+
function numberOf(value: unknown): number | undefined {
|
|
75
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The platform refused the connection for a reason only a corrected configuration can fix. */
|
|
79
|
+
class KookGatewayFatalError extends Error {
|
|
80
|
+
constructor(message: string) {
|
|
81
|
+
super(message)
|
|
82
|
+
this.name = 'KookGatewayFatalError'
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The Gateway client of one bot.
|
|
88
|
+
*
|
|
89
|
+
* `start()` returns after starting the reconnect loop, never after the first HELLO: `Bot.start` awaits `connect()`,
|
|
90
|
+
* and holding plugin initialization open until KOOK is reachable would block the whole profile.
|
|
91
|
+
*/
|
|
92
|
+
export class KookWsTransport {
|
|
93
|
+
private controller: AbortController | undefined
|
|
94
|
+
private running: Promise<void> | undefined
|
|
95
|
+
private socket: KookSocket | undefined
|
|
96
|
+
private heartbeatTimer: ReturnType<typeof setTimeout> | undefined
|
|
97
|
+
private pongTimer: ReturnType<typeof setTimeout> | undefined
|
|
98
|
+
|
|
99
|
+
constructor(private readonly bot: KookBot) {}
|
|
100
|
+
|
|
101
|
+
/** Start the reconnect loop. */
|
|
102
|
+
async start(): Promise<void> {
|
|
103
|
+
this.controller = new AbortController()
|
|
104
|
+
this.running = this.loop(this.controller.signal)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Stop the loop and wait for it to unwind. */
|
|
108
|
+
async stop(): Promise<void> {
|
|
109
|
+
this.controller?.abort()
|
|
110
|
+
this.controller = undefined
|
|
111
|
+
this.closeSocket()
|
|
112
|
+
await this.running?.catch(() => undefined)
|
|
113
|
+
this.running = undefined
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Delay before the next dial: the fast interval while the failure budget lasts, the lazy one after it. */
|
|
117
|
+
private intervalOf(failures: number): number {
|
|
118
|
+
const { ws } = this.bot.config
|
|
119
|
+
return failures < ws.retryTimes ? ws.retryInterval : ws.retryLazy
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private async loop(signal: AbortSignal): Promise<void> {
|
|
123
|
+
let failures = 0
|
|
124
|
+
while (!signal.aborted) {
|
|
125
|
+
try {
|
|
126
|
+
const socket = await this.open(signal)
|
|
127
|
+
const greeted = await this.accept(socket, signal)
|
|
128
|
+
if (signal.aborted) return
|
|
129
|
+
// A connection that greeted once proves the token works, so the next dial goes out at the fast interval.
|
|
130
|
+
failures = greeted ? 0 : failures + 1
|
|
131
|
+
this.bot.ctx.logger.warn(
|
|
132
|
+
'kook: the gateway connection closed; reconnecting',
|
|
133
|
+
)
|
|
134
|
+
this.bot.status = Status.RECONNECT
|
|
135
|
+
await sleep(this.intervalOf(failures), signal)
|
|
136
|
+
} catch (error) {
|
|
137
|
+
if (signal.aborted) return
|
|
138
|
+
if (error instanceof KookGatewayFatalError) {
|
|
139
|
+
// A rejected token cannot be fixed by reconnecting: report it and stop until the profile is edited.
|
|
140
|
+
this.bot.ctx.logger.error(error.message)
|
|
141
|
+
this.bot.offline(error)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
failures += 1
|
|
145
|
+
this.bot.ctx.logger.warn('kook: %s; reconnecting', messageOf(error))
|
|
146
|
+
this.bot.status = Status.RECONNECT
|
|
147
|
+
await sleep(this.intervalOf(failures), signal)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Fetch a fresh gateway URL and dial it, resolving once the socket opens. */
|
|
153
|
+
private async open(signal: AbortSignal): Promise<KookSocket> {
|
|
154
|
+
const gateway = await invoke<{ url?: string }>(
|
|
155
|
+
this.bot.request,
|
|
156
|
+
'GET',
|
|
157
|
+
'/gateway/index',
|
|
158
|
+
{ compress: 0 },
|
|
159
|
+
signal,
|
|
160
|
+
)
|
|
161
|
+
const url = gateway?.url
|
|
162
|
+
if (url === undefined || url === '') {
|
|
163
|
+
throw new Error('kook: /gateway/index answered without a url')
|
|
164
|
+
}
|
|
165
|
+
return await this.dial(url, signal)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Dial one gateway URL and resolve once the socket is open. */
|
|
169
|
+
private dial(url: string, signal: AbortSignal): Promise<KookSocket> {
|
|
170
|
+
const socket = this.bot.ctx.http.ws(url, {
|
|
171
|
+
headers: { authorization: `Bot ${this.bot.config.token}` },
|
|
172
|
+
})
|
|
173
|
+
return new Promise<KookSocket>((resolve, reject) => {
|
|
174
|
+
const cleanup = (): void => {
|
|
175
|
+
socket.removeEventListener('open', onOpen)
|
|
176
|
+
socket.removeEventListener('error', onError)
|
|
177
|
+
socket.removeEventListener('close', onClose)
|
|
178
|
+
signal.removeEventListener('abort', onAbort)
|
|
179
|
+
}
|
|
180
|
+
const onOpen = (): void => {
|
|
181
|
+
cleanup()
|
|
182
|
+
resolve(socket)
|
|
183
|
+
}
|
|
184
|
+
const onError = (event: { message?: string }): void => {
|
|
185
|
+
cleanup()
|
|
186
|
+
reject(
|
|
187
|
+
new Error(
|
|
188
|
+
`kook: WebSocket error${event.message === undefined ? '' : `: ${event.message}`}`,
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
const onClose = (event: { code: number }): void => {
|
|
193
|
+
cleanup()
|
|
194
|
+
reject(
|
|
195
|
+
new Error(
|
|
196
|
+
`kook: WebSocket closed before opening (code ${event.code})`,
|
|
197
|
+
),
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
const onAbort = (): void => {
|
|
201
|
+
cleanup()
|
|
202
|
+
reject(signal.reason ?? new Error('kook: adapter stopped'))
|
|
203
|
+
}
|
|
204
|
+
if (signal.aborted) {
|
|
205
|
+
onAbort()
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
socket.addEventListener('open', onOpen)
|
|
209
|
+
socket.addEventListener('error', onError)
|
|
210
|
+
socket.addEventListener('close', onClose)
|
|
211
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Serve one open connection until it closes.
|
|
217
|
+
* @param socket - the open socket.
|
|
218
|
+
* @param signal - cancellation of the loop.
|
|
219
|
+
* @returns whether HELLO arrived, i.e. whether the connection ever worked.
|
|
220
|
+
*/
|
|
221
|
+
private async accept(
|
|
222
|
+
socket: KookSocket,
|
|
223
|
+
signal: AbortSignal,
|
|
224
|
+
): Promise<boolean> {
|
|
225
|
+
this.socket = socket
|
|
226
|
+
let greeted = false
|
|
227
|
+
let sn = 0
|
|
228
|
+
// Events are received one at a time so `sn` only advances past a message whose `bot.receive` resolved.
|
|
229
|
+
let queue: Promise<void> = Promise.resolve()
|
|
230
|
+
|
|
231
|
+
// HELLO settles through one of: the frame, the connection closing, the deadline, or the loop stopping.
|
|
232
|
+
let helloCode: number | undefined
|
|
233
|
+
let helloDone = false
|
|
234
|
+
let settleHello: (() => void) | undefined
|
|
235
|
+
const hello = new Promise<void>((resolve) => {
|
|
236
|
+
settleHello = resolve
|
|
237
|
+
})
|
|
238
|
+
const settle = (code: number | undefined): void => {
|
|
239
|
+
if (helloDone) return
|
|
240
|
+
helloDone = true
|
|
241
|
+
helloCode = code
|
|
242
|
+
settleHello?.()
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const closed = new Promise<void>((resolve) => {
|
|
246
|
+
socket.addEventListener('close', () => {
|
|
247
|
+
settle(undefined)
|
|
248
|
+
resolve()
|
|
249
|
+
})
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
socket.addEventListener('message', (event) => {
|
|
253
|
+
let parsed: Frame
|
|
254
|
+
try {
|
|
255
|
+
parsed = JSON.parse(frameText(event.data)) as Frame
|
|
256
|
+
} catch (error) {
|
|
257
|
+
this.bot.ctx.logger.warn(
|
|
258
|
+
'kook: cannot parse a gateway frame: %s',
|
|
259
|
+
messageOf(error),
|
|
260
|
+
)
|
|
261
|
+
return
|
|
262
|
+
}
|
|
263
|
+
switch (parsed.s) {
|
|
264
|
+
case Signal.event: {
|
|
265
|
+
queue = queue.then(async () => {
|
|
266
|
+
try {
|
|
267
|
+
const session = decodeEvent(this.bot, parsed.d as Data)
|
|
268
|
+
if (session !== undefined) await this.bot.receive(session)
|
|
269
|
+
const frameSn = numberOf(parsed.sn)
|
|
270
|
+
if (frameSn !== undefined) sn = Math.max(sn, frameSn)
|
|
271
|
+
} catch (error) {
|
|
272
|
+
// The heartbeat's `sn` still points at the previous message, so the platform retransmits this one.
|
|
273
|
+
this.bot.ctx.logger.error(
|
|
274
|
+
'kook: intake failed: %s',
|
|
275
|
+
messageOf(error),
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
})
|
|
279
|
+
break
|
|
280
|
+
}
|
|
281
|
+
case Signal.hello: {
|
|
282
|
+
settle(numberOf(recordOf(parsed.d)?.code) ?? 0)
|
|
283
|
+
break
|
|
284
|
+
}
|
|
285
|
+
case Signal.pong: {
|
|
286
|
+
this.clearPong()
|
|
287
|
+
break
|
|
288
|
+
}
|
|
289
|
+
case Signal.resume: {
|
|
290
|
+
// The migrated enum names s=5 `resume`; the platform sends s=5 to demand a reconnect (and s=4 is only ever
|
|
291
|
+
// sent by a client that resumes, which this adapter does not).
|
|
292
|
+
const code = numberOf(recordOf(parsed.d)?.code)
|
|
293
|
+
this.bot.ctx.logger.info(
|
|
294
|
+
'kook: the platform asked for a reconnect%s',
|
|
295
|
+
code === undefined ? '' : ` (code ${code})`,
|
|
296
|
+
)
|
|
297
|
+
if (isResumeCode(code)) {
|
|
298
|
+
this.bot.ctx.logger.warn(
|
|
299
|
+
'kook: the platform refused the session (%s); resume is not implemented, so the offline window is lost',
|
|
300
|
+
code,
|
|
301
|
+
)
|
|
302
|
+
}
|
|
303
|
+
this.closeSocket()
|
|
304
|
+
break
|
|
305
|
+
}
|
|
306
|
+
default:
|
|
307
|
+
this.bot.ctx.logger.debug(
|
|
308
|
+
'kook: ignored a gateway frame with s=%s',
|
|
309
|
+
String(parsed.s),
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
const deadline = setTimeout(() => {
|
|
315
|
+
settle(Number.NaN)
|
|
316
|
+
}, HELLO_TIMEOUT)
|
|
317
|
+
const onAbort = (): void => {
|
|
318
|
+
settle(Number.NaN)
|
|
319
|
+
this.closeSocket()
|
|
320
|
+
}
|
|
321
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
322
|
+
|
|
323
|
+
try {
|
|
324
|
+
await hello
|
|
325
|
+
clearTimeout(deadline)
|
|
326
|
+
if (signal.aborted) return false
|
|
327
|
+
if (helloCode === undefined) {
|
|
328
|
+
// The connection closed before HELLO: a transport failure, not a configuration one.
|
|
329
|
+
throw new Error('kook: the gateway connection closed before HELLO')
|
|
330
|
+
}
|
|
331
|
+
if (Number.isNaN(helloCode)) {
|
|
332
|
+
this.closeSocket()
|
|
333
|
+
throw new Error(
|
|
334
|
+
`kook: HELLO did not arrive within ${HELLO_TIMEOUT / 1_000} s`,
|
|
335
|
+
)
|
|
336
|
+
}
|
|
337
|
+
if (helloCode !== 0) {
|
|
338
|
+
this.closeSocket()
|
|
339
|
+
// Only 40100–40103 are configuration refusals; an undocumented code is retried like any other transport failure.
|
|
340
|
+
if (isPermanentHelloCode(helloCode)) {
|
|
341
|
+
throw new KookGatewayFatalError(
|
|
342
|
+
`kook: the gateway refused the connection (code ${helloCode}); fix token/selfId and restart`,
|
|
343
|
+
)
|
|
344
|
+
}
|
|
345
|
+
throw new Error(`kook: the gateway HELLO failed with code ${helloCode}`)
|
|
346
|
+
}
|
|
347
|
+
greeted = true
|
|
348
|
+
this.bot.online()
|
|
349
|
+
this.scheduleHeartbeat(socket, () => sn, signal)
|
|
350
|
+
await closed
|
|
351
|
+
// Let the receives already queued finish before a new connection starts dispatching.
|
|
352
|
+
await queue
|
|
353
|
+
return greeted
|
|
354
|
+
} finally {
|
|
355
|
+
clearTimeout(deadline)
|
|
356
|
+
signal.removeEventListener('abort', onAbort)
|
|
357
|
+
this.stopHeartbeat()
|
|
358
|
+
if (this.socket === socket) this.socket = undefined
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** One heartbeat at 30 s ± 5 s, then another; a missing PONG within 6 s closes the socket for the reconnect loop. */
|
|
363
|
+
private scheduleHeartbeat(
|
|
364
|
+
socket: KookSocket,
|
|
365
|
+
sn: () => number,
|
|
366
|
+
signal: AbortSignal,
|
|
367
|
+
): void {
|
|
368
|
+
this.stopHeartbeat()
|
|
369
|
+
this.queueHeartbeat(socket, sn, signal)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Arm the next heartbeat without dropping the PONG deadline of the one already sent. */
|
|
373
|
+
private queueHeartbeat(
|
|
374
|
+
socket: KookSocket,
|
|
375
|
+
sn: () => number,
|
|
376
|
+
signal: AbortSignal,
|
|
377
|
+
): void {
|
|
378
|
+
const delay =
|
|
379
|
+
HEARTBEAT_BASE + Math.round((Math.random() * 2 - 1) * HEARTBEAT_JITTER)
|
|
380
|
+
this.heartbeatTimer = setTimeout(() => {
|
|
381
|
+
if (signal.aborted || this.socket !== socket) return
|
|
382
|
+
try {
|
|
383
|
+
socket.send(JSON.stringify({ s: Signal.ping, sn: sn() }))
|
|
384
|
+
} catch (error) {
|
|
385
|
+
this.bot.ctx.logger.warn(
|
|
386
|
+
'kook: could not send a heartbeat: %s',
|
|
387
|
+
messageOf(error),
|
|
388
|
+
)
|
|
389
|
+
this.closeSocket()
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
this.pongTimer = setTimeout(() => {
|
|
393
|
+
if (this.socket !== socket) return
|
|
394
|
+
this.bot.ctx.logger.warn(
|
|
395
|
+
'kook: the gateway did not answer the heartbeat within %s s; reconnecting',
|
|
396
|
+
PONG_TIMEOUT / 1_000,
|
|
397
|
+
)
|
|
398
|
+
this.closeSocket()
|
|
399
|
+
}, PONG_TIMEOUT)
|
|
400
|
+
this.queueHeartbeat(socket, sn, signal)
|
|
401
|
+
}, delay)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private clearPong(): void {
|
|
405
|
+
if (this.pongTimer !== undefined) clearTimeout(this.pongTimer)
|
|
406
|
+
this.pongTimer = undefined
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
private stopHeartbeat(): void {
|
|
410
|
+
if (this.heartbeatTimer !== undefined) clearTimeout(this.heartbeatTimer)
|
|
411
|
+
this.heartbeatTimer = undefined
|
|
412
|
+
this.clearPong()
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private closeSocket(): void {
|
|
416
|
+
const socket = this.socket
|
|
417
|
+
this.socket = undefined
|
|
418
|
+
this.stopHeartbeat()
|
|
419
|
+
try {
|
|
420
|
+
socket?.close(1000, 'adapter stopped')
|
|
421
|
+
} catch (error) {
|
|
422
|
+
// The socket is already closed or closing; nothing left to release.
|
|
423
|
+
error
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Message of any caught value, for a log line. */
|
|
429
|
+
function messageOf(error: unknown): string {
|
|
430
|
+
return error instanceof Error ? error.message : String(error)
|
|
431
|
+
}
|
package/README.md
DELETED