* Build a raw SSE body string from an array of event objects. * Each event becomes: (optional comment) + (optional id) + (optional event) + * data lines + blank line. The terminating [DONE] event is added at the end.
(events: Array<{
data?: string;
event?: string;
id?: string;
comment?: string;
}>)
| 8 | * data lines + blank line. The terminating [DONE] event is added at the end. |
| 9 | */ |
| 10 | function buildSSE(events: Array<{ |
| 11 | data?: string; |
| 12 | event?: string; |
| 13 | id?: string; |
| 14 | comment?: string; |
| 15 | }>): string { |
| 16 | const lines: string[] = []; |
| 17 | for (const ev of events) { |
| 18 | if (ev.comment) lines.push(`: ${ev.comment}`); |
| 19 | if (ev.id) lines.push(`id: ${ev.id}`); |
| 20 | if (ev.event) lines.push(`event: ${ev.event}`); |
| 21 | if (ev.data !== undefined) { |
| 22 | for (const dl of ev.data.split('\n')) lines.push(`data: ${dl}`); |
| 23 | } |
| 24 | lines.push(''); // blank line terminates this event |
| 25 | } |
| 26 | // [DONE] terminator — sent as a normal data event that callers check for |
| 27 | lines.push('data: [DONE]'); |
| 28 | return lines.join('\n'); |
| 29 | } |
| 30 | |
| 31 | function sseResponse(events: Parameters<typeof buildSSE>[0]): Response { |
| 32 | return new Response(buildSSE(events), { |