@llamaindex/liteparse 2.14.4 → 2.14.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -1
- package/dist/lib.cjs +3 -0
- package/dist/lib.cjs.map +1 -1
- package/dist/lib.d.cts +29 -1
- package/dist/lib.d.ts +29 -1
- package/dist/lib.js +3 -0
- package/dist/lib.js.map +1 -1
- package/dist/pool-worker.js +1 -0
- package/dist/pool-worker.js.map +1 -1
- package/libpdfium.so +0 -0
- package/liteparse.linux-x64-gnu.node +0 -0
- package/package.json +8 -8
package/dist/lib.cjs
CHANGED
|
@@ -366,6 +366,7 @@ var LiteParse = class {
|
|
|
366
366
|
extractTextMetadata: userConfig.extractTextMetadata,
|
|
367
367
|
cropBox: userConfig.cropBox,
|
|
368
368
|
skipDiagonalText: userConfig.skipDiagonalText,
|
|
369
|
+
pageOrientationCorrections: userConfig.pageOrientationCorrections,
|
|
369
370
|
includeComplexity: userConfig.includeComplexity,
|
|
370
371
|
extractVectorGraphics: userConfig.extractVectorGraphics
|
|
371
372
|
};
|
|
@@ -419,6 +420,7 @@ var LiteParse = class {
|
|
|
419
420
|
extractTextMetadata: resolved.extractTextMetadata ?? false,
|
|
420
421
|
cropBox: resolved.cropBox ?? void 0,
|
|
421
422
|
skipDiagonalText: resolved.skipDiagonalText ?? false,
|
|
423
|
+
pageOrientationCorrections: resolved.pageOrientationCorrections ?? void 0,
|
|
422
424
|
includeComplexity: resolved.includeComplexity ?? false,
|
|
423
425
|
extractVectorGraphics: resolved.extractVectorGraphics ?? false
|
|
424
426
|
};
|
|
@@ -588,6 +590,7 @@ function toParseResult(result) {
|
|
|
588
590
|
function toPage(p) {
|
|
589
591
|
return {
|
|
590
592
|
pageNum: p.pageNum,
|
|
593
|
+
pageLabel: p.pageLabel ?? void 0,
|
|
591
594
|
width: p.width,
|
|
592
595
|
height: p.height,
|
|
593
596
|
contentBounds: p.contentBounds,
|
package/dist/lib.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib.ts","../node_modules/tsup/assets/cjs_shims.js","../src/native.ts","../src/pool.ts"],"sourcesContent":["import {\n native,\n type LiteParseNative,\n type LiteParseNativeConfig,\n type NativeParseResult,\n type NativeParsedPage,\n type NativePageInput,\n type NativeTextItem,\n type NativeExtractedImage,\n type NativeStructureTreeElement,\n type NativePageComplexityStats,\n type NativeScreenshotResult,\n} from \"./native.js\";\nimport { WorkerPool, ParseTimeoutError } from \"./pool.js\";\n\nexport { ParseTimeoutError };\n\n// ---------------------------------------------------------------------------\n// Public types — match the existing TypeScript API\n// ---------------------------------------------------------------------------\n\nexport type LiteParseInput = string | Buffer | Uint8Array;\nexport type OutputFormat = \"json\" | \"text\" | \"markdown\";\nexport type ImageMode = \"off\" | \"placeholder\" | \"embed\";\n\n/** Options for pool mode: parsing in persistent, killable worker processes. */\nexport interface PoolOptions {\n /**\n * Route `parse()` through a pool of this many persistent worker processes.\n * Call `close()` when done (an idle pool never keeps the event loop alive, \n * but explicit shutdown frees workers immediately).\n */\n poolSize?: number;\n /**\n * Hard per-parse deadline in milliseconds. Requires `poolSize`.\n * The pool enforces the deadline by SIGKILLing the worker. On expiry\n * the parse rejects with {@link ParseTimeoutError} (naming the document)\n * and a fresh worker replaces the killed one.\n */\n parseTimeoutMs?: number;\n}\n\nexport interface LiteParseConfig {\n ocrLanguage: string;\n ocrEnabled: boolean;\n ocrServerUrl?: string;\n /** Extra HTTP headers sent with every request to `ocrServerUrl`. */\n ocrServerHeaders?: Record<string, string>;\n tessdataPath?: string;\n maxPages: number;\n targetPages?: string;\n /** Render parsed pages to PNG and return them in `ParseResult.screenshots`. */\n extractScreenshots: boolean;\n /** Continue after page-level extraction failures and collect `pageErrors`. */\n continueOnPageError: boolean;\n dpi: number;\n outputFormat: OutputFormat;\n /** How to surface raster images in markdown output (default: \"placeholder\"). */\n imageMode: ImageMode;\n /** Extract embedded image bytes and metadata (default: false). */\n extractImages: boolean;\n /** Directory where extracted embedded image files are written. Requires `extractImages`. */\n imageOutputDir?: string;\n /** Render hyperlink annotations as `[text](url)` in markdown output (default: true). */\n extractLinks: boolean;\n /** Keep running headers/footers in markdown output instead of stripping repeated page-band lines and page chrome (default: false). */\n keepHeadersFooters: boolean;\n /** Extract all PDF annotations into each parsed page (default: false). */\n extractAnnotations: boolean;\n /** Extract AcroForm widget fields and values (default: false). */\n extractFormFields: boolean;\n /** Extract the tagged-PDF logical structure tree (default: false). */\n extractStructureTree: boolean;\n /**\n * Emit each page's classified layout blocks with bounding boxes\n * (default: false). This is the same decomposition the Markdown renderer\n * consumes, exposed as data; enabling it never changes the rendered Markdown.\n */\n extractBlocks: boolean;\n /** Extract raw XFA packets (name + XML content) into `ParseResult.xfaPackets` (default: false). */\n extractXfaPackets: boolean;\n /**\n * Collect document provenance metadata into `result.docMeta`. Default\n * false: Absent for inputs converted from a non-PDF format.\n */\n extractDocumentMetadata: boolean;\n /** Emit each page's `contentBounds` (union bbox of top-level content objects) (default: false). */\n extractContentBounds: boolean;\n /** Detect solid rectangles/lines in rendered page screenshots (default: false). */\n detectScreenshotRects: boolean;\n /** Draw AcroForm field appearances into rendered rasters (screenshots and OCR inputs; runs document open/JS actions; default: false). */\n renderFormFields: boolean;\n preserveVerySmallText: boolean;\n password?: string;\n quiet: boolean;\n numWorkers: number;\n /**\n * Whether a systemic OCR failure (every OCR task failed and at least one was\n * a text-sparse page) aborts the whole parse (default: true). Set false to\n * keep already-recovered native text and return partial results instead of\n * rejecting — for callers that prefer a degraded document over a hard failure.\n */\n ocrFailureFatal: boolean;\n /**\n * OCR request-hedging schedule (ms). Empty (default) = no hedging. Multiple\n * delays (e.g. `[0, 5000, 10000, 15000, 20000]`) fire duplicate requests per\n * OCR attempt and take the first success — lower tail latency on a slow/stuck\n * OCR pod, at the cost of extra OCR-server load. HTTP OCR engine only.\n */\n ocrHedgeDelaysMs: number[];\n /**\n * Emit per-word sub-boxes on each text item ({@link TextItem.words}).\n * Default false. Word boxes roughly double the text-item payload (size + napi\n * marshalling), so enable only when doing word-level bbox attribution.\n */\n emitWordBoxes: boolean;\n /** Include rich PDF text metadata on returned text items. Default false. */\n extractTextMetadata?: boolean;\n /**\n * Restrict output to a page sub-region. Each field is the fraction of the\n * page cropped away from that side (top-left origin), so `{ left: 0.5 }`\n * discards the left half. A text item survives only when it lies entirely\n * inside the remaining rectangle. Undefined (default) keeps the whole page.\n * Applied after OCR merge, so OCR text outside the region is dropped too.\n */\n cropBox?: CropBox;\n /**\n * Drop diagonal text — items whose rotation is more than 2° off the nearest\n * right angle (0/90/180/270). Default false. Use to exclude rotated\n * watermarks/stamps from the output.\n */\n skipDiagonalText: boolean;\n /**\n * Compute per-page complexity signals during {@link LiteParse.parse} and\n * attach them to each page as {@link ParsedPage.complexity} (the same signals\n * {@link LiteParse.isComplex} returns). Default false; enabling it runs an\n * extra vector-text detection pass.\n */\n includeComplexity: boolean;\n /** Expose page-scoped vector shapes and merged H/V line segments. Default false. */\n extractVectorGraphics: boolean;\n}\n\n/**\n * A page sub-region expressed as the fraction cropped from each side\n * (top-left origin, each value in `[0, 1]`).\n */\nexport interface CropBox {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\n/**\n * One word's bounding box within a {@link TextItem}, in the same viewport space\n * (top-left origin, 72 DPI). `text` excludes inter-word spaces.\n */\nexport interface WordBox {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface TextItem {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n fontName?: string;\n fontSize?: number;\n /** Font size after applying the text matrix's vertical scale. */\n fontHeight?: number;\n fontAscent?: number;\n fontDescent?: number;\n fontWeight?: number;\n /** Sum of source glyph widths in points. */\n textWidth?: number;\n fontIsBuggy?: boolean;\n /** Marked-content ID from the PDF structure tree. */\n mcid?: number;\n /** Fill color as an eight-character ARGB hex string. */\n fillColor?: string;\n /** Stroke color as an eight-character ARGB hex string. */\n strokeColor?: string;\n /** Raw PDF content-stream character codes for the source glyphs. */\n charCodes?: number[];\n /** True when the trailing source space was synthesized by PDFium. */\n trailingSpaceGenerated?: boolean;\n /** OCR confidence score (0.0-1.0). Undefined for native PDF text. */\n confidence?: number;\n /** Rotation in degrees (viewport space). Defaults to 0 when omitted. */\n rotation?: number;\n /**\n * Per-word sub-boxes within this item. A text item groups several words\n * together (breaking only at line/column boundaries), so this carries the\n * finer word-level geometry for bbox attribution. Empty/undefined for items\n * with no word split (e.g. OCR-sourced or single-token items).\n */\n words?: WordBox[];\n}\n\n/**\n * A vector-graphic primitive supplied to {@link LiteParse.parsePages}. `kind`\n * selects the variant: `\"stroke\"` (uses `x1/y1/x2/y2`) or `\"rect\"` (uses\n * `x/y/width/height`, top-left origin). Coordinates are viewport space (72 DPI),\n * matching the text items. `hasFill`/`hasStroke` carry the paint intent even\n * when the color is unknown, so ruled-table edge detection still treats a\n * colorless stroked rect as stroked.\n */\nexport interface Graphic {\n kind: \"stroke\" | \"rect\";\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n hasFill?: boolean;\n hasStroke?: boolean;\n fillColor?: string;\n strokeColor?: string;\n lineWidth?: number;\n}\n\n/**\n * A page of pre-extracted text supplied to {@link LiteParse.parsePages}.\n * Coordinates are viewport space (top-left origin, 72 DPI). `graphics` is\n * optional; when supplied it enables ruled-table and horizontal-rule detection.\n */\nexport interface PageInput {\n pageNumber: number;\n pageWidth: number;\n pageHeight: number;\n textItems: TextItem[];\n graphics?: Graphic[];\n}\n\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface ParsedPage {\n pageNum: number;\n width: number;\n height: number;\n /**\n * Union bbox of the page's top-level content objects in viewport coords\n * (visible content extent). Absent for empty pages.\n */\n /** Present only when `extractContentBounds` is enabled. */\n contentBounds?: Rect;\n text: string;\n markdown: string;\n textItems: TextItem[];\n /**\n * Per-page complexity signals (the same {@link LiteParse.isComplex} returns).\n * Present only when parsing with `includeComplexity: true`; `undefined`\n * otherwise.\n */\n complexity?: PageComplexityStats;\n /** Present only when parsing with `extractVectorGraphics: true`. */\n vectorGraphics?: VectorGraphics;\n /** Present only when `extractAnnotations` is enabled. */\n annotations?: DocumentAnnotation[];\n /** Present only when `extractFormFields` is enabled. */\n formFields?: FormField[];\n /** Present only when `extractStructureTree` is enabled. */\n structureTree?: StructureTree;\n /**\n * Classified layout blocks in reading order — the same blocks, in the same\n * order, the page's Markdown is built from. Present only when\n * `extractBlocks` is enabled.\n */\n blocks?: LayoutBlock[];\n}\n\n/** One table cell: its text and the region of the page it was read from. */\nexport interface LayoutCell {\n text: string;\n /**\n * Absent for cells with no ink behind them — padding inserted to square off\n * a ragged grid, or halves of a merged run split at an estimated position.\n */\n bbox?: Rect;\n}\n\n/** A classified block of page content, discriminated by `kind`. */\nexport interface LayoutBlock {\n kind:\n | \"heading\"\n | \"paragraph\"\n | \"list_item\"\n | \"code\"\n | \"table\"\n | \"grid_fallback\"\n | \"rule\"\n | \"figure\";\n /** Rendered text for `heading`, `paragraph`, and `list_item`. */\n text?: string;\n /** Heading level (1-6), or list nesting depth for `list_item`. */\n level?: number;\n bold?: boolean;\n italic?: boolean;\n /** `list_item` only. `marker` is the marker as it appeared on the page. */\n ordered?: boolean;\n marker?: string;\n /** Verbatim source lines for `code` and `grid_fallback`. */\n lines?: string[];\n /** Best-effort language hint for `code`. */\n lang?: string;\n /** `table` only. */\n header?: LayoutCell[];\n rows?: LayoutCell[][];\n /** `figure` only, matching the `img_{id}.{format}` Markdown target. */\n id?: string;\n format?: string;\n /**\n * Region this block occupies, in the same top-left 72-DPI viewport space as\n * `textItems`. The union of every source line that fed the block.\n */\n bbox?: Rect;\n}\n\nexport type StructureAttributeValue = boolean | number | string;\n\nexport interface StructureTree {\n roots: StructureTreeElement[];\n}\n\nexport interface StructureTreeElement {\n type: string;\n id?: string;\n actualText?: string;\n altText?: string;\n title?: string;\n attributes: Record<string, StructureAttributeValue>;\n markedContentIds: number[];\n children: StructureTreeElement[];\n annotations: DocumentAnnotation[];\n}\n\nexport interface VectorGraphics {\n shapes: VectorShape[];\n lines: VectorLine[];\n}\n\nexport interface VectorShape {\n bbox: { x: number; y: number; width: number; height: number };\n stroke: boolean;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n hasCurve: boolean;\n}\n\nexport interface VectorLine {\n x1: number; y1: number; x2: number; y2: number;\n stroke: boolean;\n strokeWidth?: number;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n}\n\nexport interface AnnotationRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface DocumentAnnotation {\n subtype: string;\n contents?: string;\n created?: string;\n modified?: string;\n title?: string;\n rect?: AnnotationRect;\n quadpointRects: AnnotationRect[];\n uri?: string;\n}\n\nexport interface FormField {\n id: string;\n type: string;\n page: number;\n annotationIndex: number;\n widgetIndex: number;\n objectNumber?: number;\n name?: string;\n alternateName?: string;\n value?: string;\n exportValue?: string;\n fieldFlags: number;\n controlCount?: number;\n controlIndex?: number;\n checked?: boolean;\n rect?: AnnotationRect;\n options: string[];\n selectedOptions: string[];\n}\n\nexport interface ExtractedImage {\n /** Reference id used in the markdown output (e.g. `` → `\"p1_1\"`). */\n id: string;\n /** File name used when `imageOutputDir` is configured. */\n name: string;\n /** Written file path, absent for in-memory-only extraction. */\n path?: string;\n page: number;\n /** Placement on the page in viewport coordinates (top-left origin, 72 DPI). */\n bbox: { x: number; y: number; width: number; height: number };\n /** Intrinsic pixel dimensions of the image resource. */\n width: number;\n height: number;\n /** Clockwise page-object rotation in degrees. */\n rotation: number;\n format: string;\n /** First occurrence with identical encoded source data, when duplicated. */\n duplicateOf?: string;\n bytes: Buffer;\n}\n\nexport interface ParseResult {\n /** Total source-document pages before `targetPages` or `maxPages` filtering. */\n totalPages: number;\n pages: ParsedPage[];\n /** Page-level PDFium extraction failures when tolerance is enabled. */\n pageErrors: Array<{ pageNum: number; message: string }>;\n text: string;\n /** Populated only when `extractImages` is true. */\n images: ExtractedImage[];\n /** PNG screenshots of parsed pages when `extractScreenshots` is enabled. */\n screenshots: ScreenshotResult[];\n /** Embedded image objects that PDFium could not render or encode. */\n imageErrorCount: number;\n /** PDFium form type, present only when `extractFormFields` is enabled. */\n formType?: number;\n /** The document's `/Info` `Creator` entry, when present. */\n creator?: string;\n /** The document's `/Info` `Producer` entry, when present. */\n producer?: string;\n /**\n * Document-level provenance metadata from PDFium and the source PDF.\n * Present only when `extractDocumentMetadata` is enabled and the input was\n * a real PDF (not converted from DOCX/XLSX/an image).\n */\n docMeta?: DocumentMetadata;\n /** Raw XFA packets; present only when `extractXfaPackets` is enabled. */\n xfaPackets?: XfaPacket[];\n}\n\nexport interface ParseBatchOptions {\n /** Pages materialized in one batch. Default: 25. */\n batchSize?: number;\n}\n\nexport interface ParseBatch {\n /** First source page in this batch (1-indexed). */\n startPage: number;\n /** Last source page in this batch (1-indexed, inclusive). */\n endPage: number;\n /** Total source-document pages, before the parser's `maxPages` cap. */\n totalPages: number;\n result: ParseResult;\n}\n\n/** Provenance and tamper-analysis facts extracted from the source PDF. */\nexport interface DocumentMetadata {\n creationDate?: string;\n modDate?: string;\n /** Encoded PDF version (`14` means PDF 1.4). */\n fileVersion?: number;\n isEncrypted?: boolean;\n securityHandlerRevision?: number;\n permissions?: number;\n eofSectionCount?: number;\n startxrefCount?: number;\n trailerIdPairDiffers?: boolean;\n rawFileSize?: number;\n /**\n * The document catalog's `/Metadata` XMP packet, capped at 64 KiB. Absent\n * when the document has none, when it is too large to resolve cheaply, or\n * in WASM builds.\n */\n xmp?: string;\n /** True when the catalog's XMP stream exceeded the 64 KiB cap. */\n xmpTruncated?: boolean;\n signatureCount?: number;\n /** False when bytes were appended after a readable signature byte range. */\n signatureByteRangeReachesEof?: boolean;\n}\n\n/** One raw packet from an XFA form document's `/XFA` array. */\nexport interface XfaPacket {\n index: number;\n name?: string;\n contentLength: number;\n /** Packet content (usually XML), lossily decoded as UTF-8. */\n content?: string;\n}\n\nexport interface ScreenshotResult {\n pageNum: number;\n width: number;\n height: number;\n imageBuffer: Buffer;\n /** True when every pixel has the same color (blank page after render). */\n isSolidFill: boolean;\n /** Solid rectangles/lines detected in the raster (viewport coords). Populated only with `detectScreenshotRects`. */\n rects: ScreenshotRect[];\n}\n\n/** One solid rectangle (or line) detected in a rendered page bitmap. */\nexport interface ScreenshotRect {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Fill color as ARGB hex string (e.g. \"ff1a2b3c\"). */\n color: string;\n /** True when the region is a solid line rather than a filled area. */\n isLine: boolean;\n}\n\n/**\n * Per-page complexity signals from {@link LiteParse.isComplex}, used to decide\n * whether a document needs OCR or other advanced parsing.\n */\nexport interface PageComplexityStats {\n pageNumber: number;\n textLength: number;\n /** Fraction of the page area covered by native text (0–1). */\n textCoverage: number;\n hasSubstantialImages: boolean;\n /**\n * Number of counted raster images — inline figures only; full-page\n * backgrounds are excluded (see {@link fullPageImage}).\n */\n imageBlockCount: number;\n /**\n * Summed image-bbox area over page area, clamped to 1. Counts inline figures\n * only: a full-page scan raster contributes 0 here — check\n * {@link fullPageImage} for that.\n */\n imageCoverage: number;\n /**\n * Largest single *counted* image's area over page area, clamped to 1. Same\n * exclusion as {@link imageCoverage}: a full-page raster contributes 0.\n */\n largestImageCoverage: number;\n /**\n * A single raster covers ≥90% of the page. Full-page backgrounds are excluded\n * from the image coverage fields, so this is the only signal that tells a scan\n * apart from a blank page — both otherwise report no text and no images.\n */\n fullPageImage: boolean;\n /**\n * Filled vector-outline area not covered by native text, in pt². `undefined`\n * when a cheaper signal already decided the page, so this walk was skipped.\n */\n uncoveredVectorArea?: number;\n isGarbled: boolean;\n pageArea: number;\n /** Verdict: whether this page needs more than the cheap text-only path. */\n needsOcr: boolean;\n /**\n * Every reason the page was flagged (e.g. `\"scanned\"`, `\"sparse-text\"`,\n * `\"garbled\"`). Empty exactly when `needsOcr` is false. This is the value to\n * route on; new reasons may be added over time.\n */\n reasons: string[];\n /**\n * Layout-difficulty signals (columns, tables, dense graphics). Orthogonal to\n * `needsOcr`: none of these imply OCR — they signal that the text-only path\n * may mangle reading order or structure. Present in `isComplex()` results\n * and `includeComplexity` parses.\n */\n layout?: LayoutComplexityStats;\n}\n\n/**\n * Layout-difficulty signals for one page, computed from the real\n * grid-projection pass.\n */\nexport interface LayoutComplexityStats {\n /** Side-by-side text columns found by the layout pass (1 = single column). */\n columnCount: number;\n /** Ruled-table grids detected on the page. */\n ruledTableCount: number;\n /** Combined ruled-table area over page area, clamped to 1. */\n ruledTableCoverage: number;\n /**\n * Borderless table runs found by track-aligned text detection (description\n * lists excluded). Ruled tables can appear here too — don't sum with\n * `ruledTableCount`; the two discriminate ruled from borderless.\n */\n textTableRunCount: number;\n /** Figure regions clustered from vector graphics. */\n figureCount: number;\n /** Combined figure area over page area, clamped to 1. */\n figureCoverage: number;\n /** Verdict: whether any layout reason fired. */\n isComplex: boolean;\n /**\n * Every layout reason (e.g. `\"multi-column\"`, `\"table-likely\"`,\n * `\"dense-graphics\"`). Empty exactly when `isComplex` is false; new reasons\n * may be added over time.\n */\n reasons: string[];\n}\n\n// ---------------------------------------------------------------------------\n// LiteParse class\n// ---------------------------------------------------------------------------\n\nexport class LiteParse {\n private _native: LiteParseNative;\n private _config: LiteParseConfig;\n private _pool: WorkerPool | null = null;\n\n constructor(userConfig: Partial<LiteParseConfig> & PoolOptions = {}) {\n const nativeConfig: LiteParseNativeConfig = {\n ocrLanguage: userConfig.ocrLanguage,\n ocrEnabled: userConfig.ocrEnabled,\n ocrServerUrl: userConfig.ocrServerUrl,\n ocrServerHeaders: userConfig.ocrServerHeaders,\n tessdataPath: userConfig.tessdataPath,\n maxPages: userConfig.maxPages,\n targetPages: userConfig.targetPages,\n extractScreenshots: userConfig.extractScreenshots,\n continueOnPageError: userConfig.continueOnPageError,\n dpi: userConfig.dpi,\n outputFormat: userConfig.outputFormat,\n imageMode: userConfig.imageMode,\n extractImages: userConfig.extractImages,\n imageOutputDir: userConfig.imageOutputDir,\n extractLinks: userConfig.extractLinks,\n keepHeadersFooters: userConfig.keepHeadersFooters,\n extractAnnotations: userConfig.extractAnnotations,\n extractFormFields: userConfig.extractFormFields,\n extractStructureTree: userConfig.extractStructureTree,\n extractBlocks: userConfig.extractBlocks,\n extractXfaPackets: userConfig.extractXfaPackets,\n extractDocumentMetadata: userConfig.extractDocumentMetadata,\n extractContentBounds: userConfig.extractContentBounds,\n detectScreenshotRects: userConfig.detectScreenshotRects,\n renderFormFields: userConfig.renderFormFields,\n preserveVerySmallText: userConfig.preserveVerySmallText,\n password: userConfig.password,\n quiet: userConfig.quiet,\n numWorkers: userConfig.numWorkers,\n ocrFailureFatal: userConfig.ocrFailureFatal,\n ocrHedgeDelaysMs: userConfig.ocrHedgeDelaysMs,\n emitWordBoxes: userConfig.emitWordBoxes,\n extractTextMetadata: userConfig.extractTextMetadata,\n cropBox: userConfig.cropBox,\n skipDiagonalText: userConfig.skipDiagonalText,\n includeComplexity: userConfig.includeComplexity,\n extractVectorGraphics: userConfig.extractVectorGraphics,\n };\n\n this._native = new native.LiteParse(nativeConfig);\n\n if (\n userConfig.parseTimeoutMs !== undefined &&\n userConfig.poolSize === undefined\n ) {\n throw new Error(\n \"parseTimeoutMs requires poolSize\"\n );\n }\n if (userConfig.poolSize !== undefined) {\n this._pool = new WorkerPool(\n nativeConfig as unknown as Record<string, unknown>,\n userConfig.poolSize,\n userConfig.parseTimeoutMs,\n );\n }\n\n // Read back the resolved config from the native side\n const resolved = this._native.config;\n this._config = {\n ocrLanguage: resolved.ocrLanguage ?? \"eng\",\n ocrEnabled: resolved.ocrEnabled ?? true,\n ocrServerUrl: resolved.ocrServerUrl ?? undefined,\n ocrServerHeaders: resolved.ocrServerHeaders ?? undefined,\n tessdataPath: resolved.tessdataPath ?? undefined,\n maxPages: resolved.maxPages ?? 1000,\n targetPages: resolved.targetPages ?? undefined,\n extractScreenshots: resolved.extractScreenshots ?? false,\n continueOnPageError: resolved.continueOnPageError ?? false,\n dpi: resolved.dpi ?? 150,\n outputFormat: (resolved.outputFormat as OutputFormat) ?? \"json\",\n imageMode: (resolved.imageMode as ImageMode) ?? \"placeholder\",\n extractImages: resolved.extractImages ?? false,\n imageOutputDir: resolved.imageOutputDir ?? undefined,\n extractLinks: resolved.extractLinks ?? true,\n keepHeadersFooters: resolved.keepHeadersFooters ?? false,\n extractAnnotations: resolved.extractAnnotations ?? false,\n extractFormFields: resolved.extractFormFields ?? false,\n extractStructureTree: resolved.extractStructureTree ?? false,\n extractBlocks: resolved.extractBlocks ?? false,\n extractXfaPackets: resolved.extractXfaPackets ?? false,\n extractDocumentMetadata: resolved.extractDocumentMetadata ?? false,\n extractContentBounds: resolved.extractContentBounds ?? false,\n detectScreenshotRects: resolved.detectScreenshotRects ?? false,\n renderFormFields: resolved.renderFormFields ?? false,\n preserveVerySmallText: resolved.preserveVerySmallText ?? false,\n password: resolved.password ?? undefined,\n quiet: resolved.quiet ?? false,\n numWorkers: resolved.numWorkers ?? 1,\n ocrFailureFatal: resolved.ocrFailureFatal ?? true,\n ocrHedgeDelaysMs: resolved.ocrHedgeDelaysMs ?? [],\n emitWordBoxes: resolved.emitWordBoxes ?? false,\n extractTextMetadata: resolved.extractTextMetadata ?? false,\n cropBox: resolved.cropBox ?? undefined,\n skipDiagonalText: resolved.skipDiagonalText ?? false,\n includeComplexity: resolved.includeComplexity ?? false,\n extractVectorGraphics: resolved.extractVectorGraphics ?? false,\n };\n }\n\n async parse(input: LiteParseInput): Promise<ParseResult> {\n // Convert Uint8Array to Buffer for the native side\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n if (this._pool !== null) {\n const source =\n typeof nativeInput === \"string\"\n ? nativeInput\n : `<${nativeInput.byteLength} bytes>`;\n return this._pool.parse(nativeInput, source);\n }\n const result: NativeParseResult = await this._native.parse(nativeInput);\n return toParseResult(result);\n }\n\n /**\n * Resolves once every pool worker is initialized. No-op without `poolSize`.\n *\n * Optional: the first parse on each worker waits for its init anyway. Call\n * this before latency-sensitive traffic to avoid paying worker startup on\n * the first request.\n */\n async warmUp(): Promise<void> {\n if (this._pool !== null) await this._pool.warmUp();\n }\n\n /**\n * Shut down pool workers, if pool mode is enabled. Idempotent.\n *\n * Without `poolSize` this is a no-op. An idle pool never keeps the event\n * loop alive and workers exit when the parent does, so forgetting to call\n * this leaks nothing past process exit.\n */\n close(): void {\n if (this._pool !== null) this._pool.close();\n }\n\n /**\n * Parse a document in bounded-memory page batches of `batchSize` pages.\n *\n * Each yielded result is independent and becomes collectible once the caller\n * advances the iterator, so a consumer that does not retain batches never\n * holds more than one batch of pages in memory. A non-PDF source is\n * converted once when the iterator starts, not once per batch; its temporary\n * file is released when iteration ends — including an early `break` or\n * `throw`, which run the generator's cleanup.\n *\n * Cross-page passes see only the pages in their own batch, so repeated\n * header/footer removal and image deduplication are batch-local and the\n * output can differ from `parse()`. Prefer `parse()` unless the size of the\n * materialized result is the problem.\n *\n * As with any async generator, work starts on the first `next()` call, so\n * errors (an unreadable file, or a parser configured with `targetPages` —\n * ambiguous with generated batch ranges) surface on the first iteration\n * rather than when `parseBatches()` itself is called.\n */\n async *parseBatches(\n input: LiteParseInput,\n options: ParseBatchOptions = {},\n ): AsyncGenerator<ParseBatch> {\n const nativeInput = typeof input === \"string\" ? input : Buffer.from(input);\n const session = await this._native.openBatchSession(\n nativeInput,\n options.batchSize,\n );\n try {\n const totalPages = session.totalPages;\n\n for (;;) {\n const batch = await session.nextBatch();\n if (batch == null) {\n return;\n }\n yield {\n startPage: batch.startPage,\n endPage: batch.endPage,\n totalPages,\n result: toParseResult(batch.result),\n };\n }\n } finally {\n // Frees the session's converted-PDF temp file now instead of at GC —\n // this runs on normal exhaustion and when the consumer abandons the\n // loop early.\n await session.close();\n }\n }\n\n /**\n * Parse from pre-extracted pages, skipping PDFium text extraction. Runs only\n * grid projection + the configured output formatter, so the caller's own\n * text-extraction / font-recovery owns the text content. Synchronous: no\n * PDFium load and no OCR on this path.\n */\n parsePages(pages: PageInput[]): ParseResult {\n const nativePages: NativePageInput[] = pages.map((p) => ({\n pageNumber: p.pageNumber,\n pageWidth: p.pageWidth,\n pageHeight: p.pageHeight,\n textItems: p.textItems,\n graphics: p.graphics,\n }));\n const result = this._native.parsePages(nativePages);\n return toParseResult(result);\n }\n\n /**\n * Determine per-page complexity without running a full parse. Returns one\n * entry per page with signals and a `needsOcr` verdict — a cheap pre-OCR\n * check to decide whether a document needs advanced parsing.\n */\n async isComplex(input: LiteParseInput): Promise<PageComplexityStats[]> {\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n const stats: NativePageComplexityStats[] =\n await this._native.isComplex(nativeInput);\n return stats.map(toComplexity);\n }\n\n async screenshot(\n input: LiteParseInput,\n pageNumbers?: number[],\n ): Promise<ScreenshotResult[]> {\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n const results = await this._native.screenshot(\n nativeInput,\n pageNumbers ?? null,\n );\n return results.map((r) => ({\n pageNum: r.pageNum,\n width: r.width,\n height: r.height,\n imageBuffer: r.imageBuffer,\n isSolidFill: r.isSolidFill,\n rects: r.rects,\n }));\n }\n\n getConfig(): LiteParseConfig {\n return { ...this._config };\n }\n}\n\nfunction toComplexity(s: NativePageComplexityStats): PageComplexityStats {\n return {\n pageNumber: s.pageNumber,\n textLength: s.textLength,\n textCoverage: s.textCoverage,\n hasSubstantialImages: s.hasSubstantialImages,\n imageBlockCount: s.imageBlockCount,\n imageCoverage: s.imageCoverage,\n largestImageCoverage: s.largestImageCoverage,\n fullPageImage: s.fullPageImage,\n uncoveredVectorArea: s.uncoveredVectorArea ?? undefined,\n isGarbled: s.isGarbled,\n pageArea: s.pageArea,\n needsOcr: s.needsOcr,\n reasons: s.reasons,\n layout: s.layout\n ? {\n columnCount: s.layout.columnCount,\n ruledTableCount: s.layout.ruledTableCount,\n ruledTableCoverage: s.layout.ruledTableCoverage,\n textTableRunCount: s.layout.textTableRunCount,\n figureCount: s.layout.figureCount,\n figureCoverage: s.layout.figureCoverage,\n isComplex: s.layout.isComplex,\n reasons: s.layout.reasons,\n }\n : undefined,\n };\n}\n\n/** @internal Exported for pool-worker.ts only; not public API. */\nexport function toParseResult(result: NativeParseResult): ParseResult {\n return {\n totalPages: result.totalPages,\n pages: result.pages.map(toPage),\n pageErrors: result.pageErrors ?? [],\n text: result.text,\n images: (result.images ?? []).map(toImage),\n screenshots: (result.screenshots ?? []).map(toScreenshot),\n imageErrorCount: result.imageErrorCount ?? 0,\n formType: result.formType,\n creator: result.creator,\n producer: result.producer,\n docMeta: result.docMeta,\n xfaPackets: result.xfaPackets,\n };\n}\n\nfunction toPage(p: NativeParsedPage): ParsedPage {\n return {\n pageNum: p.pageNum,\n width: p.width,\n height: p.height,\n contentBounds: p.contentBounds,\n text: p.text,\n markdown: p.markdown,\n textItems: p.textItems.map(toTextItem),\n complexity: p.complexity ? toComplexity(p.complexity) : undefined,\n vectorGraphics: p.vectorGraphics ?? undefined,\n annotations: p.annotations,\n formFields: p.formFields?.map((field) => ({\n id: field.id,\n type: field.fieldType,\n page: field.page,\n annotationIndex: field.annotationIndex,\n widgetIndex: field.widgetIndex,\n objectNumber: field.objectNumber,\n name: field.name,\n alternateName: field.alternateName,\n value: field.value,\n exportValue: field.exportValue,\n fieldFlags: field.fieldFlags,\n controlCount: field.controlCount,\n controlIndex: field.controlIndex,\n checked: field.checked,\n rect: field.rect,\n options: field.options,\n selectedOptions: field.selectedOptions,\n })),\n structureTree: p.structureTree\n ? { roots: p.structureTree.roots.map(toStructureTreeElement) }\n : undefined,\n blocks: p.blocks as LayoutBlock[] | undefined,\n };\n}\n\nfunction toStructureTreeElement(\n element: NativeStructureTreeElement,\n): StructureTreeElement {\n const attributes: Record<string, StructureAttributeValue> = {};\n for (const attribute of element.attributes) {\n if (attribute.booleanValue !== undefined) {\n attributes[attribute.name] = attribute.booleanValue;\n } else if (attribute.numberValue !== undefined) {\n attributes[attribute.name] = attribute.numberValue;\n } else if (attribute.stringValue !== undefined) {\n attributes[attribute.name] = attribute.stringValue;\n }\n }\n return {\n type: element.elementType,\n id: element.id,\n actualText: element.actualText,\n altText: element.altText,\n title: element.title,\n attributes,\n markedContentIds: element.markedContentIds,\n children: element.children.map(toStructureTreeElement),\n annotations: element.annotations,\n };\n}\n\nfunction toImage(img: NativeExtractedImage): ExtractedImage {\n return {\n id: img.id,\n name: img.name,\n path: img.path,\n page: img.page,\n bbox: img.bbox,\n width: img.width,\n height: img.height,\n rotation: img.rotation,\n format: img.format,\n duplicateOf: img.duplicateOf,\n bytes: img.bytes,\n };\n}\n\nfunction toScreenshot(result: NativeScreenshotResult): ScreenshotResult {\n return {\n pageNum: result.pageNum,\n width: result.width,\n height: result.height,\n imageBuffer: result.imageBuffer,\n isSolidFill: result.isSolidFill,\n rects: result.rects,\n };\n}\n\nfunction toTextItem(item: NativeTextItem): TextItem {\n return {\n text: item.text,\n x: item.x,\n y: item.y,\n width: item.width,\n height: item.height,\n fontName: item.fontName,\n fontSize: item.fontSize,\n fontHeight: item.fontHeight,\n fontAscent: item.fontAscent,\n fontDescent: item.fontDescent,\n fontWeight: item.fontWeight,\n textWidth: item.textWidth,\n fontIsBuggy: item.fontIsBuggy,\n mcid: item.mcid,\n fillColor: item.fillColor,\n strokeColor: item.strokeColor,\n charCodes: item.charCodes,\n trailingSpaceGenerated: item.trailingSpaceGenerated,\n confidence: item.confidence,\n rotation: item.rotation,\n words: item.words,\n };\n}\n\n// ---------------------------------------------------------------------------\n// searchItems — standalone utility\n// ---------------------------------------------------------------------------\n\nexport interface SearchItemsOptions {\n phrase: string;\n caseSensitive?: boolean;\n}\n\nexport function searchItems(\n items: TextItem[],\n options: SearchItemsOptions,\n): TextItem[] {\n const nativeResults = native.searchItems(\n items,\n options.phrase,\n options.caseSensitive ?? false,\n );\n return nativeResults.map(toTextItem);\n}\n\nexport default LiteParse;\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// Native binary loader - tries platform-specific packages, falls back to local .node file.\n//\n// In production: the correct @llamaindex/liteparse-<platform> optional dependency\n// provides the .node binary. During development: `napi build` places it alongside package.json.\n\nimport { createRequire } from \"node:module\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst require = createRequire(import.meta.url);\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface NativeBindings {\n LiteParse: new (config?: LiteParseNativeConfig) => LiteParseNative;\n searchItems(\n items: NativeTextItem[],\n phrase: string,\n caseSensitive?: boolean | null,\n ): NativeTextItem[];\n}\n\nexport interface LiteParseNativeConfig {\n ocrLanguage?: string;\n ocrEnabled?: boolean;\n ocrServerUrl?: string;\n ocrServerHeaders?: Record<string, string>;\n tessdataPath?: string;\n maxPages?: number;\n targetPages?: string;\n extractScreenshots?: boolean;\n continueOnPageError?: boolean;\n dpi?: number;\n outputFormat?: string;\n imageMode?: string;\n extractImages?: boolean;\n imageOutputDir?: string;\n extractLinks?: boolean;\n keepHeadersFooters?: boolean;\n extractAnnotations?: boolean;\n extractFormFields?: boolean;\n extractStructureTree?: boolean;\n extractBlocks?: boolean;\n extractXfaPackets?: boolean;\n extractDocumentMetadata?: boolean;\n extractContentBounds?: boolean;\n detectScreenshotRects?: boolean;\n renderFormFields?: boolean;\n preserveVerySmallText?: boolean;\n password?: string;\n quiet?: boolean;\n numWorkers?: number;\n ocrFailureFatal?: boolean;\n ocrHedgeDelaysMs?: number[];\n emitWordBoxes?: boolean;\n extractTextMetadata?: boolean;\n cropBox?: NativeCropBox;\n skipDiagonalText?: boolean;\n includeComplexity?: boolean;\n extractVectorGraphics?: boolean;\n}\n\nexport interface NativeCropBox {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport interface NativeWordBox {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeTextItem {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n fontName?: string;\n fontSize?: number;\n fontHeight?: number;\n fontAscent?: number;\n fontDescent?: number;\n fontWeight?: number;\n textWidth?: number;\n fontIsBuggy?: boolean;\n mcid?: number;\n fillColor?: string;\n strokeColor?: string;\n charCodes?: number[];\n trailingSpaceGenerated?: boolean;\n confidence?: number;\n rotation?: number;\n words?: NativeWordBox[];\n}\n\nexport interface NativeGraphic {\n kind: string;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n hasFill?: boolean;\n hasStroke?: boolean;\n fillColor?: string;\n strokeColor?: string;\n lineWidth?: number;\n}\n\nexport interface NativePageInput {\n pageNumber: number;\n pageWidth: number;\n pageHeight: number;\n textItems: NativeTextItem[];\n graphics?: NativeGraphic[];\n}\n\nexport interface NativeRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeParsedPage {\n pageNum: number;\n width: number;\n height: number;\n contentBounds?: NativeRect;\n text: string;\n markdown: string;\n textItems: NativeTextItem[];\n complexity?: NativePageComplexityStats;\n vectorGraphics?: NativeVectorGraphics;\n annotations?: NativeDocumentAnnotation[];\n formFields?: NativeFormField[];\n structureTree?: NativeStructureTree;\n blocks?: NativeLayoutBlock[];\n}\n\nexport interface NativeLayoutCell {\n text: string;\n bbox?: NativeRect;\n}\n\nexport interface NativeLayoutBlock {\n kind: string;\n text?: string;\n level?: number;\n bold?: boolean;\n italic?: boolean;\n ordered?: boolean;\n marker?: string;\n lines?: string[];\n lang?: string;\n header?: NativeLayoutCell[];\n rows?: NativeLayoutCell[][];\n id?: string;\n format?: string;\n bbox?: NativeRect;\n}\n\nexport interface NativeStructureAttribute {\n name: string;\n booleanValue?: boolean;\n numberValue?: number;\n stringValue?: string;\n}\n\nexport interface NativeStructureTree {\n roots: NativeStructureTreeElement[];\n}\n\nexport interface NativeStructureTreeElement {\n elementType: string;\n id?: string;\n actualText?: string;\n altText?: string;\n title?: string;\n attributes: NativeStructureAttribute[];\n markedContentIds: number[];\n children: NativeStructureTreeElement[];\n annotations: NativeDocumentAnnotation[];\n}\n\nexport interface NativeVectorGraphics {\n shapes: Array<{\n bbox: { x: number; y: number; width: number; height: number };\n stroke: boolean;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n hasCurve: boolean;\n }>;\n lines: Array<{\n x1: number; y1: number; x2: number; y2: number;\n stroke: boolean; strokeWidth?: number; strokeColor?: string;\n fill: boolean; fillColor?: string;\n }>;\n}\n\nexport interface NativeAnnotationRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeDocumentAnnotation {\n subtype: string;\n contents?: string;\n created?: string;\n modified?: string;\n title?: string;\n rect?: NativeAnnotationRect;\n quadpointRects: NativeAnnotationRect[];\n uri?: string;\n}\n\nexport interface NativeFormField {\n id: string;\n fieldType: string;\n page: number;\n annotationIndex: number;\n widgetIndex: number;\n objectNumber?: number;\n name?: string;\n alternateName?: string;\n value?: string;\n exportValue?: string;\n fieldFlags: number;\n controlCount?: number;\n controlIndex?: number;\n checked?: boolean;\n rect?: NativeAnnotationRect;\n options: string[];\n selectedOptions: string[];\n}\n\nexport interface NativeExtractedImage {\n id: string;\n name: string;\n path?: string;\n page: number;\n bbox: { x: number; y: number; width: number; height: number };\n width: number;\n height: number;\n rotation: number;\n format: string;\n duplicateOf?: string;\n bytes: Buffer;\n}\n\nexport interface NativeParseResult {\n totalPages: number;\n pages: NativeParsedPage[];\n pageErrors: Array<{ pageNum: number; message: string }>;\n text: string;\n images: NativeExtractedImage[];\n screenshots: NativeScreenshotResult[];\n imageErrorCount: number;\n formType?: number;\n creator?: string;\n producer?: string;\n docMeta?: NativeDocumentMetadata;\n xfaPackets?: NativeXfaPacket[];\n}\n\nexport interface NativeDocumentMetadata {\n creationDate?: string;\n modDate?: string;\n fileVersion?: number;\n isEncrypted?: boolean;\n securityHandlerRevision?: number;\n permissions?: number;\n eofSectionCount?: number;\n startxrefCount?: number;\n trailerIdPairDiffers?: boolean;\n rawFileSize?: number;\n xmp?: string;\n xmpTruncated?: boolean;\n signatureCount?: number;\n signatureByteRangeReachesEof?: boolean;\n}\n\nexport interface NativeXfaPacket {\n index: number;\n name?: string;\n contentLength: number;\n content?: string;\n}\n\nexport interface NativeScreenshotResult {\n pageNum: number;\n width: number;\n height: number;\n imageBuffer: Buffer;\n isSolidFill: boolean;\n rects: NativeScreenshotRect[];\n}\n\nexport interface NativeScreenshotRect {\n x: number;\n y: number;\n width: number;\n height: number;\n color: string;\n isLine: boolean;\n}\n\nexport interface NativeLayoutComplexityStats {\n columnCount: number;\n ruledTableCount: number;\n ruledTableCoverage: number;\n textTableRunCount: number;\n figureCount: number;\n figureCoverage: number;\n isComplex: boolean;\n reasons: string[];\n}\n\nexport interface NativePageComplexityStats {\n pageNumber: number;\n textLength: number;\n textCoverage: number;\n hasSubstantialImages: boolean;\n imageBlockCount: number;\n imageCoverage: number;\n largestImageCoverage: number;\n fullPageImage: boolean;\n uncoveredVectorArea?: number;\n isGarbled: boolean;\n pageArea: number;\n needsOcr: boolean;\n reasons: string[];\n layout?: NativeLayoutComplexityStats;\n}\n\nexport interface NativeParseBatch {\n startPage: number;\n endPage: number;\n result: NativeParseResult;\n}\n\nexport interface NativeParseSession {\n nextBatch(): Promise<NativeParseBatch | null>;\n close(): Promise<void>;\n readonly totalPages: number;\n}\n\nexport interface LiteParseNative {\n parse(input: string | Buffer): Promise<NativeParseResult>;\n openBatchSession(\n input: string | Buffer,\n batchSize?: number,\n ): Promise<NativeParseSession>;\n parsePages(pages: NativePageInput[]): NativeParseResult;\n isComplex(input: string | Buffer): Promise<NativePageComplexityStats[]>;\n screenshot(\n input: string | Buffer,\n pageNumbers?: number[] | null,\n ): Promise<NativeScreenshotResult[]>;\n format(result: NativeParseResult): string;\n readonly config: LiteParseNativeConfig;\n}\n\nfunction loadNative(): NativeBindings {\n // Platform-specific package names generated by napi-rs\n const triples: Record<string, string> = {\n \"darwin-x64\": \"@llamaindex/liteparse-darwin-x64\",\n \"darwin-arm64\": \"@llamaindex/liteparse-darwin-arm64\",\n \"linux-x64-gnu\": \"@llamaindex/liteparse-linux-x64-gnu\",\n \"linux-x64-musl\": \"@llamaindex/liteparse-linux-x64-musl\",\n \"linux-arm64-gnu\": \"@llamaindex/liteparse-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"@llamaindex/liteparse-linux-arm64-musl\",\n \"win32-x64-msvc\": \"@llamaindex/liteparse-win32-x64-msvc\",\n \"win32-arm64-msvc\": \"@llamaindex/liteparse-win32-arm64-msvc\",\n };\n\n // Try platform-specific package first\n const platform = process.platform;\n const arch = process.arch;\n\n const candidates: string[] = [];\n if (platform === \"linux\") {\n // Try gnu first, then musl\n candidates.push(`${platform}-${arch}-gnu`);\n candidates.push(`${platform}-${arch}-musl`);\n } else if (platform === \"win32\") {\n candidates.push(`${platform}-${arch}-msvc`);\n } else {\n candidates.push(`${platform}-${arch}`);\n }\n\n for (const key of candidates) {\n const pkg = triples[key];\n if (pkg) {\n try {\n return require(pkg);\n } catch {\n // Not installed, try next\n }\n }\n }\n\n // Fallback: local .node file (development builds)\n // Try several paths since __dirname may be dist/ or dist/src/\n const searchDirs = [__dirname, join(__dirname, \"..\"), join(__dirname, \"..\", \"..\")];\n // Try full triple names (e.g. liteparse.linux-x64-gnu.node) and simple name\n const fileNames = [\n ...candidates.map((c) => `liteparse.${c}.node`),\n `liteparse.${platform}-${arch}.node`,\n \"liteparse.node\",\n ];\n for (const dir of searchDirs) {\n for (const fileName of fileNames) {\n try {\n return require(join(dir, fileName));\n } catch {\n // try next\n }\n }\n }\n\n throw new Error(\n `Failed to load native module for ${platform}-${arch}. ` +\n `Ensure the correct optional dependency is installed.`,\n );\n}\n\nexport const native = loadNative();\n","// Process-isolated worker pool for LiteParse.\n//\n// Not public API; use `new LiteParse({ poolSize, parseTimeoutMs })`.\n\nimport { fork, type ChildProcess } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ParseResult } from \"./lib.js\";\n\n/** A pooled parse exceeded `parseTimeoutMs` and its worker was killed.\n *\n * Only thrown in pool mode, where the deadline is enforced by killing the\n * worker process — the timed-out parse is guaranteed dead, not still running\n * in the background. `source` names the document (file path, or `<N bytes>`\n * for byte inputs); log it to identify the documents that stall your\n * pipeline.\n */\nexport class ParseTimeoutError extends Error {\n readonly source: string;\n readonly timeoutMs: number;\n\n constructor(message: string, source: string, timeoutMs: number) {\n super(message);\n this.name = \"ParseTimeoutError\";\n this.source = source;\n this.timeoutMs = timeoutMs;\n }\n}\n\nclass WorkerTimeout extends Error {}\nclass WorkerCrashed extends Error {}\n\ntype WorkerResponse =\n | { type: \"ready\" }\n | { type: \"initError\"; message: string }\n | { type: \"ok\"; result: ParseResult }\n | { type: \"err\"; message: string };\n\nconst WORKER_PATH = fileURLToPath(new URL(\"./pool-worker.js\", import.meta.url));\n\n/** IPC deserialization yields plain Uint8Arrays where the API promises\n * Buffers; rewrap in place (no copy). */\nfunction reviveBuffers(result: ParseResult): ParseResult {\n for (const image of result.images ?? []) {\n if (image.bytes && !Buffer.isBuffer(image.bytes)) {\n const b = image.bytes as Uint8Array;\n image.bytes = Buffer.from(b.buffer, b.byteOffset, b.byteLength);\n }\n }\n for (const shot of result.screenshots ?? []) {\n if (shot.imageBuffer && !Buffer.isBuffer(shot.imageBuffer)) {\n const b = shot.imageBuffer as Uint8Array;\n shot.imageBuffer = Buffer.from(b.buffer, b.byteOffset, b.byteLength);\n }\n }\n return result;\n}\n\nclass WorkerHandle {\n private child: ChildProcess;\n private readyPromise: Promise<void>;\n private pending: {\n resolve: (r: ParseResult) => void;\n reject: (e: Error) => void;\n } | null = null;\n private dead = false;\n\n constructor(config: Record<string, unknown>) {\n this.child = fork(WORKER_PATH, [], {\n serialization: \"advanced\",\n // stdout/stderr inherited: parse logs and crash traces stay visible.\n stdio: [\"ignore\", \"inherit\", \"inherit\", \"ipc\"],\n });\n\n let readyResolve!: () => void;\n let readyReject!: (e: Error) => void;\n this.readyPromise = new Promise<void>((resolve, reject) => {\n readyResolve = resolve;\n readyReject = reject;\n });\n // ready() may never be awaited if the worker is retired first.\n this.readyPromise.catch(() => {});\n\n this.child.on(\"message\", (msg: WorkerResponse) => {\n if (msg.type === \"ready\") {\n readyResolve();\n if (this.pending === null) this.idle();\n } else if (msg.type === \"initError\") {\n readyReject(new Error(msg.message));\n } else if (this.pending) {\n const { resolve, reject } = this.pending;\n this.pending = null;\n this.idle();\n if (msg.type === \"ok\") resolve(reviveBuffers(msg.result));\n else reject(new WorkerCrashed(msg.message));\n }\n });\n const onGone = (cause: string) => {\n this.dead = true;\n readyReject(new WorkerCrashed(cause));\n if (this.pending) {\n const { reject } = this.pending;\n this.pending = null;\n reject(new WorkerCrashed(cause));\n }\n };\n this.child.on(\"error\", (e) => onGone(e.message));\n this.child.on(\"exit\", (code, signal) =>\n onGone(`worker exited (code=${code}, signal=${signal})`),\n );\n\n // Stay ref'd until the init handshake arrives — a caller awaiting\n // warmUp()/ready() must keep the event loop alive. idle() runs on\n // \"ready\"; after that, an idle worker never holds the loop open.\n this.child.send({ type: \"init\", config });\n }\n\n /** Resolves when the worker's native parser is constructed. Init time\n * never counts toward the parse deadline — the deadline is a promise about\n * parsing, not about process startup. */\n ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /** An idle pool must not hold the parent's event loop open. */\n private idle(): void {\n this.child.unref();\n this.child.channel?.unref();\n }\n\n request(\n payload: string | Buffer,\n timeoutMs: number | undefined,\n ): Promise<ParseResult> {\n if (this.dead) {\n return Promise.reject(new WorkerCrashed(\"worker already exited\"));\n }\n this.child.ref();\n this.child.channel?.ref();\n return new Promise<ParseResult>((resolve, reject) => {\n let timer: NodeJS.Timeout | undefined;\n const settle =\n (fn: (v: never) => void) =>\n (value: never): void => {\n if (timer !== undefined) clearTimeout(timer);\n fn(value);\n };\n this.pending = {\n resolve: settle(resolve) as (r: ParseResult) => void,\n reject: settle(reject) as (e: Error) => void,\n };\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (this.pending) {\n const { reject: rejectPending } = this.pending;\n this.pending = null;\n rejectPending(new WorkerTimeout());\n }\n }, timeoutMs);\n }\n this.child.send({ type: \"parse\", payload });\n });\n }\n\n kill(): void {\n this.dead = true;\n this.child.kill(\"SIGKILL\");\n }\n\n /** Graceful shutdown; escalates to SIGKILL if the worker doesn't exit. */\n stop(): void {\n if (this.dead) return;\n this.dead = true;\n try {\n this.child.send({ type: \"stop\" });\n } catch {\n // channel already closed\n }\n const escalate = setTimeout(() => this.child.kill(\"SIGKILL\"), 5000);\n escalate.unref();\n this.child.once(\"exit\", () => clearTimeout(escalate));\n this.idle();\n }\n}\n\nexport class WorkerPool {\n private config: Record<string, unknown>;\n private timeoutMs: number | undefined;\n private workers = new Set<WorkerHandle>();\n private idle: WorkerHandle[] = [];\n private waiters: Array<{\n resolve: (w: WorkerHandle) => void;\n reject: (e: Error) => void;\n }> = [];\n private closed = false;\n\n constructor(\n config: Record<string, unknown>,\n poolSize: number,\n parseTimeoutMs?: number,\n ) {\n if (!Number.isInteger(poolSize) || poolSize < 1) {\n throw new Error(\"poolSize must be an integer >= 1\");\n }\n if (parseTimeoutMs !== undefined && !(parseTimeoutMs > 0)) {\n throw new Error(\"parseTimeoutMs must be > 0\");\n }\n this.config = config;\n this.timeoutMs = parseTimeoutMs;\n // Spawn eagerly: children load the addon and construct their native\n // parsers concurrently while the caller goes on with its own startup.\n for (let i = 0; i < poolSize; i++) {\n this.spawnWorker();\n }\n }\n\n private spawnWorker(): void {\n const worker = new WorkerHandle(this.config);\n this.workers.add(worker);\n this.release(worker);\n }\n\n private acquire(): Promise<WorkerHandle> {\n const worker = this.idle.pop();\n if (worker !== undefined) return Promise.resolve(worker);\n return new Promise((resolve, reject) =>\n this.waiters.push({ resolve, reject }),\n );\n }\n\n private release(worker: WorkerHandle): void {\n if (this.closed) {\n this.workers.delete(worker);\n worker.stop();\n return;\n }\n const waiter = this.waiters.shift();\n if (waiter !== undefined) waiter.resolve(worker);\n else this.idle.push(worker);\n }\n\n private retire(worker: WorkerHandle): void {\n worker.kill();\n this.workers.delete(worker);\n if (!this.closed) this.spawnWorker();\n }\n\n /** Run one parse on an idle worker.\n *\n * Waits for a free worker first; `parseTimeoutMs` bounds the parse itself,\n * not the wait. */\n async parse(payload: string | Buffer, source: string): Promise<ParseResult> {\n if (this.closed) throw new Error(\"parser pool is closed\");\n const worker = await this.acquire();\n try {\n await worker.ready();\n const result = await worker.request(payload, this.timeoutMs);\n this.release(worker);\n return result;\n } catch (e) {\n this.retire(worker);\n if (e instanceof WorkerTimeout) {\n throw new ParseTimeoutError(\n `parse of ${source} exceeded ${this.timeoutMs}ms; the worker process was killed`,\n source,\n this.timeoutMs!,\n );\n }\n if (e instanceof WorkerCrashed) {\n throw new Error(\n `liteparse worker process died while parsing ${source}: ${e.message}`,\n );\n }\n throw e;\n }\n }\n\n /** Resolves when every worker is initialized. Optional — the first parse\n * per worker waits for init anyway. */\n async warmUp(): Promise<void> {\n await Promise.all([...this.workers].map((w) => w.ready()));\n }\n\n /** Shut down all workers. Idempotent. Busy workers are stopped as their\n * in-flight parses finish. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n for (const waiter of this.waiters.splice(0)) {\n waiter.reject(new Error(\"parser pool is closed\"));\n }\n for (const worker of this.idle.splice(0)) {\n this.workers.delete(worker);\n worker.stop();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SA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IACV,MAAM,IAAI;AAAA,IACV,MAAM,IAAI;AAAA,IACV,MAAM,IAAI;AAAA,IACV,OAAO,IAAI;AAAA,IACX,QAAQ,IAAI;AAAA,IACZ,UAAU,IAAI;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ,aAAa,IAAI;AAAA,IACjB,OAAO,IAAI;AAAA,EACb;AACF;AAEA,SAAS,aAAa,QAAkD;AACtE,SAAO;AAAA,IACL,SAAS,OAAO;AAAA,IAChB,OAAO,OAAO;AAAA,IACd,QAAQ,OAAO;AAAA,IACf,aAAa,OAAO;AAAA,IACpB,aAAa,OAAO;AAAA,IACpB,OAAO,OAAO;AAAA,EAChB;AACF;AAEA,SAAS,WAAW,MAAgC;AAClD,SAAO;AAAA,IACL,MAAM,KAAK;AAAA,IACX,GAAG,KAAK;AAAA,IACR,GAAG,KAAK;AAAA,IACR,OAAO,KAAK;AAAA,IACZ,QAAQ,KAAK;AAAA,IACb,UAAU,KAAK;AAAA,IACf,UAAU,KAAK;AAAA,IACf,YAAY,KAAK;AAAA,IACjB,YAAY,KAAK;AAAA,IACjB,aAAa,KAAK;AAAA,IAClB,YAAY,KAAK;AAAA,IACjB,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,MAAM,KAAK;AAAA,IACX,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,WAAW,KAAK;AAAA,IAChB,wBAAwB,KAAK;AAAA,IAC7B,YAAY,KAAK;AAAA,IACjB,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,EACd;AACF;AAWO,SAAS,YACd,OACA,SACY;AACZ,QAAM,gBAAgB,OAAO;AAAA,IAC3B;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ,iBAAiB;AAAA,EAC3B;AACA,SAAO,cAAc,IAAI,UAAU;AACrC;AAEA,IAAO,cAAQ;","names":["require","import_node_url"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib.ts","../node_modules/tsup/assets/cjs_shims.js","../src/native.ts","../src/pool.ts"],"sourcesContent":["import {\n native,\n type LiteParseNative,\n type LiteParseNativeConfig,\n type NativeParseResult,\n type NativeParsedPage,\n type NativePageInput,\n type NativeTextItem,\n type NativeExtractedImage,\n type NativeStructureTreeElement,\n type NativePageComplexityStats,\n type NativeScreenshotResult,\n} from \"./native.js\";\nimport { WorkerPool, ParseTimeoutError } from \"./pool.js\";\n\nexport { ParseTimeoutError };\n\n// ---------------------------------------------------------------------------\n// Public types — match the existing TypeScript API\n// ---------------------------------------------------------------------------\n\nexport type LiteParseInput = string | Buffer | Uint8Array;\nexport type OutputFormat = \"json\" | \"text\" | \"markdown\";\nexport type ImageMode = \"off\" | \"placeholder\" | \"embed\";\n\n/** Options for pool mode: parsing in persistent, killable worker processes. */\nexport interface PoolOptions {\n /**\n * Route `parse()` through a pool of this many persistent worker processes.\n * Call `close()` when done (an idle pool never keeps the event loop alive, \n * but explicit shutdown frees workers immediately).\n */\n poolSize?: number;\n /**\n * Hard per-parse deadline in milliseconds. Requires `poolSize`.\n * The pool enforces the deadline by SIGKILLing the worker. On expiry\n * the parse rejects with {@link ParseTimeoutError} (naming the document)\n * and a fresh worker replaces the killed one.\n */\n parseTimeoutMs?: number;\n}\n\nexport interface LiteParseConfig {\n ocrLanguage: string;\n ocrEnabled: boolean;\n ocrServerUrl?: string;\n /** Extra HTTP headers sent with every request to `ocrServerUrl`. */\n ocrServerHeaders?: Record<string, string>;\n tessdataPath?: string;\n maxPages: number;\n targetPages?: string;\n /** Render parsed pages to PNG and return them in `ParseResult.screenshots`. */\n extractScreenshots: boolean;\n /** Continue after page-level extraction failures and collect `pageErrors`. */\n continueOnPageError: boolean;\n dpi: number;\n outputFormat: OutputFormat;\n /** How to surface raster images in markdown output (default: \"placeholder\"). */\n imageMode: ImageMode;\n /** Extract embedded image bytes and metadata (default: false). */\n extractImages: boolean;\n /** Directory where extracted embedded image files are written. Requires `extractImages`. */\n imageOutputDir?: string;\n /** Render hyperlink annotations as `[text](url)` in markdown output (default: true). */\n extractLinks: boolean;\n /** Keep running headers/footers in markdown output instead of stripping repeated page-band lines and page chrome (default: false). */\n keepHeadersFooters: boolean;\n /** Extract all PDF annotations into each parsed page (default: false). */\n extractAnnotations: boolean;\n /** Extract AcroForm widget fields and values (default: false). */\n extractFormFields: boolean;\n /** Extract the tagged-PDF logical structure tree (default: false). */\n extractStructureTree: boolean;\n /**\n * Emit each page's classified layout blocks with bounding boxes\n * (default: false). This is the same decomposition the Markdown renderer\n * consumes, exposed as data; enabling it never changes the rendered Markdown.\n */\n extractBlocks: boolean;\n /** Extract raw XFA packets (name + XML content) into `ParseResult.xfaPackets` (default: false). */\n extractXfaPackets: boolean;\n /**\n * Collect document provenance metadata into `result.docMeta`. Default\n * false: Absent for inputs converted from a non-PDF format.\n */\n extractDocumentMetadata: boolean;\n /** Emit each page's `contentBounds` (union bbox of top-level content objects) (default: false). */\n extractContentBounds: boolean;\n /** Detect solid rectangles/lines in rendered page screenshots (default: false). */\n detectScreenshotRects: boolean;\n /** Draw AcroForm field appearances into rendered rasters (screenshots and OCR inputs; runs document open/JS actions; default: false). */\n renderFormFields: boolean;\n preserveVerySmallText: boolean;\n password?: string;\n quiet: boolean;\n numWorkers: number;\n /**\n * Whether a systemic OCR failure (every OCR task failed and at least one was\n * a text-sparse page) aborts the whole parse (default: true). Set false to\n * keep already-recovered native text and return partial results instead of\n * rejecting — for callers that prefer a degraded document over a hard failure.\n */\n ocrFailureFatal: boolean;\n /**\n * OCR request-hedging schedule (ms). Empty (default) = no hedging. Multiple\n * delays (e.g. `[0, 5000, 10000, 15000, 20000]`) fire duplicate requests per\n * OCR attempt and take the first success — lower tail latency on a slow/stuck\n * OCR pod, at the cost of extra OCR-server load. HTTP OCR engine only.\n */\n ocrHedgeDelaysMs: number[];\n /**\n * Emit per-word sub-boxes on each text item ({@link TextItem.words}).\n * Default false. Word boxes roughly double the text-item payload (size + napi\n * marshalling), so enable only when doing word-level bbox attribution.\n */\n emitWordBoxes: boolean;\n /** Include rich PDF text metadata on returned text items. Default false. */\n extractTextMetadata?: boolean;\n /**\n * Restrict output to a page sub-region. Each field is the fraction of the\n * page cropped away from that side (top-left origin), so `{ left: 0.5 }`\n * discards the left half. A text item survives only when it lies entirely\n * inside the remaining rectangle. Undefined (default) keeps the whole page.\n * Applied after OCR merge, so OCR text outside the region is dropped too.\n */\n cropBox?: CropBox;\n /**\n * Drop diagonal text — items whose rotation is more than 2° off the nearest\n * right angle (0/90/180/270). Default false. Use to exclude rotated\n * watermarks/stamps from the output.\n */\n skipDiagonalText: boolean;\n /**\n * Per-page orientation corrections from an upstream orientation classifier\n * (one that saw the rendered page). Each entry names a 1-based page and the\n * clockwise angle (0/90/180/270) by which that page's content *appears*\n * rotated in its viewport; LiteParse counter-rotates the page before\n * extraction, so text coordinates, reading order, page dimensions and OCR\n * rasters all come out upright. Applied on top of the PDF's own `/Rotate`.\n * Pages not listed, or past the end of the document, are left unchanged.\n * Default: none.\n */\n pageOrientationCorrections?: PageOrientationCorrection[];\n /**\n * Compute per-page complexity signals during {@link LiteParse.parse} and\n * attach them to each page as {@link ParsedPage.complexity} (the same signals\n * {@link LiteParse.isComplex} returns). Default false; enabling it runs an\n * extra vector-text detection pass.\n */\n includeComplexity: boolean;\n /** Expose page-scoped vector shapes and merged H/V line segments. Default false. */\n extractVectorGraphics: boolean;\n}\n\n/**\n * A page sub-region expressed as the fraction cropped from each side\n * (top-left origin, each value in `[0, 1]`).\n */\nexport interface CropBox {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\n/**\n * One page's orientation correction (see\n * {@link LiteParseConfig.pageOrientationCorrections}).\n */\nexport interface PageOrientationCorrection {\n /** 1-based document page number. */\n page: number;\n /** Clockwise degrees the content appears rotated: 0, 90, 180 or 270. */\n angle: 0 | 90 | 180 | 270;\n}\n\n/**\n * One word's bounding box within a {@link TextItem}, in the same viewport space\n * (top-left origin, 72 DPI). `text` excludes inter-word spaces.\n */\nexport interface WordBox {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface TextItem {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n fontName?: string;\n fontSize?: number;\n /** Font size after applying the text matrix's vertical scale. */\n fontHeight?: number;\n fontAscent?: number;\n fontDescent?: number;\n fontWeight?: number;\n /** Sum of source glyph widths in points. */\n textWidth?: number;\n fontIsBuggy?: boolean;\n /** Marked-content ID from the PDF structure tree. */\n mcid?: number;\n /** Fill color as an eight-character ARGB hex string. */\n fillColor?: string;\n /** Stroke color as an eight-character ARGB hex string. */\n strokeColor?: string;\n /** Raw PDF content-stream character codes for the source glyphs. */\n charCodes?: number[];\n /** True when the trailing source space was synthesized by PDFium. */\n trailingSpaceGenerated?: boolean;\n /** OCR confidence score (0.0-1.0). Undefined for native PDF text. */\n confidence?: number;\n /** Rotation in degrees (viewport space). Defaults to 0 when omitted. */\n rotation?: number;\n /**\n * Per-word sub-boxes within this item. A text item groups several words\n * together (breaking only at line/column boundaries), so this carries the\n * finer word-level geometry for bbox attribution. Empty/undefined for items\n * with no word split (e.g. OCR-sourced or single-token items).\n */\n words?: WordBox[];\n}\n\n/**\n * A vector-graphic primitive supplied to {@link LiteParse.parsePages}. `kind`\n * selects the variant: `\"stroke\"` (uses `x1/y1/x2/y2`) or `\"rect\"` (uses\n * `x/y/width/height`, top-left origin). Coordinates are viewport space (72 DPI),\n * matching the text items. `hasFill`/`hasStroke` carry the paint intent even\n * when the color is unknown, so ruled-table edge detection still treats a\n * colorless stroked rect as stroked.\n */\nexport interface Graphic {\n kind: \"stroke\" | \"rect\";\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n hasFill?: boolean;\n hasStroke?: boolean;\n fillColor?: string;\n strokeColor?: string;\n lineWidth?: number;\n}\n\n/**\n * A page of pre-extracted text supplied to {@link LiteParse.parsePages}.\n * Coordinates are viewport space (top-left origin, 72 DPI). `graphics` is\n * optional; when supplied it enables ruled-table and horizontal-rule detection.\n */\nexport interface PageInput {\n pageNumber: number;\n pageWidth: number;\n pageHeight: number;\n textItems: TextItem[];\n graphics?: Graphic[];\n}\n\nexport interface Rect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface ParsedPage {\n pageNum: number;\n /**\n * The document's `/PageLabels` label for this page (\"iv\", \"A-1\"), absent\n * when the PDF defines none. This is what a reader displays for the page\n * and is not always its position, so fall back to `pageNum` when absent.\n */\n pageLabel?: string;\n width: number;\n height: number;\n /**\n * Union bbox of the page's top-level content objects in viewport coords\n * (visible content extent). Absent for empty pages.\n */\n /** Present only when `extractContentBounds` is enabled. */\n contentBounds?: Rect;\n text: string;\n markdown: string;\n textItems: TextItem[];\n /**\n * Per-page complexity signals (the same {@link LiteParse.isComplex} returns).\n * Present only when parsing with `includeComplexity: true`; `undefined`\n * otherwise.\n */\n complexity?: PageComplexityStats;\n /** Present only when parsing with `extractVectorGraphics: true`. */\n vectorGraphics?: VectorGraphics;\n /** Present only when `extractAnnotations` is enabled. */\n annotations?: DocumentAnnotation[];\n /** Present only when `extractFormFields` is enabled. */\n formFields?: FormField[];\n /** Present only when `extractStructureTree` is enabled. */\n structureTree?: StructureTree;\n /**\n * Classified layout blocks in reading order — the same blocks, in the same\n * order, the page's Markdown is built from. Present only when\n * `extractBlocks` is enabled.\n */\n blocks?: LayoutBlock[];\n}\n\n/** One table cell: its text and the region of the page it was read from. */\nexport interface LayoutCell {\n text: string;\n /**\n * Absent for cells with no ink behind them — padding inserted to square off\n * a ragged grid, or halves of a merged run split at an estimated position.\n */\n bbox?: Rect;\n}\n\n/** A classified block of page content, discriminated by `kind`. */\nexport interface LayoutBlock {\n kind:\n | \"heading\"\n | \"paragraph\"\n | \"list_item\"\n | \"code\"\n | \"table\"\n | \"grid_fallback\"\n | \"rule\"\n | \"figure\";\n /** Rendered text for `heading`, `paragraph`, and `list_item`. */\n text?: string;\n /** Heading level (1-6), or list nesting depth for `list_item`. */\n level?: number;\n bold?: boolean;\n italic?: boolean;\n /** `list_item` only. `marker` is the marker as it appeared on the page. */\n ordered?: boolean;\n marker?: string;\n /** Verbatim source lines for `code` and `grid_fallback`. */\n lines?: string[];\n /** Best-effort language hint for `code`. */\n lang?: string;\n /** `table` only. */\n header?: LayoutCell[];\n rows?: LayoutCell[][];\n /** `figure` only, matching the `img_{id}.{format}` Markdown target. */\n id?: string;\n format?: string;\n /**\n * Region this block occupies, in the same top-left 72-DPI viewport space as\n * `textItems`. The union of every source line that fed the block.\n */\n bbox?: Rect;\n}\n\nexport type StructureAttributeValue = boolean | number | string;\n\nexport interface StructureTree {\n roots: StructureTreeElement[];\n}\n\nexport interface StructureTreeElement {\n type: string;\n id?: string;\n actualText?: string;\n altText?: string;\n title?: string;\n attributes: Record<string, StructureAttributeValue>;\n markedContentIds: number[];\n children: StructureTreeElement[];\n annotations: DocumentAnnotation[];\n}\n\nexport interface VectorGraphics {\n shapes: VectorShape[];\n lines: VectorLine[];\n}\n\nexport interface VectorShape {\n bbox: { x: number; y: number; width: number; height: number };\n stroke: boolean;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n hasCurve: boolean;\n}\n\nexport interface VectorLine {\n x1: number; y1: number; x2: number; y2: number;\n stroke: boolean;\n strokeWidth?: number;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n}\n\nexport interface AnnotationRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface DocumentAnnotation {\n subtype: string;\n contents?: string;\n created?: string;\n modified?: string;\n title?: string;\n rect?: AnnotationRect;\n quadpointRects: AnnotationRect[];\n uri?: string;\n}\n\nexport interface FormField {\n id: string;\n type: string;\n page: number;\n annotationIndex: number;\n widgetIndex: number;\n objectNumber?: number;\n name?: string;\n alternateName?: string;\n value?: string;\n exportValue?: string;\n fieldFlags: number;\n controlCount?: number;\n controlIndex?: number;\n checked?: boolean;\n rect?: AnnotationRect;\n options: string[];\n selectedOptions: string[];\n}\n\nexport interface ExtractedImage {\n /** Reference id used in the markdown output (e.g. `` → `\"p1_1\"`). */\n id: string;\n /** File name used when `imageOutputDir` is configured. */\n name: string;\n /** Written file path, absent for in-memory-only extraction. */\n path?: string;\n page: number;\n /** Placement on the page in viewport coordinates (top-left origin, 72 DPI). */\n bbox: { x: number; y: number; width: number; height: number };\n /** Intrinsic pixel dimensions of the image resource. */\n width: number;\n height: number;\n /** Clockwise page-object rotation in degrees. */\n rotation: number;\n format: string;\n /** First occurrence with identical encoded source data, when duplicated. */\n duplicateOf?: string;\n bytes: Buffer;\n}\n\nexport interface ParseResult {\n /** Total source-document pages before `targetPages` or `maxPages` filtering. */\n totalPages: number;\n pages: ParsedPage[];\n /** Page-level PDFium extraction failures when tolerance is enabled. */\n pageErrors: Array<{ pageNum: number; message: string }>;\n text: string;\n /** Populated only when `extractImages` is true. */\n images: ExtractedImage[];\n /** PNG screenshots of parsed pages when `extractScreenshots` is enabled. */\n screenshots: ScreenshotResult[];\n /** Embedded image objects that PDFium could not render or encode. */\n imageErrorCount: number;\n /** PDFium form type, present only when `extractFormFields` is enabled. */\n formType?: number;\n /** The document's `/Info` `Creator` entry, when present. */\n creator?: string;\n /** The document's `/Info` `Producer` entry, when present. */\n producer?: string;\n /**\n * Document-level provenance metadata from PDFium and the source PDF.\n * Present only when `extractDocumentMetadata` is enabled and the input was\n * a real PDF (not converted from DOCX/XLSX/an image).\n */\n docMeta?: DocumentMetadata;\n /** Raw XFA packets; present only when `extractXfaPackets` is enabled. */\n xfaPackets?: XfaPacket[];\n}\n\nexport interface ParseBatchOptions {\n /** Pages materialized in one batch. Default: 25. */\n batchSize?: number;\n}\n\nexport interface ParseBatch {\n /** First source page in this batch (1-indexed). */\n startPage: number;\n /** Last source page in this batch (1-indexed, inclusive). */\n endPage: number;\n /** Total source-document pages, before the parser's `maxPages` cap. */\n totalPages: number;\n result: ParseResult;\n}\n\n/** Provenance and tamper-analysis facts extracted from the source PDF. */\nexport interface DocumentMetadata {\n creationDate?: string;\n modDate?: string;\n /** Encoded PDF version (`14` means PDF 1.4). */\n fileVersion?: number;\n isEncrypted?: boolean;\n securityHandlerRevision?: number;\n permissions?: number;\n eofSectionCount?: number;\n startxrefCount?: number;\n trailerIdPairDiffers?: boolean;\n rawFileSize?: number;\n /**\n * The document catalog's `/Metadata` XMP packet, capped at 64 KiB. Absent\n * when the document has none, when it is too large to resolve cheaply, or\n * in WASM builds.\n */\n xmp?: string;\n /** True when the catalog's XMP stream exceeded the 64 KiB cap. */\n xmpTruncated?: boolean;\n signatureCount?: number;\n /** False when bytes were appended after a readable signature byte range. */\n signatureByteRangeReachesEof?: boolean;\n}\n\n/** One raw packet from an XFA form document's `/XFA` array. */\nexport interface XfaPacket {\n index: number;\n name?: string;\n contentLength: number;\n /** Packet content (usually XML), lossily decoded as UTF-8. */\n content?: string;\n}\n\nexport interface ScreenshotResult {\n pageNum: number;\n width: number;\n height: number;\n imageBuffer: Buffer;\n /** True when every pixel has the same color (blank page after render). */\n isSolidFill: boolean;\n /** Solid rectangles/lines detected in the raster (viewport coords). Populated only with `detectScreenshotRects`. */\n rects: ScreenshotRect[];\n}\n\n/** One solid rectangle (or line) detected in a rendered page bitmap. */\nexport interface ScreenshotRect {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Fill color as ARGB hex string (e.g. \"ff1a2b3c\"). */\n color: string;\n /** True when the region is a solid line rather than a filled area. */\n isLine: boolean;\n}\n\n/**\n * Per-page complexity signals from {@link LiteParse.isComplex}, used to decide\n * whether a document needs OCR or other advanced parsing.\n */\nexport interface PageComplexityStats {\n pageNumber: number;\n textLength: number;\n /** Fraction of the page area covered by native text (0–1). */\n textCoverage: number;\n hasSubstantialImages: boolean;\n /**\n * Number of counted raster images — inline figures only; full-page\n * backgrounds are excluded (see {@link fullPageImage}).\n */\n imageBlockCount: number;\n /**\n * Summed image-bbox area over page area, clamped to 1. Counts inline figures\n * only: a full-page scan raster contributes 0 here — check\n * {@link fullPageImage} for that.\n */\n imageCoverage: number;\n /**\n * Largest single *counted* image's area over page area, clamped to 1. Same\n * exclusion as {@link imageCoverage}: a full-page raster contributes 0.\n */\n largestImageCoverage: number;\n /**\n * A single raster covers ≥90% of the page. Full-page backgrounds are excluded\n * from the image coverage fields, so this is the only signal that tells a scan\n * apart from a blank page — both otherwise report no text and no images.\n */\n fullPageImage: boolean;\n /**\n * Filled vector-outline area not covered by native text, in pt². `undefined`\n * when a cheaper signal already decided the page, so this walk was skipped.\n */\n uncoveredVectorArea?: number;\n isGarbled: boolean;\n pageArea: number;\n /** Verdict: whether this page needs more than the cheap text-only path. */\n needsOcr: boolean;\n /**\n * Every reason the page was flagged (e.g. `\"scanned\"`, `\"sparse-text\"`,\n * `\"garbled\"`). Empty exactly when `needsOcr` is false. This is the value to\n * route on; new reasons may be added over time.\n */\n reasons: string[];\n /**\n * Layout-difficulty signals (columns, tables, dense graphics). Orthogonal to\n * `needsOcr`: none of these imply OCR — they signal that the text-only path\n * may mangle reading order or structure. Present in `isComplex()` results\n * and `includeComplexity` parses.\n */\n layout?: LayoutComplexityStats;\n}\n\n/**\n * Layout-difficulty signals for one page, computed from the real\n * grid-projection pass.\n */\nexport interface LayoutComplexityStats {\n /** Side-by-side text columns found by the layout pass (1 = single column). */\n columnCount: number;\n /** Ruled-table grids detected on the page. */\n ruledTableCount: number;\n /** Combined ruled-table area over page area, clamped to 1. */\n ruledTableCoverage: number;\n /**\n * Borderless table runs found by track-aligned text detection (description\n * lists excluded). Ruled tables can appear here too — don't sum with\n * `ruledTableCount`; the two discriminate ruled from borderless.\n */\n textTableRunCount: number;\n /** Figure regions clustered from vector graphics. */\n figureCount: number;\n /** Combined figure area over page area, clamped to 1. */\n figureCoverage: number;\n /** Verdict: whether any layout reason fired. */\n isComplex: boolean;\n /**\n * Every layout reason (e.g. `\"multi-column\"`, `\"table-likely\"`,\n * `\"dense-graphics\"`). Empty exactly when `isComplex` is false; new reasons\n * may be added over time.\n */\n reasons: string[];\n}\n\n// ---------------------------------------------------------------------------\n// LiteParse class\n// ---------------------------------------------------------------------------\n\nexport class LiteParse {\n private _native: LiteParseNative;\n private _config: LiteParseConfig;\n private _pool: WorkerPool | null = null;\n\n constructor(userConfig: Partial<LiteParseConfig> & PoolOptions = {}) {\n const nativeConfig: LiteParseNativeConfig = {\n ocrLanguage: userConfig.ocrLanguage,\n ocrEnabled: userConfig.ocrEnabled,\n ocrServerUrl: userConfig.ocrServerUrl,\n ocrServerHeaders: userConfig.ocrServerHeaders,\n tessdataPath: userConfig.tessdataPath,\n maxPages: userConfig.maxPages,\n targetPages: userConfig.targetPages,\n extractScreenshots: userConfig.extractScreenshots,\n continueOnPageError: userConfig.continueOnPageError,\n dpi: userConfig.dpi,\n outputFormat: userConfig.outputFormat,\n imageMode: userConfig.imageMode,\n extractImages: userConfig.extractImages,\n imageOutputDir: userConfig.imageOutputDir,\n extractLinks: userConfig.extractLinks,\n keepHeadersFooters: userConfig.keepHeadersFooters,\n extractAnnotations: userConfig.extractAnnotations,\n extractFormFields: userConfig.extractFormFields,\n extractStructureTree: userConfig.extractStructureTree,\n extractBlocks: userConfig.extractBlocks,\n extractXfaPackets: userConfig.extractXfaPackets,\n extractDocumentMetadata: userConfig.extractDocumentMetadata,\n extractContentBounds: userConfig.extractContentBounds,\n detectScreenshotRects: userConfig.detectScreenshotRects,\n renderFormFields: userConfig.renderFormFields,\n preserveVerySmallText: userConfig.preserveVerySmallText,\n password: userConfig.password,\n quiet: userConfig.quiet,\n numWorkers: userConfig.numWorkers,\n ocrFailureFatal: userConfig.ocrFailureFatal,\n ocrHedgeDelaysMs: userConfig.ocrHedgeDelaysMs,\n emitWordBoxes: userConfig.emitWordBoxes,\n extractTextMetadata: userConfig.extractTextMetadata,\n cropBox: userConfig.cropBox,\n skipDiagonalText: userConfig.skipDiagonalText,\n pageOrientationCorrections: userConfig.pageOrientationCorrections,\n includeComplexity: userConfig.includeComplexity,\n extractVectorGraphics: userConfig.extractVectorGraphics,\n };\n\n this._native = new native.LiteParse(nativeConfig);\n\n if (\n userConfig.parseTimeoutMs !== undefined &&\n userConfig.poolSize === undefined\n ) {\n throw new Error(\n \"parseTimeoutMs requires poolSize\"\n );\n }\n if (userConfig.poolSize !== undefined) {\n this._pool = new WorkerPool(\n nativeConfig as unknown as Record<string, unknown>,\n userConfig.poolSize,\n userConfig.parseTimeoutMs,\n );\n }\n\n // Read back the resolved config from the native side\n const resolved = this._native.config;\n this._config = {\n ocrLanguage: resolved.ocrLanguage ?? \"eng\",\n ocrEnabled: resolved.ocrEnabled ?? true,\n ocrServerUrl: resolved.ocrServerUrl ?? undefined,\n ocrServerHeaders: resolved.ocrServerHeaders ?? undefined,\n tessdataPath: resolved.tessdataPath ?? undefined,\n maxPages: resolved.maxPages ?? 1000,\n targetPages: resolved.targetPages ?? undefined,\n extractScreenshots: resolved.extractScreenshots ?? false,\n continueOnPageError: resolved.continueOnPageError ?? false,\n dpi: resolved.dpi ?? 150,\n outputFormat: (resolved.outputFormat as OutputFormat) ?? \"json\",\n imageMode: (resolved.imageMode as ImageMode) ?? \"placeholder\",\n extractImages: resolved.extractImages ?? false,\n imageOutputDir: resolved.imageOutputDir ?? undefined,\n extractLinks: resolved.extractLinks ?? true,\n keepHeadersFooters: resolved.keepHeadersFooters ?? false,\n extractAnnotations: resolved.extractAnnotations ?? false,\n extractFormFields: resolved.extractFormFields ?? false,\n extractStructureTree: resolved.extractStructureTree ?? false,\n extractBlocks: resolved.extractBlocks ?? false,\n extractXfaPackets: resolved.extractXfaPackets ?? false,\n extractDocumentMetadata: resolved.extractDocumentMetadata ?? false,\n extractContentBounds: resolved.extractContentBounds ?? false,\n detectScreenshotRects: resolved.detectScreenshotRects ?? false,\n renderFormFields: resolved.renderFormFields ?? false,\n preserveVerySmallText: resolved.preserveVerySmallText ?? false,\n password: resolved.password ?? undefined,\n quiet: resolved.quiet ?? false,\n numWorkers: resolved.numWorkers ?? 1,\n ocrFailureFatal: resolved.ocrFailureFatal ?? true,\n ocrHedgeDelaysMs: resolved.ocrHedgeDelaysMs ?? [],\n emitWordBoxes: resolved.emitWordBoxes ?? false,\n extractTextMetadata: resolved.extractTextMetadata ?? false,\n cropBox: resolved.cropBox ?? undefined,\n skipDiagonalText: resolved.skipDiagonalText ?? false,\n pageOrientationCorrections:\n (resolved.pageOrientationCorrections as PageOrientationCorrection[] | undefined) ?? undefined,\n includeComplexity: resolved.includeComplexity ?? false,\n extractVectorGraphics: resolved.extractVectorGraphics ?? false,\n };\n }\n\n async parse(input: LiteParseInput): Promise<ParseResult> {\n // Convert Uint8Array to Buffer for the native side\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n if (this._pool !== null) {\n const source =\n typeof nativeInput === \"string\"\n ? nativeInput\n : `<${nativeInput.byteLength} bytes>`;\n return this._pool.parse(nativeInput, source);\n }\n const result: NativeParseResult = await this._native.parse(nativeInput);\n return toParseResult(result);\n }\n\n /**\n * Resolves once every pool worker is initialized. No-op without `poolSize`.\n *\n * Optional: the first parse on each worker waits for its init anyway. Call\n * this before latency-sensitive traffic to avoid paying worker startup on\n * the first request.\n */\n async warmUp(): Promise<void> {\n if (this._pool !== null) await this._pool.warmUp();\n }\n\n /**\n * Shut down pool workers, if pool mode is enabled. Idempotent.\n *\n * Without `poolSize` this is a no-op. An idle pool never keeps the event\n * loop alive and workers exit when the parent does, so forgetting to call\n * this leaks nothing past process exit.\n */\n close(): void {\n if (this._pool !== null) this._pool.close();\n }\n\n /**\n * Parse a document in bounded-memory page batches of `batchSize` pages.\n *\n * Each yielded result is independent and becomes collectible once the caller\n * advances the iterator, so a consumer that does not retain batches never\n * holds more than one batch of pages in memory. A non-PDF source is\n * converted once when the iterator starts, not once per batch; its temporary\n * file is released when iteration ends — including an early `break` or\n * `throw`, which run the generator's cleanup.\n *\n * Cross-page passes see only the pages in their own batch, so repeated\n * header/footer removal and image deduplication are batch-local and the\n * output can differ from `parse()`. Prefer `parse()` unless the size of the\n * materialized result is the problem.\n *\n * As with any async generator, work starts on the first `next()` call, so\n * errors (an unreadable file, or a parser configured with `targetPages` —\n * ambiguous with generated batch ranges) surface on the first iteration\n * rather than when `parseBatches()` itself is called.\n */\n async *parseBatches(\n input: LiteParseInput,\n options: ParseBatchOptions = {},\n ): AsyncGenerator<ParseBatch> {\n const nativeInput = typeof input === \"string\" ? input : Buffer.from(input);\n const session = await this._native.openBatchSession(\n nativeInput,\n options.batchSize,\n );\n try {\n const totalPages = session.totalPages;\n\n for (;;) {\n const batch = await session.nextBatch();\n if (batch == null) {\n return;\n }\n yield {\n startPage: batch.startPage,\n endPage: batch.endPage,\n totalPages,\n result: toParseResult(batch.result),\n };\n }\n } finally {\n // Frees the session's converted-PDF temp file now instead of at GC —\n // this runs on normal exhaustion and when the consumer abandons the\n // loop early.\n await session.close();\n }\n }\n\n /**\n * Parse from pre-extracted pages, skipping PDFium text extraction. Runs only\n * grid projection + the configured output formatter, so the caller's own\n * text-extraction / font-recovery owns the text content. Synchronous: no\n * PDFium load and no OCR on this path.\n */\n parsePages(pages: PageInput[]): ParseResult {\n const nativePages: NativePageInput[] = pages.map((p) => ({\n pageNumber: p.pageNumber,\n pageWidth: p.pageWidth,\n pageHeight: p.pageHeight,\n textItems: p.textItems,\n graphics: p.graphics,\n }));\n const result = this._native.parsePages(nativePages);\n return toParseResult(result);\n }\n\n /**\n * Determine per-page complexity without running a full parse. Returns one\n * entry per page with signals and a `needsOcr` verdict — a cheap pre-OCR\n * check to decide whether a document needs advanced parsing.\n */\n async isComplex(input: LiteParseInput): Promise<PageComplexityStats[]> {\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n const stats: NativePageComplexityStats[] =\n await this._native.isComplex(nativeInput);\n return stats.map(toComplexity);\n }\n\n async screenshot(\n input: LiteParseInput,\n pageNumbers?: number[],\n ): Promise<ScreenshotResult[]> {\n const nativeInput =\n typeof input === \"string\" ? input : Buffer.from(input);\n const results = await this._native.screenshot(\n nativeInput,\n pageNumbers ?? null,\n );\n return results.map((r) => ({\n pageNum: r.pageNum,\n width: r.width,\n height: r.height,\n imageBuffer: r.imageBuffer,\n isSolidFill: r.isSolidFill,\n rects: r.rects,\n }));\n }\n\n getConfig(): LiteParseConfig {\n return { ...this._config };\n }\n}\n\nfunction toComplexity(s: NativePageComplexityStats): PageComplexityStats {\n return {\n pageNumber: s.pageNumber,\n textLength: s.textLength,\n textCoverage: s.textCoverage,\n hasSubstantialImages: s.hasSubstantialImages,\n imageBlockCount: s.imageBlockCount,\n imageCoverage: s.imageCoverage,\n largestImageCoverage: s.largestImageCoverage,\n fullPageImage: s.fullPageImage,\n uncoveredVectorArea: s.uncoveredVectorArea ?? undefined,\n isGarbled: s.isGarbled,\n pageArea: s.pageArea,\n needsOcr: s.needsOcr,\n reasons: s.reasons,\n layout: s.layout\n ? {\n columnCount: s.layout.columnCount,\n ruledTableCount: s.layout.ruledTableCount,\n ruledTableCoverage: s.layout.ruledTableCoverage,\n textTableRunCount: s.layout.textTableRunCount,\n figureCount: s.layout.figureCount,\n figureCoverage: s.layout.figureCoverage,\n isComplex: s.layout.isComplex,\n reasons: s.layout.reasons,\n }\n : undefined,\n };\n}\n\n/** @internal Exported for pool-worker.ts only; not public API. */\nexport function toParseResult(result: NativeParseResult): ParseResult {\n return {\n totalPages: result.totalPages,\n pages: result.pages.map(toPage),\n pageErrors: result.pageErrors ?? [],\n text: result.text,\n images: (result.images ?? []).map(toImage),\n screenshots: (result.screenshots ?? []).map(toScreenshot),\n imageErrorCount: result.imageErrorCount ?? 0,\n formType: result.formType,\n creator: result.creator,\n producer: result.producer,\n docMeta: result.docMeta,\n xfaPackets: result.xfaPackets,\n };\n}\n\nfunction toPage(p: NativeParsedPage): ParsedPage {\n return {\n pageNum: p.pageNum,\n pageLabel: p.pageLabel ?? undefined,\n width: p.width,\n height: p.height,\n contentBounds: p.contentBounds,\n text: p.text,\n markdown: p.markdown,\n textItems: p.textItems.map(toTextItem),\n complexity: p.complexity ? toComplexity(p.complexity) : undefined,\n vectorGraphics: p.vectorGraphics ?? undefined,\n annotations: p.annotations,\n formFields: p.formFields?.map((field) => ({\n id: field.id,\n type: field.fieldType,\n page: field.page,\n annotationIndex: field.annotationIndex,\n widgetIndex: field.widgetIndex,\n objectNumber: field.objectNumber,\n name: field.name,\n alternateName: field.alternateName,\n value: field.value,\n exportValue: field.exportValue,\n fieldFlags: field.fieldFlags,\n controlCount: field.controlCount,\n controlIndex: field.controlIndex,\n checked: field.checked,\n rect: field.rect,\n options: field.options,\n selectedOptions: field.selectedOptions,\n })),\n structureTree: p.structureTree\n ? { roots: p.structureTree.roots.map(toStructureTreeElement) }\n : undefined,\n blocks: p.blocks as LayoutBlock[] | undefined,\n };\n}\n\nfunction toStructureTreeElement(\n element: NativeStructureTreeElement,\n): StructureTreeElement {\n const attributes: Record<string, StructureAttributeValue> = {};\n for (const attribute of element.attributes) {\n if (attribute.booleanValue !== undefined) {\n attributes[attribute.name] = attribute.booleanValue;\n } else if (attribute.numberValue !== undefined) {\n attributes[attribute.name] = attribute.numberValue;\n } else if (attribute.stringValue !== undefined) {\n attributes[attribute.name] = attribute.stringValue;\n }\n }\n return {\n type: element.elementType,\n id: element.id,\n actualText: element.actualText,\n altText: element.altText,\n title: element.title,\n attributes,\n markedContentIds: element.markedContentIds,\n children: element.children.map(toStructureTreeElement),\n annotations: element.annotations,\n };\n}\n\nfunction toImage(img: NativeExtractedImage): ExtractedImage {\n return {\n id: img.id,\n name: img.name,\n path: img.path,\n page: img.page,\n bbox: img.bbox,\n width: img.width,\n height: img.height,\n rotation: img.rotation,\n format: img.format,\n duplicateOf: img.duplicateOf,\n bytes: img.bytes,\n };\n}\n\nfunction toScreenshot(result: NativeScreenshotResult): ScreenshotResult {\n return {\n pageNum: result.pageNum,\n width: result.width,\n height: result.height,\n imageBuffer: result.imageBuffer,\n isSolidFill: result.isSolidFill,\n rects: result.rects,\n };\n}\n\nfunction toTextItem(item: NativeTextItem): TextItem {\n return {\n text: item.text,\n x: item.x,\n y: item.y,\n width: item.width,\n height: item.height,\n fontName: item.fontName,\n fontSize: item.fontSize,\n fontHeight: item.fontHeight,\n fontAscent: item.fontAscent,\n fontDescent: item.fontDescent,\n fontWeight: item.fontWeight,\n textWidth: item.textWidth,\n fontIsBuggy: item.fontIsBuggy,\n mcid: item.mcid,\n fillColor: item.fillColor,\n strokeColor: item.strokeColor,\n charCodes: item.charCodes,\n trailingSpaceGenerated: item.trailingSpaceGenerated,\n confidence: item.confidence,\n rotation: item.rotation,\n words: item.words,\n };\n}\n\n// ---------------------------------------------------------------------------\n// searchItems — standalone utility\n// ---------------------------------------------------------------------------\n\nexport interface SearchItemsOptions {\n phrase: string;\n caseSensitive?: boolean;\n}\n\nexport function searchItems(\n items: TextItem[],\n options: SearchItemsOptions,\n): TextItem[] {\n const nativeResults = native.searchItems(\n items,\n options.phrase,\n options.caseSensitive ?? false,\n );\n return nativeResults.map(toTextItem);\n}\n\nexport default LiteParse;\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// Native binary loader - tries platform-specific packages, falls back to local .node file.\n//\n// In production: the correct @llamaindex/liteparse-<platform> optional dependency\n// provides the .node binary. During development: `napi build` places it alongside package.json.\n\nimport { createRequire } from \"node:module\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst require = createRequire(import.meta.url);\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\ninterface NativeBindings {\n LiteParse: new (config?: LiteParseNativeConfig) => LiteParseNative;\n searchItems(\n items: NativeTextItem[],\n phrase: string,\n caseSensitive?: boolean | null,\n ): NativeTextItem[];\n}\n\nexport interface LiteParseNativeConfig {\n ocrLanguage?: string;\n ocrEnabled?: boolean;\n ocrServerUrl?: string;\n ocrServerHeaders?: Record<string, string>;\n tessdataPath?: string;\n maxPages?: number;\n targetPages?: string;\n extractScreenshots?: boolean;\n continueOnPageError?: boolean;\n dpi?: number;\n outputFormat?: string;\n imageMode?: string;\n extractImages?: boolean;\n imageOutputDir?: string;\n extractLinks?: boolean;\n keepHeadersFooters?: boolean;\n extractAnnotations?: boolean;\n extractFormFields?: boolean;\n extractStructureTree?: boolean;\n extractBlocks?: boolean;\n extractXfaPackets?: boolean;\n extractDocumentMetadata?: boolean;\n extractContentBounds?: boolean;\n detectScreenshotRects?: boolean;\n renderFormFields?: boolean;\n preserveVerySmallText?: boolean;\n password?: string;\n quiet?: boolean;\n numWorkers?: number;\n ocrFailureFatal?: boolean;\n ocrHedgeDelaysMs?: number[];\n emitWordBoxes?: boolean;\n extractTextMetadata?: boolean;\n cropBox?: NativeCropBox;\n skipDiagonalText?: boolean;\n pageOrientationCorrections?: NativePageOrientationCorrection[];\n includeComplexity?: boolean;\n extractVectorGraphics?: boolean;\n}\n\nexport interface NativeCropBox {\n top: number;\n right: number;\n bottom: number;\n left: number;\n}\n\nexport interface NativePageOrientationCorrection {\n page: number;\n angle: number;\n}\n\nexport interface NativeWordBox {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeTextItem {\n text: string;\n x: number;\n y: number;\n width: number;\n height: number;\n fontName?: string;\n fontSize?: number;\n fontHeight?: number;\n fontAscent?: number;\n fontDescent?: number;\n fontWeight?: number;\n textWidth?: number;\n fontIsBuggy?: boolean;\n mcid?: number;\n fillColor?: string;\n strokeColor?: string;\n charCodes?: number[];\n trailingSpaceGenerated?: boolean;\n confidence?: number;\n rotation?: number;\n words?: NativeWordBox[];\n}\n\nexport interface NativeGraphic {\n kind: string;\n x1?: number;\n y1?: number;\n x2?: number;\n y2?: number;\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n hasFill?: boolean;\n hasStroke?: boolean;\n fillColor?: string;\n strokeColor?: string;\n lineWidth?: number;\n}\n\nexport interface NativePageInput {\n pageNumber: number;\n pageWidth: number;\n pageHeight: number;\n textItems: NativeTextItem[];\n graphics?: NativeGraphic[];\n}\n\nexport interface NativeRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeParsedPage {\n pageNum: number;\n pageLabel?: string;\n width: number;\n height: number;\n contentBounds?: NativeRect;\n text: string;\n markdown: string;\n textItems: NativeTextItem[];\n complexity?: NativePageComplexityStats;\n vectorGraphics?: NativeVectorGraphics;\n annotations?: NativeDocumentAnnotation[];\n formFields?: NativeFormField[];\n structureTree?: NativeStructureTree;\n blocks?: NativeLayoutBlock[];\n}\n\nexport interface NativeLayoutCell {\n text: string;\n bbox?: NativeRect;\n}\n\nexport interface NativeLayoutBlock {\n kind: string;\n text?: string;\n level?: number;\n bold?: boolean;\n italic?: boolean;\n ordered?: boolean;\n marker?: string;\n lines?: string[];\n lang?: string;\n header?: NativeLayoutCell[];\n rows?: NativeLayoutCell[][];\n id?: string;\n format?: string;\n bbox?: NativeRect;\n}\n\nexport interface NativeStructureAttribute {\n name: string;\n booleanValue?: boolean;\n numberValue?: number;\n stringValue?: string;\n}\n\nexport interface NativeStructureTree {\n roots: NativeStructureTreeElement[];\n}\n\nexport interface NativeStructureTreeElement {\n elementType: string;\n id?: string;\n actualText?: string;\n altText?: string;\n title?: string;\n attributes: NativeStructureAttribute[];\n markedContentIds: number[];\n children: NativeStructureTreeElement[];\n annotations: NativeDocumentAnnotation[];\n}\n\nexport interface NativeVectorGraphics {\n shapes: Array<{\n bbox: { x: number; y: number; width: number; height: number };\n stroke: boolean;\n strokeColor?: string;\n fill: boolean;\n fillColor?: string;\n hasCurve: boolean;\n }>;\n lines: Array<{\n x1: number; y1: number; x2: number; y2: number;\n stroke: boolean; strokeWidth?: number; strokeColor?: string;\n fill: boolean; fillColor?: string;\n }>;\n}\n\nexport interface NativeAnnotationRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface NativeDocumentAnnotation {\n subtype: string;\n contents?: string;\n created?: string;\n modified?: string;\n title?: string;\n rect?: NativeAnnotationRect;\n quadpointRects: NativeAnnotationRect[];\n uri?: string;\n}\n\nexport interface NativeFormField {\n id: string;\n fieldType: string;\n page: number;\n annotationIndex: number;\n widgetIndex: number;\n objectNumber?: number;\n name?: string;\n alternateName?: string;\n value?: string;\n exportValue?: string;\n fieldFlags: number;\n controlCount?: number;\n controlIndex?: number;\n checked?: boolean;\n rect?: NativeAnnotationRect;\n options: string[];\n selectedOptions: string[];\n}\n\nexport interface NativeExtractedImage {\n id: string;\n name: string;\n path?: string;\n page: number;\n bbox: { x: number; y: number; width: number; height: number };\n width: number;\n height: number;\n rotation: number;\n format: string;\n duplicateOf?: string;\n bytes: Buffer;\n}\n\nexport interface NativeParseResult {\n totalPages: number;\n pages: NativeParsedPage[];\n pageErrors: Array<{ pageNum: number; message: string }>;\n text: string;\n images: NativeExtractedImage[];\n screenshots: NativeScreenshotResult[];\n imageErrorCount: number;\n formType?: number;\n creator?: string;\n producer?: string;\n docMeta?: NativeDocumentMetadata;\n xfaPackets?: NativeXfaPacket[];\n}\n\nexport interface NativeDocumentMetadata {\n creationDate?: string;\n modDate?: string;\n fileVersion?: number;\n isEncrypted?: boolean;\n securityHandlerRevision?: number;\n permissions?: number;\n eofSectionCount?: number;\n startxrefCount?: number;\n trailerIdPairDiffers?: boolean;\n rawFileSize?: number;\n xmp?: string;\n xmpTruncated?: boolean;\n signatureCount?: number;\n signatureByteRangeReachesEof?: boolean;\n}\n\nexport interface NativeXfaPacket {\n index: number;\n name?: string;\n contentLength: number;\n content?: string;\n}\n\nexport interface NativeScreenshotResult {\n pageNum: number;\n width: number;\n height: number;\n imageBuffer: Buffer;\n isSolidFill: boolean;\n rects: NativeScreenshotRect[];\n}\n\nexport interface NativeScreenshotRect {\n x: number;\n y: number;\n width: number;\n height: number;\n color: string;\n isLine: boolean;\n}\n\nexport interface NativeLayoutComplexityStats {\n columnCount: number;\n ruledTableCount: number;\n ruledTableCoverage: number;\n textTableRunCount: number;\n figureCount: number;\n figureCoverage: number;\n isComplex: boolean;\n reasons: string[];\n}\n\nexport interface NativePageComplexityStats {\n pageNumber: number;\n textLength: number;\n textCoverage: number;\n hasSubstantialImages: boolean;\n imageBlockCount: number;\n imageCoverage: number;\n largestImageCoverage: number;\n fullPageImage: boolean;\n uncoveredVectorArea?: number;\n isGarbled: boolean;\n pageArea: number;\n needsOcr: boolean;\n reasons: string[];\n layout?: NativeLayoutComplexityStats;\n}\n\nexport interface NativeParseBatch {\n startPage: number;\n endPage: number;\n result: NativeParseResult;\n}\n\nexport interface NativeParseSession {\n nextBatch(): Promise<NativeParseBatch | null>;\n close(): Promise<void>;\n readonly totalPages: number;\n}\n\nexport interface LiteParseNative {\n parse(input: string | Buffer): Promise<NativeParseResult>;\n openBatchSession(\n input: string | Buffer,\n batchSize?: number,\n ): Promise<NativeParseSession>;\n parsePages(pages: NativePageInput[]): NativeParseResult;\n isComplex(input: string | Buffer): Promise<NativePageComplexityStats[]>;\n screenshot(\n input: string | Buffer,\n pageNumbers?: number[] | null,\n ): Promise<NativeScreenshotResult[]>;\n format(result: NativeParseResult): string;\n readonly config: LiteParseNativeConfig;\n}\n\nfunction loadNative(): NativeBindings {\n // Platform-specific package names generated by napi-rs\n const triples: Record<string, string> = {\n \"darwin-x64\": \"@llamaindex/liteparse-darwin-x64\",\n \"darwin-arm64\": \"@llamaindex/liteparse-darwin-arm64\",\n \"linux-x64-gnu\": \"@llamaindex/liteparse-linux-x64-gnu\",\n \"linux-x64-musl\": \"@llamaindex/liteparse-linux-x64-musl\",\n \"linux-arm64-gnu\": \"@llamaindex/liteparse-linux-arm64-gnu\",\n \"linux-arm64-musl\": \"@llamaindex/liteparse-linux-arm64-musl\",\n \"win32-x64-msvc\": \"@llamaindex/liteparse-win32-x64-msvc\",\n \"win32-arm64-msvc\": \"@llamaindex/liteparse-win32-arm64-msvc\",\n };\n\n // Try platform-specific package first\n const platform = process.platform;\n const arch = process.arch;\n\n const candidates: string[] = [];\n if (platform === \"linux\") {\n // Try gnu first, then musl\n candidates.push(`${platform}-${arch}-gnu`);\n candidates.push(`${platform}-${arch}-musl`);\n } else if (platform === \"win32\") {\n candidates.push(`${platform}-${arch}-msvc`);\n } else {\n candidates.push(`${platform}-${arch}`);\n }\n\n for (const key of candidates) {\n const pkg = triples[key];\n if (pkg) {\n try {\n return require(pkg);\n } catch {\n // Not installed, try next\n }\n }\n }\n\n // Fallback: local .node file (development builds)\n // Try several paths since __dirname may be dist/ or dist/src/\n const searchDirs = [__dirname, join(__dirname, \"..\"), join(__dirname, \"..\", \"..\")];\n // Try full triple names (e.g. liteparse.linux-x64-gnu.node) and simple name\n const fileNames = [\n ...candidates.map((c) => `liteparse.${c}.node`),\n `liteparse.${platform}-${arch}.node`,\n \"liteparse.node\",\n ];\n for (const dir of searchDirs) {\n for (const fileName of fileNames) {\n try {\n return require(join(dir, fileName));\n } catch {\n // try next\n }\n }\n }\n\n throw new Error(\n `Failed to load native module for ${platform}-${arch}. ` +\n `Ensure the correct optional dependency is installed.`,\n );\n}\n\nexport const native = loadNative();\n","// Process-isolated worker pool for LiteParse.\n//\n// Not public API; use `new LiteParse({ poolSize, parseTimeoutMs })`.\n\nimport { fork, type ChildProcess } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ParseResult } from \"./lib.js\";\n\n/** A pooled parse exceeded `parseTimeoutMs` and its worker was killed.\n *\n * Only thrown in pool mode, where the deadline is enforced by killing the\n * worker process — the timed-out parse is guaranteed dead, not still running\n * in the background. `source` names the document (file path, or `<N bytes>`\n * for byte inputs); log it to identify the documents that stall your\n * pipeline.\n */\nexport class ParseTimeoutError extends Error {\n readonly source: string;\n readonly timeoutMs: number;\n\n constructor(message: string, source: string, timeoutMs: number) {\n super(message);\n this.name = \"ParseTimeoutError\";\n this.source = source;\n this.timeoutMs = timeoutMs;\n }\n}\n\nclass WorkerTimeout extends Error {}\nclass WorkerCrashed extends Error {}\n\ntype WorkerResponse =\n | { type: \"ready\" }\n | { type: \"initError\"; message: string }\n | { type: \"ok\"; result: ParseResult }\n | { type: \"err\"; message: string };\n\nconst WORKER_PATH = fileURLToPath(new URL(\"./pool-worker.js\", import.meta.url));\n\n/** IPC deserialization yields plain Uint8Arrays where the API promises\n * Buffers; rewrap in place (no copy). */\nfunction reviveBuffers(result: ParseResult): ParseResult {\n for (const image of result.images ?? []) {\n if (image.bytes && !Buffer.isBuffer(image.bytes)) {\n const b = image.bytes as Uint8Array;\n image.bytes = Buffer.from(b.buffer, b.byteOffset, b.byteLength);\n }\n }\n for (const shot of result.screenshots ?? []) {\n if (shot.imageBuffer && !Buffer.isBuffer(shot.imageBuffer)) {\n const b = shot.imageBuffer as Uint8Array;\n shot.imageBuffer = Buffer.from(b.buffer, b.byteOffset, b.byteLength);\n }\n }\n return result;\n}\n\nclass WorkerHandle {\n private child: ChildProcess;\n private readyPromise: Promise<void>;\n private pending: {\n resolve: (r: ParseResult) => void;\n reject: (e: Error) => void;\n } | null = null;\n private dead = false;\n\n constructor(config: Record<string, unknown>) {\n this.child = fork(WORKER_PATH, [], {\n serialization: \"advanced\",\n // stdout/stderr inherited: parse logs and crash traces stay visible.\n stdio: [\"ignore\", \"inherit\", \"inherit\", \"ipc\"],\n });\n\n let readyResolve!: () => void;\n let readyReject!: (e: Error) => void;\n this.readyPromise = new Promise<void>((resolve, reject) => {\n readyResolve = resolve;\n readyReject = reject;\n });\n // ready() may never be awaited if the worker is retired first.\n this.readyPromise.catch(() => {});\n\n this.child.on(\"message\", (msg: WorkerResponse) => {\n if (msg.type === \"ready\") {\n readyResolve();\n if (this.pending === null) this.idle();\n } else if (msg.type === \"initError\") {\n readyReject(new Error(msg.message));\n } else if (this.pending) {\n const { resolve, reject } = this.pending;\n this.pending = null;\n this.idle();\n if (msg.type === \"ok\") resolve(reviveBuffers(msg.result));\n else reject(new WorkerCrashed(msg.message));\n }\n });\n const onGone = (cause: string) => {\n this.dead = true;\n readyReject(new WorkerCrashed(cause));\n if (this.pending) {\n const { reject } = this.pending;\n this.pending = null;\n reject(new WorkerCrashed(cause));\n }\n };\n this.child.on(\"error\", (e) => onGone(e.message));\n this.child.on(\"exit\", (code, signal) =>\n onGone(`worker exited (code=${code}, signal=${signal})`),\n );\n\n // Stay ref'd until the init handshake arrives — a caller awaiting\n // warmUp()/ready() must keep the event loop alive. idle() runs on\n // \"ready\"; after that, an idle worker never holds the loop open.\n this.child.send({ type: \"init\", config });\n }\n\n /** Resolves when the worker's native parser is constructed. Init time\n * never counts toward the parse deadline — the deadline is a promise about\n * parsing, not about process startup. */\n ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /** An idle pool must not hold the parent's event loop open. */\n private idle(): void {\n this.child.unref();\n this.child.channel?.unref();\n }\n\n request(\n payload: string | Buffer,\n timeoutMs: number | undefined,\n ): Promise<ParseResult> {\n if (this.dead) {\n return Promise.reject(new WorkerCrashed(\"worker already exited\"));\n }\n this.child.ref();\n this.child.channel?.ref();\n return new Promise<ParseResult>((resolve, reject) => {\n let timer: NodeJS.Timeout | undefined;\n const settle =\n (fn: (v: never) => void) =>\n (value: never): void => {\n if (timer !== undefined) clearTimeout(timer);\n fn(value);\n };\n this.pending = {\n resolve: settle(resolve) as (r: ParseResult) => void,\n reject: settle(reject) as (e: Error) => void,\n };\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => {\n if (this.pending) {\n const { reject: rejectPending } = this.pending;\n this.pending = null;\n rejectPending(new WorkerTimeout());\n }\n }, timeoutMs);\n }\n this.child.send({ type: \"parse\", payload });\n });\n }\n\n kill(): void {\n this.dead = true;\n this.child.kill(\"SIGKILL\");\n }\n\n /** Graceful shutdown; escalates to SIGKILL if the worker doesn't exit. */\n stop(): void {\n if (this.dead) return;\n this.dead = true;\n try {\n this.child.send({ type: \"stop\" });\n } catch {\n // channel already closed\n }\n const escalate = setTimeout(() => this.child.kill(\"SIGKILL\"), 5000);\n escalate.unref();\n this.child.once(\"exit\", () => clearTimeout(escalate));\n this.idle();\n }\n}\n\nexport class WorkerPool {\n private config: Record<string, unknown>;\n private timeoutMs: number | undefined;\n private workers = new Set<WorkerHandle>();\n private idle: WorkerHandle[] = [];\n private waiters: Array<{\n resolve: (w: WorkerHandle) => void;\n reject: (e: Error) => void;\n }> = [];\n private closed = false;\n\n constructor(\n config: Record<string, unknown>,\n poolSize: number,\n parseTimeoutMs?: number,\n ) {\n if (!Number.isInteger(poolSize) || poolSize < 1) {\n throw new Error(\"poolSize must be an integer >= 1\");\n }\n if (parseTimeoutMs !== undefined && !(parseTimeoutMs > 0)) {\n throw new Error(\"parseTimeoutMs must be > 0\");\n }\n this.config = config;\n this.timeoutMs = parseTimeoutMs;\n // Spawn eagerly: children load the addon and construct their native\n // parsers concurrently while the caller goes on with its own startup.\n for (let i = 0; i < poolSize; i++) {\n this.spawnWorker();\n }\n }\n\n private spawnWorker(): void {\n const worker = new WorkerHandle(this.config);\n this.workers.add(worker);\n this.release(worker);\n }\n\n private acquire(): Promise<WorkerHandle> {\n const worker = this.idle.pop();\n if (worker !== undefined) return Promise.resolve(worker);\n return new Promise((resolve, reject) =>\n this.waiters.push({ resolve, reject }),\n );\n }\n\n private release(worker: WorkerHandle): void {\n if (this.closed) {\n this.workers.delete(worker);\n worker.stop();\n return;\n }\n const waiter = this.waiters.shift();\n if (waiter !== undefined) waiter.resolve(worker);\n else this.idle.push(worker);\n }\n\n private retire(worker: WorkerHandle): void {\n worker.kill();\n this.workers.delete(worker);\n if (!this.closed) this.spawnWorker();\n }\n\n /** Run one parse on an idle worker.\n *\n * Waits for a free worker first; `parseTimeoutMs` bounds the parse itself,\n * not the wait. */\n async parse(payload: string | Buffer, source: string): Promise<ParseResult> {\n if (this.closed) throw new Error(\"parser pool is closed\");\n const worker = await this.acquire();\n try {\n await worker.ready();\n const result = await worker.request(payload, this.timeoutMs);\n this.release(worker);\n return result;\n } catch (e) {\n this.retire(worker);\n if (e instanceof WorkerTimeout) {\n throw new ParseTimeoutError(\n `parse of ${source} exceeded ${this.timeoutMs}ms; the worker process was killed`,\n source,\n this.timeoutMs!,\n );\n }\n if (e instanceof WorkerCrashed) {\n throw new Error(\n `liteparse worker process died while parsing ${source}: ${e.message}`,\n );\n }\n throw e;\n }\n }\n\n /** Resolves when every worker is initialized. Optional — the first parse\n * per worker waits for init anyway. */\n async warmUp(): Promise<void> {\n await Promise.all([...this.workers].map((w) => w.ready()));\n }\n\n /** Shut down all workers. Idempotent. Busy workers are stopped as their\n * in-flight parses finish. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n for (const waiter of this.waiters.splice(0)) {\n waiter.reject(new Error(\"parser pool is closed\"));\n }\n for (const worker of this.idle.splice(0)) {\n this.workers.delete(worker);\n worker.stop();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACP9D,yBAA8B;AAC9B,uBAA8B;AAC9B,sBAA8B;AAE9B,IAAMA,eAAU,kCAAc,aAAe;AAC7C,IAAM,gBAAY,8BAAQ,+BAAc,aAAe,CAAC;AAmXxD,SAAS,aAA6B;AAEpC,QAAM,UAAkC;AAAA,IACtC,cAAc;AAAA,IACd,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,IACnB,oBAAoB;AAAA,IACpB,kBAAkB;AAAA,IAClB,oBAAoB;AAAA,EACtB;AAGA,QAAM,WAAW,QAAQ;AACzB,QAAM,OAAO,QAAQ;AAErB,QAAM,aAAuB,CAAC;AAC9B,MAAI,aAAa,SAAS;AAExB,eAAW,KAAK,GAAG,QAAQ,IAA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KAAK;AAAA,IACX,GAAG,KAAK;AAAA,IACR,GAAG,KAAK;AAAA,IACR,OAAO,KAAK;AAAA,IACZ,QAAQ,KAAK;AAAA,IACb,UAAU,KAAK;AAAA,IACf,UAAU,KAAK;AAAA,IACf,YAAY,KAAK;AAAA,IACjB,YAAY,KAAK;AAAA,IACjB,aAAa,KAAK;AAAA,IAClB,YAAY,KAAK;AAAA,IACjB,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,MAAM,KAAK;AAAA,IACX,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,WAAW,KAAK;AAAA,IAChB,wBAAwB,KAAK;AAAA,IAC7B,YAAY,KAAK;AAAA,IACjB,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,EACd;AACF;AAWO,SAAS,YACd,OACA,SACY;AACZ,QAAM,gBAAgB,OAAO;AAAA,IAC3B;AAAA,IACA,QAAQ;AAAA,IACR,QAAQ,iBAAiB;AAAA,EAC3B;AACA,SAAO,cAAc,IAAI,UAAU;AACrC;AAEA,IAAO,cAAQ;","names":["require","import_node_url"]}
|
package/dist/lib.d.cts
CHANGED
|
@@ -36,6 +36,7 @@ interface NativeRect {
|
|
|
36
36
|
}
|
|
37
37
|
interface NativeParsedPage {
|
|
38
38
|
pageNum: number;
|
|
39
|
+
pageLabel?: string;
|
|
39
40
|
width: number;
|
|
40
41
|
height: number;
|
|
41
42
|
contentBounds?: NativeRect;
|
|
@@ -373,6 +374,17 @@ interface LiteParseConfig {
|
|
|
373
374
|
* watermarks/stamps from the output.
|
|
374
375
|
*/
|
|
375
376
|
skipDiagonalText: boolean;
|
|
377
|
+
/**
|
|
378
|
+
* Per-page orientation corrections from an upstream orientation classifier
|
|
379
|
+
* (one that saw the rendered page). Each entry names a 1-based page and the
|
|
380
|
+
* clockwise angle (0/90/180/270) by which that page's content *appears*
|
|
381
|
+
* rotated in its viewport; LiteParse counter-rotates the page before
|
|
382
|
+
* extraction, so text coordinates, reading order, page dimensions and OCR
|
|
383
|
+
* rasters all come out upright. Applied on top of the PDF's own `/Rotate`.
|
|
384
|
+
* Pages not listed, or past the end of the document, are left unchanged.
|
|
385
|
+
* Default: none.
|
|
386
|
+
*/
|
|
387
|
+
pageOrientationCorrections?: PageOrientationCorrection[];
|
|
376
388
|
/**
|
|
377
389
|
* Compute per-page complexity signals during {@link LiteParse.parse} and
|
|
378
390
|
* attach them to each page as {@link ParsedPage.complexity} (the same signals
|
|
@@ -393,6 +405,16 @@ interface CropBox {
|
|
|
393
405
|
bottom: number;
|
|
394
406
|
left: number;
|
|
395
407
|
}
|
|
408
|
+
/**
|
|
409
|
+
* One page's orientation correction (see
|
|
410
|
+
* {@link LiteParseConfig.pageOrientationCorrections}).
|
|
411
|
+
*/
|
|
412
|
+
interface PageOrientationCorrection {
|
|
413
|
+
/** 1-based document page number. */
|
|
414
|
+
page: number;
|
|
415
|
+
/** Clockwise degrees the content appears rotated: 0, 90, 180 or 270. */
|
|
416
|
+
angle: 0 | 90 | 180 | 270;
|
|
417
|
+
}
|
|
396
418
|
/**
|
|
397
419
|
* One word's bounding box within a {@link TextItem}, in the same viewport space
|
|
398
420
|
* (top-left origin, 72 DPI). `text` excludes inter-word spaces.
|
|
@@ -486,6 +508,12 @@ interface Rect {
|
|
|
486
508
|
}
|
|
487
509
|
interface ParsedPage {
|
|
488
510
|
pageNum: number;
|
|
511
|
+
/**
|
|
512
|
+
* The document's `/PageLabels` label for this page ("iv", "A-1"), absent
|
|
513
|
+
* when the PDF defines none. This is what a reader displays for the page
|
|
514
|
+
* and is not always its position, so fall back to `pageNum` when absent.
|
|
515
|
+
*/
|
|
516
|
+
pageLabel?: string;
|
|
489
517
|
width: number;
|
|
490
518
|
height: number;
|
|
491
519
|
/**
|
|
@@ -908,4 +936,4 @@ interface SearchItemsOptions {
|
|
|
908
936
|
}
|
|
909
937
|
declare function searchItems(items: TextItem[], options: SearchItemsOptions): TextItem[];
|
|
910
938
|
|
|
911
|
-
export { type AnnotationRect, type CropBox, type DocumentAnnotation, type DocumentMetadata, type ExtractedImage, type FormField, type Graphic, type ImageMode, type LayoutBlock, type LayoutCell, type LayoutComplexityStats, LiteParse, type LiteParseConfig, type LiteParseInput, type OutputFormat, type PageComplexityStats, type PageInput, type ParseBatch, type ParseBatchOptions, type ParseResult, ParseTimeoutError, type ParsedPage, type PoolOptions, type Rect, type ScreenshotRect, type ScreenshotResult, type SearchItemsOptions, type StructureAttributeValue, type StructureTree, type StructureTreeElement, type TextItem, type VectorGraphics, type VectorLine, type VectorShape, type WordBox, type XfaPacket, LiteParse as default, searchItems, toParseResult };
|
|
939
|
+
export { type AnnotationRect, type CropBox, type DocumentAnnotation, type DocumentMetadata, type ExtractedImage, type FormField, type Graphic, type ImageMode, type LayoutBlock, type LayoutCell, type LayoutComplexityStats, LiteParse, type LiteParseConfig, type LiteParseInput, type OutputFormat, type PageComplexityStats, type PageInput, type PageOrientationCorrection, type ParseBatch, type ParseBatchOptions, type ParseResult, ParseTimeoutError, type ParsedPage, type PoolOptions, type Rect, type ScreenshotRect, type ScreenshotResult, type SearchItemsOptions, type StructureAttributeValue, type StructureTree, type StructureTreeElement, type TextItem, type VectorGraphics, type VectorLine, type VectorShape, type WordBox, type XfaPacket, LiteParse as default, searchItems, toParseResult };
|
package/dist/lib.d.ts
CHANGED
|
@@ -36,6 +36,7 @@ interface NativeRect {
|
|
|
36
36
|
}
|
|
37
37
|
interface NativeParsedPage {
|
|
38
38
|
pageNum: number;
|
|
39
|
+
pageLabel?: string;
|
|
39
40
|
width: number;
|
|
40
41
|
height: number;
|
|
41
42
|
contentBounds?: NativeRect;
|
|
@@ -373,6 +374,17 @@ interface LiteParseConfig {
|
|
|
373
374
|
* watermarks/stamps from the output.
|
|
374
375
|
*/
|
|
375
376
|
skipDiagonalText: boolean;
|
|
377
|
+
/**
|
|
378
|
+
* Per-page orientation corrections from an upstream orientation classifier
|
|
379
|
+
* (one that saw the rendered page). Each entry names a 1-based page and the
|
|
380
|
+
* clockwise angle (0/90/180/270) by which that page's content *appears*
|
|
381
|
+
* rotated in its viewport; LiteParse counter-rotates the page before
|
|
382
|
+
* extraction, so text coordinates, reading order, page dimensions and OCR
|
|
383
|
+
* rasters all come out upright. Applied on top of the PDF's own `/Rotate`.
|
|
384
|
+
* Pages not listed, or past the end of the document, are left unchanged.
|
|
385
|
+
* Default: none.
|
|
386
|
+
*/
|
|
387
|
+
pageOrientationCorrections?: PageOrientationCorrection[];
|
|
376
388
|
/**
|
|
377
389
|
* Compute per-page complexity signals during {@link LiteParse.parse} and
|
|
378
390
|
* attach them to each page as {@link ParsedPage.complexity} (the same signals
|
|
@@ -393,6 +405,16 @@ interface CropBox {
|
|
|
393
405
|
bottom: number;
|
|
394
406
|
left: number;
|
|
395
407
|
}
|
|
408
|
+
/**
|
|
409
|
+
* One page's orientation correction (see
|
|
410
|
+
* {@link LiteParseConfig.pageOrientationCorrections}).
|
|
411
|
+
*/
|
|
412
|
+
interface PageOrientationCorrection {
|
|
413
|
+
/** 1-based document page number. */
|
|
414
|
+
page: number;
|
|
415
|
+
/** Clockwise degrees the content appears rotated: 0, 90, 180 or 270. */
|
|
416
|
+
angle: 0 | 90 | 180 | 270;
|
|
417
|
+
}
|
|
396
418
|
/**
|
|
397
419
|
* One word's bounding box within a {@link TextItem}, in the same viewport space
|
|
398
420
|
* (top-left origin, 72 DPI). `text` excludes inter-word spaces.
|
|
@@ -486,6 +508,12 @@ interface Rect {
|
|
|
486
508
|
}
|
|
487
509
|
interface ParsedPage {
|
|
488
510
|
pageNum: number;
|
|
511
|
+
/**
|
|
512
|
+
* The document's `/PageLabels` label for this page ("iv", "A-1"), absent
|
|
513
|
+
* when the PDF defines none. This is what a reader displays for the page
|
|
514
|
+
* and is not always its position, so fall back to `pageNum` when absent.
|
|
515
|
+
*/
|
|
516
|
+
pageLabel?: string;
|
|
489
517
|
width: number;
|
|
490
518
|
height: number;
|
|
491
519
|
/**
|
|
@@ -908,4 +936,4 @@ interface SearchItemsOptions {
|
|
|
908
936
|
}
|
|
909
937
|
declare function searchItems(items: TextItem[], options: SearchItemsOptions): TextItem[];
|
|
910
938
|
|
|
911
|
-
export { type AnnotationRect, type CropBox, type DocumentAnnotation, type DocumentMetadata, type ExtractedImage, type FormField, type Graphic, type ImageMode, type LayoutBlock, type LayoutCell, type LayoutComplexityStats, LiteParse, type LiteParseConfig, type LiteParseInput, type OutputFormat, type PageComplexityStats, type PageInput, type ParseBatch, type ParseBatchOptions, type ParseResult, ParseTimeoutError, type ParsedPage, type PoolOptions, type Rect, type ScreenshotRect, type ScreenshotResult, type SearchItemsOptions, type StructureAttributeValue, type StructureTree, type StructureTreeElement, type TextItem, type VectorGraphics, type VectorLine, type VectorShape, type WordBox, type XfaPacket, LiteParse as default, searchItems, toParseResult };
|
|
939
|
+
export { type AnnotationRect, type CropBox, type DocumentAnnotation, type DocumentMetadata, type ExtractedImage, type FormField, type Graphic, type ImageMode, type LayoutBlock, type LayoutCell, type LayoutComplexityStats, LiteParse, type LiteParseConfig, type LiteParseInput, type OutputFormat, type PageComplexityStats, type PageInput, type PageOrientationCorrection, type ParseBatch, type ParseBatchOptions, type ParseResult, ParseTimeoutError, type ParsedPage, type PoolOptions, type Rect, type ScreenshotRect, type ScreenshotResult, type SearchItemsOptions, type StructureAttributeValue, type StructureTree, type StructureTreeElement, type TextItem, type VectorGraphics, type VectorLine, type VectorShape, type WordBox, type XfaPacket, LiteParse as default, searchItems, toParseResult };
|
package/dist/lib.js
CHANGED
|
@@ -332,6 +332,7 @@ var LiteParse = class {
|
|
|
332
332
|
extractTextMetadata: userConfig.extractTextMetadata,
|
|
333
333
|
cropBox: userConfig.cropBox,
|
|
334
334
|
skipDiagonalText: userConfig.skipDiagonalText,
|
|
335
|
+
pageOrientationCorrections: userConfig.pageOrientationCorrections,
|
|
335
336
|
includeComplexity: userConfig.includeComplexity,
|
|
336
337
|
extractVectorGraphics: userConfig.extractVectorGraphics
|
|
337
338
|
};
|
|
@@ -385,6 +386,7 @@ var LiteParse = class {
|
|
|
385
386
|
extractTextMetadata: resolved.extractTextMetadata ?? false,
|
|
386
387
|
cropBox: resolved.cropBox ?? void 0,
|
|
387
388
|
skipDiagonalText: resolved.skipDiagonalText ?? false,
|
|
389
|
+
pageOrientationCorrections: resolved.pageOrientationCorrections ?? void 0,
|
|
388
390
|
includeComplexity: resolved.includeComplexity ?? false,
|
|
389
391
|
extractVectorGraphics: resolved.extractVectorGraphics ?? false
|
|
390
392
|
};
|
|
@@ -554,6 +556,7 @@ function toParseResult(result) {
|
|
|
554
556
|
function toPage(p) {
|
|
555
557
|
return {
|
|
556
558
|
pageNum: p.pageNum,
|
|
559
|
+
pageLabel: p.pageLabel ?? void 0,
|
|
557
560
|
width: p.width,
|
|
558
561
|
height: p.height,
|
|
559
562
|
contentBounds: p.contentBounds,
|