Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

242 lines · 12.4 KBRaw History
1import { crc32, deflateSync } from "node:zlib";
2import { describe, expect, it } from "vitest";
3import encodeJpeg, { init as initJpegEncode } from "@jsquash/jpeg/encode.js";
4import decodeWebpWasm, { init as initWebpDecode } from "@jsquash/webp/decode.js";
5import encodeWebp from "@jsquash/webp/encode.js";
6import JPEG_ENC_WASM from "@jsquash/jpeg/codec/enc/mozjpeg_enc.wasm";
7import WEBP_DEC_WASM from "@jsquash/webp/codec/dec/webp_dec.wasm";
8import { AVATAR_SIZES, MAX_AVATAR_BYTES, cropAndShrink, imageSize, jpegOrientation, makeAvatarImages, orientSquare, shrinkFactor, sniffImage, squareCrop, type Pixels } from "../../src/lib/image.js";
9import { HttpError } from "../../src/lib/util.js";
10
11// ---------------------------------------------------------------- fixtures, generated here
12
13type Paint = (x: number, y: number) => [number, number, number, number?];
14
15function pixels(width: number, height: number, paint: Paint): Pixels {
16 const data = new Uint8ClampedArray(width * height * 4);
17 for (let y = 0; y < height; y++)
18 for (let x = 0; x < width; x++) {
19 const [r, g, b, a = 255] = paint(x, y);
20 data.set([r, g, b, a], (y * width + x) * 4);
21 }
22 return { data, width, height };
23}
24
25/** A minimal RGBA PNG: IHDR, one IDAT (filter 0 rows), IEND. */
26function png(img: Pixels): Uint8Array {
27 const chunk = (type: string, body: Uint8Array) => {
28 const out = new Uint8Array(12 + body.length);
29 const v = new DataView(out.buffer);
30 v.setUint32(0, body.length);
31 out.set(new TextEncoder().encode(type), 4);
32 out.set(body, 8);
33 v.setUint32(8 + body.length, crc32(out.subarray(4, 8 + body.length)));
34 return out;
35 };
36 const ihdr = new Uint8Array(13);
37 new DataView(ihdr.buffer).setUint32(0, img.width);
38 new DataView(ihdr.buffer).setUint32(4, img.height);
39 ihdr.set([8, 6, 0, 0, 0], 8); // 8-bit RGBA
40 const raw = new Uint8Array((img.width * 4 + 1) * img.height);
41 for (let y = 0; y < img.height; y++) raw.set(img.data.subarray(y * img.width * 4, (y + 1) * img.width * 4), y * (img.width * 4 + 1) + 1);
42 return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())]);
43}
44
45let jpegReady: Promise<unknown> | undefined;
46async function jpeg(img: Pixels, quality = 85): Promise<Uint8Array> {
47 jpegReady ??= (initJpegEncode as unknown as (m: WebAssembly.Module) => Promise<unknown>)(JPEG_ENC_WASM);
48 await jpegReady;
49 return new Uint8Array(await encodeJpeg(img as Parameters<typeof encodeJpeg>[0], { quality }));
50}
51
52async function decodeWebp(bytes: ArrayBuffer): Promise<Pixels> {
53 await (initWebpDecode as unknown as (m: WebAssembly.Module) => Promise<unknown>)(WEBP_DEC_WASM);
54 return (await decodeWebpWasm(bytes)) as Pixels;
55}
56
57async function webp(img: Pixels, lossless = false): Promise<Uint8Array> {
58 await makeAvatarImages(png(pixels(1, 1, () => [0, 0, 0]))); // initialises the shared encoder
59 return new Uint8Array(await encodeWebp(img as Parameters<typeof encodeWebp>[0], { quality: 80, lossless: lossless ? 1 : 0 }));
60}
61
62/** Insert an EXIF APP1 segment carrying only an orientation tag right after SOI. */
63function withOrientation(jpg: Uint8Array, orientation: number, le = true): Uint8Array {
64 const tiff = new Uint8Array(26);
65 const v = new DataView(tiff.buffer);
66 tiff.set(new TextEncoder().encode(le ? "II" : "MM"), 0);
67 v.setUint16(2, 42, le);
68 v.setUint32(4, 8, le); // IFD0 offset
69 v.setUint16(8, 1, le); // one entry
70 v.setUint16(10, 0x0112, le); // Orientation
71 v.setUint16(12, 3, le); // SHORT
72 v.setUint32(14, 1, le); // count
73 v.setUint16(18, orientation, le);
74 const body = Buffer.concat([Buffer.from("Exif\0\0", "binary"), tiff]);
75 const seg = Buffer.concat([Buffer.from([0xff, 0xe1, (body.length + 2) >> 8, (body.length + 2) & 0xff]), body]);
76 return Buffer.concat([jpg.subarray(0, 2), seg, jpg.subarray(2)]);
77}
78
79/** A photo-like test card: smooth gradients plus fine noise, which is what makes real photos expensive to encode. */
80const photo: Paint = (x, y) => {
81 const n = ((x * 7919 + y * 104729) ^ (x * y)) % 23;
82 return [(x * 0.21 + Math.sin(y / 37) * 40 + 90 + n) & 255, (y * 0.17 + Math.cos(x / 53) * 50 + 100 + n) & 255, (150 + Math.sin((x + y) / 71) * 60 + n) & 255];
83};
84
85const px = (img: Pixels, x: number, y: number) => [...img.data.subarray((y * img.width + x) * 4, (y * img.width + x) * 4 + 4)];
86
87async function status(p: Promise<unknown>): Promise<{ status: number; message: string }> {
88 try {
89 await p;
90 } catch (e) {
91 if (e instanceof HttpError) return { status: e.status, message: e.detail };
92 throw e;
93 }
94 throw new Error("expected a rejection");
95}
96
97// ---------------------------------------------------------------- tests
98
99describe("image format sniffing", () => {
100 it("recognises JPEG, PNG and WebP by their magic bytes only", async () => {
101 const img = pixels(3, 2, () => [10, 20, 30]);
102 expect(sniffImage(await jpeg(img))).toBe("jpeg");
103 expect(sniffImage(png(img))).toBe("png");
104 expect(sniffImage(await webp(img))).toBe("webp");
105 expect(sniffImage(new TextEncoder().encode("GIF89a\x01\x00\x01\x00"))).toBeNull();
106 expect(sniffImage(new TextEncoder().encode("\0\0\0\x18ftypheic"))).toBeNull();
107 expect(sniffImage(new TextEncoder().encode("<svg xmlns='http://www.w3.org/2000/svg'/>"))).toBeNull();
108 expect(sniffImage(new TextEncoder().encode("RIFF\0\0\0\0WAVEfmt "))).toBeNull();
109 expect(sniffImage(new Uint8Array())).toBeNull();
110 });
111
112 it("reads dimensions from headers without decoding", async () => {
113 const img = pixels(37, 21, photo);
114 expect(imageSize(await jpeg(img), "jpeg")).toEqual({ width: 37, height: 21 });
115 expect(imageSize(withOrientation(await jpeg(img), 6), "jpeg")).toEqual({ width: 37, height: 21 });
116 expect(imageSize(png(img), "png")).toEqual({ width: 37, height: 21 });
117 expect(imageSize(await webp(img), "webp")).toEqual({ width: 37, height: 21 }); // VP8
118 expect(imageSize(await webp(img, true), "webp")).toEqual({ width: 37, height: 21 }); // VP8L
119 expect(imageSize(await webp(pixels(37, 21, (x) => [1, 2, 3, x * 6])), "webp")).toEqual({ width: 37, height: 21 }); // VP8X (alpha)
120 expect(imageSize(new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 2]), "jpeg")).toBeNull();
121 });
122
123 it("reads the EXIF orientation of a JPEG", async () => {
124 const jpg = await jpeg(pixels(8, 8, photo));
125 expect(jpegOrientation(jpg)).toBe(1);
126 expect(jpegOrientation(withOrientation(jpg, 6))).toBe(6);
127 expect(jpegOrientation(withOrientation(jpg, 8, false))).toBe(8);
128 expect(jpegOrientation(withOrientation(jpg, 42))).toBe(1);
129 });
130});
131
132describe("crop and scale math", () => {
133 it("takes the centred square", () => {
134 expect(squareCrop(3000, 2000)).toEqual({ x: 500, y: 0, side: 2000 });
135 expect(squareCrop(2000, 3001)).toEqual({ x: 0, y: 500, side: 2000 });
136 expect(squareCrop(64, 64)).toEqual({ x: 0, y: 0, side: 64 });
137 });
138
139 it("box-filters by an integer factor, keeping at least the minimum", () => {
140 expect(shrinkFactor(4096, 512)).toBe(8);
141 expect(shrinkFactor(2000, 512)).toBe(3); // 666 px
142 expect(shrinkFactor(1023, 512)).toBe(1);
143 expect(shrinkFactor(100, 512)).toBe(1);
144 expect(cropAndShrink(pixels(3000, 2000, () => [1, 2, 3])).width).toBe(666);
145 expect(cropAndShrink(pixels(300, 200, () => [1, 2, 3])).width).toBe(200);
146 });
147
148 it("averages colour weighted by alpha and crops off the sides", () => {
149 // 4×2: red | green green | blue. The centre square is the two green columns.
150 const img = pixels(4, 2, (x) => (x === 0 ? [255, 0, 0] : x === 3 ? [0, 0, 255] : [0, 200, 0]));
151 const out = cropAndShrink(img, 1);
152 expect(out.width).toBe(1);
153 expect(px(out, 0, 0)).toEqual([0, 200, 0, 255]);
154 // A transparent black pixel next to opaque white: still white, half transparent.
155 const half = cropAndShrink(pixels(2, 1, (x) => (x ? [255, 255, 255, 255] : [0, 0, 0, 0])), 1);
156 expect(px(half, 0, 0)).toEqual([0, 0, 0, 0]); // 2×1 crops to the centre 1×1 (x = 0)
157 const quad = cropAndShrink(pixels(2, 2, (x) => (x ? [255, 255, 255, 255] : [0, 0, 0, 0])), 1);
158 expect(px(quad, 0, 0)).toEqual([255, 255, 255, 128]);
159 });
160
161 it("applies EXIF orientations to a square", () => {
162 const A = [1, 0, 0, 255],
163 B = [2, 0, 0, 255],
164 C = [3, 0, 0, 255],
165 D = [4, 0, 0, 255];
166 const img = pixels(2, 2, (x, y) => [[A, B], [C, D]][y]![x]! as [number, number, number, number]);
167 const grid = (o: number) => {
168 const r = orientSquare(img, o);
169 return [px(r, 0, 0)[0], px(r, 1, 0)[0], px(r, 0, 1)[0], px(r, 1, 1)[0]];
170 };
171 expect(grid(1)).toEqual([1, 2, 3, 4]);
172 expect(grid(2)).toEqual([2, 1, 4, 3]); // mirrored
173 expect(grid(3)).toEqual([4, 3, 2, 1]); // 180°
174 expect(grid(4)).toEqual([3, 4, 1, 2]); // flipped
175 expect(grid(5)).toEqual([1, 3, 2, 4]); // transposed
176 expect(grid(6)).toEqual([3, 1, 4, 2]); // 90° clockwise
177 expect(grid(7)).toEqual([4, 2, 3, 1]); // transversed
178 expect(grid(8)).toEqual([2, 4, 1, 3]); // 90° counter-clockwise
179 });
180});
181
182describe("decode → crop → resize → encode", () => {
183 it("turns a landscape photo into small square WebPs of the centre", async () => {
184 // Red and blue bars outside the centre square; the avatar must be all photo, no bars.
185 const jpg = await jpeg(pixels(1200, 800, (x, y) => (x < 200 ? [255, 0, 0] : x >= 1000 ? [0, 0, 255] : photo(x, y))));
186 const out = await makeAvatarImages(jpg);
187 expect([...out.keys()]).toEqual([...AVATAR_SIZES]);
188 const sizes: Record<number, number> = {};
189 for (const [size, bytes] of out) {
190 sizes[size] = bytes.byteLength;
191 expect(sniffImage(bytes)).toBe("webp");
192 expect(imageSize(bytes, "webp")).toEqual({ width: size, height: size });
193 const back = await decodeWebp(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer);
194 for (const [x, y] of [
195 [0, 0],
196 [size - 1, size / 2],
197 ]) {
198 const [r, , b] = px(back as Pixels, x!, y!);
199 expect(r! < 200 || b! < 200).toBe(true); // neither pure red nor pure blue survived the crop
200 }
201 }
202 // A few KB each.
203 console.log("avatar WebP bytes (1200×800 synthetic photo):", sizes);
204 expect(sizes[256]!).toBeLessThan(20_000);
205 expect(sizes[64]!).toBeLessThan(sizes[256]!);
206 });
207
208 it("keeps transparency from a PNG and accepts WebP input", async () => {
209 const pic = pixels(300, 300, (x, y) => ((x - 150) ** 2 + (y - 150) ** 2 < 120 ** 2 ? [30, 120, 220] : [0, 0, 0, 0]));
210 const fromPng = await makeAvatarImages(png(pic));
211 const corner = px((await decodeWebp(fromPng.get(64)!.slice().buffer)) as Pixels, 0, 0);
212 const centre = px((await decodeWebp(fromPng.get(64)!.slice().buffer)) as Pixels, 32, 32);
213 expect(corner[3]).toBe(0);
214 expect(centre[3]).toBe(255);
215 const fromWebp = await makeAvatarImages(await webp(pixels(100, 50, photo)));
216 expect(imageSize(fromWebp.get(256)!, "webp")).toEqual({ width: 256, height: 256 });
217 });
218
219 it("rotates a JPEG by its EXIF orientation", async () => {
220 // Stored: red top half, blue bottom half. Orientation 6 (rotate 90° clockwise) shows red on the right.
221 const jpg = withOrientation(await jpeg(pixels(300, 300, (_x, y) => (y < 150 ? [230, 20, 20] : [20, 20, 230])), 95), 6);
222 const out = await makeAvatarImages(jpg);
223 const img = (await decodeWebp(out.get(128)!.slice().buffer)) as Pixels;
224 const [lr, , lb] = px(img, 10, 64);
225 const [rr, , rb] = px(img, 117, 64);
226 expect(lb!).toBeGreaterThan(lr!);
227 expect(rr!).toBeGreaterThan(rb!);
228 });
229
230 it("rejects what it cannot or should not handle", async () => {
231 expect(await status(makeAvatarImages(new TextEncoder().encode("GIF89a\x01\x00\x01\x00")))).toEqual({ status: 422, message: "Use a JPEG, PNG or WebP image." });
232 expect((await status(makeAvatarImages(new Uint8Array(MAX_AVATAR_BYTES + 1)))).status).toBe(413);
233 // A header claiming 5000×10: refused before anything is decoded.
234 const wide = png(pixels(1, 1, () => [0, 0, 0]));
235 new DataView(wide.buffer, wide.byteOffset).setUint32(16, 5000);
236 expect(await status(makeAvatarImages(wide))).toMatchObject({ status: 422, message: expect.stringContaining("3072") });
237 // A plausible JPEG header (64×64 baseline frame) followed by junk.
238 const junk = Uint8Array.from([0xff, 0xd8, 0xff, 0xc0, 0, 17, 8, 0, 64, 0, 64, 3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1, ...Array.from({ length: 200 }, (_, i) => (i * 37) & 0xff)]);
239 expect(imageSize(junk, "jpeg")).toEqual({ width: 64, height: 64 });
240 expect(await status(makeAvatarImages(junk))).toMatchObject({ status: 422, message: expect.stringContaining("could not be read") });
241 });
242});