@stll/folio-core 0.72.0 → 0.73.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 (192) hide show
  1. package/README.md +12 -6
  2. package/dist/ai-edits/apply.d.ts +6 -114
  3. package/dist/ai-edits/apply.js +9 -131
  4. package/dist/ai-edits/applyTypes.d.ts +85 -0
  5. package/dist/ai-edits/applyTypes.js +24 -0
  6. package/dist/ai-edits/clean-text.d.ts +7 -1
  7. package/dist/ai-edits/clean-text.js +23 -2
  8. package/dist/ai-edits/finalSectionReview.d.ts +1 -1
  9. package/dist/ai-edits/headless.d.ts +29 -147
  10. package/dist/ai-edits/headless.js +213 -1634
  11. package/dist/ai-edits/index.d.ts +3 -3
  12. package/dist/ai-edits/index.js +2 -3
  13. package/dist/ai-edits/pending-suggestions.d.ts +14 -4
  14. package/dist/ai-edits/pending-suggestions.js +183 -90
  15. package/dist/ai-edits/result-validation.js +1 -1
  16. package/dist/ai-edits/retired-comment-receipts.d.ts +1 -1
  17. package/dist/ai-edits/snapshot.js +8 -3
  18. package/dist/ai-edits/table-cell-mutations.d.ts +1 -1
  19. package/dist/ai-edits/table-cell-mutations.js +1 -1
  20. package/dist/ai-edits/table-geometry.d.ts +1 -1
  21. package/dist/ai-edits/table-geometry.js +1 -1
  22. package/dist/ai-edits/table-row-column-mutations.d.ts +1 -1
  23. package/dist/ai-edits/table-row-column-mutations.js +1 -1
  24. package/dist/ai-edits/tableNodes.d.ts +38 -0
  25. package/dist/ai-edits/tableNodes.js +86 -0
  26. package/dist/ai-edits/tracked-batch-fidelity.d.ts +1 -1
  27. package/dist/ai-edits/undefinedReferences.d.ts +7 -0
  28. package/dist/canonical/batchCommentReferences.js +1 -0
  29. package/dist/canonical/canonicalInlineProjection.js +1 -1
  30. package/dist/canonical/canonicalPublicOperations.js +228 -64
  31. package/dist/canonical/canonicalSession.d.ts +9 -1
  32. package/dist/canonical/canonicalSession.js +95 -15
  33. package/dist/compare/compare.d.ts +1 -1
  34. package/dist/compare/inline-atoms-model.d.ts +1 -1
  35. package/dist/compare/inline-atoms.d.ts +2 -2
  36. package/dist/compare/inline-provenance-model.d.ts +1 -1
  37. package/dist/compare/inline-provenance.d.ts +2 -2
  38. package/dist/compat/eigenpal.d.ts +3 -3
  39. package/dist/compat/eigenpal.js +2 -3
  40. package/dist/controller/canonicalClipboard.d.ts +13 -3
  41. package/dist/controller/canonicalClipboard.js +185 -49
  42. package/dist/controller/canonicalClipboardResources.d.ts +9 -1
  43. package/dist/controller/canonicalClipboardResources.js +22 -2
  44. package/dist/controller/canonicalReview.d.ts +1 -1
  45. package/dist/controller/canonicalReview.js +1 -1
  46. package/dist/controller/canonicalStructure.js +1 -1
  47. package/dist/controller/canonicalWatermark.d.ts +10 -0
  48. package/dist/controller/canonicalWatermark.js +37 -0
  49. package/dist/controller/hiddenEditorApi.d.ts +1 -1
  50. package/dist/controller/hiddenEditorManager.d.ts +4 -3
  51. package/dist/controller/hiddenEditorManager.js +75 -15
  52. package/dist/document-operations-apply.d.ts +15 -0
  53. package/dist/document-operations-apply.js +280 -0
  54. package/dist/document-operations.d.ts +1 -14
  55. package/dist/document-operations.js +2 -279
  56. package/dist/docx/modelValidation.js +1 -1
  57. package/dist/docx/paragraphParser.js +2 -2
  58. package/dist/docx/paragraphPropertySource.d.ts +1 -1
  59. package/dist/docx/reviewResolutionProvenance.d.ts +3 -2
  60. package/dist/docx/reviewResolutionProvenance.js +32 -9
  61. package/dist/docx/revisionIdNormalization.js +30 -7
  62. package/dist/docx/rezip.js +1 -1
  63. package/dist/docx/serializer/borderSerializer.js +1 -1
  64. package/dist/docx/serializer/commentSerializer.js +1 -1
  65. package/dist/docx/serializer/documentSerializer.js +1 -1
  66. package/dist/docx/serializer/paragraphSerializer.js +3 -3
  67. package/dist/docx/serializer/runSerializer.js +1 -1
  68. package/dist/docx/serializer/sectionPropertiesSerializer.js +1 -1
  69. package/dist/docx/serializer/tableSerializer.js +5 -37
  70. package/dist/docx/serializer/textFormattingSerializer.js +1 -1
  71. package/dist/docx/serializer/trackedChangeAttributes.js +1 -1
  72. package/dist/docx/server/templatePlan/apply.d.ts +15 -0
  73. package/dist/docx/server/templatePlan/apply.js +600 -0
  74. package/dist/docx/server/templatePlan/blocks.d.ts +97 -0
  75. package/dist/docx/server/templatePlan/blocks.js +355 -0
  76. package/dist/docx/server/templatePlan/builders.d.ts +72 -0
  77. package/dist/docx/server/templatePlan/builders.js +237 -0
  78. package/dist/docx/server/templatePlan/emit.d.ts +118 -0
  79. package/dist/docx/server/templatePlan/emit.js +466 -0
  80. package/dist/docx/server/templatePlan/emphasis.d.ts +62 -0
  81. package/dist/docx/server/templatePlan/emphasis.js +173 -0
  82. package/dist/docx/server/templatePlan/inspect.d.ts +22 -0
  83. package/dist/docx/server/templatePlan/inspect.js +177 -0
  84. package/dist/docx/server/templatePlan/labels.d.ts +36 -0
  85. package/dist/docx/server/templatePlan/labels.js +126 -0
  86. package/dist/docx/server/templatePlan/package.d.ts +34 -0
  87. package/dist/docx/server/templatePlan/package.js +99 -0
  88. package/dist/docx/server/templatePlan/plan.d.ts +143 -0
  89. package/dist/docx/server/templatePlan/plan.js +841 -0
  90. package/dist/docx/server/templatePlan/planShape.d.ts +9 -0
  91. package/dist/docx/server/templatePlan/planShape.js +161 -0
  92. package/dist/docx/server/templatePlan/resources.d.ts +41 -0
  93. package/dist/docx/server/templatePlan/resources.js +136 -0
  94. package/dist/docx/server/templatePlan/story.d.ts +128 -0
  95. package/dist/docx/server/templatePlan/story.js +440 -0
  96. package/dist/docx/server/templatePlan/types.d.ts +406 -0
  97. package/dist/docx/server/templatePlan/types.js +28 -0
  98. package/dist/docx/server/templatePlan/verify.d.ts +40 -0
  99. package/dist/docx/server/templatePlan/verify.js +968 -0
  100. package/dist/docx/server/templatePlan/xml.d.ts +69 -0
  101. package/dist/docx/server/templatePlan/xml.js +119 -0
  102. package/dist/docx/settingsHeaderFooterUpdate.d.ts +9 -0
  103. package/dist/docx/settingsHeaderFooterUpdate.js +45 -10
  104. package/dist/docx/storyBlockReplay.js +1 -1
  105. package/dist/docx/structuralXmlPatch.js +9 -1
  106. package/dist/docx/tableGridXml.d.ts +30 -0
  107. package/dist/docx/tableGridXml.js +54 -0
  108. package/dist/docx/tableParser.js +7 -0
  109. package/dist/docx/xmlParser.js +1 -1
  110. package/dist/index.d.ts +3 -3
  111. package/dist/index.js +2 -3
  112. package/dist/internal/paragraphFormattingSerialization.js +1 -1
  113. package/dist/internal/wholeStoryRevisionResolution.js +1 -1
  114. package/dist/managers/ContextMenuManager.js +2 -1
  115. package/dist/managers/editorShortcuts.d.ts +1 -1
  116. package/dist/prosemirror/anchoredTextBoxes.d.ts +1 -1
  117. package/dist/prosemirror/canonicalCommands.d.ts +1 -1
  118. package/dist/prosemirror/canonicalSelectionRange.d.ts +1 -1
  119. package/dist/prosemirror/canonicalTableCommands.js +2 -2
  120. package/dist/prosemirror/commands/comments.js +3 -3
  121. package/dist/prosemirror/commands/contentControls.d.ts +1 -1
  122. package/dist/prosemirror/commands/formatPainter.d.ts +1 -1
  123. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  124. package/dist/prosemirror/commands/pastePlainText.d.ts +1 -1
  125. package/dist/prosemirror/commands/sectionBreak.js +1 -1
  126. package/dist/prosemirror/commands/tableCellMergeResolution.d.ts +1 -1
  127. package/dist/prosemirror/commands/tableMergeFoldDecisions.d.ts +1 -1
  128. package/dist/prosemirror/commentRecords.d.ts +1 -1
  129. package/dist/prosemirror/contentControlRevisions.d.ts +1 -1
  130. package/dist/prosemirror/conversion/fromProseDoc.js +1 -1
  131. package/dist/prosemirror/documentStructureCounts.d.ts +24 -0
  132. package/dist/prosemirror/documentStructureCounts.js +76 -0
  133. package/dist/prosemirror/extensions/ExtensionManager.d.ts +1 -1
  134. package/dist/prosemirror/extensions/StarterKit.d.ts +1 -1
  135. package/dist/prosemirror/extensions/core/HistoryExtension.d.ts +1 -7
  136. package/dist/prosemirror/extensions/core/HistoryExtension.js +5 -13
  137. package/dist/prosemirror/extensions/core/ParagraphExtension.js +1 -1
  138. package/dist/prosemirror/extensions/core/historyCommands.d.ts +16 -0
  139. package/dist/prosemirror/extensions/core/historyCommands.js +19 -0
  140. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +1 -1
  141. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +2 -35
  142. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.js +4 -142
  143. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +3 -87
  144. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.js +7 -162
  145. package/dist/prosemirror/extensions/features/pastedCellSections.d.ts +1 -1
  146. package/dist/prosemirror/extensions/features/pastedHeadingStyles.js +1 -1
  147. package/dist/prosemirror/extensions/marks/markUtils.d.ts +1 -1
  148. package/dist/prosemirror/extensions/nodes/TableExtension.d.ts +1 -1
  149. package/dist/prosemirror/extensions/nodes/TableExtension.js +2 -2
  150. package/dist/prosemirror/extensions/types.d.ts +1 -1
  151. package/dist/prosemirror/findReplaceSelection.d.ts +1 -1
  152. package/dist/prosemirror/hyperlinkRemoval.d.ts +1 -1
  153. package/dist/prosemirror/index.d.ts +1 -1
  154. package/dist/prosemirror/index.js +1 -1
  155. package/dist/prosemirror/insertionGaps.d.ts +1 -1
  156. package/dist/prosemirror/keptRangeBoundaries.d.ts +1 -1
  157. package/dist/prosemirror/listNumbering.d.ts +1 -1
  158. package/dist/prosemirror/lockedControls.d.ts +1 -1
  159. package/dist/prosemirror/markupViewProjection.d.ts +1 -1
  160. package/dist/prosemirror/noteReferenceOccurrences.d.ts +1 -1
  161. package/dist/prosemirror/noteReferenceReview.js +1 -1
  162. package/dist/prosemirror/paraIds.d.ts +46 -0
  163. package/dist/prosemirror/paraIds.js +152 -0
  164. package/dist/prosemirror/paragraphChangeTrackerMeta.d.ts +97 -0
  165. package/dist/prosemirror/paragraphChangeTrackerMeta.js +87 -0
  166. package/dist/prosemirror/paragraphMarkJoin.d.ts +1 -1
  167. package/dist/prosemirror/paragraphPropertyCarry.d.ts +1 -1
  168. package/dist/prosemirror/pastedCommentCopies.d.ts +1 -1
  169. package/dist/prosemirror/pastedCommentCopies.js +1 -1
  170. package/dist/prosemirror/plugins/createDocScanPlugin.d.ts +1 -1
  171. package/dist/prosemirror/plugins/documentNumbering.d.ts +1 -1
  172. package/dist/prosemirror/plugins/suggestionMode.d.ts +1 -1
  173. package/dist/prosemirror/plugins/templateDirectives.d.ts +1 -1
  174. package/dist/prosemirror/rebaseParagraphRunFormatting.d.ts +1 -1
  175. package/dist/prosemirror/rebaseParagraphRuns.d.ts +1 -1
  176. package/dist/prosemirror/rejoinRunCarriers.d.ts +1 -1
  177. package/dist/prosemirror/replacedAnnotations.d.ts +1 -1
  178. package/dist/prosemirror/replacedAnnotations.js +16 -1
  179. package/dist/prosemirror/revisionCarriers.d.ts +1 -1
  180. package/dist/prosemirror/runFormattingInlineCarriers.d.ts +1 -1
  181. package/dist/prosemirror/sectionMarkEdits.d.ts +1 -1
  182. package/dist/prosemirror/selectionBounds.d.ts +10 -0
  183. package/dist/prosemirror/selectionBounds.js +22 -0
  184. package/dist/prosemirror/storyListNumbering.d.ts +1 -1
  185. package/dist/prosemirror/tableCellPaste.d.ts +1 -1
  186. package/dist/prosemirror/tableGridMutation.d.ts +1 -1
  187. package/dist/prosemirror/textInput.d.ts +1 -1
  188. package/dist/server.d.ts +7 -2
  189. package/dist/server.js +6 -1
  190. package/dist/types/canonicalCapabilities.d.ts +8 -41
  191. package/dist/types/canonicalCapabilities.js +6 -34
  192. package/package.json +4 -4
