(filePath: string)
| 34 | * @returns Result containing PDF data or a structured error |
| 35 | */ |
| 36 | export async function readPDF(filePath: string): Promise< |
| 37 | PDFResult<{ |
| 38 | type: 'pdf' |
| 39 | file: { |
| 40 | filePath: string |
| 41 | base64: string |
| 42 | originalSize: number |
| 43 | } |
| 44 | }> |
| 45 | > { |
| 46 | try { |
| 47 | const fs = getFsImplementation() |
| 48 | const stats = await fs.stat(filePath) |
| 49 | const originalSize = stats.size |
| 50 | |
| 51 | // Check if file is empty |
| 52 | if (originalSize === 0) { |
| 53 | return { |
| 54 | success: false, |
| 55 | error: { reason: 'empty', message: `PDF file is empty: ${filePath}` }, |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Check if PDF exceeds maximum size |
| 60 | // The API has a 32MB total request limit. After base64 encoding (~33% larger), |
| 61 | // a PDF must be under ~20MB raw to leave room for conversation context. |
| 62 | if (originalSize > PDF_TARGET_RAW_SIZE) { |
| 63 | return { |
| 64 | success: false, |
| 65 | error: { |
| 66 | reason: 'too_large', |
| 67 | message: `PDF file exceeds maximum allowed size of ${formatFileSize(PDF_TARGET_RAW_SIZE)}.`, |
| 68 | }, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | const fileBuffer = await readFile(filePath) |
| 73 | |
| 74 | // Validate PDF magic bytes — reject files that aren't actually PDFs |
| 75 | // (e.g., HTML files renamed to .pdf) before they enter conversation context. |
| 76 | // Once an invalid PDF document block is in the message history, every subsequent |
| 77 | // API call fails with 400 "The PDF specified was not valid" and the session |
| 78 | // becomes unrecoverable without /clear. |
| 79 | const header = fileBuffer.subarray(0, 5).toString('ascii') |
| 80 | if (!header.startsWith('%PDF-')) { |
| 81 | return { |
| 82 | success: false, |
| 83 | error: { |
| 84 | reason: 'corrupted', |
| 85 | message: `File is not a valid PDF (missing %PDF- header): ${filePath}`, |
| 86 | }, |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | const base64 = fileBuffer.toString('base64') |
| 91 | |
| 92 | // Note: We cannot check page count here without parsing the PDF |
| 93 | // The API will enforce the 100-page limit and return an error if exceeded |
no test coverage detected