// @vitest-environment node import { describe, expect, it } from "vitest"; import { createSseClient } from "./generated/core/serverSentEvents.gen.js"; const encoder = new TextEncoder(); function streamChunks(chunks: Array, options: { errorAfterChunks?: Error } = {}) { let index = 0; return new ReadableStream({ pull(controller) { if (index < chunks.length) { controller.enqueue(encoder.encode(chunks[index])); index += 1; return; } if (options.errorAfterChunks) { controller.error(options.errorAfterChunks); return; } controller.close(); }, }); } function requestCompatibleSignal() { return new Request("https://signal.example.test").signal; } describe("generated SSE client", () => { it("parses events, transforms JSON payloads, and resumes retries with Last-Event-ID", async () => { const requests: Array = []; const events: Array = []; const retryDelays: Array = []; const errors: Array = []; const client = createSseClient<{ kind: string; count: number }>({ fetch: async (requestInfo) => { const request = requestInfo as Request; requests.push(request); if (requests.length === 1) { return new Response( streamChunks( [ "id: cursor-1\r\nevent: snapshot\r\nretry: 25\r\ndata: {\"kind\":\"snapshot\",\"count\":1}\r\n\r\n", ], { errorAfterChunks: new Error("socket closed") } ), { headers: { "Content-Type": "text/event-stream" } } ); } expect(request.headers.get("Last-Event-ID")).toBe("cursor-1"); return new Response(streamChunks(["event: notification\ndata: plain text\n\n"]), { headers: { "Content-Type": "text/event-stream" }, }); }, onSseError: (error) => errors.push(error), onSseEvent: (event) => events.push(event), responseTransformer: async (data) => ({ ...(data as Record), transformed: true }), responseValidator: async (data) => { expect(data).toEqual({ kind: "snapshot", count: 1 }); }, signal: requestCompatibleSignal(), sseMaxRetryAttempts: 2, sseSleepFn: async (ms) => { retryDelays.push(ms); }, url: "https://api.example.test/v1/notifications/stream", }); await expect(client.stream.next()).resolves.toEqual({ done: false, value: { kind: "snapshot", count: 1, transformed: true }, }); await expect(client.stream.next()).resolves.toEqual({ done: false, value: "plain text", }); await expect(client.stream.next()).resolves.toEqual({ done: true, value: undefined, }); expect(requests).toHaveLength(2); expect(requests[0].headers.has("Last-Event-ID")).toBe(false); expect(events).toEqual([ { data: { kind: "snapshot", count: 1, transformed: true }, event: "snapshot", id: "cursor-1", retry: 25, }, { data: "plain text", event: "notification", id: "cursor-1", retry: 25, }, ]); expect(errors).toHaveLength(1); expect(retryDelays).toEqual([25]); }); it("reports failed responses and stops when retry attempts are exhausted", async () => { const errors: Array = []; const client = createSseClient({ fetch: async () => new Response("nope", { status: 503, statusText: "Unavailable" }), onSseError: (error) => errors.push(error), signal: requestCompatibleSignal(), sseMaxRetryAttempts: 1, sseSleepFn: async () => { throw new Error("sleep should not run after final attempt"); }, url: "https://api.example.test/v1/notifications/stream", }); await expect(client.stream.next()).resolves.toEqual({ done: true, value: undefined, }); expect(errors).toHaveLength(1); expect(errors[0]).toBeInstanceOf(Error); expect((errors[0] as Error).message).toBe("SSE failed: 503 Unavailable"); }); });