diff --git a/src/converters/image.js b/src/converters/image.js new file mode 100644 index 0000000..6c4086e --- /dev/null +++ b/src/converters/image.js @@ -0,0 +1,25 @@ +import sharp from 'sharp'; +import { register } from './registry.js'; + +const IMAGE_FORMATS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'tiff', 'avif']; + +function sharpFormatName(format) { + return format === 'jpg' ? 'jpeg' : format; +} + +export function registerImageConverters() { + for (const sourceFormat of IMAGE_FORMATS) { + for (const targetFormat of IMAGE_FORMATS) { + if (sourceFormat === targetFormat) continue; + + register({ + family: 'image', + sourceFormat, + targetFormat, + convert: async (inputPath, outputPath) => { + await sharp(inputPath).toFormat(sharpFormatName(targetFormat)).toFile(outputPath); + }, + }); + } + } +} diff --git a/test/converters/image.test.js b/test/converters/image.test.js new file mode 100644 index 0000000..684e311 --- /dev/null +++ b/test/converters/image.test.js @@ -0,0 +1,47 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import { registerImageConverters } from '../../src/converters/image.js'; +import { resolve, listTargetFormats } from '../../src/converters/registry.js'; +import { detectInputMime } from '../../src/mime.js'; + +let tmpDir; + +beforeAll(async () => { + registerImageConverters(); + tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'converter-image-')); +}); + +afterAll(async () => { + await fs.rm(tmpDir, { recursive: true, force: true }); +}); + +describe('image converters', () => { + it('registers every pair among the supported formats', () => { + const targets = listTargetFormats('png').sort(); + expect(targets).toEqual(['avif', 'gif', 'jpeg', 'jpg', 'tiff', 'webp']); + }); + + it('converts a PNG fixture to WebP', async () => { + const inputPath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png'); + const outputPath = path.join(tmpDir, 'output.webp'); + const entry = resolve('png', 'webp'); + + await entry.convert(inputPath, outputPath); + + const detected = await detectInputMime(outputPath); + expect(detected.mime).toBe('image/webp'); + }); + + it('converts a PNG fixture to JPG', async () => { + const inputPath = path.join(import.meta.dirname, '..', 'fixtures', 'sample.png'); + const outputPath = path.join(tmpDir, 'output.jpg'); + const entry = resolve('png', 'jpg'); + + await entry.convert(inputPath, outputPath); + + const detected = await detectInputMime(outputPath); + expect(detected.mime).toBe('image/jpeg'); + }); +}); diff --git a/test/fixtures/sample.png b/test/fixtures/sample.png index 520b38b..6e2747d 100644 Binary files a/test/fixtures/sample.png and b/test/fixtures/sample.png differ