xberg 1.1.1

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
//! Hangul Word Processor XML (.hwpx) extractor.
//!
//! Extracts text, headings, tables, and images from HWPX documents using the `unhwp` crate.

use std::borrow::Cow;
use std::io::{Cursor, Read, Seek};

use ahash::AHashMap;
use async_trait::async_trait;
use bytes::Bytes;

use crate::Result;
use crate::core::config::ExtractionConfig;
use crate::extractors::security::ZipBombValidator;
use crate::plugins::{InternalDocumentExtractor, Plugin};
use crate::types::ExtractedImage;
use crate::types::document_structure::{AnnotationKind, ContentLayer, TextAnnotation};
use crate::types::internal::InternalDocument;
use crate::types::internal_builder::InternalDocumentBuilder;

/// `ProcessingWarning::source` for every warning this extractor emits (#171).
const HWPX_WARNING_SOURCE: &str = "hwpx";

/// Maximum bytes read from a single HWPX zip member's section XML.
///
/// `ZipBombValidator::validate` (called before any member is read) only checks
/// the *declared* compressed/uncompressed sizes and ratio from the zip central
/// directory -- it never decompresses. A crafted entry can under-declare its
/// size while its deflate stream expands far past that declaration, so the
/// entry's declared size cannot be trusted as an upper bound on what reading it
/// actually produces. Bounding the read itself with `Read::take` (the same
/// pattern as `odt::MAX_ODT_MEMBER_SIZE`) is what actually caps memory.
const MAX_HWPX_MEMBER_SIZE: u64 = 100 * 1024 * 1024;

/// Extractor for Hangul Word Processor XML (.hwpx) files.
///
/// Supports HWPX (Open HWPML), the ZIP-based XML successor to the binary HWP 5.0 format.
#[cfg_attr(alef, alef(skip))]
pub struct HwpxExtractor;

impl HwpxExtractor {
    pub(crate) fn new() -> Self {
        Self
    }
}

impl Default for HwpxExtractor {
    fn default() -> Self {
        Self::new()
    }
}

impl Plugin for HwpxExtractor {
    fn name(&self) -> &str {
        "hwpx-extractor"
    }

    fn version(&self) -> String {
        env!("CARGO_PKG_VERSION").to_string()
    }

    fn initialize(&self) -> Result<()> {
        Ok(())
    }

    fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    fn description(&self) -> &str {
        "Hangul Word Processor XML (.hwpx) text extraction"
    }

    fn author(&self) -> &str {
        "Xberg Team"
    }
}

fn mime_to_format(mime: &str) -> Cow<'static, str> {
    match mime {
        "image/png" => Cow::Borrowed("png"),
        "image/jpeg" | "image/jpg" => Cow::Borrowed("jpeg"),
        "image/gif" => Cow::Borrowed("gif"),
        "image/bmp" => Cow::Borrowed("bmp"),
        "image/webp" => Cow::Borrowed("webp"),
        // HWPX embeds vector/legacy Windows metafiles (WMF/EMF) and SVG far more often
        // than other office formats — `unhwp`'s resource guesser (hwpx/mod.rs
        // `guess_mime_type`) returns these three MIME strings, and previously every one
        // of them fell through to the generic "bin" bucket, discarding the real format
        // (#120).
        "image/svg+xml" => Cow::Borrowed("svg"),
        "image/x-wmf" => Cow::Borrowed("wmf"),
        "image/x-emf" => Cow::Borrowed("emf"),
        _ => Cow::Borrowed("bin"),
    }
}

/// Collect the LaTeX of every equation, one `Vec` per section, in document order.
///
/// `unhwp` reads an equation only when it sits in a paragraph-level `<hp:ctrl>`;
/// its run reader drops `<hp:equation>`. Hangul writes the equation into the run,
/// so a real document loses every formula. Reading the section XML through the
/// crate's own container keeps the archive, the section order and the script
/// conversion with `unhwp`, and adds only the search for one element.
/// Collect the LaTeX of every equation, keyed by section index and by the
/// ordinal of the paragraph that holds it.
///
/// `unhwp` reads an equation only when it sits in a paragraph-level `<hp:ctrl>`;
/// its run reader drops `<hp:equation>`. Hangul writes the equation into the run,
/// so a real document loses every formula. This walks the section parts of the
/// archive the caller already opened, so the file is neither copied nor
/// decompressed a second time, and `unhwp` keeps the script conversion.
///
/// A paragraph inside a table is not counted: `unhwp` keeps those in the cell
/// rather than in the section's block list, so counting them would shift every
/// later ordinal.
fn collect_section_formulas<R: Read + Seek>(archive: &mut zip::ZipArchive<R>) -> AHashMap<usize, Vec<(usize, String)>> {
    use crate::utils::xml_utils::EntityReader;
    use quick_xml::events::Event;

    // `unhwp` numbers a section by its position in the list it reads, not by the
    // digits in its name, so the key is the position here too. A package whose
    // parts are `section0` and `section2` gives positions 0 and 1 on both sides.
    let mut section_parts: Vec<(usize, String)> = archive
        .file_names()
        .filter_map(|name| section_index_of(name).map(|digits| (digits, name.to_string())))
        .collect();
    section_parts.sort();
    let section_parts: Vec<(usize, String)> = section_parts
        .into_iter()
        .enumerate()
        .map(|(position, (_, name))| (position, name))
        .collect();

    let mut per_section: AHashMap<usize, Vec<(usize, String)>> = AHashMap::new();
    for (section_index, name) in section_parts {
        let mut xml = String::new();
        if archive
            .by_name(&name)
            .ok()
            .and_then(|part| part.take(MAX_HWPX_MEMBER_SIZE).read_to_string(&mut xml).ok())
            .is_none()
        {
            continue;
        }

        let mut formulas: Vec<(usize, String)> = Vec::new();
        // `EntityReader` resolves `&amp;` and friends into the text it returns. A
        // bare reader emits them as separate events, and an equation script uses
        // `&` as its matrix column separator.
        let mut reader = EntityReader::from_str(&xml);
        let mut paragraph_ordinal = 0usize;
        let mut paragraph_depth = 0usize;
        let mut table_depth = 0usize;
        let mut in_equation = false;
        let mut in_script = false;
        let mut script = String::new();
        loop {
            match reader.read_event() {
                Ok(Event::Start(e)) => match local_name(e.name().as_ref()) {
                    "tbl" => table_depth += 1,
                    "p" if table_depth == 0 => paragraph_depth += 1,
                    "equation" | "eqEdit" => in_equation = true,
                    "script" if in_equation => in_script = true,
                    _ => {}
                },
                Ok(Event::Text(t)) if in_script => {
                    script.push_str(&std::borrow::Cow::Borrowed(t.as_ref()));
                }
                Ok(Event::End(e)) => match local_name(e.name().as_ref()) {
                    "tbl" => table_depth = table_depth.saturating_sub(1),
                    "p" if table_depth == 0 => {
                        paragraph_depth = paragraph_depth.saturating_sub(1);
                        if paragraph_depth == 0 {
                            paragraph_ordinal += 1;
                        }
                    }
                    "script" => in_script = false,
                    "equation" | "eqEdit" => {
                        let latex = unhwp::equation::to_latex(std::mem::take(&mut script).trim());
                        if !latex.trim().is_empty() {
                            formulas.push((paragraph_ordinal, latex.trim().to_string()));
                        }
                        in_equation = false;
                    }
                    _ => {}
                },
                Ok(Event::Eof) | Err(_) => break,
                _ => {}
            }
        }
        if !formulas.is_empty() {
            per_section.insert(section_index, formulas);
        }
    }
    per_section
}

