@conloca/mdx 0.1.16 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +50 -16
  2. package/dist/code-block-frame.js +1 -0
  3. package/dist/code-block-frame.js.map +1 -0
  4. package/dist/editor-core.d.ts +0 -2
  5. package/dist/editor-core.d.ts.map +1 -1
  6. package/dist/editor-core.js +50 -6
  7. package/dist/editor-core.js.map +1 -0
  8. package/dist/esm-passthrough.d.ts +36 -0
  9. package/dist/esm-passthrough.d.ts.map +1 -0
  10. package/dist/esm-passthrough.js +237 -0
  11. package/dist/esm-passthrough.js.map +1 -0
  12. package/dist/fragments.d.ts +37 -0
  13. package/dist/fragments.d.ts.map +1 -0
  14. package/dist/fragments.js +53 -0
  15. package/dist/fragments.js.map +1 -0
  16. package/dist/index.d.ts +0 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -0
  20. package/dist/markdown-options.js +1 -0
  21. package/dist/markdown-options.js.map +1 -0
  22. package/dist/mdx/compile-request.d.ts +5 -0
  23. package/dist/mdx/compile-request.d.ts.map +1 -0
  24. package/dist/mdx/compile-request.js +40 -0
  25. package/dist/mdx/compile-request.js.map +1 -0
  26. package/dist/mdx/compile.d.ts.map +1 -1
  27. package/dist/mdx/compile.js +21 -1
  28. package/dist/mdx/compile.js.map +1 -0
  29. package/dist/mdx/evaluate.d.ts +18 -23
  30. package/dist/mdx/evaluate.d.ts.map +1 -1
  31. package/dist/mdx/evaluate.js +103 -29
  32. package/dist/mdx/evaluate.js.map +1 -0
  33. package/dist/mdx/heading-outline.d.ts +46 -0
  34. package/dist/mdx/heading-outline.d.ts.map +1 -0
  35. package/dist/mdx/heading-outline.js +114 -0
  36. package/dist/mdx/heading-outline.js.map +1 -0
  37. package/dist/mdx/restrict-expressions.d.ts +43 -0
  38. package/dist/mdx/restrict-expressions.d.ts.map +1 -0
  39. package/dist/mdx/restrict-expressions.js +160 -0
  40. package/dist/mdx/restrict-expressions.js.map +1 -0
  41. package/dist/mdx-editor.js +1 -0
  42. package/dist/mdx-editor.js.map +1 -0
  43. package/dist/node.d.ts +3 -2
  44. package/dist/node.d.ts.map +1 -1
  45. package/dist/node.js +3 -1
  46. package/dist/node.js.map +1 -0
  47. package/dist/sandbox-frame.d.ts +114 -0
  48. package/dist/sandbox-frame.d.ts.map +1 -0
  49. package/dist/sandbox-frame.js +234 -0
  50. package/dist/sandbox-frame.js.map +1 -0
  51. package/dist/types.d.ts +7 -4
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/types.js +1 -0
  54. package/dist/types.js.map +1 -0
  55. package/package.json +58 -41
  56. package/src/code-block-frame.tsx +262 -0
  57. package/src/editor-core.tsx +403 -0
  58. package/src/editor-styles.css +282 -0
  59. package/src/esm-passthrough.ts +269 -0
  60. package/src/fragments.ts +91 -0
  61. package/src/index.ts +5 -0
  62. package/src/markdown-options.ts +21 -0
  63. package/src/mdx/compile-request.ts +53 -0
  64. package/src/mdx/compile.ts +51 -0
  65. package/src/mdx/evaluate.ts +144 -0
  66. package/src/mdx/heading-outline.ts +153 -0
  67. package/src/mdx/restrict-expressions.ts +173 -0
  68. package/src/mdx-editor.tsx +15 -0
  69. package/src/node.ts +25 -0
  70. package/src/sandbox-frame.ts +277 -0
  71. package/src/types.ts +23 -0
  72. package/dist/blocks.d.ts +0 -37
  73. package/dist/blocks.d.ts.map +0 -1
  74. package/dist/blocks.js +0 -51
  75. package/dist/hooks/useMDXEvaluation.d.ts +0 -28
  76. package/dist/hooks/useMDXEvaluation.d.ts.map +0 -1
  77. package/dist/hooks/useMDXEvaluation.js +0 -117
  78. package/dist/index.d.mts +0 -127
  79. package/dist/index.d.mts.map +0 -1
  80. package/dist/index.mjs +0 -516
  81. package/dist/index.mjs.map +0 -1
  82. package/dist/node.d.mts +0 -102
  83. package/dist/node.d.mts.map +0 -1
  84. package/dist/node.mjs +0 -140
  85. package/dist/node.mjs.map +0 -1
  86. package/dist/style.css +0 -88
