docling 2.94.2

DocumentConverter and format backends for docling.rs (a Rust port of docling).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Shared Office-Open-XML (OOXML) helpers for the DOCX/PPTX/XLSX backends.
//!
//! An OOXML file is a ZIP of XML "parts" plus `.rels` files that wire parts
//! together by relationship id. This module wraps the ZIP, parses relationship
//! files, resolves the (possibly `../`-relative) part paths, and counts embedded
//! pictures in a drawing part.

use std::collections::HashMap;
use std::io::{Cursor, Read};

use docling_core::PictureImage;
use quick_xml::events::Event;
use quick_xml::Reader;
use zip::ZipArchive;

/// Open a ZIP the way a well-formed one is laid out first: zip 9's default
/// `ArchiveOffset::Detect` finds the central directory by scanning the
/// whole archive forward for its signatures — ~1.5 instructions a byte, a
/// millisecond on a 3 MB DOCX, paid by every open (format sniffing, the
/// backend, the metadata read) — where a known offset of 0 checks the one
/// position the end record names. An archive that does not start at 0
/// (prepended data, a self-extracting stub) fails that check and is opened
/// again with detection, so nothing that opened before fails now.
pub(crate) fn open_zip<R: std::io::Read + std::io::Seek>(
    reader: impl Fn() -> R,
) -> zip::result::ZipResult<ZipArchive<R>> {
    let at_zero = zip::read::Config {
        archive_offset: zip::read::ArchiveOffset::Known(0),
    };
    ZipArchive::with_config(at_zero, reader()).or_else(|_| ZipArchive::new(reader()))
}

/// `xml` without its XML comments and processing instructions — docling's
/// `etree.strip_elements(root, Comment, ProcessingInstruction,
/// with_tail=False)` on each part it reads (docling#4584, #1157). The text
/// on either side joins (`<w:t>first <!-- x -->run</w:t>` reads `first
/// run`): roxmltree keeps a comment as a node of its own and `text()` returns
/// only the first text child, so the words after one were lost. The XML
/// declaration stays, CDATA sections are copied untouched, and an
/// unterminated comment or instruction is left for the parser to reject.
/// `notes` collects the comments' texts, trimmed, blank ones left out, in
/// document order (docling keeps those of the main document part as
/// notes-layer text). Borrowed when there is nothing to strip.
pub(crate) fn strip_comments_and_pis<'a>(
    xml: &'a str,
    mut notes: Option<&mut Vec<String>>,
) -> std::borrow::Cow<'a, str> {
    let is_declaration = |at: usize| {
        let rest = &xml.as_bytes()[at + 2..];
        rest.starts_with(b"xml")
            && rest
                .get(3)
                .is_some_and(|b| b.is_ascii_whitespace() || *b == b'?')
    };
    if !xml.contains("<!--") && xml.match_indices("<?").all(|(at, _)| is_declaration(at)) {
        return std::borrow::Cow::Borrowed(xml);
    }
    let mut out = String::with_capacity(xml.len());
    let (mut copied, mut at) = (0, 0);
    while let Some(off) = xml[at..].find('<') {
        let start = at + off;
        let rest = &xml[start..];
        let cut = if let Some(comment) = rest.strip_prefix("<!--") {
            let Some(end) = comment.find("-->") else {
                break;
            };
            if let Some(notes) = notes.as_deref_mut() {
                let text = comment[..end].trim();
                if !text.is_empty() {
                    notes.push(text.to_string());
                }
            }
            Some(4 + end + 3)
        } else if rest.starts_with("<![CDATA[") {
            let Some(end) = rest.find("]]>") else {
                break;
            };
            at = start + end + 3;
            continue;
        } else if rest.starts_with("<?") && !is_declaration(start) {
            let Some(end) = rest.find("?>") else {
                break;
            };
            Some(end + 2)
        } else {
            None
        };
        match cut {
            Some(len) => {
                out.push_str(&xml[copied..start]);
                copied = start + len;
                at = copied;
            }
            None => at = start + 1,
        }
    }
    out.push_str(&xml[copied..]);
    std::borrow::Cow::Owned(out)
}

/// [`strip_comments_and_pis`] over an owned part, reusing it when there is
/// nothing to strip.
pub(crate) fn strip_comments_and_pis_owned(xml: String, notes: Option<&mut Vec<String>>) -> String {
    match strip_comments_and_pis(&xml, notes) {
        std::borrow::Cow::Owned(s) => s,
        std::borrow::Cow::Borrowed(_) => xml,
    }
}

/// Hard cap on a single decompressed OOXML part (512 MiB). Real documents
/// stay far below this; the limit only exists to stop a decompression-bomb
/// part from exhausting memory. Override with `DOCLING_RS_MAX_PART_BYTES`.
pub(crate) fn max_part_bytes() -> u64 {
    docling_core::env::parse("DOCLING_RS_MAX_PART_BYTES").unwrap_or(512 * 1024 * 1024)
}

