@toaq-oss/omni-mdx 0.1.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.
package/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TOAQ-oss
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,221 @@
1
+ # @toaq-oss/omni-mdx
2
+
3
+ The React/Next.js visual rendering engine of the TOAQ-oss MDX ecosystem.
4
+
5
+ [![GitHub](https://img.shields.io/badge/GitHub-TOAQ--oss-181717?logo=github)](https://github.com/toaq-oss)
6
+
7
+
8
+ This package consumes the ultra-fast Abstract Syntax Tree (AST) generated by our Rust core in WebAssembly (@toaq-oss/core-parser) and transforms it into interactive, secure, and highly customizable React components.
9
+
10
+ ---
11
+
12
+ ## Why this exists
13
+
14
+ Most MDX pipelines (next-mdx-remote, @next/mdx, contentlayer) run at the JS level and require client-side hydration for math, syntax highlighting, and custom components. This means:
15
+
16
+ - A large JS bundle sent to every visitor
17
+ - Math rendered on the client (flash of unstyled content)
18
+ - Custom components that can't be pure Server Components
19
+
20
+ `@toaq-oss/omni-mdx` solves this by moving the parse step into Rust and the render step into React Server Components. The result is **zero JS for content** — everything is HTML by the time it reaches the browser.
21
+
22
+ The WASM build is available as a fallback for Edge runtimes or environments where native addons are not supported.
23
+
24
+ ---
25
+
26
+ ## Performance & Architecture
27
+
28
+ `@toaq-oss/omni-mdx` is designed for scale. While traditional parsers block the Node.js main thread, our parser offloads the heavy lifting to a native Rust core via WebAssembly or N-API.
29
+
30
+ **1. Non-Blocking by Design**
31
+ Parsing complex documents or extracting data from thousands of files for ML datasets won't freeze your server. Node.js remains completely free to handle other HTTP requests while Rust does the work in the background.
32
+
33
+ **2. Faster than the Standard**
34
+ In a strict end-to-end benchmark (parsing raw text to an exploitable JSX AST) over 1,000 iterations of a complex document:
35
+ - `@toaq-oss/omni-mdx` is consistently **~30% faster** than the official `@mdx-js/mdx` compiler.
36
+
37
+ **3. Zero Client JS**
38
+ Because the AST is generated on the server and maps directly to React Server Components, the client receives 0 bytes of parsing logic.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ npm install @toaq-oss/omni-mdx
44
+ # KaTeX is optional — only needed if your content has math
45
+ npm install katex
46
+ ```
47
+
48
+ Add the KaTeX stylesheet to your `layout.tsx`:
49
+
50
+ ```tsx
51
+ import "katex/dist/katex.min.css";
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Usage
57
+
58
+ ### Server Component (recommended)
59
+
60
+ ```tsx
61
+ import { parseMdx, MDXServerRenderer } from "@toaq-oss/omni-mdx/server";
62
+ import { Note, Details } from "@/components/mdx";
63
+
64
+ const COMPONENTS = { Note, Details };
65
+
66
+ export default async function ArticlePage({ params }) {
67
+ const content = await getArticleContent(params.slug);
68
+ const ast = await parseMdx(content);
69
+
70
+ return <MDXServerRenderer ast={ast} components={COMPONENTS} />;
71
+ }
72
+ ```
73
+
74
+ That's it. No `getStaticProps`, no serialisation workarounds, no client bundle for the content.
75
+
76
+ ### Static generation
77
+
78
+ Because `parseMdx` is async and runs on the server, it works naturally with `generateStaticParams`:
79
+
80
+ ```tsx
81
+ export async function generateStaticParams() {
82
+ const slugs = await getAllSlugs();
83
+ return slugs.map(slug => ({ slug }));
84
+ }
85
+
86
+ export default async function ArticlePage({ params }) {
87
+ const content = await getArticleContent(params.slug);
88
+ const ast = await parseMdx(content);
89
+ return <MDXServerRenderer ast={ast} components={COMPONENTS} />;
90
+ }
91
+ ```
92
+
93
+ At `next build`, Next.js calls `parseMdx` once per article and pre-renders everything to static HTML. The Rust parser never runs in the browser.
94
+
95
+ ### Live editor (client-side)
96
+
97
+ For live MDX previews where the content changes in the browser:
98
+
99
+ ```tsx
100
+ "use client";
101
+ import { MDXClientRenderer } from "@toaq-oss/omni-mdx/client";
102
+
103
+ export function LivePreview({ ast, components }) {
104
+ return <MDXClientRenderer ast={ast} components={components} katex />;
105
+ }
106
+ ```
107
+
108
+ The `ast` prop should be computed server-side and passed down, or computed client-side by calling a Route Handler that runs `parseMdx`.
109
+
110
+ ---
111
+
112
+ ## Import map
113
+
114
+ |Import path|What you get|Where to use|
115
+ |----|---|----|
116
+ |`@toaq-oss/omni-mdx`|Types + `MDX_COMPONENTS` registry|Anywhere|
117
+ |`@toaq-oss/omni-mdx/server`|`parseMdx`, `MDXServerRenderer`, `MDXParseError` |Server Components only|
118
+ |`@toaq-oss/omni-mdx/client`|`MDXClientRenderer`, `MDXErrorBoundary`|Client Components only|
119
+
120
+ ---
121
+
122
+ ## Custom components
123
+
124
+ Register components by name — the key matches the JSX tag in the MDX source:
125
+
126
+ ```tsx
127
+ // MDX source:
128
+ // <Note type="warning" title="Heads up">
129
+ // Be careful with **this**.
130
+ // </Note>
131
+
132
+ import { Note } from "@/components/Note"; // can be a Server Component
133
+ import { Details } from "@/components/Details"; // can be a Server Component
134
+ import { Chart } from "@/components/Chart"; // "use client" inside
135
+
136
+ const COMPONENTS = { Note, Details, Chart };
137
+
138
+ const ast = await parseMdx(content);
139
+ return <MDXServerRenderer ast={ast} components={COMPONENTS} />;
140
+ ```
141
+
142
+ Server Components in the registry are rendered on the server with zero client JS. Client Components are hydrated normally.
143
+
144
+ ---
145
+
146
+ ## Error handling
147
+
148
+ ### Parse errors
149
+
150
+ ```tsx
151
+ import { parseMdx, MDXParseError } from "@toaq-oss/omni-mdx/server";
152
+
153
+ try {
154
+ const ast = await parseMdx(content);
155
+ } catch (e) {
156
+ if (e instanceof MDXParseError) {
157
+ console.error("MDX syntax error:", e.message);
158
+ console.error("Source:", e.source);
159
+ }
160
+ }
161
+ ```
162
+
163
+ ### Component render errors
164
+
165
+ In `MDXClientRenderer`, every custom component is automatically wrapped in `MDXErrorBoundary`. If a component throws, the error is isolated — the rest of the document continues to render.
166
+
167
+ You can also use `MDXErrorBoundary` directly:
168
+
169
+ ```tsx
170
+ import { MDXErrorBoundary } from "@toaq-oss/omni-mdx/client";
171
+
172
+ <MDXErrorBoundary componentName="Chart">
173
+ <Chart data={maybeNull} />
174
+ </MDXErrorBoundary>
175
+ ```
176
+
177
+ ---
178
+
179
+ ## Math
180
+
181
+ Math is handled entirely by the Rust parser — no remark-math or rehype-katex needed.
182
+
183
+ | Syntax | Output |
184
+ |---|---|
185
+ | `$E = mc^2$` | `<span class="math math-inline" data-math="…">` |
186
+ | `$$…$$` | `<div class="math math-display" data-math="…">` |
187
+
188
+ KaTeX hydrates the `data-math` attributes on the client via `MDXClientRenderer`, or you can use any KaTeX auto-render script in your layout.
189
+
190
+ ---
191
+
192
+ ## Runtime support
193
+
194
+ | Runtime | Native `.node` | WASM fallback |
195
+ |-----------------|:--------------:|:-------------:|
196
+ | Node.js 18+ | ✅ | ✅ |
197
+ | Next.js (RSC) | ✅ | ✅ |
198
+ | Edge runtime | ❌ | ✅ |
199
+ | Browser | ❌ | ✅ |
200
+
201
+ The package auto-detects the environment and loads the appropriate backend. No configuration required.
202
+
203
+ ---
204
+
205
+ ## Building the native addon
206
+
207
+ The `.node` files are pre-built for common platforms. To build for your platform:
208
+
209
+ ```bash
210
+ cd core-parser
211
+ napi build --platform --release --features node --no-js
212
+ cp toaq-parser-core.*.node ../packages/mdx-next/native/
213
+ ```
214
+
215
+ To build the WASM fallback:
216
+
217
+ ```bash
218
+ cd core-parser
219
+ wasm-pack build --target bundler --features wasm
220
+ mv pkg/* ../packages/mdx-next/wasm/
221
+ ```
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ "use client";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/client.ts
32
+ var client_exports = {};
33
+ __export(client_exports, {
34
+ MDXClientRenderer: () => MDXClientRenderer,
35
+ MDXErrorBoundary: () => MDXErrorBoundary
36
+ });
37
+ module.exports = __toCommonJS(client_exports);
38
+
39
+ // src/MDXClientRenderer.tsx
40
+ var import_react2 = __toESM(require("react"), 1);
41
+
42
+ // src/MDXErrorBoundary.tsx
43
+ var import_react = require("react");
44
+ var import_jsx_runtime = require("react/jsx-runtime");
45
+ var MDXErrorBoundary = class extends import_react.Component {
46
+ constructor(props) {
47
+ super(props);
48
+ this.state = { hasError: false, error: null };
49
+ }
50
+ /**
51
+ * Updates the state when an error occurs to trigger the fallback UI rendering.
52
+ */
53
+ static getDerivedStateFromError(error) {
54
+ return { hasError: true, error };
55
+ }
56
+ /**
57
+ * Intercepts the error and its contextual information.
58
+ * This is the ideal place to hook into monitoring tools (like Sentry or Datadog)
59
+ * for production environments.
60
+ */
61
+ componentDidCatch(error, errorInfo) {
62
+ console.error(
63
+ `[MDXErrorBoundary] Error caught in component <${this.props.componentName || "Unknown"}>:
64
+ `,
65
+ error,
66
+ errorInfo.componentStack
67
+ );
68
+ }
69
+ render() {
70
+ if (this.state.hasError) {
71
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { padding: "1rem", border: "2px solid #ef4444", backgroundColor: "#fef2f2", borderRadius: "0.5rem", margin: "1rem 0" }, children: [
72
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h3", { style: { color: "#b91c1c", fontWeight: "bold", margin: 0 }, children: [
73
+ "Render Error : ",
74
+ this.props.componentName || "Unknown Component"
75
+ ] }),
76
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { style: { color: "#dc2626", fontFamily: "monospace", fontSize: "0.875rem" }, children: this.state.error?.message })
77
+ ] });
78
+ }
79
+ return this.props.children;
80
+ }
81
+ };
82
+
83
+ // src/MDXClientRenderer.tsx
84
+ var import_jsx_runtime2 = require("react/jsx-runtime");
85
+ var katexLoaded = false;
86
+ async function loadKatex() {
87
+ if (katexLoaded || typeof window === "undefined") return;
88
+ try {
89
+ const [{ default: katex }, autoRenderMod] = await Promise.all([
90
+ import("katex"),
91
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
92
+ import("katex/contrib/auto-render")
93
+ ]);
94
+ const renderMathInElement = autoRenderMod.default ?? autoRenderMod;
95
+ katexLoaded = true;
96
+ return renderMathInElement;
97
+ } catch {
98
+ console.warn("[toaq/mdx-engine] KaTeX not available. Install: npm install katex");
99
+ return null;
100
+ }
101
+ }
102
+ function resolveAttr(attr, components) {
103
+ switch (attr.kind) {
104
+ case "text":
105
+ return attr.value;
106
+ case "boolean":
107
+ return true;
108
+ case "expression": {
109
+ const raw = attr.value.trim();
110
+ try {
111
+ return JSON.parse(raw);
112
+ } catch {
113
+ }
114
+ try {
115
+ return new Function(`return (${raw})`)();
116
+ } catch {
117
+ }
118
+ return raw;
119
+ }
120
+ case "ast":
121
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MDXClientContent, { ast: attr.value, components });
122
+ default:
123
+ return void 0;
124
+ }
125
+ }
126
+ var HTML_TAGS = /* @__PURE__ */ new Set([
127
+ "a",
128
+ "abbr",
129
+ "article",
130
+ "aside",
131
+ "b",
132
+ "blockquote",
133
+ "br",
134
+ "caption",
135
+ "cite",
136
+ "code",
137
+ "col",
138
+ "colgroup",
139
+ "dd",
140
+ "del",
141
+ "details",
142
+ "dfn",
143
+ "div",
144
+ "dl",
145
+ "dt",
146
+ "em",
147
+ "figcaption",
148
+ "figure",
149
+ "footer",
150
+ "h1",
151
+ "h2",
152
+ "h3",
153
+ "h4",
154
+ "h5",
155
+ "h6",
156
+ "header",
157
+ "hr",
158
+ "i",
159
+ "img",
160
+ "ins",
161
+ "kbd",
162
+ "li",
163
+ "main",
164
+ "mark",
165
+ "nav",
166
+ "ol",
167
+ "p",
168
+ "pre",
169
+ "q",
170
+ "s",
171
+ "section",
172
+ "small",
173
+ "span",
174
+ "strong",
175
+ "sub",
176
+ "summary",
177
+ "sup",
178
+ "table",
179
+ "tbody",
180
+ "td",
181
+ "tfoot",
182
+ "th",
183
+ "thead",
184
+ "tr",
185
+ "u",
186
+ "ul",
187
+ "var"
188
+ ]);
189
+ function renderNode(node, index, components) {
190
+ const key = `${node.node_type}-${index}`;
191
+ if (node.node_type === "text") return node.content ?? null;
192
+ if (node.node_type === "fragment") {
193
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react2.default.Fragment, { children: node.children?.map((c, i) => renderNode(c, i, components)) }, key);
194
+ }
195
+ if (node.node_type === "InlineMath") {
196
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
197
+ "span",
198
+ {
199
+ className: "math math-inline",
200
+ "data-math": node.content ?? "",
201
+ suppressHydrationWarning: true
202
+ },
203
+ key
204
+ );
205
+ }
206
+ if (node.node_type === "BlockMath") {
207
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
208
+ "div",
209
+ {
210
+ className: "math math-display",
211
+ "data-math": node.content ?? "",
212
+ suppressHydrationWarning: true
213
+ },
214
+ key
215
+ );
216
+ }
217
+ const resolvedProps = {};
218
+ if (node.attributes) {
219
+ for (const [k, v] of Object.entries(node.attributes)) {
220
+ resolvedProps[k] = resolveAttr(v, components);
221
+ }
222
+ }
223
+ const renderedChildren = node.children?.length ? node.children.map((c, i) => renderNode(c, i, components)) : node.content ?? void 0;
224
+ const Custom = components[node.node_type];
225
+ if (Custom) {
226
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MDXErrorBoundary, { componentName: node.node_type, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Custom, { ...resolvedProps, children: renderedChildren }) }, key);
227
+ }
228
+ if (HTML_TAGS.has(node.node_type)) {
229
+ const Tag = node.node_type;
230
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Tag, { ...resolvedProps, children: renderedChildren }, key);
231
+ }
232
+ if (true) {
233
+ console.warn(`[toaq/mdx-engine] Unknown component: <${node.node_type}>`);
234
+ }
235
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { "data-missing-component": node.node_type, className: "mdx-missing-component", children: renderedChildren }, key);
236
+ }
237
+ function MDXClientContent({
238
+ ast,
239
+ components
240
+ }) {
241
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children: ast.map((node, i) => renderNode(node, i, components)) });
242
+ }
243
+ function MDXClientRenderer({
244
+ ast,
245
+ components = {},
246
+ katex = true
247
+ }) {
248
+ const rootRef = (0, import_react2.useRef)(null);
249
+ (0, import_react2.useEffect)(() => {
250
+ if (!katex || !rootRef.current) return;
251
+ loadKatex().then((renderMath) => {
252
+ if (!renderMath || !rootRef.current) return;
253
+ renderMath(rootRef.current, {
254
+ delimiters: [
255
+ { left: "$$", right: "$$", display: true },
256
+ { left: "$", right: "$", display: false }
257
+ ]
258
+ });
259
+ rootRef.current.querySelectorAll("[data-math]").forEach((el) => {
260
+ const math = el.getAttribute("data-math") ?? "";
261
+ const display = el.classList.contains("math-display");
262
+ try {
263
+ import("katex").then(({ default: k }) => {
264
+ el.innerHTML = k.renderToString(math, { displayMode: display, throwOnError: false });
265
+ });
266
+ } catch {
267
+ }
268
+ });
269
+ });
270
+ }, [ast, katex]);
271
+ if (!ast || !Array.isArray(ast)) return null;
272
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { ref: rootRef, className: "omni-mdx-root", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MDXClientContent, { ast, components }) });
273
+ }
274
+ //# sourceMappingURL=client.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/MDXClientRenderer.tsx","../src/MDXErrorBoundary.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * @toaq/mdx-engine/client\n *\n * Client-only entry point.\n * Use for live MDX editors, previews, or any fully client-side rendering.\n */\n\nexport { MDXClientRenderer } from \"./MDXClientRenderer\";\nexport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nexport type { AstNode, MDXComponents } from \"./MDXServerRenderer\";","\"use client\";\n\n/**\n * MDXClientRenderer.tsx\n *\n * Client Component — handles KaTeX hydration and interactive components.\n *\n * You generally do NOT use this directly.\n * Use <MDXServerRenderer> in Server Components and only register Client\n * Components (wrapped in \"use client\") for interactive parts (charts, tabs, etc.).\n *\n * Use this component ONLY when:\n * 1. You are in a page/layout that is entirely client-side (no RSC)\n * 2. You need live re-rendering (e.g. a live MDX editor/preview)\n *\n * For the live editor use case, import from '@toaq/mdx-engine/client'.\n */\n\nimport React, { ReactNode, createContext, useContext, useEffect, useRef } from \"react\";\nimport { MDXErrorBoundary } from \"./MDXErrorBoundary\";\nimport type { AstNode, MDXComponents } from \"./MDXServerRenderer\";\n\n// KaTeX loader (client-only, dynamic import)\n\nlet katexLoaded = false;\n\nasync function loadKatex() {\n if (katexLoaded || typeof window === \"undefined\") return;\n try {\n // Dynamically import KaTeX auto-render (avoids SSR issues)\n const [{ default: katex }, autoRenderMod] = await Promise.all([\n import(\"katex\"),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n import(\"katex/contrib/auto-render\") as any,\n ]);\n const renderMathInElement = autoRenderMod.default ?? autoRenderMod;\n katexLoaded = true;\n return renderMathInElement;\n } catch {\n console.warn(\"[toaq/mdx-engine] KaTeX not available. Install: npm install katex\");\n return null;\n }\n}\n\n// Attr resolver (client version handles expressions fully)\n\ntype AttrValueKind =\n | { kind: \"text\"; value: string }\n | { kind: \"expression\"; value: string }\n | { kind: \"boolean\" }\n | { kind: \"ast\"; value: AstNode[] };\n\nfunction resolveAttr(\n attr: AttrValueKind,\n components: MDXComponents,\n): React.ReactNode | string | boolean {\n switch (attr.kind) {\n case \"text\": return attr.value;\n case \"boolean\": return true;\n case \"expression\": {\n const raw = attr.value.trim();\n try { return JSON.parse(raw); } catch {}\n try { return new Function(`return (${raw})`)(); } catch {}\n return raw;\n }\n case \"ast\":\n return <MDXClientContent ast={attr.value} components={components} />;\n default:\n return undefined;\n }\n}\n\nconst HTML_TAGS = new Set([\n \"a\",\"abbr\",\"article\",\"aside\",\"b\",\"blockquote\",\"br\",\"caption\",\"cite\",\"code\",\n \"col\",\"colgroup\",\"dd\",\"del\",\"details\",\"dfn\",\"div\",\"dl\",\"dt\",\"em\",\"figcaption\",\n \"figure\",\"footer\",\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\",\"header\",\"hr\",\"i\",\"img\",\"ins\",\n \"kbd\",\"li\",\"main\",\"mark\",\"nav\",\"ol\",\"p\",\"pre\",\"q\",\"s\",\"section\",\"small\",\"span\",\n \"strong\",\"sub\",\"summary\",\"sup\",\"table\",\"tbody\",\"td\",\"tfoot\",\"th\",\"thead\",\"tr\",\n \"u\",\"ul\",\"var\",\n]);\n\nfunction renderNode(\n node: AstNode,\n index: number,\n components: MDXComponents,\n): ReactNode {\n const key = `${node.node_type}-${index}`;\n\n if (node.node_type === \"text\") return node.content ?? null;\n\n if (node.node_type === \"fragment\") {\n return (\n <React.Fragment key={key}>\n {node.children?.map((c, i) => renderNode(c, i, components))}\n </React.Fragment>\n );\n }\n\n // Math — rendered as semantic spans; KaTeX hydrates them via useEffect\n if (node.node_type === \"InlineMath\") {\n return (\n <span\n key={key}\n className=\"math math-inline\"\n data-math={node.content ?? \"\"}\n suppressHydrationWarning\n />\n );\n }\n if (node.node_type === \"BlockMath\") {\n return (\n <div\n key={key}\n className=\"math math-display\"\n data-math={node.content ?? \"\"}\n suppressHydrationWarning\n />\n );\n }\n\n const resolvedProps: Record<string, any> = {};\n if (node.attributes) {\n for (const [k, v] of Object.entries(node.attributes)) {\n resolvedProps[k] = resolveAttr(v as AttrValueKind, components);\n }\n }\n\n const renderedChildren = node.children?.length\n ? node.children.map((c, i) => renderNode(c, i, components))\n : (node.content ?? undefined);\n\n const Custom = components[node.node_type];\n if (Custom) {\n return (\n <MDXErrorBoundary key={key} componentName={node.node_type}>\n <Custom {...resolvedProps}>\n {renderedChildren}\n </Custom>\n </MDXErrorBoundary>\n );\n }\n\n if (HTML_TAGS.has(node.node_type)) {\n const Tag = node.node_type as any;\n return <Tag key={key} {...resolvedProps}>{renderedChildren}</Tag>;\n }\n\n if (process.env.NODE_ENV === \"development\") {\n console.warn(`[toaq/mdx-engine] Unknown component: <${node.node_type}>`);\n }\n return (\n <div key={key} data-missing-component={node.node_type} className=\"mdx-missing-component\">\n {renderedChildren}\n </div>\n );\n}\n\nfunction MDXClientContent({\n ast,\n components,\n}: {\n ast: AstNode[];\n components: MDXComponents;\n}) {\n return <>{ast.map((node, i) => renderNode(node, i, components))}</>;\n}\n\ninterface MDXClientRendererProps {\n /** AST from parseMdx() — must be JSON-serialisable (pass via Server Component). */\n ast: AstNode[];\n /** Component registry — same shape as MDX_COMPONENTS. */\n components?: MDXComponents;\n /** If true, activates KaTeX auto-render after mount. Default: true. */\n katex?: boolean;\n}\n\nexport function MDXClientRenderer({\n ast,\n components = {},\n katex = true,\n}: MDXClientRendererProps) {\n const rootRef = useRef<HTMLDivElement>(null);\n\n // Hydrate math after mount\n useEffect(() => {\n if (!katex || !rootRef.current) return;\n loadKatex().then((renderMath) => {\n if (!renderMath || !rootRef.current) return;\n renderMath(rootRef.current, {\n delimiters: [\n { left: \"$$\", right: \"$$\", display: true },\n { left: \"$\", right: \"$\", display: false },\n ],\n });\n // Also handle data-math attributes directly\n rootRef.current.querySelectorAll<HTMLElement>(\"[data-math]\").forEach((el) => {\n const math = el.getAttribute(\"data-math\") ?? \"\";\n const display = el.classList.contains(\"math-display\");\n try {\n import(\"katex\").then(({ default: k }) => {\n el.innerHTML = k.renderToString(math, { displayMode: display, throwOnError: false });\n });\n } catch {}\n });\n });\n }, [ast, katex]);\n\n if (!ast || !Array.isArray(ast)) return null;\n\n return (\n <div ref={rootRef} className=\"omni-mdx-root\">\n <MDXClientContent ast={ast} components={components} />\n </div>\n );\n}","\"use client\";\nimport { Component, ErrorInfo, ReactNode } from 'react';\n\ninterface Props {\n children: ReactNode;\n /** The name of the MDX component being rendered (e.g., 'Chart', 'SplitLayout') */\n componentName?: string;\n}\n\ninterface State {\n hasError: boolean;\n error: Error | null;\n}\n\n/**\n * A dedicated Error Boundary for MDX rendering.\n *\n * If a React component injected via MDX crashes (e.g., due to a data parsing error \n * inside a <Chart />), this boundary intercepts the error. This prevents the \n * entire React tree from unmounting and displays a clean fallback UI to \n * isolate the defective component.\n */\nexport class MDXErrorBoundary extends Component<Props, State> {\n constructor(props: Props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n /**\n * Updates the state when an error occurs to trigger the fallback UI rendering.\n */\n static getDerivedStateFromError(error: Error): State {\n return { hasError: true, error };\n }\n\n /**\n * Intercepts the error and its contextual information.\n * This is the ideal place to hook into monitoring tools (like Sentry or Datadog) \n * for production environments.\n */\n componentDidCatch(error: Error, errorInfo: ErrorInfo) {\n console.error(\n `[MDXErrorBoundary] Error caught in component <${this.props.componentName || 'Unknown'}>:\\n`,\n error,\n errorInfo.componentStack\n );\n }\n \n render() {\n if (this.state.hasError) {\n // Fallback UI: A clean, isolated container that doesn't break the main layout\n return (\n <div style={{ padding: '1rem', border: '2px solid #ef4444', backgroundColor: '#fef2f2', borderRadius: '0.5rem', margin: '1rem 0' }}>\n <h3 style={{ color: '#b91c1c', fontWeight: 'bold', margin: 0 }}>\n Render Error : {this.props.componentName || 'Unknown Component'}\n </h3>\n <p style={{ color: '#dc2626', fontFamily: 'monospace', fontSize: '0.875rem' }}>\n {this.state.error?.message}\n </p>\n </div>\n );\n }\n return this.props.children;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,IAAAA,gBAA+E;;;ACjB/E,mBAAgD;AAoDtC;AA/BH,IAAM,mBAAN,cAA+B,uBAAwB;AAAA,EAC5D,YAAY,OAAc;AACxB,UAAM,KAAK;AACX,SAAK,QAAQ,EAAE,UAAU,OAAO,OAAO,KAAK;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,yBAAyB,OAAqB;AACnD,WAAO,EAAE,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