import type { FileServiceConfig, ValidationResult } from '../types'; export function validateFile( file: File, config?: FileServiceConfig ): ValidationResult { const errors: string[] = []; const warnings: string[] = []; // Size validation if (config?.maxFileSize && file.size > config.maxFileSize) { const maxSizeMB = (config.maxFileSize / (1024 * 1024)).toFixed(2); const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2); errors.push( `File size (${fileSizeMB}MB) exceeds maximum allowed size (${maxSizeMB}MB)` ); } // Type validation if (config?.acceptedFileTypes && config.acceptedFileTypes.length > 0) { const isAccepted = config.acceptedFileTypes.some((acceptedType) => { if (acceptedType.endsWith('/*')) { // Wildcard match (e.g., "image/*") const baseType = acceptedType.split('/')[0]; return file.type.startsWith(baseType + '/'); } return file.type === acceptedType; }); if (!isAccepted) { errors.push( `File type "${file.type}" is not accepted. Allowed types: ${config.acceptedFileTypes.join(', ')}` ); } } // Additional validations if (file.size === 0) { errors.push('File is empty'); } if (file.name.length === 0) { errors.push('File name is empty'); } // Warning for large files if (file.size > 10 * 1024 * 1024) { warnings.push('File is larger than 10MB, upload may take longer'); } return { valid: errors.length === 0, errors, warnings, }; } export function getFileType(file: File): string { return file.type || 'application/octet-stream'; } export function isImageFile(file: File): boolean { return file.type.startsWith('image/'); } export function isPdfFile(file: File): boolean { return file.type === 'application/pdf'; } export function isWordFile(file: File): boolean { return ( file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.type === 'application/msword' ); } export function isExcelFile(file: File): boolean { return ( file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel' ); } export function isCsvFile(file: File): boolean { return ( file.type === 'text/csv' || file.name.toLowerCase().endsWith('.csv') ); } export function formatFileSize(bytes: number): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i]; }