@@ -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
@@ -93,14 +68,6 @@ import { EditorState, Selection, TextSelection } from "prosemirror-state";
93
68
  *
94
69
  * Scope: main, header, footer, footnote, and endnote blocks.
95
70
  */
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
71
  /**
105
72
  * How many document-operation batches a reviewer can step back through.
106
73
  * Each entry holds the story's state before and after its batch; older
@@ -175,67 +142,12 @@ const UnsupportedFolioReviewedViewErrorBase = TaggedError("UnsupportedFolioRevie
175
142
  var UnsupportedFolioReviewedViewError = class extends UnsupportedFolioReviewedViewErrorBase {};
176
143
  const FolioRoomJournalErrorBase = TaggedError("FolioRoomJournalError");
177
144
  /**
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.
145
+ * Why a reviewer could not replay a room's journal. `revisionGap`: a batch is
146
+ * not the one after the last the reviewer applied.
181
147
  */
182
148
  var FolioRoomJournalError = class extends FolioRoomJournalErrorBase {};
183
149
  const FolioDocumentStoryNotFoundErrorBase = TaggedError("FolioDocumentStoryNotFoundError");
184
150
  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
151
  const numberingLevelsOf = (numbering) => {
240
152
  if (!numbering) return [];
241
153
  return numberingLevelEntries(numbering).map(({ numId, ilvl, level }) => {
@@ -283,20 +195,6 @@ const noteStoryHandleOf = (key) => {
283
195
  noteId: Number(noteId)
284
196
  } : null;
285
197
  };
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
198
  /**
301
199
  * A part's roles as a reader label: `first`, or, in a document with several
302
200
  * sections, `first (sections 1, 3), default (section 2)`.
@@ -310,15 +208,6 @@ const secondaryStoryKey = (story) => story.type === "header" || story.type === "
310
208
  const editableStoryKey = (story) => story.type === "main" ? "main" : secondaryStoryKey(story);
311
209
  const isFolioReviewedView = (value) => FOLIO_REVIEWED_VIEWS.some((view) => view === value);
312
210
  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
211
  /** A state's snapshot, of `doc` when it names the state's document otherwise spelled. */
323
212
  const createStateSnapshot = (state, positionalParaIds, doc = state.doc) => createReviewerSnapshot({
324
213
  doc,
@@ -571,22 +460,6 @@ const carriedByGroup = (id, groupIds, { removed, moved }) => {
571
460
  };
572
461
  };
573
462
  /**
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
463
  * One story's reading of the numbering: the lists the package was opened
591
464
  * with, and those started since that `doc`'s paragraphs name. A list another
592
465
  * story started is defined in that story's reading, not in this one.
@@ -626,27 +499,14 @@ var FolioDocxReviewer = class FolioDocxReviewer {
626
499
  * alike; a legacy state already holds every id.
627
500
  */
628
501
  snapshotOf(state) {
629
- return this.engine.type === "canonical" ? createStateSnapshot(state, this.positionalParaIds, ensureParaIdsInDoc(state.doc)) : createStateSnapshot(state, this.positionalParaIds);
502
+ return createStateSnapshot(state, this.positionalParaIds, ensureParaIdsInDoc(state.doc));
630
503
  }
631
504
  /** Default author for tracked changes and comments. */
632
505
  author;
633
- /** The legacy reviewer's parsed model; a canonical one reads its session's. */
506
+ /** The model the reviewer was opened on; the readers follow the session's. */
634
507
  loadedDocument;
635
- finalSectionPropertiesOverride;
636
508
  originalBuffer;
637
509
  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
510
  /** Comments the body anchored when it was loaded, read as the editor projects it. */
651
511
  loadedMainCommentIds;
652
512
  /**
@@ -655,17 +515,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
655
515
  * pairs two documents' paragraphs by them.
656
516
  */
657
517
  positionalParaIds;
658
- documentOperationUndoEntries = [];
659
518
  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
519
  /** The last room revision {@link applyRoomJournal} applied. */
670
520
  roomRevision = 0;
671
521
  /** The resolved copies {@link resolvedSessionReader} last read, by view. */
@@ -679,86 +529,19 @@ var FolioDocxReviewer = class FolioDocxReviewer {
679
529
  this.originalBuffer = args.originalBuffer;
680
530
  this.state = args.state;
681
531
  this.author = args.author;
682
- this.engine = args.engine.type === "legacy" ? args.engine : this.canonicalEngine(args.engine.session);
532
+ this.engine = this.canonicalEngine(args.engine.session);
683
533
  this.commentIds = args.commentIds?.clone() ?? createCommentIdAllocator();
684
534
  seedCommentAllocator(this.commentIds, args.baseDocument.package.document.comments, { state: args.state });
685
535
  this.loadedMainCommentIds = new Set(args.loadedMainCommentIds ?? anchoredCommentIdsInProseDoc(args.state.doc));
686
536
  this.registerComparisonAccess();
687
537
  }
688
538
  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
- }));
539
+ comparisonAccessByReviewer.set(this, this.canonicalComparisonAccess());
757
540
  }
