platejs 54.0.0-beta.2 → 54.0.0-beta.3

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 (237) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +56 -0
  3. package/dist/{AIChatRequestContext-BMVWhfPV.d.ts → AIChatRequestContext-DY104TqL.d.ts} +2 -2
  4. package/dist/{BaseSuggestionPlugin-DBl3fqnm.d.ts → BaseSuggestionPlugin-Deo6n6Fs.d.ts} +7 -3
  5. package/dist/{PlateStatic-DhNv2ejp.d.ts → PlateStatic-CJX5bKuv.d.ts} +7 -7
  6. package/dist/ai/index.d.ts +1 -1
  7. package/dist/ai/react/AIChatPlugin.js +113 -78
  8. package/dist/ai/react/CopilotPlugin.js +1 -1
  9. package/dist/ai/react/index.d.ts +23 -16
  10. package/dist/authored/index.d.ts +4 -4
  11. package/dist/code-block/codemirror/createCodeMirrorAdapter.js +12 -9
  12. package/dist/code-block/codemirror/index.d.ts +1 -1
  13. package/dist/{combobox-DkBGgyd3.d.ts → combobox-DAOYWuvC.d.ts} +2 -2
  14. package/dist/{comparison-types-CYnJ35qU.d.ts → comparison-types-Dt-unJZY-DCddmbSD.d.ts} +10 -2
  15. package/dist/compiler/index.d.ts +2 -2
  16. package/dist/{core-BJG8l_mk.d.ts → core-ClHasORr.d.ts} +433 -95
  17. package/dist/diff/index.d.ts +2 -2
  18. package/dist/docs/ai.md +4 -3
  19. package/dist/docs/api/core/plate-components.md +0 -19
  20. package/dist/docs/api/core/plate-controller.md +4 -2
  21. package/dist/docs/api/core/plate-plugin.md +3 -0
  22. package/dist/docs/api/core/plate-store.md +3 -3
  23. package/dist/docs/api/dom.md +14 -4
  24. package/dist/docs/api/editor-transforms.md +2 -1
  25. package/dist/docs/api/react-hooks.md +25 -11
  26. package/dist/docs/authored-changes.md +5 -2
  27. package/dist/docs/basic-blocks.md +42 -29
  28. package/dist/docs/blockquote.md +5 -3
  29. package/dist/docs/board.md +63 -8
  30. package/dist/docs/code-block.md +47 -0
  31. package/dist/docs/discussion.md +1 -1
  32. package/dist/docs/docx.md +1 -1
  33. package/dist/docs/dom-coverage.md +5 -0
  34. package/dist/docs/examples/editable-voids.md +2 -3
  35. package/dist/docs/external-text.md +2 -0
  36. package/dist/docs/field.md +370 -0
  37. package/dist/docs/find.md +9 -6
  38. package/dist/docs/form.md +2 -0
  39. package/dist/docs/heading.md +6 -0
  40. package/dist/docs/installation/manual.md +0 -4
  41. package/dist/docs/link.md +3 -3
  42. package/dist/docs/llms.txt +4 -2
  43. package/dist/docs/markdown.md +176 -8
  44. package/dist/docs/plugin-components.md +13 -10
  45. package/dist/docs/plugin-input-rules.md +4 -12
  46. package/dist/docs/prompt-editor.md +205 -0
  47. package/dist/docs/roots.md +8 -6
  48. package/dist/docs/rtl.md +6 -4
  49. package/dist/docs/selection.md +7 -4
  50. package/dist/docs/suggestion.md +1 -1
  51. package/dist/docs/toolbar.md +26 -30
  52. package/dist/docs/upload.md +106 -17
  53. package/dist/docx/export/index.d.ts +3 -3
  54. package/dist/docx/export/lib/docxStaticComponents.js +12 -2
  55. package/dist/docx/export/lib/exportDocx.js +29 -5
  56. package/dist/docx/export/lib/reviewPart.js +1 -1
  57. package/dist/docx/export/lib/reviewProjection.js +10 -8
  58. package/dist/docx/import/index.d.ts +4 -4
  59. package/dist/docx/paste/index.d.ts +4 -4
  60. package/dist/dom/index.d.ts +1 -6
  61. package/dist/dom/plite-dom.internal.js +2 -2
  62. package/dist/excalidraw/index.d.ts +3 -2
  63. package/dist/excalidraw/react/index.d.ts +3 -2
  64. package/dist/facade.js +2 -2
  65. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +13 -5
  66. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +32 -10
  67. package/dist/features/board/index.d.ts +2 -2
  68. package/dist/features/board/lib/BaseBoardPlugin.js +14 -1
  69. package/dist/features/board/lib/boardStroke.internal.js +13 -1
  70. package/dist/features/board/lib/boardTypes.internal.js +16 -0
  71. package/dist/features/callout/index.d.ts +3 -2
  72. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +14 -5
  73. package/dist/features/combobox/index.d.ts +2 -2
  74. package/dist/features/comments/index.d.ts +1 -1
  75. package/dist/features/date/index.d.ts +3 -2
  76. package/dist/features/details/index.d.ts +3 -2
  77. package/dist/features/details/lib/BaseDetailsPlugin.js +10 -10
  78. package/dist/features/field/index.d.ts +2 -0
  79. package/dist/features/field/index.js +2 -0
  80. package/dist/features/field/lib/BaseFieldPlugin.js +414 -0
  81. package/dist/features/field/lib/fieldRules.internal.js +42 -0
  82. package/dist/features/find/index.d.ts +3 -2
  83. package/dist/features/footnote/index.d.ts +1 -1
  84. package/dist/features/ink/index.d.ts +1 -1
  85. package/dist/features/ink/lib/BaseInkPlugin.js +126 -103
  86. package/dist/features/ink/lib/inkCodec.internal.js +130 -0
  87. package/dist/features/ink/lib/inkGone.internal.js +229 -48
  88. package/dist/features/ink/lib/inkPlaces.internal.js +533 -62
  89. package/dist/features/layout/index.d.ts +1 -1
  90. package/dist/features/link/lib/BaseLinkPlugin.js +6 -4
  91. package/dist/features/lint/index.d.ts +3 -2
  92. package/dist/features/media/index.d.ts +1 -1
  93. package/dist/features/media/lib/media/parseMediaUrl.js +11 -1
  94. package/dist/features/media/lib/media-embed/BaseMediaEmbedPlugin.js +6 -2
  95. package/dist/features/mention/index.d.ts +5 -4
  96. package/dist/features/suggestion/index.d.ts +1 -1
  97. package/dist/features/table/index.d.ts +1 -1
  98. package/dist/features/table/lib/BaseTablePlugin.js +14 -8
  99. package/dist/features/table/lib/internal/selection.js +4 -2
  100. package/dist/features/toc/index.d.ts +1 -1
  101. package/dist/features/upload/index.d.ts +2 -2
  102. package/dist/features/upload/lib/BaseUploadPlugin.js +464 -250
  103. package/dist/history/index.d.ts +2 -2
  104. package/dist/html/index.d.ts +3 -3
  105. package/dist/html/server/index.d.ts +1 -1
  106. package/dist/{htmlTypes-DjeFG3P8.d.ts → htmlTypes-cg_cWsaN.d.ts} +2 -31
  107. package/dist/hyperscript/index.d.ts +1 -1
  108. package/dist/{index-D1CFXA-i.d.ts → index-8WO2vI0U.d.ts} +475 -143
  109. package/dist/{index-DaM37gF6.d.ts → index-B5mYEawV.d.ts} +37 -21
  110. package/dist/{index-Bq3sdm3S.d.ts → index-BZWFoUXt.d.ts} +5 -4
  111. package/dist/{index-DdIRduDG.d.ts → index-C0POz7rg.d.ts} +3 -2
  112. package/dist/{index-Bxfvicyy.d.ts → index-C1_JIhL4.d.ts} +4 -3
  113. package/dist/{index-DC_MNGyu.d.ts → index-C35V_hj0.d.ts} +3 -3
  114. package/dist/{index-kLKMc-pI.d.ts → index-C6ql9pKw.d.ts} +2 -2
  115. package/dist/{index-hsC_sOn2.d.ts → index-C9DiGDVj.d.ts} +35 -5
  116. package/dist/{index-DTgaSxKr.d.ts → index-CLsEe3LY.d.ts} +40 -4
  117. package/dist/{index-CT7miqQN.d.ts → index-CdOLsPaW.d.ts} +29 -9
  118. package/dist/{index-DLA2DUR2.d.ts → index-CktYvOgk.d.ts} +4 -3
  119. package/dist/{index-BBKGrsG3.d.ts → index-Cmuluh6f.d.ts} +1 -1
  120. package/dist/{index-BiQerPJS.d.ts → index-CzLwBZpY.d.ts} +2 -2
  121. package/dist/{index-DzD6BIFJ.d.ts → index-D3-2iM1b.d.ts} +7 -5
  122. package/dist/{index-Cl77E9yr.d.ts → index-DKOFvteF.d.ts} +2 -2
  123. package/dist/{index-iaZOhA76.d.ts → index-DPWyk3lG-DOYwohXO.d.ts} +1 -1
  124. package/dist/index-DQnjqtQa.d.ts +678 -0
  125. package/dist/{index-CcZbqPqk.d.ts → index-Do9pj1GK.d.ts} +73 -39
  126. package/dist/{index-BU6k1Aev.d.ts → index-DpltOCot-A2b3p3Eb.d.ts} +4735 -4586
  127. package/dist/{index-Bc2Yg_2j.d.ts → index-HPYawTae-BCUQLEWF.d.ts} +2 -2
  128. package/dist/{index-BkR7-GLI.d.ts → index-baQOK89E.d.ts} +2 -2
  129. package/dist/{index-D5W-p9bS.d.ts → index-oIJAZxc2.d.ts} +49 -4
  130. package/dist/{index-xdmCBvlT.d.ts → index-r7yb77Wy.d.ts} +3 -2
  131. package/dist/index.d.ts +4 -4
  132. package/dist/{react/internal → internal}/penStroke.internal.js +1 -1
  133. package/dist/internal/plugin/OverridePlugin.js +101 -119
  134. package/dist/internal/plugin/collectPlateNodeMappings.js +5 -1
  135. package/dist/internal/plugin/pastedUploadFiles.js +4 -0
  136. package/dist/internal/plugin/resolvePlugin.js +1 -1
  137. package/dist/internal/plugin/resolvePlugins.js +3 -0
  138. package/dist/internal/plugin/uploadDrafts.js +6 -0
  139. package/dist/internal/utils/mergePlugins.js +1 -0
  140. package/dist/lib/plugins/element-id/ElementIdPlugin.js +8 -2
  141. package/dist/lib/plugins/html/HtmlPlugin.js +9 -0
  142. package/dist/lib/plugins/html/htmlSafety.js +1 -1
  143. package/dist/lib/plugins/input-rules/InputRulesPlugin.js +5 -15
  144. package/dist/lib/plugins/input-rules/inputRuleVeto.internal.js +16 -0
  145. package/dist/markdown/index.d.ts +2 -2
  146. package/dist/markdown/index.js +2 -1
  147. package/dist/markdown/lib/MarkdownPlugin.js +16 -9
  148. package/dist/markdown/lib/RawHtmlPlugin.js +24 -0
  149. package/dist/markdown/lib/deserializer/mdastToSlate.js +12 -2
  150. package/dist/markdown/lib/internal/markdownConversion.js +773 -74
  151. package/dist/markdown/lib/internal/markdownDiagnostics.js +18 -7
  152. package/dist/markdown/lib/internal/markdownFrontmatter.js +102 -0
  153. package/dist/markdown/lib/internal/markdownIntrinsics.js +125 -43
  154. package/dist/markdown/lib/internal/markdownLine.js +5 -3
  155. package/dist/markdown/lib/internal/markdownMappings.js +19 -7
  156. package/dist/markdown/lib/internal/markdownOpenTail.js +381 -0
  157. package/dist/markdown/lib/internal/markdownRawHtml.js +314 -0
  158. package/dist/markdown/lib/internal/markdownSegments.js +57 -48
  159. package/dist/markdown/lib/internal/markdownTags.js +22 -8
  160. package/dist/markdown/lib/serializer/convertNodesSerialize.js +10 -8
  161. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +226 -0
  162. package/dist/markdown/lib/serializer/listToMdastTree.js +2 -0
  163. package/dist/math/index.d.ts +3 -2
  164. package/dist/math/react/index.d.ts +4 -3
  165. package/dist/migrations/index.d.ts +3 -3
  166. package/dist/pagination/index.d.ts +1 -1
  167. package/dist/pagination/react/index.d.ts +4 -4
  168. package/dist/react/components/EditorContentView.internal.js +17 -8
  169. package/dist/react/components/EditorProvider.js +5 -5
  170. package/dist/react/components/Plate.js +103 -122
  171. package/dist/react/components/PlateContainer.js +40 -32
  172. package/dist/react/components/PlateController.js +28 -16
  173. package/dist/react/components/PlateRoot.internal.js +3 -2
  174. package/dist/react/core.js +4 -4
  175. package/dist/react/features/board/BoardSurface.js +116 -87
  176. package/dist/react/features/board/boardClipboard.internal.js +15 -5
  177. package/dist/react/features/board/boardGesture.internal.js +6 -3
  178. package/dist/react/features/board/boardIndex.internal.js +7 -18
  179. package/dist/react/features/board/boardPictures.internal.js +19 -13
  180. package/dist/react/features/board/boardView.internal.js +184 -49
  181. package/dist/react/features/board/boardVoice.internal.js +10 -11
  182. package/dist/react/features/board/index.d.ts +64 -18
  183. package/dist/react/features/callout/index.d.ts +3 -2
  184. package/dist/react/features/combobox/index.d.ts +8 -8
  185. package/dist/react/features/comments/index.d.ts +6 -5
  186. package/dist/react/features/date/index.d.ts +4 -3
  187. package/dist/react/features/details/index.d.ts +4 -3
  188. package/dist/react/features/field/FieldPlugin.js +34 -0
  189. package/dist/react/features/field/index.d.ts +312 -0
  190. package/dist/react/features/field/index.js +2 -0
  191. package/dist/react/features/footnote/index.d.ts +7 -6
  192. package/dist/react/features/format-painter/index.d.ts +4 -3
  193. package/dist/react/features/ink/InkContent.js +313 -0
  194. package/dist/react/features/ink/index.d.ts +57 -29
  195. package/dist/react/features/ink/index.js +2 -2
  196. package/dist/react/features/ink/inkCapture.internal.js +39 -17
  197. package/dist/react/features/ink/inkInput.internal.js +1 -1
  198. package/dist/react/features/ink/inkLayout.internal.js +6 -3
  199. package/dist/react/features/ink/inkPaint.internal.js +78 -2
  200. package/dist/react/features/ink/inkPlacement.internal.js +331 -104
  201. package/dist/react/features/ink/inkWatch.internal.js +7 -5
  202. package/dist/react/features/layout/index.d.ts +5 -4
  203. package/dist/react/features/media/index.d.ts +5 -4
  204. package/dist/react/features/mention/index.d.ts +6 -5
  205. package/dist/react/features/resizable/Resizable.js +4 -6
  206. package/dist/react/features/resizable/index.d.ts +5 -5
  207. package/dist/react/features/suggestion/index.d.ts +6 -5
  208. package/dist/react/features/table/TablePlugin.js +4 -11
  209. package/dist/react/features/table/index.d.ts +8 -7
  210. package/dist/react/features/toc/index.d.ts +2 -2
  211. package/dist/react/features/upload/index.d.ts +11 -6
  212. package/dist/react/index.d.ts +6 -6
  213. package/dist/react/index.js +4 -4
  214. package/dist/react/internal/plate-context.js +425 -188
  215. package/dist/react/plite-react.js +2 -2
  216. package/dist/react/plugins/navigation-feedback/NavigationFeedbackPlugin.js +12 -10
  217. package/dist/react/stores/plate/useEditor.js +32 -14
  218. package/dist/react/stores/plate/useEditorHistory.js +55 -0
  219. package/dist/react/stores/plate/useEditorSelector.js +66 -21
  220. package/dist/react/utils/pipeRenderElement.internal.js +1 -1
  221. package/dist/react/utils/pluginRenderElement.internal.js +1 -1
  222. package/dist/react/virtualized.d.ts +4 -4
  223. package/dist/{source-CNKy99Th.d.ts → source-aUwpNnAw.d.ts} +4 -4
  224. package/dist/static/index.d.ts +18 -18
  225. package/dist/static/internal/renderStaticHtmlWithOverrides.js +2 -2
  226. package/dist/static/internal/staticPresentation.js +4 -4
  227. package/dist/static/internal/writeStaticSelectionClipboardData.js +7 -2
  228. package/dist/tabbable/index.d.ts +1 -1
  229. package/dist/tabbable/react/index.d.ts +3 -3
  230. package/dist/testing/index.d.ts +3 -3
  231. package/dist/yjs/index.d.ts +1 -1
  232. package/dist/yjs/react/index.d.ts +6 -6
  233. package/package.json +20 -2
  234. package/dist/markdown/lib/serializer/convertTextsSerialize.js +0 -163
  235. package/dist/react/components/EditorSelectionView.js +0 -40
  236. package/dist/react/features/ink/InkLayer.js +0 -218
  237. package/dist/react/internal/createPlateTargetScope.js +0 -62
