typst-pack 0.5.0

Portable single-file packs of Typst projects: sources, resources, packages, and fonts
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
//! OpenDAL read for Pack Assembly inputs.
//!
//! # Complete Pack Assembly
//!
//! The storage operations are caller-polled async operations. Their completed,
//! owned values compose through the existing synchronous Pack Creation loop:
//!
//! ```no_run
//! # #[cfg(feature = "package-reading")]
//! # mod complete {
//! use std::collections::HashSet;
//!
//! use typst::foundations::Dict;
//! use typst_pack::opendal::{Location, OperatorBindings};
//! use typst_pack::opendal::pack_assembly::{
//!     FontReadEntry, FontReadLimits, FontReadRequest, FontSource,
//!     PackageReadLimits, PackageReadRequest, PackageTreeSource,
//!     ProjectReadEntry, ProjectReadLimits, ProjectReadRequest,
//!     read_fonts, read_package, read_project, insert_read_package,
//! };
//! use typst_pack::opendal::write::{
//!     PackageCacheArchiveWriteRequest, write_package_cache_archive,
//! };
//! use typst_pack::{
//!     DiscoverySpecification, DocumentTime, FontCatalog, FontCatalogEntry, FontContainer,
//!     FontDisposition, Pack, PackCreationInput, PackCreationOutcome,
//!     PackageReadFailures, PackageCatalog, PackageDisposition,
//!     PackageExpansionLimits, ProjectSnapshotAssembly, TypstTarget, create,
//! };
//!
//! async fn assemble(bindings: &OperatorBindings) -> Result<Pack, Box<dyn std::error::Error>> {
//!     let project_request = ProjectReadRequest::new(
//!         "project:/sources/document/".parse::<Location>()?,
//!         ProjectReadLimits::reference_v1(),
//!     )?;
//!     let (_, project_entries) = read_project(bindings, &project_request).await?.into_parts();
//!     let project = ProjectSnapshotAssembly::new("main.typ").assemble(
//!         project_entries.into_iter().map(ProjectReadEntry::into_parts),
//!     )?;
//!
//!     let font_request = FontReadRequest::new(
//!         [FontSource::new(
//!             "fonts:/catalog/".parse::<Location>()?,
//!             FontDisposition::Embedded,
//!         )],
//!         FontReadLimits::reference_v1(),
//!     )?;
//!     let (_, font_entries) = read_fonts(bindings, &font_request).await?.into_parts();
//!     let mut fonts = FontCatalog::new();
//!     for entry in font_entries {
//!         let (_, _, _, disposition, bytes) = FontReadEntry::into_parts(entry);
//!         fonts.push(FontCatalogEntry::new(FontContainer::new(bytes)?, disposition));
//!     }
//!
//!     let tree_source = PackageTreeSource::new("packages:/trees/".parse::<Location>()?);
//!     let archive_cache = "packages:/cache/".parse::<Location>()?;
//!     let registry = "registry:/packages/".parse::<Location>()?;
//!     let discovery = DiscoverySpecification::new(
//!         TypstTarget::Paged,
//!         Dict::new(),
//!         DocumentTime::Absent,
//!         [],
//!     )?;
//!     let mut packages = PackageCatalog::new();
//!     let mut failures = PackageReadFailures::new();
//!     let mut attempted = HashSet::new();
//!
//!     loop {
//!         match create(PackCreationInput {
//!             project: &project,
//!             packages: &packages,
//!             fonts: &fonts,
//!             package_failures: &failures,
//!             discovery: &discovery,
//!             metadata: None,
//!         })? {
//!             PackCreationOutcome::Created { pack, warnings: _ } => return Ok(pack),
//!             PackCreationOutcome::MissingPackageSpecifications(missing) => {
//!                 for spec in missing {
//!                     if !attempted.insert(spec.to_string()) {
//!                         return Err("Pack Creation repeated an attempted specification".into());
//!                     }
//!                     let request = PackageReadRequest::new(
//!                         spec,
//!                         [tree_source.clone()],
//!                         Some(archive_cache.clone()),
//!                         Some(registry.clone()),
//!                         PackageReadLimits::reference_v1(),
//!                     )?;
//!                     let read = read_package(bindings, &request).await?;
//!                     let insertion = insert_read_package(
//!                         &mut packages,
//!                         &mut failures,
//!                         read,
//!                         PackageDisposition::Embedded,
//!                         PackageExpansionLimits::reference_v1(),
//!                     );
//!                     match insertion {
//!                         Ok(Some(residue)) => {
//!                             let write = PackageCacheArchiveWriteRequest::new(
//!                                 residue.destination().clone(),
//!                             )?;
//!                             let _cache_result = write_package_cache_archive(
//!                                 bindings,
//!                                 &write,
//!                                 residue.bytes(),
//!                             ).await;
//!                             // Cache failure is separate evidence and does not
//!                             // invalidate the inserted Package Tree.
//!                         }
//!                         Ok(None) => {}
//!                         // Insertion retained the mapped Package Read Failure.
//!                         // Resume so Dependency Discovery can attach it to the import.
//!                         Err(_error) => {}
//!                     }
//!                 }
//!             }
//!         }
//!     }
//! }
//! # }
//! ```

mod package;

pub use package::*;

use std::fmt;