/// Return the number in a section part's name, so `Contents/section3.xml`
/// gives `3`.
///
/// The number orders the parts. It is not the key: `unhwp` numbers a section by
/// its position in the list it reads, and a package may skip a number.
fn section_index_of(name: &str) -> Option<usize> {
    let file = name.rsplit('/').next()?;
    let digits = file.strip_prefix("section")?.strip_suffix(".xml")?;
    digits.parse().ok()
}

/// Return the local part of a possibly prefixed XML qualified name.
fn local_name(qname: &str) -> &str {
    match qname.rsplit_once(':') {
        Some((_, local)) => local,
        None => qname,
    }
}

fn build_hwpx_internal_document(
    doc: unhwp::model::Document,
    mime_type: &str,
    section_formulas: &AHashMap<usize, Vec<(usize, String)>>,
) -> InternalDocument {
    let mut builder = InternalDocumentBuilder::new("hwpx");
    builder.set_mime_type(Cow::Owned(mime_type.to_string()));

    let mut metadata = crate::types::metadata::Metadata::default();
    if let Some(title) = &doc.metadata.title {
        metadata.title = Some(title.clone());
    }
    if let Some(author) = &doc.metadata.author {
        metadata.authors = Some(vec![author.clone()]);
    }
    if let Some(subject) = &doc.metadata.subject {
        metadata.subject = Some(subject.clone());
    }
    if !doc.metadata.keywords.is_empty() {
        metadata.keywords = Some(doc.metadata.keywords.clone());
    }
    if let Some(created) = &doc.metadata.created {
        metadata.created_at = Some(created.clone());
    }
    if let Some(modified) = &doc.metadata.modified {
        metadata.modified_at = Some(modified.clone());
    }
    if let Some(creator_app) = &doc.metadata.creator_app {
        metadata.additional.insert(
            Cow::Borrowed("creator_app"),
            serde_json::Value::String(creator_app.clone()),
        );
    }
    if let Some(version) = &doc.metadata.format_version {
        metadata.document_version = Some(version.clone());
    }
    if !metadata.is_empty() {
        builder.set_metadata(metadata);
    }

    let mut image_index: usize = 0;
    let mut footnote_counter: u32 = 0;

    for section in &doc.sections {
        // Key on the section's own index. `unhwp` drops a section it cannot
        // read, so a position in the list does not identify the part.
        let scanned = section_formulas.get(&section.index);
        let mut next_formula = 0usize;
        let mut paragraph_ordinal = 0usize;
        // Section headers/footers (`unhwp::model::Section::header`/`footer`) previously
        // went unread entirely — only `section.content` was visited (#96). ~keep
        if let Some(header_paragraphs) = &section.header {
            push_header_footer_paragraphs(
                &mut builder,
                header_paragraphs,
                ContentLayer::Header,
                &mut footnote_counter,
            );
        }
        if let Some(footer_paragraphs) = &section.footer {
            push_header_footer_paragraphs(
                &mut builder,
                footer_paragraphs,
                ContentLayer::Footer,
                &mut footnote_counter,
            );
        }

        for block in &section.content {
            match block {
                unhwp::model::Block::Paragraph(p) => {
                    // `Paragraph::has_text_content()` does not count `InlineContent::Equation`
                    // (see `unhwp::model::paragraph`), so an equation-only paragraph (no
                    // surrounding prose) would otherwise be dropped here before its LaTeX
                    // ever reached `build_paragraph_content` (#98). ~keep
                    let has_equation = p
                        .content
                        .iter()
                        .any(|c| matches!(c, unhwp::model::InlineContent::Equation(_)));
                    let (text, annotations) = build_paragraph_content(&mut builder, p, &mut footnote_counter);
                    let (trimmed, adjusted) = trim_text_and_annotations(&text, annotations);
                    if p.style.is_heading() && (p.has_text_content() || has_equation) {
                        if !trimmed.is_empty() {
                            let idx = builder.push_heading(p.style.heading_level, trimmed, None, None);
                            if !adjusted.is_empty() {
                                builder.set_annotations(idx, adjusted);
                            }
                        }
                    } else if (p.has_text_content() || has_equation) && !trimmed.is_empty() {
                        builder.push_paragraph(trimmed, adjusted, None, None);
                    }

                    for inline in &p.content {
                        if let unhwp::model::InlineContent::Image(img_ref) = inline {
                            if let Some(resource) = doc.resources.get(&img_ref.id) {
                                let image = ExtractedImage {
                                    data: Bytes::from(resource.data.clone()),
                                    format: mime_to_format(resource.mime_type.as_deref().unwrap_or("")),
                                    image_index: image_index as u32,
                                    page_number: None,
                                    width: img_ref.width,
                                    height: img_ref.height,
                                    colorspace: None,
                                    bits_per_component: None,
                                    is_mask: false,
                                    description: img_ref.alt_text.clone(),
                                    ocr_result: None,
                                    bounding_box: None,
                                    source_path: None,
                                    image_kind: None,
                                    kind_confidence: None,
                                    cluster_id: None,
                                    caption: None,
                                    qr_codes: None,
                                    data_base64: None,
                                };
                                builder.push_image(img_ref.alt_text.as_deref(), image, None, None);
                                image_index += 1;
                            } else {
                                // `img_ref.id` names a resource that `doc.resources` never
                                // received a binary payload for (a missing/unpacked media
                                // part). A well-formed HWPX package always has a resource
                                // entry for every image reference it emits, so this only
                                // fires on a genuinely incomplete document -- and unlike the
                                // resolved case above, nothing is pushed for it at all: the
                                // image is silently absent from the output (#171).
                                builder.add_warning(crate::core::diagnostics::warning(
                                    HWPX_WARNING_SOURCE,
                                    format!(
                                        "Image reference '{}' has no corresponding entry in the document's \
                                         resources; the image could not be extracted",
                                        img_ref.id
                                    ),
                                ));
                            }
                        }
                    }
                }
                unhwp::model::Block::Table(t) => {
                    if !t.rows.is_empty() {
                        let mut cells: Vec<Vec<String>> = Vec::with_capacity(t.rows.len());
                        for row in &t.rows {
                            let mut row_cells = Vec::with_capacity(row.cells.len());
                            for cell in &row.cells {
                                row_cells.push(cell_plain_text(&mut builder, cell, &mut footnote_counter));
                            }
                            cells.push(row_cells);
                        }
                        push_table(&mut builder, cells, t.has_header);
                    }
                }
            }

            if matches!(block, unhwp::model::Block::Paragraph(_)) {
                // The scan is the only source of formula elements, because it
                // sees an equation wherever it sits. Emitting here keeps the
                // equation next to the paragraph that introduces it.
                // The two sides count paragraphs independently, and a shape
                // that holds its own paragraphs makes the crate emit more
                // blocks than the scan saw. Emitting everything up to the
                // current ordinal places a formula late when the counts drift,
                // rather than stranding every formula after it.
                while let Some((ordinal, latex)) = scanned.and_then(|list| list.get(next_formula)) {
                    if *ordinal > paragraph_ordinal {
                        break;
                    }
                    builder.push_formula(latex, None, None);
                    next_formula += 1;
                }
                paragraph_ordinal += 1;
            }
        }

        // An equation the block walk never reached still belongs to the output.
        for (_, latex) in scanned.into_iter().flatten().skip(next_formula) {
            builder.push_formula(latex, None, None);
        }
    }

    builder.build()
}

