@iwpz/fishpi-dsh 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/README.md +93 -2
- package/client.js +3614 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +36 -0
- package/fishpi.js +706 -0
- package/icon.svg +4 -0
- package/icon.webp +0 -0
- package/index.js +990 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +47 -4
package/fishpi.js
ADDED
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FishPi (摸鱼派) API v3 client, chat WebSocket manager, and event hub.
|
|
3
|
+
*
|
|
4
|
+
* This module deliberately depends on nothing but Node built-ins so the Host
|
|
5
|
+
* half stays a dependency-free local bundle and can be exercised in a plain
|
|
6
|
+
* Node test. It never touches DSH services; `index.js` wires it into Cordis.
|
|
7
|
+
*
|
|
8
|
+
* API reference: https://github.com/FishPiOffical/rhythm/blob/api_v3/API.md
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createHash } from 'node:crypto'
|
|
12
|
+
|
|
13
|
+
/** FishPi production origin. A deployment may override it in the service. */
|
|
14
|
+
export const DEFAULT_SITE = 'https://fishpi.cn'
|
|
15
|
+
|
|
16
|
+
/** Client tag accepted by `/api/v3/chat/messages` (`brand/version`). */
|
|
17
|
+
export const CLIENT_TAG = 'DSH/fishpi-chat-0.1.0'
|
|
18
|
+
|
|
19
|
+
/** The largest body the public chat message endpoint accepts. */
|
|
20
|
+
export const MAX_MESSAGE_LENGTH = 4096
|
|
21
|
+
|
|
22
|
+
/** One failed FishPi operation with a stable, client-safe code. */
|
|
23
|
+
export class FishPiError extends Error {
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} message - human-readable failure text from the server.
|
|
26
|
+
* @param {{ code?: string, status?: number, cause?: unknown }} [options] - stable code, HTTP status, cause.
|
|
27
|
+
*/
|
|
28
|
+
constructor(message, options = {}) {
|
|
29
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause })
|
|
30
|
+
this.name = 'FishPiError'
|
|
31
|
+
this.code = options.code ?? 'fishpi_error'
|
|
32
|
+
this.status = options.status ?? 0
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* MD5 of a password, lowercase hex: the form `/api/v3/auth/login` requires.
|
|
38
|
+
* @param {string} value - the plain password typed by the user.
|
|
39
|
+
* @returns {string} 32 lowercase hex characters.
|
|
40
|
+
*/
|
|
41
|
+
export function md5Hex(value) {
|
|
42
|
+
return createHash('md5').update(value, 'utf8').digest('hex')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Remove the parts of a FishPi message the sidebar never renders and make the
|
|
47
|
+
* shape predictable for the browser.
|
|
48
|
+
* @param {unknown} raw - one message from the list, detail, or realtime socket.
|
|
49
|
+
* @returns {object|undefined} the normalized message, or undefined for non-objects.
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeMessage(raw) {
|
|
52
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
|
|
53
|
+
const source = /** @type {Record<string, any>} */ (raw)
|
|
54
|
+
const id = typeof source.id === 'string' || typeof source.id === 'number' ? String(source.id) : ''
|
|
55
|
+
if (id === '') return undefined
|
|
56
|
+
const author = source.author !== null && typeof source.author === 'object' ? source.author : {}
|
|
57
|
+
return {
|
|
58
|
+
id,
|
|
59
|
+
createdAt: Number(source.createdAt) || 0,
|
|
60
|
+
type: typeof source.type === 'string' ? source.type : 'text',
|
|
61
|
+
content: typeof source.content === 'string' ? source.content : '',
|
|
62
|
+
contentHtml: typeof source.contentHtml === 'string' ? source.contentHtml : '',
|
|
63
|
+
author: {
|
|
64
|
+
id: author.id === undefined || author.id === null ? '' : String(author.id),
|
|
65
|
+
userName: typeof author.userName === 'string' ? author.userName : '',
|
|
66
|
+
userNickname: typeof author.userNickname === 'string' ? author.userNickname : '',
|
|
67
|
+
userAvatarURL: typeof author.userAvatarURL === 'string' ? author.userAvatarURL : '',
|
|
68
|
+
},
|
|
69
|
+
client: typeof source.client === 'string' ? source.client : '',
|
|
70
|
+
medals: Array.isArray(source.medals)
|
|
71
|
+
? source.medals.map(medal => ({
|
|
72
|
+
id: medal?.id === undefined ? '' : String(medal.id),
|
|
73
|
+
name: typeof medal?.name === 'string' ? medal.name : '',
|
|
74
|
+
type: typeof medal?.type === 'string' ? medal.type : '',
|
|
75
|
+
description: typeof medal?.description === 'string' ? medal.description : '',
|
|
76
|
+
}))
|
|
77
|
+
: [],
|
|
78
|
+
card: source.card !== null && typeof source.card === 'object' && !Array.isArray(source.card) ? source.card : {},
|
|
79
|
+
appearance: source.appearance !== null && typeof source.appearance === 'object' ? source.appearance : undefined,
|
|
80
|
+
reactionsUnavailable: source.reactionsUnavailable === true,
|
|
81
|
+
reactions: source.reactions !== null && typeof source.reactions === 'object' ? source.reactions : undefined,
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A slim public user record for the Host state and message snapshots.
|
|
87
|
+
* @param {unknown} raw - `/api/v3/me` data.
|
|
88
|
+
* @returns {{ id: string, userName: string, userNickname: string, userAvatarURL: string, userPoint?: number }|undefined}
|
|
89
|
+
*/
|
|
90
|
+
export function normalizeMe(raw) {
|
|
91
|
+
if (raw === null || typeof raw !== 'object') return undefined
|
|
92
|
+
const source = /** @type {Record<string, any>} */ (raw)
|
|
93
|
+
const id = source.id === undefined || source.id === null ? '' : String(source.id)
|
|
94
|
+
if (id === '') return undefined
|
|
95
|
+
return {
|
|
96
|
+
id,
|
|
97
|
+
userName: typeof source.userName === 'string' ? source.userName : '',
|
|
98
|
+
userNickname: typeof source.userNickname === 'string' ? source.userNickname : '',
|
|
99
|
+
userAvatarURL: typeof source.userAvatarURL === 'string' ? source.userAvatarURL : '',
|
|
100
|
+
userPoint: Number.isFinite(Number(source.userPoint)) ? Number(source.userPoint) : undefined,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The HTTP face of the FishPi v3 API used by the sidebar.
|
|
106
|
+
*
|
|
107
|
+
* Every call keeps the unified envelope rules: `code: 0` means success, a
|
|
108
|
+
* non-zero code or a non-2xx status becomes a {@link FishPiError}, and callers
|
|
109
|
+
* receive `data` only.
|
|
110
|
+
*/
|
|
111
|
+
export class FishPiApi {
|
|
112
|
+
/**
|
|
113
|
+
* @param {{ siteUrl?: string, token?: string, fetchImpl?: typeof fetch, clientTag?: string }} [options] - endpoint and transport overrides.
|
|
114
|
+
*/
|
|
115
|
+
constructor(options = {}) {
|
|
116
|
+
this.siteUrl = (options.siteUrl ?? DEFAULT_SITE).replace(/\/+$/u, '')
|
|
117
|
+
this.token = options.token ?? ''
|
|
118
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch
|
|
119
|
+
this.clientTag = options.clientTag ?? CLIENT_TAG
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @param {string} token - Bearer access token; an empty string clears it.
|
|
124
|
+
*/
|
|
125
|
+
setToken(token) {
|
|
126
|
+
this.token = token
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @param {string} path - absolute API path such as `/api/v3/me`.
|
|
131
|
+
* @returns {string} the absolute URL on the configured site.
|
|
132
|
+
*/
|
|
133
|
+
url(path) {
|
|
134
|
+
return new URL(path, `${this.siteUrl}/`).toString()
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* One enveloped API request.
|
|
139
|
+
* @param {string} path - absolute API path.
|
|
140
|
+
* @param {{ method?: string, body?: unknown, signal?: AbortSignal, auth?: boolean, idempotencyKey?: string, raw?: boolean }} [options] - request shape.
|
|
141
|
+
* @returns {Promise<any>} the envelope's `data`, or the raw JSON payload when `raw` is true.
|
|
142
|
+
*/
|
|
143
|
+
async request(path, options = {}) {
|
|
144
|
+
const method = options.method ?? 'GET'
|
|
145
|
+
/** @type {Record<string, string>} */
|
|
146
|
+
const headers = { accept: 'application/json' }
|
|
147
|
+
/** @type {RequestInit} */
|
|
148
|
+
const init = { method, headers, credentials: 'omit' }
|
|
149
|
+
if (options.body !== undefined) {
|
|
150
|
+
headers['content-type'] = 'application/json'
|
|
151
|
+
init.body = JSON.stringify(options.body)
|
|
152
|
+
}
|
|
153
|
+
if (options.auth !== false && this.token !== '') headers.authorization = `Bearer ${this.token}`
|
|
154
|
+
if (options.idempotencyKey !== undefined) headers['idempotency-key'] = options.idempotencyKey
|
|
155
|
+
const timeout = AbortSignal.timeout(25_000)
|
|
156
|
+
init.signal = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
|
|
157
|
+
|
|
158
|
+
let response
|
|
159
|
+
try {
|
|
160
|
+
response = await this.fetchImpl(this.url(path), init)
|
|
161
|
+
} catch (error) {
|
|
162
|
+
if (options.signal?.aborted === true) throw error
|
|
163
|
+
throw new FishPiError('无法连接摸鱼派服务器', { code: 'network', cause: error })
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const text = await response.text().catch(() => '')
|
|
167
|
+
let payload = null
|
|
168
|
+
if (text !== '') {
|
|
169
|
+
try {
|
|
170
|
+
payload = JSON.parse(text)
|
|
171
|
+
} catch {
|
|
172
|
+
throw new FishPiError('摸鱼派返回了无法解析的响应', { code: 'invalid_response', status: response.status })
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const envelope = payload !== null && typeof payload === 'object' ? payload : {}
|
|
176
|
+
const code = envelope.code
|
|
177
|
+
if (!response.ok || (code !== undefined && code !== 0 && code !== '0')) {
|
|
178
|
+
throw new FishPiError(
|
|
179
|
+
typeof envelope.msg === 'string' && envelope.msg !== '' ? envelope.msg : `HTTP ${response.status}`,
|
|
180
|
+
{
|
|
181
|
+
code: typeof code === 'string' && code !== '' ? code : `http_${response.status}`,
|
|
182
|
+
status: response.status,
|
|
183
|
+
},
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
if (options.raw === true) return payload
|
|
187
|
+
return envelope.data
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* @param {{ nameOrEmail: string, userPassword: string, mfaCode?: string }} input - credentials; password is already MD5.
|
|
192
|
+
* @returns {Promise<{ accessToken: string, tokenType?: string, expiresIn?: number, scope?: string }>} a login grant.
|
|
193
|
+
*/
|
|
194
|
+
login(input) {
|
|
195
|
+
/** @type {Record<string, string>} */
|
|
196
|
+
const body = { nameOrEmail: input.nameOrEmail, userPassword: input.userPassword }
|
|
197
|
+
if (input.mfaCode !== undefined && input.mfaCode !== '') body.mfaCode = input.mfaCode
|
|
198
|
+
return this.request('/api/v3/auth/login', { method: 'POST', body, auth: false })
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** @returns {Promise<any>} the current account profile. */
|
|
202
|
+
me() {
|
|
203
|
+
return this.request('/api/v3/me')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* @param {{ size?: number, before?: string, after?: string, signal?: AbortSignal }} [options] - one message window.
|
|
208
|
+
* @returns {Promise<{ list?: unknown[], hasMore?: boolean, nextBefore?: string, nextAfter?: string }>} the window.
|
|
209
|
+
*/
|
|
210
|
+
messages(options = {}) {
|
|
211
|
+
const query = new URLSearchParams()
|
|
212
|
+
if (options.size !== undefined) query.set('size', String(options.size))
|
|
213
|
+
if (options.before !== undefined && options.before !== '') query.set('before', options.before)
|
|
214
|
+
if (options.after !== undefined && options.after !== '') query.set('after', options.after)
|
|
215
|
+
const suffix = query.size === 0 ? '' : `?${query.toString()}`
|
|
216
|
+
return this.request(`/api/v3/chat/messages${suffix}`, { signal: options.signal })
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @param {string} id - message id.
|
|
221
|
+
* @returns {Promise<any>} one message.
|
|
222
|
+
*/
|
|
223
|
+
message(id) {
|
|
224
|
+
return this.request(`/api/v3/chat/messages/${encodeURIComponent(id)}`)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* @param {string} content - Markdown body, already trimmed by the caller.
|
|
229
|
+
* @param {string} idempotencyKey - stable key for this logical send.
|
|
230
|
+
* @returns {Promise<{ id: string, createdAt: number }>} the accepted message identity.
|
|
231
|
+
*/
|
|
232
|
+
send(content, idempotencyKey) {
|
|
233
|
+
return this.request('/api/v3/chat/messages', {
|
|
234
|
+
method: 'POST',
|
|
235
|
+
body: { content, client: this.clientTag },
|
|
236
|
+
idempotencyKey,
|
|
237
|
+
})
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* @param {string} id - red-packet message id.
|
|
242
|
+
* @returns {Promise<any>} the current red-packet detail and claims.
|
|
243
|
+
*/
|
|
244
|
+
redPacket(id) {
|
|
245
|
+
return this.request(`/api/v3/chat/red-packets/${encodeURIComponent(id)}`)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* @param {string} id - red-packet message id.
|
|
250
|
+
* @param {{ gesture?: number, riskAccepted?: boolean }} input - risk acknowledgement and RPS gesture.
|
|
251
|
+
* @param {string} idempotencyKey - stable key for this logical claim.
|
|
252
|
+
* @returns {Promise<any>} the claim receipt.
|
|
253
|
+
*/
|
|
254
|
+
claimRedPacket(id, input, idempotencyKey) {
|
|
255
|
+
/** @type {Record<string, unknown>} */
|
|
256
|
+
const body = {}
|
|
257
|
+
if (input.riskAccepted === true) body.riskAccepted = true
|
|
258
|
+
if (Number.isInteger(input.gesture)) body.gesture = input.gesture
|
|
259
|
+
return this.request(`/api/v3/chat/red-packets/${encodeURIComponent(id)}/claims`, {
|
|
260
|
+
method: 'POST',
|
|
261
|
+
body,
|
|
262
|
+
idempotencyKey,
|
|
263
|
+
})
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** @returns {Promise<{ text?: string }>} the current topic. */
|
|
267
|
+
topic() {
|
|
268
|
+
return this.request('/api/v3/chat/topic')
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* @param {{ size?: number }} [options] - page size; the endpoint caps it at 50.
|
|
273
|
+
* @returns {Promise<{ list?: unknown[], pagination?: unknown }>} online users.
|
|
274
|
+
*/
|
|
275
|
+
onlineUsers(options = {}) {
|
|
276
|
+
const query = new URLSearchParams({ p: '1', size: String(options.size ?? 50) })
|
|
277
|
+
return this.request(`/api/v3/chat/online-users?${query.toString()}`)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* @param {string} userName - public username.
|
|
282
|
+
* @returns {Promise<any>} the legacy public member record, which carries userNo and userCity.
|
|
283
|
+
*/
|
|
284
|
+
legacyUser(userName) {
|
|
285
|
+
return this.request(`/user/${encodeURIComponent(userName)}`, { raw: true })
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* @param {string} userName - public username.
|
|
290
|
+
* @returns {Promise<any>} the public profile.
|
|
291
|
+
*/
|
|
292
|
+
userProfile(userName) {
|
|
293
|
+
return this.request(`/api/v3/users/${encodeURIComponent(userName)}`)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* @param {string} userName - public username.
|
|
298
|
+
* @returns {Promise<{ list?: unknown[] }>} the user's public medals.
|
|
299
|
+
*/
|
|
300
|
+
userMedals(userName) {
|
|
301
|
+
return this.request(`/user/${encodeURIComponent(userName)}/medal`)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* @param {string} prefix - username prefix, 1–64 letters/digits/underscore/hyphen.
|
|
306
|
+
* @returns {Promise<{ list?: unknown[] }>} up to ten matching users.
|
|
307
|
+
*/
|
|
308
|
+
suggestUsers(prefix) {
|
|
309
|
+
const query = new URLSearchParams({ prefix })
|
|
310
|
+
return this.request(`/api/v3/suggestions/users?${query.toString()}`)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** @returns {Promise<{ ticket: string, tokenType?: string, uploadURL: string, fieldName?: string, expiresIn?: number }>} a short-lived upload ticket. */
|
|
314
|
+
uploadTicket() {
|
|
315
|
+
return this.request('/api/v3/uploads/tickets', { method: 'POST', body: {} })
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** @returns {Promise<{ ticket: string, expiresIn?: number, path: string, channel: string }>} a one-shot chat socket ticket. */
|
|
319
|
+
realtimeTicket() {
|
|
320
|
+
return this.request('/api/v3/chat/realtime-ticket', { method: 'POST', body: {} })
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* A bounded, monotonically numbered event log with long-poll waiters.
|
|
326
|
+
*
|
|
327
|
+
* The browser reads a cursor and asks `wait`; the hub answers immediately with
|
|
328
|
+
* the backlog or holds the request until one event lands. A cursor older than
|
|
329
|
+
* the retained window asks the caller to reset its message window.
|
|
330
|
+
*/
|
|
331
|
+
export class EventHub {
|
|
332
|
+
/**
|
|
333
|
+
* @param {{ limit?: number }} [options] - retained event count.
|
|
334
|
+
*/
|
|
335
|
+
constructor(options = {}) {
|
|
336
|
+
this.limit = options.limit ?? 500
|
|
337
|
+
/** @type {Array<{ seq: number, type: string, data: unknown, at: number }>} */
|
|
338
|
+
this.log = []
|
|
339
|
+
this.seq = 0
|
|
340
|
+
/** @type {Set<{ since: number, finish: (value: unknown) => void }>} */
|
|
341
|
+
this.waiters = new Set()
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* @param {string} type - event name consumed by the browser.
|
|
346
|
+
* @param {unknown} data - JSON-safe payload.
|
|
347
|
+
*/
|
|
348
|
+
emit(type, data) {
|
|
349
|
+
const event = { seq: ++this.seq, type, data, at: Date.now() }
|
|
350
|
+
this.log.push(event)
|
|
351
|
+
if (this.log.length > this.limit) this.log.splice(0, this.log.length - this.limit)
|
|
352
|
+
for (const waiter of [...this.waiters]) {
|
|
353
|
+
if (event.seq > waiter.since) waiter.finish(this.#batch(waiter.since))
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* @param {number} since - last cursor the caller applied.
|
|
359
|
+
* @param {AbortSignal|undefined} signal - caller lifetime.
|
|
360
|
+
* @param {number} timeoutMs - longest hold before an empty answer.
|
|
361
|
+
* @returns {Promise<{ events?: unknown[], cursor: number, reset?: boolean }>}
|
|
362
|
+
*/
|
|
363
|
+
wait(since, signal, timeoutMs) {
|
|
364
|
+
const cursor = this.seq
|
|
365
|
+
if (since > cursor) return Promise.resolve({ reset: true, cursor })
|
|
366
|
+
const first = this.log.length === 0 ? 0 : this.log[0].seq
|
|
367
|
+
if (this.log.length > 0 && since < first - 1) return Promise.resolve({ reset: true, cursor })
|
|
368
|
+
if (since < cursor && this.log.length > 0) return Promise.resolve(this.#batch(since))
|
|
369
|
+
return new Promise(resolve => {
|
|
370
|
+
let settled = false
|
|
371
|
+
/** @type {{ since: number, finish: (value: unknown) => void }} */
|
|
372
|
+
const waiter = {
|
|
373
|
+
since,
|
|
374
|
+
finish: value => {
|
|
375
|
+
if (settled) return
|
|
376
|
+
settled = true
|
|
377
|
+
clearTimeout(timer)
|
|
378
|
+
signal?.removeEventListener('abort', onAbort)
|
|
379
|
+
this.waiters.delete(waiter)
|
|
380
|
+
resolve(/** @type {any} */ (value))
|
|
381
|
+
},
|
|
382
|
+
}
|
|
383
|
+
const timer = setTimeout(() => waiter.finish({ events: [], cursor: this.seq }), timeoutMs)
|
|
384
|
+
const onAbort = () => waiter.finish({ events: [], cursor: this.seq })
|
|
385
|
+
if (signal !== undefined) {
|
|
386
|
+
if (signal.aborted) {
|
|
387
|
+
waiter.finish({ events: [], cursor: this.seq })
|
|
388
|
+
return
|
|
389
|
+
}
|
|
390
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
391
|
+
}
|
|
392
|
+
this.waiters.add(waiter)
|
|
393
|
+
})
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* @param {number} since - exclusive lower bound.
|
|
398
|
+
* @returns {{ events: unknown[], cursor: number }}
|
|
399
|
+
*/
|
|
400
|
+
#batch(since) {
|
|
401
|
+
return { events: this.log.filter(event => event.seq > since), cursor: this.seq }
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Release every held request. */
|
|
405
|
+
dispose() {
|
|
406
|
+
for (const waiter of [...this.waiters]) waiter.finish({ events: [], cursor: this.seq })
|
|
407
|
+
this.waiters.clear()
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* The chat WebSocket: one ticket per connection, authenticate, heartbeat,
|
|
413
|
+
* refresh before the grant expires, and reconnect with exponential backoff.
|
|
414
|
+
*
|
|
415
|
+
* The socket never calls the HTTP API itself. `getTicket` lets its owner renew
|
|
416
|
+
* the access token first, which is what makes a token refresh recover a
|
|
417
|
+
* closed connection instead of looping on 401.
|
|
418
|
+
*/
|
|
419
|
+
export class ChatRealtime {
|
|
420
|
+
/**
|
|
421
|
+
* @param {{
|
|
422
|
+
* getTicket: () => Promise<{ ticket: string, path: string, expiresIn?: number }>,
|
|
423
|
+
* siteUrl?: string,
|
|
424
|
+
* onEvent?: (event: { type: string, data: any }) => void,
|
|
425
|
+
* onState?: (state: 'connecting'|'connected'|'disconnected') => void,
|
|
426
|
+
* onError?: (error: unknown) => void,
|
|
427
|
+
* WebSocketImpl?: typeof WebSocket,
|
|
428
|
+
* logger?: Pick<Console, 'warn'>,
|
|
429
|
+
* }} options - transport and lifecycle hooks.
|
|
430
|
+
*/
|
|
431
|
+
constructor(options) {
|
|
432
|
+
this.getTicket = options.getTicket
|
|
433
|
+
this.siteUrl = (options.siteUrl ?? DEFAULT_SITE).replace(/\/+$/u, '')
|
|
434
|
+
this.onEvent = options.onEvent ?? (() => {})
|
|
435
|
+
this.onState = options.onState ?? (() => {})
|
|
436
|
+
this.onError = options.onError ?? (() => {})
|
|
437
|
+
this.WebSocketImpl = options.WebSocketImpl ?? globalThis.WebSocket
|
|
438
|
+
this.logger = options.logger ?? console
|
|
439
|
+
|
|
440
|
+
this.state = 'disconnected'
|
|
441
|
+
this.stopped = true
|
|
442
|
+
this.attempt = 0
|
|
443
|
+
/** @type {WebSocket|undefined} */
|
|
444
|
+
this.socket = undefined
|
|
445
|
+
this.reconnectTimer = undefined
|
|
446
|
+
this.heartbeatTimer = undefined
|
|
447
|
+
this.refreshTimer = undefined
|
|
448
|
+
this.handshakeTimer = undefined
|
|
449
|
+
this.lastPong = 0
|
|
450
|
+
this.ticket = ''
|
|
451
|
+
this.generation = 0
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Start connecting; repeated calls while running do nothing. */
|
|
455
|
+
start() {
|
|
456
|
+
if (!this.stopped) return
|
|
457
|
+
this.stopped = false
|
|
458
|
+
this.attempt = 0
|
|
459
|
+
void this.#connect()
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Stop permanently and release timers and the socket. */
|
|
463
|
+
stop() {
|
|
464
|
+
this.stopped = true
|
|
465
|
+
this.generation += 1
|
|
466
|
+
this.#clearTimers()
|
|
467
|
+
const socket = this.socket
|
|
468
|
+
this.socket = undefined
|
|
469
|
+
if (socket !== undefined) {
|
|
470
|
+
try {
|
|
471
|
+
socket.close()
|
|
472
|
+
} catch {
|
|
473
|
+
// Closing a socket the server already closed is not an error here.
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
this.#setState('disconnected')
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** @returns {'connecting'|'connected'|'disconnected'} the last published transport state. */
|
|
480
|
+
getState() {
|
|
481
|
+
return this.state
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Close the current socket and reconnect immediately with a fresh ticket.
|
|
486
|
+
* Used when the server asks for a resync or when the grant nears expiry.
|
|
487
|
+
* @param {string} reason - internal reason for diagnostics.
|
|
488
|
+
*/
|
|
489
|
+
refresh(reason) {
|
|
490
|
+
if (this.stopped) return
|
|
491
|
+
this.logger.warn?.(`[fishpi-chat] refreshing realtime connection: ${reason}`)
|
|
492
|
+
this.#restart(false)
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async #connect() {
|
|
496
|
+
if (this.stopped) return
|
|
497
|
+
const generation = ++this.generation
|
|
498
|
+
this.#setState('connecting')
|
|
499
|
+
let ticket
|
|
500
|
+
try {
|
|
501
|
+
ticket = await this.getTicket()
|
|
502
|
+
} catch (error) {
|
|
503
|
+
if (this.stopped || generation !== this.generation) return
|
|
504
|
+
this.onError(error)
|
|
505
|
+
this.#setState('disconnected')
|
|
506
|
+
if (error?.status === 401 || error?.code === 'unauthorized') {
|
|
507
|
+
this.stopped = true
|
|
508
|
+
this.#clearTimers()
|
|
509
|
+
return
|
|
510
|
+
}
|
|
511
|
+
this.#scheduleReconnect()
|
|
512
|
+
return
|
|
513
|
+
}
|
|
514
|
+
if (this.stopped || generation !== this.generation) return
|
|
515
|
+
this.ticket = ticket.ticket
|
|
516
|
+
if (typeof this.WebSocketImpl !== 'function') {
|
|
517
|
+
this.onError(new Error('This runtime does not provide WebSocket'))
|
|
518
|
+
this.#setState('disconnected')
|
|
519
|
+
return
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const url = new URL(ticket.path, `${this.siteUrl}/`)
|
|
523
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
524
|
+
let socket
|
|
525
|
+
try {
|
|
526
|
+
socket = new this.WebSocketImpl(url.toString())
|
|
527
|
+
} catch (error) {
|
|
528
|
+
this.onError(error)
|
|
529
|
+
this.#setState('disconnected')
|
|
530
|
+
this.#scheduleReconnect()
|
|
531
|
+
return
|
|
532
|
+
}
|
|
533
|
+
this.socket = socket
|
|
534
|
+
this.handshakeTimer = setTimeout(() => {
|
|
535
|
+
if (socket !== this.socket || this.state === 'connected' || this.stopped) return
|
|
536
|
+
this.logger.warn?.('[fishpi-chat] realtime handshake timed out; reconnecting')
|
|
537
|
+
this.#restart(true)
|
|
538
|
+
}, 15_000)
|
|
539
|
+
|
|
540
|
+
socket.addEventListener('message', event => {
|
|
541
|
+
if (socket !== this.socket) return
|
|
542
|
+
this.#onMessage(event.data)
|
|
543
|
+
})
|
|
544
|
+
socket.addEventListener('close', () => {
|
|
545
|
+
if (socket !== this.socket) return
|
|
546
|
+
this.socket = undefined
|
|
547
|
+
this.#clearTimers()
|
|
548
|
+
if (this.stopped) return
|
|
549
|
+
this.#setState('disconnected')
|
|
550
|
+
this.#scheduleReconnect()
|
|
551
|
+
})
|
|
552
|
+
socket.addEventListener('error', event => {
|
|
553
|
+
if (socket !== this.socket) return
|
|
554
|
+
this.onError(event)
|
|
555
|
+
})
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* @param {unknown} raw - one text frame from the socket.
|
|
560
|
+
*/
|
|
561
|
+
#onMessage(raw) {
|
|
562
|
+
let message
|
|
563
|
+
try {
|
|
564
|
+
message = JSON.parse(typeof raw === 'string' ? raw : String(raw))
|
|
565
|
+
} catch {
|
|
566
|
+
return
|
|
567
|
+
}
|
|
568
|
+
if (message === null || typeof message !== 'object') return
|
|
569
|
+
switch (message.type) {
|
|
570
|
+
case 'authentication.required': {
|
|
571
|
+
this.#send({ type: 'authenticate', ticket: this.ticket })
|
|
572
|
+
return
|
|
573
|
+
}
|
|
574
|
+
case 'ready': {
|
|
575
|
+
this.attempt = 0
|
|
576
|
+
this.lastPong = Date.now()
|
|
577
|
+
clearTimeout(this.handshakeTimer)
|
|
578
|
+
this.handshakeTimer = undefined
|
|
579
|
+
this.#setState('connected')
|
|
580
|
+
this.#startHeartbeat()
|
|
581
|
+
this.#scheduleRefresh(message.data?.expiresAt)
|
|
582
|
+
this.onEvent({ type: 'ready', data: message.data ?? {} })
|
|
583
|
+
return
|
|
584
|
+
}
|
|
585
|
+
case 'pong': {
|
|
586
|
+
this.lastPong = Date.now()
|
|
587
|
+
return
|
|
588
|
+
}
|
|
589
|
+
default: {
|
|
590
|
+
if (typeof message.type === 'string' && message.type.startsWith('chat.')) {
|
|
591
|
+
this.onEvent({ type: 'chat', data: message })
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
#startHeartbeat() {
|
|
598
|
+
clearInterval(this.heartbeatTimer)
|
|
599
|
+
this.heartbeatTimer = setInterval(() => {
|
|
600
|
+
if (Date.now() - this.lastPong > 60_000) {
|
|
601
|
+
this.logger.warn?.('[fishpi-chat] realtime heartbeat timed out; reconnecting')
|
|
602
|
+
this.#restart(true)
|
|
603
|
+
return
|
|
604
|
+
}
|
|
605
|
+
this.#send({ type: 'ping' })
|
|
606
|
+
}, 25_000)
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* @param {number|undefined} expiresAt - server-published grant expiry.
|
|
611
|
+
*/
|
|
612
|
+
#scheduleRefresh(expiresAt) {
|
|
613
|
+
clearTimeout(this.refreshTimer)
|
|
614
|
+
const expiry = Number(expiresAt) || 0
|
|
615
|
+
if (expiry <= 0) return
|
|
616
|
+
const delay = Math.max(5_000, expiry - Date.now() - 30_000)
|
|
617
|
+
this.refreshTimer = setTimeout(() => {
|
|
618
|
+
this.refresh('grant expiring')
|
|
619
|
+
}, delay)
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* @param {unknown} payload - socket frame to send.
|
|
624
|
+
*/
|
|
625
|
+
#send(payload) {
|
|
626
|
+
const socket = this.socket
|
|
627
|
+
if (socket === undefined || socket.readyState !== 1) return
|
|
628
|
+
try {
|
|
629
|
+
socket.send(JSON.stringify(payload))
|
|
630
|
+
} catch (error) {
|
|
631
|
+
this.onError(error)
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* @param {boolean} countAttempt - whether a failure counts against backoff.
|
|
637
|
+
*/
|
|
638
|
+
#restart(countAttempt) {
|
|
639
|
+
this.generation += 1
|
|
640
|
+
this.#clearTimers()
|
|
641
|
+
const socket = this.socket
|
|
642
|
+
this.socket = undefined
|
|
643
|
+
if (socket !== undefined) {
|
|
644
|
+
try {
|
|
645
|
+
socket.close()
|
|
646
|
+
} catch {
|
|
647
|
+
// Already closed.
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
if (countAttempt) this.attempt += 1
|
|
651
|
+
if (this.stopped) return
|
|
652
|
+
this.#setState('connecting')
|
|
653
|
+
void this.#connect()
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
#scheduleReconnect() {
|
|
657
|
+
if (this.stopped) return
|
|
658
|
+
const delay = Math.min(30_000, 1_000 * 2 ** Math.min(this.attempt, 5))
|
|
659
|
+
this.attempt += 1
|
|
660
|
+
clearTimeout(this.reconnectTimer)
|
|
661
|
+
this.reconnectTimer = setTimeout(() => { void this.#connect() }, delay)
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
#clearTimers() {
|
|
665
|
+
clearTimeout(this.reconnectTimer)
|
|
666
|
+
clearTimeout(this.refreshTimer)
|
|
667
|
+
clearTimeout(this.handshakeTimer)
|
|
668
|
+
clearInterval(this.heartbeatTimer)
|
|
669
|
+
this.reconnectTimer = undefined
|
|
670
|
+
this.refreshTimer = undefined
|
|
671
|
+
this.handshakeTimer = undefined
|
|
672
|
+
this.heartbeatTimer = undefined
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* @param {'connecting'|'connected'|'disconnected'} state - new transport state.
|
|
677
|
+
*/
|
|
678
|
+
#setState(state) {
|
|
679
|
+
if (this.state === state) return
|
|
680
|
+
this.state = state
|
|
681
|
+
this.onState(state)
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* @param {number} ms - delay length.
|
|
687
|
+
* @param {AbortSignal|undefined} signal - cancels the wait.
|
|
688
|
+
* @returns {Promise<void>}
|
|
689
|
+
*/
|
|
690
|
+
export function delay(ms, signal) {
|
|
691
|
+
return new Promise((resolve, reject) => {
|
|
692
|
+
if (signal?.aborted === true) {
|
|
693
|
+
reject(signal.reason)
|
|
694
|
+
return
|
|
695
|
+
}
|
|
696
|
+
const timer = setTimeout(() => {
|
|
697
|
+
signal?.removeEventListener('abort', onAbort)
|
|
698
|
+
resolve()
|
|
699
|
+
}, ms)
|
|
700
|
+
const onAbort = () => {
|
|
701
|
+
clearTimeout(timer)
|
|
702
|
+
reject(signal?.reason)
|
|
703
|
+
}
|
|
704
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
705
|
+
})
|
|
706
|
+
}
|