use super::read::recursive::{
    RecursiveReadLimits, RecursiveReadOperation, RecursiveReadResource, RecursiveReadSelection,
    RecursiveSurveyIssue, RecursiveSurveyIssueKind, read_recursive_prefix, read_recursive_prefixes,
};
use super::{BoxError, Location, LocationRoleError, OperatorResolver};
use crate::FontDisposition;
use crate::limits::{LimitError, Limits, ResourceKind};
use crate::redacted_error::RedactedError;

fn aggregate_issue_message<T: fmt::Display>(issues: &[T], summary: &str) -> String {
    if let [issue] = issues {
        issue.to_string()
    } else {
        format!("{summary} with {} issue(s)", issues.len())
    }
}

fn failed_path_context(path: Option<&str>) -> String {
    path.map(|path| format!(" while reading object operation path {path:?}"))
        .unwrap_or_default()
}

/// Named finite ceilings for one OpenDAL Project Read.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProjectReadCeilings {
    pub listed_entries: u64,
    pub listed_path_bytes: u64,
    pub total_listed_path_bytes: u64,
    pub selected_files: u64,
    pub object_bytes: u64,
    pub total_bytes: u64,
}

impl ProjectReadCeilings {
    /// The first-party version-1 Project Read profile.
    pub const fn reference_v1() -> Self {
        Self {
            listed_entries: 1_000_000,
            listed_path_bytes: 64 * 1024,
            total_listed_path_bytes: 256 * 1024 * 1024,
            selected_files: 100_000,
            object_bytes: 256 * 1024 * 1024,
            total_bytes: 2 * 1024 * 1024 * 1024,
        }
    }
}

/// A resource bounded during OpenDAL Project Read.
pub type ProjectReadResource = ResourceKind<9>;

#[allow(non_upper_case_globals)]
impl ResourceKind<9> {
    pub const ListedEntries: Self = Self::new(0);
    pub const ListedPathBytes: Self = Self::new(1);
    pub const TotalListedPathBytes: Self = Self::new(2);
    pub const SelectedFiles: Self = Self::new(3);
    pub const ObjectBytes: Self = Self::new(4);
    pub const TotalBytes: Self = Self::new(5);
}

/// Mandatory finite limits for OpenDAL Project Read.
pub type ProjectReadLimits = Limits<ProjectReadResource>;

impl Limits<ProjectReadResource> {
    /// Validates all named read ceilings.
    #[track_caller]
    pub fn new(ceilings: ProjectReadCeilings) -> Self {
        let limits = Self::from_ceilings([
            ceilings.listed_entries,
            ceilings.listed_path_bytes,
            ceilings.total_listed_path_bytes,
            ceilings.selected_files,
            ceilings.object_bytes,
            ceilings.total_bytes,
            0,
        ])
        .assert_probe_resources([
            ProjectReadResource::ListedEntries,
            ProjectReadResource::ListedPathBytes,
            ProjectReadResource::TotalListedPathBytes,
            ProjectReadResource::SelectedFiles,
            ProjectReadResource::ObjectBytes,
            ProjectReadResource::TotalBytes,
        ]);
        assert!(
            ceilings.object_bytes <= ceilings.total_bytes,
            "the ObjectBytes ceiling {} exceeds the TotalBytes ceiling {}",
            ceilings.object_bytes,
            ceilings.total_bytes
        );
        limits
    }

    /// The validated first-party version-1 Project Read limits.
    pub const fn reference_v1() -> Self {
        Self::from_ceilings([
            1_000_000,
            64 * 1024,
            256 * 1024 * 1024,
            100_000,
            256 * 1024 * 1024,
            2 * 1024 * 1024 * 1024,
            0,
        ])
    }

    pub const fn listed_entries(&self) -> u64 {
        self.ceilings[0]
    }

    pub const fn listed_path_bytes(&self) -> u64 {
        self.ceilings[1]
    }

    pub const fn total_listed_path_bytes(&self) -> u64 {
        self.ceilings[2]
    }

    pub const fn selected_files(&self) -> u64 {
        self.ceilings[3]
    }

    pub const fn object_bytes(&self) -> u64 {
        self.ceilings[4]
    }

    pub const fn total_bytes(&self) -> u64 {
        self.ceilings[5]
    }
}

/// Project Read exceeded or could not account for a mandatory limit.
pub type ProjectReadLimitError = LimitError<ProjectReadResource>;

/// A validated request to read every yielded file below one prefix.
#[derive(Clone, Debug)]
pub struct ProjectReadRequest {
    source: Location,
    limits: ProjectReadLimits,
}

impl ProjectReadRequest {
    /// Validates a prefix source and retains its mandatory limits.
    pub fn new(
        source: Location,
        limits: ProjectReadLimits,
    ) -> Result<Self, ProjectReadRequestError> {
        if let Err(role_error) = source.require_prefix() {
            return Err(ProjectReadRequestError::InvalidSourceRole {
                location: source,
                source: role_error,
            });
        }
        Ok(Self { source, limits })
    }

    /// The normalized project prefix.
    pub fn source(&self) -> &Location {
        &self.source
    }

    /// The mandatory finite Project Read limits.
    pub const fn limits(&self) -> ProjectReadLimits {
        self.limits
    }
}

/// A reason a Project Read request is invalid.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ProjectReadRequestError {
    #[error("project source {location} is not a prefix: {source}")]
    InvalidSourceRole {
        location: Location,
        #[source]
        source: LocationRoleError,
    },
}

