@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,87 +1,88 @@
1
- import { isIdentStart, isIdent, isIdentColor, mathFuncs, isColor, parseColor, isPseudo, pseudoElements, isAtKeyword, isFunction, isNumber, isPercentage, parseDimension, isHexColor, isHash, mediaTypes } from '../syntax/syntax.js';
2
- import { EnumToken, ColorType, ValidationLevel, ModuleCaseTransformEnum, ModuleScopeEnumOptions, SyntaxValidationResult } from '../ast/types.js';
3
- import { definedPropertySettings, minify, combinators } from '../ast/minify.js';
4
- import { walkValues, WalkerEvent, walk, WalkerOptionEnum } from '../ast/walk.js';
1
+ import { isIdentColor, parseColor, isColor } from '../syntax/syntax.js';
2
+ import { camelize, equalsIgnoreCase, dasherize } from './utils/text.js';
3
+ import { renderValue } from '../renderer/render.js';
4
+ import { EnumToken, EnumAstNodeStatus, ModuleCaseTransformEnum, ModuleScopeEnumOptions } from '../ast/types.js';
5
+ import { minify } from '../ast/minify.js';
5
6
  import { expand } from '../ast/expand.js';
6
- import './utils/config.js';
7
- import { parseDeclarationNode } from './utils/declaration.js';
8
- import { camelize, dasherize } from './utils/text.js';
9
- import { renderToken } from '../renderer/render.js';
10
- import '../renderer/sourcemap/lib/encode.js';
11
- import { funcLike, timingFunc, timelineFunc, COLORS_NAMES, systemColors, deprecatedSystemColors, colorsFunc } from '../syntax/color/utils/constants.js';
12
- import { buildExpression } from '../ast/math/expression.js';
13
- import { tokenize, tokenizeStream } from './tokenize.js';
14
- import '../validation/config.js';
15
- import '../validation/parser/parse.js';
16
- import { validateSelector } from '../validation/selector.js';
17
- import { validateAtRule } from '../validation/atrule.js';
18
- import { splitTokenList } from '../validation/utils/list.js';
19
- import '../validation/syntaxes/complex-selector.js';
20
- import { validateKeyframeSelector } from '../validation/syntaxes/keyframe-selector.js';
21
- import { isNodeAllowedInContext, evaluateSyntax } from '../validation/syntax.js';
22
- import { validateAtRuleKeyframes } from '../validation/at-rules/keyframes.js';
7
+ import { WalkerEvent, walk, walkValues } from '../ast/walk.js';
8
+ import { tokenizeStream, tokenize } from './tokenize.js';
9
+ import { definedPropertySettings, tokensfuncDefMap, pageMarginBoxType } from '../syntax/constants.js';
23
10
  import { hashAlgorithms, hash } from './utils/hash.js';
11
+ import { parseSelector } from './utils/selector.js';
12
+ import { parseDeclaration } from './utils/declaration.js';
13
+ import { getSyntaxRule } from '../validation/config.js';
14
+ import { matchSelectorSyntax, trimArray, matchAllSyntaxes, createValidationContext } from '../validation/match.js';
15
+ import { ValidationSyntaxGroupEnum } from '../validation/parser/typedef.js';
16
+ import { matchAtRuleImportSyntax } from './utils/at-rule-import.js';
17
+ import { matchAtRuleWhenElseSyntax } from './utils/at-rule-when-else.js';
18
+ import { parseAtRuleSupportSyntax } from './utils/at-rule-support.js';
19
+ import { replaceNodeOrValue, trimWhiteSpaceTokens } from './utils/token.js';
20
+ import { parseAtRuleContainerQueryList } from './utils/at-rule-container.js';
21
+ import { parseMediaqueryList } from './utils/at-rule-media.js';
22
+ import { matchAtRuleSyntax } from './utils/at-rule.js';
23
+ import { parseAtRuleFontFeatureValues } from './utils/at-rule-font-feature-values.js';
24
+ import { matchGenericSyntax } from './utils/at-rule-generic.js';
25
+ import { memoize } from './utils/cache.js';
24
26
 