/// The package-wide limits a DOCX, PPTX or XLSX is checked against before
/// any part is read (#1163; docling's `check_archive_limits`, DOCX/XLSX
/// since docling#4977, PPTX since docling#5113): the sizes the central
/// directory declares, one member and all together, and the member count.
/// A package past one fails with the typed [`docling_core::LimitExceeded`],
/// as docling fails it with `ArchiveLimitError`. The per-part read cap
/// ([`max_part_bytes`]) still guards the bytes actually inflated, so a
/// header that understates its member cannot get past both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PackageLimits {
    /// Declared uncompressed bytes of one member (docling's
    /// `max_file_bytes`, 128 MiB).
    pub(crate) max_member_bytes: u64,
    /// Declared uncompressed bytes of all members (`max_total_bytes`,
    /// 512 MiB).
    pub(crate) max_total_bytes: u64,
    /// Members in the archive (`max_member_count`, 10 000).
    pub(crate) max_members: usize,
}

pub(crate) const OOXML_MAX_MEMBER_MB_VAR: &str = "DOCLING_RS_OOXML_MAX_MEMBER_MB";
pub(crate) const OOXML_MAX_TOTAL_MB_VAR: &str = "DOCLING_RS_OOXML_MAX_TOTAL_MB";
pub(crate) const OOXML_MAX_MEMBERS_VAR: &str = "DOCLING_RS_OOXML_MAX_MEMBERS";

impl PackageLimits {
    /// docling's defaults, each overridable: `DOCLING_RS_OOXML_MAX_MEMBER_MB`
    /// (128), `DOCLING_RS_OOXML_MAX_TOTAL_MB` (512),
    /// `DOCLING_RS_OOXML_MAX_MEMBERS` (10 000).
    pub(crate) fn from_env() -> Self {
        let mb = |var: &str, default: u64| {
            docling_core::env::parse::<u64>(var)
                .unwrap_or(default)
                .saturating_mul(1 << 20)
        };
        Self {
            max_member_bytes: mb(OOXML_MAX_MEMBER_MB_VAR, 128),
            max_total_bytes: mb(OOXML_MAX_TOTAL_MB_VAR, 512),
            max_members: docling_core::env::parse(OOXML_MAX_MEMBERS_VAR).unwrap_or(10_000),
        }
    }
}

/// A read-only view over the parts of an OOXML package.
///
/// Cloning is cheap (the file bytes are shared behind an `Arc`, the ZIP
/// central directory is reference-counted by the `zip` crate), which gives
/// each rayon worker its own independent cursor over the same archive.
///
/// `B` is the storage: the owned, shareable copy [`Package::open`] makes,
/// or the caller's own bytes for a short read ([`Package::open_slice`]).
#[derive(Clone)]
pub struct Package<B: AsRef<[u8]> = std::sync::Arc<[u8]>> {
    zip: ZipArchive<Cursor<B>>,
    /// The member paths, decoded once: zip 9 decodes a name on every
    /// `file_names()` call and hands it back as a `Result`.
    names: std::sync::Arc<[String]>,
    /// Strip XML comments and processing instructions from every part
    /// [`Self::read`] returns ([`strip_comments_and_pis`]; the DOCX
    /// backend's choice, docling#4584).
    strip_comments: bool,
    /// Conventional part name → the part the package's relationships name
    /// in its place ([`Self::follow_main_part`], #1236): `word/document.xml`
    /// read as `word/document2.xml`. Empty for nearly every package.
    aliases: std::sync::Arc<HashMap<String, String>>,
}

impl Package {
    pub fn open(bytes: &[u8]) -> Option<Self> {
        let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(bytes);
        Package::with_storage(|| bytes.clone())
    }
}

impl<'a> Package<&'a [u8]> {
    /// [`Package::open`] over the caller's bytes, without the owned copy
    /// a long-lived (or per-worker cloned) package keeps — for a read of a
    /// part or two, such as the document metadata (#679) every conversion
    /// takes: copying a 3 MB DOCX for its `docProps` cost more than reading
    /// them.
    pub fn open_slice(bytes: &'a [u8]) -> Option<Self> {
        Package::with_storage(|| bytes)
    }
}

impl<B: AsRef<[u8]>> Package<B> {
    fn with_storage(storage: impl Fn() -> B) -> Option<Self> {
        let zip = open_zip(|| Cursor::new(storage())).ok()?;
        let names = zip
            .file_names()
            .filter_map(Result::ok)
            .map(|n| n.into_owned())
            .collect();
        Some(Self {
            zip,
            names,
            strip_comments: false,
            aliases: Default::default(),
        })
    }

