@effortlessmotion/pdf-to-md 0.1.1 → 0.1.2

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.
Files changed (53) hide show
  1. package/dist/cjs/analyze.js.map +1 -1
  2. package/dist/cjs/audit.js.map +1 -1
  3. package/dist/cjs/cli/audit.js.map +1 -1
  4. package/dist/cjs/cli/extract.js.map +1 -1
  5. package/dist/cjs/cli/index.js.map +1 -1
  6. package/dist/cjs/cli/render.js.map +1 -1
  7. package/dist/cjs/cli/types.js.map +1 -1
  8. package/dist/cjs/cli.js.map +1 -1
  9. package/dist/cjs/collect.js.map +1 -1
  10. package/dist/cjs/dict.js.map +1 -1
  11. package/dist/cjs/emit.js.map +1 -1
  12. package/dist/cjs/engines/tesseract.js.map +1 -1
  13. package/dist/cjs/errors.js.map +1 -1
  14. package/dist/cjs/extract.js.map +1 -1
  15. package/dist/cjs/geometry.js.map +1 -1
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/lines.js.map +1 -1
  18. package/dist/cjs/markdown.js.map +1 -1
  19. package/dist/cjs/page-marker.js.map +1 -1
  20. package/dist/cjs/pdf-open.js.map +1 -1
  21. package/dist/cjs/raster.js.map +1 -1
  22. package/dist/cjs/render-analysis.js.map +1 -1
  23. package/dist/cjs/report.js.map +1 -1
  24. package/dist/cjs/resolve.js.map +1 -1
  25. package/dist/cjs/types.js.map +1 -1
  26. package/dist/cjs/validate.js.map +1 -1
  27. package/dist/esm/analyze.js.map +1 -1
  28. package/dist/esm/audit.js.map +1 -1
  29. package/dist/esm/cli/audit.js.map +1 -1
  30. package/dist/esm/cli/extract.js.map +1 -1
  31. package/dist/esm/cli/index.js.map +1 -1
  32. package/dist/esm/cli/render.js.map +1 -1
  33. package/dist/esm/cli/types.js.map +1 -1
  34. package/dist/esm/cli.js.map +1 -1
  35. package/dist/esm/collect.js.map +1 -1
  36. package/dist/esm/dict.js.map +1 -1
  37. package/dist/esm/emit.js.map +1 -1
  38. package/dist/esm/engines/tesseract.js.map +1 -1
  39. package/dist/esm/errors.js.map +1 -1
  40. package/dist/esm/extract.js.map +1 -1
  41. package/dist/esm/geometry.js.map +1 -1
  42. package/dist/esm/index.js.map +1 -1
  43. package/dist/esm/lines.js.map +1 -1
  44. package/dist/esm/markdown.js.map +1 -1
  45. package/dist/esm/page-marker.js.map +1 -1
  46. package/dist/esm/pdf-open.js.map +1 -1
  47. package/dist/esm/raster.js.map +1 -1
  48. package/dist/esm/render-analysis.js.map +1 -1
  49. package/dist/esm/report.js.map +1 -1
  50. package/dist/esm/resolve.js.map +1 -1
  51. package/dist/esm/types.js.map +1 -1
  52. package/dist/esm/validate.js.map +1 -1
  53. package/package.json +10 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/page-marker.ts"],"sourcesContent":["// page-marker.ts — the single \"### pN\" convention: every producer/parser of\n// the page-marker heading imports from here so the regex can't drift (report.ts once had a `\\s+` variant).\n\n/** The marker heading for page N, with no surrounding whitespace/newlines\n * (callers own their own blank-line formatting). */\nexport function pageMarkerLine(page: number): string {\n return `### p${page}`;\n}\n\n// Single space, matching pageMarkerLine's own output exactly.\nconst MARKER_RE = /^### p(\\d+)$/;\n\n/** Is this line (already split, no trailing newline) a page-marker heading? */\nexport function isPageMarkerLine(line: string): boolean {\n return MARKER_RE.test(line);\n}\n\n/** Split markdown into per-marker body slices, in document order — one entry\n * PER OCCURRENCE (a duplicate \"### pN\" yields two entries; no slice is ever dropped). */\nexport function splitByPageMarker(md: string): { page: number; body: string }[] {\n const re = /^### p(\\d+)$/gm;\n const markers: { page: number; index: number; end: number }[] = [];\n for (let m = re.exec(md); m !== null; m = re.exec(md)) markers.push({ page: Number(m[1]), index: m.index, end: m.index + m[0].length });\n const out: { page: number; body: string }[] = [];\n for (let i = 0; i < markers.length; i++) {\n const end = i + 1 < markers.length ? markers[i + 1].index : md.length;\n out.push({ page: markers[i].page, body: md.slice(markers[i].end, end) });\n }\n return out;\n}\n\n/** Per-page body text, duplicate-marker slices CONCATENATED — a word anywhere\n * on page N counts as on page N (the auditor's membership semantics). */\nexport function bodyByPage(md: string): Map<number, string> {\n const out = new Map<number, string>();\n for (const { page, body } of splitByPageMarker(md)) out.set(page, (out.get(page) ?? '') + body);\n return out;\n}\n\n/** Count of \"### pN\" marker lines in `md`. */\nexport function countPageMarkers(md: string): number {\n return (md.match(/^### p\\d+$/gm) || []).length;\n}\n"],"names":["pageMarkerLine","page","MARKER_RE","isPageMarkerLine","line","test","splitByPageMarker","md","re","markers","m","exec","push","Number","index","end","length","out","i","body","slice","bodyByPage","Map","set","get","countPageMarkers","match"],"mappings":"AAAA,4EAA4E;AAC5E,2GAA2G;AAE3G;kDACkD,GAClD,OAAO,SAASA,eAAeC,IAAY;IACzC,OAAO,CAAC,KAAK,EAAEA,MAAM;AACvB;AAEA,8DAA8D;AAC9D,MAAMC,YAAY;AAElB,6EAA6E,GAC7E,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,OAAOF,UAAUG,IAAI,CAACD;AACxB;AAEA;uFACuF,GACvF,OAAO,SAASE,kBAAkBC,EAAU;IAC1C,MAAMC,KAAK;IACX,MAAMC,UAA0D,EAAE;IAClE,IAAK,IAAIC,IAAIF,GAAGG,IAAI,CAACJ,KAAKG,MAAM,MAAMA,IAAIF,GAAGG,IAAI,CAACJ,IAAKE,QAAQG,IAAI,CAAC;QAAEX,MAAMY,OAAOH,CAAC,CAAC,EAAE;QAAGI,OAAOJ,EAAEI,KAAK;QAAEC,KAAKL,EAAEI,KAAK,GAAGJ,CAAC,CAAC,EAAE,CAACM,MAAM;IAAC;IACrI,MAAMC,MAAwC,EAAE;IAChD,IAAK,IAAIC,IAAI,GAAGA,IAAIT,QAAQO,MAAM,EAAEE,IAAK;QACvC,MAAMH,MAAMG,IAAI,IAAIT,QAAQO,MAAM,GAAGP,OAAO,CAACS,IAAI,EAAE,CAACJ,KAAK,GAAGP,GAAGS,MAAM;QACrEC,IAAIL,IAAI,CAAC;YAAEX,MAAMQ,OAAO,CAACS,EAAE,CAACjB,IAAI;YAAEkB,MAAMZ,GAAGa,KAAK,CAACX,OAAO,CAACS,EAAE,CAACH,GAAG,EAAEA;QAAK;IACxE;IACA,OAAOE;AACT;AAEA;uEACuE,GACvE,OAAO,SAASI,WAAWd,EAAU;QAEgCU;IADnE,MAAMA,MAAM,IAAIK;IAChB,KAAK,MAAM,EAAErB,IAAI,EAAEkB,IAAI,EAAE,IAAIb,kBAAkBC,IAAKU,IAAIM,GAAG,CAACtB,MAAM,EAACgB,WAAAA,IAAIO,GAAG,CAACvB,mBAARgB,sBAAAA,WAAiB,MAAME;IAC1F,OAAOF;AACT;AAEA,4CAA4C,GAC5C,OAAO,SAASQ,iBAAiBlB,EAAU;IACzC,OAAO,AAACA,CAAAA,GAAGmB,KAAK,CAAC,mBAAmB,EAAE,AAAD,EAAGV,MAAM;AAChD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/page-marker.ts"],"sourcesContent":["// page-marker.ts — the single \"### pN\" convention: every producer/parser of\n// the page-marker heading imports from here so the regex can't drift (report.ts once had a `\\s+` variant).\n\n/** The marker heading for page N, with no surrounding whitespace/newlines\n * (callers own their own blank-line formatting). */\nexport function pageMarkerLine(page: number): string {\n return `### p${page}`;\n}\n\n// Single space, matching pageMarkerLine's own output exactly.\nconst MARKER_RE = /^### p(\\d+)$/;\n\n/** Is this line (already split, no trailing newline) a page-marker heading? */\nexport function isPageMarkerLine(line: string): boolean {\n return MARKER_RE.test(line);\n}\n\n/** Split markdown into per-marker body slices, in document order — one entry\n * PER OCCURRENCE (a duplicate \"### pN\" yields two entries; no slice is ever dropped). */\nexport function splitByPageMarker(md: string): { page: number; body: string }[] {\n const re = /^### p(\\d+)$/gm;\n const markers: { page: number; index: number; end: number }[] = [];\n for (let m = re.exec(md); m !== null; m = re.exec(md)) markers.push({ page: Number(m[1]), index: m.index, end: m.index + m[0].length });\n const out: { page: number; body: string }[] = [];\n for (let i = 0; i < markers.length; i++) {\n const end = i + 1 < markers.length ? markers[i + 1].index : md.length;\n out.push({ page: markers[i].page, body: md.slice(markers[i].end, end) });\n }\n return out;\n}\n\n/** Per-page body text, duplicate-marker slices CONCATENATED — a word anywhere\n * on page N counts as on page N (the auditor's membership semantics). */\nexport function bodyByPage(md: string): Map<number, string> {\n const out = new Map<number, string>();\n for (const { page, body } of splitByPageMarker(md)) out.set(page, (out.get(page) ?? '') + body);\n return out;\n}\n\n/** Count of \"### pN\" marker lines in `md`. */\nexport function countPageMarkers(md: string): number {\n return (md.match(/^### p\\d+$/gm) || []).length;\n}\n"],"names":["pageMarkerLine","page","MARKER_RE","isPageMarkerLine","line","test","splitByPageMarker","md","re","markers","m","exec","push","Number","index","end","length","out","i","body","slice","bodyByPage","Map","set","get","countPageMarkers","match"],"mappings":"AAAA,4EAA4E;AAC5E,2GAA2G;AAE3G;kDACkD,GAClD,OAAO,SAASA,eAAeC,IAAY;IACzC,OAAO,CAAC,KAAK,EAAEA,MAAM;AACvB;AAEA,8DAA8D;AAC9D,MAAMC,YAAY;AAElB,6EAA6E,GAC7E,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,OAAOF,UAAUG,IAAI,CAACD;AACxB;AAEA;uFACuF,GACvF,OAAO,SAASE,kBAAkBC,EAAU;IAC1C,MAAMC,KAAK;IACX,MAAMC,UAA0D,EAAE;IAClE,IAAK,IAAIC,IAAIF,GAAGG,IAAI,CAACJ,KAAKG,MAAM,MAAMA,IAAIF,GAAGG,IAAI,CAACJ,IAAKE,QAAQG,IAAI,CAAC;QAAEX,MAAMY,OAAOH,CAAC,CAAC,EAAE;QAAGI,OAAOJ,EAAEI,KAAK;QAAEC,KAAKL,EAAEI,KAAK,GAAGJ,CAAC,CAAC,EAAE,CAACM,MAAM;IAAC;IACrI,MAAMC,MAAwC,EAAE;IAChD,IAAK,IAAIC,IAAI,GAAGA,IAAIT,QAAQO,MAAM,EAAEE,IAAK;QACvC,MAAMH,MAAMG,IAAI,IAAIT,QAAQO,MAAM,GAAGP,OAAO,CAACS,IAAI,EAAE,CAACJ,KAAK,GAAGP,GAAGS,MAAM;QACrEC,IAAIL,IAAI,CAAC;YAAEX,MAAMQ,OAAO,CAACS,EAAE,CAACjB,IAAI;YAAEkB,MAAMZ,GAAGa,KAAK,CAACX,OAAO,CAACS,EAAE,CAACH,GAAG,EAAEA;QAAK;IACxE;IACA,OAAOE;AACT;AAEA;uEACuE,GACvE,OAAO,SAASI,WAAWd,EAAU;QAEgCU;IADnE,MAAMA,MAAM,IAAIK;IAChB,KAAK,MAAM,EAAErB,IAAI,EAAEkB,IAAI,EAAE,IAAIb,kBAAkBC,IAAKU,IAAIM,GAAG,CAACtB,MAAM,EAACgB,WAAAA,IAAIO,GAAG,CAACvB,mBAARgB,sBAAAA,WAAiB,MAAME;IAC1F,OAAOF;AACT;AAEA,4CAA4C,GAC5C,OAAO,SAASQ,iBAAiBlB,EAAU;IACzC,OAAO,AAACA,CAAAA,GAAGmB,KAAK,CAAC,mBAAmB,EAAE,AAAD,EAAGV,MAAM;AAChD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/pdf-open.ts"],"sourcesContent":["// pdf-open.ts — the one seam that opens a PDF via pdfjs-dist, in the two\n// shapes callers need: openDocument (data-based, already-open doc) and openPdfForRender (url-based, task you must await + destroy()).\n// Both wrap a failure the same way: PdfToMdError/PDF_OPEN, original message preserved.\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport type { PDFDocumentLoadingTask, PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { getDocument, VerbosityLevel } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { PdfToMdError } from './errors.ts';\nimport { resolvePackagePath } from './resolve.ts';\n\n// `verbosity: VerbosityLevel.ERRORS` silences pdfjs's own console.warn calls\n// — the library's documented promise is it never writes to stdout/stderr on its own.\n\n/** Data-based open (collect.ts's seam): no cMaps/fonts — text-layer extraction\n * only, verified to decode CJK correctly. Wraps missing/unreadable and non-PDF files as PdfToMdError/PDF_OPEN. */\nexport async function openDocument(src: string): Promise<PDFDocumentProxy> {\n let data: Uint8Array;\n try {\n data = new Uint8Array(readFileSync(src));\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `cannot read ${src}: ${(err as Error).message}`);\n }\n try {\n return await getDocument({\n data,\n useSystemFonts: true,\n verbosity: VerbosityLevel.ERRORS,\n }).promise;\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `cannot open ${src} as a PDF: ${(err as Error).message}`);\n }\n}\n\n// Wires up pdfjs's bundled cmaps/standard_fonts so CJK and non-embedded\n// standard fonts resolve instead of falling back to substitute glyphs.\n//\n// GOTCHA: despite the `...Url` name, pdfjs's Node loader does `fs.readFile`\n// on the string directly — a `file://` URL silently fails every lookup (only a stderr warning); plain filesystem paths are required.\nconst PDFJS_DIST_ROOT = path.dirname(resolvePackagePath('pdfjs-dist/package.json'));\nconst CMAP_URL = path.join(PDFJS_DIST_ROOT, 'cmaps') + path.sep;\nconst STANDARD_FONT_DATA_URL = path.join(PDFJS_DIST_ROOT, 'standard_fonts') + path.sep;\n// JBIG2/JPEG2000 decoding lives in pdfjs's WASM modules: without this, bitonal\n// scans (the usual encoding for B&W page images) decode to a BLANK page and OCR sees nothing.\nconst WASM_URL = path.join(PDFJS_DIST_ROOT, 'wasm') + path.sep;\n\n/**\n * Open a PDF for rendering (raster.ts/tesseract.ts's seam): cMaps + standard\n * fonts wired up, url-based. Callers must `await` the returned task's `.promise` (via `awaitPdfOpen`) and call `.destroy()` when done.\n */\nexport function openPdfForRender(pdfPath: string): PDFDocumentLoadingTask {\n // No `worker` option: this pdfjs-dist Node build needs no real Worker thread wired up to run.\n return getDocument({\n url: pdfPath,\n cMapUrl: CMAP_URL,\n cMapPacked: true,\n standardFontDataUrl: STANDARD_FONT_DATA_URL,\n wasmUrl: WASM_URL,\n verbosity: VerbosityLevel.ERRORS,\n });\n}\n\n/** Shared error wrapping for `openPdfForRender`'s task: a raw pdfjs open\n * failure becomes PdfToMdError/PDF_OPEN, original message preserved. */\nexport async function awaitPdfOpen(loadingTask: PDFDocumentLoadingTask, pdfPath: string): Promise<PDFDocumentProxy> {\n try {\n return await loadingTask.promise;\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `could not open PDF: ${pdfPath} (${(err as Error).message})`);\n }\n}\n"],"names":["readFileSync","path","getDocument","VerbosityLevel","PdfToMdError","resolvePackagePath","openDocument","src","data","Uint8Array","err","message","useSystemFonts","verbosity","ERRORS","promise","PDFJS_DIST_ROOT","dirname","CMAP_URL","join","sep","STANDARD_FONT_DATA_URL","WASM_URL","openPdfForRender","pdfPath","url","cMapUrl","cMapPacked","standardFontDataUrl","wasmUrl","awaitPdfOpen","loadingTask"],"mappings":"AAAA,yEAAyE;AACzE,sIAAsI;AACtI,uFAAuF;AACvF,SAASA,YAAY,QAAQ,UAAU;AACvC,OAAOC,UAAU,YAAY;AAE7B,SAASC,WAAW,EAAEC,cAAc,QAAQ,kCAAkC;AAC9E,SAASC,YAAY,QAAQ,cAAc;AAC3C,SAASC,kBAAkB,QAAQ,eAAe;AAElD,6EAA6E;AAC7E,qFAAqF;AAErF;gHACgH,GAChH,OAAO,eAAeC,aAAaC,GAAW;IAC5C,IAAIC;IACJ,IAAI;QACFA,OAAO,IAAIC,WAAWT,aAAaO;IACrC,EAAE,OAAOG,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,YAAY,EAAEG,IAAI,EAAE,EAAE,AAACG,IAAcC,OAAO,EAAE;IACpF;IACA,IAAI;QACF,OAAO,MAAMT,YAAY;YACvBM;YACAI,gBAAgB;YAChBC,WAAWV,eAAeW,MAAM;QAClC,GAAGC,OAAO;IACZ,EAAE,OAAOL,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,YAAY,EAAEG,IAAI,WAAW,EAAE,AAACG,IAAcC,OAAO,EAAE;IAC7F;AACF;AAEA,wEAAwE;AACxE,uEAAuE;AACvE,EAAE;AACF,4EAA4E;AAC5E,qIAAqI;AACrI,MAAMK,kBAAkBf,KAAKgB,OAAO,CAACZ,mBAAmB;AACxD,MAAMa,WAAWjB,KAAKkB,IAAI,CAACH,iBAAiB,WAAWf,KAAKmB,GAAG;AAC/D,MAAMC,yBAAyBpB,KAAKkB,IAAI,CAACH,iBAAiB,oBAAoBf,KAAKmB,GAAG;AACtF,+EAA+E;AAC/E,8FAA8F;AAC9F,MAAME,WAAWrB,KAAKkB,IAAI,CAACH,iBAAiB,UAAUf,KAAKmB,GAAG;AAE9D;;;CAGC,GACD,OAAO,SAASG,iBAAiBC,OAAe;IAC9C,8FAA8F;IAC9F,OAAOtB,YAAY;QACjBuB,KAAKD;QACLE,SAASR;QACTS,YAAY;QACZC,qBAAqBP;QACrBQ,SAASP;QACTT,WAAWV,eAAeW,MAAM;IAClC;AACF;AAEA;sEACsE,GACtE,OAAO,eAAegB,aAAaC,WAAmC,EAAEP,OAAe;IACrF,IAAI;QACF,OAAO,MAAMO,YAAYhB,OAAO;IAClC,EAAE,OAAOL,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,oBAAoB,EAAEoB,QAAQ,EAAE,EAAE,AAACd,IAAcC,OAAO,CAAC,CAAC,CAAC;IACjG;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/pdf-open.ts"],"sourcesContent":["// pdf-open.ts — the one seam that opens a PDF via pdfjs-dist, in the two\n// shapes callers need: openDocument (data-based, already-open doc) and openPdfForRender (url-based, task you must await + destroy()).\n// Both wrap a failure the same way: PdfToMdError/PDF_OPEN, original message preserved.\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport type { PDFDocumentLoadingTask, PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { getDocument, VerbosityLevel } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { PdfToMdError } from './errors.ts';\nimport { resolvePackagePath } from './resolve.ts';\n\n// `verbosity: VerbosityLevel.ERRORS` silences pdfjs's own console.warn calls\n// — the library's documented promise is it never writes to stdout/stderr on its own.\n\n/** Data-based open (collect.ts's seam): no cMaps/fonts — text-layer extraction\n * only, verified to decode CJK correctly. Wraps missing/unreadable and non-PDF files as PdfToMdError/PDF_OPEN. */\nexport async function openDocument(src: string): Promise<PDFDocumentProxy> {\n let data: Uint8Array;\n try {\n data = new Uint8Array(readFileSync(src));\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `cannot read ${src}: ${(err as Error).message}`);\n }\n try {\n return await getDocument({\n data,\n useSystemFonts: true,\n verbosity: VerbosityLevel.ERRORS,\n }).promise;\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `cannot open ${src} as a PDF: ${(err as Error).message}`);\n }\n}\n\n// Wires up pdfjs's bundled cmaps/standard_fonts so CJK and non-embedded\n// standard fonts resolve instead of falling back to substitute glyphs.\n//\n// GOTCHA: despite the `...Url` name, pdfjs's Node loader does `fs.readFile`\n// on the string directly — a `file://` URL silently fails every lookup (only a stderr warning); plain filesystem paths are required.\nconst PDFJS_DIST_ROOT = path.dirname(resolvePackagePath('pdfjs-dist/package.json'));\nconst CMAP_URL = path.join(PDFJS_DIST_ROOT, 'cmaps') + path.sep;\nconst STANDARD_FONT_DATA_URL = path.join(PDFJS_DIST_ROOT, 'standard_fonts') + path.sep;\n// JBIG2/JPEG2000 decoding lives in pdfjs's WASM modules: without this, bitonal\n// scans (the usual encoding for B&W page images) decode to a BLANK page and OCR sees nothing.\nconst WASM_URL = path.join(PDFJS_DIST_ROOT, 'wasm') + path.sep;\n\n/**\n * Open a PDF for rendering (raster.ts/tesseract.ts's seam): cMaps + standard\n * fonts wired up, url-based. Callers must `await` the returned task's `.promise` (via `awaitPdfOpen`) and call `.destroy()` when done.\n */\nexport function openPdfForRender(pdfPath: string): PDFDocumentLoadingTask {\n // No `worker` option: this pdfjs-dist Node build needs no real Worker thread wired up to run.\n return getDocument({\n url: pdfPath,\n cMapUrl: CMAP_URL,\n cMapPacked: true,\n standardFontDataUrl: STANDARD_FONT_DATA_URL,\n wasmUrl: WASM_URL,\n verbosity: VerbosityLevel.ERRORS,\n });\n}\n\n/** Shared error wrapping for `openPdfForRender`'s task: a raw pdfjs open\n * failure becomes PdfToMdError/PDF_OPEN, original message preserved. */\nexport async function awaitPdfOpen(loadingTask: PDFDocumentLoadingTask, pdfPath: string): Promise<PDFDocumentProxy> {\n try {\n return await loadingTask.promise;\n } catch (err) {\n throw new PdfToMdError('PDF_OPEN', `could not open PDF: ${pdfPath} (${(err as Error).message})`);\n }\n}\n"],"names":["readFileSync","path","getDocument","VerbosityLevel","PdfToMdError","resolvePackagePath","openDocument","src","data","Uint8Array","err","message","useSystemFonts","verbosity","ERRORS","promise","PDFJS_DIST_ROOT","dirname","CMAP_URL","join","sep","STANDARD_FONT_DATA_URL","WASM_URL","openPdfForRender","pdfPath","url","cMapUrl","cMapPacked","standardFontDataUrl","wasmUrl","awaitPdfOpen","loadingTask"],"mappings":"AAAA,yEAAyE;AACzE,sIAAsI;AACtI,uFAAuF;AACvF,SAASA,YAAY,QAAQ,UAAU;AACvC,OAAOC,UAAU,YAAY;AAE7B,SAASC,WAAW,EAAEC,cAAc,QAAQ,kCAAkC;AAC9E,SAASC,YAAY,QAAQ,cAAc;AAC3C,SAASC,kBAAkB,QAAQ,eAAe;AAElD,6EAA6E;AAC7E,qFAAqF;AAErF;gHACgH,GAChH,OAAO,eAAeC,aAAaC,GAAW;IAC5C,IAAIC;IACJ,IAAI;QACFA,OAAO,IAAIC,WAAWT,aAAaO;IACrC,EAAE,OAAOG,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,YAAY,EAAEG,IAAI,EAAE,EAAE,AAACG,IAAcC,OAAO,EAAE;IACpF;IACA,IAAI;QACF,OAAO,MAAMT,YAAY;YACvBM;YACAI,gBAAgB;YAChBC,WAAWV,eAAeW,MAAM;QAClC,GAAGC,OAAO;IACZ,EAAE,OAAOL,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,YAAY,EAAEG,IAAI,WAAW,EAAE,AAACG,IAAcC,OAAO,EAAE;IAC7F;AACF;AAEA,wEAAwE;AACxE,uEAAuE;AACvE,EAAE;AACF,4EAA4E;AAC5E,qIAAqI;AACrI,MAAMK,kBAAkBf,KAAKgB,OAAO,CAACZ,mBAAmB;AACxD,MAAMa,WAAWjB,KAAKkB,IAAI,CAACH,iBAAiB,WAAWf,KAAKmB,GAAG;AAC/D,MAAMC,yBAAyBpB,KAAKkB,IAAI,CAACH,iBAAiB,oBAAoBf,KAAKmB,GAAG;AACtF,+EAA+E;AAC/E,8FAA8F;AAC9F,MAAME,WAAWrB,KAAKkB,IAAI,CAACH,iBAAiB,UAAUf,KAAKmB,GAAG;AAE9D;;;CAGC,GACD,OAAO,SAASG,iBAAiBC,OAAe;IAC9C,8FAA8F;IAC9F,OAAOtB,YAAY;QACjBuB,KAAKD;QACLE,SAASR;QACTS,YAAY;QACZC,qBAAqBP;QACrBQ,SAASP;QACTT,WAAWV,eAAeW,MAAM;IAClC;AACF;AAEA;sEACsE,GACtE,OAAO,eAAegB,aAAaC,WAAmC,EAAEP,OAAe;IACrF,IAAI;QACF,OAAO,MAAMO,YAAYhB,OAAO;IAClC,EAAE,OAAOL,KAAK;QACZ,MAAM,IAAIN,aAAa,YAAY,CAAC,oBAAoB,EAAEoB,QAAQ,EAAE,EAAE,AAACd,IAAcC,OAAO,CAAC,CAAC,CAAC;IACjG;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/raster.ts"],"sourcesContent":["// Renders PDF pages to PNG with pdfjs-dist + @napi-rs/canvas. Shared by the\n// `render` CLI command (human/vision-model page verification) and src/engines/tesseract.ts (OCR page images).\n\nimport { createCanvas } from '@napi-rs/canvas';\nimport type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { PdfToMdError } from './errors.ts';\nimport { awaitPdfOpen, openPdfForRender } from './pdf-open.ts';\n\n// pdfjs-dist doesn't export RenderParameters from the package root; derive\n// it from PDFPageProxy['render'] rather than hand-declaring a shape that could drift.\ntype RenderParams = Parameters<PDFPageProxy['render']>[0];\n\n// No CanvasFactory shim needed: pdfjs-dist detects `@napi-rs/canvas` itself\n// and uses it internally (patterns, SMasks, Type3 glyphs); we only hand it a `canvasContext` for the page itself, created directly below.\n\nexport { openPdfForRender } from './pdf-open.ts';\n\n/** One rendered page, from renderPageToPNG (or the `pdf-to-md render` CLI\n * command it backs). */\nexport interface RenderPageResult {\n /** the rendered page, PNG-encoded */\n png: Buffer;\n /** pixel width at the requested dpi */\n width: number;\n /** pixel height at the requested dpi */\n height: number;\n /** the page's own /Rotate entry, baked into `png`/`width`/`height` already\n * — informational, not something a caller needs to apply again */\n rotation: number;\n}\n\n/** Render one already-open document's page to a PNG buffer at the given DPI. */\nexport async function renderLoadedPage(doc: PDFDocumentProxy, pageNum: number, dpi: number): Promise<RenderPageResult> {\n if (!(pageNum >= 1) || pageNum > doc.numPages) {\n throw new PdfToMdError('PAGE_RANGE', `page ${pageNum} is outside this document (1-${doc.numPages})`);\n }\n const page = await doc.getPage(pageNum);\n\n // getViewport({scale}) bakes in the page's own /Rotate entry AND its\n // mediaBox origin automatically — no manual origin translate needed on top of it.\n const scale = dpi / 72;\n const viewport = page.getViewport({ scale });\n const width = Math.round(viewport.width);\n const height = Math.round(viewport.height);\n if (width <= 0 || height <= 0) throw new PdfToMdError('PAGE_RENDER', `page ${pageNum} has non-positive dimensions ${width}x${height}`);\n\n const canvas = createCanvas(width, height);\n const context = canvas.getContext('2d');\n\n // Paint white first: an unpainted @napi-rs/canvas context is transparent,\n // which would encode as black/checkered rather than a white page.\n context.fillStyle = 'white';\n context.fillRect(0, 0, width, height);\n\n // pdfjs's RenderParameters types canvas/context against DOM types;\n // @napi-rs/canvas's are API-compatible at runtime but not that DOM type — the interop boundary the \"no any\" rule allows a cast for.\n const renderTask = page.render({\n canvas: canvas as unknown as RenderParams['canvas'],\n canvasContext: context as unknown as RenderParams['canvasContext'],\n viewport,\n });\n await renderTask.promise;\n\n const png = await canvas.encode('png');\n return { png, width, height, rotation: viewport.rotation };\n}\n\n/**\n * Render one page of a PDF to a PNG buffer at the given DPI. Opens and\n * closes the document itself — for more than one page from the same PDF, use `openPdfForRender` + `renderLoadedPage` instead.\n *\n * @param pdfPath path to the PDF file\n * @param pageNum 1-based page number\n * @param dpi PDF user space is 72 units/inch, so scale = dpi / 72\n */\nexport async function renderPageToPNG(pdfPath: string, pageNum: number, dpi: number): Promise<RenderPageResult> {\n const loadingTask = openPdfForRender(pdfPath);\n try {\n const doc = await awaitPdfOpen(loadingTask, pdfPath);\n return await renderLoadedPage(doc, pageNum, dpi);\n } finally {\n await loadingTask.destroy();\n }\n}\n"],"names":["createCanvas","PdfToMdError","awaitPdfOpen","openPdfForRender","renderLoadedPage","doc","pageNum","dpi","numPages","page","getPage","scale","viewport","getViewport","width","Math","round","height","canvas","context","getContext","fillStyle","fillRect","renderTask","render","canvasContext","promise","png","encode","rotation","renderPageToPNG","pdfPath","loadingTask","destroy"],"mappings":"AAAA,4EAA4E;AAC5E,8GAA8G;AAE9G,SAASA,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,YAAY,QAAQ,cAAc;AAC3C,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,gBAAgB;AAM/D,4EAA4E;AAC5E,0IAA0I;AAE1I,SAASA,gBAAgB,QAAQ,gBAAgB;AAgBjD,8EAA8E,GAC9E,OAAO,eAAeC,iBAAiBC,GAAqB,EAAEC,OAAe,EAAEC,GAAW;IACxF,IAAI,CAAED,CAAAA,WAAW,CAAA,KAAMA,UAAUD,IAAIG,QAAQ,EAAE;QAC7C,MAAM,IAAIP,aAAa,cAAc,CAAC,KAAK,EAAEK,QAAQ,6BAA6B,EAAED,IAAIG,QAAQ,CAAC,CAAC,CAAC;IACrG;IACA,MAAMC,OAAO,MAAMJ,IAAIK,OAAO,CAACJ;IAE/B,qEAAqE;IACrE,kFAAkF;IAClF,MAAMK,QAAQJ,MAAM;IACpB,MAAMK,WAAWH,KAAKI,WAAW,CAAC;QAAEF;IAAM;IAC1C,MAAMG,QAAQC,KAAKC,KAAK,CAACJ,SAASE,KAAK;IACvC,MAAMG,SAASF,KAAKC,KAAK,CAACJ,SAASK,MAAM;IACzC,IAAIH,SAAS,KAAKG,UAAU,GAAG,MAAM,IAAIhB,aAAa,eAAe,CAAC,KAAK,EAAEK,QAAQ,6BAA6B,EAAEQ,MAAM,CAAC,EAAEG,QAAQ;IAErI,MAAMC,SAASlB,aAAac,OAAOG;IACnC,MAAME,UAAUD,OAAOE,UAAU,CAAC;IAElC,0EAA0E;IAC1E,kEAAkE;IAClED,QAAQE,SAAS,GAAG;IACpBF,QAAQG,QAAQ,CAAC,GAAG,GAAGR,OAAOG;IAE9B,mEAAmE;IACnE,oIAAoI;IACpI,MAAMM,aAAad,KAAKe,MAAM,CAAC;QAC7BN,QAAQA;QACRO,eAAeN;QACfP;IACF;IACA,MAAMW,WAAWG,OAAO;IAExB,MAAMC,MAAM,MAAMT,OAAOU,MAAM,CAAC;IAChC,OAAO;QAAED;QAAKb;QAAOG;QAAQY,UAAUjB,SAASiB,QAAQ;IAAC;AAC3D;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeC,gBAAgBC,OAAe,EAAEzB,OAAe,EAAEC,GAAW;IACjF,MAAMyB,cAAc7B,iBAAiB4B;IACrC,IAAI;QACF,MAAM1B,MAAM,MAAMH,aAAa8B,aAAaD;QAC5C,OAAO,MAAM3B,iBAAiBC,KAAKC,SAASC;IAC9C,SAAU;QACR,MAAMyB,YAAYC,OAAO;IAC3B;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/raster.ts"],"sourcesContent":["// Renders PDF pages to PNG with pdfjs-dist + @napi-rs/canvas. Shared by the\n// `render` CLI command (human/vision-model page verification) and src/engines/tesseract.ts (OCR page images).\n\nimport { createCanvas } from '@napi-rs/canvas';\nimport type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { PdfToMdError } from './errors.ts';\nimport { awaitPdfOpen, openPdfForRender } from './pdf-open.ts';\n\n// pdfjs-dist doesn't export RenderParameters from the package root; derive\n// it from PDFPageProxy['render'] rather than hand-declaring a shape that could drift.\ntype RenderParams = Parameters<PDFPageProxy['render']>[0];\n\n// No CanvasFactory shim needed: pdfjs-dist detects `@napi-rs/canvas` itself\n// and uses it internally (patterns, SMasks, Type3 glyphs); we only hand it a `canvasContext` for the page itself, created directly below.\n\nexport { openPdfForRender } from './pdf-open.ts';\n\n/** One rendered page, from renderPageToPNG (or the `pdf-to-md render` CLI\n * command it backs). */\nexport interface RenderPageResult {\n /** the rendered page, PNG-encoded */\n png: Buffer;\n /** pixel width at the requested dpi */\n width: number;\n /** pixel height at the requested dpi */\n height: number;\n /** the page's own /Rotate entry, baked into `png`/`width`/`height` already\n * — informational, not something a caller needs to apply again */\n rotation: number;\n}\n\n/** Render one already-open document's page to a PNG buffer at the given DPI. */\nexport async function renderLoadedPage(doc: PDFDocumentProxy, pageNum: number, dpi: number): Promise<RenderPageResult> {\n if (!(pageNum >= 1) || pageNum > doc.numPages) {\n throw new PdfToMdError('PAGE_RANGE', `page ${pageNum} is outside this document (1-${doc.numPages})`);\n }\n const page = await doc.getPage(pageNum);\n\n // getViewport({scale}) bakes in the page's own /Rotate entry AND its\n // mediaBox origin automatically — no manual origin translate needed on top of it.\n const scale = dpi / 72;\n const viewport = page.getViewport({ scale });\n const width = Math.round(viewport.width);\n const height = Math.round(viewport.height);\n if (width <= 0 || height <= 0) throw new PdfToMdError('PAGE_RENDER', `page ${pageNum} has non-positive dimensions ${width}x${height}`);\n\n const canvas = createCanvas(width, height);\n const context = canvas.getContext('2d');\n\n // Paint white first: an unpainted @napi-rs/canvas context is transparent,\n // which would encode as black/checkered rather than a white page.\n context.fillStyle = 'white';\n context.fillRect(0, 0, width, height);\n\n // pdfjs's RenderParameters types canvas/context against DOM types;\n // @napi-rs/canvas's are API-compatible at runtime but not that DOM type — the interop boundary the \"no any\" rule allows a cast for.\n const renderTask = page.render({\n canvas: canvas as unknown as RenderParams['canvas'],\n canvasContext: context as unknown as RenderParams['canvasContext'],\n viewport,\n });\n await renderTask.promise;\n\n const png = await canvas.encode('png');\n return { png, width, height, rotation: viewport.rotation };\n}\n\n/**\n * Render one page of a PDF to a PNG buffer at the given DPI. Opens and\n * closes the document itself — for more than one page from the same PDF, use `openPdfForRender` + `renderLoadedPage` instead.\n *\n * @param pdfPath path to the PDF file\n * @param pageNum 1-based page number\n * @param dpi PDF user space is 72 units/inch, so scale = dpi / 72\n */\nexport async function renderPageToPNG(pdfPath: string, pageNum: number, dpi: number): Promise<RenderPageResult> {\n const loadingTask = openPdfForRender(pdfPath);\n try {\n const doc = await awaitPdfOpen(loadingTask, pdfPath);\n return await renderLoadedPage(doc, pageNum, dpi);\n } finally {\n await loadingTask.destroy();\n }\n}\n"],"names":["createCanvas","PdfToMdError","awaitPdfOpen","openPdfForRender","renderLoadedPage","doc","pageNum","dpi","numPages","page","getPage","scale","viewport","getViewport","width","Math","round","height","canvas","context","getContext","fillStyle","fillRect","renderTask","render","canvasContext","promise","png","encode","rotation","renderPageToPNG","pdfPath","loadingTask","destroy"],"mappings":"AAAA,4EAA4E;AAC5E,8GAA8G;AAE9G,SAASA,YAAY,QAAQ,kBAAkB;AAE/C,SAASC,YAAY,QAAQ,cAAc;AAC3C,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,gBAAgB;AAM/D,4EAA4E;AAC5E,0IAA0I;AAE1I,SAASA,gBAAgB,QAAQ,gBAAgB;AAgBjD,8EAA8E,GAC9E,OAAO,eAAeC,iBAAiBC,GAAqB,EAAEC,OAAe,EAAEC,GAAW;IACxF,IAAI,CAAED,CAAAA,WAAW,CAAA,KAAMA,UAAUD,IAAIG,QAAQ,EAAE;QAC7C,M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Users/kevin/Projects/pdf-to-md/src/render-analysis.ts"],"sourcesContent":["// Pure renderers over the Analysis IR: toMarkdown()/toText() are the public,\n// validated entry points; renderPagesToMarkdown/renderPagesToText below are the unvalidated core, reused (unvalidated) by src/analyze.ts.\nimport { PdfToMdError } from './errors.ts';\nimport { pageMarkerLine } from './page-marker.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage } from './types.ts';\n\nconst BLOCK_TYPES = new Set(['heading', 'paragraph', 'float', 'review']);\n\n// Whole-object, fail-fast validation: every page/block/wordIndexes entry is\n// checked BEFORE toMarkdown/toText render a single character — a malformed Analysis must never produce partial output, only a clean throw.\nfunction validateAnalysis(analysis: unknown): asserts analysis is Analysis {\n const fail = (msg: string): never => {\n throw new PdfToMdError('ANALYSIS_INPUT', msg);\n };\n if (typeof analysis !== 'object' || analysis === null) fail('Analysis must be an object');\n const a = analysis as Record<string, unknown>;\n if (typeof a.report !== 'object' || a.report === null) fail('Analysis.report must be an object');\n const path = (a.report as Record<string, unknown>).path;\n if (path !== 'text' && path !== 'ocr') fail(`Analysis.report.path must be \"text\" or \"ocr\" (got ${JSON.stringify(path)})`);\n if (!Array.isArray(a.pages)) fail('Analysis.pages must be an array');\n\n for (const [pi, page] of (a.pages as unknown[]).entries()) {\n if (typeof page !== 'object' || page === null) fail(`Analysis.pages[${pi}] must be an object`);\n const p = page as Record<string, unknown>;\n if (typeof p.page !== 'number') fail(`Analysis.pages[${pi}].page must be a number`);\n if (!Array.isArray(p.words)) fail(`Analysis.pages[${pi}].words must be an array`);\n for (const [wi, w] of (p.words as unknown[]).entries()) {\n if (typeof w !== 'object' || w === null || typeof (w as Record<string, unknown>).text !== 'string') {\n fail(`Analysis.pages[${pi}].words[${wi}] must be an object with a string 'text'`);\n }\n }\n const wordCount = (p.words as unknown[]).length;\n\n if (!Array.isArray(p.blocks)) fail(`Analysis.pages[${pi}].blocks must be an array`);\n for (const [bi, b] of (p.blocks as unknown[]).entries()) {\n if (typeof b !== 'object' || b === null) fail(`Analysis.pages[${pi}].blocks[${bi}] must be an object`);\n const block = b as Record<string, unknown>;\n if (typeof block.type !== 'string' || !BLOCK_TYPES.has(block.type)) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].type must be one of heading|paragraph|float|review (got ${JSON.stringify(block.type)})`);\n }\n if (typeof block.text !== 'string') fail(`Analysis.pages[${pi}].blocks[${bi}].text must be a string`);\n // `level` contract (see AnalysisBlock, src/types.ts): required 1-6 on a\n // heading, forbidden otherwise — rejected, not ignored, since it likely means `type` was mistyped.\n if (block.type === 'heading') {\n if (!Number.isInteger(block.level) || (block.level as number) < 1 || (block.level as number) > 6) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].level must be an integer 1-6 on a heading block (got ${JSON.stringify(block.level)})`);\n }\n } else if (block.level !== undefined) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].level is only allowed on heading blocks (got a ${JSON.stringify(block.type)} block with level ${JSON.stringify(block.level)})`);\n }\n if (!Array.isArray(block.wordIndexes)) fail(`Analysis.pages[${pi}].blocks[${bi}].wordIndexes must be an array`);\n for (const idx of block.wordIndexes as unknown[]) {\n if (typeof idx !== 'number' || !Number.isInteger(idx) || idx < 0 || idx >= wordCount) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].wordIndexes has an out-of-range index (${JSON.stringify(idx)}; page ${pi} has ${wordCount} words)`);\n }\n }\n }\n }\n}\n\n// See AnalysisBlock's doc comment (src/types.ts) for the `text` contract this relies on.\nfunction renderBlockLiteral(block: AnalysisBlock): string {\n // A heading's `level` is guaranteed present (1-6): validateAnalysis\n // enforces it, and src/analyze.ts (the only unvalidated caller) always sets it.\n if (block.type === 'heading') return `${'#'.repeat(block.level as number)} ${block.text}`;\n return block.text;\n}\n\n/** Unvalidated core, reused by `src/analyze.ts`. `forcePageMarkers` is the\n * OCR path's always-on \"### pN\"; `pageMarkers` is the text path's opt-in flag, ignored when `forcePageMarkers` is set. */\nexport function renderPagesToMarkdown(pages: AnalysisPage[], opts: { forcePageMarkers: boolean; pageMarkers: boolean }): string {\n let md = '';\n for (const page of pages) {\n if (opts.forcePageMarkers) md += `\\n${pageMarkerLine(page.page)}\\n\\n`;\n else if (opts.pageMarkers) md += `${pageMarkerLine(page.page)}\\n\\n`;\n for (const block of page.blocks) md += `${renderBlockLiteral(block)}\\n\\n`;\n }\n return md;\n}\n\n// Strips a block's markdown decoration for plain-text rendering (the inverse\n// of AnalysisBlock's literal-text convention); headings need no stripping.\nfunction bareBlockText(block: AnalysisBlock): string {\n if (block.type === 'heading') return block.text;\n if (block.type === 'review') return block.text.replace(/^> \\[review: [^\\]]*\\] /, '');\n if (block.type === 'float') return block.text.replace(/^> \\[floats\\] /, '');\n return block.text.replace(/^> /, '');\n}\n\nexport function renderPagesToText(pages: AnalysisPage[]): string {\n const out: string[] = [];\n for (const page of pages) {\n for (const block of page.blocks) out.push(bareBlockText(block));\n }\n return out.length ? `${out.join('\\n\\n').trim()}\\n` : '';\n}\n\n/**\n * Render an Analysis to markdown. PURE and fail-fast over any well-formed Analysis (including hand-built/spliced ones) — throws `PdfToMdError`/`'ANALYSIS_INPUT'` before any output on a malformed one.\n * OCR-origin output is byte-identical to extractOcr's own markdown (shared core); text-origin is NOT byte-identical to extractText's (see `AnalysisPage.words`, `src/types.ts`).\n *\n * @param analysis the Analysis to render (from analyze(), or hand-built/spliced)\n * @param opts.pageMarkers text-origin only; an OCR-origin Analysis always carries markers\n */\nexport function toMarkdown(analysis: Analysis, opts: { pageMarkers?: boolean } = {}): string {\n validateAnalysis(analysis);\n const isOcr = analysis.report.path === 'ocr';\n const md = renderPagesToMarkdown(analysis.pages, { forcePageMarkers: isOcr, pageMarkers: !!opts.pageMarkers });\n return isOcr ? md : `${md.trim()}\\n`;\n}\n\n/**\n * Render an Analysis to reading-order plain text: headings drop their `#`;\n * float/review content is INCLUDED with only its markdown decoration stripped, so no content is lost silently. Same fail-fast validation as toMarkdown.\n *\n * @param analysis the Analysis to render (from analyze(), or hand-built/spliced)\n */\nexport function toText(analysis: Analysis): string {\n validateAnalysis(analysis);\n return renderPagesToText(analysis.pages);\n}\n"],"names":["PdfToMdError","pageMarkerLine","BLOCK_TYPES","Set","validateAnalysis","analysis","fail","msg","a","report","path","JSON","stringify","Array","isArray","pages","pi","page","entries","p","words","wi","w","text","wordCount","length","blocks","bi","b","block","type","has","Number","isInteger","level","undefined","wordIndexes","idx","renderBlockLiteral","repeat","renderPagesToMarkdown","opts","md","forcePageMarkers","pageMarkers","bareBlockText","replace","renderPagesToText","out","push","join","trim","toMarkdown","isOcr","toText"],"mappings":"AAAA,6EAA6E;AAC7E,0IAA0I;AAC1I,SAASA,YAAY,QAAQ,cAAc;AAC3C,SAASC,cAAc,QAAQ,mBAAmB;AAGlD,MAAMC,cAAc,IAAIC,IAAI;IAAC;IAAW;IAAa;IAAS;CAAS;AAEvE,4EAA4E;AAC5E,2IAA2I;AAC3I,SAASC,iBAAiBC,QAAiB;IACzC,MAAMC,OAAO,CAACC;QACZ,MAAM,IAAIP,aAAa,kBAAkBO;IAC3C;IACA,IAAI,OAAOF,aAAa,YAAYA,aAAa,MAAMC,KAAK;IAC5D,MAAME,IAAIH;IACV,IAAI,OAAOG,EAAEC,MAAM,KAAK,YAAYD,EAAEC,MAAM,KAAK,MAAMH,KAAK;IAC5D,MAAMI,OAAO,AAACF,EAAEC,MAAM,CAA6BC,IAAI;IACvD,IAAIA,SAAS,UAAUA,SAAS,OAAOJ,KAAK,CAAC,kDAAkD,EAAEK,KAAKC,SAAS,CAACF,MAAM,CAAC,CAAC;IACxH,IAAI,CAACG,MAAMC,OAAO,CAACN,EAAEO,KAAK,GAAGT,KAAK;IAElC,KAAK,MAAM,CAACU,IAAIC,KAAK,IAAI,AAACT,EAAEO,KAAK,CAAeG,OAAO,GAAI;QACzD,IAAI,OAAOD,SAAS,YAAYA,SAAS,MAAMX,KAAK,CAAC,eAAe,EAAEU,GAAG,mBAAmB,CAAC;QAC7F,MAAMG,IAAIF;QACV,IAAI,OAAOE,EAAEF,I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,QAAQX,KAAK,GAAGA,GAAGS,IAAI,GAAG,EAAE,CAAC;AACtC;AAEA;;;;;CAKC,GACD,OAAO,SAASG,OAAOjD,QAAkB;IACvCD,iBAAiBC;IACjB,OAAO0C,kBAAkB1C,SAASU,KAAK;AACzC"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/render-analysis.ts"],"sourcesContent":["// Pure renderers over the Analysis IR: toMarkdown()/toText() are the public,\n// validated entry points; renderPagesToMarkdown/renderPagesToText below are the unvalidated core, reused (unvalidated) by src/analyze.ts.\nimport { PdfToMdError } from './errors.ts';\nimport { pageMarkerLine } from './page-marker.ts';\nimport type { Analysis, AnalysisBlock, AnalysisPage } from './types.ts';\n\nconst BLOCK_TYPES = new Set(['heading', 'paragraph', 'float', 'review']);\n\n// Whole-object, fail-fast validation: every page/block/wordIndexes entry is\n// checked BEFORE toMarkdown/toText render a single character — a malformed Analysis must never produce partial output, only a clean throw.\nfunction validateAnalysis(analysis: unknown): asserts analysis is Analysis {\n const fail = (msg: string): never => {\n throw new PdfToMdError('ANALYSIS_INPUT', msg);\n };\n if (typeof analysis !== 'object' || analysis === null) fail('Analysis must be an object');\n const a = analysis as Record<string, unknown>;\n if (typeof a.report !== 'object' || a.report === null) fail('Analysis.report must be an object');\n const path = (a.report as Record<string, unknown>).path;\n if (path !== 'text' && path !== 'ocr') fail(`Analysis.report.path must be \"text\" or \"ocr\" (got ${JSON.stringify(path)})`);\n if (!Array.isArray(a.pages)) fail('Analysis.pages must be an array');\n\n for (const [pi, page] of (a.pages as unknown[]).entries()) {\n if (typeof page !== 'object' || page === null) fail(`Analysis.pages[${pi}] must be an object`);\n const p = page as Record<string, unknown>;\n if (typeof p.page !== 'number') fail(`Analysis.pages[${pi}].page must be a number`);\n if (!Array.isArray(p.words)) fail(`Analysis.pages[${pi}].words must be an array`);\n for (const [wi, w] of (p.words as unknown[]).entries()) {\n if (typeof w !== 'object' || w === null || typeof (w as Record<string, unknown>).text !== 'string') {\n fail(`Analysis.pages[${pi}].words[${wi}] must be an object with a string 'text'`);\n }\n }\n const wordCount = (p.words as unknown[]).length;\n\n if (!Array.isArray(p.blocks)) fail(`Analysis.pages[${pi}].blocks must be an array`);\n for (const [bi, b] of (p.blocks as unknown[]).entries()) {\n if (typeof b !== 'object' || b === null) fail(`Analysis.pages[${pi}].blocks[${bi}] must be an object`);\n const block = b as Record<string, unknown>;\n if (typeof block.type !== 'string' || !BLOCK_TYPES.has(block.type)) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].type must be one of heading|paragraph|float|review (got ${JSON.stringify(block.type)})`);\n }\n if (typeof block.text !== 'string') fail(`Analysis.pages[${pi}].blocks[${bi}].text must be a string`);\n // `level` contract (see AnalysisBlock, src/types.ts): required 1-6 on a\n // heading, forbidden otherwise — rejected, not ignored, since it likely means `type` was mistyped.\n if (block.type === 'heading') {\n if (!Number.isInteger(block.level) || (block.level as number) < 1 || (block.level as number) > 6) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].level must be an integer 1-6 on a heading block (got ${JSON.stringify(block.level)})`);\n }\n } else if (block.level !== undefined) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].level is only allowed on heading blocks (got a ${JSON.stringify(block.type)} block with level ${JSON.stringify(block.level)})`);\n }\n if (!Array.isArray(block.wordIndexes)) fail(`Analysis.pages[${pi}].blocks[${bi}].wordIndexes must be an array`);\n for (const idx of block.wordIndexes as unknown[]) {\n if (typeof idx !== 'number' || !Number.isInteger(idx) || idx < 0 || idx >= wordCount) {\n fail(`Analysis.pages[${pi}].blocks[${bi}].wordIndexes has an out-of-range index (${JSON.stringify(idx)}; page ${pi} has ${wordCount} words)`);\n }\n }\n }\n }\n}\n\n// See AnalysisBlock's doc comment (src/types.ts) for the `text` contract this relies on.\nfunction renderBlockLiteral(block: AnalysisBlock): string {\n // A heading's `level` is guaranteed present (1-6): validateAnalysis\n // enforces it, and src/analyze.ts (the only unvalidated caller) always sets it.\n if (block.type === 'heading') return `${'#'.repeat(block.level as number)} ${block.text}`;\n return block.text;\n}\n\n/** Unvalidated core, reused by `src/analyze.ts`. `forcePageMarkers` is the\n * OCR path's always-on \"### pN\"; `pageMarkers` is the text path's opt-in flag, ignored when `forcePageMarkers` is set. */\nexport function renderPagesToMarkdown(pages: AnalysisPage[], opts: { forcePageMarkers: boolean; pageMarkers: boolean }): string {\n let md = '';\n for (const page of pages) {\n if (opts.forcePageMarkers) md += `\\n${pageMarkerLine(page.page)}\\n\\n`;\n else if (opts.pageMarkers) md += `${pageMarkerLine(page.page)}\\n\\n`;\n for (const block of page.blocks) md += `${renderBlockLiteral(block)}\\n\\n`;\n }\n return md;\n}\n\n// Strips a block's markdown decoration for plain-text rendering (the inverse\n// of AnalysisBlock's literal-text convention); headings need no stripping.\nfunction bareBlockText(block: AnalysisBlock): string {\n if (block.type === 'heading') return block.text;\n if (block.type === 'review') return block.text.replace(/^> \\[review: [^\\]]*\\] /, '');\n if (block.type === 'float') return block.text.replace(/^> \\[floats\\] /, '');\n return block.text.replace(/^> /, '');\n}\n\nexport function renderPagesToText(pages: AnalysisPage[]): string {\n const out: string[] = [];\n for (const page of pages) {\n for (const block of page.blocks) out.push(bareBlockText(block));\n }\n return out.length ? `${out.join('\\n\\n').trim()}\\n` : '';\n}\n\n/**\n * Render an Analysis to markdown. PURE and fail-fast over any well-formed Analysis (including hand-built/spliced ones) — throws `PdfToMdError`/`'ANALYSIS_INPUT'` before any output on a malformed one.\n * OCR-origin output is byte-identical to extractOcr's own markdown (shared core); text-origin is NOT byte-identical to extractText's (see `AnalysisPage.words`, `src/types.ts`).\n *\n * @param analysis the Analysis to render (from analyze(), or hand-built/spliced)\n * @param opts.pageMarkers text-origin only; an OCR-origin Analysis always carries markers\n */\nexport function toMarkdown(analysis: Analysis, opts: { pageMarkers?: boolean } = {}): string {\n validateAnalysis(analysis);\n const isOcr = analysis.report.path === 'ocr';\n const md = renderPagesToMarkdown(analysis.pages, { forcePageMarkers: isOcr, pageMarkers: !!opts.pageMarkers });\n return isOcr ? md : `${md.trim()}\\n`;\n}\n\n/**\n * Render an Analysis to reading-order plain text: headings drop their `#`;\n * float/review content is INCLUDED with only its markdown decoration stripped, so no content is lost silently. Same fail-fast validation as toMarkdown.\n *\n * @param analysis the Analysis to render (from analyze(), or hand-built/spliced)\n */\nexport function toText(analysis: Analysis): string {\n validateAnalysis(analysis);\n return renderPagesToText(analysis.pages);\n}\n"],"names":["PdfToMdError","pageMarkerLine","BLOCK_TYPES","Set","validateAnalysis","analysis","fail","msg","a","report","path","JSON","stringify","Array","isArray","pages","pi","page","entries","p","words","wi","w","text","wordCount","length","blocks","bi","b","block","type","has","Number","isInteger","level","undefined","wordIndexes","idx","renderBlockLiteral","repeat","renderPagesToMarkdown","opts","md","forcePageMarkers","pageMarkers","bareBlockText","replace","renderPagesToText","out","push","join","trim","toMarkdown","isOcr","toText"],"mappings":"AAAA,6EAA6E;AAC7E,0IAA0I;AAC1I,SAASA,YAAY,QAAQ,cAAc;AAC3C,SAASC,cAAc,QAAQ,mBAAmB;AAGlD,MAAMC,cAAc,IAAIC,IAAI;IAAC;IAAW;IAAa;IAAS;CAAS;AAEvE,4EAA4E;AAC5E,2IAA2I;AAC3I,SAASC,iBAAiBC,QAAiB;IACzC,MAAMC,OAAO,CAACC;QACZ,MAAM,IAAIP,aAAa,kBAAkBO;IAC3C;IACA,IAAI,OAAOF,aAAa,YAAYA,aAAa,MAAMC,KAAK;IAC5D,MAAME,IAAIH;IACV,IAAI,OAAOG,EAAEC,MAAM,KAAK,YAAYD,EAAEC,MAAM,KAAK,MAAMH,KAAK;IAC5D,MAAMI,OAAO,AAACF,EAAEC,MAAM,CAA6BC,IAAI;IACvD,IAAIA,SAAS,UAAUA,SAAS,OAAOJ,KAAK,CAAC,kDAAkD,EAAEK,KAAKC,SAAS,CAACF,MAAM,CAAC,CAAC;IACxH,IAAI,CAACG,MAAMC,OAAO,CAACN,EAAEO,KAAK,GAAGT,KAAK;IAElC,KAAK,MAAM,CA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AC;IACjFrC,iBAAiBC;IACjB,MAAMgD,QAAQhD,SAASI,MAAM,CAACC,IAAI,KAAK;IACvC,MAAMgC,KAAKF,sBAAsBnC,SAASU,KAAK,EAAE;QAAE4B,kBAAkBU;QAAOT,aAAa,CAAC,CAACH,KAAKG,WAAW;IAAC;IAC5G,OAAOS,QAAQX,KAAK,GAAGA,GAAGS,IAAI,GAAG,EAAE,CAAC;AACtC;AAEA;;;;;CAKC,GACD,OAAO,SAASG,OAAOjD,QAAkB;IACvCD,iBAAiBC;IACjB,OAAO0C,kBAAkB1C,SAASU,KAAK;AACzC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/report.ts"],"sourcesContent":["// report.ts — QA report over an extraction, machine-readable with --json.\nimport { countPageMarkers, isPageMarkerLine, splitByPageMarker } from './page-marker.ts';\nimport type { BuildOcrReportInput, BuildReportInput, PageStatsRow, Report, WordConfidenceInput } from './types.ts';\n\n// < SPARSE warns only; < AUTO_OCR means the pages are certainly images (measured:\n// an image-only 100-pager yields ~4 chars/page) and the auto-OCR fallback fires.\nexport const SPARSE_CHARS_PER_PAGE = 200;\nexport const AUTO_OCR_CHARS_PER_PAGE = 20;\n\n/** A manually-bumped integer, deliberately not the npm package version —\n * bump whenever a change can alter output for identical input. See `CHANGELOG.md` for history. */\nexport const OUTPUT_VERSION = 1;\n\n// A body paragraph line may end in sentence/clause punctuation, a closing\n// quote/bracket, an ellipsis, or a digit (chart/label lines like \"1/3\" legitimately end in a number).\nconst TERMINAL_PUNCT = /[.!?:;\"”'’)\\]…0-9]$/;\n\n// Lines that are not body prose at all: headings (incl. \"### pN\" markers),\n// floats/blockquotes, table rows, and list items — excluded before TERMINAL_PUNCT runs.\nconst NON_PROSE_LINE = /^[#>|*-]/;\n\n// A `> [review: reason] text` line (src/emit.ts). Shared by pageStats (per\n// page) and both top-level report builders (whole doc) so the counts can't drift apart.\nconst REVIEW_LINE = /^> \\[review: /gm;\n\n// Dangling lines split by length: long ones are the invisible column-break/splice\n// signal; short ones are usually a missed heading or an unjoined label.\nconst DANGLING_LONG_MIN = 60;\n\n/** Below this per-word confidence (0-100, tesseract.js's `confidence`), a\n * word counts as low-confidence. Measured: junk max 43 vs prose min 76, cut 60, 2026-08-17. */\nexport const LOW_CONFIDENCE_THRESHOLD = 60;\n\n// Cap on `lowConfidenceSample`'s length per page — a few representative\n// offenders, not the whole page re-emitted a second time.\nexport const LOW_CONFIDENCE_SAMPLE_CAP = 12;\n\ninterface LowConfidenceStats {\n measured: number; // words on this page that carried a confidence value at all\n low: number; // of those, how many scored below LOW_CONFIDENCE_THRESHOLD\n sample: string[]; // worst-confidence-first, capped list of the actual low-confidence tokens\n}\n\n// Grouped from the flat recognized-word list (confidence is per-word, never\n// merged into a line — see Word's comment). `measured` is tracked separately from `low` so a page with nothing to measure reports ABSENT, not a lying zero.\nfunction lowConfidenceByPage(words: WordConfidenceInput[]): Map<number, LowConfidenceStats> {\n const byPage = new Map<number, { measured: number; low: number; lowWords: { text: string; confidence: number }[] }>();\n for (const w of words) {\n if (w.confidence === undefined) continue;\n const entry = byPage.get(w.page) ?? { measured: 0, low: 0, lowWords: [] };\n entry.measured++;\n if (w.confidence < LOW_CONFIDENCE_THRESHOLD) {\n entry.low++;\n entry.lowWords.push({ text: w.text, confidence: w.confidence });\n }\n byPage.set(w.page, entry);\n }\n const result = new Map<number, LowConfidenceStats>();\n for (const [page, entry] of byPage) {\n // Sort ascending by confidence BEFORE capping, so the cap keeps the\n // worst offenders regardless of appearance order.\n const sample = entry.lowWords\n .slice()\n .sort((a, b) => a.confidence - b.confidence)\n .slice(0, LOW_CONFIDENCE_SAMPLE_CAP)\n .map((w) => w.text);\n result.set(page, { measured: entry.measured, low: entry.low, sample });\n }\n return result;\n}\n\ninterface DanglingCounts {\n long: number;\n short: number;\n}\n\n// Counts of body paragraph LINES ending WITHOUT terminal punctuation, split\n// by length: `long` is the invisible column-break/splice signal; `short` is usually a missed heading or unjoined label.\nfunction danglingCounts(body: string): DanglingCounts {\n let long = 0;\n let short = 0;\n for (const raw of body.split('\\n')) {\n const line = raw.trim();\n if (!line || NON_PROSE_LINE.test(line)) continue;\n if (TERMINAL_PUNCT.test(line)) continue;\n if (line.length >= DANGLING_LONG_MIN) long++;\n else short++;\n }\n return { long, short };\n}\n\n// One page's own measured stats, derivable from its body text alone —\n// shared by `pageStats` and any future caller that already has a page's body text in hand.\nfunction measurePage(body: string): Omit<PageStatsRow, 'page' | 'largeImages' | 'lowConfidenceWords' | 'lowConfidenceSample'> {\n const heads = body.match(/^#{1,6}\\s*(.+)$/gm) || [];\n const dangling = danglingCounts(body);\n return {\n chars: body.length,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n floats: (body.match(/^> \\[floats\\]/gm) || []).length,\n paragraphs: (body.match(/^(?![#>-])\\S.*$/gm) || []).length,\n danglingLong: dangling.long,\n danglingShort: dangling.short,\n reviewBlocks: (body.match(REVIEW_LINE) || []).length,\n };\n}\n\n// Per-page QA rows, one per \"### pN\" block. The text path always passes\n// markdown with markers forced on (`statsMd`) regardless of `--page-markers`, so pageStats is always populated.\n//\n// `hybridPages` (text path only) marks a row `largeImages: true` when that\n// page used its text layer but also carries a large embedded image; omitted entirely on the OCR path, which has no equivalent signal.\nfunction pageStats(md: string, hybridPages?: number[]): PageStatsRow[] {\n const rows: PageStatsRow[] = [];\n for (const { page, body } of splitByPageMarker(md)) {\n const row: PageStatsRow = { page, ...measurePage(body) };\n if (hybridPages) row.largeImages = hybridPages.includes(page);\n rows.push(row);\n }\n return rows;\n}\n\nexport function buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages = [] }: BuildReportInput): Report {\n const heads = (md.match(/^#{1,6}\\s*(.+)$/gm) || []).filter((h) => !isPageMarkerLine(h)); // page markers are provenance, not structure\n const perPage = Math.round(md.length / numPages);\n const perPageStats = pageStats(statsMd, hybridPages);\n return {\n outputVersion: OUTPUT_VERSION,\n path: 'text',\n pages: numPages,\n bodyFontHeight: bodyH,\n headingSizes: headingSizes.slice(0, 6),\n chars: md.length,\n charsPerPage: perPage,\n sparse: perPage < SPARSE_CHARS_PER_PAGE,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n listItems: stats.listItems,\n paragraphs: stats.paragraphs,\n joinedPairs: stats.joinedPairs,\n callouts: stats.callouts,\n closedHyphens: stats.closedHyphens,\n danglingLong: perPageStats.reduce((sum, r) => sum + r.danglingLong, 0),\n danglingShort: perPageStats.reduce((sum, r) => sum + r.danglingShort, 0),\n reviewBlocks: perPageStats.reduce((sum, r) => sum + r.reviewBlocks, 0),\n // The text path never sees per-word confidence at all; 0 here means\n // \"nothing to measure\" (see PageStatsRow's field doc), not \"measured 0\".\n lowConfidenceWords: 0,\n hybridPages,\n pageStats: perPageStats,\n };\n}\n\n// QA report for the OCR path: measured from the emitted markdown text.\n// `fallback` records that the text layer was tried first and found empty.\nexport function buildOcrReport({ md, fallback, words = [] }: BuildOcrReportInput): Report {\n const numPages = countPageMarkers(md);\n const heads = (md.match(/^#{1,6}\\s*(.+)$/gm) || []).filter((h) => !isPageMarkerLine(h));\n const perPage = numPages ? Math.round(md.length / numPages) : 0;\n const perPageStats = pageStats(md);\n // Attach the low-confidence detector's per-page results after the fact:\n // pageStats() has no confidence data (it reads markdown text only), so join it in here by page number.\n const lowConf = lowConfidenceByPage(words);\n for (const row of perPageStats) {\n const entry = lowConf.get(row.page);\n if (entry && entry.measured > 0) {\n row.lowConfidenceWords = entry.low;\n if (entry.sample.length) row.lowConfidenceSample = entry.sample;\n }\n }\n return {\n outputVersion: OUTPUT_VERSION,\n path: 'ocr',\n pages: numPages,\n ocrFallback: !!fallback,\n chars: md.length,\n charsPerPage: perPage,\n sparse: perPage < SPARSE_CHARS_PER_PAGE,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n paragraphs: (md.match(/^(?![#>-])\\S.*$/gm) || []).length,\n // Exclude BOTH \"[floats]\" and \"[review: ...]\" lines — a review marker is\n // a labeled unstructured block, not a genuine callout.\n callouts: (md.match(/^> (?!\\[floats\\]|\\[review:)/gm) || []).length,\n floats: (md.match(/^> \\[floats\\]/gm) || []).length,\n danglingLong: perPageStats.reduce((sum, r) => sum + r.danglingLong, 0),\n danglingShort: perPageStats.reduce((sum, r) => sum + r.danglingShort, 0),\n reviewBlocks: perPageStats.reduce((sum, r) => sum + r.reviewBlocks, 0),\n lowConfidenceWords: perPageStats.reduce((sum, r) => sum + (r.lowConfidenceWords ?? 0), 0),\n pageStats: perPageStats,\n };\n}\n"],"names":["countPageMarkers","isPageMarkerLine","splitByPageMarker","SPARSE_CHARS_PER_PAGE","AUTO_OCR_CHARS_PER_PAGE","OUTPUT_VERSION","TERMINAL_PUNCT","NON_PROSE_LINE","REVIEW_LINE","DANGLING_LONG_MIN","LOW_CONFIDENCE_THRESHOLD","LOW_CONFIDENCE_SAMPLE_CAP","lowConfidenceByPage","words","byPage","Map","w","confidence","undefined","entry","get","page","measured","low","lowWords","push","text","set","result","sample","slice","sort","a","b","map","danglingCounts","body","long","short","raw","split","line","trim","test","length","measurePage","heads","match","dangling","chars","headings","junkHeadings","filter","h","floats","paragraphs","danglingLong","danglingShort","reviewBlocks","pageStats","md","hybridPages","rows","row","largeImages","includes","buildReport","numPages","statsMd","stats","bodyH","headingSizes","perPage","Math","round","perPageStats","outputVersion","path","pages","bodyFontHeight","charsPerPage","sparse","listItems","joinedPairs","callouts","closedHyphens","reduce","sum","r","lowConfidenceWords","buildOcrReport","fallback","lowConf","lowConfidenceSample","ocrFallback"],"mappings":"AAAA,0EAA0E;AAC1E,SAASA,gBAAgB,EAAEC,gBAAgB,EAAEC,iBAAiB,QAAQ,mBAAmB;AAGzF,kFAAkF;AAClF,iFAAiF;AACjF,OAAO,MAAMC,wBAAwB,IAAI;AACzC,OAAO,MAAMC,0BAA0B,GAAG;AAE1C;gGACgG,GAChG,OAAO,MA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U,AAACxB,CAAAA,GAAGb,KAAK,CAAC,oCAAoC,EAAE,AAAD,EAAGH,MAAM;QAClEU,QAAQ,AAACM,CAAAA,GAAGb,KAAK,CAAC,sBAAsB,EAAE,AAAD,EAAGH,MAAM;QAClDY,cAAcmB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAEhC,YAAY,EAAE;QACpEC,eAAekB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAE/B,aAAa,EAAE;QACtEC,cAAciB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAE9B,YAAY,EAAE;QACpE+B,oBAAoBd,aAAaW,MAAM,CAAC,CAACC,KAAKC;gBAAaA;mBAAPD,QAAOC,wBAAAA,EAAEC,kBAAkB,cAApBD,mCAAAA,wBAAwB;WAAI;QACvF7B,WAAWgB;IACb;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/report.ts"],"sourcesContent":["// report.ts — QA report over an extraction, machine-readable with --json.\nimport { countPageMarkers, isPageMarkerLine, splitByPageMarker } from './page-marker.ts';\nimport type { BuildOcrReportInput, BuildReportInput, PageStatsRow, Report, WordConfidenceInput } from './types.ts';\n\n// < SPARSE warns only; < AUTO_OCR means the pages are certainly images (measured:\n// an image-only 100-pager yields ~4 chars/page) and the auto-OCR fallback fires.\nexport const SPARSE_CHARS_PER_PAGE = 200;\nexport const AUTO_OCR_CHARS_PER_PAGE = 20;\n\n/** A manually-bumped integer, deliberately not the npm package version —\n * bump whenever a change can alter output for identical input. See `CHANGELOG.md` for history. */\nexport const OUTPUT_VERSION = 1;\n\n// A body paragraph line may end in sentence/clause punctuation, a closing\n// quote/bracket, an ellipsis, or a digit (chart/label lines like \"1/3\" legitimately end in a number).\nconst TERMINAL_PUNCT = /[.!?:;\"”'’)\\]…0-9]$/;\n\n// Lines that are not body prose at all: headings (incl. \"### pN\" markers),\n// floats/blockquotes, table rows, and list items — excluded before TERMINAL_PUNCT runs.\nconst NON_PROSE_LINE = /^[#>|*-]/;\n\n// A `> [review: reason] text` line (src/emit.ts). Shared by pageStats (per\n// page) and both top-level report builders (whole doc) so the counts can't drift apart.\nconst REVIEW_LINE = /^> \\[review: /gm;\n\n// Dangling lines split by length: long ones are the invisible column-break/splice\n// signal; short ones are usually a missed heading or an unjoined label.\nconst DANGLING_LONG_MIN = 60;\n\n/** Below this per-word confidence (0-100, tesseract.js's `confidence`), a\n * word counts as low-confidence. Measured: junk max 43 vs prose min 76, cut 60, 2026-08-17. */\nexport const LOW_CONFIDENCE_THRESHOLD = 60;\n\n// Cap on `lowConfidenceSample`'s length per page — a few representative\n// offenders, not the whole page re-emitted a second time.\nexport const LOW_CONFIDENCE_SAMPLE_CAP = 12;\n\ninterface LowConfidenceStats {\n measured: number; // words on this page that carried a confidence value at all\n low: number; // of those, how many scored below LOW_CONFIDENCE_THRESHOLD\n sample: string[]; // worst-confidence-first, capped list of the actual low-confidence tokens\n}\n\n// Grouped from the flat recognized-word list (confidence is per-word, never\n// merged into a line — see Word's comment). `measured` is tracked separately from `low` so a page with nothing to measure reports ABSENT, not a lying zero.\nfunction lowConfidenceByPage(words: WordConfidenceInput[]): Map<number, LowConfidenceStats> {\n const byPage = new Map<number, { measured: number; low: number; lowWords: { text: string; confidence: number }[] }>();\n for (const w of words) {\n if (w.confidence === undefined) continue;\n const entry = byPage.get(w.page) ?? { measured: 0, low: 0, lowWords: [] };\n entry.measured++;\n if (w.confidence < LOW_CONFIDENCE_THRESHOLD) {\n entry.low++;\n entry.lowWords.push({ text: w.text, confidence: w.confidence });\n }\n byPage.set(w.page, entry);\n }\n const result = new Map<number, LowConfidenceStats>();\n for (const [page, entry] of byPage) {\n // Sort ascending by confidence BEFORE capping, so the cap keeps the\n // worst offenders regardless of appearance order.\n const sample = entry.lowWords\n .slice()\n .sort((a, b) => a.confidence - b.confidence)\n .slice(0, LOW_CONFIDENCE_SAMPLE_CAP)\n .map((w) => w.text);\n result.set(page, { measured: entry.measured, low: entry.low, sample });\n }\n return result;\n}\n\ninterface DanglingCounts {\n long: number;\n short: number;\n}\n\n// Counts of body paragraph LINES ending WITHOUT terminal punctuation, split\n// by length: `long` is the invisible column-break/splice signal; `short` is usually a missed heading or unjoined label.\nfunction danglingCounts(body: string): DanglingCounts {\n let long = 0;\n let short = 0;\n for (const raw of body.split('\\n')) {\n const line = raw.trim();\n if (!line || NON_PROSE_LINE.test(line)) continue;\n if (TERMINAL_PUNCT.test(line)) continue;\n if (line.length >= DANGLING_LONG_MIN) long++;\n else short++;\n }\n return { long, short };\n}\n\n// One page's own measured stats, derivable from its body text alone —\n// shared by `pageStats` and any future caller that already has a page's body text in hand.\nfunction measurePage(body: string): Omit<PageStatsRow, 'page' | 'largeImages' | 'lowConfidenceWords' | 'lowConfidenceSample'> {\n const heads = body.match(/^#{1,6}\\s*(.+)$/gm) || [];\n const dangling = danglingCounts(body);\n return {\n chars: body.length,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n floats: (body.match(/^> \\[floats\\]/gm) || []).length,\n paragraphs: (body.match(/^(?![#>-])\\S.*$/gm) || []).length,\n danglingLong: dangling.long,\n danglingShort: dangling.short,\n reviewBlocks: (body.match(REVIEW_LINE) || []).length,\n };\n}\n\n// Per-page QA rows, one per \"### pN\" block. The text path always passes\n// markdown with markers forced on (`statsMd`) regardless of `--page-markers`, so pageStats is always populated.\n//\n// `hybridPages` (text path only) marks a row `largeImages: true` when that\n// page used its text layer but also carries a large embedded image; omitted entirely on the OCR path, which has no equivalent signal.\nfunction pageStats(md: string, hybridPages?: number[]): PageStatsRow[] {\n const rows: PageStatsRow[] = [];\n for (const { page, body } of splitByPageMarker(md)) {\n const row: PageStatsRow = { page, ...measurePage(body) };\n if (hybridPages) row.largeImages = hybridPages.includes(page);\n rows.push(row);\n }\n return rows;\n}\n\nexport function buildReport({ numPages, md, statsMd, stats, bodyH, headingSizes, hybridPages = [] }: BuildReportInput): Report {\n const heads = (md.match(/^#{1,6}\\s*(.+)$/gm) || []).filter((h) => !isPageMarkerLine(h)); // page markers are provenance, not structure\n const perPage = Math.round(md.length / numPages);\n const perPageStats = pageStats(statsMd, hybridPages);\n return {\n outputVersion: OUTPUT_VERSION,\n path: 'text',\n pages: numPages,\n bodyFontHeight: bodyH,\n headingSizes: headingSizes.slice(0, 6),\n chars: md.length,\n charsPerPage: perPage,\n sparse: perPage < SPARSE_CHARS_PER_PAGE,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n listItems: stats.listItems,\n paragraphs: stats.paragraphs,\n joinedPairs: stats.joinedPairs,\n callouts: stats.callouts,\n closedHyphens: stats.closedHyphens,\n danglingLong: perPageStats.reduce((sum, r) => sum + r.danglingLong, 0),\n danglingShort: perPageStats.reduce((sum, r) => sum + r.danglingShort, 0),\n reviewBlocks: perPageStats.reduce((sum, r) => sum + r.reviewBlocks, 0),\n // The text path never sees per-word confidence at all; 0 here means\n // \"nothing to measure\" (see PageStatsRow's field doc), not \"measured 0\".\n lowConfidenceWords: 0,\n hybridPages,\n pageStats: perPageStats,\n };\n}\n\n// QA report for the OCR path: measured from the emitted markdown text.\n// `fallback` records that the text layer was tried first and found empty.\nexport function buildOcrReport({ md, fallback, words = [] }: BuildOcrReportInput): Report {\n const numPages = countPageMarkers(md);\n const heads = (md.match(/^#{1,6}\\s*(.+)$/gm) || []).filter((h) => !isPageMarkerLine(h));\n const perPage = numPages ? Math.round(md.length / numPages) : 0;\n const perPageStats = pageStats(md);\n // Attach the low-confidence detector's per-page results after the fact:\n // pageStats() has no confidence data (it reads markdown text only), so join it in here by page number.\n const lowConf = lowConfidenceByPage(words);\n for (const row of perPageStats) {\n const entry = lowConf.get(row.page);\n if (entry && entry.measured > 0) {\n row.lowConfidenceWords = entry.low;\n if (entry.sample.length) row.lowConfidenceSample = entry.sample;\n }\n }\n return {\n outputVersion: OUTPUT_VERSION,\n path: 'ocr',\n pages: numPages,\n ocrFallback: !!fallback,\n chars: md.length,\n charsPerPage: perPage,\n sparse: perPage < SPARSE_CHARS_PER_PAGE,\n headings: heads.length,\n junkHeadings: heads.filter((h) => !/[A-Za-z]{3}/.test(h)).length,\n paragraphs: (md.match(/^(?![#>-])\\S.*$/gm) || []).length,\n // Exclude BOTH \"[floats]\" and \"[review: ...]\" lines — a review marker is\n // a labeled unstructured block, not a genuine callout.\n callouts: (md.match(/^> (?!\\[floats\\]|\\[review:)/gm) || []).length,\n floats: (md.match(/^> \\[floats\\]/gm) || []).length,\n danglingLong: perPageStats.reduce((sum, r) => sum + r.danglingLong, 0),\n danglingShort: perPageStats.reduce((sum, r) => sum + r.danglingShort, 0),\n reviewBlocks: perPageStats.reduce((sum, r) => sum + r.reviewBlocks, 0),\n lowConfidenceWords: perPageStats.reduce((sum, r) => sum + (r.lowConfidenceWords ?? 0), 0),\n pageStats: perPageStats,\n };\n}\n"],"names":["countPageMarkers","isPageMarkerLine","splitByPageMarker","SPARSE_CHARS_PER_PAGE","AUTO_OCR_CHARS_PER_PAGE","OUTPUT_VERSION","TERMINAL_PUNCT","NON_PROSE_LINE","REVIEW_LINE","DANGLING_LONG_MIN","LOW_CONFIDENCE_THRESHOLD","LOW_CONFIDENCE_SAMPLE_CAP","lowConfidenceByPage","words","byPage","Map","w","confidence","undefined","entry","get","page","measured","low","lowWords","push","text","set","result","sample","slice","sort","a","b","map","danglingCounts","body","long","short","raw","split","line","trim","test","length","measurePage","heads","match","dangling","chars","headings","junkHeadings","filter","h","floats","paragraphs","danglingLong","danglingShort","reviewBlocks","pageStats","md","hybridPages","rows","row","largeImages","includes","buildReport","numPages","statsMd","stats","bodyH","headingSizes","perPage","Math","round","perPageStats","outputVersion","path","pages","bodyFontHeight","charsPerPage","sparse","listItems","joinedPairs","callouts","closedHyphens","reduce","sum","r","lowConfidenceWords","buildOcrReport","fallback","lowConf","lowConfidenceSample","ocrFallback"],"mappings":"AAAA,0EAA0E;AAC1E,SAASA,g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AM,CAAC,CAACC,IAAM,CAAC,cAAcV,IAAI,CAACU,IAAIT,MAAM;QAChEW,YAAY,AAACK,CAAAA,GAAGb,KAAK,CAAC,wBAAwB,EAAE,AAAD,EAAGH,MAAM;QACxD,yEAAyE;QACzE,uDAAuD;QACvDwC,UAAU,AAACxB,CAAAA,GAAGb,KAAK,CAAC,oCAAoC,EAAE,AAAD,EAAGH,MAAM;QAClEU,QAAQ,AAACM,CAAAA,GAAGb,KAAK,CAAC,sBAAsB,EAAE,AAAD,EAAGH,MAAM;QAClDY,cAAcmB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAEhC,YAAY,EAAE;QACpEC,eAAekB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAE/B,aAAa,EAAE;QACtEC,cAAciB,aAAaW,MAAM,CAAC,CAACC,KAAKC,IAAMD,MAAMC,EAAE9B,YAAY,EAAE;QACpE+B,oBAAoBd,aAAaW,MAAM,CAAC,CAACC,KAAKC;gBAAaA;mBAAPD,QAAOC,wBAAAA,EAAEC,kBAAkB,cAApBD,mCAAAA,wBAAwB;WAAI;QACvF7B,WAAWgB;IACb;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/resolve.ts"],"sourcesContent":["// Resolves an installed package file's on-disk path for both build targets:\n// ESM's import.meta.resolve returns a file:// URL, the CJS build's rewritten require.resolve a plain path — normalizes both to a plain path.\nimport { fileURLToPath } from 'node:url';\n\nexport function resolvePackagePath(specifier: string): string {\n const resolved = import.meta.resolve(specifier);\n return resolved.startsWith('file://') ? fileURLToPath(resolved) : resolved;\n}\n"],"names":["fileURLToPath","resolvePackagePath","specifier","resolved","resolve","startsWith"],"mappings":"AAAA,4EAA4E;AAC5E,6IAA6I;AAC7I,SAASA,aAAa,QAAQ,WAAW;AAEzC,OAAO,SAASC,mBAAmBC,SAAiB;IAClD,MAAMC,WAAW,YAAYC,OAAO,CAACF;IACrC,OAAOC,SAASE,UAAU,CAAC,aAAaL,cAAcG,YAAYA;AACpE"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/resolve.ts"],"sourcesContent":["// Resolves an installed package file's on-disk path for both build targets:\n// ESM's import.meta.resolve returns a file:// URL, the CJS build's rewritten require.resolve a plain path — normalizes both to a plain path.\nimport { fileURLToPath } from 'node:url';\n\nexport function resolvePackagePath(specifier: string): string {\n const resolved = import.meta.resolve(specifier);\n return resolved.startsWith('file://') ? fileURLToPath(resolved) : resolved;\n}\n"],"names":["fileURLToPath","resolvePackagePath","specifier","resolved","resolve","startsWith"],"mappings":"AAAA,4EAA4E;AAC5E,6IAA6I;AAC7I,SAASA,aAAa,QAAQ,WAAW;AAEzC,OAAO,SAASC,mBAAmBC,SAAiB;IAClD,MAAMC,WAAW,YAAYC,OAAO,CAACF;IACrC,OAAOC,SAASE,UAAU,CAAC,aAAaL,cAAcG,YAAYA;AACpE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/types.ts"],"sourcesContent":["// Shared shapes threaded through the collect -> lines -> markdown -> report\n// pipeline; kept in one place since every downstream stage uses at least one.\n\n// A positioned glyph run from the PDF's text layer: `s` may be more than one\n// character; `y` is flipped so ascending sorts top-down; `h` is font height rounded to 0.1pt.\nexport interface Glyph {\n s: string;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n// One page's worth of collected glyphs plus the geometry collect.ts needs\n// downstream (lines.ts's two-column detection, report.ts's hybrid-page flag).\nexport interface CollectedPage {\n page: number;\n glyphs: Glyph[];\n width: number;\n height: number;\n textChars: number;\n largeImage: boolean;\n}\n\n// collect.ts's return value: selected pages plus the char-weighted\n// font-height histogram, built ONLY from those pages (matters for a `--pages` re-extraction — see collect.ts).\nexport interface CollectResult {\n numPages: number;\n pages: CollectedPage[];\n heightChars: Map<number, number>;\n}\n\n// A visual line assembled from glyphs (lines.ts's `toLines`): `h` is the\n// char-weighted dominant height (not max); `col` is 0 (left/only) or 1 (right, de-braided page).\nexport interface Line {\n text: string;\n x: number;\n y: number;\n h: number;\n col: number;\n}\n\n// One page's lines, as src/extract.ts assembles them for buildMarkdown.\nexport interface PageLines {\n page: number;\n lines: Line[];\n}\n\nexport interface BuildMarkdownOptions {\n pageMarkers?: boolean;\n}\n\n// Running counters src/markdown.ts accumulates while building the output,\n// surfaced in the QA report (src/report.ts's buildReport).\nexport interface MarkdownStats {\n headings: number;\n listItems: number;\n paragraphs: number;\n joinedPairs: number;\n reflowed: number;\n callouts: number;\n closedHyphens: number;\n}\n\nexport interface MarkdownResult {\n md: string;\n stats: MarkdownStats;\n bodyH: number;\n headingSizes: number[];\n}\n\n/** One row of the per-page QA breakdown (\"### pN\" blocks) — used to decide\n * which pages are worth rendering and re-checking (README's \"Design contract\"). */\nexport interface PageStatsRow {\n page: number;\n chars: number;\n headings: number;\n junkHeadings: number;\n floats: number;\n paragraphs: number;\n danglingLong: number;\n danglingShort: number;\n /** count of `> [review: ...]` lines — blocks the geometry could not order\n * and labeled instead of guessing (README's \"Design contract\"). */\n reviewBlocks: number;\n /** present only on the text path's rows; omitted (not `false`) on the OCR\n * path, which has no per-page hybrid-image signal. */\n largeImages?: boolean;\n /** count of words below `report.ts`'s LOW_CONFIDENCE_THRESHOLD; omitted (not\n * 0) when the page had no confidence data at all, so \"measured 0\" and \"nothing to measure\" stay distinct. */\n lowConfidenceWords?: number;\n /** the suspect tokens behind `lowConfidenceWords`, worst-confidence first\n * and capped (`report.ts`'s LOW_CONFIDENCE_SAMPLE_CAP) so a chart-heavy page can't bloat the JSON. */\n lowConfidenceSample?: string[];\n}\n\n// buildReport's params (src/report.ts) — everything the text (default) path\n// hands over after running collect -> lines -> markdown.\nexport interface BuildReportInput {\n numPages: number;\n md: string;\n /** identical to `md` but always carries \"### pN\" markers, so pageStats is\n * measured independent of the caller's `--page-markers` choice; same string as `md` when markers were requested. */\n statsMd: string;\n stats: MarkdownStats;\n bodyH: number;\n headingSizes: number[];\n hybridPages?: number[];\n}\n\n/** One recognized word's page/text/confidence — `report.ts`'s low-confidence\n * detector input; a structural subset of OcrWordInput kept here so `types.ts` doesn't import the library-layer module that depends on it. */\nexport interface WordConfidenceInput {\n page: number;\n text: string;\n confidence?: number;\n}\n\nexport interface BuildOcrReportInput {\n md: string;\n fallback?: boolean;\n /** every recognized word, for `report.ts`'s low-confidence detector.\n * Defaults to [] (a pre-confidence --words-json replay), reporting the detector absent, never wrong. */\n words?: WordConfidenceInput[];\n}\n\n/** Per-document and per-page QA metrics returned by every extraction entry\n * point, discriminated by `path`; OCR-only and text-only fields are grouped below. */\nexport interface Report {\n /** manually-bumped integer (not the npm package version) — see\n * `report.ts`'s OUTPUT_VERSION for the bump rule; present on every Report so a frozen baseline's staleness is self-announcing. */\n outputVersion: number;\n path: 'text' | 'ocr';\n pages: number;\n chars: number;\n charsPerPage: number;\n sparse: boolean;\n headings: number;\n junkHeadings: number;\n paragraphs: number;\n callouts: number;\n danglingLong: number;\n danglingShort: number;\n /** total `> [review: ...]` blocks across all pages (sum of pageStats'\n * reviewBlocks); always 0 on the text path — only the OCR path emits review markers. */\n reviewBlocks: number;\n /** document-level sum of pageStats' `lowConfidenceWords` — see that\n * field for why 0 can mean \"measured 0\" or \"nothing to measure\". */\n lowConfidenceWords: number;\n pageStats: PageStatsRow[];\n\n // --- OCR-only ---\n floats?: number;\n ocrFallback?: boolean;\n\n // --- text-only ---\n bodyFontHeight?: number;\n headingSizes?: number[];\n listItems?: number;\n joinedPairs?: number;\n closedHyphens?: number;\n hybridPages?: number[];\n}\n\n// --- Analysis: the raw-mode IR (analyze() produces it; toMarkdown()/toText()\n// in render-analysis.ts render it — see toMarkdown's doc comment for the fail-fast validation contract) ---\n\n/** One recognized/collected word, page-relative; `box` is always present.\n * See `AnalysisPage.words` for the coordinate contract and per-path granularity difference. */\nexport interface AnalysisWord {\n text: string;\n box: { x: number; y: number; w: number; h: number };\n confidence?: number;\n}\n\n/** One structural block; `wordIndexes` links it to its page's `words` list (blocks -> words only).\n * `text` is bare content for `'heading'` (level separate), else the LITERAL markdown line (decoration included, round-trippable) — a pull-quote is `'paragraph'`, not a 5th type. */\nexport interface AnalysisBlock {\n type: 'heading' | 'paragraph' | 'float' | 'review';\n text: string;\n /** Heading level (integer 1-6); REQUIRED when `type` is `'heading'`,\n * FORBIDDEN otherwise — toMarkdown()/toText() validate this fail-fast (throws PdfToMdError/'ANALYSIS_INPUT'), never silently ignored. */\n level?: number;\n wordIndexes: number[];\n}\n\n/** One page's flat words plus its structural blocks. */\nexport interface AnalysisPage {\n page: number;\n /** Flat, page-relative word list; `AnalysisBlock.wordIndexes` indexes into it. `box` is always normalized [0,1], origin bottom-left, y up, regardless of path.\n * OCR-path is genuinely per-word; TEXT-path is per visual LINE (`box.w` always 0, `box.y` the line's baseline) — coarser but honest, not faked. */\n words: AnalysisWord[];\n blocks: AnalysisBlock[];\n}\n\n/** analyze()'s output: plain, JSON-serializable per-page words/blocks plus\n * the same QA `report` the other entry points return. */\nexport interface Analysis {\n /** manually-bumped integer — see `Report.outputVersion` / `report.ts`'s OUTPUT_VERSION. */\n outputVersion: number;\n /** the same QA report extractText/extractOcr/pdfToMarkdown return, always\n * measured off real markdown (OCR: the shared core's output; TEXT: buildMarkdown's reflowed output, not this coarser IR) — never stale relative to the IR. */\n report: Report;\n pages: AnalysisPage[];\n}\n"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAE9E,6EAA6E;AAC7E,8FAA8F;AA+L9F;uDACuD,GACvD,WAOC"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/types.ts"],"sourcesContent":["// Shared shapes threaded through the collect -> lines -> markdown -> report\n// pipeline; kept in one place since every downstream stage uses at least one.\n\n// A positioned glyph run from the PDF's text layer: `s` may be more than one\n// character; `y` is flipped so ascending sorts top-down; `h` is font height rounded to 0.1pt.\nexport interface Glyph {\n s: string;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n// One page's worth of collected glyphs plus the geometry collect.ts needs\n// downstream (lines.ts's two-column detection, report.ts's hybrid-page flag).\nexport interface CollectedPage {\n page: number;\n glyphs: Glyph[];\n width: number;\n height: number;\n textChars: number;\n largeImage: boolean;\n}\n\n// collect.ts's return value: selected pages plus the char-weighted\n// font-height histogram, built ONLY from those pages (matters for a `--pages` re-extraction — see collect.ts).\nexport interface CollectResult {\n numPages: number;\n pages: CollectedPage[];\n heightChars: Map<number, number>;\n}\n\n// A visual line assembled from glyphs (lines.ts's `toLines`): `h` is the\n// char-weighted dominant height (not max); `col` is 0 (left/only) or 1 (right, de-braided page).\nexport interface Line {\n text: string;\n x: number;\n y: number;\n h: number;\n col: number;\n}\n\n// One page's lines, as src/extract.ts assembles them for buildMarkdown.\nexport interface PageLines {\n page: number;\n lines: Line[];\n}\n\nexport interface BuildMarkdownOptions {\n pageMarkers?: boolean;\n}\n\n// Running counters src/markdown.ts accumulates while building the output,\n// surfaced in the QA report (src/report.ts's buildReport).\nexport interface MarkdownStats {\n headings: number;\n listItems: number;\n paragraphs: number;\n joinedPairs: number;\n reflowed: number;\n callouts: number;\n closedHyphens: number;\n}\n\nexport interface MarkdownResult {\n md: string;\n stats: MarkdownStats;\n bodyH: number;\n headingSizes: number[];\n}\n\n/** One row of the per-page QA breakdown (\"### pN\" blocks) — used to decide\n * which pages are worth rendering and re-checking (README's \"Design contract\"). */\nexport interface PageStatsRow {\n page: number;\n chars: number;\n headings: number;\n junkHeadings: number;\n floats: number;\n paragraphs: number;\n danglingLong: number;\n danglingShort: number;\n /** count of `> [review: ...]` lines — blocks the geometry could not order\n * and labeled instead of guessing (README's \"Design contract\"). */\n reviewBlocks: number;\n /** present only on the text path's rows; omitted (not `false`) on the OCR\n * path, which has no per-page hybrid-image signal. */\n largeImages?: boolean;\n /** count of words below `report.ts`'s LOW_CONFIDENCE_THRESHOLD; omitted (not\n * 0) when the page had no confidence data at all, so \"measured 0\" and \"nothing to measure\" stay distinct. */\n lowConfidenceWords?: number;\n /** the suspect tokens behind `lowConfidenceWords`, worst-confidence first\n * and capped (`report.ts`'s LOW_CONFIDENCE_SAMPLE_CAP) so a chart-heavy page can't bloat the JSON. */\n lowConfidenceSample?: string[];\n}\n\n// buildReport's params (src/report.ts) — everything the text (default) path\n// hands over after running collect -> lines -> markdown.\nexport interface BuildReportInput {\n numPages: number;\n md: string;\n /** identical to `md` but always carries \"### pN\" markers, so pageStats is\n * measured independent of the caller's `--page-markers` choice; same string as `md` when markers were requested. */\n statsMd: string;\n stats: MarkdownStats;\n bodyH: number;\n headingSizes: number[];\n hybridPages?: number[];\n}\n\n/** One recognized word's page/text/confidence — `report.ts`'s low-confidence\n * detector input; a structural subset of OcrWordInput kept here so `types.ts` doesn't import the library-layer module that depends on it. */\nexport interface WordConfidenceInput {\n page: number;\n text: string;\n confidence?: number;\n}\n\nexport interface BuildOcrReportInput {\n md: string;\n fallback?: boolean;\n /** every recognized word, for `report.ts`'s low-confidence detector.\n * Defaults to [] (a pre-confidence --words-json replay), reporting the detector absent, never wrong. */\n words?: WordConfidenceInput[];\n}\n\n/** Per-document and per-page QA metrics returned by every extraction entry\n * point, discriminated by `path`; OCR-only and text-only fields are grouped below. */\nexport interface Report {\n /** manually-bumped integer (not the npm package version) — see\n * `report.ts`'s OUTPUT_VERSION for the bump rule; present on every Report so a frozen baseline's staleness is self-announcing. */\n outputVersion: number;\n path: 'text' | 'ocr';\n pages: number;\n chars: number;\n charsPerPage: number;\n sparse: boolean;\n headings: number;\n junkHeadings: number;\n paragraphs: number;\n callouts: number;\n danglingLong: number;\n danglingShort: number;\n /** total `> [review: ...]` blocks across all pages (sum of pageStats'\n * reviewBlocks); always 0 on the text path — only the OCR path emits review markers. */\n reviewBlocks: number;\n /** document-level sum of pageStats' `lowConfidenceWords` — see that\n * field for why 0 can mean \"measured 0\" or \"nothing to measure\". */\n lowConfidenceWords: number;\n pageStats: PageStatsRow[];\n\n // --- OCR-only ---\n floats?: number;\n ocrFallback?: boolean;\n\n // --- text-only ---\n bodyFontHeight?: number;\n headingSizes?: number[];\n listItems?: number;\n joinedPairs?: number;\n closedHyphens?: number;\n hybridPages?: number[];\n}\n\n// --- Analysis: the raw-mode IR (analyze() produces it; toMarkdown()/toText()\n// in render-analysis.ts render it — see toMarkdown's doc comment for the fail-fast validation contract) ---\n\n/** One recognized/collected word, page-relative; `box` is always present.\n * See `AnalysisPage.words` for the coordinate contract and per-path granularity difference. */\nexport interface AnalysisWord {\n text: string;\n box: { x: number; y: number; w: number; h: number };\n confidence?: number;\n}\n\n/** One structural block; `wordIndexes` links it to its page's `words` list (blocks -> words only).\n * `text` is bare content for `'heading'` (level separate), else the LITERAL markdown line (decoration included, round-trippable) — a pull-quote is `'paragraph'`, not a 5th type. */\nexport interface AnalysisBlock {\n type: 'heading' | 'paragraph' | 'float' | 'review';\n text: string;\n /** Heading level (integer 1-6); REQUIRED when `type` is `'heading'`,\n * FORBIDDEN otherwise — toMarkdown()/toText() validate this fail-fast (throws PdfToMdError/'ANALYSIS_INPUT'), never silently ignored. */\n level?: number;\n wordIndexes: number[];\n}\n\n/** One page's flat words plus its structural blocks. */\nexport interface AnalysisPage {\n page: number;\n /** Flat, page-relative word list; `AnalysisBlock.wordIndexes` indexes into it. `box` is always normalized [0,1], origin bottom-left, y up, regardless of path.\n * OCR-path is genuinely per-word; TEXT-path is per visual LINE (`box.w` always 0, `box.y` the line's baseline) — coarser but honest, not faked. */\n words: AnalysisWord[];\n blocks: AnalysisBlock[];\n}\n\n/** analyze()'s output: plain, JSON-serializable per-page words/blocks plus\n * the same QA `report` the other entry points return. */\nexport interface Analysis {\n /** manually-bumped integer — see `Report.outputVersion` / `report.ts`'s OUTPUT_VERSION. */\n outputVersion: number;\n /** the same QA report extractText/extractOcr/pdfToMarkdown return, always\n * measured off real markdown (OCR: the shared core's output; TEXT: buildMarkdown's reflowed output, not this coarser IR) — never stale relative to the IR. */\n report: Report;\n pages: AnalysisPage[];\n}\n"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAE9E,6EAA6E;AAC7E,8FAA8F;AA+L9F;uDACuD,GACvD,WAOC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Projects/pdf-to-md/src/validate.ts"],"sourcesContent":["// validate.ts — input-shape validation shared by analyze.ts and extract.ts,\n// kept out of both to dodge their value-level import cycle (extract.ts imports analyze.ts's buildOcrAnalysisPages; both need this).\nimport { PdfToMdError } from './errors.ts';\nimport type { OcrWordInput } from './extract.ts';\n\n/** Validates the one option every entry point accepts before touching the\n * PDF. Type-only import from `extract.ts` keeps this cycle-free. */\nexport function validatePages(pages: unknown): void {\n if (pages === undefined) return;\n const isRecord = typeof pages === 'object' && pages !== null;\n const first = isRecord ? (pages as Record<string, unknown>).first : undefined;\n const last = isRecord ? (pages as Record<string, unknown>).last : undefined;\n const firstOk = typeof first === 'number' && Number.isFinite(first) && first >= 1;\n const lastOk = last === undefined || (typeof last === 'number' && Number.isFinite(last) && last >= (first as number));\n if (!isRecord || !firstOk || !lastOk) {\n throw new PdfToMdError('PAGE_RANGE', `pages option must be { first: number, last?: number } with first >= 1 and last >= first (got ${JSON.stringify(pages)})`);\n }\n}\n\n/** Validates analyze()'s non-string `input` branch (`{ words }`) before\n * `.words` is read, so a plain-JS mistake like `analyze(null)` throws PdfToMdError/WORDS_INPUT instead of a raw TypeError. */\nexport function validateWordsInput(input: unknown): OcrWordInput[] {\n const isRecord = typeof input === 'object' && input !== null;\n const words = isRecord ? (input as Record<string, unknown>).words : undefined;\n if (!Array.isArray(words)) {\n throw new PdfToMdError('WORDS_INPUT', `analyze() input must be a pdf path (string) or { words: OcrWordInput[] } (got ${isRecord ? JSON.stringify(input) : String(input)})`);\n }\n return words as OcrWordInput[];\n}\n\n/** Runtime shape guard for `buildOcrAnalysisPages`'s input: a plain-JS\n * caller bypasses the TS union, so this turns a raw TypeError into PdfToMdError before any property is read off it. */\nexport function validateOcrAnalysisInput(input: unknown): { pdfPath: string } | { words: OcrWordInput[] } {\n if (typeof input === 'string') {\n throw new PdfToMdError('PDF_OPEN', `extractOcr/analyze input must be { pdfPath: string } or { words: OcrWordInput[] }, not a bare path string (got ${JSON.stringify(input)}) — did you mean { pdfPath: ${JSON.stringify(input)} }?`);\n }\n const isRecord = typeof input === 'object' && input !== null;\n const rawPdfPath = isRecord ? (input as Record<string, unknown>).pdfPath : undefined;\n const rawWords = isRecord ? (input as Record<string, unknown>).words : undefined;\n if (!isRecord || (rawPdfPath === undefined && rawWords === undefined)) {\n throw new PdfToMdError('WORDS_INPUT', `extractOcr/analyze input must be { pdfPath: string } or { words: OcrWordInput[] } (got ${isRecord ? JSON.stringify(input) : String(input)})`);\n }\n if (rawWords !== undefined && !Array.isArray(rawWords)) {\n throw new PdfToMdError('WORDS_INPUT', `extractOcr/analyze { words } input must be an array (got ${JSON.stringify(rawWords)})`);\n }\n if (rawPdfPath !== undefined && typeof rawPdfPath !== 'string') {\n throw new PdfToMdError('PDF_OPEN', `extractOcr/analyze { pdfPath } input must be a string (got ${JSON.stringify(rawPdfPath)})`);\n }\n if (rawWords !== undefined) {\n for (const w of rawWords as unknown[]) {\n const rec = w as Record<string, unknown>;\n if (typeof rec.page !== 'number' || typeof rec.text !== 'string' || typeof rec.x !== 'number' || typeof rec.y !== 'number' || typeof rec.w !== 'number' || typeof rec.h !== 'number') {\n throw new PdfToMdError('WORDS_INPUT', `malformed word entry (need {page, text, x, y, w, h}): ${JSON.stringify(w)}`);\n }\n }\n return { words: rawWords as OcrWordInput[] };\n }\n return { pdfPath: rawPdfPath as string };\n}\n"],"names":["PdfToMdError","validatePages","pages","undefined","isRecord","first","last","firstOk","Number","isFinite","lastOk","JSON","stringify","validateWordsInput","input","words","Array","isArray","String","validateOcrAnalysisInput","rawPdfPath","pdfPath","rawWords","w","rec","page","text","x","y","h"],"mappings":"AAAA,4EAA4E;AAC5E,oIAAoI;AACpI,SAASA,YAAY,QAAQ,cAAc;AAG3C;kEACkE,GAClE,OAAO,SAASC,cAAcC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eAAejB,aAAamB,aAAanB,WAAY;QACrE,MAAM,IAAIH,aAAa,eAAe,CAAC,uFAAuF,EAAEI,WAAWO,KAAKC,SAAS,CAACE,SAASI,OAAOJ,OAAO,CAAC,CAAC;IACrL;IACA,IAAIQ,aAAanB,aAAa,CAACa,MAAMC,OAAO,CAACK,WAAW;QACtD,MAAM,IAAItB,aAAa,eAAe,CAAC,yDAAyD,EAAEW,KAAKC,SAAS,CAACU,UAAU,CAAC,CAAC;IAC/H;IACA,IAAIF,eAAejB,aAAa,OAAOiB,eAAe,UAAU;QAC9D,MAAM,IAAIpB,aAAa,YAAY,CAAC,2DAA2D,EAAEW,KAAKC,SAAS,CAACQ,YAAY,CAAC,CAAC;IAChI;IACA,IAAIE,aAAanB,WAAW;QAC1B,KAAK,MAAMoB,KAAKD,SAAuB;YACrC,MAAME,MAAMD;YACZ,IAAI,OAAOC,IAAIC,IAAI,KAAK,YAAY,OAAOD,IAAIE,IAAI,KAAK,YAAY,OAAOF,IAAIG,CAAC,KAAK,YAAY,OAAOH,IAAII,CAAC,KAAK,YAAY,OAAOJ,IAAID,CAAC,KAAK,YAAY,OAAOC,IAAIK,CAAC,KAAK,UAAU;gBACpL,MAAM,IAAI7B,aAAa,eAAe,CAAC,sDAAsD,EAAEW,KAAKC,SAAS,CAACW,IAAI;YACpH;QACF;QACA,OAAO;YAAER,OAAOO;QAA2B;IAC7C;IACA,OAAO;QAAED,SAASD;IAAqB;AACzC"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/formats/pdf-to-md/src/validate.ts"],"sourcesContent":["// validate.ts — input-shape validation shared by analyze.ts and extract.ts,\n// kept out of both to dodge their value-level import cycle (extract.ts imports analyze.ts's buildOcrAnalysisPages; both need this).\nimport { PdfToMdError } from './errors.ts';\nimport type { OcrWordInput } from './extract.ts';\n\n/** Validates the one option every entry point accepts before touching the\n * PDF. Type-only import from `extract.ts` keeps this cycle-free. */\nexport function validatePages(pages: unknown): void {\n if (pages === undefined) return;\n const isRecord = typeof pages === 'object' && pages !== null;\n const first = isRecord ? (pages as Record<string, unknown>).first : undefined;\n const last = isRecord ? (pages as Record<string, unknown>).last : undefined;\n const firstOk = typeof first === 'number' && Number.isFinite(first) && first >= 1;\n const lastOk = last === undefined || (typeof last === 'number' && Number.isFinite(last) && last >= (first as number));\n if (!isRecord || !firstOk || !lastOk) {\n throw new PdfToMdError('PAGE_RANGE', `pages option must be { first: number, last?: number } with first >= 1 and last >= first (got ${JSON.stringify(pages)})`);\n }\n}\n\n/** Validates analyze()'s non-string `input` branch (`{ words }`) before\n * `.words` is read, so a plain-JS mistake like `analyze(null)` throws PdfToMdError/WORDS_INPUT instead of a raw TypeError. */\nexport function validateWordsInput(input: unknown): OcrWordInput[] {\n const isRecord = typeof input === 'object' && input !== null;\n const words = isRecord ? (input as Record<string, unknown>).words : undefined;\n if (!Array.isArray(words)) {\n throw new PdfToMdError('WORDS_INPUT', `analyze() input must be a pdf path (string) or { words: OcrWordInput[] } (got ${isRecord ? JSON.stringify(input) : String(input)})`);\n }\n return words as OcrWordInput[];\n}\n\n/** Runtime shape guard for `buildOcrAnalysisPages`'s input: a plain-JS\n * caller bypasses the TS union, so this turns a raw TypeError into PdfToMdError before any property is read off it. */\nexport function validateOcrAnalysisInput(input: unknown): { pdfPath: string } | { words: OcrWordInput[] } {\n if (typeof input === 'string') {\n throw new PdfToMdError('PDF_OPEN', `extractOcr/analyze input must be { pdfPath: string } or { words: OcrWordInput[] }, not a bare path string (got ${JSON.stringify(input)}) — did you mean { pdfPath: ${JSON.stringify(input)} }?`);\n }\n const isRecord = typeof input === 'object' && input !== null;\n const rawPdfPath = isRecord ? (input as Record<string, unknown>).pdfPath : undefined;\n const rawWords = isRecord ? (input as Record<string, unknown>).words : undefined;\n if (!isRecord || (rawPdfPath === undefined && rawWords === undefined)) {\n throw new PdfToMdError('WORDS_INPUT', `extractOcr/analyze input must be { pdfPath: string } or { words: OcrWordInput[] } (got ${isRecord ? JSON.stringify(input) : String(input)})`);\n }\n if (rawWords !== undefined && !Array.isArray(rawWords)) {\n throw new PdfToMdError('WORDS_INPUT', `extractOcr/analyze { words } input must be an array (got ${JSON.stringify(rawWords)})`);\n }\n if (rawPdfPath !== undefined && typeof rawPdfPath !== 'string') {\n throw new PdfToMdError('PDF_OPEN', `extractOcr/analyze { pdfPath } input must be a string (got ${JSON.stringify(rawPdfPath)})`);\n }\n if (rawWords !== undefined) {\n for (const w of rawWords as unknown[]) {\n const rec = w as Record<string, unknown>;\n if (typeof rec.page !== 'number' || typeof rec.text !== 'string' || typeof rec.x !== 'number' || typeof rec.y !== 'number' || typeof rec.w !== 'number' || typeof rec.h !== 'number') {\n throw new PdfToMdError('WORDS_INPUT', `malformed word entry (need {page, text, x, y, w, h}): ${JSON.stringify(w)}`);\n }\n }\n return { words: rawWords as OcrWordInput[] };\n }\n return { pdfPath: rawPdfPath as string };\n}\n"],"names":["PdfToMdError","validatePages","pages","undefined","isRecord","first","last","firstOk","Number","isFinite","lastOk","JSON","stringify","validateWordsInput","input","words","Array","isArray","String","validateOcrAnalysisInput","rawPdfPath","pdfPath","rawWords","w","rec","page","text","x","y","h"],"mappings":"AAAA,4EAA4E;AAC5E,oIAAoI;AACpI,SAASA,YAAY,QAAQ,cAAc;AAG3C;kEACkE,GAClE,OAAO,SAASC,cAAcC,KAAc;IAC1C,IAAIA,UAAUC,WAAW;IACzB,MAAMC,WAAW,OAAOF,UAAU,YAAYA,UAAU;IACxD,MAAMG,QAAQD,WAAW,AAACF,MAAkCG,KAAK,GAAGF;IACpE,MAAMG,OAAOF,WAAW,AAACF,MAAkCI,IAAI,GAAGH;IAClE,MAAMI,UAAU,OAAOF,UAAU,YAAYG,OAAOC,QAAQ,CAACJ,UAAUA,SAAS;IAChF,MAAMK,SAASJ,SAASH,aAAc,OAAOG,SAAS,YAAYE,OAAOC,QAAQ,CAACH,SAASA,QAASD;IACpG,IAAI,CAACD,YAAY,CAACG,WAAW,CAACG,QAAQ;QACpC,MAAM,IAAIV,a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Q,YAAY,CAAC,CAAC;IAChI;IACA,IAAIE,aAAanB,WAAW;QAC1B,KAAK,MAAMoB,KAAKD,SAAuB;YACrC,MAAME,MAAMD;YACZ,IAAI,OAAOC,IAAIC,IAAI,KAAK,YAAY,OAAOD,IAAIE,IAAI,KAAK,YAAY,OAAOF,IAAIG,CAAC,KAAK,YAAY,OAAOH,IAAII,CAAC,KAAK,YAAY,OAAOJ,IAAID,CAAC,KAAK,YAAY,OAAOC,IAAIK,CAAC,KAAK,UAAU;gBACpL,MAAM,IAAI7B,aAAa,eAAe,CAAC,sDAAsD,EAAEW,KAAKC,SAAS,CAACW,IAAI;YACpH;QACF;QACA,OAAO;YAAER,OAAOO;QAA2B;IAC7C;IACA,OAAO;QAAED,SAASD;IAAqB;AACzC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effortlessmotion/pdf-to-md",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Extract PDFs to structured markdown: text layer via pdf.js, OCR fallback for image-only pages, pure npm and cross-platform",
5
5
  "keywords": [
6
6
  "pdf",
@@ -63,5 +63,14 @@
63
63
  },
64
64
  "publishConfig": {
65
65
  "access": "public"
66
+ },
67
+ "allowScripts": {
68
+ "tesseract.js": true,
69
+ "core-js-pure": true,
70
+ "@swc/core": true,
71
+ "node-filename-to-dist-paths": true,
72
+ "node-semvers": true,
73
+ "node-version-use": true,
74
+ "thread-sleep-compat": true
66
75
  }
67
76
  }