Open History to see the last commit
1import { afterEach, beforeEach, 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 prepareImageForAttachment,
9} from "./imageCompression";
10
11import type { SnapShotSource } from "@t3tools/contracts";
12import { hydrateImagesFromPersisted } from "../composerDraftStore";
13import { resizeSnapShotSource } from "./snapShotSource";
14
15const mocks = vi.hoisted(() => ({
16 heicTo: vi.fn(),
17}));
18
19vi.mock("heic-to/csp", () => ({
20 heicTo: mocks.heicTo,
21}));
22
23const originalCreateImageBitmap = globalThis.createImageBitmap;
24const originalOffscreenCanvas = globalThis.OffscreenCanvas;
25
26beforeEach(() => {
27 vi.stubGlobal(
28 "FileReader",
29 class extends EventTarget {
30 result: string | null = null;
31 error: unknown = null;
32 async readAsDataURL(blob: Blob) {
33 try {
34 const bytes = await blob.arrayBuffer();
35 this.result = `data:${blob.type || "application/octet-stream"};base64,${Buffer.from(bytes).toString("base64")}`;
36 this.dispatchEvent(new Event("load"));
37 } catch (error) {
38 this.error = error;
39 this.dispatchEvent(new Event("error"));
40 }
41 }
42 },
43 );
44});
45
46function makeFile(sizeBytes: number, type = "image/png"): File {
47 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
48}
49
50function makeHeicFile(options?: {
51 name?: string;
52 type?: string;
53 width?: number;
54 height?: number;
55 lastModified?: number;
56}): File {
57 const encoder = new TextEncoder();
58 const makeBox = (name: string, ...contents: Uint8Array[]) => {
59 const bytes = new Uint8Array(8 + contents.reduce((size, content) => size + content.length, 0));
60 new DataView(bytes.buffer).setUint32(0, bytes.length);
61 bytes.set(encoder.encode(name), 4);
62 let offset = 8;
63 for (const content of contents) {
64 bytes.set(content, offset);
65 offset += content.length;
66 }
67 return bytes;
68 };
69
70 const dimensions = new Uint8Array(12);
71 const view = new DataView(dimensions.buffer);
72 view.setUint32(4, options?.width ?? 4000);
73 view.setUint32(8, options?.height ?? 3000);
74 const properties = makeBox("iprp", makeBox("ipco", makeBox("ispe", dimensions)));
75
76 return new File(
77 [
78 makeBox("ftyp", encoder.encode("heic"), new Uint8Array(4)),
79 makeBox("meta", new Uint8Array(4), properties),
80 ],
81 options?.name ?? "photo.heic",
82 {
83 type: options?.type ?? "image/heic",
84 ...(options?.lastModified !== undefined ? { lastModified: options.lastModified } : {}),
85 },
86 );
87}
88
89function stubCanvasPipeline(
90 sizeForQuality: (quality: number) => number,
91 options?: { supportsWebp?: boolean; htmlCanvas?: boolean },
92) {
93 const supportsWebp = options?.supportsWebp ?? true;
94 const close = vi.fn();
95 const fillRect = vi.fn();
96 vi.stubGlobal(
97 "createImageBitmap",
98 vi.fn(async () => ({ width: 4000, height: 3000, close })),
99 );
100 vi.stubGlobal(
101 "OffscreenCanvas",
102 class {
103 constructor(
104 public width: number,
105 public height: number,
106 ) {}
107 getContext() {
108 return {
109 fillStyle: "",
110 fillRect,
111 drawImage: vi.fn(),
112 };
113 }
114 async convertToBlob({ type, quality }: { type: string; quality: number }) {
115 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
116 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
117 }
118 },
119 );
120 if (options?.htmlCanvas) {
121 const Canvas = globalThis.OffscreenCanvas;
122 class HtmlCanvas extends Canvas {
123 toBlob(callback: BlobCallback, type: string, quality: number) {
124 void this.convertToBlob({ type, quality }).then(callback);
125 }
126 }
127 vi.stubGlobal("OffscreenCanvas", undefined);
128 vi.stubGlobal("HTMLCanvasElement", HtmlCanvas);
129 vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) });
130 }
131 return { close, fillRect };
132}
133
134afterEach(() => {
135 mocks.heicTo.mockReset();
136 vi.unstubAllGlobals();
137 globalThis.createImageBitmap = originalCreateImageBitmap;
138 globalThis.OffscreenCanvas = originalOffscreenCanvas;
139});
140
141describe("compressImageForStash", () => {
142 it("keeps the exact data URL budget boundary and original bytes", async () => {
143 const original = makeFile(3);
144 const dataUrl = "data:image/png;base64,BwcH";
145
146 const result = await compressImageForStash(original, dataUrl.length);
147
148 expect(result.ok && result.image.dataUrl).toBe(dataUrl);
149 expect(result.ok && result.image.recompressed).toBe(false);
150 expect(await compressImageForStash(original, dataUrl.length - 1)).toEqual({
151 ok: false,
152 reason: "too-large",
153 });
154 });
155
156 it("compresses an oversized source before reading it as a data URL", async () => {
157 stubCanvasPipeline(() => 120_000);
158 const original = makeFile(4_000_000);
159 const read = vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("unneeded read"));
160
161 const result = await compressImageForStash(original);
162
163 expect(result.ok && result.image.recompressed).toBe(true);
164 expect(read).not.toHaveBeenCalled();
165 });
166
167 it("re-encodes an oversized image to WebP within the budget", async () => {
168 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
169
170 const result = await compressImageForStash(makeFile(4_000_000));
171
172 expect(result.ok).toBe(true);
173 expect(result.ok && result.image.recompressed).toBe(true);
174 expect(result.ok && result.image.mimeType).toBe("image/webp");
175 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
176 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
177 expect(fillRect).not.toHaveBeenCalled();
178 expect(close).toHaveBeenCalled();
179 });
180
181 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
182 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
183
184 const result = await compressImageForStash(makeFile(4_000_000));
185
186 expect(result.ok && result.image.recompressed).toBe(true);
187 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
188 expect(fillRect).toHaveBeenCalled();
189 });
190
191 it("steps quality down until the encoded image fits", async () => {
192 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
193
194 const result = await compressImageForStash(makeFile(9_000_000));
195
196 expect(result.ok && result.image.recompressed).toBe(true);
197 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
198 expect(close).toHaveBeenCalled();
199 });
200
201 it("reports too-large when even the smallest encoding overflows the budget", async () => {
202 const { close } = stubCanvasPipeline(() => 8_000_000);
203
204 const result = await compressImageForStash(makeFile(9_000_000));
205
206 expect(result).toEqual({ ok: false, reason: "too-large" });
207 expect(close).toHaveBeenCalled();
208 });
209
210 it("reports unreadable when the image fails to decode", async () => {
211 vi.stubGlobal(
212 "createImageBitmap",
213 vi.fn(async () => {
214 throw new Error("corrupt image");
215 }),
216 );
217 vi.stubGlobal(
218 "OffscreenCanvas",
219 class {
220 getContext() {
221 return null;
222 }
223 },
224 );
225
226 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
227 ok: false,
228 reason: "unreadable",
229 });
230 });
231
232 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
233 const bitmapSpy = vi.fn();
234 vi.stubGlobal("createImageBitmap", bitmapSpy);
235
236 const result = await compressImageToByteLimit(
237 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
238 10 * 1024 * 1024,
239 );
240
241 expect(result).toEqual({ ok: false, reason: "too-large" });
242 expect(bitmapSpy).not.toHaveBeenCalled();
243 });
244});
245
246describe("HEIC attachment preparation", () => {
247 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
248 const original = makeHeicFile({
249 name: "IMG_1234.HEIC",
250 type: "",
251 lastModified: 123,
252 });
253 mocks.heicTo.mockResolvedValueOnce(
254 new Blob([new Uint8Array([4, 5, 6, 7])], { type: "image/jpeg" }),
255 );
256
257 const result = await prepareImageForAttachment(original, 1024);
258
259 expect(mocks.heicTo).toHaveBeenCalledWith({
260 blob: original,
261 type: "image/jpeg",
262 quality: 0.92,
263 });
264 expect(result.ok && result.file.name).toBe("IMG_1234.jpg");
265 expect(result.ok && result.file.type).toBe("image/jpeg");
266 expect(result.ok && result.file.size).toBe(4);
267 expect(result.ok && result.file.lastModified).toBe(123);
268 expect(result.ok && result.recompressed).toBe(true);
269 });
270
271 it("compresses JPEG intermediates above the source safety ceiling", async () => {
272 const original = makeHeicFile({
273 name: "large.heic",
274 type: "image/heic",
275 });
276 mocks.heicTo.mockResolvedValueOnce(
277 new Blob([new Uint8Array(MAX_COMPRESSIBLE_SOURCE_BYTES + 1)], {
278 type: "image/jpeg",
279 }),
280 );
281 const { close } = stubCanvasPipeline(() => 200_000);
282
283 const result = await prepareImageForAttachment(original, 1_000_000);
284
285 expect(result.ok && result.file.name).toBe("large.jpg");
286 expect(result.ok && result.file.type).toBe("image/jpeg");
287 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
288 expect(close).toHaveBeenCalled();
289 });
290
291 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
292 const original = makeHeicFile({ width: 16_000, height: 4001 });
293
294 expect(await prepareImageForAttachment(original, 1024)).toEqual({
295 ok: false,
296 reason: "too-large",
297 });
298 expect(mocks.heicTo).not.toHaveBeenCalled();
299 });
300
301 it("rejects unsafe HEIC sources before loading the decoder", async () => {
302 const original = new File(["photo"], "large.heic", { type: "image/heic" });
303 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
304
305 expect(await prepareImageForAttachment(original, 1024)).toEqual({
306 ok: false,
307 reason: "too-large",
308 });
309 expect(mocks.heicTo).not.toHaveBeenCalled();
310 });
311});
312
313describe("attachment max edge", () => {
314 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
315 const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff];
316 const pngHeader = (width: number, height: number) => [
317 0x89,
318 0x50,
319 0x4e,
320 0x47,
321 0x0d,
322 0x0a,
323 0x1a,
324 0x0a,
325 ...u32(13),
326 0x49,
327 0x48,
328 0x44,
329 0x52,
330 ...u32(width),
331 ...u32(height),
332 8,
333 6,
334 0,
335 0,
336 0,
337 ];
338 const jpegHeader = (width: number, height: number) => [
339 0xff,
340 0xd8,
341 0xff,
342 0xc0,
343 ...u16(17),
344 8,
345 ...u16(height),
346 ...u16(width),
347 ];
348 const image = (header: number[], name: string, type: string) =>
349 new File([new Uint8Array([...header, ...new Uint8Array(2048).fill(7)])], name, { type });
350
351 function stubDecoder(bitmapSize: { width: number; height: number }) {
352 const decode = vi.fn(async () => ({ ...bitmapSize, close: vi.fn() }));
353 const canvases: Array<{ width: number; height: number }> = [];
354 const encodes: Array<{ type: string; quality: number }> = [];
355 const fillRect = vi.fn();
356 vi.stubGlobal("createImageBitmap", decode);
357 vi.stubGlobal(
358 "OffscreenCanvas",
359 class {
360 constructor(width: number, height: number) {
361 canvases.push({ width, height });
362 }
363 getContext() {
364 return { fillRect, drawImage: vi.fn() };
365 }
366 async convertToBlob(options: { type: string; quality: number }) {
367 encodes.push(options);
368 return new Blob([new Uint8Array(500_000)], { type: options.type });
369 }
370 },
371 );
372 return { decode, canvases, encodes, fillRect };
373 }
374
375 it("scales a large PNG screenshot under the byte cap to 2000px and keeps it a PNG", async () => {
376 const { decode, canvases, encodes, fillRect } = stubDecoder({ width: 3024, height: 1964 });
377 const original = image(pngHeader(3024, 1964), "shot.png", "image/png");
378
379 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
380
381 expect(decode).toHaveBeenCalledExactlyOnceWith(original, { imageOrientation: "from-image" });
382 expect(canvases).toEqual([{ width: 2000, height: 1299 }]);
383 expect(encodes.map(({ type }) => type)).toEqual(["image/png"]);
384 expect(fillRect).not.toHaveBeenCalled();
385 expect(result.ok && result.recompressed).toBe(true);
386 expect(result.ok && result.imageSize).toEqual({ width: 2000, height: 1299 });
387 expect(result.ok && result.file.name).toBe("shot.png");
388 expect(result.ok && result.file.type).toBe("image/png");
389 });
390
391 it("scales a rotated JPEG by its displayed size and keeps it a JPEG", async () => {
392 const { canvases, encodes } = stubDecoder({ width: 3024, height: 4032 });
393 const original = image(jpegHeader(4032, 3024), "photo.jpg", "image/jpeg");
394
395 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
396
397 expect(canvases).toEqual([{ width: 1500, height: 2000 }]);
398 expect(encodes).toEqual([{ type: "image/jpeg", quality: 0.92 }]);
399 expect(result.ok && result.file.type).toBe("image/jpeg");
400 expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 });
401 });
402
403 it.each([
404 { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" },
405 {
406 label: "a 3000px GIF",
407 header: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xb8, 0x0b, 0x10, 0x04],
408 type: "image/gif",
409 },
410 ])("passes $label through without decoding it", async ({ header, type }) => {
411 const { decode } = stubDecoder({ width: 3000, height: 1040 });
412 const original = image(header, "image", type);
413
414 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
415
416 expect(result.ok && result.file).toBe(original);
417 expect(result.ok && result.recompressed).toBe(false);
418 expect(decode).not.toHaveBeenCalled();
419 });
420});
421
422describe("snapshot coordinates after compression", () => {
423 const source: SnapShotSource = {
424 kind: "snap-shot",
425 capturedAt: "2026-09-01T00:00:00.000Z",
426 appName: "Editor",
427 windowTitle: "main.ts",
428 accessibility: {
429 format: "element-tree",
430 coordinateSpace: "captured-image",
431 imageSize: { width: 2560, height: 1600 },
432 truncated: false,
433 root: {
434 role: "window",
435 bounds: { x: 0, y: 0, width: 2560, height: 1600 },
436 children: [
437 {
438 role: "button",
439 name: "Save",
440 bounds: { x: 2400, y: 1400, width: 100, height: 100 },
441 children: [],
442 },
443 { role: "static_text", name: "Untitled", bounds: null, children: [] },
444 ],
445 },
446 },
447 };
448
449 it.each(["stash", "delivery"])(
450 "rescales the source and restores it with the compressed %s image",
451 async (path) => {
452 stubCanvasPipeline(() => 100);
453 vi.stubGlobal(
454 "createImageBitmap",
455 vi.fn(async () => ({ width: 2560, height: 1600, close: vi.fn() })),
456 );
457 const original = makeFile(2000);
458 const compressed =
459 path === "stash"
460 ? await compressImageForStash(original, 1000)
461 : await compressImageToByteLimit(original, 1000);
462 expect(compressed.ok).toBe(true);
463 if (!compressed.ok) throw new Error("Compression failed");
464 const image =
465 "image" in compressed
466 ? compressed.image
467 : {
468 ...compressed,
469 mimeType: compressed.file.type,
470 sizeBytes: compressed.file.size,
471 dataUrl: `data:${compressed.file.type};base64,${Buffer.from(await compressed.file.arrayBuffer()).toString("base64")}`,
472 };
473 expect(image.imageSize).toEqual({ width: 2000, height: 1250 });
474 const resized = resizeSnapShotSource(source, image.imageSize);
475 const [restored] = hydrateImagesFromPersisted([
476 {
477 id: "capture",
478 name: "window.webp",
479 mimeType: image.mimeType,
480 sizeBytes: image.sizeBytes,
481 dataUrl: image.dataUrl,
482 source: resized,
483 },
484 ]);
485 expect(restored?.source?.accessibility).toMatchObject({
486 imageSize: { width: 2000, height: 1250 },
487 root: {
488 bounds: { x: 0, y: 0, width: 2000, height: 1250 },
489 children: [{ bounds: { x: 1875, y: 1094, width: 78, height: 78 } }, { bounds: null }],
490 },
491 });
492 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
493 },
494 );
495});