@docx-editor.dev/core 2.28.0 → 2.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/automation.cjs +1 -1
  2. package/dist/automation.d.ts +65 -13
  3. package/dist/automation.js +1 -1
  4. package/dist/binding.cjs +1 -1
  5. package/dist/binding.d.ts +54 -38
  6. package/dist/binding.js +1 -1
  7. package/dist/{index-Bsg7oIKP.d.ts → chrome-print-BM3Js-6X.d.ts} +281 -222
  8. package/dist/{chunk-Z6WBFXJU.js → chunk-2PV5L5NJ.js} +3 -3
  9. package/dist/chunk-4HENIAFG.js +1 -0
  10. package/dist/chunk-5OTS2EJ7.js +7 -0
  11. package/dist/chunk-5P4223J4.cjs +27 -0
  12. package/dist/{chunk-O2AL2HSJ.cjs → chunk-5RRAZMBU.cjs} +1 -1
  13. package/dist/chunk-5SPITS5F.js +18 -0
  14. package/dist/{chunk-VDNNLG6X.js → chunk-7ATNKARV.js} +1 -1
  15. package/dist/{chunk-SRPILEWV.cjs → chunk-BGCUTKWE.cjs} +5 -5
  16. package/dist/chunk-EBCXSH2W.js +3 -0
  17. package/dist/{chunk-K5U2PLDP.cjs → chunk-ERECKTIR.cjs} +1 -1
  18. package/dist/{chunk-QMLCVPCD.cjs → chunk-FLBEJC6X.cjs} +1 -1
  19. package/dist/{chunk-6AWEKBLB.cjs → chunk-HYASLE2G.cjs} +1 -1
  20. package/dist/chunk-JC47NRJC.cjs +3 -0
  21. package/dist/{chunk-ZUHOMK52.cjs → chunk-KJRTNY2Q.cjs} +1 -1
  22. package/dist/chunk-NKPUH3QJ.js +1 -0
  23. package/dist/chunk-PF5NJWS3.js +2 -0
  24. package/dist/chunk-PWTRJSES.cjs +18 -0
  25. package/dist/chunk-QFKGI242.cjs +30 -0
  26. package/dist/{chunk-5CSUYANV.js → chunk-RJCQGJR7.js} +1 -1
  27. package/dist/chunk-RPPV4S6T.cjs +4 -0
  28. package/dist/{chunk-TSLBZ26X.js → chunk-T32MGBJS.js} +1 -1
  29. package/dist/chunk-UM26GH5B.js +30 -0
  30. package/dist/chunk-V3N4SOAK.cjs +1 -0
  31. package/dist/chunk-VRCZBFLH.js +27 -0
  32. package/dist/{chunk-2GO5T2JU.cjs → chunk-WF7JZ755.cjs} +1 -1
  33. package/dist/chunk-WK5X2MMA.cjs +7 -0
  34. package/dist/{chunk-E7BQA6UP.js → chunk-WPDD2Y32.js} +1 -1
  35. package/dist/chunk-YBMWBXST.cjs +2 -0
  36. package/dist/{chunk-ETTO6GK3.js → chunk-YZGUBCHP.js} +1 -1
  37. package/dist/chunk-ZOS2PM4A.js +4 -0
  38. package/dist/collaboration/replication.cjs +1 -1
  39. package/dist/collaboration/replication.d.ts +5 -5
  40. package/dist/collaboration/replication.js +1 -1
  41. package/dist/collaboration.d.ts +4 -4
  42. package/dist/contracts/document.d.ts +3 -3
  43. package/dist/contracts/editor.d.ts +9 -10
  44. package/dist/contracts/interaction.d.ts +2 -2
  45. package/dist/contracts/modules.cjs +1 -1
  46. package/dist/contracts/modules.d.ts +33 -9
  47. package/dist/contracts/modules.js +1 -1
  48. package/dist/contracts/types.d.ts +2 -2
  49. package/dist/{custom-node-writes-cvL5rhcD.d.ts → custom-node-writes-0v0Kgw1T.d.ts} +2 -2
  50. package/dist/diagnostic-context-CcAO4q1s.d.ts +30 -0
  51. package/dist/diagnostic-hints-2Bke6H_w.d.ts +120 -0
  52. package/dist/{document-protection-BAGVGqaP.d.ts → document-protection-8eyMWIJ0.d.ts} +2 -2
  53. package/dist/{editor-Ci7IZGmG.d.ts → editor-DaEJd2so.d.ts} +460 -9
  54. package/dist/{editor-scope-OHPwVQ5l.d.ts → editor-scope-7o9xweiJ.d.ts} +1 -1
  55. package/dist/editor.cjs +1 -1
  56. package/dist/editor.d.ts +55 -33
  57. package/dist/editor.js +1 -1
  58. package/dist/export.cjs +2 -2
  59. package/dist/export.d.ts +17 -15
  60. package/dist/export.js +2 -2
  61. package/dist/{font-resolver-BVQB14qT.d.ts → font-resolver-CL9BVKZo.d.ts} +3 -3
  62. package/dist/font-shaping-policy-BvpkrfxM.d.ts +7 -0
  63. package/dist/{headless-document-view-qH331moE.d.ts → headless-document-view-DZQN8Bnx.d.ts} +2 -2
  64. package/dist/{image-resources-BN-hUgCn.d.ts → image-resources-Bipz8toD.d.ts} +2 -2
  65. package/dist/index.cjs +1 -1
  66. package/dist/index.d.ts +67 -21
  67. package/dist/index.js +1 -1
  68. package/dist/{layout-shaping-BEyuiQOk.d.ts → layout-shaping-cEnVrhWg.d.ts} +3 -2
  69. package/dist/layout.cjs +1 -1
  70. package/dist/layout.d.ts +42 -42
  71. package/dist/layout.js +1 -1
  72. package/dist/{note-properties-4Y9o6Gyk.d.ts → note-properties-9FH8zAeG.d.ts} +3 -3
  73. package/dist/{omml-equation-CuzBL5DD.d.ts → omml-equation-DP2WpUbK.d.ts} +13 -1
  74. package/dist/output.cjs +1 -1
  75. package/dist/output.d.ts +8 -9
  76. package/dist/output.js +1 -1
  77. package/dist/{protocol-Bqk4Izjc.d.ts → protocol-CZ1uUlPO.d.ts} +2 -2
  78. package/dist/{review-paragraph-order-DT-n6ouC.d.ts → review-paragraph-order-CqVelc5A.d.ts} +1 -1
  79. package/dist/{semantic-cell-selection-D9D1KSXq.d.ts → semantic-cell-selection-Dr9yxFZt.d.ts} +4 -211
  80. package/dist/{semantic-interaction-CIC-PooQ.d.ts → semantic-interaction-Dc3pf3hr.d.ts} +1 -1
  81. package/dist/{semantic-paint-BME37OMv.d.ts → semantic-paint-Bz3FBAoH.d.ts} +17 -5
  82. package/dist/{semantic-record-queries-CBlZqZNa.d.ts → semantic-record-queries-Bx0pl6kL.d.ts} +1 -1
  83. package/dist/{semantic-records-4B3WwFAi.d.ts → semantic-records-CjcF26ZL.d.ts} +892 -416
  84. package/dist/store.cjs +1 -1
  85. package/dist/store.d.ts +1463 -1574
  86. package/dist/store.js +1 -1
  87. package/dist/{tree-package-fragment-BeeKxDw8.d.ts → tree-package-store-DKhdEVym.d.ts} +238 -84
  88. package/dist/{tree-session-contract-CVbmlMlq.d.ts → tree-session-contract-CwnTEVLF.d.ts} +8 -6
  89. package/dist/{types-barrel-D3xCgQX6.d.ts → types-barrel-CA0xB8kH.d.ts} +548 -527
  90. package/package.json +3 -3
  91. package/dist/chunk-2RC2EPND.js +0 -3
  92. package/dist/chunk-4GBTELJV.cjs +0 -28
  93. package/dist/chunk-4R3TEXMN.js +0 -18
  94. package/dist/chunk-6APGXLBB.cjs +0 -3
  95. package/dist/chunk-6EYYL7FL.js +0 -1
  96. package/dist/chunk-EO4C5QJW.cjs +0 -2
  97. package/dist/chunk-FIJZIQXA.cjs +0 -18
  98. package/dist/chunk-FRXAOVTB.js +0 -28
  99. package/dist/chunk-J6BVWIDB.js +0 -2
  100. package/dist/chunk-JGNVNT2A.cjs +0 -2
  101. package/dist/chunk-KKIJG3C6.js +0 -2
  102. package/dist/chunk-LWDSDCMO.js +0 -27
  103. package/dist/chunk-NBCVVZOM.cjs +0 -1
  104. package/dist/chunk-O5INAWZQ.js +0 -1
  105. package/dist/chunk-RCHS4ZEH.cjs +0 -27
  106. package/dist/chunk-VHAVHCQY.js +0 -7
  107. package/dist/chunk-VX43VBAX.cjs +0 -7
  108. package/dist/review-pane-D9jm8DcY.d.ts +0 -128
  109. package/dist/revision-projection-DZ4kKVev.d.ts +0 -242
package/dist/store.d.ts CHANGED
@@ -12,21 +12,21 @@
12
12
  * @packageDocumentation
13
13
  * @public
14
14
  */
15
- import { e as ResourceLimits } from './image-resources-BN-hUgCn.js';
16
- export { C as CreateImageResourceCacheOptions, D as DEFAULT_IMAGE_RESOURCE_LIMITS, f as DEFAULT_LIMITS, H as HARD_CEILINGS, g as IMAGE_RESOURCE_HARD_CEILINGS, a as ImageDecodePort, I as ImageResourceLimits, h as ImageResourceLookup, b as ImageResourceState, M as MAX_SVG_SNIFF_BYTES, P as PreservedImageMime, R as RenderableImageMime, S as SupportedImageMime, V as ValidatedImageBytesHandle, i as ValidatedRasterHeader, j as createImageResourceCache, k as hasBoundedSvgRoot, l as imageResourceLookupFor, m as liveDrawingReferenceCount, r as resolveImageResourceLimits, n as resolveLimits, s as sniffImageMime, o as validateGifHeader, p as validateJpegHeader, q as validatePngHeader, v as validateRasterHeader } from './image-resources-BN-hUgCn.js';
17
- import { O as OoxmlPart, N as OoxmlNode, aP as OoxmlInvariantResult, aQ as OoxmlInvariantIssue, Z as OoxmlElement, ab as OoxmlParagraphNode, aR as OoxmlFldCharNode, aS as OoxmlFldSimpleNode, aT as OoxmlInstrTextNode, W as TreeDocOp, a8 as TreeOpRejection, aU as TreeOpResult, Q as OoxmlPackage, aV as RelationshipRecord, V as OoxmlGenericElementNode, aW as OoxmlHardBreakNode, aX as OoxmlAttribute, X as OoxmlProperty, f as ReviewRange, R as ReviewModelInput, a as ReviewItem, C as CommentRecord, e as ReviewPosition, aY as CommentThreadState, c as ReviewCommentItem, b as ReviewRevisionItem, aj as DrawingTreeDocOp, ak as ImpactClass, an as ImageWrapTarget } from './types-barrel-D3xCgQX6.js';
18
- export { aZ as ACCEPTED_PARAGRAPH_PROPERTIES, a_ as ACCEPTED_RUN_PROPERTIES, a$ as CONTENT_CONTROL_ID_MAX, b0 as CONTENT_CONTROL_PROPERTY_ORDER, b1 as CommentAnchor, b2 as CommentPosition, b3 as CommitTextFormFieldOp, b4 as ContentControlCheckbox, b5 as ContentControlCheckboxState, b6 as ContentControlDataBinding, b7 as ContentControlDateFormat, b8 as ContentControlEntry, b9 as ContentControlKind, ba as ContentControlLevel, bb as ContentControlListItem, bc as ContentControlLock, bd as ContentControlProperties, be as ContentTypeError, bf as ContentTypeIndex, bg as ContentTypeRecords, bh as DEFAULT_OOXML_PACKAGE_LIMITS, bi as DEFAULT_ZIP_LIMITS, bj as DefaultRecord, bk as DeleteTextOp, aL as DrawingImageEffects, am as DrawingKind, ap as DrawingLocks, ao as DrawingPositionInput, bl as HYPERLINK_RELATIONSHIP_TYPE, bm as HyperlinkKind, bn as HyperlinkTarget, bo as IMAGE_RELATIONSHIP_TYPE, aH as IMAGE_WRAP_TARGETS, bp as ImageRelationshipResolution, bq as IndexResult, br as InsertBuildingBlockOp, bs as InsertTextOp, bt as LegacyCheckboxFieldRange, bu as MAX_CONTENT_CONTROLS_PER_PART, bv as MAX_CONTENT_CONTROL_NESTING, bw as NameRejection, bx as NameResult, by as OFFICE_RELATIONSHIP_NAMESPACE_URI, bz as OOXML_NODE_IDENTITY_RULES, bA as OoxmlBodyNode, bB as OoxmlBookmarkEndNode, bC as OoxmlBookmarkStartNode, bD as OoxmlContentControlCalendarNode, bE as OoxmlContentControlCheckboxNode, bF as OoxmlContentControlCheckedNode, bG as OoxmlContentControlCheckedStateNode, bH as OoxmlContentControlComboBoxNode, $ as OoxmlContentControlContentNode, bI as OoxmlContentControlDataBindingNode, bJ as OoxmlContentControlDateFormatNode, bK as OoxmlContentControlDateNode, bL as OoxmlContentControlDropDownListNode, bM as OoxmlContentControlEndPropertiesNode, bN as OoxmlContentControlLidNode, bO as OoxmlContentControlListItemNode, _ as OoxmlContentControlNode, bP as OoxmlContentControlPropertiesNode, bQ as OoxmlContentControlStoreMappedDataAsNode, bR as OoxmlContentControlTextNode, bS as OoxmlContentControlUncheckedStateNode, ad as OoxmlContinuationSeparatorNode, bT as OoxmlDocumentNode, ae as OoxmlEndnotesNode, bU as OoxmlExternalTarget, af as OoxmlFootnotesNode, bV as OoxmlGenericExtensionAttribute, bW as OoxmlHyperlinkNode, bX as OoxmlInvariantIssueCode, bY as OoxmlKnownNodeAttribute, bZ as OoxmlNamespaceBinding, U as OoxmlNodeId, b_ as OoxmlNodeIdentityRules, ac as OoxmlNoteNode, ag as OoxmlNoteRefNode, ah as OoxmlNoteReferenceNode, a1 as OoxmlPackageLimits, Y as OoxmlPackageRejection, b$ as OoxmlPackageResult, c0 as OoxmlParagraphPropertiesNode, c1 as OoxmlPartMetadata, c2 as OoxmlReadRejection, c3 as OoxmlReadResult, c4 as OoxmlRunNode, c5 as OoxmlRunPropertiesNode, ai as OoxmlSeparatorNode, c6 as OoxmlTabNode, c7 as OoxmlTextElementNode, c8 as OoxmlTextNode, c9 as OoxmlWmlValAttribute, ca as OoxmlXmlSpaceAttribute, cb as OverrideRecord, cc as RelationshipError, cd as RelationshipSetResult, ce as RelationshipTargetResolver, cf as ResolveResult, cg as ResolvedRelationship, d as ReviewCustomItem, g as ReviewRevisionKind, h as RevisionAddress, a2 as RevisionAuthorEntry, a3 as RevisionAuthorResult, a4 as RevisionAuthorSkipReason, a5 as RevisionBatchEntry, a6 as RevisionBatchResult, a7 as RevisionBatchSkipReason, ch as SetLegacyCheckboxOp, ci as SetLegacyDropdownOp, cj as SetTextFormFieldDefaultOp, al as SourceCrop, ck as TABLE_BORDER_STYLES, cl as TabStopWrite, aJ as TableBorderStyle, cm as TargetMode, cn as TextFormFieldOptions, co as TextFormFieldRange, cp as TextFormFieldType, cq as TreeDocOpKind, cr as TreeOpEffect, cs as W15_NAMESPACE_URI, ct as WML_NAMESPACE_URI, cu as XMLNS_NAMESPACE_URI, cv as XML_NAMESPACE_URI, cw as XmlLimits, cx as XmlNode, cy as XmlRejection, cz as XmlResult, cA as ZipLimits, cB as ZipReadResult, cC as ZipRejection, cD as allocateContentControlId, cE as asciiFold, cF as buildContentTypeIndex, cG as buildRelationshipSet, cH as childElements, cI as commentAnchorsOfStory, cJ as commentsOfPart, cK as contentControlContentChildren, cL as contentControlContentNodeOf, cM as contentControlEndPropertiesNodeOf, cN as contentControlLevelOf, cO as contentControlPropertiesNodeOf, cP as contentControlPropertiesOf, cQ as contentControlTextOf, cR as contentControlsIn, cS as detectDuplicateNames, cT as extensionKey, cU as findContentControl, cV as findElement, cW as firstReviewRange, cX as flattenContentControls, cY as hasAnyComment, cZ as hyperlinkAnchorOf, c_ as hyperlinkRelationshipIdOf, c$ as hyperlinkTargetOf, d0 as isContentControlContentNode, d1 as isContentControlNode, d2 as isContentControlWrapper, d3 as isContentRevisionKind, d4 as isHyperlinkNode, d5 as isRangeMarkerKind, d6 as isValidMime, d7 as legacyCheckboxFieldsOf, d8 as lockForbidsEdit, d9 as lockForbidsRemoval, da as normalizePartName, db as orderedContentControlProperties, dc as parseContentControlId, dd as partNameKey, de as planRevisionAuthorChange, df as planRevisionBatch, dg as projectDrawing, dh as readOnOffChild, di as readOoxmlPackage, dj as readOoxmlPart, dk as readXml, dl as readZip, dm as resolveContentControlLock, dn as resolveContentType, dp as resolveImageRelationship, dq as resolveInternalTarget, dr as resolveRelationship, ds as reviewItemKey, dt as reviewItemRanges, du as textContent, dv as textFormFieldsOf, dw as threadStateOfPart, dx as validateExternalTarget, dy as withPart, dz as writeOoxmlPackage, dA as writeZip } from './types-barrel-D3xCgQX6.js';
19
- import { k as FieldResultsMode, e as TreeModelChange, f as TreeDocumentStore, T as TreePackageStore, S as StoryScope } from './tree-package-fragment-BeeKxDw8.js';
20
- export { l as AtomicNoteSpan, C as CascadeDeletedNoteReferencesOptions, D as DEFAULT_MAX_EDITABLE_STORY_PARTS, m as DrawingPropertyIdResult, F as FragmentPasteInput, j as FragmentPasteResult, n as HeaderFooterKind, o as HeaderFooterLifecycleImpact, p as HeaderFooterLifecycleOp, q as HeaderFooterLifecycleRejection, s as HeaderFooterLifecycleResult, H as HeaderFooterParts, b as HeaderFooterSectionResolution, t as HeaderFooterSlotMeta, c as HeaderFooterVariant, u as HistoryCaptureKind, d as HistoryGroup, M as MAX_FRAGMENT_DECODED_BYTES, v as MAX_NOTES_PER_PART, w as MAX_NOTE_REFERENCE_PARTS, x as MAX_NOTE_REFERENCE_SCAN, y as NOTE_ATOM_CHAR, z as NOTE_CONTINUATION_SEPARATOR_ID, B as NOTE_ID_MAX, E as NOTE_ID_MIN, G as NOTE_SEPARATOR_ID, J as NoteDiagnostic, K as NoteDiagnosticCode, N as NoteKind, L as NoteLifecycleImpact, O as NoteLifecycleOp, P as NoteLifecycleOptions, Q as NoteLifecycleRejection, U as NoteLifecycleResult, V as NoteReferenceHit, W as NoteReferenceScanBudget, X as NoteType, Y as PackageTransactResult, Z as RemotePackageAttribution, g as SelectionMark, _ as StoryResolveResult, a as StoryTargetRejection, $ as TreeDocumentStoreOptions, a0 as TreePackageStoreOptions, a1 as TreeStoryRef, h as TreeTransactOptions, a2 as TreeTransactResult, a3 as TreeTransactionContext, a4 as allocateDrawingPropertyId, a5 as allocateNoteId, a6 as applyFragmentPaste, a7 as applyHeaderFooterLifecycleOp, a8 as applyNoteLifecycleOp, a9 as atomicNoteSpansOf, aa as cascadeDeletedNoteReferences, ab as collectNoteReferences, ac as collectPackageNoteReferences, ad as collectSectionPropertyNodes, ae as createNoteReferenceScanBudget, af as customMarkFollows, ag as diagnoseNoteReferences, ah as findNoteById, ai as formatNoteScopeId, aj as isContinuationSeparatorNode, ak as isEndnotesNode, al as isFootnotesNode, am as isHeaderFooterLifecycleOp, an as isNormalNote, ao as isNoteAtomNode, ap as isNoteLifecycleOp, aq as isNoteNode, ar as isNoteRefNode, as as isNoteReferenceNode, at as isSeparatorNode, au as normalNoteIds, av as noteAtomText, aw as noteIdOf, ax as noteKindOf, ay as noteRefKindOf, az as noteReferenceKindOf, aA as noteTypeOf, aB as notesOf, aC as notesPartHasId, aD as observeHistoryGroup, aE as parseNoteId, aF as parseNoteScopeId, r as reportHistoryGroup, aG as resolveHeaderFooterParts, aH as resolveHeaderFooterPartsBySection, aI as resolveHeaderFooterResolutionBySection, aJ as resolveNotesPart, aK as withBinaryPart, aL as withEmbeddedImage, aM as withoutUnreferencedImagePart } from './tree-package-fragment-BeeKxDw8.js';
21
- import { O as OmmlEquationProjection } from './omml-equation-CuzBL5DD.js';
22
- export { D as DEFAULT_OMML_LIMITS, E as EquationExpression, L as LinearMathOmmlResult, a as LinearMathParseResult, b as LinearMathRejection, c as OFFICE_MATH_NAMESPACE_URI, d as OmmlLimits, e as equationExpressionToLinearMath, l as linearMathToOmml, p as parseLinearMath, f as projectOmmlEquation } from './omml-equation-CuzBL5DD.js';
23
- import { I as InsertCustomNodeWrite, C as CustomNodeWriteResult } from './custom-node-writes-cvL5rhcD.js';
24
- export { b as BookmarkAnchor, B as BookmarkIndex, c as CustomNodePayloadRead, d as CustomNodePayloadWrite, a as CustomNodeSweepOutcome, e as CustomNodeSweepResult, f as CustomNodeWriteRejection, D as DocumentTrackingSettings, E as EmbeddedFont, F as FontStyleKey, L as ListKind, M as MAX_CUSTOM_NODE_LABEL_LENGTH, g as MAX_CUSTOM_NODE_PAYLOAD_LENGTH, N as NO_TRACKING_SETTINGS, R as ReadEmbeddedFontsOptions, h as buildBookmarkIndex, i as customNodePayloadsByControl, j as customNodePayloadsOf, k as deobfuscateFont, l as ensureListDefinition, m as ensureNumberingLevel, n as insertCustomNodeWrite, r as readEmbeddedFonts, o as readTrackingSettings, p as removeCustomNodeWrite, s as sweepCustomNodePayloads } from './custom-node-writes-cvL5rhcD.js';
25
- export { c as collectFlowBlocks, a as commentBodyText, b as commentInitials, d as contentControlContentOf, e as deepParagraphOrderOfPart, i as isContentControl, f as isContentControlContent, p as paragraphOrderOfPart, w as walkAllStoryParagraphs, g as walkParagraphInline, h as walkStoryBlocks } from './review-paragraph-order-DT-n6ouC.js';
26
- export { D as DocumentProperties, E as EnsuredHyperlinkRelationship, a as HeadlessDocumentRejection, H as HeadlessDocumentView, b as HeadlessThemeFonts, O as OpenHeadlessDocumentResult, c as authorableHyperlinkTarget, e as ensureHyperlinkRelationship, h as headlessViewOfStore, o as openHeadlessDocument, r as relationshipTargetIn } from './headless-document-view-qH331moE.js';
27
- export { A as AuthoredNoteProperties, D as DEFAULT_ENDNOTE_PROPERTIES, a as DEFAULT_FOOTNOTE_PROPERTIES, E as EndnotePosition, F as FootnotePosition, N as NoteNumRestart, R as ResolvedEndnoteProperties, b as ResolvedFootnoteProperties, c as authoredDocumentEndnoteProperties, d as authoredDocumentFootnoteProperties, e as authoredEndnotePropertiesFromSectPr, f as authoredFootnotePropertiesFromSectPr, i as isLegalEndnotePosition, g as isLegalFootnotePosition, h as isLegalNumRestart, p as parseAuthoredNoteProperties, r as resolveEndnoteProperties, j as resolveFootnoteProperties, s as settingsPartOf } from './note-properties-4Y9o6Gyk.js';
28
- export { a as DocumentProtectionEdit, D as DocumentProtectionState, N as NO_DOCUMENT_PROTECTION, r as readDocumentProtection } from './document-protection-BAGVGqaP.js';
29
- import './editor-scope-OHPwVQ5l.js';
15
+ import { e as ResourceLimits } from './image-resources-Bipz8toD.js';
16
+ export { C as CreateImageResourceCacheOptions, D as DEFAULT_IMAGE_RESOURCE_LIMITS, f as DEFAULT_LIMITS, H as HARD_CEILINGS, g as IMAGE_RESOURCE_HARD_CEILINGS, c as ImageDecodePort, b as ImageResourceLimits, h as ImageResourceLookup, I as ImageResourceState, M as MAX_SVG_SNIFF_BYTES, P as PreservedImageMime, R as RenderableImageMime, S as SupportedImageMime, V as ValidatedImageBytesHandle, i as ValidatedRasterHeader, j as createImageResourceCache, k as hasBoundedSvgRoot, l as imageResourceLookupFor, m as liveDrawingReferenceCount, r as resolveImageResourceLimits, n as resolveLimits, s as sniffImageMime, o as validateGifHeader, p as validateJpegHeader, q as validatePngHeader, v as validateRasterHeader } from './image-resources-Bipz8toD.js';
17
+ import { O as OoxmlPart, N as OoxmlNode, aV as OoxmlInvariantResult, aA as OoxmlParagraphNode, aW as OoxmlFldCharNode, aX as OoxmlFldSimpleNode, aY as OoxmlInstrTextNode, ag as TreeDocOp, av as TreeOpRejection, aZ as TreeOpResult, Q as OoxmlPackage, a_ as RelationshipRecord, ah as OoxmlElement, V as OoxmlGenericElementNode, a$ as OoxmlHardBreakNode, b0 as OoxmlAttribute, am as OoxmlProperty, au as RevisionSiteRefusal, f as ReviewRange, R as ReviewModelInput, a as ReviewItem, C as CommentRecord, e as ReviewPosition, b1 as CommentThreadState, c as ReviewCommentItem, b as ReviewRevisionItem, az as DrawingTreeDocOp, aI as ImpactClass, a1 as ImageWrapTarget } from './types-barrel-CA0xB8kH.js';
18
+ export { b2 as ACCEPTED_PARAGRAPH_PROPERTIES, b3 as ACCEPTED_RUN_PROPERTIES, b4 as CONTENT_CONTROL_ID_MAX, b5 as CONTENT_CONTROL_PROPERTY_ORDER, b6 as CommentAnchor, b7 as CommentPosition, b8 as CommitTextFormFieldOp, b9 as ContentControlCheckbox, ba as ContentControlCheckboxState, bb as ContentControlDataBinding, bc as ContentControlDateFormat, bd as ContentControlEntry, be as ContentControlKind, bf as ContentControlLevel, bg as ContentControlListItem, bh as ContentControlLock, bi as ContentControlProperties, bj as ContentTypeError, bk as ContentTypeIndex, bl as ContentTypeRecords, bm as DEFAULT_OOXML_PACKAGE_LIMITS, bn as DEFAULT_ZIP_LIMITS, bo as DefaultRecord, bp as DeleteTextOp, aS as DrawingImageEffects, Y as DrawingKind, Z as DrawingLocks, _ as DrawingPositionInput, bq as HYPERLINK_RELATIONSHIP_TYPE, br as HyperlinkKind, bs as HyperlinkTarget, bt as IMAGE_RELATIONSHIP_TYPE, aL as IMAGE_WRAP_TARGETS, bu as ImageRelationshipResolution, bv as IndexResult, bw as InsertBuildingBlockOp, bx as InsertTextOp, by as LegacyCheckboxFieldRange, bz as MAX_CONTENT_CONTROLS_PER_PART, bA as MAX_CONTENT_CONTROL_NESTING, bB as NameRejection, bC as NameResult, bD as OFFICE_RELATIONSHIP_NAMESPACE_URI, bE as OOXML_NODE_IDENTITY_RULES, bF as OoxmlBodyNode, bG as OoxmlBookmarkEndNode, bH as OoxmlBookmarkStartNode, bI as OoxmlContentControlCalendarNode, bJ as OoxmlContentControlCheckboxNode, bK as OoxmlContentControlCheckedNode, bL as OoxmlContentControlCheckedStateNode, bM as OoxmlContentControlComboBoxNode, aj as OoxmlContentControlContentNode, bN as OoxmlContentControlDataBindingNode, bO as OoxmlContentControlDateFormatNode, bP as OoxmlContentControlDateNode, bQ as OoxmlContentControlDropDownListNode, bR as OoxmlContentControlEndPropertiesNode, bS as OoxmlContentControlLidNode, bT as OoxmlContentControlListItemNode, ai as OoxmlContentControlNode, bU as OoxmlContentControlPropertiesNode, bV as OoxmlContentControlStoreMappedDataAsNode, bW as OoxmlContentControlTextNode, bX as OoxmlContentControlUncheckedStateNode, aC as OoxmlContinuationSeparatorNode, bY as OoxmlDocumentNode, aD as OoxmlEndnotesNode, bZ as OoxmlExternalTarget, aE as OoxmlFootnotesNode, b_ as OoxmlGenericExtensionAttribute, b$ as OoxmlHyperlinkNode, ay as OoxmlInvariantIssue, c0 as OoxmlInvariantIssueCode, c1 as OoxmlKnownNodeAttribute, c2 as OoxmlNamespaceBinding, U as OoxmlNodeId, c3 as OoxmlNodeIdentityRules, aB as OoxmlNoteNode, aF as OoxmlNoteRefNode, aG as OoxmlNoteReferenceNode, ao as OoxmlPackageLimits, ak as OoxmlPackageRejection, an as OoxmlPackageResult, c4 as OoxmlParagraphPropertiesNode, c5 as OoxmlPartMetadata, c6 as OoxmlReadRejection, c7 as OoxmlReadResult, c8 as OoxmlRunNode, c9 as OoxmlRunPropertiesNode, aH as OoxmlSeparatorNode, ca as OoxmlTabNode, cb as OoxmlTextElementNode, cc as OoxmlTextNode, cd as OoxmlWmlValAttribute, ce as OoxmlXmlSpaceAttribute, cf as OverrideRecord, cg as RelationshipError, ch as RelationshipSetResult, ci as RelationshipTargetResolver, cj as ResolveResult, ck as ResolvedRelationship, d as ReviewCustomItem, g as ReviewRevisionKind, h as RevisionAddress, ap as RevisionAuthorEntry, a8 as RevisionAuthorResult, aq as RevisionAuthorSkipReason, ar as RevisionBatchEntry, a9 as RevisionBatchResult, as as RevisionBatchSkipDetail, at as RevisionBatchSkipReason, cl as SetLegacyCheckboxOp, cm as SetLegacyDropdownOp, cn as SetTextFormFieldDefaultOp, aJ as SourceCrop, co as TABLE_BORDER_STYLES, cp as TabStopWrite, aQ as TableBorderStyle, cq as TargetMode, aO as TextFormFieldOptions, aN as TextFormFieldRange, cr as TextFormFieldType, cs as TreeDocOpKind, ct as TreeOpEffect, cu as W15_NAMESPACE_URI, cv as WML_NAMESPACE_URI, cw as XMLNS_NAMESPACE_URI, cx as XML_NAMESPACE_URI, cy as XmlLimits, cz as XmlNode, cA as XmlRejection, cB as XmlResult, cC as ZipLimits, cD as ZipReadResult, cE as ZipRejection, cF as allocateContentControlId, cG as asciiFold, cH as buildContentTypeIndex, cI as buildRelationshipSet, cJ as childElements, cK as commentAnchorsOfStory, cL as commentsOfPart, cM as contentControlContentChildren, cN as contentControlContentNodeOf, cO as contentControlEndPropertiesNodeOf, cP as contentControlLevelOf, cQ as contentControlPropertiesNodeOf, cR as contentControlPropertiesOf, cS as contentControlTextOf, cT as contentControlsIn, cU as detectDuplicateNames, cV as extensionKey, cW as findContentControl, cX as findElement, cY as firstReviewRange, cZ as flattenContentControls, c_ as hasAnyComment, c$ as hyperlinkAnchorOf, d0 as hyperlinkRelationshipIdOf, d1 as hyperlinkTargetOf, d2 as isContentControlContentNode, d3 as isContentControlNode, d4 as isContentControlWrapper, d5 as isContentRevisionKind, d6 as isHyperlinkNode, d7 as isRangeMarkerKind, d8 as isValidMime, d9 as legacyCheckboxFieldsOf, da as lockForbidsEdit, db as lockForbidsRemoval, dc as normalizePartName, dd as orderedContentControlProperties, de as parseContentControlId, df as partNameKey, dg as planRevisionAuthorChange, dh as planRevisionBatch, di as projectDrawing, dj as readOnOffChild, dk as readOoxmlPackage, dl as readOoxmlPart, dm as readXml, dn as readZip, dp as resolveContentControlLock, dq as resolveContentType, dr as resolveImageRelationship, ds as resolveInternalTarget, dt as resolveRelationship, du as reviewItemKey, dv as reviewItemRanges, dw as textContent, dx as textFormFieldsOf, dy as threadStateOfPart, dz as validateExternalTarget, dA as withPart, dB as writeOoxmlPackage, dC as writeZip } from './types-barrel-CA0xB8kH.js';
19
+ import { F as FieldResultsMode, E as EditOptions, e as TreeModelChange, f as TreeDocumentStore, T as TreePackageStore, S as StoryScope } from './tree-package-store-DKhdEVym.js';
20
+ export { l as AtomicNoteSpan, m as CascadeDeletedNoteReferencesOptions, C as ContentLockPolicy, D as DEFAULT_MAX_EDITABLE_STORY_PARTS, n as DrawingPropertyIdResult, j as FragmentPasteInput, k as FragmentPasteResult, o as HeaderFooterKind, p as HeaderFooterLifecycleImpact, q as HeaderFooterLifecycleOp, s as HeaderFooterLifecycleRejection, t as HeaderFooterLifecycleResult, H as HeaderFooterParts, a as HeaderFooterSectionResolution, u as HeaderFooterSlotMeta, c as HeaderFooterVariant, v as HistoryCaptureKind, d as HistoryGroup, M as MAX_FRAGMENT_DECODED_BYTES, w as MAX_NOTES_PER_PART, x as MAX_NOTE_REFERENCE_PARTS, y as MAX_NOTE_REFERENCE_SCAN, z as NOTE_ATOM_CHAR, B as NOTE_CONTINUATION_SEPARATOR_ID, G as NOTE_ID_MAX, J as NOTE_ID_MIN, K as NOTE_SEPARATOR_ID, L as NoteDiagnostic, O as NoteDiagnosticCode, N as NoteKind, P as NoteLifecycleImpact, Q as NoteLifecycleOp, U as NoteLifecycleOptions, V as NoteLifecycleRejection, W as NoteLifecycleResult, X as NoteReferenceHit, Y as NoteReferenceScanBudget, Z as NoteType, _ as OoxmlEditResult, $ as PackageTransactResult, a0 as RemotePackageAttribution, g as SelectionMark, a1 as StoryResolveResult, b as StoryTargetRejection, a2 as TransactionRevisionIds, a3 as TreeDocumentStoreOptions, a4 as TreePackageStoreOptions, a5 as TreeStoryRef, h as TreeTransactOptions, a6 as TreeTransactResult, a7 as TreeTransactionContext, a8 as allocateDrawingPropertyId, a9 as allocateNoteId, aa as applyEdits, ab as applyFragmentPaste, ac as applyHeaderFooterLifecycleOp, ad as applyNoteLifecycleOp, ae as atomicNoteSpansOf, af as cascadeDeletedNoteReferences, ag as collectNodeIds, ah as collectNoteReferences, ai as collectPackageNoteReferences, aj as collectSectionPropertyNodes, ak as createNodeIdAllocator, al as createNoteReferenceScanBudget, am as customMarkFollows, an as diagnoseNoteReferences, ao as findNode, ap as findNoteById, aq as formatNoteScopeId, ar as hasNode, as as insertChildren, at as isContinuationSeparatorNode, au as isEndnotesNode, av as isFootnotesNode, aw as isHeaderFooterLifecycleOp, ax as isNormalNote, ay as isNoteAtomNode, az as isNoteLifecycleOp, aA as isNoteNode, aB as isNoteRefNode, aC as isNoteReferenceNode, aD as isSeparatorNode, aE as normalNoteIds, aF as noteAtomText, aG as noteIdOf, aH as noteKindOf, aI as noteRefKindOf, aJ as noteReferenceKindOf, aK as noteTypeOf, aL as notesOf, aM as notesPartHasId, aN as observeHistoryGroup, aO as parentNodeOf, aP as parseNoteId, aQ as parseNoteScopeId, aR as removeNode, aS as replaceChildren, aT as replaceNode, r as reportHistoryGroup, aU as resolveHeaderFooterParts, aV as resolveHeaderFooterPartsBySection, aW as resolveHeaderFooterResolutionBySection, aX as resolveNotesPart, aY as withBinaryPart, aZ as withEmbeddedImage, a_ as withoutUnreferencedImagePart } from './tree-package-store-DKhdEVym.js';
21
+ import { O as OmmlEquationProjection } from './omml-equation-DP2WpUbK.js';
22
+ export { D as DEFAULT_OMML_LIMITS, E as EquationExpression, L as LinearMathOmmlResult, a as LinearMathParseResult, b as LinearMathRejection, c as OFFICE_MATH_NAMESPACE_URI, d as OmmlLimits, e as equationExpressionToLinearMath, l as linearMathToOmml, p as parseLinearMath, f as projectOmmlEquation } from './omml-equation-DP2WpUbK.js';
23
+ import { I as InsertCustomNodeWrite, C as CustomNodeWriteResult } from './custom-node-writes-0v0Kgw1T.js';
24
+ export { b as BookmarkAnchor, B as BookmarkIndex, c as CustomNodePayloadRead, d as CustomNodePayloadWrite, a as CustomNodeSweepOutcome, e as CustomNodeSweepResult, f as CustomNodeWriteRejection, D as DocumentTrackingSettings, E as EmbeddedFont, F as FontStyleKey, L as ListKind, M as MAX_CUSTOM_NODE_LABEL_LENGTH, g as MAX_CUSTOM_NODE_PAYLOAD_LENGTH, N as NO_TRACKING_SETTINGS, R as ReadEmbeddedFontsOptions, h as buildBookmarkIndex, i as customNodePayloadsByControl, j as customNodePayloadsOf, k as deobfuscateFont, l as ensureListDefinition, m as ensureNumberingLevel, n as insertCustomNodeWrite, r as readEmbeddedFonts, o as readTrackingSettings, p as removeCustomNodeWrite, s as sweepCustomNodePayloads } from './custom-node-writes-0v0Kgw1T.js';
25
+ export { c as collectFlowBlocks, a as commentBodyText, b as commentInitials, d as contentControlContentOf, e as deepParagraphOrderOfPart, i as isContentControl, f as isContentControlContent, p as paragraphOrderOfPart, w as walkAllStoryParagraphs, g as walkParagraphInline, h as walkStoryBlocks } from './review-paragraph-order-CqVelc5A.js';
26
+ export { D as DocumentProperties, E as EnsuredHyperlinkRelationship, a as HeadlessDocumentRejection, H as HeadlessDocumentView, b as HeadlessThemeFonts, O as OpenHeadlessDocumentResult, c as authorableHyperlinkTarget, e as ensureHyperlinkRelationship, h as headlessViewOfStore, o as openHeadlessDocument, r as relationshipTargetIn } from './headless-document-view-DZQN8Bnx.js';
27
+ export { A as AuthoredNoteProperties, D as DEFAULT_ENDNOTE_PROPERTIES, b as DEFAULT_FOOTNOTE_PROPERTIES, E as EndnotePosition, F as FootnotePosition, N as NoteNumRestart, a as ResolvedEndnoteProperties, R as ResolvedFootnoteProperties, c as authoredDocumentEndnoteProperties, d as authoredDocumentFootnoteProperties, e as authoredEndnotePropertiesFromSectPr, f as authoredFootnotePropertiesFromSectPr, i as isLegalEndnotePosition, g as isLegalFootnotePosition, h as isLegalNumRestart, p as parseAuthoredNoteProperties, r as resolveEndnoteProperties, j as resolveFootnoteProperties, s as settingsPartOf } from './note-properties-9FH8zAeG.js';
28
+ export { D as DocumentProtectionEdit, a as DocumentProtectionState, N as NO_DOCUMENT_PROTECTION, r as readDocumentProtection } from './document-protection-8eyMWIJ0.js';
29
+ import './editor-scope-7o9xweiJ.js';
30
30
 
