{"version":3,"file":"enrich-BX0IDp4z.mjs","names":[],"sources":["../src/media/placeholder.ts","../src/media/enrich.ts"],"sourcesContent":["/**\n * Image Placeholder Generation\n *\n * Generates blurhash and dominant color from image buffers for LQIP support.\n * Decodes images via jpeg-js (pure JS) and upng-js (pure JS, uses pako for\n * deflate). No Node-specific dependencies — works in Workers and Node SSR.\n */\n\nimport { encode } from \"blurhash\";\nimport { imageSize } from \"image-size\";\n\nimport { normalizeMime } from \"./mime.js\";\n\nexport interface PlaceholderData {\n\tblurhash: string;\n\tdominantColor: string;\n}\n\nconst SUPPORTED_TYPES: Record<string, \"jpeg\" | \"png\"> = {\n\t\"image/jpeg\": \"jpeg\",\n\t\"image/jpg\": \"jpeg\",\n\t\"image/png\": \"png\",\n};\n\n/** Max width for blurhash input. Encode is O(w*h*components), so downsample first. */\nconst MAX_ENCODE_WIDTH = 32;\n\n/** Max decoded RGBA size (32 MB). Images exceeding this skip placeholder generation. */\nconst MAX_DECODED_BYTES = 32 * 1024 * 1024;\n\ninterface DecodedImage {\n\twidth: number;\n\theight: number;\n\tdata: Uint8Array;\n}\n\n/**\n * Decode a JPEG buffer into raw RGBA pixel data.\n */\nasync function decodeJpeg(buffer: Uint8Array): Promise<DecodedImage> {\n\tconst { decode } = await import(\"jpeg-js\");\n\tconst result = decode(buffer, { useTArray: true });\n\treturn { width: result.width, height: result.height, data: result.data };\n}\n\n/**\n * Decode a PNG buffer into raw RGBA pixel data.\n * Uses upng-js (pure JS with pako deflate) — no Node zlib dependency.\n */\nasync function decodePng(buffer: Uint8Array): Promise<DecodedImage> {\n\t// @ts-expect-error -- upng-js has no type declarations\n\tconst UPNG = (await import(\"upng-js\")).default;\n\tconst img = UPNG.decode(buffer.buffer);\n\t// toRGBA8 returns an array of frames; take the first frame\n\tconst frames: ArrayBuffer[] = UPNG.toRGBA8(img);\n\tconst rgba = new Uint8Array(frames[0]);\n\treturn { width: img.width, height: img.height, data: rgba };\n}\n\n/**\n * Extract the dominant color from RGBA pixel data.\n * Simple average of all non-transparent pixels.\n */\nfunction extractDominantColor(data: Uint8Array, width: number, height: number): string {\n\tlet r = 0;\n\tlet g = 0;\n\tlet b = 0;\n\tlet count = 0;\n\n\tconst len = width * height * 4;\n\tfor (let i = 0; i < len; i += 4) {\n\t\tconst a = data[i + 3];\n\t\tif (a < 128) continue; // skip mostly-transparent pixels\n\t\tr += data[i];\n\t\tg += data[i + 1];\n\t\tb += data[i + 2];\n\t\tcount++;\n\t}\n\n\tif (count === 0) return \"rgb(0,0,0)\";\n\n\tconst avgR = Math.round(r / count);\n\tconst avgG = Math.round(g / count);\n\tconst avgB = Math.round(b / count);\n\treturn `rgb(${avgR},${avgG},${avgB})`;\n}\n\n/**\n * Read image dimensions from headers without decoding pixel data.\n * Returns null when the header cannot be parsed.\n *\n * Shared by every caller that needs pixel dimensions so the header is parsed\n * once per buffer, not re-read inside generatePlaceholder.\n */\nexport function readDimensions(buffer: Uint8Array): { width: number; height: number } | null {\n\ttry {\n\t\tconst result = imageSize(buffer);\n\t\tif (result.width != null && result.height != null) {\n\t\t\treturn { width: result.width, height: result.height };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Generate blurhash and dominant color from an image buffer.\n * Returns null for non-image MIME types or on failure.\n *\n * @param dimensions - Optional pre-known dimensions. When present they are\n *   trusted verbatim (the caller has typically already read them via\n *   readDimensions); otherwise dimensions are read from this buffer's header.\n *   Generation is skipped (returns null) when no dimensions are available at\n *   all, or when the decoded size (width * height * 4) exceeds\n *   MAX_DECODED_BYTES — both guards avoid OOM from unbounded decodes on\n *   memory-constrained runtimes.\n */\nexport async function generatePlaceholder(\n\tbuffer: Uint8Array,\n\tmimeType: string,\n\tdimensions?: { width: number; height: number },\n): Promise<PlaceholderData | null> {\n\tconst format = SUPPORTED_TYPES[normalizeMime(mimeType)];\n\tif (!format) return null;\n\n\ttry {\n\t\t// Trust caller-supplied dimensions when present (the caller has usually\n\t\t// already read them via readDimensions); otherwise read them from this\n\t\t// buffer. The header is parsed at most once per call.\n\t\tconst dims = dimensions ?? readDimensions(buffer);\n\n\t\t// Safety net: the decoders allocate the full RGBA buffer with no internal\n\t\t// cap, so refuse to decode unless we can bound the output size. When we\n\t\t// have no parseable header AND no known dimensions, the decoded size is\n\t\t// unbounded — a crafted/truncated PNG whose header image-size can't read\n\t\t// could still be decodable by upng-js, so we must bail to avoid OOM on\n\t\t// memory-constrained runtimes. LQIP is progressive enhancement; missing\n\t\t// it is preferable to crashing the request.\n\t\tif (!dims) return null;\n\t\tif (dims.width * dims.height * 4 > MAX_DECODED_BYTES) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst imageData = format === \"jpeg\" ? await decodeJpeg(buffer) : await decodePng(buffer);\n\t\tconst { width, height, data } = imageData;\n\n\t\tif (width === 0 || height === 0) return null;\n\n\t\t// Downsample for blurhash encoding if needed\n\t\tlet encodePixels: Uint8ClampedArray;\n\t\tlet encodeWidth: number;\n\t\tlet encodeHeight: number;\n\n\t\tif (width > MAX_ENCODE_WIDTH) {\n\t\t\tconst scale = MAX_ENCODE_WIDTH / width;\n\t\t\tencodeWidth = MAX_ENCODE_WIDTH;\n\t\t\tencodeHeight = Math.max(1, Math.round(height * scale));\n\t\t\tencodePixels = downsample(data, width, height, encodeWidth, encodeHeight);\n\t\t} else {\n\t\t\tencodeWidth = width;\n\t\t\tencodeHeight = height;\n\t\t\tencodePixels = new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength);\n\t\t}\n\n\t\tconst blurhash = encode(encodePixels, encodeWidth, encodeHeight, 4, 3);\n\t\tconst dominantColor = extractDominantColor(data, width, height);\n\n\t\treturn { blurhash, dominantColor };\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Nearest-neighbor downsample of RGBA pixel data.\n */\nfunction downsample(\n\tsrc: Uint8Array,\n\tsrcW: number,\n\tsrcH: number,\n\tdstW: number,\n\tdstH: number,\n): Uint8ClampedArray {\n\tconst dst = new Uint8ClampedArray(dstW * dstH * 4);\n\n\tfor (let y = 0; y < dstH; y++) {\n\t\tconst srcY = Math.floor((y * srcH) / dstH);\n\t\tfor (let x = 0; x < dstW; x++) {\n\t\t\tconst srcX = Math.floor((x * srcW) / dstW);\n\t\t\tconst srcIdx = (srcY * srcW + srcX) * 4;\n\t\t\tconst dstIdx = (y * dstW + x) * 4;\n\t\t\tdst[dstIdx] = src[srcIdx]!;\n\t\t\tdst[dstIdx + 1] = src[srcIdx + 1]!;\n\t\t\tdst[dstIdx + 2] = src[srcIdx + 2]!;\n\t\t\tdst[dstIdx + 3] = src[srcIdx + 3]!;\n\t\t}\n\t}\n\n\treturn dst;\n}\n","/**\n * Image Metadata Enrichment\n *\n * Single seam that derives image dimensions and LQIP placeholders (blurhash,\n * dominant color) from raw image bytes. Every server-side media-creation path\n * routes through this so records are populated consistently. Pure-JS and\n * Workers-safe (image-size reads headers only; generatePlaceholder guards\n * decode size).\n */\n\nimport { normalizeMime } from \"./mime.js\";\nimport { generatePlaceholder, readDimensions } from \"./placeholder.js\";\n\nexport interface EnrichedImageMetadata {\n\twidth?: number;\n\theight?: number;\n\tblurhash?: string;\n\tdominantColor?: string;\n}\n\n/**\n * Derive dimensions + LQIP placeholders from image bytes.\n *\n * - Non-image content types return `{}`.\n * - `knownDimensions` (e.g. browser `naturalWidth/Height`) win over `image-size`\n *   for the *stored record* because the browser applies EXIF orientation;\n *   `image-size` reports raw header dimensions, which are swapped for\n *   90°/270°-rotated JPEGs. They are NOT used for the decode OOM guard — see below.\n * - The placeholder OOM guard uses only header dimensions read from the bytes\n *   actually decoded. Caller-supplied `knownDimensions` are untrusted for the\n *   guard: a client could claim a tiny size for a huge image to bypass the cap.\n * - `placeholder` lets a caller decode a smaller thumbnail for the blurhash to\n *   avoid OOM on large originals; dimensions still come from `bytes`.\n * - Placeholders are jpeg/png only (the generator's supported formats); other\n *   image types still get dimensions.\n */\nexport async function enrichImageMetadata(\n\tbytes: Uint8Array,\n\tcontentType: string,\n\topts?: {\n\t\tknownDimensions?: { width: number; height: number };\n\t\tplaceholder?: { bytes: Uint8Array; contentType: string };\n\t},\n): Promise<EnrichedImageMetadata> {\n\tconst normalizedContentType = normalizeMime(contentType);\n\tif (!normalizedContentType.startsWith(\"image/\")) return {};\n\n\t// Header dimensions are read once from the actual bytes. They feed the\n\t// placeholder OOM guard, which must never trust caller-supplied dimensions:\n\t// `knownDimensions` is decoupled from the buffer, so a client could claim a\n\t// tiny size for a huge image and slip past the decoded-size cap, making the\n\t// decoder allocate an unbounded RGBA buffer and OOM the runtime. Only dims\n\t// read from the buffer that actually gets decoded can bound the decode.\n\tconst headerDims = readDimensions(bytes) ?? undefined;\n\n\t// Dimensions published on the record prefer the caller's knownDimensions\n\t// (e.g. browser naturalWidth/Height, which apply EXIF orientation) over the\n\t// raw header dims, which are swapped for 90°/270°-rotated JPEGs.\n\tconst recordDims = opts?.knownDimensions ?? headerDims;\n\n\t// When a smaller thumbnail override is supplied, decode that for the blurhash\n\t// and let generatePlaceholder read the thumbnail's own header for the OOM\n\t// guard (the override buffer is what actually gets decoded). On the common\n\t// no-override path pass the header dims already read from this same buffer.\n\tconst override = opts?.placeholder;\n\tconst placeholder = await generatePlaceholder(\n\t\toverride ? override.bytes : bytes,\n\t\toverride ? normalizeMime(override.contentType) : normalizedContentType,\n\t\toverride ? undefined : headerDims,\n\t);\n\n\treturn {\n\t\twidth: recordDims?.width,\n\t\theight: recordDims?.height,\n\t\tblurhash: placeholder?.blurhash,\n\t\tdominantColor: placeholder?.dominantColor,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,kBAAkD;CACvD,cAAc;CACd,aAAa;CACb,aAAa;CACb;;AAGD,MAAM,mBAAmB;;AAGzB,MAAM,oBAAoB,KAAK,OAAO;;;;AAWtC,eAAe,WAAW,QAA2C;CACpE,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,OAAO,QAAQ,EAAE,WAAW,MAAM,CAAC;AAClD,QAAO;EAAE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