@@ -4,18 +4,23 @@ import { ElementIdPlugin } from "../../../lib/plugins/element-id/ElementIdPlugin
4
4
  import { ContentSlice, EditorSchemaValidationError, ElementApi, TextApi } from "../../../core.js";
5
5
  import { UNLANDED_MARKDOWN_PARAGRAPH_TYPE, getMarkdownParagraphType, landsMarkdownParagraph } from "../../../internal/plugin/markdownParagraph.js";
6
6
  import { sameUpToListIds } from "../../../features/list/lib/listIdentity.internal.js";
7
+ import { MARKDOWN_FRONTMATTER_KEY, blankMarkdownFrontmatter, hasMarkdownFrontmatterShape, isMarkdownFrontmatter, opensMarkdownFrontmatterFence, readMarkdownFrontmatter, writeMarkdownFrontmatter } from "./markdownFrontmatter.js";
7
8
  import { createValidatedContentSlice } from "../../../internal/utils/trustedContentSlice.js";
8
- import { getMarkdownTagRepair, remarkMarkdownTagWriter, remarkMarkdownTags, trimIncompleteMarkdownTag } from "./markdownTags.js";
9
- import { getMarkdownParagraphLanding, remarkSeparateEscapes, writeBareUrlsSafely } from "./markdownIntrinsics.js";
9
+ import { RawHtmlPlugin } from "../RawHtmlPlugin.js";
10
+ import { getMarkdownTagRepair, isMarkdownTagSyntax, remarkMarkdownTagWriter, remarkMarkdownTags, trimIncompleteMarkdownTag } from "./markdownTags.js";
11
+ import { findMarkdownRawHtml, getMarkdownParagraphLanding, isRawHtmlFlow, rawHtmlPieceOf, remarkSeparateEscapes, writeBareUrlsSafely } from "./markdownIntrinsics.js";
10
12
  import { finishMarkdownLists } from "../serializer/listToMdastTree.js";
11
- import { convertNodesSerialize } from "../serializer/convertNodesSerialize.js";
13
+ import { convertNodesSerialize, mayJoinList } from "../serializer/convertNodesSerialize.js";
12
14
  import { DEFAULT_MARKDOWN_PARSE_LIMITS, MarkdownDiagnostics, ReportedMarkdownFailureError, checkMarkdownTreeLimits, createMarkdownModelLocator, createMarkdownSourceLocation } from "./markdownDiagnostics.js";
13
15
  import { compileMarkdownMappings, getMarkdownMappingsRegistryKey, getRegisteredMarkdownMappings, registerMarkdownMappings } from "./markdownMappings.js";
14
16
  import { mdastToSlate } from "../deserializer/mdastToSlate.js";
15
17
  import { materializeMarkdownSettings, materializeRemarkPlugins } from "../utils/remarkPlugins.js";
18
+ import { keepsReceived, remarkOpenTail } from "./markdownOpenTail.js";
19
+ import { createRawHtmlPlacementDecider, decideRawHtmlBlocks, printsNoText } from "./markdownRawHtml.js";
16
20
  import { allocateMarkdownFootnoteLabels, remarkResolveMarkdownReferences } from "./markdownReferences.js";
17
21
  import { cleanMarkdownDestinations } from "./markdownSafety.js";
