| 12345678910111213141516171819202122232425262728 |
- import type { SseEventType } from './types';
- export interface ParsedSseEvent {
- type: SseEventType;
- data: Record<string, unknown>;
- }
- export function parseSseChunk(previous: string, chunk: string): { events: ParsedSseEvent[]; remainder: string } {
- const buffer = previous + chunk;
- const rawEvents = buffer.split('\n\n');
- const remainder = rawEvents.pop() ?? '';
- const events: ParsedSseEvent[] = [];
- for (const raw of rawEvents) {
- const eventMatch = raw.match(/^event:\s*(.+)$/m);
- const dataMatch = raw.match(/^data:\s*(.+)$/m);
- if (!eventMatch || !dataMatch) continue;
- const type = eventMatch[1].trim() as SseEventType;
- try {
- events.push({ type, data: JSON.parse(dataMatch[1]) });
- } catch {
- events.push({ type: 'error', data: { message: 'SSE 数据解析失败' } });
- }
- }
- return { events, remainder };
- }
|