@stll/folio-core 0.72.0 → 0.74.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 (244) hide show
  1. package/README.md +12 -6
  2. package/dist/ai-edits/applyTypes.d.ts +85 -0
  3. package/dist/ai-edits/applyTypes.js +24 -0
  4. package/dist/ai-edits/clean-text.d.ts +7 -1
  5. package/dist/ai-edits/clean-text.js +23 -2
  6. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  7. package/dist/ai-edits/headless.d.ts +29 -147
  8. package/dist/ai-edits/headless.js +215 -1639
  9. package/dist/ai-edits/index.d.ts +3 -3
  10. package/dist/ai-edits/index.js +2 -3
  11. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  12. package/dist/ai-edits/pending-suggestions.js +183 -90
  13. package/dist/ai-edits/pendingJoin.js +6 -1
  14. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  15. package/dist/ai-edits/snapshot.js +9 -4
  16. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  17. package/dist/ai-edits/table-cell-mutations.js +2 -2
  18. package/dist/ai-edits/table-geometry.d.ts +1 -1
  19. package/dist/ai-edits/table-geometry.js +1 -1
  20. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  21. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  22. package/dist/ai-edits/tableNodes.d.ts +38 -0
  23. package/dist/ai-edits/tableNodes.js +86 -0
  24. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  25. package/dist/ai-edits/tracked-batch-fidelity.js +1 -1
  26. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  27. package/dist/canonical/batchCommentReferences.js +1 -0
  28. package/dist/canonical/canonicalInlineGaps.d.ts +56 -0
  29. package/dist/canonical/canonicalInlineGaps.js +118 -0
  30. package/dist/canonical/canonicalInlineProjection.d.ts +4 -13
  31. package/dist/canonical/canonicalInlineProjection.js +5 -27
  32. package/dist/canonical/canonicalProjectionBlocks.d.ts +4 -4
  33. package/dist/canonical/canonicalPublicOperations.js +282 -75
  34. package/dist/canonical/canonicalSelection.js +1 -1
  35. package/dist/canonical/canonicalSession.d.ts +9 -1
  36. package/dist/canonical/canonicalSession.js +106 -33
  37. package/dist/compare/compare.d.ts +1 -1
  38. package/dist/compare/inline-atoms-model.d.ts +1 -1
  39. package/dist/compare/inline-atoms.d.ts +2 -2
  40. package/dist/compare/inline-provenance-model.d.ts +1 -1
  41. package/dist/compare/inline-provenance.d.ts +2 -2
  42. package/dist/compat/eigenpal.d.ts +3 -3
  43. package/dist/compat/eigenpal.js +2 -3
  44. package/dist/controller/autocompleteSuggestion.js +1 -1
  45. package/dist/controller/canonicalClipboard.d.ts +13 -3
  46. package/dist/controller/canonicalClipboard.js +186 -50
  47. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  48. package/dist/controller/canonicalClipboardResources.js +22 -2
  49. package/dist/controller/canonicalComposition.js +1 -1
  50. package/dist/controller/canonicalInput.js +1 -1
  51. package/dist/controller/canonicalPresence.js +1 -1
  52. package/dist/controller/canonicalReview.d.ts +1 -1
  53. package/dist/controller/canonicalReview.js +1 -1
  54. package/dist/controller/canonicalRoomAuthority.js +1 -1
  55. package/dist/controller/canonicalRoomWire.js +1 -1
  56. package/dist/controller/canonicalStructure.js +1 -1
  57. package/dist/controller/canonicalTabRoom.js +1 -1
  58. package/dist/controller/canonicalWatermark.d.ts +10 -0
  59. package/dist/controller/canonicalWatermark.js +37 -0
  60. package/dist/controller/canonicalYjsRoom.js +1 -1
  61. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  62. package/dist/controller/hiddenEditorApi.js +2 -17
  63. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  64. package/dist/controller/hiddenEditorManager.js +79 -23
  65. package/dist/document-operations.d.ts +1 -14
  66. package/dist/document-operations.js +1 -278
  67. package/dist/docx/canonicalSave.d.ts +1 -1
  68. package/dist/docx/canonicalSave.js +1 -1
  69. package/dist/docx/canonicalSessionInput.js +1 -1
  70. package/dist/docx/containerChildren.js +1 -1
  71. package/dist/docx/createDocx.d.ts +4 -0
  72. package/dist/docx/createDocx.js +6 -0
  73. package/dist/docx/paragraphParser.js +2 -2
  74. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  75. package/dist/docx/parser.js +1 -1
  76. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  77. package/dist/docx/reviewResolutionProvenance.js +31 -8
  78. package/dist/docx/revisionIdNormalization.js +30 -7
  79. package/dist/docx/rezip.d.ts +1 -1
  80. package/dist/docx/rezip.js +1 -1
  81. package/dist/docx/serializer/tableSerializer.js +4 -36
  82. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  83. package/dist/docx/server/templatePlan/apply.js +658 -0
  84. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  85. package/dist/docx/server/templatePlan/blocks.js +355 -0
  86. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  87. package/dist/docx/server/templatePlan/builders.js +237 -0
  88. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  89. package/dist/docx/server/templatePlan/emit.js +466 -0
  90. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  91. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  92. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  93. package/dist/docx/server/templatePlan/inspect.js +230 -0
  94. package/dist/docx/server/templatePlan/labels.d.ts +45 -0
  95. package/dist/docx/server/templatePlan/labels.js +155 -0
  96. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  97. package/dist/docx/server/templatePlan/package.js +99 -0
  98. package/dist/docx/server/templatePlan/plan.d.ts +145 -0
  99. package/dist/docx/server/templatePlan/plan.js +875 -0
  100. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  101. package/dist/docx/server/templatePlan/planShape.js +180 -0
  102. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  103. package/dist/docx/server/templatePlan/resources.js +136 -0
  104. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  105. package/dist/docx/server/templatePlan/story.js +440 -0
  106. package/dist/docx/server/templatePlan/types.d.ts +442 -0
  107. package/dist/docx/server/templatePlan/types.js +29 -0
  108. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  109. package/dist/docx/server/templatePlan/verify.js +976 -0
  110. package/dist/docx/server/templatePlan/xml.d.ts +74 -0
  111. package/dist/docx/server/templatePlan/xml.js +125 -0
  112. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  113. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  114. package/dist/docx/structuralXmlPatch.js +9 -1
  115. package/dist/docx/tableGridXml.d.ts +30 -0
  116. package/dist/docx/tableGridXml.js +54 -0
  117. package/dist/docx/tableParser.js +7 -0
  118. package/dist/i18n/loadMessages.d.ts +5 -0
  119. package/dist/i18n/loadMessages.js +46 -0
  120. package/dist/i18n/locales.d.ts +3 -0
  121. package/dist/i18n/locales.js +17 -0
  122. package/dist/i18n/messages.d.ts +3 -2
  123. package/dist/i18n/messages.js +4 -16
  124. package/dist/index.d.ts +3 -3
  125. package/dist/index.js +2 -3
  126. package/dist/internal/clipboardTransformPlugin.d.ts +3 -0
  127. package/dist/internal/clipboardTransformPlugin.js +13 -0
  128. package/dist/internal/extensionRuntime.d.ts +7 -0
  129. package/dist/internal/extensionRuntime.js +28 -0
  130. package/dist/internal/starterKitExtensions.d.ts +20 -0
  131. package/dist/internal/starterKitExtensions.js +123 -0
  132. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  133. package/dist/managers/ContextMenuManager.js +2 -1
  134. package/dist/managers/editorShortcuts.d.ts +1 -1
  135. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  136. package/dist/prosemirror/attrs/index.js +1 -1
  137. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  138. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  139. package/dist/prosemirror/canonicalSelectionRange.js +1 -1
  140. package/dist/prosemirror/canonicalTableCommands.js +3 -3
  141. package/dist/prosemirror/commands/comments.js +4 -4
  142. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  143. package/dist/prosemirror/commands/contentControls.js +1 -1
  144. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  145. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  146. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  147. package/dist/prosemirror/commands/pastePlainText.js +2 -3
  148. package/dist/prosemirror/commands/replaceRangeText.js +1 -1
  149. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  150. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  151. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  152. package/dist/prosemirror/commentRecords.d.ts +1 -1
  153. package/dist/prosemirror/commentRecords.js +2 -2
  154. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  155. package/dist/prosemirror/conversion/fromProseDoc.d.ts +0 -5
  156. package/dist/prosemirror/conversion/fromProseDoc.js +2 -9
  157. package/dist/prosemirror/conversion/index.d.ts +2 -2
  158. package/dist/prosemirror/conversion/index.js +2 -2
  159. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  160. package/dist/prosemirror/documentStructureCounts.js +76 -0
  161. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  162. package/dist/prosemirror/extensions/ExtensionManager.js +4 -22
  163. package/dist/prosemirror/extensions/StarterKit.d.ts +4 -27
  164. package/dist/prosemirror/extensions/StarterKit.js +29 -115
  165. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  166. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  167. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  168. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  169. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +1 -1
  170. package/dist/prosemirror/extensions/features/ListExtension.js +7 -2
  171. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  172. package/dist/prosemirror/extensions/index.d.ts +2 -1
  173. package/dist/prosemirror/extensions/marks/FootnoteRefExtension.js +8 -3
  174. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  175. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  176. package/dist/prosemirror/extensions/nodes/TableExtension.js +8 -41
  177. package/dist/prosemirror/extensions/types.d.ts +1 -1
  178. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  179. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  180. package/dist/prosemirror/hyperlinkRemoval.js +7 -2
  181. package/dist/prosemirror/index.d.ts +3 -3
  182. package/dist/prosemirror/index.js +3 -3
  183. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  184. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  185. package/dist/prosemirror/keptRangeBoundaries.js +1 -1
  186. package/dist/prosemirror/listNumbering.d.ts +1 -1
  187. package/dist/prosemirror/listNumbering.js +1 -1
  188. package/dist/prosemirror/lockedControls.d.ts +1 -1
  189. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  190. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  191. package/dist/prosemirror/noteReferenceOccurrences.js +1 -1
  192. package/dist/prosemirror/noteReferenceReview.d.ts +2 -56
  193. package/dist/prosemirror/noteReferenceReview.js +2 -243
  194. package/dist/prosemirror/{extensions/features/ParaIdAllocatorExtension.d.ts → paraIds.d.ts} +13 -23
  195. package/dist/prosemirror/paraIds.js +152 -0
  196. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  197. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  198. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  199. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  200. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  201. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  202. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  203. package/dist/prosemirror/plugins/documentNumbering.js +1 -1
  204. package/dist/prosemirror/plugins/documentStyles.js +1 -1
  205. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  206. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  207. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  208. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  209. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  210. package/dist/prosemirror/replacedAnnotations.js +17 -2
  211. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  212. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  213. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  214. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  215. package/dist/prosemirror/selectionBounds.js +22 -0
  216. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  217. package/dist/prosemirror/suggestionCommands.d.ts +47 -0
  218. package/dist/prosemirror/suggestionCommands.js +31 -0
  219. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  220. package/dist/prosemirror/tableCellPaste.js +1 -1
  221. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  222. package/dist/prosemirror/tableRunIn.js +1 -1
  223. package/dist/prosemirror/textInput.d.ts +1 -1
  224. package/dist/prosemirror/textInput.js +1 -1
  225. package/dist/server.d.ts +7 -2
  226. package/dist/server.js +6 -1
  227. package/dist/types/canonicalCapabilities.d.ts +13 -92
  228. package/dist/types/canonicalCapabilities.js +11 -85
  229. package/package.json +4 -4
  230. package/dist/ai-edits/apply.d.ts +0 -202
  231. package/dist/ai-edits/apply.js +0 -6759
  232. package/dist/ai-edits/note-story-inventory.d.ts +0 -5
  233. package/dist/ai-edits/note-story-inventory.js +0 -10
  234. package/dist/ai-edits/revisionStretches.d.ts +0 -32
  235. package/dist/ai-edits/revisionStretches.js +0 -147
  236. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +0 -18
  237. package/dist/prosemirror/extensions/core/HistoryExtension.js +0 -122
  238. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +0 -408
  239. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +0 -135
  240. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +0 -566
  241. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -92
  242. package/dist/prosemirror/plugins/suggestionMode.js +0 -1515
  243. package/dist/prosemirror/tablePositionedBookmarks.d.ts +0 -8
  244. package/dist/prosemirror/tablePositionedBookmarks.js +0 -80
@@ -5,72 +5,47 @@ import { canonicalRevisionLocks } from "../canonical/canonicalRevisionLocks.js";
5
5
  import { openCanonicalDocxSession, openCanonicalRoomBase } from "../canonical/canonicalRoomBase.js";
6
6
  import { CanonicalSessionError, createCanonicalSession, publishCanonicalProjection } from "../canonical/canonicalSession.js";
7
7
  import { matchInlineAtomsOnModel } from "../compare/inline-atoms-model.js";
8
- import { matchInlineAtoms } from "../compare/inline-atoms.js";
9
8
  import { inlineProvenanceOperations } from "../compare/inline-provenance-model.js";
10
- import { matchInlineProvenance, planInlineProvenance } from "../compare/inline-provenance.js";
11
- import { stageSectionBoundaryOperations, stageSectionBoundaryProperties } from "../compare/section-boundary-properties.js";
9
+ import { planInlineProvenance } from "../compare/inline-provenance.js";
10
+ import { stageSectionBoundaryOperations } from "../compare/section-boundary-properties.js";
12
11
  import { importReferencedStyleDefinitions, styleClosureNumberingReferences } from "../compare/style-resources.js";
13
- import { applyFolioDocumentOperationsInPackage, parseFolioDocumentOperationBatch } from "../document-operations.js";
12
+ import { parseFolioDocumentOperationBatch } from "../document-operations.js";
14
13
  import { CanonicalSaveRepackRefusedError, serializeCanonicalSave } from "../docx/canonicalSave.js";
15
- import { removeCommentMarkers } from "../docx/commentAnchorIndex.js";
16
- import { applyReplyThreadMarkers } from "../docx/commentReplyMarkers.js";
17
- import { commentTextParagraph } from "../docx/commentTextParagraph.js";
18
- import { buildSections } from "../docx/documentParser.js";
19
14
  import { rebindDrawingImageRelationship } from "../docx/drawingRelationships.js";
20
15
  import { isSeparatorEndnote, isSeparatorFootnote } from "../docx/footnoteParser.js";
21
- import { normalizeListModelRendering } from "../docx/listModelNormalization.js";
22
16
  import { createNumberingIdAllocator, numberingNumIdsTaken } from "../docx/numberingIds.js";
23
17
  import { getCachedNumberingMap } from "../docx/numberingParser.js";
24
18
  import { cloneDocumentWithParagraphPropertySources } from "../docx/paragraphPropertySource.js";
25
- import { visitDocxParagraphs } from "../docx/paragraphTraversal.js";
26
- import { parseDocx } from "../docx/parser.js";
27
- import { createReply } from "../docx/replyToComment.js";
28
- import { repackDocx } from "../docx/rezip.js";
29
- import { attemptSelectiveSave } from "../docx/selectiveSave.js";
30
19
  import { getEndnoteText, getFootnoteText, getHeaderFooterText } from "../docx/storyPlainText.js";
31
- import { pluginsForHeadlessRevisionResolution } from "../internal/headlessRevisionResolutionGuard.js";
32
- import { withTrackedSectionEndpointRemoval } from "../internal/sectionEndpointResolution.js";
33
- import { captureSectionReferenceInventory, resolvedSectionReferenceLosses, withSectionReferenceResolution } from "../internal/sectionReferenceResolution.js";
34
- import { expectCharacterStyleMarkAttrs, expectFootnoteRefMarkAttrs } from "../prosemirror/attrs/index.js";
35
- import { acceptAIEditRevision, acceptSuggestion, getSuggestions, rejectAIEditRevision, rejectEverySuggestion, rejectSuggestion, resolveAllChangesInHeadlessState, revisionResolutionLockViolation, suggestionIdOfRevision, suggestionOwnersByRevision } from "../prosemirror/commands/comments.js";
20
+ import { expectCharacterStyleMarkAttrs } from "../prosemirror/attrs/index.js";
21
+ import { getSuggestions, suggestionIdOfRevision, suggestionOwnersByRevision } from "../prosemirror/commands/comments.js";
36
22
  import { createCommentIdAllocator, seedCommentAllocator } from "../prosemirror/commentIdAllocator.js";
37
- import { commentThreadIds, removeCommentAnchors } from "../prosemirror/commentRecords.js";
38
- import { fromProseDoc, proseDocToBlocks } from "../prosemirror/conversion/fromProseDoc.js";
39
- import { footnoteToProseDoc, headerFooterToProseDoc, toProseDoc } from "../prosemirror/conversion/toProseDoc.js";
40
- import { ensureBaseDirectionInState } from "../prosemirror/extensions/features/AutoBidiDetectionExtension.js";
41
- import { ensureParaIdsInDoc } from "../prosemirror/extensions/features/ParaIdAllocatorExtension.js";
42
- import { getChangedParagraphIds, getTrackedSectionEndpointRemoval, hasStructuralChanges, hasUntrackedChanges } from "../prosemirror/extensions/features/ParagraphChangeTrackerExtension.js";
43
- import { completeNumberingForDoc, paragraphListReferences } from "../prosemirror/listInstanceReferences.js";
23
+ import { commentThreadIds } from "../prosemirror/commentRecords.js";
24
+ import { paragraphListReferences } from "../prosemirror/listInstanceReferences.js";
44
25
  import "../prosemirror/listMarker.js";
45
- import { lockedControlSpans } from "../prosemirror/lockedControls.js";
46
- import { deleteNoteWithReference, noteDeletionRevisions, noteKeysReferencedIn, noteReferenceStates, noteReferencesRestored, referenceDeletions, referencedNotes } from "../prosemirror/noteReferenceReview.js";
47
- import { createDocumentNumberingPlugin, getDocumentNumbering, withDocumentNumbering } from "../prosemirror/plugins/documentNumbering.js";
26
+ import { noteReferenceStates } from "../prosemirror/noteReferenceReview.js";
27
+ import { ensureParaIdsInDoc } from "../prosemirror/paraIds.js";
28
+ import { createDocumentNumberingPlugin, getDocumentNumbering } from "../prosemirror/plugins/documentNumbering.js";
48
29
  import { getDocumentStyleResolver } from "../prosemirror/plugins/documentStyleState.js";