/// One exact path-and-byte entry read below a project prefix.
pub struct ProjectReadEntry {
    relative_path: String,
    bytes: Vec<u8>,
}

impl ProjectReadEntry {
    /// The operation path relative to the requested prefix.
    pub fn relative_path(&self) -> &str {
        &self.relative_path
    }

    /// The exact bytes observed by the completed object read.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// The read byte length.
    pub fn len(&self) -> u64 {
        self.bytes.len() as u64
    }

    /// Whether this read object was empty.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Recovers the owned path and exact bytes for Project Snapshot assembly.
    pub fn into_parts(self) -> (String, Vec<u8>) {
        (self.relative_path, self.bytes)
    }
}

impl fmt::Debug for ProjectReadEntry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProjectReadEntry")
            .field("relative_path", &self.relative_path)
            .field("byte_length", &self.bytes.len())
            .finish()
    }
}

/// Exact entries read from one project prefix.
pub struct ProjectRead {
    source: Location,
    entries: Vec<ProjectReadEntry>,
}

impl ProjectRead {
    /// The normalized prefix from which entries were read.
    pub fn source(&self) -> &Location {
        &self.source
    }

    /// Read entries in relative operation-path order.
    pub fn entries(&self) -> &[ProjectReadEntry] {
        &self.entries
    }

    /// Recovers the source and owned entries for Project Snapshot assembly.
    pub fn into_parts(self) -> (Location, Vec<ProjectReadEntry>) {
        (self.source, self.entries)
    }
}

impl fmt::Debug for ProjectRead {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProjectRead")
            .field("source", &self.source)
            .field("entries", &self.entries)
            .finish()
    }
}

/// An unsupported yielded OpenDAL entry kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ProjectReadEntryKind {
    Unknown,
}

/// One structural issue found while surveying a project prefix.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum ProjectReadIssue {
    #[error("listed operation path {operation_path:?} is outside the project prefix")]
    ListedPathOutsidePrefix { operation_path: String },
    #[error("listed operation path {operation_path:?} is a prefix marker where a file is required")]
    PrefixMarkerWhereFileRequired { operation_path: String },
    #[error("listed operation path {operation_path:?} has an empty relative path")]
    EmptyRelativeOperationPath { operation_path: String },
    #[error("listed operation path {operation_path:?} is not a valid relative operation path")]
    InvalidRelativeOperationPath { operation_path: String },
    #[error("listed object {operation_path:?} was yielded more than once")]
    DuplicateListedObject { operation_path: String },
    #[error("listed operation path {operation_path:?} has unsupported kind {kind:?}")]
    UnsupportedEntryKind {
        operation_path: String,
        kind: ProjectReadEntryKind,
    },
}

/// The nonempty canonical set of structural project survey issues.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error(
    "{message}",
    message = aggregate_issue_message(.issues.as_slice(), "project survey failed")
)]
pub struct ProjectReadSurveyError {
    issues: Vec<ProjectReadIssue>,
}

impl ProjectReadSurveyError {
    /// Every independently detectable issue in canonical order.
    pub fn issues(&self) -> &[ProjectReadIssue] {
        &self.issues
    }
}

/// Reads every file entry yielded below one project prefix.
///
/// Directory markers are ignored. `.typkignore` is an ordinary file; Project
/// Snapshot assembly remains authoritative for canonical project paths,
/// collisions, `.typk` exclusion, entrypoint presence, bytes, and ordering.
/// The listing is one observation, not a storage snapshot or coexistence claim.
///
/// ```no_run
/// use typst::foundations::Dict;
/// use typst_pack::{
///     DiscoverySpecification, DocumentTime, FontCatalog, PackCreationInput,
///     PackageReadFailures, PackageCatalog, ProjectSnapshotAssembly,
///     TypstTarget, create,
/// };
/// use typst_pack::opendal::OperatorBindings;
/// use typst_pack::opendal::pack_assembly::{
///     ProjectReadEntry, ProjectReadRequest, read_project,
/// };
///
/// async fn read_and_create(
///     bindings: &OperatorBindings,
///     request: &ProjectReadRequest,
/// ) -> Result<(), Box<dyn std::error::Error>> {
///     let (_, entries) = read_project(bindings, request).await?.into_parts();
///     let project = ProjectSnapshotAssembly::new("main.typ").assemble(
///         entries.into_iter().map(ProjectReadEntry::into_parts),
///     )?;
///     let packages = PackageCatalog::new();
///     let fonts = FontCatalog::new();
///     let package_failures = PackageReadFailures::new();
///     let discovery = DiscoverySpecification::new(
///         TypstTarget::Paged,
///         Dict::new(),
///         DocumentTime::Absent,
///         [],
///     )?;
///     let _outcome = create(PackCreationInput {
///         project: &project,
///         packages: &packages,
///         fonts: &fonts,
///         package_failures: &package_failures,
///         discovery: &discovery,
///         metadata: None,
///     })?;
///     Ok(())
/// }
/// ```
#[allow(clippy::result_large_err)]
pub async fn read_project<R: OperatorResolver + ?Sized>(
    resolver: &R,
    request: &ProjectReadRequest,
) -> Result<ProjectRead, ProjectReadError> {
    let source = request.source().clone();
    let entries = read_recursive_prefix(
        resolver,
        request.source(),
        RecursiveReadSelection::AllFiles,
        request.limits().into(),
        &ProjectReadOperation {
            source_location: request.source(),
        },
    )
    .await?
    .into_iter()
    .map(|object| ProjectReadEntry {
        relative_path: object.relative_path,
        bytes: object.bytes,
    })
    .collect();

    Ok(ProjectRead { source, entries })
}

