bindery-cli 1.1.1__tar.gz → 1.2.0__tar.gz

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 (56) hide show
  1. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/AGENTS.md +4 -4
  2. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/PKG-INFO +2 -1
  3. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/README.md +1 -0
  4. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/patchnotes.md +50 -0
  5. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/pyproject.toml +1 -1
  6. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/roadmap.md +1 -0
  7. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/spec.md +20 -3
  8. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/__init__.py +1 -1
  9. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/cli.py +18 -0
  10. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/epub.py +97 -1
  11. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_epub.py +141 -0
  12. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_flags_real_core.py +17 -0
  13. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_flags_wiring.py +1 -0
  14. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/uv.lock +1 -1
  15. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/.github/FUNDING.yml +0 -0
  16. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/.github/workflows/ci.yml +0 -0
  17. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/.github/workflows/publish.yml +0 -0
  18. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/.gitignore +0 -0
  19. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/LICENSE +0 -0
  20. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/OBSERVE-RESEARCH.md +0 -0
  21. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/docs/screenshots/library-sweep.png +0 -0
  22. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/logo.svg +0 -0
  23. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/plugin/__init__.py +0 -0
  24. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/project.done +0 -0
  25. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/run_tests.sh +0 -0
  26. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/scripts/FastSweep.java +0 -0
  27. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/scripts/build_plugin.py +0 -0
  28. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/scripts/fast_sweep.py +0 -0
  29. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/__main__.py +0 -0
  30. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/audit.py +0 -0
  31. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/library.py +0 -0
  32. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/observe.py +0 -0
  33. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/pagination.py +0 -0
  34. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/reserialize.py +0 -0
  35. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/transforms.py +0 -0
  36. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/validate.py +0 -0
  37. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/src/bindery/watermark.py +0 -0
  38. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_audit.py +0 -0
  39. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_cli.py +0 -0
  40. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_comment_hyphens.py +0 -0
  41. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_contamination.py +0 -0
  42. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_cover_tocdrift.py +0 -0
  43. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_help.py +0 -0
  44. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_library.py +0 -0
  45. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_matcher_hardening.py +0 -0
  46. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_observe.py +0 -0
  47. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_pagination.py +0 -0
  48. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_plugin.py +0 -0
  49. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_reserialize.py +0 -0
  50. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_space_renames.py +0 -0
  51. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_spine_guard.py +0 -0
  52. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_transforms.py +0 -0
  53. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_validate.py +0 -0
  54. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_version.py +0 -0
  55. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_watermark.py +0 -0
  56. {bindery_cli-1.1.1 → bindery_cli-1.2.0}/tests/test_xml_hardening.py +0 -0
@@ -35,7 +35,7 @@ Born from the 2026 library audit (see the user memory `calibre-library-epubcheck
35
35
  `xmlns`, bare `&`, named entities, void self-closing), the NCX pipeline, and the
36
36
  mimetype fix (added/normalized/first-stored, epub.py's archive rewrite); every core
37
37
  fix must render identically to the author's intent: never add, remove, or reorder
38
- visible content. The canonical opt-in inventory lives in spec.md: thirty-four structural
38
+ visible content. The canonical opt-in inventory lives in spec.md: thirty-five structural
39
39
  repairs, four lossy strips, five safe opt-ins, plus `--reserialize` (the
40
40
  seven v0.62.x/v0.63.0 flags -- `--fix-package-version`, `--fix-doctype`,
41
41
  `--prune-invalid-guide-refs`, `--fix-item-properties`,
@@ -53,7 +53,7 @@ Born from the 2026 library audit (see the user memory `calibre-library-epubcheck
53
53
  `--fix-unbound-prefix`, `--fix-package-version`, `--fix-doctype`,
54
54
  `--prune-invalid-guide-refs`, `--fix-item-properties`,
55
55
  `--strip-presentational-attrs`, `--encode-ref-brackets`,
56
- `--encode-ref-delims`,
56
+ `--encode-ref-delims`, `--strip-dead-font-faces`,
57
57
  `--prune-dead-spine`;
58
58
  transforms.py, threaded through epub.py). The v0.47.0 five (the 2026-10-06
59
59
  issue batch): `--fix-svg-dup-ids` renames duplicate glyph ids inside
