@stll/folio-core 0.66.2 → 0.68.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 (323) hide show
  1. package/dist/ai-edits/apply.d.ts +9 -1
  2. package/dist/ai-edits/apply.js +138 -17
  3. package/dist/ai-edits/batch-claims.js +5 -3
  4. package/dist/ai-edits/clean-text.js +4 -1
  5. package/dist/ai-edits/headless.d.ts +36 -21
  6. package/dist/ai-edits/headless.js +104 -34
  7. package/dist/ai-edits/index.d.ts +2 -2
  8. package/dist/ai-edits/note-references.d.ts +6 -0
  9. package/dist/ai-edits/note-references.js +7 -1
  10. package/dist/ai-edits/read.d.ts +19 -0
  11. package/dist/ai-edits/read.js +6 -4
  12. package/dist/ai-edits/snapshot.d.ts +6 -0
  13. package/dist/ai-edits/snapshot.js +32 -17
  14. package/dist/ai-edits/table-cell-mutations.js +3 -2
  15. package/dist/ai-edits/table-row-column-mutations.js +20 -6
  16. package/dist/ai-edits/types.d.ts +9 -1
  17. package/dist/ai-suggestions/apply.js +13 -4
  18. package/dist/compare/compare.js +2 -1
  19. package/dist/compare/inserted-resource-snapshot.d.ts +4 -1
  20. package/dist/compare/inserted-resource-snapshot.js +7 -3
  21. package/dist/controller/canonicalClipboard.js +29 -12
  22. package/dist/controller/canonicalComposition.d.ts +1 -1
  23. package/dist/controller/canonicalComposition.js +77 -19
  24. package/dist/controller/canonicalInlineProjection.d.ts +35 -10
  25. package/dist/controller/canonicalInlineProjection.js +192 -28
  26. package/dist/controller/canonicalInput.d.ts +2 -2
  27. package/dist/controller/canonicalInput.js +47 -2
  28. package/dist/controller/canonicalListRendering.d.ts +2 -1
  29. package/dist/controller/canonicalListRendering.js +1 -1
  30. package/dist/controller/canonicalLockGuard.d.ts +8 -0
  31. package/dist/controller/canonicalLockGuard.js +88 -0
  32. package/dist/controller/canonicalPublicOperations.d.ts +12 -4
  33. package/dist/controller/canonicalPublicOperations.js +274 -20
  34. package/dist/controller/canonicalSession.d.ts +87 -7
  35. package/dist/controller/canonicalSession.js +328 -75
  36. package/dist/controller/canonicalStoryEditor.d.ts +3 -2
  37. package/dist/controller/canonicalStoryEditor.js +4 -3
  38. package/dist/controller/canonicalStructure.d.ts +2 -1
  39. package/dist/controller/canonicalStructure.js +129 -7
  40. package/dist/controller/contentControlWidgetController.d.ts +5 -0
  41. package/dist/controller/contentControlWidgetController.js +13 -1
  42. package/dist/controller/folioEditor.js +1 -0
  43. package/dist/controller/headerFooterEditorManager.d.ts +2 -2
  44. package/dist/controller/headerFooterEditorManager.js +5 -5
  45. package/dist/controller/hiddenEditorApi.d.ts +6 -0
  46. package/dist/controller/hiddenEditorApi.js +1 -0
  47. package/dist/controller/hiddenEditorManager.d.ts +10 -3
  48. package/dist/controller/hiddenEditorManager.js +94 -38
  49. package/dist/controller/layoutPipeline.d.ts +2 -0
  50. package/dist/controller/layoutPipeline.js +55 -18
  51. package/dist/controller/layoutSession.d.ts +1 -0
  52. package/dist/controller/noteEditorManager.d.ts +2 -2
  53. package/dist/controller/noteEditorManager.js +5 -5
  54. package/dist/display-list/build/pageFurniture.js +41 -19
  55. package/dist/display-list/build/tablePrimitives.d.ts +3 -1
  56. package/dist/display-list/build/tablePrimitives.js +49 -14
  57. package/dist/display-list/dom/renderDisplayListToDom.js +4 -4
  58. package/dist/document-operations.d.ts +8 -0
  59. package/dist/document-operations.js +4 -3
  60. package/dist/docx/blockContentParser.d.ts +7 -3
  61. package/dist/docx/blockContentParser.js +2 -3
  62. package/dist/docx/blockPlainText.js +2 -0
  63. package/dist/docx/bookmarkRangeJoin.d.ts +6 -0
  64. package/dist/docx/bookmarkRangeJoin.js +43 -0
  65. package/dist/docx/canonicalSave.js +5 -1
  66. package/dist/docx/canonicalSessionInput.d.ts +5 -1
  67. package/dist/docx/canonicalSessionInput.js +7 -2
  68. package/dist/docx/chartPreview.d.ts +4 -1
  69. package/dist/docx/chartPreview.js +26 -15
  70. package/dist/docx/commentAnchorIndex.d.ts +21 -5
  71. package/dist/docx/commentAnchorIndex.js +39 -11
  72. package/dist/docx/commentRangeIntegrity.js +30 -24
  73. package/dist/docx/commentRangeJoin.d.ts +4 -0
  74. package/dist/docx/commentRangeJoin.js +26 -12
  75. package/dist/docx/commentReferenceCompletion.js +5 -4
  76. package/dist/docx/commentReferenceNormalization.js +40 -18
  77. package/dist/docx/compatibility.js +9 -2
  78. package/dist/docx/containerChildren.js +22 -1
  79. package/dist/docx/encryption/compoundFile.js +9 -1
  80. package/dist/docx/encryption/encryptionInfo.js +16 -2
  81. package/dist/docx/ensureParaIds.js +46 -7
  82. package/dist/docx/ensureUniqueControlIds.d.ts +25 -0
  83. package/dist/docx/ensureUniqueControlIds.js +110 -0
  84. package/dist/docx/headerFooterVerbatim.d.ts +7 -0
  85. package/dist/docx/headerFooterVerbatim.js +13 -2
  86. package/dist/docx/hostCommentThreads.d.ts +17 -0
  87. package/dist/docx/hostCommentThreads.js +49 -0
  88. package/dist/docx/hyperlinkParser.js +9 -2
  89. package/dist/docx/inlineWrapperContent.d.ts +8 -1
  90. package/dist/docx/inlineWrapperContent.js +9 -2
  91. package/dist/docx/listMarkerComputation.d.ts +35 -1
  92. package/dist/docx/listMarkerComputation.js +39 -1
  93. package/dist/docx/listModelNormalization.d.ts +44 -1
  94. package/dist/docx/listModelNormalization.js +227 -96
  95. package/dist/docx/mainDocumentPart.d.ts +6 -0
  96. package/dist/docx/mainDocumentPart.js +65 -0
  97. package/dist/docx/markupRangeMarker.d.ts +14 -0
  98. package/dist/docx/markupRangeMarker.js +15 -1
  99. package/dist/docx/metadataPrivacy.js +43 -22
  100. package/dist/docx/normalizeBaseDirection.js +3 -1
  101. package/dist/docx/packageParts.d.ts +1 -1
  102. package/dist/docx/packageParts.js +10 -4
  103. package/dist/docx/paragraphParser.js +159 -48
  104. package/dist/docx/paragraphPropertySource.d.ts +7 -0
  105. package/dist/docx/paragraphPropertySource.js +22 -1
  106. package/dist/docx/paragraphTextBoxEnrichment.js +2 -1
  107. package/dist/docx/paragraphTraversal.js +2 -0
  108. package/dist/docx/parseWarningMessage.js +2 -1
  109. package/dist/docx/parser.js +6 -0
  110. package/dist/docx/previewBudget.d.ts +6 -0
  111. package/dist/docx/previewBudget.js +7 -1
  112. package/dist/docx/renderedPageBreakNormalization.js +1 -1
  113. package/dist/docx/reviewProvenanceDiagnostics.d.ts +7 -0
  114. package/dist/docx/reviewProvenanceDiagnostics.js +39 -0
  115. package/dist/docx/reviewResolutionProvenance.d.ts +29 -3
  116. package/dist/docx/reviewResolutionProvenance.js +110 -25
  117. package/dist/docx/rezip.d.ts +6 -0
  118. package/dist/docx/rezip.js +42 -25
  119. package/dist/docx/selectiveSave.js +6 -10
  120. package/dist/docx/selectiveXmlPatch.d.ts +5 -4
  121. package/dist/docx/selectiveXmlPatch.js +11 -7
  122. package/dist/docx/serializer/documentSerializer.js +3 -1
  123. package/dist/docx/serializer/headerFooterSerializer.js +3 -1
  124. package/dist/docx/serializer/markupRangeAttributes.d.ts +6 -1
  125. package/dist/docx/serializer/markupRangeAttributes.js +6 -1
  126. package/dist/docx/serializer/noteSerializer.d.ts +17 -4
  127. package/dist/docx/serializer/noteSerializer.js +23 -16
  128. package/dist/docx/serializer/paragraphSerializer.js +56 -12
  129. package/dist/docx/serializer/runSerializer.d.ts +1 -3
  130. package/dist/docx/serializer/runSerializer.js +2 -2
  131. package/dist/docx/serializer/tableSerializer.d.ts +4 -0
  132. package/dist/docx/serializer/tableSerializer.js +4 -2
  133. package/dist/docx/server/applyDocxXmlPatchProposal.js +8 -4
  134. package/dist/docx/server/createBilingualDocument.js +27 -5
  135. package/dist/docx/server/migrateYjsAttrSchema.js +4 -0
  136. package/dist/docx/sessionListPruning.d.ts +2 -0
  137. package/dist/docx/sessionListPruning.js +50 -0
  138. package/dist/docx/shapeAlternateContent.js +19 -0
  139. package/dist/docx/splitRevisionPieces.d.ts +10 -0
  140. package/dist/docx/splitRevisionPieces.js +14 -0
  141. package/dist/docx/storyBlockReplay.js +4 -0
  142. package/dist/docx/structuralXmlPatch.js +19 -7
  143. package/dist/docx/tableParser.d.ts +6 -2
  144. package/dist/docx/tableParser.js +2 -3
  145. package/dist/docx/textBoxContentParser.d.ts +11 -0
  146. package/dist/docx/textBoxContentParser.js +51 -0
  147. package/dist/docx/textBoxParser.d.ts +0 -5
  148. package/dist/docx/textBoxParser.js +1 -23
  149. package/dist/docx/unzip.js +2 -0
  150. package/dist/docx/verticalMergeProjection.js +1 -1
  151. package/dist/fonts/fontsourceFaces.d.ts +2 -8
  152. package/dist/fonts/fontsourceFaces.js +1 -7
  153. package/dist/i18n/messages/ar.gen.js +3 -0
  154. package/dist/i18n/messages/catalogs.gen.d.ts +51 -0
  155. package/dist/i18n/messages/catalogs.gen.js +51 -0
  156. package/dist/i18n/messages/cs.gen.js +3 -0
  157. package/dist/i18n/messages/de.gen.js +3 -0
  158. package/dist/i18n/messages/en.gen.js +3 -0
  159. package/dist/i18n/messages/es.gen.js +3 -0
  160. package/dist/i18n/messages/et.gen.js +3 -0
  161. package/dist/i18n/messages/fr.gen.js +3 -0
  162. package/dist/i18n/messages/he.gen.js +3 -0
  163. package/dist/i18n/messages/hi.gen.js +3 -0
  164. package/dist/i18n/messages/hu.gen.js +3 -0
  165. package/dist/i18n/messages/lt.gen.js +3 -0
  166. package/dist/i18n/messages/lv.gen.js +3 -0
  167. package/dist/i18n/messages/messages.gen.d.ts +3 -0
  168. package/dist/i18n/messages/pl.gen.js +3 -0
  169. package/dist/i18n/messages/pt-BR.gen.js +3 -0
  170. package/dist/i18n/messages/sk.gen.js +3 -0
  171. package/dist/i18n/messages/tr.gen.js +3 -0
  172. package/dist/i18n/messages/zh-CN.gen.js +3 -0
  173. package/dist/internal/acceptedBlockProjection.js +2 -0
  174. package/dist/internal/pageBreakRunSourceDescendantIndex.d.ts +5 -0
  175. package/dist/internal/pageBreakRunSourceDescendantIndex.js +5 -0
  176. package/dist/internal/revisionResolutionInline.js +1 -2
  177. package/dist/internal/wholeStoryRevisionResolution.js +57 -12
  178. package/dist/layout-bridge/convert/altChunkPlaceholder.d.ts +10 -0
  179. package/dist/layout-bridge/convert/altChunkPlaceholder.js +70 -0
  180. package/dist/layout-bridge/convert/fixedTableColumnWidths.js +2 -1
  181. package/dist/layout-bridge/convert/flowConversionShared.d.ts +10 -0
  182. package/dist/layout-bridge/convert/flowConversionShared.js +11 -1
  183. package/dist/layout-bridge/convert/footnoteLayout.d.ts +1 -0
  184. package/dist/layout-bridge/convert/footnoteLayout.js +4 -1
  185. package/dist/layout-bridge/convert/headerFooterLayout.d.ts +1 -0
  186. package/dist/layout-bridge/convert/headerFooterLayout.js +6 -1
  187. package/dist/layout-bridge/convert/tableConversion.js +25 -10
  188. package/dist/layout-bridge/convert/toFlowBlocks.js +4 -0
  189. package/dist/layout-bridge/engine/blockIndex.d.ts +7 -0
  190. package/dist/layout-bridge/engine/blockIndex.js +12 -0
  191. package/dist/layout-bridge/engine/clickToPosition.js +5 -1
  192. package/dist/layout-bridge/engine/hitTest.js +9 -10
  193. package/dist/layout-bridge/engine/selectionRects.js +6 -6
  194. package/dist/layout-engine/footnoteContinuation.d.ts +36 -0
  195. package/dist/layout-engine/footnoteContinuation.js +210 -0
  196. package/dist/layout-engine/index.d.ts +2 -2
  197. package/dist/layout-engine/index.js +7 -2
  198. package/dist/layout-engine/measure/cache.js +10 -5
  199. package/dist/layout-engine/measure/measureParagraph.js +1 -1
  200. package/dist/layout-engine/measure/tableCellFloating.d.ts +2 -0
  201. package/dist/layout-engine/measure/tableCellFloating.js +1 -0
  202. package/dist/layout-engine/measure/tableVisibleBand.d.ts +16 -0
  203. package/dist/layout-engine/measure/tableVisibleBand.js +28 -0
  204. package/dist/layout-engine/tableLayout.js +34 -7
  205. package/dist/layout-engine/tableRowBreak.d.ts +46 -0
  206. package/dist/layout-engine/tableRowBreak.js +193 -36
  207. package/dist/layout-engine/types.d.ts +43 -3
  208. package/dist/layout-painter/previewSvg.d.ts +8 -0
  209. package/dist/layout-painter/previewSvg.js +47 -0
  210. package/dist/layout-painter/renderImage.js +2 -1
  211. package/dist/layout-painter/renderPage.d.ts +5 -4
  212. package/dist/layout-painter/renderPage.js +52 -20
  213. package/dist/layout-painter/renderParagraph.js +3 -2
  214. package/dist/layout-painter/renderTable.d.ts +5 -2
  215. package/dist/layout-painter/renderTable.js +39 -22
  216. package/dist/managers/AutoSaveManager.d.ts +5 -1
  217. package/dist/managers/FindReplaceManager.js +3 -10
  218. package/dist/markdown/escape.d.ts +20 -1
  219. package/dist/markdown/escape.js +43 -1
  220. package/dist/markdown/renderBlock.js +4 -1
  221. package/dist/markdown/renderParagraph.js +13 -27
  222. package/dist/markdown/renderTable.js +6 -2
  223. package/dist/markdown/trailers.js +1 -0
  224. package/dist/pdf/images.d.ts +17 -1
  225. package/dist/pdf/images.js +22 -4
  226. package/dist/pdf/writePdf.js +4 -2
  227. package/dist/prosemirror/anchoredTextBoxes.d.ts +2 -1
  228. package/dist/prosemirror/attrs/index.js +1 -0
  229. package/dist/prosemirror/canonicalCommands.d.ts +39 -1
  230. package/dist/prosemirror/canonicalTableCommands.d.ts +28 -0
  231. package/dist/prosemirror/canonicalTableCommands.js +362 -0
  232. package/dist/prosemirror/commands/comments.d.ts +25 -0
  233. package/dist/prosemirror/commands/comments.js +122 -18
  234. package/dist/prosemirror/commands/deleteBesideInlineAnchor.d.ts +9 -0
  235. package/dist/prosemirror/commands/deleteBesideInlineAnchor.js +36 -0
  236. package/dist/prosemirror/commands/formatting.d.ts +1 -1
  237. package/dist/prosemirror/commands/index.d.ts +1 -1
  238. package/dist/prosemirror/commands/pastePlainText.d.ts +6 -0
  239. package/dist/prosemirror/commands/pastePlainText.js +13 -3
  240. package/dist/prosemirror/commands/resolveAllTableChanges.js +30 -2
  241. package/dist/prosemirror/commentIdAllocator.js +2 -2
  242. package/dist/prosemirror/commentRangeBoundaryAttrs.d.ts +6 -0
  243. package/dist/prosemirror/commentRangeBoundaryAttrs.js +9 -3
  244. package/dist/prosemirror/commentReferenceIntegrity.d.ts +8 -2
  245. package/dist/prosemirror/commentReferenceIntegrity.js +22 -8
  246. package/dist/prosemirror/conversion/fromProseDoc.d.ts +2 -0
  247. package/dist/prosemirror/conversion/fromProseDoc.js +115 -35
  248. package/dist/prosemirror/conversion/index.d.ts +1 -1
  249. package/dist/prosemirror/conversion/toProseDoc.d.ts +128 -1
  250. package/dist/prosemirror/conversion/toProseDoc.js +325 -55
  251. package/dist/prosemirror/extensions/StarterKit.js +2 -0
  252. package/dist/prosemirror/extensions/core/DocExtension.js +1 -1
  253. package/dist/prosemirror/extensions/core/ParagraphExtension.d.ts +3 -1
  254. package/dist/prosemirror/extensions/core/ParagraphExtension.js +8 -9
  255. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.d.ts +1 -1
  256. package/dist/prosemirror/extensions/features/AutoBidiDetectionExtension.js +46 -11
  257. package/dist/prosemirror/extensions/features/BaseKeymapExtension.js +3 -2
  258. package/dist/prosemirror/extensions/features/BidiShortcutExtension.js +2 -3
  259. package/dist/prosemirror/extensions/features/JoinedRunStyleExtension.d.ts +1 -1
  260. package/dist/prosemirror/extensions/features/ListExtension.js +22 -1
  261. package/dist/prosemirror/extensions/features/ParaIdAllocatorExtension.d.ts +1 -1
  262. package/dist/prosemirror/extensions/features/ParagraphChangeTrackerExtension.d.ts +1 -1
  263. package/dist/prosemirror/extensions/features/pastedHtmlLists.js +5 -4
  264. package/dist/prosemirror/extensions/marks/CommentExtension.js +6 -3
  265. package/dist/prosemirror/extensions/marks/HyperlinkExtension.js +5 -0
  266. package/dist/prosemirror/extensions/marks/TextColorExtension.js +1 -1
  267. package/dist/prosemirror/extensions/marks/TrackedChangeExtensions.js +8 -4
  268. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.d.ts +4 -0
  269. package/dist/prosemirror/extensions/nodes/BlockCommentRangeBoundaryExtension.js +49 -0
  270. package/dist/prosemirror/extensions/nodes/BookmarkBoundaryExtension.js +5 -1
  271. package/dist/prosemirror/extensions/nodes/CommentRangeBoundaryExtension.js +2 -1
  272. package/dist/prosemirror/extensions/nodes/CommentReferenceExtension.js +4 -3
  273. package/dist/prosemirror/extensions/nodes/ImageExtension.js +12 -3
  274. package/dist/prosemirror/extensions/nodes/MoveRangeBoundaryExtension.js +2 -1
  275. package/dist/prosemirror/extensions/nodes/NoteMarkerExtension.js +2 -1
  276. package/dist/prosemirror/extensions/nodes/RangeAnchorExtension.js +2 -1
  277. package/dist/prosemirror/extensions/nodes/RenderedPageBreakExtension.js +2 -1
  278. package/dist/prosemirror/extensions/nodes/TableExtension.js +119 -38
  279. package/dist/prosemirror/extensions/nodes/TextBoxExtension.js +1 -1
  280. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.d.ts +11 -0
  281. package/dist/prosemirror/extensions/nodes/inlineAnchorDom.js +21 -0
  282. package/dist/prosemirror/index.d.ts +2 -2
  283. package/dist/prosemirror/listLabels.js +3 -2
  284. package/dist/prosemirror/listNumbering.d.ts +6 -0
  285. package/dist/prosemirror/listNumbering.js +12 -9
  286. package/dist/prosemirror/lockedControls.d.ts +13 -0
  287. package/dist/prosemirror/lockedControls.js +106 -0
  288. package/dist/prosemirror/markupViewProjection.js +1 -1
  289. package/dist/prosemirror/noteReferenceReview.js +2 -2
  290. package/dist/prosemirror/plugins/documentNumbering.js +4 -1
  291. package/dist/prosemirror/plugins/suggestionMode.d.ts +0 -8
  292. package/dist/prosemirror/plugins/suggestionMode.js +195 -30
  293. package/dist/prosemirror/plugins/templatePreviewValues.js +16 -1
  294. package/dist/prosemirror/rebaseParagraphRuns.js +1 -1
  295. package/dist/prosemirror/replacedAnnotations.js +1 -0
  296. package/dist/prosemirror/rowGridOmissions.d.ts +11 -0
  297. package/dist/prosemirror/rowGridOmissions.js +21 -0
  298. package/dist/prosemirror/runFormattingFromMarks.d.ts +0 -1
  299. package/dist/prosemirror/runFormattingFromMarks.js +2 -4
  300. package/dist/prosemirror/runFormattingReconciliation.js +2 -2
  301. package/dist/prosemirror/runPropertyChangeResolution.js +1 -2
  302. package/dist/prosemirror/runStyleFormatting.d.ts +14 -4
  303. package/dist/prosemirror/runStyleFormatting.js +16 -13
  304. package/dist/prosemirror/schema/marks.d.ts +6 -0
  305. package/dist/prosemirror/styles/paragraphStyleCascade.js +2 -2
  306. package/dist/prosemirror/tableGridMutation.d.ts +19 -2
  307. package/dist/prosemirror/tableGridMutation.js +118 -15
  308. package/dist/prosemirror/tablePositionedBookmarks.d.ts +2 -0
  309. package/dist/prosemirror/tablePositionedBookmarks.js +80 -0
  310. package/dist/prosemirror/validation.js +2 -1
  311. package/dist/redline.js +23 -9
  312. package/dist/server.d.ts +2 -2
  313. package/dist/style-sets/extract.js +2 -2
  314. package/dist/types/canonicalCapabilities.d.ts +29 -8
  315. package/dist/types/canonicalCapabilities.js +13 -9
  316. package/dist/utils/cssString.d.ts +7 -0
  317. package/dist/utils/cssString.js +9 -0
  318. package/dist/utils/fontResolver.js +4 -1
  319. package/dist/utils/replaceText.d.ts +11 -0
  320. package/dist/utils/replaceText.js +39 -7
  321. package/dist/version-comparison.d.ts +9 -1
  322. package/dist/version-comparison.js +11 -5
  323. package/package.json +2 -2
