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
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
use crate::{
    AttributedComment, AttributedRevision, BookmarkFact, CommentContent, DocumentPackageProjection,
    DocumentProjection, DocumentReviewFacts, DocumentStructureFacts, DocxLimits,
    InternalParagraphId, InternalReferenceFact, InternalReferenceRole, NumberingHierarchyFact,
    ParagraphIdentityFacts, ParagraphIndentationFact, ParagraphOutlineLevelFact,
    ParagraphStructure, ProjectedParagraph, ProjectionOptions, ReviewDetail, ReviewFactLimits,
    ReviewFactSet, ReviewFactUnknownReason, ReviewPoint, ReviewSpan, RevisionContent,
    RevisionFactKind, RevisionProjectionStatus, RevisionUnsupportedReason, SpanCoverage,
    StructuralFactSet, StructuralFactUnknownReason, StructuralSpan, TextMaterialization, TextStyle,
    project_docx, project_docx_with_review_facts,
};
use js_sys::Array;
use wasm_bindgen::{JsCast, prelude::*};

const DOCX_PROJECTION_SCHEMA_VERSION: u32 = 3;
const DOCX_PACKAGE_PROJECTION_SCHEMA_VERSION: u32 = 1;
const DOCX_REVIEW_FACTS_SCHEMA_VERSION: u32 = 1;

#[wasm_bindgen(typescript_custom_section)]
const TYPESCRIPT_TYPES: &str = r#"
export type DocxProjectionFormattingSpan = readonly [
  startUtf16: number,
  endUtf16: number,
  style: "bold" | "highlight",
];
export type DocxProjectionStructure =
  | readonly []
  | readonly [
      type: "table",
      tableId: string,
      row: number,
      column: number,
    ];
export type DocxProjectionParagraph = readonly [
  ordinal: number,
  text: string,
  packageParagraphId: string | null,
  formatting: readonly DocxProjectionFormattingSpan[],
  structure: DocxProjectionStructure,
  styleId: string | null,
];
export type DocxProjectionFactSet<T> =
  | readonly [status: "known", items: readonly T[]]
  | readonly [status: "unknown", reason: DocxProjectionUnknownReason];
export type DocxProjectionUnknownReason =
  | "document-part-only"
  | "styles-part-unavailable"
  | "unsupported-styles"
  | "unsupported-numbering"
  | "incomplete-bookmark-ranges"
  | "unsupported-internal-references";
export type DocxProjectionIndentationFact = readonly [
  paragraphOrdinal: number,
  firstLineTwips: number | null,
  hangingTwips: number | null,
  leftTwips: number | null,
  rightTwips: number | null,
  startTwips: number | null,
  endTwips: number | null,
  firstLineCharsHundredths: number | null,
  hangingCharsHundredths: number | null,
  leftCharsHundredths: number | null,
  rightCharsHundredths: number | null,
  startCharsHundredths: number | null,
  endCharsHundredths: number | null,
];
export type DocxProjectionNumberingFact = readonly [
  paragraphOrdinal: number,
  parentParagraphOrdinal: number | null,
  childParagraphOrdinals: readonly number[],
];
export type DocxProjectionOutlineLevelFact = readonly [
  paragraphOrdinal: number,
  outlineLevel: number,
];
export type DocxProjectionBookmarkFact = readonly [
  paragraphOrdinal: number,
  bookmarkId: number,
  name: string,
  span: DocxProjectionStructuralSpan,
];
export type DocxProjectionReferenceFact = readonly [
  paragraphOrdinal: number,
  referenceId: string,
  role: "source" | "target",
  span: DocxProjectionStructuralSpan,
];
export type DocxProjectionStructuralSpan = readonly [
  startUtf8: number,
  endUtf8: number,
  startUtf16: number,
  endUtf16: number,
  coverage:
    | "complete"
    | "continues-before"
    | "continues-after"
    | "continues-before-and-after",
];
export type DocxProjectionStructuralFacts = readonly [
  indentation: DocxProjectionFactSet<DocxProjectionIndentationFact>,
  numberingHierarchy: DocxProjectionFactSet<DocxProjectionNumberingFact>,
  bookmarks: DocxProjectionFactSet<DocxProjectionBookmarkFact>,
  internalReferences: DocxProjectionFactSet<DocxProjectionReferenceFact>,
  outlineLevels: DocxProjectionFactSet<DocxProjectionOutlineLevelFact>,
];
export type DocxProjectionRevisionUnsupportedReason =
  | "incompatible-paragraph-merge"
  | "structural-table-revision"
  | "unsupported-revision-markup";