    /// The package's member paths, in central-directory order (a name that
    /// is neither UTF-8 nor CP437 is left out).
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.names.iter().map(String::as_str)
    }

    /// Check the package against `limits` from its central directory alone
    /// — nothing is inflated ([`PackageLimits`]).
    pub(crate) fn check_limits(
        &mut self,
        limits: &PackageLimits,
    ) -> Result<(), docling_core::LimitExceeded> {
        let to_usize = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
        let members = self.zip.len();
        if members > limits.max_members {
            return Err(docling_core::LimitExceeded {
                variable: OOXML_MAX_MEMBERS_VAR,
                limit: limits.max_members,
                actual: members,
                what: "the package".into(),
            });
        }
        let mut total = 0u64;
        for i in 0..members {
            let Ok(file) = self.zip.by_index_raw(i) else {
                continue;
            };
            let size = file.size();
            if size > limits.max_member_bytes {
                let name = file.name().map(|n| n.into_owned()).unwrap_or_default();
                return Err(docling_core::LimitExceeded {
                    variable: OOXML_MAX_MEMBER_MB_VAR,
                    limit: to_usize(limits.max_member_bytes),
                    actual: to_usize(size),
                    what: format!("member {name}"),
                });
            }
            total = total.saturating_add(size);
            if total > limits.max_total_bytes {
                return Err(docling_core::LimitExceeded {
                    variable: OOXML_MAX_TOTAL_MB_VAR,
                    limit: to_usize(limits.max_total_bytes),
                    actual: to_usize(total),
                    what: "the package's members together".into(),
                });
            }
        }
        Ok(())
    }

    /// Whether any member cannot be read because it is encrypted — docling's
    /// `is_encrypted` for iWork packages. Standard ZIP encryption sets bit 0
    /// of the general-purpose flags; Pages does not use that: it leaves the
    /// flag clear and writes a compression method outside the set ZIP defines
    /// (stored, deflate, bzip2 = 12, lzma = 14), so both signals are needed.
    /// Reads only the central directory — no member is decompressed.
    #[allow(deprecated)] // `CompressionMethod::Unsupported` is how `zip` reports methods it lacks a codec for
    pub fn any_encrypted(&mut self) -> bool {
        use zip::CompressionMethod;
        (0..self.zip.len()).any(|i| match self.zip.by_index_raw(i) {
            Ok(file) => {
                let readable = matches!(
                    file.compression(),
                    CompressionMethod::Stored
                        | CompressionMethod::Deflated
                        | CompressionMethod::Unsupported(12)
                        | CompressionMethod::Unsupported(14)
                );
                file.encrypted() || !readable
            }
            Err(_) => false,
        })
    }

    /// Read a part to a string, or `None` if it is absent, not valid UTF-8, or
    /// nested deeper than the XML guard allows (see [`super::xml_depth`]; the
    /// part is reported and skipped, like an unreadable one).
    pub fn read(&mut self, path: &str) -> Option<String> {
        let bytes = self.read_bytes(path)?;
        let text = String::from_utf8(bytes).ok()?;
        if let Err(e) = super::xml_depth::check(&text, path) {
            eprintln!("docling: {e}; part skipped");
            return None;
        }
        Some(if self.strip_comments {
            strip_comments_and_pis_owned(text, None)
        } else {
            text
        })
    }

    /// From now on, strip XML comments and processing instructions from
    /// every part [`Self::read`] returns.
    pub fn strip_comments_and_pis(&mut self) {
        self.strip_comments = true;
    }

    /// Read a part's raw bytes (e.g. an embedded image), or `None` if absent.
    ///
    /// A single part is never allowed to inflate past [`max_part_bytes`]: an
    /// OOXML file is a ZIP, and a "zip bomb" part (a few KB deflating to many
    /// GB) would otherwise exhaust memory and abort the process. Reads stop at
    /// the cap and the oversized part is rejected (`None`) rather than
    /// truncated, so a partial part never reaches an XML parser.
    pub fn read_bytes(&mut self, path: &str) -> Option<Vec<u8>> {
        self.read_bytes_capped(path, max_part_bytes())
    }

    fn read_bytes_capped(&mut self, path: &str, cap: u64) -> Option<Vec<u8>> {
        let aliases = self.aliases.clone();
        let path = aliases.get(path).map_or(path, String::as_str);
        let file = self.zip.by_name(path).ok()?;
        // Reject up front when the central directory already advertises an
        // oversized part; still cap the actual read in case the header lies.
        if file.size() > cap {
            return None;
        }
        let mut out = Vec::new();
        // read_to_end on a `.take(cap + 1)` reader: if it returns cap+1 bytes,
        // the part exceeded the cap and is rejected rather than truncated.
        file.take(cap + 1).read_to_end(&mut out).ok()?;
        if out.len() as u64 > cap {
            return None;
        }
        Some(out)
    }

    /// Map each `/image` relationship id of `part` to its extracted
    /// [`PictureImage`] (`base_dir` is the part's directory for resolving
    /// targets, e.g. `word` / `ppt`). Unreadable or undecodable images are skipped.
    pub fn image_rels(&mut self, part: &str, base_dir: &str) -> HashMap<String, PictureImage> {
        let rels = self.rels_for(part);
        let mut out = HashMap::new();
        for r in &rels {
            if !r.rel_type.ends_with("/image") {
                continue;
            }
            let path = resolve(base_dir, &r.target);
            if let Some(bytes) = self.read_bytes(&path) {
                if let Some(img) = picture_image(&path, bytes) {
                    out.insert(r.id.clone(), img);
                }
            }
        }
        out
    }

    /// The `.rels` file governing `part` (e.g. `xl/worksheets/sheet1.xml` →
    /// `xl/worksheets/_rels/sheet1.xml.rels`), parsed into relationships.
    pub fn rels_for(&mut self, part: &str) -> Vec<Relationship> {
        // An aliased part's relationships are its own: `document2.xml.rels`.
        let aliases = self.aliases.clone();
        let part = aliases.get(part).map_or(part, String::as_str);
        let (dir, file) = split_path(part);
        let rels_path = if dir.is_empty() {
            format!("_rels/{file}.rels")
        } else {
            format!("{dir}/_rels/{file}.rels")
        };
        self.read(&rels_path)
            .map(|x| parse_rels(&x))
            .unwrap_or_default()
    }
}

