-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
get-source-plugins-as-remark-plugins.js
83 lines (77 loc) · 2.14 KB
/
get-source-plugins-as-remark-plugins.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
const visit = require(`unist-util-visit`)
const _ = require(`lodash`)
const debug = require(`debug`)(`get-source-plugins-as-remark-plugins`)
const { interopDefault } = require(`./interop-default`)
// ensure only one `/` in new url
const withPathPrefix = (url, pathPrefix) =>
(pathPrefix + url).replace(/\/\//, `/`)
module.exports = async function getSourcePluginsAsRemarkPlugins({
gatsbyRemarkPlugins,
mdxNode,
getNode,
getNodesByType,
reporter,
cache,
pathPrefix,
...helpers
}) {
debug(`getSourcePluginsAsRemarkPlugins`)
let pathPlugin = undefined
if (pathPrefix) {
pathPlugin = () =>
async function transformer(markdownAST) {
// Ensure relative links include `pathPrefix`
visit(markdownAST, `link`, node => {
if (
node.url &&
node.url.startsWith(`/`) &&
!node.url.startsWith(`//`)
) {
// TODO: where does withPathPrefix
node.url = withPathPrefix(node.url, pathPrefix)
}
})
return markdownAST
}
}
// return list of remarkPlugins
const userPlugins = gatsbyRemarkPlugins
.filter(plugin => {
if (_.isFunction(interopDefault(require(plugin.resolve)))) {
return true
} else {
debug(`userPlugins: filtering out`, plugin)
return false
}
})
.map(plugin => {
debug(`userPlugins: constructing remark plugin for `, plugin)
const requiredPlugin = interopDefault(require(plugin.resolve))
const wrappedPlugin = () =>
async function transformer(markdownAST) {
await requiredPlugin(
{
markdownAST,
markdownNode: mdxNode,
getNode,
getNodesByType,
get files() {
return getNodesByType(`File`)
},
pathPrefix,
reporter,
cache,
...helpers,
},
plugin.options || {}
)
return markdownAST
}
return [wrappedPlugin, {}]
})
if (pathPlugin) {
return [pathPlugin, ...userPlugins]
} else {
return [...userPlugins]
}
}