export type DocxProjectionRevisionStatus =
  | readonly [status: "complete"]
  | readonly [
      status: "incomplete",
      reasons: readonly DocxProjectionRevisionUnsupportedReason[],
    ];
export type DocxProjectionWire = readonly [
  schemaVersion: 3,
  paragraphs: readonly DocxProjectionParagraph[],
  structuralFacts: DocxProjectionStructuralFacts,
  revisionStatus: DocxProjectionRevisionStatus,
];
export type DocxReviewUnknownReason =
  | "invalid-document"
  | "invalid-comments"
  | "invalid-comments-extended"
  | "resource-limit"
  | "unsupported-location";
export type DocxReviewFactSet<T> =
  | readonly [status: "known", items: readonly T[]]
  | readonly [status: "unknown", reason: DocxReviewUnknownReason];
export type DocxReviewDetail<T> =
  | readonly [status: "known", value: T]
  | readonly [status: "unknown", reason: DocxReviewUnknownReason];
export type DocxReviewPoint = readonly [
  paragraphOrdinal: number,
  utf8: number,
  utf16: number,
];
export type DocxReviewSpan = readonly [
  start: DocxReviewPoint,
  end: DocxReviewPoint,
];
/** Compact versioned boundary tuple. Field order is stable within schema version 1. */
export type DocxRevisionContent = readonly [
  span: DocxReviewSpan,
  text: string,
  contentKind: "text" | "formatting-only",
];
export type DocxCommentContent = readonly [
  anchor: DocxReviewSpan,
  commentText: string,
  referencedText: string,
];
/** Attributed revision wire tuple; positions are named and versioned by its container. */
export type DocxAttributedRevision = readonly [
  type:
    | "insertion"
    | "deletion"
    | "moveFrom"
    | "moveTo"
    | "cellIns"
    | "cellDel"
    | "cellMerge"
    | "pPrChange"
    | "rPrChange"
    | "sectPrChange"
    | "tblPrChange"
    | "trPrChange"
    | "tcPrChange"
    | "tblGridChange"
    | "customXmlDelRangeStart"
    | "customXmlDelRangeEnd"
    | "customXmlInsRangeStart"
    | "customXmlInsRangeEnd"
    | "customXmlMoveFromRangeStart"
    | "customXmlMoveFromRangeEnd"
    | "customXmlMoveToRangeStart"
    | "customXmlMoveToRangeEnd",
  author: string,
  date: string | null,
  revisionId: string | null,
  content: DocxReviewDetail<DocxRevisionContent>,
];
/** Attributed comment wire tuple; positions are named and versioned by its container. */
export type DocxAttributedComment = readonly [
  commentId: string,
  author: string,
  initials: string | null,
  date: string | null,
  parentCommentId: string | null,
  threadState: "open" | "resolved",
  content: DocxReviewDetail<DocxCommentContent>,
];
/** Review-fact wire schema. A new tuple layout requires a schema-version bump. */
export type DocxReviewFactsWire = readonly [
  schemaVersion: 1,
  revisions: DocxReviewFactSet<DocxAttributedRevision>,
  comments: DocxReviewFactSet<DocxAttributedComment>,
];
/** Fused package wire schema. A new tuple layout requires a schema-version bump. */
export type DocxPackageProjectionWire = readonly [
  schemaVersion: 1,
  document: DocxProjectionWire,
  reviewFacts: DocxReviewFactsWire,
];
"#;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(typescript_type = "DocxProjectionWire")]
    pub type DocxProjectionWire;
    #[wasm_bindgen(typescript_type = "DocxPackageProjectionWire")]
    pub type DocxPackageProjectionWire;
}

