@tbela99/css-parser 1.4.8 → 1.4.10

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 (56) hide show
  1. package/CHANGELOG.md +32 -3
  2. package/README.md +1 -1
  3. package/dist/index-umd-web.js +12950 -13310
  4. package/dist/index.cjs +16447 -16809
  5. package/dist/index.d.ts +2481 -1754
  6. package/dist/lib/ast/features/calc.js +3 -1
  7. package/dist/lib/ast/features/if.js +2 -96
  8. package/dist/lib/ast/features/prefix.js +7 -2
  9. package/dist/lib/ast/features/shorthand.js +1 -1
  10. package/dist/lib/ast/features/transform.js +1 -1
  11. package/dist/lib/ast/find.js +6 -6
  12. package/dist/lib/ast/math/expression.js +30 -12
  13. package/dist/lib/ast/math/math.js +2 -1
  14. package/dist/lib/ast/minify.js +34 -5
  15. package/dist/lib/ast/transform/compute.js +2 -1
  16. package/dist/lib/ast/transform/perspective.js +1 -1
  17. package/dist/lib/ast/transform/utils.js +29 -21
  18. package/dist/lib/ast/types.js +9 -66
  19. package/dist/lib/fs/resolve.js +1 -16
  20. package/dist/lib/parser/declaration/list.js +6 -1
  21. package/dist/lib/parser/{linemap.js → linesmap.js} +25 -9
  22. package/dist/lib/parser/parse.js +1264 -151
  23. package/dist/lib/parser/source.js +48 -17
  24. package/dist/lib/parser/tokenize.js +112 -133
  25. package/dist/lib/parser/utils/at-rule-container.js +12 -44
  26. package/dist/lib/parser/utils/at-rule-generic.js +12 -24
  27. package/dist/lib/parser/utils/at-rule-import.js +4 -172
  28. package/dist/lib/parser/utils/at-rule-media.js +14 -251
  29. package/dist/lib/parser/utils/at-rule-support.js +8 -258
  30. package/dist/lib/parser/utils/at-rule-when-else.js +4 -214
  31. package/dist/lib/parser/utils/declaration.js +5 -95
  32. package/dist/lib/parser/utils/hash.js +54 -1
  33. package/dist/lib/parser/utils/selector.js +1 -1
  34. package/dist/lib/parser/utils/token.js +1 -0
  35. package/dist/lib/renderer/render.js +79 -87
  36. package/dist/lib/renderer/sourcemap/sourcemap.js +47 -43
  37. package/dist/lib/syntax/color/cmyk.js +3 -3
  38. package/dist/lib/syntax/color/color-mix.js +7 -7
  39. package/dist/lib/syntax/color/color.js +9 -27
  40. package/dist/lib/syntax/color/hsl.js +6 -6
  41. package/dist/lib/syntax/color/hwb.js +6 -6
  42. package/dist/lib/syntax/color/lab.js +5 -5
  43. package/dist/lib/syntax/color/lch.js +6 -6
  44. package/dist/lib/syntax/color/oklab.js +5 -5
  45. package/dist/lib/syntax/color/oklch.js +5 -5
  46. package/dist/lib/syntax/color/relative-color.js +8 -1
  47. package/dist/lib/syntax/color/utils/distance.js +2 -1
  48. package/dist/lib/syntax/constants.js +2 -1
  49. package/dist/lib/syntax/syntax.js +96 -9
  50. package/dist/lib/validation/config.json.js +27 -6
  51. package/dist/lib/validation/match.js +42 -845
  52. package/dist/node.js +134 -9
  53. package/dist/web.js +133 -6
  54. package/llms.txt +73 -0
  55. package/package.json +13 -16
  56. package/dist/lib/parser/arena.js +0 -206
@@ -7,7 +7,7 @@ import { expand } from '../ast/expand.js';
7
7
  import { WalkerEvent, walk, walkValues } from '../ast/walk.js';
8
8
  import { tokenizeStream, tokenize } from './tokenize.js';
9
9
  import { ROOT, LOC, tokensfuncDefMap, STATE, PARENT, TOKENS, ERRORS, pageMarginBoxType } from '../syntax/constants.js';
10
- import { hashAlgorithms, hash } from './utils/hash.js';
10
+ import { hashAlgorithms, hash, syncHash } from './utils/hash.js';
11
11
  import { parseSelector } from './utils/selector.js';
12
12
  import { parseDeclaration } from './utils/declaration.js';
13
13
  import { getSyntaxRule } from '../validation/config.js';
@@ -23,6 +23,7 @@ import { matchAtRuleSyntax } from './utils/at-rule.js';
23
23
  import { parseAtRuleFontFeatureValues } from './utils/at-rule-font-feature-values.js';
24
24
  import { matchGenericSyntax } from './utils/at-rule-generic.js';
25
25
  import { memoize } from './utils/cache.js';
26
+ import { SourceFile } from './source.js';
26
27
 