impl<B: AsRef<[u8]>> Package<B> {
    /// Whether the package has a member named `path` (no alias applied).
    fn has_member(&self, path: &str) -> bool {
        self.names.iter().any(|n| n == path)
    }

    /// The package's main part (#1236): the target of the root
    /// `_rels/.rels` relationship of type `…/officeDocument` (transitional
    /// or strict, ECMA-376 Part 2 — the Open Packaging Conventions name the
    /// main part by relationship, not by a fixed name), when that member
    /// exists. `None` when the package has no such relationship or its
    /// target is missing.
    pub fn main_part(&mut self) -> Option<String> {
        let rels = self.read_bytes("_rels/.rels")?;
        let rels = String::from_utf8_lossy(&rels);
        main_part_target(&rels).filter(|t| self.has_member(t))
    }

    /// Read the package's main part under its `conventional` name
    /// (`word/document.xml`, `ppt/presentation.xml`, `xl/workbook.xml`) when
    /// the root relationships name another one (#1236: real-world DOCX
    /// files whose main part is `word/document2.xml`; mammoth and
    /// python-docx resolve the relationship). The backends then read the
    /// conventional name — and its `_rels/<name>.rels` — unchanged.
    ///
    /// `related` lists the main part's own relationship types (suffixes
    /// such as `/styles`) with their conventional names: each one that
    /// names another part is aliased the same way (`styles2.xml`). The
    /// relationship wins over a conventional member that also exists (a
    /// stale `word/document.xml` the package no longer points at); a
    /// package whose main part sits at the conventional name is read
    /// exactly as before. Relative
    /// targets still resolve against the backends' conventional directory
    /// (`word/`): a main part in another directory is read, but parts its
    /// relationships name relative to that directory may not be.
    pub fn follow_main_part(&mut self, conventional: &str, related: &[(&str, &str)]) {
        let Some(main) = self.main_part() else {
            return;
        };
        if main == conventional {
            return;
        }
        let mut aliases = HashMap::new();
        aliases.insert(conventional.to_string(), main.clone());
        let (dir, _) = split_path(&main);
        let dir = dir.to_string();
        self.aliases = std::sync::Arc::new(aliases.clone());
        for rel in self.rels_for(conventional) {
            let Some((_, name)) = related
                .iter()
                .find(|(suffix, _)| rel.rel_type.ends_with(suffix))
            else {
                continue;
            };
            let target = resolve(&dir, &rel.target);
            if target != *name && self.has_member(&target) {
                aliases.entry(name.to_string()).or_insert(target);
            }
        }
        self.aliases = std::sync::Arc::new(aliases);
    }
}

/// The `…/officeDocument` relationship's target in a root `_rels/.rels`,
/// as a package path (no leading `/`) — [`Package::main_part`].
pub(crate) fn main_part_target(root_rels_xml: &str) -> Option<String> {
    parse_rels(root_rels_xml)
        .into_iter()
        .find(|r| r.rel_type.ends_with("/officeDocument"))
        .map(|r| resolve("", &r.target))
        .filter(|t| !t.is_empty())
}

