@fluixi-css/core 1.0.0-next.4 → 1.0.0-next.5

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.
@@ -380,1354 +380,677 @@ function write(node, depth, opts, w) {
380
380
  w.emit("".concat(pad, "}").concat(nl));
381
381
  }
382
382
 
383
- // Parses one raw utility (e.g. `md:hover:-bg-red-500/50!` or `[&_p]:text-[13px]`)
384
- // into a structured Atom in a single pass. Splitting is bracket/paren aware,
385
- // so `:` `/` `-` inside arbitrary values are left alone — no regex, no
386
- // backtracking. Which part is the root and which is the value can't be known from
387
- // the string alone (`text-red-500` vs `grid-cols-3`), so that split is resolved
388
- // against the registry through AtomContext.
383
+ // ─── Charcode constants (avoids string allocation on hot paths) ───────────────
384
+ var CC_TAB = 9,
385
+ CC_LF = 10,
386
+ CC_CR = 13,
387
+ CC_FF = 12,
388
+ CC_SPACE = 32;
389
+ var CC_DQUOTE = 34,
390
+ CC_HASH = 35,
391
+ CC_AMP = 38,
392
+ CC_SQUOTE = 39;
393
+ var CC_LPAREN = 40,
394
+ CC_RPAREN = 41,
395
+ CC_STAR = 42,
396
+ CC_PLUS = 43;
397
+ var CC_COMMA = 44,
398
+ CC_MINUS = 45,
399
+ CC_DOT = 46,
400
+ CC_SLASH = 47;
401
+ var CC_COLON = 58,
402
+ CC_SEMI = 59,
403
+ CC_GT = 62;
404
+ var CC_AT = 64,
405
+ CC_LBRACK = 91,
406
+ CC_BSLASH = 92,
407
+ CC_RBRACK = 93;
408
+ var CC_UNDER = 95,
409
+ CC_LBRACE = 123,
410
+ CC_RBRACE = 125,
411
+ CC_TILDE = 126;
389
412
 
390
- // Split on `sep` at depth 0 only; `[...]` and `(...)` are opaque, and `\` escapes
391
- // the next character.
392
- function splitAtTopLevel(input, sep) {
393
- var out = [];
394
- var depthBracket = 0;
395
- var depthParen = 0;
396
- var start = 0;
397
- for (var i = 0; i < input.length; i++) {
398
- var c = input[i];
399
- if (c === '\\') {
400
- i++; // skip the escaped char
401
- continue;
402
- }
403
- if (c === '[') depthBracket++;else if (c === ']') depthBracket = Math.max(0, depthBracket - 1);else if (c === '(') depthParen++;else if (c === ')') depthParen = Math.max(0, depthParen - 1);else if (c === sep && depthBracket === 0 && depthParen === 0) {
404
- out.push(input.slice(start, i));
405
- start = i + 1;
406
- }
407
- }
408
- out.push(input.slice(start));
409
- return out;
410
- }
413
+ // ─── Character predicates (charcode-based, no regex) ─────────────────────────
411
414
 