27
28
  function renderTokens(tokens, options) {
28
29
  if (tokens == null || tokens.length === 0)
@@ -192,6 +193,1126 @@ const generateScopedName = memoize(async (localName, filePath, pattern, hashLeng
192
193
  // if leading char is digit, prefix underscore (very rare)
193
194
  return (/^[0-9]/.test(result) ? "_" : "") + result;
194
195
  });
196
+ const generateSyncScopedName = memoize((localName, filePath, pattern, hashLength = 5) => {
197
+ if (localName.startsWith("--")) {
198
+ localName = localName.slice(2);
199
+ }
200
+ const matches = /.*?(([^/]+)\/)?([^/\\]*?)(\.([^?/]+))?([?].*)?$/.exec(filePath);
201
+ const folder = matches?.[2]?.replace?.(/[^A-Za-z0-9_-]/g, "_") ?? "";
202
+ const fileBase = matches?.[3] ?? "";
203
+ const ext = matches?.[5] ?? "";
204
+ const path = filePath.replace(/[^A-Za-z0-9_-]/g, "_");
205
+ // sanitize localName for safe char set (replace spaces/illegal chars)
206
+ const safeLocal = localName.replace(/[^A-Za-z0-9_-]/g, "_");
207
+ const hashString = `${localName}::${filePath}`;
208
+ let result = "";
209
+ let inParens = 0;
210
+ let key = "";
211
+ let position = 0;
212
+ // Compose final scoped name. Ensure the entire class doesn't start with a digit:
213
+ for (const char of pattern) {
214
+ position += char.length;
215
+ if (char == "[") {
216
+ inParens++;
217
+ if (inParens != 1) {
218
+ throw new Error(`Unexpected character: '${char} at position ${position - 1}' in pattern '${pattern}'`);
219
+ }
220
+ continue;
221
+ }
222
+ if (char == "]") {
223
+ inParens--;
224
+ if (inParens != 0) {
225
+ throw new Error(`Unexpected character: '${char}:${position - 1}'`);
226
+ }
227
+ let hashAlgo = null;
228
+ let length = null;
229
+ if (key.includes(":")) {
230
+ const parts = key.split(":");
231
+ if (parts.length == 2) {
232
+ // @ts-ignore
233
+ [key, length] = parts;
234
+ // @ts-ignore
235
+ if (key == "hash" && hashAlgorithms.includes(length)) {
236
+ // @ts-ignore
237
+ hashAlgo = length;
238
+ length = null;
239
+ if (hashAlgo.startsWith("sha")) {
240
+ throw new Error(`Unsupported hash algorithm: '${hashAlgo}'. Not supported by parseSync() or transformSync(). Use parse() or transform().`);
241
+ }
242
+ }
243
+ }
244
+ if (parts.length == 3) {
245
+ // @ts-ignore
246
+ [key, hashAlgo, length] = parts;
247
+ }
248
+ if (length != null && !Number.isInteger(+length)) {
249
+ throw new Error(`Unsupported hash length: '${length}'. expecting format [hash:length] or [hash:hash-algo:length]`);
250
+ }
251
+ }
252
+ const slice = length != null && length != fileBase.length;
253
+ switch (key) {
254
+ case "hash":
255
+ result += syncHash(hashString, length ?? hashLength, hashAlgo);
256
+ break;
257
+ case "name":
258
+ // @ts-expect-error
259
+ result += slice ? fileBase.slice(0, +length) : fileBase;
260
+ break;
261
+ case "local":
262
+ // @ts-expect-error
263
+ result += slice ? safeLocal.slice(0, +length) : localName;
264
+ break;
265
+ case "ext":
266
+ // @ts-expect-error
267
+ result += slice ? ext.slice(0, +length) : ext;
268
+ break;
269
+ case "path":
270
+ // @ts-expect-error
271
+ result += slice ? path.slice(0, +length) : path;
272
+ break;
273
+ case "folder":
274
+ // @ts-expect-error
275
+ result += slice ? folder.slice(0, +length) : folder;
276
+ break;
277
+ default:
278
+ throw new Error(`Unsupported key: '${key}'`);
279
+ }
280
+ key = "";
281
+ continue;
282
+ }
283
+ if (inParens > 0) {
284
+ key += char;
285
+ }
286
+ else {
287
+ result += char;
288
+ }
289
+ }
290
+ // if leading char is digit, prefix underscore (very rare)
291
+ return (/^[0-9]/.test(result) ? "_" : "") + result;
292
+ });
293
+ /**
294
+ * Parse css string
295
+ * @param iter
296
+ * @param options
297
+ *
298
+ * @throws Error
299
+ * @private
300
+ */
301
+ function doParseSync(iter, options = {}) {
302
+ if (options.signal != null) {
303
+ options.signal.addEventListener("abort", reject);
304
+ }
305
+ options = {
306
+ src: "",
307
+ sourcemap: false,
308
+ minify: true,
309
+ pass: 1,
310
+ expandIfSyntax: false,
311
+ parseColor: true,
312
+ nestingRules: true,
313
+ resolveUrls: false,
314
+ removeCharset: true,
315
+ removeEmpty: true,
316
+ removeDuplicateDeclarations: true,
317
+ computeTransform: true,
318
+ computeShorthand: true,
319
+ computeCalcExpression: true,
320
+ inlineCssVariables: false,
321
+ setParent: true,
322
+ removePrefix: false,
323
+ validation: false,
324
+ lenient: true,
325
+ ...options,
326
+ };
327
+ if (typeof options.validation !== "boolean") {
328
+ options.validation = !!options.validation;
329
+ }
330
+ if (options.module) {
331
+ options.expandNestingRules = true;
332
+ }
333
+ if (options.expandNestingRules) {
334
+ options.nestingRules = false;
335
+ }
336
+ const startTime = performance.now();
337
+ const errors = [];
338
+ const stack = [];
339
+ const stats = {
340
+ src: options.src ?? "",
341
+ bytesIn: 0,
342
+ nodesCount: 0,
343
+ tokensCount: 0,
344
+ importedBytesIn: 0,
345
+ tokenize: `0ms`,
346
+ parse: `0ms`,
347
+ minify: `0ms`,
348
+ total: `0ms`,
349
+ imports: [],
350
+ };
351
+ const invalidNodes = [];
352
+ let ast = {
353
+ typ: EnumToken.StyleSheetNodeType,
354
+ chi: [],
355
+ };
356
+ let tokens = [];
357
+ let context = ast;
358
+ ast[ROOT] = ast;
359
+ ast[LOC] = {
360
+ sta: 0,
361
+ end: 0,
362
+ srcId: options.source.id,
363
+ };
364
+ let valuesHandlers;
365
+ let preValuesHandlers;
366
+ let postValuesHandlers;
367
+ let preVisitorsHandlersMap;
368
+ let visitorsHandlersMap;
369
+ let postVisitorsHandlersMap;
370
+ let item;
371
+ let node;
372
+ // @ts-ignore ignore error
373
+ let parensMatch = 0;
374
+ let curlyBracketMatch = 0;
375
+ if (options.visitor != null) {
376
+ valuesHandlers = new Map();
377
+ preValuesHandlers = new Map();
378
+ postValuesHandlers = new Map();
379
+ preVisitorsHandlersMap = new Map();
380
+ visitorsHandlersMap = new Map();
381
+ postVisitorsHandlersMap = new Map();
382
+ const visitors = Object.entries(options.visitor);
383
+ let key;
384
+ let value;
385
+ let i;
386
+ for (i = 0; i < visitors.length; i++) {
387
+ key = visitors[i][0];
388
+ value = visitors[i][1];
389
+ if (Number.isInteger(+key)) {
390
+ visitors.splice(i + 1, 0, ...Object.entries(value));
391
+ continue;
392
+ }
393
+ if (Array.isArray(value)) {
394
+ // @ts-ignore
395
+ visitors.splice(i + 1, 0, ...value.map((item) => [key, item]));
396
+ continue;
397
+ }
398
+ if (key in EnumToken) {
399
+ if (typeof value == "function") {
400
+ if (!valuesHandlers.has(EnumToken[key])) {
401
+ valuesHandlers.set(EnumToken[key], []);
402
+ }
403
+ valuesHandlers.get(EnumToken[key]).push(value);
404
+ }
405
+ else if (typeof value == "object" &&
406
+ "type" in value &&
407
+ "handler" in value &&
408
+ value.type in WalkerEvent) {
409
+ if (value.type == WalkerEvent.Enter) {
410
+ if (!preValuesHandlers.has(EnumToken[key])) {
411
+ preValuesHandlers.set(EnumToken[key], []);
412
+ }
413
+ preValuesHandlers
414
+ .get(EnumToken[key])
415
+ .push(value.handler);
416
+ }
417
+ else if (value.type == WalkerEvent.Leave) {
418
+ if (!postValuesHandlers.has(EnumToken[key])) {
419
+ postValuesHandlers.set(EnumToken[key], []);
420
+ }
421
+ postValuesHandlers
422
+ .get(EnumToken[key])
423
+ .push(value.handler);
424
+ }
425
+ }
426
+ else {
427
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
428
+ }
429
+ }
430
+ else if (["Declaration", "Rule", "AtRule", "KeyframesRule", "KeyframesAtRule"].includes(key)) {
431
+ if (typeof value == "function") {
432
+ if (!visitorsHandlersMap.has(key)) {
433
+ visitorsHandlersMap.set(key, []);
434
+ }
435
+ visitorsHandlersMap
436
+ .get(key)
437
+ .push(value);
438
+ }
439
+ else if (typeof value == "object") {
440
+ if ("type" in value && "handler" in value && value.type in WalkerEvent) {
441
+ if (value.type == WalkerEvent.Enter) {
442
+ if (!preVisitorsHandlersMap.has(key)) {
443
+ preVisitorsHandlersMap.set(key, []);
444
+ }
445
+ preVisitorsHandlersMap
446
+ .get(key)
447
+ .push(value.handler);
448
+ }
449
+ else if (value.type == WalkerEvent.Leave) {
450
+ if (!postVisitorsHandlersMap.has(key)) {
451
+ postVisitorsHandlersMap.set(key, []);
452
+ }
453
+ postVisitorsHandlersMap
454
+ .get(key)
455
+ .push(value.handler);
456
+ }
457
+ }
458
+ else {
459
+ if (!visitorsHandlersMap.has(key)) {
460
+ visitorsHandlersMap.set(key, []);
461
+ }
462
+ visitorsHandlersMap
463
+ .get(key)
464
+ .push(value);
465
+ }
466
+ }
467
+ else {
468
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
469
+ }
470
+ }
471
+ else {
472
+ errors.push({ action: "ignore", message: `doParse: visitor.${key} is not a valid key name` });
473
+ }
474
+ }
475
+ }
476
+ if (Array.isArray(iter)) {
477
+ // @ts-expect-error
478
+ iter = iter[Symbol.iterator]();
479
+ }
480
+ while (
481
+ // @ts-expect-error
482
+ (item = iter.next().value)) {
483
+ stats.bytesIn = item.bytesIn;
484
+ stats.tokensCount++;
485
+ if (BadTokensTypes.includes(item.token.typ)) {
486
+ tokens.push(item.token);
487
+ errors.push({
488
+ action: "drop",
489
+ message: "Bad token",
490
+ syntax: null,
491
+ node: item.token,
492
+ location: options.source.getSourceLocation(item.token[LOC].sta),
493
+ });
494
+ // bad token
495
+ continue;
496
+ }
497
+ if (item.token.typ === EnumToken.StartParensTokenType || tokensfuncDefMap.has(item.token.typ)) {
498
+ parensMatch++;
499
+ }
500
+ else if (item.token.typ === EnumToken.EndParensTokenType && parensMatch > 0) {
501
+ parensMatch--;
502
+ }
503
+ if (item.token.typ === EnumToken.BlockStartTokenType) {
504
+ curlyBracketMatch++;
505
+ }
506
+ else if (item.token.typ === EnumToken.BlockEndTokenType && curlyBracketMatch > 0) {
507
+ curlyBracketMatch--;
508
+ }
509
+ tokens.push(item.token);
510
+ // console.debug([item.token, {parensMatch, curlyBracketMatch}]);
511
+ // if (parensMatch === 0) {
512
+ if (parensMatch === 0 &&
513
+ (item.token.typ === EnumToken.SemiColonTokenType ||
514
+ item.token.typ === EnumToken.BlockStartTokenType ||
515
+ item.token.typ === EnumToken.EOFTokenType)) {
516
+ node = parseNode(tokens, context, options, errors, stats, invalidNodes);
517
+ if (node != null) {
518
+ if ("chi" in node) {
519
+ stack.push(node);
520
+ context = node;
521
+ }
522
+ }
523
+ else if (item.token.typ == EnumToken.BlockStartTokenType) {
524
+ let inBlock = 1;
525
+ tokens = [item.token];
526
+ do {
527
+ // @ts-expect-error
528
+ item = iter.next().value;
529
+ if (item == null) {
530
+ break;
531
+ }
532
+ tokens.push(item.token);
533
+ if (item.token.typ === EnumToken.BlockStartTokenType) {
534
+ inBlock++;
535
+ }
536
+ else if (item.token.typ === EnumToken.BlockEndTokenType) {
537
+ inBlock--;
538
+ }
539
+ } while (inBlock != 0);
540
+ if (tokens.length > 0) {
541
+ errors.push({
542
+ action: "drop",
543
+ message: "invalid block",
544
+ location: options.source.getSourceLocation(tokens[0][LOC].sta),
545
+ });
546
+ }
547
+ }
548
+ tokens = [];
549
+ }
550
+ else if ((parensMatch === 0 || curlyBracketMatch === 0) && item.token.typ === EnumToken.BlockEndTokenType) {
551
+ parseNode(tokens, context, options, errors, stats, invalidNodes);
552
+ if (context[LOC] != null) {
553
+ context[LOC].end = item.token[LOC].end;
554
+ }
555
+ const previousNode = stack.pop();
556
+ context = (stack[stack.length - 1] ?? ast);
557
+ if (options.removeEmpty &&
558
+ previousNode != null &&
559
+ previousNode.chi.length == 0 &&
560
+ context.chi[context.chi.length - 1] == previousNode) {
561
+ context.chi.pop();
562
+ }
563
+ tokens = [];
564
+ parensMatch = 0;
565
+ curlyBracketMatch = 0;
566
+ }
567
+ // }
568
+ }
569
+ if (tokens.length > 0) {
570
+ node = parseNode(tokens, context, options, errors, stats, invalidNodes);
571
+ if (node != null) {
572
+ if ("chi" in node /* && node.typ != EnumToken.InvalidRuleNodeType */) {
573
+ stack.push(node);
574
+ context = node;
575
+ }
576
+ }
577
+ }
578
+ const endParseTime = performance.now();
579
+ if (options.expandNestingRules) {
580
+ ast = expand(ast);
581
+ }
582
+ let replacement;
583
+ let callable;
584
+ if (options.visitor != null) {
585
+ let parens;
586
+ for (const result of walk(ast)) {
587
+ parens = null;
588
+ if (valuesHandlers.size > 0 ||
589
+ preVisitorsHandlersMap.size > 0 ||
590
+ visitorsHandlersMap.size > 0 ||
591
+ postVisitorsHandlersMap.size > 0) {
592
+ if ((result.node.typ == EnumToken.DeclarationNodeType &&
593
+ (preVisitorsHandlersMap.has("Declaration") ||
594
+ visitorsHandlersMap.has("Declaration") ||
595
+ postVisitorsHandlersMap.has("Declaration"))) ||
596
+ (result.node.typ == EnumToken.AtRuleNodeType &&
597
+ (preVisitorsHandlersMap.has("AtRule") ||
598
+ visitorsHandlersMap.has("AtRule") ||
599
+ postVisitorsHandlersMap.has("AtRule"))) ||
600
+ (result.node.typ == EnumToken.KeyframesAtRuleNodeType &&
601
+ (preVisitorsHandlersMap.has("KeyframesAtRule") ||
602
+ visitorsHandlersMap.has("KeyframesAtRule") ||
603
+ postVisitorsHandlersMap.has("KeyframesAtRule")))) {
604
+ const handlers = [];
605
+ const key = result.node.typ == EnumToken.DeclarationNodeType
606
+ ? "Declaration"
607
+ : result.node.typ == EnumToken.AtRuleNodeType
608
+ ? "AtRule"
609
+ : "KeyframesAtRule";
610
+ if (preVisitorsHandlersMap.has(key)) {
611
+ handlers.push(
612
+ // @ts-expect-error
613
+ ...preVisitorsHandlersMap.get(key));
614
+ }
615
+ if (visitorsHandlersMap.has(key)) {
616
+ // @ts-ignore
617
+ handlers.push(...visitorsHandlersMap.get(key));
618
+ }
619
+ if (postVisitorsHandlersMap.has(key)) {
620
+ // @ts-ignore
621
+ handlers.push(...postVisitorsHandlersMap.get(key));
622
+ }
623
+ let node = result.node;
624
+ for (const handler of handlers) {
625
+ callable =
626
+ typeof handler == "function"
627
+ ? handler
628
+ : handler[camelize(node.typ === EnumToken.DeclarationNodeType ||
629
+ node.typ === EnumToken.AtRuleNodeType
630
+ ? node.nam
631
+ : node.val)];
632
+ if (callable == null) {
633
+ continue;
634
+ }
635
+ // @ts-expect-error
636
+ replacement = callable(node, result[PARENT], ast, function* () {
637
+ if (parens == null) {
638
+ // @ts-expect-error
639
+ parens = [...result.parents()];
640
+ }
641
+ yield* parens[Symbol.iterator]();
642
+ });
643
+ if (replacement == null) {
644
+ continue;
645
+ }
646
+ if (replacement == null || replacement == node) {
647
+ continue;
648
+ }
649
+ // @ts-ignore
650
+ node = replacement;
651
+ if (Array.isArray(node)) {
652
+ break;
653
+ }
654
+ }
655
+ if (node != result.node) {
656
+ replaceNodeOrValue(result.parent, result.node, node);
657
+ }
658
+ }
659
+ else if ((result.node.typ == EnumToken.RuleNodeType &&
660
+ (preVisitorsHandlersMap.has("Rule") ||
661
+ visitorsHandlersMap.has("Rule") ||
662
+ postVisitorsHandlersMap.has("Rule"))) ||
663
+ (result.node.typ == EnumToken.KeyFramesRuleNodeType &&
664
+ (preVisitorsHandlersMap.has("KeyframesRule") ||
665
+ visitorsHandlersMap.has("KeyframesRule") ||
666
+ postVisitorsHandlersMap.has("KeyframesRule")))) {
667
+ const handlers = [];
668
+ const key = result.node.typ == EnumToken.RuleNodeType ? "Rule" : "KeyframesRule";
669
+ if (preVisitorsHandlersMap.has(key)) {
670
+ handlers.push(...preVisitorsHandlersMap.get(key));
671
+ }
672
+ if (visitorsHandlersMap.has(key)) {
673
+ handlers.push(...visitorsHandlersMap.get(key));
674
+ }
675
+ if (postVisitorsHandlersMap.has(key)) {
676
+ handlers.push(...postVisitorsHandlersMap.get(key));
677
+ }
678
+ let node = result.node;
679
+ for (const callable of handlers) {
680
+ replacement = callable(node, result.parent, result.root,
681
+ // @ts-expect-error
682
+ function* () {
683
+ if (parens == null) {
684
+ // @ts-expect-error
685
+ parens = [...result.parents()];
686
+ }
687
+ yield* parens[Symbol.iterator]();
688
+ });
689
+ if (replacement == null) {
690
+ continue;
691
+ }
692
+ if (replacement == null || replacement == node) {
693
+ continue;
694
+ }
695
+ // @ts-ignore
696
+ node = replacement;
697
+ //
698
+ if (Array.isArray(node)) {
699
+ break;
700
+ }
701
+ }
702
+ // @ts-ignore
703
+ if (node != result.node) {
704
+ // @ts-ignore
705
+ replaceNodeOrValue(result.parent, result.node, node);
706
+ }
707
+ }
708
+ else if (valuesHandlers.size > 0) {
709
+ let node = null;
710
+ node = result.node;
711
+ if (valuesHandlers.has(node.typ)) {
712
+ for (const valueHandler of valuesHandlers.get(node.typ)) {
713
+ callable = valueHandler;
714
+ replacement = callable(node, result.parent, ast,
715
+ // @ts-expect-error
716
+ function* () {
717
+ if (parens == null) {
718
+ // @ts-expect-error
719
+ parens = [...result.parents()];
720
+ }
721
+ yield* parens[Symbol.iterator]();
722
+ });
723
+ if (replacement == null) {
724
+ continue;
725
+ }
726
+ if (replacement != null && replacement != node) {
727
+ node = replacement;
728
+ }
729
+ }
730
+ }
731
+ if (node != result.node) {
732
+ // @ts-ignore
733
+ replaceNodeOrValue(result[PARENT], value, node);
734
+ }
735
+ const tokens = Array.isArray(result.node[TOKENS]) ? result.node[TOKENS] : [];
736
+ if (Array.isArray(result.node.val)) {
737
+ tokens.push(...result.node.val);
738
+ }
739
+ if (tokens.length == 0) {
740
+ continue;
741
+ }
742
+ for (const { value, parent, root, parents } of walkValues(tokens, result.node)) {
743
+ node = value;
744
+ if (valuesHandlers.has(node.typ)) {
745
+ let parens = null;
746
+ for (const valueHandler of valuesHandlers.get(node.typ)) {
747
+ callable = valueHandler;
748
+ // @ts-expect-error
749
+ let result = callable(node, parent, root, function* () {
750
+ if (parens == null) {
751
+ // @ts-expect-error
752
+ parens = [...parents()];
753
+ }
754
+ yield* parens[Symbol.iterator]();
755
+ });
756
+ if (result == null) {
757
+ continue;
758
+ }
759
+ if (result != null && result != node) {
760
+ node = result;
761
+ }
762
+ if (Array.isArray(node)) {
763
+ break;
764
+ }
765
+ }
766
+ }
767
+ if (node != value) {
768
+ // @ts-ignore
769
+ replaceNodeOrValue(parent, value, node);
770
+ }
771
+ }
772
+ }
773
+ }
774
+ }
775
+ }
776
+ if (invalidNodes.length > 0) {
777
+ let count = invalidNodes.length;
778
+ for (const { node, parent } of walk(ast)) {
779
+ if (options.lenient && node[STATE] == EnumAstNodeStatus.Unknown) {
780
+ continue;
781
+ }
782
+ if (node[STATE] === EnumAstNodeStatus.Invalid ||
783
+ node[STATE] === EnumAstNodeStatus.Unknown ||
784
+ node[STATE] === EnumAstNodeStatus.Unparsed ||
785
+ node[STATE] === EnumAstNodeStatus.Malformed ||
786
+ node[STATE] === EnumAstNodeStatus.Disallowed) {
787
+ // @ts-ignore
788
+ parent.chi.splice(parent.chi.indexOf(node), 1);
789
+ node[PARENT] = null;
790
+ count--;
791
+ if (count == 0) {
792
+ break;
793
+ }
794
+ }
795
+ }
796
+ }
797
+ while (stack.length > 0 && context != ast) {
798
+ const previousNode = stack.pop();
799
+ context = (stack[stack.length - 1] ?? ast);
800
+ // remove empty nodes
801
+ if (options.removeEmpty &&
802
+ previousNode != null &&
803
+ previousNode.chi.length == 0 &&
804
+ context.chi[context.chi.length - 1] == previousNode) {
805
+ context.chi.pop();
806
+ continue;
807
+ }
808
+ break;
809
+ }
810
+ if (options.minify) {
811
+ if (ast.chi.length > 0) {
812
+ let passes = options.pass ?? 1;
813
+ while (passes--) {
814
+ minify(ast, options, true, errors, false);
815
+ }
816
+ }
817
+ }
818
+ stats.bytesIn += stats.importedBytesIn;
819
+ let endTime = performance.now();
820
+ const result = {
821
+ ast,
822
+ errors,
823
+ stats: {
824
+ ...stats,
825
+ parse: `${(endParseTime - startTime).toFixed(2)}ms`,
826
+ minify: `${(endTime - endParseTime).toFixed(2)}ms`,
827
+ tokenize: `${(options?.parseInfo?.time ?? 0).toFixed(2)}ms`,
828
+ total: `${(endTime - startTime).toFixed(2)}ms`,
829
+ },
830
+ };
831
+ if (options.module) {
832
+ const moduleSettings = {
833
+ hashLength: 5,
834
+ filePath: "",
835
+ scoped: ModuleScopeEnumOptions.Local,
836
+ naming: ModuleCaseTransformEnum.IgnoreCase,
837
+ pattern: "",
838
+ generateScopedName,
839
+ ...(typeof options.module != "object" ? {} : options.module),
840
+ };
841
+ const parseModuleTime = performance.now();
842
+ const namesMapping = {};
843
+ const global = new Set();
844
+ const processed = new Set();
845
+ const pattern = typeof options.module == "boolean" ? null : moduleSettings.pattern;
846
+ const importMapping = {};
847
+ const cssVariablesMap = {};
848
+ const importedCssVariables = {};
849
+ let mapping = {};
850
+ let revMapping = {};
851
+ let filePath = typeof options.module == "boolean"
852
+ ? options.src
853
+ : (moduleSettings.filePath ?? options.src);
854
+ filePath =
855
+ filePath === ""
856
+ ? options.src
857
+ : options.resolve(filePath, options.dirname(options.src), options.cwd).relative;
858
+ if (typeof options.module == "number") {
859
+ if (options.module & ModuleCaseTransformEnum.CamelCase) {
860
+ moduleSettings.naming = ModuleCaseTransformEnum.CamelCase;
861
+ }
862
+ else if (options.module & ModuleCaseTransformEnum.CamelCaseOnly) {
863
+ moduleSettings.naming = ModuleCaseTransformEnum.CamelCaseOnly;
864
+ }
865
+ else if (options.module & ModuleCaseTransformEnum.DashCase) {
866
+ moduleSettings.naming = ModuleCaseTransformEnum.DashCase;
867
+ }
868
+ else if (options.module & ModuleCaseTransformEnum.DashCaseOnly) {
869
+ moduleSettings.naming = ModuleCaseTransformEnum.DashCaseOnly;
870
+ }
871
+ if (options.module & ModuleScopeEnumOptions.Global) {
872
+ moduleSettings.scoped = ModuleScopeEnumOptions.Global;
873
+ }
874
+ if (options.module & ModuleScopeEnumOptions.Pure) {
875
+ // @ts-ignore
876
+ moduleSettings.scoped |= ModuleScopeEnumOptions.Pure;
877
+ }
878
+ if (options.module & ModuleScopeEnumOptions.Shortest) {
879
+ // @ts-ignore
880
+ moduleSettings.scoped |= ModuleScopeEnumOptions.Shortest;
881
+ }
882
+ if (options.module & ModuleScopeEnumOptions.ICSS) {
883
+ // @ts-ignore
884
+ moduleSettings.scoped |= ModuleScopeEnumOptions.ICSS;
885
+ }
886
+ }
887
+ if (typeof moduleSettings.scoped == "boolean") {
888
+ moduleSettings.scoped = moduleSettings.scoped
889
+ ? ModuleScopeEnumOptions.Local
890
+ : ModuleScopeEnumOptions.Global;
891
+ }
892
+ if (moduleSettings.scoped & ModuleScopeEnumOptions.Shortest) {
893
+ moduleSettings.generateScopedName = generateSyncScopedName;
894
+ }
895
+ moduleSettings.filePath = filePath;
896
+ moduleSettings.pattern =
897
+ pattern != null && pattern !== "" ? pattern : filePath === "" ? `[local]_[hash]` : `[local]_[hash]_[name]`;
898
+ for (const { node, parent } of walk(ast)) {
899
+ if (node.typ == EnumToken.CssVariableImportTokenType) {
900
+ throw new Error("css variable import not supported by parseSync() or transformSync(). use parse() or transform() instead.\nat " +
901
+ options.source.getSourceLocation(node[LOC].sta).join(":"));
902
+ }
903
+ if (node.typ == EnumToken.CssVariableDeclarationMapTokenType) {
904
+ const from = node.from.find((t) => t.typ == EnumToken.IdenTokenType || isIdentColor(t));
905
+ if (!(from.val in cssVariablesMap)) {
906
+ errors.push({
907
+ node,
908
+ message: `could not resolve @value import from '${from.val}'`,
909
+ action: "drop",
910
+ });
911
+ }
912
+ else {
913
+ for (const token of node.vars) {
914
+ if (token.typ == EnumToken.IdenTokenType || isIdentColor(token)) {
915
+ if (!(token.val in cssVariablesMap[from.val])) {
916
+ errors.push({
917
+ node,
918
+ message: `value '${token.val}' is not exported from '${from.val}'`,
919
+ action: "drop",
920
+ });
921
+ continue;
922
+ }
923
+ result.cssModuleVariables ??= {};
924
+ result.cssModuleVariables[token.val] = importedCssVariables[token.val] = cssVariablesMap[from.val][token.val];
925
+ }
926
+ }
927
+ }
928
+ parent.chi.splice(parent.chi.indexOf(node), 1);
929
+ continue;
930
+ }
931
+ if (node.typ == EnumToken.CssVariableTokenType) {
932
+ if (parent?.typ == EnumToken.StyleSheetNodeType) {
933
+ if (result.cssModuleVariables == null) {
934
+ result.cssModuleVariables = {};
935
+ }
936
+ result.cssModuleVariables[node.nam] = node;
937
+ }
938
+ parent.chi.splice(parent.chi.indexOf(node), 1);
939
+ continue;
940
+ }
941
+ if (node.typ == EnumToken.DeclarationNodeType) {
942
+ if (node.nam.startsWith("--")) {
943
+ if (!(node.nam in namesMapping)) {
944
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
945
+ ? node.nam
946
+ : moduleSettings.generateScopedName(node.nam, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
947
+ let value = result;
948
+ mapping[node.nam] =
949
+ "--" +
950
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
951
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
952
+ ? getKeyName(value, moduleSettings.naming)
953
+ : value);
954
+ revMapping[node.nam] = node.nam;
955
+ }
956
+ node.nam = mapping[node.nam];
957
+ }
958
+ if (equalsIgnoreCase("composes", node.nam)) {
959
+ const composeSelectors = [];
960
+ // let isValid: boolean = true;
961
+ for (const token of node.val) {
962
+ if (token.typ == EnumToken.ComposesSelectorNodeType) {
963
+ composeSelectors.push(token);
964
+ }
965
+ }
966
+ // find parent rule
967
+ let parentRule = parent;
968
+ while (parentRule != null && parentRule.typ != EnumToken.RuleNodeType) {
969
+ parentRule = parentRule[PARENT];
970
+ }
971
+ if ( /* !isValid || */composeSelectors.length == 0) {
972
+ errors.push({
973
+ action: "drop",
974
+ message: `composes is empty`,
975
+ node,
976
+ });
977
+ parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
978
+ continue;
979
+ }
980
+ for (const token of composeSelectors) {
981
+ // composes: a b c;
982
+ if (token.r == null) {
983
+ for (const rule of token.l) {
984
+ if (rule.typ == EnumToken.WhitespaceTokenType ||
985
+ rule.typ == EnumToken.CommentTokenType) {
986
+ continue;
987
+ }
988
+ if (!(rule.val in mapping)) {
989
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
990
+ ? rule.val
991
+ : moduleSettings.generateScopedName(rule.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
992
+ let value = result;
993
+ mapping[rule.val] =
994
+ (rule.typ == EnumToken.DashedIdenTokenType ? "--" : "") +
995
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
996
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
997
+ ? getKeyName(value, moduleSettings.naming)
998
+ : value);
999
+ revMapping[mapping[rule.val]] = rule.val;
1000
+ }
1001
+ if (parentRule != null) {
1002
+ for (const tk of parentRule[TOKENS]) {
1003
+ if (tk.typ == EnumToken.ClassSelectorTokenType) {
1004
+ const val = tk.val.slice(1);
1005
+ if (val in revMapping) {
1006
+ const key = revMapping[val];
1007
+ mapping[key] = [
1008
+ ...new Set([
1009
+ ...mapping[key].split(" "),
1010
+ mapping[rule.val],
1011
+ ]),
1012
+ ].join(" ");
1013
+ }
1014
+ }
1015
+ }
1016
+ }
1017
+ }
1018
+ }
1019
+ // composes: a b c from 'file.css';
1020
+ else if (token.r.typ == EnumToken.String) {
1021
+ throw new Error(`composes from file is not supported using parseSync() or transformSync(). Use parse() or transform() instead.\nat ${options.source.getSourceLocation(node[LOC].sta).join(":")}`);
1022
+ }
1023
+ // composes: a b c from global;
1024
+ else if (token.r.typ == EnumToken.IdenTokenType) {
1025
+ // global
1026
+ if (parentRule != null) {
1027
+ if (equalsIgnoreCase("global", token.r.val)) {
1028
+ for (const tk of parentRule[TOKENS]) {
1029
+ if (tk.typ == EnumToken.ClassSelectorTokenType) {
1030
+ const val = tk.val.slice(1);
1031
+ if (val in revMapping) {
1032
+ const key = revMapping[val];
1033
+ mapping[key] = [
1034
+ ...new Set([
1035
+ ...mapping[key].split(" "),
1036
+ ...token.l.reduce((acc, curr) => {
1037
+ if (curr.typ == EnumToken.IdenTokenType) {
1038
+ acc.push(curr.val);
1039
+ }
1040
+ return acc;
1041
+ }, []),
1042
+ ]),
1043
+ ].join(" ");
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+ else {
1049
+ errors.push({
1050
+ action: "drop",
1051
+ message: `composes '${token.r.val}' is not supported`,
1052
+ node,
1053
+ });
1054
+ }
1055
+ }
1056
+ }
1057
+ }
1058
+ parent.chi.splice(parent.chi.indexOf(node), 1);
1059
+ }
1060
+ if (node.typ == EnumToken.DeclarationNodeType &&
1061
+ [
1062
+ "grid-column",
1063
+ "grid-column-start",
1064
+ "grid-column-end",
1065
+ "grid-row",
1066
+ "grid-row-start",
1067
+ "grid-row-end",
1068
+ "grid-template",
1069
+ "grid-template-columns",
1070
+ "grid-template-rows",
1071
+ ].includes(node.nam)) {
1072
+ for (const { value } of walkValues(node.val, node)) {
1073
+ if (value.typ != EnumToken.IdenTokenType) {
1074
+ continue;
1075
+ }
1076
+ let idenToken = value.val;
1077
+ let suffix = "";
1078
+ if (idenToken.endsWith("-start")) {
1079
+ suffix = "-start";
1080
+ idenToken = idenToken.slice(0, -6);
1081
+ }
1082
+ else if (idenToken.endsWith("-end")) {
1083
+ suffix = "-end";
1084
+ idenToken = idenToken.slice(0, -4);
1085
+ }
1086
+ if (!(idenToken in mapping)) {
1087
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1088
+ ? idenToken
1089
+ : moduleSettings.generateScopedName(idenToken, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1090
+ mapping[idenToken] = result;
1091
+ revMapping[result] = idenToken;
1092
+ if (suffix !== "") {
1093
+ idenToken += suffix;
1094
+ if (!(idenToken in mapping)) {
1095
+ mapping[idenToken] = result + suffix;
1096
+ revMapping[result + suffix] = idenToken;
1097
+ }
1098
+ }
1099
+ }
1100
+ value.val = mapping[idenToken];
1101
+ }
1102
+ }
1103
+ else if (node.nam == "grid-template-areas" || node.nam == "grid-template") {
1104
+ for (let i = 0; i < node.val.length; i++) {
1105
+ if (node.val[i].typ == EnumToken.String) {
1106
+ const tokens = parseString(node.val[i].val.slice(1, -1));
1107
+ for (const { value } of walkValues(tokens)) {
1108
+ if (value.typ == EnumToken.IdenTokenType ||
1109
+ value.typ == EnumToken.DashedIdenTokenType) {
1110
+ if (value.val in mapping) {
1111
+ value.val = mapping[value.val];
1112
+ }
1113
+ else {
1114
+ let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1115
+ ? value.val
1116
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1117
+ mapping[value.val] = result;
1118
+ revMapping[result] = value.val;
1119
+ value.val = result;
1120
+ }
1121
+ }
1122
+ }
1123
+ node.val[i].val =
1124
+ node.val[i].val.charAt(0) +
1125
+ renderTokens(tokens) +
1126
+ node.val[i].val.charAt(node.val[i].val.length - 1);
1127
+ }
1128
+ }
1129
+ }
1130
+ else if (node.nam == "animation" || node.nam == "animation-name") {
1131
+ for (const { value } of walkValues(node.val, node)) {
1132
+ if (value.typ == EnumToken.IdenTokenType &&
1133
+ ![
1134
+ "none",
1135
+ "infinite",
1136
+ "normal",
1137
+ "reverse",
1138
+ "alternate",
1139
+ "alternate-reverse",
1140
+ "forwards",
1141
+ "backwards",
1142
+ "both",
1143
+ "running",
1144
+ "paused",
1145
+ "linear",
1146
+ "ease",
1147
+ "ease-in",
1148
+ "ease-out",
1149
+ "ease-in-out",
1150
+ "step-start",
1151
+ "step-end",
1152
+ "jump-start",
1153
+ "jump-end",
1154
+ "jump-none",
1155
+ "jump-both",
1156
+ "start",
1157
+ "end",
1158
+ "inherit",
1159
+ "initial",
1160
+ "unset",
1161
+ ].includes(value.val)) {
1162
+ if (!(value.val in mapping)) {
1163
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1164
+ ? value.val
1165
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1166
+ mapping[value.val] = result;
1167
+ revMapping[mapping[value.val]] = value.val;
1168
+ }
1169
+ value.val = mapping[value.val];
1170
+ }
1171
+ }
1172
+ }
1173
+ for (const { value, parent } of walkValues(node.val, node)) {
1174
+ if (value.typ == EnumToken.DashedIdenTokenType) {
1175
+ value.val = mapping[value.val];
1176
+ }
1177
+ else if ((value.typ == EnumToken.IdenTokenType || isIdentColor(value)) &&
1178
+ value.val in importedCssVariables) {
1179
+ replaceNodeOrValue(parent, value, importedCssVariables[value.val].val);
1180
+ }
1181
+ }
1182
+ }
1183
+ else if (node.typ == EnumToken.RuleNodeType) {
1184
+ // if (node[TOKENS] == null) {
1185
+ const tokens = parseString(node.sel);
1186
+ matchSelectorSyntax(tokens, [], options);
1187
+ node[TOKENS] = trimArray(tokens);
1188
+ let hasIdOrClass = false;
1189
+ for (const { value } of walkValues(node[TOKENS], node,
1190
+ // @ts-ignore
1191
+ (value, parent) => {
1192
+ if (value.typ == EnumToken.PseudoClassTokenType ||
1193
+ value.typ == EnumToken.PseudoElementTokenType) {
1194
+ const val = value.val.toLowerCase();
1195
+ switch (val) {
1196
+ case ":local":
1197
+ case ":global":
1198
+ {
1199
+ let index = parent[TOKENS].indexOf(value);
1200
+ parent[TOKENS].splice(index, 1);
1201
+ if (parent[TOKENS][index]?.typ == EnumToken.WhitespaceTokenType ||
1202
+ parent[TOKENS][index]?.typ ==
1203
+ EnumToken.DescendantCombinatorTokenType) {
1204
+ parent[TOKENS].splice(index, 1);
1205
+ }
1206
+ }
1207
+ break;
1208
+ }
1209
+ }
1210
+ else if (value.typ == EnumToken.PseudoClassFuncTokenType) {
1211
+ switch (value.val.toLowerCase()) {
1212
+ case ":global":
1213
+ for (const token of value.chi) {
1214
+ global.add(token);
1215
+ }
1216
+ case ":local":
1217
+ parent[TOKENS].splice(parent[TOKENS].indexOf(value), 1, ...value.chi);
1218
+ break;
1219
+ }
1220
+ }
1221
+ })) {
1222
+ if (value.typ == EnumToken.HashTokenType || value.typ == EnumToken.ClassSelectorTokenType) {
1223
+ hasIdOrClass = true;
1224
+ }
1225
+ if (processed.has(value)) {
1226
+ continue;
1227
+ }
1228
+ processed.add(value);
1229
+ if (value.typ == EnumToken.PseudoClassTokenType || value.typ == EnumToken.PseudoElementTokenType) ;
1230
+ else if (value.typ == EnumToken.PseudoClassFuncTokenType) ;
1231
+ else {
1232
+ if (global.has(value)) {
1233
+ continue;
1234
+ }
1235
+ if (value.typ == EnumToken.ClassSelectorTokenType) {
1236
+ const val = value.val.slice(1);
1237
+ if (!(val in mapping)) {
1238
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1239
+ ? val
1240
+ : moduleSettings.generateScopedName(val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1241
+ let value = result;
1242
+ mapping[val] =
1243
+ moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1244
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1245
+ ? getKeyName(value, moduleSettings.naming)
1246
+ : value;
1247
+ revMapping[mapping[val]] = val;
1248
+ }
1249
+ value.val = "." + mapping[val];
1250
+ }
1251
+ }
1252
+ }
1253
+ if (moduleSettings.scoped & ModuleScopeEnumOptions.Pure) {
1254
+ if (!hasIdOrClass) {
1255
+ 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 ?? ""}`);
1256
+ }
1257
+ }
1258
+ node.sel = "";
1259
+ for (const token of node[TOKENS]) {
1260
+ node.sel += renderValue(token);
1261
+ }
1262
+ }
1263
+ else if (node.typ == EnumToken.AtRuleNodeType || node.typ == EnumToken.KeyframesAtRuleNodeType) {
1264
+ const val = node.nam.toLowerCase();
1265
+ if (node[TOKENS] == null) {
1266
+ node[TOKENS] = parseString(node.val);
1267
+ }
1268
+ if (val == "property" || val == "keyframes") {
1269
+ const prefix = val == "property" ? "--" : "";
1270
+ for (const value of node[TOKENS]) {
1271
+ if ((prefix == "--" && value.typ == EnumToken.DashedIdenTokenType) ||
1272
+ (prefix == "" && value.typ == EnumToken.IdenTokenType)) {
1273
+ if (!(value.val in mapping)) {
1274
+ const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1275
+ ? value.val
1276
+ : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
1277
+ let val = result;
1278
+ mapping[value.val] =
1279
+ prefix +
1280
+ (moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1281
+ moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
1282
+ ? getKeyName(val, moduleSettings.naming)
1283
+ : val);
1284
+ revMapping[mapping[value.val]] = value.val;
1285
+ }
1286
+ value.val = mapping[value.val];
1287
+ }
1288
+ }
1289
+ node.val = renderTokens(node[TOKENS]);
1290
+ }
1291
+ }
1292
+ }
1293
+ if (moduleSettings.naming != ModuleCaseTransformEnum.IgnoreCase) {
1294
+ revMapping = {};
1295
+ mapping = Object.entries(mapping).reduce((acc, [key, value]) => {
1296
+ const keyName = getKeyName(key, moduleSettings.naming);
1297
+ acc[keyName] = value;
1298
+ revMapping[value] = keyName;
1299
+ return acc;
1300
+ }, {});
1301
+ }
1302
+ result.mapping = mapping;
1303
+ result.revMapping = revMapping;
1304
+ if (moduleSettings.scoped & ModuleScopeEnumOptions.ICSS && Object.keys(importMapping).length > 0) {
1305
+ result.importMapping = importMapping;
1306
+ }
1307
+ endTime = performance.now();
1308
+ result.stats.module = `${(endTime - parseModuleTime).toFixed(2)}ms`;
1309
+ result.stats.total = `${(endTime - startTime).toFixed(2)}ms`;
1310
+ }
1311
+ if (options.signal != null) {
1312
+ options.signal.removeEventListener("abort", reject);
1313
+ }
1314
+ return result;
1315
+ }
195
1316
  /**
196
1317
  * Parse css string
197
1318
  * @param iter
@@ -241,7 +1362,6 @@ async function doParse(iter, options = {}) {
241
1362
  }
242
1363
  const startTime = performance.now();
243
1364
  const errors = [];
244
- const src = options.src;
245
1365
  const stack = [];
246
1366
  const stats = {
247
1367
  src: options.src ?? "",
@@ -263,21 +1383,11 @@ async function doParse(iter, options = {}) {
263
1383
  let tokens = [];
264
1384
  let context = ast;
265
1385
  ast[ROOT] = ast;
266
- if (options.sourcemap) {
267
- ast[LOC] = {
268
- sta: {
269
- ind: 0,
270
- lin: 1,
271
- col: 1,
272
- },
273
- end: {
274
- ind: 0,
275
- lin: 1,
276
- col: 1,
277
- },
278
- src: "",
279
- };
280
- }
1386
+ ast[LOC] = {
1387
+ sta: 0,
1388
+ end: 0,
1389
+ srcId: options.source.id,
1390
+ };
281
1391
  let valuesHandlers;
282
1392
  let preValuesHandlers;
283
1393
  let postValuesHandlers;
@@ -410,7 +1520,7 @@ async function doParse(iter, options = {}) {
410
1520
  message: "Bad token",
411
1521
  syntax: null,
412
1522
  node: item.token,
413
- location: item.token[LOC],
1523
+ location: options.source.getSourceLocation(item.token[LOC].sta),
414
1524
  });
415
1525
  // bad token
416
1526
  continue;
@@ -468,11 +1578,7 @@ async function doParse(iter, options = {}) {
468
1578
  errors.push({
469
1579
  action: "drop",
470
1580
  message: "invalid block",
471
- location: {
472
- src,
473
- sta: tokens[0][LOC].sta,
474
- end: tokens[tokens.length - 1][LOC].end,
475
- },
1581
+ location: options.source.getSourceLocation(tokens[0][LOC].sta),
476
1582
  });
477
1583
  }
478
1584
  }
@@ -517,25 +1623,29 @@ async function doParse(iter, options = {}) {
517
1623
  const token = node[TOKENS][0];
518
1624
  const url = token.typ == EnumToken.StringTokenType ? token.val.slice(1, -1) : token.val;
519
1625
  try {
520
- const result = options.load(url, options.src || options.cwd);
1626
+ const src = options.resolve(url, options.src || options.cwd);
1627
+ const result = options.load(src);
521
1628
  const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
522
1629
  ? await result
523
1630
  : result;
524
- const root = await doParse(stream instanceof ReadableStream
525
- ? tokenizeStream(stream)
526
- : tokenize({
527
- stream,
528
- src: options.resolve(url, options.src || options.cwd).relative,
529
- buffer: "",
530
- offset: 0,
531
- position: { ind: 0, lin: 1, col: 1 },
532
- currentPosition: { ind: -1, lin: 1, col: 0 },
533
- }), Object.assign({}, options, {
1631
+ const source = new SourceFile(typeof stream === "string" ? stream : "", [], src.relative);
1632
+ options.sourcesMap.set(source.id, source);
1633
+ const parseInfo = {
1634
+ stream,
1635
+ buffer: "",
1636
+ offset: 0,
1637
+ source,
1638
+ position: 0,
1639
+ currentPosition: -1,
1640
+ };
1641
+ const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream, parseInfo) : tokenize(parseInfo), Object.assign({}, options, {
534
1642
  minify: false,
535
1643
  setParent: false,
536
1644
  src: options.resolve(url, options.src || options.cwd).relative,
537
1645
  }));
538
1646
  stats.importedBytesIn += root.stats.bytesIn;
1647
+ stats.nodesCount += root.stats.nodesCount;
1648
+ stats.tokensCount += root.stats.tokensCount;
539
1649
  stats.imports.push(root.stats);
540
1650
  node[PARENT].chi.splice(node[PARENT].chi.indexOf(node), 1, ...root.ast.chi);
541
1651
  if (root.errors.length > 0) {
@@ -616,10 +1726,7 @@ async function doParse(iter, options = {}) {
616
1726
  if (replacement == null) {
617
1727
  continue;
618
1728
  }
619
- isAsync =
620
- replacement instanceof Promise ||
621
- Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
622
- if (replacement) {
1729
+ if (replacement instanceof Promise) {
623
1730
  replacement = await replacement;
624
1731
  }
625
1732
  if (replacement == null || replacement == node) {
@@ -668,10 +1775,7 @@ async function doParse(iter, options = {}) {
668
1775
  if (replacement == null) {
669
1776
  continue;
670
1777
  }
671
- isAsync =
672
- replacement instanceof Promise ||
673
- Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
674
- if (replacement) {
1778
+ if (replacement instanceof Promise) {
675
1779
  replacement = await replacement;
676
1780
  }
677
1781
  if (replacement == null || replacement == node) {
@@ -708,10 +1812,7 @@ async function doParse(iter, options = {}) {
708
1812
  if (replacement == null) {
709
1813
  continue;
710
1814
  }
711
- isAsync =
712
- replacement instanceof Promise ||
713
- Object.getPrototypeOf(replacement).constructor.name == "AsyncFunction";
714
- if (isAsync) {
1815
+ if (replacement instanceof Promise) {
715
1816
  replacement = await replacement;
716
1817
  }
717
1818
  if (replacement != null && replacement != node) {
@@ -747,10 +1848,7 @@ async function doParse(iter, options = {}) {
747
1848
  if (result == null) {
748
1849
  continue;
749
1850
  }
750
- isAsync =
751
- result instanceof Promise ||
752
- Object.getPrototypeOf(result).constructor.name == "AsyncFunction";
753
- if (isAsync) {
1851
+ if (result instanceof Promise) {
754
1852
  result = await result;
755
1853
  }
756
1854
  if (result != null && result != node) {
@@ -770,19 +1868,25 @@ async function doParse(iter, options = {}) {
770
1868
  }
771
1869
  }
772
1870
  }
773
- // console.debug("invalid nodes", invalidNodes);
774
1871
  if (invalidNodes.length > 0) {
775
- let k = invalidNodes.length;
776
- while (k-- > 0) {
777
- if (invalidNodes[k][STATE] == EnumAstNodeStatus.Validated ||
778
- invalidNodes[k][STATE] == EnumAstNodeStatus.Unvalidated ||
779
- invalidNodes[k][STATE] == EnumAstNodeStatus.ValidationFailed) {
1872
+ let count = invalidNodes.length;
1873
+ for (const { node, parent } of walk(ast)) {
1874
+ if (options.lenient && node[STATE] == EnumAstNodeStatus.Unknown) {
780
1875
  continue;
781
1876
  }
782
- if (options.lenient && invalidNodes[k][STATE] == EnumAstNodeStatus.Unknown) {
783
- continue;
1877
+ if (node[STATE] === EnumAstNodeStatus.Invalid ||
1878
+ node[STATE] === EnumAstNodeStatus.Unknown ||
1879
+ node[STATE] === EnumAstNodeStatus.Unparsed ||
1880
+ node[STATE] === EnumAstNodeStatus.Malformed ||
1881
+ node[STATE] === EnumAstNodeStatus.Disallowed) {
1882
+ // @ts-ignore
1883
+ parent.chi.splice(parent.chi.indexOf(node), 1);
1884
+ node[PARENT] = null;
1885
+ count--;
1886
+ if (count == 0) {
1887
+ break;
1888
+ }
784
1889
  }
785
- invalidNodes[k][PARENT].chi.splice(invalidNodes[k][PARENT].chi.indexOf(invalidNodes[k]), 1);
786
1890
  }
787
1891
  }
788
1892
  while (stack.length > 0 && context != ast) {
@@ -894,15 +1998,19 @@ async function doParse(iter, options = {}) {
894
1998
  const stream = result instanceof Promise || Object.getPrototypeOf(result).constructor.name == "AsyncFunction"
895
1999
  ? await result
896
2000
  : result;
2001
+ const source = new SourceFile(typeof stream === "string" ? stream : "", [], src.relative);
2002
+ options.sourcesMap.set(source.id, source);
897
2003
  const parseInfo = {
898
2004
  stream,
899
2005
  buffer: "",
900
2006
  offset: 0,
901
2007
  time: 0,
902
- position: { ind: 0, lin: 1, col: 1 },
903
- currentPosition: { ind: -1, lin: 1, col: 0 },
2008
+ source,
2009
+ position: 0,
2010
+ currentPosition: -1,
904
2011
  };
905
2012
  const root = await doParse(stream instanceof ReadableStream ? tokenizeStream(stream, parseInfo) : tokenize(parseInfo), Object.assign({}, options, {
2013
+ source,
906
2014
  minify: false,
907
2015
  setParent: false,
908
2016
  src: src.relative,
@@ -968,19 +2076,19 @@ async function doParse(iter, options = {}) {
968
2076
  node.nam = mapping[node.nam];
969
2077
  }
970
2078
  if (equalsIgnoreCase("composes", node.nam)) {
971
- const tokens = [];
2079
+ const composeSelectors = [];
972
2080
  // let isValid: boolean = true;
973
2081
  for (const token of node.val) {
974
2082
  if (token.typ == EnumToken.ComposesSelectorNodeType) {
975
- tokens.push(token);
2083
+ composeSelectors.push(token);
976
2084
  }
977
2085
  }
978
2086
  // find parent rule
979
- let parentRule = node[PARENT];
2087
+ let parentRule = parent;
980
2088
  while (parentRule != null && parentRule.typ != EnumToken.RuleNodeType) {
981
2089
  parentRule = parentRule[PARENT];
982
2090
  }
983
- if ( /* !isValid || */tokens.length == 0) {
2091
+ if ( /* !isValid || */composeSelectors.length == 0) {
984
2092
  errors.push({
985
2093
  action: "drop",
986
2094
  message: `composes is empty`,
@@ -989,7 +2097,7 @@ async function doParse(iter, options = {}) {
989
2097
  parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
990
2098
  continue;
991
2099
  }
992
- for (const token of tokens) {
2100
+ for (const token of composeSelectors) {
993
2101
  // composes: a b c;
994
2102
  if (token.r == null) {
995
2103
  for (const rule of token.l) {
@@ -1001,6 +2109,7 @@ async function doParse(iter, options = {}) {
1001
2109
  let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1002
2110
  ? rule.val
1003
2111
  : moduleSettings.generateScopedName(rule.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2112
+ // @ts-expect-error
1004
2113
  let value = result instanceof Promise ? await result : result;
1005
2114
  mapping[rule.val] =
1006
2115
  (rule.typ == EnumToken.DashedIdenTokenType ? "--" : "") +
@@ -1038,13 +2147,20 @@ async function doParse(iter, options = {}) {
1038
2147
  ? await result
1039
2148
  : result;
1040
2149
  const root = await doParse(stream instanceof ReadableStream
1041
- ? tokenizeStream(stream)
2150
+ ? tokenizeStream(stream, {
2151
+ buffer: "",
2152
+ offset: 0,
2153
+ source: new SourceFile("", [], src.relative),
2154
+ position: 0,
2155
+ currentPosition: -1,
2156
+ })
1042
2157
  : tokenize({
1043
2158
  stream,
1044
2159
  buffer: "",
1045
2160
  offset: 0,
1046
- position: { ind: 0, lin: 1, col: 1 },
1047
- currentPosition: { ind: -1, lin: 1, col: 0 },
2161
+ position: 0,
2162
+ source: new SourceFile(stream, [], src.relative),
2163
+ currentPosition: -1,
1048
2164
  }), Object.assign({}, options, {
1049
2165
  minify: false,
1050
2166
  setParent: false,
@@ -1071,7 +2187,9 @@ async function doParse(iter, options = {}) {
1071
2187
  const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1072
2188
  ? iden.val
1073
2189
  : moduleSettings.generateScopedName(iden.val, srcIndex, moduleSettings.pattern, moduleSettings.hashLength);
1074
- let value = result instanceof Promise ? await result : result;
2190
+ let value =
2191
+ // @ts-expect-error
2192
+ result instanceof Promise ? await result : result;
1075
2193
  root.mapping[iden.val] =
1076
2194
  moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
1077
2195
  moduleSettings.naming & ModuleCaseTransformEnum.CamelCaseOnly
@@ -1124,7 +2242,7 @@ async function doParse(iter, options = {}) {
1124
2242
  }
1125
2243
  }
1126
2244
  }
1127
- parentRule.chi.splice(parentRule.chi.indexOf(node), 1);
2245
+ parent.chi.splice(parent.chi.indexOf(node), 1);
1128
2246
  }
1129
2247
  if (node.typ == EnumToken.DeclarationNodeType &&
1130
2248
  [
@@ -1156,6 +2274,7 @@ async function doParse(iter, options = {}) {
1156
2274
  let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1157
2275
  ? idenToken
1158
2276
  : moduleSettings.generateScopedName(idenToken, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2277
+ // @ts-expect-error
1159
2278
  if (result instanceof Promise) {
1160
2279
  result = await result;
1161
2280
  }
@@ -1186,6 +2305,7 @@ async function doParse(iter, options = {}) {
1186
2305
  let result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1187
2306
  ? value.val
1188
2307
  : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2308
+ // @ts-expect-error
1189
2309
  if (result instanceof Promise) {
1190
2310
  result = await result;
1191
2311
  }
@@ -1238,6 +2358,7 @@ async function doParse(iter, options = {}) {
1238
2358
  const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1239
2359
  ? value.val
1240
2360
  : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2361
+ // @ts-expect-error
1241
2362
  mapping[value.val] = result instanceof Promise ? await result : result;
1242
2363
  revMapping[mapping[value.val]] = value.val;
1243
2364
  }
@@ -1275,26 +2396,11 @@ async function doParse(iter, options = {}) {
1275
2396
  }
1276
2397
  }
1277
2398
  else if (node.typ == EnumToken.RuleNodeType) {
1278
- if (node[TOKENS] == null) {
1279
- const tokens = parseString(node.sel);
1280
- matchSelectorSyntax(tokens, [], options);
1281
- node[TOKENS] = trimArray(tokens);
1282
- // let i: number;
1283
- // const stack: Token[] = [];
1284
- // for (i = 0; i < tokens.length; i++) {
1285
- // if (tokensfuncDefMap.has(tokens[i].typ)) {
1286
- // stack.push(tokens[i]);
1287
- // continue;
1288
- // } else if (tokens[i].typ == EnumToken.EndParensTokenType) {
1289
- // const func = stack.at(-1) as PseudoClassFunctionToken;
1290
- // tokens.splice(i, 1);
1291
- // // @ts-expect-error
1292
- // func.typ = tokensfuncDefMap.get(func.typ)!;
1293
- // func.chi = tokens.splice(tokens.indexOf(func) + 1, i - 1);
1294
- // stack.pop();
1295
- // }
1296
- // }
1297
- }
2399
+ // if (node[TOKENS] == null) {
2400
+ const tokens = parseString(node.sel);
2401
+ matchSelectorSyntax(tokens, [], options);
2402
+ node[TOKENS] = trimArray(tokens);
2403
+ // }
1298
2404
  let hasIdOrClass = false;
1299
2405
  for (const { value } of walkValues(node[TOKENS], node,
1300
2406
  // @ts-ignore
@@ -1374,6 +2480,7 @@ async function doParse(iter, options = {}) {
1374
2480
  const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1375
2481
  ? val
1376
2482
  : moduleSettings.generateScopedName(val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2483
+ // @ts-expect-error
1377
2484
  let value = result instanceof Promise ? await result : result;
1378
2485
  mapping[val] =
1379
2486
  moduleSettings.naming & ModuleCaseTransformEnum.DashCaseOnly ||
@@ -1410,6 +2517,7 @@ async function doParse(iter, options = {}) {
1410
2517
  const result = moduleSettings.scoped & ModuleScopeEnumOptions.Global
1411
2518
  ? value.val
1412
2519
  : moduleSettings.generateScopedName(value.val, moduleSettings.filePath, moduleSettings.pattern, moduleSettings.hashLength);
2520
+ // @ts-expect-error
1413
2521
  let val = result instanceof Promise ? await result : result;
1414
2522
  mapping[value.val] =
1415
2523
  prefix +
@@ -1499,11 +2607,6 @@ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
1499
2607
  matchCount = 0;
1500
2608
  }
1501
2609
  while (matchCount > 0) {
1502
- position = {
1503
- ...position,
1504
- sta: { ...position.sta, ind: position.sta.ind + 1, col: position.sta.col + 1 },
1505
- end: { ...position.end, ind: position.end.ind + 1, col: position.end.col + 1 },
1506
- };
1507
2610
  tokens.push({
1508
2611
  typ: EnumToken.EndParensTokenType,
1509
2612
  [LOC]: { ...position },
@@ -1518,7 +2621,7 @@ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
1518
2621
  action: "drop",
1519
2622
  message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`,
1520
2623
  node: tokens[i],
1521
- location: tokens[i][LOC],
2624
+ location: options.source.getSourceLocation(tokens[i][LOC].sta),
1522
2625
  });
1523
2626
  tokens[i].typ = EnumToken.InvalidCommentTokenType;
1524
2627
  continue;
@@ -1536,13 +2639,12 @@ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
1536
2639
  }
1537
2640
  for (; i < tokens.length; i++) {
1538
2641
  if (tokens[i].typ == EnumToken.CommentTokenType || tokens[i].typ == EnumToken.CDOCOMMTokenType) {
1539
- const location = tokens[i]?.[LOC];
1540
2642
  if (tokens[i].typ == EnumToken.CDOCOMMTokenType && context.typ != EnumToken.StyleSheetNodeType) {
1541
2643
  errors.push({
1542
2644
  action: "drop",
1543
2645
  message: `CDOCOMM not allowed here ${JSON.stringify(tokens[i], null, 1)}`,
1544
2646
  node: tokens[i],
1545
- location,
2647
+ location: options.source.getSourceLocation(tokens[i][LOC].sta),
1546
2648
  });
1547
2649
  tokens[i].typ = EnumToken.InvalidCommentTokenType;
1548
2650
  continue;
@@ -1623,7 +2725,7 @@ function parseNode(tokens, context, options, errors, stats, invalidNodes) {
1623
2725
  message: "<declaration> not allowed in <stylesheet>",
1624
2726
  action: "drop",
1625
2727
  node,
1626
- location: node[LOC],
2728
+ location: options.source.getSourceLocation(node[LOC].sta),
1627
2729
  });
1628
2730
  }
1629
2731
  else if (options.lenient || node.typ === EnumToken.DeclarationNodeType) {
@@ -1660,10 +2762,10 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1660
2762
  errors.push({
1661
2763
  action: "drop",
1662
2764
  node: atRule,
1663
- location: atRule[LOC],
2765
+ location: options.source.getSourceLocation(atRule[LOC].sta),
1664
2766
  message: "unknown at-rule",
1665
2767
  });
1666
- const result = matchGenericSyntax(stream);
2768
+ const result = matchGenericSyntax(stream, options);
1667
2769
  atRule[TOKENS] = parseTokens(stream);
1668
2770
  atRule[STATE] = result.success ? EnumAstNodeStatus.Unknown : EnumAstNodeStatus.Invalid;
1669
2771
  atRule[ERRORS] = result.success ? [errors[errors.length - 1]] : [errors[errors.length - 1], ...result.errors];
@@ -1681,7 +2783,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1681
2783
  errors.push({
1682
2784
  action: "drop",
1683
2785
  node: atRule,
1684
- location: atRule[LOC],
2786
+ location: options.source.getSourceLocation(atRule[LOC].sta),
1685
2787
  message: parseAsBlock ? "at-rule block not supported" : "at-rule block is required",
1686
2788
  });
1687
2789
  atRule[TOKENS] = parseTokens(stream);
@@ -1699,8 +2801,8 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1699
2801
  errors.push({
1700
2802
  action: "drop",
1701
2803
  node: token,
1702
- location: token[LOC],
1703
- message: `unexpected token ${EnumToken[token.typ]} at ${token[LOC].src}:${token[LOC].sta.lin}:${token[LOC].sta.col}`,
2804
+ location: options.source.getSourceLocation(token[LOC].sta),
2805
+ message: `unexpected token ${EnumToken[token.typ]} at ${token[LOC].srcId}:${token[LOC].sta}:${token[LOC].sta}`,
1704
2806
  });
1705
2807
  atRule[TOKENS] = parseTokens(stream);
1706
2808
  atRule[STATE] = EnumAstNodeStatus.Invalid;
@@ -1721,7 +2823,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1721
2823
  errors.push({
1722
2824
  action: "drop",
1723
2825
  node: atRule,
1724
- location: atRule[LOC],
2826
+ location: options.source.getSourceLocation(atRule[LOC].sta),
1725
2827
  message: parseAsBlock ? "at-rule block not supported" : "at-rule block is required",
1726
2828
  });
1727
2829
  atRule[TOKENS] = parseTokens(stream);
@@ -1744,7 +2846,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1744
2846
  errors.push({
1745
2847
  action: "drop",
1746
2848
  node: stream[0] ?? atRule,
1747
- location: (stream[0] ?? atRule)[LOC],
2849
+ location: options.source.getSourceLocation((stream[0] ?? atRule)[LOC].sta),
1748
2850
  message: "expecting <space>",
1749
2851
  });
1750
2852
  }
@@ -1753,7 +2855,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1753
2855
  errors.push({
1754
2856
  action: "drop",
1755
2857
  node: stream[1] ?? atRule,
1756
- location: (stream[1] ?? atRule)[LOC],
2858
+ location: options.source.getSourceLocation((stream[1] ?? atRule)[LOC].sta),
1757
2859
  message: "expecting <string>",
1758
2860
  });
1759
2861
  }
@@ -1762,7 +2864,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1762
2864
  errors.push({
1763
2865
  action: "drop",
1764
2866
  node: stream[1] ?? atRule,
1765
- location: (stream[1] ?? atRule)[LOC],
2867
+ location: options.source.getSourceLocation((stream[1] ?? atRule)[LOC].sta),
1766
2868
  message: "expecting double-quoted string",
1767
2869
  });
1768
2870
  }
@@ -1817,7 +2919,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1817
2919
  errors.push({
1818
2920
  action: "drop",
1819
2921
  node: atRule,
1820
- location: atRule[LOC],
2922
+ location: options.source.getSourceLocation(atRule[LOC].sta),
1821
2923
  message: `unexpected at-rule ${atRule.nam}`,
1822
2924
  });
1823
2925
  }
@@ -1828,8 +2930,8 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1828
2930
  errors.push({
1829
2931
  action: "drop",
1830
2932
  node: token,
1831
- location: token[LOC],
1832
- message: `unexpected token ${EnumToken[token.typ]} at ${token[LOC].src}:${token[LOC].sta.lin}:${token[LOC].sta.col}`,
2933
+ location: options.source.getSourceLocation(token[LOC].sta),
2934
+ message: `unexpected token ${EnumToken[token.typ]} at ${token[LOC].srcId}:${token[LOC].sta}:${token[LOC].sta}`,
1833
2935
  });
1834
2936
  }
1835
2937
  }
@@ -1889,8 +2991,8 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1889
2991
  errors.push({
1890
2992
  action: "drop",
1891
2993
  node: atRule,
1892
- location: atRule[LOC],
1893
- message: `expected <keyframe-name> at ${atRule[LOC].src}:${atRule[LOC].sta.lin}:${atRule[LOC].sta.col}`,
2994
+ location: options.source.getSourceLocation(atRule[LOC].sta),
2995
+ message: `expected <keyframe-name> at ${atRule[LOC].srcId}:${atRule[LOC].sta}:${atRule[LOC].sta}`,
1894
2996
  });
1895
2997
  success = false;
1896
2998
  }
@@ -1939,9 +3041,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1939
3041
  stream.splice(start - 1, end - start + 2, ...stream.slice(start, end));
1940
3042
  }
1941
3043
  }
1942
- // @ts-expect-error
1943
- options = { ...options, convertColor: false };
1944
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3044
+ atRule[LOC].end = stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end;
1945
3045
  atRule[TOKENS] = stream.slice();
1946
3046
  atRule[STATE] = valid ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
1947
3047
  atRule[ERRORS] = valid ? [] : result.errors;
@@ -1969,7 +3069,8 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
1969
3069
  stream.splice(0, 1, ...stream[0].chi);
1970
3070
  }
1971
3071
  }