/// Projects compressed DOCX bytes into a versioned host-independent snapshot.
///
/// The ordinal is the paragraph's position in this immutable package snapshot.
/// Package `w14:paraId` values are returned separately. Neither value is an
/// application identity or a host navigation identity. A structural fact
/// family is `unknown` when the package does not prove completeness; an empty
/// `known` list is authoritative negative evidence.
///
/// # Errors
///
/// Returns a JavaScript `Error` when the package cannot be projected or a
/// numeric wire value cannot be represented by the schema.
#[wasm_bindgen(js_name = projectCompressedDocx)]
pub fn project_compressed_docx(bytes: &[u8]) -> Result<DocxProjectionWire, JsValue> {
    project_docx_projection(bytes)
        .and_then(|projection| output_projection_with_structure(&projection))
        // SAFETY: the output builder constructs the exact tuple declared as
        // `DocxProjectionWire` in the wasm-bindgen TypeScript custom section.
        .map(JsCast::unchecked_into)
        .map_err(|error| js_error(&error))
}

/// Projects the document snapshot and attributed review facts from one bounded
/// package-directory scan.
///
/// # Errors
///
/// Returns a JavaScript `Error` when the document package itself cannot be
/// projected. Invalid optional review parts are represented as unknown facts.
#[wasm_bindgen(js_name = projectCompressedDocxWithReviewFacts)]
pub fn project_compressed_docx_with_review_facts(
    bytes: &[u8],
) -> Result<DocxPackageProjectionWire, JsValue> {
    project_docx_package_projection(bytes, TextMaterialization::WordHost)
        .and_then(|projection| output_package_projection(&projection))
        // SAFETY: the output builder constructs the exact tuple declared as
        // `DocxPackageProjectionWire` in the TypeScript custom section.
        .map(JsCast::unchecked_into)
        .map_err(|error| js_error(&error))
}

/// Projects the same fused snapshot with controls normalized for readable text.
///
/// # Errors
///
/// Returns a JavaScript `Error` under the same conditions as
/// [`project_compressed_docx_with_review_facts`].
#[wasm_bindgen(js_name = projectCompressedDocxWithReadableReviewFacts)]
pub fn project_compressed_docx_with_readable_review_facts(
    bytes: &[u8],
) -> Result<DocxPackageProjectionWire, JsValue> {
    project_docx_package_projection(bytes, TextMaterialization::ReadablePlainText)
        .and_then(|projection| output_package_projection(&projection))
        // SAFETY: the output builder constructs the exact tuple declared as
        // `DocxPackageProjectionWire` in the TypeScript custom section.
        .map(JsCast::unchecked_into)
        .map_err(|error| js_error(&error))
}

fn project_docx_projection(bytes: &[u8]) -> Result<DocumentProjection, String> {
    let limits = DocxLimits::default();
    project_docx(bytes, limits, |facts: ParagraphIdentityFacts<'_>| {
        InternalParagraphId::new(format!("projected-{}", facts.ordinal))
    })
    .map_err(|error| error.to_string())
}

fn project_docx_package_projection(
    bytes: &[u8],
    text_materialization: TextMaterialization,
) -> Result<DocumentPackageProjection, String> {
    project_docx_with_review_facts(
        bytes,
        DocxLimits::default(),
        ReviewFactLimits::default(),
        ProjectionOptions {
            text_materialization,
            ..ProjectionOptions::default()
        },
        |facts: ParagraphIdentityFacts<'_>| {
            InternalParagraphId::new(format!("projected-{}", facts.ordinal))
        },
    )
    .map_err(|error| error.to_string())
}

fn output_paragraphs(projection: &DocumentProjection) -> Result<JsValue, String> {
    let output = Array::new();
    for (ordinal, paragraph) in projection.paragraphs.iter().enumerate() {
        output.push(&output_projected_paragraph(ordinal, paragraph)?);
    }
    Ok(output.into())
}

