import { afterEach, describe, expect, it, vi } from "vitest"; import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js"; import { subscribeToRealtime, type RealtimeEventSourceLike, type RealtimeMessageEvent, type RealtimeSubscriberDiagnostic, type RealtimeSubscriberOptions, } from "./client.js"; const item: NotificationStreamItem = { id: "delivery_cb_1", cursor: "2026-05-08T20:00:00.000Z:delivery_cb_1", tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "billing", messageKey: "invoice.ready", status: "SENT", attemptsMade: 1, createdAt: "2026-05-08T19:59:00.000Z", updatedAt: "2026-05-08T20:00:00.000Z", sentAt: "2026-05-08T20:00:00.000Z", readAt: null, }; const baseEvent = { cursor: item.cursor, requestId: "req_cb_1", tenantId: "tenant_1", userId: "user_1" }; class FakeEventSource implements RealtimeEventSourceLike { static instances: FakeEventSource[] = []; readonly listeners = new Map void>>(); onopen: (() => void) | null = null; onmessage: ((event: RealtimeMessageEvent) => void) | null = null; onerror: ((event: unknown) => void) | null = null; closed = false; constructor(readonly url: string | URL) { FakeEventSource.instances.push(this); } emit(data: unknown): void { this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) }); } addEventListener(type: string, listener: (event: RealtimeMessageEvent) => void): void { const listeners = this.listeners.get(type) ?? []; listeners.push(listener); this.listeners.set(type, listeners); } close(): void { this.closed = true; } } function createSubscriber(overrides: Partial = {}) { FakeEventSource.instances = []; const diagnostics: RealtimeSubscriberDiagnostic[] = []; const subscriber = subscribeToRealtime({ ...overrides, url: overrides.url ?? "https://example.test/stream", EventSource: overrides.EventSource ?? FakeEventSource, onDiagnostic: (diagnostic) => diagnostics.push(diagnostic), }); return { diagnostics, source: FakeEventSource.instances[0], subscriber }; } describe("realtime client subscriber edge cases", () => { const originalEventSource = (globalThis as { EventSource?: unknown }).EventSource; afterEach(() => { if (originalEventSource === undefined) { delete (globalThis as { EventSource?: unknown }).EventSource; } else { (globalThis as { EventSource?: unknown }).EventSource = originalEventSource; } }); it("exposes the active source via the source getter", () => { const { source, subscriber } = createSubscriber(); expect(subscriber.source).toBe(source); expect(subscriber.currentSource).toBe(source); }); it("falls back to the global EventSource when no constructor is provided", () => { FakeEventSource.instances = []; (globalThis as { EventSource?: unknown }).EventSource = FakeEventSource; const subscriber = subscribeToRealtime({ url: "https://example.test/global" }); expect(FakeEventSource.instances).toHaveLength(1); expect(subscriber.source).toBe(FakeEventSource.instances[0]); subscriber.close(); }); it("throws a guidance error when no EventSource is available at all", () => { delete (globalThis as { EventSource?: unknown }).EventSource; expect(() => subscribeToRealtime({ url: "https://example.test/none" })).toThrow( /EventSource is not available; provide an EventSource option/, ); }); it("silently ignores valid events when no matching callback is registered", () => { const { diagnostics, source } = createSubscriber(); expect(() => source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] }), ).not.toThrow(); expect(diagnostics).toEqual([]); }); it("emits a context-free diagnostic when the parsed payload is not an object", () => { const { diagnostics, source } = createSubscriber(); source.emit("42"); expect(diagnostics).toEqual([{ phase: "validation", message: "realtime event must be an object" }]); }); it("omits diagnostic context fields when envelope identifiers are not strings", () => { const { diagnostics, source } = createSubscriber(); source.emit({ event: 5, cursor: 6, requestId: 7 }); // toEqual treats `undefined` context fields as absent, proving non-string ids are dropped. expect(diagnostics).toEqual([{ phase: "validation", message: "event must be a supported realtime event name" }]); expect(diagnostics[0].eventName).toBeUndefined(); }); it("uses a generic message when a callback throws a non-Error value", () => { const onKeepalive = vi.fn(() => { throw "raw string failure with token=secret"; }); const { diagnostics, source } = createSubscriber({ onKeepalive }); source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive }); expect(onKeepalive).toHaveBeenCalledTimes(1); expect(diagnostics).toEqual([ { phase: "callback", message: "Realtime subscriber rejected an invalid event.", eventName: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "req_cb_1", }, ]); expect(JSON.stringify(diagnostics)).not.toContain("token=secret"); }); });