1972
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3072
+ // @ts-expect-error
3073
+ atRule[LOC].end = stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end;
1973
3074
  atRule[TOKENS] = stream.slice();
1974
3075
  atRule[STATE] = result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
1975
3076
  atRule[ERRORS] = result.success ? [] : result.errors;
@@ -2027,7 +3128,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2027
3128
  errors.push({
2028
3129
  action: "drop",
2029
3130
  node: atRule,
2030
- location: atRule[LOC],
3131
+ location: options.source.getSourceLocation(atRule[LOC].sta),
2031
3132
  message: "at-rule @when is required before @else block",
2032
3133
  });
2033
3134
  }
@@ -2036,14 +3137,14 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2036
3137
  errors.push({
2037
3138
  action: "drop",
2038
3139
  node: atRule,
2039
- location: atRule[LOC],
3140
+ location: options.source.getSourceLocation(atRule[LOC].sta),
2040
3141
  message: "at-rule @else block is defined after last @else block",
2041
3142
  });
2042
3143
  }
2043
3144
  }
2044
3145
  // @ts-expect-error
2045
3146
  options = { ...options, minify: false, convertColor: false };
2046
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3147
+ atRule[LOC] = { ...atRule[LOC], end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end };
2047
3148
  atRule[TOKENS] = stream.slice();