@@ -1,16 +1,31 @@
1
1
  import { document_d_exports } from "../types/document.js";
2
- export type CommentMarkerSlot = {
2
+ type CommentMarker = Extract<document_d_exports.ParagraphContent, {
3
+ type: "commentRangeStart";
4
+ } | {
5
+ type: "commentRangeEnd";
6
+ } | {
7
+ type: "commentReference";
8
+ }>;
9
+ /** A marker inside a paragraph, in the inline-content array it sits in. */
10
+ export type InlineCommentMarkerSlot = {
11
+ level: "inline";
3
12
  /** The inline-content array the marker sits in, so a caller can splice it. */
4
13
  content: document_d_exports.ParagraphContent[];
5
14
  index: number;
6
- item: Extract<document_d_exports.ParagraphContent, {
15
+ item: CommentMarker;
16
+ };
17
+ /** A range marker between blocks, in the block array it sits in. */
18
+ export type BlockCommentMarkerSlot = {
19
+ level: "block";
20
+ content: document_d_exports.BlockContent[];
21
+ index: number;
22
+ item: Extract<document_d_exports.BlockContent, {
7
23
  type: "commentRangeStart";
8
24
  } | {
9
25
  type: "commentRangeEnd";
10
- } | {
11
- type: "commentReference";
12
26
  }>;
13
27
  };
28
+ export type CommentMarkerSlot = InlineCommentMarkerSlot | BlockCommentMarkerSlot;
14
29
  export declare const visitCommentMarkers: (blocks: readonly document_d_exports.BlockContent[], visit: (slot: CommentMarkerSlot) => void) => void;
15
30
  /** Remove every serialized anchor record for comments whose definitions are retired. */
16
31
  export declare const removeCommentMarkers: (blocks: readonly document_d_exports.BlockContent[], commentIds: ReadonlySet<number>) => document_d_exports.BlockContent[];
@@ -26,4 +41,5 @@ export declare const removeCommentMarkers: (blocks: readonly document_d_exports.
26
41
  * whole story: a reference that trails the end of a range three paragraphs back
27
42
  * is still not a point comment.
28
43
  */
29
- export declare const rangedCommentIds: (blocks: readonly document_d_exports.BlockContent[]) => ReadonlySet<number>;
44
+ export declare const rangedCommentIds: (blocks: readonly document_d_exports.BlockContent[]) => ReadonlySet<number>;
45
+ export {};
@@ -5,6 +5,7 @@ const visitCommentMarkers = (blocks, visit) => {
5
5
  const visitParagraph = (paragraph) => {
6
6
  visitInlineContentSlots(paragraph, ({ content, index, item }) => {
7
7
  if (item.type === "commentRangeStart" || item.type === "commentRangeEnd" || item.type === "commentReference") visit({
8
+ level: "inline",
8
9
  content,
9
10
  index,
10
11
  item
@@ -12,19 +13,42 @@ const visitCommentMarkers = (blocks, visit) => {
12
13
  });
13
14
  };
14
15
  const visitBlock = (block) => {
15
- if (block.type === "paragraph") {
16
- visitParagraph(block);
17
- return;
18
- }
19
- if (block.type === "table") {
20
- for (const row of block.rows) for (const cell of row.cells) visitBlocks(cell.content);
21
- return;
16
+ switch (block.type) {
17
+ case "paragraph":
18
+ visitParagraph(block);
19
+ return;
20
+ case "table":
21
+ for (const row of block.rows) for (const cell of row.cells) visitBlocks(cell.content);
22
+ return;
23
+ case "blockSdt":
24
+ case "blockCustomXml":
25
+ visitBlocks(block.content);
26
+ return;
27
+ case "commentRangeStart":
28
+ case "commentRangeEnd": return;
29
+ case "preservedBlock":
30
+ case "bookmarkStart":
31
+ case "bookmarkEnd":
32
+ case "moveFromRangeStart":
33
+ case "moveFromRangeEnd":
34
+ case "moveToRangeStart":
35
+ case "moveToRangeEnd": return;
36
+ default: return block;
22
37
  }
23
- if (block.type !== "blockSdt" && block.type !== "blockCustomXml") return;
24
- visitBlocks(block.content);
25
38
  };
26
39
  const visitBlocks = (nested) => {
27
- for (const block of nested) visitBlock(block);
40
+ for (const [index, block] of nested.entries()) {
41
+ if (block.type === "commentRangeStart" || block.type === "commentRangeEnd") {
42
+ visit({
43
+ level: "block",
44
+ content: nested,
45
+ index,
46
+ item: block
47
+ });
48
+ continue;
49
+ }
50
+ visitBlock(block);
51
+ }
28
52
  };
29
53
  visitBlocks(blocks);
30
54
  };
@@ -209,6 +233,7 @@ const removeCommentMarkers = (blocks, commentIds) => {
209
233
  case "moveFromRangeEnd":
210
234
  case "moveToRangeStart":
211
235
  case "moveToRangeEnd":
236
+ case "complexField":
212
237
  case "preservedInline": return item;
213
238
  }
214
239
  };
@@ -253,6 +278,8 @@ const removeCommentMarkers = (blocks, commentIds) => {
253
278
  case "preservedBlock":
254
279
  case "bookmarkStart":
255
280
  case "bookmarkEnd":
281
+ case "commentRangeStart":
282
+ case "commentRangeEnd":
256
283
  case "moveFromRangeStart":
257
284
  case "moveFromRangeEnd":
258
285
  case "moveToRangeStart":
@@ -260,7 +287,8 @@ const removeCommentMarkers = (blocks, commentIds) => {
260
287
  }
261
288
  };
262
289
  const rebuildBlocks = (content) => rebuildArray(content, rebuildBlock);
263
- return rebuildBlocks(blocks.slice());
290
+ const rebuilt = rebuildBlocks(blocks);
291
+ return rebuilt === blocks ? blocks.slice() : rebuilt;
264
292
  };
265
293
  /**
266
294
  * Comments that open a range anywhere in these blocks.
@@ -161,20 +161,38 @@ const withoutOrphanBlockMarkers = (blocks, validCommentIds) => {
161
161
  for (const block of blocks) {
162
162
  const nextBlock = withoutOrphanBlockMarker(block, validCommentIds);
163
163
  if (nextBlock !== block) changed = true;
164
- next.push(nextBlock);
164
+ if (nextBlock !== null) next.push(nextBlock);
165
165
  }
166
166
  return changed ? next : null;
167
167
  };
168
+ /**
169
+ * A block with its orphaned comment markers gone, or `null` when the block is
170
+ * itself one: a comment range marker between blocks for a comment the save no
171
+ * longer holds.
172
+ */
168
173
  const withoutOrphanBlockMarker = (block, validCommentIds) => {
169
- if (block.type === "paragraph") return withoutOrphanParagraphMarkers(block, validCommentIds);
170
- if (block.type === "table") return withoutOrphanTableMarkers(block, validCommentIds);
171
- if (block.type !== "blockSdt" && block.type !== "blockCustomXml") return block;
172
- const content = withoutOrphanBlockMarkers(block.content, validCommentIds);
173
- if (!content) return block;
174
- return {
175
- ...block,
176
- content
177
- };
174
+ switch (block.type) {
175
+ case "paragraph": return withoutOrphanParagraphMarkers(block, validCommentIds);
176
+ case "table": return withoutOrphanTableMarkers(block, validCommentIds);
177
+ case "blockSdt":
178
+ case "blockCustomXml": {
179
+ const content = withoutOrphanBlockMarkers(block.content, validCommentIds);
180
+ return content ? {
181
+ ...block,
182
+ content
183
+ } : block;
184
+ }
185
+ case "commentRangeStart":
186
+ case "commentRangeEnd": return validCommentIds.has(block.id) ? block : null;
187
+ case "preservedBlock":
188
+ case "bookmarkStart":
189
+ case "bookmarkEnd":
190
+ case "moveFromRangeStart":
191
+ case "moveFromRangeEnd":
192
+ case "moveToRangeStart":
193
+ case "moveToRangeEnd": return block;
194
+ default: return block;
195
+ }
178
196
  };
179
197
  const withoutOrphanTableMarkers = (table, validCommentIds) => {
180
198
  let changed = false;
@@ -216,24 +234,12 @@ const withoutOrphanTableCellBlockMarkers = (blocks, validCommentIds) => {
216
234
  let changed = false;
217
235
  const next = [];
218
236
  for (const block of blocks) {
219
- const nextBlock = withoutOrphanTableCellBlockMarker(block, validCommentIds);
237
+ const nextBlock = withoutOrphanBlockMarker(block, validCommentIds);
220
238
  if (nextBlock !== block) changed = true;
221
- next.push(nextBlock);
239
+ if (nextBlock !== null) next.push(nextBlock);
222
240
  }
223
241
  return changed ? next : null;
224
242
  };
225
- const withoutOrphanTableCellBlockMarker = (block, validCommentIds) => {
226
- if (block.type === "paragraph") return withoutOrphanParagraphMarkers(block, validCommentIds);
227
- if (block.type === "table") return withoutOrphanTableMarkers(block, validCommentIds);
228
- if (block.type === "blockSdt" || block.type === "blockCustomXml") {
229
- const content = withoutOrphanTableCellBlockMarkers(block.content, validCommentIds);
230
- return content ? {
231
- ...block,
232
- content
233
- } : block;
234
- }
235
- return block;
236
- };
237
243
  const withoutOrphanParagraphMarkers = (paragraph, validCommentIds) => {
238
244
  let changed = false;
239
245
  const content = [];
@@ -2,5 +2,9 @@ import { document_d_exports } from "../types/document.js";
2
2
  /**
3
3
  * Collapse each comment's range markers to its first start and its last end.
4
4
  * Answers how many markers were dropped.
5
+ *
6
+ * A start or an end between blocks counts as one of the range's markers, so a
7
+ * range that opens beside a content control keeps that start and loses the
8
+ * one its mark wrote at the front of the first paragraph.
5
9
  */
6
10
  export declare const joinCommentRangesAcrossParagraphs: (blocks: readonly document_d_exports.BlockContent[]) => number;
@@ -4,29 +4,43 @@ import { InlineContentRemovals } from "./inlineContentRemovals.js";
4
4
  /**
5
5
  * Collapse each comment's range markers to its first start and its last end.
6
6
  * Answers how many markers were dropped.
7
+ *
8
+ * A start or an end between blocks counts as one of the range's markers, so a
9
+ * range that opens beside a content control keeps that start and loses the
10
+ * one its mark wrote at the front of the first paragraph.
7
11
  */
8
12
  const joinCommentRangesAcrossParagraphs = (blocks) => {
9
13
  const startsById = /* @__PURE__ */ new Map();
10
14
  const endsById = /* @__PURE__ */ new Map();
11
- visitCommentMarkers(blocks, ({ content, index, item }) => {
15
+ visitCommentMarkers(blocks, (slot) => {
16
+ const { item } = slot;
12
17
  if (item.type === "commentReference") return;
13
18
  const slotsById = item.type === "commentRangeStart" ? startsById : endsById;
14
19
  const slots = slotsById.get(item.id);
15
20
  if (slots) {
16
- slots.push({
17
- content,
18
- index
19
- });
21
+ slots.push(slot);
20
22
  return;
21
23
  }
22
- slotsById.set(item.id, [{
23
- content,
24
- index
25
- }]);
24
+ slotsById.set(item.id, [slot]);
26
25
  });
27
26
  const removals = new InlineContentRemovals();
28
- for (const slots of startsById.values()) for (const slot of slots.slice(1)) removals.mark(slot);
29
- for (const slots of endsById.values()) for (const slot of slots.slice(0, -1)) removals.mark(slot);
30
- return removals.apply();
27
+ const blockRemovals = /* @__PURE__ */ new Map();
28
+ const remove = (slot) => {
29
+ if (slot.level === "inline") {
30
+ removals.mark(slot);
31
+ return;
32
+ }
33
+ const indexes = blockRemovals.get(slot.content) ?? [];
34
+ indexes.push(slot.index);
35
+ blockRemovals.set(slot.content, indexes);
36
+ };
37
+ for (const slots of startsById.values()) for (const slot of slots.slice(1)) remove(slot);
38
+ for (const slots of endsById.values()) for (const slot of slots.slice(0, -1)) remove(slot);
39
+ let dropped = removals.apply();
40
+ for (const [content, indexes] of blockRemovals) for (const index of indexes.toSorted((first, second) => second - first)) {
41
+ content.splice(index, 1);
42
+ dropped += 1;
43
+ }
44
+ return dropped;
31
45
  };
32
46
  export { joinCommentRangesAcrossParagraphs };
@@ -7,14 +7,15 @@ import { visitCommentMarkers } from "./commentAnchorIndex.js";
7
7
  const completeCommentReferences = (blocks) => {
8
8
  const lastRangeEnds = /* @__PURE__ */ new Map();
9
9
  const referencedIds = /* @__PURE__ */ new Set();
10
- visitCommentMarkers(blocks, ({ content, index, item }) => {
10
+ visitCommentMarkers(blocks, (slot) => {
11
+ const { item } = slot;
11
12
  if (item.type === "commentReference") {
12
13
  referencedIds.add(item.id);
13
14
  return;
14
15
  }
15
- if (item.type === "commentRangeEnd") lastRangeEnds.set(item.id, {
16
- content,
17
- index
16
+ if (item.type === "commentRangeEnd" && slot.level === "inline") lastRangeEnds.set(item.id, {
17
+ content: slot.content,
18
+ index: slot.index
18
19
  });
19
20
  });
20
21
  const insertionsByContent = /* @__PURE__ */ new Map();
@@ -21,8 +21,10 @@ const normalizeCommentReferences = ({ documentBody, comments, headers, footers,
21
21
  return;
22
22
  }
23
23
  if (isCommentRangeMarker(item)) rangeMarkers.push({
24
- content,
25
- index,
24
+ slot: {
25
+ content,
26
+ index
27
+ },
26
28
  id: item.id,
27
29
  type: item.type
28
30
  });
@@ -32,19 +34,40 @@ const normalizeCommentReferences = ({ documentBody, comments, headers, footers,
32
34
  for (const row of table.rows) for (const cell of row.cells) normalizeBlocks(cell.content);
33
35
  };
34
36
  const normalizeBlock = (block) => {
35
- if (block.type === "paragraph") {
36
- normalizeParagraph(block);
37
- return;
38
- }
39
- if (block.type === "table") {
40
- normalizeTable(block);
41
- return;
37
+ switch (block.type) {
38
+ case "commentRangeStart":
39
+ case "commentRangeEnd":
40
+ if (validCommentIds.has(block.id)) rangeMarkers.push({
41
+ id: block.id,
42
+ type: block.type
43
+ });
44
+ return;
45
+ case "paragraph":
46
+ normalizeParagraph(block);
47
+ return;
48
+ case "table":
49
+ normalizeTable(block);
50
+ return;
51
+ case "blockSdt":
52
+ case "blockCustomXml":
53
+ normalizeBlocks(block.content);
54
+ return;
55
+ case "preservedBlock":
56
+ case "bookmarkStart":
57
+ case "bookmarkEnd":
58
+ case "moveFromRangeStart":
59
+ case "moveFromRangeEnd":
60
+ case "moveToRangeStart":
61
+ case "moveToRangeEnd": return;
62
+ default: return block;
42
63
  }
43
- if (block.type !== "blockSdt" && block.type !== "blockCustomXml") return;
44
- normalizeBlocks(block.content);
45
64
  };
46
65
  const normalizeBlocks = (blocks) => {
47
66
  for (const block of blocks) normalizeBlock(block);
67
+ for (const [index, block] of blocks.entries()) if ((block.type === "commentRangeStart" || block.type === "commentRangeEnd") && !validCommentIds.has(block.id)) blocks[index] = {
68
+ type: "preservedBlock",
69
+ xml: `<w:${block.type} w:id="${String(block.id)}"${block.displacedByCustomXml === void 0 ? "" : ` w:displacedByCustomXml="${block.displacedByCustomXml}"`}/>`
70
+ };
48
71
  };
49
72
  normalizeBlocks(documentBody.content);
50
73
  for (const header of headers?.values() ?? []) normalizeBlocks(header.content);
@@ -75,32 +98,31 @@ const reanchorUnbalancedCommentRanges = (rangeMarkers) => {
75
98
  for (const marker of markers) {
76
99
  if (marker.type === "commentRangeStart") {
77
100
  if (openStart) {
78
- reanchorCommentRangeMarker(marker);
79
- reanchoredCount += 1;
101
+ if (reanchorCommentRangeMarker(marker)) reanchoredCount += 1;
80
102
  continue;
81
103
  }
82
104
  openStart = marker;
83
105
  continue;
84
106
  }
85
107
  if (!openStart) {
86
- reanchorCommentRangeMarker(marker);
87
- reanchoredCount += 1;
108
+ if (reanchorCommentRangeMarker(marker)) reanchoredCount += 1;
88
109
  continue;
89
110
  }
90
111
  openStart = null;
91
112
  }
92
113
  if (openStart) {
93
- reanchorCommentRangeMarker(openStart);
94
- reanchoredCount += 1;
114
+ if (reanchorCommentRangeMarker(openStart)) reanchoredCount += 1;
95
115
  }
96
116
  }
97
117
  return reanchoredCount;
98
118
  };
99
119
  const reanchorCommentRangeMarker = (marker) => {
100
- marker.content[marker.index] = {
120
+ if (!marker.slot) return false;
121
+ marker.slot.content[marker.slot.index] = {
101
122
  type: "commentReference",
102
123
  id: marker.id
103
124
  };
125
+ return true;
104
126
  };
105
127
  const isCommentMarker = (content) => content.type === "commentRangeStart" || content.type === "commentRangeEnd" || content.type === "commentReference";
106
128
  const isCommentRangeMarker = (content) => content.type === "commentRangeStart" || content.type === "commentRangeEnd";
@@ -190,9 +190,16 @@ function inspectHyperlink(hyperlink, context) {
190
190
  });
191
191
  continue;
192
192
  }
193
- if (child.type === "inlineWrapper") inspectParagraphContent(child.content, {
193
+ if (child.type === "inlineWrapper") {
194
+ inspectParagraphContent(child.content, {
195
+ ...context,
196
+ path: `${path}.content`
197
+ });
198
+ continue;
199
+ }
200
+ if (child.type === "complexField") inspectParagraphContent([child], {
194
201
  ...context,
195
- path: `${path}.content`
202
+ path
196
203
  });
197
204
  }
198
205
  }
@@ -1,6 +1,7 @@
1
1
  import { TRANSITIONAL_NAMESPACE_BY_STRICT_URI } from "./strictValueEncodings.gen.js";
2
2
  import { captureVerbatimXml } from "./verbatimCapture.js";
3
3
  import { WORDPROCESSINGML_NAMESPACE_URIS, getChildElements, getLocalName, getNamespaceUri } from "./xmlParser.js";
4
+ import { OOXML_NS } from "@stll/docx-utils";
4
5
  import { SEQUENCE_CHILDREN } from "@stll/docx-core/schema";
5
6
  // src/docx/containerChildren.ts
6
7
  /** Keep this child's markup verbatim, in place. */
@@ -167,13 +168,33 @@ const sequenceOrdinals = (container) => {
167
168
  SEQUENCE_ORDINALS.set(container, ordinals);
168
169
  return ordinals;
169
170
  };
171
+ /**
172
+ * Where a container's schema puts the children of its extension namespaces.
173
+ *
174
+ * The neighbour rule cannot hold for these: an edit that adds a declared
175
+ * property after the source's last one would land it behind the extension
176
+ * child, out of the order the extended schema requires. `CT_RPr` appends the
177
+ * `w14` run effects (`w14:ligatures`, `w14:textFill` and the rest) after
178
+ * every base property and before `w:rPrChange`, so they take the place of the
179
+ * declared child before that record.
180
+ */
181
+ const EXTENSION_PLACEMENT = { "run-properties": {
182
+ namespaces: /* @__PURE__ */ new Set([OOXML_NS.w14]),
183
+ after: "oMath"
184
+ } };
170
185
  const computeSequencePositions = (container, element) => {
171
186
  const ordinals = sequenceOrdinals(container);
187
+ const extension = EXTENSION_PLACEMENT[container];
188
+ const extensionAt = extension === void 0 ? -1 : ordinals.get(extension.after) ?? -1;
172
189
  const positions = /* @__PURE__ */ new Map();
173
190
  let previous = -1;
174
191
  for (const child of getChildElements(element)) {
175
192
  const namespace = getNamespaceUri(child);
176
- const at = namespace === void 0 || WORDPROCESSINGML_NAMESPACE_URIS.has(namespace) ? ordinals.get(getLocalName(child.name)) ?? -1 : -1;
193
+ const isDeclaredNamespace = namespace === void 0 || WORDPROCESSINGML_NAMESPACE_URIS.has(namespace);
194
+ const isExtension = namespace !== void 0 && extension?.namespaces.has(namespace) === true && extensionAt !== -1;
195
+ let at = -1;
196
+ if (isDeclaredNamespace) at = ordinals.get(getLocalName(child.name)) ?? -1;
197
+ else if (isExtension) at = extensionAt;
177
198
  if (at !== -1) previous = at;
178
199
  positions.set(child, at === -1 ? previous : at);
179
200
  }
@@ -83,6 +83,8 @@ const loadSector = (file, header, sectorId) => {
83
83
  return file.subarray(offset, offset + header.sectorBytes);
84
84
  };
85
85
  const loadFatSectorIds = (file, header) => {
86
+ const physicalSectors = Math.floor(file.length / header.sectorBytes) - 1;
87
+ if (header.fatSectorCount > physicalSectors) throw new Error(`Declared FAT sector count ${header.fatSectorCount} exceeds the ${physicalSectors} sectors in the file`);
86
88
  const ids = [...header.headerDifat];
87
89
  const maxDifatSectors = Math.ceil(file.length / header.sectorBytes);
88
90
  const stepLimit = Math.min(header.difatSectorCount, maxDifatSectors);
@@ -102,7 +104,13 @@ const loadFatSectorIds = (file, header) => {
102
104
  chain = u32(view, header.sectorBytes - 4);
103
105
  }
104
106
  if (ids.length < header.fatSectorCount) throw new Error("DIFAT chain shorter than declared FAT sector count");
105
- return ids.slice(0, header.fatSectorCount);
107
+ const fatSectorIds = ids.slice(0, header.fatSectorCount);
108
+ const listed = /* @__PURE__ */ new Set();
109
+ for (const id of fatSectorIds) {
110
+ if (listed.has(id)) throw new Error(`FAT sector ${id} listed more than once`);
111
+ listed.add(id);
112
+ }
113
+ return fatSectorIds;
106
114
  };
107
115
  const loadFat = (file, header) => {
108
116
  const table = [];
@@ -85,6 +85,20 @@ const requireSpinCount = (attrs, element) => {
85
85
  });
86
86
  return spinCount;
87
87
  };
88
+ /**
89
+ * Agile decryption here is AES-CBC only, whose block is always 16 bytes.
90
+ * The block size also sizes the padded verifier and segment IVs, so any
91
+ * other declared value is refused while parsing.
92
+ */
93
+ const AES_BLOCK_BYTES = 16;
94
+ const requireAesBlockSize = (attrs, element) => {
95
+ const blockSize = requireInt(attrs, "blockSize", element);
96
+ if (blockSize !== AES_BLOCK_BYTES) throw new DocxEncryptionError({
97
+ code: DOCX_ENCRYPTION_ERROR_CODES.DECRYPTION_FAILED,
98
+ message: `EncryptionInfo <${element}> attribute "blockSize" must be ${AES_BLOCK_BYTES}: ${blockSize}`
99
+ });
100
+ return blockSize;
101
+ };
88
102
  const parseAgileXml = (xmlBytes) => {
89
103
  const xml = decodeText(xmlBytes, { encoding: "utf-8" });
90
104
  const keyDataTag = findElement(xml, "keyData");
@@ -102,14 +116,14 @@ const parseAgileXml = (xmlBytes) => {
102
116
  packageKeyBits: requireInt(keyData, "keyBits", "keyData"),
103
117
  packageHash: requireAttr(keyData, "hashAlgorithm", "keyData"),
104
118
  packageHashBytes: requireInt(keyData, "hashSize", "keyData"),
105
- cipherBlockBytes: requireInt(keyData, "blockSize", "keyData"),
119
+ cipherBlockBytes: requireAesBlockSize(keyData, "keyData"),
106
120
  cipherName: requireAttr(keyData, "cipherAlgorithm", "keyData"),
107
121
  cipherMode: requireAttr(keyData, "cipherChaining", "keyData"),
108
122
  passwordIterations: requireSpinCount(encryptedKey, "encryptedKey"),
109
123
  passwordSalt: requireBase64(encryptedKey, "saltValue", "encryptedKey"),
110
124
  passwordHash: requireAttr(encryptedKey, "hashAlgorithm", "encryptedKey"),
111
125
  passwordKeyBits: requireInt(encryptedKey, "keyBits", "encryptedKey"),
112
- passwordBlockBytes: requireInt(encryptedKey, "blockSize", "encryptedKey"),
126
+ passwordBlockBytes: requireAesBlockSize(encryptedKey, "encryptedKey"),
113
127
  encryptedVerifierInput: requireBase64(encryptedKey, "encryptedVerifierHashInput", "encryptedKey"),
114
128
  encryptedVerifierDigest: requireBase64(encryptedKey, "encryptedVerifierHashValue", "encryptedKey"),
115
129
  encryptedIntermediateKey: requireBase64(encryptedKey, "encryptedKeyValue", "encryptedKey"),
@@ -1,4 +1,4 @@
1
- import { deterministicHexId } from "../utils/hexId.js";
1
+ import { deterministicHexId, isValidHexId } from "../utils/hexId.js";
2
2
  import { resolvePackageRelationshipTarget } from "./packageParts.js";
3
3
  import { spliceXml } from "./selectiveXmlPatch.js";
4
4
  import { loadDocxArchive } from "./server/boundedArchive.js";
@@ -29,7 +29,9 @@ import { ZipArchive } from "@stll/docx-core/zip";
29
29
  * so documents carrying features folio's parser does not model come back
30
30
  * with those features byte-identical. Contract:
31
31
  *
32
- * - Parts covered: the officeDocument relationship target, `word/header*.xml`, `word/footer*.xml`,
32
+ * - Parts covered: the officeDocument relationship target, the header,
33
+ * footer, footnotes, and endnotes parts its relationships name (wherever
34
+ * they live), and `word/header*.xml`, `word/footer*.xml`,
33
35
  * `word/footnotes.xml`, `word/endnotes.xml`. Paragraphs nested in table
34
36
  * cells and in `mc:Choice` text boxes are plain `<w:p>` elements inside
35
37
  * those parts and are covered by the same scan. The comments part mints its
@@ -38,8 +40,9 @@ import { ZipArchive } from "@stll/docx-core/zip";
38
40
  * - Paragraphs inside `mc:Fallback` are never modified: Word regenerates the
39
41
  * fallback branch (duplicating the `mc:Choice` ids) on save, so stamping or
40
42
  * deduplicating there would churn on every Word round-trip.
41
- * - Existing ids are preserved. Only three cases get a fresh id: a missing
43
+ * - Existing ids are preserved. Only these cases get a fresh id: a missing
42
44
  * `paraId`, the reserved all-zero value (Word reads `00000000` as "no id"),
45
+ * a value that is not eight hex digits (the parser drops it as no id),
43
46
  * and a duplicate of an id already seen earlier in the scan (first
44
47
  * occurrence keeps it — the same rule `ParaIdAllocatorExtension` applies in
45
48
  * the editor). `w14:textId` is written alongside a newly minted `paraId`
@@ -78,6 +81,13 @@ const DIGITAL_SIGNATURE_PART_PREFIX = "_xmlsignatures/";
78
81
  /** Word reads an all-zero `w14:paraId` as "no id assigned". */
79
82
  const RESERVED_ZERO_ID_PATTERN = /^0*$/u;
80
83
  const PACKAGE_RELATIONSHIP_URI = "http://schemas.openxmlformats.org/package/2006/relationships";
84
+ /** Relationship types, under each office namespace, whose targets are editable stories. */
85
+ const STORY_RELATIONSHIP_TYPES = [
86
+ "header",
87
+ "footer",
88
+ "footnotes",
89
+ "endnotes"
90
+ ];
81
91
  const TARGET_PART_PATTERNS = [
82
92
  /^word\/header\d*\.xml$/u,
83
93
  /^word\/footer\d*\.xml$/u,
@@ -241,7 +251,7 @@ const scanPart = ({ partPath, spelling, context, seen }) => {
241
251
  continue;
242
252
  }
243
253
  const value = paraId.value.toUpperCase();
244
- const unassigned = RESERVED_ZERO_ID_PATTERN.test(value);
254
+ const unassigned = !isValidHexId(value) || RESERVED_ZERO_ID_PATTERN.test(value);
245
255
  if (!unassigned && !seen.has(value)) {
246
256
  seen.add(value);
247
257
  continue;
@@ -316,8 +326,33 @@ const mainDocumentPart = (rels, entries) => {
316
326
  if (name === void 0) throw createEnsureParaIdsError("officeDocument part not found");
317
327
  return name;
318
328
  };
329
+ /** The `.rels` part that holds `partName`'s relationships. */
330
+ const relationshipsPathFor = (partName) => {
331
+ const slash = partName.lastIndexOf("/");
332
+ return `${partName.slice(0, slash + 1)}_rels/${partName.slice(slash + 1)}.rels`;
333
+ };
334
+ /**
335
+ * The header, footer, and note parts the main part's relationships name.
336
+ * The parser follows these relationships, so a story at a custom path
337
+ * (`word/custom/defaultHeader.xml`) is as editable as `word/header1.xml`.
338
+ */
339
+ const relatedStoryParts = (rels, relsPath, entries) => {
340
+ const parts = /* @__PURE__ */ new Set();
341
+ const root = rels === null ? null : parseXmlDocument(rels);
342
+ if (root === null || getLocalName(root.name ?? "") !== "Relationships" || getNamespaceUri(root) !== PACKAGE_RELATIONSHIP_URI) return parts;
343
+ const storyTypes = /* @__PURE__ */ new Set();
344
+ for (const uri of OFFICE_RELATIONSHIP_NAMESPACE_URIS) for (const type of STORY_RELATIONSHIP_TYPES) storyTypes.add(`${uri}/${type}`);
345
+ for (const element of getChildElements(root)) {
346
+ if (getLocalName(element.name ?? "") !== "Relationship" || getNamespaceUri(element) !== PACKAGE_RELATIONSHIP_URI || !storyTypes.has(getAttribute(element, null, "Type") ?? "") || getAttribute(element, null, "TargetMode") === "External") continue;
347
+ const target = getAttribute(element, null, "Target");
348
+ const partPath = target === null ? void 0 : resolvePackageRelationshipTarget(target, relsPath);
349
+ const name = partPath === void 0 ? void 0 : entries.find((entry) => entry.toLowerCase() === partPath);
350
+ if (name !== void 0) parts.add(name);
351
+ }
352
+ return parts;
353
+ };
319
354
  /** OPC part names are case-insensitive; compare lowercased. */
320
- const isTargetPart = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
355
+ const matchesTargetPattern = (path) => TARGET_PART_PATTERNS.some((pattern) => pattern.test(path.toLowerCase()));
321
356
  const toUint8Array = (docx) => docx instanceof Uint8Array ? docx : new Uint8Array(docx);
322
357
  const hasDigitalSignatureParts = (zip) => zip.entries().some(({ path }) => path.toLowerCase().startsWith(DIGITAL_SIGNATURE_PART_PREFIX));
323
358
  /**
@@ -331,7 +366,11 @@ const ensureParaIdsInternal = async (docx, options) => {
331
366
  const rels = relsPath === void 0 ? null : await archive.readEntryString(relsPath);
332
367
  if (rels === null) throw createEnsureParaIdsError("Package relationships not found");
333
368
  const documentPartName = mainDocumentPart(rels, archive.entries);
334
- const xmlPartNames = archive.entries.filter((name) => name.toLowerCase().endsWith(".xml") || name === documentPartName);
369
+ const documentRelsPath = relationshipsPathFor(documentPartName);
370
+ const documentRelsName = archive.entries.find((name) => name.toLowerCase() === documentRelsPath.toLowerCase());
371
+ const storyParts = relatedStoryParts(documentRelsName === void 0 ? null : await archive.readEntryString(documentRelsName), documentRelsPath, archive.entries);
372
+ const isTargetPart = (name) => name !== documentPartName && (storyParts.has(name) || matchesTargetPattern(name));
373
+ const xmlPartNames = archive.entries.filter((name) => name.toLowerCase().endsWith(".xml") || name === documentPartName || storyParts.has(name));
335
374
  const partTexts = /* @__PURE__ */ new Map();
336
375
  for (const name of xmlPartNames) {
337
376
  const text = await archive.readEntryString(name);
@@ -345,7 +384,7 @@ const ensureParaIdsInternal = async (docx, options) => {
345
384
  taken,
346
385
  docKey: deterministicHexId(documentXml)
347
386
  };
348
- const targetParts = [documentPartName, ...xmlPartNames.filter((name) => name !== documentPartName && isTargetPart(name)).sort((a, b) => a.localeCompare(b))];
387
+ const targetParts = [documentPartName, ...xmlPartNames.filter((name) => isTargetPart(name)).sort((a, b) => a.localeCompare(b))];
349
388
  const spellings = /* @__PURE__ */ new Map();
350
389
  const seen = /* @__PURE__ */ new Set();
351
390
  for (const [partPath, xml] of partTexts) if (partPath === documentPartName || isTargetPart(partPath)) {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Headless `w:sdtPr/w:id` normalization for a `.docx` buffer.
3
+ *
4
+ * A content control names itself by `w:id`, and the package model holds
5
+ * every control by that id. A package can repeat one: a producer that copied
6
+ * a control, or merged two documents, wrote the same id twice. The first
7
+ * control in document order keeps its id; each later control carrying it gets
8
+ * an id the package does not use. Every control is kept, and so is everything
9
+ * else in the part.
10
+ *
11
+ * Alternate content (`mc:Fallback`) restates the controls of its `mc:Choice`
12
+ * under the same ids for older readers, and the parser reads one of the two,
13
+ * so a fallback's ids are reserved but never counted as a repeat.
14
+ */
15
+ export type EnsureUniqueControlIdsResult = {
16
+ /** The normalized `.docx`; the input bytes when nothing repeated. */
17
+ docx: Uint8Array;
18
+ /** Controls given a new id. */
19
+ reminted: number;
20
+ };
21
+ /**
22
+ * Give each content control after the first carrying an id an id of its own.
23
+ * A signed package, or a part that does not scan, is left as it is.
24
+ */
25
+ export declare const ensureUniqueControlIds: (docx: Uint8Array) => Promise<EnsureUniqueControlIdsResult>;