stella-docx-kernel 0.35.0

Bounded DOCX package projection and WordprocessingML scanning
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
//! Bounded, host-independent projection of the main OOXML document part.
//!
//! This crate deliberately knows nothing about host-specific paragraph identifiers.
//! Callers allocate opaque application identities from package facts; `w14:paraId`
//! remains optional package metadata and is never treated as a host navigation ID.

mod archive;
mod compatibility;
mod flat_opc;
mod namespaces;
mod numbering;
mod ooxml;
mod relationships;
mod review;
mod structure;
mod styles;

use std::collections::{HashMap, HashSet};
use std::fmt;

pub use archive::{DocumentParts, DocxLimits, extract_document_parts, extract_document_xml};
pub use ooxml::{
    PackageParagraphId, ParagraphStructure, RevisionProjectionStatus, RevisionUnsupportedReason,
    RevisionView, TextFormattingSpan, TextMaterialization, TextStyle,
};
pub use review::{
    AttributedComment, AttributedRevision, CommentContent, DocumentReviewFacts, ReviewDetail,
    ReviewFactLimits, ReviewFactSet, ReviewFactUnknownReason, ReviewPoint, ReviewSpan,
    RevisionContent, RevisionFactKind, RevisionPayload,
};
pub use structure::{
    BookmarkFact, DocumentStructureFacts, InternalReferenceFact, InternalReferenceRole,
    NumberingHierarchyFact, ParagraphAlignmentFact, ParagraphAlignmentSource,
    ParagraphAlignmentValue, ParagraphIndentation, ParagraphIndentationFact,
    ParagraphOutlineLevelFact, SpanCoverage, StructuralFactSet, StructuralFactUnknownReason,
    StructuralSpan,
};
pub use styles::is_semantic_highlight_color;

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct InternalParagraphId(String);