18
- import { MARKDOWN_DEFINITION, countMarkdownLines, findMarkdownSegmentBoundaries, shiftMarkdownDiagnostic } from "./markdownSegments.js";
22
+ import { DEFINITION_SYNTAX, MARKDOWN_DEFINITION, countMarkdownLines, findMarkdownSegmentBoundaries, holdsMarkdownSegmentOpen, readsMarkdownWhole, shiftMarkdownDiagnostic } from "./markdownSegments.js";
23
+ import { dequal } from "dequal";
19
24
  import remarkParse from "remark-parse";
20
25
  import remarkStringify from "remark-stringify";
21
26
  import { unified } from "unified";
@@ -73,17 +78,25 @@ const getMergedOptionsDeserialize = (runtime, options = {}, operation = {}) => {
73
78
  state: runtime.state
74
79
  };
75
80
  };
81
+ const writesRawHtml = (runtime, plainMarks) => runtime.registry.has(RawHtmlPlugin) && !plainMarks?.includes(RawHtmlPlugin.name);
82
+ const importsRawHtml = (runtime) => writesRawHtml(runtime, runtime.options.plainMarks);
76
83
  const getMergedOptionsSerialize = (runtime, options = {}, documentOverride, diagnostics = new MarkdownDiagnostics(), readRoots = /* @__PURE__ */ new Set()) => {
77
84
  const { plainMarks, remarkPlugins, remarkStringifyOptions } = runtime.options;
78
85
  const document = documentOverride ?? runtime.state.value();
86
+ let locate;
87
+ const plain = options.plainMarks ?? (plainMarks ? [...plainMarks] : plainMarks);
79
88
  return {
80
89
  ...createConversionContext(runtime),
81
90
  document,
82
91
  lossPolicy: options.lossPolicy ?? "reject",
83
92
  mappings: runtime.formats,
84
- modelLocation: createMarkdownModelLocator(document),
85
- plainMarks: options.plainMarks ?? (plainMarks ? [...plainMarks] : plainMarks),
93
+ modelLocation: (node) => (locate ??= createMarkdownModelLocator(document))(node),
94
+ plainMarks: plain,
86
95
  preserveEmptyParagraphs: options.preserveEmptyParagraphs,
96
+ ...writesRawHtml(runtime, plain) ? { rawHtml: { decide: createRawHtmlPlacementDecider({
97
+ commonmark: (source) => COMMONMARK.parse(source),
98
+ editor: (source) => getRawHtmlEditorReader(runtime)(source)
99
+ }) } } : {},
87
100
  readRoots,
88
101
  remarkPlugins: materializeRemarkPlugins(remarkPlugins),
89
102
  remarkStringifyOptions: options.remarkStringifyOptions ?? (remarkStringifyOptions ? materializeMarkdownSettings(remarkStringifyOptions) : remarkStringifyOptions),
@@ -93,16 +106,78 @@ const getMergedOptionsSerialize = (runtime, options = {}, documentOverride, diag
93
106
  value: [...document.children]
94
107
  };
95
108
  };
96
- const markdownToSlateNodesWithRuntime = (runtime, data, options = {}, diagnostics = new MarkdownDiagnostics(), hooks = {}) => {
109
+ const createMarkdownParser = (runtime, remarkPlugins, openTail) => unified().use(remarkParse).use(remarkSeparateEscapes).use(remarkMarkdownTags, { tags: runtime.formats.tags }).use(remarkResolveMarkdownReferences).use(openTail ? [[remarkOpenTail, openTail]] : []).use(remarkPlugins);
110
+ const COMMONMARK = unified().use(remarkParse).freeze();
111
+ const samePlugins = (cached, remarkPlugins) => cached.remarkPlugins.length === remarkPlugins.length && cached.remarkPlugins.every((plugin, index) => plugin === remarkPlugins[index]);
112
+ const rawHtmlEditorReaders = /* @__PURE__ */ new WeakMap();
113
+ const getRawHtmlEditorReader = (runtime) => {
114
+ const { remarkPlugins } = runtime.options;
115
+ const cached = rawHtmlEditorReaders.get(runtime.formats);
116
+ if (cached && samePlugins(cached, remarkPlugins)) return cached.read;
117
+ const parser = createMarkdownParser(runtime, materializeRemarkPlugins(remarkPlugins)).freeze();
118
+ const read = (source) => parser.runSync(parser.parse(source), source);
119
+ rawHtmlEditorReaders.set(runtime.formats, {
120
+ read,
121
+ remarkPlugins
122
+ });
123
+ return read;
124
+ };
125
+ const SCANNED_BLOCK_SYNTAX = /* @__PURE__ */ new Set([
126
+ ...DEFINITION_SYNTAX,
127
+ "mathFlow",
128
+ "table"
129
+ ]);
130
+ const SCANNED_INLINE_SYNTAX = /* @__PURE__ */ new Set([
131
+ ...DEFINITION_SYNTAX,
132
+ "attention",
133
+ "emailAutolink",
134
+ "mathText",
135
+ "protocolAutolink",
136
+ "strikethrough",
137
+ "tasklistCheck",
138
+ "wwwAutolink"
139
+ ]);
140
+ const SCANNED_SYNTAX = [[[
141
+ "document",
142
+ "contentInitial",
143
+ "flowInitial",
144
+ "flow"
145
+ ], SCANNED_BLOCK_SYNTAX], [[
146
+ "string",
147
+ "text",
148
+ "insideSpan"
149
+ ], SCANNED_INLINE_SYNTAX]];
150
+ const knownPluginSyntax = /* @__PURE__ */ new WeakMap();
151
+ /**
152
+ * remark-frontmatter's fences, a directive or another plugin's block can close
153
+ * on a later line or open at a segment's start, and another plugin's inline
154
+ * syntax can read the line it starts on or the labels defined before it, so a
155
+ * continued parse with one reads the whole source.
156
+ */
157
+ const knowsPluginSyntax = (runtime) => {
158
+ const { remarkPlugins } = runtime.options;
159
+ const cached = knownPluginSyntax.get(runtime.formats);
160
+ if (cached && samePlugins(cached, remarkPlugins)) return cached.scanned;
161
+ const scanned = [createMarkdownParser(runtime, materializeRemarkPlugins(remarkPlugins)).freeze().data("micromarkExtensions") ?? []].flat(Infinity).every((extension) => isMarkdownTagSyntax(extension) || SCANNED_SYNTAX.every(([fields, names]) => fields.every((field) => Object.values(extension?.[field] ?? {}).flat().every((construct) => !construct || !!construct.name && names.has(construct.name)))));
162
+ knownPluginSyntax.set(runtime.formats, {
163
+ remarkPlugins,
164
+ scanned
165
+ });
166
+ return scanned;
167
+ };
168
+ const markdownToSlateNodesWithRuntime = (runtime, text, options = {}, diagnostics = new MarkdownDiagnostics(), { inline, onRawHtmlEnd, openTail, rawHtmlBefore, ...hooks } = {}, source = text) => {
97
169
  const mergedOptions = {
98
170
  ...getMergedOptionsDeserialize(runtime, options, {
99
171
  diagnostics,
100
172
  positionsReferToSource: true,
101
- source: data
173
+ source
102
174
  }),
103
175
  ...hooks
104
176
  };
105
- return unified().use(remarkParse).use(remarkSeparateEscapes).use(remarkMarkdownTags, { tags: runtime.formats.tags }).use(remarkResolveMarkdownReferences).use(mergedOptions.remarkPlugins ?? []).use(remarkToSlate, mergedOptions).processSync(data).result;
177
+ return createMarkdownParser(runtime, mergedOptions.remarkPlugins, options.partial ? openTail : void 0).use(remarkToSlate, mergedOptions, importsRawHtml(runtime) ? inline ? "inline" : {
178
+ onRawHtmlEnd,
179
+ rawHtmlBefore
180
+ } : void 0).processSync(text).result;
106
181
  };
107
182
  const readLineEndingsAsLf = (node) => {
108
183
  if ("value" in node) node.value = node.value.replaceAll(/\r\n?/g, "\n");
@@ -118,19 +193,29 @@ const readLineEndingsAsLf = (node) => {
118
193
  }
119
194
  }
120
195
  };
121
- const remarkToSlate = function(options) {
196
+ const NO_RAW_HTML_BLOCKS = Object.freeze({ blocks: /* @__PURE__ */ new Set() });
197
+ const readRawHtmlBlocks = (root, { onRawHtmlEnd, rawHtmlBefore }) => {
198
+ const found = findMarkdownRawHtml(root, rawHtmlBefore);
199
+ onRawHtmlEnd?.(found.follows);
200
+ return found;
201
+ };
202
+ const remarkToSlate = function(options, rawHtml) {
122
203
  this.compiler = (node, file) => {
123
204
  if (String(file).includes("\r")) readLineEndingsAsLf(node);
124
205
  const syntaxNodes = checkMarkdownTreeLimits(node, options.limits, options.report);
125
206
  if (syntaxNodes === null) throw new ReportedMarkdownFailureError();
126
207
  options.onSyntaxNodes?.(syntaxNodes);
208
+ options.onSyntaxTree?.(node);
127
209
  cleanMarkdownDestinations(node, {
128
210
  lossPolicy: options.lossPolicy,
129
211
  phase: "parse",
130
212
  report: options.report,
131
213
  sourceLocation: options.sourceLocation
132
214
  });
133
- return mdastToSlate(node, options);
215
+ return mdastToSlate(node, rawHtml ? {
216
+ ...options,
217
+ rawHtml: rawHtml === "inline" ? NO_RAW_HTML_BLOCKS : readRawHtmlBlocks(node, rawHtml)
218
+ } : options);
134
219
  };
135
220
  };
136
221
  const remarkEscapeDollars = function() {
@@ -140,29 +225,51 @@ const remarkEscapeDollars = function() {
140
225
  inConstruct: "phrasing"
141
226
  }] });
142
227
  };
