|
| 1 | +import { expect, it, vi } from "vite-plus/test"; |
| 2 | + |
| 3 | +import { readMediaPng } from "./mediaContent"; |
| 4 | + |
| 5 | +const PNG_BYTES = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; |
| 6 | + |
| 7 | +it("copies a data URL image without fetching it", async () => { |
| 8 | + // The desktop renderer's connect-src rejects data: URLs the way fetch rejects a CORS failure. |
| 9 | + using fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch")); |
| 10 | + const src = `data:image/png;base64,${btoa(String.fromCharCode(...PNG_BYTES))}`; |
| 11 | + |
| 12 | + const png = await readMediaPng(src); |
| 13 | + |
| 14 | + expect(fetch).not.toHaveBeenCalled(); |
| 15 | + expect(png.type).toBe("image/png"); |
| 16 | + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES); |
| 17 | +}); |
| 18 | + |
| 19 | +it("decodes percent-escaped bytes in a non-base64 data URL", async () => { |
| 20 | + const escaped = PNG_BYTES.map((byte) => `%${byte.toString(16).padStart(2, "0")}`).join(""); |
| 21 | + const src = `data:image/png,${escaped}`; |
| 22 | + |
| 23 | + const png = await readMediaPng(src); |
| 24 | + |
| 25 | + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES); |
| 26 | +}); |
| 27 | + |
| 28 | +it("accepts any case in the scheme and base64 marker, and escapes in base64", async () => { |
| 29 | + const base64 = btoa(String.fromCharCode(...PNG_BYTES)).replaceAll("=", "%3D"); |
| 30 | + |
| 31 | + const png = await readMediaPng(`DATA:image/png;BASE64,${base64}`); |
| 32 | + |
| 33 | + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES); |
| 34 | +}); |
| 35 | + |
| 36 | +it("ignores the URL fragment when decoding a data URL", async () => { |
| 37 | + const src = `data:image/png;base64,${btoa(String.fromCharCode(...PNG_BYTES))}#preview`; |
| 38 | + |
| 39 | + const png = await readMediaPng(src); |
| 40 | + |
| 41 | + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES); |
| 42 | +}); |
| 43 | + |
| 44 | +it.each(["data:image/png;base64,%%%", "data:image/png"])( |
| 45 | + "reports malformed inline media: %s", |
| 46 | + async (src) => { |
| 47 | + await expect(readMediaPng(src)).rejects.toThrow("This inline media could not be decoded."); |
| 48 | + }, |
| 49 | +); |
| 50 | + |
| 51 | +it("keeps remote media on the fetch path", async () => { |
| 52 | + const png = new Blob([new Uint8Array(PNG_BYTES)], { type: "image/png" }); |
| 53 | + using fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(png)); |
| 54 | + |
| 55 | + expect(await readMediaPng("https://example.com/image.png")).toEqual(png); |
| 56 | + expect(fetch).toHaveBeenCalledWith("https://example.com/image.png"); |
| 57 | +}); |
0 commit comments