@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.
Files changed (46) hide show
  1. package/README.md +147 -33
  2. package/cli.js +70 -54
  3. package/dist/types/htmlminifier.d.ts +87 -33
  4. package/dist/types/htmlminifier.d.ts.map +1 -1
  5. package/dist/types/htmlparser.d.ts +4 -1
  6. package/dist/types/htmlparser.d.ts.map +1 -1
  7. package/dist/types/lib/attributes.d.ts +12 -10
  8. package/dist/types/lib/attributes.d.ts.map +1 -1
  9. package/dist/types/lib/constants.d.ts +38 -3
  10. package/dist/types/lib/constants.d.ts.map +1 -1
  11. package/dist/types/lib/content.d.ts.map +1 -1
  12. package/dist/types/lib/elements.d.ts.map +1 -1
  13. package/dist/types/lib/fragments.d.ts +1 -0
  14. package/dist/types/lib/fragments.d.ts.map +1 -1
  15. package/dist/types/lib/option-definitions.d.ts.map +1 -1
  16. package/dist/types/lib/options.d.ts +14 -46
  17. package/dist/types/lib/options.d.ts.map +1 -1
  18. package/dist/types/lib/unused-css.d.ts +34 -4
  19. package/dist/types/lib/unused-css.d.ts.map +1 -1
  20. package/dist/types/lib/urls.d.ts.map +1 -1
  21. package/dist/types/lib/utils.d.ts +31 -1
  22. package/dist/types/lib/utils.d.ts.map +1 -1
  23. package/dist/types/lib/whitespace.d.ts +57 -5
  24. package/dist/types/lib/whitespace.d.ts.map +1 -1
  25. package/dist/types/presets.d.ts +1 -2
  26. package/dist/types/presets.d.ts.map +1 -1
  27. package/dist/types/tokenchain.d.ts.map +1 -1
  28. package/html-minifier-next.schema.json +15 -7
  29. package/package.json +17 -18
  30. package/src/htmlminifier.js +1103 -392
  31. package/src/htmlparser.js +452 -200
  32. package/src/lib/attributes.js +201 -112
  33. package/src/lib/constants.js +130 -19
  34. package/src/lib/content.js +1 -6
  35. package/src/lib/elements.js +17 -12
  36. package/src/lib/file-pool.js +18 -2
  37. package/src/lib/file-write.js +87 -0
  38. package/src/lib/fragments.js +74 -8
  39. package/src/lib/option-definitions.js +17 -10
  40. package/src/lib/options.js +151 -71
  41. package/src/lib/unused-css.js +145 -27
  42. package/src/lib/urls.js +0 -9
  43. package/src/lib/utils.js +210 -45
  44. package/src/lib/whitespace.js +173 -63
  45. package/src/presets.js +1 -2
  46. package/src/tokenchain.js +1 -4
@@ -2,7 +2,7 @@
2
2
  * Unused-CSS removal
3
3
  */
4
4
 
5
- import { findTagEnd } from './utils.js';
5
+ import { findTagEnd, hashContent } from './utils.js';
6
6
 
7
7
  // Attributes whose values name elements by ID or hold space-separated ID lists