/// A single `<Relationship Id Type Target>` entry from a `.rels` part.
pub struct Relationship {
    pub id: String,
    pub rel_type: String,
    pub target: String,
}

/// Parse a `.rels` XML document into its relationships.
pub fn parse_rels(xml: &str) -> Vec<Relationship> {
    let mut reader = Reader::from_str(xml);
    let mut buf = Vec::new();
    let mut out = Vec::new();
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(e)) | Ok(Event::Start(e)) if e.name().as_ref() == b"Relationship" => {
                let (mut id, mut rel_type, mut target) =
                    (String::new(), String::new(), String::new());
                for attr in e.attributes().flatten() {
                    let value = String::from_utf8_lossy(attr.value.as_ref()).into_owned();
                    match attr.key.as_ref() {
                        b"Id" => id = value,
                        b"Type" => rel_type = value,
                        b"Target" => target = value,
                        _ => {}
                    }
                }
                out.push(Relationship {
                    id,
                    rel_type,
                    target,
                });
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buf.clear();
    }
    out
}

/// Split a part path into its directory and file name.
fn split_path(path: &str) -> (&str, &str) {
    match path.rfind('/') {
        Some(i) => (&path[..i], &path[i + 1..]),
        None => ("", path),
    }
}

/// Resolve a relationship `target` against the directory of the part that owns
/// the `.rels`, collapsing `.` / `..` segments. A leading `/` is package-absolute.
pub fn resolve(base_dir: &str, target: &str) -> String {
    if let Some(abs) = target.strip_prefix('/') {
        return abs.to_string();
    }
    let mut parts: Vec<&str> = base_dir.split('/').filter(|p| !p.is_empty()).collect();
    for seg in target.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }
    parts.join("/")
}

/// Build a [`PictureImage`] from image bytes, reading the pixel size from the
/// header (decode-free). A Windows metafile (EMF/WMF), which the `image`
/// crate cannot read, is rendered to PNG instead (#536); `None` for anything
/// else it can't read.
pub fn picture_image(path: &str, data: Vec<u8>) -> Option<PictureImage> {
    let dims = image::ImageReader::new(Cursor::new(&data))
        .with_guessed_format()
        .ok()
        .and_then(|r| r.into_dimensions().ok());
    let Some((width, height)) = dims else {
        return super::metafile::render(&data, None);
    };
    Some(PictureImage {
        dpi: PictureImage::DEFAULT_DPI,
        mimetype: mime_for(path).to_string(),
        width,
        height,
        data,
        display_size: None,
    })
}

/// Whether an embedded picture is a Windows metafile — a placeable WMF (its
/// `9AC6CDD7` key) or an EMF (`" EMF"` at byte 40) — docling's `_is_metafile`.
/// Pillow cannot decode either off Windows, and upstream keeps such a picture
/// (payload-less, unless LibreOffice renders it) where any other undecodable
/// image is dropped.
pub fn is_metafile(data: &[u8]) -> bool {
    data.starts_with(&[0xd7, 0xcd, 0xc6, 0x9a]) || data.get(40..44) == Some(b" EMF")
}

/// PIL's `Image.info["dpi"]` (its horizontal value) for an embedded picture,
/// read the way Pillow reads it ([`docling_core::image_dpi::resolution`]: a
/// PNG `pHYs` chunk, a JPEG's JFIF density else its EXIF resolution, a BMP's
/// pixels per metre, a TIFF's resolution tags). `None` when the format
/// records none (GIF, WebP, a PNG without `pHYs`): python-pptx's `Image.dpi`
/// then reports 72, and docling's `ImageRef.dpi` follows it.
pub fn image_dpi(data: &[u8]) -> Option<f64> {
    docling_core::image_dpi::resolution(data).map(|(x, _)| x)
}

fn mime_for(path: &str) -> &'static str {
    match path
        .rsplit('.')
        .next()
        .unwrap_or("")
        .to_ascii_lowercase()
        .as_str()
    {
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "bmp" => "image/bmp",
        "tif" | "tiff" => "image/tiff",
        "webp" => "image/webp",
        _ => "image/png",
    }
}

/// The content type of a package part, resolved from `[Content_Types].xml`
/// (an exact `<Override PartName>` wins over a `<Default Extension>`).
pub fn content_type(content_types_xml: &str, part: &str) -> Option<String> {
    let mut reader = Reader::from_str(content_types_xml);
    let mut buf = Vec::new();
    let want_part = format!("/{}", part.trim_start_matches('/'));
    let ext = part.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
    let mut default: Option<String> = None;
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Empty(e)) | Ok(Event::Start(e)) => {
                let tag = e.name();
                let attr = |key: &[u8]| -> Option<String> {
                    e.attributes()
                        .flatten()
                        .find(|a| a.key.as_ref() == key)
                        .map(|a| String::from_utf8_lossy(a.value.as_ref()).into_owned())
                };
                match tag.as_ref() {
                    b"Override" => {
                        if attr(b"PartName").as_deref() == Some(want_part.as_str()) {
                            return attr(b"ContentType");
                        }
                    }
                    b"Default"
                        if attr(b"Extension")
                            .map(|x| x.to_ascii_lowercase())
                            .as_deref()
                            == Some(ext.as_str()) =>
                    {
                        default = attr(b"ContentType");
                    }
                    _ => {}
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
        buf.clear();
    }
    default
}

