// Варианты изображения (libvips через sharp). Параметры зависят от версии pipeline; результат версии N // всегда один и тот же набор: thumbnail, crop, optimized. // thumbnail — JPEG, вписан в 256×256 без увеличения, EXIF orientation применяется, alpha на белом, // размеры округляются вниз (не меньше 1 px): 320×200 → 256×160; // crop — JPEG, центрированный квадрат 128×128 (маленький исходник увеличивается); // optimized — WebP, вписан в 1280×1280 без увеличения; метаданные (EXIF/XMP/ICC) не копируются — sharp // по умолчанию их отбрасывает, цвета приводятся к sRGB. // Ограничения: пиксели проверяются по заголовку до декодирования (limitInputPixels), время — timeout libvips, // память — один поток libvips на процесс, без кэша операций, и лимит памяти контейнера worker. import { createHash } from 'node:crypto'; import sharp, { type Sharp } from 'sharp'; sharp.cache(false); sharp.concurrency(1); export class PermanentError extends Error { code: string; constructor(code: string, message: string) { super(message); this.code = code; } } // Версия 2 (трек 5): другое качество и лёгкая резкость — заметно иной результат той же логической работы. const PIPELINES: Record = { 1: { jpeg: 82, webp: 80, sharpen: false }, 2: { jpeg: 90, webp: 85, sharpen: true }, }; export const SUPPORTED_VERSIONS = Object.keys(PIPELINES).map(Number); export type Rendered = { name: 'thumbnail' | 'crop' | 'optimized'; content_type: 'image/jpeg' | 'image/webp'; ext: string; data: Buffer; width: number; height: number; size_bytes: number; sha256: string; }; export async function render(source: Buffer, version: number, maxPixels: number, timeoutSeconds: number): Promise { const p = PIPELINES[version]; if (!p) throw new PermanentError('unsupported_pipeline', `pipeline v${version} не поддерживается`); const input = () => sharp(source, { limitInputPixels: maxPixels, sequentialRead: true }).timeout({ seconds: timeoutSeconds }); try { const meta = await input().metadata(); if (!meta.width || !meta.height || !['png', 'jpeg'].includes(meta.format ?? '')) throw new PermanentError('invalid_image', 'не PNG/JPEG'); const turned = (meta.orientation ?? 1) >= 5; // EXIF 5–8: после поворота ширина и высота меняются местами const width = turned ? meta.height : meta.width; const height = turned ? meta.width : meta.height; const inside = (box: number) => { const k = Math.min(box / width, box / height, 1); return [Math.max(1, Math.floor(width * k)), Math.max(1, Math.floor(height * k))]; }; const [tw, th] = inside(256); const [ow, oh] = inside(1280); const oriented = () => { const img = input().autoOrient(); return p.sharpen ? img.sharpen() : img; }; return [ await output('thumbnail', oriented().flatten({ background: '#ffffff' }).resize(tw, th, { fit: 'fill' }).jpeg({ quality: p.jpeg, mozjpeg: true })), await output('crop', oriented().flatten({ background: '#ffffff' }).resize(128, 128, { fit: 'cover', position: 'centre' }).jpeg({ quality: p.jpeg, mozjpeg: true })), await output('optimized', oriented().resize(ow, oh, { fit: 'fill' }).webp({ quality: p.webp, effort: 4 })), ]; } catch (err) { if (err instanceof PermanentError) throw err; const message = (err as Error).message ?? ''; // Ошибки libvips — свойство входного файла: повтор не поможет. throw /timeout/i.test(message) ? new PermanentError('processing_timeout', 'обработка дольше лимита') : new PermanentError('invalid_image', message.split('\n')[0].slice(0, 200)); } } async function output(name: Rendered['name'], img: Sharp): Promise { const { data, info } = await img.toBuffer({ resolveWithObject: true }); const webp = info.format === 'webp'; return { name, content_type: webp ? 'image/webp' : 'image/jpeg', ext: webp ? 'webp' : 'jpg', data, width: info.width, height: info.height, size_bytes: data.length, sha256: createHash('sha256').update(data).digest('hex'), }; }