All files / scripts optimize-images.ts

25.8% Statements 8/31
23.07% Branches 3/13
20% Functions 1/5
23.33% Lines 7/30

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 1381x           1x 1x                                           1x                                                                                           44x 44x                                                                                                                 1x        
import { mkdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
 
import sharp from 'sharp';
 
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const imageDir = path.join(repoRoot, 'public', 'images');
 
type VariantFormat = 'avif' | 'webp' | 'png';
 
interface WidthVariantSet {
  readonly kind: 'width';
  readonly source: string;
  readonly widths: readonly number[];
  readonly formats: readonly VariantFormat[];
  readonly fit?: keyof sharp.FitEnum;
}
 
interface SquareVariantSet {
  readonly kind: 'square';
  readonly source: string;
  readonly sizes: readonly number[];
  readonly formats: readonly VariantFormat[];
  readonly background?: sharp.Color;
}
 
type VariantSet = WidthVariantSet | SquareVariantSet;
 
export const IMAGE_VARIANT_MANIFEST: readonly VariantSet[] = [
  {
    kind: 'width',
    source: 'riksdagsmonitor-banner.webp',
    widths: [480, 768, 1024, 1536],
    formats: ['avif', 'webp'],
    fit: 'inside',
  },
  {
    kind: 'width',
    source: 'riksdagsmonitornews-banner.webp',
    widths: [480, 768, 1024, 1536],
    formats: ['avif', 'webp'],
    fit: 'inside',
  },
  {
    kind: 'width',
    source: 'og-image.png',
    widths: [600, 1200],
    formats: ['avif', 'webp'],
    fit: 'inside',
  },
  {
    kind: 'width',
    source: 'og-image-news.png',
    widths: [600, 1200],
    formats: ['avif', 'webp'],
    fit: 'inside',
  },
  {
    kind: 'square',
    source: 'riksdagsmonitor-logo.webp',
    sizes: [48, 96, 180, 192, 512],
    formats: ['png', 'webp'],
    background: { r: 0, g: 0, b: 0, alpha: 0 },
  },
  {
    kind: 'square',
    source: 'riksdagsmonitornews-logo.webp',
    sizes: [48, 96, 180, 192, 512],
    formats: ['png', 'webp'],
    background: { r: 0, g: 0, b: 0, alpha: 0 },
  },
];
 
export function variantName(source: string, size: number, format: VariantFormat): string {
  const { name } = path.parse(source);
  return `${name}-${size}w.${format}`;
}
 
async function encode(image: sharp.Sharp, format: VariantFormat): Promise<sharp.Sharp> {
  switch (format) {
    case 'avif':
      return image.avif({ quality: 62, effort: 6 });
    case 'webp':
      return image.webp({ quality: 78, effort: 6 });
    case 'png':
      return image.png({ compressionLevel: 9, adaptiveFiltering: true, palette: true });
  }
}
 
async function writeWidthVariant(set: WidthVariantSet, width: number, format: VariantFormat): Promise<void> {
  const input = path.join(imageDir, set.source);
  const output = path.join(imageDir, variantName(set.source, width, format));
  const pipeline = sharp(input)
    .resize({ width, fit: set.fit ?? 'inside', withoutEnlargement: true })
    .rotate();
  await (await encode(pipeline, format)).toFile(output);
}
 
async function writeSquareVariant(set: SquareVariantSet, size: number, format: VariantFormat): Promise<void> {
  const input = path.join(imageDir, set.source);
  const output = path.join(imageDir, variantName(set.source, size, format));
  const pipeline = sharp(input)
    .resize({
      width: size,
      height: size,
      fit: 'contain',
      background: set.background ?? { r: 0, g: 0, b: 0, alpha: 0 },
      withoutEnlargement: true,
    })
    .rotate();
  await (await encode(pipeline, format)).toFile(output);
}
 
export async function optimizeImages(): Promise<void> {
  await mkdir(imageDir, { recursive: true });
  for (const set of IMAGE_VARIANT_MANIFEST) {
    if (set.kind === 'width') {
      for (const width of set.widths) {
        for (const format of set.formats) {
          await writeWidthVariant(set, width, format);
        }
      }
    } else {
      for (const size of set.sizes) {
        for (const format of set.formats) {
          await writeSquareVariant(set, size, format);
        }
      }
    }
  }
}
 
Iif (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  await optimizeImages();
  console.log('✅ Optimized responsive image variants generated in public/images/');
}