@@ -286,14 +286,14 @@ Born from the 2026 library audit (see the user memory `calibre-library-epubcheck
286
286
  - `src/bindery/epub.py`: archive rewrite, NCX uid sync, RepairReport, mismatch detection, and the opt-in structural-repair plumbing (including the CSS precondition scan). Since v0.59.0 (issue #23) `strip_ncx_dangling_targets` is the NCX dangling-target prune (`--prune-dangling-ncx-targets`): a balanced stack scanner over navPoint/navTarget/pageTarget tokens (quote-aware possessive regex, `_NcxTargetNode` tree, iterative post-order survival pass; header_end delimits the node's own navLabel+`<content>` so a splice removes the tags AND the dead header while the children re-home; an unbalanced walk aborts the part unchanged) and the NCX branch re-runs `fix_ncx_playorder` when it fires, alongside the anchor pass's own re-run. Since v0.58.0 (issue #18) the copy loop hands every `zout.writestr` a PRIVATE ZipInfo (`copy.copy(item)`, a fresh one on a rename) and the media-type `peek` catches `zipfile.BadZipFile` too. HAZARD: `writestr` STAMPS the ZipInfo it is handed with the DESTINATION offsets (header_offset, sizes land on it for the central directory); sharing the source's info repointed zin's own name lookups into the output file mid-loop, and one drifted probe killed whole books as "unreadable" -- 56 books "Bad magic number for file header" plus the "possible zip bomb" Development as Freedom (the drifted offset landed on a valid header whose data overlaps its neighbor), all one root cause. Since v0.58.0 (issue #21) `strip_broken_guide_fragments` gives the OPF guide the NCX fragment-strip's document-precision fallback, and the NCX branch re-runs `fix_ncx_playorder` after the anchor pass fires (the pre-strip sequence goes stale when fragments collapse onto their document). Since v0.58.0 (issue #20) `_resolve_href` decodes the five predefined XML entities plus numeric
287
287
  character references before the fragment split (attribute text arrives
288
288
  escaped; entries are raw; decoding first keeps the `#` inside `&#38;`
289
- from cutting the target), `_ITEM_TAG_RE`/`_SPINE_ITEM_RE`/`_GUIDE_REF_RE`/prune_dangling_edges' matcher accept an optional ns prefix (`<opf:item>`), and the renamed-reference spellings percent-encode `[`/`]` (`_encode_ref_path`). Since v0.52.0 (issue #10): `spine_dangles(src)` walks itemref -> manifest item -> archive entry through `_resolve_href`+`_norm_path` (None on an unreadable package: the veto needs evidence, never fires on a probe failure), and `prune_missing_manifest_items` derives its spine protection from the text it prunes (no snapshot parameter: fix_manifest_ids renames ids ahead of it, and the existence set it checks against must be the layout its hrefs are written in — `present_src` when space renames are active, matching the content-doc prune). Since v0.46.0 the opt-in selection is the `RepairFlags` dataclass (one field per flag, all off by default; the all-off instance IS the default pass): `repair_epub(src, dst, flags)` and `process_book(..., flags)` take one object instead of a ~25-kwarg signature, the EPUB2-targeted fixes' version gate swaps in a `dataclasses.replace` copy (never mutating the caller's instance), and the plugin's bare `repair_epub(src, dst)` call constructs exactly the all-off default pass. Since v0.55.0 (issue #16) the RSC-008 half lives beside the prune: `collect_undeclared_resources` (one whole-book census: content img/link, inline `<style>` url(), stylesheet url(), OPF guide refs) + `declare_missing_manifest_items` (sorted `bindery-dN` items before `</manifest>`, `_DECLARE_MEDIA_TYPES` blessed extensions only), gated and threaded through `RepairFlags.declare_missing`. Since v0.38.0/v0.39.0 (Phase 16): `generate_container` + the `--fix-container` gateway (insert after mimetype when missing, replace in-loop when stale; constant-epoch timestamp keeps bytes deterministic), `prune_dangling_edges` (prune_missing_manifest_items returns the pruned ids and the edges that pointed at them (spine@toc, media-overlay, fallback, EPUB2 cover meta) are rewritten so pruning cannot manufacture the regression the gate rejects), and `fix_manifest_media_types` (extension map + magic-byte confirmation via a `peek` callable over the open source zip; jpg/png/gif only), and `fix_cover_meta` (the ruling's deterministic half: dangling EPUB2 cover meta re-pointed from the guide's cover reference when exactly one manifest item carries that file, removed otherwise; accepted under no_worse like the lossy strips because cover wiring is invisible to epubcheck). Since v0.62.0/0.62.1 (the 2026-11-03 observatory batch): the playOrder contract is base-free (epubcheck polices sharing/distinctness/gaps, never the base; verified at singleton/pair/offset scales), `fix_pagelist_class` inserts the collision-checked `bindery-pagelist` id beside the class (class-only insertion made epubcheck demand the id it enabled), `fix_missing_title` fills the self-closed `<title/>` head-scoped only (an empty SVG `<title>` is visible text the gate cannot measure), and four new flags live beside them: `fix_package_version` (literal 1.0 -> 2.0 only; `_PACKAGE_VERSION_ONE_RE`), `fix_doctype` (present-but-forbidden declarations only; `_scan_doctype_span` walks bracket depth and refuses unterminated spans), `prune_invalid_guide_refs` (declared-but-not-a-content-doc targets, both element shapes), and `fix_manifest_item_properties` + `collect_item_properties` (EPUB3-only census: scripted from `<script>`/`<form>`, svg from `<svg>`, remote-resources from absolute-scheme src/link/CSS url(); the insert branch appends before a self-closed item's solidus, never after it -- the v0.62.1 review caught the malformed `/ properties` shape). Since v0.62.1 `fix_double_colon_tags` escapes `::`-named pseudo-tags (a QName carries at most one colon, so such a construct is never markup; nested templates escape inner-first until stable; the tail is bounded at 120 chars so an escaped-bracket construct cannot swallow prose). Since v1.1.1 (the audit batch, issues #28-#33): `_norm_fragment` decodes a fragment the way `_resolve_href` decodes a path (XML entities, then RFC 3986 percent) before every anchor-cleaner existence check, so `#caf%C3%A9` matches `id="café"` instead of reading as broken (#29, the content/NCX/guide halves alike); `_ITEM_ID_RE`/`_XML_ID_RE` carry the `(?<![\w:.-])id=` lookbehind (`data-id`/`xml:id` are not ids: the manifest half renamed a `data-id` while the item's real id stayed; #30), while `ids_by_doc` collects through the dedicated `_ANCHOR_ID_RE` (`(?:xml:)?id`) because xml:id is a real XML id the oracle resolves fragments against -- dropping it from the anchor set would strip links the oracle never flagged; `downgrade_epub3_tags` runs through `outside_protected_map` and `_append_class`'s class matcher is whitespace-anchored (the unshielded `re.sub` downgraded commented-out markup and the bare `class=` merged into `data-class`; #32); and `declare_missing_manifest_items` locates the manifest close tag through `_MANIFEST_CLOSE_RE` (`</(?:[\w.-]+:)?manifest\s*>`: the literal `"</manifest>"` check/replace silently no-opped on prefixed and whitespace spellings; #33).
289
+ from cutting the target), `_ITEM_TAG_RE`/`_SPINE_ITEM_RE`/`_GUIDE_REF_RE`/prune_dangling_edges' matcher accept an optional ns prefix (`<opf:item>`), and the renamed-reference spellings percent-encode `[`/`]` (`_encode_ref_path`). Since v0.52.0 (issue #10): `spine_dangles(src)` walks itemref -> manifest item -> archive entry through `_resolve_href`+`_norm_path` (None on an unreadable package: the veto needs evidence, never fires on a probe failure), and `prune_missing_manifest_items` derives its spine protection from the text it prunes (no snapshot parameter: fix_manifest_ids renames ids ahead of it, and the existence set it checks against must be the layout its hrefs are written in — `present_src` when space renames are active, matching the content-doc prune). Since v0.46.0 the opt-in selection is the `RepairFlags` dataclass (one field per flag, all off by default; the all-off instance IS the default pass): `repair_epub(src, dst, flags)` and `process_book(..., flags)` take one object instead of a ~25-kwarg signature, the EPUB2-targeted fixes' version gate swaps in a `dataclasses.replace` copy (never mutating the caller's instance), and the plugin's bare `repair_epub(src, dst)` call constructs exactly the all-off default pass. Since v0.55.0 (issue #16) the RSC-008 half lives beside the prune: `collect_undeclared_resources` (one whole-book census: content img/link, inline `<style>` url(), stylesheet url(), OPF guide refs) + `declare_missing_manifest_items` (sorted `bindery-dN` items before `</manifest>`, `_DECLARE_MEDIA_TYPES` blessed extensions only), gated and threaded through `RepairFlags.declare_missing`. Since v0.38.0/v0.39.0 (Phase 16): `generate_container` + the `--fix-container` gateway (insert after mimetype when missing, replace in-loop when stale; constant-epoch timestamp keeps bytes deterministic), `prune_dangling_edges` (prune_missing_manifest_items returns the pruned ids and the edges that pointed at them (spine@toc, media-overlay, fallback, EPUB2 cover meta) are rewritten so pruning cannot manufacture the regression the gate rejects), and `fix_manifest_media_types` (extension map + magic-byte confirmation via a `peek` callable over the open source zip; jpg/png/gif only), and `fix_cover_meta` (the ruling's deterministic half: dangling EPUB2 cover meta re-pointed from the guide's cover reference when exactly one manifest item carries that file, removed otherwise; accepted under no_worse like the lossy strips because cover wiring is invisible to epubcheck). Since v0.62.0/0.62.1 (the 2026-11-03 observatory batch): the playOrder contract is base-free (epubcheck polices sharing/distinctness/gaps, never the base; verified at singleton/pair/offset scales), `fix_pagelist_class` inserts the collision-checked `bindery-pagelist` id beside the class (class-only insertion made epubcheck demand the id it enabled), `fix_missing_title` fills the self-closed `<title/>` head-scoped only (an empty SVG `<title>` is visible text the gate cannot measure), and four new flags live beside them: `fix_package_version` (literal 1.0 -> 2.0 only; `_PACKAGE_VERSION_ONE_RE`), `fix_doctype` (present-but-forbidden declarations only; `_scan_doctype_span` walks bracket depth and refuses unterminated spans), `prune_invalid_guide_refs` (declared-but-not-a-content-doc targets, both element shapes), and `fix_manifest_item_properties` + `collect_item_properties` (EPUB3-only census: scripted from `<script>`/`<form>`, svg from `<svg>`, remote-resources from absolute-scheme src/link/CSS url(); the insert branch appends before a self-closed item's solidus, never after it -- the v0.62.1 review caught the malformed `/ properties` shape). Since v0.62.1 `fix_double_colon_tags` escapes `::`-named pseudo-tags (a QName carries at most one colon, so such a construct is never markup; nested templates escape inner-first until stable; the tail is bounded at 120 chars so an escaped-bracket construct cannot swallow prose). Since v1.1.1 (the audit batch, issues #28-#33): `_norm_fragment` decodes a fragment the way `_resolve_href` decodes a path (XML entities, then RFC 3986 percent) before every anchor-cleaner existence check, so `#caf%C3%A9` matches `id="café"` instead of reading as broken (#29, the content/NCX/guide halves alike); `_ITEM_ID_RE`/`_XML_ID_RE` carry the `(?<![\w:.-])id=` lookbehind (`data-id`/`xml:id` are not ids: the manifest half renamed a `data-id` while the item's real id stayed; #30), while `ids_by_doc` collects through the dedicated `_ANCHOR_ID_RE` (`(?:xml:)?id`) because xml:id is a real XML id the oracle resolves fragments against -- dropping it from the anchor set would strip links the oracle never flagged; `downgrade_epub3_tags` runs through `outside_protected_map` and `_append_class`'s class matcher is whitespace-anchored (the unshielded `re.sub` downgraded commented-out markup and the bare `class=` merged into `data-class`; #32); and `declare_missing_manifest_items` locates the manifest close tag through `_MANIFEST_CLOSE_RE` (`</(?:[\w.-]+:)?manifest\s*>`: the literal `"</manifest>"` check/replace silently no-opped on prefixed and whitespace spellings; #33). Since v1.2.0 (issue #27) `strip_dead_font_faces` is the CSS-side dead `@font-face` drop (`--strip-dead-font-faces`): ebook-convert azw3->epub carries the source's font declarations without the payloads, filling the page_styles sheets with `url(styles/XXXXXXXXXXXXXXXX)` placeholders (one RSC-007 per dead reference; the manifest prune has no item to answer, so `--all` never converges); a block whose EVERY url() misses the archive drops rendering-neutral (the font never loaded), one live url() -- or a scheme/query/fragment/raw-space/local()-only reference (first #/? starts fragment/query, the #26 oracle model), or nested braces the flat-brace matcher cannot read exactly -- keeps it; resolution walks `_resolve_href` against the existence set (`present_src` when renames are licensed: the pass runs FIRST in the CSS branch, before `rewrite_space_renames_css`); XML comments/CDATA (`outside_protected_map`) AND plain CSS comments (`_CSS_COMMENT_SPAN_RE` spans, an INTERSECTION over the whole match: a `}` inside a comment truncates the match and a start-keyed drop would leave comment garbage -- `_PROTECTED_RE` covers XML comments only) are never rewritten; runs on `.css` entries only, and the flag joins the CSS branch gate and the `present`/`present_src` condition list.
290
290
  - `src/bindery/validate.py`: epubcheck wrapper, the `gate` (improvement) and `no_worse` (no-regression, for the lossy strips) acceptance bars. Since v0.55.0 (issue #15) the default oracle budget is size-scaled (`oracle_timeout_for`: 300s at or under 10 MB, +60s per started 10 MB above, 1800s cap), one subprocess retry follows a timed-out attempt (the daemon path's subprocess fallback is that attempt), and only a double timeout raises `OracleTimeout`, which the gate surfaces as `(epubcheck timeout)` instead of `(epubcheck failed)` (the sweep selectors catch it and keep the book a candidate). Since v0.60.0 (issue #24) the size term counts decimal MB (10,440,245 bytes is 9.96 binary MiB, so the book the docs call 10.4 MB computed the flat 300s base with no size chunk), and the budget also scales on archive entry count (+60s per started 500 entries above 1,000; a path that does not open as a zip falls back to size-only): the Summa Theologica is entry-count-bound, not bytes-bound (3,831 entries / 3,808 spine docs; measured 384s source and 445s candidate), and now computes 720s.
291
291
  - `src/bindery/library.py`: Calibre walk, atomic replace, backups, and native format installation. Since v0.19.0 `CalibreIdResolver` resolves the book id from `metadata.db` through cquarry (one lazy path→id map per run; since v0.20.0 the map comes from `CalibreDB.format_path_index()`, re-normalized with `resolve().lower()` for the resolver's symlinked-directory and case-insensitive matching); the `(id)` directory-name regex is only the no-catalog fallback. Since v0.24.0 `install_format()` places the repaired file atomically and updates the `data` row through `cquarry.write.WritableCalibreDB` (since v0.31.0 via `set_format`, cquarry 1.17's sanctioned remove+add in one transaction); the external `calibredb` CLI is gone. Since v0.32.0 a guessed id drives a row update only when metadata.db corroborates it (`_verify_guess`: books row exists, file in the book's own directory, catalogued `data.name` when a row exists); anything else saves in place and leaves the catalog untouched: never reintroduce directory-name guessing as the primary source: renamed/mismatched directories would replace the wrong book. Since 2026-09-15 `make_backup` takes the opt-in `--backup-keep N` ring: at most N backup files per book, the author original `.bak` never deleted, newest content at the highest name; default remains an unbounded rotation.
292
292
  - `src/bindery/cli.py`: `repair` and `library` subcommands, including `--all` and `--install-to-calibre`; since v0.52.0 `process_book` carries the spine-resolution veto (issue #10) above every verdict path, promotions included: a candidate whose spine dangles more than the source's is `reject` with `(spine collapse)` appended to the summary, whatever the counts say. Since v1.1.0 (issue #26) the `refs_delim_encoded` keyed promotion carries the missing-file mask bar above the gate's error-cleanup answer (net-new fatals reject, still-fatal partial, fatal-free accepts the unmasking rise; the veto still overrides). `repair --json` emits the library per-book record vocabulary (2026-09-15; since v0.45.0 every per-book record, the phase1 payload included, also carries the structured fix breakdown: the `fixes` dict plus `ncx_uid_synced`/`watermark_refusals` off the `Outcome`, and `_phase1_decisions` reads that data instead of substring-matching the rendered `summary`, which stays for human eyes; CalibreQuarry's lossy-consent mirror is the waiting consumer, floor `bindery>=0.45.0`); since v0.29.0 also the `run` verbs: `phase1` (pre-import vetting over loose files: the audit battery composed with one gated repair sweep; read-only until `--apply-lossy`, which IS the lossy-strip consent) and `phase3` (the scoped post-import apply step: `library --id --sweep --only all --apply --all --install-to-calibre` plus a pre/post summary; mechanically refuses unscoped sweeps with exit 2; since 2026-09-15 the summary sums applied/equal states only and carries rejected projections as `rejected_projection`). Plus `bindery doctor` (2026-09-15): the environment self-check that imports none of the VirInvictus stack, never raises, and always exits 0. The `observe` verb (v0.53.0) writes schema v2 artifacts since v0.55.0 (issue #13): `codes.messages` (renamed from the mislabeled `occurrences`) counts aggregated epubcheck JSON message entries, `codes.occurrences` now carries the true per-site scale (summed `locations`), a `counting` block states both scales in the artifact, and `--against` accepts v1 or v2 (the trend keys exist in both). Both run verbs take `--non-interactive` and surface open questions as `decisions_needed` in their JSON, never prompts. They drive the shipped `run_library` through the real parser, so no flag can drift between the verb and the subcommand it wraps. Since v0.46.0 `cli._flags_from_args(args)` is the one place the argparse names map onto `RepairFlags` fields (each `or --all`), shared by `run_library` and `run_repair`; the old per-verb ~25-kwarg blocks are gone. Since v0.47.1 the help is two-level (the --help-repairs reference is
293
293
  custom-rendered and colors itself with the CPython 3.14 argparse theme,
294
294
  gated by argparse's own _colorize detection so the levels always agree) and the repair-flag inventory is one table: `_REPAIR_FLAG_TABLE` (dest + one-line short help + long reference text) registers the compact grouped `--help` (argparse argument groups, hand-short usage line) and `--help-repairs` renders the long descriptions (a custom argparse Action, deliberately NOT store_true so the wiring test's selection count ignores it); adding a flag means adding a table row. Since v0.48.0 the metadata.db doors are enforced: `_require_closed_calibre` (pgrep fail-closed, exit 1) guards `audit --tag` and `library --apply --install-to-calibre` (run phase3 transitively), and `--help-json` (a custom argparse Action like --help-repairs, never colored) dumps the per-verb exit contract and the door list; since v0.48.1 the per-verb exit contracts tell the code's truth (repair: 0 probed/written incl. partial / 1 trouble, never 2; audit: 0/1/2 plus 3 for findings+write-failure; library and the run slices: the unified 0/2/1); since v0.49.0 the single-file verb's no-output form is a probe (the gate runs, the record's `output` is null and `applied` false, nothing is written anywhere; the old implicit `(repaired).epub` sibling was issue #7's import litter in a vetted tree, and writing now needs an explicit DST). `library --workers N` (v0.30.0) parallelizes only the sweep's candidate pass, in windows of N consumed in order so `--limit` stays lazy; the repair phase is never parallel (shared workdir, atomic-replacement contract). Since v0.40.0 `main()` guards the VirInvictus stack: a `ModuleNotFoundError` naming `vir_tui`/`cquarry` (marker-gated to 3.14+ on the 3.12 floor) becomes one stderr line and trouble exit 2 instead of a traceback; anything else missing still raises.
295
295
  - `plugin/__init__.py` + `scripts/build_plugin.py`: the Bindery Repair Calibre plugin (v0.37.0; identity `Bindery Repair` / `bindery_repair`, approved and built per the scoped spec in roadmap.md Phase 3). The builder vendors `transforms.py`, `epub.py`, `pagination.py`, `watermark.py`, `reserialize.py` byte-identically into the zip (the zip root is a package, so their relative imports resolve unchanged; the suite's drift test pins the equality) with the version tuple substituted from the single-source VERSION; `publish.yml` attaches `BinderyRepair-v<VERSION>.zip` to each release. The plugin runs ONLY the default pass (epubcheck cannot gate inside Calibre), never raises, is byte-idempotent (zero fixes returns the original path), testzip()-verifies its output, logs one line per book, and takes JSON config via `site_customization` (`log`, `log_path`, `max_size_mb` default 150, `max_log_mb` rotation cap default 2, `epubcheck_path` experimental validation default OFF). Load it in tests through the `tests/test_plugin.py` stubs: the calibre namespace is installed in sys.modules and the package loads with a two-dir `__path__` (plugin dir first, then src/bindery) exactly like calibre's zipplugin loader shape. **Plugin/interpreter compatibility (v0.40.0):** v0.39.0 shipped PEP 758 unparenthesized except tuples, and the plugin died with a bare SyntaxError on every released Calibre (7.x and the whole 8.x series embed Python 3.11, 9.0+ embeds 3.14; from calibre's bypy sources.json, checked against the upstream clone). The core is now grammar-pinned: parenthesized except tuples everywhere, `ruff`'s `target-version = "py312"` pin (inference from requires-python would rewrite the parens back off), `tests/test_version.py`'s parse guard, and CI's `plugin-compat` job byte-compiling the built zip under 3.11/3.12/3.13/3.14. `minimum_calibre_version` is (7, 0, 0): the oldest series whose interpreter CI covers, replacing the hollow (2, 0, 0); `supported_platforms` stays `["linux"]` (developed and tested on Linux only). Any new syntax in the vendored modules must clear the guard before it ships.
296
- - `tests/`: transforms (including the shared duplicate-id rename), end-to-end repair, atomic replace, pagination, watermarks, the audit analyzers (content/pagenumbers/emptytext/ocr/monolithic/completeness, archive integrity, spine classification, contamination since v0.50.0), the library sweep and `CalibreIdResolver`, validate, reserialize, CLI wiring, the version pin and the syntax-floor grammar guard, and the Calibre plugin (build drift + run behavior under calibre stubs). Since the v0.46.0 follow-ups: `tests/test_flags_wiring.py` reflectively pins the RepairFlags inventory to the argparse dests and `_flags_from_args` mapping (a flag added without a field, a field without a flag, or a remapped line fails there), the all-off defaults, and the version gate's caller-immutability contract (test_epub's `TestVersionGateKeepsFlagsIntact`); `tests/test_comment_hyphens.py` carries the RSC-016 fix; `tests/test_flags_real_core.py` drives every repair flag from argv through the unmocked core (--no-validate; the gate itself stays pinned by the mocked-oracle tests and runs for real wherever epubcheck exists). `tests/test_contamination.py` (v0.50.0) carries the three contamination sweeps, the advisory contract, the `_dir_dispatch` key pin, and the cover-routing regression. The v0.46.0 trio (test_flags_wiring, test_comment_hyphens, test_flags_real_core) rides CI's core-compat 3.12/3.13 leg; the hand-listed module list there must gain an entry for every new stack-free test module (audit-side test modules like test_contamination stay on the 3.14 leg by convention). The v0.55.0 batch (issues #11-#16): `tests/test_validate.py` pins the size-scaled timeout and the retry-then-OracleTimeout contract, `tests/test_observe.py` the v2 line format (`CODE:messages:occurrences`), the renamed codes block, the counting envelope, and v1 `--against` acceptance, `tests/test_epub.py::TestDeclareMissingItems` the RSC-008 declarer (sorted deterministic items, blessed media types only, id collisions prefixed, schemes/fragments/spaces/declared skipped), `tests/test_transforms.py::TestFixDuplicateIds` the content-doc rename, and `tests/test_flags_real_core.py` drives `--fix-duplicate-ids`, `--declare-missing-items`, and the extended `--strip-epub3-attrs` set through the real argv-to-fix path. The v0.59.0 addition (issue #23): `tests/test_epub.py::TestPruneDanglingNcxTargets` pins the node-exact prune rule (dead leaf dropped, dead parent spliced above live children, dead subtree one span, scheme/bare-fragment/contentless/comment-hidden untouched, escaped-ampersand src resolves, pageTarget and legacy navTarget covered, wrapper-crossing and unclosed walks abort, a wholesale-dead container refuses) plus the end-to-end prune+resequence, and `tests/test_flags_real_core.py` drives `--prune-dangling-ncx-targets` through argv. The v0.60.0 addition (issue #24): `tests/test_validate.py` pins the decimal-MB size term (exactly 10 MiB earns its 360s chunk) and the entry term (the 3,831-entry shape at <= 10 MB computes 660s; the full Summa shape computes 720s; exactly 1,000 entries stays at the size budget; 1,001 adds the first chunk; 2,500 computes 540s). The v0.62.x additions: `tests/test_transforms.py::TestFixNcxPlayorder`'s base-free clause tests (zero-based/offset untouched, gap fires) and `TestFixMissingTitleSelfClosed`/`TestFixMissingTitleHeadScope` (self-closed fill, SVG-title protection), `tests/test_epub.py::TestItemPropertiesInsertionBranch` (the self-closed well-formedness pin) and the five `TestFlag*EndToEnd` classes, `tests/test_transforms.py::TestFixDoubleColonTags(+Bounds)` (book shape, closing tags, nesting, bounds, raw-ampersand), the four new-flag fixtures + rows in `tests/test_flags_real_core.py`, and the five mapping entries in `tests/test_flags_wiring.py`. The v1.1.0 additions (issue #26): `tests/test_epub.py::TestEncodeDelimRefs` (the two gates, CSS/NCX/OPF shapes, display-text and comment exclusion, idempotence, and the repair-level guard+encode end-to-end) plus `TestPruneDeadSpine`'s mixed-census case (genuine dead + recoverable prunes only the genuine), `tests/test_spine_guard.py::DelimPromotionTests` (accept under the unmasking rise, net-new fatals reject, still-fatal partial, the veto still overrides) and `DelimFixtureRegressionTests` over the real facility fixture (no amputation, 36 encoded, spine 0 dangles), and `tests/test_contamination.py::TestShellAnalyzer`'s recoverable/mixed/true-shell trio. The v1.1.1 additions (issues #28-#33): `tests/test_transforms.py::TestIssue28FragmentSync` (digit-led/apostrophe NCX and href fragments follow the full predicate; valid and external fragments untouched) and `TestIssue30DataIdLookbehind` (data-id/xml:id never seed a duplicate rename; the real duplicate beside one still renames), `tests/test_epub.py::TestIssue29PercentDecodedFragments` (percent-encoded café/Cyrillic fragments survive across the anchor/NCX/guide halves; the ghost controls still strip, one per cleaner), `TestIssue30OpfIdLookbehind` (manifest/NCX `data-id` not renamed; the real digit-led id renames beside it), `TestIssue32DowngradeGuards` (`data-class` never merged, comment/CDATA untouched beside a real downgrade), `TestIssue33ManifestCloseTag` (prefixed and whitespace close tags declare; the original spelling survives), and `tests/test_pagination.py::TestSelfClosingParagraphs` (a self-closing divider never welds into a stripped block; the conservative path tolerates it). The pre-commit review additions: `tests/test_transforms.py::TestIssue28EscapedFragmentRefusal` (percent-encoded/entity-ref fragments refused in both passes, data-href/data-src out of scope, xlink:href still covered) and `tests/test_epub.py::TestIssue30XmlIdAnchorTarget` (a link targeting an xml:id-declared anchor survives `--strip-broken-anchors`).
296
+ - `tests/`: transforms (including the shared duplicate-id rename), end-to-end repair, atomic replace, pagination, watermarks, the audit analyzers (content/pagenumbers/emptytext/ocr/monolithic/completeness, archive integrity, spine classification, contamination since v0.50.0), the library sweep and `CalibreIdResolver`, validate, reserialize, CLI wiring, the version pin and the syntax-floor grammar guard, and the Calibre plugin (build drift + run behavior under calibre stubs). Since the v0.46.0 follow-ups: `tests/test_flags_wiring.py` reflectively pins the RepairFlags inventory to the argparse dests and `_flags_from_args` mapping (a flag added without a field, a field without a flag, or a remapped line fails there), the all-off defaults, and the version gate's caller-immutability contract (test_epub's `TestVersionGateKeepsFlagsIntact`); `tests/test_comment_hyphens.py` carries the RSC-016 fix; `tests/test_flags_real_core.py` drives every repair flag from argv through the unmocked core (--no-validate; the gate itself stays pinned by the mocked-oracle tests and runs for real wherever epubcheck exists). `tests/test_contamination.py` (v0.50.0) carries the three contamination sweeps, the advisory contract, the `_dir_dispatch` key pin, and the cover-routing regression. The v0.46.0 trio (test_flags_wiring, test_comment_hyphens, test_flags_real_core) rides CI's core-compat 3.12/3.13 leg; the hand-listed module list there must gain an entry for every new stack-free test module (audit-side test modules like test_contamination stay on the 3.14 leg by convention). The v0.55.0 batch (issues #11-#16): `tests/test_validate.py` pins the size-scaled timeout and the retry-then-OracleTimeout contract, `tests/test_observe.py` the v2 line format (`CODE:messages:occurrences`), the renamed codes block, the counting envelope, and v1 `--against` acceptance, `tests/test_epub.py::TestDeclareMissingItems` the RSC-008 declarer (sorted deterministic items, blessed media types only, id collisions prefixed, schemes/fragments/spaces/declared skipped), `tests/test_transforms.py::TestFixDuplicateIds` the content-doc rename, and `tests/test_flags_real_core.py` drives `--fix-duplicate-ids`, `--declare-missing-items`, and the extended `--strip-epub3-attrs` set through the real argv-to-fix path. The v0.59.0 addition (issue #23): `tests/test_epub.py::TestPruneDanglingNcxTargets` pins the node-exact prune rule (dead leaf dropped, dead parent spliced above live children, dead subtree one span, scheme/bare-fragment/contentless/comment-hidden untouched, escaped-ampersand src resolves, pageTarget and legacy navTarget covered, wrapper-crossing and unclosed walks abort, a wholesale-dead container refuses) plus the end-to-end prune+resequence, and `tests/test_flags_real_core.py` drives `--prune-dangling-ncx-targets` through argv. The v0.60.0 addition (issue #24): `tests/test_validate.py` pins the decimal-MB size term (exactly 10 MiB earns its 360s chunk) and the entry term (the 3,831-entry shape at <= 10 MB computes 660s; the full Summa shape computes 720s; exactly 1,000 entries stays at the size budget; 1,001 adds the first chunk; 2,500 computes 540s). The v0.62.x additions: `tests/test_transforms.py::TestFixNcxPlayorder`'s base-free clause tests (zero-based/offset untouched, gap fires) and `TestFixMissingTitleSelfClosed`/`TestFixMissingTitleHeadScope` (self-closed fill, SVG-title protection), `tests/test_epub.py::TestItemPropertiesInsertionBranch` (the self-closed well-formedness pin) and the five `TestFlag*EndToEnd` classes, `tests/test_transforms.py::TestFixDoubleColonTags(+Bounds)` (book shape, closing tags, nesting, bounds, raw-ampersand), the four new-flag fixtures + rows in `tests/test_flags_real_core.py`, and the five mapping entries in `tests/test_flags_wiring.py`. The v1.1.0 additions (issue #26): `tests/test_epub.py::TestEncodeDelimRefs` (the two gates, CSS/NCX/OPF shapes, display-text and comment exclusion, idempotence, and the repair-level guard+encode end-to-end) plus `TestPruneDeadSpine`'s mixed-census case (genuine dead + recoverable prunes only the genuine), `tests/test_spine_guard.py::DelimPromotionTests` (accept under the unmasking rise, net-new fatals reject, still-fatal partial, the veto still overrides) and `DelimFixtureRegressionTests` over the real facility fixture (no amputation, 36 encoded, spine 0 dangles), and `tests/test_contamination.py::TestShellAnalyzer`'s recoverable/mixed/true-shell trio. The v1.1.1 additions (issues #28-#33): `tests/test_transforms.py::TestIssue28FragmentSync` (digit-led/apostrophe NCX and href fragments follow the full predicate; valid and external fragments untouched) and `TestIssue30DataIdLookbehind` (data-id/xml:id never seed a duplicate rename; the real duplicate beside one still renames), `tests/test_epub.py::TestIssue29PercentDecodedFragments` (percent-encoded café/Cyrillic fragments survive across the anchor/NCX/guide halves; the ghost controls still strip, one per cleaner), `TestIssue30OpfIdLookbehind` (manifest/NCX `data-id` not renamed; the real digit-led id renames beside it), `TestIssue32DowngradeGuards` (`data-class` never merged, comment/CDATA untouched beside a real downgrade), `TestIssue33ManifestCloseTag` (prefixed and whitespace close tags declare; the original spelling survives), and `tests/test_pagination.py::TestSelfClosingParagraphs` (a self-closing divider never welds into a stripped block; the conservative path tolerates it). The pre-commit review additions: `tests/test_transforms.py::TestIssue28EscapedFragmentRefusal` (percent-encoded/entity-ref fragments refused in both passes, data-href/data-src out of scope, xlink:href still covered) and `tests/test_epub.py::TestIssue30XmlIdAnchorTarget` (a link targeting an xml:id-declared anchor survives `--strip-broken-anchors`). The v1.2.0 additions (issue #27): `tests/test_epub.py::TestStripDeadFontFaces` (dead block dropped, live/mixed/scheme/local-only/fragment/space blocks kept, nested-brace refusal, XML- and CSS-comment protection, idempotence, the repair-level end-to-end) and `TestStripDeadFontFacesReviewEdges` (query-carrying references refused live or dead, the comment-`}` truncation refusing the drop) plus the fixture + row in `tests/test_flags_real_core.py` and the wiring entry in `tests/test_flags_wiring.py`.
297
297
 
298
298
  ## Conventions
299
299
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bindery-cli
3
- Version: 1.1.1
3
+ Version: 1.2.0
4
4
  Summary: Audit EPUB body text and repair broken EPUBs with deterministic, epubcheck-gated fixes; atomic in-place replacement in a Calibre library.
5
5
  Project-URL: Homepage, https://github.com/VirInvictus/bindery-cli
6
6
  Project-URL: Repository, https://github.com/VirInvictus/bindery-cli
@@ -74,6 +74,7 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
74
74
  - **`--declare-missing-items`**: the RSC-008 inverse of the prune: adds the manifest `<item>` declarations the OPF never wrote for files the archive carries and the book references (content `<img src>`/`<link href>` targets, CSS `url()` resources, OPF guide references). Deterministic ids, media types from a blessed extension map only, and no `<itemref>` is ever written: the spine is untouched. Namespace-prefixed packages (`</opf:manifest>`) declare too (v1.1.1).
75
75
  - **`--fix-unique-identifier`**: wires the dangling OPF unique-identifier (OPF-030): adds the id the package names to the first `dc:identifier` when no element carries it, and aligns the NCX `dtb:uid` the broken wiring was masking in the same run. The `dc:` values are never touched; ambiguous shapes refuse.
76
76
  - **`--prune-missing-resources`**: removes references to files the archive does not contain (RSC-007/PKG-010): dead `<link>` elements, anchors' `href` to absent files (anchor text preserved), absent `<img>` sources (replaced by their alt text when they carry one), and orphaned non-spine OPF manifest items (with every package edge that pointed at them rewritten: `spine@toc`, `item@media-overlay`, `item@fallback`, and the EPUB2 cover meta). Spine documents are never pruned: a missing spine document is reported as a damaged fragment, not silently dropped.
77
+ - **`--strip-dead-font-faces`**: drops every `@font-face` block in a stylesheet whose `url()` references ALL miss the archive (v1.2.0, issue #27). ebook-convert's azw3→epub carries the source's font declarations without the font payloads, filling `page_styles.css` with `url(styles/XXXXXXXXXXXXXXXX)` placeholders: hundreds of RSC-007s per book that the manifest prune cannot reach (the OPF never declared the fonts) and where `--all` never converges. The font never loaded, so the fallback rendering is what the file already does and the drop is rendering-neutral. One live `url()` keeps the whole block; scheme, query, fragment, raw-space, and `local()`-only blocks are never guessed at; comments (XML and CSS alike) are never rewritten. Runs on `.css` entries.
77
78
  - **`--strip-broken-anchors`**: strips href attributes that cannot resolve, keeping the anchor text byte-for-byte: a `#fragment` the target document does not define (RSC-020/RSC-012; NCX navTargets fall back to the document target, so chapter navigation survives) and unresolvable URI schemes (`kindle:`, `file:`). Fragments are percent-decoded before the existence check, so valid links to non-ASCII ids (`#caf%C3%A9` naming `id="café"`) are kept (v1.1.1).
78
79
  - **`--encode-url-spaces`**: percent-encodes raw spaces in `src`/`href` attribute values across the package (OPF manifest, NCX, content documents). A URL with a literal space is not a valid URL (RSC-020) and unresolvable on strict readers; the encoded form denotes the same file. Since v0.44.0 the flag also renames archive entries whose names carry raw spaces to their underscore spellings and rewrites every reference to them (OPF, NCX, content, CSS `url()`), clearing the PKG-010 space-in-filename advisories: underscore, never percent-encoding, because epubcheck decodes references before entry lookup.
79
80
  - **`--fix-container`**: generates `META-INF/container.xml` at the located OPF when the container is missing or names a file the archive does not contain. This is the gateway defect: epubcheck stays fatal while the OPF is unfindable, so no repair can be gate-accepted on such a book until the container exists.
@@ -47,6 +47,7 @@ Everything below is off until its flag is passed (or all at once via `--all`). T
47
47
  - **`--declare-missing-items`**: the RSC-008 inverse of the prune: adds the manifest `<item>` declarations the OPF never wrote for files the archive carries and the book references (content `<img src>`/`<link href>` targets, CSS `url()` resources, OPF guide references). Deterministic ids, media types from a blessed extension map only, and no `<itemref>` is ever written: the spine is untouched. Namespace-prefixed packages (`</opf:manifest>`) declare too (v1.1.1).
48
48
  - **`--fix-unique-identifier`**: wires the dangling OPF unique-identifier (OPF-030): adds the id the package names to the first `dc:identifier` when no element carries it, and aligns the NCX `dtb:uid` the broken wiring was masking in the same run. The `dc:` values are never touched; ambiguous shapes refuse.
49
49
  - **`--prune-missing-resources`**: removes references to files the archive does not contain (RSC-007/PKG-010): dead `<link>` elements, anchors' `href` to absent files (anchor text preserved), absent `<img>` sources (replaced by their alt text when they carry one), and orphaned non-spine OPF manifest items (with every package edge that pointed at them rewritten: `spine@toc`, `item@media-overlay`, `item@fallback`, and the EPUB2 cover meta). Spine documents are never pruned: a missing spine document is reported as a damaged fragment, not silently dropped.
50
+ - **`--strip-dead-font-faces`**: drops every `@font-face` block in a stylesheet whose `url()` references ALL miss the archive (v1.2.0, issue #27). ebook-convert's azw3→epub carries the source's font declarations without the font payloads, filling `page_styles.css` with `url(styles/XXXXXXXXXXXXXXXX)` placeholders: hundreds of RSC-007s per book that the manifest prune cannot reach (the OPF never declared the fonts) and where `--all` never converges. The font never loaded, so the fallback rendering is what the file already does and the drop is rendering-neutral. One live `url()` keeps the whole block; scheme, query, fragment, raw-space, and `local()`-only blocks are never guessed at; comments (XML and CSS alike) are never rewritten. Runs on `.css` entries.
50
51
  - **`--strip-broken-anchors`**: strips href attributes that cannot resolve, keeping the anchor text byte-for-byte: a `#fragment` the target document does not define (RSC-020/RSC-012; NCX navTargets fall back to the document target, so chapter navigation survives) and unresolvable URI schemes (`kindle:`, `file:`). Fragments are percent-decoded before the existence check, so valid links to non-ASCII ids (`#caf%C3%A9` naming `id="café"`) are kept (v1.1.1).
51
52
  - **`--encode-url-spaces`**: percent-encodes raw spaces in `src`/`href` attribute values across the package (OPF manifest, NCX, content documents). A URL with a literal space is not a valid URL (RSC-020) and unresolvable on strict readers; the encoded form denotes the same file. Since v0.44.0 the flag also renames archive entries whose names carry raw spaces to their underscore spellings and rewrites every reference to them (OPF, NCX, content, CSS `url()`), clearing the PKG-010 space-in-filename advisories: underscore, never percent-encoding, because epubcheck decodes references before entry lookup.
52
53
  - **`--fix-container`**: generates `META-INF/container.xml` at the located OPF when the container is missing or names a file the archive does not contain. This is the gateway defect: epubcheck stays fatal while the OPF is unfindable, so no repair can be gate-accepted on such a book until the container exists.
@@ -1,5 +1,55 @@
1
1
  # bindery-cli Patch Notes
2
2
 
3
+ ## v1.2.0 (2026-11-16)
4
+
5
+ ### The CSS dead-font drop (issue #27)
6
+
7
+ Found 2026-11-13 converting four azw3 cookbooks to epub with ebook-convert
8
+ before import. The converter carries the source's `@font-face` CSS
9
+ declarations but NOT the font payloads they reference: the output's
10
+ `page_styles.css` and `page_styles1.css` fill with blocks whose `src` is the
11
+ literal placeholder `url(styles/XXXXXXXXXXXXXXXX)` -- fonts named in the
12
+ source (Dante, Nexa, SourceHan, FreeSans) but never carried over. epubcheck
13
+ reports each dead reference as RSC-007 (Referenced resource could not be
14
+ found): live counts 149/316/159/450 errors across the four files, 0 fatals.
15
+ The gate's `--all` set never converges them: `--prune-missing-resources`
16
+ works the OPF manifest, and these references live in CSS `url()`, where no
17
+ item exists to prune (the OPF never declared the fonts).
18
+
19
+ - **`--strip-dead-font-faces`** (structural repair #35): for every
20
+ `@font-face` block in a stylesheet, resolve each `url()` reference
21
+ against the archive (the shared href resolver: XML entities, then RFC
22
+ 3986 percent-decoding, relative to the stylesheet's directory). A block
23
+ whose every reference misses the archive is dead by construction -- the
24
+ font never loaded, so the fallback rendering is what the file already
25
+ does -- and drops, rendering-neutral. The semantics-preserving guards
26
+ (the last two from the pre-commit review): one live `url()` keeps the
27
+ whole block; a scheme, query, fragment, raw space, or empty reference
28
+ keeps it (never guessed at: first `#`/`?` starts fragment/query, so a
29
+ query-carrying url whose path portion exists is a LIVE reference); a
30
+ `local()`-only block is not this class; a block with nested braces the
31
+ flat-brace matcher cannot read exactly is refused; and comments are
32
+ never rewritten -- XML comments and CDATA through the protected-region
33
+ split, plain CSS comments through a span-intersection check (a `}`
34
+ inside a comment truncates the flat-brace match short, and a drop
35
+ keyed on the match START alone would leave comment garbage in the
36
+ stylesheet), because dropping a commented-out block is a byte change
37
+ epubcheck cannot measure that another flag's gain could carry into an
38
+ applied candidate.
39
+ - **Gate behavior**: normal `gate`, like the other reference repairs --
40
+ the RSC-007 count is the measured gain. Runs on `.css` entries only.
41
+ When `--encode-url-spaces` renames entries, the pass judges references
42
+ against the pre-rename layout (first in the stylesheet branch, before
43
+ the reference rewrites), so a live font under a raw-space name can
44
+ never read as dead.
45
+ - **Facility verification** (the two pristine converter outputs the issue
46
+ attached): scoped-flag gate runs 0f/6e -> 0f/3e (16 blocks dropped) and
47
+ 0f/5e -> 0f/2e (25 blocks dropped), both ACCEPT, zero residual
48
+ RSC-007 -- the remaining errors are other flags' classes (`epub:type`
49
+ scrubs, colon ids) and clear under their own flags.
50
+
51
+ Suite: 985 tests.
52
+
3
53
  ## v1.1.1 (2026-11-16)
4
54
 
5
55
  ### The audit batch (issues #28-#33)
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bindery-cli"
7
- version = "1.1.1"
7
+ version = "1.2.0"
8
8
  description = "Audit EPUB body text and repair broken EPUBs with deterministic, epubcheck-gated fixes; atomic in-place replacement in a Calibre library."
9
9
  readme = "README.md"
10
10
  classifiers = [
@@ -64,6 +64,7 @@ The plugin vendors the core and never gates (the epubcheck latency ruling).
64
64
  | 0.64 | `--prune-dead-spine`: the shell repair, shell-gated at the 50% signature (drops dead manifest items + spine itemrefs, coordinates the NCX navPoint prune and an UNCONDITIONAL playOrder re-sequence to 1..K after epubcheck 5.3 flagged the non-1 base on the post-prune shape -- the base-free clause's minimal matrix missed the shell shape); proven at 742e -> 5e on the facility copy | v0.64.0 |
65
65
  | 1.1 | The delimiter-damage repair (issue #26): `--encode-ref-delims` (structural repair #34; the two-gate existence-proven encode for raw #/? filename damage: the reference must not resolve as written, the encoded spelling must match an archive entry; entities and empty-path anchors refused), the shell census's delim-recoverable exclusion (output layout AND raw layout; the Elminster shape can never cross the 50% signature), the missing-file mask acceptance bar keyed on `refs_delim_encoded`, and the audit shell verdict on the genuine fraction (`spine_missing_delim`; a fully-recoverable book reads ADVISORY, never SHELL); plus the two latent gaps the flag surfaced (the brackets OPF dispatch, the stylesheet non-UTF-8 guard). Fixture: probe accept 0f/3e -> 0f/4e, 36 encoded, no amputation, dangles 36 -> 0 | v1.1.0 |
66
66
  | 1.1.1 | The audit batch (issues #28-#33, filed from the 2026-11-16 deep codebase audit, each live-replicated before the fix; no CLI surface change): the NCX fragment half follows the full `fix_id_colons` NCName predicate and rename and both fragment passes carry the tempered-quote idiom (digit-led and apostrophe-bearing ToC/href fragments no longer dangle or diverge; escaped fragments -- percent-escapes and entity references -- refused outright per the pre-commit review, and the matchers take the whitespace+namespace anchor), the three anchor cleaners percent-decode fragments before the existence check (links to non-ASCII ids survive; xml:id stays in the anchor index via `_ANCHOR_ID_RE`), `data-id`/`xml:id`/`data-class` leave the id and class matchers (the `fix_id_colons` lookbehind generalized), the EPUB3 downgrade never rewrites comments or CDATA, a self-closing paragraph never welds into a pagination block, and the manifest declarer finds prefixed and whitespace close tags | v1.1.1 |
67
+ | 1.2 | The CSS dead-font drop (issue #27): `--strip-dead-font-faces` (structural repair #35) removes every `@font-face` block in a stylesheet whose url() references ALL miss the archive -- the ebook-convert azw3->epub placeholder class (`url(styles/XXXXXXXXXXXXXXXX)`, one RSC-007 per dead reference, 149/316/159/450 errors across the four found cookbooks; the manifest prune has no item to answer and `--all` never converges because the references live in CSS url()). Rendering-neutral by construction (the font never loaded; the fallback is the rendered reality), one live url() keeps the block, scheme/query/fragment/raw-space/local()-only references and nested-brace blocks are never guessed at (the query guard and the comment-span intersection rule are pre-commit-review catches), resolution walks the shared resolver against the pre-rename layout (the pass runs first in the CSS branch), and XML comments/CDATA plus plain CSS comments are never rewritten. Facility verification: scoped-flag gate runs 0f/6e -> 0f/3e and 0f/5e -> 0f/2e, both ACCEPT, zero residual RSC-007 (the residuals are other flags' classes: epub:type, colon ids) | v1.2.0 |
67
68
 
68
69
  ## Open work
69
70
 
@@ -13,7 +13,7 @@ restyle, re-compress, or restructure content, and it does not attempt to fix arb
13
13
  schema (RSC-005) violations, which are usually harmless to readers and not safely
14
14
  mechanizable.
15
15
 
16
- The deliberate exceptions to "semantics-preserving" come in opt-in groups. The thirty-four
16
+ The deliberate exceptions to "semantics-preserving" come in opt-in groups. The thirty-five
17
17
  **structural repairs** (`--fix-empty-body`, `--fix-missing-title`, `--fix-id-colons`,
18
18
  `--fix-page-map`, `--strip-epub3-attrs`, `--downgrade-epub3-tags`,
19
19
  `--unwrap-block-in-inline`, `--strip-invalid-value`, `--unwrap-illegal-tags`,
@@ -26,7 +26,7 @@ The deliberate exceptions to "semantics-preserving" come in opt-in groups. The t
26
26
  `--fix-unique-identifier`, `--fix-package-version`, `--fix-doctype`,
27
27
  `--prune-invalid-guide-refs`, `--fix-item-properties`,
28
28
  `--strip-presentational-attrs`, `--encode-ref-brackets`,
29
- `--encode-ref-delims`,
29
+ `--encode-ref-delims`, `--strip-dead-font-faces`,
30
30
  `--prune-dead-spine`) alter
31
31
  markup structure or fabricate minimal content; the four
32
32
  **lossy modes** (`--strip-pagination`, `--strip-broken-tags`, `--strip-watermarks`,
@@ -266,6 +266,23 @@ every EPUB3 book in an `--all` sweep taking exactly that damage).
266
266
  prune reads, never snapshotted earlier: `--fix-manifest-ids` may have renamed item
267
267
  ids and spine idrefs ahead of it in the OPF pipeline, and a guard describing the old
268
268
  spelling protects nothing.
269
+ - **`--strip-dead-font-faces`** (v1.2.0, issue #27): drop every `@font-face` block in
270
+ a stylesheet whose `url()` references ALL miss the archive (RSC-007 raised from CSS
271
+ url(): ebook-convert azw3->epub carries the source's font declarations without the
272
+ font payloads, filling `page_styles.css` with `url(styles/XXXXXXXXXXXXXXXX)`
273
+ placeholders the manifest prune cannot answer, because the OPF never declared the
274
+ fonts). The font never loaded, so the fallback rendering is what the file already
275
+ does and dropping the block is rendering-neutral. One live url() keeps the whole
276
+ block; a scheme, query, fragment, raw-space, or url()-less (`local()`-only) reference also
277
+ keeps it (never guessed at: first `#`/`?` starts fragment/query, so a query-carrying
278
+ url whose path portion exists is a live reference), as does any block the flat-brace matcher cannot read
279
+ exactly (nested braces). Resolution walks the shared href resolver; XML
280
+ comments/CDATA and plain CSS comments are never rewritten (a commented-out block is
281
+ invisible to the oracle, and dropping it would be a byte change another flag's gain
282
+ could carry into an applied candidate; the span check is an intersection over the
283
+ whole match, because a `}` inside a comment truncates the flat-brace match and a
284
+ start-keyed drop would leave comment garbage in the stylesheet). Runs on `.css`
285
+ entries only.
269
286
  - **`--declare-missing-items`**: the RSC-008 inverse of the prune (v0.55.0, issue
270
287
  #16): add the manifest `<item>` declarations the OPF never wrote for files the
271
288
  archive carries and the book references: content `<img src>` and `<link href>`
@@ -606,7 +623,7 @@ leftovers whose failing OPF is a stale non-rootfile are unreachable by construct
606
623
  book whose manifest "missing" is all recoverable now reads ADVISORY
607
624
  naming the encode, never SHELL/re-source.
608
625
 
609
- Thirty of the thirty-four are evaluated by the normal `gate`: unlike the lossy strips,
626
+ Thirty-one of the thirty-five are evaluated by the normal `gate`: unlike the lossy strips,
610
627
  their benefit is visible to epubcheck (they clear errors), so a run with no measurable
611
628
  improvement is a noop and nothing is applied. `--fix-cover`, `--encode-url-spaces`, and
612
629
  `--fix-media-types` (whose gains sit on axes epubcheck's counts do not measure:
@@ -11,7 +11,7 @@ Calibre plugin built from this core.
11
11
  Single source of truth for the version. pyproject.toml must match VERSION below.
12
12
  """
13
13
 
14
- VERSION = "1.1.1"
14
+ VERSION = "1.2.0"
15
15
  __version__ = VERSION
16
16
 
17
17
  from .epub import RepairReport, repair_epub # noqa: E402
@@ -117,6 +117,7 @@ def _flags_from_args(args: argparse.Namespace) -> RepairFlags:
117
117
  presentational_attrs=args.strip_presentational_attrs or all_,
118
118
  encode_ref_brackets=args.encode_ref_brackets or all_,
119
119
  encode_ref_delims=args.encode_ref_delims or all_,
120
+ strip_dead_font_faces=args.strip_dead_font_faces or all_,
120
121
  prune_dead_spine=args.prune_dead_spine or all_,
121
122
  )
122
123
 
@@ -1858,6 +1859,23 @@ _REPAIR_FLAG_TABLE: dict[str, list[tuple[str, str, str]]] = {
1858
1859
  ),
1859
1860
  ],
1860
1861
  "structural repairs: references and resources": [
1862
+ (
1863
+ "strip_dead_font_faces",
1864
+ "drop @font-face blocks whose url() references all miss the archive (RSC-007)",
1865
+ "drop every @font-face block in a stylesheet whose url() "
1866
+ "references ALL fail to resolve against the archive (issue #27: "
1867
+ "ebook-convert azw3->epub carries the source's font declarations "
1868
+ "but not the font payloads, filling page_styles.css with "
1869
+ "url(styles/XXXXXXXXXXXXXXXX) placeholders -- one RSC-007 per "
1870
+ "dead reference, hundreds per book, and the manifest prune has "
1871
+ "no item to answer because the OPF never declared the fonts). "
1872
+ "The font never loaded, so the fallback rendering is what the "
1873
+ "file already does and dropping the block is rendering-neutral. "
1874
+ "One live url() keeps the whole block, as does a scheme, "
1875
+ "fragment, raw-space, or url()-less (local()-only) block; "
1876
+ "resolution walks the same helper the reference repairs use, "
1877
+ "and comments/CDATA are never rewritten. Runs on .css entries.",
1878
+ ),
1861
1879
  (
1862
1880
  "prune_dead_spine",
1863
1881
  "the shell repair: drop manifest items and spine positions whose files the archive never carried",
@@ -299,6 +299,7 @@ class RepairFlags:
299
299
  presentational_attrs: bool = False
300
300
  encode_ref_brackets: bool = False
301
301
  encode_ref_delims: bool = False
302
+ strip_dead_font_faces: bool = False
302
303
  prune_dead_spine: bool = False
303
304
 
304
305
 
@@ -1557,6 +1558,83 @@ def declare_missing_manifest_items(
1557
1558
  return opf_text[:idx] + "\n".join(lines) + "\n" + opf_text[idx:], count
1558
1559
 
1559
1560
 
1561
+ # ---- --strip-dead-font-faces: the CSS-side dead @font-face drop (issue #27).
1562
+ # ebook-convert azw3->epub carries the source's @font-face declarations but
1563
+ # NOT the font payloads they reference, filling the page_styles sheets with
1564
+ # url(styles/XXXXXXXXXXXXXXXX) placeholders the archive cannot resolve: one
1565
+ # RSC-007 per dead reference, 149/316/159/450 errors across the four
1566
+ # converter outputs that found the class. The manifest prune cannot answer
1567
+ # (there is no item: the OPF never declared the fonts) and the gate's --all
1568
+ # never converges, because the references live in CSS url(), not markup. A
1569
+ # @font-face block whose EVERY url() misses the archive is dead by
1570
+ # construction -- the font never loaded, so the fallback rendering is what
1571
+ # the file already does -- and dropping the block is rendering-neutral.
1572
+ # One live url() keeps the whole block; a block with no url() at all
1573
+ # (src: local(...) spellings) is not this class.
1574
+
1575
+ _FONT_FACE_BLOCK_RE = re.compile(r"@font-face\b[^{}]*\{[^{}]*\}", re.IGNORECASE)
1576
+ # Plain CSS comments are NOT XML comments: _PROTECTED_RE covers `<!-- -->`
1577
+ # and CDATA only, so a commented-out @font-face needs its own span check
1578
+ # (the issue #21 lesson: comment-hidden markup must never count -- dropping
1579
+ # it is a byte change epubcheck cannot measure and other flags' gains would
1580
+ # carry into the applied candidate).
1581
+ _CSS_COMMENT_SPAN_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
1582
+
1583
+
1584
+ def strip_dead_font_faces(
1585
+ css: str, css_dir: str, present: frozenset[str] | set[str]
1586
+ ) -> tuple[str, int]:
1587
+ """Drop every ``@font-face`` block whose ``url()`` references all miss
1588
+ the archive (issue #27). Resolution walks the same helper the reference
1589
+ repairs resolve with (``_resolve_href``: XML entities then RFC 3986
1590
+ percent, relative to the stylesheet's directory, norm-normalized like
1591
+ the existence set). A reference carrying a scheme, a fragment, or a raw
1592
+ space is not provably dead and keeps its block: this repair never
1593
+ guesses. XML comments/CDATA (outside_protected_map) and plain CSS
1594
+ comments (the span check) are never rewritten."""
1595
+
1596
+ def fix(part: str) -> tuple[str, int]:
1597
+ n = 0
1598
+ css_comments = (
1599
+ [(m.start(), m.end()) for m in _CSS_COMMENT_SPAN_RE.finditer(part)]
1600
+ if "/*" in part
1601
+ else []
1602
+ )
1603
+
1604
+ def in_css_comment(pos: int) -> bool:
1605
+ return any(a <= pos < b for a, b in css_comments)
1606
+
1607
+ def repl(m: re.Match) -> str:
1608
+ nonlocal n
1609
+ block = m.group(0)
1610
+ # ANY comment span intersecting the match refuses the drop: a
1611
+ # `}` inside a comment truncates the flat-brace match short, and
1612
+ # dropping a truncated "block" would leave comment garbage in
1613
+ # the stylesheet (the #21/#32 comment-blindness class)
1614
+ if any(a < m.end() and m.start() < b for a, b in css_comments):
1615
+ return block
1616
+ urls = list(_iter_css_urls(block))
1617
+ if not urls:
1618
+ return block
1619
+ for ref in urls:
1620
+ # first #/? starts fragment/query (the issue #26 oracle
1621
+ # model): a query-carrying url whose path portion exists is
1622
+ # a LIVE reference, never this class
1623
+ if not ref.strip() or "#" in ref or "?" in ref or " " in ref:
1624
+ return block
1625
+ if _URL_SCHEME_RE.match(ref):
1626
+ return block
1627
+ resolved = _resolve_href(css_dir, ref)
1628
+ if resolved is not None and resolved in present:
1629
+ return block
1630
+ n += 1
1631
+ return ""
1632
+
1633
+ return _FONT_FACE_BLOCK_RE.sub(repl, part), n
1634
+
1635
+ return outside_protected_map(css, fix)
1636
+
1637
+
1560
1638
  # ---- --strip-stub-docs: the lossy drop of repeated placeholder spine docs.
1561
1639
  # The conservative identity rule mirrors the emptytext analyzer's
1562
1640
  # placeholder-stub signals (audit.py): a stub is short but not blank, the
@@ -2618,6 +2696,7 @@ def repair_epub(
2618
2696
  or flags.prune_ncx_targets
2619
2697
  or flags.encode_ref_brackets
2620
2698
  or flags.encode_ref_delims
2699
+ or flags.strip_dead_font_faces
2621
2700
  or flags.prune_dead_spine
2622
2701
  ):
2623
2702
  for n in zin.namelist():
@@ -3361,7 +3440,10 @@ def repair_epub(
3361
3440
  report.files_changed += 1
3362
3441
  data = svg_text.encode("utf-8")
3363
3442
  elif low.endswith((".css", ".xpgt")) and (
3364
- space_renames or flags.encode_ref_brackets or flags.encode_ref_delims
3443
+ space_renames
3444
+ or flags.encode_ref_brackets
3445
+ or flags.encode_ref_delims
3446
+ or (flags.strip_dead_font_faces and low.endswith(".css"))
3365
3447
  ):
3366
3448
  # Stylesheets pass through the rewrite too: a url() that
3367
3449
  # resolved against a raw-space entry would dangle the
@@ -3381,6 +3463,20 @@ def repair_epub(
3381
3463
  report.add({"non_utf8_docs_skipped": 1})
3382
3464
  zout.writestr(out_item, data, compress_type=item.compress_type)
3383
3465
  continue
3466
+ if flags.strip_dead_font_faces and low.endswith(".css"):
3467
+ # First in the branch: the references it judges are still
3468
+ # in the SOURCE spelling, so the existence set is
3469
+ # present_src when renames are licensed (the OPF prune's
3470
+ # layout rule -- a live font under a raw-space name must
3471
+ # not read as dead before its references are rewritten).
3472
+ text, n = strip_dead_font_faces(
3473
+ text,
3474
+ posixpath.dirname(name),
3475
+ present_src if space_renames else present,
3476
+ )
3477
+ if n:
3478
+ report.add({"dead_font_faces_stripped": n})
3479
+ report.files_changed += 1
3384
3480
  if flags.encode_ref_brackets:
3385
3481
  text, n = encode_bracket_refs_css(
3386
3482
  text, posixpath.dirname(name), present
@@ -34,6 +34,7 @@ from bindery.epub import (
34
34
  package_version,
35
35
  prune_invalid_guide_refs,
36
36
  repair_epub,
37
+ strip_dead_font_faces,
37
38
  strip_epub3_attributes,
38
39
  strip_missing_file_hrefs,
39
40
  strip_ncx_dangling_targets,
@@ -4406,3 +4407,143 @@ class TestIssue30XmlIdAnchorTarget(unittest.TestCase):
4406
4407
  b = z.read("OEBPS/b.xhtml").decode()
4407
4408
  self.assertIn('href="a.xhtml#tgt"', b)
4408
4409
  self.assertIn("<a>dead</a>", b)
4410
+
4411
+
4412
+ class TestStripDeadFontFaces(unittest.TestCase):
4413
+ """--strip-dead-font-faces (issue #27): a @font-face block whose every
4414
+ url() misses the archive is dead by construction -- the font never
4415
+ loaded, so the fallback rendering is what the file already does. One
4416
+ live reference keeps the block; comments are never rewritten."""
4417
+
4418
+ DEAD = (
4419
+ "@font-face {\n font-family: 'Dante';\n"
4420
+ " src: url(styles/XXXXXXXXXXXXXXXX) format('truetype');\n}\n"
4421
+ )
4422
+ LIVE = (
4423
+ "@font-face {\n font-family: 'Kept';\n"
4424
+ " src: url(fonts/kept.ttf) format('truetype');\n}\n"
4425
+ )
4426
+
4427
+ def test_dead_block_dropped(self):
4428
+ css = self.DEAD + "p { margin: 0; }"
4429
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset({"OEBPS/p.css"}))
4430
+ self.assertEqual(n, 1)
4431
+ self.assertNotIn("@font-face", out)
4432
+ self.assertIn("p { margin: 0; }", out)
4433
+
4434
+ def test_live_block_kept(self):
4435
+ css = self.LIVE + "p { margin: 0; }"
4436
+ out, n = strip_dead_font_faces(
4437
+ css, "OEBPS", frozenset({"OEBPS/fonts/kept.ttf"})
4438
+ )
4439
+ self.assertEqual((out, n), (css, 0))
4440
+
4441
+ def test_one_live_reference_keeps_the_block(self):
4442
+ css = (
4443
+ "@font-face {\n font-family: 'Mixed';\n"
4444
+ " src: url(styles/DEADBEEFDEADBEEF) format('truetype'),"
4445
+ " url(fonts/kept.ttf) format('truetype');\n}\n"
4446
+ )
4447
+ out, n = strip_dead_font_faces(
4448
+ css, "OEBPS", frozenset({"OEBPS/fonts/kept.ttf"})
4449
+ )
4450
+ self.assertEqual((out, n), (css, 0))
4451
+
4452
+ def test_local_only_and_scheme_blocks_kept(self):
4453
+ css = (
4454
+ "@font-face { font-family: 'L'; src: local('Dante'); }\n"
4455
+ "@font-face { font-family: 'R'; src: url(https://fonts.example/d.ttf); }\n"
4456
+ )
4457
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4458
+ self.assertEqual((out, n), (css, 0))
4459
+
4460
+ def test_fragment_and_space_references_kept(self):
4461
+ css = (
4462
+ "@font-face { font-family: 'F'; src: url(fonts/a.ttf#x); }\n"
4463
+ "@font-face { font-family: 'S'; src: url(fonts/a b.ttf); }\n"
4464
+ )
4465
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4466
+ self.assertEqual((out, n), (css, 0))
4467
+
4468
+ def test_nested_brace_block_refused(self):
4469
+ # the flat-brace matcher declines anything it cannot read exactly:
4470
+ # a block with nested braces is not provably this class
4471
+ css = "@font-face { src: url(a.ttf); foo { bar: baz }; }\n"
4472
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4473
+ self.assertEqual((out, n), (css, 0))
4474
+
4475
+ def test_comment_protected(self):
4476
+ css = "/* " + self.DEAD + " */\np { margin: 0; }"
4477
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4478
+ self.assertEqual((out, n), (css, 0))
4479
+
4480
+ def test_idempotent(self):
4481
+ css = self.DEAD + "p { margin: 0; }"
4482
+ once, n1 = strip_dead_font_faces(css, "OEBPS", frozenset())
4483
+ twice, n2 = strip_dead_font_faces(once, "OEBPS", frozenset())
4484
+ self.assertEqual(n1, 1)
4485
+ self.assertEqual(n2, 0)
4486
+ self.assertEqual(once, twice)
4487
+
4488
+ def test_repair_level_end_to_end(self):
4489
+ opf = (
4490
+ '<?xml version="1.0"?>'
4491
+ '<package xmlns="http://www.idpf.org/2007/opf" version="2.0" '
4492
+ 'unique-identifier="id"><metadata>'
4493
+ '<dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/" '
4494
+ 'id="id">urn:uuid:U</dc:identifier></metadata>'
4495
+ '<manifest><item id="c1" href="c1.xhtml" '
4496
+ 'media-type="application/xhtml+xml"/>'
4497
+ '<item id="ps" href="page_styles.css" media-type="text/css"/>'
4498
+ "</manifest>"
4499
+ '<spine><itemref idref="c1"/></spine></package>'
4500
+ )
4501
+ content = (
4502
+ '<?xml version="1.0"?>'
4503
+ '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>t</title>'
4504
+ '<link rel="stylesheet" href="page_styles.css" type="text/css"/>'
4505
+ "</head><body><p>x</p></body></html>"
4506
+ )
4507
+ with tempfile.TemporaryDirectory() as td:
4508
+ src = Path(td) / "in.epub"
4509
+ dst = Path(td) / "out.epub"
4510
+ with zipfile.ZipFile(src, "w") as z:
4511
+ z.writestr("mimetype", "application/epub+zip")
4512
+ z.writestr("OEBPS/content.opf", opf)
4513
+ z.writestr("OEBPS/c1.xhtml", content)
4514
+ z.writestr(
4515
+ "OEBPS/page_styles.css",
4516
+ self.DEAD + self.LIVE,
4517
+ )
4518
+ z.writestr("OEBPS/fonts/kept.ttf", b"\x00\x01\x02\x03")
4519
+ report = repair_epub(src, dst, RepairFlags(strip_dead_font_faces=True))
4520
+ self.assertEqual(report.fixes.get("dead_font_faces_stripped"), 1)
4521
+ with zipfile.ZipFile(dst) as z:
4522
+ css = z.read("OEBPS/page_styles.css").decode()
4523
+ self.assertNotIn("Dante", css)
4524
+ self.assertIn("Kept", css)
4525
+
4526
+
4527
+ class TestStripDeadFontFacesReviewEdges(unittest.TestCase):
4528
+ """The pre-commit review's two edges: a query-carrying url() whose path
4529
+ portion exists is a LIVE reference (first #/? starts fragment/query, the
4530
+ issue #26 oracle model), and a comment carrying `}` inside a block body
4531
+ refuses the drop (the truncated flat-brace match would leave comment
4532
+ garbage in the stylesheet)."""
4533
+
4534
+ def test_query_carrying_live_reference_keeps_the_block(self):
4535
+ css = "@font-face{font-family:X;src:url(fonts/x.woff?v=1);}"
4536
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset({"OEBPS/fonts/x.woff"}))
4537
+ self.assertEqual((out, n), (css, 0))
4538
+
4539
+ def test_query_carrying_dead_reference_keeps_the_block(self):
4540
+ # the query shape is refused outright, dead or not: this pass never
4541
+ # acts on a ?-carrying value (every sibling reference pass does the same)
4542
+ css = "@font-face{font-family:X;src:url(styles/DEAD?v=1);}"
4543
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4544
+ self.assertEqual((out, n), (css, 0))
4545
+
4546
+ def test_comment_with_close_brace_inside_refuses_the_drop(self):
4547
+ css = "@font-face{font-family:X;src:url(dead.woff)/* } */;}\np{margin:0}"
4548
+ out, n = strip_dead_font_faces(css, "OEBPS", frozenset())
4549
+ self.assertEqual((out, n), (css, 0))
@@ -292,6 +292,18 @@ def _fixtures() -> dict:
292
292
  ),
293
293
  "--encode-ref-delims": (delim_entries, "refs_delim_encoded"),
294
294
  "--encode-ref-brackets": (bracket_entries, "bracket_refs_encoded"),
295
+ "--strip-dead-font-faces": (
296
+ {
297
+ "OEBPS/content.opf": _opf([c1], [r1]),
298
+ "OEBPS/c1.xhtml": plain,
299
+ "OEBPS/page_styles.css": (
300
+ "@font-face {\n font-family: 'Dante';\n"
301
+ " src: url(styles/XXXXXXXXXXXXXXXX) format('truetype');\n}\n"
302
+ "p { margin: 0; }"
303
+ ),
304
+ },
305
+ "dead_font_faces_stripped",
306
+ ),
295
307
  "--fix-container": (
296
308
  {
297
309
  "META-INF/container.xml": (
@@ -714,6 +726,11 @@ class FlagEndToEndTests(unittest.TestCase):
714
726
  self._fixes_for("--encode-ref-brackets")["bracket_refs_encoded"], 1
715
727
  )
716
728
 
729
+ def test_strip_dead_font_faces(self):
730
+ self.assertGreaterEqual(
731
+ self._fixes_for("--strip-dead-font-faces")["dead_font_faces_stripped"], 1
732
+ )
733
+
717
734
  def test_fix_container(self):
718
735
  self.assertGreaterEqual(
719
736
  self._fixes_for("--fix-container")["container_generated"], 1
@@ -59,6 +59,7 @@ DEST_TO_FIELD = {
59
59
  "strip_presentational_attrs": "presentational_attrs",
60
60
  "encode_ref_brackets": "encode_ref_brackets",
61
61
  "encode_ref_delims": "encode_ref_delims",
62
+ "strip_dead_font_faces": "strip_dead_font_faces",
62
63
  "prune_dead_spine": "prune_dead_spine",
63
64
  "strip_pagination": "strip_pagination",
64
65
  "strip_broken_tags": "strip_brokentags",
@@ -8,7 +8,7 @@ resolution-markers = [
8
8
 
9
9
  [[package]]
10
10
  name = "bindery-cli"
11
- version = "1.1.1"
11
+ version = "1.2.0"
12
12
  source = { editable = "." }
13
13
  dependencies = [
14
14
  { name = "cquarry", marker = "python_full_version >= '3.14'" },
File without changes
File without changes
File without changes
File without changes
File without changes