A fast, helpful, and open-source document parser
better type detection
Logan Markewich803a53027af8
diff --git a/package-lock.json b/package-lock.jsonindex 447c7e9..7810002 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,17 +1,18 @@{"name": "@llamaindex/liteparse",- "version": "0.1.0",+ "version": "1.0.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@llamaindex/liteparse",- "version": "0.1.0",+ "version": "1.0.1","license": "Apache-2.0","dependencies": {"@hyzyla/pdfium": "^2.1.9","axios": "^1.7.0","commander": "^12.0.0",+ "file-type": "^21.3.3","form-data": "^4.0.0","p-limit": "^7.3.0","sharp": "^0.34.5",@@ -52,6 +53,15 @@"node": ">=6.9.0"}},+ "node_modules/@borewit/text-codec": {+ "version": "0.2.2",+ "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz",+ "integrity": "sha512-DDaRehssg1aNrH4+2hnj1B7vnUGEjU6OIlyRdkMd0aUdIUvKXrJfXsy8LVtXAy7DRvYVluWbMspsRhz2lcW0mQ==",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Borewit"+ }+ },"node_modules/@changesets/apply-release-plan": {"version": "7.1.0","resolved": "https://registry.npmjs.org/@changesets/apply-release-plan/-/apply-release-plan-7.1.0.tgz",@@ -2090,6 +2100,27 @@"dev": true,"license": "MIT"},+ "node_modules/@tokenizer/inflate": {+ "version": "0.4.1",+ "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz",+ "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==",+ "dependencies": {+ "debug": "^4.4.3",+ "token-types": "^6.1.1"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Borewit"+ }+ },+ "node_modules/@tokenizer/token": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",+ "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="+ },"node_modules/@types/chai": {"version": "5.2.3","resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",@@ -2778,7 +2809,6 @@"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz","integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",- "dev": true,"license": "MIT","dependencies": {"ms": "^2.1.3"@@ -3365,6 +3395,23 @@"node": ">=16.0.0"}},+ "node_modules/file-type": {+ "version": "21.3.3",+ "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.3.tgz",+ "integrity": "sha512-pNwbwz8c3aZ+GvbJnIsCnDjKvgCZLHxkFWLEFxU3RMa+Ey++ZSEfisvsWQMcdys6PpxQjWUOIDi1fifXsW3YRg==",+ "dependencies": {+ "@tokenizer/inflate": "^0.4.1",+ "strtok3": "^10.3.4",+ "token-types": "^6.1.1",+ "uint8array-extras": "^1.4.0"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sindresorhus/file-type?sponsor=1"+ }+ },"node_modules/fill-range": {"version": "7.1.1","resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",@@ -3653,6 +3700,25 @@"integrity": "sha512-yjD9nARJ/jb1g+CvD0tlhUHOrJ9Sy0P8T9MF3YaLlHnSRpwPfpTX0XIvpmw3gAJUmEu3FiICLBDPXVwyEvrleg==","license": "Apache-2.0"},+ "node_modules/ieee754": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ]+ },"node_modules/ignore": {"version": "5.3.2","resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",@@ -4010,7 +4076,6 @@"version": "2.1.3","resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz","integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",- "dev": true,"license": "MIT"},"node_modules/nanoid": {@@ -4720,6 +4785,21 @@"node": ">=4"}},+ "node_modules/strtok3": {+ "version": "10.3.4",+ "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz",+ "integrity": "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==",+ "dependencies": {+ "@tokenizer/token": "^0.3.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Borewit"+ }+ },"node_modules/synckit": {"version": "0.11.12","resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz",@@ -4830,6 +4910,23 @@"node": ">=8.0"}},+ "node_modules/token-types": {+ "version": "6.1.2",+ "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz",+ "integrity": "sha512-dRXchy+C0IgK8WPC6xvCHFRIWYUbqqdEIKPaKo/AcTUNzwLTK6AH7RjdLWsEZcAN/TBdtfUw3PYEgPr5VPr6ww==",+ "dependencies": {+ "@borewit/text-codec": "^0.2.1",+ "@tokenizer/token": "^0.3.0",+ "ieee754": "^1.2.1"+ },+ "engines": {+ "node": ">=14.16"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Borewit"+ }+ },"node_modules/tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",@@ -4994,6 +5091,17 @@"dev": true,"license": "MIT"},+ "node_modules/uint8array-extras": {+ "version": "1.5.0",+ "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz",+ "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/undici-types": {"version": "6.21.0","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",diff --git a/package.json b/package.jsonindex 6c49fc9..e228324 100644--- a/package.json+++ b/package.json@@ -43,6 +43,7 @@"@hyzyla/pdfium": "^2.1.9","axios": "^1.7.0","commander": "^12.0.0",+ "file-type": "^21.3.3","form-data": "^4.0.0","p-limit": "^7.3.0","sharp": "^0.34.5",diff --git a/src/conversion/convertToPdf.test.ts b/src/conversion/convertToPdf.test.tsindex 10ff56c..3d48c28 100644--- a/src/conversion/convertToPdf.test.ts+++ b/src/conversion/convertToPdf.test.ts@@ -1,10 +1,33 @@import { vi, describe, it, expect, afterEach } from "vitest";import { EventEmitter } from "events";-const mockFd = {- read: vi.fn(),- close: vi.fn(),-};+const mockFileTypeFromFile = vi.fn();+vi.mock("file-type", () => ({+ fileTypeFromFile: (...args: unknown[]) => mockFileTypeFromFile(...args),+ fileTypeFromBuffer: vi.fn(async (data: Buffer | Uint8Array) => {+ // Replicate enough detection to validate the wrapper+ if (data.length >= 4 && data[0] === 0x25 && data[1] === 0x50 && data[2] === 0x44 && data[3] === 0x46) {+ return { ext: "pdf", mime: "application/pdf" };+ }+ if (data.length >= 8 && data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {+ return { ext: "png", mime: "image/png" };+ }+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {+ return { ext: "jpg", mime: "image/jpeg" };+ }+ if (+ data.length >= 4 &&+ ((data[0] === 0x49 && data[1] === 0x49 && data[2] === 0x2a && data[3] === 0x00) ||+ (data[0] === 0x4d && data[1] === 0x4d && data[2] === 0x00 && data[3] === 0x2a))+ ) {+ return { ext: "tif", mime: "image/tiff" };+ }+ if (data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b) {+ return { ext: "zip", mime: "application/zip" };+ }+ return undefined;+ }),+}));const mockProc = {stdout: new EventEmitter(),@@ -22,9 +45,6 @@ vi.mock("fs", async () => {return {...actual,promises: {- open: vi.fn(async () => {- return mockFd;- }),access: vi.fn(async (path: string, _mode?: number) => {console.log(path);const toErrorPath = [@@ -62,22 +82,21 @@ import {} from "./convertToPdf";describe("test guessFileExtension", () => {- it("detects PDF", async () => {- mockFd.read.mockImplementation((buffer: Buffer) => {- Buffer.from("%PDF").copy(buffer);- });-+ it("detects PDF via file-type", async () => {+ mockFileTypeFromFile.mockResolvedValue({ ext: "pdf", mime: "application/pdf" });expect(await guessFileExtension("/some/file")).toBe(".pdf");});- it("detects PNG", async () => {- mockFd.read.mockImplementation((buffer: Buffer) => {- Buffer.from([0x89, 0x50, 0x4e, 0x47]).copy(buffer);- });-+ it("detects PNG via file-type", async () => {+ mockFileTypeFromFile.mockResolvedValue({ ext: "png", mime: "image/png" });expect(await guessFileExtension("/some/file")).toBe(".png");});+ it("defaults to .pdf when file-type returns undefined", async () => {+ mockFileTypeFromFile.mockResolvedValue(undefined);+ expect(await guessFileExtension("/some/file")).toBe(".pdf");+ });+it("returns extension directly if present", async () => {expect(await guessFileExtension("/some/file.pdf")).toBe(".pdf");});@@ -238,44 +257,44 @@ describe("test convertToPdf", () => {});describe("test guessExtensionFromBuffer", () => {- it("detects PDF from magic bytes", () => {+ it("detects PDF from magic bytes", async () => {const pdfBytes = Buffer.from("%PDF-1.4 some content");- expect(guessExtensionFromBuffer(pdfBytes)).toBe(".pdf");+ expect(await guessExtensionFromBuffer(pdfBytes)).toBe(".pdf");});- it("detects PNG from magic bytes", () => {+ it("detects PNG from magic bytes", async () => {const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);- expect(guessExtensionFromBuffer(pngBytes)).toBe(".png");+ expect(await guessExtensionFromBuffer(pngBytes)).toBe(".png");});- it("detects JPEG from magic bytes", () => {+ it("detects JPEG from magic bytes", async () => {const jpegBytes = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);- expect(guessExtensionFromBuffer(jpegBytes)).toBe(".jpg");+ expect(await guessExtensionFromBuffer(jpegBytes)).toBe(".jpg");});- it("detects TIFF (little-endian) from magic bytes", () => {+ it("detects TIFF (little-endian) from magic bytes", async () => {const tiffBytes = Buffer.from([0x49, 0x49, 0x2a, 0x00]);- expect(guessExtensionFromBuffer(tiffBytes)).toBe(".tiff");+ expect(await guessExtensionFromBuffer(tiffBytes)).toBe(".tif");});- it("detects TIFF (big-endian) from magic bytes", () => {+ it("detects TIFF (big-endian) from magic bytes", async () => {const tiffBytes = Buffer.from([0x4d, 0x4d, 0x00, 0x2a]);- expect(guessExtensionFromBuffer(tiffBytes)).toBe(".tiff");+ expect(await guessExtensionFromBuffer(tiffBytes)).toBe(".tif");});- it("detects ZIP-based formats from magic bytes", () => {+ it("detects ZIP-based formats from magic bytes", async () => {const zipBytes = Buffer.from([0x50, 0x4b, 0x03, 0x04]);- expect(guessExtensionFromBuffer(zipBytes)).toBe(".docx");+ expect(await guessExtensionFromBuffer(zipBytes)).toBe(".zip");});- it("defaults to .pdf for unknown bytes", () => {+ it("defaults to .pdf for unknown bytes", async () => {const unknownBytes = Buffer.from([0x00, 0x01, 0x02, 0x03]);- expect(guessExtensionFromBuffer(unknownBytes)).toBe(".pdf");+ expect(await guessExtensionFromBuffer(unknownBytes)).toBe(".pdf");});- it("works with Uint8Array input", () => {+ it("works with Uint8Array input", async () => {const pdfBytes = new Uint8Array(Buffer.from("%PDF-1.7"));- expect(guessExtensionFromBuffer(pdfBytes)).toBe(".pdf");+ expect(await guessExtensionFromBuffer(pdfBytes)).toBe(".pdf");});});diff --git a/src/conversion/convertToPdf.ts b/src/conversion/convertToPdf.tsindex 2743c88..4fb016b 100644--- a/src/conversion/convertToPdf.ts+++ b/src/conversion/convertToPdf.ts@@ -2,6 +2,7 @@ import { promises as fs, constants as fsConstants } from "fs";import { spawn } from "child_process";import path from "path";import os from "os";+import { fileTypeFromFile, fileTypeFromBuffer } from "file-type";/*** Returns the temp directory for LiteParse operations.@@ -75,7 +76,8 @@ export const imageExtensions = [export const htmlExtensions = [".htm", ".html", ".xhtml"];/**- * Guess file extension from file content+ * Guess file extension from file content using file-type magic byte detection.+ * Returns the path's own extension if present, otherwise inspects file bytes.*/export async function guessFileExtension(filePath: string): Promise<string> {const ext = path.extname(filePath).toLowerCase();@@ -83,34 +85,12 @@ export async function guessFileExtension(filePath: string): Promise<string> {return ext;}- // Read first few bytes to detect file type- const buffer = Buffer.alloc(16);- const fd = await fs.open(filePath, "r");- await fd.read(buffer, 0, 16, 0);- await fd.close();-- // PDF: %PDF- if (buffer.toString("utf-8", 0, 4) === "%PDF") {- return ".pdf";- }-- // PNG: 89 50 4E 47- if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47) {- return ".png";- }-- // JPEG: FF D8 FF- if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {- return ".jpg";- }-- // ZIP-based formats (docx, xlsx, etc): PK- if (buffer[0] === 0x50 && buffer[1] === 0x4b) {- // Could be docx, xlsx, pptx, odt, etc.- return ".docx"; // Default to docx for now+ const result = await fileTypeFromFile(filePath);+ if (result) {+ return `.${result.ext}`;}- return ext || ".pdf";+ return ".pdf"; // Default assumption for extensionless files}/**@@ -424,32 +404,12 @@ export async function cleanupConversionFiles(pdfPath: string): Promise<void> {}/**- * Guess file extension from raw bytes using magic-byte detection.+ * Guess file extension from raw bytes using file-type magic byte detection.*/-export function guessExtensionFromBuffer(data: Buffer | Uint8Array): string {- // PDF: %PDF- if (data.length >= 4 && data[0] === 0x25 && data[1] === 0x50 && data[2] === 0x44 && data[3] === 0x46) {- return ".pdf";- }- // PNG: 89 50 4E 47- if (data.length >= 4 && data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {- return ".png";- }- // JPEG: FF D8 FF- if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {- return ".jpg";- }- // TIFF: 49 49 2A 00 (little-endian) or 4D 4D 00 2A (big-endian)- if (- data.length >= 4 &&- ((data[0] === 0x49 && data[1] === 0x49 && data[2] === 0x2a && data[3] === 0x00) ||- (data[0] === 0x4d && data[1] === 0x4d && data[2] === 0x00 && data[3] === 0x2a))- ) {- return ".tiff";- }- // ZIP-based formats (docx, xlsx, pptx, etc.): PK- if (data.length >= 2 && data[0] === 0x50 && data[1] === 0x4b) {- return ".docx";+export async function guessExtensionFromBuffer(data: Buffer | Uint8Array): Promise<string> {+ const result = await fileTypeFromBuffer(data);+ if (result) {+ return `.${result.ext}`;}return ".pdf"; // Default assumption}@@ -461,7 +421,7 @@ export function guessExtensionFromBuffer(data: Buffer | Uint8Array): string {export async function convertBufferToPdf(data: Buffer | Uint8Array): Promise<ConversionResult | ConversionPassthrough | ConversionError> {- const ext = guessExtensionFromBuffer(data);+ const ext = await guessExtensionFromBuffer(data);// Write buffer to temp file with detected extensionconst tmpDir = await fs.mkdtemp(path.join(getTmpDir(), "liteparse-"));diff --git a/src/core/parser.ts b/src/core/parser.tsindex e8a118d..c707fd9 100644--- a/src/core/parser.ts+++ b/src/core/parser.ts@@ -123,7 +123,7 @@ export class LiteParse {doc = await this.pdfEngine.loadDocument(pdfPath);} else {log(`Processing buffer input (${input.byteLength} bytes)`);- const ext = guessExtensionFromBuffer(input);+ const ext = await guessExtensionFromBuffer(input);if (ext === ".pdf") {// Zero-disk path: pass bytes directly to the PDF engine