import { binaryMediaTypeForPath } from "./binary-content"; export type SourcePreviewKind = "image" | "pdf" | "docx" | "unsupported"; export function sourcePreviewKind( path: string, mediaType?: string, ): SourcePreviewKind { // Both the stored format and the path must agree. Never interpret arbitrary // text/HTML/SVG as an active document based only on a filename. if (!mediaType || binaryMediaTypeForPath(path) !== mediaType) return "unsupported"; if (mediaType === "image/png" || mediaType === "image/jpeg") return "image"; if (mediaType === "application/pdf") return "pdf"; if (path.toLowerCase().endsWith(".docx")) return "docx"; return "unsupported"; } export function fitSourceScale( width: number, height: number, availableWidth: number, availableHeight: number, fitHeight: boolean, ) { if (width <= 0 || height <= 0) return 1; return Math.max( 0.1, Math.min( 1, (availableWidth - 48) / width, fitHeight ? (availableHeight - 48) / height : 1, ), ); } // Check ZIP's central directory before asking the DOCX renderer to inflate it. // This bounds ordinary highly compressed files without parsing XML on the UI // thread. ZIP64/encrypted documents fall back to downloading the original. export function assertPreviewableDocx(bytes: Uint8Array) { const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); let end = bytes.length - 22; for (; end >= Math.max(0, bytes.length - 65_557); end--) { if ( data.getUint32(end, true) === 0x06054b50 && end + 22 + data.getUint16(end + 20, true) === bytes.length ) break; } if (end < Math.max(0, bytes.length - 65_557)) throw new Error("Invalid DOCX archive"); const count = data.getUint16(end + 10, true); const directorySize = data.getUint32(end + 12, true); let offset = data.getUint32(end + 16, true); if ( data.getUint32(end + 4, true) !== 0 || count > 2_000 || count === 0 || offset + directorySize !== end ) throw new Error("Unsupported DOCX archive"); let size = 0; let hasDocument = false; for (let index = 0; index < count; index++) { if ( offset + 46 > end || data.getUint32(offset, true) !== 0x02014b50 || data.getUint16(offset + 8, true) & 1 ) throw new Error("Invalid DOCX entry"); size += data.getUint32(offset + 24, true); if (size > 40_000_000) throw new Error("DOCX is too large to preview"); const nameLength = data.getUint16(offset + 28, true); const next = offset + 46 + nameLength + data.getUint16(offset + 30, true) + data.getUint16(offset + 32, true); if (next > end) throw new Error("Invalid DOCX entry"); if ( new TextDecoder().decode( bytes.subarray(offset + 46, offset + 46 + nameLength), ) === "word/document.xml" ) hasDocument = true; offset = next; } if (offset !== end || !hasDocument) throw new Error("Invalid DOCX document"); }