143
- const serializeMdWithRuntime = (runtime, options = {}, document, diagnostics = new MarkdownDiagnostics(), readRoots) => {
144
- const mergedOptions = getMergedOptionsSerialize(runtime, options, document, diagnostics, readRoots);
145
- const { remarkPlugins, value } = mergedOptions;
146
- const unwritable = { handlers: {} };
147
- const toRemarkProcessor = unified().use(remarkMarkdownTagWriter).use(remarkPlugins ?? []).use(remarkEscapeDollars).use(function remarkUnwritableNodeWriter() {
228
+ const createMarkdownStringifier = (context, unwritable) => {
229
+ const app = context.remarkStringifyOptions;
230
+ const { join: appJoin, ...appWithoutJoin } = app ?? {};
231
+ return unified().use(remarkMarkdownTagWriter).use(context.remarkPlugins).use(remarkEscapeDollars).use(function remarkUnwritableNodeWriter() {
148
232
  const data = this.data();
149
233
  (data.toMarkdownExtensions ??= []).push(unwritable);
234
+ }).use(function remarkRawHtmlJoin() {
235
+ if (!context.rawHtml) return;
236
+ const settings = this.data("settings") ?? {};
237
+ const join = app && Object.hasOwn(app, "join") ? appJoin : settings.join;
238
+ this.data("settings", {
239
+ ...settings,
240
+ join: [...join ?? [], joinRawHtmlFlow]
241
+ });
150
242
  }).use(remarkStringify, {
151
243
  emphasis: "_",
152
244
  resourceLink: false,
153
- ...mergedOptions.remarkStringifyOptions
245
+ ...context.rawHtml ? appWithoutJoin : app
154
246
  });
247
+ };
248
+ const flowEdgeOf = (node, edge) => {
249
+ if (node.type !== "blockquote" && node.type !== "list" && node.type !== "listItem") return node;
250
+ const prints = (child) => !printsNoText(child);
251
+ const child = edge === "first" ? node.children.find(prints) : node.children.findLast(prints);
252
+ return child && flowEdgeOf(child, edge);
253
+ };
254
+ const joinRawHtmlFlow = (left, right, parent) => parent.type !== "list" && [flowEdgeOf(left, "last"), flowEdgeOf(right, "first")].some((node) => node !== void 0 && isRawHtmlFlow(node)) ? 1 : void 0;
255
+ const emptyRootStartsWithByteOrderMark = (context) => createMarkdownStringifier(context, {}).stringify({
256
+ children: [],
257
+ type: "root"
258
+ }).startsWith("");
259
+ const encodeMarkdownBody = (context) => {
260
+ const unwritable = { handlers: {} };
261
+ const toRemarkProcessor = createMarkdownStringifier(context, unwritable);
155
262
  const tree = {
156
- children: convertNodesSerialize(value, mergedOptions),
263
+ children: convertNodesSerialize(context.value, context),
157
264
  type: "root"
158
265
  };
159
- finishMarkdownLists(tree, mergedOptions);
266
+ finishMarkdownLists(tree, context);
160
267
  cleanMarkdownDestinations(tree, {
161
- lossPolicy: mergedOptions.lossPolicy,
268
+ lossPolicy: context.lossPolicy,
162
269
  phase: "serialize",
163
- report: diagnostics.report
270
+ report: context.report
164
271
  });
165
- allocateMarkdownFootnoteLabels(tree, (label) => diagnostics.report({
272
+ allocateMarkdownFootnoteLabels(tree, (label) => context.report({
166
273
  action: "replaced",
167
274
  code: "markdown-unsupported-node",
168
275
  impact: "lossy",
@@ -178,10 +285,10 @@ const serializeMdWithRuntime = (runtime, options = {}, document, diagnostics = n
178
285
  [
179
286
  ...toRemarkProcessor.data("toMarkdownExtensions") ?? [],
180
287
  toRemarkProcessor.data("settings"),
181
- mergedOptions.remarkStringifyOptions
288
+ context.remarkStringifyOptions
182
289
  ].forEach((extension) => addMarkdownWriterKinds(configuredWriters, extension));
183
290
  const writable = /* @__PURE__ */ new Set([...COMMONMARK_WRITER_KINDS, ...configuredWriters]);
184
- const reportUnwritable = (nodeType) => diagnostics.report({
291
+ const reportUnwritable = (nodeType) => context.report({
185
292
  action: "dropped",
186
293
  code: "markdown-unsupported-node",
187
294
  impact: "lossy",
@@ -189,7 +296,7 @@ const serializeMdWithRuntime = (runtime, options = {}, document, diagnostics = n
189
296
  nodeType,
190
297
  owner: "markdown",
191
298
  phase: "serialize",
192
- severity: mergedOptions.lossPolicy === "allow" ? "warning" : "error"
299
+ severity: context.lossPolicy === "allow" ? "warning" : "error"
193
300
  });
194
301
  if (!configuredWriters.has("root")) dropUnwritableMarkdownNodes(transformed, writable, configuredWriters, reportUnwritable);
195
302
  addUnwritableMarkdownKinds(transformed, writable, (nodeType) => {
@@ -198,7 +305,218 @@ const serializeMdWithRuntime = (runtime, options = {}, document, diagnostics = n
198
305
  return "";
199
306
  };
200
307
  });
201
- return toRemarkProcessor.stringify(transformed);
308
+ return {
309
+ lastKind: transformed.children.filter((node) => !Object.hasOwn(unwritable.handlers, node.type)).findLast((node) => !printsNoText(node))?.type,
310
+ processor: toRemarkProcessor,
311
+ tree: transformed,
312
+ unwritable: new Set(Object.keys(unwritable.handlers))
313
+ };
314
+ };
315
+ const SETEXT_PROBE = {
316
+ children: [{
317
+ children: [{
318
+ type: "text",
319
+ value: "x"
320
+ }],
321
+ depth: 1,
322
+ type: "heading"
323
+ }],
324
+ type: "root"
325
+ };
326
+ const writesSetext = (processor) => processor.stringify(SETEXT_PROBE).includes("\n=");
327
+ const REFUSAL_ROUNDS = 3;
328
+ const holdsRawHtmlPiece = (node) => rawHtmlPieceOf(node) !== void 0 || "children" in node && node.children.some(holdsRawHtmlPiece);
329
+ const markedLeavesOf = (nodes) => nodes.flatMap((node) => TextApi.isText(node) ? node[RawHtmlPlugin.name] === true ? [node] : [] : markedLeavesOf(node.children));
330
+ /**
331
+ * Export and import both decide through it, so import marks only what export
332
+ * writes back.
333
+ */
334
+ const encodeRawHtmlBody = (context, rawHtml, refused, previousKind, readSetext) => {
335
+ const diagnostics = new MarkdownDiagnostics();
336
+ const readRoots = /* @__PURE__ */ new Set();
337
+ const body = encodeMarkdownBody({
338
+ ...context,
339
+ operation: {},
340
+ rawHtml: {
341
+ ...rawHtml,
342
+ refused
343
+ },
344
+ readRoots,
345
+ report: diagnostics.report
346
+ });
347
+ const holdsRawHtml = holdsRawHtmlPiece(body.tree);
348
+ const options = {
349
+ previousKind,
350
+ setext: holdsRawHtml && readSetext(body.processor),
351
+ unwritable: body.unwritable
352
+ };
353
+ return {
354
+ ...body,
355
+ diagnostics,
356
+ failing: holdsRawHtml ? decideRawHtmlBlocks(body.tree, rawHtml.decide, options) : [],
357
+ holdsRawHtml,
358
+ options,
359
+ readRoots
360
+ };
361
+ };
362
+ const copiesMarkedLeaf = (failing, document) => failing.some(({ leaves }) => leaves.some((leaf) => !document.has(leaf)));
363
+ const sameTextProperties = (left, right) => dequal({
364
+ ...left,
365
+ text: ""
366
+ }, {
367
+ ...right,
368
+ text: ""
369
+ });
370
+ const unmarkLeaves = (nodes, leaves) => {
371
+ const output = [];
372
+ let changed = false;
373
+ let joinsUnmarked = false;
374
+ for (const node of nodes) {
375
+ let next = node;
376
+ let unmarked = false;
377
+ if (!TextApi.isText(node)) next = unmarkElement(node, leaves);
378
+ else if (leaves.has(node)) {
379
+ const { [RawHtmlPlugin.name]: _marked, ...text } = node;
380
+ next = text;
381
+ unmarked = true;
382
+ }
383
+ changed ||= next !== node;
384
+ const previous = output.at(-1);
385
+ if ((unmarked || joinsUnmarked) && previous !== void 0 && TextApi.isText(previous) && TextApi.isText(next) && sameTextProperties(previous, next)) {
386
+ output[output.length - 1] = {
387
+ ...previous,
388
+ text: previous.text + next.text
389
+ };
390
+ joinsUnmarked = true;
391
+ } else {
392
+ output.push(next);
393
+ joinsUnmarked = unmarked;
394
+ }
395
+ }
396
+ return changed ? output : nodes;
397
+ };
398
+ const unmarkElement = (element, leaves) => {
399
+ const children = unmarkLeaves(element.children, leaves);
400
+ return children === element.children ? element : {
401
+ ...element,
402
+ children: [...children]
403
+ };
404
+ };
405
+ const unmarkBlocks = (blocks, unmarked) => blocks.map((block) => unmarkElement(block, unmarked));
406
+ const createBlocksContext = (runtime, blocks, { before = [], meta, roots }) => {
407
+ const document = createContentFormatDocument({
408
+ content: [...before, ...blocks],
409
+ meta,
410
+ roots
411
+ });
412
+ return {
413
+ ...getMergedOptionsSerialize(runtime, {}, document),
414
+ modelLocation: createMarkdownModelLocator(document, { from: before.length }),
415
+ value: [...blocks]
416
+ };
417
+ };
418
+ const keepWrittenRawHtml = (runtime, blocks, { previousKind, ...place } = {}) => {
419
+ const kept = {
420
+ blocks,
421
+ unmarkedAll: false
422
+ };
423
+ if (!importsRawHtml(runtime)) return kept;
424
+ const marked = markedLeavesOf(blocks);
425
+ if (marked.length === 0) return kept;
426
+ const context = createBlocksContext(runtime, blocks, place);
427
+ const { rawHtml } = context;
428
+ if (!rawHtml) return kept;
429
+ const document = new Set(marked);
430
+ const unmarkAll = () => ({
431
+ blocks: unmarkBlocks(blocks, document),
432
+ unmarkedAll: true
433
+ });
434
+ let failing;
435
+ let lastKind;
436
+ try {
437
+ ({failing, lastKind} = encodeRawHtmlBody(context, rawHtml, void 0, previousKind, writesSetext));
438
+ } catch (error) {
439
+ try {
440
+ encodeRawHtmlBody(context, rawHtml, "all", previousKind, writesSetext);
441
+ } catch {
442
+ return unmarkAll();
443
+ }
444
+ throw error;
445
+ }
446
+ const written = { lastKind };
447
+ if (failing.length === 0) return {
448
+ ...kept,
449
+ written
450
+ };
451
+ if (copiesMarkedLeaf(failing, document)) return unmarkAll();
452
+ return {
453
+ blocks: unmarkBlocks(blocks, new Set(failing.flatMap(({ leaves }) => leaves))),
454
+ unmarkedAll: false,
455
+ written
456
+ };
457
+ };
458
+ /**
459
+ * With `RawHtmlPlugin` installed and its mark not in `plainMarks`, each block
460
+ * of marked text decides on the tree
461
+ * the writer prints, and the document encodes again with every leaf of each
462
+ * failing block refused, so the writers escape that text as they escape any
463
+ * text. A refused leaf can sit in another block too, so encoding repeats until
464
+ * no block fails, for at most `REFUSAL_ROUNDS` rounds, because a chain of
465
+ * blocks that share leaves would otherwise encode once per leaf. `previousKind` is the
466
+ * type of the last root node the copied chunk before this one printed.
467
+ */
468
+ const writeMarkdownBody = (context, previousKind) => {
469
+ const { rawHtml } = context;
470
+ if (!rawHtml) {
471
+ const { lastKind, processor, tree } = encodeMarkdownBody(context);
472
+ return {
473
+ data: processor.stringify(tree),
474
+ holdsRawHtml: false,
475
+ lastKind
476
+ };
477
+ }
478
+ let setext;
479
+ const encode = (refused) => encodeRawHtmlBody(context, rawHtml, refused, previousKind, (processor) => {
480
+ setext ??= writesSetext(processor);
481
+ return setext;
482
+ });
483
+ let body = encode();
484
+ const documentLeaves = new Set(body.failing.length > 0 ? markedLeavesOf([...context.value, ...Object.values(context.document.roots ?? {}).flat()]) : []);
485
+ const report = ({ leaves, reason }) => context.report({
486
+ code: "markdown-unsafe-content",
487
+ impact: "lossless",
488
+ message: `Markdown raw HTML cannot be written as HTML at its place (${reason}); it was written as text.`,
489
+ model: context.modelLocation(leaves.find((leaf) => documentLeaves.has(leaf)) ?? leaves[0]),
490
+ nodeType: "html",
491
+ phase: "serialize",
492
+ severity: "warning"
493
+ });
494
+ const refused = /* @__PURE__ */ new Set();
495
+ for (let round = 0; body.failing.length > 0; round += 1) {
496
+ const copied = copiesMarkedLeaf(body.failing, documentLeaves);
497
+ if (copied || round === REFUSAL_ROUNDS) {
498
+ const reason = copied ? "copied-leaf" : "shared-leaf";
499
+ decideRawHtmlBlocks(body.tree, () => ({
500
+ ok: false,
501
+ reason
502
+ }), body.options).forEach(report);
503
+ body = encode("all");
504
+ break;
505
+ }
506
+ for (const block of body.failing) {
507
+ report(block);
508
+ block.leaves.forEach((leaf) => refused.add(leaf));
509
+ }
510
+ body = encode(new Set(refused));
511
+ }
512
+ const data = body.processor.stringify(body.tree);
513
+ body.diagnostics.all().forEach(context.report);
514
+ body.readRoots.forEach((root) => context.readRoots.add(root));
515
+ return {
516
+ data,
517
+ holdsRawHtml: body.holdsRawHtml,
518
+ lastKind: body.lastKind
519
+ };
202
520
  };
203
521
  const COMMONMARK_WRITER_KINDS = [
204
522
  "blockquote",
@@ -264,28 +582,249 @@ const reportByteLimit = (source, options, diagnostics) => {
264
582
  return true;
265
583
  };
266
584
  const previewSource = (runtime, source, options) => options.partial ? trimIncompleteMarkdownTag(source, runtime.formats.tags) : source;
267
- const runParsedNodes = (runtime, source, options, diagnostics, hooks) => {
585
+ const runParsedNodes = (runtime, source, options, diagnostics, hooks, text = source) => {
268
586
  if (reportByteLimit(source, options, diagnostics)) return null;
269
587
  if (landsMarkdownParagraph(runtime.registry) && runtime.state.schema.element("markdown:paragraph")) {
270
588
  reportUnlandedParagraph(diagnostics, `The schema declares "${UNLANDED_MARKDOWN_PARAGRAPH_TYPE}", which Markdown reserves for its own paragraph.`);
271
589
  return null;
272
590
  }
273
591
  try {
274
- return markdownToSlateNodesWithRuntime(runtime, previewSource(runtime, source, options), options, diagnostics, hooks);
592
+ return markdownToSlateNodesWithRuntime(runtime, previewSource(runtime, text, options), options, diagnostics, hooks, source);
275
593
  } catch (error) {
276
594
  if (error instanceof ReportedMarkdownFailureError) return null;
277
595
  throw error;
278
596
  }
279
597
  };
280
598
  const markdownCheckpoints = /* @__PURE__ */ new WeakMap();
281
- const snapshotBlocks = (runtime, parsed) => ContentSlice.closed(normalizeDocumentChildren(runtime, parsed)).content;
599
+ const snapshotBlocks = (runtime, parsed) => ContentSlice.closed([...keepWrittenRawHtml(runtime, normalizeDocumentChildren(runtime, parsed)).blocks]).content;
600
+ const NOTHING_COMMITTED = {
601
+ follows: "block",
602
+ printedKind: void 0
603
+ };
604
+ const rawHtmlAfter = (committed) => committed.at(-1) ?? NOTHING_COMMITTED;
605
+ const continueBlocks = (runtime, parsed, committed, prior) => {
606
+ const normalized = normalizeDocumentChildren(runtime, parsed);
607
+ if (!importsRawHtml(runtime)) return {
608
+ nodes: ContentSlice.closed([...normalized]).content,
609
+ printedKind: void 0
610
+ };
611
+ const after = rawHtmlAfter(committed);
612
+ if (after.printedKind === "list" && mayJoinList(normalized[0], runtime)) return null;
613
+ const before = prior ?? committed.flatMap((segment) => segment.nodes);
614
+ const { blocks, unmarkedAll, written } = keepWrittenRawHtml(runtime, normalized, {
615
+ before,
616
+ previousKind: after.printedKind
617
+ });
618
+ if (unmarkedAll) return null;
619
+ const nodes = ContentSlice.closed([...blocks]).content;
620
+ try {
621
+ const { lastKind } = written ?? encodeMarkdownBody(createBlocksContext(runtime, blocks, { before }));
622
+ return {
623
+ nodes,
624
+ printedKind: lastKind ?? after.printedKind
625
+ };
626
+ } catch {
627
+ return null;
628
+ }
629
+ };
630
+ const MAX_COPIED_SEGMENT_LENGTH = 2e3;
631
+ const fitsSlice = (runtime, blocks) => {
632
+ if (landsMarkdownParagraph(runtime.registry) && findMarkdownParagraph(blocks, [])) return false;
633
+ try {
634
+ runtime.state.schema.assertFragment(blocks);
635
+ return true;
636
+ } catch (error) {
637
+ if (error instanceof EditorSchemaValidationError) return false;
638
+ throw error;
639
+ }
640
+ };
641
+ const sliceFit = (runtime) => ({
642
+ fits: (blocks) => fitsSlice(runtime, blocks),
643
+ ready: (parsed) => snapshotBlocks(runtime, parsed)
644
+ });
645
+ const deferredFit = (runtime) => ({
646
+ fits: () => true,
647
+ ready: (parsed) => normalizeDocumentChildren(runtime, parsed)
648
+ });
649
+ const headJoinsOpenPart = (runtime, parsed, headEnd) => [parsed[headEnd - 1], parsed[headEnd]].every((node) => !!node && (TextApi.isText(node) || runtime.state.schema.isInline(node)));
650
+ const markKindsOf = (runtime) => {
651
+ const keys = (kind) => new Set([...runtime.formats.markWriters].filter(([, writers]) => writers.some((writer) => writer.kind === kind)).map(([key]) => key));
652
+ return {
653
+ emphasis: keys("emphasis"),
654
+ exact: new Set(importsRawHtml(runtime) ? [RawHtmlPlugin.name] : []),
655
+ strong: keys("strong")
656
+ };
657
+ };
658
+ const GRAMMAR_PROBE = "a**「b」**\n\n**b**\n\na~~「b」~~\n\n~~b~~";
659
+ const grammars = /* @__PURE__ */ new WeakMap();
660
+ const probeGrammar = (runtime) => {
661
+ const { remarkPlugins } = runtime.options;
662
+ const known = grammars.get(remarkPlugins);
663
+ if (known) return known;
664
+ const grammar = readGrammar(runtime);
665
+ grammars.set(remarkPlugins, grammar);
666
+ return grammar;
667
+ };
668
+ const readGrammar = (runtime) => {
669
+ let probe;
670
+ try {
671
+ probe = [...createMarkdownParser(runtime, materializeRemarkPlugins(runtime.options.remarkPlugins)).parse(GRAMMAR_PROBE).children];
672
+ } catch {
673
+ return {
674
+ attention: null,
675
+ strikethrough: null
676
+ };
677
+ }
678
+ const [cjkStrong, strong, cjkDelete, deleted] = probe;
679
+ const holds = (node, type) => node?.type === "paragraph" && node.children.some((child) => child.type === type);
680
+ return {
681
+ attention: holds(strong, "strong") ? holds(cjkStrong, "strong") ? "cjkFriendly" : "commonmark" : null,
682
+ strikethrough: holds(deleted, "delete") ? holds(cjkDelete, "delete") ? "cjkFriendly" : "gfm" : null
683
+ };
684
+ };
685
+ const offsetOf = (diagnostic) => ("source" in diagnostic ? diagnostic.source?.start?.offset : void 0) ?? NaN;
686
+ const diagnosticKeys = (diagnostics, sharedOffset) => diagnostics.map((diagnostic) => {
687
+ const { source: _source, ...rest } = diagnostic;
688
+ return JSON.stringify([sharedOffset(offsetOf(diagnostic)), rest]);
689
+ }).sort().join("\n");
690
+ const hasUnplaced = (diagnostics) => diagnostics.some((diagnostic) => Number.isNaN(offsetOf(diagnostic)));
691
+ const isZeroWidthAt = (diagnostic, offset) => "source" in diagnostic && diagnostic.source?.start?.offset === offset && diagnostic.source.end?.offset === offset;
692
+ const inSourceOrder = (children) => {
693
+ let end = 0;
694
+ return children.every((child) => {
695
+ const start = child.position?.start.offset;
696
+ if (start === void 0 || start < end) return false;
697
+ end = child.position?.end.offset ?? Number.POSITIVE_INFINITY;
698
+ return true;
699
+ });
700
+ };
701
+ const rootBefore = (root, from) => {
702
+ if (!inSourceOrder(root.children)) return null;
703
+ const found = root.children.findIndex((child) => (child.position?.start.offset ?? 0) >= from);
704
+ const index = found === -1 ? root.children.length : found;
705
+ if ((root.children[index - 1]?.position?.end.offset ?? from) > from) return null;
706
+ return {
707
+ index,
708
+ root,
709
+ spentNodes: (checkMarkdownTreeLimits({
710
+ children: root.children.slice(0, index),
711
+ type: "root"
712
+ }, {
713
+ maxBytes: Infinity,
714
+ maxDepth: Infinity,
715
+ maxNodes: Infinity
716
+ }, () => {}) ?? 1) - 1
717
+ };
718
+ };
719
+ const closeOpenTail = (runtime, options, received, plan, before, from, hooks, fit, kept) => {
720
+ const limits = markdownParseLimits(options);
721
+ const diagnostics = new MarkdownDiagnostics();
722
+ let children = NaN;
723
+ let copy;
724
+ try {
725
+ const parsed = markdownToSlateNodesWithRuntime(runtime, plan.copy.text, {
726
+ ...options,
727
+ limits: {
728
+ ...limits,
729
+ maxNodes: limits.maxNodes - before.spentNodes
730
+ }
731
+ }, diagnostics, {
732
+ inline: hooks.inline,
733
+ onSyntaxTree: (root) => {
734
+ children = root.children.length;
735
+ },
736
+ openTail: {
737
+ copy: plan.copy,
738
+ heldFromEnd: plan.heldFromEnd,
739
+ mode: "pairCopy"
740
+ },
741
+ previousRootSibling: before.root.children[before.index - 1] ?? hooks.previousRootSibling ?? null
742
+ });
743
+ if (diagnostics.failure() || children !== before.root.children.length - before.index) return null;
744
+ copy = fit.ready(parsed);
745
+ } catch {
746
+ return null;
747
+ }
748
+ const closersAt = plan.copy.closers.from;
749
+ return kept <= received.blocks.length && keepsReceived(received.blocks.slice(kept), copy, plan.copy, markKindsOf(runtime)) && !hasUnplaced(diagnostics.all()) && diagnosticKeys(diagnostics.all(), (offset) => offset < closersAt ? offset + from : null) === diagnosticKeys(received.diagnostics.filter((diagnostic) => offsetOf(diagnostic) >= from), (offset) => offset < from + closersAt ? offset : null) && fit.fits(copy) ? Object.freeze([...received.blocks.slice(0, kept), ...copy]) : null;
750
+ };
751
+ const fitsByteLimit = (source, options) => new TextEncoder().encode(source).byteLength <= markdownParseLimits(options).maxBytes;
752
+ const parsesInSegments = (source, options) => fitsByteLimit(source, options) && !MARKDOWN_DEFINITION.test(source);
753
+ const openSegmentStart = (runtime, source, options, start = 0) => parsesInSegments(source, options) ? findMarkdownSegmentBoundaries(previewSource(runtime, source, options), 0, runtime.formats.tags).at(-1) ?? start : null;
754
+ const deliverOpenTail = (runtime, source, start, options, diagnostics, hooks, segment) => {
755
+ const text = source.slice(start);
756
+ const { committed, fit } = segment;
757
+ const grammar = probeGrammar(runtime);
758
+ const repairable = grammar.attention ?? grammar.strikethrough;
759
+ const readHooks = committed ? {
760
+ ...hooks,
761
+ rawHtmlBefore: rawHtmlAfter(committed).follows
762
+ } : hooks;
763
+ const ready = (parsed) => committed ? continueBlocks(runtime, parsed, committed)?.nodes ?? null : fit.ready(parsed);
764
+ if (source.startsWith("") || !repairable) {
765
+ const parsed = runParsedNodes(runtime, text, options, diagnostics, readHooks);
766
+ return parsed && ready(parsed);
767
+ }
768
+ const from = segment.start === null || source.length - segment.start > MAX_COPIED_SEGMENT_LENGTH ? null : segment.start - start;
769
+ const received = new MarkdownDiagnostics();
770
+ const read = {};
771
+ const onPlan = (plan) => {
772
+ read.plan = plan;
773
+ };
774
+ const parsed = runParsedNodes(runtime, text, options, received, {
775
+ ...readHooks,
776
+ onRootBlocks: (counts) => {
777
+ read.blocks = counts;
778
+ },
779
+ onSyntaxTree: (root) => {
780
+ if (from !== null) read.before = rootBefore(root, from);
781
+ },
782
+ openTail: from === null ? {
783
+ grammar,
784
+ mode: "planHold",
785
+ onPlan
786
+ } : {
787
+ from,
788
+ grammar,
789
+ mode: "planCopy",
790
+ onPlan
791
+ }
792
+ });
793
+ const blocks = parsed && !received.failure() ? ready(parsed) : null;
794
+ const { before, plan } = read;
795
+ if (plan?.heldFromEnd.length && !(blocks && fit.fits(blocks))) {
796
+ if (!segment.retriesUncut) return null;
797
+ const uncut = runParsedNodes(runtime, text, options, diagnostics, readHooks);
798
+ return uncut && ready(uncut);
799
+ }
800
+ const receivedAll = received.all();
801
+ receivedAll.forEach(diagnostics.report);
802
+ const headEnd = (read.blocks ?? []).slice(0, before?.index).reduce((sum, n) => sum + n, 0);
803
+ if (!parsed || !blocks || headJoinsOpenPart(runtime, parsed, headEnd) || !plan?.copy || !before || from === null || hasUnplaced([...segment.keptDiagnostics, ...receivedAll]) || segment.keptDiagnostics.some((diagnostic) => isZeroWidthAt(diagnostic, from + start)) || receivedAll.some((diagnostic) => isZeroWidthAt(diagnostic, from))) return blocks;
804
+ return closeOpenTail(runtime, options, {
805
+ blocks,
806
+ diagnostics: receivedAll
807
+ }, {
808
+ ...plan,
809
+ copy: plan.copy
810
+ }, before, from, hooks, fit, normalizeDocumentChildren(runtime, parsed.slice(0, headEnd)).length) ?? blocks;
811
+ };
282
812
  const convertMarkdownSource = (runtime, source, options, diagnostics, reuse) => {
283
813
  const limits = markdownParseLimits(options);
284
814
  const limitsKey = JSON.stringify(limits);
285
815
  const lossPolicy = options.lossPolicy ?? "reject";
286
816
  const full = () => {
287
- const parsed = runParsedNodes(runtime, source, options, diagnostics);
288
- const nodes = parsed && snapshotBlocks(runtime, parsed);
817
+ let nodes;
818
+ if (options.partial) nodes = deliverOpenTail(runtime, source, 0, options, diagnostics, {}, {
819
+ fit: sliceFit(runtime),
820
+ keptDiagnostics: [],
821
+ retriesUncut: true,
822
+ start: openSegmentStart(runtime, source, options)
823
+ });
824
+ else {
825
+ const parsed = runParsedNodes(runtime, source, options, diagnostics);
826
+ nodes = parsed && snapshotBlocks(runtime, parsed);
827
+ }
289
828
  return {
290
829
  checkpoint: reuse ? {
291
830
  limits: limitsKey,
@@ -297,7 +836,7 @@ const convertMarkdownSource = (runtime, source, options, diagnostics, reuse) =>
297
836
  unvalidated: nodes ?? []
298
837
  };
299
838
  };
300
- if (!reuse?.previous || MARKDOWN_DEFINITION.test(source) || new TextEncoder().encode(source).byteLength > limits.maxBytes) return full();
839
+ if (!reuse?.previous || readsMarkdownWhole(source) || !knowsPluginSyntax(runtime) || !fitsByteLimit(source, options)) return full();
301
840
  const old = markdownCheckpoints.get(reuse.previous);
302
841
  const previousSegments = !!old && old.editor === reuse.editor && old.formats === runtime.formats && old.limits === limitsKey && old.pluginStates.length === reuse.pluginStates.length && old.pluginStates.every((state, index) => state === reuse.pluginStates[index]) && source.startsWith(old.source) ? old.segments : [];
303
842
  const kept = old?.lossPolicy === lossPolicy ? previousSegments.length : previousSegments.findIndex((segment) => segment.diagnostics.length > 0);
@@ -326,58 +865,86 @@ const convertMarkdownSource = (runtime, source, options, diagnostics, reuse) =>
326
865
  const local = new MarkdownDiagnostics();
327
866
  let count = 0;
328
867
  let lastRoot = null;
868
+ let ordered = false;
869
+ let { follows } = rawHtmlAfter(segments);
329
870
  const parsed = runParsedNodes(runtime, source.slice(stableEnd, end), {
330
871
  ...options,
331
872
  limits: {
332
873
  ...limits,
333
874
  maxNodes: limits.maxNodes - syntaxNodes + 1
334
875
  },
335
- partial: end === source.length
876
+ partial: false
336
877
  }, local, {
878
+ onRawHtmlEnd: (read) => {
879
+ follows = read;
880
+ },
337
881
  onRootChildren: (children) => {
338
882
  lastRoot = children.at(-1) ?? null;
883
+ ordered = inSourceOrder(children) && children.every((child) => child.position?.end.offset !== void 0);
339
884
  },
340
885
  onSyntaxNodes: (nodes) => {
341
886
  count = nodes;
342
887
  },
343
- previousRootSibling: segments.at(-1)?.lastRoot ?? null
888
+ previousRootSibling: segments.at(-1)?.lastRoot ?? null,
889
+ rawHtmlBefore: follows
344
890
  });
345
891
  if (!parsed || local.failure()) return null;
346
892
  const lines = countMarkdownLines(source, stableEnd);
347
893
  return {
348
894
  diagnostics: local.all().map((diagnostic) => shiftMarkdownDiagnostic(diagnostic, lines, stableEnd)),
895
+ follows,
349
896
  lastRoot,
350
897
  parsed,
898
+ placed: ordered && !hasUnplaced(local.all()),
351
899
  syntaxNodes: count
352
900
  };
353
901
  };
354
- const boundaries = findMarkdownSegmentBoundaries(source, stableEnd, runtime.formats.tags);
902
+ const boundaries = findMarkdownSegmentBoundaries(previewSource(runtime, source, options), stableEnd, runtime.formats.tags);
355
903
  let nextTry = 0;
904
+ const prior = segments.flatMap((segment) => segment.nodes);
356
905
  for (const [index, boundary] of boundaries.entries()) {
357
906
  if (index < nextTry) continue;
358
907
  const segment = convertRange(boundary);
359
908
  if (!segment) return full();
360
- if (getMarkdownTagRepair(segment.lastRoot ?? {})?.repair === "unclosed") {
909
+ const { lastRoot } = segment;
910
+ if (!segment.placed || getMarkdownTagRepair(lastRoot ?? {})?.repair === "unclosed" || holdsMarkdownSegmentOpen(source.slice(stableEnd, boundary), lastRoot)) {
361
911
  nextTry = boundaries.length - 1;
362
912
  continue;
363
913
  }
364
914
  const last = segment.parsed.at(-1);
365
915
  if (!last || TextApi.isText(last) || runtime.state.schema.isInline(last)) continue;
916
+ const committed = continueBlocks(runtime, segment.parsed, segments, prior);
917
+ if (!committed) return full();
366
918
  segments.push({
919
+ ...committed,
367
920
  diagnostics: segment.diagnostics,
368
921
  end: boundary,
922
+ follows: segment.follows,
369
923
  lastRoot: segment.lastRoot,
370
- nodes: snapshotBlocks(runtime, segment.parsed),
371
924
  syntaxNodes: segment.syntaxNodes
372
925
  });
926
+ for (const node of committed.nodes) prior.push(node);
373
927
  syntaxNodes += segment.syntaxNodes - 1;
374
928
  stableEnd = boundary;
375
929
  }
376
- const tail = convertRange(source.length);
377
- if (!tail) return full();
930
+ const local = new MarkdownDiagnostics();
931
+ const tailNodes = deliverOpenTail(runtime, source, stableEnd, {
932
+ ...options,
933
+ limits: {
934
+ ...limits,
935
+ maxNodes: limits.maxNodes - syntaxNodes + 1
936
+ }
937
+ }, local, { previousRootSibling: segments.at(-1)?.lastRoot ?? null }, {
938
+ committed: segments,
939
+ fit: sliceFit(runtime),
940
+ keptDiagnostics: segments.flatMap((segment) => segment.diagnostics),
941
+ retriesUncut: false,
942
+ start: boundaries.at(-1) ?? stableEnd
943
+ });
944
+ if (!tailNodes || local.failure()) return full();
378
945
  for (const segment of segments) segment.diagnostics.forEach(diagnostics.report);
379
- tail.diagnostics.forEach(diagnostics.report);
380
- const tailNodes = snapshotBlocks(runtime, tail.parsed);
946
+ const lines = countMarkdownLines(source, stableEnd);
947
+ for (const diagnostic of local.all()) diagnostics.report(shiftMarkdownDiagnostic(diagnostic, lines, stableEnd));
381
948
  return {
382
949
  checkpoint: {
383
950
  limits: limitsKey,
@@ -385,7 +952,7 @@ const convertMarkdownSource = (runtime, source, options, diagnostics, reuse) =>
385
952
  segments,
386
953
  source
387
954
  },
388
- nodes: Object.freeze([...segments.flatMap((segment) => segment.nodes), ...tailNodes]),
955
+ nodes: Object.freeze([...prior, ...tailNodes]),
389
956
  unvalidated: [...segments.slice(reused).flatMap((segment) => segment.nodes), ...tailNodes]
390
957
  };
391
958
  };
@@ -533,22 +1100,60 @@ const sliceParseFailure = (diagnostics) => {
533
1100
  ok: false
534
1101
  });
535
1102
  };
536
- const parseMarkdownDocumentWithRuntime = (runtime, source, options = {}) => {
537
- const diagnostics = new MarkdownDiagnostics();
538
- const parsed = runParsedNodes(runtime, source, options, diagnostics);
539
- if (!parsed || diagnostics.failure()) return documentParseFailure(diagnostics);
1103
+ const deliverMarkdownDocument = (runtime, options, frontmatter, parsed, diagnostics) => {
540
1104
  const children = normalizeDocumentChildren(runtime, parsed);
541
- const input = Object.freeze({ children: landsMarkdownParagraph(runtime.registry) ? landMarkdownParagraphs(runtime, children, diagnostics) : children });
542
- if (diagnostics.failure()) return documentParseFailure(diagnostics);
1105
+ const input = Object.freeze({
1106
+ children: landsMarkdownParagraph(runtime.registry) ? landMarkdownParagraphs(runtime, children, diagnostics) : children,
1107
+ ...frontmatter ? { meta: { [MARKDOWN_FRONTMATTER_KEY]: {
1108
+ format: frontmatter.format,
1109
+ value: frontmatter.value
1110
+ } } } : {}
1111
+ });
1112
+ if (diagnostics.failure()) return null;
543
1113
  let document;
544
1114
  try {
545
1115
  document = fitMarkdownDocument(runtime, input, options, diagnostics);
546
- if (diagnostics.failure()) return documentParseFailure(diagnostics);
1116
+ if (diagnostics.failure()) return null;
1117
+ } catch (error) {
1118
+ reportSchemaInvalid(error, diagnostics);
1119
+ return null;
1120
+ }
1121
+ const { blocks } = keepWrittenRawHtml(runtime, document.children, document);
1122
+ if (blocks !== document.children) document = {
1123
+ ...document,
1124
+ children: [...blocks]
1125
+ };
1126
+ try {
547
1127
  runtime.state.schema.assertDocument(document);
548
1128
  } catch (error) {
549
1129
  reportSchemaInvalid(error, diagnostics);
550
- return documentParseFailure(diagnostics);
1130
+ return null;
1131
+ }
1132
+ return document;
1133
+ };
1134
+ const parseMarkdownDocumentWithRuntime = (runtime, source, options = {}) => {
1135
+ const diagnostics = new MarkdownDiagnostics();
1136
+ const frontmatter = readMarkdownFrontmatter(source);
1137
+ const text = frontmatter ? blankMarkdownFrontmatter(source, frontmatter.end) : source;
1138
+ let document = null;
1139
+ if (options.partial) {
1140
+ if (reportByteLimit(source, options, diagnostics)) return documentParseFailure(diagnostics);
1141
+ const preview = new MarkdownDiagnostics();
1142
+ const blocks = deliverOpenTail(runtime, text, 0, options, preview, {}, {
1143
+ fit: deferredFit(runtime),
1144
+ keptDiagnostics: [],
1145
+ retriesUncut: true,
1146
+ start: openSegmentStart(runtime, text, options, frontmatter?.end)
1147
+ });
1148
+ if (!blocks || preview.failure()) return documentParseFailure(preview);
1149
+ document = deliverMarkdownDocument(runtime, options, frontmatter, blocks, preview);
1150
+ if (document) preview.all().forEach(diagnostics.report);
1151
+ }
1152
+ if (!document) {
1153
+ const parsed = runParsedNodes(runtime, source, options, diagnostics, {}, text);
1154
+ document = parsed && !diagnostics.failure() ? deliverMarkdownDocument(runtime, options, frontmatter, parsed, diagnostics) : null;
551
1155
  }
1156
+ if (!document || diagnostics.failure()) return documentParseFailure(diagnostics);
552
1157
  return Object.freeze({
553
1158
  diagnostics: diagnostics.warnings(),
554
1159
  document,
@@ -583,10 +1188,33 @@ const parseMarkdownSliceWithRuntime = (runtime, source, options = {}, reuse) =>
583
1188
  };
584
1189
  const LEADING_WHITESPACE = /^\s*/;
585
1190
  const TRAILING_WHITESPACE = /\s*$/;
1191
+ const whitespace = (value) => value ? [{ text: value }] : [];
1192
+ const deliverMarkdownInline = (runtime, source, parsed, diagnostics) => {
1193
+ const blocks = normalizeDocumentChildren(runtime, parsed);
1194
+ const [block] = blocks;
1195
+ if (blocks.length !== 1 || block?.type !== getMarkdownParagraphType(runtime.registry)) {
1196
+ diagnostics.report({
1197
+ actual: blocks.length,
1198
+ code: "markdown-inline-blocks",
1199
+ message: blocks.length > 1 ? `Inline Markdown produced ${blocks.length} blocks. Use parseSlice for block content.` : `Inline Markdown produced a "${block?.type}" block. Use parseSlice for block content.`,
1200
+ severity: "error"
1201
+ });
1202
+ return null;
1203
+ }
1204
+ const paragraph = {
1205
+ ...block,
1206
+ children: [
1207
+ ...whitespace(LEADING_WHITESPACE.exec(source)?.[0] ?? ""),
1208
+ ...block.children,
1209
+ ...whitespace(TRAILING_WHITESPACE.exec(source)?.[0] ?? "")
1210
+ ]
1211
+ };
1212
+ const [kept = paragraph] = keepWrittenRawHtml(runtime, [paragraph]).blocks;
1213
+ return kept.children;
1214
+ };
586
1215
  const parseMarkdownInlineWithRuntime = (runtime, source, options = {}) => {
587
1216
  const diagnostics = new MarkdownDiagnostics();
588
1217
  const trimmed = source.trim();
589
- const whitespace = (value) => value ? [{ text: value }] : [];
590
1218
  if (!trimmed) {
591
1219
  if (reportByteLimit(source, options, diagnostics)) return sliceParseFailure(diagnostics);
592
1220
  return Object.freeze({
@@ -595,34 +1223,94 @@ const parseMarkdownInlineWithRuntime = (runtime, source, options = {}) => {
595
1223
  slice: ContentSlice.closed(whitespace(source))
596
1224
  });
597
1225
  }
598
- const parsed = runParsedNodes(runtime, trimmed, options, diagnostics);
599
- if (!parsed || diagnostics.failure()) return sliceParseFailure(diagnostics);
600
- const blocks = normalizeDocumentChildren(runtime, parsed);
601
- const [block] = blocks;
602
- if (blocks.length !== 1 || block?.type !== getMarkdownParagraphType(runtime.registry)) {
603
- diagnostics.report({
604
- actual: blocks.length,
605
- code: "markdown-inline-blocks",
606
- message: blocks.length > 1 ? `Inline Markdown produced ${blocks.length} blocks. Use parseSlice for block content.` : `Inline Markdown produced a "${block?.type}" block. Use parseSlice for block content.`,
607
- severity: "error"
608
- });
609
- return sliceParseFailure(diagnostics);
1226
+ let children = null;
1227
+ if (options.partial) {
1228
+ const preview = new MarkdownDiagnostics();
1229
+ const read = fitsByteLimit(source.trimStart(), options) ? source.trimStart() : trimmed;
1230
+ let blocks;
1231
+ try {
1232
+ blocks = deliverOpenTail(runtime, read, 0, options, preview, { inline: true }, {
1233
+ fit: deferredFit(runtime),
1234
+ keptDiagnostics: [],
1235
+ retriesUncut: true,
1236
+ start: openSegmentStart(runtime, read, options)
1237
+ });
1238
+ } catch {
1239
+ blocks = null;
1240
+ }
1241
+ children = blocks && !preview.failure() ? deliverMarkdownInline(runtime, source.trimEnd(), blocks, preview) : null;
1242
+ if (children) preview.all().forEach(diagnostics.report);
610
1243
  }
1244
+ if (!children) {
1245
+ const parsed = runParsedNodes(runtime, trimmed, options, diagnostics, { inline: true });
1246
+ children = parsed && !diagnostics.failure() ? deliverMarkdownInline(runtime, source, parsed, diagnostics) : null;
1247
+ }
1248
+ if (!children || diagnostics.failure()) return sliceParseFailure(diagnostics);
611
1249
  return Object.freeze({
612
1250
  diagnostics: diagnostics.warnings(),
613
1251
  ok: true,
614
- slice: ContentSlice.closed([
615
- ...whitespace(LEADING_WHITESPACE.exec(source)?.[0] ?? ""),
616
- ...block.children,
617
- ...whitespace(TRAILING_WHITESPACE.exec(source)?.[0] ?? "")
618
- ])
1252
+ slice: ContentSlice.closed(children)
619
1253
  });
620
1254
  };
1255
+ const writeStoredMarkdownFrontmatter = (document) => {
1256
+ const stored = document.meta?.[MARKDOWN_FRONTMATTER_KEY];
1257
+ if (stored === void 0) return null;
1258
+ if (!hasMarkdownFrontmatterShape(stored)) return { reason: "shape" };
1259
+ if (!isMarkdownFrontmatter(stored)) return { reason: "format" };
1260
+ const block = writeMarkdownFrontmatter(stored);
1261
+ return block === null ? { reason: "unreadable" } : { block };
1262
+ };
1263
+ const FRONTMATTER_OMITTED_MESSAGES = {
1264
+ format: "its format is neither \"yaml\" nor \"toml\"",
1265
+ shape: "it is not an object of exactly a string \"format\" and a string \"value\"",
1266
+ unreadable: "the written block would not read back as the same value"
1267
+ };
1268
+ const withoutElementIds = (nodes) => nodes.map((node) => {
1269
+ if (!ElementApi.isElement(node)) return node;
1270
+ const { id: _id, ...kept } = node;
1271
+ return {
1272
+ ...kept,
1273
+ children: withoutElementIds(node.children)
1274
+ };
1275
+ });
1276
+ const isFittedEmptyDocument = (runtime, document) => {
1277
+ const fitted = runtime.state.schema.fitDocument({ children: [] }).children;
1278
+ if (document.children.length !== fitted.length) return false;
1279
+ const comparable = (children) => runtime.elementId ? withoutElementIds(children) : children;
1280
+ return dequal(comparable(document.children), comparable(fitted));
1281
+ };
1282
+ const isFrontmatterKind = (kind) => kind === "yaml" || kind === "toml";
1283
+ /**
1284
+ * Reads the output as a UTF-8 file gives it back: each lone surrogate
1285
+ * replaced, with and without the byte-order mark a file read may drop.
1286
+ */
1287
+ const readsBackMarkdownFrontmatter = (runtime, context, data) => {
1288
+ const readsBlock = (form) => {
1289
+ if (!opensMarkdownFrontmatterFence(form)) return false;
1290
+ const file = form.toWellFormed();
1291
+ if (readMarkdownFrontmatter(file)) return true;
1292
+ if (context.remarkPlugins.length === 0) return false;
1293
+ return isFrontmatterKind(createMarkdownParser(runtime, context.remarkPlugins).parse(file).children[0]?.type);
1294
+ };
1295
+ return readsBlock(data) || data.startsWith("") && readsBlock(data.slice(1));
1296
+ };
1297
+ const writeMarkdownDocument = (runtime, context, frontmatter) => {
1298
+ if (frontmatter !== null && isFittedEmptyDocument(runtime, context.document)) return `${emptyRootStartsWithByteOrderMark(context) ? "" : ""}${frontmatter}`;
1299
+ const { data, holdsRawHtml, lastKind } = writeMarkdownBody(context);
1300
+ const insertAfterRootByteOrderMark = (text, body) => {
1301
+ const rootMarkLength = body.startsWith("") && emptyRootStartsWithByteOrderMark(context) ? 1 : 0;
1302
+ return `${body.slice(0, rootMarkLength)}${text}${body.slice(rootMarkLength)}`;
1303
+ };
1304
+ if (frontmatter !== null) return insertAfterRootByteOrderMark(holdsRawHtml ? `${frontmatter}\n` : frontmatter, data);
1305
+ if (!readsBackMarkdownFrontmatter(runtime, context, data)) return data;
1306
+ return insertAfterRootByteOrderMark("\n", lastKind !== "html" && data.endsWith("\n") ? data.slice(0, -1) : data);
1307
+ };
621
1308
  const serializeMarkdownWithRuntime = (runtime, document, options = {}, initialDiagnostics = []) => {
622
1309
  runtime.state.schema.assertDocument(document);
623
1310
  const readRoots = /* @__PURE__ */ new Set();
624
1311
  const serialized = new MarkdownDiagnostics();
625
- const data = serializeMdWithRuntime(runtime, options, document, serialized, readRoots);
1312
+ const frontmatter = writeStoredMarkdownFrontmatter(document);
1313
+ const data = writeMarkdownDocument(runtime, getMergedOptionsSerialize(runtime, options, document, serialized, readRoots), frontmatter && "block" in frontmatter ? frontmatter.block : null);
626
1314
  const diagnostics = new MarkdownDiagnostics(initialDiagnostics);
627
1315
  Object.keys(document.roots ?? {}).filter((root) => !readRoots.has(root)).sort().forEach((root) => {
628
1316
  diagnostics.report({
@@ -632,7 +1320,14 @@ const serializeMarkdownWithRuntime = (runtime, document, options = {}, initialDi
632
1320
  severity: "warning"
633
1321
  });
634
1322
  });
635
- Object.keys(document.meta ?? {}).filter((key) => key !== "authored").sort().forEach((key) => {
1323
+ if (frontmatter && "reason" in frontmatter) diagnostics.report({
1324
+ code: "markdown-frontmatter-omitted",
1325
+ impact: "lossy",
1326
+ message: `Markdown omits the front matter block at document metadata "${MARKDOWN_FRONTMATTER_KEY}": ${FRONTMATTER_OMITTED_MESSAGES[frontmatter.reason]}.`,
1327
+ reason: frontmatter.reason,
1328
+ severity: options.lossPolicy === "allow" ? "warning" : "error"
1329
+ });
1330
+ Object.keys(document.meta ?? {}).filter((key) => key !== "authored" && key !== "markdown.frontmatter").sort().forEach((key) => {
636
1331
  diagnostics.report({
637
1332
  code: "markdown-unsupported-metadata",
638
1333
  key,
@@ -643,12 +1338,16 @@ const serializeMarkdownWithRuntime = (runtime, document, options = {}, initialDi
643
1338
  serialized.all().forEach(diagnostics.report);
644
1339
  return finishMarkdownSerialize(data, diagnostics);
645
1340
  };
646
- const serializeMarkdownSliceWithRuntime = (runtime, children, roots) => {
1341
+ const serializeMarkdownSliceWithRuntime = (runtime, children, roots, previousKind) => {
647
1342
  const diagnostics = new MarkdownDiagnostics();
648
- return finishMarkdownSerialize(serializeMdWithRuntime(runtime, {}, createContentFormatDocument({
1343
+ const { data, lastKind } = writeMarkdownBody(getMergedOptionsSerialize(runtime, {}, createContentFormatDocument({
649
1344
  content: children,
650
1345
  roots
651
- }), diagnostics), diagnostics);
1346
+ }), diagnostics), previousKind);
1347
+ return {
1348
+ lastKind,
1349
+ result: finishMarkdownSerialize(data, diagnostics)
1350
+ };
652
1351
  };
653
1352
  const finishMarkdownSerialize = (data, diagnostics) => {
654
1353
  const failure = diagnostics.failure();
@@ -663,4 +1362,4 @@ const finishMarkdownSerialize = (data, diagnostics) => {
663
1362
  });
664
1363
  };
665
1364
  //#endregion
666
- export { createMarkdownOperationRuntime, createMarkdownRuntime, getMergedOptionsDeserialize, getMergedOptionsSerialize, markdownToSlateNodesWithRuntime, parseMarkdownDocumentWithRuntime, parseMarkdownInlineWithRuntime, parseMarkdownSliceWithRuntime, prepareMarkdownRuntime, serializeMarkdownSliceWithRuntime, serializeMarkdownWithRuntime, serializeMdWithRuntime, withMarkdownRuntime };
1365
+ export { createMarkdownOperationRuntime, createMarkdownRuntime, getMergedOptionsDeserialize, getMergedOptionsSerialize, markdownToSlateNodesWithRuntime, parseMarkdownDocumentWithRuntime, parseMarkdownInlineWithRuntime, parseMarkdownSliceWithRuntime, prepareMarkdownRuntime, serializeMarkdownSliceWithRuntime, serializeMarkdownWithRuntime, withMarkdownRuntime, writesRawHtml };