412
- // Content of a `[...]` or `(...)` wrapper, or null when `s` isn't wrapped.
413
- function unwrap(s, open) {
414
- var close = open === '[' ? ']' : ')';
415
- return s.length >= 2 && s[0] === open && s[s.length - 1] === close ? s.slice(1, -1) : null;
416
- }
417
- function parseModifier(raw) {
418
- if (!raw) return null;
419
- var arb = unwrap(raw, '[');
420
- if (arb !== null) return {
421
- kind: 'arbitrary',
422
- value: arb
423
- };
424
- // `(--name)` is shorthand for the custom property it references.
425
- var paren = unwrap(raw, '(');
426
- if (paren !== null) return {
427
- kind: 'arbitrary',
428
- value: "var(".concat(paren, ")")
429
- };
430
- return {
431
- kind: 'named',
432
- value: raw
433
- };
415
+ function isWS(c) {
416
+ return c === CC_SPACE || c === CC_TAB || c === CC_LF || c === CC_CR || c === CC_FF;
434
417
  }
435
- function splitModifier(base) {
436
- var parts = splitAtTopLevel(base, '/');
437
- if (parts.length === 1) return {
438
- base: base,
439
- modifier: null
440
- };
441
- var modifier = parseModifier(parts.slice(1).join('/'));
442
- return {
443
- base: parts[0],
444
- modifier: modifier
445
- };
418
+ function isDigit(c) {
419
+ return c >= 48 && c <= 57;
446
420
  }
447
-
448
- // In arbitrary values `_` stands in for a space; `\_` is a literal underscore.
449
- function decodeUnderscores(value) {
450
- // `_` → space, `\_` → literal `_`. But a URL may legitimately contain underscores,
451
- // so leave the inside of `url(...)` verbatim (the split keeps url() at odd indices).
452
- return value.split(/(url\([^)]*\))/g).map(function (part, i) {
453
- return i % 2 === 1 ? part : part.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
454
- }).join('');
421
+ function isAlpha(c) {
422
+ return c >= 65 && c <= 90 || c >= 97 && c <= 122;
455
423
  }
456
-
457
- // An arbitrary value may lead with a `type:` hint, e.g. `[length:12px]`.
458
- function parseArbitraryValue(body) {
459
- var colon = body.indexOf(':');
460
- if (colon > 0) {
461
- var maybeType = body.slice(0, colon);
462
- if (/^[a-z-]+$/.test(maybeType)) {
463
- return {
464
- dataType: maybeType,
465
- value: decodeUnderscores(body.slice(colon + 1))
466
- };
467
- }
468
- }
469
- return {
470
- dataType: null,
471
- value: decodeUnderscores(body)
472
- };
424
+ function isHex(c) {
425
+ return isDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
473
426
  }
474
-
475
- // The `(--name)` shorthand, optionally typed: `(length:--size)`. The custom
476
- // property name keeps its underscores.
477
- function parseParenValue(paren) {
478
- var colon = paren.indexOf(':');
479
- if (colon > 0 && /^[a-z-]+$/.test(paren.slice(0, colon))) {
480
- return {
481
- dataType: paren.slice(0, colon),
482
- value: "var(".concat(paren.slice(colon + 1), ")")
483
- };
484
- }
485
- return {
486
- dataType: null,
487
- value: "var(".concat(paren, ")")
488
- };
427
+ /**
428
+ * CSS ident-start: letter | underscore | non-ASCII | hyphen.
429
+ * A leading hyphen is valid (vendor prefixes, custom properties).
430
+ */
431
+ function isNameStart(c) {
432
+ return isAlpha(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
489
433
  }
490
- function parseVariant(raw) {
491
- var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
492
- if (!raw) return null;
493
-
494
- // `[&:hover]`, `[@media(...)]` — the selector is written out; a `&` means it's
495
- // relative to the element.
496
- var arb = unwrap(raw, '[');
497
- if (arb !== null) {
498
- return {
499
- kind: 'arbitrary',
500
- selector: arb,
501
- relative: arb.includes('&')
502
- };
503
- }
504
- var _splitModifier = splitModifier(raw),
505
- base = _splitModifier.base,
506
- modifier = _splitModifier.modifier;
507
-
508
- // A variant carrying a value: `group-hover`, `data-[open]`, `supports-[display:grid]`.
509
- var dash = base.indexOf('-');
510
- if (dash > 0) {
511
- var _ctx$isDynamicVariant, _ctx$isDynamicVariant2;
512
- var _root = base.slice(0, dash);
513
- var rest = base.slice(dash + 1);
514
- if ((_ctx$isDynamicVariant = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant !== void 0 && _ctx$isDynamicVariant.call(ctx, _root) || (_ctx$isDynamicVariant2 = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant2 !== void 0 && _ctx$isDynamicVariant2.call(ctx, _root + '-')) {
515
- // A variant's `[...]` is a raw condition/attribute, not a typed value.
516
- var arbVal = unwrap(rest, '[');
517
- var value = arbVal !== null ? {
518
- kind: 'arbitrary',
519
- value: arbVal,
520
- dataType: null
521
- } : {
522
- kind: 'named',
523
- value: rest
524
- };
525
- return {
526
- kind: 'functional',
527
- root: _root,
528
- value: value,
529
- modifier: modifier
530
- };
531
- }
532
- }
533
- return {
534
- kind: 'functional',
535
- root: base,
536
- value: null,
537
- modifier: modifier
538
- };
434
+ /** CSS ident-char: ident-start | digit */
435
+ function isNameChar(c) {
436
+ return isAlpha(c) || isDigit(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
539
437
  }
540
438
 
541
- // Returns null for structurally invalid input (empty or dangling segments).
542
- // Without a context the root/value split falls back to the first dash, which is
543
- // enough to test the scanner on its own.
544
- function parseAtom(raw) {
545
- var _ctx$isRule, _ctx$isRule2;
546
- var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
547
- if (!raw) return null;
548
- var segments = splitAtTopLevel(raw, ':');
549
- var utility = segments.pop();
550
- if (utility === undefined || utility === '') return null;
551
- var variants = [];
552
- var _iterator = _createForOfIteratorHelper(segments),
553
- _step;
554
- try {
555
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
556
- var seg = _step.value;
557
- if (seg === '') return null; // dangling `::`
558
- var v = parseVariant(seg, ctx);
559
- if (!v) return null;
560
- variants.push(v);
561
- }
562
- // Written left-to-right (outermost first), stored innermost-first so consumers
563
- // can wrap the declaration outward.
564
- } catch (err) {
565
- _iterator.e(err);
566
- } finally {
567
- _iterator.f();
568
- }
569
- variants.reverse();
439
+ // ─── Block context ────────────────────────────────────────────────────────────
570
440
 
571
- // `!` marks important, accepted on either end.
572
- var body = utility;
573
- var important = false;
574
- if (body.endsWith('!')) {
575
- important = true;
576
- body = body.slice(0, -1);
577
- } else if (body.startsWith('!')) {
578
- important = true;
579
- body = body.slice(1);
580
- }
581
- if (body === '') return null;
441
+ /**
442
+ * Determines what may legally appear inside a block:
443
+ * stylesheet – top-level: rules + at-rules
444
+ * mixed – @media/@supports/@container/@layer: rules + at-rules
445
+ * rule – inside a style rule: declarations + optional CSS nesting
446
+ * keyframes – inside @keyframes: keyframe stops (from/to/%)
447
+ * declarations– @font-face/@page/etc.: declarations only
448
+ */
582
449
 
583
- // Split off a trailing `/modifier` once, up front — it applies uniformly to
584
- // arbitrary-property, static, and functional atoms.
585
- var _splitModifier2 = splitModifier(body),
586
- core0 = _splitModifier2.base,
587
- modifier = _splitModifier2.modifier;
450
+ // ─── CssParser ────────────────────────────────────────────────────────────────
588
451
 
589
- // Arbitrary property: `[color:red]`, `[--my-var:0]` (optionally with modifier).
590
- var arbProp = unwrap(core0, '[');
591
- if (arbProp !== null && arbProp.includes(':')) {
592
- var colon = arbProp.indexOf(':');
593
- if (colon <= 0) return null;
594
- // The head must be a real CSS property or custom property. Scanners pull
595
- // `[...]` runs out of JS/TS too (array/object literals like
596
- // `[...prev, { value } as T]`); rejecting a non-property head keeps those
597
- // from emitting broken rules that later crash the CSS parser.
598
- var property = arbProp.slice(0, colon);
599
- if (!/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return null;
600
- return {
601
- kind: 'arbitrary-property',
602
- property: property,
603
- value: decodeUnderscores(arbProp.slice(colon + 1)),
604
- modifier: modifier,
605
- important: important,
606
- variants: variants,
607
- raw: raw
608
- };
609
- }
610
-
611
- // Negative.
612
- var negative = false;
613
- var base = core0;
614
- if (base[0] === '-') {
615
- negative = true;
616
- base = base.slice(1);
617
- if (base === '') return null;
618
- }
619
-
620
- // Static utility (only when unambiguous: no negative/modifier).
621
- if (!negative && modifier === null && (_ctx$isRule = ctx.isRule) !== null && _ctx$isRule !== void 0 && _ctx$isRule.call(ctx, base)) {
622
- return {
623
- kind: 'static',
624
- root: base,
625
- important: important,
626
- variants: variants,
627
- raw: raw
628
- };
452
+ var CssParser = /*#__PURE__*/function () {
453
+ function CssParser() {
454
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
455
+ _classCallCheck(this, CssParser);
456
+ _defineProperty(this, "input", '');
457
+ _defineProperty(this, "pos", 0);
458
+ _defineProperty(this, "length", 0);
459
+ _defineProperty(this, "line", 1);
460
+ _defineProperty(this, "col", 1);
461
+ _defineProperty(this, "errors", []);
462
+ _defineProperty(this, "warnings", []);
463
+ _defineProperty(this, "stats", CssParser.emptyStats());
464
+ this.options = _objectSpread2({
465
+ parseAtrulePrelude: true,
466
+ parseValue: true,
467
+ parseCustomProperty: true,
468
+ parseRulePrelude: true,
469
+ parseSelector: true,
470
+ includeComments: true,
471
+ includeSourceMaps: true,
472
+ includeSpecificity: true,
473
+ includeVendorPrefixes: true,
474
+ onError: function onError() {/* noop */},
475
+ onWarning: function onWarning() {/* noop */},
476
+ maxDepth: 100,
477
+ maxNodes: 100000,
478
+ enableNesting: true,
479
+ enableCustomProperties: true,
480
+ enableLogicalProperties: true,
481
+ enableContainerQueries: true,
482
+ enableLayerQueries: true,
483
+ enableSupportsQueries: true,
484
+ // middleware — undefined by default (fast path skips them)
485
+ onRule: undefined,
486
+ onAtRule: undefined,
487
+ onDeclaration: undefined,
488
+ onComment: undefined,
489
+ onKeyframe: undefined
490
+ }, options);
629
491
  }
630
492
 
631
- // Functional: split root ↔ value. Prefer the longest known functional root;
632
- // fall back to the first-dash split when no context is supplied.
633
- var _splitRootValue = splitRootValue(base, ctx),
634
- root = _splitRootValue.root,
635
- valueStr = _splitRootValue.valueStr;
636
- if (root === '') return null;
637
- var value = null;
638
- if (valueStr !== null && valueStr !== '') {
639
- var arbVal = unwrap(valueStr, '[');
640
- if (arbVal !== null) {
641
- value = _objectSpread2({
642
- kind: 'arbitrary'
643
- }, parseArbitraryValue(arbVal));
644
- } else {
645
- var paren = unwrap(valueStr, '(');
646
- value = paren !== null ? _objectSpread2({
647
- kind: 'arbitrary'
648
- }, parseParenValue(paren)) : {
649
- kind: 'named',
650
- value: valueStr,
651
- fraction: null
652
- };
493
+ // ── Public API ────────────────────────────────────────────────────────────
494
+ return _createClass(CssParser, [{
495
+ key: "parse",
496
+ value: function parse(css) {
497
+ var t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
498
+ this.reset(css);
499
+ var sheet = this.parseStylesheet();
500
+ this.stats.parseTime = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0;
501
+ return sheet;
653
502
  }
654
- } else if ((_ctx$isRule2 = ctx.isRule) !== null && _ctx$isRule2 !== void 0 && _ctx$isRule2.call(ctx, base)) {
655
- // A bare root that is registered static (reached here due to a modifier).
656
- return {
657
- kind: 'static',
658
- root: base,
659
- important: important,
660
- variants: variants,
661
- raw: raw
662
- };
663
- }
664
- return {
665
- kind: 'functional',
666
- root: root,
667
- value: value,
668
- modifier: modifier,
669
- important: important,
670
- negative: negative,
671
- variants: variants,
672
- raw: raw
673
- };
674
- }
675
-
676
- // Splits `bg-red-500` into a root and value. The longest registered root wins
677
- // (`grid-cols-3` → `grid-cols` + `3`); with no context, split at the first dash.
678
- function splitRootValue(base, ctx) {
679
- if (ctx.isDynamicRule) {
680
- // The whole class is itself the longest possible root (`rounded-t`, `border-x`);
681
- // prefer it before splitting off a shorter registered prefix (`rounded` + `t`).
682
- if (ctx.isDynamicRule(base)) return {
683
- root: base,
684
- valueStr: null
685
- };
686
- var dashes = [];
687
- for (var i = 0; i < base.length; i++) if (base[i] === '-') dashes.push(i);
688
- for (var d = dashes.length - 1; d >= 0; d--) {
689
- var idx = dashes[d];
690
- var _root2 = base.slice(0, idx);
691
- if (ctx.isDynamicRule(_root2)) return {
692
- root: _root2,
693
- valueStr: base.slice(idx + 1)
694
- };
503
+ }, {
504
+ key: "getErrors",
505
+ value: function getErrors() {
506
+ return _toConsumableArray(this.errors);
695
507
  }
696
- }
697
- var first = base.indexOf('-');
698
- if (first <= 0) return {
699
- root: base,
700
- valueStr: null
701
- };
702
- return {
703
- root: base.slice(0, first),
704
- valueStr: base.slice(first + 1)
705
- };
706
- }
707
-
708
- // Turns a parsed atom into CSS. Returns null when the utility or any of its
709
- // variants aren't registered, so an unknown class simply produces nothing.
710
- function compileAtom(atom, reg) {
711
- var produced = producedFor(atom, reg);
712
- if (!produced || produced.length === 0) return null;
713
- var flat = [];
714
- var nested = [];
715
- var _iterator = _createForOfIteratorHelper(produced),
716
- _step;
717
- try {
718
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
719
- var node = _step.value;
720
- if (node.kind === 'declaration') flat.push(node);else nested.push(node);
508
+ }, {
509
+ key: "getWarnings",
510
+ value: function getWarnings() {
511
+ return _toConsumableArray(this.warnings);
721
512
  }
722
- } catch (err) {
723
- _iterator.e(err);
724
- } finally {
725
- _iterator.f();
726
- }
727
- if (atom.important) {
728
- var _iterator2 = _createForOfIteratorHelper(flat),
729
- _step2;
730
- try {
731
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
732
- var d = _step2.value;
733
- d.important = true;
734
- }
735
- } catch (err) {
736
- _iterator2.e(err);
737
- } finally {
738
- _iterator2.f();
513
+ }, {
514
+ key: "getStats",
515
+ value: function getStats() {
516
+ return _objectSpread2({}, this.stats);
739
517
  }
740
- var _iterator3 = _createForOfIteratorHelper(nested),
741
- _step3;
742
- try {
743
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
744
- var n = _step3.value;
745
- markImportant$1(n.nodes);
746
- }
747
- } catch (err) {
748
- _iterator3.e(err);
749
- } finally {
750
- _iterator3.f();
518
+ }, {
519
+ key: "toLegacyFormat",
520
+ value: function toLegacyFormat(stylesheet) {
521
+ var _this = this;
522
+ return stylesheet.children.map(function (c) {
523
+ return _this.toLegacyNode(c);
524
+ }).filter(Boolean);
751
525
  }
752
- }
753
- var selector = '.' + escapeClass(atom.raw);
754
- var atRules = [];
755
- var _iterator4 = _createForOfIteratorHelper(atom.variants),
756
- _step4;
757
- try {
758
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
759
- var variant = _step4.value;
760
- var wrap = resolveVariant(variant, reg);
761
- if (!wrap) return null;
762
- if (wrap.selector) selector = substitute(wrap.selector, selector);
763
- if (wrap.atRule) atRules.push(wrap.atRule);
526
+
527
+ // ── Reset ─────────────────────────────────────────────────────────────────
528
+ }, {
529
+ key: "reset",
530
+ value: function reset(css) {
531
+ this.input = css;
532
+ this.pos = 0;
533
+ this.length = css.length;
534
+ this.line = 1;
535
+ this.col = 1;
536
+ this.errors = [];
537
+ this.warnings = [];
538
+ this.stats = CssParser.emptyStats();
764
539
  }
540
+ }, {
541
+ key: "parseStylesheet",
542
+ value:
543
+ // ── Stylesheet ────────────────────────────────────────────────────────────
765
544
 
766
- // Flat declarations sit on the utility's own selector; nested rules weave that
767
- // selector into their `&` (`space-x-4` → `.space-x-4 > :not([hidden]) ~ …`).
768
- } catch (err) {
769
- _iterator4.e(err);
770
- } finally {
771
- _iterator4.f();
772
- }
773
- var nodes = [];
774
- if (flat.length) nodes.push(rule(selector, flat));
775
- for (var _i = 0, _nested = nested; _i < _nested.length; _i++) {
776
- var _n = _nested[_i];
777
- nodes.push(rule(substitute(_n.selector, selector), _n.nodes));
778
- }
779
- for (var _i2 = 0, _atRules = atRules; _i2 < _atRules.length; _i2++) {
780
- var ar = _atRules[_i2];
781
- nodes = [atRule(ar.name, ar.params, nodes)];
782
- }
783
- return nodes;
784
- }
785
- function markImportant$1(nodes) {
786
- var _iterator5 = _createForOfIteratorHelper(nodes),
787
- _step5;
788
- try {
789
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
790
- var n = _step5.value;
791
- if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant$1(n.nodes);
792
- }
793
- } catch (err) {
794
- _iterator5.e(err);
795
- } finally {
796
- _iterator5.f();
797
- }
798
- }
799
- function producedFor(atom, reg) {
800
- if (atom.kind === 'arbitrary-property') {
801
- return [decl(atom.property, atom.value)];
802
- }
803
- if (atom.kind === 'static') {
804
- // Clone: static templates are shared, and `!important` / `&`-weaving mutate.
805
- var products = reg.getRule(atom.root);
806
- return products ? products.map(cloneProduct) : null;
807
- }
808
- var handler = reg.getDynamicRule(atom.root);
809
- if (!handler) return null;
810
- return handler({
811
- value: atom.value,
812
- modifier: atom.modifier,
813
- negative: atom.negative,
814
- theme: reg.theme
815
- });
816
- }
817
- function cloneProduct(n) {
818
- return n.kind === 'declaration' ? _objectSpread2({}, n) : cloneNode(n);
819
- }
820
- function cloneNode(n) {
821
- if (n.kind === 'declaration') return _objectSpread2({}, n);
822
- if (n.kind === 'rule') return rule(n.selector, n.nodes.map(cloneNode));
823
- if (n.kind === 'at-rule') return atRule(n.name, n.params, n.nodes.map(cloneNode));
824
- return _objectSpread2({}, n);
825
- }
826
- function resolveVariant(variant, reg) {
827
- if (variant.kind === 'arbitrary') return arbitraryVariant(variant.selector);
828
- if (variant.kind === 'static') return reg.getVariant(variant.root);
829
- // functional: a null value means it's really a static variant (hover, md, …).
830
- if (variant.value === null) return reg.getVariant(variant.root);
831
- var handler = reg.getDynamicVariant(variant.root);
832
- return handler ? handler(variant.value, variant.modifier) : null;
833
- }
834
-
835
- // `[&_p]` → `& p`, `[.parent_&]` → `.parent &`, `[@media(...)]` → an at-rule.
836
- // A bare selector with no `&` is attached to the element.
837
- function arbitraryVariant(source) {
838
- if (source[0] === '@') {
839
- var cut = source.search(/[\s(]/);
840
- var name = cut === -1 ? source.slice(1) : source.slice(1, cut);
841
- var params = cut === -1 ? '' : source.slice(cut).trim();
842
- return {
843
- atRule: {
844
- name: name,
845
- params: params
545
+ function parseStylesheet() {
546
+ var locStart = this.locPos();
547
+ var ss = {
548
+ type: 'stylesheet',
549
+ source: this.input,
550
+ children: [],
551
+ charset: undefined,
552
+ imports: [],
553
+ namespaces: [],
554
+ mediaQueries: [],
555
+ keyframes: [],
556
+ fontFaces: [],
557
+ layers: [],
558
+ containers: [],
559
+ supports: [],
560
+ documents: [],
561
+ pages: [],
562
+ counterStyles: [],
563
+ fontFeatureValues: [],
564
+ viewports: [],
565
+ charsets: []
566
+ };
567
+ while (this.pos < this.length) {
568
+ this.skipWS();
569
+ if (this.pos >= this.length) break;
570
+ var node = this.parseTopNode();
571
+ if (node) {
572
+ ss.children.push(node);
573
+ this.categorize(ss, node);
574
+ this.stats.totalNodes++;
575
+ }
846
576
  }
847
- };
848
- }
849
- var sel = spacesFromUnderscores(source);
850
- return {
851
- selector: sel.includes('&') ? sel : "&".concat(sel)
852
- };
853
- }
854
- function spacesFromUnderscores(s) {
855
- return s.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
856
- }
857
- function substitute(template, current) {
858
- return template.replace(/&/g, current);
859
- }
860
-
861
- // Backslash-escape everything outside [A-Za-z0-9_-] so a utility name is a valid
862
- // class selector (`hover:bg-red-500/50` → `hover\:bg-red-500\/50`).
863
- function escapeClass(name) {
864
- return name.replace(/[^a-zA-Z0-9_-]/g, function (c) {
865
- return '\\' + c;
866
- });
867
- }
868
-
869
- // `@apply a b c;` — inline the declarations those utilities produce into the
870
- // surrounding rule. Operates on author-CSS text (which `transform` passes through
871
- // verbatim), replacing each `@apply` at-rule in place. Flat utilities inline as
872
- // declarations; utilities that need their own selector (variants like `hover:` /
873
- // `group-hover:`, child-combinators like `space-x`, at-rule variants like `md:`)
874
- // emit a nested rule with `&` bound to the applying selector.
875
- var APPLY_RE = /@apply\s+([^;{}]+);/g;
876
- function expandApply(css, reg) {
877
- if (!css.includes('@apply')) return css;
878
- return css.replace(APPLY_RE, function (_match, listRaw) {
879
- var list = listRaw.trim();
880
- // A trailing `!important` marks every inlined declaration (Tailwind semantics).
881
- var important = false;
882
- var bang = list.match(/!important\s*$/);
883
- if (bang) {
884
- important = true;
885
- list = list.slice(0, bang.index).trim();
886
- }
887
- var decls = [];
888
- var rules = [];
889
- var _iterator = _createForOfIteratorHelper(list.split(/\s+/)),
890
- _step;
891
- try {
892
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
893
- var token = _step.value;
894
- if (!token) continue;
895
- var out = compileForApply(token, reg, important);
896
- if (!out) continue;
897
- if (out.decls) decls.push.apply(decls, _toConsumableArray(out.decls));
898
- if (out.rule) rules.push(out.rule);
577
+ if (this.options.includeSourceMaps) {
578
+ ss.loc = {
579
+ start: locStart,
580
+ end: this.locPos(),
581
+ source: this.input
582
+ };
899
583
  }
900
- // Flat declarations first, then nested rules — same order as authored.
901
- } catch (err) {
902
- _iterator.e(err);
903
- } finally {
904
- _iterator.f();
584
+ return ss;
905
585
  }
906
- return [].concat(decls, rules).join(' ');
907
- });
908
- }
909
- function compileForApply(cls, reg, important) {
910
- var atom = parseAtom(cls, reg);
911
- if (!atom) return null;
912
- var compiled = compileAtom(atom, reg);
913
- if (!compiled || compiled.length === 0) return null;
914
- var classSelector = '.' + escapeClass(atom.raw);
915
586
 
916
- // A plain utility — one rule on the class itself with only declarations — inlines
917
- // straight into the applying rule.
918
- if (compiled.length === 1 && compiled[0].kind === 'rule' && compiled[0].selector === classSelector) {
919
- var flat = compiled[0].nodes;
920
- if (flat.every(function (n) {
921
- return n.kind === 'declaration';
922
- })) {
923
- return {
924
- decls: flat.map(function (n) {
925
- return declText(n, important);
926
- })
927
- };
587
+ // ── Top-level node dispatch ───────────────────────────────────────────────
588
+ }, {
589
+ key: "parseTopNode",
590
+ value: function parseTopNode() {
591
+ var c = this.peek();
592
+ if (c === CC_SLASH && this.peek(1) === CC_STAR) {
593
+ var comment = this.parseComment();
594
+ return this.options.includeComments ? comment : null;
595
+ }
596
+ if (c === CC_AT) return this.parseAtRule();
597
+ // Skip stray closing braces that can appear in malformed CSS
598
+ if (c === CC_RBRACE) {
599
+ this.advance();
600
+ return null;
601
+ }
602
+ return this.parseRule();
928
603
  }
929
- }
930
604
 
931
- // Everything else keeps its structure but nests: swap the class's own selector
932
- // for `&`, so `hover:` → `&:hover`, `group-hover:` → `.group:hover &`, `md:` →
933
- // `@media(...) { & { … } }`.
934
- if (important) markImportant(compiled);
935
- var text = stringify(compiled, {
936
- minify: false
937
- }).split(classSelector).join('&');
938
- return {
939
- rule: text
940
- };
941
- }
942
- function declText(d, important) {
943
- return "".concat(d.property, ": ").concat(d.value).concat(important || d.important ? ' !important' : '', ";");
944
- }
945
- function markImportant(nodes) {
946
- var _iterator2 = _createForOfIteratorHelper(nodes),
947
- _step2;
948
- try {
949
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
950
- var n = _step2.value;
951
- if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant(n.nodes);
605
+ // ── Block-level node dispatch ─────────────────────────────────────────────
606
+ }, {
607
+ key: "parseBlockNode",
608
+ value: function parseBlockNode(mode) {
609
+ this.skipWS();
610
+ if (this.pos >= this.length || this.peek() === CC_RBRACE) return null;
611
+ var c = this.peek();
612
+ if (c === CC_SLASH && this.peek(1) === CC_STAR) {
613
+ var comment = this.parseComment();
614
+ return this.options.includeComments ? comment : null;
615
+ }
616
+ if (c === CC_AT) return this.parseAtRule(mode);
617
+ switch (mode) {
618
+ case 'keyframes':
619
+ return this.parseKeyframeStop();
620
+ case 'declarations':
621
+ return this.parseDeclaration();
622
+ case 'mixed':
623
+ case 'stylesheet':
624
+ if (c === CC_RBRACE) return null;
625
+ return this.parseRule();
626
+ case 'rule':
627
+ default:
628
+ // Unambiguous nesting-selector starters
629
+ if (this.isNestingStart(c)) return this.parseRule();
630
+ // Lookahead: first unescaped { at depth 0 → rule, ; or } → declaration
631
+ if (this.lookaheadIsRule()) return this.parseRule();
632
+ // console.log('parse block', c, mode);
633
+ return this.parseDeclaration();
634
+ }
952
635
  }
953
- } catch (err) {
954
- _iterator2.e(err);
955
- } finally {
956
- _iterator2.f();
957
- }
958
- }
959
-
960
- // Renders a `transform()` result as a compact, colourised build line for the
961
- // Vite/PostCSS plugins to print. Pure (returns a string) so css-core stays
962
- // side-effect free — the plugins own the actual `console.log`.
963
-
964
- var ANSI = {
965
- reset: '\x1b[0m',
966
- dim: '\x1b[2m',
967
- bold: '\x1b[1m',
968
- cyan: '\x1b[36m',
969
- green: '\x1b[32m',
970
- yellow: '\x1b[33m',
971
- red: '\x1b[31m'
972
- };
973
- function paint(code, s, color) {
974
- return color ? code + s + ANSI.reset : s;
975
- }
976
- function humanBytes(n) {
977
- return n < 1024 ? "".concat(n, " B") : "".concat((n / 1024).toFixed(1), " kB");
978
- }
979
- function humanMs(ms) {
980
- return ms < 1 ? "".concat(ms * 1000 | 0, " \xB5s") : ms < 1000 ? "".concat(ms.toFixed(1), " ms") : "".concat((ms / 1000).toFixed(2), " s");
981
- }
982
636
 
983
- // Green under 10 ms, yellow under 50 ms, red beyond — a quick "is it fast?" cue.
984
- function timeColor(ms) {
985
- return ms < 10 ? ANSI.green : ms < 50 ? ANSI.yellow : ANSI.red;
986
- }
987
- function formatBuildLog(label, stats) {
988
- var _options$color;
989
- var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
990
- var color = (_options$color = options.color) !== null && _options$color !== void 0 ? _options$color : true;
991
- var head = paint(ANSI.cyan + ANSI.bold, '◆ fluixi', color);
992
- var name = paint(ANSI.bold, label, color);
993
- var time = paint(timeColor(stats.ms), humanMs(stats.ms), color);
994
- var parts = ["".concat(stats.utilities, " ").concat(stats.utilities === 1 ? 'utility' : 'utilities'), "".concat(stats.scanned, " scanned"), humanBytes(stats.bytes)];
995
- if (stats.sources) parts.push("".concat(stats.sources, " ").concat(stats.sources === 1 ? 'source' : 'sources'));
996
- var detail = paint(ANSI.dim, parts.join(' · '), color);
997
- return "".concat(head, " ").concat(name, " ").concat(time, "\n ").concat(detail);
998
- }
637
+ // ── At-rule ───────────────────────────────────────────────────────────────
999
638
 
1000
- // The resolved token table. Every entry is a CSS custom property (`--color-red-500`,
1001
- // `--spacing`, `--breakpoint-md`, …); utilities read them by namespace and emit
1002
- // `var()` references, so the tokens stay live and themeable at runtime.
639
+ /** `parent` is the block the at-rule sits in: inside a style rule, a conditional group's
640
+ * body follows the rule's grammar (CSS Nesting), declarations and nested rules. */
641
+ }, {
642
+ key: "parseAtRule",
643
+ value: function parseAtRule() {
644
+ var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'stylesheet';
645
+ if (this.peek() !== CC_AT) return null;
646
+ var locStart = this.locPos();
647
+ this.advance(); // '@'
1003
648
 
1004
- var Theme = /*#__PURE__*/function () {
1005
- function Theme() {
1006
- _classCallCheck(this, Theme);
1007
- _defineProperty(this, "values", new Map());
1008
- }
1009
- return _createClass(Theme, [{
1010
- key: "add",
1011
- value: function add(name, value) {
1012
- this.values.set(name, value);
1013
- return this;
1014
- }
1015
- }, {
1016
- key: "addAll",
1017
- value: function addAll(entries) {
1018
- for (var name in entries) this.add(name, entries[name]);
1019
- return this;
1020
- }
1021
- }, {
1022
- key: "get",
1023
- value: function get(name) {
1024
- return this.values.get(name);
1025
- }
1026
- }, {
1027
- key: "has",
1028
- value: function has(name) {
1029
- return this.values.has(name);
1030
- }
649
+ var name = this.readIdent();
650
+ if (!name) {
651
+ this.recoverPast(CC_SEMI, CC_RBRACE);
652
+ return null;
653
+ }
654
+ this.skipWS();
655
+ var preludeText = this.readPrelude();
656
+ this.skipWS();
657
+ var baseName = name.replace(/^-(webkit|moz|ms|o)-/, '');
658
+ var ar = {
659
+ type: 'atrule',
660
+ name: name,
661
+ preludeText: preludeText,
662
+ prelude: this.options.parseAtrulePrelude ? this.tokenizeValue(preludeText) : []
663
+ };
664
+ if (this.options.includeVendorPrefixes) {
665
+ var vp = name.match(/^-(webkit|moz|ms|o)-/);
666
+ if (vp) ar.vendorPrefix = vp[0];
667
+ }
668
+ if (this.peek() === CC_LBRACE) {
669
+ var mode = this.modeForAtRule(baseName, parent);
670
+ var blockStart = this.locPos();
671
+ var children = this.parseBlockChildren(mode);
672
+ var blockEnd = this.locPos();
673
+ ar.block = _objectSpread2({
674
+ type: 'block',
675
+ children: children
676
+ }, this.options.includeSourceMaps ? {
677
+ loc: {
678
+ start: blockStart,
679
+ end: blockEnd
680
+ }
681
+ } : {});
1031
682
 
1032
- // A `var()` reference to `--<namespace>-<key>` when that token exists.
683
+ // Populate keyframes shortcut
684
+ if (baseName === 'keyframes') {
685
+ ar.keyframes = children.filter(function (n) {
686
+ return n.type === 'keyframe';
687
+ });
688
+ }
689
+ } else if (this.peek() === CC_SEMI) {
690
+ this.advance();
691
+ }
692
+ this.stats.totalAtRules++;
693
+ if (this.options.includeSourceMaps) {
694
+ ar.loc = {
695
+ start: locStart,
696
+ end: this.locPos(),
697
+ source: this.input
698
+ };
699
+ }
700
+ if (this.options.onAtRule) {
701
+ var result = this.options.onAtRule(ar);
702
+ if (result === null) return null;
703
+ if (result) return result;
704
+ }
705
+ return ar;
706
+ }
1033
707
  }, {
1034
- key: "resolve",
1035
- value: function resolve(namespace, key) {
1036
- var name = "--".concat(namespace, "-").concat(key);
1037
- return this.values.has(name) ? "var(".concat(name, ")") : null;
708
+ key: "modeForAtRule",
709
+ value: function modeForAtRule(baseName) {
710
+ var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'stylesheet';
711
+ // AWC encodes comments as @comment-XXXXXXXX { --rule-...: "..."; }
712
+ // which contain only declarations — must NOT use mixed/rule mode or
713
+ // readUntilLBrace() will consume past the closing } and corrupt state.
714
+ if (baseName.startsWith('comment')) return 'declarations';
715
+ switch (baseName) {
716
+ case 'keyframes':
717
+ return 'keyframes';
718
+ case 'font-face':
719
+ case 'page':
720
+ case 'counter-style':
721
+ case 'viewport':
722
+ case 'theme':
723
+ return 'declarations';
724
+ // `@utility` bodies mix flat declarations with nested rules
725
+ // (`&:hover`, `&::-webkit-scrollbar`); `rule` mode does the
726
+ // declaration-vs-nesting lookahead. (`mixed` would read every line
727
+ // as a selector and corrupt the block.)
728
+ case 'utility':
729
+ return 'rule';
730
+ // Nested in a style rule, `@media { color: red }` holds declarations: read in
731
+ // `mixed` mode, `color: red` became a selector that ran past the closing brace
732
+ // and swallowed every rule after it.
733
+ case 'media':
734
+ case 'supports':
735
+ case 'container':
736
+ case 'layer':
737
+ case 'document':
738
+ default:
739
+ return parent === 'rule' ? 'rule' : 'mixed';
740
+ }
1038
741
  }
1039
742
 
1040
- // Bare keys registered under a namespace, e.g. every color name.
743
+ // ── Regular rule ──────────────────────────────────────────────────────────
1041
744
  }, {
1042
- key: "keysIn",
1043
- value: function keysIn(namespace) {
1044
- var prefix = "--".concat(namespace, "-");
1045
- var out = [];
1046
- var _iterator = _createForOfIteratorHelper(this.values.keys()),
745
+ key: "parseRule",
746
+ value: function parseRule() {
747
+ var locStart = this.locPos();
748
+ var rawSelector = this.readUntilLBrace().trim();
749
+ if (!rawSelector || this.peek() !== CC_LBRACE) {
750
+ // Malformed — skip to closing brace
751
+ if (this.peek() === CC_LBRACE) {
752
+ this.skipBalancedBraces();
753
+ }
754
+ return null;
755
+ }
756
+ var mode = this.options.enableNesting ? 'rule' : 'declarations';
757
+ var children = this.parseBlockChildren(mode);
758
+ var declarations = [];
759
+ var nested = [];
760
+ var _iterator = _createForOfIteratorHelper(children),
1047
761
  _step;
1048
762
  try {
1049
763
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
1050
- var name = _step.value;
1051
- if (name.startsWith(prefix)) out.push(name.slice(prefix.length));
764
+ var child = _step.value;
765
+ var t = child.type;
766
+ if (t === 'declaration') declarations.push(child);else if (t === 'rule') nested.push(child);else if (t === 'atrule') nested.push(child);
1052
767
  }
1053
768
  } catch (err) {
1054
769
  _iterator.e(err);
1055
770
  } finally {
1056
771
  _iterator.f();
1057
772
  }
1058
- return out;
773
+ var selectors = this.parseSelectorList(rawSelector);
774
+ this.stats.totalRules++;
775
+ this.stats.totalSelectors += selectors.length;
776
+ var rule = {
777
+ type: 'rule',
778
+ rawSelector: rawSelector,
779
+ selectors: selectors,
780
+ declarations: declarations
781
+ };
782
+ if (nested.length > 0) rule.children = nested;
783
+ if (this.options.includeSpecificity) {
784
+ rule.specificity = this.calcSpecificity(rawSelector);
785
+ }
786
+ if (this.options.includeSourceMaps) {
787
+ rule.loc = {
788
+ start: locStart,
789
+ end: this.locPos(),
790
+ source: this.input
791
+ };
792
+ }
793
+ if (this.options.onRule) {
794
+ var result = this.options.onRule(rule);
795
+ if (result === null) return null;
796
+ if (result) return result;
797
+ }
798
+ return rule;
1059
799
  }
800
+
801
+ // ── Keyframe stop (from / to / <percentage>) ──────────────────────────────
1060
802
  }, {
1061
- key: "entries",
1062
- value: function entries() {
1063
- return _toConsumableArray(this.values.entries());
803
+ key: "parseKeyframeStop",
804
+ value: function parseKeyframeStop() {
805
+ var locStart = this.locPos();
806
+ var selector = this.readUntilLBrace().trim();
807
+ if (!selector || this.peek() !== CC_LBRACE) return null;
808
+ var children = this.parseBlockChildren('declarations');
809
+ var declarations = children.filter(function (n) {
810
+ return n.type === 'declaration';
811
+ });
812
+ var kf = _objectSpread2({
813
+ type: 'keyframe',
814
+ selector: selector,
815
+ declarations: declarations
816
+ }, this.options.includeSourceMaps ? {
817
+ loc: {
818
+ start: locStart,
819
+ end: this.locPos()
820
+ }
821
+ } : {});
822
+ if (this.options.onKeyframe) {
823
+ var result = this.options.onKeyframe(kf);
824
+ if (result === null) return null;
825
+ if (result) return result;
826
+ }
827
+ return kf;
1064
828
  }
1065
- }]);
1066
- }();
1067
-
1068
- // ─── Charcode constants (avoids string allocation on hot paths) ───────────────
1069
- var CC_TAB = 9,
1070
- CC_LF = 10,
1071
- CC_CR = 13,
1072
- CC_FF = 12,
1073
- CC_SPACE = 32;
1074
- var CC_DQUOTE = 34,
1075
- CC_HASH = 35,
1076
- CC_AMP = 38,
1077
- CC_SQUOTE = 39;
1078
- var CC_LPAREN = 40,
1079
- CC_RPAREN = 41,
1080
- CC_STAR = 42,
1081
- CC_PLUS = 43;
1082
- var CC_COMMA = 44,
1083
- CC_MINUS = 45,
1084
- CC_DOT = 46,
1085
- CC_SLASH = 47;
1086
- var CC_COLON = 58,
1087
- CC_SEMI = 59,
1088
- CC_GT = 62;
1089
- var CC_AT = 64,
1090
- CC_LBRACK = 91,
1091
- CC_BSLASH = 92,
1092
- CC_RBRACK = 93;
1093
- var CC_UNDER = 95,
1094
- CC_LBRACE = 123,
1095
- CC_RBRACE = 125,
1096
- CC_TILDE = 126;
1097
829
 
1098
- // ─── Character predicates (charcode-based, no regex) ─────────────────────────
830
+ // ── Block (consumes { … }) ────────────────────────────────────────────────
831
+ }, {
832
+ key: "parseBlockChildren",
833
+ value: function parseBlockChildren(mode) {
834
+ if (this.peek() !== CC_LBRACE) return [];
835
+ this.advance(); // '{'
1099
836
 
1100
- function isWS(c) {
1101
- return c === CC_SPACE || c === CC_TAB || c === CC_LF || c === CC_CR || c === CC_FF;
1102
- }
1103
- function isDigit(c) {
1104
- return c >= 48 && c <= 57;
1105
- }
1106
- function isAlpha(c) {
1107
- return c >= 65 && c <= 90 || c >= 97 && c <= 122;
1108
- }
1109
- function isHex(c) {
1110
- return isDigit(c) || c >= 65 && c <= 70 || c >= 97 && c <= 102;
1111
- }
1112
- /**
1113
- * CSS ident-start: letter | underscore | non-ASCII | hyphen.
1114
- * A leading hyphen is valid (vendor prefixes, custom properties).
1115
- */
1116
- function isNameStart(c) {
1117
- return isAlpha(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
1118
- }
1119
- /** CSS ident-char: ident-start | digit */
1120
- function isNameChar(c) {
1121
- return isAlpha(c) || isDigit(c) || c === CC_UNDER || c === CC_MINUS || c > 127;
1122
- }
1123
-
1124
- // ─── Block context ────────────────────────────────────────────────────────────
1125
-
1126
- /**
1127
- * Determines what may legally appear inside a block:
1128
- * stylesheet – top-level: rules + at-rules
1129
- * mixed – @media/@supports/@container/@layer: rules + at-rules
1130
- * rule – inside a style rule: declarations + optional CSS nesting
1131
- * keyframes – inside @keyframes: keyframe stops (from/to/%)
1132
- * declarations– @font-face/@page/etc.: declarations only
1133
- */
1134
-
1135
- // ─── CssParser ────────────────────────────────────────────────────────────────
1136
-
1137
- var CssParser = /*#__PURE__*/function () {
1138
- function CssParser() {
1139
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1140
- _classCallCheck(this, CssParser);
1141
- _defineProperty(this, "input", '');
1142
- _defineProperty(this, "pos", 0);
1143
- _defineProperty(this, "length", 0);
1144
- _defineProperty(this, "line", 1);
1145
- _defineProperty(this, "col", 1);
1146
- _defineProperty(this, "errors", []);
1147
- _defineProperty(this, "warnings", []);
1148
- _defineProperty(this, "stats", CssParser.emptyStats());
1149
- this.options = _objectSpread2({
1150
- parseAtrulePrelude: true,
1151
- parseValue: true,
1152
- parseCustomProperty: true,
1153
- parseRulePrelude: true,
1154
- parseSelector: true,
1155
- includeComments: true,
1156
- includeSourceMaps: true,
1157
- includeSpecificity: true,
1158
- includeVendorPrefixes: true,
1159
- onError: function onError() {/* noop */},
1160
- onWarning: function onWarning() {/* noop */},
1161
- maxDepth: 100,
1162
- maxNodes: 100000,
1163
- enableNesting: true,
1164
- enableCustomProperties: true,
1165
- enableLogicalProperties: true,
1166
- enableContainerQueries: true,
1167
- enableLayerQueries: true,
1168
- enableSupportsQueries: true,
1169
- // middleware — undefined by default (fast path skips them)
1170
- onRule: undefined,
1171
- onAtRule: undefined,
1172
- onDeclaration: undefined,
1173
- onComment: undefined,
1174
- onKeyframe: undefined
1175
- }, options);
1176
- }
1177
-
1178
- // ── Public API ────────────────────────────────────────────────────────────
1179
- return _createClass(CssParser, [{
1180
- key: "parse",
1181
- value: function parse(css) {
1182
- var t0 = typeof performance !== 'undefined' ? performance.now() : Date.now();
1183
- this.reset(css);
1184
- var sheet = this.parseStylesheet();
1185
- this.stats.parseTime = (typeof performance !== 'undefined' ? performance.now() : Date.now()) - t0;
1186
- return sheet;
1187
- }
1188
- }, {
1189
- key: "getErrors",
1190
- value: function getErrors() {
1191
- return _toConsumableArray(this.errors);
1192
- }
1193
- }, {
1194
- key: "getWarnings",
1195
- value: function getWarnings() {
1196
- return _toConsumableArray(this.warnings);
1197
- }
1198
- }, {
1199
- key: "getStats",
1200
- value: function getStats() {
1201
- return _objectSpread2({}, this.stats);
1202
- }
1203
- }, {
1204
- key: "toLegacyFormat",
1205
- value: function toLegacyFormat(stylesheet) {
1206
- var _this = this;
1207
- return stylesheet.children.map(function (c) {
1208
- return _this.toLegacyNode(c);
1209
- }).filter(Boolean);
1210
- }
1211
-
1212
- // ── Reset ─────────────────────────────────────────────────────────────────
1213
- }, {
1214
- key: "reset",
1215
- value: function reset(css) {
1216
- this.input = css;
1217
- this.pos = 0;
1218
- this.length = css.length;
1219
- this.line = 1;
1220
- this.col = 1;
1221
- this.errors = [];
1222
- this.warnings = [];
1223
- this.stats = CssParser.emptyStats();
1224
- }
1225
- }, {
1226
- key: "parseStylesheet",
1227
- value:
1228
- // ── Stylesheet ────────────────────────────────────────────────────────────
1229
-
1230
- function parseStylesheet() {
1231
- var locStart = this.locPos();
1232
- var ss = {
1233
- type: 'stylesheet',
1234
- source: this.input,
1235
- children: [],
1236
- charset: undefined,
1237
- imports: [],
1238
- namespaces: [],
1239
- mediaQueries: [],
1240
- keyframes: [],
1241
- fontFaces: [],
1242
- layers: [],
1243
- containers: [],
1244
- supports: [],
1245
- documents: [],
1246
- pages: [],
1247
- counterStyles: [],
1248
- fontFeatureValues: [],
1249
- viewports: [],
1250
- charsets: []
1251
- };
837
+ var children = [];
1252
838
  while (this.pos < this.length) {
1253
839
  this.skipWS();
1254
- if (this.pos >= this.length) break;
1255
- var node = this.parseTopNode();
840
+ if (this.pos >= this.length || this.peek() === CC_RBRACE) break;
841
+ var prevPos = this.pos;
842
+ var node = this.parseBlockNode(mode);
843
+ // Guard against infinite loop: if nothing was consumed, force-advance
844
+ if (this.pos === prevPos) {
845
+ this.advance();
846
+ continue;
847
+ }
1256
848
  if (node) {
1257
- ss.children.push(node);
1258
- this.categorize(ss, node);
849
+ children.push(node);
1259
850
  this.stats.totalNodes++;
1260
851
  }
1261
852
  }
1262
- if (this.options.includeSourceMaps) {
1263
- ss.loc = {
1264
- start: locStart,
1265
- end: this.locPos(),
1266
- source: this.input
1267
- };
1268
- }
1269
- return ss;
853
+ if (this.pos < this.length && this.peek() === CC_RBRACE) this.advance(); // '}'
854
+ return children;
1270
855
  }
1271
856
 
1272
- // ── Top-level node dispatch ───────────────────────────────────────────────
857
+ // ── Declaration ───────────────────────────────────────────────────────────
1273
858
  }, {
1274
- key: "parseTopNode",
1275
- value: function parseTopNode() {
1276
- var c = this.peek();
1277
- if (c === CC_SLASH && this.peek(1) === CC_STAR) {
1278
- var comment = this.parseComment();
1279
- return this.options.includeComments ? comment : null;
859
+ key: "parseDeclaration",
860
+ value: function parseDeclaration() {
861
+ var locStart = this.locPos();
862
+
863
+ // Property name (supports --custom-props and -vendor-prefixed)
864
+ var property = this.readIdent();
865
+ if (!property) {
866
+ this.recoverTo(CC_SEMI, CC_RBRACE);
867
+ return null;
1280
868
  }
1281
- if (c === CC_AT) return this.parseAtRule();
1282
- // Skip stray closing braces that can appear in malformed CSS
1283
- if (c === CC_RBRACE) {
1284
- this.advance();
869
+ this.skipWS();
870
+ if (this.peek() !== CC_COLON) {
871
+ this.recoverTo(CC_SEMI, CC_RBRACE);
1285
872
  return null;
1286
873
  }
1287
- return this.parseRule();
1288
- }
874
+ this.advance(); // ':'
875
+ this.skipWS();
876
+ var rawFull = this.readRawValue();
1289
877
 
1290
- // ── Block-level node dispatch ─────────────────────────────────────────────
1291
- }, {
1292
- key: "parseBlockNode",
1293
- value: function parseBlockNode(mode) {
878
+ // Strip !important
879
+ var rawValue = rawFull;
880
+ var important = false;
881
+ var impMatch = rawFull.match(/\s*!important\s*$/i);
882
+ if (impMatch) {
883
+ important = true;
884
+ rawValue = rawFull.slice(0, rawFull.length - impMatch[0].length).trimEnd();
885
+ }
1294
886
  this.skipWS();
1295
- if (this.pos >= this.length || this.peek() === CC_RBRACE) return null;
1296
- var c = this.peek();
1297
- if (c === CC_SLASH && this.peek(1) === CC_STAR) {
1298
- var comment = this.parseComment();
1299
- return this.options.includeComments ? comment : null;
887
+ if (this.pos < this.length && this.peek() === CC_SEMI) this.advance();
888
+ this.stats.totalDeclarations++;
889
+ var decl = {
890
+ type: 'declaration',
891
+ property: property,
892
+ rawValue: rawValue,
893
+ value: this.options.parseValue ? this.tokenizeValue(rawValue) : [],
894
+ important: important
895
+ };
896
+ if (this.options.enableCustomProperties && property.startsWith('--')) {
897
+ decl.customProperty = true;
1300
898
  }
1301
- if (c === CC_AT) return this.parseAtRule();
1302
- switch (mode) {
1303
- case 'keyframes':
1304
- return this.parseKeyframeStop();
1305
- case 'declarations':
1306
- return this.parseDeclaration();
1307
- case 'mixed':
1308
- case 'stylesheet':
1309
- if (c === CC_RBRACE) return null;
1310
- return this.parseRule();
1311
- case 'rule':
1312
- default:
1313
- // Unambiguous nesting-selector starters
1314
- if (this.isNestingStart(c)) return this.parseRule();
1315
- // Lookahead: first unescaped { at depth 0 → rule, ; or } → declaration
1316
- if (this.lookaheadIsRule()) return this.parseRule();
1317
- // console.log('parse block', c, mode);
1318
- return this.parseDeclaration();
899
+ if (this.options.includeVendorPrefixes) {
900
+ var vp = property.match(/^-(webkit|moz|ms|o)-/);
901
+ if (vp) decl.vendorPrefix = vp[0];
902
+ }
903
+ if (this.options.includeSourceMaps) {
904
+ decl.loc = {
905
+ start: locStart,
906
+ end: this.locPos(),
907
+ source: this.input
908
+ };
909
+ }
910
+ if (this.options.onDeclaration) {
911
+ var result = this.options.onDeclaration(decl);
912
+ if (result === null) return null;
913
+ if (result) return result;
1319
914
  }
915
+ return decl;
1320
916
  }
1321
917
 
1322
- // ── At-rule ───────────────────────────────────────────────────────────────
918
+ // ── Comment ───────────────────────────────────────────────────────────────
1323
919
  }, {
1324
- key: "parseAtRule",
1325
- value: function parseAtRule() {
1326
- if (this.peek() !== CC_AT) return null;
1327
- var locStart = this.locPos();
1328
- this.advance(); // '@'
1329
-
1330
- var name = this.readIdent();
1331
- if (!name) {
1332
- this.recoverPast(CC_SEMI, CC_RBRACE);
1333
- return null;
1334
- }
1335
- this.skipWS();
1336
- var preludeText = this.readPrelude();
1337
- this.skipWS();
1338
- var baseName = name.replace(/^-(webkit|moz|ms|o)-/, '');
1339
- var ar = {
1340
- type: 'atrule',
1341
- name: name,
1342
- preludeText: preludeText,
1343
- prelude: this.options.parseAtrulePrelude ? this.tokenizeValue(preludeText) : []
1344
- };
1345
- if (this.options.includeVendorPrefixes) {
1346
- var vp = name.match(/^-(webkit|moz|ms|o)-/);
1347
- if (vp) ar.vendorPrefix = vp[0];
1348
- }
1349
- if (this.peek() === CC_LBRACE) {
1350
- var mode = this.modeForAtRule(baseName);
1351
- var blockStart = this.locPos();
1352
- var children = this.parseBlockChildren(mode);
1353
- var blockEnd = this.locPos();
1354
- ar.block = _objectSpread2({
1355
- type: 'block',
1356
- children: children
1357
- }, this.options.includeSourceMaps ? {
1358
- loc: {
1359
- start: blockStart,
1360
- end: blockEnd
920
+ key: "parseComment",
921
+ value: function parseComment() {
922
+ var locStart = this.locPos();
923
+ this.advance(); // '/'
924
+ this.advance(); // '*'
925
+ var start = this.pos;
926
+ while (this.pos < this.length - 1) {
927
+ if (this.peek() === CC_STAR && this.peek(1) === CC_SLASH) {
928
+ var _value = this.input.slice(start, this.pos);
929
+ this.advance();
930
+ this.advance(); // '*/'
931
+ this.stats.totalComments++;
932
+ var _c = _objectSpread2({
933
+ type: 'comment',
934
+ value: _value,
935
+ style: _value.includes('\n') ? 'multi-line' : 'single-line'
936
+ }, this.options.includeSourceMaps ? {
937
+ loc: {
938
+ start: locStart,
939
+ end: this.locPos()
940
+ }
941
+ } : {});
942
+ if (this.options.onComment) {
943
+ var result = this.options.onComment(_c);
944
+ if (result === null) return null;
945
+ if (result) return result;
1361
946
  }
1362
- } : {});
1363
-
1364
- // Populate keyframes shortcut
1365
- if (baseName === 'keyframes') {
1366
- ar.keyframes = children.filter(function (n) {
1367
- return n.type === 'keyframe';
1368
- });
947
+ return _c;
1369
948
  }
1370
- } else if (this.peek() === CC_SEMI) {
1371
949
  this.advance();
1372
950
  }
1373
- this.stats.totalAtRules++;
1374
- if (this.options.includeSourceMaps) {
1375
- ar.loc = {
1376
- start: locStart,
1377
- end: this.locPos(),
1378
- source: this.input
1379
- };
1380
- }
1381
- if (this.options.onAtRule) {
1382
- var result = this.options.onAtRule(ar);
1383
- if (result === null) return null;
1384
- if (result) return result;
951
+
952
+ // Unterminated comment
953
+ var value = this.input.slice(start);
954
+ this.pos = this.length;
955
+ this.stats.totalComments++;
956
+ var c = {
957
+ type: 'comment',
958
+ value: value,
959
+ style: 'multi-line'
960
+ };
961
+ if (this.options.onComment) {
962
+ var _result = this.options.onComment(c);
963
+ if (_result === null) return null;
964
+ if (_result) return _result;
1385
965
  }
1386
- return ar;
966
+ return c;
1387
967
  }
968
+
969
+ // ── Selectors ─────────────────────────────────────────────────────────────
970
+
971
+ /**
972
+ * Splits a raw selector string on commas (respecting parentheses depth)
973
+ * and returns one CssSelector per part.
974
+ */
1388
975
  }, {
1389
- key: "modeForAtRule",
1390
- value: function modeForAtRule(baseName) {
1391
- // AWC encodes comments as @comment-XXXXXXXX { --rule-...: "..."; }
1392
- // which contain only declarations — must NOT use mixed/rule mode or
1393
- // readUntilLBrace() will consume past the closing } and corrupt state.
1394
- if (baseName.startsWith('comment')) return 'declarations';
1395
- switch (baseName) {
1396
- case 'keyframes':
1397
- return 'keyframes';
1398
- case 'font-face':
1399
- case 'page':
1400
- case 'counter-style':
1401
- case 'viewport':
1402
- case 'theme':
1403
- return 'declarations';
1404
- // `@utility` bodies mix flat declarations with nested rules
1405
- // (`&:hover`, `&::-webkit-scrollbar`); `rule` mode does the
1406
- // declaration-vs-nesting lookahead. (`mixed` would read every line
1407
- // as a selector and corrupt the block.)
1408
- case 'utility':
1409
- return 'rule';
1410
- case 'media':
1411
- case 'supports':
1412
- case 'container':
1413
- case 'layer':
1414
- case 'document':
1415
- default:
1416
- return 'mixed';
976
+ key: "parseSelectorList",
977
+ value: function parseSelectorList(raw) {
978
+ var parts = [];
979
+ var depth = 0,
980
+ start = 0;
981
+ for (var i = 0; i < raw.length; i++) {
982
+ var c = raw.charCodeAt(i);
983
+ if (c === CC_LPAREN || c === CC_LBRACK) depth++;else if (c === CC_RPAREN || c === CC_RBRACK) depth--;else if (c === CC_COMMA && depth === 0) {
984
+ parts.push(raw.slice(start, i).trim());
985
+ start = i + 1;
986
+ }
1417
987
  }
988
+ parts.push(raw.slice(start).trim());
989
+ return parts.filter(function (p) {
990
+ return p.length > 0;
991
+ }).map(function (p) {
992
+ return {
993
+ type: 'selector',
994
+ value: p
995
+ };
996
+ });
1418
997
  }
1419
998
 
1420
- // ── Regular rule ──────────────────────────────────────────────────────────
999
+ /**
1000
+ * Simple specificity scorer — counts IDs, classes/attributes/pseudos, elements.
1001
+ */
1421
1002
  }, {
1422
- key: "parseRule",
1423
- value: function parseRule() {
1424
- var locStart = this.locPos();
1425
- var rawSelector = this.readUntilLBrace().trim();
1426
- if (!rawSelector || this.peek() !== CC_LBRACE) {
1427
- // Malformed — skip to closing brace
1428
- if (this.peek() === CC_LBRACE) {
1429
- this.skipBalancedBraces();
1430
- }
1431
- return null;
1432
- }
1433
- var mode = this.options.enableNesting ? 'rule' : 'declarations';
1434
- var children = this.parseBlockChildren(mode);
1435
- var declarations = [];
1436
- var nested = [];
1437
- var _iterator = _createForOfIteratorHelper(children),
1438
- _step;
1439
- try {
1440
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1441
- var child = _step.value;
1442
- var t = child.type;
1443
- if (t === 'declaration') declarations.push(child);else if (t === 'rule') nested.push(child);else if (t === 'atrule') nested.push(child);
1003
+ key: "calcSpecificity",
1004
+ value: function calcSpecificity(sel) {
1005
+ var ids = 0,
1006
+ classes = 0,
1007
+ elements = 0;
1008
+ var i = 0;
1009
+ while (i < sel.length) {
1010
+ var c = sel.charCodeAt(i);
1011
+ if (c === CC_HASH) {
1012
+ ids++;
1013
+ i++;
1014
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1015
+ } else if (c === CC_DOT) {
1016
+ classes++;
1017
+ i++;
1018
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1019
+ } else if (c === CC_LBRACK) {
1020
+ classes++;
1021
+ while (i < sel.length && sel.charCodeAt(i) !== CC_RBRACK) i++;
1022
+ i++;
1023
+ } else if (c === CC_COLON) {
1024
+ if (sel.charCodeAt(i + 1) === CC_COLON) {
1025
+ elements++;
1026
+ i += 2;
1027
+ } else {
1028
+ // :not(), :is(), :has() — don't double-count the wrapper
1029
+ classes++;
1030
+ i++;
1031
+ }
1032
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1033
+ // skip argument parens
1034
+ if (i < sel.length && sel.charCodeAt(i) === CC_LPAREN) {
1035
+ var d = 1;
1036
+ i++;
1037
+ while (i < sel.length && d > 0) {
1038
+ if (sel.charCodeAt(i) === CC_LPAREN) d++;else if (sel.charCodeAt(i) === CC_RPAREN) d--;
1039
+ i++;
1040
+ }
1041
+ }
1042
+ } else if (isAlpha(c) || c === CC_UNDER) {
1043
+ elements++;
1044
+ while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1045
+ } else {
1046
+ i++;
1444
1047
  }
1445
- } catch (err) {
1446
- _iterator.e(err);
1447
- } finally {
1448
- _iterator.f();
1449
1048
  }
1450
- var selectors = this.parseSelectorList(rawSelector);
1451
- this.stats.totalRules++;
1452
- this.stats.totalSelectors += selectors.length;
1453
- var rule = {
1454
- type: 'rule',
1455
- rawSelector: rawSelector,
1456
- selectors: selectors,
1457
- declarations: declarations
1458
- };
1459
- if (nested.length > 0) rule.children = nested;
1460
- if (this.options.includeSpecificity) {
1461
- rule.specificity = this.calcSpecificity(rawSelector);
1462
- }
1463
- if (this.options.includeSourceMaps) {
1464
- rule.loc = {
1465
- start: locStart,
1466
- end: this.locPos(),
1467
- source: this.input
1468
- };
1469
- }
1470
- if (this.options.onRule) {
1471
- var result = this.options.onRule(rule);
1472
- if (result === null) return null;
1473
- if (result) return result;
1474
- }
1475
- return rule;
1476
- }
1477
-
1478
- // ── Keyframe stop (from / to / <percentage>) ──────────────────────────────
1479
- }, {
1480
- key: "parseKeyframeStop",
1481
- value: function parseKeyframeStop() {
1482
- var locStart = this.locPos();
1483
- var selector = this.readUntilLBrace().trim();
1484
- if (!selector || this.peek() !== CC_LBRACE) return null;
1485
- var children = this.parseBlockChildren('declarations');
1486
- var declarations = children.filter(function (n) {
1487
- return n.type === 'declaration';
1488
- });
1489
- var kf = _objectSpread2({
1490
- type: 'keyframe',
1491
- selector: selector,
1492
- declarations: declarations
1493
- }, this.options.includeSourceMaps ? {
1494
- loc: {
1495
- start: locStart,
1496
- end: this.locPos()
1497
- }
1498
- } : {});
1499
- if (this.options.onKeyframe) {
1500
- var result = this.options.onKeyframe(kf);
1501
- if (result === null) return null;
1502
- if (result) return result;
1503
- }
1504
- return kf;
1505
- }
1506
-
1507
- // ── Block (consumes { … }) ────────────────────────────────────────────────
1508
- }, {
1509
- key: "parseBlockChildren",
1510
- value: function parseBlockChildren(mode) {
1511
- if (this.peek() !== CC_LBRACE) return [];
1512
- this.advance(); // '{'
1513
-
1514
- var children = [];
1515
- while (this.pos < this.length) {
1516
- this.skipWS();
1517
- if (this.pos >= this.length || this.peek() === CC_RBRACE) break;
1518
- var prevPos = this.pos;
1519
- var node = this.parseBlockNode(mode);
1520
- // Guard against infinite loop: if nothing was consumed, force-advance
1521
- if (this.pos === prevPos) {
1522
- this.advance();
1523
- continue;
1524
- }
1525
- if (node) {
1526
- children.push(node);
1527
- this.stats.totalNodes++;
1528
- }
1529
- }
1530
- if (this.pos < this.length && this.peek() === CC_RBRACE) this.advance(); // '}'
1531
- return children;
1532
- }
1533
-
1534
- // ── Declaration ───────────────────────────────────────────────────────────
1535
- }, {
1536
- key: "parseDeclaration",
1537
- value: function parseDeclaration() {
1538
- var locStart = this.locPos();
1539
-
1540
- // Property name (supports --custom-props and -vendor-prefixed)
1541
- var property = this.readIdent();
1542
- if (!property) {
1543
- this.recoverTo(CC_SEMI, CC_RBRACE);
1544
- return null;
1545
- }
1546
- this.skipWS();
1547
- if (this.peek() !== CC_COLON) {
1548
- this.recoverTo(CC_SEMI, CC_RBRACE);
1549
- return null;
1550
- }
1551
- this.advance(); // ':'
1552
- this.skipWS();
1553
- var rawFull = this.readRawValue();
1554
-
1555
- // Strip !important
1556
- var rawValue = rawFull;
1557
- var important = false;
1558
- var impMatch = rawFull.match(/\s*!important\s*$/i);
1559
- if (impMatch) {
1560
- important = true;
1561
- rawValue = rawFull.slice(0, rawFull.length - impMatch[0].length).trimEnd();
1562
- }
1563
- this.skipWS();
1564
- if (this.pos < this.length && this.peek() === CC_SEMI) this.advance();
1565
- this.stats.totalDeclarations++;
1566
- var decl = {
1567
- type: 'declaration',
1568
- property: property,
1569
- rawValue: rawValue,
1570
- value: this.options.parseValue ? this.tokenizeValue(rawValue) : [],
1571
- important: important
1572
- };
1573
- if (this.options.enableCustomProperties && property.startsWith('--')) {
1574
- decl.customProperty = true;
1575
- }
1576
- if (this.options.includeVendorPrefixes) {
1577
- var vp = property.match(/^-(webkit|moz|ms|o)-/);
1578
- if (vp) decl.vendorPrefix = vp[0];
1579
- }
1580
- if (this.options.includeSourceMaps) {
1581
- decl.loc = {
1582
- start: locStart,
1583
- end: this.locPos(),
1584
- source: this.input
1585
- };
1586
- }
1587
- if (this.options.onDeclaration) {
1588
- var result = this.options.onDeclaration(decl);
1589
- if (result === null) return null;
1590
- if (result) return result;
1591
- }
1592
- return decl;
1593
- }
1594
-
1595
- // ── Comment ───────────────────────────────────────────────────────────────
1596
- }, {
1597
- key: "parseComment",
1598
- value: function parseComment() {
1599
- var locStart = this.locPos();
1600
- this.advance(); // '/'
1601
- this.advance(); // '*'
1602
- var start = this.pos;
1603
- while (this.pos < this.length - 1) {
1604
- if (this.peek() === CC_STAR && this.peek(1) === CC_SLASH) {
1605
- var _value = this.input.slice(start, this.pos);
1606
- this.advance();
1607
- this.advance(); // '*/'
1608
- this.stats.totalComments++;
1609
- var _c = _objectSpread2({
1610
- type: 'comment',
1611
- value: _value,
1612
- style: _value.includes('\n') ? 'multi-line' : 'single-line'
1613
- }, this.options.includeSourceMaps ? {
1614
- loc: {
1615
- start: locStart,
1616
- end: this.locPos()
1617
- }
1618
- } : {});
1619
- if (this.options.onComment) {
1620
- var result = this.options.onComment(_c);
1621
- if (result === null) return null;
1622
- if (result) return result;
1623
- }
1624
- return _c;
1625
- }
1626
- this.advance();
1627
- }
1628
-
1629
- // Unterminated comment
1630
- var value = this.input.slice(start);
1631
- this.pos = this.length;
1632
- this.stats.totalComments++;
1633
- var c = {
1634
- type: 'comment',
1635
- value: value,
1636
- style: 'multi-line'
1637
- };
1638
- if (this.options.onComment) {
1639
- var _result = this.options.onComment(c);
1640
- if (_result === null) return null;
1641
- if (_result) return _result;
1642
- }
1643
- return c;
1644
- }
1645
-
1646
- // ── Selectors ─────────────────────────────────────────────────────────────
1647
-
1648
- /**
1649
- * Splits a raw selector string on commas (respecting parentheses depth)
1650
- * and returns one CssSelector per part.
1651
- */
1652
- }, {
1653
- key: "parseSelectorList",
1654
- value: function parseSelectorList(raw) {
1655
- var parts = [];
1656
- var depth = 0,
1657
- start = 0;
1658
- for (var i = 0; i < raw.length; i++) {
1659
- var c = raw.charCodeAt(i);
1660
- if (c === CC_LPAREN || c === CC_LBRACK) depth++;else if (c === CC_RPAREN || c === CC_RBRACK) depth--;else if (c === CC_COMMA && depth === 0) {
1661
- parts.push(raw.slice(start, i).trim());
1662
- start = i + 1;
1663
- }
1664
- }
1665
- parts.push(raw.slice(start).trim());
1666
- return parts.filter(function (p) {
1667
- return p.length > 0;
1668
- }).map(function (p) {
1669
- return {
1670
- type: 'selector',
1671
- value: p
1672
- };
1673
- });
1674
- }
1675
-
1676
- /**
1677
- * Simple specificity scorer — counts IDs, classes/attributes/pseudos, elements.
1678
- */
1679
- }, {
1680
- key: "calcSpecificity",
1681
- value: function calcSpecificity(sel) {
1682
- var ids = 0,
1683
- classes = 0,
1684
- elements = 0;
1685
- var i = 0;
1686
- while (i < sel.length) {
1687
- var c = sel.charCodeAt(i);
1688
- if (c === CC_HASH) {
1689
- ids++;
1690
- i++;
1691
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1692
- } else if (c === CC_DOT) {
1693
- classes++;
1694
- i++;
1695
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1696
- } else if (c === CC_LBRACK) {
1697
- classes++;
1698
- while (i < sel.length && sel.charCodeAt(i) !== CC_RBRACK) i++;
1699
- i++;
1700
- } else if (c === CC_COLON) {
1701
- if (sel.charCodeAt(i + 1) === CC_COLON) {
1702
- elements++;
1703
- i += 2;
1704
- } else {
1705
- // :not(), :is(), :has() — don't double-count the wrapper
1706
- classes++;
1707
- i++;
1708
- }
1709
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1710
- // skip argument parens
1711
- if (i < sel.length && sel.charCodeAt(i) === CC_LPAREN) {
1712
- var d = 1;
1713
- i++;
1714
- while (i < sel.length && d > 0) {
1715
- if (sel.charCodeAt(i) === CC_LPAREN) d++;else if (sel.charCodeAt(i) === CC_RPAREN) d--;
1716
- i++;
1717
- }
1718
- }
1719
- } else if (isAlpha(c) || c === CC_UNDER) {
1720
- elements++;
1721
- while (i < sel.length && isNameChar(sel.charCodeAt(i))) i++;
1722
- } else {
1723
- i++;
1724
- }
1725
- }
1726
- return {
1727
- ids: ids,
1728
- classes: classes,
1729
- elements: elements,
1730
- total: ids * 100 + classes * 10 + elements
1049
+ return {
1050
+ ids: ids,
1051
+ classes: classes,
1052
+ elements: elements,
1053
+ total: ids * 100 + classes * 10 + elements
1731
1054
  };
1732
1055
  }
1733
1056
 
@@ -2411,430 +1734,567 @@ function parseCss(css, options) {
2411
1734
  return new CssParser(options).parse(css);
2412
1735
  }
2413
1736
 
2414
- // Read `@theme { --color-red-500: …; --spacing: …; }` blocks from CSS into a
2415
- // Theme. This is the CSS-first way to define tokens; the registry is then
2416
- // built from the resulting theme.
2417
- function loadTheme(css) {
2418
- var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Theme();
2419
- var sheet = parseCss(css);
2420
- var _iterator = _createForOfIteratorHelper(sheet.children),
2421
- _step;
2422
- try {
2423
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2424
- var node = _step.value;
2425
- if (node.type === 'atrule' && node.name === 'theme' && node.block) {
2426
- collect(node, theme);
2427
- }
1737
+ // Parses one raw utility (e.g. `md:hover:-bg-red-500/50!` or `[&_p]:text-[13px]`)
1738
+ // into a structured Atom in a single pass. Splitting is bracket/paren aware,
1739
+ // so `:` `/` `-` inside arbitrary values are left alone — no regex, no
1740
+ // backtracking. Which part is the root and which is the value can't be known from
1741
+ // the string alone (`text-red-500` vs `grid-cols-3`), so that split is resolved
1742
+ // against the registry through AtomContext.
1743
+
1744
+ // Split on `sep` at depth 0 only; `[...]` and `(...)` are opaque, and `\` escapes
1745
+ // the next character.
1746
+ function splitAtTopLevel(input, sep) {
1747
+ var out = [];
1748
+ var depthBracket = 0;
1749
+ var depthParen = 0;
1750
+ var start = 0;
1751
+ for (var i = 0; i < input.length; i++) {
1752
+ var c = input[i];
1753
+ if (c === '\\') {
1754
+ i++; // skip the escaped char
1755
+ continue;
2428
1756
  }
2429
- } catch (err) {
2430
- _iterator.e(err);
2431
- } finally {
2432
- _iterator.f();
2433
- }
2434
- return theme;
2435
- }
2436
- function collect(atRule, theme) {
2437
- var _iterator2 = _createForOfIteratorHelper(atRule.block.children),
2438
- _step2;
2439
- try {
2440
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2441
- var child = _step2.value;
2442
- if (child.type === 'declaration' && isCustomProperty(child)) {
2443
- var _child$rawValue;
2444
- theme.add(child.property, ((_child$rawValue = child.rawValue) !== null && _child$rawValue !== void 0 ? _child$rawValue : '').trim());
2445
- }
1757
+ if (c === '[') depthBracket++;else if (c === ']') depthBracket = Math.max(0, depthBracket - 1);else if (c === '(') depthParen++;else if (c === ')') depthParen = Math.max(0, depthParen - 1);else if (c === sep && depthBracket === 0 && depthParen === 0) {
1758
+ out.push(input.slice(start, i));
1759
+ start = i + 1;
2446
1760
  }
2447
- } catch (err) {
2448
- _iterator2.e(err);
2449
- } finally {
2450
- _iterator2.f();
2451
1761
  }
2452
- }
2453
- function isCustomProperty(d) {
2454
- return d.customProperty === true || d.property.startsWith('--');
1762
+ out.push(input.slice(start));
1763
+ return out;
2455
1764
  }
2456
1765
 
2457
- // Emit the theme as `:root { --token: value; … }` so the tokens ship as live
2458
- // custom properties. Pass `used` to emit only the tokens actually referenced
2459
- // (plus any they transitively reference) — see {@link collectVarRefs}.
2460
- function emitTheme(theme) {
2461
- var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':root';
2462
- var used = arguments.length > 2 ? arguments[2] : undefined;
2463
- var entries = used ? usedEntries(theme, used) : theme.entries();
2464
- return rule(selector, entries.map(function (_ref) {
2465
- var _ref2 = _slicedToArray(_ref, 2),
2466
- name = _ref2[0],
2467
- value = _ref2[1];
2468
- return decl(name, value);
2469
- }));
1766
+ // Content of a `[...]` or `(...)` wrapper, or null when `s` isn't wrapped.
1767
+ function unwrap(s, open) {
1768
+ var close = open === '[' ? ']' : ')';
1769
+ return s.length >= 2 && s[0] === open && s[s.length - 1] === close ? s.slice(1, -1) : null;
1770
+ }
1771
+ function parseModifier(raw) {
1772
+ if (!raw) return null;
1773
+ var arb = unwrap(raw, '[');
1774
+ if (arb !== null) return {
1775
+ kind: 'arbitrary',
1776
+ value: arb
1777
+ };
1778
+ // `(--name)` is shorthand for the custom property it references.
1779
+ var paren = unwrap(raw, '(');
1780
+ if (paren !== null) return {
1781
+ kind: 'arbitrary',
1782
+ value: "var(".concat(paren, ")")
1783
+ };
1784
+ return {
1785
+ kind: 'named',
1786
+ value: raw
1787
+ };
1788
+ }
1789
+ function splitModifier(base) {
1790
+ var parts = splitAtTopLevel(base, '/');
1791
+ if (parts.length === 1) return {
1792
+ base: base,
1793
+ modifier: null
1794
+ };
1795
+ var modifier = parseModifier(parts.slice(1).join('/'));
1796
+ return {
1797
+ base: parts[0],
1798
+ modifier: modifier
1799
+ };
2470
1800
  }
2471
- var VAR_REF = /var\(\s*(--[\w-]+)/g;
2472
1801
 
2473
- // Every `--token` referenced through `var(--token)` across a compiled tree.
2474
- function collectVarRefs(nodes) {
2475
- var into = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
2476
- var _iterator3 = _createForOfIteratorHelper(nodes),
2477
- _step3;
2478
- try {
2479
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2480
- var node = _step3.value;
2481
- if (node.kind === 'declaration') {
2482
- var _iterator4 = _createForOfIteratorHelper(node.value.matchAll(VAR_REF)),
2483
- _step4;
2484
- try {
2485
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2486
- var m = _step4.value;
2487
- into.add(m[1]);
2488
- }
2489
- } catch (err) {
2490
- _iterator4.e(err);
2491
- } finally {
2492
- _iterator4.f();
2493
- }
2494
- } else if (node.kind === 'raw') {
2495
- var _iterator5 = _createForOfIteratorHelper(node.text.matchAll(VAR_REF)),
2496
- _step5;
2497
- try {
2498
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2499
- var _m = _step5.value;
2500
- into.add(_m[1]);
2501
- }
2502
- } catch (err) {
2503
- _iterator5.e(err);
2504
- } finally {
2505
- _iterator5.f();
2506
- }
2507
- } else {
2508
- collectVarRefs(node.nodes, into);
2509
- }
2510
- }
2511
- } catch (err) {
2512
- _iterator3.e(err);
2513
- } finally {
2514
- _iterator3.f();
2515
- }
2516
- return into;
1802
+ // In arbitrary values `_` stands in for a space; `\_` is a literal underscore.
1803
+ function decodeUnderscores(value) {
1804
+ // `_` → space, `\_` → literal `_`. But a URL may legitimately contain underscores,
1805
+ // so leave the inside of `url(...)` verbatim (the split keeps url() at odd indices).
1806
+ return value.split(/(url\([^)]*\))/g).map(function (part, i) {
1807
+ return i % 2 === 1 ? part : part.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
1808
+ }).join('');
2517
1809
  }
2518
1810
 
2519
- // The theme entries to keep for `used`: the referenced tokens plus the transitive
2520
- // closure of any tokens their own values reference (e.g. `--color-primary:
2521
- // var(--color-blue-500)`). Insertion order is preserved.
2522
- function usedEntries(theme, used) {
2523
- var keep = new Set();
2524
- var stack = _toConsumableArray(used);
2525
- while (stack.length) {
2526
- var name = stack.pop();
2527
- if (keep.has(name)) continue;
2528
- var value = theme.get(name);
2529
- if (value === undefined) continue; // referenced but not a theme token
2530
- keep.add(name);
2531
- var _iterator6 = _createForOfIteratorHelper(value.matchAll(VAR_REF)),
2532
- _step6;
2533
- try {
2534
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
2535
- var m = _step6.value;
2536
- stack.push(m[1]);
2537
- }
2538
- } catch (err) {
2539
- _iterator6.e(err);
2540
- } finally {
2541
- _iterator6.f();
1811
+ // An arbitrary value may lead with a `type:` hint, e.g. `[length:12px]`.
1812
+ function parseArbitraryValue(body) {
1813
+ var colon = body.indexOf(':');
1814
+ if (colon > 0) {
1815
+ var maybeType = body.slice(0, colon);
1816
+ if (/^[a-z-]+$/.test(maybeType)) {
1817
+ return {
1818
+ dataType: maybeType,
1819
+ value: decodeUnderscores(body.slice(colon + 1))
1820
+ };
2542
1821
  }
2543
1822
  }
2544
- return theme.entries().filter(function (_ref3) {
2545
- var _ref4 = _slicedToArray(_ref3, 1),
2546
- name = _ref4[0];
2547
- return keep.has(name);
2548
- });
1823
+ return {
1824
+ dataType: null,
1825
+ value: decodeUnderscores(body)
1826
+ };
2549
1827
  }
2550
1828
 
2551
- // Reads `@utility` and `@custom-variant` blocks from CSS and registers them into
2552
- // the registry — the CSS-first way to add utilities and variants, alongside
2553
- // `@theme` for tokens. Call after loadTheme so functional utilities can resolve
2554
- // against the theme.
2555
- function loadDirectives(css, reg) {
2556
- var sheet = parseCss(css);
2557
- var _iterator = _createForOfIteratorHelper(sheet.children),
2558
- _step;
2559
- try {
2560
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
2561
- var node = _step.value;
2562
- if (node.type !== 'atrule') continue;
2563
- if (node.name === 'utility') registerUtility(node, reg);else if (node.name === 'custom-variant') registerVariant(node, reg);
2564
- }
2565
- } catch (err) {
2566
- _iterator.e(err);
2567
- } finally {
2568
- _iterator.f();
1829
+ // The `(--name)` shorthand, optionally typed: `(length:--size)`. The custom
1830
+ // property name keeps its underscores.
1831
+ function parseParenValue(paren) {
1832
+ var colon = paren.indexOf(':');
1833
+ if (colon > 0 && /^[a-z-]+$/.test(paren.slice(0, colon))) {
1834
+ return {
1835
+ dataType: paren.slice(0, colon),
1836
+ value: "var(".concat(paren.slice(colon + 1), ")")
1837
+ };
2569
1838
  }
2570
- return reg;
1839
+ return {
1840
+ dataType: null,
1841
+ value: "var(".concat(paren, ")")
1842
+ };
2571
1843
  }
2572
- function registerUtility(atRule, reg) {
2573
- var _atRule$preludeText;
2574
- var name = ((_atRule$preludeText = atRule.preludeText) !== null && _atRule$preludeText !== void 0 ? _atRule$preludeText : '').trim();
2575
- if (!name || !atRule.block) return;
1844
+ function parseVariant(raw) {
1845
+ var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1846
+ if (!raw) return null;
2576
1847
 
2577
- // Flat declarations plus any nested rules (`&:hover`, `&::-webkit-scrollbar`);
2578
- // the nested `&` is later woven with the utility's own selector by the compiler.
2579
- var products = toProducts(atRule.block.children);
2580
- if (products.length === 0) return;
1848
+ // `[&:hover]`, `[@media(...)]` — the selector is written out; a `&` means it's
1849
+ // relative to the element.
1850
+ var arb = unwrap(raw, '[');
1851
+ if (arb !== null) {
1852
+ return {
1853
+ kind: 'arbitrary',
1854
+ selector: arb,
1855
+ relative: arb.includes('&')
1856
+ };
1857
+ }
1858
+ var _splitModifier = splitModifier(raw),
1859
+ base = _splitModifier.base,
1860
+ modifier = _splitModifier.modifier;
2581
1861
 
2582
- // A trailing `-*` marks a functional utility: `tab-*` handles `tab-2`, `tab-[3]`.
2583
- if (name.endsWith('-*')) {
2584
- var root = name.slice(0, -2);
2585
- if (root) reg.dynamicRule(root, function (ctx) {
2586
- return resolveProducts(products, ctx);
2587
- });
2588
- return;
2589
- }
2590
- reg.rule(name, products);
2591
- }
2592
- function toProducts(children) {
2593
- var out = [];
2594
- var _iterator2 = _createForOfIteratorHelper(children),
2595
- _step2;
2596
- try {
2597
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2598
- var c = _step2.value;
2599
- if (c.type === 'declaration') {
2600
- var _d$rawValue;
2601
- var d = c;
2602
- out.push(decl(d.property, ((_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '').trim(), d.important === true));
2603
- } else if (c.type === 'rule') {
2604
- var _r$declarations, _r$children, _r$rawSelector;
2605
- var r = c;
2606
- // The parser splits a rule's own declarations from its nested rules; a
2607
- // utility body wants both, declarations first.
2608
- var kids = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
2609
- out.push(rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), toProducts(kids)));
2610
- }
1862
+ // A variant carrying a value: `group-hover`, `data-[open]`, `supports-[display:grid]`.
1863
+ var dash = base.indexOf('-');
1864
+ if (dash > 0) {
1865
+ var _ctx$isDynamicVariant, _ctx$isDynamicVariant2;
1866
+ var _root = base.slice(0, dash);
1867
+ var rest = base.slice(dash + 1);
1868
+ if ((_ctx$isDynamicVariant = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant !== void 0 && _ctx$isDynamicVariant.call(ctx, _root) || (_ctx$isDynamicVariant2 = ctx.isDynamicVariant) !== null && _ctx$isDynamicVariant2 !== void 0 && _ctx$isDynamicVariant2.call(ctx, _root + '-')) {
1869
+ // A variant's `[...]` is a raw condition/attribute, not a typed value.
1870
+ var arbVal = unwrap(rest, '[');
1871
+ var value = arbVal !== null ? {
1872
+ kind: 'arbitrary',
1873
+ value: arbVal,
1874
+ dataType: null
1875
+ } : {
1876
+ kind: 'named',
1877
+ value: rest
1878
+ };
1879
+ return {
1880
+ kind: 'functional',
1881
+ root: _root,
1882
+ value: value,
1883
+ modifier: modifier
1884
+ };
2611
1885
  }
2612
- } catch (err) {
2613
- _iterator2.e(err);
2614
- } finally {
2615
- _iterator2.f();
2616
1886
  }
2617
- return out;
1887
+ return {
1888
+ kind: 'functional',
1889
+ root: base,
1890
+ value: null,
1891
+ modifier: modifier
1892
+ };
2618
1893
  }
2619
1894
 
2620
- // Applies a functional utility's templates to one atom, walking nested rules too.
2621
- // `--value()` is required — if it can't resolve, the whole utility is dropped
2622
- // (returns null). `--modifier()` is optional — a declaration using it is skipped
2623
- // when there's no matching modifier, so `text-lg` and `text-lg/7` share one def.
2624
- function resolveProducts(templates, ctx) {
2625
- var out = [];
2626
- var _iterator3 = _createForOfIteratorHelper(templates),
2627
- _step3;
1895
+ // Returns null for structurally invalid input (empty or dangling segments).
1896
+ // Without a context the root/value split falls back to the first dash, which is
1897
+ // enough to test the scanner on its own.
1898
+ function parseAtom(raw) {
1899
+ var _ctx$isRule, _ctx$isRule2;
1900
+ var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1901
+ if (!raw) return null;
1902
+ var segments = splitAtTopLevel(raw, ':');
1903
+ var utility = segments.pop();
1904
+ if (utility === undefined || utility === '') return null;
1905
+ var variants = [];
1906
+ var _iterator = _createForOfIteratorHelper(segments),
1907
+ _step;
2628
1908
  try {
2629
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2630
- var t = _step3.value;
2631
- if (t.kind === 'declaration') {
2632
- var withValue = replaceFn(t.value, '--value', function (args) {
2633
- return resolveValue(args, ctx);
2634
- });
2635
- if (withValue === null) return null;
2636
- var withModifier = replaceFn(withValue, '--modifier', function (args) {
2637
- return resolveModifier(args, ctx);
2638
- });
2639
- if (withModifier === null) continue;
2640
- out.push(_objectSpread2(_objectSpread2({}, t), {}, {
2641
- value: withModifier
2642
- }));
2643
- } else {
2644
- var inner = resolveProducts(t.nodes, ctx);
2645
- if (inner === null) return null;
2646
- out.push(rule(t.selector, inner));
2647
- }
1909
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
1910
+ var seg = _step.value;
1911
+ if (seg === '') return null; // dangling `::`
1912
+ var v = parseVariant(seg, ctx);
1913
+ if (!v) return null;
1914
+ variants.push(v);
2648
1915
  }
1916
+ // Written left-to-right (outermost first), stored innermost-first so consumers
1917
+ // can wrap the declaration outward.
2649
1918
  } catch (err) {
2650
- _iterator3.e(err);
1919
+ _iterator.e(err);
2651
1920
  } finally {
2652
- _iterator3.f();
1921
+ _iterator.f();
2653
1922
  }
2654
- return out.length ? out : null;
2655
- }
2656
- function resolveValue(args, ctx) {
2657
- var value = ctx.value;
2658
- if (!value) return null;
2659
- for (var _i = 0, _splitArgs = splitArgs(args); _i < _splitArgs.length; _i++) {
2660
- var arg = _splitArgs[_i];
2661
- var themed = fromTheme(arg, value.kind === 'named' ? value.value : null, ctx);
2662
- if (themed !== null) return themed;
2663
- if (value.kind === 'named') {
2664
- var lit = fromNamed(arg, value.value);
2665
- if (lit !== null) return lit;
2666
- } else {
2667
- var arb = fromArbitrary(arg, value.value, value.dataType);
2668
- if (arb !== null) return arb;
2669
- }
1923
+ variants.reverse();
1924
+
1925
+ // `!` marks important, accepted on either end.
1926
+ var body = utility;
1927
+ var important = false;
1928
+ if (body.endsWith('!')) {
1929
+ important = true;
1930
+ body = body.slice(0, -1);
1931
+ } else if (body.startsWith('!')) {
1932
+ important = true;
1933
+ body = body.slice(1);
2670
1934
  }
2671
- return null;
2672
- }
2673
- function resolveModifier(args, ctx) {
2674
- var modifier = ctx.modifier;
2675
- if (!modifier) return null;
2676
- for (var _i2 = 0, _splitArgs2 = splitArgs(args); _i2 < _splitArgs2.length; _i2++) {
2677
- var arg = _splitArgs2[_i2];
2678
- var themed = fromTheme(arg, modifier.kind === 'named' ? modifier.value : null, ctx);
2679
- if (themed !== null) return themed;
2680
- if (modifier.kind === 'named') {
2681
- var lit = fromNamed(arg, modifier.value);
2682
- if (lit !== null) return lit;
1935
+ if (body === '') return null;
1936
+
1937
+ // Split off a trailing `/modifier` once, up front — it applies uniformly to
1938
+ // arbitrary-property, static, and functional atoms.
1939
+ var _splitModifier2 = splitModifier(body),
1940
+ core0 = _splitModifier2.base,
1941
+ modifier = _splitModifier2.modifier;
1942
+
1943
+ // Arbitrary property: `[color:red]`, `[--my-var:0]` (optionally with modifier).
1944
+ var arbProp = unwrap(core0, '[');
1945
+ if (arbProp !== null && arbProp.includes(':')) {
1946
+ var colon = arbProp.indexOf(':');
1947
+ if (colon <= 0) return null;
1948
+ // The head must be a real CSS property or custom property. Scanners pull
1949
+ // `[...]` runs out of JS/TS too (array/object literals like
1950
+ // `[...prev, { value } as T]`); rejecting a non-property head keeps those
1951
+ // from emitting broken rules that later crash the CSS parser.
1952
+ var property = arbProp.slice(0, colon);
1953
+ if (!/^-{0,2}[a-zA-Z][a-zA-Z0-9-]*$/.test(property)) return null;
1954
+ return {
1955
+ kind: 'arbitrary-property',
1956
+ property: property,
1957
+ value: decodeUnderscores(arbProp.slice(colon + 1)),
1958
+ modifier: modifier,
1959
+ important: important,
1960
+ variants: variants,
1961
+ raw: raw
1962
+ };
1963
+ }
1964
+
1965
+ // Negative.
1966
+ var negative = false;
1967
+ var base = core0;
1968
+ if (base[0] === '-') {
1969
+ negative = true;
1970
+ base = base.slice(1);
1971
+ if (base === '') return null;
1972
+ }
1973
+
1974
+ // Static utility (only when unambiguous: no negative/modifier).
1975
+ if (!negative && modifier === null && (_ctx$isRule = ctx.isRule) !== null && _ctx$isRule !== void 0 && _ctx$isRule.call(ctx, base)) {
1976
+ return {
1977
+ kind: 'static',
1978
+ root: base,
1979
+ important: important,
1980
+ variants: variants,
1981
+ raw: raw
1982
+ };
1983
+ }
1984
+
1985
+ // Functional: split root ↔ value. Prefer the longest known functional root;
1986
+ // fall back to the first-dash split when no context is supplied.
1987
+ var _splitRootValue = splitRootValue(base, ctx),
1988
+ root = _splitRootValue.root,
1989
+ valueStr = _splitRootValue.valueStr;
1990
+ if (root === '') return null;
1991
+ var value = null;
1992
+ if (valueStr !== null && valueStr !== '') {
1993
+ var arbVal = unwrap(valueStr, '[');
1994
+ if (arbVal !== null) {
1995
+ value = _objectSpread2({
1996
+ kind: 'arbitrary'
1997
+ }, parseArbitraryValue(arbVal));
2683
1998
  } else {
2684
- var arb = fromArbitrary(arg, modifier.value, null);
2685
- if (arb !== null) return arb;
1999
+ var paren = unwrap(valueStr, '(');
2000
+ value = paren !== null ? _objectSpread2({
2001
+ kind: 'arbitrary'
2002
+ }, parseParenValue(paren)) : {
2003
+ kind: 'named',
2004
+ value: valueStr,
2005
+ fraction: null
2006
+ };
2686
2007
  }
2008
+ } else if ((_ctx$isRule2 = ctx.isRule) !== null && _ctx$isRule2 !== void 0 && _ctx$isRule2.call(ctx, base)) {
2009
+ // A bare root that is registered static (reached here due to a modifier).
2010
+ return {
2011
+ kind: 'static',
2012
+ root: base,
2013
+ important: important,
2014
+ variants: variants,
2015
+ raw: raw
2016
+ };
2687
2017
  }
2688
- return null;
2689
- }
2690
-
2691
- // `--foo` / `--foo-*` names a theme namespace; the atom's named value keys into
2692
- // it (`--value(--tab-size)` + `tab-2` → `var(--tab-size-2)`).
2693
- function fromTheme(arg, key, ctx) {
2694
- if (key === null || !arg.startsWith('--')) return null;
2695
- var ns = arg.replace(/-?\*$/, '').slice(2);
2696
- return ns ? ctx.theme.resolve(ns, key) : null;
2018
+ return {
2019
+ kind: 'functional',
2020
+ root: root,
2021
+ value: value,
2022
+ modifier: modifier,
2023
+ important: important,
2024
+ negative: negative,
2025
+ variants: variants,
2026
+ raw: raw
2027
+ };
2697
2028
  }
2698
2029
 
2699
- // A bare value against a data-type keyword (`integer`, `number`, `percentage`) or a
2700
- // quoted literal (`'inline'`).
2701
- function fromNamed(arg, value) {
2702
- if (isQuoted(arg)) return arg.slice(1, -1) === value ? value : null;
2703
- var rx = NUMERIC[arg];
2704
- return rx ? rx.test(value) ? value : null : null;
2705
- }
2706
-
2707
- // An arbitrary value against `[*]` (anything) or a typed bracket (`[integer]`,
2708
- // `[length]`), gated on the value's own `type:` hint when it carries one.
2709
- function fromArbitrary(arg, value, dataType) {
2710
- if (arg[0] !== '[' || arg[arg.length - 1] !== ']') return null;
2711
- var want = arg.slice(1, -1);
2712
- if (want === '*') return value;
2713
- if (dataType !== null) return dataType === want ? value : null;
2714
- // Untyped arbitrary: validate against the simple numeric types we can check.
2715
- var rx = NUMERIC[want];
2716
- return rx ? rx.test(value) ? value : null : value;
2717
- }
2718
- var NUMERIC = {
2719
- integer: /^-?\d+$/,
2720
- number: /^-?\d*\.?\d+$/,
2721
- percentage: /^-?\d*\.?\d+%$/
2722
- };
2723
- function isQuoted(s) {
2724
- return s.length >= 2 && (s[0] === '"' || s[0] === "'") && s[s.length - 1] === s[0];
2725
- }
2726
- function splitArgs(args) {
2727
- return splitAtTopLevel(args, ',').map(function (a) {
2728
- return a.trim();
2729
- }).filter(function (a) {
2730
- return a !== '';
2731
- });
2732
- }
2733
-
2734
- // Replaces every `name(...)` call in `input` (parens balanced, even when nested in
2735
- // `calc(...)`) with `resolve`'s result. Returns null if any call fails to resolve.
2736
- function replaceFn(input, name, resolve) {
2737
- var token = name + '(';
2738
- var out = '';
2739
- var i = 0;
2740
- for (;;) {
2741
- var start = input.indexOf(token, i);
2742
- if (start === -1) return out + input.slice(i);
2743
- out += input.slice(i, start);
2744
- var depth = 0;
2745
- var j = start + token.length - 1;
2746
- for (; j < input.length; j++) {
2747
- if (input[j] === '(') depth++;else if (input[j] === ')' && --depth === 0) break;
2030
+ // Splits `bg-red-500` into a root and value. The longest registered root wins
2031
+ // (`grid-cols-3` → `grid-cols` + `3`); with no context, split at the first dash.
2032
+ function splitRootValue(base, ctx) {
2033
+ if (ctx.isDynamicRule) {
2034
+ // The whole class is itself the longest possible root (`rounded-t`, `border-x`);
2035
+ // prefer it before splitting off a shorter registered prefix (`rounded` + `t`).
2036
+ if (ctx.isDynamicRule(base)) return {
2037
+ root: base,
2038
+ valueStr: null
2039
+ };
2040
+ var dashes = [];
2041
+ for (var i = 0; i < base.length; i++) if (base[i] === '-') dashes.push(i);
2042
+ for (var d = dashes.length - 1; d >= 0; d--) {
2043
+ var idx = dashes[d];
2044
+ var _root2 = base.slice(0, idx);
2045
+ if (ctx.isDynamicRule(_root2)) return {
2046
+ root: _root2,
2047
+ valueStr: base.slice(idx + 1)
2048
+ };
2748
2049
  }
2749
- if (j >= input.length) return null; // unbalanced
2750
- var resolved = resolve(input.slice(start + token.length, j));
2751
- if (resolved === null) return null;
2752
- out += resolved;
2753
- i = j + 1;
2754
2050
  }
2051
+ var first = base.indexOf('-');
2052
+ if (first <= 0) return {
2053
+ root: base,
2054
+ valueStr: null
2055
+ };
2056
+ return {
2057
+ root: base.slice(0, first),
2058
+ valueStr: base.slice(first + 1)
2059
+ };
2755
2060
  }
2756
- function registerVariant(atRule, reg) {
2757
- var _atRule$preludeText2;
2758
- var prelude = ((_atRule$preludeText2 = atRule.preludeText) !== null && _atRule$preludeText2 !== void 0 ? _atRule$preludeText2 : '').trim();
2759
- if (!prelude) return;
2760
2061
 
2761
- // Block form: `@custom-variant name { &:hover { @slot } }` — the prelude is just
2762
- // the name and the block describes the wrapping, marked by `@slot`.
2763
- if (atRule.block) {
2764
- var wrap = blockToWrap(atRule.block.children);
2765
- if (prelude && wrap) reg.variant(prelude, wrap);
2766
- return;
2062
+ // Turns a parsed atom into CSS. Returns null when the utility or any of its
2063
+ // variants aren't registered, so an unknown class simply produces nothing.
2064
+ function compileAtom(atom, reg) {
2065
+ var produced = producedFor(atom, reg);
2066
+ if (!produced || produced.length === 0) return null;
2067
+ var flat = [];
2068
+ var nested = [];
2069
+ var _iterator = _createForOfIteratorHelper(produced),
2070
+ _step;
2071
+ try {
2072
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2073
+ var node = _step.value;
2074
+ if (node.kind === 'declaration') flat.push(node);else nested.push(node);
2075
+ }
2076
+ } catch (err) {
2077
+ _iterator.e(err);
2078
+ } finally {
2079
+ _iterator.f();
2080
+ }
2081
+ if (atom.important) {
2082
+ var _iterator2 = _createForOfIteratorHelper(flat),
2083
+ _step2;
2084
+ try {
2085
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
2086
+ var d = _step2.value;
2087
+ d.important = true;
2088
+ }
2089
+ } catch (err) {
2090
+ _iterator2.e(err);
2091
+ } finally {
2092
+ _iterator2.f();
2093
+ }
2094
+ var _iterator3 = _createForOfIteratorHelper(nested),
2095
+ _step3;
2096
+ try {
2097
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
2098
+ var n = _step3.value;
2099
+ markImportant$1(n.nodes);
2100
+ }
2101
+ } catch (err) {
2102
+ _iterator3.e(err);
2103
+ } finally {
2104
+ _iterator3.f();
2105
+ }
2767
2106
  }
2107
+ var selector = '.' + escapeClass(atom.raw);
2108
+ var atRules = [];
2109
+ var _iterator4 = _createForOfIteratorHelper(atom.variants),
2110
+ _step4;
2111
+ try {
2112
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
2113
+ var variant = _step4.value;
2114
+ var wrap = resolveVariant(variant, reg);
2115
+ if (!wrap) return null;
2116
+ if (wrap.selector) selector = substitute(wrap.selector, selector);
2117
+ if (wrap.atRule) atRules.push(wrap.atRule);
2118
+ }
2768
2119
 
2769
- // Shorthand: `@custom-variant name (condition)`.
2770
- var paren = prelude.indexOf('(');
2771
- if (paren === -1 || !prelude.endsWith(')')) return;
2772
- var name = prelude.slice(0, paren).trim();
2773
- var condition = prelude.slice(paren + 1, -1).trim();
2774
- if (!name || !condition) return;
2775
- reg.variant(name, wrapFor(condition));
2120
+ // Flat declarations sit on the utility's own selector; nested rules weave that
2121
+ // selector into their `&` (`space-x-4` → `.space-x-4 > :not([hidden]) ~ …`).
2122
+ } catch (err) {
2123
+ _iterator4.e(err);
2124
+ } finally {
2125
+ _iterator4.f();
2126
+ }
2127
+ var nodes = [];
2128
+ if (flat.length) nodes.push(rule(selector, flat));
2129
+ for (var _i = 0, _nested = nested; _i < _nested.length; _i++) {
2130
+ var _n = _nested[_i];
2131
+ nodes.push(rule(substitute(_n.selector, selector), _n.nodes));
2132
+ }
2133
+ for (var _i2 = 0, _atRules = atRules; _i2 < _atRules.length; _i2++) {
2134
+ var ar = _atRules[_i2];
2135
+ nodes = [atRule(ar.name, ar.params, nodes)];
2136
+ }
2137
+ return nodes;
2776
2138
  }
2777
-
2778
- // Walk the single path down to `@slot`, collecting the selector (nested rules,
2779
- // combined by `&` substitution) and/or the wrapping at-rule (`@media`, `@supports`).
2780
- // Supports one selector level, one at-rule level, or both nested.
2781
- function blockToWrap(children) {
2782
- var selector;
2783
- var at;
2784
- var node = firstBlockChild(children);
2785
- while (node) {
2786
- if (node.type === 'rule') {
2787
- var _rawSelector, _children;
2788
- var sel = ((_rawSelector = node.rawSelector) !== null && _rawSelector !== void 0 ? _rawSelector : '').trim();
2789
- selector = selector ? sel.replace(/&/g, selector) : sel;
2790
- node = firstBlockChild((_children = node.children) !== null && _children !== void 0 ? _children : []);
2791
- } else if (node.type === 'atrule') {
2792
- var _ar$preludeText;
2793
- var ar = node;
2794
- if (ar.name === 'slot') break;
2795
- at = {
2796
- name: ar.name,
2797
- params: ((_ar$preludeText = ar.preludeText) !== null && _ar$preludeText !== void 0 ? _ar$preludeText : '').trim()
2798
- };
2799
- node = ar.block ? firstBlockChild(ar.block.children) : undefined;
2800
- } else {
2801
- node = undefined;
2139
+ function markImportant$1(nodes) {
2140
+ var _iterator5 = _createForOfIteratorHelper(nodes),
2141
+ _step5;
2142
+ try {
2143
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
2144
+ var n = _step5.value;
2145
+ if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant$1(n.nodes);
2802
2146
  }
2147
+ } catch (err) {
2148
+ _iterator5.e(err);
2149
+ } finally {
2150
+ _iterator5.f();
2803
2151
  }
2804
- var wrap = {};
2805
- if (selector) wrap.selector = selector.includes('&') ? selector : "&".concat(selector);
2806
- if (at) wrap.atRule = at;
2807
- return wrap.selector || wrap.atRule ? wrap : null;
2808
2152
  }
2809
- function firstBlockChild(children) {
2810
- return children.find(function (c) {
2811
- return c.type === 'rule' || c.type === 'atrule';
2153
+ function producedFor(atom, reg) {
2154
+ if (atom.kind === 'arbitrary-property') {
2155
+ return [decl(atom.property, atom.value)];
2156
+ }
2157
+ if (atom.kind === 'static') {
2158
+ // Clone: static templates are shared, and `!important` / `&`-weaving mutate.
2159
+ var products = reg.getRule(atom.root);
2160
+ return products ? products.map(cloneProduct) : null;
2161
+ }
2162
+ var handler = reg.getDynamicRule(atom.root);
2163
+ if (!handler) return null;
2164
+ return handler({
2165
+ value: atom.value,
2166
+ modifier: atom.modifier,
2167
+ negative: atom.negative,
2168
+ theme: reg.theme
2812
2169
  });
2813
2170
  }
2814
- function wrapFor(condition) {
2815
- if (condition[0] === '@') {
2816
- var cut = condition.search(/[\s(]/);
2817
- var at = cut === -1 ? condition.slice(1) : condition.slice(1, cut);
2818
- var params = cut === -1 ? '' : condition.slice(cut).trim();
2819
- return {
2820
- atRule: {
2821
- name: at,
2822
- params: params
2823
- }
2824
- };
2825
- }
2826
- return {
2827
- selector: condition.includes('&') ? condition : "&".concat(condition)
2828
- };
2171
+ function cloneProduct(n) {
2172
+ return n.kind === 'declaration' ? _objectSpread2({}, n) : cloneNode(n);
2829
2173
  }
2830
-
2831
- // A utility produces declarations on its own selector, and/or nested rules whose
2832
- // `&` is woven with that selector — the latter is how child-combinator utilities
2833
- // like `space-x`/`divide-y` reach `& > * + *`.
2834
-
2835
- // A variant either narrows the selector (`&:hover`, `.group:hover &`) or wraps
2836
- // the rule in an at-rule (`@media`, `@supports`). It may do both.
2837
-
2174
+ function cloneNode(n) {
2175
+ if (n.kind === 'declaration') return _objectSpread2({}, n);
2176
+ if (n.kind === 'rule') return rule(n.selector, n.nodes.map(cloneNode));
2177
+ if (n.kind === 'at-rule') return atRule(n.name, n.params, n.nodes.map(cloneNode));
2178
+ return _objectSpread2({}, n);
2179
+ }
2180
+ function resolveVariant(variant, reg) {
2181
+ if (variant.kind === 'arbitrary') return arbitraryVariant(variant.selector);
2182
+ if (variant.kind === 'static') return reg.getVariant(variant.root);
2183
+ // functional: a null value means it's really a static variant (hover, md, …).
2184
+ if (variant.value === null) return reg.getVariant(variant.root);
2185
+ var handler = reg.getDynamicVariant(variant.root);
2186
+ return handler ? handler(variant.value, variant.modifier) : null;
2187
+ }
2188
+
2189
+ // `[&_p]` → `& p`, `[.parent_&]` → `.parent &`, `[@media(...)]` → an at-rule.
2190
+ // A bare selector with no `&` is attached to the element.
2191
+ function arbitraryVariant(source) {
2192
+ if (source[0] === '@') {
2193
+ var cut = source.search(/[\s(]/);
2194
+ var name = cut === -1 ? source.slice(1) : source.slice(1, cut);
2195
+ var params = cut === -1 ? '' : source.slice(cut).trim();
2196
+ return {
2197
+ atRule: {
2198
+ name: name,
2199
+ params: params
2200
+ }
2201
+ };
2202
+ }
2203
+ var sel = spacesFromUnderscores(source);
2204
+ return {
2205
+ selector: sel.includes('&') ? sel : "&".concat(sel)
2206
+ };
2207
+ }
2208
+ function spacesFromUnderscores(s) {
2209
+ return s.replace(/\\_/g, '\0').replace(/_/g, ' ').replace(/\0/g, '_');
2210
+ }
2211
+ function substitute(template, current) {
2212
+ return template.replace(/&/g, current);
2213
+ }
2214
+
2215
+ // Backslash-escape everything outside [A-Za-z0-9_-] so a utility name is a valid
2216
+ // class selector (`hover:bg-red-500/50` → `hover\:bg-red-500\/50`).
2217
+ function escapeClass(name) {
2218
+ return name.replace(/[^a-zA-Z0-9_-]/g, function (c) {
2219
+ return '\\' + c;
2220
+ });
2221
+ }
2222
+
2223
+ // The resolved token table. Every entry is a CSS custom property (`--color-red-500`,
2224
+ // `--spacing`, `--breakpoint-md`, …); utilities read them by namespace and emit
2225
+ // `var()` references, so the tokens stay live and themeable at runtime.
2226
+
2227
+ var Theme = /*#__PURE__*/function () {
2228
+ function Theme() {
2229
+ _classCallCheck(this, Theme);
2230
+ _defineProperty(this, "values", new Map());
2231
+ }
2232
+ return _createClass(Theme, [{
2233
+ key: "add",
2234
+ value: function add(name, value) {
2235
+ this.values.set(name, value);
2236
+ return this;
2237
+ }
2238
+ }, {
2239
+ key: "addAll",
2240
+ value: function addAll(entries) {
2241
+ for (var name in entries) this.add(name, entries[name]);
2242
+ return this;
2243
+ }
2244
+ }, {
2245
+ key: "get",
2246
+ value: function get(name) {
2247
+ return this.values.get(name);
2248
+ }
2249
+ }, {
2250
+ key: "has",
2251
+ value: function has(name) {
2252
+ return this.values.has(name);
2253
+ }
2254
+
2255
+ // A `var()` reference to `--<namespace>-<key>` when that token exists.
2256
+ }, {
2257
+ key: "resolve",
2258
+ value: function resolve(namespace, key) {
2259
+ var name = "--".concat(namespace, "-").concat(key);
2260
+ return this.values.has(name) ? "var(".concat(name, ")") : null;
2261
+ }
2262
+
2263
+ // Bare keys registered under a namespace, e.g. every color name.
2264
+ }, {
2265
+ key: "keysIn",
2266
+ value: function keysIn(namespace) {
2267
+ var prefix = "--".concat(namespace, "-");
2268
+ var out = [];
2269
+ var _iterator = _createForOfIteratorHelper(this.values.keys()),
2270
+ _step;
2271
+ try {
2272
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
2273
+ var name = _step.value;
2274
+ if (name.startsWith(prefix)) out.push(name.slice(prefix.length));
2275
+ }
2276
+ } catch (err) {
2277
+ _iterator.e(err);
2278
+ } finally {
2279
+ _iterator.f();
2280
+ }
2281
+ return out;
2282
+ }
2283
+ }, {
2284
+ key: "entries",
2285
+ value: function entries() {
2286
+ return _toConsumableArray(this.values.entries());
2287
+ }
2288
+ }]);
2289
+ }();
2290
+
2291
+ // A utility produces declarations on its own selector, and/or nested rules whose
2292
+ // `&` is woven with that selector — the latter is how child-combinator utilities
2293
+ // like `space-x`/`divide-y` reach `& > * + *`.
2294
+
2295
+ // A variant either narrows the selector (`&:hover`, `.group:hover &`) or wraps
2296
+ // the rule in an at-rule (`@media`, `@supports`). It may do both.
2297
+
2838
2298
  // Holds the theme plus the rule and variant tables, and answers the keyword vs
2839
2299
  // value-taking questions the atom parser asks.
2840
2300
  var Registry = /*#__PURE__*/function () {
@@ -2884,6 +2344,18 @@ var Registry = /*#__PURE__*/function () {
2884
2344
  this.dynamicVariants.set(name, handler);
2885
2345
  return this;
2886
2346
  }
2347
+
2348
+ /** Every registered name, for tools that list them (completion, a utility reference). */
2349
+ }, {
2350
+ key: "names",
2351
+ value: function names() {
2352
+ return {
2353
+ rules: _toConsumableArray(this.rules.keys()),
2354
+ dynamicRules: _toConsumableArray(this.dynamicRules.keys()),
2355
+ variants: _toConsumableArray(this.variants.keys()),
2356
+ dynamicVariants: _toConsumableArray(this.dynamicVariants.keys())
2357
+ };
2358
+ }
2887
2359
  }, {
2888
2360
  key: "getRule",
2889
2361
  value: function getRule(root) {
@@ -4482,235 +3954,1098 @@ function resolveLeading(value, theme) {
4482
3954
  return [decl('line-height', "calc(var(--spacing) * ".concat(value.value, ")"))];
4483
3955
  }
4484
3956
  }
4485
- return null;
3957
+ return null;
3958
+ }
3959
+
3960
+ function registerUtilities(reg) {
3961
+ registerLayout(reg);
3962
+ registerFlexGrid(reg);
3963
+ registerSpacing(reg);
3964
+ registerSizing(reg);
3965
+ registerTypography(reg);
3966
+ registerBackgrounds(reg);
3967
+ registerBorders(reg);
3968
+ registerEffects(reg);
3969
+ registerTransforms(reg);
3970
+ registerTransitions(reg);
3971
+ registerFilters(reg);
3972
+ registerGradients(reg);
3973
+ }
3974
+
3975
+ function registerVariants(reg) {
3976
+ for (var _i = 0, _Object$entries = Object.entries(PSEUDO); _i < _Object$entries.length; _i++) {
3977
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
3978
+ name = _Object$entries$_i[0],
3979
+ sel = _Object$entries$_i[1];
3980
+ reg.variant(name, {
3981
+ selector: sel
3982
+ });
3983
+ }
3984
+ for (var _i2 = 0, _Object$entries2 = Object.entries(PSEUDO_ELEMENT); _i2 < _Object$entries2.length; _i2++) {
3985
+ var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
3986
+ _name = _Object$entries2$_i[0],
3987
+ _sel = _Object$entries2$_i[1];
3988
+ reg.variant(_name, {
3989
+ selector: _sel
3990
+ });
3991
+ }
3992
+ for (var _i3 = 0, _Object$entries3 = Object.entries(MEDIA); _i3 < _Object$entries3.length; _i3++) {
3993
+ var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
3994
+ _name2 = _Object$entries3$_i[0],
3995
+ params = _Object$entries3$_i[1];
3996
+ reg.variant(_name2, {
3997
+ atRule: {
3998
+ name: 'media',
3999
+ params: params
4000
+ }
4001
+ });
4002
+ }
4003
+ reg.variant('rtl', {
4004
+ selector: '&:where([dir="rtl"], [dir="rtl"] *)'
4005
+ });
4006
+ reg.variant('ltr', {
4007
+ selector: '&:where([dir="ltr"], [dir="ltr"] *)'
4008
+ });
4009
+ reg.variant('*', {
4010
+ selector: '& > *'
4011
+ }); // direct children
4012
+ reg.variant('**', {
4013
+ selector: '& *'
4014
+ }); // all descendants
4015
+ reg.variant('open', {
4016
+ selector: '&:is([open], :open)'
4017
+ });
4018
+ reg.variant('inert', {
4019
+ selector: '&:is([inert], [inert] *)'
4020
+ });
4021
+ registerBreakpointVariants(reg);
4022
+
4023
+ // `max-md`, `min-lg` resolve the named breakpoint from the theme; `max-[600px]`
4024
+ // takes the width verbatim. `max-*` overrides the `max-w`/`max-h` utilities here
4025
+ // because it's a variant, not a utility.
4026
+ var width = function width(v) {
4027
+ var _reg$theme$get;
4028
+ var value = named(v);
4029
+ if (!value) return null;
4030
+ return v.kind === 'arbitrary' ? value : (_reg$theme$get = reg.theme.get("--breakpoint-".concat(value))) !== null && _reg$theme$get !== void 0 ? _reg$theme$get : null;
4031
+ };
4032
+ reg.dynamicVariant('min', function (v) {
4033
+ return mediaWidth('min-width', width(v));
4034
+ });
4035
+ reg.dynamicVariant('max', function (v) {
4036
+ return mediaWidth('max-width', width(v));
4037
+ });
4038
+ reg.dynamicVariant('group', function (v, m) {
4039
+ return relational(v, m, '.group', ' &');
4040
+ });
4041
+ reg.dynamicVariant('peer', function (v, m) {
4042
+ return relational(v, m, '.peer', ' ~ &');
4043
+ });
4044
+ reg.dynamicVariant('data', function (v) {
4045
+ return named(v) ? {
4046
+ selector: "&[data-".concat(named(v), "]")
4047
+ } : null;
4048
+ });
4049
+ reg.dynamicVariant('aria', function (v) {
4050
+ return named(v) ? {
4051
+ selector: "&[aria-".concat(named(v), "]")
4052
+ } : null;
4053
+ });
4054
+ reg.dynamicVariant('has', function (v) {
4055
+ return named(v) ? {
4056
+ selector: "&:has(".concat(named(v), ")")
4057
+ } : null;
4058
+ });
4059
+ reg.dynamicVariant('not', function (v) {
4060
+ return notVariant(reg, v);
4061
+ });
4062
+ reg.dynamicVariant('supports', function (v) {
4063
+ return named(v) ? {
4064
+ atRule: {
4065
+ name: 'supports',
4066
+ params: "(".concat(named(v), ")")
4067
+ }
4068
+ } : null;
4069
+ });
4070
+ }
4071
+
4072
+ // The named breakpoints (`sm:`/`md:`/…) are static variants, so their media params
4073
+ // bake the theme value at registration. A `@theme { --breakpoint-md: … }` override
4074
+ // loaded later wouldn't reach them — so compile() re-runs this after loadTheme to
4075
+ // pick up overrides. (The dynamic `min-*`/`max-*` already resolve at apply time.)
4076
+ function registerBreakpointVariants(reg) {
4077
+ for (var _i4 = 0, _arr = ['sm', 'md', 'lg', 'xl', '2xl']; _i4 < _arr.length; _i4++) {
4078
+ var bp = _arr[_i4];
4079
+ var min = reg.theme.get("--breakpoint-".concat(bp));
4080
+ if (min) reg.variant(bp, {
4081
+ atRule: {
4082
+ name: 'media',
4083
+ params: "(min-width: ".concat(min, ")")
4084
+ }
4085
+ });
4086
+ }
4087
+ }
4088
+ function mediaWidth(feature, value) {
4089
+ return value ? {
4090
+ atRule: {
4091
+ name: 'media',
4092
+ params: "(".concat(feature, ": ").concat(value, ")")
4093
+ }
4094
+ } : null;
4095
+ }
4096
+ var PSEUDO = {
4097
+ hover: '&:hover',
4098
+ focus: '&:focus',
4099
+ 'focus-within': '&:focus-within',
4100
+ 'focus-visible': '&:focus-visible',
4101
+ active: '&:active',
4102
+ visited: '&:visited',
4103
+ target: '&:target',
4104
+ disabled: '&:disabled',
4105
+ enabled: '&:enabled',
4106
+ checked: '&:checked',
4107
+ indeterminate: '&:indeterminate',
4108
+ "default": '&:default',
4109
+ required: '&:required',
4110
+ valid: '&:valid',
4111
+ invalid: '&:invalid',
4112
+ 'read-only': '&:read-only',
4113
+ 'placeholder-shown': '&:placeholder-shown',
4114
+ autofill: '&:autofill',
4115
+ empty: '&:empty',
4116
+ first: '&:first-child',
4117
+ last: '&:last-child',
4118
+ only: '&:only-child',
4119
+ odd: '&:nth-child(odd)',
4120
+ even: '&:nth-child(even)',
4121
+ 'first-of-type': '&:first-of-type',
4122
+ 'last-of-type': '&:last-of-type'
4123
+ };
4124
+ var PSEUDO_ELEMENT = {
4125
+ before: '&::before',
4126
+ after: '&::after',
4127
+ placeholder: '&::placeholder',
4128
+ selection: '&::selection',
4129
+ marker: '&::marker',
4130
+ file: '&::file-selector-button',
4131
+ backdrop: '&::backdrop',
4132
+ 'first-line': '&::first-line',
4133
+ 'first-letter': '&::first-letter'
4134
+ };
4135
+ var MEDIA = {
4136
+ dark: '(prefers-color-scheme: dark)',
4137
+ 'motion-reduce': '(prefers-reduced-motion: reduce)',
4138
+ 'motion-safe': '(prefers-reduced-motion: no-preference)',
4139
+ 'contrast-more': '(prefers-contrast: more)',
4140
+ 'contrast-less': '(prefers-contrast: less)',
4141
+ portrait: '(orientation: portrait)',
4142
+ landscape: '(orientation: landscape)',
4143
+ print: 'print'
4144
+ };
4145
+ function named(v) {
4146
+ return v ? v.value : null;
4147
+ }
4148
+
4149
+ // `group-hover` → `.group:hover &`; `group-[.foo]` → `.group.foo &`. A named value
4150
+ // is a pseudo-class, an arbitrary one is a raw selector fragment. A `/name`
4151
+ // modifier scopes to a named group/peer (`group-hover/item` → `.group\/item:hover`).
4152
+ function relational(v, m, base, tail) {
4153
+ var value = named(v);
4154
+ if (!value) return null;
4155
+ var cond = v.kind === 'arbitrary' ? value : ":".concat(value);
4156
+ var scope = m ? "".concat(base, "\\/").concat(m.value) : base;
4157
+ return {
4158
+ selector: "".concat(scope).concat(cond).concat(tail)
4159
+ };
4160
+ }
4161
+
4162
+ // `not-hover` → `&:not(:hover)`, `not-first` → `&:not(:first-child)`: resolve the
4163
+ // inner variant's pseudo, so the selector is valid (not the literal name). Only
4164
+ // simple pseudo variants compose; `not-[…]` takes an arbitrary selector.
4165
+ function notVariant(reg, v) {
4166
+ var _reg$getVariant;
4167
+ var value = named(v);
4168
+ if (!value) return null;
4169
+ if (v.kind === 'arbitrary') return {
4170
+ selector: "&:not(".concat(value, ")")
4171
+ };
4172
+ var frag = (_reg$getVariant = reg.getVariant(value)) === null || _reg$getVariant === void 0 || (_reg$getVariant = _reg$getVariant.selector) === null || _reg$getVariant === void 0 ? void 0 : _reg$getVariant.replace(/^&/, '').trim();
4173
+ return frag && frag.startsWith(':') ? {
4174
+ selector: "&:not(".concat(frag, ")")
4175
+ } : null;
4176
+ }
4177
+
4178
+ // The batteries-included registry: the default token theme plus the utility
4179
+ // families and variants. Projects extend it (`@utility`, `@theme`, JS config) or
4180
+ // build a bare `new Registry(theme)` and register their own.
4181
+ function createRegistry() {
4182
+ var reg = new Registry(defaultTheme());
4183
+ registerUtilities(reg);
4184
+ registerVariants(reg);
4185
+ return reg;
4186
+ }
4187
+
4188
+ // Reads `@utility` and `@custom-variant` blocks from CSS and registers them into
4189
+ // the registry — the CSS-first way to add utilities and variants, alongside
4190
+ // `@theme` for tokens. Call after loadTheme so functional utilities can resolve
4191
+ // against the theme.
4192
+ function loadDirectives(css, reg) {
4193
+ var sheet = parseCss(css);
4194
+ var _iterator = _createForOfIteratorHelper(sheet.children),
4195
+ _step;
4196
+ try {
4197
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4198
+ var node = _step.value;
4199
+ if (node.type !== 'atrule') continue;
4200
+ if (node.name === 'utility') registerUtility(node, reg);else if (node.name === 'custom-variant') registerVariant(node, reg);
4201
+ }
4202
+ } catch (err) {
4203
+ _iterator.e(err);
4204
+ } finally {
4205
+ _iterator.f();
4206
+ }
4207
+ return reg;
4208
+ }
4209
+ function registerUtility(atRule, reg) {
4210
+ var _atRule$preludeText;
4211
+ var name = ((_atRule$preludeText = atRule.preludeText) !== null && _atRule$preludeText !== void 0 ? _atRule$preludeText : '').trim();
4212
+ if (!name || !atRule.block) return;
4213
+
4214
+ // Flat declarations plus any nested rules (`&:hover`, `&::-webkit-scrollbar`);
4215
+ // the nested `&` is later woven with the utility's own selector by the compiler.
4216
+ var products = toProducts(atRule.block.children);
4217
+ if (products.length === 0) return;
4218
+
4219
+ // A trailing `-*` marks a functional utility: `tab-*` handles `tab-2`, `tab-[3]`.
4220
+ if (name.endsWith('-*')) {
4221
+ var root = name.slice(0, -2);
4222
+ if (root) reg.dynamicRule(root, function (ctx) {
4223
+ return resolveProducts(products, ctx);
4224
+ });
4225
+ return;
4226
+ }
4227
+ reg.rule(name, products);
4228
+ }
4229
+ function toProducts(children) {
4230
+ var out = [];
4231
+ var _iterator2 = _createForOfIteratorHelper(children),
4232
+ _step2;
4233
+ try {
4234
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4235
+ var c = _step2.value;
4236
+ if (c.type === 'declaration') {
4237
+ var _d$rawValue;
4238
+ var d = c;
4239
+ out.push(decl(d.property, ((_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '').trim(), d.important === true));
4240
+ } else if (c.type === 'rule') {
4241
+ var _r$declarations, _r$children, _r$rawSelector;
4242
+ var r = c;
4243
+ // The parser splits a rule's own declarations from its nested rules; a
4244
+ // utility body wants both, declarations first.
4245
+ var kids = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
4246
+ out.push(rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), toProducts(kids)));
4247
+ }
4248
+ }
4249
+ } catch (err) {
4250
+ _iterator2.e(err);
4251
+ } finally {
4252
+ _iterator2.f();
4253
+ }
4254
+ return out;
4255
+ }
4256
+
4257
+ // Applies a functional utility's templates to one atom, walking nested rules too.
4258
+ // `--value()` is required — if it can't resolve, the whole utility is dropped
4259
+ // (returns null). `--modifier()` is optional — a declaration using it is skipped
4260
+ // when there's no matching modifier, so `text-lg` and `text-lg/7` share one def.
4261
+ function resolveProducts(templates, ctx) {
4262
+ var out = [];
4263
+ var _iterator3 = _createForOfIteratorHelper(templates),
4264
+ _step3;
4265
+ try {
4266
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4267
+ var t = _step3.value;
4268
+ if (t.kind === 'declaration') {
4269
+ var withValue = replaceFn(t.value, '--value', function (args) {
4270
+ return resolveValue(args, ctx);
4271
+ });
4272
+ if (withValue === null) return null;
4273
+ var withModifier = replaceFn(withValue, '--modifier', function (args) {
4274
+ return resolveModifier(args, ctx);
4275
+ });
4276
+ if (withModifier === null) continue;
4277
+ out.push(_objectSpread2(_objectSpread2({}, t), {}, {
4278
+ value: withModifier
4279
+ }));
4280
+ } else {
4281
+ var inner = resolveProducts(t.nodes, ctx);
4282
+ if (inner === null) return null;
4283
+ out.push(rule(t.selector, inner));
4284
+ }
4285
+ }
4286
+ } catch (err) {
4287
+ _iterator3.e(err);
4288
+ } finally {
4289
+ _iterator3.f();
4290
+ }
4291
+ return out.length ? out : null;
4292
+ }
4293
+ function resolveValue(args, ctx) {
4294
+ var value = ctx.value;
4295
+ if (!value) return null;
4296
+ for (var _i = 0, _splitArgs = splitArgs(args); _i < _splitArgs.length; _i++) {
4297
+ var arg = _splitArgs[_i];
4298
+ var themed = fromTheme(arg, value.kind === 'named' ? value.value : null, ctx);
4299
+ if (themed !== null) return themed;
4300
+ if (value.kind === 'named') {
4301
+ var lit = fromNamed(arg, value.value);
4302
+ if (lit !== null) return lit;
4303
+ } else {
4304
+ var arb = fromArbitrary(arg, value.value, value.dataType);
4305
+ if (arb !== null) return arb;
4306
+ }
4307
+ }
4308
+ return null;
4309
+ }
4310
+ function resolveModifier(args, ctx) {
4311
+ var modifier = ctx.modifier;
4312
+ if (!modifier) return null;
4313
+ for (var _i2 = 0, _splitArgs2 = splitArgs(args); _i2 < _splitArgs2.length; _i2++) {
4314
+ var arg = _splitArgs2[_i2];
4315
+ var themed = fromTheme(arg, modifier.kind === 'named' ? modifier.value : null, ctx);
4316
+ if (themed !== null) return themed;
4317
+ if (modifier.kind === 'named') {
4318
+ var lit = fromNamed(arg, modifier.value);
4319
+ if (lit !== null) return lit;
4320
+ } else {
4321
+ var arb = fromArbitrary(arg, modifier.value, null);
4322
+ if (arb !== null) return arb;
4323
+ }
4324
+ }
4325
+ return null;
4326
+ }
4327
+
4328
+ // `--foo` / `--foo-*` names a theme namespace; the atom's named value keys into
4329
+ // it (`--value(--tab-size)` + `tab-2` → `var(--tab-size-2)`).
4330
+ function fromTheme(arg, key, ctx) {
4331
+ if (key === null || !arg.startsWith('--')) return null;
4332
+ var ns = arg.replace(/-?\*$/, '').slice(2);
4333
+ return ns ? ctx.theme.resolve(ns, key) : null;
4334
+ }
4335
+
4336
+ // A bare value against a data-type keyword (`integer`, `number`, `percentage`) or a
4337
+ // quoted literal (`'inline'`).
4338
+ function fromNamed(arg, value) {
4339
+ if (isQuoted(arg)) return arg.slice(1, -1) === value ? value : null;
4340
+ var rx = NUMERIC[arg];
4341
+ return rx ? rx.test(value) ? value : null : null;
4342
+ }
4343
+
4344
+ // An arbitrary value against `[*]` (anything) or a typed bracket (`[integer]`,
4345
+ // `[length]`), gated on the value's own `type:` hint when it carries one.
4346
+ function fromArbitrary(arg, value, dataType) {
4347
+ if (arg[0] !== '[' || arg[arg.length - 1] !== ']') return null;
4348
+ var want = arg.slice(1, -1);
4349
+ if (want === '*') return value;
4350
+ if (dataType !== null) return dataType === want ? value : null;
4351
+ // Untyped arbitrary: validate against the simple numeric types we can check.
4352
+ var rx = NUMERIC[want];
4353
+ return rx ? rx.test(value) ? value : null : value;
4354
+ }
4355
+ var NUMERIC = {
4356
+ integer: /^-?\d+$/,
4357
+ number: /^-?\d*\.?\d+$/,
4358
+ percentage: /^-?\d*\.?\d+%$/
4359
+ };
4360
+ function isQuoted(s) {
4361
+ return s.length >= 2 && (s[0] === '"' || s[0] === "'") && s[s.length - 1] === s[0];
4362
+ }
4363
+ function splitArgs(args) {
4364
+ return splitAtTopLevel(args, ',').map(function (a) {
4365
+ return a.trim();
4366
+ }).filter(function (a) {
4367
+ return a !== '';
4368
+ });
4369
+ }
4370
+
4371
+ // Replaces every `name(...)` call in `input` (parens balanced, even when nested in
4372
+ // `calc(...)`) with `resolve`'s result. Returns null if any call fails to resolve.
4373
+ function replaceFn(input, name, resolve) {
4374
+ var token = name + '(';
4375
+ var out = '';
4376
+ var i = 0;
4377
+ for (;;) {
4378
+ var start = input.indexOf(token, i);
4379
+ if (start === -1) return out + input.slice(i);
4380
+ out += input.slice(i, start);
4381
+ var depth = 0;
4382
+ var j = start + token.length - 1;
4383
+ for (; j < input.length; j++) {
4384
+ if (input[j] === '(') depth++;else if (input[j] === ')' && --depth === 0) break;
4385
+ }
4386
+ if (j >= input.length) return null; // unbalanced
4387
+ var resolved = resolve(input.slice(start + token.length, j));
4388
+ if (resolved === null) return null;
4389
+ out += resolved;
4390
+ i = j + 1;
4391
+ }
4392
+ }
4393
+ function registerVariant(atRule, reg) {
4394
+ var _atRule$preludeText2;
4395
+ var prelude = ((_atRule$preludeText2 = atRule.preludeText) !== null && _atRule$preludeText2 !== void 0 ? _atRule$preludeText2 : '').trim();
4396
+ if (!prelude) return;
4397
+
4398
+ // Block form: `@custom-variant name { &:hover { @slot } }` — the prelude is just
4399
+ // the name and the block describes the wrapping, marked by `@slot`.
4400
+ if (atRule.block) {
4401
+ var wrap = blockToWrap(atRule.block.children);
4402
+ if (prelude && wrap) reg.variant(prelude, wrap);
4403
+ return;
4404
+ }
4405
+
4406
+ // Shorthand: `@custom-variant name (condition)`.
4407
+ var paren = prelude.indexOf('(');
4408
+ if (paren === -1 || !prelude.endsWith(')')) return;
4409
+ var name = prelude.slice(0, paren).trim();
4410
+ var condition = prelude.slice(paren + 1, -1).trim();
4411
+ if (!name || !condition) return;
4412
+ reg.variant(name, wrapFor(condition));
4413
+ }
4414
+
4415
+ // Walk the single path down to `@slot`, collecting the selector (nested rules,
4416
+ // combined by `&` substitution) and/or the wrapping at-rule (`@media`, `@supports`).
4417
+ // Supports one selector level, one at-rule level, or both nested.
4418
+ function blockToWrap(children) {
4419
+ var selector;
4420
+ var at;
4421
+ var node = firstBlockChild(children);
4422
+ while (node) {
4423
+ if (node.type === 'rule') {
4424
+ var _rawSelector, _children;
4425
+ var sel = ((_rawSelector = node.rawSelector) !== null && _rawSelector !== void 0 ? _rawSelector : '').trim();
4426
+ selector = selector ? sel.replace(/&/g, selector) : sel;
4427
+ node = firstBlockChild((_children = node.children) !== null && _children !== void 0 ? _children : []);
4428
+ } else if (node.type === 'atrule') {
4429
+ var _ar$preludeText;
4430
+ var ar = node;
4431
+ if (ar.name === 'slot') break;
4432
+ at = {
4433
+ name: ar.name,
4434
+ params: ((_ar$preludeText = ar.preludeText) !== null && _ar$preludeText !== void 0 ? _ar$preludeText : '').trim()
4435
+ };
4436
+ node = ar.block ? firstBlockChild(ar.block.children) : undefined;
4437
+ } else {
4438
+ node = undefined;
4439
+ }
4440
+ }
4441
+ var wrap = {};
4442
+ if (selector) wrap.selector = selector.includes('&') ? selector : "&".concat(selector);
4443
+ if (at) wrap.atRule = at;
4444
+ return wrap.selector || wrap.atRule ? wrap : null;
4445
+ }
4446
+ function firstBlockChild(children) {
4447
+ return children.find(function (c) {
4448
+ return c.type === 'rule' || c.type === 'atrule';
4449
+ });
4450
+ }
4451
+ function wrapFor(condition) {
4452
+ if (condition[0] === '@') {
4453
+ var cut = condition.search(/[\s(]/);
4454
+ var at = cut === -1 ? condition.slice(1) : condition.slice(1, cut);
4455
+ var params = cut === -1 ? '' : condition.slice(cut).trim();
4456
+ return {
4457
+ atRule: {
4458
+ name: at,
4459
+ params: params
4460
+ }
4461
+ };
4462
+ }
4463
+ return {
4464
+ selector: condition.includes('&') ? condition : "&".concat(condition)
4465
+ };
4466
+ }
4467
+
4468
+ // Read `@theme { --color-red-500: …; --spacing: …; }` blocks from CSS into a
4469
+ // Theme. This is the CSS-first way to define tokens; the registry is then
4470
+ // built from the resulting theme.
4471
+ function loadTheme(css) {
4472
+ var theme = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Theme();
4473
+ var sheet = parseCss(css);
4474
+ var _iterator = _createForOfIteratorHelper(sheet.children),
4475
+ _step;
4476
+ try {
4477
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4478
+ var node = _step.value;
4479
+ if (node.type === 'atrule' && node.name === 'theme' && node.block) {
4480
+ collect(node, theme);
4481
+ }
4482
+ }
4483
+ } catch (err) {
4484
+ _iterator.e(err);
4485
+ } finally {
4486
+ _iterator.f();
4487
+ }
4488
+ return theme;
4489
+ }
4490
+ function collect(atRule, theme) {
4491
+ var _iterator2 = _createForOfIteratorHelper(atRule.block.children),
4492
+ _step2;
4493
+ try {
4494
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4495
+ var child = _step2.value;
4496
+ if (child.type === 'declaration' && isCustomProperty(child)) {
4497
+ var _child$rawValue;
4498
+ theme.add(child.property, ((_child$rawValue = child.rawValue) !== null && _child$rawValue !== void 0 ? _child$rawValue : '').trim());
4499
+ }
4500
+ }
4501
+ } catch (err) {
4502
+ _iterator2.e(err);
4503
+ } finally {
4504
+ _iterator2.f();
4505
+ }
4506
+ }
4507
+ function isCustomProperty(d) {
4508
+ return d.customProperty === true || d.property.startsWith('--');
4486
4509
  }
4487
4510
 
4488
- function registerUtilities(reg) {
4489
- registerLayout(reg);
4490
- registerFlexGrid(reg);
4491
- registerSpacing(reg);
4492
- registerSizing(reg);
4493
- registerTypography(reg);
4494
- registerBackgrounds(reg);
4495
- registerBorders(reg);
4496
- registerEffects(reg);
4497
- registerTransforms(reg);
4498
- registerTransitions(reg);
4499
- registerFilters(reg);
4500
- registerGradients(reg);
4511
+ // Emit the theme as `:root { --token: value; … }` so the tokens ship as live
4512
+ // custom properties. Pass `used` to emit only the tokens actually referenced
4513
+ // (plus any they transitively reference) — see {@link collectVarRefs}.
4514
+ function emitTheme(theme) {
4515
+ var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':root';
4516
+ var used = arguments.length > 2 ? arguments[2] : undefined;
4517
+ var entries = used ? usedEntries(theme, used) : theme.entries();
4518
+ return rule(selector, entries.map(function (_ref) {
4519
+ var _ref2 = _slicedToArray(_ref, 2),
4520
+ name = _ref2[0],
4521
+ value = _ref2[1];
4522
+ return decl(name, value);
4523
+ }));
4501
4524
  }
4525
+ var VAR_REF = /var\(\s*(--[\w-]+)/g;
4502
4526
 
4503
- function registerVariants(reg) {
4504
- for (var _i = 0, _Object$entries = Object.entries(PSEUDO); _i < _Object$entries.length; _i++) {
4505
- var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
4506
- name = _Object$entries$_i[0],
4507
- sel = _Object$entries$_i[1];
4508
- reg.variant(name, {
4509
- selector: sel
4510
- });
4511
- }
4512
- for (var _i2 = 0, _Object$entries2 = Object.entries(PSEUDO_ELEMENT); _i2 < _Object$entries2.length; _i2++) {
4513
- var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
4514
- _name = _Object$entries2$_i[0],
4515
- _sel = _Object$entries2$_i[1];
4516
- reg.variant(_name, {
4517
- selector: _sel
4518
- });
4527
+ // Every `--token` referenced through `var(--token)` across a compiled tree.
4528
+ function collectVarRefs(nodes) {
4529
+ var into = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
4530
+ var _iterator3 = _createForOfIteratorHelper(nodes),
4531
+ _step3;
4532
+ try {
4533
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4534
+ var node = _step3.value;
4535
+ if (node.kind === 'declaration') {
4536
+ var _iterator4 = _createForOfIteratorHelper(node.value.matchAll(VAR_REF)),
4537
+ _step4;
4538
+ try {
4539
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
4540
+ var m = _step4.value;
4541
+ into.add(m[1]);
4542
+ }
4543
+ } catch (err) {
4544
+ _iterator4.e(err);
4545
+ } finally {
4546
+ _iterator4.f();
4547
+ }
4548
+ } else if (node.kind === 'raw') {
4549
+ var _iterator5 = _createForOfIteratorHelper(node.text.matchAll(VAR_REF)),
4550
+ _step5;
4551
+ try {
4552
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
4553
+ var _m = _step5.value;
4554
+ into.add(_m[1]);
4555
+ }
4556
+ } catch (err) {
4557
+ _iterator5.e(err);
4558
+ } finally {
4559
+ _iterator5.f();
4560
+ }
4561
+ } else {
4562
+ collectVarRefs(node.nodes, into);
4563
+ }
4564
+ }
4565
+ } catch (err) {
4566
+ _iterator3.e(err);
4567
+ } finally {
4568
+ _iterator3.f();
4519
4569
  }
4520
- for (var _i3 = 0, _Object$entries3 = Object.entries(MEDIA); _i3 < _Object$entries3.length; _i3++) {
4521
- var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
4522
- _name2 = _Object$entries3$_i[0],
4523
- params = _Object$entries3$_i[1];
4524
- reg.variant(_name2, {
4525
- atRule: {
4526
- name: 'media',
4527
- params: params
4570
+ return into;
4571
+ }
4572
+
4573
+ // The theme entries to keep for `used`: the referenced tokens plus the transitive
4574
+ // closure of any tokens their own values reference (e.g. `--color-primary:
4575
+ // var(--color-blue-500)`). Insertion order is preserved.
4576
+ function usedEntries(theme, used) {
4577
+ var keep = new Set();
4578
+ var stack = _toConsumableArray(used);
4579
+ while (stack.length) {
4580
+ var name = stack.pop();
4581
+ if (keep.has(name)) continue;
4582
+ var value = theme.get(name);
4583
+ if (value === undefined) continue; // referenced but not a theme token
4584
+ keep.add(name);
4585
+ var _iterator6 = _createForOfIteratorHelper(value.matchAll(VAR_REF)),
4586
+ _step6;
4587
+ try {
4588
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4589
+ var m = _step6.value;
4590
+ stack.push(m[1]);
4528
4591
  }
4529
- });
4592
+ } catch (err) {
4593
+ _iterator6.e(err);
4594
+ } finally {
4595
+ _iterator6.f();
4596
+ }
4530
4597
  }
4531
- reg.variant('rtl', {
4532
- selector: '&:where([dir="rtl"], [dir="rtl"] *)'
4533
- });
4534
- reg.variant('ltr', {
4535
- selector: '&:where([dir="ltr"], [dir="ltr"] *)'
4536
- });
4537
- reg.variant('*', {
4538
- selector: '& > *'
4539
- }); // direct children
4540
- reg.variant('**', {
4541
- selector: '& *'
4542
- }); // all descendants
4543
- reg.variant('open', {
4544
- selector: '&:is([open], :open)'
4545
- });
4546
- reg.variant('inert', {
4547
- selector: '&:is([inert], [inert] *)'
4598
+ return theme.entries().filter(function (_ref3) {
4599
+ var _ref4 = _slicedToArray(_ref3, 1),
4600
+ name = _ref4[0];
4601
+ return keep.has(name);
4548
4602
  });
4549
- registerBreakpointVariants(reg);
4603
+ }
4550
4604
 
4551
- // `max-md`, `min-lg` resolve the named breakpoint from the theme; `max-[600px]`
4552
- // takes the width verbatim. `max-*` overrides the `max-w`/`max-h` utilities here
4553
- // because it's a variant, not a utility.
4554
- var width = function width(v) {
4555
- var _reg$theme$get;
4556
- var value = named(v);
4557
- if (!value) return null;
4558
- return v.kind === 'arbitrary' ? value : (_reg$theme$get = reg.theme.get("--breakpoint-".concat(value))) !== null && _reg$theme$get !== void 0 ? _reg$theme$get : null;
4605
+ // ─── Parser tree → engine AST ────────────────────────────────────────────────
4606
+
4607
+ var offsetOf = function offsetOf(node) {
4608
+ var _node$loc$start$offse, _node$loc;
4609
+ return (_node$loc$start$offse = (_node$loc = node.loc) === null || _node$loc === void 0 ? void 0 : _node$loc.start.offset) !== null && _node$loc$start$offse !== void 0 ? _node$loc$start$offse : 0;
4610
+ };
4611
+ function locOf(node, source) {
4612
+ if (!source || !node.loc) return undefined;
4613
+ return {
4614
+ source: source,
4615
+ line: node.loc.start.line,
4616
+ column: Math.max(0, node.loc.start.column - 1)
4559
4617
  };
4560
- reg.dynamicVariant('min', function (v) {
4561
- return mediaWidth('min-width', width(v));
4562
- });
4563
- reg.dynamicVariant('max', function (v) {
4564
- return mediaWidth('max-width', width(v));
4565
- });
4566
- reg.dynamicVariant('group', function (v, m) {
4567
- return relational(v, m, '.group', ' &');
4568
- });
4569
- reg.dynamicVariant('peer', function (v, m) {
4570
- return relational(v, m, '.peer', ' ~ &');
4571
- });
4572
- reg.dynamicVariant('data', function (v) {
4573
- return named(v) ? {
4574
- selector: "&[data-".concat(named(v), "]")
4575
- } : null;
4576
- });
4577
- reg.dynamicVariant('aria', function (v) {
4578
- return named(v) ? {
4579
- selector: "&[aria-".concat(named(v), "]")
4580
- } : null;
4618
+ }
4619
+
4620
+ /** Parses author CSS into the engine's AST, in source order. */
4621
+ function parseStyle(css, from) {
4622
+ var sheet = parseCss(css, {
4623
+ includeSourceMaps: true,
4624
+ includeComments: false
4581
4625
  });
4582
- reg.dynamicVariant('has', function (v) {
4583
- return named(v) ? {
4584
- selector: "&:has(".concat(named(v), ")")
4585
- } : null;
4626
+ return convertAll(sheet.children, from);
4627
+ }
4628
+ function convertAll(nodes, from) {
4629
+ var out = [];
4630
+ var _iterator = _createForOfIteratorHelper(nodes),
4631
+ _step;
4632
+ try {
4633
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
4634
+ var node = _step.value;
4635
+ var converted = convert(node, from);
4636
+ if (converted) out.push(converted);
4637
+ }
4638
+ } catch (err) {
4639
+ _iterator.e(err);
4640
+ } finally {
4641
+ _iterator.f();
4642
+ }
4643
+ return out;
4644
+ }
4645
+ function convert(node, from) {
4646
+ switch (node.type) {
4647
+ case 'declaration':
4648
+ {
4649
+ var _d$rawValue;
4650
+ var d = node;
4651
+ return decl(d.property, (_d$rawValue = d.rawValue) !== null && _d$rawValue !== void 0 ? _d$rawValue : '', d.important, locOf(d, from));
4652
+ }
4653
+ case 'rule':
4654
+ {
4655
+ var _r$declarations, _r$children, _r$rawSelector;
4656
+ var r = node;
4657
+ // The parser keeps declarations and nested rules apart; the source offsets put them
4658
+ // back in the order they were written, which is the order they cascade in.
4659
+ var children = [].concat(_toConsumableArray((_r$declarations = r.declarations) !== null && _r$declarations !== void 0 ? _r$declarations : []), _toConsumableArray((_r$children = r.children) !== null && _r$children !== void 0 ? _r$children : []));
4660
+ children.sort(function (a, b) {
4661
+ return offsetOf(a) - offsetOf(b);
4662
+ });
4663
+ return rule(((_r$rawSelector = r.rawSelector) !== null && _r$rawSelector !== void 0 ? _r$rawSelector : '').trim(), convertAll(children, from), locOf(r, from));
4664
+ }
4665
+ case 'keyframe':
4666
+ {
4667
+ var k = node;
4668
+ return rule(k.selector, convertAll(k.declarations, from), locOf(k, from));
4669
+ }
4670
+ case 'atrule':
4671
+ {
4672
+ var _a$preludeText;
4673
+ var a = node;
4674
+ var params = ((_a$preludeText = a.preludeText) !== null && _a$preludeText !== void 0 ? _a$preludeText : '').trim();
4675
+ // A statement (`@import`, `@apply` before expansion has a block of its own only when
4676
+ // nested): no block means no braces in the output either.
4677
+ if (!a.block) return a.name === 'apply' ? atRule('apply', params, [], locOf(a, from)) : raw("@".concat(a.name).concat(params ? ' ' + params : '', ";"), locOf(a, from));
4678
+ return atRule(a.name, params, convertAll(a.block.children, from), locOf(a, from));
4679
+ }
4680
+ default:
4681
+ return null;
4682
+ }
4683
+ }
4684
+
4685
+ // ─── @apply ──────────────────────────────────────────────────────────────────
4686
+
4687
+ /**
4688
+ * Replaces each `@apply a b c` with what those utilities produce: flat declarations in place,
4689
+ * and a nested rule (`&` standing for the applying selector) for a utility that needs a
4690
+ * selector of its own (`hover:`, `group-hover:`, `space-x-*`, `md:`). Unknown classes are
4691
+ * skipped. `applied` collects the utilities used.
4692
+ */
4693
+ function applyUtilities(nodes, reg) {
4694
+ var applied = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
4695
+ var out = [];
4696
+ var _iterator2 = _createForOfIteratorHelper(nodes),
4697
+ _step2;
4698
+ try {
4699
+ var _loop = function _loop() {
4700
+ var node = _step2.value;
4701
+ if (node.kind === 'at-rule' && node.name === 'apply') {
4702
+ // What it expands to was written on the @apply line, as far as a source map can tell.
4703
+ out.push.apply(out, _toConsumableArray(expandOne(node.params, reg, applied).map(function (n) {
4704
+ return withLoc(n, node.loc);
4705
+ })));
4706
+ } else if (node.kind === 'rule' || node.kind === 'at-rule') {
4707
+ out.push(_objectSpread2(_objectSpread2({}, node), {}, {
4708
+ nodes: applyUtilities(node.nodes, reg, applied)
4709
+ }));
4710
+ } else {
4711
+ out.push(node);
4712
+ }
4713
+ };
4714
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
4715
+ _loop();
4716
+ }
4717
+ } catch (err) {
4718
+ _iterator2.e(err);
4719
+ } finally {
4720
+ _iterator2.f();
4721
+ }
4722
+ return out;
4723
+ }
4724
+ function expandOne(params, reg, applied) {
4725
+ var list = params.trim();
4726
+ // A trailing `!important` marks every inlined declaration (Tailwind semantics).
4727
+ var important = false;
4728
+ var bang = list.match(/!important\s*$/);
4729
+ if (bang) {
4730
+ important = true;
4731
+ list = list.slice(0, bang.index).trim();
4732
+ }
4733
+ var decls = [];
4734
+ var nested = [];
4735
+ var _iterator3 = _createForOfIteratorHelper(list.split(/\s+/)),
4736
+ _step3;
4737
+ try {
4738
+ var _loop2 = function _loop2() {
4739
+ var token = _step3.value;
4740
+ if (!token) return 0; // continue
4741
+ var atom = parseAtom(token, reg);
4742
+ if (!atom) return 0; // continue
4743
+ var compiled = compileAtom(atom, reg);
4744
+ if (!compiled || compiled.length === 0) return 0; // continue
4745
+ applied.add(token);
4746
+ if (important) markImportant(compiled);
4747
+ var own = '.' + escapeClass(atom.raw);
4748
+ // A plain utility, one rule on its own class with only declarations, inlines.
4749
+ var only = compiled[0];
4750
+ if (compiled.length === 1 && only.kind === 'rule' && only.selector === own && only.nodes.every(function (n) {
4751
+ return n.kind === 'declaration';
4752
+ })) {
4753
+ decls.push.apply(decls, _toConsumableArray(only.nodes.map(function (n) {
4754
+ return _objectSpread2({}, n);
4755
+ })));
4756
+ return 0; // continue
4757
+ }
4758
+ // Anything else keeps its structure, with the utility's class replaced by `&`.
4759
+ nested.push.apply(nested, _toConsumableArray(compiled.map(function (n) {
4760
+ return toNesting(n, own);
4761
+ })));
4762
+ },
4763
+ _ret;
4764
+ for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
4765
+ _ret = _loop2();
4766
+ if (_ret === 0) continue;
4767
+ }
4768
+ // Flat declarations first, then the nested rules: the order the author's line implies.
4769
+ } catch (err) {
4770
+ _iterator3.e(err);
4771
+ } finally {
4772
+ _iterator3.f();
4773
+ }
4774
+ return [].concat(decls, nested);
4775
+ }
4776
+ function withLoc(node, loc) {
4777
+ var _node$loc2;
4778
+ if (!loc) return node;
4779
+ if (node.kind === 'rule' || node.kind === 'at-rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4780
+ loc: (_node$loc2 = node.loc) !== null && _node$loc2 !== void 0 ? _node$loc2 : loc,
4781
+ nodes: node.nodes.map(function (n) {
4782
+ return withLoc(n, loc);
4783
+ })
4784
+ });
4785
+ return node.loc ? node : _objectSpread2(_objectSpread2({}, node), {}, {
4786
+ loc: loc
4586
4787
  });
4587
- reg.dynamicVariant('not', function (v) {
4588
- return notVariant(reg, v);
4788
+ }
4789
+ function toNesting(node, own) {
4790
+ if (node.kind === 'rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4791
+ selector: node.selector.split(own).join('&'),
4792
+ nodes: node.nodes.map(function (n) {
4793
+ return toNesting(n, own);
4794
+ })
4589
4795
  });
4590
- reg.dynamicVariant('supports', function (v) {
4591
- return named(v) ? {
4592
- atRule: {
4593
- name: 'supports',
4594
- params: "(".concat(named(v), ")")
4595
- }
4596
- } : null;
4796
+ if (node.kind === 'at-rule') return _objectSpread2(_objectSpread2({}, node), {}, {
4797
+ nodes: node.nodes.map(function (n) {
4798
+ return toNesting(n, own);
4799
+ })
4597
4800
  });
4801
+ return node;
4802
+ }
4803
+ function markImportant(nodes) {
4804
+ var _iterator4 = _createForOfIteratorHelper(nodes),
4805
+ _step4;
4806
+ try {
4807
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
4808
+ var n = _step4.value;
4809
+ if (n.kind === 'declaration') n.important = true;else if (n.kind === 'rule' || n.kind === 'at-rule') markImportant(n.nodes);
4810
+ }
4811
+ } catch (err) {
4812
+ _iterator4.e(err);
4813
+ } finally {
4814
+ _iterator4.f();
4815
+ }
4598
4816
  }
4599
4817
 
4600
- // The named breakpoints (`sm:`/`md:`/…) are static variants, so their media params
4601
- // bake the theme value at registration. A `@theme { --breakpoint-md: … }` override
4602
- // loaded later wouldn't reach them — so compile() re-runs this after loadTheme to
4603
- // pick up overrides. (The dynamic `min-*`/`max-*` already resolve at apply time.)
4604
- function registerBreakpointVariants(reg) {
4605
- for (var _i4 = 0, _arr = ['sm', 'md', 'lg', 'xl', '2xl']; _i4 < _arr.length; _i4++) {
4606
- var bp = _arr[_i4];
4607
- var min = reg.theme.get("--breakpoint-".concat(bp));
4608
- if (min) reg.variant(bp, {
4609
- atRule: {
4610
- name: 'media',
4611
- params: "(min-width: ".concat(min, ")")
4818
+ // ─── Nesting → plain selectors ───────────────────────────────────────────────
4819
+
4820
+ // At-rules whose body is more stylesheet: nesting is resolved through them. Everything else
4821
+ // (`@keyframes`, `@font-face`, `@property`, …) is left exactly as written.
4822
+ var GROUPING = new Set(['media', 'supports', 'container', 'layer', 'document', 'scope', 'starting-style']);
4823
+
4824
+ /** Splits a selector list on its top-level commas (not those inside `:is(…)`, `[…]` or quotes). */
4825
+ function splitSelectorList(selector) {
4826
+ var parts = [];
4827
+ var depth = 0;
4828
+ var quote = '';
4829
+ var start = 0;
4830
+ for (var i = 0; i < selector.length; i++) {
4831
+ var c = selector[i];
4832
+ if (quote) {
4833
+ if (c === '\\') i++;else if (c === quote) quote = '';
4834
+ } else if (c === '"' || c === "'") quote = c;else if (c === '\\') i++;else if (c === '(' || c === '[') depth++;else if (c === ')' || c === ']') depth--;else if (c === ',' && depth === 0) {
4835
+ parts.push(selector.slice(start, i).trim());
4836
+ start = i + 1;
4837
+ }
4838
+ }
4839
+ parts.push(selector.slice(start).trim());
4840
+ return parts.filter(Boolean);
4841
+ }
4842
+
4843
+ /** The selector a nested rule stands for, given its parent's: `&` replaced, or a descendant. */
4844
+ function resolveNested(child, parent) {
4845
+ var parents = splitSelectorList(parent);
4846
+ var out = [];
4847
+ var _iterator5 = _createForOfIteratorHelper(splitSelectorList(child)),
4848
+ _step5;
4849
+ try {
4850
+ for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
4851
+ var c = _step5.value;
4852
+ var _iterator6 = _createForOfIteratorHelper(parents),
4853
+ _step6;
4854
+ try {
4855
+ for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
4856
+ var p = _step6.value;
4857
+ out.push(c.includes('&') ? c.split('&').join(p) : "".concat(p, " ").concat(c));
4858
+ }
4859
+ } catch (err) {
4860
+ _iterator6.e(err);
4861
+ } finally {
4862
+ _iterator6.f();
4612
4863
  }
4613
- });
4864
+ }
4865
+ } catch (err) {
4866
+ _iterator5.e(err);
4867
+ } finally {
4868
+ _iterator5.f();
4614
4869
  }
4870
+ return out.join(', ');
4615
4871
  }
4616
- function mediaWidth(feature, value) {
4617
- return value ? {
4618
- atRule: {
4619
- name: 'media',
4620
- params: "(".concat(feature, ": ").concat(value, ")")
4872
+
4873
+ /**
4874
+ * Resolves CSS nesting into plain rules, keeping the cascade: a rule's declarations stay
4875
+ * together until a nested rule interrupts them, and the ones after it follow it. Grouping
4876
+ * at-rules nested in a rule wrap a rule on the parent's selector.
4877
+ */
4878
+ function flattenNesting(nodes) {
4879
+ var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
4880
+ var out = [];
4881
+ var _iterator7 = _createForOfIteratorHelper(nodes),
4882
+ _step7;
4883
+ try {
4884
+ for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
4885
+ var node = _step7.value;
4886
+ if (node.kind === 'rule') {
4887
+ var selector = parent === null ? node.selector : resolveNested(node.selector, parent);
4888
+ out.push.apply(out, _toConsumableArray(flattenRule(selector, node.nodes, node.loc)));
4889
+ } else if (node.kind === 'at-rule' && GROUPING.has(node.name)) {
4890
+ out.push(_objectSpread2(_objectSpread2({}, node), {}, {
4891
+ nodes: parent === null ? flattenNesting(node.nodes) : flattenRule(parent, node.nodes, node.loc)
4892
+ }));
4893
+ } else {
4894
+ out.push(node);
4895
+ }
4621
4896
  }
4622
- } : null;
4897
+ } catch (err) {
4898
+ _iterator7.e(err);
4899
+ } finally {
4900
+ _iterator7.f();
4901
+ }
4902
+ return out;
4623
4903
  }
4624
- var PSEUDO = {
4625
- hover: '&:hover',
4626
- focus: '&:focus',
4627
- 'focus-within': '&:focus-within',
4628
- 'focus-visible': '&:focus-visible',
4629
- active: '&:active',
4630
- visited: '&:visited',
4631
- target: '&:target',
4632
- disabled: '&:disabled',
4633
- enabled: '&:enabled',
4634
- checked: '&:checked',
4635
- indeterminate: '&:indeterminate',
4636
- "default": '&:default',
4637
- required: '&:required',
4638
- valid: '&:valid',
4639
- invalid: '&:invalid',
4640
- 'read-only': '&:read-only',
4641
- 'placeholder-shown': '&:placeholder-shown',
4642
- autofill: '&:autofill',
4643
- empty: '&:empty',
4644
- first: '&:first-child',
4645
- last: '&:last-child',
4646
- only: '&:only-child',
4647
- odd: '&:nth-child(odd)',
4648
- even: '&:nth-child(even)',
4649
- 'first-of-type': '&:first-of-type',
4650
- 'last-of-type': '&:last-of-type'
4651
- };
4652
- var PSEUDO_ELEMENT = {
4653
- before: '&::before',
4654
- after: '&::after',
4655
- placeholder: '&::placeholder',
4656
- selection: '&::selection',
4657
- marker: '&::marker',
4658
- file: '&::file-selector-button',
4659
- backdrop: '&::backdrop',
4660
- 'first-line': '&::first-line',
4661
- 'first-letter': '&::first-letter'
4662
- };
4663
- var MEDIA = {
4664
- dark: '(prefers-color-scheme: dark)',
4665
- 'motion-reduce': '(prefers-reduced-motion: reduce)',
4666
- 'motion-safe': '(prefers-reduced-motion: no-preference)',
4667
- 'contrast-more': '(prefers-contrast: more)',
4668
- 'contrast-less': '(prefers-contrast: less)',
4669
- portrait: '(orientation: portrait)',
4670
- landscape: '(orientation: landscape)',
4671
- print: 'print'
4672
- };
4673
- function named(v) {
4674
- return v ? v.value : null;
4904
+ function flattenRule(selector, children, loc) {
4905
+ var out = [];
4906
+ var pending = [];
4907
+ var flush = function flush() {
4908
+ if (pending.length) out.push(rule(selector, pending, loc));
4909
+ pending = [];
4910
+ };
4911
+ var _iterator8 = _createForOfIteratorHelper(children),
4912
+ _step8;
4913
+ try {
4914
+ for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
4915
+ var child = _step8.value;
4916
+ if (child.kind === 'declaration' || child.kind === 'raw') {
4917
+ pending.push(child);
4918
+ } else if (child.kind === 'rule') {
4919
+ flush();
4920
+ out.push.apply(out, _toConsumableArray(flattenRule(resolveNested(child.selector, selector), child.nodes, child.loc)));
4921
+ } else if (GROUPING.has(child.name)) {
4922
+ flush();
4923
+ out.push(_objectSpread2(_objectSpread2({}, child), {}, {
4924
+ nodes: flattenRule(selector, child.nodes, child.loc)
4925
+ }));
4926
+ } else {
4927
+ flush();
4928
+ out.push(child);
4929
+ }
4930
+ }
4931
+ } catch (err) {
4932
+ _iterator8.e(err);
4933
+ } finally {
4934
+ _iterator8.f();
4935
+ }
4936
+ flush();
4937
+ return out;
4675
4938
  }
4676
4939
 
4677
- // `group-hover` → `.group:hover &`; `group-[.foo]` → `.group.foo &`. A named value
4678
- // is a pseudo-class, an arbitrary one is a raw selector fragment. A `/name`
4679
- // modifier scopes to a named group/peer (`group-hover/item` → `.group\/item:hover`).
4680
- function relational(v, m, base, tail) {
4681
- var value = named(v);
4682
- if (!value) return null;
4683
- var cond = v.kind === 'arbitrary' ? value : ":".concat(value);
4684
- var scope = m ? "".concat(base, "\\/").concat(m.value) : base;
4940
+ // ─── The shared context ──────────────────────────────────────────────────────
4941
+
4942
+ /**
4943
+ * What every stylesheet of one project shares: the registry (theme, utilities, variants,
4944
+ * custom definitions) and the theme tokens the processed CSS refers to, so the global sheet
4945
+ * keeps them however they are reached. One per build, made by whoever orchestrates it.
4946
+ */
4947
+
4948
+ function createCssContext() {
4949
+ var _options$registry;
4950
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4951
+ var registry = (_options$registry = options.registry) !== null && _options$registry !== void 0 ? _options$registry : createRegistry();
4952
+ if (options.theme) {
4953
+ loadTheme(options.theme, registry.theme);
4954
+ registerBreakpointVariants(registry);
4955
+ loadDirectives(options.theme, registry);
4956
+ }
4685
4957
  return {
4686
- selector: "".concat(scope).concat(cond).concat(tail)
4958
+ registry: registry,
4959
+ usedTokens: new Set()
4687
4960
  };
4688
4961
  }
4689
4962
 
4690
- // `not-hover` → `&:not(:hover)`, `not-first` → `&:not(:first-child)`: resolve the
4691
- // inner variant's pseudo, so the selector is valid (not the literal name). Only
4692
- // simple pseudo variants compose; `not-[…]` takes an arbitrary selector.
4693
- function notVariant(reg, v) {
4694
- var _reg$getVariant;
4695
- var value = named(v);
4696
- if (!value) return null;
4697
- if (v.kind === 'arbitrary') return {
4698
- selector: "&:not(".concat(value, ")")
4963
+ // Directives that define the context; component CSS does not get to change it.
4964
+ var CONTEXT_DIRECTIVES = new Set(['theme', 'utility', 'custom-variant', 'source', 'fluixi']);
4965
+ /**
4966
+ * Processes one stylesheet in a shared context, exactly as the project's own CSS would be:
4967
+ * `@apply` expanded with the context's utilities, theme values resolved, nesting flattened.
4968
+ * It never emits the utility layer or the theme tokens; the tokens it refers to are recorded
4969
+ * in `ctx.usedTokens` for the global sheet to keep.
4970
+ */
4971
+ function processCss(input, ctx) {
4972
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
4973
+ var parsed = typeof input === 'string' ? parseStyle(input, options.from) : input;
4974
+ var ignored = [];
4975
+ var references = [];
4976
+ var kept = parsed.filter(function (n) {
4977
+ var reference = n.kind === 'raw' ? n.text.match(/^@reference\s+(["'])(.+)\1\s*;$/) : null;
4978
+ if (reference) {
4979
+ references.push(reference[2]);
4980
+ return false;
4981
+ }
4982
+ if (n.kind === 'at-rule' && CONTEXT_DIRECTIVES.has(n.name)) {
4983
+ ignored.push(n.name);
4984
+ return false;
4985
+ }
4986
+ return true;
4987
+ });
4988
+ var applied = new Set();
4989
+ var ast = applyUtilities(kept, ctx.registry, applied);
4990
+ if (options.flatten !== false) ast = flattenNesting(ast);
4991
+ collectVarRefs(ast, ctx.usedTokens);
4992
+ return {
4993
+ ast: ast,
4994
+ css: stringify(ast, {
4995
+ minify: options.minify
4996
+ }),
4997
+ applied: _toConsumableArray(applied),
4998
+ ignored: ignored,
4999
+ references: references
4699
5000
  };
4700
- var frag = (_reg$getVariant = reg.getVariant(value)) === null || _reg$getVariant === void 0 || (_reg$getVariant = _reg$getVariant.selector) === null || _reg$getVariant === void 0 ? void 0 : _reg$getVariant.replace(/^&/, '').trim();
4701
- return frag && frag.startsWith(':') ? {
4702
- selector: "&:not(".concat(frag, ")")
4703
- } : null;
4704
5001
  }
4705
5002
 
4706
- // The batteries-included registry: the default token theme plus the utility
4707
- // families and variants. Projects extend it (`@utility`, `@theme`, JS config) or
4708
- // build a bare `new Registry(theme)` and register their own.
4709
- function createRegistry() {
4710
- var reg = new Registry(defaultTheme());
4711
- registerUtilities(reg);
4712
- registerVariants(reg);
4713
- return reg;
5003
+ // `@apply a b c;` in author CSS that `transform` passes through: the slice is parsed, the
5004
+ // `@apply` at-rules are expanded on the AST (`style.ts`), and the result is printed again.
5005
+ // A slice without `@apply` is returned as written.
5006
+ function expandApply(css, reg) {
5007
+ if (!css.includes('@apply')) return css;
5008
+ return stringify(applyUtilities(parseStyle(css), reg)).trimEnd();
5009
+ }
5010
+
5011
+ // Renders a `transform()` result as a compact, colourised build line for the
5012
+ // Vite/PostCSS plugins to print. Pure (returns a string) so css-core stays
5013
+ // side-effect free — the plugins own the actual `console.log`.
5014
+
5015
+ var ANSI = {
5016
+ reset: '\x1b[0m',
5017
+ dim: '\x1b[2m',
5018
+ bold: '\x1b[1m',
5019
+ cyan: '\x1b[36m',
5020
+ green: '\x1b[32m',
5021
+ yellow: '\x1b[33m',
5022
+ red: '\x1b[31m'
5023
+ };
5024
+ function paint(code, s, color) {
5025
+ return color ? code + s + ANSI.reset : s;
5026
+ }
5027
+ function humanBytes(n) {
5028
+ return n < 1024 ? "".concat(n, " B") : "".concat((n / 1024).toFixed(1), " kB");
5029
+ }
5030
+ function humanMs(ms) {
5031
+ return ms < 1 ? "".concat(ms * 1000 | 0, " \xB5s") : ms < 1000 ? "".concat(ms.toFixed(1), " ms") : "".concat((ms / 1000).toFixed(2), " s");
5032
+ }
5033
+
5034
+ // Green under 10 ms, yellow under 50 ms, red beyond — a quick "is it fast?" cue.
5035
+ function timeColor(ms) {
5036
+ return ms < 10 ? ANSI.green : ms < 50 ? ANSI.yellow : ANSI.red;
5037
+ }
5038
+ function formatBuildLog(label, stats) {
5039
+ var _options$color;
5040
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5041
+ var color = (_options$color = options.color) !== null && _options$color !== void 0 ? _options$color : true;
5042
+ var head = paint(ANSI.cyan + ANSI.bold, '◆ fluixi', color);
5043
+ var name = paint(ANSI.bold, label, color);
5044
+ var time = paint(timeColor(stats.ms), humanMs(stats.ms), color);
5045
+ var parts = ["".concat(stats.utilities, " ").concat(stats.utilities === 1 ? 'utility' : 'utilities'), "".concat(stats.scanned, " scanned"), humanBytes(stats.bytes)];
5046
+ if (stats.sources) parts.push("".concat(stats.sources, " ").concat(stats.sources === 1 ? 'source' : 'sources'));
5047
+ var detail = paint(ANSI.dim, parts.join(' · '), color);
5048
+ return "".concat(head, " ").concat(name, " ").concat(time, "\n ").concat(detail);
4714
5049
  }
4715
5050
 
4716
5051
  // Pulls atom class strings out of arbitrary source (HTML, JSX, template
@@ -4908,6 +5243,9 @@ function scanSourceFiles(files) {
4908
5243
  return _toConsumableArray(found);
4909
5244
  }
4910
5245
 
5246
+ /** The cascade layer the bridge is emitted in: fluixi-ui's tokens layer, below its skins. */
5247
+ var UI_TOKENS_LAYER = 'flx.tokens';
5248
+
4911
5249
  // Bridges a fluixi-css theme to the `--flx-ui-*` custom properties the Fluixi UI
4912
5250
  // components read (`@fluixi-ui/tokens`). Each bridge emits `--flx-ui-x: var(--src)`
4913
5251
  // so a fluixi-css theme *drives* the UI — change the theme, the components follow —
@@ -5223,12 +5561,18 @@ function transform(input) {
5223
5561
  var used = collectVarRefs(rules);
5224
5562
  if (uiBlocks) collectVarRefs(uiBlocks, used);
5225
5563
  collectVarRefs(authorNodes, used); // keep tokens the author CSS references by hand / via @apply
5226
- var tokens = emitTheme(reg.theme, ':root', used);
5564
+ var tokens = emitTheme(reg.theme, ':root', options.keepAllTokens ? undefined : used);
5227
5565
  if (tokens.nodes.length) generated.push(tokens);
5228
5566
  }
5229
- if (uiBlocks) generated.push.apply(generated, _toConsumableArray(uiBlocks.filter(function (b) {
5230
- return b.nodes.length;
5231
- })));
5567
+ // In the tokens layer, where fluixi-ui's own defaults live: later in the cascade than those, so
5568
+ // the theme still drives them, and below `flx.skin`, so a skin's tokens win. Unlayered, the
5569
+ // bridge beat every layer and a skin's radii, sizes and shadows never applied.
5570
+ if (uiBlocks) {
5571
+ var blocks = uiBlocks.filter(function (b) {
5572
+ return b.nodes.length;
5573
+ });
5574
+ if (blocks.length) generated.push(atRule('layer', UI_TOKENS_LAYER, blocks));
5575
+ }
5232
5576
  generated.push.apply(generated, rules);
5233
5577
  var nodes = markerAt >= 0 ? [].concat(_toConsumableArray(authorNodes.slice(0, markerAt)), generated, _toConsumableArray(authorNodes.slice(markerAt))) : [].concat(authorNodes, generated);
5234
5578
  var resetFrom = (_options$resetFrom = options.resetFrom) !== null && _options$resetFrom !== void 0 ? _options$resetFrom : 'fluixi:reset.css';
@@ -5396,9 +5740,15 @@ function compile(input) {
5396
5740
  var tokens = emitTheme(reg.theme, ':root', used);
5397
5741
  if (tokens.nodes.length) nodes.push(tokens);
5398
5742
  }
5399
- if (uiBlocks) nodes.push.apply(nodes, _toConsumableArray(uiBlocks.filter(function (b) {
5400
- return b.nodes.length;
5401
- })));
5743
+ // In the tokens layer, where fluixi-ui's own defaults live: later in the cascade than those, so
5744
+ // the theme still drives them, and below `flx.skin`, so a skin's tokens win. Unlayered, the
5745
+ // bridge beat every layer and a skin's radii, sizes and shadows never applied.
5746
+ if (uiBlocks) {
5747
+ var blocks = uiBlocks.filter(function (b) {
5748
+ return b.nodes.length;
5749
+ });
5750
+ if (blocks.length) nodes.push(atRule('layer', UI_TOKENS_LAYER, blocks));
5751
+ }
5402
5752
  nodes.push.apply(nodes, rules);
5403
5753
  return {
5404
5754
  css: stringify(nodes, {
@@ -5410,5 +5760,5 @@ function compile(input) {
5410
5760
  };
5411
5761
  }
5412
5762
 
5413
- export { Registry, SPECIAL_COLORS, Theme, atRule, collectVarRefs, colorValue, compile, compileAtom, compileClasses, createRegistry, decl, decodeUnderscores, defaultTheme, emitTheme, emitUiTheme, escapeClass, expandApply, formatBuildLog, keywords, loadDirectives, loadTheme, parseAtom, parseSources, parseVariant, props, raw, registerBreakpointVariants, registerUtilities, registerVariants, resolveSourceFiles, rule, scanAtoms, scanSourceFiles, sizeValue, splitAtTopLevel, statics, stringify, stringifyWithMap, transform, uiSemanticLayer, uiTokenBridges };
5763
+ export { Registry, SPECIAL_COLORS, Theme, UI_TOKENS_LAYER, applyUtilities, atRule, collectVarRefs, colorValue, compile, compileAtom, compileClasses, createCssContext, createRegistry, decl, decodeUnderscores, defaultTheme, emitTheme, emitUiTheme, escapeClass, expandApply, flattenNesting, formatBuildLog, keywords, loadDirectives, loadTheme, parseAtom, parseSources, parseStyle, parseVariant, processCss, props, raw, registerBreakpointVariants, registerUtilities, registerVariants, resolveNested, resolveSourceFiles, rule, scanAtoms, scanSourceFiles, sizeValue, splitAtTopLevel, splitSelectorList, statics, stringify, stringifyWithMap, transform, uiSemanticLayer, uiTokenBridges };
5414
5764
  //# sourceMappingURL=index.mjs.map