2048
3149
  atRule[STATE] = success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2049
3150
  atRule[ERRORS] = result.success ? [] : [errors[errors.length - 1]].concat(result.errors);
@@ -2060,7 +3161,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2060
3161
  if (result.errors.length > 0) {
2061
3162
  errors.push(...result.errors);
2062
3163
  }
2063
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3164
+ atRule[LOC].end = stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end;
2064
3165
  atRule[TOKENS] = stream.slice();
2065
3166
  atRule[STATE] = result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2066
3167
  atRule[ERRORS] = result.success ? [] : result.errors;
@@ -2080,7 +3181,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2080
3181
  errors.push({
2081
3182
  action: "drop",
2082
3183
  node: range[0] ?? atRule,
2083
- location: (range[0] ?? atRule)[LOC],
3184
+ location: options.source.getSourceLocation((range[0] ?? atRule)[LOC].sta),
2084
3185
  message: "expected '(' at start of @scope block",
2085
3186
  });
2086
3187
  success = false;
@@ -2089,7 +3190,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2089
3190
  errors.push({
2090
3191
  action: "drop",
2091
3192
  node: range.at(-1) ?? atRule,
2092
- location: (range.at(-1) ?? atRule)[LOC],
3193
+ location: options.source.getSourceLocation((range.at(-1) ?? atRule)[LOC].sta),
2093
3194
  message: "expected ')' at end of @scope block",
2094
3195
  });
