@bigmistqke/whiteboard 0.6.1 → 0.8.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.
Files changed (101) hide show
  1. package/README.md +23 -216
  2. package/bin/whiteboard.ts +82 -239
  3. package/dist/bin/whiteboard.js +70 -200
  4. package/dist/client/runtime.js +297 -61
  5. package/dist/plugins/badge/README.md +3 -1
  6. package/dist/plugins/badge/public/style.css +17 -0
  7. package/dist/plugins/chat/public/client.js +2 -2
  8. package/dist/plugins/chat/public/style.css +19 -6
  9. package/dist/plugins/code/README.md +10 -0
  10. package/dist/plugins/code/index.js +31 -22
  11. package/dist/plugins/code/public/client.js +1 -0
  12. package/dist/plugins/code/public/style.css +33 -2
  13. package/dist/plugins/comments/public/client.js +7 -2
  14. package/dist/plugins/comments/public/style.css +4 -0
  15. package/dist/plugins/form/public/style.css +2 -0
  16. package/dist/plugins/grid/public/style.css +0 -5
  17. package/dist/plugins/iframe/index.js +2 -2
  18. package/dist/plugins/index.js +5 -1
  19. package/dist/plugins/lightbox/public/client.js +1 -1
  20. package/dist/plugins/terminal/index.js +7 -9
  21. package/dist/plugins/terminal/public/client.js +1 -1
  22. package/dist/plugins/terminal/public/style.css +3 -3
  23. package/dist/plugins/timeline/README.md +40 -0
  24. package/dist/plugins/timeline/index.js +82 -0
  25. package/dist/plugins/timeline/public/style.css +118 -0
  26. package/dist/plugins/toc/README.md +13 -13
  27. package/dist/plugins/toc/index.js +6 -4
  28. package/dist/plugins/toc/public/client.js +1 -1
  29. package/dist/plugins/toc/public/style.css +19 -2
  30. package/dist/plugins/window/index.js +4 -4
  31. package/dist/solid/index.js +2 -1
  32. package/dist/src/auth.js +7 -3
  33. package/dist/src/build.js +159 -0
  34. package/dist/src/client/page/base.css +74 -35
  35. package/dist/src/client/page/main.js +16 -5
  36. package/dist/src/document.js +93 -0
  37. package/dist/src/events.js +7 -15
  38. package/dist/src/hub.js +90 -53
  39. package/dist/src/listen.js +100 -0
  40. package/dist/src/listeners.js +67 -0
  41. package/dist/src/pages/index.js +1 -1
  42. package/dist/src/pages/markdown.js +23 -11
  43. package/dist/src/pages/render.js +13 -8
  44. package/dist/src/serve.js +2 -0
  45. package/dist/src/server.js +204 -514
  46. package/dist/src/site.js +173 -0
  47. package/dist/src/status.js +63 -1
  48. package/dist/src/ws.js +128 -0
  49. package/package.json +1 -1
  50. package/plugins/README.md +258 -0
  51. package/plugins/badge/README.md +3 -1
  52. package/plugins/badge/public/style.css +17 -0
  53. package/plugins/chat/client.tsx +34 -6
  54. package/plugins/chat/public/style.css +19 -6
  55. package/plugins/code/README.md +10 -0
  56. package/plugins/code/client.ts +73 -0
  57. package/plugins/code/index.ts +38 -26
  58. package/plugins/code/public/style.css +33 -2
  59. package/plugins/comments/client.ts +56 -6
  60. package/plugins/comments/public/style.css +4 -0
  61. package/plugins/form/public/style.css +2 -0
  62. package/plugins/grid/public/style.css +0 -5
  63. package/plugins/iframe/index.ts +2 -2
  64. package/plugins/index.ts +6 -1
  65. package/plugins/lightbox/client.ts +13 -3
  66. package/plugins/terminal/client.ts +10 -2
  67. package/plugins/terminal/index.ts +8 -6
  68. package/plugins/terminal/public/style.css +3 -3
  69. package/plugins/timeline/README.md +40 -0
  70. package/plugins/timeline/index.ts +92 -0
  71. package/plugins/timeline/public/style.css +118 -0
  72. package/plugins/toc/README.md +13 -13
  73. package/plugins/toc/client.ts +58 -32
  74. package/plugins/toc/index.ts +13 -13
  75. package/plugins/toc/public/style.css +19 -2
  76. package/plugins/window/index.ts +4 -4
  77. package/skills/whiteboard/SKILL.md +3 -1
  78. package/solid/index.tsx +3 -0
  79. package/src/auth.ts +7 -2
  80. package/src/build.ts +213 -0
  81. package/src/client/forms.ts +102 -5
  82. package/src/client/page/base.css +74 -35
  83. package/src/client/page/elsewhere.ts +14 -4
  84. package/src/client/page/waiting.ts +10 -5
  85. package/src/client/read.ts +16 -3
  86. package/src/client/runtime.ts +219 -52
  87. package/src/client/toast.ts +36 -6
  88. package/src/define.ts +44 -18
  89. package/src/document.ts +191 -0
  90. package/src/events.ts +18 -17
  91. package/src/hub.ts +102 -56
  92. package/src/listen.ts +125 -0
  93. package/src/listeners.ts +95 -0
  94. package/src/pages/index.ts +1 -1
  95. package/src/pages/markdown.ts +29 -18
  96. package/src/pages/render.ts +13 -8
  97. package/src/serve.ts +2 -0
  98. package/src/server.ts +223 -611
  99. package/src/site.ts +165 -0
  100. package/src/status.ts +100 -0
  101. package/src/ws.ts +155 -0