49
- import { createDocumentStyleContextPlugin, createDocumentStylesPlugin, withDocumentStyles } from "../prosemirror/plugins/documentStyles.js";
30
+ import { createDocumentStyleContextPlugin } from "../prosemirror/plugins/documentStyles.js";
50
31
  import { getFolioNodeRevisionCarriers } from "../prosemirror/revisionCarriers.js";
51
- import { schema, singletonManager } from "../prosemirror/schema/index.js";
32
+ import { schema } from "../prosemirror/schema/index.js";
52
33
  import { sectionPropertiesOf } from "../prosemirror/sectionCarrier.js";
53
- import { storyListNumbering } from "../prosemirror/storyListNumbering.js";
54
- import { collapseEmptyTextBoxHosts } from "../prosemirror/textBoxHostCollapse.js";
55
- import { CANONICAL_GAP, CANONICAL_RULE, headlessReviewerUsesCanonicalSession } from "../types/canonicalCapabilities.js";
34
+ import { CANONICAL_GAP, CANONICAL_RULE } from "../types/canonicalCapabilities.js";
56
35
  import { readModel } from "../types/documentModel.js";
57
36
  import { canonicalJson } from "../utils/canonicalJson.js";
58
- import { persistedBlock } from "./block-identity.js";
59
37
  import { buildAnnotatedBlockTextWithNoteReferences } from "./clean-text.js";
60
38
  import { anchoredCommentIdsInBlocks, anchoredCommentIdsInProseDoc, coveredCommentIdsInProseDoc, withoutLostCommentThreads } from "./comment-lifecycle.js";
61
39
  import { stagedFinalSectionProperties } from "./finalSectionReview.js";
62
- import { noteReferenceEditsAllowed } from "./note-references.js";
63
- import { noteStoryInventory } from "./note-story-inventory.js";
64
- import { FolioPendingSuggestionRegistry, createPendingSuggestionSourceSnapshot, withoutPendingSuggestionCommentMarks } from "./pending-suggestions.js";
65
- import { getCommentAnchorsFromDoc, getTrackedChangeGroupIdsFromDoc, getTrackedChangeStatsFromDoc, getTrackedChangesFromDoc, getTrackedChangesFromSnapshot, listedRevisionGroups } from "./read.js";
40
+ import { FolioPendingSuggestionRegistry, createPendingSuggestionSourceSnapshot } from "./pending-suggestions.js";
41
+ import { getCommentAnchorsFromDoc, getTrackedChangeStatsFromDoc, getTrackedChangesFromDoc, getTrackedChangesFromSnapshot, listedRevisionGroups } from "./read.js";
66
42
  import { classifyResourceReference } from "./referenceClassification.js";
67
43
  import { collectNoteReferenceLabels, createReviewerSnapshot, detachFolioAIEditSnapshotExternalHyperlinks, folioStoryTables, isFolioAIContentBlock, normalizeFolioAIBlockText, sourceDocumentOf } from "./snapshot.js";
68
- import { matchTableGeometry, matchTableGeometryOperations } from "./table-geometry.js";
44
+ import { matchTableGeometryOperations } from "./table-geometry.js";
69
45
  import { tableTemplateCanCrossPackageLosslessly } from "./table-template.js";
70
- import { withOperationHeadingStyles } from "./undefinedReferences.js";
71
46
  import { TaggedError, panic } from "better-result";
72
- import { CONTENT_CONTROL_LOCK, REVIEW_CARRIERS, finalizeParagraphFormatting, lockedControlMessage, numberingLevelEntries, setDocumentBodyComments } from "@stll/docx-core/model";
73
- import { DOCUMENT_OP_TYPES, OP_STORIES, captureStoryParts, freshCommentId, packageResourcesOpOf, pendingSuggestionIdsIn, reconcileDocumentPartRelationships, resolveSectionChange, resolveSectionChanges, resolvedDocumentView, sectionResolutionPatch, withoutPendingSuggestions } from "@stll/docx-core/ops";
47
+ import { CONTENT_CONTROL_LOCK, lockedControlMessage, numberingLevelEntries } from "@stll/docx-core/model";
48
+ import { DOCUMENT_OP_TYPES, OP_STORIES, captureStoryParts, freshCommentId, packageResourcesOpOf, pendingSuggestionIdsIn, reconcileDocumentPartRelationships, resolveSectionChange, resolveSectionChanges, sectionResolutionPatch, withoutPendingSuggestions } from "@stll/docx-core/ops";
74
49
  import { ZipArchive } from "@stll/docx-core/zip";
75
50
  import { EditorState, Selection, TextSelection } from "prosemirror-state";
76
51
  // src/ai-edits/headless.ts
@@ -81,11 +56,8 @@ import { EditorState, Selection, TextSelection } from "prosemirror-state";
81
56
  * reviewed `.docx` back out — the server-side counterpart to the React
82
57
  * editor's live apply flow.
83
58
  *
84
- * The operation applier is shared, not forked: {@link applyFolioAIEditOperations}
85
- * only needs a {@link FolioAIEditView} seam (`{ state, dispatch }`), which a
86
- * headless `EditorState` satisfies via `state.apply(tr)`. The React editor and
87
- * this reviewer therefore run byte-for-byte the same anchor resolution,
88
- * word-diff redlines, and tracked-change bookkeeping.
59
+ * The editor and reviewer share the canonical operation compiler and document
60
+ * session for anchor resolution, tracked changes, and save snapshots.
89
61
  *
90
62
  * Save mirrors the editor's own path: a selective patch of only the changed
91
63
  * paragraphs in `document.xml` (leaving every untouched part byte-exact), with
@@ -93,14 +65,6 @@ import { EditorState, Selection, TextSelection } from "prosemirror-state";
93
65
  *
94
66
  * Scope: main, header, footer, footnote, and endnote blocks.
95
67
  */
96
- let undoHandleCursor = Date.now();
97
- const createReviewerComment = ({ id, text, author, date }) => ({
98
- id,
99
- anchorKind: "range",
100
- author,
101
- date: date ?? (/* @__PURE__ */ new Date()).toISOString(),
102
- content: [commentTextParagraph(text)]
103
- });
104
68
  /**
105
69
  * How many document-operation batches a reviewer can step back through.
106
70
  * Each entry holds the story's state before and after its batch; older
@@ -175,67 +139,12 @@ const UnsupportedFolioReviewedViewErrorBase = TaggedError("UnsupportedFolioRevie
175
139
  var UnsupportedFolioReviewedViewError = class extends UnsupportedFolioReviewedViewErrorBase {};
176
140
  const FolioRoomJournalErrorBase = TaggedError("FolioRoomJournalError");
177
141
  /**
178
- * Why a reviewer could not replay a room's journal. `legacyEngine`: only a
179
- * canonical reviewer follows a room. `revisionGap`: a batch is not the one
180
- * after the last the reviewer applied.
142
+ * Why a reviewer could not replay a room's journal. `revisionGap`: a batch is
143
+ * not the one after the last the reviewer applied.
181
144
  */
182
145
  var FolioRoomJournalError = class extends FolioRoomJournalErrorBase {};
183
146
  const FolioDocumentStoryNotFoundErrorBase = TaggedError("FolioDocumentStoryNotFoundError");
184
147
  var FolioDocumentStoryNotFoundError = class extends FolioDocumentStoryNotFoundErrorBase {};
