@tenphi/tasty 1.5.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +20 -15
  2. package/dist/compute-styles.js +13 -26
  3. package/dist/compute-styles.js.map +1 -1
  4. package/dist/config.d.ts +39 -1
  5. package/dist/config.js +64 -2
  6. package/dist/config.js.map +1 -1
  7. package/dist/core/index.d.ts +2 -2
  8. package/dist/core/index.js +1 -1
  9. package/dist/debug.js +4 -4
  10. package/dist/debug.js.map +1 -1
  11. package/dist/hooks/useCounterStyle.js +2 -1
  12. package/dist/hooks/useCounterStyle.js.map +1 -1
  13. package/dist/hooks/useGlobalStyles.js +2 -2
  14. package/dist/hooks/useKeyframes.js +2 -1
  15. package/dist/hooks/useKeyframes.js.map +1 -1
  16. package/dist/hooks/useRawCSS.js +1 -1
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +1 -1
  19. package/dist/injector/index.js +1 -1
  20. package/dist/injector/index.js.map +1 -1
  21. package/dist/injector/injector.d.ts +5 -0
  22. package/dist/injector/injector.js +93 -6
  23. package/dist/injector/injector.js.map +1 -1
  24. package/dist/injector/sheet-manager.js +3 -2
  25. package/dist/injector/sheet-manager.js.map +1 -1
  26. package/dist/injector/types.d.ts +9 -2
  27. package/dist/pipeline/exclusive.js +57 -2
  28. package/dist/pipeline/exclusive.js.map +1 -1
  29. package/dist/pipeline/index.js +2 -2
  30. package/dist/pipeline/index.js.map +1 -1
  31. package/dist/pipeline/materialize.js +56 -2
  32. package/dist/pipeline/materialize.js.map +1 -1
  33. package/dist/pipeline/simplify.js +180 -5
  34. package/dist/pipeline/simplify.js.map +1 -1
  35. package/dist/plugins/types.d.ts +12 -1
  36. package/dist/rsc-cache.js +2 -4
  37. package/dist/rsc-cache.js.map +1 -1
  38. package/dist/ssr/astro-client.js +5 -10
  39. package/dist/ssr/astro-client.js.map +1 -1
  40. package/dist/ssr/astro.d.ts +4 -2
  41. package/dist/ssr/astro.js +2 -2
  42. package/dist/ssr/astro.js.map +1 -1
  43. package/dist/ssr/collector.d.ts +9 -13
  44. package/dist/ssr/collector.js +32 -16
  45. package/dist/ssr/collector.js.map +1 -1
  46. package/dist/ssr/hydrate.d.ts +20 -13
  47. package/dist/ssr/hydrate.js +24 -28
  48. package/dist/ssr/hydrate.js.map +1 -1
  49. package/dist/ssr/index.d.ts +3 -3
  50. package/dist/ssr/index.js +2 -2
  51. package/dist/ssr/index.js.map +1 -1
  52. package/dist/ssr/next.d.ts +4 -3
  53. package/dist/ssr/next.js +5 -5
  54. package/dist/ssr/next.js.map +1 -1
  55. package/dist/tasty.d.ts +1 -1
  56. package/dist/tasty.js +9 -4
  57. package/dist/tasty.js.map +1 -1
  58. package/dist/utils/typography.d.ts +21 -10
  59. package/dist/utils/typography.js +1 -1
  60. package/dist/utils/typography.js.map +1 -1
  61. package/dist/zero/babel.d.ts +7 -108
  62. package/dist/zero/babel.js +36 -12
  63. package/dist/zero/babel.js.map +1 -1
  64. package/docs/README.md +2 -2
  65. package/docs/adoption.md +5 -3
  66. package/docs/comparison.md +24 -25
  67. package/docs/configuration.md +69 -1
  68. package/docs/design-system.md +22 -10
  69. package/docs/dsl.md +3 -3
  70. package/docs/getting-started.md +10 -10
  71. package/docs/injector.md +2 -2
  72. package/docs/methodology.md +2 -2
  73. package/docs/{runtime.md → react-api.md} +5 -1
  74. package/docs/ssr.md +14 -7
  75. package/docs/tasty-static.md +14 -2
  76. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"sheet-manager.js","names":[],"sources":["../../src/injector/sheet-manager.ts"],"sourcesContent":["import { PropertyTypeResolver } from '../properties/property-type-resolver';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n KeyframesInfo,\n KeyframesSteps,\n RawCSSInfo,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n SheetInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\nimport type { CSSMap, StyleHandler, StyleValueStateMap } from '../utils/styles';\n\nexport class SheetManager {\n private rootRegistries = new WeakMap<Document | ShadowRoot, RootRegistry>();\n /** Strong set of active roots so background GC can iterate them all */\n private activeRoots = new Set<Document | ShadowRoot>();\n private config: StyleInjectorConfig;\n /** Dedicated style elements for raw CSS per root */\n private rawStyleElements = new WeakMap<\n Document | ShadowRoot,\n HTMLStyleElement\n >();\n /** Tracking for raw CSS blocks per root */\n private rawCSSBlocks = new WeakMap<\n Document | ShadowRoot,\n Map<string, RawCSSInfo>\n >();\n /** Counter for generating unique raw CSS IDs */\n private rawCSSCounter = 0;\n\n constructor(config: StyleInjectorConfig) {\n this.config = config;\n }\n\n /**\n * Get or create registry for a root (Document or ShadowRoot)\n */\n getRegistry(root: Document | ShadowRoot): RootRegistry {\n let registry = this.rootRegistries.get(root);\n\n if (!registry) {\n const metrics: CacheMetrics | undefined = this.config.devMode\n ? {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n }\n : undefined;\n\n registry = {\n sheets: [],\n refCounts: new Map(),\n rules: new Map(),\n cacheKeyToClassName: new Map(),\n ruleTextSet: new Set<string>(),\n metrics,\n classCounter: 0,\n keyframesCache: new Map(),\n keyframesNameToContent: new Map(),\n keyframesCounter: 0,\n injectedProperties: new Map<string, string>(),\n injectedFontFaces: new Set<string>(),\n injectedCounterStyles: new Set<string>(),\n globalRules: new Map(),\n propertyTypeResolver: new PropertyTypeResolver(),\n usageMap: new Map(),\n touchCount: 0,\n } as unknown as RootRegistry;\n\n this.rootRegistries.set(root, registry);\n this.activeRoots.add(root);\n }\n\n return registry;\n }\n\n /** Return all roots with active registries (for background GC sweep). */\n getActiveRoots(): Iterable<Document | ShadowRoot> {\n return this.activeRoots;\n }\n\n /** Check whether any roots have active registries. */\n hasActiveRoots(): boolean {\n return this.activeRoots.size > 0;\n }\n\n /** Remove registries for ShadowRoots whose host has been detached from the DOM. */\n pruneDisconnectedRoots(): void {\n const toPrune: (Document | ShadowRoot)[] = [];\n for (const root of this.activeRoots) {\n if (root !== document && !(root as ShadowRoot).host?.isConnected) {\n toPrune.push(root);\n }\n }\n for (const root of toPrune) {\n this.cleanup(root);\n }\n }\n\n /**\n * Create a new stylesheet for the registry\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n const sheet = this.createStyleElement(root);\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n /**\n * Create a style element and append to document\n */\n private createStyleElement(root: Document | ShadowRoot): HTMLStyleElement {\n const style =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n style.nonce = this.config.nonce;\n }\n\n style.setAttribute('data-tasty', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(style);\n } else if ('appendChild' in root) {\n root.appendChild(style);\n } else {\n document.head.appendChild(style);\n }\n\n // Verify it was actually added - log only if there's a problem and we're not using forceTextInjection\n if (!style.isConnected && !this.config.forceTextInjection) {\n console.error('SheetManager: Style element failed to connect to DOM!', {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n });\n }\n\n return style;\n }\n\n /**\n * Insert CSS rules as a single block\n */\n insertRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n className: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Find or create a sheet with available space\n let targetSheet = this.findAvailableSheet(registry, root);\n\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n // Group rules by selector, at-rules, and startingStyle to combine declarations\n const groupedRules: StyleRule[] = [];\n const groupMap = new Map<\n string,\n {\n idx: number;\n selector: string;\n atRules?: string[];\n startingStyle?: boolean;\n declarations: string;\n }\n >();\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n flattenedRules.forEach((r) => {\n const key = `${atKey(r.atRules)}||${r.selector}||${r.startingStyle ? '1' : '0'}`;\n const existing = groupMap.get(key);\n if (existing) {\n // Append declarations, preserving order\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n idx: groupedRules.length,\n selector: r.selector,\n atRules: r.atRules,\n startingStyle: r.startingStyle,\n declarations: r.declarations,\n });\n groupedRules.push({ ...r });\n }\n });\n\n // Normalize groupedRules from map (with merged declarations)\n groupMap.forEach((val) => {\n groupedRules[val.idx] = {\n selector: val.selector,\n atRules: val.atRules,\n startingStyle: val.startingStyle,\n declarations: val.declarations,\n } as StyleRule;\n });\n\n // Insert grouped rules\n const insertedRuleTexts: string[] = [];\n const insertedIndices: number[] = []; // Track exact indices\n // Calculate rule index atomically right before insertion to prevent race conditions\n let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);\n let firstInsertedIndex: number | null = null;\n let lastInsertedIndex: number | null = null;\n\n for (const rule of groupedRules) {\n const declarations = rule.declarations;\n const innerContent = rule.startingStyle\n ? `@starting-style { ${declarations} }`\n : declarations;\n const baseRule = `${rule.selector} { ${innerContent} }`;\n\n // Wrap with at-rules if present\n let fullRule = baseRule;\n if (rule.atRules && rule.atRules.length > 0) {\n fullRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n baseRule,\n );\n }\n\n // Insert individual rule into style element\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n // Calculate index atomically for each rule to prevent concurrent insertion races\n const maxIndex = styleSheet.cssRules.length;\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);\n\n // Helper: split comma-separated selectors safely (ignores commas inside [] () \" ')\n const splitSelectorsSafely = (selectorList: string): string[] => {\n const parts: string[] = [];\n let buf = '';\n let depthSq = 0; // [] depth\n let depthPar = 0; // () depth\n let inStr: '\"' | \"'\" | '' = '';\n for (let i = 0; i < selectorList.length; i++) {\n const ch = selectorList[i];\n if (inStr) {\n if (ch === inStr && selectorList[i - 1] !== '\\\\') {\n inStr = '';\n }\n buf += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inStr = ch as '\"' | \"'\";\n buf += ch;\n continue;\n }\n if (ch === '[') depthSq++;\n else if (ch === ']') depthSq = Math.max(0, depthSq - 1);\n else if (ch === '(') depthPar++;\n else if (ch === ')') depthPar = Math.max(0, depthPar - 1);\n\n if (ch === ',' && depthSq === 0 && depthPar === 0) {\n const part = buf.trim();\n if (part) parts.push(part);\n buf = '';\n } else {\n buf += ch;\n }\n }\n const tail = buf.trim();\n if (tail) parts.push(tail);\n return parts;\n };\n\n try {\n styleSheet.insertRule(fullRule, safeIndex);\n // Update sheet ruleCount immediately to prevent concurrent race conditions\n targetSheet.ruleCount++;\n insertedIndices.push(safeIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;\n lastInsertedIndex = safeIndex;\n currentRuleIndex = safeIndex + 1;\n } catch (e) {\n // If the browser rejects the combined selector (e.g., vendor pseudo-elements),\n // try to split and insert each selector independently. Skip unsupported ones.\n const selectors = splitSelectorsSafely(rule.selector);\n if (selectors.length > 1) {\n let anyInserted = false;\n for (const sel of selectors) {\n const singleBase = `${sel} { ${declarations} }`;\n let singleRule = singleBase;\n if (rule.atRules && rule.atRules.length > 0) {\n singleRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n singleBase,\n );\n }\n\n try {\n // Calculate index atomically for each individual selector insertion\n const maxIdx = styleSheet.cssRules.length;\n const atomicIdx = this.findAvailableRuleIndex(targetSheet);\n const idx = Math.min(Math.max(0, atomicIdx), maxIdx);\n styleSheet.insertRule(singleRule, idx);\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(idx); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = idx;\n lastInsertedIndex = idx;\n currentRuleIndex = idx + 1;\n anyInserted = true;\n } catch (singleErr) {\n // Skip unsupported selector in this engine (e.g., ::-moz-selection in Blink)\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[tasty] Browser rejected CSS rule:',\n singleRule,\n singleErr,\n );\n }\n }\n }\n // If none inserted, continue without throwing to avoid aborting the whole batch\n if (!anyInserted) {\n // noop: all selectors invalid here; safe to skip\n }\n } else {\n // Single selector failed — skip it silently (likely unsupported in this engine)\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[tasty] Browser rejected CSS rule:', fullRule, e);\n }\n }\n }\n } else {\n // Use textContent (either as fallback or when forceTextInjection is enabled)\n // Calculate index atomically for textContent insertion too\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(atomicRuleIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;\n lastInsertedIndex = atomicRuleIndex;\n currentRuleIndex = atomicRuleIndex + 1;\n }\n\n // CRITICAL DEBUG: Verify the style element is in DOM only if there are issues and we're not using forceTextInjection\n if (!styleElement.parentNode && !this.config.forceTextInjection) {\n console.error(\n 'SheetManager: Style element is NOT in DOM! This is the problem!',\n {\n className,\n ruleIndex: currentRuleIndex,\n },\n );\n }\n\n // Dev-only: store cssText for debugging tools\n if (this.config.devMode) {\n insertedRuleTexts.push(fullRule);\n try {\n registry.ruleTextSet.add(fullRule);\n } catch {\n // noop: defensive in case ruleTextSet is unavailable\n }\n }\n // currentRuleIndex already adjusted above\n }\n\n // Sheet ruleCount is now updated immediately after each insertion\n // No need for deferred update logic\n\n if (insertedIndices.length === 0) {\n return null;\n }\n\n return {\n className,\n ruleIndex: firstInsertedIndex ?? 0,\n sheetIndex,\n cssText: this.config.devMode ? insertedRuleTexts : undefined,\n endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,\n indices: insertedIndices,\n };\n } catch (error) {\n console.warn('Failed to insert CSS rules:', error, {\n flattenedRules,\n className,\n });\n return null;\n }\n }\n\n /**\n * Insert global CSS rules\n */\n insertGlobalRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n globalKey: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Insert the rule using the same mechanism as regular rules\n const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);\n\n // Track global rules for index adjustment\n if (ruleInfo) {\n registry.globalRules.set(globalKey, ruleInfo);\n }\n\n return ruleInfo;\n }\n\n /**\n * Delete a global CSS rule by key\n */\n public deleteGlobalRule(registry: RootRegistry, globalKey: string): void {\n const ruleInfo = registry.globalRules.get(globalKey);\n if (!ruleInfo) {\n return;\n }\n\n // Delete the rule using the standard deletion mechanism\n this.deleteRule(registry, ruleInfo);\n\n // Remove from global rules tracking\n registry.globalRules.delete(globalKey);\n }\n\n /**\n * Adjust rule indices after deletion to account for shifting\n */\n private adjustIndicesAfterDeletion(\n registry: RootRegistry,\n sheetIndex: number,\n startIdx: number,\n endIdx: number,\n deleteCount: number,\n deletedRuleInfo: RuleInfo,\n deletedIndices?: number[],\n ): void {\n try {\n const sortedDeleted =\n deletedIndices && deletedIndices.length > 0\n ? [...deletedIndices].sort((a, b) => a - b)\n : null;\n const countDeletedBefore = (sorted: number[], idx: number): number => {\n let shift = 0;\n for (const delIdx of sorted) {\n if (delIdx < idx) shift++;\n else break;\n }\n return shift;\n };\n // Helper function to adjust a single RuleInfo\n const adjustRuleInfo = (info: RuleInfo): void => {\n if (info === deletedRuleInfo) return; // Skip the deleted rule\n if (info.sheetIndex !== sheetIndex) return; // Different sheet\n\n if (!info.indices || info.indices.length === 0) {\n return;\n }\n\n if (sortedDeleted) {\n // Adjust each index based on how many deleted indices are before it\n info.indices = info.indices.map((idx) => {\n return idx - countDeletedBefore(sortedDeleted, idx);\n });\n } else {\n // Contiguous deletion: shift indices after the deleted range\n info.indices = info.indices.map((idx) =>\n idx > endIdx ? Math.max(0, idx - deleteCount) : idx,\n );\n }\n\n // Update ruleIndex and endRuleIndex to match adjusted indices\n if (info.indices.length > 0) {\n info.ruleIndex = Math.min(...info.indices);\n info.endRuleIndex = Math.max(...info.indices);\n }\n };\n\n // Adjust active rules\n for (const info of registry.rules.values()) {\n adjustRuleInfo(info);\n }\n\n // Adjust global rules\n for (const info of registry.globalRules.values()) {\n adjustRuleInfo(info);\n }\n\n // No need to separately adjust unused rules since they're part of the rules Map\n\n // Adjust keyframes indices stored in cache\n for (const entry of registry.keyframesCache.values()) {\n const ki = entry.info as KeyframesInfo;\n if (ki.sheetIndex !== sheetIndex) continue;\n if (sortedDeleted) {\n const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);\n if (shift > 0) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);\n }\n } else if (ki.ruleIndex > endIdx) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);\n }\n }\n } catch {\n // Defensive: do not let index adjustments crash cleanup\n }\n }\n\n /**\n * Delete a CSS rule from the sheet\n */\n deleteRule(registry: RootRegistry, ruleInfo: RuleInfo): void {\n const sheet = registry.sheets[ruleInfo.sheetIndex];\n\n if (!sheet) {\n return;\n }\n\n try {\n const texts: string[] =\n this.config.devMode && Array.isArray(ruleInfo.cssText)\n ? ruleInfo.cssText.slice()\n : [];\n\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n const rules = styleSheet.cssRules;\n\n // Use exact indices if available, otherwise fall back to range\n if (ruleInfo.indices && ruleInfo.indices.length > 0) {\n // NEW: Delete using exact tracked indices\n const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a); // Sort descending\n const deletedIndices: number[] = [];\n\n for (const idx of sortedIndices) {\n if (idx >= 0 && idx < styleSheet.cssRules.length) {\n try {\n styleSheet.deleteRule(idx);\n deletedIndices.push(idx);\n } catch (e) {\n console.warn(`Failed to delete rule at index ${idx}:`, e);\n }\n }\n }\n\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\n // Adjust indices for all other rules\n if (deletedIndices.length > 0) {\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n Math.min(...deletedIndices),\n Math.max(...deletedIndices),\n deletedIndices.length,\n ruleInfo,\n deletedIndices,\n );\n }\n } else {\n // FALLBACK: Use old range-based deletion for backwards compatibility\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n rules.length - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n if (Number.isFinite(startIdx) && endIdx >= startIdx) {\n const deleteCount = endIdx - startIdx + 1;\n for (let idx = endIdx; idx >= startIdx; idx--) {\n if (idx < 0 || idx >= styleSheet.cssRules.length) continue;\n styleSheet.deleteRule(idx);\n }\n sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);\n\n // After deletion, all subsequent rule indices shift left by deleteCount.\n // We must adjust stored indices for all other RuleInfo within the same sheet.\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n startIdx,\n endIdx,\n deleteCount,\n ruleInfo,\n );\n }\n }\n }\n\n // Dev-only: remove cssText entries from validation set\n if (this.config.devMode && texts.length) {\n try {\n for (const text of texts) {\n registry.ruleTextSet.delete(text);\n }\n } catch {\n // noop\n }\n }\n } catch (error) {\n console.warn('Failed to delete CSS rule:', error);\n }\n }\n\n /**\n * Find a sheet with available space or return null\n */\n private findAvailableSheet(\n registry: RootRegistry,\n _root: Document | ShadowRoot,\n ): SheetInfo | null {\n const maxRules = this.config.maxRulesPerSheet;\n\n if (!maxRules) {\n // No limit, use the last sheet if it exists\n const lastSheet = registry.sheets[registry.sheets.length - 1];\n return lastSheet || null;\n }\n\n // Find sheet with space\n for (const sheet of registry.sheets) {\n if (sheet.ruleCount < maxRules) {\n return sheet;\n }\n }\n\n return null; // No available sheet found\n }\n\n /**\n * Find an available rule index in the sheet\n */\n findAvailableRuleIndex(sheet: SheetInfo): number {\n // Always append to the end - CSS doesn't have holes\n return sheet.ruleCount;\n }\n\n /**\n * Force cleanup of unused styles\n */\n public forceCleanup(registry: RootRegistry): void {\n this.performBulkCleanup(registry);\n }\n\n /**\n * Perform bulk cleanup of all unused styles (refCount = 0).\n */\n private performBulkCleanup(registry: RootRegistry): void {\n const cleanupStartTime = Date.now();\n\n // Calculate unused rules dynamically: rules that have refCount = 0\n // and are not tracked in usageMap (GC-kept styles must survive)\n const unusedClassNames = Array.from(registry.refCounts.entries())\n .filter(\n ([className, refCount]) =>\n refCount === 0 && !registry.usageMap.has(className),\n )\n .map(([className]) => className);\n\n if (unusedClassNames.length === 0) return;\n\n const selected = unusedClassNames\n .map((className) => {\n const ruleInfo = registry.rules.get(className);\n return ruleInfo ? { className, ruleInfo } : null;\n })\n .filter((entry): entry is NonNullable<typeof entry> => entry != null);\n\n let cleanedUpCount = 0;\n let totalCssSize = 0;\n let totalRulesDeleted = 0;\n\n // Group by sheet for efficient deletion\n const rulesBySheet = new Map<\n number,\n { className: string; ruleInfo: RuleInfo }[]\n >();\n\n // Calculate CSS size before deletion and group rules\n for (const { className, ruleInfo } of selected) {\n const sheetIndex = ruleInfo.sheetIndex;\n\n // Dev-only metrics: estimate CSS size and rule count if available\n if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {\n const cssSize = ruleInfo.cssText.reduce(\n (total, css) => total + css.length,\n 0,\n );\n totalCssSize += cssSize;\n totalRulesDeleted += ruleInfo.cssText.length;\n }\n\n if (!rulesBySheet.has(sheetIndex)) {\n rulesBySheet.set(sheetIndex, []);\n }\n rulesBySheet.get(sheetIndex)!.push({ className, ruleInfo });\n }\n\n // Delete rules from each sheet (in reverse order to preserve indices)\n for (const [_sheetIndex, rulesInSheet] of rulesBySheet) {\n // Sort by rule index in descending order for safe deletion\n rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);\n\n for (const { className, ruleInfo } of rulesInSheet) {\n // SAFETY 1: Double-check refCount is still 0\n const currentRefCount = registry.refCounts.get(className) || 0;\n if (currentRefCount > 0) {\n // Class became active again; do not delete\n continue;\n }\n\n // SAFETY 2: Ensure rule wasn't replaced\n // Between scheduling and execution a class may have been replaced with a new RuleInfo\n const currentInfo = registry.rules.get(className);\n if (currentInfo !== ruleInfo) {\n // Rule was replaced; skip deletion of the old reference\n continue;\n }\n\n // SAFETY 3: Verify the sheet element is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || !sheetInfo.sheet) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the stylesheet itself is accessible\n const styleSheet = sheetInfo.sheet.sheet;\n if (!styleSheet) {\n // Stylesheet not available; skip this rule\n continue;\n }\n\n // SAFETY 5: Verify rule index is still within valid range\n const maxRuleIndex = styleSheet.cssRules.length - 1;\n const startIdx = ruleInfo.ruleIndex;\n const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;\n\n if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) {\n // Rule indices are out of bounds; skip this rule\n continue;\n }\n\n // All safety checks passed - proceed with deletion\n this.deleteRule(registry, ruleInfo);\n registry.rules.delete(className);\n registry.refCounts.delete(className);\n\n // Clean up cache key mappings that point to this className\n const keysToDelete: string[] = [];\n for (const [\n key,\n mappedClassName,\n ] of registry.cacheKeyToClassName.entries()) {\n if (mappedClassName === className) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n registry.cacheKeyToClassName.delete(key);\n }\n cleanedUpCount++;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.bulkCleanups++;\n registry.metrics.stylesCleanedUp += cleanedUpCount;\n\n // Add detailed cleanup stats to history\n registry.metrics.cleanupHistory.push({\n timestamp: cleanupStartTime,\n classesDeleted: cleanedUpCount,\n cssSize: totalCssSize,\n rulesDeleted: totalRulesDeleted,\n });\n }\n }\n\n /**\n * Get total number of rules across all sheets\n */\n getTotalRuleCount(registry: RootRegistry): number {\n return registry.sheets.reduce(\n (total, sheet) => total + sheet.ruleCount - sheet.holes.length,\n 0,\n );\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(registry: RootRegistry): string {\n const cssChunks: string[] = [];\n\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement.textContent) {\n cssChunks.push(styleElement.textContent);\n } else if (styleElement.sheet) {\n const rules = Array.from(styleElement.sheet.cssRules);\n cssChunks.push(rules.map((rule) => rule.cssText).join('\\n'));\n }\n } catch (error) {\n console.warn('Failed to read CSS from sheet:', error);\n }\n }\n\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(registry: RootRegistry): CacheMetrics | null {\n if (!registry.metrics) return null;\n\n // Calculate unusedHits on demand - only count CSS rules since keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n\n return {\n ...registry.metrics,\n unusedHits: unusedRulesCount,\n };\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(registry: RootRegistry): void {\n if (registry.metrics) {\n registry.metrics = {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n };\n }\n }\n\n /**\n * Convert keyframes steps to CSS string.\n * Public so the SSR collector can format keyframes without DOM access.\n * Returns both the CSS text and a combined declarations string for property type scanning.\n */\n stepsToCSS(steps: KeyframesSteps): {\n css: string;\n declarations: string;\n } {\n const rules: string[] = [];\n const allDeclarations: string[] = [];\n\n for (const [key, value] of Object.entries(steps)) {\n // Support raw CSS strings for backwards compatibility\n if (typeof value === 'string') {\n rules.push(`${key} { ${value.trim()} }`);\n allDeclarations.push(value.trim());\n continue;\n }\n\n // Treat value as a style map and process via tasty style handlers\n const styleMap = (value || {}) as StyleValueStateMap;\n\n // Build a deterministic handler queue based on present style keys\n const styleNames = Object.keys(styleMap).sort();\n const handlerQueue: StyleHandler[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n styleNames.forEach((styleName) => {\n let handlers = STYLE_HANDLER_MAP[styleName];\n if (!handlers) {\n // Create a default handler for unknown styles (maps to kebab-case CSS or custom props)\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n handlers.forEach((handler) => {\n if (!seenHandlers.has(handler)) {\n seenHandlers.add(handler);\n handlerQueue.push(handler);\n }\n });\n });\n\n // Accumulate declarations (ordered). We intentionally ignore `$` selector fan-out\n // and any responsive/state bindings for keyframes.\n const declarationPairs: { prop: string; value: string }[] = [];\n\n handlerQueue.forEach((handler) => {\n const lookup = handler.__lookupStyles;\n const filteredMap = lookup.reduce<StyleValueStateMap>((acc, name) => {\n const v = styleMap[name];\n if (v !== undefined) acc[name] = v;\n return acc;\n }, {});\n\n const result = handler(filteredMap);\n if (!result) return;\n\n const results = Array.isArray(result) ? result : [result];\n results.forEach((cssMap) => {\n if (!cssMap || typeof cssMap !== 'object') return;\n const { $: _$, ...props } = cssMap as CSSMap;\n\n Object.entries(props).forEach(([prop, val]) => {\n if (val == null || val === '') return;\n\n if (Array.isArray(val)) {\n // Multiple values for the same property -> emit in order\n val.forEach((v) => {\n if (v != null && v !== '') {\n declarationPairs.push({ prop, value: String(v) });\n }\n });\n } else {\n declarationPairs.push({ prop, value: String(val) });\n }\n });\n });\n });\n\n // Fallback: if nothing produced (e.g., empty object), generate empty block\n const declarations = declarationPairs\n .map((d) => `${d.prop}: ${d.value}`)\n .join('; ');\n\n rules.push(`${key} { ${declarations.trim()} }`);\n allDeclarations.push(declarations);\n }\n\n return { css: rules.join(' '), declarations: allDeclarations.join('; ') };\n }\n\n /**\n * Insert keyframes rule.\n * Returns the KeyframesInfo and the raw declarations string for property type scanning.\n */\n insertKeyframes(\n registry: RootRegistry,\n steps: KeyframesSteps,\n name: string,\n root: Document | ShadowRoot,\n ): { info: KeyframesInfo; declarations: string } | null {\n let targetSheet = this.findAvailableSheet(registry, root);\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const ruleIndex = this.findAvailableRuleIndex(targetSheet);\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n const { css: cssSteps, declarations } = this.stepsToCSS(steps);\n const fullRule = `@keyframes ${name} { ${cssSteps} }`;\n\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else {\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n }\n\n targetSheet.ruleCount++;\n\n return {\n info: {\n name,\n ruleIndex,\n sheetIndex,\n cssText: this.config.devMode ? fullRule : undefined,\n },\n declarations,\n };\n } catch (error) {\n console.warn('Failed to insert keyframes:', error);\n return null;\n }\n }\n\n /**\n * Delete keyframes rule\n */\n deleteKeyframes(registry: RootRegistry, info: KeyframesInfo): void {\n const sheet = registry.sheets[info.sheetIndex];\n if (!sheet) return;\n\n try {\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n if (\n info.ruleIndex >= 0 &&\n info.ruleIndex < styleSheet.cssRules.length\n ) {\n styleSheet.deleteRule(info.ruleIndex);\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n\n // Adjust indices for all other rules in the same sheet\n // This is critical - when a keyframe rule is deleted, all rules\n // with higher indices shift down by 1\n this.adjustIndicesAfterDeletion(\n registry,\n info.sheetIndex,\n info.ruleIndex,\n info.ruleIndex,\n 1,\n // Create a dummy RuleInfo to satisfy the function signature\n {\n className: '',\n ruleIndex: info.ruleIndex,\n sheetIndex: info.sheetIndex,\n } as RuleInfo,\n [info.ruleIndex],\n );\n }\n }\n } catch (error) {\n console.warn('Failed to delete keyframes:', error);\n }\n }\n\n /**\n * Clean up resources for a root\n */\n cleanup(root: Document | ShadowRoot): void {\n const registry = this.rootRegistries.get(root);\n\n if (!registry) {\n return;\n }\n\n // Remove all sheets\n for (const sheet of registry.sheets) {\n try {\n // Remove style element\n const styleElement = sheet.sheet;\n if (styleElement.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('Failed to cleanup sheet:', error);\n }\n }\n\n // Clear registry\n this.rootRegistries.delete(root);\n this.activeRoots.delete(root);\n\n // Clean up raw CSS style element\n const rawStyleElement = this.rawStyleElements.get(root);\n if (rawStyleElement?.parentNode) {\n rawStyleElement.parentNode.removeChild(rawStyleElement);\n }\n this.rawStyleElements.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Get or create a dedicated style element for raw CSS\n * Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts\n */\n private getOrCreateRawStyleElement(\n root: Document | ShadowRoot,\n ): HTMLStyleElement {\n let styleElement = this.rawStyleElements.get(root);\n\n if (!styleElement) {\n styleElement =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n styleElement.nonce = this.config.nonce;\n }\n\n styleElement.setAttribute('data-tasty-raw', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(styleElement);\n } else if ('appendChild' in root) {\n root.appendChild(styleElement);\n } else {\n document.head.appendChild(styleElement);\n }\n\n this.rawStyleElements.set(root, styleElement);\n this.rawCSSBlocks.set(root, new Map());\n }\n\n return styleElement;\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * Returns a dispose function to remove the injected CSS\n */\n injectRawCSS(css: string, root: Document | ShadowRoot): RawCSSResult {\n if (!css.trim()) {\n return {\n dispose: () => {\n /* noop */\n },\n };\n }\n\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n // Calculate offsets\n const currentContent = styleElement.textContent || '';\n const startOffset = currentContent.length;\n const cssWithNewline = (currentContent ? '\\n' : '') + css;\n const endOffset = startOffset + cssWithNewline.length;\n\n // Append CSS\n styleElement.textContent = currentContent + cssWithNewline;\n\n // Track the block\n const info: RawCSSInfo = {\n id,\n css,\n startOffset,\n endOffset,\n };\n blocksMap.set(id, info);\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const styleElement = this.rawStyleElements.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n\n if (!styleElement || !blocksMap) {\n return;\n }\n\n const info = blocksMap.get(id);\n if (!info) {\n return;\n }\n\n // Remove from tracking\n blocksMap.delete(id);\n\n // Rebuild the CSS content from remaining blocks\n // This is simpler and more reliable than trying to splice strings\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\n // Rebuild with remaining CSS blocks in order of their original insertion\n // Sort by original startOffset to maintain order\n remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);\n const newContent = remainingBlocks.map((block) => block.css).join('\\n');\n styleElement.textContent = newContent;\n\n // Update offsets for remaining blocks\n let offset = 0;\n for (const block of remainingBlocks) {\n block.startOffset = offset;\n block.endOffset = offset + block.css.length;\n offset = block.endOffset + 1; // +1 for newline\n }\n }\n }\n\n /**\n * Get the raw CSS content for SSR\n */\n getRawCSSText(root: Document | ShadowRoot): string {\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,eAAb,MAA0B;CACxB,iCAAyB,IAAI,SAA8C;;CAE3E,8BAAsB,IAAI,KAA4B;CACtD;;CAEA,mCAA2B,IAAI,SAG5B;;CAEH,+BAAuB,IAAI,SAGxB;;CAEH,gBAAwB;CA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AAK;EACpD,MAAM,YAAY,KAAK,aAAa,IAAI,KAAK;AAE7C,MAAI,CAAC,gBAAgB,CAAC,UACpB;AAIF,MAAI,CADS,UAAU,IAAI,GAAG,CAE5B;AAIF,YAAU,OAAO,GAAG;EAIpB,MAAM,kBAAkB,MAAM,KAAK,UAAU,QAAQ,CAAC;AAEtD,MAAI,gBAAgB,WAAW,EAC7B,cAAa,cAAc;OACtB;AAGL,mBAAgB,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,YAAY;AAE7D,gBAAa,cADM,gBAAgB,KAAK,UAAU,MAAM,IAAI,CAAC,KAAK,KAAK;GAIvE,IAAI,SAAS;AACb,QAAK,MAAM,SAAS,iBAAiB;AACnC,UAAM,cAAc;AACpB,UAAM,YAAY,SAAS,MAAM,IAAI;AACrC,aAAS,MAAM,YAAY;;;;;;;CAQjC,cAAc,MAAqC;AAEjD,SADqB,KAAK,iBAAiB,IAAI,KAAK,EAC/B,eAAe"}