31
31
  /**
32
32
  * Serialize normalized XML from a canonical part using repository-controlled
@@ -51,119 +51,6 @@ declare function ooxmlTreesEqual(left: OoxmlPart | OoxmlNode, right: OoxmlPart |
51
51
  */
52
52
  declare function validateOoxmlPart(part: OoxmlPart): OoxmlInvariantResult;
53
53
 
54
- /** An edited part, or the invariant violations that rejected the edit. */
55
- type OoxmlEditResult = {
56
- readonly ok: true;
57
- readonly part: OoxmlPart;
58
- } | {
59
- readonly ok: false;
60
- readonly issues: readonly OoxmlInvariantIssue[];
61
- };
62
- /**
63
- * How an edit primitive validates its result.
64
- *
65
- * By default every primitive runs the full-part invariant validation before handing its
66
- * result back — the safe reading for an isolated call. A TRANSACTION applying many ops pays
67
- * that full-tree walk once per primitive, which is what made a hundred-paragraph paste
68
- * quadratic; it defers instead, and runs the same validation ONCE on the final tree before
69
- * anything is published. Deferring is only sound for a caller that owns a commit boundary:
70
- * nothing may escape between the unvalidated intermediate and the validated result.
71
- */
72
- interface EditOptions {
73
- readonly deferValidation?: boolean;
74
- /**
75
- * A shared minter for `@w:id` on a NEW revision, for the ops of one transaction.
76
- *
77
- * `nextRevisionId` walks the whole part to find the highest id in use, and a formatting
78
- * write emits one op per run — so a Select All + Bold in suggesting mode paid a
79
- * document-wide walk thousands of times over. The transaction hands its ops one minter
80
- * instead, and it is DROPPED the moment an op that can import foreign revision ids runs
81
- * (a paste carries its own), because a stale minter would hand out an id the document had
82
- * just started using — and two revisions sharing an address are one card in the pane.
83
- *
84
- * Absent means "mint your own": every applier falls back to its own walk, which is what a
85
- * caller outside a transaction gets.
86
- */
87
- readonly revisionIds?: () => string;
88
- /**
89
- * The transaction's revision-id bookkeeping for the tracked TEXT ops, where `revisionIds`
90
- * above hands the property ops one shared id for their whole group.
91
- *
92
- * Absent means "mint your own and remember nothing", which is what a caller outside a
93
- * transaction gets: every applier falls back to its own walk of the part.
94
- */
95
- readonly trackedRevisionIds?: TransactionRevisionIds;
96
- /**
97
- * How the op addresses saved field results (`field-result-mode.ts`). Absent keeps the mode
98
- * of the enclosing store call, which is `atomic` outside any editable transaction.
99
- */
100
- readonly fieldResults?: FieldResultsMode;
101
- }
102
- /**
103
- * What one transaction knows about the revision ids its tracked text ops write.
104
- *
105
- * TWO questions, and they are the same bookkeeping. `nextRevisionId` walks the whole part, so
106
- * a replacement — a `deleteText` and an `insertText` in one transaction — walked it twice, and
107
- * on a five-hundred-page document that doubled the cost of every one. And an insertion aimed
108
- * at the front edge of a deletion relocates past it only when that deletion is THIS
109
- * transaction's own: typing over a selection. Backspace, then a keystroke, is two
110
- * transactions, and there the typed text belongs in FRONT of the struck character, as Word
111
- * writes it. Adjacency alone cannot tell the two apart; the ids can.
112
- */
113
- interface TransactionRevisionIds {
114
- /** A fresh `@w:id`, from this transaction's one walk of the part. */
115
- mint(): string;
116
- /**
117
- * Record a wrapper this transaction wrote, by its FULL `CT_TrackChange` identity — id,
118
- * author and date, as `revisionKey` spells it. Not by the id alone: that number comes out
119
- * of the file, nothing makes it unique, and a strike joining `w:id="3"` in one paragraph
120
- * would otherwise claim an unrelated `w:id="3"` elsewhere as this edit's own.
121
- */
122
- wrote(key: string): void;
123
- /** Whether this transaction wrote a wrapper with that identity. */
124
- wroteUnder(key: string): boolean;
125
- }
126
- /** Every node id currently present in the part. */
127
- declare function collectNodeIds(part: OoxmlPart): Set<string>;
128
- /**
129
- * Mint ids for nodes an edit introduces.
130
- *
131
- * Deterministic and collision-checked against the whole part: a structural-path id from the
132
- * original parse (`/word/document.xml#0.1.2`) and a minted one (`/word/document.xml#new:3`)
133
- * can never coincide, and the counter skips anything already taken so repeated edits in one
134
- * session stay unique.
135
- *
136
- * Allocators share reservations across edited roots and restored roots. Preview edits,
137
- * detached nodes, and undo branches must not reuse an identity that collaboration retains.
138
- *
139
- * Checks the part's node index directly rather than copying every id into a fresh set: the
140
- * copy was O(document) per op, and an allocator is created for every op.
141
- */
142
- declare function createNodeIdAllocator(part: OoxmlPart, family?: 'new' | 'paste'): () => string;
143
- /** Whether a node id exists in the part. */
144
- declare function hasNode(part: OoxmlPart, nodeId: string): boolean;
145
- /** Read a node back out of a part by id. */
146
- declare function findNode(part: OoxmlPart, nodeId: string): OoxmlNode | null;
147
- /** The element that holds a node, or null for the root and for unknown ids. */
148
- declare function parentNodeOf(part: OoxmlPart, nodeId: string): OoxmlElement | null;
149
- /** Replace one node's children wholesale. */
150
- declare function replaceChildren(part: OoxmlPart, nodeId: string, children: readonly OoxmlNode[], options?: EditOptions): OoxmlEditResult;
151
- /** Insert children into a node at `index` (clamped to the child list). */
152
- declare function insertChildren(part: OoxmlPart, nodeId: string, index: number, children: readonly OoxmlNode[], options?: EditOptions): OoxmlEditResult;
153
- /** Replace one node with another, keeping its position among its siblings. */
154
- declare function replaceNode(part: OoxmlPart, nodeId: string, replacement: OoxmlNode, options?: EditOptions): OoxmlEditResult;
155
- /** Remove a node and its subtree. */
156
- declare function removeNode(part: OoxmlPart, nodeId: string, options?: EditOptions): OoxmlEditResult;
157
- /**
158
- * Apply several primitives as ONE atomic step.
159
- *
160
- * Each edit runs against the result of the previous one, and the whole sequence is
161
- * validated once at the end. If any step fails, the ORIGINAL part is what the caller keeps
162
- * — there is no partially-edited intermediate to publish. This is the shape a multi-`DocOp`
163
- * store transaction needs.
164
- */
165
- declare function applyEdits(part: OoxmlPart, edits: readonly ((current: OoxmlPart) => OoxmlEditResult)[], options?: EditOptions): OoxmlEditResult;
166
-
167
54
  /** UTF-16 placeholder for one atomic field unit in `paragraphTextOf` / segments. */
168
55
  declare const FIELD_ATOM_CHAR = "\uFFFC";
169
56
  /**
@@ -355,7 +242,7 @@ declare function inlineControlEndingAt(paragraph: OoxmlParagraphNode, offset: nu
355
242
  declare function inlineControlStartingAt(paragraph: OoxmlParagraphNode, offset: number): InlineControlSpan | null;
356
243
 
357
244
  /** Structural validation, run before any tree work so a rejection changes nothing. */
358
- declare function validateTreeOp(part: OoxmlPart, op: TreeDocOp): TreeOpRejection | null;
245
+ declare function validateTreeOp(part: OoxmlPart, op: TreeDocOp, options?: Pick<EditOptions, 'contentLockPolicy'>): TreeOpRejection | null;
359
246
 
360
247
  /**
361
248
  * Paragraph text as the ops address it, for tests and callers computing offsets.
@@ -376,1716 +263,1716 @@ declare function paragraphTextOf(part: OoxmlPart, paragraphId: string, options?:
376
263
  declare function applyTreeOp(part: OoxmlPart, op: TreeDocOp, options?: EditOptions): TreeOpResult;
377
264
 
378
265
  /**
379
- * Every kind of thing the registry gives a stable identity to.
266
+ * Keys that must never be assigned from file data.
380
267
  *
381
- * Identity is `(kind, id)` plus version and NEVER registration order, so two bundles contributing
382
- * the same command resolve deterministically regardless of which loaded first.
268
+ * XML attribute names become object keys, and a document controls those names — assigning
269
+ * `__proto__` into an ordinary object is the prototype-pollution hazard this engine audits for.
383
270
  */
384
- declare const ID_KINDS: readonly ['extension', 'capability', 'command', 'query', 'schema', 'dependencyKey', 'runtimePort', 'result', 'origin'];
385
- /** One of {@link ID_KINDS}. */
386
- /** One of {@link ID_KINDS} — which sort of thing an identifier names. */
387
- type IdKind = (typeof ID_KINDS)[number];
271
+ declare const DANGEROUS_KEYS: readonly string[];
272
+ /** A file-derived key that would pollute a prototype. Refused, never sanitized-and-accepted. */
273
+ declare class DangerousKeyError extends Error {
274
+ readonly key: string;
275
+ readonly path: string;
276
+ constructor(key: string, path: string);
277
+ }
278
+ /** Whether a key is one of {@link DANGEROUS_KEYS}. */
279
+ declare function isDangerousKey(key: string): boolean;
280
+ /** A fresh null-prototype record — the only object shape parser intermediates use. */
281
+ declare function nullRecord<T = unknown>(): Record<string, T>;
388
282
  /**
389
- * Whether a string is a well-formed identifier in either accepted grammar.
390
- *
391
- * Reverse-domain (`dev.docx-editor.core.command.insert-text`) or package-owned
392
- * (`@docx-editor.dev/engine-core#command/insert-text`). Ids are opaque once validated.
283
+ * Recursively convert `value` into null-prototype records, rejecting any
284
+ * dangerous object key. Arrays and primitives pass through (arrays rebuilt so no
285
+ * inherited prototype pollution survives). Throws DangerousKeyError on the first
286
+ * unsafe key, naming its path. Cyclic inputs are rejected.
393
287
  */
394
- declare function isValidId(id: string): boolean;
288
+ declare function toSafeRecord(value: unknown, path?: string): unknown;
289
+
290
+ /** Locate `[Content_Types].xml` bytes regardless of zip key spelling. */
291
+ declare function contentTypesPartBytes(pkg: OoxmlPackage): {
292
+ readonly storageKey: string;
293
+ readonly bytes: Uint8Array;
294
+ } | null;
395
295
  /**
396
- * Validate an identifier, throwing when it is malformed.
296
+ * What a package-level invariant walk found wrong.
397
297
  *
398
- * Throws rather than returning: a bad id is an author mistake at registration time, not file
399
- * input, and accepting it would produce a registry whose identities silently collide.
298
+ * Package invariants are cross-PART: a relationship pointing at a part that does not exist, or a
299
+ * part no content-type record covers. Neither is visible from inside a single part's tree.
400
300
  */
