@stream-mdx/react 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +371 -0
  2. package/README.md +79 -4
  3. package/dist/blocks-renderer-DAOBFBfi.d.ts +29 -0
  4. package/dist/blocks-renderer-DQEL1kJW.d.cts +29 -0
  5. package/dist/components/bottom-stick-scroll-area.cjs +117 -193
  6. package/dist/components/bottom-stick-scroll-area.mjs +112 -183
  7. package/dist/components/diff-renderer.cjs +86 -0
  8. package/dist/components/diff-renderer.d.cts +11 -0
  9. package/dist/components/diff-renderer.d.ts +11 -0
  10. package/dist/components/diff-renderer.mjs +66 -0
  11. package/dist/components/index.cjs +2761 -1508
  12. package/dist/components/index.d.cts +7 -2
  13. package/dist/components/index.d.ts +7 -2
  14. package/dist/components/index.mjs +2730 -1493
  15. package/dist/components/katex-math.cjs +220 -0
  16. package/dist/components/katex-math.d.cts +10 -0
  17. package/dist/components/katex-math.d.ts +10 -0
  18. package/dist/components/katex-math.mjs +188 -0
  19. package/dist/contexts/math-tracker.cjs +240 -521
  20. package/dist/contexts/math-tracker.mjs +235 -513
  21. package/dist/index-Cmne1yUK.d.cts +723 -0
  22. package/dist/index-D7dyyu3q.d.ts +723 -0
  23. package/dist/index.cjs +13029 -6475
  24. package/dist/index.d.cts +69 -39
  25. package/dist/index.d.ts +69 -39
  26. package/dist/index.mjs +13007 -6442
  27. package/dist/math/display-wrapper.cjs +7 -15
  28. package/dist/math/display-wrapper.d.cts +2 -2
  29. package/dist/math/display-wrapper.d.ts +2 -2
  30. package/dist/math/display-wrapper.mjs +2 -6
  31. package/dist/node-views-Bpc6Gkgl.d.cts +13 -0
  32. package/dist/node-views-DpnYdaAS.d.ts +13 -0
  33. package/dist/renderer/hooks.cjs +35 -20
  34. package/dist/renderer/hooks.d.cts +22 -1
  35. package/dist/renderer/hooks.d.ts +22 -1
  36. package/dist/renderer/hooks.mjs +27 -12
  37. package/dist/renderer/patch-batching.cjs +5 -8
  38. package/dist/renderer/patch-coalescing.cjs +5 -8
  39. package/dist/renderer/patch-commit-scheduler.cjs +138 -356
  40. package/dist/renderer/patch-commit-scheduler.d.cts +13 -1
  41. package/dist/renderer/patch-commit-scheduler.d.ts +13 -1
  42. package/dist/renderer/patch-commit-scheduler.mjs +133 -348
  43. package/dist/renderer/store.cjs +3775 -1373
  44. package/dist/renderer/store.d.cts +108 -3
  45. package/dist/renderer/store.d.ts +108 -3
  46. package/dist/renderer/store.mjs +3778 -1362
  47. package/dist/renderer/virtualized-code.cjs +415 -71
  48. package/dist/renderer/virtualized-code.d.cts +24 -23
  49. package/dist/renderer/virtualized-code.d.ts +24 -23
  50. package/dist/renderer/virtualized-code.mjs +409 -62
  51. package/dist/renderer.cjs +10655 -4334
  52. package/dist/renderer.d.cts +98 -29
  53. package/dist/renderer.d.ts +98 -29
  54. package/dist/renderer.mjs +10582 -4212
  55. package/dist/server-regions-CPLHGli0.d.cts +32 -0
  56. package/dist/server-regions-mUhyoKi7.d.ts +32 -0
  57. package/dist/server.cjs +10195 -3872
  58. package/dist/server.d.cts +17 -252
  59. package/dist/server.d.ts +17 -252
  60. package/dist/server.mjs +9997 -3649
  61. package/dist/{streaming-markdown-CEI9eDZm.d.ts → streaming-markdown-yELbJxyH.d.ts} +49 -55
  62. package/dist/{streaming-markdown-DRisClXb.d.cts → streaming-markdown-zVwFuaJG.d.cts} +49 -55
  63. package/dist/streaming-markdown.cjs +11660 -5378
  64. package/dist/streaming-markdown.d.cts +7 -2
  65. package/dist/streaming-markdown.d.ts +7 -2
  66. package/dist/streaming-markdown.mjs +11679 -5347
  67. package/dist/trusted-mdx/index.cjs +833 -0
  68. package/dist/trusted-mdx/index.d.cts +11 -0
  69. package/dist/trusted-mdx/index.d.ts +11 -0
  70. package/dist/trusted-mdx/index.mjs +807 -0
  71. package/dist/trusted-mdx/native-children-slot.cjs +45 -0
  72. package/dist/trusted-mdx/native-children-slot.d.cts +11 -0
  73. package/dist/trusted-mdx/native-children-slot.d.ts +11 -0
  74. package/dist/trusted-mdx/native-children-slot.mjs +24 -0
  75. package/dist/trusted-mdx/server.cjs +752 -0
  76. package/dist/trusted-mdx/server.d.cts +24 -0
  77. package/dist/trusted-mdx/server.d.ts +24 -0
  78. package/dist/trusted-mdx/server.mjs +724 -0
  79. package/dist/trusted-mdx-contract-ElKpkDI5.d.cts +113 -0
  80. package/dist/trusted-mdx-contract-ElKpkDI5.d.ts +113 -0
  81. package/dist/utils/inline-html.cjs +246 -147
  82. package/dist/utils/inline-html.d.cts +37 -6
  83. package/dist/utils/inline-html.d.ts +37 -6
  84. package/dist/utils/inline-html.mjs +237 -134
  85. package/package.json +41 -18
  86. package/dist/index-BVhp_pcF.d.ts +0 -251
  87. package/dist/index-EaeouYp2.d.cts +0 -251
  88. package/dist/mdx-client.cjs +0 -408
  89. package/dist/mdx-client.d.cts +0 -113
  90. package/dist/mdx-client.d.ts +0 -113
  91. package/dist/mdx-client.mjs +0 -369
  92. package/dist/mdx-coordinator.cjs +0 -584
  93. package/dist/mdx-coordinator.d.cts +0 -21
  94. package/dist/mdx-coordinator.d.ts +0 -21
  95. package/dist/mdx-coordinator.mjs +0 -550
  96. package/dist/renderer/node-views.cjs +0 -1887
  97. package/dist/renderer/node-views.d.cts +0 -14
  98. package/dist/renderer/node-views.d.ts +0 -14
  99. package/dist/renderer/node-views.mjs +0 -1861
