@stream-mdx/react 0.2.0 → 0.4.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.
@@ -0,0 +1,4226 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/mdx-client.ts
12
+ var mdx_client_exports = {};
13
+ __export(mdx_client_exports, {
14
+ MDXClient: () => MDXClient,
15
+ MDXComponentFactory: () => MDXComponentFactory,
16
+ getMDXClient: () => getMDXClient,
17
+ getMDXComponentFactory: () => getMDXComponentFactory,
18
+ registerInlineMdxModule: () => registerInlineMdxModule,
19
+ registerMDXComponents: () => registerMDXComponents
20
+ });
21
+ import React2 from "react";
22
+ import * as ReactJsxRuntime from "react/jsx-runtime";
23
+ function assignMdxChildKey(child, index) {
24
+ if (child == null) return child;
25
+ if (Array.isArray(child)) {
26
+ return child.map((entry, subIndex) => assignMdxChildKey(entry, `${index}-${subIndex}`));
27
+ }
28
+ if (React2.isValidElement(child)) {
29
+ if (child.key !== null && child.key !== void 0) {
30
+ return child;
31
+ }
32
+ return React2.cloneElement(child, { key: index });
33
+ }
34
+ return child;
35
+ }
36
+ function getMDXClient(compileEndpoint) {
37
+ if (!globalMDXClient) {
38
+ globalMDXClient = new MDXClient(compileEndpoint);
39
+ }
40
+ return globalMDXClient;
41
+ }
42
+ function getMDXComponentFactory(compileEndpoint) {
43
+ if (!globalComponentFactory) {
44
+ const client = getMDXClient(compileEndpoint);
45
+ globalComponentFactory = new MDXComponentFactory(client);
46
+ }
47
+ return globalComponentFactory;
48
+ }
49
+ function registerMDXComponents(components, options) {
50
+ const factory = getMDXComponentFactory();
51
+ factory.registerComponents(components, options);
52
+ }
53
+ function registerInlineMdxModule(compiled) {
54
+ const factory = getMDXComponentFactory();
55
+ factory.registerInlineModule({
56
+ id: compiled.id,
57
+ code: compiled.code,
58
+ dependencies: compiled.dependencies ?? []
59
+ });
60
+ }
61
+ var withClassName, MDXClient, MDXComponentFactory, globalMDXClient, globalComponentFactory;
62
+ var init_mdx_client = __esm({
63
+ "src/mdx-client.ts"() {
64
+ "use strict";
65
+ withClassName = (tag, className) => {
66
+ return (props) => React2.createElement(tag, { className, ...props });
67
+ };
68
+ MDXClient = class {
69
+ constructor(compileEndpoint = "/api/mdx-compile-v2") {
70
+ this.cache = /* @__PURE__ */ new Map();
71
+ this.inlineModules = /* @__PURE__ */ new Map();
72
+ this.compiledCache = /* @__PURE__ */ new Map();
73
+ this.compiledInflight = /* @__PURE__ */ new Map();
74
+ this.compileEndpoint = compileEndpoint;
75
+ }
76
+ /**
77
+ * Compile MDX block on server
78
+ */
79
+ async compile(block) {
80
+ if (block.type !== "mdx") {
81
+ throw new Error("Block is not MDX type");
82
+ }
83
+ const cacheKey = block.id;
84
+ const cachedPromise = this.cache.get(cacheKey);
85
+ if (cachedPromise) {
86
+ return cachedPromise;
87
+ }
88
+ const compilationPromise = this.doCompile(block);
89
+ this.cache.set(cacheKey, compilationPromise);
90
+ try {
91
+ const result = await compilationPromise;
92
+ return result;
93
+ } catch (error) {
94
+ this.cache.delete(cacheKey);
95
+ throw error;
96
+ }
97
+ }
98
+ async getCompiledInternal(ref) {
99
+ const inline = this.inlineModules.get(ref.id);
100
+ if (inline) {
101
+ return this.cloneCompiled(inline);
102
+ }
103
+ const cached = this.compiledCache.get(ref.id);
104
+ if (cached) {
105
+ return this.cloneCompiled(cached);
106
+ }
107
+ const inflight = this.compiledInflight.get(ref.id);
108
+ if (inflight) {
109
+ const resolved = await inflight;
110
+ return this.cloneCompiled(resolved);
111
+ }
112
+ const fetchPromise = this.fetchCompiled(ref);
113
+ this.compiledInflight.set(ref.id, fetchPromise);
114
+ try {
115
+ const data = await fetchPromise;
116
+ this.compiledCache.set(ref.id, data);
117
+ return this.cloneCompiled(data);
118
+ } finally {
119
+ this.compiledInflight.delete(ref.id);
120
+ }
121
+ }
122
+ async getCompiled(ref, options) {
123
+ if (options?.signal) {
124
+ const inline = this.inlineModules.get(ref.id);
125
+ if (inline) {
126
+ return this.cloneCompiled(inline);
127
+ }
128
+ const cached = this.compiledCache.get(ref.id);
129
+ if (cached) {
130
+ return this.cloneCompiled(cached);
131
+ }
132
+ const data = await this.fetchCompiled(ref, options);
133
+ this.compiledCache.set(ref.id, data);
134
+ return this.cloneCompiled(data);
135
+ }
136
+ return this.getCompiledInternal(ref);
137
+ }
138
+ /**
139
+ * Clear compilation cache
140
+ */
141
+ clearCache() {
142
+ this.cache.clear();
143
+ this.compiledCache.clear();
144
+ this.compiledInflight.clear();
145
+ }
146
+ registerInlineModule(compiled) {
147
+ this.inlineModules.set(compiled.id, {
148
+ ...compiled,
149
+ dependencies: Array.isArray(compiled.dependencies) ? [...compiled.dependencies] : []
150
+ });
151
+ }
152
+ clearInlineModules() {
153
+ this.inlineModules.clear();
154
+ }
155
+ /**
156
+ * Actual compilation implementation
157
+ */
158
+ async doCompile(block) {
159
+ const response = await fetch(this.compileEndpoint, {
160
+ method: "POST",
161
+ headers: {
162
+ "Content-Type": "application/json"
163
+ },
164
+ body: JSON.stringify({
165
+ content: block.payload.raw,
166
+ blockId: block.id
167
+ })
168
+ });
169
+ if (!response.ok) {
170
+ const error = await response.json().catch(() => ({ error: "Unknown error" }));
171
+ throw new Error(`MDX compilation failed: ${error.error || response.statusText}`);
172
+ }
173
+ const data = await response.json();
174
+ return {
175
+ id: data.id,
176
+ code: data.code,
177
+ dependencies: data.dependencies || [],
178
+ cached: data.cached || false
179
+ };
180
+ }
181
+ async fetchCompiled(ref, options) {
182
+ const response = await fetch(`${this.compileEndpoint}?id=${ref.id}`, {
183
+ signal: options?.signal
184
+ });
185
+ if (!response.ok) {
186
+ throw new Error(`Failed to get compiled MDX: ${response.statusText}`);
187
+ }
188
+ const data = await response.json();
189
+ return {
190
+ id: data.id,
191
+ code: data.code,
192
+ dependencies: data.dependencies || [],
193
+ timestamp: data.timestamp
194
+ };
195
+ }
196
+ cloneCompiled(compiled) {
197
+ return {
198
+ ...compiled,
199
+ dependencies: Array.isArray(compiled.dependencies) ? [...compiled.dependencies] : []
200
+ };
201
+ }
202
+ };
203
+ MDXComponentFactory = class {
204
+ constructor(mdxClient) {
205
+ this.components = /* @__PURE__ */ new Map();
206
+ this.customComponents = /* @__PURE__ */ new Map();
207
+ this.mdxClient = mdxClient;
208
+ this.baseComponents = this.createBaseComponents();
209
+ }
210
+ registerInlineModule(module) {
211
+ this.mdxClient.registerInlineModule(module);
212
+ this.components.delete(module.id);
213
+ }
214
+ /**
215
+ * Create React component from compiled MDX
216
+ */
217
+ async createComponent(ref) {
218
+ const cached = this.components.get(ref.id);
219
+ if (cached) {
220
+ return cached;
221
+ }
222
+ const compiled = await this.mdxClient.getCompiled(ref);
223
+ const component = this.evaluateCompiledMDX(compiled);
224
+ this.components.set(ref.id, component);
225
+ return component;
226
+ }
227
+ /**
228
+ * Safely evaluate compiled MDX code
229
+ */
230
+ evaluateCompiledMDX(compiled) {
231
+ try {
232
+ const context = this.createEvaluationContext();
233
+ const argNames = Object.keys(context);
234
+ const argValues = Object.values(context);
235
+ const moduleExports = new Function(...argNames, compiled.code)(...argValues);
236
+ const MDXComponent = this.resolveEvaluatedModule(moduleExports);
237
+ return (props) => {
238
+ const registryComponents = this.getComponents();
239
+ const incomingComponents = props?.components;
240
+ const mergedComponents = incomingComponents ? { ...registryComponents, ...incomingComponents } : registryComponents;
241
+ return React2.createElement(MDXComponent, {
242
+ ...props,
243
+ components: mergedComponents
244
+ });
245
+ };
246
+ } catch (error) {
247
+ console.error("Failed to evaluate MDX:", error);
248
+ return () => React2.createElement(
249
+ "div",
250
+ {
251
+ className: "mdx-error"
252
+ },
253
+ `MDX Error: ${error instanceof Error ? error.message : "Unknown error"}`
254
+ );
255
+ }
256
+ }
257
+ /**
258
+ * Create safe evaluation context for MDX
259
+ */
260
+ createEvaluationContext() {
261
+ const runtime = ReactJsxRuntime;
262
+ const createElementWithChildren = (type, props, key) => {
263
+ const baseProps = props ?? {};
264
+ const finalProps = key === void 0 || key === null ? baseProps : { ...baseProps, key };
265
+ if (Array.isArray(finalProps.children)) {
266
+ finalProps.children = finalProps.children.map((child, index) => assignMdxChildKey(child, index));
267
+ }
268
+ return React2.createElement(type, finalProps);
269
+ };
270
+ const runtimeJsx = typeof runtime.jsx === "function" ? runtime.jsx.bind(runtime) : createElementWithChildren;
271
+ const runtimeJsxs = typeof runtime.jsxs === "function" ? runtime.jsxs.bind(runtime) : createElementWithChildren;
272
+ const runtimeJsxDEV = typeof runtime.jsxDEV === "function" ? runtime.jsxDEV.bind(runtime) : (type, props, key, ..._rest) => createElementWithChildren(type, props, key);
273
+ const jsxRuntime = {
274
+ jsx: runtimeJsx,
275
+ jsxs: runtimeJsxs,
276
+ jsxDEV: runtimeJsxDEV,
277
+ Fragment: runtime.Fragment ?? React2.Fragment
278
+ };
279
+ return {
280
+ __mdx_runtime: jsxRuntime,
281
+ React: React2,
282
+ Fragment: React2.Fragment,
283
+ useState: React2.useState,
284
+ useEffect: React2.useEffect,
285
+ useMemo: React2.useMemo,
286
+ useCallback: React2.useCallback,
287
+ useRef: React2.useRef,
288
+ useContext: React2.useContext,
289
+ useReducer: React2.useReducer,
290
+ useLayoutEffect: React2.useLayoutEffect,
291
+ console: {
292
+ log: console.log,
293
+ warn: console.warn,
294
+ error: console.error
295
+ }
296
+ };
297
+ }
298
+ resolveEvaluatedModule(output) {
299
+ if (!output) {
300
+ throw new Error("Compiled MDX module returned no exports");
301
+ }
302
+ if (typeof output === "function") {
303
+ return output;
304
+ }
305
+ if (typeof output.default === "function") {
306
+ return output.default;
307
+ }
308
+ if (typeof output.MDXContent === "function") {
309
+ return output.MDXContent;
310
+ }
311
+ throw new Error("Compiled MDX module did not export a component");
312
+ }
313
+ getComponents() {
314
+ if (this.customComponents.size === 0) {
315
+ return { ...this.baseComponents };
316
+ }
317
+ const merged = { ...this.baseComponents };
318
+ for (const [key, component] of this.customComponents) {
319
+ merged[key] = component;
320
+ }
321
+ return merged;
322
+ }
323
+ /**
324
+ * Register or replace custom MDX components
325
+ */
326
+ registerComponents(components, options) {
327
+ if (options?.replace) {
328
+ this.customComponents.clear();
329
+ }
330
+ for (const [key, component] of Object.entries(components)) {
331
+ if (!component) continue;
332
+ this.customComponents.set(key, component);
333
+ }
334
+ }
335
+ /**
336
+ * Get base MDX components
337
+ */
338
+ createBaseComponents() {
339
+ return {
340
+ // Standard HTML elements
341
+ h1: withClassName("h1", "mdx-h1"),
342
+ h2: withClassName("h2", "mdx-h2"),
343
+ h3: withClassName("h3", "mdx-h3"),
344
+ h4: withClassName("h4", "mdx-h4"),
345
+ h5: withClassName("h5", "mdx-h5"),
346
+ h6: withClassName("h6", "mdx-h6"),
347
+ p: withClassName("p", "mdx-p"),
348
+ strong: withClassName("strong", "mdx-strong"),
349
+ em: withClassName("em", "mdx-em"),
350
+ code: withClassName("code", "mdx-code"),
351
+ pre: withClassName("pre", "mdx-pre"),
352
+ ul: withClassName("ul", "mdx-ul"),
353
+ ol: withClassName("ol", "mdx-ol"),
354
+ li: withClassName("li", "mdx-li"),
355
+ blockquote: withClassName("blockquote", "mdx-blockquote"),
356
+ a: (props) => React2.createElement("a", {
357
+ className: "mdx-link",
358
+ target: props.href?.startsWith("http") ? "_blank" : void 0,
359
+ rel: props.href?.startsWith("http") ? "noopener noreferrer" : void 0,
360
+ ...props
361
+ }),
362
+ img: (props) => React2.createElement("img", { className: "mdx-img", ...props }),
363
+ table: withClassName("table", "mdx-table"),
364
+ thead: withClassName("thead", "mdx-thead"),
365
+ tbody: withClassName("tbody", "mdx-tbody"),
366
+ tr: withClassName("tr", "mdx-tr"),
367
+ th: withClassName("th", "mdx-th"),
368
+ td: withClassName("td", "mdx-td")
369
+ };
370
+ }
371
+ /**
372
+ * Clear component cache
373
+ */
374
+ clearCache() {
375
+ this.components.clear();
376
+ }
377
+ clearCustomComponents() {
378
+ this.customComponents.clear();
379
+ }
380
+ };
381
+ globalMDXClient = null;
382
+ globalComponentFactory = null;
383
+ }
384
+ });
385
+
386
+ // src/renderer/blocks-renderer.tsx
387
+ import React8, { useMemo as useMemo3 } from "react";
388
+ import { getBlockKey, PATCH_ROOT_ID as PATCH_ROOT_ID2 } from "@stream-mdx/core";
389
+
390
+ // src/renderer/hooks.ts
391
+ import { useMemo, useSyncExternalStore } from "react";
392
+ function useRendererNode(store, id) {
393
+ const selector = useMemo(() => {
394
+ return () => store.getNodeWithVersion(id);
395
+ }, [store, id]);
396
+ const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
397
+ return snapshot.node;
398
+ }
399
+ function useRendererChildren(store, id) {
400
+ const selector = useMemo(() => {
401
+ return () => store.getChildrenWithVersion(id);
402
+ }, [store, id]);
403
+ const snapshot = useSyncExternalStore(store.subscribe, selector, selector);
404
+ return snapshot.children;
405
+ }
406
+
407
+ // src/renderer/node-views.tsx
408
+ import { stripCodeFence } from "@stream-mdx/core";
409
+ import React7 from "react";
410
+
411
+ // src/components/index.ts
412
+ import { createTrustedHTML, sanitizeHTML } from "@stream-mdx/core";
413
+
414
+ // src/mdx-hydration-metrics.ts
415
+ var entries = /* @__PURE__ */ new Map();
416
+ var lastHydrationMs = null;
417
+ function now() {
418
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
419
+ return performance.now();
420
+ }
421
+ return Date.now();
422
+ }
423
+ function markMdxHydrationStart(id) {
424
+ if (!id) return;
425
+ const entry = entries.get(id) ?? { status: "compiled" };
426
+ if (entry.startedAt === void 0) {
427
+ entry.startedAt = now();
428
+ }
429
+ entry.status = "compiled";
430
+ entries.set(id, entry);
431
+ }
432
+ function markMdxHydrated(id) {
433
+ if (!id) return;
434
+ const entry = entries.get(id) ?? { status: "hydrated" };
435
+ if (entry.startedAt === void 0) {
436
+ entry.startedAt = now();
437
+ }
438
+ entry.hydratedAt = now();
439
+ entry.status = "hydrated";
440
+ entries.set(id, entry);
441
+ lastHydrationMs = entry.startedAt ? entry.hydratedAt - entry.startedAt : null;
442
+ }
443
+ function markMdxHydrationError(id) {
444
+ if (!id) return;
445
+ const entry = entries.get(id) ?? { status: "error" };
446
+ entry.status = "error";
447
+ entries.set(id, entry);
448
+ }
449
+
450
+ // src/mdx-hydration-context.ts
451
+ import React from "react";
452
+ var MdxHydrationContext = React.createContext({ controller: null });
453
+
454
+ // src/mdx-runtime.ts
455
+ var mdxRuntimePromise = null;
456
+ function loadMdxRuntime() {
457
+ if (!mdxRuntimePromise) {
458
+ mdxRuntimePromise = Promise.resolve().then(() => (init_mdx_client(), mdx_client_exports));
459
+ }
460
+ return mdxRuntimePromise;
461
+ }
462
+
463
+ // src/renderer/use-deferred-render.ts
464
+ import { useEffect, useState } from "react";
465
+ function useDeferredRender(ref, options) {
466
+ const enabled = options?.enabled ?? true;
467
+ const [shouldRender, setShouldRender] = useState(!enabled);
468
+ useEffect(() => {
469
+ if (!enabled) {
470
+ setShouldRender(true);
471
+ return;
472
+ }
473
+ const target = ref.current;
474
+ if (!target) {
475
+ return;
476
+ }
477
+ let cancelled = false;
478
+ let idleId = null;
479
+ let timerId = null;
480
+ const scheduleRender = () => {
481
+ if (cancelled) return;
482
+ setShouldRender(true);
483
+ };
484
+ const runWithIdle = () => {
485
+ if (typeof globalThis.requestIdleCallback === "function") {
486
+ idleId = globalThis.requestIdleCallback(scheduleRender, { timeout: options?.idleTimeoutMs ?? 200 });
487
+ } else {
488
+ timerId = window.setTimeout(scheduleRender, options?.idleTimeoutMs ?? 200);
489
+ }
490
+ };
491
+ const observer = new IntersectionObserver(
492
+ (entries2) => {
493
+ for (const entry of entries2) {
494
+ if (entry.isIntersecting || entry.intersectionRatio > 0) {
495
+ observer.disconnect();
496
+ const debounceMs = options?.debounceMs ?? 80;
497
+ timerId = window.setTimeout(runWithIdle, debounceMs);
498
+ return;
499
+ }
500
+ }
501
+ },
502
+ { rootMargin: options?.rootMargin ?? "200px 0px" }
503
+ );
504
+ observer.observe(target);
505
+ return () => {
506
+ cancelled = true;
507
+ observer.disconnect();
508
+ if (idleId !== null && typeof globalThis.cancelIdleCallback === "function") {
509
+ globalThis.cancelIdleCallback(idleId);
510
+ }
511
+ if (timerId !== null) {
512
+ window.clearTimeout(timerId);
513
+ }
514
+ };
515
+ }, [enabled, options?.debounceMs, options?.idleTimeoutMs, options?.rootMargin, ref]);
516
+ return shouldRender;
517
+ }
518
+
519
+ // src/components/index.ts
520
+ import { removeHeadingMarkers } from "@stream-mdx/core";
521
+ import React4 from "react";
522
+
523
+ // src/utils/inline-html.ts
524
+ import React3 from "react";
525
+ var BACKTICK_CONTENT = /^`([\s\S]+)`$/;
526
+ var DEFAULT_INLINE_HTML_RENDERERS = {
527
+ kbd: (descriptor, ctx) => {
528
+ const trimmed = descriptor.rawInner.trim();
529
+ const match = BACKTICK_CONTENT.exec(trimmed);
530
+ if (match) {
531
+ const codeText = decodeHtmlEntities(match[1]);
532
+ const props = mapAttributesToProps(descriptor.attributes);
533
+ if (ctx.key !== void 0 && ctx.key !== null) {
534
+ props.key = ctx.key;
535
+ }
536
+ return React3.createElement("kbd", props, React3.createElement("code", { className: "inline-code" }, codeText));
537
+ }
538
+ return ctx.defaultRender();
539
+ }
540
+ };
541
+ function renderInlineHtmlSegment(raw, sanitized, options = {}) {
542
+ const descriptor = parseInlineHtmlDescriptor(raw, sanitized);
543
+ if (!descriptor) {
544
+ return null;
545
+ }
546
+ const className = options.className ?? "markdown-inline-html";
547
+ const isInlineTag = INLINE_ELEMENTS.has(descriptor.tagName);
548
+ const defaultRender = () => {
549
+ if (!descriptor.sanitized || descriptor.sanitized.length === 0) {
550
+ if (!descriptor.text) {
551
+ return null;
552
+ }
553
+ if (options.key !== void 0 && options.key !== null) {
554
+ return React3.createElement(React3.Fragment, { key: options.key }, descriptor.text);
555
+ }
556
+ return React3.createElement(React3.Fragment, {}, descriptor.text);
557
+ }
558
+ if (isInlineTag) {
559
+ const parsedElement = renderSanitizedHtmlTree(descriptor.sanitized, options.key);
560
+ if (parsedElement) {
561
+ return parsedElement;
562
+ }
563
+ }
564
+ const props = {
565
+ className,
566
+ dangerouslySetInnerHTML: { __html: descriptor.sanitized }
567
+ };
568
+ if (options.key !== void 0 && options.key !== null) {
569
+ props.key = options.key;
570
+ }
571
+ return React3.createElement("span", props);
572
+ };
573
+ const allRenderers = options.renderers ? { ...DEFAULT_INLINE_HTML_RENDERERS, ...options.renderers } : DEFAULT_INLINE_HTML_RENDERERS;
574
+ const renderer = allRenderers[descriptor.tagName];
575
+ if (renderer) {
576
+ const rendered = renderer(descriptor, { key: options.key, defaultRender });
577
+ if (rendered) {
578
+ if (options.key !== void 0 && options.key !== null && React3.isValidElement(rendered) && rendered.key === null) {
579
+ return React3.cloneElement(rendered, { key: options.key });
580
+ }
581
+ return rendered;
582
+ }
583
+ }
584
+ return defaultRender();
585
+ }
586
+ function parseInlineHtmlDescriptor(raw, sanitized) {
587
+ const normalizedRaw = typeof raw === "string" ? raw.trim() : "";
588
+ const normalizedSanitized = typeof sanitized === "string" && sanitized.length > 0 ? sanitized.trim() : normalizedRaw;
589
+ if (!normalizedSanitized) {
590
+ return null;
591
+ }
592
+ const match = normalizedSanitized.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
593
+ if (!match) {
594
+ return null;
595
+ }
596
+ const [, tagNameRaw, attrString = "", sanitizedInner = ""] = match;
597
+ const tagName = tagNameRaw.toLowerCase();
598
+ const attributes = parseAttributes(attrString);
599
+ let rawInner = "";
600
+ if (normalizedRaw) {
601
+ const rawMatch = normalizedRaw.match(/^<([A-Za-z][\w:-]*)(\s[^>]*)?>([\s\S]*)<\/\1>$/);
602
+ rawInner = rawMatch ? rawMatch[3] ?? "" : normalizedRaw;
603
+ }
604
+ const text = extractPlainText(rawInner || sanitizedInner);
605
+ return {
606
+ tagName,
607
+ attributes,
608
+ raw: normalizedRaw || normalizedSanitized,
609
+ sanitized: normalizedSanitized,
610
+ rawInner,
611
+ sanitizedInner,
612
+ text
613
+ };
614
+ }
615
+ function parseAttributes(input) {
616
+ const attrs = {};
617
+ if (!input) return attrs;
618
+ const attrPattern = /([A-Za-z_:][\w:.\-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
619
+ let match = attrPattern.exec(input);
620
+ while (match !== null) {
621
+ const name = match[1];
622
+ if (!name) continue;
623
+ const value = match[2] ?? match[3] ?? match[4] ?? "";
624
+ attrs[name] = value;
625
+ match = attrPattern.exec(input);
626
+ }
627
+ return attrs;
628
+ }
629
+ function mapAttributesToProps(attrs) {
630
+ const props = {};
631
+ for (const [key, value] of Object.entries(attrs)) {
632
+ if (key === "class") {
633
+ props.className = value;
634
+ } else if (key === "style") {
635
+ props.style = parseStyleAttribute(value);
636
+ } else if (key === "tabindex" || key === "tabIndex") {
637
+ const normalized = normalizeTabIndex(value);
638
+ if (normalized !== void 0) {
639
+ props.tabIndex = normalized;
640
+ }
641
+ } else {
642
+ props[key] = value;
643
+ }
644
+ }
645
+ return props;
646
+ }
647
+ function parseStyleAttribute(value) {
648
+ const style = {};
649
+ if (!value) return style;
650
+ const pairs = value.split(";");
651
+ for (const pair of pairs) {
652
+ if (!pair.trim()) continue;
653
+ const [property, rawVal] = pair.split(":");
654
+ if (!property || rawVal === void 0) continue;
655
+ const camelProp = property.trim().replace(/-([a-z])/g, (_, char) => char.toUpperCase());
656
+ style[camelProp] = rawVal.trim();
657
+ }
658
+ return style;
659
+ }
660
+ function normalizeTabIndex(value) {
661
+ const numeric = Number(value);
662
+ return Number.isNaN(numeric) ? void 0 : numeric;
663
+ }
664
+ function decodeHtmlEntities(value) {
665
+ return value.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
666
+ }
667
+ function extractPlainText(value) {
668
+ if (!value) return "";
669
+ const withoutTags = value.replace(/<\/?[^>]+>/g, "");
670
+ return decodeHtmlEntities(withoutTags);
671
+ }
672
+ function renderSanitizedHtmlTree(html, key) {
673
+ if (typeof DOMParser === "undefined") {
674
+ return null;
675
+ }
676
+ try {
677
+ const parser = new DOMParser();
678
+ const doc = parser.parseFromString(html, "text/html");
679
+ const body = doc.body;
680
+ const nodes = Array.from(body.childNodes);
681
+ if (nodes.length === 0) {
682
+ return null;
683
+ }
684
+ const baseKey = typeof key === "string" || typeof key === "number" ? String(key) : "inline-html";
685
+ const children = nodes.map((node, index) => convertDomNode(node, `${baseKey}-${index}`)).filter((child) => child !== null && child !== void 0);
686
+ if (children.length === 0) {
687
+ return null;
688
+ }
689
+ if (children.length === 1) {
690
+ const [child] = children;
691
+ if (React3.isValidElement(child)) {
692
+ if (key !== void 0 && key !== null) {
693
+ return React3.cloneElement(child, { key });
694
+ }
695
+ return child;
696
+ }
697
+ if (typeof child === "string" || typeof child === "number") {
698
+ if (key !== void 0 && key !== null) {
699
+ return React3.createElement(React3.Fragment, { key }, child);
700
+ }
701
+ return React3.createElement(React3.Fragment, {}, child);
702
+ }
703
+ return React3.createElement(React3.Fragment, { key }, child);
704
+ }
705
+ return React3.createElement(React3.Fragment, { key }, ...children);
706
+ } catch {
707
+ return null;
708
+ }
709
+ }
710
+ function convertDomNode(node, key) {
711
+ if (node.nodeType === Node.TEXT_NODE) {
712
+ return node.textContent ?? "";
713
+ }
714
+ if (node.nodeType !== Node.ELEMENT_NODE) {
715
+ return null;
716
+ }
717
+ const element = node;
718
+ const tagName = element.tagName.toLowerCase();
719
+ const attrs = getElementAttributes(element);
720
+ const props = mapAttributesToProps(attrs);
721
+ props.key = key;
722
+ const children = [];
723
+ element.childNodes.forEach((child, index) => {
724
+ const converted = convertDomNode(child, `${key}-${index}`);
725
+ if (converted !== null && converted !== void 0) {
726
+ children.push(converted);
727
+ }
728
+ });
729
+ if (children.length === 0) {
730
+ return React3.createElement(tagName, props);
731
+ }
732
+ return React3.createElement(tagName, props, ...children);
733
+ }
734
+ function getElementAttributes(element) {
735
+ const attrs = {};
736
+ for (const attr of Array.from(element.attributes)) {
737
+ attrs[attr.name] = attr.value;
738
+ }
739
+ return attrs;
740
+ }
741
+ var INLINE_ELEMENTS = /* @__PURE__ */ new Set([
742
+ "a",
743
+ "abbr",
744
+ "b",
745
+ "bdi",
746
+ "bdo",
747
+ "br",
748
+ "cite",
749
+ "code",
750
+ "data",
751
+ "dfn",
752
+ "em",
753
+ "i",
754
+ "kbd",
755
+ "mark",
756
+ "q",
757
+ "rp",
758
+ "rt",
759
+ "ruby",
760
+ "s",
761
+ "samp",
762
+ "small",
763
+ "span",
764
+ "strong",
765
+ "sub",
766
+ "sup",
767
+ "time",
768
+ "u",
769
+ "var",
770
+ // MathML inline elements commonly emitted by KaTeX
771
+ "annotation",
772
+ "semantics",
773
+ "mtext",
774
+ "mn",
775
+ "mo",
776
+ "mi",
777
+ "mspace",
778
+ "mrow",
779
+ "msup",
780
+ "msub",
781
+ "msubsup",
782
+ "munder",
783
+ "mover",
784
+ "munderover",
785
+ "msqrt",
786
+ "mroot",
787
+ "mtable",
788
+ "mtr",
789
+ "mtd"
790
+ ]);
791
+
792
+ // src/components/index.ts
793
+ var MdxRuntimeBoundary = class extends React4.Component {
794
+ constructor() {
795
+ super(...arguments);
796
+ this.state = { hasError: false };
797
+ }
798
+ static getDerivedStateFromError() {
799
+ return { hasError: true };
800
+ }
801
+ componentDidCatch(error) {
802
+ this.props.onError(error);
803
+ }
804
+ componentDidUpdate(prevProps) {
805
+ if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {
806
+ this.setState({ hasError: false });
807
+ }
808
+ }
809
+ render() {
810
+ if (this.state.hasError) {
811
+ return null;
812
+ }
813
+ return this.props.children;
814
+ }
815
+ };
816
+ function renderInlineNodes(nodes, components) {
817
+ return nodes.map((node, index) => {
818
+ const key = `${node.kind}-${index}`;
819
+ switch (node.kind) {
820
+ case "text": {
821
+ const textComponent = components.text;
822
+ if (textComponent && textComponent !== defaultInlineComponents.text) {
823
+ return React4.createElement(textComponent, { key, text: node.text });
824
+ }
825
+ return React4.createElement(React4.Fragment, { key, children: node.text });
826
+ }
827
+ case "strong":
828
+ return React4.createElement(components.strong, {
829
+ key,
830
+ children: renderInlineNodes(node.children, components)
831
+ });
832
+ case "em":
833
+ return React4.createElement(components.em, {
834
+ key,
835
+ children: renderInlineNodes(node.children, components)
836
+ });
837
+ case "strike": {
838
+ const StrikeComponent = components.strike ?? ((props) => React4.createElement("del", {}, props.children));
839
+ return React4.createElement(StrikeComponent, {
840
+ key,
841
+ children: renderInlineNodes(node.children, components)
842
+ });
843
+ }
844
+ case "code":
845
+ return React4.createElement(components.code, { key, text: node.text });
846
+ case "link":
847
+ return React4.createElement(
848
+ components.link,
849
+ {
850
+ key,
851
+ href: node.href,
852
+ title: node.title,
853
+ children: renderInlineNodes(node.children, components)
854
+ }
855
+ );
856
+ case "image":
857
+ return React4.createElement(components.image, {
858
+ key,
859
+ src: node.src,
860
+ alt: node.alt,
861
+ title: node.title
862
+ });
863
+ case "br":
864
+ return React4.createElement(React4.Fragment, { key }, React4.createElement(components.br, {}));
865
+ default: {
866
+ const component = components[node.kind];
867
+ if (component) {
868
+ return React4.createElement(component, { key, ...node });
869
+ }
870
+ return null;
871
+ }
872
+ }
873
+ });
874
+ }
875
+ var defaultInlineComponents = {
876
+ text: ({ text }) => React4.createElement(React4.Fragment, {}, text),
877
+ strong: ({ children }) => React4.createElement("strong", {}, children),
878
+ em: ({ children }) => React4.createElement("em", {}, children),
879
+ strike: ({ children }) => React4.createElement("del", {}, children),
880
+ code: ({ text }) => React4.createElement(
881
+ "code",
882
+ {
883
+ className: "inline-code"
884
+ },
885
+ text
886
+ ),
887
+ link: ({ href, title, children }) => React4.createElement(
888
+ "a",
889
+ {
890
+ href,
891
+ title,
892
+ className: "markdown-link",
893
+ target: href?.startsWith("http") ? "_blank" : void 0,
894
+ rel: href?.startsWith("http") ? "noopener noreferrer" : void 0
895
+ },
896
+ children
897
+ ),
898
+ image: ({ src, alt, title }) => React4.createElement("img", {
899
+ src,
900
+ alt,
901
+ title,
902
+ className: "markdown-image"
903
+ }),
904
+ br: () => React4.createElement("br"),
905
+ // Custom extensible components
906
+ mention: ({ handle }) => React4.createElement(
907
+ "span",
908
+ {
909
+ className: "mention",
910
+ "data-handle": handle
911
+ },
912
+ `@${handle}`
913
+ ),
914
+ citation: ({ id }) => React4.createElement(
915
+ "span",
916
+ {
917
+ className: "citation",
918
+ "data-citation-id": id
919
+ },
920
+ `[${id}]`
921
+ ),
922
+ "math-inline": ({ tex }) => React4.createElement(
923
+ "span",
924
+ {
925
+ className: "math-inline",
926
+ "data-tex": tex
927
+ },
928
+ `$${tex}$`
929
+ ),
930
+ "math-display": ({ tex }) => React4.createElement(
931
+ "div",
932
+ {
933
+ className: "math-display markdown-math-display",
934
+ "data-tex": tex,
935
+ style: { overflowX: "auto" }
936
+ },
937
+ React4.createElement("span", { className: "math-display-content" }, `$$${tex}$$`)
938
+ ),
939
+ // Footnote inline reference (superscript anchor)
940
+ "footnote-ref": ({ label, number }) => {
941
+ const n = number ?? "?";
942
+ const href = number ? `#fn:${n}` : void 0;
943
+ const id = number ? `fnref:${n}` : void 0;
944
+ return React4.createElement("sup", { className: "footnote-ref" }, React4.createElement("a", { href, id, "data-label": label }, String(n)));
945
+ }
946
+ };
947
+ var defaultBlockComponents = {
948
+ paragraph: ({ inlines, raw, meta, children }) => {
949
+ if (children !== void 0) {
950
+ return React4.createElement(
951
+ "p",
952
+ {
953
+ className: "markdown-paragraph"
954
+ },
955
+ children
956
+ );
957
+ }
958
+ const segments = Array.isArray(meta?.mixedSegments) ? meta?.mixedSegments : void 0;
959
+ if (segments && segments.length > 0) {
960
+ const structured = renderParagraphMixedSegments(segments, defaultInlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
961
+ if (structured.length === 1) {
962
+ return structured[0];
963
+ }
964
+ return React4.createElement(React4.Fragment, {}, ...structured);
965
+ }
966
+ const filteredInlines = inlines && raw && inlines.length > 0 ? inlines.filter((node) => !(node.kind === "text" && node.text === raw)) : inlines ?? [];
967
+ const effectiveInlines = filteredInlines.length > 0 ? filteredInlines : raw ? [
968
+ {
969
+ kind: "text",
970
+ text: raw
971
+ }
972
+ ] : [];
973
+ return React4.createElement(
974
+ "p",
975
+ {
976
+ className: "markdown-paragraph"
977
+ },
978
+ effectiveInlines.length > 0 ? renderInlineNodes(effectiveInlines, defaultInlineComponents) : raw ?? ""
979
+ );
980
+ },
981
+ heading: ({ level, inlines, text, meta }) => {
982
+ const tag = `h${level}`;
983
+ const onlyPlainText = Array.isArray(inlines) && inlines.length > 0 && inlines.every((node) => node.kind === "text");
984
+ const children = onlyPlainText ? inlines.map((node) => node.kind === "text" ? node.text : "").join("") : renderInlineNodes(inlines, defaultInlineComponents);
985
+ const headingId = typeof meta?.headingId === "string" && meta.headingId.length > 0 ? meta.headingId : void 0;
986
+ return React4.createElement(
987
+ tag,
988
+ {
989
+ className: `markdown-heading markdown-h${level}`,
990
+ ...text ? { "data-heading-text": text } : {},
991
+ ...headingId ? { id: headingId, "data-heading-id": headingId } : {}
992
+ },
993
+ children
994
+ );
995
+ },
996
+ code: ({ html, meta, lines, lang, preAttrs, codeAttrs }) => {
997
+ const language = typeof lang === "string" ? lang : typeof meta?.lang === "string" ? String(meta.lang) : "text";
998
+ if (html) {
999
+ return React4.createElement("div", {
1000
+ className: `markdown-code-block language-${language || "text"}`,
1001
+ /* biome-ignore lint/security/noDangerouslySetInnerHtml: highlighted HTML is generated by our sanitizer */
1002
+ dangerouslySetInnerHTML: { __html: html }
1003
+ });
1004
+ }
1005
+ const code = meta?.code || "";
1006
+ if (lines && lines.length > 0) {
1007
+ const preAttributes = attrsToProps(preAttrs);
1008
+ const codeAttributes = attrsToProps(codeAttrs);
1009
+ return React4.createElement(
1010
+ "pre",
1011
+ {
1012
+ ...preAttributes,
1013
+ className: preAttributes.className ? `${preAttributes.className} markdown-code-block language-${language || "text"}` : `markdown-code-block language-${language || "text"}`
1014
+ },
1015
+ React4.createElement(
1016
+ "code",
1017
+ {
1018
+ ...codeAttributes,
1019
+ className: codeAttributes.className ? `${codeAttributes.className} language-${language || "text"}` : `language-${language || "text"}`
1020
+ },
1021
+ lines.map(
1022
+ (line) => React4.createElement("span", {
1023
+ key: line.id,
1024
+ className: "line",
1025
+ /* biome-ignore lint/security/noDangerouslySetInnerHtml: line HTML is sanitized server-side */
1026
+ dangerouslySetInnerHTML: { __html: line.html ?? escapeHtml(line.text) }
1027
+ })
1028
+ )
1029
+ )
1030
+ );
1031
+ }
1032
+ return React4.createElement("pre", {
1033
+ className: `markdown-code-block language-${language || "text"}`,
1034
+ children: code
1035
+ });
1036
+ },
1037
+ blockquote: ({ inlines, renderedContent }) => React4.createElement(
1038
+ "blockquote",
1039
+ {
1040
+ className: "markdown-blockquote"
1041
+ },
1042
+ renderedContent ?? renderInlineNodes(inlines, defaultInlineComponents)
1043
+ ),
1044
+ hr: (props) => React4.createElement("hr", props),
1045
+ list: ({ ordered, items }) => {
1046
+ if (items.length === 0) {
1047
+ return null;
1048
+ }
1049
+ const tag = ordered ? "ol" : "ul";
1050
+ const listStyle = ordered ? {
1051
+ ["--list-indent"]: `calc(2.5rem + ${String(items.length).length}ch)`
1052
+ } : void 0;
1053
+ const listItems = items.map(
1054
+ (item, index) => React4.createElement(
1055
+ "li",
1056
+ {
1057
+ key: index,
1058
+ className: "markdown-list-item",
1059
+ "data-counter-text": ordered ? `${index + 1}.` : void 0,
1060
+ "data-list-depth": 0
1061
+ },
1062
+ renderInlineNodes(item, defaultInlineComponents)
1063
+ )
1064
+ );
1065
+ return React4.createElement(
1066
+ tag,
1067
+ {
1068
+ className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
1069
+ style: listStyle
1070
+ },
1071
+ listItems
1072
+ );
1073
+ },
1074
+ html: ({ __trustedHtml, elements }) => {
1075
+ const raw = typeof __trustedHtml === "string" ? __trustedHtml : __trustedHtml.toString();
1076
+ const htmlString = typeof window === "undefined" ? raw : sanitizeHTML(raw);
1077
+ if (typeof window !== "undefined" && elements) {
1078
+ const content = mapHtmlToReact(htmlString, elements);
1079
+ return React4.createElement("div", { className: "markdown-html" }, content);
1080
+ }
1081
+ return React4.createElement("div", {
1082
+ className: "markdown-html",
1083
+ /* biome-ignore lint/security/noDangerouslySetInnerHtml: htmlString is sanitized before injection */
1084
+ dangerouslySetInnerHTML: { __html: htmlString }
1085
+ });
1086
+ },
1087
+ mdx: ({ compiledRef, compiledModule, status, errorMessage, raw }) => {
1088
+ const [Comp, setComp] = React4.useState(null);
1089
+ const [internalError, setInternalError] = React4.useState(null);
1090
+ const [renderError, setRenderError] = React4.useState(null);
1091
+ const [retryKey, setRetryKey] = React4.useState(0);
1092
+ const hydrationContext = React4.useContext(MdxHydrationContext);
1093
+ const hydrationController = hydrationContext?.controller ?? null;
1094
+ const hydrationOptions = hydrationContext?.options;
1095
+ const containerRef = React4.useRef(null);
1096
+ const deferHydration = hydrationOptions?.strategy === "visible";
1097
+ const shouldHydrate = useDeferredRender(
1098
+ containerRef,
1099
+ deferHydration ? {
1100
+ enabled: true,
1101
+ rootMargin: hydrationOptions?.rootMargin,
1102
+ idleTimeoutMs: hydrationOptions?.idleTimeoutMs,
1103
+ debounceMs: hydrationOptions?.debounceMs
1104
+ } : { enabled: false }
1105
+ );
1106
+ const resolvedId = compiledModule?.id ?? (compiledRef?.id && compiledRef.id !== "pending" ? compiledRef.id : void 0);
1107
+ const handleRetry = React4.useCallback(() => {
1108
+ setInternalError(null);
1109
+ setRenderError(null);
1110
+ setComp(null);
1111
+ setRetryKey((prev) => prev + 1);
1112
+ }, []);
1113
+ const handleRuntimeError = React4.useCallback(
1114
+ (error) => {
1115
+ const message2 = error instanceof Error ? error.message : String(error);
1116
+ setRenderError(message2);
1117
+ markMdxHydrationError(resolvedId ?? compiledRef?.id);
1118
+ },
1119
+ [resolvedId, compiledRef?.id]
1120
+ );
1121
+ const effectiveStatus = status ? status : resolvedId ? "compiled" : "pending";
1122
+ const failureMessage = errorMessage ?? internalError ?? renderError ?? null;
1123
+ const moduleDependencies = compiledModule?.dependencies;
1124
+ React4.useEffect(() => {
1125
+ if (!shouldHydrate) {
1126
+ return;
1127
+ }
1128
+ if (status === "error") {
1129
+ markMdxHydrationError(resolvedId ?? compiledRef?.id);
1130
+ return;
1131
+ }
1132
+ let cancelled = false;
1133
+ async function ensure() {
1134
+ let permit = null;
1135
+ try {
1136
+ if (status === "error" || !resolvedId || resolvedId === "pending") {
1137
+ if (!cancelled) {
1138
+ setComp(null);
1139
+ setInternalError(null);
1140
+ }
1141
+ return;
1142
+ }
1143
+ if (hydrationController) {
1144
+ permit = await hydrationController.acquire();
1145
+ if (cancelled) {
1146
+ permit.release();
1147
+ return;
1148
+ }
1149
+ }
1150
+ setInternalError(null);
1151
+ setRenderError(null);
1152
+ markMdxHydrationStart(resolvedId);
1153
+ const { getMDXComponentFactory: getMDXComponentFactory2, registerInlineMdxModule: registerInlineMdxModule2 } = await loadMdxRuntime();
1154
+ if (compiledModule?.code) {
1155
+ registerInlineMdxModule2({
1156
+ id: compiledModule.id,
1157
+ code: compiledModule.code,
1158
+ dependencies: moduleDependencies ?? []
1159
+ });
1160
+ }
1161
+ const factory = getMDXComponentFactory2();
1162
+ const C = await factory.createComponent({ id: resolvedId });
1163
+ if (!cancelled) {
1164
+ setComp(() => C);
1165
+ setInternalError(null);
1166
+ markMdxHydrated(resolvedId);
1167
+ }
1168
+ } catch (error) {
1169
+ if (!cancelled) {
1170
+ const message2 = error instanceof Error ? error.message : String(error);
1171
+ setInternalError(message2);
1172
+ markMdxHydrationError(resolvedId);
1173
+ }
1174
+ } finally {
1175
+ permit?.release();
1176
+ }
1177
+ }
1178
+ ensure();
1179
+ return () => {
1180
+ cancelled = true;
1181
+ };
1182
+ }, [compiledModule?.id, compiledModule?.code, moduleDependencies, resolvedId, status, shouldHydrate, retryKey]);
1183
+ const compileMode = compiledModule?.source === "worker" || compiledRef?.id?.startsWith("worker:") ? "worker" : "server";
1184
+ const pendingId = resolvedId && resolvedId !== "pending" ? resolvedId : compiledRef?.id ?? "pending";
1185
+ const waitingForVisibility = deferHydration && !shouldHydrate && Boolean(resolvedId);
1186
+ const pendingLabel = waitingForVisibility ? "MDX ready (hydrate on view)\u2026" : compileMode === "worker" ? "Compiling MDX (client)\u2026" : "Compiling MDX (server)\u2026";
1187
+ const message = failureMessage ?? (compileMode === "worker" ? "MDX compilation failed in client mode. Try switching back to server rendering or restarting the stream." : "MDX compilation failed. Try restarting the stream.");
1188
+ const rawFallback = typeof raw === "string" && raw.trim().length > 0 ? React4.createElement("pre", { className: "markdown-mdx-fallback" }, raw) : null;
1189
+ const allowRetry = Boolean(internalError || renderError);
1190
+ const retryButton = allowRetry ? React4.createElement(
1191
+ "button",
1192
+ {
1193
+ type: "button",
1194
+ className: "markdown-mdx-retry",
1195
+ onClick: handleRetry
1196
+ },
1197
+ "Retry hydration"
1198
+ ) : null;
1199
+ const errorPanel = React4.createElement(
1200
+ "div",
1201
+ { className: "markdown-mdx-error" },
1202
+ React4.createElement(React4.Fragment, null, React4.createElement("strong", null, "MDX failed"), React4.createElement("div", null, message))
1203
+ );
1204
+ if (Comp && !failureMessage) {
1205
+ return React4.createElement(
1206
+ "div",
1207
+ {
1208
+ className: "markdown-mdx",
1209
+ ref: containerRef,
1210
+ "data-mdx-ref": resolvedId ?? compiledRef?.id ?? "compiled",
1211
+ "data-mdx-status": failureMessage ? "error" : "compiled",
1212
+ "data-mdx-mode": compileMode
1213
+ },
1214
+ React4.createElement(
1215
+ MdxRuntimeBoundary,
1216
+ { resetKey: retryKey, onError: handleRuntimeError },
1217
+ React4.createElement(Comp, {})
1218
+ )
1219
+ );
1220
+ }
1221
+ if (failureMessage) {
1222
+ return React4.createElement(
1223
+ "div",
1224
+ {
1225
+ className: "markdown-mdx",
1226
+ ref: containerRef,
1227
+ "data-mdx-ref": pendingId,
1228
+ "data-mdx-status": "error",
1229
+ "data-mdx-mode": compileMode
1230
+ },
1231
+ errorPanel,
1232
+ rawFallback,
1233
+ retryButton
1234
+ );
1235
+ }
1236
+ if (!Comp) {
1237
+ return React4.createElement(
1238
+ "div",
1239
+ {
1240
+ className: "markdown-mdx",
1241
+ ref: containerRef,
1242
+ "data-mdx-ref": pendingId,
1243
+ "data-mdx-status": "pending",
1244
+ "data-mdx-mode": compileMode
1245
+ },
1246
+ pendingLabel
1247
+ );
1248
+ }
1249
+ },
1250
+ // Footnotes block rendered at page end
1251
+ footnotes: ({ items }) => {
1252
+ if (!items || items.length === 0) return React4.createElement(React4.Fragment, null);
1253
+ const listItems = items.map(
1254
+ (item) => React4.createElement(
1255
+ "li",
1256
+ { key: item.number, id: `fn:${item.number}` },
1257
+ renderInlineNodes(item.inlines, defaultInlineComponents),
1258
+ " ",
1259
+ React4.createElement("a", { href: `#fnref:${item.number}`, className: "footnote-backref", "aria-label": "Back to content" }, "\u21A9")
1260
+ )
1261
+ );
1262
+ return React4.createElement("section", { className: "footnotes" }, React4.createElement("hr", {}), React4.createElement("ol", {}, listItems));
1263
+ },
1264
+ // Footnote definition placeholders (render nothing)
1265
+ "footnote-def": () => React4.createElement(React4.Fragment, null),
1266
+ // Callouts block
1267
+ callout: ({ kind, inlines = [] }) => {
1268
+ const tone = (kind || "NOTE").toUpperCase();
1269
+ const title = tone.charAt(0) + tone.slice(1).toLowerCase();
1270
+ return React4.createElement(
1271
+ "div",
1272
+ { className: `markdown-callout markdown-callout-${tone.toLowerCase()} border rounded p-3 my-3` },
1273
+ React4.createElement("div", { className: "font-semibold mb-1" }, title),
1274
+ inlines.length > 0 ? renderInlineNodes(inlines, defaultInlineComponents) : null
1275
+ );
1276
+ },
1277
+ // Structured table block (GFM)
1278
+ table: ({
1279
+ header,
1280
+ rows,
1281
+ align,
1282
+ elements
1283
+ }) => {
1284
+ const El = getDefaultTableElements(elements);
1285
+ const renderCells = (cells, tag, rowIdx) => cells.map((cell, i) => {
1286
+ const columnAlign = align?.[i] ?? void 0;
1287
+ const cellStyle = columnAlign ? { textAlign: columnAlign } : void 0;
1288
+ return React4.createElement(
1289
+ tag === "th" ? El.Th : El.Td,
1290
+ {
1291
+ key: `${rowIdx}-${i}`,
1292
+ style: cellStyle,
1293
+ // Also pass align attribute so CSS selectors like [&[align=center]] can be used by consumers
1294
+ align: columnAlign ?? void 0
1295
+ },
1296
+ renderInlineNodes(cell, defaultInlineComponents)
1297
+ );
1298
+ });
1299
+ return React4.createElement(
1300
+ El.Table,
1301
+ { className: "markdown-table" },
1302
+ header && header.length > 0 ? React4.createElement(El.Thead, {}, React4.createElement(El.Tr, {}, renderCells(header, "th", -1))) : null,
1303
+ React4.createElement(
1304
+ El.Tbody,
1305
+ {},
1306
+ rows.map((row, r) => React4.createElement(El.Tr, { key: r }, renderCells(row, "td", r)))
1307
+ )
1308
+ );
1309
+ }
1310
+ };
1311
+ var ComponentRegistry = class {
1312
+ constructor(blockComponents = {}, inlineComponents = {}) {
1313
+ this.blockComponentMapCache = null;
1314
+ this.inlineComponentMapCache = null;
1315
+ this.blockComponents = { ...defaultBlockComponents, ...blockComponents };
1316
+ this.inlineComponents = { ...defaultInlineComponents, ...inlineComponents };
1317
+ this.htmlElements = getDefaultHtmlElements();
1318
+ this.tableElements = getDefaultTableElements();
1319
+ }
1320
+ /**
1321
+ * Update block components
1322
+ */
1323
+ setBlockComponents(components) {
1324
+ this.blockComponents = { ...this.blockComponents, ...components };
1325
+ this.blockComponentMapCache = null;
1326
+ }
1327
+ /**
1328
+ * Update inline components
1329
+ */
1330
+ setInlineComponents(components) {
1331
+ this.inlineComponents = { ...this.inlineComponents, ...components };
1332
+ this.inlineComponentMapCache = null;
1333
+ }
1334
+ /** Update HTML element mapping for html blocks */
1335
+ setHtmlElements(map) {
1336
+ this.htmlElements = { ...this.htmlElements, ...map };
1337
+ }
1338
+ /** Update table element mapping for table blocks */
1339
+ setTableElements(map) {
1340
+ this.tableElements = { ...this.tableElements, ...map };
1341
+ }
1342
+ /**
1343
+ * Get block component
1344
+ */
1345
+ getBlockComponent(type) {
1346
+ return this.blockComponents[type] || this.blockComponents.paragraph;
1347
+ }
1348
+ /**
1349
+ * Get inline components
1350
+ */
1351
+ getInlineComponents() {
1352
+ return this.inlineComponents;
1353
+ }
1354
+ getBlockComponentMap() {
1355
+ if (!this.blockComponentMapCache) {
1356
+ this.blockComponentMapCache = { ...this.blockComponents };
1357
+ }
1358
+ return this.blockComponentMapCache;
1359
+ }
1360
+ getInlineComponentMap() {
1361
+ if (!this.inlineComponentMapCache) {
1362
+ this.inlineComponentMapCache = { ...this.inlineComponents };
1363
+ }
1364
+ return this.inlineComponentMapCache;
1365
+ }
1366
+ getTableElements() {
1367
+ return this.tableElements;
1368
+ }
1369
+ /**
1370
+ * Render a block
1371
+ */
1372
+ renderBlock(block) {
1373
+ const Component = this.getBlockComponent(block.type);
1374
+ const props = this.getBlockProps(block);
1375
+ return React4.createElement(Component, {
1376
+ key: block.id,
1377
+ ...props
1378
+ });
1379
+ }
1380
+ /**
1381
+ * Get props for a block based on its type
1382
+ */
1383
+ getBlockProps(block) {
1384
+ switch (block.type) {
1385
+ case "heading": {
1386
+ const meta = block.payload.meta ?? {};
1387
+ const inlineNodes = Array.isArray(block.payload.inline) ? block.payload.inline : [];
1388
+ const levelFromMeta = typeof meta.headingLevel === "number" ? meta.headingLevel : void 0;
1389
+ const normalizedLevel = Number.isFinite(levelFromMeta) ? Math.min(Math.max(levelFromMeta, 1), 6) : void 0;
1390
+ const rawHeading = typeof block.payload.raw === "string" ? block.payload.raw : "";
1391
+ const headingText = typeof meta.headingText === "string" && meta.headingText.trim().length > 0 ? meta.headingText : removeHeadingMarkers(rawHeading).trim();
1392
+ const level = normalizedLevel ?? this.extractHeadingLevel(rawHeading);
1393
+ return {
1394
+ level,
1395
+ inlines: inlineNodes,
1396
+ text: headingText,
1397
+ meta
1398
+ };
1399
+ }
1400
+ case "paragraph":
1401
+ return {
1402
+ inlines: block.payload.inline || [],
1403
+ raw: block.payload.raw,
1404
+ meta: block.payload.meta
1405
+ };
1406
+ case "blockquote":
1407
+ return {
1408
+ inlines: block.payload.inline || []
1409
+ };
1410
+ case "hr": {
1411
+ const range = block.payload.range;
1412
+ return {
1413
+ className: "markdown-hr",
1414
+ "data-start": typeof range?.from === "number" ? range.from : void 0,
1415
+ "data-end": typeof range?.to === "number" ? range.to : void 0
1416
+ };
1417
+ }
1418
+ case "code":
1419
+ return {
1420
+ html: block.payload.highlightedHtml,
1421
+ meta: block.payload.meta,
1422
+ lang: typeof block.payload.meta?.lang === "string" ? String(block.payload.meta?.lang) : void 0
1423
+ };
1424
+ case "list": {
1425
+ const items = Array.isArray(block.payload.meta?.items) ? block.payload.meta?.items : [];
1426
+ return {
1427
+ ordered: Boolean(block.payload.meta?.ordered),
1428
+ items
1429
+ };
1430
+ }
1431
+ case "html": {
1432
+ const trusted = block.payload.sanitizedHtml ?? block.payload.raw;
1433
+ return {
1434
+ // Server render should not depend on DOMPurify (which requires a DOM `window`).
1435
+ // In worker-compiled flows, `sanitizedHtml` is already sanitized at the source.
1436
+ __trustedHtml: typeof window === "undefined" ? String(trusted ?? "") : createTrustedHTML(String(trusted ?? "")),
1437
+ elements: this.htmlElements
1438
+ };
1439
+ }
1440
+ case "mdx":
1441
+ return (() => {
1442
+ const meta = block.payload.meta;
1443
+ const rawStatus = typeof meta?.mdxStatus === "string" ? meta.mdxStatus : void 0;
1444
+ const status = rawStatus === "pending" || rawStatus === "compiled" || rawStatus === "error" ? rawStatus : void 0;
1445
+ const errorMessage = typeof meta?.mdxError === "string" ? String(meta.mdxError) : void 0;
1446
+ const compiledModule = block.payload.compiledMdxModule ?? null;
1447
+ const compiledRef = block.payload.compiledMdxRef ?? (compiledModule ? { id: compiledModule.id } : void 0);
1448
+ return {
1449
+ compiledRef: compiledRef ?? { id: "pending" },
1450
+ compiledModule,
1451
+ status,
1452
+ errorMessage,
1453
+ raw: typeof block.payload.raw === "string" ? block.payload.raw : void 0
1454
+ };
1455
+ })();
1456
+ case "table": {
1457
+ const header = Array.isArray(block.payload.meta?.header) ? block.payload.meta?.header : void 0;
1458
+ const rows = Array.isArray(block.payload.meta?.rows) ? block.payload.meta?.rows : [];
1459
+ const align = Array.isArray(block.payload.meta?.align) ? block.payload.meta?.align : void 0;
1460
+ return {
1461
+ header,
1462
+ rows,
1463
+ align,
1464
+ elements: this.tableElements
1465
+ };
1466
+ }
1467
+ case "footnotes": {
1468
+ const items = Array.isArray(block.payload.meta?.items) ? block.payload.meta?.items : [];
1469
+ return {
1470
+ items
1471
+ };
1472
+ }
1473
+ case "footnote-def":
1474
+ return {};
1475
+ case "callout": {
1476
+ const kind = typeof block.payload.meta?.kind === "string" ? String(block.payload.meta.kind) : void 0;
1477
+ const inlineNodes = Array.isArray(block.payload.inline) ? block.payload.inline : [];
1478
+ return {
1479
+ kind,
1480
+ inlines: inlineNodes
1481
+ };
1482
+ }
1483
+ default:
1484
+ return {
1485
+ content: block.payload.raw,
1486
+ meta: block.payload.meta
1487
+ };
1488
+ }
1489
+ }
1490
+ /**
1491
+ * Extract heading level from raw markdown
1492
+ */
1493
+ extractHeadingLevel(raw) {
1494
+ const match = raw.match(/^(#{1,6})\s/);
1495
+ if (match) {
1496
+ return Math.min(match[1].length, 6);
1497
+ }
1498
+ return 1;
1499
+ }
1500
+ };
1501
+ function getDefaultHtmlElements() {
1502
+ return {
1503
+ // Text semantics
1504
+ p: (props) => React4.createElement("p", props),
1505
+ strong: (props) => React4.createElement("strong", props),
1506
+ em: (props) => React4.createElement("em", props),
1507
+ code: (props) => React4.createElement("code", props),
1508
+ pre: (props) => React4.createElement("pre", props),
1509
+ span: (props) => React4.createElement("span", props),
1510
+ br: (props) => React4.createElement("br", props),
1511
+ hr: (props) => React4.createElement("hr", props),
1512
+ // Lists
1513
+ ul: (props) => React4.createElement("ul", props),
1514
+ ol: (props) => React4.createElement("ol", props),
1515
+ li: (props) => React4.createElement("li", props),
1516
+ // Links & media
1517
+ a: (props) => React4.createElement("a", props),
1518
+ img: (props) => React4.createElement("img", props),
1519
+ // Blockquotes
1520
+ blockquote: (props) => React4.createElement("blockquote", props),
1521
+ // Tables
1522
+ table: (props) => React4.createElement("table", props),
1523
+ thead: (props) => React4.createElement("thead", props),
1524
+ tbody: (props) => React4.createElement("tbody", props),
1525
+ tr: (props) => React4.createElement("tr", props),
1526
+ th: (props) => React4.createElement("th", props),
1527
+ td: (props) => React4.createElement("td", props),
1528
+ // Generic
1529
+ div: (props) => React4.createElement("div", props)
1530
+ };
1531
+ }
1532
+ function getDefaultTableElements(overrides) {
1533
+ const base = {
1534
+ Table: (props) => React4.createElement("table", props),
1535
+ Thead: (props) => React4.createElement("thead", props),
1536
+ Tbody: (props) => React4.createElement("tbody", props),
1537
+ Tr: (props) => React4.createElement("tr", props),
1538
+ Th: (props) => React4.createElement("th", props),
1539
+ Td: (props) => React4.createElement("td", props)
1540
+ };
1541
+ return { ...base, ...overrides || {} };
1542
+ }
1543
+ function mapHtmlToReact(html, elements) {
1544
+ const parser = new DOMParser();
1545
+ const doc = parser.parseFromString(html, "text/html");
1546
+ const children = [];
1547
+ doc.body.childNodes.forEach((node, index) => {
1548
+ const element = toReact(node, elements, `root-${index}`);
1549
+ if (element) {
1550
+ children.push(element);
1551
+ }
1552
+ });
1553
+ return React4.createElement(React4.Fragment, {}, ...children);
1554
+ }
1555
+ function toReact(node, elements, key) {
1556
+ if (node.nodeType === Node.TEXT_NODE) {
1557
+ const text = node.textContent ?? "";
1558
+ return React4.createElement(React4.Fragment, { key }, text);
1559
+ }
1560
+ if (node.nodeType !== Node.ELEMENT_NODE) {
1561
+ return null;
1562
+ }
1563
+ const el = node;
1564
+ const tag = el.tagName.toLowerCase();
1565
+ const props = {};
1566
+ for (const attr of Array.from(el.attributes)) {
1567
+ const name = attr.name === "class" ? "className" : attr.name;
1568
+ props[name] = attr.value;
1569
+ }
1570
+ const children = [];
1571
+ el.childNodes.forEach((childNode, childIndex) => {
1572
+ const child = toReact(childNode, elements, `${key}-${childIndex}`);
1573
+ if (child) {
1574
+ children.push(child);
1575
+ }
1576
+ });
1577
+ const component = elements[tag];
1578
+ const elementChildren = children.length > 0 ? children : void 0;
1579
+ if (component) {
1580
+ return React4.createElement(component, { ...props, key }, elementChildren);
1581
+ }
1582
+ return React4.createElement(tag, { ...props, key }, elementChildren);
1583
+ }
1584
+ function attrsToProps(attrs) {
1585
+ if (!attrs) return {};
1586
+ const result = {};
1587
+ for (const [key, value] of Object.entries(attrs)) {
1588
+ if (key === "class") {
1589
+ result.className = value;
1590
+ } else if (key === "style") {
1591
+ result.style = parseStyleAttribute2(value);
1592
+ } else if (key === "tabindex" || key === "tabIndex") {
1593
+ const numericValue = Number(value);
1594
+ if (!Number.isNaN(numericValue)) {
1595
+ result.tabIndex = numericValue;
1596
+ }
1597
+ } else {
1598
+ result[key] = value;
1599
+ }
1600
+ }
1601
+ return result;
1602
+ }
1603
+ function escapeHtml(value) {
1604
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1605
+ }
1606
+ function parseStyleAttribute2(value) {
1607
+ const style = {};
1608
+ if (!value) return style;
1609
+ const parts = value.split(";");
1610
+ for (const part of parts) {
1611
+ if (!part.trim()) continue;
1612
+ const [prop, val] = part.split(":");
1613
+ if (!prop || !val) continue;
1614
+ const camelProp = prop.trim().replace(/-([a-z])/g, (_, char) => char.toUpperCase());
1615
+ style[camelProp] = val.trim();
1616
+ }
1617
+ return style;
1618
+ }
1619
+ function renderParagraphMixedSegments(segments, inlineComponents, inlineHtmlRenderers) {
1620
+ const result = [];
1621
+ let inlineBuffer = [];
1622
+ let inlineGroupIndex = 0;
1623
+ const pushRenderedNodes = (nodes, target, baseKey) => {
1624
+ nodes.forEach((node, idx) => {
1625
+ if (node === null || node === void 0) return;
1626
+ const key = `${baseKey}-${idx}`;
1627
+ if (React4.isValidElement(node)) {
1628
+ target.push(node.key === key ? node : React4.cloneElement(node, { key }));
1629
+ } else if (typeof node === "string" || typeof node === "number") {
1630
+ target.push(React4.createElement(React4.Fragment, { key }, node));
1631
+ } else {
1632
+ target.push(React4.createElement(React4.Fragment, { key }, node));
1633
+ }
1634
+ });
1635
+ };
1636
+ const ensureArray2 = (value) => {
1637
+ if (value === null || value === void 0) {
1638
+ return [];
1639
+ }
1640
+ return Array.isArray(value) ? value : [value];
1641
+ };
1642
+ const flushInline = () => {
1643
+ if (inlineBuffer.length === 0) {
1644
+ return;
1645
+ }
1646
+ const key = `paragraph-inline-group-${inlineGroupIndex++}`;
1647
+ result.push(
1648
+ React4.createElement(
1649
+ "p",
1650
+ {
1651
+ key,
1652
+ className: "markdown-paragraph"
1653
+ },
1654
+ inlineBuffer
1655
+ )
1656
+ );
1657
+ inlineBuffer = [];
1658
+ };
1659
+ segments.forEach((segment, index) => {
1660
+ const key = `paragraph-segment-${index}`;
1661
+ switch (segment.kind) {
1662
+ case "text": {
1663
+ const inlineNodes = Array.isArray(segment.inline) ? segment.inline : [];
1664
+ if (inlineNodes.length === 0) {
1665
+ if (segment.value) {
1666
+ inlineBuffer.push(React4.createElement(React4.Fragment, { key }, segment.value));
1667
+ }
1668
+ break;
1669
+ }
1670
+ let chunk = [];
1671
+ const pushChunk = (chunkNodes, chunkKey) => {
1672
+ if (chunkNodes.length === 0) return;
1673
+ const rendered = renderInlineNodes(chunkNodes, inlineComponents);
1674
+ pushRenderedNodes(ensureArray2(rendered), inlineBuffer, chunkKey);
1675
+ };
1676
+ inlineNodes.forEach((inlineNode, inlineIdx) => {
1677
+ if (inlineNode.kind === "math-display") {
1678
+ pushChunk(chunk, `${key}-chunk-${inlineIdx}`);
1679
+ chunk = [];
1680
+ flushInline();
1681
+ const rendered = renderInlineNodes([inlineNode], inlineComponents);
1682
+ pushRenderedNodes(ensureArray2(rendered), result, `${key}-math-${inlineIdx}`);
1683
+ } else {
1684
+ chunk.push(inlineNode);
1685
+ }
1686
+ });
1687
+ pushChunk(chunk, `${key}-chunk-tail`);
1688
+ break;
1689
+ }
1690
+ case "mdx": {
1691
+ const status = segment.status ?? "pending";
1692
+ let element;
1693
+ if (status === "compiled") {
1694
+ element = React4.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
1695
+ } else if (status === "error") {
1696
+ const message = segment.value || "MDX error";
1697
+ element = React4.createElement("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error" }, message);
1698
+ } else {
1699
+ element = React4.createElement("span", { className: "markdown-mdx-inline", "data-mdx-status": status }, segment.value);
1700
+ }
1701
+ inlineBuffer.push(React4.createElement(React4.Fragment, { key }, element));
1702
+ break;
1703
+ }
1704
+ case "html": {
1705
+ const html = segment.sanitized ?? segment.value;
1706
+ const isBlockLevel = isBlockLevelHtml(html);
1707
+ const element = renderInlineHtmlSegment(segment.value, segment.sanitized, {
1708
+ key,
1709
+ renderers: inlineHtmlRenderers
1710
+ });
1711
+ if (isBlockLevel) {
1712
+ flushInline();
1713
+ if (element) {
1714
+ result.push(element);
1715
+ } else if (html) {
1716
+ result.push(
1717
+ React4.createElement("div", {
1718
+ key,
1719
+ className: "markdown-inline-html-block",
1720
+ dangerouslySetInnerHTML: { __html: html }
1721
+ })
1722
+ );
1723
+ }
1724
+ } else if (element) {
1725
+ inlineBuffer.push(element);
1726
+ }
1727
+ break;
1728
+ }
1729
+ default:
1730
+ break;
1731
+ }
1732
+ });
1733
+ flushInline();
1734
+ if (result.length === 0) {
1735
+ return [
1736
+ React4.createElement(
1737
+ "p",
1738
+ {
1739
+ key: "paragraph-inline-group-0",
1740
+ className: "markdown-paragraph"
1741
+ },
1742
+ inlineBuffer
1743
+ )
1744
+ ];
1745
+ }
1746
+ return result;
1747
+ }
1748
+ function isBlockLevelHtml(html) {
1749
+ if (!html) return false;
1750
+ const trimmed = html.trim();
1751
+ if (!trimmed.startsWith("<")) {
1752
+ return false;
1753
+ }
1754
+ const match = trimmed.match(/^<([A-Za-z][\w:-]*)\b/);
1755
+ if (!match) {
1756
+ return false;
1757
+ }
1758
+ const tag = match[1].toLowerCase();
1759
+ return BLOCK_LEVEL_TAGS.has(tag);
1760
+ }
1761
+ var BLOCK_LEVEL_TAGS = /* @__PURE__ */ new Set([
1762
+ "address",
1763
+ "article",
1764
+ "aside",
1765
+ "blockquote",
1766
+ "canvas",
1767
+ "div",
1768
+ "dl",
1769
+ "fieldset",
1770
+ "figcaption",
1771
+ "figure",
1772
+ "footer",
1773
+ "form",
1774
+ "h1",
1775
+ "h2",
1776
+ "h3",
1777
+ "h4",
1778
+ "h5",
1779
+ "h6",
1780
+ "header",
1781
+ "hr",
1782
+ "li",
1783
+ "main",
1784
+ "nav",
1785
+ "ol",
1786
+ "p",
1787
+ "pre",
1788
+ "section",
1789
+ "table",
1790
+ "ul",
1791
+ "math"
1792
+ ]);
1793
+
1794
+ // src/renderer/code-highlight-context.tsx
1795
+ import React5 from "react";
1796
+ var CodeHighlightRequestContext = React5.createContext(null);
1797
+ function useCodeHighlightRequester() {
1798
+ return React5.useContext(CodeHighlightRequestContext);
1799
+ }
1800
+
1801
+ // src/renderer/deferred-render-context.tsx
1802
+ import React6 from "react";
1803
+ var DeferredRenderContext = React6.createContext(null);
1804
+
1805
+ // src/renderer/store.ts
1806
+ import {
1807
+ cloneBlock,
1808
+ createBlockSnapshot,
1809
+ extractCodeWrapperAttributes,
1810
+ getDefaultCodeWrapperAttributes,
1811
+ sanitizeCodeHTML,
1812
+ sanitizeHTML as sanitizeHTML2,
1813
+ PATCH_ROOT_ID
1814
+ } from "@stream-mdx/core";
1815
+
1816
+ // src/renderer/list-utils.ts
1817
+ function updateNodeDepth(node, depth) {
1818
+ if (!node) return false;
1819
+ const currentDepth = typeof node.props?.depth === "number" ? node.props.depth : void 0;
1820
+ if (currentDepth === depth) {
1821
+ return false;
1822
+ }
1823
+ const nextProps = { ...node.props ?? {} };
1824
+ nextProps.depth = depth;
1825
+ node.props = nextProps;
1826
+ node.version++;
1827
+ return true;
1828
+ }
1829
+ function normalizeAllListDepths(map, touched, rootId = "__root__") {
1830
+ const root = map.get(rootId);
1831
+ if (!root) return;
1832
+ for (const childId of root.children) {
1833
+ const child = map.get(childId);
1834
+ if (child && child.type === "list") {
1835
+ normalizeListDepthRecursive(map, child, 0, touched);
1836
+ }
1837
+ }
1838
+ }
1839
+ function normalizeListDepthsForIds(map, touched, listIds, rootId = "__root__") {
1840
+ if (listIds.size === 0) {
1841
+ normalizeAllListDepths(map, touched, rootId);
1842
+ return;
1843
+ }
1844
+ const visited = /* @__PURE__ */ new Set();
1845
+ for (const listId of listIds) {
1846
+ const base = map.get(listId);
1847
+ if (!base) continue;
1848
+ const listNode = base.type === "list" ? base : findNearestListAncestor(map, base);
1849
+ if (!listNode || visited.has(listNode.id)) continue;
1850
+ visited.add(listNode.id);
1851
+ const depth = computeListDepth(map, listNode, rootId);
1852
+ normalizeListDepthRecursive(map, listNode, depth, touched);
1853
+ }
1854
+ }
1855
+ function normalizeListDepthRecursive(map, listNode, depth, touched) {
1856
+ if (!listNode) return;
1857
+ if (updateNodeDepth(listNode, depth)) {
1858
+ touched.add(listNode.id);
1859
+ }
1860
+ for (const childId of listNode.children) {
1861
+ const child = map.get(childId);
1862
+ if (!child) continue;
1863
+ if (child.type === "list-item") {
1864
+ if (updateNodeDepth(child, depth)) {
1865
+ touched.add(child.id);
1866
+ }
1867
+ for (const grandchildId of child.children) {
1868
+ const grandchild = map.get(grandchildId);
1869
+ if (!grandchild) continue;
1870
+ if (grandchild.type === "list") {
1871
+ normalizeListDepthRecursive(map, grandchild, depth + 1, touched);
1872
+ }
1873
+ }
1874
+ } else if (child.type === "list") {
1875
+ normalizeListDepthRecursive(map, child, depth + 1, touched);
1876
+ }
1877
+ }
1878
+ }
1879
+ function findNearestListAncestor(map, node) {
1880
+ let current = node;
1881
+ while (current) {
1882
+ if (current.type === "list") return current;
1883
+ if (!current.parentId) return void 0;
1884
+ current = map.get(current.parentId);
1885
+ }
1886
+ return void 0;
1887
+ }
1888
+ function computeListDepth(map, listNode, rootId) {
1889
+ let depth = 0;
1890
+ let current = listNode;
1891
+ while (current && current.parentId && current.parentId !== rootId) {
1892
+ const parent = map.get(current.parentId);
1893
+ if (!parent) break;
1894
+ if (parent.type === "list") {
1895
+ depth += 1;
1896
+ }
1897
+ current = parent;
1898
+ }
1899
+ return depth;
1900
+ }
1901
+
1902
+ // src/renderer/patch-coalescing.ts
1903
+ import {
1904
+ DEFAULT_COALESCE_CONFIG,
1905
+ coalescePatches,
1906
+ coalescePatchesLinear,
1907
+ coalescePatchesQuadratic,
1908
+ coalescePatchesWithMetrics
1909
+ } from "@stream-mdx/core";
1910
+
1911
+ // src/renderer/store.ts
1912
+ function snapshotToBlock(node) {
1913
+ const candidate = node.props?.block;
1914
+ if (candidate && typeof candidate === "object") {
1915
+ return cloneBlock(candidate);
1916
+ }
1917
+ return null;
1918
+ }
1919
+ var nodeSnapshotCache = /* @__PURE__ */ new Map();
1920
+ var childrenSnapshotCache = /* @__PURE__ */ new Map();
1921
+ var NODE_SNAPSHOT_CACHE_LIMIT = 5e4;
1922
+ var CHILDREN_SNAPSHOT_CACHE_LIMIT = 5e4;
1923
+ var NODE_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(NODE_SNAPSHOT_CACHE_LIMIT * 0.1));
1924
+ var CHILDREN_SNAPSHOT_CACHE_BUFFER = Math.max(200, Math.floor(CHILDREN_SNAPSHOT_CACHE_LIMIT * 0.1));
1925
+ function pruneCache(cache, max, buffer) {
1926
+ if (cache.size <= max + buffer) return;
1927
+ let remaining = cache.size - max;
1928
+ for (const key of cache.keys()) {
1929
+ cache.delete(key);
1930
+ remaining -= 1;
1931
+ if (remaining <= 0) break;
1932
+ }
1933
+ }
1934
+ var EMPTY_CHILDREN = Object.freeze([]);
1935
+ var EMPTY_NODE_SNAPSHOT = Object.freeze({ version: -1, node: void 0 });
1936
+ var EMPTY_CHILDREN_SNAPSHOT = Object.freeze({
1937
+ version: -1,
1938
+ children: EMPTY_CHILDREN
1939
+ });
1940
+ function isListPatchDebugEnabled() {
1941
+ if (typeof globalThis !== "undefined") {
1942
+ const flag = globalThis.__STREAMING_LIST_DEBUG__;
1943
+ if (flag === true) return true;
1944
+ }
1945
+ if (typeof process !== "undefined" && process.env.NEXT_PUBLIC_STREAMING_LIST_DEBUG === "true") {
1946
+ return true;
1947
+ }
1948
+ return false;
1949
+ }
1950
+ var CODE_BLOCK_DEBUG_ENABLED = (() => {
1951
+ try {
1952
+ if (typeof process !== "undefined" && process.env && process.env.NEXT_PUBLIC_STREAMING_DEBUG_CODELINES === "1") {
1953
+ return true;
1954
+ }
1955
+ if (typeof globalThis !== "undefined") {
1956
+ const debug = globalThis?.__STREAMING_DEBUG__;
1957
+ if (debug?.codeLines) {
1958
+ return true;
1959
+ }
1960
+ }
1961
+ } catch {
1962
+ }
1963
+ return false;
1964
+ })() || false;
1965
+ var CODE_BLOCK_VALIDATION_ENABLED = typeof process !== "undefined" && process.env ? process.env.NODE_ENV !== "production" : true;
1966
+ var PATCH_PERF_HISTORY_LIMIT = 120;
1967
+ var getPerfNow = (() => {
1968
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
1969
+ return () => performance.now();
1970
+ }
1971
+ return () => Date.now();
1972
+ })();
1973
+ function isPatchPerfDebugEnabled() {
1974
+ try {
1975
+ if (typeof process !== "undefined" && process.env) {
1976
+ const value = process.env.NEXT_PUBLIC_STREAMING_DEBUG_PATCH_PERF;
1977
+ if (value === "1" || value === "true") {
1978
+ return true;
1979
+ }
1980
+ }
1981
+ } catch {
1982
+ }
1983
+ try {
1984
+ const debug = globalThis.__STREAMING_DEBUG__;
1985
+ if (debug?.patchPerf) {
1986
+ return true;
1987
+ }
1988
+ } catch {
1989
+ }
1990
+ return false;
1991
+ }
1992
+ function recordPatchPerf(summary) {
1993
+ try {
1994
+ if (typeof globalThis === "undefined") return;
1995
+ const root = globalThis;
1996
+ const history = root.__STREAM_MDX_PATCH_STATS__ ?? [];
1997
+ history.push(summary);
1998
+ if (history.length > PATCH_PERF_HISTORY_LIMIT) {
1999
+ history.splice(0, history.length - PATCH_PERF_HISTORY_LIMIT);
2000
+ }
2001
+ root.__STREAM_MDX_PATCH_STATS__ = history;
2002
+ root.__STREAM_MDX_PATCH_STATS_LAST__ = summary;
2003
+ const totals = root.__STREAM_MDX_PATCH_STATS_TOTALS__ ?? {
2004
+ calls: 0,
2005
+ totalMs: 0,
2006
+ applyMs: 0,
2007
+ coalesceMs: 0,
2008
+ listNormalizeMs: 0,
2009
+ patches: 0,
2010
+ coalescedPatches: 0,
2011
+ ops: {},
2012
+ setPropsByType: {},
2013
+ setPropsBySize: {}
2014
+ };
2015
+ totals.calls += 1;
2016
+ totals.totalMs += summary.totalMs;
2017
+ totals.applyMs += summary.applyMs;
2018
+ totals.coalesceMs += summary.coalesceMs;
2019
+ totals.listNormalizeMs += summary.listNormalizeMs;
2020
+ totals.patches += summary.patches;
2021
+ totals.coalescedPatches += summary.coalescedPatches;
2022
+ for (const [op, stats] of Object.entries(summary.ops)) {
2023
+ const entry = totals.ops[op] ?? { count: 0, durationMs: 0 };
2024
+ entry.count += stats.count;
2025
+ entry.durationMs += stats.durationMs;
2026
+ totals.ops[op] = entry;
2027
+ }
2028
+ if (summary.setPropsByType) {
2029
+ for (const [key, stats] of Object.entries(summary.setPropsByType)) {
2030
+ const entry = totals.setPropsByType[key] ?? { count: 0, durationMs: 0 };
2031
+ entry.count += stats.count;
2032
+ entry.durationMs += stats.durationMs;
2033
+ totals.setPropsByType[key] = entry;
2034
+ }
2035
+ }
2036
+ if (summary.setPropsBySize) {
2037
+ for (const [key, stats] of Object.entries(summary.setPropsBySize)) {
2038
+ const entry = totals.setPropsBySize[key] ?? { count: 0, durationMs: 0 };
2039
+ entry.count += stats.count;
2040
+ entry.durationMs += stats.durationMs;
2041
+ totals.setPropsBySize[key] = entry;
2042
+ }
2043
+ }
2044
+ root.__STREAM_MDX_PATCH_STATS_TOTALS__ = totals;
2045
+ } catch {
2046
+ }
2047
+ }
2048
+ function estimateBlockPayloadSize(block) {
2049
+ if (!block || !block.payload) return 0;
2050
+ let size = 0;
2051
+ const payload = block.payload;
2052
+ if (typeof payload.raw === "string") size += payload.raw.length;
2053
+ if (typeof payload.highlightedHtml === "string") size += payload.highlightedHtml.length;
2054
+ if (typeof payload.sanitizedHtml === "string") size += payload.sanitizedHtml.length;
2055
+ if (typeof payload.compiledMdxModule?.code === "string") size += payload.compiledMdxModule.code.length;
2056
+ if (Array.isArray(payload.inline)) size += payload.inline.length * 8;
2057
+ return size;
2058
+ }
2059
+ function estimatePropsSize(props, block) {
2060
+ let size = 0;
2061
+ if (props) {
2062
+ for (const [key, value] of Object.entries(props)) {
2063
+ if (key === "block") continue;
2064
+ if (typeof value === "string") {
2065
+ size += value.length;
2066
+ } else if (typeof value === "number") {
2067
+ size += 8;
2068
+ } else if (typeof value === "boolean") {
2069
+ size += 4;
2070
+ } else if (Array.isArray(value)) {
2071
+ size += value.length * 4;
2072
+ }
2073
+ }
2074
+ }
2075
+ if (block) {
2076
+ size += estimateBlockPayloadSize(block);
2077
+ }
2078
+ return size;
2079
+ }
2080
+ function bucketBySize(size) {
2081
+ if (size < 1024) return "<1k";
2082
+ if (size < 10 * 1024) return "1-10k";
2083
+ if (size < 50 * 1024) return "10-50k";
2084
+ if (size < 200 * 1024) return "50-200k";
2085
+ return ">=200k";
2086
+ }
2087
+ function debugCodeBlock(event, payload) {
2088
+ if (!CODE_BLOCK_DEBUG_ENABLED) return;
2089
+ try {
2090
+ console.debug(`[renderer-store][code-block] ${event}`, payload);
2091
+ } catch {
2092
+ }
2093
+ }
2094
+ function createRootRecord() {
2095
+ return {
2096
+ id: PATCH_ROOT_ID,
2097
+ type: "__root__",
2098
+ parentId: null,
2099
+ children: [],
2100
+ props: {},
2101
+ version: 0
2102
+ };
2103
+ }
2104
+ function ensureArray(value) {
2105
+ return Array.isArray(value) ? value : [];
2106
+ }
2107
+ function shallowEqualRecords(a, b) {
2108
+ if (a === b) return true;
2109
+ if (!a || !b) {
2110
+ return !a && !b;
2111
+ }
2112
+ const keysA = Object.keys(a);
2113
+ const keysB = Object.keys(b);
2114
+ if (keysA.length !== keysB.length) return false;
2115
+ for (const key of keysA) {
2116
+ if (!Object.prototype.hasOwnProperty.call(b, key)) {
2117
+ return false;
2118
+ }
2119
+ if (a[key] !== b[key]) {
2120
+ return false;
2121
+ }
2122
+ }
2123
+ return true;
2124
+ }
2125
+ function ensureUniqueChildren(parent, touched) {
2126
+ if (!parent || parent.children.length <= 1) {
2127
+ return;
2128
+ }
2129
+ const seen = /* @__PURE__ */ new Set();
2130
+ const deduped = [];
2131
+ let mutated = false;
2132
+ for (const childId of parent.children) {
2133
+ if (seen.has(childId)) {
2134
+ mutated = true;
2135
+ continue;
2136
+ }
2137
+ seen.add(childId);
2138
+ deduped.push(childId);
2139
+ }
2140
+ if (mutated) {
2141
+ parent.children = deduped;
2142
+ parent.version++;
2143
+ if (touched) {
2144
+ touched.add(parent.id);
2145
+ }
2146
+ console.error("[renderer-store] removed duplicate children", {
2147
+ parentId: parent.id,
2148
+ deduped: parent.children.slice()
2149
+ });
2150
+ }
2151
+ }
2152
+ function parseLineIndexFromId(id) {
2153
+ const match = id.match(/::line:(\d+)$/);
2154
+ if (!match) return Number.NaN;
2155
+ const value = Number(match[1]);
2156
+ return Number.isFinite(value) ? value : Number.NaN;
2157
+ }
2158
+ function escapeHtml2(value) {
2159
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2160
+ }
2161
+ function stripOuterLineSpan(html) {
2162
+ if (!html) return null;
2163
+ const openTagMatch = html.match(/<span[^>]*>/i);
2164
+ if (!openTagMatch) {
2165
+ return null;
2166
+ }
2167
+ const openTag = openTagMatch[0];
2168
+ const startIndex = html.indexOf(openTag);
2169
+ if (startIndex === -1) {
2170
+ return null;
2171
+ }
2172
+ const contentStart = startIndex + openTag.length;
2173
+ const endIndex = html.lastIndexOf("</span>");
2174
+ if (endIndex === -1 || endIndex < contentStart) {
2175
+ return null;
2176
+ }
2177
+ return html.slice(contentStart, endIndex);
2178
+ }
2179
+ function sanitizeLineInnerHtml(innerHtml, fallbackText) {
2180
+ if (innerHtml && innerHtml.trim().length > 0) {
2181
+ const wrapped = `<span class="line">${innerHtml}</span>`;
2182
+ const sanitized = sanitizeCodeHTML(wrapped);
2183
+ const inner = stripOuterLineSpan(typeof sanitized === "string" ? sanitized : String(sanitized));
2184
+ if (inner !== null) {
2185
+ return inner;
2186
+ }
2187
+ }
2188
+ return escapeHtml2(fallbackText);
2189
+ }
2190
+ function normalizeCodeBlockChildren(nodes, parent, touched) {
2191
+ if (parent.type !== "code") return;
2192
+ const previousChildren = parent.children.slice();
2193
+ const originalOrder = /* @__PURE__ */ new Map();
2194
+ const seenIds = /* @__PURE__ */ new Set();
2195
+ const codeLineNodes = [];
2196
+ const anomalies = [];
2197
+ for (let idx = 0; idx < previousChildren.length; idx++) {
2198
+ const childId = previousChildren[idx];
2199
+ const node = nodes.get(childId);
2200
+ if (!node) {
2201
+ anomalies.push(`missing:${childId}`);
2202
+ continue;
2203
+ }
2204
+ if (node.parentId !== parent.id) {
2205
+ node.parentId = parent.id;
2206
+ node.version++;
2207
+ touched.add(node.id);
2208
+ }
2209
+ if (node.type !== "code-line") {
2210
+ anomalies.push(`type-mismatch:${node.id}:${node.type}`);
2211
+ nodes.delete(node.id);
2212
+ nodeSnapshotCache.delete(node.id);
2213
+ childrenSnapshotCache.delete(node.id);
2214
+ touched.add(node.id);
2215
+ continue;
2216
+ }
2217
+ if (seenIds.has(childId)) {
2218
+ anomalies.push(`duplicate-id:${childId}`);
2219
+ continue;
2220
+ }
2221
+ seenIds.add(childId);
2222
+ codeLineNodes.push(node);
2223
+ originalOrder.set(node.id, idx);
2224
+ }
2225
+ if (anomalies.length > 0) {
2226
+ debugCodeBlock("code-block-anomalies", {
2227
+ parentId: parent.id,
2228
+ anomalies,
2229
+ children: previousChildren
2230
+ });
2231
+ if (anomalies.some((entry) => entry.startsWith("duplicate-id"))) {
2232
+ console.warn("[renderer-store] duplicate code-line ids detected", {
2233
+ parentId: parent.id,
2234
+ anomalies,
2235
+ children: previousChildren
2236
+ });
2237
+ }
2238
+ }
2239
+ const sorted = codeLineNodes.slice().sort((a, b) => {
2240
+ const ai = typeof a.props?.index === "number" ? a.props.index : parseLineIndexFromId(a.id);
2241
+ const bi = typeof b.props?.index === "number" ? b.props.index : parseLineIndexFromId(b.id);
2242
+ if (Number.isFinite(ai) && Number.isFinite(bi) && ai !== bi) {
2243
+ return ai - bi;
2244
+ }
2245
+ const ao = originalOrder.get(a.id) ?? 0;
2246
+ const bo = originalOrder.get(b.id) ?? 0;
2247
+ return ao - bo;
2248
+ });
2249
+ const nextChildren = [];
2250
+ let mutated = false;
2251
+ for (let idx = 0; idx < sorted.length; idx++) {
2252
+ const node = sorted[idx];
2253
+ const desiredId = `${parent.id}::line:${idx}`;
2254
+ const existing = nodes.get(desiredId);
2255
+ if (existing && existing !== node) {
2256
+ nodes.delete(desiredId);
2257
+ nodeSnapshotCache.delete(desiredId);
2258
+ childrenSnapshotCache.delete(desiredId);
2259
+ touched.add(desiredId);
2260
+ mutated = true;
2261
+ }
2262
+ if (node.id !== desiredId) {
2263
+ const previousId = node.id;
2264
+ nodes.delete(node.id);
2265
+ nodeSnapshotCache.delete(previousId);
2266
+ childrenSnapshotCache.delete(previousId);
2267
+ node.id = desiredId;
2268
+ nodes.set(desiredId, node);
2269
+ touched.add(desiredId);
2270
+ mutated = true;
2271
+ } else if (!nodes.has(desiredId)) {
2272
+ nodes.set(desiredId, node);
2273
+ }
2274
+ if (node.parentId !== parent.id) {
2275
+ node.parentId = parent.id;
2276
+ node.version++;
2277
+ touched.add(node.id);
2278
+ mutated = true;
2279
+ }
2280
+ const incoming = { index: idx, text: node.props?.text, html: node.props?.html };
2281
+ if (Object.prototype.hasOwnProperty.call(node.props ?? {}, "tokens")) {
2282
+ incoming.tokens = node.props.tokens;
2283
+ }
2284
+ const normalizedProps = normalizeCodeLineProps(incoming, node.props);
2285
+ if (normalizedProps !== node.props) {
2286
+ node.props = normalizedProps;
2287
+ node.version++;
2288
+ touched.add(node.id);
2289
+ mutated = true;
2290
+ }
2291
+ nextChildren.push(desiredId);
2292
+ }
2293
+ const allowed = new Set(nextChildren);
2294
+ for (const [id, record] of nodes) {
2295
+ if (record.parentId === parent.id && record.type === "code-line" && !allowed.has(id)) {
2296
+ nodes.delete(id);
2297
+ nodeSnapshotCache.delete(id);
2298
+ childrenSnapshotCache.delete(id);
2299
+ touched.add(id);
2300
+ mutated = true;
2301
+ }
2302
+ }
2303
+ if (!arraysEqual(previousChildren, nextChildren)) {
2304
+ parent.children = nextChildren;
2305
+ parent.version++;
2306
+ touched.add(parent.id);
2307
+ mutated = true;
2308
+ }
2309
+ const duplicateIds = [];
2310
+ const postSeenIds = /* @__PURE__ */ new Set();
2311
+ for (const childId of parent.children) {
2312
+ if (postSeenIds.has(childId)) {
2313
+ duplicateIds.push(childId);
2314
+ } else {
2315
+ postSeenIds.add(childId);
2316
+ }
2317
+ }
2318
+ if (duplicateIds.length > 0) {
2319
+ console.error("[renderer-store] duplicate code-line children detected post-normalize", {
2320
+ parentId: parent.id,
2321
+ duplicates: duplicateIds,
2322
+ children: parent.children.slice()
2323
+ });
2324
+ }
2325
+ if (mutated) {
2326
+ debugCodeBlock("code-block-normalized", {
2327
+ parentId: parent.id,
2328
+ children: parent.children.slice()
2329
+ });
2330
+ }
2331
+ if (CODE_BLOCK_VALIDATION_ENABLED) {
2332
+ const validation = validateCodeBlockChildren(nodes, parent);
2333
+ if (!validation.ok) {
2334
+ debugCodeBlock("code-block-validation-failed", {
2335
+ parentId: parent.id,
2336
+ issues: validation.issues
2337
+ });
2338
+ if (!rebuildCodeBlockFromSnapshot(nodes, parent, touched, validation.issues)) {
2339
+ console.warn("[renderer-store] unable to fully normalize code block", {
2340
+ parentId: parent.id,
2341
+ issues: validation.issues
2342
+ });
2343
+ }
2344
+ }
2345
+ }
2346
+ }
2347
+ function normalizeCodeLineProps(incoming, previous) {
2348
+ const previousIndex = typeof previous?.index === "number" ? previous?.index : 0;
2349
+ const index = typeof incoming.index === "number" ? incoming.index : previousIndex;
2350
+ const previousText = typeof previous?.text === "string" ? previous?.text : "";
2351
+ const previousHtml = typeof previous?.html === "string" ? previous?.html : null;
2352
+ const previousTokens = Object.prototype.hasOwnProperty.call(previous ?? {}, "tokens") ? previous?.tokens : void 0;
2353
+ const hasIncomingText = typeof incoming.text === "string";
2354
+ const hasIncomingHtml = typeof incoming.html === "string";
2355
+ const hasIncomingTokens = Object.prototype.hasOwnProperty.call(incoming, "tokens");
2356
+ const incomingTokens = hasIncomingTokens ? incoming.tokens : void 0;
2357
+ const rawText = hasIncomingText ? incoming.text : previousText;
2358
+ if (previous && !hasIncomingHtml && !hasIncomingTokens && index === previousIndex && (!hasIncomingText || rawText === previousText)) {
2359
+ return previous;
2360
+ }
2361
+ if (previous && hasIncomingHtml && !hasIncomingTokens && incoming.html === previousHtml && index === previousIndex && (!hasIncomingText || rawText === previousText)) {
2362
+ return previous;
2363
+ }
2364
+ let highlight = null;
2365
+ if (hasIncomingHtml) {
2366
+ highlight = incoming.html;
2367
+ } else if (!hasIncomingText || rawText === previousText) {
2368
+ highlight = previousHtml;
2369
+ }
2370
+ let tokens = void 0;
2371
+ if (hasIncomingTokens) {
2372
+ tokens = incomingTokens ?? null;
2373
+ } else if (!hasIncomingText || rawText === previousText) {
2374
+ tokens = previousTokens;
2375
+ } else {
2376
+ tokens = null;
2377
+ }
2378
+ return createCodeLineProps(index, rawText, highlight, tokens);
2379
+ }
2380
+ function createCodeLineProps(index, text, highlight, tokens) {
2381
+ const safeText = typeof text === "string" ? text : "";
2382
+ const sanitized = sanitizeLineInnerHtml(highlight, safeText);
2383
+ const html = sanitized && sanitized.length >= safeText.length ? sanitized : escapeHtml2(safeText);
2384
+ const props = {
2385
+ index,
2386
+ text: safeText,
2387
+ html
2388
+ };
2389
+ if (tokens !== void 0) {
2390
+ props.tokens = tokens;
2391
+ }
2392
+ return props;
2393
+ }
2394
+ function clampIndex(index, length) {
2395
+ if (!Number.isFinite(index)) return 0;
2396
+ if (length <= 0) return 0;
2397
+ return Math.max(0, Math.min(index, length));
2398
+ }
2399
+ var INLINE_SEGMENT_TYPES = /* @__PURE__ */ new Set(["paragraph-text", "blockquote-text", "list-item-text"]);
2400
+ function isInlineSegmentType(type) {
2401
+ return INLINE_SEGMENT_TYPES.has(type);
2402
+ }
2403
+ function mergeInlineSegmentProps(previous, incoming) {
2404
+ const result = previous ? { ...previous } : {};
2405
+ for (const [key, value] of Object.entries(incoming)) {
2406
+ if (value === void 0) {
2407
+ delete result[key];
2408
+ } else {
2409
+ result[key] = value;
2410
+ }
2411
+ }
2412
+ const inlineProvided = Object.prototype.hasOwnProperty.call(incoming, "inline");
2413
+ if (inlineProvided) {
2414
+ const inlineValue = Array.isArray(incoming.inline) ? incoming.inline : void 0;
2415
+ if (inlineValue) {
2416
+ result.inline = inlineValue;
2417
+ } else {
2418
+ result.inline = void 0;
2419
+ }
2420
+ } else if (previous && Array.isArray(previous.inline) && !Array.isArray(result.inline)) {
2421
+ result.inline = previous.inline;
2422
+ }
2423
+ const textProvided = Object.prototype.hasOwnProperty.call(incoming, "text");
2424
+ if (textProvided) {
2425
+ result.text = typeof incoming.text === "string" ? incoming.text : "";
2426
+ } else if (previous && typeof previous.text === "string" && typeof result.text !== "string") {
2427
+ result.text = previous.text;
2428
+ }
2429
+ return result;
2430
+ }
2431
+ function applyCodeBlockMetadata(record) {
2432
+ const block = record.block;
2433
+ const highlightedHtml = block?.payload.highlightedHtml ?? "";
2434
+ const lang = typeof block?.payload.meta?.lang === "string" ? block?.payload.meta?.lang : record.props?.lang;
2435
+ let { preAttrs, codeAttrs } = extractCodeWrapperAttributes(highlightedHtml);
2436
+ if (!preAttrs || !codeAttrs) {
2437
+ const defaults = getDefaultCodeWrapperAttributes(typeof lang === "string" ? lang : void 0);
2438
+ preAttrs = preAttrs ?? defaults.preAttrs;
2439
+ codeAttrs = codeAttrs ?? defaults.codeAttrs;
2440
+ }
2441
+ record.props = {
2442
+ ...record.props ?? {},
2443
+ lang,
2444
+ preAttrs,
2445
+ codeAttrs
2446
+ };
2447
+ }
2448
+ function normalizeNodeProps(snapshot) {
2449
+ if (snapshot.type === "code-line") {
2450
+ const index = typeof snapshot.props?.index === "number" ? snapshot.props?.index : 0;
2451
+ const text = typeof snapshot.props?.text === "string" ? snapshot.props?.text : "";
2452
+ const html = typeof snapshot.props?.html === "string" ? snapshot.props?.html : null;
2453
+ const tokens = Object.prototype.hasOwnProperty.call(snapshot.props ?? {}, "tokens") ? snapshot.props?.tokens : void 0;
2454
+ return createCodeLineProps(index, text, html, tokens);
2455
+ }
2456
+ if (isInlineSegmentType(snapshot.type)) {
2457
+ const incoming = snapshot.props ? { ...snapshot.props } : {};
2458
+ return mergeInlineSegmentProps(void 0, incoming);
2459
+ }
2460
+ return snapshot.props ? { ...snapshot.props } : {};
2461
+ }
2462
+ function validateCodeBlockChildren(nodes, parent) {
2463
+ const issues = [];
2464
+ const expectedPrefix = `${parent.id}::line:`;
2465
+ const allowed = /* @__PURE__ */ new Set();
2466
+ for (let idx = 0; idx < parent.children.length; idx++) {
2467
+ const childId = parent.children[idx];
2468
+ allowed.add(childId);
2469
+ const node = nodes.get(childId);
2470
+ if (!node) {
2471
+ issues.push({ kind: "missing-node", id: childId, expected: `${expectedPrefix}${idx}` });
2472
+ continue;
2473
+ }
2474
+ if (node.parentId !== parent.id) {
2475
+ issues.push({ kind: "parent-mismatch", id: childId, expected: parent.id, actual: node.parentId });
2476
+ }
2477
+ if (node.type !== "code-line") {
2478
+ issues.push({ kind: "unexpected-type", id: childId, expected: "code-line", actual: node.type });
2479
+ }
2480
+ const expectedId = `${expectedPrefix}${idx}`;
2481
+ if (childId !== expectedId) {
2482
+ issues.push({ kind: "id-mismatch", id: childId, expected: expectedId, actual: childId });
2483
+ }
2484
+ const indexProp = typeof node.props?.index === "number" ? node.props.index : null;
2485
+ if (indexProp !== idx) {
2486
+ issues.push({ kind: "index-mismatch", id: childId, expected: idx, actual: indexProp });
2487
+ }
2488
+ }
2489
+ for (const [id, record] of nodes) {
2490
+ if (record.parentId === parent.id && record.type === "code-line" && !allowed.has(id)) {
2491
+ issues.push({ kind: "dangling-node", id });
2492
+ }
2493
+ }
2494
+ return { ok: issues.length === 0, issues };
2495
+ }
2496
+ function rebuildCodeBlockFromSnapshot(nodes, parent, touched, issues) {
2497
+ if (!parent.block) {
2498
+ return false;
2499
+ }
2500
+ const ancestor = parent.parentId ? nodes.get(parent.parentId) : void 0;
2501
+ if (!ancestor) {
2502
+ return false;
2503
+ }
2504
+ const index = ancestor.children.indexOf(parent.id);
2505
+ if (index === -1) {
2506
+ return false;
2507
+ }
2508
+ const snapshot = createBlockSnapshot(cloneBlock(parent.block));
2509
+ removeSubtree(nodes, parent.id, touched);
2510
+ const inserted = insertSnapshotAt(nodes, ancestor, index, snapshot);
2511
+ if (!inserted) {
2512
+ return false;
2513
+ }
2514
+ for (const id of inserted.insertedIds) {
2515
+ touched.add(id);
2516
+ }
2517
+ ancestor.version++;
2518
+ touched.add(ancestor.id);
2519
+ console.warn("[renderer-store] rebuilt code block from snapshot", {
2520
+ parentId: parent.id,
2521
+ issues
2522
+ });
2523
+ return true;
2524
+ }
2525
+ function arraysEqual(a, b) {
2526
+ if (a === b) return true;
2527
+ if (a.length !== b.length) return false;
2528
+ for (let i = 0; i < a.length; i++) {
2529
+ if (a[i] !== b[i]) return false;
2530
+ }
2531
+ return true;
2532
+ }
2533
+ function buildNodeFromSnapshot(map, snapshot, parentId) {
2534
+ const record = {
2535
+ id: snapshot.id,
2536
+ type: snapshot.type,
2537
+ parentId,
2538
+ children: [],
2539
+ props: normalizeNodeProps(snapshot),
2540
+ meta: snapshot.meta ? { ...snapshot.meta } : void 0,
2541
+ range: snapshot.range ? { ...snapshot.range } : void 0,
2542
+ version: 0,
2543
+ block: snapshotToBlock(snapshot) ?? void 0
2544
+ };
2545
+ if (record.type === "code") {
2546
+ applyCodeBlockMetadata(record);
2547
+ }
2548
+ map.set(record.id, record);
2549
+ const childSnapshots = ensureArray(snapshot.children);
2550
+ for (const child of childSnapshots) {
2551
+ const childRecord = buildNodeFromSnapshot(map, child, record.id);
2552
+ record.children.push(childRecord.id);
2553
+ }
2554
+ return record;
2555
+ }
2556
+ function removeSubtree(map, id, touched) {
2557
+ const record = map.get(id);
2558
+ if (!record) return;
2559
+ const stack = [record];
2560
+ const affectedParents = /* @__PURE__ */ new Set();
2561
+ while (stack.length > 0) {
2562
+ const node = stack.pop();
2563
+ if (!node) {
2564
+ continue;
2565
+ }
2566
+ if (node.parentId) {
2567
+ const parent = map.get(node.parentId);
2568
+ if (parent) {
2569
+ const idx = parent.children.indexOf(node.id);
2570
+ if (idx !== -1) {
2571
+ parent.children.splice(idx, 1);
2572
+ parent.version++;
2573
+ touched.add(parent.id);
2574
+ affectedParents.add(parent.id);
2575
+ }
2576
+ }
2577
+ }
2578
+ map.delete(node.id);
2579
+ nodeSnapshotCache.delete(node.id);
2580
+ childrenSnapshotCache.delete(node.id);
2581
+ touched.add(node.id);
2582
+ for (const childId of node.children) {
2583
+ const child = map.get(childId);
2584
+ if (child) stack.push(child);
2585
+ }
2586
+ }
2587
+ for (const parentId of affectedParents) {
2588
+ const parent = map.get(parentId);
2589
+ if (parent && parent.type === "code") {
2590
+ normalizeCodeBlockChildren(map, parent, touched);
2591
+ }
2592
+ }
2593
+ }
2594
+ function convertNodeToBlocks(map, root) {
2595
+ const result = [];
2596
+ for (const childId of root.children) {
2597
+ const child = map.get(childId);
2598
+ if (!child || !child.block) continue;
2599
+ result.push(cloneBlock(child.block));
2600
+ }
2601
+ return result;
2602
+ }
2603
+ function resolveParent(map, path) {
2604
+ if (path.nodeId) {
2605
+ return map.get(path.nodeId);
2606
+ }
2607
+ if (path.blockId === PATCH_ROOT_ID) {
2608
+ return map.get(PATCH_ROOT_ID);
2609
+ }
2610
+ return map.get(path.blockId);
2611
+ }
2612
+ function insertSnapshotAt(map, parent, index, snapshot, touched) {
2613
+ if (!parent) return null;
2614
+ const existingIndex = parent.children.indexOf(snapshot.id);
2615
+ if (existingIndex !== -1) {
2616
+ removeSubtree(map, parent.children[existingIndex], touched ?? /* @__PURE__ */ new Set());
2617
+ }
2618
+ const record = buildNodeFromSnapshot(map, snapshot, parent.id);
2619
+ const insertedIds = [];
2620
+ const queue = [record];
2621
+ while (queue.length > 0) {
2622
+ const node = queue.pop();
2623
+ if (!node) continue;
2624
+ insertedIds.push(node.id);
2625
+ for (const childId of node.children) {
2626
+ const child = map.get(childId);
2627
+ if (child) queue.push(child);
2628
+ }
2629
+ }
2630
+ const clampedIndex = Math.min(Math.max(index, 0), parent.children.length);
2631
+ parent.children.splice(clampedIndex, 0, record.id);
2632
+ parent.version++;
2633
+ ensureUniqueChildren(parent, touched);
2634
+ return { record, insertedIds };
2635
+ }
2636
+ function replaceSnapshotAt(map, parent, index, snapshot, touched) {
2637
+ if (!parent) return;
2638
+ if (index < 0 || index >= parent.children.length) return;
2639
+ const targetId = parent.children[index];
2640
+ parent.children.splice(index, 1);
2641
+ removeSubtree(map, targetId, touched);
2642
+ const inserted = insertSnapshotAt(map, parent, index, snapshot, touched);
2643
+ if (inserted) {
2644
+ for (const id of inserted.insertedIds) {
2645
+ touched.add(id);
2646
+ }
2647
+ }
2648
+ if (parent.type === "code") {
2649
+ normalizeCodeBlockChildren(map, parent, touched);
2650
+ } else {
2651
+ ensureUniqueChildren(parent, touched);
2652
+ }
2653
+ }
2654
+ function createRendererStore(initialBlocks = []) {
2655
+ let nodes = /* @__PURE__ */ new Map();
2656
+ let version = 0;
2657
+ let blocksCache = [];
2658
+ let blocksDirty = true;
2659
+ const listeners = /* @__PURE__ */ new Set();
2660
+ let notifyScheduled = false;
2661
+ let lastCoalescingMetrics = null;
2662
+ const getRaf = () => {
2663
+ if (typeof globalThis !== "undefined" && typeof globalThis.requestAnimationFrame === "function") {
2664
+ return globalThis.requestAnimationFrame;
2665
+ }
2666
+ return null;
2667
+ };
2668
+ function scheduleNotify() {
2669
+ if (notifyScheduled) return;
2670
+ notifyScheduled = true;
2671
+ const raf = getRaf();
2672
+ if (raf) {
2673
+ raf(() => {
2674
+ notifyScheduled = false;
2675
+ notify();
2676
+ });
2677
+ } else {
2678
+ setTimeout(() => {
2679
+ notifyScheduled = false;
2680
+ notify();
2681
+ }, 0);
2682
+ }
2683
+ }
2684
+ function notify() {
2685
+ for (const listener of listeners) {
2686
+ try {
2687
+ listener();
2688
+ } catch (error) {
2689
+ console.error("RendererStore listener failed", error);
2690
+ }
2691
+ }
2692
+ }
2693
+ function rebuildFromBlocks(blocks) {
2694
+ nodeSnapshotCache.clear();
2695
+ childrenSnapshotCache.clear();
2696
+ nodes = /* @__PURE__ */ new Map();
2697
+ const root = createRootRecord();
2698
+ nodes.set(root.id, root);
2699
+ root.children = [];
2700
+ lastCoalescingMetrics = null;
2701
+ for (let i = 0; i < blocks.length; i++) {
2702
+ const block = cloneBlock(blocks[i]);
2703
+ const snapshot = createBlockSnapshot(block);
2704
+ insertSnapshotAt(nodes, root, root.children.length, snapshot);
2705
+ }
2706
+ normalizeAllListDepths(nodes, /* @__PURE__ */ new Set(), PATCH_ROOT_ID);
2707
+ version++;
2708
+ blocksDirty = true;
2709
+ scheduleNotify();
2710
+ }
2711
+ rebuildFromBlocks(initialBlocks);
2712
+ const store = {
2713
+ reset(nextBlocks) {
2714
+ rebuildFromBlocks(nextBlocks);
2715
+ },
2716
+ applyPatches(patches, options) {
2717
+ const touched = /* @__PURE__ */ new Set();
2718
+ if (!patches || patches.length === 0) {
2719
+ lastCoalescingMetrics = options?.metrics ?? null;
2720
+ return touched;
2721
+ }
2722
+ const perfEnabled = isPatchPerfDebugEnabled();
2723
+ const perfStart = perfEnabled ? getPerfNow() : 0;
2724
+ const opStats = perfEnabled ? {} : {};
2725
+ const setPropsByType = perfEnabled ? {} : {};
2726
+ const setPropsBySize = perfEnabled ? {} : {};
2727
+ let applyMs = 0;
2728
+ let listNormalizeMs = 0;
2729
+ let coalescedPatches = patches;
2730
+ let metrics = options?.metrics ?? null;
2731
+ if (!options?.coalesced) {
2732
+ const result = coalescePatchesWithMetrics(patches, DEFAULT_COALESCE_CONFIG);
2733
+ coalescedPatches = result.patches;
2734
+ metrics = result.metrics;
2735
+ }
2736
+ lastCoalescingMetrics = metrics;
2737
+ const root = nodes.get(PATCH_ROOT_ID);
2738
+ if (!root) {
2739
+ nodes.set(PATCH_ROOT_ID, createRootRecord());
2740
+ }
2741
+ let mutatedBlocks = false;
2742
+ let listDepthDirty = false;
2743
+ const listDepthDirtyNodes = /* @__PURE__ */ new Set();
2744
+ const debugListPatches = isListPatchDebugEnabled();
2745
+ const isListRelated = (type) => type === "list" || type === "list-item";
2746
+ const logListPatch = (label, details) => {
2747
+ if (!debugListPatches) return;
2748
+ try {
2749
+ console.debug(`[list-patch] ${label}`, details);
2750
+ } catch {
2751
+ }
2752
+ };
2753
+ const findNearestListNode = (nodeId) => {
2754
+ if (!nodeId) return void 0;
2755
+ let current = nodes.get(nodeId);
2756
+ while (current) {
2757
+ if (current.type === "list") return current;
2758
+ if (!current.parentId) return void 0;
2759
+ current = nodes.get(current.parentId);
2760
+ }
2761
+ return void 0;
2762
+ };
2763
+ const markListDepthDirty = (nodeId) => {
2764
+ const listNode = findNearestListNode(nodeId);
2765
+ if (listNode) {
2766
+ listDepthDirtyNodes.add(listNode.id);
2767
+ } else {
2768
+ listDepthDirty = true;
2769
+ }
2770
+ };
2771
+ const applyPropsUpdate = (at, props) => {
2772
+ const perfStartLocal = perfEnabled ? getPerfNow() : 0;
2773
+ const targetId = at.nodeId ?? at.blockId;
2774
+ if (!targetId) return;
2775
+ const target = nodes.get(targetId);
2776
+ if (!target) return;
2777
+ const parentType = target.parentId ? nodes.get(target.parentId)?.type : void 0;
2778
+ if (debugListPatches && (isListRelated(target.type) || isListRelated(parentType))) {
2779
+ logListPatch("setProps", {
2780
+ id: target.id,
2781
+ type: target.type,
2782
+ parentType,
2783
+ keys: props ? Object.keys(props) : []
2784
+ });
2785
+ }
2786
+ let propsChanged = false;
2787
+ if (target.type === "code-line") {
2788
+ const incoming = {
2789
+ index: props?.index,
2790
+ text: props?.text,
2791
+ html: props?.html
2792
+ };
2793
+ if (Object.prototype.hasOwnProperty.call(props ?? {}, "tokens")) {
2794
+ incoming.tokens = props.tokens;
2795
+ }
2796
+ const normalized = normalizeCodeLineProps(incoming, target.props);
2797
+ if (normalized !== target.props) {
2798
+ target.props = normalized;
2799
+ propsChanged = true;
2800
+ }
2801
+ if (propsChanged) {
2802
+ target.version++;
2803
+ touched.add(target.id);
2804
+ const parent = target.parentId ? nodes.get(target.parentId) : void 0;
2805
+ if (parent) {
2806
+ parent.version++;
2807
+ touched.add(parent.id);
2808
+ if (parent.type === "code") {
2809
+ normalizeCodeBlockChildren(nodes, parent, touched);
2810
+ }
2811
+ }
2812
+ }
2813
+ if (perfEnabled) {
2814
+ const duration = getPerfNow() - perfStartLocal;
2815
+ const typeKey = target.type || "unknown";
2816
+ const sizeKey = bucketBySize(estimatePropsSize(props, void 0));
2817
+ const typeEntry = setPropsByType[typeKey] ?? { count: 0, durationMs: 0 };
2818
+ typeEntry.count += 1;
2819
+ typeEntry.durationMs += duration;
2820
+ setPropsByType[typeKey] = typeEntry;
2821
+ const sizeEntry = setPropsBySize[sizeKey] ?? { count: 0, durationMs: 0 };
2822
+ sizeEntry.count += 1;
2823
+ sizeEntry.durationMs += duration;
2824
+ setPropsBySize[sizeKey] = sizeEntry;
2825
+ }
2826
+ return;
2827
+ } else if (isInlineSegmentType(target.type)) {
2828
+ const nextProps = props ? { ...props } : {};
2829
+ if ("block" in nextProps) {
2830
+ delete nextProps.block;
2831
+ }
2832
+ const mergedSegments = mergeInlineSegmentProps(target.props, nextProps);
2833
+ if (!shallowEqualRecords(target.props, mergedSegments)) {
2834
+ target.props = mergedSegments;
2835
+ propsChanged = true;
2836
+ }
2837
+ } else {
2838
+ const nextProps = props ? { ...props } : {};
2839
+ if ("block" in nextProps) {
2840
+ delete nextProps.block;
2841
+ }
2842
+ const base = target.props ? { ...target.props } : {};
2843
+ let localChanged = false;
2844
+ if (Object.prototype.hasOwnProperty.call(base, "block")) {
2845
+ delete base.block;
2846
+ localChanged = true;
2847
+ }
2848
+ for (const [key, value] of Object.entries(nextProps)) {
2849
+ if (value === void 0) {
2850
+ if (Object.prototype.hasOwnProperty.call(base, key)) {
2851
+ delete base[key];
2852
+ localChanged = true;
2853
+ }
2854
+ } else if (base[key] !== value) {
2855
+ base[key] = value;
2856
+ localChanged = true;
2857
+ }
2858
+ }
2859
+ if (localChanged) {
2860
+ target.props = base;
2861
+ propsChanged = true;
2862
+ }
2863
+ }
2864
+ let blockChanged = false;
2865
+ const incomingBlock = props?.block;
2866
+ if (incomingBlock && typeof incomingBlock === "object") {
2867
+ target.block = cloneBlock(incomingBlock);
2868
+ if (target.type === "code") {
2869
+ applyCodeBlockMetadata(target);
2870
+ }
2871
+ mutatedBlocks = true;
2872
+ blockChanged = true;
2873
+ }
2874
+ if (propsChanged || blockChanged) {
2875
+ target.version++;
2876
+ touched.add(target.id);
2877
+ let parentForNormalization;
2878
+ if (target.parentId) {
2879
+ const parent = nodes.get(target.parentId);
2880
+ if (parent) {
2881
+ if (target.type === "code-line") {
2882
+ parent.version++;
2883
+ touched.add(parent.id);
2884
+ }
2885
+ if (parent.type === "code") {
2886
+ parentForNormalization = parent;
2887
+ }
2888
+ }
2889
+ }
2890
+ if (target.type === "code") {
2891
+ normalizeCodeBlockChildren(nodes, target, touched);
2892
+ } else if (parentForNormalization) {
2893
+ normalizeCodeBlockChildren(nodes, parentForNormalization, touched);
2894
+ }
2895
+ const parentType2 = target.parentId ? nodes.get(target.parentId)?.type : void 0;
2896
+ if (isListRelated(target.type) || isListRelated(parentType2)) {
2897
+ markListDepthDirty(target.id);
2898
+ }
2899
+ }
2900
+ if (perfEnabled) {
2901
+ const duration = getPerfNow() - perfStartLocal;
2902
+ const typeKey = target.type || "unknown";
2903
+ const sizeKey = bucketBySize(estimatePropsSize(props, incomingBlock && typeof incomingBlock === "object" ? incomingBlock : void 0));
2904
+ const typeEntry = setPropsByType[typeKey] ?? { count: 0, durationMs: 0 };
2905
+ typeEntry.count += 1;
2906
+ typeEntry.durationMs += duration;
2907
+ setPropsByType[typeKey] = typeEntry;
2908
+ const sizeEntry = setPropsBySize[sizeKey] ?? { count: 0, durationMs: 0 };
2909
+ sizeEntry.count += 1;
2910
+ sizeEntry.durationMs += duration;
2911
+ setPropsBySize[sizeKey] = sizeEntry;
2912
+ }
2913
+ };
2914
+ const applyPatch = (patch) => {
2915
+ switch (patch.op) {
2916
+ case "insertChild": {
2917
+ const parent = resolveParent(nodes, patch.at);
2918
+ const inserted = insertSnapshotAt(nodes, parent, patch.index, patch.node, touched);
2919
+ if (inserted) {
2920
+ for (const id of inserted.insertedIds) {
2921
+ touched.add(id);
2922
+ }
2923
+ mutatedBlocks = true;
2924
+ if (isListRelated(inserted.record.type) || isListRelated(parent?.type)) {
2925
+ markListDepthDirty(inserted.record.id);
2926
+ if (parent) {
2927
+ markListDepthDirty(parent.id);
2928
+ }
2929
+ }
2930
+ if (debugListPatches && (isListRelated(inserted.record.type) || isListRelated(parent?.type))) {
2931
+ logListPatch("insertChild", {
2932
+ id: inserted.record.id,
2933
+ type: inserted.record.type,
2934
+ parentId: parent?.id,
2935
+ parentType: parent?.type,
2936
+ index: patch.index
2937
+ });
2938
+ }
2939
+ }
2940
+ break;
2941
+ }
2942
+ case "deleteChild": {
2943
+ const parent = resolveParent(nodes, patch.at);
2944
+ if (!parent) break;
2945
+ if (patch.index < 0 || patch.index >= parent.children.length) break;
2946
+ const childId = parent.children.splice(patch.index, 1)[0];
2947
+ if (childId) {
2948
+ const removedNode = nodes.get(childId);
2949
+ removeSubtree(nodes, childId, touched);
2950
+ parent.version++;
2951
+ touched.add(parent.id);
2952
+ ensureUniqueChildren(parent, touched);
2953
+ mutatedBlocks = true;
2954
+ if (isListRelated(parent.type) || isListRelated(removedNode?.type)) {
2955
+ markListDepthDirty(parent.id);
2956
+ }
2957
+ if (debugListPatches && (isListRelated(parent.type) || isListRelated(removedNode?.type))) {
2958
+ logListPatch("deleteChild", {
2959
+ id: childId,
2960
+ type: removedNode?.type,
2961
+ parentId: parent.id,
2962
+ parentType: parent.type,
2963
+ index: patch.index
2964
+ });
2965
+ }
2966
+ }
2967
+ break;
2968
+ }
2969
+ case "replaceChild": {
2970
+ const parent = resolveParent(nodes, patch.at);
2971
+ if (!parent) break;
2972
+ replaceSnapshotAt(nodes, parent, patch.index, patch.node, touched);
2973
+ touched.add(parent.id);
2974
+ mutatedBlocks = true;
2975
+ if (isListRelated(parent.type)) {
2976
+ markListDepthDirty(parent.id);
2977
+ }
2978
+ if (debugListPatches && isListRelated(parent.type)) {
2979
+ logListPatch("replaceChild", {
2980
+ parentId: parent.id,
2981
+ parentType: parent.type,
2982
+ index: patch.index
2983
+ });
2984
+ }
2985
+ break;
2986
+ }
2987
+ case "setProps": {
2988
+ applyPropsUpdate(patch.at, patch.props);
2989
+ break;
2990
+ }
2991
+ case "setPropsBatch": {
2992
+ const entries2 = Array.isArray(patch.entries) ? patch.entries : [];
2993
+ for (const entry of entries2) {
2994
+ if (!entry || !entry.at) continue;
2995
+ applyPropsUpdate(entry.at, entry.props);
2996
+ }
2997
+ break;
2998
+ }
2999
+ case "finalize": {
3000
+ const target = nodes.get(patch.at.nodeId ?? patch.at.blockId);
3001
+ if (!target || !target.block) break;
3002
+ if (!target.block.isFinalized) {
3003
+ target.block = cloneBlock(target.block);
3004
+ target.block.isFinalized = true;
3005
+ target.version++;
3006
+ touched.add(target.id);
3007
+ mutatedBlocks = true;
3008
+ }
3009
+ if (isListRelated(target.type)) {
3010
+ markListDepthDirty(target.id);
3011
+ }
3012
+ if (debugListPatches && isListRelated(target.type)) {
3013
+ logListPatch("finalize", {
3014
+ id: target.id,
3015
+ type: target.type
3016
+ });
3017
+ }
3018
+ break;
3019
+ }
3020
+ case "reorder": {
3021
+ const parent = resolveParent(nodes, patch.at);
3022
+ if (!parent) break;
3023
+ const length = parent.children.length;
3024
+ if (length === 0 || patch.count <= 0) break;
3025
+ const from = clampIndex(patch.from, length - 1);
3026
+ const count = Math.max(1, Math.min(patch.count, length - from));
3027
+ let to = clampIndex(patch.to, length);
3028
+ if (to > from) {
3029
+ to = Math.max(0, to - count);
3030
+ }
3031
+ const moved = parent.children.splice(from, count);
3032
+ parent.children.splice(to, 0, ...moved);
3033
+ parent.version++;
3034
+ touched.add(parent.id);
3035
+ if (isListRelated(parent.type)) {
3036
+ markListDepthDirty(parent.id);
3037
+ }
3038
+ if (debugListPatches && isListRelated(parent.type)) {
3039
+ logListPatch("reorder", {
3040
+ parentId: parent.id,
3041
+ parentType: parent.type,
3042
+ from: patch.from,
3043
+ to: patch.to,
3044
+ count: patch.count
3045
+ });
3046
+ }
3047
+ break;
3048
+ }
3049
+ case "appendLines": {
3050
+ const parent = resolveParent(nodes, patch.at);
3051
+ if (!parent) break;
3052
+ const startIndex = Math.max(0, Math.min(patch.startIndex, parent.children.length));
3053
+ const lineCount = patch.lines?.length ?? 0;
3054
+ if (lineCount === 0) break;
3055
+ const originalChildren = parent.children.slice();
3056
+ const insertedIds = [];
3057
+ const insertedSet = /* @__PURE__ */ new Set();
3058
+ const isTrailingAppend = startIndex >= originalChildren.length;
3059
+ let parentChildrenChanged = false;
3060
+ let codeLinesMutated = false;
3061
+ for (let offset = 0; offset < lineCount; offset++) {
3062
+ const absoluteIndex = startIndex + offset;
3063
+ const lineId = `${parent.id}::line:${absoluteIndex}`;
3064
+ insertedIds.push(lineId);
3065
+ insertedSet.add(lineId);
3066
+ const hasTokens = Object.prototype.hasOwnProperty.call(patch, "tokens");
3067
+ const nextTokens = hasTokens ? patch.tokens?.[offset] ?? null : void 0;
3068
+ const nextLineProps = createCodeLineProps(
3069
+ absoluteIndex,
3070
+ patch.lines[offset] ?? "",
3071
+ patch.highlight?.[offset] ?? null,
3072
+ nextTokens
3073
+ );
3074
+ const existing = nodes.get(lineId);
3075
+ if (existing && existing.type === "code-line") {
3076
+ const existingIndex = parent.children.indexOf(lineId);
3077
+ if (existingIndex !== -1) {
3078
+ parent.children.splice(existingIndex, 1);
3079
+ parentChildrenChanged = true;
3080
+ }
3081
+ if (existing.parentId !== parent.id) {
3082
+ existing.parentId = parent.id;
3083
+ existing.version++;
3084
+ touched.add(lineId);
3085
+ codeLinesMutated = true;
3086
+ }
3087
+ if (!shallowEqualRecords(existing.props, nextLineProps)) {
3088
+ existing.props = nextLineProps;
3089
+ existing.version++;
3090
+ touched.add(lineId);
3091
+ codeLinesMutated = true;
3092
+ }
3093
+ } else {
3094
+ const record = {
3095
+ id: lineId,
3096
+ type: "code-line",
3097
+ parentId: parent.id,
3098
+ children: [],
3099
+ props: nextLineProps,
3100
+ version: 0
3101
+ };
3102
+ nodes.set(lineId, record);
3103
+ touched.add(lineId);
3104
+ codeLinesMutated = true;
3105
+ }
3106
+ }
3107
+ if (insertedIds.length > 0) {
3108
+ let nextChildren;
3109
+ if (isTrailingAppend) {
3110
+ nextChildren = [...originalChildren, ...insertedIds];
3111
+ } else {
3112
+ const cleanedChildren = originalChildren.filter((childId) => !insertedSet.has(childId));
3113
+ const clampedStart = Math.max(0, Math.min(startIndex, cleanedChildren.length));
3114
+ nextChildren = [...cleanedChildren.slice(0, clampedStart), ...insertedIds, ...cleanedChildren.slice(clampedStart)];
3115
+ }
3116
+ if (!arraysEqual(originalChildren, nextChildren)) {
3117
+ parent.children = nextChildren;
3118
+ parentChildrenChanged = true;
3119
+ }
3120
+ }
3121
+ if (!isTrailingAppend) {
3122
+ for (let idx = 0; idx < parent.children.length; idx++) {
3123
+ const childId = parent.children[idx];
3124
+ const child = nodes.get(childId);
3125
+ if (child && child.type === "code-line") {
3126
+ const incoming = { index: idx, text: child.props?.text, html: child.props?.html };
3127
+ if (Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens")) {
3128
+ incoming.tokens = child.props.tokens;
3129
+ }
3130
+ const normalized = normalizeCodeLineProps(incoming, child.props);
3131
+ if (normalized !== child.props) {
3132
+ child.props = normalized;
3133
+ child.version++;
3134
+ touched.add(child.id);
3135
+ codeLinesMutated = true;
3136
+ }
3137
+ }
3138
+ }
3139
+ }
3140
+ if (parentChildrenChanged || codeLinesMutated) {
3141
+ parent.version++;
3142
+ touched.add(parent.id);
3143
+ if (!isTrailingAppend) {
3144
+ normalizeCodeBlockChildren(nodes, parent, touched);
3145
+ }
3146
+ }
3147
+ break;
3148
+ }
3149
+ case "setHTML": {
3150
+ const target = nodes.get(patch.at.nodeId ?? patch.at.blockId);
3151
+ if (!target) break;
3152
+ const sanitized = patch.sanitized ? patch.html : sanitizeHTML2(patch.html);
3153
+ target.props = {
3154
+ ...target.props ?? {},
3155
+ html: sanitized,
3156
+ policy: patch.policy || "markdown-renderer-v2",
3157
+ meta: patch.meta ? { ...patch.meta } : target.props?.meta
3158
+ };
3159
+ if (patch.block) {
3160
+ target.block = cloneBlock(patch.block);
3161
+ if (!target.block.payload.meta) {
3162
+ target.block.payload.meta = {};
3163
+ }
3164
+ target.block.payload.sanitizedHtml = sanitized;
3165
+ mutatedBlocks = true;
3166
+ }
3167
+ target.version++;
3168
+ touched.add(target.id);
3169
+ break;
3170
+ }
3171
+ default:
3172
+ break;
3173
+ }
3174
+ };
3175
+ if (perfEnabled) {
3176
+ const loopStart = getPerfNow();
3177
+ for (const patch of coalescedPatches) {
3178
+ const opStart = getPerfNow();
3179
+ applyPatch(patch);
3180
+ const opDuration = getPerfNow() - opStart;
3181
+ const entry = opStats[patch.op] ?? { count: 0, durationMs: 0 };
3182
+ entry.count += 1;
3183
+ entry.durationMs += opDuration;
3184
+ opStats[patch.op] = entry;
3185
+ }
3186
+ applyMs = getPerfNow() - loopStart;
3187
+ } else {
3188
+ for (const patch of coalescedPatches) {
3189
+ applyPatch(patch);
3190
+ }
3191
+ }
3192
+ if (mutatedBlocks) {
3193
+ blocksDirty = true;
3194
+ }
3195
+ if (listDepthDirty) {
3196
+ if (perfEnabled) {
3197
+ const start = getPerfNow();
3198
+ normalizeAllListDepths(nodes, touched, PATCH_ROOT_ID);
3199
+ listNormalizeMs = getPerfNow() - start;
3200
+ } else {
3201
+ normalizeAllListDepths(nodes, touched, PATCH_ROOT_ID);
3202
+ }
3203
+ } else if (listDepthDirtyNodes.size > 0) {
3204
+ if (perfEnabled) {
3205
+ const start = getPerfNow();
3206
+ normalizeListDepthsForIds(nodes, touched, listDepthDirtyNodes, PATCH_ROOT_ID);
3207
+ listNormalizeMs = getPerfNow() - start;
3208
+ } else {
3209
+ normalizeListDepthsForIds(nodes, touched, listDepthDirtyNodes, PATCH_ROOT_ID);
3210
+ }
3211
+ }
3212
+ if (touched.size > 0 || mutatedBlocks) {
3213
+ version++;
3214
+ scheduleNotify();
3215
+ }
3216
+ if (perfEnabled) {
3217
+ const totalMs = getPerfNow() - perfStart;
3218
+ const coalesceMs = typeof metrics?.durationMs === "number" ? metrics.durationMs : 0;
3219
+ recordPatchPerf({
3220
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3221
+ totalMs,
3222
+ applyMs,
3223
+ coalesceMs,
3224
+ listNormalizeMs,
3225
+ patches: patches.length,
3226
+ coalescedPatches: coalescedPatches.length,
3227
+ touchedCount: touched.size,
3228
+ mutatedBlocks,
3229
+ ops: opStats,
3230
+ setPropsByType,
3231
+ setPropsBySize
3232
+ });
3233
+ }
3234
+ return touched;
3235
+ },
3236
+ getBlocks() {
3237
+ if (!blocksDirty) {
3238
+ return blocksCache;
3239
+ }
3240
+ const root = nodes.get(PATCH_ROOT_ID);
3241
+ if (!root) {
3242
+ blocksCache = [];
3243
+ } else {
3244
+ blocksCache = convertNodeToBlocks(nodes, root);
3245
+ }
3246
+ blocksDirty = false;
3247
+ return blocksCache;
3248
+ },
3249
+ getVersion() {
3250
+ return version;
3251
+ },
3252
+ getNode(id) {
3253
+ return nodes.get(id);
3254
+ },
3255
+ getNodeWithVersion(id) {
3256
+ const record = nodes.get(id);
3257
+ if (!record) {
3258
+ return EMPTY_NODE_SNAPSHOT;
3259
+ }
3260
+ const cached = nodeSnapshotCache.get(id);
3261
+ if (cached && cached.version === record.version && cached.node === record) {
3262
+ return cached;
3263
+ }
3264
+ const snapshot = { version: record.version, node: record };
3265
+ nodeSnapshotCache.set(id, snapshot);
3266
+ pruneCache(nodeSnapshotCache, NODE_SNAPSHOT_CACHE_LIMIT, NODE_SNAPSHOT_CACHE_BUFFER);
3267
+ return snapshot;
3268
+ },
3269
+ getChildren(id) {
3270
+ const record = nodes.get(id);
3271
+ if (!record) return EMPTY_CHILDREN;
3272
+ return record.children;
3273
+ },
3274
+ getChildrenWithVersion(id) {
3275
+ const record = nodes.get(id);
3276
+ if (!record) {
3277
+ return EMPTY_CHILDREN_SNAPSHOT;
3278
+ }
3279
+ const cached = childrenSnapshotCache.get(id);
3280
+ if (cached && cached.version === record.version) {
3281
+ return cached;
3282
+ }
3283
+ const snapshot = { version: record.version, children: record.children.slice() };
3284
+ childrenSnapshotCache.set(id, snapshot);
3285
+ pruneCache(childrenSnapshotCache, CHILDREN_SNAPSHOT_CACHE_LIMIT, CHILDREN_SNAPSHOT_CACHE_BUFFER);
3286
+ return snapshot;
3287
+ },
3288
+ getLastCoalescingMetrics() {
3289
+ return lastCoalescingMetrics;
3290
+ },
3291
+ subscribe(listener) {
3292
+ listeners.add(listener);
3293
+ return () => {
3294
+ listeners.delete(listener);
3295
+ };
3296
+ }
3297
+ };
3298
+ return store;
3299
+ }
3300
+
3301
+ // src/renderer/virtualized-code.tsx
3302
+ import { useCallback, useEffect as useEffect2, useMemo as useMemo2, useRef, useState as useState2 } from "react";
3303
+ var DEFAULT_VIRTUALIZED_CODE_CONFIG = {
3304
+ enabled: true,
3305
+ windowSize: 100,
3306
+ // Render 100 lines at a time
3307
+ bufferSize: 50,
3308
+ // +50 lines buffer above/below
3309
+ virtualizeThreshold: 200
3310
+ // Only virtualize if 200+ lines
3311
+ };
3312
+ function calculateCodeWindow(lines, scrollTop, containerHeight, lineHeight, config) {
3313
+ const totalLines = lines.length;
3314
+ if (!config.enabled || totalLines < config.virtualizeThreshold) {
3315
+ return {
3316
+ startIndex: 0,
3317
+ endIndex: totalLines,
3318
+ visibleStart: 0,
3319
+ visibleEnd: totalLines,
3320
+ visibleLines: lines,
3321
+ totalLines,
3322
+ mountedLines: totalLines
3323
+ };
3324
+ }
3325
+ const firstVisibleLine = Math.floor(scrollTop / lineHeight);
3326
+ const lastVisibleLine = Math.ceil((scrollTop + containerHeight) / lineHeight);
3327
+ const visibleStart = Math.max(0, firstVisibleLine);
3328
+ const visibleEnd = Math.min(totalLines, Math.max(visibleStart, lastVisibleLine));
3329
+ const startIndex = Math.max(0, visibleStart - config.bufferSize);
3330
+ const endIndex = Math.min(totalLines, visibleEnd + config.bufferSize);
3331
+ return {
3332
+ startIndex,
3333
+ endIndex,
3334
+ visibleStart,
3335
+ visibleEnd,
3336
+ visibleLines: lines.slice(startIndex, endIndex),
3337
+ totalLines,
3338
+ mountedLines: endIndex - startIndex
3339
+ };
3340
+ }
3341
+ function useVirtualizedCode(lines, config = DEFAULT_VIRTUALIZED_CODE_CONFIG) {
3342
+ const containerRef = useRef(null);
3343
+ const [scrollTop, setScrollTop] = useState2(0);
3344
+ const [containerHeight, setContainerHeight] = useState2(0);
3345
+ const lineHeightRef = useRef(20);
3346
+ useEffect2(() => {
3347
+ if (!containerRef.current || lines.length === 0) return;
3348
+ const timeoutId = setTimeout(() => {
3349
+ if (!containerRef.current) return;
3350
+ const firstLine = containerRef.current.querySelector(".line");
3351
+ if (firstLine) {
3352
+ const measuredHeight = firstLine.offsetHeight || 20;
3353
+ if (measuredHeight !== lineHeightRef.current) {
3354
+ lineHeightRef.current = measuredHeight;
3355
+ }
3356
+ }
3357
+ }, 0);
3358
+ return () => clearTimeout(timeoutId);
3359
+ }, [lines.length]);
3360
+ const handleScroll = useCallback((e) => {
3361
+ const target = e.currentTarget;
3362
+ setScrollTop(target.scrollTop);
3363
+ setContainerHeight(target.clientHeight);
3364
+ }, []);
3365
+ useEffect2(() => {
3366
+ if (!containerRef.current) return;
3367
+ const resizeObserver = new ResizeObserver((entries2) => {
3368
+ for (const entry of entries2) {
3369
+ setContainerHeight(entry.contentRect.height);
3370
+ }
3371
+ });
3372
+ resizeObserver.observe(containerRef.current);
3373
+ return () => resizeObserver.disconnect();
3374
+ }, []);
3375
+ const window2 = useMemo2(() => {
3376
+ return calculateCodeWindow(lines, scrollTop, containerHeight, lineHeightRef.current, config);
3377
+ }, [lines, scrollTop, containerHeight, config]);
3378
+ const scrollToLine = useCallback((lineIndex) => {
3379
+ if (!containerRef.current) return;
3380
+ const targetScrollTop = lineIndex * lineHeightRef.current;
3381
+ containerRef.current.scrollTop = targetScrollTop;
3382
+ setScrollTop(targetScrollTop);
3383
+ }, []);
3384
+ return {
3385
+ containerRef,
3386
+ window: window2,
3387
+ handleScroll,
3388
+ scrollToLine,
3389
+ lineHeight: lineHeightRef.current,
3390
+ config
3391
+ };
3392
+ }
3393
+
3394
+ // src/renderer/node-views.tsx
3395
+ import { jsx, jsxs } from "react/jsx-runtime";
3396
+ var BlockNodeRenderer = ({ store, blockId, registry }) => {
3397
+ const node = useRendererNode(store, blockId);
3398
+ const block = node?.block;
3399
+ if (!node || !block) return null;
3400
+ switch (block.type) {
3401
+ case "paragraph":
3402
+ return /* @__PURE__ */ jsx(ParagraphBlockView, { store, blockId: block.id, registry });
3403
+ case "blockquote":
3404
+ return /* @__PURE__ */ jsx(BlockquoteBlockView, { store, blockId: block.id, registry });
3405
+ case "list":
3406
+ return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: block.id, registry, depth: 0 });
3407
+ case "table":
3408
+ return /* @__PURE__ */ jsx(TableBlockView, { store, blockId: block.id, registry });
3409
+ case "code":
3410
+ return /* @__PURE__ */ jsx(CodeBlockView, { store, blockId: block.id, registry });
3411
+ case "html":
3412
+ return /* @__PURE__ */ jsx(HtmlBlockView, { store, blockId: block.id, registry });
3413
+ case "mdx":
3414
+ return /* @__PURE__ */ jsx(MdxBlockView, { store, blockId: block.id, registry });
3415
+ default:
3416
+ return registry.renderBlock(block);
3417
+ }
3418
+ };
3419
+ var ParagraphBlockView = React7.memo(({ store, blockId, registry }) => {
3420
+ const node = useRendererNode(store, blockId);
3421
+ const block = node?.block;
3422
+ const childIds = useRendererChildren(store, blockId);
3423
+ if (!node || !block) {
3424
+ return null;
3425
+ }
3426
+ const inlineComponents = registry.getInlineComponents();
3427
+ if (!block.isFinalized) {
3428
+ const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
3429
+ const meta = block.payload.meta ?? {};
3430
+ const segments2 = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
3431
+ if (segments2.length > 0) {
3432
+ const allowMixedStreaming = Boolean(meta.allowMixedStreaming);
3433
+ if (!allowMixedStreaming) {
3434
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
3435
+ }
3436
+ const structured = renderParagraphMixedSegments(segments2, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
3437
+ if (structured.length === 1) {
3438
+ const [single] = structured;
3439
+ return React7.isValidElement(single) ? single : single;
3440
+ }
3441
+ return structured;
3442
+ }
3443
+ if (meta.inlineStatus === "complete" || meta.inlineStatus === "anticipated") {
3444
+ const inlineNodes2 = block.payload.inline ?? [];
3445
+ const containsDisplayMath2 = inlineNodes2.some((node2) => node2.kind === "math-display");
3446
+ if (containsDisplayMath2) {
3447
+ const derivedSegments = [
3448
+ {
3449
+ kind: "text",
3450
+ value: raw,
3451
+ inline: inlineNodes2
3452
+ }
3453
+ ];
3454
+ const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
3455
+ if (structured.length === 1) {
3456
+ const [single] = structured;
3457
+ return React7.isValidElement(single) ? single : single;
3458
+ }
3459
+ return structured;
3460
+ }
3461
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: renderInlineNodes(inlineNodes2, inlineComponents) });
3462
+ }
3463
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph streaming-partial", children: raw });
3464
+ }
3465
+ const propsBlock = node.props?.block;
3466
+ const inlineStatus = propsBlock?.payload?.meta?.inlineStatus ?? block.payload.meta?.inlineStatus ?? node.props?.inlineStatus;
3467
+ if (inlineStatus && inlineStatus !== "complete") {
3468
+ const raw = typeof block.payload.raw === "string" ? block.payload.raw : "";
3469
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: raw });
3470
+ }
3471
+ const segments = Array.isArray(block.payload.meta?.mixedSegments) ? block.payload.meta.mixedSegments : void 0;
3472
+ if (segments && segments.length > 0) {
3473
+ const structured = renderParagraphMixedSegments(segments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
3474
+ if (structured.length === 1) {
3475
+ const [single] = structured;
3476
+ return React7.isValidElement(single) ? single : single;
3477
+ }
3478
+ return structured;
3479
+ }
3480
+ const inlineNodes = block.payload.inline ?? [];
3481
+ const containsDisplayMath = inlineNodes.some((node2) => node2.kind === "math-display");
3482
+ if (containsDisplayMath) {
3483
+ const derivedSegments = [
3484
+ {
3485
+ kind: "text",
3486
+ value: typeof block.payload.raw === "string" ? block.payload.raw : "",
3487
+ inline: inlineNodes
3488
+ }
3489
+ ];
3490
+ const structured = renderParagraphMixedSegments(derivedSegments, inlineComponents, DEFAULT_INLINE_HTML_RENDERERS);
3491
+ if (structured.length === 1) {
3492
+ const [single] = structured;
3493
+ return React7.isValidElement(single) ? single : single;
3494
+ }
3495
+ return structured;
3496
+ }
3497
+ const ParagraphComponent = registry.getBlockComponent("paragraph");
3498
+ const baseElement = React7.createElement(ParagraphComponent, {
3499
+ inlines: block.payload.inline ?? [],
3500
+ raw: block.payload.raw,
3501
+ meta: block.payload.meta
3502
+ });
3503
+ if (childIds.length > 0) {
3504
+ const renderedChildren = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
3505
+ if (React7.isValidElement(baseElement)) {
3506
+ const { children: _ignored, className = "markdown-paragraph", inlines: _inlines, raw: _raw, meta: _meta, ...rest } = baseElement.props ?? {};
3507
+ return React7.createElement("p", { ...rest, className }, renderedChildren);
3508
+ }
3509
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderedChildren });
3510
+ }
3511
+ if (React7.isValidElement(baseElement)) {
3512
+ return baseElement;
3513
+ }
3514
+ return /* @__PURE__ */ jsx("p", { className: "markdown-paragraph", children: renderInlineNodes(block.payload.inline ?? [], inlineComponents) });
3515
+ });
3516
+ ParagraphBlockView.displayName = "ParagraphBlockView";
3517
+ var BlockquoteBlockView = React7.memo(({ store, blockId, registry }) => {
3518
+ const node = useRendererNode(store, blockId);
3519
+ const block = node?.block;
3520
+ const childIds = useRendererChildren(store, blockId);
3521
+ if (!node || !block) {
3522
+ return null;
3523
+ }
3524
+ const meta = block.payload.meta ?? {};
3525
+ const mixedSegments = Array.isArray(meta.mixedSegments) ? meta.mixedSegments : [];
3526
+ const normalizedText = typeof meta.normalizedText === "string" && meta.normalizedText.length > 0 ? meta.normalizedText : typeof block.payload.raw === "string" ? block.payload.raw : "";
3527
+ const inlineComponents = registry.getInlineComponents();
3528
+ const renderTextWithBreaks = (text, keyPrefix) => {
3529
+ const lines = text.split("\n");
3530
+ const lastIndex = lines.length - 1;
3531
+ let offset = 0;
3532
+ return lines.map((line, idx) => {
3533
+ const key = `${keyPrefix}${offset}`;
3534
+ offset += line.length + 1;
3535
+ return /* @__PURE__ */ jsxs("span", { className: "markdown-blockquote-line", children: [
3536
+ line,
3537
+ idx < lastIndex ? /* @__PURE__ */ jsx("br", {}) : null
3538
+ ] }, key);
3539
+ });
3540
+ };
3541
+ const renderInlineContent = (inline, keyPrefix) => {
3542
+ if (inline && inline.length > 0) {
3543
+ return renderInlineNodes(inline, inlineComponents);
3544
+ }
3545
+ return null;
3546
+ };
3547
+ const renderMixedSegments = () => {
3548
+ if (!mixedSegments.length) {
3549
+ return [];
3550
+ }
3551
+ const elements = [];
3552
+ mixedSegments.forEach((segment, segmentIndex) => {
3553
+ switch (segment.kind) {
3554
+ case "html": {
3555
+ const htmlNode = renderInlineHtmlSegment(segment.value, segment.sanitized ?? segment.value, {
3556
+ key: `blockquote-html-${block.id}-${segmentIndex}`,
3557
+ renderers: DEFAULT_INLINE_HTML_RENDERERS
3558
+ });
3559
+ if (htmlNode) {
3560
+ elements.push(htmlNode);
3561
+ } else {
3562
+ elements.push(
3563
+ React7.createElement("span", {
3564
+ key: `blockquote-html-${block.id}-${segmentIndex}`,
3565
+ className: "markdown-inline-html",
3566
+ /* biome-ignore lint/security/noDangerouslySetInnerHtml: segment content is sanitized by the worker before streaming */
3567
+ dangerouslySetInnerHTML: { __html: segment.sanitized ?? segment.value }
3568
+ })
3569
+ );
3570
+ }
3571
+ break;
3572
+ }
3573
+ case "mdx":
3574
+ elements.push(
3575
+ /* @__PURE__ */ jsx("span", { "data-mdx-status": segment.status ?? "pending", children: segment.value }, `blockquote-mdx-${block.id}-${segmentIndex}`)
3576
+ );
3577
+ break;
3578
+ default: {
3579
+ const inline = renderInlineContent(segment.inline, `blockquote-text-inline-${block.id}-${segmentIndex}-`);
3580
+ if (inline) {
3581
+ elements.push(/* @__PURE__ */ jsx(React7.Fragment, { children: inline }, `blockquote-inline-${block.id}-${segmentIndex}`));
3582
+ } else {
3583
+ elements.push(
3584
+ /* @__PURE__ */ jsx(React7.Fragment, { children: renderTextWithBreaks(segment.value, `blockquote-text-${block.id}-${segmentIndex}-`) }, `blockquote-text-${block.id}-${segmentIndex}`)
3585
+ );
3586
+ }
3587
+ break;
3588
+ }
3589
+ }
3590
+ });
3591
+ return elements;
3592
+ };
3593
+ const mixedSegmentElements = renderMixedSegments();
3594
+ const fallbackElements = normalizedText ? renderTextWithBreaks(normalizedText, `blockquote-fallback-${block.id}-`) : null;
3595
+ const inlineNodes = block.payload.inline ?? [];
3596
+ const inlineElements = inlineNodes.length > 0 ? renderInlineNodes(inlineNodes, inlineComponents) : null;
3597
+ if (!block.isFinalized) {
3598
+ const streamingContent = mixedSegmentElements.length ? mixedSegmentElements : inlineElements ? inlineElements : fallbackElements;
3599
+ const shouldShowStreaming = !block.isFinalized && (!streamingContent || Array.isArray(streamingContent) && streamingContent.length === 0);
3600
+ const className = shouldShowStreaming ? "markdown-blockquote streaming-partial" : "markdown-blockquote";
3601
+ return /* @__PURE__ */ jsx("blockquote", { className, children: streamingContent });
3602
+ }
3603
+ const childContent = childIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
3604
+ const renderedContent = (() => {
3605
+ if (mixedSegmentElements.length > 0) {
3606
+ return mixedSegmentElements;
3607
+ }
3608
+ if (childIds.length > 0) {
3609
+ const resolved = childContent.filter((child) => child !== null);
3610
+ if (resolved.length > 0) {
3611
+ return resolved;
3612
+ }
3613
+ }
3614
+ if (inlineElements) {
3615
+ return inlineElements;
3616
+ }
3617
+ if (fallbackElements && fallbackElements.length > 0) {
3618
+ return fallbackElements;
3619
+ }
3620
+ return null;
3621
+ })();
3622
+ const BlockquoteComponent = registry.getBlockComponent("blockquote");
3623
+ const baseElement = React7.createElement(
3624
+ BlockquoteComponent,
3625
+ {
3626
+ inlines: block.payload.inline ?? [],
3627
+ renderedContent
3628
+ },
3629
+ renderedContent
3630
+ );
3631
+ if (React7.isValidElement(baseElement)) {
3632
+ return baseElement;
3633
+ }
3634
+ return /* @__PURE__ */ jsx("blockquote", { className: "markdown-blockquote", children: renderedContent });
3635
+ });
3636
+ BlockquoteBlockView.displayName = "BlockquoteBlockView";
3637
+ var MixedSegmentView = React7.memo(({ store, nodeId, inlineComponents }) => {
3638
+ const node = useRendererNode(store, nodeId);
3639
+ if (!node) return null;
3640
+ switch (node.type) {
3641
+ case "paragraph-text":
3642
+ case "blockquote-text":
3643
+ case "list-item-text": {
3644
+ const inline = node.props?.inline ?? [];
3645
+ if (inline.length > 0) {
3646
+ return renderInlineNodes(inline, inlineComponents);
3647
+ }
3648
+ const text = typeof node.props?.text === "string" ? node.props?.text : "";
3649
+ if (!text) return null;
3650
+ return text;
3651
+ }
3652
+ case "paragraph-html":
3653
+ case "blockquote-html":
3654
+ case "list-item-html": {
3655
+ const raw = typeof node.props?.raw === "string" ? node.props.raw : void 0;
3656
+ const html = typeof node.props?.html === "string" ? node.props?.html : "";
3657
+ const rendered = renderInlineHtmlSegment(raw, html, {
3658
+ key: node.id,
3659
+ renderers: DEFAULT_INLINE_HTML_RENDERERS
3660
+ });
3661
+ if (rendered) {
3662
+ return rendered;
3663
+ }
3664
+ if (!html) return null;
3665
+ return React7.createElement("span", {
3666
+ className: "markdown-inline-html",
3667
+ /* biome-ignore lint/security/noDangerouslySetInnerHtml: html is sanitized upstream before reaching the renderer */
3668
+ dangerouslySetInnerHTML: { __html: html }
3669
+ });
3670
+ }
3671
+ case "paragraph-mdx":
3672
+ case "blockquote-mdx":
3673
+ case "list-item-mdx": {
3674
+ const status = node.props?.status ?? "pending";
3675
+ const raw = typeof node.props?.raw === "string" ? node.props?.raw : "";
3676
+ if (status === "compiled") {
3677
+ return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": "compiled" });
3678
+ }
3679
+ if (status === "error") {
3680
+ const message = raw || "MDX error";
3681
+ return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline text-destructive", "data-mdx-status": "error", children: message });
3682
+ }
3683
+ return /* @__PURE__ */ jsx("span", { className: "markdown-mdx-inline", "data-mdx-status": status, children: status === "compiled" ? "" : raw });
3684
+ }
3685
+ default:
3686
+ return null;
3687
+ }
3688
+ });
3689
+ MixedSegmentView.displayName = "MixedSegmentView";
3690
+ var HtmlBlockView = React7.memo(({ store, blockId, registry }) => {
3691
+ const node = useRendererNode(store, blockId);
3692
+ if (!node || !node.block) return null;
3693
+ return registry.renderBlock(node.block);
3694
+ });
3695
+ HtmlBlockView.displayName = "HtmlBlockView";
3696
+ var MdxBlockView = React7.memo(({ store, blockId, registry }) => {
3697
+ const node = useRendererNode(store, blockId);
3698
+ if (!node || !node.block) return null;
3699
+ return registry.renderBlock(node.block);
3700
+ });
3701
+ MdxBlockView.displayName = "MdxBlockView";
3702
+ var ListBlockView = React7.memo(
3703
+ ({ store, blockId, registry, depth = 0 }) => {
3704
+ const node = useRendererNode(store, blockId);
3705
+ const block = node?.block;
3706
+ const childIds = useRendererChildren(store, blockId);
3707
+ const inlineComponents = registry.getInlineComponents();
3708
+ const ordered = Boolean(node?.props?.ordered ?? block?.payload.meta?.ordered);
3709
+ const Tag = ordered ? "ol" : "ul";
3710
+ const listDebugEnabled = isListPatchDebugEnabled();
3711
+ const listItemIds = React7.useMemo(() => {
3712
+ const ids = [];
3713
+ for (const childId of childIds) {
3714
+ const childNode = store.getNode(childId);
3715
+ if (childNode?.type === "list-item") {
3716
+ ids.push(childId);
3717
+ }
3718
+ }
3719
+ return ids;
3720
+ }, [childIds, store]);
3721
+ React7.useEffect(() => {
3722
+ if (!listDebugEnabled) return;
3723
+ const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
3724
+ console.info("[stream-mdx:list-render]", {
3725
+ listId: blockId,
3726
+ depth,
3727
+ ordered,
3728
+ childIds,
3729
+ childTypes,
3730
+ listItemIds,
3731
+ listItems: listItemIds.length,
3732
+ totalChildren: childIds.length,
3733
+ isFinalized: block?.isFinalized ?? false
3734
+ });
3735
+ }, [listDebugEnabled, blockId, depth, ordered, childIds, listItemIds, store, block?.isFinalized]);
3736
+ const listStyle = React7.useMemo(() => {
3737
+ if (!ordered || listItemIds.length === 0) return void 0;
3738
+ let maxDigits = 1;
3739
+ listItemIds.forEach((childId, index) => {
3740
+ const childNode = store.getNode(childId);
3741
+ const raw = typeof childNode?.block?.payload?.raw === "string" ? childNode.block.payload.raw : void 0;
3742
+ const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
3743
+ const marker = markerMatch?.[1]?.trim();
3744
+ const text = marker ?? `${index + 1}.`;
3745
+ const digitMatch = text.match(/\d/g);
3746
+ const digits = digitMatch ? digitMatch.length : text.length;
3747
+ if (digits > maxDigits) maxDigits = digits;
3748
+ });
3749
+ const baseIndent = depth === 0 ? "2.5rem" : depth === 1 ? "2rem" : "1.5rem";
3750
+ return {
3751
+ ["--list-indent"]: `calc(${baseIndent} + ${maxDigits}ch)`
3752
+ };
3753
+ }, [ordered, listItemIds, store, depth]);
3754
+ if (listItemIds.length === 0) return null;
3755
+ return /* @__PURE__ */ jsx(
3756
+ Tag,
3757
+ {
3758
+ className: `markdown-list ${ordered ? "ordered" : "unordered"}`,
3759
+ "data-list-depth": depth,
3760
+ "data-list-id": listDebugEnabled ? blockId : void 0,
3761
+ style: listStyle,
3762
+ children: listItemIds.map((childId, index) => /* @__PURE__ */ jsx(
3763
+ ListItemView,
3764
+ {
3765
+ store,
3766
+ nodeId: childId,
3767
+ inlineComponents,
3768
+ registry,
3769
+ ordered,
3770
+ index,
3771
+ depth
3772
+ },
3773
+ childId
3774
+ ))
3775
+ }
3776
+ );
3777
+ }
3778
+ );
3779
+ ListBlockView.displayName = "ListBlockView";
3780
+ var ListItemView = React7.memo(({ store, nodeId, inlineComponents, registry, ordered, index, depth }) => {
3781
+ const node = useRendererNode(store, nodeId);
3782
+ const childIds = useRendererChildren(store, nodeId);
3783
+ const inline = node?.props?.inline ?? [];
3784
+ const isTask = Boolean(node?.props?.task);
3785
+ const isChecked = Boolean(node?.props?.checked);
3786
+ const block = node?.block;
3787
+ const raw = typeof block?.payload?.raw === "string" ? block.payload.raw : void 0;
3788
+ const markerMatch = raw ? raw.match(/^([^\s]+)\s+/) : null;
3789
+ const marker = markerMatch?.[1]?.trim();
3790
+ const inferredIndex = typeof node?.props?.index === "number" ? Number(node?.props?.index) : index;
3791
+ const isOrdered = Boolean(node?.props?.ordered ?? ordered);
3792
+ const counterText = !isTask ? isOrdered ? marker ? marker : `${inferredIndex + 1}.` : "\u2022" : void 0;
3793
+ const listDebugEnabled = isListPatchDebugEnabled();
3794
+ const inlineLength = inline.length;
3795
+ const [segmentChildIds, contentChildIds] = React7.useMemo(() => {
3796
+ const segments = [];
3797
+ const structural = [];
3798
+ for (const childId of childIds) {
3799
+ const childNode = store.getNode(childId);
3800
+ if (!childNode) continue;
3801
+ if (childNode.type?.startsWith("list-item-")) {
3802
+ segments.push(childId);
3803
+ } else {
3804
+ structural.push(childId);
3805
+ }
3806
+ }
3807
+ return [segments, structural];
3808
+ }, [childIds, store]);
3809
+ const segmentElements = React7.useMemo(() => {
3810
+ return segmentChildIds.map((childId) => /* @__PURE__ */ jsx(MixedSegmentView, { store, nodeId: childId, inlineComponents }, childId));
3811
+ }, [segmentChildIds, store, inlineComponents]);
3812
+ const primaryContent = React7.useMemo(() => {
3813
+ if (segmentChildIds.length > 0) {
3814
+ return segmentElements;
3815
+ }
3816
+ return renderInlineNodes(inline, inlineComponents);
3817
+ }, [segmentChildIds, segmentElements, inline, inlineComponents]);
3818
+ const trailingChildren = React7.useMemo(() => {
3819
+ return contentChildIds.map((childId) => {
3820
+ const childNode = store.getNode(childId);
3821
+ if (!childNode) return null;
3822
+ switch (childNode.type) {
3823
+ case "paragraph": {
3824
+ const childInline = childNode.props?.inline ?? [];
3825
+ return /* @__PURE__ */ jsx("p", { className: "markdown-list-item-paragraph", children: renderInlineNodes(childInline, inlineComponents) }, childId);
3826
+ }
3827
+ case "list":
3828
+ return /* @__PURE__ */ jsx(ListBlockView, { store, blockId: childId, registry, depth: depth + 1 }, childId);
3829
+ default:
3830
+ return /* @__PURE__ */ jsx(BlockNodeRenderer, { store, blockId: childId, registry }, childId);
3831
+ }
3832
+ });
3833
+ }, [contentChildIds, store, inlineComponents, registry, depth]);
3834
+ const filteredChildren = trailingChildren.filter((child) => Boolean(child));
3835
+ const hasChildren = filteredChildren.length > 0;
3836
+ React7.useEffect(() => {
3837
+ if (!listDebugEnabled) return;
3838
+ const childTypes = childIds.map((childId) => store.getNode(childId)?.type ?? "missing");
3839
+ console.info("[stream-mdx:list-item-render]", {
3840
+ itemId: nodeId,
3841
+ depth,
3842
+ ordered: isOrdered,
3843
+ inferredIndex,
3844
+ marker,
3845
+ isTask,
3846
+ isChecked,
3847
+ childIds,
3848
+ childTypes,
3849
+ segmentChildIds,
3850
+ contentChildIds,
3851
+ inlineLength,
3852
+ hasChildren,
3853
+ isFinalized: block?.isFinalized ?? false
3854
+ });
3855
+ }, [
3856
+ listDebugEnabled,
3857
+ nodeId,
3858
+ depth,
3859
+ isOrdered,
3860
+ inferredIndex,
3861
+ marker,
3862
+ isTask,
3863
+ isChecked,
3864
+ childIds,
3865
+ segmentChildIds,
3866
+ contentChildIds,
3867
+ inlineLength,
3868
+ hasChildren,
3869
+ store,
3870
+ block?.isFinalized
3871
+ ]);
3872
+ return /* @__PURE__ */ jsxs(
3873
+ "li",
3874
+ {
3875
+ className: `markdown-list-item${isTask ? " markdown-list-item-task" : ""}`,
3876
+ "data-counter-text": counterText,
3877
+ "data-list-depth": depth,
3878
+ "data-list-item-id": listDebugEnabled ? nodeId : void 0,
3879
+ children: [
3880
+ isTask ? /* @__PURE__ */ jsxs("div", { className: "markdown-task", children: [
3881
+ /* @__PURE__ */ jsx("input", { type: "checkbox", className: "markdown-task-checkbox", checked: isChecked, readOnly: true, disabled: true, tabIndex: -1, "aria-checked": isChecked }),
3882
+ /* @__PURE__ */ jsx("span", { className: "markdown-task-content", children: primaryContent })
3883
+ ] }) : primaryContent,
3884
+ hasChildren ? /* @__PURE__ */ jsx("div", { className: "markdown-list-item-children", children: filteredChildren }) : null
3885
+ ]
3886
+ }
3887
+ );
3888
+ });
3889
+ ListItemView.displayName = "ListItemView";
3890
+ var TableBlockView = React7.memo(({ store, blockId, registry }) => {
3891
+ const tableElements = registry.getTableElements();
3892
+ const childIds = useRendererChildren(store, blockId);
3893
+ return /* @__PURE__ */ jsx(tableElements.Table, { className: "markdown-table w-full caption-bottom text-base", children: childIds.map((sectionId) => /* @__PURE__ */ jsx(TableSectionView, { store, nodeId: sectionId, registry }, sectionId)) });
3894
+ });
3895
+ TableBlockView.displayName = "TableBlockView";
3896
+ var TableSectionView = React7.memo(({ store, nodeId, registry }) => {
3897
+ const node = useRendererNode(store, nodeId);
3898
+ if (!node) return null;
3899
+ const tableElements = registry.getTableElements();
3900
+ if (node.type === "table-header") {
3901
+ const childIds = useRendererChildren(store, nodeId);
3902
+ return /* @__PURE__ */ jsx(tableElements.Thead, { children: /* @__PURE__ */ jsx(tableElements.Tr, { children: childIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) }) });
3903
+ }
3904
+ if (node.type === "table-body") {
3905
+ const rowIds = useRendererChildren(store, nodeId);
3906
+ return /* @__PURE__ */ jsx(tableElements.Tbody, { children: rowIds.map((rowId) => /* @__PURE__ */ jsx(TableRowView, { store, nodeId: rowId, registry }, rowId)) });
3907
+ }
3908
+ return null;
3909
+ });
3910
+ TableSectionView.displayName = "TableSectionView";
3911
+ var TableRowView = React7.memo(({ store, nodeId, registry }) => {
3912
+ const tableElements = registry.getTableElements();
3913
+ const cellIds = useRendererChildren(store, nodeId);
3914
+ return /* @__PURE__ */ jsx(tableElements.Tr, { children: cellIds.map((cellId) => /* @__PURE__ */ jsx(TableCellView, { store, nodeId: cellId, registry }, cellId)) });
3915
+ });
3916
+ TableRowView.displayName = "TableRowView";
3917
+ var TableCellView = React7.memo(({ store, nodeId, registry }) => {
3918
+ const node = useRendererNode(store, nodeId);
3919
+ const inlineComponents = registry.getInlineComponents();
3920
+ const tableElements = registry.getTableElements();
3921
+ if (!node) return null;
3922
+ const Tag = node.type === "table-header-cell" ? tableElements.Th : tableElements.Td;
3923
+ const inline = node.props?.inline ?? [];
3924
+ const align = node.props?.align;
3925
+ const content = renderInlineNodes(inline, inlineComponents);
3926
+ const alignProps = align ? { align } : void 0;
3927
+ return /* @__PURE__ */ jsx(Tag, { ...alignProps, children: content });
3928
+ });
3929
+ TableCellView.displayName = "TableCellView";
3930
+ var CodeBlockView = React7.memo(({ store, blockId, registry }) => {
3931
+ const node = useRendererNode(store, blockId);
3932
+ const childIds = useRendererChildren(store, blockId);
3933
+ const CodeComponent = registry.getBlockComponent("code");
3934
+ const deferredConfig = React7.useContext(DeferredRenderContext);
3935
+ const deferredRef = React7.useRef(null);
3936
+ const shouldRenderDeferred = useDeferredRender(
3937
+ deferredRef,
3938
+ deferredConfig ? { ...deferredConfig, enabled: true } : { enabled: false }
3939
+ );
3940
+ if (!node || !node.block) return null;
3941
+ const nodeVersion = node.version;
3942
+ const lines = React7.useMemo(() => {
3943
+ const seenIds = /* @__PURE__ */ new Set();
3944
+ const seenIndices = /* @__PURE__ */ new Set();
3945
+ const deduped = [];
3946
+ for (const childId of childIds) {
3947
+ const child = store.getNode(childId);
3948
+ if (!child) continue;
3949
+ const index = typeof child.props?.index === "number" ? child.props?.index : deduped.length;
3950
+ const text = typeof child.props?.text === "string" ? child.props?.text : "";
3951
+ const html = typeof child.props?.html === "string" ? child.props?.html : null;
3952
+ const tokens = Object.prototype.hasOwnProperty.call(child.props ?? {}, "tokens") ? child.props?.tokens : void 0;
3953
+ if (seenIds.has(child.id) || seenIndices.has(index)) {
3954
+ console.warn("[renderer-view] duplicate code line detected", {
3955
+ blockId,
3956
+ childId: child.id,
3957
+ index
3958
+ });
3959
+ continue;
3960
+ }
3961
+ seenIds.add(child.id);
3962
+ seenIndices.add(index);
3963
+ deduped.push({ id: child.id, index, text, html, tokens });
3964
+ }
3965
+ deduped.sort((a, b) => a.index - b.index);
3966
+ return deduped;
3967
+ }, [childIds, store, blockId, nodeVersion]);
3968
+ const lang = typeof node.props?.lang === "string" ? node.props?.lang : node.block.payload.meta?.lang;
3969
+ const preAttrs = node.props?.preAttrs ?? void 0;
3970
+ const codeAttrs = node.props?.codeAttrs ?? void 0;
3971
+ const virtualizationConfig = DEFAULT_VIRTUALIZED_CODE_CONFIG;
3972
+ const virtualizationDisabled = typeof process !== "undefined" && typeof process.env === "object" && process.env.STREAM_MDX_DISABLE_VIRTUALIZED_CODE === "true";
3973
+ const shouldVirtualize = !virtualizationDisabled && virtualizationConfig.enabled && lines.length >= virtualizationConfig.virtualizeThreshold;
3974
+ const virtualization = useVirtualizedCode(lines, shouldVirtualize ? virtualizationConfig : { ...virtualizationConfig, enabled: false });
3975
+ const highlightRequester = useCodeHighlightRequester();
3976
+ const lazyEnabled = Boolean(node.block.payload.meta?.lazyTokenization);
3977
+ const lazyTokenizedUntil = typeof node.block.payload.meta?.lazyTokenizedUntil === "number" ? node.block.payload.meta.lazyTokenizedUntil : 0;
3978
+ const lastRangeRef = React7.useRef(null);
3979
+ const rafRef = React7.useRef(null);
3980
+ const idleRef = React7.useRef(null);
3981
+ React7.useEffect(() => {
3982
+ if (!shouldVirtualize || !lazyEnabled || !highlightRequester) return;
3983
+ const { visibleStart, visibleEnd, startIndex, endIndex } = virtualization.window;
3984
+ if (endIndex <= lazyTokenizedUntil) return;
3985
+ const nextRange = {
3986
+ visibleStart,
3987
+ visibleEnd,
3988
+ prefetchStart: startIndex,
3989
+ prefetchEnd: endIndex,
3990
+ tokenizedUntil: lazyTokenizedUntil
3991
+ };
3992
+ const last = lastRangeRef.current;
3993
+ if (last && last.visibleStart === nextRange.visibleStart && last.visibleEnd === nextRange.visibleEnd && last.prefetchStart === nextRange.prefetchStart && last.prefetchEnd === nextRange.prefetchEnd && last.tokenizedUntil === nextRange.tokenizedUntil) {
3994
+ return;
3995
+ }
3996
+ lastRangeRef.current = nextRange;
3997
+ if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
3998
+ cancelAnimationFrame(rafRef.current);
3999
+ }
4000
+ if (typeof requestAnimationFrame === "function") {
4001
+ rafRef.current = requestAnimationFrame(() => {
4002
+ highlightRequester({
4003
+ blockId,
4004
+ startLine: visibleStart,
4005
+ endLine: visibleEnd,
4006
+ priority: "visible",
4007
+ reason: "scroll"
4008
+ });
4009
+ rafRef.current = null;
4010
+ });
4011
+ } else {
4012
+ highlightRequester({
4013
+ blockId,
4014
+ startLine: visibleStart,
4015
+ endLine: visibleEnd,
4016
+ priority: "visible",
4017
+ reason: "scroll"
4018
+ });
4019
+ }
4020
+ const prefetchNeeded = startIndex < visibleStart || endIndex > visibleEnd;
4021
+ if (prefetchNeeded) {
4022
+ const idleCallback = globalThis.requestIdleCallback;
4023
+ const cancelIdle = globalThis.cancelIdleCallback;
4024
+ if (idleRef.current !== null) {
4025
+ if (typeof cancelIdle === "function") {
4026
+ cancelIdle(idleRef.current);
4027
+ } else if (typeof clearTimeout === "function") {
4028
+ clearTimeout(idleRef.current);
4029
+ }
4030
+ }
4031
+ const schedule = () => {
4032
+ highlightRequester({
4033
+ blockId,
4034
+ startLine: startIndex,
4035
+ endLine: endIndex,
4036
+ priority: "prefetch",
4037
+ reason: "buffer"
4038
+ });
4039
+ idleRef.current = null;
4040
+ };
4041
+ if (typeof idleCallback === "function") {
4042
+ idleRef.current = idleCallback(() => schedule());
4043
+ } else if (typeof setTimeout === "function") {
4044
+ idleRef.current = setTimeout(schedule, 80);
4045
+ }
4046
+ }
4047
+ }, [
4048
+ blockId,
4049
+ highlightRequester,
4050
+ lazyEnabled,
4051
+ lazyTokenizedUntil,
4052
+ shouldVirtualize,
4053
+ virtualization.window.visibleStart,
4054
+ virtualization.window.visibleEnd,
4055
+ virtualization.window.startIndex,
4056
+ virtualization.window.endIndex
4057
+ ]);
4058
+ const highlightedHtml = React7.useMemo(() => {
4059
+ if (!shouldVirtualize && node.block?.payload.highlightedHtml) {
4060
+ return node.block.payload.highlightedHtml;
4061
+ }
4062
+ if (lines.length > 0) {
4063
+ const hasLineHtml = lines.some((line) => typeof line.html === "string" && line.html.length > 0);
4064
+ if (!hasLineHtml && node.block?.payload.highlightedHtml) {
4065
+ return node.block.payload.highlightedHtml;
4066
+ }
4067
+ if (shouldVirtualize) {
4068
+ return composeHighlightedHtml(virtualization.window.visibleLines, preAttrs, codeAttrs);
4069
+ }
4070
+ return composeHighlightedHtml(lines, preAttrs, codeAttrs);
4071
+ }
4072
+ const blockHtml = node.block?.payload.highlightedHtml ?? "";
4073
+ if (blockHtml?.trim().match(/^```[\w-]*\s*$/)) {
4074
+ const raw = node.block?.payload.raw ?? "";
4075
+ if (raw.trim().length > 0) {
4076
+ return composeHighlightedHtml([{ index: 0, text: raw, html: null, id: "temp" }], preAttrs, codeAttrs);
4077
+ }
4078
+ }
4079
+ return blockHtml;
4080
+ }, [shouldVirtualize, node.block?.payload.highlightedHtml, lines, preAttrs, codeAttrs, virtualization.window.visibleLines, node.block?.payload.raw]);
4081
+ const rendered = /* @__PURE__ */ jsx(
4082
+ CodeComponent,
4083
+ {
4084
+ html: highlightedHtml,
4085
+ meta: node.block.payload.meta,
4086
+ lines: shouldVirtualize ? virtualization.window.visibleLines : lines,
4087
+ lang,
4088
+ preAttrs,
4089
+ codeAttrs
4090
+ }
4091
+ );
4092
+ const codeFrameClass = "not-prose flex flex-col rounded-lg border border-input pt-1 font-mono text-sm";
4093
+ const codeMetricsAttrs = {
4094
+ "data-code-block": "true",
4095
+ "data-block-id": blockId,
4096
+ "data-code-virtualized": shouldVirtualize ? "true" : "false",
4097
+ "data-code-total-lines": String(lines.length),
4098
+ "data-code-mounted-lines": String(shouldVirtualize ? virtualization.window.mountedLines : lines.length),
4099
+ "data-code-window-size": String(virtualization.config.windowSize)
4100
+ };
4101
+ const codeView = shouldVirtualize ? (() => {
4102
+ const { containerRef, window: window2, handleScroll, lineHeight } = virtualization;
4103
+ const spacerTop = window2.startIndex * lineHeight;
4104
+ const spacerBottom = (window2.totalLines - window2.endIndex) * lineHeight;
4105
+ return /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: /* @__PURE__ */ jsxs(
4106
+ "div",
4107
+ {
4108
+ ref: containerRef,
4109
+ className: "markdown-code-block-container relative",
4110
+ style: { overflowY: "auto", overflowX: "hidden", maxHeight: "600px" },
4111
+ onScroll: handleScroll,
4112
+ children: [
4113
+ /* @__PURE__ */ jsx("div", { style: { height: spacerTop }, "aria-hidden": "true" }),
4114
+ rendered,
4115
+ /* @__PURE__ */ jsx("div", { style: { height: spacerBottom }, "aria-hidden": "true" })
4116
+ ]
4117
+ }
4118
+ ) });
4119
+ })() : /* @__PURE__ */ jsx("pre", { className: codeFrameClass, ...codeMetricsAttrs, children: rendered });
4120
+ const blockComponentMap = registry.getBlockComponentMap();
4121
+ const MermaidComponent = Object.prototype.hasOwnProperty.call(blockComponentMap, "mermaid") ? blockComponentMap.mermaid : null;
4122
+ if ((lang ?? "").toLowerCase() === "mermaid" && MermaidComponent) {
4123
+ const raw = typeof node.block.payload.raw === "string" ? node.block.payload.raw : "";
4124
+ const fenced = stripCodeFence(raw);
4125
+ const code = fenced.hadFence ? fenced.code : raw;
4126
+ if (deferredConfig) {
4127
+ return /* @__PURE__ */ jsx("div", { ref: deferredRef, children: shouldRenderDeferred ? React7.createElement(MermaidComponent, {
4128
+ code,
4129
+ renderCode: codeView,
4130
+ meta: node.block.payload.meta,
4131
+ isFinalized: node.block.isFinalized
4132
+ }) : codeView });
4133
+ }
4134
+ return React7.createElement(MermaidComponent, {
4135
+ code,
4136
+ renderCode: codeView,
4137
+ meta: node.block.payload.meta,
4138
+ isFinalized: node.block.isFinalized
4139
+ });
4140
+ }
4141
+ return codeView;
4142
+ });
4143
+ CodeBlockView.displayName = "CodeBlockView";
4144
+ function composeHighlightedHtml(lines, preAttrs, codeAttrs) {
4145
+ const lineMarkup = lines.map((line) => {
4146
+ const content = line.html ?? escapeHtml3(line.text);
4147
+ const dataLine = Number.isFinite(line.index) ? ` data-line="${line.index + 1}"` : "";
4148
+ return `<span class="line"${dataLine}>${content}</span>`;
4149
+ }).join("\n");
4150
+ const preAttr = attrsToString(preAttrs);
4151
+ const codeAttr = attrsToString(codeAttrs);
4152
+ return `<pre${preAttr}><code${codeAttr}>${lineMarkup}
4153
+ </code></pre>`;
4154
+ }
4155
+ function attrsToString(attrs) {
4156
+ if (!attrs) return "";
4157
+ return Object.entries(attrs).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("");
4158
+ }
4159
+ function escapeHtml3(value) {
4160
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
4161
+ }
4162
+ function escapeAttribute(value) {
4163
+ return value.replace(/"/g, "&quot;");
4164
+ }
4165
+
4166
+ // src/renderer/blocks-renderer.tsx
4167
+ var MarkdownBlocksRenderer = React8.memo(({ blocks, componentRegistry, className = "markdown-renderer", style, store }) => {
4168
+ if (store) {
4169
+ return React8.createElement(
4170
+ "div",
4171
+ {
4172
+ className,
4173
+ style: { contain: "content", ...style ?? {} }
4174
+ // CSS containment for performance
4175
+ },
4176
+ React8.createElement(StoreBackedBlocks, { store, componentRegistry })
4177
+ );
4178
+ }
4179
+ const renderedBlocks = useMemo3(() => {
4180
+ return blocks.map((block) => {
4181
+ const key = getBlockKey(block);
4182
+ return React8.createElement(BlockRenderer, {
4183
+ key,
4184
+ block,
4185
+ componentRegistry,
4186
+ isFinalized: block.isFinalized
4187
+ });
4188
+ });
4189
+ }, [blocks, componentRegistry]);
4190
+ return React8.createElement(
4191
+ "div",
4192
+ {
4193
+ className,
4194
+ style: { contain: "content", ...style ?? {} }
4195
+ // CSS containment for performance
4196
+ },
4197
+ renderedBlocks
4198
+ );
4199
+ });
4200
+ var StoreBackedBlocks = React8.memo(
4201
+ ({ store, componentRegistry }) => {
4202
+ const blockIds = useRendererChildren(store, PATCH_ROOT_ID2);
4203
+ return React8.createElement(
4204
+ React8.Fragment,
4205
+ null,
4206
+ blockIds.map((blockId) => React8.createElement(BlockNodeRenderer, { key: blockId, store, blockId, registry: componentRegistry }))
4207
+ );
4208
+ }
4209
+ );
4210
+ StoreBackedBlocks.displayName = "StoreBackedBlocks";
4211
+ var BlockRenderer = React8.memo(({ block, componentRegistry, isFinalized }) => {
4212
+ const element = useMemo3(() => {
4213
+ return componentRegistry.renderBlock(block);
4214
+ }, [block, componentRegistry]);
4215
+ const className = `markdown-block markdown-block-${block.type} ${isFinalized ? "finalized" : "dirty"}`;
4216
+ return React8.cloneElement(element, {
4217
+ className: `${element.props.className || ""} ${className}`.trim(),
4218
+ "data-block-id": block.id,
4219
+ "data-finalized": isFinalized
4220
+ });
4221
+ });
4222
+ export {
4223
+ ComponentRegistry,
4224
+ MarkdownBlocksRenderer,
4225
+ createRendererStore
4226
+ };