758
541
  stageTargetStyles({ source, snapshots, importedHeaderFooterSnapshots, numberingReferenceMap }) {
759
542
  const destination = this.baseDocument.package;
760
543
  const sourcePackage = source.baseDocument.package;
761
- const destinationStyles = this.importedStyles ?? destination.styles;
544
+ const destinationStyles = destination.styles;
762
545
  const sourceStylesById = new Map(sourcePackage.styles?.styles.map((style) => [style.styleId, style]));
763
546
  const destinationStyleIds = new Set(destinationStyles?.styles.map(({ styleId }) => styleId));
764
547
  const collect = (document) => {
@@ -823,39 +606,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
823
606
  reservedStyleIds: [...reservedStyleIds],
824
607
  materializeDefaultParagraphStyle
825
608
  });
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);
609
+ if (result.status === "imported") this.stagePackageResourcesOnSession({ styles: result.styles });
831
610
  return result;
832
611
  }
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
612
  stageTargetNumbering(target, references, remappedNumIds) {
860
613
  if (references.length === 0) return "unchanged";
861
614
  if (!target) return "conflict";
@@ -909,13 +662,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
909
662
  abstractNums: [...abstracts.values()],
910
663
  nums: [...nums.values()]
911
664
  };
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);
665
+ this.stagePackageResourcesOnSession({ numbering });
919
666
  return "staged";
920
667
  }
921
668
  planTargetNumberingReferences(target, references) {
@@ -957,37 +704,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
957
704
  return base.value;
958
705
  }
959
706
  /** 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
- });
707
+ static fromBuffer(buffer, options = {}) {
708
+ return FolioDocxReviewer.fromCanonicalBuffer(buffer, options);
991
709
  }
992
710
  /**
993
711
  * Load as a canonical editor does: the same input normalization (paragraph
@@ -1042,39 +760,20 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1042
760
  * either leave the other as it is. The copy's undo history starts empty.
1043
761
  */
1044
762
  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();
763
+ const document = readModel(this.engine.session.document);
764
+ const created = createCanonicalSession(document, document.package.styles);
765
+ if (created.isErr()) throw created.error;
1068
766
  const copy = new FolioDocxReviewer({
1069
- baseDocument: this.loadedDocument,
767
+ baseDocument: document,
1070
768
  originalBuffer: this.originalBuffer,
1071
- state: snapshot.mainState.apply(snapshot.mainState.tr),
769
+ state: canonicalReviewerState(created.value),
1072
770
  author: this.author,
1073
- engine: { type: "legacy" },
1074
- loadedMainCommentIds: this.loadedMainCommentIds,
1075
- commentIds: this.commentIds
771
+ engine: {
772
+ type: "canonical",
773
+ session: created.value
774
+ },
775
+ positionalParaIds: this.positionalParaIds
1076
776
  });