2095
3196
  success = false;
@@ -2115,7 +3216,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2115
3216
  errors.push({
2116
3217
  action: "drop",
2117
3218
  node: stream[index],
2118
- location: stream[index]?.[LOC],
3219
+ location: options.source.getSourceLocation(stream[index]?.[LOC].sta),
2119
3220
  message: "expected 'to' at end of @scope block",
2120
3221
  });
2121
3222
  success = false;
@@ -2128,7 +3229,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2128
3229
  errors.push({
2129
3230
  action: "drop",
2130
3231
  node: stream[index],
2131
- location: stream[index]?.[LOC],
3232
+ location: options.source.getSourceLocation(stream[index]?.[LOC].sta),
2132
3233
  message: "expected 'to' at end of @scope block",
2133
3234
  });
2134
3235
  success = false;
@@ -2141,7 +3242,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2141
3242
  errors.push({
2142
3243
  action: "drop",
2143
3244
  node: range.at(-1) ?? atRule,
2144
- location: (range.at(-1) ?? atRule)[LOC],
3245
+ location: options.source.getSourceLocation((range.at(-1) ?? atRule)[LOC].sta),
2145
3246
  message: "expected ')' at end of @scope block",
2146
3247
  });
2147
3248
  success = false;
@@ -2160,7 +3261,8 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2160
3261
  }
