-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
mdx-loader.js
225 lines (195 loc) · 6.02 KB
/
mdx-loader.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
const _ = require(`lodash`)
const { getOptions } = require(`loader-utils`)
const grayMatter = require(`gray-matter`)
const unified = require(`unified`)
const babel = require(`@babel/core`)
const { createRequireFromPath, slash } = require(`gatsby-core-utils`)
const { interopDefault } = require(`../utils/interop-default`)
const {
isImport,
isExport,
isExportDefault,
BLOCKS_REGEX,
EMPTY_NEWLINE,
} = require(`@mdx-js/mdx/util`)
// Some packages are required implicitly from @mdx-js/mdx (not listed in package.json).
// To support yarn PnP, we need them to be required from their direct parent.
const requireFromMDX = createRequireFromPath(require.resolve(`@mdx-js/mdx`))
const toMDAST = requireFromMDX(`remark-parse`)
const squeeze = requireFromMDX(`remark-squeeze-paragraphs`)
const debug = require(`debug`)(`gatsby-plugin-mdx:mdx-loader`)
const debugMore = require(`debug`)(`gatsby-plugin-mdx-info:mdx-loader`)
const genMdx = require(`../utils/gen-mdx`)
const withDefaultOptions = require(`../utils/default-options`)
const createMDXNodeWithScope = require(`../utils/mdx-node-with-scope`)
const { createFileNode } = require(`../utils/create-fake-file-node`)
const DEFAULT_OPTIONS = {
footnotes: true,
remarkPlugins: [],
rehypePlugins: [],
compilers: [],
blocks: [BLOCKS_REGEX],
}
/**
* TODO: Find a way to PR all of this code that was lifted
* from @mdx-js/mdx back into mdx with the modifications. We
* don't want to maintain subtly different parsing code if we
* can avoid it.
*/
const hasDefaultExport = (str, options) => {
let hasDefaultExportBool = false
function getDefaultExportBlock(subvalue) {
const isDefault = isExportDefault(subvalue)
hasDefaultExportBool = hasDefaultExportBool || isDefault
return isDefault
}
const tokenizeEsSyntax = (eat, value) => {
const index = value.indexOf(EMPTY_NEWLINE)
const subvalue = value.slice(0, index)
if (isExport(subvalue) || isImport(subvalue)) {
return eat(subvalue)({
type: isExport(subvalue) ? `export` : `import`,
default: getDefaultExportBlock(subvalue),
value: subvalue,
})
}
return undefined
}
tokenizeEsSyntax.locator = value =>
isExport(value) || isImport(value) ? -1 : 1
function esSyntax() {
var Parser = this.Parser
var tokenizers = Parser.prototype.blockTokenizers
var methods = Parser.prototype.blockMethods
tokenizers.esSyntax = tokenizeEsSyntax
methods.splice(methods.indexOf(`paragraph`), 0, `esSyntax`)
}
const { content } = grayMatter(str)
unified()
.use(toMDAST, options)
.use(esSyntax)
.use(squeeze, options)
.parse(content)
.toString()
return hasDefaultExportBool
}
module.exports = async function (content) {
const callback = this.async()
const {
getNode: rawGetNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
pluginOptions,
...helpers
} = getOptions(this)
const options = withDefaultOptions(pluginOptions)
let fileNode = getNodes().find(
node =>
node.internal.type === `File` &&
node.absolutePath === slash(this.resourcePath)
)
let isFakeFileNode = false
if (!fileNode) {
fileNode = await createFileNode(
this.resourcePath,
pth => `fakeFileNodeMDX${pth}`
)
isFakeFileNode = true
}
const source = fileNode && fileNode.sourceInstanceName
let mdxNode
try {
// This node attempts to break the chicken-egg problem, where parsing mdx
// allows for custom plugins, which can receive a mdx node
;({ mdxNode } = await createMDXNodeWithScope({
id: `fakeNodeIdMDXFileABugIfYouSeeThis`,
node: fileNode,
content,
options,
getNodesByType,
}))
} catch (e) {
return callback(e)
}
// get the default layout for the file source group, or if it doesn't
// exist, the overall default layout
const defaultLayout = _.get(
options.defaultLayouts,
source,
_.get(options.defaultLayouts, `default`)
)
let code = content
// after running mdx, the code *always* has a default export, so this
// check needs to happen first.
if (!hasDefaultExport(content, DEFAULT_OPTIONS) && !!defaultLayout) {
debug(`inserting default layout`, defaultLayout)
const { content: contentWithoutFrontmatter, matter } = grayMatter(content)
code = `${matter ? matter : ``}
import DefaultLayout from "${slash(defaultLayout)}"
export default DefaultLayout
${contentWithoutFrontmatter}`
}
const getNode = id => {
if (isFakeFileNode && id === fileNode.id) {
return fileNode
} else {
return rawGetNode(id)
}
}
/**
* Support gatsby-remark parser plugins
*/
for (let plugin of options.gatsbyRemarkPlugins) {
debug(`requiring`, plugin.resolve)
const requiredPlugin = interopDefault(require(plugin.resolve))
debug(`required`, plugin)
if (_.isFunction(requiredPlugin.setParserPlugins)) {
for (let parserPlugin of requiredPlugin.setParserPlugins(
plugin.options || {}
)) {
if (_.isArray(parserPlugin)) {
const [parser, parserPluginOptions] = parserPlugin
debug(`adding remarkPlugin with options`, plugin, parserPluginOptions)
options.remarkPlugins.push([parser, parserPluginOptions])
} else {
debug(`adding remarkPlugin`, plugin)
options.remarkPlugins.push(parserPlugin)
}
}
}
}
const { rawMDXOutput } = await genMdx({
...helpers,
isLoader: true,
options,
node: { ...mdxNode, rawBody: code },
getNode,
getNodes,
getNodesByType,
reporter,
cache,
pathPrefix,
})
try {
const result = babel.transform(rawMDXOutput, {
configFile: false,
plugins: [
requireFromMDX(`@babel/plugin-syntax-jsx`),
requireFromMDX(`@babel/plugin-syntax-object-rest-spread`),
require(`../utils/babel-plugin-html-attr-to-jsx-attr`),
],
})
debugMore(`transformed code`, result.code)
return callback(
null,
`import * as React from 'react'
${result.code}
`
)
} catch (e) {
return callback(e)
}
}