@tbela99/css-parser 2.1.0 → 2.2.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 (125) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +14 -7
  3. package/architecture.png +0 -0
  4. package/dist/{src/data → data}/properties.json.js +86 -2
  5. package/dist/{src/data → data}/validation.json.js +5 -2
  6. package/dist/index-umd-web.js +10738 -4359
  7. package/dist/index.d.ts +734 -100
  8. package/dist/{src/lib → lib}/ast/arena-node.js +10 -10
  9. package/dist/{src/lib → lib}/ast/arena.js +304 -139
  10. package/dist/{src/lib → lib}/ast/cache.js +2 -2
  11. package/dist/{src/lib → lib}/ast/features/calc.js +11 -9
  12. package/dist/{src/lib → lib}/ast/features/if.js +6 -6
  13. package/dist/{src/lib → lib}/ast/features/index.js +3 -2
  14. package/dist/{src/lib → lib}/ast/features/inlinecssvariables.js +12 -10
  15. package/dist/lib/ast/features/mixin.js +953 -0
  16. package/dist/{src/lib → lib}/ast/features/prefix.js +39 -39
  17. package/dist/lib/ast/features/shorthand.js +129 -0
  18. package/dist/lib/ast/features/transform.js +188 -0
  19. package/dist/{src/lib → lib}/ast/features/type.js +2 -2
  20. package/dist/{src/lib → lib}/ast/math/expression.js +24 -24
  21. package/dist/{src/lib → lib}/ast/math/math.js +2 -2
  22. package/dist/{src/lib → lib}/ast/minify.js +745 -201
  23. package/dist/lib/ast/mixins/custom-function.js +393 -0
  24. package/dist/lib/ast/mixins/utils.js +53 -0
  25. package/dist/lib/ast/mixins/variables.js +678 -0
  26. package/dist/lib/ast/strings.js +906 -0
  27. package/dist/lib/ast/transform/compute.js +560 -0
  28. package/dist/lib/ast/transform/matrix.js +67 -0
  29. package/dist/lib/ast/transform/minify.js +325 -0
  30. package/dist/lib/ast/transform/perspective.js +24 -0
  31. package/dist/{src/lib → lib}/ast/transform/rotate.js +16 -7
  32. package/dist/lib/ast/transform/scale.js +43 -0
  33. package/dist/lib/ast/transform/skew.js +38 -0
  34. package/dist/lib/ast/transform/translate.js +56 -0
  35. package/dist/lib/ast/transform/utils.js +390 -0
  36. package/dist/{src/lib → lib}/ast/types.js +2 -2
  37. package/dist/{src/lib → lib}/ast/walk.js +2 -2
  38. package/dist/{src/lib → lib}/fs/resolve.js +2 -2
  39. package/dist/{src/lib → lib}/parser/declaration/list.js +25 -8
  40. package/dist/{src/lib → lib}/parser/declaration/map.js +15 -15
  41. package/dist/{src/lib → lib}/parser/declaration/set.js +5 -5
  42. package/dist/{src/lib → lib}/parser/input.js +18 -3
  43. package/dist/{src/lib → lib}/parser/linesmap.js +2 -2
  44. package/dist/{src/lib → lib}/parser/parse.js +425 -258
  45. package/dist/{src/lib → lib}/parser/source.js +2 -2
  46. package/dist/{src/lib → lib}/parser/tokenize.js +480 -312
  47. package/dist/{src/lib → lib}/parser/utils/angle.js +3 -3
  48. package/dist/{src/lib → lib}/parser/utils/at-rule-container.js +12 -12
  49. package/dist/{src/lib → lib}/parser/utils/at-rule-font-feature-values.js +3 -3
  50. package/dist/{src/lib → lib}/parser/utils/at-rule-generic.js +7 -7
  51. package/dist/{src/lib → lib}/parser/utils/at-rule-import.js +10 -10
  52. package/dist/{src/lib → lib}/parser/utils/at-rule-media.js +14 -14
  53. package/dist/{src/lib → lib}/parser/utils/at-rule-support.js +9 -14
  54. package/dist/{src/lib → lib}/parser/utils/at-rule-when-else.js +6 -6
  55. package/dist/{src/lib → lib}/parser/utils/at-rule.js +3 -3
  56. package/dist/{src/lib → lib}/parser/utils/base64.js +2 -2
  57. package/dist/lib/parser/utils/cache.js +53 -0
  58. package/dist/lib/parser/utils/canonical.js +78 -0
  59. package/dist/lib/parser/utils/codes.js +93 -0
  60. package/dist/{src/lib → lib}/parser/utils/config.js +2 -2
  61. package/dist/{src/lib → lib}/parser/utils/declaration.js +31 -26
  62. package/dist/{src/lib → lib}/parser/utils/eq.js +2 -2
  63. package/dist/{src/lib → lib}/parser/utils/hash.js +2 -2
  64. package/dist/{src/lib → lib}/parser/utils/selector.js +305 -63
  65. package/dist/{src/lib → lib}/parser/utils/text.js +2 -2
  66. package/dist/{src/lib → lib}/parser/utils/token.js +2 -2
  67. package/dist/{src/lib → lib}/parser/utils/type.js +9 -7
  68. package/dist/{src/lib → lib}/printer/render.js +420 -152
  69. package/dist/lib/printer/result.js +148 -0
  70. package/dist/{src/lib → lib}/printer/sourcemap/lib/codec.js +2 -2
  71. package/dist/{src/lib → lib}/printer/sourcemap/sourcemap.js +2 -2
  72. package/dist/lib/printer/writer.js +252 -0
  73. package/dist/{src/lib → lib}/syntax/color/a98rgb.js +2 -2
  74. package/dist/{src/lib → lib}/syntax/color/alpha.js +10 -10
  75. package/dist/{src/lib → lib}/syntax/color/cmyk.js +2 -2
  76. package/dist/{src/lib → lib}/syntax/color/color-mix.js +18 -18
  77. package/dist/{src/lib → lib}/syntax/color/color.js +18 -18
  78. package/dist/{src/lib → lib}/syntax/color/hex.js +3 -3
  79. package/dist/{src/lib → lib}/syntax/color/hsl.js +2 -2
  80. package/dist/{src/lib → lib}/syntax/color/hwb.js +2 -2
  81. package/dist/{src/lib → lib}/syntax/color/lab.js +2 -2
  82. package/dist/{src/lib → lib}/syntax/color/lch.js +2 -2
  83. package/dist/{src/lib → lib}/syntax/color/oklab.js +2 -2
  84. package/dist/{src/lib → lib}/syntax/color/oklch.js +3 -3
  85. package/dist/{src/lib → lib}/syntax/color/p3.js +2 -2
  86. package/dist/{src/lib → lib}/syntax/color/prophotorgb.js +2 -2
  87. package/dist/{src/lib → lib}/syntax/color/rec2020.js +2 -2
  88. package/dist/{src/lib → lib}/syntax/color/relative-color.js +14 -14
  89. package/dist/{src/lib → lib}/syntax/color/rgb.js +4 -4
  90. package/dist/{src/lib → lib}/syntax/color/srgb.js +5 -5
  91. package/dist/{src/lib → lib}/syntax/color/utils/color-type.js +4 -4
  92. package/dist/{src/lib → lib}/syntax/color/utils/colorspace.js +10 -10
  93. package/dist/{src/lib → lib}/syntax/color/utils/components.js +5 -5
  94. package/dist/{src/lib → lib}/syntax/color/utils/distance.js +2 -2
  95. package/dist/{src/lib → lib}/syntax/color/utils/make-color.js +3 -3
  96. package/dist/{src/lib → lib}/syntax/color/utils/matrix.js +2 -2
  97. package/dist/{src/lib → lib}/syntax/color/xyz.js +2 -2
  98. package/dist/{src/lib → lib}/syntax/color/xyzd50.js +2 -2
  99. package/dist/{src/lib → lib}/syntax/constants.js +26 -3
  100. package/dist/{src/lib → lib}/syntax/syntax.js +37 -29
  101. package/dist/{src/lib → lib}/validation/config.js +23 -10
  102. package/dist/lib/validation/first.js +571 -0
  103. package/dist/{src/lib → lib}/validation/match.js +292 -150
  104. package/dist/{src/lib → lib}/validation/parser/parse.js +2 -2
  105. package/dist/{src/lib → lib}/validation/parser/typedef.js +2 -2
  106. package/dist/{src/lib → lib}/validation/utils/list.js +3 -19
  107. package/dist/{src/node.js → node.js} +52 -34
  108. package/dist/{src/types.js → types.js} +2 -2
  109. package/dist/{src/utils → utils}/sync.js +10 -5
  110. package/dist/version.d.ts +4 -0
  111. package/dist/version.js +13 -0
  112. package/dist/{src/web.js → web.js} +47 -34
  113. package/package.json +12 -12
  114. package/dist/package.json.js +0 -10
  115. package/dist/src/lib/ast/features/shorthand.js +0 -95
  116. package/dist/src/lib/ast/features/transform.js +0 -90
  117. package/dist/src/lib/ast/transform/compute.js +0 -362
  118. package/dist/src/lib/ast/transform/matrix.js +0 -88
  119. package/dist/src/lib/ast/transform/minify.js +0 -267
  120. package/dist/src/lib/ast/transform/perspective.js +0 -16
  121. package/dist/src/lib/ast/transform/scale.js +0 -39
  122. package/dist/src/lib/ast/transform/skew.js +0 -30
  123. package/dist/src/lib/ast/transform/translate.js +0 -39
  124. package/dist/src/lib/ast/transform/utils.js +0 -287
  125. package/dist/src/lib/parser/utils/cache.js +0 -54