2161
3262
  }
2162
3263
  }
2163
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3264
+ // @ts-expect-error
3265
+ atRule[LOC].end = stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end;
2164
3266
  atRule[TOKENS] = stream.slice();
2165
3267
  atRule[STATE] = success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2166
3268
  atRule[ERRORS] = success ? [] : [errors[errors.length - 1]];
@@ -2173,7 +3275,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2173
3275
  }
2174
3276
  case "page": {
2175
3277
  trimArray(stream);
2176
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3278
+ atRule[LOC].end = stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end;
2177
3279
  atRule[TOKENS] = stream.slice();
2178
3280
  atRule[STATE] = success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2179
3281
  atRule[ERRORS] = success ? [] : [errors[errors.length - 1]];
@@ -2204,7 +3306,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2204
3306
  errors.push({
2205
3307
  action: "drop",
2206
3308
  node: atRule,
2207
- location: atRule[LOC],
3309
+ location: options.source.getSourceLocation(atRule[LOC].sta),
2208
3310
  message: "node is allowd only in @page rule",
2209
3311
  });
2210
3312
  }
@@ -2217,14 +3319,14 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2217
3319
  errors.push({
2218
3320
  action: "drop",
2219
3321
  node: stream[i],
2220
- location: stream[i][LOC],
3322
+ location: options.source.getSourceLocation(stream[i][LOC].sta),
2221
3323
  message: "expected whitespace or comment",
2222
3324
  });
