All files / lib file-validation.ts

100% Statements 16/16
100% Branches 8/8
100% Functions 2/2
100% Lines 16/16

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        15x                 15x             15x           15x     15x     15x                 15x                         67x 67x   67x 14x 63x   14x     53x 9x 9x      
// Shared file upload validation constants and utilities
import { ValidationError } from "./errors";
 
/** Allowed image MIME types */
export const ALLOWED_IMAGE_TYPES: string[] = [
	"image/jpeg",
	"image/png",
	"image/webp",
	"image/gif",
	"image/avif",
];
 
/** Allowed video MIME types */
export const ALLOWED_VIDEO_TYPES: string[] = [
	"video/mp4",
	"video/quicktime",
	"video/webm",
];
 
/** All allowed upload MIME types (images + videos) */
export const ALLOWED_UPLOAD_TYPES: string[] = [
	...ALLOWED_IMAGE_TYPES,
	...ALLOWED_VIDEO_TYPES,
];
 
/** Maximum image file size: 10 MB */
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
 
/** Maximum video file size: 500 MB */
export const MAX_VIDEO_SIZE = 500 * 1024 * 1024;
 
/** Allowed audio MIME types */
export const ALLOWED_AUDIO_TYPES: string[] = [
	"audio/mpeg",
	"audio/mp3",
	"audio/wav",
	"audio/ogg",
	"audio/aac",
];
 
/** Maximum audio file size: 20 MB */
export const MAX_AUDIO_SIZE = 20 * 1024 * 1024;
 
/**
 * Validate an uploaded file against allowed types and size limits.
 * Throws ValidationError if the file type or size is not acceptable.
 */
export function validateUploadedFile(
	file: File,
	options?: {
		allowedTypes?: string[];
		maxSize?: number;
	},
): void {
	const allowedTypes = options?.allowedTypes ?? ALLOWED_IMAGE_TYPES;
	const maxSize = options?.maxSize ?? MAX_IMAGE_SIZE;
 
	if (!allowedTypes.includes(file.type)) {
		const typeNames = allowedTypes
			.map((t) => t.split("/")[1].toUpperCase())
			.join(", ");
		throw new ValidationError(`Invalid file type. Allowed: ${typeNames}`);
	}
 
	if (file.size > maxSize) {
		const sizeMB = Math.round(maxSize / (1024 * 1024));
		throw new ValidationError(`File too large. Maximum size is ${sizeMB}MB`);
	}
}