/// A failure while reading a project through OpenDAL.
///
/// This error's own `Display` and `Debug` omit native resolver and OpenDAL
/// messages. Rendering its complete source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "Project Read failed for binding {binding} at prefix operation path {operation_path:?}{failed_path}: {cause}",
    binding = .source_location.binding(),
    operation_path = .source_location.operation_path(),
    failed_path = failed_path_context(.failed_path.as_deref()),
)]
pub struct ProjectReadError {
    source_location: Location,
    failed_path: Option<String>,
    #[source]
    cause: RedactedError<ProjectReadErrorCause>,
}

impl ProjectReadError {
    /// The normalized project prefix whose read failed.
    pub fn source_location(&self) -> &Location {
        &self.source_location
    }

    /// The selected object's operation path when one object read failed.
    pub fn failed_path(&self) -> Option<&str> {
        self.failed_path.as_deref()
    }

    /// The typed cause of this failure.
    pub fn cause(&self) -> &ProjectReadErrorCause {
        self.cause.inner()
    }

    fn new(
        source_location: &Location,
        failed_path: Option<String>,
        cause: ProjectReadErrorCause,
    ) -> Self {
        Self {
            source_location: source_location.clone(),
            failed_path,
            cause: RedactedError::new(cause),
        }
    }
}

/// The typed cause of an OpenDAL Project Read failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProjectReadErrorCause {
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("required listing or read capability is unsupported")]
    UnsupportedCapabilities {
        list: bool,
        list_with_recursive: bool,
        read: bool,
    },
    #[error("the recursive listing failed")]
    List(#[source] ::opendal::Error),
    #[error("a listed object read failed")]
    Read(#[source] ::opendal::Error),
    #[error("a listed object was absent when read")]
    ListedObjectAbsent(#[source] ::opendal::Error),
    #[error("the completed listing had structural issues")]
    Structural(#[source] ProjectReadSurveyError),
    #[error("a Project Read limit failed")]
    Limit(#[source] ProjectReadLimitError),
}

struct ProjectReadOperation<'a> {
    source_location: &'a Location,
}

impl RecursiveReadOperation for ProjectReadOperation<'_> {
    type Error = ProjectReadError;

    fn invalid_location_role(&self, _: usize, _: LocationRoleError) -> ProjectReadError {
        unreachable!("ProjectReadRequest validates the prefix role")
    }

    fn resolve_operator(&self, _: usize, source: BoxError) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::ResolveOperator(source),
        )
    }

    fn unsupported_capabilities(
        &self,
        _: usize,
        list: bool,
        list_with_recursive: bool,
        read: bool,
    ) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::UnsupportedCapabilities {
                list,
                list_with_recursive,
                read,
            },
        )
    }

    fn list(&self, _: usize, source: ::opendal::Error) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::List(source),
        )
    }

    fn read(&self, _: usize, operation_path: String, source: ::opendal::Error) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            Some(operation_path),
            ProjectReadErrorCause::Read(source),
        )
    }

    fn listed_object_absent(
        &self,
        _: usize,
        operation_path: String,
        source: ::opendal::Error,
    ) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            Some(operation_path),
            ProjectReadErrorCause::ListedObjectAbsent(source),
        )
    }

    fn structural(&self, _: usize, issues: Vec<RecursiveSurveyIssue>) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::Structural(ProjectReadSurveyError {
                issues: issues.into_iter().map(map_issue).collect(),
            }),
        )
    }

    fn limit(
        &self,
        _: usize,
        resource: RecursiveReadResource,
        ceiling: u64,
        _: u64,
    ) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::Limit(ProjectReadLimitError::exceeded(
                map_resource(resource),
                ceiling,
            )),
        )
    }

    fn accounting_overflow(&self, _: usize, resource: RecursiveReadResource) -> ProjectReadError {
        ProjectReadError::new(
            self.source_location,
            None,
            ProjectReadErrorCause::Limit(ProjectReadLimitError::AccountingOverflow {
                resource: map_resource(resource),
            }),
        )
    }
}

impl From<ProjectReadLimits> for RecursiveReadLimits {
    fn from(limits: ProjectReadLimits) -> Self {
        Self::new(
            limits.listed_entries(),
            limits.listed_path_bytes(),
            limits.total_listed_path_bytes(),
            limits.selected_files(),
            limits.object_bytes(),
            limits.total_bytes(),
        )
    }
}

fn map_resource(resource: RecursiveReadResource) -> ProjectReadResource {
    match resource {
        RecursiveReadResource::ListedEntries => ProjectReadResource::ListedEntries,
        RecursiveReadResource::ListedPathBytes => ProjectReadResource::ListedPathBytes,
        RecursiveReadResource::TotalListedPathBytes => ProjectReadResource::TotalListedPathBytes,
        RecursiveReadResource::SelectedObjects => ProjectReadResource::SelectedFiles,
        RecursiveReadResource::ObjectBytes => ProjectReadResource::ObjectBytes,
        RecursiveReadResource::TotalBytes => ProjectReadResource::TotalBytes,
        _ => unreachable!("unknown recursive read resource"),
    }
}