1077
- copy.restoreReviewerState(snapshot);
1078
777
  copy.pendingSuggestions = this.pendingSuggestions.clone();
1079
778
  return copy;
1080
779
  }
@@ -1087,7 +786,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1087
786
  stageTargetStyles: (options) => this.stageTargetStyles(options),
1088
787
  createComparisonHeaderFooter: (source, story) => this.createComparisonHeaderFooter(source, story),
1089
788
  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
789
  const result = matchInlineAtomsOnModel({
1092
790
  ...options,
1093
791
  document: this.engine.session.document,
@@ -1111,7 +809,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1111
809
  };
1112
810
  },
1113
811
  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
812
  const { session } = this.engine;
1116
813
  const projected = session.projectStory(canonicalOpStory(story));
1117
814
  if (projected.isErr()) throw projected.error;
@@ -1162,9 +859,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1162
859
  }
1163
860
  /** Resolve on an independent fork, then publish only the complete semantic projection. */
1164
861
  projectComparisonStoriesOnSession(mode) {
1165
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer projects comparison stories");
1166
862
  const copy = this.fork();
1167
- if (copy.engine.type !== "canonical") return panic("A canonical comparison fork must retain its engine");
1168
863
  const handles = copy.listStoryHandlesInternal();
1169
864
  const ids = /* @__PURE__ */ new Set();
1170
865
  let present = false;
@@ -1172,21 +867,22 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1172
867
  ids.add(change.info.id);
1173
868
  present = true;
1174
869
  }
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
870
  const operations = [];
1186
871
  const session = copy.engine.session;
1187
872
  const unsubscribe = session.onCommitted(({ ops }) => operations.push(...ops));
1188
873
  let stories;
