@ohos-ports/html-minifier-next 8.4.2-beta.0 → 8.10.8-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -33
- package/cli.js +70 -54
- package/dist/types/htmlminifier.d.ts +87 -33
- package/dist/types/htmlminifier.d.ts.map +1 -1
- package/dist/types/htmlparser.d.ts +4 -1
- package/dist/types/htmlparser.d.ts.map +1 -1
- package/dist/types/lib/attributes.d.ts +12 -10
- package/dist/types/lib/attributes.d.ts.map +1 -1
- package/dist/types/lib/constants.d.ts +38 -3
- package/dist/types/lib/constants.d.ts.map +1 -1
- package/dist/types/lib/content.d.ts.map +1 -1
- package/dist/types/lib/elements.d.ts.map +1 -1
- package/dist/types/lib/fragments.d.ts +1 -0
- package/dist/types/lib/fragments.d.ts.map +1 -1
- package/dist/types/lib/option-definitions.d.ts.map +1 -1
- package/dist/types/lib/options.d.ts +14 -46
- package/dist/types/lib/options.d.ts.map +1 -1
- package/dist/types/lib/unused-css.d.ts +34 -4
- package/dist/types/lib/unused-css.d.ts.map +1 -1
- package/dist/types/lib/urls.d.ts.map +1 -1
- package/dist/types/lib/utils.d.ts +31 -1
- package/dist/types/lib/utils.d.ts.map +1 -1
- package/dist/types/lib/whitespace.d.ts +57 -5
- package/dist/types/lib/whitespace.d.ts.map +1 -1
- package/dist/types/presets.d.ts +1 -2
- package/dist/types/presets.d.ts.map +1 -1
- package/dist/types/tokenchain.d.ts.map +1 -1
- package/html-minifier-next.schema.json +15 -7
- package/package.json +17 -18
- package/src/htmlminifier.js +1103 -392
- package/src/htmlparser.js +452 -200
- package/src/lib/attributes.js +201 -112
- package/src/lib/constants.js +130 -19
- package/src/lib/content.js +1 -6
- package/src/lib/elements.js +17 -12
- package/src/lib/file-pool.js +18 -2
- package/src/lib/file-write.js +87 -0
- package/src/lib/fragments.js +74 -8
- package/src/lib/option-definitions.js +17 -10
- package/src/lib/options.js +151 -71
- package/src/lib/unused-css.js +145 -27
- package/src/lib/urls.js +0 -9
- package/src/lib/utils.js +210 -45
- package/src/lib/whitespace.js +173 -63
- package/src/presets.js +1 -2
- package/src/tokenchain.js +1 -4
package/src/lib/constants.js
CHANGED
|
@@ -17,6 +17,10 @@ const RE_TRAILING_SEMICOLON = /;$/;
|
|
|
17
17
|
const RE_AMP_ENTITY = /&(#?[0-9a-zA-Z]+;)/g;
|
|
18
18
|
const RE_LEGACY_ENTITIES = /&((?:Iacute|aacute|uacute|plusmn|Otilde|otilde|agrave|Agrave|Yacute|yacute|Oslash|oslash|atilde|Atilde|brvbar|ccedil|Ccedil|Ograve|curren|divide|eacute|Eacute|ograve|Oacute|egrave|Egrave|Ugrave|frac12|frac14|frac34|ugrave|oacute|iacute|Ntilde|ntilde|Uacute|middot|igrave|Igrave|iquest|Aacute|cedil|laquo|micro|iexcl|Icirc|icirc|acirc|Ucirc|Ecirc|ocirc|Ocirc|ecirc|ucirc|Aring|aring|AElig|aelig|acute|pound|raquo|Acirc|times|THORN|szlig|thorn|COPY|auml|ordf|ordm|Uuml|macr|uuml|Auml|ouml|Ouml|para|nbsp|euml|quot|QUOT|Euml|yuml|cent|sect|copy|sup1|sup2|sup3|iuml|Iuml|ETH|shy|reg|not|yen|amp|AMP|REG|uml|eth|deg|gt|GT|LT|lt)(?!;)|(?:#?[0-9a-zA-Z]+;))/g;
|
|
19
19
|
const RE_ESCAPE_LT = /</g;
|
|
20
|
+
// What decoded text and attribute values hold that XML reads otherwise: markup, and
|
|
21
|
+
// line breaks and tabs XML normalizes (quotes are left to attribute quoting)
|
|
22
|
+
const RE_XML_ESCAPE_TEXT = /[&<\r]|]]>/g;
|
|
23
|
+
const RE_XML_ESCAPE_ATTR = /[&<\t\n\r]/g;
|
|
20
24
|
// In escapable raw text only the element’s own end tag ends the element, so nothing else
|
|
21
25
|
// that `decodeEntities` decoded to a `<` needs escaping there
|
|
22
26
|
// (the record has no prototype, so a tag named after an inherited property—`constructor`,
|
|
@@ -28,9 +32,15 @@ const RE_ESCAPE_LT_RAW_TEXT = /** @type {Record<string, RegExp>} */ (Object.assi
|
|
|
28
32
|
// Encodings that make an `annotation-xml` element hold HTML rather than MathML
|
|
29
33
|
// https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point
|
|
30
34
|
const RE_HTML_ENCODING = /^(text\/html|application\/xhtml\+xml)$/i;
|
|
35
|
+
// A doctype’s name, public identifier, and system identifier (quoted),
|
|
36
|
+
// and what follows them, as the tokenizer reads them; unless a system
|
|
37
|
+
// identifier precedes it, anything but `>` sets quirks mode
|
|
38
|
+
// https://html.spec.whatwg.org/multipage/parsing.html#doctype-state
|
|
39
|
+
const RE_DOCTYPE = /^<!doctype[ \n\r\t\f]*([^ \n\r\t\f>]+)[ \n\r\t\f]*(?:public[ \n\r\t\f]*("[^">]*"|'[^'>]*')[ \n\r\t\f]*("[^">]*"|'[^'>]*')?|system[ \n\r\t\f]*("[^">]*"|'[^'>]*'))?([^]*)$/i;
|
|
31
40
|
const RE_ATTR_WS_CHECK = /[ \n\r\t\f]/;
|
|
32
41
|
const RE_ATTR_WS_COLLAPSE = /[ \n\r\t\f]+/g;
|
|
33
42
|
const RE_ATTR_WS_TRIM = /^[ \n\r\t\f]+|[ \n\r\t\f]+$/g;
|
|
43
|
+
const RE_WS_CHAR = /\s/;
|
|
34
44
|
const RE_STYLE_ELEMENT = /<style[\s/>]/i;
|
|
35
45
|
const RE_EMPTY_ATTRIBUTE = new RegExp(
|
|
36
46
|
'^(?:class|id|style|title|lang|dir|on(?:focus|blur|change|click|dblclick|mouse(' +
|
|
@@ -39,18 +49,45 @@ const RE_EMPTY_ATTRIBUTE = new RegExp(
|
|
|
39
49
|
// Inline element sets for whitespace handling
|
|
40
50
|
|
|
41
51
|
// Non-empty elements that will maintain whitespace around them
|
|
42
|
-
const inlineElementsToKeepWhitespaceAround = new Set(['a', 'abbr', 'acronym', 'b', 'bdi', 'bdo', 'big', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'mark', 'math', 'meter', 'nobr', 'object', 'output', 'progress', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'svg', 'textarea', 'time', 'tt', 'u', 'var', 'wbr']);
|
|
52
|
+
const inlineElementsToKeepWhitespaceAround = new Set(['a', 'abbr', 'acronym', 'audio', 'b', 'bdi', 'bdo', 'big', 'button', 'canvas', 'cite', 'code', 'data', 'del', 'dfn', 'em', 'embed', 'font', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'map', 'mark', 'math', 'meter', 'nobr', 'object', 'output', 'picture', 'progress', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'select', 'selectedcontent', 'slot', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'svg', 'textarea', 'time', 'tt', 'u', 'var', 'video', 'wbr']);
|
|
43
53
|
|
|
44
54
|
// Non-empty elements that will maintain whitespace within them
|
|
45
|
-
const inlineElementsToKeepWhitespaceWithin = new Set(['a', 'abbr', 'acronym', 'b', 'big', 'del', 'em', 'font', 'i', 'ins', 'kbd', 'mark', 'nobr', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'time', 'tt', 'u', 'var']);
|
|
55
|
+
const inlineElementsToKeepWhitespaceWithin = new Set(['a', 'abbr', 'acronym', 'b', 'big', 'data', 'del', 'em', 'font', 'i', 'ins', 'kbd', 'map', 'mark', 'nobr', 's', 'samp', 'slot', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'time', 'tt', 'u', 'var']);
|
|
56
|
+
|
|
57
|
+
// Text-level elements that keep whitespace between them and other elements under
|
|
58
|
+
// `collapseInlineTagWhitespace`
|
|
59
|
+
const inlineElementsToKeepWhitespaceBetween = new Set([...inlineElementsToKeepWhitespaceWithin, 'bdi', 'bdo', 'cite', 'code', 'dfn', 'label', 'math', 'q', 'ruby']);
|
|
60
|
+
|
|
61
|
+
// Phrasing elements that don’t render, whose neighbors decide on the whitespace around them
|
|
62
|
+
const inlineElementsTransparent = new Set(['area', 'datalist', 'link', 'meta', 'noscript', 'script', 'style', 'template']);
|
|
63
|
+
const inlineElementsTransparentVoid = new Set(['area', 'link', 'meta']);
|
|
64
|
+
|
|
65
|
+
// What the parser reports as the tag next to text that borders a processing instruction—
|
|
66
|
+
// no tag name can be `?`, and content may be inserted there, so whitespace around it stays
|
|
67
|
+
const processingInstructionTag = '?';
|
|
46
68
|
|
|
47
69
|
// Elements that will always maintain whitespace around them
|
|
48
|
-
const inlineElementsToKeepWhitespace = new Set(['comment', 'img', 'input', 'wbr']);
|
|
70
|
+
const inlineElementsToKeepWhitespace = new Set(['comment', 'embed', 'img', 'input', 'wbr', processingInstructionTag]);
|
|
71
|
+
|
|
72
|
+
// Formatting elements, which browsers reopen after a block that closed them, so their end tags
|
|
73
|
+
// count even when stray, https://html.spec.whatwg.org/multipage/parsing.html#formatting
|
|
74
|
+
const formattingElements = new Set(['a', 'b', 'big', 'code', 'em', 'font', 'i', 'nobr', 's', 'small', 'strike', 'strong', 'tt', 'u']);
|
|
49
75
|
|
|
50
76
|
// Form control elements (for conditional whitespace collapsing)
|
|
51
77
|
const formControlElements = new Set(['input', 'button', 'select', 'textarea', 'output', 'meter', 'progress']);
|
|
52
78
|
|
|
53
|
-
//
|
|
79
|
+
// End-tag spellings (`/a`) of a set of element names
|
|
80
|
+
/** @param {Iterable<string>} names */
|
|
81
|
+
const toEndTags = names => new Set(Array.from(names, name => '/' + name));
|
|
82
|
+
|
|
83
|
+
// Membership under either spelling, for the whitespace checks that ignore the slash;
|
|
84
|
+
// looking a tag up as it comes keeps the hot path from slicing one string per call
|
|
85
|
+
const formControlElementsEither = new Set([...formControlElements, ...toEndTags(formControlElements)]);
|
|
86
|
+
|
|
87
|
+
const inlineElementsToKeepWhitespaceBetweenEnd = toEndTags(inlineElementsToKeepWhitespaceBetween);
|
|
88
|
+
// Spelled as the tags that sit before and after the element: a start tag before it, an end tag
|
|
89
|
+
// (or, for void elements, the start tag) after it
|
|
90
|
+
const inlineElementsTransparentAfter = new Set([...toEndTags(inlineElementsTransparent), ...inlineElementsTransparentVoid]);
|
|
54
91
|
|
|
55
92
|
// Default attribute values (could apply to any element)
|
|
56
93
|
const generalDefaults = {
|
|
@@ -113,8 +150,7 @@ const isSimpleBoolean = new Set(['allowfullscreen', 'async', 'autofocus', 'autop
|
|
|
113
150
|
|
|
114
151
|
const isBooleanValue = new Set(['true', 'false']);
|
|
115
152
|
|
|
116
|
-
//
|
|
117
|
-
// maps each attribute name to the set of values that collapse to the bare attribute:
|
|
153
|
+
// Values that collapse to the bare attribute name:
|
|
118
154
|
// - `crossorigin=""` and `crossorigin="anonymous"` → `crossorigin` (anonymous is the default)
|
|
119
155
|
// - `contenteditable=""` → `contenteditable` (empty string means inherit/true)
|
|
120
156
|
const collapsibleValues = new Map([
|
|
@@ -122,12 +158,8 @@ const collapsibleValues = new Map([
|
|
|
122
158
|
['contenteditable', new Set([''])]
|
|
123
159
|
]);
|
|
124
160
|
|
|
125
|
-
// `srcset` elements
|
|
126
|
-
|
|
127
161
|
const srcsetElements = new Set(['img', 'source']);
|
|
128
162
|
|
|
129
|
-
// JSON script types
|
|
130
|
-
|
|
131
163
|
const jsonScriptTypes = new Set([
|
|
132
164
|
'application/json',
|
|
133
165
|
'application/ld+json',
|
|
@@ -140,11 +172,11 @@ const jsonScriptTypes = new Set([
|
|
|
140
172
|
'speculationrules',
|
|
141
173
|
]);
|
|
142
174
|
|
|
143
|
-
// Tag omission rules
|
|
144
|
-
|
|
145
|
-
// Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags with the following extensions:
|
|
175
|
+
// Tag omission rules from https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
|
|
176
|
+
// with the following extensions:
|
|
146
177
|
// - retain `<body>` if followed by `<noscript>`
|
|
147
|
-
// - `<rb>`, `<rt>`, `<rtc>`, `<rp>` follow HTML Ruby Markup Extensions draft
|
|
178
|
+
// - `<rb>`, `<rt>`, `<rtc>`, `<rp>` follow the HTML Ruby Markup Extensions draft:
|
|
179
|
+
// https://www.w3.org/TR/html-ruby-extensions/
|
|
148
180
|
// - retain all tags which are adjacent to non-standard HTML tags
|
|
149
181
|
|
|
150
182
|
const optionalStartTags = new Set(['html', 'head', 'body', 'colgroup', 'tbody']);
|
|
@@ -157,7 +189,8 @@ const descriptionElements = new Set(['dt', 'dd']);
|
|
|
157
189
|
|
|
158
190
|
const pBlockElements = new Set(['address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'div', 'dl', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'search', 'section', 'table', 'ul']);
|
|
159
191
|
|
|
160
|
-
|
|
192
|
+
// Elements whose end tags close an open `p` in browsers, so that `</p>` may be omitted before them
|
|
193
|
+
const pClosingParents = new Set(['address', 'applet', 'article', 'aside', 'blockquote', 'body', 'button', 'caption', 'center', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'html', 'li', 'listing', 'main', 'marquee', 'menu', 'nav', 'object', 'ol', 'pre', 'search', 'section', 'summary', 'td', 'template', 'th', 'ul']);
|
|
161
194
|
|
|
162
195
|
const rubyEndTagOmission = new Set(['rb', 'rt', 'rtc', 'rp']); // `</rb>`, `</rt>`, `</rp>` can be omitted if followed by `<rb>`, `<rt>`, `<rtc>`, or `<rp>`
|
|
163
196
|
|
|
@@ -181,7 +214,18 @@ const trailingElements = new Set(['dt', 'thead']);
|
|
|
181
214
|
|
|
182
215
|
const htmlElements = new Set(['a', 'abbr', 'acronym', 'address', 'applet', 'area', 'article', 'aside', 'audio', 'b', 'base', 'basefont', 'bdi', 'bdo', 'bgsound', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'content', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'image', 'img', 'input', 'ins', 'isindex', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'listing', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'multicol', 'nav', 'nobr', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'plaintext', 'pre', 'progress', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'search', 'section', 'select', 'selectedcontent', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr', 'xmp']);
|
|
183
216
|
|
|
184
|
-
//
|
|
217
|
+
// Doctype identifiers that set quirks mode, lowercase for their case-insensitive comparison
|
|
218
|
+
// https://html.spec.whatwg.org/multipage/parsing.html#the-initial-insertion-mode
|
|
219
|
+
|
|
220
|
+
const quirksPublicIds = new Set(['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html']);
|
|
221
|
+
|
|
222
|
+
const quirksSystemIds = new Set(['http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd']);
|
|
223
|
+
|
|
224
|
+
const quirksPublicIdPrefixes = ['+//silmaril//dtd html pro v0r11 19970101//', '-//as//dtd html 3.0 aswedit + extensions//', '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', '-//ietf//dtd html 2.0 level 1//', '-//ietf//dtd html 2.0 level 2//', '-//ietf//dtd html 2.0 strict level 1//', '-//ietf//dtd html 2.0 strict level 2//', '-//ietf//dtd html 2.0 strict//', '-//ietf//dtd html 2.0//', '-//ietf//dtd html 2.1e//', '-//ietf//dtd html 3.0//', '-//ietf//dtd html 3.2 final//', '-//ietf//dtd html 3.2//', '-//ietf//dtd html 3//', '-//ietf//dtd html level 0//', '-//ietf//dtd html level 1//', '-//ietf//dtd html level 2//', '-//ietf//dtd html level 3//', '-//ietf//dtd html strict level 0//', '-//ietf//dtd html strict level 1//', '-//ietf//dtd html strict level 2//', '-//ietf//dtd html strict level 3//', '-//ietf//dtd html strict//', '-//ietf//dtd html//', '-//metrius//dtd metrius presentational//', '-//microsoft//dtd internet explorer 2.0 html strict//', '-//microsoft//dtd internet explorer 2.0 html//', '-//microsoft//dtd internet explorer 2.0 tables//', '-//microsoft//dtd internet explorer 3.0 html strict//', '-//microsoft//dtd internet explorer 3.0 html//', '-//microsoft//dtd internet explorer 3.0 tables//', '-//netscape comm. corp.//dtd html//', '-//netscape comm. corp.//dtd strict html//', '-//o\'reilly and associates//dtd html 2.0//', '-//o\'reilly and associates//dtd html extended 1.0//', '-//o\'reilly and associates//dtd html extended relaxed 1.0//', '-//sq//dtd html 2.0 hotmetal + extensions//', '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', '-//spyglass//dtd html 2.0 extended//', '-//sun microsystems corp.//dtd hotjava html//', '-//sun microsystems corp.//dtd hotjava strict html//', '-//w3c//dtd html 3 1995-03-24//', '-//w3c//dtd html 3.2 draft//', '-//w3c//dtd html 3.2 final//', '-//w3c//dtd html 3.2//', '-//w3c//dtd html 3.2s draft//', '-//w3c//dtd html 4.0 frameset//', '-//w3c//dtd html 4.0 transitional//', '-//w3c//dtd html experimental 19960712//', '-//w3c//dtd html experimental 970421//', '-//w3c//dtd w3 html//', '-//w3o//dtd w3 html 3.0//', '-//c.0//', '-//webtechs//dtd mozilla html//'];
|
|
225
|
+
|
|
226
|
+
// Prefixes that set quirks mode only without a system identifier or with an empty one
|
|
227
|
+
// (limited-quirks mode otherwise)
|
|
228
|
+
const quirksPublicIdPrefixesNoSystemId = ['-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//'];
|
|
185
229
|
|
|
186
230
|
const specialContentElements = new Set(['script', 'style']);
|
|
187
231
|
|
|
@@ -207,7 +251,54 @@ const escapableRawTextElements = new Set(['textarea', 'title']);
|
|
|
207
251
|
// of `textarea` and `title`, where they are resolved as they are anywhere else
|
|
208
252
|
const rawTextElements = new Set([...specialContentElements, ...genericRawTextElements]);
|
|
209
253
|
|
|
210
|
-
//
|
|
254
|
+
// Marks the error for a minifier that was asked for but isn’t available—a
|
|
255
|
+
// configuration error, and so not one that `continueOnMinifyError` waves through
|
|
256
|
+
const MISSING_DEPENDENCY = 'HMN_MISSING_DEPENDENCY';
|
|
257
|
+
|
|
258
|
+
// SVGO’s `preset-default` treats an SVG as a file of its own, but an inline SVG’s
|
|
259
|
+
// IDs, `style` rules, hidden sprites, and empty attributes (`[data-v-…]` hooks, `alt=""`)
|
|
260
|
+
// reach into the rest of the document, so the plugins that assume otherwise stay off,
|
|
261
|
+
// and `minifyStyles` keeps the rules the SVG itself does not use
|
|
262
|
+
const svgoPluginsInline = [{
|
|
263
|
+
name: 'preset-default',
|
|
264
|
+
params: {
|
|
265
|
+
overrides: {
|
|
266
|
+
cleanupIds: false,
|
|
267
|
+
inlineStyles: false,
|
|
268
|
+
minifyStyles: { usage: false },
|
|
269
|
+
removeEmptyAttrs: false,
|
|
270
|
+
removeHiddenElems: false,
|
|
271
|
+
removeUnknownsAndDefaults: { keepRoleAttr: true }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}];
|
|
275
|
+
|
|
276
|
+
// Mixed-case names the HTML parser gives SVG elements and attributes and MathML attributes, keyed
|
|
277
|
+
// by the lowercase it reads every other name as (no lowercase name is both an element and an
|
|
278
|
+
// attribute of different case, so one table serves both)
|
|
279
|
+
// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
|
|
280
|
+
const namesForeignMixedCase = new Map([
|
|
281
|
+
// SVG elements
|
|
282
|
+
'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animateColor', 'animateMotion', 'animateTransform',
|
|
283
|
+
'clipPath', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix',
|
|
284
|
+
'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA',
|
|
285
|
+
'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode',
|
|
286
|
+
'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile',
|
|
287
|
+
'feTurbulence', 'foreignObject', 'glyphRef', 'linearGradient', 'radialGradient', 'textPath',
|
|
288
|
+
// SVG attributes
|
|
289
|
+
'attributeName', 'attributeType', 'baseFrequency', 'baseProfile', 'calcMode', 'clipPathUnits',
|
|
290
|
+
'diffuseConstant', 'edgeMode', 'filterUnits', 'gradientTransform', 'gradientUnits',
|
|
291
|
+
'kernelMatrix', 'kernelUnitLength', 'keyPoints', 'keySplines', 'keyTimes', 'lengthAdjust',
|
|
292
|
+
'limitingConeAngle', 'markerHeight', 'markerUnits', 'markerWidth', 'maskContentUnits', 'maskUnits',
|
|
293
|
+
'numOctaves', 'pathLength', 'patternContentUnits', 'patternTransform', 'patternUnits', 'pointsAtX',
|
|
294
|
+
'pointsAtY', 'pointsAtZ', 'preserveAlpha', 'preserveAspectRatio', 'primitiveUnits', 'refX', 'refY',
|
|
295
|
+
'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'specularConstant',
|
|
296
|
+
'specularExponent', 'spreadMethod', 'startOffset', 'stdDeviation', 'stitchTiles', 'surfaceScale',
|
|
297
|
+
'systemLanguage', 'tableValues', 'targetX', 'targetY', 'textLength', 'viewBox', 'viewTarget',
|
|
298
|
+
'xChannelSelector', 'yChannelSelector', 'zoomAndPan',
|
|
299
|
+
// MathML attributes
|
|
300
|
+
'definitionURL'
|
|
301
|
+
].map(name => [name.toLowerCase(), name]));
|
|
211
302
|
|
|
212
303
|
export {
|
|
213
304
|
// Regex patterns
|
|
@@ -227,18 +318,29 @@ export {
|
|
|
227
318
|
RE_LEGACY_ENTITIES,
|
|
228
319
|
RE_ESCAPE_LT,
|
|
229
320
|
RE_ESCAPE_LT_RAW_TEXT,
|
|
321
|
+
RE_XML_ESCAPE_TEXT,
|
|
322
|
+
RE_XML_ESCAPE_ATTR,
|
|
230
323
|
RE_HTML_ENCODING,
|
|
324
|
+
RE_DOCTYPE,
|
|
231
325
|
RE_ATTR_WS_CHECK,
|
|
232
326
|
RE_ATTR_WS_COLLAPSE,
|
|
233
327
|
RE_ATTR_WS_TRIM,
|
|
328
|
+
RE_WS_CHAR,
|
|
234
329
|
RE_STYLE_ELEMENT,
|
|
235
330
|
RE_EMPTY_ATTRIBUTE,
|
|
236
331
|
|
|
237
332
|
// Inline element sets
|
|
333
|
+
formattingElements,
|
|
238
334
|
inlineElementsToKeepWhitespaceAround,
|
|
239
335
|
inlineElementsToKeepWhitespaceWithin,
|
|
336
|
+
inlineElementsToKeepWhitespaceBetween,
|
|
337
|
+
inlineElementsToKeepWhitespaceBetweenEnd,
|
|
338
|
+
inlineElementsTransparent,
|
|
339
|
+
inlineElementsTransparentAfter,
|
|
240
340
|
inlineElementsToKeepWhitespace,
|
|
241
|
-
|
|
341
|
+
processingInstructionTag,
|
|
342
|
+
formControlElementsEither,
|
|
343
|
+
toEndTags,
|
|
242
344
|
|
|
243
345
|
// Default values
|
|
244
346
|
generalDefaults,
|
|
@@ -256,6 +358,9 @@ export {
|
|
|
256
358
|
|
|
257
359
|
// Misc
|
|
258
360
|
srcsetElements,
|
|
361
|
+
MISSING_DEPENDENCY,
|
|
362
|
+
namesForeignMixedCase,
|
|
363
|
+
svgoPluginsInline,
|
|
259
364
|
|
|
260
365
|
// Tag omission rules
|
|
261
366
|
optionalStartTags,
|
|
@@ -263,7 +368,7 @@ export {
|
|
|
263
368
|
headerElements,
|
|
264
369
|
descriptionElements,
|
|
265
370
|
pBlockElements,
|
|
266
|
-
|
|
371
|
+
pClosingParents,
|
|
267
372
|
rubyEndTagOmission,
|
|
268
373
|
rubyRtcEndTagOmission,
|
|
269
374
|
optionElements,
|
|
@@ -276,6 +381,12 @@ export {
|
|
|
276
381
|
trailingElements,
|
|
277
382
|
htmlElements,
|
|
278
383
|
|
|
384
|
+
// Doctype identifiers
|
|
385
|
+
quirksPublicIds,
|
|
386
|
+
quirksSystemIds,
|
|
387
|
+
quirksPublicIdPrefixes,
|
|
388
|
+
quirksPublicIdPrefixesNoSystemId,
|
|
389
|
+
|
|
279
390
|
// Special content elements
|
|
280
391
|
specialContentElements,
|
|
281
392
|
genericRawTextElements,
|
package/src/lib/content.js
CHANGED
|
@@ -13,8 +13,7 @@ import { trimWhitespace } from './whitespace.js';
|
|
|
13
13
|
|
|
14
14
|
// CSS processing
|
|
15
15
|
|
|
16
|
-
//
|
|
17
|
-
// This ensures proper context for CSS minification
|
|
16
|
+
// Give bare declarations and media queries a parseable context for CSS minifiers
|
|
18
17
|
/**
|
|
19
18
|
* @param {string} text
|
|
20
19
|
* @param {string} [type]
|
|
@@ -92,11 +91,9 @@ async function processScript(text, options, currentAttrs, minifyHTML) {
|
|
|
92
91
|
if (attrName === 'type') {
|
|
93
92
|
const rawValue = attr.value;
|
|
94
93
|
const normalizedValue = trimWhitespace((rawValue || '').split(/;/, 2)[0] ?? '').toLowerCase();
|
|
95
|
-
// Minify JSON script types automatically
|
|
96
94
|
if (jsonScriptTypes.has(normalizedValue)) {
|
|
97
95
|
return minifyJson(text, options);
|
|
98
96
|
}
|
|
99
|
-
// Process custom script types if specified
|
|
100
97
|
if (options.processScripts && rawValue && options.processScripts.indexOf(rawValue) > -1) {
|
|
101
98
|
return await minifyHTML(text, options);
|
|
102
99
|
}
|
|
@@ -175,8 +172,6 @@ function extractScriptBodies(html) {
|
|
|
175
172
|
return bodies;
|
|
176
173
|
}
|
|
177
174
|
|
|
178
|
-
// Exports
|
|
179
|
-
|
|
180
175
|
export {
|
|
181
176
|
// CSS
|
|
182
177
|
wrapCSS,
|
package/src/lib/elements.js
CHANGED
|
@@ -18,8 +18,6 @@ import { hasAttrName } from './attributes.js';
|
|
|
18
18
|
/** @import { HTMLAttribute } from './attributes.js' */
|
|
19
19
|
/** @import { ProcessedOptions } from './options.js' */
|
|
20
20
|
|
|
21
|
-
// Tag omission rules
|
|
22
|
-
|
|
23
21
|
/**
|
|
24
22
|
* @param {string} optionalStartTag
|
|
25
23
|
* @param {string} tag
|
|
@@ -94,8 +92,6 @@ function canRemovePrecedingTag(optionalEndTag, tag) {
|
|
|
94
92
|
return false;
|
|
95
93
|
}
|
|
96
94
|
|
|
97
|
-
// Element removal logic
|
|
98
|
-
|
|
99
95
|
/**
|
|
100
96
|
* @param {string} tag
|
|
101
97
|
* @param {HTMLAttribute[]} attrs
|
|
@@ -111,7 +107,24 @@ function canRemoveElement(tag, attrs) {
|
|
|
111
107
|
return false;
|
|
112
108
|
}
|
|
113
109
|
|
|
110
|
+
// Nor must elements that carry accessibility semantics, take focus, or point elsewhere
|
|
111
|
+
// with `for` (a `label` activates a control, an `output` shows its result, a `template`
|
|
112
|
+
// replaces content, even with nothing), unless the value is empty
|
|
113
|
+
const takesFor = tag === 'label' || tag === 'output' || tag === 'template';
|
|
114
|
+
for (const attr of attrs) {
|
|
115
|
+
const name = attr.name.toLowerCase();
|
|
116
|
+
if ((name === 'role' || name === 'tabindex' || name.startsWith('aria-') || (takesFor && name === 'for')) && attr.value?.trim()) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Custom elements and `canvas` are there for scripts to fill or draw into
|
|
122
|
+
if (tag.includes('-')) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
114
126
|
switch (tag) {
|
|
127
|
+
case 'canvas':
|
|
115
128
|
case 'textarea':
|
|
116
129
|
return false;
|
|
117
130
|
case 'audio':
|
|
@@ -161,7 +174,6 @@ function parseElementSpec(str, options) {
|
|
|
161
174
|
}
|
|
162
175
|
|
|
163
176
|
// HTML-like markup: `<span aria-hidden='true'>` or `<td></td>`
|
|
164
|
-
// Extract opening tag using regex
|
|
165
177
|
const match = trimmed.match(/^<([a-zA-Z][\w:-]*)((?:\s+[^>]*)?)>/);
|
|
166
178
|
if (!match) {
|
|
167
179
|
return null;
|
|
@@ -174,7 +186,6 @@ function parseElementSpec(str, options) {
|
|
|
174
186
|
return { tag, attrs: null };
|
|
175
187
|
}
|
|
176
188
|
|
|
177
|
-
// Parse attributes from string
|
|
178
189
|
/** @type {{[key: string]: string | undefined}} */
|
|
179
190
|
const attrs = {};
|
|
180
191
|
const attrRegex = /([a-zA-Z][\w:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>/]+)))?/g;
|
|
@@ -226,17 +237,14 @@ function parseRemoveEmptyElementsExcept(input, options) {
|
|
|
226
237
|
*/
|
|
227
238
|
function shouldPreserveEmptyElement(tag, attrs, preserveList) {
|
|
228
239
|
for (const spec of preserveList) {
|
|
229
|
-
// Tag name must match
|
|
230
240
|
if (spec.tag !== tag) {
|
|
231
241
|
continue;
|
|
232
242
|
}
|
|
233
243
|
|
|
234
|
-
// If no attributes specified in spec, tag match is enough
|
|
235
244
|
if (!spec.attrs) {
|
|
236
245
|
return true;
|
|
237
246
|
}
|
|
238
247
|
|
|
239
|
-
// Check if all specified attributes match
|
|
240
248
|
const allAttrsMatch = Object.entries(spec.attrs).every(([name, value]) => {
|
|
241
249
|
const attr = attrs.find(a => a.name === name);
|
|
242
250
|
if (!attr) {
|
|
@@ -246,7 +254,6 @@ function shouldPreserveEmptyElement(tag, attrs, preserveList) {
|
|
|
246
254
|
if (value === undefined) {
|
|
247
255
|
return true;
|
|
248
256
|
}
|
|
249
|
-
// Valued attribute must match exactly
|
|
250
257
|
return attr.value === value;
|
|
251
258
|
});
|
|
252
259
|
|
|
@@ -258,8 +265,6 @@ function shouldPreserveEmptyElement(tag, attrs, preserveList) {
|
|
|
258
265
|
return false;
|
|
259
266
|
}
|
|
260
267
|
|
|
261
|
-
// Exports
|
|
262
|
-
|
|
263
268
|
export {
|
|
264
269
|
// Tag omission
|
|
265
270
|
canRemoveParentTag,
|
package/src/lib/file-pool.js
CHANGED
|
@@ -15,12 +15,13 @@
|
|
|
15
15
|
* worker runs its own isolate and warms up its own JIT, so the useful worker count tops
|
|
16
16
|
* out well short of the core count.
|
|
17
17
|
*
|
|
18
|
-
* Node-only: cli.js loads this module lazily and minifies in
|
|
18
|
+
* Node-only: cli.js loads this module lazily and minifies in-process wherever worker
|
|
19
19
|
* threads are unavailable or the options can’t cross a structured clone.
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
import fs from 'node:fs';
|
|
23
23
|
import { isMainThread, parentPort, workerData, Worker } from 'node:worker_threads';
|
|
24
|
+
import { writeFileAtomic } from './file-write.js';
|
|
24
25
|
|
|
25
26
|
// This module is its own worker entry point: The pool spawns it by URL and the branch
|
|
26
27
|
// below runs in the spawned copy. Keeping both halves in one file keeps the message
|
|
@@ -61,7 +62,7 @@ if (!isMainThread && parentPort) {
|
|
|
61
62
|
const minified = await minify(data, taskOptions);
|
|
62
63
|
if (!task.dryRun) {
|
|
63
64
|
stage = 'write';
|
|
64
|
-
await
|
|
65
|
+
await writeFileAtomic(task.outputFile, minified);
|
|
65
66
|
}
|
|
66
67
|
port.postMessage({
|
|
67
68
|
id: task.id,
|
|
@@ -76,6 +77,21 @@ if (!isMainThread && parentPort) {
|
|
|
76
77
|
|
|
77
78
|
const urlWorker = new URL(import.meta.url);
|
|
78
79
|
|
|
80
|
+
/**
|
|
81
|
+
* The order to hand files to the pool in: Largest first, so the file that takes longest
|
|
82
|
+
* doesn’t start last and hold up the run on its own (ties keep their order)
|
|
83
|
+
* @template T
|
|
84
|
+
* @param {T[]} items - One per file
|
|
85
|
+
* @param {number[]} sizes - Byte size per file, in the order of `items`
|
|
86
|
+
* @returns {T[]}
|
|
87
|
+
*/
|
|
88
|
+
export function orderLargestFirst(items, sizes) {
|
|
89
|
+
return items
|
|
90
|
+
.map((item, index) => ({ item, size: sizes[index] ?? 0 }))
|
|
91
|
+
.sort((a, b) => b.size - a.size)
|
|
92
|
+
.map(entry => entry.item);
|
|
93
|
+
}
|
|
94
|
+
|
|
79
95
|
/**
|
|
80
96
|
* @param {object} args
|
|
81
97
|
* @param {import('../htmlminifier.js').MinifierOptions} args.options
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output writing for the CLI, shared by in-process runs and the worker pool
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
// A random name is taken by chance only, so a few attempts are plenty
|
|
10
|
+
const ATTEMPTS_MAX = 10;
|
|
11
|
+
// As many links as a system commonly follows before reporting a loop
|
|
12
|
+
const LINKS_MAX = 40;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The file a write replaces: the output itself or, for a symlink, the file it
|
|
16
|
+
* points to—followed by hand where that file does not exist yet, which
|
|
17
|
+
* `realpath` cannot resolve
|
|
18
|
+
* @param {string} outputFile
|
|
19
|
+
* @returns {Promise<string>}
|
|
20
|
+
*/
|
|
21
|
+
async function resolveTarget(outputFile) {
|
|
22
|
+
let file = outputFile;
|
|
23
|
+
for (let i = 0; i < LINKS_MAX; i++) {
|
|
24
|
+
try {
|
|
25
|
+
return await fs.promises.realpath(file);
|
|
26
|
+
} catch {
|
|
27
|
+
const link = await fs.promises.readlink(file).catch(() => undefined);
|
|
28
|
+
if (link === undefined) return file;
|
|
29
|
+
// A relative link is read from the real location of its folder
|
|
30
|
+
const dir = await fs.promises.realpath(path.dirname(file)).catch(() => path.dirname(file));
|
|
31
|
+
file = path.resolve(dir, link);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// A loop, which writing through wouldn’t resolve either—refused, so the rename can’t replace it
|
|
35
|
+
throw Object.assign(new Error(`ELOOP: Too many symbolic links encountered, '${outputFile}'`), { code: 'ELOOP', path: outputFile });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Create a temporary file next to the target under a random name, exclusively,
|
|
40
|
+
* so that it can neither be predicted nor write through a file or link already there
|
|
41
|
+
* @param {string} targetFile
|
|
42
|
+
* @param {number | undefined} mode
|
|
43
|
+
*/
|
|
44
|
+
async function openTempFile(targetFile, mode) {
|
|
45
|
+
for (let attempt = 1; ; attempt++) {
|
|
46
|
+
const tempFile = path.join(path.dirname(targetFile), `.${path.basename(targetFile)}.${crypto.randomBytes(8).toString('hex')}.tmp`);
|
|
47
|
+
try {
|
|
48
|
+
return { tempFile, handle: await fs.promises.open(tempFile, 'wx', mode) };
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (/** @type {any} */ (err).code !== 'EEXIST' || attempt >= ATTEMPTS_MAX) throw err;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Write a file by way of a temporary file in the same folder, so that an exit
|
|
57
|
+
* that leaves no chance to clean up—a native crash in a minifier, an OOM
|
|
58
|
+
* kill—cannot leave a half-written file where the output belongs
|
|
59
|
+
* @param {string} outputFile
|
|
60
|
+
* @param {string} data
|
|
61
|
+
*/
|
|
62
|
+
export async function writeFileAtomic(outputFile, data) {
|
|
63
|
+
// A rename would replace a symlink itself, so work on the file it points to
|
|
64
|
+
const targetFile = await resolveTarget(outputFile);
|
|
65
|
+
// The rename replaces the output rather than writing through it, so its mode is carried over
|
|
66
|
+
const stats = await fs.promises.stat(targetFile).catch(() => undefined);
|
|
67
|
+
const mode = stats ? stats.mode & 0o7777 : undefined;
|
|
68
|
+
|
|
69
|
+
// Outside the `try`, so that only a file this write created is ever removed
|
|
70
|
+
const { tempFile, handle } = await openTempFile(targetFile, mode);
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
try {
|
|
74
|
+
await handle.writeFile(data, 'utf8');
|
|
75
|
+
} finally {
|
|
76
|
+
await handle.close();
|
|
77
|
+
}
|
|
78
|
+
// `mode` on creation is subject to the umask, so the exact bits have to be set separately
|
|
79
|
+
if (mode !== undefined) {
|
|
80
|
+
await fs.promises.chmod(tempFile, mode);
|
|
81
|
+
}
|
|
82
|
+
await fs.promises.rename(tempFile, targetFile);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
await fs.promises.rm(tempFile, { force: true });
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|