fn map_issue(issue: RecursiveSurveyIssue) -> ProjectReadIssue {
    let operation_path = issue.operation_path;
    match issue.kind {
        RecursiveSurveyIssueKind::ListedPathOutsidePrefix => {
            ProjectReadIssue::ListedPathOutsidePrefix { operation_path }
        }
        RecursiveSurveyIssueKind::PrefixMarkerWhereFileRequired => {
            ProjectReadIssue::PrefixMarkerWhereFileRequired { operation_path }
        }
        RecursiveSurveyIssueKind::EmptyRelativeOperationPath => {
            ProjectReadIssue::EmptyRelativeOperationPath { operation_path }
        }
        RecursiveSurveyIssueKind::InvalidRelativeOperationPath => {
            ProjectReadIssue::InvalidRelativeOperationPath { operation_path }
        }
        RecursiveSurveyIssueKind::DuplicateListedObject => {
            ProjectReadIssue::DuplicateListedObject { operation_path }
        }
        RecursiveSurveyIssueKind::UnsupportedEntryKind => ProjectReadIssue::UnsupportedEntryKind {
            operation_path,
            kind: ProjectReadEntryKind::Unknown,
        },
    }
}

/// Named finite ceilings for one OpenDAL Font Read.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FontReadCeilings {
    pub listed_entries: u64,
    pub listed_path_bytes: u64,
    pub total_listed_path_bytes: u64,
    pub selected_containers: u64,
    pub container_bytes: u64,
    pub total_bytes: u64,
}

impl FontReadCeilings {
    /// The first-party version-1 Font Read profile.
    pub const fn reference_v1() -> Self {
        Self {
            listed_entries: 100_000,
            listed_path_bytes: 64 * 1024,
            total_listed_path_bytes: 64 * 1024 * 1024,
            selected_containers: 16_384,
            container_bytes: 256 * 1024 * 1024,
            total_bytes: 2 * 1024 * 1024 * 1024,
        }
    }
}

/// A resource bounded across one OpenDAL Font Read.
pub type FontReadResource = ResourceKind<10>;

#[allow(non_upper_case_globals)]
impl ResourceKind<10> {
    pub const ListedEntries: Self = Self::new(0);
    pub const ListedPathBytes: Self = Self::new(1);
    pub const TotalListedPathBytes: Self = Self::new(2);
    pub const SelectedContainers: Self = Self::new(3);
    pub const ContainerBytes: Self = Self::new(4);
    pub const TotalBytes: Self = Self::new(5);
}

/// Mandatory finite limits for OpenDAL Font Read.
pub type FontReadLimits = Limits<FontReadResource>;

impl Limits<FontReadResource> {
    /// Validates all named read ceilings.
    #[track_caller]
    pub fn new(ceilings: FontReadCeilings) -> Self {
        let limits = Self::from_ceilings([
            ceilings.listed_entries,
            ceilings.listed_path_bytes,
            ceilings.total_listed_path_bytes,
            ceilings.selected_containers,
            ceilings.container_bytes,
            ceilings.total_bytes,
            0,
        ])
        .assert_probe_resources([
            FontReadResource::ListedEntries,
            FontReadResource::ListedPathBytes,
            FontReadResource::TotalListedPathBytes,
            FontReadResource::SelectedContainers,
            FontReadResource::ContainerBytes,
            FontReadResource::TotalBytes,
        ]);
        assert!(
            ceilings.container_bytes <= ceilings.total_bytes,
            "the ContainerBytes ceiling {} exceeds the TotalBytes ceiling {}",
            ceilings.container_bytes,
            ceilings.total_bytes
        );
        limits
    }

    /// The validated first-party version-1 Font Read limits.
    pub const fn reference_v1() -> Self {
        Self::from_ceilings([
            100_000,
            64 * 1024,
            64 * 1024 * 1024,
            16_384,
            256 * 1024 * 1024,
            2 * 1024 * 1024 * 1024,
            0,
        ])
    }

    pub const fn listed_entries(&self) -> u64 {
        self.ceilings[0]
    }

    pub const fn listed_path_bytes(&self) -> u64 {
        self.ceilings[1]
    }

    pub const fn total_listed_path_bytes(&self) -> u64 {
        self.ceilings[2]
    }

    pub const fn selected_containers(&self) -> u64 {
        self.ceilings[3]
    }

    pub const fn container_bytes(&self) -> u64 {
        self.ceilings[4]
    }

    pub const fn total_bytes(&self) -> u64 {
        self.ceilings[5]
    }
}

/// Font Read exceeded or could not account for a mandatory limit.
pub type FontReadLimitError = LimitError<FontReadResource>;

/// One explicitly configured OpenDAL prefix of Font Containers.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FontSource {
    source: Location,
    disposition: FontDisposition,
}

impl FontSource {
    /// Associates one prefix with the disposition of every selected container.
    pub fn new(source: Location, disposition: FontDisposition) -> Self {
        Self {
            source,
            disposition,
        }
    }

    /// The normalized Font Container prefix.
    pub fn source(&self) -> &Location {
        &self.source
    }

    /// The disposition every selected container from this source carries.
    pub const fn disposition(&self) -> FontDisposition {
        self.disposition
    }
}