fn output_projected_paragraph(
    ordinal: usize,
    paragraph: &ProjectedParagraph,
) -> Result<JsValue, String> {
    let output = Array::new_with_length(6);
    output.set(0, usize_number(ordinal)?);
    output.set(1, JsValue::from_str(&paragraph.text));
    output.set(
        2,
        paragraph.package_paragraph_id.map_or(JsValue::NULL, |id| {
            JsValue::from_str(&format!("{:08X}", id.value()))
        }),
    );

    let formatting = Array::new();
    for span in &paragraph.formatting {
        let output_span = Array::new_with_length(3);
        output_span.set(0, JsValue::from_f64(f64::from(span.start_utf16)));
        output_span.set(1, JsValue::from_f64(f64::from(span.end_utf16)));
        output_span.set(
            2,
            JsValue::from_str(match span.style {
                TextStyle::Bold => "bold",
                TextStyle::Highlight => "highlight",
            }),
        );
        formatting.push(&output_span);
    }
    output.set(3, formatting.into());
    output.set(4, output_paragraph_structure(paragraph.structure.clone())?);
    output.set(
        5,
        paragraph
            .style_id
            .as_ref()
            .map_or(JsValue::NULL, |style_id| JsValue::from_str(style_id)),
    );
    Ok(output.into())
}

fn output_projection_with_structure(projection: &DocumentProjection) -> Result<JsValue, String> {
    let output = Array::new_with_length(4);
    output.set(
        0,
        JsValue::from_f64(f64::from(DOCX_PROJECTION_SCHEMA_VERSION)),
    );
    output.set(1, output_paragraphs(projection)?);
    output.set(2, output_structural_facts(&projection.structural_facts)?);
    output.set(3, output_revision_status(&projection.revision_status));
    Ok(output.into())
}

fn output_package_projection(projection: &DocumentPackageProjection) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(
        0,
        JsValue::from_f64(f64::from(DOCX_PACKAGE_PROJECTION_SCHEMA_VERSION)),
    );
    output.set(1, output_projection_with_structure(&projection.document)?);
    output.set(2, output_review_facts(&projection.review_facts)?);
    Ok(output.into())
}

fn output_review_facts(facts: &DocumentReviewFacts) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(
        0,
        JsValue::from_f64(f64::from(DOCX_REVIEW_FACTS_SCHEMA_VERSION)),
    );
    output.set(
        1,
        output_review_fact_set(&facts.revisions, output_revision_fact)?,
    );
    output.set(
        2,
        output_review_fact_set(&facts.comments, output_comment_fact)?,
    );
    Ok(output.into())
}

fn output_review_fact_set<T>(
    facts: &ReviewFactSet<T>,
    mut output_item: impl FnMut(&T) -> Result<JsValue, String>,
) -> Result<JsValue, String> {
    let output = Array::new_with_length(2);
    match facts {
        ReviewFactSet::Known(items) => {
            output.set(0, JsValue::from_str("known"));
            let values = Array::new();
            for item in items {
                values.push(&output_item(item)?);
            }
            output.set(1, values.into());
        }
        ReviewFactSet::Unknown(reason) => {
            output.set(0, JsValue::from_str("unknown"));
            output.set(1, JsValue::from_str(review_unknown_reason(*reason)));
        }
    }
    Ok(output.into())
}

