Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

imageCompression.test.ts

253 lines9.0 KB

1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import {
4 compressImageForStash,
5 compressImageToByteLimit,
6 MAX_COMPRESSIBLE_SOURCE_BYTES,
7 MAX_STASH_IMAGE_DATA_URL_CHARS,
8} from "./imageCompression";
9​
10/**
11 * jsdom has no real canvas/codec, so the re-encode path is exercised with
12 * stubbed `createImageBitmap` + `OffscreenCanvas`. The encoder stub returns a
13 * payload whose size scales with quality, mirroring how a real JPEG encoder
14 * shrinks as quality drops — enough to verify the ladder logic and budget
15 * enforcement without pulling in a native canvas.
16 */
17​
18const originalCreateImageBitmap = globalThis.createImageBitmap;
19const originalOffscreenCanvas = globalThis.OffscreenCanvas;
20​
21function makeFile(sizeBytes: number, type = "image/png"): File {
22 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
24​
25/**
26 * Installs a fake bitmap + canvas whose encoded size follows `sizeForQuality`.
27 * `supportsWebp: false` makes `convertToBlob` hand back a differently-typed
28 * blob for WebP requests, which is how a real browser signals it cannot
29 * encode that format.
30 */
31function stubCanvasPipeline(
32 sizeForQuality: (quality: number) => number,
33 options?: { supportsWebp?: boolean },
34) {
35 const supportsWebp = options?.supportsWebp ?? true;
36 const close = vi.fn();
37 const fillRect = vi.fn();
38 vi.stubGlobal(
39 "createImageBitmap",
40 vi.fn(async () => ({ width: 4000, height: 3000, close })),
41 );
42 vi.stubGlobal(
43 "OffscreenCanvas",
44 class {
45 constructor(
46 public width: number,
47 public height: number,
48 ) {}
49 getContext() {
50 return {
51 fillStyle: "",
52 fillRect,
53 drawImage: vi.fn(),
54 };
55 }
56 async convertToBlob({ type, quality }: { type: string; quality: number }) {
57 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
58 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
59 }
60 },
61 );
62 return { close, fillRect };
64​
65afterEach(() => {
66 vi.unstubAllGlobals();
67 globalThis.createImageBitmap = originalCreateImageBitmap;
68 globalThis.OffscreenCanvas = originalOffscreenCanvas;
69});
70​
71describe("compressImageForStash", () => {
72 it("stores a small image verbatim without re-encoding", async () => {
73 const bitmapSpy = vi.fn();
74 vi.stubGlobal("createImageBitmap", bitmapSpy);
75​
76 const result = await compressImageForStash(makeFile(1024));
77​
78 expect(result.ok).toBe(true);
79 expect(result.ok && result.image.recompressed).toBe(false);
80 expect(result.ok && result.image.mimeType).toBe("image/png");
81 expect(result.ok && result.image.dataUrl.startsWith("data:image/png")).toBe(true);
82 // Untouched payloads must not pay for a decode.
83 expect(bitmapSpy).not.toHaveBeenCalled();
84 });
85​
86 it("re-encodes an oversized image to WebP within the budget", async () => {
87 // Comfortably under budget at the very first quality step.
88 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
89​
90 const result = await compressImageForStash(makeFile(4_000_000));
91​
92 expect(result.ok).toBe(true);
93 expect(result.ok && result.image.recompressed).toBe(true);
94 expect(result.ok && result.image.mimeType).toBe("image/webp");
95 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
96 // sizeBytes should describe the re-encoded payload, not the 4MB original.
97 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
98 // WebP keeps alpha, so no white matte should be painted.
99 expect(fillRect).not.toHaveBeenCalled();
100 expect(close).toHaveBeenCalled();
101 });
102​
103 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
104 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
105​
106 const result = await compressImageForStash(makeFile(4_000_000));
107​
108 expect(result.ok && result.image.recompressed).toBe(true);
109 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
110 // JPEG has no alpha, so transparent regions must be matted white.
111 expect(fillRect).toHaveBeenCalled();
112 });
113​
114 it("steps quality down until the encoded image fits", async () => {
115 // Only the lowest quality step (0.68) lands under the budget.
116 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
117​
118 const result = await compressImageForStash(makeFile(9_000_000));
119​
120 expect(result.ok && result.image.recompressed).toBe(true);
121 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
122 expect(close).toHaveBeenCalled();
123 });
124​
125 it("reports too-large when even the smallest encoding overflows the budget", async () => {
126 const { close } = stubCanvasPipeline(() => 8_000_000);
127​
128 const result = await compressImageForStash(makeFile(9_000_000));
129​
130 expect(result).toEqual({ ok: false, reason: "too-large" });
131 // The bitmap must still be released on the give-up path.
132 expect(close).toHaveBeenCalled();
133 });
134​
135 it("reports too-large for an oversized image when the browser cannot re-encode", async () => {
136 vi.stubGlobal("createImageBitmap", undefined);
137 vi.stubGlobal("OffscreenCanvas", undefined);
138​
139 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
140 ok: false,
141 reason: "too-large",
142 });
143 });
144​
145 it("reports unreadable when the image fails to decode", async () => {
146 vi.stubGlobal(
147 "createImageBitmap",
148 vi.fn(async () => {
149 throw new Error("corrupt image");
150 }),
151 );
152 vi.stubGlobal(
153 "OffscreenCanvas",
154 class {
155 getContext() {
156 return null;
157 }
158 },
159 );
160​
161 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
162 ok: false,
163 reason: "unreadable",
164 });
165 });
166​
167 it("compressImageToByteLimit passes small files through byte-for-byte", async () => {
168 const bitmapSpy = vi.fn();
169 vi.stubGlobal("createImageBitmap", bitmapSpy);
170​
171 const original = makeFile(1024);
172 const result = await compressImageToByteLimit(original, 10 * 1024 * 1024);
173​
174 expect(result.ok).toBe(true);
175 expect(result.ok && result.recompressed).toBe(false);
176 // Pass-through must be the same File object, not a copy.
177 expect(result.ok && result.file).toBe(original);
178 expect(bitmapSpy).not.toHaveBeenCalled();
179 });
180​
181 it("compressImageToByteLimit re-encodes an oversized file under the byte cap", async () => {
182 stubCanvasPipeline(() => 200_000);
183​
184 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
185​
186 expect(result.ok).toBe(true);
187 expect(result.ok && result.recompressed).toBe(true);
188 expect(result.ok && result.file.type).toBe("image/webp");
189 // The re-encoded name must match the new container format.
190 expect(result.ok && result.file.name).toBe("shot.webp");
191 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
192 });
193​
194 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
195 const bitmapSpy = vi.fn();
196 vi.stubGlobal("createImageBitmap", bitmapSpy);
197​
198 const result = await compressImageToByteLimit(
199 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
200 10 * 1024 * 1024,
201 );
202​
203 expect(result).toEqual({ ok: false, reason: "too-large" });
204 // The whole point of the ceiling is to never decode such a file.
205 expect(bitmapSpy).not.toHaveBeenCalled();
206 });
207​
208 it("compressImageToByteLimit reports too-large when no encoding fits", async () => {
209 const { close } = stubCanvasPipeline(() => 3_000_000);
210​
211 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
212​
213 expect(result).toEqual({ ok: false, reason: "too-large" });
214 expect(close).toHaveBeenCalled();
215 });
216​
217 it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
218 // A small-but-heavy source (e.g. a dense PNG): only a real downscale can
219 // get it under budget, since quality alone is stubbed to never suffice.
220 let smallestRequested = Number.POSITIVE_INFINITY;
221 const close = vi.fn();
222 vi.stubGlobal(
223 "createImageBitmap",
224 vi.fn(async () => ({ width: 800, height: 600, close })),
225 );
226 vi.stubGlobal(
227 "OffscreenCanvas",
228 class {
229 constructor(
230 public width: number,
231 public height: number,
232 ) {
233 smallestRequested = Math.min(smallestRequested, width);
234 }
235 getContext() {
236 return { fillStyle: "", fillRect: vi.fn(), drawImage: vi.fn() };
237 }
238 async convertToBlob({ type }: { type: string; quality: number }) {
239 // Only a genuinely downscaled pass fits the budget.
240 const size = smallestRequested < 800 ? 100_000 : 5_000_000;
241 return new Blob([new Uint8Array(size)], { type });
242 }
243 },
244 );
245​
246 const result = await compressImageForStash(makeFile(4_000_000));
247​
248 expect(result.ok).toBe(true);
249 // Fallback passes must scale off the bitmap, not a fixed 2048 ceiling
250 // that would never go below an 800px source.
251 expect(smallestRequested).toBeLessThan(800);
252 });
253});