@conloca/mdx 0.1.15 → 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 +62 -18
  2. package/dist/code-block-frame.d.ts +41 -0
  3. package/dist/code-block-frame.d.ts.map +1 -0
  4. package/dist/code-block-frame.js +187 -0
  5. package/dist/code-block-frame.js.map +1 -0
  6. package/dist/editor-core.d.ts +56 -0
  7. package/dist/editor-core.d.ts.map +1 -0
  8. package/dist/editor-core.js +225 -0
  9. package/dist/editor-core.js.map +1 -0
  10. package/dist/esm-passthrough.d.ts +36 -0
  11. package/dist/esm-passthrough.d.ts.map +1 -0
  12. package/dist/esm-passthrough.js +237 -0
  13. package/dist/esm-passthrough.js.map +1 -0
  14. package/dist/fragments.d.ts +37 -0
  15. package/dist/fragments.d.ts.map +1 -0
  16. package/dist/fragments.js +53 -0
  17. package/dist/fragments.js.map +1 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +4 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/markdown-options.d.ts +3 -0
  23. package/dist/markdown-options.d.ts.map +1 -0
  24. package/dist/markdown-options.js +20 -0
  25. package/dist/markdown-options.js.map +1 -0
  26. package/dist/mdx/compile-request.d.ts +5 -0
  27. package/dist/mdx/compile-request.d.ts.map +1 -0
  28. package/dist/mdx/compile-request.js +40 -0
  29. package/dist/mdx/compile-request.js.map +1 -0
  30. package/dist/mdx/compile.d.ts +3 -0
  31. package/dist/mdx/compile.d.ts.map +1 -0
  32. package/dist/mdx/compile.js +47 -0
  33. package/dist/mdx/compile.js.map +1 -0
  34. package/dist/mdx/evaluate.d.ts +39 -0
  35. package/dist/mdx/evaluate.d.ts.map +1 -0
  36. package/dist/mdx/evaluate.js +131 -0
  37. package/dist/mdx/evaluate.js.map +1 -0
  38. package/dist/mdx/heading-outline.d.ts +46 -0
  39. package/dist/mdx/heading-outline.d.ts.map +1 -0
  40. package/dist/mdx/heading-outline.js +114 -0
  41. package/dist/mdx/heading-outline.js.map +1 -0
  42. package/dist/mdx/restrict-expressions.d.ts +43 -0
  43. package/dist/mdx/restrict-expressions.d.ts.map +1 -0
  44. package/dist/mdx/restrict-expressions.js +160 -0
  45. package/dist/mdx/restrict-expressions.js.map +1 -0
  46. package/dist/mdx-editor.d.ts +7 -0
  47. package/dist/mdx-editor.d.ts.map +1 -0
  48. package/dist/mdx-editor.js +8 -0
  49. package/dist/mdx-editor.js.map +1 -0
  50. package/dist/node.d.ts +18 -0
  51. package/dist/node.d.ts.map +1 -0
  52. package/dist/node.js +18 -0
  53. package/dist/node.js.map +1 -0
  54. package/dist/sandbox-frame.d.ts +114 -0
  55. package/dist/sandbox-frame.d.ts.map +1 -0
  56. package/dist/sandbox-frame.js +234 -0
  57. package/dist/sandbox-frame.js.map +1 -0
  58. package/dist/types.d.ts +19 -0
  59. package/dist/types.d.ts.map +1 -0
  60. package/dist/types.js +2 -0
  61. package/dist/types.js.map +1 -0
  62. package/package.json +82 -26
  63. package/src/code-block-frame.tsx +262 -0
  64. package/src/editor-core.tsx +403 -0
  65. package/src/editor-styles.css +282 -0
  66. package/src/esm-passthrough.ts +269 -0
  67. package/src/fragments.ts +91 -0
  68. package/src/index.ts +5 -0
  69. package/src/markdown-options.ts +21 -0
  70. package/src/mdx/compile-request.ts +53 -0
  71. package/src/mdx/compile.ts +51 -0
  72. package/src/mdx/evaluate.ts +144 -0
  73. package/src/mdx/heading-outline.ts +153 -0
  74. package/src/mdx/restrict-expressions.ts +173 -0
  75. package/src/mdx-editor.tsx +15 -0
  76. package/src/node.ts +25 -0
  77. package/src/sandbox-frame.ts +277 -0
  78. package/src/types.ts +23 -0
  79. package/dist/index.d.mts +0 -96
  80. package/dist/index.d.mts.map +0 -1
  81. package/dist/index.mjs +0 -425
  82. package/dist/index.mjs.map +0 -1
  83. package/dist/node.d.mts +0 -107
  84. package/dist/node.d.mts.map +0 -1
  85. package/dist/node.mjs +0 -125
  86. package/dist/node.mjs.map +0 -1
