-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
build.js
93 lines (73 loc) · 2.2 KB
/
build.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
import fs from 'node:fs/promises'
import {fetch} from 'undici'
import {fromHtml} from 'hast-util-from-html'
import {selectAll} from 'hast-util-select'
import {toString} from 'hast-util-to-string'
import {htmlElementAttributes} from './index.js'
const own = {}.hasOwnProperty
if (!('*' in htmlElementAttributes)) {
htmlElementAttributes['*'] = []
}
// Global attributes.
const globals = htmlElementAttributes['*']
// Crawl WHATWG HTML.
const response = await fetch(
'https://html.spec.whatwg.org/multipage/indices.html'
)
const text = await response.text()
const nodes = selectAll('#attributes-1 tbody tr', fromHtml(text))
// Throw if we didn’t match, e.g., when the spec updates.
if (nodes.length === 0) {
throw new Error('Missing results in html')
}
/** @type {Record<string, Array<string>>} */
const result = {}
let index = -1
while (++index < nodes.length) {
const name = toString(nodes[index].children[0]).trim()
const value = toString(nodes[index].children[1]).trim()
if (/custom elements/i.test(value)) {
continue
}
const elements = /HTML elements/.test(value)
? ['*']
: value.split(/;/g).map((d) => d.replace(/\([^)]+\)/g, '').trim())
let offset = -1
while (++offset < elements.length) {
const tagName = elements[offset].toLowerCase().trim()
if (!own.call(htmlElementAttributes, tagName)) {
htmlElementAttributes[tagName] = []
}
/** @type {string[]} */
const attributes = htmlElementAttributes[tagName]
if (!attributes.includes(name)) {
attributes.push(name)
}
}
}
const keys = Object.keys(htmlElementAttributes).sort()
index = -1
while (++index < keys.length) {
const key = keys[index]
htmlElementAttributes[key].sort()
if (key !== '*') {
htmlElementAttributes[key] = htmlElementAttributes[key].filter(
(/** @type {string} */ d) => !globals.includes(d)
)
}
if (htmlElementAttributes[key].length > 0) {
result[key] = htmlElementAttributes[key]
}
}
await fs.writeFile(
'index.js',
[
'/**',
' * Map of HTML elements to allowed attributes.',
' *',
' * @type {Record<string, Array<string>>}',
' */',
'export const htmlElementAttributes = ' + JSON.stringify(result, null, 2),
''
].join('\n')
)