#[cfg(test)]
mod zip_bomb_tests {
    use super::Package;
    use std::io::Write;

    /// A minimal in-memory OOXML-style zip with one part of `part_len` bytes.
    fn zip_with_part(name: &str, part_len: usize) -> Vec<u8> {
        let mut buf = std::io::Cursor::new(Vec::new());
        {
            let mut zw = zip::ZipWriter::new(&mut buf);
            let opts = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Deflated);
            zw.start_file(name, opts).unwrap();
            zw.write_all(&vec![b'a'; part_len]).unwrap();
            zw.finish().unwrap();
        }
        buf.into_inner()
    }

    #[test]
    fn oversized_part_is_rejected_not_truncated() {
        // A highly compressible 1 MiB part in a tiny zip (deflates to ~1 KB):
        // the decompression-bomb shape. With the cap below its size, the read
        // must return None rather than a truncated buffer.
        let bytes = zip_with_part("word/document.xml", 1024 * 1024);
        assert!(bytes.len() < 64 * 1024, "part should compress tiny");
        let mut pkg = Package::open(&bytes).unwrap();
        assert!(
            pkg.read_bytes_capped("word/document.xml", 4096).is_none(),
            "a part over the cap must be rejected"
        );
        // Under a generous cap it reads back in full.
        let out = pkg
            .read_bytes_capped("word/document.xml", 8 * 1024 * 1024)
            .expect("part under the cap reads");
        assert_eq!(out.len(), 1024 * 1024);
    }
}

#[cfg(test)]
pub(crate) mod image_dpi_tests {
    use super::{image_dpi, is_metafile};

