@tbela99/css-parser 1.4.2 → 1.4.4

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 (122) hide show
  1. package/CHANGELOG.md +354 -4
  2. package/README.md +69 -1077
  3. package/dist/config.json.js +76 -3
  4. package/dist/index-umd-web.js +26838 -18743
  5. package/dist/index.cjs +26819 -18731
  6. package/dist/index.d.ts +2471 -1884
  7. package/dist/lib/ast/clone.js +46 -0
  8. package/dist/lib/ast/expand.js +90 -65
  9. package/dist/lib/ast/features/calc.js +86 -43
  10. package/dist/lib/ast/features/if.js +221 -0
  11. package/dist/lib/ast/features/index.js +1 -0
  12. package/dist/lib/ast/features/inlinecssvariables.js +33 -28
  13. package/dist/lib/ast/features/prefix.js +406 -44
  14. package/dist/lib/ast/features/shorthand.js +6 -9
  15. package/dist/lib/ast/features/transform.js +14 -15
  16. package/dist/lib/ast/find.js +175 -0
  17. package/dist/lib/ast/math/expression.js +145 -99
  18. package/dist/lib/ast/math/math.js +30 -41
  19. package/dist/lib/ast/minify.js +551 -232
  20. package/dist/lib/ast/transform/compute.js +82 -69
  21. package/dist/lib/ast/transform/matrix.js +12 -26
  22. package/dist/lib/ast/transform/minify.js +154 -150
  23. package/dist/lib/ast/transform/perspective.js +1 -1
  24. package/dist/lib/ast/transform/rotate.js +1 -1
  25. package/dist/lib/ast/transform/scale.js +1 -1
  26. package/dist/lib/ast/transform/skew.js +1 -1
  27. package/dist/lib/ast/transform/translate.js +1 -1
  28. package/dist/lib/ast/transform/utils.js +3 -2
  29. package/dist/lib/ast/types.js +345 -30
  30. package/dist/lib/ast/walk.js +119 -64
  31. package/dist/lib/fs/resolve.js +94 -88
  32. package/dist/lib/parser/declaration/list.js +117 -26
  33. package/dist/lib/parser/declaration/map.js +141 -96
  34. package/dist/lib/parser/declaration/set.js +30 -25
  35. package/dist/lib/parser/parse.js +1810 -1739
  36. package/dist/lib/parser/tokenize.js +662 -403
  37. package/dist/lib/parser/utils/angle.js +29 -0
  38. package/dist/lib/parser/utils/at-rule-container.js +486 -0
  39. package/dist/lib/parser/utils/at-rule-font-feature-values.js +13 -0
  40. package/dist/lib/parser/utils/at-rule-generic.js +118 -0
  41. package/dist/lib/parser/utils/at-rule-import.js +393 -0
  42. package/dist/lib/parser/utils/at-rule-media.js +603 -0
  43. package/dist/lib/parser/utils/at-rule-support.js +431 -0
  44. package/dist/lib/parser/utils/at-rule-when-else.js +363 -0
  45. package/dist/lib/parser/utils/at-rule.js +31 -0
  46. package/dist/lib/parser/utils/cache.js +19 -0
  47. package/dist/lib/parser/utils/config.js +1 -0
  48. package/dist/lib/parser/utils/declaration.js +672 -91
  49. package/dist/lib/parser/utils/hash.js +1 -1
  50. package/dist/lib/parser/utils/selector.js +518 -0
  51. package/dist/lib/parser/utils/text.js +17 -1
  52. package/dist/lib/parser/utils/token.js +104 -0
  53. package/dist/lib/parser/utils/type.js +29 -18
  54. package/dist/lib/renderer/render.js +870 -269
  55. package/dist/lib/renderer/sourcemap/sourcemap.js +17 -7
  56. package/dist/lib/syntax/color/a98rgb.js +8 -12
  57. package/dist/lib/syntax/color/alpha.js +64 -0
  58. package/dist/lib/syntax/color/cmyk.js +23 -21
  59. package/dist/lib/syntax/color/color-mix.js +311 -237
  60. package/dist/lib/syntax/color/color.js +98 -92
  61. package/dist/lib/syntax/color/hex.js +29 -33
  62. package/dist/lib/syntax/color/hsl.js +7 -14
  63. package/dist/lib/syntax/color/hwb.js +14 -27
  64. package/dist/lib/syntax/color/lab.js +23 -24
  65. package/dist/lib/syntax/color/lch.js +16 -18
  66. package/dist/lib/syntax/color/oklab.js +21 -40
  67. package/dist/lib/syntax/color/oklch.js +16 -18
  68. package/dist/lib/syntax/color/p3.js +0 -8
  69. package/dist/lib/syntax/color/rec2020.js +9 -13
  70. package/dist/lib/syntax/color/relativecolor.js +160 -48
  71. package/dist/lib/syntax/color/rgb.js +14 -18
  72. package/dist/lib/syntax/color/srgb.js +30 -29
  73. package/dist/lib/syntax/color/utils/color-type.js +18 -0
  74. package/dist/lib/syntax/color/utils/colorspace.js +46 -0
  75. package/dist/lib/syntax/color/utils/components.js +36 -16
  76. package/dist/lib/syntax/color/utils/distance.js +21 -11
  77. package/dist/lib/syntax/color/utils/make-color.js +56 -0
  78. package/dist/lib/syntax/color/xyz.js +10 -22
  79. package/dist/lib/syntax/color/xyzd50.js +6 -20
  80. package/dist/lib/syntax/constants.js +464 -0
  81. package/dist/lib/syntax/syntax.js +825 -592
  82. package/dist/lib/validation/config.js +72 -33
  83. package/dist/lib/validation/config.json.js +1185 -85
  84. package/dist/lib/validation/match.js +3120 -0
  85. package/dist/lib/validation/parser/parse.js +683 -935
  86. package/dist/lib/validation/parser/typedef.js +106 -0
  87. package/dist/lib/validation/utils/list.js +4 -11
  88. package/dist/lib/validation/utils/whitespace.js +2 -8
  89. package/dist/node.js +102 -57
  90. package/dist/web.js +100 -48
  91. package/package.json +31 -17
  92. package/dist/lib/syntax/color/utils/constants.js +0 -214
  93. package/dist/lib/syntax/utils.js +0 -70
  94. package/dist/lib/validation/at-rules/container.js +0 -342
  95. package/dist/lib/validation/at-rules/counter-style.js +0 -90
  96. package/dist/lib/validation/at-rules/custom-media.js +0 -50
  97. package/dist/lib/validation/at-rules/document.js +0 -89
  98. package/dist/lib/validation/at-rules/else.js +0 -5
  99. package/dist/lib/validation/at-rules/font-feature-values.js +0 -63
  100. package/dist/lib/validation/at-rules/import.js +0 -150
  101. package/dist/lib/validation/at-rules/keyframes.js +0 -67
  102. package/dist/lib/validation/at-rules/layer.js +0 -41
  103. package/dist/lib/validation/at-rules/media.js +0 -255
  104. package/dist/lib/validation/at-rules/namespace.js +0 -81
  105. package/dist/lib/validation/at-rules/page-margin-box.js +0 -64
  106. package/dist/lib/validation/at-rules/page.js +0 -100
  107. package/dist/lib/validation/at-rules/supports.js +0 -295
  108. package/dist/lib/validation/at-rules/when.js +0 -185
  109. package/dist/lib/validation/atrule.js +0 -184
  110. package/dist/lib/validation/selector.js +0 -36
  111. package/dist/lib/validation/syntax.js +0 -1073
  112. package/dist/lib/validation/syntaxes/complex-selector-list.js +0 -27
  113. package/dist/lib/validation/syntaxes/complex-selector.js +0 -52
  114. package/dist/lib/validation/syntaxes/compound-selector.js +0 -196
  115. package/dist/lib/validation/syntaxes/family-name.js +0 -57
  116. package/dist/lib/validation/syntaxes/keyframe-selector.js +0 -36
  117. package/dist/lib/validation/syntaxes/layer-name.js +0 -57
  118. package/dist/lib/validation/syntaxes/relative-selector-list.js +0 -31
  119. package/dist/lib/validation/syntaxes/relative-selector.js +0 -38
  120. package/dist/lib/validation/syntaxes/selector-list.js +0 -5
  121. package/dist/lib/validation/syntaxes/selector.js +0 -5
  122. package/dist/lib/validation/syntaxes/url.js +0 -40