impl InternalParagraphId {
    /// Creates a bounded, non-empty application paragraph identity.
    ///
    /// # Errors
    ///
    /// Returns [`ProjectionError::InvalidInternalParagraphId`] when the value
    /// is empty or exceeds the identity length limit.
    pub fn new(value: impl Into<String>) -> Result<Self, ProjectionError> {
        let value = value.into();
        if value.is_empty() || value.len() > 128 {
            return Err(ProjectionError::InvalidInternalParagraphId);
        }
        Ok(Self(value))
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Clone, Copy, Debug)]
pub struct ParagraphIdentityFacts<'a> {
    pub ordinal: usize,
    pub package_paragraph_id: Option<PackageParagraphId>,
    pub text: &'a str,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjectedParagraph {
    pub id: InternalParagraphId,
    pub ordinal: usize,
    pub package_paragraph_id: Option<PackageParagraphId>,
    pub style_id: Option<String>,
    pub text: String,
    pub formatting: Vec<TextFormattingSpan>,
    pub structure: Option<ParagraphStructure>,
    pub alignment: Option<ParagraphAlignmentFact>,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum FormattingUnknownReason {
    DocumentPartOnly,
    StylesPartUnavailable,
    UnsupportedStyles,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FormattingFactStatus {
    Known,
    Unknown(FormattingUnknownReason),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormattingCompleteness {
    pub bold: FormattingFactStatus,
    pub highlight: FormattingFactStatus,
    pub superscript: FormattingFactStatus,
}

impl FormattingCompleteness {
    fn from_styles(styles: Result<(), FormattingUnknownReason>) -> Self {
        let status = |family| match family {
            // Highlight facts report direct markup, independently of the cascade.
            TextStyle::Highlight => FormattingFactStatus::Known,
            TextStyle::Bold | TextStyle::Superscript => styles
                .map_or_else(FormattingFactStatus::Unknown, |()| {
                    FormattingFactStatus::Known
                }),
        };
        Self {
            bold: status(TextStyle::Bold),
            highlight: status(TextStyle::Highlight),
            superscript: status(TextStyle::Superscript),
        }
    }

    fn mark_styles_unread(&mut self) {
        let unread = Self::from_styles(Err(FormattingUnknownReason::UnsupportedStyles));
        self.bold = unread.bold;
        self.superscript = unread.superscript;
    }

    const fn mark_formatting_unread(&mut self) {
        let unknown = FormattingFactStatus::Unknown(FormattingUnknownReason::UnsupportedStyles);
        self.bold = unknown;
        self.highlight = unknown;
        self.superscript = unknown;
    }
}

impl Default for FormattingCompleteness {
    fn default() -> Self {
        Self::from_styles(Err(FormattingUnknownReason::DocumentPartOnly))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocumentProjection {
    pub paragraphs: Vec<ProjectedParagraph>,
    pub formatting_completeness: FormattingCompleteness,
    pub revision_status: RevisionProjectionStatus,
    pub structural_facts: DocumentStructureFacts,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocumentPackageProjection {
    pub document: DocumentProjection,
    pub review_facts: DocumentReviewFacts,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ProjectionOptions {
    pub revision_view: RevisionView,
    pub text_materialization: TextMaterialization,
}

impl Default for ProjectionOptions {
    fn default() -> Self {
        Self {
            revision_view: RevisionView::Current,
            text_materialization: TextMaterialization::WordHost,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProjectionError {
    ArchiveTooLarge,
    InvalidArchive,
    InvalidFlatOpcPackage,
    TooManyArchiveEntries,
    InvalidPackageRelationships,
    PackageRelationshipsTooLarge,
    MissingDocumentXml,
    DuplicateDocumentXml,
    DuplicateStylesXml,
    DuplicateNumberingXml,
    EncryptedDocumentXml,
    UnsupportedCompression(u16),
    DocumentXmlTooLarge,
    SuspiciousCompressionRatio,
    InvalidDocumentXmlEntry,
    DocumentXmlIntegrity,
    StylesXmlTooLarge,
    InvalidStylesXmlEntry,
    StylesXmlIntegrity,
    NumberingXmlTooLarge,
    InvalidNumberingXmlEntry,
    NumberingXmlIntegrity,
    InvalidDocumentXml,
    InvalidStylesXml,
    InvalidNumberingXml,
    MissingDocumentBody,
    TooManyParagraphs,
    TooManyStructuralFacts,
    TooManyNumberingItems,
    InvalidInternalParagraphId,
    DuplicateInternalParagraphId,
}

impl fmt::Display for ProjectionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self {
            Self::ArchiveTooLarge => "DOCX archive exceeds the configured size limit",
            Self::InvalidFlatOpcPackage => "Flat OPC package has invalid structure",
            Self::InvalidArchive => "DOCX archive is invalid",
            Self::TooManyArchiveEntries => "DOCX archive has too many entries",
            Self::InvalidPackageRelationships => "DOCX archive has invalid package relationships",
            Self::PackageRelationshipsTooLarge => {
                "DOCX package relationships exceed the configured size limit"
            }
            Self::MissingDocumentXml => "DOCX archive has no main document part",
            Self::DuplicateDocumentXml => "DOCX archive has duplicate main document parts",
            Self::DuplicateStylesXml => "DOCX archive has duplicate entries for its styles part",
            Self::DuplicateNumberingXml => {
                "DOCX archive has duplicate entries for its numbering part"
            }
            Self::EncryptedDocumentXml => "DOCX main document part is encrypted",
            Self::UnsupportedCompression(_) => {
                "selected DOCX package part uses unsupported compression"
            }
            Self::DocumentXmlTooLarge => {
                "DOCX main document part exceeds the configured size limit"
            }
            Self::SuspiciousCompressionRatio => {
                "selected DOCX package part exceeds the compression-ratio limit"
            }
            Self::InvalidDocumentXmlEntry => "DOCX main document part has an invalid ZIP entry",
            Self::DocumentXmlIntegrity => "DOCX main document part failed size or CRC validation",
            Self::StylesXmlTooLarge => "DOCX styles part exceeds the configured size limit",
            Self::InvalidStylesXmlEntry => "DOCX styles part has an invalid ZIP entry",
            Self::StylesXmlIntegrity => "DOCX styles part failed size or CRC validation",
            Self::NumberingXmlTooLarge => "DOCX numbering part exceeds the configured size limit",
            Self::InvalidNumberingXmlEntry => "DOCX numbering part has an invalid ZIP entry",
            Self::NumberingXmlIntegrity => "DOCX numbering part failed size or CRC validation",
            Self::InvalidDocumentXml => "DOCX main document part is invalid XML",
            Self::InvalidStylesXml => "DOCX styles part is invalid XML",
            Self::InvalidNumberingXml => "DOCX numbering part is invalid XML",
            Self::MissingDocumentBody => "DOCX main document part has no document body",
            Self::TooManyParagraphs => "DOCX main document part has too many paragraphs",
            Self::TooManyStructuralFacts => {
                "DOCX main document part produces too many structural facts"
            }
            Self::TooManyNumberingItems => "DOCX numbering part exceeds the configured item limit",
            Self::InvalidInternalParagraphId => "application paragraph ID is invalid",
            Self::DuplicateInternalParagraphId => "application paragraph IDs are not unique",
        };
        formatter.write_str(message)
    }
}

impl std::error::Error for ProjectionError {}

/// Projects a bounded DOCX package using default projection options.
///
/// # Errors
///
/// Returns [`ProjectionError`] for invalid or unsupported package input, a
/// resource-limit violation, or an invalid identity allocated by the caller.
pub fn project_docx<F>(
    bytes: &[u8],
    limits: DocxLimits,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    project_docx_with_options(bytes, limits, ProjectionOptions::default(), allocate_id)
}

/// Projects a bounded DOCX package using explicit projection options.
///
/// # Errors
///
/// Returns [`ProjectionError`] for invalid or unsupported package input, a
/// resource-limit violation, or an invalid identity allocated by the caller.
pub fn project_docx_with_options<F>(
    bytes: &[u8],
    limits: DocxLimits,
    options: ProjectionOptions,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    let parts = extract_document_parts(bytes, limits)?;
    project_parts(&parts, limits, options, allocate_id)
}

// Both package entry points must share dependency preparation and projection.
#[inline(never)]
fn project_parts<F>(
    parts: &DocumentParts,
    limits: DocxLimits,
    options: ProjectionOptions,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    let styles = parts.styles_xml.as_deref().map_or(
        Err(StructuralFactUnknownReason::StylesPartUnavailable),
        |styles| {
            styles::parse_styles(styles, limits.maximum_styles)
                .map_err(|_| StructuralFactUnknownReason::UnsupportedStyles)
        },
    );
    let numbering = parse_optional_numbering(
        parts.numbering_xml.as_deref(),
        limits.maximum_numbering_items,
    )?;
    project_document_xml_with_limit(
        &parts.document_xml,
        limits.maximum_paragraphs,
        limits.maximum_structural_facts,
        options,
        ProjectionDependencies {
            styles: styles.as_ref().map_err(|reason| *reason),
            numbering: numbering
                .as_ref()
                .ok_or(StructuralFactUnknownReason::UnsupportedNumbering),
        },
        allocate_id,
    )
}

/// Projects a bounded DOCX package and its attributed review facts in one
/// package-directory scan.
///
/// Invalid optional review parts produce an explicit unknown fact family; they
/// do not discard an otherwise valid document projection.
///
/// # Errors
///
/// Returns [`ProjectionError`] for an invalid document projection or package
/// boundary. Optional comments-part failures remain represented in
/// [`DocumentReviewFacts`].
pub fn project_docx_with_review_facts<F>(
    bytes: &[u8],
    limits: DocxLimits,
    review_limits: ReviewFactLimits,
    options: ProjectionOptions,
    allocate_id: F,
) -> Result<DocumentPackageProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    let parts = archive::extract_projection_parts(bytes, limits, review_limits)?;
    let styles = parts.styles.as_deref().map_or(
        Err(StructuralFactUnknownReason::StylesPartUnavailable),
        |styles| {
            styles::parse_styles(styles, limits.maximum_styles)
                .map_err(|_| StructuralFactUnknownReason::UnsupportedStyles)
        },
    );
    let numbering =
        parse_optional_numbering(parts.numbering.as_deref(), limits.maximum_numbering_items)?;
    let ProjectedDocumentWithReview {
        document,
        revisions,
        comment_anchors,
    } = project_document_xml_with_limit_and_review(
        &parts.document,
        limits.maximum_paragraphs,
        limits.maximum_structural_facts,
        options,
        ProjectionDependencies {
            styles: styles.as_ref().map_err(|reason| *reason),
            numbering: numbering
                .as_ref()
                .ok_or(StructuralFactUnknownReason::UnsupportedNumbering),
        },
        Some(ooxml::ReviewProjectionLimits {
            maximum_facts: review_limits.maximum_facts_per_family,
            maximum_detail_bytes: review_limits.maximum_review_detail_bytes,
        }),
        allocate_id,
    )?;
    let review_facts = review::project_review_facts(
        revisions.unwrap_or(ReviewFactSet::Unknown(
            ReviewFactUnknownReason::InvalidDocument,
        )),
        comment_anchors.as_ref(),
        &document,
        parts.comments,
        parts.comments_extended,
        review_limits,
        options.text_materialization,
    );
    Ok(DocumentPackageProjection {
        document,
        review_facts,
    })
}

fn parse_optional_numbering(
    xml: Option<&[u8]>,
    maximum_items: usize,
) -> Result<Option<numbering::NumberingCatalog>, ProjectionError> {
    let Some(xml) = xml else {
        return Ok(None);
    };
    match numbering::parse_numbering(xml, maximum_items) {
        Ok(catalog) => Ok(Some(catalog)),
        Err(ProjectionError::TooManyNumberingItems) => Err(ProjectionError::TooManyNumberingItems),
        Err(_) => Ok(None),
    }
}

/// Projects a bounded standalone main document or relationship-selected Flat OPC package.
///
/// Package payloads are indexed without scanning their bodies. Only the selected
/// document and its style/numbering dependencies enter the shared projection.
/// Standalone input retains unknown dependency-derived evidence.
///
/// # Errors
/// Returns [`ProjectionError`] for malformed input, resource limits or allocator failures.
pub fn project_main_document_xml<F>(
    xml: &[u8],
    limits: DocxLimits,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    if xml.len() > limits.maximum_archive_bytes {
        return Err(ProjectionError::ArchiveTooLarge);
    }
    match flat_opc::input_kind(xml)? {
        flat_opc::XmlInputKind::Document => {
            if xml.len() > limits.maximum_document_xml_bytes {
                return Err(ProjectionError::DocumentXmlTooLarge);
            }
            project_document_xml_with_limit(
                xml,
                limits.maximum_paragraphs,
                limits.maximum_structural_facts,
                ProjectionOptions::default(),
                ProjectionDependencies {
                    styles: Err(StructuralFactUnknownReason::DocumentPartOnly),
                    numbering: Err(StructuralFactUnknownReason::DocumentPartOnly),
                },
                allocate_id,
            )
        }
        flat_opc::XmlInputKind::Package => project_parts(
            &flat_opc::extract_parts(xml, limits)?,
            limits,
            ProjectionOptions::default(),
            allocate_id,
        ),
    }
}

/// Projects exactly one paragraph from a relationship-selected Flat OPC package.
///
/// The caller's package, XML, dependency and fact limits still apply; the paragraph
/// count is additionally capped at one. Namespace context and related styles use
/// the same package selection as full-document projection. This is partial evidence:
/// all document structural fact families are unknown, and table coordinates are
/// unavailable because fragment-local positions cannot identify document locations.
///
/// # Errors
/// Returns [`ProjectionError`] for malformed input, zero or multiple paragraphs,
/// resource limits or allocator failures. Standalone XML is not a package fragment.
pub fn project_paragraph_fragment<F>(
    xml: &[u8],
    mut limits: DocxLimits,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    limits.maximum_paragraphs = limits.maximum_paragraphs.min(1);
    let mut projection = project_parts(
        &flat_opc::extract_parts(xml, limits)?,
        limits,
        ProjectionOptions::default(),
        allocate_id,
    )?;
    let [paragraph] = projection.paragraphs.as_mut_slice() else {
        return Err(ProjectionError::InvalidDocumentXml);
    };
    paragraph.structure = None;
    projection.structural_facts = DocumentStructureFacts {
        indentation: StructuralFactSet::Unknown(StructuralFactUnknownReason::ParagraphFragment),
        numbering_hierarchy: StructuralFactSet::Unknown(
            StructuralFactUnknownReason::ParagraphFragment,
        ),
        bookmarks: StructuralFactSet::Unknown(StructuralFactUnknownReason::ParagraphFragment),
        internal_references: StructuralFactSet::Unknown(
            StructuralFactUnknownReason::ParagraphFragment,
        ),
        outline_levels: StructuralFactSet::Unknown(StructuralFactUnknownReason::ParagraphFragment),
    };
    Ok(projection)
}

/// Projects an uncompressed main OOXML document part with default options.
///
/// # Errors
///
/// Returns [`ProjectionError`] for invalid or unsupported XML, a resource-limit
/// violation, or an invalid identity allocated by the caller.
pub fn project_document_xml<F>(
    xml: &[u8],
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    project_document_xml_with_options(xml, ProjectionOptions::default(), allocate_id)
}

/// Projects an uncompressed main OOXML document part with explicit options.
///
/// # Errors
///
/// Returns [`ProjectionError`] for invalid or unsupported XML, a resource-limit
/// violation, or an invalid identity allocated by the caller.
pub fn project_document_xml_with_options<F>(
    xml: &[u8],
    options: ProjectionOptions,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    project_document_xml_with_limit(
        xml,
        DocxLimits::default().maximum_paragraphs,
        DocxLimits::default().maximum_structural_facts,
        options,
        ProjectionDependencies {
            styles: Err(StructuralFactUnknownReason::DocumentPartOnly),
            numbering: Err(StructuralFactUnknownReason::DocumentPartOnly),
        },
        allocate_id,
    )
}

fn project_document_xml_with_limit<F>(
    xml: &[u8],
    maximum_paragraphs: usize,
    maximum_structural_facts: usize,
    options: ProjectionOptions,
    dependencies: ProjectionDependencies<'_>,
    allocate_id: F,
) -> Result<DocumentProjection, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    project_document_xml_with_limit_and_review(
        xml,
        maximum_paragraphs,
        maximum_structural_facts,
        options,
        dependencies,
        None,
        allocate_id,
    )
    .map(|projection| projection.document)
}

struct ProjectedDocumentWithReview {
    document: DocumentProjection,
    revisions: Option<ReviewFactSet<AttributedRevision>>,
    comment_anchors: Option<HashMap<String, ReviewSpan>>,
}

#[derive(Clone, Copy)]
struct ProjectionDependencies<'a> {
    styles: Result<&'a structure::StyleSheet, StructuralFactUnknownReason>,
    numbering: Result<&'a numbering::NumberingCatalog, StructuralFactUnknownReason>,
}

fn project_document_xml_with_limit_and_review<F>(
    xml: &[u8],
    maximum_paragraphs: usize,
    maximum_structural_facts: usize,
    options: ProjectionOptions,
    dependencies: ProjectionDependencies<'_>,
    review_limits: Option<ooxml::ReviewProjectionLimits>,
    mut allocate_id: F,
) -> Result<ProjectedDocumentWithReview, ProjectionError>
where
    F: FnMut(ParagraphIdentityFacts<'_>) -> Result<InternalParagraphId, ProjectionError>,
{
    let projected = ooxml::project_document_xml(
        xml,
        maximum_paragraphs,
        options.revision_view,
        options.text_materialization,
        dependencies.styles.map_err(formatting_unknown_reason),
        review_limits,
    )?;
    let review_revisions = projected.review_revisions;
    let review_comment_anchors = review_limits
        .is_some()
        .then_some(projected.review_comment_anchors);
    let mut seen_ids = HashSet::with_capacity(projected.paragraphs.len());
    let mut ids = Vec::with_capacity(projected.paragraphs.len());
    for paragraph in &projected.paragraphs {
        let facts = ParagraphIdentityFacts {
            ordinal: paragraph.ordinal,
            package_paragraph_id: paragraph.package_paragraph_id,
            text: &paragraph.text,
        };
        let id = allocate_id(facts)?;
        if !seen_ids.insert(id.clone()) {
            return Err(ProjectionError::DuplicateInternalParagraphId);
        }
        ids.push(id);
    }
    let texts = projected
        .paragraphs
        .iter()
        .map(|paragraph| paragraph.text.as_str())
        .collect::<Vec<_>>();
    let properties = projected
        .paragraphs
        .iter()
        .map(|paragraph| &paragraph.properties)
        .collect::<Vec<_>>();
    let structural_facts = structure::materialize_structure(
        structure::RawStructureInput {
            paragraph_texts: &texts,
            properties: &properties,
            bookmarks: projected.bookmarks.as_deref().map_err(|reason| *reason),
            references: projected.references.as_deref().map_err(|reason| *reason),
        },
        dependencies.styles,
        dependencies.numbering,
        maximum_structural_facts,
    )?;
    let mut paragraphs = Vec::with_capacity(projected.paragraphs.len());
    for (id, paragraph) in ids.into_iter().zip(projected.paragraphs) {
        let alignment =
            structure::resolve_paragraph_alignment(dependencies.styles, &paragraph.properties);
        paragraphs.push(ProjectedParagraph {
            id,
            ordinal: paragraph.ordinal,
            package_paragraph_id: paragraph.package_paragraph_id,
            style_id: paragraph.properties.style_id,
            text: paragraph.text,
            formatting: paragraph.formatting,
            structure: paragraph.structure,
            alignment,
        });
    }
    Ok(ProjectedDocumentWithReview {
        document: DocumentProjection {
            paragraphs,
            formatting_completeness: projected.formatting_completeness,
            revision_status: projected.revision_status,
            structural_facts,
        },
        revisions: review_revisions,
        comment_anchors: review_comment_anchors,
    })
}

const fn formatting_unknown_reason(reason: StructuralFactUnknownReason) -> FormattingUnknownReason {
    match reason {
        StructuralFactUnknownReason::DocumentPartOnly
        | StructuralFactUnknownReason::ParagraphFragment => {
            FormattingUnknownReason::DocumentPartOnly
        }
        StructuralFactUnknownReason::StylesPartUnavailable => {
            FormattingUnknownReason::StylesPartUnavailable
        }
        StructuralFactUnknownReason::UnsupportedStyles
        | StructuralFactUnknownReason::UnsupportedNumbering
        | StructuralFactUnknownReason::IncompleteBookmarkRanges
        | StructuralFactUnknownReason::UnsupportedInternalReferences => {
            FormattingUnknownReason::UnsupportedStyles
        }
    }
}