-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathgen-mdx.js
360 lines (316 loc) · 8.57 KB
/
gen-mdx.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
const babel = require(`@babel/core`)
const grayMatter = require(`gray-matter`)
const mdx = require(`@mdx-js/mdx`)
const objRestSpread = require(`@babel/plugin-proposal-object-rest-spread`)
const debug = require(`debug`)(`gatsby-plugin-mdx:gen-mdx`)
const getSourcePluginsAsRemarkPlugins = require(`./get-source-plugins-as-remark-plugins`)
const htmlAttrToJSXAttr = require(`./babel-plugin-html-attr-to-jsx-attr`)
const removeExportKeywords = require(`./babel-plugin-remove-export-keywords`)
const BabelPluginPluckImports = require(`./babel-plugin-pluck-imports`)
const { parseImportBindings } = require(`./import-parser`)
/*
* function mutateNode({
* pluginOptions,
* mdxNode,
* getNode,
* files,
* reporter,
* cache
* }) {
* return Promise.each(pluginOptions.gatsbyRemarkPlugins, plugin => {
* const requiredPlugin = require(plugin.resolve);
* if (_.isFunction(requiredPlugin.mutateSource)) {
* return requiredPlugin.mutateSource(
* {
* mdxNode,
* files: fileNodes,
* getNode,
* reporter,
* cache
* },
* plugin.pluginOptions
* );
* } else {
* return Promise.resolve();
* }
* });
* }
* */
async function genMDX(
{
isLoader,
node,
options,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
...helpers
},
{ forceDisableCache = false } = {}
) {
const pathPrefixCacheStr = pathPrefix || ``
const payloadCacheKey = node =>
`gatsby-plugin-mdx-entire-payload-${node.internal.contentDigest}-${pathPrefixCacheStr}`
if (!forceDisableCache) {
const cachedPayload = await cache.get(payloadCacheKey(node))
if (cachedPayload) {
return cachedPayload
}
}
let results = {
mdast: undefined,
hast: undefined,
html: undefined,
scopeImports: [],
scopeIdentifiers: [],
body: undefined,
}
// TODO: a remark and a hast plugin that pull out the ast and store it in results
/* const cacheMdast = () => ast => {
* results.mdast = ast;
* return ast;
* };
* const cacheHast = () => ast => {
* results.hast = ast;
* return ast;
* }; */
// pull classic style frontmatter off the raw MDX body
debug(`processing classic frontmatter`)
const { data, content: frontMatterCodeResult } = grayMatter(node.rawBody)
const content = `${frontMatterCodeResult}
export const _frontmatter = ${JSON.stringify(data)}`
// get mdast by itself
// in the future it'd be nice to not do this twice
debug(`generating AST`)
const compiler = mdx.createMdxAstCompiler(options)
results.mdast = compiler.parse(content)
/* await mutateNode({
* pluginOptions,
* mdxNode,
* files: getNodes().filter(n => n.internal.type === `File`),
* getNode,
* reporter,
* cache
* }); */
const gatsbyRemarkPluginsAsremarkPlugins = await getSourcePluginsAsRemarkPlugins(
{
gatsbyRemarkPlugins: options.gatsbyRemarkPlugins,
mdxNode: node,
// files,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
compiler: {
parseString: compiler.parse.bind(compiler),
generateHTML: ast => mdx(ast, options),
},
...helpers,
}
)
debug(`running mdx`)
let code = await mdx(content, {
filepath: node.fileAbsolutePath,
...options,
remarkPlugins: options.remarkPlugins.concat(
gatsbyRemarkPluginsAsremarkPlugins
),
})
results.rawMDXOutput = `/* @jsx mdx */
import { mdx } from '@mdx-js/react';
${code}`
if (!isLoader) {
debug(`compiling scope`)
const instance = new BabelPluginPluckImports()
const result = babel.transform(code, {
configFile: false,
plugins: [
instance.plugin,
objRestSpread,
htmlAttrToJSXAttr,
removeExportKeywords,
],
presets: [
require(`@babel/preset-react`),
[
require(`@babel/preset-env`),
{
useBuiltIns: `entry`,
corejs: 3,
modules: false,
},
],
],
})
const identifiers = Array.from(instance.state.identifiers)
const imports = Array.from(instance.state.imports)
if (!identifiers.includes(`React`)) {
identifiers.push(`React`)
imports.push(`import * as React from 'react'`)
}
results.scopeImports = imports
results.scopeIdentifiers = identifiers
// TODO: be more sophisticated about these replacements
results.body = result.code
.replace(
/export\s*default\s*function\s*MDXContent\s*/,
`return function MDXContent`
)
.replace(
/export\s*{\s*MDXContent\s+as\s+default\s*};?/,
`return MDXContent;`
)
}
/* results.html = renderToStaticMarkup(
* React.createElement(MDXRenderer, null, results.body)
* ); */
if (!forceDisableCache) {
await cache.set(payloadCacheKey(node), results)
}
return results
}
module.exports = genMDX // Legacy API, drop in v3 in favor of named export
module.exports.genMDX = genMDX
async function findImports({
node,
options,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
...helpers
}) {
const { content } = grayMatter(node.rawBody)
const gatsbyRemarkPluginsAsremarkPlugins = await getSourcePluginsAsRemarkPlugins(
{
gatsbyRemarkPlugins: options.gatsbyRemarkPlugins,
mdxNode: node,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
compiler: {
parseString: () => compiler.parse.bind(compiler),
generateHTML: ast => mdx(ast, options),
},
...helpers,
}
)
const compilerOptions = {
filepath: node.fileAbsolutePath,
...options,
remarkPlugins: [
...options.remarkPlugins,
...gatsbyRemarkPluginsAsremarkPlugins,
],
}
const compiler = mdx.createCompiler(compilerOptions)
const fileOpts = { contents: content }
if (node.fileAbsolutePath) {
fileOpts.path = node.fileAbsolutePath
}
let mdast = await compiler.parse(fileOpts)
mdast = await compiler.run(mdast, fileOpts)
// Assuming valid code, identifiers must be unique (they are consts) so
// we don't need to dedupe the symbols here.
const identifiers = []
const imports = []
mdast.children.forEach(node => {
if (node.type !== `import`) return
const importCode = node.value
imports.push(importCode)
const bindings = parseImportBindings(importCode)
identifiers.push(...bindings)
})
if (!identifiers.includes(`React`)) {
identifiers.push(`React`)
imports.push(`import * as React from 'react'`)
}
return {
scopeImports: imports,
scopeIdentifiers: identifiers,
}
}
module.exports.findImports = findImports
async function findImportsExports({
mdxNode,
rawInput,
absolutePath = null,
options,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
...helpers
}) {
const { data: frontmatter, content } = grayMatter(rawInput)
const gatsbyRemarkPluginsAsRemarkPlugins = await getSourcePluginsAsRemarkPlugins(
{
gatsbyRemarkPlugins: options.gatsbyRemarkPlugins,
mdxNode,
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
compiler: {
parseString: () => compiler.parse.bind(compiler),
generateHTML: ast => mdx(ast, options),
},
...helpers,
}
)
const compilerOptions = {
filepath: absolutePath,
...options,
remarkPlugins: [
...options.remarkPlugins,
...gatsbyRemarkPluginsAsRemarkPlugins,
],
}
const compiler = mdx.createCompiler(compilerOptions)
const fileOpts = { contents: content }
if (absolutePath) {
fileOpts.path = absolutePath
}
let mdast = await compiler.parse(fileOpts)
mdast = await compiler.run(mdast, fileOpts)
// Assuming valid code, identifiers must be unique (they are consts) so
// we don't need to dedupe the symbols here.
const identifiers = []
const imports = []
const exports = []
mdast.children.forEach(node => {
if (node.type === `import`) {
const importCode = node.value
imports.push(importCode)
const bindings = parseImportBindings(importCode)
identifiers.push(...bindings)
} else if (node.type === `export`) {
exports.push(node.value)
}
})
if (!identifiers.includes(`React`)) {
identifiers.push(`React`)
imports.push(`import * as React from 'react'`)
}
return {
frontmatter,
scopeImports: imports,
scopeExports: exports,
scopeIdentifiers: identifiers,
}
}
module.exports.findImportsExports = findImportsExports