package/src/site.ts ADDED
@@ -0,0 +1,165 @@
1
+ // Where things are, for the pages: a page's id ↔ its file ↔ its address, its source with its
2
+ // frontmatter (parsed here, once), the folders of pages, and the address of a file a page links
3
+ // to. The server serves a project through one (servedSite); `whiteboard build` writes one out (see
4
+ // build.ts), with ids, files and addresses of its own.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { parse as parseYaml } from 'yaml'
8
+ import type { Project } from './config.ts'
9
+ import type { PageSource, PagesSource, StoredPage } from './define.ts'
10
+
11
+ /** Folders never shown or served: what a repository keeps for its tools. */
12
+ export const SKIP_DIRS = new Set(['node_modules', '.git'])
13
+
14
+ /** A page's frontmatter: YAML between `---` lines, at the very start. */
15
+ export const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/
16
+
17
+ /** Is `file` the folder `dir` or inside it? */
18
+ export const within = (file: string, dir: string) => file === dir || file.startsWith(dir + path.sep)
19
+
20
+ /** Resolve a path inside a base folder, refusing anything that escapes it. */
21
+ export function inside(base: string, rel: string): string | null {
22
+ const p = path.resolve(base, '.' + path.posix.normalize('/' + rel))
23
+ return within(p, base) ? p : null
24
+ }
25
+
26
+ /** A page's frontmatter, parsed as YAML; empty, with the reason, when it isn't fields. */
27
+ export function parseFrontmatter(source: string): { data: Record<string, unknown>; error: string | null } {
28
+ const m = FRONTMATTER.exec(source)
29
+ if (!m) return { data: {}, error: null }
30
+ let data: unknown
31
+ try {
32
+ data = parseYaml(m[1]!)
33
+ } catch (err) {
34
+ return { data: {}, error: (err as Error).message }
35
+ }
36
+ if (data == null) return { data: {}, error: null }
37
+ if (typeof data !== 'object' || Array.isArray(data))
38
+ return { data: {}, error: 'it must be fields (`key: value` lines), not a single value or a list' }
39
+ return { data: data as Record<string, unknown>, error: null }
40
+ }
41
+
42
+ /** A markdown file as a page: its source, the body after its frontmatter, and the frontmatter parsed. */
43
+ export function pageSource(id: string, file: string): PageSource {
44
+ const source = fs.readFileSync(file, 'utf8')
45
+ const { data, error } = parseFrontmatter(source)
46
+ return {
47
+ kind: 'page',
48
+ id,
49
+ file,
50
+ mtime: fs.statSync(file).mtimeMs,
51
+ source,
52
+ body: source.replace(FRONTMATTER, ''),
53
+ frontmatter: data,
54
+ frontmatterError: error,
55
+ }
56
+ }
57
+
58
+ /** Text files show as files; anything with a NUL byte near the start is binary. */
59
+ function isText(file: string): boolean {
60
+ const fd = fs.openSync(file, 'r')
61
+ const buf = Buffer.alloc(8192)
62
+ const n = fs.readSync(fd, buf, 0, buf.length, 0)
63
+ fs.closeSync(fd)
64
+ return !buf.subarray(0, n).includes(0)
65
+ }
66
+
67
+ /** A repository file's id: `-/` and its path in the project (`-` for the project's folder). */
68
+ export const isRepoId = (id: string) => id === '-' || id.startsWith('-/')
69
+
70
+ /** A project as the server serves it: its pages under its base, its files under `-/` when it serves them. */
71
+ export interface ServedSite {
72
+ /**
73
+ * A page id → the stored page, or { raw: file } (serve the bytes), or null (nothing there). A
74
+ * folder of pages without an index lists its pages; a repository folder lists its entries.
75
+ */
76
+ page(id: string): StoredPage | { raw: string } | null
77
+ /** The pages in a folder of the pages folder, newest first (what waits on each is the status's). */
78
+ pagesIn(dir: string): PagesSource['pages']
79
+ /** The address that serves a file or folder on disk, or null when nothing here serves it. */
80
+ urlOf(file: string): string | null
81
+ /** For links: the target if it exists (also with .md added), as its address. */
82
+ urlFor(file: string): string | null
83
+ }
84
+
85
+ /**
86
+ * The project as its server serves it, below `base`. `files()` says whether it serves the project's
87
+ * own files (`-/…`), which the config can change while it runs.
88
+ */
89
+ export function servedSite(project: Project, { base, files }: { base: string; files: () => boolean }): ServedSite {
90
+ function pagesIn(dir: string): PagesSource['pages'] {
91
+ const out: PagesSource['pages'] = []
92
+ const walk = (d: string) => {
93
+ if (!fs.existsSync(d)) return
94
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
95
+ if (ent.name.startsWith('.') || ent.name === 'node_modules') continue
96
+ const full = path.join(d, ent.name)
97
+ if (ent.isDirectory()) walk(full)
98
+ else if (ent.name.endsWith('.md')) {
99
+ const id = path.relative(project.pagesDir, full).split(path.sep).join('/').replace(/\.md$/, '')
100
+ out.push({ id, file: full, mtime: fs.statSync(full).mtimeMs, lastEvent: null, awaiting: 0 })
101
+ }
102
+ }
103
+ }
104
+ walk(dir)
105
+ return out.sort((a, b) => b.mtime - a.mtime)
106
+ }
107
+
108
+ function page(id: string): StoredPage | { raw: string } | null {
109
+ if (!id) return { kind: 'pages', id: '', file: project.pagesDir, mtime: null, pages: pagesIn(project.pagesDir) }
110
+ if (isRepoId(id)) {
111
+ const target = inside(project.dir, id.slice(2))
112
+ if (!target || path.relative(project.dir, target).split(path.sep).includes('.git') || !fs.existsSync(target))
113
+ return null
114
+ const stat = fs.statSync(target)
115
+ if (stat.isDirectory()) {
116
+ const entries = fs
117
+ .readdirSync(target, { withFileTypes: true })
118
+ .filter(e => !SKIP_DIRS.has(e.name) && e.name !== '.DS_Store')
119
+ .map(e => ({ name: e.name, dir: e.isDirectory() }))
120
+ .sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
121
+ return { kind: 'folder', id, file: target, mtime: stat.mtimeMs, entries }
122
+ }
123
+ if (/\.(md|markdown)$/i.test(target)) return pageSource(id, target)
124
+ if (stat.size > 1e6 || !isText(target)) return { raw: target }
125
+ return { kind: 'file', id, file: target, mtime: stat.mtimeMs, source: fs.readFileSync(target, 'utf8') }
126
+ }
127
+ const target = inside(project.pagesDir, id)
128
+ if (!target) return null
129
+ if (path.extname(id) && fs.existsSync(target) && fs.statSync(target).isFile()) return { raw: target }
130
+ if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {
131
+ const index = path.join(target, 'index.md')
132
+ if (fs.existsSync(index)) return pageSource(id, index)
133
+ return { kind: 'pages', id, file: target, mtime: null, pages: pagesIn(target) }
134
+ }
135
+ const file = target + '.md'
136
+ return fs.existsSync(file) ? pageSource(id, file) : null
137
+ }
138
+
139
+ function urlOf(abs: string): string | null {
140
+ const rel = (dir: string) => path.relative(dir, abs).split(path.sep).map(encodeURIComponent).join('/')
141
+ if (within(abs, project.pagesDir)) return `${base}/${rel(project.pagesDir).replace(/\.md$/, '')}`
142
+ if (files() && within(abs, project.dir)) {
143
+ if (
144
+ rel(project.dir)
145
+ .split('/')
146
+ .some(part => SKIP_DIRS.has(part))
147
+ )
148
+ return null
149
+ return `${base}/-/${rel(project.dir)}`
150
+ }
151
+ return null
152
+ }
153
+
154
+ function urlFor(abs: string): string | null {
155
+ for (const candidate of [abs, abs + '.md']) {
156
+ if (fs.existsSync(candidate)) {
157
+ const url = urlOf(candidate)
158
+ if (url) return url + (fs.statSync(candidate).isDirectory() && !url.endsWith('/') ? '/' : '')
159
+ }
160
+ }
161
+ return null
162
+ }
163
+
164
+ return { page, pagesIn, urlOf, urlFor }
165
+ }
package/src/status.ts CHANGED
@@ -71,6 +71,13 @@ export const heard = (name: string, listeners: Listener[]): boolean =>
71
71
  /** The type of the event the page appends once messages were in view: `{ ids }`. */
