import { readFile } from 'node:fs/promises'; import { APIError } from 'payload'; const OPTIMIZABLE = new Set([ 'image/jpeg', 'image/png' ]); const MB = 1024 * 1024; const fmt = (bytes)=>`${(bytes / MB).toFixed(1)} MB`; /** * Consent checkbox for the upload collection's sidebar. Unticked by default; * only read when a file exceeds the limits. */ export function buildOptimizeUploadField(name = 'optimizeOnUpload') { return { name, type: 'checkbox', admin: { description: 'Only used when an image is too large: converts it to WebP, resizes it and removes metadata (EXIF/GPS). Prepared files are never changed.', position: 'sidebar' }, defaultValue: false, label: 'Optimize this upload' }; } /** * beforeOperation hook for an upload collection (e.g. Media): * * hooks: { beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook()] }, * fields: [..., buildOptimizeUploadField()], */ export function buildOptimizeUploadHook(options = {}) { const { consentField = 'optimizeOnUpload', maxImageBytes = 1.5 * MB, maxImageWidth = 2560, maxVideoBytes = 20 * MB, png = 'lossless', quality = 82 } = options; return async ({ args, operation, req })=>{ if (operation !== 'create' && operation !== 'update') { return; } const file = req.file; if (!file) { return; } const data = args.data; const consent = Boolean(data?.[consentField]); const size = file.size || file.data?.length || 0; // --- Video: limit only, never transcoded --- if (file.mimetype.startsWith('video/')) { if (maxVideoBytes !== false && size > maxVideoBytes) { throw new APIError(`Video is ${fmt(size)} (limit ${fmt(maxVideoBytes)}). Export it before uploading: ` + 'MP4 (H.264), 720p–1080p, about 2–4 Mbit/s, no audio track for background videos, ' + '"web optimized" / fast start enabled (e.g. HandBrake preset "Web").', 400, undefined, true); } return; } if (!OPTIMIZABLE.has(file.mimetype)) { return; } // GIF, SVG, WebP, AVIF, PDF… untouched const sharp = req.payload.config.sharp; const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined; if (!buffer) { return; } let width; let animated = false; if (sharp) { const meta = await sharp(buffer).metadata(); width = meta.width; animated = (meta.pages ?? 1) > 1; } if (animated) { return; } // APNG — converting would drop the animation const tooHeavy = size > maxImageBytes; const tooWide = width !== undefined && width > maxImageWidth; if (!tooHeavy && !tooWide) { return; } const problem = [ tooHeavy ? `${fmt(size)} (limit ${fmt(maxImageBytes)})` : null, tooWide ? `${width} px wide (limit ${maxImageWidth} px)` : null ].filter(Boolean).join(', '); if (!consent) { throw new APIError(`Image is ${problem}. Tick "Optimize this upload" in the sidebar and save again to convert it ` + `to WebP (max ${maxImageWidth} px wide, metadata removed), or upload a smaller file.`, 400, undefined, true); } if (!sharp) { throw new APIError('Image optimization needs sharp: pass it to buildConfig({ sharp }) in payload.config.ts.', 500, undefined, true); } const lossless = file.mimetype === 'image/png' && png === 'lossless'; const output = await sharp(buffer).rotate() // apply EXIF orientation before metadata is dropped .resize({ width: maxImageWidth, withoutEnlargement: true }).webp(lossless ? { lossless: true } : { quality }).toBuffer(); // Conversion didn't help (rare) and the width was fine → keep the original. if (output.length >= size && !tooWide) { return; } file.data = output; file.size = output.length; file.mimetype = 'image/webp'; file.name = `${file.name.replace(/\.[^.]+$/, '')}.webp`; delete file.tempFilePath; // Payload must read the new buffer, not the temp file if (data) { data[consentField] = false; } // next oversized upload asks again }; } //# sourceMappingURL=optimizeUpload.js.map