@conloca/mdx 0.1.16 → 0.2.1

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 (91) 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 +30 -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 +123 -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/literal-attributes.d.ts +26 -0
  38. package/dist/mdx/literal-attributes.d.ts.map +1 -0
  39. package/dist/mdx/literal-attributes.js +40 -0
  40. package/dist/mdx/literal-attributes.js.map +1 -0
  41. package/dist/mdx/restrict-expressions.d.ts +45 -0
  42. package/dist/mdx/restrict-expressions.d.ts.map +1 -0
  43. package/dist/mdx/restrict-expressions.js +171 -0
  44. package/dist/mdx/restrict-expressions.js.map +1 -0
  45. package/dist/mdx-editor.js +1 -0
  46. package/dist/mdx-editor.js.map +1 -0
  47. package/dist/node.d.ts +3 -2
  48. package/dist/node.d.ts.map +1 -1
  49. package/dist/node.js +3 -1
  50. package/dist/node.js.map +1 -0
  51. package/dist/sandbox-frame.d.ts +114 -0
  52. package/dist/sandbox-frame.d.ts.map +1 -0
  53. package/dist/sandbox-frame.js +253 -0
  54. package/dist/sandbox-frame.js.map +1 -0
  55. package/dist/types.d.ts +7 -4
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/types.js +1 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +58 -41
  60. package/src/code-block-frame.tsx +262 -0
  61. package/src/editor-core.tsx +403 -0
  62. package/src/editor-styles.css +282 -0
  63. package/src/esm-passthrough.ts +269 -0
  64. package/src/fragments.ts +91 -0
  65. package/src/index.ts +5 -0
  66. package/src/markdown-options.ts +21 -0
  67. package/src/mdx/compile-request.ts +53 -0
  68. package/src/mdx/compile.ts +60 -0
  69. package/src/mdx/evaluate.ts +174 -0
  70. package/src/mdx/heading-outline.ts +153 -0
  71. package/src/mdx/literal-attributes.ts +50 -0
  72. package/src/mdx/restrict-expressions.ts +184 -0
  73. package/src/mdx-editor.tsx +15 -0
  74. package/src/node.ts +25 -0
  75. package/src/sandbox-frame.ts +294 -0
  76. package/src/types.ts +23 -0
  77. package/dist/blocks.d.ts +0 -37
  78. package/dist/blocks.d.ts.map +0 -1
  79. package/dist/blocks.js +0 -51
  80. package/dist/hooks/useMDXEvaluation.d.ts +0 -28
  81. package/dist/hooks/useMDXEvaluation.d.ts.map +0 -1
  82. package/dist/hooks/useMDXEvaluation.js +0 -117
  83. package/dist/index.d.mts +0 -127
  84. package/dist/index.d.mts.map +0 -1
  85. package/dist/index.mjs +0 -516
  86. package/dist/index.mjs.map +0 -1
  87. package/dist/node.d.mts +0 -102
  88. package/dist/node.d.mts.map +0 -1
  89. package/dist/node.mjs +0 -140
  90. package/dist/node.mjs.map +0 -1
  91. package/dist/style.css +0 -88
