import 'server-only'; import { getCloudflareContext } from '@opennextjs/cloudflare'; type Dimensions = { width: number; height: number }; type RasterInfo = Dimensions & { format: string }; type Bounds = Dimensions & { left: number; top: number }; type Margins = { left: number; top: number; right: number; bottom: number }; type ImageFit = 'scale-down' | 'squeeze'; type ImageTransform = Partial & { fit?: ImageFit; trim?: Margins }; type ImageOutput = | { format: 'image/png'; anim: false } | { format: 'image/jpeg'; quality: number; background?: string; anim: false }; type ImageTransformer = { transform(options: ImageTransform): ImageTransformer; draw(overlay: ReadableStream, options: { left: number; top: number }): ImageTransformer; output(options: ImageOutput): Promise<{ response(): Response }>; }; type WorkerImageResources = { IMAGES?: { input(source: ReadableStream): ImageTransformer; info(source: ReadableStream): Promise; }; rasterizeSvg?: (svg: string) => Promise; }; function workerImages() { if (!process.env.CLOUDFLARE_DEPLOYMENT_ENV) return undefined; const { IMAGES, rasterizeSvg } = getCloudflareContext().env as WorkerImageResources; if (!IMAGES || !rasterizeSvg) throw new Error('Cloudflare image processing is unavailable.'); return { binding: IMAGES, rasterizeSvg }; } async function nodeImage(bytes: Buffer, limitInputPixels?: number) { const { default: sharp } = await import('sharp'); return sharp(bytes, limitInputPixels ? { limitInputPixels } : undefined); } function stream(bytes: Uint8Array): ReadableStream { return new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); } }); } async function output(transform: ImageTransformer, format: ImageOutput): Promise { return Buffer.from(await (await transform.output(format)).response().arrayBuffer()); } export async function imageDimensions(input: Buffer): Promise> { const worker = workerImages(); if (!worker) return (await nodeImage(input)).metadata(); const info = await worker.binding.info(stream(input)); return 'width' in info ? { width: info.width, height: info.height } : {}; } export async function cropImage(input: Buffer, source: Dimensions, crop: Bounds): Promise { const worker = workerImages(); if (!worker) return (await nodeImage(input)).extract(crop).png().toBuffer(); const trim = { left: crop.left, top: crop.top, right: source.width - crop.left - crop.width, bottom: source.height - crop.top - crop.height, }; return output(worker.binding.input(stream(input)).transform({ trim }), { format: 'image/png', anim: false }); } export async function encodePhotoJpeg(input: Buffer, quality: number, edge?: number): Promise { const worker = workerImages(); if (!worker) { const image = await nodeImage(input); if (edge) image.autoOrient().resize(edge, edge, { fit: 'inside', withoutEnlargement: true }); return image.flatten({ background: '#ffffff' }).jpeg({ quality, mozjpeg: !edge }).toBuffer(); } const image = worker.binding.input(stream(input)); const sized = edge ? image.transform({ width: edge, height: edge, fit: 'scale-down' }) : image; return output(sized, { format: 'image/jpeg', quality, background: '#ffffff', anim: false }); } export async function encodeReviewPhoto(input: Buffer): Promise { const worker = workerImages(); const target = 1600; const maxPixels = 40_000_000; if (!worker) { const image = await nodeImage(input, maxPixels); const { format } = await image.metadata(); if (!format || !['jpeg', 'png', 'webp'].includes(format)) return null; return image.rotate().resize({ width: target, height: target, fit: 'inside', withoutEnlargement: true }) .flatten({ background: '#fff' }).jpeg({ quality: 84 }).toBuffer(); } const info = await worker.binding.info(stream(input)); if (!['image/jpeg', 'image/png', 'image/webp'].includes(info.format)) return null; if (!('width' in info) || info.width * info.height > maxPixels) throw new Error('Review photo dimensions exceed the limit.'); const sized = worker.binding.input(stream(input)).transform({ width: target, height: target, fit: 'scale-down' }); return output(sized, { format: 'image/jpeg', quality: 84, background: '#ffffff', anim: false }); } export async function upscalePrintImage(input: Buffer, source: Dimensions, longEdge: number) { const worker = workerImages(); if (!worker) { const size = source.width >= source.height ? { width: longEdge } : { height: longEdge }; return (await nodeImage(input)).resize({ ...size, kernel: 'lanczos3' }).png().toBuffer({ resolveWithObject: true }); } const scale = longEdge / Math.max(source.width, source.height); const width = Math.max(1, Math.round(source.width * scale)); const height = Math.max(1, Math.round(source.height * scale)); const resized = worker.binding.input(stream(input)).transform({ width, height, fit: 'squeeze' }); const data = await output(resized, { format: 'image/png', anim: false }); const info = await worker.binding.info(stream(data)); if (!('width' in info) || info.width !== width || info.height !== height) { throw new Error('Could not retain the requested print resolution.'); } return { data, info }; } function centeredFraming(width: number, height: number) { const innerWidth = Math.round(width * 0.86); const innerHeight = Math.round(height * 0.86); return { innerWidth, innerHeight, left: Math.floor((width - innerWidth) / 2), top: Math.floor((height - innerHeight) / 2), }; } export async function encodeMirroredFraming(input: Buffer): Promise { const worker = workerImages(); if (!worker) { const image = (await nodeImage(input)).rotate(); const { width, height } = (await image.metadata()).autoOrient; const { innerWidth, innerHeight, left, top } = centeredFraming(width, height); return image.resize(innerWidth, innerHeight, { fit: 'fill' }).extend({ top, bottom: height - innerHeight - top, left, right: width - innerWidth - left, extendWith: 'mirror', }).jpeg({ quality: 94, mozjpeg: true }).toBuffer(); } const jpeg = { format: 'image/jpeg', quality: 94, anim: false } as const; const oriented = await output(worker.binding.input(stream(input)), { ...jpeg, quality: 100 }); const info = await worker.binding.info(stream(oriented)); if (!('width' in info)) throw new Error('Could not read image dimensions for wider framing.'); const { width, height } = info; const { innerWidth, innerHeight, left, top } = centeredFraming(width, height); const resized = worker.binding.input(stream(oriented)).transform({ width: innerWidth, height: innerHeight, fit: 'squeeze' }); const centered = await output(resized, { ...jpeg, quality: 100 }); const url = 'data:image/jpeg;base64,' + centered.toString('base64'); const columns = [[left, -1], [left, 1], [left + 2 * innerWidth, -1]]; const rows = [[top, -1], [top, 1], [top + 2 * innerHeight, -1]]; // The SVG viewport clips the reflected tiles to the original canvas. const tiles = rows.flatMap(([y, sy]) => columns.map(([x, sx]) => '', )).join(''); const svg = '' + tiles + ''; return output(worker.binding.input(stream(await worker.rasterizeSvg(svg))), jpeg); }