185
- const FolioResolvedViewRefusedErrorBase = TaggedError("FolioResolvedViewRefusedError");
186
- /** A resolved view whose revision resolution refused in some stories. */
187
- var FolioResolvedViewRefusedError = class extends FolioResolvedViewRefusedErrorBase {};
188
- const FOLIO_RESOLVED_STORY_SERIALIZATION_MISMATCHES = Object.freeze({
189
- storyMissing: "story-missing",
190
- revisionMarkupRemains: "revision-markup-remains",
191
- textProjection: "text-projection",
192
- blockProjection: "block-projection"
193
- });
194
- const FolioResolvedStorySerializationErrorBase = TaggedError("FolioResolvedStorySerializationError");
195
- var FolioResolvedStorySerializationError = class extends FolioResolvedStorySerializationErrorBase {};
196
- /** Blocks whose id folio minted, because the package names no id for them. */
197
- const mintedBlockOrdinals = (snapshot) => {
198
- const ordinals = /* @__PURE__ */ new Set();
199
- for (const [ordinal, block] of snapshot.blocks.entries()) if (block.idStability === "positional") ordinals.add(ordinal);
200
- return ordinals;
201
- };
202
- /**
203
- * What a block looks like once the story has been through the package.
204
- *
205
- * `idStability` is the snapshot's own fact rather than the package's, so it
206
- * goes. `minted` names the blocks whose id folio invented for a paragraph the
207
- * package gives no `w14:paraId`, and each of those stands down to its position.
208
- * A minted id is derived from the paragraph's text and ordinal, so resolving
209
- * its text can make an id-less paragraph derive a different id when reopened.
210
- * The two save paths also disagree about whether it reaches the file at all:
211
- * the selective patch keeps the author's id-less convention (see
212
- * `withoutMintedIds`) while a full repack writes the model's ids. Which path
213
- * ran is not what this check is about, so neither the id nor the choice between
214
- * them may decide it. An authored id is compared exactly as it is, and a block
215
- * that moved still fails.
216
- */
217
- const resolvedStoryBlockProjection = (block, ordinal, minted) => {
218
- const persisted = persistedBlock(block);
219
- return minted.has(ordinal) ? {
220
- ...persisted,
221
- id: `minted-${String(ordinal)}`
222
- } : persisted;
223
- };
224
- /**
225
- * The two halves of the expectation, from one projection.
226
- *
227
- * The reading text carries each block's id, so it has to be built from the
228
- * same projected blocks the block comparison uses; formatting the raw snapshot
229
- * instead would put a minted id back into the text and fail the check the
230
- * block projection just passed.
231
- */
232
- const resolvedStoryProjection = (snapshot, minted) => {
233
- const blocks = snapshot.blocks.map((block, ordinal) => resolvedStoryBlockProjection(block, ordinal, minted));
234
- return {
235
- text: blocks.filter(isFolioAIContentBlock).map(formatBlockForLLM).join("\n"),
236
- blocks
237
- };
238
- };
239
148
  const numberingLevelsOf = (numbering) => {
240
149
  if (!numbering) return [];
241
150
  return numberingLevelEntries(numbering).map(({ numId, ilvl, level }) => {
@@ -283,20 +192,6 @@ const noteStoryHandleOf = (key) => {
283
192
  noteId: Number(noteId)
284
193
  } : null;
285
194
  };
286
- /** The notes a story's text refers to, keyed as {@link noteStoryKey} keys them. */
287
- const referencedNoteKeys = (doc) => {
288
- const keys = /* @__PURE__ */ new Set();
289
- doc.descendants((node) => {
290
- if (!node.isText) return true;
291
- for (const mark of node.marks) {
292
- if (mark.type.name !== "footnoteRef") continue;
293
- const { id, noteType } = expectFootnoteRefMarkAttrs(mark);
294
- keys.add(`${noteType === "endnote" ? "endnote" : "footnote"}:${String(id)}`);
295
- }
296
- return false;
297
- });
298
- return keys;
299
- };
300
195
  /**
301
196
  * A part's roles as a reader label: `first`, or, in a document with several
302
197
  * sections, `first (sections 1, 3), default (section 2)`.
@@ -310,15 +205,6 @@ const secondaryStoryKey = (story) => story.type === "header" || story.type === "
310
205
  const editableStoryKey = (story) => story.type === "main" ? "main" : secondaryStoryKey(story);
311
206
  const isFolioReviewedView = (value) => FOLIO_REVIEWED_VIEWS.some((view) => view === value);
312
207
  const isFolioResolvedReviewedView = (value) => FOLIO_RESOLVED_REVIEWED_VIEWS.some((view) => view === value);
313
- const resolveReviewedState = (state, view) => {
314
- if (view === "current-markup") return state;
315
- return resolveAllChangesInHeadlessState(state, view === "original" ? "reject" : "accept");
316
- };
317
- const createHeadlessPlugins = (styles, numbering) => [
318
- createDocumentNumberingPlugin(numbering),
319
- ...pluginsForHeadlessRevisionResolution(singletonManager.getPlugins()),
320
- createDocumentStylesPlugin(styles)
321
- ];
322
208
  /** A state's snapshot, of `doc` when it names the state's document otherwise spelled. */
323
209
  const createStateSnapshot = (state, positionalParaIds, doc = state.doc) => createReviewerSnapshot({
324
210
  doc,
@@ -571,22 +457,6 @@ const carriedByGroup = (id, groupIds, { removed, moved }) => {
571
457
  };
572
458
  };
573
459
  /**
574
- * The changes of a story, by revision id, that a content control's lock keeps
575
- * from being resolved in `mode`: every physical revision of one change is
576
- * resolved together, so the change is held when resolving them would break a
577
- * lock. Empty without a locked control.
578
- */
579
- const lockHeldChanges = (state, mode) => {
580
- const held = /* @__PURE__ */ new Map();
581
- if (lockedControlSpans(state.doc).length === 0) return held;
582
- for (const { id } of getTrackedChangesFromDoc(state.doc)) {
583
- const ids = getTrackedChangeGroupIdsFromDoc(state.doc, id);
584
- const violation = revisionResolutionLockViolation(state, ids, mode);
585
- if (violation !== null) held.set(id, violation);
586
- }
587
- return held;
588
- };
589
- /**
590
460
  * One story's reading of the numbering: the lists the package was opened
591
461
  * with, and those started since that `doc`'s paragraphs name. A list another
592
462
  * story started is defined in that story's reading, not in this one.
@@ -626,27 +496,14 @@ var FolioDocxReviewer = class FolioDocxReviewer {
626
496
  * alike; a legacy state already holds every id.
627
497
  */
628
498
  snapshotOf(state) {
629
- return this.engine.type === "canonical" ? createStateSnapshot(state, this.positionalParaIds, ensureParaIdsInDoc(state.doc)) : createStateSnapshot(state, this.positionalParaIds);
499
+ return createStateSnapshot(state, this.positionalParaIds, ensureParaIdsInDoc(state.doc));
630
500
  }
631
501
  /** Default author for tracked changes and comments. */
632
502
  author;
633
- /** The legacy reviewer's parsed model; a canonical one reads its session's. */
503
+ /** The model the reviewer was opened on; the readers follow the session's. */
634
504
  loadedDocument;
635
- finalSectionPropertiesOverride;
636
505
  originalBuffer;
637
506
  state;
638
- secondaryStoryStates = /* @__PURE__ */ new Map();
639
- removedHeaderFooterStories = /* @__PURE__ */ new Map();
640
- /** Notes whose reference a resolution removed: a note exists only through its reference. */
641
- removedNoteStories = /* @__PURE__ */ new Map();
642
- sectionReferenceRemovals = [];
643
- importedStyles;
644
- importedMedia = /* @__PURE__ */ new Map();
645
- importedHeaders = /* @__PURE__ */ new Map();
646
- importedFooters = /* @__PURE__ */ new Map();
647
- resolvedStoryExpectations = /* @__PURE__ */ new Map();
648
- createdComments = [];
649
- deletedCommentIds = /* @__PURE__ */ new Set();
650
507
  /** Comments the body anchored when it was loaded, read as the editor projects it. */
651
508
  loadedMainCommentIds;
652
509
  /**
@@ -655,17 +512,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
655
512
  * pairs two documents' paragraphs by them.
656
513
  */
657
514
  positionalParaIds;
658
- documentOperationUndoEntries = [];
659
515
  pendingSuggestions = new FolioPendingSuggestionRegistry();
660
- /**
661
- * Resolved-state overrides recorded by {@link resolveComment}, keyed by
662
- * comment id. Applied on read ({@link getComments}) and on write
663
- * ({@link toDocument}) rather than mutating the parsed `Comment` objects in
664
- * place, matching how the parser/serializer treat `Comment` as immutable
665
- * (`commentParser.ts` replaces array slots via spread; the serializer
666
- * types its inputs `readonly Comment[]`).
667
- */
668
- resolvedOverrides = /* @__PURE__ */ new Map();
669
516
  /** The last room revision {@link applyRoomJournal} applied. */
670
517
  roomRevision = 0;
671
518
  /** The resolved copies {@link resolvedSessionReader} last read, by view. */
@@ -679,86 +526,19 @@ var FolioDocxReviewer = class FolioDocxReviewer {
679
526
  this.originalBuffer = args.originalBuffer;
680
527
  this.state = args.state;
681
528
  this.author = args.author;
682
- this.engine = args.engine.type === "legacy" ? args.engine : this.canonicalEngine(args.engine.session);
529
+ this.engine = this.canonicalEngine(args.engine.session);
683
530
  this.commentIds = args.commentIds?.clone() ?? createCommentIdAllocator();
684
531
  seedCommentAllocator(this.commentIds, args.baseDocument.package.document.comments, { state: args.state });
685
532
  this.loadedMainCommentIds = new Set(args.loadedMainCommentIds ?? anchoredCommentIdsInProseDoc(args.state.doc));
686
533
  this.registerComparisonAccess();
687
534
  }
688
535
  registerComparisonAccess() {
689
- if (this.engine.type === "canonical") {
690
- comparisonAccessByReviewer.set(this, this.canonicalComparisonAccess());
691
- return;
692
- }
693
- comparisonAccessByReviewer.set(this, Object.freeze({
694
- stageTerminalTableReviewCarrier: (target) => this.stageTerminalTableReviewCarrier(target),
695
- stageTargetStyles: (options) => this.stageTargetStyles(options),
696
- createComparisonHeaderFooter: (source, story) => this.createComparisonHeaderFooter(source, story),
697
- finalSectionProperties: () => this.currentFinalSectionProperties(),
698
- stageFinalSectionProperties: ({ target, previous, revision }) => this.stageFinalSectionProperties({
699
- target,
700
- previous,
701
- revision
702
- }),
703
- stageMappedSectionBoundaries: (options) => this.stageMappedSectionBoundaries(options),
704
- matchInlineAtoms: ({ story, targetReviewer: _targetReviewer, targetStory: _targetStory, ...options }) => {
705
- const state = this.getEditableStoryState(story);
706
- if (!state) return panic("A compared story lost its editable state", { story });
707
- const result = matchInlineAtoms({
708
- ...options,
709
- state,
710
- author: this.author
711
- });
712
- switch (result.status) {
713
- case "matched":
714
- if (result.transaction.docChanged) this.setEditableStoryState(story, state.apply(result.transaction));
715
- return {
716
- status: "matched",
717
- nextRevisionId: result.nextRevisionId,
718
- changedTargetBlockIds: result.changedTargetBlockIds,
719
- rangeCount: result.rangeCount,
720
- documentChanged: result.transaction.docChanged
721
- };
722
- case "unalignable":
723
- case "budget-exceeded": return result;
724
- default: return panic("Unhandled inline atom result", { result });
725
- }
726
- },
727
- matchInlineProvenance: ({ story, targetReviewer: _targetReviewer, targetStory: _targetStory, ...options }) => {
728
- const state = this.getEditableStoryState(story);
729
- if (!state) return panic("A compared story lost its editable state", { story });
730
- const result = matchInlineProvenance({
731
- ...options,
732
- state,
733
- author: this.author
734
- });
735
- switch (result.status) {
736
- case "matched":
737
- if (result.transaction.docChanged) this.setEditableStoryState(story, state.apply(result.transaction));
738
- return {
739
- status: "matched",
740
- nextRevisionId: result.nextRevisionId,
741
- changedTargetBlockIds: result.changedTargetBlockIds,
742
- rangeCount: result.rangeCount,
743
- documentChanged: result.transaction.docChanged
744
- };
745
- case "unalignable":
746
- case "budget-exceeded": return result;
747
- default: return panic("Unhandled inline provenance result", { result });
748
- }
749
- },
750
- projectStories: (mode) => this.projectComparisonStoriesInternal(mode),
751
- snapshotReviewedStory: (options) => this.snapshotReviewedStoryInternal(options),
752
- numberingDefinitions: () => this.baseDocument.package.numbering,
753
- styleDefinitions: () => this.importedStyles ?? this.baseDocument.package.styles,
754
- planTargetNumberingReferences: (target, references) => this.planTargetNumberingReferences(target, references),
755
- stageTargetNumbering: (target, references, remappedNumIds) => this.stageTargetNumbering(target, references, remappedNumIds)
756
- }));
536
+ comparisonAccessByReviewer.set(this, this.canonicalComparisonAccess());
757
537
  }
758
538
  stageTargetStyles({ source, snapshots, importedHeaderFooterSnapshots, numberingReferenceMap }) {
759
539
  const destination = this.baseDocument.package;
760
540
  const sourcePackage = source.baseDocument.package;
761
- const destinationStyles = this.importedStyles ?? destination.styles;
541
+ const destinationStyles = destination.styles;
762
542
  const sourceStylesById = new Map(sourcePackage.styles?.styles.map((style) => [style.styleId, style]));
763
543
  const destinationStyleIds = new Set(destinationStyles?.styles.map(({ styleId }) => styleId));
764
544
  const collect = (document) => {
@@ -823,39 +603,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
823
603
  reservedStyleIds: [...reservedStyleIds],
824
604
  materializeDefaultParagraphStyle
825
605
  });
826
- if (result.status === "imported" && this.engine.type === "canonical") {
827
- this.stagePackageResourcesOnSession({ styles: result.styles });
828
- return result;
829
- }
830
- if (result.status === "imported") this.installImportedStyles(result.styles);
606
+ if (result.status === "imported") this.stagePackageResourcesOnSession({ styles: result.styles });
831
607
  return result;
832
608
  }
833
- installImportedStyles(styles, restoredStory) {
834
- this.importedStyles = styles;
835
- const definitions = styles ?? this.loadedDocument.package.styles;
836
- if (restoredStory?.type !== "main") this.state = withDocumentStyles(this.state, definitions);
837
- for (const entry of this.secondaryStoryStates.values()) {
838
- if (restoredStory !== void 0 && editableStoryKey(entry.handle) === editableStoryKey(restoredStory)) continue;
839
- const wasUntouched = entry.state === entry.initialState;
840
- const refreshed = withDocumentStyles(entry.state, definitions);
841
- entry.state = refreshed;
842
- if (wasUntouched) entry.initialState = refreshed;
843
- }
844
- }
845
- /**
846
- * A raw final table has no paragraph mark after it for Word to merge into
847
- * when the target ends in a paragraph. Folio-exact comparison adds this
848
- * untracked receiver before planning; its private marker makes resolving in
849
- * Folio restore the raw source view.
850
- */
851
- stageTerminalTableReviewCarrier(target) {
852
- if (this.state.doc.lastChild?.type.name !== "table" || target.lastChild?.type.name !== "paragraph") return false;
853
- const paragraphType = this.state.schema.nodes["paragraph"];
854
- if (!paragraphType) return panic("The schema has no paragraph node for a terminal-table review carrier");
855
- const carrier = paragraphType.create({ reviewCarrier: REVIEW_CARRIERS.TERMINAL_TABLE });
856
- this.state = this.state.apply(this.state.tr.insert(this.state.doc.content.size, carrier));
857
- return true;
858
- }
859
609
  stageTargetNumbering(target, references, remappedNumIds) {
860
610
  if (references.length === 0) return "unchanged";
861
611
  if (!target) return "conflict";
@@ -909,13 +659,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
909
659
  abstractNums: [...abstracts.values()],
910
660
  nums: [...nums.values()]
911
661
  };
912
- if (this.engine.type === "canonical") {
913
- this.stagePackageResourcesOnSession({ numbering });
914
- return "staged";
915
- }
916
- this.baseDocument.package.numbering = numbering;
917
- this.state = withDocumentNumbering(this.state, numbering);
918
- for (const entry of this.secondaryStoryStates.values()) entry.state = withDocumentNumbering(entry.state, numbering);
662
+ this.stagePackageResourcesOnSession({ numbering });
919
663
  return "staged";
920
664
  }
921
665
  planTargetNumberingReferences(target, references) {
@@ -957,37 +701,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
957
701
  return base.value;
958
702
  }
959
703
  /** Parse a `.docx` buffer into a reviewer. */
960
- static async fromBuffer(buffer, options = {}) {
961
- if (headlessReviewerUsesCanonicalSession(options.session)) return FolioDocxReviewer.fromCanonicalBuffer(buffer, options);
962
- const baseDocument = await parseDocx(buffer, {
963
- detectVariables: false,
964
- preloadFonts: false,
965
- password: options.password
966
- });
967
- return FolioDocxReviewer.legacyOver(baseDocument, {
968
- originalBuffer: baseDocument.originalBuffer ?? buffer,
969
- author: options.author ?? "AI"
970
- });
971
- }
972
- /**
973
- * A legacy reviewer over a parsed or resolved document. A resolved one names
974
- * the ids its source read as positional, which its model now spells as ids.
975
- */
976
- static legacyOver(baseDocument, { originalBuffer, author, positionalParaIds }) {
977
- const plugins = createHeadlessPlugins(baseDocument.package.styles, baseDocument.package.numbering);
978
- const state = ensureBaseDirectionInState(EditorState.create({
979
- schema,
980
- doc: ensureParaIdsInDoc(toProseDoc(baseDocument)),
981
- plugins
982
- }));
983
- return new FolioDocxReviewer({
984
- baseDocument,
985
- originalBuffer,
986
- state,
987
- author,
988
- engine: { type: "legacy" },
989
- ...positionalParaIds === void 0 ? {} : { positionalParaIds }
990
- });
704
+ static fromBuffer(buffer, options = {}) {
705
+ return FolioDocxReviewer.fromCanonicalBuffer(buffer, options);
991
706
  }
992
707
  /**
993
708
  * Load as a canonical editor does: the same input normalization (paragraph
@@ -1042,39 +757,20 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1042
757
  * either leave the other as it is. The copy's undo history starts empty.
1043
758
  */
1044
759
  fork() {
1045
- if (this.engine.type === "canonical") {
1046
- const document = readModel(this.engine.session.document);
1047
- const created = createCanonicalSession(document, document.package.styles);
1048
- if (created.isErr()) throw created.error;
1049
- const copy = new FolioDocxReviewer({
1050
- baseDocument: document,
1051
- originalBuffer: this.originalBuffer,
1052
- state: canonicalReviewerState(created.value),
1053
- author: this.author,
1054
- engine: {
1055
- type: "canonical",
1056
- session: created.value
1057
- },
1058
- positionalParaIds: this.positionalParaIds
1059
- });
1060
- copy.pendingSuggestions = this.pendingSuggestions.clone();
1061
- return copy;
1062
- }
1063
- return this.forkLegacy();
1064
- }
1065
- /** A constructor-backed copy over the legacy snapshot owner. */
1066
- forkLegacy() {
1067
- const snapshot = this.captureReviewerState();
760
+ const document = readModel(this.engine.session.document);
761
+ const created = createCanonicalSession(document, document.package.styles);
762
+ if (created.isErr()) throw created.error;
1068
763
  const copy = new FolioDocxReviewer({
1069
- baseDocument: this.loadedDocument,
764
+ baseDocument: document,
1070
765
  originalBuffer: this.originalBuffer,
1071
- state: snapshot.mainState.apply(snapshot.mainState.tr),
766
+ state: canonicalReviewerState(created.value),
1072
767
  author: this.author,
1073
- engine: { type: "legacy" },
1074
- loadedMainCommentIds: this.loadedMainCommentIds,
1075
- commentIds: this.commentIds
768
+ engine: {
769
+ type: "canonical",
770
+ session: created.value
771
+ },
772
+ positionalParaIds: this.positionalParaIds
1076
773
  });
1077
- copy.restoreReviewerState(snapshot);
1078
774
  copy.pendingSuggestions = this.pendingSuggestions.clone();
1079
775
  return copy;
1080
776
  }
@@ -1087,7 +783,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1087
783
  stageTargetStyles: (options) => this.stageTargetStyles(options),
1088
784
  createComparisonHeaderFooter: (source, story) => this.createComparisonHeaderFooter(source, story),
1089
785
  matchInlineAtoms: ({ story, targetReviewer, targetStory, targetSnapshot, noteReferenceLabels, ...options }) => {
1090
- if (this.engine.type !== "canonical" || targetReviewer.engine.type !== "canonical") return refuse("match inline atoms against a legacy target");
1091
786
  const result = matchInlineAtomsOnModel({
1092
787
  ...options,
1093
788
  document: this.engine.session.document,
@@ -1111,7 +806,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1111
806
  };
1112
807
  },
1113
808
  matchInlineProvenance: ({ story, targetReviewer: _targetReviewer, targetStory: _targetStory, revisionStamp, ...options }) => {
1114
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer matches on the session");
1115
809
  const { session } = this.engine;
1116
810
  const projected = session.projectStory(canonicalOpStory(story));
1117
811
  if (projected.isErr()) throw projected.error;
@@ -1162,9 +856,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1162
856
  }
1163
857
  /** Resolve on an independent fork, then publish only the complete semantic projection. */
1164
858
  projectComparisonStoriesOnSession(mode) {
1165
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer projects comparison stories");
1166
859
  const copy = this.fork();
1167
- if (copy.engine.type !== "canonical") return panic("A canonical comparison fork must retain its engine");
1168
860
  const handles = copy.listStoryHandlesInternal();
1169
861
  const ids = /* @__PURE__ */ new Set();
1170
862
  let present = false;
@@ -1172,21 +864,22 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1172
864
  ids.add(change.info.id);
1173
865
  present = true;
1174
866
  }
1175
- for (const handle of handles) {
1176
- const state = copy.getEditableStoryState(handle);
1177
- if (!state) continue;
1178
- if (getSuggestions(state).length > 0) throw canonicalReviewerRefusal("project a story holding pending suggestions");
1179
- if (mode === "with-revision-census") {
1180
- const stats = getTrackedChangeStatsFromDoc(state.doc);
1181
- for (const id of stats.ids) ids.add(id);
1182
- present ||= stats.present;
1183
- }
1184
- }
1185
867
  const operations = [];
1186
868
  const session = copy.engine.session;
1187
869
  const unsubscribe = session.onCommitted(({ ops }) => operations.push(...ops));
1188
870
  let stories;
1189
871
  try {
872
+ copy.promoteSuggestionsOnSession(session);
873
+ for (const handle of handles) {
874
+ const state = copy.getEditableStoryState(handle);
875
+ if (!state) continue;
876
+ if (getSuggestions(state).length > 0) throw canonicalReviewerRefusal("project a story holding a suggestion the session will not accept");
877
+ if (mode === "with-revision-census") {
878
+ const stats = getTrackedChangeStatsFromDoc(state.doc);
879
+ for (const id of stats.ids) ids.add(id);
880
+ present ||= stats.present;
881
+ }
882
+ }
1190
883
  stories = handles.map((handle) => {
1191
884
  return {
1192
885
  handle,
@@ -1224,12 +917,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1224
917
  * its journal holds the room's document, which `toBuffer` saves.
1225
918
  */
1226
919
  applyRoomJournal(journal) {
1227
- if (this.engine.type !== "canonical") throw new FolioRoomJournalError({
1228
- message: "Only a canonical reviewer replays a room journal.",
1229
- reason: "legacyEngine",
1230
- expectedRevision: this.roomRevision + 1,
1231
- receivedRevision: journal.at(0)?.revision
1232
- });
1233
920
  for (const batch of journal) {
1234
921
  const expectedRevision = this.roomRevision + 1;
1235
922
  if (batch.revision !== expectedRevision) throw new FolioRoomJournalError({
@@ -1243,7 +930,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1243
930
  }
1244
931
  }
1245
932
  commitOpsOnSession(ops) {
1246
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer commits session operations");
1247
933
  const prepared = this.engine.session.prepareOperations(this.state, ops);
1248
934
  if (prepared.isErr()) {
1249
935
  if (prepared.error.reason === "noChange") return false;
@@ -1252,7 +938,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1252
938
  return this.publishOnSession(prepared.value);
1253
939
  }
1254
940
  stageMappedSectionBoundariesOnSession(options) {
1255
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer stages on the session");
1256
941
  const { session } = this.engine;
1257
942
  const result = stageSectionBoundaryOperations({
1258
943
  document: readModel(session.document),
@@ -1272,34 +957,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1272
957
  documentChanged: result.operations.length > 0 && this.commitOpsOnSession(result.operations)
1273
958
  };
1274
959
  }
1275
- /** Restore the authoritative snapshot into an independent reviewer's collections. */
1276
- restoreReviewerState(snapshot) {
1277
- const { mainState, finalSectionPropertiesOverride, secondaryStoryStates, sectionReferenceRemovals, removedHeaderFooterStories, removedNoteStories, importedStyles, importedMedia, importedHeaders, importedFooters, createdComments, deletedCommentIds, resolvedOverrides, resolvedStoryExpectations, ...unhandled } = snapshot;
1278
- this.state = mainState.apply(mainState.tr);
1279
- this.finalSectionPropertiesOverride = finalSectionPropertiesOverride;
1280
- for (const entry of secondaryStoryStates) this.secondaryStoryStates.set(secondaryStoryKey(entry.handle), {
1281
- handle: entry.handle,
1282
- state: entry.state.apply(entry.state.tr),
1283
- initialState: entry.initialState.apply(entry.initialState.tr)
1284
- });
1285
- this.sectionReferenceRemovals.push(...sectionReferenceRemovals);
1286
- for (const handle of removedHeaderFooterStories) this.removedHeaderFooterStories.set(headerFooterStoryKey(handle), handle);
1287
- for (const handle of removedNoteStories) this.removedNoteStories.set(noteStoryKey(handle), handle);
1288
- this.importedStyles = importedStyles;
1289
- for (const [key, value] of importedMedia) this.importedMedia.set(key, value);
1290
- for (const [key, value] of importedHeaders) this.importedHeaders.set(key, value);
1291
- for (const [key, value] of importedFooters) this.importedFooters.set(key, value);
1292
- this.createdComments.push(...createdComments);
1293
- this.deletedCommentIds = deletedCommentIds;
1294
- for (const [key, value] of resolvedOverrides) this.resolvedOverrides.set(key, value);
1295
- for (const expectation of resolvedStoryExpectations) this.resolvedStoryExpectations.set(editableStoryKey(expectation.story), expectation);
1296
- }
1297
- /**
1298
- * The model the readers read: the parsed package on the legacy engine, the
1299
- * session's document, as it is after every commit, on the canonical one.
1300
- */
960
+ /** The model the readers read: the session's document after every commit. */
1301
961
  get baseDocument() {
1302
- return this.engine.type === "canonical" ? readModel(this.engine.session.document) : this.loadedDocument;
962
+ return readModel(this.engine.session.document);
1303
963
  }
1304
964
  /**
1305
965
  * Publish a commit the session prepared on the reviewer's main state. The
@@ -1307,7 +967,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1307
967
  * throws the session's refusal; nothing falls back to the legacy engine.
1308
968
  */
1309
969
  publishOnSession(commit) {
1310
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer publishes session commits");
1311
970
  const { session } = this.engine;
1312
971
  const published = publishCanonicalProjection({
1313
972
  state: commit.selection.anchor.story === OP_STORIES.MAIN ? this.state : canonicalStoryState(session, commit.transaction.before),
@@ -1337,7 +996,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1337
996
  throw error;
1338
997
  }
1339
998
  const absorptions = prepared.value.touched.absorbed ?? [];
1340
- const sourceSnapshotForStory = (story) => this.pendingSuggestionSource(story, /* @__PURE__ */ new Set());
999
+ const sourceSnapshotForStory = (story) => this.pendingSuggestionSource(story);
1341
1000
  const absorption = absorptions.length === 0 ? null : this.pendingSuggestions.prepareAbsorption({
1342
1001
  survivors: new Map(absorptions.map(({ absorbed, survivor }) => [absorbed, survivor])),
1343
1002
  activeSuggestionIds: this.activeSuggestionIds(),
@@ -1504,38 +1163,14 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1504
1163
  snapshot() {
1505
1164
  return this.snapshotOf(this.state);
1506
1165
  }
1507
- /**
1508
- * The numbering ids every story but `story` defines: the package's and the
1509
- * lists each story started. Numbering ids are package-wide, while a story's
1510
- * state completes its numbering from its own paragraphs only.
1511
- */
1512
- numberingIdsOutside(story) {
1513
- const key = editableStoryKey(story);
1514
- const states = [...story.type === "main" ? [] : [this.state], ...[...this.secondaryStoryStates.values()].filter(({ handle }) => editableStoryKey(handle) !== key).map(({ state }) => state)];
1515
- const numIds = /* @__PURE__ */ new Set();
1516
- const abstractNumIds = /* @__PURE__ */ new Set();
1517
- for (const state of states) {
1518
- const definitions = getDocumentNumbering(state)?.definitions;
1519
- for (const { numId } of definitions?.nums ?? []) numIds.add(numId);
1520
- for (const { abstractNumId } of definitions?.abstractNums ?? []) abstractNumIds.add(abstractNumId);
1521
- }
1522
- return {
1523
- numIds,
1524
- abstractNumIds
1525
- };
1526
- }
1527
1166
  /** Every suggestion id the document's stories still carry. */
1528
1167
  activeSuggestionIds() {
1529
1168
  const active = new Set(getSuggestions(this.state).map(({ suggestionId }) => suggestionId));
1530
- if (this.engine.type === "canonical") {
1531
- for (const handle of this.listStoryHandlesInternal()) {
1532
- if (handle.type === "main") continue;
1533
- const state = this.getEditableStoryState(handle);
1534
- for (const { suggestionId } of state ? getSuggestions(state) : []) active.add(suggestionId);
1535
- }
1536
- return active;
1169
+ for (const handle of this.listStoryHandlesInternal()) {
1170
+ if (handle.type === "main") continue;
1171
+ const state = this.getEditableStoryState(handle);
1172
+ for (const { suggestionId } of state ? getSuggestions(state) : []) active.add(suggestionId);
1537
1173
  }
1538
- for (const entry of this.secondaryStoryStates.values()) for (const { suggestionId } of getSuggestions(entry.state)) active.add(suggestionId);
1539
1174
  return active;
1540
1175
  }
1541
1176
  /** Export staged AI operations for storage by the host, outside the DOCX. */
@@ -1543,44 +1178,40 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1543
1178
  const active = this.activeSuggestionIds();
1544
1179
  return this.pendingSuggestions.exportPendingSuggestions({
1545
1180
  activeSuggestionIds: active,
1546
- snapshotForStory: (story, commentIds) => this.pendingSuggestionSource(story, commentIds),
1547
- stateForStory: (story) => this.engine.type === "canonical" ? this.getEditableStoryState(story) : null
1181
+ snapshotForStory: (story) => this.pendingSuggestionSource(story),
1182
+ stateForStory: (story) => this.getEditableStoryState(story)
1548
1183
  });
1549
1184
  }
1550
1185
  /**
1551
1186
  * A story as a save writes it, every pending suggestion rejected: what a
1552
- * suggestion record's fingerprint describes. On the canonical engine it is
1553
- * read from a session over the document the save writes, so a reviewer
1554
- * reopened on the saved package reads the same story.
1187
+ * suggestion record's fingerprint describes. It is read from a session over
1188
+ * the document the save writes, so a reviewer reopened on the saved package
1189
+ * reads the same story.
1555
1190
  */
1556
- pendingSuggestionSource(story, commentIds) {
1557
- if (this.engine.type === "canonical") {
1558
- if (!this.getEditableStoryState(story)) return null;
1559
- const document = this.toDocument();
1560
- const created = createCanonicalSession(document, document.package.styles);
1561
- if (created.isErr()) throw created.error;
1562
- const saved = new FolioDocxReviewer({
1563
- baseDocument: document,
1564
- originalBuffer: this.originalBuffer,
1565
- state: canonicalReviewerState(created.value),
1566
- author: this.author,
1567
- engine: {
1568
- type: "canonical",
1569
- session: created.value
1570
- },
1571
- positionalParaIds: this.positionalParaIds
1572
- }).getEditableStoryState(story);
1573
- return saved ? createPendingSuggestionSourceSnapshot(saved, /* @__PURE__ */ new Set()) : null;
1574
- }
1575
- const state = this.getEditableStoryState(story);
1576
- return state ? createPendingSuggestionSourceSnapshot(state, commentIds) : null;
1191
+ pendingSuggestionSource(story) {
1192
+ if (!this.getEditableStoryState(story)) return null;
1193
+ const document = this.toDocument();
1194
+ const created = createCanonicalSession(document, document.package.styles);
1195
+ if (created.isErr()) throw created.error;
1196
+ const saved = new FolioDocxReviewer({
1197
+ baseDocument: document,
1198
+ originalBuffer: this.originalBuffer,
1199
+ state: canonicalReviewerState(created.value),
1200
+ author: this.author,
1201
+ engine: {
1202
+ type: "canonical",
1203
+ session: created.value
1204
+ },
1205
+ positionalParaIds: this.positionalParaIds
1206
+ }).getEditableStoryState(story);
1207
+ return saved ? createPendingSuggestionSourceSnapshot(saved, /* @__PURE__ */ new Set()) : null;
1577
1208
  }
1578
1209
  /** Validate saved proposals against this document before restaging them. */
1579
1210
  loadPendingSuggestions(records) {
1580
1211
  return this.pendingSuggestions.loadPendingSuggestions({
1581
1212
  records,
1582
1213
  snapshotForStory: (story) => this.snapshotStory(story),
1583
- sourceSnapshotForStory: (story, commentIds) => this.pendingSuggestionSource(story, commentIds),
1214
+ sourceSnapshotForStory: (story) => this.pendingSuggestionSource(story),
1584
1215
  apply: (record, snapshot) => {
1585
1216
  const restage = {
1586
1217
  undefinedReferences: "refuse",
@@ -1594,12 +1225,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1594
1225
  snapshot,
1595
1226
  author: record.author
1596
1227
  };
1597
- const result = this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1228
+ const result = this.applyDocumentOperationsOnSession({
1598
1229
  ...restage,
1599
1230
  operations: this.engine.operations
1600
- }) : this.applyDocumentOperationsInternal({
1601
- ...restage,
1602
- createUndoEntry: false
1603
1231
  });
1604
1232
  return {
1605
1233
  applied: result.applied,
@@ -1612,11 +1240,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1612
1240
  readNumberingDefinitions(story = MAIN_STORY) {
1613
1241
  const doc = story.type === "main" ? this.state.doc : this.readSecondaryStoryDoc(story);
1614
1242
  if (!doc) return null;
1615
- const numbering = this.engine.type === "canonical" ? storyOwnNumbering({
1243
+ const numbering = storyOwnNumbering({
1616
1244
  current: this.baseDocument.package.numbering,
1617
1245
  loaded: this.loadedDocument.package.numbering,
1618
1246
  doc
1619
- }) : completeNumberingForDoc(this.baseDocument.package.numbering, doc);
1247
+ });
1620
1248
  return numberingLevelsOf(numbering).toSorted((left, right) => left.numId - right.numId || left.level - right.level);
1621
1249
  }
1622
1250
  /** Return parsed package metadata without exposing the mutable document model. */
@@ -1648,39 +1276,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1648
1276
  const sourceState = this.getEditableStoryState(story);
1649
1277
  return sourceState ? this.snapshotOf(sourceState) : null;
1650
1278
  }
1651
- projectComparisonStoriesInternal(mode) {
1652
- const handles = this.listStoryHandlesInternal();
1653
- const ids = /* @__PURE__ */ new Set();
1654
- let present = false;
1655
- if (mode === "with-revision-census") {
1656
- for (const change of this.currentFinalSectionProperties()?.propertyChanges ?? []) {
1657
- ids.add(change.info.id);
1658
- present = true;
1659
- }
1660
- for (const handle of handles) {
1661
- const state = this.getEditableStoryState(handle);
1662
- if (!state) continue;
1663
- const stats = getTrackedChangeStatsFromDoc(state.doc);
1664
- for (const id of stats.ids) ids.add(id);
1665
- present ||= stats.present;
1666
- }
1667
- }
1668
- const stories = [];
1669
- for (const handle of handles) stories.push({
1670
- handle,
1671
- snapshot: this.resolveReviewedStorySnapshotInternal({
1672
- story: handle,
1673
- view: "final"
1674
- })
1675
- });
1676
- return {
1677
- stories,
1678
- revisions: {
1679
- ids: [...ids],
1680
- present
1681
- }
1682
- };
1683
- }
1684
1279
  /**
1685
1280
  * One story's tables, in the document order {@link snapshotStory} numbers
1686
1281
  * them with, read through a reviewed view.
@@ -1717,7 +1312,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1717
1312
  matchStoryTableGeometry({ story = MAIN_STORY, targetTables, pairings, revisionStamp }) {
1718
1313
  const state = this.getEditableStoryState(story);
1719
1314
  if (!state || pairings.length === 0) return revisionStamp.idSeed;
1720
- if (this.engine.type === "canonical") {
1315
+ {
1721
1316
  const matched = matchTableGeometryOperations({
1722
1317
  story: canonicalOpStory(story),
1723
1318
  baseTables: folioStoryTables(state.doc),
@@ -1733,20 +1328,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1733
1328
  if (matched.operations.length > 0) this.commitOpsOnSession(matched.operations);
1734
1329
  return matched.nextRevisionId;
1735
1330
  }
1736
- const transaction = state.tr;
1737
- const { nextRevisionId } = matchTableGeometry({
1738
- tr: transaction,
1739
- baseTables: folioStoryTables(state.doc),
1740
- targetTables,
1741
- pairings,
1742
- revision: {
1743
- author: this.author,
1744
- date: revisionStamp.date,
1745
- idSeed: revisionStamp.idSeed
1746
- }
1747
- });
1748
- if (transaction.docChanged) this.setEditableStoryState(story, state.apply(transaction));
1749
- return nextRevisionId;
1750
1331
  }
1751
1332
  /**
1752
1333
  * Read one story through an immutable reviewed-view projection. A canonical
@@ -1769,35 +1350,13 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1769
1350
  };
1770
1351
  }
1771
1352
  /**
1772
- * Resolve one editable story to its original or final state. A canonical
1773
- * target story holding staged suggestions refuses; resolve those through
1774
- * the suggestion methods first. A lock that prevents any target change
1775
- * from resolving refuses before mutation.
1353
+ * Resolve one editable story to its original or final state, its staged
1354
+ * suggestions with its other changes. A suggestion that reaches another
1355
+ * story resolves only whole, through the suggestion methods. A lock that
1356
+ * prevents any target change from resolving refuses before mutation.
1776
1357
  */
1777
1358
  resolveReviewedStory({ story = MAIN_STORY, view }) {
1778
- if (this.engine.type === "canonical") return this.resolveStoryOnSession(this.engine.session, story, view);
1779
- return this.resolveReviewedStorySnapshotInternal({
1780
- story,
1781
- view
1782
- }) !== null;
1783
- }
1784
- resolveReviewedStorySnapshotInternal({ story = MAIN_STORY, view }) {
1785
- if (!isFolioResolvedReviewedView(view)) throw new UnsupportedFolioReviewedViewError({
1786
- message: "Only original and final views can replace editable story state.",
1787
- receivedView: view
1788
- });
1789
- const sourceState = this.getEditableStoryState(story);
1790
- if (!sourceState) return null;
1791
- const resolvedState = resolveReviewedState(sourceState, view);
1792
- this.setEditableStoryState(story, resolvedState);
1793
- const snapshot = this.snapshotOf(resolvedState);
1794
- const minted = mintedBlockOrdinals(snapshot);
1795
- this.resolvedStoryExpectations.set(editableStoryKey(story), {
1796
- story,
1797
- minted,
1798
- ...resolvedStoryProjection(snapshot, minted)
1799
- });
1800
- return snapshot;
1359
+ return this.resolveStoryOnSession(this.engine.session, story, view);
1801
1360
  }
1802
1361
  /**
1803
1362
  * Apply operations against the current state. Reuses the live-editor applier
@@ -1817,12 +1376,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1817
1376
  ...options.wordDiff !== void 0 && { wordDiff: options.wordDiff },
1818
1377
  undefinedReferences: options.undefinedReferences
1819
1378
  };
1820
- const { applied, skipped } = this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1379
+ const { applied, skipped } = this.applyDocumentOperationsOnSession({
1821
1380
  ...internal,
1822
1381
  operations: this.engine.operations
1823
- }) : this.applyDocumentOperationsInternal({
1824
- ...internal,
1825
- createUndoEntry: false
1826
1382
  });
1827
1383
  return {
1828
1384
  applied,
@@ -1844,12 +1400,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1844
1400
  ...options.wordDiff !== void 0 && { wordDiff: options.wordDiff },
1845
1401
  undefinedReferences: options.undefinedReferences
1846
1402
  };
1847
- return this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1403
+ return this.applyDocumentOperationsOnSession({
1848
1404
  ...internal,
1849
1405
  operations: this.engine.operations
1850
- }) : this.applyDocumentOperationsInternal({
1851
- ...internal,
1852
- createUndoEntry: true
1853
1406
  });
1854
1407
  }
1855
1408
  /** Apply a versioned operation batch to one editable document story. */
@@ -1864,140 +1417,18 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1864
1417
  ...replacementBackground !== void 0 && { replacementBackground },
1865
1418
  undefinedReferences
1866
1419
  };
1867
- return this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1420
+ return this.applyDocumentOperationsOnSession({
1868
1421
  ...internal,
1869
1422
  operations: this.engine.operations
1870
- }) : this.applyDocumentOperationsInternal({
1871
- ...internal,
1872
- createUndoEntry: true
1873
1423
  });
1874
1424
  }
1875
- /** Apply a batch; the notes whose references it deletes or removes follow them. */
1876
- applyDocumentOperationsInternal(options) {
1877
- if (noteReferenceEditsAllowed()) return this.applyDocumentOperationsToStoryState(options);
1878
- return this.withNotesFollowingReferences(() => this.applyDocumentOperationsToStoryState(options));
1879
- }
1880
- applyDocumentOperationsToStoryState({ story, batch, author, snapshot, revisionStamp, wordDiff, tableTemplates, replacementBackground, undefinedReferences, createUndoEntry, restagesSuggestions }) {
1881
- const validatedBatch = parseFolioDocumentOperationBatch(batch);
1882
- const beforeState = this.requireEditableStoryState(story);
1883
- const operationAuthor = author ?? this.author;
1884
- const sourceSnapshot = snapshot ?? this.snapshotOf(beforeState);
1885
- const createdCommentsLengthBefore = this.createdComments.length;
1886
- const beforeStyles = this.importedStyles;
1887
- const definitions = beforeStyles ?? this.loadedDocument.package.styles;
1888
- const candidateStyles = undefinedReferences === "keep" ? definitions : withOperationHeadingStyles(definitions, validatedBatch.operations);
1889
- const candidateState = candidateStyles === definitions ? beforeState : withDocumentStyles(beforeState, candidateStyles);
1890
- const view = {
1891
- state: candidateState,
1892
- dispatch: (transaction) => {
1893
- view.state = view.state.apply(transaction);
1894
- }
1895
- };
1896
- const result = applyFolioDocumentOperationsInPackage({
1897
- view,
1898
- snapshot: sourceSnapshot,
1899
- batch: validatedBatch,
1900
- story: story.type === "main" ? "main" : story,
1901
- author: operationAuthor,
1902
- ...revisionStamp !== void 0 && { revisionStamp },
1903
- ...wordDiff !== void 0 && { wordDiff },
1904
- ...tableTemplates !== void 0 && { tableTemplates },
1905
- ...replacementBackground !== void 0 && { replacementBackground },
1906
- undefinedReferences,
1907
- numberingIdsElsewhere: this.numberingIdsOutside(story),
1908
- ...restagesSuggestions === true ? { restagesSuggestions } : { pendingSuggestionIds: this.activeSuggestionIds() },
1909
- createCommentId: (text) => {
1910
- const comment = createReviewerComment({
1911
- id: this.nextCommentId(),
1912
- text,
1913
- author: operationAuthor,
1914
- date: revisionStamp?.date
1915
- });
1916
- this.createdComments.push(comment);
1917
- return comment.id;
1918
- },
1919
- ...createUndoEntry && { createUndoHandle: () => ({
1920
- type: "documentOperationUndo",
1921
- id: `headless-${String(undoHandleCursor++)}`
1922
- }) }
1923
- });
1924
- const appliedCommentIds = new Set(result.applied.flatMap(({ commentId }) => commentId === void 0 ? [] : [commentId]));
1925
- const createdByBatch = this.createdComments.splice(createdCommentsLengthBefore);
1926
- this.createdComments.push(...createdByBatch.filter((comment) => appliedCommentIds.has(comment.id)));
1927
- if (view.state !== candidateState) this.setEditableStoryState(story, view.state);
1928
- if (candidateStyles !== definitions && view.state !== candidateState) {
1929
- const appliedIds = new Set(result.applied.map(({ id }) => id));
1930
- const committedStyles = withOperationHeadingStyles(definitions, validatedBatch.operations.filter(({ id }) => appliedIds.has(id)));
1931
- if (committedStyles !== definitions) this.installImportedStyles(committedStyles);
1932
- else this.setEditableStoryState(story, withDocumentStyles(view.state, definitions));
1933
- }
1934
- if (batch.mode === "suggested") {
1935
- const activeSuggestionIds = new Set(getSuggestions(beforeState).map(({ suggestionId }) => suggestionId));
1936
- for (const { suggestionId } of getSuggestions(this.state)) activeSuggestionIds.add(suggestionId);
1937
- for (const entry of this.secondaryStoryStates.values()) for (const { suggestionId } of getSuggestions(entry.state)) activeSuggestionIds.add(suggestionId);
1938
- this.pendingSuggestions.recordApplied({
1939
- snapshot: sourceSnapshot,
1940
- story,
1941
- operations: batch.operations,
1942
- applied: result.applied,
1943
- author: operationAuthor,
1944
- activeSuggestionIds
1945
- });
1946
- }
1947
- if (result.undoHandle !== null) {
1948
- this.documentOperationUndoEntries.push({
1949
- undoHandle: result.undoHandle,
1950
- story,
1951
- beforeState,
1952
- afterState: this.requireEditableStoryState(story),
1953
- createdCommentsLengthBefore,
1954
- createdCommentsLengthAfter: this.createdComments.length,
1955
- deletedCommentIds: this.deletedCommentIds,
1956
- beforeStyles,
1957
- afterStyles: this.importedStyles
1958
- });
1959
- const excess = this.documentOperationUndoEntries.length - 100;
1960
- if (excess > 0) this.documentOperationUndoEntries.splice(0, excess);
1961
- }
1962
- return result;
1963
- }
1964
1425
  /**
1965
1426
  * Undo the latest unchanged document-operation batch and its created
1966
1427
  * comments. Only the last {@link FOLIO_DOCUMENT_OPERATION_UNDO_LIMIT}
1967
1428
  * batches are kept; an older handle is `unknownHandle`.
1968
1429
  */
1969
1430
  undoDocumentOperations(undoHandle) {
1970
- if (this.engine.type === "canonical") return this.engine.operations.undo(undoHandle);
1971
- const entryIndex = this.documentOperationUndoEntries.findIndex((entry) => entry.undoHandle.type === undoHandle.type && entry.undoHandle.id === undoHandle.id);
1972
- if (entryIndex === -1) return {
1973
- status: "rejected",
1974
- undoHandle,
1975
- reason: "unknownHandle"
1976
- };
1977
- if (entryIndex !== this.documentOperationUndoEntries.length - 1) return {
1978
- status: "rejected",
1979
- undoHandle,
1980
- reason: "notLatest"
1981
- };
1982
- const entry = this.documentOperationUndoEntries.at(-1);
1983
- if (!entry) return {
1984
- status: "rejected",
1985
- undoHandle,
1986
- reason: "unknownHandle"
1987
- };
1988
- if (this.requireEditableStoryState(entry.story) !== entry.afterState || this.createdComments.length !== entry.createdCommentsLengthAfter || this.deletedCommentIds !== entry.deletedCommentIds || this.importedStyles !== entry.afterStyles) return {
1989
- status: "rejected",
1990
- undoHandle,
1991
- reason: "documentChanged"
1992
- };
1993
- this.withNotesFollowingReferences(() => this.setEditableStoryState(entry.story, entry.beforeState));
1994
- if (entry.beforeStyles !== entry.afterStyles) this.installImportedStyles(entry.beforeStyles, entry.story);
1995
- this.createdComments.length = entry.createdCommentsLengthBefore;
1996
- this.documentOperationUndoEntries.pop();
1997
- return {
1998
- status: "undone",
1999
- undoHandle
2000
- };
1431
+ return this.engine.operations.undo(undoHandle);
2001
1432
  }
2002
1433
  /**
2003
1434
  * The body blocks with their stable ids, in document order — the same
@@ -2064,32 +1495,23 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2064
1495
  type: "header",
2065
1496
  relationshipId
2066
1497
  });
2067
- for (const relationshipId of this.importedHeaders.keys()) handles.push({
2068
- type: "header",
2069
- relationshipId
2070
- });
2071
1498
  for (const relationshipId of pkg.footers?.keys() ?? []) handles.push({
2072
1499
  type: "footer",
2073
1500
  relationshipId
2074
1501
  });
2075
- for (const relationshipId of this.importedFooters.keys()) handles.push({
2076
- type: "footer",
2077
- relationshipId
2078
- });
2079
- const notes = noteStoryInventory(pkg, this.removedNoteStories);
2080
- for (const footnote of notes.footnotes ?? []) if (!isSeparatorFootnote(footnote)) handles.push({
1502
+ for (const footnote of pkg.footnotes ?? []) if (!isSeparatorFootnote(footnote)) handles.push({
2081
1503
  type: "footnote",
2082
1504
  noteId: footnote.id
2083
1505
  });
2084
- for (const endnote of notes.endnotes ?? []) if (!isSeparatorEndnote(endnote)) handles.push({
1506
+ for (const endnote of pkg.endnotes ?? []) if (!isSeparatorEndnote(endnote)) handles.push({
2085
1507
  type: "endnote",
2086
1508
  noteId: endnote.id
2087
1509
  });
2088
- const retired = this.engine.type === "canonical" ? this.engine.session.retiredHeaderFooters() : void 0;
1510
+ const retired = this.engine.session.retiredHeaderFooters();
2089
1511
  return handles.filter((handle) => {
2090
1512
  if (handle.type === "header" || handle.type === "footer") {
2091
1513
  const key = headerFooterStoryKey(handle);
2092
- return !this.removedHeaderFooterStories.has(key) && !retired?.has(key);
1514
+ return !retired.has(key);
2093
1515
  }
2094
1516
  return true;
2095
1517
  });
@@ -2140,7 +1562,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2140
1562
  if (!doc) continue;
2141
1563
  for (const id of coveredCommentIdsInProseDoc(doc)) covered.add(id);
2142
1564
  }
2143
- const definitions = this.withResolvedOverrides(this.keptCommentThreads(this.currentCommentDefinitions(), this.state, this.secondaryStoryStates.values()).filter(({ id, parentId, anchorKind }) => anchorKind !== "range" || parentId !== void 0 || covered.has(id)));
1565
+ const definitions = this.keptCommentThreads(this.currentCommentDefinitions(), this.state).filter(({ id, parentId, anchorKind }) => anchorKind !== "range" || parentId !== void 0 || covered.has(id));
2144
1566
  if (definitions.length === 0) return [];
2145
1567
  const repliesByParent = /* @__PURE__ */ new Map();
2146
1568
  const topLevel = [];
@@ -2194,36 +1616,17 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2194
1616
  roots.set(id, parentId !== void 0 && knownIds.has(parentId) ? "reply" : "thread");
2195
1617
  }
2196
1618
  if (removed.size === 0) return { deleted: [] };
2197
- if (this.engine.type === "canonical") {
2198
- const prepared = this.engine.session.prepareOperations(this.state, [...roots].map(([id, scope]) => ({
2199
- type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
2200
- id,
2201
- scope
2202
- })));
2203
- if (prepared.isErr()) throw prepared.error;
2204
- this.publishOnSession(prepared.value);
2205
- } else this.deleteCommentAnchors(removed);
1619
+ const prepared = this.engine.session.prepareOperations(this.state, [...roots].map(([id, scope]) => ({
1620
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
1621
+ id,
1622
+ scope
1623
+ })));
1624
+ if (prepared.isErr()) throw prepared.error;
1625
+ this.publishOnSession(prepared.value);
2206
1626
  return { deleted: [...removed].sort((left, right) => left - right) };
2207
1627
  }
2208
1628
  currentCommentDefinitions() {
2209
- return [...this.baseDocument.package.document.comments ?? [], ...this.createdComments].filter(({ id }) => !this.deletedCommentIds.has(id));
2210
- }
2211
- deleteCommentAnchors(ids) {
2212
- for (const story of this.listStoryHandlesInternal()) this.getEditableStoryState(story);
2213
- const edits = [{
2214
- handle: MAIN_STORY,
2215
- state: this.state
2216
- }, ...this.secondaryStoryStates.values()].flatMap(({ handle, state }) => {
2217
- const transaction = state.tr;
2218
- removeCommentAnchors(transaction, ids);
2219
- return transaction.docChanged ? [{
2220
- handle,
2221
- state: state.apply(transaction)
2222
- }] : [];
2223
- });
2224
- for (const { handle, state } of edits) this.setEditableStoryState(handle, state);
2225
- this.deletedCommentIds = /* @__PURE__ */ new Set([...this.deletedCommentIds, ...ids]);
2226
- for (const id of ids) this.resolvedOverrides.delete(id);
1629
+ return [...this.baseDocument.package.document.comments ?? []];
2227
1630
  }
2228
1631
  /**
2229
1632
  * Add a reply to a comment thread. Pass a {@link FolioReviewComment} from
@@ -2236,56 +1639,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2236
1639
  */
2237
1640
  replyTo(target, input) {
2238
1641
  const parentId = typeof target === "number" ? target : target.id;
2239
- if (this.engine.type === "canonical") return this.replyOnSession(this.engine.session, parentId, input);
2240
- const existing = this.currentCommentDefinitions();
2241
- const reply = createReply({
2242
- comments: existing,
2243
- parentCommentId: parentId,
2244
- input: {
2245
- author: input.author ?? this.author,
2246
- text: input.text,
2247
- ...input.initials !== void 0 ? { initials: input.initials } : {},
2248
- ...input.date !== void 0 && { date: input.date }
2249
- },
2250
- commentIds: this.commentIds
2251
- });
2252
- if (!reply) return null;
2253
- this.createdComments.push(reply);
2254
- this.anchorReplyInEditor({
2255
- parentId: reply.parentId ?? parentId,
2256
- replyId: reply.id
2257
- });
2258
- return {
2259
- id: reply.id,
2260
- author: reply.author,
2261
- date: reply.date ?? null,
2262
- text: input.text
2263
- };
2264
- }
2265
- anchorReplyInEditor({ parentId, replyId }) {
2266
- for (const story of this.listStoryHandlesInternal()) {
2267
- const state = this.getEditableStoryState(story);
2268
- if (!state) continue;
2269
- const commentMark = state.schema.marks["comment"];
2270
- const referenceNode = state.schema.nodes["commentReference"];
2271
- if (!commentMark || !referenceNode) continue;
2272
- let from = null;
2273
- let to = 0;
2274
- let referenceAt = null;
2275
- state.doc.descendants((node, pos) => {
2276
- if (node.type === referenceNode && node.attrs["commentId"] === parentId) referenceAt ??= pos + node.nodeSize;
2277
- if (node.isInline && node.marks.some((mark) => mark.type === commentMark && mark.attrs["commentId"] === parentId)) {
2278
- from ??= pos;
2279
- to = pos + node.nodeSize;
2280
- }
2281
- });
2282
- if (referenceAt === null || from === null || from >= to) continue;
2283
- let transaction = state.tr;
2284
- transaction = transaction.addMark(from, to, commentMark.create({ commentId: replyId }));
2285
- transaction = transaction.insert(referenceAt, referenceNode.create({ commentId: replyId }));
2286
- this.setEditableStoryState(story, state.apply(transaction));
2287
- return;
2288
- }
1642
+ return this.replyOnSession(this.engine.session, parentId, input);
2289
1643
  }
2290
1644
  /**
2291
1645
  * Mark a comment thread resolved, or reopen a previously resolved one. Pass
@@ -2301,11 +1655,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2301
1655
  */
2302
1656
  resolveComment(commentId, options = {}) {
2303
1657
  const resolved = options.resolved ?? true;
2304
- if (this.engine.type === "canonical") return this.resolveCommentOnSession(this.engine.session, commentId, resolved);
2305
- const target = this.currentCommentDefinitions().find((comment) => String(comment.id) === commentId);
2306
- if (!target) return false;
2307
- this.resolvedOverrides.set(target.id, resolved);
2308
- return true;
1658
+ return this.resolveCommentOnSession(this.engine.session, commentId, resolved);
2309
1659
  }
2310
1660
  /** Run a semantic comment command as one session commit, as the editor does. */
2311
1661
  commitCommentOnSession(session, command) {
@@ -2399,47 +1749,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2399
1749
  };
2400
1750
  }
2401
1751
  currentFinalSectionProperties() {
2402
- return this.finalSectionPropertiesOverride ?? this.baseDocument.package.document.finalSectionProperties;
2403
- }
2404
- stageFinalSectionProperties(options) {
2405
- const staged = stagedFinalSectionProperties({
2406
- ...options,
2407
- author: this.author
2408
- });
2409
- if (!staged) return false;
2410
- this.finalSectionPropertiesOverride = staged;
2411
- return true;
2412
- }
2413
- stageMappedSectionBoundaries({ target, originalRevisionIdSeed, maxRanges, revision, mapTargetProperties }) {
2414
- const result = stageSectionBoundaryProperties({
2415
- state: this.state,
2416
- target,
2417
- originalRevisionIdSeed,
2418
- revisionStamp: revision,
2419
- author: this.author,
2420
- maxRanges,
2421
- mapTargetProperties
2422
- });
2423
- if (result.status !== "matched") return result;
2424
- const documentChanged = result.transaction.docChanged;
2425
- if (documentChanged) this.state = this.state.apply(result.transaction);
2426
- return {
2427
- status: "matched",
2428
- rangeCount: result.rangeCount,
2429
- nextRevisionId: result.nextRevisionId,
2430
- documentChanged
2431
- };
2432
- }
2433
- resolveFinalSectionProperties(mode, id) {
2434
- const current = this.currentFinalSectionProperties();
2435
- const resolved = current && resolveSectionChange({
2436
- current,
2437
- decision: mode,
2438
- id
2439
- });
2440
- if (!resolved) return 0;
2441
- this.finalSectionPropertiesOverride = resolved;
2442
- return 1;
1752
+ return this.baseDocument.package.document.finalSectionProperties;
2443
1753
  }
2444
1754
  /**
2445
1755
  * Accept an existing tracked change, keeping its text and dropping the
@@ -2452,64 +1762,22 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2452
1762
  * removal. A held change stays pending as it is.
2453
1763
  */
2454
1764
  acceptChange(target) {
2455
- if (this.engine.type === "canonical") return this.resolveChangeOnSession(target, "accept");
2456
- return this.resolveWithSectionReferenceHistory(() => this.withNotesFollowingReferences(() => this.acceptChangeInternal(target)));
2457
- }
2458
- acceptChangeInternal(target) {
2459
- const id = revisionIdOf(target);
2460
- const ids = getTrackedChangeGroupIdsFromDoc(this.state.doc, id);
2461
- if (revisionResolutionLockViolation(this.state, ids, "accept") !== null) return false;
2462
- const suggestionId = suggestionIdOfRevision(this.state, id);
2463
- if (suggestionId !== null && !this.runCommand(acceptSuggestion(suggestionId, { author: this.author }))) return false;
2464
- let bodyChanged = false;
2465
- for (const memberId of ids) bodyChanged = this.runCommand(acceptAIEditRevision(memberId)) || bodyChanged;
2466
- const sectionChanged = this.resolveFinalSectionProperties("accept", id) > 0;
2467
- return bodyChanged || sectionChanged;
1765
+ return this.resolveChangeOnSession(target, "accept");
2468
1766
  }
2469
1767
  /**
2470
1768
  * Reject an existing tracked change: an insertion's text is removed, a
2471
1769
  * deletion's text is restored. See {@link acceptChange} for targeting.
2472
1770
  */
2473
1771
  rejectChange(target) {
2474
- if (this.engine.type === "canonical") return this.resolveChangeOnSession(target, "reject");
2475
- return this.resolveWithSectionReferenceHistory(() => this.withNotesFollowingReferences(() => this.rejectChangeInternal(target)));
2476
- }
2477
- rejectChangeInternal(target) {
2478
- const id = revisionIdOf(target);
2479
- const ids = getTrackedChangeGroupIdsFromDoc(this.state.doc, id);
2480
- if (revisionResolutionLockViolation(this.state, ids, "reject") !== null) return false;
2481
- const suggestionId = suggestionIdOfRevision(this.state, id);
2482
- if (suggestionId !== null && this.runCommand(rejectSuggestion(suggestionId))) return true;
2483
- let bodyChanged = false;
2484
- for (const memberId of ids) bodyChanged = this.runCommand(rejectAIEditRevision(memberId)) || bodyChanged;
2485
- const sectionChanged = this.resolveFinalSectionProperties("reject", id) > 0;
2486
- return bodyChanged || sectionChanged;
1772
+ return this.resolveChangeOnSession(target, "reject");
2487
1773
  }
2488
1774
  /** Convert one pending suggestion into an ordinary tracked change. */
2489
1775
  acceptSuggestion(suggestionId, options) {
2490
- if (this.engine.type === "canonical") return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "accept", options?.author ?? this.author);
2491
- return this.resolveWithSectionReferenceHistory(() => {
2492
- let accepted = false;
2493
- for (const handle of this.listStoryHandlesInternal()) {
2494
- const state = this.getEditableStoryState(handle);
2495
- if (!state || !getSuggestions(state).some((entry) => entry.suggestionId === suggestionId)) continue;
2496
- accepted = this.runStoryCommand(acceptSuggestion(suggestionId, { author: options?.author ?? this.author }), handle) || accepted;
2497
- }
2498
- return accepted;
2499
- });
1776
+ return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "accept", options?.author ?? this.author);
2500
1777
  }
2501
1778
  /** Remove one pending suggestion without applying it. */
2502
1779
  rejectSuggestion(suggestionId) {
2503
- if (this.engine.type === "canonical") return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "reject", this.author);
2504
- return this.resolveWithSectionReferenceHistory(() => {
2505
- let rejected = false;
2506
- for (const handle of this.listStoryHandlesInternal()) {
2507
- const state = this.getEditableStoryState(handle);
2508
- if (!state || !getSuggestions(state).some((entry) => entry.suggestionId === suggestionId)) continue;
2509
- rejected = this.runStoryCommand(rejectSuggestion(suggestionId), handle) || rejected;
2510
- }
2511
- return rejected;
2512
- });
1780
+ return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "reject", this.author);
2513
1781
  }
2514
1782
  /**
2515
1783
  * Accept every ordinary tracked change in the package. Pending suggestions
@@ -2525,11 +1793,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2525
1793
  * ordinary changes resolved.
2526
1794
  */
2527
1795
  acceptAll() {
2528
- return this.engine.type === "canonical" ? this.resolveAllOnSession(this.engine.session, "accept") : this.resolveAll("accept");
1796
+ return this.resolveAllOnSession(this.engine.session, "accept");
2529
1797
  }
2530
1798
  /** Reject every tracked change in the package. See {@link acceptAll}. */
2531
1799
  rejectAll() {
2532
- return this.engine.type === "canonical" ? this.resolveAllOnSession(this.engine.session, "reject") : this.resolveAll("reject");
1800
+ return this.resolveAllOnSession(this.engine.session, "reject");
2533
1801
  }
2534
1802
  /**
2535
1803
  * One change of the body, resolved by the session's review intent: every
@@ -2537,7 +1805,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2537
1805
  * several ids) resolves together, as the editor resolves it.
2538
1806
  */
2539
1807
  resolveChangeOnSession(target, resolution) {
2540
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer resolves on the session");
2541
1808
  const { session } = this.engine;
2542
1809
  const id = revisionIdOf(target);
2543
1810
  const suggestionId = suggestionIdOfRevision(this.state, id);
@@ -2628,259 +1895,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2628
1895
  ...outcome.absorbedBlocks.length === 0 ? {} : { absorbedBlocks: outcome.absorbedBlocks }
2629
1896
  };
2630
1897
  }
2631
- resolveAll(mode) {
2632
- return this.resolveWithSectionReferenceHistory(() => {
2633
- const skipped = [];
2634
- return {
2635
- resolved: this.resolveEveryStory(mode, skipped) + this.resolveEveryFinalSectionChange(mode),
2636
- skipped
2637
- };
2638
- });
2639
- }
2640
- resolveWithSectionReferenceHistory(resolve) {
2641
- const before = captureSectionReferenceInventory(this.state.doc, this.currentFinalSectionProperties());
2642
- const result = resolve();
2643
- const removedEndpointReferences = getTrackedSectionEndpointRemoval(this.state)?.removedReferences ?? [];
2644
- if (before.revisionRelationships.size > 0 || removedEndpointReferences.length > 0) {
2645
- const after = captureSectionReferenceInventory(this.state.doc, this.currentFinalSectionProperties());
2646
- const removed = resolvedSectionReferenceLosses({
2647
- before,
2648
- after
2649
- });
2650
- this.sectionReferenceRemovals.push(...removed);
2651
- for (const reference of [...removed, ...removedEndpointReferences]) {
2652
- if (after.references.some(({ part, relationshipId }) => part === reference.part && relationshipId === reference.relationshipId)) continue;
2653
- const handle = {
2654
- type: reference.part,
2655
- relationshipId: reference.relationshipId
2656
- };
2657
- this.removedHeaderFooterStories.set(headerFooterStoryKey(handle), handle);
2658
- }
2659
- }
2660
- return result;
2661
- }
2662
- resolveEveryFinalSectionChange(mode) {
2663
- const current = this.currentFinalSectionProperties();
2664
- const resolved = current && resolveSectionChanges(current, mode);
2665
- if (!resolved) return 0;
2666
- this.finalSectionPropertiesOverride = resolved;
2667
- return current?.propertyChanges?.length ?? 0;
2668
- }
2669
- resolveEveryStory(mode, skipped) {
2670
- return this.withNotesFollowingReferences(() => this.resolveEveryStoryOnce(mode, skipped));
2671
- }
2672
- /**
2673
- * Change the body the way a note follows its reference: a note whose
2674
- * reference goes, goes too, as a note no text refers to does; a note whose
2675
- * reference an edit deletes as a tracked change has its text deleted with
2676
- * it; a note whose reference's deletion is rejected gets back the text that
2677
- * deletion took.
2678
- */
2679
- withNotesFollowingReferences(change) {
2680
- const before = this.state.doc;
2681
- const result = change();
2682
- const after = this.state.doc;
2683
- const referencedAfter = referencedNoteKeys(after);
2684
- for (const key of referencedAfter) this.removedNoteStories.delete(key);
2685
- const unreferenced = new Set([...referencedNoteKeys(before)].filter((key) => !referencedAfter.has(key)));
2686
- const referencedElsewhere = unreferenced.size > 0 ? this.noteKeysReferencedOutsideBody(unreferenced) : /* @__PURE__ */ new Set();
2687
- for (const key of unreferenced) {
2688
- if (referencedElsewhere.has(key)) continue;
2689
- const handle = noteStoryHandleOf(key);
2690
- if (handle) this.removedNoteStories.set(noteStoryKey(handle), handle);
2691
- }
2692
- const rejectedDeletions = referenceDeletions(before);
2693
- for (const key of noteReferencesRestored(before, after)) {
2694
- const handle = noteStoryHandleOf(key);
2695
- const state = handle ? this.getEditableStoryState(handle) : null;
2696
- const reference = rejectedDeletions.get(key);
2697
- const revisions = state && reference ? noteDeletionRevisions(state.doc, reference) : [];
2698
- if (handle && revisions.length > 0) this.runStoryCommand(rejectAIEditRevision(revisions), handle);
2699
- }
2700
- this.deleteNotesWithTheirReferences(before, after);
2701
- return result;
2702
- }
2703
- /** Delete the text of each note whose reference went from live to a tracked deletion. */
2704
- deleteNotesWithTheirReferences(before, after) {
2705
- const was = noteReferenceStates(before);
2706
- const deletions = referenceDeletions(after);
2707
- for (const [key, state] of noteReferenceStates(after)) {
2708
- if (state !== "deleted" || was.get(key) !== "live") continue;
2709
- const reference = deletions.get(key);
2710
- if (!reference || reference.attrs["provenance"] === "suggested" || reference.attrs["moveKind"] != null) continue;
2711
- const handle = noteStoryHandleOf(key);
2712
- if (!handle || this.removedNoteStories.has(noteStoryKey(handle))) continue;
2713
- this.runStoryCommand((storyState, dispatch) => {
2714
- const transaction = deleteNoteWithReference(storyState.tr, reference);
2715
- if (!transaction.docChanged) return false;
2716
- dispatch?.(transaction);
2717
- return true;
2718
- }, handle);
2719
- }
2720
- }
2721
- /**
2722
- * The notes a story other than the body refers to (a header, a footer, a
2723
- * comment, another note), leaving out references inside the `skipped` notes.
2724
- */
2725
- noteKeysReferencedOutsideBody(skipped) {
2726
- const keys = new Set(noteKeysReferencedIn(this.currentCommentDefinitions()));
2727
- for (const handle of this.listStoryHandlesInternal()) {
2728
- if (handle.type === "main") continue;
2729
- let source;
2730
- if (handle.type === "footnote" || handle.type === "endnote") {
2731
- if (skipped.has(noteStoryKey(handle))) continue;
2732
- source = this.getNoteStory(handle);
2733
- } else source = this.getHeaderFooterStory(handle);
2734
- const state = this.secondaryStoryStates.get(secondaryStoryKey(handle))?.state;
2735
- const found = state ? referencedNoteKeys(state.doc) : noteKeysReferencedIn(source?.content ?? []);
2736
- for (const key of found) keys.add(key);
2737
- }
2738
- return keys;
2739
- }
2740
- resolveEveryStoryOnce(mode, skipped) {
2741
- let count = 0;
2742
- const resolvedStories = [];
2743
- const refreshes = [];
2744
- const stories = this.listStoryHandlesInternal().flatMap((handle) => {
2745
- const state = this.getEditableStoryState(handle);
2746
- if (!state) return [];
2747
- const held = lockHeldChanges(state, mode);
2748
- const carried = revisionIdsCarriedByResolution(state.doc, mode);
2749
- return [{
2750
- source: {
2751
- handle,
2752
- state
2753
- },
2754
- changes: getTrackedChangesFromDoc(state.doc).map(({ id }) => {
2755
- const { carries, moves } = carriedByGroup(id, getTrackedChangeGroupIdsFromDoc(state.doc, id), carried);
2756
- return {
2757
- id,
2758
- suggestionId: suggestionIdOfRevision(state, id),
2759
- violation: held.get(id),
2760
- carries,
2761
- moves
2762
- };
2763
- })
2764
- }];
2765
- });
2766
- const classified = classifyReviewLocks({
2767
- stories,
2768
- grouping: mode === "reject" ? "whole-proposal" : "individual-change"
2769
- });
2770
- for (const { source: { handle, state }, changes } of classified.stories) {
2771
- const held = /* @__PURE__ */ new Map();
2772
- for (const entry of changes) switch (entry.type) {
2773
- case "held":
2774
- held.set(entry.change.id, entry.violation);
2775
- break;
2776
- case "free": break;
2777
- default: return panic("Unknown classified review lock", { entry });
2778
- }
2779
- if (held.size > 0) {
2780
- count += this.resolveStoryAroundHeldChanges(handle, mode, held, skipped);
2781
- continue;
2782
- }
2783
- const ordinaryCount = getTrackedChangesFromDoc(state.doc).filter(({ id }) => mode === "reject" || suggestionIdOfRevision(state, id) === null).length;
2784
- count += ordinaryCount;
2785
- const withSuggestions = mode === "accept" && ordinaryCount > 0 && getSuggestions(state).length > 0 ? this.acceptOrdinaryChangesWithSuggestions(state, handle) : null;
2786
- if (withSuggestions) refreshes.push(withSuggestions.refresh);
2787
- let resolvedState = state;
2788
- if (mode === "reject") resolvedState = resolveAllChangesInHeadlessState(rejectEverySuggestion(state), mode);
2789
- else if (ordinaryCount > 0) resolvedState = withSuggestions?.state ?? resolveAllChangesInHeadlessState(state, mode);
2790
- resolvedStories.push({
2791
- handle,
2792
- state: resolvedState
2793
- });
2794
- }
2795
- for (const { handle, state } of resolvedStories) this.setEditableStoryState(handle, state);
2796
- if (refreshes.length > 0) {
2797
- const activeSuggestionIds = new Set(getSuggestions(this.state).map(({ suggestionId }) => suggestionId));
2798
- for (const entry of this.secondaryStoryStates.values()) for (const { suggestionId } of getSuggestions(entry.state)) activeSuggestionIds.add(suggestionId);
2799
- for (const refresh of refreshes) refresh(activeSuggestionIds);
2800
- }
2801
- return count;
2802
- }
2803
- /**
2804
- * Resolve each change of a story a content control's lock does not hold, on
2805
- * its own: the one-pass resolver takes the whole story or nothing. The held
2806
- * changes stay pending as they are and are reported in `skipped`.
2807
- */
2808
- resolveStoryAroundHeldChanges(handle, mode, held, skipped) {
2809
- for (const [id, violation] of held) skipped.push({
2810
- id,
2811
- reason: CONTENT_CONTROL_LOCK,
2812
- message: lockedControlMessage(violation)
2813
- });
2814
- const state = this.getEditableStoryState(handle);
2815
- if (!state) return 0;
2816
- let resolved = 0;
2817
- for (const { id } of getTrackedChangesFromDoc(state.doc).toReversed()) {
2818
- if (held.has(id)) continue;
2819
- const current = this.getEditableStoryState(handle);
2820
- if (!current) break;
2821
- const ids = getTrackedChangeGroupIdsFromDoc(current.doc, id);
2822
- if (ids.length === 0) continue;
2823
- const resolveOne = mode === "accept" ? acceptAIEditRevision(ids) : rejectAIEditRevision(ids);
2824
- if (this.runStoryCommand(resolveOne, handle)) resolved += 1;
2825
- }
2826
- return resolved;
2827
- }
2828
- acceptOrdinaryChangesWithSuggestions(state, story) {
2829
- const originalSuggestions = getSuggestions(state);
2830
- const records = this.exportPendingSuggestions().filter((record) => editableStoryKey(record.story) === editableStoryKey(story));
2831
- const recordedIds = new Set(records.map(({ suggestionId }) => suggestionId));
2832
- if (originalSuggestions.some(({ suggestionId }) => !recordedIds.has(suggestionId))) panic("A pending suggestion has no operation to restage after bulk acceptance");
2833
- let clean = rejectEverySuggestion(state);
2834
- const restagedCommentIds = new Set(records.flatMap(({ commentId }) => commentId === void 0 ? [] : [commentId]));
2835
- clean = withoutPendingSuggestionCommentMarks(clean, restagedCommentIds);
2836
- let resolved = resolveAllChangesInHeadlessState(clean, "accept");
2837
- const restaged = [];
2838
- for (const record of records) {
2839
- const snapshot = this.snapshotOf(resolved);
2840
- const view = {
2841
- state: resolved,
2842
- dispatch: (transaction) => {
2843
- view.state = view.state.apply(transaction);
2844
- }
2845
- };
2846
- const applied = applyFolioDocumentOperationsInPackage({
2847
- undefinedReferences: "refuse",
2848
- restagesSuggestions: true,
2849
- numberingIdsElsewhere: this.numberingIdsOutside(story),
2850
- view,
2851
- snapshot,
2852
- batch: {
2853
- version: 1,
2854
- mode: "suggested",
2855
- operations: [record.operation]
2856
- },
2857
- story: story.type === "main" ? "main" : story,
2858
- author: record.author,
2859
- createCommentId: () => {
2860
- if (record.commentId === void 0) panic("A staged comment suggestion has no comment id", { suggestionId: record.suggestionId });
2861
- return record.commentId;
2862
- }
2863
- }).applied.find(({ id }) => id === record.operation.id);
2864
- if (!applied) continue;
2865
- restaged.push({
2866
- snapshot,
2867
- operation: record.operation,
2868
- applied,
2869
- author: record.author
2870
- });
2871
- resolved = view.state;
2872
- }
2873
- const restagedIds = new Set(getSuggestions(resolved).map(({ suggestionId }) => suggestionId));
2874
- if (restaged.some(({ applied }) => !restagedIds.has(applied.suggestionId ?? applied.id))) panic("Bulk acceptance lost a pending suggestion");
2875
- return {
2876
- state: resolved,
2877
- refresh: (activeSuggestionIds) => this.pendingSuggestions.replaceRestagedStory({
2878
- story,
2879
- restaged,
2880
- activeSuggestionIds
2881
- })
2882
- };
2883
- }
2884
1898
  /** Resolve ordinary revisions on a detached in-memory document. */
2885
1899
  toResolvedDocument(decision) {
2886
1900
  return this.resolvedCopy(decision === "accept" ? "final" : "original").toDocument();
@@ -2892,23 +1906,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2892
1906
  * way, or a legacy reviewer over the model that resolution returns.
2893
1907
  */
2894
1908
  resolvedCopy(view) {
2895
- if (this.engine.type === "canonical") return this.resolvedSessionCopy(this.engine.session, view);
2896
- const resolved = resolvedDocumentView(this.toDocument(), view === "final" ? "accept" : "reject");
2897
- if (resolved.unresolved.length > 0) throw new FolioResolvedViewRefusedError({
2898
- message: `The ${view} view cannot be read: the changes of ${resolved.unresolved.length} stories do not resolve.`,
2899
- view,
2900
- stories: resolved.unresolved
2901
- });
2902
- const rendered = normalizeListModelRendering(resolved.document, { inverse: "omit" }).document;
2903
- return FolioDocxReviewer.legacyOver(rendered, {
2904
- originalBuffer: this.originalBuffer,
2905
- author: this.author,
2906
- positionalParaIds: this.storyPositionalParaIds()
2907
- });
1909
+ return this.resolvedSessionCopy(this.engine.session, view);
2908
1910
  }
2909
1911
  /** The {@link resolvedCopy} a reader takes one story of. */
2910
1912
  resolvedReader(view) {
2911
- return this.engine.type === "canonical" ? this.resolvedSessionReader(this.engine.session, view) : this.resolvedCopy(view);
1913
+ return this.resolvedSessionReader(this.engine.session, view);
2912
1914
  }
2913
1915
  /**
2914
1916
  * The {@link resolvedSessionCopy} a reader takes one story of: the stories
@@ -2927,19 +1929,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2927
1929
  return reviewer;
2928
1930
  }
2929
1931
  /**
2930
- * The paragraph ids this reviewer's stories read as positional: ids it
2931
- * minted where the package named none, which `toDocument` writes as ids.
2932
- */
2933
- storyPositionalParaIds() {
2934
- const ids = new Set(this.positionalParaIds);
2935
- const states = [this.state, ...[...this.secondaryStoryStates.values()].map(({ state }) => state)];
2936
- for (const { doc } of states) doc.descendants((node) => {
2937
- const paraId = node.attrs["paraId"];
2938
- if (node.attrs["idStability"] === "positional" && typeof paraId === "string") ids.add(paraId);
2939
- });
2940
- return ids;
2941
- }
2942
- /**
2943
1932
  * A reviewer on a second session over the current document, as a reviewer
2944
1933
  * reopened on it would hold it, with every change resolved to `view`. This
2945
1934
  * reviewer's session and journal are left as they are; what the session
@@ -2961,6 +1950,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2961
1950
  positionalParaIds: this.positionalParaIds
2962
1951
  });
2963
1952
  copy.pendingSuggestions = this.pendingSuggestions.clone();
1953
+ if (view === "final") copy.promoteSuggestionsOnSession(created.value);
2964
1954
  if ((view === "final" ? copy.acceptAll() : copy.rejectAll()).skipped.length > 0) throw new CanonicalSessionError({
2965
1955
  reason: "refused",
2966
1956
  ground: { rule: CANONICAL_RULE.contentControlLock },
@@ -2970,6 +1960,43 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2970
1960
  return copy;
2971
1961
  }
2972
1962
  /**
1963
+ * Turn every staged suggestion into an ordinary tracked change, so that
1964
+ * accepting every change accepts the suggestions too.
1965
+ */
1966
+ promoteSuggestionsOnSession(session) {
1967
+ for (const suggestionId of this.activeSuggestionIds()) this.resolveSuggestionOnSession(session, suggestionId, "accept", this.author);
1968
+ }
1969
+ /**
1970
+ * A story holding staged suggestions resolved to `view`: its suggestions
1971
+ * resolve with its other changes, on a fork, and the fork's operations
1972
+ * land here as one commit, so a refusal leaves this reviewer as it was. A
1973
+ * suggestion that reaches another story resolves only whole, so resolving
1974
+ * one of its stories refuses.
1975
+ */
1976
+ resolveStoryWithSuggestions({ story, view, staged }) {
1977
+ const key = editableStoryKey(story);
1978
+ for (const handle of this.listStoryHandlesInternal()) {
1979
+ if (editableStoryKey(handle) === key) continue;
1980
+ const other = this.getEditableStoryState(handle);
1981
+ if (other && getSuggestions(other).some(({ suggestionId }) => staged.has(suggestionId))) throw canonicalReviewerRefusal("resolve one story of a suggestion that reaches another");
1982
+ }
1983
+ const copy = this.fork();
1984
+ const { session } = copy.engine;
1985
+ const operations = [];
1986
+ const unsubscribe = session.onCommitted(({ ops }) => operations.push(...ops));
1987
+ let resolved;
1988
+ try {
1989
+ for (const suggestionId of staged) copy.resolveSuggestionOnSession(session, suggestionId, view === "final" ? "accept" : "reject", this.author);
1990
+ const after = copy.getEditableStoryState(story);
1991
+ if (after && getSuggestions(after).length > 0) throw canonicalReviewerRefusal("resolve a story holding a suggestion the session will not resolve");
1992
+ resolved = copy.resolveStoryOnSession(session, story, view);
1993
+ } finally {
1994
+ unsubscribe();
1995
+ }
1996
+ if (operations.length > 0) this.commitOpsOnSession(operations);
1997
+ return resolved;
1998
+ }
1999
+ /**
2973
2000
  * Resolve one story's changes to `view` in one session commit: the body's
2974
2001
  * through the review intent, another story's as its resolution operation.
2975
2002
  */
@@ -2980,7 +2007,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2980
2007
  });
2981
2008
  const state = this.getEditableStoryState(story);
2982
2009
  if (!state) return false;
2983
- if (getSuggestions(state).length > 0) throw canonicalReviewerRefusal("resolve a story holding pending suggestions");
2010
+ const staged = new Set(getSuggestions(state).map(({ suggestionId }) => suggestionId));
2011
+ if (staged.size > 0) return this.resolveStoryWithSuggestions({
2012
+ story,
2013
+ view,
2014
+ staged
2015
+ });
2984
2016
  const resolution = view === "final" ? "accept" : "reject";
2985
2017
  const section = story.type === "main" ? this.finalSectionOperation((current) => resolveSectionChanges(current, resolution)) : null;
2986
2018
  const groups = listedRevisionGroups(state.doc).map(({ groupIds }) => groupIds);
@@ -3021,184 +2053,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3021
2053
  }
3022
2054
  /** The current document model with edits merged back in. */
3023
2055
  toDocument() {
3024
- if (this.engine.type === "canonical") {
3025
- const model = withoutPendingSuggestions(this.engine.session.captureSaveSnapshot().document);
3026
- if (model.isErr()) throw model.error;
3027
- return cloneDocumentWithParagraphPropertySources(reconcileDocumentPartRelationships(model.value));
3028
- }
3029
- const document = this.documentFromStateSnapshot(this.captureReviewerState());
3030
- applyReplyThreadMarkers(document);
3031
- visitDocxParagraphs({
3032
- documentBody: document.package.document,
3033
- headers: document.package.headers,
3034
- footers: document.package.footers,
3035
- footnotes: document.package.footnotes,
3036
- endnotes: document.package.endnotes
3037
- }, (paragraph) => {
3038
- if (finalizeParagraphFormatting(paragraph.formatting) === void 0) delete paragraph.formatting;
3039
- });
3040
- return document;
3041
- }
3042
- captureReviewerState() {
3043
- const secondaryStoryStates = [];
3044
- for (const { handle, initialState, state } of this.secondaryStoryStates.values()) secondaryStoryStates.push({
3045
- handle,
3046
- initialState,
3047
- state
3048
- });
3049
- return {
3050
- mainState: this.state,
3051
- finalSectionPropertiesOverride: this.finalSectionPropertiesOverride,
3052
- secondaryStoryStates,
3053
- sectionReferenceRemovals: [...this.sectionReferenceRemovals],
3054
- removedHeaderFooterStories: [...this.removedHeaderFooterStories.values()],
3055
- removedNoteStories: [...this.removedNoteStories.values()],
3056
- importedStyles: this.importedStyles,
3057
- importedMedia: new Map(this.importedMedia),
3058
- importedHeaders: new Map(this.importedHeaders),
3059
- importedFooters: new Map(this.importedFooters),
3060
- createdComments: [...this.createdComments],
3061
- deletedCommentIds: this.deletedCommentIds,
3062
- resolvedOverrides: new Map(this.resolvedOverrides),
3063
- resolvedStoryExpectations: [...this.resolvedStoryExpectations.values()].filter(({ story }) => story.type === "main" || this.secondaryStorySource(story) !== void 0)
3064
- };
3065
- }
3066
- documentFromStateSnapshot(authored) {
3067
- const pendingCommentIds = new Set(this.exportPendingSuggestions().flatMap(({ commentId }) => commentId === void 0 ? [] : [commentId]));
3068
- const snapshot = {
3069
- ...authored,
3070
- mainState: withoutPendingSuggestionCommentMarks(rejectEverySuggestion(authored.mainState), pendingCommentIds),
3071
- secondaryStoryStates: authored.secondaryStoryStates.map((entry) => ({
3072
- ...entry,
3073
- state: withoutPendingSuggestionCommentMarks(rejectEverySuggestion(entry.state), pendingCommentIds)
3074
- })),
3075
- createdComments: authored.createdComments.filter(({ id }) => !pendingCommentIds.has(id))
3076
- };
3077
- const sourceDocument = snapshot.importedStyles === void 0 ? this.baseDocument : {
3078
- ...this.baseDocument,
3079
- package: {
3080
- ...this.baseDocument.package,
3081
- styles: snapshot.importedStyles
3082
- }
3083
- };
3084
- const document = fromProseDoc(snapshot.mainState.doc, sourceDocument, { stylesheetSource: snapshot.importedStyles === void 0 ? { type: "package" } : {
3085
- type: "supplied",
3086
- styles: snapshot.importedStyles
3087
- } });
3088
- if (snapshot.finalSectionPropertiesOverride !== void 0) {
3089
- document.package.document.finalSectionProperties = snapshot.finalSectionPropertiesOverride;
3090
- if (document.package.document.sections !== void 0) document.package.document.sections = buildSections(document.package.document.content, snapshot.finalSectionPropertiesOverride);
3091
- }
3092
- if (snapshot.importedStyles !== void 0) document.package.styles = snapshot.importedStyles;
3093
- if (snapshot.importedMedia.size > 0) document.package.media = new Map([...document.package.media ?? [], ...snapshot.importedMedia]);
3094
- if (snapshot.importedHeaders.size > 0) document.package.headers = new Map([...document.package.headers ?? [], ...snapshot.importedHeaders]);
3095
- if (snapshot.importedFooters.size > 0) document.package.footers = new Map([...document.package.footers ?? [], ...snapshot.importedFooters]);
3096
- for (const handle of snapshot.removedHeaderFooterStories) if (handle.type === "header") {
3097
- document.package.headers = new Map(document.package.headers);
3098
- document.package.headers.delete(handle.relationshipId);
3099
- } else {
3100
- document.package.footers = new Map(document.package.footers);
3101
- document.package.footers.delete(handle.relationshipId);
3102
- }
3103
- this.mergeEditedSecondaryStories(document, snapshot.secondaryStoryStates);
3104
- if (snapshot.removedNoteStories.length > 0) {
3105
- const candidates = new Set(snapshot.removedNoteStories.map(noteStoryKey));
3106
- const referenced = referencedNotes(document, candidates);
3107
- const removed = new Set([...candidates].filter((key) => !referenced.has(key)));
3108
- Object.assign(document.package, noteStoryInventory(document.package, removed));
3109
- }
3110
- const definitions = [...document.package.document.comments ?? [], ...snapshot.createdComments];
3111
- const knownDefinitions = [...this.baseDocument.package.document.comments ?? [], ...snapshot.createdComments];
3112
- const keptThreadIds = new Set(this.keptCommentThreads(knownDefinitions, snapshot.mainState, snapshot.secondaryStoryStates).map(({ id }) => id));
3113
- const kept = definitions.filter(({ id }) => keptThreadIds.has(id) && !snapshot.deletedCommentIds.has(id));
3114
- const keptIds = new Set(kept.map(({ id }) => id));
3115
- const retiredCommentIds = new Set(knownDefinitions.filter(({ id }) => !keptIds.has(id)).map(({ id }) => id));
3116
- const modelStories = [
3117
- document.package.document,
3118
- ...document.package.headers?.values() ?? [],
3119
- ...document.package.footers?.values() ?? [],
3120
- ...document.package.footnotes ?? [],
3121
- ...document.package.endnotes ?? []
3122
- ];
3123
- for (const story of modelStories) for (const id of anchoredCommentIdsInBlocks(story.content)) if (!keptIds.has(id)) retiredCommentIds.add(id);
3124
- if (retiredCommentIds.size > 0) {
3125
- document.package.document = {
3126
- ...document.package.document,
3127
- content: removeCommentMarkers(document.package.document.content, retiredCommentIds)
3128
- };
3129
- if (document.package.headers) {
3130
- const headers = new Map(document.package.headers);
3131
- for (const [id, header] of headers) headers.set(id, {
3132
- ...header,
3133
- content: removeCommentMarkers(header.content, retiredCommentIds)
3134
- });
3135
- document.package.headers = headers;
3136
- }
3137
- if (document.package.footers) {
3138
- const footers = new Map(document.package.footers);
3139
- for (const [id, footer] of footers) footers.set(id, {
3140
- ...footer,
3141
- content: removeCommentMarkers(footer.content, retiredCommentIds)
3142
- });
3143
- document.package.footers = footers;
3144
- }
3145
- if (document.package.footnotes) document.package.footnotes = document.package.footnotes.map((footnote) => ({
3146
- ...footnote,
3147
- content: removeCommentMarkers(footnote.content, retiredCommentIds)
3148
- }));
3149
- if (document.package.endnotes) document.package.endnotes = document.package.endnotes.map((endnote) => ({
3150
- ...endnote,
3151
- content: removeCommentMarkers(endnote.content, retiredCommentIds)
3152
- }));
3153
- }
3154
- if (kept.length !== definitions.length || snapshot.createdComments.length > 0 || snapshot.resolvedOverrides.size > 0) setDocumentBodyComments(document.package.document, this.withResolvedOverrides(kept, snapshot.resolvedOverrides));
3155
- const normalized = normalizeListModelRendering(reconcileDocumentPartRelationships(document), { inverse: "omit" }).document;
3156
- visitDocxParagraphs({
3157
- documentBody: normalized.package.document,
3158
- headers: normalized.package.headers,
3159
- footers: normalized.package.footers,
3160
- footnotes: normalized.package.footnotes,
3161
- endnotes: normalized.package.endnotes
3162
- }, (paragraph) => {
3163
- if (finalizeParagraphFormatting(paragraph.formatting) === void 0) delete paragraph.formatting;
3164
- });
3165
- return normalized;
3166
- }
3167
- captureSaveSnapshot() {
3168
- const snapshot = this.captureReviewerState();
3169
- const changedParaIds = new Set(getChangedParagraphIds(snapshot.mainState));
3170
- let structuralChange = hasStructuralChanges(snapshot.mainState) || snapshot.finalSectionPropertiesOverride !== void 0 || snapshot.importedStyles !== void 0 || snapshot.importedHeaders.size > 0 || snapshot.importedFooters.size > 0 || snapshot.removedNoteStories.length > 0;
3171
- let untrackedChanges = hasUntrackedChanges(snapshot.mainState);
3172
- const changedNoteParaIds = /* @__PURE__ */ new Set();
3173
- for (const entry of snapshot.secondaryStoryStates) {
3174
- if (entry.handle.type !== "footnote" && entry.handle.type !== "endnote") continue;
3175
- for (const paraId of getChangedParagraphIds(entry.state)) {
3176
- changedParaIds.add(paraId);
3177
- changedNoteParaIds.add(paraId);
3178
- }
3179
- structuralChange ||= hasStructuralChanges(entry.state);
3180
- untrackedChanges ||= hasUntrackedChanges(entry.state);
3181
- }
3182
- let path = {
3183
- type: "selective-first",
3184
- changedParaIds
3185
- };
3186
- if (structuralChange) path = {
3187
- type: "full-repack",
3188
- reason: "structuralChange"
3189
- };
3190
- else if (untrackedChanges) path = {
3191
- type: "full-repack",
3192
- reason: "untrackedChange"
3193
- };
3194
- return {
3195
- document: this.documentFromStateSnapshot(snapshot),
3196
- path,
3197
- changedNoteParaIds,
3198
- sectionReferenceRemovals: snapshot.sectionReferenceRemovals,
3199
- sectionEndpointRemoval: getTrackedSectionEndpointRemoval(snapshot.mainState),
3200
- resolvedStoryExpectations: snapshot.resolvedStoryExpectations
3201
- };
2056
+ const model = withoutPendingSuggestions(this.engine.session.captureSaveSnapshot().document);
2057
+ if (model.isErr()) throw model.error;
2058
+ return cloneDocumentWithParagraphPropertySources(reconcileDocumentPartRelationships(model.value));
3202
2059
  }
3203
2060
  /**
3204
2061
  * Serialise the reviewed document to a new `.docx` buffer. Tries a selective
@@ -3216,43 +2073,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3216
2073
  * With `repack: "refuse"`, a save the selective patch cannot express
3217
2074
  * returns the reason instead of rewriting every part.
3218
2075
  */
3219
- async save({ repack: repackPolicy = "allow" } = {}) {
3220
- if (this.engine.type === "canonical") return this.saveOnSession(this.engine.session, repackPolicy);
3221
- const save = this.captureSaveSnapshot();
3222
- const selective = save.path.type === "selective-first" ? await this.trySelectiveSave(save.document, save.path.changedParaIds) : null;
3223
- if (selective) {
3224
- await this.assertResolvedStoriesSerialized(selective, save.resolvedStoryExpectations);
3225
- return {
3226
- type: "selective",
3227
- buffer: selective
3228
- };
3229
- }
3230
- const reason = save.path.type === "full-repack" ? save.path.reason : "selectiveDeclined";
3231
- if (repackPolicy === "refuse") return {
3232
- type: "repackRefused",
3233
- reason
3234
- };
3235
- const repackDocument = {
3236
- ...save.document,
3237
- originalBuffer: this.originalBuffer
3238
- };
3239
- const repack = () => repackDocx(repackDocument, { changedNoteParaIds: save.changedNoteParaIds });
3240
- const repackReferences = () => save.sectionReferenceRemovals.length > 0 ? withSectionReferenceResolution({
3241
- document: repackDocument,
3242
- removedReferences: save.sectionReferenceRemovals,
3243
- repack
3244
- }) : repack();
3245
- const buffer = save.sectionEndpointRemoval ? await withTrackedSectionEndpointRemoval({
3246
- document: repackDocument,
3247
- resolution: save.sectionEndpointRemoval,
3248
- repack: repackReferences
3249
- }) : await repackReferences();
3250
- await this.assertResolvedStoriesSerialized(buffer, save.resolvedStoryExpectations);
3251
- return {
3252
- type: "full-repack",
3253
- reason,
3254
- buffer
3255
- };
2076
+ save({ repack: repackPolicy = "allow" } = {}) {
2077
+ return this.saveOnSession(this.engine.session, repackPolicy);
3256
2078
  }
3257
2079
  /**
3258
2080
  * The editor's canonical save of the session's committed snapshot: the
@@ -3286,79 +2108,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3286
2108
  buffer: saved.buffer
3287
2109
  };
3288
2110
  }
3289
- async assertResolvedStoriesSerialized(buffer, expectations) {
3290
- if (expectations.length === 0) return;
3291
- const reopened = await FolioDocxReviewer.fromBuffer(buffer, { session: "legacy" });
3292
- for (const { story, text, blocks, minted } of expectations) {
3293
- const serialized = reopened.readReviewedStory({
3294
- story,
3295
- view: "current-markup"
3296
- });
3297
- const persisted = serialized ? resolvedStoryProjection(serialized.snapshot, minted) : null;
3298
- const serializedText = persisted?.text ?? null;
3299
- const serializedBlocks = persisted?.blocks ?? null;
3300
- const mismatches = [];
3301
- if (!serialized) mismatches.push(FOLIO_RESOLVED_STORY_SERIALIZATION_MISMATCHES.storyMissing);
3302
- else {
3303
- if (serialized.changes.length > 0) mismatches.push(FOLIO_RESOLVED_STORY_SERIALIZATION_MISMATCHES.revisionMarkupRemains);
3304
- if (serializedText !== text) mismatches.push(FOLIO_RESOLVED_STORY_SERIALIZATION_MISMATCHES.textProjection);
3305
- if (JSON.stringify(serializedBlocks) !== JSON.stringify(blocks)) mismatches.push(FOLIO_RESOLVED_STORY_SERIALIZATION_MISMATCHES.blockProjection);
3306
- }
3307
- if (mismatches.length === 0) continue;
3308
- throw new FolioResolvedStorySerializationError({
3309
- message: "Resolved document story did not persist to the serialized DOCX.",
3310
- story,
3311
- mismatches,
3312
- expectedBlockCount: blocks.length,
3313
- actualBlockCount: serializedBlocks?.length ?? null,
3314
- remainingChangeCount: serialized?.changes.length ?? null
3315
- });
3316
- }
3317
- }
3318
- /**
3319
- * Attempt the selective patch, treating a throw the same as a decline. Odd
3320
- * source XML can make the paragraph diff throw rather than return `null`; a
3321
- * full repack is the correct lossless fallback in both cases, so the fallback
3322
- * is the graceful handling — no separate error surface is needed here.
3323
- */
3324
- async trySelectiveSave(document, changedParaIds) {
3325
- try {
3326
- return await attemptSelectiveSave(document, this.originalBuffer, {
3327
- changedParaIds,
3328
- structuralChange: false,
3329
- hasUntrackedChanges: false
3330
- });
3331
- } catch {
3332
- return null;
3333
- }
3334
- }
3335
2111
  getEditableStoryState(story) {
3336
2112
  if (story.type === "main") return this.state;
3337
2113
  if (!this.secondaryStorySource(story)) return null;
3338
- if (this.engine.type === "canonical") {
3339
- const projected = this.engine.session.projectStory(canonicalOpStory(story));
3340
- if (projected.isErr()) throw projected.error;
3341
- return canonicalStoryState(this.engine.session, projected.value.doc, projected.value);
3342
- }
3343
- const key = secondaryStoryKey(story);
3344
- const existing = this.secondaryStoryStates.get(key);
3345
- if (existing) return existing.state;
3346
- const doc = this.secondaryStoryDoc(story);
3347
- if (!doc) return null;
3348
- const initialState = ensureBaseDirectionInState(EditorState.create({
3349
- schema,
3350
- doc,
3351
- plugins: createHeadlessPlugins(this.importedStyles ?? this.baseDocument.package.styles, this.baseDocument.package.numbering)
3352
- }));
3353
- const transaction = initialState.tr;
3354
- if (this.deletedCommentIds.size > 0) removeCommentAnchors(transaction, this.deletedCommentIds);
3355
- const state = transaction.docChanged ? initialState.apply(transaction) : initialState;
3356
- this.secondaryStoryStates.set(key, {
3357
- handle: story,
3358
- initialState,
3359
- state
3360
- });
3361
- return state;
2114
+ const projected = this.engine.session.projectStory(canonicalOpStory(story));
2115
+ if (projected.isErr()) throw projected.error;
2116
+ return canonicalStoryState(this.engine.session, projected.value.doc, projected.value);
3362
2117
  }
3363
2118
  /**
3364
2119
  * A secondary story as its editable state holds it: the loaded state's
@@ -3367,8 +2122,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3367
2122
  * state for a story nothing edits.
3368
2123
  */
3369
2124
  readSecondaryStoryDoc(story) {
3370
- if (!this.secondaryStorySource(story)) return null;
3371
- return this.secondaryStoryStates.get(secondaryStoryKey(story))?.state.doc ?? this.secondaryStoryDoc(story);
2125
+ return this.secondaryStoryDoc(story);
3372
2126
  }
3373
2127
  secondaryStorySource(story) {
3374
2128
  return story.type === "header" || story.type === "footer" ? this.getHeaderFooterStory(story) : this.getNoteStory(story);
@@ -3380,49 +2134,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3380
2134
  * session's story projections yet.
3381
2135
  */
3382
2136
  secondaryStoryDoc(story) {
3383
- if (this.engine.type === "canonical") {
3384
- if (!this.secondaryStorySource(story)) return null;
3385
- const projected = this.engine.session.projectStory(canonicalOpStory(story));
3386
- if (projected.isErr()) throw projected.error;
3387
- return projected.value.doc;
3388
- }
3389
- const source = this.secondaryStorySource(story);
3390
- if (!source) return null;
3391
- const styles = this.importedStyles ?? this.baseDocument.package.styles;
3392
- const conversionOptions = {
3393
- ...this.baseDocument.package.numbering !== void 0 && { numbering: this.baseDocument.package.numbering },
3394
- ...styles !== void 0 && { styles },
3395
- ...this.baseDocument.package.theme !== void 0 && { theme: this.baseDocument.package.theme }
3396
- };
3397
- const storyDoc = story.type === "header" || story.type === "footer" ? headerFooterToProseDoc(source.content, conversionOptions) : footnoteToProseDoc(source.content, conversionOptions);
3398
- return ensureParaIdsInDoc(storyDoc);
3399
- }
3400
- requireEditableStoryState(story) {
3401
- const state = this.getEditableStoryState(story);
3402
- if (state) return state;
3403
- throw new FolioDocumentStoryNotFoundError({
3404
- message: `Document story ${JSON.stringify(story)} was not found.`,
3405
- story
3406
- });
3407
- }
3408
- setEditableStoryState(story, projected) {
3409
- this.resolvedStoryExpectations.delete(editableStoryKey(story));
3410
- const folded = (stored) => stored.doc === projected.doc ? projected : collapseEmptyTextBoxHosts(projected);
3411
- if (story.type === "main") {
3412
- this.state = folded(this.state);
3413
- return;
3414
- }
3415
- const entry = this.secondaryStoryStates.get(secondaryStoryKey(story));
3416
- if (!entry) throw new FolioDocumentStoryNotFoundError({
3417
- message: `Document story ${JSON.stringify(story)} was not found.`,
3418
- story
3419
- });
3420
- entry.state = folded(entry.state);
2137
+ if (!this.secondaryStorySource(story)) return null;
2138
+ const projected = this.engine.session.projectStory(canonicalOpStory(story));
2139
+ if (projected.isErr()) throw projected.error;
2140
+ return projected.value.doc;
3421
2141
  }
3422
2142
  getHeaderFooterStory(story) {
3423
- if (this.removedHeaderFooterStories.has(headerFooterStoryKey(story))) return void 0;
3424
- const importedStory = (story.type === "header" ? this.importedHeaders : this.importedFooters).get(story.relationshipId);
3425
- if (importedStory) return importedStory;
3426
2143
  return (story.type === "header" ? this.baseDocument.package.headers : this.baseDocument.package.footers)?.get(story.relationshipId);
3427
2144
  }
3428
2145
  async createComparisonHeaderFooter(source, story) {
@@ -3447,7 +2164,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3447
2164
  const existingPaths = new Set(originalZip.paths().map((path) => path.toLowerCase()));
3448
2165
  let suffix = 1;
3449
2166
  let path = `word/media/folio-import-${suffix}.${extension}`;
3450
- while (existingPaths.has(path.toLowerCase()) || this.baseDocument.package.media?.has(path) || this.importedMedia.has(path)) path = `word/media/folio-import-${++suffix}.${extension}`;
2167
+ while (existingPaths.has(path.toLowerCase()) || this.baseDocument.package.media?.has(path)) path = `word/media/folio-import-${++suffix}.${extension}`;
3451
2168
  importedMedia = {
3452
2169
  ...media,
3453
2170
  path,
@@ -3465,9 +2182,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3465
2182
  const taken = /* @__PURE__ */ new Set([
3466
2183
  ...this.baseDocument.package.relationships?.keys() ?? [],
3467
2184
  ...this.baseDocument.package.headers?.keys() ?? [],
3468
- ...this.baseDocument.package.footers?.keys() ?? [],
3469
- ...this.importedHeaders.keys(),
3470
- ...this.importedFooters.keys()
2185
+ ...this.baseDocument.package.footers?.keys() ?? []
3471
2186
  ]);
3472
2187
  let suffix = 1;
3473
2188
  let relationshipId = `rId${suffix}`;
@@ -3485,52 +2200,37 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3485
2200
  content: []
3486
2201
  }]
3487
2202
  };
3488
- if (this.engine.type === "canonical") {
3489
- const document = this.baseDocument;
3490
- const minted = this.engine.session.freshBlockIds([1]);
3491
- if (minted.isErr()) throw minted.error;
3492
- const paraId = minted.value.at(0)?.at(0);
3493
- if (paraId === void 0) return panic("The session minted no paragraph id for a header part");
3494
- const entries = [...(story.type === "header" ? document.package.headers : document.package.footers) ?? /* @__PURE__ */ new Map(), [relationshipId, {
3495
- ...empty,
3496
- content: [{
3497
- type: "paragraph",
3498
- paraId,
3499
- content: []
3500
- }]
3501
- }]];
3502
- const parts = story.type === "header" ? { headers: entries } : { footers: entries };
3503
- const ops = [];
3504
- if (importedMedia) ops.push(packageResourcesOpOf({
3505
- before: document,
3506
- after: {
3507
- ...document,
3508
- package: {
3509
- ...document.package,
3510
- media: new Map([...document.package.media ?? /* @__PURE__ */ new Map(), [importedMedia.path, importedMedia]])
3511
- }
2203
+ const document = this.baseDocument;
2204
+ const minted = this.engine.session.freshBlockIds([1]);
2205
+ if (minted.isErr()) throw minted.error;
2206
+ const paraId = minted.value.at(0)?.at(0);
2207
+ if (paraId === void 0) return panic("The session minted no paragraph id for a header part");
2208
+ const entries = [...(story.type === "header" ? document.package.headers : document.package.footers) ?? /* @__PURE__ */ new Map(), [relationshipId, {
2209
+ ...empty,
2210
+ content: [{
2211
+ type: "paragraph",
2212
+ paraId,
2213
+ content: []
2214
+ }]
2215
+ }]];
2216
+ const parts = story.type === "header" ? { headers: entries } : { footers: entries };
2217
+ const ops = [];
2218
+ if (importedMedia) ops.push(packageResourcesOpOf({
2219
+ before: document,
2220
+ after: {
2221
+ ...document,
2222
+ package: {
2223
+ ...document.package,
2224
+ media: new Map([...document.package.media ?? /* @__PURE__ */ new Map(), [importedMedia.path, importedMedia]])
3512
2225
  }
3513
- }));
3514
- ops.push({
3515
- type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
3516
- expected: captureStoryParts(document, parts),
3517
- parts
3518
- });
3519
- this.commitOpsOnSession(ops);
3520
- return handle;
3521
- }
3522
- if (importedMedia) this.importedMedia.set(importedMedia.path, importedMedia);
3523
- (story.type === "header" ? this.importedHeaders : this.importedFooters).set(relationshipId, empty);
3524
- const state = ensureBaseDirectionInState(EditorState.create({
3525
- schema,
3526
- doc: ensureParaIdsInDoc(headerFooterToProseDoc(empty.content)),
3527
- plugins: createHeadlessPlugins(this.baseDocument.package.styles, this.baseDocument.package.numbering)
2226
+ }
3528
2227
  }));
3529
- this.secondaryStoryStates.set(headerFooterStoryKey(handle), {
3530
- handle,
3531
- initialState: state,
3532
- state
2228
+ ops.push({
2229
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
2230
+ expected: captureStoryParts(document, parts),
2231
+ parts
3533
2232
  });
2233
+ this.commitOpsOnSession(ops);
3534
2234
  return handle;
3535
2235
  }
3536
2236
  canImportHeaderFooterContent(source, story) {
@@ -3541,7 +2241,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3541
2241
  return snapshot !== null && detachFolioAIEditSnapshotExternalHyperlinks(snapshot) !== null;
3542
2242
  }
3543
2243
  getNoteStory(story) {
3544
- const notes = noteStoryInventory(this.baseDocument.package, this.removedNoteStories);
2244
+ const notes = this.baseDocument.package;
3545
2245
  if (story.type === "footnote") return notes.footnotes?.find((note) => note.id === story.noteId && !isSeparatorFootnote(note));
3546
2246
  return notes.endnotes?.find((note) => note.id === story.noteId && !isSeparatorEndnote(note));
3547
2247
  }
@@ -3556,19 +2256,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3556
2256
  * another after. This is the conversion the save path already performs on the
3557
2257
  * same states, so the text now describes exactly what a save would write.
3558
2258
  */
3559
- storyBlocks(state, source) {
3560
- return state ? proseDocToBlocks(rejectEverySuggestion(state).doc, source.content, this.baseDocument.package.styles) : source.content;
2259
+ getHeaderFooterStoryText(source) {
2260
+ return normalizeFolioAIBlockText(getHeaderFooterText(source));
3561
2261
  }
3562
- getHeaderFooterStoryText(story, source) {
3563
- const state = this.secondaryStoryStates.get(headerFooterStoryKey(story))?.state;
3564
- return normalizeFolioAIBlockText(getHeaderFooterText({
3565
- ...source,
3566
- content: this.storyBlocks(state, source)
3567
- }));
3568
- }
3569
- getNoteStoryText(story, source) {
3570
- const state = this.secondaryStoryStates.get(noteStoryKey(story))?.state;
3571
- const content = this.storyBlocks(state, source);
2262
+ getNoteStoryText(source) {
2263
+ const { content } = source;
3572
2264
  return normalizeFolioAIBlockText(source.type === "footnote" ? getFootnoteText({
3573
2265
  ...source,
3574
2266
  content
@@ -3582,119 +2274,33 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3582
2274
  if (story.type === "header" || story.type === "footer") {
3583
2275
  const source = this.getHeaderFooterStory(story);
3584
2276
  if (!source) return panic("A listed document story no longer exists", { story });
3585
- return this.getHeaderFooterStoryText(story, source);
2277
+ return this.getHeaderFooterStoryText(source);
3586
2278
  }
3587
2279
  const source = this.getNoteStory(story);
3588
2280
  if (!source) return panic("A listed document story no longer exists", { story });
3589
- return this.getNoteStoryText(story, source);
3590
- }
3591
- mergeEditedSecondaryStories(document, secondaryStoryStates = this.secondaryStoryStates.values()) {
3592
- let headers;
3593
- let footers;
3594
- let footnotes;
3595
- let endnotes;
3596
- for (const entry of secondaryStoryStates) {
3597
- if (entry.state === entry.initialState) continue;
3598
- const lists = storyListNumbering(entry.state, document.package.numbering);
3599
- if (lists.numbering) document.package.numbering = lists.numbering;
3600
- if (entry.handle.type === "header" || entry.handle.type === "footer") {
3601
- const source = entry.handle.type === "header" ? document.package.headers?.get(entry.handle.relationshipId) : document.package.footers?.get(entry.handle.relationshipId);
3602
- if (!source) continue;
3603
- const edited = {
3604
- ...source,
3605
- content: proseDocToBlocks(lists.doc, source.content, document.package.styles)
3606
- };
3607
- if (entry.handle.type === "header") {
3608
- headers ??= new Map(document.package.headers);
3609
- headers.set(entry.handle.relationshipId, edited);
3610
- continue;
3611
- }
3612
- footers ??= new Map(document.package.footers);
3613
- footers.set(entry.handle.relationshipId, edited);
3614
- continue;
3615
- }
3616
- if (entry.handle.type === "footnote") {
3617
- const { noteId } = entry.handle;
3618
- const source = this.baseDocument.package.footnotes?.find((note) => note.id === noteId && !isSeparatorFootnote(note));
3619
- if (!source) continue;
3620
- const edited = {
3621
- ...source,
3622
- content: proseDocToBlocks(lists.doc, source.content, document.package.styles)
3623
- };
3624
- footnotes ??= [...document.package.footnotes ?? []];
3625
- const index = footnotes.findIndex((note) => note.id === noteId);
3626
- if (index !== -1) footnotes[index] = edited;
3627
- continue;
3628
- }
3629
- const { noteId } = entry.handle;
3630
- const source = this.baseDocument.package.endnotes?.find((note) => note.id === noteId && !isSeparatorEndnote(note));
3631
- if (!source) continue;
3632
- const edited = {
3633
- ...source,
3634
- content: proseDocToBlocks(lists.doc, source.content, document.package.styles)
3635
- };
3636
- endnotes ??= [...document.package.endnotes ?? []];
3637
- const index = endnotes.findIndex((note) => note.id === noteId);
3638
- if (index !== -1) endnotes[index] = edited;
3639
- }
3640
- if (headers) document.package.headers = headers;
3641
- if (footers) document.package.footers = footers;
3642
- if (footnotes) document.package.footnotes = footnotes;
3643
- if (endnotes) document.package.endnotes = endnotes;
3644
- }
3645
- /** Apply any {@link resolveComment} overrides recorded for these comments. */
3646
- withResolvedOverrides(comments, resolvedOverrides = this.resolvedOverrides) {
3647
- if (resolvedOverrides.size === 0) return [...comments];
3648
- return comments.map((comment) => {
3649
- const override = resolvedOverrides.get(comment.id);
3650
- return override === void 0 ? comment : {
3651
- ...comment,
3652
- done: override
3653
- };
3654
- });
2281
+ return this.getNoteStoryText(source);
3655
2282
  }
3656
2283
  /**
3657
2284
  * `comments` without the threads an edit left anchored nowhere: anchored in
3658
2285
  * a story when it was loaded (or created anchored by this reviewer), and
3659
2286
  * anchored in no story now. See `comment-lifecycle.ts`.
3660
2287
  */
3661
- keptCommentThreads(comments, mainState, secondaryStoryStates) {
2288
+ keptCommentThreads(comments, mainState) {
3662
2289
  const anchoredBefore = new Set(this.loadedMainCommentIds);
3663
- for (const { id } of this.createdComments) anchoredBefore.add(id);
3664
2290
  const anchoredNow = anchoredCommentIdsInProseDoc(mainState.doc);
3665
- const loaded = /* @__PURE__ */ new Map();
3666
- for (const entry of secondaryStoryStates) loaded.set(secondaryStoryKey(entry.handle), entry);
3667
2291
  const addAll = (target, ids) => {
3668
2292
  for (const id of ids) target.add(id);
3669
2293
  };
3670
2294
  const referenceStates = noteReferenceStates(mainState.doc);
3671
- for (const entry of loaded.values()) {
3672
- addAll(anchoredBefore, anchoredCommentIdsInProseDoc(entry.initialState.doc));
3673
- if ((entry.handle.type === "footnote" || entry.handle.type === "endnote") && this.removedNoteStories.has(noteStoryKey(entry.handle)) && referenceStates.get(noteStoryKey(entry.handle)) !== "deleted") continue;
3674
- addAll(anchoredNow, anchoredCommentIdsInProseDoc(entry.state.doc, entry.initialState.doc));
3675
- }
3676
2295
  for (const handle of this.listStoryHandlesInternal()) {
3677
2296
  if (handle.type === "main") continue;
3678
- if (loaded.get(secondaryStoryKey(handle))) continue;
3679
2297
  const source = handle.type === "header" || handle.type === "footer" ? this.getHeaderFooterStory(handle) : this.getNoteStory(handle);
3680
2298
  addAll(anchoredNow, anchoredCommentIdsInBlocks(source?.content ?? []));
3681
2299
  }
3682
- for (const handle of this.removedNoteStories.values()) {
3683
- if (loaded.get(secondaryStoryKey(handle))) {
3684
- if (referenceStates.get(noteStoryKey(handle)) === "deleted") {
3685
- const source = (handle.type === "footnote" ? this.baseDocument.package.footnotes : this.baseDocument.package.endnotes)?.find((note) => note.id === handle.noteId);
3686
- addAll(anchoredNow, anchoredCommentIdsInBlocks(source?.content ?? []));
3687
- }
3688
- continue;
3689
- }
3690
- const removed = anchoredCommentIdsInBlocks((handle.type === "footnote" ? this.baseDocument.package.footnotes : this.baseDocument.package.endnotes)?.find((note) => note.id === handle.noteId)?.content ?? []);
3691
- addAll(anchoredBefore, removed);
3692
- if (referenceStates.get(noteStoryKey(handle)) === "deleted") addAll(anchoredNow, removed);
3693
- }
3694
2300
  for (const [key, state] of referenceStates) {
3695
2301
  if (state !== "deleted") continue;
3696
2302
  const handle = noteStoryHandleOf(key);
3697
- if (!handle || loaded.has(secondaryStoryKey(handle))) continue;
2303
+ if (!handle) continue;
3698
2304
  addAll(anchoredNow, anchoredCommentIdsInBlocks(this.getNoteStory(handle)?.content ?? []));
3699
2305
  }
3700
2306
  return withoutLostCommentThreads(comments, {
@@ -3721,38 +2327,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3721
2327
  if (!doc) continue;
3722
2328
  add(doc, story);
3723
2329
  }
3724
- for (const story of this.removedNoteStories.values()) {
3725
- if (noteReferenceStates(this.state.doc).get(noteStoryKey(story)) !== "deleted") continue;
3726
- const entry = this.secondaryStoryStates.get(secondaryStoryKey(story));
3727
- if (entry) add(entry.initialState.doc, story);
3728
- }
3729
2330
  return anchors;
3730
2331
  }
3731
- /** Allocate outside every parsed or newly-created comment and reply id. */
3732
- nextCommentId() {
3733
- return this.commentIds.next();
3734
- }
3735
- /**
3736
- * Drive a ProseMirror command against the reviewer's headless state via the
3737
- * same `{ state, dispatch }` seam {@link applyOperations} uses, retaining the
3738
- * resulting state for {@link toBuffer}.
3739
- */
3740
- runCommand(command) {
3741
- return this.runStoryCommand(command, MAIN_STORY);
3742
- }
3743
- runStoryCommand(command, story) {
3744
- const state = this.getEditableStoryState(story);
3745
- if (!state) return false;
3746
- const view = {
3747
- state,
3748
- dispatch: (transaction) => {
3749
- view.state = view.state.apply(transaction);
3750
- }
3751
- };
3752
- const handled = command(view.state, view.dispatch);
3753
- this.setEditableStoryState(story, view.state);
3754
- return handled;
3755
- }
3756
2332
  };
3757
2333
  /** @internal Comparison-only access to atomic and fresh reviewer projections. */
3758
2334
  const getFolioDocxComparisonAccess = (reviewer) => {