stella-docx-kernel 0.10.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
//! 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 namespaces;
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, is_semantic_highlight_color,
};
pub use review::{
    AttributedComment, AttributedRevision, CommentContent, DocumentReviewFacts, ReviewDetail,
    ReviewFactLimits, ReviewFactSet, ReviewFactUnknownReason, ReviewPoint, ReviewSpan,
    RevisionContent, RevisionFactKind,
};
pub use structure::{
    BookmarkFact, DocumentStructureFacts, InternalReferenceFact, InternalReferenceRole,
    NumberingHierarchyFact, ParagraphIndentation, ParagraphIndentationFact,
    ParagraphOutlineLevelFact, SpanCoverage, StructuralFactSet, StructuralFactUnknownReason,
    StructuralSpan,
};

#[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>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DocumentProjection {
    pub paragraphs: Vec<ProjectedParagraph>,
    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,
    TooManyArchiveEntries,
    InvalidPackageRelationships,
    PackageRelationshipsTooLarge,
    MissingDocumentXml,
    DuplicateDocumentXml,
    DuplicateStylesXml,
    EncryptedDocumentXml,
    UnsupportedCompression(u16),
    DocumentXmlTooLarge,
    SuspiciousCompressionRatio,
    InvalidDocumentXmlEntry,
    DocumentXmlIntegrity,
    StylesXmlTooLarge,
    InvalidStylesXmlEntry,
    StylesXmlIntegrity,
    InvalidDocumentXml,
    InvalidStylesXml,
    MissingDocumentBody,
    TooManyParagraphs,
    TooManyStructuralFacts,
    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::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 word/styles.xml entries",
            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 => "word/styles.xml exceeds the configured size limit",
            Self::InvalidStylesXmlEntry => "word/styles.xml has an invalid ZIP entry",
            Self::StylesXmlIntegrity => "word/styles.xml failed size or CRC validation",
            Self::InvalidDocumentXml => "DOCX main document part is invalid XML",
            Self::InvalidStylesXml => "word/styles.xml 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::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)?;
    let styles = parts.styles_xml.as_deref().map_or(
        Err(StructuralFactUnknownReason::StylesPartUnavailable),
        |styles| {
            styles::parse_styles(styles).map_err(|_| StructuralFactUnknownReason::UnsupportedStyles)
        },
    );
    project_document_xml_with_limit(
        &parts.document_xml,
        limits.maximum_paragraphs,
        limits.maximum_structural_facts,
        options,
        styles.as_ref().map_err(|reason| *reason),
        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).map_err(|_| StructuralFactUnknownReason::UnsupportedStyles)
        },
    );
    let ProjectedDocumentWithReview {
        document,
        revisions,
        comment_anchors,
    } = project_document_xml_with_limit_and_review(
        &parts.document,
        limits.maximum_paragraphs,
        limits.maximum_structural_facts,
        options,
        styles.as_ref().map_err(|reason| *reason),
        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,
    })
}

/// 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,
        Err(StructuralFactUnknownReason::DocumentPartOnly),
        allocate_id,
    )
}

fn project_document_xml_with_limit<F>(
    xml: &[u8],
    maximum_paragraphs: usize,
    maximum_structural_facts: usize,
    options: ProjectionOptions,
    styles: Result<&structure::StyleSheet, StructuralFactUnknownReason>,
    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,
        styles,
        None,
        allocate_id,
    )
    .map(|projection| projection.document)
}

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

fn project_document_xml_with_limit_and_review<F>(
    xml: &[u8],
    maximum_paragraphs: usize,
    maximum_structural_facts: usize,
    options: ProjectionOptions,
    styles: Result<&structure::StyleSheet, StructuralFactUnknownReason>,
    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,
        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),
        },
        styles,
        maximum_structural_facts,
    )?;
    let mut paragraphs = Vec::with_capacity(projected.paragraphs.len());
    for (id, paragraph) in ids.into_iter().zip(projected.paragraphs) {
        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,
        });
    }
    Ok(ProjectedDocumentWithReview {
        document: DocumentProjection {
            paragraphs,
            revision_status: projected.revision_status,
            structural_facts,
        },
        revisions: review_revisions,
        comment_anchors: review_comment_anchors,
    })
}