/// A validated request to read caller-ordered OpenDAL font prefixes.
#[derive(Clone, Debug)]
pub struct FontReadRequest {
    sources: Vec<FontSource>,
    limits: FontReadLimits,
}

impl FontReadRequest {
    /// Validates every source role before accepting the request.
    pub fn new(
        sources: impl IntoIterator<Item = FontSource>,
        limits: FontReadLimits,
    ) -> Result<Self, FontReadRequestRejection> {
        let sources = sources.into_iter().collect::<Vec<_>>();
        let issues = sources
            .iter()
            .enumerate()
            .filter_map(|(source_index, configured)| {
                configured.source.require_prefix().err().map(|source| {
                    FontReadRequestIssue::InvalidSourceRole {
                        source_index,
                        location: configured.source.clone(),
                        source,
                    }
                })
            })
            .collect::<Vec<_>>();
        if !issues.is_empty() {
            return Err(FontReadRequestRejection { issues });
        }
        Ok(Self { sources, limits })
    }

    /// Font sources in caller order.
    pub fn sources(&self) -> &[FontSource] {
        &self.sources
    }

    /// The mandatory finite limits shared across every configured source.
    pub const fn limits(&self) -> FontReadLimits {
        self.limits
    }
}

/// Every invalid source role in a rejected Font Read request.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error(
    "{message}",
    message = aggregate_issue_message(.issues.as_slice(), "Font Read request rejected")
)]
pub struct FontReadRequestRejection {
    issues: Vec<FontReadRequestIssue>,
}

impl FontReadRequestRejection {
    /// Invalid source roles in caller source order.
    pub fn issues(&self) -> &[FontReadRequestIssue] {
        &self.issues
    }
}

/// One invalid source role in a Font Read request.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum FontReadRequestIssue {
    #[error("font source {source_index} at {location} is not a prefix: {source}")]
    InvalidSourceRole {
        source_index: usize,
        location: Location,
        #[source]
        source: LocationRoleError,
    },
}

/// One exact Font Container selected and read from a configured source.
pub struct FontReadEntry {
    source_index: usize,
    source: Location,
    relative_path: String,
    disposition: FontDisposition,
    bytes: Vec<u8>,
}

impl FontReadEntry {
    /// The configured source's caller-order index.
    pub fn source_index(&self) -> usize {
        self.source_index
    }

    /// The normalized prefix from which this entry was read.
    pub fn source(&self) -> &Location {
        &self.source
    }

    /// The selected operation path relative to its source prefix.
    pub fn relative_path(&self) -> &str {
        &self.relative_path
    }

    /// The explicit disposition inherited from the configured source.
    pub const fn disposition(&self) -> FontDisposition {
        self.disposition
    }

    /// The exact bytes observed by the completed object read.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// The read byte length.
    pub fn len(&self) -> u64 {
        self.bytes.len() as u64
    }

    /// Whether this read container is empty.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Recovers all owned source evidence and exact bytes.
    pub fn into_parts(self) -> (usize, Location, String, FontDisposition, Vec<u8>) {
        (
            self.source_index,
            self.source,
            self.relative_path,
            self.disposition,
            self.bytes,
        )
    }
}

impl fmt::Debug for FontReadEntry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("FontReadEntry")
            .field("source_index", &self.source_index)
            .field("source", &self.source)
            .field("relative_path", &self.relative_path)
            .field("disposition", &self.disposition)
            .field("byte_length", &self.bytes.len())
            .finish()
    }
}

/// Exact Font Containers read from caller-ordered sources.
pub struct FontRead {
    sources: Vec<FontSource>,
    entries: Vec<FontReadEntry>,
}

impl FontRead {
    /// Configured font sources in caller order.
    pub fn sources(&self) -> &[FontSource] {
        &self.sources
    }

    /// Read entries in source order, then relative operation-path order.
    pub fn entries(&self) -> &[FontReadEntry] {
        &self.entries
    }

    /// Recovers the configured sources and exact read entries.
    pub fn into_parts(self) -> (Vec<FontSource>, Vec<FontReadEntry>) {
        (self.sources, self.entries)
    }
}

impl fmt::Debug for FontRead {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("FontRead")
            .field("sources", &self.sources)
            .field("entries", &self.entries)
            .finish()
    }
}

/// An unsupported yielded OpenDAL entry kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FontReadEntryKind {
    Unknown,
}

/// One structural issue found while surveying configured font prefixes.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum FontReadIssue {
    #[error(
        "font source {source_index} listed operation path {operation_path:?} outside its prefix"
    )]
    ListedPathOutsidePrefix {
        source_index: usize,
        operation_path: String,
    },
    #[error(
        "font source {source_index} listed operation path {operation_path:?} as a prefix marker where a file is required"
    )]
    PrefixMarkerWhereFileRequired {
        source_index: usize,
        operation_path: String,
    },
    #[error(
        "font source {source_index} listed operation path {operation_path:?} with an empty relative path"
    )]
    EmptyRelativeOperationPath {
        source_index: usize,
        operation_path: String,
    },
    #[error("font source {source_index} listed invalid relative operation path {operation_path:?}")]
    InvalidRelativeOperationPath {
        source_index: usize,
        operation_path: String,
    },
    #[error("font source {source_index} listed object {operation_path:?} more than once")]
    DuplicateListedObject {
        source_index: usize,
        operation_path: String,
    },
    #[error(
        "font source {source_index} listed operation path {operation_path:?} with unsupported kind {kind:?}"
    )]
    UnsupportedEntryKind {
        source_index: usize,
        operation_path: String,
        kind: FontReadEntryKind,
    },
}

