1import { FileExtensionImage, MimeTypeImage } from '$lib/enums';
 2
 3/**
 4 * Convert a WebP base64 data URL to a PNG data URL
 5 * @param base64UrlWebp - The WebP base64 data URL to convert
 6 * @param backgroundColor - Background color for the PNG (default: 'white')
 7 * @returns Promise resolving to PNG data URL
 8 */
 9export function webpBase64UrlToPngDataURL(
10	base64UrlWebp: string,
11	backgroundColor: string = 'white'
12): Promise<string> {
13	return new Promise((resolve, reject) => {
14		try {
15			const img = new Image();
16
17			img.onload = () => {
18				const canvas = document.createElement('canvas');
19				const ctx = canvas.getContext('2d');
20
21				if (!ctx) {
22					reject(new Error('Failed to get 2D canvas context.'));
23					return;
24				}
25
26				const targetWidth = img.naturalWidth || 300;
27				const targetHeight = img.naturalHeight || 300;
28
29				canvas.width = targetWidth;
30				canvas.height = targetHeight;
31
32				if (backgroundColor) {
33					ctx.fillStyle = backgroundColor;
34					ctx.fillRect(0, 0, canvas.width, canvas.height);
35				}
36				ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
37
38				resolve(canvas.toDataURL(MimeTypeImage.PNG));
39			};
40
41			img.onerror = () => {
42				reject(new Error('Failed to load WebP image. Ensure the WebP data is valid.'));
43			};
44
45			img.src = base64UrlWebp;
46		} catch (error) {
47			const message = error instanceof Error ? error.message : String(error);
48			const errorMessage = `Error converting WebP to PNG: ${message}`;
49			console.error(errorMessage, error);
50			reject(new Error(errorMessage));
51		}
52	});
53}
54
55/**
56 * Check if a file is a WebP based on its MIME type
57 * @param file - The file to check
58 * @returns True if the file is a WebP
59 */
60export function isWebpFile(file: File): boolean {
61	return (
62		file.type === MimeTypeImage.WEBP || file.name.toLowerCase().endsWith(FileExtensionImage.WEBP)
63	);
64}
65
66/**
67 * Check if a MIME type represents a WebP
68 * @param mimeType - The MIME type to check
69 * @returns True if the MIME type is image/webp
70 */
71export function isWebpMimeType(mimeType: string): boolean {
72	return mimeType === MimeTypeImage.WEBP;
73}