@@ -0,0 +1,153 @@
1
+ import type { MDXHeading } from '@conloca/content-api';
2
+ import GithubSlugger, { slug } from 'github-slugger';
3
+
4
+ /**
5
+ * One heading of a fragment: the anchor target and the contents entry. Aliased
6
+ * from the compile response's own type rather than restated, so the shape the
7
+ * editor receives over HTTP and the shape this pass produces cannot drift.
8
+ */
9
+ export type FragmentHeading = MDXHeading;
10
+
11
+ /**
12
+ * A heading node in either shape this pipeline produces: a plain hast element,
13
+ * or the mdxJsx node `remarkRehype`'s `passThrough` list preserves for a
14
+ * heading the author wrote as literal JSX.
15
+ */
16
+ type OutlineScalar = string | number | boolean | null | undefined;
17
+
18
+ interface OutlineAttribute {
19
+ type?: string;
20
+ name?: string | null;
21
+ value?: string | null | object;
22
+ }
23
+
24
+ interface OutlineProperties {
25
+ id?: OutlineScalar | readonly OutlineScalar[];
26
+ }
27
+
28
+ export interface OutlineTree {
29
+ type: string;
30
+ children?: OutlineTree[];
31
+ value?: string;
32
+ tagName?: string;
33
+ name?: string | null;
34
+ properties?: OutlineProperties;
35
+ attributes?: OutlineAttribute[];
36
+ }
37
+
38
+ interface HeadingNode {
39
+ node: OutlineTree;
40
+ depth: number;
41
+ jsx: boolean;
42
+ }
43
+
44
+ const HEADING_NAME = /^h([1-6])$/;
45
+
46
+ function headingOf(node: OutlineTree): HeadingNode | null {
47
+ const type = node.type;
48
+ const name = type === 'element' ? node.tagName : node.name;
49
+ if (typeof name !== 'string') return null;
50
+ const match = HEADING_NAME.exec(name);
51
+ if (!match) return null;
52
+ if (type !== 'element' && type !== 'mdxJsxFlowElement' && type !== 'mdxJsxTextElement') return null;
53
+ return { node, depth: Number(match[1]), jsx: type !== 'element' };
54
+ }
55
+
56
+ function walk(node: OutlineTree, visit: (node: OutlineTree) => void): void {
57
+ visit(node);
58
+ const children = node.children;
59
+ if (Array.isArray(children)) {
60
+ for (const child of children) walk(child, visit);
61
+ }
62
+ }
63
+
64
+ /** Visible text of a heading, with `**bold**`, `` `code` `` and the like flattened away. */
65
+ function textOf(node: OutlineTree): string {
66
+ let text = '';
67
+ walk(node, (child) => {
68
+ if (child.type === 'text' && typeof child.value === 'string') text += child.value;
69
+ });
70
+ return text.trim().replace(/\s+/g, ' ');
71
+ }
72
+
73
+ function existingIdOf(heading: HeadingNode): string | undefined {
74
+ if (!heading.jsx) {
75
+ const id = heading.node.properties?.id;
76
+ if (typeof id === 'string' && id !== '') return id;
77
+ return undefined;
78
+ }
79
+ const attributes = heading.node.attributes;
80
+ if (!Array.isArray(attributes)) return undefined;
81
+ for (const attribute of attributes) {
82
+ if (attribute.name === 'id' && typeof attribute.value === 'string' && attribute.value !== '') {
83
+ return attribute.value;
84
+ }
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ function setIdOf(heading: HeadingNode, id: string): void {
90
+ if (!heading.jsx) {
91
+ const properties: OutlineProperties = heading.node.properties ?? {};
92
+ properties.id = id;
93
+ heading.node.properties = properties;
94
+ return;
95
+ }
96
+ const attributes = Array.isArray(heading.node.attributes) ? heading.node.attributes : [];
97
+ attributes.push({ type: 'mdxJsxAttribute', name: 'id', value: id });
98
+ heading.node.attributes = attributes;
99
+ }
100
+
101
+ /**
102
+ * GitHub's heading-id rules, the ones Astro gives Markdown headings too, so a
103
+ * heading in any script keeps a readable id that does not depend on its
104
+ * position. `section` stands in for a heading that slugs to nothing ('!!!'),
105
+ * because an empty id renders a contents link as a bare `#`; it goes through
106
+ * the slugger like any other text, so a second one becomes `section-1`, not
107
+ * `-1`. Author ids live in their own set because the slugger can only record
108
+ * the slug of a value, never reserve an exact id.
109
+ */
110
+ function idFor(text: string, slugger: GithubSlugger, reserved: ReadonlySet<string>): string {
111
+ const base = slug(text) || 'section';
112
+ let id = slugger.slug(base);
113
+ while (reserved.has(id)) id = slugger.slug(base);
114
+ return id;
115
+ }
116
+
117
+ /**
118
+ * Give every heading in the tree an id and report them in document order.
119
+ *
120
+ * Both pipelines call this: the published render (`evaluate.ts`) and the
121
+ * compile every editing surface goes through (`compile.ts`). One pass assigns
122
+ * the id and records it, so the anchor in the markup and the anchor in the
123
+ * outline cannot disagree — which is the whole reason the outline is produced
124
+ * here rather than read back off rendered HTML.
125
+ *
126
+ * `unknown` rather than a hast `Root`: this package does not depend on
127
+ * `@types/hast`, and the walk is structural anyway — it reads `type`, `name`,
128
+ * `tagName` and `children`, and ignores anything that does not carry them.
129
+ */
130
+ export function applyHeadingIds(tree: OutlineTree): FragmentHeading[] {
131
+ const headings: HeadingNode[] = [];
132
+ walk(tree, (node) => {
133
+ const heading = headingOf(node);
134
+ if (heading) headings.push(heading);
135
+ });
136
+
137
+ // Author-chosen ids are reserved before any are generated, so a generated
138
+ // slug never silently takes an id the author already spelled out further down.
139
+ const reserved = new Set<string>();
140
+ for (const heading of headings) {
141
+ const existing = existingIdOf(heading);
142
+ if (existing !== undefined) reserved.add(existing);
143
+ }
144
+ const slugger = new GithubSlugger();
145
+
146
+ return headings.map((heading) => {
147
+ const text = textOf(heading.node);
148
+ const existing = existingIdOf(heading);
149
+ const id = existing ?? idFor(text, slugger, reserved);
150
+ if (existing === undefined) setIdOf(heading, id);
151
+ return { depth: heading.depth, id, text };
152
+ });
153
+ }
@@ -0,0 +1,173 @@
1
+ interface MdastNode {
2
+ type?: string;
3
+ children?: MdastNode[];
4
+ attributes?: MdastAttribute[];
5
+ [key: string]: unknown;
6
+ }
7
+
8
+ interface MdastAttribute {
9
+ type?: string;
10
+ name?: string;
11
+ value?: unknown;
12
+ }
13
+
14
+ /** A JSON-literal attribute expression (`{3}`, `{true}`, `{"x"}`) is a static
15
+ * value with no executable content — the editor's prop serializers already
16
+ * treat these as data. Anything that doesn't `JSON.parse` is author-controlled
17
+ * code and is dropped. */
18
+ function isLiteralExpression(value: unknown): boolean {
19
+ if (!value || typeof value !== 'object') return true;
20
+ const raw = (value as { value?: unknown }).value;
21
+ if (typeof raw !== 'string') return true;
22
+ try {
23
+ JSON.parse(raw.trim());
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ /** URL-bearing attributes the browser fetches or navigates to. React neutralizes
31
+ * `javascript:` itself but NOT `data:text/html`, so these are scheme-filtered
32
+ * here regardless of who renders the tree. */
33
+ const URL_ATTR = /^(?:href|src|xlink:href|formaction|action|poster|background|cite)$/i;
34
+
35
+ /** Script-bearing URL schemes. Mirrors the mdast serializer's list so the
36
+ * compile gate and the raw-HTML serializer neutralize the same schemes. */
37
+ const DANGEROUS_URL_SCHEME = /^(?:javascript|vbscript):|^data:text\/html/i;
38
+
39
+ /** Intrinsic HTML elements that execute script, navigate, or embed regardless of
40
+ * their attributes. React renders author-written `<script>` verbatim, so these
41
+ * are never neutralized downstream and must be dropped here. Capitalized JSX
42
+ * (registered components) is never matched — only lowercase raw-HTML tags. */
43
+ const DANGEROUS_ELEMENTS = new Set([
44
+ 'script',
45
+ 'style',
46
+ 'iframe',
47
+ 'object',
48
+ 'embed',
49
+ 'link',
50
+ 'meta',
51
+ 'base',
52
+ 'frame',
53
+ 'frameset',
54
+ 'applet',
55
+ ]);
56
+
57
+ function hasDangerousScheme(value: string): boolean {
58
+ return DANGEROUS_URL_SCHEME.test(value.replace(/[\p{Cc} ]+/gu, ''));
59
+ }
60
+
61
+ function isDangerousElement(node: MdastNode): boolean {
62
+ if (node?.type !== 'mdxJsxFlowElement' && node?.type !== 'mdxJsxTextElement') return false;
63
+ const name = typeof node.name === 'string' ? node.name : '';
64
+ return /^[a-z]/.test(name) && DANGEROUS_ELEMENTS.has(name.toLowerCase());
65
+ }
66
+
67
+ /** A JSON-literal expression whose parsed value is a dangerous-scheme URL string
68
+ * (`href={"data:text/html,…"}` round-trips through `JSON.parse` yet navigates). */
69
+ function isDangerousLiteralUrl(value: unknown): boolean {
70
+ const raw = (value as { value?: unknown })?.value;
71
+ if (typeof raw !== 'string') return false;
72
+ try {
73
+ const parsed = JSON.parse(raw.trim());
74
+ return typeof parsed === 'string' && hasDangerousScheme(parsed);
75
+ } catch {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ /** Filter/neutralize a JSX element's attributes: drop the `dangerouslySetInnerHTML`
81
+ * raw-HTML sink and inline `on*` handlers, drop non-literal expression props, and
82
+ * empty a URL-bearing attribute carrying a dangerous scheme. */
83
+ function sanitizeAttributes(attributes: MdastAttribute[]): MdastAttribute[] {
84
+ const out: MdastAttribute[] = [];
85
+ for (const attr of attributes) {
86
+ if (attr?.type === 'mdxJsxExpressionAttribute') continue; // `{...spread}` — arbitrary props
87
+ if (attr?.type !== 'mdxJsxAttribute' || typeof attr.name !== 'string') {
88
+ out.push(attr);
89
+ continue;
90
+ }
91
+ const name = attr.name;
92
+ // React's only raw-HTML escape hatch. A JSON-literal object
93
+ // (`{"__html": "<script>…"}`) passes the literal exemption yet injects live
94
+ // HTML on the published path, so drop it regardless of value shape.
95
+ if (name.toLowerCase() === 'dangerouslysetinnerhtml') continue;
96
+ // Inline event handlers are never content. React strips string handlers, but
97
+ // dropping them here keeps the gate renderer-agnostic.
98
+ if (/^on/i.test(name)) continue;
99
+ const value = attr.value;
100
+ if (value && typeof value === 'object') {
101
+ if (!isLiteralExpression(value)) continue; // non-literal expression prop
102
+ if (URL_ATTR.test(name) && isDangerousLiteralUrl(value)) {
103
+ out.push({ ...attr, value: '' });
104
+ continue;
105
+ }
106
+ out.push(attr);
107
+ continue;
108
+ }
109
+ if (typeof value === 'string' && URL_ATTR.test(name) && hasDangerousScheme(value)) {
110
+ out.push({ ...attr, value: '' });
111
+ continue;
112
+ }
113
+ out.push(attr);
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /** Remark transform that neutralizes the author-code AND HTML-injection vectors
119
+ * in authored MDX at every compile/eval entry point.
120
+ *
121
+ * Two layers, because expression-restriction is NOT HTML sanitization:
122
+ * 1. Author code — standalone `{…}` flow/text expressions (`mdxFlowExpression`/
123
+ * `mdxTextExpression`) and top-level ESM `import`/`export` (`mdxjsEsm`) reach
124
+ * `new AsyncFunction`/`evaluate()` as live code, so they fail the compile
125
+ * with a clear error; content fragments never legitimately need either.
126
+ * 2. HTML injection — `dangerouslySetInnerHTML` (React's raw-HTML escape hatch,
127
+ * which a JSON-literal object slips past the expression exemption), inline
128
+ * `on*` handlers, dangerous URL schemes (`javascript:`/`vbscript:`/
129
+ * `data:text/html`) on URL-bearing attributes and markdown link/image URLs,
130
+ * and script/navigate/embed intrinsic elements (`<script>`, `<iframe>`, …)
131
+ * are dropped or emptied. This layers atop React's own SSR neutralization
132
+ * (it blocks `javascript:` URLs, strips string `on*` handlers, and escapes
133
+ * all text/attribute values). The set above is a renderer-agnostic superset:
134
+ * some of it (`javascript:`, string `on*`) React also covers, but it is
135
+ * re-applied here for the compile and mdast-serializer paths where React is
136
+ * not in the loop, and it adds what React does NOT handle (`data:text/html`,
137
+ * `dangerouslySetInnerHTML`, raw `<script>`/embed elements) — which the
138
+ * published `evaluateMDXToComponent` path would otherwise emit verbatim to
139
+ * every visitor.
140
+ *
141
+ * Non-literal JSX attribute and spread expressions are dropped so a component
142
+ * still renders with its safe props. Shared by `compileMDX` (editor preview) and
143
+ * `evaluateMDXToComponent` (published-site render), so the control is identical
144
+ * on both. In the editor the sandbox is the sufficient boundary; on the published
145
+ * path this transform is the boundary, so it must close the class, not just the
146
+ * eval vector. */
147
+ export function remarkRestrictExpressions() {
148
+ return (tree: MdastNode): void => {
149
+ const walk = (node: MdastNode): void => {
150
+ if (node.type === 'mdxFlowExpression' || node.type === 'mdxTextExpression') {
151
+ throw new Error('MDX expressions are not allowed: remove the `{…}` expression from the content.');
152
+ }
153
+ if (node.type === 'mdxjsEsm') {
154
+ throw new Error(
155
+ 'MDX import/export statements are not allowed: remove the top-level `import`/`export` from the content.',
156
+ );
157
+ }
158
+ if (
159
+ (node.type === 'link' || node.type === 'image') &&
160
+ typeof node.url === 'string' &&
161
+ hasDangerousScheme(node.url)
162
+ ) {
163
+ node.url = '';
164
+ }
165
+ if (Array.isArray(node.attributes)) node.attributes = sanitizeAttributes(node.attributes);
166
+ if (Array.isArray(node.children)) {
167
+ node.children = node.children.filter((child) => !isDangerousElement(child));
168
+ node.children.forEach(walk);
169
+ }
170
+ };
171
+ walk(tree);
172
+ };
173
+ }
@@ -0,0 +1,15 @@
1
+ import type { MDXEditorMethods } from '@mdxeditor/editor';
2
+ import React from 'react';
3
+ import { BaseMDXEditor, type BaseMDXEditorProps } from './editor-core.js';
4
+
5
+ export interface MDXEditorProps
6
+ extends Omit<
7
+ BaseMDXEditorProps,
8
+ 'disableImageSettingsButton' | 'imageButtonRef' | 'imageDialog' | 'onImageShortcut'
9
+ > {}
10
+
11
+ export const MDXEditor = React.forwardRef<MDXEditorMethods, MDXEditorProps>((props, ref) => {
12
+ return <BaseMDXEditor ref={ref} {...props} />;
13
+ });
14
+
15
+ MDXEditor.displayName = 'MDXEditor';
package/src/node.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Node.js-specific exports for @conloca/mdx
3
+ *
4
+ * These exports require Node.js runtime APIs and should not be imported in browser environments.
5
+ * Import from '@conloca/mdx/node' for server-side MDX operations.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // Server-side code (Astro, Next.js, etc.)
10
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
11
+ * ```
12
+ */
13
+
14
+ export { evaluateMDXFragments } from './fragments.js';
15
+ // MDX compilation and evaluation (Node.js only)
16
+ export { compileMDX } from './mdx/compile.js';
17
+ export { handleMDXCompileRequest } from './mdx/compile-request.js';
18
+ export { evaluateMDXToComponent } from './mdx/evaluate.js';
19
+ // MDX types
20
+ export type {
21
+ EvaluatedMDXFragment,
22
+ FailedMDXFragmentEvaluation,
23
+ MDXCompileResult,
24
+ MDXFragmentEvaluationResult,
25
+ } from './types.js';
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Opaque-origin MDX preview frame document + runtime. Confines the MDX
3
+ * `'unsafe-eval'` to this frame — see `SANDBOX_FRAME_CSP` below.
4
+ * Shared by the cms-spa ContentSandbox and the server route that serves this
5
+ * frame's HTML at `SANDBOX_FRAME_PATH`.
6
+ */
7
+
8
+ /**
9
+ * Build a jsx runtime that constructs real DOM nodes instead of React
10
+ * elements. The two isolated MDX preview surfaces render markdown-subset MDX
11
+ * with no component map supplied, so intrinsic elements plus `Fragment` cover
12
+ * everything they emit; this keeps the frame dependency-free (no React bundle
13
+ * to inline). Inline event-handler props are dropped defensively.
14
+ */
15
+
16
+ /** Discriminated messages the frame and its host exchange. */
17
+ export interface SandboxRenderMessage {
18
+ __conlocaSandbox: true;
19
+ kind: 'render';
20
+ mode: 'mdx' | 'html';
21
+ /** Compiled MDX function body (mode `mdx`) or sanitized HTML (mode `html`). */
22
+ payload: string;
23
+ /** Optional stylesheet text injected into the frame for preview fidelity. */
24
+ styles?: string;
25
+ }
26
+
27
+ export type SandboxOutboundMessage =
28
+ | { __conlocaSandbox: true; k: string; kind: 'ready' }
29
+ | { __conlocaSandbox: true; k: string; kind: 'height'; px: number }
30
+ | { __conlocaSandbox: true; k: string; kind: 'link'; href: string }
31
+ | { __conlocaSandbox: true; k: string; kind: 'interact' }
32
+ | { __conlocaSandbox: true; k: string; kind: 'rendered' }
33
+ | { __conlocaSandbox: true; k: string; kind: 'error'; message: string };
34
+
35
+ export function createSandboxRuntime(): {
36
+ Fragment: symbol;
37
+ jsx: (type: unknown, props: Record<string, unknown>) => Node;
38
+ jsxs: (type: unknown, props: Record<string, unknown>) => Node;
39
+ jsxDEV: (type: unknown, props: Record<string, unknown>) => Node;
40
+ } {
41
+ const Fragment = Symbol('sandbox.fragment');
42
+ const toNodes = (value: unknown): Node[] => {
43
+ if (value == null || value === true || value === false) return [];
44
+ if (Array.isArray(value)) return value.flatMap(toNodes);
45
+ if (typeof value === 'string' || typeof value === 'number') return [document.createTextNode(String(value))];
46
+ if (value instanceof Node) return [value];
47
+ return [document.createTextNode(String(value))];
48
+ };
49
+ const jsx = (type: unknown, props: Record<string, unknown>): Node => {
50
+ const p = props || {};
51
+ if (type === Fragment) {
52
+ const frag = document.createDocumentFragment();
53
+ for (const child of toNodes(p.children)) frag.appendChild(child);
54
+ return frag;
55
+ }
56
+ if (typeof type === 'function') return (type as (props: Record<string, unknown>) => Node)(p);
57
+ if (typeof type === 'string') {
58
+ const el = document.createElement(type);
59
+ for (const key in p) {
60
+ if (key === 'children' || key === 'key') continue;
61
+ const value = p[key];
62
+ if (/^on/i.test(key)) continue; // never wire an event handler
63
+ if (key === 'className') {
64
+ el.setAttribute('class', String(value));
65
+ } else if (key === 'style' && value && typeof value === 'object') {
66
+ Object.assign((el as HTMLElement).style, value as Record<string, string>);
67
+ } else if (value === true) {
68
+ el.setAttribute(key, '');
69
+ } else if (value != null && value !== false) {
70
+ el.setAttribute(key, String(value));
71
+ }
72
+ }
73
+ for (const child of toNodes(p.children)) el.appendChild(child);
74
+ return el;
75
+ }
76
+ const missing = document.createElement('span');
77
+ missing.setAttribute('data-sandbox-unknown', '');
78
+ return missing;
79
+ };
80
+ return { Fragment, jsx, jsxs: jsx, jsxDEV: jsx };
81
+ }
82
+
83
+ /**
84
+ * Evaluate a pre-compiled MDX function body. This is the `new AsyncFunction`
85
+ * eval that used to run in the privileged parent (`useMDXEvaluation`) — it now
86
+ * runs only here, inside the sandbox, which is why `'unsafe-eval'` is confined
87
+ * to the frame CSP. Returns the module's default export (the MDX component).
88
+ */
89
+ export function runCompiledMdx(
90
+ code: string,
91
+ runtime: Record<string, unknown>,
92
+ ): Promise<{ default?: (props: Record<string, unknown>) => Node }> {
93
+ const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (
94
+ body: string,
95
+ ) => (runtime: Record<string, unknown>) => Promise<{ default?: (props: Record<string, unknown>) => Node }>;
96
+ return new AsyncFunction(String(code))(runtime);
97
+ }
98
+
99
+ /**
100
+ * The frame entry point. Wires the message listener, height reporting, and
101
+ * link/interaction interception, then announces readiness. Every dependency
102
+ * arrives as `deps` so the serialized source carries no free identifiers a
103
+ * minifier could rename.
104
+ */
105
+ export function sandboxFrameMain(deps: {
106
+ createSandboxRuntime: typeof createSandboxRuntime;
107
+ runCompiledMdx: typeof runCompiledMdx;
108
+ }): void {
109
+ const root = document.getElementById('__sandbox_root');
110
+ if (!root) return;
111
+ // Per-instance key from ?k= so the host can accept messages without relying
112
+ // on event.source === iframe.contentWindow (broken for opaque sandboxes in Chromium).
113
+ let frameKey = '';
114
+ try {
115
+ frameKey = new URL(location.href).searchParams.get('k') || '';
116
+ } catch {
117
+ frameKey = '';
118
+ }
119
+ const post = (message: { kind: string; [key: string]: unknown }): void => {
120
+ parent.postMessage({ ...message, k: frameKey, __conlocaSandbox: true as const }, '*');
121
+ };
122
+ let lastHeight = -1;
123
+ const postHeight = (): void => {
124
+ // Child margins (prose p/h1) collapse out of a normal block root, so
125
+ // getBoundingClientRect(root) under-reports. flow-root on the root
126
+ // contains them; also take scrollHeight so a short iframe cannot
127
+ // circularly clamp the measure.
128
+ const px = Math.ceil(
129
+ Math.max(
130
+ root.getBoundingClientRect().height,
131
+ root.scrollHeight,
132
+ document.body.scrollHeight,
133
+ document.documentElement.scrollHeight,
134
+ ),
135
+ );
136
+ if (px !== lastHeight) {
137
+ lastHeight = px;
138
+ post({ __conlocaSandbox: true, kind: 'height', px });
139
+ }
140
+ };
141
+
142
+ document.addEventListener(
143
+ 'click',
144
+ (event) => {
145
+ const target = event.target as Element | null;
146
+ const anchor = target && 'closest' in target ? target.closest('a') : null;
147
+ if (anchor) {
148
+ event.preventDefault();
149
+ post({ __conlocaSandbox: true, kind: 'link', href: anchor.getAttribute('href') || '' });
150
+ }
151
+ },
152
+ true,
153
+ );
154
+ document.addEventListener('pointerdown', () => post({ __conlocaSandbox: true, kind: 'interact' }), true);
155
+
156
+ const applyStyles = (css: string): void => {
157
+ let style = document.getElementById('__sandbox_styles');
158
+ if (!style) {
159
+ style = document.createElement('style');
160
+ style.id = '__sandbox_styles';
161
+ document.head.appendChild(style);
162
+ }
163
+ style.textContent = css;
164
+ };
165
+ const renderMdx = (code: string): void => {
166
+ const runtime = deps.createSandboxRuntime();
167
+ deps
168
+ .runCompiledMdx(code, runtime as unknown as Record<string, unknown>)
169
+ .then((module) => {
170
+ const Component = module?.default;
171
+ root.textContent = '';
172
+ if (typeof Component === 'function') {
173
+ const output = Component({});
174
+ if (output) root.appendChild(output);
175
+ }
176
+ post({ __conlocaSandbox: true, kind: 'rendered' });
177
+ postHeight();
178
+ })
179
+ .catch((error: unknown) => {
180
+ post({
181
+ __conlocaSandbox: true,
182
+ kind: 'error',
183
+ message: error instanceof Error ? error.message : String(error),
184
+ });
185
+ });
186
+ };
187
+ const renderHtml = (html: string): void => {
188
+ // Already allowlist-sanitized by the host; the sandbox contains anything
189
+ // that slips through (opaque origin, no privileged globals, strict CSP).
190
+ root.innerHTML = html;
191
+ post({ __conlocaSandbox: true, kind: 'rendered' });
192
+ postHeight();
193
+ };
194
+
195
+ window.addEventListener('message', (event) => {
196
+ // Brand + kind only. Requiring event.source === parent drops legitimate
197
+ // host posts under some nested/opaque-origin Chromium cases.
198
+ const data = event.data as SandboxRenderMessage | undefined;
199
+ if (data?.__conlocaSandbox !== true || data.kind !== 'render') return;
200
+ if (typeof data.styles === 'string') applyStyles(data.styles);
201
+ try {
202
+ if (data.mode === 'mdx') renderMdx(data.payload);
203
+ else renderHtml(data.payload);
204
+ } catch (error: unknown) {
205
+ post({ __conlocaSandbox: true, kind: 'error', message: error instanceof Error ? error.message : String(error) });
206
+ }
207
+ });
208
+
209
+ const ResizeObs = (
210
+ window as unknown as { ResizeObserver?: new (cb: () => void) => { observe: (el: Element) => void } }
211
+ ).ResizeObserver;
212
+ if (ResizeObs) new ResizeObs(postHeight).observe(root);
213
+ post({ __conlocaSandbox: true, kind: 'ready' });
214
+ }
215
+
216
+ /**
217
+ * The frame's own Content-Security-Policy. `'unsafe-eval'` is intentional and
218
+ * confined here (the MDX eval lives in the frame). What it does and does NOT
219
+ * close, stated precisely:
220
+ * - The isolation that HOLDS: no `allow-same-origin` gives the frame an opaque
221
+ * origin, so it exposes no cookies, no privileged globals, and no
222
+ * `window.parent` — nothing privileged is reachable to exfiltrate.
223
+ * - Structured-data egress is closed: with no `connect-src`, `fetch`/XHR/
224
+ * WebSocket/`sendBeacon` cannot post data out.
225
+ * - Metadata-only leak channels REMAIN OPEN and are an accepted residual risk.
226
+ * A hostile preview script can still leak the previewing admin's IP/UA/timing
227
+ * (plus author-encoded data) to an external host two ways: (a) passive
228
+ * img/font GETs to `https:` (`img-src`/`font-src`, which `connect-src` does
229
+ * not govern — kept for remote-image/`@font-face` fidelity, CSP-toggleable
230
+ * below); and (b) self-navigation — `location.href`/`location.replace` or a
231
+ * `<meta http-equiv=refresh>` — which is inherent to `allow-scripts` and NOT
232
+ * closeable by CSP (`navigate-to` is unsupported in browsers) or the sandbox
233
+ * flags (same-frame navigation is always allowed), short of dropping
234
+ * `allow-scripts` and the interactive preview with it.
235
+ * Owner toggle: replacing `https:` with just `data: blob:` in `img-src`/`font-src`
236
+ * below closes (a) at a remote-image/-font fidelity cost — but not (b), which has
237
+ * no CSP mitigation. Both leak only request metadata, never privileged content.
238
+ */
239
+ export const SANDBOX_FRAME_CSP =
240
+ "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: https: blob:; font-src data: https:";
241
+
242
+ /**
243
+ * esbuild-style bundlers inject `/* @__PURE__ *\/ __name(fn, "id")` around
244
+ * function expressions when keepNames is on. That helper exists in the bundle
245
+ * scope but NOT inside the iframe document after Function#toString() copy.
246
+ * Provide a no-op so the serialized bootstrap can run in isolation.
247
+ */
248
+ const SANDBOX_BUNDLE_HELPERS = 'var __name=function(fn){return fn};';
249
+
250
+ /**
251
+ * Assemble the sandbox frame document. The runtime functions are injected as
252
+ * argument expressions to `sandboxFrameMain` so no cross-function identifier
253
+ * has to survive minification by name.
254
+ *
255
+ * The editor loads this from `GET /api/v1/mdx/sandbox-frame` (own response CSP
256
+ * with unsafe-eval). Do NOT use srcdoc/blob from the parent document: those
257
+ * inherit the parent CSP, which forbids unsafe-inline/unsafe-eval and leaves
258
+ * MDX fragment previews as empty white boxes.
259
+ */
260
+ export function buildSandboxSrcdoc(): string {
261
+ const bootstrap = `${SANDBOX_BUNDLE_HELPERS}(${sandboxFrameMain.toString()})({createSandboxRuntime:${createSandboxRuntime.toString()},runCompiledMdx:${runCompiledMdx.toString()}})`;
262
+ return [
263
+ '<!doctype html><html><head><meta charset="utf-8">',
264
+ `<meta http-equiv="Content-Security-Policy" content="${SANDBOX_FRAME_CSP}">`,
265
+ '<style>html,body{margin:0;padding:0}#__sandbox_root{box-sizing:border-box;display:flow-root}</style>',
266
+ // `conloca-prose` is the documented scope class for prose surfaces
267
+ // (the MDX editor's contenteditable carries it too). Sites can scope
268
+ // typography to `.conloca-prose <tag>` in their registered styles and
269
+ // it applies inside this sandbox as well as the editor.
270
+ '</head><body><div id="__sandbox_root" class="conloca-prose"></div>',
271
+ `<script>${bootstrap}</script>`,
272
+ '</body></html>',
273
+ ].join('');
274
+ }
275
+
276
+ /** Well-known path where a host serves {@link buildSandboxSrcdoc}. */
277
+ export const SANDBOX_FRAME_PATH = '/api/v1/mdx/sandbox-frame';
package/src/types.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { ComponentType } from 'react';
2
+
3
+ export type { MDXCompileResponse as MDXCompileResult, MDXHeading } from '@conloca/content-api';
4
+
5
+ import type { MDXHeading as Heading } from '@conloca/content-api';
6
+
7
+ export interface EvaluatedMDXFragment {
8
+ ok: true;
9
+ id: string;
10
+ title: string;
11
+ Component: ComponentType;
12
+ /** The fragment's headings, for a host block that shows a contents list. */
13
+ outline: readonly Heading[];
14
+ }
15
+
16
+ export interface FailedMDXFragmentEvaluation {
17
+ ok: false;
18
+ id: string;
19
+ title: string;
20
+ error: Error;
21
+ }
22
+
23
+ export type MDXFragmentEvaluationResult = EvaluatedMDXFragment | FailedMDXFragmentEvaluation;