All files / edge image-request.js

95% Statements 38/40
78.78% Branches 26/33
100% Functions 2/2
100% Lines 33/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52    1x 1x 1x 1x 1x   1x 1x     6x 6x 6x 6x     1x 3x 3x   3x 1x 1x     2x   2x 2x 2x   2x 2x   2x 2x   2x   2x 2x 2x 2x 2x   2x   2x    
'use strict'
 
const MAX_WIDTH = 4096
const MAX_HEIGHT = 4096
const MIN_DIMENSION = 1
const MIN_QUALITY = 30
const MAX_QUALITY = 95
 
const ALLOWED_FITS = new Set(['cover', 'contain', 'fill', 'inside', 'outside'])
const ALLOWED_FORMATS = new Set(['auto', 'jpeg', 'jpg', 'png', 'webp', 'avif'])
 
function toPositiveInt(value, min, max) {
  Iif (!value) return null
  const parsed = parseInt(value, 10)
  Iif (Number.isNaN(parsed)) return null
  return Math.min(max, Math.max(min, parsed))
}
 
exports.handler = (event, _context, callback) => {
  const request = event.Records[0].cf.request
  const rawQuery = request.querystring || ''
 
  if (!rawQuery) {
    callback(null, request)
    return
  }
 
  const params = new URLSearchParams(rawQuery)
 
  const width = toPositiveInt(params.get('w') || params.get('width'), MIN_DIMENSION, MAX_WIDTH)
  const height = toPositiveInt(params.get('h') || params.get('height'), MIN_DIMENSION, MAX_HEIGHT)
  const quality = toPositiveInt(params.get('q') || params.get('quality'), MIN_QUALITY, MAX_QUALITY)
 
  const fitRaw = (params.get('fit') || '').toLowerCase().trim()
  const fit = ALLOWED_FITS.has(fitRaw) ? fitRaw : null
 
  const formatRaw = (params.get('format') || params.get('f') || '').toLowerCase().trim()
  const format = ALLOWED_FORMATS.has(formatRaw) ? formatRaw : null
 
  const canonical = new URLSearchParams()
 
  Eif (width) canonical.set('w', String(width))
  Eif (height) canonical.set('h', String(height))
  Eif (quality) canonical.set('q', String(quality))
  if (fit) canonical.set('fit', fit)
  if (format) canonical.set('format', format)
 
  request.querystring = canonical.toString()
 
  callback(null, request)
}