-
-
Notifications
You must be signed in to change notification settings - Fork 84
/
index.js
57 lines (51 loc) · 1.54 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
/**
* @typedef {import('hast').Root} Root
* @typedef {import('hast-util-from-html').Options} FromHtmlOptions
* @typedef {import('unified').Parser<Root>} Parser
*/
/**
* @typedef {Omit<FromHtmlOptions, 'onerror'> & RehypeParseFields} Options
* Configuration.
*
* @typedef RehypeParseFields
* Extra fields.
* @property {boolean | null | undefined} [emitParseErrors=false]
* Whether to emit parse errors while parsing (default: `false`).
*
* > 👉 **Note**: parse errors are currently being added to HTML.
* > Not all errors emitted by parse5 (or us) are specced yet.
* > Some documentation may still be missing.
*/
import {fromHtml} from 'hast-util-from-html'
/**
* Plugin to add support for parsing from HTML.
*
* @param {Options | null | undefined} [options]
* Configuration (optional).
* @returns {undefined}
* Nothing.
*/
export default function rehypeParse(options) {
/** @type {import('unified').Processor<Root>} */
// @ts-expect-error: TS in JSDoc generates wrong types if `this` is typed regularly.
const self = this
const {emitParseErrors, ...settings} = {...self.data('settings'), ...options}
self.parser = parser
/**
* @type {Parser}
*/
function parser(doc, file) {
return fromHtml(doc, {
...settings,
onerror: emitParseErrors
? function (message) {
if (file.path) {
message.name = file.path + ':' + message.name
message.file = file.path
}
file.messages.push(message)
}
: undefined
})
}
}