@@ -0,0 +1,269 @@
1
+ import type { Root, RootContent } from 'mdast';
2
+ import remarkMdx from 'remark-mdx';
3
+ import remarkParse from 'remark-parse';
4
+ import { unified } from 'unified';
5
+
6
+ /**
7
+ * Verbatim passthrough for MDX ESM statements (`import` / `export`).
8
+ *
9
+ * `@mdxeditor/editor` cannot represent an `mdxjsEsm` node: its shipped
10
+ * `MdastMdxJsEsmVisitor` matches the node and its `visitNode` body is empty, so
11
+ * nothing reaches the Lexical tree. On export the library *rebuilds* an import
12
+ * block from scratch, using only the components it saw referred to in the
13
+ * document (`exportMarkdownFromLexical.js`). Three ways that loses author data,
14
+ * all reproduced against v3.55.0 in `esm-passthrough.test.ts`:
15
+ *
16
+ * 1. A component nested inside another JSX element is registered by name with
17
+ * no import source attached, so its specifier is pruned from the rebuilt
18
+ * line — `import { Tabs, TabItem }` comes back as `import { Tabs }` while
19
+ * `<TabItem>` is still in the document. Astro then fails the site's
20
+ * build with `TabItem is not defined`.
21
+ * 2. `export const …` is dropped outright, taking any `{value}` expression
22
+ * that referenced it down with it.
23
+ * 3. Side-effect imports (`import './styles.css'`) and specifiers that are
24
+ * imported but never referenced are dropped.
25
+ *
26
+ * Even when the rebuild keeps every name it is not byte-faithful: the library
27
+ * emits `import { X } from 'y'` with no trailing semicolon and orders
28
+ * specifiers by first reference, so a no-op save still rewrites the line.
29
+ *
30
+ * The fix keeps ESM out of the editor entirely. `splitEsm` lifts the statements
31
+ * off the markdown before the editor parses it and `joinEsm` puts them back,
32
+ * byte for byte, on the way out. Because the editor never sees an `mdxjsEsm`
33
+ * node, the library's `gatherMetadata` finds no import declarations and its
34
+ * rebuild produces nothing to collide with — except for components registered
35
+ * with an explicit `import.from` (see `MdxJsxComponentDescriptor`), which
36
+ * `joinEsm` reconciles so a binding is never declared twice.
37
+ *
38
+ * This narrows what reaches `compileMDX`, so it cannot weaken the
39
+ * `remarkRestrictExpressions` gate: the editor's live markdown now carries
40
+ * strictly fewer ESM statements than before, never more.
41
+ */
42
+
43
+ /**
44
+ * Cheap pre-filter. A real parse is the only way to tell an ESM statement from
45
+ * an `import` line inside a fenced code block, but the overwhelming majority of
46
+ * documents have no line starting with `import`/`export` at all, and this keeps
47
+ * those off the parser entirely. False positives are harmless — they fall
48
+ * through to the parse, which decides.
49
+ */
50
+ const ESM_HINT = /^(?:import|export)\b/m;
51
+
52
+ const parser = unified().use(remarkParse).use(remarkMdx);
53
+
54
+ type MdxjsEsmNode = Extract<RootContent, { type: 'mdxjsEsm' }>;
55
+
56
+ /** Type guard so `data.estree` narrows without a cast. */
57
+ function isEsmNode(node: RootContent): node is MdxjsEsmNode {
58
+ return node.type === 'mdxjsEsm';
59
+ }
60
+
61
+ /** An ESM statement lifted out of a document, with its bindings resolved. */
62
+ interface EsmStatement {
63
+ /** Statement source text, exactly as authored. */
64
+ readonly text: string;
65
+ /** Names the statement introduces into module scope. */
66
+ readonly bindings: readonly string[];
67
+ /** Module specifier, when this is an `import`. */
68
+ readonly source: string | undefined;
69
+ /** True when the statement binds a default or namespace import. */
70
+ readonly bindsDefault: boolean;
71
+ }
72
+
73
+ /** ESM lifted off a document, ready to be re-attached by {@link joinEsm}. */
74
+ export interface PreservedEsm {
75
+ /**
76
+ * Verbatim text to re-emit ahead of the edited body — the document's leading
77
+ * ESM block including the blank lines around it, so a no-op edit reproduces
78
+ * the original bytes exactly. `''` when the document had no ESM.
79
+ */
80
+ readonly prefix: string;
81
+ /** The markdown to hand the editor: the source with `prefix` removed. */
82
+ readonly body: string;
83
+ /** Every binding name declared by the preserved statements. */
84
+ readonly bindings: ReadonlySet<string>;
85
+ }
86
+
87
+ /**
88
+ * Parse far enough to locate `mdxjsEsm` nodes. Returns `undefined` when the
89
+ * document does not parse — acorn rejects `import type { … }`, for instance,
90
+ * which also makes the editor itself fall back to source view. Bailing out
91
+ * leaves behaviour exactly as it was.
92
+ */
93
+ function parseOrUndefined(source: string): Root | undefined {
94
+ try {
95
+ return parser.parse(source);
96
+ } catch {
97
+ return undefined;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Resolve the bindings an `mdxjsEsm` node introduces, from the estree that
103
+ * `micromark-extension-mdxjs` attaches (it parses with `addResult: true`).
104
+ * A statement whose bindings cannot be resolved contributes none and is simply
105
+ * preserved as opaque text.
106
+ */
107
+ function describeEsm(node: MdxjsEsmNode, text: string): EsmStatement {
108
+ const bindings: string[] = [];
109
+ let source: string | undefined;
110
+ let bindsDefault = false;
111
+
112
+ for (const statement of node.data?.estree?.body ?? []) {
113
+ if (statement.type === 'ImportDeclaration') {
114
+ if (typeof statement.source.value === 'string') source = statement.source.value;
115
+ for (const specifier of statement.specifiers) {
116
+ bindings.push(specifier.local.name);
117
+ if (specifier.type !== 'ImportSpecifier') bindsDefault = true;
118
+ }
119
+ continue;
120
+ }
121
+ if (statement.type === 'ExportNamedDeclaration') {
122
+ const declaration = statement.declaration;
123
+ if (declaration?.type === 'VariableDeclaration') {
124
+ for (const declarator of declaration.declarations) {
125
+ if (declarator.id.type === 'Identifier') bindings.push(declarator.id.name);
126
+ }
127
+ } else if (declaration?.id != null) {
128
+ bindings.push(declaration.id.name);
129
+ }
130
+ for (const specifier of statement.specifiers) {
131
+ if (specifier.exported.type === 'Identifier') bindings.push(specifier.exported.name);
132
+ }
133
+ continue;
134
+ }
135
+ if (statement.type === 'ExportDefaultDeclaration') bindings.push('default');
136
+ }
137
+
138
+ return { text, bindings, source, bindsDefault };
139
+ }
140
+
141
+ /** Number of leading root children that are ESM statements. */
142
+ function countLeadingEsm(children: readonly RootContent[]): number {
143
+ let count = 0;
144
+ for (const node of children) {
145
+ if (!isEsmNode(node)) break;
146
+ count += 1;
147
+ }
148
+ return count;
149
+ }
150
+
151
+ /**
152
+ * Offset where the body proper starts, i.e. the first root child that is not an
153
+ * ESM statement. Equal to `fallback` for an all-ESM document.
154
+ */
155
+ function firstContentOffset(children: readonly RootContent[], leadingCount: number, fallback: number): number {
156
+ const firstContent = leadingCount < children.length ? children[leadingCount] : undefined;
157
+ return firstContent?.position?.start.offset ?? fallback;
158
+ }
159
+
160
+ /**
161
+ * Lift every ESM statement off `source`.
162
+ *
163
+ * The document's leading ESM block is preserved as a literal slice, so
164
+ * re-attaching it reproduces the original bytes. Statements that appear *below*
165
+ * the first content block are hoisted into that same block: their original
166
+ * position is not recoverable once the user has restructured the body, and MDX
167
+ * compiles ESM to module scope regardless of where it sat, so hoisting keeps
168
+ * the site's build working at the cost of moving those lines. Relative
169
+ * order among the statements is preserved.
170
+ */
171
+ export function splitEsm(source: string): PreservedEsm {
172
+ const untouched: PreservedEsm = { prefix: '', body: source, bindings: new Set() };
173
+ if (!ESM_HINT.test(source)) return untouched;
174
+
175
+ const tree = parseOrUndefined(source);
176
+ if (tree === undefined) return untouched;
177
+
178
+ const children = tree.children;
179
+ const leadingCount = countLeadingEsm(children);
180
+ // Everything up to the first non-ESM block: the statements plus the blank
181
+ // lines around them, verbatim. A document that is *only* ESM keeps all of it.
182
+ const leadingText =
183
+ leadingCount === 0 ? '' : source.slice(0, firstContentOffset(children, leadingCount, source.length));
184
+
185
+ const leading: EsmStatement[] = [];
186
+ const hoisted: EsmStatement[] = [];
187
+ const cuts: Array<{ start: number; end: number }> = [];
188
+
189
+ for (const [index, node] of children.entries()) {
190
+ if (!isEsmNode(node)) continue;
191
+ const start = node.position?.start.offset;
192
+ const end = node.position?.end.offset;
193
+ // Positions are always present from a string parse; without them the text
194
+ // cannot be recovered, so leave the document alone rather than guess.
195
+ if (start === undefined || end === undefined) return untouched;
196
+ const statement = describeEsm(node, source.slice(start, end));
197
+ if (index < leadingCount) {
198
+ leading.push(statement);
199
+ } else {
200
+ hoisted.push(statement);
201
+ cuts.push({ start, end });
202
+ }
203
+ }
204
+
205
+ if (leading.length === 0 && hoisted.length === 0) return untouched;
206
+
207
+ // Cut hoisted statements out of the body back-to-front so earlier offsets stay
208
+ // valid. Blank lines left behind are irrelevant: the editor re-serializes the
209
+ // body regardless.
210
+ let body = source.slice(leadingText.length);
211
+ for (const cut of [...cuts].reverse()) {
212
+ body = body.slice(0, cut.start - leadingText.length) + body.slice(cut.end - leadingText.length);
213
+ }
214
+
215
+ return {
216
+ prefix: hoisted.length === 0 ? leadingText : `${leadingText}${hoisted.map((s) => s.text).join('\n')}\n\n`,
217
+ body,
218
+ bindings: new Set([...leading, ...hoisted].flatMap((s) => s.bindings)),
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Re-attach preserved ESM to markdown coming out of the editor.
224
+ *
225
+ * Any import the library rebuilt for a descriptor carrying `import.from` is
226
+ * reconciled against the preserved bindings first, so nothing is declared
227
+ * twice: a rebuilt statement whose every binding is already preserved is
228
+ * dropped, and one that also carries a new binding is narrowed to just the new
229
+ * names. The author's own statements are never rewritten.
230
+ */
231
+ export function joinEsm(preserved: PreservedEsm, body: string): string {
232
+ if (preserved.prefix === '') return body;
233
+ if (!ESM_HINT.test(body)) return preserved.prefix + body;
234
+
235
+ const tree = parseOrUndefined(body);
236
+ if (tree === undefined) return preserved.prefix + body;
237
+
238
+ const children = tree.children;
239
+ const leadingCount = countLeadingEsm(children);
240
+ if (leadingCount === 0) return preserved.prefix + body;
241
+
242
+ const kept: string[] = [];
243
+ for (const node of children.slice(0, leadingCount)) {
244
+ if (!isEsmNode(node)) continue;
245
+ const start = node.position?.start.offset;
246
+ const end = node.position?.end.offset;
247
+ if (start === undefined || end === undefined) continue;
248
+
249
+ const statement = describeEsm(node, body.slice(start, end));
250
+ const fresh = statement.bindings.filter((name) => !preserved.bindings.has(name));
251
+ if (statement.bindings.length === 0 || fresh.length === statement.bindings.length) {
252
+ kept.push(statement.text);
253
+ continue;
254
+ }
255
+ if (fresh.length === 0) continue;
256
+ // Partially covered. Only a rebuilt named import can land here, and it was
257
+ // generated by the library rather than authored, so narrowing it to the new
258
+ // names loses nothing the author wrote.
259
+ if (statement.source === undefined || statement.bindsDefault) {
260
+ kept.push(statement.text);
261
+ continue;
262
+ }
263
+ kept.push(`import { ${fresh.join(', ')} } from '${statement.source}'`);
264
+ }
265
+
266
+ // An all-ESM body leaves nothing after the statements.
267
+ const rest = body.slice(firstContentOffset(children, leadingCount, body.length));
268
+ return preserved.prefix + (kept.length === 0 ? rest : `${kept.join('\n')}\n\n${rest}`);
269
+ }
@@ -0,0 +1,91 @@
1
+ import { evaluateMDXToComponent } from './mdx/evaluate.js';
2
+ import type { MDXFragmentEvaluationResult } from './types.js';
3
+
4
+ interface FragmentLocaleSummary {
5
+ meta?: {
6
+ title?: string;
7
+ };
8
+ name?: string;
9
+ }
10
+
11
+ interface FragmentManifest {
12
+ id: string;
13
+ locales: Record<string, FragmentLocaleSummary | undefined>;
14
+ }
15
+
16
+ interface FragmentLocalizedEntry {
17
+ localized?: {
18
+ meta?: {
19
+ title?: string;
20
+ };
21
+ name?: string;
22
+ content?: {
23
+ mdx?: string;
24
+ };
25
+ };
26
+ }
27
+
28
+ interface FragmentAPI {
29
+ listAllContent(filters: { kind: 'fragment' }): Iterable<FragmentManifest>;
30
+ getLocalized(id: string, locale: string): Promise<FragmentLocalizedEntry | null>;
31
+ }
32
+
33
+ /**
34
+ * Evaluate all MDX fragments from a compatible content API.
35
+ *
36
+ * Returns structured success/error results so callers can decide how to
37
+ * surface broken fragments instead of hardcoding fallback UI in this package.
38
+ */
39
+ export async function evaluateMDXFragments(api: FragmentAPI, locale: string): Promise<MDXFragmentEvaluationResult[]> {
40
+ const fragments = Array.from(api.listAllContent({ kind: 'fragment' }));
41
+
42
+ return Promise.all(
43
+ fragments.map(async (fragment) => {
44
+ const locales = Object.keys(fragment.locales);
45
+ const firstLocale = locales.length > 0 ? fragment.locales[locales[0]] : null;
46
+ const manifestTitle = firstLocale?.meta?.title || firstLocale?.name || fragment.id;
47
+
48
+ try {
49
+ const fragmentLocalized = await api.getLocalized(fragment.id, locale);
50
+ const fragmentTitle =
51
+ fragmentLocalized?.localized?.meta?.title || fragmentLocalized?.localized?.name || manifestTitle;
52
+ const mdxContent = fragmentLocalized?.localized?.content?.mdx;
53
+
54
+ if (!mdxContent) {
55
+ return {
56
+ ok: false,
57
+ id: fragment.id,
58
+ title: fragmentTitle,
59
+ error: new Error(`No MDX content found for fragment: ${fragment.id}`),
60
+ };
61
+ }
62
+
63
+ const { Component: EvaluatedComponent, error, outline } = await evaluateMDXToComponent(mdxContent);
64
+
65
+ if (error || !EvaluatedComponent) {
66
+ return {
67
+ ok: false,
68
+ id: fragment.id,
69
+ title: fragmentTitle,
70
+ error: error || new Error(`MDX evaluation failed for fragment: ${fragment.id}`),
71
+ };
72
+ }
73
+
74
+ return {
75
+ ok: true,
76
+ id: fragment.id,
77
+ title: fragmentTitle,
78
+ Component: EvaluatedComponent,
79
+ outline,
80
+ };
81
+ } catch (error) {
82
+ return {
83
+ ok: false,
84
+ id: fragment.id,
85
+ title: manifestTitle,
86
+ error: error instanceof Error ? error : new Error(`Failed to evaluate fragment: ${fragment.id}`),
87
+ };
88
+ }
89
+ }),
90
+ );
91
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type { MDXEditorMethods } from '@mdxeditor/editor';
2
+ export { codeBlockWrapperInfo$ } from './code-block-frame.js';
3
+ export type { BaseMDXEditorProps } from './editor-core.js';
4
+ export { BaseMDXEditor } from './editor-core.js';
5
+ export * from './mdx-editor.js';
@@ -0,0 +1,21 @@
1
+ import type { Options as ToMarkdownOptions } from 'mdast-util-to-markdown';
2
+
3
+ // MDXEditor rebuilds the markdown body from its Lexical AST on every change
4
+ // via `mdast-util-to-markdown`. Without explicit options, the library defaults
5
+ // flip canonical project style: thematic breaks render as `***` instead of
6
+ // `---`, bullets pick `*` over `-`, and emphasis ambiguity inside GFM table
7
+ // cells inserts backslash escapes on every save. Pinning these to match the
8
+ // committed fixtures keeps no-op round-trips diff-clean.
9
+ //
10
+ // Exported as a plain TS module (no React deps) so it can be exercised
11
+ // directly from tests against `mdast-util-to-markdown` without mounting the
12
+ // editor.
13
+ export const TO_MARKDOWN_OPTIONS: ToMarkdownOptions = {
14
+ bullet: '-',
15
+ rule: '-',
16
+ emphasis: '_',
17
+ strong: '*',
18
+ fence: '`',
19
+ listItemIndent: 'one',
20
+ tightDefinitions: true,
21
+ };
@@ -0,0 +1,53 @@
1
+ import { ErrorCodes } from '@conloca/content-api';
2
+ import { compileMDX } from './compile.js';
3
+
4
+ /** Answers a compile request with the whole compile result, the one implementation every host mounts. */
5
+ export async function handleMDXCompileRequest(
6
+ request: Request,
7
+ options: { maxChars?: number } = {},
8
+ ): Promise<Response> {
9
+ let body: unknown;
10
+ try {
11
+ body = await request.json();
12
+ } catch {
13
+ return Response.json(
14
+ { error: { code: ErrorCodes.INVALID_REQUEST, message: 'Invalid JSON body' } },
15
+ { status: 400 },
16
+ );
17
+ }
18
+
19
+ const mdxContent = typeof body === 'object' && body !== null && 'mdxContent' in body ? body.mdxContent : null;
20
+ if (!mdxContent || typeof mdxContent !== 'string') {
21
+ return Response.json(
22
+ {
23
+ error: {
24
+ code: ErrorCodes.MISSING_REQUIRED_FIELD,
25
+ message: 'mdxContent string required',
26
+ details: { field: 'mdxContent' },
27
+ },
28
+ },
29
+ { status: 400 },
30
+ );
31
+ }
32
+
33
+ const { maxChars } = options;
34
+ if (maxChars !== undefined && mdxContent.length > maxChars) {
35
+ return Response.json(
36
+ {
37
+ error: {
38
+ code: ErrorCodes.INVALID_REQUEST,
39
+ message: `mdxContent exceeds size limit (${mdxContent.length} > ${maxChars} characters)`,
40
+ },
41
+ },
42
+ { status: 413 },
43
+ );
44
+ }
45
+
46
+ try {
47
+ return Response.json(await compileMDX(mdxContent));
48
+ } catch (error) {
49
+ const message = error instanceof Error ? error.message : 'Failed to compile MDX';
50
+ console.error(`[CMS] ${new URL(request.url).pathname} failed:`, error);
51
+ return Response.json({ error: { code: ErrorCodes.MDX_COMPILE_FAILED, message } }, { status: 422 });
52
+ }
53
+ }
@@ -0,0 +1,51 @@
1
+ import { compile as mdxCompile } from '@mdx-js/mdx';
2
+ import matter from 'gray-matter';
3
+ import remarkFrontmatter from 'remark-frontmatter';
4
+ import remarkGfm from 'remark-gfm';
5
+ import remarkMdxFrontmatter from 'remark-mdx-frontmatter';
6
+ import type { MDXCompileResult } from '../types.js';
7
+ import { applyHeadingIds, type FragmentHeading, type OutlineTree } from './heading-outline.js';
8
+ import { remarkRestrictExpressions } from './restrict-expressions.js';
9
+
10
+ export async function compileMDX(content: string): Promise<MDXCompileResult> {
11
+ try {
12
+ // Empty options opt out of gray-matter's module-level memo cache — a plain
13
+ // object keyed by the raw input, so inputs naming an Object.prototype
14
+ // member ('valueOf', 'toString', …) return the inherited member instead of
15
+ // a parse.
16
+ const { data: metadata } = matter(content, {});
17
+
18
+ // The editing surfaces read their outline off this compile rather than off
19
+ // the rendered frame, which they cannot see into: the fragment body renders
20
+ // in a sandbox with no same-origin access.
21
+ let outline: readonly FragmentHeading[] = [];
22
+ const collectOutline = () => (tree: OutlineTree) => {
23
+ outline = applyHeadingIds(tree);
24
+ };
25
+
26
+ const compiled = await mdxCompile(content, {
27
+ outputFormat: 'function-body',
28
+ development: process.env.NODE_ENV === 'development',
29
+ // `remarkRestrictExpressions` runs BEFORE `remarkMdxFrontmatter`: author
30
+ // `import`/`export` parse into `mdxjsEsm` nodes at parse time (so restrict
31
+ // sees and rejects them), while the legitimate `export const frontmatter`
32
+ // that `remarkMdxFrontmatter` injects appears only after restrict has run.
33
+ remarkPlugins: [remarkFrontmatter, remarkRestrictExpressions, remarkMdxFrontmatter, remarkGfm],
34
+ rehypePlugins: [collectOutline],
35
+ });
36
+
37
+ return {
38
+ code: String(compiled.value),
39
+ metadata: metadata,
40
+ outline,
41
+ };
42
+ } catch (error) {
43
+ if (error instanceof Error) {
44
+ const enhancedError = new Error(`MDX compilation failed: ${error.message}`);
45
+ enhancedError.stack = error.stack;
46
+ throw enhancedError;
47
+ }
48
+
49
+ throw error;
50
+ }
51
+ }
@@ -0,0 +1,144 @@
1
+ import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
2
+ import type { Root } from 'mdast';
3
+ import type { ComponentType } from 'react';
4
+ import { Fragment, jsx, jsxs } from 'react/jsx-runtime';
5
+ import remarkFrontmatter from 'remark-frontmatter';
6
+ import remarkGfm from 'remark-gfm';
7
+ import remarkMdx from 'remark-mdx';
8
+ import remarkParse from 'remark-parse';
9
+ import remarkRehype from 'remark-rehype';
10
+ import { type Plugin, unified } from 'unified';
11
+ import { applyHeadingIds, type FragmentHeading } from './heading-outline.js';
12
+ import { remarkRestrictExpressions } from './restrict-expressions.js';
13
+
14
+ interface JsxAttributeNode {
15
+ type?: string;
16
+ name?: string;
17
+ value?: unknown;
18
+ }
19
+
20
+ interface TreeNode {
21
+ type?: string;
22
+ children?: TreeNode[];
23
+ attributes?: JsxAttributeNode[];
24
+ [key: string]: unknown;
25
+ }
26
+
27
+ /**
28
+ * Make every JSX element in the tree statically renderable.
29
+ *
30
+ * Capitalized component names are rejected with a clear author-facing error —
31
+ * this path has no component registry to resolve them from, and letting them
32
+ * through surfaces as a cryptic converter error instead.
33
+ *
34
+ * JSON-literal `{…}` attribute values (the only expressions
35
+ * `remarkRestrictExpressions` admits) are resolved into plain static values,
36
+ * so rendering never needs an expression evaluator: strings pass through,
37
+ * numbers stringify (identical SSR output), `{true}` becomes the JSX boolean
38
+ * shorthand, and `{false}`/`null`/object literals drop the attribute. Object
39
+ * props only ever carried data for components, which this static path does not
40
+ * render, so dropping them loses nothing.
41
+ */
42
+ function resolveStaticJsx() {
43
+ return (tree: TreeNode): void => {
44
+ const walk = (node: TreeNode): void => {
45
+ if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {
46
+ const name = typeof node.name === 'string' ? node.name : '';
47
+ if (/^[A-Z]/.test(name)) {
48
+ throw new Error(
49
+ `Unknown component <${name}>: fragments render as plain content and cannot use React components.`,
50
+ );
51
+ }
52
+ }
53
+ if (Array.isArray(node.attributes)) {
54
+ node.attributes = node.attributes.flatMap((attr) => {
55
+ const value = attr?.value;
56
+ if (!value || typeof value !== 'object') return [attr];
57
+ const raw = (value as { value?: unknown }).value;
58
+ if (typeof raw !== 'string') return [];
59
+ let parsed: unknown;
60
+ try {
61
+ parsed = JSON.parse(raw.trim());
62
+ } catch {
63
+ return []; // non-literal — already dropped by the restrict gate; belt and braces
64
+ }
65
+ if (typeof parsed === 'string') return [{ ...attr, value: parsed }];
66
+ if (typeof parsed === 'number') return [{ ...attr, value: String(parsed) }];
67
+ if (parsed === true) return [{ ...attr, value: null }];
68
+ return [];
69
+ });
70
+ }
71
+ if (Array.isArray(node.children)) node.children.forEach(walk);
72
+ };
73
+ walk(tree);
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Markdown → mdast (with MDX JSX syntax) → hast, with the JSX element nodes
79
+ * passed through for `toJsxRuntime` to turn into React elements directly.
80
+ */
81
+ const processor = unified()
82
+ .use(remarkParse)
83
+ .use(remarkMdx)
84
+ .use(remarkFrontmatter)
85
+ .use(remarkGfm)
86
+ // Both transformers use loose structural node types (they predate this
87
+ // pipeline and also run inside @mdx-js's own plugin list), so bridge them to
88
+ // unified's strict Plugin shape here rather than forking their signatures.
89
+ .use(remarkRestrictExpressions as unknown as Plugin<[], Root>)
90
+ .use(resolveStaticJsx as unknown as Plugin<[], Root>)
91
+ .use(remarkRehype, { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'] });
92
+
93
+ /**
94
+ * Turn an MDX content string into a React component WITHOUT executing any
95
+ * compiled code.
96
+ *
97
+ * This is the published-site render path for CMS fragments, and it must run
98
+ * where creating code from strings is forbidden, such as Cloudflare Workers —
99
+ * `@mdx-js/mdx`'s `evaluate()` (a `new Function` under the hood) throws
100
+ * `EvalError: Code generation from strings disallowed` there. So instead of
101
+ * compile-and-execute, this parses the MDX to a syntax tree and converts the
102
+ * tree straight to React elements (`hast-util-to-jsx-runtime`). That is
103
+ * sufficient by construction: `remarkRestrictExpressions` already rejects
104
+ * `{…}` expressions and top-level `import`/`export`, and only JSON-literal
105
+ * attribute values survive — nothing in admissible content needs code
106
+ * execution to render.
107
+ *
108
+ * Unregistered capitalized JSX components fail here (evaluate time) rather
109
+ * than when React renders the component, so callers get the error result and
110
+ * can show their fragment-error UI instead of failing the whole page render.
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
115
+ *
116
+ * const { Component, error } = await evaluateMDXToComponent('# Hello\n\nThis is **MDX**');
117
+ * if (error) {
118
+ * console.error('Failed to evaluate:', error);
119
+ * } else if (Component) {
120
+ * // Render <Component /> in your React app
121
+ * }
122
+ * ```
123
+ */
124
+ export async function evaluateMDXToComponent(
125
+ mdxContent: string,
126
+ ): Promise<{ Component: ComponentType | null; error?: Error; outline: readonly FragmentHeading[] }> {
127
+ try {
128
+ const mdast = processor.parse(mdxContent);
129
+ const hast = await processor.run(mdast);
130
+ // Before the tree becomes React: assigning the ids and reading the outline
131
+ // in one pass is what keeps a contents link and its heading in agreement.
132
+ const outline = applyHeadingIds(hast);
133
+ // Convert eagerly so bad content (e.g. an unknown component) surfaces as
134
+ // the error result; the returned component just replays the static tree.
135
+ const element = toJsxRuntime(hast, { Fragment, jsx, jsxs });
136
+ return { Component: () => element, outline };
137
+ } catch (error) {
138
+ return {
139
+ Component: null,
140
+ error: error instanceof Error ? error : new Error('MDX evaluation failed'),
141
+ outline: [],
142
+ };
143
+ }
144
+ }