1189
874
  try {
875
+ copy.promoteSuggestionsOnSession(session);
876
+ for (const handle of handles) {
877
+ const state = copy.getEditableStoryState(handle);
878
+ if (!state) continue;
879
+ if (getSuggestions(state).length > 0) throw canonicalReviewerRefusal("project a story holding a suggestion the session will not accept");
880
+ if (mode === "with-revision-census") {
881
+ const stats = getTrackedChangeStatsFromDoc(state.doc);
882
+ for (const id of stats.ids) ids.add(id);
883
+ present ||= stats.present;
884
+ }
885
+ }
1190
886
  stories = handles.map((handle) => {
1191
887
  return {
1192
888
  handle,
@@ -1224,12 +920,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1224
920
  * its journal holds the room's document, which `toBuffer` saves.
1225
921
  */
1226
922
  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
923
  for (const batch of journal) {
1234
924
  const expectedRevision = this.roomRevision + 1;
1235
925
  if (batch.revision !== expectedRevision) throw new FolioRoomJournalError({
@@ -1243,7 +933,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1243
933
  }
1244
934
  }
1245
935
  commitOpsOnSession(ops) {
1246
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer commits session operations");
1247
936
  const prepared = this.engine.session.prepareOperations(this.state, ops);
1248
937
  if (prepared.isErr()) {
1249
938
  if (prepared.error.reason === "noChange") return false;
@@ -1252,7 +941,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1252
941
  return this.publishOnSession(prepared.value);
1253
942
  }
1254
943
  stageMappedSectionBoundariesOnSession(options) {
1255
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer stages on the session");
1256
944
  const { session } = this.engine;
1257
945
  const result = stageSectionBoundaryOperations({
1258
946
  document: readModel(session.document),
@@ -1272,34 +960,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1272
960
  documentChanged: result.operations.length > 0 && this.commitOpsOnSession(result.operations)
1273
961
  };
1274
962
  }
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
- */
963
+ /** The model the readers read: the session's document after every commit. */
1301
964
  get baseDocument() {
1302
- return this.engine.type === "canonical" ? readModel(this.engine.session.document) : this.loadedDocument;
965
+ return readModel(this.engine.session.document);
1303
966
  }
1304
967
  /**
1305
968
  * Publish a commit the session prepared on the reviewer's main state. The
@@ -1307,7 +970,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1307
970
  * throws the session's refusal; nothing falls back to the legacy engine.
1308
971
  */
1309
972
  publishOnSession(commit) {
1310
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer publishes session commits");
1311
973
  const { session } = this.engine;
1312
974
  const published = publishCanonicalProjection({
1313
975
  state: commit.selection.anchor.story === OP_STORIES.MAIN ? this.state : canonicalStoryState(session, commit.transaction.before),
@@ -1337,7 +999,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1337
999
  throw error;
1338
1000
  }
1339
1001
  const absorptions = prepared.value.touched.absorbed ?? [];
1340
- const sourceSnapshotForStory = (story) => this.pendingSuggestionSource(story, /* @__PURE__ */ new Set());
1002
+ const sourceSnapshotForStory = (story) => this.pendingSuggestionSource(story);
1341
1003
  const absorption = absorptions.length === 0 ? null : this.pendingSuggestions.prepareAbsorption({
1342
1004
  survivors: new Map(absorptions.map(({ absorbed, survivor }) => [absorbed, survivor])),
1343
1005
  activeSuggestionIds: this.activeSuggestionIds(),
@@ -1504,38 +1166,14 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1504
1166
  snapshot() {
1505
1167
  return this.snapshotOf(this.state);
1506
1168
  }
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
1169
  /** Every suggestion id the document's stories still carry. */
1528
1170
  activeSuggestionIds() {
1529
1171
  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;
1172
+ for (const handle of this.listStoryHandlesInternal()) {
1173
+ if (handle.type === "main") continue;
1174
+ const state = this.getEditableStoryState(handle);
1175
+ for (const { suggestionId } of state ? getSuggestions(state) : []) active.add(suggestionId);
1537
1176
  }
1538
- for (const entry of this.secondaryStoryStates.values()) for (const { suggestionId } of getSuggestions(entry.state)) active.add(suggestionId);
1539
1177
  return active;
1540
1178
  }
1541
1179
  /** Export staged AI operations for storage by the host, outside the DOCX. */
@@ -1543,44 +1181,40 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1543
1181
  const active = this.activeSuggestionIds();
1544
1182
  return this.pendingSuggestions.exportPendingSuggestions({
1545
1183
  activeSuggestionIds: active,
1546
- snapshotForStory: (story, commentIds) => this.pendingSuggestionSource(story, commentIds),
1547
- stateForStory: (story) => this.engine.type === "canonical" ? this.getEditableStoryState(story) : null
1184
+ snapshotForStory: (story) => this.pendingSuggestionSource(story),
1185
+ stateForStory: (story) => this.getEditableStoryState(story)
1548
1186
  });
1549
1187
  }
1550
1188
  /**
1551
1189
  * 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.
1190
+ * suggestion record's fingerprint describes. It is read from a session over
1191
+ * the document the save writes, so a reviewer reopened on the saved package
1192
+ * reads the same story.
1555
1193
  */
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;
1194
+ pendingSuggestionSource(story) {
1195
+ if (!this.getEditableStoryState(story)) return null;
1196
+ const document = this.toDocument();
1197
+ const created = createCanonicalSession(document, document.package.styles);
1198
+ if (created.isErr()) throw created.error;
1199
+ const saved = new FolioDocxReviewer({
1200
+ baseDocument: document,
1201
+ originalBuffer: this.originalBuffer,
1202
+ state: canonicalReviewerState(created.value),
1203
+ author: this.author,
1204
+ engine: {
1205
+ type: "canonical",
1206
+ session: created.value
1207
+ },
1208
+ positionalParaIds: this.positionalParaIds
1209
+ }).getEditableStoryState(story);
1210
+ return saved ? createPendingSuggestionSourceSnapshot(saved, /* @__PURE__ */ new Set()) : null;
1577
1211
  }
1578
1212
  /** Validate saved proposals against this document before restaging them. */
1579
1213
  loadPendingSuggestions(records) {
1580
1214
  return this.pendingSuggestions.loadPendingSuggestions({
1581
1215
  records,
1582
1216
  snapshotForStory: (story) => this.snapshotStory(story),
1583
- sourceSnapshotForStory: (story, commentIds) => this.pendingSuggestionSource(story, commentIds),
1217
+ sourceSnapshotForStory: (story) => this.pendingSuggestionSource(story),
1584
1218
  apply: (record, snapshot) => {
1585
1219
  const restage = {
1586
1220
  undefinedReferences: "refuse",
@@ -1594,12 +1228,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1594
1228
  snapshot,
1595
1229
  author: record.author
1596
1230
  };
1597
- const result = this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1231
+ const result = this.applyDocumentOperationsOnSession({
1598
1232
  ...restage,
1599
1233
  operations: this.engine.operations
1600
- }) : this.applyDocumentOperationsInternal({
1601
- ...restage,
1602
- createUndoEntry: false
1603
1234
  });
1604
1235
  return {
1605
1236
  applied: result.applied,
@@ -1612,11 +1243,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1612
1243
  readNumberingDefinitions(story = MAIN_STORY) {
1613
1244
  const doc = story.type === "main" ? this.state.doc : this.readSecondaryStoryDoc(story);
1614
1245
  if (!doc) return null;
1615
- const numbering = this.engine.type === "canonical" ? storyOwnNumbering({
1246
+ const numbering = storyOwnNumbering({
1616
1247
  current: this.baseDocument.package.numbering,
1617
1248
  loaded: this.loadedDocument.package.numbering,
1618
1249
  doc
1619
- }) : completeNumberingForDoc(this.baseDocument.package.numbering, doc);
1250
+ });
1620
1251
  return numberingLevelsOf(numbering).toSorted((left, right) => left.numId - right.numId || left.level - right.level);
1621
1252
  }
1622
1253
  /** Return parsed package metadata without exposing the mutable document model. */
@@ -1648,39 +1279,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1648
1279
  const sourceState = this.getEditableStoryState(story);
1649
1280
  return sourceState ? this.snapshotOf(sourceState) : null;
1650
1281
  }
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
1282
  /**
1685
1283
  * One story's tables, in the document order {@link snapshotStory} numbers
1686
1284
  * them with, read through a reviewed view.
@@ -1717,7 +1315,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1717
1315
  matchStoryTableGeometry({ story = MAIN_STORY, targetTables, pairings, revisionStamp }) {
1718
1316
  const state = this.getEditableStoryState(story);
1719
1317
  if (!state || pairings.length === 0) return revisionStamp.idSeed;
1720
- if (this.engine.type === "canonical") {
1318
+ {
1721
1319
  const matched = matchTableGeometryOperations({
1722
1320
  story: canonicalOpStory(story),
1723
1321
  baseTables: folioStoryTables(state.doc),
@@ -1733,20 +1331,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1733
1331
  if (matched.operations.length > 0) this.commitOpsOnSession(matched.operations);
1734
1332
  return matched.nextRevisionId;
1735
1333
  }
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
1334
  }
1751
1335
  /**
1752
1336
  * Read one story through an immutable reviewed-view projection. A canonical
@@ -1769,35 +1353,13 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1769
1353
  };
1770
1354
  }
1771
1355
  /**
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.
1356
+ * Resolve one editable story to its original or final state, its staged
1357
+ * suggestions with its other changes. A suggestion that reaches another
1358
+ * story resolves only whole, through the suggestion methods. A lock that
1359
+ * prevents any target change from resolving refuses before mutation.
1776
1360
  */
1777
1361
  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;
1362
+ return this.resolveStoryOnSession(this.engine.session, story, view);
1801
1363
  }
1802
1364
  /**
1803
1365
  * Apply operations against the current state. Reuses the live-editor applier
@@ -1817,12 +1379,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1817
1379
  ...options.wordDiff !== void 0 && { wordDiff: options.wordDiff },
1818
1380
  undefinedReferences: options.undefinedReferences
1819
1381
  };
1820
- const { applied, skipped } = this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1382
+ const { applied, skipped } = this.applyDocumentOperationsOnSession({
1821
1383
  ...internal,
1822
1384
  operations: this.engine.operations
1823
- }) : this.applyDocumentOperationsInternal({
1824
- ...internal,
1825
- createUndoEntry: false
1826
1385
  });
1827
1386
  return {
1828
1387
  applied,
@@ -1844,12 +1403,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1844
1403
  ...options.wordDiff !== void 0 && { wordDiff: options.wordDiff },
1845
1404
  undefinedReferences: options.undefinedReferences
1846
1405
  };
1847
- return this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1406
+ return this.applyDocumentOperationsOnSession({
1848
1407
  ...internal,
1849
1408
  operations: this.engine.operations
1850
- }) : this.applyDocumentOperationsInternal({
1851
- ...internal,
1852
- createUndoEntry: true
1853
1409
  });
1854
1410
  }
1855
1411
  /** Apply a versioned operation batch to one editable document story. */
@@ -1864,140 +1420,18 @@ var FolioDocxReviewer = class FolioDocxReviewer {
1864
1420
  ...replacementBackground !== void 0 && { replacementBackground },
1865
1421
  undefinedReferences
1866
1422
  };
1867
- return this.engine.type === "canonical" ? this.applyDocumentOperationsOnSession({
1423
+ return this.applyDocumentOperationsOnSession({
1868
1424
  ...internal,
1869
1425
  operations: this.engine.operations
1870
- }) : this.applyDocumentOperationsInternal({
1871
- ...internal,
1872
- createUndoEntry: true
1873
1426
  });
1874
1427
  }
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
1428
  /**
1965
1429
  * Undo the latest unchanged document-operation batch and its created
1966
1430
  * comments. Only the last {@link FOLIO_DOCUMENT_OPERATION_UNDO_LIMIT}
1967
1431
  * batches are kept; an older handle is `unknownHandle`.
1968
1432
  */
1969
1433
  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
- };
1434
+ return this.engine.operations.undo(undoHandle);
2001
1435
  }
2002
1436
  /**
2003
1437
  * The body blocks with their stable ids, in document order — the same
@@ -2064,32 +1498,23 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2064
1498
  type: "header",
2065
1499
  relationshipId
2066
1500
  });
2067
- for (const relationshipId of this.importedHeaders.keys()) handles.push({
2068
- type: "header",
2069
- relationshipId
2070
- });
2071
1501
  for (const relationshipId of pkg.footers?.keys() ?? []) handles.push({
2072
1502
  type: "footer",
2073
1503
  relationshipId
2074
1504
  });
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({
1505
+ for (const footnote of pkg.footnotes ?? []) if (!isSeparatorFootnote(footnote)) handles.push({
2081
1506
  type: "footnote",
2082
1507
  noteId: footnote.id
2083
1508
  });
2084
- for (const endnote of notes.endnotes ?? []) if (!isSeparatorEndnote(endnote)) handles.push({
1509
+ for (const endnote of pkg.endnotes ?? []) if (!isSeparatorEndnote(endnote)) handles.push({
2085
1510
  type: "endnote",
2086
1511
  noteId: endnote.id
2087
1512
  });
2088
- const retired = this.engine.type === "canonical" ? this.engine.session.retiredHeaderFooters() : void 0;
1513
+ const retired = this.engine.session.retiredHeaderFooters();
2089
1514
  return handles.filter((handle) => {
2090
1515
  if (handle.type === "header" || handle.type === "footer") {
2091
1516
  const key = headerFooterStoryKey(handle);
2092
- return !this.removedHeaderFooterStories.has(key) && !retired?.has(key);
1517
+ return !retired.has(key);
2093
1518
  }
2094
1519
  return true;
2095
1520
  });
@@ -2140,7 +1565,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2140
1565
  if (!doc) continue;
2141
1566
  for (const id of coveredCommentIdsInProseDoc(doc)) covered.add(id);
2142
1567
  }
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)));
1568
+ const definitions = this.keptCommentThreads(this.currentCommentDefinitions(), this.state).filter(({ id, parentId, anchorKind }) => anchorKind !== "range" || parentId !== void 0 || covered.has(id));
2144
1569
  if (definitions.length === 0) return [];
2145
1570
  const repliesByParent = /* @__PURE__ */ new Map();
2146
1571
  const topLevel = [];
@@ -2194,36 +1619,17 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2194
1619
  roots.set(id, parentId !== void 0 && knownIds.has(parentId) ? "reply" : "thread");
2195
1620
  }
2196
1621
  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);
1622
+ const prepared = this.engine.session.prepareOperations(this.state, [...roots].map(([id, scope]) => ({
1623
+ type: DOCUMENT_OP_TYPES.DELETE_COMMENT,
1624
+ id,
1625
+ scope
1626
+ })));
1627
+ if (prepared.isErr()) throw prepared.error;
1628
+ this.publishOnSession(prepared.value);
2206
1629
  return { deleted: [...removed].sort((left, right) => left - right) };
2207
1630
  }
2208
1631
  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);
1632
+ return [...this.baseDocument.package.document.comments ?? []];
2227
1633
  }
2228
1634
  /**
2229
1635
  * Add a reply to a comment thread. Pass a {@link FolioReviewComment} from
@@ -2236,56 +1642,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2236
1642
  */
2237
1643
  replyTo(target, input) {
2238
1644
  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
- }
1645
+ return this.replyOnSession(this.engine.session, parentId, input);
2289
1646
  }
2290
1647
  /**
2291
1648
  * Mark a comment thread resolved, or reopen a previously resolved one. Pass
@@ -2301,11 +1658,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2301
1658
  */
2302
1659
  resolveComment(commentId, options = {}) {
2303
1660
  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;
1661
+ return this.resolveCommentOnSession(this.engine.session, commentId, resolved);
2309
1662
  }
2310
1663
  /** Run a semantic comment command as one session commit, as the editor does. */
2311
1664
  commitCommentOnSession(session, command) {
@@ -2399,47 +1752,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2399
1752
  };
2400
1753
  }
2401
1754
  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;
1755
+ return this.baseDocument.package.document.finalSectionProperties;
2443
1756
  }
2444
1757
  /**
2445
1758
  * Accept an existing tracked change, keeping its text and dropping the
@@ -2452,64 +1765,22 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2452
1765
  * removal. A held change stays pending as it is.
2453
1766
  */
2454
1767
  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;
1768
+ return this.resolveChangeOnSession(target, "accept");
2468
1769
  }
2469
1770
  /**
2470
1771
  * Reject an existing tracked change: an insertion's text is removed, a
2471
1772
  * deletion's text is restored. See {@link acceptChange} for targeting.
2472
1773
  */
2473
1774
  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;
1775
+ return this.resolveChangeOnSession(target, "reject");
2487
1776
  }
2488
1777
  /** Convert one pending suggestion into an ordinary tracked change. */
2489
1778
  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
- });
1779
+ return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "accept", options?.author ?? this.author);
2500
1780
  }