fn output_revision_fact(fact: &AttributedRevision) -> Result<JsValue, String> {
    let output = Array::new_with_length(5);
    output.set(
        0,
        JsValue::from_str(match fact.kind {
            RevisionFactKind::Insertion => "insertion",
            RevisionFactKind::Deletion => "deletion",
            RevisionFactKind::MoveFrom => "moveFrom",
            RevisionFactKind::MoveTo => "moveTo",
            RevisionFactKind::CellInsertion => "cellIns",
            RevisionFactKind::CellDeletion => "cellDel",
            RevisionFactKind::CellMerge => "cellMerge",
            RevisionFactKind::ParagraphPropertiesChange => "pPrChange",
            RevisionFactKind::RunPropertiesChange => "rPrChange",
            RevisionFactKind::SectionPropertiesChange => "sectPrChange",
            RevisionFactKind::TablePropertiesChange => "tblPrChange",
            RevisionFactKind::TableRowPropertiesChange => "trPrChange",
            RevisionFactKind::TableCellPropertiesChange => "tcPrChange",
            RevisionFactKind::TableGridChange => "tblGridChange",
            RevisionFactKind::CustomXmlDeletionRangeStart => "customXmlDelRangeStart",
            RevisionFactKind::CustomXmlDeletionRangeEnd => "customXmlDelRangeEnd",
            RevisionFactKind::CustomXmlInsertionRangeStart => "customXmlInsRangeStart",
            RevisionFactKind::CustomXmlInsertionRangeEnd => "customXmlInsRangeEnd",
            RevisionFactKind::CustomXmlMoveFromRangeStart => "customXmlMoveFromRangeStart",
            RevisionFactKind::CustomXmlMoveFromRangeEnd => "customXmlMoveFromRangeEnd",
            RevisionFactKind::CustomXmlMoveToRangeStart => "customXmlMoveToRangeStart",
            RevisionFactKind::CustomXmlMoveToRangeEnd => "customXmlMoveToRangeEnd",
        }),
    );
    output.set(1, JsValue::from_str(&fact.author));
    output.set(2, optional_string(fact.date.as_deref()));
    output.set(3, optional_string(fact.revision_id.as_deref()));
    output.set(
        4,
        output_review_detail(&fact.content, output_revision_content)?,
    );
    Ok(output.into())
}

fn output_comment_fact(fact: &AttributedComment) -> Result<JsValue, String> {
    let output = Array::new_with_length(7);
    output.set(0, JsValue::from_str(&fact.comment_id));
    output.set(1, JsValue::from_str(&fact.author));
    output.set(2, optional_string(fact.initials.as_deref()));
    output.set(3, optional_string(fact.date.as_deref()));
    output.set(4, optional_string(fact.parent_comment_id.as_deref()));
    output.set(
        5,
        JsValue::from_str(if fact.resolved { "resolved" } else { "open" }),
    );
    output.set(
        6,
        output_review_detail(&fact.content, output_comment_content)?,
    );
    Ok(output.into())
}

fn optional_string(value: Option<&str>) -> JsValue {
    value.map_or(JsValue::NULL, JsValue::from_str)
}

fn output_review_detail<T>(
    detail: &ReviewDetail<T>,
    output_value: impl FnOnce(&T) -> Result<JsValue, String>,
) -> Result<JsValue, String> {
    let output = Array::new_with_length(2);
    match detail {
        ReviewDetail::Known(value) => {
            output.set(0, JsValue::from_str("known"));
            output.set(1, output_value(value)?);
        }
        ReviewDetail::Unknown(reason) => {
            output.set(0, JsValue::from_str("unknown"));
            output.set(1, JsValue::from_str(review_unknown_reason(*reason)));
        }
    }
    Ok(output.into())
}

fn output_revision_content(content: &RevisionContent) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(0, output_review_span(content.span)?);
    output.set(1, JsValue::from_str(&content.text));
    output.set(
        2,
        JsValue::from_str(if content.formatting_only {
            "formatting-only"
        } else {
            "text"
        }),
    );
    Ok(output.into())
}

fn output_comment_content(content: &CommentContent) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(0, output_review_span(content.anchor)?);
    output.set(1, JsValue::from_str(&content.comment_text));
    output.set(2, JsValue::from_str(&content.referenced_text));
    Ok(output.into())
}

fn output_review_span(span: ReviewSpan) -> Result<JsValue, String> {
    let output = Array::new_with_length(2);
    output.set(0, output_review_point(span.start)?);
    output.set(1, output_review_point(span.end)?);
    Ok(output.into())
}