@@ -1,16 +1,18 @@
1
1
  /*
2
- CSS parser, minifier and validator for node and the browser
2
+ CSS parser, minifier and validator for node, deno, bun and the browser
3
3
 
4
4
  Author(s): Thierry Bela
5
- Version: 2.1.0
5
+ Version: 2.2.0
6
6
  License: MIT
7
7
  */
8
8
  import { eq, eqToken } from '../parser/utils/eq.js';
9
9
  import { renderValue, NodeRenderer } from '../printer/render.js';
10
10
  import * as index from './features/index.js';
11
11
  import { EnumToken, EnumAstNodeStatus } from './types.js';
12
+ import { StringBuilder } from './strings.js';
12
13
  import { isWhiteSpace, isIdent, isFunction, isIdentStart } from '../syntax/syntax.js';
13
14
  import { FeatureWalkMode } from './features/type.js';
15
+ import { moveResult } from './mixins/utils.js';
14
16
  import { trimArray } from '../validation/match.js';
15
17
  import { combinators } from '../syntax/constants.js';
16
18
  import { parseString } from '../parser/parse.js';
@@ -117,6 +119,34 @@ function minify(arena, ast, options = {}, recursive = false, errors, nestingCont
117
119
  }
118
120
  return ast;
119
121
  }
122
+ /**
123
+ * `@apply --mixin()` is equivalent to `@apply --mixin`: a mixin applied without arguments is referenced by its name
124
+ * https://drafts.csswg.org/css-mixins-1/#apply-rule
125
+ * @param arena
126
+ * @param node `@apply` rule
127
+ */
128
+ function minifyApplyPrelude(arena, node) {
129
+ let reference = arena.firstToken[node];
130
+ while (reference !== 0 &&
131
+ (arena.dataTypes[reference] === EnumToken.WhitespaceTokenType ||
132
+ arena.dataTypes[reference] === EnumToken.CommentTokenType)) {
133
+ reference = arena.nextSibling[reference];
134
+ }
135
+ if (reference === 0 || arena.dataTypes[reference] !== EnumToken.CustomFunctionTokenType) {
136
+ return;
137
+ }
138
+ // the comments and the whitespace are ignored: `@apply --mixin(/* comment */)` has no argument
139
+ for (let token = arena.firstToken[reference]; token !== 0; token = arena.nextSibling[token]) {
140
+ if (arena.dataTypes[token] !== EnumToken.WhitespaceTokenType &&
141
+ arena.dataTypes[token] !== EnumToken.CommentTokenType) {
142
+ return;
143
+ }
144
+ }
145
+ const name = arena.resolveString(arena.stringValue[reference]);
146
+ arena.setTokenList(node, [arena.createToken(EnumToken.DashedIdenTokenType, name)]);
147
+ // inlined: arena.setValueString(node, name)
148
+ arena.stringValue[node] = arena.internString(name);
149
+ }
120
150
  function transformAtRuleMediaPrelude(arena, values) {
121
151
  return { hasUpdates: false, values: trimArray(arena, values) };
122
152
  }
@@ -185,6 +215,65 @@ function reduce(acc, curr) {
185
215
  acc.push(curr.join(""));
186
216
  return acc;
187
217
  }
