Open History to see the last commit
1/** Emits one verified data event followed by its durable control checkpoint. */
2export function* encodeSsePage(bytes: Buffer, hasData: boolean, binary: boolean, control: Readonly<Record<string, unknown>>): Generator<Uint8Array> {
3 if (hasData) {
4 yield Buffer.from('event: data\ndata:')
5 if (binary) {
6 // Every intermediate base64 fragment ends at a complete three-byte unit.
7 for (let position = 0; position < bytes.length; position += 49152) yield Buffer.from(bytes.subarray(position, position + 49152).toString('base64'))
8 } else {
9 const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
10 let previousCR = false
11 const fragment = (text: string) => {
12 if (!text.length) return ''
13 if (previousCR && text.startsWith('\n')) text = text.slice(1)
14 previousCR = text.endsWith('\r')
15 return text.replace(/\r\n|\r/g, '\n').replace(/\n/g, '\ndata:')
16 }
17 for (let position = 0; position < bytes.length; position += 8192) {
18 const text = fragment(decoder.decode(bytes.subarray(position, position + 8192), { stream: true }))
19 if (text) yield Buffer.from(text)
20 }
21 const tail = fragment(decoder.decode())
22 if (tail) yield Buffer.from(tail)
23 }
24 yield Buffer.from('\n\n')
25 }
26 yield Buffer.from(`event: control\ndata:${JSON.stringify(control)}\n\n`)
27}