/
grigoriygrisha
/
excel-loader
Обзор
Документация
Войти
/
grigoriygrisha
/
excel-loader
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/utils/detectFormat.ts
45 строк
1 KB
grigoriy-grisha
first_commit
26 июл 2026, 21:46
26 июл 2026, 21:46
6cc93a5
Код
Авторство
О чём код?
import { UnsupportedFormatError, type FileFormat } from '../core/types.js' export class FormatDetector { private static readonly ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04] async detect(file: File, hint?: FileFormat): Promise<FileFormat> { if (hint === 'xlsx' || hint === 'csv') return hint const byExtension = this.fromExtension(file.name) if (byExtension) return byExtension const byMagic = await this.fromMagicBytes(file) if (byMagic) return byMagic throw new UnsupportedFormatError( `Could not determine the format of "${file.name}". ` + `Supported formats are .xlsx and .csv.`, ) } private fromExtension(name: string): FileFormat | undefined { const lower = name.toLowerCase() if (lower.endsWith('.xlsx') || lower.endsWith('.xlsm')) return 'xlsx' if (lower.endsWith('.csv') || lower.endsWith('.tsv')) return 'csv' return undefined } private async fromMagicBytes(file: File): Promise<FileFormat | undefined> { const head = new Uint8Array(await file.slice(0, 4).arrayBuffer()) if (head.length >= 4 && FormatDetector.ZIP_MAGIC.every((b, i) => head[i] === b)) { return 'xlsx' } if (head.length > 0 && head.every((b) => b === 0x09 || b === 0x0a || b === 0x0d || (b >= 0x20 && b <= 0x7e))) { return 'csv' } return undefined } } export async function detectFormat( file: File, hint?: FileFormat, ): Promise<FileFormat> { return new FormatDetector().detect(file, hint) }