/// Push a header's or footer's paragraphs, tagging every element with the given
/// `ContentLayer` so downstream filters (`include_headers`/`include_footers`) can find
/// them (#96 — these were previously not read from `unhwp`'s model at all).
fn push_header_footer_paragraphs(
    builder: &mut InternalDocumentBuilder,
    paragraphs: &[unhwp::model::Paragraph],
    layer: ContentLayer,
    footnote_counter: &mut u32,
) {
    for p in paragraphs {
        let (text, annotations) = build_paragraph_content(builder, p, footnote_counter);
        let (trimmed, adjusted) = trim_text_and_annotations(&text, annotations);
        if trimmed.is_empty() {
            continue;
        }
        let idx = builder.push_paragraph(trimmed, adjusted, None, None);
        builder.set_layer(idx, layer);
    }
}

/// Builds a paragraph's flattened text plus byte-offset annotations from its inline
/// content, and records footnote definitions as a side effect.
///
/// This replaces the previous reliance on `Paragraph::plain_text()`, which silently
/// dropped footnote text (`InlineContent::Footnote` fell through `plain_text()`'s
/// catch-all arm) and hyperlink targets (only the anchor text survived) (#97), and
/// rendered equations as their raw HWP script instead of the LaTeX `unhwp` already
/// computes (#98).
fn build_paragraph_content(
    builder: &mut InternalDocumentBuilder,
    p: &unhwp::model::Paragraph,
    footnote_counter: &mut u32,
) -> (String, Vec<TextAnnotation>) {
    let mut text = String::new();
    let mut annotations = Vec::new();
    // An equation leaves the text, so the spaces that surrounded it would
    // otherwise meet and read as a gap.
    let mut after_equation = false;

    for item in &p.content {
        match item {
            unhwp::model::InlineContent::Text(run) => {
                let value = if after_equation && text.ends_with(char::is_whitespace) {
                    run.text.trim_start()
                } else {
                    run.text.as_str()
                };
                text.push_str(value);
                after_equation = false;
            }
            unhwp::model::InlineContent::LineBreak => text.push('\n'),
            unhwp::model::InlineContent::Link { text: link_text, url } => {
                let start = text.len() as u32;
                text.push_str(link_text);
                let end = text.len() as u32;
                if start < end {
                    annotations.push(TextAnnotation {
                        start,
                        end,
                        kind: AnnotationKind::Link {
                            url: url.clone(),
                            title: None,
                        },
                    });
                }
            }
            unhwp::model::InlineContent::Equation(eq) => {
                // `unhwp::equation::to_latex` converts HWP's own EQEdit script DSL
                // (not MathML/OMML — HWP equations use a distinct script format) to
                // LaTeX. The parser leaves `Equation.latex` unset (only `unhwp`'s own
                // Markdown renderer calls `to_latex`), so it is invoked directly here
                // instead of duplicating a second HWP-script-to-LaTeX converter (#98). ~keep
                let latex = eq
                    .latex
                    .clone()
                    .unwrap_or_else(|| unhwp::equation::to_latex(&eq.script));
                // An HWP equation is an object rather than inline notation, so it
                // leaves the paragraph text, the shape DOCX and PPTX use for a math
                // run. `collect_section_formulas` emits the element for it.
                if !latex.trim().is_empty() {
                    after_equation = true;
                }
            }
            unhwp::model::InlineContent::Footnote(note_text) => {
                *footnote_counter += 1;
                let key = format!("hwpx-fn{footnote_counter}");
                text.push_str(&format!("[^{footnote_counter}]"));
                if !note_text.trim().is_empty() {
                    let idx = builder.push_footnote_definition(note_text.trim(), &key, None);
                    builder.set_layer(idx, ContentLayer::Footnote);
                }
            }
            unhwp::model::InlineContent::Image(_) => {
                // Images are extracted separately by the caller, which has access to
                // `doc.resources` for the binary payload.
            }
        }
    }

    (text, annotations)
}