401
- declare function assertValidId(id: string, kind?: IdKind): void;
402
- /** A validated (kind, id, version) triple — the registry's unit of identity. */
403
- interface CapabilityId {
404
- readonly kind: IdKind;
405
- readonly id: string;
406
- readonly version: string;
301
+ type PackageInvariantCode = 'dangling-relationship' | 'missing-content-type'
302
+ /** A part occupies a name OPC reserves for package infrastructure. */
303
+ | 'reserved-part-name'
304
+ /** Two parts whose names differ only by case, which OPC treats as one part. */
305
+ | 'duplicate-part-name'
306
+ /** A part name the OPC screens refuse; `writeZip` would throw on save. */
307
+ | 'unsafe-part-name';
308
+ /** One package invariant violation, located by part name and relationship id. */
309
+ interface PackageInvariantIssue {
310
+ readonly code: PackageInvariantCode;
311
+ /** The part the issue is about: the missing target, or the part with no type. */
312
+ readonly partName: string;
313
+ /** For a dangling relationship, the owner that points at nothing. */
314
+ readonly ownerPart?: string;
407
315
  }
408
-
409
- /** A parsed semantic version. Only the three numeric components — no pre-release or build. */
410
- interface SemVer {
411
- readonly major: number;
412
- readonly minor: number;
413
- readonly patch: number;
316
+ /** Whether a package satisfies its cross-part invariants, listing every violation otherwise. */
317
+ type PackageInvariantResult = {
318
+ readonly ok: true;
319
+ } | {
320
+ readonly ok: false;
321
+ readonly issues: readonly PackageInvariantIssue[];
322
+ };
323
+ /** Relationship records owned by one part, in authored order. */
324
+ declare function relationshipsOf(pkg: OoxmlPackage, ownerPart: string): readonly RelationshipRecord[];
325
+ /** The content type that resolves for a part name, or null when nothing declares one. */
326
+ declare function resolveContentTypeOf(pkg: OoxmlPackage, partName: string): string | null;
327
+ /** The `.rels` part that owns a part's relationships, by OPC convention. */
328
+ declare function relsPartNameFor(partName: string): string;
329
+ /**
330
+ * Declare a content type for a part, by upserting an `<Override>` in the content-types tree.
331
+ *
332
+ * A no-op when the part already resolves to the same type, so repeating a write does not append
333
+ * a duplicate entry. Resolving to a DIFFERENT type replaces the existing Override in place.
334
+ * `forceOverride` writes an explicit Override even when a Default already matches.
335
+ */
336
+ declare function withContentTypeOverride(pkg: OoxmlPackage, partName: string, contentType: string, options?: {
337
+ readonly forceOverride?: boolean;
338
+ }): OoxmlPackage;
339
+ /** What {@link withoutPart} answers: `ok: false` leaves the package exactly as it was. */
340
+ interface WithoutPartResult {
341
+ readonly pkg: OoxmlPackage;
342
+ readonly ok: boolean;
414
343
  }
344
+ /** Add or replace one relationship on a part, returning a new package. */
345
+ declare function withRelationship(pkg: OoxmlPackage, ownerPart: string, type: string, rawTarget: string): {
346
+ readonly pkg: OoxmlPackage;
347
+ readonly relationshipId: string;
348
+ readonly ok: boolean;
349
+ };
415
350
  /**
416
- * Parse a semantic version, rejecting anything the registry's rules do not need.
351
+ * Add a part that does not exist yet, with the content-type override it needs to be openable.
417
352
  *
418
- * Deliberately narrow: an unsupported range form is refused rather than accepted, so a malformed
419
- * range can never masquerade as "compatible".
353
+ * Deliberately does NOT create a relationship: a part is reachable because something points at
354
+ * it, and which part points at it is the caller's decision. Creating one here would guess.
420
355
  */
421
- declare function parseSemVer(input: string): SemVer;
422
- /** Order two versions: negative, zero or positive, by major then minor then patch. */
423
- declare function compareSemVer(a: SemVer, b: SemVer): -1 | 0 | 1;
356
+ declare function withNewPart(pkg: OoxmlPackage, partName: string, root: OoxmlElement, contentType: string): OoxmlPackage;
424
357
  /**
425
- * Whether `version` satisfies `range`. Supported range grammar:
426
- * - `*` any version
427
- * - `1.2.3` exact
428
- * - `^1.2.3` caret: same major, and >= the floor (major 0 pins the minor)
429
- * - `>=1.2.3 <2.0.0` a single lower (inclusive) + upper (exclusive) bound pair
430
- * Any other shape throws — an unparseable range is a registration error, not a pass.
358
+ * The two invariants a package must satisfy before it is published.
359
+ *
360
+ * Both describe the half-written state that splitting a multi-part write across transactions
361
+ * produces, and both make a package Word refuses to open:
362
+ *
363
+ * - a relationship pointing at a part nobody created;
364
+ * - a part with no content type, which is unopenable even though the XML is well formed.
365
+ *
366
+ * Checked at the commit boundary rather than inside each primitive, for the same reason part
367
+ * validation moved there: a transaction is allowed to pass through an inconsistent intermediate
368
+ * as long as nothing can observe it.
431
369
  */
432
- declare function satisfies(version: string, range: string): boolean;
370
+ declare function validatePackageInvariants(pkg: OoxmlPackage): PackageInvariantResult;
433
371
 
434
372
  /**
435
- * Why registry resolution failed.
373
+ * Whether a string is a valid XML NCName in the strict ASCII profile — a name with no colon.
436
374
  *
437
- * Every code names a declaration conflict a bundle author can fix — a missing dependency, an
438
- * unsatisfied version range, a duplicate contribution with no replacement policy.
375
+ * This is the rule for names the engine itself writes or accepts from a caller. Names read
376
+ * from a document use {@link isXmlNCName}, which admits every XML 1.0 name.
439
377
  */
440
- type RegistryErrorCode = 'invalid-id' | 'invalid-version' | 'duplicate-extension' | 'id-collision' | 'replacement-target-missing' | 'unauthorized-replacement' | 'replacement-version-mismatch' | 'ambiguous-replacement' | 'missing-dependency' | 'dependency-cycle' | 'conflict' | 'missing-port';
378
+ declare function isValidNCName(name: string): boolean;
379
+ /** A QName is an optional `prefix:` (both NCNames) — never attacker-derived. */
380
+ declare function isValidQName(name: string): boolean;
441
381
  /**
442
- * A resolution failure naming every responsible party.
382
+ * Validate a qualified name, throwing when it is malformed.
443
383
  *
444
- * Thrown rather than returned: an unresolvable registry is a build-time composition mistake, and
445
- * an engine running with a half-resolved registry would fail later in ways that do not point back
446
- * to the bundle that caused it.
384
+ * Guards the serializer: an invalid QName written into XML produces a file Word cannot open, so
385
+ * it fails here rather than at save.
447
386
  */
448
- declare class RegistryError extends Error {
449
- readonly code: RegistryErrorCode;
450
- /** Stable identities responsible for the failure (extensions, ids). */
451
- readonly responsible: readonly string[];
452
- constructor(code: RegistryErrorCode, message: string,
453
- /** Stable identities responsible for the failure (extensions, ids). */
454
- responsible?: readonly string[]);
455
- }
456
- /** How a base contribution permits replacement by other bundles. */
457
- type ReplacementPolicy = {
458
- readonly kind: 'none';
459
- } | {
460
- readonly kind: 'single';
461
- } | {
462
- readonly kind: 'priority';
463
- };
464
- /** One thing a bundle contributes: a command, a query, a schema, a port, keyed by `(kind, id)`. */
465
- interface Contribution {
466
- readonly kind: Exclude<IdKind, 'extension' | 'origin' | 'result'>;
467
- readonly id: string;
468
- readonly version: string;
469
- /** If set, this contribution replaces an existing base contribution. */
470
- readonly replaces?: {
471
- readonly targetId: string;
472
- readonly targetRange: string;
473
- readonly priority?: number;
474
- };
475
- /** Policy this contribution exposes to would-be replacers (default `none`). */
476
- readonly replaceable?: ReplacementPolicy;
477
- readonly payload?: unknown;
478
- }
387
+ declare function assertValidQName(name: string): void;
479
388
  /**
480
- * A unit of engine functionality: its identity, version, dependencies, conflicts, required ports,
481
- * and contributions.
482
- *
483
- * The registry's whole input. Everything a bundle needs and everything it offers is DECLARED, so
484
- * resolution can be deterministic and order-independent.
389
+ * Controlled namespace-prefix allocation: deterministic, collision-free prefixes
390
+ * for namespace URIs. A known URI always yields the same registered prefix; new
391
+ * URIs get a generated `ns{n}` prefix, never one derived from file content.
485
392
  */
486
- interface FeatureBundle {
487
- readonly id: string;
488
- readonly version: string;
489
- readonly dependencies?: readonly string[];
490
- readonly conflicts?: readonly string[];
491
- readonly requiredPorts?: readonly string[];
492
- readonly contributions: readonly Contribution[];
493
- }
494
- /** The resolved result: every contribution selected, indexed by `(kind, id)`. */
495
- interface ResolvedRegistry {
496
- readonly extensions: ReadonlyMap<string, FeatureBundle>;
497
- readonly contributions: ReadonlyMap<string, Contribution>;
498
- get(kind: Contribution['kind'], id: string): Contribution | undefined;
499
- }
500
- /** How resolution treats optional bundles and replacement policies. */
501
- interface ResolveOptions {
502
- /** Runtime port ids available in this environment (design D9 / task 0.3). */
503
- readonly availablePorts?: readonly string[];
393
+ declare class PrefixAllocator {
394
+ private readonly byUri;
395
+ private readonly usedPrefixes;
396
+ private counter;
397
+ constructor(known?: Readonly<Record<string, string>>);
398
+ prefixFor(namespaceUri: string): string;
399
+ /** The declared bindings, for emitting xmlns declarations. */
400
+ bindings(): {
401
+ prefix: string;
402
+ uri: string;
403
+ }[];
504
404
  }
405
+
505
406
  /**
506
- * Resolve a set of bundles into one registry, or throw.
507
- *
508
- * Deterministic and registration-order independent: selection is by `(kind, id)` plus version,
509
- * and ties break only on declared policy. Array order never decides anything.
407
+ * A hyperlink target projected for a RUNTIME sink, or the reason it was withheld.
510
408
  *
511
- * @throws RegistryError naming every bundle responsible for the failure.
409
+ * The authored target stays authored — the record layer keeps it verbatim and escapes it into
410
+ * owned OOXML, which is not a runtime sink. Only this allowlist-sanitized projection reaches DOM,
411
+ * CSS, navigation or fetch, so `javascript:`, `data:` and `vbscript:` never leave the boundary.
512
412
  */
513
- declare function resolve(bundles: readonly FeatureBundle[], options?: ResolveOptions): ResolvedRegistry;
514
-
515
- /**
516
- * Typed-origin domains (design D5 / ADR-S5). `mutation.*` are the canonical
517
- * write origins; `projection` and `awareness` MUST NOT enter history, audit,
518
- * snapshots, or replication.
519
- */
520
- declare const ORIGIN_IDS: {
521
- readonly mutationHuman: "dev.docx-editor.core.origin.mutation.human";
522
- readonly mutationAgent: "dev.docx-editor.core.origin.mutation.agent";
523
- readonly mutationRemote: "dev.docx-editor.core.origin.mutation.remote";
524
- readonly mutationUndo: "dev.docx-editor.core.origin.mutation.undo";
525
- readonly mutationRedo: "dev.docx-editor.core.origin.mutation.redo";
526
- readonly mutationMigration: "dev.docx-editor.core.origin.mutation.migration";
527
- readonly mutationRepair: "dev.docx-editor.core.origin.mutation.repair";
528
- readonly mutationServer: "dev.docx-editor.core.origin.mutation.server";
529
- readonly projection: "dev.docx-editor.core.origin.projection";
530
- readonly awareness: "dev.docx-editor.core.origin.awareness";
413
+ type HrefProjection = {
414
+ readonly ok: true;
415
+ readonly href: string;
416
+ } | {
417
+ readonly ok: false;
418
+ readonly inert: true;
531
419
  };
532
- /** Canonical writes carry a mutation origin; these are the undoable-eligibility inputs. */
533
- declare const CANONICAL_MUTATION_ORIGINS: readonly string[];
534
- /** Origins that never enter authored state / history / audit / snapshot / replication. */
535
- declare const NON_CANONICAL_ORIGINS: readonly string[];
536
420
  /**
537
- * Result taxonomy (design D8 / task 7.8). A transport/protocol failure that
538
- * prevents a valid envelope is a typed exception, not a member here.
421
+ * Project a file-derived URL for a DOM/navigation sink. Strips embedded
422
+ * tab/LF/CR (used to smuggle `java\nscript:`), allows relative URLs and the
423
+ * scheme allowlist, and renders everything else inert. Never fetches.
539
424
  */
540
- declare const RESULT_IDS: {
541
- readonly applied: "dev.docx-editor.core.result.applied";
542
- readonly validation: "dev.docx-editor.core.result.validation";
543
- readonly conflict: "dev.docx-editor.core.result.conflict";
544
- readonly resource: "dev.docx-editor.core.result.resource";
545
- readonly authorization: "dev.docx-editor.core.result.authorization";
546
- readonly aborted: "dev.docx-editor.core.result.aborted";
547
- };
548
- /** Runtime ports (extensions-and-runtime-ports spec; design D9). */
549
- declare const RUNTIME_PORT_IDS: {
550
- readonly fonts: "dev.docx-editor.core.port.fonts";
551
- readonly shaping: "dev.docx-editor.core.port.shaping";
552
- readonly images: "dev.docx-editor.core.port.images";
553
- readonly clock: "dev.docx-editor.core.port.clock";
554
- readonly identity: "dev.docx-editor.core.port.identity";
555
- readonly persistence: "dev.docx-editor.core.port.persistence";
556
- readonly transport: "dev.docx-editor.core.port.transport";
557
- readonly scheduling: "dev.docx-editor.core.port.scheduling";
558
- readonly audit: "dev.docx-editor.core.port.audit";
559
- readonly authorization: "dev.docx-editor.core.port.authorization";
560
- readonly resourceAccounting: "dev.docx-editor.core.port.resource-accounting";
561
- readonly cancellation: "dev.docx-editor.core.port.cancellation";
562
- readonly externalResourceConsent: "dev.docx-editor.core.port.external-resource-consent";
563
- };
564
- /** Layout dependency keys (design D6 / task 8.2). */
565
- declare const DEPENDENCY_KEY_IDS: {
566
- readonly style: "dev.docx-editor.core.dep.style";
567
- readonly numbering: "dev.docx-editor.core.dep.numbering";
568
- readonly section: "dev.docx-editor.core.dep.section";
569
- readonly story: "dev.docx-editor.core.dep.story";
570
- readonly font: "dev.docx-editor.core.dep.font";
571
- readonly image: "dev.docx-editor.core.dep.image";
572
- readonly table: "dev.docx-editor.core.dep.table";
573
- readonly field: "dev.docx-editor.core.dep.field";
574
- readonly note: "dev.docx-editor.core.dep.note";
575
- readonly headerFooter: "dev.docx-editor.core.dep.header-footer";
576
- readonly annotation: "dev.docx-editor.core.dep.annotation";
577
- };
578
- /** Every frozen id as a flat list, for the immutability / uniqueness gate. */
579
- declare const ALL_FROZEN_IDS: readonly string[];
580
-
425
+ declare function sanitizeHref(raw: string): HrefProjection;
426
+ /** XML-escape a value for validated serialization back into owned OOXML. */
427
+ declare function escapeXml(value: string): string;
581
428
  /**
582
- * A counter's limit was reached. Carries the label, the limit, and what was attempted.
429
+ * CSS string-escape a file-derived value (e.g. an `@font-face` family name or an
430
+ * inline style value). Emits `\<hex> ` escapes for quotes, backslash, and
431
+ * controls so the value cannot break out of its CSS string.
432
+ */
433
+ declare function escapeCssString(value: string): string;
434
+ /** Whether a file-derived CSS fragment contains a `url()` or `@import` (must be rejected). */
435
+ declare function containsCssFetch(value: string): boolean;
436
+ /**
437
+ * Content that must never execute or auto-resolve: OLE objects, macros, DDE and `INCLUDE*` field
438
+ * instructions.
583
439
  *
584
- * Thrown at the N → N+1 boundary, so the increment that would have crossed the limit never
585
- * happens rather than being detected afterwards.
440
+ * Rendered INERT by default rather than stripped — removing it would be a lossless-preservation
441
+ * failure, so it is carried and never acted on.
586
442
  */
587
- declare class LimitExceededError extends Error {
588
- readonly label: string;
589
- readonly limit: number;
590
- readonly attempted: number;
591
- constructor(label: string, limit: number, attempted: number);
443
+ declare const INERT_EXECUTABLE_KINDS: readonly ['field-dde', 'field-include', 'macro', 'activex', 'ole', 'embedded-object', 'executable-relationship'];
444
+ /** One of {@link INERT_EXECUTABLE_KINDS}. */
445
+ /** One of {@link INERT_EXECUTABLE_KINDS} — content carried but never executed. */
446
+ type InertExecutableKind = (typeof INERT_EXECUTABLE_KINDS)[number];
447
+ /** Whether a content kind is one this engine refuses to execute or auto-resolve. */
448
+ declare function isInertExecutable(kind: string): boolean;
449
+ /** Whether a field instruction's leading keyword is safe to evaluate. */
450
+ declare function isEvaluableField(instruction: string): boolean;
451
+ /** One item a scrub pass considers: its kind, and where in the package it sits. */
452
+ interface ContentItem {
453
+ readonly id: string;
454
+ readonly kind: string;
592
455
  }
593
456
  /**
594
- * Overflow-safe counting against a fixed limit.
457
+ * What an explicit scrub removed.
595
458
  *
596
- * Never silently wraps: it rejects the increment that would cross its limit AND any arithmetic
597
- * that would exceed `Number.MAX_SAFE_INTEGER`. That second guard is the point — a file-supplied
598
- * count must never be trusted into an allocation, and a wrapped counter reads as small.
459
+ * A scrub DECLARES ITSELF non-lossless: removing executable content changes the file, which is a
460
+ * choice a caller makes deliberately rather than a default the engine applies.
599
461
  */
600
- declare class BoundedCounter {
601
- readonly label: string;
602
- readonly limit: number;
603
- private value;
604
- constructor(label: string, limit: number);
605
- get current(): number;
606
- /** Remaining headroom before the limit. */
607
- get remaining(): number;
608
- /**
609
- * Add `n` (default 1). Throws LimitExceededError if the result would exceed the
610
- * limit (so `limit` itself is reachable but `limit + 1` is not) or overflow the
611
- * safe-integer range. On rejection the counter is unchanged.
612
- */
613
- add(n?: number): number;
614
- /** Whether adding `n` would be accepted, without mutating. */
615
- canAdd(n?: number): boolean;
616
- release(n: number): void;
462
+ interface ScrubResult {
463
+ readonly kept: readonly ContentItem[];
464
+ readonly removed: readonly ContentItem[];
465
+ /** A scrub that removes anything is non-lossless by definition. */
466
+ readonly nonLossless: boolean;
617
467
  }
468
+ /** Explicit scrub export: remove inert executable classes, report removals. */
469
+ declare function scrubExport(items: readonly ContentItem[]): ScrubResult;
618
470
 
619
- /** A budget was misused: over-carved, over-reserved, or disposed with children outstanding. */
620
- declare class BudgetError extends Error {
621
- constructor(message: string);
622
- }
471
+ /** True for an `m:oMathPara` display equation. */
472
+ declare function isOmmlDisplay(node: OoxmlNode): node is OoxmlGenericElementNode;
473
+ /** True for a paragraph-level equation atom: `m:oMath` or `m:oMathPara`. */
474
+ declare function isOmmlEquationAtom(node: OoxmlNode): node is OoxmlGenericElementNode;
475
+ /** The `m:oMath` equations of a display, or the equation itself for an inline `m:oMath`. */
476
+ declare function equationsOfAtom(node: OoxmlNode): readonly OoxmlGenericElementNode[];
623
477
  /**
624
- * Capacity claimed BEFORE it is allocated.
625
- *
626
- * Reserve-then-allocate rather than allocate-then-check: discovering the overrun after the
627
- * allocation has already happened defeats the point of having a budget.
478
+ * Project a display equation as one layout atom. A display with one equation keeps that
479
+ * equation's projection, so the painted atom names the editable `m:oMath`. Several equations
480
+ * share one row, separated by an em space.
628
481
  */
629
- interface Reservation {
630
- readonly amount: number;
631
- readonly released: boolean;
632
- release(): void;
633
- }
482
+ declare function projectOmmlDisplay(node: OoxmlNode): OmmlEquationProjection | null;
634
483
  /**
635
- * One node in the hierarchical resource budget tree.
636
- *
637
- * An operation owns a root budget; parsers, extensions, workers, layout, transport and output
638
- * carve children from it, so no subsystem can consume more than the operation as a whole allows.
639
- *
640
- * `dispose()` REFUSES while children or reservations are outstanding, then runs registered
641
- * cleanups LIFO — spill files, worker termination — even if one throws. A leaked child budget is a
642
- * leaked worker, so the refusal is the diagnostic.
484
+ * The physical justification of a paragraph whose only visible content is display math.
485
+ * `m:oMathParaPr/m:jc` sets it; the default `centerGroup` centers the display. Returns null
486
+ * when the paragraph also holds text or other content, which keeps the paragraph `w:jc`.
643
487
  */
644
- declare class Budget {
645
- readonly label: string;
646
- readonly capacity: number;
647
- private readonly used;
648
- private readonly children;
649
- private activeReservations;
650
- private readonly cleanups;
651
- private disposed;
652
- private carveAmount;
653
- private parent?;
654
- constructor(label: string, capacity: number);
655
- get inUse(): number;
656
- get available(): number;
657
- get isDisposed(): boolean;
658
- /** Reserve `amount` from this budget. Throws if it would exceed capacity. */
659
- reserve(amount: number): Reservation;
660
- /** Carve a child budget of `capacity` out of this budget's headroom. */
661
- child(label: string, capacity: number): Budget;
662
- /** Register cleanup for a spill file, worker, or queue tied to this budget. */
663
- onRelease(cleanup: () => void): void;
664
- /**
665
- * Release this budget. Refuses while any child budget or reservation is
666
- * outstanding (children must finish first). Runs cleanups LIFO, returns the
667
- * carve-out to the parent, and marks disposed. Cleanup errors are collected and
668
- * rethrown after every cleanup has run.
669
- */
670
- dispose(): void;
671
- private assertLive;
672
- }
488
+ declare function displayMathAlignment(paragraph: {
489
+ readonly children: readonly OoxmlNode[];
490
+ }): 'left' | 'center' | 'right' | null;
491
+ /** Project a paragraph-level equation atom: inline `m:oMath` or display `m:oMathPara`. */
492
+ declare function projectOmmlAtom(node: OoxmlNode): OmmlEquationProjection | null;
493
+
494
+ /** UTF-16 placeholder for a page break in paragraph text projections. */
495
+ declare const PAGE_BREAK_CHAR = "\f";
496
+ /** What a `w:br` breaks. `other` covers values this engine does not model, kept losslessly. */
497
+ type HardBreakKind = 'line' | 'page' | 'column' | 'other';
498
+ /** Read the semantic break kind from a typed `w:br` node. */
499
+ declare function hardBreakKind(node: OoxmlHardBreakNode): HardBreakKind;
500
+ /** Whether a node is a `w:br` with `w:type="page"`. */
501
+ declare function isPageBreakNode(node: OoxmlNode): node is OoxmlHardBreakNode;
502
+ /** Text projection for a `w:br` node — one UTF-16 code unit per break. */
503
+ declare function hardBreakText(node: OoxmlHardBreakNode): string;
504
+ /** Attributes for a newly authored `w:br`. */
505
+ declare function hardBreakAttributes(kind: 'line' | 'page'): OoxmlHardBreakNode['attributes'];
673
506
 
507
+ /** Parsed TOC instruction. Unknown switches are ignored for generation but left on the wire. */
508
+ interface TocInstruction {
509
+ readonly keyword: 'TOC';
510
+ /** Include hyperlinks (`\\h`). */
511
+ readonly hyperlink: boolean;
512
+ /** Omit page numbers (`\\n`). */
513
+ readonly omitPageNumbers: boolean;
514
+ /** Inclusive 1-based outline levels from `\\o "n-m"`. Defaults 1–9. */
515
+ readonly outlineStart: number;
516
+ readonly outlineEnd: number;
517
+ readonly raw: string;
518
+ }
519
+ /** Longest TOC field instruction read. Instructions come from a file; the parse is bounded. */
520
+ declare const TOC_MAX_INSTRUCTION_CHARS = 256;
521
+ /** Most entries one generated table of contents may hold. */
522
+ declare const TOC_MAX_ENTRIES = 512;
523
+ /** Most bookmarks minted during one TOC refresh. */
524
+ declare const TOC_MAX_BOOKMARKS_PER_REFRESH = 512;
525
+ /** Deepest nested field instruction followed. Caps recursion on file-supplied structure. */
526
+ declare const TOC_MAX_FIELD_NESTING = 4;
674
527
  /**
675
- * Which side of the point of no return an operation is on.
528
+ * Most layout passes a TOC refresh runs before settling.
676
529
  *
677
- * Canonical publication is that point. Cancelling BEFORE it rolls the whole operation back;
678
- * cancelling after it leaves the commit standing and cancels only derived work — layout, export,
679
- * caches.
530
+ * Page numbers change the TOC's own height, which changes page numbers — bounded so a
531
+ * non-converging document stops rather than looping.
680
532
  */
681
- type CancellationPhase = 'pre-publication' | 'post-publication';
682
- /** Thrown from a `checkpoint()` when the operation has been cancelled. */
683
- declare class CancellationError extends Error {
684
- /** True when the commit is already published and only derived work is cancelled. */
685
- readonly derivedOnly: boolean;
686
- constructor(
687
- /** True when the commit is already published and only derived work is cancelled. */
688
- derivedOnly: boolean, reason?: string);
689
- }
533
+ declare const TOC_MAX_PAGE_PASSES = 3;
690
534
  /**
691
- * The read side of cancellation, handed to cooperative work.
535
+ * Parse a TOC field instruction string.
692
536
  *
693
- * Cooperative rather than pre-emptive: long work calls `checkpoint()` at declared intervals, which
694
- * is what lets an operation unwind promptly without the engine having to interrupt it mid-mutation.
537
+ * Returns null when the leading keyword is not TOC, the string is over-long, or the
538
+ * outline range is hostile. Does not evaluate or fetch anything.
695
539
  */
696
- interface CancellationToken {
697
- readonly isCancelled: boolean;
698
- readonly phase: CancellationPhase;
699
- /** True only when cancelled AND the commit is already published. */
700
- readonly derivedOnly: boolean;
701
- /** Throws CancellationError if cancelled; call at declared checkpoint intervals. */
702
- checkpoint(): void;
540
+ declare function parseTocInstruction(raw: string): TocInstruction | null;
541
+
542
+ /** A table of contents found in a document, whether wrapped in an SDT or a bare field. */
543
+ interface DetectedToc {
544
+ /** Enclosing control id when it identifies one TOC, otherwise the begin fldChar id. */
545
+ readonly id: string;
546
+ readonly beginNodeId: string;
547
+ readonly beginParagraphId: string;
548
+ readonly endParagraphId: string;
549
+ readonly resultParagraphIds: readonly string[];
550
+ /** Direct parent whose paragraph children delimit the cached result. */
551
+ readonly containerId: string;
552
+ readonly contentControlId?: string;
553
+ readonly instruction: TocInstruction;
554
+ }
555
+ /** Discover refreshable body TOCs without evaluating any field instruction. */
556
+ declare function detectBodyTocs(part: OoxmlPart): readonly DetectedToc[];
557
+ /** Locate the table of contents containing a position, or null. */
558
+ declare function findDetectedToc(tocs: readonly DetectedToc[], tocId: string): DetectedToc | null;
559
+
560
+ /** One heading symbol: its `w:font` and `w:char`, as the file wrote them. */
561
+ interface TocSymbol {
562
+ readonly font: string | null;
563
+ readonly char: string;
703
564
  }
565
+
566
+ declare const TWIPS: unique symbol;
567
+ declare const POINTS: unique symbol;
704
568
  /**
705
- * The write side of cancellation, and the owner of the phase.
569
+ * A length in twentieths of a point — OOXML's `ST_TwipsMeasure` / `ST_SignedTwipsMeasure`.
706
570
  *
707
- * Whoever starts an operation holds this; everything it calls gets only the token.
571
+ * The brand is intersection-typed onto `number`, so a `Twips` value still decays to `number`
572
+ * wherever arithmetic consumes it; only the reverse direction — passing a raw number where
573
+ * `Twips` is declared — is refused.
574
+ *
575
+ * @public
708
576
  */
709
- declare class CancellationController {
710
- private _cancelled;
711
- private _phase;
712
- private _reason?;
713
- cancel(reason?: string): void;
714
- /** Mark canonical publication — the point of no return. */
715
- markPublished(): void;
716
- get isCancelled(): boolean;
717
- get phase(): CancellationPhase;
718
- get isPublished(): boolean;
719
- /** Cancelled after publication -> full rollback is no longer possible. */
720
- get derivedOnly(): boolean;
721
- get token(): CancellationToken;
722
- }
723
-
724
- /** Injectable time source — the engine never calls Date.now directly (determinism). */
725
- interface ClockPort {
726
- now(): number;
727
- }
728
- /** Stable id minting for sessions, commits, and allocator seeds. */
729
- interface IdentityPort {
730
- newId(): string;
731
- }
732
- /** Cooperative scheduling of deferred work. */
733
- interface SchedulingPort {
734
- schedule(task: () => void): void;
735
- }
736
- /** Redacted observability sink (raw text never enters here — design D5). */
737
- interface AuditPort {
738
- record(entry: {
739
- readonly kind: string;
740
- readonly at: number;
741
- readonly meta?: Record<string, unknown>;
742
- }): void;
743
- }
744
- /** Read/write/export authorization decisions. */
745
- interface AuthorizationPort {
746
- authorize(action: string, subject?: string): boolean;
747
- }
748
- /** Explicit consent gate for any remote/external resource (no zero-click fetch). */
749
- interface ExternalResourceConsentPort {
750
- requestConsent(target: string): boolean;
751
- }
752
- /** Cancellation source for the current operation. */
753
- interface CancellationPort {
754
- readonly token: CancellationToken;
755
- }
756
- /** Where documents are stored and retrieved. Opaque marker until its milestone. */
757
- interface PersistencePort {
758
- readonly kind: 'persistence';
759
- }
760
- /** How the engine talks to a remote peer. Opaque marker until its milestone. */
761
- interface TransportPort {
762
- readonly kind: 'transport';
763
- }
764
- /** Where font bytes come from. Opaque marker until its milestone. */
765
- interface FontPort {
766
- readonly kind: 'font';
767
- }
768
- /** Which shaping backend measures text. Opaque marker until its milestone. */
769
- interface ShapingPort {
770
- readonly kind: 'shaping';
771
- }
772
- /** How image bytes are decoded. Opaque marker until its milestone. */
773
- interface ImagePort {
774
- readonly kind: 'image';
775
- }
776
- /** Where resource consumption is reported. Opaque marker until its milestone. */
777
- interface ResourceAccountingPort {
778
- readonly kind: 'resource-accounting';
779
- }
577
+ type Twips = number & {
578
+ readonly [TWIPS]: true;
579
+ };
780
580
  /**
781
- * A required port the runtime did not provide.
581
+ * A length in typographic points, the unit layout and paint compute in.
782
582
  *
783
- * Thrown rather than falling back: silently reaching for a browser global when a worker or server
784
- * adapter did not supply a port is exactly the coupling ports exist to prevent.
583
+ * @public
785
584
  */
786
- declare class PortResolutionError extends Error {
787
- readonly portId: string;
788
- constructor(portId: string);
789
- }
585
+ type Points = number & {
586
+ readonly [POINTS]: true;
587
+ };
790
588
  /**
791
- * The environment-dependent services an engine instance may reach.
589
+ * Twentieths of a point per point.
792
590
  *
793
- * Everything outside pure computation — the clock, identity minting, scheduling, fonts, images —
794
- * is reached only through here, which is what lets browser, worker and server adapters supply
795
- * only what their runtime actually offers.
591
+ * @public
796
592
  */
797
- declare class PortRegistry {
798
- private readonly ports;
799
- provide(portId: string, port: unknown): this;
800
- has(portId: string): boolean;
801
- /** Resolve a port by id or throw. */
802
- resolve<T>(portId: string): T;
803
- /** Assert every id in `portIds` is present; returns the missing ones (empty if all present). */
804
- missing(portIds: readonly string[]): string[];
805
- /** The provided port ids (for bridging to registry.resolve availablePorts). */
806
- availablePorts(): string[];
807
- clock(): ClockPort;
808
- identity(): IdentityPort;
809
- }
810
- /** Deterministic clock: starts at `start` and advances by `step` each call. */
811
- declare class DeterministicClock implements ClockPort {
812
- private readonly step;
813
- private t;
814
- constructor(start?: number, step?: number);
815
- now(): number;
816
- }
817
- /** Sequential identity for tests and deterministic fixtures. */
818
- declare class SequentialIdentity implements IdentityPort {
819
- private readonly prefix;
820
- private n;
821
- constructor(prefix?: string);
822
- newId(): string;
823
- }
824
-
825
- /** What one operation is started with. Only `ports` is required. */
826
- interface OperationInit {
827
- readonly ports: PortRegistry;
828
- readonly limits?: Partial<ResourceLimits>;
829
- readonly config?: Readonly<Record<string, unknown>>;
830
- /** Root budget capacity in abstract units (default: the byte decompression limit). */
831
- readonly capacity?: number;
832
- /** Operation identity (from IdentityPort in production); defaulted for tests. */
833
- readonly id?: string;
834
- }
593
+ declare const TWIPS_PER_POINT = 20;
835
594
  /**
836
- * The frozen environment of one operation: its limits, config, ports, root budget and
837
- * cancellation controller.
595
+ * Assert that a number is a twips measurement.
838
596
  *
839
- * IMMUTABLE for the operation's lifetime, which is what lets cache reuse and replica agreement
840
- * key on it. A new operation always gets a fresh snapshot rather than observing a mutated one.
597
+ * A compile-time cast, not a validator: bounds, integrality and finiteness stay at the parse
598
+ * boundary that produced the number, exactly where they are enforced today. The cast is the
599
+ * caller's claim about the UNIT, nothing more.
600
+ *
601
+ * @public
841
602
  */
842
- interface OperationContext {
843
- readonly id: string;
844
- readonly limits: ResourceLimits;
845
- readonly config: Readonly<Record<string, unknown>>;
846
- readonly ports: PortRegistry;
847
- readonly budget: Budget;
848
- readonly cancellation: CancellationController;
849
- }
603
+ declare const twips: (value: number) => Twips;
850
604
  /**
851
- * Begin an operation, capturing its immutable environment snapshot.
605
+ * Assert that a number is a points measurement. A compile-time cast; see {@link twips}.
852
606
  *
853
- * Resolves and freezes limits and configuration, carves the root budget, and creates the
854
- * cancellation controller — everything downstream work needs, fixed for the operation's duration.
607
+ * @public
855
608
  */
856
- declare function beginOperation(init: OperationInit): OperationContext;
857
- /** Release the operation's root budget (requires every child/reservation released). */
858
- declare function endOperation(ctx: OperationContext): void;
859
-
860
- /** What a limit counts. Typed so a byte cap and a depth cap cannot be compared by accident. */
861
- type LimitUnit = 'bytes' | 'count' | 'depth' | 'ratio' | 'passes';
609
+ declare const points: (value: number) => Points;
862
610
  /**
863
- * Where a limit is enforced.
611
+ * The one twips-to-points conversion. Exact division; twips are the finer unit.
864
612
  *
865
- * Declared per limit so enforcement happens at the boundary that can still refuse cheaply — a zip
866
- * cap checked during layout has already let the bomb decompress.
613
+ * @public
867
614
  */
868
- type EnforcementPhase = 'package-read' | 'xml-parse' | 'layout' | 'output';
869
- /** One limit's unit and enforcement phase — the metadata that makes limits testable uniformly. */
870
- interface LimitSpec {
871
- readonly unit: LimitUnit;
872
- readonly phase: EnforcementPhase;
873
- }
874
- /** Unit + enforcement phase for every resource limit. */
875
- declare const LIMIT_SPECS: Readonly<Record<keyof ResourceLimits, LimitSpec>>;
876
- /** Every limit name, for iterating the specs and asserting each has a unit and phase. */
877
- declare const LIMIT_KEYS: (keyof ResourceLimits)[];
878
- /** A phase-scoped overflow-safe counter for one limit. */
879
- declare function makeLimitCounter(limits: ResourceLimits, key: keyof ResourceLimits): BoundedCounter;
615
+ declare const twipsToPoints: (value: Twips) => Points;
880
616
  /**
881
- * Deterministic memory substitute. Tracks current and peak "allocated" units
882
- * against a hard byte ceiling; `allocate` fails closed (LimitExceededError) past
883
- * the limit. Used in place of process RSS so memory-limit tests are reproducible
884
- * and cancellation/cleanup can be asserted without a real allocator.
617
+ * The one points-to-twips conversion.
618
+ *
619
+ * Rounds to the nearest twip: every OOXML twips measurement is integral, and emitting a
620
+ * fractional twip would write a value no consumer of the file can represent.
621
+ *
622
+ * @public
885
623
  */
886
- declare class DeterministicMemoryMeter {
887
- private readonly counter;
888
- private current;
889
- private peak;
890
- constructor(limitBytes: number);
891
- allocate(bytes: number): void;
892
- free(bytes: number): void;
893
- get currentBytes(): number;
894
- get peakBytes(): number;
895
- /** Release everything (cancellation/cleanup path). */
896
- reset(): void;
897
- }
898
- /** Assert the finite-default / hard-ceiling invariant holds for every limit. */
899
- declare function assertLimitInvariants(): void;
900
-
901
- /** Any JSON value. The domain canonicalization and stable hashing operate over. */
902
- type Json = null | boolean | number | string | Json[] | {
903
- [k: string]: Json;
904
- };
624
+ declare const pointsToTwips: (value: Points) => Twips;
905
625
  /**
906
- * Produce a canonical string for `value`, dropping any object key whose name is
907
- * in `ephemera` at any depth. Numbers are emitted losslessly; -0 normalizes to 0;
908
- * non-finite numbers are rejected (they must never enter a comparator input).
626
+ * Read a twips attribute (`ST_TwipsMeasure`, `ST_SignedTwipsMeasure`, or a `dxa` table width)
627
+ * as a whole, signed number of twips, or `null` when the value is not a measurement.
628
+ *
629
+ * The schema allows an integer or a universal measure, but files also carry decimal twips
630
+ * (`4743.74`, `708.0`, `707.9999999999998`). The accepted forms read as follows:
631
+ *
632
+ * - A decimal truncates toward zero: `1443.74` is 1443 and `-720.6` is -720. A leading `+`,
633
+ * leading zeros, a bare fraction (`.5`) and a trailing point (`1440.`) are accepted.
634
+ * - A universal measure (`mm`, `cm`, `in`, `pt`, `pc`, `pi`) converts exactly and then
635
+ * truncates: `1.27cm` is 720 and `0.333in` is 479. Its sign is ignored, so `-0.5in` is 720.
636
+ * - Whitespace, exponents, hexadecimal, uppercase units, and an integer part longer than nine
637
+ * digits are not measurements.
638
+ *
639
+ * The result is NOT bounded. Callers apply their own sign rule and range clamp, because each
640
+ * attribute has a different valid range and a different fallback.
641
+ *
642
+ * @internal
909
643
  */
910
- declare function canonicalize(value: unknown, ephemera?: ReadonlySet<string>): string;
911
- /** 64-bit FNV-1a over the canonical form, returned as a 16-char hex string. */
912
- declare function stableHash(value: unknown, ephemera?: ReadonlySet<string>): string;
644
+ declare function readTwipsMeasure(raw: string | undefined): number | null;
645
+
646
+ /** Outline heading shape consumed by TOC planning (mirrors DocumentOutlineEntry). */
647
+ interface TocOutlineHeading {
648
+ readonly text: string;
649
+ readonly level: number;
650
+ readonly blockId: string;
651
+ }
913
652
 
653
+ /** Left-indent step between TOC levels, in twips (matches `scripts/demo-doc/toc-block.xml`). */
654
+ declare const TOC_LEVEL_INDENT_TWIPS: Twips;
655
+ /** Bounded left-indent twips for a TOC entry level (0-based heading depth). */
656
+ declare function tocLeftIndentTwips(level: number): Twips;
657
+ /** One planned TOC entry: its level, its text, and the heading it points at. */
658
+ interface TocEntryPlan {
659
+ readonly level: number;
660
+ readonly text: string;
661
+ readonly headingParagraphId: string;
662
+ readonly bookmarkName: string;
663
+ readonly pageNumberText: string;
664
+ /** The heading's symbols, one per {@link TOC_SYMBOL_MARK} in `text`, in order. */
665
+ readonly symbols?: readonly TocSymbol[];
666
+ }
667
+ /** Build one TOC entry paragraph node. */
668
+ declare function buildTocEntryParagraph(mint: () => string, entry: TocEntryPlan, instruction: TocInstruction, paragraphPropertiesTemplate?: OoxmlNode): OoxmlNode;
669
+ /** Build an SDT-wrapped complex TOC field with an already planned cached result. */
670
+ declare function buildTocContentControl(mint: () => string, entries: readonly TocEntryPlan[], instruction: TocInstruction, alias: string): OoxmlNode;
914
671
  /**
915
- * How one artifact class is compared.
672
+ * Word flattens manual line/tab breaks from a heading into spaces in its TOC cache.
673
+ * Carrying them verbatim makes a short title wrap even when the row has ample room, and the
674
+ * same normalization is what lets a cached row be matched back to the heading it came from.
675
+ */
676
+ declare function tocEntryText(text: string): string;
677
+ /**
678
+ * Plan TOC entries from the outline and existing bookmarks.
916
679
  *
917
- * Frozen per artifact: nothing here invents a tolerance for an artifact the spec requires to
918
- * match exactly.
680
+ * `actorId` is explicit because this planner runs BEFORE the store transaction, so the
681
+ * ambient transaction actor is not bound. Callers that already have the collaboration
682
+ * identity pass it here. `resolveAllocationActor` still honours a
683
+ * `runWithTransactionActor` wrap when the caller prefers that seam.
919
684
  */
920
- type ComparatorMode = 'canonical-exact' | 'exact' | 'tolerance' | 'sync-optimization-only';
921
- /** One artifact class's comparison mode and its declared ephemera — fields excluded from equality. */
922
- interface ComparatorDescriptor {
923
- readonly id: string;
924
- readonly mode: ComparatorMode;
925
- /** Object keys excluded from canonical-exact comparison (declared ephemera). */
926
- readonly ephemera: readonly string[];
927
- readonly note: string;
928
- }
929
- /** The frozen artifact comparator set. */
930
- declare const COMPARATORS: {
931
- readonly authoredState: {
932
- readonly id: "dev.docx-editor.core.comparator.authored-state";
933
- readonly mode: 'canonical-exact';
934
- readonly ephemera: readonly ["revision", "provenance", "producedAt", "commitId"];
935
- readonly note: 'canonical normalized authored records; ephemera excluded';
936
- };
937
- readonly anchor: {
938
- readonly id: "dev.docx-editor.core.comparator.anchor";
939
- readonly mode: 'exact';
940
- readonly ephemera: readonly [];
941
- readonly note: 'internal anchor identity/affinity compares exactly';
942
- };
943
- readonly yjsStateVector: {
944
- readonly id: "dev.docx-editor.core.comparator.yjs-state-vector";
945
- readonly mode: 'sync-optimization-only';
946
- readonly ephemera: readonly [];
947
- readonly note: 'exchange optimization only; never proves update or delete-set coverage';
948
- };
949
- readonly shapedRun: {
950
- readonly id: "dev.docx-editor.core.comparator.shaped-run";
951
- readonly mode: 'exact';
952
- readonly ephemera: readonly [];
953
- readonly note: 'glyph ids, clusters, and fixed-point advances compare exactly';
954
- };
955
- readonly paginationFingerprint: {
956
- readonly id: "dev.docx-editor.core.comparator.pagination-fingerprint";
957
- readonly mode: 'exact';
958
- readonly ephemera: readonly [];
959
- readonly note: 'page/column boundaries, break causes, fixed-point geometry compare exactly';
960
- };
961
- readonly semanticTree: {
962
- readonly id: "dev.docx-editor.core.comparator.semantic-tree";
963
- readonly mode: 'exact';
964
- readonly ephemera: readonly [];
965
- readonly note: 'reading order, roles, headings, alt text compare exactly';
966
- };
967
- readonly hitTest: {
968
- readonly id: "dev.docx-editor.core.comparator.hit-test";
969
- readonly mode: 'exact';
970
- readonly ephemera: readonly [];
971
- readonly note: 'resolved hit target and cluster affinity compare exactly';
972
- };
973
- readonly pdfSemantics: {
974
- readonly id: "dev.docx-editor.core.comparator.pdf-semantics";
975
- readonly mode: 'canonical-exact';
976
- readonly ephemera: readonly ["objectNumber", "producer", "creationDate", "modDate", "subsetTag"];
977
- readonly note: 'canonical semantic PDF objects; container ephemera excluded';
978
- };
979
- readonly rasterCheckpoint: {
980
- readonly id: "dev.docx-editor.core.comparator.raster-checkpoint";
981
- readonly mode: 'tolerance';
982
- readonly ephemera: readonly [];
983
- readonly note: 'documented unavoidable raster comparison; explicit tolerance only';
984
- };
985
- readonly benchmarkEvidence: {
986
- readonly id: "dev.docx-editor.core.comparator.benchmark-evidence";
987
- readonly mode: 'sync-optimization-only';
988
- readonly ephemera: readonly [];
989
- readonly note: 'diagnostic evidence, not an equivalence basis';
990
- };
685
+ declare function planTocEntries(part: OoxmlPart, outline: readonly TocOutlineHeading[], instruction: TocInstruction, pageNumberByParagraphId: ReadonlyMap<string, string>, excludeParagraphIds: ReadonlySet<string>, actorId?: string): {
686
+ readonly entries: readonly TocEntryPlan[];
687
+ readonly bookmarksToCreate: readonly {
688
+ paragraphId: string;
689
+ name: string;
690
+ }[];
991
691
  };
992
- /** Which frozen comparator to use. */
993
- type ComparatorName = keyof typeof COMPARATORS;
994
- /** Whether two artifacts matched, and where they diverged when they did not. */
995
- interface ComparisonResult {
996
- readonly equal: boolean;
997
- /** Canonical forms when unequal (diagnostic). */
998
- readonly left?: string;
999
- readonly right?: string;
1000
- }
692
+ /** Create bookmarkStart/End pair nodes for insertion at the start of a paragraph. */
693
+ declare function bookmarkPairNodes(mint: () => string, name: string, id: string): {
694
+ readonly start: OoxmlNode;
695
+ readonly end: OoxmlNode;
696
+ };
697
+
1001
698
  /**
1002
- * Compare two artifacts under a named comparator. `canonical-exact` and `exact`
1003
- * compare canonical forms (exact drops no ephemera). `tolerance` requires an
1004
- * epsilon and compares finite numbers structurally. `sync-optimization-only`
1005
- * throws — such artifacts are never an equivalence basis.
699
+ * The heading each cached result row stands for, aligned with `toc.resultParagraphIds`.
700
+ *
701
+ * `null` for a row that names no heading this document still has — a stale row, or the
702
+ * chrome/blank paragraphs a cached result can carry. Callers leave those alone rather than
703
+ * writing another row's number into them.
1006
704
  */
1007
- declare function compareArtifacts(name: ComparatorName, left: unknown, right: unknown, opts?: {
1008
- epsilon?: number;
1009
- }): ComparisonResult;
1010
- /** Fingerprint an artifact under a named comparator's canonicalization policy. */
1011
- declare function fingerprint(name: ComparatorName, value: unknown): string;
705
+ declare function resolveTocRowHeadings(part: OoxmlPart, toc: DetectedToc, outline: readonly TocOutlineHeading[], excludeParagraphIds: ReadonlySet<string>): readonly (string | null)[];
1012
706
 
1013
- /** Whether a recorded conformance step was expected to commit or be refused. */
1014
- type FixtureOutcome = 'applied' | 'aborted' | 'validation' | 'conflict' | 'resource' | 'authorization';
1015
- /** The change one step produced, summarized to what a fixture can compare across runtimes. */
1016
- interface ModelChangeSummary {
1017
- readonly fromRevision: number;
1018
- readonly toRevision: number;
1019
- readonly origin: string;
1020
- readonly dirty: readonly string[];
1021
- readonly dependencyKeys: readonly string[];
1022
- }
1023
- /** Where anchors sat after a step — how a fixture proves positions survived an edit. */
1024
- interface AnchorSnapshot {
1025
- readonly anchorId: string;
1026
- readonly story: string;
1027
- readonly block: string;
1028
- readonly affinity: 'before' | 'after';
1029
- }
1030
- /** What one step must produce: its outcome, its change summary, and its authored-state hash. */
1031
- interface FixtureExpectation {
1032
- readonly outcome: FixtureOutcome;
1033
- /** Present iff outcome === 'applied'; MUST be > baseRevision. */
1034
- readonly committedRevision?: number;
1035
- readonly modelChange?: ModelChangeSummary;
1036
- /** 16-hex authored-state fingerprint (comparator 0.4). */
1037
- readonly authoredStateHash?: string;
1038
- readonly outputHash?: string;
1039
- readonly anchors?: readonly AnchorSnapshot[];
707
+ /** One paragraph in the index: its node id, its story, and its position. */
708
+ interface ParagraphIndexEntry {
709
+ /** Canonical tree node id — the stable identity operations address. */
710
+ readonly nodeId: string;
711
+ /** Position among the story's paragraphs, in document order. */
712
+ readonly ordinal: number;
713
+ /** Concatenated text content, with tabs and breaks mapped as the model reads them. */
714
+ readonly text: string;
715
+ /** Node ids of the paragraph's runs, in order. */
716
+ readonly runIds: readonly string[];
1040
717
  }
1041
- /** One recorded operation and what it was expected to do. */
1042
- interface FixtureStep {
1043
- readonly baseRevision: number;
1044
- readonly origin: string;
1045
- /** Opaque DocOp payloads (schema owned by section 4). */
1046
- readonly ops: readonly unknown[];
1047
- readonly expect: FixtureExpectation;
718
+ /** One story root — body, a header/footer variant, or a note part. */
719
+ interface StoryIndexEntry {
720
+ /** The part the story lives in. */
721
+ readonly partName: string;
722
+ /** The `w:body` (or story root) node id. */
723
+ readonly rootId: string;
724
+ readonly paragraphs: readonly ParagraphIndexEntry[];
1048
725
  }
1049
- /** Opaque encoded backend bytes (snapshot or replication update). */
1050
- interface EncodedEnvelope {
1051
- readonly kind: 'snapshot' | 'update';
1052
- readonly protocolVersion: number;
1053
- readonly schemaVersion: number;
1054
- readonly documentId: string;
1055
- readonly byteLength: number;
1056
- /** Hex-encoded opaque bytes; length MUST equal byteLength. */
1057
- readonly bytesHex: string;
726
+ /** One style definition, indexed by the id content references it under. */
727
+ interface StyleIndexEntry {
728
+ readonly styleId: string;
729
+ readonly type: string;
730
+ readonly nodeId: string;
731
+ readonly name: string | null;
732
+ readonly basedOn: string | null;
733
+ /** Whether the part marks this the default style for its type (`w:default="1"`). */
734
+ readonly isDefault: boolean;
1058
735
  }
1059
- /** Which implementation recorded a fixture — local store, Yjs, or a binding. */
1060
- type FixtureSource = {
1061
- readonly kind: 'create';
1062
- } | {
1063
- readonly kind: 'docx';
1064
- readonly sha256: string;
1065
- readonly bytesRef: string;
1066
- };
1067
736
  /**
1068
- * The frozen conformance container: revisions, origins, operations, changes, snapshots and
1069
- * hashes.
737
+ * The derived lookups over a part: paragraphs, stories and styles by id.
1070
738
  *
1071
- * The CONTAINER is what is frozen — field names, origin membership, revision monotonicity, hash
1072
- * format. The op and change payloads travel opaquely, so their schemas can evolve without
1073
- * invalidating every recorded fixture.
739
+ * Diff-patched on commit rather than rebuilt — rebuilding every index per keystroke is what made
740
+ * typing scale with document length.
1074
741
  */
1075
- interface ConformanceFixture {
1076
- readonly formatVersion: 1;
1077
- readonly documentId: string;
1078
- readonly source: FixtureSource;
1079
- readonly steps: readonly FixtureStep[];
1080
- readonly snapshots?: readonly EncodedEnvelope[];
1081
- readonly updates?: readonly EncodedEnvelope[];
1082
- }
1083
- /** Whether a fixture is well-formed, listing every structural violation. */
1084
- interface ValidationResult {
1085
- readonly valid: boolean;
1086
- readonly errors: readonly string[];
1087
- }
1088
- /** Structurally validate a fixture against the frozen format rules. */
1089
- declare function validateFixture(fixture: ConformanceFixture): ValidationResult;
1090
-
1091
- /** The outcome a store reports for one replayed step. */
1092
- interface ReplayOutcome {
1093
- readonly outcome: FixtureOutcome;
1094
- readonly committedRevision?: number;
1095
- /** Canonical authored-state value AFTER the step (hashed via comparator 0.4). */
1096
- readonly authoredState?: unknown;
1097
- }
1098
- /** The interface a conformance runtime implements so one fixture can drive every backend. */
1099
- interface ReplayStore {
1100
- /** Initialize from the fixture source; return the initial revision (0 for create). */
1101
- init(fixture: ConformanceFixture): number;
1102
- /** Apply one step and report what happened. */
1103
- applyStep(step: FixtureStep): ReplayOutcome;
1104
- }
1105
- /** What replaying a fixture produced: per-step outcomes and where they diverged. */
1106
- interface ReplayReport {
1107
- readonly ok: boolean;
1108
- readonly mismatches: readonly string[];
742
+ interface OoxmlIndexes {
743
+ /** The tree revision these projections were derived from. */
744
+ readonly revision: number;
745
+ /** Body story first, then any other story parts, keyed by part name. */
746
+ readonly stories: ReadonlyMap<string, StoryIndexEntry>;
747
+ /** Every paragraph across every story, keyed by node id. */
748
+ readonly paragraphs: ReadonlyMap<string, ParagraphIndexEntry>;
749
+ readonly relationships: ReadonlyMap<string, readonly RelationshipRecord[]>;
750
+ readonly styles: ReadonlyMap<string, StyleIndexEntry>;
1109
751
  }
752
+ /** Style definitions, read out of the generic `w:styles` tree. */
753
+ declare function indexStyles(part: OoxmlPart | undefined): Map<string, StyleIndexEntry>;
754
+ /** The package's style definitions part, if it has one. */
755
+ declare function stylesPartOf(pkg: OoxmlPackage): OoxmlPart | undefined;
1110
756
  /**
1111
- * Replay a fixture against a store and check every step's outcome, committed
1112
- * revision, and authored-state fingerprint against the fixture's expectations.
1113
- */
1114
- declare function replayFixture(fixture: ConformanceFixture, store: ReplayStore): ReplayReport;
1115
- /** Hash a store's authored state, so two runtimes replaying one fixture can be compared. */
1116
- declare function hashAuthored(authoredState: unknown): string;
1117
-
1118
- /**
1119
- * Keys that must never be assigned from file data.
757
+ * Derive every index from one canonical package revision.
1120
758
  *
1121
- * XML attribute names become object keys, and a document controls those names — assigning
1122
- * `__proto__` into an ordinary object is the prototype-pollution hazard this engine audits for.
759
+ * Pure: the same package and revision always produce the same index, which is what makes
760
+ * "rebuild rather than mutate" a safe invalidation strategy.
1123
761
  */
1124
- declare const DANGEROUS_KEYS: readonly string[];
1125
- /** A file-derived key that would pollute a prototype. Refused, never sanitized-and-accepted. */
1126
- declare class DangerousKeyError extends Error {
1127
- readonly key: string;
762
+ declare function deriveOoxmlIndexes(pkg: OoxmlPackage, revision: number): OoxmlIndexes;
763
+
764
+ /** One paragraph's meaning, independent of how it was spelled in XML. */
765
+ interface ParagraphDigest {
766
+ /** Ordinal identity within its story. Node ids are NOT used: a reopened package
767
+ * legitimately re-derives them, and requiring them to match would test the id scheme
768
+ * rather than the content. */
769
+ readonly ordinal: number;
770
+ /**
771
+ * Where the paragraph SITS: the element path from the story root, so a paragraph that
772
+ * moves out of the table cell it was written in is a difference rather than a paragraph
773
+ * with the same ordinal and the same text.
774
+ */
1128
775
  readonly path: string;
1129
- constructor(key: string, path: string);
776
+ /**
777
+ * `w14:paraId`, uppercase-normalized (matching is case-insensitive), or null. This is
778
+ * MANAGED identity — the agent contract anchors on it and comment threading references
779
+ * it — so a serializer silently dropping it must be a digest difference. Other paragraph
780
+ * attributes (`w:rsidR` …) stay deliberately undigested: they are revision noise.
781
+ */
782
+ readonly paraId: string | null;
783
+ /** Text content, including tabs and hard breaks as their characters. */
784
+ readonly text: string;
785
+ /** Accepted paragraph properties, as sorted tokens including nested children. */
786
+ readonly paragraphProperties: readonly string[];
787
+ /** Per-run accepted properties, in run order. */
788
+ readonly runProperties: readonly (readonly string[])[];
789
+ /** Fingerprints of every generic (unknown) subtree, in document order. */
790
+ readonly genericStructure: readonly string[];
1130
791
  }
1131
- /** Whether a key is one of {@link DANGEROUS_KEYS}. */
1132
- declare function isDangerousKey(key: string): boolean;
1133
- /** A fresh null-prototype record — the only object shape parser intermediates use. */
1134
- declare function nullRecord<T = unknown>(): Record<string, T>;
1135
- /**
1136
- * Recursively convert `value` into null-prototype records, rejecting any
1137
- * dangerous object key. Arrays and primitives pass through (arrays rebuilt so no
1138
- * inherited prototype pollution survives). Throws DangerousKeyError on the first
1139
- * unsafe key, naming its path. Cyclic inputs are rejected.
1140
- */
1141
- declare function toSafeRecord(value: unknown, path?: string): unknown;
1142
-
1143
- /** Locate `[Content_Types].xml` bytes regardless of zip key spelling. */
1144
- declare function contentTypesPartBytes(pkg: OoxmlPackage): {
1145
- readonly storageKey: string;
1146
- readonly bytes: Uint8Array;
1147
- } | null;
1148
- /**
1149
- * What a package-level invariant walk found wrong.
1150
- *
1151
- * Package invariants are cross-PART: a relationship pointing at a part that does not exist, or a
1152
- * part no content-type record covers. Neither is visible from inside a single part's tree.
1153
- */
1154
- type PackageInvariantCode = 'dangling-relationship' | 'missing-content-type'
1155
- /** A part occupies a name OPC reserves for package infrastructure. */
1156
- | 'reserved-part-name'
1157
- /** Two parts whose names differ only by case, which OPC treats as one part. */
1158
- | 'duplicate-part-name'
1159
- /** A part name the OPC screens refuse; `writeZip` would throw on save. */
1160
- | 'unsafe-part-name';
1161
- /** One package invariant violation, located by part name and relationship id. */
1162
- interface PackageInvariantIssue {
1163
- readonly code: PackageInvariantCode;
1164
- /** The part the issue is about: the missing target, or the part with no type. */
792
+ /** One story reduced to its semantic content, ignoring everything a normalized re-emit changes. */
793
+ interface StoryDigest {
1165
794
  readonly partName: string;
1166
- /** For a dangling relationship, the owner that points at nothing. */
1167
- readonly ownerPart?: string;
795
+ readonly paragraphs: readonly ParagraphDigest[];
796
+ /**
797
+ * Every block-level element of the part OUTSIDE a paragraph, in document order, as
798
+ * `path name(attributes)` — the tables, rows, cells, sections, content controls and
799
+ * their property children, each at the position that says what contains it.
800
+ *
801
+ * A paragraph's own internals are not here (they are its `ParagraphDigest`), which keeps
802
+ * this list proportional to a document's STRUCTURE rather than its text.
803
+ */
804
+ readonly structure: readonly string[];
1168
805
  }
1169
- /** Whether a package satisfies its cross-part invariants, listing every violation otherwise. */
1170
- type PackageInvariantResult = {
1171
- readonly ok: true;
1172
- } | {
1173
- readonly ok: false;
1174
- readonly issues: readonly PackageInvariantIssue[];
1175
- };
1176
- /** Relationship records owned by one part, in authored order. */
1177
- declare function relationshipsOf(pkg: OoxmlPackage, ownerPart: string): readonly RelationshipRecord[];
1178
- /** The content type that resolves for a part name, or null when nothing declares one. */
1179
- declare function resolveContentTypeOf(pkg: OoxmlPackage, partName: string): string | null;
1180
- /** The `.rels` part that owns a part's relationships, by OPC convention. */
1181
- declare function relsPartNameFor(partName: string): string;
1182
806
  /**
1183
- * Declare a content type for a part, by upserting an `<Override>` in the content-types tree.
807
+ * The whole document's semantic content — one of the D9 losslessness oracles.
1184
808
  *
1185
- * A no-op when the part already resolves to the same type, so repeating a write does not append
1186
- * a duplicate entry. Resolving to a DIFFERENT type replaces the existing Override in place.
1187
- * `forceOverride` writes an explicit Override even when a Default already matches.
809
+ * What a save/reopen round-trip is compared on. Byte identity applies only to non-XML parts;
810
+ * modelled parts re-emit normalized, so equality is asserted HERE rather than on bytes.
1188
811
  */
1189
- declare function withContentTypeOverride(pkg: OoxmlPackage, partName: string, contentType: string, options?: {
1190
- readonly forceOverride?: boolean;
1191
- }): OoxmlPackage;
1192
- /** What {@link withoutPart} answers: `ok: false` leaves the package exactly as it was. */
1193
- interface WithoutPartResult {
1194
- readonly pkg: OoxmlPackage;
1195
- readonly ok: boolean;
812
+ interface SemanticDigest {
813
+ readonly stories: readonly StoryDigest[];
1196
814
  }
1197
- /** Add or replace one relationship on a part, returning a new package. */
1198
- declare function withRelationship(pkg: OoxmlPackage, ownerPart: string, type: string, rawTarget: string): {
1199
- readonly pkg: OoxmlPackage;
1200
- readonly relationshipId: string;
1201
- readonly ok: boolean;
815
+ /** Where two digests diverge — the diagnostic when a round-trip loses something. */
816
+ type DigestDifference = {
817
+ readonly path: string;
818
+ readonly before: string;
819
+ readonly after: string;
1202
820
  };
821
+ /** Digest one part: its paragraphs, and the structure that holds them. */
822
+ declare function digestPart(part: OoxmlPart): StoryDigest | null;
823
+ /** Digest every part, in the given order. */
824
+ declare function semanticDigest(parts: Iterable<OoxmlPart>): SemanticDigest;
1203
825
  /**
1204
- * Add a part that does not exist yet, with the content-type override it needs to be openable.
1205
- *
1206
- * Deliberately does NOT create a relationship: a part is reachable because something points at
1207
- * it, and which part points at it is the caller's decision. Creating one here would guess.
1208
- */
1209
- declare function withNewPart(pkg: OoxmlPackage, partName: string, root: OoxmlElement, contentType: string): OoxmlPackage;
1210
- /**
1211
- * The two invariants a package must satisfy before it is published.
1212
- *
1213
- * Both describe the half-written state that splitting a multi-part write across transactions
1214
- * produces, and both make a package Word refuses to open:
1215
- *
1216
- * - a relationship pointing at a part nobody created;
1217
- * - a part with no content type, which is unopenable even though the XML is well formed.
826
+ * Every way two digests differ, as readable paths.
1218
827
  *
1219
- * Checked at the commit boundary rather than inside each primitive, for the same reason part
1220
- * validation moved there: a transaction is allowed to pass through an inconsistent intermediate
1221
- * as long as nothing can observe it.
828
+ * Returns the differences rather than a boolean because "the round trip lost something" is
829
+ * useless without saying what — the failure this oracle exists to catch is a silent drop,
830
+ * and a bare `false` reproduces the silence.
1222
831
  */
1223
- declare function validatePackageInvariants(pkg: OoxmlPackage): PackageInvariantResult;
832
+ declare function diffSemanticDigests(before: SemanticDigest, after: SemanticDigest): DigestDifference[];
1224
833
 
834
+ /** Valid per MS-DOCX: 8 hex digits, non-zero, below 0x80000000. */
835
+ declare function isValidParaId(value: string): boolean;
836
+ /** The authored `w14:paraId` value of an element, verbatim, or null. */
837
+ declare function paraIdOf(node: OoxmlNode): string | null;
838
+ /** FNV-1a over UTF-16 code units — the deterministic mint every id derivation shares. */
839
+ declare function fnv1a32(value: string): number;
1225
840
  /**
1226
- * Whether a string is a valid XML NCName in the strict ASCII profile — a name with no colon.
1227
- *
1228
- * This is the rule for names the engine itself writes or accepts from a caller. Names read
1229
- * from a document use {@link isXmlNCName}, which admits every XML 1.0 name.
841
+ * Deterministic 8-hex mint in (0x00000000, 0x80000000), collision-free against
842
+ * `used` (uppercase hex). Same seed + same used-set → same value, which is what
843
+ * keeps `splitParagraphMany` byte-identical to its equivalent single splits and
844
+ * a reopened save identical to the session that produced it.
1230
845
  */
1231
- declare function isValidNCName(name: string): boolean;
1232
- /** A QName is an optional `prefix:` (both NCNames) — never attacker-derived. */
1233
- declare function isValidQName(name: string): boolean;
846
+ declare function mintParaId(seed: string, used: ReadonlySet<string>): string;
847
+ /** Every valid `w14:paraId` in the tree, uppercased. Memoized per root object. */
848
+ declare function usedParaIds(root: OoxmlElement): ReadonlySet<string>;
1234
849
  /**
1235
- * Validate a qualified name, throwing when it is malformed.
850
+ * The non-empty prefix the part ROOT binds to the w14 namespace, or null.
1236
851
  *
1237
- * Guards the serializer: an invalid QName written into XML produces a file Word cannot open, so
1238
- * it fails here rather than at save.
852
+ * Minted attributes require an in-scope binding (the invariant validator reports
853
+ * `invalid-qname` otherwise, and the serializer would allocate an `nsN` alias).
854
+ * Only the root binding counts: a binding authored on some descendant does not
855
+ * cover paragraphs elsewhere in the tree.
1239
856
  */
1240
- declare function assertValidQName(name: string): void;
857
+ declare function w14RootPrefix(root: OoxmlElement): string | null;
858
+ /** The minted `[w14:paraId, w14:textId]` pair. `textId` mirrors `paraId`: it has no uniqueness requirement, no consumer reads it, and one allocator is simpler than two — but Word writes both, so we write both. */
859
+ declare function mintedParagraphIdentityAttributes(prefix: string, value: string): readonly OoxmlAttribute[];
1241
860
  /**
1242
- * Controlled namespace-prefix allocation: deterministic, collision-free prefixes
1243
- * for namespace URIs. A known URI always yields the same registered prefix; new
1244
- * URIs get a generated `ns{n}` prefix, never one derived from file content.
861
+ * Load-time paragraph-identity normalization for a session's main part.
862
+ *
863
+ * Keeps every valid, first-seen paraId verbatim; mints (deterministically, seeded
864
+ * by the paragraph's structural node id) for paragraphs whose id is missing,
865
+ * malformed, zero, out of range, or a duplicate. Adds the root `xmlns` binding
866
+ * the minted attributes need. Returns the INPUT PART REFERENCE when there is
867
+ * nothing to do — a document Word saved yesterday re-serializes byte-identical.
868
+ *
869
+ * Attribute-only rebuilds move no child, so every node keeps its structural-path
870
+ * id; the copy respreads only the ancestors of changed paragraphs.
871
+ *
872
+ * Fail-open: if the rebuilt part does not validate (a bug, or a pathology the
873
+ * prefix choice could not defuse), the original part is returned — a document
874
+ * must never become unopenable over an identity enhancement.
1245
875
  */
1246
- declare class PrefixAllocator {
1247
- private readonly byUri;
1248
- private readonly usedPrefixes;
1249
- private counter;
1250
- constructor(known?: Readonly<Record<string, string>>);
1251
- prefixFor(namespaceUri: string): string;
1252
- /** The declared bindings, for emitting xmlns declarations. */
1253
- bindings(): {
1254
- prefix: string;
1255
- uri: string;
1256
- }[];
1257
- }
876
+ declare function normalizeParagraphIdentity(part: OoxmlPart): OoxmlPart;
1258
877
 
878
+ /** One `w:docPart` of the glossary, with the blocks its body holds. */
879
+ interface BuildingBlock {
880
+ /** `w:docPartPr/w:name`, the identity a control's placeholder and a pick refer to. */
881
+ readonly name: string;
882
+ /** `w:category/w:gallery`, an `ST_DocPartGallery` value such as `docParts`. */
883
+ readonly gallery: string;
884
+ /** `w:category/w:name`; `General` when the block declares none. */
885
+ readonly category: string;
886
+ /** The `w:docPartBody` children: paragraphs, tables and block controls, in order. */
887
+ readonly blocks: readonly OoxmlNode[];
888
+ }
889
+ /** The gallery and category a `w:docPartList` control lists. */
890
+ interface BuildingBlockGalleryFilter {
891
+ readonly gallery: string;
892
+ readonly category: string | null;
893
+ }
894
+ /** The glossary part, through the main part's relationship or the conventional name. */
895
+ declare function glossaryPartOf(pkg: OoxmlPackage): OoxmlPart | null;
896
+ /** Every named building block of the glossary, in authored order. Empty without a glossary. */
897
+ declare function buildingBlocksOf(pkg: OoxmlPackage): readonly BuildingBlock[];
898
+ /** The gallery a `w:docPartList` control lists, or null for any other control. */
899
+ declare function buildingBlockGalleryOf(control: OoxmlNode): BuildingBlockGalleryFilter | null;
1259
900
  /**
1260
- * A hyperlink target projected for a RUNTIME sink, or the reason it was withheld.
1261
- *
1262
- * The authored target stays authored — the record layer keeps it verbatim and escapes it into
1263
- * owned OOXML, which is not a runtime sink. Only this allowlist-sanitized projection reaches DOM,
1264
- * CSS, navigation or fetch, so `javascript:`, `data:` and `vbscript:` never leave the boundary.
1265
- */
1266
- type HrefProjection = {
1267
- readonly ok: true;
1268
- readonly href: string;
1269
- } | {
1270
- readonly ok: false;
1271
- readonly inert: true;
1272
- };
1273
- /**
1274
- * Project a file-derived URL for a DOM/navigation sink. Strips embedded
1275
- * tab/LF/CR (used to smuggle `java\nscript:`), allows relative URLs and the
1276
- * scheme allowlist, and renders everything else inert. Never fetches.
901
+ * The blocks a gallery control offers: same gallery, and the control's category when it names
902
+ * one. Sorted by category, then name, as Word groups its list.
1277
903
  */
1278
- declare function sanitizeHref(raw: string): HrefProjection;
1279
- /** XML-escape a value for validated serialization back into owned OOXML. */
1280
- declare function escapeXml(value: string): string;
904
+ declare function buildingBlocksForControl(pkg: OoxmlPackage, control: OoxmlNode): readonly BuildingBlock[];
905
+
1281
906
  /**
1282
- * CSS string-escape a file-derived value (e.g. an `@font-face` family name or an
1283
- * inline style value). Emits `\<hex> ` escapes for quotes, backslash, and
1284
- * controls so the value cannot break out of its CSS string.
907
+ * Which story a comment deletion or resolution may read markers from.
908
+ *
909
+ * `w:id` is not unique across stories: a header and the body can both hold comment 1.
1285
910
  */
1286
- declare function escapeCssString(value: string): string;
1287
- /** Whether a file-derived CSS fragment contains a `url()` or `@import` (must be rejected). */
1288
- declare function containsCssFetch(value: string): boolean;
911
+ interface CommentDeletionOwner {
912
+ /** Canonical name of the part holding the story's markers. */
913
+ readonly storyPartName: string;
914
+ /**
915
+ * When the story is one note inside a shared notes part, that note's `w:id`.
916
+ * Absent means the whole part is the story (body, header, footer).
917
+ */
918
+ readonly noteId?: number;
919
+ }
920
+
1289
921
  /**
1290
- * Content that must never execute or auto-resolve: OLE objects, macros, DDE and `INCLUDE*` field
1291
- * instructions.
922
+ * Delete a comment thread: that story's markers, and metadata no other story still names.
1292
923
  *
1293
- * Rendered INERT by default rather than stripped — removing it would be a lossless-preservation
1294
- * failure, so it is carried and never acted on.
924
+ * `owner` names the story whose markers may be stripped. Omitted, it is the main document
925
+ * body — never every XML part. A header or note that reused the same `w:id` is a different
926
+ * remark; pass its part (and `noteId` when the story is one note) to delete that one.
927
+ *
928
+ * Returns the package unchanged when the id names no comment, and null when a removal was
929
+ * refused — a caller inside a transaction rolls back rather than committing a package whose
930
+ * comment is half gone.
1295
931
  */
1296
- declare const INERT_EXECUTABLE_KINDS: readonly ['field-dde', 'field-include', 'macro', 'activex', 'ole', 'embedded-object', 'executable-relationship'];
1297
- /** One of {@link INERT_EXECUTABLE_KINDS}. */
1298
- /** One of {@link INERT_EXECUTABLE_KINDS} — content carried but never executed. */
1299
- type InertExecutableKind = (typeof INERT_EXECUTABLE_KINDS)[number];
1300
- /** Whether a content kind is one this engine refuses to execute or auto-resolve. */
1301
- declare function isInertExecutable(kind: string): boolean;
1302
- /** Whether a field instruction's leading keyword is safe to evaluate. */
1303
- declare function isEvaluableField(instruction: string): boolean;
1304
- /** One item a scrub pass considers: its kind, and where in the package it sits. */
1305
- interface ContentItem {
1306
- readonly id: string;
1307
- readonly kind: string;
1308
- }
932
+ declare function deleteCommentThread(pkg: OoxmlPackage, commentId: string, owner?: CommentDeletionOwner): OoxmlPackage | null;
1309
933
  /**
1310
- * What an explicit scrub removed.
934
+ * Delete every comment the edit between `before` and `after` emptied in `owner`'s story.
1311
935
  *
1312
- * A scrub DECLARES ITSELF non-lossless: removing executable content changes the file, which is a
1313
- * choice a caller makes deliberately rather than a default the engine applies.
936
+ * `owner` omitted is the main document body, matching {@link deleteCommentThread}.
937
+ *
938
+ * THE TEST, exactly, and per story. A comment dies when the words it covered in that story are
939
+ * gone and nothing in that story still places it. A neighbour that reused the same `w:id` is
940
+ * judged under its own owner. Notes that vanished (reference cascade) are reaped as their own
941
+ * stories so a unique id still loses its `comments.xml` body. Remaining-marker overflow
942
+ * preserves comments/commentEx/commentId metadata rather than deleting records the scan could
943
+ * not prove unused. Null is reserved for a removal that actually failed.
1314
944
  */
1315
- interface ScrubResult {
1316
- readonly kept: readonly ContentItem[];
1317
- readonly removed: readonly ContentItem[];
1318
- /** A scrub that removes anything is non-lossless by definition. */
1319
- readonly nonLossless: boolean;
945
+ declare function cascadeEmptiedComments(before: OoxmlPackage, after: OoxmlPackage, owner?: CommentDeletionOwner): OoxmlPackage | null;
946
+
947
+ /** Presentation settings the document itself states. Absence is the answer, never an error. */
948
+ interface DocumentViewSettings {
949
+ /**
950
+ * `w:doNotShadeFormData` (§17.15.1.49) — do NOT shade legacy form fields.
951
+ *
952
+ * Word draws a grey block behind every `w:ffData` field so a reader can find the blanks in a
953
+ * form. It is on by DEFAULT, and this element is how a document turns it off, so the absent
954
+ * case means shading. Reading the name as "shade form data" inverts it and blanks the shading
955
+ * on exactly the documents that asked for it loudest.
956
+ *
957
+ * Never printed, by Word or by us: it marks where to type, and a printed form has no blanks
958
+ * to find.
959
+ */
960
+ readonly doNotShadeFormData: boolean;
1320
961
  }
1321
- /** Explicit scrub export: remove inert executable classes, report removals. */
1322
- declare function scrubExport(items: readonly ContentItem[]): ScrubResult;
962
+ /** The defaults a document with no `settings.xml` gets: everything Word would shade, shaded. */
963
+ declare const DEFAULT_VIEW_SETTINGS: DocumentViewSettings;
964
+ /** Read the view settings from a `settings.xml` root, or the defaults when it has none. */
965
+ declare function readViewSettings(settingsRoot: OoxmlNode | null | undefined): DocumentViewSettings;
1323
966
 
1324
- /** True for an `m:oMathPara` display equation. */
1325
- declare function isOmmlDisplay(node: OoxmlNode): node is OoxmlGenericElementNode;
1326
- /** True for a paragraph-level equation atom: `m:oMath` or `m:oMathPara`. */
1327
- declare function isOmmlEquationAtom(node: OoxmlNode): node is OoxmlGenericElementNode;
1328
- /** The `m:oMath` equations of a display, or the equation itself for an inline `m:oMath`. */
1329
- declare function equationsOfAtom(node: OoxmlNode): readonly OoxmlGenericElementNode[];
967
+ /** How deep transparent block wrappers may nest before the walk stops descending. */
968
+ declare const MAX_STORY_SDT_NESTING = 32;
969
+ /** Which kind of story a root is. Layout walks all four the same way. */
970
+ type OoxmlStoryKind = 'body' | 'header' | 'footer' | 'note';
971
+ /** One story root and the blocks under it, with transparent block wrappers already flattened. */
972
+ interface OoxmlStoryRoot {
973
+ readonly kind: OoxmlStoryKind;
974
+ /** The `w:body` / `w:hdr` / `w:ftr` / `w:footnote` element that holds the blocks. */
975
+ readonly root: OoxmlNode;
976
+ }
1330
977
  /**
1331
- * Project a display equation as one layout atom. A display with one equation keeps that
1332
- * equation's projection, so the painted atom names the editable `m:oMath`. Several equations
1333
- * share one row, separated by an em space.
978
+ * Every story root in a part, in document order.
979
+ *
980
+ * Does not descend INTO a story: a story's blocks are the walk below, and a story root never
981
+ * contains another story root.
1334
982
  */
1335
- declare function projectOmmlDisplay(node: OoxmlNode): OmmlEquationProjection | null;
983
+ declare function storyRootsOf(part: OoxmlPart): readonly OoxmlStoryRoot[];
1336
984
  /**
1337
- * The physical justification of a paragraph whose only visible content is display math.
1338
- * `m:oMathParaPr/m:jc` sets it; the default `centerGroup` centers the display. Returns null
1339
- * when the paragraph also holds text or other content, which keeps the paragraph `w:jc`.
985
+ * Whether a part is SHAPED to hold stories — a body, a header, a footer, or a notes part.
986
+ *
987
+ * A shape test, deliberately not `storyRootsOf(part).length > 0`. That counts EDITABLE stories,
988
+ * and a notes part holding nothing but `w:separator` and `w:continuationSeparator` has none —
989
+ * which is the footnotes part Word writes into every document that ever held a footnote. A
990
+ * caller asking "should I walk this part at all" that used the editable count skipped it
991
+ * entirely, and the two callers that ask are a payload sweep and an export strip: both DELETE
992
+ * what they conclude nothing names.
1340
993
  */
1341
- declare function displayMathAlignment(paragraph: {
1342
- readonly children: readonly OoxmlNode[];
1343
- }): 'left' | 'center' | 'right' | null;
1344
- /** Project a paragraph-level equation atom: inline `m:oMath` or display `m:oMathPara`. */
1345
- declare function projectOmmlAtom(node: OoxmlNode): OmmlEquationProjection | null;
1346
-
1347
- /** UTF-16 placeholder for a page break in paragraph text projections. */
1348
- declare const PAGE_BREAK_CHAR = "\f";
1349
- /** What a `w:br` breaks. `other` covers values this engine does not model, kept losslessly. */
1350
- type HardBreakKind = 'line' | 'page' | 'column' | 'other';
1351
- /** Read the semantic break kind from a typed `w:br` node. */
1352
- declare function hardBreakKind(node: OoxmlHardBreakNode): HardBreakKind;
1353
- /** Whether a node is a `w:br` with `w:type="page"`. */
1354
- declare function isPageBreakNode(node: OoxmlNode): node is OoxmlHardBreakNode;
1355
- /** Text projection for a `w:br` node — one UTF-16 code unit per break. */
1356
- declare function hardBreakText(node: OoxmlHardBreakNode): string;
1357
- /** Attributes for a newly authored `w:br`. */
1358
- declare function hardBreakAttributes(kind: 'line' | 'page'): OoxmlHardBreakNode['attributes'];
1359
-
1360
- /** Parsed TOC instruction. Unknown switches are ignored for generation but left on the wire. */
1361
- interface TocInstruction {
1362
- readonly keyword: 'TOC';
1363
- /** Include hyperlinks (`\\h`). */
1364
- readonly hyperlink: boolean;
1365
- /** Omit page numbers (`\\n`). */
1366
- readonly omitPageNumbers: boolean;
1367
- /** Inclusive 1-based outline levels from `\\o "n-m"`. Defaults 1–9. */
1368
- readonly outlineStart: number;
1369
- readonly outlineEnd: number;
1370
- readonly raw: string;
1371
- }
1372
- /** Longest TOC field instruction read. Instructions come from a file; the parse is bounded. */
1373
- declare const TOC_MAX_INSTRUCTION_CHARS = 256;
1374
- /** Most entries one generated table of contents may hold. */
1375
- declare const TOC_MAX_ENTRIES = 512;
1376
- /** Most bookmarks minted during one TOC refresh. */
1377
- declare const TOC_MAX_BOOKMARKS_PER_REFRESH = 512;
1378
- /** Deepest nested field instruction followed. Caps recursion on file-supplied structure. */
1379
- declare const TOC_MAX_FIELD_NESTING = 4;
994
+ declare function isStoryPart(part: OoxmlPart): boolean;
995
+ /** The main body story of a part, or null when the part holds none. */
996
+ declare function bodyStoryRoot(part: OoxmlPart): OoxmlNode | null;
1380
997
  /**
1381
- * Most layout passes a TOC refresh runs before settling.
998
+ * Every paragraph of one story, in reading order.
1382
999
  *
1383
- * Page numbers change the TOC's own height, which changes page numbers — bounded so a
1384
- * non-converging document stops rather than looping.
1000
+ * Descends through tables (rows, cells, nested tables), block controls and block custom XML.
1001
+ * The returned nodes are paragraph elements; a caller addresses them by `id`.
1385
1002
  */
1386
- declare const TOC_MAX_PAGE_PASSES = 3;
1003
+ declare function storyParagraphs(root: OoxmlNode): readonly OoxmlNode[];
1387
1004
  /**
1388
- * Parse a TOC field instruction string.
1005
+ * The block walk itself, appending into `out`.
1389
1006
  *
1390
- * Returns null when the leading keyword is not TOC, the string is over-long, or the
1391
- * outline range is hostile. Does not evaluate or fetch anything.
1007
+ * Exported so `allParagraphs` in the binding lane is the same traversal rather than a second
1008
+ * copy of it.
1392
1009
  */
1393
- declare function parseTocInstruction(raw: string): TocInstruction | null;
1010
+ declare function collectStoryParagraphs(children: readonly OoxmlNode[], out: OoxmlNode[], sdtDepth: number): void;
1394
1011
 
1395
- /** A table of contents found in a document, whether wrapped in an SDT or a bare field. */
1396
- interface DetectedToc {
1397
- /** Enclosing control id when it identifies one TOC, otherwise the begin fldChar id. */
1398
- readonly id: string;
1399
- readonly beginNodeId: string;
1400
- readonly beginParagraphId: string;
1401
- readonly endParagraphId: string;
1402
- readonly resultParagraphIds: readonly string[];
1403
- /** Direct parent whose paragraph children delimit the cached result. */
1404
- readonly containerId: string;
1405
- readonly contentControlId?: string;
1406
- readonly instruction: TocInstruction;
1012
+ /** One searchable text-box story and the drawing location that can reveal it. */
1013
+ interface TextboxStoryRoot {
1014
+ /** The `w:txbxContent` story root. */
1015
+ readonly root: OoxmlElement;
1016
+ /** Layout atom id used to select the drawing, including an MC wrapper when present. */
1017
+ readonly drawingNodeId: string;
1018
+ /** Canonical node id of the paragraph that anchors the drawing. */
1019
+ readonly hostParagraphId: string;
1407
1020
  }
1408
- /** Discover refreshable body TOCs without evaluating any field instruction. */
1409
- declare function detectBodyTocs(part: OoxmlPart): readonly DetectedToc[];
1410
- /** Locate the table of contents containing a position, or null. */
1411
- declare function findDetectedToc(tocs: readonly DetectedToc[], tocId: string): DetectedToc | null;
1412
-
1413
- /** One heading symbol: its `w:font` and `w:char`, as the file wrote them. */
1414
- interface TocSymbol {
1415
- readonly font: string | null;
1416
- readonly char: string;
1417
- }
1418
-
1419
- declare const TWIPS: unique symbol;
1420
- declare const POINTS: unique symbol;
1421
1021
  /**
1422
- * A length in twentieths of a point — OOXML's `ST_TwipsMeasure` / `ST_SignedTwipsMeasure`.
1423
- *
1424
- * The brand is intersection-typed onto `number`, so a `Twips` value still decays to `number`
1425
- * wherever arithmetic consumes it; only the reverse direction — passing a raw number where
1426
- * `Twips` is declared — is refused.
1022
+ * List the text-box stories in one part, in document order.
1427
1023
  *
1428
- * @public
1024
+ * The bounded walk stops at drawings. It does not project pictures, shape geometry, or story
1025
+ * content. Results are memoized by immutable part-root identity.
1429
1026
  */
1430
- type Twips = number & {
1431
- readonly [TWIPS]: true;
1432
- };
1027
+ declare function textboxStoriesInPart(part: OoxmlPart): readonly TextboxStoryRoot[];
1028
+
1029
+ /** Relationship from the story to one data part. */
1030
+ declare const CUSTOM_XML_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
1031
+ /** Relationship from a data part to the properties that carry its `ds:itemID`. */
1032
+ declare const CUSTOM_XML_PROPS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps";
1033
+ /** `itemPropsN.xml` needs an Override; `itemN.xml` rides the package's `xml` default. */
1034
+ declare const CUSTOM_XML_PROPS_TYPE = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";
1035
+ /** The datastore namespace `ds:datastoreItem` lives in. */
1036
+ declare const DATASTORE_NAMESPACE_URI = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";
1037
+ /** A data part located in a package: where it lives, and the GUID an SDT binds to. */
1038
+ interface CustomXmlDataPart {
1039
+ /** Canonical part name, e.g. `/customXml/item1.xml`. */
1040
+ readonly partName: string;
1041
+ /** Part name of its properties, e.g. `/customXml/itemProps1.xml`. */
1042
+ readonly propsPartName: string;
1043
+ /** `ds:itemID`, braced and upper-case, as `w:storeItemID` must spell it. */
1044
+ readonly itemId: string;
1045
+ /** Namespace URI of the payload root, which is what identifies one store among several. */
1046
+ readonly namespaceUri: string;
1047
+ }
1433
1048
  /**
1434
- * A length in typographic points, the unit layout and paint compute in.
1049
+ * A `ds:itemID` derived from the seed rather than drawn at random.
1435
1050
  *
1436
- * @public
1051
+ * Exported so a caller that authors a store OUTSIDE a package — a template engine splicing
1052
+ * markup it will assemble into a `.docx` later — mints the id the same way this does, rather
1053
+ * than inventing a second GUID shape Word has to be tolerant of.
1054
+ *
1055
+ * The store is a pure function of what it is asked to write: the same document written twice
1056
+ * has to produce the same bytes, or a save/reopen/save round trip stops being a fixed point
1057
+ * and every digest taken over saved bytes moves. A GUID's job here is uniqueness within one
1058
+ * package, not unguessability, so four FNV-1a passes over a salted seed carry it.
1437
1059
  */
1438
- type Points = number & {
1439
- readonly [POINTS]: true;
1440
- };
1060
+ declare function datastoreItemIdFor(seed: string): string;
1441
1061
  /**
1442
- * Twentieths of a point per point.
1062
+ * The data parts a story relates to, in relationship order.
1443
1063
  *
1444
- * @public
1064
+ * Reads the relationships rather than scanning `/customXml/` by name: a part nothing relates
1065
+ * to is not part of the document, and a package from a hostile sender can hold as many
1066
+ * plausibly-named files as it likes.
1445
1067
  */
1446
- declare const TWIPS_PER_POINT = 20;
1068
+ declare function customXmlDataParts(pkg: OoxmlPackage, storyPartName: string): CustomXmlDataPart[];
1069
+ /** The data part carrying this namespace, or null when the document has none yet. */
1070
+ declare function findCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): CustomXmlDataPart | null;
1071
+ /** What {@link withCustomXmlDataPart} answers. */
1072
+ interface CustomXmlDataPartResult {
1073
+ readonly pkg: OoxmlPackage;
1074
+ /** Null when the part could not be authored; the package then comes back unchanged. */
1075
+ readonly part: CustomXmlDataPart | null;
1076
+ }
1447
1077
  /**
1448
- * Assert that a number is a twips measurement.
1078
+ * Ensure the document carries a data part for this namespace, creating it and everything it
1079
+ * needs — properties, both relationships, the properties content type — when it does not.
1449
1080
  *
1450
- * A compile-time cast, not a validator: bounds, integrality and finiteness stay at the parse
1451
- * boundary that produced the number, exactly where they are enforced today. The cast is the
1452
- * caller's claim about the UNIT, nothing more.
1081
+ * Idempotent: a package that already has one for the namespace comes back untouched, so a
1082
+ * second node added to the same store does not author a second store.
1453
1083
  *
1454
- * @public
1084
+ * @param storyPartName - Whose relationships the store hangs off. Word enumerates its data
1085
+ * store from the MAIN DOCUMENT part, so a store authored off a header or footer is one Word
1086
+ * never sees.
1455
1087
  */
1456
- declare const twips: (value: number) => Twips;
1088
+ declare function withCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string, rootLocalName: string): CustomXmlDataPartResult;
1457
1089
  /**
1458
- * Assert that a number is a points measurement. A compile-time cast; see {@link twips}.
1090
+ * Remove a store from a document: both parts, both relationships, the Override.
1459
1091
  *
1460
- * @public
1092
+ * PACKAGE ONLY. It does not touch the body, so a `w:sdt` bound to the store keeps its
1093
+ * `w:dataBinding`, its `w:storeItemID` and its `w:tag`, and Word then opens a control bound to
1094
+ * a store that is not there. Stripping those is the export path's job and is not built; this
1095
+ * is the half that removes the payload, which is the half a caller can rely on.
1096
+ *
1097
+ * `ok: false` means nothing was removed and the package is unchanged — most often because an
1098
+ * owner's `.rels` was never parsed into a tree, which {@link withoutPart} refuses to work
1099
+ * around. A caller exporting a document has to treat that as a failure to export rather than
1100
+ * as a document with nothing to strip, or it ships the payload it meant to remove.
1461
1101
  */
1462
- declare const points: (value: number) => Points;
1102
+ declare function withoutCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): WithoutPartResult;
1103
+
1104
+ /** One node in a store: its id, the bound text, and the payload beside it. */
1105
+ interface CustomXmlNode {
1106
+ readonly id: string;
1107
+ /** Text a `w:dataBinding` resolves to. Untrusted file input. */
1108
+ readonly label: string;
1109
+ /** Payload as authored, JSON by convention and unparsed here. Untrusted file input. */
1110
+ readonly data: string;
1111
+ }
1112
+ /** Every node a store holds, in document order. */
1113
+ declare function customXmlNodes(pkg: OoxmlPackage, partName: string): CustomXmlNode[];
1114
+ /** One node by id, or null. */
1115
+ declare function readCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): CustomXmlNode | null;
1463
1116
  /**
1464
- * The one twips-to-points conversion. Exact division; twips are the finer unit.
1117
+ * Write a node, replacing one that already has the id.
1465
1118
  *
1466
- * @public
1119
+ * Replace rather than append: a second node with the same id makes the binding xpath ambiguous,
1120
+ * and Word resolves an ambiguous xpath to the first match — so an "update" that appended would
1121
+ * leave the control showing its old text forever.
1467
1122
  */
1468
- declare const twipsToPoints: (value: Twips) => Points;
1123
+ declare function withCustomXmlNode(pkg: OoxmlPackage, partName: string, node: CustomXmlNode): OoxmlPackage;
1124
+ /** Drop one node by id. A store that never held it comes back unchanged. */
1125
+ declare function withoutCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): OoxmlPackage;
1469
1126
  /**
1470
- * The one points-to-twips conversion.
1127
+ * Drop every node no longer referenced, given the ids the document still binds.
1471
1128
  *
1472
- * Rounds to the nearest twip: every OOXML twips measurement is integral, and emitting a
1473
- * fractional twip would write a value no consumer of the file can represent.
1129
+ * This is the whole deletion story. Deleting a control in THIS editor can remove its node
1130
+ * directly, but a control deleted in Word leaves the node behind — Word has no lifecycle link
1131
+ * between the two and no way to run our code. Reconciling against what the story actually binds
1132
+ * collects both, and is the only thing that can collect the second.
1474
1133
  *
1475
- * @public
1134
+ * Takes the referenced ids rather than reading the story itself: the caller already walked it,
1135
+ * and a sweep that guessed at which controls exist would delete a payload on a mistake.
1476
1136
  */
1477
- declare const pointsToTwips: (value: Points) => Twips;
1137
+ declare function withoutOrphanCustomXmlNodes(pkg: OoxmlPackage, partName: string, referencedIds: ReadonlySet<string>): {
1138
+ readonly pkg: OoxmlPackage;
1139
+ readonly removed: readonly string[];
1140
+ };
1478
1141
  /**
1479
- * Read a twips attribute (`ST_TwipsMeasure`, `ST_SignedTwipsMeasure`, or a `dxa` table width)
1480
- * as a whole, signed number of twips, or `null` when the value is not a measurement.
1481
- *
1482
- * The schema allows an integer or a universal measure, but files also carry decimal twips
1483
- * (`4743.74`, `708.0`, `707.9999999999998`). The accepted forms read as follows:
1484
- *
1485
- * - A decimal truncates toward zero: `1443.74` is 1443 and `-720.6` is -720. A leading `+`,
1486
- * leading zeros, a bare fraction (`.5`) and a trailing point (`1440.`) are accepted.
1487
- * - A universal measure (`mm`, `cm`, `in`, `pt`, `pc`, `pi`) converts exactly and then
1488
- * truncates: `1.27cm` is 720 and `0.333in` is 479. Its sign is ignored, so `-0.5in` is 720.
1489
- * - Whitespace, exponents, hexadecimal, uppercase units, and an integer part longer than nine
1490
- * digits are not measurements.
1491
- *
1492
- * The result is NOT bounded. Callers apply their own sign rule and range clamp, because each
1493
- * attribute has a different valid range and a different fallback.
1142
+ * The `w:xpath` a binding uses to reach a node's label, or null when the id cannot be addressed.
1494
1143
  *
1495
- * @internal
1144
+ * Word needs a prefix for the payload namespace even when the store declares it as a default —
1145
+ * an unprefixed step in an XPath means "no namespace", so `/docxEditor/node` would match
1146
+ * nothing in a namespaced store. The prefix is declared in `w:prefixMappings` beside it.
1496
1147
  */
1497
- declare function readTwipsMeasure(raw: string | undefined): number | null;
1498
-
1499
- /** Outline heading shape consumed by TOC planning (mirrors DocumentOutlineEntry). */
1500
- interface TocOutlineHeading {
1501
- readonly text: string;
1502
- readonly level: number;
1503
- readonly blockId: string;
1504
- }
1148
+ declare function customXmlLabelXPath(prefix: string, rootLocalName: string, nodeId: string): string | null;
1149
+ /** The `w:prefixMappings` value declaring that prefix, or null when it cannot be written.
1150
+ * The namespace sits inside single quotes inside a double-quoted attribute, so a namespace
1151
+ * carrying either quote character has no representation here. */
1152
+ declare function customXmlPrefixMappings(prefix: string, namespaceUri: string): string | null;
1505
1153
 
1506
- /** Left-indent step between TOC levels, in twips (matches `scripts/demo-doc/toc-block.xml`). */
1507
- declare const TOC_LEVEL_INDENT_TWIPS: Twips;
1508
- /** Bounded left-indent twips for a TOC entry level (0-based heading depth). */
1509
- declare function tocLeftIndentTwips(level: number): Twips;
1510
- /** One planned TOC entry: its level, its text, and the heading it points at. */
1511
- interface TocEntryPlan {
1512
- readonly level: number;
1513
- readonly text: string;
1514
- readonly headingParagraphId: string;
1515
- readonly bookmarkName: string;
1516
- readonly pageNumberText: string;
1517
- /** The heading's symbols, one per {@link TOC_SYMBOL_MARK} in `text`, in order. */
1518
- readonly symbols?: readonly TocSymbol[];
1154
+ /** The prefix every binding this library authors declares and quotes. */
1155
+ declare const CUSTOM_NODE_XPATH_PREFIX = "ns0";
1156
+ /** The three attributes a `w:dataBinding` carries. */
1157
+ interface CustomNodeBinding {
1158
+ readonly prefixMappings: string;
1159
+ readonly xpath: string;
1160
+ readonly storeItemId: string;
1519
1161
  }
1520
- /** Build one TOC entry paragraph node. */
1521
- declare function buildTocEntryParagraph(mint: () => string, entry: TocEntryPlan, instruction: TocInstruction, paragraphPropertiesTemplate?: OoxmlNode): OoxmlNode;
1522
- /** Build an SDT-wrapped complex TOC field with an already planned cached result. */
1523
- declare function buildTocContentControl(mint: () => string, entries: readonly TocEntryPlan[], instruction: TocInstruction, alias: string): OoxmlNode;
1524
1162
  /**
1525
- * Word flattens manual line/tab breaks from a heading into spaces in its TOC cache.
1526
- * Carrying them verbatim makes a short title wrap even when the row has ample room, and the
1527
- * same normalization is what lets a cached row be matched back to the heading it came from.
1163
+ * The binding for one node in one store, or null when the id cannot be addressed by an XPath.
1164
+ *
1165
+ * Refuses rather than escapes: XPath 1.0 has no escape for a quote inside a literal, so an id
1166
+ * carrying one could close the predicate and append an expression of the sender's choosing.
1167
+ * The ids are minted by a host, so refusing is honest — see `ADDRESSABLE_ID`.
1528
1168
  */
1529
- declare function tocEntryText(text: string): string;
1169
+ declare function customNodeBinding(part: CustomXmlDataPart, rootLocalName: string, nodeId: string): CustomNodeBinding | null;
1530
1170
  /**
1531
- * Plan TOC entries from the outline and existing bookmarks.
1171
+ * Every node id the story's controls bind to in one store, in document order.
1532
1172
  *
1533
- * `actorId` is explicit because this planner runs BEFORE the store transaction, so the
1534
- * ambient transaction actor is not bound. Callers that already have the collaboration
1535
- * identity pass it here. `resolveAllocationActor` still honours a
1536
- * `runWithTransactionActor` wrap when the caller prefers that seam.
1173
+ * This is the input the orphan sweep takes: a node whose id is not in here is one no control
1174
+ * names, whether it was deleted in this editor or in Word. Reading it from the STORY rather than
1175
+ * from a host's bookkeeping is what makes the two cases one mechanism.
1537
1176
  */
1538
- declare function planTocEntries(part: OoxmlPart, outline: readonly TocOutlineHeading[], instruction: TocInstruction, pageNumberByParagraphId: ReadonlyMap<string, string>, excludeParagraphIds: ReadonlySet<string>, actorId?: string): {
1539
- readonly entries: readonly TocEntryPlan[];
1540
- readonly bookmarksToCreate: readonly {
1541
- paragraphId: string;
1542
- name: string;
1543
- }[];
1544
- };
1545
- /** Create bookmarkStart/End pair nodes for insertion at the start of a paragraph. */
1546
- declare function bookmarkPairNodes(mint: () => string, name: string, id: string): {
1547
- readonly start: OoxmlNode;
1548
- readonly end: OoxmlNode;
1549
- };
1550
-
1177
+ declare function boundCustomXmlNodeIds(part: OoxmlPart, storeItemId: string): Set<string>;
1551
1178
  /**
1552
- * The heading each cached result row stands for, aligned with `toc.resultParagraphIds`.
1179
+ * Every node id ANY story in the package binds, in one store.
1553
1180
  *
1554
- * `null` for a row that names no heading this document still has — a stale row, or the
1555
- * chrome/blank paragraphs a cached result can carry. Callers leave those alone rather than
1556
- * writing another row's number into them.
1181
+ * THE WHOLE PACKAGE, not one story. A payload is reachable from a header as easily as from the
1182
+ * body — Word enumerates its data store from the main part, but nothing stops a control
1183
+ * elsewhere quoting the same `w:storeItemID` — and the two callers that decide what is an orphan
1184
+ * both destroy data when they are wrong. The sweep would collect a payload a header still paints;
1185
+ * the export would strip a store a header still names, which is a document Word offers to repair.
1186
+ *
1187
+ * Costs one walk per story per store, on open and on export. Neither is a keystroke.
1557
1188
  */
1558
- declare function resolveTocRowHeadings(part: OoxmlPart, toc: DetectedToc, outline: readonly TocOutlineHeading[], excludeParagraphIds: ReadonlySet<string>): readonly (string | null)[];
1189
+ declare function boundCustomXmlNodeIdsInPackage(pkg: OoxmlPackage, storeItemId: string): Set<string>;
1190
+ /** The node id one control binds to in the named store, or null when it binds to nothing there. */
1191
+ declare function boundCustomXmlNodeIdOf(control: OoxmlNode, storeItemId: string): string | null;
1559
1192
 
1560
- /** One paragraph in the index: its node id, its story, and its position. */
1561
- interface ParagraphIndexEntry {
1562
- /** Canonical tree node id — the stable identity operations address. */
1563
- readonly nodeId: string;
1564
- /** Position among the story's paragraphs, in document order. */
1565
- readonly ordinal: number;
1566
- /** Concatenated text content, with tabs and breaks mapped as the model reads them. */
1567
- readonly text: string;
1568
- /** Node ids of the paragraph's runs, in order. */
1569
- readonly runIds: readonly string[];
1570
- }
1571
- /** One story root — body, a header/footer variant, or a note part. */
1572
- interface StoryIndexEntry {
1573
- /** The part the story lives in. */
1574
- readonly partName: string;
1575
- /** The `w:body` (or story root) node id. */
1576
- readonly rootId: string;
1577
- readonly paragraphs: readonly ParagraphIndexEntry[];
1578
- }
1579
- /** One style definition, indexed by the id content references it under. */
1580
- interface StyleIndexEntry {
1581
- readonly styleId: string;
1582
- readonly type: string;
1583
- readonly nodeId: string;
1584
- readonly name: string | null;
1585
- readonly basedOn: string | null;
1586
- /** Whether the part marks this the default style for its type (`w:default="1"`). */
1587
- readonly isDefault: boolean;
1588
- }
1589
- /**
1590
- * The derived lookups over a part: paragraphs, stories and styles by id.
1591
- *
1592
- * Diff-patched on commit rather than rebuilt — rebuilding every index per keystroke is what made
1593
- * typing scale with document length.
1594
- */
1595
- interface OoxmlIndexes {
1596
- /** The tree revision these projections were derived from. */
1597
- readonly revision: number;
1598
- /** Body story first, then any other story parts, keyed by part name. */
1599
- readonly stories: ReadonlyMap<string, StoryIndexEntry>;
1600
- /** Every paragraph across every story, keyed by node id. */
1601
- readonly paragraphs: ReadonlyMap<string, ParagraphIndexEntry>;
1602
- readonly relationships: ReadonlyMap<string, readonly RelationshipRecord[]>;
1603
- readonly styles: ReadonlyMap<string, StyleIndexEntry>;
1604
- }
1605
- /** Style definitions, read out of the generic `w:styles` tree. */
1606
- declare function indexStyles(part: OoxmlPart | undefined): Map<string, StyleIndexEntry>;
1607
- /** The package's style definitions part, if it has one. */
1608
- declare function stylesPartOf(pkg: OoxmlPackage): OoxmlPart | undefined;
1609
- /**
1610
- * Derive every index from one canonical package revision.
1611
- *
1612
- * Pure: the same package and revision always produce the same index, which is what makes
1613
- * "rebuild rather than mutate" a safe invalidation strategy.
1614
- */
1615
- declare function deriveOoxmlIndexes(pkg: OoxmlPackage, revision: number): OoxmlIndexes;
1616
-
1617
- /** One paragraph's meaning, independent of how it was spelled in XML. */
1618
- interface ParagraphDigest {
1619
- /** Ordinal identity within its story. Node ids are NOT used: a reopened package
1620
- * legitimately re-derives them, and requiring them to match would test the id scheme
1621
- * rather than the content. */
1622
- readonly ordinal: number;
1623
- /**
1624
- * Where the paragraph SITS: the element path from the story root, so a paragraph that
1625
- * moves out of the table cell it was written in is a difference rather than a paragraph
1626
- * with the same ordinal and the same text.
1627
- */
1628
- readonly path: string;
1629
- /**
1630
- * `w14:paraId`, uppercase-normalized (matching is case-insensitive), or null. This is
1631
- * MANAGED identity — the agent contract anchors on it and comment threading references
1632
- * it — so a serializer silently dropping it must be a digest difference. Other paragraph
1633
- * attributes (`w:rsidR` …) stay deliberately undigested: they are revision noise.
1634
- */
1635
- readonly paraId: string | null;
1636
- /** Text content, including tabs and hard breaks as their characters. */
1637
- readonly text: string;
1638
- /** Accepted paragraph properties, as sorted tokens including nested children. */
1639
- readonly paragraphProperties: readonly string[];
1640
- /** Per-run accepted properties, in run order. */
1641
- readonly runProperties: readonly (readonly string[])[];
1642
- /** Fingerprints of every generic (unknown) subtree, in document order. */
1643
- readonly genericStructure: readonly string[];
1644
- }
1645
- /** One story reduced to its semantic content, ignoring everything a normalized re-emit changes. */
1646
- interface StoryDigest {
1647
- readonly partName: string;
1648
- readonly paragraphs: readonly ParagraphDigest[];
1193
+ /** What happens to one control when the document is exported. */
1194
+ type CustomNodeExportPolicy = 'keep' | 'text' | 'remove';
1195
+ /** How {@link withExportedCustomNodes} decides, and which stores it may tidy afterwards. */
1196
+ interface CustomNodeExportRequest {
1197
+ /** The story whose controls are policed, and whose relationships the stores hang off. */
1198
+ readonly storyPartName: string;
1649
1199
  /**
1650
- * Every block-level element of the part OUTSIDE a paragraph, in document order, as
1651
- * `path name(attributes)` — the tables, rows, cells, sections, content controls and
1652
- * their property children, each at the position that says what contains it.
1200
+ * Payload namespaces the caller CLAIMS.
1653
1201
  *
1654
- * A paragraph's own internals are not here (they are its `ParagraphDigest`), which keeps
1655
- * this list proportional to a document's STRUCTURE rather than its text.
1202
+ * The store cleanup runs only over these. Word's own Cover Page Properties store rides in most
1203
+ * templates, and an export that tidied every customXml part would be deleting from documents it
1204
+ * was only asked to strip its own markup from.
1656
1205
  */
1657
- readonly structure: readonly string[];
1206
+ readonly namespaces: readonly string[];
1207
+ /** The fate of a control carrying this `w:tag`. A control with no tag is never touched. */
1208
+ readonly decide: (tag: string) => CustomNodeExportPolicy;
1658
1209
  }
1659
1210
  /**
1660
- * The whole document's semantic content — one of the D9 losslessness oracles.
1211
+ * The export, or the reason there is no export.
1661
1212
  *
1662
- * What a save/reopen round-trip is compared on. Byte identity applies only to non-XML parts;
1663
- * modelled parts re-emit normalized, so equality is asserted HERE rather than on bytes.
1213
+ * A refusal answers no package on purpose. "Stripping failed, here is the document anyway" is the
1214
+ * one outcome that must not be possible: a caller would ship the markup it asked to remove and
1215
+ * have been told the export succeeded.
1664
1216
  */
1665
- interface SemanticDigest {
1666
- readonly stories: readonly StoryDigest[];
1667
- }
1668
- /** Where two digests diverge — the diagnostic when a round-trip loses something. */
1669
- type DigestDifference = {
1670
- readonly path: string;
1671
- readonly before: string;
1672
- readonly after: string;
1217
+ type CustomNodeExportResult = {
1218
+ readonly ok: true;
1219
+ readonly pkg: OoxmlPackage;
1220
+ /** Controls unwrapped (`text`) and controls removed (`remove`). */
1221
+ readonly unwrapped: number;
1222
+ readonly removed: number;
1223
+ } | {
1224
+ readonly ok: false;
1225
+ readonly reason: string;
1673
1226
  };
1674
- /** Digest one part: its paragraphs, and the structure that holds them. */
1675
- declare function digestPart(part: OoxmlPart): StoryDigest | null;
1676
- /** Digest every part, in the given order. */
1677
- declare function semanticDigest(parts: Iterable<OoxmlPart>): SemanticDigest;
1678
1227
  /**
1679
- * Every way two digests differ, as readable paths.
1228
+ * Apply the policy, then take the payloads and the stores the policy orphaned.
1680
1229
  *
1681
- * Returns the differences rather than a boolean because "the round trip lost something" is
1682
- * useless without saying what — the failure this oracle exists to catch is a silent drop,
1683
- * and a bare `false` reproduces the silence.
1230
+ * Order matters and is the reverse of the write's. The BODY goes first, so the sweep that follows
1231
+ * sees the controls that actually survive; the stores go last, once nothing binds them. Doing it
1232
+ * the other way would strip a store while a control still quoted its `w:storeItemID`, which is a
1233
+ * document Word opens and offers to repair.
1684
1234
  */
1685
- declare function diffSemanticDigests(before: SemanticDigest, after: SemanticDigest): DigestDifference[];
1235
+ declare function withExportedCustomNodes(pkg: OoxmlPackage, request: CustomNodeExportRequest): CustomNodeExportResult;
1686
1236
 
1687
- /** Valid per MS-DOCX: 8 hex digits, non-zero, below 0x80000000. */
1688
- declare function isValidParaId(value: string): boolean;
1689
- /** The authored `w14:paraId` value of an element, verbatim, or null. */
1690
- declare function paraIdOf(node: OoxmlNode): string | null;
1691
- /** FNV-1a over UTF-16 code units — the deterministic mint every id derivation shares. */
1692
- declare function fnv1a32(value: string): number;
1693
1237
  /**
1694
- * Deterministic 8-hex mint in (0x00000000, 0x80000000), collision-free against
1695
- * `used` (uppercase hex). Same seed + same used-set → same value, which is what
1696
- * keeps `splitParagraphMany` byte-identical to its equivalent single splits and
1697
- * a reopened save identical to the session that produced it.
1238
+ * Every kind of thing the registry gives a stable identity to.
1239
+ *
1240
+ * Identity is `(kind, id)` plus version and NEVER registration order, so two bundles contributing
1241
+ * the same command resolve deterministically regardless of which loaded first.
1698
1242
  */
1699
- declare function mintParaId(seed: string, used: ReadonlySet<string>): string;
1700
- /** Every valid `w14:paraId` in the tree, uppercased. Memoized per root object. */
1701
- declare function usedParaIds(root: OoxmlElement): ReadonlySet<string>;
1243
+ declare const ID_KINDS: readonly ['extension', 'capability', 'command', 'query', 'schema', 'dependencyKey', 'runtimePort', 'result', 'origin'];
1244
+ /** One of {@link ID_KINDS}. */
1245
+ /** One of {@link ID_KINDS} — which sort of thing an identifier names. */
1246
+ type IdKind = (typeof ID_KINDS)[number];
1702
1247
  /**
1703
- * The non-empty prefix the part ROOT binds to the w14 namespace, or null.
1248
+ * Whether a string is a well-formed identifier in either accepted grammar.
1704
1249
  *
1705
- * Minted attributes require an in-scope binding (the invariant validator reports
1706
- * `invalid-qname` otherwise, and the serializer would allocate an `nsN` alias).
1707
- * Only the root binding counts: a binding authored on some descendant does not
1708
- * cover paragraphs elsewhere in the tree.
1250
+ * Reverse-domain (`dev.docx-editor.core.command.insert-text`) or package-owned
1251
+ * (`@docx-editor.dev/engine-core#command/insert-text`). Ids are opaque once validated.
1709
1252
  */
1710
- declare function w14RootPrefix(root: OoxmlElement): string | null;
1711
- /** The minted `[w14:paraId, w14:textId]` pair. `textId` mirrors `paraId`: it has no uniqueness requirement, no consumer reads it, and one allocator is simpler than two — but Word writes both, so we write both. */
1712
- declare function mintedParagraphIdentityAttributes(prefix: string, value: string): readonly OoxmlAttribute[];
1253
+ declare function isValidId(id: string): boolean;
1713
1254
  /**
1714
- * Load-time paragraph-identity normalization for a session's main part.
1715
- *
1716
- * Keeps every valid, first-seen paraId verbatim; mints (deterministically, seeded
1717
- * by the paragraph's structural node id) for paragraphs whose id is missing,
1718
- * malformed, zero, out of range, or a duplicate. Adds the root `xmlns` binding
1719
- * the minted attributes need. Returns the INPUT PART REFERENCE when there is
1720
- * nothing to do — a document Word saved yesterday re-serializes byte-identical.
1721
- *
1722
- * Attribute-only rebuilds move no child, so every node keeps its structural-path
1723
- * id; the copy respreads only the ancestors of changed paragraphs.
1255
+ * Validate an identifier, throwing when it is malformed.
1724
1256
  *
1725
- * Fail-open: if the rebuilt part does not validate (a bug, or a pathology the
1726
- * prefix choice could not defuse), the original part is returned — a document
1727
- * must never become unopenable over an identity enhancement.
1257
+ * Throws rather than returning: a bad id is an author mistake at registration time, not file
1258
+ * input, and accepting it would produce a registry whose identities silently collide.
1728
1259
  */
1729
- declare function normalizeParagraphIdentity(part: OoxmlPart): OoxmlPart;
1730
-
1731
- /** One `w:docPart` of the glossary, with the blocks its body holds. */
1732
- interface BuildingBlock {
1733
- /** `w:docPartPr/w:name`, the identity a control's placeholder and a pick refer to. */
1734
- readonly name: string;
1735
- /** `w:category/w:gallery`, an `ST_DocPartGallery` value such as `docParts`. */
1736
- readonly gallery: string;
1737
- /** `w:category/w:name`; `General` when the block declares none. */
1738
- readonly category: string;
1739
- /** The `w:docPartBody` children: paragraphs, tables and block controls, in order. */
1740
- readonly blocks: readonly OoxmlNode[];
1260
+ declare function assertValidId(id: string, kind?: IdKind): void;
1261
+ /** A validated (kind, id, version) triple — the registry's unit of identity. */
1262
+ interface CapabilityId {
1263
+ readonly kind: IdKind;
1264
+ readonly id: string;
1265
+ readonly version: string;
1741
1266
  }
1742
- /** The gallery and category a `w:docPartList` control lists. */
1743
- interface BuildingBlockGalleryFilter {
1744
- readonly gallery: string;
1745
- readonly category: string | null;
1267
+
1268
+ /** A parsed semantic version. Only the three numeric components — no pre-release or build. */
1269
+ interface SemVer {
1270
+ readonly major: number;
1271
+ readonly minor: number;
1272
+ readonly patch: number;
1746
1273
  }
1747
- /** The glossary part, through the main part's relationship or the conventional name. */
1748
- declare function glossaryPartOf(pkg: OoxmlPackage): OoxmlPart | null;
1749
- /** Every named building block of the glossary, in authored order. Empty without a glossary. */
1750
- declare function buildingBlocksOf(pkg: OoxmlPackage): readonly BuildingBlock[];
1751
- /** The gallery a `w:docPartList` control lists, or null for any other control. */
1752
- declare function buildingBlockGalleryOf(control: OoxmlNode): BuildingBlockGalleryFilter | null;
1753
1274
  /**
1754
- * The blocks a gallery control offers: same gallery, and the control's category when it names
1755
- * one. Sorted by category, then name, as Word groups its list.
1275
+ * Parse a semantic version, rejecting anything the registry's rules do not need.
1276
+ *
1277
+ * Deliberately narrow: an unsupported range form is refused rather than accepted, so a malformed
1278
+ * range can never masquerade as "compatible".
1756
1279
  */
1757
- declare function buildingBlocksForControl(pkg: OoxmlPackage, control: OoxmlNode): readonly BuildingBlock[];
1758
-
1280
+ declare function parseSemVer(input: string): SemVer;
1281
+ /** Order two versions: negative, zero or positive, by major then minor then patch. */
1282
+ declare function compareSemVer(a: SemVer, b: SemVer): -1 | 0 | 1;
1759
1283
  /**
1760
- * Which story a comment deletion or resolution may read markers from.
1761
- *
1762
- * `w:id` is not unique across stories: a header and the body can both hold comment 1.
1284
+ * Whether `version` satisfies `range`. Supported range grammar:
1285
+ * - `*` any version
1286
+ * - `1.2.3` exact
1287
+ * - `^1.2.3` caret: same major, and >= the floor (major 0 pins the minor)
1288
+ * - `>=1.2.3 <2.0.0` a single lower (inclusive) + upper (exclusive) bound pair
1289
+ * Any other shape throws — an unparseable range is a registration error, not a pass.
1763
1290
  */
1764
- interface CommentDeletionOwner {
1765
- /** Canonical name of the part holding the story's markers. */
1766
- readonly storyPartName: string;
1767
- /**
1768
- * When the story is one note inside a shared notes part, that note's `w:id`.
1769
- * Absent means the whole part is the story (body, header, footer).
1770
- */
1771
- readonly noteId?: number;
1772
- }
1291
+ declare function satisfies(version: string, range: string): boolean;
1773
1292
 
1774
1293
  /**
1775
- * Delete a comment thread: that story's markers, and metadata no other story still names.
1294
+ * Why registry resolution failed.
1776
1295
  *
1777
- * `owner` names the story whose markers may be stripped. Omitted, it is the main document
1778
- * body — never every XML part. A header or note that reused the same `w:id` is a different
1779
- * remark; pass its part (and `noteId` when the story is one note) to delete that one.
1780
- *
1781
- * Returns the package unchanged when the id names no comment, and null when a removal was
1782
- * refused — a caller inside a transaction rolls back rather than committing a package whose
1783
- * comment is half gone.
1296
+ * Every code names a declaration conflict a bundle author can fix — a missing dependency, an
1297
+ * unsatisfied version range, a duplicate contribution with no replacement policy.
1784
1298
  */
1785
- declare function deleteCommentThread(pkg: OoxmlPackage, commentId: string, owner?: CommentDeletionOwner): OoxmlPackage | null;
1299
+ type RegistryErrorCode = 'invalid-id' | 'invalid-version' | 'duplicate-extension' | 'id-collision' | 'replacement-target-missing' | 'unauthorized-replacement' | 'replacement-version-mismatch' | 'ambiguous-replacement' | 'missing-dependency' | 'dependency-cycle' | 'conflict' | 'missing-port';
1786
1300
  /**
1787
- * Delete every comment the edit between `before` and `after` emptied in `owner`'s story.
1788
- *
1789
- * `owner` omitted is the main document body, matching {@link deleteCommentThread}.
1301
+ * A resolution failure naming every responsible party.
1790
1302
  *
1791
- * THE TEST, exactly, and per story. A comment dies when the words it covered in that story are
1792
- * gone and nothing in that story still places it. A neighbour that reused the same `w:id` is
1793
- * judged under its own owner. Notes that vanished (reference cascade) are reaped as their own
1794
- * stories so a unique id still loses its `comments.xml` body. Remaining-marker overflow
1795
- * preserves comments/commentEx/commentId metadata rather than deleting records the scan could
1796
- * not prove unused. Null is reserved for a removal that actually failed.
1303
+ * Thrown rather than returned: an unresolvable registry is a build-time composition mistake, and
1304
+ * an engine running with a half-resolved registry would fail later in ways that do not point back
1305
+ * to the bundle that caused it.
1797
1306
  */
1798
- declare function cascadeEmptiedComments(before: OoxmlPackage, after: OoxmlPackage, owner?: CommentDeletionOwner): OoxmlPackage | null;
1799
-
1800
- /** Presentation settings the document itself states. Absence is the answer, never an error. */
1801
- interface DocumentViewSettings {
1802
- /**
1803
- * `w:doNotShadeFormData` (§17.15.1.49) — do NOT shade legacy form fields.
1804
- *
1805
- * Word draws a grey block behind every `w:ffData` field so a reader can find the blanks in a
1806
- * form. It is on by DEFAULT, and this element is how a document turns it off, so the absent
1807
- * case means shading. Reading the name as "shade form data" inverts it and blanks the shading
1808
- * on exactly the documents that asked for it loudest.
1809
- *
1810
- * Never printed, by Word or by us: it marks where to type, and a printed form has no blanks
1811
- * to find.
1812
- */
1813
- readonly doNotShadeFormData: boolean;
1307
+ declare class RegistryError extends Error {
1308
+ readonly code: RegistryErrorCode;
1309
+ /** Stable identities responsible for the failure (extensions, ids). */
1310
+ readonly responsible: readonly string[];
1311
+ constructor(code: RegistryErrorCode, message: string,
1312
+ /** Stable identities responsible for the failure (extensions, ids). */
1313
+ responsible?: readonly string[]);
1814
1314
  }
1815
- /** The defaults a document with no `settings.xml` gets: everything Word would shade, shaded. */
1816
- declare const DEFAULT_VIEW_SETTINGS: DocumentViewSettings;
1817
- /** Read the view settings from a `settings.xml` root, or the defaults when it has none. */
1818
- declare function readViewSettings(settingsRoot: OoxmlNode | null | undefined): DocumentViewSettings;
1819
-
1820
- /** How deep transparent block wrappers may nest before the walk stops descending. */
1821
- declare const MAX_STORY_SDT_NESTING = 32;
1822
- /** Which kind of story a root is. Layout walks all four the same way. */
1823
- type OoxmlStoryKind = 'body' | 'header' | 'footer' | 'note';
1824
- /** One story root and the blocks under it, with transparent block wrappers already flattened. */
1825
- interface OoxmlStoryRoot {
1826
- readonly kind: OoxmlStoryKind;
1827
- /** The `w:body` / `w:hdr` / `w:ftr` / `w:footnote` element that holds the blocks. */
1828
- readonly root: OoxmlNode;
1315
+ /** How a base contribution permits replacement by other bundles. */
1316
+ type ReplacementPolicy = {
1317
+ readonly kind: 'none';
1318
+ } | {
1319
+ readonly kind: 'single';
1320
+ } | {
1321
+ readonly kind: 'priority';
1322
+ };
1323
+ /** One thing a bundle contributes: a command, a query, a schema, a port, keyed by `(kind, id)`. */
1324
+ interface Contribution {
1325
+ readonly kind: Exclude<IdKind, 'extension' | 'origin' | 'result'>;
1326
+ readonly id: string;
1327
+ readonly version: string;
1328
+ /** If set, this contribution replaces an existing base contribution. */
1329
+ readonly replaces?: {
1330
+ readonly targetId: string;
1331
+ readonly targetRange: string;
1332
+ readonly priority?: number;
1333
+ };
1334
+ /** Policy this contribution exposes to would-be replacers (default `none`). */
1335
+ readonly replaceable?: ReplacementPolicy;
1336
+ readonly payload?: unknown;
1829
1337
  }
1830
1338
  /**
1831
- * Every story root in a part, in document order.
1339
+ * A unit of engine functionality: its identity, version, dependencies, conflicts, required ports,
1340
+ * and contributions.
1832
1341
  *
1833
- * Does not descend INTO a story: a story's blocks are the walk below, and a story root never
1834
- * contains another story root.
1342
+ * The registry's whole input. Everything a bundle needs and everything it offers is DECLARED, so
1343
+ * resolution can be deterministic and order-independent.
1835
1344
  */
1836
- declare function storyRootsOf(part: OoxmlPart): readonly OoxmlStoryRoot[];
1345
+ interface FeatureBundle {
1346
+ readonly id: string;
1347
+ readonly version: string;
1348
+ readonly dependencies?: readonly string[];
1349
+ readonly conflicts?: readonly string[];
1350
+ readonly requiredPorts?: readonly string[];
1351
+ readonly contributions: readonly Contribution[];
1352
+ }
1353
+ /** The resolved result: every contribution selected, indexed by `(kind, id)`. */
1354
+ interface ResolvedRegistry {
1355
+ readonly extensions: ReadonlyMap<string, FeatureBundle>;
1356
+ readonly contributions: ReadonlyMap<string, Contribution>;
1357
+ get(kind: Contribution['kind'], id: string): Contribution | undefined;
1358
+ }
1359
+ /** How resolution treats optional bundles and replacement policies. */
1360
+ interface ResolveOptions {
1361
+ /** Runtime port ids available in this environment (design D9 / task 0.3). */
1362
+ readonly availablePorts?: readonly string[];
1363
+ }
1837
1364
  /**
1838
- * Whether a part is SHAPED to hold stories — a body, a header, a footer, or a notes part.
1365
+ * Resolve a set of bundles into one registry, or throw.
1839
1366
  *
1840
- * A shape test, deliberately not `storyRootsOf(part).length > 0`. That counts EDITABLE stories,
1841
- * and a notes part holding nothing but `w:separator` and `w:continuationSeparator` has none —
1842
- * which is the footnotes part Word writes into every document that ever held a footnote. A
1843
- * caller asking "should I walk this part at all" that used the editable count skipped it
1844
- * entirely, and the two callers that ask are a payload sweep and an export strip: both DELETE
1845
- * what they conclude nothing names.
1367
+ * Deterministic and registration-order independent: selection is by `(kind, id)` plus version,
1368
+ * and ties break only on declared policy. Array order never decides anything.
1369
+ *
1370
+ * @throws RegistryError naming every bundle responsible for the failure.
1846
1371
  */
1847
- declare function isStoryPart(part: OoxmlPart): boolean;
1848
- /** The main body story of a part, or null when the part holds none. */
1849
- declare function bodyStoryRoot(part: OoxmlPart): OoxmlNode | null;
1372
+ declare function resolve(bundles: readonly FeatureBundle[], options?: ResolveOptions): ResolvedRegistry;
1373
+
1850
1374
  /**
1851
- * Every paragraph of one story, in reading order.
1852
- *
1853
- * Descends through tables (rows, cells, nested tables), block controls and block custom XML.
1854
- * The returned nodes are paragraph elements; a caller addresses them by `id`.
1375
+ * Typed-origin domains (design D5 / ADR-S5). `mutation.*` are the canonical
1376
+ * write origins; `projection` and `awareness` MUST NOT enter history, audit,
1377
+ * snapshots, or replication.
1855
1378
  */
1856
- declare function storyParagraphs(root: OoxmlNode): readonly OoxmlNode[];
1379
+ declare const ORIGIN_IDS: {
1380
+ readonly mutationHuman: "dev.docx-editor.core.origin.mutation.human";
1381
+ readonly mutationAgent: "dev.docx-editor.core.origin.mutation.agent";
1382
+ readonly mutationRemote: "dev.docx-editor.core.origin.mutation.remote";
1383
+ readonly mutationUndo: "dev.docx-editor.core.origin.mutation.undo";
1384
+ readonly mutationRedo: "dev.docx-editor.core.origin.mutation.redo";
1385
+ readonly mutationMigration: "dev.docx-editor.core.origin.mutation.migration";
1386
+ readonly mutationRepair: "dev.docx-editor.core.origin.mutation.repair";
1387
+ readonly mutationServer: "dev.docx-editor.core.origin.mutation.server";
1388
+ readonly projection: "dev.docx-editor.core.origin.projection";
1389
+ readonly awareness: "dev.docx-editor.core.origin.awareness";
1390
+ };
1391
+ /** Canonical writes carry a mutation origin; these are the undoable-eligibility inputs. */
1392
+ declare const CANONICAL_MUTATION_ORIGINS: readonly string[];
1393
+ /** Origins that never enter authored state / history / audit / snapshot / replication. */
1394
+ declare const NON_CANONICAL_ORIGINS: readonly string[];
1857
1395
  /**
1858
- * The block walk itself, appending into `out`.
1859
- *
1860
- * Exported so `allParagraphs` in the binding lane is the same traversal rather than a second
1861
- * copy of it.
1396
+ * Result taxonomy (design D8 / task 7.8). A transport/protocol failure that
1397
+ * prevents a valid envelope is a typed exception, not a member here.
1862
1398
  */
1863
- declare function collectStoryParagraphs(children: readonly OoxmlNode[], out: OoxmlNode[], sdtDepth: number): void;
1399
+ declare const RESULT_IDS: {
1400
+ readonly applied: "dev.docx-editor.core.result.applied";
1401
+ readonly validation: "dev.docx-editor.core.result.validation";
1402
+ readonly conflict: "dev.docx-editor.core.result.conflict";
1403
+ readonly resource: "dev.docx-editor.core.result.resource";
1404
+ readonly authorization: "dev.docx-editor.core.result.authorization";
1405
+ readonly aborted: "dev.docx-editor.core.result.aborted";
1406
+ };
1407
+ /** Runtime ports (extensions-and-runtime-ports spec; design D9). */
1408
+ declare const RUNTIME_PORT_IDS: {
1409
+ readonly fonts: "dev.docx-editor.core.port.fonts";
1410
+ readonly shaping: "dev.docx-editor.core.port.shaping";
1411
+ readonly images: "dev.docx-editor.core.port.images";
1412
+ readonly clock: "dev.docx-editor.core.port.clock";
1413
+ readonly identity: "dev.docx-editor.core.port.identity";
1414
+ readonly persistence: "dev.docx-editor.core.port.persistence";
1415
+ readonly transport: "dev.docx-editor.core.port.transport";
1416
+ readonly scheduling: "dev.docx-editor.core.port.scheduling";
1417
+ readonly audit: "dev.docx-editor.core.port.audit";
1418
+ readonly authorization: "dev.docx-editor.core.port.authorization";
1419
+ readonly resourceAccounting: "dev.docx-editor.core.port.resource-accounting";
1420
+ readonly cancellation: "dev.docx-editor.core.port.cancellation";
1421
+ readonly externalResourceConsent: "dev.docx-editor.core.port.external-resource-consent";
1422
+ };
1423
+ /** Layout dependency keys (design D6 / task 8.2). */
1424
+ declare const DEPENDENCY_KEY_IDS: {
1425
+ readonly style: "dev.docx-editor.core.dep.style";
1426
+ readonly numbering: "dev.docx-editor.core.dep.numbering";
1427
+ readonly section: "dev.docx-editor.core.dep.section";
1428
+ readonly story: "dev.docx-editor.core.dep.story";
1429
+ readonly font: "dev.docx-editor.core.dep.font";
1430
+ readonly image: "dev.docx-editor.core.dep.image";
1431
+ readonly table: "dev.docx-editor.core.dep.table";
1432
+ readonly field: "dev.docx-editor.core.dep.field";
1433
+ readonly note: "dev.docx-editor.core.dep.note";
1434
+ readonly headerFooter: "dev.docx-editor.core.dep.header-footer";
1435
+ readonly annotation: "dev.docx-editor.core.dep.annotation";
1436
+ };
1437
+ /** Every frozen id as a flat list, for the immutability / uniqueness gate. */
1438
+ declare const ALL_FROZEN_IDS: readonly string[];
1864
1439
 
1865
- /** One searchable text-box story and the drawing location that can reveal it. */
1866
- interface TextboxStoryRoot {
1867
- /** The `w:txbxContent` story root. */
1868
- readonly root: OoxmlElement;
1869
- /** Layout atom id used to select the drawing, including an MC wrapper when present. */
1870
- readonly drawingNodeId: string;
1871
- /** Canonical node id of the paragraph that anchors the drawing. */
1872
- readonly hostParagraphId: string;
1873
- }
1874
1440
  /**
1875
- * List the text-box stories in one part, in document order.
1441
+ * A counter's limit was reached. Carries the label, the limit, and what was attempted.
1876
1442
  *
1877
- * The bounded walk stops at drawings. It does not project pictures, shape geometry, or story
1878
- * content. Results are memoized by immutable part-root identity.
1443
+ * Thrown at the N → N+1 boundary, so the increment that would have crossed the limit never
1444
+ * happens rather than being detected afterwards.
1879
1445
  */
1880
- declare function textboxStoriesInPart(part: OoxmlPart): readonly TextboxStoryRoot[];
1881
-
1882
- /** Relationship from the story to one data part. */
1883
- declare const CUSTOM_XML_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml";
1884
- /** Relationship from a data part to the properties that carry its `ds:itemID`. */
1885
- declare const CUSTOM_XML_PROPS_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps";
1886
- /** `itemPropsN.xml` needs an Override; `itemN.xml` rides the package's `xml` default. */
1887
- declare const CUSTOM_XML_PROPS_TYPE = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml";
1888
- /** The datastore namespace `ds:datastoreItem` lives in. */
1889
- declare const DATASTORE_NAMESPACE_URI = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";
1890
- /** A data part located in a package: where it lives, and the GUID an SDT binds to. */
1891
- interface CustomXmlDataPart {
1892
- /** Canonical part name, e.g. `/customXml/item1.xml`. */
1893
- readonly partName: string;
1894
- /** Part name of its properties, e.g. `/customXml/itemProps1.xml`. */
1895
- readonly propsPartName: string;
1896
- /** `ds:itemID`, braced and upper-case, as `w:storeItemID` must spell it. */
1897
- readonly itemId: string;
1898
- /** Namespace URI of the payload root, which is what identifies one store among several. */
1899
- readonly namespaceUri: string;
1446
+ declare class LimitExceededError extends Error {
1447
+ readonly label: string;
1448
+ readonly limit: number;
1449
+ readonly attempted: number;
1450
+ constructor(label: string, limit: number, attempted: number);
1900
1451
  }
1901
1452
  /**
1902
- * A `ds:itemID` derived from the seed rather than drawn at random.
1903
- *
1904
- * Exported so a caller that authors a store OUTSIDE a package — a template engine splicing
1905
- * markup it will assemble into a `.docx` later — mints the id the same way this does, rather
1906
- * than inventing a second GUID shape Word has to be tolerant of.
1453
+ * Overflow-safe counting against a fixed limit.
1907
1454
  *
1908
- * The store is a pure function of what it is asked to write: the same document written twice
1909
- * has to produce the same bytes, or a save/reopen/save round trip stops being a fixed point
1910
- * and every digest taken over saved bytes moves. A GUID's job here is uniqueness within one
1911
- * package, not unguessability, so four FNV-1a passes over a salted seed carry it.
1455
+ * Never silently wraps: it rejects the increment that would cross its limit AND any arithmetic
1456
+ * that would exceed `Number.MAX_SAFE_INTEGER`. That second guard is the point — a file-supplied
1457
+ * count must never be trusted into an allocation, and a wrapped counter reads as small.
1912
1458
  */
1913
- declare function datastoreItemIdFor(seed: string): string;
1914
- /**
1915
- * The data parts a story relates to, in relationship order.
1916
- *
1917
- * Reads the relationships rather than scanning `/customXml/` by name: a part nothing relates
1918
- * to is not part of the document, and a package from a hostile sender can hold as many
1919
- * plausibly-named files as it likes.
1920
- */
1921
- declare function customXmlDataParts(pkg: OoxmlPackage, storyPartName: string): CustomXmlDataPart[];
1922
- /** The data part carrying this namespace, or null when the document has none yet. */
1923
- declare function findCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): CustomXmlDataPart | null;
1924
- /** What {@link withCustomXmlDataPart} answers. */
1925
- interface CustomXmlDataPartResult {
1926
- readonly pkg: OoxmlPackage;
1927
- /** Null when the part could not be authored; the package then comes back unchanged. */
1928
- readonly part: CustomXmlDataPart | null;
1459
+ declare class BoundedCounter {
1460
+ readonly label: string;
1461
+ readonly limit: number;
1462
+ private value;
1463
+ constructor(label: string, limit: number);
1464
+ get current(): number;
1465
+ /** Remaining headroom before the limit. */
1466
+ get remaining(): number;
1467
+ /**
1468
+ * Add `n` (default 1). Throws LimitExceededError if the result would exceed the
1469
+ * limit (so `limit` itself is reachable but `limit + 1` is not) or overflow the
1470
+ * safe-integer range. On rejection the counter is unchanged.
1471
+ */
1472
+ add(n?: number): number;
1473
+ /** Whether adding `n` would be accepted, without mutating. */
1474
+ canAdd(n?: number): boolean;
1475
+ release(n: number): void;
1476
+ }
1477
+
1478
+ /** A budget was misused: over-carved, over-reserved, or disposed with children outstanding. */
1479
+ declare class BudgetError extends Error {
1480
+ constructor(message: string);
1929
1481
  }
1930
1482
  /**
1931
- * Ensure the document carries a data part for this namespace, creating it and everything it
1932
- * needs — properties, both relationships, the properties content type — when it does not.
1933
- *
1934
- * Idempotent: a package that already has one for the namespace comes back untouched, so a
1935
- * second node added to the same store does not author a second store.
1483
+ * Capacity claimed BEFORE it is allocated.
1936
1484
  *
1937
- * @param storyPartName - Whose relationships the store hangs off. Word enumerates its data
1938
- * store from the MAIN DOCUMENT part, so a store authored off a header or footer is one Word
1939
- * never sees.
1485
+ * Reserve-then-allocate rather than allocate-then-check: discovering the overrun after the
1486
+ * allocation has already happened defeats the point of having a budget.
1940
1487
  */
1941
- declare function withCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string, rootLocalName: string): CustomXmlDataPartResult;
1488
+ interface Reservation {
1489
+ readonly amount: number;
1490
+ readonly released: boolean;
1491
+ release(): void;
1492
+ }
1942
1493
  /**
1943
- * Remove a store from a document: both parts, both relationships, the Override.
1494
+ * One node in the hierarchical resource budget tree.
1944
1495
  *
1945
- * PACKAGE ONLY. It does not touch the body, so a `w:sdt` bound to the store keeps its
1946
- * `w:dataBinding`, its `w:storeItemID` and its `w:tag`, and Word then opens a control bound to
1947
- * a store that is not there. Stripping those is the export path's job and is not built; this
1948
- * is the half that removes the payload, which is the half a caller can rely on.
1496
+ * An operation owns a root budget; parsers, extensions, workers, layout, transport and output
1497
+ * carve children from it, so no subsystem can consume more than the operation as a whole allows.
1949
1498
  *
1950
- * `ok: false` means nothing was removed and the package is unchanged — most often because an
1951
- * owner's `.rels` was never parsed into a tree, which {@link withoutPart} refuses to work
1952
- * around. A caller exporting a document has to treat that as a failure to export rather than
1953
- * as a document with nothing to strip, or it ships the payload it meant to remove.
1499
+ * `dispose()` REFUSES while children or reservations are outstanding, then runs registered
1500
+ * cleanups LIFO — spill files, worker termination — even if one throws. A leaked child budget is a
1501
+ * leaked worker, so the refusal is the diagnostic.
1954
1502
  */
1955
- declare function withoutCustomXmlDataPart(pkg: OoxmlPackage, storyPartName: string, namespaceUri: string): WithoutPartResult;
1956
-
1957
- /** One node in a store: its id, the bound text, and the payload beside it. */
1958
- interface CustomXmlNode {
1959
- readonly id: string;
1960
- /** Text a `w:dataBinding` resolves to. Untrusted file input. */
1503
+ declare class Budget {
1961
1504
  readonly label: string;
1962
- /** Payload as authored, JSON by convention and unparsed here. Untrusted file input. */
1963
- readonly data: string;
1505
+ readonly capacity: number;
1506
+ private readonly used;
1507
+ private readonly children;
1508
+ private activeReservations;
1509
+ private readonly cleanups;
1510
+ private disposed;
1511
+ private carveAmount;
1512
+ private parent?;
1513
+ constructor(label: string, capacity: number);
1514
+ get inUse(): number;
1515
+ get available(): number;
1516
+ get isDisposed(): boolean;
1517
+ /** Reserve `amount` from this budget. Throws if it would exceed capacity. */
1518
+ reserve(amount: number): Reservation;
1519
+ /** Carve a child budget of `capacity` out of this budget's headroom. */
1520
+ child(label: string, capacity: number): Budget;
1521
+ /** Register cleanup for a spill file, worker, or queue tied to this budget. */
1522
+ onRelease(cleanup: () => void): void;
1523
+ /**
1524
+ * Release this budget. Refuses while any child budget or reservation is
1525
+ * outstanding (children must finish first). Runs cleanups LIFO, returns the
1526
+ * carve-out to the parent, and marks disposed. Cleanup errors are collected and
1527
+ * rethrown after every cleanup has run.
1528
+ */
1529
+ dispose(): void;
1530
+ private assertLive;
1964
1531
  }
1965
- /** Every node a store holds, in document order. */
1966
- declare function customXmlNodes(pkg: OoxmlPackage, partName: string): CustomXmlNode[];
1967
- /** One node by id, or null. */
1968
- declare function readCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): CustomXmlNode | null;
1532
+
1969
1533
  /**
1970
- * Write a node, replacing one that already has the id.
1534
+ * Which side of the point of no return an operation is on.
1971
1535
  *
1972
- * Replace rather than append: a second node with the same id makes the binding xpath ambiguous,
1973
- * and Word resolves an ambiguous xpath to the first match — so an "update" that appended would
1974
- * leave the control showing its old text forever.
1536
+ * Canonical publication is that point. Cancelling BEFORE it rolls the whole operation back;
1537
+ * cancelling after it leaves the commit standing and cancels only derived work — layout, export,
1538
+ * caches.
1975
1539
  */
1976
- declare function withCustomXmlNode(pkg: OoxmlPackage, partName: string, node: CustomXmlNode): OoxmlPackage;
1977
- /** Drop one node by id. A store that never held it comes back unchanged. */
1978
- declare function withoutCustomXmlNode(pkg: OoxmlPackage, partName: string, nodeId: string): OoxmlPackage;
1540
+ type CancellationPhase = 'pre-publication' | 'post-publication';
1541
+ /** Thrown from a `checkpoint()` when the operation has been cancelled. */
1542
+ declare class CancellationError extends Error {
1543
+ /** True when the commit is already published and only derived work is cancelled. */
1544
+ readonly derivedOnly: boolean;
1545
+ constructor(
1546
+ /** True when the commit is already published and only derived work is cancelled. */
1547
+ derivedOnly: boolean, reason?: string);
1548
+ }
1979
1549
  /**
1980
- * Drop every node no longer referenced, given the ids the document still binds.
1981
- *
1982
- * This is the whole deletion story. Deleting a control in THIS editor can remove its node
1983
- * directly, but a control deleted in Word leaves the node behind — Word has no lifecycle link
1984
- * between the two and no way to run our code. Reconciling against what the story actually binds
1985
- * collects both, and is the only thing that can collect the second.
1550
+ * The read side of cancellation, handed to cooperative work.
1986
1551
  *
1987
- * Takes the referenced ids rather than reading the story itself: the caller already walked it,
1988
- * and a sweep that guessed at which controls exist would delete a payload on a mistake.
1552
+ * Cooperative rather than pre-emptive: long work calls `checkpoint()` at declared intervals, which
1553
+ * is what lets an operation unwind promptly without the engine having to interrupt it mid-mutation.
1989
1554
  */
1990
- declare function withoutOrphanCustomXmlNodes(pkg: OoxmlPackage, partName: string, referencedIds: ReadonlySet<string>): {
1991
- readonly pkg: OoxmlPackage;
1992
- readonly removed: readonly string[];
1993
- };
1555
+ interface CancellationToken {
1556
+ readonly isCancelled: boolean;
1557
+ readonly phase: CancellationPhase;
1558
+ /** True only when cancelled AND the commit is already published. */
1559
+ readonly derivedOnly: boolean;
1560
+ /** Throws CancellationError if cancelled; call at declared checkpoint intervals. */
1561
+ checkpoint(): void;
1562
+ }
1994
1563
  /**
1995
- * The `w:xpath` a binding uses to reach a node's label, or null when the id cannot be addressed.
1564
+ * The write side of cancellation, and the owner of the phase.
1996
1565
  *
1997
- * Word needs a prefix for the payload namespace even when the store declares it as a default —
1998
- * an unprefixed step in an XPath means "no namespace", so `/docxEditor/node` would match
1999
- * nothing in a namespaced store. The prefix is declared in `w:prefixMappings` beside it.
1566
+ * Whoever starts an operation holds this; everything it calls gets only the token.
2000
1567
  */
2001
- declare function customXmlLabelXPath(prefix: string, rootLocalName: string, nodeId: string): string | null;
2002
- /** The `w:prefixMappings` value declaring that prefix, or null when it cannot be written.
2003
- * The namespace sits inside single quotes inside a double-quoted attribute, so a namespace
2004
- * carrying either quote character has no representation here. */
2005
- declare function customXmlPrefixMappings(prefix: string, namespaceUri: string): string | null;
1568
+ declare class CancellationController {
1569
+ private _cancelled;
1570
+ private _phase;
1571
+ private _reason?;
1572
+ cancel(reason?: string): void;
1573
+ /** Mark canonical publication — the point of no return. */
1574
+ markPublished(): void;
1575
+ get isCancelled(): boolean;
1576
+ get phase(): CancellationPhase;
1577
+ get isPublished(): boolean;
1578
+ /** Cancelled after publication -> full rollback is no longer possible. */
1579
+ get derivedOnly(): boolean;
1580
+ get token(): CancellationToken;
1581
+ }
2006
1582
 
2007
- /** The prefix every binding this library authors declares and quotes. */
2008
- declare const CUSTOM_NODE_XPATH_PREFIX = "ns0";
2009
- /** The three attributes a `w:dataBinding` carries. */
2010
- interface CustomNodeBinding {
2011
- readonly prefixMappings: string;
2012
- readonly xpath: string;
2013
- readonly storeItemId: string;
1583
+ /** Injectable time source — the engine never calls Date.now directly (determinism). */
1584
+ interface ClockPort {
1585
+ now(): number;
1586
+ }
1587
+ /** Stable id minting for sessions, commits, and allocator seeds. */
1588
+ interface IdentityPort {
1589
+ newId(): string;
1590
+ }
1591
+ /** Cooperative scheduling of deferred work. */
1592
+ interface SchedulingPort {
1593
+ schedule(task: () => void): void;
1594
+ }
1595
+ /** Redacted observability sink (raw text never enters here — design D5). */
1596
+ interface AuditPort {
1597
+ record(entry: {
1598
+ readonly kind: string;
1599
+ readonly at: number;
1600
+ readonly meta?: Record<string, unknown>;
1601
+ }): void;
1602
+ }
1603
+ /** Read/write/export authorization decisions. */
1604
+ interface AuthorizationPort {
1605
+ authorize(action: string, subject?: string): boolean;
1606
+ }
1607
+ /** Explicit consent gate for any remote/external resource (no zero-click fetch). */
1608
+ interface ExternalResourceConsentPort {
1609
+ requestConsent(target: string): boolean;
1610
+ }
1611
+ /** Cancellation source for the current operation. */
1612
+ interface CancellationPort {
1613
+ readonly token: CancellationToken;
1614
+ }
1615
+ /** Where documents are stored and retrieved. Opaque marker until its milestone. */
1616
+ interface PersistencePort {
1617
+ readonly kind: 'persistence';
1618
+ }
1619
+ /** How the engine talks to a remote peer. Opaque marker until its milestone. */
1620
+ interface TransportPort {
1621
+ readonly kind: 'transport';
1622
+ }
1623
+ /** Where font bytes come from. Opaque marker until its milestone. */
1624
+ interface FontPort {
1625
+ readonly kind: 'font';
1626
+ }
1627
+ /** Which shaping backend measures text. Opaque marker until its milestone. */
1628
+ interface ShapingPort {
1629
+ readonly kind: 'shaping';
1630
+ }
1631
+ /** How image bytes are decoded. Opaque marker until its milestone. */
1632
+ interface ImagePort {
1633
+ readonly kind: 'image';
1634
+ }
1635
+ /** Where resource consumption is reported. Opaque marker until its milestone. */
1636
+ interface ResourceAccountingPort {
1637
+ readonly kind: 'resource-accounting';
2014
1638
  }
2015
1639
  /**
2016
- * The binding for one node in one store, or null when the id cannot be addressed by an XPath.
1640
+ * A required port the runtime did not provide.
2017
1641
  *
2018
- * Refuses rather than escapes: XPath 1.0 has no escape for a quote inside a literal, so an id
2019
- * carrying one could close the predicate and append an expression of the sender's choosing.
2020
- * The ids are minted by a host, so refusing is honest — see `ADDRESSABLE_ID`.
1642
+ * Thrown rather than falling back: silently reaching for a browser global when a worker or server
1643
+ * adapter did not supply a port is exactly the coupling ports exist to prevent.
2021
1644
  */
2022
- declare function customNodeBinding(part: CustomXmlDataPart, rootLocalName: string, nodeId: string): CustomNodeBinding | null;
1645
+ declare class PortResolutionError extends Error {
1646
+ readonly portId: string;
1647
+ constructor(portId: string);
1648
+ }
2023
1649
  /**
2024
- * Every node id the story's controls bind to in one store, in document order.
1650
+ * The environment-dependent services an engine instance may reach.
2025
1651
  *
2026
- * This is the input the orphan sweep takes: a node whose id is not in here is one no control
2027
- * names, whether it was deleted in this editor or in Word. Reading it from the STORY rather than
2028
- * from a host's bookkeeping is what makes the two cases one mechanism.
1652
+ * Everything outside pure computation — the clock, identity minting, scheduling, fonts, images —
1653
+ * is reached only through here, which is what lets browser, worker and server adapters supply
1654
+ * only what their runtime actually offers.
2029
1655
  */
2030
- declare function boundCustomXmlNodeIds(part: OoxmlPart, storeItemId: string): Set<string>;
1656
+ declare class PortRegistry {
1657
+ private readonly ports;
1658
+ provide(portId: string, port: unknown): this;
1659
+ has(portId: string): boolean;
1660
+ /** Resolve a port by id or throw. */
1661
+ resolve<T>(portId: string): T;
1662
+ /** Assert every id in `portIds` is present; returns the missing ones (empty if all present). */
1663
+ missing(portIds: readonly string[]): string[];
1664
+ /** The provided port ids (for bridging to registry.resolve availablePorts). */
1665
+ availablePorts(): string[];
1666
+ clock(): ClockPort;
1667
+ identity(): IdentityPort;
1668
+ }
1669
+ /** Deterministic clock: starts at `start` and advances by `step` each call. */
1670
+ declare class DeterministicClock implements ClockPort {
1671
+ private readonly step;
1672
+ private t;
1673
+ constructor(start?: number, step?: number);
1674
+ now(): number;
1675
+ }
1676
+ /** Sequential identity for tests and deterministic fixtures. */
1677
+ declare class SequentialIdentity implements IdentityPort {
1678
+ private readonly prefix;
1679
+ private n;
1680
+ constructor(prefix?: string);
1681
+ newId(): string;
1682
+ }
1683
+
1684
+ /** What one operation is started with. Only `ports` is required. */
1685
+ interface OperationInit {
1686
+ readonly ports: PortRegistry;
1687
+ readonly limits?: Partial<ResourceLimits>;
1688
+ readonly config?: Readonly<Record<string, unknown>>;
1689
+ /** Root budget capacity in abstract units (default: the byte decompression limit). */
1690
+ readonly capacity?: number;
1691
+ /** Operation identity (from IdentityPort in production); defaulted for tests. */
1692
+ readonly id?: string;
1693
+ }
2031
1694
  /**
2032
- * Every node id ANY story in the package binds, in one store.
1695
+ * The frozen environment of one operation: its limits, config, ports, root budget and
1696
+ * cancellation controller.
2033
1697
  *
2034
- * THE WHOLE PACKAGE, not one story. A payload is reachable from a header as easily as from the
2035
- * body — Word enumerates its data store from the main part, but nothing stops a control
2036
- * elsewhere quoting the same `w:storeItemID` — and the two callers that decide what is an orphan
2037
- * both destroy data when they are wrong. The sweep would collect a payload a header still paints;
2038
- * the export would strip a store a header still names, which is a document Word offers to repair.
1698
+ * IMMUTABLE for the operation's lifetime, which is what lets cache reuse and replica agreement
1699
+ * key on it. A new operation always gets a fresh snapshot rather than observing a mutated one.
1700
+ */
1701
+ interface OperationContext {
1702
+ readonly id: string;
1703
+ readonly limits: ResourceLimits;
1704
+ readonly config: Readonly<Record<string, unknown>>;
1705
+ readonly ports: PortRegistry;
1706
+ readonly budget: Budget;
1707
+ readonly cancellation: CancellationController;
1708
+ }
1709
+ /**
1710
+ * Begin an operation, capturing its immutable environment snapshot.
2039
1711
  *
2040
- * Costs one walk per story per store, on open and on export. Neither is a keystroke.
1712
+ * Resolves and freezes limits and configuration, carves the root budget, and creates the
1713
+ * cancellation controller — everything downstream work needs, fixed for the operation's duration.
2041
1714
  */
2042
- declare function boundCustomXmlNodeIdsInPackage(pkg: OoxmlPackage, storeItemId: string): Set<string>;
2043
- /** The node id one control binds to in the named store, or null when it binds to nothing there. */
2044
- declare function boundCustomXmlNodeIdOf(control: OoxmlNode, storeItemId: string): string | null;
1715
+ declare function beginOperation(init: OperationInit): OperationContext;
1716
+ /** Release the operation's root budget (requires every child/reservation released). */
1717
+ declare function endOperation(ctx: OperationContext): void;
2045
1718
 
2046
- /** What happens to one control when the document is exported. */
2047
- type CustomNodeExportPolicy = 'keep' | 'text' | 'remove';
2048
- /** How {@link withExportedCustomNodes} decides, and which stores it may tidy afterwards. */
2049
- interface CustomNodeExportRequest {
2050
- /** The story whose controls are policed, and whose relationships the stores hang off. */
2051
- readonly storyPartName: string;
2052
- /**
2053
- * Payload namespaces the caller CLAIMS.
2054
- *
2055
- * The store cleanup runs only over these. Word's own Cover Page Properties store rides in most
2056
- * templates, and an export that tidied every customXml part would be deleting from documents it
2057
- * was only asked to strip its own markup from.
2058
- */
2059
- readonly namespaces: readonly string[];
2060
- /** The fate of a control carrying this `w:tag`. A control with no tag is never touched. */
2061
- readonly decide: (tag: string) => CustomNodeExportPolicy;
1719
+ /** What a limit counts. Typed so a byte cap and a depth cap cannot be compared by accident. */
1720
+ type LimitUnit = 'bytes' | 'count' | 'depth' | 'ratio' | 'passes';
1721
+ /**
1722
+ * Where a limit is enforced.
1723
+ *
1724
+ * Declared per limit so enforcement happens at the boundary that can still refuse cheaply — a zip
1725
+ * cap checked during layout has already let the bomb decompress.
1726
+ */
1727
+ type EnforcementPhase = 'package-read' | 'xml-parse' | 'layout' | 'output';
1728
+ /** One limit's unit and enforcement phase — the metadata that makes limits testable uniformly. */
1729
+ interface LimitSpec {
1730
+ readonly unit: LimitUnit;
1731
+ readonly phase: EnforcementPhase;
2062
1732
  }
1733
+ /** Unit + enforcement phase for every resource limit. */
1734
+ declare const LIMIT_SPECS: Readonly<Record<keyof ResourceLimits, LimitSpec>>;
1735
+ /** Every limit name, for iterating the specs and asserting each has a unit and phase. */
1736
+ declare const LIMIT_KEYS: (keyof ResourceLimits)[];
1737
+ /** A phase-scoped overflow-safe counter for one limit. */
1738
+ declare function makeLimitCounter(limits: ResourceLimits, key: keyof ResourceLimits): BoundedCounter;
2063
1739
  /**
2064
- * The export, or the reason there is no export.
1740
+ * Deterministic memory substitute. Tracks current and peak "allocated" units
1741
+ * against a hard byte ceiling; `allocate` fails closed (LimitExceededError) past
1742
+ * the limit. Used in place of process RSS so memory-limit tests are reproducible
1743
+ * and cancellation/cleanup can be asserted without a real allocator.
1744
+ */
1745
+ declare class DeterministicMemoryMeter {
1746
+ private readonly counter;
1747
+ private current;
1748
+ private peak;
1749
+ constructor(limitBytes: number);
1750
+ allocate(bytes: number): void;
1751
+ free(bytes: number): void;
1752
+ get currentBytes(): number;
1753
+ get peakBytes(): number;
1754
+ /** Release everything (cancellation/cleanup path). */
1755
+ reset(): void;
1756
+ }
1757
+ /** Assert the finite-default / hard-ceiling invariant holds for every limit. */
1758
+ declare function assertLimitInvariants(): void;
1759
+
1760
+ /** Any JSON value. The domain canonicalization and stable hashing operate over. */
1761
+ type Json = null | boolean | number | string | Json[] | {
1762
+ [k: string]: Json;
1763
+ };
1764
+ /**
1765
+ * Produce a canonical string for `value`, dropping any object key whose name is
1766
+ * in `ephemera` at any depth. Numbers are emitted losslessly; -0 normalizes to 0;
1767
+ * non-finite numbers are rejected (they must never enter a comparator input).
1768
+ */
1769
+ declare function canonicalize(value: unknown, ephemera?: ReadonlySet<string>): string;
1770
+ /** 64-bit FNV-1a over the canonical form, returned as a 16-char hex string. */
1771
+ declare function stableHash(value: unknown, ephemera?: ReadonlySet<string>): string;
1772
+
1773
+ /**
1774
+ * How one artifact class is compared.
2065
1775
  *
2066
- * A refusal answers no package on purpose. "Stripping failed, here is the document anyway" is the
2067
- * one outcome that must not be possible: a caller would ship the markup it asked to remove and
2068
- * have been told the export succeeded.
1776
+ * Frozen per artifact: nothing here invents a tolerance for an artifact the spec requires to
1777
+ * match exactly.
2069
1778
  */
2070
- type CustomNodeExportResult = {
2071
- readonly ok: true;
2072
- readonly pkg: OoxmlPackage;
2073
- /** Controls unwrapped (`text`) and controls removed (`remove`). */
2074
- readonly unwrapped: number;
2075
- readonly removed: number;
1779
+ type ComparatorMode = 'canonical-exact' | 'exact' | 'tolerance' | 'sync-optimization-only';
1780
+ /** One artifact class's comparison mode and its declared ephemera — fields excluded from equality. */
1781
+ interface ComparatorDescriptor {
1782
+ readonly id: string;
1783
+ readonly mode: ComparatorMode;
1784
+ /** Object keys excluded from canonical-exact comparison (declared ephemera). */
1785
+ readonly ephemera: readonly string[];
1786
+ readonly note: string;
1787
+ }
1788
+ /** The frozen artifact comparator set. */
1789
+ declare const COMPARATORS: {
1790
+ readonly authoredState: {
1791
+ readonly id: "dev.docx-editor.core.comparator.authored-state";
1792
+ readonly mode: 'canonical-exact';
1793
+ readonly ephemera: readonly ["revision", "provenance", "producedAt", "commitId"];
1794
+ readonly note: 'canonical normalized authored records; ephemera excluded';
1795
+ };
1796
+ readonly anchor: {
1797
+ readonly id: "dev.docx-editor.core.comparator.anchor";
1798
+ readonly mode: 'exact';
1799
+ readonly ephemera: readonly [];
1800
+ readonly note: 'internal anchor identity/affinity compares exactly';
1801
+ };
1802
+ readonly yjsStateVector: {
1803
+ readonly id: "dev.docx-editor.core.comparator.yjs-state-vector";
1804
+ readonly mode: 'sync-optimization-only';
1805
+ readonly ephemera: readonly [];
1806
+ readonly note: 'exchange optimization only; never proves update or delete-set coverage';
1807
+ };
1808
+ readonly shapedRun: {
1809
+ readonly id: "dev.docx-editor.core.comparator.shaped-run";
1810
+ readonly mode: 'exact';
1811
+ readonly ephemera: readonly [];
1812
+ readonly note: 'glyph ids, clusters, and fixed-point advances compare exactly';
1813
+ };
1814
+ readonly paginationFingerprint: {
1815
+ readonly id: "dev.docx-editor.core.comparator.pagination-fingerprint";
1816
+ readonly mode: 'exact';
1817
+ readonly ephemera: readonly [];
1818
+ readonly note: 'page/column boundaries, break causes, fixed-point geometry compare exactly';
1819
+ };
1820
+ readonly semanticTree: {
1821
+ readonly id: "dev.docx-editor.core.comparator.semantic-tree";
1822
+ readonly mode: 'exact';
1823
+ readonly ephemera: readonly [];
1824
+ readonly note: 'reading order, roles, headings, alt text compare exactly';
1825
+ };
1826
+ readonly hitTest: {
1827
+ readonly id: "dev.docx-editor.core.comparator.hit-test";
1828
+ readonly mode: 'exact';
1829
+ readonly ephemera: readonly [];
1830
+ readonly note: 'resolved hit target and cluster affinity compare exactly';
1831
+ };
1832
+ readonly pdfSemantics: {
1833
+ readonly id: "dev.docx-editor.core.comparator.pdf-semantics";
1834
+ readonly mode: 'canonical-exact';
1835
+ readonly ephemera: readonly ["objectNumber", "producer", "creationDate", "modDate", "subsetTag"];
1836
+ readonly note: 'canonical semantic PDF objects; container ephemera excluded';
1837
+ };
1838
+ readonly rasterCheckpoint: {
1839
+ readonly id: "dev.docx-editor.core.comparator.raster-checkpoint";
1840
+ readonly mode: 'tolerance';
1841
+ readonly ephemera: readonly [];
1842
+ readonly note: 'documented unavoidable raster comparison; explicit tolerance only';
1843
+ };
1844
+ readonly benchmarkEvidence: {
1845
+ readonly id: "dev.docx-editor.core.comparator.benchmark-evidence";
1846
+ readonly mode: 'sync-optimization-only';
1847
+ readonly ephemera: readonly [];
1848
+ readonly note: 'diagnostic evidence, not an equivalence basis';
1849
+ };
1850
+ };
1851
+ /** Which frozen comparator to use. */
1852
+ type ComparatorName = keyof typeof COMPARATORS;
1853
+ /** Whether two artifacts matched, and where they diverged when they did not. */
1854
+ interface ComparisonResult {
1855
+ readonly equal: boolean;
1856
+ /** Canonical forms when unequal (diagnostic). */
1857
+ readonly left?: string;
1858
+ readonly right?: string;
1859
+ }
1860
+ /**
1861
+ * Compare two artifacts under a named comparator. `canonical-exact` and `exact`
1862
+ * compare canonical forms (exact drops no ephemera). `tolerance` requires an
1863
+ * epsilon and compares finite numbers structurally. `sync-optimization-only`
1864
+ * throws — such artifacts are never an equivalence basis.
1865
+ */
1866
+ declare function compareArtifacts(name: ComparatorName, left: unknown, right: unknown, opts?: {
1867
+ epsilon?: number;
1868
+ }): ComparisonResult;
1869
+ /** Fingerprint an artifact under a named comparator's canonicalization policy. */
1870
+ declare function fingerprint(name: ComparatorName, value: unknown): string;
1871
+
1872
+ /** Whether a recorded conformance step was expected to commit or be refused. */
1873
+ type FixtureOutcome = 'applied' | 'aborted' | 'validation' | 'conflict' | 'resource' | 'authorization';
1874
+ /** The change one step produced, summarized to what a fixture can compare across runtimes. */
1875
+ interface ModelChangeSummary {
1876
+ readonly fromRevision: number;
1877
+ readonly toRevision: number;
1878
+ readonly origin: string;
1879
+ readonly dirty: readonly string[];
1880
+ readonly dependencyKeys: readonly string[];
1881
+ }
1882
+ /** Where anchors sat after a step — how a fixture proves positions survived an edit. */
1883
+ interface AnchorSnapshot {
1884
+ readonly anchorId: string;
1885
+ readonly story: string;
1886
+ readonly block: string;
1887
+ readonly affinity: 'before' | 'after';
1888
+ }
1889
+ /** What one step must produce: its outcome, its change summary, and its authored-state hash. */
1890
+ interface FixtureExpectation {
1891
+ readonly outcome: FixtureOutcome;
1892
+ /** Present iff outcome === 'applied'; MUST be > baseRevision. */
1893
+ readonly committedRevision?: number;
1894
+ readonly modelChange?: ModelChangeSummary;
1895
+ /** 16-hex authored-state fingerprint (comparator 0.4). */
1896
+ readonly authoredStateHash?: string;
1897
+ readonly outputHash?: string;
1898
+ readonly anchors?: readonly AnchorSnapshot[];
1899
+ }
1900
+ /** One recorded operation and what it was expected to do. */
1901
+ interface FixtureStep {
1902
+ readonly baseRevision: number;
1903
+ readonly origin: string;
1904
+ /** Opaque DocOp payloads (schema owned by section 4). */
1905
+ readonly ops: readonly unknown[];
1906
+ readonly expect: FixtureExpectation;
1907
+ }
1908
+ /** Opaque encoded backend bytes (snapshot or replication update). */
1909
+ interface EncodedEnvelope {
1910
+ readonly kind: 'snapshot' | 'update';
1911
+ readonly protocolVersion: number;
1912
+ readonly schemaVersion: number;
1913
+ readonly documentId: string;
1914
+ readonly byteLength: number;
1915
+ /** Hex-encoded opaque bytes; length MUST equal byteLength. */
1916
+ readonly bytesHex: string;
1917
+ }
1918
+ /** Which implementation recorded a fixture — local store, Yjs, or a binding. */
1919
+ type FixtureSource = {
1920
+ readonly kind: 'create';
2076
1921
  } | {
2077
- readonly ok: false;
2078
- readonly reason: string;
1922
+ readonly kind: 'docx';
1923
+ readonly sha256: string;
1924
+ readonly bytesRef: string;
2079
1925
  };
2080
1926
  /**
2081
- * Apply the policy, then take the payloads and the stores the policy orphaned.
1927
+ * The frozen conformance container: revisions, origins, operations, changes, snapshots and
1928
+ * hashes.
2082
1929
  *
2083
- * Order matters and is the reverse of the write's. The BODY goes first, so the sweep that follows
2084
- * sees the controls that actually survive; the stores go last, once nothing binds them. Doing it
2085
- * the other way would strip a store while a control still quoted its `w:storeItemID`, which is a
2086
- * document Word opens and offers to repair.
1930
+ * The CONTAINER is what is frozen — field names, origin membership, revision monotonicity, hash
1931
+ * format. The op and change payloads travel opaquely, so their schemas can evolve without
1932
+ * invalidating every recorded fixture.
2087
1933
  */
2088
- declare function withExportedCustomNodes(pkg: OoxmlPackage, request: CustomNodeExportRequest): CustomNodeExportResult;
1934
+ interface ConformanceFixture {
1935
+ readonly formatVersion: 1;
1936
+ readonly documentId: string;
1937
+ readonly source: FixtureSource;
1938
+ readonly steps: readonly FixtureStep[];
1939
+ readonly snapshots?: readonly EncodedEnvelope[];
1940
+ readonly updates?: readonly EncodedEnvelope[];
1941
+ }
1942
+ /** Whether a fixture is well-formed, listing every structural violation. */
1943
+ interface ValidationResult {
1944
+ readonly valid: boolean;
1945
+ readonly errors: readonly string[];
1946
+ }
1947
+ /** Structurally validate a fixture against the frozen format rules. */
1948
+ declare function validateFixture(fixture: ConformanceFixture): ValidationResult;
1949
+
1950
+ /** The outcome a store reports for one replayed step. */
1951
+ interface ReplayOutcome {
1952
+ readonly outcome: FixtureOutcome;
1953
+ readonly committedRevision?: number;
1954
+ /** Canonical authored-state value AFTER the step (hashed via comparator 0.4). */
1955
+ readonly authoredState?: unknown;
1956
+ }
1957
+ /** The interface a conformance runtime implements so one fixture can drive every backend. */
1958
+ interface ReplayStore {
1959
+ /** Initialize from the fixture source; return the initial revision (0 for create). */
1960
+ init(fixture: ConformanceFixture): number;
1961
+ /** Apply one step and report what happened. */
1962
+ applyStep(step: FixtureStep): ReplayOutcome;
1963
+ }
1964
+ /** What replaying a fixture produced: per-step outcomes and where they diverged. */
1965
+ interface ReplayReport {
1966
+ readonly ok: boolean;
1967
+ readonly mismatches: readonly string[];
1968
+ }
1969
+ /**
1970
+ * Replay a fixture against a store and check every step's outcome, committed
1971
+ * revision, and authored-state fingerprint against the fixture's expectations.
1972
+ */
1973
+ declare function replayFixture(fixture: ConformanceFixture, store: ReplayStore): ReplayReport;
1974
+ /** Hash a store's authored state, so two runtimes replaying one fixture can be compared. */
1975
+ declare function hashAuthored(authoredState: unknown): string;
2089
1976
 
2090
1977
  /**
2091
1978
  * WHERE a copy reaches, computed by the editing surface against the published layout with
@@ -2484,6 +2371,8 @@ interface RevisionSite {
2484
2371
  readonly parent: OoxmlElement | null;
2485
2372
  /** True when this site cannot be resolved and the whole op must refuse. */
2486
2373
  readonly refused: boolean;
2374
+ /** Why, when `refused` is true. */
2375
+ readonly refusal?: RevisionSiteRefusal;
2487
2376
  /** True for `w:pPr/w:rPr/w:ins|w:del` — the paragraph MARK, not content. */
2488
2377
  readonly paragraphMark: boolean;
2489
2378
  /** True for a supported property-history wrapper. */
@@ -2702,5 +2591,5 @@ declare function sectionProtectsForms(part: OoxmlPart, nodeId: string): boolean;
2702
2591
  /** Every {@link TreeDocOpKind}, for validation and exhaustiveness checks. */
2703
2592
  declare const TREE_DOC_OP_KINDS: readonly ["replaceStoryBlocks", "insertText", "deleteText", "setParagraphMarkRevision", "proposeParagraphMerge", "insertCommentMarker", "acceptRevision", "rejectRevision", "acceptAllRevisions", "rejectAllRevisions", "setRevisionAttribution", "insertTab", "insertHardBreak", "insertPageBreak", "insertPageField", "setFieldCode", "setListLevel", "setListNumbering", "setParagraphTabStops", "setParagraphMarkProperties", "splitParagraph", "splitParagraphMany", "joinParagraphs", "setRunProperties", "setParagraphProperties", "setSectionProperties", "setSectionMark", "insertHyperlink", "setHyperlinkTarget", "removeHyperlink", "setMathEquation", "removeMathEquation", "setContentControlValue", "removeContentControl", "insertInlineContentControl", "addRepeatingSectionItem", "removeRepeatingSectionItem", "deleteBlock", "insertTable", "insertTableRow", "deleteTableRow", "insertTableColumn", "deleteTableColumn", "setTableColumnWidths", "setTableRightEdgeWidth", "setTableRowHeight", "setTableProperties", "authorTable", "setTableCellBorders", "setTableCellFill", "setTableCellVerticalAlignment", "createHeaderFooter", "deleteHeaderFooter", "linkToPrevious", "unlinkFromPrevious", "setSectionFurnitureOptions", "setDocumentProtection", "insertNote", "deleteNote", "convertNote", "convertAllNotes", "setNoteProperties", "setContentControlProperties", "insertContentControl", "insertFragment", "insertDrawing", "replaceDrawingResource", "deleteDrawing", "resizeDrawing", "cropDrawing", "positionDrawing", "setDrawingWrap", "setDrawingMetadata", "setDrawingLocks", "transformDrawing", "insertToc", "replaceTocResult", "rewriteTocPageNumbers", "refreshFieldResults", "setTextFormFieldDefault", "commitTextFormField", "setLegacyCheckbox", "setLegacyDropdown", "insertBuildingBlock"];
2704
2593
 
2705
- export { ALL_FROZEN_IDS, AUTHORABLE_PARAGRAPH_PROPERTIES, AUTHORABLE_RUN_PROPERTIES, BoundedCounter, Budget, BudgetError, CANONICAL_MUTATION_ORIGINS, COMPARATORS, CUSTOM_NODE_XPATH_PREFIX, CUSTOM_XML_PROPS_REL, CUSTOM_XML_PROPS_TYPE, CUSTOM_XML_REL, CancellationController, CancellationError, CommentRecord, CommentThreadState, CustomNodeWriteResult, DANGEROUS_KEYS, DATASTORE_NAMESPACE_URI, DEFAULT_FORMATTING_DISPLAY_MODE, DEFAULT_VIEW_SETTINGS, DEPENDENCY_KEY_IDS, DangerousKeyError, DeterministicClock, DeterministicMemoryMeter, DrawingTreeDocOp, FIELD_ATOM_CHAR, FieldResultsMode, ID_KINDS, INERT_EXECUTABLE_KINDS, ImageWrapTarget, ImpactClass, InsertCustomNodeWrite, LIMIT_KEYS, LIMIT_SPECS, LimitExceededError, MAX_STORY_SDT_NESTING, NON_CANONICAL_ORIGINS, ORIGIN_IDS, OmmlEquationProjection, OoxmlAttribute, OoxmlElement, OoxmlFldCharNode, OoxmlFldSimpleNode, OoxmlGenericElementNode, OoxmlHardBreakNode, OoxmlInstrTextNode, OoxmlInvariantIssue, OoxmlInvariantResult, OoxmlNode, OoxmlPackage, OoxmlParagraphNode, OoxmlPart, OoxmlProperty, PAGE_BREAK_CHAR, PortRegistry, PortResolutionError, PrefixAllocator, RESULT_IDS, RUNTIME_PORT_IDS, RegistryError, RelationshipRecord, ResourceLimits, ReviewCommentItem, ReviewItem, ReviewModelInput, ReviewPosition, ReviewRange, ReviewRevisionItem, SEARCH_MATCH_LIMIT, SEARCH_QUERY_MAX, SequentialIdentity, StoryScope, TOC_LEVEL_INDENT_TWIPS, TOC_MAX_BOOKMARKS_PER_REFRESH, TOC_MAX_ENTRIES, TOC_MAX_FIELD_NESTING, TOC_MAX_INSTRUCTION_CHARS, TOC_MAX_PAGE_PASSES, TREE_DOC_OP_KINDS, TWIPS_PER_POINT, TreeDocOp, TreeDocumentStore, TreeModelChange, TreeOpRejection, TreeOpResult, TreePackageStore, addComment, addPackageComment, applyEdits, applyTreeOp, assertLimitInvariants, assertValidId, assertValidQName, atomicFieldSpansOf, authoredProperties, beginOperation, bodyStoryRoot, bookmarkPairNodes, boundCustomXmlNodeIdOf, boundCustomXmlNodeIds, boundCustomXmlNodeIdsInPackage, buildTocContentControl, buildTocEntryParagraph, buildingBlockGalleryOf, buildingBlocksForControl, buildingBlocksOf, canonicalOoxmlFingerprint, canonicalize, cascadeEmptiedComments, collectNodeIds, collectReviewItems, collectRevisionSites, collectStoryParagraphs, commentItemsOf, commentPartNameOf, commentsExtendedPartNameOf, compareArtifacts, compareSemVer, containsCssFetch, contentTypesPartBytes, createNodeIdAllocator, customNodeBinding, customXmlDataParts, customXmlLabelXPath, customXmlNodes, customXmlPrefixMappings, datastoreItemIdFor, deleteCommentThread, deletePackageComments, deriveOoxmlIndexes, detectBodyTocs, diffSemanticDigests, digestPart, directParagraphMarkProperties, directParagraphProperties, displayMathAlignment, drawingOpImpact, endOperation, equationsOfAtom, escapeCssString, escapeXml, extractFragmentPackage, fieldAtomText, fieldOnOffAttribute, findCustomXmlDataPart, findDetectedToc, findNode, findOccurrences, fingerprint, fldCharType, fldSimpleInstr, fnv1a32, foldCase, formatOwnedRunIds, formattableRanges, formsProtectionEnabled, glossaryPartOf, hardBreakAttributes, hardBreakKind, hardBreakText, hasCommentPart, hasLegacyFormFieldData, hasNode, hashAuthored, indexStyles, inlineControlEndingAt, inlineControlStartingAt, insertChildren, insertPackageCustomNode, instrTextValue, isAuthorableRunProperty, isDangerousKey, isDrawingTreeDocOp, isEvaluableField, isFieldChrome, isFldChar, isFldCharNode, isFldSimple, isFldSimpleNode, isInertExecutable, isInstrText, isInstrTextNode, isLegalFldCharType, isOmmlDisplay, isOmmlEquationAtom, isPageBreakNode, isSearchableQuery, isStoryPart, isValidId, isValidNCName, isValidParaId, isValidQName, isWholeWord, linkRevisionReplies, locateSites, makeLimitCounter, materializeGlossaryPlaceholders, mergeFragmentIntoPackage, mergedFontProperty, mergedMultiSettingProperty, mergedParagraphMarkProperties, mergedProperties, mintParaId, mintedParagraphIdentityAttributes, nextCommentId, normalizeParagraphIdentity, nullRecord, ooxmlTreesEqual, paraIdOf, paragraphOffsetIndex, paragraphTextOf, parentNodeOf, parseSemVer, parseTocInstruction, planTocEntries, points, pointsToTwips, projectOmmlAtom, projectOmmlDisplay, propertyContainer, readCustomXmlNode, readTwipsMeasure, readViewSettings, relationshipsOf, relsPartNameFor, removeNode, removePackageCustomNode, replaceChildren, replaceNode, replayFixture, resolve, resolveContentTypeOf, resolveTocRowHeadings, revisionItemsOf, runAddressRanges, runPropertyEdits, runsCovering, sanitizeHref, satisfies, scrubExport, sectionProtectsForms, segmentsOf, semanticDigest, serializeOoxmlPart, setCommentResolved, setPackageCommentResolved, stableHash, storyParagraphs, storyRootsOf, stylesPartOf, textboxStoriesInPart, toSafeRecord, tocEntryText, tocLeftIndentTwips, twips, twipsToPoints, usedParaIds, validateDrawingOp, validateFixture, validateOoxmlPart, validatePackageInvariants, validateTreeOp, w14RootPrefix, withContentTypeOverride, withCustomXmlDataPart, withCustomXmlNode, withExportedCustomNodes, withNewPart, withRelationship, withoutCustomXmlDataPart, withoutCustomXmlNode, withoutOrphanCustomXmlNodes, wrapTargetToAnchorSpec };
2706
- export type { AddCommentRequest, AddCommentResult, AnchorSnapshot, AtomicFieldSpan, AuditPort, AuthorizationPort, BuildingBlock, BuildingBlockGalleryFilter, CancellationPhase, CancellationPort, CancellationToken, CapabilityId, ClockPort, CommentAnchorRequest, CommentDeletionOwner, ComparatorDescriptor, ComparatorMode, ComparatorName, ComparisonResult, ConformanceFixture, ContentItem, Contribution, CustomNodeBinding, CustomNodeExportPolicy, CustomNodeExportRequest, CustomNodeExportResult, CustomXmlDataPart, CustomXmlDataPartResult, CustomXmlNode, DetectedToc, DigestDifference, DocumentViewSettings, EditOptions, EncodedEnvelope, EnforcementPhase, ExternalResourceConsentPort, FeatureBundle, FixtureExpectation, FixtureOutcome, FixtureSource, FixtureStep, FldCharType, FontPort, FormattingDisplayMode, FormattingRevisionAuthorFilter, FragmentCoverage, FragmentExtractRejection, FragmentExtractResult, FragmentMergeRejection, FragmentMergeResult, HardBreakKind, HrefProjection, IdKind, IdentityPort, ImagePort, InertExecutableKind, InlineControlSpan, Json, LimitSpec, LimitUnit, LinkableReviewItem, ModelChangeSummary, OffsetSpan, OoxmlEditResult, OoxmlIndexes, OoxmlStoryKind, OoxmlStoryRoot, OperationContext, OperationInit, PackageCommentDelete, PackageInvariantCode, PackageInvariantIssue, PackageInvariantResult, ParagraphDigest, ParagraphIndexEntry, ParagraphOffsetIndex, PersistencePort, Points, RegistryErrorCode, ReplacementPolicy, ReplayOutcome, ReplayReport, ReplayStore, Reservation, ResolveOptions, ResolvedRegistry, ResourceAccountingPort, RunPropertyEdit, SchedulingPort, ScrubResult, Segment, SemVer, SemanticDigest, SetCommentResolvedResult, ShapingPort, StoryDigest, StoryIndexEntry, StyleIndexEntry, TextMatchOptions, TextOccurrence, TextOccurrences, TextboxStoryRoot, TocEntryPlan, TocInstruction, TocOutlineHeading, TransactionRevisionIds, TransportPort, Twips, ValidationResult };
2594
+ export { ALL_FROZEN_IDS, AUTHORABLE_PARAGRAPH_PROPERTIES, AUTHORABLE_RUN_PROPERTIES, BoundedCounter, Budget, BudgetError, CANONICAL_MUTATION_ORIGINS, COMPARATORS, CUSTOM_NODE_XPATH_PREFIX, CUSTOM_XML_PROPS_REL, CUSTOM_XML_PROPS_TYPE, CUSTOM_XML_REL, CancellationController, CancellationError, CommentRecord, CommentThreadState, CustomNodeWriteResult, DANGEROUS_KEYS, DATASTORE_NAMESPACE_URI, DEFAULT_FORMATTING_DISPLAY_MODE, DEFAULT_VIEW_SETTINGS, DEPENDENCY_KEY_IDS, DangerousKeyError, DeterministicClock, DeterministicMemoryMeter, DrawingTreeDocOp, EditOptions, FIELD_ATOM_CHAR, FieldResultsMode, ID_KINDS, INERT_EXECUTABLE_KINDS, ImageWrapTarget, ImpactClass, InsertCustomNodeWrite, LIMIT_KEYS, LIMIT_SPECS, LimitExceededError, MAX_STORY_SDT_NESTING, NON_CANONICAL_ORIGINS, ORIGIN_IDS, OmmlEquationProjection, OoxmlAttribute, OoxmlElement, OoxmlFldCharNode, OoxmlFldSimpleNode, OoxmlGenericElementNode, OoxmlHardBreakNode, OoxmlInstrTextNode, OoxmlInvariantResult, OoxmlNode, OoxmlPackage, OoxmlParagraphNode, OoxmlPart, OoxmlProperty, PAGE_BREAK_CHAR, PortRegistry, PortResolutionError, PrefixAllocator, RESULT_IDS, RUNTIME_PORT_IDS, RegistryError, RelationshipRecord, ResourceLimits, ReviewCommentItem, ReviewItem, ReviewModelInput, ReviewPosition, ReviewRange, ReviewRevisionItem, RevisionSiteRefusal, SEARCH_MATCH_LIMIT, SEARCH_QUERY_MAX, SequentialIdentity, StoryScope, TOC_LEVEL_INDENT_TWIPS, TOC_MAX_BOOKMARKS_PER_REFRESH, TOC_MAX_ENTRIES, TOC_MAX_FIELD_NESTING, TOC_MAX_INSTRUCTION_CHARS, TOC_MAX_PAGE_PASSES, TREE_DOC_OP_KINDS, TWIPS_PER_POINT, TreeDocOp, TreeDocumentStore, TreeModelChange, TreeOpRejection, TreeOpResult, TreePackageStore, addComment, addPackageComment, applyTreeOp, assertLimitInvariants, assertValidId, assertValidQName, atomicFieldSpansOf, authoredProperties, beginOperation, bodyStoryRoot, bookmarkPairNodes, boundCustomXmlNodeIdOf, boundCustomXmlNodeIds, boundCustomXmlNodeIdsInPackage, buildTocContentControl, buildTocEntryParagraph, buildingBlockGalleryOf, buildingBlocksForControl, buildingBlocksOf, canonicalOoxmlFingerprint, canonicalize, cascadeEmptiedComments, collectReviewItems, collectRevisionSites, collectStoryParagraphs, commentItemsOf, commentPartNameOf, commentsExtendedPartNameOf, compareArtifacts, compareSemVer, containsCssFetch, contentTypesPartBytes, customNodeBinding, customXmlDataParts, customXmlLabelXPath, customXmlNodes, customXmlPrefixMappings, datastoreItemIdFor, deleteCommentThread, deletePackageComments, deriveOoxmlIndexes, detectBodyTocs, diffSemanticDigests, digestPart, directParagraphMarkProperties, directParagraphProperties, displayMathAlignment, drawingOpImpact, endOperation, equationsOfAtom, escapeCssString, escapeXml, extractFragmentPackage, fieldAtomText, fieldOnOffAttribute, findCustomXmlDataPart, findDetectedToc, findOccurrences, fingerprint, fldCharType, fldSimpleInstr, fnv1a32, foldCase, formatOwnedRunIds, formattableRanges, formsProtectionEnabled, glossaryPartOf, hardBreakAttributes, hardBreakKind, hardBreakText, hasCommentPart, hasLegacyFormFieldData, hashAuthored, indexStyles, inlineControlEndingAt, inlineControlStartingAt, insertPackageCustomNode, instrTextValue, isAuthorableRunProperty, isDangerousKey, isDrawingTreeDocOp, isEvaluableField, isFieldChrome, isFldChar, isFldCharNode, isFldSimple, isFldSimpleNode, isInertExecutable, isInstrText, isInstrTextNode, isLegalFldCharType, isOmmlDisplay, isOmmlEquationAtom, isPageBreakNode, isSearchableQuery, isStoryPart, isValidId, isValidNCName, isValidParaId, isValidQName, isWholeWord, linkRevisionReplies, locateSites, makeLimitCounter, materializeGlossaryPlaceholders, mergeFragmentIntoPackage, mergedFontProperty, mergedMultiSettingProperty, mergedParagraphMarkProperties, mergedProperties, mintParaId, mintedParagraphIdentityAttributes, nextCommentId, normalizeParagraphIdentity, nullRecord, ooxmlTreesEqual, paraIdOf, paragraphOffsetIndex, paragraphTextOf, parseSemVer, parseTocInstruction, planTocEntries, points, pointsToTwips, projectOmmlAtom, projectOmmlDisplay, propertyContainer, readCustomXmlNode, readTwipsMeasure, readViewSettings, relationshipsOf, relsPartNameFor, removePackageCustomNode, replayFixture, resolve, resolveContentTypeOf, resolveTocRowHeadings, revisionItemsOf, runAddressRanges, runPropertyEdits, runsCovering, sanitizeHref, satisfies, scrubExport, sectionProtectsForms, segmentsOf, semanticDigest, serializeOoxmlPart, setCommentResolved, setPackageCommentResolved, stableHash, storyParagraphs, storyRootsOf, stylesPartOf, textboxStoriesInPart, toSafeRecord, tocEntryText, tocLeftIndentTwips, twips, twipsToPoints, usedParaIds, validateDrawingOp, validateFixture, validateOoxmlPart, validatePackageInvariants, validateTreeOp, w14RootPrefix, withContentTypeOverride, withCustomXmlDataPart, withCustomXmlNode, withExportedCustomNodes, withNewPart, withRelationship, withoutCustomXmlDataPart, withoutCustomXmlNode, withoutOrphanCustomXmlNodes, wrapTargetToAnchorSpec };
2595
+ export type { AddCommentRequest, AddCommentResult, AnchorSnapshot, AtomicFieldSpan, AuditPort, AuthorizationPort, BuildingBlock, BuildingBlockGalleryFilter, CancellationPhase, CancellationPort, CancellationToken, CapabilityId, ClockPort, CommentAnchorRequest, CommentDeletionOwner, ComparatorDescriptor, ComparatorMode, ComparatorName, ComparisonResult, ConformanceFixture, ContentItem, Contribution, CustomNodeBinding, CustomNodeExportPolicy, CustomNodeExportRequest, CustomNodeExportResult, CustomXmlDataPart, CustomXmlDataPartResult, CustomXmlNode, DetectedToc, DigestDifference, DocumentViewSettings, EncodedEnvelope, EnforcementPhase, ExternalResourceConsentPort, FeatureBundle, FixtureExpectation, FixtureOutcome, FixtureSource, FixtureStep, FldCharType, FontPort, FormattingDisplayMode, FormattingRevisionAuthorFilter, FragmentCoverage, FragmentExtractRejection, FragmentExtractResult, FragmentMergeRejection, FragmentMergeResult, HardBreakKind, HrefProjection, IdKind, IdentityPort, ImagePort, InertExecutableKind, InlineControlSpan, Json, LimitSpec, LimitUnit, LinkableReviewItem, ModelChangeSummary, OffsetSpan, OoxmlIndexes, OoxmlStoryKind, OoxmlStoryRoot, OperationContext, OperationInit, PackageCommentDelete, PackageInvariantCode, PackageInvariantIssue, PackageInvariantResult, ParagraphDigest, ParagraphIndexEntry, ParagraphOffsetIndex, PersistencePort, Points, RegistryErrorCode, ReplacementPolicy, ReplayOutcome, ReplayReport, ReplayStore, Reservation, ResolveOptions, ResolvedRegistry, ResourceAccountingPort, RunPropertyEdit, SchedulingPort, ScrubResult, Segment, SemVer, SemanticDigest, SetCommentResolvedResult, ShapingPort, StoryDigest, StoryIndexEntry, StyleIndexEntry, TextMatchOptions, TextOccurrence, TextOccurrences, TextboxStoryRoot, TocEntryPlan, TocInstruction, TocOutlineHeading, TransportPort, Twips, ValidationResult };