fn output_review_point(point: ReviewPoint) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(0, usize_number(point.paragraph_ordinal)?);
    output.set(1, JsValue::from_f64(f64::from(point.utf8)));
    output.set(2, JsValue::from_f64(f64::from(point.utf16)));
    Ok(output.into())
}

const fn review_unknown_reason(reason: ReviewFactUnknownReason) -> &'static str {
    match reason {
        ReviewFactUnknownReason::InvalidDocument => "invalid-document",
        ReviewFactUnknownReason::InvalidComments => "invalid-comments",
        ReviewFactUnknownReason::InvalidCommentsExtended => "invalid-comments-extended",
        ReviewFactUnknownReason::ResourceLimit => "resource-limit",
        ReviewFactUnknownReason::UnsupportedLocation => "unsupported-location",
    }
}

fn output_revision_status(status: &RevisionProjectionStatus) -> JsValue {
    let output = Array::new();
    match status {
        RevisionProjectionStatus::Complete => {
            output.push(&JsValue::from_str("complete"));
        }
        RevisionProjectionStatus::Incomplete(reasons) => {
            output.push(&JsValue::from_str("incomplete"));
            let output_reasons = Array::new();
            for reason in reasons {
                output_reasons.push(&JsValue::from_str(match reason {
                    RevisionUnsupportedReason::IncompatibleParagraphMerge => {
                        "incompatible-paragraph-merge"
                    }
                    RevisionUnsupportedReason::StructuralTableRevision => {
                        "structural-table-revision"
                    }
                    RevisionUnsupportedReason::UnsupportedRevisionMarkup => {
                        "unsupported-revision-markup"
                    }
                }));
            }
            output.push(&output_reasons);
        }
    }
    output.into()
}

fn output_structural_facts(facts: &DocumentStructureFacts) -> Result<JsValue, String> {
    let output = Array::new_with_length(5);
    output.set(
        0,
        output_fact_set(&facts.indentation, output_indentation_fact)?,
    );
    output.set(
        1,
        output_fact_set(&facts.numbering_hierarchy, output_numbering_fact)?,
    );
    output.set(2, output_fact_set(&facts.bookmarks, output_bookmark_fact)?);
    output.set(
        3,
        output_fact_set(&facts.internal_references, output_reference_fact)?,
    );
    output.set(
        4,
        output_fact_set(&facts.outline_levels, output_outline_level_fact)?,
    );
    Ok(output.into())
}

fn output_fact_set<T>(
    facts: &StructuralFactSet<T>,
    mut output_item: impl FnMut(&T) -> Result<JsValue, String>,
) -> Result<JsValue, String> {
    let output = Array::new_with_length(2);
    match facts {
        StructuralFactSet::Known(items) => {
            output.set(0, JsValue::from_str("known"));
            let output_items = Array::new();
            for item in items {
                output_items.push(&output_item(item)?);
            }
            output.set(1, output_items.into());
        }
        StructuralFactSet::Unknown(reason) => {
            output.set(0, JsValue::from_str("unknown"));
            output.set(1, JsValue::from_str(unknown_reason(*reason)));
        }
    }
    Ok(output.into())
}

fn output_indentation_fact(fact: &ParagraphIndentationFact) -> Result<JsValue, String> {
    let value = fact.value;
    let output = Array::new_with_length(13);
    output.set(0, usize_number(fact.paragraph_ordinal)?);
    for (item, index) in [
        value.first_line_twips,
        value.hanging_twips,
        value.left_twips,
        value.right_twips,
        value.start_twips,
        value.end_twips,
        value.first_line_chars_hundredths,
        value.hanging_chars_hundredths,
        value.left_chars_hundredths,
        value.right_chars_hundredths,
        value.start_chars_hundredths,
        value.end_chars_hundredths,
    ]
    .into_iter()
    .zip(1_u32..=12)
    {
        output.set(
            index,
            item.map_or(JsValue::NULL, |item_value| number(f64::from(item_value))),
        );
    }
    Ok(output.into())
}