8
8
  const idReferenceAttributes = new Set([
@@ -50,12 +50,16 @@ const fragmentURLPattern = /url\(\s*['"]?#([^)'"\s]+)/gi;
50
50
  const stringLiteralPattern = /'((?:[^'\\\n]|\\.)*)'|"((?:[^"\\\n]|\\.)*)"|`((?:[^`\\]|\\.)*)`/g;
51
51
 
52
52
  // CSS identifiers may contain escapes (`.md\:flex`, `.w-1\/2`), which have to be
53
- // resolved before comparing them against the plain tokens found in the markup
54
- const cssIdentifierPattern = /(?<![\w\\-])[.#]((?:[-_a-zA-Z]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])(?:[-\w]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])*)/g;
53
+ // resolved before comparing them against the plain tokens found in the markup. A
54
+ // symbol may follow another name (`p.note`, `.a.b`); matches outside selectors
55
+ // (`#fff`, `a.png`) are harmless, as only selectors are checked against the list.
56
+ const cssIdentifierPattern = /(?<!\\)[.#]((?:[-_a-zA-Z]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])(?:[-\w]|\\[0-9a-fA-F]{1,6}[ \t\n]?|\\[^\n0-9a-fA-F])*)/g;
55
57
  // `unusedSymbols` also drops `@keyframes` and `@counter-style` rules by name, so any
56
58
  // name used there is off limits even when no element carries it as a class or ID
57
59
  const reservedAtRulePattern = /@(?:-\w+-)?(?:keyframes|counter-style)\s+(-?[_a-zA-Z][\w-]*)/gi;
58
60
  const escapePattern = /\\(?:([0-9a-fA-F]{1,6})[ \t\n]?|(.))/g;
61
+ // Run over case-folded markup; matches inside comments and scripts only add names
62
+ const startTagPattern = /<([a-z][^\s/>]*)/g;
59
63
 
60
64
  /**
61
65
  * Resolve CSS escape sequences in an identifier.
@@ -70,7 +74,7 @@ function unescapeIdentifier(identifier) {
70
74
  if (!hex) {
71
75
  return literal;
72
76
  }
73
- // Per CSS Syntax spec, a null, surrogate, or out-of-range escape becomes U+FFFD
77
+ // Per CSS Syntax spec, a null, surrogate, or out-of-range escape becomes `U+FFFD`
74
78
  const code = parseInt(hex, 16);
75
79
  return (code === 0 || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF))
76
80
  ? '\uFFFD'
@@ -179,10 +183,11 @@ function findRawTextElements(haystack, tagName) {
179
183
  *
180
184
  * @param {string} html - Raw document markup
181
185
  * @param {boolean} includeScripts - Also treat identifiers inside inline `script` elements as used
182
- * @param {((text: string) => string)} [decode] - Resolves character references in attribute values
186
+ * @param {((text: string) => string)} [decode] - Resolves character references in attribute values and foreign script contents
187
+ * @param {Set<string>} [elements] - Receives the element names the markup uses, lowercased, and the identifiers found in scripts, as possible element names
183
188
  * @returns {Set<string>} Symbols to keep
184
189
  */
185
- function collectUsedSymbols(html, includeScripts, decode) {
190
+ function collectUsedSymbols(html, includeScripts, decode, elements) {
186
191
  const used = new Set();
187
192
  const haystack = foldCase(html);
188
193
 
@@ -196,11 +201,16 @@ function collectUsedSymbols(html, includeScripts, decode) {
196
201
  .filter(element => element.closed)
197
202
  .map(element => ({ start: element.bodyStart, end: element.bodyEnd }));
198
203
 
199
- const addIdentifiers = (/** @type {string} */ text) => {
204
+ if (elements) {
205
+ collectUsedElements(haystack, skipped, elements);
206
+ }
207
+
208
+ const addIdentifiers = (/** @type {string} */ text, /** @type {Set<string> | undefined} */ names = undefined) => {
200
209
  identifierPattern.lastIndex = 0;
201
210
  let identifier;
202
211
  while ((identifier = identifierPattern.exec(text))) {
203
212
  used.add(identifier[0]);
213
+ names?.add(identifier[0].toLowerCase());
204
214
  }
205
215
  };
206
216
 
@@ -252,19 +262,23 @@ function collectUsedSymbols(html, includeScripts, decode) {
252
262
  }
253
263
 
254
264
  if (includeScripts) {
255
- // Script contents are raw text, so character references stay literal;
256
- // an unclosed `script` runs to the end of the document, as it does in a browser
265
+ // Script contents are raw text, so character references stay literal
266
+ // except in SVG and MathML, where they are resolved; as the namespace
267
+ // isn’t tracked here, both readings count. An unclosed `script` runs
268
+ // to the end of the document, as it does in a browser.
257
269
  skipCursor = 0;
258
270
  for (const element of findRawTextElements(haystack, 'script')) {
259
271
  if (isSkipped(element.start)) {
260
272
  continue;
261
273
  }
262
274
  const body = html.slice(element.bodyStart, element.bodyEnd);
263
- addIdentifiers(body);
264
- stringLiteralPattern.lastIndex = 0;
265
- let literal;
266
- while ((literal = stringLiteralPattern.exec(body))) {
267
- addTokens(literal[1] ?? literal[2] ?? literal[3] ?? '');
275
+ for (const text of (decode && body.indexOf('&') !== -1) ? [body, decode(body)] : [body]) {
276
+ addIdentifiers(text, elements);
277
+ stringLiteralPattern.lastIndex = 0;
278
+ let literal;
279
+ while ((literal = stringLiteralPattern.exec(text))) {
280
+ addTokens(literal[1] ?? literal[2] ?? literal[3] ?? '');
281
+ }
268
282
  }
269
283
  }
270
284
  }
@@ -273,7 +287,7 @@ function collectUsedSymbols(html, includeScripts, decode) {
273
287
  }
274
288
 
275
289
  /**
276
- * Determine which class/ID symbols a style sheet defines but the document never references.
290
+ * Determine which class/ID symbols a style sheet defines but the document doesn’t reference.
277
291
  * @param {string} css - Style sheet contents
278
292
  * @param {Set<string>} used - Symbols the document references
279
293
  * @param {Array<string | RegExp>} safelist - Symbols to keep regardless
@@ -298,18 +312,7 @@ function findUnusedSymbols(css, used, safelist) {
298
312
  continue;
299
313
  }
300
314
  seen.add(symbol);
301
- if (used.has(symbol) || reserved.has(symbol)) {
302
- continue;
303
- }
304
- if (safelist.some(entry => {
305
- if (!(entry instanceof RegExp)) {
306
- return entry === symbol;
307
- }
308
- // `test()` advances `lastIndex` on global and sticky patterns, which would
309
- // make a safelist entry match only every other symbol
310
- entry.lastIndex = 0;
311
- return entry.test(symbol);
312
- })) {
315
+ if (used.has(symbol) || reserved.has(symbol) || isSafelisted(symbol, safelist)) {
313
316
  continue;
314
317
  }
315
318
  unused.push(symbol);
@@ -318,6 +321,119 @@ function findUnusedSymbols(css, used, safelist) {
318
321
  return unused;
319
322
  }
320
323
 
324
+ /**
325
+ * @param {string} symbol
326
+ * @param {Array<string | RegExp>} safelist
327
+ * @returns {boolean}
328
+ */
329
+ function isSafelisted(symbol, safelist) {
330
+ return safelist.some(entry => {
331
+ if (!(entry instanceof RegExp)) {
332
+ return entry === symbol;
333
+ }
334
+ // `test()` advances `lastIndex` on global and sticky patterns, which would
335
+ // make a safelist entry match only every other symbol
336
+ entry.lastIndex = 0;
337
+ return entry.test(symbol);
338
+ });
339
+ }
340
+
341
+ /**
342
+ * Collect the element names a document contains, including those the parser
343
+ * supplies when the markup leaves them out.
344
+ * @param {string} haystack - Case-folded markup, as returned by `foldCase`
345
+ * @param {Array<{start: number, end: number}>} skipped - Style sheet bodies, in document order
346
+ * @param {Set<string>} elements - Lowercase element names, added to
347
+ */
348
+ function collectUsedElements(haystack, skipped, elements) {
349
+ elements.add('html');
350
+ elements.add('head');
351
+ elements.add('body');
352
+
353
+ let skipIndex = 0;
354
+ startTagPattern.lastIndex = 0;
355
+ let match;
356
+ while ((match = startTagPattern.exec(haystack))) {
357
+ while (skipIndex < skipped.length && (skipped[skipIndex]?.end ?? 0) <= match.index) {
358
+ skipIndex++;
359
+ }
360
+ const element = skipped[skipIndex];
361
+ if (element && match.index >= element.start) {
362
+ continue;
363
+ }
364
+ elements.add(match[1] ?? '');
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Build the unused-CSS context for a document.
370
+ * @param {string} html - Raw document markup
371
+ * @param {boolean} includeScripts - Also treat identifiers inside inline `script` elements as used
372
+ * @param {((text: string) => string)} [decode] - Resolves character references in attribute values and foreign script contents
373
+ * @returns {{usedSymbols: Set<string>, usedElements: Set<string>, usedElementsKey: string}}
374
+ */
375
+ function collectUsage(html, includeScripts, decode) {
376
+ // A script may create the elements a rule is for, so its identifiers count as names, too
377
+ const usedElements = new Set();
378
+ const usedSymbols = collectUsedSymbols(html, includeScripts, decode, usedElements);
379
+ // Elements the parser supplies inside a `table`, added after script identifiers, as a script
380
+ // may create a `table`, too
381
+ if (usedElements.has('table')) {
382
+ usedElements.add('tbody');
383
+ usedElements.add('tr');
384
+ }
385
+ if (usedElements.has('col')) {
386
+ usedElements.add('colgroup');
387
+ }
388
+ return {
389
+ usedSymbols,
390
+ usedElements,
391
+ // The CSS cache outlives a document, so its keys tell element sets apart
392
+ usedElementsKey: String(hashContent([...usedElements].sort().join(' ')))
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Create a Lightning CSS `Selector` visitor that drops selectors naming an unused
398
+ * class, ID, or element from their list, so the rule stays for the selectors that
399
+ * remain (`unusedSymbols` alone only removes rules whose selectors are all unused).
400
+ *
401
+ * Only a selector’s own compounds are judged: Names inside pseudo-class and
402
+ * pseudo-element arguments (`:not(.x)`, `:host(.x)`) are left alone.
403
+ *
404
+ * @param {string[]} unusedSymbols - Class/ID symbols safe to remove, from `findUnusedSymbols`
405
+ * @param {Set<string>} usedElements - Lowercase element names the document contains or its scripts name
406
+ * @param {Array<string | RegExp>} safelist - Symbols to keep regardless
407
+ * @returns {(selector: Array<{type: string, name?: string}>) => [] | undefined}
408
+ */
409
+ function createSelectorPruner(unusedSymbols, usedElements, safelist) {
410
+ const unused = new Set(unusedSymbols);
411
+ /** @type {Map<string, boolean>} */
412
+ const unusedElements = new Map();
413
+ const isUnusedElement = (/** @type {string} */ name) => {
414
+ let result = unusedElements.get(name);
415
+ if (result === undefined) {
416
+ result = !usedElements.has(name.toLowerCase()) && !isSafelisted(name, safelist);
417
+ unusedElements.set(name, result);
418
+ }
419
+ return result;
420
+ };
421
+
422
+ return selector => {
423
+ for (const component of selector) {
424
+ const name = component.name;
425
+ if (name === undefined) {
426
+ continue;
427
+ }
428
+ if (((component.type === 'class' || component.type === 'id') && unused.has(name)) ||
429
+ (component.type === 'type' && isUnusedElement(name))) {
430
+ return [];
431
+ }
432
+ }
433
+ return undefined;
434
+ };
435
+ }
436
+
321
437
  const unusedCSSKeys = new Set(['safelist', 'scripts']);
322
438
 
323
439
  /**
@@ -373,7 +489,9 @@ function normalizeUnusedCSSOptions(option, warn) {
373
489
  }
374
490
 
375
491
  export {
492
+ collectUsage,
376
493
  collectUsedSymbols,
494
+ createSelectorPruner,
377
495
  findUnusedSymbols,
378
496
  normalizeUnusedCSSOptions
379
497
  };
package/src/lib/urls.js CHANGED
@@ -32,7 +32,6 @@ function relativize(baseDir, targetPath) {
32
32
  const targetSegments = targetPath.split('/').filter(Boolean);
33
33
  const isDirectoryTarget = targetPath.endsWith('/');
34
34
 
35
- // Find common prefix length
36
35
  let common = 0;
37
36
  while (
38
37
  common < baseSegments.length &&
@@ -49,7 +48,6 @@ function relativize(baseDir, targetPath) {
49
48
 
50
49
  let relative = '../'.repeat(ups) + remaining.join('/');
51
50
 
52
- // Preserve trailing slash
53
51
  if (isDirectoryTarget && relative !== '' && !relative.endsWith('/')) {
54
52
  relative += '/';
55
53
  }
@@ -112,15 +110,12 @@ export function createUrlMinifier(site) {
112
110
  }
113
111
  }
114
112
 
115
- // Skip rejected schemes
116
113
  if (REJECTED_SCHEMES.has(targetUrl.protocol)) return url;
117
114
 
118
- // Clean up pathname
119
115
  targetUrl.pathname = removeDirectoryIndex(targetUrl.pathname);
120
116
 
121
117
  const suffix = targetUrl.search + targetUrl.hash;
122
118
 
123
- // No base URL—return normalized absolute URL
124
119
  if (!baseUrl) {
125
120
  return targetUrl.href;
126
121
  }
@@ -130,22 +125,18 @@ export function createUrlMinifier(site) {
130
125
  return targetUrl.href;
131
126
  }
132
127
 
133
- // Check if same origin (protocol + hostname + port)
134
128
  const sameOrigin =
135
129
  targetUrl.protocol === baseUrl.protocol &&
136
130
  targetUrl.hostname === baseUrl.hostname &&
137
131
  targetUrl.port === baseUrl.port;
138
132
 
139
133
  if (!sameOrigin) {
140
- // Same scheme, different host—use scheme-relative
141
134
  if (targetUrl.protocol === baseUrl.protocol) {
142
135
  return '//' + targetUrl.host + targetUrl.pathname + suffix;
143
136
  }
144
- // Different scheme—return normalized absolute
145
137
  return targetUrl.href;
146
138
  }
147
139
 
148
- // Same origin—compute shortest representation
149
140
  const targetPath = targetUrl.pathname;
150
141
  const rootRelative = targetPath + suffix;
151
142
  const pathRelative = relativize(getDirectory(baseUrl.pathname), targetPath) + suffix;
package/src/lib/utils.js CHANGED
@@ -2,13 +2,37 @@
2
2
  * General utility functions
3
3
  */
4
4
 
5
+ import { quirksPublicIdPrefixes, quirksPublicIdPrefixesNoSystemId, quirksPublicIds, quirksSystemIds, RE_DOCTYPE, RE_XML_ESCAPE_ATTR, RE_XML_ESCAPE_TEXT } from './constants.js';
6
+
7
+ // Functions and other non-plain objects have no structure to compare (closures with the
8
+ // same source can behave differently), so they are told apart by identity
9
+ /** @type {WeakMap<object, number>} */
10
+ const objectIds = new WeakMap();
11
+ let objectIdLast = 0;
12
+
13
+ /** @param {object} obj */
14
+ function objectId(obj) {
15
+ let id = objectIds.get(obj);
16
+ if (id === undefined) {
17
+ id = ++objectIdLast;
18
+ objectIds.set(obj, id);
19
+ }
20
+ return id;
21
+ }
22
+
5
23
  /**
24
+ * Stringify with sorted keys, for cache keys—values that can behave differently must not
25
+ * stringify alike, so unquoted markers stand in for what JSON cannot express
6
26
  * @param {unknown} obj
7
27
  * @returns {string}
8
28
  */
9
29
  function stableStringify(obj) {
30
+ if (typeof obj === 'function') return 'function#' + objectId(obj);
10
31
  if (obj == null || typeof obj !== 'object') return JSON.stringify(obj);
32
+ if (obj instanceof RegExp) return String(obj);
11
33
  if (Array.isArray(obj)) return '[' + obj.map(stableStringify).join(',') + ']';
34
+ const proto = Object.getPrototypeOf(obj);
35
+ if (proto !== Object.prototype && proto !== null) return 'object#' + objectId(obj);
12
36
  const keys = Object.keys(obj).sort();
13
37
  let out = '{';
14
38
  for (let i = 0; i < keys.length; i++) {
@@ -65,20 +89,23 @@ class LRU {
65
89
  // (entry count × this size) without affecting realistically sized inline content
66
90
  const MAX_CACHE_ENTRY_SIZE = 1024 * 1024; // 1 MB
67
91
 
68
- // FNV-1a 32-bit hash for large-input cache keys
92
+ // 53-bit hash (cyrb53) for large-input cache keys, where a collision would hand one
93
+ // input another’s result; as fast as a 32-bit hash, whose collisions are within reach
69
94
 
70
95
  /** @param {string} str */
71
96
  function hashContent(str) {
72
- let hash = 2166136261;
97
+ let h1 = 0xdeadbeef;
98
+ let h2 = 0x41c6ce57;
73
99
  for (let i = 0; i < str.length; i++) {
74
- hash ^= str.charCodeAt(i);
75
- hash = Math.imul(hash, 16777619);
100
+ const code = str.charCodeAt(i);
101
+ h1 = Math.imul(h1 ^ code, 2654435761);
102
+ h2 = Math.imul(h2 ^ code, 1597334677);
76
103
  }
77
- return (hash >>> 0).toString(36);
104
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
105
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
106
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
78
107
  }
79
108
 
80
- // Unique ID generator
81
-
82
109
  /** @param {string} value */
83
110
  function uniqueId(value) {
84
111
  let id;
@@ -88,7 +115,46 @@ function uniqueId(value) {
88
115
  return id;
89
116
  }
90
117
 
91
- // Identity and transform functions
118
+ /** @type {Record<string, string>} */
119
+ const xmlEscapes = { '&': '&amp;', '<': '&lt;', ']]>': ']]&gt;', '\t': '&#9;', '\n': '&#10;', '\r': '&#13;' };
120
+
121
+ /** @param {string} match */
122
+ function escapeXMLMatch(match) {
123
+ return xmlEscapes[match] ?? match;
124
+ }
125
+
126
+ /**
127
+ * Write decoded text or an attribute value for an XML parser to read it the same
128
+ * @param {string} value - Text or attribute value, decoded
129
+ * @param {boolean} [attribute] - Whether the value is an attribute value
130
+ * @returns {string}
131
+ */
132
+ function escapeXML(value, attribute = false) {
133
+ return value.replace(attribute ? RE_XML_ESCAPE_ATTR : RE_XML_ESCAPE_TEXT, escapeXMLMatch);
134
+ }
135
+
136
+ /**
137
+ * Read text in foreign content as HTML does: CDATA sections hold text as written,
138
+ * while what surrounds them reads character references
139
+ * @param {string} text
140
+ * @param {(text: string) => string} decode - `decodeHTML`
141
+ * @returns {string}
142
+ */
143
+ function decodeForeignText(text, decode) {
144
+ let out = '';
145
+ let pos = 0;
146
+ while (pos < text.length) {
147
+ const start = text.indexOf('<![CDATA[', pos);
148
+ if (start === -1) return out + decode(text.slice(pos));
149
+ out += decode(text.slice(pos, start));
150
+ // An unclosed section runs to the end
151
+ const end = text.indexOf(']]>', start + 9);
152
+ if (end === -1) return out + text.slice(start + 9);
153
+ out += text.slice(start + 9, end);
154
+ pos = end + 3;
155
+ }
156
+ return out;
157
+ }
92
158
 
93
159
  /** @param {string} value */
94
160
  function identity(value) {
@@ -108,14 +174,12 @@ function lowercase(value) {
108
174
  return value.toLowerCase();
109
175
  }
110
176
 
111
- // Option name to CLI flag name (ASCII-only, no Unicode needed)
177
+ // Option name to CLI flag name (names are ASCII, so no Unicode handling is needed)
112
178
  /** @param {string} value */
113
179
  function paramCase(value) {
114
180
  return value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
115
181
  }
116
182
 
117
- // Replace async helper
118
-
119
183
  /**
120
184
  * Asynchronously replace matches in a string.
121
185
  * @param {string} str - Input string
@@ -336,6 +400,14 @@ function singleCode(ranges) {
336
400
  return ranges?.length === 1 && range && range[0] === range[1] ? range[0] : null;
337
401
  }
338
402
 
403
+ /**
404
+ * @param {string} source @param {number} i @param {boolean} nested - Whether the pattern carries `v`
405
+ * @returns {boolean} Whether a `v` class subtracts or intersects at the position
406
+ */
407
+ function isSetOperator(source, i, nested) {
408
+ return nested && i >= 0 && (source.startsWith('--', i) || source.startsWith('&&', i));
409
+ }
410
+
339
411
  /**
340
412
  * @param {string} atom - Atom as it reads in the source, already unwrapped
341
413
  * @param {boolean} [nested] - Whether the pattern carries `v`
@@ -353,46 +425,85 @@ function atomRanges(atom, nested = false, depth = 0) {
353
425
  const negated = i === 2;
354
426
  const end = atom.length - 1;
355
427
  /** @type {[number, number][]} */
356
- const members = [];
428
+ let members = [];
429
+ // A `v` class subtracts or intersects where it does not unite, one operand at a time
430
+ let operator = '';
357
431
 
358
432
  while (i < end) {
359
- // A `v` class nests, and nesting alone is a union to read through
433
+ if (isSetOperator(atom, i, nested)) {
434
+ operator = atom.slice(i, i + 2);
435
+ i += 2;
436
+ continue;
437
+ }
438
+
439
+ /** @type {[number, number][] | null} */
440
+ let operand;
360
441
  if (nested && atom[i] === '[') {
361
442
  const close = skipCharacterClass(atom, i, true);
362
- const inner = atomRanges(atom.slice(i, close), true, depth + 1);
363
- if (!inner) return null;
364
- members.push(...inner);
443
+ operand = atomRanges(atom.slice(i, close), true, depth + 1);
365
444
  i = close;
366
- continue;
367
- }
368
- // Subtraction and intersection are not unions, and are left unread
369
- //
370
- // @@ Read `--` and `&&` as set difference and intersection
371
- // (so that a `v` class built is compared rather than passed unjudged)
372
- if (nested && (atom.startsWith('--', i) || atom.startsWith('&&', i))) return null;
373
-
374
- const fromLength = tokenLength(atom, i);
375
- const from = tokenRanges(atom.slice(i, i + fromLength), true);
376
- if (!from) return null;
377
- i += fromLength;
378
-
379
- // A dash right before the closing `]` is a member, not the start of a range
380
- if (atom[i] !== '-' || i + 1 >= end) {
381
- members.push(...from);
382
- continue;
445
+ } else {
446
+ const fromLength = tokenLength(atom, i);
447
+ operand = tokenRanges(atom.slice(i, i + fromLength), true);
448
+ i += fromLength;
449
+ // A dash right before the closing `]` is a member, not the start of a range,
450
+ // and so is the `--` that subtracts
451
+ if (operand && atom[i] === '-' && i + 1 < end && !isSetOperator(atom, i, nested)) {
452
+ const toLength = tokenLength(atom, i + 1);
453
+ // Only single characters bound a range; `\d-z` is not a range at all
454
+ const low = singleCode(operand);
455
+ const high = singleCode(tokenRanges(atom.slice(i + 1, i + 1 + toLength), true));
456
+ operand = low === null || high === null ? null : [[low, high]];
457
+ i += 1 + toLength;
458
+ }
383
459
  }
384
- const toLength = tokenLength(atom, i + 1);
385
- // Only single characters bound a range; `\d-z` is not a range at all
386
- const low = singleCode(from);
387
- const high = singleCode(tokenRanges(atom.slice(i + 1, i + 1 + toLength), true));
388
- if (low === null || high === null) return null;
389
- members.push([low, high]);
390
- i += 1 + toLength;
460
+ if (!operand) return null;
461
+
462
+ members = operator === '--' ? intersectRanges(members, complement(operand))
463
+ : operator === '&&' ? intersectRanges(members, operand)
464
+ : members.concat(operand);
391
465
  }
392
466
 
393
467
  return negated ? complement(members) : members;
394
468
  }
395
469
 
470
+ /** @param {[number, number][]} ranges @returns {[number, number][]} The same set, sorted and merged */
471
+ function mergeRanges(ranges) {
472
+ const sorted = [...ranges].sort((one, other) => one[0] - other[0]);
473
+ /** @type {[number, number][]} */
474
+ const out = [];
475
+ for (const [low, high] of sorted) {
476
+ const last = out[out.length - 1];
477
+ if (last && low <= last[1] + 1) last[1] = Math.max(last[1], high);
478
+ else out.push([low, high]);
479
+ }
480
+ return out;
481
+ }
482
+
483
+ /**
484
+ * @param {[number, number][]} ranges @param {[number, number][]} other
485
+ * @returns {[number, number][]} What both match, merged so that repeated
486
+ * operations cannot multiply the pieces
487
+ */
488
+ function intersectRanges(ranges, other) {
489
+ const one = mergeRanges(ranges);
490
+ const two = mergeRanges(other);
491
+ /** @type {[number, number][]} */
492
+ const out = [];
493
+ let i = 0;
494
+ let j = 0;
495
+ while (i < one.length && j < two.length) {
496
+ const [low, high] = /** @type {[number, number]} */ (one[i]);
497
+ const [otherLow, otherHigh] = /** @type {[number, number]} */ (two[j]);
498
+ const from = Math.max(low, otherLow);
499
+ const to = Math.min(high, otherHigh);
500
+ if (from <= to) out.push([from, to]);
501
+ if (high < otherHigh) i++;
502
+ else j++;
503
+ }
504
+ return out;
505
+ }
506
+
396
507
  /** @param {[number, number][]} ranges @param {[number, number][]} other */
397
508
  function rangesIntersect(ranges, other) {
398
509
  return ranges.some(([low, high]) => other.some(([otherLow, otherHigh]) =>
@@ -493,6 +604,12 @@ function foldCase(source, nested = false) {
493
604
  continue;
494
605
  }
495
606
 
607
+ if (isSetOperator(source, i, nested)) {
608
+ out += source.slice(i, i + 2);
609
+ i += 2;
610
+ continue;
611
+ }
612
+
496
613
  const fromLength = tokenLength(source, i);
497
614
  const from = source.slice(i, i + fromLength);
498
615
  const afterFrom = i + fromLength;
@@ -500,7 +617,7 @@ function foldCase(source, nested = false) {
500
617
  // A range needs the other case’s range beside it—only where both ends are
501
618
  // ASCII letters, the one span whose two cases are contiguous and parallel
502
619
  // (`ÿ` uppercases to `Ÿ`, 150 code points past where its range ends)
503
- if (source[afterFrom] === '-' && afterFrom + 1 < source.length && source[afterFrom + 1] !== ']') {
620
+ if (source[afterFrom] === '-' && afterFrom + 1 < source.length && source[afterFrom + 1] !== ']' && !isSetOperator(source, afterFrom, nested)) {
504
621
  const toLength = tokenLength(source, afterFrom + 1);
505
622
  const to = source.slice(afterFrom + 1, afterFrom + 1 + toLength);
506
623
  out += RE_ASCII_LETTER.test(from) && RE_ASCII_LETTER.test(to) && isLower(from) === isLower(to)
@@ -512,7 +629,11 @@ function foldCase(source, nested = false) {
512
629
  continue;
513
630
  }
514
631
 
515
- out += fromLength === 1 && foldsCase(from) ? from.toLowerCase() + from.toUpperCase() : from;
632
+ // A set operand is one character, so both cases go into a class of their own
633
+ const folded = from.toLowerCase() + from.toUpperCase();
634
+ out += fromLength !== 1 || !foldsCase(from) ? from
635
+ : isSetOperator(source, afterFrom, nested) || isSetOperator(source, i - 2, nested) ? '[' + folded + ']'
636
+ : folded;
516
637
  i = afterFrom;
517
638
  }
518
639
 
@@ -598,7 +719,7 @@ function lostFlag(pattern) {
598
719
  j += tokenLength(source, j);
599
720
  continue;
600
721
  }
601
- if (source[j] === '[' || source.startsWith('--', j) || source.startsWith('&&', j)) return 'v';
722
+ if (source[j] === '[' || isSetOperator(source, j, true)) return 'v';
602
723
  j++;
603
724
  }
604
725
  i = end;
@@ -840,7 +961,47 @@ function findTagEnd(html, pos, limit = html.length) {
840
961
  return -1;
841
962
  }
842
963
 
843
- // Exports
964
+ /**
965
+ * A package that resolves but fails to load—e.g., a native binding built for
966
+ * another platform—is not one another `npm install` fixes, so name what happened
967
+ * rather than the install command
968
+ *
969
+ * @param {string} label - Minifier name as it should read in the message
970
+ * @param {string} specifier - Package that failed to load
971
+ * @param {unknown} cause - Error the import rejected with
972
+ * @returns {string} Message describing the failure
973
+ */
974
+ function describeDependencyFailure(label, specifier, cause) {
975
+ const err = /** @type {any} */ (cause);
976
+ const notInstalled =
977
+ err?.code === 'ERR_MODULE_NOT_FOUND' && String(err?.message).includes(`'${specifier}'`);
978
+ if (notInstalled) {
979
+ return `The ${label} minifier requires ${specifier} to be installed.\n` +
980
+ `Install it with: npm install ${specifier}`;
981
+ }
982
+ return `The ${label} minifier could not load ${specifier}: ` +
983
+ (cause instanceof Error ? cause.message : String(cause));
984
+ }
985
+
986
+ // Whether a doctype sets quirks mode, per the HTML parser (limited-quirks mode counts as no-quirks,
987
+ // as it only differs in line height calculation)
988
+ // https://html.spec.whatwg.org/multipage/parsing.html#the-initial-insertion-mode
989
+ /** @param {string} doctype */
990
+ function isQuirksDoctype(doctype) {
991
+ const match = RE_DOCTYPE.exec(doctype);
992
+ if (!match) return true;
993
+ const [, name = '', publicQuoted, systemQuoted, systemOnlyQuoted, rest] = match;
994
+ const systemId = (systemQuoted ?? systemOnlyQuoted)?.slice(1, -1).toLowerCase();
995
+ // The force-quirks flag
996
+ if (systemId === undefined && rest !== '>') return true;
997
+ if (name.toLowerCase() !== 'html') return true;
998
+ if (systemId !== undefined && quirksSystemIds.has(systemId)) return true;
999
+ if (publicQuoted === undefined) return false;
1000
+ const publicId = publicQuoted.slice(1, -1).toLowerCase();
1001
+ return quirksPublicIds.has(publicId) ||
1002
+ quirksPublicIdPrefixes.some(prefix => publicId.startsWith(prefix)) ||
1003
+ (!systemId && quirksPublicIdPrefixesNoSystemId.some(prefix => publicId.startsWith(prefix)));
1004
+ }
844
1005
 
845
1006
  export {
846
1007
  stableStringify,
@@ -849,7 +1010,10 @@ export {
849
1010
  MAX_CACHE_ENTRY_SIZE,
850
1011
  hashContent,
851
1012
  uniqueId,
1013
+ escapeXML,
1014
+ decodeForeignText,
852
1015
  identity,
1016
+ isQuirksDoctype,
853
1017
  isThenable,
854
1018
  lowercase,
855
1019
  paramCase,
@@ -857,5 +1021,6 @@ export {
857
1021
  parseRegExp,
858
1022
  embedSource,
859
1023
  lostFlag,
860
- describeQuantifierRisk
1024
+ describeQuantifierRisk,
1025
+ describeDependencyFailure
861
1026
  };