/
index.js
80 lines (72 loc) · 2.25 KB
/
index.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
/**
* @typedef {import('node:module').LoadHookContext} LoadHookContext
* @typedef {import('node:module').LoadFnOutput} LoadFnOutput
* @typedef {import('node:module').LoadHook} LoadHookType
* @typedef {import('@mdx-js/mdx').CompileOptions} CompileOptions
*/
/**
* @typedef {Parameters<LoadHookType>[2]} NextLoad
* Next.
*
* @typedef {Omit<CompileOptions, 'development'>} Options
* Configuration.
*
* Options are the same as [`compile` from `@mdx-js/mdx`][mdx-options]
* with the exception that the `development` option is supported based on how you
* configure webpack.
* You cannot pass it manually.
*/
import fs from 'node:fs/promises'
import {createFormatAwareProcessors} from '@mdx-js/mdx/internal-create-format-aware-processors'
import {extnamesToRegex} from '@mdx-js/mdx/internal-extnames-to-regex'
import {SourceMapGenerator} from 'source-map'
import {VFile} from 'vfile'
import {development as defaultDevelopment} from '#condition'
/**
* Create Node.js hooks to handle markdown and MDX.
*
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @returns
* Node.js hooks.
*/
export function createLoader(options) {
const options_ = options || {}
const {extnames, process} = createFormatAwareProcessors({
development: defaultDevelopment,
...options_,
SourceMapGenerator
})
const regex = extnamesToRegex(extnames)
return {load}
/**
* Load `file:` URLs to MD(X) files.
*
* @param {string} href
* URL.
* @param {LoadHookContext} context
* Context.
* @param {NextLoad} nextLoad
* Next or default `load` function.
* @returns {Promise<LoadFnOutput>}
* Result.
* @satisfies {LoadHookType}
*/
async function load(href, context, nextLoad) {
const url = new URL(href)
if (url.protocol === 'file:' && regex.test(url.pathname)) {
const value = await fs.readFile(url)
const file = await process(new VFile({value, path: url}))
return {
format: 'module',
shortCircuit: true,
source:
String(file) +
'\n//# sourceMappingURL=data:application/json;base64,' +
Buffer.from(JSON.stringify(file.map)).toString('base64') +
'\n'
}
}
return nextLoad(href, context)
}
}