lib3mf 0.1.6

Pure Rust implementation for 3MF (3D Manufacturing Format) parsing and writing
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
//! OPC (Open Packaging Conventions) handling for 3MF files
//!
//! 3MF files are ZIP archives following the OPC standard, containing
//! various parts including the main 3D model file and relationships.

mod content_types;
mod reader;
mod relationships;
mod thumbnail;
mod writer;

use crate::error::Result;
use std::io::Read;
use zip::ZipArchive;

// Re-export public API
pub use writer::{create_package, create_package_with_thumbnail};

/// Main 3D model file path within the 3MF archive
pub const MODEL_PATH: &str = "3D/3dmodel.model";

/// Alternative model path (some implementations use this)
pub const MODEL_PATH_ALT: &str = "/3D/3dmodel.model";

/// Content types file path
pub const CONTENT_TYPES_PATH: &str = "[Content_Types].xml";

/// Relationships file path
pub const RELS_PATH: &str = "_rels/.rels";

/// Model relationships file path
pub const MODEL_RELS_PATH: &str = "3D/_rels/3dmodel.model.rels";

/// 3D model relationship type
pub const MODEL_REL_TYPE: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";

/// Thumbnail relationship type (OPC standard)
pub const THUMBNAIL_REL_TYPE: &str =
    "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";

/// Keystore relationship type (Secure Content extension) - 2019/04 namespace
/// Note: The namespace changed from 2019/04 to 2019/07, but both are valid
pub const KEYSTORE_REL_TYPE_2019_04: &str =
    "http://schemas.microsoft.com/3dmanufacturing/2019/04/keystore";

/// Keystore relationship type (Secure Content extension) - 2019/07 namespace
pub const KEYSTORE_REL_TYPE_2019_07: &str =
    "http://schemas.microsoft.com/3dmanufacturing/2019/07/keystore";

/// EncryptedFile relationship type (OPC standard for encrypted files)
/// Per 3MF SecureContent spec, encrypted files must have this relationship type
pub const ENCRYPTEDFILE_REL_TYPE: &str =
    "http://schemas.openxmlformats.org/package/2006/relationships/encryptedfile";

/// 3D Texture relationship type (Materials extension)
/// Per 3MF Materials Extension spec, texture resources must have this relationship type
pub const TEXTURE_REL_TYPE: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";

/// Represents an OPC package (3MF file)
pub struct Package<R: Read> {
    archive: ZipArchive<R>,
    lenient: bool,
}

impl<R: Read + std::io::Seek> Package<R> {
    /// Open a 3MF package from a reader
    pub fn open(reader: R) -> Result<Self> {
        Self::open_lenient(reader, false)
    }

    /// Open a 3MF package from a reader with configurable conformance level.
    ///
    /// When `lenient` is `true`, non-critical OPC packaging errors are
    /// silently ignored (e.g., non-standard thumbnail relationship types).
    pub fn open_lenient(reader: R, lenient: bool) -> Result<Self> {
        reader::open(reader, lenient)
    }

    /// Get the main 3D model file content
    pub fn get_model(&mut self) -> Result<String> {
        reader::get_model(self)
    }

