@blackbelt-technology/pi-dashboard-document-converter 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,6 @@
1
1
  ---
2
2
  name: doc-summarizer
3
- description: >-
4
- Summarize documents of any size by extracting them with the document-converter
5
- engine, chunking to fit context, and fanning chunks out to subagents that
6
- produce structured summaries, then synthesizing one unified summary. Handles
7
- PDF, DOCX, PPTX, XLSX, HTML, CSV, TXT, MD and more. Use when the user wants to:
8
- (1) summarize a single document, (2) summarize multiple documents in batch,
9
- (3) condense content from large files that exceed context limits, (4) get a
10
- quick overview of document contents. Triggers on: "summarize this document",
11
- "what's in this PDF", "give me a summary of these files", "extract key points
12
- from", "condense this document", "TL;DR of this file".
3
+ description: 'Summarize documents of any size: extract with the document-converter engine, chunk to fit context, fan out to subagents, then synthesize one unified summary. Handles PDF, DOCX, PPTX, XLSX, HTML, CSV, TXT, MD. Triggers: "summarize this document", "what''s in this PDF", "give me a summary of these files", "extract key points from", "condense this document", "TL;DR of this file".'
13
4
  ---
14
5
 
15
6
  # Document Summarizer
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: document-converter
3
- description: Convert documents bidirectionally via the pi-doc-engine facade. Ingest PDF/DOCX/PPTX/XLSX to provenance-stamped Markdown for kb (with selectable OCR). Produce templated DOCX/PDF from Markdown with diagrams (mmdc or styled nano-banana), TOC, cover page, and round-trip extract/edit/merge. Use on requests like "convert this PDF to markdown", "ingest these docs into kb", "make a DOCX from markdown with our template", "render this spec to PDF", "OCR this scanned Hungarian PDF", "edit this DOCX and merge back", "fill frontmatter", "auto-size tables".
3
+ description: 'Convert documents bidirectionally via the pi-doc-engine facade: ingest PDF/DOCX/PPTX/XLSX to provenance-stamped Markdown (with OCR), and produce templated DOCX/PDF from Markdown with diagrams, TOC and round-trip merge. Use on "convert this PDF to markdown", "ingest these docs into kb", "make a DOCX from markdown with our template", "render this spec to PDF", "OCR this scanned PDF".'
4
4
  ---
5
5
 
6
6
  # Document Converter
@@ -383,6 +383,33 @@ def cmd_list_templates(args: argparse.Namespace) -> int:
383
383
  return 0
384
384
 
385
385
 
386
+ def resolve_pdf_output(
387
+ inputs: list, output: str | None, output_dir: str | None
388
+ ) -> tuple:
389
+ """Split a trailing positional output path off `inputs`.
390
+
391
+ `inputs` is `nargs='+'`, so argparse cannot own an optional positional
392
+ output — it swallows both paths and leaves `output=None` (issue #507).
393
+ The documented single-file form `convert-pdf in.docx out.pdf` is recovered
394
+ here, under rules narrow enough that a genuine batch never loses an input:
395
+
396
+ * an explicit `--output` / `--output-dir` always wins;
397
+ * at least two positionals must remain;
398
+ * the last one must look like a PDF and must NOT already exist
399
+ (an existing `.pdf` is an input someone asked to convert).
400
+
401
+ Returns `(inputs, output)`.
402
+ """
403
+ if output is not None or output_dir is not None or len(inputs) < 2:
404
+ return list(inputs), output
405
+
406
+ tail = inputs[-1]
407
+ if not tail.lower().endswith('.pdf') or Path(tail).exists():
408
+ return list(inputs), output
409
+
410
+ return list(inputs[:-1]), tail
411
+
412
+
386
413
  def cmd_convert_pdf(args: argparse.Namespace) -> int:
387
414
  """Handle the convert-pdf command."""
