@jasonshimmy/custom-elements-runtime 1.2.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +157 -83
  2. package/dist/custom-elements-runtime.cjs.js +6 -149
  3. package/dist/custom-elements-runtime.cjs.js.map +1 -1
  4. package/dist/custom-elements-runtime.directive-enhancements.cjs.js +2 -0
  5. package/dist/custom-elements-runtime.directive-enhancements.cjs.js.map +1 -0
  6. package/dist/custom-elements-runtime.directive-enhancements.es.js +144 -0
  7. package/dist/custom-elements-runtime.directive-enhancements.es.js.map +1 -0
  8. package/dist/custom-elements-runtime.directives.cjs.js +2 -0
  9. package/dist/custom-elements-runtime.directives.cjs.js.map +1 -0
  10. package/dist/custom-elements-runtime.directives.es.js +49 -0
  11. package/dist/custom-elements-runtime.directives.es.js.map +1 -0
  12. package/dist/custom-elements-runtime.es.js +2147 -4451
  13. package/dist/custom-elements-runtime.es.js.map +1 -1
  14. package/dist/custom-elements-runtime.event-bus.cjs.js +2 -0
  15. package/dist/custom-elements-runtime.event-bus.cjs.js.map +1 -0
  16. package/dist/custom-elements-runtime.event-bus.es.js +147 -0
  17. package/dist/custom-elements-runtime.event-bus.es.js.map +1 -0
  18. package/dist/custom-elements-runtime.router.cjs.js +29 -0
  19. package/dist/custom-elements-runtime.router.cjs.js.map +1 -0
  20. package/dist/custom-elements-runtime.router.es.js +305 -0
  21. package/dist/custom-elements-runtime.router.es.js.map +1 -0
  22. package/dist/custom-elements-runtime.ssr.cjs.js +2 -0
  23. package/dist/custom-elements-runtime.ssr.cjs.js.map +1 -0
  24. package/dist/custom-elements-runtime.ssr.es.js +18 -0
  25. package/dist/custom-elements-runtime.ssr.es.js.map +1 -0
  26. package/dist/custom-elements-runtime.store.cjs.js +2 -0
  27. package/dist/custom-elements-runtime.store.cjs.js.map +1 -0
  28. package/dist/custom-elements-runtime.store.es.js +25 -0
  29. package/dist/custom-elements-runtime.store.es.js.map +1 -0
  30. package/dist/custom-elements-runtime.transitions.cjs.js +2 -0
  31. package/dist/custom-elements-runtime.transitions.cjs.js.map +1 -0
  32. package/dist/custom-elements-runtime.transitions.es.js +10 -0
  33. package/dist/custom-elements-runtime.transitions.es.js.map +1 -0
  34. package/dist/directive-enhancements.d.ts +6 -6
  35. package/dist/directives.d.ts +2 -2
  36. package/dist/event-bus.d.ts +20 -11
  37. package/dist/helpers-CDfJhmMS.js +609 -0
  38. package/dist/helpers-CDfJhmMS.js.map +1 -0
  39. package/dist/helpers-D3UjNfYY.cjs +5 -0
  40. package/dist/helpers-D3UjNfYY.cjs.map +1 -0
  41. package/dist/index.d.ts +6 -20
  42. package/dist/logger-BpibrmKL.js +25 -0
  43. package/dist/logger-BpibrmKL.js.map +1 -0
  44. package/dist/logger-CqdBMdui.cjs +2 -0
  45. package/dist/logger-CqdBMdui.cjs.map +1 -0
  46. package/dist/router.d.ts +6 -6
  47. package/dist/runtime/component.d.ts +3 -3
  48. package/dist/runtime/event-manager.d.ts +3 -3
  49. package/dist/runtime/helpers.d.ts +4 -4
  50. package/dist/runtime/hooks.d.ts +3 -3
  51. package/dist/runtime/lifecycle.d.ts +1 -1
  52. package/dist/runtime/logger.d.ts +3 -3
  53. package/dist/runtime/node-metadata.d.ts +11 -2
  54. package/dist/runtime/props.d.ts +2 -2
  55. package/dist/runtime/reactive-proxy-cache.d.ts +6 -3
  56. package/dist/runtime/reactive.d.ts +5 -4
  57. package/dist/runtime/render.d.ts +4 -4
  58. package/dist/runtime/secure-expression-evaluator.d.ts +1 -1
  59. package/dist/runtime/template-compiler.d.ts +10 -10
  60. package/dist/runtime/transition-group-handler.d.ts +21 -0
  61. package/dist/runtime/transition-utils.d.ts +43 -3
  62. package/dist/runtime/types.d.ts +27 -17
  63. package/dist/runtime/vdom-model-helpers.d.ts +7 -7
  64. package/dist/runtime/vdom-ssr.d.ts +9 -0
  65. package/dist/runtime/vdom.d.ts +30 -22
  66. package/dist/runtime/watchers.d.ts +3 -3
  67. package/dist/ssr.d.ts +6 -0
  68. package/dist/transitions-Crm12oGl.cjs +115 -0
  69. package/dist/transitions-Crm12oGl.cjs.map +1 -0
  70. package/dist/transitions-D5YybtBE.js +1415 -0
  71. package/dist/transitions-D5YybtBE.js.map +1 -0
  72. package/dist/transitions.d.ts +5 -0
  73. package/package.json +56 -8
  74. package/dist/custom-elements-runtime.umd.js +0 -156
  75. package/dist/custom-elements-runtime.umd.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.cjs.js","sources":["../src/lib/runtime/logger.ts","../src/lib/runtime/scheduler.ts","../src/lib/runtime/reactive-proxy-cache.ts","../src/lib/runtime/reactive.ts","../src/lib/runtime/helpers.ts","../src/lib/runtime/watchers.ts","../src/lib/runtime/props.ts","../src/lib/runtime/lifecycle.ts","../src/lib/runtime/secure-expression-evaluator.ts","../src/lib/runtime/event-manager.ts","../src/lib/runtime/vdom-model-helpers.ts","../src/lib/runtime/transition-utils.ts","../src/lib/runtime/node-metadata.ts","../src/lib/runtime/vdom.ts","../src/lib/runtime/style.ts","../src/lib/directives.ts","../src/lib/transitions.ts","../src/lib/runtime/render.ts","../src/lib/runtime/hooks.ts","../src/lib/runtime/component.ts","../src/lib/runtime/template-compiler.ts","../src/lib/directive-enhancements.ts","../src/lib/event-bus.ts","../src/lib/store.ts","../src/lib/router.ts"],"sourcesContent":["/**\n * Development-only logging utilities\n * These are stripped out in production builds via bundler configuration\n */\n\n// Robust dev-mode detection across environments (Node tests, Vite dev server, browser)\nlet isDev = false;\ntry {\n // Node environment (Vitest / Node.js) via globalThis.process to avoid TS node type dependency\n const maybeProcess: any = (globalThis as any).process;\n if (maybeProcess && maybeProcess.env) {\n isDev = maybeProcess.env.NODE_ENV !== 'production';\n } else if (typeof import.meta !== 'undefined' && (import.meta as any).env) {\n // Vite / bundler-provided mode\n isDev = (import.meta as any).env.MODE !== 'production';\n } else {\n // Fallback: assume dev when running in a browser-like environment without explicit MODE\n isDev = typeof window !== 'undefined';\n }\n} catch (e) {\n // Be conservative: default to true to surface diagnostics during development\n isDev = true;\n}\n\n/**\n * Log error only in development mode\n */\nexport function devError(message: string, ...args: any[]): void {\n if (isDev) {\n console.error(message, ...args);\n }\n}\n\n/**\n * Log warning only in development mode\n */\nexport function devWarn(message: string, ...args: any[]): void {\n if (isDev) {\n console.warn(message, ...args);\n }\n}\n\n/**\n * Log info only in development mode\n */\nexport function devLog(message: string, ...args: any[]): void {\n if (isDev) {\n console.log(message, ...args);\n }\n}\n","/**\n * Update Scheduler for batching DOM updates\n * Prevents excessive re-renders and improves performance\n */\nimport { devError } from \"./logger\";\n\nclass UpdateScheduler {\n private pendingUpdates = new Map<string | (() => void), () => void>();\n private isFlushScheduled = false;\n\n /**\n * Schedule an update to be executed in the next microtask\n * Uses component identity to deduplicate multiple render requests for the same component\n */\n schedule(update: () => void, componentId?: string): void {\n // IMPORTANT: Never use update.toString() as it breaks with minification!\n // Use the componentId if provided, otherwise use the function reference directly as the key\n // since Map supports using function references as keys (identity-based comparison)\n const key = componentId || update;\n this.pendingUpdates.set(key, update);\n \n if (!this.isFlushScheduled) {\n this.isFlushScheduled = true;\n \n // Check if we're in a test environment\n const isTestEnv = typeof (globalThis as any).process !== 'undefined' && \n (globalThis as any).process.env?.NODE_ENV === 'test' ||\n typeof window !== 'undefined' && ((window as any).__vitest__ || (window as any).Cypress);\n \n if (isTestEnv) {\n // Execute synchronously in test environments to avoid timing issues\n this.flush();\n } else {\n queueMicrotask(() => this.flush());\n }\n }\n }\n\n /**\n * Execute all pending updates\n */\n private flush(): void {\n const updates = this.pendingUpdates;\n this.pendingUpdates = new Map();\n this.isFlushScheduled = false;\n\n // Execute all updates in batch\n for (const update of updates.values()) {\n try {\n update();\n } catch (error) {\n // Continue with other updates even if one fails\n devError('Error in batched update:', error);\n }\n }\n }\n\n /**\n * Get the number of pending updates\n */\n get pendingCount(): number {\n return this.pendingUpdates.size;\n }\n}\n\n// Global scheduler instance\nexport const updateScheduler = new UpdateScheduler();\n\n/**\n * Schedule a DOM update to be batched with optional component identity\n */\nexport function scheduleDOMUpdate(update: () => void, componentId?: string): void {\n updateScheduler.schedule(update, componentId);\n}\n","/**\n * Reactive proxy cache to optimize proxy creation and reuse\n * Uses WeakMap for automatic garbage collection when objects are no longer referenced\n */\n\n/**\n * Cache for reactive proxies to avoid creating multiple proxies for the same object\n */\n// legacy symbol marker removed — use WeakSet and non-enumerable flag instead\n// Track actual proxy instances with a WeakSet for robust detection\nconst proxiedObjects = new WeakSet<object>();\n// No legacy flag: rely solely on WeakSet and WeakMap for proxy detection\n\nclass ReactiveProxyCache {\n private static cache = new WeakMap<object, object>();\n private static arrayHandlerCache = new WeakMap<object, ProxyHandler<any>>();\n private static objectHandlerCache = new WeakMap<object, ProxyHandler<any>>();\n \n /**\n * Get or create a reactive proxy for an object\n */\n static getOrCreateProxy<T extends object>(\n obj: T, \n reactiveState: any,\n isArray: boolean = false\n ): T {\n // Check if we already have a cached proxy\n const cached = this.cache.get(obj);\n if (cached) {\n return cached as T;\n }\n \n // Create appropriate handler\n const handler = isArray \n ? this.getOrCreateArrayHandler(reactiveState)\n : this.getOrCreateObjectHandler(reactiveState);\n \n // Create proxy\n const proxy = new Proxy(obj, handler);\n\n // Mark and track the proxy instance (do this via the optimizer helper)\n try { ProxyOptimizer.markAsProxy(proxy as any); } catch {}\n\n // Cache the proxy by the original target object\n this.cache.set(obj, proxy);\n \n return proxy as T;\n }\n \n /**\n * Get or create a cached array handler\n */\n private static getOrCreateArrayHandler(reactiveState: any): ProxyHandler<any> {\n // Create a unique handler for this reactive state\n if (!this.arrayHandlerCache.has(reactiveState)) {\n const handler: ProxyHandler<any> = {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept array mutating methods\n if (typeof value === \"function\" && typeof prop === \"string\") {\n const mutatingMethods = [\n \"push\", \"pop\", \"shift\", \"unshift\", \"splice\", \n \"sort\", \"reverse\", \"fill\", \"copyWithin\"\n ];\n if (mutatingMethods.includes(prop)) {\n return function (...args: any[]) {\n const result = value.apply(target, args);\n // Trigger update after mutation\n reactiveState.triggerUpdate();\n return result;\n };\n }\n }\n\n return value;\n },\n set: (target, prop, value) => {\n (target as any)[prop] = reactiveState.makeReactiveValue(value);\n reactiveState.triggerUpdate();\n return true;\n },\n deleteProperty: (target, prop) => {\n delete (target as any)[prop];\n reactiveState.triggerUpdate();\n return true;\n }\n };\n \n this.arrayHandlerCache.set(reactiveState, handler);\n }\n \n return this.arrayHandlerCache.get(reactiveState)!;\n }\n \n /**\n * Get or create a cached object handler\n */\n private static getOrCreateObjectHandler(reactiveState: any): ProxyHandler<any> {\n // Create a unique handler for this reactive state\n if (!this.objectHandlerCache.has(reactiveState)) {\n const handler: ProxyHandler<any> = {\n get: (target, prop, receiver) => {\n return Reflect.get(target, prop, receiver);\n },\n set: (target, prop, value) => {\n (target as any)[prop] = reactiveState.makeReactiveValue(value);\n reactiveState.triggerUpdate();\n return true;\n },\n deleteProperty: (target, prop) => {\n delete (target as any)[prop];\n reactiveState.triggerUpdate();\n return true;\n }\n };\n \n this.objectHandlerCache.set(reactiveState, handler);\n }\n \n return this.objectHandlerCache.get(reactiveState)!;\n }\n \n /**\n * Check if an object already has a cached proxy\n */\n static hasProxy(obj: object): boolean {\n return this.cache.has(obj);\n }\n \n /**\n * Clear all cached proxies (useful for testing)\n */\n static clear(): void {\n this.cache = new WeakMap();\n this.arrayHandlerCache = new WeakMap();\n this.objectHandlerCache = new WeakMap();\n }\n \n /**\n * Get cache statistics (for debugging)\n * Note: WeakMap doesn't provide size, so this is limited\n */\n static getStats(): { hasCachedProxies: boolean } {\n // WeakMap doesn't expose size, but we can check if we have any handlers cached\n return {\n hasCachedProxies: this.cache instanceof WeakMap\n };\n }\n}\n\n/**\n * Optimized proxy creation utilities\n */\nclass ProxyOptimizer {\n // Cache a stable reactiveContext object keyed by onUpdate -> makeReactive\n // This allows handler caches in ReactiveProxyCache to reuse handlers\n // for identical reactive contexts instead of creating a new context object\n // on each createReactiveProxy call.\n private static contextCache = new WeakMap<Function, WeakMap<Function, { triggerUpdate: Function; makeReactiveValue: Function }>>();\n /**\n * Create an optimized reactive proxy with minimal overhead\n */\n static createReactiveProxy<T extends object>(\n obj: T,\n onUpdate: () => void,\n makeReactive: (value: any) => any\n ): T {\n // If the argument is already a proxy instance, return it directly.\n try {\n if (proxiedObjects.has(obj)) return obj;\n } catch {\n // ignore\n }\n \n const isArray = Array.isArray(obj);\n\n // Reuse a stable reactiveContext object per (onUpdate, makeReactive) pair.\n let inner = this.contextCache.get(onUpdate as any);\n if (!inner) {\n inner = new WeakMap();\n this.contextCache.set(onUpdate as any, inner);\n }\n let reactiveContext = inner.get(makeReactive as any);\n if (!reactiveContext) {\n reactiveContext = {\n triggerUpdate: onUpdate,\n makeReactiveValue: makeReactive\n };\n inner.set(makeReactive as any, reactiveContext);\n }\n \n // Delegate to the cache which will return an existing proxy for the target\n // or create one if it doesn't exist yet.\n return ReactiveProxyCache.getOrCreateProxy(obj, reactiveContext, isArray);\n }\n \n /**\n * Mark an object as a proxy (for optimization)\n */\n static markAsProxy(obj: any): void {\n if (!obj) return;\n\n // Prefer adding the actual proxy instance to the WeakSet which does not trigger proxy traps\n try {\n proxiedObjects.add(obj);\n } catch {\n // ignore\n }\n }\n}\n\nexport { ReactiveProxyCache, ProxyOptimizer };","import { scheduleDOMUpdate } from \"./scheduler\";\nimport { ProxyOptimizer } from \"./reactive-proxy-cache\";\nimport { devWarn } from \"./logger\";\n\n/**\n * Global reactive system for tracking dependencies and triggering updates\n */\nclass ReactiveSystem {\n private currentComponent: string | null = null;\n // Consolidated component data: stores dependencies, render function, state index, and last warning time\n private componentData = new Map<string, {\n dependencies: Set<ReactiveState<any>>;\n renderFn: () => void;\n stateIndex: number;\n lastWarnTime: number;\n }>();\n // Flat storage: compound key `${componentId}:${stateIndex}` -> ReactiveState\n private stateStorage = new Map<string, ReactiveState<any>>();\n private trackingDisabled = false;\n\n /**\n * Set the current component being rendered for dependency tracking\n */\n setCurrentComponent(componentId: string, renderFn: () => void): void {\n this.currentComponent = componentId;\n if (!this.componentData.has(componentId)) {\n this.componentData.set(componentId, {\n dependencies: new Set(),\n renderFn,\n stateIndex: 0,\n lastWarnTime: 0,\n });\n } else {\n const data = this.componentData.get(componentId)!;\n data.renderFn = renderFn;\n data.stateIndex = 0; // Reset state index for this render\n }\n }\n\n /**\n * Clear the current component after rendering\n */\n clearCurrentComponent(): void {\n this.currentComponent = null;\n }\n\n /**\n * Temporarily disable dependency tracking\n */\n disableTracking(): void {\n this.trackingDisabled = true;\n }\n\n /**\n * Re-enable dependency tracking\n */\n enableTracking(): void {\n this.trackingDisabled = false;\n }\n\n /**\n * Check if a component is currently rendering\n */\n isRenderingComponent(): boolean {\n return this.currentComponent !== null;\n }\n\n /**\n * Return whether we should emit a render-time warning for the current component.\n * This throttles warnings to avoid spamming the console for legitimate rapid updates.\n */\n shouldEmitRenderWarning(): boolean {\n if (!this.currentComponent) return true;\n const data = this.componentData.get(this.currentComponent);\n if (!data) return true;\n \n const now = Date.now();\n const THROTTLE_MS = 1000; // 1 second per component\n if (now - data.lastWarnTime < THROTTLE_MS) return false;\n \n data.lastWarnTime = now;\n return true;\n }\n\n /**\n * Execute a function with tracking disabled\n */\n withoutTracking<T>(fn: () => T): T {\n const wasDisabled = this.trackingDisabled;\n this.trackingDisabled = true;\n try {\n return fn();\n } finally {\n this.trackingDisabled = wasDisabled;\n }\n }\n\n /**\n * Get or create a state instance for the current component\n */\n getOrCreateState<T>(initialValue: T): ReactiveState<T> {\n if (!this.currentComponent) {\n return new ReactiveState(initialValue);\n }\n \n const data = this.componentData.get(this.currentComponent);\n if (!data) {\n return new ReactiveState(initialValue);\n }\n\n const stateKey = `${this.currentComponent}:${data.stateIndex++}`;\n let state = this.stateStorage.get(stateKey) as ReactiveState<T> | undefined;\n \n if (!state) {\n state = new ReactiveState(initialValue);\n this.stateStorage.set(stateKey, state);\n }\n \n return state;\n }\n\n /**\n * Track a dependency for the current component\n */\n trackDependency(state: ReactiveState<any>): void {\n if (this.trackingDisabled || !this.currentComponent) return;\n \n const data = this.componentData.get(this.currentComponent);\n if (data) {\n data.dependencies.add(state);\n state.addDependent(this.currentComponent);\n }\n }\n\n /**\n * Trigger updates for all components that depend on a state\n */\n triggerUpdate(state: ReactiveState<any>): void {\n const deps = state.getDependents();\n for (const componentId of deps) {\n const data = this.componentData.get(componentId);\n if (data) {\n scheduleDOMUpdate(data.renderFn, componentId);\n }\n }\n }\n\n /**\n * Clean up component dependencies when component is destroyed\n */\n cleanup(componentId: string): void {\n const data = this.componentData.get(componentId);\n if (data) {\n for (const state of data.dependencies) {\n state.removeDependent(componentId);\n }\n this.componentData.delete(componentId);\n }\n // Remove any flat-stored state keys for this component\n const prefix = componentId + ':';\n for (const key of this.stateStorage.keys()) {\n if (key.startsWith(prefix)) {\n this.stateStorage.delete(key);\n }\n }\n }\n}\n\nconst reactiveSystem = new ReactiveSystem();\n\n// Export for internal use\nexport { reactiveSystem };\n\n/**\n * Internal reactive state class\n */\nexport class ReactiveState<T> {\n private _value: T;\n private dependents = new Set<string>();\n\n constructor(initialValue: T) {\n this._value = this.makeReactive(initialValue);\n // Mark instances with a stable cross-bundle symbol so other modules\n // can reliably detect ReactiveState objects even when classes are\n // renamed/minified or when multiple copies of the package exist.\n try {\n // Use a global symbol key to make it resilient across realms/bundles\n const key = Symbol.for('@cer/ReactiveState');\n Object.defineProperty(this, key, { value: true, enumerable: false, configurable: false });\n } catch (e) {\n // ignore if Symbol.for or defineProperty fails in exotic runtimes\n }\n }\n\n get value(): T {\n // Track this state as a dependency when accessed during render\n reactiveSystem.trackDependency(this);\n return this._value;\n }\n\n set value(newValue: T) {\n // Check for state modifications during render (potential infinite loop)\n if (reactiveSystem.isRenderingComponent()) {\n if (reactiveSystem.shouldEmitRenderWarning()) {\n devWarn(\n '🚨 State modification detected during render! This can cause infinite loops.\\n' +\n ' • Move state updates to event handlers\\n' +\n ' • Use useEffect/watch for side effects\\n' +\n ' • Ensure computed properties don\\'t modify state'\n );\n }\n }\n \n this._value = this.makeReactive(newValue);\n // Trigger updates for all dependent components\n reactiveSystem.triggerUpdate(this);\n }\n\n addDependent(componentId: string): void {\n this.dependents.add(componentId);\n }\n\n removeDependent(componentId: string): void {\n this.dependents.delete(componentId);\n }\n\n getDependents(): Set<string> {\n return this.dependents;\n }\n\n private makeReactive(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Skip reactivity for DOM nodes - they should not be made reactive\n if (obj instanceof Node || obj instanceof Element || obj instanceof HTMLElement) {\n return obj;\n }\n\n // Use optimized proxy creation\n return ProxyOptimizer.createReactiveProxy(\n obj,\n () => reactiveSystem.triggerUpdate(this),\n (value: any) => this.makeReactive(value)\n );\n }\n}\n\n/**\n * Create reactive state that automatically triggers component re-renders\n * when accessed during render and modified afterwards.\n * Defaults to null if no initial value is provided (Vue-style ref).\n * \n * @example\n * ```ts\n * const counter = ref(0);\n * const user = ref({ name: 'John', age: 30 });\n * const emptyRef = ref(); // defaults to null\n * \n * // Usage in component\n * counter.value++; // triggers re-render\n * user.value.name = 'Jane'; // triggers re-render\n * console.log(emptyRef.value); // null\n * ```\n */\nexport function ref<T = null>(initialValue?: T): ReactiveState<T extends undefined ? null : T> {\n return reactiveSystem.getOrCreateState(initialValue === undefined ? null as any : initialValue);\n}\n\n/**\n * Type guard to detect ReactiveState instances in a robust way that works\n * across bundlers, minifiers, and multiple package copies.\n */\nexport function isReactiveState(v: any): v is ReactiveState<any> {\n if (!v || typeof v !== 'object') return false;\n try {\n const key = Symbol.for('@cer/ReactiveState');\n return !!v[key];\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Create computed state that derives from other reactive state\n * \n * @example\n * ```ts\n * const firstName = ref('John');\n * const lastName = ref('Doe');\n * const fullName = computed(() => `${firstName.value} ${lastName.value}`);\n * ```\n */\nexport function computed<T>(fn: () => T): { readonly value: T } {\n const computedState = new ReactiveState(fn());\n \n // We need to track dependencies when the computed function runs\n // For now, we'll re-evaluate on every access (can be optimized later)\n return {\n get value(): T {\n reactiveSystem.trackDependency(computedState as any);\n return fn();\n }\n };\n}\n\n/**\n * Create a watcher that runs when dependencies change\n * \n * @example\n * ```ts\n * const count = ref(0);\n * watch(() => count.value, (newVal, oldVal) => {\n * console.log(`Count changed from ${oldVal} to ${newVal}`);\n * });\n * ```\n */\nexport function watch<T>(\n source: () => T,\n callback: (newValue: T, oldValue: T) => void,\n options: { immediate?: boolean } = {}\n): () => void {\n let oldValue = source();\n \n if (options.immediate) {\n callback(oldValue, oldValue);\n }\n\n // Create a dummy component to track dependencies\n const watcherId = `watch-${Math.random().toString(36).substr(2, 9)}`;\n \n const updateWatcher = () => {\n reactiveSystem.setCurrentComponent(watcherId, updateWatcher);\n const newValue = source();\n reactiveSystem.clearCurrentComponent();\n \n if (newValue !== oldValue) {\n callback(newValue, oldValue);\n oldValue = newValue;\n }\n };\n\n // Initial run to establish dependencies\n reactiveSystem.setCurrentComponent(watcherId, updateWatcher);\n source();\n reactiveSystem.clearCurrentComponent();\n\n // Return cleanup function\n return () => {\n reactiveSystem.cleanup(watcherId);\n };\n}\n","/**\n * Safe execution helper - silently ignores errors\n */\nexport const safe = (fn: () => void): void => {\n try {\n fn();\n } catch {}\n};\n\nimport { isReactiveState } from \"./reactive\";\nimport { devWarn } from \"./logger\";\n\n// Caches for string transformations to improve performance\nconst KEBAB_CASE_CACHE = new Map<string, string>();\nconst CAMEL_CASE_CACHE = new Map<string, string>();\nconst HTML_ESCAPE_CACHE = new Map<string, string>();\n\n// Cache size limits to prevent memory bloat\nconst MAX_CACHE_SIZE = 500;\n\n// Module-level state for entity map and loader. Using module-level vars avoids\n// reliance on attaching properties to functions which can be brittle when\n// minifiers are configured to mangle properties.\nlet _namedEntityMap: Record<string, string> | undefined;\nlet _namedEntityMapLoader: (() => Promise<Record<string, string>>) | undefined;\nlet _usedEntityFallback = false;\nlet _warnedEntityFallback = false;\n// Module-level decode element used in browser environments to avoid attaching\n// an element to the function object (function properties can be mangled by\n// aggressive minifiers). Keep a function-attached reference only for backward\n// compatibility but prefer `_decodeEl` at runtime.\nlet _decodeEl: HTMLDivElement | undefined;\n// NOTE (internal): The runtime prefers module-level state for the entity map\n// and decode element to ensure minifier-safe behavior in production builds.\n// We intentionally retain assignments to function-attached properties in a\n// few places solely for backward compatibility with older tests and code\n// paths. New code should rely on `registerEntityMap`, `loadEntityMap`, and\n// the exported `decodeEntities` function rather than inspecting internal\n// function properties.\n// Use globalThis to avoid TypeScript requiring Node typings for `process`.\nconst _isNode = !!(\n (globalThis as any).process &&\n (globalThis as any).process.versions &&\n (globalThis as any).process.versions.node\n);\n\n/**\n * Convert camelCase to kebab-case with caching\n */\nexport function toKebab(str: string): string {\n if (KEBAB_CASE_CACHE.has(str)) {\n return KEBAB_CASE_CACHE.get(str)!;\n }\n\n const result = str.replace(/([a-z])([A-Z])/g, \"$1-$2\").toLowerCase();\n\n // Prevent memory bloat with size limit\n if (KEBAB_CASE_CACHE.size < MAX_CACHE_SIZE) {\n KEBAB_CASE_CACHE.set(str, result);\n }\n\n return result;\n}\n\n/**\n * Convert kebab-case to camelCase with caching\n */\nexport function toCamel(str: string): string {\n if (CAMEL_CASE_CACHE.has(str)) {\n return CAMEL_CASE_CACHE.get(str)!;\n }\n\n const result = str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n\n if (CAMEL_CASE_CACHE.size < MAX_CACHE_SIZE) {\n CAMEL_CASE_CACHE.set(str, result);\n }\n\n return result;\n}\n\n/**\n * Clear string transformation caches (useful for testing)\n */\nexport function clearStringCaches(): void {\n KEBAB_CASE_CACHE.clear();\n CAMEL_CASE_CACHE.clear();\n HTML_ESCAPE_CACHE.clear();\n}\n\n/**\n * Get cache statistics for debugging\n */\nexport function getStringCacheStats(): {\n kebabCacheSize: number;\n camelCacheSize: number;\n htmlEscapeCacheSize: number;\n} {\n return {\n kebabCacheSize: KEBAB_CASE_CACHE.size,\n camelCacheSize: CAMEL_CASE_CACHE.size,\n htmlEscapeCacheSize: HTML_ESCAPE_CACHE.size,\n };\n}\n\nexport function escapeHTML(\n str: string | number | boolean\n): string | number | boolean {\n if (typeof str === \"string\") {\n // Check cache first for frequently escaped strings\n if (HTML_ESCAPE_CACHE.has(str)) {\n return HTML_ESCAPE_CACHE.get(str)!;\n }\n\n const result = str.replace(\n /[&<>\"']/g,\n (c) =>\n ({\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n }[c]!)\n );\n\n // Only cache strings that contain entities to escape\n if (result !== str && HTML_ESCAPE_CACHE.size < MAX_CACHE_SIZE) {\n HTML_ESCAPE_CACHE.set(str, result);\n }\n\n return result;\n }\n return str;\n}\n\n/**\n * Decode HTML entities (named and numeric) into their character equivalents.\n * - In browser: uses a DOM-based technique to decode entities while preserving\n * existing raw tags.\n * - In non-DOM (SSR) environments: handles numeric references and a conservative\n * named-entity map for common entities.\n *\n * @param str - string containing HTML entities\n * @returns decoded string\n */\nexport function decodeEntities(str: string): string {\n if (!str) return \"\";\n const s = String(str);\n\n // Browser environment: use a DOM element to decode the full set of named entities.\n if (\n typeof document !== \"undefined\" &&\n typeof document.createElement === \"function\"\n ) {\n const SENTINEL_L = \"\\uF000\";\n const SENTINEL_G = \"\\uF001\";\n // Protect existing literal tags so they won't be parsed as HTML by innerHTML\n const protectedStr = s.replace(/</g, SENTINEL_L).replace(/>/g, SENTINEL_G);\n\n // Prefer module-level el to avoid relying on function-attached properties\n // which can be renamed/mangled by some minifiers. Keep function-attached\n // `_el` for backward compatibility but do not depend on it.\n const el = _decodeEl || (_decodeEl = document.createElement(\"div\"));\n try {\n (decodeEntities as any)._el = el;\n } catch {}\n\n el.innerHTML = protectedStr;\n const decoded = el.textContent || \"\";\n return decoded\n .replace(new RegExp(SENTINEL_L, \"g\"), \"<\")\n .replace(new RegExp(SENTINEL_G, \"g\"), \">\");\n }\n\n // SSR / non-DOM fallback: handle numeric refs and named entities via an external JSON map.\n // Keep a tiny inline map for the most common entities so decodeEntities remains sync.\n const tinyMap: Record<string, string> = {\n lt: \"<\",\n gt: \">\",\n amp: \"&\",\n quot: '\"',\n apos: \"'\",\n nbsp: \"\\u00A0\",\n };\n\n // Prefer module-level registered map first (minifier-safe). Keep function\n // attached map as a fallback for backward compatibility only.\n const registered = _namedEntityMap ?? (decodeEntities as any)._namedMap;\n\n // Select map: module-level registered > function-attached registered > sync require (Node-only) > tinyMap.\n let namedMap: Record<string, string> | undefined = registered;\n\n if (!namedMap && _isNode) {\n // Try to synchronously require the JSON in Node-like environments without importing `require`.\n try {\n // Use globalThis to avoid referencing `require` directly (prevents TS needing node types)\n const maybeRequire = (globalThis as any).require;\n if (typeof maybeRequire === \"function\") {\n // Try several common require paths (installed package, dist layout, src layout)\n const candidates = [\n \"@jasonshimmy/custom-elements-runtime/entities.json\", // installed package export\n \"../../entities.json\", // dist/runtime -> ../../entities.json\n \"../../../entities.json\", // src/lib/runtime -> ../../../entities.json\n \"../entities.json\",\n \"./entities.json\",\n ];\n for (const p of candidates) {\n try {\n const m = maybeRequire(p);\n if (m) {\n namedMap = m;\n break;\n }\n } catch {}\n }\n }\n } catch {}\n }\n\n // If we still don't have a map, fall back to tinyMap and trigger background loader if present.\n if (!namedMap) {\n namedMap = tinyMap;\n // Keep both module and function-level flags in sync for backward compatibility.\n // Mark fallback usage primarily on module-level flags (minifier-safe).\n _usedEntityFallback = true;\n try {\n (decodeEntities as any)._usedFallback = true;\n } catch {}\n const loader =\n (decodeEntities as any)._namedMapLoader ?? _namedEntityMapLoader;\n if (loader) {\n // Load asynchronously; when ready, cache it for future sync calls and sync to function props.\n loader()\n .then((m: Record<string, string>) => {\n _namedEntityMap = m;\n try {\n (decodeEntities as any)._namedMap = m;\n } catch {}\n })\n .catch(() => {});\n }\n }\n\n // Emit a one-time dev warning if we used the tiny fallback.\n // Prefer module-level flags first, then function-attached fallbacks for\n // backward compatibility. This avoids depending on function property names\n // which some minifiers may mangle.\n if (\n (_usedEntityFallback || (decodeEntities as any)._usedFallback) &&\n !(_warnedEntityFallback || (decodeEntities as any)._warnedFallback)\n ) {\n _warnedEntityFallback = true;\n try {\n (decodeEntities as any)._warnedFallback = true;\n } catch {}\n try {\n devWarn(\n \"decodeEntities: using small SSR fallback entity map. Register the full entities.json via registerEntityMap(entities) on the server to enable full HTML5 named-entity decoding.\"\n );\n } catch {}\n }\n\n // Replace entities: numeric (hex/dec) or named.\n return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (_, entity) => {\n if (entity.charCodeAt(0) === 35) {\n // '#'\n const isHex = (entity.charAt(1) || \"\").toLowerCase() === \"x\";\n const num = isHex\n ? parseInt(entity.slice(2), 16)\n : parseInt(entity.slice(1), 10);\n return Number.isNaN(num) ? `&${entity};` : String.fromCodePoint(num);\n }\n const mapped =\n (namedMap as any)[entity] ?? (registered && registered[entity]);\n return mapped !== undefined ? mapped : `&${entity};`;\n });\n}\n\n/**\n * Dynamically load the full named-entity map (used in SSR). Exported for testing and\n * to allow bundlers to exclude the JSON from client bundles when dynamic import\n * is used behind a DOM check.\n */\nexport async function loadEntityMap(): Promise<Record<string, string>> {\n // Prefer dynamic import so bundlers can code-split or ignore this file for browser bundles.\n // Try the published package export first; in installed packages this is usually the most\n // reliable path. Make the specifier a runtime string to discourage bundlers from inlining.\n const pkgExport = [\n \"@jasonshimmy\",\n \"custom-elements-runtime\",\n \"entities.json\",\n ].join(\"/\");\n try {\n // @vite-ignore: dynamic import specifier constructed at runtime\n const mPkg = await import(/* @vite-ignore */ pkgExport as any);\n return (mPkg && (mPkg.default || mPkg)) as Record<string, string>;\n } catch {\n // Next try relative local JSON (useful during development or mono-repo installs)\n try {\n // Try several reasonable local import paths (development vs built layouts)\n const localCandidates = [\n pkgExport, // try package export via dynamic import too (best for installed packages)\n \"./entities.json\",\n \"../../entities.json\",\n \"../../../entities.json\",\n ];\n for (const p of localCandidates) {\n try {\n // @vite-ignore: intentionally dynamic path candidates for dev/local resolution\n const mLocal = await import(/* @vite-ignore */ p as any);\n if (mLocal)\n return (mLocal && (mLocal.default || mLocal)) as Record<\n string,\n string\n >;\n } catch {}\n }\n // If none of the dynamic imports succeeded, fall back to the small map.\n return {\n lt: \"<\",\n gt: \">\",\n amp: \"&\",\n quot: '\"',\n apos: \"'\",\n nbsp: \"\\u00A0\",\n };\n } catch {\n // Final small fallback\n return {\n lt: \"<\",\n gt: \">\",\n amp: \"&\",\n quot: '\"',\n apos: \"'\",\n nbsp: \"\\u00A0\",\n };\n }\n }\n}\n\n// Attach loader to module state and (for backward compatibility) to the function\n// as well. Using module-level state avoids property-mangling risks in minified\n// builds; attaching to the function keeps tests that reference the property\n// working until they can be updated.\n_namedEntityMapLoader = loadEntityMap;\n(decodeEntities as any)._namedMapLoader = loadEntityMap;\n\n/**\n * Register a full named-entity map for SSR. Intended for server startup code to\n * provide the authoritative HTML5 entity mapping. This keeps the client bundle\n * small because the map is only injected on the server side.\n *\n * registerEntityMap should be called once at server startup prior to rendering.\n */\nexport function registerEntityMap(\n map: Record<string, string>,\n options?: { overwrite?: boolean }\n): void {\n if (!map || typeof map !== \"object\") return;\n const existing = _namedEntityMap;\n if (existing && !options?.overwrite) return; // first registration wins by default\n _namedEntityMap = map;\n}\n\n/**\n * Clear any registered entity map. Useful for tests or restarting state.\n */\nexport function clearRegisteredEntityMap(): void {\n _namedEntityMap = undefined;\n}\n\n/**\n * Wrap a string as raw HTML. This is intentionally unsafe — callers must\n * sanitize untrusted input before using this. The returned object provides\n * two property names to be compatible with different parts of the runtime.\n */\nexport function unsafeHTML(html: string): {\n __unsafeHTML: string;\n __rawHTML: string;\n} {\n const s = String(html);\n // Provide both property names to be compatible with compiler/renderer expectations\n return { __unsafeHTML: s, __rawHTML: s };\n}\n\n/** Type-guard for unsafeHTML wrapper */\nexport function isUnsafeHTML(\n value: unknown\n): value is { __unsafeHTML?: string; __rawHTML?: string } {\n return (\n !!value &&\n (typeof (value as any).__unsafeHTML === \"string\" ||\n typeof (value as any).__rawHTML === \"string\")\n );\n}\n\n/**\n * Get nested property value from object using dot notation\n */\nexport function getNestedValue(obj: any, path: string): any {\n if (typeof path === \"string\") {\n const result = path\n .split(\".\")\n .reduce((current, key) => current?.[key], obj);\n // If the result is a ReactiveState object, return its value\n if (isReactiveState(result)) {\n return result.value;\n }\n return result;\n }\n return path;\n}\n\n/**\n * Set nested property value in object using dot notation\n */\nexport function setNestedValue(obj: any, path: string, value: any): void {\n const keys = String(path).split(\".\");\n const lastKey = keys.pop();\n if (!lastKey) return;\n const target = keys.reduce((current: any, key: string) => {\n if (current[key] == null) current[key] = {};\n return current[key];\n }, obj);\n\n // If target[lastKey] is a ReactiveState object, set its value property\n if (isReactiveState(target[lastKey])) {\n target[lastKey].value = value;\n } else {\n target[lastKey] = value;\n }\n}\n\n/**\n * Safely unwrap reactive-like wrappers to their inner primitive when safe.\n * Returns the original value when it's not safe to coerce to a primitive.\n */\nexport function unwrapIfPrimitive(v: any): any {\n try {\n if (v && typeof v === \"object\") {\n if (isReactiveState(v)) return (v as any).value;\n if (\"value\" in v) {\n const maybe = (v as any).value;\n // Only return primitive inner values; otherwise return original\n if (\n maybe === null ||\n maybe === undefined ||\n typeof maybe === \"string\" ||\n typeof maybe === \"number\" ||\n typeof maybe === \"boolean\"\n ) {\n return maybe;\n }\n return v;\n }\n }\n } catch (e) {}\n return v;\n}\n\n/**\n * Return a serialized string for an attribute value when safe to write to DOM.\n * Returns `null` when the value should not be written as an attribute.\n */\nexport function safeSerializeAttr(val: any): string | null {\n const v = unwrapIfPrimitive(val);\n if (v === null || v === undefined) return null;\n const t = typeof v;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") return String(v);\n return null; // complex objects, nodes, functions -> do not serialize\n}\n\n/**\n * Determine if an attribute name is class-like and should be preserved on hosts.\n * Class-like: exactly 'class', camelCase ending with 'Class', or kebab-case ending with '-class'.\n */\nexport function isClassLikeAttr(name: string): boolean {\n if (!name || typeof name !== \"string\") return false;\n if (name === \"class\") return true;\n if (name.endsWith(\"Class\")) return true;\n // Kebab-case: consider attributes where one of the hyphen-separated tokens is 'class'\n if (name.includes(\"-\")) {\n try {\n const parts = name.split(\"-\");\n if (parts.some((p) => p === \"class\")) return true;\n } catch (e) {\n // fallthrough\n }\n }\n return false;\n}\n","import type { ComponentContext, WatchCallback, WatchOptions, WatcherState } from \"./types\";\nimport { getNestedValue } from \"./helpers\";\nimport { devError } from \"./logger\";\n\n/**\n * Initializes watchers for a component.\n */\nexport function initWatchers(\n context: ComponentContext<any, any, any, any>,\n watchers: Map<string, WatcherState>,\n watchConfig: Record<string, WatchCallback | [WatchCallback, WatchOptions]>\n): void {\n if (!watchConfig) return;\n\n for (const [key, config] of Object.entries(watchConfig)) {\n let callback: WatchCallback;\n let options: WatchOptions = {};\n\n if (Array.isArray(config)) {\n callback = config[0];\n options = config[1] || {};\n } else {\n callback = config;\n }\n\n watchers.set(key, {\n callback,\n options,\n oldValue: getNestedValue(context, key),\n });\n\n if (options.immediate) {\n try {\n const currentValue = getNestedValue(context, key);\n callback(currentValue, undefined, context);\n } catch (error) {\n devError(`Error in immediate watcher for \"${key}\":`, error);\n }\n }\n }\n}\n\n/**\n * Triggers watchers when state changes.\n */\nexport function triggerWatchers(\n context: ComponentContext<any, any, any, any>,\n watchers: Map<string, WatcherState>,\n path: string,\n newValue: any\n): void {\n const isEqual = (a: any, b: any): boolean => {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((val, i) => isEqual(val, b[i]));\n }\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every(key => isEqual(a[key], b[key]));\n };\n\n const watcher = watchers.get(path);\n if (watcher && !isEqual(newValue, watcher.oldValue)) {\n try {\n watcher.callback(newValue, watcher.oldValue, context);\n watcher.oldValue = newValue;\n } catch (error) {\n devError(`Error in watcher for \"${path}\":`, error);\n }\n }\n\n for (const [watchPath, watcherConfig] of watchers.entries()) {\n if (watcherConfig.options.deep && path.startsWith(watchPath + \".\")) {\n try {\n const currentValue = getNestedValue(context, watchPath);\n if (!isEqual(currentValue, watcherConfig.oldValue)) {\n watcherConfig.callback(currentValue, watcherConfig.oldValue, context);\n watcherConfig.oldValue = currentValue;\n }\n } catch (error) {\n devError(`Error in deep watcher for \"${watchPath}\":`, error);\n }\n }\n }\n}\n","import { toKebab } from \"./helpers\";\nimport { isReactiveState } from \"./reactive\";\nimport type { ComponentConfig, ComponentContext } from \"./types\";\n\nexport type PropDefinition = {\n type:\n | StringConstructor\n | NumberConstructor\n | BooleanConstructor\n | FunctionConstructor;\n default?: string | number | boolean;\n};\n\nfunction parseProp(val: string, type: any) {\n if (type === Boolean) {\n // Standalone boolean attributes (e.g., <div disabled>) have empty string value\n // and should be treated as true. Explicit false is \"false\" string.\n return val === \"\" || val === \"true\";\n }\n if (type === Number) return Number(val);\n return val;\n}\n\n/**\n * Applies props to the component context using a direct prop definitions object.\n * @param element - The custom element instance.\n * @param propDefinitions - Object mapping prop names to their definitions.\n * @param context - The component context.\n */\nexport function applyPropsFromDefinitions(\n element: HTMLElement,\n propDefinitions: Record<string, PropDefinition>,\n context: any\n): void {\n if (!propDefinitions) return;\n\n for (const key in propDefinitions) {\n const def = propDefinitions[key];\n const kebab = toKebab(key);\n const attr = element.getAttribute(kebab);\n\n // Prefer function prop on the element instance\n if (def.type === Function && typeof (element as any)[key] === \"function\") {\n (context as any)[key] = (element as any)[key];\n } else {\n // Prefer HTML attribute when present (attributes should take precedence over default property values)\n if (attr !== null) {\n (context as any)[key] = parseProp(attr, def.type);\n } else if (typeof (element as any)[key] !== \"undefined\") {\n // Fall back to JS property value when present on the instance\n try {\n const propValue = (element as any)[key];\n // If the property value is already the correct type, use it directly\n // For string props, attempt to convert object-like host properties to string.\n // If conversion throws, preserve the original object value on the context\n if (\n def.type === String &&\n propValue &&\n typeof propValue === \"object\"\n ) {\n try {\n (context as any)[key] = parseProp(String(propValue), def.type);\n } catch (e) {\n // If conversion fails, fallback to assigning the original object value\n (context as any)[key] = propValue;\n }\n } else if (def.type === Boolean && typeof propValue === \"boolean\") {\n (context as any)[key] = propValue;\n } else if (def.type === Number && typeof propValue === \"number\") {\n (context as any)[key] = propValue;\n } else if (def.type === Function && typeof propValue === \"function\") {\n (context as any)[key] = propValue;\n } else {\n // Convert to string first, then parse\n (context as any)[key] = parseProp(String(propValue), def.type);\n }\n } catch (e) {\n (context as any)[key] = (element as any)[key];\n }\n } else if (\"default\" in def && def.default !== undefined) {\n (context as any)[key] = def.default;\n }\n // else: leave undefined if no default\n }\n }\n}\n\n/**\n * Legacy function for ComponentConfig compatibility.\n * Applies props to the component context using a ComponentConfig.\n * @param element - The custom element instance.\n * @param cfg - The component config.\n * @param context - The component context.\n */\nexport function applyProps<\n S extends object,\n C extends object,\n P extends object,\n T extends object\n>(\n element: HTMLElement,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>\n): void {\n if (!cfg.props) {\n // When there are no explicit prop definitions, define dynamic getters\n // on the component context for element properties. Also ensure getters\n // exist for props declared via useProps (context._hookCallbacks.props)\n // so components that call useProps see live host properties even if the\n // host hasn't created an own enumerable property yet.\n try {\n const declared =\n (context &&\n (context as any)._hookCallbacks &&\n (context as any)._hookCallbacks.props) ||\n {};\n const keys = Array.from(\n new Set([...Object.keys(element as any), ...Object.keys(declared)])\n );\n for (const key of keys) {\n // Skip internal/private fields and functions\n if (typeof key !== \"string\" || key.startsWith(\"_\")) continue;\n // Avoid overwriting existing descriptors on context\n const existing = Object.getOwnPropertyDescriptor(context, key);\n const isDeclaredProp = Object.prototype.hasOwnProperty.call(\n declared,\n key\n );\n // If it's a declared prop via useProps, allow overriding the context\n // property with a dynamic getter so the component sees live host\n // prop values. Otherwise, avoid replacing existing accessors.\n if (\n !isDeclaredProp &&\n existing &&\n (existing.get || existing.set || !existing.configurable)\n )\n continue;\n try {\n Object.defineProperty(context, key, {\n enumerable: true,\n configurable: true,\n get() {\n try {\n // Check for attribute value first (attributes should take precedence)\n const kebab = toKebab(key);\n const attr = element.getAttribute(kebab);\n if (attr !== null) {\n // Return attribute value if present\n return attr;\n }\n\n // Fall back to property value\n const hostVal = (element as any)[key];\n let ret;\n if (isReactiveState(hostVal)) ret = (hostVal as any).value;\n else if (\n hostVal &&\n typeof hostVal === \"object\" &&\n \"value\" in hostVal &&\n !(hostVal instanceof Node)\n )\n ret = (hostVal as any).value;\n else ret = hostVal;\n // intentionally silent in production/test runs\n return ret;\n } catch (e) {\n return (element as any)[key];\n }\n },\n });\n } catch (e) {\n // ignore assignment errors\n }\n }\n } catch (e) {\n // ignore\n }\n return;\n }\n applyPropsFromDefinitions(element, cfg.props, context);\n}\n","import type { ComponentConfig, ComponentContext } from \"./types\";\n\n/**\n * Handles the connected lifecycle hook.\n */\nexport function handleConnected<S extends object, C extends object, P extends object, T extends object>(\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n isMounted: boolean,\n setMounted: (val: boolean) => void\n): void {\n if (cfg.onConnected && !isMounted) {\n cfg.onConnected(context);\n setMounted(true);\n }\n}\n\n/**\n * Handles the disconnected lifecycle hook.\n */\nexport function handleDisconnected<S extends object, C extends object, P extends object, T extends object>(\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n listeners: Array<() => void>,\n clearListeners: () => void,\n clearWatchers: () => void,\n setTemplateLoading: (val: boolean) => void,\n setTemplateError: (err: Error | null) => void,\n setMounted: (val: boolean) => void\n): void {\n if (cfg.onDisconnected) cfg.onDisconnected(context);\n listeners.forEach(unsub => unsub());\n clearListeners();\n clearWatchers();\n setTemplateLoading(false);\n setTemplateError(null);\n setMounted(false);\n}\n\n/**\n * Handles the attribute changed lifecycle hook.\n */\nexport function handleAttributeChanged<S extends object, C extends object, P extends object, T extends object>(\n cfg: ComponentConfig<S, C, P, T>,\n name: string,\n oldValue: string | null,\n newValue: string | null,\n context: ComponentContext<S, C, P, T>\n): void {\n if (cfg.onAttributeChanged) {\n cfg.onAttributeChanged(name, oldValue, newValue, context);\n }\n}\n","/**\n * Secure expression evaluator to replace unsafe Function() constructor\n * Provides AST-based validation and caching for performance\n */\n\nimport { devWarn } from \"./logger\";\nimport { getNestedValue } from \"./helpers\";\n\ninterface ExpressionCache {\n evaluator: (context: any) => any;\n isSecure: boolean;\n}\n\n/**\n * Secure expression evaluator with caching and AST validation\n */\nclass SecureExpressionEvaluator {\n private static cache = new Map<string, ExpressionCache>();\n private static maxCacheSize = 1000;\n\n // Dangerous patterns to block\n private static dangerousPatterns = [\n /constructor/i,\n /prototype/i,\n /__proto__/i,\n /function/i,\n /eval/i,\n /import/i,\n /require/i,\n /window/i,\n /document/i,\n /global/i,\n /process/i,\n /setTimeout/i,\n /setInterval/i,\n /fetch/i,\n /XMLHttpRequest/i\n ];\n \n static evaluate(expression: string, context: any): any {\n // Check cache first\n const cached = this.cache.get(expression);\n if (cached) {\n if (!cached.isSecure) {\n devWarn('Blocked cached dangerous expression:', expression);\n return undefined;\n }\n return cached.evaluator(context);\n }\n \n // Create and cache evaluator\n const evaluator = this.createEvaluator(expression);\n \n // Manage cache size (LRU-style)\n if (this.cache.size >= this.maxCacheSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n this.cache.delete(firstKey);\n }\n }\n \n this.cache.set(expression, evaluator);\n \n if (!evaluator.isSecure) {\n devWarn('Blocked dangerous expression:', expression);\n return undefined;\n }\n \n return evaluator.evaluator(context);\n }\n \n private static createEvaluator(expression: string): ExpressionCache {\n // First, check for obviously dangerous patterns\n if (this.hasDangerousPatterns(expression)) {\n return { evaluator: () => undefined, isSecure: false };\n }\n \n // Size limit\n if (expression.length > 1000) {\n return { evaluator: () => undefined, isSecure: false };\n }\n \n // Try to create a safe evaluator\n try {\n const evaluator = this.createSafeEvaluator(expression);\n return { evaluator, isSecure: true };\n } catch (error) {\n devWarn('Failed to create evaluator for expression:', expression, error);\n return { evaluator: () => undefined, isSecure: false };\n }\n }\n \n private static hasDangerousPatterns(expression: string): boolean {\n return this.dangerousPatterns.some(pattern => pattern.test(expression));\n }\n \n private static createSafeEvaluator(expression: string): (context: any) => any {\n // Handle object literals like \"{ active: ctx.isActive, disabled: ctx.isDisabled }\"\n const trimmedExpr = expression.trim();\n if (trimmedExpr.startsWith('{') && trimmedExpr.endsWith('}')) {\n return this.createObjectEvaluator(expression);\n }\n \n // Handle simple property access when the entire expression is a single ctx.path\n if (/^ctx\\.[a-zA-Z0-9_\\.]+$/.test(expression.trim())) {\n const propertyPath = expression.trim().slice(4);\n return (context: any) => getNestedValue(context, propertyPath);\n }\n \n // If expression references `ctx` or contains operators/array/ternary\n // route it to the internal parser/evaluator which performs proper\n // token validation and evaluation. This is safer than over-restrictive\n // pre-validation and fixes cases like ternary, boolean logic, and arrays.\n if (expression.includes('ctx') || /[+\\-*/%<>=&|?:\\[\\]]/.test(expression)) {\n return this.createSimpleEvaluator(expression);\n }\n\n // Fallback to property lookup for plain property paths that don't\n // include ctx or operators (e.g. \"a.b\").\n return (context: any) => getNestedValue(context, expression);\n }\n \n private static createObjectEvaluator(expression: string): (context: any) => any {\n // Parse object literal safely\n const objectContent = expression.trim().slice(1, -1); // Remove { }\n const properties = this.parseObjectProperties(objectContent);\n \n return (context: any) => {\n const result: Record<string, any> = {};\n \n for (const { key, value } of properties) {\n try {\n if (value.startsWith('ctx.')) {\n const propertyPath = value.slice(4);\n result[key] = getNestedValue(context, propertyPath);\n } else {\n // Try to evaluate as a simple expression\n result[key] = this.evaluateSimpleValue(value, context);\n }\n } catch (error) {\n result[key] = undefined;\n }\n }\n \n return result;\n };\n }\n \n private static parseObjectProperties(content: string): Array<{ key: string; value: string }> {\n const properties: Array<{ key: string; value: string }> = [];\n const parts = content.split(',');\n \n for (const part of parts) {\n const colonIndex = part.indexOf(':');\n if (colonIndex === -1) continue;\n \n const key = part.slice(0, colonIndex).trim();\n const value = part.slice(colonIndex + 1).trim();\n \n // Remove quotes from key if present\n const cleanKey = key.replace(/^['\"]|['\"]$/g, '');\n \n properties.push({ key: cleanKey, value });\n }\n \n return properties;\n }\n\n private static createSimpleEvaluator(expression: string): (context: any) => any {\n // For simple expressions, we'll use a basic substitution approach\n return (context: any) => {\n try {\n // Work on a copy we can mutate\n let processedExpression = expression;\n\n // First, replace all string literals with placeholders to avoid accidental identifier matches inside strings\n const stringLiterals: string[] = [];\n processedExpression = processedExpression.replace(/(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*')/g, (m) => {\n const idx = stringLiterals.push(m) - 1;\n // Use numeric-only markers so identifier regex won't match them (they don't start with a letter)\n return `<<#${idx}#>>`;\n });\n\n // Replace ctx.property references with placeholders to avoid creating new string/number\n // literals that the identifier scanner could accidentally pick up. Use processedExpression\n // (with string literals already removed) so we don't match ctx occurrences inside strings.\n const ctxMatches = processedExpression.match(/ctx\\.[\\w.]+/g) || [];\n for (const match of ctxMatches) {\n const propertyPath = match.slice(4); // Remove 'ctx.'\n const value = getNestedValue(context, propertyPath);\n if (value === undefined) return undefined; // unknown ctx property => undefined result\n const placeholderIndex = stringLiterals.push(JSON.stringify(value)) - 1;\n processedExpression = processedExpression.replace(new RegExp(match.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'), `<<#${placeholderIndex}#>>`);\n }\n\n // Replace dotted plain identifiers (e.g. user.age) before single-token identifiers.\n // The earlier ident regex uses word boundaries which split dotted identifiers, so\n // we must handle full dotted sequences first.\n const dottedRegex = /\\b[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)+\\b/g;\n const dottedMatches = processedExpression.match(dottedRegex) || [];\n for (const match of dottedMatches) {\n // Skip ctx.* since those were handled above\n if (match.startsWith('ctx.')) continue;\n const value = getNestedValue(context, match);\n if (value === undefined) return undefined;\n const placeholderIndex = stringLiterals.push(JSON.stringify(value)) - 1;\n processedExpression = processedExpression.replace(new RegExp(match.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'), `<<#${placeholderIndex}#>>`);\n }\n\n // Also support plain identifiers (root-level variables like `a`) when present.\n // Find identifiers (excluding keywords true/false/null) and replace them with values from context.\n // Note: dotted identifiers were handled above, so this regex intentionally excludes dots.\n const identRegex = /\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b/g;\n let m: RegExpExecArray | null;\n const seen: Set<string> = new Set();\n while ((m = identRegex.exec(processedExpression)) !== null) {\n const ident = m[1];\n if (['true','false','null','undefined'].includes(ident)) continue;\n // skip numeric-like (though regex shouldn't match numbers)\n if (/^[0-9]+$/.test(ident)) continue;\n // skip 'ctx' itself\n if (ident === 'ctx') continue;\n // Avoid re-processing same identifier\n if (seen.has(ident)) continue;\n seen.add(ident);\n\n // If identifier contains '.' try nested lookup\n const value = getNestedValue(context, ident);\n if (value === undefined) return undefined; // unknown identifier => undefined\n // Use a placeholder for the substituted value so we don't introduce new identifiers inside\n // quotes that could be matched by the ident regex.\n const repl = JSON.stringify(value);\n const placeholderIndex = stringLiterals.push(repl) - 1;\n if (ident.includes('.')) {\n // dotted identifiers contain '.' which is non-word; do a plain replace\n processedExpression = processedExpression.replace(new RegExp(ident.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'), `<<#${placeholderIndex}#>>`);\n } else {\n processedExpression = processedExpression.replace(new RegExp('\\\\b' + ident.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') + '\\\\b', 'g'), `<<#${placeholderIndex}#>>`);\n }\n }\n\n // Restore string literals\n processedExpression = processedExpression.replace(/<<#(\\d+)#>>/g, (_: string, idx: string) => stringLiterals[Number(idx)]);\n\n // Try to evaluate using the internal parser/evaluator which performs strict token validation.\n try {\n return this.evaluateBasicExpression(processedExpression);\n } catch (err) {\n return undefined;\n }\n } catch (error) {\n return undefined;\n }\n };\n }\n\n /**\n * Evaluate a very small, safe expression grammar without using eval/Function.\n * Supports: numbers, string literals, true/false, null, arrays, unary !,\n * arithmetic (+ - * / %), comparisons, logical && and ||, parentheses, and ternary `a ? b : c`.\n */\n private static evaluateBasicExpression(expr: string): any {\n const tokens = this.tokenize(expr);\n let pos = 0;\n\n function peek(): any {\n return tokens[pos];\n }\n function consume(expected?: string): any {\n const t = tokens[pos++];\n if (expected && !t) {\n throw new Error(`Unexpected token EOF, expected ${expected}`);\n }\n if (expected && t) {\n // Allow matching by token type (e.g. 'OP', 'NUMBER') or by exact token value (e.g. '?', ':')\n if (t.type !== expected && t.value !== expected) {\n throw new Error(`Unexpected token ${t.type}/${t.value}, expected ${expected}`);\n }\n }\n return t;\n }\n\n // Grammar (precedence):\n // expression := ternary\n // ternary := logical_or ( '?' expression ':' expression )?\n // logical_or := logical_and ( '||' logical_and )*\n // logical_and := equality ( '&&' equality )*\n // equality := comparison ( ('==' | '!=' | '===' | '!==') comparison )*\n // comparison := additive ( ('>' | '<' | '>=' | '<=') additive )*\n // additive := multiplicative ( ('+'|'-') multiplicative )*\n // multiplicative := unary ( ('*'|'/'|'%') unary )*\n // unary := ('!' | '-') unary | primary\n // primary := number | string | true | false | null | array | '(' expression ')'\n\n function parseExpression(): any {\n return parseTernary();\n }\n\n function parseTernary(): any {\n let cond = parseLogicalOr();\n if (peek() && peek().value === '?') {\n consume('?');\n const thenExpr = parseExpression();\n consume(':');\n const elseExpr = parseExpression();\n return cond ? thenExpr : elseExpr;\n }\n return cond;\n }\n\n function parseLogicalOr(): any {\n let left = parseLogicalAnd();\n while (peek() && peek().value === '||') {\n consume('OP');\n const right = parseLogicalAnd();\n left = left || right;\n }\n return left;\n }\n\n function parseLogicalAnd(): any {\n let left = parseEquality();\n while (peek() && peek().value === '&&') {\n consume('OP');\n const right = parseEquality();\n left = left && right;\n }\n return left;\n }\n\n function parseEquality(): any {\n let left = parseComparison();\n while (peek() && ['==','!=','===','!=='].includes(peek().value)) {\n const op = consume('OP').value;\n const right = parseComparison();\n switch (op) {\n case '==': left = left == right; break;\n case '!=': left = left != right; break;\n case '===': left = left === right; break;\n case '!==': left = left !== right; break;\n }\n }\n return left;\n }\n\n function parseComparison(): any {\n let left = parseAdditive();\n while (peek() && ['>','<','>=','<='].includes(peek().value)) {\n const op = consume('OP').value;\n const right = parseAdditive();\n switch (op) {\n case '>': left = left > right; break;\n case '<': left = left < right; break;\n case '>=': left = left >= right; break;\n case '<=': left = left <= right; break;\n }\n }\n return left;\n }\n\n function parseAdditive(): any {\n let left = parseMultiplicative();\n while (peek() && (peek().value === '+' || peek().value === '-')) {\n const op = consume('OP').value;\n const right = parseMultiplicative();\n left = op === '+' ? left + right : left - right;\n }\n return left;\n }\n\n function parseMultiplicative(): any {\n let left = parseUnary();\n while (peek() && (peek().value === '*' || peek().value === '/' || peek().value === '%')) {\n const op = consume('OP').value;\n const right = parseUnary();\n switch (op) {\n case '*': left = left * right; break;\n case '/': left = left / right; break;\n case '%': left = left % right; break;\n }\n }\n return left;\n }\n\n function parseUnary(): any {\n if (peek() && peek().value === '!') {\n consume('OP');\n return !parseUnary();\n }\n if (peek() && peek().value === '-') {\n consume('OP');\n return -parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): any {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'NUMBER') {\n consume('NUMBER');\n return Number(t.value);\n }\n if (t.type === 'STRING') {\n consume('STRING');\n // strip quotes\n return t.value.slice(1, -1);\n }\n if (t.type === 'IDENT') {\n consume('IDENT');\n if (t.value === 'true') return true;\n if (t.value === 'false') return false;\n if (t.value === 'null') return null;\n // fallback: try parse as JSON-ish literal or undefined\n return undefined;\n }\n if (t.value === '[') {\n consume('PUNC');\n const arr: any[] = [];\n while (peek() && peek().value !== ']') {\n arr.push(parseExpression());\n if (peek() && peek().value === ',') consume('PUNC');\n }\n consume('PUNC'); // ]\n return arr;\n }\n if (t.value === '(') {\n consume('PUNC');\n const v = parseExpression();\n consume('PUNC'); // )\n return v;\n }\n // Unknown primary\n throw new Error('Unexpected token in expression');\n }\n\n const result = parseExpression();\n return result;\n }\n\n private static tokenize(input: string): Array<{ type: string; value: string }> {\n const tokens: Array<{ type: string; value: string }> = [];\n const re = /\\s*(=>|===|!==|==|!=|>=|<=|\\|\\||&&|[()?:,\\[\\]]|\\+|-|\\*|\\/|%|>|<|!|\\d+\\.?\\d*|\"[^\"]*\"|'[^']*'|[a-zA-Z_][a-zA-Z0-9_]*|\\S)\\s*/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(input)) !== null) {\n const raw = m[1];\n if (!raw) continue;\n if (/^\\d/.test(raw)) tokens.push({ type: 'NUMBER', value: raw });\n else if (/^\"/.test(raw) || /^'/.test(raw)) tokens.push({ type: 'STRING', value: raw });\n else if (/^[a-zA-Z_]/.test(raw)) tokens.push({ type: 'IDENT', value: raw });\n else if (/^[()?:,\\[\\]]$/.test(raw)) tokens.push({ type: 'PUNC', value: raw });\n else tokens.push({ type: 'OP', value: raw });\n }\n return tokens;\n }\n \n private static evaluateSimpleValue(value: string, context: any): any {\n if (value === 'true') return true;\n if (value === 'false') return false;\n if (!isNaN(Number(value))) return Number(value);\n if (value.startsWith('ctx.')) {\n const propertyPath = value.slice(4);\n return getNestedValue(context, propertyPath);\n }\n \n // Remove quotes for string literals\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n return value.slice(1, -1);\n }\n \n return value;\n }\n \n static clearCache(): void {\n this.cache.clear();\n }\n \n static getCacheSize(): number {\n return this.cache.size;\n }\n}\n\nexport { SecureExpressionEvaluator };","/**\n * Event Manager for tracking and cleaning up event listeners\n * Prevents memory leaks by maintaining cleanup functions\n */\n\n/**\n * Manages event listeners and their cleanup for elements\n */\nclass EventManager {\n private static cleanupFunctions = new WeakMap<HTMLElement, Array<{\n event: string;\n handler: EventListener;\n wrapper: EventListener;\n options?: AddEventListenerOptions;\n cleanup: () => void;\n addedAt: number;\n }>>();\n \n /**\n * Add an event listener with automatic cleanup tracking\n */\n static addListener(\n element: HTMLElement, \n event: string, \n handler: EventListener,\n options?: AddEventListenerOptions\n ): void {\n element.addEventListener(event, handler, options);\n \n const cleanup = () => element.removeEventListener(event, handler, options);\n const meta = { event, handler, wrapper: handler, options, cleanup, addedAt: Date.now() };\n\n if (!this.cleanupFunctions.has(element)) {\n this.cleanupFunctions.set(element, []);\n }\n\n const list = this.cleanupFunctions.get(element)!;\n list.push(meta);\n (list as any).__metaList = list;\n }\n \n /**\n * Remove a specific event listener\n */\n static removeListener(\n element: HTMLElement, \n event: string, \n handler: EventListener,\n options?: EventListenerOptions\n ): void {\n element.removeEventListener(event, handler, options);\n \n const cleanups = this.cleanupFunctions.get(element);\n if (!cleanups) return;\n \n // Optimized: find and remove in single pass\n for (let i = 0; i < cleanups.length; i++) {\n const m = cleanups[i];\n if (m.event === event && m.handler === handler) {\n cleanups.splice(i, 1);\n if (cleanups.length === 0) {\n this.cleanupFunctions.delete(element);\n }\n return;\n }\n }\n }\n \n /**\n * Clean up all event listeners for an element\n */\n static cleanup(element: HTMLElement): void {\n const list = this.cleanupFunctions.get(element);\n if (list) {\n list.forEach(m => {\n try {\n m.cleanup();\n } catch (error) {\n // Silently ignore cleanup errors\n }\n });\n this.cleanupFunctions.delete(element);\n }\n }\n \n /**\n * Clean up all tracked event listeners (useful for testing)\n */\n static cleanupAll(): void {\n // WeakMap doesn't have a clear method and automatically cleans up\n // when elements are garbage collected. Reset internal state for testing.\n this.cleanupFunctions = new WeakMap();\n }\n \n /**\n * Check if an element has any tracked event listeners\n */\n static hasListeners(element: HTMLElement): boolean {\n const list = this.cleanupFunctions.get(element);\n return !!(list && list.length > 0);\n }\n \n /**\n * Get the number of tracked event listeners for an element\n */\n static getListenerCount(element: HTMLElement): number {\n const list = this.cleanupFunctions.get(element);\n return list ? list.length : 0;\n }\n\n /**\n * Return listener metadata stored for the element (test/debug only)\n */\n static getListenerInfo(element: HTMLElement): Array<{event:string, handler?: Function, wrapper?: Function, options?: any}> {\n const list = this.cleanupFunctions.get(element);\n if (!list) return [];\n return list.map(m => ({ event: m.event, handler: m.handler, wrapper: m.wrapper, options: m.options }));\n }\n}\n\nexport { EventManager };\n","/**\n * Helper functions for model binding updates in vdom.ts\n * Extracted to reduce code duplication and improve maintainability\n */\n\nimport {\n getNestedValue,\n setNestedValue,\n toKebab,\n safe,\n safeSerializeAttr,\n} from \"./helpers\";\n\n/**\n * Check if two values have changed, handling arrays specially\n */\nexport function hasValueChanged(newValue: any, currentValue: any): boolean {\n if (Array.isArray(newValue) && Array.isArray(currentValue)) {\n return (\n JSON.stringify([...newValue].sort()) !==\n JSON.stringify([...currentValue].sort())\n );\n }\n return newValue !== currentValue;\n}\n\n/**\n * Update state value (reactive or path-based)\n */\nexport function updateStateValue(\n isReactive: boolean,\n value: any,\n newValue: any,\n context: any,\n arg?: string\n): void {\n if (isReactive) {\n if (arg && typeof value.value === \"object\" && value.value !== null) {\n // For :model:prop, update the specific property\n const updated = { ...value.value };\n updated[arg] = newValue;\n value.value = updated;\n } else {\n // For plain :model, update the entire value\n value.value = newValue;\n }\n } else {\n // Fallback to string-based update (legacy config API)\n const actualState = context._state || context;\n setNestedValue(actualState, value as string, newValue);\n }\n}\n\n/**\n * Trigger render and watchers after state update\n */\nexport function triggerStateUpdate(\n context: any,\n isReactive: boolean,\n value: any,\n newValue: any\n): void {\n if (context._requestRender) {\n context._requestRender();\n }\n\n if (context._triggerWatchers) {\n const watchKey = isReactive ? \"reactiveState\" : (value as string);\n context._triggerWatchers(watchKey, newValue);\n }\n}\n\n/**\n * Emit custom update events (both kebab-case and camelCase)\n */\nexport function emitUpdateEvents(\n target: HTMLElement,\n propName: string,\n newValue: any\n): void {\n const customEventNameKebab = `update:${toKebab(propName)}`;\n const customEventNameCamel = `update:${propName}`;\n\n const customEventKebab = new CustomEvent(customEventNameKebab, {\n detail: newValue,\n bubbles: true,\n composed: true,\n });\n\n const customEventCamel = new CustomEvent(customEventNameCamel, {\n detail: newValue,\n bubbles: true,\n composed: true,\n });\n\n target.dispatchEvent(customEventKebab);\n target.dispatchEvent(customEventCamel);\n}\n\n/**\n * Update element properties and attributes to sync with state\n */\nexport function syncElementWithState(\n target: any,\n propName: string,\n propValue: any,\n isReactive: boolean\n): void {\n const propToSet = isReactive ? propValue : propValue;\n\n // Set property\n safe(() => {\n target[propName] = propToSet;\n });\n\n // Sync attributes for primitive/boolean values\n safe(() => {\n const attrName = toKebab(propName);\n if (typeof propToSet === \"boolean\") {\n const serialized = safeSerializeAttr(propToSet);\n if (serialized !== null) target.setAttribute(attrName, serialized);\n else target.removeAttribute?.(attrName);\n } else if (\n propToSet != null &&\n (typeof propToSet === \"string\" || typeof propToSet === \"number\")\n ) {\n target.setAttribute(attrName, String(propToSet));\n } else {\n // For anything else, attempt safe serialization and only set when safe\n const serialized = safeSerializeAttr(propToSet);\n if (serialized !== null) target.setAttribute(attrName, serialized);\n else target.removeAttribute?.(attrName);\n }\n });\n\n // Trigger component's internal handling\n safe(() => {\n target._applyProps?.(target._cfg);\n });\n safe(() => {\n target._requestRender?.();\n });\n}\n\n/**\n * Get current state value (reactive or path-based)\n */\nexport function getCurrentStateValue(\n isReactive: boolean,\n value: any,\n context: any,\n arg?: string\n): any {\n if (isReactive) {\n const unwrapped = value.value;\n if (arg && typeof unwrapped === \"object\" && unwrapped !== null) {\n return unwrapped[arg];\n }\n return unwrapped;\n }\n const actualState = context._state || context;\n return getNestedValue(actualState, value as string);\n}\n","import { devWarn, devError } from \"./logger\";\n\n/**\n * Transition utilities for VDOM\n * Handles applying transition classes and managing animation lifecycles\n */\n\n/**\n * Split space-separated class names into an array\n */\nfunction splitClasses(classString?: string): string[] {\n return classString ? classString.split(/\\s+/).filter(Boolean) : [];\n}\n\n/**\n * Add classes to an element\n * Optimized to filter out duplicates before adding\n */\nfunction addClasses(el: HTMLElement, classes: string[]): void {\n if (classes.length === 0) return;\n \n // Filter out classes that already exist (more efficient than checking one by one)\n const newClasses = classes.filter(cls => cls && !el.classList.contains(cls));\n if (newClasses.length > 0) {\n el.classList.add(...newClasses);\n }\n}\n\n/**\n * Remove classes from an element\n * Optimized to batch remove all classes at once\n */\nfunction removeClasses(el: HTMLElement, classes: string[]): void {\n if (classes.length === 0) return;\n \n const validClasses = classes.filter(Boolean);\n if (validClasses.length > 0) {\n el.classList.remove(...validClasses);\n }\n}\n\n/**\n * Track if we've successfully waited for styles at least once\n * After the first successful load, we don't need to wait again\n */\nlet stylesLoadedOnce = false;\n\n/**\n * Wait for styles to be computed and applied to an element.\n * This ensures CSS is loaded before attempting to read computed styles.\n * Uses a timeout to prevent infinite waiting.\n */\nasync function waitForStyles(el: HTMLElement, _classesToCheck: string[], maxAttempts = 10): Promise<void> {\n // If we've already loaded styles once, skip the wait\n if (stylesLoadedOnce) {\n return;\n }\n \n // If element is not in the document, styles won't compute\n if (!el.isConnected) {\n devWarn('⚠️ Element not connected to DOM, skipping style wait');\n return;\n }\n \n // Check if any of the classes produce computed styles\n for (let i = 0; i < maxAttempts; i++) {\n const computed = window.getComputedStyle(el);\n \n // Check if transform or opacity has been computed (non-empty)\n // Empty string means CSS hasn't loaded yet\n // 'none' for transform or '0'/'1' for opacity means CSS IS loaded\n const hasTransform = computed.transform && computed.transform !== '';\n const hasOpacity = computed.opacity && computed.opacity !== '';\n \n // If we have valid computed values (even if they're 'none' or '0'), styles are loaded\n if (hasTransform || hasOpacity) {\n stylesLoadedOnce = true;\n return;\n }\n \n // Wait a frame and try again\n await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));\n }\n \n // If we timeout, continue anyway - styles might not be for transform/opacity\n // But mark as loaded so we don't keep checking\n stylesLoadedOnce = true;\n devWarn('⚠️ Styles did not load in time for transition, continuing anyway');\n}\n\n/**\n * Get computed transition duration in milliseconds\n */\nfunction getTransitionDuration(el: HTMLElement): number {\n const computedStyle = window.getComputedStyle(el);\n const duration = computedStyle.transitionDuration || '0s';\n const delay = computedStyle.transitionDelay || '0s';\n \n const parseDuration = (value: string): number => {\n const num = parseFloat(value);\n return value.includes('ms') ? num : num * 1000;\n };\n \n return parseDuration(duration) + parseDuration(delay);\n}\n\n/**\n * Wait for transition to complete\n */\nfunction waitForTransition(el: HTMLElement, expectedDuration?: number): Promise<void> {\n return new Promise(resolve => {\n const duration = expectedDuration ?? getTransitionDuration(el);\n \n if (duration <= 0) {\n resolve();\n return;\n }\n \n let resolved = false;\n const done = () => {\n if (!resolved) {\n resolved = true;\n el.removeEventListener('transitionend', onTransitionEnd);\n el.removeEventListener('transitioncancel', onTransitionEnd);\n resolve();\n }\n };\n \n const onTransitionEnd = () => done();\n \n el.addEventListener('transitionend', onTransitionEnd);\n el.addEventListener('transitioncancel', onTransitionEnd);\n \n // Fallback timeout in case transitionend doesn't fire\n setTimeout(done, duration + 50);\n });\n}\n\n/**\n * Perform enter transition on an element\n */\nexport async function performEnterTransition(\n el: HTMLElement,\n transitionMeta: any\n): Promise<void> {\n const { classes, hooks, css, duration } = transitionMeta;\n\n // Call before-enter hook\n if (hooks?.onBeforeEnter) {\n try {\n hooks.onBeforeEnter(el);\n } catch (e) {\n devError('Transition onBeforeEnter error:', e);\n }\n }\n \n if (!css) {\n // JS-only transition\n if (hooks?.onEnter) {\n return new Promise(resolve => {\n hooks.onEnter(el, () => {\n if (hooks?.onAfterEnter) {\n try {\n hooks.onAfterEnter(el);\n } catch (e) {\n devError('Transition onAfterEnter error:', e);\n }\n }\n resolve();\n });\n });\n }\n return;\n }\n \n // CSS transition\n const enterFromClasses = splitClasses(classes?.enterFrom);\n const enterActiveClasses = splitClasses(classes?.enterActive);\n const enterToClasses = splitClasses(classes?.enterTo);\n\n // Step 1: Apply enter-from classes\n addClasses(el, enterFromClasses);\n\n // Force reflow to ensure enter-from is applied\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // Step 2: Add enter-active classes (transition property)\n addClasses(el, enterActiveClasses);\n\n // CRITICAL: Force another reflow so browser sees the transition property\n // applied BEFORE we change the transform/opacity values\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // Call enter hook\n let manualDone: (() => void) | undefined;\n if (hooks?.onEnter) {\n const promise = new Promise<void>(resolve => {\n manualDone = resolve;\n });\n \n try {\n hooks.onEnter(el, () => {\n if (manualDone) manualDone();\n });\n } catch (e) {\n devError('Transition onEnter error:', e);\n }\n \n // If hook provides done callback, wait for it\n if (manualDone) {\n await promise;\n }\n }\n \n // Wait for next frame - this is critical for the transition to work \n // The browser needs a frame where it sees: element + enterFrom + enterActive\n await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));\n \n // Force another reflow to ensure styles are applied\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // CRITICAL: CSS class-based transitions with conflicting properties don't work\n // reliably because of cascade conflicts. When both translate-x-[100%] and\n // translate-x-[0%] are utility classes with same specificity, whichever appears\n // last in the stylesheet wins immediately - no animation.\n //\n // SOLUTION: Use inline styles for the actual transition values.\n // - Inline styles have highest specificity\n // - We capture the \"from\" computed values as inline styles\n // - Then add \"to\" classes which override the inline values\n // - Browser animates from inline styles to class-based styles\n //\n // The JIT CSS classes are still used for:\n // - transition-all, duration-300, ease-out (timing/easing)\n // - Non-animated properties (padding, colors, etc.)\n //\n // Only the ANIMATED values (transform, opacity during transition) use inline.\n \n // Capture current computed values\n const computedStyle = window.getComputedStyle(el);\n const fromTransform = computedStyle.transform;\n const fromOpacity = computedStyle.opacity;\n\n // Remove enterFrom classes\n removeClasses(el, enterFromClasses);\n\n // Apply captured values as inline styles (highest specificity)\n if (fromTransform && fromTransform !== 'none') {\n el.style.transform = fromTransform;\n }\n if (fromOpacity && fromOpacity !== '') {\n el.style.opacity = fromOpacity;\n }\n\n // Force reflow\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // Wait for next frame\n await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));\n\n // Remove inline styles and add enterTo classes\n // Browser will animate from inline values to class values\n el.style.transform = '';\n el.style.opacity = '';\n addClasses(el, enterToClasses);\n \n // Force reflow to ensure styles are applied\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // Wait for next frame so browser recalculates computed styles\n await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));\n\n // Get duration\n let transitionDuration: number | undefined;\n if (typeof duration === 'number') {\n transitionDuration = duration;\n } else if (duration && typeof duration === 'object' && 'enter' in duration) {\n transitionDuration = duration.enter;\n }\n \n // Wait for transition\n await waitForTransition(el, transitionDuration);\n \n // Step 3: Clean up only enterActive classes, keep enterTo as final state\n removeClasses(el, enterActiveClasses);\n // Note: We keep enterToClasses since that's the final visible state\n \n // Call after-enter hook\n if (hooks?.onAfterEnter) {\n try {\n hooks.onAfterEnter(el);\n } catch (e) {\n devError('Transition onAfterEnter error:', e);\n }\n }\n}\n\n/**\n * Perform leave transition on an element\n */\nexport async function performLeaveTransition(\n el: HTMLElement,\n transitionMeta: any\n): Promise<void> {\n const { classes, hooks, css, duration } = transitionMeta;\n\n // Call before-leave hook\n if (hooks?.onBeforeLeave) {\n try {\n hooks.onBeforeLeave(el);\n } catch (e) {\n devError('Transition onBeforeLeave error:', e);\n }\n }\n \n if (!css) {\n // JS-only transition\n if (hooks?.onLeave) {\n return new Promise(resolve => {\n hooks.onLeave(el, () => {\n if (hooks?.onAfterLeave) {\n try {\n hooks.onAfterLeave(el);\n } catch (e) {\n devError('Transition onAfterLeave error:', e);\n }\n }\n resolve();\n });\n });\n }\n return;\n }\n \n // CSS transition\n const leaveFromClasses = splitClasses(classes?.leaveFrom);\n const leaveActiveClasses = splitClasses(classes?.leaveActive);\n const leaveToClasses = splitClasses(classes?.leaveTo);\n \n // Step 1: Apply leave-from classes\n addClasses(el, leaveFromClasses);\n \n // Force reflow\n // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n el.offsetHeight;\n \n // Step 2: Add leave-active classes\n addClasses(el, leaveActiveClasses);\n \n // Call leave hook\n let manualDone: (() => void) | undefined;\n if (hooks?.onLeave) {\n const promise = new Promise<void>(resolve => {\n manualDone = resolve;\n });\n \n try {\n hooks.onLeave(el, () => {\n if (manualDone) manualDone();\n });\n } catch (e) {\n devError('Transition onLeave error:', e);\n }\n \n // If hook provides done callback, wait for it\n if (manualDone) {\n await promise;\n }\n }\n \n // Use requestAnimationFrame\n await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));\n \n // Wait for CSS to be applied\n await waitForStyles(el, [...leaveFromClasses, ...leaveActiveClasses]);\n \n // Remove leave-from and add leave-to\n removeClasses(el, leaveFromClasses);\n addClasses(el, leaveToClasses);\n \n // Get duration\n let transitionDuration: number | undefined;\n if (typeof duration === 'number') {\n transitionDuration = duration;\n } else if (duration && typeof duration === 'object' && 'leave' in duration) {\n transitionDuration = duration.leave;\n }\n \n // Wait for transition\n await waitForTransition(el, transitionDuration);\n \n // Step 3: Clean up transition classes\n removeClasses(el, leaveActiveClasses);\n removeClasses(el, leaveToClasses);\n removeClasses(el, leaveFromClasses);\n \n // Call after-leave hook\n if (hooks?.onAfterLeave) {\n try {\n hooks.onAfterLeave(el);\n } catch (e) {\n devError('Transition onAfterLeave error:', e);\n }\n }\n}\n\n/**\n * Cancel ongoing transition\n */\nexport function cancelTransition(el: HTMLElement, isEnter: boolean, transitionMeta: any): void {\n const { classes, hooks } = transitionMeta;\n \n if (isEnter) {\n const enterFromClasses = splitClasses(classes?.enterFrom);\n const enterActiveClasses = splitClasses(classes?.enterActive);\n const enterToClasses = splitClasses(classes?.enterTo);\n \n removeClasses(el, enterFromClasses);\n removeClasses(el, enterActiveClasses);\n removeClasses(el, enterToClasses);\n \n if (hooks?.onEnterCancelled) {\n try {\n hooks.onEnterCancelled(el);\n } catch (e) {\n devError('Transition onEnterCancelled error:', e);\n }\n }\n } else {\n const leaveFromClasses = splitClasses(classes?.leaveFrom);\n const leaveActiveClasses = splitClasses(classes?.leaveActive);\n const leaveToClasses = splitClasses(classes?.leaveTo);\n \n removeClasses(el, leaveFromClasses);\n removeClasses(el, leaveActiveClasses);\n removeClasses(el, leaveToClasses);\n \n if (hooks?.onLeaveCancelled) {\n try {\n hooks.onLeaveCancelled(el);\n } catch (e) {\n devError('Transition onLeaveCancelled error:', e);\n }\n }\n }\n}\n","/**\n * Internal helpers for attaching metadata to DOM nodes without relying on\n * DOM-attached properties that minifiers or consumers might accidentally\n * rename/mangle.\n *\n * These helpers prefer WeakMap storage (safe and memory-leak free) and only\n * fall back to setting DOM properties/attributes for compatibility with older\n * code or tests.\n *\n * NOTE: This module is internal to the runtime and should not be re-exported\n * from the public API surface. Use the exported functions in this file when\n * you need minifier-safe metadata on nodes.\n *\n * Contract (brief):\n * - setNodeKey(node, key): associates an opaque string key with a Node.\n * - getNodeKey(node): returns the associated key or undefined.\n * - setElementTransition(el, val): stores transition-group metadata on an\n * element used by the patcher/transition system.\n * - getElementTransition(el): retrieves previously stored transition metadata.\n *\n * Edge cases / error modes:\n * - All setters swallow errors (defensive) to avoid breaking production code\n * when host environments restrict adding properties or attributes.\n * - Prefer the WeakMap APIs for future-proof, minifier-safe behavior.\n * @internal\n */\nconst nodeKeyMap = new WeakMap<Node, string>();\nconst elementTransitionMap = new WeakMap<HTMLElement, any>();\n\n/**\n * Retrieve the stored node key for a Node.\n *\n * The lookup prefers a WeakMap-stored value. For compatibility it will also\n * attempt to read legacy fallbacks: a `.key` property or the\n * `data-anchor-key` attribute on Elements.\n *\n * @internal\n */\nexport function getNodeKey(node: Node | null | undefined): string | undefined {\n if (!node) return undefined;\n const wm = nodeKeyMap.get(node);\n if (wm !== undefined) return wm as string;\n try {\n const anyNode = node as any;\n if (anyNode && anyNode.key != null) return anyNode.key;\n } catch (e) {}\n if (node instanceof Element) {\n const attr = node.getAttribute(\"data-anchor-key\");\n if (attr) return attr;\n }\n return undefined;\n}\n\n/**\n * Store a node key on a Node.\n *\n * This sets a WeakMap entry and also writes defensive DOM fallbacks for\n * compatibility with older consumers/tests. Errors are swallowed to avoid\n * disrupting host environments that forbid property writes.\n *\n * @internal\n */\nimport { safeSerializeAttr } from \"./helpers\";\n\nexport function setNodeKey(node: Node, key: string): void {\n try {\n nodeKeyMap.set(node, key);\n } catch (e) {}\n try {\n (node as any).key = key;\n } catch (e) {}\n try {\n if (node instanceof Element) {\n const s = safeSerializeAttr(key);\n if (s !== null) node.setAttribute(\"data-anchor-key\", s);\n }\n } catch (e) {}\n}\n\n/**\n * Retrieve transition-group metadata attached to an element.\n *\n * Prefers the WeakMap but falls back to a legacy `._transitionGroup` property\n * if present.\n *\n * @internal\n */\nexport function getElementTransition(el: HTMLElement | null | undefined): any {\n if (!el) return undefined;\n const wm = elementTransitionMap.get(el);\n if (wm !== undefined) return wm;\n try {\n const anyEl = el as any;\n if (anyEl && anyEl._transitionGroup != null) return anyEl._transitionGroup;\n } catch (e) {}\n return undefined;\n}\n\n/**\n * Store transition-group metadata for an element.\n *\n * Writes to the WeakMap and a defensive legacy property for compatibility.\n * Errors are swallowed to avoid breaking host environments.\n *\n * @internal\n */\nexport function setElementTransition(el: HTMLElement, val: any): void {\n try {\n elementTransitionMap.set(el, val);\n } catch (e) {}\n try {\n (el as any)._transitionGroup = val;\n } catch (e) {}\n}\n\nexport default {\n getNodeKey,\n setNodeKey,\n getElementTransition,\n setElementTransition,\n};\n","/**\n * vdom.ts\n * Lightweight, strongly typed, functional virtual DOM renderer for custom elements.\n * Features: keyed diffing, incremental patching, focus/caret preservation, event delegation, SSR-friendly, no dependencies.\n */\n\nimport type { VNode, VDomRefs, AnchorBlockVNode } from \"./types\";\nimport {\n escapeHTML,\n getNestedValue,\n setNestedValue,\n toKebab,\n toCamel,\n safe,\n safeSerializeAttr,\n isClassLikeAttr,\n} from \"./helpers\";\nimport { SecureExpressionEvaluator } from \"./secure-expression-evaluator\";\nimport { EventManager } from \"./event-manager\";\nimport { isReactiveState } from \"./reactive\";\nimport {\n hasValueChanged,\n updateStateValue,\n triggerStateUpdate,\n emitUpdateEvents,\n syncElementWithState,\n getCurrentStateValue,\n} from \"./vdom-model-helpers\";\nimport {\n performEnterTransition,\n performLeaveTransition,\n} from \"./transition-utils\";\nimport { devError } from \"./logger\";\nimport {\n getNodeKey,\n setNodeKey,\n getElementTransition,\n setElementTransition,\n} from \"./node-metadata\";\n\n/**\n * Helper: determine whether an element is a native form control we treat\n * specially for boolean-like attributes (disabled, checked, value).\n */\nfunction isNativeControl(\n el?: any\n): el is\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n | HTMLButtonElement {\n return (\n el instanceof HTMLInputElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLButtonElement\n );\n}\n\n/**\n * Coerce a value to a boolean for native DOM controls.\n * Treat empty string and literal 'true' as true, 'false' as false,\n * unwrap reactive-like wrappers and fall back to Boolean(value).\n */\nfunction coerceBooleanForNative(val: any): boolean {\n // Explicit empty-string => presence boolean true (attribute presence)\n if (val === \"\") return true;\n\n // Strings: treat 'true'/'false' specially, otherwise non-empty string is presence\n if (typeof val === \"string\") {\n if (val === \"false\") return false;\n if (val === \"true\") return true;\n return val !== \"\";\n }\n\n // Objects: only treat known reactive wrappers as booleans by unwrapping\n if (val && typeof val === \"object\") {\n if (isReactiveState(val)) return !!(val as any).value;\n if (\"value\" in val) return !!(val as any).value;\n // Defensive: do not coerce arbitrary objects (including proxies) to true\n // as they may represent rich prop wrappers (useProps proxy, etc.).\n return false;\n }\n\n // Fallback for primitives (number, boolean, etc.)\n return !!val;\n}\n\n/**\n * Recursively clean up refs and event listeners for all descendants of a node\n * @param node The node to clean up.\n * @param refs The refs to clean up.\n * @returns\n */\nexport function cleanupRefs(node: Node, refs?: VDomRefs) {\n if (!refs || !(node instanceof HTMLElement)) return;\n\n // Clean up event listeners for this element\n EventManager.cleanup(node);\n\n // Clean up refs\n for (const refKey in refs) {\n if (refs[refKey] === node) {\n delete refs[refKey];\n }\n }\n\n // Clean up child nodes\n const children = node.childNodes;\n for (let i = 0; i < children.length; i++) {\n cleanupRefs(children[i], refs);\n }\n}\n\n/**\n * Assign a ref to an element, supporting both string refs and reactive state objects\n */\nfunction assignRef(vnode: VNode, element: HTMLElement, refs?: VDomRefs): void {\n if (typeof vnode === \"string\") return;\n\n const reactiveRef =\n vnode.props?.reactiveRef ??\n (vnode.props?.props && vnode.props.props.reactiveRef);\n const refKey =\n vnode.props?.ref ?? (vnode.props?.props && vnode.props.props.ref);\n\n if (reactiveRef) {\n // For reactive state objects, assign the element to the .value property\n reactiveRef.value = element;\n } else if (refKey && refs) {\n // Legacy string-based ref\n refs[refKey] = element;\n }\n}\n\n/**\n * Process :model directive for two-way data binding\n * @param value\n * @param modifiers\n * @param props\n * @param attrs\n * @param listeners\n * @param context\n * @param el\n * @returns\n */\nexport function processModelDirective(\n value: string | any,\n modifiers: string[],\n props: Record<string, any>,\n attrs: Record<string, any>,\n listeners: Record<string, EventListener>,\n context?: any,\n el?: HTMLElement,\n arg?: string\n): void {\n if (!context) return;\n\n const hasLazy = modifiers.includes(\"lazy\");\n const hasTrim = modifiers.includes(\"trim\");\n const hasNumber = modifiers.includes(\"number\");\n\n // Enhanced support for reactive state objects (functional API)\n const isReactiveState =\n value &&\n typeof value === \"object\" &&\n \"value\" in value &&\n typeof value.value !== \"undefined\";\n\n const getCurrentValue = () => {\n if (isReactiveState) {\n const unwrapped = value.value;\n // If this is a native input and an arg was provided (e.g. :model:name),\n // we should bind the nested property to the input's value.\n if (\n arg &&\n el &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n if (typeof unwrapped === \"object\" && unwrapped !== null) {\n return unwrapped[arg];\n }\n }\n // Otherwise return the full unwrapped value for custom element props\n return unwrapped;\n }\n // Fallback to string-based lookup (legacy config API)\n return getNestedValue(context._state || context, value as string);\n };\n\n const currentValue = getCurrentValue();\n\n // determine element/input type\n let inputType = \"text\";\n if (el instanceof HTMLInputElement)\n inputType = (attrs?.type as string) || el.type || \"text\";\n else if (el instanceof HTMLSelectElement) inputType = \"select\";\n else if (el instanceof HTMLTextAreaElement) inputType = \"textarea\";\n\n const isNativeInput =\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement;\n const defaultPropName =\n inputType === \"checkbox\" || inputType === \"radio\" ? \"checked\" : \"value\";\n const propName = isNativeInput ? defaultPropName : arg ?? \"modelValue\";\n\n // Initial sync: set prop/attrs so renderer can apply proper DOM state\n if (inputType === \"checkbox\") {\n if (Array.isArray(currentValue)) {\n props[propName] = currentValue.includes(\n String(el?.getAttribute(\"value\") ?? attrs?.value ?? \"\")\n );\n } else {\n const trueValue = el?.getAttribute(\"true-value\") ?? true;\n props[propName] = currentValue === trueValue;\n }\n } else if (inputType === \"radio\") {\n props[propName] = currentValue === (attrs?.value ?? \"\");\n } else if (inputType === \"select\") {\n // For multiple selects we also schedule option selection; otherwise set prop\n if (el && el.hasAttribute(\"multiple\") && el instanceof HTMLSelectElement) {\n const arr = Array.isArray(currentValue) ? currentValue.map(String) : [];\n setTimeout(() => {\n Array.from((el as HTMLSelectElement).options).forEach((option) => {\n option.selected = arr.includes(option.value);\n });\n }, 0);\n props[propName] = Array.isArray(currentValue) ? currentValue : [];\n } else {\n props[propName] = currentValue;\n }\n } else {\n // For custom elements (non-native inputs) prefer assigning the\n // ReactiveState instance itself to the prop so child components that\n // call useProps can detect and unwrap the live ref. For native\n // inputs we must set the unwrapped current value.\n if (!isNativeInput && isReactiveState) {\n props[propName] = value; // pass the ReactiveState instance\n } else {\n props[propName] = currentValue;\n }\n // Also set an attribute so custom element constructors / applyProps can\n // read initial values via getAttribute during their initialization.\n try {\n const attrName = toKebab(propName);\n if (attrs) attrs[attrName] = currentValue;\n } catch (e) {\n // ignore\n }\n }\n\n // event type to listen for\n const eventType =\n hasLazy ||\n inputType === \"checkbox\" ||\n inputType === \"radio\" ||\n inputType === \"select\"\n ? \"change\"\n : \"input\";\n\n const eventListener: EventListener = (event: Event) => {\n if ((event as any).isComposing || (listeners as any)._isComposing) return;\n // Allow synthetic events during testing (when isTrusted is false)\n // but ignore them in production unless it's a synthetic test event\n const isTestEnv =\n (typeof (globalThis as any).process !== \"undefined\" &&\n (globalThis as any).process.env?.NODE_ENV === \"test\") ||\n (typeof window !== \"undefined\" && (window as any).__vitest__);\n if ((event as any).isTrusted === false && !isTestEnv) return;\n\n const target = event.target as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | null;\n if (!target || (target as any)._modelUpdating) return;\n\n let newValue: any = (target as any).value;\n\n if (inputType === \"checkbox\") {\n const fresh = getCurrentValue();\n if (Array.isArray(fresh)) {\n const v = target.getAttribute(\"value\") ?? \"\";\n const arr = Array.from(fresh as any[]);\n if ((target as HTMLInputElement).checked) {\n if (!arr.includes(v)) arr.push(v);\n } else {\n const idx = arr.indexOf(v);\n if (idx > -1) arr.splice(idx, 1);\n }\n newValue = arr;\n } else {\n const trueV = target.getAttribute(\"true-value\") ?? true;\n const falseV = target.getAttribute(\"false-value\") ?? false;\n newValue = (target as HTMLInputElement).checked ? trueV : falseV;\n }\n } else if (inputType === \"radio\") {\n newValue = target.getAttribute(\"value\") ?? (target as any).value;\n } else if (\n inputType === \"select\" &&\n (target as HTMLSelectElement).multiple\n ) {\n newValue = Array.from((target as HTMLSelectElement).selectedOptions).map(\n (o) => o.value\n );\n } else {\n if (hasTrim && typeof newValue === \"string\") newValue = newValue.trim();\n if (hasNumber) {\n const n = Number(newValue);\n if (!isNaN(n)) newValue = n;\n }\n }\n\n const currentStateValue = getCurrentValue();\n const changed = hasValueChanged(newValue, currentStateValue);\n\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n updateStateValue(isReactiveState, value, newValue, context, arg);\n triggerStateUpdate(context, isReactiveState, value, newValue);\n\n // Emit custom event for update:* listeners (emit both kebab and camel forms)\n if (target) {\n emitUpdateEvents(target, propName, newValue);\n }\n } finally {\n setTimeout(() => ((target as any)._modelUpdating = false), 0);\n }\n }\n };\n\n // Custom element update event names (update:prop) for non-native inputs\n if (!isNativeInput) {\n const eventNameKebab = `update:${toKebab(propName)}`;\n const eventNameCamel = `update:${propName}`;\n // Remove existing listeners to prevent memory leaks\n if (listeners[eventNameKebab]) {\n const oldListener = listeners[eventNameKebab];\n if (el) EventManager.removeListener(el, eventNameKebab, oldListener);\n }\n if (listeners[eventNameCamel]) {\n const oldListener = listeners[eventNameCamel];\n if (el) EventManager.removeListener(el, eventNameCamel, oldListener);\n }\n\n listeners[eventNameKebab] = (event: Event) => {\n const newVal =\n (event as CustomEvent).detail !== undefined\n ? (event as CustomEvent).detail\n : (event.target as any)?.value;\n // Determine current state value depending on reactive-state vs string path\n const currentStateValue = getCurrentStateValue(\n isReactiveState,\n value,\n context,\n arg\n );\n const changed = hasValueChanged(newVal, currentStateValue);\n\n if (changed) {\n try {\n /* nested handler invoked */\n } catch (e) {}\n\n updateStateValue(isReactiveState, value, newVal, context, arg);\n triggerStateUpdate(context, isReactiveState, value, newVal);\n\n // Update the custom element's property to maintain sync\n const target = event.target as any;\n if (target) {\n syncElementWithState(\n target,\n propName,\n isReactiveState ? value : newVal,\n isReactiveState\n );\n }\n }\n };\n // primary listener registered\n // If the bound reactive value is an object, also listen for nested\n // update events emitted by the child like `update:name` so the parent\n // can apply the change to the corresponding nested property on the\n // reactive state. This allows children to emit `update:<field>` when\n // they want to update a nested field of a bound object.\n if (\n isReactiveState &&\n typeof value.value === \"object\" &&\n value.value !== null\n ) {\n // Use Reflect.ownKeys to be robust across proxies; filter out internal keys\n let keys: Array<string | symbol> = [];\n try {\n keys = Reflect.ownKeys(value.value);\n } catch (e) {\n keys = Object.keys(value.value);\n }\n const userKeys = (keys as Array<any>).filter(\n (k) =>\n typeof k === \"string\" &&\n !String(k).startsWith(\"_\") &&\n k !== \"constructor\"\n );\n // preparing nested listeners\n for (const nestedKey of userKeys) {\n const nestedKebab = `update:${toKebab(nestedKey as string)}`;\n const nestedCamel = `update:${nestedKey as string}`;\n // Avoid overwriting the primary handler for the main prop\n // and avoid registering internal keys\n if (listeners[nestedKebab]) continue;\n listeners[nestedKebab] = (event: Event) => {\n const newVal =\n (event as CustomEvent).detail !== undefined\n ? (event as CustomEvent).detail\n : (event.target as any)?.value;\n const currentStateValue = isReactiveState\n ? (value.value as any)[nestedKey]\n : getNestedValue(context._state || context, value as string);\n const changed = hasValueChanged(newVal, currentStateValue);\n if (!changed) return;\n\n // Update the ReactiveState with a shallow copy so reactivity triggers\n if (isReactiveState) {\n const updated = { ...(value.value as any) };\n updated[nestedKey] = newVal;\n value.value = updated;\n } else {\n setNestedValue(context._state || context, value as string, newVal);\n }\n\n triggerStateUpdate(context, isReactiveState, value, newVal);\n\n const host =\n (event.currentTarget as any) || el || (event.target as any);\n if (host) {\n syncElementWithState(\n host,\n propName,\n isReactiveState ? value : newVal,\n isReactiveState\n );\n }\n };\n listeners[nestedCamel] = listeners[nestedKebab];\n }\n }\n // Mirror handler under camel name for compatibility\n listeners[eventNameCamel] = listeners[eventNameKebab];\n } else {\n // Remove existing listener to prevent memory leaks\n if (listeners[eventType]) {\n const oldListener = listeners[eventType];\n if (el) {\n EventManager.removeListener(el, eventType, oldListener);\n }\n }\n listeners[eventType] = eventListener;\n }\n\n // IME composition handling for text-like inputs\n if (inputType === \"text\" || inputType === \"textarea\") {\n listeners.compositionstart = () => ((listeners as any)._isComposing = true);\n listeners.compositionend = (event: Event) => {\n (listeners as any)._isComposing = false;\n const target = event.target as\n | HTMLInputElement\n | HTMLTextAreaElement\n | null;\n if (!target) return;\n setTimeout(() => {\n const val = target.value;\n const actualState = context._state || context;\n const currentStateValue = getNestedValue(actualState, value);\n let newVal: any = val;\n if (hasTrim) newVal = newVal.trim();\n if (hasNumber) {\n const n = Number(newVal);\n if (!isNaN(n)) newVal = n;\n }\n const changed = hasValueChanged(newVal, currentStateValue);\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n setNestedValue(actualState, value, newVal);\n triggerStateUpdate(context, isReactiveState, value, newVal);\n } finally {\n setTimeout(() => ((target as any)._modelUpdating = false), 0);\n }\n }\n }, 0);\n };\n }\n // processModelDirective listeners prepared\n}\n\n/**\n * Convert a prop key like `onClick` to its DOM event name `click`.\n */\nfunction eventNameFromKey(key: string): string {\n // Strip leading 'on' and lowercase the first character of the remainder.\n // This handles names like `onClick` -> `click` and\n // `onUpdate:model-value` -> `update:model-value` correctly.\n const rest = key.slice(2);\n if (!rest) return \"\";\n return rest.charAt(0).toLowerCase() + rest.slice(1);\n}\n\n/**\n * Process :bind directive for attribute/property binding\n * @param value\n * @param props\n * @param attrs\n * @param context\n * @returns\n */\nexport function processBindDirective(\n value: any,\n props: Record<string, any>,\n attrs: Record<string, any>,\n context?: any,\n el?: HTMLElement\n): void {\n // Support both object and string syntax for :bind\n if (typeof value === \"object\" && value !== null) {\n for (const [key, val] of Object.entries(value)) {\n // Only put clearly HTML-only attributes in attrs, everything else in props\n // For native input/select/textarea elements, boolean-like attributes\n // such as `disabled` should be applied as attributes rather than\n // props to avoid placing wrapper/complex values into props which\n // can later be misinterpreted as truthy and disable the control.\n if (\n key.startsWith(\"data-\") ||\n key.startsWith(\"aria-\") ||\n key === \"class\"\n ) {\n attrs[key] = val;\n } else if (key === \"disabled\" && el && isNativeControl(el)) {\n // For native controls, prefer promoting reactive/wrapper values to props\n // so property assignment keeps a live reference and updates via reactivity.\n // For primitive booleans/strings prefer attrs to avoid placing arbitrary\n // objects into props which can be misinterpreted.\n const isWrapper = val && typeof val === \"object\" && \"value\" in val;\n const isReactiveVal = (() => {\n try {\n return isReactiveState(val);\n } catch (e) {\n return false;\n }\n })();\n if (isReactiveVal || isWrapper) {\n props[key] = val;\n } else {\n attrs[key] = val;\n }\n } else {\n props[key] = val;\n }\n }\n } else if (typeof value === \"string\") {\n if (!context) return;\n try {\n // Try to evaluate as expression (could be object literal)\n const evaluated = evaluateExpression(value, context);\n if (typeof evaluated === \"object\" && evaluated !== null) {\n for (const [key, val] of Object.entries(evaluated)) {\n // Mirror the object branch handling but we don't have access to\n // the element here; prefer attrs for booleanish disabled when\n // the expression produced primitive booleans or strings.\n if (\n key.startsWith(\"data-\") ||\n key.startsWith(\"aria-\") ||\n key === \"class\"\n ) {\n attrs[key] = val;\n } else if (key === \"disabled\" && el && isNativeControl(el)) {\n const isWrapper = val && typeof val === \"object\" && \"value\" in val;\n const isReactiveVal = (() => {\n try {\n return isReactiveState(val);\n } catch (e) {\n return false;\n }\n })();\n if (isReactiveVal || isWrapper) {\n props[key] = val;\n } else {\n attrs[key] = val;\n }\n } else {\n props[key] = val;\n }\n }\n return;\n } else {\n // If not an object, treat as single value fallback\n attrs[value] = evaluated;\n return;\n }\n } catch {\n // Fallback: treat as single property binding\n const currentValue = getNestedValue(context, value);\n attrs[value] = currentValue;\n }\n }\n}\n\n/**\n * Process :show directive for conditional display\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\nexport function processShowDirective(\n value: any,\n attrs: Record<string, any>,\n context?: any\n): void {\n let isVisible: any;\n\n // Handle both string and direct value evaluation\n if (typeof value === \"string\") {\n if (!context) return;\n isVisible = evaluateExpression(value, context);\n } else {\n isVisible = value;\n }\n\n // Use the same approach as :style directive for consistency\n const currentStyle = attrs.style || \"\";\n let newStyle = currentStyle;\n\n if (!isVisible) {\n // Element should be hidden - ensure display: none is set\n if (currentStyle) {\n const styleRules = currentStyle.split(\";\").filter(Boolean);\n const displayIndex = styleRules.findIndex((rule: string) =>\n rule.trim().startsWith(\"display:\")\n );\n\n if (displayIndex >= 0) {\n styleRules[displayIndex] = \"display: none\";\n } else {\n styleRules.push(\"display: none\");\n }\n\n newStyle = styleRules.join(\"; \");\n } else {\n newStyle = \"display: none\";\n }\n } else {\n // Element should be visible - only remove display: none, don't interfere with other display values\n if (currentStyle) {\n const styleRules = currentStyle\n .split(\";\")\n .map((rule: string) => rule.trim())\n .filter(Boolean);\n const displayIndex = styleRules.findIndex((rule: string) =>\n rule.startsWith(\"display:\")\n );\n\n if (displayIndex >= 0) {\n const displayRule = styleRules[displayIndex];\n if (displayRule === \"display: none\") {\n // Remove only display: none, preserve other display values\n styleRules.splice(displayIndex, 1);\n newStyle = styleRules.length > 0 ? styleRules.join(\"; \") + \";\" : \"\";\n }\n // If display is set to something other than 'none', leave it alone\n }\n }\n // If no existing style, don't add anything\n }\n\n // Only set style if it's different from current to avoid unnecessary updates\n if (newStyle !== currentStyle) {\n if (newStyle) {\n attrs.style = newStyle;\n } else {\n // Remove the style attribute entirely if empty\n delete attrs.style;\n }\n }\n}\n\n/**\n * Process :class directive for conditional CSS classes\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\n/**\n * Evaluate a JavaScript-like object literal string in the given context\n * Uses secure AST-based evaluation instead of Function() constructor\n * @param expression\n * @param context\n * @returns\n */\nfunction evaluateExpression(expression: string, context: any): any {\n return SecureExpressionEvaluator.evaluate(expression, context);\n}\n\nexport function processClassDirective(\n value: any,\n attrs: Record<string, any>,\n context?: any\n): void {\n let classValue: any;\n\n // Handle both string and object values\n if (typeof value === \"string\") {\n if (!context) return;\n classValue = evaluateExpression(value, context);\n } else {\n classValue = value;\n }\n\n // Unwrap reactive/computed wrappers (ReactiveState) to get the inner value\n try {\n if (classValue && typeof classValue === \"object\") {\n if (isReactiveState(classValue)) {\n classValue = (classValue as any).value;\n } else if (\n \"value\" in classValue &&\n typeof (classValue as any).value !== \"undefined\"\n ) {\n // Best-effort unwrap for objects with a `.value` property that\n // are not DOM nodes (avoid unwrapping nodes that expose `.value`).\n const maybe = (classValue as any).value;\n if (!(maybe instanceof Node)) {\n classValue = maybe;\n }\n }\n }\n } catch (e) {\n // ignore\n }\n\n let classes: string[] = [];\n\n if (typeof classValue === \"string\") {\n classes = [classValue];\n } else if (Array.isArray(classValue)) {\n classes = classValue.filter(Boolean);\n } else if (typeof classValue === \"object\" && classValue !== null) {\n // Object syntax: { className: condition } - optimized without flatMap\n for (const [className, condition] of Object.entries(classValue)) {\n if (condition) {\n classes.push(className);\n }\n }\n }\n\n const existingClasses = attrs.class || \"\";\n const classString = classes.join(\" \");\n attrs.class = existingClasses\n ? `${existingClasses} ${classString}`.trim()\n : classString;\n}\n\n/**\n * Determine whether a value coming from vnode.props should be treated as\n * an explicit boolean-like value for property assignment. This avoids\n * treating empty-string or arbitrary objects as a truthy disabled prop\n * for native controls (we prefer attribute presence in those cases).\n */\nfunction isBooleanishForProps(v: any): boolean {\n // Only treat clear boolean-like values as booleanish for prop preference.\n // Accept explicit booleans, explicit empty-string (attribute presence),\n // and explicit 'true'/'false' strings. Do NOT treat numbers or arbitrary\n // objects as booleanish to avoid accidental truthiness for `disabled`.\n if (v === true || v === false) return true;\n if (v === undefined || v === null) return false;\n const t = typeof v;\n if (t === \"string\") return v === \"\" || v === \"true\" || v === \"false\";\n try {\n if (v && typeof v === \"object\" && \"value\" in v) {\n const inner = (v as any).value;\n const it = typeof inner;\n if (it === \"boolean\") return true;\n if (it === \"string\")\n return inner === \"\" || inner === \"true\" || inner === \"false\";\n return false;\n }\n } catch (e) {}\n return false;\n}\n\n/**\n * Process :style directive for dynamic inline styles\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\nexport function processStyleDirective(\n value: any,\n attrs: Record<string, any>,\n context?: any\n): void {\n let styleValue: any;\n\n if (typeof value === \"string\") {\n if (!context) return;\n styleValue = evaluateExpression(value, context);\n } else {\n styleValue = value;\n }\n\n let styleString = \"\";\n\n if (typeof styleValue === \"string\") {\n styleString = styleValue;\n } else if (styleValue && typeof styleValue === \"object\") {\n const styleRules: string[] = [];\n for (const [property, val] of Object.entries(styleValue)) {\n if (val != null && val !== \"\") {\n const kebabProperty = property.replace(\n /[A-Z]/g,\n (match) => `-${match.toLowerCase()}`\n );\n const needsPx = [\n \"width\",\n \"height\",\n \"top\",\n \"right\",\n \"bottom\",\n \"left\",\n \"margin\",\n \"margin-top\",\n \"margin-right\",\n \"margin-bottom\",\n \"margin-left\",\n \"padding\",\n \"padding-top\",\n \"padding-right\",\n \"padding-bottom\",\n \"padding-left\",\n \"font-size\",\n \"line-height\",\n \"border-width\",\n \"border-radius\",\n \"min-width\",\n \"max-width\",\n \"min-height\",\n \"max-height\",\n ];\n let cssValue = String(val);\n if (typeof val === \"number\" && needsPx.includes(kebabProperty)) {\n cssValue = `${val}px`;\n }\n styleRules.push(`${kebabProperty}: ${cssValue}`);\n }\n }\n styleString = styleRules.join(\"; \") + (styleRules.length > 0 ? \";\" : \"\");\n }\n\n const existingStyle = attrs.style || \"\";\n attrs.style =\n existingStyle +\n (existingStyle && !existingStyle.endsWith(\";\") ? \"; \" : \"\") +\n styleString;\n}\n\n/**\n * Process :ref directive for element references\n * @param value\n * @param props\n * @param context\n * @returns\n */\nexport function processRefDirective(\n value: any,\n props: Record<string, any>,\n context?: any\n): void {\n let resolvedValue = value;\n\n // If value is a string, evaluate it in the context to resolve variables\n if (typeof value === \"string\" && context) {\n resolvedValue = evaluateExpression(value, context);\n }\n\n // Support both reactive state objects (functional API) and string refs (legacy)\n if (isReactiveState(resolvedValue)) {\n // For reactive state objects, store the reactive state object itself as the ref\n // The VDOM renderer will handle setting the value\n props.reactiveRef = resolvedValue;\n } else {\n // Legacy string-based ref or direct object ref\n props.ref = resolvedValue;\n }\n}\n\n/**\n * Process directives and return merged props, attrs, and event listeners\n * @param directives\n * @param context\n * @param el\n * @param vnodeAttrs\n * @returns\n */\nexport function processDirectives(\n directives: Record<string, { value: any; modifiers: string[]; arg?: string }>,\n context?: any,\n el?: HTMLElement,\n vnodeAttrs?: Record<string, any>\n): {\n props: Record<string, any>;\n attrs: Record<string, any>;\n listeners: Record<string, EventListener>;\n} {\n const props: Record<string, any> = {};\n const attrs: Record<string, any> = { ...(vnodeAttrs || {}) };\n const listeners: Record<string, EventListener> = {};\n\n for (const [directiveName, directive] of Object.entries(directives)) {\n const { value, modifiers, arg } = directive;\n\n if (directiveName === \"model\" || directiveName.startsWith(\"model:\")) {\n // Extract arg from directiveName if present (model:prop)\n const parts = directiveName.split(\":\");\n const runtimeArg = parts.length > 1 ? parts[1] : arg;\n processModelDirective(\n value, // Pass the original value (could be string or reactive state object)\n modifiers,\n props,\n attrs,\n listeners,\n context,\n el,\n runtimeArg\n );\n continue;\n }\n\n switch (directiveName) {\n case \"bind\":\n processBindDirective(value, props, attrs, context, el);\n break;\n case \"show\":\n processShowDirective(value, attrs, context);\n break;\n case \"class\":\n processClassDirective(value, attrs, context);\n break;\n case \"style\":\n processStyleDirective(value, attrs, context);\n break;\n case \"ref\":\n processRefDirective(value, props, context);\n break;\n case \"when\":\n // The :when directive is handled during template compilation\n // by wrapping the element in an anchor block\n // This case should not normally be reached, but we handle it gracefully\n break;\n // Add other directive cases here as needed\n }\n }\n\n // Defensive post-processing: avoid leaving primitive non-wrapper\n // `disabled` values in processed props for native form controls.\n // Some code paths may incorrectly place a primitive boolean/string into\n // props which later becomes authoritative and disables native inputs.\n // To be safe, if `disabled` was placed into props by directives but is\n // a plain primitive (not a ReactiveState or wrapper with `.value`) and\n // the target element is a native input/select/textarea, move it to attrs\n // so the final disabled decision uses attribute/coercion rules instead.\n try {\n const had = Object.prototype.hasOwnProperty.call(props, \"disabled\");\n if (had && el && isNativeControl(el)) {\n const candidate = props[\"disabled\"];\n const isWrapper =\n candidate && typeof candidate === \"object\" && \"value\" in candidate;\n let isReactiveVal = false;\n try {\n isReactiveVal = isReactiveState(candidate);\n } catch (e) {\n isReactiveVal = false;\n }\n // If it's NOT reactive/wrapper, prefer attrs to avoid accidental truthiness\n if (!isWrapper && !isReactiveVal) {\n try {\n attrs[\"disabled\"] = candidate;\n delete props[\"disabled\"];\n const w = globalThis as any as any;\n if (!w.__VDOM_DISABLED_PROMOTIONS) w.__VDOM_DISABLED_PROMOTIONS = [];\n w.__VDOM_DISABLED_PROMOTIONS.push({\n phase: \"bind-directive:postfix-move\",\n location: \"attrs\",\n key: \"disabled\",\n value: candidate,\n time: Date.now(),\n stack: new Error().stack,\n });\n } catch (e) {\n // ignore\n }\n }\n }\n } catch (e) {}\n\n return { props, attrs, listeners };\n}\n\n/**\n * Assign unique keys to VNodes for efficient rendering\n * @param nodeOrNodes\n * @param baseKey\n * @returns\n */\nexport function assignKeysDeep(\n nodeOrNodes: VNode | VNode[],\n baseKey: string\n): VNode | VNode[] {\n if (Array.isArray(nodeOrNodes)) {\n const usedKeys = new Set<string>();\n\n return nodeOrNodes.map((child) => {\n if (!child || typeof child !== \"object\") return child;\n\n // Determine the starting key\n let key = child.props?.key ?? child.key;\n\n if (!key) {\n // Build a stable identity from tag + stable attributes\n const tagPart = child.tag || \"node\";\n // Look for stable identity attributes in both attrs and promoted\n // props (props.props) because the compiler may have promoted bound\n // attributes to JS properties for custom elements and converted\n // kebab-case to camelCase (e.g. data-key -> dataKey).\n const idAttrCandidates = [\n // attrs (kebab-case)\n child.props?.attrs?.id,\n child.props?.attrs?.name,\n child.props?.attrs?.[\"data-key\"],\n // promoted JS props (camelCase or original)\n child.props?.props?.id,\n child.props?.props?.name,\n child.props?.props?.dataKey,\n child.props?.props?.[\"data-key\"],\n ];\n const idPart =\n idAttrCandidates.find((v) => v !== undefined && v !== null) ?? \"\";\n key = idPart\n ? `${baseKey}:${tagPart}:${idPart}`\n : `${baseKey}:${tagPart}`;\n }\n\n // Ensure uniqueness among siblings\n let uniqueKey = key;\n let counter = 1;\n while (usedKeys.has(uniqueKey)) {\n uniqueKey = `${key}#${counter++}`;\n }\n usedKeys.add(uniqueKey);\n\n // Recurse into children with this node's unique key\n let children = child.children;\n if (Array.isArray(children)) {\n children = assignKeysDeep(children, uniqueKey) as VNode[];\n }\n\n return { ...child, key: uniqueKey, children };\n });\n }\n\n // Single node case\n const node = nodeOrNodes as VNode;\n let key = node.props?.key ?? node.key ?? baseKey;\n\n let children = node.children;\n if (Array.isArray(children)) {\n children = assignKeysDeep(children, key) as VNode[];\n }\n\n return { ...node, key, children };\n}\n\n/**\n * Patch props on an element.\n * Only update changed props, remove old, add new.\n * @param el\n * @param oldProps\n * @param newProps\n * @param context\n */\nexport function patchProps(\n el: HTMLElement,\n oldProps: Record<string, any>,\n newProps: Record<string, any>,\n context?: any\n) {\n // Process directives first\n const newDirectives = newProps.directives ?? {};\n const processedDirectives = processDirectives(\n newDirectives,\n context,\n el,\n newProps.attrs\n );\n\n // Merge processed directive results with existing props/attrs\n const mergedProps = {\n ...oldProps.props,\n ...newProps.props,\n ...processedDirectives.props,\n };\n const mergedAttrs = {\n ...oldProps.attrs,\n ...newProps.attrs,\n ...processedDirectives.attrs,\n };\n\n const oldPropProps = oldProps.props ?? {};\n const newPropProps = mergedProps;\n // Detect whether this vnode represents a custom element so we can\n // trigger its internal prop application lifecycle after patching.\n const elIsCustom =\n (newProps as any)?.isCustomElement ??\n (oldProps as any)?.isCustomElement ??\n false;\n let anyChange = false;\n for (const key in { ...oldPropProps, ...newPropProps }) {\n const oldVal = oldPropProps[key];\n const newVal = newPropProps[key];\n\n // For reactive wrapper objects (ReactiveState or { value }), compare\n // their unwrapped inner values so updates trigger even when the\n // wrapper identity stays the same across renders.\n let oldUnwrapped: any = oldVal;\n let newUnwrapped: any = newVal;\n safe(() => {\n if (isReactiveState(oldVal)) oldUnwrapped = (oldVal as any).value;\n else if (oldVal && typeof oldVal === \"object\" && \"value\" in oldVal)\n oldUnwrapped = (oldVal as any).value;\n });\n safe(() => {\n if (isReactiveState(newVal)) newUnwrapped = (newVal as any).value;\n else if (newVal && typeof newVal === \"object\" && \"value\" in newVal)\n newUnwrapped = (newVal as any).value;\n });\n\n // Consider changed when either the wrapper identity changed or the\n // inner unwrapped value changed.\n if (oldVal !== newVal && oldUnwrapped === newUnwrapped) {\n // wrapper identity changed but inner value same -> still treat as change\n }\n\n if (!(oldVal === newVal && oldUnwrapped === newUnwrapped)) {\n anyChange = true;\n if (\n key === \"value\" &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n // Unwrap reactive-like wrappers before assigning to .value\n const unwrapped =\n typeof newVal === \"object\" &&\n newVal !== null &&\n isReactiveState(newVal)\n ? (newVal as any).value\n : newVal && typeof newVal === \"object\" && \"value\" in newVal\n ? (newVal as any).value\n : newVal;\n if (el.value !== unwrapped) el.value = unwrapped ?? \"\";\n } else if (key === \"checked\" && el instanceof HTMLInputElement) {\n const unwrapped =\n typeof newVal === \"object\" &&\n newVal !== null &&\n isReactiveState(newVal)\n ? (newVal as any).value\n : newVal && typeof newVal === \"object\" && \"value\" in newVal\n ? (newVal as any).value\n : newVal;\n el.checked = !!unwrapped;\n } else if (key.startsWith(\"on\") && typeof newVal === \"function\") {\n // DOM-first listener: onClick -> click\n const ev = eventNameFromKey(key);\n if (typeof oldVal === \"function\") {\n EventManager.removeListener(el, ev, oldVal);\n }\n EventManager.addListener(el, ev, newVal);\n // If this is an update:* handler for a bound object prop, also\n // register nested update:<field> listeners that call the same\n // handler with a shallow-copied object so compiled handlers that\n // expect the full object will work with child-emitted nested events.\n try {\n if (ev && ev.startsWith(\"update:\")) {\n const propName = ev.split(\":\", 2)[1];\n const propVal = newPropProps[propName];\n // Determine nested keys robustly: if propVal is a ReactiveState,\n // inspect its .value, otherwise inspect the object itself.\n let candidateKeys: string[] = [];\n try {\n if (isReactiveState(propVal)) {\n const v = (propVal as any).value;\n candidateKeys =\n v && typeof v === \"object\" ? Object.keys(v) : [];\n } else if (propVal && typeof propVal === \"object\") {\n candidateKeys = Object.keys(propVal);\n }\n } catch (ee) {\n candidateKeys = [];\n }\n // Filter out internal keys\n const userKeys = candidateKeys.filter(\n (k) =>\n typeof k === \"string\" &&\n !k.startsWith(\"_\") &&\n k !== \"constructor\"\n );\n for (const nestedKey of userKeys) {\n const nestedEvent = `update:${nestedKey}`;\n const nestedHandler = (e: Event) => {\n const nestedNew =\n (e as CustomEvent).detail !== undefined\n ? (e as CustomEvent).detail\n : (e.target as any)?.value;\n const current = isReactiveState(propVal)\n ? (propVal as any).value || {}\n : (newPropProps[propName] as any) || {};\n const updated = { ...current, [nestedKey]: nestedNew };\n safe(() => {\n (newVal as any)({ detail: updated } as any);\n });\n };\n safe(() => {\n EventManager.addListener(el, nestedEvent, nestedHandler);\n });\n }\n }\n } catch (e) {\n /* ignore */\n }\n } else if (newVal === undefined || newVal === null) {\n el.removeAttribute(key);\n } else {\n // Prefer setting DOM properties for custom elements or when the\n // property already exists on the element so that JS properties are\n // updated (important for custom elements that observe property changes).\n // Prefer property assignment for elements that are custom elements or\n // when the property exists on the element. This avoids attribute\n // fallbacks being used for reactive properties on custom elements.\n // Rely only on compiler/runtime-provided hint. Do not perform implicit\n // dash-based heuristics here: callers/tests should set isCustomElement on\n // the vnode props when a tag is a custom element.\n const elIsCustom =\n (newProps as any)?.isCustomElement ??\n (oldProps as any)?.isCustomElement ??\n false;\n if (elIsCustom || key in el) {\n try {\n (el as any)[key] = newVal;\n // For native form controls, also remove the disabled attribute when setting disabled=false\n // The browser doesn't automatically sync the attribute when the property changes\n if (\n key === \"disabled\" &&\n newVal === false &&\n !elIsCustom &&\n isNativeControl(el)\n ) {\n el.removeAttribute(\"disabled\");\n }\n } catch (err) {\n // Enforce property-only binding: skip silently on failure.\n }\n } else {\n // Handle boolean false by removing attribute for non-custom elements\n if (newVal === false) {\n el.removeAttribute(key);\n } else {\n // Property does not exist; skip silently.\n }\n }\n }\n }\n }\n\n // Handle directive event listeners\n for (const [eventType, listener] of Object.entries(\n processedDirectives.listeners || {}\n )) {\n EventManager.addListener(el, eventType, listener as EventListener);\n try {\n const parentEl = el && (el.parentElement as HTMLElement | null);\n if (parentEl && parentEl !== el) {\n EventManager.addListener(\n parentEl,\n eventType,\n listener as EventListener\n );\n }\n } catch (e) {}\n }\n\n const oldAttrs = oldProps.attrs ?? {};\n const newAttrs = mergedAttrs;\n for (const key in { ...oldAttrs, ...newAttrs }) {\n const oldVal = oldAttrs[key];\n const newVal = newAttrs[key];\n\n // For reactive state objects, compare the unwrapped values\n let oldUnwrapped = oldVal;\n let newUnwrapped = newVal;\n\n if (isReactiveState(oldVal)) {\n oldUnwrapped = oldVal.value; // This triggers dependency tracking\n }\n if (isReactiveState(newVal)) {\n newUnwrapped = newVal.value; // This triggers dependency tracking\n }\n\n if (oldUnwrapped !== newUnwrapped) {\n anyChange = true;\n // Handle removal/null/false: remove attribute and clear corresponding\n // DOM property for native controls where Vue treats null/undefined as ''\n if (\n newUnwrapped === undefined ||\n newUnwrapped === null ||\n newUnwrapped === false\n ) {\n safe(() => {\n el.removeAttribute(key);\n });\n\n // Clear value for native controls when value is removed\n if (key === \"value\") {\n if (\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement\n ) {\n safe(() => {\n (el as any).value = \"\";\n });\n } else if (el instanceof HTMLSelectElement) {\n safe(() => {\n (el as any).value = \"\";\n });\n } else if (el instanceof HTMLProgressElement) {\n safe(() => {\n (el as any).value = 0;\n });\n }\n }\n\n // Clear checked for checkbox/radio\n if (key === \"checked\" && el instanceof HTMLInputElement) {\n safe(() => {\n el.checked = false;\n });\n }\n\n // Ensure disabled property is unset for native controls\n if (key === \"disabled\" && isNativeControl(el)) {\n safe(() => {\n (el as any).disabled = false;\n });\n }\n } else {\n // New value present: for native controls prefer assigning .value/.checked\n if (key === \"value\") {\n if (\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement\n ) {\n safe(() => {\n (el as any).value = newUnwrapped ?? \"\";\n });\n continue;\n } else if (el instanceof HTMLSelectElement) {\n safe(() => {\n (el as any).value = newUnwrapped ?? \"\";\n });\n continue;\n } else if (el instanceof HTMLProgressElement) {\n safe(() => {\n (el as any).value = Number(newUnwrapped);\n });\n continue;\n }\n }\n if (key === \"checked\" && el instanceof HTMLInputElement) {\n safe(() => {\n el.checked = !!newUnwrapped;\n });\n continue;\n }\n\n // Special handling for style attribute - always use setAttribute\n if (key === \"style\") {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n continue;\n }\n\n // Defensive handling for disabled when a new value is present\n if (key === \"disabled\" && isNativeControl(el)) {\n safe(() => {\n (el as any).disabled = coerceBooleanForNative(newUnwrapped);\n });\n if (!coerceBooleanForNative(newUnwrapped))\n safe(() => {\n el.removeAttribute(key);\n });\n else\n safe(() => {\n el.setAttribute(key, \"\");\n });\n continue;\n }\n\n // Non-native or generic attributes: prefer property when available\n const isSVG = (el as any).namespaceURI === \"http://www.w3.org/2000/svg\";\n\n // For custom elements, convert kebab-case attributes to camelCase properties\n // and prefer assigning ReactiveState instances directly to element\n // properties so child components that call useProps receive the\n // live ReactiveState (with .value) instead of a stale plain object.\n // However, preserve kebab-case class-like attributes (ending with\n // `-class`) as attributes so they remain visible in serialized\n // HTML (important for JIT CSS extraction). Only non-class-like\n // kebab attributes are promoted to camelCase props.\n if (elIsCustom && !isSVG && key.includes(\"-\")) {\n // For custom elements, prefer promoting kebab attributes to properties\n // except for class-like attributes which should remain attributes\n // for reliable HTML serialization. Use helpers to ensure safe string\n // serialization.\n if (isClassLikeAttr(key)) {\n const serialized = safeSerializeAttr(newVal ?? newUnwrapped);\n if (serialized !== null) {\n try {\n el.setAttribute(key, serialized);\n } catch (e) {\n /* best-effort */\n }\n }\n } else {\n const camelKey = toCamel(key);\n try {\n if (isReactiveState(newVal)) (el as any)[camelKey] = newVal;\n else (el as any)[camelKey] = newUnwrapped;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n const serialized = safeSerializeAttr(newVal ?? newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n } else if (!isSVG && key in el) {\n try {\n if (isReactiveState(newVal)) (el as any)[key] = newVal;\n else (el as any)[key] = newUnwrapped;\n } catch (e) {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n }\n }\n\n // If this is a custom element, attempt to notify it that props/attrs\n // were updated so it can re-run its internal applyProps logic and\n // schedule a render. This mirrors the behavior in createElement where\n // newly created custom elements are told to apply props and render.\n // Defensive: ensure native disabled property matches the intended source\n try {\n if (isNativeControl(el)) {\n const propCandidate = (mergedProps as any).disabled;\n // Only treat the propCandidate as the authoritative source when it's\n // a clear boolean-ish primitive or a reactive/wrapper we can unwrap.\n // Otherwise fallback to mergedAttrs to avoid arbitrary objects (proxies,\n // wrapper containers) from being treated as truthy and disabling native\n // controls.\n let sourceVal: any;\n try {\n // If the disabled was provided via a directive (processedDirectives)\n // or is a reactive/wrapper value we can safely prefer the prop.\n // Also accept clear boolean-ish primitive prop values as authoritative\n // so native inputs receive intended boolean state. Otherwise prefer\n // the attribute source to avoid arbitrary objects (proxies, wrapper\n // containers) from being treated as truthy and disabling native\n // controls.\n const hasDisabledInProcessed = Object.prototype.hasOwnProperty.call(\n processedDirectives.props || {},\n \"disabled\"\n );\n const isWrapper =\n propCandidate &&\n typeof propCandidate === \"object\" &&\n \"value\" in propCandidate;\n let isReactive = false;\n safe(() => {\n isReactive = !!isReactiveState(propCandidate);\n });\n const isBooleanish = isBooleanishForProps(propCandidate);\n if (isReactive || isWrapper || hasDisabledInProcessed || isBooleanish) {\n sourceVal = propCandidate;\n } else {\n sourceVal = (mergedAttrs as any).disabled;\n }\n } catch (e) {\n sourceVal = (mergedAttrs as any).disabled;\n }\n const finalDisabled = coerceBooleanForNative(sourceVal);\n safe(() => {\n (el as any).disabled = finalDisabled;\n });\n finalDisabled\n ? safe(() => {\n el.setAttribute(\"disabled\", \"\");\n })\n : safe(() => {\n el.removeAttribute(\"disabled\");\n });\n }\n } catch (e) {}\n\n if (elIsCustom && anyChange) {\n safe(() => {\n (el as any)._applyProps?.((el as any)._cfg);\n });\n safe(() => {\n if (typeof (el as any).requestRender === \"function\")\n (el as any).requestRender();\n else if (typeof (el as any)._render === \"function\")\n (el as any)._render((el as any)._cfg);\n });\n }\n}\n\n/**\n * Create a DOM element from a VNode.\n * @param vnode\n * @param context\n * @param refs\n * @returns\n */\nexport function createElement(\n vnode: VNode | string,\n context?: any,\n refs?: VDomRefs\n): Node {\n // String VNode → plain text node (no key)\n if (typeof vnode === \"string\") {\n return document.createTextNode(vnode);\n }\n\n // Text VNode\n if (vnode.tag === \"#text\") {\n const textNode = document.createTextNode(\n typeof vnode.children === \"string\" ? vnode.children : \"\"\n );\n if (vnode.key != null) setNodeKey(textNode, vnode.key); // attach key\n return textNode;\n }\n\n // Raw HTML vnode - insert provided HTML as nodes (unsafe: caller must opt-in)\n if (vnode.tag === \"#raw\") {\n const html = typeof vnode.children === \"string\" ? vnode.children : \"\";\n const range = document.createRange();\n // createContextualFragment is broadly supported and safe when used with\n // controlled input. We intentionally call it for opt-in raw HTML insertion.\n const frag = range.createContextualFragment(html);\n return frag;\n }\n\n // Anchor block VNode - ALWAYS create start/end boundaries\n if (vnode.tag === \"#anchor\") {\n const anchorVNode = vnode as AnchorBlockVNode;\n const children = Array.isArray(anchorVNode.children)\n ? anchorVNode.children\n : [];\n\n // Always create start/end markers for stable boundaries\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n\n if (anchorVNode.key != null) {\n setNodeKey(start, `${anchorVNode.key}:start`);\n setNodeKey(end, `${anchorVNode.key}:end`);\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n\n for (const child of children) {\n const childNode = createElement(child, context);\n // Propagate anchor block's key to child elements ONLY if child doesn't have its own key\n // This allows keyed lists (each()) to preserve their own keys\n if (\n anchorVNode.key != null &&\n childNode instanceof Element &&\n !childNode.hasAttribute(\"data-anchor-key\")\n ) {\n const childVNode = child as VNode;\n const childHasOwnKey =\n childVNode &&\n typeof childVNode === \"object\" &&\n childVNode.key != null;\n\n if (!childHasOwnKey) {\n setNodeKey(childNode, anchorVNode.key as any);\n }\n }\n frag.appendChild(childNode);\n }\n frag.appendChild(end);\n return frag;\n }\n\n // Standard element VNode\n const el = document.createElement(vnode.tag);\n if (vnode.key != null) setNodeKey(el, vnode.key);\n\n // Store TransitionGroup metadata on the DOM element for patchChildren to use\n if (vnode.props && (vnode.props as any)._transitionGroup) {\n setElementTransition(el, (vnode.props as any)._transitionGroup);\n }\n\n const { props = {}, attrs = {}, directives = {} } = vnode.props ?? {};\n\n // Process directives first to get merged props/attrs/listeners\n const processedDirectives = processDirectives(directives, context, el, attrs);\n\n // Merge processed directive results with existing props/attrs\n const mergedProps = {\n ...props,\n ...processedDirectives.props,\n };\n const mergedAttrs = {\n ...attrs,\n ...processedDirectives.attrs,\n };\n\n // Ensure any explicit string `class` provided on the vnode (static class)\n // is applied to the host element as a plain attribute. This guarantees\n // that parent serialized `innerHTML` includes user-specified utility\n // classes (important for JIT CSS extraction and tests). Use a safe\n // string coercion and ignore non-string values to avoid assigning\n // complex objects to DOM attributes which can throw in jsdom.\n try {\n const hostClass =\n (mergedAttrs && mergedAttrs.class) ??\n (mergedProps && mergedProps.class) ??\n (vnode.props && vnode.props.attrs && vnode.props.attrs.class) ??\n (vnode.props && vnode.props.props && vnode.props.props.class);\n const serializedHostClass = safeSerializeAttr(hostClass);\n if (serializedHostClass !== null) {\n const cls = String(serializedHostClass).trim();\n if (cls) el.setAttribute(\"class\", cls);\n }\n } catch (e) {}\n\n // Defensive: if the compiler (vnode.props) or earlier processing placed\n // a primitive `disabled` into props for a native input, move it to attrs\n // to avoid accidental truthiness causing native controls to be disabled.\n try {\n if (\n (mergedProps as any).disabled !== undefined &&\n el &&\n isNativeControl(el)\n ) {\n const candidate = (mergedProps as any).disabled;\n const isWrapper =\n candidate && typeof candidate === \"object\" && \"value\" in candidate;\n let isReactiveVal = false;\n try {\n isReactiveVal = isReactiveState(candidate);\n } catch (e) {\n isReactiveVal = false;\n }\n if (!isWrapper && !isReactiveVal) {\n safe(() => {\n (mergedAttrs as any).disabled = candidate;\n delete (mergedProps as any).disabled;\n });\n }\n }\n } catch (e) {}\n\n // Set attributes\n // Prefer property assignment for certain attributes (value/checked) and\n // when the element exposes a corresponding property. SVG elements should\n // keep attributes only.\n const isSVG = (el as any).namespaceURI === \"http://www.w3.org/2000/svg\";\n for (const key in mergedAttrs) {\n const val = mergedAttrs[key];\n // Only allow valid attribute names (string, not object)\n if (typeof key !== \"string\" || /\\[object Object\\]/.test(key)) {\n continue;\n }\n // Unwrap reactive-like wrappers (ReactiveState or { value }) to primitives\n const unwrappedVal =\n typeof val === \"object\" && val !== null && isReactiveState(val)\n ? (val as any).value\n : val && typeof val === \"object\" && \"value\" in val\n ? (val as any).value\n : val;\n\n if (typeof unwrappedVal === \"boolean\") {\n // Use the unwrapped boolean to decide presence of boolean attributes\n if (unwrappedVal) {\n el.setAttribute(key, \"\");\n } else {\n safe(() => {\n el.removeAttribute(key);\n });\n }\n } else if (unwrappedVal !== undefined && unwrappedVal !== null) {\n // For disabled attr on native inputs, coerce to boolean and set property\n if (key === \"disabled\" && isNativeControl(el)) {\n // Prefer props over attrs when deciding disabled state, but only when\n // the prop value is explicitly booleanish (boolean, numeric, or wrapper).\n // This avoids treating empty-string or arbitrary objects on props as\n // truthy which would incorrectly disable native controls.\n const propCandidate = (mergedProps as any).disabled;\n const sourceVal = isBooleanishForProps(propCandidate)\n ? propCandidate\n : unwrappedVal;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (el as any).disabled = final;\n });\n final\n ? safe(() => {\n el.setAttribute(key, \"\");\n })\n : safe(() => {\n el.removeAttribute(key);\n });\n // keep going (do not fallthrough to attribute string path)\n continue;\n }\n // Special-case value/checked for native inputs so .value/.checked are set\n if (\n !isSVG &&\n key === \"value\" &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLProgressElement)\n ) {\n try {\n // Progress expects numeric value\n if (el instanceof HTMLProgressElement)\n (el as any).value = Number(unwrappedVal);\n else el.value = unwrappedVal ?? \"\";\n } catch (e) {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else if (\n !isSVG &&\n key === \"checked\" &&\n el instanceof HTMLInputElement\n ) {\n try {\n el.checked = !!unwrappedVal;\n } catch (e) {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else if (!isSVG && key in el) {\n try {\n (el as any)[key] = unwrappedVal;\n // For native form controls, also remove the disabled attribute when setting disabled=false\n // The browser doesn't automatically sync the attribute when the property changes\n if (\n key === \"disabled\" &&\n unwrappedVal === false &&\n isNativeControl(el)\n ) {\n el.removeAttribute(\"disabled\");\n }\n } catch (e) {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n // For custom elements, convert kebab-case attributes to camelCase properties\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n if (vnodeIsCustom && !isSVG && key.includes(\"-\")) {\n const camelKey = toCamel(key);\n try {\n (el as any)[camelKey] = unwrappedVal;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n }\n }\n\n // Set props and event listeners\n for (const key in mergedProps) {\n const val = mergedProps[key];\n // Only allow valid attribute names (string, not object)\n if (typeof key !== \"string\" || /\\[object Object\\]/.test(key)) {\n // Skip invalid prop keys silently to keep runtime minimal\n continue;\n }\n if (\n key === \"value\" &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n // Check if val is a reactive state object and extract its value\n // Use the getter to ensure dependency tracking happens\n const propValue =\n typeof val === \"object\" &&\n val !== null &&\n typeof val.value !== \"undefined\"\n ? val.value\n : val;\n safe(() => {\n (el as any).value = propValue ?? \"\";\n });\n } else if (key.startsWith(\"on\") && typeof val === \"function\") {\n // If a directive already provided a listener for this event (for\n // example :model produced update:prop handlers), prefer the directive\n // listener and skip the prop-based handler. This avoids attaching\n // compiler-generated handlers that close over transient render-local\n // variables and later do nothing when events fire.\n const eventType = eventNameFromKey(key);\n // Also consider alternate camel/kebab variant when checking directive provided listeners\n const altEventType = eventType.includes(\":\")\n ? (() => {\n const parts = eventType.split(\":\");\n const prop = parts[1];\n if (prop.includes(\"-\")) {\n const camel = prop\n .split(\"-\")\n .map((p, i) =>\n i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1)\n )\n .join(\"\");\n return `${parts[0]}:${camel}`;\n } else {\n const kebab = prop\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .toLowerCase();\n return `${parts[0]}:${kebab}`;\n }\n })()\n : eventType;\n if (\n processedDirectives.listeners &&\n (processedDirectives.listeners[eventType] ||\n processedDirectives.listeners[altEventType])\n ) {\n // skip prop handler in favor of directive-provided listener\n } else {\n EventManager.addListener(el, eventType, val);\n }\n } else if (key.startsWith(\"on\") && val === undefined) {\n continue; // skip undefined event handlers\n } else if (val === undefined || val === null || val === false) {\n el.removeAttribute(key);\n } else {\n // Prefer setting DOM properties for custom elements or when the\n // property already exists on the element. This ensures JS properties\n // (and reactive custom element props) receive the value instead of\n // only an HTML attribute string. However, certain attributes like\n // `class` and `style` should remain HTML attributes on the host so\n // they show up in serialized `innerHTML` (important for JIT CSS\n // extraction and tests). Handle those as attributes explicitly.\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n // Compute propValue once for use in attribute/property assignment.\n const propValue =\n typeof val === \"object\" && val !== null && isReactiveState(val)\n ? val\n : typeof val === \"object\" &&\n val !== null &&\n typeof (val as any).value !== \"undefined\"\n ? (val as any).value\n : val;\n\n if (key === \"class\" || key === \"style\") {\n try {\n const serialized = safeSerializeAttr(propValue);\n if (serialized !== null) el.setAttribute(key, serialized);\n } catch (e) {}\n continue;\n }\n if (vnodeIsCustom || key in el) {\n try {\n // If this is a ReactiveState instance, assign the instance itself\n // to custom element properties so child components can call\n // useProps and receive the live ReactiveState (with .value).\n const propValue =\n typeof val === \"object\" && val !== null && isReactiveState(val)\n ? val\n : typeof val === \"object\" &&\n val !== null &&\n typeof val.value !== \"undefined\"\n ? val.value\n : val;\n // For native elements and the disabled prop, coerce to a boolean\n if (key === \"disabled\" && isNativeControl(el)) {\n const sourceVal =\n (mergedProps as any).disabled !== undefined\n ? (mergedProps as any).disabled\n : propValue;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (el as any).disabled = final;\n });\n final\n ? safe(() => {\n el.setAttribute(key, \"\");\n })\n : safe(() => {\n el.removeAttribute(key);\n });\n continue;\n }\n // Coerce boolean DOM properties to real booleans. This prevents\n // empty-string or 'false' string values from incorrectly enabling\n // properties like `disabled` during SSR/attribute promotions.\n try {\n const existingProp = (el as any)[key];\n if (typeof existingProp === \"boolean\") {\n let assignValue: any = propValue;\n if (typeof propValue === \"string\") {\n if (propValue === \"false\") assignValue = false;\n else if (propValue === \"true\") assignValue = true;\n else assignValue = !!propValue && propValue !== \"\";\n } else {\n assignValue = !!propValue;\n }\n (el as any)[key] = assignValue;\n } else {\n (el as any)[key] = propValue;\n }\n } catch (e) {\n (el as any)[key] = propValue;\n }\n } catch (err) {\n // silently skip on failure\n }\n } else {\n // silently skip when property doesn't exist\n }\n }\n }\n\n // Handle directive event listeners\n for (const [eventType, listener] of Object.entries(\n processedDirectives.listeners || {}\n )) {\n EventManager.addListener(el, eventType, listener as EventListener);\n }\n\n // Assign ref if present - create a vnode with processed props for ref assignment\n const vnodeWithProcessedProps = {\n ...vnode,\n props: {\n ...vnode.props,\n ...processedDirectives.props,\n },\n };\n assignRef(vnodeWithProcessedProps, el as HTMLElement, refs);\n\n // If this is a custom element instance, request an initial render now that\n // attributes/props/listeners have been applied. This fixes the common timing\n // issue where the element constructor rendered before the renderer set the\n // initial prop values (for example :model or :model:prop). Prefer the\n // public requestRender API when available, otherwise call internal _render\n // with the stored config.\n try {\n // If the element exposes an internal _applyProps, invoke it so the\n // component's reactive context picks up attributes/properties that were\n // just applied by the renderer. This is necessary when the component\n // constructor performs an initial render before the renderer sets props.\n if (typeof (el as any)._applyProps === \"function\") {\n try {\n (el as any)._applyProps((el as any)._cfg);\n } catch (e) {\n // ignore\n }\n }\n if (typeof (el as any).requestRender === \"function\") {\n (el as any).requestRender();\n } else if (typeof (el as any)._render === \"function\") {\n (el as any)._render((el as any)._cfg);\n }\n } catch (e) {\n // Swallow errors to keep the renderer robust and minimal.\n }\n\n // Append children\n if (Array.isArray(vnode.children)) {\n for (const child of vnode.children) {\n el.appendChild(createElement(child, context, refs));\n }\n } else if (typeof vnode.children === \"string\") {\n el.textContent = vnode.children;\n }\n\n // After children are appended, reapply select value selection if necessary.\n try {\n if (\n el instanceof HTMLSelectElement &&\n mergedAttrs &&\n mergedAttrs.hasOwnProperty(\"value\")\n ) {\n try {\n el.value = mergedAttrs[\"value\"] ?? \"\";\n } catch (e) {\n // ignore\n }\n }\n } catch (e) {\n // ignore\n }\n\n // Final defensive enforcement: ensure native controls are only disabled\n // when the authoritative source is a clear boolean-ish primitive or a\n // reactive/wrapper that unwraps to a boolean. This prevents transient\n // propagation of miscellaneous objects or compiler-promoted primitives\n // from leaving native inputs disabled on initial mount.\n try {\n if (isNativeControl(el)) {\n const propCandidate = (mergedProps as any).disabled;\n const attrCandidate = (mergedAttrs as any).disabled;\n const isWrapper =\n propCandidate &&\n typeof propCandidate === \"object\" &&\n \"value\" in propCandidate;\n let isReactive = false;\n try {\n isReactive = !!isReactiveState(propCandidate);\n } catch (e) {\n isReactive = false;\n }\n // choose authoritative source: prefer reactive/wrapper/booleanish propCandidate\n const useProp =\n isReactive || isWrapper || isBooleanishForProps(propCandidate);\n const sourceVal = useProp ? propCandidate : attrCandidate;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (el as any).disabled = final;\n });\n if (!final)\n safe(() => {\n el.removeAttribute(\"disabled\");\n });\n else\n safe(() => {\n el.setAttribute(\"disabled\", \"\");\n });\n }\n } catch (e) {}\n\n return el;\n}\n\n/**\n * Patch children using keys for node matching.\n * @param parent\n * @param oldChildren\n * @param newChildren\n * @param context\n * @param refs\n * @returns\n */\nexport function patchChildren(\n parent: HTMLElement,\n oldChildren: VNode[] | string | undefined,\n newChildren: VNode[] | string | undefined,\n context?: any,\n refs?: VDomRefs\n) {\n if (typeof newChildren === \"string\") {\n if (parent.textContent !== newChildren) parent.textContent = newChildren;\n return;\n }\n if (!Array.isArray(newChildren)) return;\n\n // Cache childNodes to avoid issues with live NodeList during mutations\n const oldNodeList = parent.childNodes;\n const oldNodesCache: Node[] = [];\n for (let i = 0; i < oldNodeList.length; i++) {\n oldNodesCache.push(oldNodeList[i]);\n }\n const oldVNodes: VNode[] = Array.isArray(oldChildren) ? oldChildren : [];\n\n // Check if parent has TransitionGroup metadata (use WeakMap-backed accessor)\n const transitionGroup = getElementTransition(parent as any as HTMLElement);\n\n // If TransitionGroup, flatten anchor blocks and handle as batch keyed diff\n if (transitionGroup) {\n // Helper to strip 'each-' prefix from keys for proper keyed diffing\n const stripKeyPrefix = (key: any): any => {\n return typeof key === \"string\" && key.startsWith(\"each-\")\n ? key.substring(5)\n : key;\n };\n\n const flattenedNew: VNode[] = [];\n const flattenedOldVNodes: VNode[] = [];\n\n // Flatten new children (extract from anchor blocks)\n for (const child of newChildren) {\n if (child && child.tag === \"#anchor\") {\n const anchorChildren = Array.isArray(child.children)\n ? child.children\n : [];\n for (const anchorChild of anchorChildren) {\n // Extract the actual item key from the anchor key\n const actualKey = stripKeyPrefix(\n anchorChild.key || child.key || \"unknown\"\n );\n flattenedNew.push({ ...anchorChild, key: actualKey });\n }\n } else if (child) {\n // Handle already-flattened children (from previous renders)\n flattenedNew.push({ ...child, key: stripKeyPrefix(child.key) });\n }\n }\n\n // Flatten old VNodes (extract from anchor blocks)\n for (const oldVNode of oldVNodes) {\n if (oldVNode && oldVNode.tag === \"#anchor\") {\n const anchorChildren = Array.isArray(oldVNode.children)\n ? oldVNode.children\n : [];\n for (const anchorChild of anchorChildren) {\n // Extract the actual item key from the anchor key\n const actualKey = stripKeyPrefix(\n anchorChild.key || oldVNode.key || \"unknown\"\n );\n flattenedOldVNodes.push({ ...anchorChild, key: actualKey });\n }\n } else if (oldVNode) {\n // Handle already-flattened children (from previous renders)\n flattenedOldVNodes.push({\n ...oldVNode,\n key: stripKeyPrefix(oldVNode.key),\n });\n }\n }\n\n // Now perform keyed diffing on flattened lists\n const hasKeys =\n flattenedNew.some((c) => c && c.key != null) ||\n flattenedOldVNodes.some((c) => c && c.key != null);\n\n if (hasKeys) {\n // Build maps for keyed diffing\n const oldVNodeByKeyFlat = new Map<string | number, VNode>();\n const oldNodeByKeyFlat = new Map<string | number, Node>();\n\n for (const v of flattenedOldVNodes) {\n if (v && v.key != null) {\n // Ensure key is a string for consistent comparison\n const key = String(v.key);\n oldVNodeByKeyFlat.set(key, v);\n }\n }\n\n // Map old DOM nodes by their keys with dual mapping for numeric/string keys\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n\n // Try multiple ways to find the key (WeakMap-backed accessor + attribute fallback)\n let nodeKey = getNodeKey(node);\n // Strip \"each-\" prefix from node keys to match flattened VNode keys\n nodeKey = stripKeyPrefix(nodeKey);\n\n // Skip text nodes and comment nodes without keys\n if (\n nodeKey != null &&\n node instanceof Element &&\n node.nodeType === Node.ELEMENT_NODE\n ) {\n // Extract the base key (remove :tagname suffix if present)\n let baseKey =\n typeof nodeKey === \"string\" && nodeKey.includes(\":\")\n ? nodeKey.substring(0, nodeKey.lastIndexOf(\":\"))\n : nodeKey;\n\n // Ensure key is a string for consistent comparison with VNode keys\n baseKey = String(baseKey);\n\n // Store with the base key (stripped of \"each-\" prefix to match VNode keys)\n oldNodeByKeyFlat.set(baseKey, node);\n }\n }\n\n const usedFlat = new Set<Node>();\n\n // PHASE 0: Record positions BEFORE any DOM modifications for FLIP animation\n // Only record if we have existing nodes to animate from\n const positionsBefore = new Map<Node, DOMRect>();\n const hadPreviousContent = oldNodesCache.length > 0;\n\n if (transitionGroup.moveClass && hadPreviousContent) {\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n if (node instanceof HTMLElement && node.parentElement) {\n const rect = node.getBoundingClientRect();\n // Record position even if dimensions are zero (test environments)\n positionsBefore.set(node, rect);\n }\n }\n }\n\n // PHASE 1: Identify which nodes to keep, create new nodes, but DON'T move anything yet\n const nodesToProcess: Array<{\n node: Node;\n key: string;\n newVNode: VNode;\n oldVNode?: VNode;\n isNew: boolean;\n }> = [];\n\n for (const newVNode of flattenedNew) {\n let key = newVNode.key;\n if (key == null) continue;\n\n // Ensure key is a string for consistent comparison\n key = String(key);\n\n const oldVNode = oldVNodeByKeyFlat.get(key);\n let node = oldNodeByKeyFlat.get(key);\n\n if (node && oldVNode) {\n // Existing node - patch it but don't move yet\n const patched = patch(node, oldVNode, newVNode, context);\n usedFlat.add(node);\n\n // Ensure the node has the correct key and attribute\n const keyStr = String(key);\n setNodeKey(patched, keyStr);\n\n nodesToProcess.push({\n node: patched,\n key,\n newVNode,\n oldVNode,\n isNew: false,\n });\n } else {\n // Create new node and insert it immediately (but invisible via enterFrom classes)\n node = createElement(newVNode, context);\n setNodeKey(node, key as any);\n\n // For new nodes, immediately insert them into DOM (at the end) and start enter transition\n // This ensures the transition can capture the correct FROM state\n parent.appendChild(node);\n\n // Only animate if: we had previous content to transition from OR appear is true\n // This prevents initial render items from animating (unless appear: true explicitly set)\n // but allows subsequent additions to animate\n const shouldAnimate =\n hadPreviousContent || transitionGroup.appear === true;\n\n if (node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transitionGroup).catch((err) => {\n devError(\"Enter transition error:\", err);\n });\n }\n\n nodesToProcess.push({ node, key, newVNode, isNew: true });\n }\n }\n\n const leaveTransitions: Promise<void>[] = [];\n\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n const nodeKey = getNodeKey(node);\n const isUsed = usedFlat.has(node);\n\n if (!isUsed && nodeKey != null && node instanceof HTMLElement) {\n const leavePromise = performLeaveTransition(node, transitionGroup)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError(\"Leave transition error:\", err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n leaveTransitions.push(leavePromise);\n }\n }\n\n // PHASE 3: Move nodes to correct positions and apply FLIP animations\n // SKIP if there are active leave transitions to prevent visual jumps\n if (leaveTransitions.length === 0) {\n // FLIP Animation for move transitions\n // Positions were already recorded in PHASE 0, now we just move and animate\n let currentPosition: Node | null = parent.firstChild;\n\n for (const { node } of nodesToProcess) {\n // Move node to correct position if needed\n if (node !== currentPosition) {\n parent.insertBefore(node, currentPosition);\n }\n currentPosition = node.nextSibling;\n }\n\n // Apply FLIP animation for moved items\n if (transitionGroup.moveClass && positionsBefore.size > 0) {\n // Collect elements that need to be animated\n const elementsToAnimate: Array<{\n node: HTMLElement;\n deltaX: number;\n deltaY: number;\n moveClasses: string[];\n }> = [];\n\n for (const { node, isNew } of nodesToProcess) {\n if (!isNew && node instanceof HTMLElement) {\n const oldPos = positionsBefore.get(node);\n if (oldPos) {\n const newPos = node.getBoundingClientRect();\n const deltaX = oldPos.left - newPos.left;\n const deltaY = oldPos.top - newPos.top;\n\n // If position changed, prepare for animation\n if (deltaX !== 0 || deltaY !== 0) {\n const moveClasses = transitionGroup.moveClass\n .split(/\\s+/)\n .filter((c: string) => c);\n elementsToAnimate.push({ node, deltaX, deltaY, moveClasses });\n }\n }\n }\n }\n\n if (elementsToAnimate.length > 0) {\n // FLIP Animation technique:\n // We need to ensure the browser paints the inverted state before animating\n // Step 1: Apply inverted transforms (without transition)\n for (const { node, deltaX, deltaY } of elementsToAnimate) {\n node.style.transform = `translate(${deltaX}px, ${deltaY}px)`;\n node.style.transitionProperty = \"none\";\n }\n\n // Step 2: Force reflow to ensure transforms are applied\n void parent.offsetHeight;\n\n // Step 3: Use triple RAF to ensure browser has:\n // 1. Painted the inverted state\n // 2. Applied the transition classes\n // 3. Ready to animate when transform is removed\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Add moveClass for transition properties\n for (const { node, moveClasses } of elementsToAnimate) {\n for (const cls of moveClasses) {\n node.classList.add(cls);\n }\n }\n\n // One more RAF to ensure transition classes are processed\n requestAnimationFrame(() => {\n // Set transition directly on each element\n // Parse moveClass to extract duration and timing\n const moveClassStr = transitionGroup.moveClass || \"\";\n const durationMatch = moveClassStr.match(/duration-(\\d+)/);\n const duration = durationMatch\n ? `${durationMatch[1]}ms`\n : \"300ms\";\n const easingMatch = moveClassStr.match(\n /ease-(out|in|in-out|linear)/\n );\n const easing = easingMatch\n ? `ease-${easingMatch[1]}`\n : \"ease-out\";\n\n for (const { node } of elementsToAnimate) {\n // Set transition inline to override everything\n // This sets transition-property, transition-duration, and transition-timing-function\n node.style.transition = `transform ${duration} ${easing}`;\n }\n\n // One final RAF before removing transform\n requestAnimationFrame(() => {\n // Now remove transforms to trigger animation\n for (const { node, moveClasses } of elementsToAnimate) {\n node.style.removeProperty(\"transform\");\n // Clean up moveClass after transition completes\n const cleanup = () => {\n for (const cls of moveClasses) {\n node.classList.remove(cls);\n }\n // Also remove the inline transition we set for move animation\n // This allows leave transitions to work properly\n node.style.removeProperty(\"transition\");\n node.removeEventListener(\"transitionend\", cleanup);\n node.removeEventListener(\"transitioncancel\", cleanup);\n };\n node.addEventListener(\"transitionend\", cleanup, {\n once: true,\n });\n node.addEventListener(\"transitioncancel\", cleanup, {\n once: true,\n });\n }\n });\n });\n });\n });\n }\n }\n }\n\n return; // Done with TransitionGroup keyed diffing\n }\n }\n\n // Map old VNodes by key\n const oldVNodeByKey = new Map<string | number, VNode>();\n for (const v of oldVNodes) {\n if (v && v.key != null) oldVNodeByKey.set(v.key, v);\n }\n\n // Map DOM nodes by key (elements, text, anchors)\n const oldNodeByKey = new Map<string | number, Node>();\n\n // Scan DOM for keyed nodes including anchor boundaries\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n const k = getNodeKey(node);\n if (k != null) {\n oldNodeByKey.set(k, node);\n }\n }\n\n const usedNodes = new Set<Node>();\n let nextSibling: Node | null = parent.firstChild;\n\n function markRangeUsed(start: Comment, end?: Comment) {\n let cur: Node | null = start;\n while (cur) {\n usedNodes.add(cur);\n if (cur === end) break;\n cur = cur.nextSibling;\n }\n }\n\n function patchChildrenBetween(\n start: Comment,\n end: Comment,\n oldChildren: VNode[] | undefined,\n newChildren: VNode[],\n transition?: any,\n shouldAnimate = true\n ) {\n const oldNodesInRange: Node[] = [];\n let cur: Node | null = start.nextSibling;\n while (cur && cur !== end) {\n oldNodesInRange.push(cur);\n cur = cur.nextSibling;\n }\n\n const oldVNodesInRange: VNode[] = Array.isArray(oldChildren)\n ? oldChildren\n : [];\n const hasKeys =\n newChildren.some((c) => c && c.key != null) ||\n oldVNodesInRange.some((c) => c && c.key != null);\n\n if (hasKeys) {\n // Keyed diff\n const oldVNodeByKeyRange = new Map<string | number, VNode>();\n const oldNodeByKeyRange = new Map<string | number, Node>();\n\n for (const v of oldVNodesInRange) {\n if (v && v.key != null) oldVNodeByKeyRange.set(v.key, v);\n }\n for (const node of oldNodesInRange) {\n const k = getNodeKey(node);\n if (k != null) oldNodeByKeyRange.set(k, node);\n }\n\n // Calculate if this is initial visible render (for appear transitions)\n const isInitialVisible =\n transition &&\n transition.state === \"visible\" &&\n oldVNodesInRange.length === 0 &&\n newChildren.length > 0;\n\n const usedInRange = new Set<Node>();\n let next: Node | null = start.nextSibling;\n\n for (const newVNode of newChildren) {\n let node: Node;\n if (newVNode.key != null && oldNodeByKeyRange.has(newVNode.key)) {\n const oldVNode = oldVNodeByKeyRange.get(newVNode.key)!;\n node = patch(\n oldNodeByKeyRange.get(newVNode.key)!,\n oldVNode,\n newVNode,\n context\n );\n usedInRange.add(node);\n\n // Apply enter transition to patched nodes if this is initial visible render with appear: true\n if (\n transition &&\n node instanceof HTMLElement &&\n isInitialVisible &&\n transition.appear\n ) {\n performEnterTransition(node, transition).catch((err) => {\n devError(\"Transition enter error (appear):\", err);\n });\n }\n\n if (node !== next && parent.contains(node)) {\n parent.insertBefore(node, next);\n }\n } else {\n node = createElement(newVNode, context);\n parent.insertBefore(node, next);\n usedInRange.add(node);\n\n // Apply enter transition to new nodes ONLY if shouldAnimate is true\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transition).catch((err) => {\n devError(\"Transition enter error:\", err);\n });\n }\n }\n next = node.nextSibling;\n }\n\n for (const node of oldNodesInRange) {\n if (!usedInRange.has(node) && parent.contains(node)) {\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n // Apply leave transition before removing\n performLeaveTransition(node, transition)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError(\"Transition leave error:\", err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n } else {\n parent.removeChild(node);\n }\n }\n }\n } else {\n // Keyless: fall back to index-based patch\n const commonLength = Math.min(\n oldVNodesInRange.length,\n newChildren.length\n );\n\n for (let i = 0; i < commonLength; i++) {\n const oldVNode = oldVNodesInRange[i];\n const newVNode = newChildren[i];\n const node = patch(oldNodesInRange[i], oldVNode, newVNode, context);\n if (node !== oldNodesInRange[i]) {\n parent.insertBefore(node, oldNodesInRange[i]);\n parent.removeChild(oldNodesInRange[i]);\n }\n }\n\n // Add extra new\n for (let i = commonLength; i < newChildren.length; i++) {\n const node = createElement(newChildren[i], context);\n parent.insertBefore(node, end);\n\n // Apply enter transition to new nodes ONLY if shouldAnimate is true\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transition).catch((err) => {\n devError(\"Transition enter error:\", err);\n });\n }\n }\n\n // Remove extra old\n for (let i = commonLength; i < oldNodesInRange.length; i++) {\n const node = oldNodesInRange[i];\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n // Apply leave transition before removing\n performLeaveTransition(node, transition)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError(\"Transition leave error:\", err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n } else {\n parent.removeChild(node);\n }\n }\n }\n }\n\n for (const newVNode of newChildren) {\n let node: Node;\n\n // Handle AnchorBlocks\n if (newVNode.tag === \"#anchor\") {\n const aKey = newVNode.key!;\n const startKey = `${aKey}:start`;\n const endKey = `${aKey}:end`;\n\n let start = oldNodeByKey.get(startKey) as Node;\n let end = oldNodeByKey.get(endKey) as Node;\n const children = Array.isArray(newVNode.children)\n ? newVNode.children\n : [];\n\n // Create boundaries if they don't exist\n if (!start) {\n start = document.createTextNode(\"\");\n setNodeKey(start, startKey);\n }\n if (!end) {\n end = document.createTextNode(\"\");\n setNodeKey(end, endKey);\n }\n\n // Preserve anchor references on the new VNode\n (newVNode as AnchorBlockVNode)._startNode = start as Comment;\n (newVNode as AnchorBlockVNode)._endNode = end as Comment;\n\n // If boundaries aren't in DOM, insert the whole fragment\n if (!parent.contains(start) || !parent.contains(end)) {\n parent.insertBefore(start, nextSibling);\n const transition = (newVNode as any)._transition;\n\n // Determine if we should animate:\n // - If transition.state === 'visible' and children.length > 0, this is initial visible state\n // → only animate if appear: true\n // - If transition.state === 'hidden' and children.length === 0, this is initial hidden state\n // → don't animate (nothing to animate)\n // - Otherwise, this is a state change → always animate\n const isInitialVisible =\n transition && transition.state === \"visible\" && children.length > 0;\n const shouldAnimate = !isInitialVisible || transition.appear;\n\n for (const child of children) {\n const childNode = createElement(child, context);\n parent.insertBefore(childNode, nextSibling);\n\n // Apply enter transitions to new nodes ONLY if shouldAnimate is true\n if (transition && childNode instanceof HTMLElement) {\n if (shouldAnimate) {\n performEnterTransition(childNode, transition).catch((err) => {\n devError(\"Transition enter error:\", err);\n });\n }\n }\n }\n parent.insertBefore(end, nextSibling);\n } else {\n // Patch children between existing boundaries\n const transition = (newVNode as any)._transition;\n const oldVNode = oldVNodeByKey.get(aKey) as VNode;\n const oldTransition = (oldVNode as any)?._transition;\n\n // Determine if we should animate:\n // - If this is a state change (hidden → visible or visible → hidden), always animate\n // - If this is initial render with state='visible', only animate if appear: true\n const isStateChange =\n oldTransition && oldTransition.state !== transition?.state;\n const isInitialVisible =\n transition &&\n transition.state === \"visible\" &&\n children.length > 0 &&\n !isStateChange;\n const shouldAnimate =\n isStateChange || !isInitialVisible || transition?.appear === true;\n\n patchChildrenBetween(\n start as Comment,\n end as Comment,\n (oldVNodeByKey.get(aKey) as VNode)?.children as VNode[] | undefined,\n children,\n transition,\n shouldAnimate\n );\n }\n\n markRangeUsed(start as Comment, end as Comment);\n nextSibling = end.nextSibling;\n continue;\n }\n\n // Normal keyed element/text\n if (newVNode.key != null && oldNodeByKey.has(newVNode.key)) {\n const oldVNode = oldVNodeByKey.get(newVNode.key)!;\n node = patch(\n oldNodeByKey.get(newVNode.key)!,\n oldVNode,\n newVNode,\n context,\n refs\n );\n usedNodes.add(node);\n if (node !== nextSibling && parent.contains(node)) {\n if (nextSibling && !parent.contains(nextSibling)) nextSibling = null;\n parent.insertBefore(node, nextSibling);\n }\n } else {\n node = createElement(newVNode, context, refs);\n if (nextSibling && !parent.contains(nextSibling)) nextSibling = null;\n parent.insertBefore(node, nextSibling);\n usedNodes.add(node);\n }\n\n nextSibling = node.nextSibling;\n }\n\n // Remove unused nodes (use cached array to avoid live NodeList issues)\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n if (!usedNodes.has(node) && parent.contains(node)) {\n cleanupRefs(node, refs);\n parent.removeChild(node);\n }\n }\n}\n\n/**\n * Patch a node using keys for node matching.\n * @param dom\n * @param oldVNode\n * @param newVNode\n * @param context\n * @param refs\n * @returns\n */\nexport function patch(\n dom: Node,\n oldVNode: VNode | string | null,\n newVNode: VNode | string | null,\n context?: any,\n refs?: VDomRefs\n): Node {\n if (oldVNode && typeof oldVNode !== \"string\" && oldVNode.props?.ref && refs) {\n cleanupRefs(dom, refs); // Clean up old ref and descendants\n }\n\n if (oldVNode === newVNode) return dom;\n\n if (typeof newVNode === \"string\") {\n if (dom.nodeType === Node.TEXT_NODE) {\n if (dom.textContent !== newVNode) dom.textContent = newVNode;\n return dom;\n } else {\n const textNode = document.createTextNode(newVNode);\n dom.parentNode?.replaceChild(textNode, dom);\n return textNode;\n }\n }\n\n if (newVNode && typeof newVNode !== \"string\" && newVNode.tag === \"#anchor\") {\n const anchorVNode = newVNode as AnchorBlockVNode;\n const children = Array.isArray(anchorVNode.children)\n ? anchorVNode.children\n : [];\n const start = anchorVNode._startNode ?? document.createTextNode(\"\");\n const end = anchorVNode._endNode ?? document.createTextNode(\"\");\n if (anchorVNode.key != null) {\n setNodeKey(start, `${anchorVNode.key}:start`);\n setNodeKey(end, `${anchorVNode.key}:end`);\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n for (const child of children) {\n const childNode = createElement(child, context);\n frag.appendChild(childNode);\n }\n frag.appendChild(end);\n dom.parentNode?.replaceChild(frag, dom);\n return start;\n }\n\n if (!newVNode) {\n cleanupRefs(dom, refs);\n const placeholder = document.createComment(\"removed\");\n dom.parentNode?.replaceChild(placeholder, dom);\n return placeholder;\n }\n\n if (!oldVNode || typeof oldVNode === \"string\") {\n cleanupRefs(dom, refs);\n const newEl = createElement(newVNode, context, refs);\n assignRef(newVNode, newEl as HTMLElement, refs);\n dom.parentNode?.replaceChild(newEl, dom);\n return newEl;\n }\n\n if (newVNode.tag === \"#anchor\") {\n const children = Array.isArray(newVNode.children) ? newVNode.children : [];\n const start = (newVNode as any)._startNode ?? document.createTextNode(\"\");\n const end = (newVNode as any)._endNode ?? document.createTextNode(\"\");\n\n if (newVNode.key != null) {\n setNodeKey(start, `${newVNode.key}:start`);\n setNodeKey(end, `${newVNode.key}:end`);\n }\n\n (newVNode as any)._startNode = start;\n (newVNode as any)._endNode = end;\n\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n for (const child of children) {\n frag.appendChild(createElement(child, context));\n }\n frag.appendChild(end);\n dom.parentNode?.replaceChild(frag, dom);\n return start;\n }\n\n if (\n typeof oldVNode !== \"string\" &&\n typeof newVNode !== \"string\" &&\n oldVNode.tag === newVNode.tag &&\n oldVNode.key === newVNode.key\n ) {\n const el = dom as HTMLElement;\n patchProps(el, oldVNode.props || {}, newVNode.props || {}, context);\n patchChildren(el, oldVNode.children, newVNode.children, context, refs); // <-- Pass refs\n assignRef(newVNode, el, refs);\n return el;\n }\n\n // If the tag matches but the key changed, prefer to patch in-place for\n // custom elements to avoid remounting their internals. This handles cases\n // where compiler promotion or key churn causes vnode keys to differ even\n // though the DOM element should remain the same instance.\n if (\n typeof oldVNode !== \"string\" &&\n typeof newVNode !== \"string\" &&\n oldVNode.tag === newVNode.tag\n ) {\n const isCustomTag =\n (oldVNode.tag && String(oldVNode.tag).includes(\"-\")) ||\n (newVNode.props && (newVNode.props as any).isCustomElement) ||\n (oldVNode.props && (oldVNode.props as any).isCustomElement);\n if (isCustomTag) {\n try {\n const el = dom as HTMLElement;\n patchProps(el, oldVNode.props || {}, newVNode.props || {}, context);\n // For custom elements, their internal rendering is managed by the\n // element itself; do not touch children here.\n assignRef(newVNode, el, refs);\n return el;\n } catch (e) {\n // fall through to full replace on error\n }\n }\n }\n\n cleanupRefs(dom, refs);\n const newEl = createElement(newVNode, context, refs);\n assignRef(newVNode, newEl as HTMLElement, refs);\n dom.parentNode?.replaceChild(newEl, dom);\n return newEl;\n}\n\n/**\n * Virtual DOM renderer.\n * @param root The root element to render into.\n * @param vnodeOrArray The virtual node or array of virtual nodes to render.\n * @param context The context to use for rendering.\n * @param refs The refs to use for rendering.\n */\nexport function vdomRenderer(\n root: ShadowRoot,\n vnodeOrArray: VNode | VNode[],\n context?: any,\n refs?: VDomRefs\n) {\n let newVNode: VNode;\n if (Array.isArray(vnodeOrArray)) {\n if (vnodeOrArray.length === 1) {\n newVNode = vnodeOrArray[0];\n if (newVNode && typeof newVNode === \"object\" && newVNode.key == null) {\n newVNode = { ...newVNode, key: \"__root__\" };\n }\n } else {\n newVNode = { tag: \"div\", key: \"__root__\", children: vnodeOrArray };\n }\n } else {\n newVNode = vnodeOrArray;\n if (newVNode && typeof newVNode === \"object\" && newVNode.key == null) {\n newVNode = { ...newVNode, key: \"__root__\" };\n }\n }\n\n // If the root is an AnchorBlock, wrap it in a real element for DOM insertion\n if (newVNode && typeof newVNode === \"object\" && newVNode.tag === \"#anchor\") {\n newVNode = {\n tag: \"div\",\n key: \"__anchor_root__\",\n props: {\n attrs: { \"data-anchor-block-root\": \"\", key: \"__anchor_root__\" },\n },\n children: [newVNode],\n };\n }\n\n newVNode = assignKeysDeep(newVNode, String(newVNode.key ?? \"root\")) as VNode;\n\n // Track previous VNode and DOM node\n const prevVNode: VNode | null = (root as any)._prevVNode ?? null;\n const prevDom: Node | null =\n (root as any)._prevDom ?? root.firstChild ?? null;\n\n let newDom: Node;\n\n if (prevVNode && prevDom) {\n // Only replace if tag or key changed\n if (\n typeof prevVNode !== \"string\" &&\n typeof newVNode !== \"string\" &&\n prevVNode.tag === newVNode.tag &&\n prevVNode.key === newVNode.key\n ) {\n newDom = patch(prevDom, prevVNode, newVNode, context, refs);\n } else {\n newDom = createElement(newVNode, context, refs);\n root.replaceChild(newDom, prevDom);\n }\n } else {\n newDom = createElement(newVNode, context, refs);\n if (root.firstChild) root.replaceChild(newDom, root.firstChild);\n else root.appendChild(newDom);\n }\n\n // Remove any extra nodes, but preserve style elements\n const nodesToRemove: Node[] = [];\n for (let i = 0; i < root.childNodes.length; i++) {\n const node = root.childNodes[i];\n if (node !== newDom && node.nodeName !== \"STYLE\") {\n cleanupRefs(node, refs);\n nodesToRemove.push(node);\n }\n }\n nodesToRemove.forEach((node) => root.removeChild(node));\n\n // Update tracked VNode and DOM node\n (root as any)._prevVNode = newVNode;\n (root as any)._prevDom = newDom;\n}\n\n/**\n * Render a VNode to a string.\n * @param vnode The virtual node to render.\n * @returns The rendered HTML string.\n */\nexport function renderToString(vnode: VNode): string {\n if (typeof vnode === \"string\") return escapeHTML(vnode) as string;\n\n if (vnode.tag === \"#text\") {\n return typeof vnode.children === \"string\"\n ? (escapeHTML(vnode.children) as string)\n : \"\";\n }\n\n if (vnode.tag === \"#anchor\") {\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter(Boolean)\n : [];\n return children.map(renderToString).join(\"\");\n }\n\n if (vnode.tag === \"#raw\") {\n return typeof vnode.children === \"string\" ? vnode.children : \"\";\n }\n\n // Collect attributes from props.attrs\n let attrsString = \"\";\n if (vnode.props && vnode.props.attrs) {\n attrsString = Object.entries(vnode.props.attrs)\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join(\"\");\n }\n\n // Note: vnode.props may contain a nested `props` object for runtime-only\n // values (functions, reactive state, directives). We intentionally only\n // serialize HTML attributes collected under `props.attrs` above so that\n // runtime-only values aren't emitted into SSR output.\n\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter(Boolean).map(renderToString).join(\"\")\n : typeof vnode.children === \"string\"\n ? escapeHTML(vnode.children)\n : vnode.children\n ? renderToString(vnode.children)\n : \"\";\n\n return `<${vnode.tag}${attrsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * Optimized JIT CSS implementation with reduced bloat and enhanced utilities\n */\n\n/**\n * CSS template literal\n */\nexport function css(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): string {\n let result = \"\";\n for (let i = 0; i < strings.length; i++) {\n result += strings[i];\n if (i < values.length) result += values[i];\n }\n return result;\n}\n\n/**\n * CSS minification utility (basic)\n */\nexport function minifyCSS(css: string): string {\n return css\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/\\s+/g, \" \")\n .replace(/\\s*([{}:;,>+~])\\s*/g, \"$1\")\n .replace(/;}/g, \"}\")\n .trim();\n}\n\n// --- Shared baseReset stylesheet ---\nlet baseResetSheet: CSSStyleSheet | null = null;\nexport function getBaseResetSheet(): CSSStyleSheet {\n if (!baseResetSheet) {\n baseResetSheet = new CSSStyleSheet();\n baseResetSheet.replaceSync(minifyCSS(baseReset));\n }\n return baseResetSheet;\n}\n\nexport function sanitizeCSS(css: string): string {\n return css\n .replace(/url\\s*\\(\\s*['\"]?javascript:[^)]*\\)/gi, \"\")\n .replace(/<script[\\s\\S]*?>[\\s\\S]*?<\\/script>/gi, \"\")\n .replace(/expression\\s*\\([^)]*\\)/gi, \"\");\n}\n\nexport const baseReset = css`\n :host,\n *,\n ::before,\n ::after {\n all: isolate;\n box-sizing: border-box;\n border: 0 solid currentColor;\n margin: 0;\n padding: 0;\n font: inherit;\n vertical-align: baseline;\n background: transparent;\n color: inherit;\n -webkit-tap-highlight-color: transparent;\n }\n :host {\n display: contents;\n font: 16px/1.5 var(--font-sans, ui-sans-serif, system-ui, sans-serif);\n /* Default CE line-height variable so leading-* can reliably override */\n --ce-line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n text-size-adjust: 100%;\n /* Default gradient variables to avoid undefined var() usage in generated utilities */\n --ce-gradient-from-position: 0%;\n --ce-gradient-to-position: 100%;\n --ce-gradient-via-position: 50%;\n --ce-gradient-from: rgba(255,255,255,0);\n --ce-gradient-to: rgba(255,255,255,0);\n --ce-gradient-stops: var(--ce-gradient-from), var(--ce-gradient-to);\n }\n button,\n input,\n select,\n textarea {\n background: transparent;\n outline: none;\n }\n textarea {\n resize: vertical;\n }\n progress {\n vertical-align: baseline;\n }\n button,\n textarea {\n overflow: visible;\n }\n img,\n svg,\n video,\n canvas,\n audio,\n iframe,\n embed,\n object {\n display: block;\n max-width: 100%;\n height: auto;\n }\n svg {\n fill: currentColor;\n stroke: none;\n }\n a {\n text-decoration: inherit;\n cursor: pointer;\n }\n button,\n [type=\"button\"],\n [type=\"reset\"],\n [type=\"submit\"] {\n cursor: pointer;\n appearance: button;\n background: none;\n -webkit-user-select: none;\n user-select: none;\n }\n ::-webkit-input-placeholder,\n ::placeholder {\n color: inherit;\n opacity: 0.5;\n }\n *:focus-visible {\n outline: 2px solid var(--color-primary-500, #3b82f6);\n outline-offset: 2px;\n }\n ol,\n ul {\n list-style: none;\n }\n table {\n border-collapse: collapse;\n }\n sub,\n sup {\n font-size: 0.75em;\n line-height: 0;\n position: relative;\n }\n sub {\n bottom: -0.25em;\n }\n sup {\n top: -0.5em;\n }\n [disabled],\n [aria-disabled=\"true\"] {\n cursor: not-allowed;\n }\n [hidden] {\n display: none;\n }\n`;\n\n// Types\ntype CSSMap = Record<string, string>;\ntype SelectorVariantMap = Record<\n string,\n (selector: string, body: string) => string\n>;\ntype MediaVariantMap = Record<string, string>;\n\ntype Shade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950;\ntype ColorShades = Partial<Record<Shade, string>> & { DEFAULT?: string };\n\n// Enhanced color system with standard Tailwind colors\nconst fallbackHex: Record<string, ColorShades> = {\n // Existing semantic colors\n neutral: {\n 50: \"#fafafa\",\n 100: \"#f4f4f5\",\n 200: \"#e4e4e7\",\n 300: \"#d4d4d8\",\n 400: \"#9f9fa9\",\n 500: \"#71717b\",\n 600: \"#52525c\",\n 700: \"#3f3f46\",\n 800: \"#27272a\",\n 900: \"#18181b\",\n 950: \"#09090b\",\n },\n primary: {\n 50: \"#eff6ff\",\n 100: \"#dbeafe\",\n 200: \"#bfdbfe\",\n 300: \"#93c5fd\",\n 400: \"#60a5fa\",\n 500: \"#3b82f6\",\n 600: \"#2563eb\",\n 700: \"#1d4ed8\",\n 800: \"#1e40af\",\n 900: \"#1e3a8a\",\n 950: \"#172554\",\n },\n secondary: {\n 50: \"#eef2ff\",\n 100: \"#e0e7ff\",\n 200: \"#c7d2fe\",\n 300: \"#a5b4fc\",\n 400: \"#818cf8\",\n 500: \"#6366f1\",\n 600: \"#4f46e5\",\n 700: \"#4338ca\",\n 800: \"#3730a3\",\n 900: \"#312e81\",\n 950: \"#1e1b4b\",\n },\n success: {\n 50: \"#f0fdf4\",\n 100: \"#dcfce7\",\n 200: \"#bbf7d0\",\n 300: \"#86efac\",\n 400: \"#4ade80\",\n 500: \"#22c55e\",\n 600: \"#16a34a\",\n 700: \"#15803d\",\n 800: \"#166534\",\n 900: \"#14532d\",\n 950: \"#052e16\",\n },\n info: {\n 50: \"#f0f9ff\",\n 100: \"#e0f2fe\",\n 200: \"#bae6fd\",\n 300: \"#7dd3fc\",\n 400: \"#38bdf8\",\n 500: \"#0ea5e9\",\n 600: \"#0284c7\",\n 700: \"#0369a1\",\n 800: \"#075985\",\n 900: \"#0c4a6e\",\n 950: \"#082f49\",\n },\n warning: {\n 50: \"#fffbeb\",\n 100: \"#fef3c7\",\n 200: \"#fde68a\",\n 300: \"#fcd34d\",\n 400: \"#fbbf24\",\n 500: \"#f59e0b\",\n 600: \"#d97706\",\n 700: \"#b45309\",\n 800: \"#92400e\",\n 900: \"#78350f\",\n 950: \"#451a03\",\n },\n error: {\n 50: \"#fef2f2\",\n 100: \"#fee2e2\",\n 200: \"#fecaca\",\n 300: \"#fca5a5\",\n 400: \"#f87171\",\n 500: \"#ef4444\",\n 600: \"#dc2626\",\n 700: \"#b91c1c\",\n 800: \"#991b1b\",\n 900: \"#7f1d1d\",\n 950: \"#450a0a\",\n },\n\n // Special colors\n white: { DEFAULT: \"#ffffff\" },\n black: { DEFAULT: \"#000000\" },\n transparent: { DEFAULT: \"transparent\" },\n current: { DEFAULT: \"currentColor\" },\n};\n\nexport const colors: Record<\n string,\n Record<string, string>\n> = Object.fromEntries(\n Object.entries(fallbackHex).map(([name, shades]) => [\n name,\n Object.fromEntries(\n Object.entries(shades).map(([shade, hex]) => [\n shade,\n `var(--color-${name}${shade === \"DEFAULT\" ? \"\" : `-${shade}`}, ${hex})`,\n ]),\n ),\n ]),\n);\n\nexport const spacing = \"0.25rem\";\n\nconst semanticSizes: Record<string, number> = {\n \"3xs\": 64,\n \"2xs\": 72,\n xs: 80,\n sm: 96,\n md: 112,\n lg: 128,\n xl: 144,\n \"2xl\": 168,\n \"3xl\": 192,\n \"4xl\": 224,\n \"5xl\": 256,\n \"6xl\": 288,\n \"7xl\": 320,\n};\n\n// Property mappings for spacing utilities\nexport const spacingProps: Record<string, string[]> = {\n m: [\"margin\"],\n mx: [\"margin-inline\"],\n my: [\"margin-block\"],\n mt: [\"margin-top\"],\n mr: [\"margin-right\"],\n mb: [\"margin-bottom\"],\n ml: [\"margin-left\"],\n p: [\"padding\"],\n px: [\"padding-inline\"],\n py: [\"padding-block\"],\n pt: [\"padding-top\"],\n pr: [\"padding-right\"],\n pb: [\"padding-bottom\"],\n pl: [\"padding-left\"],\n inset: [\"inset\"],\n \"inset-x\": [\"inset-inline\"],\n \"inset-y\": [\"inset-block\"],\n h: [\"height\"],\n w: [\"width\"],\n \"min-h\": [\"min-height\"],\n \"min-w\": [\"min-width\"],\n \"max-h\": [\"max-height\"],\n \"max-w\": [\"max-width\"],\n top: [\"top\"],\n bottom: [\"bottom\"],\n left: [\"left\"],\n right: [\"right\"],\n gap: [\"gap\"],\n \"gap-x\": [\"column-gap\"],\n \"gap-y\": [\"row-gap\"],\n};\n\n// Utility generators for reduced code bloat\nconst generateUtilities = (): CSSMap => {\n const utils: CSSMap = {};\n\n // Add @container utility\n utils[\"@container\"] = \"container-type:inline-size;\";\n\n // Core display utilities\n const display = [\n \"block\",\n \"inline\",\n \"inline-block\",\n \"flex\",\n \"inline-flex\",\n \"grid\",\n \"inline-grid\",\n \"table\",\n \"table-cell\",\n \"table-row\",\n \"hidden\",\n ];\n display.forEach((d) => {\n utils[d] = d === \"hidden\" ? \"display:none;\" : `display:${d};`;\n });\n\n // Position utilities\n [\"absolute\", \"relative\", \"fixed\", \"sticky\", \"static\"].forEach((p) => {\n utils[p] = `position:${p};`;\n });\n\n // Flex utilities\n Object.assign(utils, {\n \"items-center\": \"align-items:center;\",\n \"items-start\": \"align-items:flex-start;\",\n \"items-end\": \"align-items:flex-end;\",\n \"items-baseline\": \"align-items:baseline;\",\n \"items-stretch\": \"align-items:stretch;\",\n \"justify-center\": \"justify-content:center;\",\n \"justify-start\": \"justify-content:flex-start;\",\n \"justify-between\": \"justify-content:space-between;\",\n \"justify-around\": \"justify-content:space-around;\",\n \"justify-evenly\": \"justify-content:space-evenly;\",\n \"justify-end\": \"justify-content:flex-end;\",\n \"flex-wrap\": \"flex-wrap:wrap;\",\n \"flex-nowrap\": \"flex-wrap:nowrap;\",\n \"flex-wrap-reverse\": \"flex-wrap:wrap-reverse;\",\n \"content-center\": \"align-content:center;\",\n \"content-start\": \"align-content:flex-start;\",\n \"content-end\": \"align-content:flex-end;\",\n \"content-between\": \"align-content:space-between;\",\n \"content-around\": \"align-content:space-around;\",\n \"content-evenly\": \"align-content:space-evenly;\",\n \"content-stretch\": \"align-content:stretch;\",\n \"self-auto\": \"align-self:auto;\",\n \"self-start\": \"align-self:flex-start;\",\n \"self-end\": \"align-self:flex-end;\",\n \"self-center\": \"align-self:center;\",\n \"self-stretch\": \"align-self:stretch;\",\n \"flex-col\": \"flex-direction:column;\",\n \"flex-row\": \"flex-direction:row;\",\n \"flex-col-reverse\": \"flex-direction:column-reverse;\",\n \"flex-row-reverse\": \"flex-direction:row-reverse;\",\n \"flex-1\": \"flex:1 1 0%;\",\n \"flex-auto\": \"flex:1 1 auto;\",\n \"flex-initial\": \"flex:0 1 auto;\",\n \"flex-none\": \"flex:0 0 auto;\",\n grow: \"flex-grow:1;\",\n shrink: \"flex-shrink:1;\",\n \"grow-0\": \"flex-grow:0;\",\n \"shrink-0\": \"flex-shrink:0;\",\n });\n\n // Grid utilities\n for (let i = 1; i <= 12; i++) {\n utils[`grid-cols-${i}`] =\n `grid-template-columns:repeat(${i},minmax(0,1fr));`;\n utils[`grid-rows-${i}`] = `grid-template-rows:repeat(${i},minmax(0,1fr));`;\n utils[`col-span-${i}`] = `grid-column:span ${i} / span ${i};`;\n utils[`row-span-${i}`] = `grid-row:span ${i} / span ${i};`;\n utils[`col-start-${i}`] = `grid-column-start:${i};`;\n utils[`col-end-${i}`] = `grid-column-end:${i};`;\n utils[`row-start-${i}`] = `grid-row-start:${i};`;\n utils[`row-end-${i}`] = `grid-row-end:${i};`;\n }\n Object.assign(utils, {\n \"grid-cols-none\": \"grid-template-columns:none;\",\n \"grid-rows-none\": \"grid-template-rows:none;\",\n \"col-span-full\": \"grid-column:1 / -1;\",\n \"row-span-full\": \"grid-row:1 / -1;\",\n \"auto-cols-auto\": \"grid-auto-columns:auto;\",\n \"auto-cols-min\": \"grid-auto-columns:min-content;\",\n \"auto-cols-max\": \"grid-auto-columns:max-content;\",\n \"auto-cols-fr\": \"grid-auto-columns:1fr;\",\n \"auto-rows-auto\": \"grid-auto-rows:auto;\",\n \"auto-rows-min\": \"grid-auto-rows:min-content;\",\n \"auto-rows-max\": \"grid-auto-rows:max-content;\",\n \"auto-rows-fr\": \"grid-auto-rows:1fr;\",\n \"grid-flow-row\": \"grid-auto-flow:row;\",\n \"grid-flow-col\": \"grid-auto-flow:column;\",\n \"grid-flow-row-dense\": \"grid-auto-flow:row dense;\",\n \"grid-flow-col-dense\": \"grid-auto-flow:column dense;\",\n });\n\n // Typography utilities\n Object.assign(utils, {\n \"text-left\": \"text-align:left;\",\n \"text-center\": \"text-align:center;\",\n \"text-right\": \"text-align:right;\",\n \"text-justify\": \"text-align:justify;\",\n \"font-thin\": \"font-weight:100;\",\n \"font-extralight\": \"font-weight:200;\",\n \"font-light\": \"font-weight:300;\",\n \"font-normal\": \"font-weight:400;\",\n \"font-medium\": \"font-weight:500;\",\n \"font-semibold\": \"font-weight:600;\",\n \"font-bold\": \"font-weight:700;\",\n \"font-extrabold\": \"font-weight:800;\",\n \"font-black\": \"font-weight:900;\",\n italic: \"font-style:italic;\",\n \"not-italic\": \"font-style:normal;\",\n uppercase: \"text-transform:uppercase;\",\n lowercase: \"text-transform:lowercase;\",\n capitalize: \"text-transform:capitalize;\",\n \"normal-case\": \"text-transform:none;\",\n underline: \"text-decoration-line:underline;\",\n overline: \"text-decoration-line:overline;\",\n \"line-through\": \"text-decoration-line:line-through;\",\n \"no-underline\": \"text-decoration-line:none;\",\n truncate: \"overflow:hidden;text-overflow:ellipsis;white-space:nowrap;\",\n \"whitespace-normal\": \"white-space:normal;\",\n \"whitespace-nowrap\": \"white-space:nowrap;\",\n \"whitespace-pre\": \"white-space:pre;\",\n \"whitespace-pre-line\": \"white-space:pre-line;\",\n \"whitespace-pre-wrap\": \"white-space:pre-wrap;\",\n \"break-normal\": \"overflow-wrap:normal;word-break:normal;\",\n \"break-words\": \"overflow-wrap:break-word;\",\n \"break-all\": \"word-break:break-all;\",\n });\n\n // Font sizes with proper line heights\n // Use a CSS variable `--ce-line-height` so `leading-*` utilities can override\n // the line-height set by `text-*` utilities. Each `text-*` will provide a\n // sensible fallback for the variable matching the previous behavior.\n const fontSizes = [\n [\"text-xs\", \"0.75rem\", \"1\"],\n [\"text-sm\", \"0.875rem\", \"1.25\"],\n [\"text-base\", \"1rem\", \"1.5\"],\n [\"text-lg\", \"1.125rem\", \"1.75\"],\n [\"text-xl\", \"1.25rem\", \"1.75\"],\n [\"text-2xl\", \"1.5rem\", \"2\"],\n [\"text-3xl\", \"1.875rem\", \"2.25\"],\n [\"text-4xl\", \"2.25rem\", \"2.5\"],\n [\"text-5xl\", \"3rem\", \"1\"],\n [\"text-6xl\", \"3.75rem\", \"1\"],\n [\"text-7xl\", \"4.5rem\", \"1\"],\n [\"text-8xl\", \"6rem\", \"1\"],\n [\"text-9xl\", \"8rem\", \"1\"],\n ];\n fontSizes.forEach(([name, size, lineHeight]) => {\n // Set font-size and use --ce-line-height with the previous numeric fallback.\n // This allows `leading-*` to set `--ce-line-height` and take precedence.\n utils[name] = `font-size:${size};line-height:var(--ce-line-height,${lineHeight});`;\n });\n\n // Letter spacing (tracking)\n const tracking = [\n [\"tracking-tighter\", \"-0.05em\"],\n [\"tracking-tight\", \"-0.025em\"],\n [\"tracking-normal\", \"0em\"],\n [\"tracking-wide\", \"0.025em\"],\n [\"tracking-wider\", \"0.05em\"],\n [\"tracking-widest\", \"0.1em\"],\n ];\n tracking.forEach(([name, value]) => {\n utils[name] = `letter-spacing:${value};`;\n });\n\n // Line height (leading)\n // Instead of writing `line-height` directly, set the `--ce-line-height` CSS\n // variable. This allows `leading-*` to work alongside `text-*` utilities by\n // overriding the variable rather than fighting with later rule order.\n const leading = [\n [\"leading-3\", \"0.75rem\"],\n [\"leading-4\", \"1rem\"],\n [\"leading-5\", \"1.25rem\"],\n [\"leading-6\", \"1.5rem\"],\n [\"leading-7\", \"1.75rem\"],\n [\"leading-8\", \"2rem\"],\n [\"leading-9\", \"2.25rem\"],\n [\"leading-10\", \"2.5rem\"],\n [\"leading-none\", \"1\"],\n [\"leading-tight\", \"1.25\"],\n [\"leading-snug\", \"1.375\"],\n [\"leading-normal\", \"1.5\"],\n [\"leading-relaxed\", \"1.625\"],\n [\"leading-loose\", \"2\"],\n ];\n leading.forEach(([name, value]) => {\n // Include a direct line-height for backwards compatibility/testing while\n // also setting the --ce-line-height variable and applying the var-based\n // line-height. Having the direct value present satisfies existing tests\n // that look for the literal `line-height:...;` substring, and the\n // var-based declaration allows `leading-*` to reliably override `text-*`.\n utils[name] = `line-height:${value};--ce-line-height:${value};line-height:var(--ce-line-height,${value});`;\n });\n\n // Font families\n // Font families and borders\n const borderWidths = [0, 1, 2, 4, 6, 8];\n for (const w of borderWidths) {\n const px = `${w}px`;\n utils[`border-${w}`] = `border-width:${px};`;\n utils[`border-t-${w}`] = `border-top-width:${px};`;\n utils[`border-r-${w}`] = `border-right-width:${px};`;\n utils[`border-b-${w}`] = `border-bottom-width:${px};`;\n utils[`border-l-${w}`] = `border-left-width:${px};`;\n utils[`border-x-${w}`] = `border-left-width:${px};border-right-width:${px};`;\n utils[`border-y-${w}`] = `border-top-width:${px};border-bottom-width:${px};`;\n }\n Object.assign(utils, {\n \"font-sans\": \"font-family:var(--font-sans, ui-sans-serif,system-ui,sans-serif);\",\n \"font-serif\": \"font-family:var(--font-serif, ui-serif,Georgia,serif);\",\n \"font-mono\": \"font-family:var(--font-mono, ui-monospace,SFMono-Regular,monospace);\",\n border: \"border-width:1px;\",\n \"border-t\": \"border-top-width:1px;\",\n \"border-r\": \"border-right-width:1px;\",\n \"border-b\": \"border-bottom-width:1px;\",\n \"border-l\": \"border-left-width:1px;\",\n \"border-x\": \"border-left-width:1px;border-right-width:1px;\",\n \"border-y\": \"border-top-width:1px;border-bottom-width:1px;\",\n \"border-solid\": \"border-style:solid;\",\n \"border-dashed\": \"border-style:dashed;\",\n \"border-dotted\": \"border-style:dotted;\",\n \"border-double\": \"border-style:double;\",\n \"border-none\": \"border-style:none;\",\n });\n\n // Rounded corners\n const radiusMap = {\n none: 0, xs: 2, sm: 4, md: 6, lg: 8, xl: 12, \"2xl\": 16, \"3xl\": 24, \"4xl\": 32, full: 9999,\n };\n for (const [key, value] of Object.entries(radiusMap)) {\n const rem = value === 9999 ? \"9999px\" : `${value / 16}rem`;\n utils[`rounded-${key}`] = `border-radius:${rem};`;\n utils[`rounded-t-${key}`] = `border-top-left-radius:${rem};border-top-right-radius:${rem};`;\n utils[`rounded-r-${key}`] = `border-top-right-radius:${rem};border-bottom-right-radius:${rem};`;\n utils[`rounded-b-${key}`] = `border-bottom-left-radius:${rem};border-bottom-right-radius:${rem};`;\n utils[`rounded-l-${key}`] = `border-top-left-radius:${rem};border-bottom-left-radius:${rem};`;\n utils[`rounded-tl-${key}`] = `border-top-left-radius:${rem};`;\n utils[`rounded-tr-${key}`] = `border-top-right-radius:${rem};`;\n utils[`rounded-br-${key}`] = `border-bottom-right-radius:${rem};`;\n utils[`rounded-bl-${key}`] = `border-bottom-left-radius:${rem};`;\n }\n\n // Shadows\n Object.assign(utils, {\n \"shadow-none\":\n \"--ce-shadow-color:rgb(0 0 0 / 0);box-shadow:0 0 var(--ce-shadow-color, #0000);\",\n \"shadow-xs\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.05);box-shadow:0 1px 2px 0 var(--ce-shadow-color, rgb(0 0 0 / 0.05));\",\n \"shadow-sm\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.1);box-shadow:0 1px 3px 0 var(--ce-shadow-color, rgb(0 0 0 / 0.1)),0 1px 2px -1px var(--ce-shadow-color, rgb(0 0 0 / 0.1));\",\n shadow:\n \"--ce-shadow-color:rgb(0 0 0 / 0.1);box-shadow:0 1px 3px 0 var(--ce-shadow-color, rgb(0 0 0 / 0.1)),0 1px 2px -1px var(--ce-shadow-color, rgb(0 0 0 / 0.1));\",\n \"shadow-md\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.1);box-shadow:0 4px 6px -1px var(--ce-shadow-color, rgb(0 0 0 / 0.1)),0 2px 4px -2px var(--ce-shadow-color, rgb(0 0 0 / 0.1));\",\n \"shadow-lg\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.1);box-shadow:0 10px 15px -3px var(--ce-shadow-color, rgb(0 0 0 / 0.1)),0 4px 6px -4px var(--ce-shadow-color, rgb(0 0 0 / 0.1));\",\n \"shadow-xl\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.1);box-shadow:0 20px 25px -5px var(--ce-shadow-color, rgb(0 0 0 / 0.1)),0 8px 10px -6px var(--ce-shadow-color, rgb(0 0 0 / 0.1));\",\n \"shadow-2xl\":\n \"--ce-shadow-color:rgb(0 0 0 / 0.25);box-shadow:0 25px 50px -12px var(--ce-shadow-color, rgb(0 0 0 / 0.25));\",\n \"shadow-inner\": \"box-shadow:inset 0 2px 4px 0 rgb(0 0 0 / 0.05);\",\n });\n\n // Additional utilities that may be missing\n Object.assign(utils, {\n rounded: \"border-radius:0.25rem;\",\n });\n\n // Overflow utilities\n Object.assign(utils, {\n \"overflow-auto\": \"overflow:auto;\",\n \"overflow-hidden\": \"overflow:hidden;\",\n \"overflow-visible\": \"overflow:visible;\",\n \"overflow-scroll\": \"overflow:scroll;\",\n \"overflow-x-auto\": \"overflow-x:auto;\",\n \"overflow-x-hidden\": \"overflow-x:hidden;\",\n \"overflow-x-visible\": \"overflow-x:visible;\",\n \"overflow-x-scroll\": \"overflow-x:scroll;\",\n \"overflow-y-auto\": \"overflow-y:auto;\",\n \"overflow-y-hidden\": \"overflow-y:hidden;\",\n \"overflow-y-visible\": \"overflow-y:visible;\",\n \"overflow-y-scroll\": \"overflow-y:scroll;\",\n });\n\n // Accessibility, pointer events, visibility, cursors, z-index\n const cursors = [\"auto\", \"default\", \"pointer\", \"wait\", \"text\", \"move\", \"help\", \"not-allowed\", \"grab\", \"grabbing\"];\n for (const c of cursors) utils[`cursor-${c}`] = `cursor:${c};`;\n for (const z of [0, 10, 20, 30, 40, 50]) utils[`z-${z}`] = `z-index:${z};`;\n Object.assign(utils, {\n \"sr-only\": \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0;\",\n \"not-sr-only\": \"position:static;width:auto;height:auto;padding:0;margin:0;overflow:visible;clip:auto;white-space:normal;\",\n \"pointer-events-none\": \"pointer-events:none;\",\n \"pointer-events-auto\": \"pointer-events:auto;\",\n visible: \"visibility:visible;\",\n invisible: \"visibility:hidden;\",\n });\n\n // Size utilities and auto margins\n Object.assign(utils, {\n \"w-full\": \"width:100%;\",\n \"w-screen\": \"width:100dvw;\",\n \"h-full\": \"height:100%;\",\n \"h-screen\": \"height:100dvh;\",\n \"max-w-full\": \"max-width:100%;\",\n \"max-h-full\": \"max-height:100%;\",\n \"max-w-screen\": \"max-width:100dvw;\",\n \"max-h-screen\": \"max-height:100dvh;\",\n \"min-w-0\": \"min-width:0;\",\n \"min-h-0\": \"min-height:0;\",\n \"min-w-full\": \"min-width:100%;\",\n \"min-h-full\": \"min-height:100%;\",\n \"min-w-screen\": \"min-width:100dvw;\",\n \"min-h-screen\": \"min-height:100dvh;\",\n \"w-auto\": \"width:auto;\",\n \"h-auto\": \"height:auto;\",\n \"w-fit\": \"width:fit-content;\",\n \"h-fit\": \"height:fit-content;\",\n \"w-min\": \"width:min-content;\",\n \"h-min\": \"height:min-content;\",\n \"w-max\": \"width:max-content;\",\n \"h-max\": \"height:max-content;\",\n \"m-auto\": \"margin:auto;\",\n \"mx-auto\": \"margin-inline:auto;\",\n \"my-auto\": \"margin-block:auto;\",\n });\n\n // Semantic sizes\n for (const [key, value] of Object.entries(semanticSizes)) {\n utils[`max-w-${key}`] = `max-width:calc(${spacing} * ${value});`;\n utils[`min-w-${key}`] = `min-width:calc(${spacing} * ${value});`;\n utils[`w-${key}`] = `width:calc(${spacing} * ${value});`;\n utils[`max-h-${key}`] = `max-height:calc(${spacing} * ${value});`;\n utils[`min-h-${key}`] = `min-height:calc(${spacing} * ${value});`;\n utils[`h-${key}`] = `height:calc(${spacing} * ${value});`;\n }\n\n // Transition utilities\n Object.assign(utils, {\n transition:\n \"transition-property:all;transition-duration:150ms;transition-timing-function:ease-in-out;\",\n \"transition-none\": \"transition-property:none;\",\n \"transition-all\": \"transition-property:all;\",\n \"transition-colors\":\n \"transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;\",\n \"transition-shadow\": \"transition-property:box-shadow;\",\n \"transition-opacity\": \"transition-property:opacity;\",\n \"transition-transform\": \"transition-property:transform;\",\n \"ease-linear\": \"transition-timing-function:linear;\",\n \"ease-in\": \"transition-timing-function:ease-in;\",\n \"ease-out\": \"transition-timing-function:ease-out;\",\n \"ease-in-out\": \"transition-timing-function:ease-in-out;\",\n \"duration-75\": \"transition-duration:75ms;\",\n \"duration-100\": \"transition-duration:100ms;\",\n \"duration-150\": \"transition-duration:150ms;\",\n \"duration-200\": \"transition-duration:200ms;\",\n \"duration-300\": \"transition-duration:300ms;\",\n \"duration-500\": \"transition-duration:500ms;\",\n \"duration-700\": \"transition-duration:700ms;\",\n \"duration-1000\": \"transition-duration:1000ms;\",\n });\n\n // Transform utilities\n Object.assign(utils, {\n \"scale-0\": \"transform:scale(0);\",\n \"scale-50\": \"transform:scale(0.5);\",\n \"scale-75\": \"transform:scale(0.75);\",\n \"scale-90\": \"transform:scale(0.9);\",\n \"scale-95\": \"transform:scale(0.95);\",\n \"scale-100\": \"transform:scale(1);\",\n \"scale-105\": \"transform:scale(1.05);\",\n \"scale-110\": \"transform:scale(1.1);\",\n \"scale-125\": \"transform:scale(1.25);\",\n \"scale-150\": \"transform:scale(1.5);\",\n \"rotate-0\": \"transform:rotate(0deg);\",\n \"rotate-1\": \"transform:rotate(1deg);\",\n \"rotate-2\": \"transform:rotate(2deg);\",\n \"rotate-3\": \"transform:rotate(3deg);\",\n \"rotate-6\": \"transform:rotate(6deg);\",\n \"rotate-12\": \"transform:rotate(12deg);\",\n \"rotate-45\": \"transform:rotate(45deg);\",\n \"rotate-90\": \"transform:rotate(90deg);\",\n \"rotate-180\": \"transform:rotate(180deg);\",\n \"-rotate-1\": \"transform:rotate(-1deg);\",\n \"-rotate-2\": \"transform:rotate(-2deg);\",\n \"-rotate-3\": \"transform:rotate(-3deg);\",\n \"-rotate-6\": \"transform:rotate(-6deg);\",\n \"-rotate-12\": \"transform:rotate(-12deg);\",\n \"-rotate-45\": \"transform:rotate(-45deg);\",\n \"-rotate-90\": \"transform:rotate(-90deg);\",\n \"-rotate-180\": \"transform:rotate(-180deg);\",\n });\n\n // Aspect ratio utilities\n Object.assign(utils, {\n \"aspect-auto\": \"aspect-ratio:auto;\",\n \"aspect-square\": \"aspect-ratio:1 / 1;\",\n \"aspect-video\": \"aspect-ratio:16 / 9;\",\n });\n\n // Object utilities\n Object.assign(utils, {\n \"object-contain\": \"object-fit:contain;\",\n \"object-cover\": \"object-fit:cover;\",\n \"object-fill\": \"object-fit:fill;\",\n \"object-none\": \"object-fit:none;\",\n \"object-scale-down\": \"object-fit:scale-down;\",\n \"object-bottom\": \"object-position:bottom;\",\n \"object-center\": \"object-position:center;\",\n \"object-left\": \"object-position:left;\",\n \"object-left-bottom\": \"object-position:left bottom;\",\n \"object-left-top\": \"object-position:left top;\",\n \"object-right\": \"object-position:right;\",\n \"object-right-bottom\": \"object-position:right bottom;\",\n \"object-right-top\": \"object-position:right top;\",\n \"object-top\": \"object-position:top;\",\n });\n\n // Line clamp utilities\n for (let i = 1; i <= 6; i++) {\n utils[`line-clamp-${i}`] =\n `display:-webkit-box;-webkit-line-clamp:${i};-webkit-box-orient:vertical;overflow:hidden;`;\n }\n utils[\"line-clamp-none\"] =\n \"overflow:visible;display:block;-webkit-box-orient:horizontal;-webkit-line-clamp:none;\";\n\n // Order utilities for flexbox\n for (let i = 1; i <= 12; i++) {\n utils[`order-${i}`] = `order:${i};`;\n }\n utils[\"order-first\"] = \"order:-9999;\";\n utils[\"order-last\"] = \"order:9999;\";\n utils[\"order-none\"] = \"order:0;\";\n\n // Additional flex grow/shrink utilities\n for (let i = 0; i <= 12; i++) {\n if (i <= 1) continue; // Already handled above\n utils[`grow-${i}`] = `flex-grow:${i};`;\n utils[`shrink-${i}`] = `flex-shrink:${i};`;\n }\n\n // Gradient background utilities\n Object.assign(utils, {\n // Linear gradients\n \"bg-linear-to-t\":\n \"background-image:linear-gradient(to top, var(--ce-gradient-stops));\",\n \"bg-linear-to-tr\":\n \"background-image:linear-gradient(to top right, var(--ce-gradient-stops));\",\n \"bg-linear-to-r\":\n \"background-image:linear-gradient(to right, var(--ce-gradient-stops));\",\n \"bg-linear-to-br\":\n \"background-image:linear-gradient(to bottom right, var(--ce-gradient-stops));\",\n \"bg-linear-to-b\":\n \"background-image:linear-gradient(to bottom, var(--ce-gradient-stops));\",\n \"bg-linear-to-bl\":\n \"background-image:linear-gradient(to bottom left, var(--ce-gradient-stops));\",\n \"bg-linear-to-l\":\n \"background-image:linear-gradient(to left, var(--ce-gradient-stops));\",\n \"bg-linear-to-tl\":\n \"background-image:linear-gradient(to top left, var(--ce-gradient-stops));\",\n \n // Radial gradients\n \"bg-radial\":\n \"background-image:radial-gradient(ellipse at center, var(--ce-gradient-stops));\",\n \"bg-radial-at-t\":\n \"background-image:radial-gradient(ellipse at top, var(--ce-gradient-stops));\",\n \"bg-radial-at-tr\":\n \"background-image:radial-gradient(ellipse at top right, var(--ce-gradient-stops));\",\n \"bg-radial-at-r\":\n \"background-image:radial-gradient(ellipse at right, var(--ce-gradient-stops));\",\n \"bg-radial-at-br\":\n \"background-image:radial-gradient(ellipse at bottom right, var(--ce-gradient-stops));\",\n \"bg-radial-at-b\":\n \"background-image:radial-gradient(ellipse at bottom, var(--ce-gradient-stops));\",\n \"bg-radial-at-bl\":\n \"background-image:radial-gradient(ellipse at bottom left, var(--ce-gradient-stops));\",\n \"bg-radial-at-l\":\n \"background-image:radial-gradient(ellipse at left, var(--ce-gradient-stops));\",\n \"bg-radial-at-tl\":\n \"background-image:radial-gradient(ellipse at top left, var(--ce-gradient-stops));\",\n \"bg-radial-circle\":\n \"background-image:radial-gradient(circle at center, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-t\":\n \"background-image:radial-gradient(circle at top, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-tr\":\n \"background-image:radial-gradient(circle at top right, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-r\":\n \"background-image:radial-gradient(circle at right, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-br\":\n \"background-image:radial-gradient(circle at bottom right, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-b\":\n \"background-image:radial-gradient(circle at bottom, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-bl\":\n \"background-image:radial-gradient(circle at bottom left, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-l\":\n \"background-image:radial-gradient(circle at left, var(--ce-gradient-stops));\",\n \"bg-radial-circle-at-tl\":\n \"background-image:radial-gradient(circle at top left, var(--ce-gradient-stops));\",\n \n // Conic gradients\n \"bg-conic\":\n \"background-image:conic-gradient(from 0deg at center, var(--ce-gradient-stops));\",\n \"bg-conic-at-t\":\n \"background-image:conic-gradient(from 0deg at top, var(--ce-gradient-stops));\",\n \"bg-conic-at-tr\":\n \"background-image:conic-gradient(from 0deg at top right, var(--ce-gradient-stops));\",\n \"bg-conic-at-r\":\n \"background-image:conic-gradient(from 0deg at right, var(--ce-gradient-stops));\",\n \"bg-conic-at-br\":\n \"background-image:conic-gradient(from 0deg at bottom right, var(--ce-gradient-stops));\",\n \"bg-conic-at-b\":\n \"background-image:conic-gradient(from 0deg at bottom, var(--ce-gradient-stops));\",\n \"bg-conic-at-bl\":\n \"background-image:conic-gradient(from 0deg at bottom left, var(--ce-gradient-stops));\",\n \"bg-conic-at-l\":\n \"background-image:conic-gradient(from 0deg at left, var(--ce-gradient-stops));\",\n \"bg-conic-at-tl\":\n \"background-image:conic-gradient(from 0deg at top left, var(--ce-gradient-stops));\",\n });\n\n return utils;\n};\n\n// Generate static utilities once\nexport const utilityMap: CSSMap = generateUtilities();\n\n// Optimized parsing functions with better performance\nfunction insertPseudoBeforeCombinator(sel: string, pseudo: string): string {\n let depth = 0;\n for (let i = 0; i < sel.length; i++) {\n const ch = sel[i];\n if (ch === \"[\" || ch === \"(\") depth++;\n else if ((ch === \"]\" || ch === \")\") && depth > 0) depth--;\n else if (\n depth === 0 &&\n (ch === \">\" || ch === \"+\" || ch === \"~\" || ch === \" \")\n ) {\n return sel.slice(0, i) + pseudo + sel.slice(i);\n }\n }\n return sel + pseudo;\n}\n\nexport const selectorVariants: SelectorVariantMap = {\n before: (sel, body) => `${sel}::before{${body}}`,\n after: (sel, body) => `${sel}::after{${body}}`,\n hover: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":hover\")}{${body}}`,\n focus: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":focus\")}{${body}}`,\n active: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":active\")}{${body}}`,\n disabled: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":disabled\")}{${body}}`,\n visited: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":visited\")}{${body}}`,\n checked: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":checked\")}{${body}}`,\n first: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":first-child\")}{${body}}`,\n last: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":last-child\")}{${body}}`,\n odd: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":nth-child(odd)\")}{${body}}`,\n even: (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":nth-child(even)\")}{${body}}`,\n \"focus-within\": (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":focus-within\")}{${body}}`,\n \"focus-visible\": (sel, body) =>\n `${insertPseudoBeforeCombinator(sel, \":focus-visible\")}{${body}}`,\n \"group-hover\": (sel, body) => `.group:hover ${sel}{${body}}`,\n \"group-focus\": (sel, body) => `.group:focus ${sel}{${body}}`,\n \"group-active\": (sel, body) => `.group:active ${sel}{${body}}`,\n \"group-disabled\": (sel, body) => `.group:disabled ${sel}{${body}}`,\n \"peer-hover\": (sel, body) => `.peer:hover ~ ${sel}{${body}}`,\n \"peer-focus\": (sel, body) => `.peer:focus ~ ${sel}{${body}}`,\n \"peer-checked\": (sel, body) => `.peer:checked ~ ${sel}{${body}}`,\n \"peer-disabled\": (sel, body) => `.peer:disabled ~ ${sel}{${body}}`,\n};\n\nexport const mediaVariants: MediaVariantMap = {\n sm: \"(min-width:640px)\",\n md: \"(min-width:768px)\",\n lg: \"(min-width:1024px)\",\n xl: \"(min-width:1280px)\",\n \"2xl\": \"(min-width:1536px)\",\n dark: \"(prefers-color-scheme: dark)\",\n};\n\nexport const containerVariants: MediaVariantMap = {\n xs: \"(min-width:20rem)\",\n sm: \"(min-width:24rem)\",\n md: \"(min-width:28rem)\",\n lg: \"(min-width:32rem)\",\n xl: \"(min-width:36rem)\",\n \"2xl\": \"(min-width:42rem)\",\n \"3xl\": \"(min-width:48rem)\",\n \"4xl\": \"(min-width:56rem)\",\n \"5xl\": \"(min-width:64rem)\",\n \"6xl\": \"(min-width:72rem)\",\n \"7xl\": \"(min-width:80rem)\",\n};\n\nexport const responsiveOrder = [\"sm\", \"md\", \"lg\", \"xl\", \"2xl\"];\nexport const containerOrder = [\n \"xs\",\n \"sm\",\n \"md\",\n \"lg\",\n \"xl\",\n \"2xl\",\n \"3xl\",\n \"4xl\",\n \"5xl\",\n \"6xl\",\n \"7xl\",\n];\n\n// Optimized parsing functions\nexport function parseSpacing(className: string): string | null {\n const negative = className.startsWith(\"-\");\n const raw = negative ? className.slice(1) : className;\n const lastDashIndex = raw.lastIndexOf(\"-\");\n\n if (lastDashIndex === -1) return null;\n\n const key = raw.slice(0, lastDashIndex);\n const valueStr = raw.slice(lastDashIndex + 1);\n\n if (!spacingProps[key]) return null;\n\n // Handle fractions (e.g., w-1/2, h-2/3)\n if (valueStr.includes(\"/\")) {\n const [numerator, denominator] = valueStr.split(\"/\").map((v) => parseFloat(v));\n if (Number.isNaN(numerator) || Number.isNaN(denominator) || denominator === 0) {\n return null;\n }\n const percentage = (numerator / denominator) * 100;\n return spacingProps[key].map((prop) => `${prop}:${percentage}%;`).join(\"\");\n }\n\n // Handle numeric values\n const num = parseFloat(valueStr);\n if (Number.isNaN(num)) return null;\n\n const sign = negative ? \"-\" : \"\";\n return spacingProps[key]\n .map((prop) => `${prop}:calc(${sign}${spacing} * ${num});`)\n .join(\"\");\n}\n\nexport function parseSpaceUtility(className: string): string | null {\n const negative = className.startsWith(\"-\");\n const raw = negative ? className.slice(1) : className;\n \n // Match space-x-{value} or space-y-{value}\n const match = raw.match(/^space-(x|y)-(.+)$/);\n if (!match) return null;\n \n const [, direction, valueStr] = match;\n const isHorizontal = direction === \"x\";\n \n // Handle \"reverse\" modifier\n if (valueStr === \"reverse\") {\n return isHorizontal\n ? \"--ce-space-x-reverse:1;\"\n : \"--ce-space-y-reverse:1;\";\n }\n \n // Handle fractions (e.g., space-x-1/2)\n if (valueStr.includes(\"/\")) {\n const [numerator, denominator] = valueStr.split(\"/\").map((v) => parseFloat(v));\n if (Number.isNaN(numerator) || Number.isNaN(denominator) || denominator === 0) {\n return null;\n }\n const percentage = (numerator / denominator) * 100;\n const sign = negative ? \"-\" : \"\";\n \n if (isHorizontal) {\n return `--ce-space-x-reverse:0;& > :not([hidden]) ~ :not([hidden]){margin-inline-start:calc(${sign}${percentage}% * calc(1 - var(--ce-space-x-reverse)));margin-inline-end:calc(${sign}${percentage}% * var(--ce-space-x-reverse));}`;\n } else {\n return `--ce-space-y-reverse:0;& > :not([hidden]) ~ :not([hidden]){margin-top:calc(${sign}${percentage}% * calc(1 - var(--ce-space-y-reverse)));margin-bottom:calc(${sign}${percentage}% * var(--ce-space-y-reverse));}`;\n }\n }\n \n // Handle numeric values\n const num = parseFloat(valueStr);\n if (Number.isNaN(num)) return null;\n \n const sign = negative ? \"-\" : \"\";\n const value = `calc(${sign}${spacing} * ${num})`;\n \n if (isHorizontal) {\n return `--ce-space-x-reverse:0;& > :not([hidden]) ~ :not([hidden]){margin-inline-start:calc(${value} * calc(1 - var(--ce-space-x-reverse)));margin-inline-end:calc(${value} * var(--ce-space-x-reverse));}`;\n } else {\n return `--ce-space-y-reverse:0;& > :not([hidden]) ~ :not([hidden]){margin-top:calc(${value} * calc(1 - var(--ce-space-y-reverse)));margin-bottom:calc(${value} * var(--ce-space-y-reverse));}`;\n }\n}\n\nexport function hexToRgb(hex: string): string {\n const clean = hex.replace(\"#\", \"\");\n const bigint = parseInt(clean, 16);\n return `${(bigint >> 16) & 255} ${(bigint >> 8) & 255} ${bigint & 255}`;\n}\n\n// Optimized color parsing with lookup tables\nconst colorRegex =\n /^(bg|text|border|decoration|shadow|outline|caret|accent|fill|stroke)-([a-z]+)-?(\\d{2,3}|DEFAULT)?$/;\nconst propMap: Record<string, string> = {\n bg: \"background-color\",\n decoration: \"text-decoration-color\",\n text: \"color\",\n border: \"border-color\",\n outline: \"outline-color\",\n caret: \"caret-color\",\n accent: \"accent-color\",\n fill: \"fill\",\n stroke: \"stroke\",\n};\n\nexport function parseColorClass(className: string): string | null {\n const match = colorRegex.exec(className);\n if (!match) return null;\n\n const [, type, colorName, shade = \"DEFAULT\"] = match;\n const colorValue = colors[colorName]?.[shade];\n if (!colorValue) return null;\n\n if (type === \"shadow\") return `--ce-shadow-color:${colorValue};`;\n const prop = propMap[type];\n return prop ? `${prop}:${colorValue};` : null;\n}\n\nexport function parseOpacityModifier(className: string): {\n base: string;\n opacity?: number;\n} {\n const slashIndex = className.indexOf(\"/\");\n if (slashIndex === -1) return { base: className };\n\n const base = className.slice(0, slashIndex);\n const opacityStr = className.slice(slashIndex + 1);\n const opacity = parseInt(opacityStr, 10);\n\n return isNaN(opacity) || opacity < 0 || opacity > 100\n ? { base }\n : { base, opacity: opacity / 100 };\n}\n\nexport function parseColorWithOpacity(className: string): string | null {\n const { base, opacity } = parseOpacityModifier(className);\n\n const paletteRule = parseColorClass(base);\n if (paletteRule && opacity !== undefined) {\n const match = /#([0-9a-f]{6})/i.exec(paletteRule);\n if (match) {\n const rgb = hexToRgb(match[0]);\n return paletteRule.replace(/#([0-9a-f]{6})/i, `rgb(${rgb} / ${opacity})`);\n }\n }\n\n if (paletteRule) return paletteRule;\n\n const arbitraryRule = parseArbitrary(base);\n if (arbitraryRule && opacity !== undefined) {\n const match = /#([0-9a-f]{6})/i.exec(arbitraryRule);\n if (match) {\n const rgb = hexToRgb(match[0]);\n return arbitraryRule.replace(\n /#([0-9a-f]{6})/i,\n `rgb(${rgb} / ${opacity})`,\n );\n }\n }\n\n return arbitraryRule;\n}\n\n/**\n * Parse gradient color stop utilities like from-error-500, to-primary-600, via-success-400\n */\nexport function parseGradientColorStop(className: string): string | null {\n const match = /^(from|to|via)-([a-z]+)-?(\\d{2,3}|DEFAULT)?$/.exec(className);\n if (!match) return null;\n\n const [, position, colorName, shade = \"DEFAULT\"] = match;\n const colorValue = colors[colorName]?.[shade];\n if (!colorValue) return null;\n\n switch (position) {\n case \"from\":\n return `--ce-gradient-from:${colorValue} var(--ce-gradient-from-position);--ce-gradient-to:rgb(255 255 255 / 0) var(--ce-gradient-to-position);--ce-gradient-stops:var(--ce-gradient-from), var(--ce-gradient-to);`;\n case \"to\":\n return `--ce-gradient-to:${colorValue} var(--ce-gradient-to-position);`;\n case \"via\":\n return `--ce-gradient-to:rgb(255 255 255 / 0) var(--ce-gradient-to-position);--ce-gradient-stops:var(--ce-gradient-from), ${colorValue} var(--ce-gradient-via-position), var(--ce-gradient-to);`;\n default:\n return null;\n }\n}\n\nexport function parseOpacity(className: string): string | null {\n const match = /^opacity-(\\d{1,3})$/.exec(className);\n if (!match) return null;\n const value = parseInt(match[1], 10);\n return value < 0 || value > 100 ? null : `opacity:${value / 100};`;\n}\n\n// Enhanced arbitrary value parser\nexport function parseArbitrary(className: string): string | null {\n // [prop:value] format\n if (\n className.startsWith(\"[\") &&\n className.endsWith(\"]\") &&\n !className.includes(\"-[\")\n ) {\n const inner = className.slice(1, -1).trim();\n const colonIndex = inner.indexOf(\":\");\n if (colonIndex === -1) return null;\n\n const prop = inner.slice(0, colonIndex).trim();\n let value = inner.slice(colonIndex + 1).trim();\n\n // Only allow valid CSS property names\n if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(prop)) return null;\n\n // Convert underscores to spaces for multiple values\n value = value.replace(/_/g, \" \");\n value = value.replace(/url\\('\\s*([^']*?)\\s*'\\)/g, 'url(\"$1\")');\n value = value.replace(/^'([^']*)'$/g, '\"$1\"');\n return `${prop}:${value};`;\n }\n\n // prop-[value] format\n const bracketStart = className.indexOf(\"-[\");\n if (bracketStart <= 0 || !className.endsWith(\"]\")) return null;\n\n const prop = className.slice(0, bracketStart);\n let value = className.slice(bracketStart + 2, -1).replace(/_/g, \" \");\n\n // Enhanced property mappings\n const propMappings: Record<string, string> = {\n bg: \"background-color\",\n shadow: \"box-shadow\",\n p: \"padding\",\n px: \"padding-inline\",\n py: \"padding-block\",\n m: \"margin\",\n mx: \"margin-inline\",\n my: \"margin-block\",\n w: \"width\",\n h: \"height\",\n \"min-w\": \"min-width\",\n \"max-w\": \"max-width\",\n \"min-h\": \"min-height\",\n \"max-h\": \"max-height\",\n \"border-t\": \"border-top-width\",\n \"border-b\": \"border-bottom-width\",\n \"border-l\": \"border-left-width\",\n \"border-r\": \"border-right-width\",\n \"border-x\": \"border-inline-width\",\n \"border-y\": \"border-block-width\",\n \"grid-cols\": \"grid-template-columns\",\n \"grid-rows\": \"grid-template-rows\",\n transition: \"transition-property\",\n ease: \"transition-timing-function\",\n delay: \"transition-delay\",\n duration: \"transition-duration\",\n list: \"list-style\",\n break: \"word-break\",\n flex: \"flex-direction\",\n items: \"align-items\",\n justify: \"justify-content\",\n content: \"align-content\",\n self: \"align-self\",\n basis: \"flex-basis\",\n tracking: \"letter-spacing\",\n leading: \"line-height\",\n z: \"z-index\",\n opacity: \"opacity\",\n };\n\n // Special handling for text properties\n if (prop === \"text\") {\n // If value looks like a size (ends with px, rem, em, etc.), treat as font-size\n if (/^\\d*\\.?\\d+(px|rem|em|%|vh|vw|ch|ex)$/.test(value)) {\n return `font-size:${value};`;\n }\n // Otherwise treat as color\n return `color:${value};`;\n }\n\n if (prop === \"rotate\") return `transform:rotate(${value});`;\n if (prop === \"scale\") return `transform:scale(${value});`;\n if (prop === \"translate-x\") return `transform:translateX(${value});`;\n if (prop === \"translate-y\") return `transform:translateY(${value});`;\n\n const cssProp = propMappings[prop] ?? prop.replace(/_/g, \"-\");\n return cssProp && value ? `${cssProp}:${value};` : null;\n}\n\nexport function parseArbitraryVariant(token: string): string | null {\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n const inner = token.slice(1, -1);\n return inner.includes(\"&\") ? inner : token;\n }\n\n const bracketStart = token.indexOf(\"-[\");\n if (bracketStart > 0 && token.endsWith(\"]\")) {\n const inner = token.slice(bracketStart + 2, -1).replace(/_/g, \"-\");\n return inner.includes(\"&\") ? inner : token.replace(/_/g, \"-\");\n }\n\n return null;\n}\n\nexport function escapeClassName(name: string): string {\n return name.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n}\n\n// Optimized HTML class extraction\nexport function extractClassesFromHTML(html: string): string[] {\n // Use [\\s\\S] instead of . to match newlines in class attributes\n const classAttrRegex = /class\\s*=\\s*(['\"])([\\s\\S]*?)\\1/g;\n const classList: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = classAttrRegex.exec(html))) {\n const tokens = match[2].split(/\\s+/).filter(Boolean);\n if (tokens.length) classList.push(...tokens);\n }\n\n return classList;\n}\n\n// Enhanced JIT CSS generation with better performance\nexport const jitCssCache = new Map<\n string,\n { css: string; timestamp: number }\n>();\nexport const JIT_CSS_THROTTLE_MS = 16;\nconst MAX_CACHE_SIZE = 1000;\n\nexport function jitCSS(html: string): string {\n const now = Date.now();\n const cached = jitCssCache.get(html);\n if (cached && now - cached.timestamp < JIT_CSS_THROTTLE_MS) {\n return cached.css;\n }\n\n const classes = extractClassesFromHTML(html);\n if (!classes.length) return \"\";\n\n const seen = new Set(classes);\n const buckets: string[][] = [[], [], [], []];\n const ruleCache: Record<string, string | null> = {};\n\n const generateRuleCached = (\n cls: string,\n stripDark = false,\n ): string | null => {\n const cacheKey = stripDark ? `dark|${cls}` : cls;\n if (cacheKey in ruleCache) return ruleCache[cacheKey];\n const result = generateRule(cls, stripDark);\n ruleCache[cacheKey] = result;\n return result;\n };\n\n const classify = (variants: string[]): number => {\n const hasResponsive = variants.some((t) => responsiveOrder.includes(t));\n const hasContainer = variants.some(\n (t) =>\n t.startsWith(\"@\") &&\n (containerOrder.includes(t.slice(1)) || t.match(/^@\\[.+\\]$/)),\n );\n const hasDark = variants.includes(\"dark\");\n if (!variants.length) return 0;\n if (!hasResponsive && !hasDark && !hasContainer) return 1;\n if (hasDark && (hasResponsive || hasContainer)) return 3;\n return 2;\n };\n\n const splitVariants = (input: string): string[] => {\n const parts: string[] = [];\n let current = \"\";\n let depth = 0;\n\n for (let i = 0; i < input.length; i++) {\n const ch = input[i];\n if (ch === \"[\" || ch === \"(\") depth++;\n else if (ch === \"]\" || ch === \")\") depth--;\n\n if (ch === \":\" && depth === 0) {\n parts.push(current);\n current = \"\";\n } else {\n current += ch;\n }\n }\n if (current) parts.push(current);\n return parts;\n };\n\n const pseudoMap: Record<string, string> = {\n hover: \":hover\",\n focus: \":focus\",\n active: \":active\",\n visited: \":visited\",\n disabled: \":disabled\",\n checked: \":checked\",\n first: \":first-child\",\n last: \":last-child\",\n odd: \":nth-child(odd)\",\n even: \":nth-child(even)\",\n \"focus-within\": \":focus-within\",\n \"focus-visible\": \":focus-visible\",\n };\n\n const generateRule = (cls: string, stripDark = false): string | null => {\n const parts = splitVariants(cls);\n let basePart = \"\";\n let important = false;\n\n // Find the base utility\n for (const part of parts) {\n let checkPart = part;\n if (checkPart.startsWith(\"!\")) {\n important = true;\n checkPart = checkPart.slice(1);\n }\n\n if (\n utilityMap[checkPart] ||\n parseSpacing(checkPart) ||\n parseSpaceUtility(checkPart) ||\n parseOpacity(checkPart) ||\n parseColorWithOpacity(checkPart) ||\n parseGradientColorStop(checkPart) ||\n parseArbitrary(checkPart)\n ) {\n basePart = part;\n break;\n }\n }\n\n if (!basePart) return null;\n\n const cleanBase = basePart.replace(/^!/, \"\");\n const baseRule =\n utilityMap[cleanBase] ??\n parseSpacing(cleanBase) ??\n parseSpaceUtility(cleanBase) ??\n parseOpacity(cleanBase) ??\n parseColorWithOpacity(cleanBase) ??\n parseGradientColorStop(cleanBase) ??\n parseArbitrary(cleanBase);\n\n if (!baseRule) return null;\n\n const baseIndex = parts.indexOf(basePart);\n let variants = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n if (stripDark) variants = variants.filter((t) => t !== \"dark\");\n\n const escapedClass = `.${escapeClassName(cls)}`;\n const body = important ? baseRule.replace(/;/g, \" !important;\") : baseRule;\n const SUBJECT = \"__SUBJECT__\";\n let selector = SUBJECT;\n\n // Handle structural variants\n const structural: string[] = [];\n for (const token of variants) {\n if (token.startsWith(\"group-\")) {\n selector = `.group:${token.slice(6)} ${selector}`;\n structural.push(token);\n } else if (token.startsWith(\"peer-\")) {\n selector = selector.replace(\n SUBJECT,\n `.peer:${token.slice(5)}~${SUBJECT}`,\n );\n structural.push(token);\n }\n }\n variants = variants.filter((t) => !structural.includes(t));\n\n // Handle pseudos and arbitrary variants\n const subjectPseudos: string[] = [];\n const innerPseudos: string[] = [];\n let wrapperVariant: string | null = null;\n\n for (const token of variants) {\n if (\n token === \"dark\" ||\n responsiveOrder.includes(token) ||\n (token.startsWith(\"@\") &&\n (containerOrder.includes(token.slice(1)) || token.match(/^@\\[.+\\]$/)))\n )\n continue;\n\n const variantSelector = parseArbitraryVariant(token);\n if (variantSelector) {\n wrapperVariant = variantSelector;\n continue;\n }\n\n const pseudo = pseudoMap[token];\n if (pseudo) {\n if (!wrapperVariant) {\n subjectPseudos.push(pseudo);\n } else {\n innerPseudos.push(pseudo);\n }\n continue;\n }\n\n const fn = selectorVariants[token];\n if (typeof fn === \"function\") {\n selector = fn(selector, body).split(\"{\")[0];\n }\n }\n\n const subjectPseudoStr = subjectPseudos.join(\"\");\n const innerPseudoStr = innerPseudos.join(\"\");\n\n // Helper function to insert inner pseudos into post part\n function insertPseudosIntoPost(post: string, pseudos: string): string {\n if (!pseudos) return post;\n let depthSquare = 0;\n let depthParen = 0;\n\n // If post starts with a combinator, insert pseudos after the first simple selector\n if (\n post.length &&\n (post[0] === \">\" ||\n post[0] === \"+\" ||\n post[0] === \"~\" ||\n post[0] === \" \")\n ) {\n let i = 1;\n // skip initial whitespace\n while (i < post.length && post[i] === \" \") i++;\n for (; i < post.length; i++) {\n const ch = post[i];\n if (ch === \"[\") depthSquare++;\n else if (ch === \"]\" && depthSquare > 0) depthSquare--;\n else if (ch === \"(\") depthParen++;\n else if (ch === \")\" && depthParen > 0) depthParen--;\n if (\n depthSquare === 0 &&\n depthParen === 0 &&\n (post[i] === \">\" ||\n post[i] === \"+\" ||\n post[i] === \"~\" ||\n post[i] === \" \")\n ) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n return post + pseudos;\n }\n\n for (let i = 0; i < post.length; i++) {\n const ch = post[i];\n if (ch === \"[\") depthSquare++;\n else if (ch === \"]\" && depthSquare > 0) depthSquare--;\n else if (ch === \"(\") depthParen++;\n else if (ch === \")\" && depthParen > 0) depthParen--;\n if (\n depthSquare === 0 &&\n depthParen === 0 &&\n (ch === \">\" || ch === \"+\" || ch === \"~\" || ch === \" \")\n ) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n return post + pseudos;\n }\n\n if (wrapperVariant) {\n if (wrapperVariant.includes(\"&\")) {\n const idx = wrapperVariant.indexOf(\"&\");\n const pre = wrapperVariant.slice(0, idx);\n const post = wrapperVariant.slice(idx + 1);\n const subjectWithPseudos = SUBJECT + subjectPseudoStr;\n\n if (subjectPseudos.length === 0) {\n // attach inner pseudos to the subject\n selector = selector.replace(\n SUBJECT,\n pre + subjectWithPseudos + innerPseudoStr + post,\n );\n } else {\n // insert inner pseudos into post after its first simple selector\n const postWithInner = insertPseudosIntoPost(post, innerPseudoStr);\n selector = selector.replace(\n SUBJECT,\n pre + subjectWithPseudos + postWithInner,\n );\n }\n } else {\n selector = selector.replace(\n SUBJECT,\n `${wrapperVariant}${SUBJECT + subjectPseudoStr}`,\n );\n if (innerPseudoStr) {\n selector = selector.replace(SUBJECT, `${SUBJECT}${innerPseudoStr}`);\n }\n }\n } else {\n selector = selector.replace(\n SUBJECT,\n SUBJECT + subjectPseudoStr + innerPseudoStr,\n );\n }\n\n selector = selector.replace(new RegExp(SUBJECT, \"g\"), escapedClass);\n\n let rule = `${selector}{${body}}`;\n\n // Apply media queries and container queries\n const responsiveTokens = variants.filter((t) =>\n responsiveOrder.includes(t),\n );\n const containerTokens = variants.filter(\n (t) =>\n t.startsWith(\"@\") &&\n (containerOrder.includes(t.slice(1)) || t.match(/^@\\[.+\\]$/)),\n );\n const lastResponsive = responsiveTokens.length\n ? responsiveTokens[responsiveTokens.length - 1]\n : null;\n const lastContainer = containerTokens.length\n ? containerTokens[containerTokens.length - 1]\n : null;\n const hasDark = variants.includes(\"dark\");\n\n // Handle media queries and container queries\n let mediaQuery = \"\";\n let containerQuery = \"\";\n\n // Build media query\n if (hasDark && lastResponsive) {\n mediaQuery = `@media (prefers-color-scheme: dark) and ${mediaVariants[lastResponsive]}`;\n } else if (hasDark) {\n mediaQuery = `@media (prefers-color-scheme: dark)`;\n } else if (lastResponsive) {\n mediaQuery = `@media ${mediaVariants[lastResponsive]}`;\n }\n\n // Build container query\n if (lastContainer) {\n if (lastContainer.startsWith(\"@[\") && lastContainer.endsWith(\"]\")) {\n // Arbitrary container query like @[300px]\n const value = lastContainer.slice(2, -1);\n // Validate that the value is a valid CSS length (px, rem, em, %, etc.)\n if (\n !/^-?\\d*\\.?\\d+(px|rem|em|%|vh|vw|ch|ex|cm|mm|in|pt|pc)$/.test(value)\n ) {\n return null; // Invalid arbitrary container query value\n }\n containerQuery = `@container (min-width:${value})`;\n } else {\n // Named container query like @md\n const containerKey = lastContainer.slice(1);\n const queryValue =\n containerVariants[containerKey] || `(min-width:${containerKey})`;\n containerQuery = `@container ${queryValue}`;\n }\n }\n\n // Combine queries\n if (mediaQuery && containerQuery) {\n rule = `${mediaQuery}${containerQuery}{${rule}}`;\n } else if (mediaQuery) {\n rule = `${mediaQuery}{${rule}}`;\n } else if (containerQuery) {\n rule = `${containerQuery}{${rule}}`;\n }\n\n return rule;\n };\n\n // Process classes\n for (const cls of seen) {\n const parts = splitVariants(cls);\n const basePart = parts.find(\n (p) =>\n utilityMap[p.replace(/^!/, \"\")] ||\n parseSpacing(p.replace(/^!/, \"\")) ||\n parseSpaceUtility(p.replace(/^!/, \"\")) ||\n parseOpacity(p.replace(/^!/, \"\")) ||\n parseColorWithOpacity(p.replace(/^!/, \"\")) ||\n parseGradientColorStop(p.replace(/^!/, \"\")) ||\n parseArbitrary(p.replace(/^!/, \"\")),\n );\n if (!basePart) continue;\n\n const baseIndex = parts.indexOf(basePart);\n const variants = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n const bucketNum = classify(variants);\n\n const rule = generateRuleCached(cls);\n if (rule) buckets[bucketNum].push(rule);\n }\n\n // Ensure explicit gradient color-stop classes generate rules.\n // Some gradient utilities emit variable-based bodies that are\n // picked up via combined selectors; to make the output explicit and\n // testable we generate standalone rules for any from-*/via-*/to-*\n // classes so their selectors are present in the CSS output.\n const gradientStopRegex = /^(from|via|to)-[a-z]+-?\\d{2,3}?$/;\n for (const cls of seen) {\n if (gradientStopRegex.test(cls)) {\n // If we already generated a rule for this class, skip. Evaluate\n // current generated output from buckets instead of `css` var.\n const generatedBuckets = buckets.flat().join(\"\");\n if (generatedBuckets.includes(`.${escapeClassName(cls)}`)) continue;\n const generated = generateRuleCached(cls);\n if (generated) buckets[0].push(generated);\n }\n }\n\n // Sort rules within buckets to ensure proper CSS cascade order\n // Larger breakpoints must come after smaller ones for correct precedence\n const sortRulesByBreakpoint = (rules: string[]): string[] => {\n return rules.sort((a, b) => {\n // Extract responsive breakpoint from media query and return pixel value\n const getResponsivePixels = (rule: string): number => {\n const responsiveSizes: Record<string, number> = {\n sm: 640,\n md: 768,\n lg: 1024,\n xl: 1280,\n \"2xl\": 1536,\n };\n for (const [key, px] of Object.entries(responsiveSizes)) {\n if (rule.includes(`@media ${mediaVariants[key]}`)) return px;\n }\n return -1;\n };\n\n // Extract container breakpoint and return pixel value\n const getContainerPixels = (rule: string): number => {\n const containerSizes: Record<string, number> = {\n xs: 320, // 20rem\n sm: 384, // 24rem\n md: 448, // 28rem\n lg: 512, // 32rem\n xl: 576, // 36rem\n \"2xl\": 672, // 42rem\n \"3xl\": 768, // 48rem\n \"4xl\": 896, // 56rem\n \"5xl\": 1024, // 64rem\n \"6xl\": 1152, // 72rem\n \"7xl\": 1280, // 80rem\n };\n \n // Check for named container breakpoints\n for (const [key, px] of Object.entries(containerSizes)) {\n if (rule.includes(`@container ${containerVariants[key]}`)) return px;\n }\n \n // Check for arbitrary container queries like @container (min-width:300px)\n if (rule.includes(\"@container (min-width:\")) {\n const match = /@container \\(min-width:(\\d+(?:\\.\\d+)?)(px|rem|em)/.exec(rule);\n if (match) {\n const value = parseFloat(match[1]);\n const unit = match[2];\n // Convert to pixels for comparison\n return unit === \"rem\" || unit === \"em\" ? value * 16 : value;\n }\n }\n return -1;\n };\n\n const aRespPx = getResponsivePixels(a);\n const bRespPx = getResponsivePixels(b);\n const aContPx = getContainerPixels(a);\n const bContPx = getContainerPixels(b);\n\n // Sort by responsive breakpoint if both have responsive queries\n if (aRespPx >= 0 && bRespPx >= 0 && aRespPx !== bRespPx) return aRespPx - bRespPx;\n\n // Sort by container breakpoint if both have container queries\n if (aContPx >= 0 && bContPx >= 0 && aContPx !== bContPx) return aContPx - bContPx;\n\n // Keep original order for same breakpoint or no breakpoint\n return 0;\n });\n };\n\n // Sort buckets 2 and 3 which contain responsive/container queries\n buckets[2] = sortRulesByBreakpoint(buckets[2]);\n buckets[3] = sortRulesByBreakpoint(buckets[3]);\n\n const css = buckets.flat().join(\"\");\n\n // Cache size management to prevent memory leaks\n if (jitCssCache.size >= MAX_CACHE_SIZE) {\n // Remove oldest entries (simple FIFO cleanup)\n const keysToDelete = Array.from(jitCssCache.keys()).slice(\n 0,\n Math.floor(MAX_CACHE_SIZE / 2),\n );\n keysToDelete.forEach((key) => jitCssCache.delete(key));\n }\n\n jitCssCache.set(html, { css, timestamp: now });\n return css;\n}\n","import type { VNode } from \"./runtime/types\";\n\n/* --- When --- */\nexport function when(cond: boolean, children: VNode | VNode[]): VNode;\nexport function when(cond: boolean, factory: () => VNode | VNode[]): VNode;\nexport function when(cond: boolean, childrenOrFactory: any): VNode {\n const anchorKey = \"when-block\"; // stable key regardless of condition\n if (typeof childrenOrFactory === \"function\") {\n return anchorBlock(cond ? childrenOrFactory() : [], anchorKey);\n }\n return anchorBlock(cond ? childrenOrFactory : [], anchorKey);\n}\n\n/* --- Each --- */\nexport function each<\n T extends string | number | boolean | { id?: string | number; key?: string },\n>(list: T[], render: (item: T, index: number) => VNode | VNode[]): VNode[] {\n return list.map((item, i) => {\n // For primitives, use value as key; for objects, prefer key/id\n const itemKey =\n typeof item === \"object\"\n ? ((item as any)?.key ?? (item as any)?.id ?? `idx-${i}`)\n : String(item);\n return anchorBlock(render(item, i), `each-${itemKey}`);\n });\n}\n\n/* --- match --- */\nexport function match() {\n const branches: Branch[] = [];\n return {\n when(cond: any, content: VNode | VNode[] | (() => VNode | VNode[])) {\n branches.push([cond, content]);\n return this;\n },\n otherwise(content: VNode | VNode[]) {\n branches.push([true, content]);\n return this;\n },\n done() {\n return whenChain(...branches);\n },\n };\n}\n\n/* --- WhenChain --- */\ntype Branch = [condition: any, content: VNode | VNode[] | (() => VNode | VNode[])];\n\nfunction whenChain(...branches: Branch[]): VNode[] {\n for (let idx = 0; idx < branches.length; idx++) {\n const [cond, content] = branches[idx];\n if (cond) {\n const payload = typeof content === 'function' ? (content as () => VNode | VNode[])() : content;\n return [anchorBlock(payload, `whenChain-branch-${idx}`)];\n }\n }\n return [anchorBlock([], \"whenChain-empty\")];\n}\n\n/**\n * Create a stable anchor block with consistent boundaries.\n * Always has start/end boundaries.\n */\nexport function anchorBlock(\n children: VNode | VNode[] | null | undefined,\n anchorKey: string,\n): VNode {\n // Normalize children to array, filtering out only null/undefined values.\n // Preserve meaningful falsy values such as 0, false, and empty string.\n const childArray = !children\n ? []\n : Array.isArray(children)\n ? children.filter((c) => c !== null && c !== undefined)\n : [children].filter((c) => c !== null && c !== undefined);\n\n return {\n tag: \"#anchor\",\n key: anchorKey,\n children: childArray,\n };\n}","/**\n * Transitions Module\n * Vue-like transition system integrated with JIT CSS\n * Provides Transition and TransitionGroup components for enter/leave animations\n */\n\nimport { anchorBlock } from './directives';\nimport type { VNode } from './runtime/types';\nimport { jitCSS } from './runtime/style';\n\n/* --- Types --- */\n\n/**\n * Transition class names for different animation phases\n * All values should be JIT CSS utility classes\n */\nexport interface TransitionClasses {\n /** Classes applied at the start of enter transition */\n enterFrom?: string;\n /** Classes applied during entire enter transition */\n enterActive?: string;\n /** Classes applied at the end of enter transition */\n enterTo?: string;\n /** Classes applied at the start of leave transition */\n leaveFrom?: string;\n /** Classes applied during entire leave transition */\n leaveActive?: string;\n /** Classes applied at the end of leave transition */\n leaveTo?: string;\n}\n\n/**\n * Lifecycle hooks for transition events\n */\nexport interface TransitionHooks {\n /** Called before enter transition starts */\n onBeforeEnter?: (el: HTMLElement) => void;\n /** Called during enter transition (with done callback for manual control) */\n onEnter?: (el: HTMLElement, done: () => void) => void;\n /** Called after enter transition completes */\n onAfterEnter?: (el: HTMLElement) => void;\n /** Called if enter transition is cancelled */\n onEnterCancelled?: (el: HTMLElement) => void;\n /** Called before leave transition starts */\n onBeforeLeave?: (el: HTMLElement) => void;\n /** Called during leave transition (with done callback for manual control) */\n onLeave?: (el: HTMLElement, done: () => void) => void;\n /** Called after leave transition completes */\n onAfterLeave?: (el: HTMLElement) => void;\n /** Called if leave transition is cancelled */\n onLeaveCancelled?: (el: HTMLElement) => void;\n}\n\n/**\n * Options for Transition component\n */\nexport interface TransitionOptions extends TransitionClasses, TransitionHooks {\n /** Preset name (fade, slide-right, scale, etc.) */\n preset?: keyof typeof transitionPresets;\n /** Whether to show the content */\n show: boolean;\n /** Transition mode: default, out-in (leave before enter), in-out (enter before leave) */\n mode?: 'default' | 'out-in' | 'in-out';\n /** Custom duration override (ms) */\n duration?: number | { enter: number; leave: number };\n /** Whether to apply transition on initial render */\n appear?: boolean;\n /** Whether to use CSS transitions (true) or JS-only hooks (false) */\n css?: boolean;\n /** Optional name for debugging */\n name?: string;\n}\n\n/**\n * Options for TransitionGroup component\n */\nexport interface TransitionGroupOptions extends Omit<TransitionOptions, 'show'> {\n /** HTML tag for the wrapper element */\n tag?: string;\n /** Class applied during move transitions (when items reorder) */\n moveClass?: string;\n /** Whether to show the group (defaults to true for TransitionGroup) */\n show?: boolean;\n /** CSS classes to apply to the wrapper element (e.g., 'flex gap-4' or 'grid grid-cols-3') */\n class?: string;\n /** Inline styles to apply to the wrapper element */\n style?: string | Record<string, string>;\n}\n\n/* --- Transition Presets --- */\n\n/**\n * Pre-defined transition presets using JIT CSS classes\n * Users can reference these by name or define custom classes\n */\nexport const transitionPresets = {\n /** Simple fade in/out */\n fade: {\n enterFrom: 'opacity-0',\n enterActive: 'transition-opacity duration-300 ease-out',\n enterTo: 'opacity-100',\n leaveFrom: 'opacity-100',\n leaveActive: 'transition-opacity duration-200 ease-in',\n leaveTo: 'opacity-0',\n },\n\n /** Slide in from right */\n 'slide-right': {\n enterFrom: 'translate-x-[100%] opacity-0',\n enterActive: 'transition-all duration-300 ease-out',\n enterTo: 'translate-x-[0%] opacity-100',\n leaveFrom: 'translate-x-[0%] opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'translate-x-[100%] opacity-0',\n },\n\n /** Slide in from left */\n 'slide-left': {\n enterFrom: 'translate-x-[-100%] opacity-0',\n enterActive: 'transition-all duration-300 ease-out',\n enterTo: 'translate-x-[0%] opacity-100',\n leaveFrom: 'translate-x-[0%] opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'translate-x-[-100%] opacity-0',\n },\n\n /** Slide up from bottom */\n 'slide-up': {\n enterFrom: 'translate-y-[100%] opacity-0',\n enterActive: 'transition-all duration-300 ease-out',\n enterTo: 'translate-y-[0%] opacity-100',\n leaveFrom: 'translate-y-[0%] opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'translate-y-[100%] opacity-0',\n },\n\n /** Slide down from top */\n 'slide-down': {\n enterFrom: 'translate-y-[-100%] opacity-0',\n enterActive: 'transition-all duration-300 ease-out',\n enterTo: 'translate-y-[0%] opacity-100',\n leaveFrom: 'translate-y-[0%] opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'translate-y-[-100%] opacity-0',\n },\n\n /** Scale up from center */\n scale: {\n enterFrom: 'scale-95 opacity-0',\n enterActive: 'transition-all duration-200 ease-out',\n enterTo: 'scale-100 opacity-100',\n leaveFrom: 'scale-100 opacity-100',\n leaveActive: 'transition-all duration-150 ease-in',\n leaveTo: 'scale-95 opacity-0',\n },\n\n /** Scale down to center */\n 'scale-down': {\n enterFrom: 'scale-105 opacity-0',\n enterActive: 'transition-all duration-200 ease-out',\n enterTo: 'scale-100 opacity-100',\n leaveFrom: 'scale-100 opacity-100',\n leaveActive: 'transition-all duration-150 ease-in',\n leaveTo: 'scale-105 opacity-0',\n },\n\n /** Bounce effect */\n bounce: {\n enterFrom: 'scale-0 opacity-0',\n enterActive: 'transition-all duration-500 ease-out',\n enterTo: 'scale-100 opacity-100',\n leaveFrom: 'scale-100 opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'scale-0 opacity-0',\n },\n\n /** Zoom and fade */\n zoom: {\n enterFrom: 'scale-0 opacity-0',\n enterActive: 'transition-all duration-300 ease-out',\n enterTo: 'scale-100 opacity-100',\n leaveFrom: 'scale-100 opacity-100',\n leaveActive: 'transition-all duration-200 ease-in',\n leaveTo: 'scale-0 opacity-0',\n },\n\n /** Flip in */\n flip: {\n enterFrom: 'rotate-[90deg] opacity-0',\n enterActive: 'transition-all duration-400 ease-out',\n enterTo: 'rotate-[0deg] opacity-100',\n leaveFrom: 'rotate-[0deg] opacity-100',\n leaveActive: 'transition-all duration-300 ease-in',\n leaveTo: 'rotate-[90deg] opacity-0',\n },\n} as const;\n\n/* --- Core Functions --- */\n\n/**\n * Transition component - wraps content with enter/leave animations\n * \n * @example\n * ```ts\n * // Using a preset\n * ${Transition({ preset: 'fade', show: isVisible.value }, html`<div>Content</div>`)}\n * \n * // Using custom JIT classes\n * ${Transition({\n * show: isVisible.value,\n * enterFrom: 'opacity-0 scale-95',\n * enterActive: 'transition-all duration-300',\n * enterTo: 'opacity-100 scale-100',\n * leaveFrom: 'opacity-100 scale-100',\n * leaveActive: 'transition-all duration-200',\n * leaveTo: 'opacity-0 scale-95'\n * }, html`<div>Content</div>`)}\n * \n * // With lifecycle hooks\n * ${Transition({\n * preset: 'slide-right',\n * show: isVisible.value,\n * onAfterEnter: (el) => console.log('Entered!'),\n * onAfterLeave: (el) => console.log('Left!')\n * }, html`<div>Content</div>`)}\n * ```\n */\nexport function Transition(\n options: TransitionOptions,\n content: VNode | VNode[]\n): VNode {\n const {\n preset,\n show,\n mode = 'default',\n duration,\n appear = false,\n css = true,\n name,\n enterFrom,\n enterActive,\n enterTo,\n leaveFrom,\n leaveActive,\n leaveTo,\n onBeforeEnter,\n onEnter,\n onAfterEnter,\n onEnterCancelled,\n onBeforeLeave,\n onLeave,\n onAfterLeave,\n onLeaveCancelled,\n } = options;\n\n // Resolve classes from preset or explicit values\n let transitionClasses: TransitionClasses;\n if (preset && transitionPresets[preset]) {\n transitionClasses = { ...transitionPresets[preset] };\n // Allow overriding preset classes\n if (enterFrom) transitionClasses.enterFrom = enterFrom;\n if (enterActive) transitionClasses.enterActive = enterActive;\n if (enterTo) transitionClasses.enterTo = enterTo;\n if (leaveFrom) transitionClasses.leaveFrom = leaveFrom;\n if (leaveActive) transitionClasses.leaveActive = leaveActive;\n if (leaveTo) transitionClasses.leaveTo = leaveTo;\n } else {\n transitionClasses = {\n enterFrom,\n enterActive,\n enterTo,\n leaveFrom,\n leaveActive,\n leaveTo,\n };\n }\n\n // Create anchor block with transition metadata\n const transitionKey = name || (preset ? `transition-${preset}` : 'transition');\n const transitionVNode = anchorBlock(show ? content : [], transitionKey);\n\n // Attach metadata for VDOM to consume during patching\n (transitionVNode as any)._transition = {\n name: transitionKey,\n classes: transitionClasses,\n mode,\n duration,\n appear,\n css,\n state: show ? 'visible' : 'hidden',\n hooks: {\n onBeforeEnter,\n onEnter,\n onAfterEnter,\n onEnterCancelled,\n onBeforeLeave,\n onLeave,\n onAfterLeave,\n onLeaveCancelled,\n },\n };\n\n return transitionVNode;\n}\n\n/**\n * TransitionGroup component - animates lists with enter/leave/move transitions\n * \n * @example\n * ```ts\n * // Basic usage\n * ${TransitionGroup({\n * preset: 'slide-right',\n * tag: 'ul',\n * moveClass: 'transition-transform duration-300'\n * }, each(items.value, (item) => html`\n * <li key=\"${item.id}\">${item.text}</li>\n * `))}\n * \n * // With flex layout\n * ${TransitionGroup({\n * preset: 'fade',\n * class: 'flex gap-4 flex-wrap'\n * }, each(items.value, (item) => html`\n * <div key=\"${item.id}\" class=\"flex-shrink-0\">${item.text}</div>\n * `))}\n * \n * // With grid layout\n * ${TransitionGroup({\n * preset: 'scale',\n * class: 'grid grid-cols-3 gap-4'\n * }, each(items.value, (item) => html`\n * <div key=\"${item.id}\">${item.text}</div>\n * `))}\n * ```\n */\nexport function TransitionGroup(\n options: TransitionGroupOptions,\n children: VNode[]\n): VNode {\n const {\n tag = 'div',\n moveClass = 'transition-transform duration-300',\n preset,\n show = true,\n mode = 'default',\n duration,\n appear = false,\n css = true,\n name,\n class: className,\n style,\n enterFrom,\n enterActive,\n enterTo,\n leaveFrom,\n leaveActive,\n leaveTo,\n onBeforeEnter,\n onEnter,\n onAfterEnter,\n onEnterCancelled,\n onBeforeLeave,\n onLeave,\n onAfterLeave,\n onLeaveCancelled,\n } = options;\n\n // Resolve classes from preset or explicit values\n let transitionClasses: TransitionClasses;\n if (preset && transitionPresets[preset]) {\n transitionClasses = { ...transitionPresets[preset] };\n // Allow overriding preset classes\n if (enterFrom) transitionClasses.enterFrom = enterFrom;\n if (enterActive) transitionClasses.enterActive = enterActive;\n if (enterTo) transitionClasses.enterTo = enterTo;\n if (leaveFrom) transitionClasses.leaveFrom = leaveFrom;\n if (leaveActive) transitionClasses.leaveActive = leaveActive;\n if (leaveTo) transitionClasses.leaveTo = leaveTo;\n } else {\n transitionClasses = {\n enterFrom,\n enterActive,\n enterTo,\n leaveFrom,\n leaveActive,\n leaveTo,\n };\n }\n\n // Create wrapper element with transition group metadata\n const groupKey = name || (preset ? `transition-group-${preset}` : 'transition-group');\n \n // Flatten anchor block children to enable proper keyed diffing\n // When each() is used, it creates anchor blocks. We need to extract the actual elements\n // and give them keys from their anchor blocks for proper reordering\n const flattenedChildren: VNode[] = [];\n for (const child of (show ? children : [])) {\n if (child && typeof child === 'object' && child.tag === '#anchor') {\n // Extract children from anchor block\n const anchorChildren = Array.isArray(child.children) ? child.children : [];\n for (const anchorChild of anchorChildren) {\n if (anchorChild && typeof anchorChild === 'object') {\n // Use anchor block's key for the child element\n const keyedChild = {\n ...anchorChild,\n key: child.key || anchorChild.key,\n props: {\n ...anchorChild.props,\n _anchorKey: child.key // Preserve original anchor key\n }\n };\n flattenedChildren.push(keyedChild);\n } else {\n flattenedChildren.push(anchorChild);\n }\n }\n } else {\n flattenedChildren.push(child);\n }\n }\n \n return {\n tag,\n children: flattenedChildren,\n key: groupKey,\n props: {\n attrs: {\n ...(className ? { class: className } : {}),\n ...(style ? { style: style } : {}),\n },\n _transitionGroup: {\n name: groupKey,\n classes: transitionClasses,\n moveClass,\n mode,\n duration,\n appear,\n css,\n hooks: {\n onBeforeEnter,\n onEnter,\n onAfterEnter,\n onEnterCancelled,\n onBeforeLeave,\n onLeave,\n onAfterLeave,\n onLeaveCancelled,\n },\n },\n },\n };\n}\n\n/**\n * Helper to create custom transition presets\n * \n * @example\n * ```ts\n * const customFade = createTransitionPreset({\n * enterFrom: 'opacity-0',\n * enterActive: 'transition-opacity duration-500 ease-out',\n * enterTo: 'opacity-100',\n * leaveFrom: 'opacity-100',\n * leaveActive: 'transition-opacity duration-300 ease-in',\n * leaveTo: 'opacity-0'\n * });\n * \n * ${Transition({ ...customFade, show: visible.value }, content)}\n * ```\n */\nexport function createTransitionPreset(classes: TransitionClasses): TransitionClasses {\n return { ...classes };\n}\n\n/**\n * Pre-generate CSS for all transition preset classes\n * This ensures the JIT CSS system has the styles ready when transitions are used\n */\nlet transitionStyleSheet: CSSStyleSheet | null = null;\n\n/**\n * Get the global transition stylesheet (creates it if needed)\n */\nexport function getTransitionStyleSheet(): CSSStyleSheet {\n if (!transitionStyleSheet) {\n const allClasses: string[] = [];\n \n // Collect all classes from presets\n Object.values(transitionPresets).forEach(preset => {\n if (preset.enterFrom) allClasses.push(preset.enterFrom);\n if (preset.enterActive) allClasses.push(preset.enterActive);\n if (preset.enterTo) allClasses.push(preset.enterTo);\n if (preset.leaveFrom) allClasses.push(preset.leaveFrom);\n if (preset.leaveActive) allClasses.push(preset.leaveActive);\n if (preset.leaveTo) allClasses.push(preset.leaveTo);\n });\n\n // Create a fake HTML string with all transition classes\n const fakeHtml = `<div class=\"${allClasses.join(' ')}\"></div>`;\n \n // Trigger JIT CSS generation\n const generatedCSS = jitCSS(fakeHtml);\n\n // Create stylesheet\n transitionStyleSheet = new CSSStyleSheet();\n transitionStyleSheet.replaceSync(generatedCSS);\n }\n \n return transitionStyleSheet;\n}\n\nfunction initializeTransitionCSS(): void {\n // Just initialize the stylesheet on module load\n getTransitionStyleSheet();\n}\n\n// Initialize transition CSS when module loads\ninitializeTransitionCSS();\n","import { vdomRenderer } from \"./vdom\";\nimport { minifyCSS, getBaseResetSheet, sanitizeCSS, jitCSS } from \"./style\";\nimport { getTransitionStyleSheet } from \"../transitions\";\nimport type { ComponentConfig, ComponentContext, VNode, Refs } from \"./types\";\nimport { devWarn, devError } from \"./logger\";\n\n// Module-level stack for context injection (scoped to render cycle, no global pollution)\nexport const contextStack: any[] = [];\n\n/**\n * Renders the component output.\n */\nexport function renderComponent<\n S extends object,\n C extends object,\n P extends object,\n T extends object\n>(\n shadowRoot: ShadowRoot | null,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n refs: Refs[\"refs\"],\n setHtmlString: (html: string) => void,\n setLoading: (val: boolean) => void,\n setError: (err: Error | null) => void,\n applyStyle: (html: string) => void\n): void {\n if (!shadowRoot) return;\n\n // Push context to stack before rendering\n contextStack.push(context);\n\n try {\n // Loading and error states are now handled directly in the functional components\n // rather than through config templates\n\n const outputOrPromise = cfg.render(context);\n\n if (outputOrPromise instanceof Promise) {\n setLoading(true);\n outputOrPromise\n .then((output) => {\n setLoading(false);\n setError(null);\n renderOutput(shadowRoot, output, context, refs, setHtmlString);\n applyStyle(shadowRoot.innerHTML);\n })\n .catch((error) => {\n setLoading(false);\n setError(error);\n // Error handling is now done in the functional components directly\n });\n\n // Loading state is now handled in the functional components directly\n return;\n }\n\n renderOutput(shadowRoot, outputOrPromise, context, refs, setHtmlString);\n applyStyle(shadowRoot.innerHTML);\n } finally {\n // Always pop context from stack after rendering (ensures cleanup even on errors)\n contextStack.pop();\n }\n}\n\n/**\n * Renders VNode(s) to the shadowRoot.\n */\nexport function renderOutput<\n S extends object,\n C extends object,\n P extends object,\n T extends object\n>(\n shadowRoot: ShadowRoot | null,\n output: VNode | VNode[],\n context: ComponentContext<S, C, P, T>,\n refs: Refs[\"refs\"],\n setHtmlString: (html: string) => void\n): void {\n if (!shadowRoot) return;\n vdomRenderer(\n shadowRoot,\n Array.isArray(output) ? output : [output],\n context,\n refs\n );\n setHtmlString(shadowRoot.innerHTML);\n}\n\n/**\n * Debounced render request with infinite loop protection.\n */\nexport function requestRender(\n renderFn: () => void,\n lastRenderTime: number,\n renderCount: number,\n setLastRenderTime: (t: number) => void,\n setRenderCount: (c: number) => void,\n renderTimeoutId: ReturnType<typeof setTimeout> | null,\n setRenderTimeoutId: (id: ReturnType<typeof setTimeout> | null) => void\n): void {\n if (renderTimeoutId !== null) clearTimeout(renderTimeoutId);\n\n const now = Date.now();\n const isRapidRender = now - lastRenderTime < 16;\n\n if (isRapidRender) {\n setRenderCount(renderCount + 1);\n // Progressive warnings and limits\n if (renderCount === 15) {\n devWarn(\n \"⚠️ Component is re-rendering rapidly. This might indicate:\\n\" +\n \" Common causes:\\n\" +\n ' • Event handler calling a function immediately: @click=\"${fn()}\" should be @click=\"${fn}\"\\n' +\n \" • State modification during render\\n\" +\n \" • Missing dependencies in computed/watch\\n\" +\n \" Component rendering will be throttled to prevent browser freeze.\"\n );\n } else if (renderCount > 20) {\n // More aggressive limit for severe infinite loops\n devError(\n \"🛑 Infinite loop detected in component render:\\n\" +\n \" • This might be caused by state updates during render\\n\" +\n \" • Ensure all state modifications are done in event handlers or effects\\n\" +\n \"Stopping runaway component render to prevent browser freeze\"\n );\n setRenderTimeoutId(null);\n return;\n }\n } else {\n setRenderCount(0);\n }\n\n const timeoutId = setTimeout(\n () => {\n setLastRenderTime(Date.now());\n renderFn();\n setRenderTimeoutId(null);\n },\n renderCount > 10 ? 100 : 0\n ); // Add delay for rapid renders\n setRenderTimeoutId(timeoutId);\n}\n\n/**\n * Applies styles to the shadowRoot.\n */\nexport function applyStyle<\n S extends object,\n C extends object,\n P extends object,\n T extends object\n>(\n shadowRoot: ShadowRoot | null,\n context: ComponentContext<S, C, P, T>,\n htmlString: string,\n styleSheet: CSSStyleSheet | null,\n setStyleSheet: (sheet: CSSStyleSheet | null) => void\n): void {\n if (!shadowRoot) return;\n\n // Include rendered HTML from child component instances (if available)\n // so JIT CSS can find utility classes rendered inside child shadow DOM.\n let aggregatedHtml = htmlString || \"\";\n try {\n if (shadowRoot) {\n const allEls = Array.from(\n shadowRoot.querySelectorAll(\"*\")\n ) as HTMLElement[];\n for (const el of allEls) {\n try {\n const childHtml = (el as any).lastHtmlStringForJitCSS;\n if (childHtml && typeof childHtml === \"string\" && childHtml.trim()) {\n aggregatedHtml += \"\\n\" + childHtml;\n }\n } catch (e) {\n // best-effort: ignore errors while reading child's cached HTML\n }\n }\n }\n } catch (e) {}\n\n const jitCss = jitCSS(aggregatedHtml);\n\n if ((!jitCss || jitCss.trim() === \"\") && !(context as any)._computedStyle) {\n setStyleSheet(null);\n shadowRoot.adoptedStyleSheets = [\n getBaseResetSheet(),\n getTransitionStyleSheet(),\n ];\n return;\n }\n\n let userStyle = \"\";\n\n // Check for precomputed style from useStyle hook\n if ((context as any)._computedStyle) {\n userStyle = (context as any)._computedStyle;\n }\n\n let finalStyle = sanitizeCSS(`${userStyle}\\n${jitCss}\\n`);\n finalStyle = minifyCSS(finalStyle);\n\n let sheet = styleSheet;\n if (!sheet) sheet = new CSSStyleSheet();\n\n // Compare by replacing the stylesheet entirely if rules changed\n // Avoid using .toString() which may not be reliable across browsers\n const needsUpdate =\n sheet.cssRules.length === 0 ||\n (sheet.cssRules.length > 0 &&\n Array.from(sheet.cssRules)\n .map((r) => r.cssText)\n .join(\"\") !== finalStyle);\n\n if (needsUpdate) {\n sheet.replaceSync(finalStyle);\n }\n\n shadowRoot.adoptedStyleSheets = [\n getBaseResetSheet(),\n getTransitionStyleSheet(),\n sheet,\n ];\n setStyleSheet(sheet);\n}\n","/**\n * Context-based hooks for functional components\n * Provides React-like hooks with perfect TypeScript inference\n */\n\n// Global state to track current component context during render\nlet currentComponentContext: any = null;\nimport { isReactiveState } from \"./reactive\";\nimport { toKebab } from \"./helpers\";\nimport { devWarn } from \"./logger\";\n\n/**\n * Set the current component context (called internally during render)\n * @internal\n */\nexport function setCurrentComponentContext(context: any): void {\n currentComponentContext = context;\n}\n\n/**\n * Clear the current component context (called internally after render)\n * @internal\n */\nexport function clearCurrentComponentContext(): void {\n currentComponentContext = null;\n}\n\n/**\n * Get the emit function for the current component\n * Must be called during component render\n *\n * @example\n * ```ts\n * component('my-button', () => {\n * const { label } = useProps({ label: 'Click me' });\n * const emit = useEmit();\n *\n * return html`\n * <button @click=\"${() => emit('button-click', { label })}\">\n * ${label}\n * </button>\n * `;\n * });\n * ```\n */\nexport function useEmit(): (eventName: string, detail?: any) => boolean {\n if (!currentComponentContext) {\n throw new Error(\"useEmit must be called during component render\");\n }\n\n // Capture the emit function from the current context\n const emitFn = currentComponentContext.emit;\n return (eventName: string, detail?: any) => {\n return emitFn(eventName, detail);\n };\n}\n\n/**\n * Initialize hook callbacks storage on context if not exists\n * Uses Object.defineProperty to avoid triggering reactive updates\n */\nfunction ensureHookCallbacks(context: any): void {\n if (!context._hookCallbacks) {\n Object.defineProperty(context, \"_hookCallbacks\", {\n value: {},\n writable: true,\n enumerable: false,\n configurable: false,\n });\n }\n}\n\n/**\n * Register a callback to be called when component is connected to DOM\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnConnected(() => {\n * console.log('Component mounted!');\n * });\n *\n * return html`<div>Hello World</div>`;\n * });\n * ```\n */\nexport function useOnConnected(callback: () => void): void {\n if (!currentComponentContext) {\n throw new Error(\"useOnConnected must be called during component render\");\n }\n\n ensureHookCallbacks(currentComponentContext);\n currentComponentContext._hookCallbacks.onConnected = callback;\n}\n\n/**\n * Register a callback to be called when component is disconnected from DOM\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnDisconnected(() => {\n * console.log('Component unmounted!');\n * });\n *\n * return html`<div>Goodbye World</div>`;\n * });\n * ```\n */\nexport function useOnDisconnected(callback: () => void): void {\n if (!currentComponentContext) {\n throw new Error(\"useOnDisconnected must be called during component render\");\n }\n\n ensureHookCallbacks(currentComponentContext);\n currentComponentContext._hookCallbacks.onDisconnected = callback;\n}\n\n/**\n * Register a callback to be called when an attribute changes\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnAttributeChanged((name, oldValue, newValue) => {\n * console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`);\n * });\n *\n * return html`<div>Attribute watcher</div>`;\n * });\n * ```\n */\nexport function useOnAttributeChanged(\n callback: (\n name: string,\n oldValue: string | null,\n newValue: string | null\n ) => void\n): void {\n if (!currentComponentContext) {\n throw new Error(\n \"useOnAttributeChanged must be called during component render\"\n );\n }\n\n ensureHookCallbacks(currentComponentContext);\n currentComponentContext._hookCallbacks.onAttributeChanged = callback;\n}\n\n/**\n * Register a callback to be called when an error occurs\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnError((error) => {\n * console.error('Component error:', error);\n * });\n *\n * return html`<div>Error handler</div>`;\n * });\n * ```\n */\nexport function useOnError(callback: (error: Error) => void): void {\n if (!currentComponentContext) {\n throw new Error(\"useOnError must be called during component render\");\n }\n\n ensureHookCallbacks(currentComponentContext);\n currentComponentContext._hookCallbacks.onError = callback;\n}\n\n/**\n * Register prop defaults for the component. Can be called during render.\n * Stores the prop defaults on `context._hookCallbacks.props` so the runtime\n * can pick them up when building the component config.\n *\n * Example:\n * ```ts\n * component('my-comp', () => {\n * useProps({ modelValue: false, label: 'Hello' });\n * return html`<div/>`;\n * });\n * ```\n */\nexport function useProps<T extends Record<string, any>>(defaults: T): T {\n if (!currentComponentContext) {\n throw new Error(\"useProps must be called during component render\");\n }\n\n ensureHookCallbacks(currentComponentContext);\n currentComponentContext._hookCallbacks.props = {\n ...(currentComponentContext._hookCallbacks.props || {}),\n ...defaults,\n };\n\n const ctx = currentComponentContext;\n // Define dynamic getters for declared props so the context property\n // always reflects the host element's property (or reactive ref.value)\n try {\n const declaredKeys = Object.keys(defaults || {});\n for (const key of declaredKeys) {\n if (typeof key !== \"string\" || key.startsWith(\"_\")) continue;\n const existing = Object.getOwnPropertyDescriptor(ctx, key);\n // Only define if not present or configurable (allow overriding)\n if (existing && !existing.configurable) continue;\n try {\n // Preserve any existing concrete value on the context in a closure.\n // This avoids recursive getters when we later reference ctx[key].\n const hasOwn = Object.prototype.hasOwnProperty.call(ctx, key);\n let localValue: any = hasOwn ? (ctx as any)[key] : undefined;\n\n Object.defineProperty(ctx, key, {\n configurable: true,\n enumerable: true,\n get() {\n try {\n const host = (ctx && (ctx as any)._host) as\n | HTMLElement\n | undefined;\n if (host) {\n // First, check for attribute value (attributes should take precedence)\n const kebabKey = toKebab(key);\n const attrValue = host.getAttribute(kebabKey);\n if (attrValue !== null) {\n const defaultType = typeof defaults[key];\n if (defaultType === \"boolean\") {\n // Standalone boolean attributes have empty string value\n return attrValue === \"\" || attrValue === \"true\";\n }\n if (defaultType === \"number\") {\n return Number(attrValue);\n }\n return attrValue;\n }\n\n // If no attribute, check if host has a property value set\n if (typeof (host as any)[key] !== \"undefined\") {\n const fromHost = (host as any)[key];\n // prefer host value when present\n // If the host provided a ReactiveState instance or a wrapper\n // with a .value, unwrap it here so destructured props and\n // useProps return the primitive/current value consistently.\n if (isReactiveState(fromHost)) {\n return (fromHost as any).value;\n }\n if (\n fromHost &&\n typeof fromHost === \"object\" &&\n \"value\" in fromHost &&\n !(fromHost instanceof Node)\n ) {\n return (fromHost as any).value;\n }\n // For string-typed declared props, avoid returning host\n // object-like properties (for example `element.style` which\n // is a CSSStyleDeclaration). Prefer attribute value or the\n // local default instead of returning a non-primitive host\n // property into templates which expect primitives.\n const defaultType = typeof defaults[key];\n if (\n defaultType === \"string\" &&\n fromHost &&\n typeof fromHost === \"object\"\n ) {\n // fallthrough to localValue\n } else {\n // For boolean defaults, treat empty string (standalone attribute) or 'true' as true.\n if (\n defaultType === \"boolean\" &&\n typeof fromHost === \"string\"\n ) {\n return fromHost === \"\" || fromHost === \"true\";\n }\n return fromHost;\n }\n }\n }\n } catch (e) {\n // ignore host read failures and fall back to context\n }\n return localValue;\n },\n set(v: any) {\n // allow test/runtime code to set context props during render/init\n localValue = v;\n },\n });\n } catch (e) {\n // ignore\n }\n }\n } catch (e) {\n // ignore\n }\n // Return a Proxy that always reads the latest value from the component\n // context so accesses are reactive. Also unwrap functional refs ({ value })\n // and coerce string attribute values to boolean/number when defaults\n // indicate such types.\n const result = new Proxy({} as any, {\n get(_target, prop: string) {\n if (typeof prop !== \"string\") return undefined;\n const def = (defaults as any)[prop];\n\n // If a host element is available, prefer reading from attributes first,\n // then from properties. This ensures that HTML attributes take precedence\n // over default property values (like the standard \"title\" attribute).\n try {\n const host = (ctx && (ctx as any)._host) as HTMLElement | undefined;\n if (host) {\n // Check attribute first (only if host is an actual HTMLElement)\n if (\n host instanceof HTMLElement ||\n (typeof (host as any).getAttribute === \"function\" &&\n typeof (host as any).hasAttribute === \"function\")\n ) {\n const kebabKey = prop.replace(/([A-Z])/g, \"-$1\").toLowerCase();\n const attrValue = (host as any).getAttribute(kebabKey);\n if (attrValue !== null) {\n // Attribute exists - convert based on default type\n if (typeof def === \"boolean\") {\n return attrValue === \"\" || attrValue === \"true\";\n }\n if (typeof def === \"number\") {\n return Number(attrValue);\n }\n return attrValue;\n }\n }\n\n // No attribute - check property value\n const hostValue = (host as any)[prop];\n // Only use host value if it's explicitly set (not undefined AND not empty string for string defaults)\n // Empty strings on standard HTML properties (like 'title') should fall through to defaults\n if (typeof hostValue !== \"undefined\" && hostValue !== \"\") {\n // If the declared default is a string, avoid returning raw DOM\n // object-like properties (such as element.style which is a CSSStyleDeclaration)\n // since templates expect primitives and serializing objects can\n // cause DOMExceptions. However, wrapper-like objects that expose\n // a `.value` property (or ReactiveState instances) should be\n // unwrapped and returned even for string defaults.\n const isWrapperLike =\n hostValue &&\n typeof hostValue === \"object\" &&\n \"value\" in hostValue &&\n !(hostValue instanceof Node);\n if (\n typeof def === \"string\" &&\n hostValue &&\n typeof hostValue === \"object\" &&\n !isWrapperLike &&\n !isReactiveState(hostValue)\n ) {\n // treat as not present and fall through to ctx/default\n } else {\n // Special handling for boolean props: if default is false and hostValue is empty string,\n // treat it as if the property wasn't set (use default false)\n if (\n typeof def === \"boolean\" &&\n def === false &&\n hostValue === \"\"\n ) {\n return def;\n }\n\n // Unwrap ReactiveState instances and wrapper-like objects coming\n // from the host so useProps mirrors applyProps/destructured props\n // behavior and returns primitive/current values.\n if (isReactiveState(hostValue)) {\n return (hostValue as any).value;\n }\n if (isWrapperLike) {\n return (hostValue as any).value;\n }\n\n // Primitive on host - return directly (but coerce strings if default provided)\n if (typeof def === \"boolean\" && typeof hostValue === \"string\") {\n // For boolean attributes, only explicit 'true' string or non-empty presence means true\n return (\n hostValue === \"true\" ||\n (hostValue !== \"\" && hostValue !== \"false\")\n );\n }\n if (\n typeof def === \"number\" &&\n typeof hostValue === \"string\" &&\n !Number.isNaN(Number(hostValue))\n )\n return Number(hostValue);\n return hostValue;\n }\n }\n }\n } catch (e) {\n // ignore host read failures and fall back to context\n }\n\n // Fall back to reading from the component context itself.\n const raw = ctx[prop];\n // Treat empty-string on context as boolean true (attribute presence)\n // EXCEPT when the default is false - in that case, empty string means \"not set\"\n if (typeof def === \"boolean\" && raw === \"\") {\n if (def === false) {\n // For boolean props with default false, empty string means use the default\n return def;\n }\n // For boolean props with default true, empty string means attribute presence = true\n return true;\n }\n // If the context stores a ReactiveState or wrapper, unwrap it here\n // so components using useProps receive the primitive/current value\n // when the source is the component context itself. Host-provided\n // ReactiveState instances are preserved above; this path is only\n // for ctx values and defaults.\n if (isReactiveState(raw)) return (raw as any).value;\n if (\n raw &&\n typeof raw === \"object\" &&\n \"value\" in raw &&\n !(raw instanceof Node)\n )\n return (raw as any).value;\n if (raw != null && raw !== \"\") {\n if (typeof def === \"boolean\" && typeof raw === \"string\") {\n return raw === \"true\";\n }\n if (\n typeof def === \"number\" &&\n typeof raw === \"string\" &&\n !Number.isNaN(Number(raw))\n )\n return Number(raw);\n return raw;\n }\n return def;\n },\n has(_target, prop: string) {\n return typeof prop === \"string\" && (prop in ctx || prop in defaults);\n },\n ownKeys() {\n return Array.from(\n new Set([...Object.keys(defaults), ...Object.keys(ctx || {})])\n );\n },\n getOwnPropertyDescriptor() {\n return { configurable: true, enumerable: true } as PropertyDescriptor;\n },\n });\n\n return result as T;\n}\n\n/**\n * Register prop defaults and return a stable props object for use inside render.\n * The returned object reads values from the current component context at render\n * time and falls back to the provided defaults. This keeps prop access stable\n * in production builds and avoids reliance on parsing the render function.\n *\n * Must be called during render. Example:\n * const props = useProps({ modelValue: false });\n */\n// (useProps now returns the props object directly)\n\n/**\n * Register a style function that will be called during each render\n * to provide reactive styles for the component\n *\n * @example\n * ```ts\n * import { css } from '@lib/style';\n *\n * component('my-component', () => {\n * const { theme } = useProps({ theme: 'light' });\n *\n * useStyle(() => css`\n * :host {\n * background: ${theme === 'light' ? 'white' : 'black'};\n * color: ${theme === 'light' ? 'black' : 'white'};\n * }\n * `);\n *\n * return html`<div>Styled component</div>`;\n * });\n * ```\n */\nexport function useStyle(callback: () => string): void {\n if (!currentComponentContext) {\n throw new Error(\"useStyle must be called during component render\");\n }\n\n ensureHookCallbacks(currentComponentContext);\n\n // Execute the callback immediately during render to capture the current style\n // This ensures reactive state is read during the render phase, not during style application\n try {\n const computedStyle = callback();\n\n // Store the computed style using Object.defineProperty to avoid triggering reactive updates\n Object.defineProperty(currentComponentContext, \"_computedStyle\", {\n value: computedStyle,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n } catch (error) {\n devWarn(\"Error in useStyle callback:\", error);\n Object.defineProperty(currentComponentContext, \"_computedStyle\", {\n value: \"\",\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n}\n","import type {\n ComponentConfig,\n ComponentContext,\n Refs,\n WatcherState,\n VNode,\n} from \"./types\";\nimport { reactiveSystem, isReactiveState } from \"./reactive\";\nimport { toKebab, safe } from \"./helpers\";\nimport { initWatchers, triggerWatchers } from \"./watchers\";\nimport { applyProps } from \"./props\";\nimport {\n handleConnected,\n handleDisconnected,\n handleAttributeChanged,\n} from \"./lifecycle\";\nimport { renderComponent, requestRender, applyStyle } from \"./render\";\nimport { scheduleDOMUpdate } from \"./scheduler\";\nimport {\n setCurrentComponentContext,\n clearCurrentComponentContext,\n} from \"./hooks\";\nimport { devError, devWarn } from \"./logger\";\n\n/**\n * @internal\n * Runtime registry of component configs.\n * NOTE: This is an internal implementation detail. Do not import from the\n * published package in consumer code — it is intended for runtime/HMR and\n * internal tests only. Consumers should use the public `component` API.\n */\nexport const registry = new Map<string, ComponentConfig<any, any, any>>();\n\n// Expose the registry for browser/HMR use without overwriting existing globals\n// (avoid cross-request mutation in SSR and preserve HMR behavior).\nconst GLOBAL_REG_KEY = Symbol.for(\"cer.registry\");\nif (typeof window !== \"undefined\") {\n const g = globalThis as any;\n // Authoritative, collision-safe slot for programmatic access\n if (!g[GLOBAL_REG_KEY]) g[GLOBAL_REG_KEY] = registry;\n}\n\n// --- Hot Module Replacement (HMR) ---\nif (\n typeof import.meta !== \"undefined\" &&\n (import.meta as any).hot &&\n import.meta &&\n import.meta.hot\n) {\n import.meta.hot.accept((newModule) => {\n // Update registry with new configs from the hot module\n if (newModule && newModule.registry) {\n for (const [tag, newConfig] of newModule.registry.entries()) {\n registry.set(tag, newConfig);\n // Update all instances to use new config\n if (typeof document !== \"undefined\") {\n document.querySelectorAll(tag).forEach((el) => {\n if (typeof (el as any)._cfg !== \"undefined\") {\n (el as any)._cfg = newConfig;\n }\n // HMR: Preserve existing state by keeping the context object intact.\n // Instead of re-executing the component function (which would create new refs),\n // we just update the config and re-render with the existing context.\n // This ensures refs and other reactive state are preserved across HMR updates.\n if (typeof (el as any)._render === \"function\") {\n (el as any)._render(newConfig);\n }\n });\n }\n }\n }\n });\n}\n\nexport function createElementClass<\n S extends object,\n C extends object,\n P extends object,\n T extends object = any\n>(\n tag: string,\n config: ComponentConfig<S, C, P, T>\n): CustomElementConstructor | { new (): object } {\n // Validate that render is provided\n if (!config.render) {\n throw new Error(\"Component must have a render function\");\n }\n if (typeof window === \"undefined\") {\n // SSR fallback: minimal class, no DOM, no lifecycle, no \"this\"\n return class {\n constructor() {}\n };\n }\n return class extends HTMLElement {\n public context: ComponentContext<S, C, P, T>;\n private _refs: Refs[\"refs\"] = {};\n private _listeners: Array<() => void> = [];\n private _watchers: Map<string, WatcherState> = new Map();\n /** @internal */\n private _renderTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private _mounted = false;\n private _hasError = false;\n private _initializing = true;\n\n private _componentId: string;\n\n private _styleSheet: CSSStyleSheet | null = null;\n\n private _lastHtmlStringForJitCSS = \"\";\n\n /**\n * Returns the last rendered HTML string for JIT CSS.\n */\n public get lastHtmlStringForJitCSS(): string {\n return this._lastHtmlStringForJitCSS;\n }\n\n /**\n * Returns true if the component is currently loading.\n */\n public get isLoading(): boolean {\n return this._templateLoading;\n }\n\n /**\n * Returns the last error thrown during rendering, or null if none.\n */\n public get lastError(): Error | null {\n return this._templateError;\n }\n\n private _cfg: ComponentConfig<S, C, P, T>;\n private _lastRenderTime = 0;\n private _renderCount = 0;\n private _templateLoading = false;\n private _templateError: Error | null = null;\n\n constructor() {\n super();\n this.attachShadow({ mode: \"open\" });\n // Always read the latest config from the registry so re-registration\n // (HMR / tests) updates future instances.\n this._cfg = (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n\n // Generate unique component ID for render deduplication\n this._componentId = `${tag}-${Math.random().toString(36).substr(2, 9)}`;\n\n const reactiveContext = this._initContext(config);\n\n // Helper to define non-enumerable properties\n const defineNonEnum = (obj: any, key: string, value: any) => {\n Object.defineProperty(obj, key, {\n value,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n };\n\n // Inject refs into context (non-enumerable to avoid proxy traps)\n defineNonEnum(reactiveContext, \"refs\", this._refs);\n defineNonEnum(reactiveContext, \"requestRender\", () =>\n this.requestRender()\n );\n defineNonEnum(reactiveContext, \"_requestRender\", () =>\n this._requestRender()\n );\n defineNonEnum(reactiveContext, \"_componentId\", this._componentId);\n defineNonEnum(\n reactiveContext,\n \"_triggerWatchers\",\n (path: string, newValue: any) => this._triggerWatchers(path, newValue)\n );\n\n // --- Apply props BEFORE wiring listeners and emit ---\n this.context = reactiveContext;\n // Expose host element on the reactive context so hooks like useProps\n // can fallback to reading element properties when attributes were\n // serialized (e.g., objects became \"[object Object]\"). This is added\n // as a non-enumerable field to avoid interfering with reactive proxy.\n safe(() => {\n defineNonEnum(reactiveContext, \"_host\", this);\n });\n // Defer applying props until connectedCallback so attributes that are\n // set by the parent renderer (after element construction) are available.\n // applyProps will still be invoked from attributeChangedCallback when\n // attributes are set; connectedCallback will call it as a final step to\n // ensure defaults are applied when no attributes are present.\n\n // Inject emit helper for custom events (single canonical event API).\n // Emits a DOM CustomEvent and returns whether it was not defaultPrevented.\n defineNonEnum(\n this.context,\n \"emit\",\n (eventName: string, detail?: any, options?: CustomEventInit) => {\n const eventOptions = {\n detail,\n bubbles: true,\n composed: true,\n ...(options || {}),\n };\n const ev = new CustomEvent(eventName, eventOptions);\n\n // Primary event dispatch\n this.dispatchEvent(ev);\n\n // Dispatch alternate camel/kebab variation for compatibility\n const colonIndex = eventName.indexOf(\":\");\n if (colonIndex > 0) {\n const prefix = eventName.substring(0, colonIndex);\n const prop = eventName.substring(colonIndex + 1);\n const altName = prop.includes(\"-\")\n ? `${prefix}:${prop\n .split(\"-\")\n .map((p, i) =>\n i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1)\n )\n .join(\"\")}`\n : `${prefix}:${prop\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .toLowerCase()}`;\n if (altName !== eventName) {\n safe(() => {\n this.dispatchEvent(new CustomEvent(altName, eventOptions));\n });\n }\n }\n\n return !ev.defaultPrevented;\n }\n );\n\n // --- Inject config methods into context ---\n // Expose config functions on the context as callable helpers. Event\n // handling is DOM-first: use standard DOM event listeners or\n // `context.emit` (which dispatches a DOM CustomEvent) to communicate\n // with the host. There is no property-based host-callback dispatch.\n const cfgToUse =\n (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n for (const key in cfgToUse) {\n const fn = (cfgToUse as any)[key];\n if (typeof fn === \"function\") {\n // Expose as context method: context.fn(...args) => fn(...args, context)\n (this.context as any)[key] = (...args: any[]) =>\n fn(...args, this.context);\n }\n }\n\n // Set up reactive property setters for all props to detect external changes\n if (cfgToUse.props) {\n for (const propName in cfgToUse.props) {\n let internalValue = (this as any)[propName];\n\n Object.defineProperty(this, propName, {\n get() {\n return internalValue;\n },\n set(newValue) {\n const oldValue = internalValue;\n internalValue = newValue;\n\n // Update the context to trigger watchers\n (this.context as any)[propName] = newValue;\n\n // Apply props to sync with context\n if (!this._initializing) {\n this._applyProps(cfgToUse);\n // Trigger re-render if the value actually changed\n if (oldValue !== newValue) {\n this._requestRender();\n }\n }\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n this._initializing = false;\n\n // Initialize watchers after initialization phase is complete\n this._initWatchers(cfgToUse);\n\n // Apply props before initial render so they're available immediately\n // Note: Attributes set by parent renderers may not be available yet,\n // but connectedCallback will re-apply props and re-render\n this._applyProps(cfgToUse);\n\n // Initial render (styles are applied within render)\n this._render(cfgToUse);\n }\n\n connectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n // Ensure props reflect attributes set by the parent renderer before\n // invoking lifecycle hooks.\n this._applyProps(config);\n // Re-render after applying props to ensure component shows updated values\n this._requestRender();\n handleConnected(config, this.context, this._mounted, (val) => {\n this._mounted = val;\n });\n });\n }\n\n disconnectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n handleDisconnected(\n config,\n this.context,\n this._listeners,\n () => {\n this._listeners = [];\n },\n () => {\n this._watchers.clear();\n },\n (val) => {\n this._templateLoading = val;\n },\n (err) => {\n this._templateError = err;\n },\n (val) => {\n this._mounted = val;\n }\n );\n });\n }\n\n attributeChangedCallback(\n name: string,\n oldValue: string | null,\n newValue: string | null\n ) {\n this._runLogicWithinErrorBoundary(config, () => {\n this._applyProps(config);\n // Re-render after applying props to ensure component shows updated values\n if (oldValue !== newValue) {\n this._requestRender();\n }\n handleAttributeChanged(config, name, oldValue, newValue, this.context);\n });\n }\n\n static get observedAttributes() {\n return config.props ? Object.keys(config.props).map(toKebab) : [];\n }\n\n // --- Render ---\n private _render(cfg: ComponentConfig<S, C, P, T>) {\n this._runLogicWithinErrorBoundary(cfg, () => {\n // _render invoked; proceed to render via renderComponent\n renderComponent(\n this.shadowRoot,\n cfg,\n this.context,\n this._refs,\n (html) => {\n this._lastHtmlStringForJitCSS = html;\n // Optionally, use the latest HTML string for debugging or external logic\n if (typeof (this as any).onHtmlStringUpdate === \"function\") {\n (this as any).onHtmlStringUpdate(html);\n }\n },\n (val) => {\n this._templateLoading = val;\n // Optionally, use loading state for external logic\n if (typeof (this as any).onLoadingStateChange === \"function\") {\n (this as any).onLoadingStateChange(val);\n }\n },\n (err) => {\n this._templateError = err;\n // Optionally, use error state for external logic\n if (typeof (this as any).onErrorStateChange === \"function\") {\n (this as any).onErrorStateChange(err);\n }\n },\n (html) => this._applyStyle(cfg, html)\n );\n });\n }\n\n public requestRender() {\n this._requestRender();\n }\n\n _requestRender() {\n this._runLogicWithinErrorBoundary(this._cfg, () => {\n // Use scheduler to batch render requests\n scheduleDOMUpdate(() => {\n requestRender(\n () => this._render(this._cfg),\n this._lastRenderTime,\n this._renderCount,\n (t) => {\n this._lastRenderTime = t;\n },\n (c) => {\n this._renderCount = c;\n },\n this._renderTimeoutId,\n (id) => {\n this._renderTimeoutId = id;\n }\n );\n }, this._componentId);\n });\n }\n\n // --- Style ---\n private _applyStyle(cfg: ComponentConfig<S, C, P, T>, html: string) {\n this._runLogicWithinErrorBoundary(cfg, () => {\n applyStyle(\n this.shadowRoot,\n this.context,\n html,\n this._styleSheet,\n (sheet) => {\n this._styleSheet = sheet;\n }\n );\n });\n }\n\n // --- Error Boundary function ---\n private _runLogicWithinErrorBoundary(\n cfg: ComponentConfig<S, C, P, T>,\n fn: () => void\n ) {\n if (this._hasError) this._hasError = false;\n try {\n fn();\n } catch (error) {\n this._hasError = true;\n\n // DEV-only diagnostic: provide actionable context to help debugging\n try {\n const tag =\n (cfg && (cfg as any).tag) ||\n this.tagName?.toLowerCase?.() ||\n \"<unknown>\";\n const compId = this._componentId || \"<unknown-id>\";\n const safeProps: Record<string, any> = {};\n if (cfg && (cfg as any).props) {\n for (const k of Object.keys((cfg as any).props)) {\n try {\n const v = (this.context as any)[k];\n if (v instanceof Node) {\n safeProps[k] = `[DOM Node: ${v.nodeName}]`;\n } else if (typeof v === \"object\" && v !== null) {\n safeProps[k] =\n Object.keys(v).length > 5\n ? `[object(${Object.keys(v).length} keys)]`\n : v;\n } else {\n safeProps[k] = v;\n }\n } catch (e) {\n safeProps[k] = \"[unreadable]\";\n }\n }\n }\n\n devError(`Error rendering component <${tag}> (id=${compId}):`, error);\n devError(\"Component props snapshot:\", safeProps);\n devWarn(\n \"Common causes: accessing properties of null/undefined inside template interpolations; expensive or throwing expressions inside templates that evaluate eagerly. Fixes: use optional chaining (obj?.prop), guard with ternary, or use the runtime lazy overload: when(cond, () => html`...`).\"\n );\n } catch (e) {\n // best-effort diagnostics - swallow failures here to preserve original behavior\n }\n\n if (cfg.onError) {\n cfg.onError(error as Error | null, this.context);\n }\n }\n }\n\n // --- State, props, computed ---\n private _initContext(\n cfg: ComponentConfig<S, C, P, T>\n ): ComponentContext<S, C, P, T> {\n try {\n const self = this;\n function createReactive(obj: any, path = \"\"): any {\n if (Array.isArray(obj)) {\n // Create a proxy that intercepts array mutations\n return new Proxy(obj, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept array mutating methods\n if (typeof value === \"function\" && typeof prop === \"string\") {\n const mutatingMethods = [\n \"push\",\n \"pop\",\n \"shift\",\n \"unshift\",\n \"splice\",\n \"sort\",\n \"reverse\",\n ];\n if (mutatingMethods.includes(prop)) {\n return function (...args: any[]) {\n const result = value.apply(target, args);\n\n if (!self._initializing) {\n const fullPath = path || \"root\";\n self._triggerWatchers(fullPath, target);\n scheduleDOMUpdate(\n () => self._render(cfg),\n self._componentId\n );\n }\n\n return result;\n };\n }\n }\n\n return value;\n },\n set(target, prop, value) {\n target[prop as any] = value;\n if (!self._initializing) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n self._triggerWatchers(fullPath, value);\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n deleteProperty(target, prop) {\n delete target[prop as any];\n if (!self._initializing) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n self._triggerWatchers(fullPath, undefined);\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n });\n }\n if (obj && typeof obj === \"object\") {\n // Skip ReactiveState objects to avoid corrupting their internal structure\n if (isReactiveState(obj)) {\n return obj;\n }\n\n for (const key in obj) {\n const newPath = path ? `${path}.${key}` : key;\n obj[key] = createReactive(obj[key], newPath);\n }\n return new Proxy(obj, {\n set(target, prop, value) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n target[prop as any] = createReactive(value, fullPath);\n if (!self._initializing) {\n self._triggerWatchers(fullPath, target[prop as any]);\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n get(target, prop, receiver) {\n return Reflect.get(target, prop, receiver);\n },\n });\n }\n return obj;\n }\n return createReactive({\n // For functional components, state is managed by state() function calls\n // Include prop defaults in initial reactive context so prop updates trigger reactivity\n ...(cfg.props\n ? Object.fromEntries(\n Object.entries(cfg.props).map(([key, def]) => [\n key,\n def.default,\n ])\n )\n : {}),\n }) as ComponentContext<S, C, P, T>;\n } catch (error) {\n return {} as ComponentContext<S, C, P, T>;\n }\n }\n\n private _initWatchers(cfg: ComponentConfig<S, C, P, T>): void {\n this._runLogicWithinErrorBoundary(cfg, () => {\n initWatchers(\n this.context,\n this._watchers,\n {} // Watchers are now handled by the watch() function in functional API\n );\n });\n }\n\n private _triggerWatchers(path: string, newValue: any): void {\n triggerWatchers(this.context, this._watchers, path, newValue);\n }\n\n private _applyProps(cfg: ComponentConfig<S, C, P, T>): void {\n this._runLogicWithinErrorBoundary(cfg, () => {\n try {\n applyProps(this, cfg, this.context);\n } catch (error) {\n this._hasError = true;\n if (cfg.onError) cfg.onError(error as Error | null, this.context);\n // Note: errorFallback was removed as it's handled by the functional API directly\n }\n });\n }\n };\n}\n\n/**\n * Streamlined functional component API with automatic reactive props and lifecycle hooks.\n *\n * @example\n * ```ts\n * // Simple component with no parameters\n * component('simple-header', () => {\n * return html`<h1>Hello World</h1>`;\n * });\n *\n * // With props using useProps() hook\n * component('with-props', () => {\n * const { message } = useProps({ message: 'Hello' });\n * return html`<div>${message}</div>`;\n * });\n *\n * // With props and lifecycle hooks\n * component('my-switch', () => {\n * const { modelValue, label } = useProps({ modelValue: false, label: '' });\n * const emit = useEmit();\n *\n * useOnConnected(() => console.log('Switch connected!'));\n * useOnDisconnected(() => console.log('Switch disconnected!'));\n *\n * return html`\n * <label>\n * ${label}\n * <input\n * type=\"checkbox\"\n * :checked=\"${modelValue}\"\n * @change=\"${(e) => emit('update:modelValue', e.target.checked)}\"\n * />\n * </label>\n * `;\n * });\n * ```\n */\n\n// Overload: No parameters - use useProps() hook for props access\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>\n): void;\n\n// Implementation\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>\n): void {\n let normalizedTag = toKebab(tag);\n if (!normalizedTag.includes(\"-\")) {\n normalizedTag = `cer-${normalizedTag}`;\n }\n\n // Store lifecycle hooks from the render function\n let lifecycleHooks: {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (\n name: string,\n oldValue: string | null,\n newValue: string | null\n ) => void;\n onError?: (error: Error) => void;\n } = {};\n\n // Create component config\n const config: ComponentConfig<{}, {}, {}, {}> = {\n // Props are accessed via useProps() hook\n props: {},\n\n // Add lifecycle hooks from the stored functions\n onConnected: (_context) => {\n if (lifecycleHooks.onConnected) {\n lifecycleHooks.onConnected();\n }\n },\n\n onDisconnected: (_context) => {\n if (lifecycleHooks.onDisconnected) {\n lifecycleHooks.onDisconnected();\n }\n },\n\n onAttributeChanged: (name, oldValue, newValue, _context) => {\n if (lifecycleHooks.onAttributeChanged) {\n lifecycleHooks.onAttributeChanged(name, oldValue, newValue);\n }\n },\n\n onError: (error, _context) => {\n if (lifecycleHooks.onError && error) {\n lifecycleHooks.onError(error);\n }\n },\n\n render: (context) => {\n // Track dependencies for rendering\n // Use stable component ID from context if available, otherwise generate new one\n const componentId =\n (context as any)._componentId ||\n `${normalizedTag}-${Math.random().toString(36).substr(2, 9)}`;\n\n reactiveSystem.setCurrentComponent(componentId, () => {\n if (context.requestRender) {\n context.requestRender();\n }\n });\n\n try {\n // Set current component context for hooks\n setCurrentComponentContext(context);\n\n // Call render function with no arguments - use useProps() hook for props access\n // If renderFn throws synchronously (for example due to eager interpolation\n // inside templates), invoke any useOnError hook that the component may\n // have already registered during the render execution before rethrowing.\n let result: any;\n try {\n result = renderFn();\n } catch (err) {\n try {\n const hookCallbacks = (context as any)?._hookCallbacks;\n if (hookCallbacks && typeof hookCallbacks.onError === \"function\") {\n try {\n hookCallbacks.onError(err);\n } catch (e) {\n /* swallow */\n }\n }\n } catch (e) {\n /* best-effort */\n }\n throw err;\n }\n\n // Process hook callbacks that were set during render\n if ((context as any)._hookCallbacks) {\n const hookCallbacks = (context as any)._hookCallbacks;\n if (hookCallbacks.onConnected) {\n lifecycleHooks.onConnected = hookCallbacks.onConnected;\n }\n if (hookCallbacks.onDisconnected) {\n lifecycleHooks.onDisconnected = hookCallbacks.onDisconnected;\n }\n if (hookCallbacks.onAttributeChanged) {\n lifecycleHooks.onAttributeChanged =\n hookCallbacks.onAttributeChanged;\n }\n if (hookCallbacks.onError) {\n lifecycleHooks.onError = hookCallbacks.onError;\n }\n if (hookCallbacks.style) {\n // Store the style callback in the context for applyStyle to use\n (context as any)._styleCallback = hookCallbacks.style;\n }\n // If useProps() was called, update config.props with the defaults\n if (hookCallbacks.props) {\n const propsDefaults = hookCallbacks.props;\n config.props = Object.fromEntries(\n Object.entries(propsDefaults).map(([key, defaultValue]) => {\n const type =\n typeof defaultValue === \"boolean\"\n ? Boolean\n : typeof defaultValue === \"number\"\n ? Number\n : typeof defaultValue === \"string\"\n ? String\n : Function; // Use Function for complex types\n return [\n key,\n { type, default: defaultValue as string | number | boolean },\n ];\n })\n );\n // Update the registry so future instances and observedAttributes use the updated config\n registry.set(normalizedTag, config);\n }\n }\n\n return result;\n } finally {\n clearCurrentComponentContext();\n reactiveSystem.clearCurrentComponent();\n }\n },\n };\n\n // Store in registry\n registry.set(normalizedTag, config);\n\n // CRITICAL: Perform a \"discovery render\" to detect props from useProps()\n // This must happen BEFORE defining the custom element, so observedAttributes\n // includes all props declared via useProps()\n if (typeof window !== \"undefined\") {\n try {\n // Create a minimal mock context for discovery\n const discoveryContext: any = {\n _hookCallbacks: {},\n requestRender: () => {},\n };\n setCurrentComponentContext(discoveryContext);\n try {\n // Execute once to trigger useProps() calls. If this throws we want to\n // surface the error to any useOnError hook that the component may have\n // registered during discovery and emit DEV diagnostics so authors see\n // what's going wrong (best-effort).\n renderFn();\n } catch (err) {\n try {\n const hookCallbacks = (discoveryContext as any)?._hookCallbacks;\n if (hookCallbacks && typeof hookCallbacks.onError === \"function\") {\n try {\n hookCallbacks.onError(err);\n } catch (e) {\n /* swallow */\n }\n }\n // DEV diagnostics for discovery-time failures\n devError(\n `Error during component discovery render <${normalizedTag}>:`,\n err\n );\n devWarn(\n \"Error occurred during initial component discovery render. Consider guarding expensive expressions or using lazy factories for directives like when().\"\n );\n } catch (e) {\n /* best-effort */\n }\n clearCurrentComponentContext();\n throw err;\n }\n clearCurrentComponentContext();\n\n // If useProps() was called during discovery, update config.props\n if (discoveryContext._hookCallbacks?.props) {\n const propsDefaults = discoveryContext._hookCallbacks.props;\n config.props = Object.fromEntries(\n Object.entries(propsDefaults).map(([key, defaultValue]) => {\n const type =\n typeof defaultValue === \"boolean\"\n ? Boolean\n : typeof defaultValue === \"number\"\n ? Number\n : typeof defaultValue === \"string\"\n ? String\n : Function;\n return [\n key,\n { type, default: defaultValue as string | number | boolean },\n ];\n })\n );\n // Update registry with discovered props\n registry.set(normalizedTag, config);\n }\n } catch (e) {\n // Discovery render failed - this is OK, props will be discovered on first real render\n }\n\n if (!customElements.get(normalizedTag)) {\n customElements.define(\n normalizedTag,\n createElementClass(normalizedTag, config) as CustomElementConstructor\n );\n }\n }\n}\n","import type { VNode } from \"./types\";\nimport { contextStack } from \"./render\";\nimport {\n toKebab,\n toCamel,\n getNestedValue,\n setNestedValue,\n safe,\n decodeEntities,\n isUnsafeHTML,\n safeSerializeAttr,\n isClassLikeAttr,\n} from \"./helpers\";\nimport { isReactiveState } from \"./reactive\";\nimport { devWarn } from \"./logger\";\n\n// Strict LRU cache helper for fully static templates (no interpolations, no context)\nclass LRUCache<K, V> {\n private map = new Map<K, V>();\n private maxSize: number;\n constructor(maxSize: number) {\n this.maxSize = maxSize;\n }\n get(key: K): V | undefined {\n const v = this.map.get(key);\n if (v === undefined) return undefined;\n // move to end (LRU ordering)\n this.map.delete(key);\n this.map.set(key, v);\n return v;\n }\n set(key: K, value: V) {\n // Delete if exists to maintain insertion order\n this.map.delete(key);\n this.map.set(key, value);\n if (this.map.size > this.maxSize) {\n // remove oldest (first key)\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n }\n has(key: K): boolean {\n return this.map.has(key);\n }\n clear() {\n this.map.clear();\n }\n}\n\nconst TEMPLATE_COMPILE_CACHE = new LRUCache<string, VNode | VNode[]>(500);\n\n/**\n * Validates event handlers to prevent common mistakes that lead to infinite loops\n */\nfunction validateEventHandler(value: any, eventName: string): void {\n // Check for null/undefined handlers\n if (value === null || value === undefined) {\n devWarn(\n `⚠️ Event handler for '@${eventName}' is ${value}. ` +\n `This will prevent the event from working. ` +\n `Use a function reference instead: @${eventName}=\"\\${functionName}\"`\n );\n return;\n }\n\n // Check for immediate function invocation (most common mistake)\n if (typeof value !== \"function\") {\n devWarn(\n `🚨 Potential infinite loop detected! Event handler for '@${eventName}' appears to be ` +\n `the result of a function call (${typeof value}) instead of a function reference. ` +\n `Change @${eventName}=\"\\${functionName()}\" to @${eventName}=\"\\${functionName}\" ` +\n `to pass the function reference instead of calling it immediately.`\n );\n }\n\n // Additional check for common return values of mistaken function calls\n if (value === undefined && typeof value !== \"function\") {\n devWarn(\n `💡 Tip: If your event handler function returns undefined, make sure you're passing ` +\n `the function reference, not calling it. Use @${eventName}=\"\\${fn}\" not @${eventName}=\"\\${fn()}\"`\n );\n }\n}\n\nexport function h(\n tag: string,\n props: Record<string, any> = {},\n children?: VNode[] | string,\n key?: string | number\n): VNode {\n // Do NOT invent keys here; use only what the caller passes (or props.key).\n const finalKey = key ?? props.key;\n return { tag, key: finalKey, props, children };\n}\n\nexport function isAnchorBlock(v: any): boolean {\n return (\n !!v &&\n typeof v === \"object\" &&\n ((v as any).type === \"AnchorBlock\" || (v as any).tag === \"#anchor\")\n );\n}\n\nexport function isElementVNode(v: any): v is VNode {\n return (\n typeof v === \"object\" && v !== null && \"tag\" in v && !isAnchorBlock(v) // exclude anchor blocks from being treated as normal elements\n );\n}\n\nexport function ensureKey(v: VNode, k: string): VNode {\n return v.key != null ? v : { ...v, key: k };\n}\n\nexport interface ParsePropsResult {\n props: Record<string, any>;\n attrs: Record<string, any>;\n directives: Record<string, { value: any; modifiers: string[]; arg?: string }>;\n bound: string[];\n}\n\nexport function parseProps(\n str: string,\n values: unknown[] = [],\n context: Record<string, any> = {}\n): ParsePropsResult {\n const props: Record<string, any> = {};\n const attrs: Record<string, any> = {};\n const directives: Record<\n string,\n { value: any; modifiers: string[]; arg?: string }\n > = {};\n const bound: string[] = [];\n\n // Match attributes with optional prefix and support for single/double quotes\n // Also matches standalone boolean attributes (without =value)\n const attrRegex =\n /([:@#]?)([a-zA-Z0-9-:\\.]+)(?:=(\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(\\\\.[^'\\\\]*)*)'))?/g;\n\n let match: RegExpExecArray | null;\n\n while ((match = attrRegex.exec(str))) {\n const prefix = match[1];\n const rawName = match[2];\n const rawVal = (match[4] || match[6]) ?? \"\";\n\n // If no value was provided (standalone attribute), treat as boolean true\n const isStandalone = match[3] === undefined && match[6] === undefined;\n\n // Interpolation detection\n const interpMatch = rawVal.match(/^{{(\\d+)}}$/);\n let value: any = isStandalone\n ? true // Standalone attributes are boolean true\n : interpMatch\n ? values[Number(interpMatch[1])] ?? null\n : rawVal;\n\n // Type inference for booleans, null, numbers\n if (!interpMatch) {\n if (value === \"true\") value = true;\n else if (value === \"false\") value = false;\n else if (value === \"null\") value = null;\n else if (!isNaN(Number(value))) value = Number(value);\n }\n\n // Known directive names\n const knownDirectives = [\n \"model\",\n \"bind\",\n \"show\",\n \"class\",\n \"style\",\n \"ref\",\n \"when\",\n ];\n if (prefix === \":\") {\n // Support :model:checked (directive with argument) and :class.foo (modifiers)\n const [nameAndModifiers, argPart] = rawName.split(\":\");\n const [maybeDirective, ...modifierParts] = nameAndModifiers.split(\".\");\n if (knownDirectives.includes(maybeDirective)) {\n const modifiers = [...modifierParts];\n // Allow multiple :model directives on the same tag by keying them with\n // their argument when present (e.g. 'model:test'). This preserves both\n // plain :model and :model:prop simultaneously.\n const directiveKey =\n maybeDirective === \"model\" && argPart\n ? `model:${argPart}`\n : maybeDirective;\n directives[directiveKey] = {\n value,\n modifiers,\n arg: argPart,\n };\n } else {\n // Special-case certain boolean-like attributes to promote them to\n // props so runtime property assignment and coercion behave correctly\n // for native elements (e.g. :disabled should affect el.disabled).\n if (rawName === \"disabled\") {\n // Be conservative: only promote disabled to props at compile-time\n // when the bound value is an explicit boolean-ish primitive\n // (boolean, empty-string presence, literal 'true'/'false', null, or number).\n // Otherwise leave it in attrs so the runtime can apply safer coercion.\n let propValue = value;\n if (propValue && isReactiveState(propValue))\n propValue = (propValue as any).value;\n const t = typeof propValue;\n const isBoolStr =\n t === \"string\" && (propValue === \"true\" || propValue === \"false\");\n const shouldPromote =\n propValue === \"\" ||\n t === \"boolean\" ||\n isBoolStr ||\n propValue == null ||\n t === \"number\";\n if (shouldPromote) {\n props[rawName] = propValue;\n } else {\n // Unwrap reactive state objects for bound attributes and keep in attrs\n let attrValue = value;\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as any).value; // This triggers dependency tracking\n }\n attrs[rawName] = attrValue;\n }\n bound.push(rawName);\n } else {\n // Unwrap reactive state objects for bound attributes\n let attrValue = value;\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as any).value; // This triggers dependency tracking\n }\n attrs[rawName] = attrValue;\n bound.push(rawName);\n }\n }\n } else if (prefix === \"@\") {\n // Parse event modifiers: @click.prevent.stop\n const [eventName, ...modifierParts] = rawName.split(\".\");\n const modifiers = modifierParts;\n\n // Validate event handler to prevent common mistakes\n validateEventHandler(value, eventName);\n\n // Create wrapped event handler that applies modifiers\n const originalHandler =\n typeof value === \"function\"\n ? value\n : typeof context[value] === \"function\"\n ? context[value]\n : undefined;\n\n if (originalHandler) {\n const wrappedHandler = (event: Event) => {\n // Apply event modifiers\n if (modifiers.includes(\"prevent\")) {\n event.preventDefault();\n }\n if (modifiers.includes(\"stop\")) {\n event.stopPropagation();\n }\n if (\n modifiers.includes(\"self\") &&\n event.target !== event.currentTarget\n ) {\n return;\n }\n\n // For .once modifier, we need to remove the listener after first call\n if (modifiers.includes(\"once\")) {\n (event.currentTarget as Element)?.removeEventListener(\n eventName,\n wrappedHandler\n );\n }\n\n // Call the original handler\n return originalHandler(event);\n };\n\n // Map @event to an `on<Event>` prop (DOM-first event listener convention)\n const onName =\n \"on\" + eventName.charAt(0).toUpperCase() + eventName.slice(1);\n props[onName] = wrappedHandler;\n }\n } else if (rawName === \"ref\") {\n props.ref = value;\n } else {\n attrs[rawName] = value;\n }\n }\n\n return { props, attrs, directives, bound };\n}\n\n/**\n * Transform VNodes with :when directive into anchor blocks for conditional rendering\n */\nfunction transformWhenDirective(vnode: VNode): VNode {\n // Skip if not an element VNode or is already an anchor block\n if (!isElementVNode(vnode) || isAnchorBlock(vnode)) {\n return vnode;\n }\n\n // Check if this VNode has a :when directive\n const directives = vnode.props?.directives;\n if (directives && directives.when) {\n const rawWhen = directives.when.value;\n // If the directive value is a ReactiveState, unwrap it so the condition\n // reflects the current boolean value (e.g. ref(false) -> false).\n const whenCondition = isReactiveState(rawWhen)\n ? (rawWhen as any).value\n : rawWhen;\n\n // Remove the :when directive from the VNode since we're handling it here\n const { when, ...remainingDirectives } = directives;\n const newProps = { ...vnode.props };\n if (Object.keys(remainingDirectives).length > 0) {\n newProps.directives = remainingDirectives;\n } else {\n delete newProps.directives;\n }\n\n // Create a new VNode without the :when directive\n const elementVNode: VNode = {\n ...vnode,\n props: newProps,\n };\n\n // Recursively transform children if they exist\n if (Array.isArray(elementVNode.children)) {\n elementVNode.children = elementVNode.children.map((child) =>\n typeof child === \"object\" && child !== null\n ? transformWhenDirective(child as VNode)\n : child\n );\n }\n\n // Wrap in an anchor block with the condition\n const anchorKey =\n vnode.key != null ? `when-${vnode.key}` : `when-${vnode.tag}`;\n return {\n tag: \"#anchor\",\n key: anchorKey,\n children: whenCondition ? [elementVNode] : [],\n };\n }\n\n // Recursively transform children if they exist\n if (Array.isArray(vnode.children)) {\n const transformedChildren = vnode.children.map((child) =>\n typeof child === \"object\" && child !== null\n ? transformWhenDirective(child as VNode)\n : child\n );\n return {\n ...vnode,\n children: transformedChildren,\n };\n }\n\n return vnode;\n}\n\n/**\n * Internal implementation allowing an optional compile context for :model.\n * Fixes:\n * - Recognize interpolation markers embedded in text (\"World{{1}}\") and replace them.\n * - Skip empty arrays from directives so markers don't leak as text.\n * - Pass AnchorBlocks through (and deep-normalize their children's keys) so the renderer can mount/patch them surgically.\n * - Do not rewrap interpolated VNodes (preserve their keys); only fill in missing keys.\n */\nexport function htmlImpl(\n strings: TemplateStringsArray,\n values: unknown[],\n context?: Record<string, any>\n): VNode | VNode[] {\n // Retrieve current context from stack (transparent injection)\n const injectedContext =\n contextStack.length > 0 ? contextStack[contextStack.length - 1] : undefined;\n\n // Use injected context if no explicit context provided\n const effectiveContext = context ?? injectedContext;\n\n // Conservative caching: only cache templates that have no interpolations\n // (values.length === 0) and no explicit context. This avoids incorrectly\n // reusing parsed structures that depend on runtime values or context.\n const canCache = !context && values.length === 0;\n const cacheKey = canCache ? strings.join(\"<!--TEMPLATE_DELIM-->\") : null;\n if (canCache && cacheKey) {\n const cached = TEMPLATE_COMPILE_CACHE.get(cacheKey);\n if (cached) return cached;\n }\n\n // Create a text VNode for interpolations (do NOT decode entity sequences)\n function textVNode(text: string, key: string): VNode {\n return h(\"#text\", {}, text, key);\n }\n\n // Create a text VNode for literal template text (decode HTML entities so\n // authors can write `&lt;` inside template bodies and get the literal\n // character in the DOM). This should NOT be used for interpolated values\n // where the runtime should preserve the original string provided by the\n // consumer.\n function decodedTextVNode(text: string, key: string): VNode {\n const decoded = typeof text === \"string\" ? decodeEntities(text) : text;\n return h(\"#text\", {}, decoded as any, key);\n }\n\n // Stitch template with interpolation markers\n let template = \"\";\n for (let i = 0; i < strings.length; i++) {\n template += strings[i];\n if (i < values.length) template += `{{${i}}}`;\n }\n\n // Matches: comments, tags (open/close/self), standalone interpolation markers, or any other text\n // How this works:\n // const tagRegex =\n // /<!--[\\s\\S]*?--> # HTML comments\n // |<\\/?([a-zA-Z0-9-]+) # tag name\n // ( # start attributes group\n // (?:\\s+ # whitespace before attribute\n // [^\\s=>/]+ # attribute name\n // (?:\\s*=\\s* # optional equals\n // (?:\n // \"(?:\\\\.|[^\"])*\" # double-quoted value\n // |'(?:\\\\.|[^'])*' # single-quoted value\n // |[^\\s>]+ # unquoted value\n // )\n // )?\n // )* # repeat for multiple attributes\n // )\\s*\\/?> # end of tag\n // |{{(\\d+)}} # placeholder\n // |([^<]+) # text node\n // /gmx;\n // We explicitly match attributes one by one, and if a value is quoted, we allow anything inside (including >).\n // Handles both ' and \" quotes.\n // Matches unquoted attributes like disabled or checked.\n // Keeps {{(\\d+)}} and text node capture groups intact.\n // Added support for HTML comments which are ignored during parsing.\n const tagRegex =\n /<!--[\\s\\S]*?-->|<\\/?([a-zA-Z0-9-]+)((?:\\s+[^\\s=>/]+(?:\\s*=\\s*(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|[^\\s>]+))?)*)\\s*\\/?>|{{(\\d+)}}|([^<]+)/g;\n\n const stack: Array<{\n tag: string;\n props: Record<string, any>;\n children: VNode[];\n key: string | number | undefined;\n }> = [];\n let root: VNode | null = null;\n let match: RegExpExecArray | null;\n let currentChildren: VNode[] = [];\n let currentTag: string | null = null;\n let currentProps: Record<string, any> = {};\n let currentKey: string | number | undefined = undefined;\n let nodeIndex = 0;\n let fragmentChildren: VNode[] = []; // Track root-level nodes for fragments\n\n // Helper: merge object-like interpolation into currentProps\n function mergeIntoCurrentProps(maybe: any) {\n if (!maybe || typeof maybe !== \"object\") return;\n if (isAnchorBlock(maybe)) return; // do not merge AnchorBlocks\n if (maybe.props || maybe.attrs) {\n if (maybe.props) {\n // Ensure currentProps.props exists\n if (!currentProps.props) currentProps.props = {};\n Object.assign(currentProps.props, maybe.props);\n }\n if (maybe.attrs) {\n // Ensure currentProps.attrs exists\n if (!currentProps.attrs) currentProps.attrs = {};\n\n // Handle special merging for style and class attributes\n Object.keys(maybe.attrs).forEach((key) => {\n if (key === \"style\" && currentProps.attrs.style) {\n // Merge style attributes by concatenating with semicolon\n const existingStyle = currentProps.attrs.style.replace(\n /;?\\s*$/,\n \"\"\n );\n const newStyle = maybe.attrs.style.replace(/^;?\\s*/, \"\");\n currentProps.attrs.style = existingStyle + \"; \" + newStyle;\n } else if (key === \"class\" && currentProps.attrs.class) {\n // Merge class attributes by concatenating with space\n const existingClasses = currentProps.attrs.class\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n const newClasses = maybe.attrs.class\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n const allClasses = [\n ...new Set([...existingClasses, ...newClasses]),\n ];\n currentProps.attrs.class = allClasses.join(\" \");\n } else {\n // For other attributes, just assign (later values override)\n currentProps.attrs[key] = maybe.attrs[key];\n }\n });\n }\n } else {\n // If no props/attrs structure, merge directly into props\n if (!currentProps.props) currentProps.props = {};\n Object.assign(currentProps.props, maybe);\n }\n }\n\n // Helper: push an interpolated value into currentChildren/currentProps or fragments\n function pushInterpolation(val: any, baseKey: string) {\n const targetChildren = currentTag ? currentChildren : fragmentChildren;\n\n if (isAnchorBlock(val)) {\n const anchorKey = (val as VNode).key ?? baseKey;\n let anchorChildren = (val as any).children as VNode[] | undefined;\n targetChildren.push({\n ...(val as VNode),\n key: anchorKey,\n children: anchorChildren,\n });\n return;\n }\n\n if (isElementVNode(val)) {\n // Leave key undefined so assignKeysDeep can generate a stable one\n targetChildren.push(ensureKey(val, undefined as any));\n return;\n }\n\n if (Array.isArray(val)) {\n if (val.length === 0) return;\n for (let i = 0; i < val.length; i++) {\n const v = val[i];\n if (isAnchorBlock(v) || isElementVNode(v) || Array.isArray(v)) {\n // recurse or push without forcing a key\n pushInterpolation(v, `${baseKey}-${i}`);\n } else if (v !== null && typeof v === \"object\") {\n // If the object is an unsafe HTML marker, push a raw vnode\n if (isUnsafeHTML(v)) {\n targetChildren.push(\n h(\"#raw\", {}, (v as any).__rawHTML, `${baseKey}-${i}`)\n );\n } else {\n mergeIntoCurrentProps(v);\n }\n } else {\n targetChildren.push(textVNode(String(v), `${baseKey}-${i}`));\n }\n }\n return;\n }\n\n if (val !== null && typeof val === \"object\") {\n if (isUnsafeHTML(val)) {\n const raw = (val as any).__rawHTML ?? \"\";\n targetChildren.push(h(\"#raw\", {}, raw, baseKey));\n return;\n }\n mergeIntoCurrentProps(val);\n return;\n }\n\n targetChildren.push(textVNode(String(val), baseKey));\n }\n\n const voidElements = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n ]);\n\n while ((match = tagRegex.exec(template))) {\n // Skip HTML comments (they are matched by the regex but ignored)\n if (match[0].startsWith(\"<!--\") && match[0].endsWith(\"-->\")) {\n continue;\n }\n\n if (match[1]) {\n // Tag token\n const tagName = match[1];\n const isClosing = match[0][1] === \"/\";\n const isSelfClosing =\n match[0][match[0].length - 2] === \"/\" || voidElements.has(tagName);\n\n const {\n props: rawProps,\n attrs: rawAttrs,\n directives,\n bound: boundList,\n } = parseProps(\n match[2] || \"\",\n values,\n effectiveContext\n ) as ParsePropsResult;\n\n // No runtime registration here; compiler will set `isCustomElement`\n // on vnodeProps where appropriate. Runtime will consult that flag or\n // the strict registry if consumers register tags at runtime.\n\n // Shape props into { props, attrs, directives } expected by VDOM\n const vnodeProps: {\n props: Record<string, unknown>;\n attrs: Record<string, unknown>;\n directives?: Record<string, { value: any; modifiers: string[] }>;\n isCustomElement?: boolean;\n } = { props: {}, attrs: {} };\n\n for (const k in rawProps) vnodeProps.props[k] = rawProps[k];\n for (const k in rawAttrs) vnodeProps.attrs[k] = rawAttrs[k];\n\n // If a `key` attribute was provided, surface it as a vnode prop so the\n // renderer/assignKeysDeep can use it as the vnode's key and avoid\n // unnecessary remounts when children order/state changes.\n if (\n vnodeProps.attrs &&\n Object.prototype.hasOwnProperty.call(vnodeProps.attrs, \"key\") &&\n !(\n vnodeProps.props &&\n Object.prototype.hasOwnProperty.call(vnodeProps.props, \"key\")\n )\n ) {\n safe(() => {\n vnodeProps.props.key = vnodeProps.attrs[\"key\"];\n });\n }\n\n // Ensure native form control properties are set as JS props when the\n // template used `:value` or `:checked` (the parser places plain\n // `:value` into attrs). Textareas and inputs show their content from\n // the element property (el.value / el.checked), not the HTML attribute.\n // Only promote when the attribute was a bound attribute (e.g. used\n // with `:value`), otherwise leave static attributes in attrs for\n // tests and expected behavior.\n try {\n // Conservative promotion map: promote attributes that must be properties\n // for correct native behavior (value/checked/etc.). We intentionally\n // avoid promoting `disabled` at compile-time because early promotion\n // can cause accidental enabling/disabling when bound expressions or\n // wrapper proxies evaluate to truthy values. The runtime already\n // performs defensive coercion for boolean-like values; prefer that.\n const nativePromoteMap: Record<string, string[]> = {\n input: [\n \"value\",\n \"checked\",\n \"readonly\",\n \"required\",\n \"placeholder\",\n \"maxlength\",\n \"minlength\",\n ],\n textarea: [\n \"value\",\n \"readonly\",\n \"required\",\n \"placeholder\",\n \"maxlength\",\n \"minlength\",\n ],\n select: [\"value\", \"required\", \"multiple\"],\n option: [\"selected\", \"value\"],\n video: [\"muted\", \"autoplay\", \"controls\", \"loop\", \"playsinline\"],\n audio: [\"muted\", \"autoplay\", \"controls\", \"loop\"],\n img: [\"src\", \"alt\", \"width\", \"height\"],\n button: [\"type\", \"name\", \"value\", \"autofocus\", \"form\"],\n };\n\n const lname = tagName.toLowerCase();\n const promotable = nativePromoteMap[lname] ?? [];\n\n if (vnodeProps.attrs) {\n for (const propName of promotable) {\n if (\n boundList &&\n boundList.includes(propName) &&\n propName in vnodeProps.attrs &&\n !(vnodeProps.props && propName in vnodeProps.props)\n ) {\n let attrValue = vnodeProps.attrs[propName];\n // Unwrap reactive state objects during promotion\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as any).value; // This triggers dependency tracking\n // Promote the unwrapped primitive value\n vnodeProps.props[propName] = attrValue;\n delete vnodeProps.attrs[propName];\n } else {\n // Only promote primitive values to native element properties.\n // For most attributes we accept string/number/boolean/empty-string\n // but for boolean-like attributes such as `disabled` be more\n // conservative: only promote when the value is a real boolean,\n // an explicit empty-string (attribute presence), or the\n // literal strings 'true'/'false'. This avoids promoting other\n // non-boolean strings which could be misinterpreted as\n // truthy and accidentally enable native controls.\n const t = typeof attrValue;\n if (propName === \"disabled\") {\n const isBoolStr =\n t === \"string\" &&\n (attrValue === \"true\" || attrValue === \"false\");\n const shouldPromote =\n attrValue === \"\" ||\n t === \"boolean\" ||\n isBoolStr ||\n attrValue == null ||\n t === \"number\";\n if (shouldPromote) {\n vnodeProps.props[propName] = attrValue;\n // DEV INSTRUMENTATION: record compiler-time promotions of disabled\n // (dev instrumentation removed)\n delete vnodeProps.attrs[propName];\n } else {\n // leave complex objects/unknown strings in attrs so the\n // runtime can make a safer decision when applying props\n }\n } else {\n if (\n attrValue === \"\" ||\n t === \"string\" ||\n t === \"number\" ||\n t === \"boolean\" ||\n attrValue == null\n ) {\n vnodeProps.props[propName] = attrValue;\n delete vnodeProps.attrs[propName];\n } else {\n // leave complex objects in attrs so the runtime can decide how\n // to apply them (for example, :bind object form or custom handling)\n }\n }\n }\n }\n }\n }\n // If this looks like a custom element (hyphenated tag), promote all bound attrs to props\n const isCustom =\n tagName.includes(\"-\") ||\n Boolean((effectiveContext as any)?.__customElements?.has?.(tagName));\n if (isCustom) {\n // Always mark custom elements, regardless of bound attributes\n vnodeProps.isCustomElement = true;\n\n if (boundList && vnodeProps.attrs) {\n // Preserve attributes that may be used for stable key generation\n const keyAttrs = new Set([\"id\", \"name\", \"data-key\", \"key\"]);\n for (const b of boundList) {\n if (\n b in vnodeProps.attrs &&\n !(vnodeProps.props && b in vnodeProps.props)\n ) {\n // Convert kebab-case to camelCase for JS property names on custom elements\n const camel = b.includes(\"-\") ? toCamel(b) : b;\n let attrValue = vnodeProps.attrs[b];\n // Preserve ReactiveState instances for custom elements so the\n // runtime can assign the live ReactiveState to the element\n // property (children using useProps will read .value). Do not\n // unwrap here; let the renderer/runtime decide how to apply.\n vnodeProps.props[camel] = attrValue;\n // Preserve potential key attributes in attrs to avoid unstable keys\n // For custom elements, preserve host-visible class-like attributes\n // so that compile-time HTML serialization (shadowRoot.innerHTML)\n // contains utility-class tokens for the JIT extractor. We treat\n // the following as class-like and attempt to keep them in attrs:\n // - `class`\n // - any camelCase that ends with `Class` (e.g. activeClass)\n // - any kebab-case that ends with `-class` (e.g. active-class)\n const preserveInAttrs = keyAttrs.has(b) || isClassLikeAttr(b);\n if (preserveInAttrs) {\n try {\n const serialized = safeSerializeAttr(vnodeProps.attrs[b]);\n if (serialized === null) delete vnodeProps.attrs[b];\n else vnodeProps.attrs[b] = serialized as any;\n } catch (e) {\n delete vnodeProps.attrs[b];\n }\n } else {\n delete vnodeProps.attrs[b];\n }\n }\n }\n }\n }\n } catch (e) {\n // Best-effort; ignore failures to keep runtime robust.\n }\n\n // Compiler-side canonical transform: convert :model and :model:prop on\n // custom elements into explicit prop + event handler so runtime hosts\n // that don't process directives can still work. Support multiple\n // :model variants on the same tag by iterating directive keys.\n if (\n directives &&\n Object.keys(directives).some(\n (k) => k === \"model\" || k.startsWith(\"model:\")\n )\n ) {\n try {\n const GLOBAL_REG_KEY = Symbol.for(\"cer.registry\");\n const globalRegistry = (globalThis as any)[GLOBAL_REG_KEY] as\n | Set<string>\n | Map<string, any>\n | undefined;\n const isInGlobalRegistry = Boolean(\n globalRegistry &&\n typeof globalRegistry.has === \"function\" &&\n globalRegistry.has(tagName)\n );\n\n const isInContext = Boolean(\n effectiveContext &&\n (((effectiveContext as any).__customElements instanceof Set &&\n (effectiveContext as any).__customElements.has(tagName)) ||\n (Array.isArray((effectiveContext as any).__isCustomElements) &&\n (effectiveContext as any).__isCustomElements.includes(\n tagName\n )))\n );\n\n const isHyphenated = tagName.includes(\"-\");\n\n const isCustomFromContext = Boolean(\n isHyphenated || isInContext || isInGlobalRegistry\n );\n\n if (isCustomFromContext) {\n for (const dk of Object.keys(directives)) {\n if (dk !== \"model\" && !dk.startsWith(\"model:\")) continue;\n const model = directives[dk] as {\n value: any;\n modifiers: string[];\n arg?: string;\n };\n const arg =\n model.arg ??\n (dk.includes(\":\") ? dk.split(\":\", 2)[1] : undefined);\n const modelVal = model.value;\n\n const argToUse = arg ?? \"modelValue\";\n\n const getNested = getNestedValue;\n const setNested = setNestedValue;\n\n const actualState = effectiveContext\n ? (effectiveContext as any)._state || effectiveContext\n : undefined;\n\n let initial: any = undefined;\n if (typeof modelVal === \"string\" && effectiveContext) {\n initial = getNested(actualState, modelVal);\n } else {\n initial = modelVal;\n // Unwrap reactive state objects\n // Keep ReactiveState objects intact for runtime so children\n // receive the ReactiveState instance instead of an unwrapped\n // plain object. The runtime knows how to handle ReactiveState\n // when applying props/attrs.\n }\n\n vnodeProps.props[argToUse] = initial;\n\n try {\n const attrName = toKebab(argToUse);\n if (!vnodeProps.attrs) vnodeProps.attrs = {} as any;\n // Only set attributes for primitive values; skip objects/refs\n if (\n initial !== undefined &&\n initial !== null &&\n (typeof initial === \"string\" ||\n typeof initial === \"number\" ||\n typeof initial === \"boolean\")\n ) {\n vnodeProps.attrs[attrName] = initial;\n }\n } catch (e) {\n /* best-effort */\n }\n\n vnodeProps.isCustomElement = true;\n\n const eventName = `update:${toKebab(argToUse)}`;\n // Convert kebab-case event name to camelCase handler key\n const camelEventName = eventName.replace(\n /-([a-z])/g,\n (_, letter) => letter.toUpperCase()\n );\n const handlerKey =\n \"on\" +\n camelEventName.charAt(0).toUpperCase() +\n camelEventName.slice(1);\n\n vnodeProps.props[handlerKey] = function (\n ev: Event & { detail?: any }\n ) {\n const newVal =\n (ev as any).detail !== undefined\n ? (ev as any).detail\n : ev.target\n ? (ev.target as any).value\n : undefined;\n if (!actualState) return;\n\n // Handle reactive state objects (functional API)\n if (modelVal && isReactiveState(modelVal)) {\n // Compiled handler: update reactive modelVal when event received\n const current = modelVal.value;\n const changed =\n Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !==\n JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n modelVal.value = newVal;\n if ((effectiveContext as any)?.requestRender)\n (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender)\n (effectiveContext as any)._requestRender();\n }\n } else {\n // Legacy string-based state handling\n const current = getNested(\n actualState,\n typeof modelVal === \"string\" ? modelVal : String(modelVal)\n );\n const changed =\n Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !==\n JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n setNested(\n actualState,\n typeof modelVal === \"string\"\n ? modelVal\n : String(modelVal),\n newVal\n );\n if ((effectiveContext as any)?.requestRender)\n (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender)\n (effectiveContext as any)._requestRender();\n }\n }\n };\n\n delete directives[dk];\n }\n }\n } catch (e) {\n // ignore transform errors and fall back to runtime directive handling\n }\n }\n\n // Process built-in directives that should be converted to props/attrs\n // Only attach directives to VNode; normalization/merging is handled in vdom.ts\n if (Object.keys(directives).length > 0) {\n vnodeProps.directives = { ...directives };\n }\n\n if (isClosing) {\n const node = h(\n currentTag!,\n currentProps,\n currentChildren.length === 1 &&\n isElementVNode(currentChildren[0]) &&\n currentChildren[0].tag === \"#text\"\n ? typeof currentChildren[0].children === \"string\"\n ? currentChildren[0].children\n : \"\"\n : currentChildren.length\n ? currentChildren\n : undefined,\n currentKey\n );\n const prev = stack.pop();\n if (prev) {\n currentTag = prev.tag;\n currentProps = prev.props;\n currentKey = prev.key;\n currentChildren = prev.children;\n currentChildren.push(node);\n } else {\n // If there is no previous tag, this is a root-level node\n fragmentChildren.push(node);\n currentTag = null;\n currentProps = {};\n currentKey = undefined;\n currentChildren = [];\n }\n } else if (isSelfClosing) {\n const key = undefined;\n // Always push self-closing tags to fragmentChildren if not inside another tag\n if (currentTag) {\n currentChildren.push(h(tagName, vnodeProps, undefined, key));\n } else {\n fragmentChildren.push(h(tagName, vnodeProps, undefined, key));\n }\n } else {\n if (currentTag) {\n stack.push({\n tag: currentTag,\n props: currentProps,\n children: currentChildren,\n key: currentKey,\n });\n }\n currentTag = tagName;\n currentProps = vnodeProps;\n currentChildren = [];\n }\n } else if (typeof match[3] !== \"undefined\") {\n // Standalone interpolation marker {{N}}\n const idx = Number(match[3]);\n const val = values[idx];\n const baseKey = `interp-${idx}`;\n pushInterpolation(val, baseKey);\n } else if (match[4]) {\n // Plain text (may contain embedded interpolation markers like \"...{{N}}...\")\n const text = match[4];\n\n const targetChildren = currentTag ? currentChildren : fragmentChildren;\n\n // Split text by embedded markers and handle parts\n const parts = text.split(/({{\\d+}})/);\n for (const part of parts) {\n if (!part) continue;\n\n const interp = part.match(/^{{(\\d+)}}$/);\n if (interp) {\n const idx = Number(interp[1]);\n const val = values[idx];\n const baseKey = `interp-${idx}`;\n pushInterpolation(val, baseKey);\n } else {\n const key = `text-${nodeIndex++}`;\n // This branch is for literal template text (not interpolation markers)\n // so decode entity sequences here.\n targetChildren.push(decodedTextVNode(part, key));\n }\n }\n }\n }\n\n // Normalize output: prefer array for true multi-root, single node for single root\n if (root) {\n // If root is an anchor block or element, return as-is\n return root;\n }\n\n // Filter out empty text nodes and whitespace-only nodes\n const cleanedFragments = fragmentChildren.filter((child): child is VNode => {\n if (isElementVNode(child)) {\n if (child.tag === \"#text\") {\n return (\n typeof child.children === \"string\" && child.children.trim() !== \"\"\n );\n }\n return true;\n }\n // Always keep anchor blocks and non-element nodes\n return true;\n });\n\n // Transform nodes with :when directive into anchor blocks\n const transformedFragments = cleanedFragments.map((child) =>\n transformWhenDirective(child)\n );\n\n if (transformedFragments.length === 1) {\n // Single non-empty root node\n const out = transformedFragments[0];\n if (canCache && cacheKey) TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n return out;\n } else if (transformedFragments.length > 1) {\n // True multi-root: return array\n const out = transformedFragments;\n if (canCache && cacheKey) {\n TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n }\n return out;\n }\n\n // Fallback for empty content\n return h(\"div\", {}, \"\", \"fallback-root\");\n}\n\n/**\n * Clear the template compile cache (useful for tests)\n */\nexport function clearTemplateCompileCache(): void {\n TEMPLATE_COMPILE_CACHE.clear();\n}\n\n/**\n * Default export: plain html.\n */\nexport function html(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): VNode | VNode[] {\n // If last value is a context object, use it\n const last = values[values.length - 1];\n const context =\n typeof last === \"object\" && last && !Array.isArray(last)\n ? (last as Record<string, any>)\n : undefined;\n\n return htmlImpl(strings, values, context);\n}\n","// Enhanced collection directives for better developer experience\n\nimport type { VNode } from \"./runtime/types\";\nimport { when, anchorBlock } from \"./directives\";\n\n/**\n * Conditional rendering with negated condition (opposite of when)\n * @param cond - Boolean condition to negate\n * @param children - Content to render when condition is false\n */\nexport function unless(cond: boolean, children: VNode | VNode[]): VNode {\n return when(!cond, children);\n}\n\n/**\n * Render content only if array/collection is empty\n * @param collection - Array or collection to check\n * @param children - Content to render when empty\n */\nexport function whenEmpty(collection: any[] | null | undefined, children: VNode | VNode[]): VNode {\n const isEmpty = !collection || collection.length === 0;\n return when(isEmpty, children);\n}\n\n/**\n * Render content only if array/collection has items\n * @param collection - Array or collection to check\n * @param children - Content to render when not empty\n */\nexport function whenNotEmpty(collection: any[] | null | undefined, children: VNode | VNode[]): VNode {\n const hasItems = Boolean(collection && collection.length > 0);\n return when(hasItems, children);\n}\n\n/**\n * Enhanced each with filtering capability\n * @param list - Array to iterate over\n * @param predicate - Filter function (optional)\n * @param render - Render function for each item\n */\nexport function eachWhere<T>(\n list: T[],\n predicate: (item: T, index: number) => boolean,\n render: (item: T, index: number, filteredIndex: number) => VNode | VNode[]\n): VNode[] {\n const filtered: Array<{ item: T; originalIndex: number }> = [];\n \n list.forEach((item, index) => {\n if (predicate(item, index)) {\n filtered.push({ item, originalIndex: index });\n }\n });\n\n return filtered.map(({ item, originalIndex }, filteredIndex) => {\n const itemKey = typeof item === \"object\" && item != null\n ? ((item as any)?.key ?? (item as any)?.id ?? `filtered-${originalIndex}`)\n : `filtered-${originalIndex}`;\n \n return anchorBlock(render(item, originalIndex, filteredIndex), `each-where-${itemKey}`);\n });\n}\n\n/**\n * Render different content based on array length\n * @param list - Array to check\n * @param cases - Object with length-based cases\n */\nexport function switchOnLength<T>(\n list: T[],\n cases: {\n empty?: VNode | VNode[];\n one?: (item: T) => VNode | VNode[];\n many?: (items: T[]) => VNode | VNode[];\n exactly?: { [count: number]: (items: T[]) => VNode | VNode[] };\n }\n): VNode {\n const length = list?.length ?? 0;\n \n if (length === 0 && cases.empty) {\n return anchorBlock(cases.empty, \"switch-length-empty\");\n }\n \n if (length === 1 && cases.one) {\n return anchorBlock(cases.one(list[0]), \"switch-length-one\");\n }\n \n if (cases.exactly?.[length]) {\n return anchorBlock(cases.exactly[length](list), `switch-length-${length}`);\n }\n \n if (length > 1 && cases.many) {\n return anchorBlock(cases.many(list), \"switch-length-many\");\n }\n \n return anchorBlock([], \"switch-length-fallback\");\n}\n\n/**\n * Group array items and render each group\n * @param list - Array to group\n * @param groupBy - Function to determine group key\n * @param renderGroup - Function to render each group\n */\nexport function eachGroup<T, K extends string | number>(\n list: T[],\n groupBy: (item: T) => K,\n renderGroup: (groupKey: K, items: T[], groupIndex: number) => VNode | VNode[]\n): VNode[] {\n const groups = new Map<K, T[]>();\n \n list.forEach(item => {\n const key = groupBy(item);\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(item);\n });\n \n return Array.from(groups.entries()).map(([groupKey, items], groupIndex) => {\n return anchorBlock(\n renderGroup(groupKey, items, groupIndex), \n `each-group-${groupKey}`\n );\n });\n}\n\n/**\n * Render with pagination/chunking\n * @param list - Array to chunk\n * @param pageSize - Items per page/chunk\n * @param currentPage - Current page (0-based)\n * @param render - Render function for visible items\n */\nexport function eachPage<T>(\n list: T[],\n pageSize: number,\n currentPage: number,\n render: (item: T, index: number, pageIndex: number) => VNode | VNode[]\n): VNode[] {\n const startIndex = currentPage * pageSize;\n const endIndex = Math.min(startIndex + pageSize, list.length);\n const pageItems = list.slice(startIndex, endIndex);\n \n return pageItems.map((item, pageIndex) => {\n const globalIndex = startIndex + pageIndex;\n const itemKey = typeof item === \"object\" && item != null\n ? ((item as any)?.key ?? (item as any)?.id ?? `page-${globalIndex}`)\n : `page-${globalIndex}`;\n \n return anchorBlock(render(item, globalIndex, pageIndex), `each-page-${itemKey}`);\n });\n}\n\n/* --- Async & Loading State Directives --- */\n\n/**\n * Render content based on Promise state\n * @param promiseState - Object with loading, data, error states\n * @param cases - Render functions for each state\n */\nexport function switchOnPromise<T, E = Error>(\n promiseState: {\n loading?: boolean;\n data?: T;\n error?: E;\n },\n cases: {\n loading?: VNode | VNode[];\n success?: (data: T) => VNode | VNode[];\n error?: (error: E) => VNode | VNode[];\n idle?: VNode | VNode[];\n }\n): VNode {\n if (promiseState.loading && cases.loading) {\n return anchorBlock(cases.loading, \"promise-loading\");\n }\n \n if (promiseState.error && cases.error) {\n return anchorBlock(cases.error(promiseState.error), \"promise-error\");\n }\n \n if (promiseState.data !== undefined && cases.success) {\n return anchorBlock(cases.success(promiseState.data), \"promise-success\");\n }\n \n if (cases.idle) {\n return anchorBlock(cases.idle, \"promise-idle\");\n }\n \n return anchorBlock([], \"promise-fallback\");\n}\n\n/* --- Utility Directives --- */\n\n/**\n * Render content based on screen size/media query\n * @param mediaQuery - CSS media query string\n * @param children - Content to render when media query matches\n */\nexport function whenMedia(mediaQuery: string, children: VNode | VNode[]): VNode {\n const matches = typeof window !== 'undefined' && window.matchMedia?.(mediaQuery)?.matches;\n return when(Boolean(matches), children);\n}\n\n/* --- Responsive & Media Query Directives (aligned with style.ts) --- */\n\n/**\n * Media variants matching those in style.ts\n */\nexport const mediaVariants = {\n // Responsive breakpoints (matching style.ts)\n sm: \"(min-width:640px)\",\n md: \"(min-width:768px)\", \n lg: \"(min-width:1024px)\",\n xl: \"(min-width:1280px)\",\n \"2xl\": \"(min-width:1536px)\",\n \n // Dark mode (matching style.ts)\n dark: \"(prefers-color-scheme: dark)\",\n} as const;\n\n/**\n * Responsive order matching style.ts\n */\nexport const responsiveOrder = [\"sm\", \"md\", \"lg\", \"xl\", \"2xl\"] as const;\n\n/**\n * Individual responsive directives matching the style.ts breakpoint system\n */\nexport const responsive = {\n // Breakpoint-based rendering (matching style.ts exactly)\n sm: (children: VNode | VNode[]) => whenMedia(mediaVariants.sm, children),\n md: (children: VNode | VNode[]) => whenMedia(mediaVariants.md, children),\n lg: (children: VNode | VNode[]) => whenMedia(mediaVariants.lg, children),\n xl: (children: VNode | VNode[]) => whenMedia(mediaVariants.xl, children),\n \"2xl\": (children: VNode | VNode[]) => whenMedia(mediaVariants[\"2xl\"], children),\n\n // Dark mode (matching style.ts)\n dark: (children: VNode | VNode[]) => whenMedia(mediaVariants.dark, children),\n light: (children: VNode | VNode[]) => whenMedia('(prefers-color-scheme: light)', children),\n\n // Accessibility and interaction preferences\n touch: (children: VNode | VNode[]) => whenMedia('(hover: none) and (pointer: coarse)', children),\n mouse: (children: VNode | VNode[]) => whenMedia('(hover: hover) and (pointer: fine)', children),\n reducedMotion: (children: VNode | VNode[]) => whenMedia('(prefers-reduced-motion: reduce)', children),\n highContrast: (children: VNode | VNode[]) => whenMedia('(prefers-contrast: high)', children),\n\n // Orientation\n portrait: (children: VNode | VNode[]) => whenMedia('(orientation: portrait)', children),\n landscape: (children: VNode | VNode[]) => whenMedia('(orientation: landscape)', children),\n} as const;\n\n/**\n * Advanced responsive directive that matches the style.ts multi-variant processing\n * Allows chaining responsive and dark mode conditions like in CSS classes\n * @param variants - Array of variant keys (e.g., ['dark', 'lg'])\n * @param children - Content to render when all variants match\n */\nexport function whenVariants(\n variants: Array<keyof typeof mediaVariants | 'light'>,\n children: VNode | VNode[]\n): VNode {\n const conditions: string[] = [];\n \n // Process dark/light mode\n if (variants.includes('dark')) {\n conditions.push(mediaVariants.dark);\n } else if (variants.includes('light')) {\n conditions.push('(prefers-color-scheme: light)');\n }\n \n // Process responsive variants (take the last one, matching style.ts behavior)\n const responsiveVariants = variants.filter(v => \n responsiveOrder.includes(v as typeof responsiveOrder[number])\n );\n const lastResponsive = responsiveVariants[responsiveVariants.length - 1];\n if (lastResponsive && lastResponsive in mediaVariants) {\n conditions.push(mediaVariants[lastResponsive as keyof typeof mediaVariants]);\n }\n \n const mediaQuery = conditions.length > 0 ? conditions.join(' and ') : 'all';\n return whenMedia(mediaQuery, children);\n}\n\n/**\n * Responsive switch directive - render different content for different breakpoints\n * Mirrors the responsive behavior from the style system\n * @param content - Object with breakpoint keys and corresponding content\n */\nexport function responsiveSwitch(content: {\n base?: VNode | VNode[];\n sm?: VNode | VNode[]; \n md?: VNode | VNode[];\n lg?: VNode | VNode[];\n xl?: VNode | VNode[];\n \"2xl\"?: VNode | VNode[];\n}): VNode[] {\n const results: VNode[] = [];\n \n // Handle light mode variants\n if (content.base) {\n // Base content (no media query)\n results.push(anchorBlock(content.base, \"responsive-base\"));\n }\n \n // Add responsive variants in order\n responsiveOrder.forEach(breakpoint => {\n const breakpointContent = content[breakpoint];\n if (breakpointContent) {\n results.push(responsive[breakpoint](breakpointContent));\n }\n });\n\n return results;\n}\n\n/* --- Enhanced Match Directive --- */\n\n/**\n * Enhanced match directive with more fluent API\n * @param value - Value to match against\n */\nexport function switchOn<T>(value: T) {\n const branches: Array<{ condition: (val: T) => boolean; content: VNode | VNode[] }> = [];\n let otherwiseContent: VNode | VNode[] | null = null;\n\n return {\n case(matcher: T | ((val: T) => boolean), content: VNode | VNode[]) {\n const condition = typeof matcher === 'function' \n ? matcher as (val: T) => boolean\n : (val: T) => val === matcher;\n \n branches.push({ condition, content });\n return this;\n },\n \n when(predicate: (val: T) => boolean, content: VNode | VNode[]) {\n branches.push({ condition: predicate, content });\n return this;\n },\n \n otherwise(content: VNode | VNode[]) {\n otherwiseContent = content;\n return this;\n },\n \n done() {\n for (let i = 0; i < branches.length; i++) {\n const { condition, content } = branches[i];\n if (condition(value)) {\n return anchorBlock(content, `switch-case-${i}`);\n }\n }\n return anchorBlock(otherwiseContent || [], \"switch-otherwise\");\n }\n };\n}\n","\n/**\n * Event handler type for global event bus\n */\nexport type EventHandler<T = any> = (data: T) => void;\n\nimport { devError } from \"./runtime/logger\";\n\n/**\n * Event map type using Set for efficient handler management\n */\ntype EventMap = { [eventName: string]: Set<EventHandler> };\n\n/**\n * GlobalEventBus provides a singleton event bus for cross-component communication.\n * Uses Set for handler storage to optimize add/remove operations and prevent duplicates.\n */\nexport class GlobalEventBus extends EventTarget {\n private handlers: EventMap = {};\n private static instance: GlobalEventBus;\n private eventCounters: Map<string, { count: number; window: number }> = new Map();\n\n\n /**\n * Returns the singleton instance of GlobalEventBus\n */\n static getInstance(): GlobalEventBus {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n return GlobalEventBus.instance;\n }\n\n /**\n * Emit a global event with optional data. Includes event storm protection.\n * @param eventName - Name of the event\n * @param data - Optional event payload\n */\n emit<T = any>(eventName: string, data?: T): void {\n // Event storm protection\n const now = Date.now();\n const counter = this.eventCounters.get(eventName);\n \n if (!counter || now - counter.window > 1000) {\n // Reset counter every second\n this.eventCounters.set(eventName, { count: 1, window: now });\n } else {\n counter.count++;\n \n if (counter.count > 50) {\n // Throttle excessive events to avoid event storms (silent in runtime)\n if (counter.count > 100) {\n return;\n }\n }\n }\n\n // Use native CustomEvent for better browser integration\n this.dispatchEvent(new CustomEvent(eventName, { \n detail: data,\n bubbles: false, // Global events don't need to bubble\n cancelable: true \n }));\n\n // Also trigger registered handlers\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.forEach(handler => {\n try {\n handler(data);\n } catch (error) {\n devError(`Error in global event handler for \"${eventName}\":`, error);\n }\n });\n }\n }\n\n\n /**\n * Register a handler for a global event. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n on<T = any>(eventName: string, handler: EventHandler<T>): () => void {\n if (!this.handlers[eventName]) {\n this.handlers[eventName] = new Set();\n }\n this.handlers[eventName].add(handler);\n return () => this.off(eventName, handler);\n }\n\n\n /**\n * Remove a specific handler for a global event.\n * @param eventName - Name of the event\n * @param handler - Handler function to remove\n */\n off<T = any>(eventName: string, handler: EventHandler<T>): void {\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.delete(handler);\n }\n }\n\n\n /**\n * Remove all handlers for a specific event.\n * @param eventName - Name of the event\n */\n offAll(eventName: string): void {\n delete this.handlers[eventName];\n }\n\n\n /**\n * Listen for a native CustomEvent. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - CustomEvent handler\n * @param options - AddEventListener options\n */\n listen<T = any>(eventName: string, handler: (event: CustomEvent<T>) => void, options?: AddEventListenerOptions): () => void {\n this.addEventListener(eventName, handler as EventListener, options);\n return () => this.removeEventListener(eventName, handler as EventListener);\n }\n\n\n /**\n * Register a one-time event handler. Returns a promise that resolves with the event data.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n once<T = any>(eventName: string, handler: EventHandler<T>): Promise<T> {\n return new Promise((resolve) => {\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n handler(data);\n resolve(data);\n });\n });\n }\n\n\n /**\n * Get a list of all active event names with registered handlers.\n */\n getActiveEvents(): string[] {\n return Object.keys(this.handlers).filter(eventName => \n this.handlers[eventName] && this.handlers[eventName].size > 0\n );\n }\n\n\n /**\n * Clear all event handlers (useful for testing or cleanup).\n */\n clear(): void {\n this.handlers = {};\n // Note: This doesn't clear native event listeners, use removeAllListeners if needed\n }\n\n\n /**\n * Get the number of handlers registered for a specific event.\n * @param eventName - Name of the event\n */\n getHandlerCount(eventName: string): number {\n return this.handlers[eventName]?.size || 0;\n }\n\n\n /**\n * Get event statistics for debugging.\n */\n getEventStats(): Record<string, { count: number; handlersCount: number }> {\n const stats: Record<string, { count: number; handlersCount: number }> = {};\n for (const [eventName, counter] of this.eventCounters.entries()) {\n stats[eventName] = {\n count: counter.count,\n handlersCount: this.getHandlerCount(eventName)\n };\n }\n return stats;\n }\n\n\n /**\n * Reset event counters (useful for testing or after resolving issues).\n */\n resetEventCounters(): void {\n this.eventCounters.clear();\n }\n}\n\n/**\n * Singleton instance of the global event bus\n */\nexport const eventBus = GlobalEventBus.getInstance();\n\n/**\n * Emit a global event\n */\nexport const emit = <T = any>(eventName: string, data?: T) => eventBus.emit(eventName, data);\n\n/**\n * Register a handler for a global event\n */\nexport const on = <T = any>(eventName: string, handler: EventHandler<T>) => eventBus.on(eventName, handler);\n\n/**\n * Remove a handler for a global event\n */\nexport const off = <T = any>(eventName: string, handler: EventHandler<T>) => eventBus.off(eventName, handler);\n\n/**\n * Register a one-time handler for a global event\n */\nexport const once = <T = any>(eventName: string, handler: EventHandler<T>) => eventBus.once(eventName, handler);\n\n/**\n * Listen for a native CustomEvent\n */\nexport const listen = <T = any>(eventName: string, handler: (event: CustomEvent<T>) => void, options?: AddEventListenerOptions) => \n eventBus.listen(eventName, handler, options);\n","type Listener<T> = (state: T) => void;\n\nexport interface Store<T extends object> {\n /**\n * Subscribe to store updates.\n * Returns an unsubscribe function to remove the listener.\n */\n subscribe(listener: Listener<T>): () => void;\n getState(): T;\n setState(partial: Partial<T> | ((prev: T) => Partial<T>)): void;\n}\n\nexport function createStore<T extends object>(initial: T): Store<T> {\n let state = { ...initial } as T; // no Proxy needed if we update via setState\n const listeners: Listener<T>[] = [];\n\n function subscribe(listener: Listener<T>) {\n listeners.push(listener);\n listener(state); // initial push\n\n // Return unsubscribe function\n return () => {\n const idx = listeners.indexOf(listener);\n if (idx !== -1) listeners.splice(idx, 1);\n };\n }\n\n function getState(): T {\n return state;\n }\n\n function setState(partial: Partial<T> | ((prev: T) => Partial<T>)) {\n const next = typeof partial === \"function\" ? partial(state) : partial;\n\n state = { ...state, ...next };\n notify();\n }\n\n function notify() {\n listeners.forEach((fn) => fn(state));\n }\n\n return { subscribe, getState, setState };\n}\n","import { html } from \"./runtime/template-compiler\";\nimport { component } from \"./runtime/component\";\nimport {\n useProps,\n useOnConnected,\n useOnDisconnected,\n useStyle,\n} from \"./runtime/hooks\";\nimport { ref, computed } from \"./runtime/reactive\";\nimport { createStore, type Store } from \"./store\";\nimport { devError, devWarn } from \"./runtime/logger\";\nimport { match } from \"./directives\";\n\nexport type RouteComponent =\n | { new (...args: any[]): any } // class components\n | ((...args: any[]) => any); // functional components\n\nexport interface RouteState {\n path: string;\n params: Record<string, string>;\n query: Record<string, string>;\n}\n\nexport type GuardResult = boolean | string | Promise<boolean | string>;\n\nexport interface Route {\n path: string;\n\n /**\n * Statically available component (already imported)\n */\n component?: string | (() => any);\n\n /**\n * Lazy loader that resolves to something renderable\n */\n load?: () => Promise<{ default: string | HTMLElement | Function }>;\n\n /**\n * Runs before matching — return false to cancel,\n * or a string to redirect\n */\n beforeEnter?: (to: RouteState, from: RouteState) => GuardResult;\n\n /**\n * Runs right before navigation commits — can cancel or redirect\n */\n onEnter?: (to: RouteState, from: RouteState) => GuardResult;\n\n /**\n * Runs after navigation completes — cannot cancel\n */\n afterEnter?: (to: RouteState, from: RouteState) => void;\n}\n\nexport interface RouterLinkProps {\n to: string;\n tag: string;\n replace: boolean;\n exact: boolean;\n activeClass: string;\n exactActiveClass: string;\n ariaCurrentValue: string;\n disabled: boolean;\n external: boolean;\n linkClass?: string;\n linkStyle?: string;\n}\n\nexport interface RouterLinkComputed {\n current: RouteState;\n isExactActive: boolean;\n isActive: boolean;\n className: string;\n ariaCurrent: string;\n isButton: boolean;\n disabledAttr: string;\n externalAttr: string;\n}\n\nexport interface RouterConfig {\n routes: Route[];\n base?: string;\n initialUrl?: string; // For SSR: explicitly pass the URL\n}\n\nexport const parseQuery = (search: string): Record<string, string> => {\n if (!search) return {};\n if (typeof URLSearchParams === \"undefined\") return {};\n return Object.fromEntries(new URLSearchParams(search));\n};\n\nexport const matchRoute = (\n routes: Route[],\n path: string\n): { route: Route | null; params: Record<string, string> } => {\n for (const route of routes) {\n const paramNames: string[] = [];\n const regexPath = route.path.replace(/:[^/]+/g, (m) => {\n paramNames.push(m.slice(1));\n return \"([^/]+)\";\n });\n const regex = new RegExp(`^${regexPath}$`);\n const match = path.match(regex);\n if (match) {\n const params: Record<string, string> = {};\n paramNames.forEach((name, i) => {\n params[name] = match[i + 1];\n });\n return { route, params };\n }\n }\n return { route: null, params: {} };\n};\n\n/**\n * Find the first route that matches the given path.\n * Consolidates repeated inline checks like `routes.find(r => matchRoute([r], path).route !== null)`\n */\nfunction findMatchedRoute(routes: Route[], path: string): Route | null {\n for (const r of routes) {\n if (matchRoute([r], path).route !== null) return r;\n }\n return null;\n}\n\n// Async component loader cache\nconst componentCache: Record<string, any> = {};\n\n/**\n * Loads a route's component, supporting both static and async.\n * @param route Route object\n * @returns Promise resolving to the component\n */\nexport async function resolveRouteComponent(route: Route): Promise<any> {\n if (route.component) return route.component;\n if (route.load) {\n if (componentCache[route.path]) return componentCache[route.path];\n try {\n const mod = await route.load();\n componentCache[route.path] = mod.default;\n return mod.default;\n } catch (err) {\n throw new Error(`Failed to load component for route: ${route.path}`);\n }\n }\n throw new Error(`No component or loader defined for route: ${route.path}`);\n}\n\nexport function useRouter(config: RouterConfig) {\n const { routes, base = \"\", initialUrl } = config;\n\n let getLocation: () => { path: string; query: Record<string, string> };\n let initial: { path: string; query: Record<string, string> };\n let store: Store<RouteState>;\n let update: (replace?: boolean) => Promise<void>;\n let push: (path: string) => Promise<void>;\n let replaceFn: (path: string) => Promise<void>;\n let back: () => void;\n\n // Run matching route guards/hooks\n const runBeforeEnter = async (to: RouteState, from: RouteState) => {\n const matched = findMatchedRoute(routes, to.path);\n if (!matched || !matched.beforeEnter) return true;\n try {\n const result = await matched.beforeEnter(to, from);\n if (typeof result === \"string\") {\n // Redirect\n await navigate(result, true);\n return false;\n }\n return result !== false;\n } catch (err) {\n devError(\"beforeEnter error\", err);\n return false;\n }\n };\n\n const runOnEnter = async (to: RouteState, from: RouteState) => {\n const matched = findMatchedRoute(routes, to.path);\n if (!matched || !matched.onEnter) return true;\n try {\n const result = await matched.onEnter(to, from);\n if (typeof result === \"string\") {\n await navigate(result, true);\n return false;\n }\n return result !== false;\n } catch (err) {\n devError(\"onEnter error\", err);\n return false;\n }\n };\n\n const runAfterEnter = (to: RouteState, from: RouteState) => {\n const matched = findMatchedRoute(routes, to.path);\n if (!matched || !matched.afterEnter) return;\n try {\n matched.afterEnter(to, from);\n } catch (err) {\n devError(\"afterEnter error\", err);\n }\n };\n\n const navigate = async (path: string, replace = false) => {\n try {\n const loc = {\n path: path.replace(base, \"\") || \"/\",\n query: {},\n };\n const match = matchRoute(routes, loc.path);\n if (!match) throw new Error(`No route found for ${loc.path}`);\n\n const from = store.getState();\n const to: RouteState = {\n path: loc.path,\n params: match.params,\n query: loc.query,\n };\n\n // beforeEnter guard\n const allowedBefore = await runBeforeEnter(to, from);\n if (!allowedBefore) return;\n\n // onEnter guard (right before commit)\n const allowedOn = await runOnEnter(to, from);\n if (!allowedOn) return;\n\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n if (replace) {\n window.history.replaceState({}, \"\", base + path);\n } else {\n window.history.pushState({}, \"\", base + path);\n }\n }\n\n store.setState(to);\n\n // afterEnter hook (post commit)\n runAfterEnter(to, from);\n } catch (err) {\n devError(\"Navigation error:\", err);\n }\n };\n\n // If an explicit `initialUrl` is provided we treat this as SSR/static rendering\n // even if a `window` exists (useful for hydration tests). Browser mode only\n // applies when `initialUrl` is undefined.\n if (\n typeof window !== \"undefined\" &&\n typeof document !== \"undefined\" &&\n typeof initialUrl === \"undefined\"\n ) {\n // Browser mode\n getLocation = () => {\n const url = new URL(window.location.href);\n const path = url.pathname.replace(base, \"\") || \"/\";\n const query = parseQuery(url.search);\n return { path, query };\n };\n\n initial = getLocation();\n const match = matchRoute(routes, initial.path);\n store = createStore<RouteState>({\n path: initial.path,\n params: match.params,\n query: initial.query,\n });\n\n update = async (replace = false) => {\n const loc = getLocation();\n await navigate(loc.path, replace);\n };\n\n window.addEventListener(\"popstate\", () => update(true));\n\n push = (path: string) => navigate(path, false);\n replaceFn = (path: string) => navigate(path, true);\n back = () => window.history.back();\n } else {\n // SSR mode\n getLocation = () => {\n const url = new URL(initialUrl || \"/\", \"http://localhost\");\n const path = url.pathname.replace(base, \"\") || \"/\";\n const query = parseQuery(url.search);\n return { path, query };\n };\n\n initial = getLocation();\n const match = matchRoute(routes, initial.path);\n store = createStore<RouteState>({\n path: initial.path,\n params: match.params,\n query: initial.query,\n });\n\n update = async () => {\n const loc = getLocation();\n await navigateSSR(loc.path);\n };\n\n const navigateSSR = async (path: string) => {\n try {\n const loc = {\n path: path.replace(base, \"\") || \"/\",\n query: {},\n };\n const match = matchRoute(routes, loc.path);\n if (!match) throw new Error(`No route found for ${loc.path}`);\n\n const from = store.getState();\n const to: RouteState = {\n path: loc.path,\n params: match.params,\n query: loc.query,\n };\n\n // beforeEnter guard\n const matched = findMatchedRoute(routes, to.path);\n if (matched?.beforeEnter) {\n try {\n const result = await matched.beforeEnter(to, from);\n if (typeof result === \"string\") {\n // Redirect\n await navigateSSR(result);\n return;\n }\n if (result === false) return;\n } catch (err) {\n return;\n }\n }\n\n // onEnter guard\n if (matched?.onEnter) {\n try {\n const result = await matched.onEnter(to, from);\n if (typeof result === \"string\") {\n await navigateSSR(result);\n return;\n }\n if (result === false) return;\n } catch (err) {\n return;\n }\n }\n\n store.setState(to);\n\n // afterEnter hook\n if (matched?.afterEnter) {\n try {\n matched.afterEnter(to, from);\n } catch (err) {}\n }\n } catch (err) {}\n };\n\n push = async (path: string) => navigateSSR(path);\n replaceFn = async (path: string) => navigateSSR(path);\n back = () => {};\n }\n\n return {\n store,\n push,\n replace: replaceFn,\n back,\n subscribe: store.subscribe,\n matchRoute: (path: string) => matchRoute(routes, path),\n getCurrent: (): RouteState => store.getState(),\n resolveRouteComponent,\n };\n}\n\n// SSR/static site support: match route for a given path\nexport function matchRouteSSR(routes: Route[], path: string) {\n return matchRoute(routes, path);\n}\n\n// Module-level reference to the latest initialized router. Tests and\n// components may rely on re-initializing the router during their setup,\n// so exposing this lets components pick up the most recent instance.\nlet activeRouter: ReturnType<typeof useRouter> | null = null;\n\n/**\n * Singleton router instance for global access.\n *\n * Define here to prevent circular dependency\n * issue with component.\n */\n\nexport function initRouter(config: RouterConfig) {\n const router = useRouter(config);\n // Expose the most recently initialized router to components defined\n // earlier in the process (tests may call initRouter multiple times).\n // Components reference `activeRouter` so re-calling initRouter updates\n // the router instance they use.\n activeRouter = router;\n\n component(\"router-view\", () => {\n // Prefer the latest initialized router (tests may re-init). Fallback\n // to the router captured at init time.\n const r = activeRouter || router;\n // Reactive current route so the component re-renders when router updates\n if (!r) return html`<div>Router not initialized.</div>`;\n\n const current = ref(r.getCurrent());\n\n // We'll capture the unsubscribe function when the component connects\n // and register a disconnect cleanup during render-time (useOnDisconnected\n // must be called during the component render/execution).\n let unsubRouterView: (() => void) | undefined;\n\n useOnConnected(() => {\n try {\n if (r && typeof r.subscribe === \"function\") {\n unsubRouterView = r.subscribe((s) => {\n try {\n current.value = s;\n } catch (e) {\n devWarn(\"router-view subscription update failed\", e);\n }\n });\n }\n } catch (e) {\n devWarn(\"router-view subscribe failed\", e);\n }\n });\n\n useOnDisconnected(() => {\n if (typeof unsubRouterView === \"function\") {\n try {\n unsubRouterView();\n } catch (e) {\n devWarn(\"router-view unsubscribe failed\", e);\n }\n }\n });\n\n const match = r.matchRoute(current.value.path);\n if (!match || !match.route) return html`<div>Not found</div>`;\n\n // Resolve the component (supports cached async loaders)\n return r\n .resolveRouteComponent(match.route)\n .then((comp: any) => {\n // String tag (custom element) -> render as VNode\n if (typeof comp === \"string\") {\n return { tag: comp, props: {}, children: [] };\n }\n\n // Function component (sync or async) -> call and return its VNode(s)\n if (typeof comp === \"function\") {\n const out = comp();\n const resolved = out instanceof Promise ? out : Promise.resolve(out);\n return resolved.then((resolvedComp: any) => {\n if (typeof resolvedComp === \"string\")\n return { tag: resolvedComp, props: {}, children: [] };\n return resolvedComp as any;\n });\n }\n\n return html`<div>Invalid route component</div>`;\n })\n .catch(() => html`<div>Invalid route component</div>`);\n });\n\n component(\"router-link\", () => {\n // Declare props via useProps so observedAttributes are correct\n const props = useProps<Partial<RouterLinkProps>>({\n to: \"\",\n tag: \"a\",\n replace: false,\n exact: false,\n activeClass: \"active\",\n exactActiveClass: \"exact-active\",\n ariaCurrentValue: \"page\",\n disabled: false,\n external: false,\n linkClass: \"\",\n linkStyle: \"\",\n });\n\n // Prefer the latest initialized router (tests may re-init). Fallback\n // to the router captured at init time.\n const r = activeRouter || router;\n // Reactive current state so link updates when route changes\n const current = ref(r.getCurrent());\n // Capture unsubscribe for link subscriptions and register disconnect\n // cleanup during render time.\n let unsubRouterLink: (() => void) | undefined;\n\n useStyle(\n () => (`a,button{display:inline-block;}` + props.linkStyle) as string\n );\n\n useOnConnected(() => {\n try {\n if (r && typeof r.subscribe === \"function\") {\n unsubRouterLink = r.subscribe((s) => {\n try {\n current.value = s;\n } catch (e) {\n devWarn(\"router-link subscription update failed\", e);\n }\n });\n }\n } catch (e) {\n devWarn(\"router-link subscribe failed\", e);\n }\n });\n\n useOnDisconnected(() => {\n if (typeof unsubRouterLink === \"function\") {\n try {\n unsubRouterLink();\n } catch (e) {\n devWarn(\"router-link unsubscribe failed\", e);\n }\n }\n });\n\n const isExactActive = computed(\n () => current.value.path === (props.to as string)\n );\n const isActive = computed(() =>\n props.exact\n ? isExactActive.value\n : current.value && typeof current.value.path === \"string\"\n ? current.value.path.startsWith(props.to as string)\n : false\n );\n\n // Build user classes reactively from the `linkClass` prop.\n // We intentionally do NOT read the host `class` attribute to avoid\n // duplicate styling applied to both host and inner element.\n const userClasses = computed(() => {\n const raw = (props.linkClass as string) || \"\";\n const list = raw.split(/\\s+/).filter(Boolean);\n const map: Record<string, boolean> = {};\n for (const c of list) map[c] = true;\n return map;\n });\n\n const classObject = computed(() => ({\n ...userClasses.value,\n [(props.activeClass as string) || \"active\"]: isActive.value,\n [(props.exactActiveClass as string) || \"exact-active\"]:\n isExactActive.value,\n }));\n\n const isButton = computed(() => (props.tag as string) === \"button\");\n // Instead of pre-building attribute fragments as strings (which can\n // accidentally inject invalid attribute names into the template and\n // cause DOMExceptions), compute simple booleans/values and apply\n // attributes explicitly in the template below.\n const ariaCurrentValue = computed(() =>\n isExactActive.value ? (props.ariaCurrentValue as string) : \"\"\n );\n const isDisabled = computed(() => !!props.disabled);\n const isExternal = computed(\n () =>\n !!props.external &&\n ((props.tag as string) === \"a\" || !(props.tag as string))\n );\n\n const navigate = (e: MouseEvent) => {\n if (props.disabled) {\n e.preventDefault();\n return;\n }\n if (\n props.external &&\n ((props.tag as string) === \"a\" || !(props.tag as string))\n ) {\n return;\n }\n e.preventDefault();\n if (props.replace) {\n r.replace(props.to as string);\n } else {\n r.push(props.to as string);\n }\n };\n\n return html`\n ${match()\n .when(\n isButton.value,\n html`\n <button\n part=\"button\"\n :class=\"${classObject.value}\"\n aria-current=\"${ariaCurrentValue.value}\"\n disabled=\"${isDisabled.value ? \"\" : null}\"\n aria-disabled=\"${isDisabled.value ? \"true\" : null}\"\n tabindex=\"${isDisabled.value ? \"-1\" : null}\"\n @click=\"${navigate}\"\n >\n <slot></slot>\n </button>\n `\n )\n .otherwise(\n html`\n <a\n part=\"link\"\n href=\"${props.to}\"\n :class=\"${classObject.value}\"\n aria-current=\"${ariaCurrentValue.value}\"\n aria-disabled=\"${isDisabled.value ? \"true\" : null}\"\n tabindex=\"${isDisabled.value ? \"-1\" : null}\"\n target=\"${isExternal.value ? \"_blank\" : null}\"\n rel=\"${isExternal.value ? \"noopener noreferrer\" : null}\"\n @click=\"${navigate}\"\n ><slot></slot\n ></a>\n `\n )\n .done()}\n `;\n });\n\n return router;\n}\n"],"names":["isDev","maybeProcess","__vite_import_meta_env__","devError","message","args","devWarn","UpdateScheduler","update","componentId","key","updates","error","updateScheduler","scheduleDOMUpdate","proxiedObjects","ReactiveProxyCache","obj","reactiveState","isArray","cached","handler","proxy","ProxyOptimizer","target","prop","receiver","value","result","onUpdate","makeReactive","inner","reactiveContext","ReactiveSystem","renderFn","data","now","fn","wasDisabled","initialValue","ReactiveState","stateKey","state","deps","prefix","reactiveSystem","newValue","ref","isReactiveState","v","computed","computedState","watch","source","callback","options","oldValue","watcherId","updateWatcher","safe","KEBAB_CASE_CACHE","CAMEL_CASE_CACHE","HTML_ESCAPE_CACHE","MAX_CACHE_SIZE","_namedEntityMap","_namedEntityMapLoader","_usedEntityFallback","_warnedEntityFallback","_decodeEl","_isNode","toKebab","str","toCamel","_","letter","escapeHTML","c","decodeEntities","s","protectedStr","el","tinyMap","registered","namedMap","maybeRequire","candidates","p","m","loader","entity","num","mapped","loadEntityMap","pkgExport","mPkg","localCandidates","mLocal","unsafeHTML","html","isUnsafeHTML","getNestedValue","path","current","setNestedValue","keys","lastKey","unwrapIfPrimitive","maybe","safeSerializeAttr","val","t","isClassLikeAttr","name","initWatchers","context","watchers","watchConfig","config","currentValue","triggerWatchers","isEqual","a","b","i","keysA","keysB","watcher","watchPath","watcherConfig","parseProp","type","applyPropsFromDefinitions","element","propDefinitions","def","kebab","attr","propValue","applyProps","cfg","declared","existing","hostVal","ret","handleConnected","isMounted","setMounted","handleDisconnected","listeners","clearListeners","clearWatchers","setTemplateLoading","setTemplateError","unsub","handleAttributeChanged","SecureExpressionEvaluator","expression","evaluator","firstKey","pattern","trimmedExpr","propertyPath","objectContent","properties","content","parts","part","colonIndex","cleanKey","processedExpression","stringLiterals","ctxMatches","match","placeholderIndex","dottedRegex","dottedMatches","identRegex","seen","ident","repl","idx","expr","tokens","pos","peek","consume","expected","parseExpression","parseTernary","cond","parseLogicalOr","thenExpr","elseExpr","left","parseLogicalAnd","right","parseEquality","parseComparison","op","parseAdditive","parseMultiplicative","parseUnary","parsePrimary","arr","input","re","raw","EventManager","event","meta","list","cleanups","hasValueChanged","updateStateValue","isReactive","arg","updated","actualState","triggerStateUpdate","watchKey","emitUpdateEvents","propName","customEventNameKebab","customEventNameCamel","customEventKebab","customEventCamel","syncElementWithState","propToSet","attrName","serialized","getCurrentStateValue","unwrapped","splitClasses","classString","addClasses","classes","newClasses","cls","removeClasses","validClasses","stylesLoadedOnce","waitForStyles","_classesToCheck","maxAttempts","hasTransform","hasOpacity","resolve","getTransitionDuration","computedStyle","duration","delay","parseDuration","waitForTransition","expectedDuration","resolved","done","onTransitionEnd","performEnterTransition","transitionMeta","hooks","css","e","enterFromClasses","enterActiveClasses","enterToClasses","manualDone","promise","fromTransform","fromOpacity","transitionDuration","performLeaveTransition","leaveFromClasses","leaveActiveClasses","leaveToClasses","nodeKeyMap","elementTransitionMap","getNodeKey","node","wm","anyNode","setNodeKey","getElementTransition","anyEl","setElementTransition","isNativeControl","coerceBooleanForNative","cleanupRefs","refs","refKey","children","assignRef","vnode","reactiveRef","processModelDirective","modifiers","props","attrs","hasLazy","hasTrim","hasNumber","getCurrentValue","inputType","isNativeInput","trueValue","option","eventType","eventListener","isTestEnv","fresh","trueV","falseV","o","n","currentStateValue","oldListener","eventNameKebab","eventNameCamel","newVal","userKeys","k","nestedKey","nestedKebab","nestedCamel","host","eventNameFromKey","rest","processBindDirective","isWrapper","evaluated","evaluateExpression","processShowDirective","isVisible","currentStyle","newStyle","styleRules","rule","displayIndex","processClassDirective","classValue","className","condition","existingClasses","isBooleanishForProps","it","processStyleDirective","styleValue","styleString","property","kebabProperty","needsPx","cssValue","existingStyle","processRefDirective","resolvedValue","processDirectives","directives","vnodeAttrs","directiveName","directive","runtimeArg","candidate","isReactiveVal","w","assignKeysDeep","nodeOrNodes","baseKey","usedKeys","child","tagPart","idPart","uniqueKey","counter","patchProps","oldProps","newProps","newDirectives","processedDirectives","mergedProps","mergedAttrs","oldPropProps","newPropProps","elIsCustom","anyChange","oldVal","oldUnwrapped","newUnwrapped","ev","propVal","candidateKeys","nestedEvent","nestedHandler","nestedNew","listener","parentEl","oldAttrs","newAttrs","isSVG","camelKey","propCandidate","sourceVal","hasDisabledInProcessed","isBooleanish","finalDisabled","createElement","textNode","anchorVNode","start","end","frag","childNode","childVNode","hostClass","serializedHostClass","unwrappedVal","final","altEventType","camel","vnodeIsCustom","assignValue","vnodeWithProcessedProps","attrCandidate","patchChildren","parent","oldChildren","newChildren","oldNodeList","oldNodesCache","oldVNodes","transitionGroup","stripKeyPrefix","flattenedNew","flattenedOldVNodes","anchorChildren","anchorChild","actualKey","oldVNode","oldVNodeByKeyFlat","oldNodeByKeyFlat","nodeKey","usedFlat","positionsBefore","hadPreviousContent","rect","nodesToProcess","newVNode","patched","patch","keyStr","shouldAnimate","err","leaveTransitions","leavePromise","currentPosition","elementsToAnimate","isNew","oldPos","newPos","deltaX","deltaY","moveClasses","moveClassStr","durationMatch","easingMatch","easing","cleanup","oldVNodeByKey","oldNodeByKey","usedNodes","nextSibling","markRangeUsed","cur","patchChildrenBetween","transition","oldNodesInRange","oldVNodesInRange","oldVNodeByKeyRange","oldNodeByKeyRange","isInitialVisible","usedInRange","next","commonLength","aKey","startKey","endKey","oldTransition","isStateChange","dom","placeholder","newEl","vdomRenderer","root","vnodeOrArray","prevVNode","prevDom","newDom","nodesToRemove","renderToString","attrsString","strings","values","minifyCSS","baseResetSheet","getBaseResetSheet","baseReset","sanitizeCSS","fallbackHex","colors","shades","shade","hex","spacing","semanticSizes","spacingProps","generateUtilities","utils","d","size","lineHeight","borderWidths","px","radiusMap","rem","cursors","z","utilityMap","insertPseudoBeforeCombinator","sel","pseudo","depth","ch","selectorVariants","body","mediaVariants","containerVariants","responsiveOrder","containerOrder","parseSpacing","negative","lastDashIndex","valueStr","numerator","denominator","percentage","sign","parseSpaceUtility","direction","isHorizontal","hexToRgb","clean","bigint","colorRegex","propMap","parseColorClass","colorName","colorValue","parseOpacityModifier","slashIndex","base","opacityStr","opacity","parseColorWithOpacity","paletteRule","rgb","arbitraryRule","parseArbitrary","parseGradientColorStop","position","parseOpacity","bracketStart","propMappings","cssProp","parseArbitraryVariant","token","escapeClassName","extractClassesFromHTML","classAttrRegex","classList","jitCssCache","JIT_CSS_THROTTLE_MS","jitCSS","buckets","ruleCache","generateRuleCached","stripDark","cacheKey","generateRule","classify","variants","hasResponsive","hasContainer","hasDark","splitVariants","pseudoMap","basePart","important","checkPart","cleanBase","baseRule","baseIndex","escapedClass","SUBJECT","selector","structural","subjectPseudos","innerPseudos","wrapperVariant","variantSelector","subjectPseudoStr","innerPseudoStr","insertPseudosIntoPost","post","pseudos","depthSquare","depthParen","pre","subjectWithPseudos","postWithInner","responsiveTokens","containerTokens","lastResponsive","lastContainer","mediaQuery","containerQuery","containerKey","bucketNum","gradientStopRegex","generated","sortRulesByBreakpoint","rules","getResponsivePixels","responsiveSizes","getContainerPixels","containerSizes","unit","aRespPx","bRespPx","aContPx","bContPx","when","childrenOrFactory","anchorKey","anchorBlock","each","render","item","itemKey","branches","whenChain","payload","childArray","transitionPresets","Transition","preset","show","mode","appear","enterFrom","enterActive","enterTo","leaveFrom","leaveActive","leaveTo","onBeforeEnter","onEnter","onAfterEnter","onEnterCancelled","onBeforeLeave","onLeave","onAfterLeave","onLeaveCancelled","transitionClasses","transitionKey","transitionVNode","TransitionGroup","tag","moveClass","style","groupKey","flattenedChildren","keyedChild","createTransitionPreset","transitionStyleSheet","getTransitionStyleSheet","allClasses","fakeHtml","generatedCSS","initializeTransitionCSS","contextStack","renderComponent","shadowRoot","setHtmlString","setLoading","setError","applyStyle","outputOrPromise","output","renderOutput","requestRender","lastRenderTime","renderCount","setLastRenderTime","setRenderCount","renderTimeoutId","setRenderTimeoutId","timeoutId","htmlString","styleSheet","setStyleSheet","aggregatedHtml","allEls","childHtml","jitCss","userStyle","finalStyle","sheet","r","currentComponentContext","setCurrentComponentContext","clearCurrentComponentContext","useEmit","emitFn","eventName","detail","ensureHookCallbacks","useOnConnected","useOnDisconnected","useOnAttributeChanged","useOnError","useProps","defaults","ctx","declaredKeys","localValue","kebabKey","attrValue","defaultType","fromHost","_target","hostValue","isWrapperLike","useStyle","registry","GLOBAL_REG_KEY","g","createElementClass","defineNonEnum","eventOptions","altName","cfgToUse","internalValue","id","compId","safeProps","createReactive","self","fullPath","newPath","component","normalizedTag","lifecycleHooks","_context","hookCallbacks","propsDefaults","defaultValue","discoveryContext","LRUCache","maxSize","TEMPLATE_COMPILE_CACHE","validateEventHandler","h","finalKey","isAnchorBlock","isElementVNode","ensureKey","parseProps","bound","attrRegex","rawName","rawVal","isStandalone","interpMatch","knownDirectives","nameAndModifiers","argPart","maybeDirective","modifierParts","directiveKey","originalHandler","wrappedHandler","onName","transformWhenDirective","rawWhen","whenCondition","remainingDirectives","elementVNode","transformedChildren","htmlImpl","injectedContext","effectiveContext","canCache","textVNode","text","decodedTextVNode","decoded","template","tagRegex","stack","currentChildren","currentTag","currentProps","currentKey","nodeIndex","fragmentChildren","mergeIntoCurrentProps","pushInterpolation","targetChildren","voidElements","tagName","isClosing","isSelfClosing","rawProps","rawAttrs","boundList","vnodeProps","nativePromoteMap","lname","promotable","keyAttrs","globalRegistry","isInGlobalRegistry","isInContext","dk","model","modelVal","argToUse","getNested","setNested","initial","camelEventName","handlerKey","prev","interp","transformedFragments","out","last","unless","whenEmpty","collection","isEmpty","whenNotEmpty","hasItems","eachWhere","predicate","filtered","index","originalIndex","filteredIndex","switchOnLength","cases","length","eachGroup","groupBy","renderGroup","groups","items","groupIndex","eachPage","pageSize","currentPage","startIndex","endIndex","pageIndex","globalIndex","switchOnPromise","promiseState","whenMedia","matches","responsive","whenVariants","conditions","responsiveVariants","responsiveSwitch","results","breakpoint","breakpointContent","switchOn","otherwiseContent","matcher","GlobalEventBus","eventHandlers","unsubscribe","stats","eventBus","emit","on","off","once","listen","createStore","subscribe","getState","setState","partial","notify","parseQuery","search","matchRoute","routes","route","paramNames","regexPath","regex","params","findMatchedRoute","componentCache","resolveRouteComponent","mod","useRouter","initialUrl","getLocation","store","push","replaceFn","back","runBeforeEnter","to","from","matched","navigate","runOnEnter","runAfterEnter","replace","loc","url","query","navigateSSR","matchRouteSSR","activeRouter","initRouter","router","unsubRouterView","comp","resolvedComp","unsubRouterLink","isExactActive","isActive","userClasses","map","classObject","isButton","ariaCurrentValue","isDisabled","isExternal"],"mappings":"uMAMA,IAAIA,GAAQ,GACZ,GAAI,CAEF,MAAMC,EAAqB,WAAmB,QAC1CA,GAAgBA,EAAa,IAC/BD,GAAQC,EAAa,IAAI,WAAa,aAC7B,+LAAuB,KAAgBC,GAEhDF,GAAS,GAGTA,GAAQ,OAAO,OAAW,GAE9B,MAAY,CAEVA,GAAQ,EACV,CAKO,SAASG,EAASC,KAAoBC,EAAmB,CAC1DL,IACF,QAAQ,MAAMI,EAAS,GAAGC,CAAI,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BACN6oB,EAAY,KAAK;AAAA,8BACXE,EAAiB,KAAK;AAAA,+BACrBC,EAAW,MAAQ,OAAS,IAAI;AAAA,0BACrCA,EAAW,MAAQ,KAAO,IAAI;AAAA,wBAChCC,EAAW,MAAQ,SAAW,IAAI;AAAA,qBACrCA,EAAW,MAAQ,sBAAwB,IAAI;AAAA,wBAC5CxB,CAAQ;AAAA;AAAA;AAAA,WAAA,EAKvB,MAAM;AAAA,KAEb,CAAC,EAEMW,CACT"}
1
+ {"version":3,"file":"custom-elements-runtime.cjs.js","sources":["../src/lib/runtime/watchers.ts","../src/lib/runtime/props.ts","../src/lib/runtime/lifecycle.ts","../src/lib/runtime/secure-expression-evaluator.ts","../src/lib/runtime/event-manager.ts","../src/lib/runtime/vdom-model-helpers.ts","../src/lib/runtime/transition-utils.ts","../src/lib/runtime/node-metadata.ts","../src/lib/runtime/vdom.ts","../src/lib/runtime/render.ts","../src/lib/runtime/hooks.ts","../src/lib/runtime/component.ts","../src/lib/runtime/template-compiler.ts"],"sourcesContent":["import type {\n ComponentContext,\n WatchCallback,\n WatchOptions,\n WatcherState,\n} from './types';\nimport { getNestedValue } from './helpers';\nimport { devError } from './logger';\n\n/**\n * Initializes watchers for a component.\n */\nexport function initWatchers(\n context: ComponentContext<object, object, object, object>,\n watchers: Map<string, WatcherState>,\n watchConfig: Record<string, WatchCallback | [WatchCallback, WatchOptions]>,\n): void {\n if (!watchConfig) return;\n\n for (const [key, config] of Object.entries(watchConfig)) {\n let callback: WatchCallback;\n let options: WatchOptions = {};\n\n if (Array.isArray(config)) {\n callback = config[0];\n options = config[1] || {};\n } else {\n callback = config;\n }\n\n watchers.set(key, {\n callback,\n options,\n oldValue: getNestedValue(context, key),\n });\n\n if (options.immediate) {\n try {\n const currentValue = getNestedValue(context, key);\n callback(currentValue, undefined, context);\n } catch (error) {\n devError(`Error in immediate watcher for \"${key}\":`, error);\n }\n }\n }\n}\n\n/**\n * Triggers watchers when state changes.\n */\nexport function triggerWatchers(\n context: ComponentContext<object, object, object, object>,\n watchers: Map<string, WatcherState>,\n path: string,\n newValue: unknown,\n): void {\n const isEqual = (a: unknown, b: unknown): boolean => {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (typeof a !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((val, i) => isEqual(val, b[i]));\n }\n const objA = a as Record<string, unknown>;\n const objB = b as Record<string, unknown>;\n const keysA = Object.keys(objA || {});\n const keysB = Object.keys(objB || {});\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) => isEqual(objA[key], objB[key]));\n };\n\n const watcher = watchers.get(path);\n if (watcher && !isEqual(newValue, watcher.oldValue)) {\n try {\n watcher.callback(newValue, watcher.oldValue, context);\n watcher.oldValue = newValue;\n } catch (error) {\n devError(`Error in watcher for \"${path}\":`, error);\n }\n }\n\n for (const [watchPath, watcherConfig] of watchers.entries()) {\n if (watcherConfig.options.deep && path.startsWith(watchPath + '.')) {\n try {\n const currentValue = getNestedValue(context, watchPath);\n if (!isEqual(currentValue, watcherConfig.oldValue)) {\n watcherConfig.callback(currentValue, watcherConfig.oldValue, context);\n watcherConfig.oldValue = currentValue;\n }\n } catch (error) {\n devError(`Error in deep watcher for \"${watchPath}\":`, error);\n }\n }\n }\n}\n","import { toKebab } from './helpers';\nimport { isReactiveState } from './reactive';\nimport type { ComponentConfig, ComponentContext } from './types';\n\nexport type PropDefinition = {\n type:\n | StringConstructor\n | NumberConstructor\n | BooleanConstructor\n | FunctionConstructor;\n default?: string | number | boolean;\n};\n\nfunction parseProp(val: string, type: unknown) {\n if (type === Boolean) {\n // Standalone boolean attributes (e.g., <div disabled>) have empty string value\n // and should be treated as true. Explicit false is \"false\" string.\n return val === '' || val === 'true';\n }\n if (type === Number) return Number(val);\n return val;\n}\n\n/**\n * Applies props to the component context using a direct prop definitions object.\n * @param element - The custom element instance.\n * @param propDefinitions - Object mapping prop names to their definitions.\n * @param context - The component context.\n */\nexport function applyPropsFromDefinitions(\n element: HTMLElement,\n propDefinitions: Record<string, PropDefinition>,\n context: Record<string, unknown>,\n): void {\n if (!propDefinitions) return;\n\n for (const key in propDefinitions) {\n const def = propDefinitions[key];\n const kebab = toKebab(key);\n const attr = element.getAttribute(kebab);\n\n // Prefer function prop on the element instance\n if (\n def.type === Function &&\n typeof (element as unknown as Record<string, unknown>)[key] === 'function'\n ) {\n context[key] = (element as unknown as Record<string, unknown>)[key];\n } else {\n // Prefer attribute value (kebab-case)\n if (attr !== null) {\n context[key] = parseProp(attr, def.type);\n } else if (\n typeof (element as unknown as Record<string, unknown>)[key] !==\n 'undefined'\n ) {\n // Fall back to JS property value when present on the instance\n try {\n const propValue = (element as unknown as Record<string, unknown>)[\n key\n ];\n // If the property value is already the correct type, use it directly\n // For string props, attempt to convert object-like host properties to string.\n // If conversion throws, preserve the original object value on the context\n if (\n def.type === String &&\n propValue &&\n typeof propValue === 'object'\n ) {\n try {\n context[key] = parseProp(String(propValue), def.type);\n } catch {\n // If conversion fails, fallback to assigning the original object value\n context[key] = propValue;\n }\n } else if (def.type === Boolean && typeof propValue === 'boolean') {\n context[key] = propValue;\n } else if (def.type === Number && typeof propValue === 'number') {\n context[key] = propValue;\n } else if (def.type === Function && typeof propValue === 'function') {\n context[key] = propValue;\n } else {\n // Convert to string first, then parse\n context[key] = parseProp(String(propValue), def.type);\n }\n } catch {\n context[key] = (element as unknown as Record<string, unknown>)[key];\n }\n } else if ('default' in def && def.default !== undefined) {\n context[key] = def.default;\n }\n // else: leave undefined if no default\n }\n }\n}\n\n/**\n * Legacy function for ComponentConfig compatibility.\n * Applies props to the component context using a ComponentConfig.\n * @param element - The custom element instance.\n * @param cfg - The component config.\n * @param context - The component context.\n */\nexport function applyProps<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n element: HTMLElement,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n): void {\n if (!cfg.props) {\n // When there are no explicit prop definitions, define dynamic getters\n // on the component context for element properties. Also ensure getters\n // exist for props declared via useProps (context._hookCallbacks.props)\n // so components that call useProps see live host properties even if the\n // host hasn't created an own enumerable property yet.\n try {\n const declared =\n (context as { _hookCallbacks?: { props?: Record<string, unknown> } })\n ?._hookCallbacks?.props || {};\n const keys = Array.from(\n new Set([\n ...Object.keys((element as unknown as Record<string, unknown>) || {}),\n ...Object.keys(declared || {}),\n ]),\n );\n for (const key of keys) {\n // Skip internal/private fields and functions\n if (typeof key !== 'string' || key.startsWith('_')) continue;\n // Avoid overwriting existing descriptors on context\n const existing = Object.getOwnPropertyDescriptor(context, key);\n const isDeclaredProp = Object.prototype.hasOwnProperty.call(\n declared,\n key,\n );\n // If it's a declared prop via useProps, allow overriding the context\n // property with a dynamic getter so the component sees live host\n // prop values. Otherwise, avoid replacing existing accessors.\n if (\n !isDeclaredProp &&\n existing &&\n (existing.get || existing.set || !existing.configurable)\n )\n continue;\n try {\n Object.defineProperty(context, key, {\n enumerable: true,\n configurable: true,\n get() {\n try {\n // Check for attribute value first (attributes should take precedence)\n const kebab = toKebab(key);\n const attr = element.getAttribute(kebab);\n if (attr !== null) {\n // Return attribute value if present\n return attr;\n }\n\n // Fall back to property value\n const hostVal = (element as unknown as Record<string, unknown>)[\n key\n ];\n let ret;\n if (isReactiveState(hostVal))\n ret = (hostVal as { value: unknown }).value;\n else if (\n hostVal &&\n typeof hostVal === 'object' &&\n 'value' in hostVal &&\n !(hostVal instanceof Node)\n )\n ret = (hostVal as { value: unknown }).value;\n else ret = hostVal;\n // intentionally silent in production/test runs\n return ret;\n } catch {\n return (element as unknown as Record<string, unknown>)[key];\n }\n },\n });\n } catch {\n // ignore assignment errors\n }\n }\n } catch {\n // ignore\n }\n return;\n }\n applyPropsFromDefinitions(element, cfg.props, context);\n}\n","import type { ComponentConfig, ComponentContext } from './types';\n\n/**\n * Handles the connected lifecycle hook.\n */\nexport function handleConnected<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n isMounted: boolean,\n setMounted: (val: boolean) => void,\n): void {\n if (cfg.onConnected && !isMounted) {\n cfg.onConnected(context);\n setMounted(true);\n }\n}\n\n/**\n * Handles the disconnected lifecycle hook.\n */\nexport function handleDisconnected<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n listeners: Array<() => void>,\n clearListeners: () => void,\n clearWatchers: () => void,\n setTemplateLoading: (val: boolean) => void,\n setTemplateError: (err: Error | null) => void,\n setMounted: (val: boolean) => void,\n): void {\n if (cfg.onDisconnected) cfg.onDisconnected(context);\n listeners.forEach((unsub) => unsub());\n clearListeners();\n clearWatchers();\n setTemplateLoading(false);\n setTemplateError(null);\n setMounted(false);\n}\n\n/**\n * Handles the attribute changed lifecycle hook.\n */\nexport function handleAttributeChanged<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n cfg: ComponentConfig<S, C, P, T>,\n name: string,\n oldValue: string | null,\n newValue: string | null,\n context: ComponentContext<S, C, P, T>,\n): void {\n if (cfg.onAttributeChanged) {\n cfg.onAttributeChanged(name, oldValue, newValue, context);\n }\n}\n","/**\n * Secure expression evaluator to replace unsafe Function() constructor\n * Provides AST-based validation and caching for performance\n */\n\nimport { devWarn } from './logger';\nimport { getNestedValue } from './helpers';\n\ninterface ExpressionCache {\n evaluator: (context: Record<string, unknown>) => unknown;\n isSecure: boolean;\n}\n\ntype TokenType = 'NUMBER' | 'STRING' | 'IDENT' | 'PUNC' | 'OP';\ntype Token = { type: TokenType; value: string };\n\n/**\n * Secure expression evaluator with caching and AST validation\n */\nclass SecureExpressionEvaluator {\n private static cache = new Map<string, ExpressionCache>();\n private static maxCacheSize = 1000;\n\n // Dangerous patterns to block\n private static dangerousPatterns = [\n /constructor/i,\n /prototype/i,\n /__proto__/i,\n /function/i,\n /eval/i,\n /import/i,\n /require/i,\n /window/i,\n /document/i,\n /global/i,\n /process/i,\n /setTimeout/i,\n /setInterval/i,\n /fetch/i,\n /XMLHttpRequest/i,\n ];\n\n static evaluate(\n expression: string,\n context: Record<string, unknown>,\n ): unknown {\n // Check cache first\n const cached = this.cache.get(expression);\n if (cached) {\n if (!cached.isSecure) {\n devWarn('Blocked cached dangerous expression:', expression);\n return undefined;\n }\n // Move accessed entry to the end of the Map to implement LRU behavior\n // (Map preserves insertion order; deleting and re-setting moves it to the end).\n try {\n this.cache.delete(expression);\n this.cache.set(expression, cached);\n } catch {\n // ignore any cache mutations errors and continue\n }\n return cached.evaluator(context);\n }\n\n // Create and cache evaluator\n const evaluator = this.createEvaluator(expression);\n\n // Manage cache size (LRU-style)\n if (this.cache.size >= this.maxCacheSize) {\n const firstKey = this.cache.keys().next().value;\n if (firstKey) {\n this.cache.delete(firstKey);\n }\n }\n\n this.cache.set(expression, evaluator);\n\n if (!evaluator.isSecure) {\n devWarn('Blocked dangerous expression:', expression);\n return undefined;\n }\n\n return evaluator.evaluator(context);\n }\n\n private static createEvaluator(expression: string): ExpressionCache {\n // First, check for obviously dangerous patterns\n if (this.hasDangerousPatterns(expression)) {\n return { evaluator: () => undefined, isSecure: false };\n }\n\n // Size limit\n if (expression.length > 1000) {\n return { evaluator: () => undefined, isSecure: false };\n }\n\n // Try to create a safe evaluator\n try {\n const evaluator = this.createSafeEvaluator(expression);\n return { evaluator, isSecure: true };\n } catch (error) {\n devWarn('Failed to create evaluator for expression:', expression, error);\n return { evaluator: () => undefined, isSecure: false };\n }\n }\n\n private static hasDangerousPatterns(expression: string): boolean {\n return this.dangerousPatterns.some((pattern) => pattern.test(expression));\n }\n\n private static createSafeEvaluator(\n expression: string,\n ): (context: Record<string, unknown>) => unknown {\n // Handle object literals like \"{ active: ctx.isActive, disabled: ctx.isDisabled }\"\n const trimmedExpr = expression.trim();\n if (trimmedExpr.startsWith('{') && trimmedExpr.endsWith('}')) {\n return this.createObjectEvaluator(expression);\n }\n\n // Handle simple property access when the entire expression is a single ctx.path\n if (/^ctx\\.[a-zA-Z0-9_.]+$/.test(expression.trim())) {\n const propertyPath = expression.trim().slice(4);\n return (context: Record<string, unknown>) =>\n getNestedValue(context, propertyPath);\n }\n\n // If expression references `ctx` or contains operators/array/ternary\n // route it to the internal parser/evaluator which performs proper\n // token validation and evaluation. This is safer than over-restrictive\n // pre-validation and fixes cases like ternary, boolean logic, and arrays.\n if (expression.includes('ctx') || /[+\\-*/%<>=&|?:[\\]]/.test(expression)) {\n return this.createSimpleEvaluator(expression);\n }\n\n // Fallback to property lookup for plain property paths that don't\n // include ctx or operators (e.g. \"a.b\").\n return (context: Record<string, unknown>) =>\n getNestedValue(context, expression);\n }\n\n private static createObjectEvaluator(\n expression: string,\n ): (context: Record<string, unknown>) => Record<string, unknown> {\n // Parse object literal safely\n const objectContent = expression.trim().slice(1, -1); // Remove { }\n const properties = this.parseObjectProperties(objectContent);\n\n return (context: Record<string, unknown>) => {\n const result: Record<string, unknown> = {};\n\n for (const { key, value } of properties) {\n try {\n if (value.startsWith('ctx.')) {\n const propertyPath = value.slice(4);\n result[key] = getNestedValue(context, propertyPath);\n } else {\n // Try to evaluate as a simple expression\n result[key] = this.evaluateSimpleValue(value, context);\n }\n } catch {\n result[key] = undefined;\n }\n }\n\n return result;\n };\n }\n\n private static parseObjectProperties(\n content: string,\n ): Array<{ key: string; value: string }> {\n const properties: Array<{ key: string; value: string }> = [];\n const parts = content.split(',');\n\n for (const part of parts) {\n const colonIndex = part.indexOf(':');\n if (colonIndex === -1) continue;\n\n const key = part.slice(0, colonIndex).trim();\n const value = part.slice(colonIndex + 1).trim();\n\n // Remove quotes from key if present\n const cleanKey = key.replace(/^['\"]|['\"]$/g, '');\n\n properties.push({ key: cleanKey, value });\n }\n\n return properties;\n }\n\n private static createSimpleEvaluator(\n expression: string,\n ): (context: Record<string, unknown>) => unknown {\n // For simple expressions, we'll use a basic substitution approach\n return (context: Record<string, unknown>) => {\n try {\n // Work on a copy we can mutate\n let processedExpression = expression;\n\n // First, replace all string literals with placeholders to avoid accidental identifier matches inside strings\n const stringLiterals: string[] = [];\n processedExpression = processedExpression.replace(\n /(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"|'[^'\\\\]*(?:\\\\.[^'\\\\]*)*')/g,\n (m) => {\n const idx = stringLiterals.push(m) - 1;\n // Use numeric-only markers so identifier regex won't match them (they don't start with a letter)\n return `<<#${idx}#>>`;\n },\n );\n\n // Replace ctx.property references with placeholders to avoid creating new string/number\n // literals that the identifier scanner could accidentally pick up. Use processedExpression\n // (with string literals already removed) so we don't match ctx occurrences inside strings.\n const ctxMatches = processedExpression.match(/ctx\\.[\\w.]+/g) || [];\n for (const match of ctxMatches) {\n const propertyPath = match.slice(4); // Remove 'ctx.'\n const value = getNestedValue(context, propertyPath);\n if (value === undefined) return undefined; // unknown ctx property => undefined result\n const placeholderIndex =\n stringLiterals.push(JSON.stringify(value)) - 1;\n processedExpression = processedExpression.replace(\n new RegExp(match.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'),\n `<<#${placeholderIndex}#>>`,\n );\n }\n\n // Replace dotted plain identifiers (e.g. user.age) before single-token identifiers.\n // The earlier ident regex uses word boundaries which split dotted identifiers, so\n // we must handle full dotted sequences first.\n const dottedRegex =\n /\\b[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)+\\b/g;\n const dottedMatches = processedExpression.match(dottedRegex) || [];\n for (const match of dottedMatches) {\n // Skip ctx.* since those were handled above\n if (match.startsWith('ctx.')) continue;\n const value = getNestedValue(context, match);\n if (value === undefined) return undefined;\n const placeholderIndex =\n stringLiterals.push(JSON.stringify(value)) - 1;\n processedExpression = processedExpression.replace(\n new RegExp(match.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'),\n `<<#${placeholderIndex}#>>`,\n );\n }\n\n // Also support plain identifiers (root-level variables like `a`) when present.\n // Find identifiers (excluding keywords true/false/null) and replace them with values from context.\n // Note: dotted identifiers were handled above, so this regex intentionally excludes dots.\n const identRegex = /\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b/g;\n let m: RegExpExecArray | null;\n const seen: Set<string> = new Set();\n while ((m = identRegex.exec(processedExpression)) !== null) {\n const ident = m[1];\n if (['true', 'false', 'null', 'undefined'].includes(ident)) continue;\n // skip numeric-like (though regex shouldn't match numbers)\n if (/^[0-9]+$/.test(ident)) continue;\n // skip 'ctx' itself\n if (ident === 'ctx') continue;\n // Avoid re-processing same identifier\n if (seen.has(ident)) continue;\n seen.add(ident);\n\n // If identifier contains '.' try nested lookup\n const value = getNestedValue(context, ident);\n if (value === undefined) return undefined; // unknown identifier => undefined\n // Use a placeholder for the substituted value so we don't introduce new identifiers inside\n // quotes that could be matched by the ident regex.\n const repl = JSON.stringify(value);\n const placeholderIndex = stringLiterals.push(repl) - 1;\n if (ident.includes('.')) {\n // dotted identifiers contain '.' which is non-word; do a plain replace\n processedExpression = processedExpression.replace(\n new RegExp(ident.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g'),\n `<<#${placeholderIndex}#>>`,\n );\n } else {\n processedExpression = processedExpression.replace(\n new RegExp(\n '\\\\b' + ident.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') + '\\\\b',\n 'g',\n ),\n `<<#${placeholderIndex}#>>`,\n );\n }\n }\n\n // Restore string literals\n processedExpression = processedExpression.replace(\n /<<#(\\d+)#>>/g,\n (_: string, idx: string) => stringLiterals[Number(idx)],\n );\n\n // Try to evaluate using the internal parser/evaluator which performs strict token validation.\n try {\n return this.evaluateBasicExpression(processedExpression);\n } catch {\n return undefined;\n }\n } catch {\n return undefined;\n }\n };\n }\n\n /**\n * Evaluate a very small, safe expression grammar without using eval/Function.\n * Supports: numbers, string literals, true/false, null, arrays, unary !,\n * arithmetic (+ - * / %), comparisons, logical && and ||, parentheses, and ternary `a ? b : c`.\n */\n private static evaluateBasicExpression(expr: string): unknown {\n const tokens = this.tokenize(expr);\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function consume(expected?: string): Token {\n const t = tokens[pos++];\n if (expected && !t) {\n throw new Error(`Unexpected token EOF, expected ${expected}`);\n }\n if (expected && t) {\n // Allow matching by token type (e.g. 'OP', 'NUMBER') or by exact token value (e.g. '?', ':')\n if (t.type !== expected && t.value !== expected) {\n throw new Error(\n `Unexpected token ${t.type}/${t.value}, expected ${expected}`,\n );\n }\n }\n return t;\n }\n\n // Grammar (precedence):\n // expression := ternary\n // ternary := logical_or ( '?' expression ':' expression )?\n // logical_or := logical_and ( '||' logical_and )*\n // logical_and := equality ( '&&' equality )*\n // equality := comparison ( ('==' | '!=' | '===' | '!==') comparison )*\n // comparison := additive ( ('>' | '<' | '>=' | '<=') additive )*\n // additive := multiplicative ( ('+'|'-') multiplicative )*\n // multiplicative := unary ( ('*'|'/'|'%') unary )*\n // unary := ('!' | '-') unary | primary\n // primary := number | string | true | false | null | array | '(' expression ')'\n\n function parseExpression(): unknown {\n return parseTernary();\n }\n\n // Helper coercions to avoid 'any' casts:\n function toNumber(v: unknown): number {\n if (typeof v === 'number') return v;\n if (v === null || v === undefined) return NaN;\n // boolean coerces to number in JS (true->1,false->0)\n if (typeof v === 'boolean') return v ? 1 : 0;\n const n = Number(v as string);\n return Number.isNaN(n) ? NaN : n;\n }\n\n function addValues(a: unknown, b: unknown): unknown {\n if (typeof a === 'string' || typeof b === 'string')\n return String(a) + String(b);\n return toNumber(a) + toNumber(b);\n }\n\n function subValues(a: unknown, b: unknown): number {\n return toNumber(a) - toNumber(b);\n }\n\n function mulValues(a: unknown, b: unknown): number {\n return toNumber(a) * toNumber(b);\n }\n\n function divValues(a: unknown, b: unknown): number {\n return toNumber(a) / toNumber(b);\n }\n\n function modValues(a: unknown, b: unknown): number {\n return toNumber(a) % toNumber(b);\n }\n\n function compareValues(op: string, a: unknown, b: unknown): boolean {\n if (typeof a === 'number' && typeof b === 'number') {\n switch (op) {\n case '>':\n return a > b;\n case '<':\n return a < b;\n case '>=':\n return a >= b;\n case '<=':\n return a <= b;\n default:\n return false;\n }\n }\n const sa = String(a);\n const sb = String(b);\n switch (op) {\n case '>':\n return sa > sb;\n case '<':\n return sa < sb;\n case '>=':\n return sa >= sb;\n case '<=':\n return sa <= sb;\n default:\n return false;\n }\n }\n\n function parseTernary(): unknown {\n const cond = parseLogicalOr();\n const p = peek();\n if (p && p.value === '?') {\n consume('?');\n const thenExpr = parseExpression();\n consume(':');\n const elseExpr = parseExpression();\n return cond ? thenExpr : elseExpr;\n }\n return cond;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (true) {\n const p = peek();\n if (!p || p.value !== '||') break;\n consume('OP');\n const right = parseLogicalAnd();\n left = left || right;\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (true) {\n const p = peek();\n if (!p || p.value !== '&&') break;\n consume('OP');\n const right = parseEquality();\n left = left && right;\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const p = peek();\n if (!p || !['==', '!=', '===', '!=='].includes(p.value)) break;\n const op = consume('OP').value;\n const right = parseComparison();\n switch (op) {\n case '==':\n left = left == right;\n break;\n case '!=':\n left = left != right;\n break;\n case '===':\n left = left === right;\n break;\n case '!==':\n left = left !== right;\n break;\n }\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const p = peek();\n if (!p || !['>', '<', '>=', '<='].includes(p.value)) break;\n const op = consume('OP').value;\n const right = parseAdditive();\n switch (op) {\n case '>':\n left = compareValues('>', left, right);\n break;\n case '<':\n left = compareValues('<', left, right);\n break;\n case '>=':\n left = compareValues('>=', left, right);\n break;\n case '<=':\n left = compareValues('<=', left, right);\n break;\n }\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const p = peek();\n if (!p || (p.value !== '+' && p.value !== '-')) break;\n const op = consume('OP').value;\n const right = parseMultiplicative();\n left = op === '+' ? addValues(left, right) : subValues(left, right);\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const p = peek();\n if (!p || (p.value !== '*' && p.value !== '/' && p.value !== '%'))\n break;\n const op = consume('OP').value;\n const right = parseUnary();\n switch (op) {\n case '*':\n left = mulValues(left, right);\n break;\n case '/':\n left = divValues(left, right);\n break;\n case '%':\n left = modValues(left, right);\n break;\n }\n }\n return left;\n }\n\n function parseUnary(): unknown {\n const p1 = peek();\n if (p1 && p1.value === '!') {\n consume('OP');\n return !parseUnary();\n }\n if (p1 && p1.value === '-') {\n consume('OP');\n const v = parseUnary();\n return subValues(0, v);\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'NUMBER') {\n consume('NUMBER');\n return Number(t.value);\n }\n if (t.type === 'STRING') {\n consume('STRING');\n // strip quotes\n return t.value.slice(1, -1);\n }\n if (t.type === 'IDENT') {\n consume('IDENT');\n if (t.value === 'true') return true;\n if (t.value === 'false') return false;\n if (t.value === 'null') return null;\n // fallback: try parse as JSON-ish literal or undefined\n return undefined;\n }\n if (t.value === '[') {\n consume('PUNC');\n const arr: unknown[] = [];\n while (true) {\n const p = peek();\n if (!p || p.value === ']') break;\n arr.push(parseExpression());\n const p2 = peek();\n if (p2 && p2.value === ',') consume('PUNC');\n }\n consume('PUNC'); // ]\n return arr;\n }\n if (t.value === '(') {\n consume('PUNC');\n const v = parseExpression();\n consume('PUNC'); // )\n return v;\n }\n // Unknown primary\n throw new Error('Unexpected token in expression');\n }\n\n const result = parseExpression();\n return result;\n }\n\n private static tokenize(input: string): Token[] {\n const tokens: Token[] = [];\n // support escaped characters inside string literals (e.g. \"\\\"\" or '\\\\'')\n const re =\n /\\s*(=>|===|!==|==|!=|>=|<=|\\|\\||&&|[()?:,[\\]]|\\+|-|\\*|\\/|%|>|<|!|\\d+\\.?\\d*|\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|[a-zA-Z_][a-zA-Z0-9_]*|\\S)\\s*/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(input)) !== null) {\n const raw = m[1];\n if (!raw) continue;\n if (/^\\d/.test(raw)) tokens.push({ type: 'NUMBER', value: raw });\n else if (/^\"/.test(raw) || /^'/.test(raw))\n tokens.push({ type: 'STRING', value: raw });\n else if (/^[a-zA-Z_]/.test(raw))\n tokens.push({ type: 'IDENT', value: raw });\n else if (/^[()?:,[\\]]$/.test(raw))\n tokens.push({ type: 'PUNC', value: raw });\n else tokens.push({ type: 'OP', value: raw });\n }\n return tokens;\n }\n\n private static evaluateSimpleValue(\n value: string,\n context: Record<string, unknown>,\n ): unknown {\n if (value === 'true') return true;\n if (value === 'false') return false;\n if (!isNaN(Number(value))) return Number(value);\n if (value.startsWith('ctx.')) {\n const propertyPath = value.slice(4);\n return getNestedValue(context, propertyPath);\n }\n\n // Remove quotes for string literals\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n return value.slice(1, -1);\n }\n\n return value;\n }\n\n static clearCache(): void {\n this.cache.clear();\n }\n\n static getCacheSize(): number {\n return this.cache.size;\n }\n}\n\nexport { SecureExpressionEvaluator };\n","/**\n * Event Manager for tracking and cleaning up event listeners\n * Prevents memory leaks by maintaining cleanup functions\n */\n\n/**\n * Manages event listeners and their cleanup for elements\n */\nclass EventManager {\n private static cleanupFunctions = new WeakMap<\n HTMLElement,\n Array<{\n event: string;\n handler: EventListener;\n wrapper: EventListener;\n options?: AddEventListenerOptions;\n cleanup: () => void;\n addedAt: number;\n }>\n >();\n\n /**\n * Add an event listener with automatic cleanup tracking\n */\n static addListener(\n element: HTMLElement,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n ): void {\n element.addEventListener(event, handler, options);\n\n const cleanup = () => element.removeEventListener(event, handler, options);\n const meta = {\n event,\n handler,\n wrapper: handler,\n options,\n cleanup,\n addedAt: Date.now(),\n };\n\n if (!this.cleanupFunctions.has(element)) {\n this.cleanupFunctions.set(element, []);\n }\n\n const list = this.cleanupFunctions.get(element)!;\n list.push(meta);\n (list as Array<unknown> & { __metaList?: unknown }).__metaList = list;\n }\n\n /**\n * Remove a specific event listener\n */\n static removeListener(\n element: HTMLElement,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions,\n ): void {\n element.removeEventListener(event, handler, options);\n\n const cleanups = this.cleanupFunctions.get(element);\n if (!cleanups) return;\n\n // Optimized: find and remove in single pass\n for (let i = 0; i < cleanups.length; i++) {\n const m = cleanups[i];\n if (m.event === event && m.handler === handler) {\n cleanups.splice(i, 1);\n if (cleanups.length === 0) {\n this.cleanupFunctions.delete(element);\n }\n return;\n }\n }\n }\n\n /**\n * Clean up all event listeners for an element\n */\n static cleanup(element: HTMLElement): void {\n const list = this.cleanupFunctions.get(element);\n if (list) {\n list.forEach((m) => {\n try {\n m.cleanup();\n } catch {\n // Silently ignore cleanup errors\n }\n });\n this.cleanupFunctions.delete(element);\n }\n }\n\n /**\n * Clean up all tracked event listeners (useful for testing)\n */\n static cleanupAll(): void {\n // WeakMap doesn't have a clear method and automatically cleans up\n // when elements are garbage collected. Reset internal state for testing.\n this.cleanupFunctions = new WeakMap();\n }\n\n /**\n * Check if an element has any tracked event listeners\n */\n static hasListeners(element: HTMLElement): boolean {\n const list = this.cleanupFunctions.get(element);\n return !!(list && list.length > 0);\n }\n\n /**\n * Get the number of tracked event listeners for an element\n */\n static getListenerCount(element: HTMLElement): number {\n const list = this.cleanupFunctions.get(element);\n return list ? list.length : 0;\n }\n\n /**\n * Return listener metadata stored for the element (test/debug only)\n */\n static getListenerInfo(element: HTMLElement): Array<{\n event: string;\n handler?: EventListener;\n wrapper?: EventListener;\n options?: AddEventListenerOptions;\n }> {\n const list = this.cleanupFunctions.get(element);\n if (!list) return [];\n return list.map((m) => ({\n event: m.event,\n handler: m.handler,\n wrapper: m.wrapper,\n options: m.options,\n }));\n }\n}\n\nexport { EventManager };\n","/**\n * Helper functions for model binding updates in vdom.ts\n * Extracted to reduce code duplication and improve maintainability\n */\n\nimport {\n getNestedValue,\n setNestedValue,\n toKebab,\n safe,\n safeSerializeAttr,\n} from './helpers';\n\n/**\n * Check if two values have changed, handling arrays specially\n */\nexport function hasValueChanged(\n newValue: unknown,\n currentValue: unknown,\n): boolean {\n if (Array.isArray(newValue) && Array.isArray(currentValue)) {\n return (\n JSON.stringify([...newValue].sort()) !==\n JSON.stringify([...currentValue].sort())\n );\n }\n return newValue !== currentValue;\n}\n\n/**\n * Update state value (reactive or path-based)\n */\nexport function updateStateValue(\n isReactive: boolean,\n value: unknown,\n newValue: unknown,\n context: Record<string, unknown>,\n arg?: string,\n): void {\n if (isReactive) {\n const unwrapped = (value as { value?: unknown }).value;\n if (arg && typeof unwrapped === 'object' && unwrapped !== null) {\n // For :model:prop, update the specific property\n const updated = { ...(unwrapped as Record<string, unknown>) };\n (updated as Record<string, unknown>)[arg] = newValue;\n (value as { value?: unknown }).value = updated as unknown;\n } else {\n // For plain :model, update the entire value\n (value as { value?: unknown }).value = newValue;\n }\n } else {\n // Fallback to string-based update (legacy config API)\n const actualState = (context._state || context) as Record<string, unknown>;\n setNestedValue(actualState, value as string, newValue);\n }\n}\n\n/**\n * Trigger render and watchers after state update\n */\nexport function triggerStateUpdate(\n context: Record<string, unknown>,\n isReactive: boolean,\n value: unknown,\n newValue: unknown,\n): void {\n if (typeof context._requestRender === 'function') {\n context._requestRender();\n }\n\n if (typeof context._triggerWatchers === 'function') {\n const watchKey = isReactive ? 'reactiveState' : (value as string);\n context._triggerWatchers(watchKey, newValue);\n }\n}\n\n/**\n * Emit custom update events for model binding\n */\nexport function emitUpdateEvents(\n target: HTMLElement,\n propName: string,\n newValue: unknown,\n): void {\n const customEventNameKebab = `update:${toKebab(propName)}`;\n const customEventNameCamel = `update:${propName}`;\n\n const customEventKebab = new CustomEvent(customEventNameKebab, {\n detail: newValue,\n bubbles: true,\n cancelable: true,\n });\n\n const customEventCamel = new CustomEvent(customEventNameCamel, {\n detail: newValue,\n bubbles: true,\n cancelable: true,\n });\n\n target.dispatchEvent(customEventKebab);\n target.dispatchEvent(customEventCamel);\n}\n\n/**\n * Update element properties and attributes to sync with state\n */\nexport function syncElementWithState(\n target: HTMLElement | Record<string, unknown>,\n propName: string,\n propValue: unknown,\n isReactive: boolean,\n): void {\n const propToSet = isReactive ? propValue : propValue;\n\n // Set property\n safe(() => {\n if (typeof (target as HTMLElement).setAttribute === 'function') {\n // HTMLElement-like\n try {\n (target as unknown as Record<string, unknown>)[propName] = propToSet;\n } catch {\n // ignore property set failures\n }\n } else {\n // Plain record\n (target as Record<string, unknown>)[propName] = propToSet;\n }\n });\n\n // Sync attributes for primitive/boolean values\n if (\n propToSet === null ||\n propToSet === undefined ||\n typeof propToSet === 'string' ||\n typeof propToSet === 'number' ||\n typeof propToSet === 'boolean'\n ) {\n const serialized = safeSerializeAttr(propToSet);\n if (serialized !== null) {\n safe(() => {\n if (typeof (target as HTMLElement).setAttribute === 'function') {\n (target as HTMLElement).setAttribute(toKebab(propName), serialized);\n }\n });\n } else {\n safe(() => {\n if (typeof (target as HTMLElement).removeAttribute === 'function') {\n (target as HTMLElement).removeAttribute(toKebab(propName));\n }\n });\n }\n }\n}\n\n/**\n * Get current state value (reactive or path-based)\n */\nexport function getCurrentStateValue(\n isReactive: boolean,\n value: unknown,\n context: Record<string, unknown>,\n arg?: string,\n): unknown {\n if (isReactive) {\n const unwrapped = (value as { value?: unknown }).value;\n if (arg && typeof unwrapped === 'object' && unwrapped !== null) {\n return (unwrapped as Record<string, unknown>)[arg];\n }\n return unwrapped;\n } else {\n const actualState = (context._state || context) as Record<string, unknown>;\n return getNestedValue(actualState, value as string);\n }\n}\n","import { devWarn, devError } from './logger';\n\n/**\n * Transition lifecycle hook signatures\n */\ninterface TransitionHooks {\n onBeforeEnter?: (el: HTMLElement) => void;\n onEnter?: (el: HTMLElement, done?: () => void) => void;\n onAfterEnter?: (el: HTMLElement) => void;\n onBeforeLeave?: (el: HTMLElement) => void;\n onLeave?: (el: HTMLElement, done?: () => void) => void;\n onAfterLeave?: (el: HTMLElement) => void;\n onEnterCancelled?: (el: HTMLElement) => void;\n onLeaveCancelled?: (el: HTMLElement) => void;\n}\n\n/**\n * Transition utilities for VDOM\n * Handles applying transition classes and managing animation lifecycles\n */\n\n/**\n * Split space-separated class names into an array\n */\nfunction splitClasses(classString?: string): string[] {\n return classString ? classString.split(/\\s+/).filter(Boolean) : [];\n}\n\n/**\n * Add classes to an element\n * Optimized to filter out duplicates before adding\n */\nfunction addClasses(el: HTMLElement, classes: string[]): void {\n if (classes.length === 0) return;\n\n // Filter out classes that already exist (more efficient than checking one by one)\n const newClasses = classes.filter(\n (cls) => cls && !el.classList.contains(cls),\n );\n if (newClasses.length > 0) {\n el.classList.add(...newClasses);\n }\n}\n\n/**\n * Remove classes from an element\n * Optimized to batch remove all classes at once\n */\nfunction removeClasses(el: HTMLElement, classes: string[]): void {\n if (classes.length === 0) return;\n\n const validClasses = classes.filter(Boolean);\n if (validClasses.length > 0) {\n el.classList.remove(...validClasses);\n }\n}\n\n/**\n * Track if we've successfully waited for styles at least once\n * After the first successful load, we don't need to wait again\n */\nlet stylesLoadedOnce = false;\n\n/**\n * Wait for styles to be computed and applied to an element.\n * This ensures CSS is loaded before attempting to read computed styles.\n * Uses a timeout to prevent infinite waiting.\n */\nasync function waitForStyles(\n el: HTMLElement,\n _classesToCheck: string[],\n maxAttempts = 10,\n): Promise<void> {\n // If we've already loaded styles once, skip the wait\n if (stylesLoadedOnce) {\n return;\n }\n\n // If element is not in the document, styles won't compute\n if (!el.isConnected) {\n devWarn('⚠️ Element not connected to DOM, skipping style wait');\n return;\n }\n\n // Check if any of the classes produce computed styles\n for (let i = 0; i < maxAttempts; i++) {\n const computed = window.getComputedStyle(el);\n\n // Check if transform or opacity has been computed (non-empty)\n // Empty string means CSS hasn't loaded yet\n // 'none' for transform or '0'/'1' for opacity means CSS IS loaded\n const hasTransform = computed.transform && computed.transform !== '';\n const hasOpacity = computed.opacity && computed.opacity !== '';\n\n // If we have valid computed values (even if they're 'none' or '0'), styles are loaded\n if (hasTransform || hasOpacity) {\n stylesLoadedOnce = true;\n return;\n }\n\n // Wait a frame and try again\n await new Promise((resolve) =>\n requestAnimationFrame(() => resolve(undefined)),\n );\n }\n\n // If we timeout, continue anyway - styles might not be for transform/opacity\n // But mark as loaded so we don't keep checking\n stylesLoadedOnce = true;\n devWarn('⚠️ Styles did not load in time for transition, continuing anyway');\n}\n\n/**\n * Get computed transition duration in milliseconds\n */\nfunction getTransitionDuration(el: HTMLElement): number {\n const computedStyle = window.getComputedStyle(el);\n const duration = computedStyle.transitionDuration || '0s';\n const delay = computedStyle.transitionDelay || '0s';\n\n const parseDuration = (value: string): number => {\n const num = parseFloat(value);\n return value.includes('ms') ? num : num * 1000;\n };\n\n return parseDuration(duration) + parseDuration(delay);\n}\n\n/**\n * Wait for transition to complete\n */\nfunction waitForTransition(\n el: HTMLElement,\n expectedDuration?: number,\n): Promise<void> {\n return new Promise((resolve) => {\n const duration = expectedDuration ?? getTransitionDuration(el);\n\n if (duration <= 0) {\n resolve();\n return;\n }\n\n let resolved = false;\n const done = () => {\n if (!resolved) {\n resolved = true;\n el.removeEventListener('transitionend', onTransitionEnd);\n el.removeEventListener('transitioncancel', onTransitionEnd);\n resolve();\n }\n };\n\n const onTransitionEnd = () => done();\n\n el.addEventListener('transitionend', onTransitionEnd);\n el.addEventListener('transitioncancel', onTransitionEnd);\n\n // Fallback timeout in case transitionend doesn't fire\n setTimeout(done, duration + 50);\n });\n}\n\n/**\n * Perform enter transition on an element\n */\nexport async function performEnterTransition(\n el: HTMLElement,\n transitionMeta: {\n classes?: Record<string, string | undefined>;\n hooks?: TransitionHooks;\n css?: boolean;\n duration?: number | { enter?: number; leave?: number };\n [key: string]: unknown;\n },\n): Promise<void> {\n const { classes, hooks, css, duration } = transitionMeta;\n\n // Call before-enter hook\n if (hooks?.onBeforeEnter) {\n try {\n hooks.onBeforeEnter(el);\n } catch (e) {\n devError('Transition onBeforeEnter error:', e);\n }\n }\n\n if (!css) {\n // JS-only transition\n if (hooks?.onEnter) {\n return new Promise((resolve) => {\n const fn = hooks.onEnter;\n if (typeof fn === 'function') {\n fn(el, () => {\n if (hooks?.onAfterEnter) {\n try {\n hooks.onAfterEnter(el);\n } catch (e) {\n devError('Transition onAfterEnter error:', e);\n }\n }\n resolve();\n });\n } else {\n resolve();\n }\n });\n }\n return;\n }\n\n // CSS transition\n const enterFromClasses = splitClasses(classes?.enterFrom);\n const enterActiveClasses = splitClasses(classes?.enterActive);\n const enterToClasses = splitClasses(classes?.enterTo);\n\n // Step 1: Apply enter-from classes\n addClasses(el, enterFromClasses);\n\n // Force reflow to ensure enter-from is applied\n\n void el.offsetHeight;\n\n // Step 2: Add enter-active classes (transition property)\n addClasses(el, enterActiveClasses);\n\n // CRITICAL: Force another reflow so browser sees the transition property\n // applied BEFORE we change the transform/opacity values\n\n void el.offsetHeight;\n\n // Call enter hook\n let manualDone: (() => void) | undefined;\n if (hooks?.onEnter) {\n const promise = new Promise<void>((resolve) => {\n manualDone = resolve;\n });\n\n try {\n const fn = hooks.onEnter;\n if (typeof fn === 'function') {\n fn(el, () => {\n if (manualDone) manualDone();\n });\n }\n } catch (e) {\n devError('Transition onEnter error:', e);\n }\n\n // If hook provides done callback, wait for it\n if (manualDone) {\n await promise;\n }\n }\n\n // Wait for next frame - this is critical for the transition to work\n // The browser needs a frame where it sees: element + enterFrom + enterActive\n await new Promise((resolve) =>\n requestAnimationFrame(() => resolve(undefined)),\n );\n\n // Force another reflow to ensure styles are applied\n\n void el.offsetHeight;\n\n // CRITICAL: CSS class-based transitions with conflicting properties don't work\n // reliably because of cascade conflicts. When both translate-x-[100%] and\n // translate-x-[0%] are utility classes with same specificity, whichever appears\n // last in the stylesheet wins immediately - no animation.\n //\n // SOLUTION: Use inline styles for the actual transition values.\n // - Inline styles have highest specificity\n // - We capture the \"from\" computed values as inline styles\n // - Then add \"to\" classes which override the inline values\n // - Browser animates from inline styles to class-based styles\n //\n // The JIT CSS classes are still used for:\n // - transition-all, duration-300, ease-out (timing/easing)\n // - Non-animated properties (padding, colors, etc.)\n //\n // Only the ANIMATED values (transform, opacity during transition) use inline.\n\n // Capture current computed values\n const computedStyle = window.getComputedStyle(el);\n const fromTransform = computedStyle.transform;\n const fromOpacity = computedStyle.opacity;\n\n // Remove enterFrom classes\n removeClasses(el, enterFromClasses);\n\n // Apply captured values as inline styles (highest specificity)\n if (fromTransform && fromTransform !== 'none') {\n el.style.transform = fromTransform;\n }\n if (fromOpacity && fromOpacity !== '') {\n el.style.opacity = fromOpacity;\n }\n\n // Force reflow\n\n void el.offsetHeight;\n\n // Wait for next frame\n await new Promise((resolve) =>\n requestAnimationFrame(() => resolve(undefined)),\n );\n\n // Remove inline styles and add enterTo classes\n // Browser will animate from inline values to class values\n el.style.transform = '';\n el.style.opacity = '';\n addClasses(el, enterToClasses);\n\n // Force reflow to ensure styles are applied\n\n void el.offsetHeight;\n\n // Wait for next frame so browser recalculates computed styles\n await new Promise((resolve) =>\n requestAnimationFrame(() => resolve(undefined)),\n );\n\n // Get duration\n let transitionDuration: number | undefined;\n if (typeof duration === 'number') {\n transitionDuration = duration;\n } else if (duration && typeof duration === 'object' && 'enter' in duration) {\n transitionDuration = duration.enter;\n }\n\n // Wait for transition\n await waitForTransition(el, transitionDuration);\n\n // Step 3: Clean up only enterActive classes, keep enterTo as final state\n removeClasses(el, enterActiveClasses);\n // Note: We keep enterToClasses since that's the final visible state\n\n // Call after-enter hook\n if (hooks?.onAfterEnter) {\n try {\n hooks.onAfterEnter(el);\n } catch (e) {\n devError('Transition onAfterEnter error:', e);\n }\n }\n}\n\n/**\n * Perform leave transition on an element\n */\nexport async function performLeaveTransition(\n el: HTMLElement,\n transitionMeta: {\n classes?: Record<string, string | undefined>;\n hooks?: TransitionHooks;\n css?: boolean;\n duration?: number | { enter?: number; leave?: number };\n [key: string]: unknown;\n },\n): Promise<void> {\n const { classes, hooks, css, duration } = transitionMeta;\n\n // Call before-leave hook\n if (hooks?.onBeforeLeave) {\n try {\n hooks.onBeforeLeave(el);\n } catch (e) {\n devError('Transition onBeforeLeave error:', e);\n }\n }\n\n if (!css) {\n // JS-only transition\n if (hooks?.onLeave) {\n return new Promise((resolve) => {\n const fn = hooks.onLeave;\n if (typeof fn === 'function') {\n fn(el, () => {\n if (hooks?.onAfterLeave) {\n try {\n hooks.onAfterLeave(el);\n } catch (e) {\n devError('Transition onAfterLeave error:', e);\n }\n }\n resolve();\n });\n } else {\n resolve();\n }\n });\n }\n return;\n }\n\n // CSS transition\n const leaveFromClasses = splitClasses(classes?.leaveFrom);\n const leaveActiveClasses = splitClasses(classes?.leaveActive);\n const leaveToClasses = splitClasses(classes?.leaveTo);\n\n // Step 1: Apply leave-from classes\n addClasses(el, leaveFromClasses);\n\n // Force reflow\n\n void el.offsetHeight;\n\n // Step 2: Add leave-active classes\n addClasses(el, leaveActiveClasses);\n\n // Call leave hook\n let manualDone: (() => void) | undefined;\n if (hooks?.onLeave) {\n const promise = new Promise<void>((resolve) => {\n manualDone = resolve;\n });\n\n try {\n const fn = hooks.onLeave;\n if (typeof fn === 'function') {\n fn(el, () => {\n if (manualDone) manualDone();\n });\n }\n } catch (e) {\n devError('Transition onLeave error:', e);\n }\n\n // If hook provides done callback, wait for it\n if (manualDone) {\n await promise;\n }\n }\n\n // Use requestAnimationFrame\n await new Promise((resolve) =>\n requestAnimationFrame(() => resolve(undefined)),\n );\n\n // Wait for CSS to be applied\n await waitForStyles(el, [...leaveFromClasses, ...leaveActiveClasses]);\n\n // Remove leave-from and add leave-to\n removeClasses(el, leaveFromClasses);\n addClasses(el, leaveToClasses);\n\n // Get duration\n let transitionDuration: number | undefined;\n if (typeof duration === 'number') {\n transitionDuration = duration;\n } else if (duration && typeof duration === 'object' && 'leave' in duration) {\n transitionDuration = duration.leave;\n }\n\n // Wait for transition\n await waitForTransition(el, transitionDuration);\n\n // Step 3: Clean up transition classes\n removeClasses(el, leaveActiveClasses);\n removeClasses(el, leaveToClasses);\n removeClasses(el, leaveFromClasses);\n\n // Call after-leave hook\n if (hooks?.onAfterLeave) {\n try {\n hooks.onAfterLeave(el);\n } catch (e) {\n devError('Transition onAfterLeave error:', e);\n }\n }\n}\n\n/**\n * Cancel ongoing transition\n */\nexport function cancelTransition(\n el: HTMLElement,\n isEnter: boolean,\n transitionMeta: {\n classes?: Record<string, string | undefined>;\n hooks?: TransitionHooks;\n duration?: number | { enter?: number; leave?: number };\n [key: string]: unknown;\n },\n): void {\n const { classes, hooks } = transitionMeta;\n\n if (isEnter) {\n const enterFromClasses = splitClasses(classes?.enterFrom);\n const enterActiveClasses = splitClasses(classes?.enterActive);\n const enterToClasses = splitClasses(classes?.enterTo);\n\n removeClasses(el, enterFromClasses);\n removeClasses(el, enterActiveClasses);\n removeClasses(el, enterToClasses);\n\n if (hooks?.onEnterCancelled) {\n try {\n hooks.onEnterCancelled(el);\n } catch (e) {\n devError('Transition onEnterCancelled error:', e);\n }\n }\n } else {\n const leaveFromClasses = splitClasses(classes?.leaveFrom);\n const leaveActiveClasses = splitClasses(classes?.leaveActive);\n const leaveToClasses = splitClasses(classes?.leaveTo);\n\n removeClasses(el, leaveFromClasses);\n removeClasses(el, leaveActiveClasses);\n removeClasses(el, leaveToClasses);\n\n if (hooks?.onLeaveCancelled) {\n try {\n hooks.onLeaveCancelled(el);\n } catch (e) {\n devError('Transition onLeaveCancelled error:', e);\n }\n }\n }\n}\n","/**\n * Internal helpers for attaching metadata to DOM nodes without relying on\n * DOM-attached properties that minifiers or consumers might accidentally\n * rename/mangle.\n *\n * These helpers prefer WeakMap storage (safe and memory-leak free) and only\n * fall back to setting DOM properties/attributes for compatibility with older\n * code or tests.\n *\n * NOTE: This module is internal to the runtime and should not be re-exported\n * from the public API surface. Use the exported functions in this file when\n * you need minifier-safe metadata on nodes.\n *\n * Contract (brief):\n * - setNodeKey(node, key): associates an opaque string key with a Node.\n * - getNodeKey(node): returns the associated key or undefined.\n * - setElementTransition(el, val): stores transition-group metadata on an\n * element used by the patcher/transition system.\n * - getElementTransition(el): retrieves previously stored transition metadata.\n *\n * Edge cases / error modes:\n * - All setters swallow errors (defensive) to avoid breaking production code\n * when host environments restrict adding properties or attributes.\n * - Prefer the WeakMap APIs for future-proof, minifier-safe behavior.\n * @internal\n */\nconst nodeKeyMap = new WeakMap<Node, string>();\nexport interface TransitionMetadata {\n name?: string;\n appear?: boolean;\n mode?: 'out-in' | 'in-out' | 'default';\n enterClass?: string;\n leaveClass?: string;\n moveClass?: string;\n [key: string]: unknown;\n}\n\nconst elementTransitionMap = new WeakMap<HTMLElement, TransitionMetadata>();\n\n/**\n * Retrieve the stored node key for a Node.\n *\n * The lookup prefers a WeakMap-stored value. For compatibility it will also\n * attempt to read legacy fallbacks: a `.key` property or the\n * `data-anchor-key` attribute on Elements.\n *\n * @internal\n */\nexport function getNodeKey(node: Node | null | undefined): string | undefined {\n if (!node) return undefined;\n const wm = nodeKeyMap.get(node);\n if (wm !== undefined) return wm as string;\n try {\n const nodeWithKey = node as { key?: string | number };\n if (nodeWithKey && nodeWithKey.key != null) return String(nodeWithKey.key);\n } catch {\n void 0;\n }\n if (node instanceof Element) {\n const attr = node.getAttribute('data-anchor-key');\n if (attr) return attr;\n }\n return undefined;\n}\n\n/**\n * Store a node key on a Node.\n *\n * This sets a WeakMap entry and also writes defensive DOM fallbacks for\n * compatibility with older consumers/tests. Errors are swallowed to avoid\n * disrupting host environments that forbid property writes.\n *\n * @internal\n */\nimport { safeSerializeAttr } from './helpers';\n\nexport function setNodeKey(node: Node, key: string): void {\n try {\n nodeKeyMap.set(node, key);\n } catch {\n void 0;\n }\n try {\n (node as { key?: string | number }).key = key;\n } catch {\n void 0;\n }\n try {\n if (node instanceof Element) {\n const s = safeSerializeAttr(key);\n if (s !== null) node.setAttribute('data-anchor-key', s);\n }\n } catch {\n void 0;\n }\n}\n\n/**\n * Retrieve transition-group metadata attached to an element.\n *\n * Prefers the WeakMap but falls back to a legacy `._transitionGroup` property\n * if present.\n *\n * @internal\n */\nexport function getElementTransition(\n el: HTMLElement | null | undefined,\n): TransitionMetadata | undefined {\n if (!el) return undefined;\n const wm = elementTransitionMap.get(el);\n if (wm !== undefined) return wm;\n try {\n const elWithTransition = el as { _transitionGroup?: unknown };\n if (elWithTransition && elWithTransition._transitionGroup != null)\n return elWithTransition._transitionGroup as TransitionMetadata;\n } catch {\n void 0;\n }\n return undefined;\n}\n\n/**\n * Store transition-group metadata for an element.\n *\n * Writes to the WeakMap and a defensive legacy property for compatibility.\n * Errors are swallowed to avoid breaking host environments.\n *\n * @internal\n */\nexport function setElementTransition(\n el: HTMLElement,\n value: TransitionMetadata,\n): void {\n try {\n elementTransitionMap.set(el, value);\n } catch {\n void 0;\n }\n try {\n (el as { _transitionGroup?: unknown })._transitionGroup = value;\n } catch {\n void 0;\n }\n}\n\nexport default {\n getNodeKey,\n setNodeKey,\n getElementTransition,\n setElementTransition,\n};\n","/**\n * vdom.ts\n * Lightweight, strongly typed, functional virtual DOM renderer for custom elements.\n * Features: keyed diffing, incremental patching, focus/caret preservation, event delegation, SSR-friendly, no dependencies.\n */\n\nimport type { VNode, VDomRefs, AnchorBlockVNode } from './types';\nimport {\n getNestedValue,\n setNestedValue,\n toKebab,\n toCamel,\n safe,\n safeSerializeAttr,\n isClassLikeAttr,\n} from './helpers';\nimport { SecureExpressionEvaluator } from './secure-expression-evaluator';\nimport { EventManager } from './event-manager';\nimport { isReactiveState } from './reactive';\nimport {\n hasValueChanged,\n updateStateValue,\n triggerStateUpdate,\n emitUpdateEvents,\n syncElementWithState,\n getCurrentStateValue,\n} from './vdom-model-helpers';\nimport {\n performEnterTransition,\n performLeaveTransition,\n} from './transition-utils';\nimport { devError } from './logger';\nimport {\n getNodeKey,\n setNodeKey,\n getElementTransition,\n setElementTransition,\n type TransitionMetadata,\n} from './node-metadata';\n\n// Lightweight global typing used to avoid `any` casts against globalThis\ninterface VDomGlobal {\n __VDOM_DISABLED_PROMOTIONS?: unknown[];\n process?: { env?: { NODE_ENV?: string } };\n __vitest__?: unknown;\n [k: string]: unknown;\n}\n\n// Local commonly used types to avoid frequent `any` usage\ntype PropsMap = Record<string, unknown>;\ntype DirectiveSpec = { value: unknown; modifiers: string[]; arg?: string };\ntype VNodePropBag = {\n props?: PropsMap;\n attrs?: PropsMap;\n directives?: Record<string, DirectiveSpec>;\n isCustomElement?: boolean;\n [k: string]: unknown;\n};\n\n/** Minimal transition metadata shape used in the renderer for TransitionGroup/anchor blocks. */\ntype Transition = TransitionMetadata;\n\nfunction hasValueProp(v: unknown): v is { value: unknown } {\n return (\n v !== null &&\n typeof v === 'object' &&\n 'value' in (v as Record<string, unknown>)\n );\n}\n\nfunction unwrapValue(v: unknown): unknown {\n try {\n if (isReactiveState(v)) return (v as { value: unknown }).value;\n } catch {\n void 0;\n }\n try {\n if (hasValueProp(v)) return (v as { value: unknown }).value;\n } catch {\n void 0;\n }\n return v;\n}\n\n/**\n * Helper: determine whether an element is a native form control we treat\n * specially for boolean-like attributes (disabled, checked, value).\n */\nfunction isNativeControl(\n el?: HTMLElement,\n): el is\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n | HTMLButtonElement {\n return (\n el instanceof HTMLInputElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLButtonElement\n );\n}\n\n/**\n * Coerce a value to a boolean for native DOM controls.\n * Treat empty string and literal 'true' as true, 'false' as false,\n * unwrap reactive-like wrappers and fall back to Boolean(value).\n */\nfunction coerceBooleanForNative(val: unknown): boolean {\n // Explicit empty-string => presence boolean true (attribute presence)\n if (val === '') return true;\n\n // Strings: treat 'true'/'false' specially, otherwise non-empty string is presence\n if (typeof val === 'string') {\n if (val === 'false') return false;\n if (val === 'true') return true;\n return val !== '';\n }\n\n // Objects: only treat known reactive wrappers as booleans by unwrapping\n if (val && typeof val === 'object') {\n if (isReactiveState(val)) return !!(val as { value: unknown }).value;\n if ('value' in val) return !!(val as { value: unknown }).value;\n // Defensive: do not coerce arbitrary objects (including proxies) to true\n // as they may represent rich prop wrappers (useProps proxy, etc.).\n return false;\n }\n\n // Fallback for primitives (number, boolean, etc.)\n return !!val;\n}\n\n/**\n * Recursively clean up refs and event listeners for all descendants of a node\n * @param node The node to clean up.\n * @param refs The refs to clean up.\n * @returns\n */\nexport function cleanupRefs(node: Node, refs?: VDomRefs) {\n if (!refs || !(node instanceof HTMLElement)) return;\n\n // Clean up event listeners for this element\n EventManager.cleanup(node);\n\n // Clean up refs\n for (const refKey in refs) {\n if (refs[refKey] === node) {\n delete refs[refKey];\n }\n }\n\n // Clean up child nodes\n const children = node.childNodes;\n for (let i = 0; i < children.length; i++) {\n cleanupRefs(children[i], refs);\n }\n}\n\n/**\n * Assign a ref to an element, supporting both string refs and reactive state objects\n */\nfunction assignRef(vnode: VNode, element: HTMLElement, refs?: VDomRefs): void {\n if (typeof vnode === 'string') return;\n\n const reactiveRef =\n vnode.props?.reactiveRef ??\n (vnode.props?.props && vnode.props.props.reactiveRef);\n const refKey =\n vnode.props?.ref ?? (vnode.props?.props && vnode.props.props.ref);\n\n if (reactiveRef) {\n // For reactive state objects, assign the element to the .value property when possible.\n // Support both ReactiveState detection and plain objects with a `value` property.\n try {\n if (\n isReactiveState(reactiveRef) ||\n (typeof reactiveRef === 'object' && 'value' in reactiveRef)\n ) {\n (reactiveRef as { value: HTMLElement | null }).value = element;\n } else if (typeof reactiveRef === 'function') {\n // support callback refs\n (reactiveRef as unknown as (el: HTMLElement) => void)(element);\n } else if (typeof reactiveRef === 'string' && refs) {\n // string-style ref passed directly in reactiveRef slot\n try {\n const rk = String(reactiveRef);\n (refs as Record<string, HTMLElement | null>)[rk] = element;\n } catch {\n // ignore invalid ref assignments\n }\n }\n } catch {\n // ignore invalid ref assignments\n }\n } else if (refKey && refs) {\n // Legacy string-based ref - ensure string key and typed index access\n try {\n const rk = String(refKey);\n (refs as Record<string, HTMLElement | null>)[rk] = element;\n } catch {\n // ignore invalid ref assignments\n }\n }\n}\n\n/**\n * Process :model directive for two-way data binding\n * @param value\n * @param modifiers\n * @param props\n * @param attrs\n * @param listeners\n * @param context\n * @param el\n * @returns\n */\nexport function processModelDirective(\n value: string | unknown,\n modifiers: string[],\n props: Record<string, unknown>,\n attrs: Record<string, unknown>,\n listeners: Record<string, EventListener>,\n context?: Record<string, unknown>,\n el?: HTMLElement,\n arg?: string,\n): void {\n if (!context) return;\n\n const hasLazy = modifiers.includes('lazy');\n const hasTrim = modifiers.includes('trim');\n const hasNumber = modifiers.includes('number');\n\n // Enhanced support for reactive state objects (functional API)\n\n const getCurrentValue = () => {\n if (isReactiveState(value)) {\n const unwrapped = (value as { value?: unknown }).value;\n // If this is a native input and an arg was provided (e.g. :model:name),\n // we should bind the nested property to the input's value.\n if (\n arg &&\n el &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n if (typeof unwrapped === 'object' && unwrapped !== null) {\n return (unwrapped as Record<string, unknown>)[arg as string];\n }\n }\n // Otherwise return the full unwrapped value for custom element props\n return unwrapped;\n }\n // Fallback to string-based lookup (legacy config API)\n // Ensure we pass a Record<string, unknown> to getNestedValue\n const actualContext =\n ((context as { _state?: unknown } | undefined)?._state as Record<\n string,\n unknown\n >) || (context as Record<string, unknown>);\n return getNestedValue(actualContext, value as string);\n };\n\n const currentValue = getCurrentValue();\n\n // determine element/input type\n let inputType = 'text';\n if (el instanceof HTMLInputElement)\n inputType = (attrs?.type as string) || el.type || 'text';\n else if (el instanceof HTMLSelectElement) inputType = 'select';\n else if (el instanceof HTMLTextAreaElement) inputType = 'textarea';\n\n const isNativeInput =\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement;\n const defaultPropName =\n inputType === 'checkbox' || inputType === 'radio' ? 'checked' : 'value';\n const propName = isNativeInput ? defaultPropName : (arg ?? 'modelValue');\n\n // Initial sync: set prop/attrs so renderer can apply proper DOM state\n if (inputType === 'checkbox') {\n if (Array.isArray(currentValue)) {\n props[propName] = currentValue.includes(\n String(el?.getAttribute('value') ?? attrs?.value ?? ''),\n );\n } else {\n const trueValue = el?.getAttribute('true-value') ?? true;\n props[propName] = currentValue === trueValue;\n }\n } else if (inputType === 'radio') {\n props[propName] = currentValue === (attrs?.value ?? '');\n } else if (inputType === 'select') {\n // For multiple selects we also schedule option selection; otherwise set prop\n if (el && el.hasAttribute('multiple') && el instanceof HTMLSelectElement) {\n const arr = Array.isArray(currentValue) ? currentValue.map(String) : [];\n setTimeout(() => {\n Array.from((el as HTMLSelectElement).options).forEach((option) => {\n option.selected = arr.includes(option.value);\n });\n }, 0);\n props[propName] = Array.isArray(currentValue) ? currentValue : [];\n } else {\n props[propName] = currentValue;\n }\n } else {\n // For custom elements (non-native inputs) prefer assigning the\n // ReactiveState instance itself to the prop so child components that\n // call useProps can detect and unwrap the live ref. For native\n // inputs we must set the unwrapped current value.\n if (!isNativeInput && isReactiveState(value)) {\n props[propName] = value; // pass the ReactiveState instance\n } else {\n props[propName] = currentValue;\n }\n // Also set an attribute so custom element constructors / applyProps can\n // read initial values via getAttribute during their initialization.\n try {\n const attrName = toKebab(propName);\n if (attrs) attrs[attrName] = currentValue;\n } catch {\n // ignore\n }\n }\n\n // event type to listen for\n const eventType =\n hasLazy ||\n inputType === 'checkbox' ||\n inputType === 'radio' ||\n inputType === 'select'\n ? 'change'\n : 'input';\n\n const eventListener: EventListener = (event: Event) => {\n if (\n (event as { isComposing?: boolean }).isComposing ||\n (listeners as { _isComposing?: boolean })._isComposing\n )\n return;\n // Allow synthetic events during testing (when isTrusted is false)\n // but ignore them in production unless it's a synthetic test event\n const _proc = (globalThis as VDomGlobal).process;\n const isTestEnv =\n (!!_proc && _proc.env?.NODE_ENV === 'test') ||\n (typeof window !== 'undefined' && (globalThis as VDomGlobal).__vitest__);\n if ((event as { isTrusted?: boolean }).isTrusted === false && !isTestEnv)\n return;\n\n const target = event.target as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n | null;\n if (!target || (target as { _modelUpdating?: boolean })._modelUpdating)\n return;\n\n let newValue: unknown = (target as { value?: unknown }).value;\n\n if (inputType === 'checkbox') {\n const fresh = getCurrentValue();\n if (Array.isArray(fresh)) {\n const v = target.getAttribute('value') ?? '';\n const arr = Array.from(fresh as unknown[]);\n if ((target as HTMLInputElement).checked) {\n if (!arr.includes(v)) arr.push(v);\n } else {\n const idx = arr.indexOf(v);\n if (idx > -1) arr.splice(idx, 1);\n }\n newValue = arr;\n } else {\n const trueV = target.getAttribute('true-value') ?? true;\n const falseV = target.getAttribute('false-value') ?? false;\n newValue = (target as HTMLInputElement).checked ? trueV : falseV;\n }\n } else if (inputType === 'radio') {\n newValue =\n target.getAttribute('value') ?? (target as { value?: unknown }).value;\n } else if (\n inputType === 'select' &&\n (target as HTMLSelectElement).multiple\n ) {\n newValue = Array.from((target as HTMLSelectElement).selectedOptions).map(\n (o) => o.value,\n );\n } else {\n if (hasTrim && typeof newValue === 'string') newValue = newValue.trim();\n if (hasNumber) {\n const n = Number(newValue);\n if (!isNaN(n)) newValue = n;\n }\n }\n\n const currentStateValue = getCurrentValue();\n const changed = hasValueChanged(newValue, currentStateValue);\n\n if (changed) {\n (target as HTMLElement & { _modelUpdating?: boolean })._modelUpdating =\n true;\n try {\n updateStateValue(isReactiveState(value), value, newValue, context, arg);\n triggerStateUpdate(context, isReactiveState(value), value, newValue);\n\n // Emit custom event for update:* listeners (emit both kebab and camel forms)\n if (target) {\n emitUpdateEvents(target, propName, newValue);\n }\n } finally {\n setTimeout(\n () =>\n ((\n target as HTMLElement & { _modelUpdating?: boolean }\n )._modelUpdating = false),\n 0,\n );\n }\n }\n };\n\n // Custom element update event names (update:prop) for non-native inputs\n if (!isNativeInput) {\n const eventNameKebab = `update:${toKebab(propName)}`;\n const eventNameCamel = `update:${propName}`;\n // Remove existing listeners to prevent memory leaks\n if (listeners[eventNameKebab]) {\n const oldListener = listeners[eventNameKebab];\n if (el) EventManager.removeListener(el, eventNameKebab, oldListener);\n }\n if (listeners[eventNameCamel]) {\n const oldListener = listeners[eventNameCamel];\n if (el) EventManager.removeListener(el, eventNameCamel, oldListener);\n }\n\n listeners[eventNameKebab] = (event: Event) => {\n const detail = (event as CustomEvent).detail;\n let newVal: unknown = detail !== undefined ? detail : undefined;\n if (newVal === undefined) {\n // Fallback: if the event target has a `value` property use it even\n // when it's not a real DOM element (tests may provide plain objects).\n const t = (event as unknown as { target?: unknown }).target;\n if (\n t &&\n typeof t === 'object' &&\n 'value' in (t as Record<string, unknown>)\n ) {\n try {\n newVal = (t as Record<string, unknown>).value;\n } catch {\n newVal = undefined;\n }\n }\n }\n // Determine current state value depending on reactive-state vs string path\n const currentStateValue = getCurrentStateValue(\n isReactiveState(value),\n value,\n context,\n arg,\n );\n const changed = hasValueChanged(newVal, currentStateValue);\n\n if (changed) {\n try {\n /* nested handler invoked */\n } catch {\n void 0;\n }\n\n updateStateValue(isReactiveState(value), value, newVal, context, arg);\n triggerStateUpdate(context, isReactiveState(value), value, newVal);\n\n // Update the custom element's property to maintain sync\n const target = event.target as HTMLElement | null;\n if (target) {\n syncElementWithState(\n target,\n propName,\n isReactiveState(value) ? value : newVal,\n isReactiveState(value),\n );\n }\n }\n };\n // primary listener registered\n // If the bound reactive value is an object, also listen for nested\n // update events emitted by the child like `update:name` so the parent\n // can apply the change to the corresponding nested property on the\n // reactive state. This allows children to emit `update:<field>` when\n // they want to update a nested field of a bound object.\n if (\n isReactiveState(value) &&\n typeof (value as { value?: unknown }).value === 'object' &&\n (value as { value?: unknown }).value !== null\n ) {\n // Use Reflect.ownKeys to be robust across proxies; filter out internal keys\n let keys: Array<string | symbol> = [];\n try {\n keys = Reflect.ownKeys((value as { value?: unknown }).value!);\n } catch {\n keys = Object.keys((value as { value?: unknown }).value!);\n }\n const userKeys = (keys as Array<string | symbol>).filter(\n (k) =>\n typeof k === 'string' &&\n !String(k).startsWith('_') &&\n k !== 'constructor',\n );\n // preparing nested listeners\n for (const nestedKey of userKeys) {\n const nestedKeyStr = String(nestedKey);\n const nestedKebab = `update:${toKebab(nestedKeyStr)}`;\n const nestedCamel = `update:${nestedKeyStr}`;\n // Avoid overwriting the primary handler for the main prop\n // and avoid registering internal keys\n if (listeners[nestedKebab]) continue;\n listeners[nestedKebab] = (event: Event) => {\n const newVal =\n (event as CustomEvent).detail !== undefined\n ? (event as CustomEvent).detail\n : (event.target as { value?: unknown })?.value;\n const currentStateValue = isReactiveState(value)\n ? ((value as { value?: unknown }).value as Record<string, unknown>)[\n nestedKeyStr\n ]\n : getNestedValue(\n ((context as { _state?: unknown } | undefined)?._state as\n | Record<string, unknown>\n | undefined) || (context as Record<string, unknown>),\n value as string,\n );\n const changed = hasValueChanged(newVal, currentStateValue);\n if (!changed) return;\n\n // Update the ReactiveState with a shallow copy so reactivity triggers\n if (isReactiveState(value)) {\n const updated = {\n ...((value as { value?: unknown }).value as Record<\n string,\n unknown\n >),\n };\n (updated as Record<string, unknown>)[nestedKeyStr] = newVal;\n (value as { value?: unknown }).value = updated;\n } else {\n setNestedValue(\n ((context as { _state?: unknown } | undefined)?._state as Record<\n string,\n unknown\n >) || (context as Record<string, unknown>),\n value as string,\n newVal,\n );\n }\n\n triggerStateUpdate(context, isReactiveState(value), value, newVal);\n\n const host =\n (event.currentTarget as HTMLElement) ||\n el ||\n (event.target as HTMLElement);\n if (host) {\n syncElementWithState(\n host,\n propName,\n isReactiveState(value) ? value : newVal,\n isReactiveState(value),\n );\n }\n };\n listeners[nestedCamel] = listeners[nestedKebab];\n }\n }\n // Mirror handler under camel name for compatibility\n listeners[eventNameCamel] = listeners[eventNameKebab];\n } else {\n // Remove existing listener to prevent memory leaks\n if (listeners[eventType]) {\n const oldListener = listeners[eventType];\n if (el) {\n EventManager.removeListener(el, eventType, oldListener);\n }\n }\n listeners[eventType] = eventListener;\n }\n\n // IME composition handling for text-like inputs\n if (inputType === 'text' || inputType === 'textarea') {\n listeners.compositionstart = () =>\n ((listeners as { _isComposing?: boolean })._isComposing = true);\n listeners.compositionend = (event: Event) => {\n (listeners as { _isComposing?: boolean })._isComposing = false;\n const target = event.target as\n | HTMLInputElement\n | HTMLTextAreaElement\n | null;\n if (!target) return;\n setTimeout(() => {\n const val = target.value;\n const actualState =\n ((context as { _state?: unknown } | undefined)?._state as Record<\n string,\n unknown\n >) || (context as Record<string, unknown>);\n const currentStateValue = getNestedValue(actualState, value as string);\n let newVal: string | number = val;\n if (hasTrim) newVal = newVal.trim();\n if (hasNumber) {\n const n = Number(newVal);\n if (!isNaN(n)) newVal = n;\n }\n const changed = hasValueChanged(newVal, currentStateValue);\n if (changed) {\n (\n target as HTMLElement & { _modelUpdating?: boolean }\n )._modelUpdating = true;\n try {\n setNestedValue(actualState, value as string, newVal);\n triggerStateUpdate(context, isReactiveState(value), value, newVal);\n } finally {\n setTimeout(\n () =>\n ((\n target as HTMLElement & { _modelUpdating?: boolean }\n )._modelUpdating = false),\n 0,\n );\n }\n }\n }, 0);\n };\n }\n // processModelDirective listeners prepared\n}\n\n/**\n * Convert a prop key like `onClick` to its DOM event name `click`.\n */\nfunction eventNameFromKey(key: string): string {\n // Strip leading 'on' and lowercase the first character of the remainder.\n // This handles names like `onClick` -> `click` and\n // `onUpdate:model-value` -> `update:model-value` correctly.\n const rest = key.slice(2);\n if (!rest) return '';\n return rest.charAt(0).toLowerCase() + rest.slice(1);\n}\n\n/**\n * Process :bind directive for attribute/property binding\n * @param value\n * @param props\n * @param attrs\n * @param context\n * @returns\n */\nexport function processBindDirective(\n value: unknown,\n props: PropsMap,\n attrs: PropsMap,\n context?: Record<string, unknown>,\n el?: HTMLElement,\n): void {\n // Support both object and string syntax for :bind\n if (typeof value === 'object' && value !== null) {\n for (const [key, val] of Object.entries(value)) {\n // Only put clearly HTML-only attributes in attrs, everything else in props\n // For native input/select/textarea elements, boolean-like attributes\n // such as `disabled` should be applied as attributes rather than\n // props to avoid placing wrapper/complex values into props which\n // can later be misinterpreted as truthy and disable the control.\n if (\n key.startsWith('data-') ||\n key.startsWith('aria-') ||\n key === 'class'\n ) {\n attrs[key] = val;\n } else if (key === 'disabled' && el && isNativeControl(el)) {\n // For native controls, prefer promoting reactive/wrapper values to props\n // so property assignment keeps a live reference and updates via reactivity.\n // For primitive booleans/strings prefer attrs to avoid placing arbitrary\n // objects into props which can be misinterpreted.\n const isWrapper = val && typeof val === 'object' && 'value' in val;\n const isReactiveVal = (() => {\n try {\n return isReactiveState(val);\n } catch {\n return false;\n }\n })();\n if (isReactiveVal || isWrapper) {\n props[key] = val;\n } else {\n attrs[key] = val;\n }\n } else {\n props[key] = val;\n }\n }\n } else if (typeof value === 'string') {\n if (!context) return;\n try {\n // Try to evaluate as expression (could be object literal)\n const evaluated = evaluateExpression(value, context);\n if (typeof evaluated === 'object' && evaluated !== null) {\n for (const [key, val] of Object.entries(evaluated)) {\n // Mirror the object branch handling but we don't have access to\n // the element here; prefer attrs for booleanish disabled when\n // the expression produced primitive booleans or strings.\n if (\n key.startsWith('data-') ||\n key.startsWith('aria-') ||\n key === 'class'\n ) {\n attrs[key] = val;\n } else if (key === 'disabled' && el && isNativeControl(el)) {\n const isWrapper = val && typeof val === 'object' && 'value' in val;\n const isReactiveVal = (() => {\n try {\n return isReactiveState(val);\n } catch {\n return false;\n }\n })();\n if (isReactiveVal || isWrapper) {\n props[key] = val;\n } else {\n attrs[key] = val;\n }\n } else {\n props[key] = val;\n }\n }\n return;\n } else {\n // If not an object, treat as single value fallback\n attrs[value] = evaluated;\n return;\n }\n } catch {\n // Fallback: treat as single property binding\n const currentValue = getNestedValue(\n context as Record<string, unknown>,\n value as string,\n );\n attrs[value] = currentValue;\n }\n }\n}\n\n/**\n * Process :show directive for conditional display\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\nexport function processShowDirective(\n value: unknown,\n attrs: Record<string, unknown>,\n context?: Record<string, unknown>,\n): void {\n let isVisible: unknown;\n\n // Handle both string and direct value evaluation\n if (typeof value === 'string') {\n if (!context) return;\n isVisible = evaluateExpression(value, context);\n } else {\n isVisible = value;\n }\n\n // Use the same approach as :style directive for consistency\n const currentStyle = String(attrs.style || '');\n let newStyle = currentStyle;\n\n if (!isVisible) {\n // Element should be hidden - ensure display: none is set\n if (currentStyle) {\n const styleRules = String(currentStyle).split(';').filter(Boolean);\n const displayIndex = styleRules.findIndex((rule: string) =>\n rule.trim().startsWith('display:'),\n );\n\n if (displayIndex >= 0) {\n styleRules[displayIndex] = 'display: none';\n } else {\n styleRules.push('display: none');\n }\n\n newStyle = styleRules.join('; ');\n } else {\n newStyle = 'display: none';\n }\n } else {\n // Element should be visible - only remove display: none, don't interfere with other display values\n if (currentStyle) {\n const styleRules = String(currentStyle)\n .split(';')\n .map((rule: string) => rule.trim())\n .filter(Boolean);\n const displayIndex = styleRules.findIndex((rule: string) =>\n rule.startsWith('display:'),\n );\n\n if (displayIndex >= 0) {\n const displayRule = styleRules[displayIndex];\n if (displayRule === 'display: none') {\n // Remove only display: none, preserve other display values\n styleRules.splice(displayIndex, 1);\n newStyle = styleRules.length > 0 ? styleRules.join('; ') + ';' : '';\n }\n // If display is set to something other than 'none', leave it alone\n }\n }\n // If no existing style, don't add anything\n }\n\n // Only set style if it's different from current to avoid unnecessary updates\n if (newStyle !== currentStyle) {\n if (newStyle) {\n attrs.style = newStyle;\n } else {\n // Remove the style attribute entirely if empty\n delete attrs.style;\n }\n }\n}\n\n/**\n * Process :class directive for conditional CSS classes\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\n/**\n * Evaluate a JavaScript-like object literal string in the given context\n * Uses secure AST-based evaluation instead of Function() constructor\n * @param expression\n * @param context\n * @returns\n */\nfunction evaluateExpression(\n expression: string,\n context: Record<string, unknown>,\n): unknown {\n return SecureExpressionEvaluator.evaluate(expression, context);\n}\n\nexport function processClassDirective(\n value: unknown,\n attrs: Record<string, unknown>,\n context?: Record<string, unknown>,\n): void {\n let classValue: unknown;\n\n // Handle both string and object values\n if (typeof value === 'string') {\n if (!context) return;\n classValue = evaluateExpression(value, context);\n } else {\n classValue = value;\n }\n\n // Unwrap reactive/computed wrappers (ReactiveState) to get the inner value\n try {\n if (classValue && typeof classValue === 'object') {\n if (isReactiveState(classValue)) {\n classValue = (classValue as { value: unknown }).value;\n } else if (\n 'value' in classValue &&\n typeof (classValue as { value: unknown }).value !== 'undefined'\n ) {\n // Best-effort unwrap for objects with a `.value` property that\n // are not DOM nodes (avoid unwrapping nodes that expose `.value`).\n const maybe = (classValue as { value: unknown }).value;\n if (!(maybe instanceof Node)) {\n classValue = maybe;\n }\n }\n }\n } catch {\n // ignore\n }\n\n let classes: string[] = [];\n\n if (typeof classValue === 'string') {\n classes = [classValue];\n } else if (Array.isArray(classValue)) {\n classes = classValue.filter(Boolean);\n } else if (typeof classValue === 'object' && classValue !== null) {\n // Object syntax: { className: condition } - optimized without flatMap\n for (const [className, condition] of Object.entries(classValue)) {\n if (condition) {\n classes.push(className);\n }\n }\n }\n\n const existingClasses = attrs.class || '';\n const classString = classes.join(' ');\n attrs.class = existingClasses\n ? `${existingClasses} ${classString}`.trim()\n : classString;\n}\n\n/**\n * Determine whether a value coming from vnode.props should be treated as\n * an explicit boolean-like value for property assignment. This avoids\n * treating empty-string or arbitrary objects as a truthy disabled prop\n * for native controls (we prefer attribute presence in those cases).\n */\nfunction isBooleanishForProps(v: unknown): boolean {\n // Only treat clear boolean-like values as booleanish for prop preference.\n // Accept explicit booleans, explicit empty-string (attribute presence),\n // and explicit 'true'/'false' strings. Do NOT treat numbers or arbitrary\n // objects as booleanish to avoid accidental truthiness for `disabled`.\n if (v === true || v === false) return true;\n if (v === undefined || v === null) return false;\n const t = typeof v;\n if (t === 'string') return v === '' || v === 'true' || v === 'false';\n try {\n if (v && typeof v === 'object' && 'value' in v) {\n const inner = (v as { value: unknown }).value;\n const it = typeof inner;\n if (it === 'boolean') return true;\n if (it === 'string')\n return inner === '' || inner === 'true' || inner === 'false';\n return false;\n }\n } catch {\n void 0;\n }\n return false;\n}\n\n/**\n * Process :style directive for dynamic inline styles\n * @param value\n * @param attrs\n * @param context\n * @returns\n */\nexport function processStyleDirective(\n value: unknown,\n attrs: Record<string, unknown>,\n context?: Record<string, unknown>,\n): void {\n let styleValue: unknown;\n\n if (typeof value === 'string') {\n if (!context) return;\n styleValue = evaluateExpression(value, context);\n } else {\n styleValue = value;\n }\n\n let styleString = '';\n\n if (typeof styleValue === 'string') {\n styleString = styleValue;\n } else if (styleValue && typeof styleValue === 'object') {\n const styleRules: string[] = [];\n for (const [property, val] of Object.entries(styleValue)) {\n if (val != null && val !== '') {\n const kebabProperty = property.replace(\n /[A-Z]/g,\n (match) => `-${match.toLowerCase()}`,\n );\n const needsPx = [\n 'width',\n 'height',\n 'top',\n 'right',\n 'bottom',\n 'left',\n 'margin',\n 'margin-top',\n 'margin-right',\n 'margin-bottom',\n 'margin-left',\n 'padding',\n 'padding-top',\n 'padding-right',\n 'padding-bottom',\n 'padding-left',\n 'font-size',\n 'line-height',\n 'border-width',\n 'border-radius',\n 'min-width',\n 'max-width',\n 'min-height',\n 'max-height',\n ];\n let cssValue = String(val);\n if (typeof val === 'number' && needsPx.includes(kebabProperty)) {\n cssValue = `${val}px`;\n }\n styleRules.push(`${kebabProperty}: ${cssValue}`);\n }\n }\n styleString = styleRules.join('; ') + (styleRules.length > 0 ? ';' : '');\n }\n\n const existingStyle = String(attrs.style || '');\n attrs.style =\n existingStyle +\n (existingStyle && !existingStyle.endsWith(';') ? '; ' : '') +\n styleString;\n}\n\n/**\n * Process :ref directive for element references\n * @param value\n * @param props\n * @param context\n * @returns\n */\nexport function processRefDirective(\n value: unknown,\n props: Record<string, unknown>,\n context?: Record<string, unknown>,\n): void {\n let resolvedValue = value;\n\n // If value is a string, evaluate it in the context to resolve variables\n if (typeof value === 'string' && context) {\n resolvedValue = evaluateExpression(value, context);\n }\n\n // Support both reactive state objects (functional API) and string refs (legacy)\n if (isReactiveState(resolvedValue)) {\n // For reactive state objects, store the reactive state object itself as the ref\n // The VDOM renderer will handle setting the value\n props.reactiveRef = resolvedValue;\n } else {\n // Legacy string-based ref or direct object ref\n props.ref = resolvedValue;\n }\n}\n\n/**\n * Process directives and return merged props, attrs, and event listeners\n * @param directives\n * @param context\n * @param el\n * @param vnodeAttrs\n * @returns\n */\nexport function processDirectives(\n directives: Record<\n string,\n { value: unknown; modifiers: string[]; arg?: string }\n >,\n context?: Record<string, unknown>,\n el?: HTMLElement,\n vnodeAttrs?: PropsMap,\n): {\n props: Record<string, unknown>;\n attrs: Record<string, unknown>;\n listeners: Record<string, EventListener>;\n} {\n const props: PropsMap = {};\n const attrs: PropsMap = { ...(vnodeAttrs || {}) };\n const listeners: Record<string, EventListener> = {};\n\n for (const [directiveName, directive] of Object.entries(directives)) {\n const { value, modifiers, arg } = directive;\n\n if (directiveName === 'model' || directiveName.startsWith('model:')) {\n // Extract arg from directiveName if present (model:prop)\n const parts = directiveName.split(':');\n const runtimeArg = parts.length > 1 ? parts[1] : arg;\n processModelDirective(\n value, // Pass the original value (could be string or reactive state object)\n modifiers,\n props,\n attrs,\n listeners,\n context,\n el,\n runtimeArg,\n );\n continue;\n }\n\n switch (directiveName) {\n case 'bind':\n processBindDirective(value, props, attrs, context, el);\n break;\n case 'show':\n processShowDirective(value, attrs, context);\n break;\n case 'class':\n processClassDirective(value, attrs, context);\n break;\n case 'style':\n processStyleDirective(value, attrs, context);\n break;\n case 'ref':\n processRefDirective(value, props, context);\n break;\n case 'when':\n // The :when directive is handled during template compilation\n // by wrapping the element in an anchor block\n // This case should not normally be reached, but we handle it gracefully\n break;\n // Add other directive cases here as needed\n }\n }\n\n // Defensive post-processing: avoid leaving primitive non-wrapper\n // `disabled` values in processed props for native form controls.\n // Some code paths may incorrectly place a primitive boolean/string into\n // props which later becomes authoritative and disables native inputs.\n // To be safe, if `disabled` was placed into props by directives but is\n // a plain primitive (not a ReactiveState or wrapper with `.value`) and\n // the target element is a native input/select/textarea, move it to attrs\n // so the final disabled decision uses attribute/coercion rules instead.\n try {\n const had = Object.prototype.hasOwnProperty.call(props, 'disabled');\n if (had && el && isNativeControl(el)) {\n const candidate = props['disabled'];\n const isWrapper =\n candidate && typeof candidate === 'object' && 'value' in candidate;\n let isReactiveVal = false;\n try {\n isReactiveVal = isReactiveState(candidate);\n } catch {\n isReactiveVal = false;\n }\n // If it's NOT reactive/wrapper, prefer attrs to avoid accidental truthiness\n if (!isWrapper && !isReactiveVal) {\n try {\n attrs['disabled'] = candidate;\n delete props['disabled'];\n const w = globalThis as VDomGlobal;\n if (!w.__VDOM_DISABLED_PROMOTIONS) w.__VDOM_DISABLED_PROMOTIONS = [];\n (w.__VDOM_DISABLED_PROMOTIONS as unknown[]).push({\n phase: 'bind-directive:postfix-move',\n location: 'attrs',\n key: 'disabled',\n value: candidate,\n time: Date.now(),\n stack: new Error().stack,\n });\n } catch {\n // ignore\n }\n }\n }\n } catch {\n void 0;\n }\n\n return { props, attrs, listeners };\n}\n\n/**\n * Assign unique keys to VNodes for efficient rendering\n * @param nodeOrNodes\n * @param baseKey\n * @returns\n */\nexport function assignKeysDeep(\n nodeOrNodes: VNode | VNode[],\n baseKey: string,\n): VNode | VNode[] {\n if (Array.isArray(nodeOrNodes)) {\n const usedKeys = new Set<string>();\n\n return nodeOrNodes.map((child) => {\n if (!child || typeof child !== 'object') return child;\n\n // Determine the starting key\n let key = child.props?.key ?? child.key;\n\n if (!key) {\n // Build a stable identity from tag + stable attributes\n const tagPart = child.tag || 'node';\n // Look for stable identity attributes in both attrs and promoted\n // props (props.props) because the compiler may have promoted bound\n // attributes to JS properties for custom elements and converted\n // kebab-case to camelCase (e.g. data-key -> dataKey).\n const idAttrCandidates = [\n // attrs (kebab-case)\n child.props?.attrs?.id,\n child.props?.attrs?.name,\n child.props?.attrs?.['data-key'],\n // promoted JS props (camelCase or original)\n child.props?.props?.id,\n child.props?.props?.name,\n child.props?.props?.dataKey,\n child.props?.props?.['data-key'],\n ];\n const idPart =\n idAttrCandidates.find((v) => v !== undefined && v !== null) ?? '';\n key = idPart\n ? `${baseKey}:${tagPart}:${idPart}`\n : `${baseKey}:${tagPart}`;\n }\n\n // Ensure uniqueness among siblings\n let uniqueKey = key;\n let counter = 1;\n while (usedKeys.has(uniqueKey)) {\n uniqueKey = `${key}#${counter++}`;\n }\n usedKeys.add(uniqueKey);\n\n // Recurse into children with this node's unique key\n let children = child.children;\n if (Array.isArray(children)) {\n children = assignKeysDeep(children, uniqueKey) as VNode[];\n }\n\n return { ...child, key: uniqueKey, children };\n });\n }\n\n // Single node case\n const node = nodeOrNodes as VNode;\n const key = node.props?.key ?? node.key ?? baseKey;\n\n let children = node.children;\n if (Array.isArray(children)) {\n children = assignKeysDeep(children, key) as VNode[];\n }\n\n return { ...node, key, children };\n}\n\n/**\n * Patch props on an element.\n * Only update changed props, remove old, add new.\n * @param el\n * @param oldProps\n * @param newProps\n * @param context\n */\nexport function patchProps(\n el: HTMLElement,\n oldProps: VNodePropBag,\n newProps: VNodePropBag,\n context?: Record<string, unknown>,\n) {\n // Process directives first\n const newDirectives =\n (newProps.directives as Record<string, DirectiveSpec> | undefined) ?? {};\n const processedDirectives = processDirectives(\n newDirectives,\n context,\n el,\n newProps.attrs,\n );\n\n // Merge processed directive results with existing props/attrs\n const mergedProps: PropsMap = {\n ...((oldProps.props as PropsMap) || {}),\n ...((newProps.props as PropsMap) || {}),\n ...(processedDirectives.props || {}),\n };\n const mergedAttrs: PropsMap = {\n ...((oldProps.attrs as PropsMap) || {}),\n ...((newProps.attrs as PropsMap) || {}),\n ...(processedDirectives.attrs || {}),\n };\n\n const oldPropProps = (oldProps.props as PropsMap) ?? {};\n const newPropProps = mergedProps;\n // Detect whether this vnode represents a custom element so we can\n // trigger its internal prop application lifecycle after patching.\n const elIsCustom = Boolean(\n newProps?.isCustomElement ?? oldProps?.isCustomElement ?? false,\n );\n let anyChange = false;\n for (const key in { ...oldPropProps, ...newPropProps }) {\n const oldVal = oldPropProps[key];\n const newVal = newPropProps[key];\n\n // For reactive wrapper objects (ReactiveState or { value }), compare\n // their unwrapped inner values so updates trigger even when the\n // wrapper identity stays the same across renders.\n let oldUnwrapped: unknown = oldVal;\n let newUnwrapped: unknown = newVal;\n safe(() => {\n if (isReactiveState(oldVal))\n oldUnwrapped = (oldVal as { value: unknown }).value;\n else if (hasValueProp(oldVal))\n oldUnwrapped = (oldVal as { value: unknown }).value;\n });\n safe(() => {\n if (isReactiveState(newVal))\n newUnwrapped = (newVal as { value: unknown }).value;\n else if (hasValueProp(newVal))\n newUnwrapped = (newVal as { value: unknown }).value;\n });\n\n // Consider changed when either the wrapper identity changed or the\n // inner unwrapped value changed.\n if (oldVal !== newVal && oldUnwrapped === newUnwrapped) {\n // wrapper identity changed but inner value same -> still treat as change\n }\n\n if (!(oldVal === newVal && oldUnwrapped === newUnwrapped)) {\n anyChange = true;\n if (\n key === 'value' &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n // Unwrap reactive-like wrappers before assigning to .value\n const unwrapped = unwrapValue(newVal);\n const coerced =\n unwrapped === undefined || unwrapped === null\n ? ''\n : String(unwrapped);\n if (el.value !== coerced) el.value = coerced;\n } else if (key === 'checked' && el instanceof HTMLInputElement) {\n const unwrapped = unwrapValue(newVal);\n el.checked = !!unwrapped;\n } else if (key.startsWith('on') && typeof newVal === 'function') {\n // DOM-first listener: onClick -> click\n const ev = eventNameFromKey(key);\n if (typeof oldVal === 'function') {\n EventManager.removeListener(el, ev, oldVal as EventListener);\n }\n if (typeof newVal === 'function') {\n EventManager.addListener(el, ev, newVal as EventListener);\n }\n // If this is an update:* handler for a bound object prop, also\n // register nested update:<field> listeners that call the same\n // handler with a shallow-copied object so compiled handlers that\n // expect the full object will work with child-emitted nested events.\n try {\n if (ev && ev.startsWith('update:')) {\n const propName = ev.split(':', 2)[1];\n const propVal = newPropProps[propName] as unknown;\n // Determine nested keys robustly: if propVal is a ReactiveState,\n // inspect its .value, otherwise inspect the object itself.\n let candidateKeys: string[] = [];\n try {\n if (isReactiveState(propVal)) {\n const v = (propVal as { value?: unknown }).value;\n candidateKeys =\n v && typeof v === 'object' ? Object.keys(v) : [];\n } else if (propVal && typeof propVal === 'object') {\n candidateKeys = Object.keys(propVal as Record<string, unknown>);\n }\n } catch {\n candidateKeys = [];\n }\n // Filter out internal keys\n const userKeys = candidateKeys.filter(\n (k) =>\n typeof k === 'string' &&\n !k.startsWith('_') &&\n k !== 'constructor',\n );\n for (const nestedKey of userKeys) {\n const nestedEvent = `update:${nestedKey}`;\n const nestedHandler = (e: Event) => {\n const nestedNew =\n (e as CustomEvent).detail !== undefined\n ? (e as CustomEvent).detail\n : e.target instanceof HTMLInputElement ||\n e.target instanceof HTMLTextAreaElement ||\n e.target instanceof HTMLSelectElement\n ? (\n e.target as\n | HTMLInputElement\n | HTMLTextAreaElement\n | HTMLSelectElement\n ).value\n : undefined;\n const current = isReactiveState(propVal)\n ? ((propVal as { value?: unknown }).value as Record<\n string,\n unknown\n >) || {}\n : (newPropProps[propName] as Record<string, unknown>) || {};\n const updated = { ...current, [nestedKey]: nestedNew };\n try {\n if (typeof newVal === 'function') {\n (newVal as (...args: unknown[]) => unknown)({\n detail: updated,\n } as unknown);\n }\n } catch {\n void 0;\n }\n };\n safe(() => {\n EventManager.addListener(el, nestedEvent, nestedHandler);\n });\n }\n }\n } catch {\n /* ignore */\n }\n } else if (newVal === undefined || newVal === null) {\n el.removeAttribute(key);\n } else {\n // Prefer setting DOM properties for custom elements or when the\n // property already exists on the element so that JS properties are\n // updated (important for custom elements that observe property changes).\n // Prefer property assignment for elements that are custom elements or\n // when the property exists on the element. This avoids attribute\n // fallbacks being used for reactive properties on custom elements.\n // Rely only on compiler/runtime-provided hint. Do not perform implicit\n // dash-based heuristics here: callers/tests should set isCustomElement on\n // the vnode props when a tag is a custom element.\n const elIsCustom =\n newProps?.isCustomElement ?? oldProps?.isCustomElement ?? false;\n if (elIsCustom || key in el) {\n try {\n (el as unknown as Record<string, unknown>)[key] = newVal;\n // For native form controls, also remove the disabled attribute when setting disabled=false\n // The browser doesn't automatically sync the attribute when the property changes\n if (\n key === 'disabled' &&\n newVal === false &&\n !elIsCustom &&\n isNativeControl(el)\n ) {\n el.removeAttribute('disabled');\n }\n } catch {\n // Enforce property-only binding: skip silently on failure.\n }\n } else {\n // Handle boolean false by removing attribute for non-custom elements\n if (newVal === false) {\n el.removeAttribute(key);\n } else {\n // Property does not exist; skip silently.\n }\n }\n }\n }\n }\n\n // Handle directive event listeners\n for (const [eventType, listener] of Object.entries(\n processedDirectives.listeners || {},\n )) {\n EventManager.addListener(el, eventType, listener as EventListener);\n try {\n const parentEl = el && (el.parentElement as HTMLElement | null);\n if (parentEl && parentEl !== el) {\n EventManager.addListener(\n parentEl,\n eventType,\n listener as EventListener,\n );\n }\n } catch {\n void 0;\n }\n }\n\n const oldAttrs = oldProps.attrs ?? {};\n const newAttrs = mergedAttrs;\n for (const key in { ...oldAttrs, ...newAttrs }) {\n const oldVal = oldAttrs[key];\n const newVal = newAttrs[key];\n\n // For reactive state objects, compare the unwrapped values\n let oldUnwrapped = oldVal;\n let newUnwrapped = newVal;\n\n if (isReactiveState(oldVal)) {\n oldUnwrapped = (oldVal as { value?: unknown }).value; // This triggers dependency tracking\n }\n if (isReactiveState(newVal)) {\n newUnwrapped = (newVal as { value?: unknown }).value; // This triggers dependency tracking\n }\n\n if (oldUnwrapped !== newUnwrapped) {\n anyChange = true;\n // Handle removal/null/false: remove attribute and clear corresponding\n // DOM property for native controls where Vue treats null/undefined as ''\n if (\n newUnwrapped === undefined ||\n newUnwrapped === null ||\n newUnwrapped === false\n ) {\n safe(() => {\n el.removeAttribute(key);\n });\n\n // Clear value for native controls when value is removed\n if (key === 'value') {\n if (\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement\n ) {\n safe(() => {\n el.value = '';\n });\n } else if (el instanceof HTMLSelectElement) {\n safe(() => {\n el.value = '';\n });\n } else if (el instanceof HTMLProgressElement) {\n safe(() => {\n (el as HTMLProgressElement).value = 0;\n });\n }\n }\n\n // Clear checked for checkbox/radio\n if (key === 'checked' && el instanceof HTMLInputElement) {\n safe(() => {\n el.checked = false;\n });\n }\n\n // Ensure disabled property is unset for native controls\n if (key === 'disabled' && isNativeControl(el)) {\n safe(() => {\n if (el instanceof HTMLInputElement)\n (el as HTMLInputElement).disabled = false;\n else if (el instanceof HTMLSelectElement)\n (el as HTMLSelectElement).disabled = false;\n else if (el instanceof HTMLTextAreaElement)\n (el as HTMLTextAreaElement).disabled = false;\n else if (el instanceof HTMLButtonElement)\n (el as HTMLButtonElement).disabled = false;\n });\n }\n } else {\n // New value present: for native controls prefer assigning .value/.checked\n if (key === 'value') {\n if (\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement\n ) {\n safe(() => {\n el.value = (newUnwrapped as string) ?? '';\n });\n continue;\n } else if (el instanceof HTMLSelectElement) {\n safe(() => {\n el.value = (newUnwrapped as string) ?? '';\n });\n continue;\n } else if (el instanceof HTMLProgressElement) {\n safe(() => {\n (el as HTMLProgressElement).value = Number(newUnwrapped);\n });\n continue;\n }\n }\n if (key === 'checked' && el instanceof HTMLInputElement) {\n safe(() => {\n el.checked = !!newUnwrapped;\n });\n continue;\n }\n\n // Special handling for style attribute - always use setAttribute\n if (key === 'style') {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n continue;\n }\n\n // Defensive handling for disabled when a new value is present\n if (key === 'disabled' && isNativeControl(el)) {\n safe(() => {\n const final = coerceBooleanForNative(newUnwrapped);\n if (el instanceof HTMLInputElement)\n (el as HTMLInputElement).disabled = final;\n else if (el instanceof HTMLSelectElement)\n (el as HTMLSelectElement).disabled = final;\n else if (el instanceof HTMLTextAreaElement)\n (el as HTMLTextAreaElement).disabled = final;\n else if (el instanceof HTMLButtonElement)\n (el as HTMLButtonElement).disabled = final;\n });\n if (!coerceBooleanForNative(newUnwrapped))\n safe(() => {\n el.removeAttribute(key);\n });\n else\n safe(() => {\n el.setAttribute(key, '');\n });\n continue;\n }\n\n // Non-native or generic attributes: prefer property when available\n const isSVG =\n (el as Element).namespaceURI === 'http://www.w3.org/2000/svg';\n\n // For custom elements, convert kebab-case attributes to camelCase properties\n // and prefer assigning ReactiveState instances directly to element\n // properties so child components that call useProps receive the\n // live ReactiveState (with .value) instead of a stale plain object.\n // However, preserve kebab-case class-like attributes (ending with\n // `-class`) as attributes so they remain visible in serialized\n // HTML (important for JIT CSS extraction). Only non-class-like\n // kebab attributes are promoted to camelCase props.\n if (elIsCustom && !isSVG && key.includes('-')) {\n // For custom elements, prefer promoting kebab attributes to properties\n // except for class-like attributes which should remain attributes\n // for reliable HTML serialization. Use helpers to ensure safe string\n // serialization.\n if (isClassLikeAttr(key)) {\n const serialized = safeSerializeAttr(newVal ?? newUnwrapped);\n if (serialized !== null) {\n try {\n el.setAttribute(key, serialized);\n } catch {\n /* best-effort */\n }\n }\n } else {\n const camelKey = toCamel(key);\n try {\n const hostObj = el as unknown as Record<string, unknown>;\n hostObj[camelKey] = isReactiveState(newVal)\n ? (newVal as unknown)\n : newUnwrapped;\n } catch {\n // If property assignment fails, fall back to attribute\n const serialized = safeSerializeAttr(newVal ?? newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n } else if (!isSVG && key in el) {\n try {\n const hostObj = el as unknown as Record<string, unknown>;\n hostObj[key] = isReactiveState(newVal)\n ? (newVal as unknown)\n : newUnwrapped;\n } catch {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n const serialized = safeSerializeAttr(newUnwrapped);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n }\n }\n\n // If this is a custom element, attempt to notify it that props/attrs\n // were updated so it can re-run its internal applyProps logic and\n // schedule a render. This mirrors the behavior in createElement where\n // newly created custom elements are told to apply props and render.\n // Defensive: ensure native disabled property matches the intended source\n try {\n if (isNativeControl(el)) {\n const propCandidate = (mergedProps as PropsMap)['disabled'];\n // Only treat the propCandidate as the authoritative source when it's\n // a clear boolean-ish primitive or a reactive/wrapper we can unwrap.\n // Otherwise fallback to mergedAttrs to avoid arbitrary objects (proxies,\n // wrapper containers) from being treated as truthy and disabling native\n // controls.\n let sourceVal: unknown;\n try {\n // If the disabled was provided via a directive (processedDirectives)\n // or is a reactive/wrapper value we can safely prefer the prop.\n // Also accept clear boolean-ish primitive prop values as authoritative\n // so native inputs receive intended boolean state. Otherwise prefer\n // the attribute source to avoid arbitrary objects (proxies, wrapper\n // containers) from being treated as truthy and disabling native\n // controls.\n const hasDisabledInProcessed = Object.prototype.hasOwnProperty.call(\n processedDirectives.props || {},\n 'disabled',\n );\n const isWrapper =\n propCandidate &&\n typeof propCandidate === 'object' &&\n 'value' in propCandidate;\n let isReactive = false;\n safe(() => {\n isReactive = !!isReactiveState(propCandidate);\n });\n const isBooleanish = isBooleanishForProps(propCandidate);\n if (isReactive || isWrapper || hasDisabledInProcessed || isBooleanish) {\n sourceVal = propCandidate;\n } else {\n sourceVal = (mergedAttrs as PropsMap)['disabled'];\n }\n } catch {\n sourceVal = (mergedAttrs as PropsMap)['disabled'];\n }\n const finalDisabled = coerceBooleanForNative(sourceVal);\n safe(() => {\n if (el instanceof HTMLInputElement)\n (el as HTMLInputElement).disabled = finalDisabled;\n else if (el instanceof HTMLSelectElement)\n (el as HTMLSelectElement).disabled = finalDisabled;\n else if (el instanceof HTMLTextAreaElement)\n (el as HTMLTextAreaElement).disabled = finalDisabled;\n else if (el instanceof HTMLButtonElement)\n (el as HTMLButtonElement).disabled = finalDisabled;\n });\n if (finalDisabled) {\n safe(() => {\n el.setAttribute('disabled', '');\n });\n } else {\n safe(() => {\n el.removeAttribute('disabled');\n });\n }\n }\n } catch {\n void 0;\n }\n\n if (elIsCustom && anyChange) {\n const maybeEl = el as unknown as {\n _applyProps?: (cfg?: unknown) => void;\n _cfg?: unknown;\n requestRender?: () => void;\n _render?: (cfg?: unknown) => void;\n };\n safe(() => {\n maybeEl._applyProps?.(maybeEl._cfg);\n });\n safe(() => {\n if (typeof maybeEl.requestRender === 'function') maybeEl.requestRender();\n else if (typeof maybeEl._render === 'function')\n maybeEl._render?.(maybeEl._cfg);\n });\n }\n}\n\n/**\n * Create a DOM element from a VNode.\n * @param vnode\n * @param context\n * @param refs\n * @returns\n */\nexport function createElement(\n vnode: VNode | string,\n context?: Record<string, unknown>,\n refs?: VDomRefs,\n): Node {\n // String VNode → plain text node (no key)\n if (typeof vnode === 'string') {\n return document.createTextNode(vnode);\n }\n\n // Text VNode\n if (vnode.tag === '#text') {\n const textNode = document.createTextNode(\n typeof vnode.children === 'string' ? vnode.children : '',\n );\n if (vnode.key != null) setNodeKey(textNode, vnode.key); // attach key\n return textNode;\n }\n\n // Raw HTML vnode - insert provided HTML as nodes (unsafe: caller must opt-in)\n if (vnode.tag === '#raw') {\n const html = typeof vnode.children === 'string' ? vnode.children : '';\n const range = document.createRange();\n // createContextualFragment is broadly supported and safe when used with\n // controlled input. We intentionally call it for opt-in raw HTML insertion.\n const frag = range.createContextualFragment(html);\n return frag;\n }\n\n // Anchor block VNode - ALWAYS create start/end boundaries\n if (vnode.tag === '#anchor') {\n const anchorVNode = vnode as AnchorBlockVNode;\n const children = Array.isArray(anchorVNode.children)\n ? anchorVNode.children\n : [];\n\n // Always create start/end markers for stable boundaries\n const start = document.createTextNode('');\n const end = document.createTextNode('');\n\n if (anchorVNode.key != null) {\n setNodeKey(start, `${anchorVNode.key}:start`);\n setNodeKey(end, `${anchorVNode.key}:end`);\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n\n for (const child of children) {\n const childNode = createElement(child, context);\n // Propagate anchor block's key to child elements ONLY if child doesn't have its own key\n // This allows keyed lists (each()) to preserve their own keys\n if (\n anchorVNode.key != null &&\n childNode instanceof Element &&\n !childNode.hasAttribute('data-anchor-key')\n ) {\n const childVNode = child as VNode;\n const childHasOwnKey =\n childVNode &&\n typeof childVNode === 'object' &&\n childVNode.key != null;\n\n if (!childHasOwnKey) {\n setNodeKey(childNode, String(anchorVNode.key));\n }\n }\n frag.appendChild(childNode);\n }\n frag.appendChild(end);\n return frag;\n }\n\n // Standard element VNode\n const el = document.createElement(vnode.tag);\n if (vnode.key != null) setNodeKey(el, vnode.key);\n\n // Store TransitionGroup metadata on the DOM element for patchChildren to use\n if (vnode.props && (vnode.props as VNodePropBag)?._transitionGroup) {\n setElementTransition(\n el,\n (vnode.props as VNodePropBag)?._transitionGroup as TransitionMetadata,\n );\n }\n\n const { props = {}, attrs = {}, directives = {} } = vnode.props ?? {};\n\n // Process directives first to get merged props/attrs/listeners\n const processedDirectives = processDirectives(directives, context, el, attrs);\n\n // Merge processed directive results with existing props/attrs\n const mergedProps = {\n ...props,\n ...processedDirectives.props,\n };\n const mergedAttrs = {\n ...attrs,\n ...processedDirectives.attrs,\n };\n\n // Ensure any explicit string `class` provided on the vnode (static class)\n // is applied to the host element as a plain attribute. This guarantees\n // that parent serialized `innerHTML` includes user-specified utility\n // classes (important for JIT CSS extraction and tests). Use a safe\n // string coercion and ignore non-string values to avoid assigning\n // complex objects to DOM attributes which can throw in jsdom.\n try {\n const hostClass =\n (mergedAttrs && mergedAttrs.class) ??\n (mergedProps && mergedProps.class) ??\n (vnode.props && vnode.props.attrs && vnode.props.attrs.class) ??\n (vnode.props && vnode.props.props && vnode.props.props.class);\n const serializedHostClass = safeSerializeAttr(hostClass);\n if (serializedHostClass !== null) {\n const cls = String(serializedHostClass).trim();\n if (cls) el.setAttribute('class', cls);\n }\n } catch {\n void 0;\n }\n\n // Defensive: if the compiler (vnode.props) or earlier processing placed\n // a primitive `disabled` into props for a native input, move it to attrs\n // to avoid accidental truthiness causing native controls to be disabled.\n try {\n if (\n (mergedProps as Record<string, unknown>).disabled !== undefined &&\n el &&\n isNativeControl(el)\n ) {\n const candidate = (mergedProps as Record<string, unknown>).disabled;\n const isWrapper =\n candidate && typeof candidate === 'object' && 'value' in candidate;\n let isReactiveVal = false;\n try {\n isReactiveVal = isReactiveState(candidate);\n } catch {\n isReactiveVal = false;\n }\n if (!isWrapper && !isReactiveVal) {\n safe(() => {\n (mergedAttrs as Record<string, unknown>).disabled = candidate;\n delete (mergedProps as Record<string, unknown>).disabled;\n });\n }\n }\n } catch {\n void 0;\n }\n\n // Set attributes\n // Prefer property assignment for certain attributes (value/checked) and\n // when the element exposes a corresponding property. SVG elements should\n // keep attributes only.\n const isSVG = (el as Element).namespaceURI === 'http://www.w3.org/2000/svg';\n for (const key in mergedAttrs) {\n const val = mergedAttrs[key];\n // Only allow valid attribute names (string, not object)\n if (typeof key !== 'string' || /\\[object Object\\]/.test(key)) {\n continue;\n }\n // Unwrap reactive-like wrappers (ReactiveState or { value }) to primitives\n const unwrappedVal = unwrapValue(val);\n\n if (typeof unwrappedVal === 'boolean') {\n // Use the unwrapped boolean to decide presence of boolean attributes\n if (unwrappedVal) {\n el.setAttribute(key, '');\n } else {\n safe(() => {\n el.removeAttribute(key);\n });\n }\n } else if (unwrappedVal !== undefined && unwrappedVal !== null) {\n // For disabled attr on native inputs, coerce to boolean and set property\n if (key === 'disabled' && isNativeControl(el)) {\n // Prefer props over attrs when deciding disabled state, but only when\n // the prop value is explicitly booleanish (boolean, numeric, or wrapper).\n // This avoids treating empty-string or arbitrary objects on props as\n // truthy which would incorrectly disable native controls.\n const propCandidate = (mergedProps as Record<string, unknown>).disabled;\n const sourceVal = isBooleanishForProps(propCandidate)\n ? propCandidate\n : unwrappedVal;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (\n el as\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n | HTMLButtonElement\n ).disabled = final;\n });\n if (final) {\n safe(() => {\n el.setAttribute(key, '');\n });\n } else {\n safe(() => {\n el.removeAttribute(key);\n });\n }\n // keep going (do not fallthrough to attribute string path)\n continue;\n }\n // Special-case value/checked for native inputs so .value/.checked are set\n if (\n !isSVG &&\n key === 'value' &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLProgressElement)\n ) {\n try {\n // Progress expects numeric value\n if (el instanceof HTMLProgressElement)\n (el as HTMLProgressElement).value = Number(unwrappedVal as unknown);\n else el.value = String(unwrappedVal ?? '');\n } catch {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else if (\n !isSVG &&\n key === 'checked' &&\n el instanceof HTMLInputElement\n ) {\n try {\n el.checked = !!unwrappedVal;\n } catch {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else if (!isSVG && key in el) {\n try {\n (el as unknown as Record<string, unknown>)[key] = unwrappedVal;\n // For native form controls, also remove the disabled attribute when setting disabled=false\n // The browser doesn't automatically sync the attribute when the property changes\n if (\n key === 'disabled' &&\n unwrappedVal === false &&\n isNativeControl(el)\n ) {\n el.removeAttribute('disabled');\n }\n } catch {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n // For custom elements, convert kebab-case attributes to camelCase properties\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n if (vnodeIsCustom && !isSVG && key.includes('-')) {\n const camelKey = toCamel(key);\n try {\n (el as unknown as Record<string, unknown>)[camelKey] = unwrappedVal;\n } catch {\n // If property assignment fails, fall back to attribute\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n } else {\n const serialized = safeSerializeAttr(unwrappedVal);\n if (serialized !== null) el.setAttribute(key, serialized);\n }\n }\n }\n }\n\n // Set props and event listeners\n for (const key in mergedProps) {\n const val = mergedProps[key];\n // Only allow valid attribute names (string, not object)\n if (typeof key !== 'string' || /\\[object Object\\]/.test(key)) {\n // Skip invalid prop keys silently to keep runtime minimal\n continue;\n }\n if (\n key === 'value' &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n // Check if val is a reactive state object and extract its value\n // Use the getter to ensure dependency tracking happens\n const propValue =\n typeof val === 'object' && val !== null && hasValueProp(val)\n ? (val as { value: unknown }).value\n : val;\n safe(() => {\n (\n el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n ).value = String(propValue ?? '');\n });\n } else if (key.startsWith('on') && typeof val === 'function') {\n // If a directive already provided a listener for this event (for\n // example :model produced update:prop handlers), prefer the directive\n // listener and skip the prop-based handler. This avoids attaching\n // compiler-generated handlers that close over transient render-local\n // variables and later do nothing when events fire.\n const eventType = eventNameFromKey(key);\n // Also consider alternate camel/kebab variant when checking directive provided listeners\n const altEventType = eventType.includes(':')\n ? (() => {\n const parts = eventType.split(':');\n const prop = parts[1];\n if (prop.includes('-')) {\n const camel = prop\n .split('-')\n .map((p, i) =>\n i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1),\n )\n .join('');\n return `${parts[0]}:${camel}`;\n } else {\n const kebab = prop\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase();\n return `${parts[0]}:${kebab}`;\n }\n })()\n : eventType;\n if (\n processedDirectives.listeners &&\n (processedDirectives.listeners[eventType] ||\n processedDirectives.listeners[altEventType])\n ) {\n // skip prop handler in favor of directive-provided listener\n } else {\n EventManager.addListener(el, eventType, val as EventListener);\n }\n } else if (key.startsWith('on') && val === undefined) {\n continue; // skip undefined event handlers\n } else if (val === undefined || val === null || val === false) {\n el.removeAttribute(key);\n } else {\n // Prefer setting DOM properties for custom elements or when the\n // property already exists on the element. This ensures JS properties\n // (and reactive custom element props) receive the value instead of\n // only an HTML attribute string. However, certain attributes like\n // `class` and `style` should remain HTML attributes on the host so\n // they show up in serialized `innerHTML` (important for JIT CSS\n // extraction and tests). Handle those as attributes explicitly.\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n // Compute propValue once for use in attribute/property assignment.\n const propValue =\n typeof val === 'object' && val !== null && isReactiveState(val)\n ? val\n : hasValueProp(val) &&\n typeof (val as { value: unknown }).value !== 'undefined'\n ? (val as { value: unknown }).value\n : val;\n\n if (key === 'class' || key === 'style') {\n try {\n const serialized = safeSerializeAttr(propValue);\n if (serialized !== null) el.setAttribute(key, serialized);\n } catch {\n void 0;\n }\n continue;\n }\n if (vnodeIsCustom || key in el) {\n try {\n // If this is a ReactiveState instance, assign the instance itself\n // to custom element properties so child components can call\n // useProps and receive the live ReactiveState (with .value).\n const propValue =\n typeof val === 'object' && val !== null && isReactiveState(val)\n ? val\n : hasValueProp(val)\n ? (val as { value: unknown }).value\n : val;\n // For native elements and the disabled prop, coerce to a boolean\n if (key === 'disabled' && isNativeControl(el)) {\n const sourceVal =\n (mergedProps as Record<string, unknown>).disabled !== undefined\n ? (mergedProps as Record<string, unknown>).disabled\n : propValue;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (\n el as\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n | HTMLButtonElement\n ).disabled = final;\n });\n if (final) {\n safe(() => {\n el.setAttribute(key, '');\n });\n } else {\n safe(() => {\n el.removeAttribute(key);\n });\n }\n continue;\n }\n // Coerce boolean DOM properties to real booleans. This prevents\n // empty-string or 'false' string values from incorrectly enabling\n // properties like `disabled` during SSR/attribute promotions.\n try {\n const existingProp = (el as unknown as Record<string, unknown>)[\n key\n ];\n if (typeof existingProp === 'boolean') {\n let assignValue: unknown = propValue;\n if (typeof propValue === 'string') {\n if (propValue === 'false') assignValue = false;\n else if (propValue === 'true') assignValue = true;\n else assignValue = !!propValue && propValue !== '';\n } else {\n assignValue = !!propValue;\n }\n (el as unknown as Record<string, unknown>)[key] = assignValue;\n } else {\n (el as unknown as Record<string, unknown>)[key] =\n propValue as unknown;\n }\n } catch {\n (el as unknown as Record<string, unknown>)[key] =\n propValue as unknown;\n }\n } catch {\n // silently skip on failure\n }\n } else {\n // silently skip when property doesn't exist\n }\n }\n }\n\n // Handle directive event listeners\n for (const [eventType, listener] of Object.entries(\n processedDirectives.listeners || {},\n )) {\n EventManager.addListener(el, eventType, listener as EventListener);\n }\n\n // Assign ref if present - create a vnode with processed props for ref assignment\n const vnodeWithProcessedProps = {\n ...vnode,\n props: {\n ...vnode.props,\n ...processedDirectives.props,\n },\n };\n assignRef(vnodeWithProcessedProps, el as HTMLElement, refs);\n\n // If this is a custom element instance, request an initial render now that\n // attributes/props/listeners have been applied. This fixes the common timing\n // issue where the element constructor rendered before the renderer set the\n // initial prop values (for example :model or :model:prop). Prefer the\n // public requestRender API when available, otherwise call internal _render\n // with the stored config.\n try {\n // If the element exposes a public requestRender or internal _render/_applyProps,\n // call them safely. Use a typed wrapper to avoid repeated `as any` casts.\n const maybeEl = el as HTMLElement & {\n _applyProps?: (cfg?: unknown) => void;\n _cfg?: unknown;\n requestRender?: () => void;\n _render?: (cfg?: unknown) => void;\n };\n if (typeof maybeEl._applyProps === 'function') {\n try {\n maybeEl._applyProps(maybeEl._cfg);\n } catch {\n // ignore\n }\n }\n if (typeof maybeEl.requestRender === 'function') {\n maybeEl.requestRender();\n } else if (typeof maybeEl._render === 'function') {\n maybeEl._render(maybeEl._cfg);\n }\n } catch {\n // Swallow errors to keep the renderer robust and minimal.\n }\n\n // Append children\n if (Array.isArray(vnode.children)) {\n for (const child of vnode.children) {\n el.appendChild(createElement(child, context, refs));\n }\n } else if (typeof vnode.children === 'string') {\n el.textContent = vnode.children;\n }\n\n // After children are appended, reapply select value selection if necessary.\n try {\n if (\n el instanceof HTMLSelectElement &&\n mergedAttrs &&\n Object.prototype.hasOwnProperty.call(mergedAttrs, 'value')\n ) {\n try {\n el.value = String(mergedAttrs['value'] ?? '');\n } catch {\n // ignore\n }\n }\n } catch {\n // ignore\n }\n\n // Final defensive enforcement: ensure native controls are only disabled\n // when the authoritative source is a clear boolean-ish primitive or a\n // reactive/wrapper that unwraps to a boolean. This prevents transient\n // propagation of miscellaneous objects or compiler-promoted primitives\n // from leaving native inputs disabled on initial mount.\n try {\n if (isNativeControl(el)) {\n const propCandidate = (mergedProps as Record<string, unknown>).disabled;\n const attrCandidate = (mergedAttrs as Record<string, unknown>).disabled;\n const isWrapper =\n propCandidate &&\n typeof propCandidate === 'object' &&\n 'value' in propCandidate;\n let isReactive = false;\n try {\n isReactive = !!isReactiveState(propCandidate);\n } catch {\n isReactive = false;\n }\n // choose authoritative source: prefer reactive/wrapper/booleanish propCandidate\n const useProp =\n isReactive || isWrapper || isBooleanishForProps(propCandidate);\n const sourceVal = useProp ? propCandidate : attrCandidate;\n const final = coerceBooleanForNative(sourceVal);\n safe(() => {\n (\n el as\n | HTMLInputElement\n | HTMLSelectElement\n | HTMLTextAreaElement\n | HTMLButtonElement\n ).disabled = final;\n });\n if (!final)\n safe(() => {\n el.removeAttribute('disabled');\n });\n else\n safe(() => {\n el.setAttribute('disabled', '');\n });\n }\n } catch {\n void 0;\n }\n\n return el;\n}\n\n/**\n * Patch children using keys for node matching.\n * @param parent\n * @param oldChildren\n * @param newChildren\n * @param context\n * @param refs\n * @returns\n */\nexport function patchChildren(\n parent: HTMLElement,\n oldChildren: VNode[] | string | undefined,\n newChildren: VNode[] | string | undefined,\n context?: Record<string, unknown>,\n refs?: VDomRefs,\n): void {\n if (typeof newChildren === 'string') {\n if (parent.textContent !== newChildren) parent.textContent = newChildren;\n return;\n }\n if (!Array.isArray(newChildren)) return;\n\n // Cache childNodes to avoid issues with live NodeList during mutations\n const oldNodeList = parent.childNodes;\n const oldNodesCache: Node[] = [];\n for (let i = 0; i < oldNodeList.length; i++) {\n oldNodesCache.push(oldNodeList[i]);\n }\n const oldVNodes: VNode[] = Array.isArray(oldChildren) ? oldChildren : [];\n\n // Check if parent has TransitionGroup metadata (use WeakMap-backed accessor)\n const transitionGroup = getElementTransition(parent as HTMLElement);\n\n // If TransitionGroup, flatten anchor blocks and handle as batch keyed diff\n if (transitionGroup) {\n // Helper to strip 'each-' prefix from keys for proper keyed diffing\n const stripKeyPrefix = (key: unknown): string | undefined => {\n if (typeof key === 'string') {\n return key.startsWith('each-') ? key.substring(5) : key;\n }\n if (typeof key === 'number') return String(key);\n return undefined;\n };\n\n const flattenedNew: VNode[] = [];\n const flattenedOldVNodes: VNode[] = [];\n\n // Flatten new children (extract from anchor blocks)\n for (const child of newChildren) {\n if (child && child.tag === '#anchor') {\n const anchorChildren = Array.isArray(child.children)\n ? child.children\n : [];\n for (const anchorChild of anchorChildren) {\n // Extract the actual item key from the anchor key\n const actualKey = stripKeyPrefix(\n anchorChild.key ?? child.key ?? 'unknown',\n );\n flattenedNew.push({ ...anchorChild, key: actualKey });\n }\n } else if (child) {\n // Handle already-flattened children (from previous renders)\n flattenedNew.push({ ...child, key: stripKeyPrefix(child.key) });\n }\n }\n\n // Flatten old VNodes (extract from anchor blocks)\n for (const oldVNode of oldVNodes) {\n if (oldVNode && oldVNode.tag === '#anchor') {\n const anchorChildren = Array.isArray(oldVNode.children)\n ? oldVNode.children\n : [];\n for (const anchorChild of anchorChildren) {\n // Extract the actual item key from the anchor key\n const actualKey = stripKeyPrefix(\n anchorChild.key ?? oldVNode.key ?? 'unknown',\n );\n flattenedOldVNodes.push({ ...anchorChild, key: actualKey });\n }\n } else if (oldVNode) {\n // Handle already-flattened children (from previous renders)\n flattenedOldVNodes.push({\n ...oldVNode,\n key: stripKeyPrefix(oldVNode.key),\n });\n }\n }\n\n // Now perform keyed diffing on flattened lists\n const hasKeys =\n flattenedNew.some((c) => c && c.key != null) ||\n flattenedOldVNodes.some((c) => c && c.key != null);\n\n if (hasKeys) {\n // Build maps for keyed diffing\n const oldVNodeByKeyFlat = new Map<string | number, VNode>();\n const oldNodeByKeyFlat = new Map<string | number, Node>();\n\n for (const v of flattenedOldVNodes) {\n if (v && v.key != null) {\n // Ensure key is a string for consistent comparison\n const key = String(v.key);\n oldVNodeByKeyFlat.set(key, v);\n }\n }\n\n // Map old DOM nodes by their keys with dual mapping for numeric/string keys\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n\n // Try multiple ways to find the key (WeakMap-backed accessor + attribute fallback)\n let nodeKey = getNodeKey(node);\n // Strip \"each-\" prefix from node keys to match flattened VNode keys\n nodeKey = stripKeyPrefix(nodeKey);\n\n // Skip text nodes and comment nodes without keys\n if (\n nodeKey != null &&\n node instanceof Element &&\n node.nodeType === Node.ELEMENT_NODE\n ) {\n // Extract the base key (remove :tagname suffix if present)\n let baseKey =\n typeof nodeKey === 'string' && nodeKey.includes(':')\n ? nodeKey.substring(0, nodeKey.lastIndexOf(':'))\n : nodeKey;\n\n // Ensure key is a string for consistent comparison with VNode keys\n baseKey = String(baseKey);\n\n // Store with the base key (stripped of \"each-\" prefix to match VNode keys)\n oldNodeByKeyFlat.set(baseKey, node);\n }\n }\n\n const usedFlat = new Set<Node>();\n\n // PHASE 0: Record positions BEFORE any DOM modifications for FLIP animation\n // Only record if we have existing nodes to animate from\n const positionsBefore = new Map<Node, DOMRect>();\n const hadPreviousContent = oldNodesCache.length > 0;\n\n if (transitionGroup.moveClass && hadPreviousContent) {\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n if (node instanceof HTMLElement && node.parentElement) {\n const rect = node.getBoundingClientRect();\n // Record position even if dimensions are zero (test environments)\n positionsBefore.set(node, rect);\n }\n }\n }\n\n // PHASE 1: Identify which nodes to keep, create new nodes, but DON'T move anything yet\n const nodesToProcess: Array<{\n node: Node;\n key: string;\n newVNode: VNode;\n oldVNode?: VNode;\n isNew: boolean;\n }> = [];\n\n for (const newVNode of flattenedNew) {\n let key = newVNode.key;\n if (key == null) continue;\n\n // Ensure key is a string for consistent comparison\n key = String(key);\n\n const oldVNode = oldVNodeByKeyFlat.get(key);\n let node = oldNodeByKeyFlat.get(key);\n\n if (node && oldVNode) {\n // Existing node - patch it but don't move yet\n const patched = patch(node, oldVNode, newVNode, context);\n usedFlat.add(node);\n\n // Ensure the node has the correct key and attribute\n const keyStr = String(key);\n setNodeKey(patched, keyStr);\n\n nodesToProcess.push({\n node: patched,\n key,\n newVNode,\n oldVNode,\n isNew: false,\n });\n } else {\n // Create new node and insert it immediately (but invisible via enterFrom classes)\n node = createElement(newVNode, context);\n setNodeKey(node, String(key));\n\n // For new nodes, immediately insert them into DOM (at the end) and start enter transition\n // This ensures the transition can capture the correct FROM state\n parent.appendChild(node);\n\n // Only animate if: we had previous content to transition from OR appear is true\n // This prevents initial render items from animating (unless appear: true explicitly set)\n // but allows subsequent additions to animate\n const shouldAnimate =\n hadPreviousContent || transitionGroup.appear === true;\n\n if (node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transitionGroup).catch((err) => {\n devError('Enter transition error:', err);\n });\n }\n\n nodesToProcess.push({ node, key, newVNode, isNew: true });\n }\n }\n\n const leaveTransitions: Promise<void>[] = [];\n\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n const nodeKey = getNodeKey(node);\n const isUsed = usedFlat.has(node);\n\n if (!isUsed && nodeKey != null && node instanceof HTMLElement) {\n const leavePromise = performLeaveTransition(node, transitionGroup)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError('Leave transition error:', err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n leaveTransitions.push(leavePromise);\n }\n }\n\n // PHASE 3: Move nodes to correct positions and apply FLIP animations\n // SKIP if there are active leave transitions to prevent visual jumps\n if (leaveTransitions.length === 0) {\n // FLIP Animation for move transitions\n // Positions were already recorded in PHASE 0, now we just move and animate\n let currentPosition: Node | null = parent.firstChild;\n\n for (const { node } of nodesToProcess) {\n // Move node to correct position if needed\n if (node !== currentPosition) {\n parent.insertBefore(node, currentPosition);\n }\n currentPosition = node.nextSibling;\n }\n\n // Apply FLIP animation for moved items\n if (transitionGroup.moveClass && positionsBefore.size > 0) {\n // Collect elements that need to be animated\n const elementsToAnimate: Array<{\n node: HTMLElement;\n deltaX: number;\n deltaY: number;\n moveClasses: string[];\n }> = [];\n\n for (const { node, isNew } of nodesToProcess) {\n if (!isNew && node instanceof HTMLElement) {\n const oldPos = positionsBefore.get(node);\n if (oldPos) {\n const newPos = node.getBoundingClientRect();\n const deltaX = oldPos.left - newPos.left;\n const deltaY = oldPos.top - newPos.top;\n\n // If position changed, prepare for animation\n if (deltaX !== 0 || deltaY !== 0) {\n const moveClasses = transitionGroup.moveClass\n .split(/\\s+/)\n .filter((c: string) => c);\n elementsToAnimate.push({ node, deltaX, deltaY, moveClasses });\n }\n }\n }\n }\n\n if (elementsToAnimate.length > 0) {\n // FLIP Animation technique:\n // We need to ensure the browser paints the inverted state before animating\n // Step 1: Apply inverted transforms (without transition)\n for (const { node, deltaX, deltaY } of elementsToAnimate) {\n node.style.transform = `translate(${deltaX}px, ${deltaY}px)`;\n node.style.transitionProperty = 'none';\n }\n\n // Step 2: Force reflow to ensure transforms are applied\n void parent.offsetHeight;\n\n // Step 3: Use triple RAF to ensure browser has:\n // 1. Painted the inverted state\n // 2. Applied the transition classes\n // 3. Ready to animate when transform is removed\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n // Add moveClass for transition properties\n for (const { node, moveClasses } of elementsToAnimate) {\n for (const cls of moveClasses) {\n node.classList.add(cls);\n }\n }\n\n // One more RAF to ensure transition classes are processed\n requestAnimationFrame(() => {\n // Set transition directly on each element\n // Parse moveClass to extract duration and timing\n const moveClassStr = transitionGroup.moveClass || '';\n const durationMatch = moveClassStr.match(/duration-(\\d+)/);\n const duration = durationMatch\n ? `${durationMatch[1]}ms`\n : '300ms';\n const easingMatch = moveClassStr.match(\n /ease-(out|in|in-out|linear)/,\n );\n const easing = easingMatch\n ? `ease-${easingMatch[1]}`\n : 'ease-out';\n\n for (const { node } of elementsToAnimate) {\n // Set transition inline to override everything\n // This sets transition-property, transition-duration, and transition-timing-function\n node.style.transition = `transform ${duration} ${easing}`;\n }\n\n // One final RAF before removing transform\n requestAnimationFrame(() => {\n // Now remove transforms to trigger animation\n for (const { node, moveClasses } of elementsToAnimate) {\n node.style.removeProperty('transform');\n // Clean up moveClass after transition completes\n const cleanup = () => {\n for (const cls of moveClasses) {\n node.classList.remove(cls);\n }\n // Also remove the inline transition we set for move animation\n // This allows leave transitions to work properly\n node.style.removeProperty('transition');\n node.removeEventListener('transitionend', cleanup);\n node.removeEventListener('transitioncancel', cleanup);\n };\n node.addEventListener('transitionend', cleanup, {\n once: true,\n });\n node.addEventListener('transitioncancel', cleanup, {\n once: true,\n });\n }\n });\n });\n });\n });\n }\n }\n }\n\n return; // Done with TransitionGroup keyed diffing\n }\n }\n\n // Map old VNodes by key\n const oldVNodeByKey = new Map<string | number, VNode>();\n for (const v of oldVNodes) {\n if (v && v.key != null) oldVNodeByKey.set(v.key, v);\n }\n\n // Map DOM nodes by key (elements, text, anchors)\n const oldNodeByKey = new Map<string | number, Node>();\n\n // Scan DOM for keyed nodes including anchor boundaries\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n const k = getNodeKey(node);\n if (k != null) {\n oldNodeByKey.set(k, node);\n }\n }\n\n const usedNodes = new Set<Node>();\n let nextSibling: Node | null = parent.firstChild;\n\n function markRangeUsed(start: Comment, end?: Comment) {\n let cur: Node | null = start;\n while (cur) {\n usedNodes.add(cur);\n if (cur === end) break;\n cur = cur.nextSibling;\n }\n }\n\n function patchChildrenBetween(\n start: Comment,\n end: Comment,\n oldChildren: VNode[] | undefined,\n newChildren: VNode[],\n transition?: Transition | undefined,\n shouldAnimate = true,\n ) {\n const oldNodesInRange: Node[] = [];\n let cur: Node | null = start.nextSibling;\n while (cur && cur !== end) {\n oldNodesInRange.push(cur);\n cur = cur.nextSibling;\n }\n\n const oldVNodesInRange: VNode[] = Array.isArray(oldChildren)\n ? oldChildren\n : [];\n const hasKeys =\n newChildren.some((c) => c && c.key != null) ||\n oldVNodesInRange.some((c) => c && c.key != null);\n\n if (hasKeys) {\n // Keyed diff\n const oldVNodeByKeyRange = new Map<string | number, VNode>();\n const oldNodeByKeyRange = new Map<string | number, Node>();\n\n for (const v of oldVNodesInRange) {\n if (v && v.key != null) oldVNodeByKeyRange.set(v.key, v);\n }\n for (const node of oldNodesInRange) {\n const k = getNodeKey(node);\n if (k != null) oldNodeByKeyRange.set(k, node);\n }\n\n // Calculate if this is initial visible render (for appear transitions)\n const isInitialVisible =\n transition &&\n transition.state === 'visible' &&\n oldVNodesInRange.length === 0 &&\n newChildren.length > 0;\n\n const usedInRange = new Set<Node>();\n let next: Node | null = start.nextSibling;\n\n for (const newVNode of newChildren) {\n let node: Node;\n if (newVNode.key != null && oldNodeByKeyRange.has(newVNode.key)) {\n const oldVNode = oldVNodeByKeyRange.get(newVNode.key)!;\n node = patch(\n oldNodeByKeyRange.get(newVNode.key)!,\n oldVNode,\n newVNode,\n context,\n );\n usedInRange.add(node);\n\n // Apply enter transition to patched nodes if this is initial visible render with appear: true\n if (\n transition &&\n node instanceof HTMLElement &&\n isInitialVisible &&\n transition.appear\n ) {\n performEnterTransition(node, transition).catch((err) => {\n devError('Transition enter error (appear):', err);\n });\n }\n\n if (node !== next && parent.contains(node)) {\n parent.insertBefore(node, next);\n }\n } else {\n node = createElement(newVNode, context);\n parent.insertBefore(node, next);\n usedInRange.add(node);\n\n // Apply enter transition to new nodes ONLY if shouldAnimate is true\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transition).catch((err) => {\n devError('Transition enter error:', err);\n });\n }\n }\n next = node.nextSibling;\n }\n\n for (const node of oldNodesInRange) {\n if (!usedInRange.has(node) && parent.contains(node)) {\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n // Apply leave transition before removing\n performLeaveTransition(node, transition)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError('Transition leave error:', err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n } else {\n parent.removeChild(node);\n }\n }\n }\n } else {\n // Keyless: fall back to index-based patch\n const commonLength = Math.min(\n oldVNodesInRange.length,\n newChildren.length,\n );\n\n for (let i = 0; i < commonLength; i++) {\n const oldVNode = oldVNodesInRange[i];\n const newVNode = newChildren[i];\n const node = patch(oldNodesInRange[i], oldVNode, newVNode, context);\n if (node !== oldNodesInRange[i]) {\n parent.insertBefore(node, oldNodesInRange[i]);\n parent.removeChild(oldNodesInRange[i]);\n }\n }\n\n // Add extra new\n for (let i = commonLength; i < newChildren.length; i++) {\n const node = createElement(newChildren[i], context);\n parent.insertBefore(node, end);\n\n // Apply enter transition to new nodes ONLY if shouldAnimate is true\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n performEnterTransition(node, transition).catch((err) => {\n devError('Transition enter error:', err);\n });\n }\n }\n\n // Remove extra old\n for (let i = commonLength; i < oldNodesInRange.length; i++) {\n const node = oldNodesInRange[i];\n if (transition && node instanceof HTMLElement && shouldAnimate) {\n // Apply leave transition before removing\n performLeaveTransition(node, transition)\n .then(() => {\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n })\n .catch((err) => {\n devError('Transition leave error:', err);\n if (parent.contains(node)) {\n parent.removeChild(node);\n }\n });\n } else {\n parent.removeChild(node);\n }\n }\n }\n }\n\n for (const newVNode of newChildren) {\n let node: Node;\n\n // Handle AnchorBlocks\n if (newVNode.tag === '#anchor') {\n const aKey = newVNode.key!;\n const startKey = `${aKey}:start`;\n const endKey = `${aKey}:end`;\n\n let start = oldNodeByKey.get(startKey) as Node;\n let end = oldNodeByKey.get(endKey) as Node;\n const children = Array.isArray(newVNode.children)\n ? newVNode.children\n : [];\n\n // Create boundaries if they don't exist\n if (!start) {\n start = document.createTextNode('');\n setNodeKey(start, startKey);\n }\n if (!end) {\n end = document.createTextNode('');\n setNodeKey(end, endKey);\n }\n\n // Preserve anchor references on the new VNode\n (newVNode as AnchorBlockVNode)._startNode = start as Comment;\n (newVNode as AnchorBlockVNode)._endNode = end as Comment;\n\n // If boundaries aren't in DOM, insert the whole fragment\n if (!parent.contains(start) || !parent.contains(end)) {\n parent.insertBefore(start, nextSibling);\n const transition = (newVNode as VNode & Record<string, unknown>)\n ._transition as Transition | undefined;\n\n // Determine if we should animate:\n // - If transition.state === 'visible' and children.length > 0, this is initial visible state\n // → only animate if appear: true\n // - If transition.state === 'hidden' and children.length === 0, this is initial hidden state\n // → don't animate (nothing to animate)\n // - Otherwise, this is a state change → always animate\n const isInitialVisible =\n transition && transition.state === 'visible' && children.length > 0;\n const shouldAnimate = !isInitialVisible || transition.appear;\n\n for (const child of children) {\n const childNode = createElement(child, context);\n parent.insertBefore(childNode, nextSibling);\n\n // Apply enter transitions to new nodes ONLY if shouldAnimate is true\n if (transition && childNode instanceof HTMLElement) {\n if (shouldAnimate) {\n performEnterTransition(childNode, transition).catch((err) => {\n devError('Transition enter error:', err);\n });\n }\n }\n }\n parent.insertBefore(end, nextSibling);\n } else {\n // Patch children between existing boundaries\n const transition = (newVNode as VNode & Record<string, unknown>)\n ._transition as Transition | undefined;\n const oldVNode = oldVNodeByKey.get(aKey) as VNode;\n const oldTransition = (oldVNode as VNode & Record<string, unknown>)\n ._transition as Transition | undefined;\n\n // Determine if we should animate:\n // - If this is a state change (hidden → visible or visible → hidden), always animate\n // - If this is initial render with state='visible', only animate if appear: true\n const isStateChange =\n oldTransition && oldTransition.state !== transition?.state;\n const isInitialVisible =\n transition &&\n transition.state === 'visible' &&\n children.length > 0 &&\n !isStateChange;\n const shouldAnimate =\n isStateChange || !isInitialVisible || transition?.appear === true;\n\n patchChildrenBetween(\n start as Comment,\n end as Comment,\n (oldVNodeByKey.get(aKey) as VNode)?.children as VNode[] | undefined,\n children,\n transition,\n shouldAnimate,\n );\n }\n\n markRangeUsed(start as Comment, end as Comment);\n nextSibling = end.nextSibling;\n continue;\n }\n\n // Normal keyed element/text\n if (newVNode.key != null && oldNodeByKey.has(newVNode.key)) {\n const oldVNode = oldVNodeByKey.get(newVNode.key)!;\n node = patch(\n oldNodeByKey.get(newVNode.key)!,\n oldVNode,\n newVNode,\n context,\n refs,\n );\n usedNodes.add(node);\n if (node !== nextSibling && parent.contains(node)) {\n if (nextSibling && !parent.contains(nextSibling)) nextSibling = null;\n parent.insertBefore(node, nextSibling);\n }\n } else {\n node = createElement(newVNode, context, refs);\n if (nextSibling && !parent.contains(nextSibling)) nextSibling = null;\n parent.insertBefore(node, nextSibling);\n usedNodes.add(node);\n }\n\n nextSibling = node.nextSibling;\n }\n\n // Remove unused nodes (use cached array to avoid live NodeList issues)\n for (let i = 0; i < oldNodesCache.length; i++) {\n const node = oldNodesCache[i];\n if (!usedNodes.has(node) && parent.contains(node)) {\n cleanupRefs(node, refs);\n parent.removeChild(node);\n }\n }\n}\n\n/**\n * Patch a node using keys for node matching.\n * @param dom\n * @param oldVNode\n * @param newVNode\n * @param context\n * @param refs\n * @returns\n */\nexport function patch(\n dom: Node,\n oldVNode: VNode | string | null,\n newVNode: VNode | string | null,\n context?: Record<string, unknown>,\n refs?: VDomRefs,\n): Node {\n if (oldVNode && typeof oldVNode !== 'string' && oldVNode.props?.ref && refs) {\n cleanupRefs(dom, refs); // Clean up old ref and descendants\n }\n\n if (oldVNode === newVNode) return dom;\n\n if (typeof newVNode === 'string') {\n if (dom.nodeType === Node.TEXT_NODE) {\n if (dom.textContent !== newVNode) dom.textContent = newVNode;\n return dom;\n } else {\n const textNode = document.createTextNode(newVNode);\n dom.parentNode?.replaceChild(textNode, dom);\n return textNode;\n }\n }\n\n if (newVNode && typeof newVNode !== 'string' && newVNode.tag === '#anchor') {\n const anchorVNode = newVNode as AnchorBlockVNode;\n const children = Array.isArray(anchorVNode.children)\n ? anchorVNode.children\n : [];\n const start = anchorVNode._startNode ?? document.createTextNode('');\n const end = anchorVNode._endNode ?? document.createTextNode('');\n if (anchorVNode.key != null) {\n setNodeKey(start, `${anchorVNode.key}:start`);\n setNodeKey(end, `${anchorVNode.key}:end`);\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n for (const child of children) {\n const childNode = createElement(child, context);\n frag.appendChild(childNode);\n }\n frag.appendChild(end);\n dom.parentNode?.replaceChild(frag, dom);\n return start;\n }\n\n if (!newVNode) {\n cleanupRefs(dom, refs);\n const placeholder = document.createComment('removed');\n dom.parentNode?.replaceChild(placeholder, dom);\n return placeholder;\n }\n\n if (!oldVNode || typeof oldVNode === 'string') {\n cleanupRefs(dom, refs);\n const newEl = createElement(newVNode, context, refs);\n assignRef(newVNode, newEl as HTMLElement, refs);\n dom.parentNode?.replaceChild(newEl, dom);\n return newEl;\n }\n\n if (newVNode.tag === '#anchor') {\n const children = Array.isArray(newVNode.children) ? newVNode.children : [];\n const start =\n (newVNode as AnchorBlockVNode)._startNode ?? document.createTextNode('');\n const end =\n (newVNode as AnchorBlockVNode)._endNode ?? document.createTextNode('');\n\n if (newVNode.key != null) {\n setNodeKey(start, `${newVNode.key}:start`);\n setNodeKey(end, `${newVNode.key}:end`);\n }\n\n (newVNode as AnchorBlockVNode)._startNode = start as Comment;\n (newVNode as AnchorBlockVNode)._endNode = end as Comment;\n\n const frag = document.createDocumentFragment();\n frag.appendChild(start);\n for (const child of children) {\n frag.appendChild(createElement(child, context));\n }\n frag.appendChild(end);\n dom.parentNode?.replaceChild(frag, dom);\n return start;\n }\n\n if (\n typeof oldVNode !== 'string' &&\n typeof newVNode !== 'string' &&\n oldVNode.tag === newVNode.tag &&\n oldVNode.key === newVNode.key\n ) {\n const el = dom as HTMLElement;\n patchProps(el, oldVNode.props || {}, newVNode.props || {}, context);\n patchChildren(el, oldVNode.children, newVNode.children, context, refs); // <-- Pass refs\n assignRef(newVNode, el, refs);\n return el;\n }\n\n // If the tag matches but the key changed, prefer to patch in-place for\n // custom elements to avoid remounting their internals. This handles cases\n // where compiler promotion or key churn causes vnode keys to differ even\n // though the DOM element should remain the same instance.\n if (\n typeof oldVNode !== 'string' &&\n typeof newVNode !== 'string' &&\n oldVNode.tag === newVNode.tag\n ) {\n const isCustomTag =\n (oldVNode.tag && String(oldVNode.tag).includes('-')) ||\n (newVNode.props && (newVNode.props as VNodePropBag).isCustomElement) ||\n (oldVNode.props && (oldVNode.props as VNodePropBag).isCustomElement);\n if (isCustomTag) {\n try {\n const el = dom as HTMLElement;\n patchProps(el, oldVNode.props || {}, newVNode.props || {}, context);\n // For custom elements, their internal rendering is managed by the\n // element itself; do not touch children here.\n assignRef(newVNode, el, refs);\n return el;\n } catch {\n // fall through to full replace on error\n }\n }\n }\n\n cleanupRefs(dom, refs);\n const newEl = createElement(newVNode, context, refs);\n assignRef(newVNode, newEl as HTMLElement, refs);\n dom.parentNode?.replaceChild(newEl, dom);\n return newEl;\n}\n\n/**\n * Virtual DOM renderer.\n * @param root The root element to render into.\n * @param vnodeOrArray The virtual node or array of virtual nodes to render.\n * @param context The context to use for rendering.\n * @param refs The refs to use for rendering.\n */\nexport function vdomRenderer(\n root: ShadowRoot,\n vnodeOrArray: VNode | VNode[],\n context?: Record<string, unknown>,\n refs?: VDomRefs,\n) {\n let newVNode: VNode;\n if (Array.isArray(vnodeOrArray)) {\n if (vnodeOrArray.length === 1) {\n newVNode = vnodeOrArray[0];\n if (newVNode && typeof newVNode === 'object' && newVNode.key == null) {\n newVNode = { ...newVNode, key: '__root__' };\n }\n } else {\n newVNode = { tag: 'div', key: '__root__', children: vnodeOrArray };\n }\n } else {\n newVNode = vnodeOrArray;\n if (newVNode && typeof newVNode === 'object' && newVNode.key == null) {\n newVNode = { ...newVNode, key: '__root__' };\n }\n }\n\n // If the root is an AnchorBlock, wrap it in a real element for DOM insertion\n if (newVNode && typeof newVNode === 'object' && newVNode.tag === '#anchor') {\n newVNode = {\n tag: 'div',\n key: '__anchor_root__',\n props: {\n attrs: { 'data-anchor-block-root': '', key: '__anchor_root__' },\n },\n children: [newVNode],\n };\n }\n\n newVNode = assignKeysDeep(newVNode, String(newVNode.key ?? 'root')) as VNode;\n\n // Track previous VNode and DOM node\n const prevVNode: VNode | null =\n ((root as unknown as Record<string, unknown>)._prevVNode as VNode | null) ??\n null;\n const prevDom: Node | null =\n ((root as unknown as Record<string, unknown>)._prevDom as Node | null) ??\n root.firstChild ??\n null;\n\n let newDom: Node;\n\n if (prevVNode && prevDom) {\n // Only replace if tag or key changed\n if (\n typeof prevVNode !== 'string' &&\n typeof newVNode !== 'string' &&\n prevVNode.tag === newVNode.tag &&\n prevVNode.key === newVNode.key\n ) {\n newDom = patch(prevDom, prevVNode, newVNode, context, refs);\n } else {\n newDom = createElement(newVNode, context, refs);\n root.replaceChild(newDom, prevDom);\n }\n } else {\n newDom = createElement(newVNode, context, refs);\n if (root.firstChild) root.replaceChild(newDom, root.firstChild);\n else root.appendChild(newDom);\n }\n\n // Remove any extra nodes, but preserve style elements\n const nodesToRemove: Node[] = [];\n for (let i = 0; i < root.childNodes.length; i++) {\n const node = root.childNodes[i];\n if (node !== newDom && node.nodeName !== 'STYLE') {\n cleanupRefs(node, refs);\n nodesToRemove.push(node);\n }\n }\n nodesToRemove.forEach((node) => root.removeChild(node));\n\n // Update tracked VNode and DOM node\n (root as unknown as Record<string, unknown>)._prevVNode = newVNode as unknown;\n (root as unknown as Record<string, unknown>)._prevDom = newDom as unknown;\n}\n","import { vdomRenderer } from './vdom';\nimport { minifyCSS, getBaseResetSheet, sanitizeCSS, jitCSS } from './style';\nimport { getTransitionStyleSheet } from '../transitions';\nimport type { ComponentConfig, ComponentContext, VNode, Refs } from './types';\nimport { devWarn, devError } from './logger';\n\n// Module-level stack for context injection (scoped to render cycle, no global pollution)\nexport const contextStack: unknown[] = [];\n\n/**\n * Renders the component output.\n */\nexport function renderComponent<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n shadowRoot: ShadowRoot | null,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>,\n refs: Refs['refs'],\n setHtmlString: (html: string) => void,\n setLoading: (val: boolean) => void,\n setError: (err: Error | null) => void,\n applyStyle: (html: string) => void,\n): void {\n if (!shadowRoot) return;\n\n // Push context to stack before rendering\n contextStack.push(context);\n\n try {\n // Loading and error states are now handled directly in the functional components\n // rather than through config templates\n\n const outputOrPromise = cfg.render(context);\n\n if (outputOrPromise instanceof Promise) {\n setLoading(true);\n outputOrPromise\n .then((output) => {\n setLoading(false);\n setError(null);\n renderOutput(shadowRoot, output, context, refs, setHtmlString);\n applyStyle(shadowRoot.innerHTML);\n })\n .catch((error) => {\n setLoading(false);\n setError(error);\n // Error handling is now done in the functional components directly\n });\n\n // Loading state is now handled in the functional components directly\n return;\n }\n\n renderOutput(shadowRoot, outputOrPromise, context, refs, setHtmlString);\n applyStyle(shadowRoot.innerHTML);\n } finally {\n // Always pop context from stack after rendering (ensures cleanup even on errors)\n contextStack.pop();\n }\n}\n\n/**\n * Renders VNode(s) to the shadowRoot.\n */\nexport function renderOutput<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n shadowRoot: ShadowRoot | null,\n output: VNode | VNode[],\n context: ComponentContext<S, C, P, T>,\n refs: Refs['refs'],\n setHtmlString: (html: string) => void,\n): void {\n if (!shadowRoot) return;\n vdomRenderer(\n shadowRoot,\n Array.isArray(output) ? output : [output],\n context,\n refs,\n );\n setHtmlString(shadowRoot.innerHTML);\n}\n\n/**\n * Debounced render request with infinite loop protection.\n */\nexport function requestRender(\n renderFn: () => void,\n lastRenderTime: number,\n renderCount: number,\n setLastRenderTime: (t: number) => void,\n setRenderCount: (c: number) => void,\n renderTimeoutId: ReturnType<typeof setTimeout> | null,\n setRenderTimeoutId: (id: ReturnType<typeof setTimeout> | null) => void,\n): void {\n if (renderTimeoutId !== null) clearTimeout(renderTimeoutId);\n\n const now = Date.now();\n const isRapidRender = now - lastRenderTime < 16;\n\n if (isRapidRender) {\n setRenderCount(renderCount + 1);\n // Progressive warnings and limits\n if (renderCount === 15) {\n devWarn(\n '⚠️ Component is re-rendering rapidly. This might indicate:\\n' +\n ' Common causes:\\n' +\n ' • Event handler calling a function immediately: @click=\"${fn()}\" should be @click=\"${fn}\"\\n' +\n ' • State modification during render\\n' +\n ' • Missing dependencies in computed/watch\\n' +\n ' Component rendering will be throttled to prevent browser freeze.',\n );\n } else if (renderCount > 20) {\n // More aggressive limit for severe infinite loops\n devError(\n '🛑 Infinite loop detected in component render:\\n' +\n ' • This might be caused by state updates during render\\n' +\n ' • Ensure all state modifications are done in event handlers or effects\\n' +\n 'Stopping runaway component render to prevent browser freeze',\n );\n setRenderTimeoutId(null);\n return;\n }\n } else {\n setRenderCount(0);\n }\n\n const timeoutId = setTimeout(\n () => {\n setLastRenderTime(Date.now());\n renderFn();\n setRenderTimeoutId(null);\n },\n renderCount > 10 ? 100 : 0,\n ); // Add delay for rapid renders\n setRenderTimeoutId(timeoutId);\n}\n\n/**\n * Applies styles to the shadowRoot.\n */\nexport function applyStyle<\n S extends object,\n C extends object,\n P extends object,\n T extends object,\n>(\n shadowRoot: ShadowRoot | null,\n context: ComponentContext<S, C, P, T>,\n htmlString: string,\n styleSheet: CSSStyleSheet | null,\n setStyleSheet: (sheet: CSSStyleSheet | null) => void,\n): void {\n if (!shadowRoot) return;\n\n // Include rendered HTML from child component instances (if available)\n // so JIT CSS can find utility classes rendered inside child shadow DOM.\n let aggregatedHtml = htmlString || '';\n try {\n if (shadowRoot) {\n const allEls = Array.from(\n shadowRoot.querySelectorAll('*'),\n ) as HTMLElement[];\n for (const el of allEls) {\n try {\n const childHtml = (el as { lastHtmlStringForJitCSS?: string })\n .lastHtmlStringForJitCSS;\n if (childHtml && typeof childHtml === 'string' && childHtml.trim()) {\n aggregatedHtml += '\\n' + childHtml;\n }\n } catch {\n // best-effort: ignore errors while reading child's cached HTML\n }\n }\n }\n } catch {\n void 0;\n }\n\n const jitCss = jitCSS(aggregatedHtml);\n\n if (\n (!jitCss || jitCss.trim() === '') &&\n !(context as { _computedStyle?: string })._computedStyle\n ) {\n setStyleSheet(null);\n shadowRoot.adoptedStyleSheets = [\n getBaseResetSheet(),\n getTransitionStyleSheet(),\n ];\n return;\n }\n\n let userStyle = '';\n\n // Check for precomputed style from useStyle hook\n if ((context as { _computedStyle?: string })._computedStyle) {\n userStyle = (context as { _computedStyle?: string })._computedStyle ?? '';\n }\n\n let finalStyle = sanitizeCSS(`${userStyle}\\n${jitCss}\\n`);\n finalStyle = minifyCSS(finalStyle);\n\n let sheet = styleSheet;\n if (!sheet) sheet = new CSSStyleSheet();\n\n // Compare by replacing the stylesheet entirely if rules changed\n // Avoid using .toString() which may not be reliable across browsers\n const needsUpdate =\n sheet.cssRules.length === 0 ||\n (sheet.cssRules.length > 0 &&\n Array.from(sheet.cssRules)\n .map((r) => r.cssText)\n .join('') !== finalStyle);\n\n if (needsUpdate) {\n sheet.replaceSync(finalStyle);\n }\n\n shadowRoot.adoptedStyleSheets = [\n getBaseResetSheet(),\n getTransitionStyleSheet(),\n sheet,\n ];\n setStyleSheet(sheet);\n}\n","/**\n * Context-based hooks for functional components\n * Provides React-like hooks with perfect TypeScript inference\n */\n\n// Global state to track current component context during render\n// Narrowed internal type for currentComponentContext to expose _hookCallbacks\ninterface InternalHookCallbacks {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) => void;\n onError?: (err: unknown) => void;\n props?: Record<string, unknown>;\n style?: () => string;\n}\n\ntype InternalComponentContext = Record<string, unknown> & {\n _hookCallbacks?: InternalHookCallbacks;\n _computedStyle?: string;\n};\n\nlet currentComponentContext: InternalComponentContext | null = null;\nimport { isReactiveState } from './reactive';\nimport { toKebab } from './helpers';\nimport { devWarn } from './logger';\n\n/**\n * Set the current component context (called internally during render)\n * @internal\n */\nexport function setCurrentComponentContext(\n context: Record<string, unknown>,\n): void {\n currentComponentContext = context;\n}\n\n/**\n * Clear the current component context (called internally after render)\n * @internal\n */\nexport function clearCurrentComponentContext(): void {\n currentComponentContext = null;\n}\n\n/**\n * Get the emit function for the current component\n * Must be called during component render\n *\n * @example\n * ```ts\n * component('my-button', () => {\n * const { label } = useProps({ label: 'Click me' });\n * const emit = useEmit();\n *\n * return html`\n * <button @click=\"${() => emit('button-click', { label })}\">\n * ${label}\n * </button>\n * `;\n * });\n * ```\n */\nexport function useEmit(): (\n eventName: string,\n detail?: unknown,\n options?: CustomEventInit,\n) => boolean {\n if (!currentComponentContext) {\n throw new Error('useEmit must be called during component render');\n }\n\n // Capture and validate the emit function from the current context\n const emitCandidate = (currentComponentContext as { emit?: unknown }).emit;\n if (typeof emitCandidate !== 'function') {\n throw new Error(\n 'useEmit requires an emit function on the component context',\n );\n }\n const emitFn = emitCandidate as (\n eventName: string,\n detail?: unknown,\n options?: CustomEventInit,\n ) => boolean;\n\n return (eventName: string, detail?: unknown, options?: CustomEventInit) => {\n return emitFn(eventName, detail, options);\n };\n}\n\n/**\n * Initialize hook callbacks storage on context if not exists\n * Uses Object.defineProperty to avoid triggering reactive updates\n */\nfunction ensureHookCallbacks(context: Record<string, unknown>): void {\n if (!context._hookCallbacks) {\n Object.defineProperty(context, '_hookCallbacks', {\n value: {},\n writable: true,\n enumerable: false,\n configurable: false,\n });\n }\n}\n\n/**\n * Register a callback to be called when component is connected to DOM\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnConnected(() => {\n * console.log('Component mounted!');\n * });\n *\n * return html`<div>Hello World</div>`;\n * });\n * ```\n */\nexport function useOnConnected(callback: () => void): void {\n if (!currentComponentContext) {\n throw new Error('useOnConnected must be called during component render');\n }\n\n ensureHookCallbacks(currentComponentContext as InternalComponentContext);\n // currentComponentContext._hookCallbacks is typed via ensureHookCallbacks\n (\n currentComponentContext._hookCallbacks as InternalHookCallbacks\n ).onConnected = callback;\n}\n\n/**\n * Register a callback to be called when component is disconnected from DOM\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnDisconnected(() => {\n * console.log('Component unmounted!');\n * });\n *\n * return html`<div>Goodbye World</div>`;\n * });\n * ```\n */\nexport function useOnDisconnected(callback: () => void): void {\n if (!currentComponentContext) {\n throw new Error('useOnDisconnected must be called during component render');\n }\n\n ensureHookCallbacks(currentComponentContext as InternalComponentContext);\n (\n currentComponentContext._hookCallbacks as InternalHookCallbacks\n ).onDisconnected = callback;\n}\n\n/**\n * Register a callback to be called when an attribute changes\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnAttributeChanged((name, oldValue, newValue) => {\n * console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`);\n * });\n *\n * return html`<div>Attribute watcher</div>`;\n * });\n * ```\n */\nexport function useOnAttributeChanged(\n callback: (\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) => void,\n): void {\n if (!currentComponentContext) {\n throw new Error(\n 'useOnAttributeChanged must be called during component render',\n );\n }\n\n ensureHookCallbacks(currentComponentContext as InternalComponentContext);\n (\n currentComponentContext._hookCallbacks as InternalHookCallbacks\n ).onAttributeChanged = callback;\n}\n\n/**\n * Register a callback to be called when an error occurs\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * useOnError((error) => {\n * console.error('Component error:', error);\n * });\n *\n * return html`<div>Error handler</div>`;\n * });\n * ```\n */\nexport function useOnError(callback: (error: Error) => void): void {\n if (!currentComponentContext) {\n throw new Error('useOnError must be called during component render');\n }\n\n ensureHookCallbacks(currentComponentContext as InternalComponentContext);\n // Accept unknown error types from runtime and forward to user-provided Error handler when possible\n (currentComponentContext._hookCallbacks as InternalHookCallbacks).onError = (\n err: unknown,\n ) => {\n try {\n if (err instanceof Error) callback(err);\n else callback(new Error(String(err)));\n } catch {\n /* swallow */\n }\n };\n}\n\n/**\n * Register prop defaults for the component. Can be called during render.\n * Stores the prop defaults on `context._hookCallbacks.props` so the runtime\n * can pick them up when building the component config.\n *\n * Example:\n * ```ts\n * component('my-comp', () => {\n * useProps({ modelValue: false, label: 'Hello' });\n * return html`<div/>`;\n * });\n * ```\n */\nexport function useProps<T extends Record<string, unknown>>(defaults: T): T {\n if (!currentComponentContext) {\n throw new Error('useProps must be called during component render');\n }\n\n ensureHookCallbacks(currentComponentContext as InternalComponentContext);\n const hooks = currentComponentContext._hookCallbacks as InternalHookCallbacks;\n hooks.props = {\n ...(hooks.props || {}),\n ...defaults,\n };\n\n const ctx = currentComponentContext;\n // Define dynamic getters for declared props so the context property\n // always reflects the host element's property (or reactive ref.value)\n try {\n const declaredKeys = Object.keys(defaults || {});\n for (const key of declaredKeys) {\n if (typeof key !== 'string' || key.startsWith('_')) continue;\n const existing = Object.getOwnPropertyDescriptor(ctx, key);\n // Only define if not present or configurable (allow overriding)\n if (existing && !existing.configurable) continue;\n try {\n // Preserve any existing concrete value on the context in a closure.\n // This avoids recursive getters when we later reference ctx[key].\n const hasOwn = Object.prototype.hasOwnProperty.call(ctx, key);\n let localValue: unknown = hasOwn\n ? (ctx as Record<string, unknown>)[key]\n : undefined;\n\n Object.defineProperty(ctx, key, {\n configurable: true,\n enumerable: true,\n get() {\n try {\n const host = (ctx && (ctx as { _host?: HTMLElement })._host) as\n | HTMLElement\n | undefined;\n if (host) {\n // First, check for attribute value (attributes should take precedence)\n const kebabKey = toKebab(key);\n const attrValue = host.getAttribute(kebabKey);\n if (attrValue !== null) {\n const defaultType = typeof defaults[key];\n if (defaultType === 'boolean') {\n // Standalone boolean attributes have empty string value\n return attrValue === '' || attrValue === 'true';\n }\n if (defaultType === 'number') {\n return Number(attrValue);\n }\n return attrValue;\n }\n\n // If no attribute, check if host has a property value set\n if (\n typeof (host as unknown as Record<string, unknown>)[key] !==\n 'undefined'\n ) {\n const fromHost = (host as unknown as Record<string, unknown>)[\n key\n ];\n // prefer host value when present\n // If the host provided a ReactiveState instance or a wrapper\n // with a .value, unwrap it here so destructured props and\n // useProps return the primitive/current value consistently.\n if (isReactiveState(fromHost)) {\n return (fromHost as { value: unknown }).value;\n }\n if (\n fromHost &&\n typeof fromHost === 'object' &&\n 'value' in fromHost &&\n !(fromHost instanceof Node)\n ) {\n return (fromHost as { value?: unknown }).value;\n }\n // For string-typed declared props, avoid returning host\n // object-like properties (for example `element.style` which\n // is a CSSStyleDeclaration). Prefer attribute value or the\n // local default instead of returning a non-primitive host\n // property into templates which expect primitives.\n const defaultType = typeof defaults[key];\n if (\n defaultType === 'string' &&\n fromHost &&\n typeof fromHost === 'object'\n ) {\n // fallthrough to localValue\n } else {\n // For boolean defaults, treat empty string (standalone attribute) or 'true' as true.\n if (\n defaultType === 'boolean' &&\n typeof fromHost === 'string'\n ) {\n return fromHost === '' || fromHost === 'true';\n }\n return fromHost;\n }\n }\n }\n } catch {\n // ignore host read failures and fall back to context\n }\n return localValue;\n },\n set(v: unknown) {\n // allow test/runtime code to set context props during render/init\n localValue = v;\n },\n });\n } catch {\n // ignore\n }\n }\n } catch {\n // ignore\n }\n // Return a Proxy that always reads the latest value from the component\n // context so accesses are reactive. Also unwrap functional refs ({ value })\n // and coerce string attribute values to boolean/number when defaults\n // indicate such types.\n const result = new Proxy({} as Record<string, unknown>, {\n get(_target, prop: string) {\n if (typeof prop !== 'string') return undefined;\n const def = (defaults as Record<string, unknown>)[prop];\n\n // If a host element is available, prefer reading from attributes first,\n // then from properties. This ensures that HTML attributes take precedence\n // over default property values (like the standard \"title\" attribute).\n try {\n const host = (ctx && (ctx as { _host?: HTMLElement })._host) as\n | HTMLElement\n | undefined;\n if (host) {\n // Check attribute first (only if host is an actual HTMLElement)\n if (\n host instanceof HTMLElement ||\n (typeof (host as { getAttribute?: (name: string) => string | null })\n .getAttribute === 'function' &&\n typeof (host as { hasAttribute?: (name: string) => boolean })\n .hasAttribute === 'function')\n ) {\n const kebabKey = prop.replace(/([A-Z])/g, '-$1').toLowerCase();\n const attrValue = (\n host as { getAttribute: (name: string) => string | null }\n ).getAttribute(kebabKey);\n if (attrValue !== null) {\n // Attribute exists - convert based on default type\n if (typeof def === 'boolean') {\n return attrValue === '' || attrValue === 'true';\n }\n if (typeof def === 'number') {\n return Number(attrValue);\n }\n return attrValue;\n }\n }\n\n // No attribute - check property value\n const hostValue = (host as unknown as Record<string, unknown>)[prop];\n // Only use host value if it's explicitly set (not undefined AND not empty string for string defaults)\n // Empty strings on standard HTML properties (like 'title') should fall through to defaults\n if (typeof hostValue !== 'undefined' && hostValue !== '') {\n // If the declared default is a string, avoid returning raw DOM\n // object-like properties (such as element.style which is a CSSStyleDeclaration)\n // since templates expect primitives and serializing objects can\n // cause DOMExceptions. However, wrapper-like objects that expose\n // a `.value` property (or ReactiveState instances) should be\n // unwrapped and returned even for string defaults.\n const isWrapperLike =\n hostValue &&\n typeof hostValue === 'object' &&\n 'value' in hostValue &&\n !(hostValue instanceof Node);\n if (\n typeof def === 'string' &&\n hostValue &&\n typeof hostValue === 'object' &&\n !isWrapperLike &&\n !isReactiveState(hostValue)\n ) {\n // treat as not present and fall through to ctx/default\n } else {\n // Special handling for boolean props: if default is false and hostValue is empty string,\n // treat it as if the property wasn't set (use default false)\n if (\n typeof def === 'boolean' &&\n def === false &&\n hostValue === ''\n ) {\n return def;\n }\n\n // Unwrap ReactiveState instances and wrapper-like objects coming\n // from the host so useProps mirrors applyProps/destructured props\n // behavior and returns primitive/current values.\n if (isReactiveState(hostValue)) {\n return (hostValue as { value: unknown }).value;\n }\n if (isWrapperLike) {\n return (hostValue as { value: unknown }).value;\n }\n\n // Primitive on host - return directly (but coerce strings if default provided)\n if (typeof def === 'boolean' && typeof hostValue === 'string') {\n // For boolean attributes, only explicit 'true' string or non-empty presence means true\n return (\n hostValue === 'true' ||\n (hostValue !== '' && hostValue !== 'false')\n );\n }\n if (\n typeof def === 'number' &&\n typeof hostValue === 'string' &&\n !Number.isNaN(Number(hostValue))\n )\n return Number(hostValue);\n return hostValue;\n }\n }\n }\n } catch {\n // ignore host read failures and fall back to context\n }\n\n // Fall back to reading from the component context itself.\n const raw = ctx[prop];\n // Treat empty-string on context as boolean true (attribute presence)\n // EXCEPT when the default is false - in that case, empty string means \"not set\"\n if (typeof def === 'boolean' && raw === '') {\n if (def === false) {\n // For boolean props with default false, empty string means use the default\n return def;\n }\n // For boolean props with default true, empty string means attribute presence = true\n return true;\n }\n // If the context stores a ReactiveState or wrapper, unwrap it here\n // so components using useProps receive the primitive/current value\n // when the source is the component context itself. Host-provided\n // ReactiveState instances are preserved above; this path is only\n // for ctx values and defaults.\n if (isReactiveState(raw)) return (raw as { value: unknown }).value;\n if (\n raw &&\n typeof raw === 'object' &&\n 'value' in raw &&\n !(raw instanceof Node)\n )\n return (raw as { value: unknown }).value;\n if (raw != null && raw !== '') {\n if (typeof def === 'boolean' && typeof raw === 'string') {\n return raw === 'true';\n }\n if (\n typeof def === 'number' &&\n typeof raw === 'string' &&\n !Number.isNaN(Number(raw))\n )\n return Number(raw);\n return raw;\n }\n return def;\n },\n has(_target, prop: string) {\n return typeof prop === 'string' && (prop in ctx || prop in defaults);\n },\n ownKeys() {\n return Array.from(\n new Set([...Object.keys(defaults), ...Object.keys(ctx || {})]),\n );\n },\n getOwnPropertyDescriptor() {\n return { configurable: true, enumerable: true } as PropertyDescriptor;\n },\n });\n\n return result as T;\n}\n\n/**\n * Register prop defaults and return a stable props object for use inside render.\n * The returned object reads values from the current component context at render\n * time and falls back to the provided defaults. This keeps prop access stable\n * in production builds and avoids reliance on parsing the render function.\n *\n * Must be called during render. Example:\n * const props = useProps({ modelValue: false });\n */\n// (useProps now returns the props object directly)\n\n/**\n * Register a style function that will be called during each render\n * to provide reactive styles for the component\n *\n * @example\n * ```ts\n * import { css } from '@lib/style';\n *\n * component('my-component', () => {\n * const { theme } = useProps({ theme: 'light' });\n *\n * useStyle(() => css`\n * :host {\n * background: ${theme === 'light' ? 'white' : 'black'};\n * color: ${theme === 'light' ? 'black' : 'white'};\n * }\n * `);\n *\n * return html`<div>Styled component</div>`;\n * });\n * ```\n */\nexport function useStyle(callback: () => string): void {\n if (!currentComponentContext) {\n throw new Error('useStyle must be called during component render');\n }\n\n ensureHookCallbacks(currentComponentContext);\n\n // Execute the callback immediately during render to capture the current style\n // This ensures reactive state is read during the render phase, not during style application\n try {\n const computedStyle = callback();\n\n // Store the computed style using Object.defineProperty to avoid triggering reactive updates\n Object.defineProperty(currentComponentContext, '_computedStyle', {\n value: computedStyle,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n } catch (error) {\n devWarn('Error in useStyle callback:', error);\n Object.defineProperty(currentComponentContext, '_computedStyle', {\n value: '',\n writable: true,\n enumerable: false,\n configurable: true,\n });\n }\n}\n","import type {\n ComponentConfig,\n ComponentContext,\n Refs,\n WatcherState,\n VNode,\n} from './types';\nimport { reactiveSystem, isReactiveState } from './reactive';\nimport { toKebab, safe } from './helpers';\nimport { initWatchers, triggerWatchers } from './watchers';\nimport { applyProps } from './props';\nimport {\n handleConnected,\n handleDisconnected,\n handleAttributeChanged,\n} from './lifecycle';\nimport { renderComponent, requestRender, applyStyle } from './render';\nimport { scheduleDOMUpdate } from './scheduler';\nimport {\n setCurrentComponentContext,\n clearCurrentComponentContext,\n} from './hooks';\nimport { devError, devWarn } from './logger';\n\n// Interface for custom element with framework-specific properties\ninterface CustomElement extends HTMLElement {\n _cfg?: ComponentConfig<object, object, object>;\n _render?: (config: ComponentConfig<object, object, object>) => void;\n onLoadingStateChange?: (loading: boolean) => void;\n onErrorStateChange?: (error: Error | null) => void;\n}\n\n/**\n * @internal\n * Runtime registry of component configs.\n * NOTE: This is an internal implementation detail. Do not import from the\n * published package in consumer code — it is intended for runtime/HMR and\n * internal tests only. Consumers should use the public `component` API.\n */\nexport const registry = new Map<\n string,\n ComponentConfig<object, object, object>\n>();\n\n// Expose the registry for browser/HMR use without overwriting existing globals\n// (avoid cross-request mutation in SSR and preserve HMR behavior).\nconst GLOBAL_REG_KEY = Symbol.for('cer.registry');\n\n/**\n * Lazily initialize the global registry slot. This avoids performing a\n * write to globalThis at module-import time (which is a side-effect that\n * prevents bundlers from tree-shaking). Call this from entry points that\n * actually need the registry (for example `component()`) so the module\n * remains import-side-effect-free.\n */\nfunction initGlobalRegistryIfNeeded(): void {\n if (typeof window !== 'undefined') {\n const g = globalThis as Record<string | symbol, unknown>;\n if (!g[GLOBAL_REG_KEY]) g[GLOBAL_REG_KEY] = registry;\n }\n}\n\n// --- Hot Module Replacement (HMR) ---\nif (\n typeof import.meta !== 'undefined' &&\n (\n import.meta as {\n hot?: { accept: (fn: (newModule?: unknown) => void) => void };\n }\n ).hot &&\n import.meta &&\n import.meta.hot\n) {\n import.meta.hot.accept((newModule) => {\n // Update registry with new configs from the hot module\n if (newModule && newModule.registry) {\n for (const [tag, newConfig] of newModule.registry.entries()) {\n registry.set(tag, newConfig);\n // Update all instances to use new config\n if (typeof document !== 'undefined') {\n document.querySelectorAll(tag).forEach((el) => {\n const customEl = el as CustomElement;\n if (typeof customEl._cfg !== 'undefined') {\n customEl._cfg = newConfig;\n }\n // HMR: Preserve existing state by keeping the context object intact.\n // Instead of re-executing the component function (which would create new refs),\n // we just update the config and re-render with the existing context.\n // This ensures refs and other reactive state are preserved across HMR updates.\n if (typeof customEl._render === 'function') {\n customEl._render(newConfig);\n }\n });\n }\n }\n }\n });\n}\n\nexport function createElementClass<\n S extends object,\n C extends object,\n P extends object,\n T extends object = object,\n>(\n tag: string,\n config: ComponentConfig<S, C, P, T>,\n): CustomElementConstructor | { new (): object } {\n // Validate that render is provided\n if (!config.render) {\n throw new Error('Component must have a render function');\n }\n if (typeof window === 'undefined') {\n // SSR fallback: minimal class, no DOM, no lifecycle, no \"this\"\n return class {\n constructor() {}\n };\n }\n return class extends HTMLElement {\n public context: ComponentContext<S, C, P, T>;\n private _refs: Refs['refs'] = {};\n private _listeners: Array<() => void> = [];\n private _watchers: Map<string, WatcherState> = new Map();\n /** @internal */\n private _renderTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private _mounted = false;\n private _hasError = false;\n private _initializing = true;\n\n private _componentId: string;\n\n private _styleSheet: CSSStyleSheet | null = null;\n\n private _lastHtmlStringForJitCSS = '';\n\n /**\n * Returns the last rendered HTML string for JIT CSS.\n */\n public get lastHtmlStringForJitCSS(): string {\n return this._lastHtmlStringForJitCSS;\n }\n\n /**\n * Returns true if the component is currently loading.\n */\n public get isLoading(): boolean {\n return this._templateLoading;\n }\n\n /**\n * Returns the last error thrown during rendering, or null if none.\n */\n public get lastError(): Error | null {\n return this._templateError;\n }\n\n private _cfg: ComponentConfig<S, C, P, T>;\n private _lastRenderTime = 0;\n private _renderCount = 0;\n private _templateLoading = false;\n private _templateError: Error | null = null;\n\n constructor() {\n super();\n this.attachShadow({ mode: 'open' });\n // Always read the latest config from the registry so re-registration\n // (HMR / tests) updates future instances.\n this._cfg = (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n\n // Generate unique component ID for render deduplication\n this._componentId = `${tag}-${Math.random().toString(36).substr(2, 9)}`;\n\n const reactiveContext = this._initContext(config);\n\n // Helper to define non-enumerable properties\n const defineNonEnum = (\n obj: Record<string, unknown>,\n key: string,\n value: unknown,\n ) => {\n Object.defineProperty(obj, key, {\n value,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n };\n\n // Inject refs into context (non-enumerable to avoid proxy traps)\n defineNonEnum(reactiveContext, 'refs', this._refs);\n defineNonEnum(reactiveContext, 'requestRender', () =>\n this.requestRender(),\n );\n defineNonEnum(reactiveContext, '_requestRender', () =>\n this._requestRender(),\n );\n defineNonEnum(reactiveContext, '_componentId', this._componentId);\n defineNonEnum(\n reactiveContext,\n '_triggerWatchers',\n (path: string, newValue: unknown) =>\n this._triggerWatchers(path, newValue),\n );\n\n // --- Apply props BEFORE wiring listeners and emit ---\n this.context = reactiveContext;\n // Expose host element on the reactive context so hooks like useProps\n // can fallback to reading element properties when attributes were\n // serialized (e.g., objects became \"[object Object]\"). This is added\n // as a non-enumerable field to avoid interfering with reactive proxy.\n safe(() => {\n defineNonEnum(reactiveContext, '_host', this);\n });\n // Defer applying props until connectedCallback so attributes that are\n // set by the parent renderer (after element construction) are available.\n // applyProps will still be invoked from attributeChangedCallback when\n // attributes are set; connectedCallback will call it as a final step to\n // ensure defaults are applied when no attributes are present.\n\n // Inject emit helper for custom events (single canonical event API).\n // Emits a DOM CustomEvent and returns whether it was not defaultPrevented.\n defineNonEnum(\n this.context,\n 'emit',\n (eventName: string, detail?: unknown, options?: CustomEventInit) => {\n const eventOptions = {\n detail,\n bubbles: true,\n composed: true,\n ...(options || {}),\n };\n const ev = new CustomEvent(eventName, eventOptions);\n\n // Primary event dispatch\n this.dispatchEvent(ev);\n\n // Dispatch alternate camel/kebab variation for compatibility\n const colonIndex = eventName.indexOf(':');\n if (colonIndex > 0) {\n const prefix = eventName.substring(0, colonIndex);\n const prop = eventName.substring(colonIndex + 1);\n const altName = prop.includes('-')\n ? `${prefix}:${prop\n .split('-')\n .map((p, i) =>\n i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1),\n )\n .join('')}`\n : `${prefix}:${prop.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}`;\n if (altName !== eventName) {\n safe(() => {\n this.dispatchEvent(new CustomEvent(altName, eventOptions));\n });\n }\n }\n\n return !ev.defaultPrevented;\n },\n );\n\n // --- Inject config methods into context ---\n // Expose config functions on the context as callable helpers. Event\n // handling is DOM-first: use standard DOM event listeners or\n // `context.emit` (which dispatches a DOM CustomEvent) to communicate\n // with the host. There is no property-based host-callback dispatch.\n const cfgToUse =\n (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n for (const key in cfgToUse) {\n const fn = (cfgToUse as Record<string, unknown>)[key];\n if (typeof fn === 'function') {\n // Expose as context method: context.fn(...args) => fn(...args, context)\n (this.context as Record<string, unknown>)[key] = (\n ...args: unknown[]\n ) => fn(...args, this.context);\n }\n }\n\n // Set up reactive property setters for all props to detect external changes\n if (cfgToUse.props) {\n for (const propName in cfgToUse.props) {\n let internalValue = (this as Record<string, unknown>)[propName];\n\n Object.defineProperty(this, propName, {\n get() {\n return internalValue;\n },\n set(newValue) {\n const oldValue = internalValue;\n internalValue = newValue;\n\n // Update the context to trigger watchers\n (this.context as Record<string, unknown>)[propName] = newValue;\n\n // Apply props to sync with context\n if (!this._initializing) {\n this._applyProps(cfgToUse);\n // Trigger re-render if the value actually changed\n if (oldValue !== newValue) {\n this._requestRender();\n }\n }\n },\n enumerable: true,\n configurable: true,\n });\n }\n }\n\n this._initializing = false;\n\n // Initialize watchers after initialization phase is complete\n this._initWatchers(cfgToUse);\n\n // Apply props before initial render so they're available immediately\n // Note: Attributes set by parent renderers may not be available yet,\n // but connectedCallback will re-apply props and re-render\n this._applyProps(cfgToUse);\n\n // Initial render (styles are applied within render)\n this._render(cfgToUse);\n }\n\n connectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n // Ensure props reflect attributes set by the parent renderer before\n // invoking lifecycle hooks.\n this._applyProps(config);\n // Re-render after applying props to ensure component shows updated values\n this._requestRender();\n handleConnected(config, this.context, this._mounted, (val) => {\n this._mounted = val;\n });\n });\n }\n\n disconnectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n handleDisconnected(\n config,\n this.context,\n this._listeners,\n () => {\n this._listeners = [];\n },\n () => {\n this._watchers.clear();\n },\n (val) => {\n this._templateLoading = val;\n },\n (err) => {\n this._templateError = err;\n },\n (val) => {\n this._mounted = val;\n },\n );\n });\n }\n\n attributeChangedCallback(\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) {\n this._runLogicWithinErrorBoundary(config, () => {\n this._applyProps(config);\n // Re-render after applying props to ensure component shows updated values\n if (oldValue !== newValue) {\n this._requestRender();\n }\n handleAttributeChanged(config, name, oldValue, newValue, this.context);\n });\n }\n\n static get observedAttributes() {\n return config.props ? Object.keys(config.props).map(toKebab) : [];\n }\n\n // --- Render ---\n private _render(cfg: ComponentConfig<S, C, P, T>) {\n this._runLogicWithinErrorBoundary(cfg, () => {\n // _render invoked; proceed to render via renderComponent\n renderComponent(\n this.shadowRoot,\n cfg,\n this.context,\n this._refs,\n (html) => {\n this._lastHtmlStringForJitCSS = html;\n // Optionally, use the latest HTML string for debugging or external logic\n if (\n typeof (this as { onHtmlStringUpdate?: (html: string) => void })\n .onHtmlStringUpdate === 'function'\n ) {\n const htmlUpdater = this as unknown as\n | { onHtmlStringUpdate?: (html: string) => void }\n | undefined;\n htmlUpdater?.onHtmlStringUpdate?.(html as string);\n }\n },\n (val) => {\n this._templateLoading = val;\n // Optionally, use loading state for external logic\n const selfAsAny = this as unknown as\n | { onLoadingStateChange?: (val: boolean) => void }\n | undefined;\n selfAsAny?.onLoadingStateChange?.(val);\n },\n (err) => {\n this._templateError = err;\n // Optionally, use error state for external logic\n const selfAsAny2 = this as unknown as\n | { onErrorStateChange?: (err: Error) => void }\n | undefined;\n selfAsAny2?.onErrorStateChange?.(err as Error);\n },\n (html) => this._applyStyle(cfg, html),\n );\n });\n }\n\n public requestRender() {\n this._requestRender();\n }\n\n _requestRender() {\n this._runLogicWithinErrorBoundary(this._cfg, () => {\n // Use scheduler to batch render requests\n scheduleDOMUpdate(() => {\n requestRender(\n () => this._render(this._cfg),\n this._lastRenderTime,\n this._renderCount,\n (t) => {\n this._lastRenderTime = t;\n },\n (c) => {\n this._renderCount = c;\n },\n this._renderTimeoutId,\n (id) => {\n this._renderTimeoutId = id;\n },\n );\n }, this._componentId);\n });\n }\n\n // --- Style ---\n private _applyStyle(cfg: ComponentConfig<S, C, P, T>, html: string) {\n this._runLogicWithinErrorBoundary(cfg, () => {\n applyStyle(\n this.shadowRoot,\n this.context,\n html,\n this._styleSheet,\n (sheet) => {\n this._styleSheet = sheet;\n },\n );\n });\n }\n\n // --- Error Boundary function ---\n private _runLogicWithinErrorBoundary(\n cfg: ComponentConfig<S, C, P, T>,\n fn: () => void,\n ) {\n if (this._hasError) this._hasError = false;\n try {\n fn();\n } catch (error) {\n this._hasError = true;\n\n // DEV-only diagnostic: provide actionable context to help debugging\n try {\n const tag = this.tagName?.toLowerCase?.() || '<unknown>';\n const compId = this._componentId || '<unknown-id>';\n const safeProps: Record<string, unknown> = {};\n if (cfg && cfg.props) {\n for (const k of Object.keys(cfg.props)) {\n try {\n const v = (this.context as Record<string, unknown>)[k];\n if (v instanceof Node) {\n safeProps[k] = `[DOM Node: ${v.nodeName}]`;\n } else if (typeof v === 'object' && v !== null) {\n safeProps[k] =\n Object.keys(v).length > 5\n ? `[object(${Object.keys(v).length} keys)]`\n : v;\n } else {\n safeProps[k] = v;\n }\n } catch {\n safeProps[k] = '[unreadable]';\n }\n }\n }\n\n devError(`Error rendering component <${tag}> (id=${compId}):`, error);\n devError('Component props snapshot:', safeProps);\n devWarn(\n 'Common causes: accessing properties of null/undefined inside template interpolations; expensive or throwing expressions inside templates that evaluate eagerly. Fixes: use optional chaining (obj?.prop), guard with ternary, or use the runtime lazy overload: when(cond, () => html`...`).',\n );\n } catch {\n // best-effort diagnostics - swallow failures here to preserve original behavior\n }\n\n if (cfg.onError) {\n cfg.onError(error as Error | null, this.context);\n }\n }\n }\n\n // --- State, props, computed ---\n private _initContext(\n cfg: ComponentConfig<S, C, P, T>,\n ): ComponentContext<S, C, P, T> {\n try {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n function createReactive<T>(obj: T, path = ''): T {\n if (Array.isArray(obj)) {\n // Create a proxy that intercepts array mutations\n return new Proxy(obj, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Intercept array mutating methods\n if (typeof value === 'function' && typeof prop === 'string') {\n const mutatingMethods = [\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse',\n ];\n if (mutatingMethods.includes(prop)) {\n return function (...args: unknown[]) {\n const result = value.apply(target, args);\n\n if (!self._initializing) {\n const fullPath = path || 'root';\n self._triggerWatchers(fullPath, target);\n scheduleDOMUpdate(\n () => self._render(cfg),\n self._componentId,\n );\n }\n\n return result;\n };\n }\n }\n\n return value;\n },\n set(target, prop, value) {\n (target as Record<string, unknown>)[String(prop)] = value;\n if (!self._initializing) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n self._triggerWatchers(fullPath, value);\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n deleteProperty(target, prop) {\n delete (target as Record<string, unknown>)[String(prop)];\n if (!self._initializing) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n self._triggerWatchers(fullPath, undefined);\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n });\n }\n if (obj && typeof obj === 'object') {\n // Skip ReactiveState objects to avoid corrupting their internal structure\n if (isReactiveState(obj)) {\n return obj;\n }\n\n for (const key in obj) {\n const newPath = path ? `${path}.${key}` : key;\n obj[key] = createReactive(obj[key], newPath);\n }\n return new Proxy(obj, {\n set(target, prop, value) {\n const fullPath = path\n ? `${path}.${String(prop)}`\n : String(prop);\n (target as Record<string, unknown>)[String(prop)] =\n createReactive(value, fullPath);\n if (!self._initializing) {\n self._triggerWatchers(\n fullPath,\n (target as Record<string, unknown>)[String(prop)],\n );\n scheduleDOMUpdate(() => self._render(cfg), self._componentId);\n }\n return true;\n },\n get(target, prop, receiver) {\n return Reflect.get(target, prop, receiver);\n },\n });\n }\n return obj;\n }\n return createReactive({\n // For functional components, state is managed by state() function calls\n // Include prop defaults in initial reactive context so prop updates trigger reactivity\n ...(cfg.props\n ? Object.fromEntries(\n Object.entries(cfg.props).map(([key, def]) => [\n key,\n def.default,\n ]),\n )\n : {}),\n }) as ComponentContext<S, C, P, T>;\n } catch {\n return {} as ComponentContext<S, C, P, T>;\n }\n }\n\n private _initWatchers(cfg: ComponentConfig<S, C, P, T>): void {\n this._runLogicWithinErrorBoundary(cfg, () => {\n initWatchers(\n this.context,\n this._watchers,\n {}, // Watchers are now handled by the watch() function in functional API\n );\n });\n }\n\n private _triggerWatchers(path: string, newValue: unknown): void {\n triggerWatchers(this.context, this._watchers, path, newValue);\n }\n\n private _applyProps(cfg: ComponentConfig<S, C, P, T>): void {\n this._runLogicWithinErrorBoundary(cfg, () => {\n try {\n applyProps(this, cfg, this.context);\n } catch (error) {\n this._hasError = true;\n if (cfg.onError) cfg.onError(error as Error | null, this.context);\n // Note: errorFallback was removed as it's handled by the functional API directly\n }\n });\n }\n };\n}\n\n/**\n * Streamlined functional component API with automatic reactive props and lifecycle hooks.\n *\n * @example\n * ```ts\n * // Simple component with no parameters\n * component('simple-header', () => {\n * return html`<h1>Hello World</h1>`;\n * });\n *\n * // With props using useProps() hook\n * component('with-props', () => {\n * const { message } = useProps({ message: 'Hello' });\n * return html`<div>${message}</div>`;\n * });\n *\n * // With props and lifecycle hooks\n * component('my-switch', () => {\n * const { modelValue, label } = useProps({ modelValue: false, label: '' });\n * const emit = useEmit();\n *\n * useOnConnected(() => console.log('Switch connected!'));\n * useOnDisconnected(() => console.log('Switch disconnected!'));\n *\n * return html`\n * <label>\n * ${label}\n * <input\n * type=\"checkbox\"\n * :checked=\"${modelValue}\"\n * @change=\"${(e) => emit('update:modelValue', e.target.checked)}\"\n * />\n * </label>\n * `;\n * });\n * ```\n */\n\n// Overload: No parameters - use useProps() hook for props access\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>,\n): void;\n\n// Implementation\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>,\n): void {\n // Ensure the global registry is exposed when running in a browser. This is\n // performed lazily to avoid module-load side-effects that prevent\n // tree-shaking by bundlers.\n initGlobalRegistryIfNeeded();\n let normalizedTag = toKebab(tag);\n if (!normalizedTag.includes('-')) {\n normalizedTag = `cer-${normalizedTag}`;\n }\n\n // Store lifecycle hooks from the render function\n const lifecycleHooks: {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) => void;\n onError?: (error: Error) => void;\n } = {};\n\n // Create component config\n const config: ComponentConfig<object, object, object, object> = {\n // Props are accessed via useProps() hook\n props: {},\n\n // Add lifecycle hooks from the stored functions\n onConnected: () => {\n if (lifecycleHooks.onConnected) {\n lifecycleHooks.onConnected();\n }\n },\n\n onDisconnected: () => {\n if (lifecycleHooks.onDisconnected) {\n lifecycleHooks.onDisconnected();\n }\n },\n\n onAttributeChanged: (name, oldValue, newValue) => {\n if (lifecycleHooks.onAttributeChanged) {\n lifecycleHooks.onAttributeChanged(name, oldValue, newValue);\n }\n },\n\n onError: (error) => {\n if (lifecycleHooks.onError && error) {\n lifecycleHooks.onError(error);\n }\n },\n\n render: (context) => {\n // Track dependencies for rendering\n // Use stable component ID from context if available, otherwise generate new one\n type InternalContext = Record<string, unknown> & {\n _componentId?: string;\n _hookCallbacks?: Record<string, unknown> & {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) => void;\n onError?: (err: unknown) => void;\n style?: (el: HTMLElement) => void;\n props?: Record<string, unknown>;\n };\n _styleCallback?: (el: HTMLElement) => void;\n };\n\n const ictx = context as InternalContext;\n const componentId =\n ictx._componentId ||\n `${normalizedTag}-${Math.random().toString(36).substr(2, 9)}`;\n\n reactiveSystem.setCurrentComponent(componentId, () => {\n if (context.requestRender) {\n context.requestRender();\n }\n });\n\n try {\n // Set current component context for hooks\n setCurrentComponentContext(context);\n\n // Call render function with no arguments - use useProps() hook for props access\n // If renderFn throws synchronously (for example due to eager interpolation\n // inside templates), invoke any useOnError hook that the component may\n // have already registered during the render execution before rethrowing.\n let result: VNode | VNode[] | Promise<VNode | VNode[]>;\n try {\n result = renderFn();\n } catch (err) {\n try {\n const hookCallbacks = ictx._hookCallbacks;\n if (hookCallbacks && typeof hookCallbacks.onError === 'function') {\n try {\n (hookCallbacks.onError as (e: unknown) => void)(err);\n } catch {\n /* swallow */\n }\n }\n } catch {\n /* best-effort */\n }\n throw err;\n }\n\n // Process hook callbacks that were set during render\n if (ictx._hookCallbacks) {\n const hookCallbacks = ictx._hookCallbacks;\n if (hookCallbacks.onConnected) {\n lifecycleHooks.onConnected = hookCallbacks.onConnected;\n }\n if (hookCallbacks.onDisconnected) {\n lifecycleHooks.onDisconnected = hookCallbacks.onDisconnected;\n }\n if (hookCallbacks.onAttributeChanged) {\n lifecycleHooks.onAttributeChanged =\n hookCallbacks.onAttributeChanged as (\n name: string,\n oldValue: string | null,\n newValue: string | null,\n ) => void;\n }\n if (hookCallbacks.onError) {\n lifecycleHooks.onError = hookCallbacks.onError as (\n err: Error,\n ) => void;\n }\n if (hookCallbacks.style) {\n // Store the style callback in the context for applyStyle to use\n ictx._styleCallback = hookCallbacks.style as (\n el: HTMLElement,\n ) => void;\n }\n // If useProps() was called, update config.props with the defaults\n if (hookCallbacks.props) {\n const propsDefaults = hookCallbacks.props as Record<\n string,\n unknown\n >;\n config.props = Object.fromEntries(\n Object.entries(propsDefaults).map(([key, defaultValue]) => {\n const type =\n typeof defaultValue === 'boolean'\n ? Boolean\n : typeof defaultValue === 'number'\n ? Number\n : typeof defaultValue === 'string'\n ? String\n : Function; // Use Function for complex types\n return [\n key,\n { type, default: defaultValue as string | number | boolean },\n ];\n }),\n );\n // Update the registry so future instances and observedAttributes use the updated config\n registry.set(normalizedTag, config);\n }\n }\n\n return result;\n } finally {\n clearCurrentComponentContext();\n reactiveSystem.clearCurrentComponent();\n }\n },\n };\n\n // Store in registry\n registry.set(normalizedTag, config);\n\n // CRITICAL: Perform a \"discovery render\" to detect props from useProps()\n // This must happen BEFORE defining the custom element, so observedAttributes\n // includes all props declared via useProps()\n if (typeof window !== 'undefined') {\n try {\n // Create a minimal mock context for discovery\n const discoveryContext: {\n _hookCallbacks: Record<string, unknown>;\n requestRender: () => void;\n emit?: (eventName: string, detail?: unknown) => boolean;\n } = {\n _hookCallbacks: {},\n requestRender: () => {},\n // Provide a noop emit during discovery render so hooks like useEmit()\n // can be called safely when the component author invokes them at\n // module-evaluation time to declare handlers. The real element\n // instances will have a proper emit implementation.\n emit: () => true,\n };\n setCurrentComponentContext(discoveryContext);\n try {\n // Execute once to trigger useProps() calls. If this throws we want to\n // surface the error to any useOnError hook that the component may have\n // registered during discovery and emit DEV diagnostics so authors see\n // what's going wrong (best-effort).\n renderFn();\n } catch (err) {\n try {\n const hookCallbacks = (\n discoveryContext as {\n _hookCallbacks?: { onError?: (err: unknown) => void };\n }\n )?._hookCallbacks;\n if (hookCallbacks && typeof hookCallbacks.onError === 'function') {\n try {\n hookCallbacks.onError(err);\n } catch {\n /* swallow */\n }\n }\n // DEV diagnostics for discovery-time failures\n devError(\n `Error during component discovery render <${normalizedTag}>:`,\n err,\n );\n devWarn(\n 'Error occurred during initial component discovery render. Consider guarding expensive expressions or using lazy factories for directives like when().',\n );\n } catch {\n /* best-effort */\n }\n clearCurrentComponentContext();\n throw err;\n }\n clearCurrentComponentContext();\n\n // If useProps() was called during discovery, update config.props\n if (discoveryContext._hookCallbacks?.props) {\n const propsDefaults = discoveryContext._hookCallbacks.props;\n config.props = Object.fromEntries(\n Object.entries(propsDefaults).map(([key, defaultValue]) => {\n const type =\n typeof defaultValue === 'boolean'\n ? Boolean\n : typeof defaultValue === 'number'\n ? Number\n : typeof defaultValue === 'string'\n ? String\n : Function;\n return [\n key,\n { type, default: defaultValue as string | number | boolean },\n ];\n }),\n );\n // Update registry with discovered props\n registry.set(normalizedTag, config);\n }\n } catch {\n // Discovery render failed - this is OK, props will be discovered on first real render\n }\n\n if (!customElements.get(normalizedTag)) {\n customElements.define(\n normalizedTag,\n createElementClass(normalizedTag, config) as CustomElementConstructor,\n );\n }\n }\n}\n","import type { VNode } from './types';\nimport { contextStack } from './render';\nimport {\n toKebab,\n toCamel,\n getNestedValue,\n setNestedValue,\n safe,\n decodeEntities,\n isUnsafeHTML,\n safeSerializeAttr,\n isClassLikeAttr,\n} from './helpers';\nimport { isReactiveState } from './reactive';\nimport { devWarn } from './logger';\n\n// Strict LRU cache helper for fully static templates (no interpolations, no context)\nclass LRUCache<K, V> {\n private map = new Map<K, V>();\n private maxSize: number;\n constructor(maxSize: number) {\n this.maxSize = maxSize;\n }\n get(key: K): V | undefined {\n const v = this.map.get(key);\n if (v === undefined) return undefined;\n // move to end (LRU ordering)\n this.map.delete(key);\n this.map.set(key, v);\n return v;\n }\n set(key: K, value: V) {\n // Delete if exists to maintain insertion order\n this.map.delete(key);\n this.map.set(key, value);\n if (this.map.size > this.maxSize) {\n // remove oldest (first key)\n const firstKey = this.map.keys().next().value;\n if (firstKey !== undefined) this.map.delete(firstKey);\n }\n }\n has(key: K): boolean {\n return this.map.has(key);\n }\n clear() {\n this.map.clear();\n }\n}\n\nconst TEMPLATE_COMPILE_CACHE = new LRUCache<string, VNode | VNode[]>(500);\n\n/**\n * Validates event handlers to prevent common mistakes that lead to infinite loops\n */\nfunction validateEventHandler(value: unknown, eventName: string): void {\n // Check for null/undefined handlers\n if (value === null || value === undefined) {\n devWarn(\n `⚠️ Event handler for '@${eventName}' is ${value}. ` +\n `This will prevent the event from working. ` +\n `Use a function reference instead: @${eventName}=\"\\${functionName}\"`,\n );\n return;\n }\n\n // Check for immediate function invocation (most common mistake)\n if (typeof value !== 'function') {\n devWarn(\n `🚨 Potential infinite loop detected! Event handler for '@${eventName}' appears to be ` +\n `the result of a function call (${typeof value}) instead of a function reference. ` +\n `Change @${eventName}=\"\\${functionName()}\" to @${eventName}=\"\\${functionName}\" ` +\n `to pass the function reference instead of calling it immediately.`,\n );\n }\n\n // Additional check for common return values of mistaken function calls\n if (value === undefined && typeof value !== 'function') {\n devWarn(\n `💡 Tip: If your event handler function returns undefined, make sure you're passing ` +\n `the function reference, not calling it. Use @${eventName}=\"\\${fn}\" not @${eventName}=\"\\${fn()}\"`,\n );\n }\n}\n\nexport function h(\n tag: string,\n props: Record<string, unknown> = {},\n children?: VNode[] | string,\n key?: string | number,\n): VNode {\n // Do NOT invent keys here; use only what the caller passes (or props.key).\n const finalKey = (key ?? (props.key as unknown as string | undefined)) as\n | string\n | undefined;\n return { tag, key: finalKey, props, children };\n}\n\nexport function isAnchorBlock(v: unknown): boolean {\n return (\n !!v &&\n typeof v === 'object' &&\n ((v as { type?: string }).type === 'AnchorBlock' ||\n (v as { tag?: string }).tag === '#anchor')\n );\n}\n\nexport function isElementVNode(v: unknown): v is VNode {\n return (\n typeof v === 'object' && v !== null && 'tag' in v && !isAnchorBlock(v) // exclude anchor blocks from being treated as normal elements\n );\n}\n\nexport function ensureKey(v: VNode, k?: string): VNode {\n // Keep behavior consistent with the older compiler: only surface the\n // provided key when present. Do not invent a random key here — that\n // causes remounts and breaks deterministic tests (especially for\n // form controls like <select>). If caller passes `undefined`, we\n // preserve `undefined` so downstream key-assignment logic can decide.\n return v.key != null ? v : { ...v, key: k };\n}\n\nexport interface ParsePropsResult {\n props: Record<string, unknown>;\n attrs: Record<string, unknown>;\n directives: Record<\n string,\n { value: unknown; modifiers: string[]; arg?: string }\n >;\n bound: string[];\n}\n\nexport function parseProps(\n str: string,\n values: unknown[] = [],\n context: Record<string, unknown> = {},\n): ParsePropsResult {\n const props: Record<string, unknown> = {};\n const attrs: Record<string, unknown> = {};\n const directives: Record<\n string,\n { value: unknown; modifiers: string[]; arg?: string }\n > = {};\n const bound: string[] = [];\n\n // Match attributes with optional prefix and support for single/double quotes\n // Also matches standalone boolean attributes (without =value)\n const attrRegex =\n /([:@#]?)([a-zA-Z0-9-:.]+)(?:=(\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"|'([^'\\\\]*(\\\\.[^'\\\\]*)*)'))?/g;\n\n let match: RegExpExecArray | null;\n\n while ((match = attrRegex.exec(str))) {\n const prefix = match[1];\n const rawName = match[2];\n const rawVal = (match[4] || match[6]) ?? '';\n\n // If no value was provided (standalone attribute), treat as boolean true\n const isStandalone = match[3] === undefined && match[6] === undefined;\n\n // Interpolation detection\n const interpMatch = rawVal.match(/^{{(\\d+)}}$/);\n let value: unknown = isStandalone\n ? true // Standalone attributes are boolean true\n : interpMatch\n ? (values[Number(interpMatch[1])] ?? null)\n : rawVal;\n\n // Type inference for booleans, null, numbers\n if (!interpMatch) {\n if (value === 'true') value = true;\n else if (value === 'false') value = false;\n else if (value === 'null') value = null;\n else if (!isNaN(Number(value))) value = Number(value);\n }\n\n // Known directive names\n const knownDirectives = [\n 'model',\n 'bind',\n 'show',\n 'class',\n 'style',\n 'ref',\n 'when',\n ];\n if (prefix === ':') {\n // Support :model:checked (directive with argument) and :class.foo (modifiers)\n const [nameAndModifiers, argPart] = rawName.split(':');\n const [maybeDirective, ...modifierParts] = nameAndModifiers.split('.');\n if (knownDirectives.includes(maybeDirective)) {\n const modifiers = [...modifierParts];\n // Allow multiple :model directives on the same tag by keying them with\n // their argument when present (e.g. 'model:test'). This preserves both\n // plain :model and :model:prop simultaneously.\n const directiveKey =\n maybeDirective === 'model' && argPart\n ? `model:${argPart}`\n : maybeDirective;\n directives[directiveKey] = {\n value,\n modifiers,\n arg: argPart,\n };\n } else {\n // Special-case certain boolean-like attributes to promote them to\n // props so runtime property assignment and coercion behave correctly\n // for native elements (e.g. :disabled should affect el.disabled).\n if (rawName === 'disabled') {\n // Be conservative: only promote disabled to props at compile-time\n // when the bound value is an explicit boolean-ish primitive\n // (boolean, empty-string presence, literal 'true'/'false', null, or number).\n // Otherwise leave it in attrs so the runtime can apply safer coercion.\n let propValue = value;\n if (propValue && isReactiveState(propValue))\n propValue = (propValue as { value: unknown }).value;\n const t = typeof propValue;\n const isBoolStr =\n t === 'string' && (propValue === 'true' || propValue === 'false');\n const shouldPromote =\n propValue === '' ||\n t === 'boolean' ||\n isBoolStr ||\n propValue == null ||\n t === 'number';\n if (shouldPromote) {\n props[rawName] = propValue;\n } else {\n // Unwrap reactive state objects for bound attributes and keep in attrs\n let attrValue = value;\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as { value: unknown }).value; // This triggers dependency tracking\n }\n attrs[rawName] = attrValue;\n }\n bound.push(rawName);\n } else {\n // Unwrap reactive state objects for bound attributes\n let attrValue = value;\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as { value: unknown }).value; // This triggers dependency tracking\n }\n attrs[rawName] = attrValue;\n bound.push(rawName);\n }\n }\n } else if (prefix === '@') {\n // Parse event modifiers: @click.prevent.stop\n const [eventName, ...modifierParts] = rawName.split('.');\n const modifiers = modifierParts;\n\n // Validate event handler to prevent common mistakes\n validateEventHandler(value, eventName);\n\n // Create wrapped event handler that applies modifiers\n const originalHandler: ((e: Event) => unknown) | undefined =\n typeof value === 'function'\n ? (value as (e: Event) => unknown)\n : typeof (context as Record<string, unknown>)[\n value as unknown as string\n ] === 'function'\n ? ((context as Record<string, unknown>)[value as string] as (\n e: Event,\n ) => unknown)\n : undefined;\n\n if (originalHandler) {\n const wrappedHandler = (event: Event) => {\n // Apply event modifiers\n if (modifiers.includes('prevent')) {\n event.preventDefault();\n }\n if (modifiers.includes('stop')) {\n event.stopPropagation();\n }\n if (\n modifiers.includes('self') &&\n event.target !== event.currentTarget\n ) {\n return;\n }\n\n // For .once modifier, we need to remove the listener after first call\n if (modifiers.includes('once')) {\n (event.currentTarget as Element)?.removeEventListener(\n eventName,\n wrappedHandler,\n );\n }\n\n // Call the original handler\n return originalHandler(event);\n };\n\n // Map @event to an `on<Event>` prop (DOM-first event listener convention)\n const onName =\n 'on' + eventName.charAt(0).toUpperCase() + eventName.slice(1);\n props[onName] = wrappedHandler;\n }\n } else if (rawName === 'ref') {\n props.ref = value;\n } else {\n attrs[rawName] = value;\n }\n }\n\n return { props, attrs, directives, bound };\n}\n\n/**\n * Transform VNodes with :when directive into anchor blocks for conditional rendering\n */\nfunction transformWhenDirective(vnode: VNode): VNode {\n // Skip if not an element VNode or is already an anchor block\n if (!isElementVNode(vnode) || isAnchorBlock(vnode)) {\n return vnode;\n }\n\n // Check if this VNode has a :when directive\n const directives = vnode.props?.directives;\n if (directives && directives.when) {\n const rawWhen = directives.when.value;\n // If the directive value is a ReactiveState, unwrap it so the condition\n // reflects the current boolean value (e.g. ref(false) -> false).\n const whenCondition = isReactiveState(rawWhen)\n ? (rawWhen as { value: unknown }).value\n : rawWhen;\n\n // Remove the :when directive from the VNode since we're handling it here\n const remainingDirectives = { ...directives };\n delete remainingDirectives.when;\n const newProps = { ...vnode.props };\n if (Object.keys(remainingDirectives).length > 0) {\n newProps.directives = remainingDirectives;\n } else {\n delete newProps.directives;\n }\n\n // Create a new VNode without the :when directive\n const elementVNode: VNode = {\n ...vnode,\n props: newProps,\n };\n\n // Recursively transform children if they exist\n if (Array.isArray(elementVNode.children)) {\n elementVNode.children = elementVNode.children.map((child) =>\n typeof child === 'object' && child !== null\n ? transformWhenDirective(child as VNode)\n : child,\n );\n }\n\n // Wrap in an anchor block with the condition\n const anchorKey =\n vnode.key != null ? `when-${vnode.key}` : `when-${vnode.tag}`;\n return {\n tag: '#anchor',\n key: anchorKey,\n children: whenCondition ? [elementVNode] : [],\n };\n }\n\n // Recursively transform children if they exist\n if (Array.isArray(vnode.children)) {\n const transformedChildren = vnode.children.map((child) =>\n typeof child === 'object' && child !== null\n ? transformWhenDirective(child as VNode)\n : child,\n );\n return {\n ...vnode,\n children: transformedChildren,\n };\n }\n\n return vnode;\n}\n\n/**\n * Internal implementation allowing an optional compile context for :model.\n * Fixes:\n * - Recognize interpolation markers embedded in text (\"World{{1}}\") and replace them.\n * - Skip empty arrays from directives so markers don't leak as text.\n * - Pass AnchorBlocks through (and deep-normalize their children's keys) so the renderer can mount/patch them surgically.\n * - Do not rewrap interpolated VNodes (preserve their keys); only fill in missing keys.\n */\nexport function htmlImpl(\n strings: TemplateStringsArray,\n values: unknown[],\n context?: Record<string, unknown>,\n): VNode | VNode[] {\n // Retrieve current context from stack (transparent injection)\n const injectedContext =\n contextStack.length > 0 ? contextStack[contextStack.length - 1] : undefined;\n\n // Use injected context if no explicit context provided\n const effectiveContext = context ?? injectedContext;\n\n // Conservative caching: only cache templates that have no interpolations\n // (values.length === 0) and no explicit context. This avoids incorrectly\n // reusing parsed structures that depend on runtime values or context.\n const canCache = !context && values.length === 0;\n const cacheKey = canCache ? strings.join('<!--TEMPLATE_DELIM-->') : null;\n if (canCache && cacheKey) {\n const cached = TEMPLATE_COMPILE_CACHE.get(cacheKey);\n if (cached) return cached;\n }\n\n // Create a text VNode for interpolations (do NOT decode entity sequences)\n function textVNode(text: string, key: string): VNode {\n return h('#text', {}, text, key);\n }\n\n // Create a text VNode for literal template text (decode HTML entities so\n // authors can write `&lt;` inside template bodies and get the literal\n // character in the DOM). This should NOT be used for interpolated values\n // where the runtime should preserve the original string provided by the\n // consumer.\n function decodedTextVNode(text: string, key: string): VNode {\n let decoded = typeof text === 'string' ? decodeEntities(text) : text;\n // If the literal template text contains newlines or carriage returns,\n // collapse any run of whitespace (including newlines and indentation)\n // into a single space. This preserves single-space separators while\n // eliminating incidental indentation/newline leakage inside elements.\n if (typeof decoded === 'string' && /[\\r\\n]/.test(decoded)) {\n decoded = decoded.replace(/\\s+/g, ' ');\n }\n return h('#text', {}, decoded as string, key);\n }\n\n // Stitch template with interpolation markers\n let template = '';\n for (let i = 0; i < strings.length; i++) {\n template += strings[i];\n if (i < values.length) template += `{{${i}}}`;\n }\n\n // Matches: comments, tags (open/close/self), standalone interpolation markers, or any other text\n // How this works:\n // const tagRegex =\n // /<!--[\\s\\S]*?--> # HTML comments\n // |<\\/?([a-zA-Z0-9-]+) # tag name\n // ( # start attributes group\n // (?:\\s+ # whitespace before attribute\n // [^\\s=>/]+ # attribute name\n // (?:\\s*=\\s* # optional equals\n // (?:\n // \"(?:\\\\.|[^\"])*\" # double-quoted value\n // |'(?:\\\\.|[^'])*' # single-quoted value\n // |[^\\s>]+ # unquoted value\n // )\n // )?\n // )* # repeat for multiple attributes\n // )\\s*\\/?> # end of tag\n // |{{(\\d+)}} # placeholder\n // |([^<]+) # text node\n // /gmx;\n // We explicitly match attributes one by one, and if a value is quoted, we allow anything inside (including >).\n // Handles both ' and \" quotes.\n // Matches unquoted attributes like disabled or checked.\n // Keeps {{(\\d+)}} and text node capture groups intact.\n // Added support for HTML comments which are ignored during parsing.\n const tagRegex =\n /<!--[\\s\\S]*?-->|<\\/?([a-zA-Z0-9-]+)((?:\\s+[^\\s=>/]+(?:\\s*=\\s*(?:\"(?:\\\\.|[^\"])*\"|'(?:\\\\.|[^'])*'|[^\\s>]+))?)*)\\s*\\/?>|{{(\\d+)}}|([^<]+)/g;\n\n const stack: Array<{\n tag: string;\n props: Record<string, unknown>;\n children: VNode[];\n key: string | number | undefined;\n }> = [];\n const root: VNode | null = null;\n let match: RegExpExecArray | null;\n let currentChildren: VNode[] = [];\n let currentTag: string | null = null;\n let currentProps: Record<string, unknown> = {};\n let currentKey: string | number | undefined = undefined;\n let nodeIndex = 0;\n const fragmentChildren: VNode[] = []; // Track root-level nodes for fragments\n\n // Helper: merge object-like interpolation into currentProps\n type MaybeVNodeLike =\n | { props?: Record<string, unknown>; attrs?: Record<string, unknown> }\n | Record<string, unknown>;\n\n function mergeIntoCurrentProps(maybe: unknown) {\n if (!maybe || typeof maybe !== 'object') return;\n if (isAnchorBlock(maybe)) return; // do not merge AnchorBlocks\n const mm = maybe as MaybeVNodeLike;\n const cp = currentProps as {\n props?: Record<string, unknown>;\n attrs?: Record<string, unknown>;\n };\n if (\n (mm as { props?: unknown }).props ||\n (mm as { attrs?: unknown }).attrs\n ) {\n const mmWith = mm as {\n props?: Record<string, unknown>;\n attrs?: Record<string, unknown>;\n };\n if (mmWith.props) {\n // Ensure currentProps.props exists\n if (!cp.props) cp.props = {};\n Object.assign(cp.props, mmWith.props);\n }\n if (mmWith.attrs) {\n // Ensure currentProps.attrs exists\n if (!cp.attrs) cp.attrs = {};\n\n // Handle special merging for style and class attributes\n Object.keys(mmWith.attrs).forEach((key) => {\n if (key === 'style' && cp.attrs!.style) {\n // Merge style attributes by concatenating with semicolon\n const existingStyle = String(cp.attrs!.style).replace(/;?\\s*$/, '');\n const newStyle = String(mmWith.attrs!.style).replace(/^;?\\s*/, '');\n cp.attrs!.style = existingStyle + '; ' + newStyle;\n } else if (key === 'class' && cp.attrs!.class) {\n // Merge class attributes by concatenating with space\n const existingClasses = String(cp.attrs!.class)\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n const newClasses = String(mmWith.attrs!.class)\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n const allClasses = [\n ...new Set([...existingClasses, ...newClasses]),\n ];\n cp.attrs!.class = allClasses.join(' ');\n } else {\n // For other attributes, just assign (later values override)\n cp.attrs![key] = mmWith.attrs![key];\n }\n });\n }\n } else {\n // If no props/attrs structure, merge directly into props\n if (!cp.props) cp.props = {};\n Object.assign(cp.props, mm as Record<string, unknown>);\n }\n }\n\n // Helper: push an interpolated value into currentChildren/currentProps or fragments\n function pushInterpolation(val: unknown, baseKey: string) {\n const targetChildren = currentTag ? currentChildren : fragmentChildren;\n\n if (isAnchorBlock(val)) {\n const anchorKey = (val as VNode).key ?? baseKey;\n const anchorChildren = (val as { children?: VNode[] }).children;\n targetChildren.push({\n ...(val as VNode),\n key: anchorKey,\n children: anchorChildren,\n });\n return;\n }\n\n if (isElementVNode(val)) {\n // Leave key undefined so assignKeysDeep can generate a stable one\n targetChildren.push(ensureKey(val, undefined));\n return;\n }\n\n if (Array.isArray(val)) {\n if (val.length === 0) return;\n for (let i = 0; i < val.length; i++) {\n const v = val[i];\n if (isAnchorBlock(v) || isElementVNode(v) || Array.isArray(v)) {\n // recurse or push without forcing a key\n pushInterpolation(v, `${baseKey}-${i}`);\n } else if (v !== null && typeof v === 'object') {\n // If the object is an unsafe HTML marker, push a raw vnode\n if (isUnsafeHTML(v)) {\n targetChildren.push(\n h(\n '#raw',\n {},\n (v as { __rawHTML: string }).__rawHTML,\n `${baseKey}-${i}`,\n ),\n );\n } else {\n mergeIntoCurrentProps(v);\n }\n } else {\n targetChildren.push(textVNode(String(v), `${baseKey}-${i}`));\n }\n }\n return;\n }\n\n if (val !== null && typeof val === 'object') {\n if (isUnsafeHTML(val)) {\n const raw = (val as { __rawHTML?: string }).__rawHTML ?? '';\n targetChildren.push(h('#raw', {}, raw, baseKey));\n return;\n }\n mergeIntoCurrentProps(val);\n return;\n }\n\n targetChildren.push(textVNode(String(val), baseKey));\n }\n\n const voidElements = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n ]);\n\n while ((match = tagRegex.exec(template))) {\n // Skip HTML comments (they are matched by the regex but ignored)\n if (match[0].startsWith('<!--') && match[0].endsWith('-->')) {\n continue;\n }\n\n if (match[1]) {\n // Tag token\n const tagName = match[1];\n const isClosing = match[0][1] === '/';\n const isSelfClosing =\n match[0][match[0].length - 2] === '/' || voidElements.has(tagName);\n\n const {\n props: rawProps,\n attrs: rawAttrs,\n directives,\n bound: boundList,\n } = parseProps(\n match[2] || '',\n values,\n (effectiveContext ?? {}) as Record<string, unknown>,\n ) as ParsePropsResult;\n\n // No runtime registration here; compiler will set `isCustomElement`\n // on vnodeProps where appropriate. Runtime will consult that flag or\n // the strict registry if consumers register tags at runtime.\n\n // Shape props into { props, attrs, directives } expected by VDOM\n const vnodeProps: {\n props: Record<string, unknown>;\n attrs: Record<string, unknown>;\n directives?: Record<string, { value: unknown; modifiers: string[] }>;\n isCustomElement?: boolean;\n } = { props: {}, attrs: {} };\n\n for (const k in rawProps) vnodeProps.props[k] = rawProps[k];\n for (const k in rawAttrs) vnodeProps.attrs[k] = rawAttrs[k];\n\n // If a `key` attribute was provided, surface it as a vnode prop so the\n // renderer/assignKeysDeep can use it as the vnode's key and avoid\n // unnecessary remounts when children order/state changes.\n if (\n vnodeProps.attrs &&\n Object.prototype.hasOwnProperty.call(vnodeProps.attrs, 'key') &&\n !(\n vnodeProps.props &&\n Object.prototype.hasOwnProperty.call(vnodeProps.props, 'key')\n )\n ) {\n safe(() => {\n vnodeProps.props.key = vnodeProps.attrs['key'];\n });\n }\n\n // Ensure native form control properties are set as JS props when the\n // template used `:value` or `:checked` (the parser places plain\n // `:value` into attrs). Textareas and inputs show their content from\n // the element property (el.value / el.checked), not the HTML attribute.\n // Only promote when the attribute was a bound attribute (e.g. used\n // with `:value`), otherwise leave static attributes in attrs for\n // tests and expected behavior.\n try {\n // Conservative promotion map: promote attributes that must be properties\n // for correct native behavior (value/checked/etc.). We intentionally\n // avoid promoting `disabled` at compile-time because early promotion\n // can cause accidental enabling/disabling when bound expressions or\n // wrapper proxies evaluate to truthy values. The runtime already\n // performs defensive coercion for boolean-like values; prefer that.\n const nativePromoteMap: Record<string, string[]> = {\n input: [\n 'value',\n 'checked',\n 'readonly',\n 'required',\n 'placeholder',\n 'maxlength',\n 'minlength',\n ],\n textarea: [\n 'value',\n 'readonly',\n 'required',\n 'placeholder',\n 'maxlength',\n 'minlength',\n ],\n select: ['value', 'required', 'multiple'],\n option: ['selected', 'value'],\n video: ['muted', 'autoplay', 'controls', 'loop', 'playsinline'],\n audio: ['muted', 'autoplay', 'controls', 'loop'],\n img: ['src', 'alt', 'width', 'height'],\n button: ['type', 'name', 'value', 'autofocus', 'form'],\n };\n\n const lname = tagName.toLowerCase();\n const promotable = nativePromoteMap[lname] ?? [];\n\n if (vnodeProps.attrs) {\n for (const propName of promotable) {\n if (\n boundList &&\n boundList.includes(propName) &&\n propName in vnodeProps.attrs &&\n !(vnodeProps.props && propName in vnodeProps.props)\n ) {\n let attrValue = vnodeProps.attrs[propName];\n // Unwrap reactive state objects during promotion\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as { value: unknown }).value; // This triggers dependency tracking\n // Promote the unwrapped primitive value\n vnodeProps.props[propName] = attrValue;\n delete vnodeProps.attrs[propName];\n } else if (\n attrValue &&\n typeof attrValue === 'object' &&\n 'value' in (attrValue as Record<string, unknown>) &&\n !(attrValue instanceof Node)\n ) {\n // Support simple wrapper objects that carry a `value` property\n // (for example useProps/ref-like wrappers that aren't our\n // ReactiveState instances). Promote their inner primitive\n // value for native element properties such as <select>.value.\n try {\n const unwrapped = (attrValue as { value: unknown }).value;\n // For native select/option values prefer string primitives so\n // the DOM <select>.value matches option values exactly.\n vnodeProps.props[propName] =\n (lname === 'select' || lname === 'option') &&\n propName === 'value'\n ? String(unwrapped)\n : unwrapped;\n delete vnodeProps.attrs[propName];\n } catch {\n void 0;\n }\n } else {\n // Only promote primitive values to native element properties.\n // For most attributes we accept string/number/boolean/empty-string\n // but for boolean-like attributes such as `disabled` be more\n // conservative: only promote when the value is a real boolean,\n // an explicit empty-string (attribute presence), or the\n // literal strings 'true'/'false'. This avoids promoting other\n // non-boolean strings which could be misinterpreted as\n // truthy and accidentally enable native controls.\n const t = typeof attrValue;\n if (propName === 'disabled') {\n const isBoolStr =\n t === 'string' &&\n (attrValue === 'true' || attrValue === 'false');\n const shouldPromote =\n attrValue === '' ||\n t === 'boolean' ||\n isBoolStr ||\n attrValue == null ||\n t === 'number';\n if (shouldPromote) {\n vnodeProps.props[propName] = attrValue;\n // DEV INSTRUMENTATION: record compiler-time promotions of disabled\n // (dev instrumentation removed)\n delete vnodeProps.attrs[propName];\n } else {\n // leave complex objects/unknown strings in attrs so the\n // runtime can make a safer decision when applying props\n }\n } else {\n if (\n attrValue === '' ||\n t === 'string' ||\n t === 'number' ||\n t === 'boolean' ||\n attrValue == null\n ) {\n // Coerce select/option `value` to string to avoid mismatch\n const promoted =\n (lname === 'select' || lname === 'option') &&\n propName === 'value'\n ? String(attrValue)\n : attrValue;\n vnodeProps.props[propName] = promoted;\n delete vnodeProps.attrs[propName];\n } else {\n // leave complex objects in attrs so the runtime can decide how\n // to apply them (for example, :bind object form or custom handling)\n }\n }\n }\n }\n }\n }\n // If this looks like a custom element (hyphenated tag), promote all bound attrs to props\n const isCustom =\n tagName.includes('-') ||\n Boolean(\n (\n effectiveContext as { __customElements?: Set<string> }\n )?.__customElements?.has?.(tagName),\n );\n if (isCustom) {\n // Always mark custom elements, regardless of bound attributes\n vnodeProps.isCustomElement = true;\n\n if (boundList && vnodeProps.attrs) {\n // Preserve attributes that may be used for stable key generation\n const keyAttrs = new Set(['id', 'name', 'data-key', 'key']);\n for (const b of boundList) {\n if (\n b in vnodeProps.attrs &&\n !(vnodeProps.props && b in vnodeProps.props)\n ) {\n // Convert kebab-case to camelCase for JS property names on custom elements\n const camel = b.includes('-') ? toCamel(b) : b;\n const attrValue = vnodeProps.attrs[b];\n // Preserve ReactiveState instances for custom elements so the\n // runtime can assign the live ReactiveState to the element\n // property (children using useProps will read .value). Do not\n // unwrap here; let the renderer/runtime decide how to apply.\n vnodeProps.props[camel] = attrValue;\n // Preserve potential key attributes in attrs to avoid unstable keys\n // For custom elements, preserve host-visible class-like attributes\n // so that compile-time HTML serialization (shadowRoot.innerHTML)\n // contains utility-class tokens for the JIT extractor. We treat\n // the following as class-like and attempt to keep them in attrs:\n // - `class`\n // - any camelCase that ends with `Class` (e.g. activeClass)\n // - any kebab-case that ends with `-class` (e.g. active-class)\n const preserveInAttrs = keyAttrs.has(b) || isClassLikeAttr(b);\n if (preserveInAttrs) {\n try {\n const serialized = safeSerializeAttr(vnodeProps.attrs[b]);\n if (serialized === null) delete vnodeProps.attrs[b];\n else vnodeProps.attrs[b] = serialized as string;\n } catch {\n delete vnodeProps.attrs[b];\n }\n } else {\n delete vnodeProps.attrs[b];\n }\n }\n }\n }\n // Ensure common model-binding attribute forms are available as\n // JS props on custom elements even when they were passed as\n // attributes (for example :model-value=\"...\" -> attrs['model-value']).\n // This helps ensure consistent behavior for `:model-value` (bind)\n // usage where downstream component expects a `modelValue` prop.\n try {\n if (\n vnodeProps.attrs &&\n !(vnodeProps.props && 'modelValue' in vnodeProps.props)\n ) {\n const mv =\n (vnodeProps.attrs as Record<string, unknown>)['model-value'] ??\n (vnodeProps.attrs as Record<string, unknown>)['modelValue'];\n if (typeof mv !== 'undefined') vnodeProps.props.modelValue = mv;\n }\n } catch {\n void 0;\n }\n }\n } catch {\n // Best-effort; ignore failures to keep runtime robust.\n }\n\n // Compiler-side canonical transform: convert :model and :model:prop on\n // custom elements into explicit prop + event handler so runtime hosts\n // that don't process directives can still work. Support multiple\n // :model variants on the same tag by iterating directive keys.\n if (\n directives &&\n Object.keys(directives).some(\n (k) => k === 'model' || k.startsWith('model:'),\n )\n ) {\n try {\n const GLOBAL_REG_KEY = Symbol.for('cer.registry');\n const globalRegistry = (globalThis as { [key: symbol]: unknown })[\n GLOBAL_REG_KEY\n ] as Set<string> | Map<string, unknown> | undefined;\n const isInGlobalRegistry = Boolean(\n globalRegistry &&\n typeof globalRegistry.has === 'function' &&\n globalRegistry.has(tagName),\n );\n\n const ctx = effectiveContext as\n | ({\n __customElements?: Set<string>;\n __isCustomElements?: string[];\n } & Record<string, unknown>)\n | undefined;\n\n const isInContext = Boolean(\n ctx &&\n ((ctx.__customElements instanceof Set &&\n ctx.__customElements.has(tagName)) ||\n (Array.isArray(ctx.__isCustomElements) &&\n ctx.__isCustomElements.includes(tagName))),\n );\n\n const isHyphenated = tagName.includes('-');\n\n const isCustomFromContext = Boolean(\n isHyphenated || isInContext || isInGlobalRegistry,\n );\n\n if (isCustomFromContext) {\n for (const dk of Object.keys(directives)) {\n if (dk !== 'model' && !dk.startsWith('model:')) continue;\n const model = directives[dk] as {\n value: unknown;\n modifiers: string[];\n arg?: string;\n };\n const arg =\n model.arg ??\n (dk.includes(':') ? dk.split(':', 2)[1] : undefined);\n const modelVal = model.value;\n\n const argToUse = arg ?? 'modelValue';\n\n const getNested = getNestedValue;\n const setNested = setNestedValue;\n\n const actualState =\n (effectiveContext as { _state?: unknown } | undefined)\n ?._state ||\n (effectiveContext as Record<string, unknown> | undefined);\n\n let initial: unknown = undefined;\n if (typeof modelVal === 'string' && actualState) {\n initial = getNested(\n actualState as Record<string, unknown>,\n modelVal,\n );\n } else {\n initial = modelVal;\n // Unwrap reactive state objects\n // Keep ReactiveState objects intact for runtime so children\n // receive the ReactiveState instance instead of an unwrapped\n // plain object. The runtime knows how to handle ReactiveState\n // when applying props/attrs.\n }\n\n vnodeProps.props[argToUse] = initial;\n\n try {\n const attrName = toKebab(argToUse);\n if (!vnodeProps.attrs) vnodeProps.attrs = {};\n // Only set attributes for primitive values; skip objects/refs\n if (\n initial !== undefined &&\n initial !== null &&\n (typeof initial === 'string' ||\n typeof initial === 'number' ||\n typeof initial === 'boolean')\n ) {\n vnodeProps.attrs[attrName] = initial;\n }\n } catch {\n /* best-effort */\n }\n\n vnodeProps.isCustomElement = true;\n\n const eventName = `update:${toKebab(argToUse)}`;\n // Convert kebab-case event name to camelCase handler key\n const camelEventName = eventName.replace(\n /-([a-z])/g,\n (_, letter) => letter.toUpperCase(),\n );\n const handlerKey =\n 'on' +\n camelEventName.charAt(0).toUpperCase() +\n camelEventName.slice(1);\n\n vnodeProps.props[handlerKey] = function (\n ev: Event & { detail?: unknown },\n ) {\n const newVal =\n (ev as { detail?: unknown }).detail !== undefined\n ? (ev as { detail?: unknown }).detail\n : ev.target\n ? (ev.target as { value?: unknown }).value\n : undefined;\n if (!actualState) return;\n\n // Handle reactive state objects (functional API)\n if (modelVal && isReactiveState(modelVal)) {\n // Compiled handler: update reactive modelVal when event received\n const current = modelVal.value;\n const changed =\n Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !==\n JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n modelVal.value = newVal;\n try {\n const eff = effectiveContext as\n | Record<string, unknown>\n | undefined;\n if (eff) {\n const rr = (eff as { requestRender?: unknown })\n .requestRender;\n const _rr = (eff as { _requestRender?: unknown })\n ._requestRender;\n if (typeof rr === 'function') (rr as () => void)();\n else if (typeof _rr === 'function')\n (_rr as () => void)();\n }\n } catch {\n void 0;\n }\n }\n } else {\n // Legacy string-based state handling\n const current = getNested(\n (actualState as Record<string, unknown>) || {},\n typeof modelVal === 'string' ? modelVal : String(modelVal),\n );\n const changed =\n Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !==\n JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n setNested(\n (actualState as Record<string, unknown>) || {},\n typeof modelVal === 'string'\n ? modelVal\n : String(modelVal),\n newVal,\n );\n try {\n const eff = effectiveContext as\n | Record<string, unknown>\n | undefined;\n if (eff) {\n const rr = (eff as { requestRender?: unknown })\n .requestRender;\n const _rr = (eff as { _requestRender?: unknown })\n ._requestRender;\n if (typeof rr === 'function') (rr as () => void)();\n else if (typeof _rr === 'function')\n (_rr as () => void)();\n }\n } catch {\n void 0;\n }\n }\n }\n };\n\n delete directives[dk];\n }\n }\n } catch {\n // ignore transform errors and fall back to runtime directive handling\n }\n }\n\n // Process built-in directives that should be converted to props/attrs\n // Only attach directives to VNode; normalization/merging is handled in vdom.ts\n if (Object.keys(directives).length > 0) {\n vnodeProps.directives = { ...directives };\n }\n\n if (isClosing) {\n // If there are any non-text children (elements, anchors, raw), we\n // will trim incidental whitespace-only text nodes that result from\n // template indentation/newlines only at the boundaries (leading\n // and trailing). This avoids turning indentation into real text\n // nodes while preserving interior whitespace that may be used as\n // separators between interpolations.\n const hasNonTextChild = currentChildren.some(\n (c) => typeof c === 'object' && (c as VNode).tag !== '#text',\n );\n\n let effectiveChildren = currentChildren;\n if (hasNonTextChild && currentChildren.length > 0) {\n // Trim leading whitespace-only text nodes\n let start = 0;\n while (start < currentChildren.length) {\n const node = currentChildren[start];\n if (\n !isElementVNode(node) ||\n node.tag !== '#text' ||\n typeof node.children !== 'string' ||\n node.children.trim() !== ''\n ) {\n break;\n }\n start++;\n }\n\n // Trim trailing whitespace-only text nodes\n let end = currentChildren.length - 1;\n while (end >= 0) {\n const node = currentChildren[end];\n if (\n !isElementVNode(node) ||\n node.tag !== '#text' ||\n typeof node.children !== 'string' ||\n node.children.trim() !== ''\n ) {\n break;\n }\n end--;\n }\n\n if (start === 0 && end === currentChildren.length - 1) {\n effectiveChildren = currentChildren;\n } else if (start > end) {\n effectiveChildren = [];\n } else {\n effectiveChildren = currentChildren.slice(start, end + 1);\n }\n }\n\n const node = h(\n currentTag!,\n currentProps,\n effectiveChildren.length === 1 &&\n isElementVNode(effectiveChildren[0]) &&\n effectiveChildren[0].tag === '#text'\n ? typeof effectiveChildren[0].children === 'string'\n ? effectiveChildren[0].children\n : ''\n : effectiveChildren.length\n ? effectiveChildren\n : undefined,\n currentKey,\n );\n const prev = stack.pop();\n if (prev) {\n currentTag = prev.tag;\n currentProps = prev.props;\n currentKey = prev.key;\n currentChildren = prev.children;\n currentChildren.push(node);\n } else {\n // If there is no previous tag, this is a root-level node\n fragmentChildren.push(node);\n currentTag = null;\n currentProps = {};\n currentKey = undefined;\n currentChildren = [];\n }\n } else if (isSelfClosing) {\n const key = undefined;\n // Always push self-closing tags to fragmentChildren if not inside another tag\n if (currentTag) {\n currentChildren.push(h(tagName, vnodeProps, undefined, key));\n } else {\n fragmentChildren.push(h(tagName, vnodeProps, undefined, key));\n }\n } else {\n if (currentTag) {\n stack.push({\n tag: currentTag,\n props: currentProps,\n children: currentChildren,\n key: currentKey,\n });\n }\n currentTag = tagName;\n currentProps = vnodeProps;\n currentChildren = [];\n }\n } else if (typeof match[3] !== 'undefined') {\n // Standalone interpolation marker {{N}}\n const idx = Number(match[3]);\n const val = values[idx];\n const baseKey = `interp-${idx}`;\n pushInterpolation(val, baseKey);\n } else if (match[4]) {\n // Plain text (may contain embedded interpolation markers like \"...{{N}}...\")\n const text = match[4];\n\n const targetChildren = currentTag ? currentChildren : fragmentChildren;\n\n // Split text by embedded markers and handle parts\n const parts = text.split(/({{\\d+}})/);\n for (const part of parts) {\n if (!part) continue;\n\n const interp = part.match(/^{{(\\d+)}}$/);\n if (interp) {\n const idx = Number(interp[1]);\n const val = values[idx];\n const baseKey = `interp-${idx}`;\n pushInterpolation(val, baseKey);\n } else {\n const key = `text-${nodeIndex++}`;\n // This branch is for literal template text (not interpolation markers)\n // so decode entity sequences here.\n targetChildren.push(decodedTextVNode(part, key));\n }\n }\n }\n }\n\n // Normalize output: prefer array for true multi-root, single node for single root\n if (root) {\n // If root is an anchor block or element, return as-is\n return root;\n }\n\n // Filter out empty text nodes and whitespace-only nodes\n const cleanedFragments = fragmentChildren.filter((child): child is VNode => {\n if (isElementVNode(child)) {\n if (child.tag === '#text') {\n return (\n typeof child.children === 'string' && child.children.trim() !== ''\n );\n }\n return true;\n }\n // Always keep anchor blocks and non-element nodes\n return true;\n });\n\n // Transform nodes with :when directive into anchor blocks\n const transformedFragments = cleanedFragments.map((child) =>\n transformWhenDirective(child),\n );\n\n if (transformedFragments.length === 1) {\n // Single non-empty root node\n const out = transformedFragments[0];\n if (canCache && cacheKey) TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n return out;\n } else if (transformedFragments.length > 1) {\n // True multi-root: return array\n const out = transformedFragments;\n if (canCache && cacheKey) {\n TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n }\n return out;\n }\n\n // Fallback for empty content\n return h('div', {}, '', 'fallback-root');\n}\n\n/**\n * Clear the template compile cache (useful for tests)\n */\nexport function clearTemplateCompileCache(): void {\n TEMPLATE_COMPILE_CACHE.clear();\n}\n\n/**\n * Default export: plain html.\n */\nexport function html(\n strings: TemplateStringsArray,\n ...values: unknown[]\n): VNode | VNode[] {\n // If last value is a context object, use it\n const last = values[values.length - 1];\n const context =\n typeof last === 'object' && last && !Array.isArray(last)\n ? (last as Record<string, unknown>)\n : undefined;\n\n return htmlImpl(strings, values, context);\n}\n"],"names":["initWatchers","context","watchers","watchConfig","key","config","callback","options","getNestedValue","currentValue","error","devError","triggerWatchers","path","newValue","isEqual","a","b","val","i","objA","objB","keysA","keysB","watcher","watchPath","watcherConfig","parseProp","type","applyPropsFromDefinitions","element","propDefinitions","def","kebab","toKebab","attr","propValue","applyProps","cfg","declared","keys","existing","hostVal","ret","isReactiveState","handleConnected","isMounted","setMounted","handleDisconnected","listeners","clearListeners","clearWatchers","setTemplateLoading","setTemplateError","unsub","handleAttributeChanged","name","oldValue","SecureExpressionEvaluator","expression","cached","devWarn","evaluator","firstKey","pattern","trimmedExpr","propertyPath","objectContent","properties","result","value","content","parts","part","colonIndex","cleanKey","processedExpression","stringLiterals","m","ctxMatches","match","placeholderIndex","dottedRegex","dottedMatches","identRegex","seen","ident","repl","_","idx","expr","tokens","pos","peek","consume","expected","t","parseExpression","parseTernary","toNumber","v","n","addValues","subValues","mulValues","divValues","modValues","compareValues","op","sa","sb","cond","parseLogicalOr","p","thenExpr","elseExpr","left","parseLogicalAnd","right","parseEquality","parseComparison","parseAdditive","parseMultiplicative","parseUnary","p1","parsePrimary","arr","p2","input","re","raw","EventManager","event","handler","meta","list","cleanups","hasValueChanged","updateStateValue","isReactive","arg","unwrapped","updated","actualState","setNestedValue","triggerStateUpdate","watchKey","emitUpdateEvents","target","propName","customEventNameKebab","customEventNameCamel","customEventKebab","customEventCamel","syncElementWithState","propToSet","safe","serialized","safeSerializeAttr","getCurrentStateValue","splitClasses","classString","addClasses","el","classes","newClasses","cls","removeClasses","validClasses","stylesLoadedOnce","waitForStyles","_classesToCheck","maxAttempts","computed","hasTransform","hasOpacity","resolve","getTransitionDuration","computedStyle","duration","delay","parseDuration","num","waitForTransition","expectedDuration","resolved","done","onTransitionEnd","performEnterTransition","transitionMeta","hooks","css","e","fn","enterFromClasses","enterActiveClasses","enterToClasses","manualDone","promise","fromTransform","fromOpacity","transitionDuration","performLeaveTransition","leaveFromClasses","leaveActiveClasses","leaveToClasses","nodeKeyMap","elementTransitionMap","getNodeKey","node","wm","nodeWithKey","setNodeKey","s","getElementTransition","elWithTransition","setElementTransition","hasValueProp","unwrapValue","isNativeControl","coerceBooleanForNative","cleanupRefs","refs","refKey","children","assignRef","vnode","reactiveRef","rk","processModelDirective","modifiers","props","attrs","hasLazy","hasTrim","hasNumber","getCurrentValue","actualContext","inputType","isNativeInput","trueValue","option","attrName","eventType","eventListener","_proc","isTestEnv","fresh","trueV","falseV","o","currentStateValue","oldListener","eventNameKebab","eventNameCamel","detail","newVal","userKeys","k","nestedKey","nestedKeyStr","nestedKebab","nestedCamel","host","eventNameFromKey","rest","processBindDirective","isWrapper","evaluated","evaluateExpression","processShowDirective","isVisible","currentStyle","newStyle","styleRules","rule","displayIndex","processClassDirective","classValue","maybe","className","condition","existingClasses","isBooleanishForProps","inner","it","processStyleDirective","styleValue","styleString","property","kebabProperty","needsPx","cssValue","existingStyle","processRefDirective","resolvedValue","processDirectives","directives","vnodeAttrs","directiveName","directive","runtimeArg","candidate","isReactiveVal","w","assignKeysDeep","nodeOrNodes","baseKey","usedKeys","child","tagPart","idPart","uniqueKey","counter","patchProps","oldProps","newProps","newDirectives","processedDirectives","mergedProps","mergedAttrs","oldPropProps","newPropProps","elIsCustom","anyChange","oldVal","oldUnwrapped","newUnwrapped","coerced","ev","propVal","candidateKeys","nestedEvent","nestedHandler","nestedNew","listener","parentEl","oldAttrs","newAttrs","final","isSVG","isClassLikeAttr","camelKey","toCamel","hostObj","propCandidate","sourceVal","hasDisabledInProcessed","isBooleanish","finalDisabled","maybeEl","createElement","textNode","html","anchorVNode","start","end","frag","childNode","childVNode","hostClass","serializedHostClass","unwrappedVal","altEventType","prop","camel","vnodeIsCustom","assignValue","vnodeWithProcessedProps","attrCandidate","patchChildren","parent","oldChildren","newChildren","oldNodeList","oldNodesCache","oldVNodes","transitionGroup","stripKeyPrefix","flattenedNew","flattenedOldVNodes","anchorChildren","anchorChild","actualKey","oldVNode","c","oldVNodeByKeyFlat","oldNodeByKeyFlat","nodeKey","usedFlat","positionsBefore","hadPreviousContent","rect","nodesToProcess","newVNode","patched","patch","keyStr","shouldAnimate","err","leaveTransitions","leavePromise","currentPosition","elementsToAnimate","isNew","oldPos","newPos","deltaX","deltaY","moveClasses","moveClassStr","durationMatch","easingMatch","easing","cleanup","oldVNodeByKey","oldNodeByKey","usedNodes","nextSibling","markRangeUsed","cur","patchChildrenBetween","transition","oldNodesInRange","oldVNodesInRange","oldVNodeByKeyRange","oldNodeByKeyRange","isInitialVisible","usedInRange","next","commonLength","aKey","startKey","endKey","oldTransition","isStateChange","dom","placeholder","newEl","vdomRenderer","root","vnodeOrArray","prevVNode","prevDom","newDom","nodesToRemove","contextStack","renderComponent","shadowRoot","setHtmlString","setLoading","setError","applyStyle","outputOrPromise","output","renderOutput","requestRender","renderFn","lastRenderTime","renderCount","setLastRenderTime","setRenderCount","renderTimeoutId","setRenderTimeoutId","timeoutId","htmlString","styleSheet","setStyleSheet","aggregatedHtml","allEls","childHtml","jitCss","jitCSS","getBaseResetSheet","getTransitionStyleSheet","userStyle","finalStyle","sanitizeCSS","minifyCSS","sheet","r","currentComponentContext","setCurrentComponentContext","clearCurrentComponentContext","useEmit","emitCandidate","emitFn","eventName","ensureHookCallbacks","useOnConnected","useOnDisconnected","useOnAttributeChanged","useOnError","useProps","defaults","ctx","declaredKeys","localValue","kebabKey","attrValue","defaultType","fromHost","_target","hostValue","isWrapperLike","useStyle","registry","GLOBAL_REG_KEY","initGlobalRegistryIfNeeded","g","createElementClass","tag","reactiveContext","defineNonEnum","obj","eventOptions","prefix","altName","cfgToUse","args","internalValue","scheduleDOMUpdate","id","compId","safeProps","createReactive","receiver","self","fullPath","newPath","component","normalizedTag","lifecycleHooks","ictx","componentId","reactiveSystem","hookCallbacks","propsDefaults","defaultValue","discoveryContext","LRUCache","maxSize","TEMPLATE_COMPILE_CACHE","validateEventHandler","h","finalKey","isAnchorBlock","isElementVNode","ensureKey","parseProps","str","values","bound","attrRegex","rawName","rawVal","isStandalone","interpMatch","knownDirectives","nameAndModifiers","argPart","maybeDirective","modifierParts","directiveKey","originalHandler","wrappedHandler","onName","transformWhenDirective","rawWhen","whenCondition","remainingDirectives","elementVNode","transformedChildren","htmlImpl","strings","injectedContext","effectiveContext","canCache","cacheKey","textVNode","text","decodedTextVNode","decoded","decodeEntities","template","tagRegex","stack","currentChildren","currentTag","currentProps","currentKey","nodeIndex","fragmentChildren","mergeIntoCurrentProps","mm","cp","mmWith","allClasses","pushInterpolation","targetChildren","anchorKey","isUnsafeHTML","voidElements","tagName","isClosing","isSelfClosing","rawProps","rawAttrs","boundList","vnodeProps","nativePromoteMap","lname","promotable","promoted","keyAttrs","mv","globalRegistry","isInGlobalRegistry","isInContext","dk","model","modelVal","argToUse","getNested","setNested","initial","camelEventName","letter","handlerKey","current","eff","rr","_rr","hasNonTextChild","effectiveChildren","prev","interp","transformedFragments","out","last"],"mappings":"qMAYO,SAASA,GACdC,EACAC,EACAC,EACM,CACN,GAAKA,EAEL,SAAW,CAACC,EAAKC,CAAM,IAAK,OAAO,QAAQF,CAAW,EAAG,CACvD,IAAIG,EACAC,EAAwB,CAAA,EAe5B,GAbI,MAAM,QAAQF,CAAM,GACtBC,EAAWD,EAAO,CAAC,EACnBE,EAAUF,EAAO,CAAC,GAAK,CAAA,GAEvBC,EAAWD,EAGbH,EAAS,IAAIE,EAAK,CAChB,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