2501
1781
  /** Remove one pending suggestion without applying it. */
2502
1782
  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
- });
1783
+ return this.resolveSuggestionOnSession(this.engine.session, suggestionId, "reject", this.author);
2513
1784
  }
2514
1785
  /**
2515
1786
  * Accept every ordinary tracked change in the package. Pending suggestions
@@ -2525,11 +1796,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2525
1796
  * ordinary changes resolved.
2526
1797
  */
2527
1798
  acceptAll() {
2528
- return this.engine.type === "canonical" ? this.resolveAllOnSession(this.engine.session, "accept") : this.resolveAll("accept");
1799
+ return this.resolveAllOnSession(this.engine.session, "accept");
2529
1800
  }
2530
1801
  /** Reject every tracked change in the package. See {@link acceptAll}. */
2531
1802
  rejectAll() {
2532
- return this.engine.type === "canonical" ? this.resolveAllOnSession(this.engine.session, "reject") : this.resolveAll("reject");
1803
+ return this.resolveAllOnSession(this.engine.session, "reject");
2533
1804
  }
2534
1805
  /**
2535
1806
  * One change of the body, resolved by the session's review intent: every
@@ -2537,7 +1808,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2537
1808
  * several ids) resolves together, as the editor resolves it.
2538
1809
  */
2539
1810
  resolveChangeOnSession(target, resolution) {
2540
- if (this.engine.type !== "canonical") return panic("Only a canonical reviewer resolves on the session");
2541
1811
  const { session } = this.engine;
2542
1812
  const id = revisionIdOf(target);
2543
1813
  const suggestionId = suggestionIdOfRevision(this.state, id);
@@ -2628,259 +1898,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2628
1898
  ...outcome.absorbedBlocks.length === 0 ? {} : { absorbedBlocks: outcome.absorbedBlocks }
2629
1899
  };
2630
1900
  }
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
1901
  /** Resolve ordinary revisions on a detached in-memory document. */
2885
1902
  toResolvedDocument(decision) {
2886
1903
  return this.resolvedCopy(decision === "accept" ? "final" : "original").toDocument();
@@ -2892,23 +1909,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2892
1909
  * way, or a legacy reviewer over the model that resolution returns.
2893
1910
  */
2894
1911
  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
- });
1912
+ return this.resolvedSessionCopy(this.engine.session, view);
2908
1913
  }
2909
1914
  /** The {@link resolvedCopy} a reader takes one story of. */
2910
1915
  resolvedReader(view) {
2911
- return this.engine.type === "canonical" ? this.resolvedSessionReader(this.engine.session, view) : this.resolvedCopy(view);
1916
+ return this.resolvedSessionReader(this.engine.session, view);
2912
1917
  }
