Branchwell

Lumen & Gesso / website · lumengesso.com / app / lib / url-to-file.ts

1// Reconstruct a browser File from a remote image URL. Used to rehydrate
2// the builder when a customer returns to EDIT a pending order whose
3// photos already live on Cloudflare Images: ImageDrop and the /api/orders
4// submit path both work in terms of File objects, so turning the stored
5// URL back into a File lets the existing flow run unchanged — no
6// "please upload a photo" prompt for an image the customer already gave us.
7//
8// CF Images (imagedelivery.net) serves with permissive CORS, so the
9// cross-origin fetch succeeds. The print pipeline only accepts JPEG/PNG
10// (see upload-limits), so anything CF hands back in another format (e.g.
11// a WebP negotiated by the browser) is re-encoded to JPEG via a canvas
12// before becoming a File — otherwise the re-submit would fail validation.
13
14import { ACCEPTED_IMAGE_MIME } from './upload-limits';
15
16export async function urlToFile(url: string, filename: string): Promise<File> {
17 const res = await fetch(url, { mode: 'cors' });
18 if (!res.ok) throw new Error(`fetch failed (${res.status})`);
19 const blob = await res.blob();
20 if ((ACCEPTED_IMAGE_MIME as readonly string[]).includes(blob.type)) {
21 return new File([blob], filename, { type: blob.type });
22 }
23 const jpeg = await blobToJpeg(blob);
24 const jpegName = filename.replace(/\.\w+$/, '') + '.jpg';
25 return new File([jpeg], jpegName, { type: 'image/jpeg' });
26}
27
28// Decode an arbitrary image blob and re-encode it as JPEG via a canvas.
29function blobToJpeg(blob: Blob): Promise<Blob> {
30 return new Promise((resolve, reject) => {
31 const objUrl = URL.createObjectURL(blob);
32 const img = new Image();
33 img.onload = () => {
34 URL.revokeObjectURL(objUrl);
35 const canvas = document.createElement('canvas');
36 canvas.width = img.naturalWidth;
37 canvas.height = img.naturalHeight;
38 const ctx = canvas.getContext('2d');
39 if (!ctx) return reject(new Error('no 2d context'));
40 ctx.drawImage(img, 0, 0);
41 canvas.toBlob(
42 (out) => (out ? resolve(out) : reject(new Error('canvas toBlob failed'))),
43 'image/jpeg',
44 0.92,
45 );
46 };
47 img.onerror = () => {
48 URL.revokeObjectURL(objUrl);
49 reject(new Error('image decode failed'));
50 };
51 img.src = objUrl;
52 });
53}