/// Trims leading/trailing whitespace from `text` and shifts `annotations`' byte
/// offsets to match, dropping any annotation that fell entirely within the trimmed
/// prefix. Byte offsets are computed against the untrimmed text in
/// `build_paragraph_content`, so trimming without this adjustment would silently
/// misalign every annotation.
fn trim_text_and_annotations(text: &str, annotations: Vec<TextAnnotation>) -> (&str, Vec<TextAnnotation>) {
    let trimmed = text.trim();
    let trim_start = (text.len() - text.trim_start().len()) as u32;
    let trimmed_len = trimmed.len() as u32;

    let adjusted = annotations
        .into_iter()
        .filter_map(|mut annotation| {
            if annotation.end <= trim_start {
                return None;
            }
            annotation.start = annotation.start.saturating_sub(trim_start).min(trimmed_len);
            annotation.end = annotation.end.saturating_sub(trim_start).min(trimmed_len);
            if annotation.start >= annotation.end {
                None
            } else {
                Some(annotation)
            }
        })
        .collect();

    (trimmed, adjusted)
}

/// Flattens a table cell's paragraphs to a single string for the cell grid, still
/// routing through `build_paragraph_content` so footnotes/links/equations inside a
/// cell are captured rather than silently dropped by `TableCell::plain_text()` (#120).
fn cell_plain_text(
    builder: &mut InternalDocumentBuilder,
    cell: &unhwp::model::TableCell,
    footnote_counter: &mut u32,
) -> String {
    let mut lines = Vec::with_capacity(cell.content.len());
    for p in &cell.content {
        // `build_paragraph_content`'s `InlineContent::Image` arm is a no-op: it relies
        // on a second pass over `p.content` that only the top-level section/paragraph
        // loop performs (to reach `doc.resources` for the binary payload). Table cells
        // never get that second pass, so an image inside a cell is dropped outright --
        // not even as a placeholder -- unlike a resolvable top-level image (#171). ~keep
        if p.content
            .iter()
            .any(|c| matches!(c, unhwp::model::InlineContent::Image(_)))
        {
            builder.add_warning(crate::core::diagnostics::warning(
                HWPX_WARNING_SOURCE,
                "A table cell contains an image; images inside table cells are not \
                 extracted and were omitted from the output",
            ));
        }
        let (text, _annotations) = build_paragraph_content(builder, p, footnote_counter);
        lines.push(text.trim().to_string());
    }
    lines.join("\n")
}

