import { describe, it, expect } from "vitest"; import { createHiveGridClient, HiveGridApiError, HiveGridNetworkError } from "./client.js"; function mockFetchSequence(responses: Array): typeof fetch { let index = 0; return (async () => { const next = responses[index++]; if (next === undefined) { throw new Error("mock fetch exhausted"); } if (next instanceof Error) throw next; return next; }) as unknown as typeof fetch; } function jsonResponse(status: number, body: unknown, headers: Record = {}): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers }, }); } describe("createHiveGridClient", () => { it("rejects when baseUrl is missing", () => { expect(() => createHiveGridClient({ baseUrl: "" } as never)).toThrow(/baseUrl/); }); it("strips trailing slashes from the base url", () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com///", fetch: mockFetchSequence([jsonResponse(200, { ok: true })]), }); expect(client.baseUrl).toBe("https://api.example.com"); }); it("sends Authorization bearer when bearerToken is set", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(200, { hello: "world" }); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", auth: { bearerToken: "secret-token" }, fetch: stub, }); const result = await client.request<{ hello: string }>({ method: "GET", path: "/v1/me" }); expect(result.hello).toBe("world"); expect(captured.headers!.get("authorization")).toBe("Bearer secret-token"); }); it("sends X-API-Key when apiKey is set", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(200, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", auth: { apiKey: "ak_test_123" }, fetch: stub, }); await client.request({ method: "GET", path: "/v1/ping" }); expect(captured.headers!.get("x-api-key")).toBe("ak_test_123"); }); it("auto-generates Idempotency-Key on POST", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(201, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub, }); await client.request({ method: "POST", path: "/v1/items", body: { foo: 1 } }); expect(captured.headers!.get("idempotency-key")).toMatch(/^[0-9a-f-]{36}$/i); }); it("does not auto-generate Idempotency-Key on GET", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(200, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub, }); await client.request({ method: "GET", path: "/v1/items" }); expect(captured.headers!.get("idempotency-key")).toBeNull(); }); it("respects autoGenerate=false", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(201, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", idempotency: { autoGenerate: false }, fetch: stub, }); await client.request({ method: "POST", path: "/v1/items", body: { foo: 1 } }); expect(captured.headers!.get("idempotency-key")).toBeNull(); }); it("honors caller-provided Idempotency-Key", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(201, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub, }); await client.request({ method: "POST", path: "/v1/items", body: {}, idempotencyKey: "caller-key" }); expect(captured.headers!.get("idempotency-key")).toBe("caller-key"); }); it("forwards X-Tenant-ID and Sentry trace headers", async () => { const captured: { headers: Headers | null } = { headers: null }; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.headers = init.headers as Headers; return jsonResponse(200, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", tenantId: "ten_abc", sentry: { trace: "abc-1", baggage: "k=v" }, fetch: stub, }); await client.request({ method: "GET", path: "/v1/ping" }); expect(captured.headers!.get("x-tenant-id")).toBe("ten_abc"); expect(captured.headers!.get("sentry-trace")).toBe("abc-1"); expect(captured.headers!.get("baggage")).toBe("k=v"); }); it("retries on 5xx then succeeds", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 }, fetch: mockFetchSequence([jsonResponse(503, { error: "down" }), jsonResponse(200, { ok: true })]), }); const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" }); expect(result.ok).toBe(true); }); it("retries on 429 honoring Retry-After", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 10_000 }, fetch: mockFetchSequence([ jsonResponse(429, { error: "rate" }, { "retry-after": "0" }), jsonResponse(200, { ok: true }), ]), }); const t0 = Date.now(); const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" }); expect(result.ok).toBe(true); // retry-after=0 should not have produced exponential backoff (which would be >=1000ms) expect(Date.now() - t0).toBeLessThan(1000); }); it("throws HiveGridApiError on non-retryable 4xx", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", retry: { maxAttempts: 3, baseDelayMs: 1 }, fetch: mockFetchSequence([ jsonResponse(404, { error: { code: "not_found", message: "missing", requestId: "req_1" } }, { "x-request-id": "req_1" }), ]), }); await expect(client.request({ method: "GET", path: "/v1/missing" })).rejects.toMatchObject({ name: "HiveGridApiError", status: 404, requestId: "req_1", }); }); it("throws HiveGridNetworkError after exhausting retries", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", retry: { maxAttempts: 2, baseDelayMs: 1, maxDelayMs: 5 }, fetch: mockFetchSequence([new Error("ECONNRESET"), new Error("ECONNRESET")]), }); await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(HiveGridNetworkError); }); it("paginate auto-follows nextCursor and stops on null", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: mockFetchSequence([ jsonResponse(200, { data: [{ id: 1 }, { id: 2 }], nextCursor: "c1" }), jsonResponse(200, { data: [{ id: 3 }], nextCursor: null }), ]), }); const items: Array<{ id: number }> = []; for await (const item of client.paginate<{ id: number }>("/v1/items")) { items.push(item); } expect(items.map((i) => i.id)).toEqual([1, 2, 3]); }); it("paginate handles nextPage offset pagination", async () => { const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: mockFetchSequence([ jsonResponse(200, { data: [{ id: "a" }], nextPage: 2 }), jsonResponse(200, { data: [{ id: "b" }] }), ]), }); const items: Array<{ id: string }> = []; for await (const item of client.paginate<{ id: string }>("/v1/items", { maxPages: 5 })) { items.push(item); } expect(items.map((i) => i.id)).toEqual(["a", "b"]); }); it("getter mode resolves bearer token freshly", async () => { let calls = 0; const captured: Array = []; const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => { captured.push((init.headers as Headers).get("authorization")); return jsonResponse(200, {}); }) as unknown as typeof fetch; const client = createHiveGridClient({ baseUrl: "https://api.example.com", auth: { getToken: async () => `jwt-${++calls}`, }, fetch: stub, }); await client.request({ method: "GET", path: "/v1/a" }); await client.request({ method: "GET", path: "/v1/b" }); expect(captured).toEqual(["Bearer jwt-1", "Bearer jwt-2"]); }); }); describe("error types", () => { it("HiveGridApiError carries status, body, and requestId", () => { const err = new HiveGridApiError(403, "Forbidden", { error: { code: "forbidden" } }, "req_x"); expect(err.name).toBe("HiveGridApiError"); expect(err.status).toBe(403); expect(err.requestId).toBe("req_x"); }); it("HiveGridNetworkError preserves cause", () => { const cause = new Error("ECONNRESET"); const err = new HiveGridNetworkError("net", cause); expect(err.cause).toBe(cause); }); });