@@ -0,0 +1,724 @@
1
+ // src/trusted-mdx/server.tsx
2
+ import React2 from "react";
3
+
4
+ // src/trusted-mdx-contract.ts
5
+ function assertTrustedMdxNativeChildContinuations(owners, flowChildren) {
6
+ if (owners.length !== flowChildren.length)
7
+ throw new Error("A trusted MDX native child continuation has misaligned owner and source spans.");
8
+ let continuationOwnerIndex;
9
+ for (let index = 0; index < owners.length; index++) {
10
+ let owner = owners[index];
11
+ if (owner?.kind !== "continuation") {
12
+ continuationOwnerIndex = void 0;
13
+ continue;
14
+ }
15
+ let ownerIndex = owner.ownerIndex, ownerForRun = owners[ownerIndex], previousChild = flowChildren[index - 1], child = flowChildren[index];
16
+ if (!Number.isSafeInteger(ownerIndex) || ownerIndex < 0 || ownerIndex >= index || (continuationOwnerIndex === void 0 ? ownerIndex !== index - 1 : ownerIndex !== continuationOwnerIndex) || ownerForRun === null || ownerForRun === void 0 || ownerForRun.kind === "continuation" || previousChild?.kind !== "inline" || child?.kind !== "inline" || previousChild.to <= previousChild.from || child.to <= child.from || previousChild.to !== child.from)
17
+ throw new Error("A trusted MDX native child continuation does not cover one exact contiguous inline run.");
18
+ continuationOwnerIndex = ownerIndex;
19
+ }
20
+ }
21
+
22
+ // src/trusted-mdx/evaluate.ts
23
+ import React from "react";
24
+ import * as jsxRuntime from "react/jsx-runtime";
25
+ var AsyncFunction = Object.getPrototypeOf(async function() {
26
+ }).constructor;
27
+ async function evaluateCompiledMdx(code, options, canInvoke) {
28
+ let hostImports = options.imports, resolveSyncHostImport = (specifier) => {
29
+ if (specifier === "react")
30
+ return { default: React, ...React };
31
+ if (specifier === "react/jsx-runtime")
32
+ return jsxRuntime;
33
+ if (hostImports && Object.prototype.hasOwnProperty.call(hostImports, specifier))
34
+ return hostImports[specifier];
35
+ throw new Error(
36
+ `Cannot resolve MDX import specifier "${specifier}": no host binding configured. Automatic fetching and network egress are disabled.`
37
+ );
38
+ };
39
+ async function resolveDynamicHostImport(specifier) {
40
+ return resolveSyncHostImport(specifier);
41
+ }
42
+ let runtime = {
43
+ Fragment: jsxRuntime.Fragment,
44
+ jsx: jsxRuntime.jsx,
45
+ jsxs: jsxRuntime.jsxs,
46
+ _resolveSyncHostImport: resolveSyncHostImport,
47
+ _resolveDynamicHostImport: resolveDynamicHostImport
48
+ }, fn = new AsyncFunction(code);
49
+ return canInvoke() ? fn(runtime) : null;
50
+ }
51
+
52
+ // src/trusted-mdx/server.tsx
53
+ import { TrustedMdxNativeChildrenSlot } from "@stream-mdx/react/_internal/trusted-mdx-native-children";
54
+
55
+ // src/trusted-mdx/projection.ts
56
+ function getActiveTrustedMdxNativeTree(meta) {
57
+ if (Array.isArray(meta?.trustedMdxNativeChildren)) return meta.trustedMdxNativeChildren;
58
+ if (meta?.htmlOwnership === !0 && Array.isArray(meta.htmlTree)) return meta.htmlTree;
59
+ if (Array.isArray(meta?.htmlParagraphTree)) return meta.htmlParagraphTree;
60
+ if (Array.isArray(meta?.htmlTree)) return meta.htmlTree;
61
+ }
62
+ function readSourceRange(value, sourceLength) {
63
+ if (typeof value != "object" || value === null || Array.isArray(value) || !("from" in value) || !("to" in value))
64
+ return null;
65
+ let from = value.from, to = value.to;
66
+ return typeof from != "number" || typeof to != "number" || !Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to <= from || to > sourceLength ? null : { from, to };
67
+ }
68
+ function readSnapshotFields(value) {
69
+ if (typeof value != "object" || value === null || Array.isArray(value) || !("id" in value) || !("type" in value))
70
+ return null;
71
+ let id = value.id, type = value.type;
72
+ return typeof id != "string" || typeof type != "string" ? null : {
73
+ id,
74
+ type,
75
+ range: "range" in value ? value.range : void 0,
76
+ props: "props" in value ? value.props : void 0,
77
+ children: "children" in value ? value.children : void 0
78
+ };
79
+ }
80
+ function hasNativeBlockOwner(tree) {
81
+ if (!Array.isArray(tree)) return !1;
82
+ let pending = [...tree];
83
+ for (; pending.length > 0; ) {
84
+ let current = pending.pop();
85
+ if (!(typeof current != "object" || current === null || Array.isArray(current))) {
86
+ if ("kind" in current && current.kind === "block" && "block" in current) return !0;
87
+ "children" in current && Array.isArray(current.children) && pending.push(...current.children);
88
+ }
89
+ }
90
+ return !1;
91
+ }
92
+ function collectInlineOwners(value, sourceLength, matches) {
93
+ if (!Array.isArray(value)) return;
94
+ let visited = /* @__PURE__ */ new WeakSet(), pending = [...value];
95
+ for (; pending.length > 0; ) {
96
+ let current = pending.pop();
97
+ if (!(typeof current != "object" || current === null || visited.has(current))) {
98
+ if (visited.add(current), Array.isArray(current)) {
99
+ pending.push(...current);
100
+ continue;
101
+ }
102
+ "kind" in current && current.kind === "trusted-mdx-inline" && "ownerId" in current && typeof current.ownerId == "string" && addMdxOwner(
103
+ matches,
104
+ current.ownerId,
105
+ "inline expression",
106
+ "sourceRange" in current ? current.sourceRange : void 0,
107
+ sourceLength
108
+ ), "children" in current && Array.isArray(current.children) && pending.push(...current.children);
109
+ }
110
+ }
111
+ }
112
+ function isNestedMdxType(type) {
113
+ return type === "paragraph-mdx" || type === "blockquote-mdx" || type === "list-item-mdx";
114
+ }
115
+ function addMdxOwner(matches, id, label, range, sourceLength) {
116
+ let sourceRange = readSourceRange(range, sourceLength);
117
+ matches.push({
118
+ id,
119
+ label,
120
+ from: sourceRange?.from ?? null,
121
+ to: sourceRange?.to ?? null,
122
+ regions: [],
123
+ placement: null,
124
+ rootElementName: void 0,
125
+ nativeChildren: !1,
126
+ nativeChildOwners: [],
127
+ flowChildren: void 0,
128
+ nativeFlowOwnedBlockIds: [],
129
+ wholeBlockFlowRoot: !1,
130
+ ambiguous: !1
131
+ });
132
+ }
133
+ function readFlowChildRanges(flowChildren, flowRange, sourceLength) {
134
+ if (flowChildren === void 0) return;
135
+ let ranges = [], previousTo = flowRange.from;
136
+ for (let child of flowChildren) {
137
+ let range = readSourceRange(child, sourceLength);
138
+ if (!range || range.from < flowRange.from || range.to > flowRange.to || range.from < previousTo)
139
+ return null;
140
+ ranges.push(range), previousTo = range.to;
141
+ }
142
+ return ranges;
143
+ }
144
+ function classifyFlowRange(range, childRanges) {
145
+ let directChildIndex;
146
+ for (let index = 0; index < childRanges.length; index++) {
147
+ let childRange = childRanges[index];
148
+ if (!childRange) return null;
149
+ if (range.from >= childRange.from && range.to <= childRange.to) {
150
+ if (directChildIndex !== void 0) return null;
151
+ directChildIndex = index;
152
+ } else if (range.from < childRange.to && range.to > childRange.from)
153
+ return null;
154
+ }
155
+ return directChildIndex ?? "root-syntax";
156
+ }
157
+ function findInlineChildRunForRange(range, flowChildren, childRanges) {
158
+ if (!(flowChildren === void 0 || childRanges === void 0 || range.to <= range.from))
159
+ for (let startIndex = 0; startIndex < flowChildren.length; startIndex++) {
160
+ let firstChild = flowChildren[startIndex], firstRange = childRanges[startIndex];
161
+ if (firstChild?.kind !== "inline" || !firstRange || firstRange.from !== range.from || firstRange.to <= firstRange.from) continue;
162
+ let previousRange = firstRange;
163
+ for (let endIndex = startIndex + 1; endIndex < flowChildren.length; endIndex++) {
164
+ let child = flowChildren[endIndex], childRange = childRanges[endIndex];
165
+ if (child?.kind !== "inline" || !childRange || childRange.from !== previousRange.to || childRange.to <= childRange.from) break;
166
+ if (previousRange = childRange, previousRange.to === range.to)
167
+ return {
168
+ startIndex,
169
+ endIndex
170
+ };
171
+ if (previousRange.to > range.to) break;
172
+ }
173
+ }
174
+ }
175
+ function collectFlowOwnerBlocks(blocks) {
176
+ let flowOwnerBlocks = [], seenBlockIds = /* @__PURE__ */ new Set(), pendingBlocks = [...blocks], pendingNodes = [], visitedNodes = /* @__PURE__ */ new WeakSet();
177
+ for (let blockIndex = 0; blockIndex < pendingBlocks.length; blockIndex++) {
178
+ let block = pendingBlocks[blockIndex];
179
+ if (!block || seenBlockIds.has(block.id)) continue;
180
+ seenBlockIds.add(block.id), flowOwnerBlocks.push(block);
181
+ let meta = block.payload.meta, preparedTree = getActiveTrustedMdxNativeTree(meta);
182
+ for (preparedTree !== void 0 && pendingNodes.push(...preparedTree); pendingNodes.length > 0; ) {
183
+ let node = pendingNodes.pop();
184
+ !node || visitedNodes.has(node) || (visitedNodes.add(node), node.kind === "block" ? pendingBlocks.push(node.block) : (node.kind === "element" || node.kind === "component") && pendingNodes.push(...node.children));
185
+ }
186
+ }
187
+ return flowOwnerBlocks;
188
+ }
189
+ function hasWholeFlowRootMatch(block, childRange, matches) {
190
+ return matches.some(
191
+ (match) => match.wholeBlockFlowRoot && match.from === childRange.from && match.to === childRange.to && (match.id === block.id || block.payload.inline?.some(
192
+ (node) => node.kind === "trusted-mdx-inline" && node.ownerId === match.id && node.sourceRange?.from === childRange.from && node.sourceRange?.to === childRange.to
193
+ ) === !0)
194
+ );
195
+ }
196
+ function findPreparedTreeBlock(tree, childRange, sourceLength, exact = !1, wholeFlowRoots) {
197
+ if (!tree) return;
198
+ let pending = [...tree], owner, ownerWidth = -1;
199
+ for (; pending.length > 0; ) {
200
+ let node = pending.pop();
201
+ if (node)
202
+ if (node.kind === "block") {
203
+ let range = readSourceRange(node.block.payload.range, sourceLength);
204
+ if (!range) continue;
205
+ let wholeFlowRoot = wholeFlowRoots !== void 0 && hasWholeFlowRootMatch(node.block, childRange, wholeFlowRoots) && range.from === childRange.from && range.to <= childRange.to;
206
+ (exact ? range.from === childRange.from && range.to === childRange.to || wholeFlowRoot : range.from >= childRange.from && range.to <= childRange.to) && (wholeFlowRoots === void 0 || node.block.type === "mdx" || wholeFlowRoot) && range.to - range.from > ownerWidth && (owner = node.block, ownerWidth = range.to - range.from);
207
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
208
+ }
209
+ return owner;
210
+ }
211
+ function assertPreparedTreeOwnersFitFlowChildren(tree, childRanges, flowChildren, flowRange, sourceLength) {
212
+ if (!tree) return;
213
+ let pending = [...tree];
214
+ for (; pending.length > 0; ) {
215
+ let node = pending.pop();
216
+ if (node)
217
+ if (node.kind === "block") {
218
+ let range = readSourceRange(node.block.payload.range, sourceLength);
219
+ if (!range)
220
+ throw new Error("A trusted MDX flow region has a prepared worker block without a source span.");
221
+ if (range.from < flowRange.from || range.to > flowRange.to || range.from === flowRange.from && range.to === flowRange.to) continue;
222
+ if (childRanges === void 0)
223
+ throw new Error("A trusted MDX flow region has prepared tree owners but no direct-child spans.");
224
+ let inlineRun = node.block.type === "paragraph" && Array.isArray(node.block.payload.inline) && node.block.payload.inline.length > 0 ? findInlineChildRunForRange(range, flowChildren, childRanges) : void 0;
225
+ if (classifyFlowRange(range, childRanges) === null && inlineRun === void 0)
226
+ throw new Error("A trusted MDX flow region has prepared tree owners crossing direct-child boundaries.");
227
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
228
+ }
229
+ }
230
+ function collectFlowNativeBlocks(flowChildren, flowRange, blocks, rootOwnerId, sourceLength, matches, flowOwnerBlocks) {
231
+ let childRanges = readFlowChildRanges(flowChildren, flowRange, sourceLength);
232
+ if (childRanges === null)
233
+ throw new Error("A trusted MDX flow region has invalid or overlapping direct-child spans.");
234
+ let meta = flowOwnerBlocks.find((block) => block.id === rootOwnerId)?.payload.meta, preparedTree = getActiveTrustedMdxNativeTree(meta), preparedTrees = preparedTree === void 0 ? [] : [preparedTree], ownedBlockIds = [];
235
+ for (let block of blocks) {
236
+ if (block.id === rootOwnerId) continue;
237
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
238
+ if (!blockRange || blockRange.from < flowRange.from || blockRange.to > flowRange.to || blockRange.from === flowRange.from && blockRange.to === flowRange.to) continue;
239
+ if (childRanges === void 0)
240
+ throw new Error("A trusted MDX flow region has worker owners but no direct-child spans.");
241
+ let ownership = classifyFlowRange(blockRange, childRanges), inlineRun = block.type === "paragraph" && Array.isArray(block.payload.inline) && block.payload.inline.length > 0 ? findInlineChildRunForRange(blockRange, flowChildren, childRanges) : void 0;
242
+ if (ownership === null && inlineRun === void 0)
243
+ throw new Error("A trusted MDX flow region has worker owners crossing direct-child boundaries.");
244
+ ownedBlockIds.push(block.id);
245
+ }
246
+ for (let tree of preparedTrees)
247
+ hasNativeBlockOwner(tree) && assertPreparedTreeOwnersFitFlowChildren(tree, childRanges, flowChildren, flowRange, sourceLength);
248
+ if (flowChildren === void 0 || flowChildren.length === 0)
249
+ return { childOwners: [], ownedBlockIds };
250
+ if (childRanges === void 0)
251
+ throw new Error("A trusted MDX flow region has native children but no direct-child spans.");
252
+ let groupedInlineOwners, registerGroupedInlineOwner = (block, kind) => {
253
+ if (block.id === rootOwnerId || block.type !== "paragraph" || !Array.isArray(block.payload.inline) || block.payload.inline.length === 0)
254
+ return;
255
+ let range = readSourceRange(block.payload.range, sourceLength);
256
+ if (!range) return;
257
+ let run = findInlineChildRunForRange(range, flowChildren, childRanges);
258
+ if (!run) return;
259
+ let groupedOwners = groupedInlineOwners ?? (groupedInlineOwners = new Array(flowChildren.length));
260
+ for (let index = run.startIndex; index <= run.endIndex; index++) {
261
+ let existing2 = groupedOwners[index];
262
+ if (existing2 && (existing2.block.id !== block.id || existing2.startIndex !== run.startIndex || existing2.endIndex !== run.endIndex))
263
+ throw new Error("A trusted MDX flow region has duplicate native owners for one inline child run.");
264
+ }
265
+ if (groupedOwners[run.startIndex]?.owner.kind === "block" && kind === "prepared-tree") return;
266
+ let candidate = {
267
+ startIndex: run.startIndex,
268
+ endIndex: run.endIndex,
269
+ block,
270
+ owner: kind === "block" ? { kind: "block", blockId: block.id } : { kind: "prepared-tree", blockId: block.id }
271
+ };
272
+ for (let index = run.startIndex; index <= run.endIndex; index++)
273
+ groupedOwners[index] = candidate;
274
+ };
275
+ for (let block of blocks)
276
+ registerGroupedInlineOwner(block, "block");
277
+ for (let tree of preparedTrees) {
278
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
279
+ for (; pending.length > 0; ) {
280
+ let node = pending.pop();
281
+ !node || visited.has(node) || (visited.add(node), node.kind === "block" ? registerGroupedInlineOwner(node.block, "prepared-tree") : (node.kind === "element" || node.kind === "component") && pending.push(...node.children));
282
+ }
283
+ }
284
+ let groupedChildRanges;
285
+ for (let startIndex = 0; startIndex < (groupedInlineOwners?.length ?? 0); startIndex++) {
286
+ let groupedOwner = groupedInlineOwners?.[startIndex];
287
+ if (!(!groupedOwner || groupedOwner.startIndex !== startIndex))
288
+ for (let childIndex = groupedOwner.startIndex; childIndex <= groupedOwner.endIndex; childIndex++) {
289
+ let childRange = childRanges[childIndex];
290
+ if (!childRange)
291
+ throw new Error("A trusted MDX flow region has an invalid grouped inline child span.");
292
+ groupedChildRanges ?? (groupedChildRanges = /* @__PURE__ */ new Map()), groupedChildRanges.set(childRange.from, childRange.to);
293
+ }
294
+ }
295
+ if (groupedChildRanges !== void 0) {
296
+ for (let block of blocks) {
297
+ if (block.id === rootOwnerId) continue;
298
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
299
+ if (blockRange && groupedChildRanges.get(blockRange.from) === blockRange.to)
300
+ throw new Error("A trusted MDX flow region has duplicate native owners inside a grouped inline run.");
301
+ }
302
+ for (let tree of preparedTrees) {
303
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
304
+ for (; pending.length > 0; ) {
305
+ let node = pending.pop();
306
+ if (!(!node || visited.has(node)))
307
+ if (visited.add(node), node.kind === "block") {
308
+ let blockRange = readSourceRange(node.block.payload.range, sourceLength);
309
+ if (blockRange && groupedChildRanges.get(blockRange.from) === blockRange.to)
310
+ throw new Error("A trusted MDX flow region has duplicate native owners inside a grouped inline run.");
311
+ } else (node.kind === "element" || node.kind === "component") && pending.push(...node.children);
312
+ }
313
+ }
314
+ }
315
+ let childOwners = [];
316
+ for (let childIndex = 0; childIndex < flowChildren.length; childIndex++) {
317
+ let child = flowChildren[childIndex], childRange = childRanges?.[childIndex];
318
+ if (!child || !childRange)
319
+ throw new Error("A trusted MDX flow region has invalid direct-child spans.");
320
+ let groupedOwner = groupedInlineOwners?.[childIndex];
321
+ if (groupedOwner) {
322
+ if (groupedOwner.startIndex !== childIndex || child.kind !== "inline")
323
+ throw new Error("A trusted MDX flow region has an invalid grouped inline native owner.");
324
+ childOwners.push(groupedOwner.owner);
325
+ for (let coveredIndex = childIndex + 1; coveredIndex <= groupedOwner.endIndex; coveredIndex++)
326
+ childOwners.push({ kind: "continuation", ownerIndex: childIndex });
327
+ childIndex = groupedOwner.endIndex;
328
+ continue;
329
+ }
330
+ let ownerId, ownerWidth = -1;
331
+ if (child.kind !== "expression")
332
+ for (let block of blocks) {
333
+ if (block.id === rootOwnerId) continue;
334
+ let blockRange = readSourceRange(block.payload.range, sourceLength);
335
+ if (!blockRange || blockRange.from === flowRange.from && blockRange.to === flowRange.to || !(child.kind === "markdown" ? blockRange.from >= childRange.from && blockRange.to <= childRange.to : child.kind === "inline" || block.type === "mdx" ? blockRange.from === childRange.from && blockRange.to === childRange.to : blockRange.from === childRange.from && hasWholeFlowRootMatch(block, childRange, matches))) continue;
336
+ let width = blockRange.to - blockRange.from;
337
+ width > ownerWidth && (ownerId = block.id, ownerWidth = width);
338
+ }
339
+ if (ownerId !== void 0) {
340
+ childOwners.push({ kind: "block", blockId: ownerId });
341
+ continue;
342
+ }
343
+ if (child.kind !== "expression") {
344
+ let preparedOwner;
345
+ for (let tree of preparedTrees)
346
+ if (preparedOwner = findPreparedTreeBlock(
347
+ tree,
348
+ childRange,
349
+ sourceLength,
350
+ child.kind === "jsx",
351
+ child.kind === "jsx" ? matches : void 0
352
+ ), preparedOwner) break;
353
+ if (preparedOwner) {
354
+ if (child.kind === "inline") {
355
+ let preparedRange = readSourceRange(preparedOwner.payload.range, sourceLength);
356
+ if (preparedRange?.from !== childRange.from || preparedRange.to !== childRange.to)
357
+ throw new Error("A compiler-authored inline child has no exact prepared native owner.");
358
+ }
359
+ childOwners.push({ kind: "prepared-tree", blockId: preparedOwner.id });
360
+ continue;
361
+ }
362
+ }
363
+ if (child.kind === "markdown" || child.kind === "inline")
364
+ throw new Error("A compiler-authored Markdown child has no prepared native block owner.");
365
+ childOwners.push(null);
366
+ }
367
+ return { childOwners, ownedBlockIds };
368
+ }
369
+ function collectCompilerFlowBlockOwners(source, blocks, regions, matches) {
370
+ let ownerIds = new Set(matches.map((match) => match.id));
371
+ for (let region of regions) {
372
+ if (region.kind !== "render" || region.placement !== "flow" || !("rootElementName" in region)) continue;
373
+ let range = readSourceRange(region, source.length);
374
+ if (!range) continue;
375
+ let exactMatches = matches.filter((match) => match.from === range.from && match.to === range.to);
376
+ if (exactMatches.length > 0) {
377
+ for (let match of exactMatches) match.wholeBlockFlowRoot = !0;
378
+ continue;
379
+ }
380
+ let block = blocks.find((candidate) => {
381
+ let blockRange = readSourceRange(candidate.payload.range, source.length);
382
+ return blockRange !== null && blockRange.from === range.from && blockRange.to <= range.to;
383
+ });
384
+ !block || ownerIds.has(block.id) || (addMdxOwner(matches, block.id, `${block.type} compiler flow root`, range, source.length), matches[matches.length - 1].wholeBlockFlowRoot = !0, ownerIds.add(block.id));
385
+ }
386
+ }
387
+ function collectPreparedNestedOwners(prepared, sourceLength, matches) {
388
+ if (typeof prepared != "object" || prepared === null || Array.isArray(prepared) || !("children" in prepared) || !Array.isArray(prepared.children))
389
+ return;
390
+ let visited = /* @__PURE__ */ new WeakSet(), pending = [];
391
+ for (let index = 0; index < prepared.children.length; index++) {
392
+ let child = prepared.children[index];
393
+ pending.push(child);
394
+ }
395
+ for (; pending.length > 0; ) {
396
+ let value = pending.pop();
397
+ if (typeof value != "object" || value === null || Array.isArray(value) || visited.has(value))
398
+ continue;
399
+ visited.add(value);
400
+ let node = readSnapshotFields(value), nodeProps = node?.props && typeof node.props == "object" ? node.props : void 0;
401
+ if (nodeProps && "inline" in nodeProps && collectInlineOwners(nodeProps.inline, sourceLength, matches), node && isNestedMdxType(node.type) && addMdxOwner(matches, node.id, `${node.type} segment`, node.range, sourceLength), !(!node || !Array.isArray(node.children)))
402
+ for (let index = 0; index < node.children.length; index++) {
403
+ let child = node.children[index];
404
+ pending.push(child);
405
+ }
406
+ }
407
+ }
408
+ function collectHtmlTreeOwners(tree, sourceLength, matches) {
409
+ if (!Array.isArray(tree)) return;
410
+ let pending = [...tree], visited = /* @__PURE__ */ new WeakSet();
411
+ for (; pending.length > 0; ) {
412
+ let current = pending.pop();
413
+ if (!(typeof current != "object" || current === null || visited.has(current))) {
414
+ if (visited.add(current), Array.isArray(current)) {
415
+ pending.push(...current);
416
+ continue;
417
+ }
418
+ if ("kind" in current && current.kind === "block" && "block" in current) {
419
+ let candidate = current.block;
420
+ if (typeof candidate == "object" && candidate !== null && !Array.isArray(candidate) && "id" in candidate && typeof candidate.id == "string" && "type" in candidate && typeof candidate.type == "string" && "payload" in candidate && typeof candidate.payload == "object" && candidate.payload !== null) {
421
+ let block = candidate, meta = block.payload.meta;
422
+ if (block.type === "mdx" && addMdxOwner(
423
+ matches,
424
+ block.id,
425
+ "nested block",
426
+ block.payload.range,
427
+ sourceLength
428
+ ), collectInlineOwners(block.payload.inline, sourceLength, matches), meta) {
429
+ if (block.type === "paragraph" && Array.isArray(meta.mixedSegments))
430
+ for (let index = 0; index < meta.mixedSegments.length; index++) {
431
+ let segment = meta.mixedSegments[index];
432
+ typeof segment != "object" || segment === null || Array.isArray(segment) || !("kind" in segment) || segment.kind !== "mdx" || addMdxOwner(
433
+ matches,
434
+ `${block.id}::paragraph:segment:${index}`,
435
+ "paragraph segment",
436
+ "range" in segment ? segment.range : void 0,
437
+ sourceLength
438
+ );
439
+ }
440
+ collectInlineOwners(meta.header, sourceLength, matches), collectInlineOwners(meta.rows, sourceLength, matches), collectPreparedNestedOwners(meta.preparedNested, sourceLength, matches);
441
+ let preparedTree = getActiveTrustedMdxNativeTree(meta);
442
+ preparedTree !== void 0 && pending.push(preparedTree);
443
+ }
444
+ }
445
+ }
446
+ "children" in current && Array.isArray(current.children) && pending.push(...current.children);
447
+ }
448
+ }
449
+ }
450
+ function collectMdxOwners(source, blocks) {
451
+ let matches = [];
452
+ for (let block of blocks) {
453
+ if (block.type === "mdx" && addMdxOwner(
454
+ matches,
455
+ block.id,
456
+ "block",
457
+ block.payload.range,
458
+ source.length
459
+ ), block.type === "paragraph") {
460
+ let segments = block.payload.meta?.mixedSegments;
461
+ if (Array.isArray(segments))
462
+ for (let index = 0; index < segments.length; index++) {
463
+ let segment = segments[index];
464
+ typeof segment != "object" || segment === null || Array.isArray(segment) || !("kind" in segment) || segment.kind !== "mdx" || addMdxOwner(
465
+ matches,
466
+ `${block.id}::paragraph:segment:${index}`,
467
+ "paragraph segment",
468
+ "range" in segment ? segment.range : void 0,
469
+ source.length
470
+ );
471
+ }
472
+ }
473
+ collectInlineOwners(block.payload.inline, source.length, matches);
474
+ let tableMeta = block.payload.meta;
475
+ if (tableMeta) {
476
+ collectInlineOwners(tableMeta.header, source.length, matches), collectInlineOwners(tableMeta.rows, source.length, matches), collectPreparedNestedOwners(tableMeta.preparedNested, source.length, matches);
477
+ let preparedTree = getActiveTrustedMdxNativeTree(tableMeta);
478
+ preparedTree !== void 0 && collectHtmlTreeOwners(preparedTree, source.length, matches);
479
+ }
480
+ }
481
+ let unique = /* @__PURE__ */ new Map();
482
+ for (let match of matches) {
483
+ let existing = unique.get(match.id);
484
+ existing ? (existing.from !== match.from || existing.to !== match.to) && (existing.ambiguous = !0) : unique.set(match.id, match);
485
+ }
486
+ return Array.from(unique.values());
487
+ }
488
+ function describeOwner(match) {
489
+ return match.label === "block" ? `MDX block "${match.id}"` : `MDX ${match.label} "${match.id}"`;
490
+ }
491
+ function isExactNativeMdxAliasRegion(region, owners) {
492
+ if (owners.length !== 2) return !1;
493
+ let first = owners[0], second = owners[1];
494
+ return !first || !second || first.from === null || first.to === null || first.from !== second.from || first.to !== second.to || region.from !== first.from || region.to !== first.to ? !1 : (first.label === "block" || first.label === "nested block") && second.label === "inline expression" && second.id.startsWith(`${first.id}::native-mdx:`) || (second.label === "block" || second.label === "nested block") && first.label === "inline expression" && first.id.startsWith(`${second.id}::native-mdx:`);
495
+ }
496
+ function placementFields(match) {
497
+ return match.placement === null ? {} : { placement: match.placement };
498
+ }
499
+ function projectMdxBlocks(source, blocks, regions, regionComponents) {
500
+ let projections = /* @__PURE__ */ new Map(), flowOwnerBlocks = collectFlowOwnerBlocks(blocks), matches = collectMdxOwners(source, blocks);
501
+ collectCompilerFlowBlockOwners(source, flowOwnerBlocks, regions, matches);
502
+ let ownersByRegion = /* @__PURE__ */ new Map();
503
+ for (let region of regions) {
504
+ let regionRange = readSourceRange(region, source.length);
505
+ if (!regionRange) continue;
506
+ let owners = [];
507
+ for (let match of matches) {
508
+ if (match.from === null || match.to === null) continue;
509
+ let ownerFrom = match.from, ownerTo = match.to;
510
+ if (regionRange.to <= match.from || regionRange.from >= match.to) continue;
511
+ let compilerFlowRoot = region.kind === "render" && "rootElementName" in region, regionContainsOwner = regionRange.from <= match.from && regionRange.to >= match.to;
512
+ if (region.kind !== "module" && (regionRange.from < match.from || regionRange.to > match.to)) {
513
+ if (compilerFlowRoot && regionContainsOwner) continue;
514
+ match.ambiguous = !0;
515
+ continue;
516
+ }
517
+ if (!(match.wholeBlockFlowRoot && regionRange.from >= ownerFrom && regionRange.to <= ownerTo && (regionRange.from > ownerFrom || regionRange.to < ownerTo)) && (match.regions.push(region), region.kind !== "module")) {
518
+ if (owners.push(match), region.placement !== "flow" && region.placement !== "inline" || match.placement !== null && match.placement !== region.placement ? match.ambiguous = !0 : match.placement = region.placement, region.kind === "render" && region.placement === "flow" && "rootElementName" in region && regionRange.from === match.from && regionRange.to === match.to && region.kind === "render" && "rootElementName" in region) {
519
+ match.wholeBlockFlowRoot = !0;
520
+ let flowNativeBlocks = collectFlowNativeBlocks(
521
+ region.flowChildren,
522
+ regionRange,
523
+ blocks,
524
+ match.id,
525
+ source.length,
526
+ matches,
527
+ flowOwnerBlocks
528
+ );
529
+ match.nativeFlowOwnedBlockIds = flowNativeBlocks.ownedBlockIds, match.nativeChildOwners = flowNativeBlocks.childOwners, match.flowChildren = region.flowChildren;
530
+ }
531
+ match.nativeChildren = match.nativeChildOwners.some((owner) => owner !== null) && match.placement === "flow", "rootElementName" in region && (match.rootElementName !== void 0 && match.rootElementName !== region.rootElementName ? match.ambiguous = !0 : match.rootElementName = region.rootElementName);
532
+ }
533
+ }
534
+ owners.length > 1 && ownersByRegion.set(region, owners);
535
+ }
536
+ for (let [region, owners] of ownersByRegion)
537
+ if (!isExactNativeMdxAliasRegion(region, owners))
538
+ for (let owner of owners) owner.ambiguous = !0;
539
+ for (let match of matches) {
540
+ let description = describeOwner(match);
541
+ if (match.from === null || match.to === null) {
542
+ projections.set(match.id, {
543
+ kind: "unmapped",
544
+ diagnostic: `${description} has no valid authored source range.`
545
+ });
546
+ continue;
547
+ }
548
+ if (!match.ambiguous && match.regions.length > 0) {
549
+ let orderedRegions = match.regions.slice().sort((left, right) => left.from - right.from || left.to - right.to), coveredUntil = match.from;
550
+ for (let region of orderedRegions) {
551
+ let from = Math.max(match.from, region.from), to = Math.min(match.to, region.to);
552
+ if (from < coveredUntil || source.slice(coveredUntil, from).trim().length > 0) {
553
+ match.ambiguous = !0;
554
+ break;
555
+ }
556
+ coveredUntil = to;
557
+ }
558
+ !match.ambiguous && source.slice(coveredUntil, match.to).trim().length > 0 && (match.ambiguous = !0);
559
+ }
560
+ if (match.ambiguous || match.regions.length === 0) {
561
+ projections.set(match.id, {
562
+ kind: "unmapped",
563
+ diagnostic: match.ambiguous ? `${description} cannot be mapped exactly to unique authored regions.` : `${description} (${match.from}..${match.to}) has no corresponding authored MDX region.`,
564
+ ...placementFields(match)
565
+ });
566
+ continue;
567
+ }
568
+ let renderRegions = match.regions.filter((region) => region.kind === "render");
569
+ if (renderRegions.length > 0) {
570
+ let placement = match.placement;
571
+ if (placement === null) {
572
+ projections.set(match.id, {
573
+ kind: "unmapped",
574
+ diagnostic: `${description} has render regions without compiler placement provenance.`
575
+ });
576
+ continue;
577
+ }
578
+ if (match.nativeChildren && match.rootElementName === void 0) {
579
+ projections.set(match.id, {
580
+ kind: "unmapped",
581
+ diagnostic: `${description} has prepared native children but no compiler-authored flow JSX root.`,
582
+ placement
583
+ });
584
+ continue;
585
+ }
586
+ let components = [], missingKey = null;
587
+ for (let region of renderRegions) {
588
+ if (!Object.prototype.hasOwnProperty.call(regionComponents, region.key)) {
589
+ missingKey = region.key;
590
+ break;
591
+ }
592
+ let component = regionComponents[region.key];
593
+ if (typeof component != "function") {
594
+ missingKey = region.key;
595
+ break;
596
+ }
597
+ components.push(component);
598
+ }
599
+ projections.set(
600
+ match.id,
601
+ missingKey === null ? {
602
+ kind: "render",
603
+ regions: Object.freeze(components),
604
+ placement,
605
+ ...match.nativeChildren ? { nativeChildren: !0 } : {},
606
+ ...match.nativeChildOwners.length > 0 ? { nativeChildOwners: Object.freeze([...match.nativeChildOwners]) } : {},
607
+ ...match.flowChildren ? { flowChildren: match.flowChildren } : {},
608
+ ...match.nativeFlowOwnedBlockIds.length > 0 ? { nativeFlowOwnedBlockIds: Object.freeze([...match.nativeFlowOwnedBlockIds]) } : {},
609
+ ...match.wholeBlockFlowRoot ? { wholeBlockFlowRoot: !0 } : {},
610
+ ...match.rootElementName === void 0 ? {} : { rootElementName: match.rootElementName }
611
+ } : {
612
+ kind: "unmapped",
613
+ diagnostic: `No evaluated renderer exists for MDX region "${missingKey}".`,
614
+ placement
615
+ }
616
+ );
617
+ continue;
618
+ }
619
+ if (match.regions.some((region) => region.kind === "module")) {
620
+ projections.set(match.id, { kind: "module" });
621
+ continue;
622
+ }
623
+ projections.set(match.id, {
624
+ kind: "unmapped",
625
+ diagnostic: `${description} has no renderable or module region.`
626
+ });
627
+ }
628
+ let moduleRanges = [];
629
+ for (let region of regions) {
630
+ if (region.kind !== "module") continue;
631
+ let range = readSourceRange(region, source.length);
632
+ range && moduleRanges.push(range);
633
+ }
634
+ for (let block of blocks) {
635
+ let range = readSourceRange(block.payload.range, source.length);
636
+ range && moduleRanges.some((module) => module.from <= range.from && module.to >= range.to) && projections.set(block.id, { kind: "module" });
637
+ }
638
+ let nativeChildIds = /* @__PURE__ */ new Set();
639
+ for (let projection of projections.values())
640
+ if (projection.kind === "render")
641
+ for (let id of projection.nativeFlowOwnedBlockIds ?? []) nativeChildIds.add(id);
642
+ for (let id of nativeChildIds) {
643
+ let projection = projections.get(id);
644
+ projection ? projections.set(id, { ...projection, nativeFlowParent: !0 }) : projections.set(id, { kind: "native-child", nativeFlowParent: !0 });
645
+ }
646
+ return Object.freeze(Object.fromEntries(projections));
647
+ }
648
+
649
+ // src/trusted-mdx/server.tsx
650
+ async function projectTrustedMdxServerDocument(options) {
651
+ let components = options.components ? Object.freeze({ ...options.components }) : Object.freeze({}), evaluated = await evaluateCompiledMdx(options.artifact.code, { imports: options.imports }, () => !0);
652
+ if (!evaluated)
653
+ throw new Error("Trusted MDX server evaluation was unexpectedly cancelled.");
654
+ let regionComponents = evaluated.createRegions({ components }), projections = projectMdxBlocks(options.source, options.blocks, options.artifact.regions, regionComponents), regions = [];
655
+ for (let [ownerId, projection] of Object.entries(projections)) {
656
+ if (projection.kind === "native-child") {
657
+ regions.push(Object.freeze({ ownerId, kind: "native-child" }));
658
+ continue;
659
+ }
660
+ if (projection.kind === "module") {
661
+ regions.push(Object.freeze({ ownerId, kind: "module", ...projection.nativeFlowParent ? { nativeFlowParent: !0 } : {} }));
662
+ continue;
663
+ }
664
+ if (projection.kind === "unmapped")
665
+ throw new Error(projection.diagnostic);
666
+ if (projection.kind !== "render")
667
+ throw new Error(`Trusted MDX owner "${ownerId}" has no server-renderable compiler regions.`);
668
+ if (projection.nativeChildren && (projection.rootElementName === void 0 || projection.regions.length !== 1))
669
+ throw new Error(`Trusted MDX owner "${ownerId}" has no unique compiler-authored native-children root.`);
670
+ let nativeChildrenOverride = projection.nativeChildren ? (fallback) => {
671
+ let owners = projection.nativeChildOwners, flowChildren = projection.flowChildren;
672
+ if (!owners || !flowChildren || owners.length !== flowChildren.length)
673
+ throw new Error(`Trusted MDX owner "${ownerId}" has misaligned native child owners.`);
674
+ assertTrustedMdxNativeChildContinuations(owners, flowChildren);
675
+ let children = owners.map((owner, index) => {
676
+ if (owner?.kind === "continuation") return null;
677
+ if (owner !== null)
678
+ return React2.createElement(TrustedMdxNativeChildrenSlot, {
679
+ index,
680
+ key: `${owner.kind}:${owner.blockId}:${index}`
681
+ });
682
+ let flowChild = flowChildren[index];
683
+ if (flowChild === void 0)
684
+ throw new Error(`Trusted MDX owner "${ownerId}" has a missing native flow child at index ${index}.`);
685
+ return React2.createElement(
686
+ React2.Fragment,
687
+ { key: `source:${flowChild.kind}:${flowChild.from}:${flowChild.to}` },
688
+ fallback(index)
689
+ );
690
+ });
691
+ return React2.createElement(TrustedMdxNativeChildrenSlot, null, children);
692
+ } : void 0, content = React2.createElement(
693
+ React2.Fragment,
694
+ null,
695
+ ...projection.regions.map((Region, index) => React2.createElement(
696
+ React2.Fragment,
697
+ { key: `${ownerId}:${index}` },
698
+ Region({
699
+ components,
700
+ ...nativeChildrenOverride === void 0 ? {} : { children: nativeChildrenOverride }
701
+ })
702
+ ))
703
+ );
704
+ regions.push(
705
+ Object.freeze({
706
+ ownerId,
707
+ kind: "render",
708
+ content,
709
+ placement: projection.placement,
710
+ ...projection.nativeChildren ? { nativeChildren: !0 } : {},
711
+ ...projection.nativeChildOwners ? { nativeChildOwners: projection.nativeChildOwners } : {},
712
+ ...projection.flowChildren ? { flowChildren: projection.flowChildren } : {},
713
+ ...projection.nativeFlowOwnedBlockIds ? { nativeFlowOwnedBlockIds: projection.nativeFlowOwnedBlockIds } : {},
714
+ ...projection.wholeBlockFlowRoot ? { wholeBlockFlowRoot: !0 } : {},
715
+ ...projection.nativeFlowParent ? { nativeFlowParent: !0 } : {},
716
+ ...projection.rootElementName === void 0 ? {} : { rootElementName: projection.rootElementName }
717
+ })
718
+ );
719
+ }
720
+ return Object.freeze({ regions: Object.freeze(regions), layout: evaluated.layout ?? null });
721
+ }
722
+ export {
723
+ projectTrustedMdxServerDocument
724
+ };