2913
1918
  /**
2914
1919
  * The {@link resolvedSessionCopy} a reader takes one story of: the stories
@@ -2927,19 +1932,6 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2927
1932
  return reviewer;
2928
1933
  }
2929
1934
  /**
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
1935
  * A reviewer on a second session over the current document, as a reviewer
2944
1936
  * reopened on it would hold it, with every change resolved to `view`. This
2945
1937
  * reviewer's session and journal are left as they are; what the session
@@ -2961,6 +1953,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2961
1953
  positionalParaIds: this.positionalParaIds
2962
1954
  });
2963
1955
  copy.pendingSuggestions = this.pendingSuggestions.clone();
1956
+ if (view === "final") copy.promoteSuggestionsOnSession(created.value);
2964
1957
  if ((view === "final" ? copy.acceptAll() : copy.rejectAll()).skipped.length > 0) throw new CanonicalSessionError({
2965
1958
  reason: "refused",
2966
1959
  ground: { rule: CANONICAL_RULE.contentControlLock },
@@ -2970,6 +1963,43 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2970
1963
  return copy;
2971
1964
  }
2972
1965
  /**
1966
+ * Turn every staged suggestion into an ordinary tracked change, so that
1967
+ * accepting every change accepts the suggestions too.
1968
+ */
1969
+ promoteSuggestionsOnSession(session) {
1970
+ for (const suggestionId of this.activeSuggestionIds()) this.resolveSuggestionOnSession(session, suggestionId, "accept", this.author);
1971
+ }
1972
+ /**
1973
+ * A story holding staged suggestions resolved to `view`: its suggestions
1974
+ * resolve with its other changes, on a fork, and the fork's operations
1975
+ * land here as one commit, so a refusal leaves this reviewer as it was. A
1976
+ * suggestion that reaches another story resolves only whole, so resolving
1977
+ * one of its stories refuses.
1978
+ */
1979
+ resolveStoryWithSuggestions({ story, view, staged }) {
1980
+ const key = editableStoryKey(story);
1981
+ for (const handle of this.listStoryHandlesInternal()) {
1982
+ if (editableStoryKey(handle) === key) continue;
1983
+ const other = this.getEditableStoryState(handle);
1984
+ if (other && getSuggestions(other).some(({ suggestionId }) => staged.has(suggestionId))) throw canonicalReviewerRefusal("resolve one story of a suggestion that reaches another");
1985
+ }
1986
+ const copy = this.fork();
1987
+ const { session } = copy.engine;
1988
+ const operations = [];
1989
+ const unsubscribe = session.onCommitted(({ ops }) => operations.push(...ops));
1990
+ let resolved;
1991
+ try {
1992
+ for (const suggestionId of staged) copy.resolveSuggestionOnSession(session, suggestionId, view === "final" ? "accept" : "reject", this.author);
1993
+ const after = copy.getEditableStoryState(story);
1994
+ if (after && getSuggestions(after).length > 0) throw canonicalReviewerRefusal("resolve a story holding a suggestion the session will not resolve");
1995
+ resolved = copy.resolveStoryOnSession(session, story, view);
1996
+ } finally {
1997
+ unsubscribe();
1998
+ }
1999
+ if (operations.length > 0) this.commitOpsOnSession(operations);
2000
+ return resolved;
2001
+ }
2002
+ /**
2973
2003
  * Resolve one story's changes to `view` in one session commit: the body's
2974
2004
  * through the review intent, another story's as its resolution operation.
2975
2005
  */
@@ -2980,7 +2010,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
2980
2010
  });
2981
2011
  const state = this.getEditableStoryState(story);
2982
2012
  if (!state) return false;
2983
- if (getSuggestions(state).length > 0) throw canonicalReviewerRefusal("resolve a story holding pending suggestions");
2013
+ const staged = new Set(getSuggestions(state).map(({ suggestionId }) => suggestionId));
2014
+ if (staged.size > 0) return this.resolveStoryWithSuggestions({
2015
+ story,
2016
+ view,
2017
+ staged
2018
+ });
2984
2019
  const resolution = view === "final" ? "accept" : "reject";
2985
2020
  const section = story.type === "main" ? this.finalSectionOperation((current) => resolveSectionChanges(current, resolution)) : null;
2986
2021
  const groups = listedRevisionGroups(state.doc).map(({ groupIds }) => groupIds);
@@ -3021,184 +2056,9 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3021
2056
  }
3022
2057
  /** The current document model with edits merged back in. */
3023
2058
  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
- };
2059
+ const model = withoutPendingSuggestions(this.engine.session.captureSaveSnapshot().document);
2060
+ if (model.isErr()) throw model.error;
2061
+ return cloneDocumentWithParagraphPropertySources(reconcileDocumentPartRelationships(model.value));
3202
2062
  }
3203
2063
  /**
3204
2064
  * Serialise the reviewed document to a new `.docx` buffer. Tries a selective
@@ -3216,43 +2076,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3216
2076
  * With `repack: "refuse"`, a save the selective patch cannot express
3217
2077
  * returns the reason instead of rewriting every part.
3218
2078
  */
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
- };
2079
+ save({ repack: repackPolicy = "allow" } = {}) {
2080
+ return this.saveOnSession(this.engine.session, repackPolicy);
3256
2081
  }
3257
2082
  /**
3258
2083
  * The editor's canonical save of the session's committed snapshot: the
@@ -3286,79 +2111,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3286
2111
  buffer: saved.buffer
3287
2112
  };
3288
2113
  }
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
2114
  getEditableStoryState(story) {
3336
2115
  if (story.type === "main") return this.state;
3337
2116
  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;
2117
+ const projected = this.engine.session.projectStory(canonicalOpStory(story));
2118
+ if (projected.isErr()) throw projected.error;
2119
+ return canonicalStoryState(this.engine.session, projected.value.doc, projected.value);
3362
2120
  }
3363
2121
  /**
3364
2122
  * A secondary story as its editable state holds it: the loaded state's
@@ -3367,8 +2125,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3367
2125
  * state for a story nothing edits.
3368
2126
  */
3369
2127
  readSecondaryStoryDoc(story) {
3370
- if (!this.secondaryStorySource(story)) return null;
3371
- return this.secondaryStoryStates.get(secondaryStoryKey(story))?.state.doc ?? this.secondaryStoryDoc(story);
2128
+ return this.secondaryStoryDoc(story);
3372
2129
  }
3373
2130
  secondaryStorySource(story) {
3374
2131
  return story.type === "header" || story.type === "footer" ? this.getHeaderFooterStory(story) : this.getNoteStory(story);
@@ -3380,49 +2137,12 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3380
2137
  * session's story projections yet.
3381
2138
  */
3382
2139
  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);
2140
+ if (!this.secondaryStorySource(story)) return null;
2141
+ const projected = this.engine.session.projectStory(canonicalOpStory(story));
2142
+ if (projected.isErr()) throw projected.error;
2143
+ return projected.value.doc;
3421
2144
  }
3422
2145
  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
2146
  return (story.type === "header" ? this.baseDocument.package.headers : this.baseDocument.package.footers)?.get(story.relationshipId);
3427
2147
  }