1
+ {"version":3,"file":"sheet-manager.js","names":[],"sources":["../../src/injector/sheet-manager.ts"],"sourcesContent":["import { PropertyTypeResolver } from '../properties/property-type-resolver';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n KeyframesInfo,\n KeyframesSteps,\n RawCSSInfo,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n SheetInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\nimport type { CSSMap, StyleHandler, StyleValueStateMap } from '../utils/styles';\n\nexport class SheetManager {\n private rootRegistries = new WeakMap<Document | ShadowRoot, RootRegistry>();\n /** Strong set of active roots so background GC can iterate them all */\n private activeRoots = new Set<Document | ShadowRoot>();\n private config: StyleInjectorConfig;\n /** Dedicated style elements for raw CSS per root */\n private rawStyleElements = new WeakMap<\n Document | ShadowRoot,\n HTMLStyleElement\n >();\n /** Tracking for raw CSS blocks per root */\n private rawCSSBlocks = new WeakMap<\n Document | ShadowRoot,\n Map<string, RawCSSInfo>\n >();\n /** Counter for generating unique raw CSS IDs */\n private rawCSSCounter = 0;\n\n constructor(config: StyleInjectorConfig) {\n this.config = config;\n }\n\n /**\n * Get or create registry for a root (Document or ShadowRoot)\n */\n getRegistry(root: Document | ShadowRoot): RootRegistry {\n let registry = this.rootRegistries.get(root);\n\n if (!registry) {\n const metrics: CacheMetrics | undefined = this.config.devMode\n ? {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n }\n : undefined;\n\n registry = {\n sheets: [],\n refCounts: new Map(),\n rules: new Map(),\n cacheKeyToClassName: new Map(),\n ruleTextSet: new Set<string>(),\n metrics,\n keyframesCache: new Map(),\n keyframesNameToContent: new Map(),\n keyframesCounter: 0,\n injectedProperties: new Map<string, string>(),\n injectedFontFaces: new Set<string>(),\n injectedCounterStyles: new Set<string>(),\n globalRules: new Map(),\n propertyTypeResolver: new PropertyTypeResolver(),\n usageMap: new Map(),\n touchCount: 0,\n serverClassSyncIndex: 0,\n rscStylesScanned: false,\n } as unknown as RootRegistry;\n\n this.rootRegistries.set(root, registry);\n this.activeRoots.add(root);\n }\n\n return registry;\n }\n\n /** Return all roots with active registries (for background GC sweep). */\n getActiveRoots(): Iterable<Document | ShadowRoot> {\n return this.activeRoots;\n }\n\n /** Check whether any roots have active registries. */\n hasActiveRoots(): boolean {\n return this.activeRoots.size > 0;\n }\n\n /** Remove registries for ShadowRoots whose host has been detached from the DOM. */\n pruneDisconnectedRoots(): void {\n const toPrune: (Document | ShadowRoot)[] = [];\n for (const root of this.activeRoots) {\n if (root !== document && !(root as ShadowRoot).host?.isConnected) {\n toPrune.push(root);\n }\n }\n for (const root of toPrune) {\n this.cleanup(root);\n }\n }\n\n /**\n * Create a new stylesheet for the registry\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n const sheet = this.createStyleElement(root);\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n /**\n * Create a style element and append to document\n */\n private createStyleElement(root: Document | ShadowRoot): HTMLStyleElement {\n const style =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n style.nonce = this.config.nonce;\n }\n\n style.setAttribute('data-tasty', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(style);\n } else if ('appendChild' in root) {\n root.appendChild(style);\n } else {\n document.head.appendChild(style);\n }\n\n // Verify it was actually added - log only if there's a problem and we're not using forceTextInjection\n if (!style.isConnected && !this.config.forceTextInjection) {\n console.error('SheetManager: Style element failed to connect to DOM!', {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n });\n }\n\n return style;\n }\n\n /**\n * Insert CSS rules as a single block\n */\n insertRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n className: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Find or create a sheet with available space\n let targetSheet = this.findAvailableSheet(registry, root);\n\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n // Group rules by selector, at-rules, and startingStyle to combine declarations\n const groupedRules: StyleRule[] = [];\n const groupMap = new Map<\n string,\n {\n idx: number;\n selector: string;\n atRules?: string[];\n startingStyle?: boolean;\n declarations: string;\n }\n >();\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n flattenedRules.forEach((r) => {\n const key = `${atKey(r.atRules)}||${r.selector}||${r.startingStyle ? '1' : '0'}`;\n const existing = groupMap.get(key);\n if (existing) {\n // Append declarations, preserving order\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n idx: groupedRules.length,\n selector: r.selector,\n atRules: r.atRules,\n startingStyle: r.startingStyle,\n declarations: r.declarations,\n });\n groupedRules.push({ ...r });\n }\n });\n\n // Normalize groupedRules from map (with merged declarations)\n groupMap.forEach((val) => {\n groupedRules[val.idx] = {\n selector: val.selector,\n atRules: val.atRules,\n startingStyle: val.startingStyle,\n declarations: val.declarations,\n } as StyleRule;\n });\n\n // Insert grouped rules\n const insertedRuleTexts: string[] = [];\n const insertedIndices: number[] = []; // Track exact indices\n // Calculate rule index atomically right before insertion to prevent race conditions\n let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);\n let firstInsertedIndex: number | null = null;\n let lastInsertedIndex: number | null = null;\n\n for (const rule of groupedRules) {\n const declarations = rule.declarations;\n const innerContent = rule.startingStyle\n ? `@starting-style { ${declarations} }`\n : declarations;\n const baseRule = `${rule.selector} { ${innerContent} }`;\n\n // Wrap with at-rules if present\n let fullRule = baseRule;\n if (rule.atRules && rule.atRules.length > 0) {\n fullRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n baseRule,\n );\n }\n\n // Insert individual rule into style element\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n // Calculate index atomically for each rule to prevent concurrent insertion races\n const maxIndex = styleSheet.cssRules.length;\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);\n\n // Helper: split comma-separated selectors safely (ignores commas inside [] () \" ')\n const splitSelectorsSafely = (selectorList: string): string[] => {\n const parts: string[] = [];\n let buf = '';\n let depthSq = 0; // [] depth\n let depthPar = 0; // () depth\n let inStr: '\"' | \"'\" | '' = '';\n for (let i = 0; i < selectorList.length; i++) {\n const ch = selectorList[i];\n if (inStr) {\n if (ch === inStr && selectorList[i - 1] !== '\\\\') {\n inStr = '';\n }\n buf += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inStr = ch as '\"' | \"'\";\n buf += ch;\n continue;\n }\n if (ch === '[') depthSq++;\n else if (ch === ']') depthSq = Math.max(0, depthSq - 1);\n else if (ch === '(') depthPar++;\n else if (ch === ')') depthPar = Math.max(0, depthPar - 1);\n\n if (ch === ',' && depthSq === 0 && depthPar === 0) {\n const part = buf.trim();\n if (part) parts.push(part);\n buf = '';\n } else {\n buf += ch;\n }\n }\n const tail = buf.trim();\n if (tail) parts.push(tail);\n return parts;\n };\n\n try {\n styleSheet.insertRule(fullRule, safeIndex);\n // Update sheet ruleCount immediately to prevent concurrent race conditions\n targetSheet.ruleCount++;\n insertedIndices.push(safeIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;\n lastInsertedIndex = safeIndex;\n currentRuleIndex = safeIndex + 1;\n } catch (e) {\n // If the browser rejects the combined selector (e.g., vendor pseudo-elements),\n // try to split and insert each selector independently. Skip unsupported ones.\n const selectors = splitSelectorsSafely(rule.selector);\n if (selectors.length > 1) {\n let anyInserted = false;\n for (const sel of selectors) {\n const singleBase = `${sel} { ${declarations} }`;\n let singleRule = singleBase;\n if (rule.atRules && rule.atRules.length > 0) {\n singleRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n singleBase,\n );\n }\n\n try {\n // Calculate index atomically for each individual selector insertion\n const maxIdx = styleSheet.cssRules.length;\n const atomicIdx = this.findAvailableRuleIndex(targetSheet);\n const idx = Math.min(Math.max(0, atomicIdx), maxIdx);\n styleSheet.insertRule(singleRule, idx);\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(idx); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = idx;\n lastInsertedIndex = idx;\n currentRuleIndex = idx + 1;\n anyInserted = true;\n } catch (singleErr) {\n // Skip unsupported selector in this engine (e.g., ::-moz-selection in Blink)\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[tasty] Browser rejected CSS rule:',\n singleRule,\n singleErr,\n );\n }\n }\n }\n // If none inserted, continue without throwing to avoid aborting the whole batch\n if (!anyInserted) {\n // noop: all selectors invalid here; safe to skip\n }\n } else {\n // Single selector failed — skip it silently (likely unsupported in this engine)\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[tasty] Browser rejected CSS rule:', fullRule, e);\n }\n }\n }\n } else {\n // Use textContent (either as fallback or when forceTextInjection is enabled)\n // Calculate index atomically for textContent insertion too\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(atomicRuleIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;\n lastInsertedIndex = atomicRuleIndex;\n currentRuleIndex = atomicRuleIndex + 1;\n }\n\n // CRITICAL DEBUG: Verify the style element is in DOM only if there are issues and we're not using forceTextInjection\n if (!styleElement.parentNode && !this.config.forceTextInjection) {\n console.error(\n 'SheetManager: Style element is NOT in DOM! This is the problem!',\n {\n className,\n ruleIndex: currentRuleIndex,\n },\n );\n }\n\n // Dev-only: store cssText for debugging tools\n if (this.config.devMode) {\n insertedRuleTexts.push(fullRule);\n try {\n registry.ruleTextSet.add(fullRule);\n } catch {\n // noop: defensive in case ruleTextSet is unavailable\n }\n }\n // currentRuleIndex already adjusted above\n }\n\n // Sheet ruleCount is now updated immediately after each insertion\n // No need for deferred update logic\n\n if (insertedIndices.length === 0) {\n return null;\n }\n\n return {\n className,\n ruleIndex: firstInsertedIndex ?? 0,\n sheetIndex,\n cssText: this.config.devMode ? insertedRuleTexts : undefined,\n endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,\n indices: insertedIndices,\n };\n } catch (error) {\n console.warn('Failed to insert CSS rules:', error, {\n flattenedRules,\n className,\n });\n return null;\n }\n }\n\n /**\n * Insert global CSS rules\n */\n insertGlobalRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n globalKey: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Insert the rule using the same mechanism as regular rules\n const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);\n\n // Track global rules for index adjustment\n if (ruleInfo) {\n registry.globalRules.set(globalKey, ruleInfo);\n }\n\n return ruleInfo;\n }\n\n /**\n * Delete a global CSS rule by key\n */\n public deleteGlobalRule(registry: RootRegistry, globalKey: string): void {\n const ruleInfo = registry.globalRules.get(globalKey);\n if (!ruleInfo) {\n return;\n }\n\n // Delete the rule using the standard deletion mechanism\n this.deleteRule(registry, ruleInfo);\n\n // Remove from global rules tracking\n registry.globalRules.delete(globalKey);\n }\n\n /**\n * Adjust rule indices after deletion to account for shifting\n */\n private adjustIndicesAfterDeletion(\n registry: RootRegistry,\n sheetIndex: number,\n startIdx: number,\n endIdx: number,\n deleteCount: number,\n deletedRuleInfo: RuleInfo,\n deletedIndices?: number[],\n ): void {\n try {\n const sortedDeleted =\n deletedIndices && deletedIndices.length > 0\n ? [...deletedIndices].sort((a, b) => a - b)\n : null;\n const countDeletedBefore = (sorted: number[], idx: number): number => {\n let shift = 0;\n for (const delIdx of sorted) {\n if (delIdx < idx) shift++;\n else break;\n }\n return shift;\n };\n // Helper function to adjust a single RuleInfo\n const adjustRuleInfo = (info: RuleInfo): void => {\n if (info === deletedRuleInfo) return; // Skip the deleted rule\n if (info.sheetIndex !== sheetIndex) return; // Different sheet\n\n if (!info.indices || info.indices.length === 0) {\n return;\n }\n\n if (sortedDeleted) {\n // Adjust each index based on how many deleted indices are before it\n info.indices = info.indices.map((idx) => {\n return idx - countDeletedBefore(sortedDeleted, idx);\n });\n } else {\n // Contiguous deletion: shift indices after the deleted range\n info.indices = info.indices.map((idx) =>\n idx > endIdx ? Math.max(0, idx - deleteCount) : idx,\n );\n }\n\n // Update ruleIndex and endRuleIndex to match adjusted indices\n if (info.indices.length > 0) {\n info.ruleIndex = Math.min(...info.indices);\n info.endRuleIndex = Math.max(...info.indices);\n }\n };\n\n // Adjust active rules\n for (const info of registry.rules.values()) {\n adjustRuleInfo(info);\n }\n\n // Adjust global rules\n for (const info of registry.globalRules.values()) {\n adjustRuleInfo(info);\n }\n\n // No need to separately adjust unused rules since they're part of the rules Map\n\n // Adjust keyframes indices stored in cache\n for (const entry of registry.keyframesCache.values()) {\n const ki = entry.info as KeyframesInfo;\n if (ki.sheetIndex !== sheetIndex) continue;\n if (sortedDeleted) {\n const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);\n if (shift > 0) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);\n }\n } else if (ki.ruleIndex > endIdx) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);\n }\n }\n } catch {\n // Defensive: do not let index adjustments crash cleanup\n }\n }\n\n /**\n * Delete a CSS rule from the sheet\n */\n deleteRule(registry: RootRegistry, ruleInfo: RuleInfo): void {\n const sheet = registry.sheets[ruleInfo.sheetIndex];\n\n if (!sheet) {\n return;\n }\n\n try {\n const texts: string[] =\n this.config.devMode && Array.isArray(ruleInfo.cssText)\n ? ruleInfo.cssText.slice()\n : [];\n\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n const rules = styleSheet.cssRules;\n\n // Use exact indices if available, otherwise fall back to range\n if (ruleInfo.indices && ruleInfo.indices.length > 0) {\n // NEW: Delete using exact tracked indices\n const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a); // Sort descending\n const deletedIndices: number[] = [];\n\n for (const idx of sortedIndices) {\n if (idx >= 0 && idx < styleSheet.cssRules.length) {\n try {\n styleSheet.deleteRule(idx);\n deletedIndices.push(idx);\n } catch (e) {\n console.warn(`Failed to delete rule at index ${idx}:`, e);\n }\n }\n }\n\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\n // Adjust indices for all other rules\n if (deletedIndices.length > 0) {\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n Math.min(...deletedIndices),\n Math.max(...deletedIndices),\n deletedIndices.length,\n ruleInfo,\n deletedIndices,\n );\n }\n } else {\n // FALLBACK: Use old range-based deletion for backwards compatibility\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n rules.length - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n if (Number.isFinite(startIdx) && endIdx >= startIdx) {\n const deleteCount = endIdx - startIdx + 1;\n for (let idx = endIdx; idx >= startIdx; idx--) {\n if (idx < 0 || idx >= styleSheet.cssRules.length) continue;\n styleSheet.deleteRule(idx);\n }\n sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);\n\n // After deletion, all subsequent rule indices shift left by deleteCount.\n // We must adjust stored indices for all other RuleInfo within the same sheet.\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n startIdx,\n endIdx,\n deleteCount,\n ruleInfo,\n );\n }\n }\n }\n\n // Dev-only: remove cssText entries from validation set\n if (this.config.devMode && texts.length) {\n try {\n for (const text of texts) {\n registry.ruleTextSet.delete(text);\n }\n } catch {\n // noop\n }\n }\n } catch (error) {\n console.warn('Failed to delete CSS rule:', error);\n }\n }\n\n /**\n * Find a sheet with available space or return null\n */\n private findAvailableSheet(\n registry: RootRegistry,\n _root: Document | ShadowRoot,\n ): SheetInfo | null {\n const maxRules = this.config.maxRulesPerSheet;\n\n if (!maxRules) {\n // No limit, use the last sheet if it exists\n const lastSheet = registry.sheets[registry.sheets.length - 1];\n return lastSheet || null;\n }\n\n // Find sheet with space\n for (const sheet of registry.sheets) {\n if (sheet.ruleCount < maxRules) {\n return sheet;\n }\n }\n\n return null; // No available sheet found\n }\n\n /**\n * Find an available rule index in the sheet\n */\n findAvailableRuleIndex(sheet: SheetInfo): number {\n // Always append to the end - CSS doesn't have holes\n return sheet.ruleCount;\n }\n\n /**\n * Force cleanup of unused styles\n */\n public forceCleanup(registry: RootRegistry): void {\n this.performBulkCleanup(registry);\n }\n\n /**\n * Perform bulk cleanup of all unused styles (refCount = 0).\n */\n private performBulkCleanup(registry: RootRegistry): void {\n const cleanupStartTime = Date.now();\n\n // Calculate unused rules dynamically: rules that have refCount = 0\n // and are not tracked in usageMap (GC-kept styles must survive)\n const unusedClassNames = Array.from(registry.refCounts.entries())\n .filter(\n ([className, refCount]) =>\n refCount === 0 && !registry.usageMap.has(className),\n )\n .map(([className]) => className);\n\n if (unusedClassNames.length === 0) return;\n\n const selected = unusedClassNames\n .map((className) => {\n const ruleInfo = registry.rules.get(className);\n return ruleInfo ? { className, ruleInfo } : null;\n })\n .filter((entry): entry is NonNullable<typeof entry> => entry != null);\n\n let cleanedUpCount = 0;\n let totalCssSize = 0;\n let totalRulesDeleted = 0;\n\n // Group by sheet for efficient deletion\n const rulesBySheet = new Map<\n number,\n { className: string; ruleInfo: RuleInfo }[]\n >();\n\n // Calculate CSS size before deletion and group rules\n for (const { className, ruleInfo } of selected) {\n const sheetIndex = ruleInfo.sheetIndex;\n\n // Dev-only metrics: estimate CSS size and rule count if available\n if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {\n const cssSize = ruleInfo.cssText.reduce(\n (total, css) => total + css.length,\n 0,\n );\n totalCssSize += cssSize;\n totalRulesDeleted += ruleInfo.cssText.length;\n }\n\n if (!rulesBySheet.has(sheetIndex)) {\n rulesBySheet.set(sheetIndex, []);\n }\n rulesBySheet.get(sheetIndex)!.push({ className, ruleInfo });\n }\n\n // Delete rules from each sheet (in reverse order to preserve indices)\n for (const [_sheetIndex, rulesInSheet] of rulesBySheet) {\n // Sort by rule index in descending order for safe deletion\n rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);\n\n for (const { className, ruleInfo } of rulesInSheet) {\n // SAFETY 1: Double-check refCount is still 0\n const currentRefCount = registry.refCounts.get(className) || 0;\n if (currentRefCount > 0) {\n // Class became active again; do not delete\n continue;\n }\n\n // SAFETY 2: Ensure rule wasn't replaced\n // Between scheduling and execution a class may have been replaced with a new RuleInfo\n const currentInfo = registry.rules.get(className);\n if (currentInfo !== ruleInfo) {\n // Rule was replaced; skip deletion of the old reference\n continue;\n }\n\n // SAFETY 3: Verify the sheet element is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || !sheetInfo.sheet) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the stylesheet itself is accessible\n const styleSheet = sheetInfo.sheet.sheet;\n if (!styleSheet) {\n // Stylesheet not available; skip this rule\n continue;\n }\n\n // SAFETY 5: Verify rule index is still within valid range\n const maxRuleIndex = styleSheet.cssRules.length - 1;\n const startIdx = ruleInfo.ruleIndex;\n const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;\n\n if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) {\n // Rule indices are out of bounds; skip this rule\n continue;\n }\n\n // All safety checks passed - proceed with deletion\n this.deleteRule(registry, ruleInfo);\n registry.rules.delete(className);\n registry.refCounts.delete(className);\n\n // Clean up cache key mappings that point to this className\n const keysToDelete: string[] = [];\n for (const [\n key,\n mappedClassName,\n ] of registry.cacheKeyToClassName.entries()) {\n if (mappedClassName === className) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n registry.cacheKeyToClassName.delete(key);\n }\n cleanedUpCount++;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.bulkCleanups++;\n registry.metrics.stylesCleanedUp += cleanedUpCount;\n\n // Add detailed cleanup stats to history\n registry.metrics.cleanupHistory.push({\n timestamp: cleanupStartTime,\n classesDeleted: cleanedUpCount,\n cssSize: totalCssSize,\n rulesDeleted: totalRulesDeleted,\n });\n }\n }\n\n /**\n * Get total number of rules across all sheets\n */\n getTotalRuleCount(registry: RootRegistry): number {\n return registry.sheets.reduce(\n (total, sheet) => total + sheet.ruleCount - sheet.holes.length,\n 0,\n );\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(registry: RootRegistry): string {\n const cssChunks: string[] = [];\n\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement.textContent) {\n cssChunks.push(styleElement.textContent);\n } else if (styleElement.sheet) {\n const rules = Array.from(styleElement.sheet.cssRules);\n cssChunks.push(rules.map((rule) => rule.cssText).join('\\n'));\n }\n } catch (error) {\n console.warn('Failed to read CSS from sheet:', error);\n }\n }\n\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(registry: RootRegistry): CacheMetrics | null {\n if (!registry.metrics) return null;\n\n // Calculate unusedHits on demand - only count CSS rules since keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n\n return {\n ...registry.metrics,\n unusedHits: unusedRulesCount,\n };\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(registry: RootRegistry): void {\n if (registry.metrics) {\n registry.metrics = {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n };\n }\n }\n\n /**\n * Convert keyframes steps to CSS string.\n * Public so the SSR collector can format keyframes without DOM access.\n * Returns both the CSS text and a combined declarations string for property type scanning.\n */\n stepsToCSS(steps: KeyframesSteps): {\n css: string;\n declarations: string;\n } {\n const rules: string[] = [];\n const allDeclarations: string[] = [];\n\n for (const [key, value] of Object.entries(steps)) {\n // Support raw CSS strings for backwards compatibility\n if (typeof value === 'string') {\n rules.push(`${key} { ${value.trim()} }`);\n allDeclarations.push(value.trim());\n continue;\n }\n\n // Treat value as a style map and process via tasty style handlers\n const styleMap = (value || {}) as StyleValueStateMap;\n\n // Build a deterministic handler queue based on present style keys\n const styleNames = Object.keys(styleMap).sort();\n const handlerQueue: StyleHandler[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n styleNames.forEach((styleName) => {\n let handlers = STYLE_HANDLER_MAP[styleName];\n if (!handlers) {\n // Create a default handler for unknown styles (maps to kebab-case CSS or custom props)\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n handlers.forEach((handler) => {\n if (!seenHandlers.has(handler)) {\n seenHandlers.add(handler);\n handlerQueue.push(handler);\n }\n });\n });\n\n // Accumulate declarations (ordered). We intentionally ignore `$` selector fan-out\n // and any responsive/state bindings for keyframes.\n const declarationPairs: { prop: string; value: string }[] = [];\n\n handlerQueue.forEach((handler) => {\n const lookup = handler.__lookupStyles;\n const filteredMap = lookup.reduce<StyleValueStateMap>((acc, name) => {\n const v = styleMap[name];\n if (v !== undefined) acc[name] = v;\n return acc;\n }, {});\n\n const result = handler(filteredMap);\n if (!result) return;\n\n const results = Array.isArray(result) ? result : [result];\n results.forEach((cssMap) => {\n if (!cssMap || typeof cssMap !== 'object') return;\n const { $: _$, ...props } = cssMap as CSSMap;\n\n Object.entries(props).forEach(([prop, val]) => {\n if (val == null || val === '') return;\n\n if (Array.isArray(val)) {\n // Multiple values for the same property -> emit in order\n val.forEach((v) => {\n if (v != null && v !== '') {\n declarationPairs.push({ prop, value: String(v) });\n }\n });\n } else {\n declarationPairs.push({ prop, value: String(val) });\n }\n });\n });\n });\n\n // Fallback: if nothing produced (e.g., empty object), generate empty block\n const declarations = declarationPairs\n .map((d) => `${d.prop}: ${d.value}`)\n .join('; ');\n\n rules.push(`${key} { ${declarations.trim()} }`);\n allDeclarations.push(declarations);\n }\n\n return { css: rules.join(' '), declarations: allDeclarations.join('; ') };\n }\n\n /**\n * Insert keyframes rule.\n * Returns the KeyframesInfo and the raw declarations string for property type scanning.\n */\n insertKeyframes(\n registry: RootRegistry,\n steps: KeyframesSteps,\n name: string,\n root: Document | ShadowRoot,\n ): { info: KeyframesInfo; declarations: string } | null {\n let targetSheet = this.findAvailableSheet(registry, root);\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const ruleIndex = this.findAvailableRuleIndex(targetSheet);\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n const { css: cssSteps, declarations } = this.stepsToCSS(steps);\n const fullRule = `@keyframes ${name} { ${cssSteps} }`;\n\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else {\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n }\n\n targetSheet.ruleCount++;\n\n return {\n info: {\n name,\n ruleIndex,\n sheetIndex,\n cssText: this.config.devMode ? fullRule : undefined,\n },\n declarations,\n };\n } catch (error) {\n console.warn('Failed to insert keyframes:', error);\n return null;\n }\n }\n\n /**\n * Delete keyframes rule\n */\n deleteKeyframes(registry: RootRegistry, info: KeyframesInfo): void {\n const sheet = registry.sheets[info.sheetIndex];\n if (!sheet) return;\n\n try {\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n if (\n info.ruleIndex >= 0 &&\n info.ruleIndex < styleSheet.cssRules.length\n ) {\n styleSheet.deleteRule(info.ruleIndex);\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n\n // Adjust indices for all other rules in the same sheet\n // This is critical - when a keyframe rule is deleted, all rules\n // with higher indices shift down by 1\n this.adjustIndicesAfterDeletion(\n registry,\n info.sheetIndex,\n info.ruleIndex,\n info.ruleIndex,\n 1,\n // Create a dummy RuleInfo to satisfy the function signature\n {\n className: '',\n ruleIndex: info.ruleIndex,\n sheetIndex: info.sheetIndex,\n } as RuleInfo,\n [info.ruleIndex],\n );\n }\n }\n } catch (error) {\n console.warn('Failed to delete keyframes:', error);\n }\n }\n\n /**\n * Clean up resources for a root\n */\n cleanup(root: Document | ShadowRoot): void {\n const registry = this.rootRegistries.get(root);\n\n if (!registry) {\n return;\n }\n\n // Remove all sheets\n for (const sheet of registry.sheets) {\n try {\n // Remove style element\n const styleElement = sheet.sheet;\n if (styleElement.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('Failed to cleanup sheet:', error);\n }\n }\n\n // Clear registry\n this.rootRegistries.delete(root);\n this.activeRoots.delete(root);\n\n // Clean up raw CSS style element\n const rawStyleElement = this.rawStyleElements.get(root);\n if (rawStyleElement?.parentNode) {\n rawStyleElement.parentNode.removeChild(rawStyleElement);\n }\n this.rawStyleElements.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Get or create a dedicated style element for raw CSS\n * Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts\n */\n private getOrCreateRawStyleElement(\n root: Document | ShadowRoot,\n ): HTMLStyleElement {\n let styleElement = this.rawStyleElements.get(root);\n\n if (!styleElement) {\n styleElement =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n styleElement.nonce = this.config.nonce;\n }\n\n styleElement.setAttribute('data-tasty-raw', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(styleElement);\n } else if ('appendChild' in root) {\n root.appendChild(styleElement);\n } else {\n document.head.appendChild(styleElement);\n }\n\n this.rawStyleElements.set(root, styleElement);\n this.rawCSSBlocks.set(root, new Map());\n }\n\n return styleElement;\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * Returns a dispose function to remove the injected CSS\n */\n injectRawCSS(css: string, root: Document | ShadowRoot): RawCSSResult {\n if (!css.trim()) {\n return {\n dispose: () => {\n /* noop */\n },\n };\n }\n\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n // Calculate offsets\n const currentContent = styleElement.textContent || '';\n const startOffset = currentContent.length;\n const cssWithNewline = (currentContent ? '\\n' : '') + css;\n const endOffset = startOffset + cssWithNewline.length;\n\n // Append CSS\n styleElement.textContent = currentContent + cssWithNewline;\n\n // Track the block\n const info: RawCSSInfo = {\n id,\n css,\n startOffset,\n endOffset,\n };\n blocksMap.set(id, info);\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const styleElement = this.rawStyleElements.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n\n if (!styleElement || !blocksMap) {\n return;\n }\n\n const info = blocksMap.get(id);\n if (!info) {\n return;\n }\n\n // Remove from tracking\n blocksMap.delete(id);\n\n // Rebuild the CSS content from remaining blocks\n // This is simpler and more reliable than trying to splice strings\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\n // Rebuild with remaining CSS blocks in order of their original insertion\n // Sort by original startOffset to maintain order\n remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);\n const newContent = remainingBlocks.map((block) => block.css).join('\\n');\n styleElement.textContent = newContent;\n\n // Update offsets for remaining blocks\n let offset = 0;\n for (const block of remainingBlocks) {\n block.startOffset = offset;\n block.endOffset = offset + block.css.length;\n offset = block.endOffset + 1; // +1 for newline\n }\n }\n }\n\n /**\n * Get the raw CSS content for SSR\n */\n getRawCSSText(root: Document | ShadowRoot): string {\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,eAAb,MAA0B;CACxB,iCAAyB,IAAI,SAA8C;;CAE3E,8BAAsB,IAAI,KAA4B;CACtD;;CAEA,mCAA2B,IAAI,SAG5B;;CAEH,+BAAuB,IAAI,SAGxB;;CAEH,gBAAwB;CAExB,YAAY,QAA6B;AACvC,OAAK,SAAS;;;;;CAMhB,YAAY,MAA2C;EACrD,IAAI,WAAW,KAAK,eAAe,IAAI,KAAK;AAE5C,MAAI,CAAC,UAAU;GACb,MAAM,UAAoC,KAAK,OAAO,UAClD;IACE,MAAM;IACN,QAAQ;IACR,cAAc;IACd,iBAAiB;IACjB,aAAa;IACb,iBAAiB;IACjB,gBAAgB,EAAE;IAClB,WAAW,KAAK,KAAK;IACtB,GACD,KAAA;AAEJ,cAAW;IACT,QAAQ,EAAE;IACV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Y;AAE7D,gBAAa,cADM,gBAAgB,KAAK,UAAU,MAAM,IAAI,CAAC,KAAK,KAAK;GAIvE,IAAI,SAAS;AACb,QAAK,MAAM,SAAS,iBAAiB;AACnC,UAAM,cAAc;AACpB,UAAM,YAAY,SAAS,MAAM,IAAI;AACrC,aAAS,MAAM,YAAY;;;;;;;CAQjC,cAAc,MAAqC;AAEjD,SADqB,KAAK,iBAAiB,IAAI,KAAK,EAC/B,eAAe"}
@@ -2,6 +2,11 @@ import { PropertyTypeResolver } from "../properties/property-type-resolver.js";
2
2
  import { StyleResult } from "../pipeline/index.js";
3
3
 
4
4
  //#region src/injector/types.d.ts
5
+ declare global {
6
+ interface Window {
7
+ __TASTY__?: string[];
8
+ }
9
+ }
5
10
  interface InjectResult {
6
11
  className: string;
7
12
  dispose: () => void;
@@ -110,8 +115,6 @@ interface RootRegistry {
110
115
  ruleTextSet: Set<string>;
111
116
  /** Performance metrics (optional) */
112
117
  metrics?: CacheMetrics;
113
- /** Counter for generating sequential class names like t0, t1, t2... */
114
- classCounter: number;
115
118
  /** Keyframes cache by content hash -> entry */
116
119
  keyframesCache: Map<string, KeyframesCacheEntry>;
117
120
  /** Keyframes name to content hash mapping for collision detection */
@@ -132,6 +135,10 @@ interface RootRegistry {
132
135
  usageMap: Map<string, StyleUsage>;
133
136
  /** Touch counter for scheduling GC (per-root) */
134
137
  touchCount: number;
138
+ /** How many entries from `window.__TASTY__` have been synced into this registry */
139
+ serverClassSyncIndex: number;
140
+ /** Whether `<style data-tasty-rsc>` tags have been scanned for class names */
141
+ rscStylesScanned: boolean;
135
142
  }
136
143
  type StyleRule = StyleResult;
137
144
  interface KeyframesInfo {
@@ -1,4 +1,4 @@
1
- import { and, isCompoundCondition, not, trueCondition } from "./conditions.js";
1
+ import { and, isCompoundCondition, not, or, trueCondition } from "./conditions.js";
2
2
  import { simplifyCondition } from "./simplify.js";
3
3
  //#region src/pipeline/exclusive.ts
4
4
  /**
@@ -66,6 +66,61 @@ function parseStyleEntries(styleKey, valueMap, parseCondition) {
66
66
  return entries;
67
67
  }
68
68
  /**
69
+ * Merge parsed entries that share the same value.
70
+ *
71
+ * When multiple state keys map to the same value, their conditions can
72
+ * be combined with OR and treated as a single entry. This must happen
73
+ * **before** exclusive expansion and OR branch splitting to avoid
74
+ * combinatorial explosion and duplicate CSS output.
75
+ *
76
+ * Example: `{ '@dark': 'red', '@dark & @hc': 'red' }` merges into a
77
+ * single entry with condition `@dark | (@dark & @hc)` = `@dark`.
78
+ *
79
+ * Entries are ordered highest-priority-first. The merged entry keeps the
80
+ * highest priority of the group.
81
+ */
82
+ function mergeEntriesByValue(entries) {
83
+ if (entries.length <= 1) return entries;
84
+ const groups = /* @__PURE__ */ new Map();
85
+ for (const entry of entries) {
86
+ const valueKey = serializeValue(entry.value);
87
+ const group = groups.get(valueKey);
88
+ if (group) {
89
+ group.entries.push(entry);
90
+ group.maxPriority = Math.max(group.maxPriority, entry.priority);
91
+ } else groups.set(valueKey, {
92
+ entries: [entry],
93
+ maxPriority: entry.priority
94
+ });
95
+ }
96
+ if (groups.size === entries.length) return entries;
97
+ const merged = [];
98
+ for (const [, group] of groups) {
99
+ if (group.entries.length === 1) {
100
+ merged.push(group.entries[0]);
101
+ continue;
102
+ }
103
+ const combinedCondition = simplifyCondition(or(...group.entries.map((e) => e.condition)));
104
+ const combinedStateKey = group.entries.map((e) => e.stateKey).join(" | ");
105
+ const hasDefault = group.entries.some((e) => e.condition.kind === "true");
106
+ const minPriority = Math.min(...group.entries.map((e) => e.priority));
107
+ merged.push({
108
+ styleKey: group.entries[0].styleKey,
109
+ stateKey: combinedStateKey,
110
+ value: group.entries[0].value,
111
+ condition: combinedCondition,
112
+ priority: hasDefault ? minPriority : group.maxPriority
113
+ });
114
+ }
115
+ merged.sort((a, b) => b.priority - a.priority);
116
+ return merged;
117
+ }
118
+ function serializeValue(value) {
119
+ if (value === null || value === void 0) return "null";
120
+ if (typeof value === "string" || typeof value === "number") return String(value);
121
+ return JSON.stringify(value);
122
+ }
123
+ /**
69
124
  * Check if a value is a style value mapping (object with state keys)
70
125
  */
71
126
  function isValueMapping(value) {
@@ -225,6 +280,6 @@ function expandExclusiveConditionOrs(entry) {
225
280
  return result;
226
281
  }
227
282
  //#endregion
228
- export { buildExclusiveConditions, expandExclusiveOrs, expandOrConditions, isValueMapping, parseStyleEntries };
283
+ export { buildExclusiveConditions, expandExclusiveOrs, expandOrConditions, isValueMapping, mergeEntriesByValue, parseStyleEntries };
229
284
 
230
285
  //# sourceMappingURL=exclusive.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"exclusive.js","names":[],"sources":["../../src/pipeline/exclusive.ts"],"sourcesContent":["/**\n * Exclusive Condition Builder\n *\n * Transforms parsed style entries into exclusive conditions.\n * Each entry's condition is ANDed with the negation of all higher-priority conditions,\n * ensuring exactly one condition matches at any given time.\n */\n\nimport type { StyleValue } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, isCompoundCondition, not, trueCondition } from './conditions';\nimport { simplifyCondition } from './simplify';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed style entry with condition\n */\nexport interface ParsedStyleEntry {\n styleKey: string; // e.g., 'padding', 'fill'\n stateKey: string; // Original key: '', 'compact', '@media(w < 768px)'\n value: StyleValue; // The style value (before handler processing)\n condition: ConditionNode; // Parsed condition tree\n priority: number; // Order in original object (higher = higher priority)\n}\n\n/**\n * Style entry with exclusive condition\n */\nexport interface ExclusiveStyleEntry extends ParsedStyleEntry {\n exclusiveCondition: ConditionNode; // condition & !higherPriorityConditions\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Build exclusive conditions for a list of parsed style entries.\n *\n * The entries should be ordered by priority (highest priority first).\n *\n * For each entry, we compute:\n * exclusiveCondition = condition & !prior[0] & !prior[1] & ...\n *\n * This ensures exactly one condition matches at any time.\n *\n * Example:\n * Input (ordered highest to lowest priority):\n * A: value1 (priority 2)\n * B: value2 (priority 1)\n * C: value3 (priority 0)\n *\n * Output:\n * A: A\n * B: B & !A\n * C: C & !A & !B\n *\n * @param entries Parsed style entries ordered by priority (highest first)\n * @returns Entries with exclusive conditions, filtered to remove impossible ones\n */\nexport function buildExclusiveConditions(\n entries: ParsedStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n const priorConditions: ConditionNode[] = [];\n\n for (const entry of entries) {\n // Build: condition & !prior[0] & !prior[1] & ...\n let exclusive: ConditionNode = entry.condition;\n\n for (const prior of priorConditions) {\n // Skip negating \"always true\" (default state) - it would become \"always false\"\n if (prior.kind !== 'true') {\n exclusive = and(exclusive, not(prior));\n }\n }\n\n // Simplify the exclusive condition\n const simplified = simplifyCondition(exclusive);\n\n // Skip impossible conditions (simplified to FALSE)\n if (simplified.kind === 'false') {\n continue;\n }\n\n result.push({\n ...entry,\n exclusiveCondition: simplified,\n });\n\n // Add non-default conditions to prior list for subsequent entries\n if (entry.condition.kind !== 'true') {\n priorConditions.push(entry.condition);\n }\n }\n\n return result;\n}\n\n/**\n * Parse style entries from a value mapping object.\n *\n * @param styleKey The style key (e.g., 'padding')\n * @param valueMap The value mapping { '': '2x', 'compact': '1x', '@media(w < 768px)': '0.5x' }\n * @param parseCondition Function to parse state keys into conditions\n * @returns Parsed entries ordered by priority (highest first)\n */\nexport function parseStyleEntries(\n styleKey: string,\n valueMap: Record<string, StyleValue>,\n parseCondition: (stateKey: string) => ConditionNode,\n): ParsedStyleEntry[] {\n const entries: ParsedStyleEntry[] = [];\n const keys = Object.keys(valueMap);\n\n keys.forEach((stateKey, index) => {\n const value = valueMap[stateKey];\n const condition =\n stateKey === '' ? trueCondition() : parseCondition(stateKey);\n\n entries.push({\n styleKey,\n stateKey,\n value,\n condition,\n priority: index,\n });\n });\n\n // Reverse so highest priority (last in object) comes first for exclusive building\n // buildExclusiveConditions expects highest priority first\n entries.reverse();\n\n return entries;\n}\n\n/**\n * Check if a value is a style value mapping (object with state keys)\n */\nexport function isValueMapping(\n value: StyleValue | Record<string, StyleValue>,\n): value is Record<string, StyleValue> {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n );\n}\n\n// ============================================================================\n// OR Expansion\n// ============================================================================\n\n/**\n * Expand OR conditions in parsed entries into multiple exclusive entries.\n *\n * For an entry with condition `A | B | C`, this creates 3 entries:\n * - condition: A\n * - condition: B & !A\n * - condition: C & !A & !B\n *\n * This ensures OR branches are mutually exclusive BEFORE the main\n * exclusive condition building pass.\n *\n * @param entries Parsed entries (may contain OR conditions)\n * @returns Expanded entries with OR branches made exclusive\n */\nexport function expandOrConditions(\n entries: ParsedStyleEntry[],\n): ParsedStyleEntry[] {\n const result: ParsedStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandSingleEntry(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Expand a single entry's OR condition into multiple exclusive entries\n */\nfunction expandSingleEntry(entry: ParsedStyleEntry): ParsedStyleEntry[] {\n const orBranches = collectOrBranches(entry.condition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Make each OR branch exclusive from prior branches\n const result: ParsedStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[${i}]`, // Mark as expanded branch\n condition: simplified,\n // Keep same priority - all branches from same entry have same priority\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n\n/**\n * Collect top-level OR branches from a condition.\n *\n * For `A | B | C`, returns [A, B, C]\n * For `A & B`, returns [A & B] (single branch)\n * For `A | (B & C)`, returns [A, B & C]\n */\nfunction collectOrBranches(condition: ConditionNode): ConditionNode[] {\n if (condition.kind === 'true' || condition.kind === 'false') {\n return [condition];\n }\n\n if (isCompoundCondition(condition) && condition.operator === 'OR') {\n // Flatten nested ORs\n const branches: ConditionNode[] = [];\n for (const child of condition.children) {\n branches.push(...collectOrBranches(child));\n }\n return branches;\n }\n\n // Not an OR - return as single branch\n return [condition];\n}\n\n// ============================================================================\n// Post-Build OR Expansion (for De Morgan ORs)\n// ============================================================================\n\n/**\n * Expand OR conditions in exclusive entries AFTER buildExclusiveConditions.\n *\n * This handles ORs that arise from De Morgan expansion during negation:\n * !(A & B) = !A | !B\n *\n * These ORs need to be made exclusive to avoid overlapping CSS rules:\n * !A | !B → !A | (A & !B)\n *\n * This is logically equivalent but ensures each branch has proper context.\n *\n * Example:\n * Input: { \"\": V1, \"@supports(...) & :has()\": V2 }\n * V2's exclusive = @supports & :has\n * V1's exclusive = !(@supports & :has) = !@supports | !:has\n *\n * Without this fix: V1 gets two rules:\n * - @supports (not ...) → V1 ✓\n * - :not(:has()) → V1 ✗ (missing @supports context!)\n *\n * With this fix: V1 gets two exclusive rules:\n * - @supports (not ...) → V1 ✓\n * - @supports (...) { :not(:has()) } → V1 ✓ (proper context!)\n */\nexport function expandExclusiveOrs(\n entries: ExclusiveStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandExclusiveConditionOrs(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Check if a condition involves at-rules (media, container, supports, starting)\n */\nfunction hasAtRuleContext(node: ConditionNode): boolean {\n if (node.kind === 'true' || node.kind === 'false') {\n return false;\n }\n\n if (node.kind === 'state') {\n // These condition types generate at-rules\n return (\n node.type === 'media' ||\n node.type === 'container' ||\n node.type === 'supports' ||\n node.type === 'starting'\n );\n }\n\n if (node.kind === 'compound') {\n return node.children.some(hasAtRuleContext);\n }\n\n return false;\n}\n\n/**\n * Sort OR branches to prioritize at-rule conditions first.\n *\n * This is critical for correct CSS generation. For `!A | !B` where A is at-rule\n * and B is modifier, we want:\n * - Branch 0: !A (at-rule negation - covers \"no @supports/media\" case)\n * - Branch 1: A & !B (modifier negation with at-rule context)\n *\n * If we process in wrong order (!B first), we'd get:\n * - Branch 0: !B (modifier negation WITHOUT at-rule context - WRONG!)\n * - Branch 1: B & !A (at-rule negation with modifier - incomplete coverage)\n */\nfunction sortOrBranchesForExpansion(\n branches: ConditionNode[],\n): ConditionNode[] {\n return [...branches].sort((a, b) => {\n const aHasAtRule = hasAtRuleContext(a);\n const bHasAtRule = hasAtRuleContext(b);\n\n // At-rule conditions come first\n if (aHasAtRule && !bHasAtRule) return -1;\n if (!aHasAtRule && bHasAtRule) return 1;\n\n // Same type - keep original order (stable sort)\n return 0;\n });\n}\n\n/**\n * Expand ORs in a single entry's exclusive condition\n */\nfunction expandExclusiveConditionOrs(\n entry: ExclusiveStyleEntry,\n): ExclusiveStyleEntry[] {\n let orBranches = collectOrBranches(entry.exclusiveCondition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Sort branches so at-rule conditions come first\n // This ensures proper context inheritance during expansion\n orBranches = sortOrBranchesForExpansion(orBranches);\n\n // Make each OR branch exclusive from prior branches\n const result: ExclusiveStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n // This transforms: !A | !B → !A, !B & !!A = !A, (A & !B)\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations and clean up double negations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[or:${i}]`, // Mark as expanded OR branch\n exclusiveCondition: simplified,\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,yBACd,SACuB;CACvB,MAAM,SAAgC,EAAE;CACxC,MAAM,kBAAmC,EAAE;AAE3C,MAAK,MAAM,SAAS,SAAS;EAE3B,IAAI,YAA2B,MAAM;AAErC,OAAK,MAAM,SAAS,gBAElB,KAAI,MAAM,SAAS,OACjB,aAAY,IAAI,WAAW,IAAI,MAAM,CAAC;EAK1C,MAAM,aAAa,kBAAkB,UAAU;AAG/C,MAAI,WAAW,SAAS,QACtB;AAGF,SAAO,KAAK;GACV,GAAG;GACH,oBAAoB;GACrB,CAAC;AAGF,MAAI,MAAM,UAAU,SAAS,OAC3B,iBAAgB,KAAK,MAAM,UAAU;;AAIzC,QAAO;;;;;;;;;;AAWT,SAAgB,kBACd,UACA,UACA,gBACoB;CACpB,MAAM,UAA8B,EAAE;AACzB,QAAO,KAAK,SAAS,CAE7B,SAAS,UAAU,UAAU;EAChC,MAAM,QAAQ,SAAS;EACvB,MAAM,YACJ,aAAa,KAAK,eAAe,GAAG,eAAe,SAAS;AAE9D,UAAQ,KAAK;GACX;GACA;GACA;GACA;GACA,UAAU;GACX,CAAC;GACF;AAIF,SAAQ,SAAS;AAEjB,QAAO;;;;;AAMT,SAAgB,eACd,OACqC;AACrC,QACE,UAAU,QACV,OAAO,UAAU,YACjB,CAAC,MAAM,QAAQ,MAAM,IACrB,EAAE,iBAAiB;;;;;;;;;;;;;;;;AAsBvB,SAAgB,mBACd,SACoB;CACpB,MAAM,SAA6B,EAAE;AAErC,MAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,WAAW,kBAAkB,MAAM;AACzC,SAAO,KAAK,GAAG,SAAS;;AAG1B,QAAO;;;;;AAMT,SAAS,kBAAkB,OAA6C;CACtE,MAAM,aAAa,kBAAkB,MAAM,UAAU;AAGrD,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K,iBAAiB;AAG7C,QAAO;;;;;;;;;;;;;;AAeT,SAAS,2BACP,UACiB;AACjB,QAAO,CAAC,GAAG,SAAS,CAAC,MAAM,GAAG,MAAM;EAClC,MAAM,aAAa,iBAAiB,EAAE;EACtC,MAAM,aAAa,iBAAiB,EAAE;AAGtC,MAAI,cAAc,CAAC,WAAY,QAAO;AACtC,MAAI,CAAC,cAAc,WAAY,QAAO;AAGtC,SAAO;GACP;;;;;AAMJ,SAAS,4BACP,OACuB;CACvB,IAAI,aAAa,kBAAkB,MAAM,mBAAmB;AAG5D,KAAI,WAAW,UAAU,EACvB,QAAO,CAAC,MAAM;AAKhB,cAAa,2BAA2B,WAAW;CAGnD,MAAM,SAAgC,EAAE;CACxC,MAAM,gBAAiC,EAAE;AAEzC,MAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;EAC1C,MAAM,SAAS,WAAW;EAI1B,IAAI,kBAAiC;AACrC,OAAK,MAAM,SAAS,cAClB,mBAAkB,IAAI,iBAAiB,IAAI,MAAM,CAAC;EAIpD,MAAM,aAAa,kBAAkB,gBAAgB;AAGrD,MAAI,WAAW,SAAS,SAAS;AAC/B,iBAAc,KAAK,OAAO;AAC1B;;AAGF,SAAO,KAAK;GACV,GAAG;GACH,UAAU,GAAG,MAAM,SAAS,MAAM,EAAE;GACpC,oBAAoB;GACrB,CAAC;AAEF,gBAAc,KAAK,OAAO;;AAG5B,QAAO"}
1
+ {"version":3,"file":"exclusive.js","names":[],"sources":["../../src/pipeline/exclusive.ts"],"sourcesContent":["/**\n * Exclusive Condition Builder\n *\n * Transforms parsed style entries into exclusive conditions.\n * Each entry's condition is ANDed with the negation of all higher-priority conditions,\n * ensuring exactly one condition matches at any given time.\n */\n\nimport type { StyleValue } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, isCompoundCondition, not, or, trueCondition } from './conditions';\nimport { simplifyCondition } from './simplify';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed style entry with condition\n */\nexport interface ParsedStyleEntry {\n styleKey: string; // e.g., 'padding', 'fill'\n stateKey: string; // Original key: '', 'compact', '@media(w < 768px)'\n value: StyleValue; // The style value (before handler processing)\n condition: ConditionNode; // Parsed condition tree\n priority: number; // Order in original object (higher = higher priority)\n}\n\n/**\n * Style entry with exclusive condition\n */\nexport interface ExclusiveStyleEntry extends ParsedStyleEntry {\n exclusiveCondition: ConditionNode; // condition & !higherPriorityConditions\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Build exclusive conditions for a list of parsed style entries.\n *\n * The entries should be ordered by priority (highest priority first).\n *\n * For each entry, we compute:\n * exclusiveCondition = condition & !prior[0] & !prior[1] & ...\n *\n * This ensures exactly one condition matches at any time.\n *\n * Example:\n * Input (ordered highest to lowest priority):\n * A: value1 (priority 2)\n * B: value2 (priority 1)\n * C: value3 (priority 0)\n *\n * Output:\n * A: A\n * B: B & !A\n * C: C & !A & !B\n *\n * @param entries Parsed style entries ordered by priority (highest first)\n * @returns Entries with exclusive conditions, filtered to remove impossible ones\n */\nexport function buildExclusiveConditions(\n entries: ParsedStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n const priorConditions: ConditionNode[] = [];\n\n for (const entry of entries) {\n // Build: condition & !prior[0] & !prior[1] & ...\n let exclusive: ConditionNode = entry.condition;\n\n for (const prior of priorConditions) {\n // Skip negating \"always true\" (default state) - it would become \"always false\"\n if (prior.kind !== 'true') {\n exclusive = and(exclusive, not(prior));\n }\n }\n\n // Simplify the exclusive condition\n const simplified = simplifyCondition(exclusive);\n\n // Skip impossible conditions (simplified to FALSE)\n if (simplified.kind === 'false') {\n continue;\n }\n\n result.push({\n ...entry,\n exclusiveCondition: simplified,\n });\n\n // Add non-default conditions to prior list for subsequent entries\n if (entry.condition.kind !== 'true') {\n priorConditions.push(entry.condition);\n }\n }\n\n return result;\n}\n\n/**\n * Parse style entries from a value mapping object.\n *\n * @param styleKey The style key (e.g., 'padding')\n * @param valueMap The value mapping { '': '2x', 'compact': '1x', '@media(w < 768px)': '0.5x' }\n * @param parseCondition Function to parse state keys into conditions\n * @returns Parsed entries ordered by priority (highest first)\n */\nexport function parseStyleEntries(\n styleKey: string,\n valueMap: Record<string, StyleValue>,\n parseCondition: (stateKey: string) => ConditionNode,\n): ParsedStyleEntry[] {\n const entries: ParsedStyleEntry[] = [];\n const keys = Object.keys(valueMap);\n\n keys.forEach((stateKey, index) => {\n const value = valueMap[stateKey];\n const condition =\n stateKey === '' ? trueCondition() : parseCondition(stateKey);\n\n entries.push({\n styleKey,\n stateKey,\n value,\n condition,\n priority: index,\n });\n });\n\n // Reverse so highest priority (last in object) comes first for exclusive building\n // buildExclusiveConditions expects highest priority first\n entries.reverse();\n\n return entries;\n}\n\n/**\n * Merge parsed entries that share the same value.\n *\n * When multiple state keys map to the same value, their conditions can\n * be combined with OR and treated as a single entry. This must happen\n * **before** exclusive expansion and OR branch splitting to avoid\n * combinatorial explosion and duplicate CSS output.\n *\n * Example: `{ '@dark': 'red', '@dark & @hc': 'red' }` merges into a\n * single entry with condition `@dark | (@dark & @hc)` = `@dark`.\n *\n * Entries are ordered highest-priority-first. The merged entry keeps the\n * highest priority of the group.\n */\nexport function mergeEntriesByValue(\n entries: ParsedStyleEntry[],\n): ParsedStyleEntry[] {\n if (entries.length <= 1) return entries;\n\n const groups = new Map<\n string,\n { entries: ParsedStyleEntry[]; maxPriority: number }\n >();\n\n for (const entry of entries) {\n const valueKey = serializeValue(entry.value);\n const group = groups.get(valueKey);\n if (group) {\n group.entries.push(entry);\n group.maxPriority = Math.max(group.maxPriority, entry.priority);\n } else {\n groups.set(valueKey, { entries: [entry], maxPriority: entry.priority });\n }\n }\n\n // If no merges possible, return as-is\n if (groups.size === entries.length) return entries;\n\n const merged: ParsedStyleEntry[] = [];\n for (const [, group] of groups) {\n if (group.entries.length === 1) {\n merged.push(group.entries[0]);\n continue;\n }\n\n // Combine conditions with OR, then simplify\n const combinedCondition = simplifyCondition(\n or(...group.entries.map((e) => e.condition)),\n );\n\n // Combine state keys for debugging\n const combinedStateKey = group.entries.map((e) => e.stateKey).join(' | ');\n\n // When a group contains the default (true) entry, use minPriority.\n // true|X = true, so the merged condition is unconditional; at elevated\n // priority it would shadow entries between the default and the\n // highest-priority member, breaking exclusivity.\n const hasDefault = group.entries.some((e) => e.condition.kind === 'true');\n const minPriority = Math.min(...group.entries.map((e) => e.priority));\n\n merged.push({\n styleKey: group.entries[0].styleKey,\n stateKey: combinedStateKey,\n value: group.entries[0].value,\n condition: combinedCondition,\n priority: hasDefault ? minPriority : group.maxPriority,\n });\n }\n\n // Re-sort by priority (highest first)\n merged.sort((a, b) => b.priority - a.priority);\n\n return merged;\n}\n\nfunction serializeValue(value: StyleValue): string {\n if (value === null || value === undefined) return 'null';\n if (typeof value === 'string' || typeof value === 'number') {\n return String(value);\n }\n return JSON.stringify(value);\n}\n\n/**\n * Check if a value is a style value mapping (object with state keys)\n */\nexport function isValueMapping(\n value: StyleValue | Record<string, StyleValue>,\n): value is Record<string, StyleValue> {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n );\n}\n\n// ============================================================================\n// OR Expansion\n// ============================================================================\n\n/**\n * Expand OR conditions in parsed entries into multiple exclusive entries.\n *\n * For an entry with condition `A | B | C`, this creates 3 entries:\n * - condition: A\n * - condition: B & !A\n * - condition: C & !A & !B\n *\n * This ensures OR branches are mutually exclusive BEFORE the main\n * exclusive condition building pass.\n *\n * @param entries Parsed entries (may contain OR conditions)\n * @returns Expanded entries with OR branches made exclusive\n */\nexport function expandOrConditions(\n entries: ParsedStyleEntry[],\n): ParsedStyleEntry[] {\n const result: ParsedStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandSingleEntry(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Expand a single entry's OR condition into multiple exclusive entries\n */\nfunction expandSingleEntry(entry: ParsedStyleEntry): ParsedStyleEntry[] {\n const orBranches = collectOrBranches(entry.condition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Make each OR branch exclusive from prior branches\n const result: ParsedStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[${i}]`, // Mark as expanded branch\n condition: simplified,\n // Keep same priority - all branches from same entry have same priority\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n\n/**\n * Collect top-level OR branches from a condition.\n *\n * For `A | B | C`, returns [A, B, C]\n * For `A & B`, returns [A & B] (single branch)\n * For `A | (B & C)`, returns [A, B & C]\n */\nfunction collectOrBranches(condition: ConditionNode): ConditionNode[] {\n if (condition.kind === 'true' || condition.kind === 'false') {\n return [condition];\n }\n\n if (isCompoundCondition(condition) && condition.operator === 'OR') {\n // Flatten nested ORs\n const branches: ConditionNode[] = [];\n for (const child of condition.children) {\n branches.push(...collectOrBranches(child));\n }\n return branches;\n }\n\n // Not an OR - return as single branch\n return [condition];\n}\n\n// ============================================================================\n// Post-Build OR Expansion (for De Morgan ORs)\n// ============================================================================\n\n/**\n * Expand OR conditions in exclusive entries AFTER buildExclusiveConditions.\n *\n * This handles ORs that arise from De Morgan expansion during negation:\n * !(A & B) = !A | !B\n *\n * These ORs need to be made exclusive to avoid overlapping CSS rules:\n * !A | !B → !A | (A & !B)\n *\n * This is logically equivalent but ensures each branch has proper context.\n *\n * Example:\n * Input: { \"\": V1, \"@supports(...) & :has()\": V2 }\n * V2's exclusive = @supports & :has\n * V1's exclusive = !(@supports & :has) = !@supports | !:has\n *\n * Without this fix: V1 gets two rules:\n * - @supports (not ...) → V1 ✓\n * - :not(:has()) → V1 ✗ (missing @supports context!)\n *\n * With this fix: V1 gets two exclusive rules:\n * - @supports (not ...) → V1 ✓\n * - @supports (...) { :not(:has()) } → V1 ✓ (proper context!)\n */\nexport function expandExclusiveOrs(\n entries: ExclusiveStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandExclusiveConditionOrs(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Check if a condition involves at-rules (media, container, supports, starting)\n */\nfunction hasAtRuleContext(node: ConditionNode): boolean {\n if (node.kind === 'true' || node.kind === 'false') {\n return false;\n }\n\n if (node.kind === 'state') {\n // These condition types generate at-rules\n return (\n node.type === 'media' ||\n node.type === 'container' ||\n node.type === 'supports' ||\n node.type === 'starting'\n );\n }\n\n if (node.kind === 'compound') {\n return node.children.some(hasAtRuleContext);\n }\n\n return false;\n}\n\n/**\n * Sort OR branches to prioritize at-rule conditions first.\n *\n * This is critical for correct CSS generation. For `!A | !B` where A is at-rule\n * and B is modifier, we want:\n * - Branch 0: !A (at-rule negation - covers \"no @supports/media\" case)\n * - Branch 1: A & !B (modifier negation with at-rule context)\n *\n * If we process in wrong order (!B first), we'd get:\n * - Branch 0: !B (modifier negation WITHOUT at-rule context - WRONG!)\n * - Branch 1: B & !A (at-rule negation with modifier - incomplete coverage)\n */\nfunction sortOrBranchesForExpansion(\n branches: ConditionNode[],\n): ConditionNode[] {\n return [...branches].sort((a, b) => {\n const aHasAtRule = hasAtRuleContext(a);\n const bHasAtRule = hasAtRuleContext(b);\n\n // At-rule conditions come first\n if (aHasAtRule && !bHasAtRule) return -1;\n if (!aHasAtRule && bHasAtRule) return 1;\n\n // Same type - keep original order (stable sort)\n return 0;\n });\n}\n\n/**\n * Expand ORs in a single entry's exclusive condition\n */\nfunction expandExclusiveConditionOrs(\n entry: ExclusiveStyleEntry,\n): ExclusiveStyleEntry[] {\n let orBranches = collectOrBranches(entry.exclusiveCondition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Sort branches so at-rule conditions come first\n // This ensures proper context inheritance during expansion\n orBranches = sortOrBranchesForExpansion(orBranches);\n\n // Make each OR branch exclusive from prior branches\n const result: ExclusiveStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n // This transforms: !A | !B → !A, !B & !!A = !A, (A & !B)\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations and clean up double negations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[or:${i}]`, // Mark as expanded OR branch\n exclusiveCondition: simplified,\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,yBACd,SACuB;CACvB,MAAM,SAAgC,EAAE;CACxC,MAAM,kBAAmC,EAAE;AAE3C,MAAK,MAAM,SAAS,SAAS;EAE3B,IAAI,YAA2B,MAAM;AAErC,OAAK,MAAM,SAAS,gBAElB,KAAI,MAAM,SAAS,OACjB,aAAY,IAAI,WAAW,IAAI,MAAM,CAAC;EAK1C,MAAM,aAAa,kBAAkB,UAAU;AAG/C,MAAI,WAAW,SAAS,QACtB;AAGF,SAAO,KAAK;GACV,GAAG;GACH,oBAAoB;GACrB,CAAC;AAGF,MAAI,MAAM,UAAU,SAAS,OAC3B,iBAAgB,KAAK,MAAM,UAAU;;AAIzC,QAAO;;;;;;;;;;AAWT,SAAgB,kBACd,UACA,UACA,gBACoB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1C,MAAM,SAAS,WAAW;EAI1B,IAAI,kBAAiC;AACrC,OAAK,MAAM,SAAS,cAClB,mBAAkB,IAAI,iBAAiB,IAAI,MAAM,CAAC;EAIpD,MAAM,aAAa,kBAAkB,gBAAgB;AAGrD,MAAI,WAAW,SAAS,SAAS;AAC/B,iBAAc,KAAK,OAAO;AAC1B;;AAGF,SAAO,KAAK;GACV,GAAG;GACH,UAAU,GAAG,MAAM,SAAS,MAAM,EAAE;GACpC,oBAAoB;GACrB,CAAC;AAEF,gBAAc,KAAK,OAAO;;AAG5B,QAAO"}
@@ -5,7 +5,7 @@ import { STYLE_HANDLER_MAP } from "../styles/index.js";
5
5
  import { createStateParserContext, extractLocalPredefinedStates } from "../states/index.js";
6
6
  import { and, or, trueCondition } from "./conditions.js";
7
7
  import { simplifyCondition } from "./simplify.js";
8
- import { buildExclusiveConditions, expandExclusiveOrs, expandOrConditions, isValueMapping, parseStyleEntries } from "./exclusive.js";
8
+ import { buildExclusiveConditions, expandExclusiveOrs, expandOrConditions, isValueMapping, mergeEntriesByValue, parseStyleEntries } from "./exclusive.js";
9
9
  import { branchToCSS, buildAtRulesFromVariant, conditionToCSS, mergeVariantsIntoSelectorGroups, optimizeGroups, parentGroupsToCSS, rootGroupsToCSS, selectorGroupToCSS } from "./materialize.js";
10
10
  import { emitWarning } from "./warnings.js";
11
11
  import { parseStateKey } from "./parseStateKey.js";
@@ -88,7 +88,7 @@ function processStyles(styles, selectorSuffix, parserContext, allRules) {
88
88
  const value = styleMap[styleName];
89
89
  if (value === void 0) continue;
90
90
  if (isValueMapping(value)) {
91
- const fullyExpanded = expandExclusiveOrs(buildExclusiveConditions(expandOrConditions(parseStyleEntries(styleName, value, (stateKey) => parseStateKey(stateKey, { context: parserContext })))));
91
+ const fullyExpanded = expandExclusiveOrs(buildExclusiveConditions(expandOrConditions(mergeEntriesByValue(parseStyleEntries(styleName, value, (stateKey) => parseStateKey(stateKey, { context: parserContext }))))));
92
92
  exclusiveByStyle.set(styleName, fullyExpanded);
93
93
  } else exclusiveByStyle.set(styleName, [{
94
94
  styleKey: styleName,