Skip to content

Commit 07775b0

Browse files
committed
Just wrap everything in an IIFE, micromark doesn\'t give us what we want
1 parent b773209 commit 07775b0

File tree

1 file changed

+2
-62
lines changed

1 file changed

+2
-62
lines changed
Lines changed: 2 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,5 @@
1-
import {unified} from 'unified';
2-
import remarkParse from 'remark-parse';
3-
import remarkMdx from 'remark-mdx';
4-
import remarkBreaks from 'remark-breaks';
5-
61
export default function processCode(code: string) {
7-
/*
8-
- Is this just JSX?
9-
- If it is, we can just return the code without an IIFE
10-
- If not, insert wrapping code such that it includes an IIFE
11-
- With an explicit return around the JSX
12-
- If the JSX has multiple adjacent nodes at root, wrap it in a fragment as well.
13-
*/
14-
try {
15-
const output = unified()
16-
.use(remarkParse)
17-
.use(remarkBreaks)
18-
.use(remarkMdx)
19-
.parse(code);
20-
// console.log('BOOP AST output', output);
21-
// The assummption here is that every top level child of our output ast
22-
// is a paragraph. If it isn't and ends up being a piece of flow content
23-
// this will break.
24-
// @ts-expect-error
25-
26-
const MDXAST = output.children.flatMap((m) => m.children);
27-
let lastIndex = MDXAST.length - 1;
28-
let firstIndex;
29-
for (let i = MDXAST.length - 1; i >= 0; i--) {
30-
const node = MDXAST[i];
31-
if (node.type === 'text' && /\s+/gm.test(node.value)) {
32-
continue;
33-
}
34-
if (!node.type.startsWith('mdxJsx')) {
35-
break;
36-
}
37-
firstIndex = i;
38-
}
39-
if (firstIndex === undefined) {
40-
// TODO Add a better error message
41-
throw new Error('trailing characters found');
42-
}
43-
const JSXStartPos = MDXAST[firstIndex].position.start.offset;
44-
const JSXEndPos = MDXAST[lastIndex].position.end.offset;
45-
const beforeJSX = code.slice(0, JSXStartPos);
46-
let JSX = code.slice(JSXStartPos, JSXEndPos);
47-
const afterJSX = code.slice(JSXEndPos).replace(/\n/g, '');
48-
const codeOutput = `
49-
${beforeJSX}
50-
return (
51-
<React.Fragment>
52-
${JSX}
53-
</React.Fragment>
54-
)
55-
${afterJSX}
56-
`;
57-
58-
return `{
59-
(() => {${codeOutput}})()
2+
return `{
3+
(() => {${code}})()
604
}`;
61-
} catch (e) {
62-
console.error(e);
63-
throw e;
64-
}
655
}

0 commit comments

Comments
 (0)