| 1 | import { describe, expect, it } from "vite-plus/test"; |
| 2 | import { FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview"; |
| 3 | import { readFilePreviewResponse } from "./filePreview.ts"; |
| 4 | |
| 5 | describe("readFilePreviewResponse", () => { |
| 6 | it("cancels a pending read when its preview closes", async () => { |
| 7 | const controller = new AbortController(); |
| 8 | let cancelled = false; |
| 9 | const body = new ReadableStream<Uint8Array>({ |
| 10 | cancel() { |
| 11 | cancelled = true; |
| 12 | }, |
| 13 | }); |
| 14 | const result = readFilePreviewResponse(new Response(body), controller.signal); |
| 15 | controller.abort(); |
| 16 | await expect(result).rejects.toThrow(); |
| 17 | expect(cancelled).toBe(true); |
| 18 | }); |
| 19 | it("supports native AbortSignal implementations without throwIfAborted", async () => { |
| 20 | const signal = new AbortController().signal; |
| 21 | Object.defineProperty(signal, "throwIfAborted", { value: undefined }); |
| 22 | await expect(readFilePreviewResponse(new Response("native text"), signal)).resolves.toEqual({ |
| 23 | text: "native text", |
| 24 | truncated: false, |
| 25 | }); |
| 26 | }); |
| 27 | it("reads text and rejects unsuccessful responses", async () => { |
| 28 | const signal = new AbortController().signal; |
| 29 | await expect(readFilePreviewResponse(new Response('{"ok":true}'), signal)).resolves.toEqual({ |
| 30 | text: '{"ok":true}', |
| 31 | truncated: false, |
| 32 | }); |
| 33 | await expect( |
| 34 | readFilePreviewResponse(new Response(null, { status: 403 }), signal), |
| 35 | ).rejects.toThrow("could not be loaded"); |
| 36 | }); |
| 37 | it("cancels a streamed error body instead of leaving it open", async () => { |
| 38 | const signal = new AbortController().signal; |
| 39 | let cancelled = false; |
| 40 | const body = new ReadableStream<Uint8Array>({ |
| 41 | cancel() { |
| 42 | cancelled = true; |
| 43 | }, |
| 44 | }); |
| 45 | |
| 46 | await expect( |
| 47 | readFilePreviewResponse(new Response(body, { status: 500 }), signal), |
| 48 | ).rejects.toThrow("could not be loaded"); |
| 49 | expect(cancelled).toBe(true); |
| 50 | }); |
| 51 | |
| 52 | it("stops consuming an unbounded response and cancels its stream", async () => { |
| 53 | let cancelled = false; |
| 54 | const body = new ReadableStream<Uint8Array>({ |
| 55 | pull(controller) { |
| 56 | controller.enqueue(new Uint8Array(FILE_TEXT_PREVIEW_MAX_BYTES).fill(97)); |
| 57 | }, |
| 58 | cancel() { |
| 59 | cancelled = true; |
| 60 | }, |
| 61 | }); |
| 62 | const result = await readFilePreviewResponse(new Response(body), new AbortController().signal); |
| 63 | expect(result.text.length).toBe(FILE_TEXT_PREVIEW_MAX_BYTES); |
| 64 | expect(result.truncated).toBe(true); |
| 65 | expect(cancelled).toBe(true); |
| 66 | }); |
| 67 | }); |