platejs 54.0.0-beta.2 → 54.0.0-beta.20

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 (840) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +36 -8
  3. package/dist/EditorStatic-BTyhgdYL.d.ts +792 -0
  4. package/dist/ai/index.d.ts +2 -2
  5. package/dist/ai/index.js +4 -2
  6. package/dist/ai/lib/aiDraftSession.js +1081 -0
  7. package/dist/ai/{react → lib}/aiOutputLanding.internal.js +90 -96
  8. package/dist/ai/lib/aiPolicy.internal.js +471 -0
  9. package/dist/ai/lib/editorAgent.js +3441 -0
  10. package/dist/ai/lib/editorAgentDispatcher.internal.js +205 -0
  11. package/dist/ai/lib/editorAgentPresence.internal.js +114 -0
  12. package/dist/ai/lib/editorAgentSync.internal.js +306 -0
  13. package/dist/ai/lib/inkRuntime.internal.js +8 -0
  14. package/dist/ai/lib/lockedContext.internal.js +144 -0
  15. package/dist/ai/lib/lockedContext.js +272 -0
  16. package/dist/ai/lib/registerEditorTools.js +311 -0
  17. package/dist/ai/lib/webmcpConfinement.internal.js +8 -0
  18. package/dist/ai/react/AIPlugin.js +246 -0
  19. package/dist/ai/react/CopilotPlugin.js +359 -191
  20. package/dist/ai/react/copilotInline.internal.js +359 -0
  21. package/dist/ai/react/index.d.ts +327 -1007
  22. package/dist/ai/react/index.js +3 -3
  23. package/dist/ai/react/useEditorAgent.js +514 -0
  24. package/dist/authored/AuthoredPlugin.js +35 -3
  25. package/dist/authored/index.d.ts +5 -4
  26. package/dist/authored/index.js +3 -2
  27. package/dist/authored/suggestionColorOf.js +20 -0
  28. package/dist/{index-hsC_sOn2.d.ts → authored-CYoZAxr--Ba0JwRbO.d.ts} +198 -87
  29. package/dist/clipboard-format-key-CMZ3jPZO-DEODtsVZ.d.ts +1 -0
  30. package/dist/code-block/codemirror/createCodeMirrorAdapter.js +236 -67
  31. package/dist/code-block/codemirror/index.d.ts +2 -1
  32. package/dist/comment-anchor.internal-DQfEtr1Z.d.ts +28 -0
  33. package/dist/compiler/index.d.ts +9 -3
  34. package/dist/compiler/index.js +3 -1
  35. package/dist/{core-BJG8l_mk.d.ts → core-ClO5Umhx.d.ts} +5480 -7255
  36. package/dist/core.js +3 -12
  37. package/dist/diff/index.d.ts +3 -30
  38. package/dist/docs/agents/mcp.md +131 -0
  39. package/dist/docs/agents/skills.md +71 -0
  40. package/dist/docs/agents.md +79 -0
  41. package/dist/docs/ai-agents.md +80 -0
  42. package/dist/docs/ai.md +622 -387
  43. package/dist/docs/annotations.md +41 -122
  44. package/dist/docs/api/anchor.md +17 -2
  45. package/dist/docs/api/core/plate-components.md +78 -196
  46. package/dist/docs/api/core/plate-controller.md +6 -4
  47. package/dist/docs/api/core/plate-editor.md +35 -132
  48. package/dist/docs/api/core/plate-plugin.md +429 -560
  49. package/dist/docs/api/core/plate-store.md +21 -20
  50. package/dist/docs/api/core.md +261 -441
  51. package/dist/docs/api/document-change.md +60 -28
  52. package/dist/docs/api/dom.md +82 -107
  53. package/dist/docs/api/editor-api.md +86 -51
  54. package/dist/docs/api/editor-transforms.md +52 -51
  55. package/dist/docs/api/element.md +3 -3
  56. package/dist/docs/api/location.md +7 -14
  57. package/dist/docs/api/node.md +6 -7
  58. package/dist/docs/api/path.md +3 -3
  59. package/dist/docs/api/plate.md +21 -13
  60. package/dist/docs/api/point.md +4 -3
  61. package/dist/docs/api/range.md +21 -2
  62. package/dist/docs/api/react-hooks.md +288 -188
  63. package/dist/docs/api/resizable.md +20 -42
  64. package/dist/docs/api/selection.md +12 -4
  65. package/dist/docs/api/text.md +3 -3
  66. package/dist/docs/api/utils.md +23 -25
  67. package/dist/docs/authored-changes.md +66 -51
  68. package/dist/docs/autoformat.md +24 -13
  69. package/dist/docs/basic-blocks.md +55 -59
  70. package/dist/docs/basic-marks.md +11 -48
  71. package/dist/docs/block-menu.md +26 -19
  72. package/dist/docs/block-placeholder.md +59 -64
  73. package/dist/docs/blockquote.md +31 -19
  74. package/dist/docs/board.md +187 -73
  75. package/dist/docs/bold.md +1 -9
  76. package/dist/docs/browser.md +6 -17
  77. package/dist/docs/business/compliance-pdf.md +54 -0
  78. package/dist/docs/business/security-kernel.md +57 -0
  79. package/dist/docs/business/security-proof.md +61 -0
  80. package/dist/docs/business/verify.md +78 -0
  81. package/dist/docs/business.md +143 -0
  82. package/dist/docs/callout.md +130 -52
  83. package/dist/docs/clear-formatting.md +5 -15
  84. package/dist/docs/clipboard.md +48 -28
  85. package/dist/docs/code-block.md +168 -68
  86. package/dist/docs/code.md +1 -7
  87. package/dist/docs/collaboration.md +127 -0
  88. package/dist/docs/column.md +36 -31
  89. package/dist/docs/combobox.md +65 -100
  90. package/dist/docs/comment.md +219 -158
  91. package/dist/docs/comparison.md +128 -0
  92. package/dist/docs/components/toolbar-buttons.md +38 -0
  93. package/dist/docs/controlled.md +36 -22
  94. package/dist/docs/copilot.md +215 -203
  95. package/dist/docs/date.md +20 -20
  96. package/dist/docs/debugging.md +5 -14
  97. package/dist/docs/deck.md +173 -0
  98. package/dist/docs/decorations.md +3 -4
  99. package/dist/docs/details.md +69 -17
  100. package/dist/docs/diff.md +109 -0
  101. package/dist/docs/discussion.md +45 -31
  102. package/dist/docs/dnd.md +66 -68
  103. package/dist/docs/document-meta.md +36 -30
  104. package/dist/docs/document-model.md +26 -13
  105. package/dist/docs/docx.md +211 -151
  106. package/dist/docs/dom-coverage.md +6 -1
  107. package/dist/docs/editing-behavior.md +5 -8
  108. package/dist/docs/editor-methods.md +50 -26
  109. package/dist/docs/editor.md +149 -158
  110. package/dist/docs/emoji.md +56 -52
  111. package/dist/docs/equation.md +48 -26
  112. package/dist/docs/examples/collaboration-example.md +21 -30
  113. package/dist/docs/examples/editable-voids.md +4 -3
  114. package/dist/docs/examples/export.md +56 -39
  115. package/dist/docs/examples/huge-document.md +8 -0
  116. package/dist/docs/examples/hundreds-editors.md +2 -0
  117. package/dist/docs/examples/merge.md +50 -0
  118. package/dist/docs/examples/preview-markdown.md +2 -0
  119. package/dist/docs/examples/version-history.md +35 -13
  120. package/dist/docs/exit-break.md +39 -74
  121. package/dist/docs/external-text.md +28 -13
  122. package/dist/docs/field.md +683 -0
  123. package/dist/docs/find.md +110 -97
  124. package/dist/docs/font.md +26 -42
  125. package/dist/docs/footnote.md +252 -242
  126. package/dist/docs/form.md +4 -2
  127. package/dist/docs/format-painter.md +6 -16
  128. package/dist/docs/heading.md +20 -11
  129. package/dist/docs/highlight.md +2 -8
  130. package/dist/docs/history.md +216 -76
  131. package/dist/docs/horizontal-rule.md +22 -34
  132. package/dist/docs/html.md +79 -37
  133. package/dist/docs/indent.md +41 -80
  134. package/dist/docs/index.md +47 -72
  135. package/dist/docs/ink.md +275 -0
  136. package/dist/docs/installation/manual.md +27 -36
  137. package/dist/docs/installation/next.md +23 -24
  138. package/dist/docs/installation/node.md +17 -17
  139. package/dist/docs/installation/plate-ui.md +90 -54
  140. package/dist/docs/installation/react.md +56 -20
  141. package/dist/docs/installation/rsc.md +9 -15
  142. package/dist/docs/installation.md +11 -32
  143. package/dist/docs/italic.md +1 -7
  144. package/dist/docs/kbd.md +1 -7
  145. package/dist/docs/license.md +59 -0
  146. package/dist/docs/line-height.md +2 -12
  147. package/dist/docs/link.md +120 -147
  148. package/dist/docs/lint.md +181 -132
  149. package/dist/docs/list.md +146 -50
  150. package/dist/docs/live-block.md +189 -0
  151. package/dist/docs/llms.txt +102 -80
  152. package/dist/docs/lock.md +298 -0
  153. package/dist/docs/markdown.md +299 -99
  154. package/dist/docs/media.md +240 -219
  155. package/dist/docs/mention.md +46 -44
  156. package/dist/docs/migration-v54.md +361 -0
  157. package/dist/docs/mobile.md +415 -0
  158. package/dist/docs/multi-select.md +30 -34
  159. package/dist/docs/navigation-feedback.md +23 -40
  160. package/dist/docs/pagination.md +151 -128
  161. package/dist/docs/performance.md +13 -17
  162. package/dist/docs/plugin-components.md +23 -20
  163. package/dist/docs/plugin-context.md +18 -13
  164. package/dist/docs/plugin-input-rules.md +169 -171
  165. package/dist/docs/plugin-methods.md +74 -28
  166. package/dist/docs/plugin-rules.md +23 -47
  167. package/dist/docs/plugin-shortcuts.md +70 -14
  168. package/dist/docs/plugin.md +59 -8
  169. package/dist/docs/prompt-editor.md +334 -0
  170. package/dist/docs/reference.md +192 -0
  171. package/dist/docs/releases.md +3 -1
  172. package/dist/docs/roots.md +157 -35
  173. package/dist/docs/rtl.md +8 -4
  174. package/dist/docs/schema.md +18 -7
  175. package/dist/docs/selection.md +17 -5
  176. package/dist/docs/serializing.md +102 -15
  177. package/dist/docs/single-block.md +1 -3
  178. package/dist/docs/slash-command.md +78 -35
  179. package/dist/docs/static.md +122 -54
  180. package/dist/docs/strikethrough.md +1 -7
  181. package/dist/docs/subscript.md +1 -7
  182. package/dist/docs/suggestion.md +96 -92
  183. package/dist/docs/superscript.md +1 -7
  184. package/dist/docs/sync.md +358 -0
  185. package/dist/docs/tabbable.md +56 -93
  186. package/dist/docs/table.md +166 -50
  187. package/dist/docs/text-align.md +8 -18
  188. package/dist/docs/toc.md +48 -72
  189. package/dist/docs/toolbar.md +102 -92
  190. package/dist/docs/trailing-block.md +19 -50
  191. package/dist/docs/transactions.md +2 -2
  192. package/dist/docs/troubleshooting.md +5 -5
  193. package/dist/docs/underline.md +3 -9
  194. package/dist/docs/unit-testing.md +37 -6
  195. package/dist/docs/upload.md +183 -58
  196. package/dist/docx/export/index.d.ts +212 -59
  197. package/dist/docx/export/index.js +2 -1
  198. package/dist/docx/export/lib/compileAst.js +2552 -0
  199. package/dist/docx/export/lib/docxComments.js +153 -0
  200. package/dist/docx/export/lib/exportDocx.js +585 -229
  201. package/dist/docx/export/lib/mathOmml.js +232 -0
  202. package/dist/docx/export/lib/ooxmlBuilder.js +2596 -0
  203. package/dist/docx/export/lib/outputSafety.js +241 -84
  204. package/dist/docx/export/lib/reviewProjection.js +332 -120
  205. package/dist/docx/export/lib/sourceEnvelopePatcher.js +1169 -0
  206. package/dist/docx/export/lib/sourcePreservation.js +233 -110
  207. package/dist/docx/export/lib/wordStyles.js +450 -0
  208. package/dist/docx/html/cleanWordHtml.internal.js +398 -115
  209. package/dist/docx/html/domParser.internal.js +4 -0
  210. package/dist/docx/import/index.d.ts +37 -5
  211. package/dist/docx/import/index.js +2 -1
  212. package/dist/docx/import/lib/docxComments.js +151 -0
  213. package/dist/docx/import/lib/importDocx.js +3516 -1082
  214. package/dist/docx/import/lib/opcRelationships.js +88 -0
  215. package/dist/docx/import/lib/readWordDocument.js +2534 -0
  216. package/dist/docx/import/lib/wordStyles.js +638 -0
  217. package/dist/docx/internal/abort.js +3 -3
  218. package/dist/docx/internal/colors.js +307 -0
  219. package/dist/docx/internal/diagnostics.js +68 -0
  220. package/dist/docx/internal/docxComments.js +34 -0
  221. package/dist/docx/internal/docxPackage.js +343 -71
  222. package/dist/docx/internal/packageParts.js +17 -18
  223. package/dist/docx/internal/pageLayout.js +313 -0
  224. package/dist/docx/internal/readDocxNumbering.js +79 -59
  225. package/dist/docx/internal/reviewPart.js +68 -37
  226. package/dist/docx/internal/source.js +1 -0
  227. package/dist/docx/internal/sourceEligibility.js +385 -60
  228. package/dist/docx/internal/sourceEnvelope.js +473 -0
  229. package/dist/docx/internal/tableBorders.js +79 -0
  230. package/dist/docx/internal/wordFields.js +40 -0
  231. package/dist/docx/internal/wordMath.js +136 -166
  232. package/dist/docx/internal/xmlTree.js +288 -0
  233. package/dist/docx/internal/xmlWriter.js +44 -0
  234. package/dist/docx/paste/index.d.ts +28 -6
  235. package/dist/docx/paste/lib/WordPastePlugin.js +78 -107
  236. package/dist/dom/index.d.ts +2 -7
  237. package/dist/dom/index.js +2 -2
  238. package/dist/dom/plite-dom.internal.js +2 -2
  239. package/dist/facade.js +3 -3
  240. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +170 -87
  241. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +140 -27
  242. package/dist/features/basic-nodes/lib/BaseMarkPlugins.js +160 -82
  243. package/dist/features/basic-styles/lib/BaseFormattingPlugin.js +66 -30
  244. package/dist/features/basic-styles/lib/BaseStylePlugins.js +144 -89
  245. package/dist/features/board/index.d.ts +2 -2
  246. package/dist/features/board/index.js +4 -3
  247. package/dist/features/board/lib/BaseBoardArrowPlugin.js +90 -87
  248. package/dist/features/board/lib/BaseBoardFramePlugin.js +7 -7
  249. package/dist/features/board/lib/BaseBoardGeoPlugin.js +3 -2
  250. package/dist/features/board/lib/BaseBoardImagePlugin.js +9 -6
  251. package/dist/features/board/lib/BaseBoardNotePlugin.js +3 -2
  252. package/dist/features/board/lib/BaseBoardPlugin.js +473 -281
  253. package/dist/features/board/lib/BaseBoardStrokePlugin.js +9 -6
  254. package/dist/features/board/lib/BaseBoardTextPlugin.js +13 -0
  255. package/dist/features/board/lib/boardArrow.internal.js +7 -5
  256. package/dist/features/board/lib/boardCopy.internal.js +42 -36
  257. package/dist/features/board/lib/boardFrame.internal.js +5 -7
  258. package/dist/features/board/lib/boardGeometry.internal.js +127 -0
  259. package/dist/features/board/lib/boardHeights.internal.js +57 -0
  260. package/dist/features/board/lib/boardHtml.internal.js +51 -34
  261. package/dist/features/board/lib/boardMember.internal.js +10 -10
  262. package/dist/features/board/lib/boardShape.internal.js +10 -119
  263. package/dist/features/board/lib/boardStroke.internal.js +13 -1
  264. package/dist/features/board/lib/boardStyle.internal.js +11 -7
  265. package/dist/features/board/lib/boardTypes.internal.js +28 -0
  266. package/dist/features/callout/index.d.ts +2 -84
  267. package/dist/features/callout/lib/BaseCalloutPlugin.js +464 -18
  268. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +236 -194
  269. package/dist/features/code-block/lib/CodeBlockRules.js +133 -14
  270. package/dist/features/column/index.d.ts +2 -0
  271. package/dist/features/column/lib/BaseColumnPlugin.js +767 -0
  272. package/dist/features/comments/BaseCommentsPlugin.js +1832 -729
  273. package/dist/features/comments/comment-active-presentations.internal.js +86 -0
  274. package/dist/features/comments/comment-range-reader.internal.js +12 -0
  275. package/dist/features/comments/comment-thread-index.internal.js +869 -0
  276. package/dist/features/comments/comment-unresolved-index.internal.js +102 -0
  277. package/dist/features/comments/comment-validation.internal.js +136 -0
  278. package/dist/features/comments/fitCommentBody.js +338 -0
  279. package/dist/features/comments/index.d.ts +3 -2
  280. package/dist/features/comments/index.js +3 -2
  281. package/dist/features/date/index.d.ts +3 -2
  282. package/dist/features/date/lib/BaseDatePlugin.js +126 -33
  283. package/dist/features/details/index.d.ts +11 -4
  284. package/dist/features/details/lib/BaseDetailsPlugin.js +602 -217
  285. package/dist/features/field/index.d.ts +2 -0
  286. package/dist/features/field/index.js +4 -0
  287. package/dist/features/field/lib/BaseFieldPlugin.js +682 -0
  288. package/dist/features/field/lib/applyFieldValues.js +579 -0
  289. package/dist/features/field/lib/fieldCache.internal.js +67 -0
  290. package/dist/features/field/lib/fieldRules.internal.js +658 -0
  291. package/dist/features/find/index.d.ts +125 -40
  292. package/dist/features/find/lib/BaseFindPlugin.js +1952 -207
  293. package/dist/features/footnote/index.d.ts +429 -2
  294. package/dist/features/footnote/lib/BaseFootnotePlugin.js +512 -180
  295. package/dist/features/indent/lib/BaseIndentPlugin.js +226 -76
  296. package/dist/features/indent/lib/indentHtml.internal.js +35 -0
  297. package/dist/features/indent/lib/indentLevel.internal.js +3 -3
  298. package/dist/features/ink/index.d.ts +2 -2
  299. package/dist/features/ink/index.js +2 -2
  300. package/dist/features/ink/lib/BaseInkPlugin.js +891 -155
  301. package/dist/features/ink/lib/inkAnchor.internal.js +436 -0
  302. package/dist/features/ink/lib/inkCodec.internal.js +145 -0
  303. package/dist/features/ink/lib/inkMatch.internal.js +236 -71
  304. package/dist/features/ink/lib/inkPlaces.internal.js +219 -71
  305. package/dist/features/ink/lib/inkReflow.internal.js +406 -0
  306. package/dist/features/ink/lib/inkSvg.internal.js +419 -0
  307. package/dist/features/link/lib/BaseLinkPlugin.js +504 -193
  308. package/dist/features/lint/index.d.ts +57 -30
  309. package/dist/features/lint/lib/BaseLintPlugin.js +581 -186
  310. package/dist/features/list/lib/BaseListPlugin.js +105 -690
  311. package/dist/features/list/lib/listCommands.internal.js +161 -0
  312. package/dist/features/list/lib/listFamily.internal.js +68 -23
  313. package/dist/features/list/lib/listHtml.internal.js +185 -69
  314. package/dist/features/list/lib/listIndex.internal.js +54 -20
  315. package/dist/features/list/lib/listKeyboard.internal.js +181 -0
  316. package/dist/features/list/lib/listMarkdown.internal.js +123 -0
  317. package/dist/features/list/lib/listNumbering.internal.js +1 -1
  318. package/dist/features/list/lib/listRules.internal.js +125 -0
  319. package/dist/features/lock/index.d.ts +2 -0
  320. package/dist/features/lock/index.js +2 -0
  321. package/dist/features/lock/lib/BaseLockPlugin.js +761 -0
  322. package/dist/features/media/index.d.ts +2 -2
  323. package/dist/features/media/index.js +5 -5
  324. package/dist/features/media/lib/BaseMediaPlugin.js +120 -155
  325. package/dist/features/media/lib/image/BaseImagePlugin.js +128 -154
  326. package/dist/features/media/lib/media/parseMediaEmbedUrl.internal.js +326 -0
  327. package/dist/features/media/lib/media/parseMediaEmbedUrl.js +12 -0
  328. package/dist/features/media/lib/media-embed/BaseMediaEmbedPlugin.js +68 -11
  329. package/dist/features/media/lib/mediaHtml.internal.js +2 -2
  330. package/dist/features/media/lib/mediaPasteRule.internal.js +89 -0
  331. package/dist/features/media/lib/mediaPlugin.internal.js +201 -0
  332. package/dist/features/mention/index.d.ts +2 -72
  333. package/dist/features/mention/lib/BaseMentionPlugin.js +97 -49
  334. package/dist/features/reference/index.d.ts +240 -0
  335. package/dist/features/reference/index.js +2 -0
  336. package/dist/features/reference/lib/BaseReferencePlugin.js +598 -0
  337. package/dist/features/table/index.d.ts +3 -2
  338. package/dist/features/table/lib/BaseTablePlugin.js +1312 -447
  339. package/dist/features/table/lib/internal/authoredProjection.js +172 -0
  340. package/dist/features/table/lib/internal/axisMove.js +244 -0
  341. package/dist/features/table/lib/internal/docxBorders.js +79 -0
  342. package/dist/features/table/lib/internal/grid.js +34 -1
  343. package/dist/features/table/lib/internal/mutation.js +53 -141
  344. package/dist/features/table/lib/internal/paste.js +66 -3
  345. package/dist/features/table/lib/internal/selection.js +120 -20
  346. package/dist/features/table/lib/internal/tableCellHtml.js +11 -2
  347. package/dist/features/table/lib/internal/tabularText.js +105 -3
  348. package/dist/features/table/lib/internal/widths.js +136 -0
  349. package/dist/features/toc/index.d.ts +2 -2
  350. package/dist/features/toc/index.js +2 -2
  351. package/dist/features/toc/lib/BaseTocPlugin.js +163 -22
  352. package/dist/features/upload/index.d.ts +2 -2
  353. package/dist/features/upload/index.js +3 -2
  354. package/dist/features/upload/lib/BaseUploadPlugin.js +644 -443
  355. package/dist/features/upload/lib/uploadRules.internal.js +259 -0
  356. package/dist/history/index.d.ts +2 -3
  357. package/dist/history/index.js +2 -1
  358. package/dist/html/index.d.ts +4 -3
  359. package/dist/html/server/index.d.ts +6 -2
  360. package/dist/html/server/index.js +8 -4
  361. package/dist/html/server/serverCssParser.internal.js +372 -0
  362. package/dist/html/server/serverCssStyle.internal.js +214 -0
  363. package/dist/{index-DC_MNGyu.d.ts → htmlConversion-CmUPi9rg.d.ts} +6 -3
  364. package/dist/{htmlTypes-DjeFG3P8.d.ts → htmlTypes-C3hHzpRh.d.ts} +33 -45
  365. package/dist/hyperscript/index.d.ts +1 -1
  366. package/dist/index-5j5BcvLz.d.ts +493 -0
  367. package/dist/{react/features/layout/index.d.ts → index-B7vlwvLQ.d.ts} +201 -193
  368. package/dist/{index-Bxfvicyy.d.ts → index-BFuz7j3F.d.ts} +292 -176
  369. package/dist/index-BKiW8Kte.d.ts +21 -0
  370. package/dist/index-BTGCF8li.d.ts +3146 -0
  371. package/dist/index-BnqTluVD-D50uRAnI.d.ts +348 -0
  372. package/dist/index-Bw3p8fsS.d.ts +258 -0
  373. package/dist/{index-D5W-p9bS.d.ts → index-BxJ1-Bk3.d.ts} +631 -320
  374. package/dist/index-Byf_lqL7.d.ts +84 -0
  375. package/dist/index-CEQXbShY.d.ts +1 -0
  376. package/dist/{index-DaM37gF6.d.ts → index-CW0A2w5s.d.ts} +166 -248
  377. package/dist/{index-DzD6BIFJ.d.ts → index-CXFQCw_T.d.ts} +474 -443
  378. package/dist/{index-CcZbqPqk.d.ts → index-Cv3NLcDO.d.ts} +213 -75
  379. package/dist/index-D17Cz7nd.d.ts +97 -0
  380. package/dist/index-D4gbdWPp.d.ts +208 -0
  381. package/dist/index-D7LkEoIA.d.ts +118 -0
  382. package/dist/index-DQAD-81H.d.ts +930 -0
  383. package/dist/{index-Bc2Yg_2j.d.ts → index-DgYHSQmu-DLvTjIM2.d.ts} +4 -4
  384. package/dist/index-DqsRyYXn.d.ts +3 -0
  385. package/dist/{index-DTgaSxKr.d.ts → index-DzXvKehR.d.ts} +130 -110
  386. package/dist/index-KVVMEzVq.d.ts +45 -0
  387. package/dist/index-OJ8B_v_P-D5yZA1mD.d.ts +254 -0
  388. package/dist/index-Q7hzYYQW.d.ts +1 -0
  389. package/dist/index-RrccNMAA.d.ts +69 -0
  390. package/dist/index-h-K-xgfs.d.ts +305 -0
  391. package/dist/index.d.ts +4 -4
  392. package/dist/index.js +6 -15
  393. package/dist/internal/comments/comment-anchor.internal.js +696 -0
  394. package/dist/internal/mergePlateRenderedAttributes.js +13 -16
  395. package/dist/{react/internal → internal}/penStroke.internal.js +29 -4
  396. package/dist/internal/plugin/OverridePlugin.js +251 -141
  397. package/dist/internal/plugin/blockInsertion.js +7 -5
  398. package/dist/internal/plugin/collectPlateNodeMappings.js +23 -9
  399. package/dist/internal/plugin/compilePlainTextMappings.js +68 -15
  400. package/dist/internal/plugin/compilePlateModel.js +180 -135
  401. package/dist/internal/plugin/compilePlateShortcuts.js +2 -1
  402. package/dist/internal/plugin/compilePluginInputMaps.js +126 -0
  403. package/dist/internal/plugin/conversionLaws.js +73 -0
  404. package/dist/internal/plugin/createPlateModelPublication.js +271 -0
  405. package/dist/internal/plugin/createPlateRuntimePlugins.js +277 -0
  406. package/dist/internal/plugin/defaultElementTag.js +17 -1
  407. package/dist/{react/utils/dom-attributes.internal.js → internal/plugin/domHandlers.js} +8 -2
  408. package/dist/internal/plugin/endMatterPartition.js +28 -0
  409. package/dist/internal/plugin/getPlateDecorationSources.js +2 -1
  410. package/dist/internal/plugin/getPluginRenderAttributes.js +4 -8
  411. package/dist/internal/plugin/indentShift.js +44 -0
  412. package/dist/internal/plugin/isEditOnlyDisabled.js +1 -1
  413. package/dist/internal/plugin/markdownClipboardUnwrap.js +10 -0
  414. package/dist/internal/plugin/markdownEscapes.js +20 -0
  415. package/dist/internal/plugin/markdownParagraph.js +23 -1
  416. package/dist/internal/plugin/markdownPreservedProperties.js +25 -0
  417. package/dist/internal/plugin/matchesPluginInject.internal.js +20 -0
  418. package/dist/internal/plugin/mergeNodeAttributes.internal.js +76 -0
  419. package/dist/internal/plugin/pastedUploadFiles.js +4 -0
  420. package/dist/internal/plugin/pipeInjectNodeProps.js +8 -13
  421. package/dist/internal/plugin/plateRuntime.js +11 -3
  422. package/dist/internal/plugin/pluginDescriptorSnapshot.js +172 -0
  423. package/dist/internal/plugin/pluginFormatOperation.js +8 -3
  424. package/dist/internal/plugin/pluginInjectNodeProps.js +49 -34
  425. package/dist/internal/plugin/pluginNodeClass.internal.js +6 -0
  426. package/dist/internal/plugin/pluginStore.js +81 -11
  427. package/dist/internal/plugin/resolvePlugin.js +45 -25
  428. package/dist/internal/plugin/resolvePluginGraph.js +352 -0
  429. package/dist/internal/plugin/resolvePlugins.js +20 -1133
  430. package/dist/internal/plugin/staticReuseKey.internal.js +15 -0
  431. package/dist/internal/plugin/uploadDrafts.js +11 -0
  432. package/dist/internal/utils/mergePlugins.js +7 -5
  433. package/dist/internal/utils/trustedContentSlice.js +1 -1
  434. package/dist/internal/utils/urlPolicy.js +37 -2
  435. package/dist/internal/utils/vscodeClipboard.js +11 -0
  436. package/dist/lib/editor/editorUser.internal.js +13 -5
  437. package/dist/lib/editor/withPlite.js +118 -61
  438. package/dist/lib/libs/zustand.js +31 -7
  439. package/dist/lib/plugin/basePluginFactory.internal.js +7 -0
  440. package/dist/lib/plugin/createPluginContext.internal.js +8 -27
  441. package/dist/lib/plugin/defineBasePlugin.internal.js +69 -9
  442. package/dist/lib/plugin/definePlugin.js +1 -1
  443. package/dist/lib/plugin/pluginFactoryRuntime.internal.js +40 -0
  444. package/dist/lib/plugins/affinity/AffinityPlugin.js +85 -52
  445. package/dist/lib/plugins/debug/DebugPlugin.js +1 -4
  446. package/dist/lib/plugins/dom/DOMPlugin.js +35 -15
  447. package/dist/lib/plugins/dom/clipboardFormatKey.internal.js +9 -0
  448. package/dist/lib/plugins/dom/isPlainTextPasteTarget.internal.js +13 -0
  449. package/dist/lib/plugins/getCorePlugins.internal.js +1 -3
  450. package/dist/lib/plugins/html/HtmlPlugin.js +49 -1745
  451. package/dist/lib/plugins/html/cssLexer.internal.js +409 -0
  452. package/dist/lib/plugins/html/cssSafety.internal.js +100 -0
  453. package/dist/lib/plugins/html/htmlAst.js +62 -18
  454. package/dist/lib/plugins/html/htmlConversion.js +25 -9
  455. package/dist/lib/plugins/html/htmlDecode.internal.js +808 -0
  456. package/dist/lib/plugins/html/htmlDom.js +3 -13
  457. package/dist/lib/plugins/html/htmlMatcher.internal.js +24 -1
  458. package/dist/lib/plugins/html/htmlRules.internal.js +417 -0
  459. package/dist/lib/plugins/html/htmlSafety.js +38 -24
  460. package/dist/lib/plugins/html/htmlSerialize.internal.js +495 -0
  461. package/dist/lib/plugins/html/htmlStyleInline.internal.js +688 -0
  462. package/dist/lib/plugins/html/htmlWhitespace.internal.js +137 -0
  463. package/dist/lib/plugins/input-rules/InputRulesPlugin.js +187 -54
  464. package/dist/lib/plugins/input-rules/createInputRules.js +65 -69
  465. package/dist/lib/plugins/input-rules/inputRuleVeto.internal.js +144 -0
  466. package/dist/lib/plugins/input-rules/inputRuleVeto.js +2 -2
  467. package/dist/lib/plugins/input-rules/inputRules.internal.js +20 -0
  468. package/dist/lib/plugins/input-rules/markInputRule.internal.js +64 -2
  469. package/dist/lib/plugins/paragraph/BaseParagraphPlugin.js +21 -8
  470. package/dist/lib/utils/getInjectMatch.js +6 -39
  471. package/dist/markdown/index.d.ts +2 -2
  472. package/dist/markdown/index.js +2 -1
  473. package/dist/markdown/lib/MarkdownPlugin.js +129 -84
  474. package/dist/markdown/lib/deserializer/convertNodesDeserialize.js +32 -8
  475. package/dist/markdown/lib/deserializer/mdastToSlate.js +11 -3
  476. package/dist/markdown/lib/internal/markdownAttributes.js +18 -8
  477. package/dist/markdown/lib/internal/markdownBareLinks.js +270 -0
  478. package/dist/markdown/lib/internal/markdownBreaks.js +191 -0
  479. package/dist/markdown/lib/internal/markdownDiagnostics.js +33 -16
  480. package/dist/markdown/lib/internal/markdownDocument.js +14 -33
  481. package/dist/markdown/lib/internal/markdownFootnoteWriter.js +35 -0
  482. package/dist/markdown/lib/internal/markdownFrontmatter.js +102 -0
  483. package/dist/markdown/lib/internal/markdownIntrinsics.js +88 -163
  484. package/dist/markdown/lib/internal/markdownLine.js +186 -145
  485. package/dist/markdown/lib/internal/markdownMappings.js +335 -107
  486. package/dist/markdown/lib/internal/markdownParse.js +596 -0
  487. package/dist/markdown/lib/internal/markdownReferences.js +12 -6
  488. package/dist/markdown/lib/internal/markdownRuntime.js +456 -0
  489. package/dist/markdown/lib/internal/markdownSafety.js +53 -1
  490. package/dist/markdown/lib/internal/markdownSerialize.js +197 -0
  491. package/dist/markdown/lib/internal/markdownStream.js +1006 -0
  492. package/dist/markdown/lib/internal/markdownTags.js +206 -76
  493. package/dist/markdown/lib/internal/markdownTailHeal.js +869 -0
  494. package/dist/markdown/lib/internal/walkMdast.js +34 -0
  495. package/dist/markdown/lib/serializer/convertNodesSerialize.js +33 -18
  496. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +322 -0
  497. package/dist/markdown/lib/serializer/listToMdastTree.js +34 -12
  498. package/dist/markdown/lib/serializer/reportOmittedProperties.js +5 -2
  499. package/dist/markdown/lib/utils/remarkPlugins.js +48 -23
  500. package/dist/math/index.d.ts +21 -384
  501. package/dist/math/lib/BaseEquationPlugin.js +111 -29
  502. package/dist/math/react/index.d.ts +10 -9
  503. package/dist/migrations/documentMigrationAuthored.internal.js +2 -1
  504. package/dist/migrations/documentMigrationSelection.internal.js +138 -2
  505. package/dist/migrations/documentMigrationTarget.internal.js +10 -2
  506. package/dist/migrations/documentMigrations.js +134 -143
  507. package/dist/migrations/index.d.ts +30 -44
  508. package/dist/migrations/index.js +1 -2
  509. package/dist/migrations/migratePlateV54.js +61 -52
  510. package/dist/migrations/migratePlateV54Ast.internal.js +201 -118
  511. package/dist/migrations/migratePlateV54BuiltIns.internal.js +18 -3
  512. package/dist/migrations/migratePlateV54Callout.internal.js +61 -0
  513. package/dist/migrations/migratePlateV54CodeBlocks.internal.js +68 -34
  514. package/dist/migrations/migratePlateV54Excalidraw.internal.js +534 -0
  515. package/dist/migrations/migratePlateV54ExcalidrawHelpers.internal.js +82 -0
  516. package/dist/migrations/migratePlateV54Inputs.internal.js +39 -32
  517. package/dist/migrations/migratePlateV54ListIdentity.internal.js +220 -0
  518. package/dist/migrations/migratePlateV54Profile.internal.js +54 -27
  519. package/dist/migrations/migratePlateV54RetiredMarks.internal.js +25 -10
  520. package/dist/migrations/migratePlateV54Stage.internal.js +127 -0
  521. package/dist/migrations/migratePlateV54Suggestions.internal.js +10 -3
  522. package/dist/migrations/migratePlateV54Toggle.internal.js +66 -0
  523. package/dist/migrations/migratePlateV54Urls.internal.js +149 -58
  524. package/dist/migrations/v53-manifest.internal.js +4 -0
  525. package/dist/pagination/index.d.ts +2 -167
  526. package/dist/pagination/index.js +26 -2
  527. package/dist/pagination/react/PaginationPlugin.js +271 -0
  528. package/dist/pagination/react/index.d.ts +168 -31
  529. package/dist/pagination/react/index.js +3 -5
  530. package/dist/plain-text.js +19 -15
  531. package/dist/protocol-o3jVSHir-Bouoin05.d.ts +103 -0
  532. package/dist/react/authored/AuthoredReactPlugin.js +127 -0
  533. package/dist/react/authored/index.d.ts +37 -0
  534. package/dist/react/authored/index.js +3 -0
  535. package/dist/react/authored/useAuthored.js +118 -0
  536. package/dist/react/components/EditorContentView.internal.js +100 -53
  537. package/dist/react/components/EditorProvider.js +26 -25
  538. package/dist/react/components/EditorRefEffect.internal.js +74 -0
  539. package/dist/react/components/EditorRefEffect.js +12 -56
  540. package/dist/react/components/NodeSelection.js +513 -485
  541. package/dist/react/components/Plate.js +259 -185
  542. package/dist/react/components/PlateContainer.js +110 -45
  543. package/dist/react/components/PlateContent.js +3 -3
  544. package/dist/react/components/PlateController.js +28 -16
  545. package/dist/react/components/PlateRoot.internal.js +3 -2
  546. package/dist/react/components/PlateView.js +34 -20
  547. package/dist/{static/internal/getPlainText.js → react/components/getPlainText.internal.js} +1 -4
  548. package/dist/react/components/plate-nodes.js +66 -87
  549. package/dist/{static/internal/writeStaticSelectionClipboardData.js → react/components/writeStaticSelectionClipboardData.internal.js} +11 -7
  550. package/dist/react/core.js +8 -17
  551. package/dist/react/editor/getPlateCorePlugins.internal.js +1 -1
  552. package/dist/react/editor/useCreateEditor.js +19 -17
  553. package/dist/react/editor/withPlate.js +11 -8
  554. package/dist/react/features/basic-styles/BasicStylePlugins.js +2 -3
  555. package/dist/react/features/board/BoardPlugin.js +8 -2
  556. package/dist/react/features/board/BoardShape.js +475 -169
  557. package/dist/react/features/board/BoardSurface.js +118 -89
  558. package/dist/react/features/board/boardCamera.internal.js +295 -0
  559. package/dist/react/features/board/boardClipboard.internal.js +41 -32
  560. package/dist/react/features/board/boardConnect.internal.js +2 -10
  561. package/dist/react/features/board/boardExport.internal.js +757 -0
  562. package/dist/react/features/board/boardGesture.internal.js +234 -65
  563. package/dist/react/features/board/boardIndex.internal.js +282 -46
  564. package/dist/react/features/board/boardInk.internal.js +2 -13
  565. package/dist/react/features/board/boardKeys.internal.js +76 -47
  566. package/dist/react/features/board/boardLanding.internal.js +147 -0
  567. package/dist/react/features/board/boardPick.internal.js +4 -3
  568. package/dist/react/features/board/boardPicking.internal.js +0 -17
  569. package/dist/react/features/board/boardPictureStyles.internal.js +415 -0
  570. package/dist/react/features/board/boardPictures.internal.js +19 -13
  571. package/dist/react/features/board/boardPreview.internal.js +74 -16
  572. package/dist/react/features/board/boardResize.internal.js +114 -47
  573. package/dist/react/features/board/boardSnap.internal.js +14 -9
  574. package/dist/react/features/board/boardStyleView.internal.js +123 -0
  575. package/dist/react/features/board/boardTextFit.internal.js +311 -0
  576. package/dist/react/features/board/boardView.internal.js +560 -552
  577. package/dist/react/features/board/boardVoice.internal.js +29 -17
  578. package/dist/react/features/board/boardWindow.internal.js +138 -0
  579. package/dist/react/features/board/index.d.ts +559 -156
  580. package/dist/react/features/board/index.js +3 -3
  581. package/dist/react/features/callout/index.d.ts +212 -39
  582. package/dist/react/features/{layout → column}/ColumnPlugin.js +4 -3
  583. package/dist/react/features/column/index.d.ts +808 -0
  584. package/dist/react/features/combobox/combobox.internal.js +119 -0
  585. package/dist/react/features/combobox/comboboxOwner.internal.js +76 -27
  586. package/dist/react/features/combobox/index.d.ts +51 -18
  587. package/dist/react/features/combobox/useCombobox.js +50 -13
  588. package/dist/react/features/comments/CommentsPlugin.js +2 -3
  589. package/dist/react/features/comments/index.d.ts +74 -342
  590. package/dist/react/features/comments/index.js +2 -1
  591. package/dist/react/features/comments/useCommentThreadIndex.js +243 -0
  592. package/dist/react/features/date/index.d.ts +4 -3
  593. package/dist/react/features/details/index.d.ts +126 -10
  594. package/dist/react/features/field/FieldPlugin.js +49 -0
  595. package/dist/react/features/field/index.d.ts +326 -0
  596. package/dist/react/features/field/index.js +2 -0
  597. package/dist/react/features/footnote/FootnotePlugin.js +13 -8
  598. package/dist/react/features/footnote/index.d.ts +373 -130
  599. package/dist/react/features/format-painter/FormatPainterPlugin.js +66 -27
  600. package/dist/react/features/format-painter/index.d.ts +13 -120
  601. package/dist/react/features/ink/InkContent.js +375 -0
  602. package/dist/react/features/ink/InkPlugin.js +102 -6
  603. package/dist/react/features/ink/index.d.ts +290 -260
  604. package/dist/react/features/ink/index.js +2 -3
  605. package/dist/react/features/ink/inkCapture.internal.js +338 -57
  606. package/dist/react/features/ink/inkImages.internal.js +304 -0
  607. package/dist/react/features/ink/inkInput.internal.js +43 -4
  608. package/dist/react/features/ink/inkLayout.internal.js +6 -3
  609. package/dist/react/features/ink/inkMeasure.internal.js +43 -17
  610. package/dist/react/features/ink/inkPaint.internal.js +134 -10
  611. package/dist/react/features/ink/inkPick.internal.js +323 -0
  612. package/dist/react/features/ink/inkPlacement.internal.js +420 -167
  613. package/dist/react/features/ink/inkWatch.internal.js +7 -36
  614. package/dist/react/features/list/ListPlugin.js +74 -38
  615. package/dist/react/features/lock/LockPlugin.js +138 -0
  616. package/dist/react/features/lock/index.d.ts +60 -0
  617. package/dist/react/features/lock/index.js +2 -0
  618. package/dist/react/features/media/index.d.ts +55 -35
  619. package/dist/react/features/mention/index.d.ts +13 -17
  620. package/dist/react/features/resizable/Resizable.js +9 -8
  621. package/dist/react/features/resizable/index.d.ts +7 -6
  622. package/dist/react/features/table/TablePlugin.js +251 -85
  623. package/dist/react/features/table/index.d.ts +1247 -2690
  624. package/dist/react/features/table/index.js +2 -1
  625. package/dist/react/features/table/measureTableColumnWidths.internal.js +48 -0
  626. package/dist/react/features/table/tableSelectionHostBinding.internal.js +4 -6
  627. package/dist/react/features/table/useTableControls.js +1170 -0
  628. package/dist/react/features/table/useTableResize.js +57 -16
  629. package/dist/react/features/toc/TocPlugin.js +1 -0
  630. package/dist/react/features/toc/index.d.ts +9 -11
  631. package/dist/react/features/upload/UploadPlugin.js +14 -5
  632. package/dist/react/features/upload/index.d.ts +25 -201
  633. package/dist/react/index.d.ts +7 -6
  634. package/dist/react/index.js +12 -21
  635. package/dist/react/internal/plate-context.js +472 -205
  636. package/dist/react/internal/plite-components.js +2 -2
  637. package/dist/react/internal/rendered-attributes.js +1 -1
  638. package/dist/react/internal/useDeepCompareMemo.js +36 -7
  639. package/dist/react/internal/usePlateModelRevision.js +13 -9
  640. package/dist/react/plite-react.js +2 -2
  641. package/dist/react/plugin/pluginFactory.internal.js +1 -37
  642. package/dist/react/plugin/toReactPlugin.js +40 -8
  643. package/dist/react/plugins/navigation-feedback/NavigationFeedbackPlugin.js +12 -10
  644. package/dist/react/plugins/paragraph/ParagraphPlugin.js +3 -3
  645. package/dist/react/stores/element/useElement.js +2 -2
  646. package/dist/react/stores/element/useElementSelector.js +4 -2
  647. package/dist/react/stores/element/useElementStore.js +142 -106
  648. package/dist/react/stores/element/useElementStoreSelector.internal.js +80 -24
  649. package/dist/react/stores/element/usePath.js +32 -32
  650. package/dist/react/stores/plate/pluginStoreSelector.internal.js +44 -0
  651. package/dist/react/stores/plate/useEditor.js +135 -71
  652. package/dist/react/stores/plate/useEditorHistory.js +55 -0
  653. package/dist/react/stores/plate/useEditorSelector.js +33 -22
  654. package/dist/react/stores/plate/usePluginStore.js +36 -43
  655. package/dist/react/stores/plate/useViewStore.js +38 -23
  656. package/dist/react/utils/BlockPlaceholderPlugin.js +41 -26
  657. package/dist/react/utils/dispatchPlateShortcut.internal.js +2 -1
  658. package/dist/react/utils/editableKeyDown.internal.js +1 -0
  659. package/dist/react/utils/getRenderNodeProps.internal.js +18 -19
  660. package/dist/react/utils/hardAffinityBoundary.internal.js +25 -0
  661. package/dist/react/utils/pipeHandler.internal.js +43 -17
  662. package/dist/react/utils/pipeRenderElement.internal.js +86 -70
  663. package/dist/react/utils/pipeRenderLeaf.internal.js +26 -45
  664. package/dist/react/utils/pipeRenderText.internal.js +44 -42
  665. package/dist/react/utils/pluginRenderElement.internal.js +9 -7
  666. package/dist/react/utils/pluginRenderLeaf.internal.js +6 -28
  667. package/dist/react/utils/pluginRenderText.internal.js +3 -15
  668. package/dist/react/utils/useSelectionFragment.js +8 -2
  669. package/dist/react/virtualized.d.ts +7 -6
  670. package/dist/react/virtualized.js +2 -2
  671. package/dist/refusal-hmMeqqsF-DEODtsVZ.d.ts +1 -0
  672. package/dist/registerEditorTools-CxU5qGen.d.ts +519 -0
  673. package/dist/root.js +6 -15
  674. package/dist/shared-room-D0Ch6_0l-DEODtsVZ.d.ts +1 -0
  675. package/dist/skills/plate/SKILL.md +49 -0
  676. package/dist/skills/plate/references/ai-and-agents.md +16 -0
  677. package/dist/skills/plate/references/plugins.md +22 -0
  678. package/dist/skills/plate/references/pricing.md +38 -0
  679. package/dist/skills/plate/references/report-a-bug.md +8 -0
  680. package/dist/skills/plate/references/setup.md +78 -0
  681. package/dist/skills/plate/references/testing.md +22 -0
  682. package/dist/skills/plate/references/ui-and-sync.md +25 -0
  683. package/dist/{source-CNKy99Th.d.ts → source-SWPrNfXp.d.ts} +32 -20
  684. package/dist/static/components/{PlateStatic.js → EditorStatic.js} +184 -42
  685. package/dist/static/components/plite-nodes.js +40 -17
  686. package/dist/static/index.d.ts +60 -38
  687. package/dist/static/index.js +1 -1
  688. package/dist/static/internal/loadStaticRenderer.js +4 -0
  689. package/dist/static/internal/staticDocumentView.js +219 -17
  690. package/dist/static/internal/staticPendingMedia.internal.js +147 -0
  691. package/dist/static/internal/staticPresentation.js +22 -25
  692. package/dist/static/internal/staticViewState.internal.js +47 -0
  693. package/dist/static/pipeRenderElementStatic.internal.js +3 -13
  694. package/dist/static/pluginRenderElementStatic.internal.js +32 -7
  695. package/dist/static/pluginRenderMarkStatic.internal.js +90 -0
  696. package/dist/static/renderStaticHtml.js +92 -6
  697. package/dist/static/utils/fallbackContentRoots.internal.js +15 -0
  698. package/dist/static/utils/getRenderNodeStaticProps.internal.js +12 -5
  699. package/dist/storage-BiSc0Cnj-BamxXwsJ.d.ts +250 -0
  700. package/dist/sync/SyncPlugin.js +16 -0
  701. package/dist/sync/cloudflare/index.d.ts +72 -0
  702. package/dist/sync/cloudflare/index.js +2 -0
  703. package/dist/sync/index.d.ts +5 -0
  704. package/dist/sync/index.js +3 -0
  705. package/dist/sync/postgres/index.d.ts +41 -0
  706. package/dist/sync/postgres/index.js +2 -0
  707. package/dist/sync/react/SyncReactPlugin.js +20 -0
  708. package/dist/sync/react/hooks.js +71 -0
  709. package/dist/sync/react/index.d.ts +87 -0
  710. package/dist/sync/react/index.js +3 -0
  711. package/dist/sync/server/index.d.ts +6 -0
  712. package/dist/sync/server/index.js +2 -0
  713. package/dist/tabbable/react/TabbableEffects.internal.js +96 -37
  714. package/dist/tabbable/react/TabbablePlugin.js +6 -1
  715. package/dist/tabbable/react/index.d.ts +63 -5
  716. package/dist/testing/index.d.ts +20 -10
  717. package/dist/transport-CWTT3vFK-_eytF0bO.d.ts +78 -0
  718. package/dist/{index-BU6k1Aev.d.ts → tx-only-CFSEh_pE-j0KGzcne.d.ts} +8226 -6860
  719. package/dist/utils/plate-keys.js +4 -9
  720. package/dist/utils/plugins/TrailingBlockPlugin.js +10 -7
  721. package/dist/utils/plugins/resolveTrailingBlockType.internal.js +8 -0
  722. package/dist/{index-xdmCBvlT.d.ts → widths-C1tAKF__.d.ts} +590 -140
  723. package/package.json +94 -148
  724. package/LICENSE +0 -24
  725. package/dist/AIChatRequestContext-BMVWhfPV.d.ts +0 -34
  726. package/dist/BaseSuggestionPlugin-DBl3fqnm.d.ts +0 -86
  727. package/dist/PlateStatic-DhNv2ejp.d.ts +0 -19
  728. package/dist/ai/lib/AIChatRequestContext.js +0 -16
  729. package/dist/ai/lib/findQuotedSpan.internal.js +0 -63
  730. package/dist/ai/react/AIChatPlugin.js +0 -1203
  731. package/dist/ai/react/useAIChat.js +0 -327
  732. package/dist/combobox-DkBGgyd3.d.ts +0 -22
  733. package/dist/comparison-types-CYnJ35qU.d.ts +0 -169
  734. package/dist/docs/excalidraw.md +0 -200
  735. package/dist/docs/installation/docs.md +0 -24
  736. package/dist/docs/installation/mcp.md +0 -147
  737. package/dist/docs/migration/plite-to-plate.md +0 -251
  738. package/dist/docs/yjs.md +0 -256
  739. package/dist/docx/export/lib/comments.js +0 -231
  740. package/dist/docx/export/lib/docxStaticComponents.js +0 -371
  741. package/dist/docx/export/lib/exportHtmlToDocx.internal.js +0 -70
  742. package/dist/docx/export/lib/generatedParts.js +0 -51
  743. package/dist/docx/export/lib/html-to-docx.internal.js +0 -40
  744. package/dist/docx/export/lib/internal/constants.js +0 -106
  745. package/dist/docx/export/lib/internal/docx-document.js +0 -652
  746. package/dist/docx/export/lib/internal/escape-xml.js +0 -4
  747. package/dist/docx/export/lib/internal/html-to-docx.js +0 -148
  748. package/dist/docx/export/lib/internal/list-item.js +0 -85
  749. package/dist/docx/export/lib/internal/list.js +0 -43
  750. package/dist/docx/export/lib/internal/math.js +0 -187
  751. package/dist/docx/export/lib/internal/namespaces.js +0 -40
  752. package/dist/docx/export/lib/internal/render-document-file.js +0 -403
  753. package/dist/docx/export/lib/internal/schemas/content-types.js +0 -25
  754. package/dist/docx/export/lib/internal/schemas/core.js +0 -26
  755. package/dist/docx/export/lib/internal/schemas/document-rels.js +0 -15
  756. package/dist/docx/export/lib/internal/schemas/document.template.js +0 -36
  757. package/dist/docx/export/lib/internal/schemas/font-table.js +0 -55
  758. package/dist/docx/export/lib/internal/schemas/generic-rels.js +0 -9
  759. package/dist/docx/export/lib/internal/schemas/numbering.js +0 -18
  760. package/dist/docx/export/lib/internal/schemas/rels.js +0 -12
  761. package/dist/docx/export/lib/internal/schemas/settings.js +0 -17
  762. package/dist/docx/export/lib/internal/schemas/styles.js +0 -142
  763. package/dist/docx/export/lib/internal/schemas/theme.js +0 -198
  764. package/dist/docx/export/lib/internal/schemas/web-settings.js +0 -10
  765. package/dist/docx/export/lib/internal/unit-conversion.js +0 -24
  766. package/dist/docx/export/lib/internal/vnode.js +0 -4
  767. package/dist/docx/export/lib/internal/word-styles.js +0 -123
  768. package/dist/docx/export/lib/internal/xml-builder.js +0 -1808
  769. package/dist/docx/export/lib/reviewPart.js +0 -234
  770. package/dist/docx/import/lib/wordFormatting.js +0 -608
  771. package/dist/docx/internal/domParser.js +0 -23
  772. package/dist/excalidraw/index.d.ts +0 -57
  773. package/dist/excalidraw/index.js +0 -2
  774. package/dist/excalidraw/lib/BaseExcalidrawPlugin.js +0 -15
  775. package/dist/excalidraw/react/ExcalidrawPlugin.js +0 -6
  776. package/dist/excalidraw/react/index.d.ts +0 -101
  777. package/dist/excalidraw/react/index.js +0 -3
  778. package/dist/excalidraw/react/useExcalidrawSync.js +0 -103
  779. package/dist/features/combobox/index.d.ts +0 -3
  780. package/dist/features/combobox/index.js +0 -2
  781. package/dist/features/combobox/lib/combobox.internal.js +0 -111
  782. package/dist/features/combobox/lib/filterWords.js +0 -23
  783. package/dist/features/comments/plite-comments.internal.js +0 -2
  784. package/dist/features/ink/lib/inkGone.internal.js +0 -107
  785. package/dist/features/layout/index.d.ts +0 -2
  786. package/dist/features/layout/lib/BaseColumnPlugin.js +0 -249
  787. package/dist/features/media/lib/media/parseMediaUrl.js +0 -151
  788. package/dist/features/suggestion/BaseSuggestionPlugin.js +0 -30
  789. package/dist/features/suggestion/index.d.ts +0 -9
  790. package/dist/features/suggestion/index.js +0 -3
  791. package/dist/features/suggestion/suggestionColorOf.js +0 -14
  792. package/dist/features/upload/lib/mimeTypes.internal.js +0 -3982
  793. package/dist/index-BBKGrsG3.d.ts +0 -8
  794. package/dist/index-BiQerPJS.d.ts +0 -46
  795. package/dist/index-BkR7-GLI.d.ts +0 -166
  796. package/dist/index-Bq3sdm3S.d.ts +0 -158
  797. package/dist/index-CT7miqQN.d.ts +0 -298
  798. package/dist/index-Cl77E9yr.d.ts +0 -184
  799. package/dist/index-D1CFXA-i.d.ts +0 -6187
  800. package/dist/index-DLA2DUR2.d.ts +0 -28
  801. package/dist/index-DdIRduDG.d.ts +0 -399
  802. package/dist/index-iaZOhA76.d.ts +0 -59
  803. package/dist/index-kLKMc-pI.d.ts +0 -36
  804. package/dist/internal/plugin/plateChangeHandlers.js +0 -74
  805. package/dist/lib/plugins/element-id/ElementIdPlugin.js +0 -47
  806. package/dist/lib/plugins/element-id/elementIdAdmission.internal.js +0 -34
  807. package/dist/lib/plugins/element-state/ElementStatePlugin.js +0 -14
  808. package/dist/lib/utils/applyDeepToNodes.js +0 -17
  809. package/dist/lib/utils/defaultsDeepToNodes.js +0 -12
  810. package/dist/lib/utils/hotkeys.js +0 -113
  811. package/dist/lib/utils/mergeDeepToNodes.js +0 -12
  812. package/dist/lib/utils/pluginNodeClass.js +0 -10
  813. package/dist/markdown/lib/internal/markdownConversion.js +0 -666
  814. package/dist/markdown/lib/internal/markdownSegments.js +0 -134
  815. package/dist/markdown/lib/serializer/convertTextsSerialize.js +0 -163
  816. package/dist/migrations/migrateListIdentity.js +0 -93
  817. package/dist/pagination/react/PagedEditorContent.js +0 -77
  818. package/dist/react/components/EditorSelectionView.js +0 -40
  819. package/dist/react/features/ink/InkCopyView.js +0 -203
  820. package/dist/react/features/ink/InkLayer.js +0 -218
  821. package/dist/react/features/suggestion/SuggestionPlugin.js +0 -24
  822. package/dist/react/features/suggestion/index.d.ts +0 -44
  823. package/dist/react/features/suggestion/index.js +0 -3
  824. package/dist/react/features/suggestion/suggestion-view.internal.js +0 -112
  825. package/dist/react/features/suggestion/useSuggestion.js +0 -135
  826. package/dist/react/internal/createPlateTargetScope.js +0 -62
  827. package/dist/react/libs/jotai.js +0 -3
  828. package/dist/static/internal/renderStaticHtmlWithOverrides.js +0 -33
  829. package/dist/static/pluginRenderLeafStatic.internal.js +0 -87
  830. package/dist/static/pluginRenderTextStatic.internal.js +0 -87
  831. package/dist/tabbable/index.d.ts +0 -2
  832. package/dist/tabbable/index.js +0 -0
  833. package/dist/utils/plugins/ExitBreakPlugin.js +0 -26
  834. package/dist/yjs/index.d.ts +0 -2
  835. package/dist/yjs/index.js +0 -1
  836. package/dist/yjs/react/YjsPlugin.js +0 -60
  837. package/dist/yjs/react/index.d.ts +0 -94
  838. package/dist/yjs/react/index.js +0 -3
  839. /package/dist/features/{layout → column}/index.js +0 -0
  840. /package/dist/react/features/{layout → column}/index.js +0 -0