/// The nonempty canonical set of structural font survey issues.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error(
    "{message}",
    message = aggregate_issue_message(.issues.as_slice(), "font survey failed")
)]
pub struct FontReadSurveyError {
    issues: Vec<FontReadIssue>,
}

impl FontReadSurveyError {
    /// Every independently detectable issue in source and path order.
    pub fn issues(&self) -> &[FontReadIssue] {
        &self.issues
    }
}

/// Reads suffix-selected Font Containers from caller-ordered prefixes.
///
/// `.ttf`, `.ttc`, `.otf`, and `.otc` suffixes are matched
/// case-insensitively. Directory markers and non-font entries are ignored. All
/// selected entries come only from completed listing observations; those
/// observations make no storage snapshot or coexistence claim.
///
/// ```no_run
/// use typst_pack::{
///     DiscoverySpecification, FontCatalog, FontCatalogEntry, FontContainer,
///     PackCreationInput, PackageReadFailures, PackageCatalog,
///     ProjectSnapshot, create,
/// };
/// use typst_pack::opendal::OperatorBindings;
/// use typst_pack::opendal::pack_assembly::{
///     FontReadRequest, read_fonts,
/// };
///
/// async fn read_fonts_and_create(
///     bindings: &OperatorBindings,
///     request: &FontReadRequest,
///     project: &ProjectSnapshot,
///     packages: &PackageCatalog,
///     package_failures: &PackageReadFailures,
///     discovery: &DiscoverySpecification,
/// ) -> Result<(), Box<dyn std::error::Error>> {
///     let (_, read) = read_fonts(bindings, request).await?.into_parts();
///     let mut fonts = FontCatalog::new();
///     for entry in read {
///         let (_, _, _, disposition, bytes) = entry.into_parts();
///         let container = FontContainer::new(bytes)?;
///         fonts.push(FontCatalogEntry::new(container, disposition));
///     }
///     let _outcome = create(PackCreationInput {
///         project,
///         packages,
///         fonts: &fonts,
///         package_failures,
///         discovery,
///         metadata: None,
///     })?;
///     Ok(())
/// }
/// ```
#[allow(clippy::result_large_err)]
pub async fn read_fonts<R: OperatorResolver + ?Sized>(
    resolver: &R,
    request: &FontReadRequest,
) -> Result<FontRead, FontReadError> {
    let locations = request
        .sources()
        .iter()
        .map(FontSource::source)
        .collect::<Vec<_>>();
    let read = read_recursive_prefixes(
        resolver,
        &locations,
        RecursiveReadSelection::FontContainers,
        request.limits().into(),
        &FontReadOperation {
            sources: request.sources(),
        },
    )
    .await?;

    let sources = request.sources().to_vec();
    let entries = read
        .into_iter()
        .enumerate()
        .flat_map(|(source_index, objects)| {
            let source = sources[source_index].clone();
            objects.into_iter().map(move |object| FontReadEntry {
                source_index,
                source: source.source.clone(),
                relative_path: object.relative_path,
                disposition: source.disposition,
                bytes: object.bytes,
            })
        })
        .collect();

    Ok(FontRead { sources, entries })
}

/// A failure while reading Font Containers through OpenDAL.
///
/// This error's own `Display` and `Debug` omit native resolver and OpenDAL
/// messages. Rendering its complete source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "Font Read failed at source {source_index} for binding {binding} at prefix operation path {operation_path:?}{failed_path}: {cause}",
    binding = .source_location.binding(),
    operation_path = .source_location.operation_path(),
    failed_path = failed_path_context(.failed_path.as_deref()),
)]
pub struct FontReadError {
    source_index: usize,
    source_location: Location,
    failed_path: Option<String>,
    #[source]
    cause: RedactedError<FontReadErrorCause>,
}

impl FontReadError {
    /// The caller-order index of the source at which read failed.
    pub fn source_index(&self) -> usize {
        self.source_index
    }

    /// The normalized font prefix at which read failed.
    pub fn source_location(&self) -> &Location {
        &self.source_location
    }

    /// The selected object's operation path when one object read failed.
    pub fn failed_path(&self) -> Option<&str> {
        self.failed_path.as_deref()
    }

    /// The typed cause of this failure.
    pub fn cause(&self) -> &FontReadErrorCause {
        self.cause.inner()
    }

    fn new(
        source_index: usize,
        source_location: &Location,
        failed_path: Option<String>,
        cause: FontReadErrorCause,
    ) -> Self {
        Self {
            source_index,
            source_location: source_location.clone(),
            failed_path,
            cause: RedactedError::new(cause),
        }
    }
}

