@effortlessmotion/pdf-to-md 0.1.4 → 0.1.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/extract.ts"],"sourcesContent":["// extract command — parse this command's flags, call src/extract.ts, print\n// and write the result. No business logic here — the library returns data and throws; only the CLI prints and exits.\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport type { OcrWordInput } from '../extract.ts';\nimport type { Tuning } from '../geometry.ts';\nimport type { Analysis, Report } from '../types.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE =\n 'usage: pdf-to-md [extract] <file.pdf> [out.md] [--json] [--page-markers] [--ocr] [--no-ocr] ' +\n '[--pages N[-M]] [--stdout] [--words-json=FILE] [--debug-words=FILE] ' +\n '[--format md|txt|raw (default md; raw = Analysis JSON incl. the report; txt = reading-order plain text)] ' +\n '[--dpi=N (OCR render resolution, default 288; raise for tiny print or chart/label pages, ' +\n '>~400 measured worse on ordinary prose pages)] ' +\n '[--float-max-words=N] [--float-max-width=F] [--float-margin=F] [--para-gap=F] [--heading-scale=F] ' +\n '[--col-max-width=F] [--col-split=F] [--line-y-tol=F] [--line-height-ratio=F]';\n\nconst FORMATS = ['md', 'txt', 'raw'] as const;\ntype Format = (typeof FORMATS)[number];\n\n// A bad tuning-flag value (non-numeric, or <= 0 unless the flag allows zero) is a usage error, not a silent no-op.\nconst TUNING_FLAGS: {\n name: string;\n key: keyof Tuning;\n allowZero?: boolean;\n isInt?: boolean;\n}[] = [\n {\n name: 'float-max-words',\n key: 'floatMaxWords',\n allowZero: true,\n isInt: true,\n },\n { name: 'float-max-width', key: 'floatMaxWidth' },\n { name: 'float-margin', key: 'floatMargin' },\n { name: 'para-gap', key: 'paraGap' },\n { name: 'heading-scale', key: 'headingScale' },\n { name: 'col-max-width', key: 'colMaxWidth' },\n { name: 'col-split', key: 'colSplit' },\n { name: 'line-y-tol', key: 'lineYTol' },\n { name: 'line-height-ratio', key: 'lineHeightRatio' },\n];\n\nconst extract: Command = async (ctx) => {\n // --debug-words takes a required FILE value; a bare --debug-words is a\n // usage error, checked before parseArgs so it can't silently swallow the next token as its value.\n if (ctx.rest.includes('--debug-words')) {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n json: { type: 'boolean', default: false },\n 'page-markers': { type: 'boolean', default: false },\n ocr: { type: 'boolean', default: false },\n 'no-ocr': { type: 'boolean', default: false },\n stdout: { type: 'boolean', default: false },\n 'debug-words': { type: 'string' },\n help: { type: 'boolean', default: false, short: 'h' },\n pages: { type: 'string' },\n dpi: { type: 'string' },\n format: { type: 'string', default: 'md' },\n 'words-json': { type: 'string' },\n ...Object.fromEntries(TUNING_FLAGS.map((f) => [f.name, { type: 'string' as const }])),\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const values = parsed.values as Record<string, string | boolean | undefined>;\n const positionals = parsed.positionals;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [src, outArg] = positionals;\n const wordsPath = values['words-json'] as string | undefined;\n if (!src && !wordsPath) ctx.usageError(USAGE);\n\n const formatRaw = values.format as string;\n if (!(FORMATS as readonly string[]).includes(formatRaw)) {\n ctx.usageError(`${USAGE}\\n--format must be one of ${FORMATS.join('|')} (got ${JSON.stringify(formatRaw)})`);\n }\n const format = formatRaw as Format;\n\n // --pages: a malformed spec is a usage error; out-of-range page NUMBERS\n // clamp instead (collect.ts / the engine apply the same clamping policy).\n let pages: { first: number; last: number } | undefined;\n if (values.pages !== undefined) {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(values.pages as string);\n const first = m ? Number(m[1]) : Number.NaN;\n const last = m ? (m[2] !== undefined ? Number(m[2]) : first) : Number.NaN;\n if (!m || first < 1 || last < first) {\n ctx.usageError(`${USAGE}\\n--pages requires N or N-M, N >= 1, M >= N (got ${JSON.stringify(values.pages)})`);\n }\n pages = { first, last };\n }\n\n const tuning: Partial<Tuning> = {};\n for (const spec of TUNING_FLAGS) {\n const raw = values[spec.name] as string | undefined;\n if (raw === undefined) continue;\n const value = Number(raw);\n const ok = raw !== '' && Number.isFinite(value) && (spec.allowZero ? value >= 0 : value > 0);\n if (!ok) {\n ctx.usageError(`${USAGE}\\n--${spec.name} requires a ${spec.allowZero ? 'non-negative' : 'positive'} number (got ${JSON.stringify(raw)})`);\n }\n (tuning[spec.key] as number) = spec.isInt ? Math.trunc(value) : value;\n }\n\n // --dpi: page-render resolution, validated like the tuning flags. Default\n // 288 is the measured operating point; >~400 measured WORSE on ordinary pages — not a \"bigger is safer\" knob.\n let dpi: number | undefined;\n if (values.dpi !== undefined) {\n const raw = values.dpi as string;\n const value = Number(raw);\n if (raw === '' || !Number.isFinite(value) || value <= 0) {\n ctx.usageError(`${USAGE}\\n--dpi requires a positive number (got ${JSON.stringify(raw)})`);\n }\n dpi = value;\n }\n\n // In --words-json mode there may be no PDF positional; the words file\n // stands in for naming, extension stripped so the default dest can never overwrite the input. Default extension follows --format.\n const source = src ?? (wordsPath as string);\n const defaultExt = format === 'raw' ? 'json' : format === 'txt' ? 'txt' : 'md';\n const dest = outArg || `${source.replace(/\\.(pdf|jsonl)$/i, '')}.${defaultExt}`;\n\n const onWarning = (m: string) => console.error(m);\n const showProgress = process.stderr.isTTY;\n // onProgress carries per-page timing/count only; human-readable\n // diagnostics (e.g. the sparse-retry notice) arrive via onWarning instead, so they print regardless of TTY-ness.\n const onProgress = (e: { type: 'page'; page: number; words: number; ms: number }) => {\n if (showProgress) console.error(`p${e.page}: ${e.words} words, ${e.ms}ms`);\n };\n const debugWordsPath = values['debug-words'] as string | undefined;\n if (debugWordsPath !== undefined && debugWordsPath.trim() === '') {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n // The severity-1 audit instrument: every recognized word as clean JSON\n // lines to its own file. stderr stays a human channel (mixed prose), never a dump target — this file is guaranteed byte-for-byte parseable.\n const onWords = debugWordsPath\n ? (words: OcrWordInput[]) => {\n const lines = words.map((w) => {\n const entry: OcrWordInput = { page: w.page, text: w.text, x: w.x, y: w.y, w: w.w, h: w.h };\n if (w.confidence !== undefined) entry.confidence = w.confidence;\n return JSON.stringify(entry);\n });\n writeFileSync(debugWordsPath, lines.length ? `${lines.join('\\n')}\\n` : '');\n }\n : undefined;\n\n const common = { pages, onWarning };\n const ocrCommon = {\n ...common,\n tuning,\n dpi,\n onProgress,\n onWords,\n };\n\n let words: OcrWordInput[] | undefined;\n let skipped = 0;\n if (wordsPath !== undefined) {\n ({ words, skipped } = parseWordLines(readFileSync(wordsPath, 'utf8')));\n if (skipped > 0) console.error(`--words-json: skipped ${skipped} non-JSON line(s)`);\n }\n\n let content: string;\n let report: Report;\n if (format === 'md') {\n // Unchanged path: extractOcr/pdfToMarkdown directly, exactly as before\n // --format existed.\n const { extractOcr, pdfToMarkdown } = await import('../extract.ts');\n let markdown: string;\n if (words !== undefined) {\n ({ markdown, report } = await extractOcr({ words }, ocrCommon));\n } else {\n ({ markdown, report } = await pdfToMarkdown(src, {\n ...ocrCommon,\n ocr: values.ocr as boolean,\n noOcr: values['no-ocr'] as boolean,\n pageMarkers: values['page-markers'] as boolean,\n }));\n }\n content = markdown;\n } else {\n // raw/txt: both render from an Analysis — raw IS the Analysis as JSON;\n // txt is toText(analysis). Mirrors pdfToMarkdown's own auto-OCR fallback decision so a different --format doesn't silently pick a different path.\n const { analyze } = await import('../analyze.ts');\n const { toText } = await import('../render-analysis.ts');\n const { needsOcrFallback, ocrFallbackNotice } = await import('../extract.ts');\n let analysis: Analysis;\n if (words !== undefined) {\n analysis = await analyze({ words }, { ...ocrCommon, path: 'ocr' });\n } else if (values.ocr) {\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr' });\n } else {\n const text = await analyze(src, { ...common, path: 'text', pageMarkers: values['page-markers'] as boolean });\n if (needsOcrFallback(text.report.charsPerPage) && !values['no-ocr']) {\n onWarning(ocrFallbackNotice(text.report.charsPerPage));\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr', fallback: true });\n } else {\n analysis = text;\n }\n }\n report = analysis.report;\n content = format === 'raw' ? JSON.stringify(analysis, null, 1) : toText(analysis);\n }\n\n if (values.stdout) process.stdout.write(content);\n else writeFileSync(dest, content);\n\n // The library's Report stays clean of source/out; --json consumers keep\n // report.json files around and need to know which input produced each one, so the CLI (only) decorates the printed JSON with source/out here.\n if (values.json) console.log(JSON.stringify({ source, out: dest, ...report }, null, 1));\n else if (report.path === 'ocr') {\n console.error(`${path.basename(dest).padEnd(32)} OCR path heads=${report.headings}(junk ${report.junkHeadings}) ` + `paras=${report.paragraphs} callouts=${report.callouts} floats=${report.floats ?? 0} dangling=${report.danglingLong} (long) ` + `~${report.charsPerPage} chars/page`);\n } else {\n console.error(\n `${path.basename(dest).padEnd(32)} body=${report.bodyFontHeight}pt heads=${report.headings}(junk ${report.junkHeadings}) ` +\n `lists=${report.listItems} paras=${report.paragraphs} callouts=${report.callouts} pairs=${report.joinedPairs} ` +\n `~${report.charsPerPage} chars/page` +\n (report.sparse ? ' ⚠️ implausibly sparse — pages are likely images; re-run with --ocr' : '')\n );\n }\n};\n\n// Parse one word-dump JSON line per word — key order is not guaranteed, parse\n// never grep. Non-JSON lines are skipped with a count, not fatal (the auditor applies the same policy).\nfunction parseWordLines(raw: string): { words: OcrWordInput[]; skipped: number } {\n const words: OcrWordInput[] = [];\n let skipped = 0;\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n words.push(JSON.parse(line));\n } catch {\n skipped++;\n }\n }\n return { words, skipped };\n}\n\nexport default extract;\n"],"names":["USAGE","FORMATS","TUNING_FLAGS","name","key","allowZero","isInt","extract","ctx","parsed","values","positionals","src","outArg","wordsPath","formatRaw","format","pages","m","first","last","tuning","spec","raw","value","ok","dpi","source","defaultExt","dest","onWarning","showProgress","onProgress","debugWordsPath","onWords","common","ocrCommon","words","skipped","content","report","extractOcr","pdfToMarkdown","markdown","analyze","toText","needsOcrFallback","ocrFallbackNotice","analysis","text","rest","includes","usageError","parseArgs","args","options","json","type","default","ocr","stdout","help","short","Object","fromEntries","map","f","allowPositionals","err","message","console","log","JSON","join","stringify","undefined","exec","Number","NaN","isFinite","Math","trunc","replace","error","process","stderr","isTTY","e","page","ms","trim","lines","w","entry","x","y","h","confidence","writeFileSync","length","parseWordLines","readFileSync","noOcr","pageMarkers","path","charsPerPage","fallback","write","out","basename","padEnd","headings","junkHeadings","paragraphs","callouts","floats","danglingLong","bodyFontHeight","listItems","joinedPairs","sparse","split","line","push","parse"],"mappings":"AAAA,2EAA2E;AAC3E,qHAAqH;;;;;+BA6PrH;;;eAAA;;;sBA5P4C;+DAC3B;wBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAM1B,IAAMA,QACJ,iGACA,yEACA,8GACA,8FACA,oDACA,uGACA;AAEF,IAAMC,UAAU;IAAC;IAAM;IAAO;CAAM;AAGpC,mHAAmH;AACnH,IAAMC,eAKA;IACJ;QACEC,MAAM;QACNC,KAAK;QACLC,WAAW;QACXC,OAAO;IACT;IACA;QAAEH,MAAM;QAAmBC,KAAK;IAAgB;IAChD;QAAED,MAAM;QAAgBC,KAAK;IAAc;IAC3C;QAAED,MAAM;QAAYC,KAAK;IAAU;IACnC;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"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/extract.ts"],"sourcesContent":["// extract command — parse this command's flags, call src/extract.ts, print\n// and write the result. No business logic here — the library returns data and throws; only the CLI prints and exits.\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { analyze } from '../analyze.ts';\nimport type { OcrWordInput } from '../extract.ts';\nimport { extractOcr, needsOcrFallback, ocrFallbackNotice, pdfToMarkdown } from '../extract.ts';\nimport type { Tuning } from '../geometry.ts';\nimport { toText } from '../render-analysis.ts';\nimport type { Analysis, Report } from '../types.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE =\n 'usage: pdf-to-md [extract] <file.pdf> [out.md] [--json] [--page-markers] [--ocr] [--no-ocr] ' +\n '[--pages N[-M]] [--stdout] [--words-json=FILE] [--debug-words=FILE] ' +\n '[--format md|txt|raw (default md; raw = Analysis JSON incl. the report; txt = reading-order plain text)] ' +\n '[--dpi=N (OCR render resolution, default 288; raise for tiny print or chart/label pages, ' +\n '>~400 measured worse on ordinary prose pages)] ' +\n '[--float-max-words=N] [--float-max-width=F] [--float-margin=F] [--para-gap=F] [--heading-scale=F] ' +\n '[--col-max-width=F] [--col-split=F] [--line-y-tol=F] [--line-height-ratio=F]';\n\nconst FORMATS = ['md', 'txt', 'raw'] as const;\ntype Format = (typeof FORMATS)[number];\n\n// A bad tuning-flag value (non-numeric, or <= 0 unless the flag allows zero) is a usage error, not a silent no-op.\nconst TUNING_FLAGS: {\n name: string;\n key: keyof Tuning;\n allowZero?: boolean;\n isInt?: boolean;\n}[] = [\n {\n name: 'float-max-words',\n key: 'floatMaxWords',\n allowZero: true,\n isInt: true,\n },\n { name: 'float-max-width', key: 'floatMaxWidth' },\n { name: 'float-margin', key: 'floatMargin' },\n { name: 'para-gap', key: 'paraGap' },\n { name: 'heading-scale', key: 'headingScale' },\n { name: 'col-max-width', key: 'colMaxWidth' },\n { name: 'col-split', key: 'colSplit' },\n { name: 'line-y-tol', key: 'lineYTol' },\n { name: 'line-height-ratio', key: 'lineHeightRatio' },\n];\n\nconst extract: Command = async (ctx) => {\n // --debug-words takes a required FILE value; a bare --debug-words is a\n // usage error, checked before parseArgs so it can't silently swallow the next token as its value.\n if (ctx.rest.includes('--debug-words')) {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n json: { type: 'boolean', default: false },\n 'page-markers': { type: 'boolean', default: false },\n ocr: { type: 'boolean', default: false },\n 'no-ocr': { type: 'boolean', default: false },\n stdout: { type: 'boolean', default: false },\n 'debug-words': { type: 'string' },\n help: { type: 'boolean', default: false, short: 'h' },\n pages: { type: 'string' },\n dpi: { type: 'string' },\n format: { type: 'string', default: 'md' },\n 'words-json': { type: 'string' },\n ...Object.fromEntries(TUNING_FLAGS.map((f) => [f.name, { type: 'string' as const }])),\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const values = parsed.values as Record<string, string | boolean | undefined>;\n const positionals = parsed.positionals;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [src, outArg] = positionals;\n const wordsPath = values['words-json'] as string | undefined;\n if (!src && !wordsPath) ctx.usageError(USAGE);\n\n const formatRaw = values.format as string;\n if (!(FORMATS as readonly string[]).includes(formatRaw)) {\n ctx.usageError(`${USAGE}\\n--format must be one of ${FORMATS.join('|')} (got ${JSON.stringify(formatRaw)})`);\n }\n const format = formatRaw as Format;\n\n // --pages: a malformed spec is a usage error; out-of-range page NUMBERS\n // clamp instead (collect.ts / the engine apply the same clamping policy).\n let pages: { first: number; last: number } | undefined;\n if (values.pages !== undefined) {\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(values.pages as string);\n const first = m ? Number(m[1]) : Number.NaN;\n const last = m ? (m[2] !== undefined ? Number(m[2]) : first) : Number.NaN;\n if (!m || first < 1 || last < first) {\n ctx.usageError(`${USAGE}\\n--pages requires N or N-M, N >= 1, M >= N (got ${JSON.stringify(values.pages)})`);\n }\n pages = { first, last };\n }\n\n const tuning: Partial<Tuning> = {};\n for (const spec of TUNING_FLAGS) {\n const raw = values[spec.name] as string | undefined;\n if (raw === undefined) continue;\n const value = Number(raw);\n const ok = raw !== '' && Number.isFinite(value) && (spec.allowZero ? value >= 0 : value > 0);\n if (!ok) {\n ctx.usageError(`${USAGE}\\n--${spec.name} requires a ${spec.allowZero ? 'non-negative' : 'positive'} number (got ${JSON.stringify(raw)})`);\n }\n (tuning[spec.key] as number) = spec.isInt ? Math.trunc(value) : value;\n }\n\n // --dpi: page-render resolution, validated like the tuning flags. Default\n // 288 is the measured operating point; >~400 measured WORSE on ordinary pages — not a \"bigger is safer\" knob.\n let dpi: number | undefined;\n if (values.dpi !== undefined) {\n const raw = values.dpi as string;\n const value = Number(raw);\n if (raw === '' || !Number.isFinite(value) || value <= 0) {\n ctx.usageError(`${USAGE}\\n--dpi requires a positive number (got ${JSON.stringify(raw)})`);\n }\n dpi = value;\n }\n\n // In --words-json mode there may be no PDF positional; the words file\n // stands in for naming, extension stripped so the default dest can never overwrite the input. Default extension follows --format.\n const source = src ?? (wordsPath as string);\n const defaultExt = format === 'raw' ? 'json' : format === 'txt' ? 'txt' : 'md';\n const dest = outArg || `${source.replace(/\\.(pdf|jsonl)$/i, '')}.${defaultExt}`;\n\n const onWarning = (m: string) => console.error(m);\n const showProgress = process.stderr.isTTY;\n // onProgress carries per-page timing/count only; human-readable\n // diagnostics (e.g. the sparse-retry notice) arrive via onWarning instead, so they print regardless of TTY-ness.\n const onProgress = (e: { type: 'page'; page: number; words: number; ms: number }) => {\n if (showProgress) console.error(`p${e.page}: ${e.words} words, ${e.ms}ms`);\n };\n const debugWordsPath = values['debug-words'] as string | undefined;\n if (debugWordsPath !== undefined && debugWordsPath.trim() === '') {\n ctx.usageError(`${USAGE}\\n--debug-words requires a value: --debug-words=FILE`);\n }\n // The severity-1 audit instrument: every recognized word as clean JSON\n // lines to its own file. stderr stays a human channel (mixed prose), never a dump target — this file is guaranteed byte-for-byte parseable.\n const onWords = debugWordsPath\n ? (words: OcrWordInput[]) => {\n const lines = words.map((w) => {\n const entry: OcrWordInput = { page: w.page, text: w.text, x: w.x, y: w.y, w: w.w, h: w.h };\n if (w.confidence !== undefined) entry.confidence = w.confidence;\n return JSON.stringify(entry);\n });\n writeFileSync(debugWordsPath, lines.length ? `${lines.join('\\n')}\\n` : '');\n }\n : undefined;\n\n const common = { pages, onWarning };\n const ocrCommon = {\n ...common,\n tuning,\n dpi,\n onProgress,\n onWords,\n };\n\n let words: OcrWordInput[] | undefined;\n let skipped = 0;\n if (wordsPath !== undefined) {\n ({ words, skipped } = parseWordLines(readFileSync(wordsPath, 'utf8')));\n if (skipped > 0) console.error(`--words-json: skipped ${skipped} non-JSON line(s)`);\n }\n\n let content: string;\n let report: Report;\n if (format === 'md') {\n let markdown: string;\n if (words !== undefined) {\n ({ markdown, report } = await extractOcr({ words }, ocrCommon));\n } else {\n ({ markdown, report } = await pdfToMarkdown(src, {\n ...ocrCommon,\n ocr: values.ocr as boolean,\n noOcr: values['no-ocr'] as boolean,\n pageMarkers: values['page-markers'] as boolean,\n }));\n }\n content = markdown;\n } else {\n // raw/txt: both render from an Analysis — raw IS the Analysis as JSON;\n // txt is toText(analysis). Mirrors pdfToMarkdown's own auto-OCR fallback decision so a different --format doesn't silently pick a different path.\n let analysis: Analysis;\n if (words !== undefined) {\n analysis = await analyze({ words }, { ...ocrCommon, path: 'ocr' });\n } else if (values.ocr) {\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr' });\n } else {\n const text = await analyze(src, { ...common, path: 'text', pageMarkers: values['page-markers'] as boolean });\n if (needsOcrFallback(text.report.charsPerPage) && !values['no-ocr']) {\n onWarning(ocrFallbackNotice(text.report.charsPerPage));\n analysis = await analyze(src, { ...ocrCommon, path: 'ocr', fallback: true });\n } else {\n analysis = text;\n }\n }\n report = analysis.report;\n content = format === 'raw' ? JSON.stringify(analysis, null, 1) : toText(analysis);\n }\n\n if (values.stdout) process.stdout.write(content);\n else writeFileSync(dest, content);\n\n // The library's Report stays clean of source/out; --json consumers keep\n // report.json files around and need to know which input produced each one, so the CLI (only) decorates the printed JSON with source/out here.\n if (values.json) console.log(JSON.stringify({ source, out: dest, ...report }, null, 1));\n else if (report.path === 'ocr') {\n console.error(`${path.basename(dest).padEnd(32)} OCR path heads=${report.headings}(junk ${report.junkHeadings}) ` + `paras=${report.paragraphs} callouts=${report.callouts} floats=${report.floats ?? 0} dangling=${report.danglingLong} (long) ` + `~${report.charsPerPage} chars/page`);\n } else {\n console.error(\n `${path.basename(dest).padEnd(32)} body=${report.bodyFontHeight}pt heads=${report.headings}(junk ${report.junkHeadings}) ` +\n `lists=${report.listItems} paras=${report.paragraphs} callouts=${report.callouts} pairs=${report.joinedPairs} ` +\n `~${report.charsPerPage} chars/page` +\n (report.sparse ? ' ⚠️ implausibly sparse — pages are likely images; re-run with --ocr' : '')\n );\n }\n};\n\n// Parse one word-dump JSON line per word — key order is not guaranteed, parse\n// never grep. Non-JSON lines are skipped with a count, not fatal (the auditor applies the same policy).\nfunction parseWordLines(raw: string): { words: OcrWordInput[]; skipped: number } {\n const words: OcrWordInput[] = [];\n let skipped = 0;\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue;\n try {\n words.push(JSON.parse(line));\n } catch {\n skipped++;\n }\n }\n return { words, skipped };\n}\n\nexport default extract;\n"],"names":["USAGE","FORMATS","TUNING_FLAGS","name","key","allowZero","isInt","extract","ctx","parsed","values","positionals","src","outArg","wordsPath","formatRaw","format","pages","m","first","last","tuning","spec","raw","value","ok","dpi","source","defaultExt","dest","onWarning","showProgress","onProgress","debugWordsPath","onWords","common","ocrCommon","words","skipped","content","report","markdown","analysis","text","rest","includes","usageError","parseArgs","args","options","json","type","default","ocr","stdout","help","short","Object","fromEntries","map","f","allowPositionals","err","message","console","log","JSON","join","stringify","undefined","exec","Number","NaN","isFinite","Math","trunc","replace","error","process","stderr","isTTY","e","page","ms","trim","lines","w","entry","x","y","h","confidence","writeFileSync","length","parseWordLines","readFileSync","extractOcr","pdfToMarkdown","noOcr","pageMarkers","analyze","path","needsOcrFallback","charsPerPage","ocrFallbackNotice","fallback","toText","write","out","basename","padEnd","headings","junkHeadings","paragraphs","callouts","floats","danglingLong","bodyFontHeight","listItems","joinedPairs","sparse","split","line","push","parse"],"mappings":"AAAA,2EAA2E;AAC3E,qHAAqH;;;;;+BA0PrH;;;eAAA;;;sBAzP4C;+DAC3B;wBACS;yBACF;yBAEuD;gCAExD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIvB,IAAMA,QACJ,iGACA,yEACA,8GACA,8FACA,oDACA,uGACA;AAEF,IAAMC,UAAU;IAAC;IAAM;IAAO;CAAM;AAGpC,mHAAmH;AACnH,IAAMC,eAKA;IACJ;QACEC,MAAM;QACNC,KAAK;QACLC,WAAW;QACXC,OAAO;IACT;IACA;QAAEH,MAAM;QAAmBC,KAAK;IAAgB;IAChD;QAAED,MAAM;QAAgBC,KAAK;IAAc;IAC3C;QAAED,MAAM;QAAYC,KAAK;IAAU;IACnC;QAAED,MAAM;QAAiBC,KAAK;IAAe;IAC7C;QAAED,MAAM;QAAiBC,KAAK;IAAc;IAC5C;QAAED,MAAM;QAAaC,KAAK;IAAW;IACrC;QAAED,MAAM;QAAcC,KAAK;IAAW;IACtC;QAAED,MAAM;QAAqBC,KAAK;IAAkB;CACrD;AAED,IAAMG,UAAmB,iBAAOC;;YAOxBC,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C,SAAkCxE,OAA1BA,OAAO8E,SAAS,EAAC,WAAuC9E,OAA9BA,OAAOyE,UAAU,EAAC,cAAqCzE,OAAzBA,OAAO0E,QAAQ,EAAC,WAA4B,OAAnB1E,OAAO+E,WAAW,EAAC,OAC7G,AAAC,IAAuB,OAApB/E,OAAO+D,YAAY,EAAC,iBACvB/D,CAAAA,OAAOgF,MAAM,GAAG,0EAA0E,EAAC;oBAElG;;;;;;IACF;;AAEA,8EAA8E;AAC9E,wGAAwG;AACxG,SAAS1B,eAAevE,GAAW;IACjC,IAAMc,QAAwB,EAAE;IAChC,IAAIC,UAAU;QACT,kCAAA,2BAAA;;QAAL,QAAK,YAAcf,IAAIkG,KAAK,CAAC,0BAAxB,SAAA,6BAAA,QAAA,yBAAA,iCAA+B;YAA/B,IAAMC,OAAN;YACH,IAAI,CAACA,KAAKtC,IAAI,IAAI;YAClB,IAAI;gBACF/C,MAAMsF,IAAI,CAACzD,KAAK0D,KAAK,CAACF;YACxB,EAAE,eAAM;gBACNpF;YACF;QACF;;QAPK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAQL,OAAO;QAAED,OAAAA;QAAOC,SAAAA;IAAQ;AAC1B;IAEA,WAAe/B"}
@@ -14,6 +14,8 @@ var _nodefs = require("node:fs");
14
14
  var _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