    /// A PNG of `chunks` (length + type + data + a zero CRC, which the reader
    /// never checks).
    pub(crate) fn png(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> {
        let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
        for (kind, data) in chunks {
            out.extend((data.len() as u32).to_be_bytes());
            out.extend(*kind);
            out.extend(data);
            out.extend([0; 4]);
        }
        out
    }

    fn phys(ppu: u32, unit: u8) -> Vec<u8> {
        let mut d = ppu.to_be_bytes().to_vec();
        d.extend(ppu.to_be_bytes());
        d.push(unit);
        d
    }

    /// Pillow: a `pHYs` in metres is `px * 0.0254` dpi; an aspect-only one
    /// (unit 0) or no chunk at all records no dpi.
    #[test]
    fn png_phys_in_metres_is_dpi() {
        let ihdr = (b"IHDR", vec![0; 13]);
        let dpi = image_dpi(&png(&[
            ihdr.clone(),
            (b"pHYs", phys(11811, 1)),
            (b"IEND", vec![]),
        ]));
        assert!((dpi.unwrap() - 299.9994).abs() < 1e-4, "{dpi:?}");
        assert_eq!(
            image_dpi(&png(&[ihdr.clone(), (b"pHYs", phys(1, 0))])),
            None
        );
        assert_eq!(
            image_dpi(&png(&[ihdr, (b"IDAT", vec![0]), (b"IEND", vec![])])),
            None
        );
    }

    fn jpeg(segments: &[(u8, Vec<u8>)]) -> Vec<u8> {
        let mut out = vec![0xff, 0xd8];
        for (marker, payload) in segments {
            out.extend([0xff, *marker]);
            out.extend((payload.len() as u16 + 2).to_be_bytes());
            out.extend(payload);
        }
        out.extend([0xff, 0xda, 0, 2]);
        out
    }

    fn jfif(unit: u8, density: u16) -> Vec<u8> {
        let mut d = b"JFIF\0\x01\x01".to_vec();
        d.push(unit);
        d.extend(density.to_be_bytes());
        d.extend(density.to_be_bytes());
        d.extend([0, 0]);
        d
    }

    /// Little-endian TIFF with `XResolution = num/den` and, optionally,
    /// `ResolutionUnit`.
    fn tiff(num: u32, den: u32, unit: Option<u16>) -> Vec<u8> {
        let mut t = b"II*\0".to_vec();
        t.extend(8u32.to_le_bytes());
        let n: u16 = if unit.is_some() { 2 } else { 1 };
        t.extend(n.to_le_bytes());
        let rational_at = 8 + 2 + 12 * u32::from(n) + 4;
        t.extend(0x011au16.to_le_bytes());
        t.extend(5u16.to_le_bytes());
        t.extend(1u32.to_le_bytes());
        t.extend(rational_at.to_le_bytes());
        if let Some(u) = unit {
            t.extend(0x0128u16.to_le_bytes());
            t.extend(3u16.to_le_bytes());
            t.extend(1u32.to_le_bytes());
            t.extend(u.to_le_bytes());
            t.extend([0, 0]);
        }
        t.extend(0u32.to_le_bytes()); // next IFD
        t.extend(num.to_le_bytes());
        t.extend(den.to_le_bytes());
        t
    }

    /// Pillow: the JFIF density in inches or centimetres; with no JFIF unit,
    /// the EXIF `XResolution` (centimetres × 2.54), 72 when the EXIF lacks
    /// the tags; nothing at all when neither segment says.
    #[test]
    fn jpeg_density_from_jfif_then_exif() {
        assert_eq!(image_dpi(&jpeg(&[(0xe0, jfif(1, 96))])), Some(96.0));
        let dpcm = image_dpi(&jpeg(&[(0xe0, jfif(2, 118))])).unwrap();
        assert!((dpcm - 299.72).abs() < 1e-9);
        let mut exif = b"Exif\0\0".to_vec();
        exif.extend(tiff(300, 1, Some(2)));
        assert_eq!(
            image_dpi(&jpeg(&[(0xe0, jfif(0, 1)), (0xe1, exif)])),
            Some(300.0)
        );
        let mut exif_cm = b"Exif\0\0".to_vec();
        exif_cm.extend(tiff(100, 1, Some(3)));
        assert_eq!(image_dpi(&jpeg(&[(0xe1, exif_cm)])), Some(254.0));
        let mut exif_bare = b"Exif\0\0".to_vec();
        exif_bare.extend(tiff(300, 1, None));
        assert_eq!(
            image_dpi(&jpeg(&[(0xe1, exif_bare)])),
            Some(72.0),
            "no unit tag → Pillow's 72"
        );
        assert_eq!(image_dpi(&jpeg(&[(0xe0, jfif(0, 1))])), None);
        // A JFIF density beats a later EXIF, an earlier EXIF yields to it.
        let mut exif = b"Exif\0\0".to_vec();
        exif.extend(tiff(300, 1, Some(2)));
        assert_eq!(
            image_dpi(&jpeg(&[(0xe1, exif.clone()), (0xe0, jfif(1, 96))])),
            Some(96.0)
        );
    }

    /// A BMP's pixels per metre ÷ 39.3701; a TIFF's resolution in inches (unit
    /// 2 or none), centimetres (3), or none at all (1).
    #[test]
    fn bmp_and_tiff_resolutions() {
        let mut bmp = vec![0u8; 54];
        bmp[..2].copy_from_slice(b"BM");
        bmp[14..18].copy_from_slice(&40u32.to_le_bytes());
        bmp[38..42].copy_from_slice(&11811i32.to_le_bytes());
        assert!((image_dpi(&bmp).unwrap() - 299.9992).abs() < 1e-3);
        assert_eq!(image_dpi(&tiff(200, 1, Some(2))), Some(200.0));
        assert_eq!(image_dpi(&tiff(200, 1, None)), Some(200.0));
        assert_eq!(image_dpi(&tiff(100, 1, Some(3))), Some(254.0));
        assert_eq!(image_dpi(&tiff(100, 1, Some(1))), None);
        assert_eq!(image_dpi(b"GIF89a"), None);
    }

    /// docling's `_is_metafile`: a placeable WMF key or an EMF signature at 40.
    #[test]
    fn metafiles_by_signature() {
        assert!(is_metafile(&[0xd7, 0xcd, 0xc6, 0x9a, 0, 0]));
        let mut emf = vec![1u8; 44];
        emf[40..44].copy_from_slice(b" EMF");
        assert!(is_metafile(&emf));
        assert!(!is_metafile(b"\x89PNG\r\n\x1a\n"));
        assert!(!is_metafile(&[]));
    }
}

/// A picture's author-written alt text (#676): the `descr` (else `title`)
/// attribute of its non-visual properties — `wp:docPr` of a DOCX drawing,
/// `p:cNvPr` of a PPTX picture, `xdr:cNvPr` of a spreadsheet drawing —
/// trimmed; `None` when both are missing or blank. Office writes `descr`
/// (the "Alt Text" box; its generated captions read "… Description
/// automatically generated") and older documents `title`.
pub(crate) fn alt_text_of(props: roxmltree::Node) -> Option<String> {
    ["descr", "title"].iter().find_map(|name| {
        props
            .attributes()
            .find(|a| a.name() == *name)
            .map(|a| a.value().trim())
            .filter(|v| !v.is_empty())
            .map(str::to_string)
    })
}

/// #1163 (docling#5113 / docling#4977, `test_backend_archive_limits.py`):
/// the package-wide limits of a DOCX, PPTX or XLSX.
#[cfg(test)]
mod package_limit_tests {
    use super::{Package, PackageLimits};
    use crate::backend::DeclarativeBackend;
    use crate::format::InputFormat;
    use crate::source::SourceDocument;
    use std::io::Write;