2223
3325
  break;
2224
3326
  }
2225
3327
  }
2226
3328
  }
2227
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3329
+ atRule[LOC] = { ...atRule[LOC], end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end };
2228
3330
  atRule[TOKENS] = stream.slice();
2229
3331
  atRule[STATE] = success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2230
3332
  atRule[ERRORS] = success ? [] : [errors[errors.length - 1]];
@@ -2246,7 +3348,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2246
3348
  });
2247
3349
  stream.splice(index, 0, {
2248
3350
  typ: EnumToken.ColonTokenType,
2249
- [LOC]: { ...stream[index][LOC], end: { ...stream[index]?.[LOC]?.sta } },
3351
+ [LOC]: { ...stream[index][LOC], end: stream[index]?.[LOC]?.end },
2250
3352
  });
2251
3353
  isVarDeclaration = true;
2252
3354
  break;
@@ -2274,7 +3376,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2274
3376
  val: renderTokens(stream, options),
2275
3377
  [LOC]: {
2276
3378
  ...atRule[LOC],
2277
- end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) },
3379
+ end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end,
2278
3380
  },
2279
3381
  [TOKENS]: stream,
2280
3382
  [STATE]: EnumAstNodeStatus.Invalid,
@@ -2292,7 +3394,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2292
3394
  val: value,