    /// Get a streaming reader for the main 3D model file
    ///
    /// Returns a reader that decompresses the model file on-the-fly from the ZIP
    /// archive, avoiding loading the entire file into memory. The returned reader
    /// implements `Read` and borrows the package for its lifetime.
    pub fn get_model_reader(&mut self) -> Result<impl Read + '_> {
        reader::get_model_reader(self)
    }

    /// Get a file from the package by name
    pub fn get_file(&mut self, name: &str) -> Result<String> {
        reader::get_file(self, name)
    }

    /// Check if a file exists in the package
    pub fn has_file(&mut self, name: &str) -> bool {
        reader::has_file(self, name)
    }

    /// Get the number of files in the package
    pub fn len(&self) -> usize {
        reader::len(self)
    }

    /// Check if the package is empty
    pub fn is_empty(&self) -> bool {
        reader::is_empty(self)
    }

    /// Get a list of all file names in the package
    pub fn file_names(&mut self) -> Vec<String> {
        reader::file_names(self)
    }

    /// Get a file as binary data
    pub fn get_file_binary(&mut self, name: &str) -> Result<Vec<u8>> {
        reader::get_file_binary(self, name)
    }

    /// Get thumbnail metadata from the package
    pub fn get_thumbnail_metadata(&mut self) -> Result<Option<crate::model::Thumbnail>> {
        thumbnail::get_thumbnail_metadata(self, self.lenient)
    }

    /// Validate no model-level thumbnails exist
    pub fn validate_no_model_level_thumbnails(&mut self) -> Result<()> {
        thumbnail::validate_no_model_level_thumbnails(self, self.lenient)
    }

    /// Discover keystore file path from package relationships
    pub fn discover_keystore_path(&mut self) -> Result<Option<String>> {
        relationships::discover_keystore_path(self)
    }

    /// Check if a target file has a relationship of a specific type
    pub fn has_relationship_to_target(
        &mut self,
        target_path: &str,
        relationship_type: &str,
        source_file: Option<&str>,
    ) -> Result<bool> {
        relationships::has_relationship_to_target(self, target_path, relationship_type, source_file)
    }

    /// Validate keystore relationship
    pub fn validate_keystore_relationship(&mut self, keystore_path: &str) -> Result<()> {
        relationships::validate_keystore_relationship(self, keystore_path)
    }

    /// Validate keystore content type
    pub fn validate_keystore_content_type(&mut self, keystore_path: &str) -> Result<()> {
        content_types::validate_keystore_content_type(self, keystore_path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use std::io::Read;
    use std::io::Write;
    use zip::ZipWriter;
    use zip::write::SimpleFileOptions;

    // -----------------------------------------------------------------------
    // Test helpers
    // -----------------------------------------------------------------------

    /// Create a ZIP archive from a slice of (filename, data) pairs.
    fn make_zip(files: &[(&str, &[u8])]) -> Cursor<Vec<u8>> {
        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
        let options = SimpleFileOptions::default();
        for (name, data) in files {
            zip.start_file(*name, options).unwrap();
            zip.write_all(data).unwrap();
        }
        zip.finish().unwrap()
    }

    const MINIMAL_CONTENT_TYPES: &[u8] = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";

    const MINIMAL_RELS: &[u8] = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";

    const MINIMAL_MODEL: &[u8] = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<model unit=\"millimeter\" xml:lang=\"en-US\" \
xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\">\
  <resources/><build/></model>";

    /// Create the smallest valid 3MF package.
    fn minimal_3mf() -> Cursor<Vec<u8>> {
        make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ])
    }

    /// Create a valid 3MF package that also includes a PNG thumbnail.
    fn minimal_3mf_with_thumbnail() -> Cursor<Vec<u8>> {
        let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"rel1\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\
</Relationships>";
        // Minimal valid 1x1 RGB PNG bytes
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG magic
            0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
            0x77, 0x53, 0xDE, // IHDR data + CRC
            0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, // IDAT chunk
            0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21,
            0xBC, 0x33, // IDAT data + CRC
            0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, // IEND
        ];
        make_zip(&[
            ("[Content_Types].xml", content_types),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("Metadata/thumbnail.png", png),
        ])
    }

    /// Create a valid 3MF package that includes a keystore file.
    fn minimal_3mf_with_keystore() -> Cursor<Vec<u8>> {
        let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"xml\" ContentType=\"application/vnd.ms-package.3dmanufacturing-keystore+xml\"/>\
</Types>";
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/keystore.xml\" Id=\"rel1\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2019/07/keystore\"/>\
</Relationships>";
        make_zip(&[
            ("[Content_Types].xml", content_types),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            (
                "Metadata/keystore.xml",
                b"<?xml version=\"1.0\"?><keystore/>",
            ),
        ])
    }

    // -----------------------------------------------------------------------
    // Package method tests (happy-path, require a valid package)
    // -----------------------------------------------------------------------

    #[test]
    fn test_package_get_model() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let model = pkg.get_model().unwrap();
        assert!(
            model.contains("<model"),
            "get_model should return model XML"
        );
    }

    #[test]
    fn test_package_get_model_reader() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let mut reader = pkg.get_model_reader().unwrap();
        let mut content = String::new();
        reader.read_to_string(&mut content).unwrap();
        assert!(
            content.contains("<model"),
            "get_model_reader should stream model XML"
        );
    }

    #[test]
    fn test_package_get_file() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let content = pkg.get_file(RELS_PATH).unwrap();
        assert!(
            content.contains("Relationships"),
            "get_file should return rels XML"
        );
    }

    #[test]
    fn test_package_has_file_existing_and_missing() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        assert!(
            pkg.has_file(MODEL_PATH),
            "has_file should return true for existing file"
        );
        assert!(
            !pkg.has_file("nonexistent.bin"),
            "has_file should return false for missing file"
        );
    }

    #[test]
    fn test_package_len_and_is_empty() {
        let pkg = Package::open(minimal_3mf()).unwrap();
        assert_eq!(pkg.len(), 3, "minimal 3MF should have 3 files");
        assert!(!pkg.is_empty(), "non-empty package should not be is_empty");
    }

    #[test]
    fn test_package_file_names() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let names = pkg.file_names();
        assert_eq!(names.len(), 3);
        assert!(names.contains(&CONTENT_TYPES_PATH.to_string()));
        assert!(names.contains(&RELS_PATH.to_string()));
        assert!(names.contains(&MODEL_PATH.to_string()));
    }

    #[test]
    fn test_package_get_file_binary() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let data = pkg.get_file_binary(MODEL_PATH).unwrap();
        assert!(
            !data.is_empty(),
            "get_file_binary should return non-empty data"
        );
        // Model XML starts with <?xml
        assert_eq!(&data[..5], b"<?xml");
    }

    #[test]
    fn test_package_get_file_missing_returns_error() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        assert!(pkg.get_file("does_not_exist.xml").is_err());
        assert!(pkg.get_file_binary("does_not_exist.bin").is_err());
    }

    // -----------------------------------------------------------------------
    // Missing required files
    // -----------------------------------------------------------------------

    #[test]
    fn test_open_missing_rels_file() {
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(
            result.is_err(),
            "Package without _rels/.rels should fail to open"
        );
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("_rels/.rels") || err.contains("rels"),
            "Error should mention missing rels file, got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Content types validation
    // -----------------------------------------------------------------------

    #[test]
    fn test_content_types_missing_rels_extension() {
        // Content_Types.xml with no Default for "rels" extension
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("rels"),
            "Error should mention missing rels extension, got: {err}"
        );
    }

    #[test]
    fn test_content_types_missing_model_type() {
        // Content_Types.xml with no model content type
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("model"),
            "Error should mention missing model content type, got: {err}"
        );
    }

    #[test]
    fn test_content_types_empty_extension() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("empty"),
            "Error should mention empty Extension, got: {err}"
        );
    }

    #[test]
    fn test_content_types_duplicate_extension() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Duplicate"),
            "Error should mention duplicate extension, got: {err}"
        );
    }

    #[test]
    fn test_content_types_invalid_png_content_type() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/jpeg\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("image/png"),
            "Error should mention correct PNG content type, got: {err}"
        );
    }

    #[test]
    fn test_content_types_wrong_model_extension() {
        // Model content type assigned to an extension that is neither "model" nor "part"
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"xyz\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Extension"),
            "Error should mention Extension requirement, got: {err}"
        );
    }

    #[test]
    fn test_content_types_model_via_override_succeeds() {
        // Override element for the model file is valid (found_model via Override)
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Override PartName=\"/3D/3dmodel.model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        assert!(
            Package::open(cursor).is_ok(),
            "Model content type via Override should be accepted"
        );
    }

    #[test]
    fn test_content_types_empty_partname() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Override PartName=\"\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("PartName"),
            "Error should mention empty PartName, got: {err}"
        );
    }

    #[test]
    fn test_content_types_duplicate_override() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Override PartName=\"/3D/3dmodel.model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Override PartName=\"/3D/3dmodel.model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Duplicate"),
            "Error should mention duplicate Override, got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Model relationship / filename validation
    // -----------------------------------------------------------------------

    #[test]
    fn test_model_filename_dot_prefix() {
        // Relationship points to a file whose name starts with '.'
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/.3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/.3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("dot"),
            "Error should mention dot-prefix filename, got: {err}"
        );
    }

    #[test]
    fn test_model_filename_non_ascii_prefix() {
        // Relationship points to a file whose name has a non-ASCII prefix before "3dmodel".
        // U+00C6 (Æ, Latin Capital Letter Ae) is used as a representative non-ASCII character
        // that visually resembles an ASCII letter and could be used to spoof a model filename.
        let rels = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/\u{00C6}3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let model_name = "3D/\u{00C6}3dmodel.model";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels.as_bytes()),
            (model_name, MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("non-ASCII"),
            "Error should mention non-ASCII prefix, got: {err}"
        );
    }

    #[test]
    fn test_model_file_not_found_in_zip() {
        // Relationship points to a file that doesn't exist in the archive
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/missing.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            // Note: "3D/missing.model" is deliberately absent
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("missing") || err.contains("non-existent") || err.contains("exist"),
            "Error should indicate file not found, got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // All-relationships validation
    // -----------------------------------------------------------------------

    #[test]
    fn test_duplicate_relationship_ids() {
        // Two relationships share the same Id in _rels/.rels
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Duplicate") || err.contains("duplicate"),
            "Error should mention duplicate ID, got: {err}"
        );
    }

    #[test]
    fn test_relationship_id_starts_with_digit_in_root_rels() {
        // Root .rels relationship Id starts with a digit
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"1invalid\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("digit"),
            "Error should mention ID starting with digit, got: {err}"
        );
    }

    #[test]
    fn test_relationship_missing_id_attribute() {
        // A relationship element has no Id attribute
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Id"),
            "Error should mention missing Id attribute, got: {err}"
        );
    }

    #[test]
    fn test_wrong_relationship_type_for_texture_file() {
        // A PNG texture in 3dmodel.model.rels uses MODEL_REL_TYPE instead of TEXTURE_REL_TYPE
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        let model_rels =
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/texture.png\" Id=\"tex0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("3D/_rels/3dmodel.model.rels", model_rels),
            // texture.png intentionally absent (error fires before file-existence check)
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("texture") || err.contains("3dtexture"),
            "Error should mention texture relationship type, got: {err}"
        );
    }

    #[test]
    fn test_relationship_type_with_query_string() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel1\" Type=\"http://example.com/type?query=1\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("query"),
            "Error should mention query string, got: {err}"
        );
    }

    #[test]
    fn test_relationship_type_with_fragment() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel1\" Type=\"http://example.com/type#frag\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("fragment"),
            "Error should mention fragment identifier, got: {err}"
        );
    }

    #[test]
    fn test_duplicate_relationship_targets() {
        // Two relationships point to the same target with the same type (different IDs)
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel1\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("Duplicate") || err.contains("duplicate"),
            "Error should mention duplicate target, got: {err}"
        );
    }

    #[test]
    fn test_part_specific_rels_without_associated_part() {
        // 3D/_rels/orphan.model.rels exists but 3D/orphan.model does not
        let orphan_rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("3D/_rels/orphan.model.rels", orphan_rels),
            // "3D/orphan.model" is intentionally absent
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("orphan") || err.contains("exist"),
            "Error should mention missing associated part, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_with_hash() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/bad#part.model\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("fragment") || err.contains('#'),
            "Error should mention fragment in part name, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_with_question_mark() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/bad?part.model\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("query") || err.contains('?'),
            "Error should mention query string in part name, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_with_dotdot_segment() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/../etc/passwd\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains(".."),
            "Error should mention '..' segment, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_with_single_dot_segment() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D/./other.model\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("'.'"),
            "Error should mention '.' segment, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_segment_ends_with_dot() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D./other.model\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("'.'") || err.contains("end"),
            "Error should mention segment ending with dot, got: {err}"
        );
    }

    #[test]
    fn test_invalid_part_name_empty_path_segment() {
        // Double slash creates an empty path segment
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/3D//other.model\" Id=\"rel1\" Type=\"http://example.com/other\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);
        let result = Package::open(cursor);
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("empty") || err.contains("segment"),
            "Error should mention empty path segment, got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Thumbnail tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_get_thumbnail_metadata_returns_none_when_no_thumbnail() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let result = pkg.get_thumbnail_metadata().unwrap();
        assert!(
            result.is_none(),
            "Package without thumbnail should return None"
        );
    }

    #[test]
    fn test_get_thumbnail_metadata_png() {
        let mut pkg = Package::open(minimal_3mf_with_thumbnail()).unwrap();
        let thumb = pkg.get_thumbnail_metadata().unwrap();
        assert!(thumb.is_some(), "Package with thumbnail should return Some");
        let thumb = thumb.unwrap();
        assert!(
            thumb.path.contains("thumbnail"),
            "Thumbnail path should contain 'thumbnail'"
        );
        assert_eq!(&thumb.content_type, "image/png");
    }

    #[test]
    fn test_thumbnail_cmyk_jpeg_rejected() {
        // Craft a minimal CMYK JPEG (4 components in SOF0 marker)
        // Layout: FF D8 (SOI), then FF C0 (SOF0) at position 2
        // data[2..]: FF C0 LL LL PP HH HH WW WW CC
        //   where CC = num_components at offset 9 from FF = data[11]
        let cmyk_jpeg: Vec<u8> = vec![
            0xFF, 0xD8, // SOI
            0xFF, 0xC0, // SOF0 marker
            0x00, 0x0B, // length = 11
            0x08, // precision
            0x00, 0x01, // height = 1
            0x00, 0x01, // width = 1
            0x04, // num_components = 4 (CMYK)
        ];
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"jpeg\" ContentType=\"image/jpeg\"/>\
</Types>";
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/thumbnail.jpeg\" Id=\"rel1\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("Metadata/thumbnail.jpeg", &cmyk_jpeg),
        ]);
        let mut pkg = Package::open(cursor).expect("Package with CMYK JPEG should open");
        let result = pkg.get_thumbnail_metadata();
        assert!(result.is_err(), "CMYK JPEG thumbnail should be rejected");
        let err = result.err().unwrap().to_string();
        assert!(
            err.contains("CMYK"),
            "Error should mention CMYK, got: {err}"
        );
    }

    #[test]
    fn test_validate_no_model_level_thumbnail_with_package_thumbnail_ok() {
        // Package has both package-level and model-level thumbnails -> OK
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        let pkg_rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"rel1\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\
</Relationships>";
        let model_rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"mrel0\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\
</Relationships>";
        let png = &[0x89u8, 0x50, 0x4E, 0x47]; // first 4 bytes of valid PNG magic number
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", pkg_rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("3D/_rels/3dmodel.model.rels", model_rels),
            ("Metadata/thumbnail.png", png),
        ]);
        let mut pkg = Package::open(cursor).expect("Package should open");
        assert!(
            pkg.validate_no_model_level_thumbnails().is_ok(),
            "Model-level thumbnail is allowed when package-level thumbnail also exists"
        );
    }

    #[test]
    fn test_validate_model_level_thumbnail_without_package_level_fails() {
        // Package has model-level thumbnail but NO package-level thumbnail -> should fail
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        // No thumbnail in root rels
        let pkg_rels = MINIMAL_RELS;
        let model_rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"mrel0\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail\"/>\
</Relationships>";
        let png = &[0x89u8, 0x50, 0x4E, 0x47];
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", pkg_rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("3D/_rels/3dmodel.model.rels", model_rels),
            ("Metadata/thumbnail.png", png),
        ]);
        let mut pkg = Package::open(cursor).expect("Package should open");
        let result = pkg.validate_no_model_level_thumbnails();
        assert!(
            result.is_err(),
            "Model-level thumbnail without package-level thumbnail should fail"
        );
    }

    // -----------------------------------------------------------------------
    // Keystore / relationship discovery tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_discover_keystore_path_returns_none_when_absent() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let path = pkg.discover_keystore_path().unwrap();
        assert!(
            path.is_none(),
            "No keystore relationship should return None"
        );
    }

    #[test]
    fn test_discover_keystore_path_returns_path_when_present() {
        let mut pkg = Package::open(minimal_3mf_with_keystore()).unwrap();
        let path = pkg.discover_keystore_path().unwrap();
        assert_eq!(path, Some("Metadata/keystore.xml".to_string()));
    }

    #[test]
    fn test_has_relationship_to_target_found() {
        let mut pkg = Package::open(minimal_3mf_with_thumbnail()).unwrap();
        let found = pkg
            .has_relationship_to_target(
                "Metadata/thumbnail.png",
                "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail",
                None,
            )
            .unwrap();
        assert!(found, "Should find the thumbnail relationship");
    }

    #[test]
    fn test_has_relationship_to_target_not_found() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let found = pkg
            .has_relationship_to_target(
                "Metadata/thumbnail.png",
                "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail",
                None,
            )
            .unwrap();
        assert!(
            !found,
            "Should not find thumbnail relationship in package without thumbnail"
        );
    }

    #[test]
    fn test_has_relationship_to_target_with_source_file_not_found() {
        // Source file has no associated .rels -> should return false gracefully
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let found = pkg
            .has_relationship_to_target(
                "3D/3dmodel.model",
                "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel",
                Some("3D/3dmodel.model"),
            )
            .unwrap();
        assert!(
            !found,
            "Should return false when the associated .rels file does not exist"
        );
    }

    #[test]
    fn test_validate_keystore_relationship_fails_when_absent() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let result = pkg.validate_keystore_relationship("Metadata/keystore.xml");
        assert!(
            result.is_err(),
            "Should fail when no keystore relationship exists"
        );
    }

    #[test]
    fn test_validate_keystore_relationship_succeeds_when_present() {
        let mut pkg = Package::open(minimal_3mf_with_keystore()).unwrap();
        assert!(
            pkg.validate_keystore_relationship("Metadata/keystore.xml")
                .is_ok(),
            "Should succeed when keystore relationship is present"
        );
    }

    #[test]
    fn test_validate_keystore_content_type_via_default_extension() {
        // Content types has Default Extension="xml" with keystore content type
        let mut pkg = Package::open(minimal_3mf_with_keystore()).unwrap();
        assert!(
            pkg.validate_keystore_content_type("Metadata/keystore.xml")
                .is_ok(),
            "Should accept keystore content type declared via Default Extension='xml'"
        );
    }

    #[test]
    fn test_validate_keystore_content_type_via_override() {
        let ct = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Override PartName=\"/Metadata/keystore.xml\" ContentType=\"application/vnd.ms-package.3dmanufacturing-keystore+xml\"/>\
</Types>";
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/keystore.xml\" Id=\"rel1\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2019/07/keystore\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", ct),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            (
                "Metadata/keystore.xml",
                b"<?xml version=\"1.0\"?><keystore/>",
            ),
        ]);
        let mut pkg = Package::open(cursor).unwrap();
        assert!(
            pkg.validate_keystore_content_type("Metadata/keystore.xml")
                .is_ok(),
            "Should accept keystore content type declared via Override PartName"
        );
    }

    #[test]
    fn test_validate_keystore_content_type_fails_when_absent() {
        let mut pkg = Package::open(minimal_3mf()).unwrap();
        let result = pkg.validate_keystore_content_type("Metadata/keystore.xml");
        assert!(
            result.is_err(),
            "Should fail when no keystore content type exists"
        );
    }

    // -----------------------------------------------------------------------
    // writer tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_create_package_with_thumbnail_no_thumbnail_data() {
        // Call create_package_with_thumbnail with None thumbnail -> should produce valid package
        let model_xml = std::str::from_utf8(MINIMAL_MODEL).unwrap();
        let buf =
            create_package_with_thumbnail(Cursor::new(Vec::new()), model_xml, None, None).unwrap();
        let mut pkg = Package::open(buf).unwrap();
        assert!(pkg.get_model().is_ok());
    }

    #[test]
    fn test_create_package_with_jpeg_thumbnail() {
        let model_xml = std::str::from_utf8(MINIMAL_MODEL).unwrap();
        let thumb_data = &[0xFFu8, 0xD8, 0xFF, 0xE0]; // first 4 bytes of JPEG SOI + APP0 marker
        let buf = create_package_with_thumbnail(
            Cursor::new(Vec::new()),
            model_xml,
            Some(thumb_data),
            Some("image/jpeg"),
        )
        .unwrap();
        // Package should open successfully
        assert!(Package::open(buf).is_ok());
    }

    #[test]
    fn test_package_constants() {
        assert_eq!(MODEL_PATH, "3D/3dmodel.model");
        assert_eq!(CONTENT_TYPES_PATH, "[Content_Types].xml");
    }

    #[test]
    fn test_package_from_empty_zip() {
        // Create an empty ZIP archive
        let buffer = Vec::new();
        let cursor = Cursor::new(buffer);
        let zip = ZipWriter::new(cursor);
        let cursor = zip.finish().unwrap();

        // Should fail validation because it's missing required files
        let result = Package::open(cursor);
        assert!(
            result.is_err(),
            "Expected package validation to fail for empty ZIP"
        );
    }

    #[test]
    fn test_percent_encoded_part_names() {
        // Create a 3MF file with percent-encoded part name in XML relationships
        // and UTF-8 character in ZIP file name (correct per OPC spec)
        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
        let options = SimpleFileOptions::default();

        // [Content_Types].xml
        zip.start_file("[Content_Types].xml", options).unwrap();
        zip.write_all(
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>
</Types>",
        )
        .unwrap();

        // _rels/.rels with percent-encoded target (%C3%86 = Æ)
        zip.start_file("_rels/.rels", options).unwrap();
        zip.write_all(
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">
  <Relationship Target=\"/2D/test%C3%86file.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>
</Relationships>",
        )
        .unwrap();

        // Actual ZIP file with UTF-8 character (Æ)
        zip.start_file("2D/testÆfile.model", options).unwrap();
        zip.write_all(
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<model unit=\"millimeter\" xml:lang=\"en-US\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\">
  <resources>
    <object id=\"1\" type=\"model\">
      <mesh>
        <vertices>
          <vertex x=\"0\" y=\"0\" z=\"0\"/>
          <vertex x=\"100\" y=\"0\" z=\"0\"/>
          <vertex x=\"0\" y=\"100\" z=\"0\"/>
        </vertices>
        <triangles>
          <triangle v1=\"0\" v2=\"1\" v3=\"2\"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid=\"1\"/>
  </build>
</model>",
        )
        .unwrap();

        let cursor = zip.finish().unwrap();

        // This should succeed: percent-encoded in XML, UTF-8 in ZIP
        let result = Package::open(cursor);
        assert!(
            result.is_ok(),
            "Package with percent-encoded part names should open successfully"
        );
    }

    #[test]
    fn test_utf8_in_xml_accepted_for_compatibility() {
        // Per OPC spec, non-ASCII should be percent-encoded in XML Target attributes.
        // However, for compatibility with real-world files (including official test suites),
        // we accept UTF-8 characters directly in the Target attribute.
        let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
        let options = SimpleFileOptions::default();

        zip.start_file("[Content_Types].xml", options).unwrap();
        zip.write_all(
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>
</Types>",
        )
        .unwrap();

        zip.start_file("_rels/.rels", options).unwrap();
        let rels = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">
  <Relationship Target=\"/2D/testÆfile.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>
</Relationships>";
        zip.write_all(rels.as_bytes()).unwrap();

        zip.start_file("2D/testÆfile.model", options).unwrap();
        zip.write_all(
            b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<model unit=\"millimeter\" xml:lang=\"en-US\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\">
  <resources>
    <object id=\"1\" type=\"model\">
      <mesh>
        <vertices>
          <vertex x=\"0\" y=\"0\" z=\"0\"/>
          <vertex x=\"100\" y=\"0\" z=\"0\"/>
          <vertex x=\"0\" y=\"100\" z=\"0\"/>
        </vertices>
        <triangles>
          <triangle v1=\"0\" v2=\"1\" v3=\"2\"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid=\"1\"/>
  </build>
</model>",
        )
        .unwrap();

        let cursor = zip.finish().unwrap();

        // This should now succeed for compatibility
        let result = Package::open(cursor);
        assert!(
            result.is_ok(),
            "Package with UTF-8 characters in XML should be accepted for compatibility"
        );
    }

    // -----------------------------------------------------------------------
    // Lenient mode tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_lenient_accepts_nonstandard_thumbnail_rel_type() {
        // Simulates BambuLab/OrcaSlicer files that use a non-standard thumbnail relationship type
        let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"rel1\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\
</Relationships>";
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC,
            0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let cursor = make_zip(&[
            ("[Content_Types].xml", content_types),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("Metadata/thumbnail.png", png),
        ]);

        // Strict mode should reject this
        let strict_result = Package::open(cursor.clone());
        assert!(
            strict_result.is_err(),
            "Strict mode should reject non-standard thumbnail relationship type"
        );

        // Lenient mode should accept it
        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_ok(),
            "Lenient mode should accept non-standard thumbnail relationship type"
        );
    }

    #[test]
    fn test_lenient_accepts_duplicate_relationship_ids() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/something.xml\" Id=\"rel0\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
            ("Metadata/something.xml", b"<root/>"),
        ]);

        let strict_result = Package::open(cursor.clone());
        assert!(
            strict_result.is_err(),
            "Strict mode should reject duplicate relationship IDs"
        );

        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_ok(),
            "Lenient mode should accept duplicate relationship IDs"
        );
    }

    #[test]
    fn test_lenient_accepts_id_starting_with_digit() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"0rel\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);

        let strict_result = Package::open(cursor.clone());
        assert!(
            strict_result.is_err(),
            "Strict mode should reject ID starting with digit"
        );

        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_ok(),
            "Lenient mode should accept ID starting with digit"
        );
    }

    #[test]
    fn test_lenient_accepts_duplicate_content_type_defaults() {
        let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", content_types),
            ("_rels/.rels", MINIMAL_RELS),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);

        let strict_result = Package::open(cursor.clone());
        assert!(
            strict_result.is_err(),
            "Strict mode should reject duplicate content type defaults"
        );

        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_ok(),
            "Lenient mode should accept duplicate content type defaults"
        );
    }

    #[test]
    fn test_lenient_accepts_nonexistent_relationship_target() {
        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/missing.xml\" Id=\"rel1\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\"/>\
</Relationships>";
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", MINIMAL_MODEL),
        ]);

        let strict_result = Package::open(cursor.clone());
        assert!(
            strict_result.is_err(),
            "Strict mode should reject relationship pointing to non-existent file"
        );

        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_ok(),
            "Lenient mode should accept relationship pointing to non-existent file"
        );
    }

    #[test]
    fn test_lenient_still_rejects_missing_model() {
        // Even in lenient mode, critical model-related errors must still fail
        let cursor = make_zip(&[
            ("[Content_Types].xml", MINIMAL_CONTENT_TYPES),
            ("_rels/.rels", MINIMAL_RELS),
            // Missing 3D/3dmodel.model
        ]);

        let lenient_result = Package::open_lenient(cursor, true);
        assert!(
            lenient_result.is_err(),
            "Lenient mode should still reject packages missing the model file"
        );
    }

    #[test]
    fn test_lenient_parserconfig_integration() {
        // Verify that parse_3mf_with_config properly threads SpecConformance through
        use crate::model::{ParserConfig, SpecConformance};
        use crate::parser::parse_3mf_with_config;

        let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
  <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
  <Relationship Target=\"/Metadata/thumbnail.png\" Id=\"rel1\" Type=\"http://schemas.bambulab.com/package/2021/cover-thumbnail-middle\"/>\
</Relationships>";
        let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
  <Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
  <Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
  <Default Extension=\"png\" ContentType=\"image/png\"/>\
</Types>";
        // A minimal model with one object (a single triangle) to pass model validation
        let model = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<model unit=\"millimeter\" xml:lang=\"en-US\" \
xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\">\
  <resources>\
    <object id=\"1\" type=\"model\">\
      <mesh>\
        <vertices>\
          <vertex x=\"0\" y=\"0\" z=\"0\"/>\
          <vertex x=\"1\" y=\"0\" z=\"0\"/>\
          <vertex x=\"0\" y=\"1\" z=\"0\"/>\
          <vertex x=\"0\" y=\"0\" z=\"1\"/>\
        </vertices>\
        <triangles>\
          <triangle v1=\"0\" v2=\"1\" v3=\"2\"/>\
          <triangle v1=\"0\" v2=\"1\" v3=\"3\"/>\
          <triangle v1=\"0\" v2=\"2\" v3=\"3\"/>\
          <triangle v1=\"1\" v2=\"2\" v3=\"3\"/>\
        </triangles>\
      </mesh>\
    </object>\
  </resources>\
  <build><item objectid=\"1\"/></build>\
</model>";
        let png: &[u8] = &[
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00,
            0x00, 0x90, 0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, 0x08,
            0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xE2, 0x21, 0xBC,
            0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        let cursor = make_zip(&[
            ("[Content_Types].xml", content_types),
            ("_rels/.rels", rels),
            ("3D/3dmodel.model", model),
            ("Metadata/thumbnail.png", png),
        ]);

        // Strict config should reject
        let config = ParserConfig::with_all_extensions();
        assert!(config.spec_conformance() == SpecConformance::Strict);
        let strict_result = parse_3mf_with_config(cursor.clone(), config);
        assert!(strict_result.is_err());

        // Lenient config should accept
        let config =
            ParserConfig::with_all_extensions().with_spec_conformance(SpecConformance::Lenient);
        assert!(config.is_lenient());
        let lenient_result = parse_3mf_with_config(cursor, config);
        assert!(
            lenient_result.is_ok(),
            "parse_3mf_with_config with Lenient should accept non-standard thumbnail: {:?}",
            lenient_result.err()
        );
    }
}