@tenphi/tasty 0.0.0-snapshot.9155dd5 → 0.0.0-snapshot.92cfaf9
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.
- package/README.md +208 -248
- package/dist/chunks/definitions.d.ts +1 -1
- package/dist/chunks/definitions.js +1 -1
- package/dist/chunks/definitions.js.map +1 -1
- package/dist/config.d.ts +45 -2
- package/dist/config.js +63 -23
- package/dist/config.js.map +1 -1
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +4 -4
- package/dist/counter-style/index.js +51 -0
- package/dist/counter-style/index.js.map +1 -0
- package/dist/debug.d.ts +26 -141
- package/dist/debug.js +356 -635
- package/dist/debug.js.map +1 -1
- package/dist/font-face/index.js +63 -0
- package/dist/font-face/index.js.map +1 -0
- package/dist/hooks/resolve-ssr-collector.js +15 -0
- package/dist/hooks/resolve-ssr-collector.js.map +1 -0
- package/dist/hooks/useCounterStyle.d.ts +50 -0
- package/dist/hooks/useCounterStyle.js +47 -0
- package/dist/hooks/useCounterStyle.js.map +1 -0
- package/dist/hooks/useFontFace.d.ts +43 -0
- package/dist/hooks/useFontFace.js +71 -0
- package/dist/hooks/useFontFace.js.map +1 -0
- package/dist/hooks/useGlobalStyles.js +1 -5
- package/dist/hooks/useGlobalStyles.js.map +1 -1
- package/dist/hooks/useKeyframes.js +1 -5
- package/dist/hooks/useKeyframes.js.map +1 -1
- package/dist/hooks/useProperty.js +1 -5
- package/dist/hooks/useProperty.js.map +1 -1
- package/dist/hooks/useRawCSS.js +1 -5
- package/dist/hooks/useRawCSS.js.map +1 -1
- package/dist/hooks/useStyles.js +35 -46
- package/dist/hooks/useStyles.js.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.js +6 -4
- package/dist/injector/index.d.ts +20 -2
- package/dist/injector/index.js +19 -1
- package/dist/injector/index.js.map +1 -1
- package/dist/injector/injector.d.ts +19 -1
- package/dist/injector/injector.js +35 -0
- package/dist/injector/injector.js.map +1 -1
- package/dist/injector/sheet-manager.js +7 -2
- package/dist/injector/sheet-manager.js.map +1 -1
- package/dist/injector/types.d.ts +61 -1
- package/dist/parser/classify.js +3 -3
- package/dist/parser/classify.js.map +1 -1
- package/dist/parser/const.js +17 -1
- package/dist/parser/const.js.map +1 -1
- package/dist/pipeline/index.d.ts +2 -0
- package/dist/pipeline/index.js +56 -17
- package/dist/pipeline/index.js.map +1 -1
- package/dist/pipeline/materialize.js +0 -1
- package/dist/pipeline/materialize.js.map +1 -1
- package/dist/properties/index.js.map +1 -1
- package/dist/ssr/collector.d.ts +17 -0
- package/dist/ssr/collector.js +50 -6
- package/dist/ssr/collector.js.map +1 -1
- package/dist/ssr/format-rules.js +7 -4
- package/dist/ssr/format-rules.js.map +1 -1
- package/dist/ssr/index.js +1 -1
- package/dist/states/index.js +2 -0
- package/dist/states/index.js.map +1 -1
- package/dist/styles/border.js +2 -2
- package/dist/styles/border.js.map +1 -1
- package/dist/styles/predefined.js +1 -1
- package/dist/styles/predefined.js.map +1 -1
- package/dist/styles/preset.d.ts +5 -0
- package/dist/styles/preset.js +48 -47
- package/dist/styles/preset.js.map +1 -1
- package/dist/styles/types.d.ts +46 -7
- package/dist/tasty.d.ts +30 -892
- package/dist/tasty.js +20 -7
- package/dist/tasty.js.map +1 -1
- package/dist/utils/color-math.d.ts +2 -1
- package/dist/utils/color-math.js +40 -8
- package/dist/utils/color-math.js.map +1 -1
- package/dist/utils/color-space.js +78 -35
- package/dist/utils/color-space.js.map +1 -1
- package/dist/utils/mod-attrs.js +1 -1
- package/dist/utils/mod-attrs.js.map +1 -1
- package/dist/utils/process-tokens.js +1 -1
- package/dist/utils/process-tokens.js.map +1 -1
- package/dist/utils/styles.d.ts +1 -3
- package/dist/utils/styles.js +4 -6
- package/dist/utils/styles.js.map +1 -1
- package/dist/utils/typography.js +8 -0
- package/dist/utils/typography.js.map +1 -1
- package/dist/zero/babel.d.ts +14 -2
- package/dist/zero/babel.js +52 -24
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/extractor.js +53 -1
- package/dist/zero/extractor.js.map +1 -1
- package/docs/PIPELINE.md +1 -1
- package/docs/README.md +31 -0
- package/docs/adoption.md +16 -6
- package/docs/comparison.md +16 -9
- package/docs/configuration.md +65 -2
- package/docs/debug.md +152 -339
- package/docs/design-system.md +26 -3
- package/docs/dsl.md +136 -3
- package/docs/getting-started.md +29 -13
- package/docs/injector.md +2 -2
- package/docs/methodology.md +71 -5
- package/docs/runtime.md +228 -34
- package/docs/ssr.md +5 -3
- package/docs/styles.md +28 -23
- package/docs/tasty-static.md +15 -2
- package/package.json +3 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"materialize.js","names":[],"sources":["../../src/pipeline/materialize.ts"],"sourcesContent":["/**\n * CSS Materialization\n *\n * Converts condition trees into CSS selectors and at-rules.\n * This is the final stage that produces actual CSS output.\n */\n\nimport { Lru } from '../parser/lru';\n\nimport type {\n ConditionNode,\n ContainerCondition,\n MediaCondition,\n ModifierCondition,\n PseudoCondition,\n StateCondition,\n SupportsCondition,\n} from './conditions';\nimport { getConditionUniqueId } from './conditions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed media condition for structured analysis and combination\n */\nexport interface ParsedMediaCondition {\n /** Subtype for structured analysis */\n subtype: 'dimension' | 'feature' | 'type';\n /** Whether this is a negated condition */\n negated: boolean;\n /** The condition part for CSS output (e.g., \"(width < 600px)\", \"print\") */\n condition: string;\n /** For dimension queries: dimension name */\n dimension?: 'width' | 'height' | 'inline-size' | 'block-size';\n /** For dimension queries: lower bound value */\n lowerBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n };\n /** For dimension queries: upper bound value */\n upperBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n };\n /** For feature queries: feature name */\n feature?: string;\n /** For feature queries: feature value */\n featureValue?: string;\n /** For type queries: media type */\n mediaType?: 'print' | 'screen' | 'all' | 'speech';\n}\n\n/**\n * Parsed container condition for structured analysis and combination\n */\nexport interface ParsedContainerCondition {\n /** Container name (undefined = unnamed/nearest container) */\n name?: string;\n /** The condition part (e.g., \"(width < 600px)\" or \"style(--variant: danger)\") */\n condition: string;\n /** Whether this is a negated condition */\n negated: boolean;\n /** Subtype for structured analysis */\n subtype: 'dimension' | 'style' | 'raw';\n /** For style queries: property name (without --) */\n property?: string;\n /** For style queries: property value (undefined = existence check) */\n propertyValue?: string;\n}\n\n/**\n * Parsed supports condition for structured analysis and combination\n */\nexport interface ParsedSupportsCondition {\n /** Subtype: 'feature' for property support, 'selector' for selector() support */\n subtype: 'feature' | 'selector';\n /** The condition string (e.g., \"display: grid\" or \":has(*)\") */\n condition: string;\n /** Whether this is a negated condition */\n negated: boolean;\n}\n\n/**\n * Parsed modifier condition for structured analysis\n */\nexport interface ParsedModifierCondition {\n /** Attribute name (e.g., 'data-hovered', 'data-size') */\n attribute: string;\n /** Value if present (e.g., 'large', 'danger') */\n value?: string;\n /** Operator for value matching (default '=') */\n operator?: '=' | '^=' | '$=' | '*=';\n /** Whether this is negated (:not(...)) */\n negated: boolean;\n}\n\n/**\n * Parsed pseudo-class condition for structured analysis\n */\nexport interface ParsedPseudoCondition {\n /** The pseudo-class (e.g., ':hover', ':focus-visible', ':has(> Icon)') */\n pseudo: string;\n /** Whether this is negated (:not(...)) */\n negated: boolean;\n}\n\n/** Modifier or pseudo condition (shared across own/root/parent) */\ntype ParsedSelectorCondition = ParsedModifierCondition | ParsedPseudoCondition;\n\n/**\n * A group of selector conditions that produces an :is() or :not() wrapper.\n *\n * Each branch is an AND conjunction of conditions (one selector fragment).\n * Multiple branches are OR'd together inside the :is()/:not() wrapper.\n *\n * Example: size=small | size=medium\n * branches: [[size=small], [size=medium]]\n * renders: :is([data-size=\"small\"], [data-size=\"medium\"])\n *\n * When negated, :is() becomes :not():\n * :not([data-size=\"small\"], [data-size=\"medium\"])\n *\n * Single-branch groups are unwrapped (no :is() wrapper):\n * branches: [[size=small]]\n * renders: [data-size=\"small\"]\n */\nexport interface SelectorGroup {\n branches: ParsedSelectorCondition[][];\n negated: boolean;\n}\n\n/**\n * A group of parent conditions originating from a single @parent() call.\n * Each group produces its own :is()/:not() wrapper in the final CSS.\n * Separate @parent() calls = separate groups = can match different ancestors.\n *\n * Extends SelectorGroup with a `direct` flag for ancestor combinator:\n * direct = false → ` *` (any ancestor)\n * direct = true → ` > *` (direct parent only)\n *\n * Example: @parent(hovered & pressed | active)\n * branches: [[hovered, pressed], [active]]\n * renders: :is([data-hovered][data-pressed] *, [data-active] *)\n */\nexport interface ParentGroup extends SelectorGroup {\n direct: boolean;\n}\n\n/**\n * A single selector variant (one term in a DNF expression)\n */\nexport interface SelectorVariant {\n /** Structured modifier conditions (flat AND) */\n modifierConditions: ParsedModifierCondition[];\n\n /** Structured pseudo conditions (flat AND) */\n pseudoConditions: ParsedPseudoCondition[];\n\n /** Selector groups — :is()/:not() wrappers for OR branches on the element */\n selectorGroups: SelectorGroup[];\n\n /** Own groups — :is()/:not() wrappers for @own() OR branches on sub-elements */\n ownGroups: SelectorGroup[];\n\n /** Parsed media conditions for structured combination */\n mediaConditions: ParsedMediaCondition[];\n\n /** Parsed container conditions for structured combination */\n containerConditions: ParsedContainerCondition[];\n\n /** Parsed supports conditions for @supports at-rules */\n supportsConditions: ParsedSupportsCondition[];\n\n /** Root groups — :is()/:not() wrappers for @root() OR branches */\n rootGroups: SelectorGroup[];\n\n /** Parent condition groups — each @parent() call is a separate group */\n parentGroups: ParentGroup[];\n\n /** Whether to wrap in @starting-style */\n startingStyle: boolean;\n}\n\n/**\n * CSS output components extracted from a condition\n * Supports multiple variants for OR conditions (DNF form)\n */\nexport interface CSSComponents {\n /** Selector variants - OR means multiple variants, AND means single variant with combined selectors */\n variants: SelectorVariant[];\n\n /** Whether condition is impossible (should skip) */\n isImpossible: boolean;\n}\n\n/**\n * Final CSS rule output\n */\nexport interface CSSRule {\n /** Single selector or array of selector fragments (for OR conditions) */\n selector: string | string[];\n declarations: string;\n atRules?: string[];\n rootPrefix?: string;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst conditionCache = new Lru<string, CSSComponents>(3000);\n\n// ============================================================================\n// Main Functions\n// ============================================================================\n\n/**\n * Convert a condition tree to CSS components\n */\nexport function conditionToCSS(node: ConditionNode): CSSComponents {\n // Check cache\n const key = getConditionUniqueId(node);\n const cached = conditionCache.get(key);\n if (cached) {\n return cached;\n }\n\n const result = conditionToCSSInner(node);\n\n // Cache result\n conditionCache.set(key, result);\n\n return result;\n}\n\n/**\n * Clear the condition cache (for testing)\n */\nexport function clearConditionCache(): void {\n conditionCache.clear();\n}\n\n// ============================================================================\n// Inner Implementation\n// ============================================================================\n\nfunction emptyVariant(): SelectorVariant {\n return {\n modifierConditions: [],\n pseudoConditions: [],\n selectorGroups: [],\n ownGroups: [],\n mediaConditions: [],\n containerConditions: [],\n supportsConditions: [],\n rootGroups: [],\n parentGroups: [],\n startingStyle: false,\n };\n}\n\nfunction conditionToCSSInner(node: ConditionNode): CSSComponents {\n // Base case: TRUE condition - single empty variant (matches everything)\n if (node.kind === 'true') {\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n }\n\n // Base case: FALSE condition - no variants (matches nothing)\n if (node.kind === 'false') {\n return {\n variants: [],\n isImpossible: true,\n };\n }\n\n // State condition\n if (node.kind === 'state') {\n return stateToCSS(node);\n }\n\n // Compound condition\n if (node.kind === 'compound') {\n if (node.operator === 'AND') {\n return andToCSS(node.children);\n } else {\n return orToCSS(node.children);\n }\n }\n\n // Fallback - single empty variant\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n}\n\n/**\n * Convert a state condition to CSS\n */\nfunction stateToCSS(state: StateCondition): CSSComponents {\n switch (state.type) {\n case 'media': {\n const mediaResults = mediaToParsed(state);\n const variants = mediaResults.map((mediaCond) => {\n const v = emptyVariant();\n v.mediaConditions.push(mediaCond);\n return v;\n });\n return { variants, isImpossible: false };\n }\n\n case 'root':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'rootGroups',\n );\n\n case 'parent':\n return parentConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n state.direct,\n );\n\n case 'own':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'ownGroups',\n );\n\n case 'modifier': {\n const v = emptyVariant();\n v.modifierConditions.push(modifierToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'pseudo': {\n const v = emptyVariant();\n v.pseudoConditions.push(pseudoToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'container': {\n const v = emptyVariant();\n v.containerConditions.push(containerToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'supports': {\n const v = emptyVariant();\n v.supportsConditions.push(supportsToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'starting': {\n const v = emptyVariant();\n v.startingStyle = !state.negated;\n return { variants: [v], isImpossible: false };\n }\n }\n}\n\n/**\n * Convert modifier condition to parsed structure\n */\nfunction modifierToParsed(state: ModifierCondition): ParsedModifierCondition {\n return {\n attribute: state.attribute,\n value: state.value,\n operator: state.operator,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed modifier to CSS selector string (for final output)\n */\nexport function modifierToCSS(mod: ParsedModifierCondition): string {\n let selector: string;\n\n if (mod.value !== undefined) {\n // Value attribute: [data-attr=\"value\"]\n const op = mod.operator || '=';\n selector = `[${mod.attribute}${op}\"${mod.value}\"]`;\n } else {\n // Boolean attribute: [data-attr]\n selector = `[${mod.attribute}]`;\n }\n\n if (mod.negated) {\n return `:not(${selector})`;\n }\n return selector;\n}\n\n/**\n * Convert pseudo condition to parsed structure\n */\nfunction pseudoToParsed(state: PseudoCondition): ParsedPseudoCondition {\n return {\n pseudo: state.pseudo,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed pseudo to CSS selector string (for final output).\n *\n * :not() is normalized to negated :is() at parse time, so pseudo.pseudo\n * never starts with ':not(' here. When negated:\n * - :is(X) → :not(X) (unwrap :is)\n * - :where(X) → :not(X) (unwrap :where)\n * - :has(X) → :not(:has(X))\n * - other → :not(other)\n *\n * When not negated, single-argument :is()/:where() is unwrapped when the\n * inner content is a simple compound selector that can safely append to\n * the base selector (this happens after double-negation of :not()).\n */\nexport function pseudoToCSS(pseudo: ParsedPseudoCondition): string {\n const p = pseudo.pseudo;\n\n if (pseudo.negated) {\n if (p.startsWith(':is(') || p.startsWith(':where(')) {\n return `:not(${p.slice(p.indexOf('(') + 1, -1)})`;\n }\n return `:not(${p})`;\n }\n\n if ((p.startsWith(':is(') || p.startsWith(':where(')) && !p.includes(',')) {\n const inner = p.slice(p.indexOf('(') + 1, -1);\n const ch = inner[0];\n\n // Only unwrap when the inner content is a simple compound selector:\n // must start with a compoundable character and contain no whitespace\n // (whitespace implies combinators like `>`, `+`, `~`, or descendant).\n if (\n (ch === ':' || ch === '.' || ch === '[' || ch === '#') &&\n !/\\s/.test(inner)\n ) {\n return inner;\n }\n }\n\n return p;\n}\n\n/**\n * Convert media condition to parsed structure(s)\n * Returns an array because negated ranges produce OR branches (two separate conditions)\n */\nfunction mediaToParsed(state: MediaCondition): ParsedMediaCondition[] {\n if (state.subtype === 'type') {\n // @media:print → @media print (or @media not print)\n const mediaType = state.mediaType || 'all';\n return [\n {\n subtype: 'type',\n negated: state.negated ?? false,\n condition: mediaType,\n mediaType: state.mediaType,\n },\n ];\n } else if (state.subtype === 'feature') {\n // @media(prefers-contrast: high) → @media (prefers-contrast: high)\n let condition: string;\n if (state.featureValue) {\n condition = `(${state.feature}: ${state.featureValue})`;\n } else {\n condition = `(${state.feature})`;\n }\n return [\n {\n subtype: 'feature',\n negated: state.negated ?? false,\n condition,\n feature: state.feature,\n featureValue: state.featureValue,\n },\n ];\n } else {\n // Dimension query - negation is handled by inverting the condition\n // because \"not (width < x)\" doesn't work reliably in browsers\n return dimensionToMediaParsed(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n state.negated ?? false,\n );\n }\n}\n\n/**\n * Convert dimension bounds to parsed media condition(s)\n * Uses CSS Media Queries Level 4 `not (condition)` syntax for negation.\n */\nfunction dimensionToMediaParsed(\n dimension: 'width' | 'height' | 'inline-size' | 'block-size',\n lowerBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n upperBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n negated?: boolean,\n): ParsedMediaCondition[] {\n // Build the condition string\n let condition: string;\n if (lowerBound && upperBound) {\n const lowerOp = lowerBound.inclusive ? '<=' : '<';\n const upperOp = upperBound.inclusive ? '<=' : '<';\n condition = `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;\n } else if (upperBound) {\n const op = upperBound.inclusive ? '<=' : '<';\n condition = `(${dimension} ${op} ${upperBound.value})`;\n } else if (lowerBound) {\n const op = lowerBound.inclusive ? '>=' : '>';\n condition = `(${dimension} ${op} ${lowerBound.value})`;\n } else {\n condition = `(${dimension})`;\n }\n\n // For negation, we use CSS `not (condition)` syntax in buildAtRulesFromVariant\n return [\n {\n subtype: 'dimension',\n negated: negated ?? false,\n condition,\n dimension,\n lowerBound,\n upperBound,\n },\n ];\n}\n\n/**\n * Convert container condition to parsed structure\n * This enables structured analysis for contradiction detection and condition combining\n */\nfunction containerToParsed(\n state: ContainerCondition,\n): ParsedContainerCondition {\n let condition: string;\n\n if (state.subtype === 'style') {\n // Style query: style(--prop: value)\n if (state.propertyValue) {\n condition = `style(--${state.property}: ${state.propertyValue})`;\n } else {\n condition = `style(--${state.property})`;\n }\n } else if (state.subtype === 'raw') {\n // Raw function query: passed through verbatim (e.g., scroll-state(stuck: top))\n condition = state.rawCondition!;\n } else {\n // Dimension query\n condition = dimensionToContainerCondition(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n );\n }\n\n return {\n name: state.containerName,\n condition,\n negated: state.negated ?? false,\n subtype: state.subtype,\n property: state.property,\n propertyValue: state.propertyValue,\n };\n}\n\n/**\n * Convert dimension bounds to container query condition (single string)\n * Container queries support \"not (condition)\", so no need to invert manually\n */\nfunction dimensionToContainerCondition(\n dimension: string,\n lowerBound?: { value: string; inclusive: boolean },\n upperBound?: { value: string; inclusive: boolean },\n): string {\n if (lowerBound && upperBound) {\n const lowerOp = lowerBound.inclusive ? '<=' : '<';\n const upperOp = upperBound.inclusive ? '<=' : '<';\n return `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;\n } else if (upperBound) {\n const op = upperBound.inclusive ? '<=' : '<';\n return `(${dimension} ${op} ${upperBound.value})`;\n } else if (lowerBound) {\n const op = lowerBound.inclusive ? '>=' : '>';\n return `(${dimension} ${op} ${lowerBound.value})`;\n }\n return '(width)'; // Fallback\n}\n\n/**\n * Convert supports condition to parsed structure\n */\nfunction supportsToParsed(state: SupportsCondition): ParsedSupportsCondition {\n return {\n subtype: state.subtype,\n condition: state.condition,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Collect all modifier and pseudo conditions from a variant as a flat array.\n */\nfunction collectSelectorConditions(\n variant: SelectorVariant,\n): ParsedSelectorCondition[] {\n return [...variant.modifierConditions, ...variant.pseudoConditions];\n}\n\n/**\n * Convert an inner condition tree into a single SelectorVariant with\n * one SelectorGroup whose branches represent the inner OR alternatives.\n * Shared by @root() and @own().\n *\n * Both positive and negated cases produce one variant with one group.\n * Negation simply sets the `negated` flag, which swaps :is() for :not()\n * in the final CSS output — no De Morgan transformation is needed.\n *\n * This mirrors parentConditionToVariants: OR branches are kept inside\n * a single group and rendered as comma-separated arguments in\n * :is()/:not(), e.g. :root:is([a], [b]) or [el]:not([a], [b]).\n */\nfunction innerConditionToVariants(\n innerCondition: ConditionNode,\n negated: boolean,\n target: 'rootGroups' | 'ownGroups',\n): CSSComponents {\n const innerCSS = conditionToCSS(innerCondition);\n\n if (innerCSS.isImpossible || innerCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n const branches: ParsedSelectorCondition[][] = [];\n\n for (const innerVariant of innerCSS.variants) {\n const conditions = collectSelectorConditions(innerVariant);\n\n if (conditions.length > 0) {\n branches.push(conditions);\n }\n }\n\n if (branches.length === 0) {\n return { variants: [emptyVariant()], isImpossible: false };\n }\n\n const v = emptyVariant();\n v[target].push({ branches, negated });\n\n return { variants: [v], isImpossible: false };\n}\n\n/**\n * Convert a @parent() inner condition into a single SelectorVariant with\n * one ParentGroup whose branches represent the inner OR alternatives.\n *\n * Both positive and negated cases produce one variant with one group.\n * Negation simply sets the `negated` flag, which swaps :is() for :not()\n * in the final CSS output — no structural transformation is needed.\n */\nfunction parentConditionToVariants(\n innerCondition: ConditionNode,\n negated: boolean,\n direct: boolean,\n): CSSComponents {\n const innerCSS = conditionToCSS(innerCondition);\n\n if (innerCSS.isImpossible || innerCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n const branches: ParsedSelectorCondition[][] = [];\n\n for (const innerVariant of innerCSS.variants) {\n const conditions = collectSelectorConditions(innerVariant);\n\n if (conditions.length > 0) {\n branches.push(conditions);\n }\n }\n\n if (branches.length === 0) {\n return { variants: [emptyVariant()], isImpossible: false };\n }\n\n const v = emptyVariant();\n v.parentGroups.push({ branches, direct, negated });\n\n return { variants: [v], isImpossible: false };\n}\n\n/**\n * Sort key for canonical condition output within selectors.\n *\n * Priority order:\n * 0: Boolean attribute selectors ([data-hovered])\n * 1: Value attribute selectors ([data-size=\"small\"])\n * 2: Negated boolean attributes (:not([data-disabled]))\n * 3: Negated value attributes (:not([data-size=\"small\"]))\n * 4: Pseudo-classes (:hover, :focus)\n * 5: Negated pseudo-classes (:not(:disabled))\n *\n * Secondary sort: alphabetical by attribute name / pseudo string.\n */\nfunction conditionSortKey(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n const hasValue = cond.value !== undefined ? 1 : 0;\n const neg = cond.negated ? 2 : 0;\n return `${neg + hasValue}|${cond.attribute}|${cond.value ?? ''}`;\n }\n const priority = cond.negated ? 5 : 4;\n return `${priority}|${cond.pseudo}`;\n}\n\nfunction sortConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n return conditions.toSorted((a, b) =>\n conditionSortKey(a).localeCompare(conditionSortKey(b)),\n );\n}\n\nexport function branchToCSS(branch: ParsedSelectorCondition[]): string {\n let parts = '';\n for (const cond of sortConditions(branch)) {\n parts += selectorConditionToCSS(cond);\n }\n return parts;\n}\n\n/**\n * Wrap serialized selector arguments in :is() or :not().\n * Arguments are sorted for canonical output.\n */\nfunction wrapInIsOrNot(args: string[], negated: boolean): string {\n const wrapper = negated ? ':not' : ':is';\n return `${wrapper}(${args.sort().join(', ')})`;\n}\n\n/**\n * Convert a selector group to a CSS selector fragment.\n *\n * Single-branch groups are unwrapped (no :is() wrapper).\n * Multi-branch groups use :is() or :not().\n * Negation swaps :is() for :not().\n */\nexport function selectorGroupToCSS(group: SelectorGroup): string {\n if (group.branches.length === 0) return '';\n\n // Single branch: emit directly without :is() wrapper\n if (group.branches.length === 1) {\n const parts = branchToCSS(group.branches[0]);\n if (group.negated) {\n return `:not(${parts})`;\n }\n return parts;\n }\n\n return wrapInIsOrNot(group.branches.map(branchToCSS), group.negated);\n}\n\n// ============================================================================\n// Modifier Subsumption (shared by optimizeGroups and dedupeSelectorConditions)\n// ============================================================================\n\ninterface SubsumptionFacts {\n negatedBooleanAttrs: Set<string>;\n positiveExactValuesByAttr: Map<string, Set<string>>;\n}\n\n/**\n * Collect facts about modifier conditions for subsumption analysis.\n * Tracks negated boolean attrs (:not([attr])) and positive exact values ([attr=\"X\"]).\n */\nfunction collectSubsumptionFacts(\n modifiers: Iterable<ParsedModifierCondition>,\n): SubsumptionFacts {\n const negatedBooleanAttrs = new Set<string>();\n const positiveExactValuesByAttr = new Map<string, Set<string>>();\n\n for (const mod of modifiers) {\n if (mod.negated && mod.value === undefined) {\n negatedBooleanAttrs.add(mod.attribute);\n }\n if (\n !mod.negated &&\n mod.value !== undefined &&\n (mod.operator ?? '=') === '='\n ) {\n let vals = positiveExactValuesByAttr.get(mod.attribute);\n if (!vals) {\n vals = new Set();\n positiveExactValuesByAttr.set(mod.attribute, vals);\n }\n vals.add(mod.value);\n }\n }\n\n return { negatedBooleanAttrs, positiveExactValuesByAttr };\n}\n\n/**\n * Check if a negated-value modifier is subsumed by stronger facts:\n * - :not([attr]) subsumes :not([attr=\"val\"])\n * - [attr=\"X\"] implies :not([attr=\"Y\"]) is redundant (single exact value)\n *\n * Only applies to exact-match (=) operators; substring operators don't\n * imply exclusivity between values.\n */\nfunction isSubsumedNegatedModifier(\n mod: ParsedModifierCondition,\n facts: SubsumptionFacts,\n): boolean {\n if (!mod.negated || mod.value === undefined) return false;\n\n if (facts.negatedBooleanAttrs.has(mod.attribute)) return true;\n\n if ((mod.operator ?? '=') === '=') {\n const posVals = facts.positiveExactValuesByAttr.get(mod.attribute);\n if (posVals && posVals.size === 1 && !posVals.has(mod.value)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Remove redundant single-condition groups that are subsumed by stronger\n * groups on the same attribute. O(n) — only inspects single-branch,\n * single-condition groups.\n */\nexport function optimizeGroups(groups: SelectorGroup[]): SelectorGroup[] {\n if (groups.length <= 1) return groups;\n\n // Exact dedup by key\n const seen = new Set<string>();\n const result: SelectorGroup[] = [];\n for (const g of groups) {\n const key = getSelectorGroupKey(g);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(g);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Extract modifier conditions from simple groups for subsumption analysis\n const effectiveModifiers: ParsedModifierCondition[] = [];\n for (const g of result) {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) continue;\n const cond = g.branches[0][0];\n if (!('attribute' in cond)) continue;\n // Map group-level negation onto the condition for fact collection\n effectiveModifiers.push({\n ...cond,\n negated: g.negated !== cond.negated,\n });\n }\n\n const facts = collectSubsumptionFacts(effectiveModifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((g) => {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) return true;\n const cond = g.branches[0][0];\n if (\n !('attribute' in cond) ||\n !g.negated ||\n cond.negated ||\n cond.value === undefined\n ) {\n return true;\n }\n return !isSubsumedNegatedModifier({ ...cond, negated: true }, facts);\n });\n}\n\n/**\n * Convert root groups to CSS selector prefix (for final output)\n */\nexport function rootGroupsToCSS(groups: SelectorGroup[]): string | undefined {\n if (groups.length === 0) return undefined;\n\n const optimized = optimizeGroups(groups);\n if (optimized.length === 0) return undefined;\n\n let prefix = ':root';\n for (const group of optimized) {\n prefix += selectorGroupToCSS(group);\n }\n return prefix;\n}\n\n/**\n * Convert parent groups to CSS selector fragments (for final output).\n * Each group produces its own :is()/:not() wrapper with a combinator\n * suffix (` *` or ` > *`) appended to each branch.\n */\nexport function parentGroupsToCSS(groups: ParentGroup[]): string {\n let result = '';\n for (const group of groups) {\n const combinator = group.direct ? ' > *' : ' *';\n const args = group.branches.map(\n (branch) => branchToCSS(branch) + combinator,\n );\n result += wrapInIsOrNot(args, group.negated);\n }\n return result;\n}\n\n/**\n * Convert a modifier or pseudo condition to a CSS selector fragment\n */\nexport function selectorConditionToCSS(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n return modifierToCSS(cond);\n }\n return pseudoToCSS(cond);\n}\n\n/**\n * Get unique key for a modifier condition\n */\nfunction getModifierKey(mod: ParsedModifierCondition): string {\n const base = mod.value\n ? `${mod.attribute}${mod.operator || '='}${mod.value}`\n : mod.attribute;\n return mod.negated ? `!${base}` : base;\n}\n\n/**\n * Get unique key for a pseudo condition\n */\nfunction getPseudoKey(pseudo: ParsedPseudoCondition): string {\n return pseudo.negated ? `!${pseudo.pseudo}` : pseudo.pseudo;\n}\n\n/**\n * Get unique key for any selector condition (modifier or pseudo)\n */\nfunction getSelectorConditionKey(cond: ParsedSelectorCondition): string {\n return 'attribute' in cond\n ? `mod:${getModifierKey(cond)}`\n : `pseudo:${getPseudoKey(cond)}`;\n}\n\n/**\n * Deduplicate selector conditions (modifiers or pseudos).\n * Shared by root, parent, and own conditions.\n */\nfunction dedupeSelectorConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n // Pass 1: exact-key dedup\n const seen = new Set<string>();\n const result: ParsedSelectorCondition[] = [];\n for (const c of conditions) {\n const key = getSelectorConditionKey(c);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(c);\n }\n }\n\n // Pass 2: remove negated value modifiers subsumed by other modifiers\n const modifiers = result.filter(\n (c): c is ParsedModifierCondition => 'attribute' in c,\n );\n const facts = collectSubsumptionFacts(modifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((c) => {\n if (!('attribute' in c)) return true;\n return !isSubsumedNegatedModifier(c, facts);\n });\n}\n\n/**\n * Check for modifier contradiction: same attribute with opposite negation\n */\nfunction hasModifierContradiction(\n conditions: ParsedModifierCondition[],\n): boolean {\n const byKey = new Map<string, boolean>(); // base key -> isPositive\n\n for (const mod of conditions) {\n const baseKey = mod.value\n ? `${mod.attribute}${mod.operator || '='}${mod.value}`\n : mod.attribute;\n const existing = byKey.get(baseKey);\n if (existing !== undefined && existing !== !mod.negated) {\n return true; // Same attribute with opposite negation\n }\n byKey.set(baseKey, !mod.negated);\n }\n return false;\n}\n\n/**\n * Check for pseudo contradiction: same pseudo with opposite negation\n */\nfunction hasPseudoContradiction(conditions: ParsedPseudoCondition[]): boolean {\n const byKey = new Map<string, boolean>(); // pseudo -> isPositive\n\n for (const pseudo of conditions) {\n const existing = byKey.get(pseudo.pseudo);\n if (existing !== undefined && existing !== !pseudo.negated) {\n return true; // Same pseudo with opposite negation\n }\n byKey.set(pseudo.pseudo, !pseudo.negated);\n }\n return false;\n}\n\n/**\n * Check for selector condition contradiction (modifier or pseudo with opposite negation).\n * Shared by root, parent, and own conditions.\n */\nfunction hasSelectorConditionContradiction(\n conditions: ParsedSelectorCondition[],\n): boolean {\n const modifiers: ParsedModifierCondition[] = [];\n const pseudos: ParsedPseudoCondition[] = [];\n\n for (const c of conditions) {\n if ('attribute' in c) {\n modifiers.push(c);\n } else {\n pseudos.push(c);\n }\n }\n\n return hasModifierContradiction(modifiers) || hasPseudoContradiction(pseudos);\n}\n\n/**\n * Check for parent group contradiction: same target (direct + conditions)\n * with opposite negation. E.g. :not([data-hovered] *) and :is([data-hovered] *)\n * in the same variant is impossible.\n */\nfunction getBranchesKey(branches: ParsedSelectorCondition[][]): string {\n if (branches.length === 1) {\n const b = branches[0];\n if (b.length === 1) return getSelectorConditionKey(b[0]);\n return b.map(getSelectorConditionKey).sort().join('+');\n }\n return branches\n .map((b) => b.map(getSelectorConditionKey).sort().join('+'))\n .sort()\n .join(',');\n}\n\nfunction hasParentGroupContradiction(groups: ParentGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = `${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Check for selector group contradiction: same branches with opposite negation.\n * E.g. :is([data-a]) and :not([data-a]) in the same variant is impossible.\n */\nfunction hasSelectorGroupContradiction(groups: SelectorGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = getBranchesKey(g.branches);\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Merge two selector variants (AND operation)\n * Deduplicates conditions and checks for contradictions\n */\nfunction mergeVariants(\n a: SelectorVariant,\n b: SelectorVariant,\n): SelectorVariant | null {\n // Merge media conditions and check for contradictions\n const mergedMedia = dedupeMediaConditions([\n ...a.mediaConditions,\n ...b.mediaConditions,\n ]);\n if (hasMediaContradiction(mergedMedia)) {\n return null; // Impossible variant\n }\n\n // Concatenate root groups, optimize, and check for contradictions\n const mergedRootGroups = optimizeGroups([...a.rootGroups, ...b.rootGroups]);\n if (hasSelectorGroupContradiction(mergedRootGroups)) {\n return null; // Impossible variant\n }\n\n // Merge modifier and pseudo conditions separately, then cross-check\n const mergedModifiers = dedupeSelectorConditions([\n ...a.modifierConditions,\n ...b.modifierConditions,\n ]) as ParsedModifierCondition[];\n const mergedPseudos = dedupeSelectorConditions([\n ...a.pseudoConditions,\n ...b.pseudoConditions,\n ]) as ParsedPseudoCondition[];\n if (\n hasSelectorConditionContradiction([...mergedModifiers, ...mergedPseudos])\n ) {\n return null; // Impossible variant\n }\n\n // Concatenate selector groups, optimize, and check for contradictions\n const mergedSelectorGroups = optimizeGroups([\n ...a.selectorGroups,\n ...b.selectorGroups,\n ]);\n if (hasSelectorGroupContradiction(mergedSelectorGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate parent groups (each group is an independent :is() wrapper)\n const mergedParentGroups = [...a.parentGroups, ...b.parentGroups];\n if (hasParentGroupContradiction(mergedParentGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate own groups, optimize, and check for contradictions\n const mergedOwnGroups = optimizeGroups([...a.ownGroups, ...b.ownGroups]);\n if (hasSelectorGroupContradiction(mergedOwnGroups)) {\n return null; // Impossible variant\n }\n\n // Merge container conditions and check for contradictions\n const mergedContainers = dedupeContainerConditions([\n ...a.containerConditions,\n ...b.containerConditions,\n ]);\n if (hasContainerStyleContradiction(mergedContainers)) {\n return null; // Impossible variant\n }\n\n // Merge supports conditions and check for contradictions\n const mergedSupports = dedupeSupportsConditions([\n ...a.supportsConditions,\n ...b.supportsConditions,\n ]);\n if (hasSupportsContradiction(mergedSupports)) {\n return null; // Impossible variant\n }\n\n return {\n modifierConditions: mergedModifiers,\n pseudoConditions: mergedPseudos,\n selectorGroups: mergedSelectorGroups,\n ownGroups: mergedOwnGroups,\n mediaConditions: mergedMedia,\n containerConditions: mergedContainers,\n supportsConditions: mergedSupports,\n rootGroups: mergedRootGroups,\n parentGroups: mergedParentGroups,\n startingStyle: a.startingStyle || b.startingStyle,\n };\n}\n\n/**\n * Generic deduplication by a key extraction function.\n * Preserves insertion order, keeping the first occurrence of each key.\n */\nfunction dedupeByKey<T>(items: T[], getKey: (item: T) => string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const item of items) {\n const key = getKey(item);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(item);\n }\n }\n return result;\n}\n\nfunction dedupeMediaConditions(\n conditions: ParsedMediaCondition[],\n): ParsedMediaCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction dedupeContainerConditions(\n conditions: ParsedContainerCondition[],\n): ParsedContainerCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction dedupeSupportsConditions(\n conditions: ParsedSupportsCondition[],\n): ParsedSupportsCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\n/**\n * Check if supports conditions contain contradictions\n * e.g., @supports(display: grid) AND NOT @supports(display: grid)\n */\nfunction hasSupportsContradiction(\n conditions: ParsedSupportsCondition[],\n): boolean {\n const conditionMap = new Map<string, boolean>(); // key -> isPositive\n\n for (const cond of conditions) {\n const key = `${cond.subtype}|${cond.condition}`;\n const existing = conditionMap.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n conditionMap.set(key, !cond.negated);\n }\n\n return false;\n}\n\n/**\n * Check if a set of media conditions contains contradictions\n * e.g., (prefers-color-scheme: light) AND NOT (prefers-color-scheme: light)\n * or (width >= 900px) AND (width < 600px)\n *\n * Uses parsed media conditions for efficient analysis without regex parsing.\n */\nfunction hasMediaContradiction(conditions: ParsedMediaCondition[]): boolean {\n // Track conditions by their key (condition string) to detect A and NOT A\n const featureConditions = new Map<string, boolean>(); // key -> isPositive\n const typeConditions = new Map<string, boolean>(); // mediaType -> isPositive\n const dimensionConditions = new Map<string, boolean>(); // condition -> isPositive\n\n // Track dimension conditions for range contradiction detection (non-negated only)\n const dimensionsByDim = new Map<\n string,\n { lowerBound: number | null; upperBound: number | null }\n >();\n\n for (const cond of conditions) {\n if (cond.subtype === 'type') {\n // Type query: check for direct contradiction (print AND NOT print)\n const key = cond.mediaType || 'all';\n const existing = typeConditions.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n typeConditions.set(key, !cond.negated);\n } else if (cond.subtype === 'feature') {\n // Feature query: check for direct contradiction\n const key = cond.condition;\n const existing = featureConditions.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n featureConditions.set(key, !cond.negated);\n } else if (cond.subtype === 'dimension') {\n // First, check for direct contradiction: (width < 600px) AND NOT (width < 600px)\n const condKey = cond.condition;\n const existing = dimensionConditions.get(condKey);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n dimensionConditions.set(condKey, !cond.negated);\n\n // For range analysis, only consider non-negated conditions\n // Negated conditions are handled via the direct contradiction check above\n if (!cond.negated) {\n const dim = cond.dimension || 'width';\n let bounds = dimensionsByDim.get(dim);\n if (!bounds) {\n bounds = { lowerBound: null, upperBound: null };\n dimensionsByDim.set(dim, bounds);\n }\n\n // Track the effective bounds\n if (cond.lowerBound?.valueNumeric != null) {\n const value = cond.lowerBound.valueNumeric;\n if (bounds.lowerBound === null || value > bounds.lowerBound) {\n bounds.lowerBound = value;\n }\n }\n if (cond.upperBound?.valueNumeric != null) {\n const value = cond.upperBound.valueNumeric;\n if (bounds.upperBound === null || value < bounds.upperBound) {\n bounds.upperBound = value;\n }\n }\n\n // Check for impossible range\n if (\n bounds.lowerBound !== null &&\n bounds.upperBound !== null &&\n bounds.lowerBound >= bounds.upperBound\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\n/**\n * Check if container conditions contain contradictions in style queries\n * e.g., style(--variant: danger) and style(--variant: success) together\n * Same property with different values = always false\n *\n * Uses parsed container conditions for efficient analysis without regex parsing.\n */\nfunction hasContainerStyleContradiction(\n conditions: ParsedContainerCondition[],\n): boolean {\n // Track style queries by property name\n // key: property name, value: { hasExistence: boolean, values: Set<string>, hasNegatedExistence: boolean }\n const styleQueries = new Map<\n string,\n { hasExistence: boolean; values: Set<string>; hasNegatedExistence: boolean }\n >();\n\n for (const cond of conditions) {\n // Only analyze style queries\n if (cond.subtype !== 'style' || !cond.property) {\n continue;\n }\n\n const property = cond.property;\n const value = cond.propertyValue;\n\n if (!styleQueries.has(property)) {\n styleQueries.set(property, {\n hasExistence: false,\n values: new Set(),\n hasNegatedExistence: false,\n });\n }\n\n const entry = styleQueries.get(property)!;\n\n if (cond.negated) {\n if (value === undefined) {\n // not style(--prop) - negated existence check\n entry.hasNegatedExistence = true;\n }\n // Negated value checks don't contradict positive value checks directly\n // They just mean \"not this value\"\n } else {\n if (value === undefined) {\n // style(--prop) - existence check\n entry.hasExistence = true;\n } else {\n // style(--prop: value) - value check\n entry.values.add(value);\n }\n }\n }\n\n // Check for contradictions\n for (const [, entry] of styleQueries) {\n // Contradiction: existence check + negated existence check\n if (entry.hasExistence && entry.hasNegatedExistence) {\n return true;\n }\n\n // Contradiction: multiple different values for same property\n // style(--variant: danger) AND style(--variant: success) is impossible\n if (entry.values.size > 1) {\n return true;\n }\n\n // Contradiction: negated existence + value check\n // not style(--variant) AND style(--variant: danger) is impossible\n if (entry.hasNegatedExistence && entry.values.size > 0) {\n return true;\n }\n }\n\n return false;\n}\n\nconst variantKeyCache = new WeakMap<SelectorVariant, string>();\n\n/**\n * Get a unique key for a variant (for deduplication).\n * Cached via WeakMap since variants are compared multiple times during\n * deduplication and sorting.\n */\nfunction getSelectorGroupKey(g: SelectorGroup): string {\n return `${g.negated ? '!' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Get a context key for a variant — everything except flat modifier/pseudo\n * conditions. Variants with the same context key can be merged into an\n * :is() group. Also used by getVariantKey as the shared non-selector portion.\n */\nfunction getVariantContextKey(v: SelectorVariant): string {\n const mediaKey = v.mediaConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const containerKey = v.containerConditions\n .map((c) => `${c.name ?? ''}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const supportsKey = v.supportsConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const rootKey = v.rootGroups.map(getSelectorGroupKey).sort().join('|');\n const parentKey = v.parentGroups.map(getParentGroupKey).sort().join('|');\n const ownKey = v.ownGroups.map(getSelectorGroupKey).sort().join('|');\n const selectorGroupKey = v.selectorGroups\n .map(getSelectorGroupKey)\n .sort()\n .join('|');\n\n return [\n mediaKey,\n containerKey,\n supportsKey,\n rootKey,\n parentKey,\n ownKey,\n selectorGroupKey,\n v.startingStyle ? '1' : '0',\n ].join('###');\n}\n\nfunction getVariantKey(v: SelectorVariant): string {\n const cached = variantKeyCache.get(v);\n if (cached !== undefined) return cached;\n const modifierKey = v.modifierConditions.map(getModifierKey).sort().join('|');\n const pseudoKey = v.pseudoConditions.map(getPseudoKey).sort().join('|');\n const key = modifierKey + '###' + pseudoKey + '###' + getVariantContextKey(v);\n variantKeyCache.set(v, key);\n return key;\n}\n\n/**\n * Total number of leaf conditions in a variant (for superset / dedup comparisons).\n */\nfunction groupConditionCount(\n groups: readonly { branches: ParsedSelectorCondition[][] }[],\n): number {\n return groups.reduce(\n (sum, g) => sum + g.branches.reduce((s, b) => s + b.length, 0),\n 0,\n );\n}\n\nfunction variantConditionCount(v: SelectorVariant): number {\n return (\n v.modifierConditions.length +\n v.pseudoConditions.length +\n groupConditionCount(v.selectorGroups) +\n groupConditionCount(v.ownGroups) +\n v.mediaConditions.length +\n v.containerConditions.length +\n v.supportsConditions.length +\n groupConditionCount(v.rootGroups) +\n groupConditionCount(v.parentGroups)\n );\n}\n\n/**\n * Check if variant A is a superset of variant B (A is more restrictive)\n *\n * If A has all of B's conditions plus more, then A is redundant\n * because B already covers the same cases (and more).\n *\n * Example:\n * A: :not([size=large]):not([size=medium]):not([size=small])\n * B: :not([size=large])\n * A is a superset of B, so A is redundant when B exists.\n */\nfunction isVariantSuperset(a: SelectorVariant, b: SelectorVariant): boolean {\n // Must have same context\n if (a.startingStyle !== b.startingStyle) return false;\n\n // Check if a.rootGroups is superset of b.rootGroups\n if (!isSelectorGroupsSuperset(a.rootGroups, b.rootGroups)) return false;\n\n // Check if a.mediaConditions is superset of b.mediaConditions\n if (!isMediaConditionsSuperset(a.mediaConditions, b.mediaConditions))\n return false;\n\n // Check if a.containerConditions is superset of b.containerConditions\n if (\n !isContainerConditionsSuperset(a.containerConditions, b.containerConditions)\n )\n return false;\n\n // Check if a.supportsConditions is superset of b.supportsConditions\n if (!isSupportsConditionsSuperset(a.supportsConditions, b.supportsConditions))\n return false;\n\n // Check if a.modifierConditions is superset of b.modifierConditions\n if (!isModifierConditionsSuperset(a.modifierConditions, b.modifierConditions))\n return false;\n\n // Check if a.pseudoConditions is superset of b.pseudoConditions\n if (!isPseudoConditionsSuperset(a.pseudoConditions, b.pseudoConditions))\n return false;\n\n // Check if a.selectorGroups is superset of b.selectorGroups\n if (!isSelectorGroupsSuperset(a.selectorGroups, b.selectorGroups))\n return false;\n\n // Check if a.ownGroups is superset of b.ownGroups\n if (!isSelectorGroupsSuperset(a.ownGroups, b.ownGroups)) return false;\n\n // Check if a.parentGroups is superset of b.parentGroups\n if (!isParentGroupsSuperset(a.parentGroups, b.parentGroups)) return false;\n\n return variantConditionCount(a) > variantConditionCount(b);\n}\n\n/**\n * Generic superset check: true if every item in B has a matching key in A.\n */\nfunction isConditionsSuperset<T>(\n a: T[],\n b: T[],\n getKey: (item: T) => string,\n): boolean {\n const aKeys = new Set(a.map(getKey));\n return b.every((c) => aKeys.has(getKey(c)));\n}\n\nfunction isMediaConditionsSuperset(\n a: ParsedMediaCondition[],\n b: ParsedMediaCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isContainerConditionsSuperset(\n a: ParsedContainerCondition[],\n b: ParsedContainerCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isSupportsConditionsSuperset(\n a: ParsedSupportsCondition[],\n b: ParsedSupportsCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isModifierConditionsSuperset(\n a: ParsedModifierCondition[],\n b: ParsedModifierCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getModifierKey);\n}\n\nfunction isPseudoConditionsSuperset(\n a: ParsedPseudoCondition[],\n b: ParsedPseudoCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getPseudoKey);\n}\n\nfunction isSelectorGroupsSuperset(\n a: SelectorGroup[],\n b: SelectorGroup[],\n): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getSelectorGroupKey);\n}\n\n/**\n * Check if parent groups A is a superset of B.\n * Each group in B must have a matching group in A.\n */\nfunction isParentGroupsSuperset(a: ParentGroup[], b: ParentGroup[]): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getParentGroupKey);\n}\n\nfunction getParentGroupKey(g: ParentGroup): string {\n return `${g.negated ? '!' : ''}${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Deduplicate variants\n *\n * Removes:\n * 1. Exact duplicates (same key)\n * 2. Superset variants (more restrictive selectors that are redundant)\n */\nfunction dedupeVariants(variants: SelectorVariant[]): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // First pass: exact deduplication\n const seen = new Set<string>();\n const result: SelectorVariant[] = [];\n\n for (const v of variants) {\n const key = getVariantKey(v);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(v);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Second pass: remove supersets (more restrictive variants)\n // Sort by total condition count (fewer conditions = less restrictive = keep)\n result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));\n\n // Remove variants that are supersets of earlier (less restrictive) variants\n const filtered: SelectorVariant[] = [];\n for (const candidate of result) {\n let isRedundant = false;\n for (const kept of filtered) {\n if (isVariantSuperset(candidate, kept)) {\n isRedundant = true;\n break;\n }\n }\n if (!isRedundant) {\n filtered.push(candidate);\n }\n }\n\n return filtered;\n}\n\n/**\n * Combine AND conditions into CSS\n *\n * AND of conditions means cartesian product of variants:\n * (A1 | A2) & (B1 | B2) = A1&B1 | A1&B2 | A2&B1 | A2&B2\n *\n * Variants that result in contradictions (e.g., conflicting media rules)\n * are filtered out.\n */\nfunction andToCSS(children: ConditionNode[]): CSSComponents {\n // Start with a single empty variant\n let currentVariants: SelectorVariant[] = [emptyVariant()];\n\n for (const child of children) {\n const childCSS = conditionToCSSInner(child);\n\n if (childCSS.isImpossible || childCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Cartesian product: each current variant × each child variant\n const newVariants: SelectorVariant[] = [];\n for (const current of currentVariants) {\n for (const childVariant of childCSS.variants) {\n const merged = mergeVariants(current, childVariant);\n // Skip impossible variants (contradictions detected during merge)\n if (merged !== null) {\n newVariants.push(merged);\n }\n }\n }\n\n if (newVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Deduplicate after each step to prevent exponential blowup\n currentVariants = dedupeVariants(newVariants);\n }\n\n return {\n variants: currentVariants,\n isImpossible: false,\n };\n}\n\n/**\n * Combine OR conditions into CSS\n *\n * OR in CSS means multiple selector variants (DNF).\n * After deduplication, variants that differ only in their base\n * modifier/pseudo conditions are merged into :is() groups.\n *\n * Note: OR exclusivity is handled at the pipeline level (expandOrConditions),\n * so here we just collect all variants. Any remaining ORs in the condition\n * tree (e.g., from De Morgan expansion) are handled as simple alternatives.\n */\nfunction orToCSS(children: ConditionNode[]): CSSComponents {\n const allVariants: SelectorVariant[] = [];\n\n for (const child of children) {\n const childCSS = conditionToCSSInner(child);\n if (childCSS.isImpossible) continue;\n\n allVariants.push(...childCSS.variants);\n }\n\n if (allVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n return {\n variants: dedupeVariants(allVariants),\n isImpossible: false,\n };\n}\n\n// ============================================================================\n// OR → :is() Merging\n// ============================================================================\n\n/**\n * Find keys present in ALL condition arrays.\n */\nfunction findCommonKeys<T>(\n conditionSets: T[][],\n getKey: (item: T) => string,\n): Set<string> {\n if (conditionSets.length === 0) return new Set();\n\n const common = new Set(conditionSets[0].map(getKey));\n for (let i = 1; i < conditionSets.length; i++) {\n const keys = new Set(conditionSets[i].map(getKey));\n for (const key of common) {\n if (!keys.has(key)) common.delete(key);\n }\n }\n return common;\n}\n\n/**\n * Merge OR variants that share the same \"context\" (at-rules, root, parent,\n * own, starting) into a single variant with a SelectorGroup.\n *\n * Variants with no modifier/pseudo conditions are kept separate (they match\n * unconditionally and can't be expressed inside :is()).\n */\nexport function mergeVariantsIntoSelectorGroups(\n variants: SelectorVariant[],\n): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // Group variants by their context (everything except flat modifier/pseudo)\n const groups = new Map<string, SelectorVariant[]>();\n for (const v of variants) {\n const key = getVariantContextKey(v);\n const group = groups.get(key);\n if (group) group.push(v);\n else groups.set(key, [v]);\n }\n\n const result: SelectorVariant[] = [];\n for (const group of groups.values()) {\n if (group.length === 1) {\n result.push(group[0]);\n continue;\n }\n\n // Separate variants with no selector conditions (can't merge into :is())\n const withSelectors: SelectorVariant[] = [];\n const withoutSelectors: SelectorVariant[] = [];\n for (const v of group) {\n if (\n v.modifierConditions.length === 0 &&\n v.pseudoConditions.length === 0\n ) {\n withoutSelectors.push(v);\n } else {\n withSelectors.push(v);\n }\n }\n\n result.push(...withoutSelectors);\n\n if (withSelectors.length <= 1) {\n result.push(...withSelectors);\n continue;\n }\n\n // Factor out common conditions and create a SelectorGroup\n result.push(factorAndGroup(withSelectors));\n }\n\n return result;\n}\n\n/**\n * Factor common modifier/pseudo conditions out of variants and create\n * a single variant with a SelectorGroup for the remaining (differing)\n * conditions.\n *\n * Precondition: all variants must share the same context key (identical\n * at-rules, root/parent/own/selector groups, startingStyle).\n */\nfunction factorAndGroup(variants: SelectorVariant[]): SelectorVariant {\n if (process.env.NODE_ENV !== 'production') {\n const key0 = getVariantContextKey(variants[0]);\n for (let i = 1; i < variants.length; i++) {\n const keyI = getVariantContextKey(variants[i]);\n if (keyI !== key0) {\n throw new Error(\n `factorAndGroup: context key mismatch at index ${i}.\\n` +\n ` expected: ${key0}\\n got: ${keyI}`,\n );\n }\n }\n }\n\n // Find common modifier and pseudo keys across ALL variants\n const commonModKeys = findCommonKeys(\n variants.map((v) => v.modifierConditions),\n getModifierKey,\n );\n const commonPseudoKeys = findCommonKeys(\n variants.map((v) => v.pseudoConditions),\n getPseudoKey,\n );\n\n // Extract common conditions from first variant\n const commonModifiers = variants[0].modifierConditions.filter((m) =>\n commonModKeys.has(getModifierKey(m)),\n );\n const commonPseudos = variants[0].pseudoConditions.filter((p) =>\n commonPseudoKeys.has(getPseudoKey(p)),\n );\n\n // Build branches from remaining (non-common) conditions.\n // If any variant has only common conditions (empty branch), it matches\n // unconditionally within this context — the :is() group would lose it.\n // In that case, return the broadest variant (common conditions only).\n const branches: ParsedSelectorCondition[][] = [];\n let hasEmptyBranch = false;\n for (const v of variants) {\n const branch: ParsedSelectorCondition[] = [];\n for (const mod of v.modifierConditions) {\n if (!commonModKeys.has(getModifierKey(mod))) branch.push(mod);\n }\n for (const pseudo of v.pseudoConditions) {\n if (!commonPseudoKeys.has(getPseudoKey(pseudo))) branch.push(pseudo);\n }\n if (branch.length > 0) {\n branches.push(branch);\n } else {\n hasEmptyBranch = true;\n }\n }\n\n // If a variant has only common conditions, it's the broadest match —\n // the :is() group with specific branches is subsumed by it.\n // Return the variant with common conditions only.\n if (hasEmptyBranch) {\n return {\n ...variants[0],\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n };\n }\n\n return {\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n selectorGroups: [\n ...variants[0].selectorGroups,\n { branches, negated: false },\n ],\n ownGroups: [...variants[0].ownGroups],\n mediaConditions: [...variants[0].mediaConditions],\n containerConditions: [...variants[0].containerConditions],\n supportsConditions: [...variants[0].supportsConditions],\n rootGroups: [...variants[0].rootGroups],\n parentGroups: [...variants[0].parentGroups],\n startingStyle: variants[0].startingStyle,\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Build at-rules array from a variant\n */\nexport function buildAtRulesFromVariant(variant: SelectorVariant): string[] {\n const atRules: string[] = [];\n\n // Add media rules - combine all conditions with \"and\"\n if (variant.mediaConditions.length > 0) {\n const conditionParts = variant.mediaConditions.map((c) => {\n if (c.subtype === 'type') {\n // Media type: print, screen, etc.\n return c.negated ? `not ${c.condition}` : c.condition;\n } else {\n // Feature or dimension: use not (condition) syntax for negation\n // MQ Level 4 requires parentheses around the condition for negation\n return c.negated ? `(not ${c.condition})` : c.condition;\n }\n });\n atRules.push(`@media ${conditionParts.join(' and ')}`);\n }\n\n // Add container rules - group by container name and combine with \"and\"\n if (variant.containerConditions.length > 0) {\n // Group conditions by container name (undefined = unnamed/nearest)\n const byName = new Map<string | undefined, ParsedContainerCondition[]>();\n for (const cond of variant.containerConditions) {\n const group = byName.get(cond.name) || [];\n group.push(cond);\n byName.set(cond.name, group);\n }\n\n // Build one @container rule per container name\n for (const [name, conditions] of byName) {\n // CSS Container Query syntax requires parentheses around negated conditions:\n // @container (not style(--x)) and style(--y) - NOT @container not style(--x) and style(--y)\n const conditionParts = conditions.map((c) =>\n c.negated ? `(not ${c.condition})` : c.condition,\n );\n const namePrefix = name ? `${name} ` : '';\n atRules.push(`@container ${namePrefix}${conditionParts.join(' and ')}`);\n }\n }\n\n // Add supports rules - combine all conditions with \"and\"\n if (variant.supportsConditions.length > 0) {\n const conditionParts = variant.supportsConditions.map((c) => {\n // Build the condition based on subtype\n // feature: (display: grid) or (not (display: grid))\n // selector: selector(:has(*)) or (not selector(:has(*)))\n if (c.subtype === 'selector') {\n const selectorCond = `selector(${c.condition})`;\n return c.negated ? `(not ${selectorCond})` : selectorCond;\n } else {\n const featureCond = `(${c.condition})`;\n return c.negated ? `(not ${featureCond})` : featureCond;\n }\n });\n atRules.push(`@supports ${conditionParts.join(' and ')}`);\n }\n\n // Add starting-style\n if (variant.startingStyle) {\n atRules.push('@starting-style');\n }\n\n return atRules;\n}\n"],"mappings":";;;;;;;;;;AAsNA,MAAM,iBAAiB,IAAI,IAA2B,IAAK;;;;AAS3D,SAAgB,eAAe,MAAoC;CAEjE,MAAM,MAAM,qBAAqB,KAAK;CACtC,MAAM,SAAS,eAAe,IAAI,IAAI;AACtC,KAAI,OACF,QAAO;CAGT,MAAM,SAAS,oBAAoB,KAAK;AAGxC,gBAAe,IAAI,KAAK,OAAO;AAE/B,QAAO;;AAcT,SAAS,eAAgC;AACvC,QAAO;EACL,oBAAoB,EAAE;EACtB,kBAAkB,EAAE;EACpB,gBAAgB,EAAE;EAClB,WAAW,EAAE;EACb,iBAAiB,EAAE;EACnB,qBAAqB,EAAE;EACvB,oBAAoB,EAAE;EACtB,YAAY,EAAE;EACd,cAAc,EAAE;EAChB,eAAe;EAChB;;AAGH,SAAS,oBAAoB,MAAoC;AAE/D,KAAI,KAAK,SAAS,OAChB,QAAO;EACL,UAAU,CAAC,cAAc,CAAC;EAC1B,cAAc;EACf;AAIH,KAAI,KAAK,SAAS,QAChB,QAAO;EACL,UAAU,EAAE;EACZ,cAAc;EACf;AAIH,KAAI,KAAK,SAAS,QAChB,QAAO,WAAW,KAAK;AAIzB,KAAI,KAAK,SAAS,WAChB,KAAI,KAAK,aAAa,MACpB,QAAO,SAAS,KAAK,SAAS;KAE9B,QAAO,QAAQ,KAAK,SAAS;AAKjC,QAAO;EAC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,QAAQ,mBAAmB,SAAS,GAAG;EACzC,MAAM,iBAAiB,QAAQ,mBAAmB,KAAK,MAAM;AAI3D,OAAI,EAAE,YAAY,YAAY;IAC5B,MAAM,eAAe,YAAY,EAAE,UAAU;AAC7C,WAAO,EAAE,UAAU,QAAQ,aAAa,KAAK;UACxC;IACL,MAAM,cAAc,IAAI,EAAE,UAAU;AACpC,WAAO,EAAE,UAAU,QAAQ,YAAY,KAAK;;IAE9C;AACF,UAAQ,KAAK,aAAa,eAAe,KAAK,QAAQ,GAAG;;AAI3D,KAAI,QAAQ,cACV,SAAQ,KAAK,kBAAkB;AAGjC,QAAO"}
|
|
1
|
+
{"version":3,"file":"materialize.js","names":[],"sources":["../../src/pipeline/materialize.ts"],"sourcesContent":["/**\n * CSS Materialization\n *\n * Converts condition trees into CSS selectors and at-rules.\n * This is the final stage that produces actual CSS output.\n */\n\nimport { Lru } from '../parser/lru';\n\nimport type {\n ConditionNode,\n ContainerCondition,\n MediaCondition,\n ModifierCondition,\n PseudoCondition,\n StateCondition,\n SupportsCondition,\n} from './conditions';\nimport { getConditionUniqueId } from './conditions';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed media condition for structured analysis and combination\n */\nexport interface ParsedMediaCondition {\n /** Subtype for structured analysis */\n subtype: 'dimension' | 'feature' | 'type';\n /** Whether this is a negated condition */\n negated: boolean;\n /** The condition part for CSS output (e.g., \"(width < 600px)\", \"print\") */\n condition: string;\n /** For dimension queries: dimension name */\n dimension?: 'width' | 'height' | 'inline-size' | 'block-size';\n /** For dimension queries: lower bound value */\n lowerBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n };\n /** For dimension queries: upper bound value */\n upperBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n };\n /** For feature queries: feature name */\n feature?: string;\n /** For feature queries: feature value */\n featureValue?: string;\n /** For type queries: media type */\n mediaType?: 'print' | 'screen' | 'all' | 'speech';\n}\n\n/**\n * Parsed container condition for structured analysis and combination\n */\nexport interface ParsedContainerCondition {\n /** Container name (undefined = unnamed/nearest container) */\n name?: string;\n /** The condition part (e.g., \"(width < 600px)\" or \"style(--variant: danger)\") */\n condition: string;\n /** Whether this is a negated condition */\n negated: boolean;\n /** Subtype for structured analysis */\n subtype: 'dimension' | 'style' | 'raw';\n /** For style queries: property name (without --) */\n property?: string;\n /** For style queries: property value (undefined = existence check) */\n propertyValue?: string;\n}\n\n/**\n * Parsed supports condition for structured analysis and combination\n */\nexport interface ParsedSupportsCondition {\n /** Subtype: 'feature' for property support, 'selector' for selector() support */\n subtype: 'feature' | 'selector';\n /** The condition string (e.g., \"display: grid\" or \":has(*)\") */\n condition: string;\n /** Whether this is a negated condition */\n negated: boolean;\n}\n\n/**\n * Parsed modifier condition for structured analysis\n */\nexport interface ParsedModifierCondition {\n /** Attribute name (e.g., 'data-hovered', 'data-size') */\n attribute: string;\n /** Value if present (e.g., 'large', 'danger') */\n value?: string;\n /** Operator for value matching (default '=') */\n operator?: '=' | '^=' | '$=' | '*=';\n /** Whether this is negated (:not(...)) */\n negated: boolean;\n}\n\n/**\n * Parsed pseudo-class condition for structured analysis\n */\nexport interface ParsedPseudoCondition {\n /** The pseudo-class (e.g., ':hover', ':focus-visible', ':has(> Icon)') */\n pseudo: string;\n /** Whether this is negated (:not(...)) */\n negated: boolean;\n}\n\n/** Modifier or pseudo condition (shared across own/root/parent) */\ntype ParsedSelectorCondition = ParsedModifierCondition | ParsedPseudoCondition;\n\n/**\n * A group of selector conditions that produces an :is() or :not() wrapper.\n *\n * Each branch is an AND conjunction of conditions (one selector fragment).\n * Multiple branches are OR'd together inside the :is()/:not() wrapper.\n *\n * Example: size=small | size=medium\n * branches: [[size=small], [size=medium]]\n * renders: :is([data-size=\"small\"], [data-size=\"medium\"])\n *\n * When negated, :is() becomes :not():\n * :not([data-size=\"small\"], [data-size=\"medium\"])\n *\n * Single-branch groups are unwrapped (no :is() wrapper):\n * branches: [[size=small]]\n * renders: [data-size=\"small\"]\n */\nexport interface SelectorGroup {\n branches: ParsedSelectorCondition[][];\n negated: boolean;\n}\n\n/**\n * A group of parent conditions originating from a single @parent() call.\n * Each group produces its own :is()/:not() wrapper in the final CSS.\n * Separate @parent() calls = separate groups = can match different ancestors.\n *\n * Extends SelectorGroup with a `direct` flag for ancestor combinator:\n * direct = false → ` *` (any ancestor)\n * direct = true → ` > *` (direct parent only)\n *\n * Example: @parent(hovered & pressed | active)\n * branches: [[hovered, pressed], [active]]\n * renders: :is([data-hovered][data-pressed] *, [data-active] *)\n */\nexport interface ParentGroup extends SelectorGroup {\n direct: boolean;\n}\n\n/**\n * A single selector variant (one term in a DNF expression)\n */\nexport interface SelectorVariant {\n /** Structured modifier conditions (flat AND) */\n modifierConditions: ParsedModifierCondition[];\n\n /** Structured pseudo conditions (flat AND) */\n pseudoConditions: ParsedPseudoCondition[];\n\n /** Selector groups — :is()/:not() wrappers for OR branches on the element */\n selectorGroups: SelectorGroup[];\n\n /** Own groups — :is()/:not() wrappers for @own() OR branches on sub-elements */\n ownGroups: SelectorGroup[];\n\n /** Parsed media conditions for structured combination */\n mediaConditions: ParsedMediaCondition[];\n\n /** Parsed container conditions for structured combination */\n containerConditions: ParsedContainerCondition[];\n\n /** Parsed supports conditions for @supports at-rules */\n supportsConditions: ParsedSupportsCondition[];\n\n /** Root groups — :is()/:not() wrappers for @root() OR branches */\n rootGroups: SelectorGroup[];\n\n /** Parent condition groups — each @parent() call is a separate group */\n parentGroups: ParentGroup[];\n\n /** Whether to wrap in @starting-style */\n startingStyle: boolean;\n}\n\n/**\n * CSS output components extracted from a condition\n * Supports multiple variants for OR conditions (DNF form)\n */\nexport interface CSSComponents {\n /** Selector variants - OR means multiple variants, AND means single variant with combined selectors */\n variants: SelectorVariant[];\n\n /** Whether condition is impossible (should skip) */\n isImpossible: boolean;\n}\n\n/**\n * Final CSS rule output\n */\nexport interface CSSRule {\n /** Single selector or array of selector fragments (for OR conditions) */\n selector: string | string[];\n declarations: string;\n atRules?: string[];\n rootPrefix?: string;\n /** When true, declarations are wrapped in @starting-style { ... } inside the selector rule */\n startingStyle?: boolean;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst conditionCache = new Lru<string, CSSComponents>(3000);\n\n// ============================================================================\n// Main Functions\n// ============================================================================\n\n/**\n * Convert a condition tree to CSS components\n */\nexport function conditionToCSS(node: ConditionNode): CSSComponents {\n // Check cache\n const key = getConditionUniqueId(node);\n const cached = conditionCache.get(key);\n if (cached) {\n return cached;\n }\n\n const result = conditionToCSSInner(node);\n\n // Cache result\n conditionCache.set(key, result);\n\n return result;\n}\n\n/**\n * Clear the condition cache (for testing)\n */\nexport function clearConditionCache(): void {\n conditionCache.clear();\n}\n\n// ============================================================================\n// Inner Implementation\n// ============================================================================\n\nfunction emptyVariant(): SelectorVariant {\n return {\n modifierConditions: [],\n pseudoConditions: [],\n selectorGroups: [],\n ownGroups: [],\n mediaConditions: [],\n containerConditions: [],\n supportsConditions: [],\n rootGroups: [],\n parentGroups: [],\n startingStyle: false,\n };\n}\n\nfunction conditionToCSSInner(node: ConditionNode): CSSComponents {\n // Base case: TRUE condition - single empty variant (matches everything)\n if (node.kind === 'true') {\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n }\n\n // Base case: FALSE condition - no variants (matches nothing)\n if (node.kind === 'false') {\n return {\n variants: [],\n isImpossible: true,\n };\n }\n\n // State condition\n if (node.kind === 'state') {\n return stateToCSS(node);\n }\n\n // Compound condition\n if (node.kind === 'compound') {\n if (node.operator === 'AND') {\n return andToCSS(node.children);\n } else {\n return orToCSS(node.children);\n }\n }\n\n // Fallback - single empty variant\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n}\n\n/**\n * Convert a state condition to CSS\n */\nfunction stateToCSS(state: StateCondition): CSSComponents {\n switch (state.type) {\n case 'media': {\n const mediaResults = mediaToParsed(state);\n const variants = mediaResults.map((mediaCond) => {\n const v = emptyVariant();\n v.mediaConditions.push(mediaCond);\n return v;\n });\n return { variants, isImpossible: false };\n }\n\n case 'root':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'rootGroups',\n );\n\n case 'parent':\n return parentConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n state.direct,\n );\n\n case 'own':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'ownGroups',\n );\n\n case 'modifier': {\n const v = emptyVariant();\n v.modifierConditions.push(modifierToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'pseudo': {\n const v = emptyVariant();\n v.pseudoConditions.push(pseudoToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'container': {\n const v = emptyVariant();\n v.containerConditions.push(containerToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'supports': {\n const v = emptyVariant();\n v.supportsConditions.push(supportsToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'starting': {\n const v = emptyVariant();\n v.startingStyle = !state.negated;\n return { variants: [v], isImpossible: false };\n }\n }\n}\n\n/**\n * Convert modifier condition to parsed structure\n */\nfunction modifierToParsed(state: ModifierCondition): ParsedModifierCondition {\n return {\n attribute: state.attribute,\n value: state.value,\n operator: state.operator,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed modifier to CSS selector string (for final output)\n */\nexport function modifierToCSS(mod: ParsedModifierCondition): string {\n let selector: string;\n\n if (mod.value !== undefined) {\n // Value attribute: [data-attr=\"value\"]\n const op = mod.operator || '=';\n selector = `[${mod.attribute}${op}\"${mod.value}\"]`;\n } else {\n // Boolean attribute: [data-attr]\n selector = `[${mod.attribute}]`;\n }\n\n if (mod.negated) {\n return `:not(${selector})`;\n }\n return selector;\n}\n\n/**\n * Convert pseudo condition to parsed structure\n */\nfunction pseudoToParsed(state: PseudoCondition): ParsedPseudoCondition {\n return {\n pseudo: state.pseudo,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed pseudo to CSS selector string (for final output).\n *\n * :not() is normalized to negated :is() at parse time, so pseudo.pseudo\n * never starts with ':not(' here. When negated:\n * - :is(X) → :not(X) (unwrap :is)\n * - :where(X) → :not(X) (unwrap :where)\n * - :has(X) → :not(:has(X))\n * - other → :not(other)\n *\n * When not negated, single-argument :is()/:where() is unwrapped when the\n * inner content is a simple compound selector that can safely append to\n * the base selector (this happens after double-negation of :not()).\n */\nexport function pseudoToCSS(pseudo: ParsedPseudoCondition): string {\n const p = pseudo.pseudo;\n\n if (pseudo.negated) {\n if (p.startsWith(':is(') || p.startsWith(':where(')) {\n return `:not(${p.slice(p.indexOf('(') + 1, -1)})`;\n }\n return `:not(${p})`;\n }\n\n if ((p.startsWith(':is(') || p.startsWith(':where(')) && !p.includes(',')) {\n const inner = p.slice(p.indexOf('(') + 1, -1);\n const ch = inner[0];\n\n // Only unwrap when the inner content is a simple compound selector:\n // must start with a compoundable character and contain no whitespace\n // (whitespace implies combinators like `>`, `+`, `~`, or descendant).\n if (\n (ch === ':' || ch === '.' || ch === '[' || ch === '#') &&\n !/\\s/.test(inner)\n ) {\n return inner;\n }\n }\n\n return p;\n}\n\n/**\n * Convert media condition to parsed structure(s)\n * Returns an array because negated ranges produce OR branches (two separate conditions)\n */\nfunction mediaToParsed(state: MediaCondition): ParsedMediaCondition[] {\n if (state.subtype === 'type') {\n // @media:print → @media print (or @media not print)\n const mediaType = state.mediaType || 'all';\n return [\n {\n subtype: 'type',\n negated: state.negated ?? false,\n condition: mediaType,\n mediaType: state.mediaType,\n },\n ];\n } else if (state.subtype === 'feature') {\n // @media(prefers-contrast: high) → @media (prefers-contrast: high)\n let condition: string;\n if (state.featureValue) {\n condition = `(${state.feature}: ${state.featureValue})`;\n } else {\n condition = `(${state.feature})`;\n }\n return [\n {\n subtype: 'feature',\n negated: state.negated ?? false,\n condition,\n feature: state.feature,\n featureValue: state.featureValue,\n },\n ];\n } else {\n // Dimension query - negation is handled by inverting the condition\n // because \"not (width < x)\" doesn't work reliably in browsers\n return dimensionToMediaParsed(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n state.negated ?? false,\n );\n }\n}\n\n/**\n * Convert dimension bounds to parsed media condition(s)\n * Uses CSS Media Queries Level 4 `not (condition)` syntax for negation.\n */\nfunction dimensionToMediaParsed(\n dimension: 'width' | 'height' | 'inline-size' | 'block-size',\n lowerBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n upperBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n negated?: boolean,\n): ParsedMediaCondition[] {\n // Build the condition string\n let condition: string;\n if (lowerBound && upperBound) {\n const lowerOp = lowerBound.inclusive ? '<=' : '<';\n const upperOp = upperBound.inclusive ? '<=' : '<';\n condition = `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;\n } else if (upperBound) {\n const op = upperBound.inclusive ? '<=' : '<';\n condition = `(${dimension} ${op} ${upperBound.value})`;\n } else if (lowerBound) {\n const op = lowerBound.inclusive ? '>=' : '>';\n condition = `(${dimension} ${op} ${lowerBound.value})`;\n } else {\n condition = `(${dimension})`;\n }\n\n // For negation, we use CSS `not (condition)` syntax in buildAtRulesFromVariant\n return [\n {\n subtype: 'dimension',\n negated: negated ?? false,\n condition,\n dimension,\n lowerBound,\n upperBound,\n },\n ];\n}\n\n/**\n * Convert container condition to parsed structure\n * This enables structured analysis for contradiction detection and condition combining\n */\nfunction containerToParsed(\n state: ContainerCondition,\n): ParsedContainerCondition {\n let condition: string;\n\n if (state.subtype === 'style') {\n // Style query: style(--prop: value)\n if (state.propertyValue) {\n condition = `style(--${state.property}: ${state.propertyValue})`;\n } else {\n condition = `style(--${state.property})`;\n }\n } else if (state.subtype === 'raw') {\n // Raw function query: passed through verbatim (e.g., scroll-state(stuck: top))\n condition = state.rawCondition!;\n } else {\n // Dimension query\n condition = dimensionToContainerCondition(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n );\n }\n\n return {\n name: state.containerName,\n condition,\n negated: state.negated ?? false,\n subtype: state.subtype,\n property: state.property,\n propertyValue: state.propertyValue,\n };\n}\n\n/**\n * Convert dimension bounds to container query condition (single string)\n * Container queries support \"not (condition)\", so no need to invert manually\n */\nfunction dimensionToContainerCondition(\n dimension: string,\n lowerBound?: { value: string; inclusive: boolean },\n upperBound?: { value: string; inclusive: boolean },\n): string {\n if (lowerBound && upperBound) {\n const lowerOp = lowerBound.inclusive ? '<=' : '<';\n const upperOp = upperBound.inclusive ? '<=' : '<';\n return `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;\n } else if (upperBound) {\n const op = upperBound.inclusive ? '<=' : '<';\n return `(${dimension} ${op} ${upperBound.value})`;\n } else if (lowerBound) {\n const op = lowerBound.inclusive ? '>=' : '>';\n return `(${dimension} ${op} ${lowerBound.value})`;\n }\n return '(width)'; // Fallback\n}\n\n/**\n * Convert supports condition to parsed structure\n */\nfunction supportsToParsed(state: SupportsCondition): ParsedSupportsCondition {\n return {\n subtype: state.subtype,\n condition: state.condition,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Collect all modifier and pseudo conditions from a variant as a flat array.\n */\nfunction collectSelectorConditions(\n variant: SelectorVariant,\n): ParsedSelectorCondition[] {\n return [...variant.modifierConditions, ...variant.pseudoConditions];\n}\n\n/**\n * Convert an inner condition tree into a single SelectorVariant with\n * one SelectorGroup whose branches represent the inner OR alternatives.\n * Shared by @root() and @own().\n *\n * Both positive and negated cases produce one variant with one group.\n * Negation simply sets the `negated` flag, which swaps :is() for :not()\n * in the final CSS output — no De Morgan transformation is needed.\n *\n * This mirrors parentConditionToVariants: OR branches are kept inside\n * a single group and rendered as comma-separated arguments in\n * :is()/:not(), e.g. :root:is([a], [b]) or [el]:not([a], [b]).\n */\nfunction innerConditionToVariants(\n innerCondition: ConditionNode,\n negated: boolean,\n target: 'rootGroups' | 'ownGroups',\n): CSSComponents {\n const innerCSS = conditionToCSS(innerCondition);\n\n if (innerCSS.isImpossible || innerCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n const branches: ParsedSelectorCondition[][] = [];\n\n for (const innerVariant of innerCSS.variants) {\n const conditions = collectSelectorConditions(innerVariant);\n\n if (conditions.length > 0) {\n branches.push(conditions);\n }\n }\n\n if (branches.length === 0) {\n return { variants: [emptyVariant()], isImpossible: false };\n }\n\n const v = emptyVariant();\n v[target].push({ branches, negated });\n\n return { variants: [v], isImpossible: false };\n}\n\n/**\n * Convert a @parent() inner condition into a single SelectorVariant with\n * one ParentGroup whose branches represent the inner OR alternatives.\n *\n * Both positive and negated cases produce one variant with one group.\n * Negation simply sets the `negated` flag, which swaps :is() for :not()\n * in the final CSS output — no structural transformation is needed.\n */\nfunction parentConditionToVariants(\n innerCondition: ConditionNode,\n negated: boolean,\n direct: boolean,\n): CSSComponents {\n const innerCSS = conditionToCSS(innerCondition);\n\n if (innerCSS.isImpossible || innerCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n const branches: ParsedSelectorCondition[][] = [];\n\n for (const innerVariant of innerCSS.variants) {\n const conditions = collectSelectorConditions(innerVariant);\n\n if (conditions.length > 0) {\n branches.push(conditions);\n }\n }\n\n if (branches.length === 0) {\n return { variants: [emptyVariant()], isImpossible: false };\n }\n\n const v = emptyVariant();\n v.parentGroups.push({ branches, direct, negated });\n\n return { variants: [v], isImpossible: false };\n}\n\n/**\n * Sort key for canonical condition output within selectors.\n *\n * Priority order:\n * 0: Boolean attribute selectors ([data-hovered])\n * 1: Value attribute selectors ([data-size=\"small\"])\n * 2: Negated boolean attributes (:not([data-disabled]))\n * 3: Negated value attributes (:not([data-size=\"small\"]))\n * 4: Pseudo-classes (:hover, :focus)\n * 5: Negated pseudo-classes (:not(:disabled))\n *\n * Secondary sort: alphabetical by attribute name / pseudo string.\n */\nfunction conditionSortKey(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n const hasValue = cond.value !== undefined ? 1 : 0;\n const neg = cond.negated ? 2 : 0;\n return `${neg + hasValue}|${cond.attribute}|${cond.value ?? ''}`;\n }\n const priority = cond.negated ? 5 : 4;\n return `${priority}|${cond.pseudo}`;\n}\n\nfunction sortConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n return conditions.toSorted((a, b) =>\n conditionSortKey(a).localeCompare(conditionSortKey(b)),\n );\n}\n\nexport function branchToCSS(branch: ParsedSelectorCondition[]): string {\n let parts = '';\n for (const cond of sortConditions(branch)) {\n parts += selectorConditionToCSS(cond);\n }\n return parts;\n}\n\n/**\n * Wrap serialized selector arguments in :is() or :not().\n * Arguments are sorted for canonical output.\n */\nfunction wrapInIsOrNot(args: string[], negated: boolean): string {\n const wrapper = negated ? ':not' : ':is';\n return `${wrapper}(${args.sort().join(', ')})`;\n}\n\n/**\n * Convert a selector group to a CSS selector fragment.\n *\n * Single-branch groups are unwrapped (no :is() wrapper).\n * Multi-branch groups use :is() or :not().\n * Negation swaps :is() for :not().\n */\nexport function selectorGroupToCSS(group: SelectorGroup): string {\n if (group.branches.length === 0) return '';\n\n // Single branch: emit directly without :is() wrapper\n if (group.branches.length === 1) {\n const parts = branchToCSS(group.branches[0]);\n if (group.negated) {\n return `:not(${parts})`;\n }\n return parts;\n }\n\n return wrapInIsOrNot(group.branches.map(branchToCSS), group.negated);\n}\n\n// ============================================================================\n// Modifier Subsumption (shared by optimizeGroups and dedupeSelectorConditions)\n// ============================================================================\n\ninterface SubsumptionFacts {\n negatedBooleanAttrs: Set<string>;\n positiveExactValuesByAttr: Map<string, Set<string>>;\n}\n\n/**\n * Collect facts about modifier conditions for subsumption analysis.\n * Tracks negated boolean attrs (:not([attr])) and positive exact values ([attr=\"X\"]).\n */\nfunction collectSubsumptionFacts(\n modifiers: Iterable<ParsedModifierCondition>,\n): SubsumptionFacts {\n const negatedBooleanAttrs = new Set<string>();\n const positiveExactValuesByAttr = new Map<string, Set<string>>();\n\n for (const mod of modifiers) {\n if (mod.negated && mod.value === undefined) {\n negatedBooleanAttrs.add(mod.attribute);\n }\n if (\n !mod.negated &&\n mod.value !== undefined &&\n (mod.operator ?? '=') === '='\n ) {\n let vals = positiveExactValuesByAttr.get(mod.attribute);\n if (!vals) {\n vals = new Set();\n positiveExactValuesByAttr.set(mod.attribute, vals);\n }\n vals.add(mod.value);\n }\n }\n\n return { negatedBooleanAttrs, positiveExactValuesByAttr };\n}\n\n/**\n * Check if a negated-value modifier is subsumed by stronger facts:\n * - :not([attr]) subsumes :not([attr=\"val\"])\n * - [attr=\"X\"] implies :not([attr=\"Y\"]) is redundant (single exact value)\n *\n * Only applies to exact-match (=) operators; substring operators don't\n * imply exclusivity between values.\n */\nfunction isSubsumedNegatedModifier(\n mod: ParsedModifierCondition,\n facts: SubsumptionFacts,\n): boolean {\n if (!mod.negated || mod.value === undefined) return false;\n\n if (facts.negatedBooleanAttrs.has(mod.attribute)) return true;\n\n if ((mod.operator ?? '=') === '=') {\n const posVals = facts.positiveExactValuesByAttr.get(mod.attribute);\n if (posVals && posVals.size === 1 && !posVals.has(mod.value)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Remove redundant single-condition groups that are subsumed by stronger\n * groups on the same attribute. O(n) — only inspects single-branch,\n * single-condition groups.\n */\nexport function optimizeGroups(groups: SelectorGroup[]): SelectorGroup[] {\n if (groups.length <= 1) return groups;\n\n // Exact dedup by key\n const seen = new Set<string>();\n const result: SelectorGroup[] = [];\n for (const g of groups) {\n const key = getSelectorGroupKey(g);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(g);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Extract modifier conditions from simple groups for subsumption analysis\n const effectiveModifiers: ParsedModifierCondition[] = [];\n for (const g of result) {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) continue;\n const cond = g.branches[0][0];\n if (!('attribute' in cond)) continue;\n // Map group-level negation onto the condition for fact collection\n effectiveModifiers.push({\n ...cond,\n negated: g.negated !== cond.negated,\n });\n }\n\n const facts = collectSubsumptionFacts(effectiveModifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((g) => {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) return true;\n const cond = g.branches[0][0];\n if (\n !('attribute' in cond) ||\n !g.negated ||\n cond.negated ||\n cond.value === undefined\n ) {\n return true;\n }\n return !isSubsumedNegatedModifier({ ...cond, negated: true }, facts);\n });\n}\n\n/**\n * Convert root groups to CSS selector prefix (for final output)\n */\nexport function rootGroupsToCSS(groups: SelectorGroup[]): string | undefined {\n if (groups.length === 0) return undefined;\n\n const optimized = optimizeGroups(groups);\n if (optimized.length === 0) return undefined;\n\n let prefix = ':root';\n for (const group of optimized) {\n prefix += selectorGroupToCSS(group);\n }\n return prefix;\n}\n\n/**\n * Convert parent groups to CSS selector fragments (for final output).\n * Each group produces its own :is()/:not() wrapper with a combinator\n * suffix (` *` or ` > *`) appended to each branch.\n */\nexport function parentGroupsToCSS(groups: ParentGroup[]): string {\n let result = '';\n for (const group of groups) {\n const combinator = group.direct ? ' > *' : ' *';\n const args = group.branches.map(\n (branch) => branchToCSS(branch) + combinator,\n );\n result += wrapInIsOrNot(args, group.negated);\n }\n return result;\n}\n\n/**\n * Convert a modifier or pseudo condition to a CSS selector fragment\n */\nexport function selectorConditionToCSS(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n return modifierToCSS(cond);\n }\n return pseudoToCSS(cond);\n}\n\n/**\n * Get unique key for a modifier condition\n */\nfunction getModifierKey(mod: ParsedModifierCondition): string {\n const base = mod.value\n ? `${mod.attribute}${mod.operator || '='}${mod.value}`\n : mod.attribute;\n return mod.negated ? `!${base}` : base;\n}\n\n/**\n * Get unique key for a pseudo condition\n */\nfunction getPseudoKey(pseudo: ParsedPseudoCondition): string {\n return pseudo.negated ? `!${pseudo.pseudo}` : pseudo.pseudo;\n}\n\n/**\n * Get unique key for any selector condition (modifier or pseudo)\n */\nfunction getSelectorConditionKey(cond: ParsedSelectorCondition): string {\n return 'attribute' in cond\n ? `mod:${getModifierKey(cond)}`\n : `pseudo:${getPseudoKey(cond)}`;\n}\n\n/**\n * Deduplicate selector conditions (modifiers or pseudos).\n * Shared by root, parent, and own conditions.\n */\nfunction dedupeSelectorConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n // Pass 1: exact-key dedup\n const seen = new Set<string>();\n const result: ParsedSelectorCondition[] = [];\n for (const c of conditions) {\n const key = getSelectorConditionKey(c);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(c);\n }\n }\n\n // Pass 2: remove negated value modifiers subsumed by other modifiers\n const modifiers = result.filter(\n (c): c is ParsedModifierCondition => 'attribute' in c,\n );\n const facts = collectSubsumptionFacts(modifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((c) => {\n if (!('attribute' in c)) return true;\n return !isSubsumedNegatedModifier(c, facts);\n });\n}\n\n/**\n * Check for modifier contradiction: same attribute with opposite negation\n */\nfunction hasModifierContradiction(\n conditions: ParsedModifierCondition[],\n): boolean {\n const byKey = new Map<string, boolean>(); // base key -> isPositive\n\n for (const mod of conditions) {\n const baseKey = mod.value\n ? `${mod.attribute}${mod.operator || '='}${mod.value}`\n : mod.attribute;\n const existing = byKey.get(baseKey);\n if (existing !== undefined && existing !== !mod.negated) {\n return true; // Same attribute with opposite negation\n }\n byKey.set(baseKey, !mod.negated);\n }\n return false;\n}\n\n/**\n * Check for pseudo contradiction: same pseudo with opposite negation\n */\nfunction hasPseudoContradiction(conditions: ParsedPseudoCondition[]): boolean {\n const byKey = new Map<string, boolean>(); // pseudo -> isPositive\n\n for (const pseudo of conditions) {\n const existing = byKey.get(pseudo.pseudo);\n if (existing !== undefined && existing !== !pseudo.negated) {\n return true; // Same pseudo with opposite negation\n }\n byKey.set(pseudo.pseudo, !pseudo.negated);\n }\n return false;\n}\n\n/**\n * Check for selector condition contradiction (modifier or pseudo with opposite negation).\n * Shared by root, parent, and own conditions.\n */\nfunction hasSelectorConditionContradiction(\n conditions: ParsedSelectorCondition[],\n): boolean {\n const modifiers: ParsedModifierCondition[] = [];\n const pseudos: ParsedPseudoCondition[] = [];\n\n for (const c of conditions) {\n if ('attribute' in c) {\n modifiers.push(c);\n } else {\n pseudos.push(c);\n }\n }\n\n return hasModifierContradiction(modifiers) || hasPseudoContradiction(pseudos);\n}\n\n/**\n * Check for parent group contradiction: same target (direct + conditions)\n * with opposite negation. E.g. :not([data-hovered] *) and :is([data-hovered] *)\n * in the same variant is impossible.\n */\nfunction getBranchesKey(branches: ParsedSelectorCondition[][]): string {\n if (branches.length === 1) {\n const b = branches[0];\n if (b.length === 1) return getSelectorConditionKey(b[0]);\n return b.map(getSelectorConditionKey).sort().join('+');\n }\n return branches\n .map((b) => b.map(getSelectorConditionKey).sort().join('+'))\n .sort()\n .join(',');\n}\n\nfunction hasParentGroupContradiction(groups: ParentGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = `${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Check for selector group contradiction: same branches with opposite negation.\n * E.g. :is([data-a]) and :not([data-a]) in the same variant is impossible.\n */\nfunction hasSelectorGroupContradiction(groups: SelectorGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = getBranchesKey(g.branches);\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Merge two selector variants (AND operation)\n * Deduplicates conditions and checks for contradictions\n */\nfunction mergeVariants(\n a: SelectorVariant,\n b: SelectorVariant,\n): SelectorVariant | null {\n // Merge media conditions and check for contradictions\n const mergedMedia = dedupeMediaConditions([\n ...a.mediaConditions,\n ...b.mediaConditions,\n ]);\n if (hasMediaContradiction(mergedMedia)) {\n return null; // Impossible variant\n }\n\n // Concatenate root groups, optimize, and check for contradictions\n const mergedRootGroups = optimizeGroups([...a.rootGroups, ...b.rootGroups]);\n if (hasSelectorGroupContradiction(mergedRootGroups)) {\n return null; // Impossible variant\n }\n\n // Merge modifier and pseudo conditions separately, then cross-check\n const mergedModifiers = dedupeSelectorConditions([\n ...a.modifierConditions,\n ...b.modifierConditions,\n ]) as ParsedModifierCondition[];\n const mergedPseudos = dedupeSelectorConditions([\n ...a.pseudoConditions,\n ...b.pseudoConditions,\n ]) as ParsedPseudoCondition[];\n if (\n hasSelectorConditionContradiction([...mergedModifiers, ...mergedPseudos])\n ) {\n return null; // Impossible variant\n }\n\n // Concatenate selector groups, optimize, and check for contradictions\n const mergedSelectorGroups = optimizeGroups([\n ...a.selectorGroups,\n ...b.selectorGroups,\n ]);\n if (hasSelectorGroupContradiction(mergedSelectorGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate parent groups (each group is an independent :is() wrapper)\n const mergedParentGroups = [...a.parentGroups, ...b.parentGroups];\n if (hasParentGroupContradiction(mergedParentGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate own groups, optimize, and check for contradictions\n const mergedOwnGroups = optimizeGroups([...a.ownGroups, ...b.ownGroups]);\n if (hasSelectorGroupContradiction(mergedOwnGroups)) {\n return null; // Impossible variant\n }\n\n // Merge container conditions and check for contradictions\n const mergedContainers = dedupeContainerConditions([\n ...a.containerConditions,\n ...b.containerConditions,\n ]);\n if (hasContainerStyleContradiction(mergedContainers)) {\n return null; // Impossible variant\n }\n\n // Merge supports conditions and check for contradictions\n const mergedSupports = dedupeSupportsConditions([\n ...a.supportsConditions,\n ...b.supportsConditions,\n ]);\n if (hasSupportsContradiction(mergedSupports)) {\n return null; // Impossible variant\n }\n\n return {\n modifierConditions: mergedModifiers,\n pseudoConditions: mergedPseudos,\n selectorGroups: mergedSelectorGroups,\n ownGroups: mergedOwnGroups,\n mediaConditions: mergedMedia,\n containerConditions: mergedContainers,\n supportsConditions: mergedSupports,\n rootGroups: mergedRootGroups,\n parentGroups: mergedParentGroups,\n startingStyle: a.startingStyle || b.startingStyle,\n };\n}\n\n/**\n * Generic deduplication by a key extraction function.\n * Preserves insertion order, keeping the first occurrence of each key.\n */\nfunction dedupeByKey<T>(items: T[], getKey: (item: T) => string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const item of items) {\n const key = getKey(item);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(item);\n }\n }\n return result;\n}\n\nfunction dedupeMediaConditions(\n conditions: ParsedMediaCondition[],\n): ParsedMediaCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction dedupeContainerConditions(\n conditions: ParsedContainerCondition[],\n): ParsedContainerCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction dedupeSupportsConditions(\n conditions: ParsedSupportsCondition[],\n): ParsedSupportsCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\n/**\n * Check if supports conditions contain contradictions\n * e.g., @supports(display: grid) AND NOT @supports(display: grid)\n */\nfunction hasSupportsContradiction(\n conditions: ParsedSupportsCondition[],\n): boolean {\n const conditionMap = new Map<string, boolean>(); // key -> isPositive\n\n for (const cond of conditions) {\n const key = `${cond.subtype}|${cond.condition}`;\n const existing = conditionMap.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n conditionMap.set(key, !cond.negated);\n }\n\n return false;\n}\n\n/**\n * Check if a set of media conditions contains contradictions\n * e.g., (prefers-color-scheme: light) AND NOT (prefers-color-scheme: light)\n * or (width >= 900px) AND (width < 600px)\n *\n * Uses parsed media conditions for efficient analysis without regex parsing.\n */\nfunction hasMediaContradiction(conditions: ParsedMediaCondition[]): boolean {\n // Track conditions by their key (condition string) to detect A and NOT A\n const featureConditions = new Map<string, boolean>(); // key -> isPositive\n const typeConditions = new Map<string, boolean>(); // mediaType -> isPositive\n const dimensionConditions = new Map<string, boolean>(); // condition -> isPositive\n\n // Track dimension conditions for range contradiction detection (non-negated only)\n const dimensionsByDim = new Map<\n string,\n { lowerBound: number | null; upperBound: number | null }\n >();\n\n for (const cond of conditions) {\n if (cond.subtype === 'type') {\n // Type query: check for direct contradiction (print AND NOT print)\n const key = cond.mediaType || 'all';\n const existing = typeConditions.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n typeConditions.set(key, !cond.negated);\n } else if (cond.subtype === 'feature') {\n // Feature query: check for direct contradiction\n const key = cond.condition;\n const existing = featureConditions.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n featureConditions.set(key, !cond.negated);\n } else if (cond.subtype === 'dimension') {\n // First, check for direct contradiction: (width < 600px) AND NOT (width < 600px)\n const condKey = cond.condition;\n const existing = dimensionConditions.get(condKey);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n dimensionConditions.set(condKey, !cond.negated);\n\n // For range analysis, only consider non-negated conditions\n // Negated conditions are handled via the direct contradiction check above\n if (!cond.negated) {\n const dim = cond.dimension || 'width';\n let bounds = dimensionsByDim.get(dim);\n if (!bounds) {\n bounds = { lowerBound: null, upperBound: null };\n dimensionsByDim.set(dim, bounds);\n }\n\n // Track the effective bounds\n if (cond.lowerBound?.valueNumeric != null) {\n const value = cond.lowerBound.valueNumeric;\n if (bounds.lowerBound === null || value > bounds.lowerBound) {\n bounds.lowerBound = value;\n }\n }\n if (cond.upperBound?.valueNumeric != null) {\n const value = cond.upperBound.valueNumeric;\n if (bounds.upperBound === null || value < bounds.upperBound) {\n bounds.upperBound = value;\n }\n }\n\n // Check for impossible range\n if (\n bounds.lowerBound !== null &&\n bounds.upperBound !== null &&\n bounds.lowerBound >= bounds.upperBound\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n}\n\n/**\n * Check if container conditions contain contradictions in style queries\n * e.g., style(--variant: danger) and style(--variant: success) together\n * Same property with different values = always false\n *\n * Uses parsed container conditions for efficient analysis without regex parsing.\n */\nfunction hasContainerStyleContradiction(\n conditions: ParsedContainerCondition[],\n): boolean {\n // Track style queries by property name\n // key: property name, value: { hasExistence: boolean, values: Set<string>, hasNegatedExistence: boolean }\n const styleQueries = new Map<\n string,\n { hasExistence: boolean; values: Set<string>; hasNegatedExistence: boolean }\n >();\n\n for (const cond of conditions) {\n // Only analyze style queries\n if (cond.subtype !== 'style' || !cond.property) {\n continue;\n }\n\n const property = cond.property;\n const value = cond.propertyValue;\n\n if (!styleQueries.has(property)) {\n styleQueries.set(property, {\n hasExistence: false,\n values: new Set(),\n hasNegatedExistence: false,\n });\n }\n\n const entry = styleQueries.get(property)!;\n\n if (cond.negated) {\n if (value === undefined) {\n // not style(--prop) - negated existence check\n entry.hasNegatedExistence = true;\n }\n // Negated value checks don't contradict positive value checks directly\n // They just mean \"not this value\"\n } else {\n if (value === undefined) {\n // style(--prop) - existence check\n entry.hasExistence = true;\n } else {\n // style(--prop: value) - value check\n entry.values.add(value);\n }\n }\n }\n\n // Check for contradictions\n for (const [, entry] of styleQueries) {\n // Contradiction: existence check + negated existence check\n if (entry.hasExistence && entry.hasNegatedExistence) {\n return true;\n }\n\n // Contradiction: multiple different values for same property\n // style(--variant: danger) AND style(--variant: success) is impossible\n if (entry.values.size > 1) {\n return true;\n }\n\n // Contradiction: negated existence + value check\n // not style(--variant) AND style(--variant: danger) is impossible\n if (entry.hasNegatedExistence && entry.values.size > 0) {\n return true;\n }\n }\n\n return false;\n}\n\nconst variantKeyCache = new WeakMap<SelectorVariant, string>();\n\n/**\n * Get a unique key for a variant (for deduplication).\n * Cached via WeakMap since variants are compared multiple times during\n * deduplication and sorting.\n */\nfunction getSelectorGroupKey(g: SelectorGroup): string {\n return `${g.negated ? '!' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Get a context key for a variant — everything except flat modifier/pseudo\n * conditions. Variants with the same context key can be merged into an\n * :is() group. Also used by getVariantKey as the shared non-selector portion.\n */\nfunction getVariantContextKey(v: SelectorVariant): string {\n const mediaKey = v.mediaConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const containerKey = v.containerConditions\n .map((c) => `${c.name ?? ''}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const supportsKey = v.supportsConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const rootKey = v.rootGroups.map(getSelectorGroupKey).sort().join('|');\n const parentKey = v.parentGroups.map(getParentGroupKey).sort().join('|');\n const ownKey = v.ownGroups.map(getSelectorGroupKey).sort().join('|');\n const selectorGroupKey = v.selectorGroups\n .map(getSelectorGroupKey)\n .sort()\n .join('|');\n\n return [\n mediaKey,\n containerKey,\n supportsKey,\n rootKey,\n parentKey,\n ownKey,\n selectorGroupKey,\n v.startingStyle ? '1' : '0',\n ].join('###');\n}\n\nfunction getVariantKey(v: SelectorVariant): string {\n const cached = variantKeyCache.get(v);\n if (cached !== undefined) return cached;\n const modifierKey = v.modifierConditions.map(getModifierKey).sort().join('|');\n const pseudoKey = v.pseudoConditions.map(getPseudoKey).sort().join('|');\n const key = modifierKey + '###' + pseudoKey + '###' + getVariantContextKey(v);\n variantKeyCache.set(v, key);\n return key;\n}\n\n/**\n * Total number of leaf conditions in a variant (for superset / dedup comparisons).\n */\nfunction groupConditionCount(\n groups: readonly { branches: ParsedSelectorCondition[][] }[],\n): number {\n return groups.reduce(\n (sum, g) => sum + g.branches.reduce((s, b) => s + b.length, 0),\n 0,\n );\n}\n\nfunction variantConditionCount(v: SelectorVariant): number {\n return (\n v.modifierConditions.length +\n v.pseudoConditions.length +\n groupConditionCount(v.selectorGroups) +\n groupConditionCount(v.ownGroups) +\n v.mediaConditions.length +\n v.containerConditions.length +\n v.supportsConditions.length +\n groupConditionCount(v.rootGroups) +\n groupConditionCount(v.parentGroups)\n );\n}\n\n/**\n * Check if variant A is a superset of variant B (A is more restrictive)\n *\n * If A has all of B's conditions plus more, then A is redundant\n * because B already covers the same cases (and more).\n *\n * Example:\n * A: :not([size=large]):not([size=medium]):not([size=small])\n * B: :not([size=large])\n * A is a superset of B, so A is redundant when B exists.\n */\nfunction isVariantSuperset(a: SelectorVariant, b: SelectorVariant): boolean {\n // Must have same context\n if (a.startingStyle !== b.startingStyle) return false;\n\n // Check if a.rootGroups is superset of b.rootGroups\n if (!isSelectorGroupsSuperset(a.rootGroups, b.rootGroups)) return false;\n\n // Check if a.mediaConditions is superset of b.mediaConditions\n if (!isMediaConditionsSuperset(a.mediaConditions, b.mediaConditions))\n return false;\n\n // Check if a.containerConditions is superset of b.containerConditions\n if (\n !isContainerConditionsSuperset(a.containerConditions, b.containerConditions)\n )\n return false;\n\n // Check if a.supportsConditions is superset of b.supportsConditions\n if (!isSupportsConditionsSuperset(a.supportsConditions, b.supportsConditions))\n return false;\n\n // Check if a.modifierConditions is superset of b.modifierConditions\n if (!isModifierConditionsSuperset(a.modifierConditions, b.modifierConditions))\n return false;\n\n // Check if a.pseudoConditions is superset of b.pseudoConditions\n if (!isPseudoConditionsSuperset(a.pseudoConditions, b.pseudoConditions))\n return false;\n\n // Check if a.selectorGroups is superset of b.selectorGroups\n if (!isSelectorGroupsSuperset(a.selectorGroups, b.selectorGroups))\n return false;\n\n // Check if a.ownGroups is superset of b.ownGroups\n if (!isSelectorGroupsSuperset(a.ownGroups, b.ownGroups)) return false;\n\n // Check if a.parentGroups is superset of b.parentGroups\n if (!isParentGroupsSuperset(a.parentGroups, b.parentGroups)) return false;\n\n return variantConditionCount(a) > variantConditionCount(b);\n}\n\n/**\n * Generic superset check: true if every item in B has a matching key in A.\n */\nfunction isConditionsSuperset<T>(\n a: T[],\n b: T[],\n getKey: (item: T) => string,\n): boolean {\n const aKeys = new Set(a.map(getKey));\n return b.every((c) => aKeys.has(getKey(c)));\n}\n\nfunction isMediaConditionsSuperset(\n a: ParsedMediaCondition[],\n b: ParsedMediaCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isContainerConditionsSuperset(\n a: ParsedContainerCondition[],\n b: ParsedContainerCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isSupportsConditionsSuperset(\n a: ParsedSupportsCondition[],\n b: ParsedSupportsCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isModifierConditionsSuperset(\n a: ParsedModifierCondition[],\n b: ParsedModifierCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getModifierKey);\n}\n\nfunction isPseudoConditionsSuperset(\n a: ParsedPseudoCondition[],\n b: ParsedPseudoCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getPseudoKey);\n}\n\nfunction isSelectorGroupsSuperset(\n a: SelectorGroup[],\n b: SelectorGroup[],\n): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getSelectorGroupKey);\n}\n\n/**\n * Check if parent groups A is a superset of B.\n * Each group in B must have a matching group in A.\n */\nfunction isParentGroupsSuperset(a: ParentGroup[], b: ParentGroup[]): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getParentGroupKey);\n}\n\nfunction getParentGroupKey(g: ParentGroup): string {\n return `${g.negated ? '!' : ''}${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Deduplicate variants\n *\n * Removes:\n * 1. Exact duplicates (same key)\n * 2. Superset variants (more restrictive selectors that are redundant)\n */\nfunction dedupeVariants(variants: SelectorVariant[]): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // First pass: exact deduplication\n const seen = new Set<string>();\n const result: SelectorVariant[] = [];\n\n for (const v of variants) {\n const key = getVariantKey(v);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(v);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Second pass: remove supersets (more restrictive variants)\n // Sort by total condition count (fewer conditions = less restrictive = keep)\n result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));\n\n // Remove variants that are supersets of earlier (less restrictive) variants\n const filtered: SelectorVariant[] = [];\n for (const candidate of result) {\n let isRedundant = false;\n for (const kept of filtered) {\n if (isVariantSuperset(candidate, kept)) {\n isRedundant = true;\n break;\n }\n }\n if (!isRedundant) {\n filtered.push(candidate);\n }\n }\n\n return filtered;\n}\n\n/**\n * Combine AND conditions into CSS\n *\n * AND of conditions means cartesian product of variants:\n * (A1 | A2) & (B1 | B2) = A1&B1 | A1&B2 | A2&B1 | A2&B2\n *\n * Variants that result in contradictions (e.g., conflicting media rules)\n * are filtered out.\n */\nfunction andToCSS(children: ConditionNode[]): CSSComponents {\n // Start with a single empty variant\n let currentVariants: SelectorVariant[] = [emptyVariant()];\n\n for (const child of children) {\n const childCSS = conditionToCSSInner(child);\n\n if (childCSS.isImpossible || childCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Cartesian product: each current variant × each child variant\n const newVariants: SelectorVariant[] = [];\n for (const current of currentVariants) {\n for (const childVariant of childCSS.variants) {\n const merged = mergeVariants(current, childVariant);\n // Skip impossible variants (contradictions detected during merge)\n if (merged !== null) {\n newVariants.push(merged);\n }\n }\n }\n\n if (newVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Deduplicate after each step to prevent exponential blowup\n currentVariants = dedupeVariants(newVariants);\n }\n\n return {\n variants: currentVariants,\n isImpossible: false,\n };\n}\n\n/**\n * Combine OR conditions into CSS\n *\n * OR in CSS means multiple selector variants (DNF).\n * After deduplication, variants that differ only in their base\n * modifier/pseudo conditions are merged into :is() groups.\n *\n * Note: OR exclusivity is handled at the pipeline level (expandOrConditions),\n * so here we just collect all variants. Any remaining ORs in the condition\n * tree (e.g., from De Morgan expansion) are handled as simple alternatives.\n */\nfunction orToCSS(children: ConditionNode[]): CSSComponents {\n const allVariants: SelectorVariant[] = [];\n\n for (const child of children) {\n const childCSS = conditionToCSSInner(child);\n if (childCSS.isImpossible) continue;\n\n allVariants.push(...childCSS.variants);\n }\n\n if (allVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n return {\n variants: dedupeVariants(allVariants),\n isImpossible: false,\n };\n}\n\n// ============================================================================\n// OR → :is() Merging\n// ============================================================================\n\n/**\n * Find keys present in ALL condition arrays.\n */\nfunction findCommonKeys<T>(\n conditionSets: T[][],\n getKey: (item: T) => string,\n): Set<string> {\n if (conditionSets.length === 0) return new Set();\n\n const common = new Set(conditionSets[0].map(getKey));\n for (let i = 1; i < conditionSets.length; i++) {\n const keys = new Set(conditionSets[i].map(getKey));\n for (const key of common) {\n if (!keys.has(key)) common.delete(key);\n }\n }\n return common;\n}\n\n/**\n * Merge OR variants that share the same \"context\" (at-rules, root, parent,\n * own, starting) into a single variant with a SelectorGroup.\n *\n * Variants with no modifier/pseudo conditions are kept separate (they match\n * unconditionally and can't be expressed inside :is()).\n */\nexport function mergeVariantsIntoSelectorGroups(\n variants: SelectorVariant[],\n): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // Group variants by their context (everything except flat modifier/pseudo)\n const groups = new Map<string, SelectorVariant[]>();\n for (const v of variants) {\n const key = getVariantContextKey(v);\n const group = groups.get(key);\n if (group) group.push(v);\n else groups.set(key, [v]);\n }\n\n const result: SelectorVariant[] = [];\n for (const group of groups.values()) {\n if (group.length === 1) {\n result.push(group[0]);\n continue;\n }\n\n // Separate variants with no selector conditions (can't merge into :is())\n const withSelectors: SelectorVariant[] = [];\n const withoutSelectors: SelectorVariant[] = [];\n for (const v of group) {\n if (\n v.modifierConditions.length === 0 &&\n v.pseudoConditions.length === 0\n ) {\n withoutSelectors.push(v);\n } else {\n withSelectors.push(v);\n }\n }\n\n result.push(...withoutSelectors);\n\n if (withSelectors.length <= 1) {\n result.push(...withSelectors);\n continue;\n }\n\n // Factor out common conditions and create a SelectorGroup\n result.push(factorAndGroup(withSelectors));\n }\n\n return result;\n}\n\n/**\n * Factor common modifier/pseudo conditions out of variants and create\n * a single variant with a SelectorGroup for the remaining (differing)\n * conditions.\n *\n * Precondition: all variants must share the same context key (identical\n * at-rules, root/parent/own/selector groups, startingStyle).\n */\nfunction factorAndGroup(variants: SelectorVariant[]): SelectorVariant {\n if (process.env.NODE_ENV !== 'production') {\n const key0 = getVariantContextKey(variants[0]);\n for (let i = 1; i < variants.length; i++) {\n const keyI = getVariantContextKey(variants[i]);\n if (keyI !== key0) {\n throw new Error(\n `factorAndGroup: context key mismatch at index ${i}.\\n` +\n ` expected: ${key0}\\n got: ${keyI}`,\n );\n }\n }\n }\n\n // Find common modifier and pseudo keys across ALL variants\n const commonModKeys = findCommonKeys(\n variants.map((v) => v.modifierConditions),\n getModifierKey,\n );\n const commonPseudoKeys = findCommonKeys(\n variants.map((v) => v.pseudoConditions),\n getPseudoKey,\n );\n\n // Extract common conditions from first variant\n const commonModifiers = variants[0].modifierConditions.filter((m) =>\n commonModKeys.has(getModifierKey(m)),\n );\n const commonPseudos = variants[0].pseudoConditions.filter((p) =>\n commonPseudoKeys.has(getPseudoKey(p)),\n );\n\n // Build branches from remaining (non-common) conditions.\n // If any variant has only common conditions (empty branch), it matches\n // unconditionally within this context — the :is() group would lose it.\n // In that case, return the broadest variant (common conditions only).\n const branches: ParsedSelectorCondition[][] = [];\n let hasEmptyBranch = false;\n for (const v of variants) {\n const branch: ParsedSelectorCondition[] = [];\n for (const mod of v.modifierConditions) {\n if (!commonModKeys.has(getModifierKey(mod))) branch.push(mod);\n }\n for (const pseudo of v.pseudoConditions) {\n if (!commonPseudoKeys.has(getPseudoKey(pseudo))) branch.push(pseudo);\n }\n if (branch.length > 0) {\n branches.push(branch);\n } else {\n hasEmptyBranch = true;\n }\n }\n\n // If a variant has only common conditions, it's the broadest match —\n // the :is() group with specific branches is subsumed by it.\n // Return the variant with common conditions only.\n if (hasEmptyBranch) {\n return {\n ...variants[0],\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n };\n }\n\n return {\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n selectorGroups: [\n ...variants[0].selectorGroups,\n { branches, negated: false },\n ],\n ownGroups: [...variants[0].ownGroups],\n mediaConditions: [...variants[0].mediaConditions],\n containerConditions: [...variants[0].containerConditions],\n supportsConditions: [...variants[0].supportsConditions],\n rootGroups: [...variants[0].rootGroups],\n parentGroups: [...variants[0].parentGroups],\n startingStyle: variants[0].startingStyle,\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Build at-rules array from a variant\n */\nexport function buildAtRulesFromVariant(variant: SelectorVariant): string[] {\n const atRules: string[] = [];\n\n // Add media rules - combine all conditions with \"and\"\n if (variant.mediaConditions.length > 0) {\n const conditionParts = variant.mediaConditions.map((c) => {\n if (c.subtype === 'type') {\n // Media type: print, screen, etc.\n return c.negated ? `not ${c.condition}` : c.condition;\n } else {\n // Feature or dimension: use not (condition) syntax for negation\n // MQ Level 4 requires parentheses around the condition for negation\n return c.negated ? `(not ${c.condition})` : c.condition;\n }\n });\n atRules.push(`@media ${conditionParts.join(' and ')}`);\n }\n\n // Add container rules - group by container name and combine with \"and\"\n if (variant.containerConditions.length > 0) {\n // Group conditions by container name (undefined = unnamed/nearest)\n const byName = new Map<string | undefined, ParsedContainerCondition[]>();\n for (const cond of variant.containerConditions) {\n const group = byName.get(cond.name) || [];\n group.push(cond);\n byName.set(cond.name, group);\n }\n\n // Build one @container rule per container name\n for (const [name, conditions] of byName) {\n // CSS Container Query syntax requires parentheses around negated conditions:\n // @container (not style(--x)) and style(--y) - NOT @container not style(--x) and style(--y)\n const conditionParts = conditions.map((c) =>\n c.negated ? `(not ${c.condition})` : c.condition,\n );\n const namePrefix = name ? `${name} ` : '';\n atRules.push(`@container ${namePrefix}${conditionParts.join(' and ')}`);\n }\n }\n\n // Add supports rules - combine all conditions with \"and\"\n if (variant.supportsConditions.length > 0) {\n const conditionParts = variant.supportsConditions.map((c) => {\n // Build the condition based on subtype\n // feature: (display: grid) or (not (display: grid))\n // selector: selector(:has(*)) or (not selector(:has(*)))\n if (c.subtype === 'selector') {\n const selectorCond = `selector(${c.condition})`;\n return c.negated ? `(not ${selectorCond})` : selectorCond;\n } else {\n const featureCond = `(${c.condition})`;\n return c.negated ? `(not ${featureCond})` : featureCond;\n }\n });\n atRules.push(`@supports ${conditionParts.join(' and ')}`);\n }\n\n return atRules;\n}\n"],"mappings":";;;;;;;;;;AAwNA,MAAM,iBAAiB,IAAI,IAA2B,IAAK;;;;AAS3D,SAAgB,eAAe,MAAoC;CAEjE,MAAM,MAAM,qBAAqB,KAAK;CACtC,MAAM,SAAS,eAAe,IAAI,IAAI;AACtC,KAAI,OACF,QAAO;CAGT,MAAM,SAAS,oBAAoB,KAAK;AAGxC,gBAAe,IAAI,KAAK,OAAO;AAE/B,QAAO;;AAcT,SAAS,eAAgC;AACvC,QAAO;EACL,oBAAoB,EAAE;EACtB,kBAAkB,EAAE;EACpB,gBAAgB,EAAE;EAClB,WAAW,EAAE;EACb,iBAAiB,EAAE;EACnB,qBAAqB,EAAE;EACvB,oBAAoB,EAAE;EACtB,YAAY,EAAE;EACd,cAAc,EAAE;EAChB,eAAe;EAChB;;AAGH,SAAS,oBAAoB,MAAoC;AAE/D,KAAI,KAAK,SAAS,OAChB,QAAO;EACL,UAAU,CAAC,cAAc,CAAC;EAC1B,cAAc;EACf;AAIH,KAAI,KAAK,SAAS,QAChB,QAAO;EACL,UAAU,EAAE;EACZ,cAAc;EACf;AAIH,KAAI,KAAK,SAAS,QAChB,QAAO,WAAW,KAAK;AAIzB,KAAI,KAAK,SAAS,WAChB,KAAI,KAAK,aAAa,MACpB,QAAO,SAAS,KAAK,SAAS;KAE9B,QAAO,QAAQ,KAAK,SAAS;AAKjC,QAAO;EACL,U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AQ,mBAAmB,SAAS,GAAG;EACzC,MAAM,iBAAiB,QAAQ,mBAAmB,KAAK,MAAM;AAI3D,OAAI,EAAE,YAAY,YAAY;IAC5B,MAAM,eAAe,YAAY,EAAE,UAAU;AAC7C,WAAO,EAAE,UAAU,QAAQ,aAAa,KAAK;UACxC;IACL,MAAM,cAAc,IAAI,EAAE,UAAU;AACpC,WAAO,EAAE,UAAU,QAAQ,YAAY,KAAK;;IAE9C;AACF,UAAQ,KAAK,aAAa,eAAe,KAAK,QAAQ,GAAG;;AAG3D,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/properties/index.ts"],"sourcesContent":["/**\n * Properties Utilities\n *\n * Utilities for extracting and processing CSS @property definitions in styles.\n * Unlike keyframes, properties are permanent once registered and don't need cleanup.\n *\n * Property names use tasty token syntax:\n * - `$name` for regular properties → `--name`\n * - `#name` for color properties → `--name-color` (auto-sets syntax: '<color>')\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { RE_NUMBER, RE_RAW_UNIT } from '../parser/const';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst PROPERTIES_KEY = '@properties';\n\n/**\n * Valid CSS custom property name pattern (after the -- prefix).\n * Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.\n */\nconst VALID_PROPERTY_NAME_PATTERN = /^[a-z_][a-z0-9-_]*$/i;\n\n// ============================================================================\n// Validation Functions\n// ============================================================================\n\n/**\n * Validate a CSS custom property name (the part after --).\n * Returns true if the name is valid for use as a CSS custom property.\n */\nexport function isValidPropertyName(name: string): boolean {\n return VALID_PROPERTY_NAME_PATTERN.test(name);\n}\n\n/**\n * Result of parsing a property token.\n */\nexport interface ParsedPropertyToken {\n /** The CSS custom property name (e.g., '--my-prop') */\n cssName: string;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @properties definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalProperties(styles: Styles): boolean {\n return PROPERTIES_KEY in styles;\n}\n\n/**\n * Extract local @properties from styles object.\n * Returns null if no local properties (fast path).\n */\nexport function extractLocalProperties(\n styles: Styles,\n): Record<string, PropertyDefinition> | null {\n const properties = styles[PROPERTIES_KEY];\n if (!properties || typeof properties !== 'object') {\n return null;\n }\n return properties as Record<string, PropertyDefinition>;\n}\n\n// ============================================================================\n// Token Parsing Functions\n// ============================================================================\n\n/**\n * Parse a property token name and return the CSS property name and whether it's a color.\n * Supports tasty token syntax and validates the property name.\n *\n * Token formats:\n * - `$name` → { cssName: '--name', isColor: false }\n * - `#name` → { cssName: '--name-color', isColor: true }\n * - `--name` → { cssName: '--name', isColor: false } (legacy, auto-detect color by suffix)\n * - `name` → { cssName: '--name', isColor: false } (legacy)\n *\n * @param token - The property token to parse\n * @returns Parsed result with cssName, isColor, isValid, and optional error\n */\nexport function parsePropertyToken(token: string): ParsedPropertyToken {\n if (!token || typeof token !== 'string') {\n return {\n cssName: '',\n isColor: false,\n isValid: false,\n error: 'Property token must be a non-empty string',\n };\n }\n\n let name: string;\n let isColor: boolean;\n\n if (token.startsWith('$')) {\n // Regular property token: $name → --name\n name = token.slice(1);\n isColor = false;\n } else if (token.startsWith('#')) {\n // Color property token: #name → --name-color\n name = token.slice(1);\n isColor = true;\n } else if (token.startsWith('--')) {\n // Legacy format with -- prefix\n name = token.slice(2);\n isColor = token.endsWith('-color');\n } else {\n // Legacy format without prefix\n name = token;\n isColor = token.endsWith('-color');\n }\n\n // Validate the name\n if (!name) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: 'Property name cannot be empty',\n };\n }\n\n if (!isValidPropertyName(name)) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: `Invalid property name \"${name}\". Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.`,\n };\n }\n\n // Build the CSS custom property name\n // For #name tokens, we add -color suffix\n // For legacy formats (--name-color or name-color), the name already includes -color\n let cssName: string;\n if (token.startsWith('#')) {\n // Color token: #name → --name-color\n cssName = `--${name}-color`;\n } else {\n // All other formats: just add -- prefix\n cssName = `--${name}`;\n }\n\n return {\n cssName,\n isColor,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Normalization Functions\n// ============================================================================\n\n/**\n * Normalize a property name to the CSS custom property format.\n *\n * @deprecated Use parsePropertyToken instead for proper token handling\n */\nexport function normalizePropertyName(name: string): string {\n const result = parsePropertyToken(name);\n return result.isValid ? result.cssName : `--${name}`;\n}\n\n/**\n * Normalize a property definition to a consistent string representation.\n * Used for comparing definitions to detect type conflicts.\n *\n * Only `syntax` and `inherits` are compared — `initialValue` is intentionally\n * excluded because different components may set different defaults for the\n * same typed property (e.g. auto-inferred `0px` vs explicit `6px`).\n *\n * Keys are sorted alphabetically to ensure consistent comparison:\n * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }\n */\nexport function normalizePropertyDefinition(def: PropertyDefinition): string {\n const normalized: Record<string, unknown> = {};\n\n if (def.inherits !== undefined) {\n normalized.inherits = def.inherits;\n }\n if (def.syntax !== undefined) {\n normalized.syntax = def.syntax;\n }\n\n return JSON.stringify(normalized);\n}\n\n/**\n * Result of getEffectiveDefinition.\n */\nexport interface EffectiveDefinitionResult {\n /** The CSS custom property name */\n cssName: string;\n /** The effective property definition */\n definition: PropertyDefinition;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Get the effective property definition for a token.\n * For color tokens (#name), auto-sets syntax to '<color>' and defaults initialValue to 'transparent'.\n *\n * @param token - Property token ($name, #name, --name, or plain name)\n * @param userDefinition - User-provided definition options\n * @returns Effective definition with cssName, definition, isValid, and optional error\n */\nexport function getEffectiveDefinition(\n token: string,\n userDefinition: PropertyDefinition,\n): EffectiveDefinitionResult {\n const parsed = parsePropertyToken(token);\n\n if (!parsed.isValid) {\n return {\n cssName: '',\n definition: userDefinition,\n isColor: false,\n isValid: false,\n error: parsed.error,\n };\n }\n\n if (parsed.isColor) {\n // Color properties have fixed syntax and default initialValue\n return {\n cssName: parsed.cssName,\n definition: {\n syntax: '<color>', // Always '<color>' for color tokens, cannot be overridden\n inherits: userDefinition.inherits, // Allow inherits to be customized\n initialValue: userDefinition.initialValue ?? 'transparent', // Default to transparent\n },\n isColor: true,\n isValid: true,\n };\n }\n\n // Regular properties use the definition as-is\n return {\n cssName: parsed.cssName,\n definition: userDefinition,\n isColor: false,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\n/**\n * Convert a color initialValue to components in the configured color space.\n * Used by SSR to emit `@property --name-color-{suffix}`.\n *\n * @deprecated Use `colorInitialValueToComponents` from `utils/color-space` instead.\n */\nexport { colorInitialValueToComponents as colorInitialValueToRgb } from '../utils/color-space';\n\n// ============================================================================\n// Value Type Inference\n// ============================================================================\n\n/**\n * Result of inferring a CSS @property syntax from a value.\n */\nexport interface InferredSyntax {\n syntax: string;\n initialValue: string;\n}\n\nconst UNIT_TO_SYNTAX: Record<string, InferredSyntax> = {};\n\nconst LENGTH_UNITS = [\n 'px',\n 'em',\n 'rem',\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n 'ch',\n 'ex',\n 'cap',\n 'ic',\n 'lh',\n 'rlh',\n 'svw',\n 'svh',\n 'lvw',\n 'lvh',\n 'dvw',\n 'dvh',\n 'cqw',\n 'cqh',\n 'cqi',\n 'cqb',\n 'cqmin',\n 'cqmax',\n];\n\nconst ANGLE_UNITS = ['deg', 'rad', 'grad', 'turn'];\nconst TIME_UNITS = ['ms', 's'];\n\nfor (const u of LENGTH_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<length-percentage>', initialValue: '0px' };\n}\nUNIT_TO_SYNTAX['%'] = { syntax: '<length-percentage>', initialValue: '0px' };\nfor (const u of ANGLE_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<angle>', initialValue: '0deg' };\n}\nfor (const u of TIME_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<time>', initialValue: '0s' };\n}\n\n/**\n * Infer CSS @property syntax from a concrete value.\n * Detects numeric types: \\<number\\>, \\<length-percentage\\>, \\<angle\\>, \\<time\\>.\n * Length and percentage values both map to \\<length-percentage\\> for maximum flexibility.\n * Color properties are handled separately via the #name token convention\n * (--name-color gets \\<color\\> syntax automatically in getEffectiveDefinition).\n *\n * @param value - The CSS value to infer from (e.g. '10px', '1', '45deg')\n * @returns Inferred syntax and initial value, or null if not inferable\n */\nexport function inferSyntaxFromValue(value: string): InferredSyntax | null {\n if (!value || typeof value !== 'string') return null;\n\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n if (RE_NUMBER.test(trimmed)) {\n // Bare zero is ambiguous (could be <length>, <angle>, <percentage>, etc.)\n if (parseFloat(trimmed) === 0) return null;\n return { syntax: '<number>', initialValue: '0' };\n }\n\n const unitMatch = trimmed.match(RE_RAW_UNIT);\n if (unitMatch) {\n const unit = unitMatch[2];\n const mapping = UNIT_TO_SYNTAX[unit];\n if (mapping) return mapping;\n }\n\n return null;\n}\n"],"mappings":";;;;AAmBA,MAAM,iBAAiB;;;;;AAMvB,MAAM,8BAA8B;;;;;AAUpC,SAAgB,oBAAoB,MAAuB;AACzD,QAAO,4BAA4B,KAAK,KAAK;;;;;;AAyB/C,SAAgB,mBAAmB,QAAyB;AAC1D,QAAO,kBAAkB;;;;;;AAO3B,SAAgB,uBACd,QAC2C;CAC3C,MAAM,aAAa,OAAO;AAC1B,KAAI,CAAC,cAAc,OAAO,eAAe,SACvC,QAAO;AAET,QAAO;;;;;;;;;;;;;;;AAoBT,SAAgB,mBAAmB,OAAoC;AACrE,KAAI,CAAC,SAAS,OAAO,UAAU,SAC7B,QAAO;EACL,SAAS;EACT,SAAS;EACT,SAAS;EACT,OAAO;EACR;CAGH,IAAI;CACJ,IAAI;AAEJ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;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,cAAc;CAAC;CAAO;CAAO;CAAQ;CAAO;AAClD,MAAM,aAAa,CAAC,MAAM,IAAI;AAE9B,KAAK,MAAM,KAAK,aACd,gBAAe,KAAK;CAAE,QAAQ;CAAuB,cAAc;CAAO;AAE5E,eAAe,OAAO;CAAE,QAAQ;CAAuB,cAAc;CAAO;AAC5E,KAAK,MAAM,KAAK,YACd,gBAAe,KAAK;CAAE,QAAQ;CAAW,cAAc;CAAQ;AAEjE,KAAK,MAAM,KAAK,WACd,gBAAe,KAAK;CAAE,QAAQ;CAAU,cAAc;CAAM;;;;;;;;;;;AAa9D,SAAgB,qBAAqB,OAAsC;AACzE,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;CAEhD,MAAM,UAAU,MAAM,MAAM;AAC5B,KAAI,CAAC,QAAS,QAAO;AAErB,KAAI,UAAU,KAAK,QAAQ,EAAE;AAE3B,MAAI,WAAW,QAAQ,KAAK,EAAG,QAAO;AACtC,SAAO;GAAE,QAAQ;GAAY,cAAc;GAAK;;CAGlD,MAAM,YAAY,QAAQ,MAAM,YAAY;AAC5C,KAAI,WAAW;EAEb,MAAM,UAAU,eADH,UAAU;AAEvB,MAAI,QAAS,QAAO;;AAGtB,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/properties/index.ts"],"sourcesContent":["/**\n * Properties Utilities\n *\n * Utilities for extracting and processing CSS @property definitions in styles.\n * Unlike keyframes, properties are permanent once registered and don't need cleanup.\n *\n * Property names use tasty token syntax:\n * - `$name` for regular properties → `--name`\n * - `#name` for color properties → `--name-color` (auto-sets syntax: '<color>')\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { RE_NUMBER, RE_RAW_UNIT } from '../parser/const';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst PROPERTIES_KEY = '@properties';\n\n/**\n * Valid CSS custom property name pattern (after the -- prefix).\n * Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.\n */\nconst VALID_PROPERTY_NAME_PATTERN = /^[a-z_][a-z0-9-_]*$/i;\n\n// ============================================================================\n// Validation Functions\n// ============================================================================\n\n/**\n * Validate a CSS custom property name (the part after --).\n * Returns true if the name is valid for use as a CSS custom property.\n */\nexport function isValidPropertyName(name: string): boolean {\n return VALID_PROPERTY_NAME_PATTERN.test(name);\n}\n\n/**\n * Result of parsing a property token.\n */\nexport interface ParsedPropertyToken {\n /** The CSS custom property name (e.g., '--my-prop') */\n cssName: string;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @properties definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalProperties(styles: Styles): boolean {\n return PROPERTIES_KEY in styles;\n}\n\n/**\n * Extract local @properties from styles object.\n * Returns null if no local properties (fast path).\n */\nexport function extractLocalProperties(\n styles: Styles,\n): Record<string, PropertyDefinition> | null {\n const properties = styles[PROPERTIES_KEY];\n if (!properties || typeof properties !== 'object') {\n return null;\n }\n return properties as Record<string, PropertyDefinition>;\n}\n\n// ============================================================================\n// Token Parsing Functions\n// ============================================================================\n\n/**\n * Parse a property token name and return the CSS property name and whether it's a color.\n * Supports tasty token syntax and validates the property name.\n *\n * Token formats:\n * - `$name` → { cssName: '--name', isColor: false }\n * - `#name` → { cssName: '--name-color', isColor: true }\n * - `--name` → { cssName: '--name', isColor: false } (legacy, auto-detect color by suffix)\n * - `name` → { cssName: '--name', isColor: false } (legacy)\n *\n * @param token - The property token to parse\n * @returns Parsed result with cssName, isColor, isValid, and optional error\n */\nexport function parsePropertyToken(token: string): ParsedPropertyToken {\n if (!token || typeof token !== 'string') {\n return {\n cssName: '',\n isColor: false,\n isValid: false,\n error: 'Property token must be a non-empty string',\n };\n }\n\n let name: string;\n let isColor: boolean;\n\n if (token.startsWith('$')) {\n // Regular property token: $name → --name\n name = token.slice(1);\n isColor = false;\n } else if (token.startsWith('#')) {\n // Color property token: #name → --name-color\n name = token.slice(1);\n isColor = true;\n } else if (token.startsWith('--')) {\n // Legacy format with -- prefix\n name = token.slice(2);\n isColor = token.endsWith('-color');\n } else {\n // Legacy format without prefix\n name = token;\n isColor = token.endsWith('-color');\n }\n\n // Validate the name\n if (!name) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: 'Property name cannot be empty',\n };\n }\n\n if (!isValidPropertyName(name)) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: `Invalid property name \"${name}\". Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.`,\n };\n }\n\n // Build the CSS custom property name\n // For #name tokens, we add -color suffix\n // For legacy formats (--name-color or name-color), the name already includes -color\n let cssName: string;\n if (token.startsWith('#')) {\n // Color token: #name → --name-color\n cssName = `--${name}-color`;\n } else {\n // All other formats: just add -- prefix\n cssName = `--${name}`;\n }\n\n return {\n cssName,\n isColor,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Normalization Functions\n// ============================================================================\n\n/**\n * Normalize a property name to the CSS custom property format.\n *\n * @deprecated Use parsePropertyToken instead for proper token handling\n */\nexport function normalizePropertyName(name: string): string {\n const result = parsePropertyToken(name);\n return result.isValid ? result.cssName : `--${name}`;\n}\n\n/**\n * Normalize a property definition to a consistent string representation.\n * Used for comparing definitions to detect type conflicts.\n *\n * Only `syntax` and `inherits` are compared — `initialValue` is intentionally\n * excluded because different components may set different defaults for the\n * same typed property (e.g. auto-inferred `0px` vs explicit `6px`).\n *\n * Keys are sorted alphabetically to ensure consistent comparison:\n * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }\n */\nexport function normalizePropertyDefinition(def: PropertyDefinition): string {\n const normalized: Record<string, unknown> = {};\n\n if (def.inherits !== undefined) {\n normalized.inherits = def.inherits;\n }\n if (def.syntax !== undefined) {\n normalized.syntax = def.syntax;\n }\n\n return JSON.stringify(normalized);\n}\n\n/**\n * Result of getEffectiveDefinition.\n */\nexport interface EffectiveDefinitionResult {\n /** The CSS custom property name */\n cssName: string;\n /** The effective property definition */\n definition: PropertyDefinition;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Get the effective property definition for a token.\n * For color tokens (#name), auto-sets syntax to '<color>' and defaults initialValue to 'transparent'.\n *\n * @param token - Property token ($name, #name, --name, or plain name)\n * @param userDefinition - User-provided definition options\n * @returns Effective definition with cssName, definition, isValid, and optional error\n */\nexport function getEffectiveDefinition(\n token: string,\n userDefinition: PropertyDefinition,\n): EffectiveDefinitionResult {\n const parsed = parsePropertyToken(token);\n\n if (!parsed.isValid) {\n return {\n cssName: '',\n definition: userDefinition,\n isColor: false,\n isValid: false,\n error: parsed.error,\n };\n }\n\n if (parsed.isColor) {\n // Color properties have fixed syntax and default initialValue\n return {\n cssName: parsed.cssName,\n definition: {\n syntax: '<color>', // Always '<color>' for color tokens, cannot be overridden\n inherits: userDefinition.inherits, // Allow inherits to be customized\n initialValue: userDefinition.initialValue ?? 'transparent', // Default to transparent\n },\n isColor: true,\n isValid: true,\n };\n }\n\n // Regular properties use the definition as-is\n return {\n cssName: parsed.cssName,\n definition: userDefinition,\n isColor: false,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Color Utilities\n// ============================================================================\n\nexport { colorInitialValueToComponents } from '../utils/color-space';\n\n// ============================================================================\n// Value Type Inference\n// ============================================================================\n\n/**\n * Result of inferring a CSS @property syntax from a value.\n */\nexport interface InferredSyntax {\n syntax: string;\n initialValue: string;\n}\n\nconst UNIT_TO_SYNTAX: Record<string, InferredSyntax> = {};\n\nconst LENGTH_UNITS = [\n 'px',\n 'em',\n 'rem',\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n 'ch',\n 'ex',\n 'cap',\n 'ic',\n 'lh',\n 'rlh',\n 'svw',\n 'svh',\n 'lvw',\n 'lvh',\n 'dvw',\n 'dvh',\n 'cqw',\n 'cqh',\n 'cqi',\n 'cqb',\n 'cqmin',\n 'cqmax',\n];\n\nconst ANGLE_UNITS = ['deg', 'rad', 'grad', 'turn'];\nconst TIME_UNITS = ['ms', 's'];\n\nfor (const u of LENGTH_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<length-percentage>', initialValue: '0px' };\n}\nUNIT_TO_SYNTAX['%'] = { syntax: '<length-percentage>', initialValue: '0px' };\nfor (const u of ANGLE_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<angle>', initialValue: '0deg' };\n}\nfor (const u of TIME_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<time>', initialValue: '0s' };\n}\n\n/**\n * Infer CSS @property syntax from a concrete value.\n * Detects numeric types: \\<number\\>, \\<length-percentage\\>, \\<angle\\>, \\<time\\>.\n * Length and percentage values both map to \\<length-percentage\\> for maximum flexibility.\n * Color properties are handled separately via the #name token convention\n * (--name-color gets \\<color\\> syntax automatically in getEffectiveDefinition).\n *\n * @param value - The CSS value to infer from (e.g. '10px', '1', '45deg')\n * @returns Inferred syntax and initial value, or null if not inferable\n */\nexport function inferSyntaxFromValue(value: string): InferredSyntax | null {\n if (!value || typeof value !== 'string') return null;\n\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n if (RE_NUMBER.test(trimmed)) {\n // Bare zero is ambiguous (could be <length>, <angle>, <percentage>, etc.)\n if (parseFloat(trimmed) === 0) return null;\n return { syntax: '<number>', initialValue: '0' };\n }\n\n const unitMatch = trimmed.match(RE_RAW_UNIT);\n if (unitMatch) {\n const unit = unitMatch[2];\n const mapping = UNIT_TO_SYNTAX[unit];\n if (mapping) return mapping;\n }\n\n return null;\n}\n"],"mappings":";;;;AAmBA,MAAM,iBAAiB;;;;;AAMvB,MAAM,8BAA8B;;;;;AAUpC,SA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AEb,MAAM,UAAU,eADH,UAAU;AAEvB,MAAI,QAAS,QAAO;;AAGtB,QAAO"}
|
package/dist/ssr/collector.d.ts
CHANGED
|
@@ -23,7 +23,12 @@ declare class ServerStyleCollector {
|
|
|
23
23
|
private flushedGlobalKeys;
|
|
24
24
|
private rawCSS;
|
|
25
25
|
private flushedRawKeys;
|
|
26
|
+
private fontFaceRules;
|
|
27
|
+
private flushedFontFaceKeys;
|
|
28
|
+
private counterStyleRules;
|
|
29
|
+
private flushedCounterStyleKeys;
|
|
26
30
|
private keyframesCounter;
|
|
31
|
+
private counterStyleCounter;
|
|
27
32
|
private internalsCollected;
|
|
28
33
|
/**
|
|
29
34
|
* Collect internal @property rules and :root token defaults.
|
|
@@ -56,6 +61,18 @@ declare class ServerStyleCollector {
|
|
|
56
61
|
* Allocate a keyframe name for SSR. Uses provided name or generates one.
|
|
57
62
|
*/
|
|
58
63
|
allocateKeyframeName(providedName?: string): string;
|
|
64
|
+
/**
|
|
65
|
+
* Record a @font-face rule. Deduplicated by key (content hash).
|
|
66
|
+
*/
|
|
67
|
+
collectFontFace(key: string, css: string): void;
|
|
68
|
+
/**
|
|
69
|
+
* Record a @counter-style rule. Deduplicated by name.
|
|
70
|
+
*/
|
|
71
|
+
collectCounterStyle(name: string, css: string): void;
|
|
72
|
+
/**
|
|
73
|
+
* Allocate a counter-style name for SSR. Uses provided name or generates one.
|
|
74
|
+
*/
|
|
75
|
+
allocateCounterStyleName(providedName?: string): string;
|
|
59
76
|
/**
|
|
60
77
|
* Record global styles (from useGlobalStyles). Deduplicated by key.
|
|
61
78
|
*/
|