* One open SSE connection, with the frames it has received so far. * * The parser is the whole SSE grammar this server uses: `retry:`, `event:`, * `data:` and a blank line. Comment frames (`: ping`) are counted separately — * they are the heartbeat, and a client must never see them as events.
| 79 | * they are the heartbeat, and a client must never see them as events. |
| 80 | */ |
| 81 | class Stream { |
| 82 | readonly events: SseEvent[] = []; |
| 83 | comments = 0; |
| 84 | status = 0; |
| 85 | contentType: string | undefined; |
| 86 | private buffer = ''; |
| 87 | private req: http.ClientRequest | null = null; |
| 88 | private res: http.IncomingMessage | null = null; |
| 89 | |
| 90 | open(requestPath = '/api/events'): Promise<void> { |
| 91 | return new Promise((resolve, reject) => { |
| 92 | const req = http.request( |
| 93 | { |
| 94 | host: '127.0.0.1', |
| 95 | port: server.port, |
| 96 | path: requestPath, |
| 97 | method: 'GET', |
| 98 | headers: { Host: `127.0.0.1:${server.port}`, Accept: 'text/event-stream' }, |
| 99 | setHost: false, |
| 100 | }, |
| 101 | (res) => { |
| 102 | this.res = res; |
| 103 | this.status = res.statusCode ?? 0; |
| 104 | this.contentType = res.headers['content-type']; |
| 105 | res.setEncoding('utf-8'); |
| 106 | res.on('data', (chunk: string) => this.ingest(chunk)); |
| 107 | resolve(); |
| 108 | } |
| 109 | ); |
| 110 | this.req = req; |
| 111 | req.on('error', reject); |
| 112 | req.end(); |
| 113 | }); |
| 114 | } |
| 115 | |
| 116 | private ingest(chunk: string): void { |
| 117 | this.buffer += chunk; |
| 118 | let split = this.buffer.indexOf('\n\n'); |
| 119 | while (split !== -1) { |
| 120 | const frame = this.buffer.slice(0, split); |
| 121 | this.buffer = this.buffer.slice(split + 2); |
| 122 | this.parse(frame); |
| 123 | split = this.buffer.indexOf('\n\n'); |
| 124 | } |
| 125 | // A heartbeat is its own frame and ends the same way, but node may deliver |
| 126 | // it alone; the loop above already handled it. |
| 127 | } |
| 128 | |
| 129 | private parse(frame: string): void { |
| 130 | let name = 'message'; |
| 131 | let data = ''; |
| 132 | for (const line of frame.split('\n')) { |
| 133 | if (line.startsWith(':')) { |
| 134 | this.comments += 1; |
| 135 | continue; |
| 136 | } |
| 137 | if (line.startsWith('event: ')) name = line.slice(7); |
| 138 | else if (line.startsWith('data: ')) data += line.slice(6); |
nothing calls this directly
no outgoing calls
no test coverage detected