72
72
  export const READ = 'whiteboard:read'
73
73
 
74
+ /**
75
+ * The type of the event `whiteboard scroll` appends: show the reader a place on a page, `{ to }`. A
76
+ * page applies the latest one that came after it loaded, as it comes or once its live channel is
77
+ * back.
78
+ */
79
+ export const SCROLL = 'whiteboard:scroll'
80
+
74
81
  /**
75
82
  * The agent's messages on a page the reader hasn't read: events from the agent of a type
76
83
  * `isMessage` says is for the reader, not named by a `whiteboard:read` from the reader, and not
@@ -90,6 +97,99 @@ export function unreadMessages(events: WbEvent[], isMessage: (type: string) => b
90
97
  /** How many things on a page wait for the reader: its open questions and unread messages. */
91
98
  export const awaiting = (p: Pick<PageStatus, 'open' | 'unread'>): number => p.open.length + p.unread.length
92
99
 
100
+ /** The type of the event that says another event was handed to an agent: `{ event: <its id> }`. */
101
+ export const PICKED = 'whiteboard:picked'
102
+
103
+ /**
104
+ * The type of the event `whiteboard new` appends when an agent session creates a page:
105
+ * `{ session }`. The colon keeps it apart from form names, which are event types too.
106
+ */
107
+ export const CLAIM = 'whiteboard:claim'
108
+
109
+ /** The ids of the events that were picked up. Only the command line's picks count. */
110
+ export function pickedUp(events: WbEvent[]): Set<string> {
111
+ return new Set(events.filter(e => e.type === PICKED && !fromReader(e)).map(e => String(e.data?.event)))
112
+ }
113
+
114
+ /** A page as the snapshot needs it; its questions (`asks`) are its named forms. */
115
+ export interface StatusPage {
116
+ id: string
117
+ file: string
118
+ title: string
119
+ asks: string[]
120
+ }
121
+
122
+ /** What a project's status is made of: no disk in it, the server reads and hands it over. */
123
+ export interface StatusInput {
124
+ pages: StatusPage[]
125
+ /** the whole log */
126
+ events: WbEvent[]
127
+ /** the running waits and watches covering a page */
128
+ listeners: (page: string) => Listener[]
129
+ /** the event types handed to an agent (a form's answers; plugins' events declared handOut) */
130
+ forAgent: (type: string) => boolean
131
+ /** the event types that are messages for the reader (declared forReader) */
132
+ forReader: (type: string) => boolean
133
+ }
134
+
135
+ /** A project's status at one moment: what `whiteboard status`, the page lists and the log's marks take. */
136
+ export interface ProjectStatus {
137
+ /** per page, in the order given */
138
+ pages: PageStatus[]
139
+ /** the events that were picked up, by id */
140
+ picked: Set<string>
141
+ /** when the reader last sent something on a page (what the agent appended doesn't count) */
142
+ lastAnswered: (page: string) => string | null
143
+ }
144
+
145
+ /**
146
+ * A project's status from its pages, its log and who listens: per page its questions and where each
147
+ * stands, what is open and unheard, the agent's messages unread, the reader's events not picked up,
148
+ * and who listens; which events were picked up; when each page was last answered. The log is
149
+ * gone through once.
150
+ */
151
+ export function projectStatus({ pages, events, listeners, forAgent, forReader }: StatusInput): ProjectStatus {
152
+ const picked = pickedUp(events)
153
+ const byPage = new Map<string, WbEvent[]>()
154
+ const owner = new Map<string, string | null>()
155
+ const last = new Map<string, string>()
156
+ for (const e of events) {
157
+ let list = byPage.get(e.page)
158
+ if (!list) byPage.set(e.page, (list = []))
159
+ list.push(e)
160
+ if (fromReader(e)) last.set(e.page, e.ts)
161
+ else if (e.type === CLAIM) owner.set(e.page, (e.data?.session as string | undefined) ?? null)
162
+ }
163
+ return {
164
+ picked,
165
+ lastAnswered: page => last.get(page) ?? null,
166
+ pages: pages.map(p => {
167
+ const own = byPage.get(p.id) ?? []
168
+ const listening = listeners(p.id)
169
+ // where each question stands, as the page shows it
170
+ const questions = p.asks.map(name => ({
171
+ name,
172
+ state: questionState(name, own, listening, id => picked.has(id)).state,
173
+ }))
174
+ const open = questions.filter(q => q.state === 'open').map(q => q.name)
175
+ return {
176
+ page: p.id,
177
+ title: p.title,
178
+ file: p.file,
179
+ owner: owner.get(p.id) ?? null,
180
+ asks: p.asks,
181
+ questions,
182
+ open,
183
+ unheard: open.filter(name => !heard(name, listening)),
184
+ unread: unreadMessages(own, forReader),
185
+ // the reader's events for an agent: a form's answers, and plugin events declared handOut
186
+ unpicked: own.filter(e => fromReader(e) && forAgent(e.type) && !picked.has(e.id)),
187
+ listeners: listening,
188
+ }
189
+ }),
190
+ }
191
+ }
192
+
93
193
  /**
94
194
  * What is open on a page, one short line each; the command that picks it up comes last, once.
95
195
  * `file` is how to name the page's file to the reader (relative to where they are). Without
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
+ }