fn output_numbering_fact(fact: &NumberingHierarchyFact) -> Result<JsValue, String> {
    let output = Array::new_with_length(3);
    output.set(0, usize_number(fact.paragraph_ordinal)?);
    output.set(
        1,
        fact.parent_paragraph_ordinal
            .map(usize_number)
            .transpose()?
            .unwrap_or(JsValue::NULL),
    );
    let children = Array::new();
    for child in &fact.child_paragraph_ordinals {
        children.push(&usize_number(*child)?);
    }
    output.set(2, children.into());
    Ok(output.into())
}

fn output_outline_level_fact(fact: &ParagraphOutlineLevelFact) -> Result<JsValue, String> {
    let output = Array::new_with_length(2);
    output.set(0, usize_number(fact.paragraph_ordinal)?);
    output.set(1, number(f64::from(fact.outline_level)));
    Ok(output.into())
}

fn output_bookmark_fact(fact: &BookmarkFact) -> Result<JsValue, String> {
    let output = Array::new_with_length(4);
    output.set(0, usize_number(fact.paragraph_ordinal)?);
    output.set(1, number(f64::from(fact.bookmark_id)));
    output.set(2, JsValue::from_str(&fact.name));
    output.set(3, output_span(fact.span));
    Ok(output.into())
}

fn output_reference_fact(fact: &InternalReferenceFact) -> Result<JsValue, String> {
    let output = Array::new_with_length(4);
    output.set(0, usize_number(fact.paragraph_ordinal)?);
    output.set(1, JsValue::from_str(&fact.reference_id));
    output.set(
        2,
        JsValue::from_str(match fact.role {
            InternalReferenceRole::Source => "source",
            InternalReferenceRole::Target => "target",
        }),
    );
    output.set(3, output_span(fact.span));
    Ok(output.into())
}

fn output_span(span: StructuralSpan) -> JsValue {
    let output = Array::new_with_length(5);
    output.set(0, number(f64::from(span.start_utf8)));
    output.set(1, number(f64::from(span.end_utf8)));
    output.set(2, number(f64::from(span.start_utf16)));
    output.set(3, number(f64::from(span.end_utf16)));
    output.set(
        4,
        JsValue::from_str(match span.coverage {
            SpanCoverage::Complete => "complete",
            SpanCoverage::ContinuesBefore => "continues-before",
            SpanCoverage::ContinuesAfter => "continues-after",
            SpanCoverage::ContinuesBeforeAndAfter => "continues-before-and-after",
        }),
    );
    output.into()
}

fn number(value: f64) -> JsValue {
    JsValue::from_f64(value)
}

fn usize_number(value: usize) -> Result<JsValue, String> {
    u32::try_from(value)
        .map(|value| number(f64::from(value)))
        .map_err(|_| "projection ordinal exceeds the wire format limit".to_owned())
}

const fn unknown_reason(reason: StructuralFactUnknownReason) -> &'static str {
    match reason {
        StructuralFactUnknownReason::DocumentPartOnly => "document-part-only",
        StructuralFactUnknownReason::StylesPartUnavailable => "styles-part-unavailable",
        StructuralFactUnknownReason::UnsupportedStyles => "unsupported-styles",
        StructuralFactUnknownReason::UnsupportedNumbering => "unsupported-numbering",
        StructuralFactUnknownReason::IncompleteBookmarkRanges => "incomplete-bookmark-ranges",
        StructuralFactUnknownReason::UnsupportedInternalReferences => {
            "unsupported-internal-references"
        }
    }
}

fn output_paragraph_structure(structure: Option<ParagraphStructure>) -> Result<JsValue, String> {
    let output = Array::new();
    if let Some(structure) = structure {
        output.push(&JsValue::from_str("table"));
        output.push(&JsValue::from_str(&format!(
            "table-{}",
            structure.table_ordinal
        )));
        output.push(&usize_number(structure.row)?);
        output.push(&usize_number(structure.column)?);
    }
    Ok(output.into())
}

fn js_error(error: &str) -> JsValue {
    js_sys::Error::new(error).into()
}