    fn fixture(rel: &str) -> Vec<u8> {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data");
        std::fs::read(root.join(rel)).expect(rel)
    }

    const FIXTURES: [(&str, &str); 3] = [
        ("docx/sources/Transitional.docx", "word/document.xml"),
        (
            "pptx/sources/powerpoint_sample.pptx",
            "ppt/slides/slide1.xml",
        ),
        ("xlsx/sources/xlsx_01.xlsx", "xl/worksheets/sheet1.xml"),
    ];

    #[test]
    fn upstream_fixtures_are_within_the_default_limits() {
        for (rel, _) in FIXTURES {
            let mut pkg = Package::open(&fixture(rel)).unwrap();
            assert_eq!(
                pkg.check_limits(&PackageLimits::from_env()),
                Ok(()),
                "{rel}"
            );
        }
    }

    #[test]
    fn a_member_over_the_limit_is_named() {
        for (rel, member) in FIXTURES {
            let bytes = fixture(rel);
            let mut pkg = Package::open(&bytes).unwrap();
            let size = {
                let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
                let size = zip.by_name(member).unwrap().size();
                size
            };
            // A limit just under that member's size, high enough for every
            // member before it in the archive.
            let largest_other = {
                let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
                let mut best = 0;
                for i in 0..zip.len() {
                    let f = zip.by_index_raw(i).unwrap();
                    if f.name().unwrap() != member {
                        best = best.max(f.size());
                    }
                }
                best
            };
            if largest_other >= size {
                continue; // another member is the largest; covered below
            }
            let limits = PackageLimits {
                max_member_bytes: size - 1,
                max_total_bytes: u64::MAX,
                max_members: usize::MAX,
            };
            let err = pkg.check_limits(&limits).unwrap_err();
            assert_eq!(err.variable, super::OOXML_MAX_MEMBER_MB_VAR, "{rel}");
            assert_eq!(err.what, format!("member {member}"), "{rel}");
            assert_eq!(err.actual, size as usize);
            assert!(err.to_string().contains("bytes exceeds the limit"), "{err}");
        }
        // Whatever the largest member, a 1-byte cap names one, and a total
        // cap under the package's size fails the package.
        for (rel, _) in FIXTURES {
            let mut pkg = Package::open(&fixture(rel)).unwrap();
            let one = PackageLimits {
                max_member_bytes: 1,
                max_total_bytes: u64::MAX,
                max_members: usize::MAX,
            };
            let err = pkg.check_limits(&one).unwrap_err();
            assert!(err.what.starts_with("member "), "{rel}: {err}");
            let total = PackageLimits {
                max_member_bytes: u64::MAX,
                max_total_bytes: 1024,
                max_members: usize::MAX,
            };
            let err = pkg.check_limits(&total).unwrap_err();
            assert_eq!(err.variable, super::OOXML_MAX_TOTAL_MB_VAR, "{rel}");
        }
    }

    /// A package of 10 001 members fails every OOXML backend with the typed
    /// limit, before any part is parsed.
    #[test]
    fn too_many_members_fail_the_conversion() {
        let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let opts = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        for i in 0..10_001 {
            zw.start_file(format!("m/{i}.xml"), opts).unwrap();
            zw.write_all(b"<a/>").unwrap();
        }
        let bytes = zw.finish().unwrap().into_inner();
        let backends: [(InputFormat, &str, Box<dyn DeclarativeBackend>); 3] = [
            (
                InputFormat::Docx,
                "t.docx",
                Box::new(crate::backend::DocxBackend::default()),
            ),
            (
                InputFormat::Pptx,
                "t.pptx",
                Box::new(crate::backend::PptxBackend),
            ),
            (
                InputFormat::Xlsx,
                "t.xlsx",
                Box::new(crate::backend::XlsxBackend::default()),
            ),
        ];
        for (format, name, backend) in backends {
            let src = SourceDocument::from_bytes(name, format, bytes.clone());
            let err = backend.convert(&src).unwrap_err();
            let limit = err.limit().unwrap_or_else(|| panic!("{name}: {err}"));
            assert_eq!(limit.variable, super::OOXML_MAX_MEMBERS_VAR);
            assert_eq!((limit.limit, limit.actual), (10_000, 10_001));
            assert!(err.to_string().contains("10001 members exceeds"), "{err}");
        }
    }
}