@@ -1,23 +1,28 @@
1
- import { parseString, replaceToken } from '../parser/parse.js';
2
- import '../parser/tokenize.js';
3
- import '../parser/utils/config.js';
4
- import { EnumToken } from './types.js';
5
- import { walkValues } from './walk.js';
6
- import { doRender, renderToken } from '../renderer/render.js';
7
- import '../renderer/sourcemap/lib/encode.js';
8
- import { isWhiteSpace, isIdent, isFunction, isIdentStart } from '../syntax/syntax.js';
9
1
  import { eq } from '../parser/utils/eq.js';
2
+ import { renderValue, doRender } from '../renderer/render.js';
10
3
  import * as index from './features/index.js';
4
+ import { walkValues } from './walk.js';
5
+ import { EnumToken } from './types.js';
6
+ import { isWhiteSpace, isIdent, isFunction, isIdentStart } from '../syntax/syntax.js';
11
7
  import { FeatureWalkMode } from './features/type.js';
8
+ import { trimArray } from '../validation/match.js';
9
+ import { definedPropertySettings, combinators } from '../syntax/constants.js';
10
+ import { replaceNodeOrValue } from '../parser/utils/token.js';
11
+ import { parseString } from '../parser/parse.js';
12
+ import { tokenize } from '../parser/tokenize.js';
13
+ import { replaceCompound } from './expand.js';
12
14
 
13
- const combinators = ['+', '>', '~', '||', '|'];
14
- const definedPropertySettings = { configurable: true, enumerable: false, writable: true };
15
- const notEndingWith = ['(', '['].concat(combinators);
16
- const rules = [EnumToken.AtRuleNodeType, EnumToken.RuleNodeType, EnumToken.AtRuleTokenType, EnumToken.KeyFramesRuleNodeType];
15
+ const notEndingWith = ["(", "["].concat(combinators);
16
+ const rules = [
17
+ EnumToken.AtRuleNodeType,
18
+ EnumToken.RuleNodeType,
19
+ EnumToken.AtRuleTokenType,
20
+ EnumToken.KeyFramesRuleNodeType,
21
+ ];
17
22
  // @ts-ignore
18
23
  const features = Object.values(index).sort((a, b) => a.ordering - b.ordering);
19
24
  /**
20
- * apply minification rules to the ast tree
25
+ * Apply minification rules to the ast tree
21
26
  * @param ast
22
27
  * @param options
23
28
  * @param recursive
@@ -31,14 +36,15 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
31
36
  let postprocess = false;
32
37
  let parents;
33
38
  let replacement;
34
- if (!('features' in options)) {
39
+ if (!("features" in options)) {
35
40
  // @ts-ignore
36
41
  options = {
37
42
  removeDuplicateDeclarations: true,
38
43
  computeShorthand: true,
39
44
  computeCalcExpression: true,
40
45
  removePrefix: false,
41
- features: [], ...options
46
+ features: [],
47
+ ...options,
42
48
  };
43
49
  for (const feature of features) {
44
50
  feature.register(options);
@@ -56,17 +62,23 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
56
62
  if (preprocess) {
57
63
  parents = new Set([ast]);
58
64
  for (const parent of parents) {
59
- if (parent.typ == EnumToken.CommentTokenType ||
60
- parent.typ == EnumToken.CDOCOMMTokenType) {
65
+ if (parent.typ == EnumToken.CommentTokenType || parent.typ == EnumToken.CDOCOMMTokenType) {
61
66
  continue;
62
67
  }
63
68
  replacement = parent;
64
69
  for (const feature of options.features) {
65
- if ((feature.processMode & FeatureWalkMode.Pre) === 0 || (feature.accept != null && !feature.accept.has(parent.typ))) {
70
+ if ((feature.processMode & FeatureWalkMode.Pre) === 0 ||
71
+ (feature.accept != null && !feature.accept.has(parent.typ))) {
66
72
  continue;
67
73
  }
68
74
  if (rules.includes(replacement.typ) && !Array.isArray(replacement.tokens)) {
69
- Object.defineProperty(replacement, 'tokens', { ...definedPropertySettings, value: parseString(replacement.typ == EnumToken.RuleNodeType || replacement.typ == EnumToken.KeyFramesRuleNodeType ? replacement.sel : replacement.val) });
75
+ Object.defineProperty(replacement, "tokens", {
76
+ ...definedPropertySettings,
77
+ value: parseString(replacement.typ == EnumToken.RuleNodeType ||
78
+ replacement.typ === EnumToken.KeyFramesRuleNodeType
79
+ ? replacement.sel
80
+ : replacement.nam),
81
+ });
70
82
  }
71
83
  const result = feature.run(replacement, options, parent.parent ?? ast, context, FeatureWalkMode.Pre);
72
84
  if (result != null) {
@@ -75,20 +87,20 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
75
87
  }
76
88
  if (replacement != parent && parent.parent != null) {
77
89
  // @ts-ignore
78
- replaceToken(parent.parent, parent, replacement);
90
+ replaceNodeOrValue(parent.parent, parent, replacement);
79
91
  }
80
- if (('chi' in replacement)) {
92
+ if ("chi" in replacement) {
81
93
  // @ts-ignore
82
94
  for (const node of replacement.chi) {
83
- parents.add(Object.defineProperty(node, 'parent', {
95
+ parents.add(Object.defineProperty(node, "parent", {
84
96
  ...definedPropertySettings,
85
- value: replacement
97
+ value: replacement,
86
98
  }));
87
99
  }
88
100
  }
89
101
  }
90
102
  for (const feature of options.features) {
91
- if ((feature.processMode & FeatureWalkMode.Pre) && 'cleanup' in feature) {
103
+ if (feature.processMode & FeatureWalkMode.Pre && "cleanup" in feature) {
92
104
  // @ts-ignore
93
105
  feature.cleanup(ast, options, context, FeatureWalkMode.Pre);
94
106
  }
@@ -97,14 +109,14 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
97
109
  doMinify(ast, options, recursive, errors, nestingContent, context);
98
110
  parents = new Set([ast]);
99
111
  for (const parent of parents) {
100
- if (parent.typ == EnumToken.CommentTokenType ||
101
- parent.typ == EnumToken.CDOCOMMTokenType) {
112
+ if (parent.typ == EnumToken.CommentTokenType || parent.typ == EnumToken.CDOCOMMTokenType) {
102
113
  continue;
103
114
  }
104
115
  replacement = parent;
105
116
  if (postprocess) {
106
117
  for (const feature of options.features) {
107
- if ((feature.processMode & FeatureWalkMode.Post) === 0 || (feature.accept != null && !feature.accept.has(parent.typ))) {
118
+ if ((feature.processMode & FeatureWalkMode.Post) === 0 ||
119
+ (feature.accept != null && !feature.accept.has(parent.typ))) {
108
120
  continue;
109
121
  }
110
122
  const result = feature.run(replacement, options, parent.parent ?? ast, context, FeatureWalkMode.Post);
@@ -115,20 +127,20 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
115
127
  }
116
128
  if (replacement != null && replacement != parent && parent.parent != null) {
117
129
  // @ts-ignore
118
- replaceToken(parent.parent, parent, replacement);
130
+ replaceNodeOrValue(parent.parent, parent, replacement);
119
131
  }
120
- if (('chi' in replacement)) {
132
+ if ("chi" in replacement) {
121
133
  for (const node of replacement.chi) {
122
- parents.add(Object.defineProperty(node, 'parent', {
134
+ parents.add(Object.defineProperty(node, "parent", {
123
135
  ...definedPropertySettings,
124
- value: replacement
136
+ value: replacement,
125
137
  }));
126
138
  }
127
139
  }
128
140
  }
129
141
  if (postprocess) {
130
142
  for (const feature of options.features) {
131
- if (feature.processMode & FeatureWalkMode.Post && 'cleanup' in feature) {
143
+ if (feature.processMode & FeatureWalkMode.Post && "cleanup" in feature) {
132
144
  // @ts-ignore
133
145
  feature.cleanup(ast, options, context, FeatureWalkMode.Post);
134
146
  }
@@ -136,8 +148,143 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
136
148
  }
137
149
  return ast;
138
150
  }
151
+ function transformAtRuleMediaPrelude(values) {
152
+ let hasUpdates = false;
153
+ for (let { value, parent, parents } of walkValues(values)) {
154
+ if (value.typ === EnumToken.MediaQueryConditionTokenType) {
155
+ if (value.op.typ == EnumToken.AndTokenType &&
156
+ // @ts-ignore
157
+ value.l.typ === EnumToken.IdenTokenType &&
158
+ // @ts-ignore
159
+ value.l.val.toLowerCase() === "all") {
160
+ if (parent === null) {
161
+ // @ts-ignore
162
+ values[values.indexOf(value)] = value.l;
163
+ }
164
+ else {
165
+ replaceNodeOrValue(parent, value, value.l);
166
+ // @ts-ignore
167
+ value = value.l;
168
+ }
169
+ hasUpdates = true;
170
+ }
171
+ }
172
+ // range operator
173
+ if (parent != null &&
174
+ parent.typ === EnumToken.MediaQueryConditionTokenType &&
175
+ parent.op.typ == EnumToken.AndTokenType &&
176
+ // @ts-ignore
177
+ parent.l.typ == EnumToken.ParensTokenType) {
178
+ let token = parent.r.find((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
179
+ if (token?.typ === EnumToken.ParensTokenType) {
180
+ // @ts-ignore
181
+ const node1 = parent.l.chi.find((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
182
+ const node2 = token.chi.find((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
183
+ if (node1?.typ === EnumToken.MediaQueryConditionTokenType &&
184
+ node2?.typ === EnumToken.MediaQueryConditionTokenType &&
185
+ node1.op.typ == EnumToken.ColonTokenType &&
186
+ node2.op.typ == EnumToken.ColonTokenType &&
187
+ // @ts-ignore
188
+ node1.l.typ == EnumToken.IdenTokenType &&
189
+ // @ts-ignore
190
+ node2.l.typ == EnumToken.IdenTokenType &&
191
+ // @ts-ignore
192
+ node1.l.val.startsWith("min-") &&
193
+ // @ts-ignore
194
+ node2.l.val.startsWith("max-") &&
195
+ // @ts-ignore
196
+ node1.l.val.slice(4) ==
197
+ // @ts-ignore
198
+ node2.l.val.slice(4)) {
199
+ const val1 = node1.r.find((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
200
+ const val2 = node2.r.find((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
201
+ const replacement = {
202
+ typ: EnumToken.ParensTokenType,
203
+ chi: [
204
+ // @ts-ignore
205
+ {
206
+ typ: EnumToken.MediaRangeQueryTokenType,
207
+ op: {
208
+ typ: EnumToken.IdenTokenType,
209
+ // @ts-ignore
210
+ val: node1.l.val.slice(4),
211
+ },
212
+ l: val1,
213
+ r: val2,
214
+ loc: value.loc,
215
+ },
216
+ ],
217
+ };
218
+ // @ts-expect-error
219
+ const p = parents?.[parents?.indexOf?.(parent) + 1];
220
+ if (p != null) {
221
+ replaceNodeOrValue(p, parent, replacement);
222
+ }
223
+ else {
224
+ values.splice(values.indexOf(parent), 1, replacement);
225
+ }
226
+ hasUpdates = true;
227
+ value = replacement;
228
+ }
229
+ }
230
+ }
231
+ }
232
+ return { hasUpdates, values: trimArray(values) };
233
+ }
234
+ /**
235
+ * Minify at-rule media
236
+ * - remove redundant tokens
237
+ * - generate range queries
238
+ * @param ast
239
+ *
240
+ * @private
241
+ */
242
+ function minifyAtRuleMedia(tokens) {
243
+ let hasUpdates = false;
244
+ const sections = tokens
245
+ .reduce((acc, t) => {
246
+ if (t.typ === EnumToken.CommaTokenType) {
247
+ acc.push([]);
248
+ }
249
+ else {
250
+ acc[acc.length - 1].push(t);
251
+ }
252
+ return acc;
253
+ }, [[]])
254
+ .reduce((acc, values) => {
255
+ if (acc.has("all")) {
256
+ return acc;
257
+ }
258
+ const result = transformAtRuleMediaPrelude(values);
259
+ if (result.values.length === 0) {
260
+ return acc;
261
+ }
262
+ if (result.hasUpdates) {
263
+ hasUpdates = true;
264
+ }
265
+ acc.set(values.reduce((acc, t) => acc + renderValue(t), ""), result.values);
266
+ return acc;
267
+ }, new Map());
268
+ if (sections.has("all")) {
269
+ tokens.length = 0;
270
+ }
271
+ else if (hasUpdates) {
272
+ tokens.length = 0;
273
+ tokens.push(...[...sections.values()].reduce((acc, t) => {
274
+ if (acc.length > 0) {
275
+ acc.push({
276
+ typ: EnumToken.CommaTokenType,
277
+ });
278
+ }
279
+ acc.push(...t);
280
+ return acc;
281
+ }, []));
282
+ }
283
+ // return ast;
284
+ return tokens;
285
+ }
139
286
  /**
140
- * reduce selectors
287
+ * Reduce selectors
141
288
  * @param acc
142
289
  * @param curr
143
290
  *
@@ -145,20 +292,16 @@ function minify(ast, options = {}, recursive = false, errors, nestingContent, co
145
292
  */
