/
loader.ts
216 lines (185 loc) · 5.89 KB
/
loader.ts
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
import type { LoaderOptions } from './types'
import path from 'path'
import grayMatter from 'gray-matter'
import slash from 'slash'
import { LoaderContext } from 'webpack'
import { Repository } from '@napi-rs/simple-git'
import { addPage } from './content-dump'
import { getLocaleFromFilename } from './utils'
import { compileMdx } from './compile'
import { getPageMap, findPagesDir } from './page-map'
import { collectFiles } from './plugin'
const extension = /\.mdx?$/
const isProductionBuild = process.env.NODE_ENV === 'production'
// TODO: create this as a webpack plugin.
const indexContentEmitted = new Set()
const pagesDir = path.resolve(findPagesDir())
const [repository, gitRoot] = (function () {
try {
const repo = Repository.discover(process.cwd())
// repository.path() returns the `/path/to/repo/.git`, we need the parent directory of it
const gitRoot = path.join(repo.path(), '..')
return [repo, gitRoot]
} catch (e) {
console.warn('[nextra] Init git repository failed', e)
return []
}
})()
async function loader(
context: LoaderContext<LoaderOptions>,
source: string
): Promise<string> {
context.cacheable(true)
const options = context.getOptions()
let {
theme,
themeConfig,
defaultLocale,
unstable_flexsearch,
unstable_staticImage,
mdxOptions,
pageMapCache
} = options
const { resourcePath } = context
if (resourcePath.includes('/pages/api/')) {
console.warn(`[nextra] Ignoring ${resourcePath} because it is located in the "pages/api" folder.`)
return ''
}
const filename = resourcePath.slice(resourcePath.lastIndexOf('/') + 1)
const fileLocale = getLocaleFromFilename(filename)
// Check if there's a theme provided
if (!theme) {
throw new Error('No Nextra theme found!')
}
const { items: pageMapResult, fileMap } = isProductionBuild
? pageMapCache.get()!
: await collectFiles(pagesDir, '/')
const [pageMap, route, title] = getPageMap(
resourcePath,
pageMapResult,
fileMap,
defaultLocale
)
if (!isProductionBuild) {
// Add the entire directory `pages` as the dependency
// so we can generate the correct page map.
context.addContextDependency(pagesDir)
} else {
// We only add meta files as dependencies for production build,
// so we can do incremental builds.
Object.entries(fileMap).forEach(([filePath, { name, meta, locale }]) => {
if (
name === 'meta.json' &&
meta &&
(!fileLocale || locale === fileLocale)
) {
context.addDependency(filePath)
}
})
}
// Extract frontMatter information if it exists
let { data, content } = grayMatter(source)
let layout = theme
let layoutConfig = themeConfig || null
// Relative path instead of a package name
if (theme.startsWith('.') || theme.startsWith('/')) {
layout = path.resolve(theme)
}
if (layoutConfig) {
layoutConfig = slash(path.resolve(layoutConfig))
}
if (isProductionBuild && indexContentEmitted.has(filename)) {
unstable_flexsearch = false
}
const { result, titleText, headings, hasH1, structurizedData } =
await compileMdx(
content,
mdxOptions,
{
unstable_staticImage,
unstable_flexsearch
},
resourcePath
)
content = result.replace('export default MDXContent;', '')
if (unstable_flexsearch) {
// We only add .MD and .MDX contents
if (extension.test(filename) && data.searchable !== false) {
addPage({
fileLocale: fileLocale || 'default',
route,
title,
data,
structurizedData
})
}
indexContentEmitted.add(filename)
}
let timestamp: number | undefined
if (repository && gitRoot) {
if (repository.isShallow()) {
if (process.env.VERCEL) {
console.warn(
'[nextra] The repository is shallow cloned, so the latest modified time will not be presented. Set the VERCEL_DEEP_CLONE=true environment variable to enable deep cloning.'
)
} else if (process.env.GITHUB_ACTION) {
console.warn(
'[nextra] The repository is shallow cloned, so the latest modified time will not be presented. See https://github.com/actions/checkout#fetch-all-history-for-all-tags-and-branches to fetch all the history.'
)
} else {
console.warn(
'[nextra] The repository is shallow cloned, so the latest modified time will not be presented.'
)
}
}
try {
timestamp = await repository.getFileLatestModifiedDateAsync(
path.relative(gitRoot, resourcePath)
)
} catch {
// Failed to get timestamp for this file. Silently ignore it.
}
}
const layoutConfigImport = layoutConfig
? `import __nextra_layoutConfig__ from '${layoutConfig}'`
: ''
return `
import __nextra_withLayout__ from '${layout}'
import { withSSG as __nextra_withSSG__ } from 'nextra/ssg'
${layoutConfigImport}
const __nextra_pageMap__ = ${JSON.stringify(pageMap)}
globalThis.__nextra_internal__ = {
pageMap: __nextra_pageMap__,
route: ${JSON.stringify(route)}
}
const NextraLayout = __nextra_withSSG__(__nextra_withLayout__({
filename: "${slash(filename)}",
route: "${slash(route)}",
meta: ${JSON.stringify(data)},
pageMap: __nextra_pageMap__,
titleText: ${JSON.stringify(titleText)},
headings: ${JSON.stringify(headings)},
hasH1: ${JSON.stringify(hasH1)},
${timestamp ? `timestamp: ${timestamp},\n` : ''}
}, ${layoutConfig ? '__nextra_layoutConfig__' : 'null'}))
${content}
function NextraPage(props) {
return (
<NextraLayout {...props}>
<MDXContent />
</NextraLayout>
)
}
NextraPage.getLayout = NextraLayout.getLayout
export default NextraPage
`.trimStart()
}
export default function syncLoader(
this: LoaderContext<LoaderOptions>,
source: string,
callback: (err?: null | Error, content?: string | Buffer) => void
) {
loader(this, source)
.then(result => callback(null, result))
.catch(err => callback(err))
}