@tenphi/tasty 0.0.0-snapshot.d656d18 → 0.0.0-snapshot.d7129ca
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/{babel-_RVkw0iE.d.ts → babel-DD7kdEFT.d.ts} +2 -2
- package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
- package/dist/chunks/{async-storage-DKK-wTD4.js.map → async-storage-CG5HnUT5.js.map} +1 -1
- package/dist/chunks/build-config-CUQVwdWF.js +42 -0
- package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
- package/dist/chunks/{collector-DBGcmUEq.js → collector-B0LTHw6Z.js} +6 -124
- package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
- package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
- package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
- package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
- package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
- package/dist/chunks/{css-resources-Cyl_axbI.js → css-resources-BN8apgxt.js} +1 -8
- package/dist/chunks/{css-resources-Cyl_axbI.js.map → css-resources-BN8apgxt.js.map} +1 -1
- package/dist/chunks/{debug-BUwqo6vC.js → debug-CiiHDgmR.js} +69 -150
- package/dist/chunks/debug-CiiHDgmR.js.map +1 -0
- package/dist/chunks/{dsl-CXvoaLnj.js → dsl-C5yuAn41.js} +62 -786
- package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
- package/dist/chunks/hydration-TRcz5vnk.js +41 -0
- package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
- package/dist/chunks/react-runtime-sH6r6Ajr.js +557 -0
- package/dist/chunks/react-runtime-sH6r6Ajr.js.map +1 -0
- package/dist/chunks/runtime-engine-BrRcOZwD.js +2438 -0
- package/dist/chunks/runtime-engine-BrRcOZwD.js.map +1 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
- package/dist/chunks/{shared-utils-OIg0N_dp.js → shared-utils-DWA4LjIa.js} +24 -62
- package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
- package/dist/chunks/{style-engine-CqSmIlud.js → style-engine-C1ECBZxR.js} +671 -2736
- package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
- package/dist/chunks/{css-writer-PFzrSPeu.js → zero-engine-B6EnYcXY.js} +3 -120
- package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
- package/dist/{collector-CVdVIy7s.d.ts → collector-YpsMjV7T.d.ts} +6 -4
- package/dist/{config-BI0y21JV.d.ts → config-BnZqyYG4.d.ts} +16 -25
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +9 -7
- package/dist/{index-CrT0bsiI.d.ts → index-BLJLo9cl.d.ts} +17 -50
- package/dist/index.d.ts +5 -5
- package/dist/index.js +10 -7
- package/dist/{merge-styles-BFktNP8J.d.ts → merge-styles-CTDLIrO5.d.ts} +2 -2
- package/dist/ssr/astro-client.js +1 -14
- package/dist/ssr/astro-client.js.map +1 -1
- package/dist/ssr/astro-middleware-static.js +0 -11
- package/dist/ssr/astro-middleware-static.js.map +1 -1
- package/dist/ssr/astro-middleware.js +0 -12
- package/dist/ssr/astro-middleware.js.map +1 -1
- package/dist/ssr/astro.js +5 -85
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/index.d.ts +6 -6
- package/dist/ssr/index.js +4 -4
- package/dist/ssr/next-config.d.ts +1 -1
- package/dist/ssr/next-config.js +29 -20
- package/dist/ssr/next-config.js.map +1 -1
- package/dist/ssr/next.d.ts +1 -1
- package/dist/ssr/next.js +5 -36
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +2 -2
- package/dist/static/index.js +1 -19
- package/dist/static/index.js.map +1 -1
- package/dist/{index-BzAC3p06.d.ts → types-vfRQhzRd.d.ts} +811 -811
- package/dist/zero/babel.d.ts +1 -1
- package/dist/zero/babel.js +25 -95
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +1 -1
- package/dist/zero/index.js +1 -1
- package/dist/zero/next.d.ts +1 -1
- package/dist/zero/next.js +0 -31
- package/dist/zero/next.js.map +1 -1
- package/docs/ai-agents.md +5 -1
- package/docs/dsl.md +2 -2
- package/docs/getting-started.md +12 -11
- package/docs/methodology.md +2 -2
- package/docs/pipeline.md +3 -0
- package/docs/plugins.md +1 -1
- package/docs/runtime-benchmarks.md +105 -68
- package/docs/ssr.md +1 -1
- package/docs/styles.md +5 -5
- package/docs/tasty-static.md +1 -1
- package/package.json +29 -10
- package/dist/chunks/async-storage-DKK-wTD4.js +0 -44
- package/dist/chunks/collector-DBGcmUEq.js.map +0 -1
- package/dist/chunks/css-writer-PFzrSPeu.js.map +0 -1
- package/dist/chunks/debug-BUwqo6vC.js.map +0 -1
- package/dist/chunks/dsl-CXvoaLnj.js.map +0 -1
- package/dist/chunks/hydrate-6YoHZP6A.js +0 -37
- package/dist/chunks/hydrate-6YoHZP6A.js.map +0 -1
- package/dist/chunks/react-runtime-B3CmvDEQ.js +0 -1525
- package/dist/chunks/react-runtime-B3CmvDEQ.js.map +0 -1
- package/dist/chunks/runtime-engine-Y00VWjrS.js +0 -4719
- package/dist/chunks/runtime-engine-Y00VWjrS.js.map +0 -1
- package/dist/chunks/shared-utils-OIg0N_dp.js.map +0 -1
- package/dist/chunks/style-engine-CqSmIlud.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-engine-Y00VWjrS.js","names":["devMode"],"sources":["../../src/functions/index.ts","../../src/prop-handlers.ts","../../src/properties/index.ts","../../src/utils/hash.ts","../../src/utils/name-prefix.ts","../../src/injector/batch.ts","../../src/properties/property-type-resolver.ts","../../src/injector/sheet-manager.ts","../../src/font-face/index.ts","../../src/counter-style/index.ts","../../src/injector/injector.ts","../../src/utils/typography.ts","../../src/config.ts","../../src/injector/chunk-sheet-registry.ts","../../src/injector/index.ts","../../src/keyframes/index.ts","../../src/ssr/ssr-collector-ref.ts","../../src/ssr/format-property.ts","../../src/ssr/format-keyframes.ts","../../src/ssr/format-rules.ts","../../src/utils/resolve-recipes.ts","../../src/utils/cache-wrapper.ts","../../src/ssr/format-global-rules.ts","../../src/utils/client-state.ts","../../src/utils/deps-equal.ts"],"sourcesContent":["/**\n * Function Utilities\n *\n * Utilities for extracting and processing CSS @function definitions in styles.\n * Custom functions are permanent once injected and do not need cleanup.\n *\n * Token syntax:\n * - Function name keys use `$$name` (the literal callable `--name`), matching\n * the call site `$$name(...)`. `$name` and `--name` are also accepted.\n * - Parameters and local variables use `$name` (declared/referenced as a custom\n * property), exactly like a normal styles object.\n * - `result`, local-variable values, and parameter defaults flow through the\n * Tasty DSL parser, so units, color tokens, auto-calc, and fallbacks all work.\n */\n\nimport type { FunctionDefinition, FunctionParameter } from '../injector/types';\nimport type { StyleDetails } from '../parser/types';\nimport type { Styles } from '../styles/types';\nimport { customFunction, parseStyle } from '../utils/styles';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst FUNCTION_KEY = '@function';\n\n/** Descriptor keys that are not local-variable declarations. */\nconst RESERVED_KEYS = new Set(['args', 'returns', 'result']);\n\n/**\n * A parse-time function: receives the parsed (comma-separated) argument groups\n * and returns a CSS value string. This is the JS flavor of the unified\n * `functions` config (bare-name keys), distinct from declarative `@function`\n * definitions (`$$`-prefixed keys).\n */\nexport type ParseFunction = (groups: StyleDetails[]) => string;\n\n/**\n * The unified `functions` map: keys are either bare names (parse functions,\n * value is a function) or `$$name`/`$name`/`--name` (declarative CSS functions,\n * value is a {@link FunctionDefinition} object).\n */\nexport type FunctionsConfig = Record<\n string,\n FunctionDefinition | ParseFunction\n>;\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has a local @function definition.\n */\nexport function hasLocalFunctions(styles: Styles): boolean {\n return FUNCTION_KEY in styles;\n}\n\n/**\n * Extract local @function definitions from a styles object.\n * Returns null if none (fast path).\n */\nexport function extractLocalFunctions(\n styles: Styles,\n): Record<string, FunctionDefinition> | null {\n const functions = styles[FUNCTION_KEY];\n if (!functions || typeof functions !== 'object') {\n return null;\n }\n return functions as Record<string, FunctionDefinition>;\n}\n\n// ============================================================================\n// Token Parsing\n// ============================================================================\n\n/**\n * Parse a function name token into its CSS custom name.\n * Accepts `$$name`, `$name`, `--name`, or bare `name` → `--name`.\n */\nexport function parseFunctionName(token: string): string {\n if (token.startsWith('$$')) return `--${token.slice(2)}`;\n if (token.startsWith('$')) return `--${token.slice(1)}`;\n if (token.startsWith('--')) return token;\n return `--${token}`;\n}\n\n/**\n * Parse a parameter / local-variable name token into its CSS custom name.\n * Accepts `$name`, `--name`, or bare `name` → `--name`.\n */\nexport function parseParamName(token: string): string {\n if (token.startsWith('$')) return `--${token.slice(1)}`;\n if (token.startsWith('--')) return token;\n return `--${token}`;\n}\n\n// ============================================================================\n// CSS Formatting\n// ============================================================================\n\n/**\n * Format a single parameter (`--name <type>: default`).\n */\nfunction formatParameter(token: string, param: FunctionParameter): string {\n const name = parseParamName(token);\n\n if (param === true) {\n return name;\n }\n\n if (typeof param === 'string') {\n return param ? `${name} ${param}` : name;\n }\n\n let out = name;\n if (param.syntax) {\n out += ` ${param.syntax}`;\n }\n if (param.default !== undefined) {\n out += `: ${parseStyle(param.default).output}`;\n }\n return out;\n}\n\n/**\n * Format the function prelude: `@function --name(params) returns <type>`.\n */\nexport function formatFunctionPrelude(\n name: string,\n args: FunctionDefinition['args'],\n returns?: string,\n): string {\n const cssName = parseFunctionName(name);\n\n let params = '';\n if (Array.isArray(args)) {\n params = args.map((token) => formatParameter(token, true)).join(', ');\n } else if (args) {\n params = Object.entries(args)\n .map(([token, param]) => formatParameter(token, param))\n .join(', ');\n }\n\n const returnsPart = returns ? ` returns ${returns}` : '';\n\n return `@function ${cssName}(${params})${returnsPart}`;\n}\n\n/**\n * Format the inner declarations of a @function rule (local variables + result).\n */\nexport function formatFunctionDeclarations(def: FunctionDefinition): string {\n const parts: string[] = [];\n\n for (const key of Object.keys(def)) {\n if (RESERVED_KEYS.has(key) || !key.startsWith('$')) continue;\n const value = def[key as `$${string}`];\n if (value === undefined) continue;\n parts.push(`${parseParamName(key)}: ${parseStyle(value).output};`);\n }\n\n parts.push(`result: ${parseStyle(def.result).output};`);\n\n return parts.join(' ');\n}\n\n/**\n * Format a complete @function rule as CSS.\n */\nexport function formatFunctionRule(\n name: string,\n def: FunctionDefinition,\n): string {\n const prelude = formatFunctionPrelude(name, def.args, def.returns);\n return `${prelude} { ${formatFunctionDeclarations(def)} }`;\n}\n\n// ============================================================================\n// Unified `functions` config: value-type split\n// ============================================================================\n\n/** A key is a CSS-function key when it carries the `$`/`--` prefix. */\nfunction isCssFunctionKey(key: string): boolean {\n return key.startsWith('$') || key.startsWith('--');\n}\n\n/** Discriminate a unified `functions` entry by its value type. */\nfunction isParseFunction(\n value: FunctionDefinition | ParseFunction,\n): value is ParseFunction {\n return typeof value === 'function';\n}\n\nexport type FunctionMismatch =\n | 'expected-definition' // function value under a `$$` key\n | 'expected-parse-function'; // object value under a bare key\n\n/**\n * Split the unified `functions` map into the two internal registries:\n * - `parseFuncs`: JS parse functions (bare keys).\n * - `functionDefs`: declarative CSS `@function` definitions (`$$` keys).\n *\n * Entries whose key prefix does not match the value type are reported via\n * `onMismatch` and skipped.\n */\nexport function splitFunctions(\n map: FunctionsConfig,\n onMismatch?: (key: string, kind: FunctionMismatch) => void,\n): {\n parseFuncs: Record<string, ParseFunction>;\n functionDefs: Record<string, FunctionDefinition>;\n} {\n const parseFuncs: Record<string, ParseFunction> = {};\n const functionDefs: Record<string, FunctionDefinition> = {};\n\n for (const [key, value] of Object.entries(map)) {\n const cssKey = isCssFunctionKey(key);\n if (isParseFunction(value)) {\n if (cssKey) {\n onMismatch?.(key, 'expected-definition');\n continue;\n }\n parseFuncs[key] = value;\n } else {\n if (!cssKey) {\n onMismatch?.(key, 'expected-parse-function');\n continue;\n }\n functionDefs[key] = value;\n }\n }\n\n return { parseFuncs, functionDefs };\n}\n\n// ============================================================================\n// Polyfill: compile a declarative @function into a parse-function closure\n// ============================================================================\n\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nconst paramBareName = (token: string): string => parseParamName(token).slice(2);\n\n/**\n * Rewrite `var(--name)` references for declared parameter/local names to a\n * collision-resistant, function-scoped prefix. This guarantees that later\n * value substitution only ever targets the function's own variables and can\n * never accidentally match a real element-level `var(--name)` introduced by an\n * argument value (e.g. the `--gap` used by Tasty units). Blanket prefix — no\n * exact-collision detection.\n */\nfunction prefixDeclaredVars(\n template: string,\n declared: string[],\n prefixOf: (bare: string) => string,\n): string {\n let out = template;\n for (const bare of declared) {\n const re = new RegExp(`var\\\\(\\\\s*--${escapeRegExp(bare)}(?![\\\\w-])`, 'g');\n out = out.replace(re, `var(--${prefixOf(bare)}`);\n }\n return out;\n}\n\n/**\n * Replace the prefixed `var(--<prefixed>)` / `var(--<prefixed>, fallback)`\n * references with their mapped values, iterating so that local variables that\n * reference parameters (or other locals) resolve fully.\n */\nfunction substituteVars(\n template: string,\n valueMap: Map<string, string>,\n): string {\n let out = template;\n for (let iter = 0; iter < 30; iter++) {\n let changed = false;\n for (const [name, value] of valueMap) {\n const re = new RegExp(\n `var\\\\(\\\\s*--${escapeRegExp(name)}\\\\s*(?:,[^)]*)?\\\\)`,\n 'g',\n );\n const next = out.replace(re, () => {\n changed = true;\n return value;\n });\n out = next;\n }\n if (!changed) break;\n }\n return out;\n}\n\n/** Function names currently being expanded, to guard against recursion cycles. */\nconst inProgress = new Set<string>();\n\n/**\n * Compile a declarative `@function` definition into a parse-function closure\n * that fully inlines the call into plain CSS (the `@function` polyfill).\n *\n * Parameters and local variables are substituted directly with their values,\n * so no function-internal custom properties are emitted (collisions are\n * structurally impossible). Self/mutually-recursive functions are not expanded:\n * the cycle guard bails and the call is left untouched.\n */\nexport function compileFunctionClosure(\n name: string,\n def: FunctionDefinition,\n): ParseFunction {\n const cssName = parseFunctionName(name);\n // Function-scoped, collision-resistant prefix for this function's variables.\n const prefixOf = (bare: string): string => `tf-${cssName.slice(2)}-${bare}`;\n\n const params: { prefixed: string; default?: string }[] = [];\n if (Array.isArray(def.args)) {\n for (const token of def.args) {\n params.push({ prefixed: prefixOf(paramBareName(token)) });\n }\n } else if (def.args) {\n for (const [token, param] of Object.entries(def.args)) {\n let dflt: string | undefined;\n if (param && typeof param === 'object' && param.default !== undefined) {\n dflt = parseStyle(param.default).output;\n }\n params.push({ prefixed: prefixOf(paramBareName(token)), default: dflt });\n }\n }\n\n const localKeys = Object.keys(def).filter(\n (key) => !RESERVED_KEYS.has(key) && key.startsWith('$'),\n );\n\n const declared = [\n ...(Array.isArray(def.args)\n ? def.args.map(paramBareName)\n : def.args\n ? Object.keys(def.args).map(paramBareName)\n : []),\n ...localKeys.map(paramBareName),\n ];\n\n // Built lazily on first call so that nested function calls referenced by the\n // result are resolved against the fully-populated registry.\n let built = false;\n let resultTemplate = '';\n const localTemplates: { prefixed: string; value: string }[] = [];\n\n const build = () => {\n built = true;\n resultTemplate = prefixDeclaredVars(\n parseStyle(def.result).output,\n declared,\n prefixOf,\n );\n for (const key of localKeys) {\n const value = def[key as `$${string}`];\n if (value === undefined) continue;\n localTemplates.push({\n prefixed: prefixOf(paramBareName(key)),\n value: prefixDeclaredVars(parseStyle(value).output, declared, prefixOf),\n });\n }\n };\n\n return (groups: StyleDetails[]): string => {\n if (inProgress.has(cssName)) return '';\n inProgress.add(cssName);\n try {\n if (!built) build();\n\n const valueMap = new Map<string, string>();\n params.forEach((param, index) => {\n const arg = groups[index]?.output?.trim();\n valueMap.set(param.prefixed, arg || param.default || '');\n });\n for (const local of localTemplates) {\n valueMap.set(local.prefixed, local.value);\n }\n\n return substituteVars(resultTemplate, valueMap);\n } finally {\n inProgress.delete(cssName);\n }\n };\n}\n\n/** CSS function name -> serialized definition, to dedupe polyfill registration. */\nconst registeredFunctionDefs = new Map<string, string>();\n\n/**\n * Register a declarative `@function` as a parse-function closure so the parser\n * inlines its call sites. Deduplicated by name + definition; a later, different\n * definition of the same name overrides the previous one (local wins).\n */\nexport function registerFunctionPolyfill(\n name: string,\n definition: FunctionDefinition,\n): void {\n const cssName = parseFunctionName(name);\n const serialized = JSON.stringify(definition);\n if (registeredFunctionDefs.get(cssName) === serialized) return;\n registeredFunctionDefs.set(cssName, serialized);\n customFunction(cssName, compileFunctionClosure(name, definition));\n}\n\n/** Register all local `@function` definitions from a styles object (polyfill). */\nexport function registerLocalFunctionPolyfills(styles: Styles): void {\n const local = extractLocalFunctions(styles);\n if (!local) return;\n for (const [name, definition] of Object.entries(local)) {\n registerFunctionPolyfill(name, definition);\n }\n}\n\n/** Clear polyfill registration bookkeeping (used by resetConfig in tests). */\nexport function resetFunctionPolyfills(): void {\n registeredFunctionDefs.clear();\n}\n","/**\n * Props middleware for tasty components.\n *\n * A prop handler receives a component's props and returns them, changed or not.\n * That makes it the extension point for props that are *not* style properties:\n * it can read a custom prop, strip it so it never reaches the DOM, and fold its\n * meaning into `styles`, `mods`, `tokens`, `variant`, or `as`.\n *\n * ```ts\n * configure({\n * propHandlers: {\n * glaze: (props) => {\n * const { glaze, ...rest } = props;\n * if (!glaze) return rest;\n * return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };\n * },\n * },\n * });\n * ```\n *\n * Handlers run on every render of every tasty component, so the registry is a\n * pre-composed chain that is `null` while nothing is registered — the cost when\n * unused is one property load and one branch.\n */\n\nimport { isDevEnv } from './utils/is-dev-env';\n\n/** Props object handed to a prop handler. Deliberately untyped: handlers see everything. */\nexport type PropHandlerProps = Record<string, unknown>;\n\n/**\n * Props middleware: props in, props out. Returning nothing means \"unchanged\".\n *\n * Must be a **pure function** and must not mutate its input. Style values are\n * cached by object identity, so mutating a value object in place produces a stale\n * class name and stale CSS. Return fresh (ideally frozen, ideally memoized)\n * objects instead.\n */\nexport type PropHandler = (\n props: PropHandlerProps,\n) => PropHandlerProps | void | null;\n\n/**\n * How a prop handler is declared. The map key is both its name and, by default,\n * the prop that triggers it.\n *\n * - `fn` — triggered when a prop matching the key is present\n * - `['glaze', fn]` — triggered by the named prop\n * - `[['glaze', 'tone'], fn]` — triggered by any of them\n * - `['*', fn]` — unconditional; runs on every render of every component\n */\nexport type PropHandlerDefinition =\n PropHandler | [string, PropHandler] | [string[], PropHandler];\n\ninterface NormalizedPropHandler {\n key: string;\n /** Props that trigger this handler, or `null` for unconditional. */\n triggers: string[] | null;\n fn: PropHandler;\n source: string;\n}\n\ntype PropHandlerChain = (props: PropHandlerProps) => PropHandlerProps;\n\ninterface PropHandlerRegistry {\n /** Pre-composed chain, or `null` while nothing is registered. */\n apply: PropHandlerChain | null;\n list: NormalizedPropHandler[];\n}\n\n// Held on globalThis so a duplicated module graph (Astro's server/client split)\n// shares one registry, matching how the rest of the global config is stored.\nconst GTKEY = '__tasty_prop_handlers__';\n\nconst globalStore = globalThis as unknown as Record<string, unknown>;\n\nexport const propHandlerRegistry: PropHandlerRegistry =\n (globalStore[GTKEY] as PropHandlerRegistry | undefined) ??\n ((globalStore[GTKEY] = { apply: null, list: [] }) as PropHandlerRegistry);\n\nexport interface RegisterPropHandlerOptions {\n /** Where the handler came from — a plugin name, or `'configure()'`. */\n source?: string;\n}\n\nfunction normalize(\n key: string,\n definition: PropHandlerDefinition,\n options?: RegisterPropHandlerOptions,\n): NormalizedPropHandler {\n const source = options?.source ?? 'configure()';\n\n if (typeof definition === 'function') {\n return { key, triggers: [key], fn: definition, source };\n }\n\n if (Array.isArray(definition)) {\n const [first, fn] = definition;\n\n if (typeof fn !== 'function') {\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'Tuple must have a function as the second element: [string, function] or [string[], function].',\n );\n }\n\n if (first === '*') {\n return { key, triggers: null, fn, source };\n }\n\n if (typeof first === 'string') {\n return { key, triggers: [first], fn, source };\n }\n\n if (Array.isArray(first)) {\n return {\n key,\n triggers: first.includes('*') ? null : first,\n fn,\n source,\n };\n }\n\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'First element must be a string or string array.',\n );\n }\n\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'Expected function, [string, function], or [string[], function].',\n );\n}\n\n/**\n * Run one handler, treating a nothing/non-object return as \"unchanged\".\n *\n * `isDevEnv()` is called lazily rather than captured at module load so the\n * warnings are assertable in tests; it is only reached on the misuse path.\n */\nfunction runOne(\n handler: NormalizedPropHandler,\n props: PropHandlerProps,\n): PropHandlerProps {\n const next = handler.fn(props);\n\n if (next != null && typeof next === 'object' && !Array.isArray(next)) {\n return next;\n }\n\n if (isDevEnv()) {\n console.warn(\n next == null\n ? `[Tasty] propHandlers[\"${handler.key}\"] (from ${handler.source}) returned ` +\n `${String(next)}. Props are treated as unchanged — did you forget to ` +\n `\\`return props\\`?`\n : `[Tasty] propHandlers[\"${handler.key}\"] (from ${handler.source}) returned ` +\n `${Array.isArray(next) ? 'an array' : typeof next}. A prop handler must ` +\n `return a props object. The result was ignored.`,\n );\n }\n\n return props;\n}\n\nfunction compose(list: NormalizedPropHandler[]): PropHandlerChain | null {\n if (list.length === 0) return null;\n\n // Specialize the overwhelmingly common single-handler case.\n if (list.length === 1) {\n const only = list[0];\n\n if (only.triggers === null) {\n return (props) => runOne(only, props);\n }\n\n if (only.triggers.length === 1) {\n const trigger = only.triggers[0];\n\n return (props) => (trigger in props ? runOne(only, props) : props);\n }\n }\n\n return (props) => {\n for (const handler of list) {\n const triggers = handler.triggers;\n\n if (triggers !== null) {\n let triggered = false;\n\n for (const trigger of triggers) {\n if (trigger in props) {\n triggered = true;\n break;\n }\n }\n\n if (!triggered) continue;\n }\n\n props = runOne(handler, props);\n }\n\n return props;\n };\n}\n\n/**\n * Register a props middleware under `key`, replacing any handler already\n * registered under the same key while keeping its position in the chain.\n */\nexport function registerPropHandler(\n key: string,\n definition: PropHandlerDefinition,\n options?: RegisterPropHandlerOptions,\n): void {\n const normalized = normalize(key, definition, options);\n const { list } = propHandlerRegistry;\n const existing = list.findIndex((handler) => handler.key === key);\n\n if (existing === -1) {\n list.push(normalized);\n } else {\n list[existing] = normalized;\n }\n\n propHandlerRegistry.apply = compose(list);\n}\n\n/** Drop every registered props middleware. Called by `resetConfig()`. */\nexport function resetPropHandlers(): void {\n if (propHandlerRegistry.list.length === 0) return;\n\n // Mutate the holder rather than replacing it: other modules captured this\n // object reference at import time.\n propHandlerRegistry.list.length = 0;\n propHandlerRegistry.apply = null;\n}\n","/**\n * Properties Utilities\n *\n * Utilities for extracting and processing CSS @property definitions in styles.\n * Unlike keyframes, properties are permanent once registered and don't need cleanup.\n *\n * Property names use tasty token syntax:\n * - `$name` for regular properties → `--name`\n * - `#name` for color properties → `--name-color` (auto-sets syntax: '<color>')\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { RE_NUMBER, RE_RAW_UNIT } from '../parser/const';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst PROPERTIES_KEY = '@property';\n\n/**\n * Valid CSS custom property name pattern (after the -- prefix).\n * Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.\n */\nconst VALID_PROPERTY_NAME_PATTERN = /^[a-z_][a-z0-9-_]*$/i;\n\n// ============================================================================\n// Validation Functions\n// ============================================================================\n\n/**\n * Validate a CSS custom property name (the part after --).\n * Returns true if the name is valid for use as a CSS custom property.\n */\nexport function isValidPropertyName(name: string): boolean {\n return VALID_PROPERTY_NAME_PATTERN.test(name);\n}\n\n/**\n * Result of parsing a property token.\n */\ninterface ParsedPropertyToken {\n /** The CSS custom property name (e.g., '--my-prop') */\n cssName: string;\n /** Whether this is a color property */\n isColor: boolean;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @property definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalProperties(styles: Styles): boolean {\n return PROPERTIES_KEY in styles;\n}\n\n/**\n * Extract local @property from styles object.\n * Returns null if no local properties (fast path).\n */\nexport function extractLocalProperties(\n styles: Styles,\n): Record<string, PropertyDefinition> | null {\n const properties = styles[PROPERTIES_KEY];\n if (!properties || typeof properties !== 'object') {\n return null;\n }\n return properties as Record<string, PropertyDefinition>;\n}\n\n// ============================================================================\n// Token Parsing Functions\n// ============================================================================\n\n/**\n * Parse a property token name and return the CSS property name and whether it's a color.\n * Supports tasty token syntax and validates the property name.\n *\n * Token formats:\n * - `$name` → { cssName: '--name', isColor: false }\n * - `#name` → { cssName: '--name-color', isColor: true }\n * - `--name` → { cssName: '--name', isColor: false } (legacy, auto-detect color by suffix)\n * - `name` → { cssName: '--name', isColor: false } (legacy)\n *\n * @param token - The property token to parse\n * @returns Parsed result with cssName, isColor, isValid, and optional error\n */\nexport function parsePropertyToken(token: string): ParsedPropertyToken {\n if (!token || typeof token !== 'string') {\n return {\n cssName: '',\n isColor: false,\n isValid: false,\n error: 'Property token must be a non-empty string',\n };\n }\n\n let name: string;\n let isColor: boolean;\n\n if (token.startsWith('$')) {\n // Regular property token: $name → --name\n name = token.slice(1);\n isColor = false;\n } else if (token.startsWith('#')) {\n // Color property token: #name → --name-color\n name = token.slice(1);\n isColor = true;\n } else if (token.startsWith('--')) {\n // Legacy format with -- prefix\n name = token.slice(2);\n isColor = token.endsWith('-color');\n } else {\n // Legacy format without prefix\n name = token;\n isColor = token.endsWith('-color');\n }\n\n // Validate the name\n if (!name) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: 'Property name cannot be empty',\n };\n }\n\n if (!isValidPropertyName(name)) {\n return {\n cssName: '',\n isColor,\n isValid: false,\n error: `Invalid property name \"${name}\". Must start with a letter or underscore, followed by letters, digits, hyphens, or underscores.`,\n };\n }\n\n // Build the CSS custom property name\n // For #name tokens, we add -color suffix\n // For legacy formats (--name-color or name-color), the name already includes -color\n let cssName: string;\n if (token.startsWith('#')) {\n // Color token: #name → --name-color\n cssName = `--${name}-color`;\n } else {\n // All other formats: just add -- prefix\n cssName = `--${name}`;\n }\n\n return {\n cssName,\n isColor,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Normalization Functions\n// ============================================================================\n\n/**\n * Normalize a property name to the CSS custom property format.\n *\n * @deprecated Use parsePropertyToken instead for proper token handling\n */\nexport function normalizePropertyName(name: string): string {\n const result = parsePropertyToken(name);\n return result.isValid ? result.cssName : `--${name}`;\n}\n\n/**\n * Normalize a property definition to a consistent string representation.\n * Used for comparing definitions to detect type conflicts.\n *\n * Only `syntax` and `inherits` are compared — `initialValue` is intentionally\n * excluded because different components may set different defaults for the\n * same typed property (e.g. auto-inferred `0px` vs explicit `6px`).\n *\n * Keys are sorted alphabetically to ensure consistent comparison:\n * { inherits: true, syntax: '<color>' } === { syntax: '<color>', inherits: true }\n */\nexport function normalizePropertyDefinition(def: PropertyDefinition): string {\n const normalized: Record<string, unknown> = {};\n\n if (def.inherits !== undefined) {\n normalized.inherits = def.inherits;\n }\n if (def.syntax !== undefined) {\n normalized.syntax = def.syntax;\n }\n\n return JSON.stringify(normalized);\n}\n\n/**\n * Result of getEffectiveDefinition.\n */\ninterface EffectiveDefinitionResult {\n /** The CSS custom property name */\n cssName: string;\n /** The effective property definition */\n definition: PropertyDefinition;\n /** Whether the token was valid */\n isValid: boolean;\n /** Error message if invalid */\n error?: string;\n}\n\n/**\n * Get the effective property definition for a token.\n * For color tokens (#name), auto-sets syntax to '<color>' and defaults initialValue to 'transparent'.\n *\n * @param token - Property token ($name, #name, --name, or plain name)\n * @param userDefinition - User-provided definition options\n * @returns Effective definition with cssName, definition, isValid, and optional error\n */\nexport function getEffectiveDefinition(\n token: string,\n userDefinition: PropertyDefinition,\n): EffectiveDefinitionResult {\n const parsed = parsePropertyToken(token);\n\n if (!parsed.isValid) {\n return {\n cssName: '',\n definition: userDefinition,\n isValid: false,\n error: parsed.error,\n };\n }\n\n if (parsed.isColor) {\n // Color properties have fixed syntax and default initialValue\n return {\n cssName: parsed.cssName,\n definition: {\n syntax: '<color>', // Always '<color>' for color tokens, cannot be overridden\n inherits: userDefinition.inherits, // Allow inherits to be customized\n initialValue: userDefinition.initialValue ?? 'transparent', // Default to transparent\n },\n isValid: true,\n };\n }\n\n // Regular properties use the definition as-is\n return {\n cssName: parsed.cssName,\n definition: userDefinition,\n isValid: true,\n };\n}\n\n// ============================================================================\n// Value Type Inference\n// ============================================================================\n\n/**\n * Result of inferring a CSS @property syntax from a value.\n */\ninterface InferredSyntax {\n syntax: string;\n initialValue: string;\n}\n\nconst UNIT_TO_SYNTAX: Record<string, InferredSyntax> = {};\n\nconst LENGTH_UNITS = [\n 'px',\n 'em',\n 'rem',\n 'vw',\n 'vh',\n 'vmin',\n 'vmax',\n 'ch',\n 'ex',\n 'cap',\n 'ic',\n 'lh',\n 'rlh',\n 'svw',\n 'svh',\n 'lvw',\n 'lvh',\n 'dvw',\n 'dvh',\n 'cqw',\n 'cqh',\n 'cqi',\n 'cqb',\n 'cqmin',\n 'cqmax',\n];\n\nconst ANGLE_UNITS = ['deg', 'rad', 'grad', 'turn'];\nconst TIME_UNITS = ['ms', 's'];\n\nfor (const u of LENGTH_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<length-percentage>', initialValue: '0px' };\n}\nUNIT_TO_SYNTAX['%'] = { syntax: '<length-percentage>', initialValue: '0px' };\nfor (const u of ANGLE_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<angle>', initialValue: '0deg' };\n}\nfor (const u of TIME_UNITS) {\n UNIT_TO_SYNTAX[u] = { syntax: '<time>', initialValue: '0s' };\n}\n\n/**\n * Infer CSS @property syntax from a concrete value.\n * Detects numeric types: \\<number\\>, \\<length-percentage\\>, \\<angle\\>, \\<time\\>.\n * Length and percentage values both map to \\<length-percentage\\> for maximum flexibility.\n * Color properties are handled separately via the #name token convention\n * (--name-color gets \\<color\\> syntax automatically in getEffectiveDefinition).\n *\n * @param value - The CSS value to infer from (e.g. '10px', '1', '45deg')\n * @returns Inferred syntax and initial value, or null if not inferable\n */\nexport function inferSyntaxFromValue(value: string): InferredSyntax | null {\n if (!value || typeof value !== 'string') return null;\n\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n if (RE_NUMBER.test(trimmed)) {\n // Bare zero is ambiguous (could be <length>, <angle>, <percentage>, etc.)\n if (parseFloat(trimmed) === 0) return null;\n return { syntax: '<number>', initialValue: '0' };\n }\n\n const unitMatch = trimmed.match(RE_RAW_UNIT);\n if (unitMatch) {\n const unit = unitMatch[2];\n const mapping = UNIT_TO_SYNTAX[unit];\n if (mapping) return mapping;\n }\n\n return null;\n}\n","/**\n * Fast string hash (djb2) for deduplication keys.\n * Not cryptographic — just collision-resistant enough for cache keys.\n */\nexport function hashString(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash + str.charCodeAt(i)) | 0;\n }\n return (hash >>> 0).toString(36);\n}\n","/**\n * Name prefix utilities for generated identifiers.\n *\n * Tasty generates three kinds of identifiers from content hashes:\n * - class names (used in DOM `class` attribute)\n * - keyframe names (used in CSS `animation`)\n * - counter-style names (used in CSS `list-style-type`)\n *\n * All three derive from a single configurable prefix so that an app\n * can namespace every identifier under one string. Discriminator letters\n * (`k`, `c`) keep the three kinds visually distinct in devtools — they\n * are not required for correctness (CSS keeps these in separate\n * namespaces), only for readability.\n *\n * The runtime / SSR / RSC paths must agree on the prefix; otherwise the\n * client-side hash for a given style will not match the server-rendered\n * class and hydration breaks. The zero-runtime build path uses a\n * different default (`'ts'`) so its classes can't collide with runtime\n * (`'t'`) classes when both are loaded on the same page.\n */\n\n/** Default prefix used by the runtime / SSR / RSC paths. */\nexport const DEFAULT_NAME_PREFIX = 't';\n\n/** Default prefix used by the zero-runtime (`tastyStatic`) build path. */\nexport const DEFAULT_ZERO_NAME_PREFIX = 'ts';\n\n/**\n * Allowed shape: starts with a letter or underscore, then letters/\n * digits/underscore/hyphen. Length capped at 32 to keep generated\n * names sane. Matches the CSS identifier rules for the common case\n * while keeping the surface conservative.\n */\nconst NAME_PREFIX_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_-]{0,31}$/;\n\n/**\n * Validate a `namePrefix` value.\n * Throws a TypeError with a descriptive message on invalid input so\n * misconfiguration fails loudly at `configure()` time rather than\n * surfacing later as broken hydration.\n */\nexport function validateNamePrefix(prefix: unknown): void {\n if (typeof prefix !== 'string') {\n throw new TypeError(\n `[Tasty] namePrefix must be a string, got ${typeof prefix}.`,\n );\n }\n if (!NAME_PREFIX_PATTERN.test(prefix)) {\n throw new TypeError(\n `[Tasty] namePrefix \"${prefix}\" is invalid. ` +\n `It must start with a letter (a-z, A-Z) or \"_\", contain only ` +\n `letters, digits, \"_\" or \"-\", and be 1-32 characters long. ` +\n `Examples: \"t\", \"ts\", \"myapp-\", \"_foo\".`,\n );\n }\n}\n\n/**\n * Build a class name: `${prefix}${hash}`.\n * The hash is appended verbatim — supply a separator inside the prefix\n * itself if you want one (e.g. `'myapp-'`).\n */\nexport function makeClassName(prefix: string, hash: string): string {\n return `${prefix}${hash}`;\n}\n\n/**\n * Build a keyframe name: `${prefix}k${suffix}`.\n * The `k` discriminator keeps keyframe names visually distinct from\n * class names sharing the same prefix. `suffix` is typically a content\n * hash but may be a counter for ad-hoc allocation.\n */\nexport function makeKeyframeName(prefix: string, suffix: string): string {\n return `${prefix}k${suffix}`;\n}\n\n/**\n * Build a counter-style name: `${prefix}c${suffix}`.\n * The `c` discriminator keeps counter-style names visually distinct\n * from class names sharing the same prefix.\n */\nexport function makeCounterStyleName(prefix: string, suffix: string): string {\n return `${prefix}c${suffix}`;\n}\n\n/** Escape a string for safe inclusion in a regex literal. */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Regex matching any tasty class for the given prefix.\n * Used by the runtime GC's DOM scan and class-allocation bookkeeping.\n */\nexport function tastyClassRegex(prefix: string): RegExp {\n return new RegExp(`^${escapeRegex(prefix)}[a-z0-9]+$`);\n}\n\n/**\n * Global regex extracting tasty class names from RSC-inlined CSS.\n * Looks for the doubled-specificity pattern `.cls.cls` that\n * `formatRules()` always emits, which makes extraction reliable.\n */\nexport function rscClassRegexGlobal(prefix: string): RegExp {\n return new RegExp(`\\\\.(${escapeRegex(prefix)}[a-z0-9]+)\\\\.\\\\1`, 'g');\n}\n","/**\n * Deferred CSSOM writes (\"batched injection\").\n *\n * Every `insertRule()` on a live stylesheet invalidates style for the sheet's\n * scope, so Blink recalculates style the next time anything reads layout or\n * computed style. When components inject during React's render phase and other\n * components read layout in the same pass, the two interleave:\n *\n * inject -> read (forced recalc) -> inject -> read (forced recalc) -> ...\n *\n * Batching moves every sheet write out from between those reads. Writes are\n * queued in FIFO order and drained in one go, so the tree is invalidated once\n * per flush instead of once per component.\n *\n * ## Ordering\n *\n * A single queue holds *all* writes — component rules, global rules, keyframes,\n * `@property`, `@font-face`, `@counter-style`, `@function` and raw CSS. Draining\n * it in insertion order keeps the sheet byte-identical to unbatched output,\n * which matters because equal-specificity rules resolve by document order.\n *\n * ## Batch windows — why queuing is safe\n *\n * Deferring a write past React's layout phase would let a `useLayoutEffect`\n * measure an element whose rules are not in the sheet yet, reading the unstyled\n * box. `<TastyBatchProvider>` closes that hole by opening a *window* during its\n * render and closing it — flushing — in its `useInsertionEffect`, which React\n * runs in the mutation phase, before any layout effect:\n *\n * provider renders -> window OPEN\n * children render -> injections queued\n * provider insertionEffect -> FLUSH, window CLOSED\n * layout effects run -> rules are in the sheet\n *\n * So in the default (`batchInjection: true`) mode a write is only ever queued\n * inside a commit whose flush is already guaranteed by that same commit. Every\n * injection outside a window — a deep update the provider did not re-render\n * for, a `useLayoutEffect` that injects, an event handler, an async callback —\n * is written straight through, exactly as with batching off.\n *\n * `batchInjection: 'always'` opts out of the gate and queues unconditionally.\n * That wins on more commits, at the cost of the measurement hazard above.\n *\n * ## Flush points (earliest wins)\n *\n * 1. `<TastyBatchProvider>`'s `useInsertionEffect` — closes the window.\n * 2. A microtask — a backstop for a render that was aborted or suspended and\n * therefore never reached its insertion effect. An aborted render mounts\n * nothing, so nothing can measure what it queued. Microtasks also always\n * drain before paint, so styles are never visually missing.\n * 3. `flushStyles()` — explicit, and called internally by every injector read\n * API (`getCSSText`, `cleanup`, `gc`, `destroy`, ...).\n */\n\nimport { isDevEnv } from '../utils/is-dev-env';\nimport { warn } from '../utils/warnings';\n\nexport interface QueuedWrite {\n /** Perform the deferred sheet write. */\n run: () => void;\n /** Set when the owner disposed before the write happened. */\n cancelled: boolean;\n /** Set once the write has been applied (or skipped as cancelled). */\n done: boolean;\n}\n\n/**\n * FIFO of pending writes. Drained with a moving `head` index rather than\n * `shift()` so a large batch stays O(n) instead of O(n²).\n */\nlet queue: QueuedWrite[] = [];\nlet head = 0;\nlet microtaskScheduled = false;\nlet flushing = false;\n\n/**\n * Whether a `<TastyBatchProvider>` has rendered in the current commit and will\n * therefore flush in its insertion effect, making it safe to queue a write.\n *\n * A flag rather than a depth count, because renders and insertion effects do\n * not pair up one-to-one. StrictMode double-invokes render but runs the\n * insertion effect once, so a counter ends the commit stuck above zero — and a\n * window that stays open past its commit turns the next provider-less commit\n * into `'always'` mode behind the user's back, which is exactly the measurement\n * hazard `true` exists to avoid.\n *\n * Clearing on the first close is safe with nested or sibling providers: React\n * finishes every render in a commit before running any insertion effect, so once\n * one closes, no further render-phase injection can arrive in that commit.\n */\nlet windowOpen = false;\n/** Whether any window has ever been opened, i.e. a provider is in the tree. */\nlet everOpened = false;\n/** Dev-only: warn at most once that batching is on with no provider mounted. */\nlet warnedNoProvider = false;\n\n/**\n * Queue a sheet write.\n *\n * Returns a handle whose `cancel()` drops the write if the caller disposes\n * before the flush. The handle is intentionally tiny — one is allocated per\n * injected class, on the cache-miss path only.\n */\nexport function enqueueStyleWrite(run: () => void): QueuedWrite {\n // A write triggered by the write currently being drained — an `@property`\n // rule inferred from declarations that are going into the sheet right now —\n // has to land at the position the drain is at, not behind everything already\n // queued after it. Appending would reorder the sheet against unbatched\n // output, so run it in place and hand back an already-done handle.\n if (flushing) {\n run();\n return { run, cancelled: false, done: true };\n }\n\n const entry: QueuedWrite = { run, cancelled: false, done: false };\n queue.push(entry);\n scheduleMicrotaskFlush();\n return entry;\n}\n\n/** Whether any write is still waiting to hit a stylesheet. */\nexport function hasPendingStyleWrites(): boolean {\n return head < queue.length;\n}\n\n/**\n * Open a batch window. Called from `<TastyBatchProvider>`'s render, so every\n * descendant injection in this commit is covered by the provider's insertion\n * effect.\n *\n * Called during render on purpose: the window must be open before children\n * render. It is idempotent — so StrictMode's double render costs nothing — and\n * carries no other side effect. A render that is thrown away is recovered by the\n * microtask backstop.\n *\n * A no-op without a `document`. On the server there is no sheet to batch\n * against, and `useInsertionEffect` never runs, so nothing would ever close a\n * window this opened. Skipping it keeps the provider inert during SSR and RSC\n * instead of merely harmless.\n */\nexport function openBatchWindow(): void {\n if (typeof document === 'undefined') return;\n windowOpen = true;\n everOpened = true;\n}\n\n/**\n * Close a batch window and flush. Called from the provider's\n * `useInsertionEffect`, i.e. after every render in the commit and before any\n * layout effect.\n */\nexport function closeBatchWindow(): void {\n windowOpen = false;\n flushStyles();\n}\n\n/** Whether a batch window is currently open. */\nexport function isBatchWindowOpen(): boolean {\n return windowOpen;\n}\n\nfunction scheduleMicrotaskFlush(): void {\n if (microtaskScheduled || flushing) return;\n microtaskScheduled = true;\n queueMicrotask(() => {\n microtaskScheduled = false;\n // Normally a no-op: the provider's insertion effect has already drained the\n // queue. This only does work when a render was aborted or suspended before\n // reaching that effect, or when running in `'always'` mode.\n windowOpen = false;\n flushStyles();\n });\n}\n\n/**\n * Drain every pending sheet write, in insertion order.\n *\n * Safe to call when the queue is empty (the common case, so the guard comes\n * first) and safe to call re-entrantly: a nested `flushStyles()` is a no-op,\n * and work a draining write triggers is written in place by\n * `enqueueStyleWrite` rather than queued behind the rest of the batch.\n */\nexport function flushStyles(): void {\n if (head >= queue.length) return;\n if (flushing) return;\n\n flushing = true;\n try {\n // `queue.length` is re-read every iteration so a write appended by anything\n // reachable from `run()` that does not go through `enqueueStyleWrite` still\n // gets drained by this loop instead of waiting for the next flush.\n while (head < queue.length) {\n const entry = queue[head++];\n if (entry.cancelled) {\n entry.done = true;\n continue;\n }\n entry.run();\n entry.done = true;\n }\n } finally {\n queue = [];\n head = 0;\n flushing = false;\n }\n}\n\n/**\n * Dev-only: `batchInjection: true` batches nothing unless a window opens, and no\n * window has ever opened, so no provider is in the tree. Called by the injector\n * the first time it declines to batch.\n */\nexport function warnBatchProviderMissing(): void {\n if (everOpened || warnedNoProvider || !isDevEnv()) return;\n warnedNoProvider = true;\n warn('[Tasty] batchInjection needs <TastyBatchProvider> mounted to batch.');\n}\n\n/**\n * Drop every pending write without applying it. Test helper — production code\n * should call `flushStyles()` instead.\n */\nexport function resetStyleBatch(): void {\n queue = [];\n head = 0;\n microtaskScheduled = false;\n flushing = false;\n windowOpen = false;\n everOpened = false;\n warnedNoProvider = false;\n}\n","/**\n * PropertyTypeResolver\n *\n * Automatically infers CSS @property types from custom property values.\n * Supports deferred resolution for var() reference chains of arbitrary depth.\n */\n\nimport { inferSyntaxFromValue } from './index';\n\n/**\n * One `--name: value` declaration, with the surrounding whitespace dropped.\n *\n * The value is anchored on `\\S` at both ends so no two quantifiers can claim\n * the same character. A lazy `(.+?)\\s*$` is quadratic on a value of nothing\n * but spaces — every split point gets tried (CodeQL `js/polynomial-redos`).\n */\nconst CUSTOM_PROP_DECL = /^\\s*(--[a-z0-9_-]+)\\s*:\\s*(\\S|\\S.*\\S)\\s*$/i;\nconst SINGLE_VAR_REF = /^var\\((--[a-z0-9_-]+)\\)$/i;\n\nexport class PropertyTypeResolver {\n /** propName → the prop it depends on */\n private pendingDeps = new Map<string, string>();\n /** propName → list of props waiting on it */\n private reverseDeps = new Map<string, string[]>();\n\n /**\n * Scan CSS declarations and auto-register @property for custom properties\n * whose types can be inferred from their values.\n */\n scanDeclarations(\n declarations: string,\n isPropertyDefined: (name: string) => boolean,\n registerProperty: (\n name: string,\n syntax: string,\n initialValue: string,\n ) => void,\n ): void {\n if (!declarations.includes('--')) return;\n\n const parts = declarations.split(/;+/);\n\n for (const part of parts) {\n if (!part.trim()) continue;\n\n const match = CUSTOM_PROP_DECL.exec(part);\n if (!match) continue;\n\n const propName = match[1];\n const value = match[2].trim();\n\n if (isPropertyDefined(propName)) continue;\n\n // Name-based: --*-color properties are always <color> (from #name tokens)\n if (propName.endsWith('-color')) {\n registerProperty(propName, '<color>', 'transparent');\n continue;\n }\n\n // Name-based: --*-line-height accepts numbers, lengths, and percentages\n if (propName.endsWith('-line-height')) {\n registerProperty(propName, '<number> | <length-percentage>', '0');\n continue;\n }\n\n // Name-based: --*-opacity accepts numbers and percentages\n if (propName.endsWith('-opacity')) {\n registerProperty(propName, '<number> | <percentage>', '0');\n continue;\n }\n\n // Single var() reference → record dependency for deferred resolution\n const varMatch = SINGLE_VAR_REF.exec(value);\n if (varMatch) {\n const depName = varMatch[1];\n this.addDependency(propName, depName);\n continue;\n }\n\n // Skip complex expressions (calc, multiple var, etc.)\n if (this.isComplexValue(value)) continue;\n\n const inferred = inferSyntaxFromValue(value);\n if (!inferred) continue;\n\n this.resolve(\n propName,\n inferred.syntax,\n inferred.initialValue,\n isPropertyDefined,\n registerProperty,\n );\n }\n }\n\n private addDependency(propName: string, depName: string): void {\n if (propName === depName) return;\n\n this.pendingDeps.set(propName, depName);\n\n let dependents = this.reverseDeps.get(depName);\n if (!dependents) {\n dependents = [];\n this.reverseDeps.set(depName, dependents);\n }\n if (!dependents.includes(propName)) {\n dependents.push(propName);\n }\n }\n\n private resolve(\n propName: string,\n syntax: string,\n initialValue: string,\n isPropertyDefined: (name: string) => boolean,\n registerProperty: (\n name: string,\n syntax: string,\n initialValue: string,\n ) => void,\n resolving?: Set<string>,\n ): void {\n if (!resolving) resolving = new Set();\n if (resolving.has(propName)) return;\n resolving.add(propName);\n\n if (!isPropertyDefined(propName)) {\n registerProperty(propName, syntax, initialValue);\n }\n\n const dependents = this.reverseDeps.get(propName);\n if (dependents) {\n this.reverseDeps.delete(propName);\n\n for (const dependent of dependents) {\n this.pendingDeps.delete(dependent);\n\n if (isPropertyDefined(dependent)) continue;\n\n this.resolve(\n dependent,\n syntax,\n initialValue,\n isPropertyDefined,\n registerProperty,\n resolving,\n );\n }\n }\n }\n\n private isComplexValue(value: string): boolean {\n if (value.includes('calc(')) return true;\n const firstVar = value.indexOf('var(');\n if (firstVar === -1) return false;\n if (value.indexOf('var(', firstVar + 4) !== -1) return true;\n return !SINGLE_VAR_REF.test(value);\n }\n}\n","import { PropertyTypeResolver } from '../properties/property-type-resolver';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n InjectionMode,\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\nconst supportsConstructableSheets =\n typeof CSSStyleSheet !== 'undefined' &&\n (() => {\n try {\n new CSSStyleSheet();\n return true;\n } catch {\n return false;\n }\n })();\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 /** Constructable sheets for raw CSS in adopted mode */\n private rawConstructableSheets = new WeakMap<ShadowRoot, CSSStyleSheet>();\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 * Resolve the underlying CSSStyleSheet from a SheetInfo,\n * abstracting away adopted vs style-element modes.\n */\n getCSSSheet(sheetInfo: SheetInfo): CSSStyleSheet | null {\n if (sheetInfo.constructableSheet) return sheetInfo.constructableSheet;\n return sheetInfo.sheet?.sheet ?? null;\n }\n\n /**\n * Record an inserted rule text at its rule index (text mode only).\n *\n * `textRules` mirrors the sheet's rule order. `textContent` cannot be edited\n * rule-by-rule the way CSSOM can, so keeping the texts is what makes\n * deletion possible at all in this mode.\n */\n private trackTextRule(\n sheet: SheetInfo,\n ruleIndex: number,\n ruleText: string,\n ): void {\n if (!sheet.textMode) return;\n\n const rules = (sheet.textRules ??= []);\n // Defensive: keep the array dense so indices stay meaningful\n while (rules.length < ruleIndex) rules.push('');\n rules[ruleIndex] = ruleText;\n }\n\n /**\n * Remove rule indices from a text-mode sheet and rewrite the element's text.\n * Returns the indices that were actually removed.\n */\n private deleteTextRules(sheet: SheetInfo, indices: number[]): number[] {\n const rules = sheet.textRules;\n if (!rules) return [];\n\n const removed = [...new Set(indices)]\n .filter((idx) => idx >= 0 && idx < rules.length)\n .sort((a, b) => b - a);\n\n for (const idx of removed) {\n rules.splice(idx, 1);\n }\n\n if (removed.length > 0 && sheet.sheet) {\n sheet.sheet.textContent = rules.length ? '\\n' + rules.join('\\n') : '';\n }\n\n return removed;\n }\n\n /**\n * Determine the injection mode for a root.\n * ShadowRoot uses adopted stylesheets when supported; Document uses <style> elements.\n */\n private detectInjectionMode(root: Document | ShadowRoot): InjectionMode {\n if (\n root instanceof ShadowRoot &&\n supportsConstructableSheets &&\n !this.config.forceTextInjection\n ) {\n return 'adopted';\n }\n return 'style-element';\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 pinCounts: 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 Map<string, boolean>(),\n injectedFunctions: new Map<string, boolean>(),\n globalRules: new Map(),\n propertyTypeResolver: new PropertyTypeResolver(),\n unusedSince: new Map(),\n localKeyframes: new Map(),\n touchCount: 0,\n serverClassSyncIndex: 0,\n rscStylesScanned: false,\n injectionMode: this.detectInjectionMode(root),\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 * In adopted mode (ShadowRoot), creates a constructable CSSStyleSheet and\n * pushes it to adoptedStyleSheets. Otherwise creates a <style> element.\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n if (registry.injectionMode === 'adopted') {\n const constructableSheet = new CSSStyleSheet();\n\n // Append after any existing raw CSS sheet\n (root as ShadowRoot).adoptedStyleSheets = [\n ...(root as ShadowRoot).adoptedStyleSheets,\n constructableSheet,\n ];\n\n const sheetInfo: SheetInfo = {\n sheet: null,\n constructableSheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n const sheet = this.createStyleElement(root);\n\n // Pin the write mode now: `insertRule` and `deleteRule` must agree on it for\n // the lifetime of the sheet, otherwise tracked rule indices desync from\n // whichever representation is actually applied.\n const textMode =\n this.config.forceTextInjection === true || sheet.sheet == null;\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n textMode,\n ...(textMode ? { textRules: [] } : {}),\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(\n '[Tasty] SheetManager: style element failed to connect to the DOM.',\n {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n },\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\n const styleElement = targetSheet.sheet;\n const styleSheet = this.getCSSSheet(targetSheet);\n\n if (!targetSheet.textMode && styleSheet) {\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 // For @property rules specifically, probe once per registry to distinguish\n // \"engine doesn't support @property at all\" (e.g., jsdom) from\n // \"engine supports @property but this specific rule is invalid\"\n // (a real user bug worth warning about).\n if (process.env.NODE_ENV !== 'production') {\n const isAtProperty = fullRule.startsWith('@property ');\n const shouldSuppress =\n isAtProperty &&\n !this.engineSupportsAtProperty(registry, styleSheet);\n if (!shouldSuppress) {\n console.warn(\n '[Tasty] Browser rejected CSS rule:',\n fullRule,\n e,\n );\n }\n }\n }\n }\n } else if (styleElement) {\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 // Record the text so `deleteRule` can rebuild the element without it\n this.trackTextRule(targetSheet, atomicRuleIndex, fullRule);\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 // Report a detached style element only if there are issues and we're not using forceTextInjection\n if (\n styleElement &&\n !styleElement.parentNode &&\n !this.config.forceTextInjection\n ) {\n console.error(\n '[Tasty] SheetManager: style element is not attached to the DOM; rules will not apply.',\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('[Tasty] 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 styleSheet = this.getCSSSheet(sheet);\n\n if (sheet.textMode) {\n // Text mode: splice the rules out of the tracked texts and rewrite the\n // element. Never also touch CSSOM here — assigning textContent\n // reparses the sheet, so a CSSOM delete would be undone anyway.\n let targetIndices: number[];\n\n if (ruleInfo.indices && ruleInfo.indices.length > 0) {\n targetIndices = ruleInfo.indices;\n } else {\n // FALLBACK: range-based deletion, mirroring the CSSOM path below\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n (sheet.textRules?.length ?? 0) - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n targetIndices = [];\n for (let idx = startIdx; idx <= endIdx; idx++) {\n targetIndices.push(idx);\n }\n }\n\n const deletedIndices = this.deleteTextRules(sheet, targetIndices);\n\n if (deletedIndices.length > 0) {\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\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 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(\n `[Tasty] Failed to delete rule at index ${idx}:`,\n e,\n );\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('[Tasty] 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 * Probe whether the underlying CSS engine supports `@property` at-rules.\n * Result is cached per registry on `registry.atPropertySupported`.\n *\n * The probe inserts and immediately deletes a minimal known-valid rule\n * (`@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }`).\n * Engines that lack `@property` support (jsdom, happy-dom) reject any\n * `@property` rule including this one, so a probe failure is a reliable\n * signal that further `@property` rejections are environmental noise and\n * not user-authored bugs.\n *\n * The probe is intentionally a separate operation from the user's failing\n * insertion: we don't want to leak `--__tasty_probe__` into the sheet, so\n * on success we delete the probe rule immediately, leaving `ruleCount`\n * and `cssRules.length` unchanged.\n */\n private engineSupportsAtProperty(\n registry: RootRegistry,\n styleSheet: CSSStyleSheet,\n ): boolean {\n if (registry.atPropertySupported !== undefined) {\n return registry.atPropertySupported;\n }\n\n const probeRule =\n '@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }';\n\n try {\n const probeIdx = styleSheet.cssRules.length;\n styleSheet.insertRule(probeRule, probeIdx);\n try {\n styleSheet.deleteRule(probeIdx);\n } catch {\n // noop: unable to delete the probe; leaving it in is harmless\n // (declares an unused CSS custom property scoped to documentElement)\n }\n registry.atPropertySupported = true;\n } catch {\n registry.atPropertySupported = false;\n }\n\n return registry.atPropertySupported;\n }\n\n /**\n * Delete the given classes: their rules leave the sheets and every registry\n * entry pointing at them is dropped.\n *\n * Deciding *what* is unused belongs to `StyleInjector.gc()`, which owns the\n * DOM scan and the capacity policy. This only re-checks that each class is\n * still safe to delete, and reports how many were.\n *\n * @returns Number of classes actually deleted.\n */\n public deleteClasses(\n registry: RootRegistry,\n classNames: Iterable<string>,\n ): number {\n const cleanupStartTime = Date.now();\n\n const selected = Array.from(classNames)\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 if (selected.length === 0) return 0;\n\n const deleted = new Set<string>();\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: Never delete a class someone pinned\n if ((registry.pinCounts.get(className) ?? 0) > 0) {\n // Class was pinned again between collection and deletion\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 entry is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || (!sheetInfo.sheet && !sheetInfo.constructableSheet)) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the rule storage itself is accessible.\n // Text-mode sheets are backed by `textRules`, not CSSOM, so a missing\n // CSSStyleSheet is expected there and must not block cleanup.\n const styleSheet = this.getCSSSheet(sheetInfo);\n if (!sheetInfo.textMode && !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 =\n (sheetInfo.textMode\n ? (sheetInfo.textRules?.length ?? 0)\n : (styleSheet?.cssRules.length ?? 0)) - 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.pinCounts.delete(className);\n registry.unusedSince.delete(className);\n\n // Last class animating these keyframes: nothing refers to them now.\n for (const [key, entry] of registry.localKeyframes) {\n if (!entry.owners.delete(className)) continue;\n if (entry.owners.size === 0) {\n entry.dispose();\n registry.localKeyframes.delete(key);\n }\n }\n deleted.add(className);\n cleanedUpCount++;\n }\n }\n\n // Cache keys are indexed by key, not by className, so finding the ones that\n // point at a deleted class means scanning the map — once for the whole\n // batch rather than once per class.\n if (deleted.size > 0) {\n for (const [key, mappedClassName] of registry.cacheKeyToClassName) {\n if (deleted.has(mappedClassName)) {\n registry.cacheKeyToClassName.delete(key);\n }\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 return cleanedUpCount;\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 * The CSS of one managed sheet, or `null` when it holds none this can read —\n * an empty style element, or a sheet the engine refuses to hand over.\n */\n private readSheetCSS(sheetInfo: SheetInfo): string | null {\n try {\n if (sheetInfo.constructableSheet) {\n const rules = Array.from(sheetInfo.constructableSheet.cssRules);\n return rules.map((rule) => rule.cssText).join('\\n');\n }\n\n if (sheetInfo.sheet) {\n const styleElement = sheetInfo.sheet;\n if (styleElement.textContent) return styleElement.textContent;\n if (styleElement.sheet) {\n const rules = Array.from(styleElement.sheet.cssRules);\n return rules.map((rule) => rule.cssText).join('\\n');\n }\n }\n } catch (error) {\n console.warn('[Tasty] Failed to read CSS from sheet:', error);\n }\n\n return null;\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 sheetInfo of registry.sheets) {\n const css = this.readSheetCSS(sheetInfo);\n if (css !== null) cssChunks.push(css);\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 // `unusedHits` needs a DOM scan to be meaningful, so `StyleInjector.getMetrics()`\n // fills it in; a registry on its own cannot tell which classes are still rendered.\n return {\n ...registry.metrics,\n unusedHits: 0,\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 styleSheet = this.getCSSSheet(targetSheet);\n\n if (!targetSheet.textMode && styleSheet) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else if (targetSheet.sheet) {\n // Keyframes share the sheet's rule-index sequence, so their text has to\n // be tracked too or every later index desyncs\n this.trackTextRule(targetSheet, ruleIndex, fullRule);\n targetSheet.sheet.textContent =\n (targetSheet.sheet.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('[Tasty] 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 styleSheet = this.getCSSSheet(sheet);\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 const adjustIndices = () =>\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 if (sheet.textMode) {\n const deleted = this.deleteTextRules(sheet, [info.ruleIndex]);\n\n if (deleted.length > 0) {\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n adjustIndices();\n }\n } else 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 adjustIndices();\n }\n }\n } catch (error) {\n console.warn('[Tasty] 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 if (registry.injectionMode === 'adopted') {\n // Remove all adopted stylesheets from the shadow root\n const shadowRoot = root as ShadowRoot;\n\n // Collect all constructable sheets owned by this registry\n const ownedSheets = new Set<CSSStyleSheet>();\n for (const sheetInfo of registry.sheets) {\n if (sheetInfo.constructableSheet) {\n ownedSheets.add(sheetInfo.constructableSheet);\n }\n }\n\n // Also include the raw CSS constructable sheet\n const rawSheet = this.rawConstructableSheets.get(shadowRoot);\n if (rawSheet) {\n ownedSheets.add(rawSheet);\n this.rawConstructableSheets.delete(shadowRoot);\n }\n\n // Remove owned sheets from adoptedStyleSheets\n if (ownedSheets.size > 0) {\n shadowRoot.adoptedStyleSheets = shadowRoot.adoptedStyleSheets.filter(\n (s) => !ownedSheets.has(s),\n );\n }\n } else {\n // Remove all <style> elements\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement?.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('[Tasty] Failed to cleanup sheet:', error);\n }\n }\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 }\n\n // Clear registry\n this.rootRegistries.delete(root);\n this.activeRoots.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Check if a root uses adopted injection mode.\n */\n private isAdoptedMode(root: Document | ShadowRoot): boolean {\n const registry = this.rootRegistries.get(root);\n if (registry) return registry.injectionMode === 'adopted';\n return this.detectInjectionMode(root) === 'adopted';\n }\n\n /**\n * Get or create a constructable CSSStyleSheet for raw CSS in adopted mode.\n * The raw sheet is prepended to adoptedStyleSheets so it precedes tasty rules.\n */\n private getOrCreateRawAdoptedSheet(root: ShadowRoot): CSSStyleSheet {\n let sheet = this.rawConstructableSheets.get(root);\n\n if (!sheet) {\n sheet = new CSSStyleSheet();\n // Prepend raw sheet before any tasty-managed sheets for cascade ordering\n root.adoptedStyleSheets = [sheet, ...root.adoptedStyleSheets];\n this.rawConstructableSheets.set(root, sheet);\n if (!this.rawCSSBlocks.has(root)) {\n this.rawCSSBlocks.set(root, new Map());\n }\n }\n\n return sheet;\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 // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n if (this.isAdoptedMode(root)) {\n this.getOrCreateRawAdoptedSheet(root as ShadowRoot);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n const info: RawCSSInfo = {\n id,\n css,\n startOffset: 0,\n endOffset: css.length,\n };\n blocksMap.set(id, info);\n\n // Rebuild full text and apply via replaceSync\n this.rebuildRawAdoptedSheet(root as ShadowRoot);\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\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 * Rebuild the raw CSS constructable sheet from all tracked blocks.\n */\n private rebuildRawAdoptedSheet(root: ShadowRoot): void {\n const sheet = this.rawConstructableSheets.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!sheet || !blocksMap) return;\n\n if (blocksMap.size === 0) {\n sheet.replaceSync('');\n return;\n }\n\n const blocks = Array.from(blocksMap.values());\n blocks.sort((a, b) => a.startOffset - b.startOffset);\n const allCSS = blocks.map((b) => b.css).join('\\n');\n sheet.replaceSync(allCSS);\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!blocksMap) return;\n\n const info = blocksMap.get(id);\n if (!info) return;\n\n blocksMap.delete(id);\n\n // Adopted mode: rebuild via replaceSync\n if (this.isAdoptedMode(root)) {\n this.rebuildRawAdoptedSheet(root as ShadowRoot);\n return;\n }\n\n // Style-element mode: rebuild textContent\n const styleElement = this.rawStyleElements.get(root);\n if (!styleElement) return;\n\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\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\n */\n /**\n * The CSS this injector owns in `root`, one entry per sheet, in the order the\n * engine applies them.\n *\n * `getCSSText()` walks the managed sheets only, and raw CSS has its own —\n * which sits before, after, or *between* them depending on how it got there:\n * prepended to `adoptedStyleSheets`, or wherever in `<head>` the first raw\n * injection happened to land, with every managed sheet opened afterwards\n * following it. Reporting a fixed order would describe the opposite winner\n * from the live page whenever two rules of equal specificity meet, so the raw\n * sheet is spliced in at the position the DOM actually gives it.\n */\n getOwnedCSSInOrder(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n ): string[] {\n const raw = this.getRawCSSText(root);\n // Adopted mode prepends the raw sheet to `adoptedStyleSheets`, always, so\n // there is nothing to compare positions against.\n const rawElement = this.isAdoptedMode(root)\n ? null\n : this.rawStyleElements.get(root);\n\n let rawIndex = raw && !rawElement ? 0 : -1;\n const chunks: string[] = [];\n\n for (const sheetInfo of registry.sheets) {\n const css = this.readSheetCSS(sheetInfo);\n if (css === null) continue;\n\n if (\n rawIndex < 0 &&\n rawElement &&\n sheetInfo.sheet &&\n // DOCUMENT_POSITION_FOLLOWING: this managed sheet comes after the raw\n // one, so the raw CSS belongs in front of it.\n rawElement.compareDocumentPosition(sheetInfo.sheet) &\n Node.DOCUMENT_POSITION_FOLLOWING\n ) {\n rawIndex = chunks.length;\n }\n\n chunks.push(css);\n }\n\n if (!raw) return chunks;\n\n // No managed sheet follows it: the raw CSS is last.\n chunks.splice(rawIndex < 0 ? chunks.length : rawIndex, 0, raw);\n\n return chunks;\n }\n\n /**\n * Top-level rules in the raw sheet.\n *\n * Read from the sheet the engine parsed, not from the text: a raw block is\n * one string but any number of rules, and one rule — `@keyframes`, `@media` —\n * can contain any number of blocks, so counting braces answers neither\n * question.\n */\n getRawRuleCount(root: Document | ShadowRoot): number {\n const sheet = this.isAdoptedMode(root)\n ? this.rawConstructableSheets.get(root as ShadowRoot)\n : this.rawStyleElements.get(root)?.sheet;\n\n try {\n return sheet?.cssRules.length ?? 0;\n } catch {\n // Sheet not readable (not yet attached, or cross-origin).\n return 0;\n }\n }\n\n getRawCSSText(root: Document | ShadowRoot): string {\n // In adopted mode, read from the blocks map (source of truth)\n if (this.isAdoptedMode(root)) {\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!blocksMap || blocksMap.size === 0) return '';\n const blocks = Array.from(blocksMap.values());\n blocks.sort((a, b) => a.startOffset - b.startOffset);\n return blocks.map((b) => b.css).join('\\n');\n }\n\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n","/**\n * Font Face Utilities\n *\n * Utilities for extracting and processing CSS @font-face definitions in styles.\n * Font-face rules are permanent once injected and do not need cleanup.\n */\n\nimport type { FontFaceDescriptors, FontFaceInput } from '../injector/types';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst FONT_FACE_KEY = '@font-face';\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @font-face definition.\n */\nexport function hasLocalFontFace(styles: Styles): boolean {\n return FONT_FACE_KEY in styles;\n}\n\n/**\n * Extract local @font-face from styles object.\n * Returns null if no local font faces (fast path).\n */\nexport function extractLocalFontFace(\n styles: Styles,\n): Record<string, FontFaceInput> | null {\n const fontFace = styles[FONT_FACE_KEY];\n if (!fontFace || typeof fontFace !== 'object') {\n return null;\n }\n return fontFace as Record<string, FontFaceInput>;\n}\n\n// ============================================================================\n// CSS Formatting\n// ============================================================================\n\nconst FONT_FACE_DESCRIPTOR_MAP: Record<string, string> = {\n fontWeight: 'font-weight',\n fontStyle: 'font-style',\n fontStretch: 'font-stretch',\n fontDisplay: 'font-display',\n unicodeRange: 'unicode-range',\n ascentOverride: 'ascent-override',\n descentOverride: 'descent-override',\n lineGapOverride: 'line-gap-override',\n sizeAdjust: 'size-adjust',\n fontFeatureSettings: 'font-feature-settings',\n fontVariationSettings: 'font-variation-settings',\n};\n\n/**\n * Format the inner declarations of a @font-face rule (no wrapper).\n * Used by the injector which needs selector and declarations separately.\n */\nexport function formatFontFaceDeclarations(\n family: string,\n descriptors: FontFaceDescriptors,\n): string {\n const parts: string[] = [];\n\n parts.push(`font-family: \"${family}\";`);\n parts.push(`src: ${descriptors.src};`);\n\n for (const [key, cssName] of Object.entries(FONT_FACE_DESCRIPTOR_MAP)) {\n const value = descriptors[key as keyof FontFaceDescriptors];\n if (value !== undefined) {\n parts.push(`${cssName}: ${value};`);\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format a single @font-face rule as CSS.\n */\nexport function formatFontFaceRule(\n family: string,\n descriptors: FontFaceDescriptors,\n): string {\n return `@font-face { ${formatFontFaceDeclarations(family, descriptors)} }`;\n}\n\n/**\n * Format all @font-face rules for a family (handles single or array form).\n * Returns an array of CSS strings, one per rule.\n */\nexport function formatFontFaceRules(\n family: string,\n input: FontFaceInput,\n): string[] {\n const descriptors = Array.isArray(input) ? input : [input];\n return descriptors.map((desc) => formatFontFaceRule(family, desc));\n}\n\n/**\n * Generate a content hash for deduplication of a single font-face rule.\n */\nexport function fontFaceContentHash(\n family: string,\n descriptors: FontFaceDescriptors,\n): string {\n return JSON.stringify({ family, ...descriptors });\n}\n","/**\n * Counter Style Utilities\n *\n * Utilities for extracting and processing CSS @counter-style definitions in styles.\n * Counter-style rules are permanent once injected and do not need cleanup.\n */\n\nimport type { CounterStyleDescriptors } from '../injector/types';\nimport type { Styles } from '../styles/types';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst COUNTER_STYLE_KEY = '@counter-style';\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @counter-style definition.\n */\nexport function hasLocalCounterStyle(styles: Styles): boolean {\n return COUNTER_STYLE_KEY in styles;\n}\n\n/**\n * Extract local @counter-style from styles object.\n * Returns null if no local counter styles (fast path).\n */\nexport function extractLocalCounterStyle(\n styles: Styles,\n): Record<string, CounterStyleDescriptors> | null {\n const counterStyle = styles[COUNTER_STYLE_KEY];\n if (!counterStyle || typeof counterStyle !== 'object') {\n return null;\n }\n return counterStyle as Record<string, CounterStyleDescriptors>;\n}\n\n// ============================================================================\n// CSS Formatting\n// ============================================================================\n\nconst COUNTER_STYLE_DESCRIPTOR_MAP: Record<string, string> = {\n system: 'system',\n symbols: 'symbols',\n additiveSymbols: 'additive-symbols',\n prefix: 'prefix',\n suffix: 'suffix',\n negative: 'negative',\n range: 'range',\n pad: 'pad',\n fallback: 'fallback',\n speakAs: 'speak-as',\n};\n\n/**\n * Format the inner declarations of a @counter-style rule (no wrapper).\n * Used by the injector which needs selector and declarations separately.\n */\nexport function formatCounterStyleDeclarations(\n descriptors: CounterStyleDescriptors,\n): string {\n const parts: string[] = [];\n\n for (const [key, cssName] of Object.entries(COUNTER_STYLE_DESCRIPTOR_MAP)) {\n const value = descriptors[key as keyof CounterStyleDescriptors];\n if (value !== undefined) {\n parts.push(`${cssName}: ${value};`);\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Format a @counter-style rule as CSS.\n */\nexport function formatCounterStyleRule(\n name: string,\n descriptors: CounterStyleDescriptors,\n): string {\n return `@counter-style ${name} { ${formatCounterStyleDeclarations(descriptors)} }`;\n}\n","/**\n * Style injector that works with structured style objects\n * Eliminates CSS string parsing for better performance\n */\n\nimport type { StyleResult } from '../pipeline';\nimport {\n getEffectiveDefinition,\n normalizePropertyDefinition,\n} from '../properties';\nimport { hashString } from '../utils/hash';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport {\n DEFAULT_NAME_PREFIX,\n makeClassName,\n makeKeyframeName,\n rscClassRegexGlobal,\n tastyClassRegex,\n validateNamePrefix,\n} from '../utils/name-prefix';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\nimport {\n enqueueStyleWrite,\n flushStyles,\n isBatchWindowOpen,\n warnBatchProviderMissing,\n} from './batch';\nimport type { QueuedWrite } from './batch';\nimport { SheetManager } from './sheet-manager';\nimport { fontFaceContentHash, formatFontFaceDeclarations } from '../font-face';\nimport { formatCounterStyleDeclarations } from '../counter-style';\nimport {\n formatFunctionDeclarations,\n formatFunctionPrelude,\n parseFunctionName,\n} from '../functions';\nimport {\n HYDRATED_RULE_INDEX,\n PENDING_RULE_INDEX,\n PLACEHOLDER_RULE_INDEX,\n} from './types';\nimport type {\n CacheMetrics,\n CounterStyleDescriptors,\n FontFaceDescriptors,\n FunctionDefinition,\n GCOptions,\n GlobalInjectResult,\n InjectOptions,\n InjectResult,\n KeyframesCacheEntry,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n PropertyDefinition,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\n/**\n * How long a class is left alone after it was last known to be wanted.\n * Long enough that a render cannot plausibly still be waiting to commit one.\n */\nconst DEFAULT_GC_GRACE = 10_000;\n\n/** Dispose handle handed back for injections that took no pin. */\nconst noop = () => {\n /* nothing to release */\n};\n\n/**\n * Placeholder `KeyframesInfo` for a cache entry reserved by a batched write and\n * not yet backed by a real rule. Only ever read through `entry.pending`, which\n * is checked before the info is used.\n */\nconst EMPTY_KEYFRAMES_INFO = {\n name: '',\n ruleIndex: PENDING_RULE_INDEX,\n sheetIndex: PENDING_RULE_INDEX,\n} as unknown as KeyframesInfo;\n\n/**\n * Extract class names from `<style data-tasty-rsc>` tags.\n * The doubled-specificity pattern `.tXXX.tXXX` makes extraction reliable.\n */\nfunction extractRSCClassNames(rscClassRegex: RegExp): string[] {\n if (typeof document === 'undefined') return [];\n const styles = document.querySelectorAll('style[data-tasty-rsc]');\n if (styles.length === 0) return [];\n\n const classSet = new Set<string>();\n for (const style of styles) {\n const text = style.textContent;\n if (!text) continue;\n let match: RegExpExecArray | null;\n rscClassRegex.lastIndex = 0;\n while ((match = rscClassRegex.exec(text)) !== null) {\n classSet.add(match[1]);\n }\n }\n return Array.from(classSet);\n}\n\n/**\n * Lazily sync server-rendered class names into the client registry.\n *\n * Sources:\n * 1. `window.__TASTY__` — pushed by SSR/RSC streaming scripts\n * 2. `<style data-tasty-rsc>` tags — inline CSS emitted by RSC components\n *\n * Called inside `inject()` / `allocateClassName()` to pick up\n * class names rendered on the server (including during SPA navigation).\n */\nfunction syncServerClasses(\n registry: RootRegistry,\n rscClassRegex: RegExp,\n): void {\n if (typeof window === 'undefined') return;\n\n // Source 1: window.__TASTY__ (SSR streaming scripts)\n const classes = window.__TASTY__;\n if (classes && classes.length > registry.serverClassSyncIndex) {\n for (let i = registry.serverClassSyncIndex; i < classes.length; i++) {\n registerHydratedClass(registry, classes[i]);\n }\n registry.serverClassSyncIndex = classes.length;\n }\n\n // Source 2: <style data-tasty-rsc> tags (RSC inline styles)\n if (!registry.rscStylesScanned) {\n registry.rscStylesScanned = true;\n for (const cls of extractRSCClassNames(rscClassRegex)) {\n registerHydratedClass(registry, cls);\n }\n }\n}\n\nfunction registerHydratedClass(\n registry: RootRegistry,\n className: string,\n): void {\n if (registry.rules.has(className)) return;\n registry.rules.set(className, {\n className,\n ruleIndex: HYDRATED_RULE_INDEX,\n sheetIndex: HYDRATED_RULE_INDEX,\n });\n registry.pinCounts.set(className, 0);\n}\n\nexport class StyleInjector {\n private sheetManager: SheetManager;\n private config: StyleInjectorConfig;\n private globalRuleCounter = 0;\n /** Cancels the scheduled sweep, whichever timer scheduled it. */\n private cancelPendingGC: (() => void) | null = null;\n private namePrefix: string;\n private classRegex: RegExp;\n private rscClassRegex: RegExp;\n\n /** @internal — exposed for debug utilities only */\n get _sheetManager(): SheetManager {\n return this.sheetManager;\n }\n\n /**\n * Whether sheet writes should be queued instead of applied immediately.\n *\n * Only ever true on the client: SSR collects CSS as text and the RSC path\n * returns it as strings, so neither has a live sheet to batch writes against.\n *\n * In the default `true` mode a write is only queued inside an open batch\n * window — a commit in which `<TastyBatchProvider>` rendered and will\n * therefore flush in its insertion effect, before any layout effect can\n * measure. Everything else falls through to a synchronous write, so enabling\n * the flag cannot make a `useLayoutEffect` read an unstyled element.\n * `'always'` drops the gate and accepts that trade for wider coverage.\n */\n private get batching(): boolean {\n const mode = this.config.batchInjection;\n if (!mode || typeof document === 'undefined') return false;\n if (mode === 'always') return true;\n if (isBatchWindowOpen()) return true;\n warnBatchProviderMissing();\n return false;\n }\n\n /**\n * Apply a sheet write now, or queue it when batching is on.\n * Returns the queue handle when deferred, so the caller can cancel it if it\n * disposes before the flush.\n */\n private writeSheet(task: () => void): QueuedWrite | null {\n if (this.batching) return enqueueStyleWrite(task);\n task();\n return null;\n }\n\n /**\n * Insert a global (non-class) rule, honouring batching.\n *\n * `onApplied` records the caller's dedupe bookkeeping. When the write is\n * queued it runs eagerly, so a repeat call before the flush bails out instead\n * of queueing the same rule twice — the same reasoning as\n * `insertPropertyRule`'s eager marking. When written synchronously it runs\n * only on success, preserving the existing retry-on-failure behaviour.\n */\n private writeGlobalRule(\n registry: RootRegistry,\n rules: StyleRule[],\n key: string,\n root: Document | ShadowRoot,\n onApplied?: () => void,\n ): void {\n if (this.batching) {\n onApplied?.();\n enqueueStyleWrite(() => {\n this.sheetManager.insertGlobalRule(registry, rules, key, root);\n });\n return;\n }\n const info = this.sheetManager.insertGlobalRule(registry, rules, key, root);\n if (info) onApplied?.();\n }\n\n constructor(config: StyleInjectorConfig = {}) {\n if (config.namePrefix !== undefined) {\n validateNamePrefix(config.namePrefix);\n }\n this.config = config;\n this.sheetManager = new SheetManager(config);\n this.namePrefix = config.namePrefix ?? DEFAULT_NAME_PREFIX;\n this.classRegex = tastyClassRegex(this.namePrefix);\n this.rscClassRegex = rscClassRegexGlobal(this.namePrefix);\n }\n\n /**\n * Generate a deterministic class name from a cache key using content hash.\n * The same cache key always produces the same class name across environments\n * with the same `namePrefix`.\n */\n private generateClassName(cacheKey: string): string {\n return makeClassName(this.namePrefix, hashString(cacheKey));\n }\n\n /**\n * Check if `className` was hydrated from server-rendered styles and,\n * if so, wire the cacheKey mapping. Returns true on hit.\n */\n private tryHydratedHit(\n registry: RootRegistry,\n cacheKey: string,\n className: string,\n ): boolean {\n syncServerClasses(registry, this.rscClassRegex);\n const rule = registry.rules.get(className);\n if (\n rule &&\n rule.ruleIndex === HYDRATED_RULE_INDEX &&\n rule.sheetIndex === HYDRATED_RULE_INDEX\n ) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n return true;\n }\n return false;\n }\n\n /**\n * Allocate a className for a cacheKey without injecting styles yet.\n * This allows separating className allocation (render phase) from style injection (insertion phase).\n */\n allocateClassName(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n ): { className: string; isNewAllocation: boolean } {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Check if we can reuse existing className for this cache key\n if (registry.cacheKeyToClassName.has(cacheKey)) {\n const className = registry.cacheKeyToClassName.get(cacheKey)!;\n return {\n className,\n isNewAllocation: false,\n };\n }\n\n // Generate deterministic className from cache key\n const className = this.generateClassName(cacheKey);\n\n // Check if this className was hydrated from server-rendered styles\n if (this.tryHydratedHit(registry, cacheKey, className)) {\n return { className, isNewAllocation: false };\n }\n\n // Hash collision guard: another cache key already owns this class name\n const existingRule = registry.rules.get(className);\n if (existingRule) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] Hash collision: cache keys produce the same class \"${className}\". Styles may be incorrect.`,\n );\n }\n // Treat as already allocated to avoid overwriting\n registry.cacheKeyToClassName.set(cacheKey, className);\n return { className, isNewAllocation: false };\n }\n\n // Create placeholder RuleInfo to reserve the className\n const placeholderRuleInfo = {\n className,\n ruleIndex: PLACEHOLDER_RULE_INDEX,\n sheetIndex: PLACEHOLDER_RULE_INDEX,\n };\n\n // Store RuleInfo only once by className, and map cacheKey separately\n registry.rules.set(className, placeholderRuleInfo);\n registry.cacheKeyToClassName.set(cacheKey, className);\n\n return {\n className,\n isNewAllocation: true,\n };\n }\n\n /**\n * Inject styles from StyleResult objects\n */\n inject(rules: StyleResult[], options?: InjectOptions): InjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n // `pin: false` injects without holding the class: the caller keeps no handle\n // and lets the DOM decide when the class is done (see `gc()`).\n const pin = options?.pin ?? true;\n\n if (rules.length === 0) {\n return {\n className: '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Rules are now in StyleRule format directly\n\n // Check if we can reuse based on cache key\n const cacheKey = options?.cacheKey;\n let className: string;\n\n if (cacheKey && registry.cacheKeyToClassName.has(cacheKey)) {\n // Reuse existing class for this cache key\n className = registry.cacheKeyToClassName.get(cacheKey)!;\n const existingRuleInfo = registry.rules.get(className)!;\n\n // Rules are already queued for a batched write. Record the pin and let\n // the queued write land — injecting again would duplicate every rule.\n if (existingRuleInfo.ruleIndex === PENDING_RULE_INDEX) {\n registry.unusedSince.delete(className);\n if (pin) {\n registry.pinCounts.set(\n className,\n (registry.pinCounts.get(className) || 0) + 1,\n );\n }\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n\n // A placeholder means the class name was pre-allocated but its CSS was\n // never injected, so fall through and inject it now. Anything else is\n // already in a sheet.\n const isPreAllocated =\n existingRuleInfo.ruleIndex === PLACEHOLDER_RULE_INDEX &&\n existingRuleInfo.sheetIndex === PLACEHOLDER_RULE_INDEX;\n\n if (!isPreAllocated) {\n // Handing the class to a render makes it wanted again: clearing the\n // cold mark puts it back in band 1/3, so a sweep cannot take it out\n // from under a render that has not committed yet. A `delete` that\n // misses is what the live case costs, which is nothing.\n registry.unusedSince.delete(className);\n\n // Already injected — nothing to write, only the reference to record.\n if (pin) {\n const pins = registry.pinCounts.get(className) || 0;\n registry.pinCounts.set(className, pins + 1);\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n } else if (cacheKey) {\n // Generate deterministic className from cache key\n className = this.generateClassName(cacheKey);\n\n // Check if this className was hydrated from server-rendered styles\n if (this.tryHydratedHit(registry, cacheKey, className)) {\n if (pin) {\n registry.pinCounts.set(\n className,\n (registry.pinCounts.get(className) || 0) + 1,\n );\n }\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n } else {\n // No cache key — generate from rules content\n const parts = rules.map((r) => `${r.selector}\\0${r.declarations}`);\n className = makeClassName(this.namePrefix, hashString(parts.join('\\n')));\n }\n\n // Process rules: handle needsClassName flag and apply specificity\n const rulesToInsert = rules.map((rule) => {\n let newSelector = rule.selector;\n\n // If rule needs className prepended\n if (rule.needsClassName) {\n // Handle multiple selectors (separated by ||| for OR conditions)\n const selectorParts = newSelector ? newSelector.split('|||') : [''];\n\n const classPrefix = `.${className}.${className}`;\n\n newSelector = selectorParts\n .map((part) => {\n const classSelector = part ? `${classPrefix}${part}` : classPrefix;\n\n // If there's a root prefix, add it before the class selector\n if (rule.rootPrefix) {\n return `${rule.rootPrefix} ${classSelector}`;\n }\n return classSelector;\n })\n .join(', ');\n }\n\n return {\n ...rule,\n selector: newSelector,\n needsClassName: undefined, // Remove the flag after processing\n rootPrefix: undefined, // Remove rootPrefix after processing\n };\n });\n\n // The sheet write, plus the `@property` auto-registration that the rules'\n // declarations may trigger. Kept together in one closure so batching moves\n // them as a unit and the sheet ends up in the same order either way.\n const applySheetWrite = (): RuleInfo | null => {\n // Auto-register @property for custom properties with inferable types.\n // Colors are detected by --*-color name pattern, numeric types by value.\n if (this.config.autoPropertyTypes !== false) {\n const resolver = registry.propertyTypeResolver;\n const defined = registry.injectedProperties;\n for (const rule of rulesToInsert) {\n if (!rule.declarations) continue;\n resolver.scanDeclarations(\n rule.declarations,\n (name) => defined.has(name),\n (name, syntax, initialValue) => {\n this.property(name, {\n syntax,\n inherits: true,\n initialValue,\n root,\n });\n },\n );\n }\n }\n\n // Insert rules using existing sheet manager\n const ruleInfo = this.sheetManager.insertRule(\n registry,\n rulesToInsert,\n className,\n root,\n );\n\n if (!ruleInfo) {\n // Update metrics\n if (registry.metrics) {\n registry.metrics.misses++;\n }\n return null;\n }\n\n // Store in registry. Setting the cacheKey mapping is idempotent when the\n // class was pre-allocated, so both paths can share one branch.\n registry.rules.set(className, ruleInfo);\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return ruleInfo;\n };\n\n if (this.batching) {\n // Reserve the class name before returning so a repeat inject() with the\n // same cacheKey — very common, one per sibling component — takes the\n // PENDING short-circuit above instead of queueing the same rules again.\n registry.rules.set(className, {\n className,\n ruleIndex: PENDING_RULE_INDEX,\n sheetIndex: PENDING_RULE_INDEX,\n });\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n if (pin) {\n registry.pinCounts.set(className, 1);\n }\n registry.unusedSince.set(className, Date.now());\n\n const queued = enqueueStyleWrite(() => {\n if (applySheetWrite()) return;\n // Insertion failed. Fall back to the \"allocated but not injected\"\n // state so a later render retries, matching the unbatched path.\n registry.rules.set(className, {\n className,\n ruleIndex: PLACEHOLDER_RULE_INDEX,\n sheetIndex: PLACEHOLDER_RULE_INDEX,\n });\n });\n\n return {\n className,\n dispose: pin\n ? () => {\n // Still queued and this was the only owner: drop the write and the\n // reservation rather than leaving an orphan rule for GC to find.\n if (\n !queued.done &&\n registry.pinCounts.get(className) === 1 &&\n registry.rules.get(className)?.ruleIndex === PENDING_RULE_INDEX\n ) {\n queued.cancelled = true;\n registry.rules.delete(className);\n if (cacheKey) {\n registry.cacheKeyToClassName.delete(cacheKey);\n }\n registry.pinCounts.set(className, 0);\n return;\n }\n this.unpin(className, registry);\n }\n : noop,\n };\n }\n\n if (!applySheetWrite()) {\n return {\n className,\n dispose: () => {\n /* noop */\n },\n };\n }\n\n if (pin) {\n registry.pinCounts.set(className, 1);\n }\n registry.unusedSince.set(className, Date.now());\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n\n /**\n * Inject global styles (rules without a generated tasty class selector)\n * This ensures we don't reserve a tasty class name (t{number}) for global rules,\n * which could otherwise collide with element-level styles and break lookups.\n */\n injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n ): GlobalInjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (!rules || rules.length === 0) {\n return {\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Use a non-tasty identifier to avoid any collisions with .t{number} classes\n const key = `global:${this.globalRuleCounter++}`;\n\n // The `@property` auto-registration inserts rules of its own, so it stays in\n // the same queue slot as the rules that triggered it. Global rules are style\n // rules and do take part in the cascade, so they share the one FIFO with\n // component rules — that is what keeps sheet order identical to unbatched\n // output, and equal-specificity rules resolve by document order.\n const applyWrite = (): RuleInfo | null => {\n // Auto-register @property for custom properties in global rules\n if (this.config.autoPropertyTypes !== false) {\n const resolver = registry.propertyTypeResolver;\n const defined = registry.injectedProperties;\n for (const rule of rules) {\n if (!rule.declarations) continue;\n resolver.scanDeclarations(\n rule.declarations,\n (name) => defined.has(name),\n (name, syntax, initialValue) => {\n this.property(name, {\n syntax,\n inherits: true,\n initialValue,\n root,\n });\n },\n );\n }\n }\n\n const inserted = this.sheetManager.insertGlobalRule(\n registry,\n rules as unknown as StyleRule[],\n key,\n root,\n );\n\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n }\n\n return inserted;\n };\n\n if (this.batching) {\n let info: RuleInfo | null = null;\n const queued = enqueueStyleWrite(() => {\n info = applyWrite();\n });\n\n return {\n dispose: () => {\n // Cancel instead of deleting a rule that never made it into a sheet.\n if (!queued.done) {\n queued.cancelled = true;\n return;\n }\n if (info) this.sheetManager.deleteGlobalRule(registry, key);\n },\n };\n }\n\n const info = applyWrite();\n\n return {\n dispose: () => {\n if (info) this.sheetManager.deleteGlobalRule(registry, key);\n },\n };\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead alternative to createGlobalStyle for raw CSS\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking\n */\n injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n ): RawCSSResult {\n const root = options?.root || document;\n\n if (!this.batching) {\n return this.sheetManager.injectRawCSS(css, root);\n }\n\n // Raw CSS is arbitrary and does take part in the cascade, so it goes through\n // the same FIFO as component and global rules.\n let result: RawCSSResult | null = null;\n const queued = enqueueStyleWrite(() => {\n result = this.sheetManager.injectRawCSS(css, root);\n });\n\n return {\n dispose: () => {\n if (!queued.done) {\n queued.cancelled = true;\n return;\n }\n result?.dispose();\n },\n };\n }\n\n /**\n * Get raw CSS text for SSR\n */\n getRawCSSText(options?: { root?: Document | ShadowRoot }): string {\n flushStyles();\n const root = options?.root || document;\n return this.sheetManager.getRawCSSText(root);\n }\n\n /**\n * Take a reference on local `@keyframes`, under the deterministic names the\n * caller resolved.\n *\n * One reference per distinct set of steps, shared by every class that ends up\n * animating it, so a repeat render takes nothing further. Ownership is\n * assigned by `ownKeyframes()` once the rules exist to be inspected.\n */\n holdKeyframes(\n steps: Record<string, KeyframesSteps>,\n names: Map<string, string>,\n options?: { root?: Document | ShadowRoot },\n ): Map<string, string> {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n // Authored name -> the entry key holding it, so a chunk that runs the\n // animation can be recorded as an owner.\n const keys = new Map<string, string>();\n\n for (const [authored, definition] of Object.entries(steps)) {\n const resolved = names.get(authored) ?? authored;\n let entry = registry.localKeyframes.get(resolved);\n\n if (!entry) {\n // `distinctByName`: the rules rewritten to this name need a rule under\n // it. Two authored animations can share steps — `fade` and `spin` with\n // the same from/to — and would otherwise collapse onto whichever name\n // was injected first, leaving the other animating nothing.\n const injected = this.keyframes(definition, {\n name: resolved,\n root,\n distinctByName: true,\n });\n entry = {\n name: injected.toString(),\n dispose: injected.dispose,\n owners: new Set(),\n };\n registry.localKeyframes.set(resolved, entry);\n }\n\n keys.set(authored, resolved);\n }\n\n return keys;\n }\n\n /**\n * Record that `className` animates these keyframes, so the reference is\n * released when the last such class is collected.\n *\n * Only classes whose rules actually reference the animation should be here:\n * a class that merely rendered alongside one would otherwise keep the\n * keyframes alive for as long as it lives.\n */\n ownKeyframes(\n key: string,\n className: string,\n options?: { root?: Document | ShadowRoot },\n ): void {\n const registry = this.sheetManager.getRegistry(options?.root || document);\n registry.localKeyframes.get(key)?.owners.add(className);\n }\n\n /**\n * Pin an already-injected cacheKey and return the handle that releases it.\n * For callers that skipped the pipeline on a cache hit but still need the\n * class held. Returns null if the cacheKey is not found.\n */\n trackRef(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n ): InjectResult | null {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (!registry.cacheKeyToClassName.has(cacheKey)) return null;\n\n const className = registry.cacheKeyToClassName.get(cacheKey)!;\n const pins = registry.pinCounts.get(className) || 0;\n registry.pinCounts.set(className, pins + 1);\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: () => this.unpin(className, registry),\n };\n }\n\n /**\n * Release one pin on a className. At zero pins the class is not deleted — it\n * stays cached and collectible, and `gc()` decides when it actually goes.\n */\n private unpin(className: string, registry: RootRegistry): void {\n const pins = registry.pinCounts.get(className);\n if (pins == null || pins <= 0) {\n return;\n }\n\n const remaining = pins - 1;\n registry.pinCounts.set(className, remaining);\n\n if (remaining === 0 && registry.metrics) {\n registry.metrics.totalUnused++;\n }\n }\n\n /**\n * Remove every style that is neither in the DOM nor referenced by an\n * outstanding `inject()` handle, ignoring the GC capacity threshold.\n */\n cleanup(root?: Document | ShadowRoot): void {\n this.gc({ root, force: true });\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCSSText(options?: { root?: Document | ShadowRoot }): string {\n flushStyles();\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n return this.sheetManager.getCSSText(registry);\n }\n\n /**\n * Get CSS only for the provided tasty classNames (e.g., [\"t0\",\"t3\"])\n */\n getCSSTextForClasses(\n classNames: Iterable<string>,\n options?: { root?: Document | ShadowRoot },\n ): string {\n flushStyles();\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n const cssChunks: string[] = [];\n for (const cls of classNames) {\n const info = registry.rules.get(cls);\n if (info) {\n // Always prefer reading from the live stylesheet, since indices can change\n const sheet = registry.sheets[info.sheetIndex];\n const styleSheet = sheet ? this.sheetManager.getCSSSheet(sheet) : null;\n if (styleSheet) {\n const start = Math.max(0, info.ruleIndex);\n const end = Math.min(\n styleSheet.cssRules.length - 1,\n (info.endRuleIndex as number) ?? info.ruleIndex,\n );\n // Additional validation: ensure indices are valid and in correct order\n if (\n start >= 0 &&\n end >= start &&\n start < styleSheet.cssRules.length\n ) {\n for (let i = start; i <= end; i++) {\n const rule = styleSheet.cssRules[i] as CSSRule | undefined;\n if (rule) cssChunks.push(rule.cssText);\n }\n }\n } else if (info.cssText && info.cssText.length) {\n // Fallback in environments without CSSOM access\n cssChunks.push(...info.cssText);\n }\n }\n }\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(options?: { root?: Document | ShadowRoot }): CacheMetrics | null {\n // Batched insertions only count themselves once they reach a sheet, so a read\n // taken mid-window would report a torn picture: `hits` already advanced,\n // `totalInsertions` not yet.\n flushStyles();\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const metrics = this.sheetManager.getMetrics(registry);\n\n if (metrics && typeof document !== 'undefined') {\n metrics.unusedHits = this.collectUnused(registry, root).length;\n }\n\n return metrics;\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(options?: { root?: Document | ShadowRoot }): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n this.sheetManager.resetMetrics(registry);\n }\n\n /**\n * Define a CSS @property custom property.\n *\n * Accepts tasty token syntax for the property name:\n * - `$name` → defines `--name`\n * - `#name` → defines `--name-color` (auto-sets syntax: '<color>', defaults initialValue: 'transparent')\n * - `--name` → defines `--name` (legacy format)\n *\n * Example:\n * @property --rotation { syntax: \"<angle>\"; inherits: false; initial-value: 45deg; }\n *\n * Note: No caching or dispose — this defines a global property.\n *\n * If the same property is registered with different options, a warning is emitted\n * but the original definition is preserved (CSS @property cannot be redefined).\n */\n property(\n name: string,\n options?: PropertyDefinition & {\n root?: Document | ShadowRoot;\n },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token and get effective definition\n // This handles $name, #name, --name formats and auto-sets syntax for colors\n const userDefinition: PropertyDefinition = {\n syntax: options?.syntax,\n inherits: options?.inherits,\n initialValue: options?.initialValue,\n };\n\n const effectiveResult = getEffectiveDefinition(name, userDefinition);\n\n if (!effectiveResult.isValid) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] property(): ${effectiveResult.error}. Got: \"${name}\"`,\n );\n }\n return;\n }\n\n const cssName = effectiveResult.cssName;\n const definition = effectiveResult.definition;\n\n this.insertPropertyRule(registry, root, cssName, definition, name);\n }\n\n /**\n * Build and insert a single `@property` rule into the given registry.\n * No-op if the property was already injected.\n */\n private insertPropertyRule(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n cssName: string,\n definition: PropertyDefinition,\n cacheKey: string,\n ): void {\n if (registry.injectedProperties.has(cssName)) {\n return;\n }\n\n const parts: string[] = [];\n\n if (definition.syntax != null) {\n let syntax = String(definition.syntax).trim();\n if (!/^['\"]/u.test(syntax)) syntax = `\"${syntax}\"`;\n parts.push(`syntax: ${syntax};`);\n }\n\n // inherits is required by the CSS @property spec - default to true\n const inherits = definition.inherits ?? true;\n parts.push(`inherits: ${inherits ? 'true' : 'false'};`);\n\n if (definition.initialValue != null) {\n let initialValueStr: string;\n if (typeof definition.initialValue === 'number') {\n initialValueStr = String(definition.initialValue);\n } else {\n // Process via tasty parser to resolve custom units/functions\n initialValueStr = parseStyle(\n definition.initialValue as StyleValue,\n ).output;\n }\n parts.push(`initial-value: ${initialValueStr};`);\n }\n\n const declarations = parts.join(' ').trim();\n\n const rule: StyleRule = {\n selector: `@property ${cssName}`,\n declarations,\n } as StyleRule;\n\n // Mark as attempted BEFORE inserting so repeated calls bail early even\n // when the insertion ultimately fails (e.g., engines like jsdom that\n // don't support @property reject every @property rule unconditionally).\n // Without this, every render's auto-property scan would re-attempt the\n // same rejected rules and flood the console with warnings.\n registry.injectedProperties.set(\n cssName,\n normalizePropertyDefinition(definition),\n );\n\n this.writeGlobalRule(registry, [rule], `property:${cacheKey}`, root);\n }\n\n /**\n * Check whether a given @property name was already injected by this injector.\n *\n * Accepts tasty token syntax:\n * - `$name` → checks `--name`\n * - `#name` → checks `--name-color`\n * - `--name` → checks `--name` (legacy format)\n */\n isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n ): boolean {\n flushStyles();\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token to get the CSS property name\n const effectiveResult = getEffectiveDefinition(name, {});\n if (!effectiveResult.isValid) {\n return false;\n }\n\n return registry.injectedProperties.has(effectiveResult.cssName);\n }\n\n /**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\n fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n const hash = fontFaceContentHash(family, descriptors);\n\n if (registry.injectedFontFaces.has(hash)) {\n return;\n }\n\n const rule: StyleRule = {\n selector: '@font-face',\n declarations: formatFontFaceDeclarations(family, descriptors),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `fontface:${hash}`, root, () => {\n registry.injectedFontFaces.add(hash);\n });\n }\n\n /**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by name.\n * By default a definition overrides a previously injected one of the same\n * name. Pass `weak: true` for global `configure()` definitions, which must\n * never clobber an existing rule (so component-local definitions win\n * regardless of injection order).\n */\n counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const isWeak = options?.weak === true;\n\n const existingIsStrong = registry.injectedCounterStyles.get(name);\n if (existingIsStrong !== undefined) {\n // A weak (global) definition never overrides; a strong one keeps the\n // first definition. Only a strong definition replacing a weak one wins.\n if (isWeak || existingIsStrong === true) {\n return;\n }\n this.writeSheet(() => {\n this.sheetManager.deleteGlobalRule(registry, `counterstyle:${name}`);\n });\n }\n\n const rule: StyleRule = {\n selector: `@counter-style ${name}`,\n declarations: formatCounterStyleDeclarations(descriptors),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `counterstyle:${name}`, root, () => {\n registry.injectedCounterStyles.set(name, !isWeak);\n });\n }\n\n /**\n * Inject a CSS @function rule (custom function).\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by function\n * name. By default a definition overrides a previously injected one of the\n * same name. Pass `weak: true` for global `configure()` definitions, which\n * must never clobber an existing rule (so component-local definitions win\n * regardless of injection order).\n */\n func(\n name: string,\n definition: FunctionDefinition,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const isWeak = options?.weak === true;\n\n const cssName = parseFunctionName(name);\n\n const existingIsStrong = registry.injectedFunctions.get(cssName);\n if (existingIsStrong !== undefined) {\n // A weak (global) definition never overrides; a strong one keeps the\n // first definition. Only a strong definition replacing a weak one wins.\n if (isWeak || existingIsStrong === true) {\n return;\n }\n this.writeSheet(() => {\n this.sheetManager.deleteGlobalRule(registry, `function:${cssName}`);\n });\n }\n\n const rule: StyleRule = {\n selector: formatFunctionPrelude(\n name,\n definition.args,\n definition.returns,\n ),\n declarations: formatFunctionDeclarations(definition),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `function:${cssName}`, root, () => {\n registry.injectedFunctions.set(cssName, !isWeak);\n });\n }\n\n /**\n * Inject keyframes and return object with toString() and dispose()\n *\n * Keyframes are cached by content (steps). If the same content is injected\n * multiple times with different provided names, the first injected name is reused.\n *\n * If the same name is provided with different content (collision), a unique\n * name is generated to avoid overwriting the existing keyframes.\n */\n keyframes(\n steps: KeyframesSteps,\n nameOrOptions?:\n | string\n | {\n root?: Document | ShadowRoot;\n name?: string;\n /**\n * Give this name its own rule even if another name already carries\n * the same steps. Without it two names with identical steps share\n * one rule under whichever name arrived first — fine when the caller\n * only wants the animation, wrong when the name has to be the one it\n * asked for.\n */\n distinctByName?: boolean;\n },\n ): KeyframesResult {\n // Parse parameters\n const isStringName = typeof nameOrOptions === 'string';\n const providedName = isStringName ? nameOrOptions : nameOrOptions?.name;\n const distinctByName = isStringName\n ? false\n : (nameOrOptions?.distinctByName ?? false);\n const root = isStringName ? document : nameOrOptions?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (Object.keys(steps).length === 0) {\n return {\n toString: () => '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Content-based cache key, scoped to the name when the caller needs that\n // exact name to exist.\n const contentHash =\n distinctByName && providedName\n ? `${providedName}\\u0000${JSON.stringify(steps)}`\n : JSON.stringify(steps);\n\n // Check if this exact content is already cached\n const existing = registry.keyframesCache.get(contentHash);\n if (existing) {\n existing.refCount++;\n return {\n toString: () => existing.name,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n // Determine the actual name to use\n let actualName: string;\n\n if (providedName) {\n // Check if this name is already used with different content\n const existingContentForName =\n registry.keyframesNameToContent.get(providedName);\n\n if (existingContentForName && existingContentForName !== contentHash) {\n // Name collision: same name, different content\n // Generate a unique name to avoid overwriting\n actualName = `${providedName}-${makeKeyframeName(\n this.namePrefix,\n String(registry.keyframesCounter++),\n )}`;\n } else {\n // Name is available or used with same content\n actualName = providedName;\n // Track this name -> content mapping\n registry.keyframesNameToContent.set(providedName, contentHash);\n }\n } else {\n // No name provided, generate one\n actualName = makeKeyframeName(\n this.namePrefix,\n String(registry.keyframesCounter++),\n );\n }\n\n // The insertion plus the `@property` scan over the resulting declarations.\n // Returns false when the sheet rejected the rule, so the caller can leave\n // the cache untouched and let a later call retry.\n const applyWrite = (): boolean => {\n const result = this.sheetManager.insertKeyframes(\n registry,\n steps,\n actualName,\n root,\n );\n if (!result) return false;\n\n const { info, declarations } = result;\n\n // Auto-register @property for custom properties found in keyframe declarations\n if (this.config.autoPropertyTypes !== false && declarations) {\n const resolver = registry.propertyTypeResolver;\n resolver.scanDeclarations(\n declarations,\n (name) => registry.injectedProperties.has(name),\n (name, syntax, initialValue) => {\n this.property(name, {\n syntax,\n inherits: true,\n initialValue,\n root,\n });\n },\n );\n }\n\n const entry = registry.keyframesCache.get(contentHash);\n if (entry) {\n // Batched path: the entry was reserved up front, fill in the real info.\n entry.info = info;\n entry.pending = undefined;\n } else {\n registry.keyframesCache.set(contentHash, {\n name: actualName,\n refCount: 1,\n info,\n });\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return true;\n };\n\n if (this.batching) {\n // Reserve the cache entry now so a second keyframes() call with the same\n // content before the flush reuses the name instead of queueing again.\n // `info` is a placeholder until the write lands; `pending` marks that, and\n // disposeKeyframes() cancels rather than deleting a non-existent rule.\n const entry: KeyframesCacheEntry = {\n name: actualName,\n refCount: 1,\n info: EMPTY_KEYFRAMES_INFO,\n };\n registry.keyframesCache.set(contentHash, entry);\n\n entry.pending = enqueueStyleWrite(() => {\n if (applyWrite()) return;\n // Rejected: drop the reservation so a later call can retry, mirroring\n // the unbatched path which never caches a failed insertion.\n if (registry.keyframesCache.get(contentHash) === entry) {\n registry.keyframesCache.delete(contentHash);\n }\n });\n\n return {\n toString: () => actualName,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n if (!applyWrite()) {\n return {\n toString: () => '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n return {\n toString: () => actualName,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n /**\n * Dispose keyframes\n */\n private disposeKeyframes(contentHash: string, registry: RootRegistry): void {\n const entry = registry.keyframesCache.get(contentHash);\n if (!entry) return;\n\n entry.refCount--;\n if (entry.refCount <= 0) {\n // Queued but not yet written: cancel the write instead of deleting a rule\n // that was never inserted.\n if (entry.pending && !entry.pending.done) {\n entry.pending.cancelled = true;\n } else {\n // Dispose immediately - keyframes are global and safe to clean up right away\n this.sheetManager.deleteKeyframes(registry, entry.info);\n }\n registry.keyframesCache.delete(contentHash);\n\n // Clean up name-to-content mapping if this name was tracked\n // Find and remove the mapping for this content hash\n for (const [name, hash] of registry.keyframesNameToContent.entries()) {\n if (hash === contentHash) {\n registry.keyframesNameToContent.delete(name);\n break;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalUnused++;\n registry.metrics.stylesCleanedUp++;\n }\n }\n }\n\n // =========================================================================\n // GC: touch-count-driven garbage collection with DOM safety guard\n // =========================================================================\n\n /**\n * Count a render, and schedule a collection pass every `touchInterval` of\n * them. Nothing else: what a class is worth keeping is decided by the sweep's\n * own DOM scan, so rendering does not track usage at all.\n *\n * @deprecated The class name is ignored — pass anything, or stop calling it.\n * Collection no longer records per-class usage, and scheduling does not need\n * to know which class was rendered. A class handed back by `inject()` is\n * marked wanted there, which is what reuse actually goes through.\n */\n touch(_className: string, options?: { root?: Document | ShadowRoot }): void {\n if (typeof document === 'undefined') return;\n if (!this.config.gc) return;\n\n const registry = this.sheetManager.getRegistry(options?.root || document);\n\n if (++registry.touchCount >= (this.config.gc.touchInterval ?? 1000)) {\n registry.touchCount = 0;\n this.scheduleGC();\n }\n }\n\n /**\n * Schedule a GC in idle time. Runs GC on all active roots, and avoids\n * double-scheduling.\n *\n * Idle only. Without `requestIdleCallback` nothing is collected\n * automatically: running the sweep inline here would put it inside the render\n * that touched the class, and collection is never urgent enough for that.\n */\n private scheduleGC(): void {\n if (this.cancelPendingGC) return;\n\n const runGC = () => {\n this.cancelPendingGC = null;\n this.sheetManager.pruneDisconnectedRoots();\n for (const root of this.sheetManager.getActiveRoots()) {\n this.gc({ root });\n }\n };\n\n if (typeof requestIdleCallback !== 'undefined') {\n const handle = requestIdleCallback(() => runGC());\n this.cancelPendingGC = () => cancelIdleCallback(handle);\n }\n }\n\n /**\n * The one definition of \"unused\": this injector owns the class's rules, no\n * element in `root` carries it, and nobody pinned it.\n *\n * `gc()` evicts from this set, `getMetrics()` counts it, and `tastyDebug`\n * reports it — all through here, so the three can never disagree about what\n * \"unused\" means. Entries carry their last `touch()` so callers can drop the\n * oldest first; a class that was never touched sorts as oldest.\n */\n /**\n * Everything the injector holds falls into one of five bands, and only the\n * last of them is ever deleted:\n *\n * 1. rendered — some element carries the class right now\n * 2. not ours — queued for a batched write, pre-allocated, or server-rendered\n * 3. hot — nothing carries it, but that was noticed less than `grace` ago\n * 4. cached — cold, but within `capacity` when ordered by when it went cold\n * 5. the rest\n *\n * This returns bands 4 and 5 together, most recently cold first; `gc()` draws\n * the capacity line through them. Band 3 is what makes collection safe\n * without a commit signal: a render can resolve a class and commit it a\n * little later, and during that gap nothing on the page carries it.\n */\n private collectUnused(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n ): string[] {\n const now = Date.now();\n const grace = this.config.gc?.grace ?? DEFAULT_GC_GRACE;\n\n // Scan the DOM for live classes (classList handles SVG elements too)\n const liveClasses = new Set<string>();\n for (const el of root.querySelectorAll('[class]')) {\n for (const token of el.classList) {\n if (this.classRegex.test(token)) liveClasses.add(token);\n }\n }\n\n const unused: string[] = [];\n\n for (const [className, ruleInfo] of registry.rules) {\n // Band 2: a negative sheet index marks a rule this injector does not own\n // — server rendered (hydrated), pre-allocated, or still queued.\n if (ruleInfo.sheetIndex < 0) continue;\n\n // Band 1.\n if (liveClasses.has(className)) {\n registry.unusedSince.delete(className);\n continue;\n }\n\n // Someone still holds the dispose handle `inject()` returned.\n if ((registry.pinCounts.get(className) ?? 0) > 0) continue;\n\n // Band 3. The clock starts at the sighting, not at whatever moment the\n // element actually left — nothing was watching for that — so every class\n // gets the same full window however long ago it went.\n let since = registry.unusedSince.get(className);\n if (since === undefined) {\n since = now;\n registry.unusedSince.set(className, now);\n }\n if (now - since < grace) continue;\n\n unused.push(className);\n }\n\n // Most recently cold first, so `gc()` can keep that many and drop the tail.\n unused.sort(\n (a, b) =>\n (registry.unusedSince.get(b) ?? 0) - (registry.unusedSince.get(a) ?? 0),\n );\n\n return unused;\n }\n\n /**\n * Class names this injector holds CSS for that nothing renders and nobody\n * pinned — exactly what `gc({ force: true })` would delete. Unordered.\n */\n getUnusedClasses(options?: { root?: Document | ShadowRoot }): string[] {\n flushStyles();\n if (typeof document === 'undefined') return [];\n\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n return this.collectUnused(registry, root);\n }\n\n /**\n * Synchronous garbage collection.\n *\n * 1. Quick upper-bound check: skip if the registry is smaller than capacity.\n * 2. Scans the DOM for live tasty classNames — the DOM, not a ref count, is\n * what says a class rendered by a component is still in use.\n * 3. With `force: true`: deletes every unused class.\n * Without `force`: keeps the `capacity` most recently touched and deletes\n * the rest, oldest first.\n *\n * @returns Number of styles evicted.\n */\n gc(options?: GCOptions): number {\n // Pending writes still carry PENDING sentinels in `registry.rules`; sweeping\n // those would corrupt sheet indices, so land every write first.\n flushStyles();\n if (typeof document === 'undefined') return 0;\n\n // Cancel any pending scheduled GC to prevent double runs\n this.cancelPendingGC?.();\n this.cancelPendingGC = null;\n\n const root = options?.root || document;\n const force = options?.force;\n const registry = this.sheetManager.getRegistry(root);\n const capacity = this.config.gc?.capacity ?? 1000;\n\n // Quick upper-bound check: not even every class being unused would exceed\n // capacity, so skip the DOM scan.\n if (!force && registry.rules.size <= capacity) return 0;\n\n const unused = this.collectUnused(registry, root);\n\n let doomed: string[];\n\n if (force) {\n // Bands 4 and 5. Band 3 is spared even here: an explicit cleanup is still\n // no reason to take rules from a render that has not committed yet.\n doomed = unused;\n } else if (unused.length > capacity) {\n // Band 4 is the `capacity` classes that went cold most recently; band 5\n // is everything behind them, and only band 5 goes.\n doomed = unused.slice(capacity);\n } else {\n return 0;\n }\n\n if (doomed.length === 0) return 0;\n\n return this.sheetManager.deleteClasses(registry, doomed);\n }\n\n /**\n * Destroy all resources for a root\n */\n destroy(root?: Document | ShadowRoot): void {\n flushStyles();\n const targetRoot = root || document;\n this.sheetManager.cleanup(targetRoot);\n\n // Clear pending GC when no active roots remain\n if (this.cancelPendingGC && !this.sheetManager.hasActiveRoots()) {\n this.cancelPendingGC();\n this.cancelPendingGC = null;\n }\n }\n}\n","import type { ConfigTokens } from '../styles/types';\n\nconst RESERVED_PRESET_NAMES = new Set([\n 'strong',\n 'bold',\n 'italic',\n 'icon',\n 'tight',\n]);\n\n/**\n * A typography token value: plain value or a state map for responsive/theme-aware presets.\n *\n * @example\n * // Plain value\n * fontWeight: '400'\n * // State map\n * fontWeight: { '': '400', '@dark': '300' }\n */\nexport type TypographyTokenValue =\n | string\n | number\n | Record<string, string | number | undefined | null | '@inherit'>;\n\n/**\n * Typography preset configuration.\n * Each preset defines font properties that get expanded into CSS custom properties.\n * All fields accept plain values or state maps for responsive/theme-aware tokens.\n *\n * Use with `generateTypographyTokens()` to create typography tokens for your design system.\n */\nexport interface TypographyPreset {\n fontSize: TypographyTokenValue;\n lineHeight: TypographyTokenValue;\n letterSpacing?: TypographyTokenValue;\n fontWeight: TypographyTokenValue;\n boldFontWeight?: TypographyTokenValue;\n iconSize?: TypographyTokenValue;\n textTransform?: TypographyTokenValue;\n fontFamily?: TypographyTokenValue;\n fontStyle?: TypographyTokenValue;\n}\n\n/**\n * Generate typography tokens with $ prefix for CSS custom properties.\n *\n * Each preset generates the following CSS custom properties:\n * - `${name}-font-size`\n * - `${name}-line-height`\n * - `${name}-letter-spacing`\n * - `${name}-font-weight`\n * - `${name}-bold-font-weight` (if defined)\n * - `${name}-icon-size` (if defined)\n * - `${name}-text-transform` (if defined)\n * - `${name}-font-family` (if defined)\n * - `${name}-font-style` (if defined)\n *\n * @param presets - Typography presets object\n * @returns ConfigTokens object with $ prefixed keys\n *\n * @example\n * const customTokens = generateTypographyTokens({\n * myHeading: { fontSize: '24px', lineHeight: '32px', fontWeight: '700' },\n * body: { fontSize: '16px', lineHeight: '24px', fontWeight: '400' },\n * });\n */\nexport function generateTypographyTokens(\n presets: Record<string, TypographyPreset>,\n): ConfigTokens {\n const tokens: ConfigTokens = {} as ConfigTokens;\n\n for (const [name, preset] of Object.entries(presets)) {\n if (RESERVED_PRESET_NAMES.has(name)) {\n throw new Error(\n `Invalid typography preset name \"${name}\". This name is reserved as a preset modifier.`,\n );\n }\n\n tokens[`$${name}-font-size`] = preset.fontSize;\n tokens[`$${name}-line-height`] = preset.lineHeight;\n tokens[`$${name}-letter-spacing`] = preset.letterSpacing ?? 'normal';\n tokens[`$${name}-font-weight`] = preset.fontWeight;\n\n if (preset.boldFontWeight !== undefined) {\n tokens[`$${name}-bold-font-weight`] = preset.boldFontWeight;\n }\n\n if (preset.iconSize !== undefined) {\n tokens[`$${name}-icon-size`] = preset.iconSize;\n }\n\n if (preset.textTransform !== undefined) {\n tokens[`$${name}-text-transform`] = preset.textTransform;\n }\n\n if (preset.fontFamily !== undefined) {\n tokens[`$${name}-font-family`] = preset.fontFamily;\n }\n\n if (preset.fontStyle !== undefined) {\n tokens[`$${name}-font-style`] = preset.fontStyle;\n }\n }\n\n return tokens;\n}\n","/**\n * Tasty Configuration Module\n *\n * Centralizes all tasty configuration, including:\n * - Style injector settings (nonce, cleanup thresholds, etc.)\n * - Global predefined states for advanced state mapping\n * - stylesGenerated flag that locks configuration after first style generation\n *\n * Configuration must be done BEFORE any styles are generated.\n * After the first `inject()` call, configuration is locked and attempts to\n * reconfigure will emit a warning and be ignored.\n */\n\nimport {\n registerFunctionPolyfill,\n resetFunctionPolyfills,\n splitFunctions,\n} from './functions';\nimport {\n hasStylesGenerated,\n markStylesGeneratedState,\n resetStylesGeneratedState,\n} from './config-state';\nimport { resetStyleChunks } from './chunks/style-chunk-map';\nimport type { PropHandlerDefinition } from './prop-handlers';\nimport { registerPropHandler, resetPropHandlers } from './prop-handlers';\nimport { StyleInjector } from './injector/injector';\nimport { clearPipelineCache, renderStyles } from './pipeline';\nimport { setGlobalPredefinedStates } from './states';\nimport {\n normalizeHandlerDefinition,\n registerHandler,\n resetHandlers,\n} from './styles/predefined';\nimport {\n registerBaseStyleProps,\n resetBaseStyleProps,\n} from './styles/base-props';\nimport { isDevEnv } from './utils/is-dev-env';\nimport { isSelector } from './utils/is-selector';\nimport { DEFAULT_NAME_PREFIX, validateNamePrefix } from './utils/name-prefix';\nimport { resetStyleWarnings } from './utils/warnings';\nimport {\n CUSTOM_UNITS,\n getGlobalParseFunctions,\n getGlobalParser,\n normalizeColorTokenValue,\n resetGlobalParseFunctions,\n resetGlobalPredefinedTokens,\n setGlobalPredefinedTokens,\n} from './utils/styles';\n\nimport type { FunctionsConfig, ParseFunction } from './functions';\nimport type { ColorSpace } from './utils/color-space';\n\nimport type {\n CounterStyleDescriptors,\n FontFaceInput,\n FunctionDefinition,\n GCConfig,\n KeyframesSteps,\n PropertyDefinition,\n} from './injector/types';\nimport type { UnitHandler } from './parser/types';\nimport type { StyleResult } from './pipeline';\nimport type { TastyPlugin } from './plugins/types';\nimport type { RecipeStyles, ConfigTokens } from './styles/types';\nimport type { Styles } from './styles/types';\nimport type { StyleHandlerDefinition } from './utils/styles';\nimport type { TypographyPreset } from './utils/typography';\nimport { generateTypographyTokens } from './utils/typography';\n\n/**\n * Configuration options for the Tasty style system\n */\nexport interface TastyConfig {\n /** CSP nonce for style elements */\n nonce?: string;\n /** Maximum rules per stylesheet (default: 8192) */\n maxRulesPerSheet?: number;\n /** Force text injection mode, auto-detected in test environments (default: auto) */\n forceTextInjection?: boolean;\n /** Enable development mode features: performance metrics and debug info (default: auto) */\n devMode?: boolean;\n /**\n * Global predefined states for advanced state mapping.\n * These are state aliases that can be used in any component.\n * Example: { '@mobile': '@media(w < 920px)', '@dark': '@root(theme=dark)' }\n */\n states?: Record<string, string>;\n /**\n * Parser LRU cache size (default: 1000).\n * Larger values improve performance for apps with many unique style values.\n */\n parserCacheSize?: number;\n /**\n * Custom units for the style parser (merged with built-in units).\n * Units transform numeric values like `2x` → `calc(2 * var(--gap))`.\n * @example { em: 'em', vw: 'vw', custom: (n) => `${n * 10}px` }\n */\n units?: Record<string, string | UnitHandler>;\n /**\n * Custom functions (merged with existing). A single map holds both flavors,\n * discriminated by value type:\n *\n * - **Bare key + function value** — a parse-time function that processes the\n * parsed argument groups and returns a CSS value. Called as `name(...)`.\n * - **`$$name` key + object value** — a declarative CSS `@function`\n * definition. Called as `$$name(...)` (→ native `--name(...)`).\n *\n * A key whose prefix does not match its value type (object under a bare key,\n * or function under a `$$` key) is ignored with a dev warning.\n *\n * @example\n * ```ts\n * configure({\n * functions: {\n * double: (groups) => `calc(2 * ${groups[0].output})`, // parse function\n * $$negative: { args: ['$value'], result: '(-1 * $value)' }, // CSS function\n * },\n * });\n * ```\n */\n functions?: FunctionsConfig;\n /**\n * @deprecated No longer has any effect; will be removed in the next major.\n * Setting it warns in development.\n *\n * A `#name` token's value used to be rewritten into this color space so an\n * opacity suffix had numeric channels to write an alpha into. Opacity now uses\n * relative color syntax — `oklch(from var(--name-color) l c h / .5)` — which\n * has the browser read the channels, so a color is emitted exactly as\n * authored and there is nothing left for the setting to decide.\n *\n * To address a token's channels yourself, write relative color syntax against\n * the token: `oklch(from var(--brand-color) calc(l * 1.2) c h)`. It works on\n * every `<color>`, including the ones no conversion could evaluate.\n */\n colorSpace?: ColorSpace;\n /**\n * Automatically infer and register CSS @property declarations\n * from custom property values found in styles, keyframes, and global config.\n * Covers all types: \\<color\\>, \\<number\\>, \\<length\\>, \\<angle\\>, \\<percentage\\>, \\<time\\>.\n * When false, only explicitly declared @property are registered.\n * @default true\n */\n autoPropertyTypes?: boolean;\n /**\n * Defer stylesheet writes and apply them in one batch instead of performing\n * one `insertRule()` per component during render.\n *\n * Each `insertRule()` on a live sheet invalidates style for that sheet's\n * scope. When components inject during React's render phase while other\n * components read layout in the same pass, the two interleave and the browser\n * is forced to recalculate style between every injection. Batching collapses\n * that into one invalidation per flush.\n *\n * - `false` (default) — inject synchronously, one write per component.\n * - `true` — batch, but only inside a *batch window*: a commit in which\n * `<TastyBatchProvider>` rendered and will therefore flush in its\n * `useInsertionEffect`, before any `useLayoutEffect` runs. Any injection\n * outside a window — a deep update the provider did not re-render for, an\n * injection from a layout effect, an event handler, an async callback — is\n * written straight through. Enabling this can never make a layout effect\n * measure an unstyled element. Requires `<TastyBatchProvider>`; without it\n * nothing is batched (and dev mode says so once).\n * - `'always'` — batch every injection, flushing on a microtask when no\n * window is open. Wins on more commits, but a `useLayoutEffect` that\n * measures a freshly mounted element can read its unstyled box, because\n * microtasks run after the layout phase. Paint is unaffected: microtasks\n * always drain before the browser paints.\n *\n * No effect during SSR or RSC: styles are collected as text there, the\n * runtime injector never runs, and the provider is inert without a\n * `document`. No effect on zero-runtime `tastyStatic` styles either — those\n * are extracted at build time and never reach the injector.\n *\n * @default false\n * @example\n * ```tsx\n * configure({ batchInjection: true });\n *\n * <TastyBatchProvider>\n * <App />\n * </TastyBatchProvider>\n * ```\n */\n batchInjection?: boolean | 'always';\n /**\n * Garbage collection configuration for unused styles.\n * GC is triggered by touch count: every `touchInterval` touches, the\n * oldest unused styles are evicted when their count exceeds `capacity`.\n * @example\n * ```ts\n * configure({\n * gc: { touchInterval: 1000, capacity: 1000 },\n * });\n * ```\n */\n gc?: GCConfig;\n /**\n * Prefix prepended to every generated identifier (class names,\n * keyframe names, counter-style names). The hash is appended verbatim,\n * so include any separator inside the prefix itself (e.g. `'myapp-'`).\n *\n * Discriminator letters are inserted between the prefix and the hash\n * for non-class names so the three kinds stay visually distinct:\n * - class: `${namePrefix}${hash}` — e.g. `t1a2b3`\n * - keyframe: `${namePrefix}k${hash}` — e.g. `tk1a2b3`\n * - counter-style: `${namePrefix}c${hash}` — e.g. `tc1a2b3`\n *\n * The runtime, SSR, and RSC paths must agree on this value or\n * hydration will mismatch. The zero-runtime build path defaults to\n * `'ts'` (overridable via the same option) so its classes can't\n * collide with runtime classes when both are loaded on the same page.\n *\n * Must match `^[a-zA-Z_][a-zA-Z0-9_-]{0,31}$`. Locked once styles\n * have been generated.\n *\n * @default 't'\n */\n namePrefix?: string;\n /**\n * Plugins that extend tasty with custom functions, units, or states.\n * Plugins are processed in order, with later plugins overriding earlier ones.\n * @example\n * ```ts\n * import { okhslPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhslPlugin()],\n * });\n * ```\n */\n plugins?: TastyPlugin[];\n /**\n * Global keyframes definitions that can be referenced by animation names in styles.\n * Keys are animation names, values are keyframes step definitions.\n * Keyframes are only injected when actually used in styles.\n * @example\n * ```ts\n * configure({\n * keyframes: {\n * fadeIn: { from: { opacity: 0 }, to: { opacity: 1 } },\n * pulse: { '0%, 100%': { transform: 'scale(1)' }, '50%': { transform: 'scale(1.05)' } },\n * },\n * });\n * ```\n */\n keyframes?: Record<string, KeyframesSteps>;\n /**\n * Global CSS @property definitions for custom properties.\n * Keys use tasty token syntax ($name for properties, #name for colors).\n *\n * Tasty ships with `DEFAULT_PROPERTIES` (e.g. `$gap`, `$radius`, `#white`,\n * `#black`, `#clear`, `#border`, etc.) that are always included.\n * Properties you specify here are merged on top, so you can override any\n * default by using the same key.\n *\n * For color tokens (#name), `syntax: '<color>'` is auto-set and\n * `initialValue` defaults to `'transparent'` if not specified.\n *\n * @example\n * ```ts\n * configure({\n * properties: {\n * '$rotation': { syntax: '<angle>', initialValue: '0deg' },\n * '$scale': { syntax: '<number>', inherits: false, initialValue: 1 },\n * '#accent': { initialValue: 'purple' }, // syntax: '<color>' auto-set\n * // Override a default property:\n * '$gap': { syntax: '<length>', inherits: true, initialValue: '8px' },\n * },\n * });\n *\n * // Now use in styles - properties are registered when component renders:\n * const Spinner = tasty({\n * styles: {\n * transform: 'rotate($rotation)',\n * transition: '$$rotation 0.3s', // outputs: --rotation 0.3s\n * },\n * });\n * ```\n */\n properties?: Record<string, PropertyDefinition>;\n /**\n * Global @font-face definitions.\n * Keys are font-family names, values are descriptors or arrays of descriptors\n * (for multiple weights/styles of the same family).\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * fontFaces: {\n * 'Brand Sans': [\n * { src: 'url(\"/fonts/brand-regular.woff2\") format(\"woff2\")', fontWeight: 400, fontDisplay: 'swap' },\n * { src: 'url(\"/fonts/brand-bold.woff2\") format(\"woff2\")', fontWeight: 700, fontDisplay: 'swap' },\n * ],\n * Icons: { src: 'url(\"/fonts/icons.woff2\") format(\"woff2\")', fontDisplay: 'block' },\n * },\n * });\n * ```\n */\n fontFaces?: Record<string, FontFaceInput>;\n /**\n * Global @counter-style definitions.\n * Keys are counter-style names, values are descriptor objects.\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * counterStyles: {\n * thumbs: { system: 'cyclic', symbols: '\"👍\"', suffix: '\" \"' },\n * },\n * });\n * ```\n */\n counterStyles?: Record<string, CounterStyleDescriptors>;\n /**\n * Opt-in polyfills for not-yet-baseline CSS features. Each key toggles a\n * feature polyfill; all default to `false`.\n *\n * - `functions` — polyfill CSS `@function` by inlining every `$$name(...)`\n * call into plain CSS (calc/var/color-mix) at parse time instead of\n * emitting the native `@function` at-rule. Enables `@function` usage in\n * browsers that don't support it yet (Firefox/Safari). Note this is the\n * `functions` *feature toggle*, distinct from the top-level `functions`\n * definitions map.\n *\n * @example\n * ```ts\n * configure({ polyfills: { functions: true } });\n * ```\n */\n polyfills?: { functions?: boolean };\n /**\n * Custom style handlers that transform style properties into CSS declarations.\n * Handlers replace built-in handlers for the same style name.\n * @example\n * ```ts\n * import { styleHandlers } from '@tenphi/tasty';\n *\n * configure({\n * handlers: {\n * // Override fill with custom behavior\n * fill: ({ fill }) => {\n * if (fill?.startsWith('gradient:')) {\n * return { background: fill.slice(9) };\n * }\n * return styleHandlers.fill({ fill });\n * },\n * // Add new custom style\n * elevation: ({ elevation }) => {\n * const level = parseInt(elevation) || 1;\n * return {\n * 'box-shadow': `0 ${level * 2}px ${level * 4}px rgba(0,0,0,0.1)`,\n * 'z-index': String(level * 100),\n * };\n * },\n * },\n * });\n * ```\n */\n handlers?: Record<string, StyleHandlerDefinition>;\n /**\n * Props middleware for every tasty component. A prop handler receives the\n * component's props and returns them, changed or not — the extension point for\n * props that are not style properties.\n *\n * The map key is the handler's name and, by default, the prop that triggers it.\n * Use `['*', fn]` for an unconditional handler, or `[['a', 'b'], fn]` to trigger\n * on any of several props.\n *\n * Handlers must be pure and must not mutate their input: style values are cached\n * by object identity, so mutating one in place yields stale CSS. Memoize the\n * styles you build per input value.\n *\n * Not applicable to zero-runtime mode — `tastyStatic()` takes styles objects, not\n * props, so there is nothing for middleware to run on. Components rendered\n * through `tasty()` are unaffected and keep the runtime injector.\n *\n * @example\n * ```ts\n * configure({\n * propHandlers: {\n * glaze: (props) => {\n * const { glaze, ...rest } = props;\n * if (!glaze) return rest;\n * return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };\n * },\n * },\n * });\n *\n * <Element glaze=\"purple\" />\n * ```\n */\n propHandlers?: Record<string, PropHandlerDefinition>;\n /**\n * Style properties exposed as top-level props on **every** tasty component, in\n * addition to the built-in base styles, without each component listing them in\n * `styleProps`.\n *\n * Augment `TastyBaseStylePropNames` to type them. Each name costs one property\n * check per render of every component, so keep the list short; the effect is\n * app-global and cannot be scoped to a subtree.\n *\n * @example\n * ```ts\n * configure({ baseStyleProps: ['radius', 'shadow'] });\n *\n * <Card radius=\"1r\" shadow />\n * ```\n */\n baseStyleProps?: readonly string[];\n /**\n * Design tokens injected as CSS custom properties on `:root`.\n * Values are parsed through the Tasty DSL. Supports state maps\n * for responsive/theme-aware tokens.\n *\n * - `$name` keys become `--name` CSS custom properties\n * - `#name` keys become `--name-color` properties\n *\n * Tokens are injected once when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * tokens: {\n * '$gap': '4px',\n * '#primary': {\n * '': '#purple',\n * '@dark': '#light-purple',\n * },\n * },\n * });\n * ```\n */\n tokens?: ConfigTokens;\n /**\n * Predefined tokens that are replaced during style parsing (parse-time substitution).\n * Use `$name` for custom properties and `#name` for color tokens.\n * Values are substituted inline before CSS generation, unlike `tokens` which\n * inject CSS custom properties on `:root`.\n *\n * For color tokens (#name), boolean `true` is converted to `transparent`.\n *\n * @example\n * ```ts\n * configure({\n * replaceTokens: {\n * $spacing: '2x',\n * '#accent': '#purple',\n * '#overlay': true, // → transparent\n * },\n * });\n *\n * // Now use in styles - tokens are replaced at parse time:\n * const Card = tasty({\n * styles: {\n * padding: '$spacing', // → calc(2 * var(--gap))\n * fill: '#accent', // → var(--purple-color)\n * },\n * });\n * ```\n */\n replaceTokens?: Record<`$${string}`, string | number | boolean> &\n Record<`#${string}`, string | number | boolean>;\n /**\n * Predefined style recipes -- named style bundles that can be applied via `recipe` style property.\n * Recipe values are flat tasty styles (no sub-element keys). They may contain base styles,\n * tokens (`$name`/`#name` definitions), local states, `@keyframes`, and `@property`.\n *\n * Components reference recipes via: `recipe: 'name1 name2'` in their styles.\n * Use `/` to separate base recipes from post recipes: `recipe: 'base1 base2 / post1'`.\n * Use `none` to skip base recipes: `recipe: 'none / post1'`.\n * Resolution order: `base_recipes → component styles → post_recipes`.\n *\n * Recipes cannot reference other recipes.\n *\n * @example\n * ```ts\n * configure({\n * recipes: {\n * card: { padding: '4x', fill: '#surface', radius: '1r', border: true },\n * elevated: { shadow: '2x 2x 4x #shadow' },\n * },\n * });\n *\n * // Usage in styles:\n * const Card = tasty({\n * styles: {\n * recipe: 'card elevated',\n * color: '#text', // Overrides recipe values\n * },\n * });\n * ```\n */\n recipes?: Record<string, RecipeStyles>;\n /**\n * Typography presets — shorthand for `generateTypographyTokens()`.\n * Accepts the same input and internally generates typography tokens\n * that are merged into `tokens`. Explicit `tokens` override preset-generated ones.\n *\n * @example\n * ```ts\n * configure({\n * presets: {\n * h1: { fontSize: '32px', lineHeight: '1.2', fontWeight: '700' },\n * t2: { fontSize: '16px', lineHeight: '1.5', fontWeight: '400' },\n * },\n * tokens: {\n * // Overrides the preset-generated $t2-font-weight\n * '$t2-font-weight': { '': '400', '@dark': '300' },\n * },\n * });\n * ```\n */\n presets?: Record<string, TypographyPreset>;\n /**\n * Global Tasty styles keyed by CSS selector.\n * Each entry applies the full Tasty style syntax (style properties,\n * tokens, state maps, selector-based sub-styling) to the given selector.\n * Injected alongside `:root` tokens when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * globalStyles: {\n * body: { fill: '#surface', color: '#text', preset: 't2', margin: 0 },\n * html: { overflow: 'hidden' },\n * },\n * });\n * ```\n */\n globalStyles?: Record<string, Styles>;\n}\n\n// Warnings tracking to avoid duplicates\nconst emittedWarnings = new Set<string>();\n\nconst devMode = isDevEnv();\n\n/**\n * Emit a warning only once\n */\nfunction warnOnce(key: string, message: string): void {\n if (devMode && !emittedWarnings.has(key)) {\n emittedWarnings.add(key);\n console.warn(message);\n }\n}\n\n// ============================================================================\n// Configuration State\n// ============================================================================\n\n// Current configuration (null until first configure() or auto-configured on first use)\nlet currentConfig: TastyConfig | null = null;\n\n// Global keyframes storage (null = no keyframes configured, empty object checked via hasGlobalKeyframes)\nlet globalKeyframes: Record<string, KeyframesSteps> | null = null;\n\n// Global font-face storage (null = no font faces configured)\nlet globalFontFace: Record<string, FontFaceInput> | null = null;\n\n// Global counter-style storage (null = no counter styles configured)\nlet globalCounterStyle: Record<string, CounterStyleDescriptors> | null = null;\n\n// Global @function storage (null = no functions configured)\nlet globalFunction: Record<string, FunctionDefinition> | null = null;\n\n// Global polyfill toggles (null = no polyfills configured)\nlet globalPolyfills: { functions?: boolean } | null = null;\n\n// Global properties storage (null = no properties configured)\nlet globalProperties: Record<string, PropertyDefinition> | null = null;\n\n// Global recipes storage (null = no recipes configured)\nlet globalRecipes: Record<string, RecipeStyles> | null = null;\n\n// Global token styles storage (injected as :root CSS custom properties)\nlet globalConfigTokens: ConfigTokens | null = null;\n\n// Global styles storage (injected as CSS for configured selectors)\nlet globalStyles: Record<string, Styles> | null = null;\n\n// ============================================================================\n// Cross-module config sharing via globalThis\n//\n// Frameworks like Astro may load middleware and page components from\n// separate module graphs, creating duplicate module-level state.\n// Config values read by SSR collector's collectInternals() are mirrored\n// to globalThis so they're accessible regardless of which module instance\n// the collector was loaded from.\n// ============================================================================\n\nconst GTKEY_TOKENS = '__tasty_cfg_tokens__';\nconst GTKEY_FONT_FACE = '__tasty_cfg_font_face__';\nconst GTKEY_COUNTER_STYLE = '__tasty_cfg_counter_style__';\nconst GTKEY_FUNCTION = '__tasty_cfg_function__';\nconst GTKEY_POLYFILLS = '__tasty_cfg_polyfills__';\nconst GTKEY_PROPERTIES = '__tasty_cfg_properties__';\nconst GTKEY_GLOBAL_STYLES = '__tasty_cfg_global_styles__';\n\nfunction setOnGlobalThis(key: string, value: unknown): void {\n (globalThis as Record<string, unknown>)[key] = value;\n}\n\nfunction getFromGlobalThis<T>(key: string): T | undefined {\n return (globalThis as Record<string, unknown>)[key] as T | undefined;\n}\n\nfunction clearGlobalThisConfig(): void {\n const g = globalThis as Record<string, unknown>;\n delete g[GTKEY_TOKENS];\n delete g[GTKEY_FONT_FACE];\n delete g[GTKEY_COUNTER_STYLE];\n delete g[GTKEY_FUNCTION];\n delete g[GTKEY_POLYFILLS];\n delete g[GTKEY_PROPERTIES];\n delete g[GTKEY_GLOBAL_STYLES];\n}\n\n/**\n * Default properties shipped with tasty.\n * These are always included unless explicitly overridden via `configure({ properties })`.\n * Keys use tasty token syntax (#name for colors, $name for other properties).\n *\n * For properties with CSS @property-compatible types (length, time, number, color),\n * an `initialValue` is provided so the property works even without a project-level token.\n */\nconst DEFAULT_PROPERTIES: Record<string, PropertyDefinition> = {\n // Used by dual-fill feature to enable CSS transitions on the second fill color\n '#tasty-second-fill': {\n inherits: false,\n initialValue: 'transparent',\n },\n // The inherited color, published by the `color` handler for anything that\n // wants it as a color rather than as the `currentcolor` keyword. (`#current`\n // itself compiles to the keyword.) `initial-value: currentcolor` makes it a\n // true stand-in where nothing published it: a registered `<color>` property\n // keeps the keyword as its computed value and resolves it against each\n // element's own color. `transparent` here would render a reader invisible.\n '#current': {\n inherits: true,\n initialValue: 'currentcolor',\n },\n // White and black are fundamental colors that need explicit initial values.\n '#white': {\n inherits: true,\n initialValue: 'rgb(255 255 255)',\n },\n '#black': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n // Shorthand for transparent\n '#clear': {\n inherits: true,\n initialValue: 'transparent',\n },\n // Default border color\n '#border': {\n inherits: true,\n initialValue: 'rgb(0 0 0)',\n },\n\n // ---- Core design tokens used by style handlers ----\n // These provide sensible defaults so tasty works standalone without a design system.\n // Consuming projects (e.g. uikit) override these by defining tokens on :root.\n\n $gap: {\n syntax: '<length>',\n inherits: true,\n initialValue: '4px',\n },\n $radius: {\n syntax: '<length>',\n inherits: true,\n initialValue: '6px',\n },\n '$border-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '1px',\n },\n '$outline-width': {\n syntax: '<length>',\n inherits: true,\n initialValue: '3px',\n },\n $transition: {\n syntax: '<time>',\n inherits: true,\n initialValue: '80ms',\n },\n // Used by radius.ts for `radius=\"leaf\"` modifier\n '$sharp-radius': {\n syntax: '<length>',\n inherits: true,\n initialValue: '0px',\n },\n // Used by preset.ts for `preset=\"name / strong\"`\n '$bold-font-weight': {\n syntax: '<number>',\n inherits: true,\n initialValue: '700',\n },\n // Used by preset.ts as fallback font stacks\n '$font-sans-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'system-ui, -apple-system, \"Segoe UI\", Roboto, Helvetica, Arial, \"Apple Color Emoji\", \"Segoe UI Emoji\", sans-serif',\n },\n '$font-mono-fallback': {\n syntax: '*',\n inherits: true,\n initialValue:\n 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace',\n },\n};\n\n// Global injector instance key\nconst GLOBAL_INJECTOR_KEY = '__TASTY_GLOBAL_INJECTOR__';\n\ninterface TastyGlobalStorage {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n}\n\ndeclare global {\n interface Window {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n }\n\n var __TASTY_GLOBAL_INJECTOR__: StyleInjector | undefined;\n}\n\n/**\n * Detect if we're running in a test environment\n */\nexport function isTestEnvironment(): boolean {\n // Check Node.js environment\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n return true;\n }\n\n // Check for test runner globals (safely)\n if (typeof global !== 'undefined') {\n const g = global as unknown as Record<string, unknown>;\n if (g.vi || g.jest || g.expect || g.describe || g.it) {\n return true;\n }\n }\n\n // Check for simulated DOM environments (common in tests)\n if (typeof window !== 'undefined') {\n const ua = window.navigator?.userAgent;\n if (ua?.includes('jsdom') || ua?.includes('HappyDOM')) {\n return true;\n }\n }\n\n // Check for other test runners\n if (typeof globalThis !== 'undefined') {\n const gt = globalThis as unknown as Record<string, unknown>;\n if (gt.vitest || gt.mocha) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Create default configuration with optional test environment detection\n */\nfunction createDefaultConfig(isTest?: boolean): TastyConfig {\n return {\n maxRulesPerSheet: 8192,\n forceTextInjection: isTest ?? false,\n devMode: isDevEnv(),\n namePrefix: DEFAULT_NAME_PREFIX,\n };\n}\n\n// ============================================================================\n// stylesGenerated Flag Management\n// ============================================================================\n\n/**\n * Mark that styles have been generated (called by injector on first inject)\n * This locks the configuration - no further changes allowed.\n * Also injects internal and global properties.\n */\nexport function markStylesGenerated(): void {\n if (!markStylesGeneratedState()) return;\n\n // When SSR styles are already in the document, the SSR collector's\n // collectInternals() already rendered tokens, @property, globalStyles,\n // @font-face, @counter-style, and @function. Skip client-side injection to\n // avoid duplicate CSS rules.\n if (\n typeof document !== 'undefined' &&\n document.querySelector('[data-tasty-ssr]')\n ) {\n warnOnce(\n 'ssr-globals-skip',\n '[Tasty] SSR styles detected — skipping client-side global CSS injection to avoid duplicates.',\n );\n return;\n }\n\n const injector = getGlobalInjector();\n\n // Inject all properties (defaults merged with user-configured overrides)\n for (const [token, definition] of Object.entries(getEffectiveProperties())) {\n injector.property(token, definition);\n }\n\n // Inject global @font-face rules (eagerly — fonts should be available before render)\n if (globalFontFace && Object.keys(globalFontFace).length > 0) {\n for (const [family, input] of Object.entries(globalFontFace)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n injector.fontFace(family, desc);\n }\n }\n }\n\n // Inject global @counter-style rules (eagerly, weakly — never override a\n // component-local definition of the same name)\n if (globalCounterStyle && Object.keys(globalCounterStyle).length > 0) {\n for (const [name, descriptors] of Object.entries(globalCounterStyle)) {\n injector.counterStyle(name, descriptors, { weak: true });\n }\n }\n\n // Inject global @function rules (eagerly, weakly — never override a\n // component-local definition of the same name)\n if (globalFunction && Object.keys(globalFunction).length > 0) {\n for (const [name, definition] of Object.entries(globalFunction)) {\n injector.func(name, definition, { weak: true });\n }\n }\n\n // Inject configured tokens as :root CSS custom properties\n if (globalConfigTokens && Object.keys(globalConfigTokens).length > 0) {\n const tokenRules = renderStyles(\n globalConfigTokens,\n ':root',\n ) as StyleResult[];\n if (tokenRules.length > 0) {\n injector.injectGlobal(tokenRules);\n }\n }\n\n // Inject configured global styles\n if (globalStyles) {\n for (const [selector, styles] of Object.entries(globalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n injector.injectGlobal(rules);\n }\n }\n }\n }\n}\n\n/**\n * Check if styles have been generated (configuration is locked)\n */\nexport { hasStylesGenerated } from './config-state';\n\n/**\n * Reset styles generated flag (for testing only)\n */\nexport function resetStylesGenerated(): void {\n resetStylesGeneratedState();\n emittedWarnings.clear();\n}\n\n// ============================================================================\n// Global Keyframes Management\n// ============================================================================\n\nlet _hasGlobalKeyframes = false;\n\n/**\n * Check if any global keyframes are configured.\n * Uses a pre-computed flag to avoid Object.keys() allocation on every call.\n */\nexport function hasGlobalKeyframes(): boolean {\n return _hasGlobalKeyframes;\n}\n\n/**\n * Get global keyframes configuration.\n * Returns null if no keyframes configured (fast path for zero-overhead).\n */\nexport function getGlobalKeyframes(): Record<string, KeyframesSteps> | null {\n return globalKeyframes;\n}\n\n/**\n * Set global keyframes (called from configure).\n * Internal use only.\n */\nfunction setGlobalKeyframes(keyframes: Record<string, KeyframesSteps>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'keyframes-after-styles',\n `[Tasty] Cannot update keyframes after styles have been generated.\\n` +\n `The new keyframes will be ignored.`,\n );\n return;\n }\n globalKeyframes = { ...(globalKeyframes ?? {}), ...keyframes };\n _hasGlobalKeyframes = Object.keys(globalKeyframes).length > 0;\n}\n\n// ============================================================================\n// Global Properties Management\n// ============================================================================\n\n/**\n * Set global properties (called from configure).\n * Internal use only.\n */\nfunction setGlobalProperties(\n properties: Record<string, PropertyDefinition>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'properties-after-styles',\n `[Tasty] Cannot update properties after styles have been generated.\\n` +\n `The new properties will be ignored.`,\n );\n return;\n }\n // Merge against the raw user map, not getEffectiveProperties(), which would\n // bake DEFAULT_PROPERTIES into it.\n globalProperties = {\n ...(globalProperties ?? getFromGlobalThis(GTKEY_PROPERTIES) ?? {}),\n ...properties,\n };\n setOnGlobalThis(GTKEY_PROPERTIES, globalProperties);\n}\n\n/**\n * Get the effective properties: DEFAULT_PROPERTIES merged with user-configured\n * properties. User properties override defaults with matching keys.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getEffectiveProperties(): Record<string, PropertyDefinition> {\n const props =\n globalProperties ??\n getFromGlobalThis<Record<string, PropertyDefinition>>(GTKEY_PROPERTIES);\n if (!props) return DEFAULT_PROPERTIES;\n return { ...DEFAULT_PROPERTIES, ...props };\n}\n\n// ============================================================================\n// Global Font Face Management\n// ============================================================================\n\n/**\n * Get global font-face configuration.\n * Returns null if no font faces configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalFontFaces(): Record<string, FontFaceInput> | null {\n return (\n globalFontFace ??\n getFromGlobalThis<Record<string, FontFaceInput>>(GTKEY_FONT_FACE) ??\n null\n );\n}\n\n/**\n * Set global font faces (called from configure).\n * Internal use only.\n */\nfunction setGlobalFontFace(fontFace: Record<string, FontFaceInput>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'fontface-after-styles',\n `[Tasty] Cannot update fontFaces after styles have been generated.\\n` +\n `The new font faces will be ignored.`,\n );\n return;\n }\n globalFontFace = { ...(getGlobalFontFaces() ?? {}), ...fontFace };\n setOnGlobalThis(GTKEY_FONT_FACE, globalFontFace);\n}\n\n// ============================================================================\n// Global Counter Style Management\n// ============================================================================\n\n/**\n * Get global counter-style configuration.\n * Returns null if no counter styles configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalCounterStyles(): Record<\n string,\n CounterStyleDescriptors\n> | null {\n return (\n globalCounterStyle ??\n getFromGlobalThis<Record<string, CounterStyleDescriptors>>(\n GTKEY_COUNTER_STYLE,\n ) ??\n null\n );\n}\n\n/**\n * Set global counter styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalCounterStyle(\n counterStyle: Record<string, CounterStyleDescriptors>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'counterstyle-after-styles',\n `[Tasty] Cannot update counterStyles after styles have been generated.\\n` +\n `The new counter styles will be ignored.`,\n );\n return;\n }\n globalCounterStyle = { ...(getGlobalCounterStyles() ?? {}), ...counterStyle };\n setOnGlobalThis(GTKEY_COUNTER_STYLE, globalCounterStyle);\n}\n\n// ============================================================================\n// Global Function Management\n// ============================================================================\n\n/**\n * Get global @function configuration.\n * Returns null if no functions configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalFunctions(): Record<\n string,\n FunctionDefinition\n> | null {\n return (\n globalFunction ??\n getFromGlobalThis<Record<string, FunctionDefinition>>(GTKEY_FUNCTION) ??\n null\n );\n}\n\n/**\n * Set global functions (called from configure).\n * Internal use only.\n */\nfunction setGlobalFunction(\n functions: Record<string, FunctionDefinition>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'function-after-styles',\n `[Tasty] Cannot update functions after styles have been generated.\\n` +\n `The new functions will be ignored.`,\n );\n return;\n }\n globalFunction = { ...(getGlobalFunctions() ?? {}), ...functions };\n setOnGlobalThis(GTKEY_FUNCTION, globalFunction);\n}\n\n// ============================================================================\n// Polyfills Management\n// ============================================================================\n\n/**\n * Whether the CSS `@function` polyfill (inline expansion) is enabled.\n * Reads from globalThis first for cross-module SSR/zero-runtime support.\n */\nexport function isFunctionsPolyfillEnabled(): boolean {\n const polyfills =\n globalPolyfills ??\n getFromGlobalThis<{ functions?: boolean }>(GTKEY_POLYFILLS) ??\n null;\n return polyfills?.functions === true;\n}\n\n/**\n * Set global polyfill toggles (called from configure).\n * Internal use only.\n */\nfunction setGlobalPolyfills(polyfills: { functions?: boolean }): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'polyfills-after-styles',\n `[Tasty] Cannot update polyfills after styles have been generated.\\n` +\n `The new polyfill toggles will be ignored.`,\n );\n return;\n }\n\n globalPolyfills = { ...(globalPolyfills ?? {}), ...polyfills };\n setOnGlobalThis(GTKEY_POLYFILLS, globalPolyfills);\n}\n\n// ============================================================================\n// Global Recipes Management\n// ============================================================================\n\n/**\n * Check if any global recipes are configured.\n * Fast path: returns false if no recipes were ever set.\n */\nexport function hasGlobalRecipes(): boolean {\n return globalRecipes !== null && Object.keys(globalRecipes).length > 0;\n}\n\n/**\n * Get global recipes configuration.\n * Returns null if no recipes configured (fast path for zero-overhead).\n */\nexport function getGlobalRecipes(): Record<string, RecipeStyles> | null {\n return globalRecipes;\n}\n\n/**\n * Set global recipes (called from configure).\n * Internal use only.\n */\nfunction setGlobalRecipes(recipes: Record<string, RecipeStyles>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'recipes-after-styles',\n `[Tasty] Cannot update recipes after styles have been generated.\\n` +\n `The new recipes will be ignored.`,\n );\n return;\n }\n\n // Dev-mode validation\n if (devMode) {\n for (const [name, recipeStyles] of Object.entries(recipes)) {\n if (name === 'none') {\n warnOnce(\n 'recipe-reserved-none',\n `[Tasty] Recipe name \"none\" is reserved. ` +\n `It is used as a keyword meaning \"no base recipes\" ` +\n `(e.g. recipe: 'none / post-recipe'). ` +\n `Choose a different name for your recipe.`,\n );\n }\n\n for (const key of Object.keys(recipeStyles)) {\n if (isSelector(key)) {\n warnOnce(\n `recipe-selector-${name}-${key}`,\n `[Tasty] Recipe \"${name}\" contains sub-element key \"${key}\". ` +\n `Recipes must be flat styles without sub-element keys. ` +\n `Remove the sub-element key from the recipe definition.`,\n );\n }\n if (key === 'recipe') {\n warnOnce(\n `recipe-recursive-${name}`,\n `[Tasty] Recipe \"${name}\" contains a \"recipe\" key. ` +\n `Recipes cannot reference other recipes. ` +\n `Use space-separated names for composition: recipe: 'base elevated'.`,\n );\n }\n }\n }\n }\n\n globalRecipes = { ...(globalRecipes ?? {}), ...recipes };\n}\n\n// ============================================================================\n// Global Token Styles Management\n// ============================================================================\n\n/**\n * Get global token styles for :root injection.\n * Returns null if no tokens configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalConfigTokens(): ConfigTokens | null {\n return (\n globalConfigTokens ?? getFromGlobalThis<ConfigTokens>(GTKEY_TOKENS) ?? null\n );\n}\n\n/**\n * Set global token styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalConfigTokens(styles: ConfigTokens): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'tokens-after-styles',\n `[Tasty] Cannot update tokens after styles have been generated.\\n` +\n `The new tokens will be ignored.`,\n );\n return;\n }\n globalConfigTokens = globalConfigTokens\n ? { ...globalConfigTokens, ...styles }\n : styles;\n setOnGlobalThis(GTKEY_TOKENS, globalConfigTokens);\n}\n\n// ============================================================================\n// Global Styles Management\n// ============================================================================\n\n/**\n * Get configured global styles for injection.\n * Returns null if no global styles configured.\n * Reads from globalThis first for cross-module SSR support.\n */\nexport function getGlobalStyles(): Record<string, Styles> | null {\n return (\n globalStyles ??\n getFromGlobalThis<Record<string, Styles>>(GTKEY_GLOBAL_STYLES) ??\n null\n );\n}\n\n/**\n * Set configured global styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalStyles(styles: Record<string, Styles>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'globalStyles-after-styles',\n `[Tasty] Cannot update globalStyles after styles have been generated.\\n` +\n `The new global styles will be ignored.`,\n );\n return;\n }\n if (globalStyles) {\n for (const [selector, selectorStyles] of Object.entries(styles)) {\n globalStyles[selector] = globalStyles[selector]\n ? { ...globalStyles[selector], ...selectorStyles }\n : selectorStyles;\n }\n } else {\n globalStyles = { ...styles };\n }\n setOnGlobalThis(GTKEY_GLOBAL_STYLES, globalStyles);\n}\n\n/**\n * Check if configuration is locked (styles have been generated)\n */\nexport function isConfigLocked(): boolean {\n return hasStylesGenerated();\n}\n\n// ============================================================================\n// Configuration API\n// ============================================================================\n\n/**\n * Configure the Tasty style system.\n *\n * Must be called BEFORE any styles are generated (before first render that uses tasty).\n * After styles are generated, configuration is locked and calls to configure() will\n * emit a warning and be ignored.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n *\n * // Configure before app renders\n * configure({\n * nonce: 'abc123',\n * states: {\n * '@mobile': '@media(w < 768px)',\n * '@dark': '@root(theme=dark)',\n * },\n * });\n * ```\n */\nexport function configure(config: Partial<TastyConfig> = {}): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'configure-after-styles',\n `[Tasty] Cannot call configure() after styles have been generated.\\n` +\n `Configuration must be done before the first render. The configuration will be ignored.`,\n );\n return;\n }\n\n // Validate namePrefix early so misconfiguration fails loudly before any\n // CSS is generated under a bad prefix.\n if (config.namePrefix !== undefined) {\n validateNamePrefix(config.namePrefix);\n }\n\n // Collect merged values from plugins first, then override with direct config\n let mergedStates: Record<string, string> = {};\n let mergedUnits: Record<string, string | UnitHandler> = {};\n let mergedFunctions: FunctionsConfig = {};\n let mergedHandlers: Record<string, StyleHandlerDefinition> = {};\n /** Where each handler key came from, so registration warnings can name it. */\n const handlerSources = new Map<string, string>();\n let mergedPropHandlers: Record<string, PropHandlerDefinition> = {};\n /** Where each prop handler key came from, for its warnings. */\n const propHandlerSources = new Map<string, string>();\n const mergedBaseStyleProps: string[] = [];\n let mergedProperties: Record<string, PropertyDefinition> = {};\n let mergedKeyframes: Record<string, KeyframesSteps> = {};\n let mergedFontFaces: Record<string, FontFaceInput> = {};\n let mergedCounterStyles: Record<string, CounterStyleDescriptors> = {};\n let mergedReplaceTokens: Record<string, string | number | boolean> = {};\n let mergedConfigTokens: ConfigTokens = {} as ConfigTokens;\n let mergedRecipes: Record<string, RecipeStyles> = {};\n let mergedPresets: Record<string, TypographyPreset> = {};\n const mergedGlobalStyles: Record<string, Styles> = {};\n\n // Process plugins in order\n if (config.plugins) {\n for (const plugin of config.plugins) {\n if (plugin.states) {\n mergedStates = { ...mergedStates, ...plugin.states };\n }\n if (plugin.units) {\n mergedUnits = { ...mergedUnits, ...plugin.units };\n }\n if (plugin.functions) {\n mergedFunctions = { ...mergedFunctions, ...plugin.functions };\n }\n if (plugin.handlers) {\n mergedHandlers = { ...mergedHandlers, ...plugin.handlers };\n for (const key of Object.keys(plugin.handlers)) {\n handlerSources.set(key, `plugin \"${plugin.name}\"`);\n }\n }\n if (plugin.propHandlers) {\n mergedPropHandlers = { ...mergedPropHandlers, ...plugin.propHandlers };\n for (const key of Object.keys(plugin.propHandlers)) {\n propHandlerSources.set(key, `plugin \"${plugin.name}\"`);\n }\n }\n if (plugin.baseStyleProps) {\n mergedBaseStyleProps.push(...plugin.baseStyleProps);\n }\n if (plugin.properties) {\n mergedProperties = { ...mergedProperties, ...plugin.properties };\n }\n if (plugin.keyframes) {\n mergedKeyframes = { ...mergedKeyframes, ...plugin.keyframes };\n }\n if (plugin.fontFaces) {\n mergedFontFaces = { ...mergedFontFaces, ...plugin.fontFaces };\n }\n if (plugin.counterStyles) {\n mergedCounterStyles = {\n ...mergedCounterStyles,\n ...plugin.counterStyles,\n };\n }\n if (plugin.replaceTokens) {\n mergedReplaceTokens = {\n ...mergedReplaceTokens,\n ...plugin.replaceTokens,\n };\n }\n if (plugin.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...plugin.tokens };\n }\n if (plugin.recipes) {\n mergedRecipes = { ...mergedRecipes, ...plugin.recipes };\n }\n if (plugin.presets) {\n mergedPresets = { ...mergedPresets, ...plugin.presets };\n }\n if (plugin.globalStyles) {\n for (const [sel, styles] of Object.entries(plugin.globalStyles)) {\n mergedGlobalStyles[sel] = mergedGlobalStyles[sel]\n ? { ...mergedGlobalStyles[sel], ...styles }\n : styles;\n }\n }\n }\n }\n\n // Direct config overrides plugins\n if (config.states) {\n mergedStates = { ...mergedStates, ...config.states };\n }\n if (config.units) {\n mergedUnits = { ...mergedUnits, ...config.units };\n }\n if (config.functions) {\n mergedFunctions = { ...mergedFunctions, ...config.functions };\n }\n if (config.handlers) {\n mergedHandlers = { ...mergedHandlers, ...config.handlers };\n for (const key of Object.keys(config.handlers)) {\n handlerSources.set(key, 'configure()');\n }\n }\n if (config.propHandlers) {\n mergedPropHandlers = { ...mergedPropHandlers, ...config.propHandlers };\n for (const key of Object.keys(config.propHandlers)) {\n propHandlerSources.set(key, 'configure()');\n }\n }\n if (config.baseStyleProps) {\n mergedBaseStyleProps.push(...config.baseStyleProps);\n }\n if (config.properties) {\n mergedProperties = { ...mergedProperties, ...config.properties };\n }\n if (config.keyframes) {\n mergedKeyframes = { ...mergedKeyframes, ...config.keyframes };\n }\n if (config.fontFaces) {\n mergedFontFaces = { ...mergedFontFaces, ...config.fontFaces };\n }\n if (config.counterStyles) {\n mergedCounterStyles = { ...mergedCounterStyles, ...config.counterStyles };\n }\n if (config.replaceTokens) {\n mergedReplaceTokens = { ...mergedReplaceTokens, ...config.replaceTokens };\n }\n if (config.presets) {\n mergedPresets = { ...mergedPresets, ...config.presets };\n }\n\n // Generate typography tokens from presets and merge UNDER explicit tokens\n if (Object.keys(mergedPresets).length > 0) {\n const presetTokens = generateTypographyTokens(mergedPresets);\n mergedConfigTokens = {\n ...presetTokens,\n ...mergedConfigTokens,\n };\n }\n\n if (config.tokens) {\n mergedConfigTokens = { ...mergedConfigTokens, ...config.tokens };\n }\n if (config.recipes) {\n mergedRecipes = { ...mergedRecipes, ...config.recipes };\n }\n if (config.globalStyles) {\n for (const [sel, styles] of Object.entries(config.globalStyles)) {\n mergedGlobalStyles[sel] = mergedGlobalStyles[sel]\n ? { ...mergedGlobalStyles[sel], ...styles }\n : styles;\n }\n }\n\n // Warn on tokens/replaceTokens key conflicts\n if (devMode) {\n const tokenKeys = new Set(Object.keys(mergedConfigTokens));\n for (const key of Object.keys(mergedReplaceTokens)) {\n if (tokenKeys.has(key)) {\n warnOnce(\n `token-conflict-${key}`,\n `[Tasty] Token \"${key}\" is defined in both \\`tokens\\` and \\`replaceTokens\\`. ` +\n `\\`replaceTokens\\` performs parse-time substitution, so the \\`tokens\\` ` +\n `CSS custom property will be injected but never used by Tasty styles. ` +\n `Remove it from one of the two.`,\n );\n }\n }\n }\n\n if (config.colorSpace) {\n warnOnce(\n 'colorSpace-deprecated',\n '[Tasty] configure({ colorSpace }) no longer has any effect and will be ' +\n 'removed in the next major. Colors are emitted as authored, and opacity ' +\n \"is applied with relative color syntax, which reads a color's channels \" +\n 'in the browser. To address channels yourself, write ' +\n '`oklch(from var(--name-color) l c h)` against the token.',\n );\n }\n\n // Handle predefined states\n if (Object.keys(mergedStates).length > 0) {\n setGlobalPredefinedStates(mergedStates);\n }\n\n // Handle parser configuration (merge semantics - extend, not replace)\n const parser = getGlobalParser();\n\n if (config.parserCacheSize !== undefined) {\n parser.updateOptions({ cacheSize: config.parserCacheSize });\n }\n\n if (Object.keys(mergedUnits).length > 0) {\n // Merge with existing units\n const currentUnits = parser.getUnits() ?? CUSTOM_UNITS;\n parser.setUnits({ ...currentUnits, ...mergedUnits });\n }\n\n // Record polyfill toggles before processing functions so we know whether to\n // register inline closures or emit native @function rules.\n if (config.polyfills) {\n setGlobalPolyfills(config.polyfills);\n }\n\n // Split the unified `functions` map by value type into parse functions\n // (bare keys) and declarative CSS @function definitions (`$$` keys).\n const { parseFuncs, functionDefs } = splitFunctions(\n mergedFunctions,\n (key, kind) => {\n warnOnce(\n `functions-mismatch-${key}`,\n kind === 'expected-definition'\n ? `[Tasty] functions[\"${key}\"]: a \"$$\"-prefixed key denotes a CSS @function ` +\n `and expects a definition object, but received a function. Entry ignored.`\n : `[Tasty] functions[\"${key}\"]: a bare key denotes a parse function and ` +\n `expects a function value, but received an object. ` +\n `Did you mean \"$$${key}\"? Entry ignored.`,\n );\n },\n );\n\n if (Object.keys(parseFuncs).length > 0) {\n // Merge with existing parse functions\n const currentFuncs = getGlobalParseFunctions();\n const finalFuncs: Record<string, ParseFunction> = {\n ...currentFuncs,\n ...parseFuncs,\n };\n parser.setFunctions(finalFuncs);\n // Also update the global registry so customFunction() continues to work\n Object.assign(currentFuncs, parseFuncs);\n }\n\n // Declarative CSS @function definitions. When the polyfill is enabled, compile\n // each into an inline parse-function closure (and skip native emission);\n // otherwise store them for eager native @function injection.\n if (Object.keys(functionDefs).length > 0) {\n if (isFunctionsPolyfillEnabled()) {\n for (const [name, definition] of Object.entries(functionDefs)) {\n registerFunctionPolyfill(name, definition);\n }\n } else {\n setGlobalFunction(functionDefs);\n }\n }\n\n // Handle keyframes\n if (Object.keys(mergedKeyframes).length > 0) {\n setGlobalKeyframes(mergedKeyframes);\n }\n\n // Handle properties\n if (Object.keys(mergedProperties).length > 0) {\n setGlobalProperties(mergedProperties);\n }\n\n // Handle font faces\n if (Object.keys(mergedFontFaces).length > 0) {\n setGlobalFontFace(mergedFontFaces);\n }\n\n // Handle counter styles\n if (Object.keys(mergedCounterStyles).length > 0) {\n setGlobalCounterStyle(mergedCounterStyles);\n }\n\n // Handle custom handlers\n if (Object.keys(mergedHandlers).length > 0) {\n for (const [name, definition] of Object.entries(mergedHandlers)) {\n const handler = normalizeHandlerDefinition(name, definition);\n registerHandler(handler, {\n key: name,\n source: handlerSources.get(name),\n });\n }\n }\n\n // Handle props middleware\n if (Object.keys(mergedPropHandlers).length > 0) {\n for (const [name, definition] of Object.entries(mergedPropHandlers)) {\n registerPropHandler(name, definition, {\n source: propHandlerSources.get(name),\n });\n }\n }\n\n // Handle promoted base style props\n if (mergedBaseStyleProps.length > 0) {\n registerBaseStyleProps(mergedBaseStyleProps);\n }\n\n // Handle replaceTokens (parse-time substitution)\n if (Object.keys(mergedReplaceTokens).length > 0) {\n const processedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(mergedReplaceTokens)) {\n if (key.startsWith('#')) {\n const normalized = normalizeColorTokenValue(value);\n if (normalized === null) continue;\n processedTokens[key] = String(normalized);\n } else if (value === false) {\n continue;\n } else {\n processedTokens[key] = String(value);\n }\n }\n setGlobalPredefinedTokens(processedTokens);\n }\n\n // Handle tokens (CSS custom properties on :root)\n if (Object.keys(mergedConfigTokens).length > 0) {\n setGlobalConfigTokens(mergedConfigTokens);\n }\n\n // Handle recipes\n if (Object.keys(mergedRecipes).length > 0) {\n setGlobalRecipes(mergedRecipes);\n }\n\n // Handle global styles\n if (Object.keys(mergedGlobalStyles).length > 0) {\n setGlobalStyles(mergedGlobalStyles);\n }\n\n const {\n states: _states,\n parserCacheSize: _parserCacheSize,\n units: _units,\n functions: _functions,\n polyfills: _polyfills,\n plugins: _plugins,\n keyframes: _keyframes,\n properties: _properties,\n fontFaces: _fontFaces,\n counterStyles: _counterStyles,\n handlers: _handlers,\n propHandlers: _propHandlers,\n baseStyleProps: _baseStyleProps,\n tokens: _tokens,\n replaceTokens: _replaceTokens,\n recipes: _recipes,\n colorSpace: _colorSpace,\n presets: _presets,\n globalStyles: _globalStyles,\n ...injectorConfig\n } = config;\n\n const fullConfig: TastyConfig = {\n ...createDefaultConfig(),\n ...currentConfig,\n ...injectorConfig,\n };\n\n // Store the config\n currentConfig = fullConfig;\n\n // Create/replace the global injector\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n storage[GLOBAL_INJECTOR_KEY] = new StyleInjector(fullConfig);\n}\n\n/**\n * Get the current configuration.\n * If not configured, returns default configuration.\n */\nexport function getConfig(): TastyConfig {\n if (!currentConfig) {\n currentConfig = createDefaultConfig(isTestEnvironment());\n }\n return currentConfig;\n}\n\n/**\n * Get the configured prefix used for every generated identifier\n * (class names, keyframe names, counter-style names).\n *\n * Falls back to the default prefix (`'t'`) when `configure()` has not\n * been called yet — this matches the auto-configuration behavior used\n * by the rest of the system.\n */\nexport function getNamePrefix(): string {\n return currentConfig?.namePrefix ?? DEFAULT_NAME_PREFIX;\n}\n\n/**\n * Get the global injector instance.\n * Auto-configures with defaults if not already configured.\n */\nexport function getGlobalInjector(): StyleInjector {\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n\n if (!storage[GLOBAL_INJECTOR_KEY]) {\n configure();\n }\n\n return storage[GLOBAL_INJECTOR_KEY]!;\n}\n\n/**\n * Reset configuration (for testing only).\n * Clears the global injector and allows reconfiguration.\n */\nexport function resetConfig(): void {\n resetStylesGeneratedState();\n currentConfig = null;\n globalKeyframes = null;\n _hasGlobalKeyframes = false;\n globalProperties = null;\n globalFontFace = null;\n globalCounterStyle = null;\n globalFunction = null;\n globalPolyfills = null;\n globalRecipes = null;\n globalConfigTokens = null;\n globalStyles = null;\n clearGlobalThisConfig();\n resetGlobalPredefinedTokens();\n resetGlobalParseFunctions();\n resetFunctionPolyfills();\n resetHandlers();\n resetStyleChunks();\n resetPropHandlers();\n resetBaseStyleProps();\n clearPipelineCache();\n emittedWarnings.clear();\n resetStyleWarnings();\n\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n delete storage[GLOBAL_INJECTOR_KEY];\n}\n","import { hashString } from '../utils/hash';\n\ninterface ChunkSheet {\n sheet: CSSStyleSheet;\n cssText: string;\n refCount: number;\n}\n\n/**\n * Global registry mapping CSS content hashes to shared constructable\n * CSSStyleSheet objects with reference counting.\n *\n * Multiple shadow roots adopting the same chunk share a single underlying\n * stylesheet object — parse once, adopt everywhere.\n */\nexport class ChunkSheetRegistry {\n private sheets = new Map<string, ChunkSheet>();\n private sheetToHash = new WeakMap<CSSStyleSheet, string>();\n\n /**\n * Get or create a CSSStyleSheet for the given CSS text.\n * Increments refCount. Uses content hash as the dedup key.\n */\n acquire(cssText: string): CSSStyleSheet {\n const hash = hashString(cssText);\n const existing = this.sheets.get(hash);\n\n if (existing) {\n existing.refCount++;\n return existing.sheet;\n }\n\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n\n const entry: ChunkSheet = { sheet, cssText, refCount: 1 };\n this.sheets.set(hash, entry);\n this.sheetToHash.set(sheet, hash);\n\n return sheet;\n }\n\n /**\n * Decrement refCount for a sheet. When refCount reaches 0,\n * the sheet is removed from the registry.\n */\n release(sheet: CSSStyleSheet): void {\n const hash = this.sheetToHash.get(sheet);\n if (!hash) return;\n\n const entry = this.sheets.get(hash);\n if (!entry) return;\n\n entry.refCount--;\n\n if (entry.refCount <= 0) {\n this.sheets.delete(hash);\n this.sheetToHash.delete(sheet);\n }\n }\n\n /**\n * Bulk acquire — returns an array of CSSStyleSheet in the same order.\n */\n acquireAll(cssTexts: string[]): CSSStyleSheet[] {\n return cssTexts.map((text) => this.acquire(text));\n }\n\n /**\n * Bulk release — decrements refCount for each sheet.\n */\n releaseAll(sheets: CSSStyleSheet[]): void {\n for (const sheet of sheets) {\n this.release(sheet);\n }\n }\n\n /** Number of unique sheets currently held. */\n get size(): number {\n return this.sheets.size;\n }\n}\n\n/** Module-level singleton shared across the entire application. */\nexport const chunkSheetRegistry = new ChunkSheetRegistry();\n","import {\n getConfig,\n getGlobalInjector,\n getNamePrefix,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\nimport { tastyClassRegex } from '../utils/name-prefix';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n FunctionDefinition,\n GCOptions,\n GlobalInjectResult,\n InjectOptions,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n PropertyOptions,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: InjectOptions,\n): InjectResult {\n const injector = getGlobalInjector();\n\n markStylesGenerated();\n\n return injector.inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by name and\n * overrides an existing rule by default. Pass `weak: true` for global\n * `configure()` definitions, which never clobber an existing rule.\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Inject a CSS @function rule (custom function).\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by function\n * name and overrides an existing rule by default. Pass `weak: true` for global\n * `configure()` definitions, which never clobber an existing rule.\n *\n * @param name - The function name (`$$name`, `$name`, or `--name`)\n * @param definition - Function definition (args, returns, result, local vars)\n *\n * @example\n * ```ts\n * func('$$negative', { args: ['$value'], result: '(-1 * $value)' });\n * ```\n */\nexport function func(\n name: string,\n definition: FunctionDefinition,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n): void {\n return getGlobalInjector().func(name, definition, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCSSText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCSSText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCSSTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names from the subtree using the\n // configured namePrefix (default `'t'`).\n const classRegex = tastyClassRegex(getNamePrefix());\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (classRegex.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCSSTextForClasses(classSet, options);\n}\n\n/**\n * Take a reference on local `@keyframes` under the deterministic names the\n * caller resolved, and report which entry holds each. Pair with\n * `ownKeyframes()` once the rules exist to inspect.\n */\nexport function holdKeyframes(\n steps: Record<string, KeyframesSteps>,\n names: Map<string, string>,\n options?: { root?: Document | ShadowRoot },\n): Map<string, string> {\n return getGlobalInjector().holdKeyframes(steps, names, options);\n}\n\n/**\n * Record that a class animates these keyframes, so the reference is released\n * when the last such class is collected.\n */\nexport function ownKeyframes(\n key: string,\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n getGlobalInjector().ownKeyframes(key, className, options);\n}\n\n/**\n * Remove every injected rule that is neither in the DOM nor held by an\n * outstanding `inject()` handle. Equivalent to `gc({ force: true })`.\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Count a render, so that a collection pass is scheduled every\n * `gc.touchInterval` of them. Used internally by computeStyles and tasty().\n *\n * @deprecated The class name is ignored — collection asks the DOM what is\n * rendered rather than recording usage per class. The argument is kept so\n * existing calls still compile.\n */\nexport function touch(\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n if (!getConfig().gc) return;\n getGlobalInjector().touch(className, options);\n}\n\n/**\n * Synchronous garbage collection of unused styles — those no element carries\n * and no `inject()` handle references. Evicts the oldest ones once they exceed\n * capacity. With `{ force: true }`, removes all of them regardless of capacity.\n *\n * @returns Number of styles evicted.\n */\nexport function gc(options?: GCOptions): number {\n return getGlobalInjector().gc(options);\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectionMode,\n InjectOptions,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n StyleUsage,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n PropertyOptions,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n FunctionDefinition,\n FunctionParameter,\n GCConfig,\n GCOptions,\n} from './types';\n\nexport { flushStyles, hasPendingStyleWrites, resetStyleBatch } from './batch';\nexport type { QueuedWrite } from './batch';\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\nexport { ChunkSheetRegistry, chunkSheetRegistry } from './chunk-sheet-registry';\n","/**\n * Keyframes Utilities\n *\n * Optimized utilities for extracting and processing keyframes in styles.\n * Designed for zero overhead when no keyframes are used.\n */\n\nimport type { KeyframesSteps } from '../injector/types';\nimport type { Styles } from '../styles/types';\nimport { hashString } from '../utils/hash';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst KEYFRAMES_KEY = '@keyframes';\n\n/**\n * Pattern to extract animation names from CSS animation property values.\n * Animation name is typically the first identifier in the shorthand.\n * Handles: \"fadeIn 300ms ease-in\", \"pulse 1s infinite\", etc.\n *\n * CSS animation shorthand order (all optional except name):\n * animation: name | duration | timing | delay | iteration | direction | fill-mode | play-state\n *\n * Animation names must:\n * - Start with a letter, underscore, or hyphen (but not a digit or CSS keyword)\n * - Not be CSS keywords: none, initial, inherit, unset, revert\n */\nconst CSS_KEYWORDS = new Set([\n 'none',\n 'initial',\n 'inherit',\n 'unset',\n 'revert',\n 'auto',\n 'normal',\n 'running',\n 'paused',\n]);\n\n/**\n * Pattern to match animation name at the start of an animation value.\n * Must start with letter, underscore, or hyphen (not digit).\n */\nconst ANIMATION_NAME_PATTERN = /^([a-zA-Z_-][a-zA-Z0-9_-]*)/;\n\n// ============================================================================\n// Extraction Functions\n// ============================================================================\n\n/**\n * Check if styles object has local @keyframes definition.\n * Fast path: single property lookup.\n */\nexport function hasLocalKeyframes(styles: Styles): boolean {\n return KEYFRAMES_KEY in styles;\n}\n\n/**\n * Extract local @keyframes from styles object.\n * Returns null if no local keyframes (fast path).\n */\nexport function extractLocalKeyframes(\n styles: Styles,\n): Record<string, KeyframesSteps> | null {\n const keyframes = styles[KEYFRAMES_KEY];\n if (!keyframes || typeof keyframes !== 'object') {\n return null;\n }\n return keyframes as Record<string, KeyframesSteps>;\n}\n\n/**\n * Merge local and global keyframes.\n * Local keyframes take priority over global.\n * Returns null if no keyframes exist (fast path).\n */\nexport function mergeKeyframes(\n local: Record<string, KeyframesSteps> | null,\n global: Record<string, KeyframesSteps> | null,\n): Record<string, KeyframesSteps> | null {\n if (!local && !global) return null;\n if (!local) return global;\n if (!global) return local;\n // Local overrides global\n return { ...global, ...local };\n}\n\n// ============================================================================\n// Animation Name Extraction\n// ============================================================================\n\n/**\n * Extract animation name from a single animation value.\n * Returns null if no valid name found.\n *\n * Examples:\n * - \"fadeIn 300ms ease-in\" → \"fadeIn\"\n * - \"1s pulse infinite\" → \"pulse\" (name can be anywhere)\n * - \"none\" → null (CSS keyword)\n * - \"300ms ease-in\" → null (no name, just duration/timing)\n */\nfunction extractAnimationNameFromValue(value: string): string | null {\n const trimmed = value.trim();\n if (!trimmed) return null;\n\n // Split by whitespace and find the first valid animation name\n const parts = trimmed.split(/\\s+/);\n\n for (const part of parts) {\n // Skip CSS keywords\n if (CSS_KEYWORDS.has(part.toLowerCase())) continue;\n\n // Skip time values (e.g., 300ms, 1s, 0.5s)\n if (/^-?[\\d.]+m?s$/i.test(part)) continue;\n\n // Skip iteration counts (e.g., infinite, 3)\n if (part === 'infinite' || /^\\d+$/.test(part)) continue;\n\n // Skip direction values\n if (\n ['normal', 'reverse', 'alternate', 'alternate-reverse'].includes(\n part.toLowerCase(),\n )\n )\n continue;\n\n // Skip fill-mode values\n if (['forwards', 'backwards', 'both'].includes(part.toLowerCase()))\n continue;\n\n // Skip play-state values\n if (['running', 'paused'].includes(part.toLowerCase())) continue;\n\n // Skip timing functions (ease, linear, ease-in, etc., or cubic-bezier/steps)\n if (\n /^(ease|linear|ease-in|ease-out|ease-in-out|step-start|step-end)$/i.test(\n part,\n )\n )\n continue;\n if (/^(cubic-bezier|steps)\\(/i.test(part)) continue;\n\n // Check if it looks like a valid animation name\n const match = ANIMATION_NAME_PATTERN.exec(part);\n if (match) {\n return match[1];\n }\n }\n\n return null;\n}\n\n/**\n * Extract all animation names from an animation property value.\n * Handles multiple animations separated by commas.\n *\n * Example: \"fadeIn 300ms, slideIn 500ms ease-out\" → [\"fadeIn\", \"slideIn\"]\n */\nfunction extractAnimationNamesFromAnimationValue(value: string): string[] {\n const names: string[] = [];\n\n // Split by comma for multiple animations\n const animations = value.split(',');\n\n for (const animation of animations) {\n const name = extractAnimationNameFromValue(animation);\n if (name && !names.includes(name)) {\n names.push(name);\n }\n }\n\n return names;\n}\n\n/**\n * Extract animation names from a style value (handles mappings and arrays).\n */\nfunction extractAnimationNamesFromStyleValue(\n value: unknown,\n names: Set<string>,\n): void {\n if (typeof value === 'string') {\n for (const name of extractAnimationNamesFromAnimationValue(value)) {\n names.add(name);\n }\n } else if (Array.isArray(value)) {\n // Responsive array\n for (const v of value) {\n extractAnimationNamesFromStyleValue(v, names);\n }\n } else if (value && typeof value === 'object') {\n // State mapping\n for (const v of Object.values(value)) {\n extractAnimationNamesFromStyleValue(v, names);\n }\n }\n}\n\n/**\n * Extract all animation names referenced in styles.\n * Scans 'animation' and 'animationName' properties including in state mappings.\n * Returns empty set if no animation properties found (fast path).\n */\nexport function extractAnimationNamesFromStyles(styles: Styles): Set<string> {\n const names = new Set<string>();\n\n // Check animation property\n if ('animation' in styles) {\n extractAnimationNamesFromStyleValue(styles.animation, names);\n }\n\n // Check animationName property\n if ('animationName' in styles) {\n extractAnimationNamesFromStyleValue(styles.animationName, names);\n }\n\n // Check nested selectors (sub-elements)\n for (const [key, value] of Object.entries(styles)) {\n // Skip non-selector keys and special keys\n if (key === '$' || key === KEYFRAMES_KEY) continue;\n\n // Check if it's a selector (starts with &, ., or uppercase)\n if (\n (key.startsWith('&') || key.startsWith('.') || /^[A-Z]/.test(key)) &&\n value &&\n typeof value === 'object'\n ) {\n // Recursively extract from nested styles\n const nestedNames = extractAnimationNamesFromStyles(value as Styles);\n for (const name of nestedNames) {\n names.add(name);\n }\n }\n }\n\n return names;\n}\n\n// ============================================================================\n// Name Replacement\n// ============================================================================\n\n/**\n * Replace animation names in CSS declarations with injected names.\n * Optimized to avoid regex creation - uses simple string replacement.\n *\n * @param declarations CSS declarations string\n * @param nameMap Map from original name to injected name (only contains names that differ)\n * @returns Updated declarations string\n */\n/**\n * The name a local `@keyframes` block is emitted under.\n *\n * Content-addressed, and a pure function of what was authored: the same steps\n * always produce the same name, and different steps under the same authored\n * name cannot collide. That is what lets the server and the client agree —\n * a name handed out by whichever injector happened to see the definition first\n * depends on run order, so the two would disagree on both the animation name\n * and the class that references it.\n */\nexport function resolveKeyframesName(\n authored: string,\n steps: KeyframesSteps,\n): string {\n return `${authored}-${hashString(JSON.stringify(steps))}`;\n}\n\n/**\n * The emitted name for every local `@keyframes` in `styles`, by authored name.\n * Pure — the server, the RSC pass and the client all reach the same answer.\n */\nexport function resolveKeyframesNames(\n used: Record<string, KeyframesSteps>,\n): Map<string, string> {\n const names = new Map<string, string>();\n\n for (const [authored, steps] of Object.entries(used)) {\n names.set(authored, resolveKeyframesName(authored, steps));\n }\n\n return names;\n}\n\n/**\n * Whether `declarations` names `animation` as an animation to run.\n *\n * Only `animation` and `animation-name` values count, and only whole tokens\n * within them: an animation called `crossfade` does not use keyframes called\n * `fade`. Same parsing as `replaceAnimationNames`, so the two agree on what\n * counts as a reference.\n */\nexport function referencesAnimation(\n declarations: string,\n animation: string,\n): boolean {\n if (!declarations.includes('animation')) return false;\n\n for (const part of declarations.split(';')) {\n const colonIdx = part.indexOf(':');\n if (colonIdx === -1) continue;\n\n const prop = part.slice(0, colonIdx).trim().toLowerCase();\n if (prop !== 'animation' && prop !== 'animation-name') continue;\n\n const value = part.slice(colonIdx + 1);\n if (replaceWord(value, animation, '\\u0000') !== value) return true;\n }\n\n return false;\n}\n\nexport function replaceAnimationNames(\n declarations: string,\n nameMap: Map<string, string>,\n): string {\n // Fast path: no animation properties\n if (!declarations.includes('animation')) return declarations;\n\n // Parse and replace\n const parts = declarations.split(';');\n let modified = false;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n const colonIdx = part.indexOf(':');\n if (colonIdx === -1) continue;\n\n const prop = part.slice(0, colonIdx).trim().toLowerCase();\n\n if (prop === 'animation' || prop === 'animation-name') {\n const prefix = part.slice(0, colonIdx + 1);\n let value = part.slice(colonIdx + 1);\n\n // Replace each animation name using simple word replacement\n for (const [original, injected] of nameMap) {\n // Simple word boundary replacement without regex\n const newValue = replaceWord(value, original, injected);\n if (newValue !== value) {\n value = newValue;\n modified = true;\n }\n }\n\n parts[i] = prefix + value;\n }\n }\n\n return modified ? parts.join(';') : declarations;\n}\n\n/**\n * Replace a word in a string (word boundary aware, no regex).\n */\nfunction replaceWord(str: string, word: string, replacement: string): string {\n let result = str;\n let idx = 0;\n\n while ((idx = result.indexOf(word, idx)) !== -1) {\n // Check word boundaries\n const before = idx === 0 ? ' ' : result[idx - 1];\n const after =\n idx + word.length >= result.length ? ' ' : result[idx + word.length];\n\n const isWordBoundaryBefore = !/[a-zA-Z0-9_-]/.test(before);\n const isWordBoundaryAfter = !/[a-zA-Z0-9_-]/.test(after);\n\n if (isWordBoundaryBefore && isWordBoundaryAfter) {\n result =\n result.slice(0, idx) + replacement + result.slice(idx + word.length);\n idx += replacement.length;\n } else {\n idx += word.length;\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Filter Functions\n// ============================================================================\n\n/**\n * Filter keyframes to only those that are actually used.\n * Returns null if no keyframes are used (fast path).\n */\nexport function filterUsedKeyframes(\n keyframes: Record<string, KeyframesSteps> | null,\n usedNames: Set<string>,\n): Record<string, KeyframesSteps> | null {\n if (!keyframes || usedNames.size === 0) return null;\n\n const used: Record<string, KeyframesSteps> = {};\n let hasAny = false;\n\n for (const name of usedNames) {\n if (keyframes[name]) {\n used[name] = keyframes[name];\n hasAny = true;\n }\n }\n\n return hasAny ? used : null;\n}\n","/**\n * Global reference to the SSR collector getter function.\n *\n * This indirection avoids importing 'node:async_hooks' in the browser bundle.\n * The SSR entry point sets this ref when loaded on the server. The useStyles\n * hook calls it if set; on the client it stays null and is never called.\n *\n * Uses a module-level variable as the primary mechanism. In Next.js App\n * Router the RSC and SSR module graphs load separate copies of this module,\n * so the getter registered by TastyRegistry (SSR layer) is invisible to\n * server components (RSC layer) — which correctly fall through to inline\n * RSC styles.\n *\n * A globalThis fallback (`registerSSRCollectorGetterGlobal`) is provided\n * for frameworks like Astro where middleware and page components live in\n * different module graphs and must share the getter across them.\n */\n\nimport type { ServerStyleCollector } from './collector';\n\ntype SSRCollectorGetter = () => ServerStyleCollector | null;\n\nconst GETTER_KEY = '__tasty_ssr_collector_getter__';\n\nlet _getSSRCollector: SSRCollectorGetter | null = null;\n\n/**\n * Register the collector getter in the current module graph only.\n * Used by Next.js TastyRegistry.\n */\nexport function registerSSRCollectorGetter(fn: SSRCollectorGetter): void {\n _getSSRCollector = fn;\n}\n\n/**\n * Register the collector getter on globalThis so it is visible across\n * separate module graphs (e.g. Astro middleware ↔ page components).\n */\nexport function registerSSRCollectorGetterGlobal(fn: SSRCollectorGetter): void {\n (globalThis as Record<string, unknown>)[GETTER_KEY] = fn;\n}\n\n/**\n * Retrieve the SSR collector: module-level first, globalThis fallback.\n */\nexport function getRegisteredSSRCollector(): ServerStyleCollector | null {\n if (_getSSRCollector) return _getSSRCollector();\n const getter = (globalThis as Record<string, unknown>)[GETTER_KEY] as\n SSRCollectorGetter | undefined;\n return getter ? getter() : null;\n}\n","/**\n * Format @property CSS rules for SSR output.\n *\n * Replicates the CSS construction from StyleInjector.property()\n * but returns a CSS string instead of inserting into the DOM.\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { getEffectiveDefinition } from '../properties';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\n/**\n * Format a single @property rule as a CSS string.\n *\n * Returns the full `@property --name { ... }` text, or empty string\n * if the token is invalid.\n */\nexport function formatPropertyCSS(\n token: string,\n definition: PropertyDefinition,\n): string {\n const result = getEffectiveDefinition(token, definition);\n if (!result.isValid) return '';\n\n return buildPropertyRule(result.cssName, result.definition);\n}\n\nfunction buildPropertyRule(\n cssName: string,\n definition: PropertyDefinition,\n): string {\n const parts: string[] = [];\n\n if (definition.syntax != null) {\n let syntax = String(definition.syntax).trim();\n if (!/^['\"]/u.test(syntax)) syntax = `\"${syntax}\"`;\n parts.push(`syntax: ${syntax};`);\n }\n\n const inherits = definition.inherits ?? true;\n parts.push(`inherits: ${inherits ? 'true' : 'false'};`);\n\n if (definition.initialValue != null) {\n let initialValueStr: string;\n if (typeof definition.initialValue === 'number') {\n initialValueStr = String(definition.initialValue);\n } else {\n initialValueStr = parseStyle(\n definition.initialValue as StyleValue,\n ).output;\n }\n parts.push(`initial-value: ${initialValueStr};`);\n }\n\n const declarations = parts.join(' ').trim();\n return `@property ${cssName} { ${declarations} }`;\n}\n","/**\n * Format @keyframes CSS rules for SSR output.\n *\n * Replicates the stepsToCSS logic from SheetManager but as a\n * standalone function that doesn't need DOM access.\n */\n\nimport type { KeyframesSteps } from '../injector/types';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\nimport type { CSSMap, StyleHandler, StyleValueStateMap } from '../utils/styles';\n\n/**\n * Convert keyframes steps to a CSS string.\n * Replicates SheetManager.stepsToCSS() without the class instance.\n */\nfunction stepsToCSS(steps: KeyframesSteps): string {\n const rules: string[] = [];\n\n for (const [key, value] of Object.entries(steps)) {\n if (typeof value === 'string') {\n rules.push(`${key} { ${value.trim()} }`);\n continue;\n }\n\n const styleMap = (value || {}) as StyleValueStateMap;\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 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 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 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 const declarations = declarationPairs\n .map((d) => `${d.prop}: ${d.value}`)\n .join('; ');\n\n rules.push(`${key} { ${declarations.trim()} }`);\n }\n\n return rules.join(' ');\n}\n\n/**\n * Format a @keyframes rule as a CSS string.\n */\nexport function formatKeyframesCSS(\n name: string,\n steps: KeyframesSteps,\n): string {\n const cssSteps = stepsToCSS(steps);\n return `@keyframes ${name} { ${cssSteps} }`;\n}\n","/**\n * Shared CSS rule formatting utility.\n *\n * Extracted from SheetManager to allow both the DOM-based injector (client)\n * and the ServerStyleCollector (server) to produce identical CSS text\n * from StyleResult arrays.\n */\n\nimport type { StyleResult } from '../pipeline';\n\n/**\n * Resolve selectors for a rule, applying className-based specificity doubling\n * and rootPrefix handling. Mirrors the logic in StyleInjector.inject().\n */\nfunction resolveSelector(rule: StyleResult, className: string): string {\n let selector = rule.selector;\n\n if (rule.needsClassName) {\n const selectorParts = selector ? selector.split('|||') : [''];\n const classPrefix = `.${className}.${className}`;\n\n selector = selectorParts\n .map((part) => {\n const classSelector = part ? `${classPrefix}${part}` : classPrefix;\n\n if (rule.rootPrefix) {\n return `${rule.rootPrefix} ${classSelector}`;\n }\n return classSelector;\n })\n .join(', ');\n }\n\n return selector;\n}\n\ninterface GroupedRule {\n selector: string;\n declarations: string;\n atRules?: string[];\n startingStyle?: boolean;\n}\n\n/**\n * Group rules by selector + at-rules + startingStyle and merge their declarations.\n * Mirrors the grouping logic in SheetManager.insertRule().\n */\nfunction groupRules(rules: GroupedRule[]): GroupedRule[] {\n const groupMap = new Map<string, GroupedRule>();\n const order: string[] = [];\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n for (const r of rules) {\n const key = `${atKey(r.atRules)}||${r.selector}||${r.startingStyle ? '1' : '0'}`;\n const existing = groupMap.get(key);\n if (existing) {\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n selector: r.selector,\n atRules: r.atRules,\n startingStyle: r.startingStyle,\n declarations: r.declarations,\n });\n order.push(key);\n }\n }\n\n return order.map((key) => groupMap.get(key)!);\n}\n\n/**\n * Format an array of StyleResult rules into a CSS text string.\n *\n * Applies className-based specificity doubling (.cls.cls),\n * groups rules by selector + at-rules, and wraps with at-rule blocks.\n *\n * Produces the same CSS text as SheetManager.insertRule() would insert\n * into the DOM, but as a plain string suitable for SSR output.\n */\nexport function formatRules(rules: StyleResult[], className: string): string {\n if (rules.length === 0) return '';\n\n const resolvedRules = rules.map((rule) => ({\n selector: resolveSelector(rule, className),\n declarations: rule.declarations,\n atRules: rule.atRules,\n startingStyle: rule.startingStyle,\n }));\n\n const grouped = groupRules(resolvedRules);\n const cssRules: string[] = [];\n\n for (const rule of grouped) {\n const innerContent = rule.startingStyle\n ? `@starting-style { ${rule.declarations} }`\n : rule.declarations;\n const baseRule = `${rule.selector} { ${innerContent} }`;\n\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 cssRules.push(fullRule);\n }\n\n return cssRules.join('\\n');\n}\n","/**\n * Recipe resolution utility.\n *\n * Resolves `recipe` style properties by looking up predefined recipe styles\n * from global configuration and merging them with the component's own styles.\n *\n * Resolution order per level (top-level and each sub-element independently):\n * base_recipe_1 base_recipe_2 → component styles → post_recipe_1 post_recipe_2\n *\n * The `/` separator splits base recipes (before component styles)\n * from post recipes (after component styles). All merges use mergeStyles\n * semantics: primitives and state maps with '' key fully replace;\n * state maps without '' key extend the existing value.\n *\n * Returns the same object reference if no recipes are present (zero overhead).\n */\n\nimport { getGlobalRecipes } from '../config';\nimport type { RecipeStyles, Styles } from '../styles/types';\n\nimport { isDevEnv } from './is-dev-env';\nimport { isSelector } from './is-selector';\nimport { mergeStyles } from './merge-styles';\n\nconst devMode = isDevEnv();\n\ninterface ParsedRecipeGroups {\n base: string[] | null;\n post: string[] | null;\n}\n\n/**\n * Parse a recipe string into base and post recipe name groups.\n *\n * Syntax: `'base1 base2 / post1 post2'`\n * - Names are space-separated within each group\n * - `/` separates base (before component) from post (after component) groups\n * - `/` is optional; if absent, all names are base\n * - `none` as the sole base value means \"no base recipes\"\n *\n * Returns `{ base: null, post: null }` if the string is empty or invalid.\n */\nfunction parseRecipeNames(value: unknown): ParsedRecipeGroups {\n const empty: ParsedRecipeGroups = { base: null, post: null };\n\n if (typeof value !== 'string') return empty;\n const trimmed = value.trim();\n if (trimmed === '') return empty;\n\n const slashIndex = trimmed.indexOf('/');\n\n if (slashIndex === -1) {\n if (trimmed === 'none') return empty;\n const names = splitNames(trimmed);\n return { base: names, post: null };\n }\n\n const basePart = trimmed.slice(0, slashIndex);\n const postPart = trimmed.slice(slashIndex + 1);\n\n return {\n base: basePart.trim() === 'none' ? null : splitNames(basePart),\n post: splitNames(postPart),\n };\n}\n\nfunction splitNames(s: string): string[] | null {\n const names = s.split(/\\s+/).filter(Boolean);\n return names.length > 0 ? names : null;\n}\n\n/**\n * Collect merged styles for a list of recipe names.\n * Each recipe is flat-spread on top of the previous.\n */\nfunction collectRecipeStyles(\n names: string[],\n recipes: Record<string, RecipeStyles>,\n): Record<string, unknown> {\n let merged: Record<string, unknown> = {};\n\n for (const name of names) {\n const recipeStyles = recipes[name];\n\n if (!recipeStyles) {\n if (devMode) {\n console.warn(\n `[Tasty] Recipe \"${name}\" not found. ` +\n `Make sure it is defined in configure({ recipes: { ... } }).`,\n );\n }\n continue;\n }\n\n merged = { ...merged, ...(recipeStyles as Record<string, unknown>) };\n }\n\n return merged;\n}\n\n/**\n * Resolve recipe references in a flat styles object (no sub-elements).\n * Returns null if no `recipe` key is present.\n *\n * Resolution: base recipes → component styles → post recipes (all via mergeStyles)\n */\nfunction resolveRecipesForLevel(\n styles: Record<string, unknown>,\n recipes: Record<string, RecipeStyles>,\n): Record<string, unknown> | null {\n if (!('recipe' in styles)) return null;\n\n const { base, post } = parseRecipeNames(styles.recipe);\n\n // Separate selector keys (sub-elements) from flat style properties.\n // mergeStyles handles selectors with its own semantics (e.g. false = delete),\n // but at this level we only want recipe merging on flat properties.\n\n const { recipe: _recipe, ...allRest } = styles;\n const flatStyles: Record<string, unknown> = {};\n const selectorStyles: Record<string, unknown> = {};\n\n for (const key of Object.keys(allRest)) {\n if (isSelector(key)) {\n selectorStyles[key] = allRest[key];\n } else {\n flatStyles[key] = allRest[key];\n }\n }\n\n if (!base && !post) {\n return allRest;\n }\n\n // 1. Merge base recipes, then component styles on top (via mergeStyles)\n let result: Record<string, unknown>;\n\n if (base) {\n const baseStyles = collectRecipeStyles(base, recipes);\n result = mergeStyles(baseStyles as Styles, flatStyles as Styles) as Record<\n string,\n unknown\n >;\n } else {\n result = { ...flatStyles };\n }\n\n // 2. Apply post recipes via mergeStyles (state map extend semantics)\n if (post) {\n const postStyles = collectRecipeStyles(post, recipes);\n result = mergeStyles(result as Styles, postStyles as Styles) as Record<\n string,\n unknown\n >;\n }\n\n // Re-attach selector keys unchanged\n for (const key of Object.keys(selectorStyles)) {\n result[key] = selectorStyles[key];\n }\n\n return result;\n}\n\n/**\n * Resolve all `recipe` style properties in a styles object.\n *\n * Handles both top-level and sub-element recipe references.\n * Returns the same object reference if no recipes are present anywhere\n * (zero overhead for the common case).\n *\n * @param styles - The styles object potentially containing `recipe` keys\n * @returns Resolved styles with recipe values merged in, or the original object if unchanged\n */\nexport function resolveRecipes(styles: Styles): Styles {\n const recipes = getGlobalRecipes();\n\n // Fast path: no recipes configured globally\n if (!recipes) return styles;\n\n let changed = false;\n\n // Resolve top-level recipe\n const topResolved = resolveRecipesForLevel(\n styles as Record<string, unknown>,\n recipes,\n );\n\n let result: Record<string, unknown>;\n\n if (topResolved) {\n changed = true;\n result = topResolved;\n } else {\n // Keep reference; a shallow copy is deferred until a sub-element actually changes\n result = styles as Record<string, unknown>;\n }\n\n // Resolve sub-element recipes\n const keys = Object.keys(result);\n\n for (const key of keys) {\n if (!isSelector(key)) continue;\n\n const subStyles = result[key];\n\n if (\n !subStyles ||\n typeof subStyles !== 'object' ||\n Array.isArray(subStyles)\n ) {\n continue;\n }\n\n const subRecord = subStyles as Record<string, unknown>;\n\n if (!('recipe' in subRecord)) continue;\n\n const subResolved = resolveRecipesForLevel(subRecord, recipes);\n\n if (subResolved) {\n if (!changed) {\n // First change in sub-elements -- need to shallow-copy the top level\n changed = true;\n result = { ...(styles as Record<string, unknown>) };\n }\n result[key] = subResolved;\n }\n }\n\n return changed ? (result as Styles) : styles;\n}\n","import { Lru } from '../parser/lru';\n\n/**\n * Create a function that caches the result with LRU eviction.\n */\nexport function cacheWrapper<A, B, R>(\n handler: (firstArg: A, secondArg?: B) => R,\n limit = 1000,\n): (firstArg: A, secondArg?: B) => R {\n const cache = new Lru<string, R>(limit);\n\n return (firstArg: A, secondArg?: B) => {\n const key =\n typeof firstArg === 'string' && secondArg == null\n ? firstArg\n : JSON.stringify([firstArg, secondArg]);\n\n let result = cache.get(key);\n if (result === undefined) {\n result =\n secondArg == null ? handler(firstArg) : handler(firstArg, secondArg);\n cache.set(key, result);\n }\n return result;\n };\n}\n","/**\n * Format global CSS rules for SSR output.\n *\n * Unlike formatRules() which applies className-based specificity doubling,\n * this function formats rules that already have their full selectors\n * (from renderStyles called with a selector string).\n */\n\nimport type { StyleResult } from '../pipeline';\n\n/**\n * Format an array of global StyleResult rules into a CSS text string.\n *\n * Rules already have their full selectors applied by renderStyles().\n * Handles rootPrefix prepending and at-rule wrapping.\n */\nexport function formatGlobalRules(rules: StyleResult[]): string {\n if (rules.length === 0) return '';\n\n const cssRules: string[] = [];\n\n for (const rule of rules) {\n const selector = rule.rootPrefix\n ? `${rule.rootPrefix} ${rule.selector}`\n : rule.selector;\n\n const baseRule = `${selector} { ${rule.declarations} }`;\n\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 cssRules.push(fullRule);\n }\n\n return cssRules.join('\\n');\n}\n","import { getGlobalInjector } from '../config';\n\n/**\n * Build a per-(injector, root) client state cache for the standalone style\n * functions (`useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useCounterStyle`).\n *\n * Two levels, both weak:\n *\n * - **injector** — `configure()` replaces the global injector, and every dispose\n * handle and generated name we cache belongs to the one that produced it.\n * Keying by injector makes stale state fall away with it, instead of letting\n * change-detection keys suppress re-injection into the new sheets.\n * - **root** — the same selector or slot name can be used in several shadow\n * roots, and each holds its own injection.\n */\nexport function createClientState<T extends object>(\n create: () => T,\n): (root: Document | ShadowRoot) => T {\n const byInjector = new WeakMap<object, WeakMap<Document | ShadowRoot, T>>();\n\n return (root: Document | ShadowRoot): T => {\n const injector = getGlobalInjector() as unknown as object;\n\n let byRoot = byInjector.get(injector);\n if (!byRoot) {\n byRoot = new WeakMap();\n byInjector.set(injector, byRoot);\n }\n\n let state = byRoot.get(root);\n if (!state) {\n state = create();\n byRoot.set(root, state);\n }\n\n return state;\n };\n}\n","/**\n * Shallow comparison of two dependency arrays using Object.is semantics.\n * Returns true when both arrays have the same length and every element\n * at the same index is identical.\n */\nexport function depsEqual(\n a: readonly unknown[],\n b: readonly unknown[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n"],"mappings":";;;;AAwBA,MAAM,eAAe;;AAGrB,MAAM,gBAAgB,IAAI,IAAI;CAAC;CAAQ;CAAW;AAAQ,CAAC;;;;AA2B3D,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,gBAAgB;AACzB;;;;;AAMA,SAAgB,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