15
15
  var _nodeutil = require("node:util");
16
16
  var _errorsts = require("../errors.js");
17
+ var _pdfopents = require("../pdf-open.js");
18
+ var _rasterts = require("../raster.js");
17
19
  function _array_like_to_array(arr, len) {
18
20
  if (len == null || len > arr.length) len = arr.length;
19
21
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
@@ -53,36 +55,6 @@ function _interop_require_default(obj) {
53
55
  default: obj
54
56
  };
55
57
  }
56
- function _getRequireWildcardCache(nodeInterop) {
57
- if (typeof WeakMap !== "function") return null;
58
- var cacheBabelInterop = new WeakMap();
59
- var cacheNodeInterop = new WeakMap();
60
- return (_getRequireWildcardCache = function(nodeInterop) {
61
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
62
- })(nodeInterop);
63
- }
64
- function _interop_require_wildcard(obj, nodeInterop) {
65
- if (!nodeInterop && obj && obj.__esModule) return obj;
66
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") return {
67
- default: obj
68
- };
69
- var cache = _getRequireWildcardCache(nodeInterop);
70
- if (cache && cache.has(obj)) return cache.get(obj);
71
- var newObj = {
72
- __proto__: null
73
- };
74
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
75
- for(var key in obj){
76
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
77
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
78
- if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
79
- else newObj[key] = obj[key];
80
- }
81
- }
82
- newObj.default = obj;
83
- if (cache) cache.set(obj, newObj);
84
- return newObj;
85
- }
86
58
  function _iterable_to_array_limit(arr, i) {
87
59
  var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
88
60
  if (_i == null) return;
@@ -223,7 +195,7 @@ function _unsupported_iterable_to_array(o, minLen) {
223
195
  var USAGE = 'usage: pdf-to-md render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]';
224
196
  var render = function render(ctx) {
225
197
  return _async_to_generator(function() {
226
- var _values_out, parsed, values, positionals, _positionals, pdfPath, spec, m, firstPage, lastPage, dpi, outDir, stem, _ref, awaitPdfOpen, openPdfForRender, renderLoadedPage, loadingTask, doc, n, png, outPath;
198
+ var _values_out, parsed, values, positionals, _positionals, pdfPath, spec, m, firstPage, lastPage, dpi, outDir, stem, loadingTask, doc, n, png, outPath;
227
199
  return _ts_generator(this, function(_state) {
228
200
  switch(_state.label){
229
201
  case 0:
@@ -275,36 +247,20 @@ var render = function render(ctx) {
275
247
  recursive: true
276
248
  });
277
249
  stem = _nodepath.default.basename(pdfPath, _nodepath.default.extname(pdfPath)).replaceAll(' ', '-');
278
- return [
279
- 4,
280
- Promise.resolve().then(function() {
281
- return /*#__PURE__*/ _interop_require_wildcard(require("../pdf-open.js"));
282
- })
283
- ];
250
+ loadingTask = (0, _pdfopents.openPdfForRender)(pdfPath);
251
+ _state.label = 1;
284
252
  case 1:
285
- _ref = _state.sent(), awaitPdfOpen = _ref.awaitPdfOpen, openPdfForRender = _ref.openPdfForRender;
286
- return [
287
- 4,
288
- Promise.resolve().then(function() {
289
- return /*#__PURE__*/ _interop_require_wildcard(require("../raster.js"));
290
- })
291
- ];
292
- case 2:
293
- renderLoadedPage = _state.sent().renderLoadedPage;
294
- loadingTask = openPdfForRender(pdfPath);
295
- _state.label = 3;
296
- case 3:
297
253
  _state.trys.push([
298
- 3,
254
+ 1,
299
255
  ,
300
- 9,
301
- 11
256
+ 7,
257
+ 9
302
258
  ]);
303
259
  return [
304
260
  4,
305
- awaitPdfOpen(loadingTask, pdfPath)
261
+ (0, _pdfopents.awaitPdfOpen)(loadingTask, pdfPath)
306
262
  ];
307
- case 4:
263
+ case 2:
308
264
  doc = _state.sent();
309
265
  // Whole-range check before any file is written, so a partly-valid range
310
266
  // fails atomically; renderLoadedPage re-validates per page.
@@ -312,44 +268,44 @@ var render = function render(ctx) {
312
268
  throw new _errorsts.PdfToMdError('PAGE_RANGE', "page range ".concat(firstPage, "-").concat(lastPage, " is outside this document (1-").concat(doc.numPages, ")"));
313
269
  }
314
270
  n = firstPage;
315
- _state.label = 5;
316
- case 5:
271
+ _state.label = 3;
272
+ case 3:
317
273
  if (!(n <= lastPage)) return [
318
274
  3,
319
- 8
275
+ 6
320
276
  ];
321
277
  return [
322
278
  4,
323
- renderLoadedPage(doc, n, dpi)
279
+ (0, _rasterts.renderLoadedPage)(doc, n, dpi)
324
280
  ];
325
- case 6:
281
+ case 4:
326
282
  png = _state.sent().png;
327
283
  outPath = _nodepath.default.join(outDir, "".concat(stem, "-p").concat(n, ".png"));
328
284
  (0, _nodefs.writeFileSync)(outPath, png);
329
285
  console.log(outPath);
330
- _state.label = 7;
331
- case 7:
286
+ _state.label = 5;
287
+ case 5:
332
288
  n++;
333
289
  return [
334
290
  3,
335
- 5
291
+ 3
336
292
  ];
337
- case 8:
293
+ case 6:
338
294
  return [
339
295
  3,
340
- 11
296
+ 9
341
297
  ];
342
- case 9:
298
+ case 7:
343
299
  return [
344
300
  4,
345
301
  loadingTask.destroy()
346
302
  ];
347
- case 10:
303
+ case 8:
348
304
  _state.sent();
349
305
  return [
350
306
  7
351
307
  ];
352
- case 11:
308
+ case 9:
353
309
  return [
354
310
  2
355
311
  ];
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/render.ts"],"sourcesContent":["// render command — render PDF pages to PNG for human/vision-model\n// verification (extraction output is a claim; the page itself is the truth). Thin wrapper: parse flags, call src/raster.ts, write files.\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { PdfToMdError } from '../errors.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE = 'usage: pdf-to-md render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]';\n\nconst render: Command = async (ctx) => {\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n dpi: { type: 'string', default: '288', short: 'd' },\n out: { type: 'string', short: 'o' },\n help: { type: 'boolean', default: false, short: 'h' },\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const { values, positionals } = parsed;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [pdfPath, spec] = positionals;\n if (!pdfPath || !spec) ctx.usageError(USAGE);\n\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(spec);\n if (m === null) throw ctx.usageError(`${USAGE}\\ncould not parse page spec: ${spec}`);\n const firstPage = Number(m[1]);\n const lastPage = m[2] !== undefined ? Number(m[2]) : firstPage;\n if (!(firstPage >= 1) || !(lastPage >= firstPage)) throw ctx.usageError(`${USAGE}\\ninvalid page spec: ${spec}`);\n\n const dpi = Number.parseFloat(values.dpi as string);\n if (!(dpi > 0)) ctx.usageError(`${USAGE}\\n--dpi must be positive`);\n\n const outDir = values.out ?? process.cwd();\n mkdirSync(outDir, { recursive: true });\n const stem = path.basename(pdfPath, path.extname(pdfPath)).replaceAll(' ', '-');\n\n // Imported here, not at module top: keeps pdfjs/canvas out of every other command's startup.\n const { awaitPdfOpen, openPdfForRender } = await import('../pdf-open.ts');\n const { renderLoadedPage } = await import('../raster.ts');\n const loadingTask = openPdfForRender(pdfPath);\n try {\n const doc = await awaitPdfOpen(loadingTask, pdfPath);\n\n // Whole-range check before any file is written, so a partly-valid range\n // fails atomically; renderLoadedPage re-validates per page.\n if (lastPage > doc.numPages) {\n throw new PdfToMdError('PAGE_RANGE', `page range ${firstPage}-${lastPage} is outside this document (1-${doc.numPages})`);\n }\n for (let n = firstPage; n <= lastPage; n++) {\n const { png } = await renderLoadedPage(doc, n, dpi);\n const outPath = path.join(outDir, `${stem}-p${n}.png`);\n writeFileSync(outPath, png);\n console.log(outPath);\n }\n } finally {\n await loadingTask.destroy();\n }\n};\n\nexport default render;\n"],"names":["USAGE","render","ctx","values","parsed","positionals","pdfPath","spec","m","firstPage","lastPage","dpi","outDir","stem","awaitPdfOpen","openPdfForRender","renderLoadedPage","loadingTask","doc","n","png","outPath","parseArgs","args","rest","options","type","default","short","out","help","allowPositionals","err","usageError","message","console","log","exec","Number","undefined","parseFloat","process","cwd","mkdirSync","recursive","path","basename","extname","replaceAll","numPages","PdfToMdError","join","writeFileSync","destroy"],"mappings":"AAAA,kEAAkE;AAClE,yIAAyI;;;;;+BAwEzI;;;eAAA;;;sBAvEyC;+DACxB;wBACS;wBACG;;;;;;;;;;;;;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O;;;;oBAClB;;wBAAMM,iBAAiBE,KAAKC,GAAGR;;;oBAAvCS,MAAQ,cAARA;oBACFC,UAAUwB,iBAAI,CAACM,IAAI,CAACvC,QAAQ,AAAC,GAAWO,OAATN,MAAK,MAAM,OAAFM,GAAE;oBAChDiC,IAAAA,qBAAa,EAAC/B,SAASD;oBACvBe,QAAQC,GAAG,CAACf;;;oBAJyBF;;;;;;;;;;;oBAOvC;;wBAAMF,YAAYoC,OAAO;;;oBAAzB;;;;;;;;;;IAEJ;;IAEA,WAAepD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli/render.ts"],"sourcesContent":["// render command — render PDF pages to PNG for human/vision-model\n// verification (extraction output is a claim; the page itself is the truth). Thin wrapper: parse flags, call src/raster.ts, write files.\nimport { mkdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { PdfToMdError } from '../errors.ts';\nimport { awaitPdfOpen, openPdfForRender } from '../pdf-open.ts';\nimport { renderLoadedPage } from '../raster.ts';\nimport type { Command } from './types.ts';\n\nconst USAGE = 'usage: pdf-to-md render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]';\n\nconst render: Command = async (ctx) => {\n const parsed = (() => {\n try {\n return parseArgs({\n args: ctx.rest,\n options: {\n dpi: { type: 'string', default: '288', short: 'd' },\n out: { type: 'string', short: 'o' },\n help: { type: 'boolean', default: false, short: 'h' },\n },\n allowPositionals: true,\n });\n } catch (err) {\n // usageError exits; the throw is dead code that tells the compiler so.\n throw ctx.usageError(`${(err as Error).message}\\n${USAGE}`);\n }\n })();\n const { values, positionals } = parsed;\n\n if (values.help) {\n console.log(USAGE);\n return;\n }\n\n const [pdfPath, spec] = positionals;\n if (!pdfPath || !spec) ctx.usageError(USAGE);\n\n const m = /^(\\d+)(?:-(\\d+))?$/.exec(spec);\n if (m === null) throw ctx.usageError(`${USAGE}\\ncould not parse page spec: ${spec}`);\n const firstPage = Number(m[1]);\n const lastPage = m[2] !== undefined ? Number(m[2]) : firstPage;\n if (!(firstPage >= 1) || !(lastPage >= firstPage)) throw ctx.usageError(`${USAGE}\\ninvalid page spec: ${spec}`);\n\n const dpi = Number.parseFloat(values.dpi as string);\n if (!(dpi > 0)) ctx.usageError(`${USAGE}\\n--dpi must be positive`);\n\n const outDir = values.out ?? process.cwd();\n mkdirSync(outDir, { recursive: true });\n const stem = path.basename(pdfPath, path.extname(pdfPath)).replaceAll(' ', '-');\n\n const loadingTask = openPdfForRender(pdfPath);\n try {\n const doc = await awaitPdfOpen(loadingTask, pdfPath);\n\n // Whole-range check before any file is written, so a partly-valid range\n // fails atomically; renderLoadedPage re-validates per page.\n if (lastPage > doc.numPages) {\n throw new PdfToMdError('PAGE_RANGE', `page range ${firstPage}-${lastPage} is outside this document (1-${doc.numPages})`);\n }\n for (let n = firstPage; n <= lastPage; n++) {\n const { png } = await renderLoadedPage(doc, n, dpi);\n const outPath = path.join(outDir, `${stem}-p${n}.png`);\n writeFileSync(outPath, png);\n console.log(outPath);\n }\n } finally {\n await loadingTask.destroy();\n }\n};\n\nexport default render;\n"],"names":["USAGE","render","ctx","values","parsed","positionals","pdfPath","spec","m","firstPage","lastPage","dpi","outDir","stem","loadingTask","doc","n","png","outPath","parseArgs","args","rest","options","type","default","short","out","help","allowPositionals","err","usageError","message","console","log","exec","Number","undefined","parseFloat","process","cwd","mkdirSync","recursive","path","basename","extname","replaceAll","openPdfForRender","awaitPdfOpen","numPages","PdfToMdError","renderLoadedPage","join","writeFileSync","destroy"],"mappings":"AAAA,kEAAkE;AAClE,yIAAyI;;;;;+BAuEzI;;;eAAA;;;sBAtEyC;+DACxB;wBACS;wBACG;yBACkB;wBACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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J;;IAEA,WAAepD"}
@@ -1,2 +1 @@
1
- export declare function isBelowNodeFloor(version: string, floor: string): boolean | null;
2
1
  export default function cli(argv: string[], name: string): Promise<void>;
package/dist/cjs/cli.d.ts CHANGED
@@ -1,2 +1 @@
1
- export declare function isBelowNodeFloor(version: string, floor: string): boolean | null;
2
1
  export default function cli(argv: string[], name: string): Promise<void>;
package/dist/cjs/cli.js CHANGED
@@ -4,33 +4,17 @@
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- function _export(target, all) {
8
- for(var name in all)Object.defineProperty(target, name, {
9
- enumerable: true,
10
- get: Object.getOwnPropertyDescriptor(all, name).get
11
- });
12
- }
13
- _export(exports, {
14
- get // Thrown errors -> exit 1 with the message verbatim; usage errors exit 2.
15
- default () {
7
+ Object.defineProperty(exports, // Thrown errors -> exit 1 with the message verbatim; usage errors exit 2.
8
+ "default", {
9
+ enumerable: true,
10
+ get: function() {
16
11
  return cli;
17
- },
18
- get isBelowNodeFloor () {
19
- return isBelowNodeFloor;
20
12
  }
21
13
  });
22
14
  var _nodefs = require("node:fs");
23
15
  var _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
24
16
  var _nodeurl = require("node:url");
25
17
  var _indexts = require("./cli/index.js");
26
- function _array_like_to_array(arr, len) {
27
- if (len == null || len > arr.length) len = arr.length;
28
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
29
- return arr2;
30
- }
31
- function _array_with_holes(arr) {
32
- if (Array.isArray(arr)) return arr;
33
- }
34
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
35
19
  try {
36
20
  var info = gen[key](arg);
@@ -62,36 +46,6 @@ function _interop_require_default(obj) {
62
46
  default: obj
63
47
  };
64
48
  }
65
- function _iterable_to_array_limit(arr, i) {
66
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
67
- if (_i == null) return;
68
- var _arr = [];
69
- var _n = true;
70
- var _d = false;
71
- var _s, _e;
72
- try {
73
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
74
- _arr.push(_s.value);
75
- if (i && _arr.length === i) break;
76
- }
77
- } catch (err) {
78
- _d = true;
79
- _e = err;
80
- } finally{
81
- try {
82
- if (!_n && _i["return"] != null) _i["return"]();
83
- } finally{
84
- if (_d) throw _e;
85
- }
86
- }
87
- return _arr;
88
- }
89
- function _non_iterable_rest() {
90
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
91
- }
92
- function _sliced_to_array(arr, i) {
93
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
94
- }
95
49
  function _ts_generator(thisArg, body) {
96
50
  var f, y, t, _ = {
97
51
  label: 0,
@@ -191,14 +145,6 @@ function _ts_generator(thisArg, body) {
191
145
  };
192
146
  }
193
147
  }
194
- function _unsupported_iterable_to_array(o, minLen) {
195
- if (!o) return;
196
- if (typeof o === "string") return _array_like_to_array(o, minLen);
197
- var n = Object.prototype.toString.call(o).slice(8, -1);
198
- if (n === "Object" && o.constructor) n = o.constructor.name;
199
- if (n === "Map" || n === "Set") return Array.from(n);
200
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
201
- }
202
148
  // __dirname (CJS) or its ESM equivalent, then two fixed hops up to the
203
149
  // package root. NOT `import.meta.resolve('pdf-to-md/package.json')` — Node's self-reference lookup throws ERR_MODULE_NOT_FOUND from a file this deep; a location-relative path is stable across both build targets.
204
150
  var __dirname = _nodepath.default.dirname(typeof __filename !== 'undefined' ? __filename : (0, _nodeurl.fileURLToPath)(require("url").pathToFileURL(__filename).toString()));
@@ -212,43 +158,15 @@ function packageVersion() {
212
158
  return 'unknown';
213
159
  }
214
160
  }
215
- function isBelowNodeFloor(version, floor) {
216
- var parts = function parts(v) {
217
- return v.replace(/^v/, '').replace(/^>=/, '').split('.').map(Number);
218
- };
219
- var v = parts(version);
220
- var f = parts(floor);
221
- if (v.length !== 3 || f.length !== 3 || v.some(Number.isNaN) || f.some(Number.isNaN)) return null;
222
- var _v = _sliced_to_array(v, 3), rMaj = _v[0], rMin = _v[1], rPat = _v[2];
223
- var _f = _sliced_to_array(f, 3), fMaj = _f[0], fMin = _f[1], fPat = _f[2];
224
- return rMaj !== fMaj ? rMaj < fMaj : rMin !== fMin ? rMin < fMin : rPat < fPat;
225
- }
226
- // Reads engines.node from package.json (kept as the single source of truth,
227
- // not hardcoded here) and returns it iff process.version is below it.
228
- function belowNodeFloor() {
229
- var version = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : process.version;
230
- try {
231
- var _pkg_engines;
232
- var pkgPath = _nodepath.default.resolve(__dirname, '..', '..', 'package.json');
233
- var pkg = JSON.parse((0, _nodefs.readFileSync)(pkgPath, 'utf8'));
234
- var floor = (_pkg_engines = pkg.engines) === null || _pkg_engines === void 0 ? void 0 : _pkg_engines.node;
235
- if (!floor) return null;
236
- return isBelowNodeFloor(version, floor) ? floor.replace(/^>=/, '') : null;
237
- } catch (unused) {
238
- return null;
239
- }
240
- }
241
161
  function usage(name) {
242
162
  return "usage: ".concat(name, " <file.pdf> [out.md] [flags...] convert a PDF to markdown\n") + " ".concat(name, " extract <file.pdf> [out.md] [flags...] (same, explicit)\n") + " ".concat(name, " render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]\n") + " ".concat(name, " audit <words.jsonl> <file.md> severity-1 word-loss check\n") + " ".concat(name, " --version | --help\n") + '\n' + 'extract flags:\n' + ' --ocr force the OCR path (image-only/scanned pages)\n' + ' --no-ocr never fall back to OCR; keep sparse text output\n' + ' --pages N[-M] convert only these 1-based source pages\n' + ' --stdout write markdown to stdout instead of a file\n' + ' --json print the full QA report as JSON\n' + ' --page-markers emit a "### pN" heading per page\n' + ' --format md|txt|raw output format (default md; raw = Analysis JSON incl. the\n' + ' report; txt = reading-order plain text)\n' + ' --words-json=FILE OCR path from a recognized-word dump (offline replay)\n' + ' --debug-words=FILE dump every recognized word as JSON lines to FILE\n' + ' --dpi=N OCR render resolution (default 288; raise for tiny print or\n' + ' chart/label pages, >~400 measured worse on ordinary prose)\n' + '\n' + "extract tuning (measured defaults; see README's tuning table):\n" + ' --float-max-words=N --float-max-width=F --float-margin=F --para-gap=F\n' + ' --heading-scale=F --col-max-width=F --col-split=F --line-y-tol=F\n' + ' --line-height-ratio=F\n' + '\n' + 'examples:\n' + " ".concat(name, " book.pdf # text layer -> book.md (auto-OCR if scanned)\n") + " ".concat(name, " scan.pdf out.md --ocr --json # force OCR, print the QA report\n") + " ".concat(name, " book.pdf --pages 27-31 --stdout # re-extract a page range to stdout\n") + " ".concat(name, " render book.pdf 27 # render p27 to PNG for eyeballing (288 dpi)\n") + " ".concat(name, " audit words.jsonl book.md # check no recognized word was lost");
243
163
  }
244
164
  function cli(argv, name) {
245
165
  return _async_to_generator(function() {
246
- var floor, ctx, load, err;
166
+ var ctx, load, err;
247
167
  return _ts_generator(this, function(_state) {
248
168
  switch(_state.label){
249
169
  case 0:
250
- floor = belowNodeFloor();
251
- if (floor) console.error("".concat(name, ": Node ").concat(process.version, " is below the required >=").concat(floor, " — the OCR path can silently find no words instead of erroring; upgrade Node."));
252
170
  if (argv[0] === '--version' || argv[0] === '-v') {
253
171
  console.log(packageVersion());
254
172
  return [
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli.ts"],"sourcesContent":["// Parsing and dispatch only. Commands live in src/cli/, one file each,\n// lazy-loaded — nothing tree- or dependency-heavy may be imported at the top of this file (`render` must never load the OCR engine, `--version` must load almost nothing).\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { COMMANDS } from './cli/index.ts';\nimport type { Ctx } from './cli/types.ts';\n\n// __dirname (CJS) or its ESM equivalent, then two fixed hops up to the\n// package root. NOT `import.meta.resolve('pdf-to-md/package.json')` — Node's self-reference lookup throws ERR_MODULE_NOT_FOUND from a file this deep; a location-relative path is stable across both build targets.\nconst __dirname = path.dirname(typeof __filename !== 'undefined' ? __filename : fileURLToPath(import.meta.url));\n\nfunction packageVersion(): string {\n try {\n const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { version?: string };\n return pkg.version ?? 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n// Exported so the comparison is unit-testable without spawning a subprocess\n// with a faked Node version. null means unparseable input, not \"not below\".\nexport function isBelowNodeFloor(version: string, floor: string): boolean | null {\n const parts = (v: string) => v.replace(/^v/, '').replace(/^>=/, '').split('.').map(Number);\n const v = parts(version);\n const f = parts(floor);\n if (v.length !== 3 || f.length !== 3 || v.some(Number.isNaN) || f.some(Number.isNaN)) return null;\n const [rMaj, rMin, rPat] = v;\n const [fMaj, fMin, fPat] = f;\n return rMaj !== fMaj ? rMaj < fMaj : rMin !== fMin ? rMin < fMin : rPat < fPat;\n}\n\n// Reads engines.node from package.json (kept as the single source of truth,\n// not hardcoded here) and returns it iff process.version is below it.\nfunction belowNodeFloor(version = process.version): string | null {\n try {\n const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { engines?: { node?: string } };\n const floor = pkg.engines?.node;\n if (!floor) return null;\n return isBelowNodeFloor(version, floor) ? floor.replace(/^>=/, '') : null;\n } catch {\n return null;\n }\n}\n\nfunction usage(name: string): string {\n return (\n `usage: ${name} <file.pdf> [out.md] [flags...] convert a PDF to markdown\\n` +\n ` ${name} extract <file.pdf> [out.md] [flags...] (same, explicit)\\n` +\n ` ${name} render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]\\n` +\n ` ${name} audit <words.jsonl> <file.md> severity-1 word-loss check\\n` +\n ` ${name} --version | --help\\n` +\n '\\n' +\n 'extract flags:\\n' +\n ' --ocr force the OCR path (image-only/scanned pages)\\n' +\n ' --no-ocr never fall back to OCR; keep sparse text output\\n' +\n ' --pages N[-M] convert only these 1-based source pages\\n' +\n ' --stdout write markdown to stdout instead of a file\\n' +\n ' --json print the full QA report as JSON\\n' +\n ` --page-markers emit a \"### pN\" heading per page\\n` +\n ' --format md|txt|raw output format (default md; raw = Analysis JSON incl. the\\n' +\n ' report; txt = reading-order plain text)\\n' +\n ' --words-json=FILE OCR path from a recognized-word dump (offline replay)\\n' +\n ' --debug-words=FILE dump every recognized word as JSON lines to FILE\\n' +\n ' --dpi=N OCR render resolution (default 288; raise for tiny print or\\n' +\n ' chart/label pages, >~400 measured worse on ordinary prose)\\n' +\n '\\n' +\n `extract tuning (measured defaults; see README's tuning table):\\n` +\n ' --float-max-words=N --float-max-width=F --float-margin=F --para-gap=F\\n' +\n ' --heading-scale=F --col-max-width=F --col-split=F --line-y-tol=F\\n' +\n ' --line-height-ratio=F\\n' +\n '\\n' +\n 'examples:\\n' +\n ` ${name} book.pdf # text layer -> book.md (auto-OCR if scanned)\\n` +\n ` ${name} scan.pdf out.md --ocr --json # force OCR, print the QA report\\n` +\n ` ${name} book.pdf --pages 27-31 --stdout # re-extract a page range to stdout\\n` +\n ` ${name} render book.pdf 27 # render p27 to PNG for eyeballing (288 dpi)\\n` +\n ` ${name} audit words.jsonl book.md # check no recognized word was lost`\n );\n}\n\n// Thrown errors -> exit 1 with the message verbatim; usage errors exit 2.\nexport default async function cli(argv: string[], name: string): Promise<void> {\n const floor = belowNodeFloor();\n if (floor) console.error(`${name}: Node ${process.version} is below the required >=${floor} — the OCR path can silently find no words instead of erroring; upgrade Node.`);\n\n if (argv[0] === '--version' || argv[0] === '-v') {\n console.log(packageVersion());\n return;\n }\n if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {\n // No args is a usage ERROR (bare `pdf-to-md` can't do anything); asking\n // for --help is not.\n if (argv.length === 0) {\n console.error(usage(name));\n process.exit(2);\n }\n console.log(`${name} v${packageVersion()}`);\n console.log('');\n console.log(usage(name));\n return;\n }\n\n const ctx: Ctx = {\n name,\n rest: argv.slice(1),\n usageError(message) {\n console.error(message);\n process.exit(2);\n },\n };\n\n try {\n const load = COMMANDS[argv[0]];\n if (load) {\n await (await load()).default(ctx);\n } else {\n // Compat shim: `pdf-to-md file.pdf [...]` — any first word that isn't\n // a reserved command is extract's own first argument.\n ctx.rest = argv;\n await (await COMMANDS.extract()).default(ctx);\n }\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n}\n"],"names":["cli","isBelowNodeFloor","__dirname","path","dirname","__filename","fileURLToPath","packageVersion","pkg","pkgPath","resolve","JSON","parse","readFileSync","version","floor","parts","v","replace","split","map","Number","f","length","some","isNaN","rMaj","rMin","rPat","fMaj","fMin","fPat","belowNodeFloor","process","engines","node","usage","name","argv","ctx","load","err","console","error","log","exit","rest","slice","usageError","message","COMMANDS","default","extract"],"mappings":"AAAA,uEAAuE;AACvE,2KAA2K;;;;;;;;;;;;QAmF3K,0EAA0E;IAC1E;eAA8BA;;QA7DdC;eAAAA;;;sBAtBa;+DACZ;uBACa;uBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGzB,uEAAuE;AACvE,oNAAoN;AACpN,IAAMC,YAAYC,iBAAI,CAACC,OAAO,CAAC,OAAOC,eAAe,cAAcA,aAAaC,IAAAA,sBAAa,EAAC;AAE9F,SAASC;IACP,IAAI;YAGKC;QAFP,IAAMC,UAAUN,iBAAI,CAACO,OAAO,CAACR,WAAW,MAAM,MAAM;QACpD,IAAMM,MAAMG,KAAKC,KAAK,CAACC,IAAAA,oBAAY,EAACJ,SA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;4BACdhB,QAAQY,IAAI,CAAC;wBACf;oBACF;;;;;;;;;oBAGQL,OAAOU,iBAAQ,CAACZ,IAAI,CAAC,EAAE,CAAC;yBAC1BE,MAAAA;;;;oBACK;;wBAAMA;;;oBAAb;;wBAAO,cAAcW,OAAO,CAACZ;;;oBAA7B;;;;;;oBAEA,sEAAsE;oBACtE,sDAAsD;oBACtDA,IAAIO,IAAI,GAAGR;oBACJ;;wBAAMY,iBAAQ,CAACE,OAAO;;;oBAA7B;;wBAAO,cAA0BD,OAAO,CAACZ;;;oBAAzC;;;;;;;;oBAEKE;oBACPC,QAAQC,KAAK,CAAC,AAACF,IAAcQ,OAAO;oBACpChB,QAAQY,IAAI,CAAC;;;;;;;;;;;IAEjB"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/cli.ts"],"sourcesContent":["// Parsing and dispatch only. Commands live in src/cli/, one file each,\n// lazy-loaded — nothing tree- or dependency-heavy may be imported at the top of this file (`render` must never load the OCR engine, `--version` must load almost nothing).\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { COMMANDS } from './cli/index.ts';\nimport type { Ctx } from './cli/types.ts';\n\n// __dirname (CJS) or its ESM equivalent, then two fixed hops up to the\n// package root. NOT `import.meta.resolve('pdf-to-md/package.json')` — Node's self-reference lookup throws ERR_MODULE_NOT_FOUND from a file this deep; a location-relative path is stable across both build targets.\nconst __dirname = path.dirname(typeof __filename !== 'undefined' ? __filename : fileURLToPath(import.meta.url));\n\nfunction packageVersion(): string {\n try {\n const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { version?: string };\n return pkg.version ?? 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\nfunction usage(name: string): string {\n return (\n `usage: ${name} <file.pdf> [out.md] [flags...] convert a PDF to markdown\\n` +\n ` ${name} extract <file.pdf> [out.md] [flags...] (same, explicit)\\n` +\n ` ${name} render <file.pdf> <page>[-<page>] [--dpi|-d N (default 288)] [--out|-o DIR (default .)]\\n` +\n ` ${name} audit <words.jsonl> <file.md> severity-1 word-loss check\\n` +\n ` ${name} --version | --help\\n` +\n '\\n' +\n 'extract flags:\\n' +\n ' --ocr force the OCR path (image-only/scanned pages)\\n' +\n ' --no-ocr never fall back to OCR; keep sparse text output\\n' +\n ' --pages N[-M] convert only these 1-based source pages\\n' +\n ' --stdout write markdown to stdout instead of a file\\n' +\n ' --json print the full QA report as JSON\\n' +\n ` --page-markers emit a \"### pN\" heading per page\\n` +\n ' --format md|txt|raw output format (default md; raw = Analysis JSON incl. the\\n' +\n ' report; txt = reading-order plain text)\\n' +\n ' --words-json=FILE OCR path from a recognized-word dump (offline replay)\\n' +\n ' --debug-words=FILE dump every recognized word as JSON lines to FILE\\n' +\n ' --dpi=N OCR render resolution (default 288; raise for tiny print or\\n' +\n ' chart/label pages, >~400 measured worse on ordinary prose)\\n' +\n '\\n' +\n `extract tuning (measured defaults; see README's tuning table):\\n` +\n ' --float-max-words=N --float-max-width=F --float-margin=F --para-gap=F\\n' +\n ' --heading-scale=F --col-max-width=F --col-split=F --line-y-tol=F\\n' +\n ' --line-height-ratio=F\\n' +\n '\\n' +\n 'examples:\\n' +\n ` ${name} book.pdf # text layer -> book.md (auto-OCR if scanned)\\n` +\n ` ${name} scan.pdf out.md --ocr --json # force OCR, print the QA report\\n` +\n ` ${name} book.pdf --pages 27-31 --stdout # re-extract a page range to stdout\\n` +\n ` ${name} render book.pdf 27 # render p27 to PNG for eyeballing (288 dpi)\\n` +\n ` ${name} audit words.jsonl book.md # check no recognized word was lost`\n );\n}\n\n// Thrown errors -> exit 1 with the message verbatim; usage errors exit 2.\nexport default async function cli(argv: string[], name: string): Promise<void> {\n if (argv[0] === '--version' || argv[0] === '-v') {\n console.log(packageVersion());\n return;\n }\n if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {\n // No args is a usage ERROR (bare `pdf-to-md` can't do anything); asking\n // for --help is not.\n if (argv.length === 0) {\n console.error(usage(name));\n process.exit(2);\n }\n console.log(`${name} v${packageVersion()}`);\n console.log('');\n console.log(usage(name));\n return;\n }\n\n const ctx: Ctx = {\n name,\n rest: argv.slice(1),\n usageError(message) {\n console.error(message);\n process.exit(2);\n },\n };\n\n try {\n const load = COMMANDS[argv[0]];\n if (load) {\n await (await load()).default(ctx);\n } else {\n // Compat shim: `pdf-to-md file.pdf [...]` — any first word that isn't\n // a reserved command is extract's own first argument.\n ctx.rest = argv;\n await (await COMMANDS.extract()).default(ctx);\n }\n } catch (err) {\n console.error((err as Error).message);\n process.exit(1);\n }\n}\n"],"names":["cli","__dirname","path","dirname","__filename","fileURLToPath","packageVersion","pkg","pkgPath","resolve","JSON","parse","readFileSync","version","usage","name","argv","ctx","load","err","console","log","length","error","process","exit","rest","slice","usageError","message","COMMANDS","default","extract"],"mappings":"AAAA,uEAAuE;AACvE,2KAA2K;;;;;+BAyD3K,0EAA0E;AAC1E;;;eAA8BA;;;sBAzDD;+DACZ;uBACa;uBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGzB,uEAAuE;AACvE,oNAAoN;AACpN,IAAMC,YAAYC,iBAAI,CAACC,OAAO,CAAC,OAAOC,eAAe,cAAcA,aAAaC,IAAAA,sBAAa,EAAC;AAE9F,SAASC;IACP,IAAI;YAGKC;QAFP,IAAMC,UAAUN,iBAAI,CAACO,OAAO,CAACR,WAAW,MAAM,MAAM;QACpD,IAAMM,MAAMG,KAAKC,KAAK,CAACC,IAAAA,oBAAY,EAACJ,SAAS;QAC7C,QAAOD,eAAAA,IAAIM,OAAO,cAAXN,0BAAAA,eAAe;IACxB,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA,SAASO,MAAMC,IAAY;IACzB,OACE,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MAAAA;;;;oBACK;;wBAAMA;;;oBAAb;;wBAAO,cAAca,OAAO,CAACd;;;oBAA7B;;;;;;oBAEA,sEAAsE;oBACtE,sDAAsD;oBACtDA,IAAIS,IAAI,GAAGV;oBACJ;;wBAAMc,iBAAQ,CAACE,OAAO;;;oBAA7B;;wBAAO,cAA0BD,OAAO,CAACd;;;oBAAzC;;;;;;;;oBAEKE;oBACPC,QAAQG,KAAK,CAAC,AAACJ,IAAcU,OAAO;oBACpCL,QAAQC,IAAI,CAAC;;;;;;;;;;;IAEjB"}
@@ -3,6 +3,7 @@
3
3
  import { collect, pageCount } from './collect.js';
4
4
  import { dictAvailable, dictUnavailableWarning } from './dict.js';
5
5
  import { emitPage, renderEmitBlock } from './emit.js';
6
+ import { recognizePdf } from './engines/tesseract.js';
6
7
  import { buildPageOCR, DEFAULT_TUNING, headingLevels } from './geometry.js';
7
8
  import { toLines } from './lines.js';
8
9
  import { buildMarkdown } from './markdown.js';
@@ -68,7 +69,6 @@ function toAnalysisBlock(b, wordIndex) {
68
69
  } else {
69
70
  var _ref3, _ref4;
70
71
  var _opts_pages3, _opts_pages4;
71
- const { recognizePdf } = await import('./engines/tesseract.js');
72
72
  const totalPages = await pageCount(validated.pdfPath);
73
73
  const rawFirst = (_ref3 = (_opts_pages3 = opts.pages) === null || _opts_pages3 === void 0 ? void 0 : _opts_pages3.first) !== null && _ref3 !== void 0 ? _ref3 : 1;
74
74
  const rawLast = (_ref4 = (_opts_pages4 = opts.pages) === null || _opts_pages4 === void 0 ? void 0 : _opts_pages4.last) !== null && _ref4 !== void 0 ? _ref4 : opts.pages ? rawFirst : totalPages;
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/analyze.ts"],"sourcesContent":["// analyze() plus the OCR-path core (buildOcrAnalysisPages) that extractOcr\n// shares with it — same buildPageOCR -> emitPage -> renderPagesToMarkdown pipeline, so OCR-path markdown is byte-identical by construction, not two implementations kept in sync by hand. The TEXT path is NOT shared this way (see analyzeText).\nimport { collect, pageCount } from './collect.ts';\nimport { dictAvailable, dictUnavailableWarning } from './dict.ts';\nimport type { EmitBlock } from './emit.ts';\nimport { emitPage, renderEmitBlock } from './emit.ts';\n// Type-only: erased at compile time, so this does NOT create a runtime\n// circular dependency even though src/extract.ts imports (value-level) from this module.\nimport type { ExtractOcrOptions, ExtractTextOptions, OcrWordInput } from './extract.ts';\nimport type { PageOCR, Tuning, Word } from './geometry.ts';\nimport { buildPageOCR, DEFAULT_TUNING, headingLevels } from './geometry.ts';\nimport { toLines } from './lines.ts';\nimport { buildMarkdown } from './markdown.ts';\nimport { renderPagesToMarkdown } from './render-analysis.ts';\nimport { buildOcrReport, buildReport, OUTPUT_VERSION } from './report.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage, AnalysisWord, Line, PageLines } from './types.ts';\nimport { validateOcrAnalysisInput, validatePages, validateWordsInput } from './validate.ts';\n\n/** analyze(pdf) with the default/'text' path — OCR-only fields don't exist\n * on this branch, so passing e.g. `tuning` without `path: 'ocr'` is a compile error. */\nexport type AnalyzeTextOptions = ExtractTextOptions & { path?: 'text' };\n\n/** analyze(pdf, {path:'ocr'}) — same fields as {@link ExtractOcrOptions},\n * unlocked only once `path: 'ocr'` is set. */\nexport type AnalyzeOcrOptions = ExtractOcrOptions & { path: 'ocr' };\n\n/** Options for {@link analyze}: which fields type-check depends on `path`\n * (ignored, forced 'ocr', when `input` is a `{ words }` replay). */\nexport type AnalyzeOptions = AnalyzeTextOptions | AnalyzeOcrOptions;\n\nfunction toAnalysisWord(w: OcrWordInput): AnalysisWord {\n const box = { x: w.x, y: w.y, w: w.w, h: w.h };\n return w.confidence === undefined ? { text: w.text, box } : { text: w.text, box, confidence: w.confidence };\n}\n\n// EmitBlock -> AnalysisBlock: collapses emit.ts's 'quote' kind (a pull-quote)\n// into Analysis's 'paragraph' type, `text` keeping its literal '> ' prefix — see AnalysisBlock's doc comment (src/types.ts) for why.\nfunction toAnalysisBlock(b: EmitBlock, wordIndex: Map<Word, number>): AnalysisBlock {\n const wordIndexes = b.words.map((w) => wordIndex.get(w) as number);\n if (b.kind === 'heading') return { type: 'heading', text: b.text, level: b.level, wordIndexes };\n if (b.kind === 'review') return { type: 'review', text: renderEmitBlock(b), wordIndexes };\n return { type: 'paragraph', text: renderEmitBlock(b), wordIndexes };\n}\n\n/** The OCR-path core shared by extractOcr and analyze(..., {path:'ocr'}):\n * recognizes (or replays) words and runs the unchanged buildPageOCR/emitPage pipeline. Word IDENTITY (object reference), not value, carries indices through into the emitted blocks — see `geometry.ts`'s OcrLine.words. */\nexport async function buildOcrAnalysisPages(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions, warn: (m: string) => void): Promise<{ pages: AnalysisPage[]; words: OcrWordInput[] }> {\n const tuning: Tuning = { ...DEFAULT_TUNING, ...opts.tuning };\n const validated = validateOcrAnalysisInput(input);\n\n let words: OcrWordInput[];\n let first: number;\n let last: number;\n if ('words' in validated) {\n // Replay: page range from --pages if given, else every page up to the highest one the dump mentions.\n words = validated.words;\n first = opts.pages?.first ?? 1;\n last = opts.pages?.last ?? opts.pages?.first ?? Math.max(1, ...words.map((w) => w.page));\n } else {\n const { recognizePdf } = await import('./engines/tesseract.ts');\n const totalPages = await pageCount(validated.pdfPath);\n const rawFirst = opts.pages?.first ?? 1;\n const rawLast = opts.pages?.last ?? (opts.pages ? rawFirst : totalPages);\n first = Math.min(Math.max(1, rawFirst), Math.max(1, totalPages));\n last = Math.min(Math.max(first, rawLast), totalPages);\n const result = await recognizePdf(validated.pdfPath, first, last, {\n dpi: opts.dpi,\n onProgress: opts.onProgress,\n onWarning: warn,\n });\n words = result.words;\n }\n\n opts.onWords?.(words);\n\n // Stable per-page index, assigned in recognition/replay order — this IS\n // the page's flat `words` list order; `wordIndex` recovers it later since geometry.ts never clones a Word (object identity survives row-building).\n const byPage = new Map<number, OcrWordInput[]>();\n const wordIndex = new Map<Word, number>();\n for (const w of words) {\n const list = byPage.get(w.page);\n if (list) {\n wordIndex.set(w, list.length);\n list.push(w);\n } else {\n wordIndex.set(w, 0);\n byPage.set(w.page, [w]);\n }\n }\n\n const pageOcrs = new Map<number, PageOCR>();\n for (let pn = first; pn <= last; pn++) pageOcrs.set(pn, buildPageOCR(byPage.get(pn) ?? [], tuning));\n const { levelOf } = headingLevels([...pageOcrs.values()], tuning);\n\n const pages: AnalysisPage[] = [];\n for (let pn = first; pn <= last; pn++) {\n const p = pageOcrs.get(pn) as PageOCR;\n // An in-range page with no recognized words stays visible (marker +\n // warning), never silently absent — same rule as extractOcr.\n if (!byPage.has(pn)) warn(`p${pn}: no recognized words, page emitted with no OCR text`);\n\n const blocks: AnalysisBlock[] = emitPage(p, levelOf, tuning).map((b) => toAnalysisBlock(b, wordIndex));\n // Decorative fragments always render as one visible \"> [floats]\" aside\n // per page (matching the one printed line) — see geometry.ts's PageOCR.floats.\n if (p.floats.length) {\n blocks.push({\n type: 'float',\n text: `> [floats] ${p.floats.map((f) => f.text).join(' · ')}`,\n wordIndexes: p.floats.flatMap((f) => f.words).map((w) => wordIndex.get(w) as number),\n });\n }\n\n pages.push({\n page: pn,\n words: (byPage.get(pn) ?? []).map(toAnalysisWord),\n blocks,\n });\n }\n\n return { pages, words };\n}\n\nasync function analyzeOcr(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const { pages, words } = await buildOcrAnalysisPages(input, opts, warn);\n const md = renderPagesToMarkdown(pages, { forcePageMarkers: true, pageMarkers: true });\n const report = buildOcrReport({ md, fallback: opts.fallback, words });\n return { outputVersion: OUTPUT_VERSION, report, pages };\n}\n\n// TEXT path: deliberately NOT routed through the OCR shared-core pattern —\n// buildMarkdown's reflow/hyphen-rejoin/list rules don't fit the 4-type Analysis block union, so this is an independent, intentionally coarser reconstruction (one word/block per visual LINE) — honest, not byte-identical to extractText (see AnalysisPage, src/types.ts).\n\n// Converts a text-path Line's page-point geometry (src/lines.ts) into the\n// same normalized box contract the OCR path uses (see AnalysisPage.words) — only the coordinate SYSTEM changes; `box.y` anchors on the line's baseline, `box.w` stays 0.\nfunction textLineBox(l: Line, dims: { width: number; height: number }): AnalysisWord['box'] {\n const { width, height } = dims;\n return {\n x: width > 0 ? l.x / width : 0,\n y: height > 0 ? (height - l.y) / height : 0,\n w: 0,\n h: height > 0 ? l.h / height : 0,\n };\n}\n\nasync function analyzeText(pdfPath: string, opts: ExtractTextOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const range = opts.pages ? { first: opts.pages.first, last: opts.pages.last ?? opts.pages.first } : {};\n const { numPages, pages, heightChars } = await collect(pdfPath, range);\n const pageDims = new Map(pages.map((p) => [p.page, { width: p.width, height: p.height }]));\n const pageLines: PageLines[] = pages.map((p) => ({ page: p.page, lines: toLines(p) }));\n const pageMarkers = opts.pageMarkers ?? false;\n const { md, stats, bodyH, headingSizes } = buildMarkdown(pageLines, heightChars, { pageMarkers });\n const statsMd = pageMarkers ? md : buildMarkdown(pageLines, heightChars, { pageMarkers: true }).md;\n\n const hybridPages = pages.filter((p) => p.largeImage).map((p) => p.page);\n for (const n of hybridPages) {\n warn(`p${n}: text layer used but page carries large image(s); if it has baked-in text this output won't have it — compare (don't blindly replace) against --pages ${n} --ocr, which can itself introduce errors`);\n }\n\n // Report is measured from the REAL markdown above — accurate regardless of\n // the coarser block/word reconstruction below.\n const report = buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages });\n\n // headingSizes is offset-independent — reused directly, then re-leveled\n // here with offset 0 regardless of `opts.pageMarkers` (see AnalysisPage).\n const levelOf = new Map(headingSizes.slice(0, 6).map((h, i) => [h, Math.min(6, i + 1)]));\n const analysisPages: AnalysisPage[] = pageLines.map(({ page, lines }) => {\n const dims = pageDims.get(page) as { width: number; height: number };\n const words: AnalysisWord[] = lines.map((l) => ({ text: l.text, box: textLineBox(l, dims) }));\n const blocks: AnalysisBlock[] = lines.map((l, i) => {\n const level = levelOf.get(l.h);\n return level !== undefined ? { type: 'heading' as const, text: l.text, level, wordIndexes: [i] } : { type: 'paragraph' as const, text: l.text, wordIndexes: [i] };\n });\n return { page, words, blocks };\n });\n\n return { outputVersion: OUTPUT_VERSION, report, pages: analysisPages };\n}\n\n/**\n * Analyze a PDF (or replay an already-recognized OCR word dump) into\n * `Analysis`: plain, JSON-serializable per-page `words`/`blocks` plus the same QA `report` the other entry points return. Render with toMarkdown()/toText(), or hand-edit/splice it (no merge API — see toMarkdown's doc comment).\n *\n * @param input a bare pdf path, or `{ words }` to replay a dump (always analyzed as OCR) — unlike extractOcr, never `{ pdfPath }`\n * @param opts see {@link AnalyzeOptions}; for a pdf path, `opts.path` picks 'text' (default) or 'ocr' — analyze() makes no auto-fallback decision (that's pdfToMarkdown's job)\n */\nexport async function analyze(input: string | { words: OcrWordInput[] }, opts: AnalyzeOptions = {}): Promise<Analysis> {\n validatePages(opts.pages);\n if (typeof input !== 'string') return analyzeOcr({ words: validateWordsInput(input) }, opts);\n if (opts.path === 'ocr') return analyzeOcr({ pdfPath: input }, opts);\n return analyzeText(input, opts);\n}\n"],"names":["collect","pageCount","dictAvailable","dictUnavailableWarning","emitPage","renderEmitBlock","buildPageOCR","DEFAULT_TUNING","headingLevels","toLines","buildMarkdown","renderPagesToMarkdown","buildOcrReport","buildReport","OUTPUT_VERSION","validateOcrAnalysisInput","validatePages","validateWordsInput","toAnalysisWord","w","box","x","y","h","confidence","undefined","text","toAnalysisBlock","b","wordIndex","wordIndexes","words","map","get","kind","type","level","buildOcrAnalysisPages","input","opts","warn","byPage","tuning","validated","first","last","pages","Math","max","page","recognizePdf","totalPages","pdfPath","rawFirst","rawLast","min","result","dpi","onProgress","onWarning","onWords","Map","list","set","length","push","pageOcrs","pn","levelOf","values","p","has","blocks","floats","f","join","flatMap","analyzeOcr","m","md","forcePageMarkers","pageMarkers","report","fallback","outputVersion","textLineBox","l","dims","width","height","analyzeText","range","numPages","heightChars","pageDims","pageLines","lines","stats","bodyH","headingSizes","statsMd","hybridPages","filter","largeImage","n","slice","i","analysisPages","analyze","path"],"mappings":"AAAA,2EAA2E;AAC3E,kPAAkP;AAClP,SAASA,OAAO,EAAEC,SAAS,QAAQ,eAAe;AAClD,SAASC,aAAa,EAAEC,sBAAsB,QAAQ,YAAY;AAElE,SAASC,QAAQ,EAAEC,eAAe,QAAQ,YAAY;AAKtD,SAASC,YAAY,EAAEC,cAAc,EAAEC,aAAa,QAAQ,gBAAgB;AAC5E,SAASC,OAAO,QAAQ,aAAa;AACrC,SAASC,aAAa,QAAQ,gBAAgB;AAC9C,SAASC,qBAAqB,QAAQ,uBAAuB;AAC7D,SAASC,cAAc,EAAEC,WAAW,EAAEC,cAAc,QAAQ,cAAc;AAE1E,SAASC,wBAAwB,EAAEC,aAAa,EAAEC,kBAAkB,QAAQ,gBAAgB;AAc5F,SAASC,eAAeC,CAAe;IACrC,MAAMC,MAAM;QAAEC,GAAGF,EAAEE,CAAC;QAAEC,GAAGH,EAAEG,CAAC;QAAEH,GAAGA,EAAEA,CAAC;QAAEI,GAAGJ,EAAEI,CAAC;IAAC;IAC7C,OAAOJ,EAAEK,UAAU,KAAKC,YAAY;QAAEC,MAAMP,EAAEO,IAAI;QAAEN;IAAI,IAAI;QAAEM,MAAMP,EAAEO,IAAI;QAAEN;QAAKI,YAAYL,EAAEK,UAAU;IAAC;AAC5G;AAEA,8EAA8E;AAC9E,qIAAqI;AACrI,SAASG,gBAAgBC,CAAY,EAAEC,SAA4B;IACjE,MAAMC,cAAcF,EAAEG,KAAK,CAACC,GAAG,CAAC,CAACb,IAAMU,UAAUI,GAAG,CAACd;IACrD,IAAIS,EAAEM,IAAI,KAAK,WAAW,OAAO;QAAEC,MAAM;QAAWT,MAAME,EAAEF,IAAI;QAAEU,OAAOR,EAAEQ,KAAK;QAAEN;IAAY;IAC9F,IAAIF,E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AC4E;iBAAE;YAAC,IAAI;gBAAEvE,MAAM;gBAAsBT,MAAM4D,EAAE5D,IAAI;gBAAEI,aAAa;oBAAC4E;iBAAE;YAAC;QAClK;QACA,OAAO;YAAEzD;YAAMlB;YAAOyC;QAAO;IAC/B;IAEA,OAAO;QAAEY,eAAetE;QAAgBoE;QAAQpC,OAAO6D;IAAc;AACvE;AAEA;;;;;;CAMC,GACD,OAAO,eAAeC,QAAQtE,KAAyC,EAAEC,OAAuB,CAAC,CAAC;IAChGvB,cAAcuB,KAAKO,KAAK;IACxB,IAAI,OAAOR,UAAU,UAAU,OAAOuC,WAAW;QAAE9C,OAAOd,mBAAmBqB;IAAO,GAAGC;IACvF,IAAIA,KAAKsE,IAAI,KAAK,OAAO,OAAOhC,WAAW;QAAEzB,SAASd;IAAM,GAAGC;IAC/D,OAAOmD,YAAYpD,OAAOC;AAC5B"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/analyze.ts"],"sourcesContent":["// analyze() plus the OCR-path core (buildOcrAnalysisPages) that extractOcr\n// shares with it — same buildPageOCR -> emitPage -> renderPagesToMarkdown pipeline, so OCR-path markdown is byte-identical by construction, not two implementations kept in sync by hand. The TEXT path is NOT shared this way (see analyzeText).\nimport { collect, pageCount } from './collect.ts';\nimport { dictAvailable, dictUnavailableWarning } from './dict.ts';\nimport type { EmitBlock } from './emit.ts';\nimport { emitPage, renderEmitBlock } from './emit.ts';\nimport { recognizePdf } from './engines/tesseract.ts';\n// Type-only: erased at compile time, so this does NOT create a runtime\n// circular dependency even though src/extract.ts imports (value-level) from this module.\nimport type { ExtractOcrOptions, ExtractTextOptions, OcrWordInput } from './extract.ts';\nimport type { PageOCR, Tuning, Word } from './geometry.ts';\nimport { buildPageOCR, DEFAULT_TUNING, headingLevels } from './geometry.ts';\nimport { toLines } from './lines.ts';\nimport { buildMarkdown } from './markdown.ts';\nimport { renderPagesToMarkdown } from './render-analysis.ts';\nimport { buildOcrReport, buildReport, OUTPUT_VERSION } from './report.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage, AnalysisWord, Line, PageLines } from './types.ts';\nimport { validateOcrAnalysisInput, validatePages, validateWordsInput } from './validate.ts';\n\n/** analyze(pdf) with the default/'text' path — OCR-only fields don't exist\n * on this branch, so passing e.g. `tuning` without `path: 'ocr'` is a compile error. */\nexport type AnalyzeTextOptions = ExtractTextOptions & { path?: 'text' };\n\n/** analyze(pdf, {path:'ocr'}) — same fields as {@link ExtractOcrOptions},\n * unlocked only once `path: 'ocr'` is set. */\nexport type AnalyzeOcrOptions = ExtractOcrOptions & { path: 'ocr' };\n\n/** Options for {@link analyze}: which fields type-check depends on `path`\n * (ignored, forced 'ocr', when `input` is a `{ words }` replay). */\nexport type AnalyzeOptions = AnalyzeTextOptions | AnalyzeOcrOptions;\n\nfunction toAnalysisWord(w: OcrWordInput): AnalysisWord {\n const box = { x: w.x, y: w.y, w: w.w, h: w.h };\n return w.confidence === undefined ? { text: w.text, box } : { text: w.text, box, confidence: w.confidence };\n}\n\n// EmitBlock -> AnalysisBlock: collapses emit.ts's 'quote' kind (a pull-quote)\n// into Analysis's 'paragraph' type, `text` keeping its literal '> ' prefix — see AnalysisBlock's doc comment (src/types.ts) for why.\nfunction toAnalysisBlock(b: EmitBlock, wordIndex: Map<Word, number>): AnalysisBlock {\n const wordIndexes = b.words.map((w) => wordIndex.get(w) as number);\n if (b.kind === 'heading') return { type: 'heading', text: b.text, level: b.level, wordIndexes };\n if (b.kind === 'review') return { type: 'review', text: renderEmitBlock(b), wordIndexes };\n return { type: 'paragraph', text: renderEmitBlock(b), wordIndexes };\n}\n\n/** The OCR-path core shared by extractOcr and analyze(..., {path:'ocr'}):\n * recognizes (or replays) words and runs the unchanged buildPageOCR/emitPage pipeline. Word IDENTITY (object reference), not value, carries indices through into the emitted blocks — see `geometry.ts`'s OcrLine.words. */\nexport async function buildOcrAnalysisPages(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions, warn: (m: string) => void): Promise<{ pages: AnalysisPage[]; words: OcrWordInput[] }> {\n const tuning: Tuning = { ...DEFAULT_TUNING, ...opts.tuning };\n const validated = validateOcrAnalysisInput(input);\n\n let words: OcrWordInput[];\n let first: number;\n let last: number;\n if ('words' in validated) {\n // Replay: page range from --pages if given, else every page up to the highest one the dump mentions.\n words = validated.words;\n first = opts.pages?.first ?? 1;\n last = opts.pages?.last ?? opts.pages?.first ?? Math.max(1, ...words.map((w) => w.page));\n } else {\n const totalPages = await pageCount(validated.pdfPath);\n const rawFirst = opts.pages?.first ?? 1;\n const rawLast = opts.pages?.last ?? (opts.pages ? rawFirst : totalPages);\n first = Math.min(Math.max(1, rawFirst), Math.max(1, totalPages));\n last = Math.min(Math.max(first, rawLast), totalPages);\n const result = await recognizePdf(validated.pdfPath, first, last, {\n dpi: opts.dpi,\n onProgress: opts.onProgress,\n onWarning: warn,\n });\n words = result.words;\n }\n\n opts.onWords?.(words);\n\n // Stable per-page index, assigned in recognition/replay order — this IS\n // the page's flat `words` list order; `wordIndex` recovers it later since geometry.ts never clones a Word (object identity survives row-building).\n const byPage = new Map<number, OcrWordInput[]>();\n const wordIndex = new Map<Word, number>();\n for (const w of words) {\n const list = byPage.get(w.page);\n if (list) {\n wordIndex.set(w, list.length);\n list.push(w);\n } else {\n wordIndex.set(w, 0);\n byPage.set(w.page, [w]);\n }\n }\n\n const pageOcrs = new Map<number, PageOCR>();\n for (let pn = first; pn <= last; pn++) pageOcrs.set(pn, buildPageOCR(byPage.get(pn) ?? [], tuning));\n const { levelOf } = headingLevels([...pageOcrs.values()], tuning);\n\n const pages: AnalysisPage[] = [];\n for (let pn = first; pn <= last; pn++) {\n const p = pageOcrs.get(pn) as PageOCR;\n // An in-range page with no recognized words stays visible (marker +\n // warning), never silently absent — same rule as extractOcr.\n if (!byPage.has(pn)) warn(`p${pn}: no recognized words, page emitted with no OCR text`);\n\n const blocks: AnalysisBlock[] = emitPage(p, levelOf, tuning).map((b) => toAnalysisBlock(b, wordIndex));\n // Decorative fragments always render as one visible \"> [floats]\" aside\n // per page (matching the one printed line) — see geometry.ts's PageOCR.floats.\n if (p.floats.length) {\n blocks.push({\n type: 'float',\n text: `> [floats] ${p.floats.map((f) => f.text).join(' · ')}`,\n wordIndexes: p.floats.flatMap((f) => f.words).map((w) => wordIndex.get(w) as number),\n });\n }\n\n pages.push({\n page: pn,\n words: (byPage.get(pn) ?? []).map(toAnalysisWord),\n blocks,\n });\n }\n\n return { pages, words };\n}\n\nasync function analyzeOcr(input: { pdfPath: string } | { words: OcrWordInput[] }, opts: ExtractOcrOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const { pages, words } = await buildOcrAnalysisPages(input, opts, warn);\n const md = renderPagesToMarkdown(pages, { forcePageMarkers: true, pageMarkers: true });\n const report = buildOcrReport({ md, fallback: opts.fallback, words });\n return { outputVersion: OUTPUT_VERSION, report, pages };\n}\n\n// TEXT path: deliberately NOT routed through the OCR shared-core pattern —\n// buildMarkdown's reflow/hyphen-rejoin/list rules don't fit the 4-type Analysis block union, so this is an independent, intentionally coarser reconstruction (one word/block per visual LINE) — honest, not byte-identical to extractText (see AnalysisPage, src/types.ts).\n\n// Converts a text-path Line's page-point geometry (src/lines.ts) into the\n// same normalized box contract the OCR path uses (see AnalysisPage.words) — only the coordinate SYSTEM changes; `box.y` anchors on the line's baseline, `box.w` stays 0.\nfunction textLineBox(l: Line, dims: { width: number; height: number }): AnalysisWord['box'] {\n const { width, height } = dims;\n return {\n x: width > 0 ? l.x / width : 0,\n y: height > 0 ? (height - l.y) / height : 0,\n w: 0,\n h: height > 0 ? l.h / height : 0,\n };\n}\n\nasync function analyzeText(pdfPath: string, opts: ExtractTextOptions): Promise<Analysis> {\n const warn = (m: string) => opts.onWarning?.(m);\n if (!dictAvailable()) warn(dictUnavailableWarning());\n const range = opts.pages ? { first: opts.pages.first, last: opts.pages.last ?? opts.pages.first } : {};\n const { numPages, pages, heightChars } = await collect(pdfPath, range);\n const pageDims = new Map(pages.map((p) => [p.page, { width: p.width, height: p.height }]));\n const pageLines: PageLines[] = pages.map((p) => ({ page: p.page, lines: toLines(p) }));\n const pageMarkers = opts.pageMarkers ?? false;\n const { md, stats, bodyH, headingSizes } = buildMarkdown(pageLines, heightChars, { pageMarkers });\n const statsMd = pageMarkers ? md : buildMarkdown(pageLines, heightChars, { pageMarkers: true }).md;\n\n const hybridPages = pages.filter((p) => p.largeImage).map((p) => p.page);\n for (const n of hybridPages) {\n warn(`p${n}: text layer used but page carries large image(s); if it has baked-in text this output won't have it — compare (don't blindly replace) against --pages ${n} --ocr, which can itself introduce errors`);\n }\n\n // Report is measured from the REAL markdown above — accurate regardless of\n // the coarser block/word reconstruction below.\n const report = buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages });\n\n // headingSizes is offset-independent — reused directly, then re-leveled\n // here with offset 0 regardless of `opts.pageMarkers` (see AnalysisPage).\n const levelOf = new Map(headingSizes.slice(0, 6).map((h, i) => [h, Math.min(6, i + 1)]));\n const analysisPages: AnalysisPage[] = pageLines.map(({ page, lines }) => {\n const dims = pageDims.get(page) as { width: number; height: number };\n const words: AnalysisWord[] = lines.map((l) => ({ text: l.text, box: textLineBox(l, dims) }));\n const blocks: AnalysisBlock[] = lines.map((l, i) => {\n const level = levelOf.get(l.h);\n return level !== undefined ? { type: 'heading' as const, text: l.text, level, wordIndexes: [i] } : { type: 'paragraph' as const, text: l.text, wordIndexes: [i] };\n });\n return { page, words, blocks };\n });\n\n return { outputVersion: OUTPUT_VERSION, report, pages: analysisPages };\n}\n\n/**\n * Analyze a PDF (or replay an already-recognized OCR word dump) into\n * `Analysis`: plain, JSON-serializable per-page `words`/`blocks` plus the same QA `report` the other entry points return. Render with toMarkdown()/toText(), or hand-edit/splice it (no merge API — see toMarkdown's doc comment).\n *\n * @param input a bare pdf path, or `{ words }` to replay a dump (always analyzed as OCR) — unlike extractOcr, never `{ pdfPath }`\n * @param opts see {@link AnalyzeOptions}; for a pdf path, `opts.path` picks 'text' (default) or 'ocr' — analyze() makes no auto-fallback decision (that's pdfToMarkdown's job)\n */\nexport async function analyze(input: string | { words: OcrWordInput[] }, opts: AnalyzeOptions = {}): Promise<Analysis> {\n validatePages(opts.pages);\n if (typeof input !== 'string') return analyzeOcr({ words: validateWordsInput(input) }, opts);\n if (opts.path === 'ocr') return analyzeOcr({ pdfPath: input }, opts);\n return analyzeText(input, opts);\n}\n"],"names":["collect","pageCount","dictAvailable","dictUnavailableWarning","emitPage","renderEmitBlock","recognizePdf","buildPageOCR","DEFAULT_TUNING","headingLevels","toLines","buildMarkdown","renderPagesToMarkdown","buildOcrReport","buildReport","OUTPUT_VERSION","validateOcrAnalysisInput","validatePages","validateWordsInput","toAnalysisWord","w","box","x","y","h","confidence","undefined","text","toAnalysisBlock","b","wordIndex","wordIndexes","words","map","get","kind","type","level","buildOcrAnalysisPages","input","opts","warn","byPage","tuning","validated","first","last","pages","Math","max","page","totalPages","pdfPath","rawFirst","rawLast","min","result","dpi","onProgress","onWarning","onWords","Map","list","set","length","push","pageOcrs","pn","levelOf","values","p","has","blocks","floats","f","join","flatMap","analyzeOcr","m","md","forcePageMarkers","pageMarkers","report","fallback","outputVersion","textLineBox","l","dims","width","height","analyzeText","range","numPages","heightChars","pageDims","pageLines","lines","stats","bodyH","headingSizes","statsMd","hybridPages","filter","largeImage","n","slice","i","analysisPages","analyze","path"],"mappings":"AAAA,2EAA2E;AAC3E,kPAAkP;AAClP,SAASA,OAAO,EAAEC,SAAS,QAAQ,eAAe;AAClD,SAASC,aAAa,EAAEC,sBAAsB,QAAQ,YAAY;AAElE,SAASC,QAAQ,EAAEC,eAAe,QAAQ,YAAY;AACtD,SAASC,YAAY,QAAQ,yBAAyB;AAKtD,SAASC,YAAY,EAAEC,cAAc,EAAEC,aAAa,QAAQ,gBAAgB;AAC5E,SAASC,OAAO,QAAQ,aAAa;AACrC,SAASC,aAAa,QAAQ,gBAAgB;AA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