@@ -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,60 @@
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 { remarkDropUnrenderedAttributes } from './literal-attributes.js';
9
+ import { remarkRestrictExpressions } from './restrict-expressions.js';
10
+
11
+ export async function compileMDX(content: string): Promise<MDXCompileResult> {
12
+ try {
13
+ // Empty options opt out of gray-matter's module-level memo cache — a plain
14
+ // object keyed by the raw input, so inputs naming an Object.prototype
15
+ // member ('valueOf', 'toString', …) return the inherited member instead of
16
+ // a parse.
17
+ const { data: metadata } = matter(content, {});
18
+
19
+ // The editing surfaces read their outline off this compile rather than off
20
+ // the rendered frame, which they cannot see into: the fragment body renders
21
+ // in a sandbox with no same-origin access.
22
+ let outline: readonly FragmentHeading[] = [];
23
+ const collectOutline = () => (tree: OutlineTree) => {
24
+ outline = applyHeadingIds(tree);
25
+ };
26
+
27
+ const compiled = await mdxCompile(content, {
28
+ outputFormat: 'function-body',
29
+ development: process.env.NODE_ENV === 'development',
30
+ // `remarkRestrictExpressions` runs BEFORE `remarkMdxFrontmatter`: author
31
+ // `import`/`export` parse into `mdxjsEsm` nodes at parse time (so restrict
32
+ // sees and rejects them), while the legitimate `export const frontmatter`
33
+ // that `remarkMdxFrontmatter` injects appears only after restrict has run.
34
+ // `remarkDropUnrenderedAttributes` drops what the published fragment
35
+ // drops (`style={{…}}`, lists, `null`), so the preview matches it.
36
+ remarkPlugins: [
37
+ remarkFrontmatter,
38
+ remarkRestrictExpressions,
39
+ remarkDropUnrenderedAttributes,
40
+ remarkMdxFrontmatter,
41
+ remarkGfm,
42
+ ],
43
+ rehypePlugins: [collectOutline],
44
+ });
45
+
46
+ return {
47
+ code: String(compiled.value),
48
+ metadata: metadata,
49
+ outline,
50
+ };
51
+ } catch (error) {
52
+ if (error instanceof Error) {
53
+ const enhancedError = new Error(`MDX compilation failed: ${error.message}`);
54
+ enhancedError.stack = error.stack;
55
+ throw enhancedError;
56
+ }
57
+
58
+ throw error;
59
+ }
60
+ }
@@ -0,0 +1,174 @@
1
+ import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
2
+ import type { Parent, Root, RootContent } 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 { literalAttributeValue } from './literal-attributes.js';
13
+ import { remarkRestrictExpressions } from './restrict-expressions.js';
14
+
15
+ interface JsxAttributeNode {
16
+ type?: string;
17
+ name?: string;
18
+ value?: unknown;
19
+ }
20
+
21
+ interface TreeNode {
22
+ type?: string;
23
+ children?: TreeNode[];
24
+ attributes?: JsxAttributeNode[];
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ /**
29
+ * Make every JSX element in the tree statically renderable.
30
+ *
31
+ * Capitalized component names are rejected with a clear author-facing error —
32
+ * this path has no component registry to resolve them from, and letting them
33
+ * through surfaces as a cryptic converter error instead.
34
+ *
35
+ * JSON-literal `{…}` attribute values (the only expressions
36
+ * `remarkRestrictExpressions` admits) are resolved into plain static values,
37
+ * so rendering never needs an expression evaluator: strings pass through,
38
+ * numbers stringify (identical SSR output), and `{true}`/`{false}` reach React
39
+ * as booleans, which it renders as it renders any boolean prop: `{false}`
40
+ * leaves out `disabled` but writes `aria-hidden="false"` and `data-open="false"`.
41
+ * `null` and object literals drop the attribute. The converter reads an object
42
+ * value as an expression to run, which this path never does, so `style={{…}}`
43
+ * on an HTML element is dropped too.
44
+ */
45
+ function resolveStaticJsx() {
46
+ return (tree: TreeNode): void => {
47
+ const walk = (node: TreeNode): void => {
48
+ if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {
49
+ const name = typeof node.name === 'string' ? node.name : '';
50
+ if (/^[A-Z]/.test(name)) {
51
+ throw new Error(
52
+ `Unknown component <${name}>: fragments render as plain content and cannot use React components.`,
53
+ );
54
+ }
55
+ }
56
+ if (Array.isArray(node.attributes)) {
57
+ node.attributes = node.attributes.flatMap((attr) => {
58
+ const value = attr?.value;
59
+ if (!value || typeof value !== 'object') return [attr];
60
+ const raw = (value as { value?: unknown }).value;
61
+ // The same rule compileMDX applies, so the editor preview drops what this drops.
62
+ const literal = typeof raw === 'string' ? literalAttributeValue(raw) : undefined;
63
+ if (literal === undefined) return [];
64
+ return [{ ...attr, value: typeof literal === 'number' ? String(literal) : literal }];
65
+ });
66
+ }
67
+ if (Array.isArray(node.children)) node.children.forEach(walk);
68
+ };
69
+ walk(tree);
70
+ };
71
+ }
72
+
73
+ /** Nothing, or only the HTML whitespace a line break or a space between two tags leaves. */
74
+ const BLANK = /^[\t\n\f\r ]*$/;
75
+
76
+ /** A JSX element standing on its own as a block, like `<div>` written over several lines. */
77
+ type JsxBlock = Extract<RootContent, { type: 'mdxJsxFlowElement' }>;
78
+
79
+ /**
80
+ * Lift HTML tags out of a paragraph that holds nothing else. Markdown reads a tag written on one line,
81
+ * `<div>x</div>`, as the start of a paragraph, and `<p><div>x</div></p>` is HTML a browser splits into
82
+ * an empty paragraph and a loose `<div>`. The `@mdx-js/mdx` compiler this pipeline replaced does the
83
+ * same lifting (its `remarkMarkAndUnravel`); a paragraph with any text beside its tags keeps its `<p>`.
84
+ */
85
+ function unravelJsxParagraphs() {
86
+ const lift = (node: Parent): void => {
87
+ node.children = node.children.flatMap((child): RootContent[] => {
88
+ if (child.type !== 'paragraph') return [child];
89
+ const tags = child.children.filter((inline) => inline.type === 'mdxJsxTextElement');
90
+ const onlyTags = child.children.every(
91
+ (inline) => inline.type === 'mdxJsxTextElement' || (inline.type === 'text' && BLANK.test(inline.value)),
92
+ );
93
+ if (tags.length === 0 || !onlyTags) return [child];
94
+ // A tag's inline content stays as it is: written on one line, it never held a block.
95
+ return tags.map(
96
+ (tag): JsxBlock => ({ ...tag, type: 'mdxJsxFlowElement', children: tag.children as JsxBlock['children'] }),
97
+ );
98
+ });
99
+ for (const child of node.children) {
100
+ if ('children' in child) lift(child);
101
+ }
102
+ };
103
+ return (tree: Root): void => lift(tree);
104
+ }
105
+
106
+ /**
107
+ * Markdown → mdast (with MDX JSX syntax) → hast, with the JSX element nodes
108
+ * passed through for `toJsxRuntime` to turn into React elements directly.
109
+ */
110
+ const processor = unified()
111
+ .use(remarkParse)
112
+ .use(remarkMdx)
113
+ .use(remarkFrontmatter)
114
+ .use(remarkGfm)
115
+ // Both transformers use loose structural node types (they predate this
116
+ // pipeline and also run inside @mdx-js's own plugin list), so bridge them to
117
+ // unified's strict Plugin shape here rather than forking their signatures.
118
+ .use(remarkRestrictExpressions as unknown as Plugin<[], Root>)
119
+ .use(resolveStaticJsx as unknown as Plugin<[], Root>)
120
+ .use(unravelJsxParagraphs)
121
+ .use(remarkRehype, { passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'] });
122
+
123
+ /**
124
+ * Turn an MDX content string into a React component WITHOUT executing any
125
+ * compiled code.
126
+ *
127
+ * This is the published-site render path for CMS fragments, and it must run
128
+ * where creating code from strings is forbidden, such as Cloudflare Workers —
129
+ * `@mdx-js/mdx`'s `evaluate()` (a `new Function` under the hood) throws
130
+ * `EvalError: Code generation from strings disallowed` there. So instead of
131
+ * compile-and-execute, this parses the MDX to a syntax tree and converts the
132
+ * tree straight to React elements (`hast-util-to-jsx-runtime`). That is
133
+ * sufficient by construction: `remarkRestrictExpressions` already rejects
134
+ * `{…}` expressions and top-level `import`/`export`, and only JSON-literal
135
+ * attribute values survive — nothing in admissible content needs code
136
+ * execution to render.
137
+ *
138
+ * Unregistered capitalized JSX components fail here (evaluate time) rather
139
+ * than when React renders the component, so callers get the error result and
140
+ * can show their fragment-error UI instead of failing the whole page render.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * import { evaluateMDXToComponent } from '@conloca/mdx/node';
145
+ *
146
+ * const { Component, error } = await evaluateMDXToComponent('# Hello\n\nThis is **MDX**');
147
+ * if (error) {
148
+ * console.error('Failed to evaluate:', error);
149
+ * } else if (Component) {
150
+ * // Render <Component /> in your React app
151
+ * }
152
+ * ```
153
+ */
154
+ export async function evaluateMDXToComponent(
155
+ mdxContent: string,
156
+ ): Promise<{ Component: ComponentType | null; error?: Error; outline: readonly FragmentHeading[] }> {
157
+ try {
158
+ const mdast = processor.parse(mdxContent);
159
+ const hast = await processor.run(mdast);
160
+ // Before the tree becomes React: assigning the ids and reading the outline
161
+ // in one pass is what keeps a contents link and its heading in agreement.
162
+ const outline = applyHeadingIds(hast);
163
+ // Convert eagerly so bad content (e.g. an unknown component) surfaces as
164
+ // the error result; the returned component just replays the static tree.
165
+ const element = toJsxRuntime(hast, { Fragment, jsx, jsxs });
166
+ return { Component: () => element, outline };
167
+ } catch (error) {
168
+ return {
169
+ Component: null,
170
+ error: error instanceof Error ? error : new Error('MDX evaluation failed'),
171
+ outline: [],
172
+ };
173
+ }
174
+ }
@@ -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,50 @@
1
+ interface JsxAttributeNode {
2
+ type?: string;
3
+ name?: string;
4
+ value?: unknown;
5
+ }
6
+
7
+ interface TreeNode {
8
+ type?: string;
9
+ children?: TreeNode[];
10
+ attributes?: JsxAttributeNode[];
11
+ [key: string]: unknown;
12
+ }
13
+
14
+ /**
15
+ * The value a JSON-literal attribute expression (`{3}`, `{true}`, `{"x"}`) has
16
+ * on a published fragment, or undefined when the attribute renders as nothing
17
+ * there: an object (`style={{…}}`), a list, `null`, or anything not JSON.
18
+ */
19
+ export function literalAttributeValue(expression: string): string | number | boolean | undefined {
20
+ let parsed: unknown;
21
+ try {
22
+ parsed = JSON.parse(expression.trim());
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ return typeof parsed === 'string' || typeof parsed === 'number' || typeof parsed === 'boolean' ? parsed : undefined;
27
+ }
28
+
29
+ /**
30
+ * Remark transform that drops every JSX attribute whose `{…}` value renders as
31
+ * nothing on a published fragment, so a compiled preview shows what will be
32
+ * published. It runs on the markdown tree, before the compiler writes the
33
+ * style objects that align table columns, so those are kept.
34
+ */
35
+ export function remarkDropUnrenderedAttributes() {
36
+ return (tree: TreeNode): void => {
37
+ const walk = (node: TreeNode): void => {
38
+ if (Array.isArray(node.attributes)) {
39
+ node.attributes = node.attributes.filter((attr) => {
40
+ const value = attr?.value;
41
+ if (!value || typeof value !== 'object') return true;
42
+ const expression = (value as { value?: unknown }).value;
43
+ return typeof expression === 'string' && literalAttributeValue(expression) !== undefined;
44
+ });
45
+ }
46
+ if (Array.isArray(node.children)) node.children.forEach(walk);
47
+ };
48
+ walk(tree);
49
+ };
50
+ }
@@ -0,0 +1,184 @@
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
+ /** `{/* … *\/}`, the way MDX writes a comment: the parsed program has no
68
+ * statements, so nothing in it can run. Without the parsed program it is
69
+ * not trusted to be one. */
70
+ function isComment(node: MdastNode): boolean {
71
+ if (node?.type !== 'mdxFlowExpression' && node?.type !== 'mdxTextExpression') return false;
72
+ const program = (node.data as { estree?: { body?: unknown } } | undefined)?.estree;
73
+ return Array.isArray(program?.body) && program.body.length === 0;
74
+ }
75
+
76
+ /** A JSON-literal expression whose parsed value is a dangerous-scheme URL string
77
+ * (`href={"data:text/html,…"}` round-trips through `JSON.parse` yet navigates). */
78
+ function isDangerousLiteralUrl(value: unknown): boolean {
79
+ const raw = (value as { value?: unknown })?.value;
80
+ if (typeof raw !== 'string') return false;
81
+ try {
82
+ const parsed = JSON.parse(raw.trim());
83
+ return typeof parsed === 'string' && hasDangerousScheme(parsed);
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ /** Filter/neutralize a JSX element's attributes: drop the `dangerouslySetInnerHTML`
90
+ * raw-HTML sink and inline `on*` handlers, drop non-literal expression props, and
91
+ * empty a URL-bearing attribute carrying a dangerous scheme. */
92
+ function sanitizeAttributes(attributes: MdastAttribute[]): MdastAttribute[] {
93
+ const out: MdastAttribute[] = [];
94
+ for (const attr of attributes) {
95
+ if (attr?.type === 'mdxJsxExpressionAttribute') continue; // `{...spread}` — arbitrary props
96
+ if (attr?.type !== 'mdxJsxAttribute' || typeof attr.name !== 'string') {
97
+ out.push(attr);
98
+ continue;
99
+ }
100
+ const name = attr.name;
101
+ // React's only raw-HTML escape hatch. A JSON-literal object
102
+ // (`{"__html": "<script>…"}`) passes the literal exemption yet injects live
103
+ // HTML on the published path, so drop it regardless of value shape.
104
+ if (name.toLowerCase() === 'dangerouslysetinnerhtml') continue;
105
+ // Inline event handlers are never content. React strips string handlers, but
106
+ // dropping them here keeps the gate renderer-agnostic.
107
+ if (/^on/i.test(name)) continue;
108
+ const value = attr.value;
109
+ if (value && typeof value === 'object') {
110
+ if (!isLiteralExpression(value)) continue; // non-literal expression prop
111
+ if (URL_ATTR.test(name) && isDangerousLiteralUrl(value)) {
112
+ out.push({ ...attr, value: '' });
113
+ continue;
114
+ }
115
+ out.push(attr);
116
+ continue;
117
+ }
118
+ if (typeof value === 'string' && URL_ATTR.test(name) && hasDangerousScheme(value)) {
119
+ out.push({ ...attr, value: '' });
120
+ continue;
121
+ }
122
+ out.push(attr);
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /** Remark transform that neutralizes the author-code AND HTML-injection vectors
128
+ * in authored MDX at every compile/eval entry point.
129
+ *
130
+ * Two layers, because expression-restriction is NOT HTML sanitization:
131
+ * 1. Author code — standalone `{…}` flow/text expressions (`mdxFlowExpression`/
132
+ * `mdxTextExpression`) and top-level ESM `import`/`export` (`mdxjsEsm`) reach
133
+ * `new AsyncFunction`/`evaluate()` as live code, so they fail the compile
134
+ * with a clear error; content fragments never legitimately need either.
135
+ * A comment, `{/* … *\/}`, holds no code and is removed instead, so it
136
+ * renders as nothing, as it does in MDX.
137
+ * 2. HTML injection — `dangerouslySetInnerHTML` (React's raw-HTML escape hatch,
138
+ * which a JSON-literal object slips past the expression exemption), inline
139
+ * `on*` handlers, dangerous URL schemes (`javascript:`/`vbscript:`/
140
+ * `data:text/html`) on URL-bearing attributes and markdown link/image URLs,
141
+ * and script/navigate/embed intrinsic elements (`<script>`, `<iframe>`, …)
142
+ * are dropped or emptied. This layers atop React's own SSR neutralization
143
+ * (it blocks `javascript:` URLs, strips string `on*` handlers, and escapes
144
+ * all text/attribute values). The set above is a renderer-agnostic superset:
145
+ * some of it (`javascript:`, string `on*`) React also covers, but it is
146
+ * re-applied here for the compile and mdast-serializer paths where React is
147
+ * not in the loop, and it adds what React does NOT handle (`data:text/html`,
148
+ * `dangerouslySetInnerHTML`, raw `<script>`/embed elements) — which the
149
+ * published `evaluateMDXToComponent` path would otherwise emit verbatim to
150
+ * every visitor.
151
+ *
152
+ * Non-literal JSX attribute and spread expressions are dropped so a component
153
+ * still renders with its safe props. Shared by `compileMDX` (editor preview) and
154
+ * `evaluateMDXToComponent` (published-site render), so the control is identical
155
+ * on both. In the editor the sandbox is the sufficient boundary; on the published
156
+ * path this transform is the boundary, so it must close the class, not just the
157
+ * eval vector. */
158
+ export function remarkRestrictExpressions() {
159
+ return (tree: MdastNode): void => {
160
+ const walk = (node: MdastNode): void => {
161
+ if (node.type === 'mdxFlowExpression' || node.type === 'mdxTextExpression') {
162
+ throw new Error('MDX expressions are not allowed: remove the `{…}` expression from the content.');
163
+ }
164
+ if (node.type === 'mdxjsEsm') {
165
+ throw new Error(
166
+ 'MDX import/export statements are not allowed: remove the top-level `import`/`export` from the content.',
167
+ );
168
+ }
169
+ if (
170
+ (node.type === 'link' || node.type === 'image') &&
171
+ typeof node.url === 'string' &&
172
+ hasDangerousScheme(node.url)
173
+ ) {
174
+ node.url = '';
175
+ }
176
+ if (Array.isArray(node.attributes)) node.attributes = sanitizeAttributes(node.attributes);
177
+ if (Array.isArray(node.children)) {
178
+ node.children = node.children.filter((child) => !isDangerousElement(child) && !isComment(child));
179
+ node.children.forEach(walk);
180
+ }
181
+ };
182
+ walk(tree);
183
+ };
184
+ }