import { randomInt } from "crypto"; import { FetchResponse } from "ofetch"; import { assertType, test } from "vitest"; import { _handleResponse, EventSourcePlusOptions, OnResponseContext, } from "./event-source"; import { wait } from "./internal"; test("Header Type Inference", () => { type HeaderInput = EventSourcePlusOptions["headers"]; assertType(undefined); assertType({ Authorization: "test", }); assertType({ Authorization: undefined, }); assertType(() => { if (randomInt(100) >= 50) { return { Authorization: "test", }; } return {}; }); assertType(async () => { await wait(500); if (randomInt(100) >= 50) { return { Authorization: "test", }; } return {}; }); }); test("onResponse passes with valid response", async () => { const headers = new Headers(); headers.set("Content-Type", "text/event-stream"); const res: FetchResponse = { headers: headers, ok: true, redirected: false, status: 200, statusText: "Ok", type: "default", url: "", clone: function (): Response { throw new Error("Function not implemented."); }, body: null, bodyUsed: false, arrayBuffer: function (): Promise { throw new Error("Function not implemented."); }, blob: function (): Promise { throw new Error("Function not implemented."); }, formData: function (): Promise { throw new Error("Function not implemented."); }, json: function (): Promise { throw new Error("Function not implemented."); }, text: function (): Promise { throw new Error("Function not implemented."); }, } as any; const context: OnResponseContext = { request: {} as any, response: res, options: { headers: new Headers(), }, }; await _handleResponse(context, { onMessage() {}, }); }); test.fails( "onResponse throws when Content-Type header is undefined", async () => { const res: FetchResponse = { headers: new Headers(), ok: true, redirected: false, status: 200, statusText: "Ok", type: "default", url: "", clone: function (): Response { throw new Error("Function not implemented."); }, body: null, bodyUsed: false, arrayBuffer: function (): Promise { throw new Error("Function not implemented."); }, blob: function (): Promise { throw new Error("Function not implemented."); }, formData: function (): Promise { throw new Error("Function not implemented."); }, json: function (): Promise { throw new Error("Function not implemented."); }, text: function (): Promise { throw new Error("Function not implemented."); }, } as any; const context: OnResponseContext = { request: {} as any, response: res, options: { headers: new Headers(), }, }; await _handleResponse(context, { onMessage: () => {}, }); }, );