ReviewOS

also looking at this

stacks/rpx

feat: imgx integration — on-the-fly image transforms from query params

#2264
Merged glennmichael123 wants to merge feat/imgx-integration into main
15 files +1118 -16
packages/rpx/src/imgx.tsadded+669-0
Changes to packages/rpx/src/imgx.ts
@@ -0,0 +1,669 @@
1/**
2 * imgx integration: on-the-fly image transformation driven by query params.
3 *
4 * When a route enables `imgx`, the proxy inspects image responses whose request
5 * carries imgix/meema-style params (`?w=200&h=1200&q=80&format=webp`, see
6 * {@link parseImgxParams}) and re-encodes the upstream bytes through the
7 * pure-TypeScript `ts-images` pipeline (decode → resize/ops → encode) before
8 * answering. The upstream itself never sees anything but the original request,
9 * so any dev server, static dir, or app gains image resizing for free.
10 *
11 * Design constraints:
12 * - Never break serving: any parse/decode/encode failure falls back to the
13 * original upstream bytes (the response was already buffered by then).
14 * - Never buffer unbounded: responses larger than `maxInputBytes` pass through
15 * untouched, still streaming.
16 * - Never re-encode twice: transformed variants are cached in-memory, keyed by
17 * path + normalized params + a hash of the upstream bytes — an unchanged
18 * upstream is a cache hit, a changed one misses naturally, with no TTLs.
19 * - `ts-images` is imported lazily on the first transform so enabling the
20 * integration costs nothing at startup and rpx works without the package
21 * installed (transforms just pass through, with a one-time warning).
22 */
23import type { ImgxOptions } from './types'
24import { debugLog } from './utils'
25
26/** Query params that trigger a transform (as opposed to only modifying one). */
27const TRIGGER_PARAMS = /[?&](?:w|h|width|height|q|fm|format|auto|blur|sharp|greyscale|grayscale|bri|sat|hue|tint|rot|flip|flop|lossless)=/
28
29/** Response content types the ts-images codecs can decode. */
30const DECODABLE_TYPES = new Set([
31 'image/jpeg',
32 'image/jpg',
33 'image/png',
34 'image/gif',
35 'image/bmp',
36 'image/webp',
37 'image/avif',
38])
39
40/** Path extensions accepted when the upstream sends no content-type. */
41const DECODABLE_EXTENSIONS: Record<string, string> = {
42 '.jpg': 'image/jpeg',
43 '.jpeg': 'image/jpeg',
44 '.png': 'image/png',
45 '.gif': 'image/gif',
46 '.bmp': 'image/bmp',
47 '.webp': 'image/webp',
48 '.avif': 'image/avif',
49}
50
51type OutputFormat = 'jpeg' | 'png' | 'webp' | 'avif' | 'gif' | 'bmp'
52
53const OUTPUT_FORMATS = new Set<string>(['jpeg', 'png', 'webp', 'avif', 'gif', 'bmp'])
54
55/** imgix `fit` values rpx implements (`clamp`→clip and `fillmax`→fill degrade). */
56type FitMode = 'clip' | 'max' | 'min' | 'crop' | 'scale' | 'fill'
57
58type CropPosition = 'center' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
59
60interface Rgba { r: number, g: number, b: number, a?: number }
61
62/** A request's parsed transform, normalized and clamped. */
63export interface ImgxTransform {
64 width?: number
65 height?: number
66 fit: FitMode
67 position: CropPosition
68 aspectRatio?: number
69 dpr: number
70 quality?: number
71 format?: OutputFormat
72 autoFormat: boolean
73 lossless?: boolean
74 blur?: number
75 sharpen: boolean
76 grayscale: boolean
77 brightness?: number
78 saturation?: number
79 hue?: number
80 tint?: Rgba
81 rotate?: number
82 flip: boolean
83 flop: boolean
84 background?: Rgba
85}
86
87export interface ResolvedImgxOptions {
88 /** Encode quality used when the request has no `q`. */
89 quality: number
90 /** Upper clamp for requested output width. */
91 maxWidth: number
92 /** Upper clamp for requested output height. */
93 maxHeight: number
94 /** Responses larger than this pass through untransformed (still streaming). */
95 maxInputBytes: number
96 /** In-memory cache of transformed variants for this route, or null when disabled. */
97 cache: ImgxCache | null
98}
99
100/**
101 * Bounded LRU for transformed variants. Keys embed a hash of the source bytes,
102 * so entries never go stale — a changed upstream simply misses.
103 */
104export class ImgxCache {
105 private entries = new Map<string, { bytes: Uint8Array, contentType: string }>()
106 private totalBytes = 0
107
108 constructor(private maxBytes: number, private maxEntries: number) {}
109
110 get(key: string): { bytes: Uint8Array, contentType: string } | undefined {
111 const hit = this.entries.get(key)
112 if (hit) {
113 // Refresh recency: Map iteration order is insertion order.
114 this.entries.delete(key)
115 this.entries.set(key, hit)
116 }
117 return hit
118 }
119
120 set(key: string, value: { bytes: Uint8Array, contentType: string }): void {
121 if (value.bytes.byteLength > this.maxBytes)
122 return
123 const existing = this.entries.get(key)
124 if (existing) {
125 this.entries.delete(key)
126 this.totalBytes -= existing.bytes.byteLength
127 }
128 this.entries.set(key, value)
129 this.totalBytes += value.bytes.byteLength
130 while (this.entries.size > this.maxEntries || this.totalBytes > this.maxBytes) {
131 const oldest = this.entries.keys().next().value
132 if (oldest === undefined)
133 break
134 this.totalBytes -= this.entries.get(oldest)!.bytes.byteLength
135 this.entries.delete(oldest)
136 }
137 }
138
139 get size(): number {
140 return this.entries.size
141 }
142}
143
144/**
145 * Resolve a route's `imgx` config value into runtime options. `false`/absent
146 * disables the integration for the route.
147 */
148export function resolveImgx(value: boolean | ImgxOptions | undefined): ResolvedImgxOptions | undefined {
149 if (!value)
150 return undefined
151 const opts = value === true ? {} : value
152 const cacheEnabled = opts.cache !== false
153 return {
154 quality: clampInt(opts.quality, 1, 100) ?? 80,
155 maxWidth: clampInt(opts.maxWidth, 2, 16384) ?? 8192,
156 maxHeight: clampInt(opts.maxHeight, 2, 16384) ?? 8192,
157 maxInputBytes: opts.maxInputBytes && opts.maxInputBytes > 0 ? opts.maxInputBytes : 32 * 1024 * 1024,
158 cache: cacheEnabled
159 ? new ImgxCache(
160 opts.cacheMaxBytes && opts.cacheMaxBytes > 0 ? opts.cacheMaxBytes : 64 * 1024 * 1024,
161 opts.cacheMaxEntries && opts.cacheMaxEntries > 0 ? opts.cacheMaxEntries : 500,
162 )
163 : null,
164 }
165}
166
167/** Cheap pre-check so requests without transform params never pay for parsing. */
168export function hasImgxParams(search: string): boolean {
169 return search.length > 1 && TRIGGER_PARAMS.test(search)
170}
171
172function clampInt(value: number | undefined, min: number, max: number): number | undefined {
173 if (value === undefined || !Number.isFinite(value))
174 return undefined
175 return Math.min(max, Math.max(min, Math.round(value)))
176}
177
178function parseNumber(value: string | null): number | undefined {
179 if (value === null || value === '')
180 return undefined
181 const n = Number(value)
182 return Number.isFinite(n) ? n : undefined
183}
184
185/** `''`, `1`, `true`, `yes` → true (bare `?flip` arrives as an empty string). */
186function parseBool(value: string | null): boolean {
187 if (value === null)
188 return false
189 return value === '' || value === '1' || value === 'true' || value === 'yes'
190}
191
192/**
193 * Dimension params accept absolute pixels or, imgix-style, a 0–1 fraction of
194 * the source dimension (resolved against the decoded image later).
195 */
196function parseDimension(value: string | null): number | undefined {
197 const n = parseNumber(value)
198 if (n === undefined || n <= 0)
199 return undefined
200 return n
201}
202
203/** `#rgb`, `#rrggbb`, `#rrggbbaa` (leading `#` optional) or a few CSS keywords. */
204function parseColor(value: string | null): Rgba | undefined {
205 if (!value)
206 return undefined
207 const keywords: Record<string, Rgba> = {
208 white: { r: 255, g: 255, b: 255 },
209 black: { r: 0, g: 0, b: 0 },
210 transparent: { r: 0, g: 0, b: 0, a: 0 },
211 }
212 const keyword = keywords[value.toLowerCase()]
213 if (keyword)
214 return keyword
215 const hex = value.startsWith('#') ? value.slice(1) : value
216 if (!/^[0-9a-f]+$/i.test(hex))
217 return undefined
218 if (hex.length === 3 || hex.length === 4) {
219 const [r, g, b, a] = hex.split('').map(c => Number.parseInt(c + c, 16))
220 return { r, g, b, ...(a === undefined ? {} : { a }) }
221 }
222 if (hex.length === 6 || hex.length === 8) {
223 const r = Number.parseInt(hex.slice(0, 2), 16)
224 const g = Number.parseInt(hex.slice(2, 4), 16)
225 const b = Number.parseInt(hex.slice(4, 6), 16)
226 const a = hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) : undefined
227 return { r, g, b, ...(a === undefined ? {} : { a }) }
228 }
229 return undefined
230}
231
232/** `crop=top,left` → ts-images' `top-left` anchor (unsupported modes → center). */
233function parseCropPosition(value: string | null): CropPosition {
234 if (!value)
235 return 'center'
236 const parts = new Set(value.split(',').map(p => p.trim().toLowerCase()))
237 const vertical = parts.has('top') ? 'top' : parts.has('bottom') ? 'bottom' : ''
238 const horizontal = parts.has('left') ? 'left' : parts.has('right') ? 'right' : ''
239 if (vertical && horizontal)
240 return `${vertical}-${horizontal}` as CropPosition
241 if (vertical)
242 return vertical as CropPosition
243 if (horizontal)
244 return horizontal as CropPosition
245 return 'center'
246}
247
248/**
249 * Parse the meema/imgix-compatible transform params out of a query string
250 * (`search` includes the leading `?`). Returns `undefined` when no param that
251 * triggers a transform is present — modifier-only queries (`?fit=crop`) and
252 * unrelated queries cost nothing downstream.
253 *
254 * Supported params: `w`/`h` (px, or a 0–1 fraction of the source), `fit`
255 * (`clip|max|min|crop|scale|fill`), `crop` (position keywords), `ar` (`16:9`),
256 * `dpr`, `q`, `fm`/`format` (+`auto`), `auto=format|compress`, `lossless`,
257 * `blur` (imgix 0–2000 scale), `sharp`, `greyscale`/`grayscale`, `bri`/`sat`
258 * (−100..100), `hue` (degrees), `tint`, `rot`, `flip`, `flop`, `bg`.
259 */
260export function parseImgxParams(search: string): ImgxTransform | undefined {
261 if (!hasImgxParams(search))
262 return undefined
263 const params = new URLSearchParams(search.slice(1))
264
265 const auto = new Set((params.get('auto') ?? '').split(',').map(v => v.trim().toLowerCase()).filter(Boolean))
266
267 let format: OutputFormat | undefined
268 let autoFormat = auto.has('format')
269 const rawFormat = (params.get('fm') ?? params.get('format'))?.toLowerCase()
270 if (rawFormat === 'auto')
271 autoFormat = true
272 else if (rawFormat === 'jpg')
273 format = 'jpeg'
274 else if (rawFormat && OUTPUT_FORMATS.has(rawFormat))
275 format = rawFormat as OutputFormat
276
277 let fit = (params.get('fit') ?? params.get('f') ?? 'clip').toLowerCase()
278 // imgix modes without a ts-images equivalent degrade to their closest match.
279 if (fit === 'clamp')
280 fit = 'clip'
281 if (fit === 'fillmax')
282 fit = 'fill'
283 if (!['clip', 'max', 'min', 'crop', 'scale', 'fill'].includes(fit))
284 fit = 'clip'
285
286 let aspectRatio: number | undefined
287 const ar = params.get('ar')
288 if (ar) {
289 const match = ar.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/)
290 if (match) {
291 const [, arw, arh] = match
292 const ratio = Number(arw) / Number(arh)
293 if (Number.isFinite(ratio) && ratio > 0)
294 aspectRatio = ratio
295 }
296 }
297
298 const quality = clampInt(parseNumber(params.get('q')), 1, 100)
299 const compressQuality = auto.has('compress') && quality === undefined ? 75 : undefined
300
301 const rawBlur = parseNumber(params.get('blur'))
302
303 const transform: ImgxTransform = {
304 width: parseDimension(params.get('w') ?? params.get('width')),
305 height: parseDimension(params.get('h') ?? params.get('height')),
306 fit: fit as FitMode,
307 position: parseCropPosition(params.get('crop')),
308 aspectRatio,
309 dpr: Math.min(5, Math.max(0.1, parseNumber(params.get('dpr')) ?? 1)),
310 quality: quality ?? compressQuality,
311 format,
312 autoFormat,
313 lossless: params.has('lossless') ? parseBool(params.get('lossless')) : undefined,
314 // imgix blur is 0–2000; ts-images takes a gaussian sigma. Same remap meema uses.
315 blur: rawBlur && rawBlur > 0 ? Math.min(2000, rawBlur) * 0.22 : undefined,
316 sharpen: parseBool(params.get('sharp')),
317 grayscale: parseBool(params.get('greyscale')) || parseBool(params.get('grayscale')),
318 // imgix bri/sat are −100..100 offsets; ts-images modulate takes multipliers.
319 brightness: mapOffsetToMultiplier(parseNumber(params.get('bri'))),
320 saturation: mapOffsetToMultiplier(parseNumber(params.get('sat'))),
321 hue: parseNumber(params.get('hue')),
322 tint: parseColor(params.get('tint')),
323 rotate: parseNumber(params.get('rot')),
324 flip: parseBool(params.get('flip')),
325 flop: parseBool(params.get('flop')),
326 background: parseColor(params.get('bg')),
327 }
328
329 const triggers = transform.width !== undefined
330 || transform.height !== undefined
331 || transform.quality !== undefined
332 || transform.format !== undefined
333 || transform.autoFormat
334 || transform.lossless !== undefined
335 || transform.blur !== undefined
336 || transform.sharpen
337 || transform.grayscale
338 || transform.brightness !== undefined
339 || transform.saturation !== undefined
340 || transform.hue !== undefined
341 || transform.tint !== undefined
342 || transform.rotate !== undefined
343 || transform.flip
344 || transform.flop
345 return triggers ? transform : undefined
346}
347
348function mapOffsetToMultiplier(offset: number | undefined): number | undefined {
349 if (offset === undefined)
350 return undefined
351 return Math.max(0, 1 + Math.min(100, Math.max(-100, offset)) / 100)
352}
353
354/**
355 * Lazy `ts-images` loader. The import is deferred to the first transform and
356 * failures are remembered — a missing package means transforms pass through
357 * with a single warning instead of a per-request error.
358 */
359type TsImages = typeof import('ts-images')
360let tsImagesPromise: Promise<TsImages | null> | undefined
361
362function loadTsImages(verbose?: boolean): Promise<TsImages | null> {
363 tsImagesPromise ??= import('ts-images').catch((err) => {
364 console.warn(`[rpx] imgx integration disabled: failed to load ts-images (${err instanceof Error ? err.message : err})`)
365 debugLog('imgx', `ts-images import failed: ${err}`, verbose)
366 return null
367 })
368 return tsImagesPromise
369}
370
371/** Test hook: reset the memoized ts-images import. */
372export function resetImgxRuntime(): void {
373 tsImagesPromise = undefined
374}
375
376function contentTypeOf(res: Response): string | undefined {
377 const raw = res.headers.get('content-type')
378 if (!raw)
379 return undefined
380 const semi = raw.indexOf(';')
381 return (semi === -1 ? raw : raw.slice(0, semi)).trim().toLowerCase()
382}
383
384function extensionType(pathname: string): string | undefined {
385 const dot = pathname.lastIndexOf('.')
386 if (dot === -1)
387 return undefined
388 return DECODABLE_EXTENSIONS[pathname.slice(dot).toLowerCase()]
389}
390
391/**
392 * Read a body into memory up to `cap` bytes. When the cap is exceeded the
393 * already-read chunks are stitched back in front of the remaining stream so the
394 * caller can return an untouched passthrough response.
395 */
396async function bufferBody(res: Response, cap: number): Promise<{ bytes: Uint8Array } | { overflow: ReadableStream<Uint8Array> | null }> {
397 if (!res.body)
398 return { overflow: null }
399 const reader = res.body.getReader()
400 const chunks: Uint8Array[] = []
401 let total = 0
402 while (true) {
403 const { done, value } = await reader.read()
404 if (done)
405 break
406 chunks.push(value)
407 total += value.byteLength
408 if (total > cap) {
409 const replay = new ReadableStream<Uint8Array>({
410 async start(controller) {
411 for (const chunk of chunks)
412 controller.enqueue(chunk)
413 },
414 async pull(controller) {
415 const { done: d, value: v } = await reader.read()
416 if (d)
417 controller.close()
418 else
419 controller.enqueue(v)
420 },
421 cancel(reason) {
422 return reader.cancel(reason)
423 },
424 })
425 return { overflow: replay }
426 }
427 }
428 const out = new Uint8Array(total)
429 let offset = 0
430 for (const chunk of chunks) {
431 out.set(chunk, offset)
432 offset += chunk.byteLength
433 }
434 return { bytes: out }
435}
436
437/** Compute the exact output dimensions for a fit mode (rpx does its own math
438 * so imgix semantics don't depend on ts-images' internal dimension rules). */
439function planResize(
440 srcW: number,
441 srcH: number,
442 t: ImgxTransform,
443 opts: ResolvedImgxOptions,
444): { width: number, height: number, fit: 'fill' | 'cover' | 'contain' } | undefined {
445 let w = t.width
446 let h = t.height
447 if (w === undefined && h === undefined)
448 return undefined
449
450 // 0–1 fractions are relative to the source dimension.
451 if (w !== undefined && w < 1)
452 w = srcW * w
453 if (h !== undefined && h < 1)
454 h = srcH * h
455
456 // Derive the missing dimension from `ar` (crop workflows) or the source AR.
457 const aspect = srcW / srcH
458 if (w === undefined)
459 w = h! * (t.aspectRatio ?? aspect)
460 else if (h === undefined)
461 h = w / (t.aspectRatio ?? aspect)
462
463 w *= t.dpr
464 h! *= t.dpr
465
466 w = Math.min(w, opts.maxWidth)
467 h = Math.min(h!, opts.maxHeight)
468
469 switch (t.fit) {
470 case 'scale':
471 // Distort to the exact box.
472 break
473 case 'crop':
474 // Fill the box, cropping overflow at `position`.
475 return { width: dim(w), height: dim(h), fit: 'cover' }
476 case 'min': {
477 // Like crop, but never enlarge beyond the source.
478 const k = Math.min(srcW / w, srcH / h, 1)
479 return { width: dim(w * k), height: dim(h * k), fit: 'cover' }
480 }
481 case 'fill':
482 // Letterbox to the exact box with `bg` padding.
483 return { width: dim(w), height: dim(h), fit: 'contain' }
484 case 'max':
485 case 'clip': {
486 // Preserve AR inside the box; `max` additionally never enlarges.
487 let scale = Math.min(w / srcW, h / srcH)
488 if (t.fit === 'max')
489 scale = Math.min(scale, 1)
490 return { width: dim(srcW * scale), height: dim(srcH * scale), fit: 'fill' }
491 }
492 }
493 return { width: dim(w), height: dim(h), fit: 'fill' }
494}
495
496function dim(value: number): number {
497 return Math.max(1, Math.round(value))
498}
499
500const FORMAT_CONTENT_TYPES: Record<OutputFormat, string> = {
501 jpeg: 'image/jpeg',
502 png: 'image/png',
503 webp: 'image/webp',
504 avif: 'image/avif',
505 gif: 'image/gif',
506 bmp: 'image/bmp',
507}
508
509/**
510 * Decide the encode format: explicit `fm`/`format` wins; `auto=format`
511 * negotiates from `Accept` (webp when accepted — the ts-images avif encoder
512 * needs a system `avifenc` to produce real AV1, so rpx doesn't auto-pick it);
513 * otherwise keep the source format.
514 */
515function resolveOutputFormat(t: ImgxTransform, sourceFormat: string, accept: string | null): OutputFormat {
516 if (t.format)
517 return t.format
518 if (t.autoFormat && accept && accept.includes('image/webp'))
519 return 'webp'
520 const normalized = sourceFormat === 'jpg' ? 'jpeg' : sourceFormat
521 return OUTPUT_FORMATS.has(normalized) ? normalized as OutputFormat : 'png'
522}
523
524/** Serialize the parts of a transform that affect output bytes into a cache key. */
525function transformKey(t: ImgxTransform, outputFormat: OutputFormat, quality: number): string {
526 return [
527 t.width, t.height, t.fit, t.position, t.aspectRatio, t.dpr,
528 outputFormat, quality, t.lossless,
529 t.blur, t.sharpen, t.grayscale, t.brightness, t.saturation, t.hue,
530 t.tint && `${t.tint.r}.${t.tint.g}.${t.tint.b}`,
531 t.rotate, t.flip, t.flop,
532 t.background && `${t.background.r}.${t.background.g}.${t.background.b}.${t.background.a ?? 255}`,
533 ].join('|')
534}
535
536/**
537 * Post-upstream hook: given the request context and the upstream response,
538 * return either the transformed image response or the original response
539 * untouched. This must never throw — every failure path degrades to the
540 * original bytes.
541 */
542export async function applyImgxTransform(
543 req: Request,
544 pathname: string,
545 search: string,
546 imgx: ResolvedImgxOptions | undefined,
547 res: Response,
548 verbose?: boolean,
549): Promise<Response> {
550 if (!imgx || req.method !== 'GET' || res.status !== 200 || res.headers.has('content-range'))
551 return res
552
553 const transform = parseImgxParams(search)
554 if (!transform)
555 return res
556
557 const contentType = contentTypeOf(res)
558 if (contentType ? !DECODABLE_TYPES.has(contentType) : !extensionType(pathname))
559 return res
560
561 const declaredLength = Number(res.headers.get('content-length'))
562 if (Number.isFinite(declaredLength) && declaredLength > imgx.maxInputBytes)
563 return res
564
565 let bytes: Uint8Array
566 try {
567 const buffered = await bufferBody(res, imgx.maxInputBytes)
568 if (!('bytes' in buffered)) {
569 debugLog('imgx', `response for ${pathname} exceeds maxInputBytes; passing through`, verbose)
570 return new Response(buffered.overflow, { status: res.status, statusText: res.statusText, headers: res.headers })
571 }
572 bytes = buffered.bytes
573 }
574 catch (err) {
575 debugLog('imgx', `failed to buffer ${pathname}: ${err}`, verbose)
576 return new Response(null, { status: 502 })
577 }
578
579 const passthrough = () => new Response(bytes, { status: 200, statusText: res.statusText, headers: res.headers })
580
581 const mod = await loadTsImages(verbose)
582 if (!mod)
583 return passthrough()
584
585 try {
586 const sourceFormat = await mod.getMetadata(bytes).then(meta => meta.format)
587 .catch(() => contentType ? contentType.slice('image/'.length) : '')
588 if (!sourceFormat)
589 return passthrough()
590
591 const outputFormat = resolveOutputFormat(transform, sourceFormat, req.headers.get('accept'))
592 const quality = transform.quality ?? imgx.quality
593 const cacheKey = `${pathname}|${transformKey(transform, outputFormat, quality)}|${Bun.hash(bytes).toString(36)}`
594
595 const cached = imgx.cache?.get(cacheKey)
596 if (cached) {
597 debugLog('imgx', `cache hit for ${pathname}`, verbose)
598 return buildResponse(res, cached.bytes, cached.contentType, transform, 'hit')
599 }
600
601 let img = await mod.decode(bytes)
602
603 if (transform.rotate)
604 img = mod.rotate(img, transform.rotate, transform.background ? { background: transform.background } : {})
605 if (transform.flip)
606 img = mod.flip(img)
607 if (transform.flop)
608 img = mod.flop(img)
609
610 const plan = planResize(img.width, img.height, transform, imgx)
611 if (plan && (plan.width !== img.width || plan.height !== img.height || plan.fit !== 'fill')) {
612 img = mod.resize(img, {
613 width: plan.width,
614 height: plan.height,
615 fit: plan.fit,
616 position: transform.position,
617 background: transform.background ?? { r: 255, g: 255, b: 255 },
618 })
619 }
620
621 if (transform.blur)
622 img = mod.blur(img, transform.blur)
623 if (transform.sharpen)
624 img = mod.sharpen(img)
625 if (transform.grayscale)
626 img = mod.grayscale(img)
627 if (transform.brightness !== undefined || transform.saturation !== undefined || transform.hue !== undefined) {
628 img = mod.modulate(img, {
629 brightness: transform.brightness,
630 saturation: transform.saturation,
631 hue: transform.hue,
632 })
633 }
634 if (transform.tint)
635 img = mod.tint(img, transform.tint)
636
637 const encoded = await mod.encode(img, outputFormat, {
638 quality,
639 ...(transform.lossless === undefined ? {} : { lossless: transform.lossless }),
640 })
641 const outBytes = encoded instanceof Uint8Array ? encoded : new Uint8Array(encoded)
642 const outContentType = FORMAT_CONTENT_TYPES[outputFormat]
643
644 imgx.cache?.set(cacheKey, { bytes: outBytes, contentType: outContentType })
645 debugLog('imgx', `transformed ${pathname} (${bytes.byteLength}B ${sourceFormat} → ${outBytes.byteLength}B ${outputFormat})`, verbose)
646 return buildResponse(res, outBytes, outContentType, transform, 'miss')
647 }
648 catch (err) {
649 debugLog('imgx', `transform failed for ${pathname}, serving original: ${err}`, verbose)
650 return passthrough()
651 }
652}
653
654/** Assemble the transformed response, carrying upstream headers that still
655 * apply and dropping the ones invalidated by re-encoding. */
656function buildResponse(upstream: Response, bytes: Uint8Array, contentType: string, t: ImgxTransform, cache: 'hit' | 'miss'): Response {
657 const headers = new Headers(upstream.headers)
658 // The entity changed: upstream validators and framing no longer describe it.
659 headers.delete('content-encoding')
660 headers.delete('transfer-encoding')
661 headers.delete('etag')
662 headers.delete('last-modified')
663 headers.set('content-type', contentType)
664 headers.set('content-length', String(bytes.byteLength))
665 headers.set('x-rpx-imgx', cache)
666 if (t.autoFormat && !t.format)
667 headers.set('vary', headers.has('vary') ? `${headers.get('vary')}, accept` : 'accept')
668 return new Response(bytes, { status: 200, headers })
669}