25
- const urlTokenMatcher = /^(["']?)[a-zA-Z0-9_/.-][a-zA-Z0-9_/:.#?-]+(\1)$/;
26
- const trimWhiteSpace = [EnumToken.CommentTokenType, EnumToken.GtTokenType, EnumToken.GteTokenType, EnumToken.LtTokenType, EnumToken.LteTokenType, EnumToken.ColumnCombinatorTokenType];
27
+ function renderTokens(tokens, options) {
28
+ if (tokens == null || tokens.length === 0)
29
+ return "";
30
+ if (options != null)
31
+ return tokens.map((t) => renderValue(t, options)).join("");
32
+ return tokens.map((t) => renderValue(t)).join("");
33
+ }
34
+ const trimWhiteSpace = [
35
+ EnumToken.CommentTokenType,
36
+ EnumToken.GtTokenType,
37
+ EnumToken.GteTokenType,
38
+ EnumToken.LtTokenType,
39
+ EnumToken.LteTokenType,
40
+ EnumToken.ColumnCombinatorTokenType,
41
+ ];
27
42
  const BadTokensTypes = [
28
43
  EnumToken.BadCommentTokenType,
29
44
  EnumToken.BadCdoTokenType,
30
45
  EnumToken.BadUrlTokenType,
31
- EnumToken.BadStringTokenType
46
+ EnumToken.BadStringTokenType,
32
47
  ];
33
- const enumTokenHints = new Set([
34
- EnumToken.WhitespaceTokenType, EnumToken.SemiColonTokenType, EnumToken.ColonTokenType, EnumToken.BlockStartTokenType,
35
- EnumToken.BlockStartTokenType, EnumToken.AttrStartTokenType, EnumToken.AttrEndTokenType, EnumToken.StartParensTokenType, EnumToken.EndParensTokenType,
36
- EnumToken.CommaTokenType, EnumToken.GtTokenType, EnumToken.LtTokenType, EnumToken.GteTokenType, EnumToken.LteTokenType, EnumToken.CommaTokenType,
37
- EnumToken.StartMatchTokenType, EnumToken.EndMatchTokenType, EnumToken.IncludeMatchTokenType, EnumToken.DashMatchTokenType, EnumToken.ContainMatchTokenType,
38
- EnumToken.EOFTokenType
39
- ]);
40
- function reject(reason) {
41
- throw new Error(reason ?? 'Parsing aborted');
42
- }
48
+ let keyNameCounter = 0;
49
+ let keyNameCache = {};
50
+ const forbiddenStartCharacters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].map((c) => c.charCodeAt(0));
43
51
  /**
44
- * replace token in its parent node
45
- * @param parent
46
- * @param value
47
- * @param replacement
52
+ * Short-scoped name generator.
53
+ *
54
+ * @param localName
55
+ * @param filePath
56
+ * @param pattern
57
+ * @param hashLength
58
+ *
59
+ * @returns string
48
60
  */
49
- function replaceToken(parent, value, replacement) {
50
- for (const node of (Array.isArray(replacement) ? replacement : [replacement])) {
51
- if ('parent' in value && value.parent != node.parent) {
52
- Object.defineProperty(node, 'parent', {
53
- ...definedPropertySettings,
54
- value: value.parent
55
- });
56
- }
57
- }
58
- if (parent.typ == EnumToken.BinaryExpressionTokenType) {
59
- if (parent.l == value) {
60
- parent.l = replacement;
61
- }
62
- else {
63
- parent.r = replacement;
64
- }
61
+ const getShortNameGenerator = memoize((localName, filePath, pattern, hashLength = 5) => {
62
+ const key = `${localName}_${filePath}_${pattern}_${hashLength}`;
63
+ if (key in keyNameCache) {
64
+ return keyNameCache[key];
65
65
  }
66
- else {
67
- const target = 'val' in parent && Array.isArray(parent.val) ? parent.val : parent.chi;
68
- // @ts-ignore
69
- const index = target.indexOf(value);
70
- if (index == -1) {
71
- return;
72
- }
73
- target.splice(index, 1, ...(Array.isArray(replacement) ? replacement : [replacement]));
66
+ let value = keyNameCounter.toString(36);
67
+ keyNameCounter++;
68
+ while (forbiddenStartCharacters.includes(value.charCodeAt(0))) {
69
+ value = keyNameCounter.toString(36);
70
+ keyNameCounter++;
74
71
  }
72
+ return (keyNameCache[key] = value);
73
+ });
74
+ function reject(reason) {
75
+ throw new Error(reason ?? "Parsing aborted");
75
76
  }
76
77
  /**
77
- * transform case of key name
78
+ * Transform case of key name
78
79
  * @param key
79
80
  * @param how
80
81
  *
81
82
  * @throws Error
82
83
  * @private
83
84
  */
84
- function getKeyName(key, how) {
85
+ const getKeyName = memoize((key, how) => {
85
86
  switch (how) {
86
87
  case ModuleCaseTransformEnum.CamelCase:
87
88
  case ModuleCaseTransformEnum.CamelCaseOnly:
@@ -91,9 +92,9 @@ function getKeyName(key, how) {
91
92
  return dasherize(key);
92
93
  }
93
94
  return key;
94
- }
95
+ });
95
96
  /**
96
- * generate scoped name
97
+ * Generate scoped name
97
98
  * @param localName
98
99
  * @param filePath
99
100
  * @param pattern
@@ -102,46 +103,46 @@ function getKeyName(key, how) {
102
103
  * @throws Error
103
104
  * @private
104
105
  */
105
- async function generateScopedName(localName, filePath, pattern, hashLength = 5) {
106
- if (localName.startsWith('--')) {
106
+ const generateScopedName = memoize(async (localName, filePath, pattern, hashLength = 5) => {
107
+ if (localName.startsWith("--")) {
107
108
  localName = localName.slice(2);
108
109
  }
109
110
  const matches = /.*?(([^/]+)\/)?([^/\\]*?)(\.([^?/]+))?([?].*)?$/.exec(filePath);
110
- const folder = matches?.[2]?.replace?.(/[^A-Za-z0-9_-]/g, "_") ?? '';
111
- const fileBase = matches?.[3] ?? '';
112
- const ext = matches?.[5] ?? '';
111
+ const folder = matches?.[2]?.replace?.(/[^A-Za-z0-9_-]/g, "_") ?? "";
112
+ const fileBase = matches?.[3] ?? "";
113
+ const ext = matches?.[5] ?? "";
113
114
  const path = filePath.replace(/[^A-Za-z0-9_-]/g, "_");
114
115
  // sanitize localName for safe char set (replace spaces/illegal chars)
115
116
  const safeLocal = localName.replace(/[^A-Za-z0-9_-]/g, "_");
116
117
  const hashString = `${localName}::${filePath}`;
117
- let result = '';
118
+ let result = "";
118
119
  let inParens = 0;
119
- let key = '';
120
+ let key = "";
120
121
  let position = 0;
121
- // Compose final scoped name. Ensure the entire class doesn't start with digit:
122
+ // Compose final scoped name. Ensure the entire class doesn't start with a digit:
122
123
  for (const char of pattern) {
123
124
  position += char.length;
124
- if (char == '[') {
125
+ if (char == "[") {
125
126
  inParens++;
126
127
  if (inParens != 1) {
127
128
  throw new Error(`Unexpected character: '${char} at position ${position - 1}' in pattern '${pattern}'`);
128
129
  }
129
130
  continue;
130
131
  }
131
- if (char == ']') {
132
+ if (char == "]") {
132
133
  inParens--;
133
134
  if (inParens != 0) {
134
135
  throw new Error(`Unexpected character: '${char}:${position - 1}'`);
135
136
  }
136
137
  let hashAlgo = null;
137
138
  let length = null;
138
- if (key.includes(':')) {
139
- const parts = key.split(':');
139
+ if (key.includes(":")) {
140
+ const parts = key.split(":");
140
141
  if (parts.length == 2) {
141
142
  // @ts-ignore
142
143
  [key, length] = parts;
143
144
  // @ts-ignore
144
- if (key == 'hash' && hashAlgorithms.includes(length)) {
145
+ if (key == "hash" && hashAlgorithms.includes(length)) {
145
146
  // @ts-ignore
146
147
  hashAlgo = length;
147
148
  length = null;
@@ -155,29 +156,35 @@ async function generateScopedName(localName, filePath, pattern, hashLength = 5)
155
156
  throw new Error(`Unsupported hash length: '${length}'. expecting format [hash:length] or [hash:hash-algo:length]`);
156
157
  }
157
158
  }
159
+ const slice = length != null && length != fileBase.length;
158
160
  switch (key) {
159
- case 'hash':
161
+ case "hash":
160
162
  result += await hash(hashString, length ?? hashLength, hashAlgo);
161
163
  break;
162
- case 'name':
163
- result += length != null ? fileBase.slice(0, +length) : fileBase;
164
+ case "name":
165
+ // @ts-expect-error
166
+ result += slice ? fileBase.slice(0, +length) : fileBase;
164
167
  break;
165
- case 'local':
166
- result += length != null ? safeLocal.slice(0, +length) : localName;
168
+ case "local":
169
+ // @ts-expect-error
170
+ result += slice ? safeLocal.slice(0, +length) : localName;
167
171
  break;
168
- case 'ext':
169
- result += length != null ? ext.slice(0, +length) : ext;
172
+ case "ext":
173
+ // @ts-expect-error
174
+ result += slice ? ext.slice(0, +length) : ext;
170
175
  break;
171
- case 'path':
172
- result += length != null ? path.slice(0, +length) : path;
176
+ case "path":
177
+ // @ts-expect-error
178
+ result += slice ? path.slice(0, +length) : path;
173
179
  break;
174
- case 'folder':
175
- result += length != null ? folder.slice(0, +length) : folder;
180
+ case "folder":
181
+ // @ts-expect-error
182
+ result += slice ? folder.slice(0, +length) : folder;
176
183
  break;
177
184
  default:
178
185
  throw new Error(`Unsupported key: '${key}'`);
179
186
  }
180
- key = '';
187
+ key = "";
181
188
  continue;
182
189
  }
183
190
  if (inParens > 0) {
@@ -188,10 +195,10 @@ async function generateScopedName(localName, filePath, pattern, hashLength = 5)
188
195
  }
189
196
  }
190
197
  // if leading char is digit, prefix underscore (very rare)
191
- return (/^[0-9]/.test(result) ? '_' : '') + result;
192
- }
198
+ return (/^[0-9]/.test(result) ? "_" : "") + result;
199
+ });
193
200
  /**
194
- * parse css string
201
+ * Parse css string
195
202
  * @param iter
196
203
  * @param options
197
204
  *
@@ -200,13 +207,14 @@ async function generateScopedName(localName, filePath, pattern, hashLength = 5)
200
207
  */
201
208
  async function doParse(iter, options = {}) {
202
209
  if (options.signal != null) {
203
- options.signal.addEventListener('abort', reject);
210
+ options.signal.addEventListener("abort", reject);
204
211
  }
205
212
  options = {
206
- src: '',
213
+ src: "",
207
214
  sourcemap: false,
208
215
  minify: true,
209
216
  pass: 1,
217
+ expandIfSyntax: false,
210
218
  parseColor: true,
211
219
  nestingRules: true,
212
220
  resolveImport: false,
@@ -220,12 +228,12 @@ async function doParse(iter, options = {}) {
220
228
  inlineCssVariables: false,
221
229
  setParent: true,
222
230
  removePrefix: false,
223
- validation: ValidationLevel.Default,
231
+ validation: false,
224
232
  lenient: true,
225
- ...options
233
+ ...options,
226
234
  };
227
- if (typeof options.validation == 'boolean') {
228
- options.validation = options.validation ? ValidationLevel.All : ValidationLevel.None;
235
+ if (typeof options.validation !== "boolean") {
236
+ options.validation = !!options.validation;
229
237
  }
230
238
  if (options.module) {
231
239
  options.expandNestingRules = true;
@@ -241,36 +249,37 @@ async function doParse(iter, options = {}) {
241
249
  const src = options.src;
242
250
  const stack = [];
243
251
  const stats = {
244
- src: options.src ?? '',
252
+ src: options.src ?? "",
245
253
  bytesIn: 0,
246
254
  nodesCount: 0,
247
255
  tokensCount: 0,
248
256
  importedBytesIn: 0,
257
+ tokenize: `0ms`,
249
258
  parse: `0ms`,
250
259
  minify: `0ms`,
251
260
  total: `0ms`,
252
- imports: []
261
+ imports: [],
253
262
  };
263
+ const invalidNodes = [];
254
264
  let ast = {
255
265
  typ: EnumToken.StyleSheetNodeType,
256
- chi: []
266
+ chi: [],
257
267
  };
258
268
  let tokens = [];
259
- let map = new Map;
260
269
  let context = ast;
261
270
  if (options.sourcemap) {
262
271
  ast.loc = {
263
272
  sta: {
264
273
  ind: 0,
265
274
  lin: 1,
266
- col: 1
275
+ col: 1,
267
276
  },
268
277
  end: {
269
278
  ind: 0,
270
279
  lin: 1,
271
- col: 1
280
+ col: 1,
272
281
  },
273
- src: ''
282
+ src: "",
274
283
  };
275
284
  }
276
285
  let valuesHandlers;
@@ -279,19 +288,19 @@ async function doParse(iter, options = {}) {
279
288
  let preVisitorsHandlersMap;
280
289
  let visitorsHandlersMap;
281
290
  let postVisitorsHandlersMap;
282
- const rawTokens = [];
283
291
  const imports = [];
284
292
  let item;
285
293
  let node;
286
294
  // @ts-ignore ignore error
287
- let isAsync = typeof iter[Symbol.asyncIterator] === 'function';
295
+ let isAsync = typeof iter[Symbol.asyncIterator] === "function";
296
+ let parensMatch = 0;
288
297
  if (options.visitor != null) {
289
- valuesHandlers = new Map;
290
- preValuesHandlers = new Map;
291
- postValuesHandlers = new Map;
292
- preVisitorsHandlersMap = new Map;
293
- visitorsHandlersMap = new Map;
294
- postVisitorsHandlersMap = new Map;
298
+ valuesHandlers = new Map();
299
+ preValuesHandlers = new Map();
300
+ postValuesHandlers = new Map();
301
+ preVisitorsHandlersMap = new Map();
302
+ visitorsHandlersMap = new Map();
303
+ postVisitorsHandlersMap = new Map();
295
304
  const visitors = Object.entries(options.visitor);
296
305
  let key;
297
306
  let value;
@@ -309,199 +318,221 @@ async function doParse(iter, options = {}) {
309
318
  continue;
310
319
  }
311
320
  if (key in EnumToken) {
312
- if (typeof value == 'function') {
321
+ if (typeof value == "function") {
313
322
  if (!valuesHandlers.has(EnumToken[key])) {
314
323
  valuesHandlers.set(EnumToken[key], []);
315
324
  }
316
325
  valuesHandlers.get(EnumToken[key]).push(value);
317
326
  }
318
- else if (typeof value == 'object' && 'type' in value && 'handler' in value && value.type in WalkerEvent) {
327
+ else if (typeof value == "object" &&
328
+ "type" in value &&
329
+ "handler" in value &&
330
+ value.type in WalkerEvent) {
319
331
  if (value.type == WalkerEvent.Enter) {
320
332
  if (!preValuesHandlers.has(EnumToken[key])) {
321
333
  preValuesHandlers.set(EnumToken[key], []);
322
334
  }
323
- preValuesHandlers.get(EnumToken[key]).push(value.handler);
335
+ preValuesHandlers
336
+ .get(EnumToken[key])
337
+ .push(value.handler);
324
338
  }
325
339
  else if (value.type == WalkerEvent.Leave) {
326
340
  if (!postValuesHandlers.has(EnumToken[key])) {
327
341
  postValuesHandlers.set(EnumToken[key], []);
328
342
  }
329
- postValuesHandlers.get(EnumToken[key]).push(value.handler);
343
+ postValuesHandlers
344
+ .get(EnumToken[key])
345
+ .push(value.handler);
330
346
  }
331
347
  }
332
348
  else {
333
- errors.push({ action: 'ignore', message: `doParse: visitor.${key} is not a valid key name` });
349
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
334
350
  }
335
351
  }
336
- else if (['Declaration', 'Rule', 'AtRule', 'KeyframesRule', 'KeyframesAtRule'].includes(key)) {
337
- if (typeof value == 'function') {
352
+ else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) {
353
+ if (typeof value == "function") {
338
354
  if (!visitorsHandlersMap.has(key)) {
339
355
  visitorsHandlersMap.set(key, []);
340
356
  }
341
- visitorsHandlersMap.get(key).push(value);
357
+ visitorsHandlersMap
358
+ .get(key)
359
+ .push(value);
342
360
  }
343
- else if (typeof value == 'object') {
344
- if ('type' in value && 'handler' in value && value.type in WalkerEvent) {
361
+ else if (typeof value == "object") {
362
+ if ("type" in value && "handler" in value && value.type in WalkerEvent) {
345
363
  if (value.type == WalkerEvent.Enter) {
346
364
  if (!preVisitorsHandlersMap.has(key)) {
347
365
  preVisitorsHandlersMap.set(key, []);
348
366
  }
349
- preVisitorsHandlersMap.get(key).push(value.handler);
367
+ preVisitorsHandlersMap
368
+ .get(key)
369
+ .push(value.handler);
350
370
  }
351
371
  else if (value.type == WalkerEvent.Leave) {
352
372
  if (!postVisitorsHandlersMap.has(key)) {
353
373
  postVisitorsHandlersMap.set(key, []);
354
374
  }
355
- postVisitorsHandlersMap.get(key).push(value.handler);
375
+ postVisitorsHandlersMap
376
+ .get(key)
377
+ .push(value.handler);
356
378
  }
357
379
  }
358
380
  else {
359
381
  if (!visitorsHandlersMap.has(key)) {
360
382
  visitorsHandlersMap.set(key, []);
361
383
  }
362
- visitorsHandlersMap.get(key).push(value);
384
+ visitorsHandlersMap
385
+ .get(key)
386
+ .push(value);
363
387
  }
364
388
  }
365
389
  else {
366
- errors.push({ action: 'ignore', message: `doParse: visitor.${key} is not a valid key name` });
390
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
367
391
  }
368
392
  }
369
393
  else {
370
- errors.push({ action: 'ignore', message: `doParse: visitor.${key} is not a valid key name` });
394
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
371
395
  }
372
396
  }
373
397
  }
374
- while (item = isAsync ? (await iter.next()).value : iter.next().value) {
398
+ if (Array.isArray(iter)) {
399
+ // @ts-expect-error
400
+ iter = iter[Symbol.iterator]();
401
+ }
402
+ while ((item = isAsync
403
+ ? // @ts-expect-error
404
+ (await iter.next()).value
405
+ : // @ts-expect-error
406
+ iter.next().value)) {
375
407
  stats.bytesIn = item.bytesIn;
376
408
  stats.tokensCount++;
377
- rawTokens.push(item);
378
- if (item.hint != null && BadTokensTypes.includes(item.hint)) {
379
- const node = getTokenType(item.token, item.hint);
409
+ if (options.sourcemap !== false) {
410
+ Object.defineProperty(item.token, "loc", {
411
+ ...definedPropertySettings,
412
+ value: item.token.loc,
413
+ enumerable: true,
414
+ });
415
+ }
416
+ if (BadTokensTypes.includes(item.token.typ)) {
417
+ tokens.push(item.token);
380
418
  errors.push({
381
- action: 'drop',
382
- message: 'Bad token',
419
+ action: "drop",
420
+ message: "Bad token",
383
421
  syntax: null,
384
- node,
385
- location: {
386
- src,
387
- sta: item.sta,
388
- end: item.end
389
- }
422
+ node: item.token,
423
+ location: item.token.loc,
390
424
  });
391
425
  // bad token
392
426
  continue;
393
427
  }
394
- if (item.hint != EnumToken.EOFTokenType) {
395
- tokens.push(item);
428
+ if (item.token.typ === EnumToken.StartParensTokenType || tokensfuncDefMap.has(item.token.typ)) {
429
+ parensMatch++;
396
430
  }
397
- else if (ast.loc != null) {
398
- for (let i = stack.length - 1; i >= 0; i--) {
399
- stack[i].loc.end = { ...item.end };
400
- }
401
- ast.loc.end = item.end;
431
+ else if (item.token.typ === EnumToken.EndParensTokenType && parensMatch > 0) {
432
+ parensMatch--;
402
433
  }
403
- if (item.token == ';' || item.token == '{') {
404
- node = parseNode(tokens, context, options, errors, src, map, rawTokens, stats);
405
- rawTokens.length = 0;
434
+ tokens.push(item.token);
435
+ if ((parensMatch === 0 &&
436
+ (item.token.typ === EnumToken.SemiColonTokenType ||
437
+ item.token.typ === EnumToken.BlockStartTokenType)) ||
438
+ item.token.typ === EnumToken.EOFTokenType) {
439
+ node = parseNode(tokens, context, options, errors, stats, invalidNodes);
406
440
  if (node != null) {
407
- if ('chi' in node) {
441
+ if ("chi" in node) {
408
442
  stack.push(node);
409
443
  context = node;
410
444
  }
411
- else if (node.typ == EnumToken.AtRuleNodeType && node.nam == 'import') {
445
+ else if (node.typ == EnumToken.AtRuleNodeType && node.nam === "import") {
412
446
  imports.push(node);
413
447
  }
414
448
  }
415
- else if (item.token == '{') {
449
+ else if (item.token.typ == EnumToken.BlockStartTokenType) {
416
450
  let inBlock = 1;
417
- tokens = [item];
451
+ tokens = [item.token];
418
452
  do {
419
- item = isAsync ? (await iter.next()).value : iter.next().value;
453
+ item = isAsync
454
+ ? // @ts-expect-error
455
+ (await iter.next()).value
456
+ : // @ts-expect-error
457
+ iter.next().value;
420
458
  if (item == null) {
421
459
  break;
422
460
  }
423
- tokens.push(item);
424
- if (item.token == '{') {
461
+ tokens.push(item.token);
462
+ if (item.token.typ === EnumToken.BlockStartTokenType) {
425
463
  inBlock++;
426
464
  }
427
- else if (item.token == '}') {
465
+ else if (item.token.typ === EnumToken.BlockEndTokenType) {
428
466
  inBlock--;
429
467
  }
430
468
  } while (inBlock != 0);
431
469
  if (tokens.length > 0) {
432
470
  errors.push({
433
- action: 'drop',
434
- message: 'invalid block',
435
- rawTokens: tokens.slice(),
471
+ action: "drop",
472
+ message: "invalid block",
436
473
  location: {
437
474
  src,
438
- sta: tokens[0].sta,
439
- end: tokens[tokens.length - 1].end
440
- }
475
+ sta: tokens[0].loc.sta,
476
+ end: tokens[tokens.length - 1].loc.end,
477
+ },
441
478
  });
442
479
  }
443
480
  }
444
481
  tokens = [];
445
- map = new Map;
446
482
  }
447
- else if (item.token == '}') {
448
- parseNode(tokens, context, options, errors, src, map, rawTokens, stats);
449
- rawTokens.length = 0;
483
+ else if (item.token.typ === EnumToken.BlockEndTokenType) {
484
+ parseNode(tokens, context, options, errors, stats, invalidNodes);
450
485
  if (context.loc != null) {
451
- context.loc.end = item.end;
486
+ context.loc.end = item.token.loc.end;
452
487
  }
453
488
  const previousNode = stack.pop();
454
489
  context = (stack[stack.length - 1] ?? ast);
455
- if (previousNode != null && previousNode.typ == EnumToken.InvalidRuleTokenType) {
456
- const index = context.chi.findIndex(node => node == previousNode);
457
- if (index > -1) {
458
- context.chi.splice(index, 1);
459
- }
460
- }
461
- if (options.removeEmpty && previousNode != null && previousNode.chi.length == 0 && context.chi[context.chi.length - 1] == previousNode) {
490
+ if (options.removeEmpty &&
491
+ previousNode != null &&
492
+ previousNode.chi.length == 0 &&
493
+ context.chi[context.chi.length - 1] == previousNode) {
462
494
  context.chi.pop();
463
495
  }
464
496
  tokens = [];
465
- map = new Map;
466
497
  }
467
498
  }
468
499
  if (tokens.length > 0) {
469
- node = parseNode(tokens, context, options, errors, src, map, rawTokens, stats);
470
- rawTokens.length = 0;
500
+ node = parseNode(tokens, context, options, errors, stats, invalidNodes);
471
501
  if (node != null) {
472
- if (node.typ == EnumToken.AtRuleNodeType && node.nam == 'import') {
502
+ if (node.typ == EnumToken.AtRuleNodeType && "import" === node.val) {
473
503
  imports.push(node);
474
504
  }
475
- else if ('chi' in node && node.typ != EnumToken.InvalidRuleTokenType) {
505
+ if ("chi" in node /* && node.typ != EnumToken.InvalidRuleNodeType */) {
476
506
  stack.push(node);
477
507
  context = node;
478
508
  }
479
509
  }
480
- if (context != null && context.typ == EnumToken.InvalidRuleTokenType) {
481
- // @ts-ignore ignore error
482
- const index = context.chi.findIndex((node) => node === context);
483
- if (index > -1) {
484
- context.chi.splice(index, 1);
485
- }
486
- }
487
510
  }
488
511
  if (imports.length > 0 && options.resolveImport) {
489
512
  await Promise.all(imports.map(async (node) => {
513
+ if (node.state !== EnumAstNodeStatus.Validated) {
514
+ return;
515
+ }
490
516
  const token = node.tokens[0];
491
517
  const url = token.typ == EnumToken.StringTokenType ? token.val.slice(1, -1) : token.val;
492
518
  try {
493
- const result = options.load(url, options.src);
494
- const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == 'AsyncFunction' ? await result : result;
495
- const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream) : tokenize({
496
- stream,
497
- buffer: '',
498
- offset: 0,
499
- position: { ind: 0, lin: 1, col: 1 },
500
- currentPosition: { ind: -1, lin: 1, col: 0 }
501
- }), Object.assign({}, options, {
519
+ const result = options.load(url, options.src || options.cwd);
520
+ const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
521
+ ? await result
522
+ : result;
523
+ const root = await doParse(stream instanceof ReadableStream
524
+ ? tokenizeStream(stream)
525
+ : tokenize({
526
+ stream,
527
+ src: options.resolve(url, options.src || options.cwd).relative,
528
+ buffer: "",
529
+ offset: 0,
530
+ position: { ind: 0, lin: 1, col: 1 },
531
+ currentPosition: { ind: -1, lin: 1, col: 0 },
532
+ }), Object.assign({}, options, {
502
533
  minify: false,
503
534
  setParent: false,
504
- src: options.resolve(url, options.src).absolute
535
+ src: options.resolve(url, options.src || options.cwd).relative,
505
536
  }));
506
537
  stats.importedBytesIn += root.stats.bytesIn;
507
538
  stats.imports.push(root.stats);
@@ -512,20 +543,10 @@ async function doParse(iter, options = {}) {
512
543
  }
513
544
  catch (error) {
514
545
  // @ts-ignore ignore error
515
- errors.push({ action: 'ignore', message: 'doParse: ' + error.message, error });
546
+ errors.push({ action: "ignore", message: ("doParse: " + error.message), error });
516
547
  }
517
548
  }));
518
549
  }
519
- while (stack.length > 0 && context != ast) {
520
- const previousNode = stack.pop();
521
- context = (stack[stack.length - 1] ?? ast);
522
- // remove empty nodes
523
- if (options.removeEmpty && previousNode != null && previousNode.chi.length == 0 && context.chi[context.chi.length - 1] == previousNode) {
524
- context.chi.pop();
525
- continue;
526
- }
527
- break;
528
- }
529
550
  const endParseTime = performance.now();
530
551
  if (options.expandNestingRules) {
531
552
  ast = expand(ast);
@@ -533,17 +554,35 @@ async function doParse(iter, options = {}) {
533
554
  let replacement;
534
555
  let callable;
535
556
  if (options.visitor != null) {
557
+ let parens;
536
558
  for (const result of walk(ast)) {
537
- if (valuesHandlers.size > 0 || preVisitorsHandlersMap.size > 0 || visitorsHandlersMap.size > 0 || postVisitorsHandlersMap.size > 0) {
559
+ parens = null;
560
+ if (valuesHandlers.size > 0 ||
561
+ preVisitorsHandlersMap.size > 0 ||
562
+ visitorsHandlersMap.size > 0 ||
563
+ postVisitorsHandlersMap.size > 0) {
538
564
  if ((result.node.typ == EnumToken.DeclarationNodeType &&
539
- (preVisitorsHandlersMap.has('Declaration') || visitorsHandlersMap.has('Declaration') || postVisitorsHandlersMap.has('Declaration'))) ||
540
- (result.node.typ == EnumToken.AtRuleNodeType && (preVisitorsHandlersMap.has('AtRule') || visitorsHandlersMap.has('AtRule') || postVisitorsHandlersMap.has('AtRule'))) ||
541
- (result.node.typ == EnumToken.KeyframesAtRuleNodeType && (preVisitorsHandlersMap.has('KeyframesAtRule') || visitorsHandlersMap.has('KeyframesAtRule') || postVisitorsHandlersMap.has('KeyframesAtRule')))) {
565
+ (preVisitorsHandlersMap.has("Declaration") ||
566
+ visitorsHandlersMap.has("Declaration") ||
567
+ postVisitorsHandlersMap.has("Declaration"))) ||
568
+ (result.node.typ == EnumToken.AtRuleNodeType &&
569
+ (preVisitorsHandlersMap.has("AtRule") ||
570
+ visitorsHandlersMap.has("AtRule") ||
571
+ postVisitorsHandlersMap.has("AtRule"))) ||
572
+ (result.node.typ == EnumToken.KeyframesAtRuleNodeType &&
573
+ (preVisitorsHandlersMap.has("KeyframesAtRule") ||
574
+ visitorsHandlersMap.has("KeyframesAtRule") ||
575
+ postVisitorsHandlersMap.has("KeyframesAtRule")))) {
542
576
  const handlers = [];
543
- const key = result.node.typ == EnumToken.DeclarationNodeType ? 'Declaration' : result.node.typ == EnumToken.AtRuleNodeType ? 'AtRule' : 'KeyframesAtRule';
577
+ const key = result.node.typ == EnumToken.DeclarationNodeType
578
+ ? "Declaration"
579
+ : result.node.typ == EnumToken.AtRuleNodeType
580
+ ? "AtRule"
581
+ : "KeyframesAtRule";
544
582
  if (preVisitorsHandlersMap.has(key)) {
545
- // @ts-ignore
546
- handlers.push(...preVisitorsHandlersMap.get(key));
583
+ handlers.push(
584
+ // @ts-expect-error
585
+ ...preVisitorsHandlersMap.get(key));
547
586
  }
548
587
  if (visitorsHandlersMap.has(key)) {
549
588
  // @ts-ignore
@@ -555,15 +594,30 @@ async function doParse(iter, options = {}) {
555
594
  }
556
595
  let node = result.node;
557
596
  for (const handler of handlers) {
558
- callable = typeof handler == 'function' ? handler : handler[camelize(node.typ == EnumToken.DeclarationNodeType || node.typ == EnumToken.AtRuleNodeType ? node.nam : node.val)];
597
+ callable =
598
+ typeof handler == "function"
599
+ ? handler
600
+ : handler[camelize(node.typ === EnumToken.DeclarationNodeType ||
601
+ node.typ === EnumToken.AtRuleNodeType
602
+ ? node.nam
603
+ : node.val)];
559
604
  if (callable == null) {
560
605
  continue;
561
606
  }
562
- replacement = callable(node, result.parent);
607
+ // @ts-expect-error
608
+ replacement = callable(node, result.parent, ast, function* () {
609
+ if (parens == null) {
610
+ // @ts-expect-error
611
+ parens = [...result.parents()];
612
+ }
613
+ yield* parens[Symbol.iterator]();
614
+ });
563
615
  if (replacement == null) {
564
616
  continue;
565
617
  }
566
- isAsync = replacement instanceof Promise || Object.getPrototypeOf(replacement).constructor.name == 'AsyncFunction';
618
+ isAsync =
619
+ replacement instanceof Promise ||
620
+ Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
567
621
  if (replacement) {
568
622
  replacement = await replacement;
569
623
  }
@@ -572,20 +626,24 @@ async function doParse(iter, options = {}) {
572
626
  }
573
627
  // @ts-ignore
574
628
  node = replacement;
575
- //
576
629
  if (Array.isArray(node)) {
577
630
  break;
578
631
  }
579
632
  }
580
633
  if (node != result.node) {
581
- // @ts-ignore
582
- replaceToken(result.parent, result.node, node);
634
+ replaceNodeOrValue(result.parent, result.node, node);
583
635
  }
584
636
  }
585
- else if ((result.node.typ == EnumToken.RuleNodeType && (preVisitorsHandlersMap.has('Rule') || visitorsHandlersMap.has('Rule') || postVisitorsHandlersMap.has('Rule'))) ||
586
- (result.node.typ == EnumToken.KeyFramesRuleNodeType && (preVisitorsHandlersMap.has('KeyframesRule') || visitorsHandlersMap.has('KeyframesRule') || postVisitorsHandlersMap.has('KeyframesRule')))) {
637
+ else if ((result.node.typ == EnumToken.RuleNodeType &&
638
+ (preVisitorsHandlersMap.has("Rule") ||
639
+ visitorsHandlersMap.has("Rule") ||
640
+ postVisitorsHandlersMap.has("Rule"))) ||
641
+ (result.node.typ == EnumToken.KeyFramesRuleNodeType &&
642
+ (preVisitorsHandlersMap.has("KeyframesRule") ||
643
+ visitorsHandlersMap.has("KeyframesRule") ||
644
+ postVisitorsHandlersMap.has("KeyframesRule")))) {
587
645
  const handlers = [];
588
- const key = result.node.typ == EnumToken.RuleNodeType ? 'Rule' : 'KeyframesRule';
646
+ const key = result.node.typ == EnumToken.RuleNodeType ? "Rule" : "KeyframesRule";
589
647
  if (preVisitorsHandlersMap.has(key)) {
590
648
  handlers.push(...preVisitorsHandlersMap.get(key));
591
649
  }
@@ -597,11 +655,21 @@ async function doParse(iter, options = {}) {
597
655
  }
598
656
  let node = result.node;
599
657
  for (const callable of handlers) {
600
- replacement = callable(node, result.parent);
658
+ replacement = callable(node, result.parent, result.root,
659
+ // @ts-expect-error
660
+ function* () {
661
+ if (parens == null) {
662
+ // @ts-expect-error
663
+ parens = [...result.parents()];
664
+ }
665
+ yield* parens[Symbol.iterator]();
666
+ });
601
667
  if (replacement == null) {
602
668
  continue;
603
669
  }
604
- isAsync = replacement instanceof Promise || Object.getPrototypeOf(replacement).constructor.name == 'AsyncFunction';
670
+ isAsync =
671
+ replacement instanceof Promise ||
672
+ Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
605
673
  if (replacement) {
606
674
  replacement = await replacement;
607
675
  }
@@ -618,7 +686,7 @@ async function doParse(iter, options = {}) {
618
686
  // @ts-ignore
619
687
  if (node != result.node) {
620
688
  // @ts-ignore
621
- replaceToken(result.parent, result.node, node);
689
+ replaceNodeOrValue(result.parent, result.node, node);
622
690
  }
623
691
  }
624
692
  else if (valuesHandlers.size > 0) {
@@ -627,11 +695,21 @@ async function doParse(iter, options = {}) {
627
695
  if (valuesHandlers.has(node.typ)) {
628
696
  for (const valueHandler of valuesHandlers.get(node.typ)) {
629
697
  callable = valueHandler;
630
- replacement = callable(node, result.parent);
698
+ replacement = callable(node, result.parent, ast,
699
+ // @ts-expect-error
700
+ function* () {
701
+ if (parens == null) {
702
+ // @ts-expect-error
703
+ parens = [...result.parents()];
704
+ }
705
+ yield* parens[Symbol.iterator]();
706
+ });
631
707
  if (replacement == null) {
632
708
  continue;
633
709
  }
634
- isAsync = replacement instanceof Promise || Object.getPrototypeOf(replacement).constructor.name == 'AsyncFunction';
710
+ isAsync =
711
+ replacement instanceof Promise ||
712
+ Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
635
713
  if (isAsync) {
636
714
  replacement = await replacement;
637
715
  }
@@ -642,32 +720,41 @@ async function doParse(iter, options = {}) {
642
720
  }
643
721
  if (node != result.node) {
644
722
  // @ts-ignore
645
- replaceToken(result.parent, value, node);
723
+ replaceNodeOrValue(result.parent, value, node);
646
724
  }
647
- const tokens = 'tokens' in result.node ? result.node.tokens : [];
648
- if ('val' in result.node && Array.isArray(result.node.val)) {
725
+ const tokens = Array.isArray(result.node.tokens) ? result.node.tokens : [];
726
+ if (Array.isArray(result.node.val)) {
649
727
  tokens.push(...result.node.val);
650
728
  }
651
729
  if (tokens.length == 0) {
652
730
  continue;
653
731
  }
654
- for (const { value, parent, root } of walkValues(tokens, result.node)) {
732
+ for (const { value, parent, root, parents } of walkValues(tokens, result.node)) {
655
733
  node = value;
656
734
  if (valuesHandlers.has(node.typ)) {
735
+ let parens = null;
657
736
  for (const valueHandler of valuesHandlers.get(node.typ)) {
658
737
  callable = valueHandler;
659
- let result = callable(node, parent, root);
738
+ // @ts-expect-error
739
+ let result = callable(node, parent, root, function* () {
740
+ if (parens == null) {
741
+ // @ts-expect-error
742
+ parens = [...parents()];
743
+ }
744
+ yield* parens[Symbol.iterator]();
745
+ });
660
746
  if (result == null) {
661
747
  continue;
662
748
  }
663
- isAsync = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == 'AsyncFunction';
749
+ isAsync =
750
+ result instanceof Promise ||
751
+ Object.getPrototypeOf(result).constructor.name == "AsyncFunction";
664
752
  if (isAsync) {
665
753
  result = await result;
666
754
  }
667
755
  if (result != null && result != node) {
668
756
  node = result;
669
757
  }
670
- //
671
758
  if (Array.isArray(node)) {
672
759
  break;
673
760
  }
@@ -675,13 +762,50 @@ async function doParse(iter, options = {}) {
675
762
  }
676
763
  if (node != value) {
677
764
  // @ts-ignore
678
- replaceToken(parent, value, node);
765
+ replaceNodeOrValue(parent, value, node);
679
766
  }
680
767
  }
681
768
  }
682
769
  }
683
770
  }
684
771
  }
772
+ if (invalidNodes.length > 0) {
773
+ let k = invalidNodes.length;
774
+ while (k-- > 0) {
775
+ if (invalidNodes[k].state == EnumAstNodeStatus.Validated || invalidNodes[k].state == EnumAstNodeStatus.Unvalidated || invalidNodes[k].state == EnumAstNodeStatus.ValidationFailed) {
776
+ continue;
777
+ }
778
+ if (options.lenient && invalidNodes[k].state == EnumAstNodeStatus.Unknown) {
779
+ continue;
780
+ }
781
+ invalidNodes[k].parent.chi.splice(invalidNodes[k].parent.chi.indexOf(invalidNodes[k]), 1);
782
+ }
783
+ }
784
+ while (stack.length > 0 && context != ast) {
785
+ const previousNode = stack.pop();
786
+ context = (stack[stack.length - 1] ?? ast);
787
+ // remove empty nodes
788
+ if (options.removeEmpty &&
789
+ previousNode != null &&
790
+ previousNode.chi.length == 0 &&
791
+ context.chi[context.chi.length - 1] == previousNode) {
792
+ context.chi.pop();
793
+ continue;
794
+ }
795
+ // remove invalid nodes
796
+ if (!options.lenient &&
797
+ previousNode?.parent != null &&
798
+ // @ts-expect-error
799
+ (previousNode.typ == EnumToken.InvalidRuleNodeType || previousNode.typ == EnumToken.InvalidAtRuleNodeType)) {
800
+ for (let i = context.chi.length - 1; i >= 0; i--) {
801
+ if (context.chi[i] == previousNode) {
802
+ context.chi.splice(i, 1);
803
+ break;
804
+ }
805
+ }
806
+ }
807
+ break;
808
+ }
685
809
  if (options.minify) {
686
810
  if (ast.chi.length > 0) {
687
811
  let passes = options.pass ?? 1;
@@ -699,32 +823,38 @@ async function doParse(iter, options = {}) {
699
823
  ...stats,
700
824
  parse: `${(endParseTime - startTime).toFixed(2)}ms`,
701
825
  minify: `${(endTime - endParseTime).toFixed(2)}ms`,
702
- total: `${(endTime - startTime).toFixed(2)}ms`
703
- }
826
+ tokenize: `${(options?.parseInfo?.time ?? 0).toFixed(2)}ms`,
827
+ total: `${(endTime - startTime).toFixed(2)}ms`,
828
+ },
704
829
  };
705
830
  if (options.module) {
706
831
  const moduleSettings = {
707
832
  hashLength: 5,
708
- filePath: '',
833
+ filePath: "",
709
834
  scoped: ModuleScopeEnumOptions.Local,
710
835
  naming: ModuleCaseTransformEnum.IgnoreCase,
711
- pattern: '',
836
+ pattern: "",
712
837
  generateScopedName,
713
- ...(typeof options.module != 'object' ? {} : options.module)
838
+ ...(typeof options.module != "object" ? {} : options.module),
714
839
  };
715
840
  const parseModuleTime = performance.now();
716
841
  const namesMapping = {};
717
- const global = new Set;
718
- const processed = new Set;
719
- const pattern = typeof options.module == 'boolean' ? null : moduleSettings.pattern;
842
+ const global = new Set();
843
+ const processed = new Set();
844
+ const pattern = typeof options.module == "boolean" ? null : moduleSettings.pattern;
720
845
  const importMapping = {};
721
846
  const cssVariablesMap = {};
722
847
  const importedCssVariables = {};
723
848
  let mapping = {};
724
849
  let revMapping = {};
725
- let filePath = typeof options.module == 'boolean' ? options.src : (moduleSettings.filePath ?? options.src);
726
- filePath = filePath === '' ? options.src : options.resolve(filePath, options.dirname(options.src), options.cwd).relative;
727
- if (typeof options.module == 'number') {
850
+ let filePath = typeof options.module == "boolean"
851
+ ? options.src
852
+ : (moduleSettings.filePath ?? options.src);
853
+ filePath =
854
+ filePath === ""
855
+ ? options.src
856
+ : options.resolve(filePath, options.dirname(options.src), options.cwd).relative;
857
+ if (typeof options.module == "number") {
728
858
  if (options.module & ModuleCaseTransformEnum.CamelCase) {
729
859
  moduleSettings.naming = ModuleCaseTransformEnum.CamelCase;
730
860
  }
@@ -744,44 +874,59 @@ async function doParse(iter, options = {}) {
744
874
  // @ts-ignore
745
875
  moduleSettings.scoped |= ModuleScopeEnumOptions.Pure;
746
876
  }
877
+ if (options.module & ModuleScopeEnumOptions.Shortest) {
878
+ // @ts-ignore
879
+ moduleSettings.scoped |= ModuleScopeEnumOptions.Shortest;
880
+ }
747
881
  if (options.module & ModuleScopeEnumOptions.ICSS) {
748
882
  // @ts-ignore
749
883
  moduleSettings.scoped |= ModuleScopeEnumOptions.ICSS;
750
884
  }
751
885
  }
752
- if (typeof moduleSettings.scoped == 'boolean') {
753
- moduleSettings.scoped = moduleSettings.scoped ? ModuleScopeEnumOptions.Local : ModuleScopeEnumOptions.Global;
886
+ if (typeof moduleSettings.scoped == "boolean") {
887
+ moduleSettings.scoped = moduleSettings.scoped
888
+ ? ModuleScopeEnumOptions.Local
889
+ : ModuleScopeEnumOptions.Global;
890
+ }
891
+ if (moduleSettings.scoped & ModuleScopeEnumOptions.Shortest) {
892
+ moduleSettings.generateScopedName = getShortNameGenerator;
754
893
  }
755
894
  moduleSettings.filePath = filePath;
756
- moduleSettings.pattern = pattern != null && pattern !== '' ? pattern : (filePath === '' ? `[local]_[hash]` : `[local]_[hash]_[name]`);
895
+ moduleSettings.pattern =
896
+ pattern != null && pattern !== "" ? pattern : filePath === "" ? `[local]_[hash]` : `[local]_[hash]_[name]`;
757
897
  for (const { node, parent } of walk(ast)) {
758
898
  if (node.typ == EnumToken.CssVariableImportTokenType) {
759
- const url = node.val.find(t => t.typ == EnumToken.StringTokenType).val.slice(1, -1);
899
+ const url = node.val.find((t) => t.typ == EnumToken.StringTokenType).val.slice(1, -1);
760
900
  const src = options.resolve(url, options.dirname(options.src), options.cwd);
761
- const result = options.load(url, options.src);
762
- const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == 'AsyncFunction' ? await result : result;
763
- const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream) : tokenize({
901
+ const result = options.load(src, "");
902
+ const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
903
+ ? await result
904
+ : result;
905
+ const parseInfo = {
764
906
  stream,
765
- buffer: '',
907
+ buffer: "",
766
908
  offset: 0,
909
+ time: 0,
767
910
  position: { ind: 0, lin: 1, col: 1 },
768
- currentPosition: { ind: -1, lin: 1, col: 0 }
769
- }), Object.assign({}, options, {
911
+ currentPosition: { ind: -1, lin: 1, col: 0 },
912
+ };
913
+ const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream, parseInfo) : tokenize(parseInfo), Object.assign({}, options, {
770
914
  minify: false,
771
915
  setParent: false,
772
- src: src.relative
916
+ src: src.relative,
773
917
  }));
918
+ options.parseInfo.time += parseInfo.time;
774
919
  cssVariablesMap[node.nam] = root.cssModuleVariables;
775
920
  parent.chi.splice(parent.chi.indexOf(node), 1);
776
921
  continue;
777
922
  }
778
923
  if (node.typ == EnumToken.CssVariableDeclarationMapTokenType) {
779
- const from = node.from.find(t => t.typ == EnumToken.IdenTokenType || isIdentColor(t));
924
+ const from = node.from.find((t) => t.typ == EnumToken.IdenTokenType || isIdentColor(t));
780
925
  if (!(from.val in cssVariablesMap)) {
781
926
  errors.push({
782
927
  node,
783
928
  message: `could not resolve @value import from '${from.val}'`,
784
- action: 'drop'
929
+ action: "drop",
785
930
  });
786
931
  }
787
932
  else {
@@ -791,7 +936,7 @@ async function doParse(iter, options = {}) {
791
936
  errors.push({
792
937
  node,
793
938
  message: `value '${token.val}' is not exported from '${from.val}'`,
794
- action: 'drop'
939
+ action: "drop",
795
940
  });
796
941
  continue;
797
942
  }
@@ -814,29 +959,27 @@ async function doParse(iter, options = {}) {
814
959
  continue;
815
960
  }
816
961
  if (node.typ == EnumToken.DeclarationNodeType) {
817
- if (node.nam.startsWith('--')) {
962
+ if (node.nam.startsWith("--")) {
818
963
  if (!(node.nam in namesMapping)) {
819
- let result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? node.nam : moduleSettings.generateScopedName(node.nam, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
964
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
965
+ ? node.nam
966
+ : moduleSettings.generateScopedName(node.nam, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
820
967
  let value = result instanceof Promise ? await result : result;
821
- mapping[node.nam] = '--' + (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) : value);
968
+ mapping[node.nam] =
969
+ "--" +
970
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
971
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
972
+ ? getKeyName(value, moduleSettings.naming)
973
+ : value);
822
974
  revMapping[node.nam] = node.nam;
823
975
  }
824
976
  node.nam = mapping[node.nam];
825
977
  }
826
- if ('composes' == node.nam.toLowerCase()) {
978
+ if (equalsIgnoreCase("composes", node.nam)) {
827
979
  const tokens = [];
828
- let isValid = true;
980
+ // let isValid: boolean = true;
829
981
  for (const token of node.val) {
830
982
  if (token.typ == EnumToken.ComposesSelectorNodeType) {
831
- if (!(token.r == null || token.r.typ == EnumToken.StringTokenType || token.r.typ == EnumToken.IdenTokenType)) {
832
- errors.push({
833
- action: 'drop',
834
- message: `composes '${EnumToken[token.r.typ]}' is not supported`,
835
- node
836
- });
837
- isValid = false;
838
- break;
839
- }
840
983
  tokens.push(token);
841
984
  }
842
985
  }
@@ -845,14 +988,12 @@ async function doParse(iter, options = {}) {
845
988
  while (parentRule != null && parentRule.typ != EnumToken.RuleNodeType) {
846
989
  parentRule = parentRule.parent;
847
990
  }
848
- if (!isValid || tokens.length == 0) {
849
- if (tokens.length == 0) {
850
- errors.push({
851
- action: 'drop',
852
- message: `composes is empty`,
853
- node
854
- });
855
- }
991
+ if ( /* !isValid || */tokens.length == 0) {
992
+ errors.push({
993
+ action: "drop",
994
+ message: `composes is empty`,
995
+ node,
996
+ });
856
997
  parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
857
998
  continue;
858
999
  }
@@ -860,13 +1001,21 @@ async function doParse(iter, options = {}) {
860
1001
  // composes: a b c;
861
1002
  if (token.r == null) {
862
1003
  for (const rule of token.l) {
863
- if (rule.typ == EnumToken.WhitespaceTokenType || rule.typ == EnumToken.CommentTokenType) {
1004
+ if (rule.typ == EnumToken.WhitespaceTokenType ||
1005
+ rule.typ == EnumToken.CommentTokenType) {
864
1006
  continue;
865
1007
  }
866
1008
  if (!(rule.val in mapping)) {
867
- let result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? rule.val : moduleSettings.generateScopedName(rule.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1009
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1010
+ ? rule.val
1011
+ : moduleSettings.generateScopedName(rule.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
868
1012
  let value = result instanceof Promise ? await result : result;
869
- mapping[rule.val] = (rule.typ == EnumToken.DashedIdenTokenType ? '--' : '') + (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) : value);
1013
+ mapping[rule.val] =
1014
+ (rule.typ == EnumToken.DashedIdenTokenType ? "--" : "") +
1015
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1016
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1017
+ ? getKeyName(value, moduleSettings.naming)
1018
+ : value);
870
1019
  revMapping[mapping[rule.val]] = rule.val;
871
1020
  }
872
1021
  if (parentRule != null) {
@@ -875,7 +1024,12 @@ async function doParse(iter, options = {}) {
875
1024
  const val = tk.val.slice(1);
876
1025
  if (val in revMapping) {
877
1026
  const key = revMapping[val];
878
- mapping[key] = [...new Set([...mapping[key].split(' '), mapping[rule.val]])].join(' ');
1027
+ mapping[key] = [
1028
+ ...new Set([
1029
+ ...mapping[key].split(" "),
1030
+ mapping[rule.val],
1031
+ ]),
1032
+ ].join(" ");
879
1033
  }
880
1034
  }
881
1035
  }
@@ -886,20 +1040,26 @@ async function doParse(iter, options = {}) {
886
1040
  else if (token.r.typ == EnumToken.String) {
887
1041
  const url = token.r.val.slice(1, -1);
888
1042
  const src = options.resolve(url, options.dirname(options.src), options.cwd);
889
- const result = options.load(url, options.src);
890
- const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == 'AsyncFunction' ? await result : result;
891
- const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream) : tokenize({
892
- stream,
893
- buffer: '',
894
- offset: 0,
895
- position: { ind: 0, lin: 1, col: 1 },
896
- currentPosition: { ind: -1, lin: 1, col: 0 }
897
- }), Object.assign({}, options, {
1043
+ const result = options.load(src, "");
1044
+ const stream = result instanceof Promise ||
1045
+ Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
1046
+ ? await result
1047
+ : result;
1048
+ const root = await doParse(stream instanceof ReadableStream
1049
+ ? tokenizeStream(stream)
1050
+ : tokenize({
1051
+ stream,
1052
+ buffer: "",
1053
+ offset: 0,
1054
+ position: { ind: 0, lin: 1, col: 1 },
1055
+ currentPosition: { ind: -1, lin: 1, col: 0 },
1056
+ }), Object.assign({}, options, {
898
1057
  minify: false,
899
1058
  setParent: false,
900
- src: src.relative
1059
+ src: src.relative,
901
1060
  }));
902
- const srcIndex = (src.relative.startsWith('/') || src.relative.startsWith('../') ? '' : './') + src.relative;
1061
+ const srcIndex = (src.relative.startsWith("/") || src.relative.startsWith("../") ? "" : "./") +
1062
+ src.relative;
903
1063
  if (Object.keys(root.mapping).length > 0) {
904
1064
  importMapping[srcIndex] = {};
905
1065
  }
@@ -911,19 +1071,27 @@ async function doParse(iter, options = {}) {
911
1071
  const key = revMapping[val];
912
1072
  const values = [];
913
1073
  for (const iden of token.l) {
914
- if (iden.typ != EnumToken.IdenTokenType && iden.typ != EnumToken.DashedIdenTokenType) {
1074
+ if (iden.typ != EnumToken.IdenTokenType &&
1075
+ iden.typ != EnumToken.DashedIdenTokenType) {
915
1076
  continue;
916
1077
  }
917
1078
  if (!(iden.val in root.mapping)) {
918
- const result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? iden.val : moduleSettings.generateScopedName(iden.val, srcIndex, moduleSettings.pattern, moduleSettings.hashLength);
1079
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1080
+ ? iden.val
1081
+ : moduleSettings.generateScopedName(iden.val, srcIndex, moduleSettings.pattern, moduleSettings.hashLength);
919
1082
  let value = result instanceof Promise ? await result : result;
920
- root.mapping[iden.val] = (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) : value);
1083
+ root.mapping[iden.val] =
1084
+ moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1085
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1086
+ ? getKeyName(value, moduleSettings.naming)
1087
+ : value;
921
1088
  root.revMapping[root.mapping[iden.val]] = iden.val;
922
1089
  }
923
- importMapping[srcIndex][iden.val] = root.mapping[iden.val];
1090
+ importMapping[srcIndex][iden.val] =
1091
+ root.mapping[iden.val];
924
1092
  values.push(root.mapping[iden.val]);
925
1093
  }
926
- mapping[key] = [...new Set([...mapping[key].split(' '), ...values])].join(' ');
1094
+ mapping[key] = [...new Set([...mapping[key].split(" "), ...values])].join(" ");
927
1095
  }
928
1096
  }
929
1097
  }
@@ -933,27 +1101,32 @@ async function doParse(iter, options = {}) {
933
1101
  else if (token.r.typ == EnumToken.IdenTokenType) {
934
1102
  // global
935
1103
  if (parentRule != null) {
936
- if ('global' == token.r.val.toLowerCase()) {
1104
+ if (equalsIgnoreCase("global", token.r.val)) {
937
1105
  for (const tk of parentRule.tokens) {
938
1106
  if (tk.typ == EnumToken.ClassSelectorTokenType) {
939
1107
  const val = tk.val.slice(1);
940
1108
  if (val in revMapping) {
941
1109
  const key = revMapping[val];
942
- mapping[key] = [...new Set([...mapping[key].split(' '), ...(token.l.reduce((acc, curr) => {
1110
+ mapping[key] = [
1111
+ ...new Set([
1112
+ ...mapping[key].split(" "),
1113
+ ...token.l.reduce((acc, curr) => {
943
1114
  if (curr.typ == EnumToken.IdenTokenType) {
944
1115
  acc.push(curr.val);
945
1116
  }
946
1117
  return acc;
947
- }, []))])].join(' ');
1118
+ }, []),
1119
+ ]),
1120
+ ].join(" ");
948
1121
  }
949
1122
  }
950
1123
  }
951
1124
  }
952
1125
  else {
953
1126
  errors.push({
954
- action: 'drop',
1127
+ action: "drop",
955
1128
  message: `composes '${token.r.val}' is not supported`,
956
- node
1129
+ node,
957
1130
  });
958
1131
  }
959
1132
  }
@@ -961,29 +1134,42 @@ async function doParse(iter, options = {}) {
961
1134
  }
962
1135
  parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
963
1136
  }
964
- if (node.typ == EnumToken.DeclarationNodeType && ['grid-column', 'grid-column-start', 'grid-column-end', 'grid-row', 'grid-row-start', 'grid-row-end', 'grid-template', 'grid-template-columns', 'grid-template-rows'].includes(node.nam)) {
1137
+ if (node.typ == EnumToken.DeclarationNodeType &&
1138
+ [
1139
+ "grid-column",
1140
+ "grid-column-start",
1141
+ "grid-column-end",
1142
+ "grid-row",
1143
+ "grid-row-start",
1144
+ "grid-row-end",
1145
+ "grid-template",
1146
+ "grid-template-columns",
1147
+ "grid-template-rows",
1148
+ ].includes(node.nam)) {
965
1149
  for (const { value } of walkValues(node.val, node)) {
966
1150
  if (value.typ != EnumToken.IdenTokenType) {
967
1151
  continue;
968
1152
  }
969
1153
  let idenToken = value.val;
970
- let suffix = '';
971
- if (idenToken.endsWith('-start')) {
972
- suffix = '-start';
1154
+ let suffix = "";
1155
+ if (idenToken.endsWith("-start")) {
1156
+ suffix = "-start";
973
1157
  idenToken = idenToken.slice(0, -6);
974
1158
  }
975
- else if (idenToken.endsWith('-end')) {
976
- suffix = '-end';
1159
+ else if (idenToken.endsWith("-end")) {
1160
+ suffix = "-end";
977
1161
  idenToken = idenToken.slice(0, -4);
978
1162
  }
979
1163
  if (!(idenToken in mapping)) {
980
- let result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? idenToken : moduleSettings.generateScopedName(idenToken, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1164
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1165
+ ? idenToken
1166
+ : moduleSettings.generateScopedName(idenToken, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
981
1167
  if (result instanceof Promise) {
982
1168
  result = await result;
983
1169
  }
984
1170
  mapping[idenToken] = result;
985
1171
  revMapping[result] = idenToken;
986
- if (suffix !== '') {
1172
+ if (suffix !== "") {
987
1173
  idenToken += suffix;
988
1174
  if (!(idenToken in mapping)) {
989
1175
  mapping[idenToken] = result + suffix;
@@ -994,17 +1180,20 @@ async function doParse(iter, options = {}) {
994
1180
  value.val = mapping[idenToken];
995
1181
  }
996
1182
  }
997
- else if (node.nam == 'grid-template-areas' || node.nam == 'grid-template') {
1183
+ else if (node.nam == "grid-template-areas" || node.nam == "grid-template") {
998
1184
  for (let i = 0; i < node.val.length; i++) {
999
1185
  if (node.val[i].typ == EnumToken.String) {
1000
- const tokens = parseString(node.val[i].val.slice(1, -1), { location: true });
1186
+ const tokens = parseString(node.val[i].val.slice(1, -1));
1001
1187
  for (const { value } of walkValues(tokens)) {
1002
- if (value.typ == EnumToken.IdenTokenType || value.typ == EnumToken.DashedIdenTokenType) {
1188
+ if (value.typ == EnumToken.IdenTokenType ||
1189
+ value.typ == EnumToken.DashedIdenTokenType) {
1003
1190
  if (value.val in mapping) {
1004
1191
  value.val = mapping[value.val];
1005
1192
  }
1006
1193
  else {
1007
- let result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? value.val : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1194
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1195
+ ? value.val
1196
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1008
1197
  if (result instanceof Promise) {
1009
1198
  result = await result;
1010
1199
  }
@@ -1014,22 +1203,49 @@ async function doParse(iter, options = {}) {
1014
1203
  }
1015
1204
  }
1016
1205
  }
1017
- node.val[i].val = node.val[i].val.charAt(0) + tokens.reduce((acc, curr) => acc + renderToken(curr), '') + node.val[i].val.charAt(node.val[i].val.length - 1);
1206
+ node.val[i].val =
1207
+ node.val[i].val.charAt(0) +
1208
+ renderTokens(tokens) +
1209
+ node.val[i].val.charAt(node.val[i].val.length - 1);
1018
1210
  }
1019
1211
  }
1020
1212
  }
1021
- else if (node.nam == 'animation' || node.nam == 'animation-name') {
1213
+ else if (node.nam == "animation" || node.nam == "animation-name") {
1022
1214
  for (const { value } of walkValues(node.val, node)) {
1023
- if (value.typ == EnumToken.IdenTokenType && ![
1024
- 'none', 'infinite', 'normal', 'reverse', 'alternate',
1025
- 'alternate-reverse', 'forwards', 'backwards', 'both',
1026
- 'running', 'paused', 'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out',
1027
- 'step-start', 'step-end', 'jump-start', 'jump-end',
1028
- 'jump-none', 'jump-both', 'start', 'end',
1029
- 'inherit', 'initial', 'unset'
1030
- ].includes(value.val)) {
1215
+ if (value.typ == EnumToken.IdenTokenType &&
1216
+ ![
1217
+ "none",
1218
+ "infinite",
1219
+ "normal",
1220
+ "reverse",
1221
+ "alternate",
1222
+ "alternate-reverse",
1223
+ "forwards",
1224
+ "backwards",
1225
+ "both",
1226
+ "running",
1227
+ "paused",
1228
+ "linear",
1229
+ "ease",
1230
+ "ease-in",
1231
+ "ease-out",
1232
+ "ease-in-out",
1233
+ "step-start",
1234
+ "step-end",
1235
+ "jump-start",
1236
+ "jump-end",
1237
+ "jump-none",
1238
+ "jump-both",
1239
+ "start",
1240
+ "end",
1241
+ "inherit",
1242
+ "initial",
1243
+ "unset",
1244
+ ].includes(value.val)) {
1031
1245
  if (!(value.val in mapping)) {
1032
- const result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? value.val : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1246
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1247
+ ? value.val
1248
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1033
1249
  mapping[value.val] = result instanceof Promise ? await result : result;
1034
1250
  revMapping[mapping[value.val]] = value.val;
1035
1251
  }
@@ -1040,24 +1256,50 @@ async function doParse(iter, options = {}) {
1040
1256
  for (const { value, parent } of walkValues(node.val, node)) {
1041
1257
  if (value.typ == EnumToken.DashedIdenTokenType) {
1042
1258
  if (!(value.val in mapping)) {
1043
- const result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? value.val : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1259
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1260
+ ? value.val
1261
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1044
1262
  let val = result instanceof Promise ? await result : result;
1045
- mapping[value.val] = '--' + (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(val, moduleSettings.naming) : val);
1263
+ mapping[value.val] =
1264
+ "--" +
1265
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1266
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1267
+ ? getKeyName(val, moduleSettings.naming)
1268
+ : val);
1046
1269
  revMapping[mapping[value.val]] = value.val;
1047
1270
  }
1048
1271
  value.val = mapping[value.val];
1049
1272
  }
1050
- else if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) && value.val in importedCssVariables) {
1051
- replaceToken(parent, value, importedCssVariables[value.val].val);
1273
+ else if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) &&
1274
+ value.val in importedCssVariables) {
1275
+ replaceNodeOrValue(parent, value, importedCssVariables[value.val].val);
1052
1276
  }
1053
1277
  }
1054
1278
  }
1055
1279
  else if (node.typ == EnumToken.RuleNodeType) {
1056
1280
  if (node.tokens == null) {
1057
- Object.defineProperty(node, 'tokens', {
1281
+ const tokens = parseString(node.sel);
1282
+ matchSelectorSyntax(tokens, [], options);
1283
+ Object.defineProperty(node, "tokens", {
1058
1284
  ...definedPropertySettings,
1059
- value: parseSelector(parseString(node.sel, { location: true }))
1285
+ value: trimArray(tokens),
1060
1286
  });
1287
+ let i;
1288
+ const stack = [];
1289
+ for (i = 0; i < tokens.length; i++) {
1290
+ if (tokensfuncDefMap.has(tokens[i].typ)) {
1291
+ stack.push(tokens[i]);
1292
+ continue;
1293
+ }
1294
+ else if (tokens[i].typ == EnumToken.EndParensTokenType) {
1295
+ const func = stack.at(-1);
1296
+ tokens.splice(i, 1);
1297
+ // @ts-expect-error
1298
+ func.typ = tokensfuncDefMap.get(func.typ);
1299
+ func.chi = tokens.splice(tokens.indexOf(func) + 1, i - 1);
1300
+ stack.pop();
1301
+ }
1302
+ }
1061
1303
  }
1062
1304
  let hasIdOrClass = false;
1063
1305
  for (const { value } of walkValues(node.tokens, node,
@@ -1066,19 +1308,25 @@ async function doParse(iter, options = {}) {
1066
1308
  if (value.typ == EnumToken.PseudoClassTokenType) {
1067
1309
  const val = value.val.toLowerCase();
1068
1310
  switch (val) {
1069
- case ':local':
1070
- case ':global':
1311
+ case ":local":
1312
+ case ":global":
1071
1313
  {
1072
1314
  let index = parent.tokens.indexOf(value);
1073
1315
  parent.tokens.splice(index, 1);
1074
- if (parent.tokens[index]?.typ == EnumToken.WhitespaceTokenType || parent.tokens[index]?.typ == EnumToken.DescendantCombinatorTokenType) {
1316
+ if (parent.tokens[index]?.typ == EnumToken.WhitespaceTokenType ||
1317
+ parent.tokens[index]?.typ ==
1318
+ EnumToken.DescendantCombinatorTokenType) {
1075
1319
  parent.tokens.splice(index, 1);
1076
1320
  }
1077
- if (val == ':global') {
1321
+ if (val == ":global") {
1078
1322
  for (; index < parent.tokens.length; index++) {
1079
- if (parent.tokens[index].typ == EnumToken.CommaTokenType ||
1080
- ([EnumToken.PseudoClassFuncTokenType, EnumToken.PseudoClassTokenType].includes(parent.tokens[index].typ) &&
1081
- [':global', ':local'].includes(parent.tokens[index].val.toLowerCase()))) {
1323
+ if (parent.tokens[index].typ ==
1324
+ EnumToken.CommaTokenType ||
1325
+ ([
1326
+ EnumToken.PseudoClassFuncTokenType,
1327
+ EnumToken.PseudoClassTokenType,
1328
+ ].includes(parent.tokens[index].typ) &&
1329
+ [":global", ":local"].includes(parent.tokens[index].val.toLowerCase()))) {
1082
1330
  break;
1083
1331
  }
1084
1332
  global.add(parent.tokens[index]);
@@ -1090,13 +1338,13 @@ async function doParse(iter, options = {}) {
1090
1338
  }
1091
1339
  else if (value.typ == EnumToken.PseudoClassFuncTokenType) {
1092
1340
  switch (value.val.toLowerCase()) {
1093
- case ':global':
1341
+ case ":global":
1094
1342
  for (const token of value.chi) {
1095
1343
  global.add(token);
1096
1344
  }
1097
1345
  parent.tokens.splice(parent.tokens.indexOf(value), 1, ...value.chi);
1098
1346
  break;
1099
- case ':local':
1347
+ case ":local":
1100
1348
  parent.tokens.splice(parent.tokens.indexOf(value), 1, ...value.chi);
1101
1349
  break;
1102
1350
  }
@@ -1118,61 +1366,78 @@ async function doParse(iter, options = {}) {
1118
1366
  if (value.typ == EnumToken.ClassSelectorTokenType) {
1119
1367
  const val = value.val.slice(1);
1120
1368
  if (!(val in mapping)) {
1121
- const result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? val : moduleSettings.generateScopedName(val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1369
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1370
+ ? val
1371
+ : moduleSettings.generateScopedName(val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1122
1372
  let value = result instanceof Promise ? await result : result;
1123
- mapping[val] = (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(value, moduleSettings.naming) : value);
1373
+ mapping[val] =
1374
+ moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1375
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1376
+ ? getKeyName(value, moduleSettings.naming)
1377
+ : value;
1124
1378
  revMapping[mapping[val]] = val;
1125
1379
  }
1126
- value.val = '.' + mapping[val];
1380
+ value.val = "." + mapping[val];
1127
1381
  }
1128
1382
  }
1129
1383
  }
1130
1384
  if (moduleSettings.scoped & ModuleScopeEnumOptions.Pure) {
1131
1385
  if (!hasIdOrClass) {
1132
- throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${node.loc?.src ?? ''}':${node.loc?.sta?.lin ?? ''}:${node.loc?.sta?.col ?? ''}`);
1386
+ throw new Error(`pure module: No id or class found in selector '${node.sel}' at '${node.loc?.src ?? ""}':${node.loc?.sta?.lin ?? ""}:${node.loc?.sta?.col ?? ""}`);
1133
1387
  }
1134
1388
  }
1135
- node.sel = '';
1389
+ node.sel = "";
1136
1390
  for (const token of node.tokens) {
1137
- node.sel += renderToken(token);
1391
+ node.sel += renderValue(token);
1138
1392
  }
1139
1393
  }
1140
1394
  else if (node.typ == EnumToken.AtRuleNodeType || node.typ == EnumToken.KeyframesAtRuleNodeType) {
1141
1395
  const val = node.nam.toLowerCase();
1142
1396
  if (node.tokens == null) {
1143
- Object.defineProperty(node, 'tokens', {
1397
+ Object.defineProperty(node, "tokens", {
1144
1398
  ...definedPropertySettings,
1145
1399
  // @ts-ignore
1146
- value: parseAtRulePrelude(parseString(node.val), node)
1400
+ value: parseString(node.val),
1147
1401
  });
1148
1402
  }
1149
- if (val == 'property' || val == 'keyframes') {
1150
- const prefix = val == 'property' ? '--' : '';
1403
+ if (val == "property" || val == "keyframes") {
1404
+ const prefix = val == "property" ? "--" : "";
1151
1405
  for (const value of node.tokens) {
1152
- if ((prefix == '--' && value.typ == EnumToken.DashedIdenTokenType) || (prefix == '' && value.typ == EnumToken.IdenTokenType)) {
1406
+ if ((prefix == "--" && value.typ == EnumToken.DashedIdenTokenType) ||
1407
+ (prefix == "" && value.typ == EnumToken.IdenTokenType)) {
1153
1408
  if (!(value.val in mapping)) {
1154
- const result = (moduleSettings.scoped & ModuleScopeEnumOptions.Global) ? value.val : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1409
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1410
+ ? value.val
1411
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1155
1412
  let val = result instanceof Promise ? await result : result;
1156
- mapping[value.val] = prefix + (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly || moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly ? getKeyName(val, moduleSettings.naming) : val);
1413
+ mapping[value.val] =
1414
+ prefix +
1415
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1416
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1417
+ ? getKeyName(val, moduleSettings.naming)
1418
+ : val);
1157
1419
  revMapping[mapping[value.val]] = value.val;
1158
1420
  }
1159
1421
  value.val = mapping[value.val];
1160
1422
  }
1161
1423
  }
1162
- node.val = node.tokens.reduce((a, b) => a + renderToken(b), '');
1424
+ node.val = renderTokens(node.tokens);
1163
1425
  }
1164
1426
  else {
1165
1427
  let isReplaced = false;
1166
1428
  for (const { value, parent } of walkValues(node.tokens, node)) {
1167
- if (EnumToken.MediaQueryConditionTokenType == parent.typ && value != parent.l) {
1168
- if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) && value.val in importedCssVariables) {
1429
+ if (EnumToken.MediaQueryConditionTokenType == parent.typ &&
1430
+ // @ts-expect-error
1431
+ value != parent.l) {
1432
+ if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) &&
1433
+ value.val in importedCssVariables) {
1169
1434
  isReplaced = true;
1170
1435
  parent.r.splice(parent.r.indexOf(value), 1, ...importedCssVariables[value.val].val);
1171
1436
  }
1172
1437
  }
1173
1438
  }
1174
1439
  if (isReplaced) {
1175
- node.val = node.tokens.reduce((a, b) => a + renderToken(b), '');
1440
+ node.val = renderTokens(node.tokens);
1176
1441
  }
1177
1442
  }
1178
1443
  }
@@ -1188,7 +1453,7 @@ async function doParse(iter, options = {}) {
1188
1453
  }
1189
1454
  result.mapping = mapping;
1190
1455
  result.revMapping = revMapping;
1191
- if ((moduleSettings.scoped & ModuleScopeEnumOptions.ICSS) && Object.keys(importMapping).length > 0) {
1456
+ if (moduleSettings.scoped & ModuleScopeEnumOptions.ICSS && Object.keys(importMapping).length > 0) {
1192
1457
  result.importMapping = importMapping;
1193
1458
  }
1194
1459
  endTime = performance.now();
@@ -1196,890 +1461,1096 @@ async function doParse(iter, options = {}) {
1196
1461
  result.stats.total = `${(endTime - startTime).toFixed(2)}ms`;
1197
1462
  }
1198
1463
  if (options.signal != null) {
1199
- options.signal.removeEventListener('abort', reject);
1464
+ options.signal.removeEventListener("abort", reject);
1200
1465
  }
1201
1466
  return result;
1202
1467
  }
1203
- function getLastNode(context) {
1204
- let i = context.chi.length;
1205
- while (i--) {
1206
- if ([EnumToken.CommentTokenType, EnumToken.CDOCOMMTokenType, EnumToken.WhitespaceTokenType].includes(context.chi[i].typ)) {
1468
+ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
1469
+ let i = 0;
1470
+ if (tokens.at(-1)?.typ === EnumToken.EOFTokenType) {
1471
+ tokens.pop();
1472
+ // check parenthesis are balanced
1473
+ let matchCount = 0;
1474
+ let position = tokens.at(-1)?.loc;
1475
+ for (let i = 0; i < tokens.length; i++) {
1476
+ const token = tokens[i];
1477
+ if (token.typ === EnumToken.StartParensTokenType || tokensfuncDefMap.has(token.typ)) {
1478
+ matchCount++;
1479
+ }
1480
+ else if (token.typ === EnumToken.EndParensTokenType) {
1481
+ matchCount--;
1482
+ }
1483
+ }
1484
+ if (matchCount > 0) {
1485
+ let k = tokens.length;
1486
+ while (k-- > 0 &&
1487
+ (tokens[k].typ === EnumToken.WhitespaceTokenType || tokens[k].typ === EnumToken.CommentTokenType))
1488
+ ;
1489
+ if (tokens[k]?.typ == EnumToken.SemiColonTokenType) {
1490
+ matchCount = 0;
1491
+ }
1492
+ while (matchCount > 0) {
1493
+ position = {
1494
+ ...position,
1495
+ sta: { ...position.sta, ind: position.sta.ind + 1, col: position.sta.col + 1 },
1496
+ end: { ...position.end, ind: position.end.ind + 1, col: position.end.col + 1 },
1497
+ };
1498
+ tokens.push(Object.defineProperty({
1499
+ typ: EnumToken.EndParensTokenType,
1500
+ loc: tokens.at(-1)?.loc,
1501
+ }, "loc", {
1502
+ ...definedPropertySettings,
1503
+ value: { ...position },
1504
+ }));
1505
+ matchCount--;
1506
+ }
1507
+ }
1508
+ }
1509
+ for (; i < tokens.length; i++) {
1510
+ if (tokens[i].typ === EnumToken.CDOCOMMTokenType && context.typ !== EnumToken.StyleSheetNodeType) {
1511
+ errors.push({
1512
+ action: "drop",
1513
+ message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`,
1514
+ node: tokens[i],
1515
+ location: tokens[i].loc,
1516
+ });
1517
+ tokens[i].typ = EnumToken.InvalidCommentTokenType;
1207
1518
  continue;
1208
1519
  }
1209
- return context.chi[i];
1520
+ if (tokens[i].typ === EnumToken.CommentTokenType ||
1521
+ tokens[i].typ === EnumToken.CDOCOMMTokenType ||
1522
+ tokens[i].typ === EnumToken.WhitespaceTokenType) {
1523
+ continue;
1524
+ }
1525
+ break;
1210
1526
  }
1211
- return null;
1212
- }
1213
- function parseNode(results, context, options, errors, src, map, rawTokens, stats) {
1214
- let tokens = [];
1215
- for (const t of results) {
1216
- const node = getTokenType(t.token, t.hint);
1217
- map.set(node, { sta: t.sta, end: t.end, src });
1218
- tokens.push(node);
1527
+ if (i > 0) {
1528
+ context.chi.push(...tokens.splice(0, i).filter((n) => n.typ !== EnumToken.WhitespaceTokenType));
1529
+ i = 0;
1219
1530
  }
1220
- let i;
1221
- let loc;
1222
- for (i = 0; i < tokens.length; i++) {
1531
+ for (; i < tokens.length; i++) {
1223
1532
  if (tokens[i].typ == EnumToken.CommentTokenType || tokens[i].typ == EnumToken.CDOCOMMTokenType) {
1224
- const location = map.get(tokens[i]);
1533
+ const location = tokens[i]?.loc;
1225
1534
  if (tokens[i].typ == EnumToken.CDOCOMMTokenType && context.typ != EnumToken.StyleSheetNodeType) {
1226
1535
  errors.push({
1227
- action: 'drop',
1536
+ action: "drop",
1228
1537
  message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`,
1229
1538
  node: tokens[i],
1230
- location
1539
+ location,
1231
1540
  });
1541
+ tokens[i].typ = EnumToken.InvalidCommentTokenType;
1232
1542
  continue;
1233
1543
  }
1234
- loc = location;
1235
1544
  context.chi.push(tokens[i]);
1236
1545
  stats.nodesCount++;
1237
- Object.defineProperty(tokens[i], 'loc', {
1238
- ...definedPropertySettings,
1239
- value: loc,
1240
- enumerable: options.sourcemap !== false
1241
- });
1242
1546
  }
1243
1547
  else if (tokens[i].typ != EnumToken.WhitespaceTokenType) {
1244
1548
  break;
1245
1549
  }
1246
1550
  }
1247
- tokens = tokens.slice(i);
1248
1551
  if (tokens.length == 0) {
1249
1552
  return null;
1250
1553
  }
1251
1554
  let delim = tokens.at(-1);
1252
- if (delim.typ == EnumToken.SemiColonTokenType || delim.typ == EnumToken.BlockStartTokenType || delim.typ == EnumToken.BlockEndTokenType) {
1253
- tokens.pop();
1254
- }
1255
- while ([EnumToken.WhitespaceTokenType, EnumToken.BadStringTokenType, EnumToken.BadCommentTokenType].includes(tokens.at(-1)?.typ)) {
1555
+ if (delim.typ == EnumToken.SemiColonTokenType ||
1556
+ delim.typ == EnumToken.BlockStartTokenType ||
1557
+ delim.typ == EnumToken.BlockEndTokenType) {
1256
1558
  tokens.pop();
1257
1559
  }
1258
1560
  if (tokens.length == 0) {
1259
1561
  return null;
1260
1562
  }
1261
1563
  if (tokens[0]?.typ == EnumToken.AtRuleTokenType) {
1262
- const atRule = tokens.shift();
1263
- const location = map.get(atRule);
1264
- // @ts-ignore
1265
- while ([EnumToken.WhitespaceTokenType].includes(tokens[0]?.typ)) {
1266
- tokens.shift();
1564
+ let nestedRule = false;
1565
+ let parent = context;
1566
+ let node;
1567
+ while (parent != null) {
1568
+ if (parent.typ == EnumToken.RuleNodeType) {
1569
+ nestedRule = true;
1570
+ break;
1571
+ }
1572
+ parent = parent.parent;
1267
1573
  }
1268
- rawTokens.shift();
1269
- if (atRule.val == 'import') {
1270
- // only @charset and @layer are accepted before @import
1271
- if (context.chi.length > 0) {
1272
- let i = context.chi.length;
1273
- while (i--) {
1274
- // @ts-ignore
1275
- const type = context.chi[i].typ;
1276
- if (type == EnumToken.CommentNodeType) {
1277
- continue;
1278
- }
1279
- if (type != EnumToken.AtRuleNodeType) {
1280
- if (!(type == EnumToken.InvalidAtRuleTokenType &&
1281
- ['charset', 'layer', 'import'].includes(context.chi[i].nam))) {
1282
- errors.push({
1283
- action: 'drop',
1284
- message: 'invalid @import',
1285
- location,
1286
- // @ts-ignore
1287
- rawTokens: [atRule, ...tokens]
1288
- });
1289
- return null;
1290
- }
1291
- }
1292
- const name = context.chi[i].nam;
1293
- if (name != 'charset' && name != 'import' && name != 'layer') {
1294
- errors.push({ action: 'drop', message: 'invalid @import', location });
1295
- return null;
1296
- }
1297
- break;
1298
- }
1574
+ node = parseAtRule(tokens, context, { ...options, nestedRule }, errors, delim.typ == EnumToken.BlockStartTokenType);
1575
+ if (node == null) {
1576
+ return null;
1577
+ }
1578
+ if (node.state == EnumAstNodeStatus.Invalid ||
1579
+ node.state == EnumAstNodeStatus.Disallowed ||
1580
+ node.state == EnumAstNodeStatus.Unknown ||
1581
+ node.state == EnumAstNodeStatus.Unparsed ||
1582
+ node.state == EnumAstNodeStatus.Malformed) {
1583
+ invalidNodes.push(node);
1584
+ }
1585
+ stats.nodesCount++;
1586
+ context.chi.push(node);
1587
+ // @ts-expect-error
1588
+ return Object.defineProperty(node, "parent", { ...definedPropertySettings, value: context });
1589
+ }
1590
+ else {
1591
+ stats.nodesCount++;
1592
+ // rule
1593
+ if (delim.typ == EnumToken.BlockStartTokenType) {
1594
+ const node = parseSelector(tokens, context, options, errors);
1595
+ context.chi.push(node);
1596
+ Object.defineProperty(node, "parent", { ...definedPropertySettings, value: context });
1597
+ if (node.state == EnumAstNodeStatus.Invalid ||
1598
+ node.state == EnumAstNodeStatus.Disallowed ||
1599
+ node.state == EnumAstNodeStatus.Unknown ||
1600
+ node.state == EnumAstNodeStatus.Unparsed ||
1601
+ node.state == EnumAstNodeStatus.Malformed) {
1602
+ invalidNodes.push(node);
1299
1603
  }
1300
- // @ts-ignore
1301
- if (tokens[0]?.typ != EnumToken.StringTokenType && tokens[0]?.typ != EnumToken.UrlFunctionTokenType) {
1604
+ return node;
1605
+ }
1606
+ else {
1607
+ const node = parseDeclaration(tokens, context, options, errors);
1608
+ Object.defineProperty(node, "parent", { ...definedPropertySettings, value: context });
1609
+ if (context.typ === EnumToken.StyleSheetNodeType && node.typ === EnumToken.DeclarationNodeType) {
1610
+ node.state = EnumAstNodeStatus.Invalid;
1302
1611
  errors.push({
1303
- action: 'drop',
1304
- message: 'doParse: invalid @import',
1305
- location
1612
+ message: "<declaration> not allowed in <stylesheet>",
1613
+ action: "drop",
1614
+ node,
1615
+ location: node.loc,
1306
1616
  });
1307
- return null;
1308
1617
  }
1309
- // @ts-ignore
1310
- if (tokens[0].typ == EnumToken.UrlFunctionTokenType && tokens[1]?.typ != EnumToken.UrlTokenTokenType && tokens[1]?.typ != EnumToken.StringTokenType) {
1618
+ else if (options.lenient || node.typ === EnumToken.DeclarationNodeType) {
1619
+ context.chi.push(node);
1620
+ }
1621
+ if (node.state == EnumAstNodeStatus.Invalid ||
1622
+ node.state == EnumAstNodeStatus.Disallowed ||
1623
+ node.state == EnumAstNodeStatus.Unknown ||
1624
+ node.state == EnumAstNodeStatus.Unparsed ||
1625
+ node.state == EnumAstNodeStatus.Malformed) {
1626
+ invalidNodes.push(node);
1627
+ }
1628
+ }
1629
+ }
1630
+ return null;
1631
+ }
1632
+ /**
1633
+ * @param options
1634
+ * @param errors
1635
+ * @param parseAsBlock
1636
+ */
1637
+ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1638
+ let success = true;
1639
+ let atRuleName = stream[0].nam;
1640
+ if (atRuleName.startsWith("-")) {
1641
+ atRuleName = atRuleName.replace(/^-[a-z]+-/, "").toLowerCase();
1642
+ }
1643
+ const atRule = stream.shift();
1644
+ const syntaxRules = getSyntaxRule(ValidationSyntaxGroupEnum.AtRules, "@" + atRule.nam);
1645
+ const syntax = syntaxRules?.getPreludeRules()?.slice?.(1);
1646
+ const blockAllowed = syntaxRules?.getBlockRules() != null;
1647
+ if (syntaxRules == null) {
1648
+ // if (!options.lenient) {
1649
+ errors.push({
1650
+ action: "drop",
1651
+ node: atRule,
1652
+ location: atRule.loc,
1653
+ message: "unknown at-rule",
1654
+ });
1655
+ const result = matchGenericSyntax(stream);
1656
+ // @ts-expect-error
1657
+ return Object.defineProperties(Object.assign(atRule, {
1658
+ typ: EnumToken.AtRuleNodeType,
1659
+ val: renderTokens(trimArray(stream), options),
1660
+ ...(parseAsBlock ? { chi: [] } : {}),
1661
+ }), {
1662
+ state: {
1663
+ ...definedPropertySettings,
1664
+ value: result.success ? EnumAstNodeStatus.Unknown : EnumAstNodeStatus.Invalid,
1665
+ },
1666
+ errors: {
1667
+ ...definedPropertySettings,
1668
+ value: result.success ? [errors[errors.length - 1]] : [errors[errors.length - 1], ...result.errors],
1669
+ },
1670
+ });
1671
+ // }
1672
+ }
1673
+ else if (context.typ === EnumToken.AtRuleNodeType &&
1674
+ "page" === context.nam &&
1675
+ pageMarginBoxType.has(atRuleName.toLowerCase())) {
1676
+ if (parseAsBlock === false) {
1677
+ errors.push({
1678
+ action: "drop",
1679
+ node: atRule,
1680
+ location: atRule.loc,
1681
+ message: parseAsBlock ? "at-rule block not supported" : "at-rule block is required",
1682
+ });
1683
+ // @ts-expect-error
1684
+ return Object.defineProperties(Object.assign(atRule, {
1685
+ typ: EnumToken.AtRuleNodeType,
1686
+ val: renderTokens(trimArray(stream), options),
1687
+ ...(parseAsBlock ? { chi: [] } : {}),
1688
+ }), {
1689
+ state: {
1690
+ ...definedPropertySettings,
1691
+ value: EnumAstNodeStatus.Invalid,
1692
+ },
1693
+ errors: {
1694
+ ...definedPropertySettings,
1695
+ value: [errors[errors.length - 1]],
1696
+ },
1697
+ });
1698
+ }
1699
+ const token = stream.find((t) => t.typ != EnumToken.WhitespaceTokenType && t.typ === EnumToken.CommentTokenType) ?? null;
1700
+ if (token != null) {
1701
+ errors.push({
1702
+ action: "drop",
1703
+ node: token,
1704
+ location: token.loc,
1705
+ message: `unexpected token ${EnumToken[token.typ]} at ${token.loc.src}:${token.loc.sta.lin}:${token.loc.sta.col}`,
1706
+ });
1707
+ // @ts-expect-error
1708
+ return Object.defineProperties(Object.assign(atRule, {
1709
+ typ: EnumToken.AtRuleNodeType,
1710
+ val: renderTokens(trimArray(stream), options),
1711
+ ...(parseAsBlock ? { chi: [] } : {}),
1712
+ }), {
1713
+ state: {
1714
+ ...definedPropertySettings,
1715
+ value: EnumAstNodeStatus.Invalid,
1716
+ },
1717
+ errors: {
1718
+ ...definedPropertySettings,
1719
+ value: [errors[errors.length - 1]],
1720
+ },
1721
+ });
1722
+ }
1723
+ }
1724
+ if (parseAsBlock === null) {
1725
+ parseAsBlock = blockAllowed;
1726
+ }
1727
+ if (syntax != null && atRule.nam !== "layer" && parseAsBlock !== blockAllowed) {
1728
+ success = false;
1729
+ errors.push({
1730
+ action: "drop",
1731
+ node: atRule,
1732
+ location: atRule.loc,
1733
+ message: parseAsBlock ? "at-rule block not supported" : "at-rule block is required",
1734
+ });
1735
+ // @ts-expect-error
1736
+ return Object.defineProperties(Object.assign(atRule, {
1737
+ typ: EnumToken.AtRuleNodeType,
1738
+ val: renderTokens(trimArray(stream), options),
1739
+ ...(parseAsBlock ? { chi: [] } : {}),
1740
+ }), {
1741
+ state: {
1742
+ ...definedPropertySettings,
1743
+ value: EnumAstNodeStatus.Invalid,
1744
+ },
1745
+ errors: {
1746
+ ...definedPropertySettings,
1747
+ value: [errors[errors.length - 1]],
1748
+ },
1749
+ });
1750
+ }
1751
+ switch (atRuleName) {
1752
+ case "charset": {
1753
+ let success = true;
1754
+ if (stream.length === 0 ||
1755
+ stream[0].typ !== EnumToken.WhitespaceTokenType ||
1756
+ stream[0].val !== " ") {
1757
+ success = false;
1758
+ errors.push({
1759
+ action: "drop",
1760
+ node: stream[0] ?? atRule,
1761
+ location: (stream[0] ?? atRule).loc,
1762
+ message: "expecting <space>",
1763
+ });
1764
+ }
1765
+ else if (stream[1].typ !== EnumToken.StringTokenType) {
1766
+ success = false;
1767
+ errors.push({
1768
+ action: "drop",
1769
+ node: stream[1] ?? atRule,
1770
+ location: (stream[1] ?? atRule).loc,
1771
+ message: "expecting <string>",
1772
+ });
1773
+ }
1774
+ if (success && stream[1].val.charCodeAt(0) !== 0x22) {
1775
+ success = false;
1311
1776
  errors.push({
1312
- action: 'drop',
1313
- message: 'doParse: invalid @import',
1314
- location
1777
+ action: "drop",
1778
+ node: stream[1] ?? atRule,
1779
+ location: (stream[1] ?? atRule).loc,
1780
+ message: "expecting double-quoted string",
1781
+ });
1782
+ }
1783
+ if (!success) {
1784
+ // @ts-expect-error
1785
+ return Object.defineProperties(Object.assign(atRule, {
1786
+ typ: success ? EnumToken.AtRuleNodeType : EnumToken.InvalidRuleNodeType,
1787
+ val: renderTokens(trimArray(stream), options),
1788
+ }), {
1789
+ state: {
1790
+ ...definedPropertySettings,
1791
+ value: EnumAstNodeStatus.Invalid,
1792
+ },
1793
+ errors: {
1794
+ ...definedPropertySettings,
1795
+ value: [errors[errors.length - 1]],
1796
+ },
1797
+ loc: {
1798
+ ...definedPropertySettings,
1799
+ value: { ...atRule.loc, end: (stream.at(-1) ?? atRule).loc.end },
1800
+ },
1801
+ tokens: { ...definedPropertySettings, value: stream },
1315
1802
  });
1803
+ }
1804
+ if (options.removeCharset) {
1316
1805
  return null;
1317
1806
  }
1807
+ // @ts-expect-error
1808
+ return Object.defineProperties(Object.assign(atRule, {
1809
+ typ: success ? EnumToken.AtRuleNodeType : EnumToken.InvalidRuleNodeType,
1810
+ val: renderTokens(trimArray(stream), options),
1811
+ }), {
1812
+ state: {
1813
+ ...definedPropertySettings,
1814
+ value: EnumAstNodeStatus.Validated,
1815
+ },
1816
+ errors: {
1817
+ ...definedPropertySettings,
1818
+ value: [],
1819
+ },
1820
+ loc: {
1821
+ ...definedPropertySettings,
1822
+ value: { ...atRule.loc, end: (stream.at(-1) ?? atRule).loc.end },
1823
+ },
1824
+ tokens: { ...definedPropertySettings, value: stream },
1825
+ });
1318
1826
  }
1319
- if (atRule.val == 'import') {
1320
- // @ts-ignore
1321
- if (tokens[0].typ == EnumToken.UrlFunctionTokenType) {
1322
- if (tokens[1].typ == EnumToken.UrlTokenTokenType || tokens[1].typ == EnumToken.StringTokenType) {
1323
- tokens.shift();
1324
- if (tokens[0]?.typ == EnumToken.UrlTokenTokenType) {
1325
- // @ts-ignore
1326
- tokens[0].typ = EnumToken.StringTokenType;
1327
- // @ts-ignore
1328
- tokens[0].val = `"${tokens[0].val}"`;
1329
- }
1330
- // @ts-ignore
1331
- while (tokens[1]?.typ == EnumToken.WhitespaceTokenType || tokens[1]?.typ == EnumToken.CommentTokenType) {
1332
- tokens.splice(1, 1);
1827
+ case "font-feature-values": {
1828
+ const result = parseAtRuleFontFeatureValues(stream, atRule, options);
1829
+ if (result.errors.length > 0) {
1830
+ errors.push(...result.errors);
1831
+ }
1832
+ // @ts-expect-error
1833
+ return Object.defineProperties(Object.assign(atRule, {
1834
+ typ: EnumToken.AtRuleNodeType,
1835
+ val: renderTokens(trimWhiteSpaceTokens(stream), options),
1836
+ chi: [],
1837
+ }), {
1838
+ state: {
1839
+ ...definedPropertySettings,
1840
+ value: result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
1841
+ },
1842
+ errors: {
1843
+ ...definedPropertySettings,
1844
+ value: result.success ? [] : result.errors,
1845
+ },
1846
+ loc: {
1847
+ ...definedPropertySettings,
1848
+ value: { ...atRule.loc, end: (stream.at(-1) ?? atRule).loc.end },
1849
+ },
1850
+ tokens: { ...definedPropertySettings, value: stream },
1851
+ });
1852
+ }
1853
+ case "stylistic":
1854
+ case "historical-forms":
1855
+ case "character-variant":
1856
+ case "swash":
1857
+ case "ornaments":
1858
+ case "annotation": {
1859
+ let success = context.typ === EnumToken.AtRuleNodeType && "font-feature-values" === context.nam;
1860
+ if (!success) {
1861
+ errors.push({
1862
+ action: "drop",
1863
+ node: atRule,
1864
+ location: atRule.loc,
1865
+ message: `unexpected at-rule ${atRule.nam}`,
1866
+ });
1867
+ }
1868
+ if (success) {
1869
+ for (const token of stream) {
1870
+ if (token.typ !== EnumToken.CommentTokenType && token.typ !== EnumToken.WhitespaceTokenType) {
1871
+ success = false;
1872
+ errors.push({
1873
+ action: "drop",
1874
+ node: token,
1875
+ location: token.loc,
1876
+ message: `unexpected token ${EnumToken[token.typ]} at ${token.loc.src}:${token.loc.sta.lin}:${token.loc.sta.col}`,
1877
+ });
1333
1878
  }
1334
- // @ts-ignore
1335
- if (tokens[1]?.typ == EnumToken.EndParensTokenType) {
1336
- tokens.splice(1, 1);
1879
+ }
1880
+ }
1881
+ // @ts-expect-error
1882
+ return Object.defineProperties(Object.assign(atRule, {
1883
+ typ: EnumToken.AtRuleNodeType,
1884
+ val: renderTokens(trimWhiteSpaceTokens(stream), options),
1885
+ chi: [],
1886
+ }), {
1887
+ state: {
1888
+ ...definedPropertySettings,
1889
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
1890
+ },
1891
+ errors: {
1892
+ ...definedPropertySettings,
1893
+ value: [errors[errors.length - 1]],
1894
+ },
1895
+ loc: {
1896
+ ...definedPropertySettings,
1897
+ value: { ...atRule.loc, end: (stream.at(-1) ?? atRule).loc.end },
1898
+ },
1899
+ tokens: { ...definedPropertySettings, value: stream },
1900
+ });
1901
+ }
1902
+ case "container": {
1903
+ const result = parseAtRuleContainerQueryList(stream, atRule, options);
1904
+ if (result.errors.length > 0) {
1905
+ errors.push(...result.errors);
1906
+ }
1907
+ // @ts-expect-error
1908
+ return Object.defineProperties(Object.assign(atRule, {
1909
+ typ: EnumToken.AtRuleNodeType,
1910
+ val: renderTokens(trimWhiteSpaceTokens(stream), options),
1911
+ chi: [],
1912
+ }), {
1913
+ state: {
1914
+ ...definedPropertySettings,
1915
+ value: result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
1916
+ },
1917
+ errors: {
1918
+ ...definedPropertySettings,
1919
+ value: result.success ? [] : result.errors,
1920
+ },
1921
+ loc: {
1922
+ ...definedPropertySettings,
1923
+ value: { ...atRule.loc, end: (stream.at(-1) ?? atRule).loc.end },
1924
+ },
1925
+ tokens: { ...definedPropertySettings, value: stream },
1926
+ });
1927
+ }
1928
+ case "custom-media": {
1929
+ const tokens = trimArray(stream.slice(1));
1930
+ const result = matchAllSyntaxes(syntax, createValidationContext(tokens), options);
1931
+ if (result.errors.length > 0) {
1932
+ errors.push(...result.errors);
1933
+ }
1934
+ // @ts-expect-error
1935
+ options = { ...options, convertColor: false };
1936
+ // @ts-expect-error
1937
+ return Object.defineProperties(Object.assign(atRule, {
1938
+ typ: EnumToken.AtRuleNodeType,
1939
+ val: renderTokens(trimWhiteSpaceTokens(tokens), options),
1940
+ }), {
1941
+ state: {
1942
+ ...definedPropertySettings,
1943
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.ValidationFailed,
1944
+ },
1945
+ errors: {
1946
+ ...definedPropertySettings,
1947
+ value: result.success ? [] : result.errors,
1948
+ },
1949
+ loc: {
1950
+ ...definedPropertySettings,
1951
+ value: { ...atRule.loc, end: (tokens.at(-1) ?? atRule).loc.end },
1952
+ },
1953
+ tokens: { ...definedPropertySettings, value: tokens },
1954
+ });
1955
+ }
1956
+ case "keyframes": {
1957
+ const tokens = trimArray(stream.slice(1));
1958
+ const filtered = stream.filter((t) => t.typ !== EnumToken.WhitespaceTokenType && t.typ !== EnumToken.CommentTokenType);
1959
+ if (filtered.length != 1 ||
1960
+ (filtered[0].typ !== EnumToken.IdenTokenType &&
1961
+ filtered[0].typ !== EnumToken.StringTokenType &&
1962
+ filtered[0].typ !== EnumToken.DashedIdenTokenType)) {
1963
+ errors.push({
1964
+ action: "drop",
1965
+ node: atRule,
1966
+ location: atRule.loc,
1967
+ message: `expected <keyframe-name> at ${atRule.loc.src}:${atRule.loc.sta.lin}:${atRule.loc.sta.col}`,
1968
+ });
1969
+ success = false;
1970
+ }
1971
+ // @ts-expect-error
1972
+ options = { ...options, convertColor: false };
1973
+ // @ts-expect-error
1974
+ return Object.defineProperties(Object.assign(atRule, {
1975
+ typ: EnumToken.KeyframesAtRuleNodeType,
1976
+ val: renderTokens(tokens, options),
1977
+ chi: [],
1978
+ }), {
1979
+ state: {
1980
+ ...definedPropertySettings,
1981
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
1982
+ },
1983
+ errors: {
1984
+ ...definedPropertySettings,
1985
+ value: success ? [] : errors[errors.length - 1],
1986
+ },
1987
+ loc: {
1988
+ ...definedPropertySettings,
1989
+ value: { ...atRule.loc, end: (tokens.at(-1) ?? atRule).loc.end },
1990
+ },
1991
+ tokens: { ...definedPropertySettings, value: tokens },
1992
+ });
1993
+ }
1994
+ case "namespace": {
1995
+ const result = matchAllSyntaxes(syntax, createValidationContext(stream), options);
1996
+ if (!result.success) {
1997
+ errors.push(...result.errors);
1998
+ }
1999
+ // else {
2000
+ // parseUrlToken(stream);
2001
+ // }
2002
+ const valid = blockAllowed === parseAsBlock && result.success;
2003
+ if (valid) {
2004
+ let start = 0;
2005
+ let end = -1;
2006
+ let hasString = false;
2007
+ for (start = 0; start < stream.length; start++) {
2008
+ if (stream[start].typ == EnumToken.UrlFunctionTokenDefType) {
2009
+ start++;
2010
+ for (end = start; end < stream.length; end++) {
2011
+ if (stream[end].typ == EnumToken.EndParensTokenType) {
2012
+ break;
2013
+ }
2014
+ if (stream[end].typ === EnumToken.StringTokenType) {
2015
+ hasString = true;
2016
+ }
2017
+ }
2018
+ break;
1337
2019
  }
1338
2020
  }
2021
+ // replace url(string) -> string
2022
+ if (hasString) {
2023
+ stream.splice(start - 1, end - start + 2, ...stream.slice(start, end));
2024
+ }
2025
+ }
2026
+ // @ts-expect-error
2027
+ options = { ...options, convertColor: false };
2028
+ // @ts-expect-error
2029
+ return Object.defineProperties(Object.assign(atRule, {
2030
+ typ: EnumToken.AtRuleNodeType,
2031
+ val: trimArray(stream).reduce((acc, t, index) => acc +
2032
+ (t.typ === EnumToken.CommentTokenType ||
2033
+ (t.typ === EnumToken.WhitespaceTokenType &&
2034
+ stream[index + 1]?.typ === EnumToken.CommentTokenType &&
2035
+ (stream.length < index + 3 || stream[index + 2]?.typ === EnumToken.WhitespaceTokenType))
2036
+ ? ""
2037
+ : renderValue(t, options)), ""),
2038
+ ...(parseAsBlock ? { chi: [] } : {}),
2039
+ }), {
2040
+ state: {
2041
+ ...definedPropertySettings,
2042
+ value: valid ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2043
+ },
2044
+ errors: {
2045
+ ...definedPropertySettings,
2046
+ value: valid ? [] : result.errors,
2047
+ },
2048
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2049
+ loc: {
2050
+ ...definedPropertySettings,
2051
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2052
+ },
2053
+ });
2054
+ }
2055
+ case "import": {
2056
+ const result = matchAtRuleImportSyntax(atRule, stream, context, options);
2057
+ if (result.errors.length > 0) {
2058
+ errors.push(...result.errors);
1339
2059
  }
2060
+ else {
2061
+ if (stream[0]?.typ == EnumToken.UrlFunctionTokenType &&
2062
+ stream[0].chi.some((t) => t.typ == EnumToken.StringTokenType || t.typ == EnumToken.UrlTokenTokenType)) {
2063
+ stream.splice(0, 1, ...stream[0].chi);
2064
+ }
2065
+ }
2066
+ // @ts-expect-error
2067
+ return Object.defineProperties(Object.assign(atRule, {
2068
+ typ: EnumToken.AtRuleNodeType,
2069
+ val: stream.reduce((acc, t, index) => acc +
2070
+ (t.typ === EnumToken.CommentTokenType ||
2071
+ (t.typ === EnumToken.WhitespaceTokenType &&
2072
+ stream[index + 1]?.typ === EnumToken.CommentTokenType &&
2073
+ (stream.length < index + 3 || stream[index + 2]?.typ === EnumToken.WhitespaceTokenType))
2074
+ ? ""
2075
+ : renderValue(t, options)), ""),
2076
+ }), {
2077
+ state: {
2078
+ ...definedPropertySettings,
2079
+ value: result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2080
+ },
2081
+ errors: {
2082
+ ...definedPropertySettings,
2083
+ value: result.success ? [] : result.errors,
2084
+ },
2085
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2086
+ loc: {
2087
+ ...definedPropertySettings,
2088
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2089
+ },
2090
+ });
1340
2091
  }
1341
- // https://www.w3.org/TR/css-nesting-1/#conditionals
1342
- // allowed nesting at-rules
1343
- // there must be a top level rule in the stack
1344
- if (atRule.val == 'charset') {
1345
- let spaces = 0;
1346
- // https://developer.mozilla.org/en-US/docs/Web/CSS/@charset
1347
- for (let k = 0; k < rawTokens.length; k++) {
1348
- if (rawTokens[k].hint == EnumToken.WhitespaceTokenType) {
1349
- spaces += rawTokens[k].len;
1350
- continue;
2092
+ case "supports":
2093
+ case "when":
2094
+ case "else": {
2095
+ trimWhiteSpaceTokens(stream);
2096
+ const result = atRuleName === "supports"
2097
+ ? parseAtRuleSupportSyntax(stream, atRule, options)
2098
+ : matchAtRuleWhenElseSyntax(stream, atRule, options);
2099
+ if (result.errors.length > 0) {
2100
+ errors.push(...result.errors);
2101
+ }
2102
+ let success = result.success;
2103
+ if (atRule.nam === "else") {
2104
+ const siblings = context.chi;
2105
+ let sibling = null;
2106
+ let l = siblings.length;
2107
+ while (l--) {
2108
+ if (siblings[l].typ === EnumToken.WhitespaceTokenType ||
2109
+ siblings[l].typ === EnumToken.CommentTokenType ||
2110
+ siblings[l].typ === EnumToken.CDOCOMMTokenType) {
2111
+ continue;
2112
+ }
2113
+ sibling = siblings[l];
2114
+ break;
1351
2115
  }
1352
- if (rawTokens[k].hint == EnumToken.CommentTokenType) {
1353
- continue;
2116
+ let missingWhen = false;
2117
+ let definedAfterLastElse = false;
2118
+ if (sibling == null || sibling.typ !== EnumToken.AtRuleNodeType) {
2119
+ missingWhen = true;
1354
2120
  }
1355
- if (rawTokens[k].hint == EnumToken.CDOCOMMTokenType) {
1356
- continue;
2121
+ else if (sibling.nam !== "when") {
2122
+ if (sibling.nam !== "else") {
2123
+ missingWhen = true;
2124
+ }
2125
+ else if (sibling.val === "") {
2126
+ definedAfterLastElse = true;
2127
+ }
1357
2128
  }
1358
- if (spaces > 1) {
2129
+ if (missingWhen) {
2130
+ success = false;
1359
2131
  errors.push({
1360
- action: 'drop',
1361
- message: '@charset must have only one space',
1362
- // @ts-ignore
1363
- location, rawTokens: [atRule, ...tokens]
2132
+ action: "drop",
2133
+ node: atRule,
2134
+ location: atRule.loc,
2135
+ message: "at-rule @when is required before @else block",
1364
2136
  });
1365
- return null;
1366
2137
  }
1367
- if (rawTokens[k].hint != EnumToken.StringTokenType || rawTokens[k].token[0] != '"') {
2138
+ else if (definedAfterLastElse) {
2139
+ success = false;
1368
2140
  errors.push({
1369
- action: 'drop',
1370
- message: '@charset expects a "<charset>"',
1371
- location
2141
+ action: "drop",
2142
+ node: atRule,
2143
+ location: atRule.loc,
2144
+ message: "at-rule @else block is defined after last @else block",
1372
2145
  });
1373
- return null;
1374
2146
  }
1375
- break;
1376
- }
1377
- if (options.removeCharset) {
1378
- return null;
1379
2147
  }
2148
+ // @ts-expect-error
2149
+ options = { ...options, minify: false, convertColor: false };
2150
+ // @ts-expect-error
2151
+ return Object.defineProperties(Object.assign(atRule, {
2152
+ typ: EnumToken.AtRuleNodeType,
2153
+ val: renderTokens(stream, options),
2154
+ chi: [],
2155
+ }), {
2156
+ state: {
2157
+ ...definedPropertySettings,
2158
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2159
+ },
2160
+ errors: {
2161
+ ...definedPropertySettings,
2162
+ value: result.success ? [] : [errors[errors.length - 1]].concat(result.errors),
2163
+ },
2164
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2165
+ loc: {
2166
+ ...definedPropertySettings,
2167
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2168
+ },
2169
+ });
1380
2170
  }
1381
- const t = parseAtRulePrelude(parseTokens(tokens, { minify: options.minify }), atRule);
1382
- const raw = [];
1383
- for (const curr of t) {
1384
- raw.push(renderToken(curr, { removeComments: true, convertColor: false }));
1385
- }
1386
- const nam = renderToken(atRule, { removeComments: true });
1387
- // @ts-ignore
1388
- const node = {
1389
- typ: /^(-[a-z]+-)?keyframes$/.test(nam) ? EnumToken.KeyframesAtRuleNodeType : EnumToken.AtRuleNodeType,
1390
- nam,
1391
- val: raw.join('')
1392
- };
1393
- Object.defineProperties(node, {
1394
- tokens: { ...definedPropertySettings, enumerable: false, value: t.slice() },
1395
- raw: { ...definedPropertySettings, value: raw }
1396
- });
1397
- if (delim.typ == EnumToken.BlockStartTokenType) {
1398
- node.chi = [];
2171
+ case "media": {
2172
+ options = { ...options, parseColor: false };
2173
+ const result = parseMediaqueryList(stream, options);
2174
+ if (result.errors.length > 0) {
2175
+ errors.push(...result.errors);
2176
+ }
2177
+ // @ts-expect-error
2178
+ return Object.defineProperties(Object.assign(atRule, {
2179
+ typ: EnumToken.AtRuleNodeType,
2180
+ val: renderTokens(stream, options),
2181
+ chi: [],
2182
+ }), {
2183
+ state: {
2184
+ ...definedPropertySettings,
2185
+ value: result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2186
+ },
2187
+ errors: {
2188
+ ...definedPropertySettings,
2189
+ value: result.success ? [] : result.errors,
2190
+ },
2191
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2192
+ loc: {
2193
+ ...definedPropertySettings,
2194
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2195
+ },
2196
+ });
1399
2197
  }
1400
- loc = map.get(atRule);
1401
- Object.defineProperty(node, 'loc', {
1402
- ...definedPropertySettings,
1403
- value: loc,
1404
- enumerable: options.sourcemap !== false
1405
- });
1406
- node.loc.end = { ...map.get(delim).end };
1407
- let isValid = true;
1408
- if (node.nam == 'else') {
1409
- const prev = getLastNode(context);
1410
- if (prev != null && prev.typ == EnumToken.AtRuleNodeType && ['when', 'else'].includes(prev.nam)) {
1411
- if (prev.nam == 'else') {
1412
- isValid = Array.isArray(prev.tokens) && prev.tokens.length > 0;
1413
- }
2198
+ case "scope": {
2199
+ let context = createValidationContext(trimArray(stream));
2200
+ let success = true;
2201
+ // @ts-ignore
2202
+ let range = context.peekRange((t) => t.typ === EnumToken.EndParensTokenType);
2203
+ if (range[0]?.typ !== EnumToken.StartParensTokenType) {
2204
+ errors.push({
2205
+ action: "drop",
2206
+ node: range[0] ?? atRule,
2207
+ location: (range[0] ?? atRule).loc,
2208
+ message: "expected '(' at start of @scope block",
2209
+ });
2210
+ success = false;
1414
2211
  }
1415
- else {
1416
- isValid = false;
2212
+ else if (range.at(-1)?.typ !== EnumToken.EndParensTokenType) {
2213
+ errors.push({
2214
+ action: "drop",
2215
+ node: range.at(-1) ?? atRule,
2216
+ location: (range.at(-1) ?? atRule).loc,
2217
+ message: "expected ')' at end of @scope block",
2218
+ });
2219
+ success = false;
1417
2220
  }
1418
- }
1419
- if (node.nam == 'value') {
1420
- let i = 0;
1421
- while (i < tokens.length) {
1422
- if (tokens[i].typ == EnumToken.WhitespaceTokenType || tokens[i].typ == EnumToken.CommentTokenType) {
1423
- i++;
1424
- continue;
2221
+ else {
2222
+ const srange = range.slice(1, -1);
2223
+ const result = matchSelectorSyntax(srange, errors, options, true);
2224
+ if (!result.success) {
2225
+ success = false;
2226
+ }
2227
+ else {
2228
+ stream.splice(stream.indexOf(range[0]) + 1, range.length - 2, ...trimWhiteSpaceTokens(srange));
1425
2229
  }
1426
- break;
1427
2230
  }
1428
- if (i < tokens.length) {
1429
- if (tokens[i].typ == EnumToken.IdenTokenType || isIdentColor(tokens[i])) {
1430
- let k = i + 1;
1431
- while (k < tokens.length) {
1432
- if (tokens[k].typ == EnumToken.WhitespaceTokenType || tokens[k].typ == EnumToken.CommentTokenType) {
1433
- k++;
1434
- continue;
2231
+ let index = stream.indexOf(range.at(-1));
2232
+ if (stream.length > index + 1) {
2233
+ while (stream[++index]?.typ === EnumToken.WhitespaceTokenType ||
2234
+ stream[index]?.typ === EnumToken.CommentTokenType)
2235
+ ;
2236
+ if (index < stream.length) {
2237
+ if (stream[index].typ !== EnumToken.IdenTokenType ||
2238
+ "to" !== stream[index].val.toLowerCase()) {
2239
+ errors.push({
2240
+ action: "drop",
2241
+ node: stream[index],
2242
+ location: stream[index]?.loc,
2243
+ message: "expected 'to' at end of @scope block",
2244
+ });
2245
+ success = false;
2246
+ }
2247
+ else {
2248
+ while (stream[++index]?.typ === EnumToken.WhitespaceTokenType ||
2249
+ stream[index]?.typ === EnumToken.CommentTokenType)
2250
+ ;
2251
+ if (stream[index].typ !== EnumToken.StartParensTokenType) {
2252
+ errors.push({
2253
+ action: "drop",
2254
+ node: stream[index],
2255
+ location: stream[index]?.loc,
2256
+ message: "expected 'to' at end of @scope block",
2257
+ });
2258
+ success = false;
1435
2259
  }
1436
- // var or import
1437
- if (tokens[k].typ == EnumToken.ColonTokenType) {
1438
- let j = k;
1439
- while (++j < tokens.length) {
1440
- if (tokens[j].typ != EnumToken.WhitespaceTokenType && tokens[j].typ != EnumToken.CommentTokenType) {
1441
- break;
1442
- }
1443
- }
1444
- let offset = k + 1;
1445
- while (offset < tokens.length && tokens[offset].typ == EnumToken.WhitespaceTokenType) {
1446
- offset++;
1447
- }
1448
- if (tokens[j].typ == EnumToken.StringTokenType) {
1449
- Object.assign(node, {
1450
- typ: EnumToken.CssVariableImportTokenType,
1451
- nam: tokens[i].val,
1452
- val: tokens.slice(offset)
2260
+ else {
2261
+ context = createValidationContext(stream.slice(index));
2262
+ // @ts-ignore
2263
+ range = context.peekRange((t) => t.typ === EnumToken.EndParensTokenType);
2264
+ if (range.at(-1)?.typ !== EnumToken.EndParensTokenType) {
2265
+ errors.push({
2266
+ action: "drop",
2267
+ node: range.at(-1) ?? atRule,
2268
+ location: (range.at(-1) ?? atRule).loc,
2269
+ message: "expected ')' at end of @scope block",
1453
2270
  });
1454
- delete node.tokens;
1455
- context.chi.push(node);
1456
- return null;
2271
+ success = false;
1457
2272
  }
1458
- Object.assign(node, {
1459
- typ: EnumToken.CssVariableTokenType,
1460
- nam: tokens[i].val,
1461
- val: tokens.slice(offset)
1462
- });
1463
- context.chi.push(node);
1464
- return null;
1465
- }
1466
- if (tokens[k].typ == EnumToken.PseudoClassTokenType) {
1467
- Object.assign(tokens[k], {
1468
- typ: EnumToken.IdenTokenType,
1469
- val: tokens[k].val.slice(1)
1470
- });
1471
- Object.assign(node, {
1472
- typ: EnumToken.CssVariableTokenType,
1473
- nam: tokens[i].val,
1474
- val: tokens.slice(k)
1475
- });
1476
- context.chi.push(node);
1477
- return null;
1478
- }
1479
- if (tokens[k].typ == EnumToken.CommaTokenType) {
1480
- let j = i;
1481
- while (++j < tokens.length) {
1482
- if (tokens[j].typ == EnumToken.IdenTokenType && tokens[j].val.toLowerCase() == 'from') {
1483
- const vars = tokens.slice(i, j);
1484
- const from = tokens.slice(j + 1);
1485
- let l = 0;
1486
- let expect = EnumToken.IdenTokenType;
1487
- for (; l < vars.length; l++) {
1488
- if (vars[l].typ == EnumToken.WhitespaceTokenType || vars[l].typ == EnumToken.CommentTokenType) {
1489
- continue;
1490
- }
1491
- if (expect == vars[l].typ || (expect == EnumToken.IdenTokenType && isIdentColor(vars[l]))) {
1492
- expect = expect == EnumToken.CommaTokenType ? EnumToken.IdenTokenType : EnumToken.CommaTokenType;
1493
- continue;
1494
- }
1495
- errors.push({
1496
- action: 'drop',
1497
- node: node,
1498
- location: map.get(vars[l]) ?? location,
1499
- message: `expecting '${EnumToken[expect]}' but found ${renderToken(vars[l])}`
1500
- });
1501
- return null;
1502
- }
1503
- l = 0;
1504
- expect = EnumToken.IdenTokenType;
1505
- for (; l < from.length; l++) {
1506
- if (from[l].typ == EnumToken.WhitespaceTokenType || from[l].typ == EnumToken.CommentTokenType) {
1507
- continue;
1508
- }
1509
- if (expect == from[l].typ || isIdentColor(from[l])) {
1510
- while (++l < from.length) {
1511
- if (from[l].typ == EnumToken.WhitespaceTokenType || from[l].typ == EnumToken.CommentTokenType) {
1512
- continue;
1513
- }
1514
- errors.push({
1515
- action: 'drop',
1516
- node: node,
1517
- location: map.get(from[l]) ?? location,
1518
- message: `unexpected '${renderToken(from[l])}'`
1519
- });
1520
- return null;
1521
- }
1522
- break;
1523
- }
1524
- errors.push({
1525
- action: 'drop',
1526
- node: node,
1527
- location: map.get(from[l]) ?? location,
1528
- message: `expecting <string> but found ${renderToken(from[l])}`
1529
- });
1530
- return null;
1531
- }
1532
- // @ts-ignore
1533
- delete node.nam;
1534
- // @ts-ignore
1535
- delete node.val;
1536
- Object.assign(node, {
1537
- typ: EnumToken.CssVariableDeclarationMapTokenType,
1538
- vars,
1539
- from
1540
- });
1541
- context.chi.push(node);
1542
- return null;
2273
+ else {
2274
+ const srange = range.slice(1, -1);
2275
+ const result = matchSelectorSyntax(srange, errors, options, true);
2276
+ if (!result.success) {
2277
+ success = false;
2278
+ }
2279
+ else {
2280
+ stream.splice(stream.indexOf(range[0]) + 1, range.length - 2, ...trimWhiteSpaceTokens(srange));
1543
2281
  }
1544
2282
  }
1545
2283
  }
1546
- k++;
1547
2284
  }
1548
- Object.assign(node, {
1549
- typ: EnumToken.CssVariableTokenType,
1550
- nam: tokens[i].val,
1551
- val: tokens.slice(k)
1552
- });
1553
- context.chi.push(node);
1554
- return null;
1555
2285
  }
1556
2286
  }
1557
- }
1558
- // @ts-ignore
1559
- const skipValidate = (options.validation & ValidationLevel.AtRule) == 0;
1560
- const isAllowed = skipValidate || isNodeAllowedInContext(node, context);
1561
- // @ts-ignore
1562
- const valid = skipValidate ? {
1563
- valid: SyntaxValidationResult.Valid,
1564
- error: '',
1565
- node,
1566
- syntax: '@' + node.nam
1567
- } : !isAllowed ? {
1568
- valid: SyntaxValidationResult.Drop,
1569
- node,
1570
- syntax: '@' + node.nam,
1571
- error: `${EnumToken[context.typ]}: child ${EnumToken[node.typ]} not allowed in context${context.typ == EnumToken.AtRuleNodeType ? ` '@${context.nam}'` : context.typ == EnumToken.StyleSheetNodeType ? ` 'stylesheet'` : ''}`} : isValid ? (node.typ == EnumToken.KeyframesAtRuleNodeType ? validateAtRuleKeyframes(node) : validateAtRule(node, options, context)) : {
1572
- valid: SyntaxValidationResult.Drop,
1573
- node,
1574
- syntax: '@' + node.nam,
1575
- error: '@' + node.nam + ' not allowed here'};
1576
- if (valid.valid == SyntaxValidationResult.Drop) {
1577
- let message = '';
1578
- for (const token of tokens) {
1579
- message += renderToken(token, { minify: false });
1580
- }
1581
- errors.push({
1582
- action: 'drop',
1583
- message: valid.error + ' - "' + message + '"',
1584
- node,
1585
- // @ts-ignore
1586
- location: { src, ...(map.get(valid.node) ?? location) }
2287
+ // @ts-expect-error
2288
+ return Object.defineProperties(Object.assign(atRule, {
2289
+ typ: EnumToken.AtRuleNodeType,
2290
+ val: renderTokens(stream, options),
2291
+ chi: [],
2292
+ }), {
2293
+ state: {
2294
+ ...definedPropertySettings,
2295
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2296
+ },
2297
+ errors: {
2298
+ ...definedPropertySettings,
2299
+ value: success ? [] : [errors[errors.length - 1]],
2300
+ },
2301
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2302
+ loc: {
2303
+ ...definedPropertySettings,
2304
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2305
+ },
1587
2306
  });
1588
- // @ts-ignore
1589
- node.typ = EnumToken.InvalidAtRuleTokenType;
1590
- }
1591
- else {
1592
- node.val = '';
1593
- for (const token of node.tokens) {
1594
- node.val += renderToken(token, {
1595
- minify: false,
1596
- convertColor: false,
1597
- removeComments: true
1598
- });
1599
- }
1600
2307
  }
1601
- context.chi.push(node);
1602
- stats.nodesCount++;
1603
- Object.defineProperties(node, {
1604
- parent: { ...definedPropertySettings, value: context },
1605
- validSyntax: { ...definedPropertySettings, value: valid.valid == SyntaxValidationResult.Valid }
1606
- });
1607
- return node;
1608
- }
1609
- else {
1610
- // rule
1611
- if (delim.typ == EnumToken.BlockStartTokenType) {
1612
- const location = map.get(tokens[0]);
1613
- const uniq = new Map;
1614
- parseTokens(tokens, { minify: true });
1615
- const ruleType = context.typ == EnumToken.KeyframesAtRuleNodeType ? EnumToken.KeyFramesRuleNodeType : EnumToken.RuleNodeType;
1616
- if (ruleType == EnumToken.RuleNodeType) {
1617
- parseSelector(tokens);
1618
- }
1619
- const node = {
1620
- typ: ruleType,
1621
- sel: [...tokens.reduce((acc, curr, index, array) => {
1622
- if (curr.typ == EnumToken.CommentTokenType) {
1623
- return acc;
1624
- }
1625
- if (options.minify) {
1626
- if (curr.typ == EnumToken.PseudoClassFuncTokenType && curr.val == ':nth-child') {
1627
- let i = 0;
1628
- for (; i < curr.chi.length; i++) {
1629
- if (curr.chi[i].typ == EnumToken.IdenTokenType && curr.chi[i].val == 'even') {
1630
- Object.assign(curr.chi[i], {
1631
- typ: EnumToken.Dimension,
1632
- val: 2,
1633
- unit: 'n'
1634
- });
1635
- }
1636
- else if (curr.chi[i].typ == EnumToken.Dimension &&
1637
- curr.chi[i].val == 2 &&
1638
- curr.chi[i].unit == 'n' &&
1639
- curr.chi[i + 1]?.typ == EnumToken.WhitespaceTokenType &&
1640
- curr.chi[i + 2]?.typ == EnumToken.LiteralTokenType &&
1641
- curr.chi[i + 2].val == '+' &&
1642
- curr.chi[i + 3]?.typ == EnumToken.WhitespaceTokenType &&
1643
- curr.chi[i + 4]?.typ == EnumToken.NumberTokenType &&
1644
- curr.chi[i + 4].val == 1) {
1645
- curr.chi.splice(i, 5, Object.assign(curr.chi[i], {
1646
- typ: EnumToken.IdenTokenType,
1647
- val: 'odd'
1648
- }));
1649
- }
1650
- }
1651
- }
1652
- }
1653
- if (curr.typ == EnumToken.WhitespaceTokenType) {
1654
- if (trimWhiteSpace.includes(array[index - 1]?.typ) ||
1655
- trimWhiteSpace.includes(array[index + 1]?.typ) ||
1656
- combinators.includes(array[index - 1]?.val) ||
1657
- combinators.includes(array[index + 1]?.val)) {
1658
- return acc;
1659
- }
1660
- }
1661
- if (ruleType == EnumToken.KeyFramesRuleNodeType && options.minify) {
1662
- if (curr.typ == EnumToken.IdenTokenType && curr.val == 'from') {
1663
- Object.assign(curr, { typ: EnumToken.PercentageTokenType, val: '0' });
1664
- }
1665
- else if (curr.typ == EnumToken.PercentageTokenType && curr.val == 100) {
1666
- Object.assign(curr, { typ: EnumToken.IdenTokenType, val: 'to' });
1667
- }
1668
- }
1669
- let t = renderToken(curr, { minify: false });
1670
- if (t == ',') {
1671
- acc.push([]);
1672
- }
1673
- else {
1674
- acc[acc.length - 1].push(t);
1675
- }
1676
- return acc;
1677
- }, [[]]).reduce((acc, curr) => {
1678
- let i = 0;
1679
- for (; i < curr.length; i++) {
1680
- if (i + 1 < curr.length && curr[i] == '*') {
1681
- if (curr[i] == '*') {
1682
- let index = curr[i + 1] == ' ' ? 2 : 1;
1683
- if (!['>', '~', '+'].includes(curr[index])) {
1684
- curr.splice(i, index);
1685
- }
1686
- }
1687
- }
1688
- }
1689
- acc.set(curr.join(''), curr);
1690
- return acc;
1691
- }, uniq).keys()].join(','),
1692
- chi: []
1693
- };
1694
- Object.defineProperty(node, 'tokens', {
1695
- ...definedPropertySettings,
1696
- enumerable: false,
1697
- value: tokens.slice()
1698
- });
1699
- loc = location;
1700
- Object.defineProperty(node, 'loc', {
1701
- ...definedPropertySettings,
1702
- value: loc,
1703
- enumerable: options.sourcemap !== false
1704
- });
1705
- context.chi.push(node);
1706
- Object.defineProperty(node, 'parent', { ...definedPropertySettings, value: context });
1707
- // @ts-ignore
1708
- const skipValidate = (options.validation & ValidationLevel.Selector) == 0;
1709
- const isAllowed = skipValidate || isNodeAllowedInContext(node, context);
1710
- // @ts-ignore
1711
- const valid = skipValidate ? {
1712
- valid: SyntaxValidationResult.Valid,
1713
- error: null
1714
- } : !isAllowed ? {
1715
- valid: SyntaxValidationResult.Drop,
1716
- error: `${EnumToken[context.typ]}: child ${EnumToken[node.typ]} not allowed in context${context.typ == EnumToken.AtRuleNodeType ? ` '@${context.nam}'` : context.typ == EnumToken.StyleSheetNodeType ? ` 'stylesheet'` : ''}`
1717
- } : ruleType == EnumToken.KeyFramesRuleNodeType ? validateKeyframeSelector(tokens) : validateSelector(tokens, options, context);
1718
- if (valid.valid != SyntaxValidationResult.Valid) {
1719
- // @ts-ignore
1720
- node.typ = EnumToken.InvalidRuleTokenType;
1721
- node.sel = tokens.reduce((acc, curr) => acc + renderToken(curr, { minify: false }), '');
1722
- errors.push({
1723
- action: 'drop',
1724
- message: valid.error + ' - "' + tokens.reduce((acc, curr) => acc + renderToken(curr, { minify: false }), '') + '"',
1725
- node,
1726
- // @ts-ignore
1727
- location
1728
- });
1729
- }
1730
- Object.defineProperty(node, 'validSyntax', {
1731
- ...definedPropertySettings,
1732
- value: valid.valid == SyntaxValidationResult.Valid
2308
+ case "page": {
2309
+ trimArray(stream);
2310
+ // @ts-expect-error
2311
+ return Object.defineProperties(Object.assign(atRule, {
2312
+ typ: EnumToken.AtRuleNodeType,
2313
+ val: renderTokens(stream, options),
2314
+ chi: [],
2315
+ }), {
2316
+ state: {
2317
+ ...definedPropertySettings,
2318
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2319
+ },
2320
+ errors: {
2321
+ ...definedPropertySettings,
2322
+ value: success ? [] : [errors[errors.length - 1]],
2323
+ },
2324
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2325
+ loc: {
2326
+ ...definedPropertySettings,
2327
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2328
+ },
1733
2329
  });
1734
- return node;
1735
2330
  }
1736
- else {
1737
- let name = null;
1738
- let value = null;
1739
- let i = 0;
1740
- for (; i < tokens.length; i++) {
1741
- if (tokens[i].typ == EnumToken.LiteralTokenType && tokens[i].val.length > 1) {
1742
- const start = tokens[i].val.charAt(0);
1743
- const val = tokens[i].val.slice(1);
1744
- if (['/', '*'].includes(start) && isNumber(val)) {
1745
- tokens.splice(i, 1, {
1746
- typ: EnumToken.LiteralTokenType,
1747
- val: tokens[i].val.charAt(0)
1748
- }, {
1749
- typ: EnumToken.NumberTokenType,
1750
- val: +tokens[i].val.slice(1)
1751
- });
1752
- }
1753
- else if (start == '/' && isFunction(val)) {
1754
- tokens.splice(i, 1, { typ: EnumToken.LiteralTokenType, val: '/' }, getTokenType(val));
1755
- }
1756
- }
1757
- }
1758
- parseTokens(tokens, { ...options, parseColor: true });
1759
- for (i = 0; i < tokens.length; i++) {
1760
- if (tokens[i].typ == EnumToken.CommentTokenType) {
1761
- continue;
1762
- }
1763
- if (name == null && [EnumToken.IdenTokenType, EnumToken.DashedIdenTokenType].includes(tokens[i].typ)) {
1764
- name = tokens.slice(0, i + 1);
1765
- }
1766
- else if (name == null && tokens[i].typ == EnumToken.ColorTokenType && [ColorType.SYS, ColorType.DPSYS].includes(tokens[i].kin)) {
1767
- name = tokens.slice(0, i + 1);
1768
- tokens[i].typ = EnumToken.IdenTokenType;
1769
- }
1770
- else if (name != null && funcLike.concat([
1771
- EnumToken.LiteralTokenType,
1772
- EnumToken.IdenTokenType, EnumToken.DashedIdenTokenType,
1773
- EnumToken.PseudoClassTokenType, EnumToken.PseudoClassFuncTokenType
1774
- ]).includes(tokens[i].typ)) {
1775
- if (tokens[i].val?.charAt?.(0) == ':') {
1776
- Object.assign(tokens[i], getTokenType(tokens[i].val.slice(1)));
1777
- if ('chi' in tokens[i]) {
1778
- tokens[i].typ = EnumToken.FunctionTokenType;
1779
- if (colorsFunc.includes(tokens[i].val) && isColor(tokens[i])) {
1780
- parseColor(tokens[i]);
1781
- }
1782
- }
1783
- tokens.splice(i--, 0, { typ: EnumToken.ColonTokenType });
1784
- continue;
1785
- }
1786
- if ('chi' in tokens[i]) {
1787
- tokens[i].typ = EnumToken.FunctionTokenType;
1788
- }
1789
- value = tokens.slice(i);
1790
- }
1791
- if (tokens[i].typ == EnumToken.ColonTokenType) {
1792
- name = tokens.slice(0, i);
1793
- value = tokens.slice(i + 1);
1794
- break;
1795
- }
1796
- }
1797
- if (name == null) {
1798
- name = tokens;
1799
- }
1800
- const location = map.get(name[0]);
1801
- if (name.length > 0) {
1802
- for (let i = 1; i < name.length; i++) {
1803
- if (name[i].typ != EnumToken.WhitespaceTokenType && name[i].typ != EnumToken.CommentTokenType) {
1804
- errors.push({
1805
- action: 'drop',
1806
- message: 'doParse: invalid declaration',
1807
- location
1808
- });
1809
- return null;
1810
- }
1811
- }
1812
- }
1813
- const nam = renderToken(name.shift(), { removeComments: true });
1814
- if (value == null || (!nam.startsWith('--') && value.length == 0)) {
2331
+ case "top-left-corner":
2332
+ case "top-left":
2333
+ case "top-center":
2334
+ case "top-right":
2335
+ case "top-right-corner":
2336
+ case "bottom-left-corner":
2337
+ case "bottom-left":
2338
+ case "bottom-right":
2339
+ case "bottom-right-corner":
2340
+ case "left-top":
2341
+ case "left-middle":
2342
+ case "left-bottom":
2343
+ case "right-top":
2344
+ case "right-middle":
2345
+ case "right-bottom": {
2346
+ if (context.typ !== EnumToken.AtRuleNodeType || context.nam !== "page") {
2347
+ success = false;
1815
2348
  errors.push({
1816
- action: 'drop',
1817
- message: 'doParse: invalid declaration',
1818
- location
2349
+ action: "drop",
2350
+ node: atRule,
2351
+ location: atRule.loc,
2352
+ message: "node is allowd only in @page rule",
1819
2353
  });
1820
- if (options.lenient) {
1821
- const node = {
1822
- typ: EnumToken.InvalidDeclarationNodeType,
1823
- nam,
1824
- val: []
1825
- };
1826
- Object.defineProperty(node, 'loc', {
1827
- ...definedPropertySettings,
1828
- value: location,
1829
- enumerable: options.sourcemap !== false
1830
- });
1831
- context.chi.push(node);
1832
- stats.nodesCount++;
1833
- }
1834
- return null;
1835
2354
  }
1836
- for (const { value: token } of walkValues(value, null, {
1837
- fn: (node) => node.typ == EnumToken.FunctionTokenType && node.val == 'calc' ? WalkerOptionEnum.IgnoreChildren : null,
1838
- type: EnumToken.FunctionTokenType
1839
- })) {
1840
- if (token.typ == EnumToken.FunctionTokenType && token.val == 'calc') {
1841
- for (const { value: node, parent } of walkValues(token.chi, token)) {
1842
- // fix expressions starting with '/' or '*' such as '/4' in (1 + 1)/4
1843
- if (node.typ == EnumToken.LiteralTokenType && node.val.length > 0) {
1844
- if (node.val[0] == '/' || node.val[0] == '*') {
1845
- parent.chi.splice(parent.chi.indexOf(node), 1, { typ: node.val[0] == '/' ? EnumToken.Div : EnumToken.Mul }, ...parseString(node.val.slice(1)));
1846
- }
1847
- }
1848
- }
1849
- }
1850
- }
1851
- const node = {
1852
- typ: EnumToken.DeclarationNodeType,
1853
- nam,
1854
- val: value
1855
- };
1856
- Object.defineProperty(node, 'loc', {
1857
- ...definedPropertySettings,
1858
- value: location,
1859
- enumerable: options.sourcemap !== false
1860
- });
1861
- node.loc.end = { ...map.get(delim).end };
1862
- // do not allow declarations in style sheets
1863
- if (context.typ == EnumToken.StyleSheetNodeType && options.lenient) {
1864
- Object.assign(node, { typ: EnumToken.InvalidDeclarationNodeType });
1865
- context.chi.push(node);
1866
- stats.nodesCount++;
1867
- return null;
1868
- }
1869
- const result = parseDeclarationNode(node, errors, location);
1870
- Object.defineProperty(result, 'parent', { ...definedPropertySettings, value: context });
1871
- if (result != null) {
1872
- if (options.validation & ValidationLevel.Declaration) {
1873
- const isAllowed = isNodeAllowedInContext(node, context);
1874
- // @ts-ignore
1875
- const valid = !isAllowed ? {
1876
- valid: SyntaxValidationResult.Drop,
1877
- error: `${EnumToken[node.typ]} not allowed in context${context.typ == EnumToken.AtRuleNodeType ? ` '@${context.nam}'` : context.typ == EnumToken.StyleSheetNodeType ? ` 'stylesheet'` : ''}`,
1878
- node,
1879
- syntax: null
1880
- } : evaluateSyntax(result, context, options);
1881
- Object.defineProperty(result, 'validSyntax', {
1882
- ...definedPropertySettings,
1883
- value: valid.valid == SyntaxValidationResult.Valid
1884
- });
1885
- if (valid.valid == SyntaxValidationResult.Drop) {
2355
+ else {
2356
+ trimArray(stream);
2357
+ for (let i = 0; i < stream.length; i++) {
2358
+ if (stream[i].typ !== EnumToken.WhitespaceTokenType &&
2359
+ stream[i].typ !== EnumToken.CommentTokenType) {
2360
+ success = false;
1886
2361
  errors.push({
1887
- action: 'drop',
1888
- message: valid.error,
1889
- syntax: valid.syntax,
1890
- node: valid.node,
1891
- location: map.get(valid.node) ?? valid.node?.loc ?? result.loc ?? location
2362
+ action: "drop",
2363
+ node: stream[i],
2364
+ location: stream[i].loc,
2365
+ message: "expected whitespace or comment",
1892
2366
  });
1893
- if (!options.lenient) {
1894
- return null;
1895
- }
1896
- Object.assign(node, { typ: EnumToken.InvalidDeclarationNodeType });
2367
+ break;
1897
2368
  }
1898
2369
  }
1899
- context.chi.push(result);
1900
- stats.nodesCount++;
1901
2370
  }
1902
- return null;
1903
- }
1904
- }
1905
- }
1906
- /**
1907
- * parse at-rule prelude
1908
- * @param tokens
1909
- * @param atRule
1910
- */
1911
- function parseAtRulePrelude(tokens, atRule) {
1912
- for (const { value, parent } of walkValues(tokens, null, null, true)) {
1913
- if (value.typ == EnumToken.CommentTokenType ||
1914
- value.typ == EnumToken.WhitespaceTokenType ||
1915
- value.typ == EnumToken.CommaTokenType) {
1916
- continue;
2371
+ // @ts-expect-error
2372
+ return Object.defineProperties(Object.assign(atRule, {
2373
+ typ: EnumToken.AtRuleNodeType,
2374
+ val: renderTokens(stream, options),
2375
+ chi: [],
2376
+ }), {
2377
+ state: {
2378
+ ...definedPropertySettings,
2379
+ value: success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2380
+ },
2381
+ errors: {
2382
+ ...definedPropertySettings,
2383
+ value: success ? [] : [errors[errors.length - 1]],
2384
+ },
2385
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2386
+ loc: {
2387
+ ...definedPropertySettings,
2388
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2389
+ },
2390
+ });
1917
2391
  }
1918
- if (value.typ == EnumToken.PseudoClassFuncTokenType || value.typ == EnumToken.PseudoClassTokenType) {
1919
- if (parent?.typ == EnumToken.ParensTokenType) {
1920
- const index = parent.chi.indexOf(value);
1921
- let i = index;
1922
- while (i--) {
1923
- if (parent.chi[i].typ == EnumToken.IdenTokenType || parent.chi[i].typ == EnumToken.DashedIdenTokenType) {
1924
- break;
1925
- }
1926
- }
1927
- if (i >= 0) {
1928
- const token = getTokenType(parent.chi[index].val.slice(1) + (funcLike.includes(parent.chi[index].typ) ? '(' : ''));
1929
- parent.chi[index].val = token.val;
1930
- parent.chi[index].typ = token.typ;
1931
- if (parent.chi[index].typ == EnumToken.FunctionTokenType && isColor(parent.chi[index])) {
1932
- parseColor(parent.chi[index]);
1933
- }
1934
- parent.chi.splice(i, index - i + 1, {
1935
- typ: EnumToken.MediaQueryConditionTokenType,
1936
- l: parent.chi[i],
1937
- r: parent.chi.slice(index),
1938
- op: {
1939
- typ: EnumToken.ColonTokenType
1940
- }
2392
+ case "value": {
2393
+ let index = 0;
2394
+ let isVarDeclaration = false;
2395
+ for (; index < stream.length; index++) {
2396
+ if (stream[index].typ == EnumToken.PseudoClassTokenType) {
2397
+ Object.assign(stream[index], {
2398
+ typ: EnumToken.IdenTokenType,
2399
+ val: stream[index].val.slice(1),
1941
2400
  });
2401
+ stream.splice(index, 0, Object.defineProperty({
2402
+ typ: EnumToken.ColonTokenType,
2403
+ }, "loc", {
2404
+ ...definedPropertySettings,
2405
+ value: { ...stream[index].loc, end: { ...stream[index]?.loc?.sta } },
2406
+ }));
2407
+ isVarDeclaration = true;
2408
+ break;
1942
2409
  }
1943
- }
1944
- }
1945
- if (atRule.val == 'page' && value.typ == EnumToken.PseudoClassTokenType) {
1946
- if ([':left', ':right', ':first', ':blank'].includes(value.val)) {
1947
- Object.assign(value, { typ: EnumToken.PseudoPageTokenType });
1948
- }
1949
- }
1950
- if (atRule.val == 'layer') {
1951
- if (parent == null && value.typ == EnumToken.LiteralTokenType) {
1952
- if (value.val.charAt(0) == '.') {
1953
- if (isIdent(value.val.slice(1))) {
1954
- Object.assign(value, { typ: EnumToken.ClassSelectorTokenType });
1955
- }
2410
+ else if (stream[index].typ == EnumToken.ColonTokenType) {
2411
+ isVarDeclaration = true;
2412
+ break;
1956
2413
  }
1957
- }
1958
- }
1959
- const val = value.typ == EnumToken.IdenTokenType ? value.val.toLowerCase() : null;
1960
- if (value.typ == EnumToken.IdenTokenType) {
1961
- if (parent == null && mediaTypes.some((t) => {
1962
- if (val === t) {
1963
- Object.assign(value, { typ: EnumToken.MediaFeatureTokenType });
1964
- return true;
2414
+ else if (stream[index].typ == EnumToken.IdenTokenType &&
2415
+ equalsIgnoreCase("from", stream[index].val)) {
2416
+ break;
1965
2417
  }
1966
- return false;
1967
- })) {
1968
- continue;
1969
- }
1970
- if (value.typ == EnumToken.IdenTokenType && 'and' === val) {
1971
- Object.assign(value, { typ: EnumToken.MediaFeatureAndTokenType });
1972
- continue;
1973
2418
  }
1974
- if (value.typ == EnumToken.IdenTokenType && 'or' === val) {
1975
- Object.assign(value, { typ: EnumToken.MediaFeatureOrTokenType });
1976
- continue;
2419
+ // supported syntaxes:
2420
+ // @value <ident>: <string>; // import from file as alias
2421
+ // @value id : <declaration-value>; // variable declaration
2422
+ // @value <ident># from <ident>; // import variables from alias
2423
+ let result = matchAllSyntaxes(syntaxRules?.getPreludeRules()?.slice?.(1), createValidationContext(stream), options);
2424
+ if (!result.success) {
2425
+ errors.push(...result.errors);
2426
+ return Object.defineProperties({
2427
+ typ: EnumToken.AtRuleNodeType,
2428
+ val: renderTokens(stream, options),
2429
+ }, {
2430
+ state: {
2431
+ ...definedPropertySettings,
2432
+ value: EnumAstNodeStatus.Invalid,
2433
+ },
2434
+ errors: {
2435
+ ...definedPropertySettings,
2436
+ value: result.errors,
2437
+ },
2438
+ loc: {
2439
+ ...definedPropertySettings,
2440
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2441
+ },
2442
+ });
1977
2443
  }
1978
- if (value.typ == EnumToken.IdenTokenType &&
1979
- ['not', 'only'].some((t) => val === t)) {
1980
- const array = parent?.chi ?? tokens;
1981
- const startIndex = array.indexOf(value);
1982
- let index = startIndex + 1;
1983
- if (index == 0) {
1984
- continue;
1985
- }
1986
- while (index < array.length && [EnumToken.CommentTokenType, EnumToken.WhitespaceTokenType].includes(array[index].typ)) {
1987
- index++;
1988
- }
1989
- if (array[index] == null || array[index].typ == EnumToken.CommaTokenType) {
1990
- continue;
2444
+ if (isVarDeclaration) {
2445
+ const nam = stream.find((t) => t.typ == EnumToken.IdenTokenType);
2446
+ const value = trimArray(stream.slice(index + 1).filter((t) => t.typ != EnumToken.CommentTokenType));
2447
+ if (value.length == 1 && value[0].typ == EnumToken.StringTokenType) {
2448
+ // import from file as alias
2449
+ return Object.defineProperties({
2450
+ typ: EnumToken.CssVariableImportTokenType,
2451
+ nam: nam.val,
2452
+ val: value,
2453
+ }, {
2454
+ loc: {
2455
+ ...definedPropertySettings,
2456
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2457
+ },
2458
+ });
1991
2459
  }
1992
- Object.assign(array[startIndex], {
1993
- typ: value.val.toLowerCase() == 'not' ? EnumToken.MediaFeatureNotTokenType : EnumToken.MediaFeatureOnlyTokenType,
1994
- val: array[index]
2460
+ // import variables from alias
2461
+ return Object.defineProperties({
2462
+ typ: EnumToken.CssVariableTokenType,
2463
+ nam: nam.val,
2464
+ val: value,
2465
+ }, {
2466
+ loc: {
2467
+ ...definedPropertySettings,
2468
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2469
+ },
1995
2470
  });
1996
- array.splice(startIndex + 1, index - startIndex);
1997
- continue;
1998
2471
  }
2472
+ // @ts-expect-error
2473
+ return Object.defineProperties(Object.assign(atRule, {
2474
+ typ: EnumToken.CssVariableDeclarationMapTokenType,
2475
+ vars: trimArray(stream.slice(0, index)),
2476
+ from: stream.slice(index + 1),
2477
+ }), {
2478
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2479
+ loc: {
2480
+ ...definedPropertySettings,
2481
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2482
+ },
2483
+ });
1999
2484
  }
2000
- if (value.typ == EnumToken.FunctionTokenType && value.val == 'selector') {
2001
- parseSelector(value.chi);
2002
- }
2003
- if (value.typ == EnumToken.ParensTokenType || (value.typ == EnumToken.FunctionTokenType && ['media', 'supports', 'style', 'scroll-state'].includes(value.val))) {
2004
- let i;
2005
- let nameIndex = -1;
2006
- let valueIndex = -1;
2007
- const dashedIdent = value.typ == EnumToken.FunctionTokenType && value.val == 'style';
2008
- for (let i = 0; i < value.chi.length; i++) {
2009
- if (value.chi[i].typ == EnumToken.CommentTokenType || value.chi[i].typ == EnumToken.WhitespaceTokenType) {
2010
- continue;
2011
- }
2012
- if ((dashedIdent && value.chi[i].typ == EnumToken.DashedIdenTokenType) || value.chi[i].typ == EnumToken.IdenTokenType || value.chi[i].typ == EnumToken.FunctionTokenType || value.chi[i].typ == EnumToken.ColorTokenType) {
2013
- nameIndex = i;
2014
- }
2015
- break;
2016
- }
2017
- if (nameIndex == -1) {
2018
- continue;
2019
- }
2020
- for (let i = nameIndex + 1; i < value.chi.length; i++) {
2021
- if (value.chi[i].typ == EnumToken.CommentTokenType || value.chi[i].typ == EnumToken.WhitespaceTokenType) {
2022
- continue;
2023
- }
2024
- if (value.chi[i].typ == EnumToken.LiteralTokenType && value.chi[i].val.startsWith(':')) {
2025
- const dimension = parseDimension(value.chi[i].val.slice(1));
2026
- if (dimension != null) {
2027
- value.chi.splice(i, 1, {
2028
- typ: EnumToken.ColonTokenType,
2029
- }, Object.assign(value.chi[i], dimension));
2030
- i--;
2031
- continue;
2032
- }
2033
- }
2034
- if (nameIndex != -1 && value.chi[i].typ == EnumToken.PseudoClassTokenType) {
2035
- value.chi.splice(i, 1, {
2036
- typ: EnumToken.ColonTokenType,
2037
- }, Object.assign(value.chi[i], {
2038
- typ: EnumToken.IdenTokenType,
2039
- val: value.chi[i].val.slice(1)
2040
- }));
2041
- i--;
2042
- continue;
2043
- }
2044
- valueIndex = i;
2045
- break;
2046
- }
2047
- if (valueIndex == -1) {
2048
- continue;
2049
- }
2050
- for (i = nameIndex + 1; i < value.chi.length; i++) {
2051
- if ([
2052
- EnumToken.GtTokenType, EnumToken.LtTokenType,
2053
- EnumToken.GteTokenType, EnumToken.LteTokenType,
2054
- EnumToken.ColonTokenType
2055
- ].includes(value.chi[valueIndex].typ)) {
2056
- const val = value.chi.splice(valueIndex, 1)[0];
2057
- const node = value.chi.splice(nameIndex, 1)[0];
2058
- // 'background'
2059
- if (node.typ == EnumToken.ColorTokenType && node.kin == ColorType.DPSYS) {
2060
- Object.assign(node, { typ: EnumToken.IdenTokenType });
2061
- // @ts-ignore
2062
- delete node.kin;
2063
- }
2064
- while (value.chi[0]?.typ == EnumToken.WhitespaceTokenType) {
2065
- value.chi.shift();
2066
- }
2067
- const t = [{
2068
- typ: EnumToken.MediaQueryConditionTokenType,
2069
- l: node,
2070
- op: { typ: val.typ },
2071
- r: value.chi.slice()
2072
- }];
2073
- value.chi.length = 0;
2074
- value.chi.push(...t);
2485
+ default: {
2486
+ options = { ...options, parseColor: false };
2487
+ let result = null;
2488
+ if (syntax == null) {
2489
+ // check matching '(' and ')'
2490
+ // check commas , or ,,
2491
+ // check colon :
2492
+ // check or and and
2493
+ result = matchGenericSyntax(stream);
2494
+ if (result.errors.length > 0) {
2495
+ errors.push(...result.errors);
2075
2496
  }
2076
2497
  }
2498
+ else {
2499
+ result = matchAtRuleSyntax(atRule, stream, options);
2500
+ if (result.errors.length > 0) {
2501
+ errors.push(...result.errors);
2502
+ }
2503
+ // else if (atRuleName === "document") {
2504
+ // parseUrlToken(stream);
2505
+ // }
2506
+ if (result.success) {
2507
+ let i = 0;
2508
+ const stack = [];
2509
+ for (; i < stream.length; i++) {
2510
+ if (stream[i].typ === EnumToken.StartParensTokenType || tokensfuncDefMap.has(stream[i].typ)) {
2511
+ stack.push(stream[i]);
2512
+ continue;
2513
+ }
2514
+ if (stream[i].typ === EnumToken.EndParensTokenType && stack.length > 0) {
2515
+ const index = stream.indexOf(stack[stack.length - 1]);
2516
+ stream[index].loc.end = stream[i].loc.end;
2517
+ Object.assign(stream[index], {
2518
+ typ: tokensfuncDefMap.get(stream[index].typ),
2519
+ chi: stream.splice(index + 1, i - index - 1),
2520
+ });
2521
+ i = index;
2522
+ stream.splice(index + 1, 1);
2523
+ stack.pop();
2524
+ // continue;
2525
+ }
2526
+ }
2527
+ }
2528
+ }
2529
+ // @ts-expect-error
2530
+ return Object.defineProperties(Object.assign(atRule, {
2531
+ typ: EnumToken.AtRuleNodeType,
2532
+ val: renderTokens(trimWhiteSpaceTokens(stream), options),
2533
+ ...(parseAsBlock ? { chi: [] } : {}),
2534
+ }), {
2535
+ state: {
2536
+ ...definedPropertySettings,
2537
+ value: result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid,
2538
+ },
2539
+ errors: {
2540
+ ...definedPropertySettings,
2541
+ value: result.errors,
2542
+ },
2543
+ tokens: { ...definedPropertySettings, value: stream.slice() },
2544
+ loc: {
2545
+ ...definedPropertySettings,
2546
+ value: { ...atRule.loc, end: { ...(stream.at(-1)?.loc?.end ?? atRule.loc.end) } },
2547
+ },
2548
+ });
2077
2549
  }
2078
2550
  }
2079
- return tokens;
2080
2551
  }
2081
2552
  /**
2082
- * parse a string as an array of declaration nodes
2553
+ * Parse a string as an array of declaration nodes
2083
2554
  * @param declaration
2084
2555
  *
2085
2556
  * Example:
@@ -2092,110 +2563,23 @@ function parseAtRulePrelude(tokens, atRule) {
2092
2563
  async function parseDeclarations(declaration) {
2093
2564
  return doParse(tokenize({
2094
2565
  stream: `.x{${declaration}}`,
2095
- buffer: '',
2566
+ buffer: "",
2096
2567
  offset: 0,
2097
2568
  position: { ind: 0, lin: 1, col: 1 },
2098
- currentPosition: { ind: -1, lin: 1, col: 0 }
2099
- }), { setParent: false, minify: false, validation: false }).then(result => {
2100
- return result.ast.chi[0].chi.filter(t => t.typ == EnumToken.DeclarationNodeType || t.typ == EnumToken.CommentNodeType);
2569
+ currentPosition: { ind: -1, lin: 1, col: 0 },
2570
+ }), { setParent: false, minify: false, validation: false }).then((result) => {
2571
+ return result.ast.chi[0].chi.filter((t) => t.typ == EnumToken.DeclarationNodeType ||
2572
+ t.typ == EnumToken.CommentNodeType);
2101
2573
  });
2102
2574
  }
2103
2575
  /**
2104
- * parse selector
2105
- * @param tokens
2106
- */
2107
- function parseSelector(tokens) {
2108
- for (const { value, parent } of walkValues(tokens)) {
2109
- if (value.typ == EnumToken.CommentTokenType ||
2110
- value.typ == EnumToken.WhitespaceTokenType ||
2111
- value.typ == EnumToken.CommaTokenType ||
2112
- value.typ == EnumToken.IdenTokenType ||
2113
- value.typ == EnumToken.HashTokenType) {
2114
- continue;
2115
- }
2116
- if (parent == null) {
2117
- if (value.typ == EnumToken.GtTokenType) {
2118
- Object.assign(value, { typ: EnumToken.ChildCombinatorTokenType });
2119
- }
2120
- else if (value.typ == EnumToken.LiteralTokenType) {
2121
- if (value.val.charAt(0) == '&') {
2122
- Object.assign(value, { typ: EnumToken.NestingSelectorTokenType });
2123
- // @ts-ignore
2124
- delete value.val;
2125
- }
2126
- else if (value.val.charAt(0) == '.') {
2127
- if (!isIdent(value.val.slice(1))) {
2128
- Object.assign(value, { typ: EnumToken.InvalidClassSelectorTokenType });
2129
- }
2130
- else {
2131
- Object.assign(value, { typ: EnumToken.ClassSelectorTokenType });
2132
- }
2133
- }
2134
- if (['*', '>', '+', '~'].includes(value.val)) {
2135
- switch (value.val) {
2136
- case '*':
2137
- Object.assign(value, { typ: EnumToken.UniversalSelectorTokenType });
2138
- break;
2139
- case '>':
2140
- Object.assign(value, { typ: EnumToken.ChildCombinatorTokenType });
2141
- break;
2142
- case '+':
2143
- Object.assign(value, { typ: EnumToken.NextSiblingCombinatorTokenType });
2144
- break;
2145
- case '~':
2146
- Object.assign(value, { typ: EnumToken.SubsequentSiblingCombinatorTokenType });
2147
- break;
2148
- }
2149
- // @ts-ignore
2150
- delete value.val;
2151
- }
2152
- }
2153
- else if (value.typ == EnumToken.ColorTokenType) {
2154
- if (value.kin == ColorType.LIT || value.kin == ColorType.HEX || value.kin == ColorType.SYS || value.kin == ColorType.DPSYS) {
2155
- if (value.kin == ColorType.HEX) {
2156
- if (!isIdent(value.val.slice(1))) {
2157
- continue;
2158
- }
2159
- Object.assign(value, { typ: EnumToken.HashTokenType });
2160
- }
2161
- else {
2162
- Object.assign(value, { typ: EnumToken.IdenTokenType });
2163
- }
2164
- // @ts-ignore
2165
- delete value.kin;
2166
- }
2167
- }
2168
- }
2169
- }
2170
- let i = 0;
2171
- const combinators = [
2172
- EnumToken.ChildCombinatorTokenType,
2173
- EnumToken.NextSiblingCombinatorTokenType,
2174
- EnumToken.SubsequentSiblingCombinatorTokenType
2175
- ];
2176
- for (; i < tokens.length; i++) {
2177
- if (combinators.includes(tokens[i].typ)) {
2178
- if (i + 1 < tokens.length && [EnumToken.WhitespaceTokenType, EnumToken.DescendantCombinatorTokenType].includes(tokens[i + 1].typ)) {
2179
- tokens.splice(i + 1, 1);
2180
- }
2181
- if (i > 0 && [EnumToken.WhitespaceTokenType, EnumToken.DescendantCombinatorTokenType].includes(tokens[i - 1].typ)) {
2182
- tokens.splice(i - 1, 1);
2183
- i--;
2184
- continue;
2185
- }
2186
- }
2187
- if (tokens[i].typ == EnumToken.WhitespaceTokenType) {
2188
- tokens[i].typ = EnumToken.DescendantCombinatorTokenType;
2189
- }
2190
- }
2191
- return tokens;
2192
- }
2193
- /**
2194
- * parse css string and return an array of tokens
2576
+ * Parse css string and return an array of tokens
2195
2577
  * @param src
2196
2578
  * @param options
2197
- *
2198
- * @private
2579
+ * - parseColor: parse identifiers as colors
2580
+ * - src: source url used for source map
2581
+ * @param errors capture parse errors in the provided array
2582
+
2199
2583
  *
2200
2584
  * Example:
2201
2585
  *
@@ -2206,206 +2590,35 @@ function parseSelector(tokens) {
2206
2590
  * let tokens = parseString('body { color: red; }');
2207
2591
  * console.log(tokens);
2208
2592
  *
2209
- * tokens = parseString('#c322c980');
2593
+ * tokens = parseString('#c322c980');
2210
2594
  * console.log(tokens);
2211
2595
  * ```
2212
2596
  */
2213
- function parseString(src, options = { location: false }) {
2597
+ function parseString(src, options = { parseColor: true }, errors) {
2214
2598
  const parseInfo = {
2215
2599
  stream: src,
2216
- buffer: '',
2600
+ src: options?.src ?? "",
2601
+ buffer: "",
2217
2602
  offset: 0,
2603
+ time: 0,
2218
2604
  position: { ind: 0, lin: 1, col: 1 },
2219
- currentPosition: { ind: -1, lin: 1, col: 0 }
2605
+ currentPosition: { ind: -1, lin: 1, col: 0 },
2220
2606
  };
2221
- return parseTokens([...tokenize(parseInfo)].reduce((acc, t) => {
2222
- if (t.hint == EnumToken.EOFTokenType) {
2223
- return acc;
2224
- }
2225
- const token = getTokenType(t.token, t.hint);
2226
- Object.defineProperty(token, 'loc', {
2227
- ...definedPropertySettings,
2228
- value: { sta: t.sta },
2229
- enumerable: options.location !== false
2230
- });
2231
- acc.push(token);
2232
- return acc;
2233
- }, []));
2234
- }
2235
- /**
2236
- * get the token type from a string
2237
- * @param val
2238
- * @param hint
2239
- */
2240
- function getTokenType(val, hint) {
2241
- if (hint != null) {
2242
- return enumTokenHints.has(hint) ? { typ: hint } : { typ: hint, val };
2243
- }
2244
- switch (val) {
2245
- case ' ':
2246
- return { typ: EnumToken.WhitespaceTokenType };
2247
- case ';':
2248
- return { typ: EnumToken.SemiColonTokenType };
2249
- case '{':
2250
- return { typ: EnumToken.BlockStartTokenType };
2251
- case '}':
2252
- return { typ: EnumToken.BlockEndTokenType };
2253
- case '[':
2254
- return { typ: EnumToken.AttrStartTokenType };
2255
- case ']':
2256
- return { typ: EnumToken.AttrEndTokenType };
2257
- case ':':
2258
- return { typ: EnumToken.ColonTokenType };
2259
- case ')':
2260
- return { typ: EnumToken.EndParensTokenType };
2261
- case '(':
2262
- return { typ: EnumToken.StartParensTokenType };
2263
- case '=':
2264
- return { typ: EnumToken.DelimTokenType };
2265
- case ',':
2266
- return { typ: EnumToken.CommaTokenType };
2267
- case '<':
2268
- return { typ: EnumToken.LtTokenType };
2269
- case '>':
2270
- return { typ: EnumToken.GtTokenType };
2271
- }
2272
- if (val.charAt(0) == ':' && isPseudo(val)) {
2273
- return val.endsWith('(') ? {
2274
- typ: EnumToken.PseudoClassFuncTokenType,
2275
- val: val.slice(0, -1),
2276
- chi: []
2277
- }
2278
- : (
2279
- // https://www.w3.org/TR/selectors-4/#single-colon-pseudos
2280
- val.startsWith('::') || pseudoElements.includes(val) ? {
2281
- typ: EnumToken.PseudoElementTokenType,
2282
- val
2283
- } :
2284
- {
2285
- typ: EnumToken.PseudoClassTokenType,
2286
- val
2287
- });
2607
+ const result = parseTokens([...tokenize(parseInfo)].map((t) => t.token), options, errors);
2608
+ // remove EOF token
2609
+ result.pop();
2610
+ if (result.at(-1)?.typ === EnumToken.WhitespaceTokenType) {
2611
+ result.pop();
2288
2612
  }
2289
- if (val.charAt(0) == '@' && isAtKeyword(val)) {
2290
- return {
2291
- typ: EnumToken.AtRuleTokenType,
2292
- val: val.slice(1)
2293
- };
2294
- }
2295
- if (val.endsWith('(') && isFunction(val)) {
2296
- val = val.slice(0, -1);
2297
- if (val == 'url') {
2298
- return {
2299
- typ: EnumToken.UrlFunctionTokenType,
2300
- val,
2301
- chi: []
2302
- };
2303
- }
2304
- if (['linear-gradient', 'radial-gradient', 'repeating-linear-gradient', 'repeating-radial-gradient', 'conic-gradient', 'image', 'image-set', 'element', 'cross-fade', 'paint'].includes(val)) {
2305
- return {
2306
- typ: EnumToken.ImageFunctionTokenType,
2307
- val,
2308
- chi: []
2309
- };
2310
- }
2311
- if (timingFunc.includes(val.toLowerCase())) {
2312
- return {
2313
- typ: EnumToken.TimingFunctionTokenType,
2314
- val,
2315
- chi: []
2316
- };
2317
- }
2318
- if (timelineFunc.includes(val)) {
2319
- return {
2320
- typ: EnumToken.TimelineFunctionTokenType,
2321
- val,
2322
- chi: []
2323
- };
2324
- }
2325
- return {
2326
- typ: EnumToken.FunctionTokenType,
2327
- val,
2328
- chi: []
2329
- };
2330
- }
2331
- if (isNumber(val)) {
2332
- return {
2333
- typ: EnumToken.NumberTokenType,
2334
- val: +val
2335
- };
2336
- }
2337
- if (isPercentage(val)) {
2338
- return {
2339
- typ: EnumToken.PercentageTokenType,
2340
- val: +val.slice(0, -1)
2341
- };
2342
- }
2343
- const dimension = parseDimension(val);
2344
- if (dimension != null) {
2345
- return dimension;
2346
- }
2347
- const v = val.toLowerCase();
2348
- if (v == 'currentcolor' || v == 'transparent' || v in COLORS_NAMES) {
2349
- return {
2350
- typ: EnumToken.ColorTokenType,
2351
- val: v,
2352
- kin: ColorType.LIT
2353
- };
2354
- }
2355
- if (isIdent(val)) {
2356
- if (systemColors.has(v)) {
2357
- return {
2358
- typ: EnumToken.ColorTokenType,
2359
- val,
2360
- kin: ColorType.SYS
2361
- };
2362
- }
2363
- if (deprecatedSystemColors.has(v)) {
2364
- return {
2365
- typ: EnumToken.ColorTokenType,
2366
- val,
2367
- kin: ColorType.DPSYS
2368
- };
2369
- }
2370
- return {
2371
- typ: val.startsWith('--') ? EnumToken.DashedIdenTokenType : EnumToken.IdenTokenType,
2372
- val
2373
- };
2374
- }
2375
- if (val.charAt(0) == '.' && isIdent(val.slice(1))) {
2376
- return {
2377
- typ: EnumToken.ClassSelectorTokenType,
2378
- val
2379
- };
2380
- }
2381
- if (val.charAt(0) == '#' && isHexColor(val)) {
2382
- return {
2383
- typ: EnumToken.ColorTokenType,
2384
- val,
2385
- kin: ColorType.HEX
2386
- };
2387
- }
2388
- if (val.charAt(0) == '#' && isHash(val)) {
2389
- return {
2390
- typ: EnumToken.HashTokenType,
2391
- val
2392
- };
2393
- }
2394
- if ('"\''.includes(val.charAt(0))) {
2395
- return {
2396
- typ: EnumToken.UnclosedStringTokenType,
2397
- val
2398
- };
2399
- }
2400
- return {
2401
- typ: EnumToken.LiteralTokenType,
2402
- val
2403
- };
2613
+ return result;
2404
2614
  }
2405
2615
  /**
2406
- * parse function tokens in a token array
2616
+ * Parse function tokens in a token array
2407
2617
  * @param tokens
2408
2618
  * @param options
2619
+ * - parseColor: parse identifiers as colors
2620
+ * @param errors parse errors
2621
+ *
2409
2622
  *
2410
2623
  * Example:
2411
2624
  *
@@ -2422,62 +2635,157 @@ function getTokenType(val, hint) {
2422
2635
  *
2423
2636
  * @private
2424
2637
  */
2425
- function parseTokens(tokens, options = {}) {
2426
- for (let i = 0; i < tokens.length; i++) {
2427
- const t = tokens[i];
2428
- if (t.typ == EnumToken.IdenTokenType && t.val == 'from' && i > 0) {
2429
- const left = [];
2430
- const right = [];
2431
- let foundLeft = 0;
2432
- let foundRight = 0;
2433
- let k = i;
2434
- let l = i;
2435
- while (k > 0) {
2436
- if (tokens[k - 1].typ == EnumToken.CommentTokenType || tokens[k - 1].typ == EnumToken.WhitespaceTokenType) {
2437
- left.push(tokens[--k]);
2438
- continue;
2439
- }
2440
- if (tokens[k - 1].typ == EnumToken.IdenTokenType || tokens[k - 1].typ == EnumToken.DashedIdenTokenType) {
2441
- foundLeft++;
2442
- left.push(tokens[--k]);
2443
- continue;
2444
- }
2445
- break;
2638
+ function parseTokens(tokens, options, errors) {
2639
+ const stack = [];
2640
+ let i = 0;
2641
+ let index;
2642
+ let t;
2643
+ options ??= { parseColor: true };
2644
+ for (; i < tokens.length; i++) {
2645
+ t = tokens[i];
2646
+ if (t.typ === EnumToken.FunctionTokenDefType) {
2647
+ if (tokens[i - 1]?.typ === EnumToken.ColonTokenType ||
2648
+ tokens[i - 1]?.typ === EnumToken.DoubleColonTokenType) {
2649
+ t = Object.assign(tokens[i - 1], {
2650
+ typ: EnumToken.PseudoClassFunctionTokenDefType,
2651
+ val: (tokens[i - 1].typ === EnumToken.ColonTokenType ? ":" : "::") +
2652
+ tokens[i].val,
2653
+ });
2654
+ t.loc.end = tokens[i].loc.end;
2655
+ tokens.splice(i--, 1);
2446
2656
  }
2447
- while (++l < tokens.length) {
2448
- if (tokens[l].typ == EnumToken.CommentTokenType || tokens[l].typ == EnumToken.WhitespaceTokenType) {
2449
- right.push(tokens[l]);
2450
- continue;
2657
+ }
2658
+ if (t.typ === EnumToken.AttrStartTokenType ||
2659
+ t.typ === EnumToken.StartParensTokenType ||
2660
+ tokensfuncDefMap.has(t.typ)) {
2661
+ stack.push(t);
2662
+ continue;
2663
+ }
2664
+ if (t.typ === EnumToken.EndParensTokenType) {
2665
+ if (stack.length === 0 ||
2666
+ (stack.at(-1)?.typ !== EnumToken.StartParensTokenType && !tokensfuncDefMap.has(stack.at(-1)?.typ))) {
2667
+ // unbalanced parens
2668
+ const node = stack.at(-1);
2669
+ errors?.push?.({
2670
+ action: "drop",
2671
+ message: `Unbalanced token ')' at ${node.loc.src}:${node.loc.sta.lin}:${node.loc.sta.col}`,
2672
+ node,
2673
+ location: node.loc,
2674
+ });
2675
+ // return [];
2676
+ continue;
2677
+ }
2678
+ tokens.splice(i, 1);
2679
+ index = tokens.indexOf(stack.at(-1));
2680
+ Object.assign(tokens[index], {
2681
+ typ: tokens[index].typ === EnumToken.StartParensTokenType
2682
+ ? EnumToken.ParensTokenType
2683
+ : tokensfuncDefMap.get(tokens[index].typ),
2684
+ chi: trimArray(tokens.splice(index + 1, i - index - 1)),
2685
+ });
2686
+ i = index;
2687
+ if (tokens[index].typ === EnumToken.ColorTokenType && options?.parseColor) {
2688
+ parseColor(tokens[index]);
2689
+ }
2690
+ stack.pop();
2691
+ continue;
2692
+ }
2693
+ if (t.typ === EnumToken.AttrEndTokenType) {
2694
+ if (stack.at(-1)?.typ !== EnumToken.AttrStartTokenType) {
2695
+ // unbalanced
2696
+ const node = stack.at(-1);
2697
+ errors?.push?.({
2698
+ action: "drop",
2699
+ message: `Unbalanced token ']' at ${node.loc.src}:${node.loc.sta.lin}:${node.loc.sta.col}`,
2700
+ node,
2701
+ location: node.loc,
2702
+ });
2703
+ // return [];
2704
+ continue;
2705
+ }
2706
+ index = tokens.indexOf(stack.at(-1));
2707
+ const attr = stack.at(-1);
2708
+ attr.loc.end = t.loc.end;
2709
+ tokens.splice(i, 1);
2710
+ Object.assign(attr, {
2711
+ typ: EnumToken.AttrTokenType,
2712
+ chi: tokens.splice(index + 1, i - index - 1),
2713
+ });
2714
+ tokens[index] = attr;
2715
+ i = index;
2716
+ stack.pop();
2717
+ continue;
2718
+ }
2719
+ if (t.typ == EnumToken.IdenTokenType) {
2720
+ if (t.val == "from" && i > 0) {
2721
+ const left = [];
2722
+ const right = [];
2723
+ let foundLeft = 0;
2724
+ let foundRight = 0;
2725
+ let k = i;
2726
+ let l = i;
2727
+ while (k > 0) {
2728
+ if (tokens[k - 1].typ == EnumToken.CommentTokenType ||
2729
+ tokens[k - 1].typ == EnumToken.WhitespaceTokenType) {
2730
+ left.push(tokens[--k]);
2731
+ continue;
2732
+ }
2733
+ if (tokens[k - 1].typ == EnumToken.IdenTokenType ||
2734
+ tokens[k - 1].typ == EnumToken.DashedIdenTokenType) {
2735
+ foundLeft++;
2736
+ left.push(tokens[--k]);
2737
+ continue;
2738
+ }
2739
+ break;
2451
2740
  }
2452
- if (tokens[l].typ == EnumToken.IdenTokenType || tokens[l].typ == EnumToken.StringTokenType) {
2453
- foundRight++;
2454
- right.push(tokens[l]);
2741
+ while (++l < tokens.length) {
2742
+ if (tokens[l].typ == EnumToken.CommentTokenType || tokens[l].typ == EnumToken.WhitespaceTokenType) {
2743
+ right.push(tokens[l]);
2744
+ continue;
2745
+ }
2746
+ if (tokens[l].typ == EnumToken.IdenTokenType || tokens[l].typ == EnumToken.StringTokenType) {
2747
+ foundRight++;
2748
+ right.push(tokens[l]);
2749
+ continue;
2750
+ }
2751
+ break;
2752
+ }
2753
+ if (foundLeft > 0 && foundRight == 1) {
2754
+ while (left?.[0].typ == EnumToken.WhitespaceTokenType) {
2755
+ left.shift();
2756
+ }
2757
+ while (left.at(-1)?.typ == EnumToken.WhitespaceTokenType) {
2758
+ left.pop();
2759
+ }
2760
+ tokens.splice(k, l - k + 1, {
2761
+ typ: EnumToken.ComposesSelectorNodeType,
2762
+ l: left,
2763
+ r: right.reduce((a, b) => {
2764
+ return a == null
2765
+ ? b
2766
+ : b.typ == EnumToken.IdenTokenType || b.typ == EnumToken.StringTokenType
2767
+ ? b
2768
+ : a;
2769
+ }, null),
2770
+ });
2771
+ i = k;
2455
2772
  continue;
2456
2773
  }
2457
- break;
2458
2774
  }
2459
- if (foundLeft > 0 && foundRight == 1) {
2460
- while (left?.[0].typ == EnumToken.WhitespaceTokenType) {
2461
- left.shift();
2462
- }
2463
- while (left.at(-1)?.typ == EnumToken.WhitespaceTokenType) {
2464
- left.pop();
2465
- }
2466
- tokens.splice(k, l - k + 1, {
2467
- typ: EnumToken.ComposesSelectorNodeType,
2468
- l: left,
2469
- r: right.reduce((a, b) => {
2470
- return a == null ? b : b.typ == EnumToken.IdenTokenType || b.typ == EnumToken.StringTokenType ? b : a;
2471
- }, null)
2472
- });
2473
- i = k;
2474
- continue;
2775
+ else if (options?.parseColor && isColor(t)) {
2776
+ parseColor(t);
2475
2777
  }
2476
2778
  }
2477
- if (t.typ == EnumToken.WhitespaceTokenType && ((i == 0 ||
2478
- i + 1 == tokens.length ||
2479
- [EnumToken.CommaTokenType, EnumToken.GteTokenType, EnumToken.LteTokenType, EnumToken.ColumnCombinatorTokenType].includes(tokens[i + 1].typ)) ||
2480
- (i > 0 && trimWhiteSpace.includes(tokens[i - 1].typ)))) {
2779
+ if (t.typ == EnumToken.WhitespaceTokenType &&
2780
+ (i == 0 ||
2781
+ i + 1 == tokens.length ||
2782
+ [
2783
+ EnumToken.CommaTokenType,
2784
+ EnumToken.GteTokenType,
2785
+ EnumToken.LteTokenType,
2786
+ EnumToken.ColumnCombinatorTokenType,
2787
+ ].includes(tokens[i + 1].typ) ||
2788
+ (i > 0 && trimWhiteSpace.includes(tokens[i - 1].typ)))) {
2481
2789
  tokens.splice(i--, 1);
2482
2790
  continue;
2483
2791
  }
@@ -2488,7 +2796,7 @@ function parseTokens(tokens, options = {}) {
2488
2796
  tokens[i + 1].typ = EnumToken.PseudoClassFuncTokenType;
2489
2797
  }
2490
2798
  else if (typ == EnumToken.IdenTokenType) {
2491
- tokens[i + 1].val = ':' + tokens[i + 1].val;
2799
+ tokens[i + 1].val = ":" + tokens[i + 1].val;
2492
2800
  tokens[i + 1].typ = EnumToken.PseudoClassTokenType;
2493
2801
  }
2494
2802
  if (typ == EnumToken.FunctionTokenType || typ == EnumToken.IdenTokenType) {
@@ -2496,265 +2804,28 @@ function parseTokens(tokens, options = {}) {
2496
2804
  i--;
2497
2805
  }
2498
2806
  }
2499
- continue;
2500
- }
2501
- if (t.typ == EnumToken.AttrStartTokenType) {
2502
- let k = i;
2503
- let inAttr = 1;
2504
- while (++k < tokens.length) {
2505
- if (tokens[k].typ == EnumToken.AttrEndTokenType) {
2506
- inAttr--;
2507
- }
2508
- else if (tokens[k].typ == EnumToken.AttrStartTokenType) {
2509
- inAttr++;
2510
- }
2511
- if (inAttr == 0) {
2512
- break;
2513
- }
2514
- }
2515
- const attr = Object.assign(t, {
2516
- typ: inAttr == 0 ? EnumToken.AttrTokenType : EnumToken.InvalidAttrTokenType,
2517
- chi: tokens.splice(i + 1, k - i)
2518
- });
2519
- // @ts-ignore
2520
- if (attr.chi.at(-1).typ == EnumToken.AttrEndTokenType) {
2521
- // @ts-ignore
2522
- attr.chi.pop();
2523
- }
2524
- // @ts-ignore
2525
- if (attr.chi.length > 1) {
2526
- // @ts-ignore
2527
- parseTokens(attr.chi, t.typ);
2528
- }
2529
- let m = attr.chi.length;
2530
- let val;
2531
- for (m = 0; m < attr.chi.length; m++) {
2532
- val = attr.chi[m];
2533
- if (val.typ == EnumToken.StringTokenType) {
2534
- const slice = val.val.slice(1, -1);
2535
- if ((slice.charAt(0) != '-' || (slice.charAt(0) == '-' && isIdentStart(slice.charCodeAt(1)))) && isIdent(slice)) {
2536
- Object.assign(val, { typ: EnumToken.IdenTokenType, val: slice });
2537
- }
2538
- }
2539
- else if (val.typ == EnumToken.LiteralTokenType && val.val == '|') {
2540
- let upper = m;
2541
- let lower = m;
2542
- while (++upper < attr.chi.length) {
2543
- if (attr.chi[upper].typ == EnumToken.CommentTokenType) {
2544
- continue;
2545
- }
2546
- break;
2547
- }
2548
- while (lower-- > 0) {
2549
- if (attr.chi[lower].typ == EnumToken.CommentTokenType) {
2550
- continue;
2551
- }
2552
- break;
2553
- }
2554
- // @ts-ignore
2555
- attr.chi[m] = {
2556
- typ: EnumToken.NameSpaceAttributeTokenType,
2557
- l: attr.chi[lower],
2558
- r: attr.chi[upper]
2559
- };
2560
- attr.chi.splice(upper, 1);
2561
- if (lower >= 0) {
2562
- attr.chi.splice(lower, 1);
2563
- m--;
2564
- }
2565
- }
2566
- else if ([
2567
- EnumToken.DashMatchTokenType, EnumToken.StartMatchTokenType, EnumToken.ContainMatchTokenType, EnumToken.EndMatchTokenType, EnumToken.IncludeMatchTokenType, EnumToken.DelimTokenType
2568
- ].includes(attr.chi[m].typ)) {
2569
- let upper = m;
2570
- let lower = m;
2571
- while (++upper < attr.chi.length) {
2572
- if (attr.chi[upper].typ == EnumToken.CommentTokenType) {
2573
- continue;
2574
- }
2575
- break;
2576
- }
2577
- while (lower-- > 0) {
2578
- if (attr.chi[lower].typ == EnumToken.CommentTokenType) {
2579
- continue;
2580
- }
2581
- break;
2582
- }
2583
- val = attr.chi[lower];
2584
- if (val.typ == EnumToken.StringTokenType) {
2585
- const slice = val.val.slice(1, -1);
2586
- if ((slice.charAt(0) != '-' || (slice.charAt(0) == '-' && isIdentStart(slice.charCodeAt(1)))) && isIdent(slice)) {
2587
- Object.assign(val, { typ: EnumToken.IdenTokenType, val: slice });
2588
- }
2589
- }
2590
- val = attr.chi[upper];
2591
- if (val.typ == EnumToken.StringTokenType) {
2592
- const slice = val.val.slice(1, -1);
2593
- if ((slice.charAt(0) != '-' || (slice.charAt(0) == '-' && isIdentStart(slice.charCodeAt(1)))) && isIdent(slice)) {
2594
- Object.assign(val, { typ: EnumToken.IdenTokenType, val: slice });
2595
- }
2596
- }
2597
- // @ts-ignore
2598
- const typ = t.chi[m].typ;
2599
- // @ts-ignore
2600
- t.chi[m] = {
2601
- typ: EnumToken.MatchExpressionTokenType,
2602
- op: {
2603
- // @ts-ignore
2604
- typ: typ == EnumToken.DelimTokenType ? EnumToken.EqualMatchTokenType : typ
2605
- },
2606
- l: t.chi[lower],
2607
- r: t.chi[upper]
2608
- };
2609
- if (isIdentColor(t.chi[m].l)) {
2610
- t.chi[m].l.typ = EnumToken.IdenTokenType;
2611
- }
2612
- if (isIdentColor(t.chi[m].r)) {
2613
- t.chi[m].r.typ = EnumToken.IdenTokenType;
2614
- }
2615
- t.chi.splice(upper, 1);
2616
- t.chi.splice(lower, 1);
2617
- upper = m;
2618
- m--;
2619
- while (upper < t.chi.length && t.chi[upper].typ == EnumToken.WhitespaceTokenType) {
2620
- upper++;
2621
- }
2622
- if (upper < t.chi.length &&
2623
- t.chi[upper].typ == EnumToken.IdenTokenType &&
2624
- ['i', 's'].includes(t.chi[upper].val.toLowerCase())) {
2625
- t.chi[m].attr = t.chi[upper].val;
2626
- t.chi.splice(upper, 1);
2627
- }
2628
- }
2629
- }
2630
- m = t.chi.length;
2631
- while (t.chi.at(-1)?.typ == EnumToken.WhitespaceTokenType) {
2632
- t.chi.pop();
2633
- }
2634
- continue;
2635
2807
  }
2636
- if (funcLike.includes(t.typ)) {
2637
- let parens = 1;
2638
- let k = i;
2639
- while (++k < tokens.length) {
2640
- if (tokens[k].typ == EnumToken.ColonTokenType) {
2641
- const typ = tokens[k + 1]?.typ;
2642
- if (typ != null) {
2643
- if (typ == EnumToken.IdenTokenType) {
2644
- tokens[k + 1].typ = EnumToken.PseudoClassTokenType;
2645
- tokens[k + 1].val = ':' + tokens[k + 1].val;
2646
- }
2647
- else if (typ == EnumToken.FunctionTokenType) {
2648
- tokens[k + 1].typ = EnumToken.PseudoClassFuncTokenType;
2649
- tokens[k + 1].val = ':' + tokens[k + 1].val;
2650
- }
2651
- if (typ == EnumToken.FunctionTokenType || typ == EnumToken.IdenTokenType) {
2652
- tokens.splice(k, 1);
2653
- k--;
2654
- continue;
2655
- }
2656
- }
2657
- }
2658
- if (funcLike.includes(tokens[k].typ)) {
2659
- parens++;
2660
- }
2661
- else if (tokens[k].typ == EnumToken.EndParensTokenType) {
2662
- parens--;
2663
- }
2664
- if (parens == 0) {
2665
- break;
2666
- }
2667
- }
2668
- // @ts-ignore
2669
- t.chi = tokens.splice(i + 1, k - i);
2670
- // @ts-ignore
2671
- if (t.chi.at(-1)?.typ == EnumToken.EndParensTokenType) {
2672
- // @ts-ignore
2673
- t.chi.pop();
2674
- }
2675
- // @ts-ignore
2676
- if (t.chi.length > 0) {
2677
- // @ts-ignore
2678
- parseTokens(t.chi, options);
2679
- }
2680
- if (t.typ == EnumToken.FunctionTokenType && mathFuncs.includes(t.val)) {
2681
- for (const { value, parent } of walkValues(t.chi)) {
2682
- if (value.typ == EnumToken.WhitespaceTokenType) {
2683
- const p = (parent ?? t);
2684
- for (let i = 0; i < (p).chi.length; i++) {
2685
- // @ts-ignore
2686
- if (p.chi[i] == value) {
2687
- // @ts-ignore
2688
- (p).chi.splice(i, 1);
2689
- i--;
2690
- break;
2691
- }
2692
- }
2693
- }
2694
- else if (value.typ == EnumToken.LiteralTokenType && ['+', '-', '/', '*'].includes(value.val)) {
2695
- // @ts-ignore
2696
- value.typ = value.val == '+' ? EnumToken.Add : (value.val == '-' ? EnumToken.Sub : (value.val == '*' ? EnumToken.Mul : EnumToken.Div));
2697
- // @ts-ignore
2698
- delete value.val;
2699
- }
2700
- }
2701
- t.chi = splitTokenList(t.chi).reduce((acc, t) => {
2702
- if (acc.length > 0) {
2703
- acc.push({ typ: EnumToken.CommaTokenType });
2704
- }
2705
- acc.push(buildExpression(t));
2706
- return acc;
2707
- }, []);
2708
- }
2709
- else if (t.typ == EnumToken.FunctionTokenType && ['minmax', 'fit-content', 'repeat'].includes(t.val)) {
2710
- // @ts-ignore
2711
- t.typ = EnumToken.GridTemplateFuncTokenType;
2712
- }
2713
- else if (t.typ == EnumToken.StartParensTokenType) {
2714
- // @ts-ignore
2715
- t.typ = EnumToken.ParensTokenType;
2716
- }
2717
- // @ts-ignore
2718
- if (options.parseColor && t.typ == EnumToken.FunctionTokenType && isColor(t)) {
2719
- parseColor(t);
2720
- continue;
2721
- }
2722
- if (t.typ == EnumToken.UrlFunctionTokenType) {
2723
- // @ts-ignore
2724
- if (t.chi[0]?.typ == EnumToken.StringTokenType) {
2725
- // @ts-ignore
2726
- const value = t.chi[0].val.slice(1, -1);
2727
- // @ts-ignore
2728
- if (t.chi[0].val.slice(1, 5) != 'data:' && urlTokenMatcher.test(value)) {
2729
- // @ts-ignore
2730
- t.chi[0].typ = EnumToken.UrlTokenTokenType;
2731
- // @ts-ignore
2732
- t.chi[0].val = options.src !== '' && options.resolveUrls ? options.resolve(value, options.src).absolute : value;
2733
- }
2734
- }
2735
- if (t.chi[0]?.typ == EnumToken.UrlTokenTokenType) {
2736
- if (options.src !== '' && options.resolveUrls) {
2737
- // @ts-ignore
2738
- t.chi[0].val = options.resolve(t.chi[0].val, options.src, options.cwd).relative;
2739
- }
2740
- }
2808
+ if (t.typ === EnumToken.CommaTokenType) {
2809
+ if (tokens[i + 1]?.typ === EnumToken.WhitespaceTokenType) {
2810
+ tokens.splice(i + 1, 1);
2741
2811
  }
2742
- // @ts-ignore
2743
- if (t.chi.length > 0) {
2744
- if (t.typ == EnumToken.PseudoClassFuncTokenType && t.val == ':is' && options.minify) {
2745
- const count = t.chi.filter((t) => t.typ != EnumToken.CommentTokenType).length;
2746
- if (count == 1 ||
2747
- (i == 0 &&
2748
- (tokens[i + 1]?.typ == EnumToken.CommaTokenType || tokens.length == i + 1)) ||
2749
- (tokens[i - 1]?.typ == EnumToken.CommaTokenType && (tokens[i + 1]?.typ == EnumToken.CommaTokenType || tokens.length == i + 1))) {
2750
- tokens.splice(i, 1, ...t.chi);
2751
- i = Math.max(0, i - t.chi.length);
2752
- }
2753
- }
2812
+ if (tokens[i - 1]?.typ === EnumToken.WhitespaceTokenType) {
2813
+ tokens.splice(i - 1, 1);
2814
+ i--;
2754
2815
  }
2755
2816
  }
2756
2817
  }
2818
+ if (stack.length > 0) {
2819
+ const node = stack.at(-1);
2820
+ errors?.push?.({
2821
+ action: "drop",
2822
+ message: `Unbalanced token. Expecting ${node.typ === EnumToken.AttrStartTokenType ? "']'" : ")"}'`,
2823
+ node,
2824
+ location: node.loc,
2825
+ });
2826
+ // return [];
2827
+ }
2757
2828
  return tokens;
2758
2829
  }
2759
2830
 
2760
- export { doParse, generateScopedName, getKeyName, getTokenType, parseAtRulePrelude, parseDeclarations, parseSelector, parseString, parseTokens, replaceToken, urlTokenMatcher };
2831
+ export { doParse, generateScopedName, getKeyName, getShortNameGenerator, parseAtRule, parseDeclarations, parseString, parseTokens, trimWhiteSpace };