import { describe, expect, it, vi } from "vitest"; import { ApiError, apiGet, apiRequest, apiSend } from "../../lib/api"; interface FetchCall { url: URL; init: RequestInit; } function stubFetch( handler: (url: URL, init: RequestInit) => Response | Promise, ): FetchCall[] { const calls: FetchCall[] = []; vi.stubGlobal( "fetch", vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => { const url = new URL(String(input), "http://localhost"); calls.push({ url, init }); return handler(url, init); }), ); return calls; } function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" }, }); } function fakeLocation(pathname: string) { const original = window.location; const assign = vi.fn(); Object.defineProperty(window, "location", { configurable: true, value: { pathname, search: "", origin: "http://localhost", assign }, }); return { assign, restore: () => Object.defineProperty(window, "location", { configurable: true, value: original, }), }; } describe("api client", () => { it("asks for JSON with same-origin credentials and returns the parsed body", async () => { const calls = stubFetch(() => jsonResponse({ items: [], cursor: "", has_more: false }), ); const page = await apiGet<{ items: unknown[]; has_more: boolean }>( "/api/feed?limit=20", ); expect(page).toEqual({ items: [], cursor: "", has_more: false }); const headers = new Headers(calls[0].init.headers); expect(headers.get("Accept")).toBe("application/json"); expect(headers.get("Content-Type")).toBeNull(); expect(calls[0].init.credentials).toBe("same-origin"); expect(calls[0].init.method).toBe("GET"); }); it("preserves browser-generated multipart boundaries", async () => { const calls = stubFetch(() => jsonResponse({ saved: true })); const body = new FormData(); body.set("display_name", "Alex"); await apiRequest("/api/settings/bluesky-profile", { method: "POST", body }); const headers = new Headers(calls[0].init.headers); expect(headers.get("Content-Type")).toBeNull(); expect(headers.get("Accept")).toBe("application/json"); expect(calls[0].init.body).toBe(body); }); it("sends mutations as JSON", async () => { const calls = stubFetch(() => jsonResponse({ rkey: "brew-1" })); await apiSend("POST", "/api/brews", { tea_rkey: "tea-1", style: "longSteep", }); const headers = new Headers(calls[0].init.headers); expect(headers.get("Content-Type")).toBe("application/json"); expect(calls[0].init.method).toBe("POST"); expect(JSON.parse(String(calls[0].init.body))).toEqual({ tea_rkey: "tea-1", style: "longSteep", }); }); it("surfaces the server's error envelope as an ApiError", async () => { stubFetch(() => jsonResponse({ error: "Invalid steep", code: "validation_failed" }, 422), ); const failure = await apiGet("/api/brews/nope").catch( (error: unknown) => error, ); expect(failure).toBeInstanceOf(ApiError); expect(failure).toMatchObject({ status: 422, code: "validation_failed", message: "Invalid steep", }); }); it("falls back to http_ for plain-text failures", async () => { stubFetch( () => new Response("upstream exploded", { status: 500, headers: { "content-type": "text/plain" }, }), ); const failure = (await apiGet("/api/feed").catch( (error: unknown) => error, )) as ApiError; expect(failure).toBeInstanceOf(ApiError); expect(failure.status).toBe(500); expect(failure.code).toBe("http_500"); expect(failure.message).toBe("upstream exploded"); }); it("reports an unreachable server as a network error", async () => { stubFetch(() => Promise.reject(new TypeError("Failed to fetch"))); const failure = (await apiGet("/api/feed").catch( (error: unknown) => error, )) as ApiError; expect(failure).toBeInstanceOf(ApiError); expect(failure.status).toBe(0); expect(failure.code).toBe("network_error"); expect(failure.message).toContain("Could not reach Oolong"); }); it("redirects an expired session to login with the current path", async () => { stubFetch(() => jsonResponse( { error: "Authentication required", code: "authentication_required" }, 401, ), ); const location = fakeLocation("/brews/new"); try { const failure = (await apiGet("/api/data").catch( (error: unknown) => error, )) as ApiError; expect(failure.status).toBe(401); expect(location.assign).toHaveBeenCalledWith( "/login?return=%2Fbrews%2Fnew", ); } finally { location.restore(); } }); it("leaves the redirect to the caller when suppressed", async () => { stubFetch(() => jsonResponse( { error: "Authentication required", code: "authentication_required" }, 401, ), ); const location = fakeLocation("/brews/new"); try { const failure = (await apiGet("/api/session", { suppressAuthRedirect: true, }).catch((error: unknown) => error)) as ApiError; expect(failure.status).toBe(401); expect(location.assign).not.toHaveBeenCalled(); } finally { location.restore(); } }); it("forwards the abort signal and rethrows the abort", async () => { const controller = new AbortController(); const calls = stubFetch((_url, init) => { expect(init.signal).toBe(controller.signal); return Promise.reject(new DOMException("Aborted", "AbortError")); }); const failure = await apiGet("/api/feed", { signal: controller.signal, }).catch((error: unknown) => error); expect(failure).toBeInstanceOf(DOMException); expect((failure as DOMException).name).toBe("AbortError"); expect(calls).toHaveLength(1); }); });