/// Pushes a table, setting `Table::columns` from the first row when `unhwp` reports a
/// header row — previously always `None` regardless of `has_header` (#120). Note:
/// `unhwp`'s HWPX parser currently sets `has_header` on every non-empty table
/// (`hwpx/section.rs::parse_table`), so this is best-effort until that upstream signal
/// is more precise; it is still strictly more informative than never populating
/// `columns` at all.
fn push_table(builder: &mut InternalDocumentBuilder, cells: Vec<Vec<String>>, has_header: bool) -> u32 {
    let markdown = crate::rendering::common::render_table_markdown(&cells);
    let columns = if has_header { cells.first().cloned() } else { None };
    let table = crate::types::Table {
        cells,
        markdown,
        columns,
        ..Default::default()
    };
    builder.push_table(table, None, None)
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl InternalDocumentExtractor for HwpxExtractor {
    async fn extract_content(
        &self,
        content: &[u8],
        mime_type: &str,
        config: &ExtractionConfig,
    ) -> Result<InternalDocument> {
        let limits = config.security_limits.clone().unwrap_or_default();

        if content.len() as u64 > limits.max_archive_size as u64 {
            return Err(crate::XbergError::validation(format!(
                "HWPX file exceeds size limit ({} > {} bytes)",
                content.len(),
                limits.max_archive_size
            )));
        }

        let cursor = Cursor::new(content);
        let mut archive =
            zip::ZipArchive::new(cursor).map_err(|e| crate::XbergError::parsing(format!("invalid HWPX zip: {e}")))?;
        ZipBombValidator::new(limits)
            .validate(&mut archive)
            .map_err(|e| crate::XbergError::validation(e.to_string()))?;

        let section_formulas = collect_section_formulas(&mut archive);

        let doc = unhwp::parse_bytes(content)
            .map_err(|e| crate::XbergError::parsing(format!("Failed to parse HWPX: {e}")))?;
        Ok(build_hwpx_internal_document(doc, mime_type, &section_formulas))
    }

    fn supported_mime_types(&self) -> &[&str] {
        &["application/haansofthwpx", "application/hwp+zip"]
    }

    fn priority(&self) -> i32 {
        50
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::internal::ElementKind;
    use unhwp::model::{
        Block, Document, Equation, InlineContent, Paragraph, Section, Table, TableCell, TableRow, TextRun,
    };

    /// Build a HWPX package in memory holding one section.
    fn hwpx_package(sections: &[(&str, &str)]) -> Vec<u8> {
        let mut buffer = Vec::new();
        {
            let mut writer = zip::ZipWriter::new(Cursor::new(&mut buffer));
            let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
            writer.start_file("mimetype", stored).unwrap();
            std::io::Write::write_all(&mut writer, b"application/hwp+zip").unwrap();
            for (name, xml) in sections {
                writer
                    .start_file(*name, zip::write::SimpleFileOptions::default())
                    .unwrap();
                std::io::Write::write_all(&mut writer, xml.as_bytes()).unwrap();
            }
            writer.finish().unwrap();
        }
        buffer
    }

    fn scan(package: &[u8]) -> AHashMap<usize, Vec<(usize, String)>> {
        let mut archive = zip::ZipArchive::new(Cursor::new(package)).unwrap();
        collect_section_formulas(&mut archive)
    }

    /// Hangul writes the equation into the run, which `unhwp` skips, so the scan
    /// is the only thing that finds it.
    /// A formula is placed after the paragraph that holds it, and a section's
    /// map is read by the section's own number.
    #[test]
    fn test_a_section_formula_follows_its_paragraph() {
        use unhwp::model::{Block, Document, Paragraph, Section, TextRun};

        let mut doc = Document::new();
        let mut section = Section::new(2);
        for text in ["First.", "Second.", "Third."] {
            let mut p = Paragraph::new();
            p.push_text(TextRun::new(text));
            section.content.push(Block::Paragraph(p));
        }
        doc.sections.push(section);

        // The equation sits in the third paragraph, which is ordinal 2.
        let scanned: AHashMap<usize, Vec<(usize, String)>> = [(2usize, vec![(2usize, "\\frac{a}{b}".to_string())])]
            .into_iter()
            .collect();
        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &scanned);

        let kinds: Vec<&ElementKind> = internal.elements.iter().map(|e| &e.kind).collect();
        let formula_at = kinds
            .iter()
            .position(|k| matches!(k, ElementKind::Formula))
            .expect("the equation reaches the document");
        assert_eq!(
            formula_at,
            kinds.len() - 1,
            "the equation follows the third paragraph, got {kinds:?}"
        );
    }

    #[test]
    fn test_scan_reads_an_equation_inside_a_run() {
        let xml = r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <hp:p><hp:run><hp:t>Prose.</hp:t></hp:run></hp:p>
  <hp:p><hp:run><hp:equation><hp:script>a OVER b</hp:script></hp:equation></hp:run></hp:p>
</hs:sec>"#;

        let found = scan(&hwpx_package(&[("Contents/section0.xml", xml)]));

        assert_eq!(
            found.get(&0).map(Vec::as_slice),
            Some(&[(1usize, "\\frac{a}{b}".to_string())][..])
        );
    }

    /// `&amp;` separates the columns of a matrix, so a reader that drops entity
    /// references merges them silently.
    #[test]
    fn test_scan_resolves_entity_references_in_a_script() {
        let xml = r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <hp:p><hp:run><hp:equation><hp:script>bmatrix { 1 &amp; 2 # 3 &amp; 4 }</hp:script></hp:equation></hp:run></hp:p>
</hs:sec>"#;

        let found = scan(&hwpx_package(&[("Contents/section0.xml", xml)]));

        let latex = &found.get(&0).expect("section 0 has an equation")[0].1;
        // Compare against the script with its references already resolved. A
        // reader that drops them converts `1 &amp; 2` as `1 2`, which differs.
        let expected = unhwp::equation::to_latex("bmatrix { 1 & 2 # 3 & 4 }");
        assert_eq!(
            latex,
            expected.trim(),
            "the scan must resolve `&amp;` before conversion"
        );
        assert_ne!(
            latex,
            unhwp::equation::to_latex("bmatrix { 1  2 # 3  4 }").trim(),
            "a dropped reference must not produce the same LaTeX"
        );
    }

    /// `ZipBombValidator::validate` only checks the *declared* central-directory
    /// sizes; it never decompresses. `collect_section_formulas` must bound its own
    /// read of a member's content with `Read::take(MAX_HWPX_MEMBER_SIZE)` rather
    /// than trusting the declared size, or a section whose entry decompresses to
    /// far more than declared can still exhaust memory. An XML comment (ignored by
    /// the parser, so it does not disturb element nesting) padded past the cap
    /// proves the bound: an equation entirely before the cap is found, one that
    /// only starts after it is not, and the scan completes without hanging or
    /// panicking on the oversized member.
    #[test]
    fn test_scan_bounds_the_read_of_an_oversized_section_member() {
        let before = r#"<hp:p><hp:run><hp:equation><hp:script>a OVER b</hp:script></hp:equation></hp:run></hp:p>"#;
        let padding = "x".repeat(MAX_HWPX_MEMBER_SIZE as usize + 4096);
        let after = r#"<hp:p><hp:run><hp:equation><hp:script>p OVER q</hp:script></hp:equation></hp:run></hp:p>"#;
        let xml = format!(
            "<hs:sec xmlns:hp=\"http://www.hancom.co.kr/hwpml/2011/paragraph\">{before}<!--{padding}-->{after}</hs:sec>"
        );

        let found = scan(&hwpx_package(&[("Contents/section0.xml", &xml)]));

        let formulas = found.get(&0).expect("the equation before the cap is found");
        assert_eq!(
            formulas.as_slice(),
            &[(0usize, "\\frac{a}{b}".to_string())][..],
            "only the equation entirely within the first MAX_HWPX_MEMBER_SIZE bytes must be found; \
             finding the second equation would mean the read was not actually bounded"
        );
    }

    /// A section keeps its own index, so a section the crate cannot read does
    /// not shift the equations of the sections after it.
    #[test]
    fn test_scan_keys_each_section_by_its_own_index() {
        let one = r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <hp:p><hp:run><hp:equation><hp:script>x OVER y</hp:script></hp:equation></hp:run></hp:p>
</hs:sec>"#;
        let two = r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <hp:p><hp:run><hp:equation><hp:script>p OVER q</hp:script></hp:equation></hp:run></hp:p>
</hs:sec>"#;

        let found = scan(&hwpx_package(&[
            ("Contents/section0.xml", one),
            ("Contents/section2.xml", two),
        ]));

        // The parts are keyed by position, which is how the crate numbers a
        // section. A package that skips a number still lines the two sides up.
        assert_eq!(found.get(&0).map(|f| f[0].1.as_str()), Some("\\frac{x}{y}"));
        assert_eq!(found.get(&1).map(|f| f[0].1.as_str()), Some("\\frac{p}{q}"));
        assert!(found.get(&2).is_none(), "only two parts exist");
    }

    /// A paragraph inside a table stays in the cell for `unhwp`, so counting it
    /// would shift the ordinal of every paragraph after the table.
    #[test]
    fn test_scan_does_not_count_a_paragraph_inside_a_table() {
        let xml = r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <hp:p><hp:run><hp:tbl><hp:tr><hp:tc><hp:subList><hp:p><hp:run><hp:t>Cell.</hp:t></hp:run></hp:p></hp:subList></hp:tc></hp:tr></hp:tbl></hp:run></hp:p>
  <hp:p><hp:run><hp:equation><hp:script>a OVER b</hp:script></hp:equation></hp:run></hp:p>
</hs:sec>"#;

        let found = scan(&hwpx_package(&[("Contents/section0.xml", xml)]));

        assert_eq!(
            found.get(&0).map(|f| f[0].0),
            Some(1),
            "the equation is in the second paragraph"
        );
    }

    #[test]
    fn test_mime_to_format_maps_svg_wmf_emf() {
        assert_eq!(mime_to_format("image/svg+xml"), Cow::Borrowed("svg"));
        assert_eq!(mime_to_format("image/x-wmf"), Cow::Borrowed("wmf"));
        assert_eq!(mime_to_format("image/x-emf"), Cow::Borrowed("emf"));
        assert_eq!(mime_to_format("image/png"), Cow::Borrowed("png"));
        assert_eq!(mime_to_format("application/octet-stream"), Cow::Borrowed("bin"));
    }

    #[test]
    fn test_section_header_and_footer_are_extracted() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        section.header = Some(vec![Paragraph::text("Confidential Draft")]);
        section.footer = Some(vec![Paragraph::text("Page footer text")]);
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let header = internal
            .elements
            .iter()
            .find(|e| e.layer == ContentLayer::Header)
            .expect("header element must be present");
        assert_eq!(header.text, "Confidential Draft");

        let footer = internal
            .elements
            .iter()
            .find(|e| e.layer == ContentLayer::Footer)
            .expect("footer element must be present");
        assert_eq!(footer.text, "Page footer text");
    }

    #[test]
    fn test_footnote_produces_marker_and_definition() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.push_text(TextRun::new("See "));
        p.content.push(InlineContent::Footnote("The note body.".to_string()));
        p.push_text(TextRun::new(" done"));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let body = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::Paragraph)
            .expect("body paragraph must be present");
        assert_eq!(body.text, "See [^1] done");

        let definition = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::FootnoteDefinition)
            .expect("footnote definition element must be present");
        assert_eq!(definition.text, "The note body.");
        assert_eq!(definition.layer, ContentLayer::Footnote);
    }

    #[test]
    fn test_link_produces_link_annotation_with_correct_offsets() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.push_text(TextRun::new("Go to "));
        p.content.push(InlineContent::Link {
            text: "our site".to_string(),
            url: "https://example.com".to_string(),
        });
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let elem = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::Paragraph)
            .expect("paragraph must be present");
        assert_eq!(elem.text, "Go to our site");
        assert_eq!(elem.annotations.len(), 1);
        let annotation = &elem.annotations[0];
        assert_eq!(annotation.start, 6);
        assert_eq!(annotation.end, 14);
        assert_eq!(
            annotation.kind,
            AnnotationKind::Link {
                url: "https://example.com".to_string(),
                title: None,
            }
        );
    }

    /// An equation is an object, so its LaTeX becomes a formula element and
    /// leaves the paragraph's own text.
    #[test]
    fn test_equation_becomes_a_formula_element() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.push_text(TextRun::new("Result: "));
        p.content.push(InlineContent::Equation(Equation::new("FRAC{a}{b}")));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let section_formulas: AHashMap<usize, Vec<(usize, String)>> =
            [(0usize, vec![(0usize, "\\frac{a}{b}".to_string())])]
                .into_iter()
                .collect();
        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &section_formulas);

        let formulas: Vec<&str> = internal
            .elements
            .iter()
            .filter(|e| e.kind == ElementKind::Formula)
            .map(|e| e.text.as_str())
            .collect();
        assert_eq!(formulas, vec!["\\frac{a}{b}"]);

        let elem = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::Paragraph)
            .expect("paragraph must be present");
        assert_eq!(elem.text, "Result:");
    }

    /// The spaces that surrounded an equation would meet once it leaves the
    /// text, so the sentence keeps exactly one.
    #[test]
    fn test_removing_an_equation_leaves_one_space() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.push_text(TextRun::new("The ratio is "));
        p.content.push(InlineContent::Equation(Equation::new("x OVER y")));
        p.push_text(TextRun::new(" per unit."));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let para = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::Paragraph)
            .expect("paragraph must be present");
        assert_eq!(para.text, "The ratio is per unit.");
    }

    /// A paragraph holding nothing but an equation still carries its math: the
    /// formula element stands in for the paragraph that no longer has text.
    #[test]
    fn test_equation_only_paragraph_keeps_its_math() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.content.push(InlineContent::Equation(Equation::new("FRAC{a}{b}")));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let section_formulas: AHashMap<usize, Vec<(usize, String)>> =
            [(0usize, vec![(0usize, "\\frac{a}{b}".to_string())])]
                .into_iter()
                .collect();
        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &section_formulas);

        let formulas: Vec<&str> = internal
            .elements
            .iter()
            .filter(|e| e.kind == ElementKind::Formula)
            .map(|e| e.text.as_str())
            .collect();
        assert_eq!(formulas, vec!["\\frac{a}{b}"], "the equation survives (#98)");
    }

    #[test]
    fn test_table_header_row_populates_columns_and_cell_content() {
        let mut doc = Document::new();
        let mut section = Section::new(0);

        let mut table = Table::new();
        table.has_header = true;
        let mut header_row = TableRow::new();
        header_row.cells.push(TableCell::text("Name"));
        header_row.cells.push(TableCell::text("Age"));
        table.rows.push(header_row);
        let mut data_row = TableRow::new();
        data_row.cells.push(TableCell::text("Alice"));
        data_row.cells.push(TableCell::text("30"));
        table.rows.push(data_row);

        section.content.push(Block::Table(table));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let table_elem = internal
            .elements
            .iter()
            .find(|e| matches!(e.kind, ElementKind::Table { .. }))
            .expect("table element must be present");
        let ElementKind::Table { table_index } = table_elem.kind else {
            unreachable!()
        };
        let extracted_table = &internal.tables[table_index as usize];
        assert_eq!(
            extracted_table.columns,
            Some(vec!["Name".to_string(), "Age".to_string()])
        );
        assert_eq!(
            extracted_table.cells,
            vec![
                vec!["Name".to_string(), "Age".to_string()],
                vec!["Alice".to_string(), "30".to_string()],
            ]
        );
    }

    #[test]
    fn test_table_without_header_leaves_columns_unset() {
        let mut doc = Document::new();
        let mut section = Section::new(0);

        let mut table = Table::new();
        table.has_header = false;
        let mut row = TableRow::new();
        row.cells.push(TableCell::text("A"));
        table.rows.push(row);

        section.content.push(Block::Table(table));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let table_elem = internal
            .elements
            .iter()
            .find(|e| matches!(e.kind, ElementKind::Table { .. }))
            .expect("table element must be present");
        let ElementKind::Table { table_index } = table_elem.kind else {
            unreachable!()
        };
        assert_eq!(internal.tables[table_index as usize].columns, None);
    }

    #[test]
    fn test_table_cell_footnote_is_extracted_not_dropped() {
        let mut doc = Document::new();
        let mut section = Section::new(0);

        let mut table = Table::new();
        let mut row = TableRow::new();
        let mut cell = TableCell::new();
        let mut cell_para = Paragraph::new();
        cell_para.content.push(InlineContent::Footnote("cell note".to_string()));
        cell_para.push_text(TextRun::new("cell body"));
        cell.content.push(cell_para);
        row.cells.push(cell);
        table.rows.push(row);

        section.content.push(Block::Table(table));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let definition = internal
            .elements
            .iter()
            .find(|e| e.kind == ElementKind::FootnoteDefinition)
            .expect("footnote inside a table cell must still produce a definition");
        assert_eq!(definition.text, "cell note");
    }

    fn hwpx_warnings(doc: &InternalDocument) -> Vec<String> {
        doc.processing_warnings
            .iter()
            .filter(|w| w.source == HWPX_WARNING_SOURCE)
            .map(|w| w.message.to_string())
            .collect()
    }

    /// #171: an `InlineContent::Image` whose `id` has no entry in
    /// `doc.resources` cannot be resolved to binary data and is dropped
    /// entirely (no image element, no placeholder).
    #[test]
    fn should_warn_when_image_resource_id_is_missing_from_resources() {
        let mut doc = Document::new();
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.content
            .push(InlineContent::Image(unhwp::model::ImageRef::new("bin0")));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);
        // Deliberately leave `doc.resources` empty: "bin0" is never registered.

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let warnings = hwpx_warnings(&internal);
        assert_eq!(warnings.len(), 1, "expected exactly one hwpx warning, got {warnings:?}");
        assert!(
            warnings[0].contains("bin0") && warnings[0].contains("could not be extracted"),
            "warning must name the unresolved image id, got {warnings:?}"
        );
        assert!(
            internal.images.is_empty(),
            "an unresolved image must not produce an image element"
        );
    }

    /// A resolvable image (its id present in `doc.resources`) must not warn.
    #[test]
    fn should_not_warn_when_image_resource_resolves() {
        let mut doc = Document::new();
        doc.resources.insert(
            "bin0".to_string(),
            unhwp::model::Resource::new(unhwp::model::ResourceType::Image, vec![0x89, 0x50, 0x4E, 0x47]),
        );
        let mut section = Section::new(0);
        let mut p = Paragraph::new();
        p.content
            .push(InlineContent::Image(unhwp::model::ImageRef::new("bin0")));
        section.content.push(Block::Paragraph(p));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        assert!(
            hwpx_warnings(&internal).is_empty(),
            "a resolvable image must not warn, got {:?}",
            hwpx_warnings(&internal)
        );
    }

    /// #171: `build_paragraph_content`'s `InlineContent::Image` arm is a no-op
    /// everywhere; only the top-level section/paragraph loop performs the
    /// second pass that actually resolves and pushes an image element. A
    /// table cell never gets that second pass, so an image inside a cell is
    /// dropped outright.
    #[test]
    fn should_warn_when_table_cell_contains_an_image() {
        let mut doc = Document::new();
        doc.resources.insert(
            "bin0".to_string(),
            unhwp::model::Resource::new(unhwp::model::ResourceType::Image, vec![0x89, 0x50, 0x4E, 0x47]),
        );
        let mut section = Section::new(0);

        let mut table = Table::new();
        let mut row = TableRow::new();
        let mut cell = TableCell::new();
        let mut cell_para = Paragraph::new();
        cell_para
            .content
            .push(InlineContent::Image(unhwp::model::ImageRef::new("bin0")));
        cell.content.push(cell_para);
        row.cells.push(cell);
        table.rows.push(row);

        section.content.push(Block::Table(table));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        let warnings = hwpx_warnings(&internal);
        assert_eq!(warnings.len(), 1, "expected exactly one hwpx warning, got {warnings:?}");
        assert!(
            warnings[0].contains("table cell") && warnings[0].contains("not extracted"),
            "warning must describe the dropped table-cell image, got {warnings:?}"
        );
        assert!(
            internal.images.is_empty(),
            "an image inside a table cell must not produce an image element"
        );
    }

    /// An ordinary table with only text cells must not warn.
    #[test]
    fn should_not_warn_for_table_with_only_text_cells() {
        let mut doc = Document::new();
        let mut section = Section::new(0);

        let mut table = Table::new();
        let mut row = TableRow::new();
        row.cells.push(TableCell::text("Alice"));
        row.cells.push(TableCell::text("30"));
        table.rows.push(row);

        section.content.push(Block::Table(table));
        doc.sections.push(section);

        let internal = build_hwpx_internal_document(doc, "application/haansofthwpx", &AHashMap::new());

        assert!(
            hwpx_warnings(&internal).is_empty(),
            "a table with only text cells must not warn, got {:?}",
            hwpx_warnings(&internal)
        );
    }

    #[test]
    fn test_hwpx_extractor_plugin_interface() {
        let extractor = HwpxExtractor::new();
        assert_eq!(extractor.name(), "hwpx-extractor");
        assert_eq!(extractor.version(), env!("CARGO_PKG_VERSION"));
        assert_eq!(extractor.priority(), 50);
        assert_eq!(
            extractor.supported_mime_types(),
            &["application/haansofthwpx", "application/hwp+zip"]
        );
    }

    #[test]
    fn test_hwpx_extractor_initialize_shutdown() {
        let extractor = HwpxExtractor::new();
        assert!(extractor.initialize().is_ok());
        assert!(extractor.shutdown().is_ok());
    }

    #[tokio::test]
    async fn test_hwpx_extract_real_document() {
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../test_documents/hwpx/simple.hwpx");
        let content = std::fs::read(path).expect("test_documents/hwpx/simple.hwpx must exist");
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&content, "application/haansofthwpx", &ExtractionConfig::default())
            .await
            .expect("extraction of simple.hwpx must succeed");

        let text = result.content();
        assert!(
            text.contains("Hello from HWPX document"),
            "expected body text not found; got: {text}"
        );
    }

    #[tokio::test]
    async fn test_hwpx_extract_corrupted_returns_err() {
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(b"not a zip", "application/haansofthwpx", &ExtractionConfig::default())
            .await;
        assert!(result.is_err(), "corrupted input must return Err, not panic");
    }

    fn make_zip_with_ratio(uncompressed_len: usize) -> Vec<u8> {
        use std::io::Write as _;
        let mut buf = std::io::Cursor::new(Vec::new());
        let mut zw = zip::ZipWriter::new(&mut buf);
        let opts = zip::write::FileOptions::<()>::default().compression_method(zip::CompressionMethod::Deflated);
        zw.start_file("content.hml", opts).unwrap();
        zw.write_all(&vec![0u8; uncompressed_len]).unwrap();
        zw.finish().unwrap();
        buf.into_inner()
    }

    fn make_zip_with_n_files(n: usize) -> Vec<u8> {
        use std::io::Write as _;
        let mut buf = std::io::Cursor::new(Vec::new());
        let mut zw = zip::ZipWriter::new(&mut buf);
        let opts = zip::write::FileOptions::<()>::default().compression_method(zip::CompressionMethod::Stored);
        for i in 0..n {
            zw.start_file(format!("f{i}.bin"), opts).unwrap();
            zw.write_all(b"x").unwrap();
        }
        zw.finish().unwrap();
        buf.into_inner()
    }

    #[tokio::test]
    async fn test_hwpx_rejects_zip_bomb_default_limits() {
        let zip_bytes = make_zip_with_ratio(256 * 1024);
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&zip_bytes, "application/haansofthwpx", &ExtractionConfig::default())
            .await;
        assert!(result.is_err(), "default limits must block a >100:1 zip bomb");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("ZIP bomb") || err.contains("ratio") || err.contains("validation"),
            "error should mention bomb/ratio/validation, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_hwpx_rejects_zip_bomb() {
        use crate::extractors::security::SecurityLimits;
        let zip_bytes = make_zip_with_ratio(8 * 1024);
        let config = ExtractionConfig {
            security_limits: Some(SecurityLimits {
                max_compression_ratio: 1,
                ..SecurityLimits::default()
            }),
            ..ExtractionConfig::default()
        };
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&zip_bytes, "application/haansofthwpx", &config)
            .await;
        assert!(result.is_err(), "zip bomb must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("ZIP bomb") || err.contains("ratio") || err.contains("validation"),
            "error should mention bomb/ratio/validation, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_hwpx_rejects_oversized_file() {
        use crate::extractors::security::SecurityLimits;
        let limits = SecurityLimits {
            max_archive_size: 10,
            ..SecurityLimits::default()
        };
        let config = ExtractionConfig {
            security_limits: Some(limits),
            ..ExtractionConfig::default()
        };
        let oversized = vec![0u8; 11];
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&oversized, "application/haansofthwpx", &config)
            .await;
        assert!(result.is_err(), "oversized file must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("size limit") || err.contains("validation"),
            "error should mention size limit, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_hwpx_rejects_too_many_files() {
        use crate::extractors::security::SecurityLimits;
        let zip_bytes = make_zip_with_n_files(3);
        let config = ExtractionConfig {
            security_limits: Some(SecurityLimits {
                max_files_in_archive: 2,
                ..SecurityLimits::default()
            }),
            ..ExtractionConfig::default()
        };
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&zip_bytes, "application/haansofthwpx", &config)
            .await;
        assert!(result.is_err(), "archive exceeding file-count limit must be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("files") || err.contains("count") || err.contains("validation"),
            "error should mention file count, got: {err}"
        );
    }

    #[tokio::test]
    async fn test_hwpx_valid_zip_passes_security_check() {
        use crate::extractors::security::SecurityLimits;
        let zip_bytes = make_zip_with_ratio(1024);
        let config = ExtractionConfig {
            security_limits: Some(SecurityLimits {
                max_compression_ratio: 10_000,
                max_archive_size: 10 * 1024 * 1024,
                max_files_in_archive: 1_000,
                ..SecurityLimits::default()
            }),
            ..ExtractionConfig::default()
        };
        let extractor = HwpxExtractor::new();
        let result = extractor
            .extract_content(&zip_bytes, "application/haansofthwpx", &config)
            .await;
        let is_parse_err = match &result {
            Err(e) => {
                let msg = e.to_string();
                !msg.contains("ZIP bomb")
                    && !msg.contains("ratio")
                    && !msg.contains("size limit")
                    && !msg.contains("too many files")
            }
            Ok(_) => true,
        };
        assert!(
            is_parse_err,
            "security validator must not reject a safe ZIP; got: {result:?}"
        );
    }
}