@bigmistqke/whiteboard 0.6.1 → 0.7.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 +13 -7
- package/dist/bin/whiteboard.js +0 -0
- package/dist/client/runtime.js +235 -58
- package/dist/plugins/badge/README.md +3 -1
- package/dist/plugins/badge/public/style.css +17 -0
- package/dist/plugins/chat/public/client.js +2 -2
- package/dist/plugins/chat/public/style.css +9 -0
- package/dist/plugins/comments/public/client.js +7 -2
- package/dist/plugins/comments/public/style.css +4 -0
- package/dist/plugins/grid/public/style.css +0 -5
- package/dist/plugins/index.js +5 -1
- package/dist/plugins/timeline/README.md +40 -0
- package/dist/plugins/timeline/index.js +82 -0
- package/dist/plugins/timeline/public/style.css +118 -0
- package/dist/plugins/toc/README.md +13 -13
- package/dist/plugins/toc/index.js +5 -3
- package/dist/plugins/toc/public/client.js +1 -1
- package/dist/plugins/toc/public/style.css +19 -2
- package/dist/solid/index.js +2 -1
- package/dist/src/auth.js +7 -3
- package/dist/src/client/page/base.css +74 -35
- package/dist/src/client/page/main.js +15 -4
- package/dist/src/events.js +4 -2
- package/dist/src/hub.js +43 -18
- package/dist/src/serve.js +2 -0
- package/dist/src/server.js +49 -11
- package/dist/src/ws.js +128 -0
- package/package.json +1 -1
- package/plugins/badge/README.md +3 -1
- package/plugins/badge/public/style.css +17 -0
- package/plugins/chat/client.tsx +34 -6
- package/plugins/chat/public/style.css +9 -0
- package/plugins/comments/client.ts +48 -5
- package/plugins/comments/public/style.css +4 -0
- package/plugins/grid/public/style.css +0 -5
- package/plugins/index.ts +6 -1
- package/plugins/timeline/README.md +40 -0
- package/plugins/timeline/index.ts +92 -0
- package/plugins/timeline/public/style.css +118 -0
- package/plugins/toc/README.md +13 -13
- package/plugins/toc/client.ts +49 -30
- package/plugins/toc/index.ts +12 -12
- package/plugins/toc/public/style.css +19 -2
- package/solid/index.tsx +3 -0
- package/src/auth.ts +7 -2
- package/src/client/forms.ts +102 -5
- package/src/client/page/base.css +74 -35
- package/src/client/page/elsewhere.ts +12 -3
- package/src/client/page/waiting.ts +10 -5
- package/src/client/read.ts +16 -3
- package/src/client/runtime.ts +134 -45
- package/src/client/toast.ts +35 -5
- package/src/define.ts +10 -0
- package/src/events.ts +7 -1
- package/src/hub.ts +54 -22
- package/src/serve.ts +2 -0
- package/src/server.ts +73 -17
- package/src/ws.ts +155 -0
package/src/server.ts
CHANGED
|
@@ -16,16 +16,18 @@
|
|
|
16
16
|
// plugins bring (pages.ts). When the config fails to load, a page shows as its raw
|
|
17
17
|
// text.
|
|
18
18
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
19
|
+
import type { Duplex } from 'node:stream'
|
|
19
20
|
import fs from 'node:fs'
|
|
20
21
|
import { parse as parseYaml } from 'yaml'
|
|
21
22
|
import { stripTypeScriptTypes } from 'node:module'
|
|
22
23
|
import path from 'node:path'
|
|
23
24
|
import type { Project } from './config.ts'
|
|
24
|
-
import { appendEvent, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
|
|
25
|
+
import { appendEvent, isEventId, readEvents, matches, pickedUp, fromReader, forAgent, CLAIM } from './events.ts'
|
|
25
26
|
import { html, raw, type Html } from './html.ts'
|
|
26
27
|
import { createConfigLoader, pluginDir, toPath, type LoadedConfig } from './loader.ts'
|
|
27
28
|
import { describeRoutes, dispatch, pluginCommands, mountRoutes, usage, type MountedRoute } from './plugins.ts'
|
|
28
|
-
import { createAuth } from './auth.ts'
|
|
29
|
+
import { createAuth, sameSite } from './auth.ts'
|
|
30
|
+
import { accept, refuse } from './ws.ts'
|
|
29
31
|
import { FROM_SOURCE, PACKAGE_DIR, VERSION } from './package.ts'
|
|
30
32
|
import { awaiting, covers, heard, questionState, unreadMessages } from './status.ts'
|
|
31
33
|
import { titleOf } from './pages/render.ts'
|
|
@@ -40,6 +42,7 @@ import type {
|
|
|
40
42
|
StoredPage,
|
|
41
43
|
PagesSource,
|
|
42
44
|
BuildConfig,
|
|
45
|
+
WbEvent,
|
|
43
46
|
} from './define.ts'
|
|
44
47
|
|
|
45
48
|
const ENGINE_DIR = PACKAGE_DIR
|
|
@@ -79,6 +82,8 @@ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
|
|
|
79
82
|
export interface WhiteboardServer {
|
|
80
83
|
/** answer one request */
|
|
81
84
|
handle(req: IncomingMessage, res: ServerResponse): Promise<void>
|
|
85
|
+
/** answer one upgrade request (the HTTP server's 'upgrade' event): the page's live channel */
|
|
86
|
+
upgrade(req: IncomingMessage, conn: Duplex, head: Buffer): void
|
|
82
87
|
/** what is open on each page (or on `page` and below), as /api/status gives it */
|
|
83
88
|
status(page?: string | null): Promise<PageStatus[]>
|
|
84
89
|
/** the project's config, loaded */
|
|
@@ -97,6 +102,8 @@ export interface WhiteboardServer {
|
|
|
97
102
|
overview(): Promise<{ pages: PagesSource['pages']; files: boolean }>
|
|
98
103
|
/** tell the open overviews (`/`) that what they list changed */
|
|
99
104
|
touch(): void
|
|
105
|
+
/** tell the open pages that what waits in another project of the shared server changed */
|
|
106
|
+
elsewhere(): void
|
|
100
107
|
/** stop watching and end the live connections; the server answers nothing after */
|
|
101
108
|
close(): void
|
|
102
109
|
}
|
|
@@ -568,7 +575,10 @@ export function createServer(
|
|
|
568
575
|
'.wb-toast[hidden]{display:none}.wb-toast[data-kind=warn]{background:var(--warn,#6b4fc0)}.wb-toast[data-kind=alert]{background:var(--bad,#c4352b);color:#fff}' +
|
|
569
576
|
// where an agent scrolled the page to, lit up a moment
|
|
570
577
|
'@keyframes wb-flash{from{outline-color:var(--accent,#1d5bbf)}to{outline-color:transparent}}.wb-flash{outline:3px solid transparent;outline-offset:6px;border-radius:4px;animation:wb-flash 2s ease-out}' +
|
|
571
|
-
'.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}'
|
|
578
|
+
'.wb-toast-dismiss{margin-right:-4px;padding:0 4px;border-left:1px solid rgb(255 255 255/.35);opacity:.75}.wb-toast-dismiss:hover{opacity:1}' +
|
|
579
|
+
// a toast's details (ToastOptions.details): a ▸ on its line, unfolding them under it
|
|
580
|
+
'.wb-toast{max-width:min(24rem,calc(100vw - 32px));text-align:left}.wb-toast-more{margin:0 -4px 0 -2px;padding:0 4px;opacity:.75}.wb-toast-more:hover{opacity:1}' +
|
|
581
|
+
'.wb-toast[data-open]{flex-wrap:wrap;border-radius:12px}.wb-toast-details{flex-basis:100%;padding:2px 0 3px;font-weight:400;cursor:text}.wb-toast-details[hidden]{display:none}'
|
|
572
582
|
|
|
573
583
|
/** `extras`: what plugins add to <head> and <body> (see shellExtras). */
|
|
574
584
|
function shell(
|
|
@@ -631,24 +641,29 @@ export function createServer(
|
|
|
631
641
|
.map(({ page, type, command, fallback }) => ({ page, type, command, ...(fallback && { fallback }) }))
|
|
632
642
|
|
|
633
643
|
// ---- live changes ------------------------------------------------------------------------------
|
|
634
|
-
// The browser listens at /api/
|
|
635
|
-
// `listeners`: an agent started or stopped waiting; `style`:
|
|
636
|
-
// browser code changed; `scroll`: an agent shows the reader a place
|
|
637
|
-
|
|
638
|
-
|
|
644
|
+
// The browser listens on a WebSocket at /api/live, each message `{ event, data }`. `change`: its
|
|
645
|
+
// page changed; `events`: the log grew; `listeners`: an agent started or stopped waiting; `style`:
|
|
646
|
+
// a stylesheet changed; `reload`: browser code changed; `scroll`: an agent shows the reader a place
|
|
647
|
+
// on the page ({ to }); `elsewhere`: under a shared server, what waits in another project changed.
|
|
648
|
+
// /api/watch says the same as server-sent events, for a tab opened before
|
|
649
|
+
// /api/live: it tells it to reload first, so it moves to the WebSocket (see ws.ts for why).
|
|
650
|
+
|
|
651
|
+
/** A browser following its page; `pending`: what it will be told in a moment. */
|
|
639
652
|
interface WatchClient {
|
|
640
|
-
|
|
653
|
+
send(event: string, data?: unknown): void
|
|
641
654
|
page: string
|
|
642
655
|
isDir: boolean
|
|
643
656
|
pending?: Set<string>
|
|
644
657
|
}
|
|
645
658
|
|
|
646
659
|
const clients = new Set<WatchClient>()
|
|
660
|
+
/** what the browser appended lately, by id: a send it retries is answered with what it got */
|
|
661
|
+
const appended = new Map<string, WbEvent>()
|
|
647
662
|
function notify(client: WatchClient, kind: string) {
|
|
648
663
|
client.pending ??= new Set()
|
|
649
664
|
if (client.pending.size === 0)
|
|
650
665
|
setTimeout(() => {
|
|
651
|
-
for (const k of client.pending!) client.
|
|
666
|
+
for (const k of client.pending!) client.send(k)
|
|
652
667
|
client.pending!.clear()
|
|
653
668
|
}, 60)
|
|
654
669
|
client.pending.add(kind)
|
|
@@ -656,6 +671,11 @@ export function createServer(
|
|
|
656
671
|
const notifyAll = (kind: string) => {
|
|
657
672
|
for (const c of clients) notify(c, kind)
|
|
658
673
|
}
|
|
674
|
+
// who listens shows on this project's pages, and, under a shared server, on the others' (onChange)
|
|
675
|
+
const listenersChanged = () => {
|
|
676
|
+
notifyAll('listeners')
|
|
677
|
+
onChange?.()
|
|
678
|
+
}
|
|
659
679
|
|
|
660
680
|
function pageChanged(id: string) {
|
|
661
681
|
onChange?.()
|
|
@@ -854,7 +874,13 @@ export function createServer(
|
|
|
854
874
|
if (p === '/api/events' && req.method === 'POST') {
|
|
855
875
|
const body = JSON.parse(await readBody(req))
|
|
856
876
|
if (!body.type) return sendJson(res, 400, { error: 'event type required' })
|
|
857
|
-
|
|
877
|
+
// the browser sends it again when it heard nothing back: appended once, the same answer twice
|
|
878
|
+
const again = isEventId(body.id) ? appended.get(body.id) : undefined
|
|
879
|
+
if (again) return sendJson(res, 200, again)
|
|
880
|
+
const event = appendEvent(project.eventsFile, body)
|
|
881
|
+
appended.set(event.id, event)
|
|
882
|
+
if (appended.size > 1000) appended.delete(appended.keys().next().value!)
|
|
883
|
+
return sendJson(res, 200, event)
|
|
858
884
|
}
|
|
859
885
|
// an agent shows the reader a place on a page: every tab with it open scrolls there
|
|
860
886
|
// ({ page, to }: a heading's text, a form's name or any text) → { tabs }
|
|
@@ -865,7 +891,7 @@ export function createServer(
|
|
|
865
891
|
let tabs = 0
|
|
866
892
|
for (const c of clients) {
|
|
867
893
|
if (c.isDir || (c.page !== id && c.page + '/index' !== id)) continue
|
|
868
|
-
c.
|
|
894
|
+
c.send('scroll', { to })
|
|
869
895
|
tabs++
|
|
870
896
|
}
|
|
871
897
|
return sendJson(res, 200, { tabs })
|
|
@@ -914,7 +940,7 @@ export function createServer(
|
|
|
914
940
|
...(fallback && { fallback }),
|
|
915
941
|
}
|
|
916
942
|
listeners.add(l)
|
|
917
|
-
|
|
943
|
+
listenersChanged()
|
|
918
944
|
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
919
945
|
const end = () => {
|
|
920
946
|
clearInterval(ping)
|
|
@@ -927,7 +953,7 @@ export function createServer(
|
|
|
927
953
|
})
|
|
928
954
|
req.on('close', () => {
|
|
929
955
|
end()
|
|
930
|
-
|
|
956
|
+
listenersChanged()
|
|
931
957
|
})
|
|
932
958
|
return
|
|
933
959
|
}
|
|
@@ -945,8 +971,14 @@ export function createServer(
|
|
|
945
971
|
connection: 'keep-alive',
|
|
946
972
|
})
|
|
947
973
|
res.write(': connected\n\n')
|
|
948
|
-
const client = {
|
|
974
|
+
const client: WatchClient = {
|
|
975
|
+
send: (event, data = {}) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
|
|
976
|
+
page: q.page || '',
|
|
977
|
+
isDir: 'dir' in q,
|
|
978
|
+
}
|
|
949
979
|
clients.add(client)
|
|
980
|
+
// a tab from before /api/live: onto the WebSocket, which leaves its connection free
|
|
981
|
+
client.send('reload')
|
|
950
982
|
const ping = setInterval(() => res.write(': ping\n\n'), 25000)
|
|
951
983
|
const end = () => {
|
|
952
984
|
clearInterval(ping)
|
|
@@ -1204,8 +1236,31 @@ export function createServer(
|
|
|
1204
1236
|
return result
|
|
1205
1237
|
}
|
|
1206
1238
|
|
|
1239
|
+
/** The live channel: /api/live, a WebSocket from a page of this server's (see ws.ts). */
|
|
1240
|
+
function upgrade(req: IncomingMessage, conn: Duplex, _head: Buffer) {
|
|
1241
|
+
const url = new URL((req.url ?? '/').replace(/^\/+/, '/'), 'http://localhost')
|
|
1242
|
+
if (decodeURIComponent(url.pathname) !== '/api/live') return refuse(conn, 404, 'Not Found')
|
|
1243
|
+
// no CORS for a WebSocket: any site could open one to localhost, so the origin is checked here
|
|
1244
|
+
if (!sameSite(req)) return refuse(conn, 403, 'Forbidden')
|
|
1245
|
+
const socket = accept(req, conn)
|
|
1246
|
+
if (!socket) return
|
|
1247
|
+
const client: WatchClient = {
|
|
1248
|
+
send: (event, data = {}) => socket.send(JSON.stringify({ event, data })),
|
|
1249
|
+
page: url.searchParams.get('page') ?? '',
|
|
1250
|
+
isDir: url.searchParams.has('dir'),
|
|
1251
|
+
}
|
|
1252
|
+
clients.add(client)
|
|
1253
|
+
const stop = () => socket.close()
|
|
1254
|
+
streams.add(stop)
|
|
1255
|
+
socket.onClose(() => {
|
|
1256
|
+
clients.delete(client)
|
|
1257
|
+
streams.delete(stop)
|
|
1258
|
+
})
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1207
1261
|
return {
|
|
1208
1262
|
handle,
|
|
1263
|
+
upgrade,
|
|
1209
1264
|
listeners: () => listenersFor(null),
|
|
1210
1265
|
async overview() {
|
|
1211
1266
|
await config()
|
|
@@ -1217,11 +1272,12 @@ export function createServer(
|
|
|
1217
1272
|
touch() {
|
|
1218
1273
|
for (const c of clients) if (c.isDir && !c.page) notify(c, 'change')
|
|
1219
1274
|
},
|
|
1275
|
+
elsewhere: () => notifyAll('elsewhere'),
|
|
1220
1276
|
addListener(l) {
|
|
1221
1277
|
listeners.add(l)
|
|
1222
|
-
|
|
1278
|
+
listenersChanged()
|
|
1223
1279
|
return () => {
|
|
1224
|
-
if (listeners.delete(l))
|
|
1280
|
+
if (listeners.delete(l)) listenersChanged()
|
|
1225
1281
|
}
|
|
1226
1282
|
},
|
|
1227
1283
|
status: (page = null) => status(page),
|
package/src/ws.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// A WebSocket that only the server talks on: the page's live channel (/api/live). Not a server-sent
|
|
2
|
+
// event stream because a browser keeps at most six HTTP/1.1 connections to one origin, and every
|
|
3
|
+
// whiteboard tab is on the same one (the shared server): six open tabs, each holding its stream,
|
|
4
|
+
// left no connection for a seventh tab to load, nor for a form's answer to be sent. WebSockets don't
|
|
5
|
+
// count towards that limit.
|
|
6
|
+
//
|
|
7
|
+
// Enough of RFC 6455 for that: the handshake, text frames out, and of what comes in, close and ping
|
|
8
|
+
// (answered); anything else from the browser is read and dropped. A ping goes out every 25 s, so a
|
|
9
|
+
// connection that went away without closing is found and let go.
|
|
10
|
+
import crypto from 'node:crypto'
|
|
11
|
+
import type { IncomingMessage } from 'node:http'
|
|
12
|
+
import type { Duplex } from 'node:stream'
|
|
13
|
+
|
|
14
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
|
|
15
|
+
const PING_EVERY = 25_000
|
|
16
|
+
|
|
17
|
+
export interface Socket {
|
|
18
|
+
/** send one text message; nothing once closed */
|
|
19
|
+
send(text: string): void
|
|
20
|
+
/** close it: a close frame, then the connection ends */
|
|
21
|
+
close(): void
|
|
22
|
+
/** called once, when it closed (either side, or the connection broke) */
|
|
23
|
+
onClose(fn: () => void): void
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Is this request asking to become a WebSocket? */
|
|
27
|
+
export const isUpgrade = (req: IncomingMessage) =>
|
|
28
|
+
(req.headers.upgrade ?? '').toLowerCase() === 'websocket' && !!req.headers['sec-websocket-key']
|
|
29
|
+
|
|
30
|
+
/** Answer the handshake and give the socket; null (and the connection refused) if it isn't one. */
|
|
31
|
+
export function accept(req: IncomingMessage, conn: Duplex): Socket | null {
|
|
32
|
+
const key = req.headers['sec-websocket-key']
|
|
33
|
+
if (!isUpgrade(req) || typeof key !== 'string' || req.headers['sec-websocket-version'] !== '13') {
|
|
34
|
+
refuse(conn, 400, 'Bad Request')
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
const hash = crypto
|
|
38
|
+
.createHash('sha1')
|
|
39
|
+
.update(key + GUID)
|
|
40
|
+
.digest('base64')
|
|
41
|
+
conn.write(
|
|
42
|
+
'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' +
|
|
43
|
+
`Sec-WebSocket-Accept: ${hash}\r\n\r\n`,
|
|
44
|
+
)
|
|
45
|
+
if ('setNoDelay' in conn && typeof conn.setNoDelay === 'function') conn.setNoDelay(true)
|
|
46
|
+
|
|
47
|
+
let open = true
|
|
48
|
+
const closers: (() => void)[] = []
|
|
49
|
+
const ended = () => {
|
|
50
|
+
if (!open) return
|
|
51
|
+
open = false
|
|
52
|
+
clearInterval(ping)
|
|
53
|
+
for (const fn of closers.splice(0)) fn()
|
|
54
|
+
}
|
|
55
|
+
const write = (opcode: number, payload: Buffer) => {
|
|
56
|
+
if (!open || conn.destroyed) return
|
|
57
|
+
conn.write(Buffer.concat([header(opcode, payload.length), payload]))
|
|
58
|
+
}
|
|
59
|
+
let alive = true
|
|
60
|
+
const ping = setInterval(() => {
|
|
61
|
+
// no pong since the last ping: it went away without closing
|
|
62
|
+
if (!alive) return void conn.destroy()
|
|
63
|
+
alive = false
|
|
64
|
+
write(0x9, Buffer.alloc(0))
|
|
65
|
+
}, PING_EVERY)
|
|
66
|
+
ping.unref?.()
|
|
67
|
+
|
|
68
|
+
let buf = Buffer.alloc(0)
|
|
69
|
+
conn.on('data', (chunk: Buffer) => {
|
|
70
|
+
buf = Buffer.concat([buf, chunk])
|
|
71
|
+
for (;;) {
|
|
72
|
+
const frame = parse(buf)
|
|
73
|
+
if (!frame) break
|
|
74
|
+
buf = buf.subarray(frame.size)
|
|
75
|
+
alive = true
|
|
76
|
+
if (frame.opcode === 0x8) {
|
|
77
|
+
write(0x8, frame.payload.subarray(0, 2))
|
|
78
|
+
ended()
|
|
79
|
+
conn.end()
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
if (frame.opcode === 0x9) write(0xa, frame.payload)
|
|
83
|
+
// a browser has nothing to say on this channel: text, binary and pongs are dropped
|
|
84
|
+
}
|
|
85
|
+
// a frame that claims to be huge: not a browser of ours
|
|
86
|
+
if (buf.length > 1 << 20) conn.destroy()
|
|
87
|
+
})
|
|
88
|
+
conn.on('close', ended)
|
|
89
|
+
conn.on('error', () => conn.destroy())
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
send: text => write(0x1, Buffer.from(text, 'utf8')),
|
|
93
|
+
close() {
|
|
94
|
+
if (!open) return
|
|
95
|
+
write(0x8, Buffer.from([0x03, 0xe8])) // 1000: normal closure
|
|
96
|
+
ended()
|
|
97
|
+
conn.end()
|
|
98
|
+
// a peer that never closes its side
|
|
99
|
+
setTimeout(() => conn.destroy(), 1000).unref?.()
|
|
100
|
+
},
|
|
101
|
+
onClose(fn) {
|
|
102
|
+
if (open) closers.push(fn)
|
|
103
|
+
else fn()
|
|
104
|
+
},
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Turn an upgrade down with a plain HTTP response. */
|
|
109
|
+
export function refuse(conn: Duplex, status: number, text: string) {
|
|
110
|
+
if (conn.destroyed) return
|
|
111
|
+
conn.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A frame's header, unmasked as the server sends them, FIN set. */
|
|
115
|
+
function header(opcode: number, length: number): Buffer {
|
|
116
|
+
if (length < 126) return Buffer.from([0x80 | opcode, length])
|
|
117
|
+
if (length < 1 << 16) {
|
|
118
|
+
const h = Buffer.alloc(4)
|
|
119
|
+
h[0] = 0x80 | opcode
|
|
120
|
+
h[1] = 126
|
|
121
|
+
h.writeUInt16BE(length, 2)
|
|
122
|
+
return h
|
|
123
|
+
}
|
|
124
|
+
const h = Buffer.alloc(10)
|
|
125
|
+
h[0] = 0x80 | opcode
|
|
126
|
+
h[1] = 127
|
|
127
|
+
h.writeBigUInt64BE(BigInt(length), 2)
|
|
128
|
+
return h
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** One whole frame at the start of `buf` (unmasked), or null while it hasn't all arrived. */
|
|
132
|
+
function parse(buf: Buffer): { opcode: number; payload: Buffer; size: number } | null {
|
|
133
|
+
if (buf.length < 2) return null
|
|
134
|
+
const opcode = buf[0]! & 0x0f
|
|
135
|
+
const masked = (buf[1]! & 0x80) !== 0
|
|
136
|
+
let length = buf[1]! & 0x7f
|
|
137
|
+
let at = 2
|
|
138
|
+
if (length === 126) {
|
|
139
|
+
if (buf.length < 4) return null
|
|
140
|
+
length = buf.readUInt16BE(2)
|
|
141
|
+
at = 4
|
|
142
|
+
} else if (length === 127) {
|
|
143
|
+
if (buf.length < 10) return null
|
|
144
|
+
const big = buf.readBigUInt64BE(2)
|
|
145
|
+
if (big > BigInt(1 << 20)) return { opcode: 0x8, payload: Buffer.alloc(0), size: buf.length }
|
|
146
|
+
length = Number(big)
|
|
147
|
+
at = 10
|
|
148
|
+
}
|
|
149
|
+
const mask = masked ? buf.subarray(at, at + 4) : null
|
|
150
|
+
if (masked) at += 4
|
|
151
|
+
if (buf.length < at + length) return null
|
|
152
|
+
const payload = Buffer.from(buf.subarray(at, at + length))
|
|
153
|
+
if (mask) for (let i = 0; i < payload.length; i++) payload[i] = payload[i]! ^ mask[i % 4]!
|
|
154
|
+
return { opcode, payload, size: at + length }
|
|
155
|
+
}
|