146
293
  function reduce(acc, curr) {
147
294
  // trim :is()
148
- // if (array.length == 1 && array[0][0] == ':is(' && array[0].at(-1) == ')') {
149
- //
150
- // curr = curr.slice(1, -1);
151
- // }
152
- if (curr[0] == '&') {
153
- if (curr[1] == ' ' && !isIdent(curr[2]) && !isFunction(curr[2])) {
295
+ if (curr[0] == "&") {
296
+ if (curr[1] == " " && !isIdent(curr[2]) && !isFunction(curr[2])) {
154
297
  curr.splice(0, 2);
155
298
  }
156
299
  }
157
- acc.push(curr.join(''));
300
+ acc.push(curr.join(""));
158
301
  return acc;
159
302
  }
160
303
  /**
161
- * apply minification rules to the ast tree
304
+ * Apply minification rules to the ast tree
162
305
  * @param ast
163
306
  * @param options
164
307
  * @param recursive
@@ -169,15 +312,15 @@ function reduce(acc, curr) {
169
312
  * @private
170
313
  */
171
314
  function doMinify(ast, options = {}, recursive = false, errors, nestingContent, context = {}) {
172
- if (!('nodes' in context)) {
173
- context.nodes = new Set;
315
+ if (!("nodes" in context)) {
316
+ context.nodes = new Set();
174
317
  }
175
318
  if (context.nodes.has(ast)) {
176
319
  return ast;
177
320
  }
178
321
  context.nodes.add(ast);
179
322
  // @ts-ignore
180
- if ('chi' in ast && ast.chi.length > 0) {
323
+ if ("chi" in ast && ast.chi.length > 0) {
181
324
  const reducer = reduce.bind(ast);
182
325
  if (!nestingContent) {
183
326
  nestingContent = options.nestingRules && ast.typ == EnumToken.RuleNodeType;
@@ -187,28 +330,36 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
187
330
  let node = null;
188
331
  let nodeIndex = -1;
189
332
  for (; i < ast.chi.length; i++) {
190
- if (ast.chi[i].typ == EnumToken.CommentNodeType) {
333
+ if (ast.chi[i].typ === EnumToken.CommentNodeType) {
334
+ continue;
335
+ }
336
+ while (previous?.typ === EnumToken.CommentNodeType) {
337
+ previous = ast.chi[--nodeIndex];
191
338
  continue;
192
339
  }
193
340
  node = ast.chi[i];
194
- if (node.typ == EnumToken.AtRuleNodeType && node.nam == 'font-face') {
341
+ if (node.typ === EnumToken.AtRuleNodeType && node.nam === "font-face") {
195
342
  continue;
196
343
  }
197
- if (node.typ == EnumToken.KeyframesAtRuleNodeType) {
198
- if (previous?.typ == EnumToken.KeyframesAtRuleNodeType &&
199
- node.nam == previous.nam &&
200
- node.val == previous.val) {
344
+ if (node.typ === EnumToken.KeyframesAtRuleNodeType) {
345
+ if (previous?.typ === EnumToken.KeyframesAtRuleNodeType &&
346
+ node.nam === previous.nam &&
347
+ node.val === previous.val) {
201
348
  ast.chi?.splice(nodeIndex--, 1);
202
349
  previous = ast?.chi?.[nodeIndex] ?? null;
203
350
  i = nodeIndex;
204
351
  continue;
205
352
  }
206
353
  }
207
- else if (node.typ == EnumToken.KeyFramesRuleNodeType) {
208
- if (previous?.typ == EnumToken.KeyFramesRuleNodeType &&
209
- node.sel == previous.sel) {
354
+ else if (node.typ === EnumToken.KeyFramesRuleNodeType) {
355
+ if (previous?.typ === EnumToken.KeyFramesRuleNodeType &&
356
+ node.sel === previous.sel) {
357
+ // do not merge keyframes
358
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@keyframes#resolving_duplicates
210
359
  previous.chi.push(...node.chi);
211
- ast.chi.splice(i--, 1);
360
+ ast.chi.splice(i, 1);
361
+ previous = ast?.chi?.[nodeIndex] ?? null;
362
+ i = nodeIndex;
212
363
  continue;
213
364
  }
214
365
  let k;
@@ -216,7 +367,8 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
216
367
  if (node.chi[k].typ == EnumToken.DeclarationNodeType) {
217
368
  let l = node.chi[k].val.length;
218
369
  while (l--) {
219
- if (node.chi[k].val[l].typ == EnumToken.ImportantTokenType) {
370
+ if (node.chi[k].val[l].typ ==
371
+ EnumToken.ImportantTokenType) {
220
372
  node.chi.splice(k--, 1);
221
373
  break;
222
374
  }
@@ -229,16 +381,56 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
229
381
  }
230
382
  }
231
383
  else if (node.typ == EnumToken.AtRuleNodeType) {
232
- if (node.nam == 'media' && ['all', '', null].includes(node.val)) {
233
- ast.chi?.splice(i, 1, ...node.chi);
234
- i--;
235
- continue;
384
+ if (node.nam == "media") {
385
+ if (Array.isArray(node.tokens)) {
386
+ const slice = node.tokens.slice();
387
+ minifyAtRuleMedia(slice);
388
+ if (slice.length !== node.tokens.length) {
389
+ node.tokens.length = 0;
390
+ node.tokens.push(...slice);
391
+ node.val = slice.reduce((acc, curr, index, arr) => acc +
392
+ (curr.typ === EnumToken.CommentTokenType ||
393
+ (curr.typ === EnumToken.WhitespaceTokenType &&
394
+ arr[index + 1]?.typ === EnumToken.CommentTokenType &&
395
+ (index + 3 < arr.length ||
396
+ arr[index + 2]?.typ === EnumToken.WhitespaceTokenType))
397
+ ? ""
398
+ : renderValue(curr)), "");
399
+ }
400
+ }
401
+ if (["all", "", null].includes(node.val)) {
402
+ ast.chi?.splice(i--, 1, ...node.chi);
403
+ continue;
404
+ }
405
+ }
406
+ else if (node.nam === "import" && Array.isArray(node.tokens)) {
407
+ let l = 0;
408
+ let token;
409
+ for (; l < node.tokens.length; l++) {
410
+ token = node.tokens[l];
411
+ if (token.typ === EnumToken.ParensTokenType ||
412
+ token.typ === EnumToken.MediaQueryConditionTokenType ||
413
+ (token.typ === EnumToken.IdenTokenType && "layer" !== token.val)) {
414
+ break;
415
+ }
416
+ }
417
+ if (l < node.tokens.length) {
418
+ const slice = node.tokens?.slice(l);
419
+ node.tokens.splice(l, slice.length, ...minifyAtRuleMedia(slice));
420
+ node.val = trimArray(node.tokens).reduce((acc, curr, index, arr) => acc +
421
+ (curr.typ === EnumToken.CommentTokenType ||
422
+ (curr.typ === EnumToken.WhitespaceTokenType &&
423
+ arr[index + 1]?.typ === EnumToken.CommentTokenType &&
424
+ (index + 3 < arr.length || arr[index + 2].typ === EnumToken.WhitespaceTokenType))
425
+ ? ""
426
+ : renderValue(curr)), "");
427
+ }
236
428
  }
237
429
  if (previous?.typ == EnumToken.AtRuleNodeType &&
238
- node.nam != 'font-face' &&
239
- previous.nam == node.nam &&
240
- previous.val == node.val) {
241
- if ('chi' in node) {
430
+ node.nam != "font-face" &&
431
+ previous.nam === node.nam &&
432
+ previous.val === node.val) {
433
+ if ("chi" in node) {
242
434
  // @ts-ignore
243
435
  previous.chi.push(...node.chi);
244
436
  if (!hasDeclaration(previous)) {
@@ -257,7 +449,7 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
257
449
  continue;
258
450
  }
259
451
  // @ts-ignore
260
- else if (node.typ == EnumToken.RuleNodeType) {
452
+ else if (node.typ === EnumToken.RuleNodeType) {
261
453
  reduceRuleSelector(node);
262
454
  let wrapper = null;
263
455
  let match;
@@ -265,7 +457,7 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
265
457
  if (previous?.typ == EnumToken.RuleNodeType) {
266
458
  reduceRuleSelector(previous);
267
459
  // @ts-ignore
268
- match = matchSelectors(previous.raw, node.raw, ast.typ);
460
+ match = matchSelectors(previous.raw, node.raw);
269
461
  if (match != null) {
270
462
  wrapper = wrapNodes(previous, node, match, ast, reducer, i, nodeIndex);
271
463
  nodeIndex = i - 1;
@@ -299,13 +491,13 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
299
491
  // @ts-ignore
300
492
  wrapper = { ...node, chi: [], sel: node.optimized.optimized[0] };
301
493
  // @ts-ignore
302
- Object.defineProperty(wrapper, 'raw', {
494
+ Object.defineProperty(wrapper, "raw", {
303
495
  ...definedPropertySettings,
304
496
  // @ts-ignore
305
- value: [[node.optimized.optimized[0]]]
497
+ value: [[node.optimized.optimized[0]]],
306
498
  });
307
499
  // @ts-ignore
308
- node.sel = node.optimized.selector.reduce(reducer, []).join(',');
500
+ node.sel = node.optimized.selector.reduce(reducer, []).join(",");
309
501
  // @ts-ignore
310
502
  node.raw = node.optimized.selector.slice();
311
503
  // @ts-ignore
@@ -314,14 +506,30 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
314
506
  ast.chi.splice(i, 1, wrapper);
315
507
  node = wrapper;
316
508
  }
509
+ else if (node.optimized?.reducible) {
510
+ if (node.optimized.optimized.length === 1) {
511
+ const sel1 = node.optimized.optimized[0] +
512
+ ":is(" +
513
+ node.optimized.selector.reduce(reducer, []).join(",") +
514
+ ")";
515
+ const sel2 = node.optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") + node.optimized.optimized[0] + curr.join(""), "");
516
+ node.sel = sel1.length < sel2.length ? sel1 : sel2;
517
+ }
518
+ else if (node.optimized.optimized.length === 0) {
519
+ const testIdent = /^[a-zA-Z]/;
520
+ node.sel = node.optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") +
521
+ (nestingContent && testIdent.test(curr[0]) ? "& " : "") +
522
+ curr.join(""), "");
523
+ }
524
+ }
317
525
  }
318
526
  // @ts-ignore
319
527
  else if (node.optimized?.match) {
320
528
  let wrap = true;
321
529
  // @ts-ignore
322
530
  const selector = node.optimized.selector.reduce((acc, curr) => {
323
- if (curr[0] == '&' && curr.length > 1) {
324
- if (curr[1] == ' ') {
531
+ if (curr[0] == "&" && curr.length > 1) {
532
+ if (curr[1] == " ") {
325
533
  curr.splice(0, 2);
326
534
  }
327
535
  else {
@@ -329,14 +537,14 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
329
537
  }
330
538
  }
331
539
  else if (combinators.includes(curr[0])) {
332
- curr.unshift('&');
540
+ curr.unshift("&");
333
541
  wrap = false;
334
542
  }
335
543
  acc.push(curr);
336
544
  return acc;
337
545
  }, []);
338
546
  if (!wrap) {
339
- wrap = selector.some((s) => s[0] != '&');
547
+ wrap = selector.some((s) => s[0] != "&");
340
548
  }
341
549
  let rule = null;
342
550
  const optimized = node.optimized.optimized.slice();
@@ -345,50 +553,82 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
345
553
  if (!combinators.includes(check)) {
346
554
  let last = optimized.pop();
347
555
  wrap = false;
348
- rule = optimized.join('') + `:is(${selector.map(s => {
349
- if (s[0] == '&') {
350
- s.splice(0, 1, last);
351
- }
352
- else {
353
- s.unshift(last);
354
- }
355
- return s.join('');
356
- }).join(',')})`;
556
+ rule =
557
+ optimized.join("") +
558
+ `:is(${selector
559
+ .map((s) => {
560
+ if (s[0] == "&") {
561
+ s.splice(0, 1, last);
562
+ }
563
+ else {
564
+ s.unshift(last);
565
+ }
566
+ return s.join("");
567
+ })
568
+ .join(",")})`;
357
569
  }
358
570
  }
359
571
  if (rule == null) {
360
- rule = selector.map((s) => {
361
- if (s[0] == '&') {
572
+ rule = selector
573
+ .map((s) => {
574
+ if (s[0] == "&") {
362
575
  s.splice(0, 1, ...node.optimized.optimized);
363
576
  }
364
- return s.join('');
365
- }).join(',');
577
+ return s.join("");
578
+ })
579
+ .join(",");
580
+ }
581
+ let sel = wrap ? node.optimized.optimized.join("") + `:is(${rule})` : rule;
582
+ if (sel.length < node.sel.length) {
583
+ node.sel = sel;
366
584
  }
367
- let sel = wrap ? node.optimized.optimized.join('') + `:is(${rule})` : rule;
585
+ }
586
+ else if (node.optimized?.reducible) {
587
+ if (node.optimized.optimized.length === 1) {
588
+ const sel1 = node.optimized.optimized[0] +
589
+ ":is(" +
590
+ node.optimized.selector.reduce(reducer, []).join(",") +
591
+ ")";
592
+ const sel2 = node.optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") + node.optimized.optimized[0] + curr.join(""), "");
593
+ node.sel = sel1.length < sel2.length ? sel1 : sel2;
594
+ }
595
+ else if (node.optimized.optimized.length === 0) {
596
+ const testIdent = /^[a-zA-Z]/;
597
+ node.sel = node.optimized.selector.reduce((acc, curr) => (acc.length > 0 ? acc + "," : "") +
598
+ (nestingContent && testIdent.test(curr[0]) ? "& " : "") +
599
+ curr.join(""), "");
600
+ }
601
+ }
602
+ else if (node.optimized?.optimized.length > 0) {
603
+ const sel = node.optimized.optimized.join("");
368
604
  if (sel.length < node.sel.length) {
369
605
  node.sel = sel;
606
+ node.raw = [node.optimized.optimized.slice()];
370
607
  }
371
608
  }
372
609
  doMinify(node, options, recursive, errors, nestingContent, context);
373
610
  }
374
611
  if (previous != null) {
375
- if ('chi' in previous && ('chi' in node)) {
376
- if (previous.typ == node.typ) {
612
+ if ("chi" in previous && "chi" in node) {
613
+ if (previous.typ === node.typ) {
377
614
  let shouldMerge = true;
378
615
  let k = previous.chi.length;
379
616
  while (k-- > 0) {
380
- if (previous.chi[k].typ == EnumToken.CommentNodeType) {
617
+ if (previous.chi[k].typ === EnumToken.CommentNodeType ||
618
+ previous.chi[k].typ === EnumToken.InvalidRuleNodeType ||
619
+ previous.chi[k].typ === EnumToken.InvalidRuleNodeType) {
381
620
  continue;
382
621
  }
383
- shouldMerge = previous.chi[k].typ == EnumToken.DeclarationNodeType;
622
+ shouldMerge = previous.chi[k].typ === EnumToken.DeclarationNodeType;
384
623
  break;
385
624
  }
386
625
  if (shouldMerge) {
387
- // @ts-ignore
388
- if (((node.typ == EnumToken.RuleNodeType || node.typ == EnumToken.KeyFramesRuleNodeType) && node.sel == previous.sel) ||
389
- // @ts-ignore
390
- (node.typ == EnumToken.AtRuleNodeType) && node.val != 'font-face' && node.val == previous.val) {
391
- // @ts-ignore
626
+ if (((node.typ === EnumToken.RuleNodeType ||
627
+ node.typ === EnumToken.KeyFramesRuleNodeType) &&
628
+ node.sel === previous.sel) ||
629
+ (node.typ == EnumToken.AtRuleNodeType &&
630
+ node.nam !== "font-face" &&
631
+ node.nam === previous.nam)) {
392
632
  node.chi.unshift(...previous.chi);
393
633
  doMinify(node, options, recursive, errors, nestingContent, context);
394
634
  ast.chi.splice(nodeIndex, 1);
@@ -396,7 +636,8 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
396
636
  nodeIndex = i;
397
637
  continue;
398
638
  }
399
- else if (node.typ == previous?.typ && [EnumToken.KeyFramesRuleNodeType, EnumToken.RuleNodeType].includes(node.typ)) {
639
+ else if (node.typ == previous?.typ &&
640
+ [EnumToken.KeyFramesRuleNodeType, EnumToken.RuleNodeType].includes(node.typ)) {
400
641
  const intersect = diff(previous, node, reducer, options);
401
642
  if (intersect != null) {
402
643
  if (intersect.node1.chi.length == 0) {
@@ -416,7 +657,6 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
416
657
  ast.chi.splice(nodeIndex, 1, intersect.result, intersect.node2);
417
658
  i = (nodeIndex ?? 0) + 1;
418
659
  }
419
- reduceRuleSelector(intersect.result);
420
660
  if (node != ast.chi[i]) {
421
661
  node = ast.chi[i];
422
662
  }
@@ -426,7 +666,7 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
426
666
  }
427
667
  }
428
668
  }
429
- if (recursive && previous != node) {
669
+ if (recursive && previous != null && previous != node) {
430
670
  if (!hasDeclaration(previous)) {
431
671
  doMinify(previous, options, recursive, errors, nestingContent, context);
432
672
  }
@@ -436,15 +676,16 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
436
676
  if (!nestingContent &&
437
677
  previous != null &&
438
678
  previous.typ == EnumToken.RuleNodeType &&
439
- previous.sel.includes('&')) {
679
+ previous.sel.includes("&")) {
440
680
  fixSelector(previous);
441
681
  }
442
682
  previous = node;
443
683
  nodeIndex = i;
444
684
  }
445
- if (recursive && node != null && ('chi' in node)) {
446
- if (node.typ == EnumToken.KeyframesAtRuleNodeType || !node.chi.some((n) => n.typ == EnumToken.DeclarationNodeType)) {
447
- if (!(node.typ == EnumToken.AtRuleNodeType && node.nam != 'font-face')) {
685
+ if (recursive && node != null && "chi" in node) {
686
+ if (node.typ == EnumToken.KeyframesAtRuleNodeType ||
687
+ !node.chi.some((n) => n.typ == EnumToken.DeclarationNodeType)) {
688
+ if (!(node.typ == EnumToken.AtRuleNodeType && node.nam != "font-face")) {
448
689
  doMinify(node, options, recursive, errors, nestingContent, context);
449
690
  }
450
691
  }
@@ -452,14 +693,14 @@ function doMinify(ast, options = {}, recursive = false, errors, nestingContent,
452
693
  if (!nestingContent &&
453
694
  node != null &&
454
695
  node.typ == EnumToken.RuleNodeType &&
455
- node.sel.includes('&')) {
696
+ node.sel.includes("&")) {
456
697
  fixSelector(node);
457
698
  }
458
699
  }
459
700
  return ast;
460
701
  }
461
702
  /**
462
- * check if a rule has a declaration
703
+ * Check if a rule has a declaration
463
704
  * @param node
464
705
  *
465
706
  * @private
@@ -477,19 +718,21 @@ function hasDeclaration(node) {
477
718
  return true;
478
719
  }
479
720
  /**
480
- * optimize selector
721
+ * Optimize selector
481
722
  * @param selector
482
723
  *
483
724
  * @private
484
725
  */
485
726
  function optimizeSelector(selector) {
486
- selector = selector.reduce((acc, curr) => {
727
+ const map = new Set();
728
+ selector = selector
729
+ .reduce((acc, curr) => {
487
730
  // @ts-ignore
488
- if (curr.length > 0 && curr.at(-1).startsWith(':is(')) {
731
+ if (curr.length > 0 && curr.at(-1).startsWith(":is(")) {
489
732
  // @ts-ignore
490
- const rules = splitRule(curr.at(-1).slice(4, -1)).map(x => {
491
- if (x[0] == '&' && x.length > 1) {
492
- return x.slice(x[1] == ' ' ? 2 : 1);
733
+ const rules = splitRule(curr.at(-1).slice(4, -1)).map((x) => {
734
+ if (x[0] == "&" && x.length > 1) {
735
+ return x.slice(x[1] == " " ? 2 : 1);
493
736
  }
494
737
  return x;
495
738
  });
@@ -501,9 +744,17 @@ function optimizeSelector(selector) {
501
744
  }
502
745
  acc.push(curr);
503
746
  return acc;
504
- }, []);
747
+ }, [])
748
+ .filter((x) => {
749
+ const str = x.join("");
750
+ if (map.has(str)) {
751
+ return false;
752
+ }
753
+ map.add(str);
754
+ return true;
755
+ });
505
756
  const optimized = [];
506
- const k = selector.reduce((acc, curr) => acc == 0 ? curr.length : (curr.length == 0 ? acc : Math.min(acc, curr.length)), 0);
757
+ const k = selector.reduce((acc, curr) => acc == 0 ? curr.length : curr.length == 0 ? acc : Math.min(acc, curr.length), 0);
507
758
  let i = 0;
508
759
  let j;
509
760
  let match;
@@ -523,7 +774,7 @@ function optimizeSelector(selector) {
523
774
  }
524
775
  while (optimized.length > 0) {
525
776
  const last = optimized.at(-1);
526
- if ((last == ' ' || combinators.includes(last))) {
777
+ if (last == " " || combinators.includes(last)) {
527
778
  optimized.pop();
528
779
  continue;
529
780
  }
@@ -531,19 +782,17 @@ function optimizeSelector(selector) {
531
782
  }
532
783
  selector.forEach((selector) => selector.splice(0, optimized.length));
533
784
  let reducible = optimized.length == 1;
534
- if (optimized[0] == '&') {
535
- if (optimized[1] == ' ') {
785
+ if (optimized[0] == "&") {
786
+ if (optimized[1] == " ") {
536
787
  optimized.splice(0, 2);
537
788
  }
538
789
  }
539
- if (optimized.length == 0 ||
540
- (optimized[0].charAt(0) == '&' ||
541
- selector.length == 1)) {
790
+ if (optimized.length == 0 || optimized[0].charAt(0) == "&" || selector.length == 1) {
542
791
  return {
543
792
  match: false,
544
793
  optimized,
545
- selector: selector.map((selector) => selector[0] == '&' && selector[1] == ' ' ? selector.slice(2) : (selector)),
546
- reducible: selector.length > 1 && selector.every((selector) => !combinators.includes(selector[0]))
794
+ selector: selector.map((selector) => selector[0] == "&" && selector[1] == " " ? selector.slice(2) : selector),
795
+ reducible: selector.length > 1 && selector.every((selector) => !combinators.includes(selector[0])),
547
796
  };
548
797
  }
549
798
  return {
@@ -552,104 +801,104 @@ function optimizeSelector(selector) {
552
801
  selector: selector.reduce((acc, curr) => {
553
802
  let hasCompound = true;
554
803
  if (hasCompound && curr.length > 0) {
555
- hasCompound = !['&'].concat(combinators).includes(curr[0].charAt(0));
804
+ hasCompound = !["&"].concat(combinators).includes(curr[0].charAt(0));
556
805
  }
557
806
  // @ts-ignore
558
- if (hasCompound && curr[0] == ' ') {
807
+ if (hasCompound && curr[0] == " ") {
559
808
  hasCompound = false;
560
- curr.unshift('&');
809
+ curr.unshift("&");
561
810
  }
562
811
  if (curr.length == 0) {
563
- curr.push('&');
812
+ curr.push("&");
564
813
  hasCompound = false;
565
814
  }
566
815
  if (reducible) {
567
816
  const chr = curr[0].charAt(0);
568
817
  // @ts-ignore
569
- reducible = chr == '.' || chr == ':' || isIdentStart(chr.codePointAt(0));
818
+ reducible = chr == "." || chr == ":" || isIdentStart(chr.charCodeAt(0));
570
819
  }
571
- acc.push(hasCompound ? ['&'].concat(curr) : curr);
820
+ acc.push(hasCompound ? ["&"].concat(curr) : curr);
572
821
  return acc;
573
822
  }, []),
574
- reducible: selector.every((selector) => !['>', '+', '~', '&'].includes(selector[0]))
823
+ reducible: selector.every((selector) => ![">", "+", "~", "&"].includes(selector[0])),
575
824
  };
576
825
  }
577
826
  /**
578
- * split selector string
827
+ * Split selector string
579
828
  * @param buffer
580
829
  *
581
830
  * @internal
582
831
  */
583
832
  function splitRule(buffer) {
584
833
  const result = [[]];
585
- let str = '';
834
+ let str = "";
586
835
  for (let i = 0; i < buffer.length; i++) {
587
836
  let chr = buffer.charAt(i);
588
837
  if (isWhiteSpace(chr.charCodeAt(0))) {
589
- if (str !== '') {
838
+ if (str !== "") {
590
839
  // @ts-ignore
591
840
  result.at(-1).push(str);
592
- str = '';
841
+ str = "";
593
842
  }
594
843
  // @ts-ignore
595
844
  if (result.at(-1).length > 0) {
596
845
  // @ts-ignore
597
- result.at(-1).push(' ');
846
+ result.at(-1).push(" ");
598
847
  }
599
848
  // i = k;
600
849
  continue;
601
850
  }
602
- if (chr == ',') {
603
- if (str !== '') {
851
+ if (chr == ",") {
852
+ if (str !== "") {
604
853
  result.at(-1).push(str);
605
- str = '';
854
+ str = "";
606
855
  }
607
856
  result.push([]);
608
857
  continue;
609
858
  }
610
- if (chr == '.') {
611
- if (str !== '') {
859
+ if (chr == ".") {
860
+ if (str !== "") {
612
861
  result.at(-1).push(str);
613
- str = '';
862
+ str = "";
614
863
  }
615
864
  str += chr;
616
865
  continue;
617
866
  }
618
867
  if (combinators.includes(chr)) {
619
- if (str !== '') {
868
+ if (str !== "") {
620
869
  result.at(-1).push(str);
621
- str = '';
870
+ str = "";
622
871
  }
623
- if (chr == '|' && buffer.charAt(i + 1) == '|') {
872
+ if (chr == "|" && buffer.charAt(i + 1) == "|") {
624
873
  chr += buffer.charAt(++i);
625
874
  }
626
875
  result.at(-1).push(chr);
627
876
  continue;
628
877
  }
629
- if (chr == ':') {
630
- if (str !== '') {
878
+ if (chr == ":") {
879
+ if (str !== "") {
631
880
  result.at(-1).push(str);
632
- str = '';
881
+ str = "";
633
882
  }
634
- if (buffer.charAt(i + 1) == ':') {
883
+ if (buffer.charAt(i + 1) == ":") {
635
884
  chr += buffer.charAt(++i);
636
885
  }
637
886
  str += chr;
638
887
  continue;
639
888
  }
640
889
  str += chr;
641
- if (chr == '\\') {
890
+ if (chr == "\\") {
642
891
  str += buffer.charAt(++i);
643
892
  continue;
644
893
  }
645
- if (chr == '(' || chr == '[') {
894
+ if (chr == "(" || chr == "[") {
646
895
  const open = chr;
647
- const close = chr == '(' ? ')' : ']';
896
+ const close = chr == "(" ? ")" : "]";
648
897
  let inParens = 1;
649
898
  let k = i;
650
899
  while (++k < buffer.length) {
651
900
  chr = buffer.charAt(k);
652
- if (chr == '\\') {
901
+ if (chr == "\\") {
653
902
  str += buffer.slice(k, k + 2);
654
903
  k++;
655
904
  continue;
@@ -668,13 +917,13 @@ function splitRule(buffer) {
668
917
  i = k;
669
918
  }
670
919
  }
671
- if (str !== '') {
920
+ if (str !== "") {
672
921
  result.at(-1).push(str);
673
922
  }
674
923
  return result;
675
924
  }
676
925
  /**
677
- * reduce selector
926
+ * Reduce selector
678
927
  * @param acc
679
928
  * @param curr
680
929
  *
@@ -685,26 +934,26 @@ function reduceSelector(acc, curr) {
685
934
  // @ts-ignore
686
935
  curr = curr.slice(this.match[0].length);
687
936
  while (curr.length > 0) {
688
- if (curr[0] == ' ') {
937
+ if (curr[0] == " ") {
689
938
  hasCompoundSelector = false;
690
- curr.unshift('&');
939
+ curr.unshift("&");
691
940
  continue;
692
941
  }
693
942
  break;
694
943
  }
695
944
  if (hasCompoundSelector && curr.length > 0) {
696
- hasCompoundSelector = !['&'].concat(combinators).includes(curr[0].charAt(0));
945
+ hasCompoundSelector = !["&"].concat(combinators).includes(curr[0].charAt(0));
697
946
  }
698
- if (curr[0] == ':is(') {
947
+ if (curr[0] == ":is(") {
699
948
  let canReduce = true;
700
949
  const isCompound = curr.reduce((acc, token, index) => {
701
950
  if (index == 0) {
702
- canReduce = curr[1] == '&';
951
+ canReduce = curr[1] == "&";
703
952
  }
704
- else if (token == ')') ;
705
- else if (token == ',') {
953
+ else if (token == ")") ;
954
+ else if (token == ",") {
706
955
  if (!canReduce) {
707
- canReduce = curr[index + 1] == '&';
956
+ canReduce = curr[index + 1] == "&";
708
957
  }
709
958
  acc.push([]);
710
959
  }
@@ -715,19 +964,24 @@ function reduceSelector(acc, curr) {
715
964
  if (canReduce) {
716
965
  curr = isCompound.reduce((acc, curr) => {
717
966
  if (acc.length > 0) {
718
- acc.push(',');
967
+ acc.push(",");
719
968
  }
720
969
  acc.push(...curr);
721
970
  return acc;
722
971
  }, []);
723
972
  }
724
973
  }
974
+ acc.push(
725
975
  // @ts-ignore
726
- acc.push(this.match.length == 0 ? ['&'] : (hasCompoundSelector && curr[0] != '&' && (curr.length == 0 || !combinators.includes(curr[0].charAt(0))) ? ['&'].concat(curr) : curr));
976
+ this.match.length == 0
977
+ ? ["&"]
978
+ : hasCompoundSelector && curr[0] != "&" && (curr.length == 0 || !combinators.includes(curr[0].charAt(0)))
979
+ ? ["&"].concat(curr)
980
+ : curr);
727
981
  return acc;
728
982
  }
729
983
  /**
730
- * match selectors
984
+ * Match selectors
731
985
  * @param selector1
732
986
  * @param selector2
733
987
  *
@@ -743,6 +997,35 @@ function matchSelectors(selector1, selector2) {
743
997
  let matching = true;
744
998
  let matchFunction = 0;
745
999
  let inAttr = 0;
1000
+ const regEx = /^:is\(([:.][^\s,]+)\)$/;
1001
+ for (const _1 of selector1) {
1002
+ if (_1[0] !== "&") {
1003
+ continue;
1004
+ }
1005
+ for (let i = 1; i < _1.length; i++) {
1006
+ const token = _1[i];
1007
+ if (token.startsWith(":is(")) {
1008
+ const match = regEx.exec(token);
1009
+ if (match != null) {
1010
+ _1[i] = match[1];
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ for (const _1 of selector2) {
1016
+ if (_1[0] !== "&") {
1017
+ continue;
1018
+ }
1019
+ for (let i = 1; i < _1.length; i++) {
1020
+ const token = _1[i];
1021
+ if (token.startsWith(":is(")) {
1022
+ const match = regEx.exec(token);
1023
+ if (match != null) {
1024
+ _1[i] = match[1];
1025
+ }
1026
+ }
1027
+ }
1028
+ }
746
1029
  for (; i < j; i++) {
747
1030
  k = 0;
748
1031
  token = selector1[0][i];
@@ -764,7 +1047,7 @@ function matchSelectors(selector1, selector2) {
764
1047
  if (!matching) {
765
1048
  break;
766
1049
  }
767
- if (token.endsWith('(')) {
1050
+ if (token.endsWith("(")) {
768
1051
  matchFunction++;
769
1052
  }
770
1053
  match.at(-1).push(token);
@@ -776,17 +1059,17 @@ function matchSelectors(selector1, selector2) {
776
1059
  for (const part of match) {
777
1060
  while (part.length > 0) {
778
1061
  const token = part.at(-1);
779
- if (token == ' ' || combinators.includes(token) || notEndingWith.includes(token.at(-1))) {
1062
+ if (token == " " || combinators.includes(token) || notEndingWith.includes(token.at(-1))) {
780
1063
  part.pop();
781
1064
  continue;
782
1065
  }
783
1066
  break;
784
1067
  }
785
1068
  }
786
- if (match.every(t => t.length == 0)) {
1069
+ if (match.every((t) => t.length == 0)) {
787
1070
  return null;
788
1071
  }
789
- if (eq([['&']], match)) {
1072
+ if (eq([["&"]], match)) {
790
1073
  return null;
791
1074
  }
792
1075
  const reducer = reduceSelector.bind({ match });
@@ -794,37 +1077,40 @@ function matchSelectors(selector1, selector2) {
794
1077
  selector1 = selector1.reduce(reducer, []);
795
1078
  // @ts-ignore
796
1079
  selector2 = selector2.reduce(reducer, []);
797
- return selector1 == null || selector2 == null ? null : {
798
- eq: eq(selector1, selector2),
799
- match,
800
- selector1,
801
- selector2
802
- };
1080
+ return selector1 == null || selector2 == null
1081
+ ? null
1082
+ : {
1083
+ eq: eq(selector1, selector2),
1084
+ match,
1085
+ selector1,
1086
+ selector2,
1087
+ };
803
1088
  }
804
1089
  /**
805
- * fix selector
1090
+ * Fix selector
806
1091
  * @param node
807
1092
  *
808
1093
  * @private
809
1094
  */
810
1095
  function fixSelector(node) {
811
- if (node.sel.includes('&')) {
812
- const attributes = parseString(node.sel);
1096
+ if (node.sel.includes("&")) {
1097
+ const attributes = [...tokenize(node.sel)].map((t) => t.token); // parseString(node.sel);
813
1098
  for (const attr of walkValues(attributes)) {
814
- if (attr.value.typ == EnumToken.PseudoClassFuncTokenType && attr.value.val == ':is') {
1099
+ if (attr.value.typ == EnumToken.PseudoClassFuncTokenType &&
1100
+ attr.value.val == ":is") {
815
1101
  let i = attr.value.chi.length;
816
1102
  while (i--) {
817
- if (attr.value.chi[i].typ == EnumToken.LiteralTokenType && attr.value.chi[i].val == '&') {
1103
+ if (attr.value.chi[i].typ == EnumToken.NestingSelectorTokenType) {
818
1104
  attr.value.chi.splice(i, 1);
819
1105
  }
820
1106
  }
821
1107
  }
822
1108
  }
823
- node.sel = attributes.reduce((acc, curr) => acc + renderToken(curr), '');
1109
+ node.sel = attributes.reduce((acc, curr) => acc + renderValue(curr), "");
824
1110
  }
825
1111
  }
826
1112
  /**
827
- * wrap nodes
1113
+ * Wrap nodes
828
1114
  * @param previous
829
1115
  * @param node
830
1116
  * @param match
@@ -837,18 +1123,18 @@ function fixSelector(node) {
837
1123
  */
838
1124
  function wrapNodes(previous, node, match, ast, reducer, i, nodeIndex) {
839
1125
  // @ts-ignore
840
- let pSel = match.selector1.reduce(reducer, []).join(',');
1126
+ let pSel = match.selector1.reduce(reducer, []).join(",");
841
1127
  // @ts-ignore
842
- let nSel = match.selector2.reduce(reducer, []).join(',');
1128
+ let nSel = match.selector2.reduce(reducer, []).join(",");
843
1129
  // @ts-ignore
844
- const wrapper = { ...previous, chi: [], sel: match.match.reduce(reducer, []).join(',') };
845
- Object.defineProperty(wrapper, 'raw', {
1130
+ const wrapper = { ...previous, chi: [], sel: match.match.reduce(reducer, []).join(",") };
1131
+ Object.defineProperty(wrapper, "raw", {
846
1132
  ...definedPropertySettings,
847
- value: match.match.map(t => t.slice())
1133
+ value: match.match.map((t) => t.slice()),
848
1134
  });
849
- if (pSel == '&' || pSel === '') {
1135
+ if (pSel == "&" || pSel === "") {
850
1136
  wrapper.chi.push(...previous.chi);
851
- if ((nSel == '&' || nSel === '')) {
1137
+ if (nSel == "&" || nSel === "") {
852
1138
  wrapper.chi.push(...node.chi);
853
1139
  }
854
1140
  else {
@@ -868,7 +1154,7 @@ function wrapNodes(previous, node, match, ast, reducer, i, nodeIndex) {
868
1154
  return wrapper;
869
1155
  }
870
1156
  /**
871
- * diff nodes
1157
+ * Diff nodes
872
1158
  * @param n1
873
1159
  * @param n2
874
1160
  * @param reducer
@@ -877,7 +1163,7 @@ function wrapNodes(previous, node, match, ast, reducer, i, nodeIndex) {
877
1163
  * @private
878
1164
  */
879
1165
  function diff(n1, n2, reducer, options = {}) {
880
- if (!('cache' in options)) {
1166
+ if (!("cache" in options)) {
881
1167
  options.cache = new WeakMap();
882
1168
  }
883
1169
  let node1 = n1;
@@ -894,11 +1180,11 @@ function diff(n1, n2, reducer, options = {}) {
894
1180
  const raw1 = node1.raw;
895
1181
  const raw2 = node2.raw;
896
1182
  if (raw1 != null && raw2 != null) {
897
- const prefixes1 = new Set;
898
- const prefixes2 = new Set;
1183
+ const prefixes1 = new Set();
1184
+ const prefixes2 = new Set();
899
1185
  for (const token1 of raw1) {
900
1186
  for (const t of token1) {
901
- if (t[0] == ':') {
1187
+ if (t.includes(":")) {
902
1188
  const matches = t.match(/::?-([a-z]+)-/);
903
1189
  if (matches == null) {
904
1190
  continue;
@@ -915,7 +1201,7 @@ function diff(n1, n2, reducer, options = {}) {
915
1201
  }
916
1202
  for (const token2 of raw2) {
917
1203
  for (const t of token2) {
918
- if (t[0] == ':') {
1204
+ if (t.includes(":")) {
919
1205
  const matches = t.match(/::?-([a-z]+)-/);
920
1206
  if (matches == null) {
921
1207
  continue;
@@ -950,10 +1236,10 @@ function diff(n1, n2, reducer, options = {}) {
950
1236
  options.cache.set(node2, css2);
951
1237
  }
952
1238
  if (raw1 != null) {
953
- Object.defineProperty(node1, 'raw', { ...definedPropertySettings, value: raw1 });
1239
+ Object.defineProperty(node1, "raw", { ...definedPropertySettings, value: raw1 });
954
1240
  }
955
1241
  if (raw2 != null) {
956
- Object.defineProperty(node2, 'raw', { ...definedPropertySettings, value: raw2 });
1242
+ Object.defineProperty(node2, "raw", { ...definedPropertySettings, value: raw2 });
957
1243
  }
958
1244
  const intersect = [];
959
1245
  while (i--) {
@@ -977,73 +1263,106 @@ function diff(n1, n2, reducer, options = {}) {
977
1263
  }
978
1264
  }
979
1265
  }
980
- const result = (intersect.length == 0 ? null : {
981
- ...node1,
982
- // @ts-ignore
983
- sel: [...new Set([...(n1?.raw?.reduce(reducer, []) ?? splitRule(n1.sel)).concat(n2?.raw?.reduce(reducer, []) ?? splitRule(n2.sel))])].join(','),
984
- chi: intersect.reverse()
985
- });
986
- if (result == null || [n1, n2].reduce((acc, curr) => {
987
- let css = options.cache.get(curr);
988
- if (css == null) {
989
- css = doRender(curr, options).code;
990
- options.cache.set(curr, css);
1266
+ const result = intersect.length === 0 && (node1.chi.length > 0 || node2.chi.length > 0)
1267
+ ? null
1268
+ : {
1269
+ ...node1,
1270
+ // @ts-ignore
1271
+ sel: [
1272
+ ...new Set(splitRule(node1.sel)
1273
+ .concat(splitRule(node2.sel))
1274
+ .map((s) => s.join(""))),
1275
+ ].join(","),
1276
+ // @ts-ignore
1277
+ chi: intersect.reverse(),
1278
+ };
1279
+ if (result == null ||
1280
+ [n1, n2].reduce((acc, curr) => {
1281
+ let css = options.cache.get(curr);
1282
+ if (css == null) {
1283
+ css = doRender(curr, options).code;
1284
+ options.cache.set(curr, css);
1285
+ }
1286
+ return curr.chi.length == 0 ? acc : acc + css.length;
1287
+ }, 0) <=
1288
+ [node1, node2, result].reduce((acc, curr) => {
1289
+ const css = doRender(curr, options).code;
1290
+ return curr.chi.length == 0 ? acc : acc + css.length;
1291
+ }, 0)) {
1292
+ if (node1.chi.length != 0 && node2.chi.length != 0) {
1293
+ return null;
1294
+ }
1295
+ }
1296
+ if (result != null) {
1297
+ const optimized = optimizeSelector(splitRule(result.sel));
1298
+ if (optimized?.match) {
1299
+ const rule = optimized.selector.reduce((acc, curr) => {
1300
+ if (acc.length > 0) {
1301
+ acc += ",";
1302
+ }
1303
+ if (curr.length > 2 && curr[0] === "&" && curr[1] === " ") {
1304
+ return acc + curr.slice(2).join("");
1305
+ }
1306
+ else if (curr.length > 1 && curr[0] === "&") {
1307
+ return acc + curr.slice(1).join("");
1308
+ }
1309
+ return acc + curr.join("");
1310
+ }, "");
1311
+ const match = optimized.optimized.join("");
1312
+ const sel = match + ":is(" + replaceCompound(rule, match) + ")";
1313
+ if (sel.length < result.sel.length) {
1314
+ result.sel = sel;
1315
+ }
991
1316
  }
992
- return curr.chi.length == 0 ? acc : acc + css.length;
993
- }, 0) <= [node1, node2, result].reduce((acc, curr) => {
994
- const css = doRender(curr, options).code;
995
- return curr.chi.length == 0 ? acc : acc + css.length;
996
- }, 0)) {
997
- return null;
998
1317
  }
999
1318
  return { result, node1: exchanged ? node2 : node1, node2: exchanged ? node1 : node2 };
1000
1319
  }
1001
1320
  /**
1002
- * reduce rule selector
1321
+ * Reduce rule selector
1003
1322
  * @param node
1004
1323
  *
1005
1324
  * @private
1006
1325
  */
1007
1326
  function reduceRuleSelector(node) {
1008
1327
  if (node.raw == null) {
1009
- Object.defineProperty(node, 'raw', { ...definedPropertySettings, value: splitRule(node.sel) });
1328
+ Object.defineProperty(node, "raw", { ...definedPropertySettings, value: splitRule(node.sel) });
1010
1329
  }
1011
1330
  let optimized = optimizeSelector(node.raw.reduce((acc, curr) => {
1012
1331
  acc.push(curr.slice());
1013
1332
  return acc;
1014
1333
  }, []));
1015
1334
  if (optimized != null) {
1016
- Object.defineProperty(node, 'optimized', { ...definedPropertySettings, value: optimized });
1335
+ Object.defineProperty(node, "optimized", { ...definedPropertySettings, value: optimized });
1017
1336
  }
1018
1337
  if (optimized != null && optimized.match && optimized.reducible && optimized.selector.length > 1) {
1019
1338
  for (const selector of optimized.selector) {
1020
- if (selector.length > 1 && selector[0] == '&' &&
1339
+ if (selector.length > 1 &&
1340
+ selector[0] == "&" &&
1021
1341
  (combinators.includes(selector[1]) || !/^[a-zA-Z:]/.test(selector[1]))) {
1022
1342
  selector.shift();
1023
1343
  }
1024
1344
  }
1025
- const unique = new Set;
1026
- const raw = [
1027
- [
1028
- optimized.optimized[0], ':is('
1029
- ].concat(optimized.selector.reduce((acc, curr) => {
1030
- const sig = curr.join('');
1031
- if (!unique.has(sig)) {
1032
- if (acc.length > 0) {
1033
- acc.push(',');
1034
- }
1035
- unique.add(sig);
1036
- acc.push(...curr);
1345
+ const unique = new Set();
1346
+ const reduced = optimized.selector.reduce((acc, curr) => {
1347
+ const sig = curr.join("");
1348
+ if (!unique.has(sig)) {
1349
+ if (acc.length > 0) {
1350
+ acc.push(",");
1037
1351
  }
1038
- return acc;
1039
- }, [])).concat(')')
1352
+ unique.add(sig);
1353
+ acc.push(...curr);
1354
+ }
1355
+ return acc;
1356
+ }, []);
1357
+ const raw = [
1358
+ [optimized.optimized[0], reduced.length === 1 ? reduced.join("") : ":is("].concat(reduced).concat(")"),
1040
1359
  ];
1041
- const sel = raw[0].join('');
1360
+ const sel = raw[0].join("");
1042
1361
  if (sel.length < node.sel.length) {
1043
1362
  node.sel = sel;
1044
- Object.defineProperty(node, 'raw', { ...definedPropertySettings, value: raw });
1363
+ Object.defineProperty(node, "raw", { ...definedPropertySettings, value: raw });
1045
1364
  }
1046
1365
  }
1047
1366
  }
1048
1367
 
1049
- export { combinators, definedPropertySettings, minify, splitRule };
1368
+ export { minify, optimizeSelector, splitRule };