3428
2148
  async createComparisonHeaderFooter(source, story) {
@@ -3447,7 +2167,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3447
2167
  const existingPaths = new Set(originalZip.paths().map((path) => path.toLowerCase()));
3448
2168
  let suffix = 1;
3449
2169
  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}`;
2170
+ while (existingPaths.has(path.toLowerCase()) || this.baseDocument.package.media?.has(path)) path = `word/media/folio-import-${++suffix}.${extension}`;
3451
2171
  importedMedia = {
3452
2172
  ...media,
3453
2173
  path,
@@ -3465,9 +2185,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3465
2185
  const taken = /* @__PURE__ */ new Set([
3466
2186
  ...this.baseDocument.package.relationships?.keys() ?? [],
3467
2187
  ...this.baseDocument.package.headers?.keys() ?? [],
3468
- ...this.baseDocument.package.footers?.keys() ?? [],
3469
- ...this.importedHeaders.keys(),
3470
- ...this.importedFooters.keys()
2188
+ ...this.baseDocument.package.footers?.keys() ?? []
3471
2189
  ]);
3472
2190
  let suffix = 1;
3473
2191
  let relationshipId = `rId${suffix}`;
@@ -3485,52 +2203,37 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3485
2203
  content: []
3486
2204
  }]
3487
2205
  };
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
- }
2206
+ const document = this.baseDocument;
2207
+ const minted = this.engine.session.freshBlockIds([1]);
2208
+ if (minted.isErr()) throw minted.error;
2209
+ const paraId = minted.value.at(0)?.at(0);
2210
+ if (paraId === void 0) return panic("The session minted no paragraph id for a header part");
2211
+ const entries = [...(story.type === "header" ? document.package.headers : document.package.footers) ?? /* @__PURE__ */ new Map(), [relationshipId, {
2212
+ ...empty,
2213
+ content: [{
2214
+ type: "paragraph",
2215
+ paraId,
2216
+ content: []
2217
+ }]
2218
+ }]];
2219
+ const parts = story.type === "header" ? { headers: entries } : { footers: entries };
2220
+ const ops = [];
2221
+ if (importedMedia) ops.push(packageResourcesOpOf({
2222
+ before: document,
2223
+ after: {
2224
+ ...document,
2225
+ package: {
2226
+ ...document.package,
2227
+ media: new Map([...document.package.media ?? /* @__PURE__ */ new Map(), [importedMedia.path, importedMedia]])
3512
2228
  }
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)
2229
+ }
3528
2230
  }));
3529
- this.secondaryStoryStates.set(headerFooterStoryKey(handle), {
3530
- handle,
3531
- initialState: state,
3532
- state
2231
+ ops.push({
2232
+ type: DOCUMENT_OP_TYPES.RESTORE_STORY_PARTS,
2233
+ expected: captureStoryParts(document, parts),
2234
+ parts
3533
2235
  });
2236
+ this.commitOpsOnSession(ops);
3534
2237
  return handle;
3535
2238
  }
3536
2239
  canImportHeaderFooterContent(source, story) {
@@ -3541,7 +2244,7 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3541
2244
  return snapshot !== null && detachFolioAIEditSnapshotExternalHyperlinks(snapshot) !== null;
3542
2245
  }
3543
2246
  getNoteStory(story) {
3544
- const notes = noteStoryInventory(this.baseDocument.package, this.removedNoteStories);
2247
+ const notes = this.baseDocument.package;
3545
2248
  if (story.type === "footnote") return notes.footnotes?.find((note) => note.id === story.noteId && !isSeparatorFootnote(note));
3546
2249
  return notes.endnotes?.find((note) => note.id === story.noteId && !isSeparatorEndnote(note));
3547
2250
  }
@@ -3556,19 +2259,11 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3556
2259
  * another after. This is the conversion the save path already performs on the
3557
2260
  * same states, so the text now describes exactly what a save would write.
3558
2261
  */
3559
- storyBlocks(state, source) {
3560
- return state ? proseDocToBlocks(rejectEverySuggestion(state).doc, source.content, this.baseDocument.package.styles) : source.content;
2262
+ getHeaderFooterStoryText(source) {
2263
+ return normalizeFolioAIBlockText(getHeaderFooterText(source));
3561
2264
  }
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);
2265
+ getNoteStoryText(source) {
2266
+ const { content } = source;
3572
2267
  return normalizeFolioAIBlockText(source.type === "footnote" ? getFootnoteText({
3573
2268
  ...source,
3574
2269
  content
@@ -3582,119 +2277,33 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3582
2277
  if (story.type === "header" || story.type === "footer") {
3583
2278
  const source = this.getHeaderFooterStory(story);
3584
2279
  if (!source) return panic("A listed document story no longer exists", { story });
3585
- return this.getHeaderFooterStoryText(story, source);
2280
+ return this.getHeaderFooterStoryText(source);
3586
2281
  }
3587
2282
  const source = this.getNoteStory(story);
3588
2283
  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
- });
2284
+ return this.getNoteStoryText(source);
3655
2285
  }
3656
2286
  /**
3657
2287
  * `comments` without the threads an edit left anchored nowhere: anchored in
3658
2288
  * a story when it was loaded (or created anchored by this reviewer), and
3659
2289
  * anchored in no story now. See `comment-lifecycle.ts`.
3660
2290
  */
3661
- keptCommentThreads(comments, mainState, secondaryStoryStates) {
2291
+ keptCommentThreads(comments, mainState) {
3662
2292
  const anchoredBefore = new Set(this.loadedMainCommentIds);
3663
- for (const { id } of this.createdComments) anchoredBefore.add(id);
3664
2293
  const anchoredNow = anchoredCommentIdsInProseDoc(mainState.doc);
3665
- const loaded = /* @__PURE__ */ new Map();
3666
- for (const entry of secondaryStoryStates) loaded.set(secondaryStoryKey(entry.handle), entry);
3667
2294
  const addAll = (target, ids) => {
3668
2295
  for (const id of ids) target.add(id);
3669
2296
  };
3670
2297
  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
2298
  for (const handle of this.listStoryHandlesInternal()) {
3677
2299
  if (handle.type === "main") continue;
3678
- if (loaded.get(secondaryStoryKey(handle))) continue;
3679
2300
  const source = handle.type === "header" || handle.type === "footer" ? this.getHeaderFooterStory(handle) : this.getNoteStory(handle);
3680
2301
  addAll(anchoredNow, anchoredCommentIdsInBlocks(source?.content ?? []));
3681
2302
  }
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
2303
  for (const [key, state] of referenceStates) {
3695
2304
  if (state !== "deleted") continue;
3696
2305
  const handle = noteStoryHandleOf(key);
3697
- if (!handle || loaded.has(secondaryStoryKey(handle))) continue;
2306
+ if (!handle) continue;
3698
2307
  addAll(anchoredNow, anchoredCommentIdsInBlocks(this.getNoteStory(handle)?.content ?? []));
3699
2308
  }
3700
2309
  return withoutLostCommentThreads(comments, {
@@ -3721,38 +2330,8 @@ var FolioDocxReviewer = class FolioDocxReviewer {
3721
2330
  if (!doc) continue;
3722
2331
  add(doc, story);
3723
2332
  }
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
2333
  return anchors;
3730
2334
  }
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
2335
  };
3757
2336
  /** @internal Comparison-only access to atomic and fresh reviewer projections. */
3758
2337
  const getFolioDocxComparisonAccess = (reviewer) => {