/// The typed cause of an OpenDAL Font Read failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum FontReadErrorCause {
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("required listing or read capability is unsupported")]
    UnsupportedCapabilities {
        list: bool,
        list_with_recursive: bool,
        read: bool,
    },
    #[error("a recursive listing failed")]
    List(#[source] ::opendal::Error),
    #[error("a listed Font Container read failed")]
    Read(#[source] ::opendal::Error),
    #[error("a listed Font Container was absent when read")]
    ListedObjectAbsent(#[source] ::opendal::Error),
    #[error("the completed listings had structural issues")]
    Structural(#[source] FontReadSurveyError),
    #[error("a Font Read limit failed")]
    Limit(#[source] FontReadLimitError),
}

struct FontReadOperation<'a> {
    sources: &'a [FontSource],
}

impl FontReadOperation<'_> {
    fn error(
        &self,
        source_index: usize,
        failed_path: Option<String>,
        cause: FontReadErrorCause,
    ) -> FontReadError {
        FontReadError::new(
            source_index,
            self.sources[source_index].source(),
            failed_path,
            cause,
        )
    }
}

impl RecursiveReadOperation for FontReadOperation<'_> {
    type Error = FontReadError;

    fn invalid_location_role(&self, _: usize, _: LocationRoleError) -> FontReadError {
        unreachable!("FontReadRequest validates every prefix role")
    }

    fn resolve_operator(&self, source_index: usize, source: BoxError) -> FontReadError {
        self.error(
            source_index,
            None,
            FontReadErrorCause::ResolveOperator(source),
        )
    }

    fn unsupported_capabilities(
        &self,
        source_index: usize,
        list: bool,
        list_with_recursive: bool,
        read: bool,
    ) -> FontReadError {
        self.error(
            source_index,
            None,
            FontReadErrorCause::UnsupportedCapabilities {
                list,
                list_with_recursive,
                read,
            },
        )
    }

    fn list(&self, source_index: usize, source: ::opendal::Error) -> FontReadError {
        self.error(source_index, None, FontReadErrorCause::List(source))
    }

    fn read(
        &self,
        source_index: usize,
        operation_path: String,
        source: ::opendal::Error,
    ) -> FontReadError {
        self.error(
            source_index,
            Some(operation_path),
            FontReadErrorCause::Read(source),
        )
    }

    fn listed_object_absent(
        &self,
        source_index: usize,
        operation_path: String,
        source: ::opendal::Error,
    ) -> FontReadError {
        self.error(
            source_index,
            Some(operation_path),
            FontReadErrorCause::ListedObjectAbsent(source),
        )
    }

    fn structural(&self, source_index: usize, issues: Vec<RecursiveSurveyIssue>) -> FontReadError {
        self.error(
            source_index,
            None,
            FontReadErrorCause::Structural(FontReadSurveyError {
                issues: issues.into_iter().map(map_font_issue).collect(),
            }),
        )
    }

    fn limit(
        &self,
        source_index: usize,
        resource: RecursiveReadResource,
        ceiling: u64,
        _: u64,
    ) -> FontReadError {
        self.error(
            source_index,
            None,
            FontReadErrorCause::Limit(FontReadLimitError::exceeded(
                map_font_resource(resource),
                ceiling,
            )),
        )
    }

    fn accounting_overflow(
        &self,
        source_index: usize,
        resource: RecursiveReadResource,
    ) -> FontReadError {
        self.error(
            source_index,
            None,
            FontReadErrorCause::Limit(FontReadLimitError::AccountingOverflow {
                resource: map_font_resource(resource),
            }),
        )
    }
}

impl From<FontReadLimits> for RecursiveReadLimits {
    fn from(limits: FontReadLimits) -> Self {
        Self::new(
            limits.listed_entries(),
            limits.listed_path_bytes(),
            limits.total_listed_path_bytes(),
            limits.selected_containers(),
            limits.container_bytes(),
            limits.total_bytes(),
        )
    }
}

fn map_font_resource(resource: RecursiveReadResource) -> FontReadResource {
    match resource {
        RecursiveReadResource::ListedEntries => FontReadResource::ListedEntries,
        RecursiveReadResource::ListedPathBytes => FontReadResource::ListedPathBytes,
        RecursiveReadResource::TotalListedPathBytes => FontReadResource::TotalListedPathBytes,
        RecursiveReadResource::SelectedObjects => FontReadResource::SelectedContainers,
        RecursiveReadResource::ObjectBytes => FontReadResource::ContainerBytes,
        RecursiveReadResource::TotalBytes => FontReadResource::TotalBytes,
        _ => unreachable!("unknown recursive read resource"),
    }
}

fn map_font_issue(issue: RecursiveSurveyIssue) -> FontReadIssue {
    let source_index = issue.source_index;
    let operation_path = issue.operation_path;
    match issue.kind {
        RecursiveSurveyIssueKind::ListedPathOutsidePrefix => {
            FontReadIssue::ListedPathOutsidePrefix {
                source_index,
                operation_path,
            }
        }
        RecursiveSurveyIssueKind::PrefixMarkerWhereFileRequired => {
            FontReadIssue::PrefixMarkerWhereFileRequired {
                source_index,
                operation_path,
            }
        }
        RecursiveSurveyIssueKind::EmptyRelativeOperationPath => {
            FontReadIssue::EmptyRelativeOperationPath {
                source_index,
                operation_path,
            }
        }
        RecursiveSurveyIssueKind::InvalidRelativeOperationPath => {
            FontReadIssue::InvalidRelativeOperationPath {
                source_index,
                operation_path,
            }
        }
        RecursiveSurveyIssueKind::DuplicateListedObject => FontReadIssue::DuplicateListedObject {
            source_index,
            operation_path,
        },
        RecursiveSurveyIssueKind::UnsupportedEntryKind => FontReadIssue::UnsupportedEntryKind {
            source_index,
            operation_path,
            kind: FontReadEntryKind::Unknown,
        },
    }
}