import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { documentMimeTypes } from '@/config/rag.config'; import { DocumentParser } from './document-parser.service'; const parser = new DocumentParser(); function pdf(content: string) { const objects = [ '<< /Type /Catalog /Pages 2 0 R >>', '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>', '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', `<< /Length ${content.length} >>\nstream\n${content}\nendstream`, ]; let output = '%PDF-1.4\n'; const refs = objects.map((object, index) => { const offset = output.length; output += `${index + 1} 0 obj\n${object}\nendobj\n`; return `${String(offset).padStart(10, '0')} 00000 n \n`; }); const xref = output.length; output += `xref\n0 6\n0000000000 65535 f \n${refs.join('')}trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; return Buffer.from(output); } it('extracts PDF text with a page number', async () => { const result = await parser.extract( pdf('BT /F1 12 Tf 10 20 Td (Article text) Tj ET'), documentMimeTypes[0], ); expect(result).toEqual([{ text: 'Article text', metadata: { page: 1 } }]); }); it('fails a PDF without extractable text', async () => { await expect( parser.extract(pdf('q Q'), documentMimeTypes[0]), ).rejects.toMatchObject({ code: 'pdf_no_text_ocr_required' }); }); it('extracts a DOCX and preserves styled section headings', async () => { const docx = await readFile( join(__dirname, '../../../test/fixtures/article.docx'), ); await expect(parser.extract(docx, documentMimeTypes[1])).resolves.toEqual([ { text: 'Overview\nArticle text', metadata: { section: 'Overview' } }, ]); await expect( parser.extract(docx.subarray(0, 12), documentMimeTypes[1]), ).rejects.toMatchObject({ code: 'invalid_docx' }); }); it('normalizes Persian UTF-8 and rejects invalid TXT input', async () => { await expect( parser.extract( Buffer.from(' سلام\r\nمتن مقاله '), documentMimeTypes[2], ), ).resolves.toEqual([{ text: 'سلام\nمتن مقاله', metadata: {} }]); await expect( parser.extract(Buffer.from([0xff]), documentMimeTypes[2]), ).rejects.toMatchObject({ code: 'invalid_utf8_text' }); });