import { describe, expect, it, vi } from "vitest"; import { readBoundedJson } from "../../src/adapters/http/bounded-json.ts"; /** * N-08. The legacy V2 reader delegates to the common bounded reader. These * cases pin the preserved failure codes and prove that a throwing cancel or * releaseLock cannot escape the closed result. */ function responseWith( body: ReadableStream | string | null, init: ResponseInit = {}, ): Response { return new Response(body, init); } describe("legacy bounded JSON compatibility", () => { it("preserves RESPONSE_BODY_LIMIT for a declared oversize body", async () => { const response = responseWith("{}", { headers: { "content-length": "9999" }, }); await expect(readBoundedJson(response, 8)).resolves.toEqual({ ok: false, code: "RESPONSE_BODY_LIMIT", }); }); it("preserves RESPONSE_BODY_LIMIT for a headerless oversize body", async () => { const response = responseWith("[1,2,3,4,5,6,7,8,9,10]"); await expect(readBoundedJson(response, 4)).resolves.toEqual({ ok: false, code: "RESPONSE_BODY_LIMIT", }); }); it.each([ ["invalid UTF-8", new Uint8Array([0xff, 0xfe, 0xfd])], ["malformed JSON", new TextEncoder().encode("{")], ["an empty body", new Uint8Array(0)], ])("maps %s to MALFORMED_JSON", async (_label, bytes) => { const response = responseWith( new ReadableStream({ start(controller) { if (bytes.byteLength > 0) controller.enqueue(bytes); controller.close(); }, }), ); await expect(readBoundedJson(response, 1_024)).resolves.toEqual({ ok: false, code: "MALFORMED_JSON", }); }); it("keeps a closed result when reader cancel or releaseLock throws", async () => { const stream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("[1,2,3,4,5,6,7,8]")); }, }); const response = responseWith(stream); const body = response.body!; const nativeGetReader = body.getReader.bind(body); vi.spyOn(body, "getReader").mockImplementation((() => { const actual = nativeGetReader(); return { ...actual, read: actual.read.bind(actual), cancel: async () => { throw new TypeError("cancel exploded"); }, releaseLock: () => { throw new TypeError("releaseLock exploded"); }, }; }) as never); await expect(readBoundedJson(response, 4)).resolves.toEqual({ ok: false, code: "RESPONSE_BODY_LIMIT", }); }); it("reads a bounded JSON value successfully", async () => { const response = responseWith('{"a":1}'); await expect(readBoundedJson(response, 1_024)).resolves.toEqual({ ok: true, value: { a: 1 }, }); }); });