388
415
  from .pdf_converter import (
@@ -395,7 +422,9 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
395
422
  # Collect input files
396
423
  input_files = []
397
424
 
398
- for pattern in args.inputs:
425
+ patterns, output = resolve_pdf_output(args.inputs, args.output, args.output_dir)
426
+
427
+ for pattern in patterns:
399
428
  # Check if it's a glob pattern
400
429
  if '*' in pattern or '?' in pattern:
401
430
  matches = glob.glob(pattern, recursive=True)
@@ -471,8 +500,8 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
471
500
  input_path = input_files[0]
472
501
 
473
502
  # Determine output path
474
- if args.output:
475
- output_path = Path(args.output)
503
+ if output:
504
+ output_path = Path(output)
476
505
  else:
477
506
  output_path = input_path.with_suffix('.pdf')
478
507
 
@@ -524,8 +553,9 @@ def cmd_convert_pdf(args: argparse.Namespace) -> int:
524
553
  return 1
525
554
 
526
555
 
527
- def main():
528
- """Main CLI entry point."""
556
+ def build_parser() -> argparse.ArgumentParser:
557
+ """Build the top-level parser. Split out of `main()` so tests can parse an
558
+ argv vector without executing a command (see tests/test_convert_pdf_output.py)."""
529
559
  parser = argparse.ArgumentParser(
530
560
  description='Document Converter - Convert between Markdown and DOCX formats',
531
561
  formatter_class=argparse.RawDescriptionHelpFormatter
@@ -694,8 +724,12 @@ Examples:
694
724
  """
695
725
  )
696
726
  pdf_parser.add_argument('inputs', nargs='+',
697
- help='Input file(s) or glob pattern (e.g., "*.docx")')
698
- pdf_parser.add_argument('output', nargs='?', default=None,
727
+ help='Input file(s), glob pattern (e.g., "*.docx"), '
728
+ 'optionally followed by the output PDF file')
729
+ # NOT a positional: `inputs` is nargs='+' and would greedily swallow it,
730
+ # leaving output=None (issue #507). The documented positional form is
731
+ # recovered by `resolve_pdf_output` instead.
732
+ pdf_parser.add_argument('-o', '--output', type=str, default=None,
699
733
  help='Output PDF file (for single file conversion)')
700
734
  pdf_parser.add_argument('--output-dir', type=str, default=None,
701
735
  help='Output directory for batch conversion')
@@ -712,6 +746,13 @@ Examples:
712
746
  help='Diagram output format (default: png)')
713
747
  add_common_args(pdf_parser)
714
748
 
749
+ return parser
750
+
751
+
752
+ def main():
753
+ """Main CLI entry point."""
754
+ parser = build_parser()
755
+
715
756
  # Parse arguments
716
757
  args = parser.parse_args()
717
758
 
@@ -357,6 +357,83 @@ def add_cover_page(
357
357
  doc.save(docx_path)
358
358
 
359
359
 
360
+ R_NS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
361
+ W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'
362
+ _SECTION_REF_TAGS = (f'{{{W_NS}}}headerReference', f'{{{W_NS}}}footerReference')
363
+
364
+
365
+ def _rel_targets(doc) -> dict:
366
+ """`{rId: target_ref}` for a document's own relationship part."""
367
+ return {rid: rel.target_ref for rid, rel in doc.part.rels.items()}
368
+
369
+
370
+ def remap_relationship_ids(elements: list, template_doc, output_doc) -> list:
371
+ """Rewrite template-local `r:id`s on copied elements to the OUTPUT's ids.
372
+
373
+ Elements copied out of a template carry that template's relationship ids.
374
+ The output package was produced independently (pandoc `--reference-doc`)
375
+ and numbered its own rels, so those ids are at best a different part and at
376
+ worst absent entirely — the dangling `rId15` that makes Word and
377
+ LibreOffice reject the file with no useful diagnostic (issue #506).
378
+
379
+ Ids are matched by TARGET, never by number: matching by number is what
380
+ silently repoints `headerReference type="first"` at *footer3*.
381
+
382
+ A header/footer reference the output package cannot satisfy is DROPPED — a
383
+ missing header renders fine, a dangling id does not. Any other unresolvable
384
+ reference is returned to the caller to fail on.
385
+
386
+ Returns the list of unresolvable non-section ids (empty when all resolved).
387
+ """
388
+
389
+ template_targets = _rel_targets(template_doc)
390
+ output_ids_by_target = {}
391
+ for rid, target in _rel_targets(output_doc).items():
392
+ output_ids_by_target.setdefault(target, rid)
393
+
394
+ unresolvable = []
395
+
396
+ for root in elements:
397
+ for el in list(root.iter()):
398
+ for key, old_id in list(el.attrib.items()):
399
+ if not key.startswith(f'{{{R_NS}}}'):
400
+ continue
401
+
402
+ target = template_targets.get(old_id)
403
+ new_id = output_ids_by_target.get(target) if target else None
404
+
405
+ if new_id is not None:
406
+ el.set(key, new_id)
407
+ continue
408
+
409
+ if el.tag in _SECTION_REF_TAGS:
410
+ parent = el.getparent()
411
+ if parent is not None:
412
+ parent.remove(el)
413
+ break # element is gone; stop reading its attributes
414
+
415
+ unresolvable.append(old_id)
416
+
417
+ return unresolvable
418
+
419
+
420
+ def find_dangling_relationship_ids(doc) -> list:
421
+ """Every `r:*` id in the body that no relationship backs.
422
+
423
+ A dangling id costs nothing at write time and everything at read time: the
424
+ package unzips, every part is well-formed, and Word/LibreOffice still
425
+ refuse it. Checking here turns silent corruption into a diagnosable error
426
+ (issue #506).
427
+ """
428
+ known = set(_rel_targets(doc))
429
+ dangling = []
430
+ for el in doc.element.body.iter():
431
+ for key, value in el.attrib.items():
432
+ if key.startswith(f'{{{R_NS}}}') and value not in known:
433
+ dangling.append(value)
434
+ return dangling
435
+
436
+
360
437
  def copy_template_cover_page(
361
438
  output_path: Path,
362
439
  template_path: Path
@@ -405,6 +482,18 @@ def copy_template_cover_page(
405
482
  if not cover_elements:
406
483
  return False
407
484
 
485
+ # The copied XML still speaks the TEMPLATE's relationship ids. Translate
486
+ # them before they reach the output package, and refuse to write a package
487
+ # whose references cannot be satisfied rather than emitting a file Word
488
+ # rejects as "source file could not be loaded". See issue #506.
489
+ unresolvable = remap_relationship_ids(cover_elements, template_doc, output_doc)
490
+ if unresolvable:
491
+ raise RuntimeError(
492
+ "Cover page references relationships absent from the output package: "
493
+ f"{', '.join(sorted(set(unresolvable)))}. "
494
+ f"Template: {template_path}"
495
+ )
496
+
408
497
  # Get the first element in output to insert before
409
498
  first_output = output_body[0] if len(output_body) > 0 else None
410
499
 
@@ -444,5 +533,13 @@ def copy_template_cover_page(
444
533
  else:
445
534
  output_body.append(page_break_para)
446
535
 
536
+ dangling = find_dangling_relationship_ids(output_doc)
537
+ if dangling:
538
+ raise RuntimeError(
539
+ "Refusing to write a DOCX with unresolvable relationship ids: "
540
+ f"{', '.join(sorted(set(dangling)))}. "
541
+ f"Output: {output_path}"
542
+ )
543
+
447
544
  output_doc.save(output_path)
448
545
  return True # Always return True if we copied something
@@ -256,7 +256,9 @@ def cmd_render_docx(req: dict) -> dict:
256
256
  def cmd_render_pdf(req: dict) -> dict:
257
257
  inp = Path(req["input"])
258
258
  out = req["output"]
259
- args = ["convert-pdf", str(inp), out]
259
+ # `--output`, never a positional: `convert-pdf`'s `inputs` is nargs='+' and
260
+ # swallows a trailing positional output. See issue #507.
261
+ args = ["convert-pdf", str(inp), "--output", out]
260
262
  if req.get("pageSize"):
261
263
  args += ["--page-size", req["pageSize"]]
262
264
  if req.get("template"):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-document-converter",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "TypeScript facade over a Dockerized Python document engine (pi-doc-engine). Bidirectional: ingest any format to provenance-stamped Markdown for kb, produce templated DOCX/PDF with diagrams. Engine quarantined in Docker; TS is the only call surface.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,13 +30,19 @@
30
30
  "test": "vitest run"
31
31
  },
32
32
  "dependencies": {
33
- "@blackbelt-technology/pi-dashboard-shared": "^0.7.0"
33
+ "@blackbelt-technology/pi-dashboard-shared": "^0.8.0"
34
34
  },
35
35
  "files": [
36
36
  "dist",
37
37
  "src",
38
38
  "engine",
39
- ".pi/skills/"
39
+ ".pi/skills/",
40
+ "!**/AGENTS.md",
41
+ "!**/*.AGENTS.md",
42
+ "!engine/tests",
43
+ "!**/__tests__",
44
+ "!**/*.test.ts",
45
+ "!**/*.test.tsx"
40
46
  ],
41
47
  "keywords": [
42
48
  "pi-package",
@@ -1,109 +0,0 @@
1
- """Engine-internal unit tests: styled-diagram md5 cache + mmdc fallback.
2
-
3
- These cover logic that lives below the TS↔engine JSON boundary (the TS suite
4
- mocks the boundary and cannot reach it). Pure stdlib + monkeypatch; no docling,
5
- no Docker. Run:
6
-
7
- python -m pytest packages/document-converter/engine/tests -q
8
- """
9
- import hashlib
10
- import sys
11
- from pathlib import Path
12
-
13
- import pytest
14
-
15
- ENGINE_DIR = Path(__file__).resolve().parent.parent
16
- sys.path.insert(0, str(ENGINE_DIR))
17
-
18
- import engine_cli # noqa: E402
19
-
20
- MERMAID_DOC = "intro\n\n```mermaid\ngraph TD; A-->B\n```\n\noutro\n"
21
-
22
-
23
- def _write_md(tmp_path: Path) -> Path:
24
- md = tmp_path / "doc.md"
25
- md.write_text(MERMAID_DOC, encoding="utf-8")
26
- return md
27
-
28
-
29
- def test_cache_hit_skips_generation(tmp_path, monkeypatch):
30
- md = _write_md(tmp_path)
31
- cache = tmp_path / ".mermaid-cache"
32
- cache.mkdir()
33
- # Pre-seed the cache with the exact md5 key.
34
- digest = hashlib.md5("graph TD; A-->B".encode()).hexdigest()
35
- (cache / f"{digest}.png").write_bytes(b"PNG")
36
-
37
- calls = {"nano": 0, "mmdc": 0}
38
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: calls.__setitem__("nano", calls["nano"] + 1) or True)
39
- monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
40
-
41
- out = engine_cli._render_styled_diagrams(md, "ros-3d", cache)
42
-
43
- assert calls == {"nano": 0, "mmdc": 0} # cache hit -> neither called
44
- text = out.read_text(encoding="utf-8")
45
- assert f"{digest}.png" in text
46
- assert "```mermaid" not in text
47
-
48
-
49
- def test_cache_miss_generates_via_nano_banana(tmp_path, monkeypatch):
50
- md = _write_md(tmp_path)
51
- cache = tmp_path / ".mermaid-cache"
52
- monkeypatch.setenv("GEMINI_API_KEY", "k")
53
-
54
- def fake_nano(source, style, png):
55
- png.write_bytes(b"PNG")
56
- return True
57
-
58
- calls = {"mmdc": 0}
59
- monkeypatch.setattr(engine_cli, "_nano_banana", fake_nano)
60
- monkeypatch.setattr(engine_cli, "_mmdc", lambda *a, **k: calls.__setitem__("mmdc", calls["mmdc"] + 1))
61
-
62
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
63
- assert calls["mmdc"] == 0 # nano-banana succeeded; no fallback
64
-
65
-
66
- def test_falls_back_to_mmdc_when_nano_fails(tmp_path, monkeypatch):
67
- md = _write_md(tmp_path)
68
- cache = tmp_path / ".mermaid-cache"
69
- monkeypatch.setenv("GEMINI_API_KEY", "k")
70
-
71
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: False)
72
-
73
- def fake_mmdc(source, png):
74
- png.write_bytes(b"PNG")
75
-
76
- fallback = {"n": 0}
77
- monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: (fallback.__setitem__("n", fallback["n"] + 1), fake_mmdc(s, p)))
78
-
79
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
80
- assert fallback["n"] == 1 # fell back to mmdc exactly once
81
-
82
-
83
- def test_missing_key_uses_mmdc(tmp_path, monkeypatch):
84
- md = _write_md(tmp_path)
85
- cache = tmp_path / ".mermaid-cache"
86
- monkeypatch.delenv("GEMINI_API_KEY", raising=False)
87
-
88
- nano = {"n": 0}
89
- monkeypatch.setattr(engine_cli, "_nano_banana", lambda *a, **k: nano.__setitem__("n", nano["n"] + 1) or True)
90
- monkeypatch.setattr(engine_cli, "_mmdc", lambda s, p: p.write_bytes(b"PNG"))
91
-
92
- engine_cli._render_styled_diagrams(md, "ros-3d", cache)
93
- assert nano["n"] == 0 # no key -> nano-banana never attempted, mmdc used
94
-
95
-
96
- def test_unknown_command_envelope():
97
- import io
98
- import json
99
-
100
- monkey_stdin = io.StringIO(json.dumps({"command": "nope"}))
101
- out = io.StringIO()
102
- old_in, old_out = sys.stdin, sys.stdout
103
- sys.stdin, sys.stdout = monkey_stdin, out
104
- try:
105
- rc = engine_cli.main()
106
- finally:
107
- sys.stdin, sys.stdout = old_in, old_out
108
- assert rc == 2
109
- assert json.loads(out.getvalue())["error"]["code"] == "UNKNOWN_COMMAND"
package/src/AGENTS.md DELETED
@@ -1,14 +0,0 @@
1
- # DOX — packages/document-converter/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `engine.ts` | Docker invocation layer. `runEngine(cfg, req)` spawns `docker run --rm -i <image>`, pipes JSON request stdin, reads JSON response stdout. Path-identical mounts (`-v dir:dir`). Maps exit codes + envelope to `DocConverterError`. Injectable `EngineRunner`. |
8
- | `errors.ts` | `DocConverterError` class + `DocConverterErrorCode` union. Single error type facade rejects with. Codes: DOCKER_UNAVAILABLE, ENGINE_NONZERO, BAD_RESPONSE, INPUT_NOT_FOUND, OCR_*, UNSUPPORTED_FORMAT, INGEST/PRODUCE/FILL/PROFILE_FAILED, INTERNAL. |
9
- | `index.ts` | Facade entry. `createDocumentConverter(config)` returns object with convertToMarkdown, renderDocx, renderPdf, extractForEdit, mergeBack, fillFrontmatter, profileTables. Only call surface. Re-exports errors, types, schema, ocr, routing, provenance. `renderPdf` input widened to accept `.pptx` (engine `convert_to_pdf` routes pptx via LibreOffice Impress export filter) — no facade validation, engine-only change. See change: render-pptx-preview. |
10
- | `ocr.ts` | Canonical language name→per-engine OCR code. `mapOcrCodes(langs, engine)`. EasyOCR `hu` vs Tesseract `hun`. rapidocr returns `[]`. Unsupported throws `OCR_LANG_UNSUPPORTED`. `SUPPORTED_LANGUAGES`. |
11
- | `provenance.ts` | Provenance frontmatter writer. `sha256File`, `buildProvenance`, `provenanceFrontmatter`, `stampProvenance`. Stamps ingested `.md` with origin metadata. Byte-stable by hash. |
12
- | `routing.ts` | Extension routing. `EXT_TO_DOCTYPE` map. `docTypeOf`, `isIngestable`, `ingestDocType`. Ingestable set = pdf/docx/pptx/xlsx. Throws `UNSUPPORTED_FORMAT`. |
13
- | `schema.ts` | Unified document-frontmatter schema. Shared bus contract across stages. Types: `DocumentFrontmatter`, `Provenance`, `NanoBananaConfig`, `TableProfiles`, `TemplateVars`, `DocType`, `DiagramFormat`. Key consts. Mirrors `schema.json`. |
14
- | `types.ts` | Facade option + result types. `OcrEngine`, `OcrMode`, `OcrOptions`, `ConvertToMarkdown*`, `RenderDocx/PdfOptions`, `Produce/Extract/MergeBack`, `FillFrontmatter/ProfileTablesOptions`. |
@@ -1,72 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { runEngine, type EngineRunner } from "../engine.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- const okRunner =
6
- (payload: object): EngineRunner =>
7
- async () => ({ stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 });
8
-
9
- describe("runEngine envelope handling", () => {
10
- it("returns the ok envelope minus the ok flag", async () => {
11
- const res = await runEngine(
12
- { image: "pi-doc-engine:test", runner: okRunner({ output: "/out.docx" }) },
13
- { command: "renderDocx", input: "/in.md", output: "/out.docx" },
14
- );
15
- expect(res).toEqual({ output: "/out.docx" });
16
- });
17
-
18
- it("maps an error envelope to a typed DocConverterError", async () => {
19
- const runner: EngineRunner = async () => ({
20
- stdout: JSON.stringify({
21
- ok: false,
22
- error: { code: "INGEST_FAILED", message: "boom", stderr: "trace" },
23
- }),
24
- stderr: "",
25
- exitCode: 1,
26
- });
27
- await expect(
28
- runEngine({ image: "x", runner }, { command: "convertToMarkdown", input: "/a.pdf" }),
29
- ).rejects.toMatchObject({ code: "INGEST_FAILED", message: "boom", stderr: "trace" });
30
- });
31
-
32
- it("rejects non-JSON stdout with BAD_RESPONSE on clean exit", async () => {
33
- const runner: EngineRunner = async () => ({ stdout: "not json", stderr: "", exitCode: 0 });
34
- await expect(
35
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
36
- ).rejects.toMatchObject({ code: "BAD_RESPONSE" });
37
- });
38
-
39
- it("rejects non-JSON stdout with ENGINE_NONZERO on bad exit", async () => {
40
- const runner: EngineRunner = async () => ({ stdout: "", stderr: "docker: not found", exitCode: 127 });
41
- await expect(
42
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
43
- ).rejects.toMatchObject({ code: "ENGINE_NONZERO", exitCode: 127 });
44
- });
45
-
46
- it("builds path-identical bind mounts for every referenced path", async () => {
47
- const runner = vi.fn<EngineRunner>(async () => ({
48
- stdout: JSON.stringify({ ok: true }),
49
- stderr: "",
50
- exitCode: 0,
51
- }));
52
- await runEngine(
53
- { image: "pi-doc-engine:test", runner, mounts: [] },
54
- { command: "renderDocx", input: "/work/in.md", output: "/work/out.docx" },
55
- );
56
- const argv = runner.mock.calls[0][0];
57
- expect(argv).toContain("-v");
58
- expect(argv).toContain("/work:/work");
59
- expect(argv).toContain("pi-doc-engine:test");
60
- // mount appears once even though two paths share /work
61
- expect(argv.filter((a) => a === "/work:/work")).toHaveLength(1);
62
- });
63
-
64
- it("surfaces DOCKER_UNAVAILABLE when the runner cannot spawn", async () => {
65
- const runner: EngineRunner = async () => {
66
- throw new DocConverterError({ code: "DOCKER_UNAVAILABLE", message: "no docker" });
67
- };
68
- await expect(
69
- runEngine({ image: "x", runner }, { command: "renderPdf", input: "/a.md", output: "/a.pdf" }),
70
- ).rejects.toMatchObject({ code: "DOCKER_UNAVAILABLE" });
71
- });
72
- });
@@ -1,120 +0,0 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { createDocumentConverter } from "../index.js";
6
- import type { EngineRunner } from "../engine.js";
7
-
8
- const tmps: string[] = [];
9
- async function workdir(): Promise<string> {
10
- const d = await mkdtemp(join(tmpdir(), "docconv-"));
11
- tmps.push(d);
12
- return d;
13
- }
14
- afterEach(async () => {
15
- await Promise.all(tmps.splice(0).map((d) => rm(d, { recursive: true, force: true })));
16
- });
17
-
18
- /** Fake runner that records the parsed request and returns a canned ok payload. */
19
- function recordingRunner(payload: object): { runner: EngineRunner; reqs: any[] } {
20
- const reqs: any[] = [];
21
- const runner: EngineRunner = async (_argv, stdin) => {
22
- reqs.push(JSON.parse(stdin));
23
- return { stdout: JSON.stringify({ ok: true, ...payload }), stderr: "", exitCode: 0 };
24
- };
25
- return { runner, reqs };
26
- }
27
-
28
- describe("facade: convertToMarkdown", () => {
29
- it("stamps provenance and writes markdown to the staging dir", async () => {
30
- const dir = await workdir();
31
- const staging = join(dir, "staging");
32
- const pdf = join(dir, "report.pdf");
33
- await writeFile(pdf, "fake-pdf-bytes");
34
-
35
- const { runner, reqs } = recordingRunner({ markdown: "# Report\n\ncontent" });
36
- const dc = createDocumentConverter({
37
- image: "pi-doc-engine:test",
38
- stagingDir: staging,
39
- engine: { runner },
40
- });
41
-
42
- const res = await dc.convertToMarkdown(pdf, { ocr: { lang: ["hungarian"], engine: "tesseract" } });
43
-
44
- // OCR canonical name was mapped to the per-engine code before the engine saw it.
45
- expect(reqs[0].command).toBe("convertToMarkdown");
46
- expect(reqs[0].ocr).toEqual({ mode: "auto", engine: "tesseract", codes: ["hun"] });
47
-
48
- const written = await readFile(res.output, "utf-8");
49
- expect(written).toContain("provenance:");
50
- expect(written).toContain("doc_type: pdf");
51
- expect(written).toContain(`source_path: ${pdf}`);
52
- expect(written).toContain("# Report");
53
- expect(res.provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
54
- expect(res.output).toBe(join(staging, "report.md"));
55
- });
56
-
57
- it("rejects unsupported input formats before calling the engine", async () => {
58
- const dir = await workdir();
59
- const { runner, reqs } = recordingRunner({ markdown: "x" });
60
- const dc = createDocumentConverter({
61
- image: "x",
62
- stagingDir: join(dir, "staging"),
63
- engine: { runner },
64
- });
65
- await expect(dc.convertToMarkdown(join(dir, "a.txt"))).rejects.toMatchObject({
66
- code: "UNSUPPORTED_FORMAT",
67
- });
68
- expect(reqs).toHaveLength(0);
69
- });
70
-
71
- it("rejects an unsupported OCR language before calling the engine", async () => {
72
- const dir = await workdir();
73
- const pdf = join(dir, "a.pdf");
74
- await writeFile(pdf, "x");
75
- const { runner, reqs } = recordingRunner({ markdown: "x" });
76
- const dc = createDocumentConverter({
77
- image: "x",
78
- stagingDir: join(dir, "staging"),
79
- engine: { runner },
80
- });
81
- await expect(
82
- dc.convertToMarkdown(pdf, { ocr: { lang: ["klingon"], engine: "easyocr" } }),
83
- ).rejects.toMatchObject({ code: "OCR_LANG_UNSUPPORTED" });
84
- expect(reqs).toHaveLength(0);
85
- });
86
- });
87
-
88
- describe("facade: produce", () => {
89
- it("forwards the nano_banana flag and template to the engine on renderDocx", async () => {
90
- const { runner, reqs } = recordingRunner({ output: "/out.docx" });
91
- const dc = createDocumentConverter({
92
- image: "x",
93
- stagingDir: "/staging",
94
- engine: { runner },
95
- });
96
- await dc.renderDocx("/in.md", {
97
- output: "/out.docx",
98
- template: "default",
99
- nanoBanana: { enabled: true, style: "ros-3d" },
100
- });
101
- expect(reqs[0]).toMatchObject({
102
- command: "renderDocx",
103
- input: "/in.md",
104
- output: "/out.docx",
105
- template: "default",
106
- nano_banana: { enabled: true, style: "ros-3d" },
107
- });
108
- });
109
-
110
- it("returns the extract result with a document_meta path", async () => {
111
- const { runner } = recordingRunner({ output: "/edit.md", meta: "/document_meta.xml" });
112
- const dc = createDocumentConverter({
113
- image: "x",
114
- stagingDir: "/staging",
115
- engine: { runner },
116
- });
117
- const res = await dc.extractForEdit("/in.docx", "/edit.md");
118
- expect(res).toEqual({ output: "/edit.md", meta: "/document_meta.xml" });
119
- });
120
- });
@@ -1,122 +0,0 @@
1
- /**
2
- * Integration test — one real conversion per direction against the built image.
3
- * VERIFIED green against `pi-doc-engine:0.1.0` (ingest PDF→md→kb; produce
4
- * md→DOCX with template + mmdc diagram).
5
- *
6
- * Opt-in only (heavy image: docling ML models + LibreOffice + pandoc). Skipped
7
- * unless `docker` is on PATH and these env vars are set:
8
- * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 built + loadable image tag
9
- * DOC_ENGINE_PDF=/abs/sample.pdf a digital PDF fixture (ingest case)
10
- * DOC_ENGINE_TEMPLATES=/abs/templates dir with <template>/template.docx (produce case)
11
- * DOC_ENGINE_PPTX=/abs/deck.pptx a real .pptx deck (pptx→PDF case)
12
- * Never runs in the default `npm test`.
13
- *
14
- * DOC_ENGINE_IMAGE=pi-doc-engine:0.1.0 DOC_ENGINE_PDF=… DOC_ENGINE_TEMPLATES=… \
15
- * npx vitest run integration
16
- */
17
- import { execFileSync } from "node:child_process";
18
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
19
- import { tmpdir } from "node:os";
20
- import { join } from "node:path";
21
- import { afterAll, beforeAll, describe, expect, it } from "vitest";
22
- import { createDocumentConverter } from "../index.js";
23
-
24
- const IMAGE = process.env.DOC_ENGINE_IMAGE;
25
-
26
- function dockerOk(): boolean {
27
- if (!IMAGE) return false;
28
- try {
29
- execFileSync("docker", ["image", "inspect", IMAGE], { stdio: "ignore" });
30
- return true;
31
- } catch {
32
- return false;
33
- }
34
- }
35
-
36
- const ENABLED = dockerOk();
37
- let work: string;
38
-
39
- beforeAll(async () => {
40
- if (!ENABLED) return;
41
- work = await mkdtemp(join(tmpdir(), "docconv-it-"));
42
- });
43
- afterAll(async () => {
44
- if (work) await rm(work, { recursive: true, force: true });
45
- });
46
-
47
- describe.skipIf(!ENABLED)("pi-doc-engine integration", () => {
48
- it("ingest: PDF -> Markdown with provenance, indexable by kb", async () => {
49
- const dc = createDocumentConverter({ image: IMAGE!, stagingDir: join(work, "staging") });
50
- // A trivial single-page PDF fixture must exist; integration fixtures are
51
- // provided alongside the built image. Point at it via DOC_ENGINE_PDF.
52
- const pdf = process.env.DOC_ENGINE_PDF;
53
- expect(pdf, "set DOC_ENGINE_PDF to a sample PDF").toBeTruthy();
54
-
55
- const { output, provenance } = await dc.convertToMarkdown(pdf!);
56
- const md = await readFile(output, "utf-8");
57
- expect(md).toContain("provenance:");
58
- expect(provenance.doc_type).toBe("pdf");
59
- expect(provenance.sha256).toMatch(/^[0-9a-f]{64}$/);
60
- }, 120_000);
61
-
62
- it("produce: Markdown -> DOCX with template + diagram", async () => {
63
- // Templates are runtime-mounted, not baked into the image (design Q4). Point
64
- // DOC_ENGINE_TEMPLATES at a dir containing `<template>/template.docx`.
65
- const templatesDir = process.env.DOC_ENGINE_TEMPLATES;
66
- expect(templatesDir, "set DOC_ENGINE_TEMPLATES to a templates dir").toBeTruthy();
67
-
68
- const dc = createDocumentConverter({
69
- image: IMAGE!,
70
- stagingDir: join(work, "staging"),
71
- mounts: [templatesDir!],
72
- });
73
- const md = join(work, "spec.md");
74
- await writeFile(
75
- md,
76
- [
77
- "---",
78
- "template: default",
79
- "---",
80
- "",
81
- "# Spec",
82
- "",
83
- "Hello world.",
84
- "",
85
- "```mermaid",
86
- "graph TD; A-->B",
87
- "```",
88
- "",
89
- ].join("\n"),
90
- "utf-8",
91
- );
92
- const out = join(work, "spec.docx");
93
- const res = await dc.renderDocx(md, {
94
- output: out,
95
- template: "default",
96
- templatesDir: templatesDir!,
97
- });
98
- expect(res.output).toBe(out);
99
- const bytes = await readFile(out);
100
- expect(bytes.byteLength).toBeGreaterThan(1000); // non-trivial DOCX
101
- }, 180_000);
102
-
103
- it("produce: PPTX -> PDF via renderPdf (fidelity path; change: render-pptx-preview)", async () => {
104
- // Verifies the engine input-type widening: renderPdf accepts .pptx and the
105
- // LibreOffice Impress export filter produces a valid PDF. Point DOC_ENGINE_PPTX
106
- // at a real deck.
107
- const pptx = process.env.DOC_ENGINE_PPTX;
108
- expect(pptx, "set DOC_ENGINE_PPTX to a sample .pptx deck").toBeTruthy();
109
-
110
- const dc = createDocumentConverter({
111
- image: IMAGE!,
112
- stagingDir: join(work, "staging"),
113
- mounts: [join(pptx!, "..")],
114
- });
115
- const out = join(work, "deck.pdf");
116
- const res = await dc.renderPdf(pptx!, { output: out });
117
- expect(res.output).toBe(out);
118
- const bytes = await readFile(out);
119
- expect(bytes.subarray(0, 5).toString()).toBe("%PDF-"); // valid PDF header
120
- expect(bytes.byteLength).toBeGreaterThan(1000);
121
- }, 180_000);
122
- });
@@ -1,34 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { mapOcrCodes, SUPPORTED_LANGUAGES } from "../ocr.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- describe("OCR canonical-name -> per-engine-code mapping", () => {
6
- it("maps the same language to different codes per engine", () => {
7
- expect(mapOcrCodes(["hungarian"], "easyocr")).toEqual(["hu"]);
8
- expect(mapOcrCodes(["hungarian"], "tesseract")).toEqual(["hun"]);
9
- });
10
-
11
- it("is case- and whitespace-insensitive", () => {
12
- expect(mapOcrCodes([" English ", "GERMAN"], "tesseract")).toEqual(["eng", "deu"]);
13
- });
14
-
15
- it("rapidocr ignores language codes", () => {
16
- expect(mapOcrCodes(["hungarian"], "rapidocr")).toEqual([]);
17
- });
18
-
19
- it("throws OCR_LANG_UNSUPPORTED for an unknown language", () => {
20
- try {
21
- mapOcrCodes(["klingon"], "easyocr");
22
- throw new Error("should have thrown");
23
- } catch (e) {
24
- expect(e).toBeInstanceOf(DocConverterError);
25
- expect((e as DocConverterError).code).toBe("OCR_LANG_UNSUPPORTED");
26
- }
27
- });
28
-
29
- it("throws when a known language is unsupported by the chosen engine path", () => {
30
- // ocrmac has no italian entry mapping? It does; use a language absent for ocrmac.
31
- expect(() => mapOcrCodes(["hungarian"], "easyocr")).not.toThrow();
32
- expect(SUPPORTED_LANGUAGES).toContain("hungarian");
33
- });
34
- });
@@ -1,89 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- buildProvenance,
4
- provenanceFrontmatter,
5
- stampProvenance,
6
- } from "../provenance.js";
7
-
8
- const FIXED = "2026-06-24T00:00:00.000Z";
9
-
10
- describe("provenance frontmatter", () => {
11
- it("builds a deterministic record with a fixed timestamp", () => {
12
- const prov = buildProvenance({
13
- sourcePath: "/docs/a.pdf",
14
- sha256: "abc123",
15
- docType: "pdf",
16
- convertedAt: FIXED,
17
- });
18
- expect(prov).toEqual({
19
- source_path: "/docs/a.pdf",
20
- sha256: "abc123",
21
- doc_type: "pdf",
22
- converted_at: FIXED,
23
- });
24
- });
25
-
26
- it("includes page/slide only when provided", () => {
27
- const prov = buildProvenance({
28
- sourcePath: "/a.pptx",
29
- sha256: "x",
30
- docType: "pptx",
31
- convertedAt: FIXED,
32
- slide: 3,
33
- });
34
- expect(prov.slide).toBe(3);
35
- expect(prov.page).toBeUndefined();
36
- });
37
-
38
- it("prepends a frontmatter block to a bare body", () => {
39
- const prov = buildProvenance({
40
- sourcePath: "/a.pdf",
41
- sha256: "deadbeef",
42
- docType: "pdf",
43
- convertedAt: FIXED,
44
- });
45
- const out = stampProvenance("# Title\n\nbody", prov);
46
- expect(out.startsWith("---\nprovenance:\n")).toBe(true);
47
- expect(out).toContain("sha256: deadbeef");
48
- expect(out.trimEnd().endsWith("body")).toBe(true);
49
- });
50
-
51
- it("injects into existing frontmatter without clobbering keys", () => {
52
- const prov = buildProvenance({
53
- sourcePath: "/a.pdf",
54
- sha256: "h",
55
- docType: "pdf",
56
- convertedAt: FIXED,
57
- });
58
- const existing = "---\ntitle: Hello\n---\n\nbody\n";
59
- const out = stampProvenance(existing, prov);
60
- expect(out).toContain("provenance:");
61
- expect(out).toContain("title: Hello");
62
- // Single opening fence only.
63
- expect(out.match(/^---\n/)).toBeTruthy();
64
- expect(out.indexOf("---", 4)).toBeGreaterThan(0);
65
- });
66
-
67
- it("re-stamping the same hash is byte-identical (idempotent)", () => {
68
- const prov = buildProvenance({
69
- sourcePath: "/a.pdf",
70
- sha256: "same",
71
- docType: "pdf",
72
- convertedAt: FIXED,
73
- });
74
- const a = stampProvenance("body", prov);
75
- const b = stampProvenance("body", prov);
76
- expect(a).toBe(b);
77
- });
78
-
79
- it("quotes scalars that could be misparsed", () => {
80
- const prov = buildProvenance({
81
- sourcePath: "/path with spaces/a.pdf",
82
- sha256: "h",
83
- docType: "pdf",
84
- convertedAt: FIXED,
85
- });
86
- const fm = provenanceFrontmatter(prov);
87
- expect(fm).toContain('"/path with spaces/a.pdf"');
88
- });
89
- });
@@ -1,40 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { docTypeOf, ingestDocType, isIngestable } from "../routing.js";
3
- import { DocConverterError } from "../errors.js";
4
-
5
- describe("routing", () => {
6
- it("maps known extensions to doc types", () => {
7
- expect(docTypeOf("/a/b.pdf")).toBe("pdf");
8
- expect(docTypeOf("/a/b.DOCX")).toBe("docx");
9
- expect(docTypeOf("report.pptx")).toBe("pptx");
10
- expect(docTypeOf("sheet.xlsx")).toBe("xlsx");
11
- expect(docTypeOf("notes.md")).toBe("md");
12
- expect(docTypeOf("notes.markdown")).toBe("md");
13
- });
14
-
15
- it("throws UNSUPPORTED_FORMAT for unknown extensions", () => {
16
- expect(() => docTypeOf("/a/b.txt")).toThrowError(DocConverterError);
17
- try {
18
- docTypeOf("/a/b");
19
- } catch (e) {
20
- expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
21
- }
22
- });
23
-
24
- it("classifies ingestable formats", () => {
25
- expect(isIngestable("a.pdf")).toBe(true);
26
- expect(isIngestable("a.docx")).toBe(true);
27
- expect(isIngestable("a.md")).toBe(false); // md is not ingested, it IS the target
28
- expect(isIngestable("a.txt")).toBe(false);
29
- });
30
-
31
- it("ingestDocType rejects markdown", () => {
32
- expect(ingestDocType("a.pdf")).toBe("pdf");
33
- try {
34
- ingestDocType("a.md");
35
- throw new Error("should have thrown");
36
- } catch (e) {
37
- expect((e as DocConverterError).code).toBe("UNSUPPORTED_FORMAT");
38
- }
39
- });
40
- });