2293
3395
  [LOC]: {
2294
3396
  ...atRule[LOC],
2295
- end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) },
3397
+ end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end,
2296
3398
  },
2297
3399
  [TOKENS]: stream,
2298
3400
  [STATE]: EnumAstNodeStatus.Validated,
@@ -2304,13 +3406,19 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2304
3406
  typ: EnumToken.CssVariableTokenType,
2305
3407
  nam: nam.val,
2306
3408
  val: value,
2307
- [LOC]: { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } },
3409
+ [LOC]: {
3410
+ ...atRule[LOC],
3411
+ end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end,
3412
+ },
2308
3413
  [TOKENS]: stream,
2309
3414
  [STATE]: EnumAstNodeStatus.Validated,
2310
3415
  [ERRORS]: [],
2311
3416
  };
2312
3417
  }
2313
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3418
+ atRule[LOC] = {
3419
+ ...atRule[LOC],
3420
+ end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end,
3421
+ };
2314
3422
  atRule[STATE] = EnumAstNodeStatus.Validated;
2315
3423
  atRule[ERRORS] = [];
2316
3424
  // @ts-expect-error
@@ -2328,7 +3436,7 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2328
3436
  // check commas , or ,,
2329
3437
  // check colon :
2330
3438
  // check or and and
2331
- result = matchGenericSyntax(stream);
3439
+ result = matchGenericSyntax(stream, options);
2332
3440
  if (result.errors.length > 0) {
2333
3441
  errors.push(...result.errors);
2334
3442
  }
@@ -2364,7 +3472,10 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2364
3472
  }
2365
3473
  }
2366
3474
  }
2367
- atRule[LOC] = { ...atRule[LOC], end: { ...(stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end) } };
3475
+ atRule[LOC] = {
3476
+ ...atRule[LOC],
3477
+ end: stream.at(-1)?.[LOC]?.end ?? atRule[LOC].end,
3478
+ };
2368
3479
  atRule[TOKENS] = stream.slice();
2369
3480
  atRule[STATE] = result.success ? EnumAstNodeStatus.Validated : EnumAstNodeStatus.Invalid;
2370
3481
  atRule[ERRORS] = result.errors;
@@ -2389,12 +3500,14 @@ function parseAtRule(stream, context, options, errors, parseAsBlock = null) {
2389
3500
  * ```
2390
3501
  */
2391
3502
  async function parseDeclarations(declaration) {
3503
+ const stream = `.x{${declaration}}`;
2392
3504
  return doParse(tokenize({
2393
- stream: `.x{${declaration}}`,
3505
+ stream,
2394
3506
  buffer: "",
2395
3507
  offset: 0,
2396
- position: { ind: 0, lin: 1, col: 1 },
2397
- currentPosition: { ind: -1, lin: 1, col: 0 },
3508
+ position: 0,
3509
+ source: new SourceFile(stream, [], ""),
3510
+ currentPosition: -1,
2398
3511
  }), { setParent: false, minify: false, validation: false }).then((result) => {
2399
3512
  return result.ast.chi[0].chi.filter((t) => t.typ == EnumToken.DeclarationNodeType || t.typ == EnumToken.CommentNodeType);
2400
3513
  });
@@ -2424,12 +3537,12 @@ async function parseDeclarations(declaration) {
2424
3537
  function parseString(src, options = { parseColor: true }, errors) {
2425
3538
  const parseInfo = {
2426
3539
  stream: src,
2427
- src: options?.src ?? "",
2428
3540
  buffer: "",
2429
3541
  offset: 0,
2430
3542
  time: 0,
2431
- position: { ind: 0, lin: 1, col: 1 },
2432
- currentPosition: { ind: -1, lin: 1, col: 0 },
3543
+ source: new SourceFile(src, [], ""),
3544
+ position: 0,
3545
+ currentPosition: -1,
2433
3546
  };
2434
3547
  const result = parseTokens([...tokenize(parseInfo)].map((t) => t.token), options, errors);
2435
3548
  // remove EOF token
@@ -2495,9 +3608,9 @@ function parseTokens(tokens, options, errors) {
2495
3608
  const node = stack.at(-1);
2496
3609
  errors?.push?.({
2497
3610
  action: "drop",
2498
- message: `Unbalanced token ')' at ${node[LOC].src}:${node[LOC].sta.lin}:${node[LOC].sta.col}`,
3611
+ message: `Unbalanced token ')'`,
2499
3612
  node,
2500
- location: node[LOC],
3613
+ location: options.source.getSourceLocation(node[LOC].sta),
2501
3614
  });
2502
3615
  // return [];
2503
3616
  continue;
@@ -2523,9 +3636,9 @@ function parseTokens(tokens, options, errors) {
2523
3636
  const node = stack.at(-1);
2524
3637
  errors?.push?.({
2525
3638
  action: "drop",
2526
- message: `Unbalanced token ']' at ${node[LOC].src}:${node[LOC].sta.lin}:${node[LOC].sta.col}`,
3639
+ message: `Unbalanced token ']'`,
2527
3640
  node,
2528
- location: node[LOC],
3641
+ location: options.source.getSourceLocation(node[LOC].sta),
2529
3642
  });
2530
3643
  // return [];
2531
3644
  continue;
@@ -2648,11 +3761,11 @@ function parseTokens(tokens, options, errors) {
2648
3761
  action: "drop",
2649
3762
  message: `Unbalanced token. Expecting ${node.typ === EnumToken.AttrStartTokenType ? "']'" : ")"}'`,
2650
3763
  node,
2651
- location: node[LOC],
3764
+ location: options.source.getSourceLocation(node[LOC].sta),
2652
3765
  });
2653
3766
  // return [];
2654
3767
  }
2655
3768
  return tokens;
2656
3769
  }
2657
3770
 
2658
- export { doParse, generateScopedName, getKeyName, getShortNameGenerator, parseAtRule, parseDeclarations, parseString, parseTokens, trimWhiteSpace };
3771
+ export { doParse, doParseSync, generateScopedName, generateSyncScopedName, getKeyName, getShortNameGenerator, parseAtRule, parseDeclarations, parseString, parseTokens, trimWhiteSpace };