218
+ /**
219
+ * true if the selector part is a simple selector that can be moved into `:is()`: it is not a combinator, a whitespace
220
+ * (descendant combinator), the nesting selector or a pseudo-element (a pseudo-element is not allowed in `:is()`)
221
+ * @param part
222
+ */
223
+ function isCompoundPart(part) {
224
+ return (part.trim() !== "" &&
225
+ part !== "&" &&
226
+ !combinators.includes(part) &&
227
+ !part.startsWith("::") &&
228
+ !/^:(before|after|first-line|first-letter)$/i.test(part));
229
+ }
230
+ /**
231
+ * factor the common prefix of the selectors of a rule into `:is()`. the selectors are relative to the common prefix,
232
+ * see {@link optimizeSelector}: `["&"]` is the prefix itself, `["&", ".a"]` is a compound selector (`.foo.a`),
233
+ * `["&", " ", ".a"]` a descendant selector (`.foo .a`) and `[">", ".a"]` a child selector (`.foo>.a`).
234
+ *
235
+ * - `.foo.a,.foo.b` -> `.foo:is(.a,.b)`. `.foo,.foo.b` -> `.foo:is(*,.b)`
236
+ * - `.foo .a,.foo .b` -> `.foo :is(.a,.b)`, `.foo>.a,.foo>.b` -> `.foo>:is(.a,.b)`
237
+ *
238
+ * the selectors are factored only when the suffixes are compound selectors joined to the prefix with the same
239
+ * combinator: `.foo .a .b,.foo .c` is not `.foo :is(.a .b,.c)`. null when the selectors cannot be factored
240
+ * @param optimized
241
+ */
242
+ function factorSelector(optimized) {
243
+ const prefix = optimized.optimized;
244
+ if (prefix.length === 0 ||
245
+ !prefix.every((part) => part === " " || isCompoundPart(part) || combinators.includes(part))) {
246
+ return null;
247
+ }
248
+ let combinator = null;
249
+ const members = [];
250
+ for (const selector of optimized.selector) {
251
+ // the parts that follow the prefix. the whitespace around the combinators is removed
252
+ const suffix = (selector[0] === "&" ? selector.slice(1) : selector.slice()).filter((part, index, parts) => part.trim() !== "" ||
253
+ (!combinators.includes(parts[index - 1]) && !combinators.includes(parts[index + 1])));
254
+ // the prefix itself
255
+ if (suffix.length === 0) {
256
+ if (combinator != null && combinator !== "") {
257
+ return null;
258
+ }
259
+ combinator = "";
260
+ members.push("*");
261
+ continue;
262
+ }
263
+ // the combinator that joins the suffix to the prefix. "" for a compound selector
264
+ const current = suffix[0].trim() === "" ? " " : combinators.includes(suffix[0]) ? suffix[0] : "";
265
+ const compound = current === "" ? suffix : suffix.slice(1);
266
+ if ((combinator != null && combinator !== current) ||
267
+ current === "|" ||
268
+ compound.length === 0 ||
269
+ !compound.every(isCompoundPart)) {
270
+ return null;
271
+ }
272
+ combinator = current;
273
+ members.push(compound.join(""));
274
+ }
275
+ return prefix.join("") + combinator + ":is(" + members.join(",") + ")";
276
+ }
188
277
  /**
189
278
  * Apply minification rules to the ast tree
190
279
  * @param arena
@@ -240,38 +329,15 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
240
329
  nodeType = arena.dataTypes[node];
241
330
  previousType = previous == null ? null : arena.dataTypes[previous];
242
331
  if (nodeType === EnumToken.AtRuleNodeType) {
243
- const nam = arena.strings[arena.name[node]];
332
+ const nam = arena.resolveString(arena.name[node]);
244
333
  if (nam === "font-face") {
245
334
  cursor = arena.nextSibling[node];
246
335
  continue;
247
336
  }
248
- // https://drafts.csswg.org/css-mixins/#:~:text=The%20value%20of%20the%20result%20descriptor%20is%20always%2016px%20in%20the%20above%20example
337
+ // there is no early return: the result that precedes the conditional rules is moved after them.
338
+ // the conditional rules are never removed
249
339
  if (equalsIgnoreCase(nam, "function")) {
250
- let k = arena.lastChild[node];
251
- let slice = false;
252
- while (k !== 0) {
253
- if (arena.dataTypes[k] === EnumToken.CommentNodeType ||
254
- arena.dataTypes[k] === EnumToken.WhitespaceTokenType) {
255
- k = arena.previousSibling[k];
256
- continue;
257
- }
258
- if (arena.dataTypes[k] === EnumToken.DeclarationNodeType &&
259
- equalsIgnoreCase(arena.strings[arena.name[k]], "result")) {
260
- slice = true;
261
- break;
262
- }
263
- k = arena.previousSibling[k];
264
- }
265
- if (k !== 0 && slice) {
266
- k = arena.previousSibling[k];
267
- while (k !== 0) {
268
- const previousNode = arena.previousSibling[k];
269
- if (arena.dataTypes[k] === EnumToken.AtRuleNodeType) {
270
- arena.detach(k);
271
- }
272
- k = previousNode;
273
- }
274
- }
340
+ moveResult(arena, node);
275
341
  }
276
342
  }
277
343
  if (nodeType === EnumToken.KeyframesAtRuleNodeType) {
@@ -319,7 +385,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
319
385
  }
320
386
  }
321
387
  else if (nodeType === EnumToken.AtRuleNodeType) {
322
- const nam = arena.strings[arena.name[node]];
388
+ const nam = arena.resolveString(arena.name[node]);
323
389
  const tokens = arena.firstToken[node] === 0 ? null : arena.tokens(node);
324
390
  const renderPrelude = (acc, curr, index, arr) => acc +
325
391
  (arena.dataTypes[curr] === EnumToken.CommentTokenType ||
@@ -330,7 +396,11 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
330
396
  (index + 3 < arr.length || arena.dataTypes[arr[index + 2]] === EnumToken.WhitespaceTokenType))
331
397
  ? ""
332
398
  : renderValue(arena, curr));
333
- if (nam === "media") {
399
+ if (nam === "apply") {
400
+ // `@apply --mixin()` is equivalent to `@apply --mixin`
401
+ minifyApplyPrelude(arena, node);
402
+ }
403
+ else if (nam === "media") {
334
404
  if (tokens != null) {
335
405
  const slice = tokens.slice();
336
406
  minifyAtRuleMedia(arena, slice);
@@ -340,7 +410,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
340
410
  arena.stringValue[node] = arena.internString(slice.reduce(renderPrelude, ""));
341
411
  }
342
412
  }
343
- if (["all", ""].includes(arena.strings[arena.stringValue[node]])) {
413
+ if (["all", ""].includes(arena.resolveString(arena.stringValue[node]))) {
344
414
  // the node is replaced by its children
345
415
  cursor = arena.firstChild[node] || arena.nextSibling[node];
346
416
  arena.moveChildren(node, ast, node);
@@ -356,7 +426,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
356
426
  if (arena.dataTypes[token] === EnumToken.ParensTokenType ||
357
427
  arena.dataTypes[token] === EnumToken.MediaQueryConditionTokenType ||
358
428
  (arena.dataTypes[token] === EnumToken.IdenTokenType &&
359
- "layer" !== arena.strings[arena.stringValue[token]])) {
429
+ "layer" !== arena.resolveString(arena.stringValue[token]))) {
360
430
  break;
361
431
  }
362
432
  }
@@ -401,23 +471,42 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
401
471
  continue;
402
472
  }
403
473
  else if (nodeType === EnumToken.RuleNodeType) {
404
- reduceRuleSelector(arena, node);
474
+ // a single selector that does not end with a combinator is not reduced (see isSimpleSelector()): the
475
+ // selector is not read
476
+ if (!isSimpleSelector(arena, arena.name[node])) {
477
+ reduceRuleSelector(arena, node);
478
+ }
405
479
  let wrapper = null;
406
480
  let match;
407
481
  if (options.nestingRules) {
408
- if (previousType === EnumToken.RuleNodeType) {
409
- reduceRuleSelector(arena, previous);
410
- match = matchSelectors(arena.raw[previous], arena.raw[node]);
411
- if (match != null) {
412
- wrapper = wrapNodes(arena, previous, node, match, reducer);
482
+ // the rules that apply a mixin are not merged
483
+ if (previousType === EnumToken.RuleNodeType &&
484
+ !hasAtRuleStatement(arena, previous) &&
485
+ !hasAtRuleStatement(arena, node)) {
486
+ if (!isSimpleSelector(arena, arena.name[previous])) {
487
+ reduceRuleSelector(arena, previous);
488
+ }
489
+ // the selectors are split when their first parts are equal: they do not match otherwise
490
+ if (mayMatchSelectors(arena, previous, node)) {
491
+ match = matchSelectors(rawSelector(arena, previous), rawSelector(arena, node));
492
+ if (match != null) {
493
+ wrapper = wrapNodes(arena, previous, node, match, reducer);
494
+ }
413
495
  }
414
496
  }
415
497
  if (wrapper != null) {
416
498
  // wrap the following rules that match the wrapper selector
417
499
  let nextNode = arena.nextSibling[wrapper];
418
- while (nextNode !== 0 && arena.dataTypes[nextNode] === EnumToken.RuleNodeType) {
419
- reduceRuleSelector(arena, nextNode);
420
- match = matchSelectors(arena.raw[wrapper], arena.raw[nextNode]);
500
+ while (nextNode !== 0 &&
501
+ arena.dataTypes[nextNode] === EnumToken.RuleNodeType &&
502
+ !hasAtRuleStatement(arena, nextNode)) {
503
+ if (!isSimpleSelector(arena, arena.name[nextNode])) {
504
+ reduceRuleSelector(arena, nextNode);
505
+ }
506
+ // the selector is split when its first part matches the wrapper selector
507
+ match = mayMatchSelectors(arena, wrapper, nextNode)
508
+ ? matchSelectors(rawSelector(arena, wrapper), rawSelector(arena, nextNode))
509
+ : null;
421
510
  if (match == null) {
422
511
  break;
423
512
  }
@@ -429,19 +518,20 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
429
518
  doMinify(arena, wrapper, options, recursive, errors, nestingContent, context);
430
519
  continue;
431
520
  }
432
- else if (arena.optimized[node] != null &&
433
- arena.optimized[node].match &&
434
- arena.optimized[node].selector.length > 1) {
435
- const optimized = arena.optimized[node];
436
- wrapper = arena.clone(node);
521
+ else if (arena.optimized.get(node) != null &&
522
+ arena.optimized.get(node).match &&
523
+ arena.optimized.get(node).selector.length > 1) {
524
+ const optimized = arena.optimized.get(node);
525
+ wrapper = arena.cloneNode(node);
526
+ arena.optimized.set(wrapper, arena.optimized.get(node));
437
527
  // inlined: arena.setSelector(wrapper, optimized.optimized[0])
438
528
  arena.name[wrapper] = arena.internString(optimized.optimized[0]);
439
- arena.raw[wrapper] = [[optimized.optimized[0]]];
529
+ arena.raw.set(wrapper, [[optimized.optimized[0]]]);
440
530
  // inlined: arena.setTokens(wrapper)
441
531
  arena.setTokenList(wrapper, []);
442
532
  // inlined: arena.setSelector(node, optimized.selector.reduce(reducer, []).join(","))
443
533
  arena.name[node] = arena.internString(optimized.selector.reduce(reducer, []).join(","));
444
- arena.raw[node] = optimized.selector.slice();
534
+ arena.raw.set(node, optimized.selector.slice());
445
535
  // inlined: arena.setTokens(node)
446
536
  arena.setTokenList(node, []);
447
537
  // the wrapper takes the place of the node
@@ -450,8 +540,8 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
450
540
  node = wrapper;
451
541
  nodeType = EnumToken.RuleNodeType;
452
542
  }
453
- else if (arena.optimized[node]?.reducible) {
454
- const optimized = arena.optimized[node];
543
+ else if (arena.optimized.get(node)?.reducible) {
544
+ const optimized = arena.optimized.get(node);
455
545
  if (optimized.optimized.length === 1) {
456
546
  const sel1 = optimized.optimized[0] +
457
547
  ":is(" +
@@ -474,104 +564,17 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
474
564
  }
475
565
  }
476
566
  }
477
- else if (arena.optimized[node]?.match) {
478
- const optimizedSelector = arena.optimized[node];
479
- let wrap = true;
480
- const selector = optimizedSelector.selector.reduce((acc, curr) => {
481
- if (curr[0] === "&" && curr.length > 1) {
482
- if (curr[1] === " ") {
483
- curr.splice(0, 2);
484
- }
485
- else {
486
- curr.splice(0, 1);
487
- }
488
- }
489
- else if (combinators.includes(curr[0])) {
490
- curr.unshift("&");
491
- wrap = false;
492
- }
493
- acc.push(curr);
494
- return acc;
495
- }, []);
496
- if (!wrap) {
497
- wrap = selector.some((s) => s[0] !== "&");
498
- }
499
- let rule = null;
500
- const optimized = optimizedSelector.optimized.slice();
501
- if (optimized.length > 1) {
502
- const check = optimized.at(-2);
503
- if (!combinators.includes(check)) {
504
- const last = optimized[optimized.length - 1];
505
- const all = new Array(Math.max(optimized.length - 1, 0));
506
- let write = 0;
507
- for (let read = 0; read < optimized.length - 1; read++) {
508
- all[write++] = optimized[read];
509
- }
510
- optimized.length = 0;
511
- for (let index = 0; index < write; index++) {
512
- optimized[index] = all[index];
513
- }
514
- wrap = false;
515
- rule =
516
- optimized.join("") +
517
- `:is(${selector
518
- .map((s) => {
519
- const next = s[0] === "&" ? new Array(s.length) : new Array(s.length + 1);
520
- let write = 0;
521
- if (s[0] === "&") {
522
- next[write++] = last;
523
- for (let read = 1; read < s.length; read++) {
524
- next[write++] = s[read];
525
- }
526
- }
527
- else {
528
- next[write++] = last;
529
- for (let read = 0; read < s.length; read++) {
530
- next[write++] = s[read];
531
- }
532
- }
533
- const rebuilt = new Array(write);
534
- for (let index = 0; index < write; index++) {
535
- rebuilt[index] = next[index];
536
- }
537
- return rebuilt.join("");
538
- })
539
- .join(",")})`;
540
- }
541
- }
542
- if (rule == null) {
543
- rule = selector
544
- .map((s) => {
545
- if (s[0] === "&") {
546
- const replacement = optimizedSelector.optimized;
547
- const all = new Array(Math.max(s.length - 1 + replacement.length, 0));
548
- let write = 0;
549
- for (let read = 0; read < replacement.length; read++) {
550
- all[write++] = replacement[read];
551
- }
552
- for (let read = 1; read < s.length; read++) {
553
- all[write++] = s[read];
554
- }
555
- const rebuilt = new Array(write);
556
- for (let index = 0; index < write; index++) {
557
- rebuilt[index] = all[index];
558
- }
559
- return rebuilt.join("");
560
- }
561
- return s.join("");
562
- })
563
- .join(",");
564
- }
565
- let sel = wrap ? optimizedSelector.optimized.join("") + `:is(${rule})` : rule;
566
- if (sel.length < arena.strings[arena.name[node]].length) {
567
+ else if (arena.optimized.get(node)?.match) {
568
+ const sel = factorSelector(arena.optimized.get(node));
569
+ if (sel != null && sel.length < arena.resolveString(arena.name[node]).length) {
567
570
  // inlined: arena.setSelector(node, sel)
568
571
  arena.name[node] = arena.internString(sel);
569
572
  // inlined: arena.setTokens(node)
570
573
  arena.setTokenList(node, []);
571
574
  }
572
575
  }
573
- else if (arena.optimized[node]?.reducible) {
574
- const optimized = arena.optimized[node];
576
+ else if (arena.optimized.get(node)?.reducible) {
577
+ const optimized = arena.optimized.get(node);
575
578
  if (optimized.optimized.length === 1) {
576
579
  const sel1 = optimized.optimized[0] + ":is(" + optimized.selector.reduce(reducer, []).join(",") + ")";
577
580
  const sel2 = optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") + optimized.optimized[0] + curr.join(""), "");
@@ -590,13 +593,13 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
590
593
  arena.setTokenList(node, []);
591
594
  }
592
595
  }
593
- else if (arena.optimized[node]?.optimized.length > 0) {
594
- const optimized = arena.optimized[node];
596
+ else if (arena.optimized.get(node)?.optimized.length > 0) {
597
+ const optimized = arena.optimized.get(node);
595
598
  const sel = optimized.optimized.join("");
596
- if (sel.length < arena.strings[arena.name[node]].length) {
599
+ if (sel.length < arena.resolveString(arena.name[node]).length) {
597
600
  // inlined: arena.setSelector(node, sel)
598
601
  arena.name[node] = arena.internString(sel);
599
- arena.raw[node] = [optimized.optimized.slice()];
602
+ arena.raw.set(node, [optimized.optimized.slice()]);
600
603
  // inlined: arena.setTokens(node)
601
604
  arena.setTokenList(node, []);
602
605
  }
@@ -618,12 +621,15 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
618
621
  shouldMerge = arena.dataTypes[k] === EnumToken.DeclarationNodeType;
619
622
  break;
620
623
  }
621
- if (shouldMerge) {
624
+ // the rules that apply a mixin are not merged
625
+ if (shouldMerge &&
626
+ (nodeType !== EnumToken.RuleNodeType ||
627
+ (!hasAtRuleStatement(arena, previous) && !hasAtRuleStatement(arena, node)))) {
622
628
  if (((nodeType === EnumToken.RuleNodeType ||
623
629
  nodeType === EnumToken.KeyframesRuleNodeType) &&
624
630
  arena.name[node] === arena.name[previous]) ||
625
631
  (nodeType === EnumToken.AtRuleNodeType &&
626
- arena.strings[arena.name[node]] !== "font-face" &&
632
+ arena.resolveString(arena.name[node]) !== "font-face" &&
627
633
  arena.name[node] === arena.name[previous])) {
628
634
  arena.moveChildren(previous, node, arena.firstChild[node]);
629
635
  options.cache?.delete(node);
@@ -678,7 +684,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
678
684
  if (!nestingContent &&
679
685
  previous != null &&
680
686
  arena.dataTypes[previous] === EnumToken.RuleNodeType &&
681
- arena.strings[arena.name[previous]].includes("&")) {
687
+ arena.stringIndexOf(arena.name[previous], 0x26) !== -1) {
682
688
  fixSelector(arena, previous);
683
689
  }
684
690
  previous = node;
@@ -687,7 +693,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
687
693
  if (recursive && node != null && arena.flags[node] & EnumAstNodeStatus.HasChildren) {
688
694
  if (arena.dataTypes[node] === EnumToken.KeyframesAtRuleNodeType || !hasDeclarationChild(arena, node)) {
689
695
  if (!(arena.dataTypes[node] === EnumToken.AtRuleNodeType &&
690
- arena.strings[arena.name[node]] !== "font-face")) {
696
+ arena.resolveString(arena.name[node]) !== "font-face")) {
691
697
  doMinify(arena, node, options, recursive, errors, nestingContent, context);
692
698
  }
693
699
  }
@@ -695,7 +701,7 @@ function doMinify(arena, ast, options = {}, recursive = false, errors, nestingCo
695
701
  if (!nestingContent &&
696
702
  node != null &&
697
703
  arena.dataTypes[node] === EnumToken.RuleNodeType &&
698
- arena.strings[arena.name[node]].includes("&")) {
704
+ arena.stringIndexOf(arena.name[node], 0x26) !== -1) {
699
705
  fixSelector(arena, node);
700
706
  }
701
707
  }
@@ -1169,13 +1175,13 @@ function matchSelectors(selector1, selector2) {
1169
1175
  * @private
1170
1176
  */
