Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createComposerImageThumbnail,
5 compressImageForStash,
6 compressImageToByteLimit,
7 dataUrlToFile,
8 isHeicImageFile,
9 MAX_COMPRESSIBLE_SOURCE_BYTES,
10 MAX_STASH_IMAGE_DATA_URL_CHARS,
11 prepareImageForAttachment,
12} from "./imageCompression";
13
14import type { SnapShotSource } from "@t3tools/contracts";
15import { hydrateImagesFromPersisted } from "../composerDraftStore";
16import { resizeSnapShotSource } from "./snapShotSource";
17
18const mocks = vi.hoisted(() => ({
19 heicTo: vi.fn(),
20}));
21
22vi.mock("heic-to/csp", () => ({
23 heicTo: mocks.heicTo,
24}));
25
26const originalCreateImageBitmap = globalThis.createImageBitmap;
27const originalOffscreenCanvas = globalThis.OffscreenCanvas;
28
29beforeEach(() => {
30 vi.stubGlobal(
31 "FileReader",
32 class extends EventTarget {
33 result: string | null = null;
34 error: unknown = null;
35 async readAsDataURL(blob: Blob) {
36 try {
37 const bytes = await blob.arrayBuffer();
38 this.result = `data:${blob.type || "application/octet-stream"};base64,${Buffer.from(bytes).toString("base64")}`;
39 this.dispatchEvent(new Event("load"));
40 } catch (error) {
41 this.error = error;
42 this.dispatchEvent(new Event("error"));
43 }
44 }
45 },
46 );
47});
48
49function makeFile(sizeBytes: number, type = "image/png"): File {
50 return new File([new Uint8Array(sizeBytes).fill(7)], "shot.png", { type });
51}
52
53function makeHeicFile(options?: {
54 name?: string;
55 type?: string;
56 width?: number;
57 height?: number;
58 lastModified?: number;
59}): File {
60 const encoder = new TextEncoder();
61 const makeBox = (name: string, ...contents: Uint8Array[]) => {
62 const bytes = new Uint8Array(8 + contents.reduce((size, content) => size + content.length, 0));
63 new DataView(bytes.buffer).setUint32(0, bytes.length);
64 bytes.set(encoder.encode(name), 4);
65 let offset = 8;
66 for (const content of contents) {
67 bytes.set(content, offset);
68 offset += content.length;
69 }
70 return bytes;
71 };
72
73 const dimensions = new Uint8Array(12);
74 const view = new DataView(dimensions.buffer);
75 view.setUint32(4, options?.width ?? 4000);
76 view.setUint32(8, options?.height ?? 3000);
77 const properties = makeBox("iprp", makeBox("ipco", makeBox("ispe", dimensions)));
78
79 return new File(
80 [
81 makeBox("ftyp", encoder.encode("heic"), new Uint8Array(4)),
82 makeBox("meta", new Uint8Array(4), properties),
83 ],
84 options?.name ?? "photo.heic",
85 {
86 type: options?.type ?? "image/heic",
87 ...(options?.lastModified !== undefined ? { lastModified: options.lastModified } : {}),
88 },
89 );
90}
91
92function stubCanvasPipeline(
93 sizeForQuality: (quality: number) => number,
94 options?: { supportsWebp?: boolean; htmlCanvas?: boolean },
95) {
96 const supportsWebp = options?.supportsWebp ?? true;
97 const close = vi.fn();
98 const fillRect = vi.fn();
99 vi.stubGlobal(
100 "createImageBitmap",
101 vi.fn(async () => ({ width: 4000, height: 3000, close })),
102 );
103 vi.stubGlobal(
104 "OffscreenCanvas",
105 class {
106 constructor(
107 public width: number,
108 public height: number,
109 ) {}
110 getContext() {
111 return {
112 fillStyle: "",
113 fillRect,
114 drawImage: vi.fn(),
115 };
116 }
117 async convertToBlob({ type, quality }: { type: string; quality: number }) {
118 const resolvedType = type === "image/webp" && !supportsWebp ? "image/png" : type;
119 return new Blob([new Uint8Array(sizeForQuality(quality))], { type: resolvedType });
120 }
121 },
122 );
123 if (options?.htmlCanvas) {
124 const Canvas = globalThis.OffscreenCanvas;
125 class HtmlCanvas extends Canvas {
126 toBlob(callback: BlobCallback, type: string, quality: number) {
127 void this.convertToBlob({ type, quality }).then(callback);
128 }
129 }
130 vi.stubGlobal("OffscreenCanvas", undefined);
131 vi.stubGlobal("HTMLCanvasElement", HtmlCanvas);
132 vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) });
133 }
134 return { close, fillRect };
135}
136
137afterEach(() => {
138 mocks.heicTo.mockReset();
139 vi.unstubAllGlobals();
140 globalThis.createImageBitmap = originalCreateImageBitmap;
141 globalThis.OffscreenCanvas = originalOffscreenCanvas;
142});
143
144describe("composer image thumbnails", () => {
145 it("decodes a tall original once and caches a bounded center crop", async () => {
146 const close = vi.fn();
147 const bitmap = { width: 2304, height: 32766, close };
148 const decode = vi.fn(async () => bitmap);
149 const drawImage = vi.fn();
150 const dimensions: number[][] = [];
151 vi.stubGlobal("createImageBitmap", decode);
152 vi.stubGlobal(
153 "OffscreenCanvas",
154 class {
155 constructor(width: number, height: number) {
156 dimensions.push([width, height]);
157 }
158 getContext() {
159 return { drawImage };
160 }
161 async convertToBlob() {
162 return new Blob(["thumbnail"], { type: "image/png" });
163 }
164 },
165 );
166 const original = new File(["original bytes"], "tall.png", { type: "image/png" });
167 const [first, second] = await Promise.all([
168 createComposerImageThumbnail(original),
169 createComposerImageThumbnail(original),
170 ]);
171 expect(first).toBe("data:image/png;base64,dGh1bWJuYWls");
172 expect(second).toBe(first);
173 expect(await createComposerImageThumbnail(original)).toBe(first);
174 expect(decode).toHaveBeenCalledExactlyOnceWith(original);
175 expect(dimensions).toEqual([[256, 256]]);
176 expect(drawImage).toHaveBeenCalledWith(bitmap, 0, 15231, 2304, 2304, 0, 0, 256, 256);
177 expect(close).toHaveBeenCalledOnce();
178 expect(await original.text()).toBe("original bytes");
179 });
180
181 it.each([
182 [3840, 2160, 796, 448],
183 [3840, 1600, 832, 347],
184 ])(
185 "preserves the full %ix%i snapshot within an 832x448 preview without replacing its square thumbnail",
186 async (sourceWidth, sourceHeight, width, height) => {
187 const bitmap = { width: sourceWidth, height: sourceHeight, close: vi.fn() };
188 const decode = vi.fn(async () => bitmap);
189 const drawImage = vi.fn();
190 vi.stubGlobal("createImageBitmap", decode);
191 vi.stubGlobal(
192 "OffscreenCanvas",
193 class {
194 constructor(
195 public width: number,
196 public height: number,
197 ) {}
198 getContext() {
199 return { drawImage };
200 }
201 async convertToBlob() {
202 return new Blob([`${this.width}x${this.height}`], { type: "image/png" });
203 }
204 },
205 );
206 const original = new File(["original bytes"], "window.png", { type: "image/png" });
207 const square = await createComposerImageThumbnail(original);
208 const [snapshot, cachedSnapshot] = await Promise.all([
209 createComposerImageThumbnail(original, "snapshot"),
210 createComposerImageThumbnail(original, "snapshot"),
211 ]);
212
213 expect(snapshot).toBe(
214 `data:image/png;base64,${Buffer.from(`${width}x${height}`).toString("base64")}`,
215 );
216 expect(drawImage).toHaveBeenLastCalledWith(
217 bitmap,
218 0,
219 0,
220 sourceWidth,
221 sourceHeight,
222 0,
223 0,
224 width,
225 height,
226 );
227 expect(cachedSnapshot).toBe(snapshot);
228 expect(await createComposerImageThumbnail(original, "snapshot")).toBe(snapshot);
229 expect(square).toBe(`data:image/png;base64,${Buffer.from("256x256").toString("base64")}`);
230 expect(await createComposerImageThumbnail(original)).toBe(square);
231 expect(decode).toHaveBeenCalledTimes(2);
232 expect(await original.text()).toBe("original bytes");
233 },
234 );
235
236 it("releases the decoded image when thumbnail encoding fails", async () => {
237 const close = vi.fn();
238 vi.stubGlobal(
239 "createImageBitmap",
240 vi.fn(async () => ({ width: 500, height: 500, close })),
241 );
242 vi.stubGlobal(
243 "OffscreenCanvas",
244 class {
245 getContext() {
246 return { drawImage: vi.fn() };
247 }
248 async convertToBlob() {
249 throw new Error("encoder unavailable");
250 }
251 },
252 );
253 expect(await createComposerImageThumbnail(makeFile(5))).toBeNull();
254 expect(close).toHaveBeenCalledOnce();
255 });
256});
257
258describe("dataUrlToFile", () => {
259 it("decodes a captured image without a fetch request", async () => {
260 const file = dataUrlToFile("data:image/png;base64,AAEC/w==", "window.png", "image/png");
261
262 expect(file.name).toBe("window.png");
263 expect(file.type).toBe("image/png");
264 expect([...new Uint8Array(await file.arrayBuffer())]).toEqual([0, 1, 2, 255]);
265 });
266});
267
268describe("compressImageForStash", () => {
269 it.each([true, false])(
270 "encodes with HTML canvas when WebP support is %s",
271 async (supportsWebp) => {
272 const { close } = stubCanvasPipeline(() => 120_000, { htmlCanvas: true, supportsWebp });
273
274 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
275
276 expect(result.ok && result.file.type).toBe(supportsWebp ? "image/webp" : "image/jpeg");
277 expect(result.ok && result.file.size).toBe(120_000);
278 expect(close).toHaveBeenCalledOnce();
279 },
280 );
281
282 it("keeps the exact data URL budget boundary and original bytes", async () => {
283 const original = makeFile(3);
284 const dataUrl = "data:image/png;base64,BwcH";
285
286 const result = await compressImageForStash(original, dataUrl.length);
287
288 expect(result.ok && result.image.dataUrl).toBe(dataUrl);
289 expect(result.ok && result.image.recompressed).toBe(false);
290 expect(await compressImageForStash(original, dataUrl.length - 1)).toEqual({
291 ok: false,
292 reason: "too-large",
293 });
294 });
295
296 it("reports unreadable if reading a small image fails", async () => {
297 const original = makeFile(3);
298 vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("read failed"));
299
300 expect(await compressImageForStash(original)).toEqual({ ok: false, reason: "unreadable" });
301 });
302
303 it("compresses an oversized source before reading it as a data URL", async () => {
304 stubCanvasPipeline(() => 120_000);
305 const original = makeFile(4_000_000);
306 const read = vi.spyOn(original, "arrayBuffer").mockRejectedValue(new Error("unneeded read"));
307
308 const result = await compressImageForStash(original);
309
310 expect(result.ok && result.image.recompressed).toBe(true);
311 expect(read).not.toHaveBeenCalled();
312 });
313
314 it("stores a small image verbatim without re-encoding", async () => {
315 const bitmapSpy = vi.fn();
316 vi.stubGlobal("createImageBitmap", bitmapSpy);
317
318 const result = await compressImageForStash(makeFile(1024));
319
320 expect(result.ok).toBe(true);
321 expect(result.ok && result.image.recompressed).toBe(false);
322 expect(result.ok && result.image.mimeType).toBe("image/png");
323 expect(result.ok && result.image.dataUrl.startsWith("data:image/png")).toBe(true);
324 expect(bitmapSpy).not.toHaveBeenCalled();
325 });
326
327 it("re-encodes an oversized image to WebP within the budget", async () => {
328 const { close, fillRect } = stubCanvasPipeline(() => 120_000);
329
330 const result = await compressImageForStash(makeFile(4_000_000));
331
332 expect(result.ok).toBe(true);
333 expect(result.ok && result.image.recompressed).toBe(true);
334 expect(result.ok && result.image.mimeType).toBe("image/webp");
335 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
336 expect(result.ok && result.image.sizeBytes).toBeLessThan(4_000_000);
337 expect(fillRect).not.toHaveBeenCalled();
338 expect(close).toHaveBeenCalled();
339 });
340
341 it("falls back to JPEG with a white matte when WebP encoding is unavailable", async () => {
342 const { fillRect } = stubCanvasPipeline(() => 120_000, { supportsWebp: false });
343
344 const result = await compressImageForStash(makeFile(4_000_000));
345
346 expect(result.ok && result.image.recompressed).toBe(true);
347 expect(result.ok && result.image.mimeType).toBe("image/jpeg");
348 expect(fillRect).toHaveBeenCalled();
349 });
350
351 it("steps quality down until the encoded image fits", async () => {
352 const { close } = stubCanvasPipeline((quality) => (quality <= 0.68 ? 400_000 : 3_000_000));
353
354 const result = await compressImageForStash(makeFile(9_000_000));
355
356 expect(result.ok && result.image.recompressed).toBe(true);
357 expect(result.ok && result.image.dataUrl.length <= MAX_STASH_IMAGE_DATA_URL_CHARS).toBe(true);
358 expect(close).toHaveBeenCalled();
359 });
360
361 it("reports too-large when even the smallest encoding overflows the budget", async () => {
362 const { close } = stubCanvasPipeline(() => 8_000_000);
363
364 const result = await compressImageForStash(makeFile(9_000_000));
365
366 expect(result).toEqual({ ok: false, reason: "too-large" });
367 expect(close).toHaveBeenCalled();
368 });
369
370 it("reports too-large for an oversized image when the browser cannot re-encode", async () => {
371 vi.stubGlobal("createImageBitmap", undefined);
372 vi.stubGlobal("OffscreenCanvas", undefined);
373
374 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
375 ok: false,
376 reason: "too-large",
377 });
378 });
379
380 it("reports unreadable when the image fails to decode", async () => {
381 vi.stubGlobal(
382 "createImageBitmap",
383 vi.fn(async () => {
384 throw new Error("corrupt image");
385 }),
386 );
387 vi.stubGlobal(
388 "OffscreenCanvas",
389 class {
390 getContext() {
391 return null;
392 }
393 },
394 );
395
396 expect(await compressImageForStash(makeFile(4_000_000))).toEqual({
397 ok: false,
398 reason: "unreadable",
399 });
400 });
401
402 it("compressImageToByteLimit passes small files through byte-for-byte", async () => {
403 const bitmapSpy = vi.fn();
404 vi.stubGlobal("createImageBitmap", bitmapSpy);
405
406 const original = makeFile(1024);
407 const result = await compressImageToByteLimit(original, 10 * 1024 * 1024);
408
409 expect(result.ok).toBe(true);
410 expect(result.ok && result.recompressed).toBe(false);
411 expect(result.ok && result.file).toBe(original);
412 expect(bitmapSpy).not.toHaveBeenCalled();
413 });
414
415 it("compressImageToByteLimit re-encodes an oversized file under the byte cap", async () => {
416 stubCanvasPipeline(() => 200_000);
417
418 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
419
420 expect(result.ok).toBe(true);
421 expect(result.ok && result.recompressed).toBe(true);
422 expect(result.ok && result.file.type).toBe("image/webp");
423 expect(result.ok && result.file.name).toBe("shot.webp");
424 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
425 });
426
427 it("compressImageToByteLimit refuses sources above the decode-safety ceiling", async () => {
428 const bitmapSpy = vi.fn();
429 vi.stubGlobal("createImageBitmap", bitmapSpy);
430
431 const result = await compressImageToByteLimit(
432 makeFile(MAX_COMPRESSIBLE_SOURCE_BYTES + 1),
433 10 * 1024 * 1024,
434 );
435
436 expect(result).toEqual({ ok: false, reason: "too-large" });
437 expect(bitmapSpy).not.toHaveBeenCalled();
438 });
439
440 it("compressImageToByteLimit reports too-large when no encoding fits", async () => {
441 const { close } = stubCanvasPipeline(() => 3_000_000);
442
443 const result = await compressImageToByteLimit(makeFile(2_000_000), 1_000_000);
444
445 expect(result).toEqual({ ok: false, reason: "too-large" });
446 expect(close).toHaveBeenCalled();
447 });
448
449 it("shrinks below the source size when the image is already under MAX_DIMENSION", async () => {
450 let smallestRequested = Number.POSITIVE_INFINITY;
451 const close = vi.fn();
452 vi.stubGlobal(
453 "createImageBitmap",
454 vi.fn(async () => ({ width: 800, height: 600, close })),
455 );
456 vi.stubGlobal(
457 "OffscreenCanvas",
458 class {
459 constructor(
460 public width: number,
461 public height: number,
462 ) {
463 smallestRequested = Math.min(smallestRequested, width);
464 }
465 getContext() {
466 return { fillStyle: "", fillRect: vi.fn(), drawImage: vi.fn() };
467 }
468 async convertToBlob({ type }: { type: string; quality: number }) {
469 const size = smallestRequested < 800 ? 100_000 : 5_000_000;
470 return new Blob([new Uint8Array(size)], { type });
471 }
472 },
473 );
474
475 const result = await compressImageForStash(makeFile(4_000_000));
476
477 expect(result.ok).toBe(true);
478 expect(smallestRequested).toBeLessThan(800);
479 });
480});
481
482describe("HEIC attachment preparation", () => {
483 it("recognizes HEIC and HEIF MIME types and case-insensitive file extensions", () => {
484 expect(isHeicImageFile({ name: "photo.bin", type: "image/heic" })).toBe(true);
485 expect(isHeicImageFile({ name: "photo.bin", type: "image/heif" })).toBe(true);
486 expect(isHeicImageFile({ name: "photo.heic", type: "image/heic-sequence" })).toBe(false);
487 expect(isHeicImageFile({ name: "photo.heif", type: "image/heif-sequence" })).toBe(false);
488 expect(isHeicImageFile({ name: "IMG_1234.HEIC", type: "" })).toBe(true);
489 expect(isHeicImageFile({ name: "photo.heif", type: "application/octet-stream" })).toBe(true);
490 expect(isHeicImageFile({ name: "photo.png", type: "image/png" })).toBe(false);
491 expect(isHeicImageFile({ name: "photo.heic", type: "image/png" })).toBe(false);
492 expect(isHeicImageFile({ name: "photo.heif", type: "image/jpeg" })).toBe(false);
493 });
494
495 it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => {
496 const original = makeHeicFile({
497 name: "IMG_1234.HEIC",
498 type: "",
499 lastModified: 123,
500 });
501 mocks.heicTo.mockResolvedValueOnce(
502 new Blob([new Uint8Array([4, 5, 6, 7])], { type: "image/jpeg" }),
503 );
504
505 const result = await prepareImageForAttachment(original, 1024);
506
507 expect(mocks.heicTo).toHaveBeenCalledWith({
508 blob: original,
509 type: "image/jpeg",
510 quality: 0.92,
511 });
512 expect(result.ok && result.file.name).toBe("IMG_1234.jpg");
513 expect(result.ok && result.file.type).toBe("image/jpeg");
514 expect(result.ok && result.file.size).toBe(4);
515 expect(result.ok && result.file.lastModified).toBe(123);
516 expect(result.ok && result.recompressed).toBe(true);
517 });
518
519 it("keeps oversized converted photos in JPEG format while shrinking them", async () => {
520 const original = makeHeicFile({
521 name: "photo.heif",
522 type: "image/heif",
523 });
524 mocks.heicTo.mockResolvedValueOnce(
525 new Blob([new Uint8Array(2_000_000)], { type: "image/jpeg" }),
526 );
527 const { fillRect } = stubCanvasPipeline(() => 200_000);
528
529 const result = await prepareImageForAttachment(original, 1_000_000);
530
531 expect(result.ok && result.file.name).toBe("photo.jpg");
532 expect(result.ok && result.file.type).toBe("image/jpeg");
533 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
534 expect(fillRect).toHaveBeenCalled();
535 });
536
537 it("compresses JPEG intermediates above the source safety ceiling", async () => {
538 const original = makeHeicFile({
539 name: "large.heic",
540 type: "image/heic",
541 });
542 mocks.heicTo.mockResolvedValueOnce(
543 new Blob([new Uint8Array(MAX_COMPRESSIBLE_SOURCE_BYTES + 1)], {
544 type: "image/jpeg",
545 }),
546 );
547 const { close } = stubCanvasPipeline(() => 200_000);
548
549 const result = await prepareImageForAttachment(original, 1_000_000);
550
551 expect(result.ok && result.file.name).toBe("large.jpg");
552 expect(result.ok && result.file.type).toBe("image/jpeg");
553 expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000);
554 expect(close).toHaveBeenCalled();
555 });
556
557 it.each([
558 { label: "24 MP", width: 5712, height: 4284 },
559 { label: "48 MP", width: 8064, height: 6048 },
560 ])("accepts $label HEIC photos", async ({ width, height }) => {
561 const original = makeHeicFile({ width, height });
562 mocks.heicTo.mockResolvedValueOnce(new Blob(["jpeg"], { type: "image/jpeg" }));
563
564 const result = await prepareImageForAttachment(original, 1024);
565
566 expect(result.ok && result.file.type).toBe("image/jpeg");
567 expect(mocks.heicTo).toHaveBeenCalledOnce();
568 });
569
570 it("rejects oversized HEIC dimensions before loading the decoder", async () => {
571 const original = makeHeicFile({ width: 16_000, height: 4001 });
572
573 expect(await prepareImageForAttachment(original, 1024)).toEqual({
574 ok: false,
575 reason: "too-large",
576 });
577 expect(mocks.heicTo).not.toHaveBeenCalled();
578 });
579
580 it("rejects invalid HEIC metadata before loading the decoder", async () => {
581 const original = new File([new Uint8Array([1, 2, 3])], "broken.heic", {
582 type: "image/heic",
583 });
584
585 expect(await prepareImageForAttachment(original, 1024)).toEqual({
586 ok: false,
587 reason: "unreadable",
588 });
589 expect(mocks.heicTo).not.toHaveBeenCalled();
590 });
591
592 it("reports unreadable when HEIC decoding fails", async () => {
593 const original = makeHeicFile({
594 name: "broken.heic",
595 type: "image/heic",
596 });
597 mocks.heicTo.mockRejectedValueOnce(new Error("Invalid HEIC image"));
598
599 expect(await prepareImageForAttachment(original, 1024)).toEqual({
600 ok: false,
601 reason: "unreadable",
602 });
603 });
604
605 it("rejects unsafe HEIC sources before loading the decoder", async () => {
606 const original = new File(["photo"], "large.heic", { type: "image/heic" });
607 Object.defineProperty(original, "size", { value: MAX_COMPRESSIBLE_SOURCE_BYTES + 1 });
608
609 expect(await prepareImageForAttachment(original, 1024)).toEqual({
610 ok: false,
611 reason: "too-large",
612 });
613 expect(mocks.heicTo).not.toHaveBeenCalled();
614 });
615
616 it("leaves supported images untouched without loading the HEIC decoder", async () => {
617 const original = makeFile(1024);
618
619 const result = await prepareImageForAttachment(original, 2048);
620
621 expect(result.ok && result.file).toBe(original);
622 expect(result.ok && result.recompressed).toBe(false);
623 expect(mocks.heicTo).not.toHaveBeenCalled();
624 });
625});
626
627describe("attachment max edge", () => {
628 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
629 const u16 = (n: number) => [(n >>> 8) & 0xff, n & 0xff];
630 const pngHeader = (width: number, height: number) => [
631 0x89,
632 0x50,
633 0x4e,
634 0x47,
635 0x0d,
636 0x0a,
637 0x1a,
638 0x0a,
639 ...u32(13),
640 0x49,
641 0x48,
642 0x44,
643 0x52,
644 ...u32(width),
645 ...u32(height),
646 8,
647 6,
648 0,
649 0,
650 0,
651 ];
652 const jpegHeader = (width: number, height: number) => [
653 0xff,
654 0xd8,
655 0xff,
656 0xc0,
657 ...u16(17),
658 8,
659 ...u16(height),
660 ...u16(width),
661 ];
662 const image = (header: number[], name: string, type: string) =>
663 new File([new Uint8Array([...header, ...new Uint8Array(2048).fill(7)])], name, { type });
664
665 function stubDecoder(bitmapSize: { width: number; height: number }) {
666 const decode = vi.fn(async () => ({ ...bitmapSize, close: vi.fn() }));
667 const canvases: Array<{ width: number; height: number }> = [];
668 const encodes: Array<{ type: string; quality: number }> = [];
669 const fillRect = vi.fn();
670 vi.stubGlobal("createImageBitmap", decode);
671 vi.stubGlobal(
672 "OffscreenCanvas",
673 class {
674 constructor(width: number, height: number) {
675 canvases.push({ width, height });
676 }
677 getContext() {
678 return { fillRect, drawImage: vi.fn() };
679 }
680 async convertToBlob(options: { type: string; quality: number }) {
681 encodes.push(options);
682 return new Blob([new Uint8Array(500_000)], { type: options.type });
683 }
684 },
685 );
686 return { decode, canvases, encodes, fillRect };
687 }
688
689 it("scales a large PNG screenshot under the byte cap to 2000px and keeps it a PNG", async () => {
690 const { decode, canvases, encodes, fillRect } = stubDecoder({ width: 3024, height: 1964 });
691 const original = image(pngHeader(3024, 1964), "shot.png", "image/png");
692
693 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
694
695 expect(decode).toHaveBeenCalledExactlyOnceWith(original, { imageOrientation: "from-image" });
696 expect(canvases).toEqual([{ width: 2000, height: 1299 }]);
697 expect(encodes.map(({ type }) => type)).toEqual(["image/png"]);
698 expect(fillRect).not.toHaveBeenCalled();
699 expect(result.ok && result.recompressed).toBe(true);
700 expect(result.ok && result.imageSize).toEqual({ width: 2000, height: 1299 });
701 expect(result.ok && result.file.name).toBe("shot.png");
702 expect(result.ok && result.file.type).toBe("image/png");
703 });
704
705 it("scales a rotated JPEG by its displayed size and keeps it a JPEG", async () => {
706 const { canvases, encodes } = stubDecoder({ width: 3024, height: 4032 });
707 const original = image(jpegHeader(4032, 3024), "photo.jpg", "image/jpeg");
708
709 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
710
711 expect(canvases).toEqual([{ width: 1500, height: 2000 }]);
712 expect(encodes).toEqual([{ type: "image/jpeg", quality: 0.92 }]);
713 expect(result.ok && result.file.type).toBe("image/jpeg");
714 expect(result.ok && result.imageSize).toEqual({ width: 1500, height: 2000 });
715 });
716
717 it.each([
718 { label: "a 2000px PNG", header: pngHeader(2000, 1200), type: "image/png" },
719 {
720 label: "a 3000px GIF",
721 header: [0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0xb8, 0x0b, 0x10, 0x04],
722 type: "image/gif",
723 },
724 ])("passes $label through without decoding it", async ({ header, type }) => {
725 const { decode } = stubDecoder({ width: 3000, height: 1040 });
726 const original = image(header, "image", type);
727
728 const result = await prepareImageForAttachment(original, 10 * 1024 * 1024);
729
730 expect(result.ok && result.file).toBe(original);
731 expect(result.ok && result.recompressed).toBe(false);
732 expect(decode).not.toHaveBeenCalled();
733 });
734});
735
736describe("snapshot coordinates after compression", () => {
737 const source: SnapShotSource = {
738 kind: "snap-shot",
739 capturedAt: "2026-09-01T00:00:00.000Z",
740 appName: "Editor",
741 windowTitle: "main.ts",
742 accessibility: {
743 format: "element-tree",
744 coordinateSpace: "captured-image",
745 imageSize: { width: 2560, height: 1600 },
746 truncated: false,
747 root: {
748 role: "window",
749 bounds: { x: 0, y: 0, width: 2560, height: 1600 },
750 children: [
751 {
752 role: "button",
753 name: "Save",
754 bounds: { x: 2400, y: 1400, width: 100, height: 100 },
755 children: [],
756 },
757 { role: "static_text", name: "Untitled", bounds: null, children: [] },
758 ],
759 },
760 },
761 };
762
763 it.each(["stash", "delivery"])(
764 "rescales the source and restores it with the compressed %s image",
765 async (path) => {
766 stubCanvasPipeline(() => 100);
767 vi.stubGlobal(
768 "createImageBitmap",
769 vi.fn(async () => ({ width: 2560, height: 1600, close: vi.fn() })),
770 );
771 const original = makeFile(2000);
772 const compressed =
773 path === "stash"
774 ? await compressImageForStash(original, 1000)
775 : await compressImageToByteLimit(original, 1000);
776 expect(compressed.ok).toBe(true);
777 if (!compressed.ok) throw new Error("Compression failed");
778 const image =
779 "image" in compressed
780 ? compressed.image
781 : {
782 ...compressed,
783 mimeType: compressed.file.type,
784 sizeBytes: compressed.file.size,
785 dataUrl: `data:${compressed.file.type};base64,${Buffer.from(await compressed.file.arrayBuffer()).toString("base64")}`,
786 };
787 expect(image.imageSize).toEqual({ width: 2000, height: 1250 });
788 const resized = resizeSnapShotSource(source, image.imageSize);
789 const [restored] = hydrateImagesFromPersisted([
790 {
791 id: "capture",
792 name: "window.webp",
793 mimeType: image.mimeType,
794 sizeBytes: image.sizeBytes,
795 dataUrl: image.dataUrl,
796 source: resized,
797 },
798 ]);
799 expect(restored?.source?.accessibility).toMatchObject({
800 imageSize: { width: 2000, height: 1250 },
801 root: {
802 bounds: { x: 0, y: 0, width: 2000, height: 1250 },
803 children: [{ bounds: { x: 1875, y: 1094, width: 78, height: 78 } }, { bounds: null }],
804 },
805 });
806 expect(source.accessibility).toMatchObject({ imageSize: { width: 2560, height: 1600 } });
807 },
808 );
809
810 it("keeps uncompressed sources unchanged", () => {
811 expect(resizeSnapShotSource(source)).toBe(source);
812 });
813});