Team Ai
Modelpublic

Felipe97/llama-cpp-compiled

sourceHugging Faceupdated 21d agoView on Hugging Face
0likes1.2kdownloads
sse.test.ts85 linesDownload Raw Back to unit
1import { parseSseJsonStream } from '$lib/utils/sse';2import { describe, expect, it } from 'vitest';3 4function makeSseResponse(events: string[]): Response {5	const body = events.join('\n\n') + '\n\n';6 7	return new Response(body, {8		headers: { 'content-type': 'text/event-stream' },9		status: 20010	});11}12 13describe('parseSseJsonStream', () => {14	it('yields parsed data for each record', async () => {15		const response = makeSseResponse(['data: {"chunk": "a"}', 'data: {"chunk": "b"}']);16		const collected: unknown[] = [];17 18		for await (const ev of parseSseJsonStream(response)) {19			collected.push(ev.data);20		}21		expect(collected).toEqual([{ chunk: 'a' }, { chunk: 'b' }]);22	});23 24	it('stops on [DONE] sentinel', async () => {25		const response = makeSseResponse([26			'data: {"chunk": "a"}',27			'data: [DONE]',28			'data: {"chunk": "after-done"}'29		]);30		const collected: unknown[] = [];31 32		for await (const ev of parseSseJsonStream(response)) {33			collected.push(ev.data);34		}35		expect(collected).toEqual([{ chunk: 'a' }]);36	});37 38	it('skips malformed JSON records', async () => {39		const response = makeSseResponse([40			'data: {"chunk": "ok"}',41			'data: {not-json}',42			'data: {"chunk": "also-ok"}'43		]);44		const collected: unknown[] = [];45 46		for await (const ev of parseSseJsonStream(response)) {47			collected.push(ev.data);48		}49		expect(collected).toEqual([{ chunk: 'ok' }, { chunk: 'also-ok' }]);50	});51 52	it('handles records split across multiple chunks (partial last line)', async () => {53		const full = 'data: {"chunk": "x"}\n\ndata: {"chunk": "y"}\n\n';54		const stream = new ReadableStream<Uint8Array>({55			start(controller) {56				const enc = new TextEncoder();57 58				controller.enqueue(enc.encode(full.slice(0, full.length / 2)));59				controller.enqueue(enc.encode(full.slice(full.length / 2)));60				controller.close();61			}62		});63		const response = new Response(stream, {64			headers: { 'content-type': 'text/event-stream' },65			status: 20066		});67		const collected: unknown[] = [];68 69		for await (const ev of parseSseJsonStream(response)) {70			collected.push(ev.data);71		}72		expect(collected).toEqual([{ chunk: 'x' }, { chunk: 'y' }]);73	});74 75	it('returns immediately if response has no body', async () => {76		const response = new Response(null, { status: 200 });77		const collected: unknown[] = [];78 79		for await (const ev of parseSseJsonStream(response)) {80			collected.push(ev.data);81		}82		expect(collected).toEqual([]);83	});84});85