1171
1177
  function fixSelector(arena, node) {
1172
- const sel = arena.strings[arena.name[node]];
1178
+ const sel = arena.resolveString(arena.name[node]);
1173
1179
  if (sel.includes("&")) {
1174
1180
  const attributes = parseString(arena, sel);
1175
1181
  // inlined: arena.walkValues(attributes)
1176
1182
  for (const attr of new ValueWalker(arena, attributes)) {
1177
1183
  if (arena.dataTypes[attr] === EnumToken.PseudoClassFuncTokenType &&
1178
- arena.strings[arena.stringValue[attr]] === ":is") {
1184
+ arena.resolveString(arena.stringValue[attr]) === ":is") {
1179
1185
  let child = arena.lastToken[attr];
1180
1186
  while (child !== 0) {
1181
1187
  const previous = arena.previousSibling[child];
@@ -1207,12 +1213,15 @@ function wrapNodes(arena, previous, node, match, reducer) {
1207
1213
  let pSel = match.selector1.reduce(reducer, []).join(",");
1208
1214
  // @ts-ignore
1209
1215
  let nSel = match.selector2.reduce(reducer, []).join(",");
1210
- const wrapper = arena.clone(previous);
1216
+ const wrapper = arena.cloneNode(previous);
1211
1217
  // inlined: arena.setSelector(wrapper, match.match.reduce(reducer, []).join(","))
1212
1218
  // @ts-ignore
1213
1219
  arena.name[wrapper] = arena.internString(match.match.reduce(reducer, []).join(","));
1214
- arena.raw[wrapper] = match.match.map((t) => t.slice());
1215
- arena.optimized[wrapper] = null;
1220
+ arena.raw.set(wrapper, match.match.map((t) => t.slice()));
1221
+ // not copied by cloneNode()
1222
+ if (arena.optimized.get(wrapper) != null) {
1223
+ arena.optimized.set(wrapper, null);
1224
+ }
1216
1225
  // inlined: arena.setTokens(wrapper)
1217
1226
  arena.setTokenList(wrapper, []);
1218
1227
  const parent = arena.parents[node];
@@ -1242,14 +1251,14 @@ function wrapNodes(arena, previous, node, match, reducer) {
1242
1251
  if (arena.parents[previous] === wrapper) {
1243
1252
  // inlined: arena.setSelector(previous, pSel)
1244
1253
  arena.name[previous] = arena.internString(pSel);
1245
- arena.raw[previous] = match.selector1;
1254
+ arena.raw.set(previous, match.selector1);
1246
1255
  // inlined: arena.setTokens(previous)
1247
1256
  arena.setTokenList(previous, []);
1248
1257
  }
1249
1258
  if (arena.parents[node] === wrapper) {
1250
1259
  // inlined: arena.setSelector(node, nSel)
1251
1260
  arena.name[node] = arena.internString(nSel);
1252
- arena.raw[node] = match.selector2;
1261
+ arena.raw.set(node, match.selector2);
1253
1262
  // inlined: arena.setTokens(node)
1254
1263
  arena.setTokenList(node, []);
1255
1264
  }
@@ -1258,6 +1267,21 @@ function wrapNodes(arena, previous, node, match, reducer) {
1258
1267
  arena.setTokenList(wrapper, []);
1259
1268
  return wrapper;
1260
1269
  }
1270
+ /**
1271
+ * true if a child of the node is an at-rule without a block or an `@apply` rule: `@apply --mixin;`,
1272
+ * `@apply --mixin { color: red }`
1273
+ * @param arena
1274
+ * @param node
1275
+ */
1276
+ function hasAtRuleStatement(arena, node) {
1277
+ for (let child = arena.firstChild[node]; child !== 0; child = arena.nextSibling[child]) {
1278
+ if (arena.dataTypes[child] === EnumToken.AtRuleNodeType &&
1279
+ (!(arena.flags[child] & EnumAstNodeStatus.HasChildren) || arena.stringEquals(arena.name[child], "apply"))) {
1280
+ return true;
1281
+ }
1282
+ }
1283
+ return false;
1284
+ }
1261
1285
  /**
1262
1286
  * Diff nodes: move the declarations shared by both rules into a new rule
1263
1287
  * @param arena
@@ -1269,6 +1293,11 @@ function wrapNodes(arena, previous, node, match, reducer) {
1269
1293
  * @private
1270
1294
  */
1271
1295
  function diff(arena, n1, n2, options, context) {
1296
+ // the declarations of a rule that applies a mixin are not moved: `@apply` inserts declarations at its position,
1297
+ // the declarations that follow it override them
1298
+ if (hasAtRuleStatement(arena, n1) || hasAtRuleStatement(arena, n2)) {
1299
+ return null;
1300
+ }
1272
1301
  if (!("cache" in options)) {
1273
1302
  options.cache = new Map();
1274
1303
  }
@@ -1281,9 +1310,23 @@ function diff(arena, n1, n2, options, context) {
1281
1310
  node2 = t;
1282
1311
  exchanged = true;
1283
1312
  }
1284
- const raw1 = arena.raw[node1];
1285
- const raw2 = arena.raw[node2];
1286
- if (raw1 != null && raw2 != null) {
1313
+ const raw1 = arena.raw.get(node1);
1314
+ const raw2 = arena.raw.get(node2);
1315
+ if (raw1 == null || raw2 == null) {
1316
+ // the selectors that are not split (see isSimpleSelector()): the vendor prefixes of the pseudo classes are
1317
+ // read from the code units of the selectors
1318
+ const prefixes1 = raw1 == null ? selectorPrefixes(arena, arena.name[node1]) : rawSelectorPrefixes(raw1);
1319
+ const prefixes2 = raw2 == null ? selectorPrefixes(arena, arena.name[node2]) : rawSelectorPrefixes(raw2);
1320
+ if (prefixes1.size !== prefixes2.size) {
1321
+ return null;
1322
+ }
1323
+ for (const prefix of prefixes1) {
1324
+ if (!prefixes2.has(prefix)) {
1325
+ return null;
1326
+ }
1327
+ }
1328
+ }
1329
+ else {
1287
1330
  const prefixes1 = new Set();
1288
1331
  const prefixes2 = new Set();
1289
1332
  for (const token1 of raw1) {
@@ -1355,25 +1398,30 @@ function diff(arena, n1, n2, options, context) {
1355
1398
  // identical values are rendered once
1356
1399
  const renderer = (context.renderer ??= new NodeRenderer(options));
1357
1400
  const renderedSize = (node, cache) => {
1358
- let css = cache ? options.cache.get(node) : undefined;
1359
- if (css == null) {
1360
- css = renderer.render(arena, node);
1401
+ let size = cache ? options.cache.get(node) : undefined;
1402
+ if (size === undefined) {
1403
+ size = renderer.size(arena, node);
1361
1404
  if (cache) {
1362
- options.cache.set(node, css);
1405
+ options.cache.set(node, size);
1363
1406
  }
1364
1407
  }
1365
- return arena.firstChild[node] === 0 ? 0 : css.length;
1408
+ return arena.firstChild[node] === 0 ? 0 : size;
1366
1409
  };
1367
1410
  // size of the original nodes
1368
1411
  const size = renderedSize(n1, true) + renderedSize(n2, true);
1369
1412
  // the shared declarations are moved into the result node
1370
- const result = arena.clone(node1);
1371
- // inlined: arena.setSelector(result, [ ...new Set(splitRule(arena.strings[arena.name[node1]]) .concat(splitRule(arena.strings[arena.name[node2]])) .map((s) => s.join(""))), ].join(","))
1372
- arena.name[result] = arena.internString([
1373
- ...new Set(splitRule(arena.strings[arena.name[node1]])
1374
- .concat(splitRule(arena.strings[arena.name[node2]]))
1375
- .map((s) => s.join(""))),
1376
- ].join(","));
1413
+ const result = arena.cloneNode(node1);
1414
+ // the distinct selectors of both rules: built from the code units of the selectors when they are normalized
1415
+ let merged = mergeSelectors(arena, arena.name[node1], arena.name[node2]);
1416
+ if (merged === -1) {
1417
+ // inlined: arena.setSelector(result, [ ...new Set(splitRule(arena.resolveString(arena.name[node1])) .concat(splitRule(arena.resolveString(arena.name[node2]))) .map((s) => s.join(""))), ].join(","))
1418
+ merged = arena.internString([
1419
+ ...new Set(splitRule(arena.resolveString(arena.name[node1]))
1420
+ .concat(splitRule(arena.resolveString(arena.name[node2])))
1421
+ .map((s) => s.join(""))),
1422
+ ].join(","));
1423
+ }
1424
+ arena.name[result] = merged;
1377
1425
  // the matched declarations of node1 are moved into the result, the duplicates in node2 are dropped.
1378
1426
  // the moves are recorded (node, parent, next sibling) to be undone when the result is not smaller
1379
1427
  const moves = [];
@@ -1399,9 +1447,12 @@ function diff(arena, n1, n2, options, context) {
1399
1447
  arena.insertBefore(n1, result);
1400
1448
  options.cache.delete(node1);
1401
1449
  options.cache.delete(node2);
1402
- if (size <= renderedSize(node1, false) + renderedSize(node2, false) + renderedSize(result, false) &&
1403
- arena.firstChild[node1] !== 0 &&
1404
- arena.firstChild[node2] !== 0) {
1450
+ // the merge is kept when the output is smaller, or when it has the same size and removes a rule (an emptied rule is
1451
+ // removed, its size is 0). the other rule keeps its selector, which is repeated in the merged selector: the merge of
1452
+ // `html{margin:0}` and `body,div,...{margin:0;font:inherit}` is larger than the rules
1453
+ const mergedSize = renderedSize(node1, false) + renderedSize(node2, false) + renderedSize(result, false);
1454
+ if (size < mergedSize ||
1455
+ (size === mergedSize && arena.firstChild[node1] !== 0 && arena.firstChild[node2] !== 0)) {
1405
1456
  // restore the nodes: undo the moves in reverse order
1406
1457
  for (let k = moves.length - 3; k >= 0; k -= 3) {
1407
1458
  if (moves[k + 2] === 0) {
@@ -1416,25 +1467,17 @@ function diff(arena, n1, n2, options, context) {
1416
1467
  }
1417
1468
  // inlined: arena.setTokens(result)
1418
1469
  arena.setTokenList(result, []);
1419
- arena.raw[result] = null;
1420
- arena.optimized[result] = null;
1421
- const optimized = optimizeSelector(splitRule(arena.strings[arena.name[result]]));
1470
+ // the raw and optimized selectors are not copied by cloneNode()
1471
+ if (arena.raw.get(result) != null) {
1472
+ arena.raw.set(result, null);
1473
+ }
1474
+ if (arena.optimized.get(result) != null) {
1475
+ arena.optimized.set(result, null);
1476
+ }
1477
+ const optimized = optimizeSelector(splitRule(arena.resolveString(arena.name[result])));
1422
1478
  if (optimized?.match) {
1423
- const rule = optimized.selector.reduce((acc, curr) => {
1424
- if (acc.length > 0) {
1425
- acc += ",";
1426
- }
1427
- if (curr.length > 2 && curr[0] === "&" && curr[1] === " ") {
1428
- return acc + curr.slice(2).join("");
1429
- }
1430
- else if (curr.length > 1 && curr[0] === "&") {
1431
- return acc + curr.slice(1).join("");
1432
- }
1433
- return acc + curr.join("");
1434
- }, "");
1435
- const match = optimized.optimized.join("");
1436
- const sel = match + ":is(" + arena.replaceCompound(rule, match) + ")";
1437
- if (sel.length < arena.strings[arena.name[result]].length) {
1479
+ const sel = factorSelector(optimized);
1480
+ if (sel != null && sel.length < arena.resolveString(arena.name[result]).length) {
1438
1481
  // inlined: arena.setSelector(result, sel)
1439
1482
  arena.name[result] = arena.internString(sel);
1440
1483
  // inlined: arena.setTokens(result)
@@ -1489,6 +1532,507 @@ function eqNode(arena, a, b) {
1489
1532
  }
1490
1533
  return true;
1491
1534
  }
1535
+ /**
1536
+ * builder of the merged selectors, see {@link mergeSelectors}
1537
+ */
1538
+ const mergedSelectors = new StringBuilder();
1539
+ /**
1540
+ * start and end of the selectors read by {@link selectorRanges}, in {@link mergedSelectors}
1541
+ */
1542
+ let selectorBounds = new Int32Array(64);
1543
+ /**
1544
+ * append the comma separated selectors of a selector string to {@link mergedSelectors} and record their bounds. the
1545
+ * selectors are the selectors of splitRule() joined: false when the selector string is not normalized (whitespace
1546
+ * other than a single space between two parts, a space after a comma)
1547
+ * @param arena
1548
+ * @param id selector string id
1549
+ * @param count number of selectors recorded
1550
+ * @returns the number of selectors recorded, -1 when the selector string is not normalized
1551
+ */
1552
+ function selectorRanges(arena, id, count) {
1553
+ const length = arena.stringLength(id);
1554
+ const offset = mergedSelectors.length;
1555
+ arena.appendString(mergedSelectors, id);
1556
+ const codes = mergedSelectors.codes;
1557
+ let start = offset;
1558
+ const add = (end) => {
1559
+ if ((count + 1) * 2 > selectorBounds.length) {
1560
+ const bounds = new Int32Array(selectorBounds.length * 2);
1561
+ bounds.set(selectorBounds);
1562
+ selectorBounds = bounds;
1563
+ }
1564
+ selectorBounds[count * 2] = start;
1565
+ selectorBounds[count * 2 + 1] = end;
1566
+ count++;
1567
+ };
1568
+ for (let i = offset; i < offset + length; i++) {
1569
+ const code = codes[i];
1570
+ if (isWhiteSpace(code)) {
1571
+ // a single space between two parts
1572
+ if (code !== 0x20 || i === start || isWhiteSpace(codes[i - 1])) {
1573
+ return -1;
1574
+ }
1575
+ continue;
1576
+ }
1577
+ if (code === 0x2c) {
1578
+ add(i);
1579
+ start = i + 1;
1580
+ continue;
1581
+ }
1582
+ if (code === 0x5c) {
1583
+ i++;
1584
+ continue;
1585
+ }
1586
+ // ( [: the part ends with the matching ) ]
1587
+ if (code === 0x28 || code === 0x5b) {
1588
+ const close = code === 0x28 ? 0x29 : 0x5d;
1589
+ let depth = 1;
1590
+ let k = i;
1591
+ let c;
1592
+ while (++k < offset + length) {
1593
+ c = codes[k];
1594
+ if (c === 0x5c) {
1595
+ k++;
1596
+ continue;
1597
+ }
1598
+ if (c === code) {
1599
+ depth++;
1600
+ }
1601
+ else if (c === close) {
1602
+ depth--;
1603
+ }
1604
+ if (depth === 0) {
1605
+ break;
1606
+ }
1607
+ }
1608
+ i = k;
1609
+ }
1610
+ }
1611
+ add(offset + length);
1612
+ return count;
1613
+ }
1614
+ /**
1615
+ * the distinct selectors of two selector strings, comma separated, like
1616
+ * `[...new Set(splitRule(sel1).concat(splitRule(sel2)).map((s) => s.join("")))].join(",")`. the selectors are read
1617
+ * from the string table and the result is interned: no string is created
1618
+ * @param arena
1619
+ * @param id1
1620
+ * @param id2
1621
+ * @returns the string id, -1 when a selector string is not normalized (see {@link selectorRanges})
1622
+ */
1623
+ function mergeSelectors(arena, id1, id2) {
1624
+ mergedSelectors.reset();
1625
+ let count = selectorRanges(arena, id1, 0);
1626
+ if (count === -1 || (count = selectorRanges(arena, id2, count)) === -1) {
1627
+ return -1;
1628
+ }
1629
+ const codes = mergedSelectors.codes;
1630
+ const end = mergedSelectors.length;
1631
+ // the result is built after the selectors
1632
+ for (let i = 0, written = 0; i < count; i++) {
1633
+ const start1 = selectorBounds[i * 2];
1634
+ const end1 = selectorBounds[i * 2 + 1];
1635
+ let duplicate = false;
1636
+ for (let k = 0; k < i && !duplicate; k++) {
1637
+ const start2 = selectorBounds[k * 2];
1638
+ const end2 = selectorBounds[k * 2 + 1];
1639
+ if (end2 - start2 === end1 - start1) {
1640
+ let j = 0;
1641
+ while (j < end1 - start1 && codes[start1 + j] === codes[start2 + j]) {
1642
+ j++;
1643
+ }
1644
+ duplicate = j === end1 - start1;
1645
+ }
1646
+ }
1647
+ if (duplicate) {
1648
+ continue;
1649
+ }
1650
+ if (written++ > 0) {
1651
+ mergedSelectors.appendCode(0x2c);
1652
+ }
1653
+ for (let j = start1; j < end1; j++) {
1654
+ // the builder may have been reallocated
1655
+ mergedSelectors.appendCode(mergedSelectors.codes[j]);
1656
+ }
1657
+ }
1658
+ // intern the result only
1659
+ const result = mergedSelectors.codes;
1660
+ return arena.internRange(result, end, mergedSelectors.length, -1 /* StringSource.Pool */);
1661
+ }
1662
+ /**
1663
+ * the split selector of a rule (see splitRule()): computed when it is not cached
1664
+ * @param arena
1665
+ * @param node
1666
+ */
1667
+ function rawSelector(arena, node) {
1668
+ let raw = arena.raw.get(node);
1669
+ if (raw == null) {
1670
+ raw = splitRule(arena.resolveString(arena.name[node]));
1671
+ arena.raw.set(node, raw);
1672
+ }
1673
+ return raw;
1674
+ }
1675
+ /**
1676
+ * start and end of the first part of a selector (see splitRule()): the leading whitespace is
1677
+ * skipped. the end is -1 when the first selector is empty
1678
+ * @param arena
1679
+ * @param id selector string id
1680
+ * @param part
1681
+ */
1682
+ function firstPartRange(arena, id, part) {
1683
+ // the code units are read until the end of the first part: the selector is not copied
1684
+ const length = arena.stringLength(id);
1685
+ let start = -1;
1686
+ let i = 0;
1687
+ part.end = -1;
1688
+ while (i < length && isWhiteSpace(arena.stringCodeAt(id, i))) {
1689
+ i++;
1690
+ }
1691
+ part.start = i;
1692
+ for (; i < length; i++) {
1693
+ const code = arena.stringCodeAt(id, i);
1694
+ if (isWhiteSpace(code)) {
1695
+ part.end = i;
1696
+ return;
1697
+ }
1698
+ // ,
1699
+ if (code === 0x2c) {
1700
+ part.end = start === -1 ? -1 : i;
1701
+ return;
1702
+ }
1703
+ // . :
1704
+ if (code === 0x2e || code === 0x3a) {
1705
+ if (start !== -1) {
1706
+ part.end = i;
1707
+ return;
1708
+ }
1709
+ start = i;
1710
+ if (code === 0x3a && arena.stringCodeAt(id, i + 1) === 0x3a) {
1711
+ i++;
1712
+ }
1713
+ continue;
1714
+ }
1715
+ // the combinators: a part
1716
+ if (code === 0x2b || code === 0x3e || code === 0x7e || code === 0x7c) {
1717
+ part.end = start !== -1 ? i : code === 0x7c && arena.stringCodeAt(id, i + 1) === 0x7c ? i + 2 : i + 1;
1718
+ return;
1719
+ }
1720
+ if (start === -1) {
1721
+ start = i;
1722
+ }
1723
+ // \: the escaped character
1724
+ if (code === 0x5c) {
1725
+ i++;
1726
+ continue;
1727
+ }
1728
+ // ( [: the part ends with the matching ) ]
1729
+ if (code === 0x28 || code === 0x5b) {
1730
+ const close = code === 0x28 ? 0x29 : 0x5d;
1731
+ let depth = 1;
1732
+ let k = i;
1733
+ let c;
1734
+ while (++k < length) {
1735
+ c = arena.stringCodeAt(id, k);
1736
+ if (c === 0x5c) {
1737
+ k++;
1738
+ continue;
1739
+ }
1740
+ if (c === code) {
1741
+ depth++;
1742
+ }
1743
+ else if (c === close) {
1744
+ depth--;
1745
+ }
1746
+ if (depth === 0) {
1747
+ break;
1748
+ }
1749
+ }
1750
+ i = k;
1751
+ }
1752
+ }
1753
+ part.end = start === -1 ? -1 : Math.min(i, length);
1754
+ }
1755
+ const firstPart1 = { str: null, start: 0, end: 0 };
1756
+ const firstPart2 = { str: null, start: 0, end: 0 };
1757
+ /**
1758
+ * the first part of the first selector of a rule. false when the first selector is empty
1759
+ * @param arena
1760
+ * @param node
1761
+ * @param part
1762
+ */
1763
+ function firstPart(arena, node, part) {
1764
+ const raw = arena.raw.get(node);
1765
+ if (raw != null) {
1766
+ // the split selector: the first part is a string
1767
+ part.str = raw.length > 0 && raw[0].length > 0 ? raw[0][0] : null;
1768
+ return part.str != null;
1769
+ }
1770
+ part.str = null;
1771
+ firstPartRange(arena, arena.name[node], part);
1772
+ return part.end !== -1;
1773
+ }
1774
+ /**
1775
+ * false when the selectors of two rules cannot match (see matchSelectors()): the first parts of their first selectors
1776
+ * are different. the selectors that are not split are read from the string table: they are not split
1777
+ * @param arena
1778
+ * @param node1
1779
+ * @param node2
1780
+ */
1781
+ function mayMatchSelectors(arena, node1, node2) {
1782
+ if (!firstPart(arena, node1, firstPart1) || !firstPart(arena, node2, firstPart2)) {
1783
+ return false;
1784
+ }
1785
+ const id1 = arena.name[node1];
1786
+ const id2 = arena.name[node2];
1787
+ const str1 = firstPart1.str;
1788
+ const str2 = firstPart2.str;
1789
+ const length1 = str1 != null ? str1.length : firstPart1.end - firstPart1.start;
1790
+ const length2 = str2 != null ? str2.length : firstPart2.end - firstPart2.start;
1791
+ if (length1 !== length2) {
1792
+ return false;
1793
+ }
1794
+ for (let i = 0; i < length1; i++) {
1795
+ const code1 = str1 != null ? str1.charCodeAt(i) : arena.stringCodeAt(id1, firstPart1.start + i);
1796
+ const code2 = str2 != null ? str2.charCodeAt(i) : arena.stringCodeAt(id2, firstPart2.start + i);
1797
+ if (code1 !== code2) {
1798
+ return false;
1799
+ }
1800
+ }
1801
+ return true;
1802
+ }
1803
+ /**
1804
+ * code units of the selector read by {@link selectorPrefixes}
1805
+ */
1806
+ let selectorCodes = new Uint16Array(256);
1807
+ /**
1808
+ * copy the code units of a selector to {@link selectorCodes}
1809
+ * @param arena
1810
+ * @param id
1811
+ * @returns the number of code units
1812
+ */
1813
+ function readSelector(arena, id) {
1814
+ const length = arena.stringLength(id);
1815
+ if (selectorCodes.length < length) {
1816
+ selectorCodes = new Uint16Array(length * 2);
1817
+ }
1818
+ return arena.copyString(id, selectorCodes, 0);
1819
+ }
1820
+ /**
1821
+ * true if a rule selector is not modified by {@link reduceRuleSelector}: a single selector (no comma), that does not
1822
+ * start with `&`, does not end with `)` (`:is()`), a combinator or a whitespace, and has no whitespace other than single
1823
+ * spaces. the selector is read from the string table, the result is computed once per string id
1824
+ * @param arena
1825
+ * @param id selector string id
1826
+ */
1827
+ function isSimpleSelector(arena, id) {
1828
+ selectorArena = arena;
1829
+ return arena.stringFlagId(id, 1 /* StringFlag.SimpleSelector */, computeSimpleSelector);
1830
+ }
1831
+ /**
1832
+ * the arena of the selector read by {@link computeSimpleSelector} and {@link hasVendorPrefix}: the functions passed to
1833
+ * the string table are not closures (no allocation per call)
1834
+ */
1835
+ let selectorArena = null;
1836
+ /**
1837
+ * see {@link isSimpleSelector}
1838
+ * @param id selector string id
1839
+ */
1840
+ function computeSimpleSelector(id) {
1841
+ {
1842
+ const length = readSelector(selectorArena, id);
1843
+ const codes = selectorCodes;
1844
+ if (length === 0 || codes[0] === 0x26) {
1845
+ return false;
1846
+ }
1847
+ let previous = 0;
1848
+ for (let i = 0; i < length; i++) {
1849
+ const code = codes[i];
1850
+ if (code === 0x2c) {
1851
+ return false;
1852
+ }
1853
+ if (isWhiteSpace(code)) {
1854
+ // a single space between two parts
1855
+ if (code !== 0x20 || i === 0 || isWhiteSpace(previous)) {
1856
+ return false;
1857
+ }
1858
+ }
1859
+ previous = code;
1860
+ }
1861
+ // ) + > ~ | and the whitespace
1862
+ return !(previous === 0x29 ||
1863
+ previous === 0x2b ||
1864
+ previous === 0x3e ||
1865
+ previous === 0x7e ||
1866
+ previous === 0x7c ||
1867
+ isWhiteSpace(previous));
1868
+ }
1869
+ }
1870
+ /**
1871
+ * the first vendor prefix of a part of a selector: `::?-([a-z]+)-`, null when there is none
1872
+ * @param codes
1873
+ * @param start
1874
+ * @param end
1875
+ */
1876
+ function partPrefix(codes, start, end) {
1877
+ for (let p = start; p < end; p++) {
1878
+ if (codes[p] !== 0x3a) {
1879
+ continue;
1880
+ }
1881
+ let q = p + 1;
1882
+ if (q < end && codes[q] === 0x3a) {
1883
+ q++;
1884
+ }
1885
+ if (q >= end || codes[q] !== 0x2d) {
1886
+ continue;
1887
+ }
1888
+ let k = q + 1;
1889
+ while (k < end && codes[k] >= 0x61 && codes[k] <= 0x7a) {
1890
+ k++;
1891
+ }
1892
+ if (k > q + 1 && k < end && codes[k] === 0x2d) {
1893
+ return String.fromCharCode.apply(null, codes.subarray(q + 1, k));
1894
+ }
1895
+ }
1896
+ return null;
1897
+ }
1898
+ /**
1899
+ * no vendor prefix. read only
1900
+ */
1901
+ const emptyPrefixes = new Set();
1902
+ /**
1903
+ * true if a selector contains `:-` (`::?-([a-z]+)-` matches `:-`)
1904
+ * @param id
1905
+ */
1906
+ function hasVendorPrefix(id) {
1907
+ const length = readSelector(selectorArena, id);
1908
+ for (let i = 0; i + 1 < length; i++) {
1909
+ if (selectorCodes[i] === 0x3a && selectorCodes[i + 1] === 0x2d) {
1910
+ return true;
1911
+ }
1912
+ }
1913
+ return false;
1914
+ }
1915
+ /**
1916
+ * the vendor prefixes of the pseudo classes of a selector, like the prefixes read from the parts of the split selector
1917
+ * in diff(): the parts are the parts of splitRule(), the first prefix of each part that contains `:`. the selector is
1918
+ * read from the string table, it is not split into strings
1919
+ * @param arena
1920
+ * @param id selector string id
1921
+ */
1922
+ function selectorPrefixes(arena, id) {
1923
+ // the selectors without `:-` are skipped: computed once per string id
1924
+ selectorArena = arena;
1925
+ if (!arena.stringFlagId(id, 2 /* StringFlag.VendorPrefix */, hasVendorPrefix)) {
1926
+ return emptyPrefixes;
1927
+ }
1928
+ const prefixes = new Set();
1929
+ const length = readSelector(arena, id);
1930
+ const codes = selectorCodes;
1931
+ // the part boundaries of splitRule()
1932
+ let start = -1;
1933
+ let code;
1934
+ const addPart = (end) => {
1935
+ for (let k = start; k < end; k++) {
1936
+ if (codes[k] === 0x3a) {
1937
+ const prefix = partPrefix(codes, start, end);
1938
+ if (prefix != null) {
1939
+ prefixes.add(prefix);
1940
+ }
1941
+ break;
1942
+ }
1943
+ }
1944
+ return prefixes.size > 1;
1945
+ };
1946
+ for (let i = 0; i < length; i++) {
1947
+ code = codes[i];
1948
+ if (isWhiteSpace(code) || code === 0x2c) {
1949
+ if (start !== -1 && addPart(i)) {
1950
+ return prefixes;
1951
+ }
1952
+ start = -1;
1953
+ continue;
1954
+ }
1955
+ if (code === 0x2e || code === 0x3a) {
1956
+ if (start !== -1 && addPart(i)) {
1957
+ return prefixes;
1958
+ }
1959
+ start = i;
1960
+ if (code === 0x3a && codes[i + 1] === 0x3a) {
1961
+ i++;
1962
+ }
1963
+ continue;
1964
+ }
1965
+ if (code === 0x2b || code === 0x3e || code === 0x7e || code === 0x7c) {
1966
+ if (start !== -1 && addPart(i)) {
1967
+ return prefixes;
1968
+ }
1969
+ start = -1;
1970
+ if (code === 0x7c && codes[i + 1] === 0x7c) {
1971
+ i++;
1972
+ }
1973
+ continue;
1974
+ }
1975
+ if (start === -1) {
1976
+ start = i;
1977
+ }
1978
+ if (code === 0x5c) {
1979
+ i++;
1980
+ continue;
1981
+ }
1982
+ if (code === 0x28 || code === 0x5b) {
1983
+ const close = code === 0x28 ? 0x29 : 0x5d;
1984
+ let depth = 1;
1985
+ let k = i;
1986
+ let c;
1987
+ while (++k < length) {
1988
+ c = codes[k];
1989
+ if (c === 0x5c) {
1990
+ k++;
1991
+ continue;
1992
+ }
1993
+ if (c === code) {
1994
+ depth++;
1995
+ }
1996
+ else if (c === close) {
1997
+ depth--;
1998
+ }
1999
+ if (depth === 0) {
2000
+ break;
2001
+ }
2002
+ }
2003
+ i = k;
2004
+ }
2005
+ }
2006
+ if (start !== -1) {
2007
+ addPart(length);
2008
+ }
2009
+ return prefixes;
2010
+ }
2011
+ /**
2012
+ * the vendor prefixes of the pseudo classes of a split selector, see diff()
2013
+ * @param raw
2014
+ */
2015
+ function rawSelectorPrefixes(raw) {
2016
+ const prefixes = new Set();
2017
+ for (const token of raw) {
2018
+ for (const t of token) {
2019
+ if (t.includes(":")) {
2020
+ const matches = t.match(/::?-([a-z]+)-/);
2021
+ if (matches == null) {
2022
+ continue;
2023
+ }
2024
+ prefixes.add(matches[1]);
2025
+ if (prefixes.size > 1) {
2026
+ break;
2027
+ }
2028
+ }
2029
+ }
2030
+ if (prefixes.size > 1) {
2031
+ break;
2032
+ }
2033
+ }
2034
+ return prefixes;
2035
+ }
1492
2036
  /**
1493
2037
  * Reduce rule selector
1494
2038
  * @param arena
@@ -1497,16 +2041,16 @@ function eqNode(arena, a, b) {
1497
2041
  * @private
1498
2042
  */
1499
2043
  function reduceRuleSelector(arena, node) {
1500
- if (arena.raw[node] == null) {
1501
- arena.raw[node] = splitRule(arena.strings[arena.name[node]]);
2044
+ if (arena.raw.get(node) == null) {
2045
+ arena.raw.set(node, splitRule(arena.resolveString(arena.name[node])));
1502
2046
  }
1503
- const raw = arena.raw[node];
2047
+ const raw = arena.raw.get(node);
1504
2048
  const singleSelectorWithoutIs = raw.length === 1 && (raw[0].at(-1) == null || !raw[0].at(-1).startsWith(":is("));
1505
2049
  let optimized = optimizeSelector(singleSelectorWithoutIs
1506
2050
  ? raw
1507
2051
  : raw.map((curr) => curr.slice()));
1508
2052
  if (optimized != null) {
1509
- arena.optimized[node] = optimized;
2053
+ arena.optimized.set(node, optimized);
1510
2054
  }
1511
2055
  if (optimized != null && optimized.match && optimized.reducible && optimized.selector.length > 1) {
1512
2056
  for (const selector of optimized.selector) {
@@ -1542,10 +2086,10 @@ function reduceRuleSelector(arena, node) {
1542
2086
  [optimized.optimized[0], reduced.length === 1 ? reduced.join("") : ":is("].concat(reduced).concat(")"),
1543
2087
  ];
1544
2088
  const sel = raw[0].join("");
1545
- if (sel.length < arena.strings[arena.name[node]].length) {
2089
+ if (sel.length < arena.resolveString(arena.name[node]).length) {
1546
2090
  // inlined: arena.setSelector(node, sel)
1547
2091
  arena.name[node] = arena.internString(sel);
1548
- arena.raw[node] = raw;
2092
+ arena.raw.set(node, raw);
1549
2093
  // inlined: arena.setTokens(node)
1550
2094
  arena.setTokenList(node, []);
1551
2095
  }