@@ -0,0 +1,2552 @@
1
+ import { MAIN_ROOT_KEY, createDetachedEditorSchema, getReaderRange, projectEditorView, readNamedRootChildren, withDocumentViewRead, withEditorDocumentProjection } from "../../../facade.js";
2
+ import { getPlateRuntimeOwner } from "../../../internal/plugin/plateRuntime.js";
3
+ import { getCompiledPlateModel, getPlateRuntime } from "../../../internal/plugin/compilePlateModel.js";
4
+ import { createPluginFormatModelView, createPluginFormatOperationContext } from "../../../internal/plugin/pluginFormatOperation.js";
5
+ import { getPlateNodeMappingContributions } from "../../../internal/plugin/collectPlateNodeMappings.js";
6
+ import { ElementApi, RangeApi, TextApi } from "../../../core.js";
7
+ import { getDocumentListOrdinal } from "../../../features/list/lib/listIndex.internal.js";
8
+ import { BaseListPlugin } from "../../../features/list/lib/BaseListPlugin.js";
9
+ import { getPlateDecorationSources } from "../../../internal/plugin/getPlateDecorationSources.js";
10
+ import { throwIfDocxAborted } from "../../internal/abort.js";
11
+ import { docxLossyContent, docxPropertyDropped, docxResourceOmitted, docxUnsupportedContent } from "../../internal/diagnostics.js";
12
+ import { filterAuthoredReviewRecords } from "../../internal/reviewPart.js";
13
+ import { isAllowedDynamicWordFieldInstruction } from "../../internal/wordFields.js";
14
+ import { renderLatexToOmml } from "./mathOmml.js";
15
+ import { resolveDocxImage, resolveDocxLinkUrl } from "./outputSafety.js";
16
+ import { reviewTargetKey } from "./reviewProjection.js";
17
+ //#region src/docx/export/lib/compileAst.ts
18
+ /**
19
+ * Shared predicate deciding whether a block stays inside Word's flat `Quote`
20
+ * paragraph style or leaves the quote. Used by both OOXML emission and
21
+ * `quote-structure` diagnostics so warnings always match the emitted file.
22
+ */
23
+ const isQuoteParagraphBlock = (block) => block.kind === "paragraph" && !block.listItem && !block.isCodeBlock && (!block.style || block.style === "Normal" || block.style === "Quote");
24
+ const FRAGMENT_PAYLOADS = /* @__PURE__ */ new WeakMap();
25
+ const createFragment = (payload) => {
26
+ const handle = Object.freeze({});
27
+ FRAGMENT_PAYLOADS.set(handle, payload);
28
+ return handle;
29
+ };
30
+ const readFragment = (value) => typeof value === "object" && value !== null ? FRAGMENT_PAYLOADS.get(value) : void 0;
31
+ const ELEMENT_DROPPED_FIELDS = /* @__PURE__ */ new Set(["dropped", "text"]);
32
+ const ELEMENT_ENCODE_FIELDS = /* @__PURE__ */ new Set([
33
+ "decode",
34
+ "encode",
35
+ "node"
36
+ ]);
37
+ const MARK_DROPPED_FIELDS = /* @__PURE__ */ new Set(["dropped"]);
38
+ const MARK_ENCODE_FIELDS = /* @__PURE__ */ new Set([
39
+ "decode",
40
+ "encode",
41
+ "mark"
42
+ ]);
43
+ const PROPERTY_DROPPED_FIELDS = /* @__PURE__ */ new Set(["dropped", "property"]);
44
+ const PROPERTY_ENCODE_FIELDS = /* @__PURE__ */ new Set([
45
+ "decode",
46
+ "encode",
47
+ "property"
48
+ ]);
49
+ const assertAllowedFields = (owner, kind, declaration, allowed) => {
50
+ for (const field of Object.keys(declaration)) if (!allowed.has(field)) throw new Error(`DOCX node mapping "${owner}" has unknown ${kind} field "${field}".`);
51
+ };
52
+ const DOCX_FORMATS_CACHE = /* @__PURE__ */ new WeakMap();
53
+ const collectDocxFormats = (editor) => {
54
+ const runtimeOwner = getPlateRuntimeOwner(editor);
55
+ const model = getCompiledPlateModel(runtimeOwner);
56
+ const cached = DOCX_FORMATS_CACHE.get(model.revision);
57
+ if (cached) return cached;
58
+ const elementEncoders = /* @__PURE__ */ new Map();
59
+ const elementTextFormats = /* @__PURE__ */ new Map();
60
+ const markEncoders = /* @__PURE__ */ new Map();
61
+ const markDropped = /* @__PURE__ */ new Map();
62
+ const propertyEncoders = /* @__PURE__ */ new Map();
63
+ const propertyDropped = [];
64
+ const seenElementTargets = /* @__PURE__ */ new Map();
65
+ const seenMarkTargets = /* @__PURE__ */ new Map();
66
+ const seenPropertyTargets = /* @__PURE__ */ new Map();
67
+ for (const { declaration, ownedPropertyKeys, owner, schema, targetKey, targetKind, targetPlugin, targetType } of getPlateNodeMappingContributions(runtimeOwner, "docx")) {
68
+ const hasEncode = declaration.encode !== void 0;
69
+ const hasDecode = declaration.decode !== void 0;
70
+ const hasDropped = declaration.dropped !== void 0;
71
+ if (hasEncode && hasDropped) throw new Error(`DOCX node mapping "${owner}" cannot define both encode and dropped.`);
72
+ if (!hasEncode && !hasDropped && !hasDecode) throw new Error(`DOCX node mapping "${owner}" must define encode, decode, or dropped.`);
73
+ if (hasEncode && typeof declaration.encode !== "function") throw new Error(`DOCX node mapping "${owner}" encode must be a function.`);
74
+ if (hasDecode && typeof declaration.decode !== "function") throw new Error(`DOCX node mapping "${owner}" decode must be a function.`);
75
+ if (hasDropped && typeof declaration.dropped !== "string") throw new Error(`DOCX node mapping "${owner}" must define a dropped warning message.`);
76
+ if (!hasEncode && !hasDropped) continue;
77
+ if (targetType !== null) {
78
+ const prior = seenElementTargets.get(targetType);
79
+ if (prior && prior !== owner) throw new Error(`DOCX node mappings "${prior}" and "${owner}" both target element "${targetPlugin}".`);
80
+ seenElementTargets.set(targetType, owner);
81
+ elementEncoders.delete(targetType);
82
+ elementTextFormats.delete(targetType);
83
+ if (hasEncode) {
84
+ assertAllowedFields(owner, "element", declaration, ELEMENT_ENCODE_FIELDS);
85
+ elementTextFormats.delete(targetType);
86
+ elementEncoders.set(targetType, {
87
+ encode: declaration.encode,
88
+ owner,
89
+ plugin: targetPlugin,
90
+ schema
91
+ });
92
+ } else {
93
+ assertAllowedFields(owner, "element", declaration, ELEMENT_DROPPED_FIELDS);
94
+ if (typeof declaration.text !== "function") throw new Error(`DOCX node mapping "${owner}" must define dropped and text for an element.`);
95
+ elementEncoders.delete(targetType);
96
+ elementTextFormats.set(targetType, {
97
+ dropped: declaration.dropped,
98
+ plugin: targetPlugin,
99
+ text: declaration.text,
100
+ type: targetType
101
+ });
102
+ }
103
+ continue;
104
+ }
105
+ const hasTextProperty = targetKind === "mark" || Object.values(schema.properties ?? {}).some((handle) => handle?.placement === "text");
106
+ const isElementPropertyMapping = ownedPropertyKeys.length > 0 && (!hasTextProperty || declaration.property !== void 0);
107
+ if (!isElementPropertyMapping && hasTextProperty && targetKey) {
108
+ const prior = seenMarkTargets.get(targetPlugin);
109
+ if (prior && prior !== owner) throw new Error(`DOCX node mappings "${prior}" and "${owner}" both target mark "${targetPlugin}".`);
110
+ seenMarkTargets.set(targetPlugin, owner);
111
+ markEncoders.delete(targetKey);
112
+ markDropped.delete(targetKey);
113
+ if (hasEncode) {
114
+ assertAllowedFields(owner, "mark", declaration, MARK_ENCODE_FIELDS);
115
+ markDropped.delete(targetKey);
116
+ markEncoders.set(targetKey, {
117
+ encode: declaration.encode,
118
+ key: targetKey,
119
+ owner,
120
+ plugin: targetPlugin,
121
+ schema
122
+ });
123
+ } else {
124
+ assertAllowedFields(owner, "mark", declaration, MARK_DROPPED_FIELDS);
125
+ markEncoders.delete(targetKey);
126
+ markDropped.set(targetKey, {
127
+ dropped: declaration.dropped,
128
+ key: targetKey,
129
+ plugin: targetPlugin
130
+ });
131
+ }
132
+ continue;
133
+ }
134
+ if (!isElementPropertyMapping) throw new Error(`DOCX node mapping "${owner}" must target an element type, text mark, or element property.`);
135
+ if (declaration.property !== void 0 && typeof declaration.property !== "string") throw new Error(`DOCX node mapping "${owner}" property must be a string.`);
136
+ const property = typeof declaration.property === "string" ? declaration.property : targetKey;
137
+ if (!property || !ownedPropertyKeys.includes(property)) throw new Error(`DOCX node mapping "${owner}" must name an element property owned by "${targetPlugin}".`);
138
+ const propertyKey = `${targetPlugin}:${property}`;
139
+ const prior = seenPropertyTargets.get(propertyKey);
140
+ if (prior && prior !== owner) throw new Error(`DOCX node mappings "${prior}" and "${owner}" both target property "${property}" of "${targetPlugin}".`);
141
+ seenPropertyTargets.set(propertyKey, owner);
142
+ if (hasEncode) {
143
+ assertAllowedFields(owner, "property", declaration, PROPERTY_ENCODE_FIELDS);
144
+ const droppedIndex = propertyDropped.findIndex((entry) => entry.plugin === targetPlugin && entry.property === property);
145
+ if (droppedIndex !== -1) propertyDropped.splice(droppedIndex, 1);
146
+ const list = propertyEncoders.get(property) ?? [];
147
+ const existingIndex = list.findIndex((entry) => entry.plugin === targetPlugin);
148
+ const nextEntry = {
149
+ encode: declaration.encode,
150
+ owner,
151
+ plugin: targetPlugin,
152
+ property,
153
+ schema
154
+ };
155
+ if (existingIndex === -1) list.push(nextEntry);
156
+ else list[existingIndex] = nextEntry;
157
+ propertyEncoders.set(property, list);
158
+ } else {
159
+ assertAllowedFields(owner, "property", declaration, PROPERTY_DROPPED_FIELDS);
160
+ const list = propertyEncoders.get(property);
161
+ if (list) {
162
+ const existingIndex = list.findIndex((entry) => entry.plugin === targetPlugin);
163
+ if (existingIndex !== -1) {
164
+ list.splice(existingIndex, 1);
165
+ if (list.length === 0) propertyEncoders.delete(property);
166
+ }
167
+ }
168
+ const droppedIndex = propertyDropped.findIndex((entry) => entry.plugin === targetPlugin && entry.property === property);
169
+ const nextDropped = {
170
+ dropped: declaration.dropped,
171
+ plugin: targetPlugin,
172
+ property
173
+ };
174
+ if (droppedIndex === -1) propertyDropped.push(nextDropped);
175
+ else propertyDropped[droppedIndex] = nextDropped;
176
+ }
177
+ }
178
+ const schemaMarks = /* @__PURE__ */ new Map();
179
+ const runtime = getPlateRuntime(runtimeOwner);
180
+ for (const binding of model.bindings) {
181
+ if (binding.kind !== "mark" || !binding.propertyKey) continue;
182
+ if (runtime.plugins[binding.name]?.enabled === false) continue;
183
+ schemaMarks.set(binding.propertyKey, binding.name);
184
+ }
185
+ const compiled = Object.freeze({
186
+ elementEncoders,
187
+ elementTextFormats,
188
+ markDropped,
189
+ markEncoders,
190
+ propertyDropped,
191
+ propertyEncoders,
192
+ schemaMarks
193
+ });
194
+ DOCX_FORMATS_CACHE.set(model.revision, compiled);
195
+ return compiled;
196
+ };
197
+ const resolveSyntaxStyle = (className, syntax) => {
198
+ if (!syntax) return void 0;
199
+ const rawTokens = className.split(/\s+/u).map((token) => token.trim()).filter((token) => token.length > 0);
200
+ if (rawTokens.length === 0) return void 0;
201
+ const stripped = rawTokens.map((token) => token.startsWith("hljs-") ? token.slice(5) : token);
202
+ const candidates = [];
203
+ if (stripped.length > 1) {
204
+ candidates.push(stripped.join("."));
205
+ candidates.push(rawTokens.join("."));
206
+ for (let i = 0; i < stripped.length - 1; i += 1) candidates.push(`${stripped[i]}.${stripped[i + 1]}`);
207
+ }
208
+ for (let i = stripped.length - 1; i >= 0; i -= 1) {
209
+ candidates.push(stripped[i]);
210
+ if (rawTokens[i] !== stripped[i]) candidates.push(rawTokens[i]);
211
+ }
212
+ for (const key of candidates) {
213
+ const style = syntax[key];
214
+ if (style) return style;
215
+ }
216
+ };
217
+ const listItemOf = (listInstalled, ordinal, element, list) => {
218
+ if (!listInstalled) return void 0;
219
+ const listElement = element;
220
+ const base = {
221
+ level: Math.max(0, (listElement.indent ?? 1) - 1),
222
+ levels: listElement.listLevels,
223
+ list
224
+ };
225
+ switch (listElement.listType) {
226
+ case "bulleted": return {
227
+ ...base,
228
+ marker: {
229
+ kind: "bulleted",
230
+ style: listElement.listStyle ?? "disc"
231
+ }
232
+ };
233
+ case "numbered": return {
234
+ ...base,
235
+ marker: {
236
+ kind: "numbered",
237
+ number: ordinal(),
238
+ restart: listElement.listRestart !== void 0,
239
+ style: listElement.listStyle ?? "decimal"
240
+ }
241
+ };
242
+ case "task": return {
243
+ ...base,
244
+ marker: {
245
+ checked: listElement.checked === true,
246
+ kind: "task"
247
+ }
248
+ };
249
+ default: return;
250
+ }
251
+ };
252
+ const mergeMarks = (base, extra) => {
253
+ if (!base) return extra;
254
+ if (!extra) return base;
255
+ return {
256
+ ...base,
257
+ ...extra
258
+ };
259
+ };
260
+ const mergeBlockProps = (target, extra) => {
261
+ if (!extra) return target;
262
+ return {
263
+ ...target,
264
+ ...extra.align !== void 0 ? { align: extra.align } : {},
265
+ ...extra.indentPx !== void 0 ? { indentPx: extra.indentPx } : {},
266
+ ...extra.lineHeight !== void 0 ? { lineHeight: extra.lineHeight } : {}
267
+ };
268
+ };
269
+ const mergeInlineMarks = (inlines, marks) => inlines.map((inline) => {
270
+ if (inline.kind === "text") return {
271
+ ...inline,
272
+ marks: mergeMarks(marks, inline.marks)
273
+ };
274
+ if (inline.kind === "link") return {
275
+ ...inline,
276
+ children: mergeInlineMarks(inline.children, marks)
277
+ };
278
+ return inline;
279
+ });
280
+ const attachReviewRunToInlines = (inlines, reviewRun) => inlines.map((inline) => {
281
+ if (inline.kind === "text" || inline.kind === "inlineEquation" || inline.kind === "lineBreak" || inline.kind === "inlineImage" || inline.kind === "footnoteReference" || inline.kind === "wordField" || inline.kind === "mention") return inline.reviewRun ? inline : {
282
+ ...inline,
283
+ reviewRun
284
+ };
285
+ if (inline.kind === "link") return {
286
+ ...inline,
287
+ children: attachReviewRunToInlines(inline.children, reviewRun)
288
+ };
289
+ return inline;
290
+ });
291
+ const indexStoryTree = (nodes, root, parentPath, nodeLocations, childrenLocations) => {
292
+ childrenLocations.set(nodes, {
293
+ parentPath,
294
+ root
295
+ });
296
+ nodes.forEach((node, index) => {
297
+ const path = [...parentPath, index];
298
+ nodeLocations.set(node, {
299
+ path,
300
+ root
301
+ });
302
+ if (ElementApi.isElement(node)) indexStoryTree(node.children, root, path, nodeLocations, childrenLocations);
303
+ });
304
+ };
305
+ const compileStorySync = (editor, storyDocument, storyName, formats, styles, review, diagnostics, detachedSchema, storyRootKey = MAIN_ROOT_KEY, sharedOrderCounter = { value: 0 }) => {
306
+ const nodeLocations = /* @__PURE__ */ new WeakMap();
307
+ const childrenLocations = /* @__PURE__ */ new WeakMap();
308
+ indexStoryTree(storyDocument.children, storyRootKey, [], nodeLocations, childrenLocations);
309
+ if (storyDocument.roots) for (const [rootKey, rootNodes] of Object.entries(storyDocument.roots)) indexStoryTree(rootNodes, rootKey, [], nodeLocations, childrenLocations);
310
+ const runtime = getPlateRuntime(editor);
311
+ const compiledModel = getCompiledPlateModel(editor);
312
+ const listInstalled = runtime.plugins[BaseListPlugin.name] !== void 0 && runtime.plugins[BaseListPlugin.name].enabled !== false;
313
+ const storyRuntime = (() => {
314
+ const operationKey = {};
315
+ if (detachedSchema) {
316
+ const storySchema = createDetachedEditorSchema(detachedSchema, storyDocument);
317
+ const getOperationContext = createPluginFormatOperationContext(editor, compiledModel, runtime.pluginList);
318
+ const formatContextCache = /* @__PURE__ */ new Map();
319
+ return {
320
+ decorations: () => [],
321
+ key: (_root, target) => {
322
+ const loc = nodeLocations.get(target);
323
+ return loc ? `${storyName}:${loc.root}:${loc.path.join(".")}` : void 0;
324
+ },
325
+ listOrdinal: (root, element) => getDocumentListOrdinal(storyDocument, root, element) ?? 1,
326
+ readFormatContext: (_root, ownerName) => {
327
+ const cached = formatContextCache.get(ownerName);
328
+ if (cached) return cached;
329
+ const ownerPlugin = runtime.plugins[ownerName];
330
+ if (!ownerPlugin) throw new Error(`DOCX format owner "${ownerName}" is not installed.`);
331
+ const resolved = withEditorDocumentProjection(editor, storyDocument, () => editor.read((state) => getOperationContext(ownerPlugin, Object.freeze({
332
+ ...state,
333
+ schema: storySchema,
334
+ value: () => storyDocument
335
+ }), operationKey)));
336
+ formatContextCache.set(ownerName, resolved);
337
+ return resolved;
338
+ },
339
+ readPlugin: () => void 0,
340
+ runInRoot: (_root, fn) => fn(),
341
+ schema: storySchema
342
+ };
343
+ }
344
+ const baseView = projectEditorView(getPlateRuntimeOwner(editor), { document: storyDocument });
345
+ const rootViews = /* @__PURE__ */ new Map([[MAIN_ROOT_KEY, baseView]]);
346
+ const getRootView = (root) => {
347
+ let view = rootViews.get(root);
348
+ if (!view) {
349
+ view = projectEditorView(baseView, { root });
350
+ rootViews.set(root, view);
351
+ }
352
+ return view;
353
+ };
354
+ const decorationSources = getPlateDecorationSources(baseView);
355
+ const getOperationContext = createPluginFormatOperationContext(baseView, getCompiledPlateModel(baseView), runtime.pluginList);
356
+ const formatContextCache = /* @__PURE__ */ new Map();
357
+ return {
358
+ decorations: (root, node, path) => {
359
+ if (decorationSources.length === 0 || !styles?.codeBlock?.syntax) return [];
360
+ const view = getRootView(root);
361
+ const result = [];
362
+ for (const source of decorationSources) {
363
+ const output = source.read({
364
+ editor: view,
365
+ entry: [node, path]
366
+ });
367
+ for (const decoration of output) {
368
+ const className = typeof decoration.attributes?.className === "string" ? decoration.attributes.className : void 0;
369
+ if (!className) continue;
370
+ const range = getReaderRange(decoration.range, root);
371
+ if (!range) continue;
372
+ const [start, end] = RangeApi.edges(range);
373
+ if (start.path.join(",") === end.path.join(",") && end.offset > start.offset) result.push({
374
+ className,
375
+ end: end.offset,
376
+ pathKey: start.path.join(","),
377
+ start: start.offset
378
+ });
379
+ }
380
+ }
381
+ return result;
382
+ },
383
+ key: (root, target) => {
384
+ const loc = nodeLocations.get(target);
385
+ const keyView = getRootView(loc?.root ?? root);
386
+ try {
387
+ return withDocumentViewRead(keyView, () => keyView.read((state) => {
388
+ try {
389
+ return state.key(target);
390
+ } catch {
391
+ const viewNode = loc ? state.nodes.get(loc.path)?.[0] : void 0;
392
+ return ElementApi.isElement(viewNode) ? state.key(viewNode) : void 0;
393
+ }
394
+ }));
395
+ } catch {
396
+ return loc ? `${storyName}:${loc.root}:${loc.path.join(".")}` : void 0;
397
+ }
398
+ },
399
+ listOrdinal: (root, _element, path) => {
400
+ const view = getRootView(root);
401
+ return withDocumentViewRead(view, () => view.plugin(BaseListPlugin).read.ordinal(path) ?? 1);
402
+ },
403
+ readFormatContext: (root, ownerName) => {
404
+ const view = getRootView(root);
405
+ let byOwner = formatContextCache.get(view);
406
+ if (!byOwner) {
407
+ byOwner = /* @__PURE__ */ new Map();
408
+ formatContextCache.set(view, byOwner);
409
+ }
410
+ const cached = byOwner.get(ownerName);
411
+ if (cached) return cached;
412
+ const ownerPlugin = runtime.plugins[ownerName];
413
+ if (!ownerPlugin) throw new Error(`DOCX format owner "${ownerName}" is not installed.`);
414
+ const resolved = withDocumentViewRead(view, () => view.read((state) => getOperationContext(ownerPlugin, state, operationKey)));
415
+ byOwner.set(ownerName, resolved);
416
+ return resolved;
417
+ },
418
+ readPlugin: (root, target) => {
419
+ if (!target) return void 0;
420
+ const view = getRootView(root);
421
+ return withDocumentViewRead(view, () => {
422
+ const handle = view.plugin(target);
423
+ return handle.installed ? handle.read : void 0;
424
+ });
425
+ },
426
+ runInRoot: (root, fn) => withDocumentViewRead(getRootView(root), fn),
427
+ schema: baseView.read.schema
428
+ };
429
+ })();
430
+ const occurrenceCounter = /* @__PURE__ */ new Map();
431
+ const textSpans = [];
432
+ const renderedRoots = /* @__PURE__ */ new Set();
433
+ const reportedMissingMarks = /* @__PURE__ */ new Set();
434
+ const droppedTextCounts = /* @__PURE__ */ new Map();
435
+ const droppedMarkCounts = /* @__PURE__ */ new Map();
436
+ const droppedPropertyCounts = /* @__PURE__ */ new Map();
437
+ const mainBlockRecords = /* @__PURE__ */ new Map();
438
+ const bumpDropped = (map, key, plugin, dropped) => {
439
+ const existing = map.get(key);
440
+ if (existing) existing.count += 1;
441
+ else map.set(key, {
442
+ count: 1,
443
+ dropped,
444
+ plugin
445
+ });
446
+ };
447
+ const nextOccurrence = (root) => {
448
+ const current = (occurrenceCounter.get(root) ?? 0) + 1;
449
+ occurrenceCounter.set(root, current);
450
+ return current;
451
+ };
452
+ const readFormatContext = (root, ownerName) => storyRuntime.readFormatContext(root, ownerName);
453
+ const readBlockDecorations = (root, node, path) => storyRuntime.decorations(root, node, path);
454
+ const resolveTextLeafMarks = (textNode, root, path, silent = false) => {
455
+ const marks = {};
456
+ for (const [key, value] of Object.entries(textNode)) {
457
+ if (key === "text" || key === "authored") continue;
458
+ if (value === void 0 || value === false) continue;
459
+ const markEncoder = formats.markEncoders.get(key);
460
+ if (markEncoder) {
461
+ const formatContext = readFormatContext(root, markEncoder.owner);
462
+ const encoded = markEncoder.encode({
463
+ ...formatContext,
464
+ node: textNode,
465
+ report: silent ? () => {} : (input) => pushFormatDiagnostic(input, root, path),
466
+ value
467
+ });
468
+ if (encoded) Object.assign(marks, encoded);
469
+ continue;
470
+ }
471
+ if (silent) continue;
472
+ const droppedMark = formats.markDropped.get(key);
473
+ if (droppedMark) {
474
+ bumpDropped(droppedMarkCounts, key, droppedMark.plugin, droppedMark.dropped);
475
+ continue;
476
+ }
477
+ const ownerPlugin = formats.schemaMarks.get(key);
478
+ if (ownerPlugin && !reportedMissingMarks.has(`${storyName}:${ownerPlugin}`)) {
479
+ reportedMissingMarks.add(`${storyName}:${ownerPlugin}`);
480
+ diagnostics.push(docxUnsupportedContent({
481
+ action: "dropped",
482
+ feature: ownerPlugin,
483
+ impact: "lossy",
484
+ message: `Plugin "${ownerPlugin}" has no DOCX mark mapping, so its formatting was dropped.`,
485
+ path,
486
+ root
487
+ }));
488
+ }
489
+ }
490
+ return Object.keys(marks).length > 0 ? marks : void 0;
491
+ };
492
+ const compileTextLeaf = (textNode, root, path, occurrence, decorations, rootsUsed) => {
493
+ rootsUsed.add(root);
494
+ const pathKey = path.join(",");
495
+ sharedOrderCounter.value += 1;
496
+ const order = sharedOrderCounter.value;
497
+ const provenance = {
498
+ length: textNode.text.length,
499
+ occurrence,
500
+ order,
501
+ path,
502
+ pathKey,
503
+ root
504
+ };
505
+ const resolvedMarks = resolveTextLeafMarks(textNode, root, path);
506
+ const reviewRun = review?.runsByTarget.get(reviewTargetKey(root, "text", path));
507
+ const previousMarks = reviewRun?.format ? resolveTextLeafMarks({
508
+ ...textNode,
509
+ ...reviewRun.format.previous
510
+ }, root, path, true) : void 0;
511
+ const leafDecorations = decorations.filter((d) => d.pathKey === pathKey);
512
+ if (leafDecorations.length === 0 || textNode.text.length === 0) return [{
513
+ kind: "text",
514
+ ...resolvedMarks ? { marks: resolvedMarks } : {},
515
+ ...previousMarks ? { previousMarks } : {},
516
+ provenance,
517
+ ...reviewRun ? { reviewRun } : {},
518
+ sliceEnd: textNode.text.length,
519
+ sliceStart: 0,
520
+ text: textNode.text
521
+ }];
522
+ const boundaries = /* @__PURE__ */ new Set([0, textNode.text.length]);
523
+ for (const decoration of leafDecorations) {
524
+ boundaries.add(Math.max(0, Math.min(textNode.text.length, decoration.start)));
525
+ boundaries.add(Math.max(0, Math.min(textNode.text.length, decoration.end)));
526
+ }
527
+ const sorted = [...boundaries].sort((a, b) => a - b);
528
+ const runs = [];
529
+ for (let i = 0; i < sorted.length - 1; i += 1) {
530
+ const start = sorted[i];
531
+ const end = sorted[i + 1];
532
+ if (start === end) continue;
533
+ let lookMarks;
534
+ for (const decoration of leafDecorations) if (decoration.start < end && decoration.end > start) {
535
+ const matched = resolveSyntaxStyle(decoration.className, styles?.codeBlock?.syntax);
536
+ if (matched) lookMarks = lookMarks ? {
537
+ ...lookMarks,
538
+ ...matched
539
+ } : matched;
540
+ }
541
+ runs.push({
542
+ kind: "text",
543
+ ...lookMarks ? { lookMarks } : {},
544
+ ...resolvedMarks ? { marks: resolvedMarks } : {},
545
+ ...previousMarks ? { previousMarks } : {},
546
+ provenance,
547
+ ...reviewRun ? { reviewRun } : {},
548
+ sliceEnd: end,
549
+ sliceStart: start,
550
+ text: textNode.text.slice(start, end)
551
+ });
552
+ }
553
+ return runs;
554
+ };
555
+ const pushFormatDiagnostic = (input, root, path) => {
556
+ switch (input.code) {
557
+ case "lossy-content":
558
+ diagnostics.push(docxLossyContent({
559
+ feature: input.feature,
560
+ message: input.message,
561
+ path,
562
+ root
563
+ }));
564
+ break;
565
+ case "property-dropped": {
566
+ const feature = input.feature ?? "property";
567
+ const key = `${feature}\0${input.message}`;
568
+ const existing = droppedTextCounts.get(key);
569
+ if (existing) existing.count += 1;
570
+ else droppedTextCounts.set(key, {
571
+ count: 1,
572
+ dropped: input.message,
573
+ plugin: feature
574
+ });
575
+ break;
576
+ }
577
+ case "resource-omitted":
578
+ diagnostics.push(docxResourceOmitted({
579
+ feature: input.feature,
580
+ impact: input.impact ?? "lossy",
581
+ message: input.message,
582
+ path,
583
+ root
584
+ }));
585
+ break;
586
+ case "unsupported-content":
587
+ diagnostics.push(docxUnsupportedContent({
588
+ action: input.action ?? "dropped",
589
+ feature: input.feature,
590
+ impact: input.impact ?? "lossy",
591
+ message: input.message,
592
+ path,
593
+ root
594
+ }));
595
+ break;
596
+ }
597
+ };
598
+ const collectElementProperties = (element, root, path) => {
599
+ let props = {};
600
+ for (const [property, encoders] of formats.propertyEncoders) {
601
+ const value = element[property];
602
+ if (value === void 0 || value === false) continue;
603
+ for (const entry of encoders) {
604
+ const formatContext = readFormatContext(root, entry.owner);
605
+ const encoded = entry.encode({
606
+ ...formatContext,
607
+ key: property,
608
+ node: element,
609
+ report: (input) => pushFormatDiagnostic(input, root, path),
610
+ value
611
+ });
612
+ props = mergeBlockProps(props, encoded);
613
+ }
614
+ }
615
+ for (const dropped of formats.propertyDropped) {
616
+ const value = element[dropped.property];
617
+ if (value !== void 0 && value !== false) bumpDropped(droppedPropertyCounts, `${dropped.plugin}:${dropped.property}`, dropped.plugin, dropped.dropped);
618
+ }
619
+ return props;
620
+ };
621
+ const lowerInlines = (items, rootsUsed, inheritedMarks) => {
622
+ const out = [];
623
+ for (const item of items) {
624
+ const fragment = readFragment(item);
625
+ if (fragment) {
626
+ for (const r of fragment.rootsUsed) rootsUsed.add(r);
627
+ if (fragment.kind === "inlines") out.push(...inheritedMarks ? mergeInlineMarks(fragment.inlines, inheritedMarks) : fragment.inlines);
628
+ else for (const block of fragment.blocks) if (block.kind === "paragraph") out.push(...inheritedMarks ? mergeInlineMarks(block.children, inheritedMarks) : block.children);
629
+ continue;
630
+ }
631
+ const inline = item;
632
+ switch (inline.kind) {
633
+ case "text": {
634
+ const merged = mergeMarks(inheritedMarks, inline.marks);
635
+ out.push({
636
+ kind: "text",
637
+ ...merged ? { marks: merged } : {},
638
+ ...inline.placeholder !== void 0 ? { placeholder: inline.placeholder } : {},
639
+ text: inline.text
640
+ });
641
+ break;
642
+ }
643
+ case "link":
644
+ out.push({
645
+ children: lowerInlines(inline.children, rootsUsed, inheritedMarks),
646
+ kind: "link",
647
+ url: inline.url
648
+ });
649
+ break;
650
+ case "inlineEquation":
651
+ out.push({
652
+ kind: "inlineEquation",
653
+ latex: inline.latex
654
+ });
655
+ break;
656
+ case "lineBreak":
657
+ out.push({ kind: "lineBreak" });
658
+ break;
659
+ case "inlineImage":
660
+ out.push({
661
+ ...inline.alt !== void 0 ? { alt: inline.alt } : {},
662
+ ...inline.heightPx !== void 0 ? { heightPx: inline.heightPx } : {},
663
+ kind: "inlineImage",
664
+ url: inline.url,
665
+ ...inline.widthPx !== void 0 ? { widthPx: inline.widthPx } : {}
666
+ });
667
+ break;
668
+ case "inlineGroup":
669
+ out.push(...lowerInlines(inline.children, rootsUsed, mergeMarks(inheritedMarks, inline.marks)));
670
+ break;
671
+ case "footnoteReference":
672
+ out.push({
673
+ kind: "footnoteReference",
674
+ ref: inline.ref
675
+ });
676
+ break;
677
+ case "wordField":
678
+ if (!isAllowedDynamicWordFieldInstruction(inline.instruction)) {
679
+ diagnostics.push(docxUnsupportedContent({
680
+ action: "replaced",
681
+ feature: "field-instruction",
682
+ impact: "lossy",
683
+ message: `DOCX export omitted unsupported Word field instruction "${inline.instruction}" and kept its cached text.`
684
+ }));
685
+ const fallbackText = inline.text ?? "";
686
+ if (fallbackText.length > 0) out.push({
687
+ kind: "text",
688
+ marks: inheritedMarks,
689
+ text: fallbackText
690
+ });
691
+ break;
692
+ }
693
+ out.push({
694
+ instruction: inline.instruction,
695
+ kind: "wordField",
696
+ text: inline.text ?? ""
697
+ });
698
+ break;
699
+ case "mention":
700
+ out.push({
701
+ kind: "mention",
702
+ ...inline.label !== void 0 ? { label: inline.label } : {},
703
+ ref: inline.ref
704
+ });
705
+ break;
706
+ }
707
+ }
708
+ return out;
709
+ };
710
+ const lowerBlocks = (items, rootsUsed, defaultRoot) => {
711
+ const out = [];
712
+ for (const item of items) {
713
+ const fragment = readFragment(item);
714
+ if (fragment) {
715
+ for (const r of fragment.rootsUsed) rootsUsed.add(r);
716
+ if (fragment.kind === "blocks") out.push(...fragment.blocks);
717
+ else if (fragment.inlines.length > 0) out.push({
718
+ children: fragment.inlines,
719
+ kind: "paragraph",
720
+ roots: new Set(fragment.rootsUsed)
721
+ });
722
+ continue;
723
+ }
724
+ const block = item;
725
+ const blockRoots = /* @__PURE__ */ new Set([defaultRoot]);
726
+ switch (block.kind) {
727
+ case "paragraph": {
728
+ const children = lowerInlines(block.children, blockRoots);
729
+ for (const r of blockRoots) rootsUsed.add(r);
730
+ out.push({
731
+ ...block.align !== void 0 ? { align: block.align } : {},
732
+ ...block.bookmark !== void 0 ? { bookmark: block.bookmark } : {},
733
+ children,
734
+ ...block.codeLanguage !== void 0 ? { codeLanguage: block.codeLanguage } : {},
735
+ ...block.indentPx !== void 0 ? { indentPx: block.indentPx } : {},
736
+ ...block.isCodeBlock ? { isCodeBlock: true } : {},
737
+ kind: "paragraph",
738
+ ...block.lineHeight !== void 0 ? { lineHeight: block.lineHeight } : {},
739
+ ...block.preserveWhitespace ? { preserveWhitespace: true } : {},
740
+ roots: blockRoots,
741
+ ...block.style !== void 0 ? { style: block.style } : {}
742
+ });
743
+ break;
744
+ }
745
+ case "callout": {
746
+ const bodyBlocks = lowerBlocks(block.children, blockRoots, defaultRoot);
747
+ const icon = block.icon?.trim();
748
+ const bodyCell = {
749
+ ...block.backgroundColor ? { backgroundColor: block.backgroundColor } : {},
750
+ children: bodyBlocks.length > 0 ? bodyBlocks : [{
751
+ children: [],
752
+ kind: "paragraph",
753
+ roots: /* @__PURE__ */ new Set([defaultRoot])
754
+ }]
755
+ };
756
+ for (const r of blockRoots) rootsUsed.add(r);
757
+ out.push({
758
+ borders: "none",
759
+ ...block.variant ? { calloutVariant: block.variant } : {},
760
+ columnWidthsPx: icon ? [30, 594] : [624],
761
+ isCallout: true,
762
+ kind: "table",
763
+ roots: blockRoots,
764
+ rows: [{ cells: icon ? [{
765
+ ...block.backgroundColor ? { backgroundColor: block.backgroundColor } : {},
766
+ children: [{
767
+ children: [{
768
+ kind: "text",
769
+ text: icon
770
+ }],
771
+ kind: "paragraph",
772
+ roots: /* @__PURE__ */ new Set([defaultRoot])
773
+ }],
774
+ isCalloutIcon: true,
775
+ widthPx: 30
776
+ }, bodyCell] : [bodyCell] }]
777
+ });
778
+ break;
779
+ }
780
+ case "table": {
781
+ const rows = block.rows.map((row) => ({
782
+ cells: row.cells.map((cell) => {
783
+ const cellRoots = /* @__PURE__ */ new Set([defaultRoot]);
784
+ const cellChildren = lowerBlocks(cell.children, cellRoots, defaultRoot);
785
+ for (const r of cellRoots) blockRoots.add(r);
786
+ return {
787
+ ...cell.backgroundColor !== void 0 ? { backgroundColor: cell.backgroundColor } : {},
788
+ ...cell.borders !== void 0 ? { borders: cell.borders } : {},
789
+ children: cellChildren,
790
+ ...cell.colSpan !== void 0 ? { colSpan: cell.colSpan } : {},
791
+ ...cell.header ? { header: true } : {},
792
+ ...cell.rowSpan !== void 0 ? { rowSpan: cell.rowSpan } : {},
793
+ ...cell.verticalAlign !== void 0 ? { verticalAlign: cell.verticalAlign } : {},
794
+ ...cell.widthPct !== void 0 ? { widthPct: cell.widthPct } : {},
795
+ ...cell.widthPx !== void 0 ? { widthPx: cell.widthPx } : {}
796
+ };
797
+ }),
798
+ ...row.header ? { header: true } : {},
799
+ ...row.minHeightPx !== void 0 ? { minHeightPx: row.minHeightPx } : {}
800
+ }));
801
+ for (const r of blockRoots) rootsUsed.add(r);
802
+ out.push({
803
+ ...block.borders !== void 0 ? { borders: block.borders } : {},
804
+ ...block.columnWidthsPx !== void 0 ? { columnWidthsPx: block.columnWidthsPx } : {},
805
+ kind: "table",
806
+ ...block.marginLeftPx !== void 0 ? { marginLeftPx: block.marginLeftPx } : {},
807
+ roots: blockRoots,
808
+ rows
809
+ });
810
+ break;
811
+ }
812
+ case "blockImage": {
813
+ const caption = block.caption ? lowerInlines(block.caption, blockRoots) : void 0;
814
+ for (const r of blockRoots) rootsUsed.add(r);
815
+ out.push({
816
+ ...block.alt !== void 0 ? { alt: block.alt } : {},
817
+ ...caption ? { caption } : {},
818
+ ...block.heightPx !== void 0 ? { heightPx: block.heightPx } : {},
819
+ kind: "blockImage",
820
+ roots: blockRoots,
821
+ url: block.url,
822
+ ...block.widthPx !== void 0 ? { widthPx: block.widthPx } : {}
823
+ });
824
+ break;
825
+ }
826
+ case "blockEquation":
827
+ for (const r of blockRoots) rootsUsed.add(r);
828
+ out.push({
829
+ kind: "blockEquation",
830
+ latex: block.latex,
831
+ roots: blockRoots
832
+ });
833
+ break;
834
+ case "horizontalRule":
835
+ for (const r of blockRoots) rootsUsed.add(r);
836
+ out.push({
837
+ kind: "horizontalRule",
838
+ roots: blockRoots
839
+ });
840
+ break;
841
+ case "pageBreak":
842
+ for (const r of blockRoots) rootsUsed.add(r);
843
+ out.push({
844
+ kind: "pageBreak",
845
+ roots: blockRoots
846
+ });
847
+ break;
848
+ case "blockquote": {
849
+ const children = lowerBlocks(block.children, blockRoots, defaultRoot);
850
+ for (const r of blockRoots) rootsUsed.add(r);
851
+ out.push({
852
+ children,
853
+ kind: "blockquote",
854
+ roots: blockRoots
855
+ });
856
+ break;
857
+ }
858
+ case "group": {
859
+ const children = lowerBlocks(block.children, blockRoots, defaultRoot);
860
+ for (const r of blockRoots) rootsUsed.add(r);
861
+ out.push(...children);
862
+ break;
863
+ }
864
+ case "footnoteDefinition": {
865
+ const children = lowerBlocks(block.children, blockRoots, defaultRoot);
866
+ for (const r of blockRoots) rootsUsed.add(r);
867
+ out.push({
868
+ children,
869
+ kind: "footnoteDefinition",
870
+ ref: block.ref,
871
+ roots: blockRoots
872
+ });
873
+ break;
874
+ }
875
+ case "toc": {
876
+ const children = lowerBlocks(block.children, blockRoots, defaultRoot);
877
+ for (const r of blockRoots) rootsUsed.add(r);
878
+ out.push({
879
+ children,
880
+ kind: "toc",
881
+ roots: blockRoots
882
+ });
883
+ break;
884
+ }
885
+ }
886
+ }
887
+ return out;
888
+ };
889
+ const applyElementBlockProps = (blocks, props, listItem, structureRevision, previousListItem, previousStyle, previousProps, paragraphBreakRevision) => {
890
+ for (const block of blocks) if (block.kind === "paragraph") {
891
+ if (props.align !== void 0 && block.align === void 0) block.align = props.align;
892
+ if (props.indentPx !== void 0 && block.indentPx === void 0) block.indentPx = props.indentPx;
893
+ if (props.lineHeight !== void 0 && block.lineHeight === void 0) block.lineHeight = props.lineHeight;
894
+ if (structureRevision && !block.structureRevision) {
895
+ block.structureRevision = structureRevision;
896
+ if (previousListItem) block.previousListItem = previousListItem;
897
+ if (previousStyle) block.previousStyle = previousStyle;
898
+ if (previousProps?.align !== void 0) block.previousAlign = previousProps.align;
899
+ if (previousProps?.indentPx !== void 0) block.previousIndentPx = previousProps.indentPx;
900
+ if (previousProps?.lineHeight !== void 0) block.previousLineHeight = previousProps.lineHeight;
901
+ }
902
+ } else if (block.kind === "blockquote" || block.kind === "toc") applyElementBlockProps(block.children, props, void 0, structureRevision, void 0, previousStyle, previousProps);
903
+ if (paragraphBreakRevision && blocks.length > 0) {
904
+ const last = blocks.at(-1);
905
+ if (last?.kind === "paragraph") last.paragraphBreakRevision = paragraphBreakRevision;
906
+ else if (last?.kind === "blockquote" && last.children.length > 0) {
907
+ const lastInner = last.children.at(-1);
908
+ if (lastInner?.kind === "paragraph") lastInner.paragraphBreakRevision = paragraphBreakRevision;
909
+ }
910
+ }
911
+ if (listItem && blocks.length > 0) {
912
+ blocks[0].listItem = listItem;
913
+ const isCheckedTask = listItem.marker.kind === "task" && listItem.marker.checked;
914
+ if (blocks.length > 1) for (let i = 1; i < blocks.length; i += 1) {
915
+ const b = blocks[i];
916
+ if (isCheckedTask) b.isCheckedTaskContinuation = true;
917
+ if (b.kind === "paragraph" && b.indentPx === void 0) b.indentPx = (listItem.level + 1) * 24;
918
+ }
919
+ }
920
+ };
921
+ const voidCoveredReviewRuns = /* @__PURE__ */ new Set();
922
+ const coverVoidBlockReviewRuns = (element, root, path) => {
923
+ if (!review) return;
924
+ const visit = (nodes, parentPath) => {
925
+ nodes.forEach((child, index) => {
926
+ const childPath = [...parentPath, index];
927
+ if (ElementApi.isElement(child)) visit(child.children, childPath);
928
+ else {
929
+ const run = review.runsByTarget.get(reviewTargetKey(root, "text", childPath));
930
+ if (run) voidCoveredReviewRuns.add(run);
931
+ }
932
+ });
933
+ };
934
+ visit(element.children, path);
935
+ };
936
+ const compileVoidTextAnchors = (element, root, path, occurrence, rootsUsed) => {
937
+ const anchors = [];
938
+ const visit = (nodes, parentPath) => {
939
+ nodes.forEach((child, index) => {
940
+ const childPath = [...parentPath, index];
941
+ if (ElementApi.isElement(child)) visit(child.children, childPath);
942
+ else {
943
+ rootsUsed.add(root);
944
+ sharedOrderCounter.value += 1;
945
+ const order = sharedOrderCounter.value;
946
+ anchors.push({
947
+ kind: "voidAnchor",
948
+ provenance: {
949
+ length: child.text.length,
950
+ occurrence,
951
+ order,
952
+ path: childPath,
953
+ pathKey: childPath.join(","),
954
+ root
955
+ }
956
+ });
957
+ }
958
+ });
959
+ };
960
+ visit(element.children, path);
961
+ return anchors;
962
+ };
963
+ const createEncodeContext = (element, root, path, occurrence, rootStack, encoder, decorations) => {
964
+ const readSchema = storyRuntime.schema;
965
+ const resolveChildrenLocation = (children) => {
966
+ const targetNodes = children ?? element.children;
967
+ const loc = childrenLocations.get(targetNodes);
968
+ if (loc) {
969
+ const targetRoot = loc.root;
970
+ const isNewRoot = targetRoot !== root;
971
+ return {
972
+ nodes: targetNodes,
973
+ occ: isNewRoot ? nextOccurrence(targetRoot) : occurrence,
974
+ parentPath: loc.parentPath,
975
+ root: targetRoot,
976
+ stack: isNewRoot ? [...rootStack, targetRoot] : rootStack
977
+ };
978
+ }
979
+ if (targetNodes.length > 0) {
980
+ const firstLoc = nodeLocations.get(targetNodes[0]);
981
+ if (firstLoc) {
982
+ const targetRoot = firstLoc.root;
983
+ const isNewRoot = targetRoot !== root;
984
+ return {
985
+ nodes: targetNodes,
986
+ occ: isNewRoot ? nextOccurrence(targetRoot) : occurrence,
987
+ parentPath: firstLoc.path.slice(0, -1),
988
+ root: targetRoot,
989
+ stack: isNewRoot ? [...rootStack, targetRoot] : rootStack
990
+ };
991
+ }
992
+ }
993
+ return {
994
+ nodes: targetNodes,
995
+ occ: occurrence,
996
+ parentPath: path,
997
+ root,
998
+ stack: rootStack
999
+ };
1000
+ };
1001
+ const formatContext = readFormatContext(root, encoder.owner);
1002
+ const modelView = createPluginFormatModelView(storyDocument, element, path, root);
1003
+ return {
1004
+ ...formatContext,
1005
+ ...modelView,
1006
+ contentRoot: (slot) => {
1007
+ const targetRoot = readSchema.getElementContentRoots(element)[slot];
1008
+ if (!targetRoot) throw new Error(`Element "${element.type}" does not own content root slot "${slot}".`);
1009
+ if (rootStack.includes(targetRoot)) throw new Error(`Content root "${targetRoot}" cannot recursively render itself.`);
1010
+ const rootNodes = readNamedRootChildren(storyDocument.roots, targetRoot);
1011
+ if (!rootNodes) return [];
1012
+ if (!childrenLocations.has(rootNodes)) indexStoryTree(rootNodes, targetRoot, [], nodeLocations, childrenLocations);
1013
+ return rootNodes;
1014
+ },
1015
+ encodeBlocks: (children) => {
1016
+ const resolved = resolveChildrenLocation(children);
1017
+ const rootsUsed = /* @__PURE__ */ new Set();
1018
+ const blocks = compileBlockList(resolved.nodes, resolved.root, resolved.parentPath, resolved.occ, resolved.stack, rootsUsed);
1019
+ return blocks.length > 0 ? [createFragment({
1020
+ blocks,
1021
+ kind: "blocks",
1022
+ rootsUsed
1023
+ })] : [];
1024
+ },
1025
+ encodeInlines: (children) => {
1026
+ const resolved = resolveChildrenLocation(children);
1027
+ const rootsUsed = /* @__PURE__ */ new Set();
1028
+ const inlines = compileInlineList(resolved.nodes, resolved.root, resolved.parentPath, resolved.occ, resolved.stack, decorations, rootsUsed);
1029
+ return inlines.length > 0 ? [createFragment({
1030
+ inlines,
1031
+ kind: "inlines",
1032
+ rootsUsed
1033
+ })] : [];
1034
+ },
1035
+ key: (target) => storyRuntime.key(root, target ?? element),
1036
+ node: element,
1037
+ readPlugin: ((plugin) => storyRuntime.readPlugin(root, plugin ?? runtime.plugins[encoder.plugin])),
1038
+ report: (input) => pushFormatDiagnostic(input, root, path)
1039
+ };
1040
+ };
1041
+ const compileInlineElement = (element, root, path, occurrence, rootStack, decorations, rootsUsed) => {
1042
+ rootsUsed.add(root);
1043
+ const readSchema = storyRuntime.schema;
1044
+ const isVoid = readSchema.isVoid(element);
1045
+ const reviewRun = isVoid ? review?.runsByTarget.get(reviewTargetKey(root, "element", path)) : void 0;
1046
+ const voidAnchors = isVoid ? compileVoidTextAnchors(element, root, path, occurrence, rootsUsed) : [];
1047
+ const textFormat = formats.elementTextFormats.get(element.type);
1048
+ if (textFormat) {
1049
+ bumpDropped(droppedTextCounts, element.type, textFormat.plugin, textFormat.dropped);
1050
+ const renderedText = textFormat.text({ node: element });
1051
+ const voidMarks = readSchema.isMarkableVoid(element) && element.children.length === 1 && TextApi.isText(element.children[0]) ? resolveTextLeafMarks(element.children[0], root, [...path, 0]) : void 0;
1052
+ const base = [...voidAnchors, ...renderedText ? [{
1053
+ kind: "text",
1054
+ ...voidMarks ? { marks: voidMarks } : {},
1055
+ text: renderedText
1056
+ }] : []];
1057
+ return reviewRun ? attachReviewRunToInlines(base, reviewRun) : base;
1058
+ }
1059
+ const encoder = formats.elementEncoders.get(element.type);
1060
+ if (encoder) {
1061
+ if (isVoid) coverVoidBlockReviewRuns(element, root, path);
1062
+ const ctx = createEncodeContext(element, root, path, occurrence, rootStack, encoder, decorations);
1063
+ const rawResult = storyRuntime.runInRoot(root, () => encoder.encode(ctx));
1064
+ if (rawResult === null || rawResult === void 0) return voidAnchors;
1065
+ const list = Array.isArray(rawResult) ? rawResult : [rawResult];
1066
+ const voidMarks = readSchema.isMarkableVoid(element) && element.children.length === 1 && TextApi.isText(element.children[0]) ? resolveTextLeafMarks(element.children[0], root, [...path, 0]) : void 0;
1067
+ const lowered = lowerInlines(list, rootsUsed, voidMarks);
1068
+ const inlineTargetKey = reviewTargetKey(root, "element", path);
1069
+ const inlineStructureRev = !isVoid ? review?.structuresByTarget.get(inlineTargetKey) : void 0;
1070
+ if (inlineStructureRev && review) {
1071
+ const structureKind = review.structureKindByTarget.get(inlineTargetKey);
1072
+ const structurePrev = review.structurePreviousByTarget.get(inlineTargetKey);
1073
+ for (const item of lowered) {
1074
+ if (item.kind !== "link") continue;
1075
+ if (structureKind === "wrap" || structureKind === "unwrap") item.linkRevision = {
1076
+ kind: structureKind,
1077
+ revision: inlineStructureRev
1078
+ };
1079
+ else if (typeof structurePrev?.url === "string" && structurePrev.url !== item.url) item.linkRevision = {
1080
+ kind: "urlChange",
1081
+ previousUrl: structurePrev.url,
1082
+ revision: inlineStructureRev
1083
+ };
1084
+ }
1085
+ }
1086
+ if (reviewRun?.format?.previous) {
1087
+ const prevLatex = reviewRun.format.previous.latex;
1088
+ if (typeof prevLatex === "string") {
1089
+ for (const item of lowered) if (item.kind === "inlineEquation" && prevLatex !== item.latex) item.previousLatex = prevLatex;
1090
+ }
1091
+ }
1092
+ const combined = [...voidAnchors, ...lowered];
1093
+ return reviewRun ? attachReviewRunToInlines(combined, reviewRun) : combined;
1094
+ }
1095
+ diagnostics.push(docxUnsupportedContent({
1096
+ action: isVoid ? "dropped" : "unwrapped",
1097
+ feature: element.type,
1098
+ impact: "lossy",
1099
+ message: `Element "${element.type}" has no DOCX mapping, so it was ${isVoid ? "dropped" : "unwrapped"}.`,
1100
+ path,
1101
+ root
1102
+ }));
1103
+ if (isVoid) return voidAnchors;
1104
+ return compileInlineList(element.children, root, path, occurrence, rootStack, decorations, rootsUsed);
1105
+ };
1106
+ const compileInlineList = (nodes, root, parentPath, occurrence, rootStack, decorations, rootsUsed) => {
1107
+ const out = [];
1108
+ nodes.forEach((child, index) => {
1109
+ const loc = nodeLocations.get(child);
1110
+ const childPath = loc && loc.root === root ? loc.path : [...parentPath, index];
1111
+ if (ElementApi.isElement(child)) out.push(...compileInlineElement(child, root, childPath, occurrence, rootStack, decorations, rootsUsed));
1112
+ else out.push(...compileTextLeaf(child, root, childPath, occurrence, decorations, rootsUsed));
1113
+ });
1114
+ return out;
1115
+ };
1116
+ const compileBlockElement = (element, root, path, occurrence, rootStack, rootsUsed) => {
1117
+ rootsUsed.add(root);
1118
+ const readSchema = storyRuntime.schema;
1119
+ const isVoid = readSchema.isVoid(element);
1120
+ const blockProps = collectElementProperties(element, root, path);
1121
+ const listItem = listItemOf(listInstalled, () => storyRuntime.listOrdinal(root, element, path), element, {
1122
+ id: typeof element.listId === "string" ? element.listId : "",
1123
+ root,
1124
+ story: storyName
1125
+ });
1126
+ const elementTargetKey = reviewTargetKey(root, "element", path);
1127
+ const structureRevision = review?.structuresByTarget.get(elementTargetKey);
1128
+ const structureKind = review?.structureKindByTarget.get(elementTargetKey);
1129
+ const structurePrevious = structureRevision && review ? review.structurePreviousByTarget.get(elementTargetKey) : void 0;
1130
+ const paragraphBreakRevision = review?.paragraphBreakByTarget.get(elementTargetKey);
1131
+ let previousListItem;
1132
+ let previousStyle;
1133
+ let previousProps;
1134
+ if (structurePrevious) {
1135
+ const prevRecord = { ...element };
1136
+ for (const [key, value] of Object.entries(structurePrevious)) if (value === void 0) delete prevRecord[key];
1137
+ else prevRecord[key] = value;
1138
+ const prevElement = prevRecord;
1139
+ previousProps = collectElementProperties(prevElement, root, path);
1140
+ previousListItem = listItemOf(listInstalled, () => storyRuntime.listOrdinal(root, element, path), prevElement, {
1141
+ id: typeof prevElement.listId === "string" ? prevElement.listId : "",
1142
+ root,
1143
+ story: storyName
1144
+ });
1145
+ if (structureKind === "wrap" && element.type === "blockquote") previousStyle = "Normal";
1146
+ else if (prevElement.type === "heading" && typeof prevElement.level === "number" && prevElement.level >= 1 && prevElement.level <= 6) previousStyle = `Heading${prevElement.level}`;
1147
+ else if (prevElement.type === "blockquote") previousStyle = "Quote";
1148
+ else if (prevElement.type === "codeBlock") previousStyle = "HTMLPreformatted";
1149
+ else previousStyle = "Normal";
1150
+ }
1151
+ const blockDecorations = readBlockDecorations(root, element, path);
1152
+ const textFormat = formats.elementTextFormats.get(element.type);
1153
+ if (textFormat) {
1154
+ bumpDropped(droppedTextCounts, element.type, textFormat.plugin, textFormat.dropped);
1155
+ const voidAnchors = isVoid ? compileVoidTextAnchors(element, root, path, occurrence, rootsUsed) : [];
1156
+ const renderedText = textFormat.text({ node: element });
1157
+ const blocks = [{
1158
+ children: [...voidAnchors, ...renderedText ? [{
1159
+ kind: "text",
1160
+ text: renderedText
1161
+ }] : []],
1162
+ kind: "paragraph",
1163
+ roots: /* @__PURE__ */ new Set([root])
1164
+ }];
1165
+ applyElementBlockProps(blocks, blockProps, listItem, structureRevision);
1166
+ return blocks;
1167
+ }
1168
+ const encoder = formats.elementEncoders.get(element.type);
1169
+ if (encoder) {
1170
+ if (isVoid) coverVoidBlockReviewRuns(element, root, path);
1171
+ const ctx = createEncodeContext(element, root, path, occurrence, rootStack, encoder, blockDecorations);
1172
+ const rawResult = storyRuntime.runInRoot(root, () => encoder.encode(ctx));
1173
+ if (rawResult === null || rawResult === void 0) return [];
1174
+ const blocks = lowerBlocks(Array.isArray(rawResult) ? rawResult : [rawResult], rootsUsed, root);
1175
+ const firstBlock = blocks[0];
1176
+ const isCaptionlessBlockImage = !isVoid && blocks.length === 1 && firstBlock?.kind === "blockImage" && !firstBlock.caption;
1177
+ if (blocks.length === 1 && review && firstBlock?.kind === "paragraph") {
1178
+ const elementRun = review.runsByTarget.get(elementTargetKey);
1179
+ if (elementRun) firstBlock.reviewRun = elementRun;
1180
+ }
1181
+ if (blocks.length === 1 && review && firstBlock?.kind === "table") {
1182
+ const gridRev = review.tableGridRevisionByTarget.get(elementTargetKey);
1183
+ if (gridRev) firstBlock.gridRevision = gridRev;
1184
+ const tablePropRev = review.tablePropertyRevisionByTarget.get(elementTargetKey);
1185
+ if (tablePropRev) firstBlock.propertyRevision = tablePropRev;
1186
+ firstBlock.rows.forEach((row, rowIndex) => {
1187
+ const rowKey = reviewTargetKey(root, "element", [...path, rowIndex]);
1188
+ const rowRev = review.rowRevisionsByTarget.get(rowKey);
1189
+ if (rowRev) row.rowRevision = rowRev;
1190
+ const rowPropRev = review.rowPropertyRevisionByTarget.get(rowKey);
1191
+ if (rowPropRev) row.propertyRevision = rowPropRev;
1192
+ row.cells.forEach((cell, cellIndex) => {
1193
+ const cellKey = reviewTargetKey(root, "element", [
1194
+ ...path,
1195
+ rowIndex,
1196
+ cellIndex
1197
+ ]);
1198
+ const cellRev = review.cellRevisionsByTarget.get(cellKey);
1199
+ if (cellRev) cell.cellRevision = cellRev;
1200
+ const cellPropRev = review.cellPropertyRevisionByTarget.get(cellKey);
1201
+ if (cellPropRev) cell.propertyRevision = cellPropRev;
1202
+ });
1203
+ });
1204
+ }
1205
+ if (blocks.length === 1 && review && (firstBlock?.kind === "blockImage" || isVoid && (firstBlock?.kind === "horizontalRule" || firstBlock?.kind === "blockEquation" || firstBlock?.kind === "pageBreak" || firstBlock?.kind === "toc"))) {
1206
+ const voidRun = review.runsByTarget.get(elementTargetKey) ?? (isCaptionlessBlockImage || isVoid ? review.runsByTarget.get(reviewTargetKey(root, "text", [...path, 0])) : void 0);
1207
+ if (voidRun) {
1208
+ if (isCaptionlessBlockImage || isVoid) coverVoidBlockReviewRuns(element, root, path);
1209
+ firstBlock.reviewRun = voidRun;
1210
+ }
1211
+ if (structureRevision) {
1212
+ if (firstBlock.kind === "blockImage") {
1213
+ firstBlock.structureRevision = structureRevision;
1214
+ if (typeof structurePrevious?.url === "string" && structurePrevious.url !== firstBlock.url) firstBlock.previousUrl = structurePrevious.url;
1215
+ if (typeof structurePrevious?.width === "number" && structurePrevious.width !== firstBlock.widthPx) firstBlock.previousWidthPx = structurePrevious.width;
1216
+ const prevNaturalWidth = typeof structurePrevious?.naturalWidth === "number" ? structurePrevious.naturalWidth : typeof element.naturalWidth === "number" ? element.naturalWidth : void 0;
1217
+ const prevNaturalHeight = typeof structurePrevious?.naturalHeight === "number" ? structurePrevious.naturalHeight : typeof element.naturalHeight === "number" ? element.naturalHeight : void 0;
1218
+ if (typeof structurePrevious?.height === "number" && structurePrevious.height !== firstBlock.heightPx) firstBlock.previousHeightPx = structurePrevious.height;
1219
+ else if (firstBlock.previousWidthPx !== void 0 && prevNaturalWidth && prevNaturalHeight) firstBlock.previousHeightPx = Math.round(firstBlock.previousWidthPx / prevNaturalWidth * prevNaturalHeight);
1220
+ } else if (firstBlock.kind === "blockEquation") {
1221
+ firstBlock.structureRevision = structureRevision;
1222
+ if (typeof structurePrevious?.latex === "string" && structurePrevious.latex !== firstBlock.latex) firstBlock.previousLatex = structurePrevious.latex;
1223
+ }
1224
+ }
1225
+ }
1226
+ if ((isVoid || isCaptionlessBlockImage) && blocks.length > 0) {
1227
+ const voidAnchors = compileVoidTextAnchors(element, root, path, occurrence, rootsUsed);
1228
+ if (voidAnchors.length > 0) if (blocks[0].kind === "paragraph") blocks[0].children.unshift(...voidAnchors);
1229
+ else blocks[0].voidAnchors = [...blocks[0].voidAnchors ?? [], ...voidAnchors];
1230
+ }
1231
+ applyElementBlockProps(blocks, blockProps, listItem, structureRevision, previousListItem, previousStyle, previousProps, paragraphBreakRevision);
1232
+ return blocks;
1233
+ }
1234
+ diagnostics.push(docxUnsupportedContent({
1235
+ action: isVoid ? "dropped" : "unwrapped",
1236
+ feature: element.type,
1237
+ impact: "lossy",
1238
+ message: `Element "${element.type}" has no DOCX mapping, so it was ${isVoid ? "dropped" : "unwrapped"}.`,
1239
+ path,
1240
+ root
1241
+ }));
1242
+ if (isVoid) return [];
1243
+ if (element.children.some((child) => ElementApi.isElement(child) && !readSchema.isInline(child))) {
1244
+ const blocks = compileBlockList(element.children, root, path, occurrence, rootStack, rootsUsed);
1245
+ applyElementBlockProps(blocks, blockProps, listItem, structureRevision);
1246
+ return blocks;
1247
+ }
1248
+ const blocks = [{
1249
+ children: compileInlineList(element.children, root, path, occurrence, rootStack, blockDecorations, rootsUsed),
1250
+ kind: "paragraph",
1251
+ roots: /* @__PURE__ */ new Set([root])
1252
+ }];
1253
+ applyElementBlockProps(blocks, blockProps, listItem, structureRevision);
1254
+ return blocks;
1255
+ };
1256
+ const compileBlockList = (nodes, root, parentPath, occurrence, rootStack, rootsUsed) => {
1257
+ const out = [];
1258
+ nodes.forEach((child, index) => {
1259
+ const loc = nodeLocations.get(child);
1260
+ const childPath = loc && loc.root === root ? loc.path : [...parentPath, index];
1261
+ if (ElementApi.isElement(child)) {
1262
+ const compiled = compileBlockElement(child, root, childPath, occurrence, rootStack, rootsUsed);
1263
+ for (const block of compiled) {
1264
+ if (block.sourcePath === void 0) {
1265
+ block.sourcePath = childPath;
1266
+ block.sourceRoot = root;
1267
+ }
1268
+ if (root === MAIN_ROOT_KEY && parentPath.length === 0 && block.mainBlockIndex === void 0) block.mainBlockIndex = childPath[0];
1269
+ }
1270
+ out.push(...compiled);
1271
+ } else {
1272
+ const inlines = compileTextLeaf(child, root, childPath, occurrence, [], rootsUsed);
1273
+ if (inlines.length > 0) out.push({
1274
+ children: inlines,
1275
+ kind: "paragraph",
1276
+ roots: /* @__PURE__ */ new Set([root])
1277
+ });
1278
+ }
1279
+ });
1280
+ return out;
1281
+ };
1282
+ const mainOccurrence = nextOccurrence(MAIN_ROOT_KEY);
1283
+ const rawBlocks = compileBlockList(storyDocument.children, MAIN_ROOT_KEY, [], mainOccurrence, [MAIN_ROOT_KEY], /* @__PURE__ */ new Set());
1284
+ const extractedFootnotes = storyName === "body" ? extractMainStoryFootnotes(rawBlocks, diagnostics) : {
1285
+ blocks: rawBlocks,
1286
+ footnotes: []
1287
+ };
1288
+ const { blocks } = extractedFootnotes;
1289
+ const emittedReviewRuns = /* @__PURE__ */ new Set();
1290
+ const recordFootnoteReviewRuns = (items) => {
1291
+ const walkInlines = (inlines) => {
1292
+ for (const inline of inlines) if ((inline.kind === "text" || inline.kind === "inlineEquation" || inline.kind === "lineBreak" || inline.kind === "inlineImage" || inline.kind === "footnoteReference" || inline.kind === "wordField" || inline.kind === "mention") && inline.reviewRun) emittedReviewRuns.add(inline.reviewRun);
1293
+ else if (inline.kind === "link") walkInlines(inline.children);
1294
+ };
1295
+ for (const block of items) {
1296
+ for (const r of block.roots) if (r !== MAIN_ROOT_KEY) renderedRoots.add(r);
1297
+ if (block.kind === "paragraph") walkInlines(block.children);
1298
+ else if (block.kind === "blockImage" && block.caption) walkInlines(block.caption);
1299
+ else if (block.kind === "blockquote" || block.kind === "toc") recordFootnoteReviewRuns(block.children);
1300
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) recordFootnoteReviewRuns(cell.children);
1301
+ }
1302
+ };
1303
+ for (const fn of extractedFootnotes.footnotes) recordFootnoteReviewRuns(fn.blocks);
1304
+ const collectEmitted = (blockList, enclosingMainBlock, containerRoots) => {
1305
+ for (const block of blockList) {
1306
+ if (block.kind === "footnoteDefinition") {
1307
+ for (const r of block.roots) if (r !== MAIN_ROOT_KEY) renderedRoots.add(r);
1308
+ recordFootnoteReviewRuns(block.children);
1309
+ continue;
1310
+ }
1311
+ const activeMain = block.mainBlockIndex ?? enclosingMainBlock;
1312
+ const mergedRoots = /* @__PURE__ */ new Set([...containerRoots, ...block.roots]);
1313
+ for (const r of block.roots) if (r !== MAIN_ROOT_KEY) renderedRoots.add(r);
1314
+ if (activeMain !== void 0) {
1315
+ let record = mainBlockRecords.get(activeMain);
1316
+ if (!record) {
1317
+ record = {
1318
+ count: 0,
1319
+ duplicateTextPath: false,
1320
+ hasForeignRoot: false,
1321
+ hasSiblingMainBlock: false,
1322
+ seenTextPaths: /* @__PURE__ */ new Set()
1323
+ };
1324
+ mainBlockRecords.set(activeMain, record);
1325
+ }
1326
+ if (enclosingMainBlock === void 0) {
1327
+ record.count += 1;
1328
+ record.firstBlock ??= block;
1329
+ record.lastBlock = block;
1330
+ }
1331
+ for (const r of block.roots) if (r !== MAIN_ROOT_KEY) record.hasForeignRoot = true;
1332
+ if (block.mainBlockIndex !== void 0 && enclosingMainBlock !== void 0 && block.mainBlockIndex !== enclosingMainBlock) record.hasSiblingMainBlock = true;
1333
+ }
1334
+ const recordInlines = (inlines) => {
1335
+ for (const inline of inlines) {
1336
+ if ((inline.kind === "text" || inline.kind === "inlineEquation" || inline.kind === "lineBreak" || inline.kind === "inlineImage" || inline.kind === "footnoteReference" || inline.kind === "wordField" || inline.kind === "mention") && inline.reviewRun) emittedReviewRuns.add(inline.reviewRun);
1337
+ if (inline.kind === "text" && inline.provenance) {
1338
+ const p = inline.provenance;
1339
+ if (p.root !== MAIN_ROOT_KEY) renderedRoots.add(p.root);
1340
+ if (textSpans.at(-1)?.root !== p.root || textSpans.at(-1)?.pathKey !== p.pathKey || textSpans.at(-1)?.occurrence !== p.occurrence) {
1341
+ textSpans.push({
1342
+ containerRoots: mergedRoots,
1343
+ length: p.length,
1344
+ occurrence: p.occurrence,
1345
+ order: p.order,
1346
+ path: p.path,
1347
+ pathKey: p.pathKey,
1348
+ root: p.root
1349
+ });
1350
+ if (activeMain !== void 0 && p.root === MAIN_ROOT_KEY) {
1351
+ const record = mainBlockRecords.get(activeMain);
1352
+ if (record) {
1353
+ if (record.seenTextPaths.has(p.pathKey)) record.duplicateTextPath = true;
1354
+ else record.seenTextPaths.add(p.pathKey);
1355
+ const blockOfPath = p.path[0];
1356
+ if (blockOfPath !== void 0 && blockOfPath !== activeMain) record.hasSiblingMainBlock = true;
1357
+ }
1358
+ } else if (activeMain !== void 0 && p.root !== MAIN_ROOT_KEY) {
1359
+ const record = mainBlockRecords.get(activeMain);
1360
+ if (record) record.hasForeignRoot = true;
1361
+ }
1362
+ }
1363
+ } else if (inline.kind === "voidAnchor") {
1364
+ const p = inline.provenance;
1365
+ if (p.root !== MAIN_ROOT_KEY) renderedRoots.add(p.root);
1366
+ textSpans.push({
1367
+ containerRoots: mergedRoots,
1368
+ length: p.length,
1369
+ occurrence: p.occurrence,
1370
+ order: p.order,
1371
+ path: p.path,
1372
+ pathKey: p.pathKey,
1373
+ root: p.root
1374
+ });
1375
+ } else if (inline.kind === "link") recordInlines(inline.children);
1376
+ }
1377
+ };
1378
+ if (block.voidAnchors?.length) recordInlines(block.voidAnchors);
1379
+ if (block.kind === "paragraph") recordInlines(block.children);
1380
+ else if (block.kind === "blockImage" && block.caption) recordInlines(block.caption);
1381
+ else if (block.kind === "blockquote" || block.kind === "toc") collectEmitted(block.children, activeMain, mergedRoots);
1382
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) collectEmitted(cell.children, activeMain, mergedRoots);
1383
+ }
1384
+ };
1385
+ collectEmitted(blocks, void 0, /* @__PURE__ */ new Set());
1386
+ if (review) for (const entry of review.runs) {
1387
+ if (entry.root !== storyRootKey && !renderedRoots.has(entry.root)) continue;
1388
+ if (!emittedReviewRuns.has(entry.run) && !voidCoveredReviewRuns.has(entry.run)) diagnostics.push(docxUnsupportedContent({
1389
+ action: "dropped",
1390
+ feature: "review-text-wrapper",
1391
+ impact: "lossy",
1392
+ message: "A review run could not be attached because its custom DOCX encoder omitted text provenance.",
1393
+ path: entry.path,
1394
+ root: entry.root
1395
+ }));
1396
+ }
1397
+ for (const entry of droppedTextCounts.values()) diagnostics.push(docxPropertyDropped({
1398
+ count: entry.count,
1399
+ feature: entry.plugin,
1400
+ message: entry.dropped
1401
+ }));
1402
+ for (const entry of droppedMarkCounts.values()) diagnostics.push(docxPropertyDropped({
1403
+ count: entry.count,
1404
+ feature: entry.plugin,
1405
+ message: entry.dropped
1406
+ }));
1407
+ for (const entry of droppedPropertyCounts.values()) diagnostics.push(docxPropertyDropped({
1408
+ count: entry.count,
1409
+ feature: entry.plugin,
1410
+ message: entry.dropped
1411
+ }));
1412
+ return {
1413
+ blocks,
1414
+ diagnostics,
1415
+ footnotes: extractedFootnotes.footnotes,
1416
+ mainBlockRecords,
1417
+ renderedRoots,
1418
+ textSpans
1419
+ };
1420
+ };
1421
+ const spanKey = (root, pathKey, occurrence) => `${root}\0${pathKey}\0${occurrence}`;
1422
+ const anchorCommentsOnAst = (blocks, textSpans, comments, diagnostics) => {
1423
+ if (comments.length === 0) return [];
1424
+ const spansByRootAndPath = /* @__PURE__ */ new Map();
1425
+ for (const span of textSpans) {
1426
+ const key = `${span.root}\0${span.pathKey}`;
1427
+ const list = spansByRootAndPath.get(key) ?? [];
1428
+ list.push(span);
1429
+ spansByRootAndPath.set(key, list);
1430
+ }
1431
+ const hasUnownedSpanBetween = (startSpan, endSpan, root) => {
1432
+ if (root === MAIN_ROOT_KEY) return false;
1433
+ for (const span of textSpans) if (span.order > startSpan.order && span.order < endSpan.order && span.root !== root) return true;
1434
+ return false;
1435
+ };
1436
+ const resolveEndpoints = (start, end) => {
1437
+ const startRoot = start.root ?? MAIN_ROOT_KEY;
1438
+ const endRoot = end.root ?? MAIN_ROOT_KEY;
1439
+ const startPath = start.path.join(",");
1440
+ const endPath = end.path.join(",");
1441
+ const startSpans = spansByRootAndPath.get(`${startRoot}\0${startPath}`) ?? [];
1442
+ if (startSpans.length === 0) return null;
1443
+ if (startRoot === endRoot && startPath === endPath) return [startSpans[0], startSpans[0]];
1444
+ const endSpans = spansByRootAndPath.get(`${endRoot}\0${endPath}`) ?? [];
1445
+ for (const startSpan of startSpans) {
1446
+ const endSpan = endSpans.find((candidate) => candidate.occurrence === startSpan.occurrence && candidate.order > startSpan.order && !hasUnownedSpanBetween(startSpan, candidate, startRoot));
1447
+ if (endSpan) return [startSpan, endSpan];
1448
+ }
1449
+ return null;
1450
+ };
1451
+ const markersBySpan = /* @__PURE__ */ new Map();
1452
+ const groupAt = (span, offset) => {
1453
+ const key = spanKey(span.root, span.pathKey, span.occurrence);
1454
+ let byOffset = markersBySpan.get(key);
1455
+ if (!byOffset) {
1456
+ byOffset = /* @__PURE__ */ new Map();
1457
+ markersBySpan.set(key, byOffset);
1458
+ }
1459
+ let group = byOffset.get(offset);
1460
+ if (!group) {
1461
+ group = {
1462
+ collapsed: [],
1463
+ ends: [],
1464
+ starts: []
1465
+ };
1466
+ byOffset.set(offset, group);
1467
+ }
1468
+ return group;
1469
+ };
1470
+ const prepared = [];
1471
+ for (const comment of comments) {
1472
+ if (!comment.target) {
1473
+ diagnostics.push(docxLossyContent({
1474
+ feature: "comment-range",
1475
+ message: `Comment ${comment.id} has no exportable range.`,
1476
+ sourceId: comment.id
1477
+ }));
1478
+ continue;
1479
+ }
1480
+ const start = RangeApi.start(comment.target.range);
1481
+ const end = RangeApi.end(comment.target.range);
1482
+ const endpoints = resolveEndpoints(start, end);
1483
+ if (!endpoints) {
1484
+ diagnostics.push(docxLossyContent({
1485
+ feature: "comment-range",
1486
+ message: `Comment ${comment.id} addresses content outside the selected DOCX projection.`,
1487
+ sourceId: comment.id
1488
+ }));
1489
+ continue;
1490
+ }
1491
+ const [startSpan, endSpan] = endpoints;
1492
+ const validStart = Number.isSafeInteger(start.offset) && start.offset >= 0 && start.offset <= startSpan.length;
1493
+ const validEnd = Number.isSafeInteger(end.offset) && end.offset >= 0 && end.offset <= endSpan.length;
1494
+ if (!validStart || !validEnd || startSpan === endSpan && start.offset > end.offset) {
1495
+ diagnostics.push(docxLossyContent({
1496
+ feature: "comment-range",
1497
+ message: `Comment ${comment.id} has an invalid text offset.`,
1498
+ sourceId: comment.id
1499
+ }));
1500
+ continue;
1501
+ }
1502
+ const id = prepared.length;
1503
+ const paragraphId = (id + 1).toString(16).toUpperCase().padStart(8, "0");
1504
+ const startMarker = {
1505
+ id,
1506
+ kind: "commentRangeStart"
1507
+ };
1508
+ const endMarker = {
1509
+ id,
1510
+ kind: "commentRangeEnd"
1511
+ };
1512
+ if (startSpan === endSpan && start.offset === end.offset) groupAt(startSpan, start.offset).collapsed.push(startMarker, endMarker);
1513
+ else {
1514
+ groupAt(endSpan, end.offset).ends.push(endMarker);
1515
+ groupAt(startSpan, start.offset).starts.push(startMarker);
1516
+ }
1517
+ prepared.push({
1518
+ comment,
1519
+ id,
1520
+ paragraphId
1521
+ });
1522
+ }
1523
+ if (markersBySpan.size === 0) return prepared;
1524
+ const spliceInlines = (inlines) => {
1525
+ const out = [];
1526
+ for (const inline of inlines) {
1527
+ if (inline.kind === "link") {
1528
+ out.push({
1529
+ ...inline,
1530
+ children: spliceInlines(inline.children)
1531
+ });
1532
+ continue;
1533
+ }
1534
+ if (inline.kind === "voidAnchor") {
1535
+ const key = spanKey(inline.provenance.root, inline.provenance.pathKey, inline.provenance.occurrence);
1536
+ const byOffset = markersBySpan.get(key);
1537
+ if (byOffset) {
1538
+ const group = byOffset.get(0);
1539
+ if (group) {
1540
+ out.push(...group.ends, ...group.collapsed, ...group.starts);
1541
+ byOffset.delete(0);
1542
+ }
1543
+ }
1544
+ continue;
1545
+ }
1546
+ if (inline.kind === "text" && inline.provenance) {
1547
+ const key = spanKey(inline.provenance.root, inline.provenance.pathKey, inline.provenance.occurrence);
1548
+ const byOffset = markersBySpan.get(key);
1549
+ if (!byOffset || byOffset.size === 0) {
1550
+ out.push(inline);
1551
+ continue;
1552
+ }
1553
+ const sliceStart = inline.sliceStart ?? 0;
1554
+ const sliceEnd = inline.sliceEnd ?? inline.text.length;
1555
+ const relevantOffsets = [...byOffset.keys()].filter((offset) => offset >= sliceStart && offset <= sliceEnd).sort((a, b) => a - b);
1556
+ if (relevantOffsets.length === 0) {
1557
+ out.push(inline);
1558
+ continue;
1559
+ }
1560
+ let cursor = sliceStart;
1561
+ for (const offset of relevantOffsets) {
1562
+ if (offset > cursor) {
1563
+ out.push({
1564
+ ...inline,
1565
+ sliceEnd: offset,
1566
+ sliceStart: cursor,
1567
+ text: inline.text.slice(cursor - sliceStart, offset - sliceStart)
1568
+ });
1569
+ cursor = offset;
1570
+ }
1571
+ const group = byOffset.get(offset);
1572
+ if (group) {
1573
+ out.push(...group.ends, ...group.collapsed, ...group.starts);
1574
+ byOffset.delete(offset);
1575
+ }
1576
+ }
1577
+ if (cursor < sliceEnd || sliceStart === sliceEnd && inline.text === "") {
1578
+ const remaining = inline.text.slice(cursor - sliceStart);
1579
+ if (remaining.length > 0 || sliceStart === sliceEnd && inline.text === "") out.push({
1580
+ ...inline,
1581
+ sliceEnd,
1582
+ sliceStart: cursor,
1583
+ text: remaining
1584
+ });
1585
+ }
1586
+ continue;
1587
+ }
1588
+ out.push(inline);
1589
+ }
1590
+ return out;
1591
+ };
1592
+ const spliceBlocks = (list) => {
1593
+ for (const block of list) {
1594
+ if (block.voidAnchors?.length) block.voidAnchors = spliceInlines(block.voidAnchors);
1595
+ if (block.kind === "paragraph") block.children = spliceInlines(block.children);
1596
+ else if (block.kind === "blockImage" && block.caption) block.caption = spliceInlines(block.caption);
1597
+ else if (block.kind === "blockquote" || block.kind === "toc") spliceBlocks(block.children);
1598
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) spliceBlocks(cell.children);
1599
+ }
1600
+ };
1601
+ spliceBlocks(blocks);
1602
+ return prepared;
1603
+ };
1604
+ const stripDroppedKeysFromRecord = (record, droppedKeys) => {
1605
+ const next = {};
1606
+ for (const [key, value] of Object.entries(record)) if (!droppedKeys.has(key)) next[key] = value;
1607
+ return next;
1608
+ };
1609
+ const stripDroppedAuthoredMembers = (authored, droppedKeys) => {
1610
+ const next = [];
1611
+ for (const member of authored) {
1612
+ if (!member || typeof member !== "object" || Array.isArray(member)) {
1613
+ next.push(member);
1614
+ continue;
1615
+ }
1616
+ const record = member;
1617
+ if (record.kind === "format" && typeof record.key === "string" && droppedKeys.has(record.key)) continue;
1618
+ if (record.kind === "as" && record.values && typeof record.values === "object" && !Array.isArray(record.values)) {
1619
+ const values = stripDroppedKeysFromRecord(record.values, droppedKeys);
1620
+ if (Object.keys(values).length > 0) next.push({
1621
+ ...record,
1622
+ values
1623
+ });
1624
+ continue;
1625
+ }
1626
+ if (record.kind === "split") {
1627
+ let updated = record;
1628
+ if (record.kept && typeof record.kept === "object" && !Array.isArray(record.kept)) {
1629
+ const kept = stripDroppedKeysFromRecord(record.kept, droppedKeys);
1630
+ if (Object.keys(kept).length > 0) updated = {
1631
+ ...updated,
1632
+ kept
1633
+ };
1634
+ else {
1635
+ const { kept: _kept, ...rest } = updated;
1636
+ updated = rest;
1637
+ }
1638
+ }
1639
+ if (record.gave && typeof record.gave === "object" && !Array.isArray(record.gave)) {
1640
+ const gave = stripDroppedKeysFromRecord(record.gave, droppedKeys);
1641
+ if (Object.keys(gave).length > 0) updated = {
1642
+ ...updated,
1643
+ gave
1644
+ };
1645
+ else {
1646
+ const { gave: _gave, ...rest } = updated;
1647
+ updated = rest;
1648
+ }
1649
+ }
1650
+ next.push(updated);
1651
+ continue;
1652
+ }
1653
+ if (record.kind === "reserve" && record.node && typeof record.node === "object" && !Array.isArray(record.node)) {
1654
+ next.push({
1655
+ ...record,
1656
+ node: stripDroppedReviewNode(record.node, droppedKeys)
1657
+ });
1658
+ continue;
1659
+ }
1660
+ next.push(member);
1661
+ }
1662
+ return next;
1663
+ };
1664
+ const stripDroppedReviewNode = (node, droppedKeys) => {
1665
+ if (droppedKeys.size === 0) return node;
1666
+ const record = node;
1667
+ const next = {};
1668
+ for (const [key, value] of Object.entries(record)) {
1669
+ if (droppedKeys.has(key)) continue;
1670
+ if (key === "authored" && Array.isArray(value)) {
1671
+ const filtered = stripDroppedAuthoredMembers(value, droppedKeys);
1672
+ if (filtered.length > 0) next.authored = filtered;
1673
+ continue;
1674
+ }
1675
+ if (key === "children" && Array.isArray(value)) {
1676
+ next.children = value.map((child) => stripDroppedReviewNode(child, droppedKeys));
1677
+ continue;
1678
+ }
1679
+ next[key] = value;
1680
+ }
1681
+ return next;
1682
+ };
1683
+ const canonicalReserveJsonKey = (value) => {
1684
+ if (value === null) return "null";
1685
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalReserveJsonKey(item)).join(",")}]`;
1686
+ if (typeof value === "object" && value !== null) {
1687
+ const record = value;
1688
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalReserveJsonKey(record[key])}`).join(",")}}`;
1689
+ }
1690
+ return `${typeof value}:${JSON.stringify(value)}`;
1691
+ };
1692
+ const hashReserveNodeKey = (value) => {
1693
+ let high = 3421674724;
1694
+ let low = 2216829733;
1695
+ for (let index = 0; index < value.length; index++) {
1696
+ low = (low ^ value.charCodeAt(index)) >>> 0;
1697
+ const lowProduct = low * 435;
1698
+ const carry = Math.floor(lowProduct / 4294967296);
1699
+ high = Math.imul(high, 435) + Math.imul(low, 256) + carry >>> 0;
1700
+ low = lowProduct >>> 0;
1701
+ }
1702
+ return `${high.toString(16).padStart(8, "0")}${low.toString(16).padStart(8, "0")}`;
1703
+ };
1704
+ const recomputeBuiltReserveId = (id, node) => {
1705
+ try {
1706
+ const parsed = JSON.parse(id);
1707
+ if (Array.isArray(parsed) && parsed.length === 5 && typeof parsed[4] === "string" && parsed[4].startsWith("b:")) {
1708
+ const next = [...parsed];
1709
+ next[4] = `b:${hashReserveNodeKey(canonicalReserveJsonKey(node))}`;
1710
+ return JSON.stringify(next);
1711
+ }
1712
+ } catch {
1713
+ return id;
1714
+ }
1715
+ return id;
1716
+ };
1717
+ const stripDroppedReviewRecords = (records, droppedKeys) => {
1718
+ if (!records || droppedKeys.size === 0) return records;
1719
+ const reserves = records["authored-reserves"];
1720
+ if (!reserves || typeof reserves !== "object") return records;
1721
+ const nextReserves = {};
1722
+ for (const [id, entry] of Object.entries(reserves)) if (entry && typeof entry === "object" && !Array.isArray(entry) && "node" in entry && entry.node && typeof entry.node === "object" && !Array.isArray(entry.node)) {
1723
+ const strippedNode = stripDroppedReviewNode(entry.node, droppedKeys);
1724
+ const nextId = entry.built === true && canonicalReserveJsonKey(strippedNode) !== canonicalReserveJsonKey(entry.node) ? recomputeBuiltReserveId(id, strippedNode) : id;
1725
+ nextReserves[nextId] = {
1726
+ ...entry,
1727
+ node: strippedNode
1728
+ };
1729
+ } else nextReserves[id] = entry;
1730
+ return {
1731
+ ...records,
1732
+ "authored-reserves": nextReserves
1733
+ };
1734
+ };
1735
+ const attachReviewBindings = (review, mainBlockRecords, diagnostics, droppedKeys) => {
1736
+ if (!review) return [];
1737
+ const bindings = [];
1738
+ for (const blockIndex of review.bound) {
1739
+ const record = mainBlockRecords.get(blockIndex);
1740
+ if (!record || !record.firstBlock || !record.lastBlock) {
1741
+ diagnostics.push(docxLossyContent({
1742
+ feature: "authored-review",
1743
+ message: `The review marks of block ${blockIndex} have no rendered host to bind them to.`,
1744
+ path: [blockIndex]
1745
+ }));
1746
+ continue;
1747
+ }
1748
+ if (record.count > 1 || record.duplicateTextPath || record.hasForeignRoot || record.hasSiblingMainBlock) continue;
1749
+ const name = `_ReviewBlock${bindings.length + 1}`;
1750
+ record.firstBlock.reviewBlockStart = [...record.firstBlock.reviewBlockStart ?? [], name];
1751
+ record.lastBlock.reviewBlockEnd = [...record.lastBlock.reviewBlockEnd ?? [], name];
1752
+ bindings.push({
1753
+ name,
1754
+ nodes: [stripDroppedReviewNode(review.stored.children[blockIndex], droppedKeys)]
1755
+ });
1756
+ }
1757
+ return bindings;
1758
+ };
1759
+ const splitNewlinesInText = (inline) => {
1760
+ const { lookMarks, marks, placeholder, previousMarks, reviewRun, text } = inline;
1761
+ if (!text.includes("\n")) return [{
1762
+ kind: "text",
1763
+ ...lookMarks ? { lookMarks } : {},
1764
+ ...marks ? { marks } : {},
1765
+ ...placeholder !== void 0 ? { placeholder } : {},
1766
+ ...previousMarks ? { previousMarks } : {},
1767
+ ...reviewRun ? { reviewRun } : {},
1768
+ text
1769
+ }];
1770
+ const parts = text.split("\n");
1771
+ const out = [];
1772
+ parts.forEach((part, index) => {
1773
+ if (part.length > 0 || parts.length === 1) out.push({
1774
+ kind: "text",
1775
+ ...lookMarks ? { lookMarks } : {},
1776
+ ...marks ? { marks } : {},
1777
+ ...placeholder !== void 0 ? { placeholder } : {},
1778
+ ...previousMarks ? { previousMarks } : {},
1779
+ ...reviewRun ? { reviewRun } : {},
1780
+ text: part
1781
+ });
1782
+ if (index < parts.length - 1) out.push({
1783
+ kind: "lineBreak",
1784
+ ...reviewRun ? { reviewRun } : {}
1785
+ });
1786
+ });
1787
+ return out;
1788
+ };
1789
+ const hasPlainText = (inlines) => inlines.some((inline) => {
1790
+ if (inline.kind === "text") return inline.text.trim().length > 0;
1791
+ if (inline.kind === "link") return hasPlainText(inline.children);
1792
+ return false;
1793
+ });
1794
+ const resolveInlinesAsync = async (inlines, options, diagnostics) => {
1795
+ const out = [];
1796
+ for (const inline of inlines) {
1797
+ throwIfDocxAborted(options.signal);
1798
+ switch (inline.kind) {
1799
+ case "voidAnchor": break;
1800
+ case "text":
1801
+ out.push(...splitNewlinesInText(inline));
1802
+ break;
1803
+ case "footnoteReference":
1804
+ if (inline.id !== void 0) out.push({
1805
+ id: inline.id,
1806
+ kind: "footnoteReference",
1807
+ ref: inline.ref,
1808
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {}
1809
+ });
1810
+ else {
1811
+ diagnostics.push(docxLossyContent({
1812
+ feature: "footnote",
1813
+ message: `Footnote reference "${inline.ref}" has no matching definition in the document body and was exported as plain text.`
1814
+ }));
1815
+ out.push({
1816
+ kind: "text",
1817
+ marks: { script: "sup" },
1818
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {},
1819
+ text: `[${inline.ref}]`
1820
+ });
1821
+ }
1822
+ break;
1823
+ case "lineBreak":
1824
+ out.push({
1825
+ kind: "lineBreak",
1826
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {}
1827
+ });
1828
+ break;
1829
+ case "wordField":
1830
+ out.push({
1831
+ instruction: inline.instruction,
1832
+ kind: "wordField",
1833
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {},
1834
+ text: inline.text
1835
+ });
1836
+ break;
1837
+ case "mention":
1838
+ out.push({
1839
+ kind: "mention",
1840
+ ...inline.label !== void 0 ? { label: inline.label } : {},
1841
+ ref: inline.ref,
1842
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {}
1843
+ });
1844
+ break;
1845
+ case "commentRangeStart":
1846
+ case "commentRangeEnd":
1847
+ case "bookmarkStart":
1848
+ case "bookmarkEnd":
1849
+ out.push(inline);
1850
+ break;
1851
+ case "link": {
1852
+ const resolvedChildren = await resolveInlinesAsync(inline.children, options, diagnostics);
1853
+ const link = resolveDocxLinkUrl(inline.url);
1854
+ if (link.kind === "unwrapped") {
1855
+ if (link.diagnostic) diagnostics.push(link.diagnostic);
1856
+ out.push(...resolvedChildren);
1857
+ } else {
1858
+ let compiledLinkRev;
1859
+ if (inline.linkRevision) if (inline.linkRevision.kind === "urlChange") {
1860
+ const prevLink = resolveDocxLinkUrl(inline.linkRevision.previousUrl);
1861
+ if (prevLink.kind !== "unwrapped") compiledLinkRev = {
1862
+ kind: "urlChange",
1863
+ previousTarget: prevLink.target,
1864
+ previousTargetKind: prevLink.kind,
1865
+ revision: inline.linkRevision.revision
1866
+ };
1867
+ } else compiledLinkRev = inline.linkRevision;
1868
+ out.push({
1869
+ children: resolvedChildren,
1870
+ kind: "link",
1871
+ ...compiledLinkRev ? { linkRevision: compiledLinkRev } : {},
1872
+ target: link.target,
1873
+ targetKind: link.kind
1874
+ });
1875
+ }
1876
+ break;
1877
+ }
1878
+ case "inlineEquation": {
1879
+ const { omml } = await renderLatexToOmml(inline.latex, "inline");
1880
+ const previousOmml = (inline.previousLatex ? await renderLatexToOmml(inline.previousLatex, "inline") : void 0)?.omml;
1881
+ throwIfDocxAborted(options.signal);
1882
+ out.push({
1883
+ kind: "inlineEquation",
1884
+ latex: inline.latex,
1885
+ omml,
1886
+ ...previousOmml ? { previousOmml } : {},
1887
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {}
1888
+ });
1889
+ break;
1890
+ }
1891
+ case "inlineImage": {
1892
+ const resolution = await resolveDocxImage(inline.url, options);
1893
+ if (resolution.ok) out.push({
1894
+ ...inline.alt !== void 0 ? { alt: inline.alt } : {},
1895
+ ...inline.heightPx !== void 0 ? { heightPx: inline.heightPx } : {},
1896
+ image: resolution.image,
1897
+ kind: "inlineImage",
1898
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {},
1899
+ ...inline.widthPx !== void 0 ? { widthPx: inline.widthPx } : {}
1900
+ });
1901
+ else {
1902
+ const alt = inline.alt?.trim() ?? "";
1903
+ diagnostics.push(docxResourceOmitted({
1904
+ feature: "image",
1905
+ impact: resolution.unsafeScript && alt.length > 0 ? "lossless" : "lossy",
1906
+ message: `An image was omitted because ${resolution.reason}.`
1907
+ }));
1908
+ if (alt.length > 0) out.push({
1909
+ kind: "text",
1910
+ ...inline.reviewRun ? { reviewRun: inline.reviewRun } : {},
1911
+ text: alt
1912
+ });
1913
+ }
1914
+ break;
1915
+ }
1916
+ }
1917
+ }
1918
+ return out;
1919
+ };
1920
+ const resolveBlocksAsync = async (blocks, options, diagnostics) => {
1921
+ const out = [];
1922
+ for (const block of blocks) {
1923
+ throwIfDocxAborted(options.signal);
1924
+ const commentMarkers = block.voidAnchors?.filter((inline) => inline.kind === "commentRangeStart" || inline.kind === "commentRangeEnd");
1925
+ const common = {
1926
+ ...commentMarkers?.length ? { commentMarkers } : {},
1927
+ ...block.isCheckedTaskContinuation ? { isCheckedTaskContinuation: true } : {},
1928
+ ...block.listItem ? { listItem: block.listItem } : {},
1929
+ ...block.mainBlockIndex !== void 0 ? { mainBlockIndex: block.mainBlockIndex } : {},
1930
+ ...block.reviewBlockStart ? { reviewBlockStart: block.reviewBlockStart } : {},
1931
+ ...block.reviewBlockEnd ? { reviewBlockEnd: block.reviewBlockEnd } : {}
1932
+ };
1933
+ switch (block.kind) {
1934
+ case "paragraph": {
1935
+ const children = await resolveInlinesAsync(block.children, options, diagnostics);
1936
+ out.push({
1937
+ ...common,
1938
+ ...block.align !== void 0 ? { align: block.align } : {},
1939
+ ...block.bookmark !== void 0 ? { bookmark: block.bookmark } : {},
1940
+ children,
1941
+ ...block.codeLanguage !== void 0 ? { codeLanguage: block.codeLanguage } : {},
1942
+ ...block.indentPx !== void 0 ? { indentPx: block.indentPx } : {},
1943
+ ...block.isCodeBlock ? { isCodeBlock: true } : {},
1944
+ kind: "paragraph",
1945
+ ...block.lineHeight !== void 0 ? { lineHeight: block.lineHeight } : {},
1946
+ ...block.paragraphBreakRevision ? { paragraphBreakRevision: block.paragraphBreakRevision } : {},
1947
+ ...block.preserveWhitespace ? { preserveWhitespace: true } : {},
1948
+ ...block.previousAlign !== void 0 ? { previousAlign: block.previousAlign } : {},
1949
+ ...block.previousIndentPx !== void 0 ? { previousIndentPx: block.previousIndentPx } : {},
1950
+ ...block.previousLineHeight !== void 0 ? { previousLineHeight: block.previousLineHeight } : {},
1951
+ ...block.previousListItem ? { previousListItem: block.previousListItem } : {},
1952
+ ...block.previousStyle ? { previousStyle: block.previousStyle } : {},
1953
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {},
1954
+ ...block.structureRevision ? { structureRevision: block.structureRevision } : {},
1955
+ ...block.style !== void 0 ? { style: block.style } : {}
1956
+ });
1957
+ break;
1958
+ }
1959
+ case "horizontalRule":
1960
+ out.push({
1961
+ ...common,
1962
+ kind: "horizontalRule",
1963
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {}
1964
+ });
1965
+ break;
1966
+ case "pageBreak":
1967
+ out.push({
1968
+ ...common,
1969
+ kind: "pageBreak",
1970
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {}
1971
+ });
1972
+ break;
1973
+ case "blockquote": {
1974
+ const children = await resolveBlocksAsync(block.children, options, diagnostics);
1975
+ out.push({
1976
+ ...common,
1977
+ children,
1978
+ kind: "blockquote"
1979
+ });
1980
+ break;
1981
+ }
1982
+ case "toc": {
1983
+ const children = await resolveBlocksAsync(block.children, options, diagnostics);
1984
+ out.push({
1985
+ ...common,
1986
+ children,
1987
+ kind: "toc",
1988
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {}
1989
+ });
1990
+ break;
1991
+ }
1992
+ case "footnoteDefinition": {
1993
+ diagnostics.push(docxLossyContent({
1994
+ feature: "footnote",
1995
+ message: `Unreferenced footnote definition "${block.ref}" was flattened into body paragraphs.`
1996
+ }));
1997
+ const children = await resolveBlocksAsync(block.children, options, diagnostics);
1998
+ out.push({
1999
+ ...common,
2000
+ children: [{
2001
+ kind: "text",
2002
+ text: block.ref
2003
+ }],
2004
+ kind: "paragraph"
2005
+ }, ...children);
2006
+ break;
2007
+ }
2008
+ case "blockEquation": {
2009
+ const { omml } = await renderLatexToOmml(block.latex, "block");
2010
+ const previousOmml = (block.previousLatex ? await renderLatexToOmml(block.previousLatex, "block") : void 0)?.omml;
2011
+ throwIfDocxAborted(options.signal);
2012
+ out.push({
2013
+ ...common,
2014
+ kind: "blockEquation",
2015
+ latex: block.latex,
2016
+ omml,
2017
+ ...previousOmml ? { previousOmml } : {},
2018
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {},
2019
+ ...block.structureRevision ? { structureRevision: block.structureRevision } : {}
2020
+ });
2021
+ break;
2022
+ }
2023
+ case "blockImage": {
2024
+ const caption = block.caption ? await resolveInlinesAsync(block.caption, options, diagnostics) : void 0;
2025
+ const resolution = await resolveDocxImage(block.url, options);
2026
+ const prevResolution = block.previousUrl ? await resolveDocxImage(block.previousUrl, options) : void 0;
2027
+ if (resolution.ok) out.push({
2028
+ ...common,
2029
+ ...block.alt !== void 0 ? { alt: block.alt } : {},
2030
+ ...caption && caption.length > 0 ? { caption } : {},
2031
+ ...block.heightPx !== void 0 ? { heightPx: block.heightPx } : {},
2032
+ image: resolution.image,
2033
+ kind: "blockImage",
2034
+ ...block.previousHeightPx !== void 0 ? { previousHeightPx: block.previousHeightPx } : {},
2035
+ ...prevResolution?.ok ? { previousImage: prevResolution.image } : {},
2036
+ ...block.previousWidthPx !== void 0 ? { previousWidthPx: block.previousWidthPx } : {},
2037
+ ...block.reviewRun ? { reviewRun: block.reviewRun } : {},
2038
+ ...block.structureRevision ? { structureRevision: block.structureRevision } : {},
2039
+ ...block.widthPx !== void 0 ? { widthPx: block.widthPx } : {}
2040
+ });
2041
+ else {
2042
+ const alt = block.alt?.trim() ?? "";
2043
+ const hasSurvivingText = caption !== void 0 && hasPlainText(caption) || alt.length > 0;
2044
+ diagnostics.push(docxResourceOmitted({
2045
+ feature: "image",
2046
+ impact: resolution.unsafeScript && hasSurvivingText ? "lossless" : "lossy",
2047
+ message: `An image was omitted because ${resolution.reason}.`
2048
+ }));
2049
+ const fallbackBlocks = [];
2050
+ if (alt.length > 0) fallbackBlocks.push({
2051
+ children: [{
2052
+ kind: "text",
2053
+ text: alt
2054
+ }],
2055
+ kind: "paragraph"
2056
+ });
2057
+ if (caption && caption.length > 0) fallbackBlocks.push({
2058
+ children: caption,
2059
+ kind: "paragraph"
2060
+ });
2061
+ const first = fallbackBlocks[0];
2062
+ const last = fallbackBlocks.at(-1);
2063
+ if (first && last) {
2064
+ const startMarkers = common.commentMarkers?.filter((marker) => marker.kind === "commentRangeStart");
2065
+ const endMarkers = common.commentMarkers?.filter((marker) => marker.kind === "commentRangeEnd");
2066
+ fallbackBlocks[0] = {
2067
+ ...first,
2068
+ ...startMarkers?.length ? { children: [...startMarkers, ...first.children] } : {},
2069
+ ...common.listItem ? { listItem: common.listItem } : {},
2070
+ ...common.reviewBlockStart ? { reviewBlockStart: common.reviewBlockStart } : {}
2071
+ };
2072
+ const lastIndex = fallbackBlocks.length - 1;
2073
+ const updatedLast = fallbackBlocks[lastIndex];
2074
+ if (updatedLast) fallbackBlocks[lastIndex] = {
2075
+ ...updatedLast,
2076
+ ...endMarkers?.length ? { children: [...updatedLast.children, ...endMarkers] } : {},
2077
+ ...common.reviewBlockEnd ? { reviewBlockEnd: common.reviewBlockEnd } : {}
2078
+ };
2079
+ out.push(...fallbackBlocks);
2080
+ } else if (common.commentMarkers?.length || common.listItem || common.reviewBlockStart || common.reviewBlockEnd) out.push({
2081
+ ...common,
2082
+ children: common.commentMarkers ? [...common.commentMarkers] : [],
2083
+ kind: "paragraph"
2084
+ });
2085
+ }
2086
+ break;
2087
+ }
2088
+ case "table": {
2089
+ const rows = [];
2090
+ for (const row of block.rows) {
2091
+ const cells = [];
2092
+ for (const cell of row.cells) {
2093
+ const children = await resolveBlocksAsync(cell.children, options, diagnostics);
2094
+ cells.push({
2095
+ ...cell.backgroundColor !== void 0 ? { backgroundColor: cell.backgroundColor } : {},
2096
+ ...cell.borders !== void 0 ? { borders: cell.borders } : {},
2097
+ ...cell.cellRevision ? { cellRevision: cell.cellRevision } : {},
2098
+ children,
2099
+ ...cell.colSpan !== void 0 ? { colSpan: cell.colSpan } : {},
2100
+ ...cell.header ? { header: true } : {},
2101
+ ...cell.isCalloutIcon ? { isCalloutIcon: true } : {},
2102
+ ...cell.propertyRevision ? { propertyRevision: cell.propertyRevision } : {},
2103
+ ...cell.rowSpan !== void 0 ? { rowSpan: cell.rowSpan } : {},
2104
+ ...cell.verticalAlign !== void 0 ? { verticalAlign: cell.verticalAlign } : {},
2105
+ ...cell.widthPct !== void 0 ? { widthPct: cell.widthPct } : {},
2106
+ ...cell.widthPx !== void 0 ? { widthPx: cell.widthPx } : {}
2107
+ });
2108
+ }
2109
+ rows.push({
2110
+ cells,
2111
+ ...row.header ? { header: true } : {},
2112
+ ...row.minHeightPx !== void 0 ? { minHeightPx: row.minHeightPx } : {},
2113
+ ...row.propertyRevision ? { propertyRevision: row.propertyRevision } : {},
2114
+ ...row.rowRevision ? { rowRevision: row.rowRevision } : {}
2115
+ });
2116
+ }
2117
+ out.push({
2118
+ ...common,
2119
+ ...block.borders !== void 0 ? { borders: block.borders } : {},
2120
+ ...block.calloutVariant !== void 0 ? { calloutVariant: block.calloutVariant } : {},
2121
+ ...block.columnWidthsPx !== void 0 ? { columnWidthsPx: block.columnWidthsPx } : {},
2122
+ ...block.gridRevision ? { gridRevision: block.gridRevision } : {},
2123
+ ...block.isCallout ? { isCallout: true } : {},
2124
+ kind: "table",
2125
+ ...block.marginLeftPx !== void 0 ? { marginLeftPx: block.marginLeftPx } : {},
2126
+ ...block.propertyRevision ? { propertyRevision: block.propertyRevision } : {},
2127
+ rows
2128
+ });
2129
+ break;
2130
+ }
2131
+ }
2132
+ }
2133
+ return out;
2134
+ };
2135
+ const POSITIVE_INT_REF_RE = /^[1-9]\d*$/;
2136
+ const extractMainStoryFootnotes = (blocks, diagnostics) => {
2137
+ const defByRef = /* @__PURE__ */ new Map();
2138
+ const collectDefinitions = (items) => {
2139
+ for (const block of items) if (block.kind === "footnoteDefinition") {
2140
+ if (block.ref && !defByRef.has(block.ref)) defByRef.set(block.ref, block);
2141
+ } else if (block.kind === "blockquote" || block.kind === "toc") collectDefinitions(block.children);
2142
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) collectDefinitions(cell.children);
2143
+ };
2144
+ collectDefinitions(blocks);
2145
+ if (defByRef.size === 0) return {
2146
+ blocks: [...blocks],
2147
+ footnotes: []
2148
+ };
2149
+ const usedIds = /* @__PURE__ */ new Set();
2150
+ const referencedDefs = /* @__PURE__ */ new Set();
2151
+ const refCounts = /* @__PURE__ */ new Map();
2152
+ const footnotes = [];
2153
+ const allocateId = (ref) => {
2154
+ if (POSITIVE_INT_REF_RE.test(ref)) {
2155
+ const parsed = Number.parseInt(ref, 10);
2156
+ if (Number.isSafeInteger(parsed) && parsed > 0 && !usedIds.has(parsed)) {
2157
+ usedIds.add(parsed);
2158
+ return parsed;
2159
+ }
2160
+ }
2161
+ let candidate = 1;
2162
+ while (usedIds.has(candidate)) candidate += 1;
2163
+ usedIds.add(candidate);
2164
+ return candidate;
2165
+ };
2166
+ const bindInlines = (inlines) => {
2167
+ for (const inline of inlines) if (inline.kind === "footnoteReference") {
2168
+ const def = defByRef.get(inline.ref);
2169
+ if (def) {
2170
+ const priorCount = refCounts.get(inline.ref) ?? 0;
2171
+ refCounts.set(inline.ref, priorCount + 1);
2172
+ if (priorCount === 1) diagnostics.push(docxLossyContent({
2173
+ feature: "footnote",
2174
+ message: `Footnote "${inline.ref}" was referenced multiple times and exported as separate Word footnotes.`
2175
+ }));
2176
+ const id = allocateId(inline.ref);
2177
+ inline.id = id;
2178
+ referencedDefs.add(def);
2179
+ footnotes.push({
2180
+ blocks: def.children,
2181
+ id,
2182
+ ref: inline.ref
2183
+ });
2184
+ }
2185
+ } else if (inline.kind === "link") bindInlines(inline.children);
2186
+ };
2187
+ const bindBlocks = (items) => {
2188
+ const out = [];
2189
+ for (const block of items) {
2190
+ if (block.kind === "footnoteDefinition") {
2191
+ out.push(block);
2192
+ continue;
2193
+ }
2194
+ if (block.kind === "paragraph") bindInlines(block.children);
2195
+ else if (block.kind === "blockImage" && block.caption) bindInlines(block.caption);
2196
+ else if (block.kind === "blockquote" || block.kind === "toc") block.children = bindBlocks(block.children);
2197
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) cell.children = bindBlocks(cell.children);
2198
+ out.push(block);
2199
+ }
2200
+ return out;
2201
+ };
2202
+ const pruneReferencedDefs = (items) => {
2203
+ const out = [];
2204
+ for (const block of items) {
2205
+ if (block.kind === "footnoteDefinition") {
2206
+ if (referencedDefs.has(block)) continue;
2207
+ out.push(block);
2208
+ continue;
2209
+ }
2210
+ if (block.kind === "blockquote" || block.kind === "toc") block.children = pruneReferencedDefs(block.children);
2211
+ else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) cell.children = pruneReferencedDefs(cell.children);
2212
+ out.push(block);
2213
+ }
2214
+ return out;
2215
+ };
2216
+ return {
2217
+ blocks: pruneReferencedDefs(bindBlocks(blocks)),
2218
+ footnotes
2219
+ };
2220
+ };
2221
+ const writesQuoteParagraphAt = (block, end) => {
2222
+ if (!block || block.kind !== "blockquote") return false;
2223
+ if (block.children.length === 0) return true;
2224
+ const child = block.children.at(end);
2225
+ return child !== void 0 && (isQuoteParagraphBlock(child) || child.kind === "blockquote" && writesQuoteParagraphAt(child, end));
2226
+ };
2227
+ const collectQuoteDiagnostics = (blocks, commentId) => {
2228
+ const diagnostics = [];
2229
+ const place = (path) => commentId === void 0 ? path.join(".") : `${path.join(".")} in comment ${commentId}`;
2230
+ const warn = (path, message) => {
2231
+ diagnostics.push({
2232
+ code: "lossy-content",
2233
+ feature: "quote-structure",
2234
+ impact: "lossy",
2235
+ message,
2236
+ path,
2237
+ severity: "warning",
2238
+ ...commentId === void 0 ? {} : { sourceId: commentId }
2239
+ });
2240
+ };
2241
+ const visit = (items, parentPath) => {
2242
+ items.forEach((block, index) => {
2243
+ const path = block.sourcePath ?? [...parentPath, index];
2244
+ if (block.kind === "blockquote") {
2245
+ const previous = items[index - 1];
2246
+ if (previous?.kind === "blockquote" && writesQuoteParagraphAt(previous, -1) && writesQuoteParagraphAt(block, 0)) warn(path, `The quote at ${place(path)} joins the quote before it in Word.`);
2247
+ block.children.forEach((child, childIndex) => {
2248
+ const childPath = child.sourcePath ?? [...path, childIndex];
2249
+ if (child.kind === "blockquote") warn(childPath, `The quote at ${place(childPath)} merges into the quote around it in Word.`);
2250
+ else if (!isQuoteParagraphBlock(child)) warn(childPath, `The block at ${place(childPath)} exports outside its quote.`);
2251
+ });
2252
+ visit(block.children, path);
2253
+ } else if (block.kind === "table") for (const row of block.rows) for (const cell of row.cells) visit(cell.children, path);
2254
+ else if (block.kind === "footnoteDefinition") visit(block.children, path);
2255
+ });
2256
+ };
2257
+ visit(blocks, []);
2258
+ return diagnostics;
2259
+ };
2260
+ /**
2261
+ * Compile one captured document and its comment bodies synchronously through
2262
+ * plugin `formats.docx` encoders, returning an immutable pending IR holding no
2263
+ * editor reference.
2264
+ */
2265
+ const compileDocxAstSync = (editor, { comments, detachedSchema, document, review, storyRoots, styles }) => {
2266
+ const formats = collectDocxFormats(editor);
2267
+ const diagnostics = [...review?.diagnostics ?? []];
2268
+ const sharedOrderCounter = { value: 0 };
2269
+ const mainStory = compileStorySync(editor, document, "body", formats, styles, review, diagnostics, detachedSchema, MAIN_ROOT_KEY, sharedOrderCounter);
2270
+ const pendingStoryRoots = /* @__PURE__ */ new Map();
2271
+ const renderedRoots = new Set(mainStory.renderedRoots);
2272
+ const allCommentBlocks = [...mainStory.blocks];
2273
+ const allTextSpans = [...mainStory.textSpans];
2274
+ if (storyRoots && storyRoots.size > 0 && document.roots) for (const rootKey of storyRoots) {
2275
+ if (!Object.hasOwn(document.roots, rootKey)) continue;
2276
+ const rootNodes = document.roots[rootKey];
2277
+ if (!rootNodes) continue;
2278
+ const story = compileStorySync(editor, { children: rootNodes }, `story:${rootKey}`, formats, styles, review, diagnostics, detachedSchema, rootKey, sharedOrderCounter);
2279
+ pendingStoryRoots.set(rootKey, story);
2280
+ renderedRoots.add(rootKey);
2281
+ for (const nestedRoot of story.renderedRoots) renderedRoots.add(nestedRoot);
2282
+ allCommentBlocks.push(...story.blocks);
2283
+ allTextSpans.push(...story.textSpans);
2284
+ }
2285
+ const quoteDiagnostics = [...collectQuoteDiagnostics(mainStory.blocks), ...[...new Set(mainStory.footnotes.map((footnote) => footnote.blocks))].flatMap((blocks) => collectQuoteDiagnostics(blocks))];
2286
+ const anchoredComments = anchorCommentsOnAst(allCommentBlocks, allTextSpans, comments, diagnostics);
2287
+ const droppedReviewPropertyKeys = /* @__PURE__ */ new Set([...formats.markDropped.keys(), ...formats.propertyDropped.map((entry) => entry.property)]);
2288
+ const reviewBindings = attachReviewBindings(review, mainStory.mainBlockRecords, diagnostics, droppedReviewPropertyKeys);
2289
+ const anchoredIds = new Set(anchoredComments.map((entry) => entry.comment.id));
2290
+ const pendingCommentStories = anchoredComments.map((entry) => {
2291
+ const story = compileStorySync(editor, { children: entry.comment.body }, `comment:${entry.comment.id}`, formats, styles, void 0, diagnostics, detachedSchema);
2292
+ quoteDiagnostics.push(...collectQuoteDiagnostics(story.blocks, entry.comment.id));
2293
+ return {
2294
+ ...entry,
2295
+ story
2296
+ };
2297
+ });
2298
+ for (const comment of comments) {
2299
+ if (!comment.target || anchoredIds.has(comment.id)) continue;
2300
+ try {
2301
+ const unanchoredStory = compileStorySync(editor, { children: comment.body }, `comment:${comment.id}`, formats, styles, void 0, [], detachedSchema);
2302
+ quoteDiagnostics.push(...collectQuoteDiagnostics(unanchoredStory.blocks, comment.id));
2303
+ } catch {}
2304
+ }
2305
+ const collectChangeIdsDeep = (value, out) => {
2306
+ if (Array.isArray(value)) {
2307
+ for (const item of value) collectChangeIdsDeep(item, out);
2308
+ return;
2309
+ }
2310
+ if (!value || typeof value !== "object") return;
2311
+ const rec = value;
2312
+ if (typeof rec.change === "string") out.add(rec.change);
2313
+ if (Array.isArray(rec.authored)) collectChangeIdsDeep(rec.authored, out);
2314
+ if (Array.isArray(rec.over)) collectChangeIdsDeep(rec.over, out);
2315
+ if (rec.member) collectChangeIdsDeep(rec.member, out);
2316
+ if (Array.isArray(rec.children)) collectChangeIdsDeep(rec.children, out);
2317
+ };
2318
+ if (review && pendingStoryRoots.size > 0 && review.stored.roots) {
2319
+ const mainChanges = /* @__PURE__ */ new Set();
2320
+ const storyChanges = /* @__PURE__ */ new Set();
2321
+ collectChangeIdsDeep(review.stored.children, mainChanges);
2322
+ for (const rootKey of pendingStoryRoots.keys()) {
2323
+ const rootNodes = Object.hasOwn(review.stored.roots, rootKey) ? review.stored.roots[rootKey] : void 0;
2324
+ if (rootNodes) collectChangeIdsDeep(rootNodes, storyChanges);
2325
+ }
2326
+ for (const changeId of storyChanges) if (mainChanges.has(changeId)) {
2327
+ diagnostics.push(docxLossyContent({
2328
+ feature: "tracked-revision",
2329
+ message: "A tracked change spanning both the main document body and a header or footer exports as separate Word revisions."
2330
+ }));
2331
+ break;
2332
+ }
2333
+ }
2334
+ const rawReviewRecords = stripDroppedReviewRecords(filterAuthoredReviewRecords(review?.stored.records), droppedReviewPropertyKeys);
2335
+ const scopeReviewRecordsToBindings = (records, bindings) => {
2336
+ const liveChanges = /* @__PURE__ */ new Set();
2337
+ const contextQueue = [];
2338
+ const enqueueContext = (id) => {
2339
+ contextQueue.push(id);
2340
+ };
2341
+ const collectRefs = (value) => {
2342
+ if (Array.isArray(value)) {
2343
+ for (const item of value) collectRefs(item);
2344
+ return;
2345
+ }
2346
+ if (!value || typeof value !== "object") return;
2347
+ const rec = value;
2348
+ if (typeof rec.change === "string") liveChanges.add(rec.change);
2349
+ if (typeof rec.ctx === "string") enqueueContext(rec.ctx);
2350
+ if (typeof rec.context === "string") enqueueContext(rec.context);
2351
+ if (Array.isArray(rec.authored)) collectRefs(rec.authored);
2352
+ if (Array.isArray(rec.over)) collectRefs(rec.over);
2353
+ if (rec.member) collectRefs(rec.member);
2354
+ if (Array.isArray(rec.children)) collectRefs(rec.children);
2355
+ };
2356
+ for (const binding of bindings) collectRefs(binding.nodes);
2357
+ const contexts = records["authored-contexts"];
2358
+ const reachableContexts = /* @__PURE__ */ new Set();
2359
+ if (contexts && typeof contexts === "object") while (contextQueue.length > 0) {
2360
+ const ctxId = contextQueue.pop();
2361
+ if (!ctxId || reachableContexts.has(ctxId)) continue;
2362
+ const entry = contexts[ctxId];
2363
+ if (!entry || typeof entry !== "object") continue;
2364
+ reachableContexts.add(ctxId);
2365
+ const rec = entry;
2366
+ if (typeof rec.base === "string") enqueueContext(rec.base);
2367
+ if (rec.member) collectRefs(rec.member);
2368
+ }
2369
+ const verdicts = records["authored-verdicts"];
2370
+ if (verdicts && typeof verdicts === "object") {
2371
+ for (const entry of Object.values(verdicts)) if (entry && typeof entry === "object" && typeof entry.change === "string") liveChanges.add(entry.change);
2372
+ }
2373
+ const events = records["authored-events"];
2374
+ const sortedKept = [...(events && typeof events === "object" ? Object.entries(events) : []).filter(([, entry]) => {
2375
+ if (!entry || typeof entry !== "object") return false;
2376
+ const { change } = entry;
2377
+ return typeof change === "string" && liveChanges.has(change);
2378
+ })].sort(([, a], [, b]) => {
2379
+ return (typeof a.lamport === "number" ? a.lamport : 0) - (typeof b.lamport === "number" ? b.lamport : 0);
2380
+ });
2381
+ const lamportMap = /* @__PURE__ */ new Map();
2382
+ const scopeClockList = /* @__PURE__ */ new Map();
2383
+ for (const [, entry] of sortedKept) {
2384
+ const rec = entry;
2385
+ if (typeof rec.scope === "string" && typeof rec.clock === "number") {
2386
+ let list = scopeClockList.get(rec.scope);
2387
+ if (!list) {
2388
+ list = [];
2389
+ scopeClockList.set(rec.scope, list);
2390
+ }
2391
+ list.push(rec.clock);
2392
+ }
2393
+ }
2394
+ const scopeClockMap = /* @__PURE__ */ new Map();
2395
+ for (const [scope, clocks] of scopeClockList) {
2396
+ const sortedClocks = [...new Set(clocks)].sort((a, b) => a - b);
2397
+ const map = /* @__PURE__ */ new Map();
2398
+ sortedClocks.forEach((orig, idx) => map.set(orig, idx + 1));
2399
+ scopeClockMap.set(scope, map);
2400
+ }
2401
+ const compactedEvents = {};
2402
+ sortedKept.forEach(([key, entry], idx) => {
2403
+ const rec = entry;
2404
+ const newLamport = idx + 1;
2405
+ if (typeof rec.lamport === "number") lamportMap.set(rec.lamport, newLamport);
2406
+ const scope = typeof rec.scope === "string" ? rec.scope : void 0;
2407
+ const origClock = typeof rec.clock === "number" ? rec.clock : void 0;
2408
+ const newClock = scope && origClock !== void 0 ? scopeClockMap.get(scope)?.get(origClock) ?? 1 : origClock;
2409
+ let compactedVv;
2410
+ if (rec.vv && typeof rec.vv === "object") {
2411
+ const nextVv = {};
2412
+ for (const [s, c] of Object.entries(rec.vv)) {
2413
+ if (typeof c !== "number") continue;
2414
+ const map = scopeClockMap.get(s);
2415
+ if (!map) continue;
2416
+ let maxMapped = 0;
2417
+ for (const [origC, mappedC] of map) if (origC <= c && mappedC > maxMapped) maxMapped = mappedC;
2418
+ if (maxMapped > 0) nextVv[s] = maxMapped;
2419
+ }
2420
+ if (Object.keys(nextVv).length > 0) compactedVv = nextVv;
2421
+ }
2422
+ const nextRec = {
2423
+ ...rec,
2424
+ ...newClock !== void 0 ? { clock: newClock } : {},
2425
+ lamport: newLamport
2426
+ };
2427
+ if (compactedVv) nextRec.vv = compactedVv;
2428
+ else delete nextRec.vv;
2429
+ compactedEvents[key] = nextRec;
2430
+ });
2431
+ const filterByChange = (bucket) => {
2432
+ if (!bucket || typeof bucket !== "object") return void 0;
2433
+ const filtered = Object.fromEntries(Object.entries(bucket).filter(([, entry]) => {
2434
+ if (!entry || typeof entry !== "object") return false;
2435
+ const { change } = entry;
2436
+ return typeof change === "string" && liveChanges.has(change);
2437
+ }));
2438
+ return Object.keys(filtered).length > 0 ? filtered : void 0;
2439
+ };
2440
+ const filteredContexts = contexts && typeof contexts === "object" ? Object.fromEntries(Object.entries(contexts).filter(([id]) => reachableContexts.has(id))) : void 0;
2441
+ const filteredReserves = filterByChange(records["authored-reserves"]);
2442
+ const filteredLanded = filterByChange(records["authored-landed"]);
2443
+ const meta = records["authored-meta"];
2444
+ const filteredMeta = meta && typeof meta === "object" ? Object.fromEntries(Object.entries(meta).filter(([changeId]) => liveChanges.has(changeId))) : void 0;
2445
+ const compactedVerdicts = verdicts && typeof verdicts === "object" ? Object.fromEntries(Object.entries(verdicts).flatMap(([k, entry]) => {
2446
+ if (!entry || typeof entry !== "object") return [];
2447
+ const rec = entry;
2448
+ if (typeof rec.order !== "number") return [[k, entry]];
2449
+ let mappedOrder = lamportMap.get(rec.order);
2450
+ if (mappedOrder === void 0) {
2451
+ mappedOrder = 0;
2452
+ for (const [origL, nextL] of lamportMap) if (origL <= rec.order && nextL > mappedOrder) mappedOrder = nextL;
2453
+ }
2454
+ return mappedOrder > 0 ? [[k, {
2455
+ ...rec,
2456
+ order: mappedOrder
2457
+ }]] : [];
2458
+ })) : void 0;
2459
+ const scoped = {};
2460
+ if (Object.keys(compactedEvents).length > 0) scoped["authored-events"] = compactedEvents;
2461
+ if (filteredContexts && Object.keys(filteredContexts).length > 0) scoped["authored-contexts"] = filteredContexts;
2462
+ if (filteredReserves) scoped["authored-reserves"] = filteredReserves;
2463
+ if (filteredLanded) scoped["authored-landed"] = filteredLanded;
2464
+ if (filteredMeta && Object.keys(filteredMeta).length > 0) scoped["authored-meta"] = filteredMeta;
2465
+ if (compactedVerdicts && Object.keys(compactedVerdicts).length > 0) scoped["authored-verdicts"] = compactedVerdicts;
2466
+ return scoped;
2467
+ };
2468
+ const reviewRecords = (() => {
2469
+ if (!rawReviewRecords) return void 0;
2470
+ if (reviewBindings.length > 0) return scopeReviewRecordsToBindings(rawReviewRecords, reviewBindings);
2471
+ const verdicts = rawReviewRecords["authored-verdicts"];
2472
+ if (!verdicts || typeof verdicts !== "object" || Object.keys(verdicts).length === 0) return;
2473
+ const decidedChanges = /* @__PURE__ */ new Set();
2474
+ for (const entry of Object.values(verdicts)) if (entry && typeof entry === "object" && typeof entry.change === "string") decidedChanges.add(entry.change);
2475
+ const events = rawReviewRecords["authored-events"];
2476
+ const filteredEvents = events && typeof events === "object" ? Object.fromEntries(Object.entries(events).filter(([, entry]) => {
2477
+ if (!entry || typeof entry !== "object") return false;
2478
+ const { change } = entry;
2479
+ return typeof change === "string" && decidedChanges.has(change);
2480
+ })) : void 0;
2481
+ return {
2482
+ ...filteredEvents && Object.keys(filteredEvents).length > 0 ? { "authored-events": filteredEvents } : {},
2483
+ "authored-verdicts": verdicts
2484
+ };
2485
+ })();
2486
+ return Object.freeze({
2487
+ diagnostics,
2488
+ mainStory,
2489
+ pendingCommentStories,
2490
+ pendingStoryRoots,
2491
+ quoteDiagnostics,
2492
+ renderedRoots,
2493
+ reviewBindings,
2494
+ reviewRecords
2495
+ });
2496
+ };
2497
+ /** Resolve async images and KaTeX OMML equations on a synchronously compiled DOCX AST. */
2498
+ const resolveCompiledDocxDocument = async (pending, { allowRemoteImages = false, signal }) => {
2499
+ const { diagnostics, mainStory, pendingCommentStories, pendingStoryRoots, renderedRoots, reviewBindings, reviewRecords } = pending;
2500
+ throwIfDocxAborted(signal);
2501
+ const resolveOptions = {
2502
+ allowRemoteImages,
2503
+ signal
2504
+ };
2505
+ const resolvedBlocks = await resolveBlocksAsync(mainStory.blocks, resolveOptions, diagnostics);
2506
+ const resolvedStoryBlocks = /* @__PURE__ */ new Map();
2507
+ for (const [rootKey, story] of pendingStoryRoots) {
2508
+ const blocks = await resolveBlocksAsync(story.blocks, resolveOptions, diagnostics);
2509
+ resolvedStoryBlocks.set(rootKey, blocks.length > 0 ? blocks : [{
2510
+ children: [],
2511
+ kind: "paragraph"
2512
+ }]);
2513
+ }
2514
+ const resolvedFootnotes = [];
2515
+ for (const entry of mainStory.footnotes) {
2516
+ const blocks = await resolveBlocksAsync(entry.blocks, resolveOptions, diagnostics);
2517
+ resolvedFootnotes.push({
2518
+ blocks: blocks.length > 0 ? blocks : [{
2519
+ children: [],
2520
+ kind: "paragraph"
2521
+ }],
2522
+ id: entry.id,
2523
+ ref: entry.ref
2524
+ });
2525
+ }
2526
+ const resolvedComments = [];
2527
+ for (const entry of pendingCommentStories) {
2528
+ const blocks = await resolveBlocksAsync(entry.story.blocks, resolveOptions, diagnostics);
2529
+ resolvedComments.push({
2530
+ blocks: blocks.length > 0 ? blocks : [{
2531
+ children: [],
2532
+ kind: "paragraph"
2533
+ }],
2534
+ comment: entry.comment,
2535
+ id: entry.id,
2536
+ paragraphId: entry.paragraphId
2537
+ });
2538
+ }
2539
+ throwIfDocxAborted(signal);
2540
+ return Object.freeze({
2541
+ blocks: resolvedBlocks,
2542
+ comments: resolvedComments,
2543
+ diagnostics,
2544
+ footnotes: resolvedFootnotes,
2545
+ renderedRoots,
2546
+ reviewBindings,
2547
+ reviewRecords,
2548
+ ...resolvedStoryBlocks.size > 0 ? { storyBlocks: resolvedStoryBlocks } : {}
2549
+ });
2550
+ };
2551
+ //#endregion
2552
+ export { collectDocxFormats, compileDocxAstSync, isQuoteParagraphBlock, resolveCompiledDocxDocument };