@jasonshimmy/custom-elements-runtime 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/custom-elements-runtime.cjs.js +9 -9
- package/dist/custom-elements-runtime.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.es.js +791 -749
- package/dist/custom-elements-runtime.es.js.map +1 -1
- package/dist/custom-elements-runtime.umd.js +10 -10
- package/dist/custom-elements-runtime.umd.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.cjs.js","sources":["../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/logger.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.ts","../src/lib/runtime/style.ts","../src/lib/runtime/render.ts","../src/lib/runtime/hooks.ts","../src/lib/runtime/component.ts","../src/lib/runtime/template-compiler.ts","../src/lib/directives.ts","../src/lib/directive-enhancements.ts","../src/lib/event-bus.ts","../src/lib/store.ts","../src/lib/router.ts"],"sourcesContent":["/**\n * Update Scheduler for batching DOM updates\n * Prevents excessive re-renders and improves performance\n */\n\nclass UpdateScheduler {\n private pendingUpdates = new Map<string, () => 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 const key = componentId || update.toString();\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 = Array.from(this.pendingUpdates.values());\n this.pendingUpdates.clear();\n this.isFlushScheduled = false;\n\n // Execute all updates in batch\n for (const update of updates) {\n try {\n update();\n } catch (error) {\n // Continue with other updates even if one fails\n if (typeof console !== 'undefined' && console.error) {\n console.error('Error in batched update:', error);\n }\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\";\n\n/**\n * Global reactive system for tracking dependencies and triggering updates\n */\nclass ReactiveSystem {\n private currentComponent: string | null = null;\n private componentDependencies = new Map<string, Set<ReactiveState<any>>>();\n private componentRenderFunctions = new Map<string, () => void>();\n // Flat storage: compound key `${componentId}:${stateIndex}` -> ReactiveState\n private stateStorage = new Map<string, ReactiveState<any>>();\n private stateIndexCounter = new Map<string, number>();\n private trackingDisabled = false;\n // Per-component last warning timestamp to throttle repeated warnings\n private lastWarningTime = new Map<string, number>();\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 this.componentRenderFunctions.set(componentId, renderFn);\n if (!this.componentDependencies.has(componentId)) {\n this.componentDependencies.set(componentId, new Set());\n }\n // reset index; state instances will be stored in `stateStorage`\n // under compound keys when created\n // Reset state index for this render\n this.stateIndexCounter.set(componentId, 0);\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 id = this.currentComponent;\n const last = this.lastWarningTime.get(id) || 0;\n const now = Date.now();\n const THROTTLE_MS = 1000; // 1 second per component\n if (now - last < THROTTLE_MS) return false;\n this.lastWarningTime.set(id, 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 // If not in component context, create standalone state\n return new ReactiveState(initialValue);\n }\n \n const componentId = this.currentComponent;\n const currentIndex = this.stateIndexCounter.get(componentId) || 0;\n const stateKey = `${componentId}:${currentIndex}`;\n\n // Increment state index for next state call\n this.stateIndexCounter.set(componentId, currentIndex + 1);\n\n if (this.stateStorage.has(stateKey)) {\n return this.stateStorage.get(stateKey)! as ReactiveState<T>;\n }\n\n const stateInstance = new ReactiveState(initialValue);\n this.stateStorage.set(stateKey, stateInstance);\n return stateInstance;\n }\n\n /**\n * Track a dependency for the current component\n */\n trackDependency(state: ReactiveState<any>): void {\n if (this.trackingDisabled) return;\n \n if (this.currentComponent) {\n this.componentDependencies.get(this.currentComponent)?.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 state.getDependents().forEach(componentId => {\n const renderFn = this.componentRenderFunctions.get(componentId);\n if (renderFn) {\n scheduleDOMUpdate(renderFn, componentId);\n }\n });\n }\n\n /**\n * Clean up component dependencies when component is destroyed\n */\n cleanup(componentId: string): void {\n const dependencies = this.componentDependencies.get(componentId);\n if (dependencies) {\n dependencies.forEach(state => state.removeDependent(componentId));\n this.componentDependencies.delete(componentId);\n }\n this.componentRenderFunctions.delete(componentId);\n // Remove any flat-stored state keys for this component\n for (const key of Array.from(this.stateStorage.keys())) {\n if (key.startsWith(componentId + ':')) this.stateStorage.delete(key);\n }\n this.stateIndexCounter.delete(componentId);\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 console.warn(\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 if (v[key]) return true;\n } catch (e) {\n // ignore and fall back\n }\n\n // Fallback for test doubles or environments without symbol tagging\n try {\n return !!(v.constructor && v.constructor.name === 'ReactiveState');\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","// 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/**\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(str: string | number | boolean): 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 \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\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 * Get nested property value from object using dot notation\n */\nimport { isReactiveState } from \"./reactive\";\n\nexport function getNestedValue(obj: any, path: string): any {\n if (typeof path === \"string\") {\n const result = path.split(\".\").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 * Development-only logging utilities\n * These are stripped out in production builds via bundler configuration\n */\n\ndeclare const process: any;\nconst isDev = typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production';\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","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, escapeHTML } from \"./helpers\";\nimport type { ComponentConfig, ComponentContext } from \"./types\";\n\nexport type PropDefinition = {\n type: StringConstructor | NumberConstructor | BooleanConstructor | FunctionConstructor;\n default?: string | number | boolean;\n};\n\nfunction parseProp(val: string, type: any) {\n if (type === Boolean) return val === \"true\";\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 Object.entries(propDefinitions).forEach(([key, def]) => {\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 JS property value when present on the instance (important\n // for runtime updates where the renderer assigns element properties\n // instead of HTML attributes). Check property first, then attribute.\n if (typeof (element as any)[key] !== 'undefined') {\n try {\n const propValue = (element as any)[key];\n // If the property value is already the correct type, use it directly\n 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] = escapeHTML(parseProp(String(propValue), def.type));\n }\n } catch (e) {\n (context as any)[key] = (element as any)[key];\n }\n } else if (attr !== null) {\n (context as any)[key] = escapeHTML(parseProp(attr, def.type));\n } else if (\"default\" in def && def.default !== undefined) {\n (context as any)[key] = escapeHTML(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<S extends object, C extends object, P extends object, T extends object>(\n element: HTMLElement,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>\n): void {\n if (!cfg.props) return;\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 if (expression.trim().startsWith('{') && expression.trim().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, (() => void)[]>();\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, options, cleanup, addedAt: Date.now() };\n\n if (!this.cleanupFunctions.has(element)) {\n // store an array of metadata objects\n this.cleanupFunctions.set(element, [] as any);\n }\n\n const list = this.cleanupFunctions.get(element) as any[];\n list.push(meta);\n // also expose metadata for backward-compatible removal routines\n (this.cleanupFunctions.get(element) 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 // Remove matching cleanup from tracking by matching the specific handler/options\n const cleanups = this.cleanupFunctions.get(element);\n if (cleanups) {\n // Each cleanup was created as a closure capturing event/handler/options;\n // we can't introspect that closure, so store a small metadata tuple instead\n // to allow precise removal. We'll convert the internal representation lazily\n // if needed: if the stored element is the old-style function, rebuild metadata.\n // New approach: store an array of objects { event, handler, options, cleanup }\n const metaList: any[] = (cleanups as any).__metaList || null;\n if (metaList) {\n const idx = metaList.findIndex(m => m.event === event && m.handler === handler && JSON.stringify(m.options) === JSON.stringify(options));\n if (idx >= 0) {\n // Remove actual cleanup function and metadata\n try { metaList[idx].cleanup(); } catch (e) { /* ignore */ }\n metaList.splice(idx, 1);\n }\n if (metaList.length === 0) {\n this.cleanupFunctions.delete(element);\n }\n } else {\n // Backwards-compat: try to find a cleanup by invoking and comparing length\n // This is best-effort only. Prefer DetailedEventManager for robust behavior.\n const index = cleanups.findIndex(() => true);\n if (index >= 0) {\n cleanups.splice(index, 1);\n if (cleanups.length === 0) this.cleanupFunctions.delete(element);\n }\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) as any[] | undefined;\n if (list) {\n const metaList = (list as any).__metaList || list;\n metaList.forEach((m: any) => {\n try {\n if (typeof m === 'function') m();\n else if (m && typeof m.cleanup === 'function') m.cleanup();\n } catch (error) {\n // Silently ignore cleanup errors to avoid breaking the cleanup process\n console.error('Error during event cleanup:', error);\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, but we can iterate and cleanup\n // Note: This is primarily for testing, as WeakMap automatically cleans up\n // when elements are garbage collected\n try {\n // We can't iterate over WeakMap, so this is more of a reset for internal state\n this.cleanupFunctions = new WeakMap();\n } catch (error) {\n console.error('Error during global cleanup:', error);\n }\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) as any[] | undefined;\n const metaList = list ? (list as any).__metaList || list : undefined;\n return !!(metaList && metaList.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) as any[] | undefined;\n const metaList = list ? (list as any).__metaList || list : undefined;\n return metaList ? metaList.length : 0;\n }\n}\n\n/**\n * Enhanced event listener tracker that stores more metadata\n * for better debugging and cleanup\n */\ninterface EventListenerMetadata {\n event: string;\n handler: EventListener;\n options?: AddEventListenerOptions;\n cleanup: () => void;\n addedAt: number; // timestamp\n}\n\nclass DetailedEventManager {\n private static listeners = new WeakMap<HTMLElement, EventListenerMetadata[]>();\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 metadata: EventListenerMetadata = {\n event,\n handler,\n options,\n cleanup: () => element.removeEventListener(event, handler, options),\n addedAt: Date.now()\n };\n \n if (!this.listeners.has(element)) {\n this.listeners.set(element, []);\n }\n \n this.listeners.get(element)!.push(metadata);\n }\n \n static removeListener(\n element: HTMLElement,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions\n ): boolean {\n const elementListeners = this.listeners.get(element);\n if (!elementListeners) return false;\n \n const index = elementListeners.findIndex(meta => \n meta.event === event && \n meta.handler === handler &&\n JSON.stringify(meta.options) === JSON.stringify(options)\n );\n \n if (index >= 0) {\n const metadata = elementListeners[index];\n metadata.cleanup();\n elementListeners.splice(index, 1);\n \n if (elementListeners.length === 0) {\n this.listeners.delete(element);\n }\n \n return true;\n }\n \n return false;\n }\n \n static cleanup(element: HTMLElement): void {\n const elementListeners = this.listeners.get(element);\n if (elementListeners) {\n elementListeners.forEach(metadata => {\n try {\n metadata.cleanup();\n } catch (error) {\n console.error(`Error cleaning up ${metadata.event} listener:`, error);\n }\n });\n this.listeners.delete(element);\n }\n }\n \n static getListenerInfo(element: HTMLElement): EventListenerMetadata[] {\n return this.listeners.get(element) || [];\n }\n \n static findStaleListeners(_maxAge: number = 300000): Array<{element: HTMLElement, listeners: EventListenerMetadata[]}> {\n const stale: Array<{element: HTMLElement, listeners: EventListenerMetadata[]}> = [];\n \n // Note: Can't iterate WeakMap, this is more for the concept\n // In practice, you'd need to track elements separately if you want this functionality\n \n return stale;\n }\n}\n\nexport { EventManager, DetailedEventManager };\nexport type { EventListenerMetadata };","/**\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 { escapeHTML, getNestedValue, setNestedValue, toKebab, toCamel } from \"./helpers\";\nimport { SecureExpressionEvaluator } from \"./secure-expression-evaluator\";\nimport { EventManager } from \"./event-manager\";\nimport { isReactiveState } from \"./reactive\";\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) return;\n if (node instanceof HTMLElement) {\n // Clean up event listeners for this element\n EventManager.cleanup(node);\n \n for (const refKey in refs) {\n if (refs[refKey] === node) {\n delete refs[refKey];\n }\n }\n // Clean up child nodes\n for (const child of Array.from(node.childNodes)) {\n cleanupRefs(child, refs);\n }\n }\n}\n\n/**\n * Assign a ref to an element, supporting both string refs and reactive state objects\n */\nfunction assignRef(\n vnode: VNode,\n element: HTMLElement,\n refs?: VDomRefs\n): void {\n if (typeof vnode === \"string\") return;\n \n const reactiveRef = vnode.props?.reactiveRef ?? (vnode.props?.props && vnode.props.props.reactiveRef);\n const refKey = 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 = value && typeof value === 'object' && 'value' in value && typeof value.value !== 'undefined';\n \n const getCurrentValue = () => {\n if (isReactiveState) {\n const unwrapped = value.value;\n // If we have an argument (like :model:name), access that property\n if (arg && typeof unwrapped === 'object' && unwrapped !== null) {\n return unwrapped[arg];\n }\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) 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 = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement;\n const defaultPropName = 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(String(el?.getAttribute(\"value\") ?? attrs?.value ?? \"\"));\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 props[propName] = currentValue;\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 = hasLazy || inputType === \"checkbox\" || inputType === \"radio\" || inputType === \"select\" ? \"change\" : \"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 = 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 HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | 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 (inputType === \"select\" && (target as HTMLSelectElement).multiple) {\n newValue = Array.from((target as HTMLSelectElement).selectedOptions).map((o) => o.value);\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 actualState = context._state || context;\n const currentStateValue = getCurrentValue();\n const changed = Array.isArray(newValue) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newValue].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newValue !== currentStateValue;\n\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n // Enhanced support for reactive state objects (functional API)\n if (isReactiveState) {\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 setNestedValue(actualState, value as string, newValue);\n }\n \n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n const watchKey = isReactiveState ? 'reactiveState' : value as string;\n context._triggerWatchers(watchKey, newValue);\n }\n \n // Emit custom event for update:* listeners (e.g., @update:model-value)\n if (target) {\n const customEventName = `update:${toKebab(propName)}`;\n const customEvent = new CustomEvent(customEventName, {\n detail: newValue,\n bubbles: true,\n composed: true\n });\n target.dispatchEvent(customEvent);\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 eventName = `update:${toKebab(propName)}`;\n // Remove existing listener to prevent memory leaks\n if (listeners[eventName]) {\n const oldListener = listeners[eventName];\n if (el) {\n EventManager.removeListener(el, eventName, oldListener);\n }\n }\n \n listeners[eventName] = (event: Event) => {\n const actualState = context._state || context;\n const newVal = (event as CustomEvent).detail !== undefined ? (event as CustomEvent).detail : (event.target as any)?.value;\n const currentStateValue = getNestedValue(actualState, value);\n const changed = Array.isArray(newVal) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newVal !== currentStateValue;\n if (changed) {\n setNestedValue(actualState, value, newVal);\n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n context._triggerWatchers(value, newVal);\n }\n \n // Update the custom element's property to maintain sync\n const target = event.target as any;\n if (target) {\n // Set the property directly on the element\n target[propName] = newVal;\n \n // Also ensure the attribute is set for proper DOM reflection\n try {\n const attrName = toKebab(propName);\n if (typeof newVal === 'boolean') {\n if (newVal) {\n target.setAttribute(attrName, 'true');\n } else {\n target.setAttribute(attrName, 'false');\n }\n } else {\n target.setAttribute(attrName, String(newVal));\n }\n } catch (e) {\n // ignore attribute setting errors\n }\n \n // Trigger component's internal property handling and re-render\n // Use queueMicrotask instead of setTimeout to avoid race conditions\n queueMicrotask(() => {\n if (typeof target._applyProps === 'function') {\n target._applyProps(target._cfg);\n }\n if (typeof target._requestRender === 'function') {\n target._requestRender();\n }\n });\n }\n }\n };\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 HTMLInputElement | HTMLTextAreaElement | 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 = Array.isArray(newVal) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newVal !== currentStateValue;\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n setNestedValue(actualState, value, newVal);\n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n context._triggerWatchers(value, newVal);\n }\n } finally {\n setTimeout(() => ((target as any)._modelUpdating = false), 0);\n }\n }\n }, 0);\n };\n }\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): 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 // This matches the original behavior expected by tests\n if (key.startsWith('data-') || key.startsWith('aria-') || key === 'class') {\n attrs[key] = val;\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 // Only put clearly HTML-only attributes in attrs\n if (key.startsWith('data-') || key.startsWith('aria-') || key === 'class') {\n attrs[key] = val;\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.split(\";\").map((rule: string) => rule.trim()).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 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 }\n classes = Object.entries(classValue)\n .filter(([, condition]) => Boolean(condition))\n .flatMap(([className]) => className.split(/\\s+/).filter(Boolean));\n }\n\n const existingClasses = attrs.class || \"\";\n const allClasses = existingClasses\n ? `${existingClasses} ${classes.join(\" \")}`.trim()\n : classes.join(\" \");\n\n if (allClasses) {\n attrs.class = allClasses;\n }\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);\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 // Add other directive cases here as needed\n }\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 = 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 = (newProps as any)?.isCustomElement ?? (oldProps as any)?.isCustomElement ?? false;\n let anyChange = false;\n for (const key in { ...oldPropProps, ...newPropProps }) {\n const oldVal = oldPropProps[key];\n const newVal = newPropProps[key];\n \n if (oldVal !== newVal) {\n anyChange = true;\n if (\n key === \"value\" &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n if (el.value !== newVal) el.value = newVal ?? \"\";\n } else if (key === \"checked\" && el instanceof HTMLInputElement) {\n el.checked = !!newVal;\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 } 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 = (newProps as any)?.isCustomElement ?? (oldProps as any)?.isCustomElement ?? false;\n if (elIsCustom || key in el) {\n try {\n (el as any)[key] = newVal;\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 }\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 (newUnwrapped === undefined || newUnwrapped === null || newUnwrapped === false) {\n el.removeAttribute(key);\n if (key === 'value') {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n try { (el as any).value = \"\"; } catch (e) {}\n } else if (el instanceof HTMLSelectElement) {\n try { (el as any).value = \"\"; } catch (e) {}\n } else if (el instanceof HTMLProgressElement) {\n try { (el as any).value = 0; } catch (e) {}\n }\n }\n if (key === 'checked' && el instanceof HTMLInputElement) {\n try { el.checked = false; } catch (e) {}\n }\n if (key === 'disabled') {\n try { (el as any).disabled = false; } catch (e) {}\n }\n } else {\n // New value present: for native controls prefer assigning .value/.checked\n if (key === 'value') {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n try { (el as any).value = newUnwrapped ?? \"\"; } catch (e) { el.setAttribute(key, String(newUnwrapped)); }\n continue;\n } else if (el instanceof HTMLSelectElement) {\n try { (el as any).value = newUnwrapped ?? \"\"; } catch (e) { /* ignore */ }\n continue;\n } else if (el instanceof HTMLProgressElement) {\n try { (el as any).value = Number(newUnwrapped); } catch (e) { /* ignore */ }\n continue;\n }\n }\n if (key === 'checked' && el instanceof HTMLInputElement) {\n try { el.checked = !!newUnwrapped; } catch (e) { /* ignore */ }\n continue;\n }\n\n // Special handling for style attribute - always use setAttribute\n if (key === 'style') {\n el.setAttribute(key, String(newUnwrapped));\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 if (elIsCustom && !isSVG && key.includes('-')) {\n const camelKey = toCamel(key);\n try {\n (el as any)[camelKey] = newUnwrapped;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n el.setAttribute(key, String(newUnwrapped));\n }\n } else if (!isSVG && key in el) {\n try { (el as any)[key] = newUnwrapped; }\n catch (e) { el.setAttribute(key, String(newUnwrapped)); }\n } else {\n el.setAttribute(key, String(newUnwrapped));\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 if (elIsCustom && anyChange) {\n try {\n if (typeof (el as any)._applyProps === 'function') {\n try { (el as any)._applyProps((el as any)._cfg); } catch (e) { /* ignore */ }\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 to keep renderer robust\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) (textNode as any).key = vnode.key; // attach key\n return textNode;\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 (start as any).key = `${anchorVNode.key}:start`;\n (end as any).key = `${anchorVNode.key}:end`;\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n\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 return frag;\n }\n\n // Standard element VNode\n const el = document.createElement(vnode.tag);\n if (vnode.key != null) (el as any).key = vnode.key; // attach key\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 // 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 if (typeof val === \"boolean\") {\n if (val) el.setAttribute(key, \"\");\n // If false, do not set attribute\n } else if (val !== undefined && val !== null) {\n // Special-case value/checked for native inputs so .value/.checked are set\n if (!isSVG && key === 'value' && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement || el instanceof HTMLProgressElement)) {\n try {\n // Progress expects numeric value\n if (el instanceof HTMLProgressElement) (el as any).value = Number(val);\n else el.value = val ?? \"\";\n } catch (e) {\n el.setAttribute(key, String(val));\n }\n } else if (!isSVG && key === 'checked' && el instanceof HTMLInputElement) {\n try {\n el.checked = !!val;\n } catch (e) {\n el.setAttribute(key, String(val));\n }\n } else if (!isSVG && key in el) {\n try {\n (el as any)[key] = val;\n } catch (e) {\n el.setAttribute(key, String(val));\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] = val;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n el.setAttribute(key, String(val));\n }\n } else {\n el.setAttribute(key, String(val));\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n el.value = propValue ?? \"\";\n } else if (key === \"checked\" && el instanceof HTMLInputElement) {\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n el.checked = !!propValue;\n } else if (key.startsWith(\"on\") && typeof val === \"function\") {\n EventManager.addListener(el, eventNameFromKey(key), val);\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.\n // Use the compiler-provided hint when available, otherwise fall back\n // to a conservative tag-name test. Prefer property assignment for\n // custom elements or when the property exists on the element.\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n if (vnodeIsCustom || key in el) {\n try {\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n (el as any)[key] = propValue;\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 (el instanceof HTMLSelectElement && mergedAttrs && mergedAttrs.hasOwnProperty('value')) {\n try {\n el.value = mergedAttrs['value'] ?? \"\";\n } catch (e) {\n // ignore\n }\n }\n } catch (e) {\n // ignore\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?: 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 const oldNodes = Array.from(parent.childNodes);\n const oldVNodes: VNode[] = Array.isArray(oldChildren) ? oldChildren : [];\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 (const node of oldNodes) {\n const k = (node as any).key;\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 ) {\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 = (node as any).key;\n if (k != null) oldNodeByKeyRange.set(k, node);\n }\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 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 next = node.nextSibling;\n }\n\n // Remove unused\n for (const node of oldNodesInRange) {\n if (!usedInRange.has(node) && parent.contains(node)) {\n parent.removeChild(node);\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 parent.insertBefore(createElement(newChildren[i], context), end);\n }\n\n // Remove extra old\n for (let i = commonLength; i < oldNodesInRange.length; i++) {\n parent.removeChild(oldNodesInRange[i]);\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 (start as any).key = startKey;\n }\n if (!end) {\n end = document.createTextNode(\"\");\n (end as any).key = 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 for (const child of children) {\n parent.insertBefore(createElement(child, context), nextSibling);\n }\n parent.insertBefore(end, nextSibling);\n } else {\n // Patch children between existing boundaries\n patchChildrenBetween(\n start as Comment,\n end as Comment,\n (oldVNodeByKey.get(aKey) as VNode)?.children as VNode[] | undefined,\n children,\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\n for (const node of oldNodes) {\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 (start as any).key = `${anchorVNode.key}:start`;\n (end as any).key = `${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 (start as any).key = `${newVNode.key}:start`;\n (end as any).key = `${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 = (oldVNode.tag && String(oldVNode.tag).includes('-')) || (newVNode.props && (newVNode.props as any).isCustomElement) || (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: { attrs: { 'data-anchor-block-root': '', key: \"__anchor_root__\" } },\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\" ? escapeHTML(vnode.children) as string : \"\";\n }\n\n if (vnode.tag === \"#anchor\") {\n const children = Array.isArray(vnode.children) ? vnode.children.filter(Boolean) : [];\n return children.map(renderToString).join(\"\");\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 // Collect other props (excluding attrs, directives, ref, key)\n let propsString = \"\";\n if (vnode.props) {\n propsString = Object.entries(vnode.props)\n .filter(([k]) => k !== \"attrs\" && k !== \"directives\" && k !== \"ref\" && k !== \"key\")\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join(\"\");\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter(Boolean).map(renderToString).join(\"\")\n : (typeof vnode.children === \"string\" ? escapeHTML(vnode.children) : vnode.children ? renderToString(vnode.children) : \"\");\n\n return `<${vnode.tag}${attrsString}${propsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * CSS template literal\n *\n * This doesn't sanitize CSS values.\n * Runtime does that for us.\n * \n * @param strings\n * @param values\n * @returns\n */\nexport function css(strings: TemplateStringsArray, ...values: unknown[]): 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 // Remove comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n // Remove unnecessary whitespace\n .replace(/\\s+/g, ' ')\n // Remove spaces around specific characters\n .replace(/\\s*([{}:;,>+~])\\s*/g, '$1')\n // Remove trailing semicolons before closing braces\n .replace(/;}/g, '}')\n // Remove leading/trailing whitespace\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 // Remove any url(javascript:...) and <script> tags\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\n/**\n * Minimal Shadow DOM reset\n */\nexport const baseReset = css`\n :host, *, ::before, ::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 ui-sans-serif, system-ui, sans-serif;\n -webkit-text-size-adjust: 100%;\n text-size-adjust: 100%;\n }\n button, input, select, textarea {\n background: transparent;\n outline: none;\n }\n textarea { resize: vertical }\n progress { vertical-align: baseline }\n button, textarea { overflow: visible }\n img, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n max-width: 100%;\n height: auto;\n }\n svg { fill: currentColor; stroke: none }\n a { text-decoration: inherit; cursor: pointer }\n button, [type=button], [type=reset], [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, ::placeholder {\n color: inherit; opacity: .5;\n }\n *:focus-visible {\n outline: 2px solid var(--color-primary-500, #3b82f6);\n outline-offset: 2px;\n }\n ol, ul { list-style: none }\n table { border-collapse: collapse }\n sub, sup {\n font-size: .75em;\n line-height: 0;\n position: relative;\n }\n sub { bottom: -.25em }\n sup { top: -.5em }\n [disabled], [aria-disabled=true] { cursor: not-allowed }\n [hidden] { display: none }\n`;\n\n/**\n * JIT CSS implementation\n */\n\ntype CSSMap = Record<string, string>;\ntype SelectorVariantMap = Record<string, (selector: string, body: string) => string>;\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\nconst fallbackHex: Record<string, ColorShades> = {\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 white: { DEFAULT: \"#ffffff\" },\n black: { DEFAULT: \"#000000\" },\n transparent: { DEFAULT: \"transparent\" },\n current: { DEFAULT: \"currentColor\" }\n};\n\nexport const colors: Record<string, 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 // Tailwind container widths\n // 3xs: 16rem => 16 / 0.25 = 64\n \"3xs\": 64,\n // 2xs: 18rem => 72\n \"2xs\": 72,\n // xs: 20rem => 80\n \"xs\": 80,\n // sm: 24rem => 96\n \"sm\": 96,\n // md: 28rem => 112\n \"md\": 112,\n // lg: 32rem => 128\n \"lg\": 128,\n // xl: 36rem => 144\n \"xl\": 144,\n // 2xl: 42rem => 168\n \"2xl\": 168,\n // 3xl: 48rem => 192\n \"3xl\": 192,\n // 4xl: 56rem => 224\n \"4xl\": 224,\n // 5xl: 64rem => 256\n \"5xl\": 256,\n // 6xl: 72rem => 288\n \"6xl\": 288,\n // 7xl: 80rem => 320\n \"7xl\": 320\n};\n\nconst generateSemanticSizeClasses = (): CSSMap => {\n const classes: CSSMap = {};\n for (const [key, value] of Object.entries(semanticSizes)) {\n classes[`max-w-${key}`] = `max-width:calc(${spacing} * ${value});`;\n classes[`min-w-${key}`] = `min-width:calc(${spacing} * ${value});`;\n classes[`w-${key}`] = `width:calc(${spacing} * ${value});`;\n classes[`max-h-${key}`] = `max-height:calc(${spacing} * ${value});`;\n classes[`min-h-${key}`] = `min-height:calc(${spacing} * ${value});`;\n classes[`h-${key}`] = `height:calc(${spacing} * ${value});`;\n }\n return classes;\n};\n\nconst generateGridClasses = (): CSSMap => {\n const classes: CSSMap = {};\n for (const key of [1,2,3,4,5,6,7,8,9,10,11,12]) {\n classes[`grid-cols-${key}`] = `grid-template-columns:repeat(${key},minmax(0,1fr));`;\n classes[`grid-rows-${key}`] = `grid-template-rows:repeat(${key},minmax(0,1fr));`;\n classes[`col-span-${key}`] = `grid-column:span ${key} / span ${key};`;\n classes[`row-span-${key}`] = `grid-row:span ${key} / span ${key};`;\n }\n return classes;\n};\n\nexport const utilityMap: CSSMap = {\n /* Display */\n block: \"display:block;\",\n inline: \"display:inline;\",\n \"inline-block\": \"display:inline-block;\",\n flex: \"display:flex;\",\n \"inline-flex\": \"display:inline-flex;\",\n grid: \"display:grid;\",\n hidden: \"display:none;\",\n\n /* Sizing & Spacing */\n \"w-full\": \"width:100%;\",\n \"w-screen\": \"width:100dvw;\",\n \"h-full\": \"height:100%;\",\n \"h-screen\": \"height:100dvw;\",\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-screen\": \"min-width:100dvw;\",\n \"min-h-screen\": \"min-height:100dvh;\",\n ...generateSemanticSizeClasses(),\n \"m-auto\": \"margin:auto;\",\n \"mx-auto\": \"margin-inline:auto;\",\n \"my-auto\": \"margin-block:auto;\",\n\n /* Overflow */\n \"overflow-auto\": \"overflow:auto;\",\n \"overflow-hidden\": \"overflow:hidden;\",\n \"overflow-visible\": \"overflow:visible;\",\n \"overflow-scroll\": \"overflow:scroll;\",\n\n /* Pointer Events */\n \"pointer-events-none\": \"pointer-events:none;\",\n \"pointer-events-auto\": \"pointer-events:auto;\",\n\n /* Accessibility */\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\n /* Grid Layout & Placement */\n ...generateGridClasses(),\n\n /* Positioning */\n absolute: \"position:absolute;\",\n relative: \"position:relative;\",\n fixed: \"position:fixed;\",\n sticky: \"position:sticky;\",\n\n /* Typography */\n \"font-bold\": \"font-weight:700;\",\n \"font-semibold\": \"font-weight:600;\",\n \"font-medium\": \"font-weight:500;\",\n \"font-light\": \"font-weight:300;\",\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 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 \"text-left\": \"text-align:left;\",\n \"text-center\": \"text-align:center;\",\n \"text-right\": \"text-align:right;\",\n \"text-xs\": \"font-size:0.75rem;line-height:calc(1 / 0.75)\",\n \"text-sm\": \"font-size:0.875rem;line-height:calc(1.25 / 0.875)\",\n \"text-base\": \"font-size:1rem;line-height:calc(1.5 / 1)\",\n \"text-lg\": \"font-size:1.125rem;line-height:calc(1.75 / 1.125)\",\n \"text-xl\": \"font-size:1.25rem;line-height:calc(1.75 / 1.25)\",\n \"text-2xl\": \"font-size:1.5rem;line-height:calc(2 / 1.5)\",\n \"text-3xl\": \"font-size:1.875rem;line-height:calc(2.25 / 1.875)\",\n \"text-4xl\": \"font-size:2.25rem;line-height:calc(2.5 / 2.25)\",\n \"text-5xl\": \"font-size:3rem;line-height:1\",\n \"text-6xl\": \"font-size:3.75rem;line-height:1\",\n \"text-7xl\": \"font-size:4.5rem;line-height:1\",\n \"text-8xl\": \"font-size:6rem;line-height:1\",\n\n /* Borders */\n border: \"border-width:1px;\",\n \"border-2\": \"border-width:2px;\",\n \"border-4\": \"border-width:4px;\",\n \"border-6\": \"border-width:6px;\",\n \"border-8\": \"border-width:8px;\",\n \"rounded-none\": \"border-radius:0;\",\n \"rounded-xs\": \"border-radius:0.125rem;\",\n \"rounded-sm\": \"border-radius:0.25rem;\",\n \"rounded-md\": \"border-radius:0.375rem;\",\n \"rounded-lg\": \"border-radius:0.5rem;\",\n \"rounded-xl\": \"border-radius:0.75rem;\",\n \"rounded-2xl\": \"border-radius:1rem;\",\n \"rounded-3xl\": \"border-radius:1.5rem;\",\n \"rounded-4xl\": \"border-radius:2rem;\",\n \"rounded-full\": \"border-radius:9999px;\",\n\n /* Shadow and effects */\n // Shadows use a CSS variable for color so color utilities can modify --ce-shadow-color\n \"shadow-none\": \"--ce-shadow-color: rgb(0 0 0 / 0);box-shadow:0 0 var(--ce-shadow-color, #0000);\",\n \"shadow-xs\": \"--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\": \"--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\": \"--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\": \"--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\": \"--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\": \"--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\n /* Text Overflow & Whitespace */\n truncate: \"overflow:hidden;text-overflow:ellipsis;white-space:nowrap;\",\n\n /* Visibility */\n \"visible\": \"visibility:visible;\",\n \"invisible\": \"visibility:hidden;\",\n\n /* Flex Grow/Shrink/Basis */\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-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-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 \"flex-col\": \"flex-direction:column;\",\n \"flex-row\": \"flex-direction:row;\",\n \"grow\": \"flex-grow:1;\",\n \"shrink\": \"flex-shrink:1;\",\n \"grow-0\": \"flex-grow:0;\",\n \"shrink-0\": \"flex-shrink:0;\",\n\n /* Font Family */\n \"font-sans\": \"font-family:ui-sans-serif,system-ui,sans-serif;\",\n \"font-serif\": \"font-family:ui-serif,Georgia,serif;\",\n \"font-mono\": \"font-family:ui-monospace,SFMono-Regular,monospace;\",\n\n /* Line Clamp (for webkit) */\n \"line-clamp-1\": \"display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-2\": \"display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-3\": \"display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-4\": \"display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;\",\n\n /* Transitions */\n transition: \"transition-property:all;transition-duration:150ms;transition-timing-function:ease-in-out;\",\n \"transition-all\": \"transition-property:all;\",\n \"transition-colors\": \"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 \"transition-none\": \"transition-property:none;\",\n\n /* Cursor */\n \"cursor-auto\": \"cursor:auto;\",\n \"cursor-default\": \"cursor:default;\",\n \"cursor-pointer\": \"cursor:pointer;\",\n \"cursor-wait\": \"cursor:wait;\",\n \"cursor-text\": \"cursor:text;\",\n \"cursor-move\": \"cursor:move;\",\n \"cursor-help\": \"cursor:help;\",\n \"cursor-not-allowed\": \"cursor:not-allowed;\",\n\n /* Z-index */\n \"z-0\": \"z-index:0;\",\n \"z-10\": \"z-index:10;\",\n \"z-20\": \"z-index:20;\",\n \"z-30\": \"z-index:30;\",\n \"z-40\": \"z-index:40;\",\n \"z-50\": \"z-index:50;\",\n};\n\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\nfunction insertPseudoBeforeCombinator(sel: string, pseudo: string): string {\n let depthSquare = 0;\n let depthParen = 0;\n for (let i = 0; i < sel.length; i++) {\n const ch = sel[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 else if (depthSquare === 0 && depthParen === 0 && (ch === \">\" || ch === \"+\" || ch === \"~\" || ch === \" \")) {\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) => `${insertPseudoBeforeCombinator(sel, \":hover\")}{${body}}`,\n focus: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus\")}{${body}}`,\n active: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":active\")}{${body}}`,\n disabled: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":disabled\")}{${body}}`,\n visited: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":visited\")}{${body}}`,\n checked: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":checked\")}{${body}}`,\n first: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":first-child\")}{${body}}`,\n last: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":last-child\")}{${body}}`,\n odd: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":nth-child(odd)\")}{${body}}`,\n even: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":nth-child(even)\")}{${body}}`,\n \"focus-within\": (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus-within\")}{${body}}`,\n \"focus-visible\": (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus-visible\")}{${body}}`,\n\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\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\n\nexport const mediaVariants: MediaVariantMap = {\n // Responsive\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 (now plain string)\n \"dark\": \"(prefers-color-scheme: dark)\"\n};\n\nexport const responsiveOrder = [\"sm\", \"md\", \"lg\", \"xl\", \"2xl\"];\n\nexport function parseSpacing(className: string): string | null {\n const negative = className.startsWith(\"-\");\n const raw = negative ? className.slice(1) : className;\n const parts = raw.split(\"-\");\n\n if (parts.length < 2) return null;\n\n const key = parts.slice(0, -1).join(\"-\");\n const numStr = parts[parts.length - 1];\n const num = parseFloat(numStr);\n\n if (Number.isNaN(num) || !spacingProps[key]) 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 hexToRgb(hex: string): string {\n const clean = hex.replace(\"#\", \"\");\n const bigint = parseInt(clean, 16);\n const r = (bigint >> 16) & 255;\n const g = (bigint >> 8) & 255;\n const b = bigint & 255;\n return `${r} ${g} ${b}`;\n}\n\nexport function parseColorClass(className: string): string | null {\n // Match bg-red-500, text-gray-200, border-blue-600, etc.\n const match = /^(bg|text|border|decoration|shadow|outline|caret|accent|fill|stroke)-([a-z]+)-?(\\d{2,3}|DEFAULT)?$/.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 // Special-case shadow: we set a CSS variable so shadow-size utilities can compose with color\n if (type === 'shadow') return `--ce-shadow-color:${colorValue};`;\n\n const 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\n const prop = propMap[type];\n if (!prop) return null;\n return `${prop}:${colorValue};`;\n}\n\nexport function parseOpacityModifier(className: string): { base: string; opacity?: number } {\n const [base, opacityStr] = className.split(\"/\");\n if (!opacityStr) return { base };\n\n const opacity = parseInt(opacityStr, 10);\n if (isNaN(opacity) || opacity < 0 || opacity > 100) return { base };\n\n return { base, opacity: opacity / 100 };\n}\n\nexport function parseColorWithOpacity(className: string): string | null {\n const { base, opacity } = parseOpacityModifier(className);\n\n // Try palette first\n const paletteRule = parseColorClass(base); // e.g., \"background-color:#ef4444;\"\n if (paletteRule) {\n if (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 return paletteRule;\n }\n\n // Try arbitrary color: [bg:#ff0000]/50\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(/#([0-9a-f]{6})/i, `rgb(${rgb} / ${opacity})`);\n }\n }\n\n return arbitraryRule;\n}\n\n/**\n * Parse opacity utility class (e.g., opacity-25)\n * Returns CSS rule string or null if not valid\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 if (value < 0 || value > 100) return null;\n return `opacity:${value / 100};`;\n}\n\n/**\n * Arbitrary value parser — supports:\n * - prop-[value]\n */\nexport function parseArbitrary(className: string): string | null {\n // 1) [prop:value] — only when \"prop\" is a valid CSS property name (not a selector)\n if (className.startsWith(\"[\") && className.endsWith(\"]\") && !className.includes(\"-[\")) {\n const inner = className.slice(1, -1).trim();\n\n // prop must be at the very start, and must be a CSS identifier (letters + hyphens)\n const m = inner.match(/^([a-zA-Z][a-zA-Z0-9-]*)\\s*:(.*)$/);\n if (m) {\n const prop = m[1].trim();\n let value = m[2].trim();\n // normalize url('...') to url(\"...\") and whole-value single-quotes to double\n value = value.replace(/url\\('\\s*([^']*?)\\s*'\\)/g, 'url(\"$1\")');\n value = value.replace(/^'([^']*)'$/g, '\"$1\"');\n return `${prop}:${value};`;\n }\n // If it didn't match a property, it's an arbitrary variant selector (e.g. [&>h2:hover]) — not a utility\n return null;\n }\n\n // 2) prop-[value] — arbitrary values for known properties\n const bracketStart = className.indexOf(\"-[\");\n const bracketEnd = className.endsWith(\"]\");\n if (bracketStart > 0 && bracketEnd) {\n const prop = className.slice(0, bracketStart);\n let value = className.slice(bracketStart + 2, -1);\n\n // Convert underscores to spaces\n value = value.replace(/_/g, \" \");\n\n // Map common abbreviations to CSS properties\n const propMap: Record<string, string> = {\n bg: \"background-color\",\n text: \"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\",\n \"border-b\": \"border-bottom\",\n \"border-l\": \"border-left\",\n \"border-r\": \"border-right\",\n \"border-x\": \"border-inline\",\n \"border-y\": \"border-block\",\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 whitespace: \"white-space\",\n select: \"user-select\",\n content: \"align-content\",\n self: \"align-self\",\n basis: \"flex-basis\",\n tracking: \"letter-spacing\",\n scroll: \"scroll-behavior\",\n weight: \"font-weight\",\n leading: \"line-height\",\n z: \"z-index\",\n };\n\n // Tailwind-like rotate behavior for arbitrary values\n if (prop === \"rotate\") {\n return `transform:rotate(${value});`;\n }\n\n const cssProp = propMap[prop] ?? prop.replace(/_/g, \"-\");\n if (cssProp && value) return `${cssProp}:${value};`;\n }\n\n return null;\n}\n\n/**\n * Parse arbitrary variant from class name.\n * Supports [attr=value]:utility or foo-[bar]:utility\n */\nexport function parseArbitraryVariant(token: string): string | null {\n // [attr=value] or [&...]\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n const inner = token.slice(1, -1);\n // If it contains &, return without brackets so & can be replaced\n return inner.includes(\"&\") ? inner : token;\n }\n\n // foo-[bar] style\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 // Escape only selector-relevant characters, not brackets\n return name.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, '\\\\$1');\n}\n\nexport function extractClassesFromHTML(html: string): string[] {\n // Match class attributes robustly by capturing the opening quote and\n // using a backreference to the same quote for the closing boundary.\n // This ensures embedded single quotes (e.g. url('/icons/mask.svg')) do\n // not prematurely terminate the match.\n const classAttrRegex = /class\\s*=\\s*(['\"])(.*?)\\1/g;\n const classList: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = classAttrRegex.exec(html))) {\n // Split on whitespace to preserve complex tokens containing colons,\n // brackets, parentheses and quotes (e.g. [mask-image:url('/icons/mask.svg')]).\n const tokens = match[2].split(/\\s+/).filter(Boolean);\n if (tokens.length) classList.push(...tokens);\n }\n return classList.filter(Boolean);\n}\n\n/**\n * JIT CSS generation with throttling and memoization.\n * Only regenerates CSS if HTML changes and enough time has passed.\n * Caches results for repeated HTML inputs.\n */\nexport const jitCssCache = new Map<string, { css: string; timestamp: number }>();\nexport const JIT_CSS_THROTTLE_MS = 16; // 60fps\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) return cached.css;\n\n const classes = extractClassesFromHTML(html);\n const seen = new Set(classes);\n\n const bucket1: string[] = [];\n const bucket2: string[] = [];\n const bucket3: string[] = [];\n const bucket4: string[] = [];\n const ruleCache: Record<string, string | null> = {};\n\n function generateRuleCached(cls: string, stripDark = false): string | null {\n const cacheKey = (stripDark ? \"dark|\" : \"\") + 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 function classify(before: string[]): number {\n const hasResponsive = before.some(t => responsiveOrder.includes(t));\n const hasDark = before.includes(\"dark\");\n if (before.length === 0) return 1;\n if (!hasResponsive && !hasDark) return 2;\n if (hasResponsive && !hasDark) return 3;\n return 4;\n }\n\n function splitVariants(input: string): string[] {\n const out: string[] = [];\n let buf = \"\";\n let depthSquare = 0;\n let depthParen = 0;\n for (let i = 0; i < input.length; i++) {\n const ch = input[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 (ch === \":\" && depthSquare === 0 && depthParen === 0) {\n out.push(buf);\n buf = \"\";\n } else {\n buf += ch;\n }\n }\n if (buf) out.push(buf);\n return out;\n }\n\n // Map Tailwind pseudo-variant tokens to their CSS pseudo class strings\n function tokenToPseudo(token: string): string | null {\n switch (token) {\n case \"hover\": return \":hover\";\n case \"focus\": return \":focus\";\n case \"active\": return \":active\";\n case \"visited\": return \":visited\";\n case \"disabled\": return \":disabled\";\n case \"checked\": return \":checked\";\n case \"first\": return \":first-child\";\n case \"last\": return \":last-child\";\n case \"odd\": return \":nth-child(odd)\";\n case \"even\": return \":nth-child(even)\";\n case \"focus-within\": return \":focus-within\";\n case \"focus-visible\": return \":focus-visible\";\n default: return null;\n }\n }\n\n function generateRule(cls: string, stripDark = false): string | null {\n const parts = splitVariants(cls);\n\n // Find base utility\n let important = false;\n const basePart = parts.find(p => {\n if (p.startsWith(\"!\")) {\n important = true;\n p = p.slice(1);\n }\n return (\n utilityMap[p] ||\n parseSpacing(p) ||\n parseOpacity(p) ||\n parseColorWithOpacity(p) ||\n parseArbitrary(p)\n );\n });\n if (!basePart) return null;\n\n const cleanBase = basePart.replace(/^!/, \"\");\n const baseRule =\n utilityMap[cleanBase] ??\n parseSpacing(cleanBase) ??\n parseOpacity(cleanBase) ??\n parseColorWithOpacity(cleanBase) ??\n parseArbitrary(cleanBase);\n\n if (!baseRule) return null;\n\n const baseIndex = parts.indexOf(basePart);\n let before = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n if (stripDark) before = before.filter(t => t !== \"dark\");\n\n const escapedClass = `.${escapeClassName(cls)}`;\n const SUBJECT = \"__SUBJECT__\";\n const body = important ? baseRule.replace(/;$/, \" !important;\") : baseRule;\n\n // Start with a SUBJECT placeholder we will replace later with the real class\n let selector = SUBJECT;\n\n // Handle structural wrappers (group/peer) first (preserve order)\n const structural: string[] = [];\n for (const token of before) {\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(SUBJECT, `.peer:${token.slice(5)}~${SUBJECT}`);\n structural.push(token);\n }\n }\n before = before.filter(t => !structural.includes(t));\n\n // Collect pseudos in left-to-right order, but don't mutate SUBJECT yet to preserve order.\n const subjectPseudos: string[] = [];\n const innerPseudos: string[] = [];\n let wrapperVariant: string | null = null;\n\n for (const token of before) {\n if (token === \"dark\" || responsiveOrder.includes(token)) continue;\n\n const variantSelector = parseArbitraryVariant(token);\n if (variantSelector) {\n wrapperVariant = variantSelector;\n continue;\n }\n\n const pseudo = tokenToPseudo(token);\n if (pseudo) {\n if (!wrapperVariant) subjectPseudos.push(pseudo);\n else innerPseudos.push(pseudo);\n continue;\n }\n\n const fn = selectorVariants[token];\n if (typeof fn === \"function\") {\n // apply structural variant immediately\n selector = fn(selector, body).split(\"{\")[0];\n }\n }\n\n // helper: insert inner pseudos into the 'post' part after the first simple selector\n function insertPseudosIntoPost(post: string, pseudos: string): string {\n if (!pseudos) return post;\n let depthSquare = 0;\n let depthParen = 0;\n // If post starts with a combinator, insert pseudos after the first simple selector\n if (post.length && (post[0] === '>' || post[0] === '+' || post[0] === '~' || post[0] === ' ')) {\n // find end of first simple selector after the combinator\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 // stop at next combinator at depth 0\n if (depthSquare === 0 && depthParen === 0 && (post[i] === '>' || post[i] === '+' || post[i] === '~' || post[i] === ' ')) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n // reached end: append pseudos at end\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 // break at first combinator at depth 0 (space, >, +, ~)\n if (depthSquare === 0 && depthParen === 0 && (ch === '>' || ch === '+' || ch === '~' || ch === ' ')) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n return post + pseudos;\n }\n\n const subjectPseudoStr = subjectPseudos.join(\"\");\n const innerPseudoStr = innerPseudos.join(\"\");\n\n // Build selector by applying wrapper if present, inserting pseudos in the right spots\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 // place subject with its pseudos where & sits\n const subjectWithPseudos = SUBJECT + subjectPseudoStr;\n // If there are no subject pseudos (nothing attached before the wrapper),\n // inner pseudos should apply to the subject. Otherwise they target the\n // element inside the wrapper (the post), so insert them into the post.\n // Preserve any structural wrappers that were applied earlier by\n // replacing the SUBJECT placeholder in the current selector.\n const currentSelector = selector;\n if (subjectPseudos.length === 0) {\n // attach inner pseudos to the subject\n selector = currentSelector.replace(SUBJECT, pre + subjectWithPseudos + innerPseudoStr + post);\n } else {\n // insert inner pseudos into post after its first simple selector\n const postWithInner = insertPseudosIntoPost(post, innerPseudoStr);\n selector = currentSelector.replace(SUBJECT, pre + subjectWithPseudos + postWithInner);\n }\n } else {\n // prefix-style wrapper like [data-open=true]\n // Insert the wrapper around the existing selector's SUBJECT so structural\n // prefixes remain on the outside.\n const currentSelector = selector;\n selector = currentSelector.replace(SUBJECT, `${wrapperVariant}${SUBJECT + subjectPseudoStr}`);\n if (innerPseudoStr) selector = selector.replace(SUBJECT, `${SUBJECT}${innerPseudoStr}`);\n }\n } else {\n // no wrapper: just attach subject and inner pseudos directly to SUBJECT\n selector = SUBJECT + subjectPseudoStr + innerPseudoStr;\n }\n\n // re-apply any previously applied structural wrappers (they were applied to the placeholder earlier)\n // At this point 'selector' is a string containing SUBJECT (or actual class replacement next).\n // Replace any remaining SUBJECT with escaped class\n selector = selector.replace(new RegExp(SUBJECT, \"g\"), escapedClass);\n\n // Emit final rule\n let rule = `${selector}{${body}}`;\n\n // Wrap in media queries\n const responsiveTokens = before.filter(t => responsiveOrder.includes(t));\n const lastResponsive = responsiveTokens.length\n ? responsiveTokens[responsiveTokens.length - 1]\n : null;\n const hasDark = before.includes(\"dark\");\n\n if (stripDark && lastResponsive) {\n rule = `@media (prefers-color-scheme: dark) and ${mediaVariants[lastResponsive]}{${rule}}`;\n } else if (stripDark) {\n rule = `@media (prefers-color-scheme: dark){${rule}}`;\n } else if (hasDark && lastResponsive) {\n rule = `@media (prefers-color-scheme: dark) and ${mediaVariants[lastResponsive]}{${rule}}`;\n } else if (hasDark) {\n rule = `@media (prefers-color-scheme: dark){${rule}}`;\n } else if (lastResponsive) {\n rule = `@media ${mediaVariants[lastResponsive]}{${rule}}`;\n }\n\n return rule;\n }\n\n // Use safe splitting in the outer loop as well\n for (const cls of seen) {\n const parts = splitVariants(cls);\n const basePart = parts.find(\n p => utilityMap[p] || parseSpacing(p) || parseOpacity(p) || parseColorWithOpacity(p) || parseArbitrary(p)\n );\n if (!basePart) continue;\n const baseIndex = parts.indexOf(basePart);\n const before = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n const bucketNum = classify(before);\n\n if (bucketNum === 4) {\n const rule = generateRuleCached(cls, true);\n if (rule) bucket4.push(rule);\n } else {\n const rule = generateRuleCached(cls);\n if (rule) {\n if (bucketNum === 1) bucket1.push(rule);\n else if (bucketNum === 2) bucket2.push(rule);\n else if (bucketNum === 3) bucket3.push(rule);\n }\n }\n }\n\n const css = [...bucket1, ...bucket2, ...bucket3, ...bucket4].join(\"\");\n jitCssCache.set(html, { css, timestamp: now });\n return css;\n}\n","import { vdomRenderer } from \"./vdom\";\nimport { minifyCSS, getBaseResetSheet, sanitizeCSS, jitCSS } from \"./style\";\nimport type { ComponentConfig, ComponentContext, VNode, Refs } from \"./types\";\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<S extends object, C extends object, P extends object, T extends object>(\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<S extends object, C extends object, P extends object, T extends object>(\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 console.warn(\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 console.error(\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 setLastRenderTime(Date.now());\n renderFn();\n setRenderTimeoutId(null);\n }, renderCount > 10 ? 100 : 0); // Add delay for rapid renders\n setRenderTimeoutId(timeoutId);\n}\n\n/**\n * Applies styles to the shadowRoot.\n */\nexport function applyStyle<S extends object, C extends object, P extends object, T extends object>(\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 const jitCss = jitCSS(htmlString);\n\n if ((!jitCss || jitCss.trim() === \"\") && !(context as any)._computedStyle) {\n setStyleSheet(null);\n shadowRoot.adoptedStyleSheets = [getBaseResetSheet()];\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 if (sheet.cssRules.length === 0 || sheet.toString() !== finalStyle) {\n sheet.replaceSync(finalStyle);\n }\n shadowRoot.adoptedStyleSheets = [getBaseResetSheet(), sheet];\n setStyleSheet(sheet);\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;\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', ({ 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: (name: string, oldValue: string | null, newValue: string | null) => void\n): void {\n if (!currentComponentContext) {\n throw new Error('useOnAttributeChanged must be called during component render');\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 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', ({ theme = 'light' }) => {\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 console.warn('Error in useStyle callback:', error);\n Object.defineProperty(currentComponentContext, '_computedStyle', {\n value: '',\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n}","import type {\n ComponentConfig,\n ComponentContext,\n Refs,\n WatcherState,\n VNode,\n} from \"./types\";\nimport { reactiveSystem } from \"./reactive\";\nimport { toKebab } 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\";\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 && 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 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>(tag: string, config: ComponentConfig<S, C, P, T>): CustomElementConstructor | { new (): object } {\n // Validate that render is provided\n if (!config.render) {\n throw new Error(\n \"Component must have a render function\",\n );\n }\n if (typeof window === \"undefined\") {\n // SSR fallback: minimal class, no DOM, no lifecycle, no \"this\"\n return class { constructor() {} };\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 // Inject refs into context (non-enumerable to avoid proxy traps)\n Object.defineProperty(reactiveContext, \"refs\", {\n value: this._refs,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject requestRender into context (non-enumerable to avoid proxy traps)\n Object.defineProperty(reactiveContext, 'requestRender', {\n value: () => this.requestRender(),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject _requestRender for backward compatibility (used by model directive)\n Object.defineProperty(reactiveContext, '_requestRender', {\n value: () => this._requestRender(),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject component ID for functional component state persistence\n Object.defineProperty(reactiveContext, '_componentId', {\n value: this._componentId,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject _triggerWatchers for model directive to trigger watchers\n Object.defineProperty(reactiveContext, '_triggerWatchers', {\n value: (path: string, newValue: any) => this._triggerWatchers(path, newValue),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // --- Apply props BEFORE wiring listeners and emit ---\n this.context = reactiveContext;\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 Object.defineProperty(this.context, \"emit\", {\n value: (eventName: string, detail?: any, options?: CustomEventInit) => {\n const ev = new CustomEvent(eventName, {\n detail,\n bubbles: true,\n composed: true,\n ...(options || {})\n });\n // DOM-first: dispatch the event and return whether it was prevented\n this.dispatchEvent(ev);\n return !ev.defaultPrevented;\n },\n writable: false,\n enumerable: false,\n configurable: false,\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 = (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n Object.keys(cfgToUse).forEach((key) => {\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[]) => fn(...args, this.context);\n }\n });\n\n this._applyComputed(cfgToUse);\n\n // Set up reactive property setters for all props to detect external changes\n if (cfgToUse.props) {\n Object.keys(cfgToUse.props).forEach((propName) => {\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(\n config,\n this.context,\n this._mounted,\n (val) => { this._mounted = val; }\n );\n });\n }\n\n disconnectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n handleDisconnected(\n config,\n this.context,\n this._listeners,\n () => { this._listeners = []; },\n () => { this._watchers.clear(); },\n (val) => { this._templateLoading = val; },\n (err) => { this._templateError = err; },\n (val) => { this._mounted = val; }\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(\n config,\n name,\n oldValue,\n newValue,\n this.context\n );\n });\n }\n\n static get observedAttributes() {\n return config.props ? Object.keys(config.props).map(toKebab) : [];\n }\n\n private _applyComputed(_cfg: ComponentConfig<S, C, P, T>) {\n // Computed properties are now handled by the computed() function and reactive system\n // This method is kept for compatibility but does nothing in the functional API\n }\n\n // --- Render ---\n private _render(cfg: ComponentConfig<S, C, P, T>) {\n this._runLogicWithinErrorBoundary(cfg, () => {\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) => { this._lastRenderTime = t; },\n (c) => { this._renderCount = c; },\n this._renderTimeoutId,\n (id) => { this._renderTimeoutId = id; }\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) => { this._styleSheet = sheet; }\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 if (cfg.onError) {\n cfg.onError(error as Error | null, this.context);\n }\n // Note: errorFallback was removed as it's handled by the functional API directly\n }\n }\n\n // --- State, props, computed ---\n private _initContext(cfg: ComponentConfig<S, C, P, T>): 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(() => self._render(cfg), self._componentId);\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 (obj.constructor && obj.constructor.name === 'ReactiveState') {\n return obj;\n }\n \n Object.keys(obj).forEach((key) => {\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(\n fullPath,\n target[prop as any]\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 ? Object.fromEntries(\n Object.entries(cfg.props).map(([key, def]) => [key, def.default])\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 only\n * component('with-props', ({ message = 'Hello' }) => {\n * return html`<div>${message}</div>`;\n * });\n * \n * // With props and hooks\n * component('my-switch', ({\n * modelValue = false,\n * label = ''\n * }, { emit, onConnected, onDisconnected }) => {\n * onConnected(() => console.log('Switch connected!'));\n * onDisconnected(() => 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 1: No parameters - simple components\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>\n): void;\n\n// Overload 2: Props only - modern recommended approach with context-based hooks\nexport function component<TProps extends Record<string, any> = {}>(\n tag: string,\n renderFn: (props: TProps) => VNode | VNode[] | Promise<VNode | VNode[]>\n): void;\n\n// Implementation\nexport function component(\n tag: string,\n renderFn: (...args: any[]) => VNode | VNode[] | Promise<VNode | VNode[]>\n): void {\n let normalizedTag = toKebab(tag);\n if (!normalizedTag.includes(\"-\")) {\n normalizedTag = `cer-${normalizedTag}`;\n }\n\n // We'll parse the function string to extract defaults (dev time only)\n let propDefaults: Record<string, any> = {};\n \n if (typeof window !== \"undefined\") {\n try {\n const fnString = renderFn.toString();\n \n // More robust parsing for destructured parameters with defaults\n const paramsMatch = fnString.match(/\\(\\s*{\\s*([^}]+)\\s*}/);\n if (paramsMatch) {\n const propsString = paramsMatch[1];\n \n // Split by comma but handle nested objects/arrays\n const propPairs = propsString.split(',').map(p => p.trim());\n \n for (const pair of propPairs) {\n // Handle \"prop = defaultValue\" pattern\n const equalIndex = pair.indexOf('=');\n if (equalIndex !== -1) {\n const key = pair.substring(0, equalIndex).trim();\n const defaultValue = pair.substring(equalIndex + 1).trim();\n \n try {\n // Parse simple default values\n if (defaultValue === 'true') propDefaults[key] = true;\n else if (defaultValue === 'false') propDefaults[key] = false;\n else if (defaultValue === '[]') propDefaults[key] = [];\n else if (defaultValue === '{}') propDefaults[key] = {};\n else if (/^\\d+$/.test(defaultValue)) propDefaults[key] = parseInt(defaultValue);\n else if (/^'.*'$/.test(defaultValue) || /^\".*\"$/.test(defaultValue)) {\n propDefaults[key] = defaultValue.slice(1, -1);\n } else {\n propDefaults[key] = defaultValue;\n }\n } catch (e) {\n propDefaults[key] = '';\n }\n } else {\n // No default value, extract just the key name (remove type annotation)\n const key = pair.split(':')[0].trim();\n if (key && !key.includes('}')) {\n propDefaults[key] = '';\n }\n }\n }\n }\n } catch (e) {\n // Fallback: no props parsing\n }\n }\n\n // Store lifecycle hooks from the render function\n let lifecycleHooks: {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (name: string, oldValue: string | null, newValue: string | null) => void;\n onError?: (error: Error) => void;\n } = {};\n\n // Create component config\n const config: ComponentConfig<{}, {}, {}, {}> = {\n // Generate props config from defaults\n props: Object.fromEntries(\n Object.entries(propDefaults).map(([key, defaultValue]) => {\n const type = typeof defaultValue === 'boolean' ? Boolean\n : typeof defaultValue === 'number' ? Number\n : typeof defaultValue === 'string' ? String\n : Function; // Use Function for complex types\n return [key, { type, default: defaultValue }];\n })\n ),\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 = (context as any)._componentId || `${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 // Check if we have prop defaults (indicates destructured parameters)\n const hasProps = Object.keys(propDefaults).length > 0;\n \n let result;\n if (hasProps) {\n // Destructured parameters detected - create fresh props object with current context values\n const freshProps: any = {};\n Object.keys(propDefaults).forEach(key => {\n freshProps[key] = (context as any)[key] ?? propDefaults[key];\n });\n result = renderFn(freshProps);\n } else {\n // No parameters expected - call with no arguments\n result = renderFn();\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 = 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 }\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 if (typeof window !== \"undefined\") {\n if (!customElements.get(normalizedTag)) {\n customElements.define(normalizedTag, createElementClass(normalizedTag, config) as CustomElementConstructor);\n }\n }\n}\n","import type { VNode } from \"./types\";\nimport { contextStack } from \"./render\";\nimport { toKebab, getNestedValue, setNestedValue } from \"./helpers\";\nimport { isReactiveState } from \"./reactive\";\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) { this.maxSize = maxSize; }\n get(key: K): V | undefined {\n const v = this.map.get(key);\n if (v === undefined) return undefined;\n // move to end\n this.map.delete(key);\n this.map.set(key, v);\n return v;\n }\n set(key: K, value: V) {\n if (this.map.has(key)) {\n this.map.delete(key);\n }\n this.map.set(key, value);\n if (this.map.size > this.maxSize) {\n // remove oldest\n const first = this.map.keys().next().value;\n if (first !== undefined) this.map.delete(first);\n }\n }\n has(key: K): boolean { return this.map.has(key); }\n clear() { this.map.clear(); }\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 console.warn(\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 console.warn(\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 console.warn(\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<string, { value: any; modifiers: string[]; arg?: string }> = {};\n const bound: string[] = [];\n\n // Match attributes with optional prefix and support for single/double quotes\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 // Interpolation detection\n const interpMatch = rawVal.match(/^{{(\\d+)}}$/);\n let value: any = 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 = [\"model\", \"bind\", \"show\", \"class\", \"style\", \"ref\"];\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 = maybeDirective === 'model' && argPart ? `model:${argPart}` : maybeDirective;\n directives[directiveKey] = {\n value,\n modifiers,\n arg: argPart,\n };\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 } 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 = 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 (modifiers.includes(\"self\") && event.target !== event.currentTarget) {\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(eventName, wrappedHandler);\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 = \"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 * 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 = 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 function textVNode(text: string, key: string): VNode {\n return h(\"#text\", {}, text, 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 mergeIntoCurrentProps(v);\n } else {\n targetChildren.push(textVNode(String(v), `${baseKey}-${i}`));\n }\n }\n return;\n }\n\n if (val !== null && typeof val === \"object\") {\n mergeIntoCurrentProps(val);\n return;\n }\n\n targetChildren.push(textVNode(String(val), baseKey));\n }\n\n const voidElements = new Set([\n 'area','base','br','col','embed','hr','img','input',\n 'link','meta','param','source','track','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 = 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(match[2] || \"\", values, effectiveContext) 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 !(vnodeProps.props && Object.prototype.hasOwnProperty.call(vnodeProps.props, 'key'))\n ) {\n try {\n vnodeProps.props.key = vnodeProps.attrs['key'];\n } catch (e) {\n // best-effort; ignore\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 const nativePromoteMap: Record<string, string[]> = {\n input: ['value', 'checked', 'disabled', 'readonly', 'required', 'placeholder', 'maxlength', 'minlength'],\n textarea: ['value', 'disabled', 'readonly', 'required', 'placeholder', 'maxlength', 'minlength'],\n select: ['value', 'disabled', 'required', 'multiple'],\n option: ['selected', 'disabled', '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', 'disabled', '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 (boundList && boundList.includes(propName) && propName in vnodeProps.attrs && !(vnodeProps.props && propName in vnodeProps.props)) {\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 }\n vnodeProps.props[propName] = attrValue;\n delete vnodeProps.attrs[propName];\n }\n }\n }\n // If this looks like a custom element (hyphenated tag), promote all bound attrs to props\n const isCustom = tagName.includes('-') || 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 (b in vnodeProps.attrs && !(vnodeProps.props && b in vnodeProps.props)) {\n // Convert kebab-case to camelCase for JS property names on custom elements\n const camel = b.includes('-') ? b.split('-').map((s, i) => i === 0 ? s : s.charAt(0).toUpperCase() + s.slice(1)).join('') : b;\n let attrValue = vnodeProps.attrs[b];\n // Unwrap reactive state objects during promotion\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as any).value; // This triggers dependency tracking\n }\n vnodeProps.props[camel] = attrValue;\n // Preserve potential key attributes in attrs to avoid unstable keys\n if (!keyAttrs.has(b)) {\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 (directives && Object.keys(directives).some(k => k === 'model' || k.startsWith('model:'))) {\n try {\n const GLOBAL_REG_KEY = Symbol.for('cer.registry');\n const globalRegistry = (globalThis as any)[GLOBAL_REG_KEY] as Set<string> | Map<string, any> | undefined;\n const isInGlobalRegistry = Boolean(globalRegistry && typeof globalRegistry.has === 'function' && globalRegistry.has(tagName));\n\n const isInContext = Boolean(\n effectiveContext && (\n ((effectiveContext as any).__customElements instanceof Set && (effectiveContext as any).__customElements.has(tagName)) ||\n (Array.isArray((effectiveContext as any).__isCustomElements) && (effectiveContext as any).__isCustomElements.includes(tagName))\n )\n );\n\n const isHyphenated = tagName.includes('-');\n\n const isCustomFromContext = Boolean(isHyphenated || isInContext || isInGlobalRegistry);\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 { value: any; modifiers: string[]; arg?: string };\n const arg = model.arg ?? (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 ? ((effectiveContext as any)._state || effectiveContext) : 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 if (initial && isReactiveState(initial)) {\n initial = (initial as any).value; // This triggers dependency tracking\n }\n }\n\n vnodeProps.props[argToUse] = initial;\n\n try {\n const attrName = toKebab(argToUse);\n if (!vnodeProps.attrs) vnodeProps.attrs = {} as any;\n if (initial !== undefined) vnodeProps.attrs[attrName] = initial;\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(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n const handlerKey = 'on' + camelEventName.charAt(0).toUpperCase() + camelEventName.slice(1);\n\n vnodeProps.props[handlerKey] = function (ev: Event & { detail?: any }) {\n const newVal = (ev as any).detail !== undefined ? (ev as any).detail : (ev.target ? (ev.target as any).value : undefined);\n if (!actualState) return;\n \n // Handle reactive state objects (functional API)\n if (modelVal && isReactiveState(modelVal)) {\n const current = modelVal.value;\n const changed = Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n modelVal.value = newVal;\n if ((effectiveContext as any)?.requestRender) (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender) (effectiveContext as any)._requestRender();\n }\n } else {\n // Legacy string-based state handling\n const current = getNested(actualState, typeof modelVal === 'string' ? modelVal : String(modelVal));\n const changed = Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n setNested(actualState, typeof modelVal === 'string' ? modelVal : String(modelVal), newVal);\n if ((effectiveContext as any)?.requestRender) (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender) (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 targetChildren.push(textVNode(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 typeof child.children === \"string\" && child.children.trim() !== \"\";\n }\n return true;\n }\n // Always keep anchor blocks and non-element nodes\n return true;\n });\n\n if (cleanedFragments.length === 1) {\n // Single non-empty root node\n const out = cleanedFragments[0];\n if (canCache && cacheKey) TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n return out;\n } else if (cleanedFragments.length > 1) {\n // True multi-root: return array\n const out = cleanedFragments;\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}","import type { VNode } from \"./runtime/types\";\n\n/* --- When --- */\nexport function when(cond: boolean, children: VNode | VNode[]): VNode {\n const anchorKey = \"when-block\"; // stable key regardless of condition\n return anchorBlock(cond ? children : [], 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[]) {\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[]];\n\nfunction whenChain(...branches: Branch[]): VNode[] {\n for (let idx = 0; idx < branches.length; idx++) {\n const [cond, content] = branches[idx];\n if (cond) return [anchorBlock(content, `whenChain-branch-${idx}`)];\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 null/undefined\n const childArray = !children\n ? []\n : Array.isArray(children)\n ? children.filter(Boolean)\n : [children].filter(Boolean);\n\n return {\n tag: \"#anchor\",\n key: anchorKey,\n children: childArray,\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 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\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'\n ? partial(state)\n : 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","/**\n * Lightweight, scalable router for Custom Elements Runtime\n * - Functional API, zero dependencies, SSR/static site compatible\n * - Integrates with createStore and lib/index.ts\n */\n\nimport { html } from './runtime/template-compiler';\nimport { component } from './runtime/component';\nimport { createStore, type Store } from './store';\nimport { devError } from './runtime/logger';\nimport { match } from './directives';\n\nexport interface RouteComponent {\n // Can be any renderable type — adjust as needed for your framework\n new (...args: any[]): any; // class components\n // OR functional components\n (...args: any[]): any;\n}\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 /**\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 class?: string;\n style: 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 interface RouteState {\n path: string;\n params: Record<string, string>;\n query: Record<string, string>;\n}\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 = (routes: Route[], path: string): { 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// 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 = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.beforeEnter) {\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 return true;\n };\n\n const runOnEnter = async (to: RouteState, from: RouteState) => {\n const matched = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.onEnter) {\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 return true;\n };\n\n const runAfterEnter = (to: RouteState, from: RouteState) => {\n const matched = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.afterEnter) {\n try {\n matched.afterEnter(to, from);\n } catch (err) {\n devError('afterEnter error', err);\n }\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\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 (typeof window !== 'undefined' && typeof document !== 'undefined' && typeof initialUrl === 'undefined') {\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\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 = routes.find(r => matchRoute([r], to.path).route !== null);\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\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/**\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 \n component('router-view', (_props = {}, hooks: any = {}) => {\n const { onConnected } = hooks;\n // Set up router subscription on component connection\n if (onConnected) {\n onConnected(() => {\n if (router && typeof router.subscribe === 'function') {\n router.subscribe(() => {\n // The component will auto-rerender when router state changes\n });\n }\n });\n }\n\n if (!router) return html`<div>Router not initialized.</div>`;\n const current = router.getCurrent();\n const { path } = current;\n const match = router.matchRoute(path);\n if (!match.route) return html`<div>Not found</div>`;\n\n // Resolve the component (supports cached async loaders)\n return router.resolveRouteComponent(match.route).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 the function returned a string tag, render that element\n if (typeof resolvedComp === 'string') return { tag: resolvedComp, props: {}, children: [] };\n // Otherwise assume it's a VNode or VNode[] and return it directly\n return resolvedComp as any;\n });\n }\n\n // Unknown component type\n return html`<div>Invalid route component</div>`;\n }).catch(() => {\n // Propagate as an invalid route component to show a clear message in the view\n return html`<div>Invalid route component</div>`;\n });\n });\n\n component('router-link', (props: {\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 class?: string;\n } = {}, _hooks = {}) => {\n const {\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 class: userClass = ''\n } = props;\n // Recalculate computed values in render\n const current = router.getCurrent();\n \n // Computed\n const isExactActive = current.path === to;\n const isActive = exact\n ? isExactActive\n : current && typeof current.path === 'string'\n ? current.path.startsWith(to)\n : false;\n const ariaCurrent = isExactActive ? `aria-current=\"${ariaCurrentValue}\"` : '';\n \n // Build class object so JIT CSS can see the literal class names.\n const userClassList = (userClass || '').split(/\\s+/).filter(Boolean);\n const userClasses: Record<string, boolean> = {};\n for (const c of userClassList) userClasses[c] = true;\n const classObject = {\n ...userClasses,\n // Also include the configurable names (may duplicate the above)\n [activeClass]: isActive,\n [exactActiveClass]: isExactActive,\n };\n \n const isButton = tag === 'button';\n const disabledAttr = disabled\n ? isButton\n ? 'disabled aria-disabled=\"true\" tabindex=\"-1\"'\n : 'aria-disabled=\"true\" tabindex=\"-1\"'\n : '';\n const externalAttr = external && (tag === 'a' || !tag)\n ? 'target=\"_blank\" rel=\"noopener noreferrer\"'\n : '';\n\n const navigate = (e: MouseEvent) => {\n if (disabled) {\n e.preventDefault();\n return;\n }\n if (external && (tag === 'a' || !tag)) {\n return;\n }\n e.preventDefault();\n if (replace) {\n router.replace(to);\n } else {\n router.push(to);\n }\n };\n \n return html`\n ${match()\n .when(isButton, html`\n <button\n part=\"button\"\n :class=\"${classObject}\"\n ${ariaCurrent}\n ${disabledAttr}\n ${externalAttr}\n @click=\"${navigate}\"\n ><slot></slot></button>\n `)\n .otherwise(html`\n <a\n part=\"link\"\n href=\"${to}\"\n :class=\"${classObject}\"\n ${ariaCurrent}\n ${disabledAttr}\n ${externalAttr}\n @click=\"${navigate}\"\n ><slot></slot></a>\n `)\n .done()}\n `;\n });\n \n return router;\n}"],"names":["UpdateScheduler","update","componentId","key","updates","error","updateScheduler","scheduleDOMUpdate","proxiedObjects","ReactiveProxyCache","obj","reactiveState","isArray","cached","handler","proxy","ProxyOptimizer","target","prop","receiver","value","args","result","onUpdate","makeReactive","inner","reactiveContext","ReactiveSystem","renderFn","id","last","now","fn","wasDisabled","initialValue","ReactiveState","currentIndex","stateKey","stateInstance","state","dependencies","reactiveSystem","newValue","ref","isReactiveState","v","computed","computedState","watch","source","callback","options","oldValue","watcherId","updateWatcher","KEBAB_CASE_CACHE","CAMEL_CASE_CACHE","HTML_ESCAPE_CACHE","MAX_CACHE_SIZE","toKebab","str","toCamel","_","letter","escapeHTML","c","getNestedValue","path","current","setNestedValue","keys","lastKey","isDev","devError","message","devWarn","initWatchers","context","watchers","watchConfig","config","currentValue","triggerWatchers","isEqual","a","b","val","i","keysA","keysB","watcher","watchPath","watcherConfig","parseProp","type","applyPropsFromDefinitions","element","propDefinitions","def","kebab","attr","propValue","applyProps","cfg","handleConnected","isMounted","setMounted","handleDisconnected","listeners","clearListeners","clearWatchers","setTemplateLoading","setTemplateError","unsub","handleAttributeChanged","name","SecureExpressionEvaluator","expression","evaluator","firstKey","pattern","propertyPath","objectContent","properties","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","cond","parseLogicalOr","thenExpr","elseExpr","left","parseLogicalAnd","right","parseEquality","parseComparison","op","parseAdditive","parseMultiplicative","parseUnary","parsePrimary","arr","input","re","raw","EventManager","event","meta","list","cleanups","metaList","index","cleanupRefs","node","refs","refKey","child","assignRef","vnode","reactiveRef","processModelDirective","modifiers","props","attrs","el","arg","hasLazy","hasTrim","hasNumber","getCurrentValue","unwrapped","inputType","isNativeInput","propName","trueValue","option","attrName","eventType","eventListener","isTestEnv","fresh","trueV","falseV","o","n","actualState","currentStateValue","updated","watchKey","customEventName","customEvent","oldListener","eventName","newVal","eventNameFromKey","rest","processBindDirective","evaluated","evaluateExpression","processShowDirective","isVisible","currentStyle","newStyle","styleRules","rule","displayIndex","processClassDirective","classValue","classes","condition","className","existingClasses","allClasses","processStyleDirective","styleValue","styleString","property","kebabProperty","needsPx","cssValue","existingStyle","processRefDirective","resolvedValue","processDirectives","directives","vnodeAttrs","directiveName","directive","runtimeArg","assignKeysDeep","nodeOrNodes","baseKey","usedKeys","tagPart","idPart","uniqueKey","counter","children","patchProps","oldProps","newProps","newDirectives","processedDirectives","mergedProps","mergedAttrs","oldPropProps","newPropProps","elIsCustom","anyChange","oldVal","ev","listener","oldAttrs","newAttrs","oldUnwrapped","newUnwrapped","isSVG","camelKey","createElement","textNode","anchorVNode","start","end","frag","childNode","vnodeWithProcessedProps","patchChildren","parent","oldChildren","newChildren","oldNodes","oldVNodes","oldVNodeByKey","oldNodeByKey","k","usedNodes","nextSibling","markRangeUsed","cur","patchChildrenBetween","oldNodesInRange","oldVNodesInRange","oldVNodeByKeyRange","oldNodeByKeyRange","usedInRange","next","newVNode","oldVNode","patch","commonLength","aKey","startKey","endKey","dom","placeholder","newEl","vdomRenderer","root","vnodeOrArray","prevVNode","prevDom","newDom","nodesToRemove","renderToString","attrsString","propsString","css","strings","values","minifyCSS","baseResetSheet","getBaseResetSheet","baseReset","sanitizeCSS","fallbackHex","colors","shades","shade","hex","spacing","semanticSizes","generateSemanticSizeClasses","generateGridClasses","utilityMap","spacingProps","insertPseudoBeforeCombinator","sel","pseudo","depthSquare","depthParen","ch","selectorVariants","body","mediaVariants","responsiveOrder","parseSpacing","negative","numStr","num","sign","hexToRgb","clean","bigint","g","parseColorClass","colorName","colorValue","parseOpacityModifier","base","opacityStr","opacity","parseColorWithOpacity","paletteRule","rgb","arbitraryRule","parseArbitrary","parseOpacity","bracketStart","bracketEnd","propMap","cssProp","parseArbitraryVariant","token","escapeClassName","extractClassesFromHTML","html","classAttrRegex","classList","jitCssCache","JIT_CSS_THROTTLE_MS","jitCSS","bucket1","bucket2","bucket3","bucket4","ruleCache","generateRuleCached","cls","stripDark","cacheKey","generateRule","classify","before","hasResponsive","hasDark","splitVariants","out","buf","tokenToPseudo","important","basePart","p","cleanBase","baseRule","baseIndex","escapedClass","SUBJECT","selector","structural","subjectPseudos","innerPseudos","wrapperVariant","variantSelector","insertPseudosIntoPost","post","pseudos","subjectPseudoStr","innerPseudoStr","pre","subjectWithPseudos","currentSelector","postWithInner","responsiveTokens","lastResponsive","bucketNum","contextStack","renderComponent","shadowRoot","setHtmlString","setLoading","setError","applyStyle","outputOrPromise","output","renderOutput","requestRender","lastRenderTime","renderCount","setLastRenderTime","setRenderCount","renderTimeoutId","setRenderTimeoutId","timeoutId","htmlString","styleSheet","setStyleSheet","jitCss","userStyle","finalStyle","sheet","currentComponentContext","setCurrentComponentContext","clearCurrentComponentContext","useEmit","emitFn","detail","ensureHookCallbacks","useOnConnected","useOnDisconnected","useOnAttributeChanged","useOnError","useStyle","computedStyle","registry","GLOBAL_REG_KEY","createElementClass","tag","cfgToUse","internalValue","err","_cfg","createReactive","self","fullPath","newPath","component","normalizedTag","propDefaults","paramsMatch","propPairs","pair","equalIndex","defaultValue","lifecycleHooks","_context","hasProps","freshProps","hookCallbacks","LRUCache","maxSize","first","TEMPLATE_COMPILE_CACHE","validateEventHandler","h","finalKey","isAnchorBlock","isElementVNode","ensureKey","parseProps","bound","attrRegex","prefix","rawName","rawVal","interpMatch","knownDirectives","nameAndModifiers","argPart","maybeDirective","modifierParts","directiveKey","attrValue","originalHandler","wrappedHandler","onName","htmlImpl","injectedContext","effectiveContext","canCache","textVNode","text","template","tagRegex","stack","currentChildren","currentTag","currentProps","currentKey","nodeIndex","fragmentChildren","mergeIntoCurrentProps","maybe","newClasses","pushInterpolation","targetChildren","anchorKey","anchorChildren","voidElements","tagName","isClosing","isSelfClosing","rawProps","rawAttrs","boundList","vnodeProps","nativePromoteMap","lname","promotable","keyAttrs","camel","s","globalRegistry","isInGlobalRegistry","isInContext","dk","model","modelVal","argToUse","getNested","setNested","initial","camelEventName","handlerKey","prev","interp","cleanedFragments","when","anchorBlock","each","render","item","itemKey","branches","whenChain","childArray","unless","whenEmpty","collection","isEmpty","whenNotEmpty","hasItems","eachWhere","predicate","filtered","originalIndex","filteredIndex","switchOnLength","cases","length","eachGroup","groupBy","renderGroup","groups","groupKey","items","groupIndex","eachPage","pageSize","currentPage","startIndex","endIndex","pageIndex","globalIndex","switchOnPromise","promiseState","whenMedia","mediaQuery","matches","responsive","whenVariants","variants","conditions","responsiveVariants","responsiveSwitch","results","breakpoint","breakpointContent","switchOn","otherwiseContent","matcher","GlobalEventBus","data","eventHandlers","resolve","unsubscribe","stats","eventBus","emit","on","off","once","listen","createStore","subscribe","getState","setState","partial","notify","parseQuery","search","matchRoute","routes","route","paramNames","regexPath","regex","params","componentCache","resolveRouteComponent","mod","useRouter","initialUrl","getLocation","store","push","replaceFn","back","runBeforeEnter","to","from","matched","r","navigate","runOnEnter","runAfterEnter","replace","loc","url","query","navigateSSR","matchRouteSSR","initRouter","router","_props","hooks","onConnected","comp","resolvedComp","_hooks","exact","activeClass","exactActiveClass","ariaCurrentValue","disabled","external","userClass","isExactActive","isActive","ariaCurrent","userClassList","userClasses","classObject","isButton","disabledAttr","externalAttr","e"],"mappings":"gFAKA,MAAMA,EAAgB,CACZ,mBAAqB,IACrB,iBAAmB,GAM3B,SAASC,EAAoBC,EAA4B,CACvD,MAAMC,EAAMD,GAAeD,EAAO,SAAA,EAClC,KAAK,eAAe,IAAIE,EAAKF,CAAM,EAE9B,KAAK,mBACR,KAAK,iBAAmB,GAGN,OAAQ,WAAmB,QAAY,KACtC,WAAmB,QAAQ,KAAK,WAAa,QAC9C,OAAO,OAAW,MAAiB,OAAe,YAAe,OAAe,SAIhG,KAAK,MAAA,EAEL,eAAe,IAAM,KAAK,OAAO,EAGvC,CAKQ,OAAc,CACpB,MAAMG,EAAU,MAAM,KAAK,KAAK,eAAe,QAAQ,EACvD,KAAK,eAAe,MAAA,EACpB,KAAK,iBAAmB,GAGxB,UAAWH,KAAUG,EACnB,GAAI,CACFH,EAAA,CACF,OAASI,EAAO,CAEV,OAAO,QAAY,KAAe,QAAQ,OAC5C,QAAQ,MAAM,2BAA4BA,CAAK,CAEnD,CAEJ,CAKA,IAAI,cAAuB,CACzB,OAAO,KAAK,eAAe,IAC7B,CACF,CAGO,MAAMC,GAAkB,IAAIN,GAK5B,SAASO,GAAkBN,EAAoBC,EAA4B,CAChFI,GAAgB,SAASL,EAAQC,CAAW,CAC9C,CC7DA,MAAMM,OAAqB,QAG3B,MAAMC,EAAmB,CACvB,OAAe,MAAQ,IAAI,QAC3B,OAAe,kBAAoB,IAAI,QACvC,OAAe,mBAAqB,IAAI,QAKxC,OAAO,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AEH,CAACV,CAAW,EAAGO,EACf,CAACN,CAAgB,EAAGK,CAAA,EAGhBM,EAAWlO,IAAQ,SACnBmO,EAAeV,EACjBS,EACE,8CACA,qCACF,GACEE,EAAeV,IAAa1N,IAAQ,KAAO,CAACA,GAC9C,4CACA,GAEEoM,EAAYiC,GAAkB,CAClC,GAAIZ,EAAU,CACZY,EAAE,eAAA,EACF,MACF,CACIX,IAAa1N,IAAQ,KAAO,CAACA,KAGjCqO,EAAE,eAAA,EACE9B,EACFO,EAAO,QAAQd,CAAE,EAEjBc,EAAO,KAAKd,CAAE,EAElB,EAEA,OAAO3R;AAAA,QACHhQ,GAAA,EACC,KAAK6jB,EAAU7T;AAAA;AAAA;AAAA,sBAGF4T,CAAW;AAAA,cACnBH,CAAW;AAAA,cACXK,CAAY;AAAA,cACZC,CAAY;AAAA,sBACJhC,CAAQ;AAAA;AAAA,SAErB,EACA,UAAU/R;AAAA;AAAA;AAAA,oBAGC2R,CAAE;AAAA,sBACAiC,CAAW;AAAA,cACnBH,CAAW;AAAA,cACXK,CAAY;AAAA,cACZC,CAAY;AAAA,sBACJhC,CAAQ;AAAA;AAAA,SAErB,EACA,MAAM;AAAA,KAEb,CAAC,EAEMU,CACT"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.cjs.js","sources":["../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/logger.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.ts","../src/lib/runtime/style.ts","../src/lib/runtime/render.ts","../src/lib/runtime/hooks.ts","../src/lib/runtime/component.ts","../src/lib/runtime/template-compiler.ts","../src/lib/directives.ts","../src/lib/directive-enhancements.ts","../src/lib/event-bus.ts","../src/lib/store.ts","../src/lib/router.ts"],"sourcesContent":["/**\n * Update Scheduler for batching DOM updates\n * Prevents excessive re-renders and improves performance\n */\n\nclass UpdateScheduler {\n private pendingUpdates = new Map<string, () => 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 const key = componentId || update.toString();\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 = Array.from(this.pendingUpdates.values());\n this.pendingUpdates.clear();\n this.isFlushScheduled = false;\n\n // Execute all updates in batch\n for (const update of updates) {\n try {\n update();\n } catch (error) {\n // Continue with other updates even if one fails\n if (typeof console !== 'undefined' && console.error) {\n console.error('Error in batched update:', error);\n }\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\";\n\n/**\n * Global reactive system for tracking dependencies and triggering updates\n */\nclass ReactiveSystem {\n private currentComponent: string | null = null;\n private componentDependencies = new Map<string, Set<ReactiveState<any>>>();\n private componentRenderFunctions = new Map<string, () => void>();\n // Flat storage: compound key `${componentId}:${stateIndex}` -> ReactiveState\n private stateStorage = new Map<string, ReactiveState<any>>();\n private stateIndexCounter = new Map<string, number>();\n private trackingDisabled = false;\n // Per-component last warning timestamp to throttle repeated warnings\n private lastWarningTime = new Map<string, number>();\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 this.componentRenderFunctions.set(componentId, renderFn);\n if (!this.componentDependencies.has(componentId)) {\n this.componentDependencies.set(componentId, new Set());\n }\n // reset index; state instances will be stored in `stateStorage`\n // under compound keys when created\n // Reset state index for this render\n this.stateIndexCounter.set(componentId, 0);\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 id = this.currentComponent;\n const last = this.lastWarningTime.get(id) || 0;\n const now = Date.now();\n const THROTTLE_MS = 1000; // 1 second per component\n if (now - last < THROTTLE_MS) return false;\n this.lastWarningTime.set(id, 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 // If not in component context, create standalone state\n return new ReactiveState(initialValue);\n }\n \n const componentId = this.currentComponent;\n const currentIndex = this.stateIndexCounter.get(componentId) || 0;\n const stateKey = `${componentId}:${currentIndex}`;\n\n // Increment state index for next state call\n this.stateIndexCounter.set(componentId, currentIndex + 1);\n\n if (this.stateStorage.has(stateKey)) {\n return this.stateStorage.get(stateKey)! as ReactiveState<T>;\n }\n\n const stateInstance = new ReactiveState(initialValue);\n this.stateStorage.set(stateKey, stateInstance);\n return stateInstance;\n }\n\n /**\n * Track a dependency for the current component\n */\n trackDependency(state: ReactiveState<any>): void {\n if (this.trackingDisabled) return;\n \n if (this.currentComponent) {\n this.componentDependencies.get(this.currentComponent)?.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 state.getDependents().forEach(componentId => {\n const renderFn = this.componentRenderFunctions.get(componentId);\n if (renderFn) {\n scheduleDOMUpdate(renderFn, componentId);\n }\n });\n }\n\n /**\n * Clean up component dependencies when component is destroyed\n */\n cleanup(componentId: string): void {\n const dependencies = this.componentDependencies.get(componentId);\n if (dependencies) {\n dependencies.forEach(state => state.removeDependent(componentId));\n this.componentDependencies.delete(componentId);\n }\n this.componentRenderFunctions.delete(componentId);\n // Remove any flat-stored state keys for this component\n for (const key of Array.from(this.stateStorage.keys())) {\n if (key.startsWith(componentId + ':')) this.stateStorage.delete(key);\n }\n this.stateIndexCounter.delete(componentId);\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 console.warn(\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 if (v[key]) return true;\n } catch (e) {\n // ignore and fall back\n }\n\n // Fallback for test doubles or environments without symbol tagging\n try {\n return !!(v.constructor && v.constructor.name === 'ReactiveState');\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","// 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/**\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(str: string | number | boolean): 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 \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\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 * Get nested property value from object using dot notation\n */\nimport { isReactiveState } from \"./reactive\";\n\nexport function getNestedValue(obj: any, path: string): any {\n if (typeof path === \"string\") {\n const result = path.split(\".\").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 * Development-only logging utilities\n * These are stripped out in production builds via bundler configuration\n */\n\ndeclare const process: any;\nconst isDev = typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production';\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","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, escapeHTML } from \"./helpers\";\nimport type { ComponentConfig, ComponentContext } from \"./types\";\n\nexport type PropDefinition = {\n type: StringConstructor | NumberConstructor | BooleanConstructor | FunctionConstructor;\n default?: string | number | boolean;\n};\n\nfunction parseProp(val: string, type: any) {\n if (type === Boolean) return val === \"true\";\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 Object.entries(propDefinitions).forEach(([key, def]) => {\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 JS property value when present on the instance (important\n // for runtime updates where the renderer assigns element properties\n // instead of HTML attributes). Check property first, then attribute.\n if (typeof (element as any)[key] !== 'undefined') {\n try {\n const propValue = (element as any)[key];\n // If the property value is already the correct type, use it directly\n 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] = escapeHTML(parseProp(String(propValue), def.type));\n }\n } catch (e) {\n (context as any)[key] = (element as any)[key];\n }\n } else if (attr !== null) {\n (context as any)[key] = escapeHTML(parseProp(attr, def.type));\n } else if (\"default\" in def && def.default !== undefined) {\n (context as any)[key] = escapeHTML(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<S extends object, C extends object, P extends object, T extends object>(\n element: HTMLElement,\n cfg: ComponentConfig<S, C, P, T>,\n context: ComponentContext<S, C, P, T>\n): void {\n if (!cfg.props) return;\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 if (expression.trim().startsWith('{') && expression.trim().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, (() => void)[]>();\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, options, cleanup, addedAt: Date.now() };\n\n if (!this.cleanupFunctions.has(element)) {\n // store an array of metadata objects\n this.cleanupFunctions.set(element, [] as any);\n }\n\n const list = this.cleanupFunctions.get(element) as any[];\n list.push(meta);\n // also expose metadata for backward-compatible removal routines\n (this.cleanupFunctions.get(element) 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 // Remove matching cleanup from tracking by matching the specific handler/options\n const cleanups = this.cleanupFunctions.get(element);\n if (cleanups) {\n // Each cleanup was created as a closure capturing event/handler/options;\n // we can't introspect that closure, so store a small metadata tuple instead\n // to allow precise removal. We'll convert the internal representation lazily\n // if needed: if the stored element is the old-style function, rebuild metadata.\n // New approach: store an array of objects { event, handler, options, cleanup }\n const metaList: any[] = (cleanups as any).__metaList || null;\n if (metaList) {\n const idx = metaList.findIndex(m => m.event === event && m.handler === handler && JSON.stringify(m.options) === JSON.stringify(options));\n if (idx >= 0) {\n // Remove actual cleanup function and metadata\n try { metaList[idx].cleanup(); } catch (e) { /* ignore */ }\n metaList.splice(idx, 1);\n }\n if (metaList.length === 0) {\n this.cleanupFunctions.delete(element);\n }\n } else {\n // Backwards-compat: try to find a cleanup by invoking and comparing length\n // This is best-effort only. Prefer DetailedEventManager for robust behavior.\n const index = cleanups.findIndex(() => true);\n if (index >= 0) {\n cleanups.splice(index, 1);\n if (cleanups.length === 0) this.cleanupFunctions.delete(element);\n }\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) as any[] | undefined;\n if (list) {\n const metaList = (list as any).__metaList || list;\n metaList.forEach((m: any) => {\n try {\n if (typeof m === 'function') m();\n else if (m && typeof m.cleanup === 'function') m.cleanup();\n } catch (error) {\n // Silently ignore cleanup errors to avoid breaking the cleanup process\n console.error('Error during event cleanup:', error);\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, but we can iterate and cleanup\n // Note: This is primarily for testing, as WeakMap automatically cleans up\n // when elements are garbage collected\n try {\n // We can't iterate over WeakMap, so this is more of a reset for internal state\n this.cleanupFunctions = new WeakMap();\n } catch (error) {\n console.error('Error during global cleanup:', error);\n }\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) as any[] | undefined;\n const metaList = list ? (list as any).__metaList || list : undefined;\n return !!(metaList && metaList.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) as any[] | undefined;\n const metaList = list ? (list as any).__metaList || list : undefined;\n return metaList ? metaList.length : 0;\n }\n}\n\n/**\n * Enhanced event listener tracker that stores more metadata\n * for better debugging and cleanup\n */\ninterface EventListenerMetadata {\n event: string;\n handler: EventListener;\n options?: AddEventListenerOptions;\n cleanup: () => void;\n addedAt: number; // timestamp\n}\n\nclass DetailedEventManager {\n private static listeners = new WeakMap<HTMLElement, EventListenerMetadata[]>();\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 metadata: EventListenerMetadata = {\n event,\n handler,\n options,\n cleanup: () => element.removeEventListener(event, handler, options),\n addedAt: Date.now()\n };\n \n if (!this.listeners.has(element)) {\n this.listeners.set(element, []);\n }\n \n this.listeners.get(element)!.push(metadata);\n }\n \n static removeListener(\n element: HTMLElement,\n event: string,\n handler: EventListener,\n options?: EventListenerOptions\n ): boolean {\n const elementListeners = this.listeners.get(element);\n if (!elementListeners) return false;\n \n const index = elementListeners.findIndex(meta => \n meta.event === event && \n meta.handler === handler &&\n JSON.stringify(meta.options) === JSON.stringify(options)\n );\n \n if (index >= 0) {\n const metadata = elementListeners[index];\n metadata.cleanup();\n elementListeners.splice(index, 1);\n \n if (elementListeners.length === 0) {\n this.listeners.delete(element);\n }\n \n return true;\n }\n \n return false;\n }\n \n static cleanup(element: HTMLElement): void {\n const elementListeners = this.listeners.get(element);\n if (elementListeners) {\n elementListeners.forEach(metadata => {\n try {\n metadata.cleanup();\n } catch (error) {\n console.error(`Error cleaning up ${metadata.event} listener:`, error);\n }\n });\n this.listeners.delete(element);\n }\n }\n \n static getListenerInfo(element: HTMLElement): EventListenerMetadata[] {\n return this.listeners.get(element) || [];\n }\n \n static findStaleListeners(_maxAge: number = 300000): Array<{element: HTMLElement, listeners: EventListenerMetadata[]}> {\n const stale: Array<{element: HTMLElement, listeners: EventListenerMetadata[]}> = [];\n \n // Note: Can't iterate WeakMap, this is more for the concept\n // In practice, you'd need to track elements separately if you want this functionality\n \n return stale;\n }\n}\n\nexport { EventManager, DetailedEventManager };\nexport type { EventListenerMetadata };","/**\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 { escapeHTML, getNestedValue, setNestedValue, toKebab, toCamel } from \"./helpers\";\nimport { SecureExpressionEvaluator } from \"./secure-expression-evaluator\";\nimport { EventManager } from \"./event-manager\";\nimport { isReactiveState } from \"./reactive\";\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) return;\n if (node instanceof HTMLElement) {\n // Clean up event listeners for this element\n EventManager.cleanup(node);\n \n for (const refKey in refs) {\n if (refs[refKey] === node) {\n delete refs[refKey];\n }\n }\n // Clean up child nodes\n for (const child of Array.from(node.childNodes)) {\n cleanupRefs(child, refs);\n }\n }\n}\n\n/**\n * Assign a ref to an element, supporting both string refs and reactive state objects\n */\nfunction assignRef(\n vnode: VNode,\n element: HTMLElement,\n refs?: VDomRefs\n): void {\n if (typeof vnode === \"string\") return;\n \n const reactiveRef = vnode.props?.reactiveRef ?? (vnode.props?.props && vnode.props.props.reactiveRef);\n const refKey = 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 = value && typeof value === 'object' && 'value' in value && typeof value.value !== 'undefined';\n \n const getCurrentValue = () => {\n if (isReactiveState) {\n const unwrapped = value.value;\n // If we have an argument (like :model:name), access that property\n if (arg && typeof unwrapped === 'object' && unwrapped !== null) {\n return unwrapped[arg];\n }\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) 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 = el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement;\n const defaultPropName = 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(String(el?.getAttribute(\"value\") ?? attrs?.value ?? \"\"));\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 props[propName] = currentValue;\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 = hasLazy || inputType === \"checkbox\" || inputType === \"radio\" || inputType === \"select\" ? \"change\" : \"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 = 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 HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | 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 (inputType === \"select\" && (target as HTMLSelectElement).multiple) {\n newValue = Array.from((target as HTMLSelectElement).selectedOptions).map((o) => o.value);\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 actualState = context._state || context;\n const currentStateValue = getCurrentValue();\n const changed = Array.isArray(newValue) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newValue].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newValue !== currentStateValue;\n\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n // Enhanced support for reactive state objects (functional API)\n if (isReactiveState) {\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 setNestedValue(actualState, value as string, newValue);\n }\n \n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n const watchKey = isReactiveState ? 'reactiveState' : value as string;\n context._triggerWatchers(watchKey, newValue);\n }\n \n // Emit custom event for update:* listeners (e.g., @update:model-value)\n if (target) {\n const customEventName = `update:${toKebab(propName)}`;\n const customEvent = new CustomEvent(customEventName, {\n detail: newValue,\n bubbles: true,\n composed: true\n });\n target.dispatchEvent(customEvent);\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 eventName = `update:${toKebab(propName)}`;\n // Remove existing listener to prevent memory leaks\n if (listeners[eventName]) {\n const oldListener = listeners[eventName];\n if (el) {\n EventManager.removeListener(el, eventName, oldListener);\n }\n }\n \n listeners[eventName] = (event: Event) => {\n const actualState = context._state || context;\n const newVal = (event as CustomEvent).detail !== undefined ? (event as CustomEvent).detail : (event.target as any)?.value;\n const currentStateValue = getNestedValue(actualState, value);\n const changed = Array.isArray(newVal) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newVal !== currentStateValue;\n if (changed) {\n setNestedValue(actualState, value, newVal);\n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n context._triggerWatchers(value, newVal);\n }\n \n // Update the custom element's property to maintain sync\n const target = event.target as any;\n if (target) {\n // Set the property directly on the element\n target[propName] = newVal;\n \n // Also ensure the attribute is set for proper DOM reflection\n try {\n const attrName = toKebab(propName);\n if (typeof newVal === 'boolean') {\n if (newVal) {\n target.setAttribute(attrName, 'true');\n } else {\n target.setAttribute(attrName, 'false');\n }\n } else {\n target.setAttribute(attrName, String(newVal));\n }\n } catch (e) {\n // ignore attribute setting errors\n }\n \n // Trigger component's internal property handling and re-render\n // Use queueMicrotask instead of setTimeout to avoid race conditions\n queueMicrotask(() => {\n if (typeof target._applyProps === 'function') {\n target._applyProps(target._cfg);\n }\n if (typeof target._requestRender === 'function') {\n target._requestRender();\n }\n });\n }\n }\n };\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 HTMLInputElement | HTMLTextAreaElement | 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 = Array.isArray(newVal) && Array.isArray(currentStateValue)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...currentStateValue].sort())\n : newVal !== currentStateValue;\n if (changed) {\n (target as any)._modelUpdating = true;\n try {\n setNestedValue(actualState, value, newVal);\n if (context._requestRender) context._requestRender();\n \n // Trigger watchers for state changes\n if (context._triggerWatchers) {\n context._triggerWatchers(value, newVal);\n }\n } finally {\n setTimeout(() => ((target as any)._modelUpdating = false), 0);\n }\n }\n }, 0);\n };\n }\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): 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 // This matches the original behavior expected by tests\n if (key.startsWith('data-') || key.startsWith('aria-') || key === 'class') {\n attrs[key] = val;\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 // Only put clearly HTML-only attributes in attrs\n if (key.startsWith('data-') || key.startsWith('aria-') || key === 'class') {\n attrs[key] = val;\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.split(\";\").map((rule: string) => rule.trim()).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 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 }\n classes = Object.entries(classValue)\n .filter(([, condition]) => Boolean(condition))\n .flatMap(([className]) => className.split(/\\s+/).filter(Boolean));\n }\n\n const existingClasses = attrs.class || \"\";\n const allClasses = existingClasses\n ? `${existingClasses} ${classes.join(\" \")}`.trim()\n : classes.join(\" \");\n\n if (allClasses) {\n attrs.class = allClasses;\n }\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);\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 // Add other directive cases here as needed\n }\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 = 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 = (newProps as any)?.isCustomElement ?? (oldProps as any)?.isCustomElement ?? false;\n let anyChange = false;\n for (const key in { ...oldPropProps, ...newPropProps }) {\n const oldVal = oldPropProps[key];\n const newVal = newPropProps[key];\n \n if (oldVal !== newVal) {\n anyChange = true;\n if (\n key === \"value\" &&\n (el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement)\n ) {\n if (el.value !== newVal) el.value = newVal ?? \"\";\n } else if (key === \"checked\" && el instanceof HTMLInputElement) {\n el.checked = !!newVal;\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 } 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 = (newProps as any)?.isCustomElement ?? (oldProps as any)?.isCustomElement ?? false;\n if (elIsCustom || key in el) {\n try {\n (el as any)[key] = newVal;\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 }\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 (newUnwrapped === undefined || newUnwrapped === null || newUnwrapped === false) {\n el.removeAttribute(key);\n if (key === 'value') {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n try { (el as any).value = \"\"; } catch (e) {}\n } else if (el instanceof HTMLSelectElement) {\n try { (el as any).value = \"\"; } catch (e) {}\n } else if (el instanceof HTMLProgressElement) {\n try { (el as any).value = 0; } catch (e) {}\n }\n }\n if (key === 'checked' && el instanceof HTMLInputElement) {\n try { el.checked = false; } catch (e) {}\n }\n if (key === 'disabled') {\n try { (el as any).disabled = false; } catch (e) {}\n }\n } else {\n // New value present: for native controls prefer assigning .value/.checked\n if (key === 'value') {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n try { (el as any).value = newUnwrapped ?? \"\"; } catch (e) { el.setAttribute(key, String(newUnwrapped)); }\n continue;\n } else if (el instanceof HTMLSelectElement) {\n try { (el as any).value = newUnwrapped ?? \"\"; } catch (e) { /* ignore */ }\n continue;\n } else if (el instanceof HTMLProgressElement) {\n try { (el as any).value = Number(newUnwrapped); } catch (e) { /* ignore */ }\n continue;\n }\n }\n if (key === 'checked' && el instanceof HTMLInputElement) {\n try { el.checked = !!newUnwrapped; } catch (e) { /* ignore */ }\n continue;\n }\n\n // Special handling for style attribute - always use setAttribute\n if (key === 'style') {\n el.setAttribute(key, String(newUnwrapped));\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 if (elIsCustom && !isSVG && key.includes('-')) {\n const camelKey = toCamel(key);\n try {\n (el as any)[camelKey] = newUnwrapped;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n el.setAttribute(key, String(newUnwrapped));\n }\n } else if (!isSVG && key in el) {\n try { (el as any)[key] = newUnwrapped; }\n catch (e) { el.setAttribute(key, String(newUnwrapped)); }\n } else {\n el.setAttribute(key, String(newUnwrapped));\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 if (elIsCustom && anyChange) {\n try {\n if (typeof (el as any)._applyProps === 'function') {\n try { (el as any)._applyProps((el as any)._cfg); } catch (e) { /* ignore */ }\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 to keep renderer robust\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) (textNode as any).key = vnode.key; // attach key\n return textNode;\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 (start as any).key = `${anchorVNode.key}:start`;\n (end as any).key = `${anchorVNode.key}:end`;\n }\n anchorVNode._startNode = start;\n anchorVNode._endNode = end;\n\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 return frag;\n }\n\n // Standard element VNode\n const el = document.createElement(vnode.tag);\n if (vnode.key != null) (el as any).key = vnode.key; // attach key\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 // 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 if (typeof val === \"boolean\") {\n if (val) el.setAttribute(key, \"\");\n // If false, do not set attribute\n } else if (val !== undefined && val !== null) {\n // Special-case value/checked for native inputs so .value/.checked are set\n if (!isSVG && key === 'value' && (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement || el instanceof HTMLProgressElement)) {\n try {\n // Progress expects numeric value\n if (el instanceof HTMLProgressElement) (el as any).value = Number(val);\n else el.value = val ?? \"\";\n } catch (e) {\n el.setAttribute(key, String(val));\n }\n } else if (!isSVG && key === 'checked' && el instanceof HTMLInputElement) {\n try {\n el.checked = !!val;\n } catch (e) {\n el.setAttribute(key, String(val));\n }\n } else if (!isSVG && key in el) {\n try {\n (el as any)[key] = val;\n } catch (e) {\n el.setAttribute(key, String(val));\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] = val;\n } catch (e) {\n // If property assignment fails, fall back to attribute\n el.setAttribute(key, String(val));\n }\n } else {\n el.setAttribute(key, String(val));\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n el.value = propValue ?? \"\";\n } else if (key === \"checked\" && el instanceof HTMLInputElement) {\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n el.checked = !!propValue;\n } else if (key.startsWith(\"on\") && typeof val === \"function\") {\n EventManager.addListener(el, eventNameFromKey(key), val);\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.\n // Use the compiler-provided hint when available, otherwise fall back\n // to a conservative tag-name test. Prefer property assignment for\n // custom elements or when the property exists on the element.\n const vnodeIsCustom = vnode.props?.isCustomElement ?? false;\n if (vnodeIsCustom || key in el) {\n try {\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 = (typeof val === \"object\" && val !== null && typeof val.value !== \"undefined\") ? val.value : val;\n (el as any)[key] = propValue;\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 (el instanceof HTMLSelectElement && mergedAttrs && mergedAttrs.hasOwnProperty('value')) {\n try {\n el.value = mergedAttrs['value'] ?? \"\";\n } catch (e) {\n // ignore\n }\n }\n } catch (e) {\n // ignore\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?: 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 const oldNodes = Array.from(parent.childNodes);\n const oldVNodes: VNode[] = Array.isArray(oldChildren) ? oldChildren : [];\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 (const node of oldNodes) {\n const k = (node as any).key;\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 ) {\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 = (node as any).key;\n if (k != null) oldNodeByKeyRange.set(k, node);\n }\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 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 next = node.nextSibling;\n }\n\n // Remove unused\n for (const node of oldNodesInRange) {\n if (!usedInRange.has(node) && parent.contains(node)) {\n parent.removeChild(node);\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 parent.insertBefore(createElement(newChildren[i], context), end);\n }\n\n // Remove extra old\n for (let i = commonLength; i < oldNodesInRange.length; i++) {\n parent.removeChild(oldNodesInRange[i]);\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 (start as any).key = startKey;\n }\n if (!end) {\n end = document.createTextNode(\"\");\n (end as any).key = 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 for (const child of children) {\n parent.insertBefore(createElement(child, context), nextSibling);\n }\n parent.insertBefore(end, nextSibling);\n } else {\n // Patch children between existing boundaries\n patchChildrenBetween(\n start as Comment,\n end as Comment,\n (oldVNodeByKey.get(aKey) as VNode)?.children as VNode[] | undefined,\n children,\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\n for (const node of oldNodes) {\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 (start as any).key = `${anchorVNode.key}:start`;\n (end as any).key = `${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 (start as any).key = `${newVNode.key}:start`;\n (end as any).key = `${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 = (oldVNode.tag && String(oldVNode.tag).includes('-')) || (newVNode.props && (newVNode.props as any).isCustomElement) || (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: { attrs: { 'data-anchor-block-root': '', key: \"__anchor_root__\" } },\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\" ? escapeHTML(vnode.children) as string : \"\";\n }\n\n if (vnode.tag === \"#anchor\") {\n const children = Array.isArray(vnode.children) ? vnode.children.filter(Boolean) : [];\n return children.map(renderToString).join(\"\");\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 // Collect other props (excluding attrs, directives, ref, key)\n let propsString = \"\";\n if (vnode.props) {\n propsString = Object.entries(vnode.props)\n .filter(([k]) => k !== \"attrs\" && k !== \"directives\" && k !== \"ref\" && k !== \"key\")\n .map(([k, v]) => ` ${k}=\"${escapeHTML(String(v))}\"`)\n .join(\"\");\n }\n\n const children = Array.isArray(vnode.children)\n ? vnode.children.filter(Boolean).map(renderToString).join(\"\")\n : (typeof vnode.children === \"string\" ? escapeHTML(vnode.children) : vnode.children ? renderToString(vnode.children) : \"\");\n\n return `<${vnode.tag}${attrsString}${propsString}>${children}</${vnode.tag}>`;\n}\n","/**\n * CSS template literal\n *\n * This doesn't sanitize CSS values.\n * Runtime does that for us.\n * \n * @param strings\n * @param values\n * @returns\n */\nexport function css(strings: TemplateStringsArray, ...values: unknown[]): 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 // Remove comments\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n // Remove unnecessary whitespace\n .replace(/\\s+/g, ' ')\n // Remove spaces around specific characters\n .replace(/\\s*([{}:;,>+~])\\s*/g, '$1')\n // Remove trailing semicolons before closing braces\n .replace(/;}/g, '}')\n // Remove leading/trailing whitespace\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 // Remove any url(javascript:...) and <script> tags\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\n/**\n * Minimal Shadow DOM reset\n */\nexport const baseReset = css`\n :host, *, ::before, ::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 ui-sans-serif, system-ui, sans-serif;\n -webkit-text-size-adjust: 100%;\n text-size-adjust: 100%;\n }\n button, input, select, textarea {\n background: transparent;\n outline: none;\n }\n textarea { resize: vertical }\n progress { vertical-align: baseline }\n button, textarea { overflow: visible }\n img, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n max-width: 100%;\n height: auto;\n }\n svg { fill: currentColor; stroke: none }\n a { text-decoration: inherit; cursor: pointer }\n button, [type=button], [type=reset], [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, ::placeholder {\n color: inherit; opacity: .5;\n }\n *:focus-visible {\n outline: 2px solid var(--color-primary-500, #3b82f6);\n outline-offset: 2px;\n }\n ol, ul { list-style: none }\n table { border-collapse: collapse }\n sub, sup {\n font-size: .75em;\n line-height: 0;\n position: relative;\n }\n sub { bottom: -.25em }\n sup { top: -.5em }\n [disabled], [aria-disabled=true] { cursor: not-allowed }\n [hidden] { display: none }\n`;\n\n/**\n * JIT CSS implementation\n */\n\ntype CSSMap = Record<string, string>;\ntype SelectorVariantMap = Record<string, (selector: string, body: string) => string>;\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\nconst fallbackHex: Record<string, ColorShades> = {\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 white: { DEFAULT: \"#ffffff\" },\n black: { DEFAULT: \"#000000\" },\n transparent: { DEFAULT: \"transparent\" },\n current: { DEFAULT: \"currentColor\" }\n};\n\nexport const colors: Record<string, 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 // Tailwind container widths\n // 3xs: 16rem => 16 / 0.25 = 64\n \"3xs\": 64,\n // 2xs: 18rem => 72\n \"2xs\": 72,\n // xs: 20rem => 80\n \"xs\": 80,\n // sm: 24rem => 96\n \"sm\": 96,\n // md: 28rem => 112\n \"md\": 112,\n // lg: 32rem => 128\n \"lg\": 128,\n // xl: 36rem => 144\n \"xl\": 144,\n // 2xl: 42rem => 168\n \"2xl\": 168,\n // 3xl: 48rem => 192\n \"3xl\": 192,\n // 4xl: 56rem => 224\n \"4xl\": 224,\n // 5xl: 64rem => 256\n \"5xl\": 256,\n // 6xl: 72rem => 288\n \"6xl\": 288,\n // 7xl: 80rem => 320\n \"7xl\": 320\n};\n\nconst generateSemanticSizeClasses = (): CSSMap => {\n const classes: CSSMap = {};\n for (const [key, value] of Object.entries(semanticSizes)) {\n classes[`max-w-${key}`] = `max-width:calc(${spacing} * ${value});`;\n classes[`min-w-${key}`] = `min-width:calc(${spacing} * ${value});`;\n classes[`w-${key}`] = `width:calc(${spacing} * ${value});`;\n classes[`max-h-${key}`] = `max-height:calc(${spacing} * ${value});`;\n classes[`min-h-${key}`] = `min-height:calc(${spacing} * ${value});`;\n classes[`h-${key}`] = `height:calc(${spacing} * ${value});`;\n }\n return classes;\n};\n\nconst generateGridClasses = (): CSSMap => {\n const classes: CSSMap = {};\n for (const key of [1,2,3,4,5,6,7,8,9,10,11,12]) {\n classes[`grid-cols-${key}`] = `grid-template-columns:repeat(${key},minmax(0,1fr));`;\n classes[`grid-rows-${key}`] = `grid-template-rows:repeat(${key},minmax(0,1fr));`;\n classes[`col-span-${key}`] = `grid-column:span ${key} / span ${key};`;\n classes[`row-span-${key}`] = `grid-row:span ${key} / span ${key};`;\n }\n return classes;\n};\n\nexport const utilityMap: CSSMap = {\n /* Display */\n block: \"display:block;\",\n inline: \"display:inline;\",\n \"inline-block\": \"display:inline-block;\",\n flex: \"display:flex;\",\n \"inline-flex\": \"display:inline-flex;\",\n grid: \"display:grid;\",\n hidden: \"display:none;\",\n\n /* Sizing & Spacing */\n \"w-full\": \"width:100%;\",\n \"w-screen\": \"width:100dvw;\",\n \"h-full\": \"height:100%;\",\n \"h-screen\": \"height:100dvw;\",\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-screen\": \"min-width:100dvw;\",\n \"min-h-screen\": \"min-height:100dvh;\",\n ...generateSemanticSizeClasses(),\n \"m-auto\": \"margin:auto;\",\n \"mx-auto\": \"margin-inline:auto;\",\n \"my-auto\": \"margin-block:auto;\",\n\n /* Overflow */\n \"overflow-auto\": \"overflow:auto;\",\n \"overflow-hidden\": \"overflow:hidden;\",\n \"overflow-visible\": \"overflow:visible;\",\n \"overflow-scroll\": \"overflow:scroll;\",\n\n /* Pointer Events */\n \"pointer-events-none\": \"pointer-events:none;\",\n \"pointer-events-auto\": \"pointer-events:auto;\",\n\n /* Accessibility */\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\n /* Grid Layout & Placement */\n ...generateGridClasses(),\n\n /* Positioning */\n absolute: \"position:absolute;\",\n relative: \"position:relative;\",\n fixed: \"position:fixed;\",\n sticky: \"position:sticky;\",\n\n /* Typography */\n \"font-bold\": \"font-weight:700;\",\n \"font-semibold\": \"font-weight:600;\",\n \"font-medium\": \"font-weight:500;\",\n \"font-light\": \"font-weight:300;\",\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 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 \"text-left\": \"text-align:left;\",\n \"text-center\": \"text-align:center;\",\n \"text-right\": \"text-align:right;\",\n \"text-xs\": \"font-size:0.75rem;line-height:calc(1 / 0.75)\",\n \"text-sm\": \"font-size:0.875rem;line-height:calc(1.25 / 0.875)\",\n \"text-base\": \"font-size:1rem;line-height:calc(1.5 / 1)\",\n \"text-lg\": \"font-size:1.125rem;line-height:calc(1.75 / 1.125)\",\n \"text-xl\": \"font-size:1.25rem;line-height:calc(1.75 / 1.25)\",\n \"text-2xl\": \"font-size:1.5rem;line-height:calc(2 / 1.5)\",\n \"text-3xl\": \"font-size:1.875rem;line-height:calc(2.25 / 1.875)\",\n \"text-4xl\": \"font-size:2.25rem;line-height:calc(2.5 / 2.25)\",\n \"text-5xl\": \"font-size:3rem;line-height:1\",\n \"text-6xl\": \"font-size:3.75rem;line-height:1\",\n \"text-7xl\": \"font-size:4.5rem;line-height:1\",\n \"text-8xl\": \"font-size:6rem;line-height:1\",\n\n /* Borders */\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-inline-width:1px;\",\n \"border-y\": \"border-block-width:1px;\",\n \"border-2\": \"border-width:2px;\",\n \"border-4\": \"border-width:4px;\",\n \"border-6\": \"border-width:6px;\",\n \"border-8\": \"border-width:8px;\",\n \"rounded-none\": \"border-radius:0;\",\n \"rounded-xs\": \"border-radius:0.125rem;\",\n \"rounded-t-xs\": \"border-top-left-radius:0.125rem;border-top-right-radius:0.125rem;\",\n \"rounded-r-xs\": \"border-top-right-radius:0.125rem;border-bottom-right-radius:0.125rem;\",\n \"rounded-b-xs\": \"border-bottom-left-radius:0.125rem;border-bottom-right-radius:0.125rem;\",\n \"rounded-l-xs\": \"border-top-left-radius:0.125rem;border-bottom-left-radius:0.125rem;\",\n \"rounded-sm\": \"border-radius:0.25rem;\",\n \"rounded-t-sm\": \"border-top-left-radius:0.25rem;border-top-right-radius:0.25rem;\",\n \"rounded-r-sm\": \"border-top-right-radius:0.25rem;border-bottom-right-radius:0.25rem;\",\n \"rounded-b-sm\": \"border-bottom-left-radius:0.25rem;border-bottom-right-radius:0.25rem;\",\n \"rounded-l-sm\": \"border-top-left-radius:0.25rem;border-bottom-left-radius:0.25rem;\",\n \"rounded-md\": \"border-radius:0.375rem;\",\n \"rounded-t-md\": \"border-top-left-radius:0.375rem;border-top-right-radius:0.375rem;\",\n \"rounded-r-md\": \"border-top-right-radius:0.375rem;border-bottom-right-radius:0.375rem;\",\n \"rounded-b-md\": \"border-bottom-left-radius:0.375rem;border-bottom-right-radius:0.375rem;\",\n \"rounded-l-md\": \"border-top-left-radius:0.375rem;border-bottom-left-radius:0.375rem;\",\n \"rounded-lg\": \"border-radius:0.5rem;\",\n \"rounded-t-lg\": \"border-top-left-radius:0.5rem;border-top-right-radius:0.5rem;\",\n \"rounded-r-lg\": \"border-top-right-radius:0.5rem;border-bottom-right-radius:0.5rem;\",\n \"rounded-b-lg\": \"border-bottom-left-radius:0.5rem;border-bottom-right-radius:0.5rem;\",\n \"rounded-l-lg\": \"border-top-left-radius:0.5rem;border-bottom-left-radius:0.5rem;\",\n \"rounded-xl\": \"border-radius:0.75rem;\",\n \"rounded-t-xl\": \"border-top-left-radius:0.75rem;border-top-right-radius:0.75rem;\",\n \"rounded-r-xl\": \"border-top-right-radius:0.75rem;border-bottom-right-radius:0.75rem;\",\n \"rounded-b-xl\": \"border-bottom-left-radius:0.75rem;border-bottom-right-radius:0.75rem;\",\n \"rounded-l-xl\": \"border-top-left-radius:0.75rem;border-bottom-left-radius:0.75rem;\",\n \"rounded-2xl\": \"border-radius:1rem;\",\n \"rounded-t-2xl\": \"border-top-left-radius:1rem;border-top-right-radius:1rem;\",\n \"rounded-r-2xl\": \"border-top-right-radius:1rem;border-bottom-right-radius:1rem;\",\n \"rounded-b-2xl\": \"border-bottom-left-radius:1rem;border-bottom-right-radius:1rem;\",\n \"rounded-l-2xl\": \"border-top-left-radius:1rem;border-bottom-left-radius:1rem;\",\n \"rounded-3xl\": \"border-radius:1.5rem;\",\n \"rounded-t-3xl\": \"border-top-left-radius:1.5rem;border-top-right-radius:1.5rem;\",\n \"rounded-r-3xl\": \"border-top-right-radius:1.5rem;border-bottom-right-radius:1.5rem;\",\n \"rounded-b-3xl\": \"border-bottom-left-radius:1.5rem;border-bottom-right-radius:1.5rem;\",\n \"rounded-l-3xl\": \"border-top-left-radius:1.5rem;border-bottom-left-radius:1.5rem;\",\n \"rounded-4xl\": \"border-radius:2rem;\",\n \"rounded-t-4xl\": \"border-top-left-radius:2rem;border-top-right-radius:2rem;\",\n \"rounded-r-4xl\": \"border-top-right-radius:2rem;border-bottom-right-radius:2rem;\",\n \"rounded-b-4xl\": \"border-bottom-left-radius:2rem;border-bottom-right-radius:2rem;\",\n \"rounded-l-4xl\": \"border-top-left-radius:2rem;border-bottom-left-radius:2rem;\",\n \"rounded-full\": \"border-radius:9999px;\",\n \"rounded-t-full\": \"border-top-left-radius:9999px;border-top-right-radius:9999px;\",\n \"rounded-r-full\": \"border-top-right-radius:9999px;border-bottom-right-radius:9999px;\",\n \"rounded-b-full\": \"border-bottom-left-radius:9999px;border-bottom-right-radius:9999px;\",\n \"rounded-l-full\": \"border-top-left-radius:9999px;border-bottom-left-radius:9999px;\",\n\n /* Shadow and effects */\n // Shadows use a CSS variable for color so color utilities can modify --ce-shadow-color\n \"shadow-none\": \"--ce-shadow-color: rgb(0 0 0 / 0);box-shadow:0 0 var(--ce-shadow-color, #0000);\",\n \"shadow-xs\": \"--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\": \"--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\": \"--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\": \"--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\": \"--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\": \"--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\n /* Text Overflow & Whitespace */\n truncate: \"overflow:hidden;text-overflow:ellipsis;white-space:nowrap;\",\n\n /* Visibility */\n \"visible\": \"visibility:visible;\",\n \"invisible\": \"visibility:hidden;\",\n\n /* Flex Grow/Shrink/Basis */\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-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-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 \"flex-col\": \"flex-direction:column;\",\n \"flex-row\": \"flex-direction:row;\",\n \"grow\": \"flex-grow:1;\",\n \"shrink\": \"flex-shrink:1;\",\n \"grow-0\": \"flex-grow:0;\",\n \"shrink-0\": \"flex-shrink:0;\",\n\n /* Font Family */\n \"font-sans\": \"font-family:ui-sans-serif,system-ui,sans-serif;\",\n \"font-serif\": \"font-family:ui-serif,Georgia,serif;\",\n \"font-mono\": \"font-family:ui-monospace,SFMono-Regular,monospace;\",\n\n /* Line Clamp (for webkit) */\n \"line-clamp-1\": \"display:-webkit-box;-webkit-line-clamp:1;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-2\": \"display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-3\": \"display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;\",\n \"line-clamp-4\": \"display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;\",\n\n /* Transitions */\n transition: \"transition-property:all;transition-duration:150ms;transition-timing-function:ease-in-out;\",\n \"transition-all\": \"transition-property:all;\",\n \"transition-colors\": \"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 \"transition-none\": \"transition-property:none;\",\n\n /* Cursor */\n \"cursor-auto\": \"cursor:auto;\",\n \"cursor-default\": \"cursor:default;\",\n \"cursor-pointer\": \"cursor:pointer;\",\n \"cursor-wait\": \"cursor:wait;\",\n \"cursor-text\": \"cursor:text;\",\n \"cursor-move\": \"cursor:move;\",\n \"cursor-help\": \"cursor:help;\",\n \"cursor-not-allowed\": \"cursor:not-allowed;\",\n\n /* Z-index */\n \"z-0\": \"z-index:0;\",\n \"z-10\": \"z-index:10;\",\n \"z-20\": \"z-index:20;\",\n \"z-30\": \"z-index:30;\",\n \"z-40\": \"z-index:40;\",\n \"z-50\": \"z-index:50;\",\n};\n\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\nfunction insertPseudoBeforeCombinator(sel: string, pseudo: string): string {\n let depthSquare = 0;\n let depthParen = 0;\n for (let i = 0; i < sel.length; i++) {\n const ch = sel[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 else if (depthSquare === 0 && depthParen === 0 && (ch === \">\" || ch === \"+\" || ch === \"~\" || ch === \" \")) {\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) => `${insertPseudoBeforeCombinator(sel, \":hover\")}{${body}}`,\n focus: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus\")}{${body}}`,\n active: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":active\")}{${body}}`,\n disabled: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":disabled\")}{${body}}`,\n visited: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":visited\")}{${body}}`,\n checked: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":checked\")}{${body}}`,\n first: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":first-child\")}{${body}}`,\n last: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":last-child\")}{${body}}`,\n odd: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":nth-child(odd)\")}{${body}}`,\n even: (sel, body) => `${insertPseudoBeforeCombinator(sel, \":nth-child(even)\")}{${body}}`,\n \"focus-within\": (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus-within\")}{${body}}`,\n \"focus-visible\": (sel, body) => `${insertPseudoBeforeCombinator(sel, \":focus-visible\")}{${body}}`,\n\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\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\n\nexport const mediaVariants: MediaVariantMap = {\n // Responsive\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 (now plain string)\n \"dark\": \"(prefers-color-scheme: dark)\"\n};\n\nexport const responsiveOrder = [\"sm\", \"md\", \"lg\", \"xl\", \"2xl\"];\n\nexport function parseSpacing(className: string): string | null {\n const negative = className.startsWith(\"-\");\n const raw = negative ? className.slice(1) : className;\n const parts = raw.split(\"-\");\n\n if (parts.length < 2) return null;\n\n const key = parts.slice(0, -1).join(\"-\");\n const numStr = parts[parts.length - 1];\n const num = parseFloat(numStr);\n\n if (Number.isNaN(num) || !spacingProps[key]) 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 hexToRgb(hex: string): string {\n const clean = hex.replace(\"#\", \"\");\n const bigint = parseInt(clean, 16);\n const r = (bigint >> 16) & 255;\n const g = (bigint >> 8) & 255;\n const b = bigint & 255;\n return `${r} ${g} ${b}`;\n}\n\nexport function parseColorClass(className: string): string | null {\n // Match bg-red-500, text-gray-200, border-blue-600, etc.\n const match = /^(bg|text|border|decoration|shadow|outline|caret|accent|fill|stroke)-([a-z]+)-?(\\d{2,3}|DEFAULT)?$/.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 // Special-case shadow: we set a CSS variable so shadow-size utilities can compose with color\n if (type === 'shadow') return `--ce-shadow-color:${colorValue};`;\n\n const 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\n const prop = propMap[type];\n if (!prop) return null;\n return `${prop}:${colorValue};`;\n}\n\nexport function parseOpacityModifier(className: string): { base: string; opacity?: number } {\n const [base, opacityStr] = className.split(\"/\");\n if (!opacityStr) return { base };\n\n const opacity = parseInt(opacityStr, 10);\n if (isNaN(opacity) || opacity < 0 || opacity > 100) return { base };\n\n return { base, opacity: opacity / 100 };\n}\n\nexport function parseColorWithOpacity(className: string): string | null {\n const { base, opacity } = parseOpacityModifier(className);\n\n // Try palette first\n const paletteRule = parseColorClass(base); // e.g., \"background-color:#ef4444;\"\n if (paletteRule) {\n if (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 return paletteRule;\n }\n\n // Try arbitrary color: [bg:#ff0000]/50\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(/#([0-9a-f]{6})/i, `rgb(${rgb} / ${opacity})`);\n }\n }\n\n return arbitraryRule;\n}\n\n/**\n * Parse opacity utility class (e.g., opacity-25)\n * Returns CSS rule string or null if not valid\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 if (value < 0 || value > 100) return null;\n return `opacity:${value / 100};`;\n}\n\n/**\n * Arbitrary value parser — supports:\n * - prop-[value]\n */\nexport function parseArbitrary(className: string): string | null {\n // 1) [prop:value] — only when \"prop\" is a valid CSS property name (not a selector)\n if (className.startsWith(\"[\") && className.endsWith(\"]\") && !className.includes(\"-[\")) {\n const inner = className.slice(1, -1).trim();\n\n // prop must be at the very start, and must be a CSS identifier (letters + hyphens)\n const m = inner.match(/^([a-zA-Z][a-zA-Z0-9-]*)\\s*:(.*)$/);\n if (m) {\n const prop = m[1].trim();\n let value = m[2].trim();\n // normalize url('...') to url(\"...\") and whole-value single-quotes to double\n value = value.replace(/url\\('\\s*([^']*?)\\s*'\\)/g, 'url(\"$1\")');\n value = value.replace(/^'([^']*)'$/g, '\"$1\"');\n return `${prop}:${value};`;\n }\n // If it didn't match a property, it's an arbitrary variant selector (e.g. [&>h2:hover]) — not a utility\n return null;\n }\n\n // 2) prop-[value] — arbitrary values for known properties\n const bracketStart = className.indexOf(\"-[\");\n const bracketEnd = className.endsWith(\"]\");\n if (bracketStart > 0 && bracketEnd) {\n const prop = className.slice(0, bracketStart);\n let value = className.slice(bracketStart + 2, -1);\n\n // Convert underscores to spaces\n value = value.replace(/_/g, \" \");\n\n // Map common abbreviations to CSS properties\n const propMap: Record<string, string> = {\n bg: \"background-color\",\n text: \"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 whitespace: \"white-space\",\n select: \"user-select\",\n content: \"align-content\",\n self: \"align-self\",\n basis: \"flex-basis\",\n tracking: \"letter-spacing\",\n scroll: \"scroll-behavior\",\n weight: \"font-weight\",\n leading: \"line-height\",\n z: \"z-index\",\n };\n\n // Tailwind-like rotate behavior for arbitrary values\n if (prop === \"rotate\") {\n return `transform:rotate(${value});`;\n }\n\n const cssProp = propMap[prop] ?? prop.replace(/_/g, \"-\");\n if (cssProp && value) return `${cssProp}:${value};`;\n }\n\n return null;\n}\n\n/**\n * Parse arbitrary variant from class name.\n * Supports [attr=value]:utility or foo-[bar]:utility\n */\nexport function parseArbitraryVariant(token: string): string | null {\n // [attr=value] or [&...]\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n const inner = token.slice(1, -1);\n // If it contains &, return without brackets so & can be replaced\n return inner.includes(\"&\") ? inner : token;\n }\n\n // foo-[bar] style\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 // Escape only selector-relevant characters, not brackets\n return name.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, '\\\\$1');\n}\n\nexport function extractClassesFromHTML(html: string): string[] {\n // Match class attributes robustly by capturing the opening quote and\n // using a backreference to the same quote for the closing boundary.\n // This ensures embedded single quotes (e.g. url('/icons/mask.svg')) do\n // not prematurely terminate the match.\n const classAttrRegex = /class\\s*=\\s*(['\"])(.*?)\\1/g;\n const classList: string[] = [];\n let match: RegExpExecArray | null;\n\n while ((match = classAttrRegex.exec(html))) {\n // Split on whitespace to preserve complex tokens containing colons,\n // brackets, parentheses and quotes (e.g. [mask-image:url('/icons/mask.svg')]).\n const tokens = match[2].split(/\\s+/).filter(Boolean);\n if (tokens.length) classList.push(...tokens);\n }\n return classList.filter(Boolean);\n}\n\n/**\n * JIT CSS generation with throttling and memoization.\n * Only regenerates CSS if HTML changes and enough time has passed.\n * Caches results for repeated HTML inputs.\n */\nexport const jitCssCache = new Map<string, { css: string; timestamp: number }>();\nexport const JIT_CSS_THROTTLE_MS = 16; // 60fps\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) return cached.css;\n\n const classes = extractClassesFromHTML(html);\n const seen = new Set(classes);\n\n const bucket1: string[] = [];\n const bucket2: string[] = [];\n const bucket3: string[] = [];\n const bucket4: string[] = [];\n const ruleCache: Record<string, string | null> = {};\n\n function generateRuleCached(cls: string, stripDark = false): string | null {\n const cacheKey = (stripDark ? \"dark|\" : \"\") + 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 function classify(before: string[]): number {\n const hasResponsive = before.some(t => responsiveOrder.includes(t));\n const hasDark = before.includes(\"dark\");\n if (before.length === 0) return 1;\n if (!hasResponsive && !hasDark) return 2;\n if (hasResponsive && !hasDark) return 3;\n return 4;\n }\n\n function splitVariants(input: string): string[] {\n const out: string[] = [];\n let buf = \"\";\n let depthSquare = 0;\n let depthParen = 0;\n for (let i = 0; i < input.length; i++) {\n const ch = input[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 (ch === \":\" && depthSquare === 0 && depthParen === 0) {\n out.push(buf);\n buf = \"\";\n } else {\n buf += ch;\n }\n }\n if (buf) out.push(buf);\n return out;\n }\n\n // Map Tailwind pseudo-variant tokens to their CSS pseudo class strings\n function tokenToPseudo(token: string): string | null {\n switch (token) {\n case \"hover\": return \":hover\";\n case \"focus\": return \":focus\";\n case \"active\": return \":active\";\n case \"visited\": return \":visited\";\n case \"disabled\": return \":disabled\";\n case \"checked\": return \":checked\";\n case \"first\": return \":first-child\";\n case \"last\": return \":last-child\";\n case \"odd\": return \":nth-child(odd)\";\n case \"even\": return \":nth-child(even)\";\n case \"focus-within\": return \":focus-within\";\n case \"focus-visible\": return \":focus-visible\";\n default: return null;\n }\n }\n\n function generateRule(cls: string, stripDark = false): string | null {\n const parts = splitVariants(cls);\n\n // Find base utility\n let important = false;\n const basePart = parts.find(p => {\n if (p.startsWith(\"!\")) {\n important = true;\n p = p.slice(1);\n }\n return (\n utilityMap[p] ||\n parseSpacing(p) ||\n parseOpacity(p) ||\n parseColorWithOpacity(p) ||\n parseArbitrary(p)\n );\n });\n if (!basePart) return null;\n\n const cleanBase = basePart.replace(/^!/, \"\");\n const baseRule =\n utilityMap[cleanBase] ??\n parseSpacing(cleanBase) ??\n parseOpacity(cleanBase) ??\n parseColorWithOpacity(cleanBase) ??\n parseArbitrary(cleanBase);\n\n if (!baseRule) return null;\n\n const baseIndex = parts.indexOf(basePart);\n let before = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n if (stripDark) before = before.filter(t => t !== \"dark\");\n\n const escapedClass = `.${escapeClassName(cls)}`;\n const SUBJECT = \"__SUBJECT__\";\n const body = important ? baseRule.replace(/;$/, \" !important;\") : baseRule;\n\n // Start with a SUBJECT placeholder we will replace later with the real class\n let selector = SUBJECT;\n\n // Handle structural wrappers (group/peer) first (preserve order)\n const structural: string[] = [];\n for (const token of before) {\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(SUBJECT, `.peer:${token.slice(5)}~${SUBJECT}`);\n structural.push(token);\n }\n }\n before = before.filter(t => !structural.includes(t));\n\n // Collect pseudos in left-to-right order, but don't mutate SUBJECT yet to preserve order.\n const subjectPseudos: string[] = [];\n const innerPseudos: string[] = [];\n let wrapperVariant: string | null = null;\n\n for (const token of before) {\n if (token === \"dark\" || responsiveOrder.includes(token)) continue;\n\n const variantSelector = parseArbitraryVariant(token);\n if (variantSelector) {\n wrapperVariant = variantSelector;\n continue;\n }\n\n const pseudo = tokenToPseudo(token);\n if (pseudo) {\n if (!wrapperVariant) subjectPseudos.push(pseudo);\n else innerPseudos.push(pseudo);\n continue;\n }\n\n const fn = selectorVariants[token];\n if (typeof fn === \"function\") {\n // apply structural variant immediately\n selector = fn(selector, body).split(\"{\")[0];\n }\n }\n\n // helper: insert inner pseudos into the 'post' part after the first simple selector\n function insertPseudosIntoPost(post: string, pseudos: string): string {\n if (!pseudos) return post;\n let depthSquare = 0;\n let depthParen = 0;\n // If post starts with a combinator, insert pseudos after the first simple selector\n if (post.length && (post[0] === '>' || post[0] === '+' || post[0] === '~' || post[0] === ' ')) {\n // find end of first simple selector after the combinator\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 // stop at next combinator at depth 0\n if (depthSquare === 0 && depthParen === 0 && (post[i] === '>' || post[i] === '+' || post[i] === '~' || post[i] === ' ')) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n // reached end: append pseudos at end\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 // break at first combinator at depth 0 (space, >, +, ~)\n if (depthSquare === 0 && depthParen === 0 && (ch === '>' || ch === '+' || ch === '~' || ch === ' ')) {\n return post.slice(0, i) + pseudos + post.slice(i);\n }\n }\n return post + pseudos;\n }\n\n const subjectPseudoStr = subjectPseudos.join(\"\");\n const innerPseudoStr = innerPseudos.join(\"\");\n\n // Build selector by applying wrapper if present, inserting pseudos in the right spots\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 // place subject with its pseudos where & sits\n const subjectWithPseudos = SUBJECT + subjectPseudoStr;\n // If there are no subject pseudos (nothing attached before the wrapper),\n // inner pseudos should apply to the subject. Otherwise they target the\n // element inside the wrapper (the post), so insert them into the post.\n // Preserve any structural wrappers that were applied earlier by\n // replacing the SUBJECT placeholder in the current selector.\n const currentSelector = selector;\n if (subjectPseudos.length === 0) {\n // attach inner pseudos to the subject\n selector = currentSelector.replace(SUBJECT, pre + subjectWithPseudos + innerPseudoStr + post);\n } else {\n // insert inner pseudos into post after its first simple selector\n const postWithInner = insertPseudosIntoPost(post, innerPseudoStr);\n selector = currentSelector.replace(SUBJECT, pre + subjectWithPseudos + postWithInner);\n }\n } else {\n // prefix-style wrapper like [data-open=true]\n // Insert the wrapper around the existing selector's SUBJECT so structural\n // prefixes remain on the outside.\n const currentSelector = selector;\n selector = currentSelector.replace(SUBJECT, `${wrapperVariant}${SUBJECT + subjectPseudoStr}`);\n if (innerPseudoStr) selector = selector.replace(SUBJECT, `${SUBJECT}${innerPseudoStr}`);\n }\n } else {\n // no wrapper: just attach subject and inner pseudos directly to SUBJECT\n selector = SUBJECT + subjectPseudoStr + innerPseudoStr;\n }\n\n // re-apply any previously applied structural wrappers (they were applied to the placeholder earlier)\n // At this point 'selector' is a string containing SUBJECT (or actual class replacement next).\n // Replace any remaining SUBJECT with escaped class\n selector = selector.replace(new RegExp(SUBJECT, \"g\"), escapedClass);\n\n // Emit final rule\n let rule = `${selector}{${body}}`;\n\n // Wrap in media queries\n const responsiveTokens = before.filter(t => responsiveOrder.includes(t));\n const lastResponsive = responsiveTokens.length\n ? responsiveTokens[responsiveTokens.length - 1]\n : null;\n const hasDark = before.includes(\"dark\");\n\n if (stripDark && lastResponsive) {\n rule = `@media (prefers-color-scheme: dark) and ${mediaVariants[lastResponsive]}{${rule}}`;\n } else if (stripDark) {\n rule = `@media (prefers-color-scheme: dark){${rule}}`;\n } else if (hasDark && lastResponsive) {\n rule = `@media (prefers-color-scheme: dark) and ${mediaVariants[lastResponsive]}{${rule}}`;\n } else if (hasDark) {\n rule = `@media (prefers-color-scheme: dark){${rule}}`;\n } else if (lastResponsive) {\n rule = `@media ${mediaVariants[lastResponsive]}{${rule}}`;\n }\n\n return rule;\n }\n\n // Use safe splitting in the outer loop as well\n for (const cls of seen) {\n const parts = splitVariants(cls);\n const basePart = parts.find(\n p => utilityMap[p] || parseSpacing(p) || parseOpacity(p) || parseColorWithOpacity(p) || parseArbitrary(p)\n );\n if (!basePart) continue;\n const baseIndex = parts.indexOf(basePart);\n const before = baseIndex >= 0 ? parts.slice(0, baseIndex) : [];\n const bucketNum = classify(before);\n\n if (bucketNum === 4) {\n const rule = generateRuleCached(cls, true);\n if (rule) bucket4.push(rule);\n } else {\n const rule = generateRuleCached(cls);\n if (rule) {\n if (bucketNum === 1) bucket1.push(rule);\n else if (bucketNum === 2) bucket2.push(rule);\n else if (bucketNum === 3) bucket3.push(rule);\n }\n }\n }\n\n const css = [...bucket1, ...bucket2, ...bucket3, ...bucket4].join(\"\");\n jitCssCache.set(html, { css, timestamp: now });\n return css;\n}\n","import { vdomRenderer } from \"./vdom\";\nimport { minifyCSS, getBaseResetSheet, sanitizeCSS, jitCSS } from \"./style\";\nimport type { ComponentConfig, ComponentContext, VNode, Refs } from \"./types\";\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<S extends object, C extends object, P extends object, T extends object>(\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<S extends object, C extends object, P extends object, T extends object>(\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 console.warn(\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 console.error(\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 setLastRenderTime(Date.now());\n renderFn();\n setRenderTimeoutId(null);\n }, renderCount > 10 ? 100 : 0); // Add delay for rapid renders\n setRenderTimeoutId(timeoutId);\n}\n\n/**\n * Applies styles to the shadowRoot.\n */\nexport function applyStyle<S extends object, C extends object, P extends object, T extends object>(\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 const jitCss = jitCSS(htmlString);\n\n if ((!jitCss || jitCss.trim() === \"\") && !(context as any)._computedStyle) {\n setStyleSheet(null);\n shadowRoot.adoptedStyleSheets = [getBaseResetSheet()];\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 if (sheet.cssRules.length === 0 || sheet.toString() !== finalStyle) {\n sheet.replaceSync(finalStyle);\n }\n shadowRoot.adoptedStyleSheets = [getBaseResetSheet(), sheet];\n setStyleSheet(sheet);\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;\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', ({ 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: (name: string, oldValue: string | null, newValue: string | null) => void\n): void {\n if (!currentComponentContext) {\n throw new Error('useOnAttributeChanged must be called during component render');\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 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', ({ theme = 'light' }) => {\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 console.warn('Error in useStyle callback:', error);\n Object.defineProperty(currentComponentContext, '_computedStyle', {\n value: '',\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n}","import type {\n ComponentConfig,\n ComponentContext,\n Refs,\n WatcherState,\n VNode,\n} from \"./types\";\nimport { reactiveSystem } from \"./reactive\";\nimport { toKebab } 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\";\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 && 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 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>(tag: string, config: ComponentConfig<S, C, P, T>): CustomElementConstructor | { new (): object } {\n // Validate that render is provided\n if (!config.render) {\n throw new Error(\n \"Component must have a render function\",\n );\n }\n if (typeof window === \"undefined\") {\n // SSR fallback: minimal class, no DOM, no lifecycle, no \"this\"\n return class { constructor() {} };\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 // Inject refs into context (non-enumerable to avoid proxy traps)\n Object.defineProperty(reactiveContext, \"refs\", {\n value: this._refs,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject requestRender into context (non-enumerable to avoid proxy traps)\n Object.defineProperty(reactiveContext, 'requestRender', {\n value: () => this.requestRender(),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject _requestRender for backward compatibility (used by model directive)\n Object.defineProperty(reactiveContext, '_requestRender', {\n value: () => this._requestRender(),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject component ID for functional component state persistence\n Object.defineProperty(reactiveContext, '_componentId', {\n value: this._componentId,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // Inject _triggerWatchers for model directive to trigger watchers\n Object.defineProperty(reactiveContext, '_triggerWatchers', {\n value: (path: string, newValue: any) => this._triggerWatchers(path, newValue),\n writable: false,\n enumerable: false,\n configurable: false,\n });\n\n // --- Apply props BEFORE wiring listeners and emit ---\n this.context = reactiveContext;\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 Object.defineProperty(this.context, \"emit\", {\n value: (eventName: string, detail?: any, options?: CustomEventInit) => {\n const ev = new CustomEvent(eventName, {\n detail,\n bubbles: true,\n composed: true,\n ...(options || {})\n });\n // DOM-first: dispatch the event and return whether it was prevented\n this.dispatchEvent(ev);\n return !ev.defaultPrevented;\n },\n writable: false,\n enumerable: false,\n configurable: false,\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 = (registry.get(tag) as ComponentConfig<S, C, P, T>) || config;\n Object.keys(cfgToUse).forEach((key) => {\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[]) => fn(...args, this.context);\n }\n });\n\n this._applyComputed(cfgToUse);\n\n // Set up reactive property setters for all props to detect external changes\n if (cfgToUse.props) {\n Object.keys(cfgToUse.props).forEach((propName) => {\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(\n config,\n this.context,\n this._mounted,\n (val) => { this._mounted = val; }\n );\n });\n }\n\n disconnectedCallback() {\n this._runLogicWithinErrorBoundary(config, () => {\n handleDisconnected(\n config,\n this.context,\n this._listeners,\n () => { this._listeners = []; },\n () => { this._watchers.clear(); },\n (val) => { this._templateLoading = val; },\n (err) => { this._templateError = err; },\n (val) => { this._mounted = val; }\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(\n config,\n name,\n oldValue,\n newValue,\n this.context\n );\n });\n }\n\n static get observedAttributes() {\n return config.props ? Object.keys(config.props).map(toKebab) : [];\n }\n\n private _applyComputed(_cfg: ComponentConfig<S, C, P, T>) {\n // Computed properties are now handled by the computed() function and reactive system\n // This method is kept for compatibility but does nothing in the functional API\n }\n\n // --- Render ---\n private _render(cfg: ComponentConfig<S, C, P, T>) {\n this._runLogicWithinErrorBoundary(cfg, () => {\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) => { this._lastRenderTime = t; },\n (c) => { this._renderCount = c; },\n this._renderTimeoutId,\n (id) => { this._renderTimeoutId = id; }\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) => { this._styleSheet = sheet; }\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 if (cfg.onError) {\n cfg.onError(error as Error | null, this.context);\n }\n // Note: errorFallback was removed as it's handled by the functional API directly\n }\n }\n\n // --- State, props, computed ---\n private _initContext(cfg: ComponentConfig<S, C, P, T>): 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(() => self._render(cfg), self._componentId);\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 (obj.constructor && obj.constructor.name === 'ReactiveState') {\n return obj;\n }\n \n Object.keys(obj).forEach((key) => {\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(\n fullPath,\n target[prop as any]\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 ? Object.fromEntries(\n Object.entries(cfg.props).map(([key, def]) => [key, def.default])\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 only\n * component('with-props', ({ message = 'Hello' }) => {\n * return html`<div>${message}</div>`;\n * });\n * \n * // With props and hooks\n * component('my-switch', ({\n * modelValue = false,\n * label = ''\n * }, { emit, onConnected, onDisconnected }) => {\n * onConnected(() => console.log('Switch connected!'));\n * onDisconnected(() => 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 1: No parameters - simple components\nexport function component(\n tag: string,\n renderFn: () => VNode | VNode[] | Promise<VNode | VNode[]>\n): void;\n\n// Overload 2: Props only - modern recommended approach with context-based hooks\nexport function component<TProps extends Record<string, any> = {}>(\n tag: string,\n renderFn: (props: TProps) => VNode | VNode[] | Promise<VNode | VNode[]>\n): void;\n\n// Implementation\nexport function component(\n tag: string,\n renderFn: (...args: any[]) => VNode | VNode[] | Promise<VNode | VNode[]>\n): void {\n let normalizedTag = toKebab(tag);\n if (!normalizedTag.includes(\"-\")) {\n normalizedTag = `cer-${normalizedTag}`;\n }\n\n // We'll parse the function string to extract defaults (dev time only)\n let propDefaults: Record<string, any> = {};\n \n if (typeof window !== \"undefined\") {\n try {\n const fnString = renderFn.toString();\n \n // More robust parsing for destructured parameters with defaults\n const paramsMatch = fnString.match(/\\(\\s*{\\s*([^}]+)\\s*}/);\n if (paramsMatch) {\n const propsString = paramsMatch[1];\n \n // Split by comma but handle nested objects/arrays\n const propPairs = propsString.split(',').map(p => p.trim());\n \n for (const pair of propPairs) {\n // Handle \"prop = defaultValue\" pattern\n const equalIndex = pair.indexOf('=');\n if (equalIndex !== -1) {\n const key = pair.substring(0, equalIndex).trim();\n const defaultValue = pair.substring(equalIndex + 1).trim();\n \n try {\n // Parse simple default values\n if (defaultValue === 'true') propDefaults[key] = true;\n else if (defaultValue === 'false') propDefaults[key] = false;\n else if (defaultValue === '[]') propDefaults[key] = [];\n else if (defaultValue === '{}') propDefaults[key] = {};\n else if (/^\\d+$/.test(defaultValue)) propDefaults[key] = parseInt(defaultValue);\n else if (/^'.*'$/.test(defaultValue) || /^\".*\"$/.test(defaultValue)) {\n propDefaults[key] = defaultValue.slice(1, -1);\n } else {\n propDefaults[key] = defaultValue;\n }\n } catch (e) {\n propDefaults[key] = '';\n }\n } else {\n // No default value, extract just the key name (remove type annotation)\n const key = pair.split(':')[0].trim();\n if (key && !key.includes('}')) {\n propDefaults[key] = '';\n }\n }\n }\n }\n } catch (e) {\n // Fallback: no props parsing\n }\n }\n\n // Store lifecycle hooks from the render function\n let lifecycleHooks: {\n onConnected?: () => void;\n onDisconnected?: () => void;\n onAttributeChanged?: (name: string, oldValue: string | null, newValue: string | null) => void;\n onError?: (error: Error) => void;\n } = {};\n\n // Create component config\n const config: ComponentConfig<{}, {}, {}, {}> = {\n // Generate props config from defaults\n props: Object.fromEntries(\n Object.entries(propDefaults).map(([key, defaultValue]) => {\n const type = typeof defaultValue === 'boolean' ? Boolean\n : typeof defaultValue === 'number' ? Number\n : typeof defaultValue === 'string' ? String\n : Function; // Use Function for complex types\n return [key, { type, default: defaultValue }];\n })\n ),\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 = (context as any)._componentId || `${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 // Check if we have prop defaults (indicates destructured parameters)\n const hasProps = Object.keys(propDefaults).length > 0;\n \n let result;\n if (hasProps) {\n // Destructured parameters detected - create fresh props object with current context values\n const freshProps: any = {};\n Object.keys(propDefaults).forEach(key => {\n freshProps[key] = (context as any)[key] ?? propDefaults[key];\n });\n result = renderFn(freshProps);\n } else {\n // No parameters expected - call with no arguments\n result = renderFn();\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 = 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 }\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 if (typeof window !== \"undefined\") {\n if (!customElements.get(normalizedTag)) {\n customElements.define(normalizedTag, createElementClass(normalizedTag, config) as CustomElementConstructor);\n }\n }\n}\n","import type { VNode } from \"./types\";\nimport { contextStack } from \"./render\";\nimport { toKebab, getNestedValue, setNestedValue } from \"./helpers\";\nimport { isReactiveState } from \"./reactive\";\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) { this.maxSize = maxSize; }\n get(key: K): V | undefined {\n const v = this.map.get(key);\n if (v === undefined) return undefined;\n // move to end\n this.map.delete(key);\n this.map.set(key, v);\n return v;\n }\n set(key: K, value: V) {\n if (this.map.has(key)) {\n this.map.delete(key);\n }\n this.map.set(key, value);\n if (this.map.size > this.maxSize) {\n // remove oldest\n const first = this.map.keys().next().value;\n if (first !== undefined) this.map.delete(first);\n }\n }\n has(key: K): boolean { return this.map.has(key); }\n clear() { this.map.clear(); }\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 console.warn(\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 console.warn(\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 console.warn(\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<string, { value: any; modifiers: string[]; arg?: string }> = {};\n const bound: string[] = [];\n\n // Match attributes with optional prefix and support for single/double quotes\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 // Interpolation detection\n const interpMatch = rawVal.match(/^{{(\\d+)}}$/);\n let value: any = 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 = [\"model\", \"bind\", \"show\", \"class\", \"style\", \"ref\"];\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 = maybeDirective === 'model' && argPart ? `model:${argPart}` : maybeDirective;\n directives[directiveKey] = {\n value,\n modifiers,\n arg: argPart,\n };\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 } 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 = 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 (modifiers.includes(\"self\") && event.target !== event.currentTarget) {\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(eventName, wrappedHandler);\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 = \"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 * 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 = 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 function textVNode(text: string, key: string): VNode {\n return h(\"#text\", {}, text, 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 mergeIntoCurrentProps(v);\n } else {\n targetChildren.push(textVNode(String(v), `${baseKey}-${i}`));\n }\n }\n return;\n }\n\n if (val !== null && typeof val === \"object\") {\n mergeIntoCurrentProps(val);\n return;\n }\n\n targetChildren.push(textVNode(String(val), baseKey));\n }\n\n const voidElements = new Set([\n 'area','base','br','col','embed','hr','img','input',\n 'link','meta','param','source','track','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 = 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(match[2] || \"\", values, effectiveContext) 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 !(vnodeProps.props && Object.prototype.hasOwnProperty.call(vnodeProps.props, 'key'))\n ) {\n try {\n vnodeProps.props.key = vnodeProps.attrs['key'];\n } catch (e) {\n // best-effort; ignore\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 const nativePromoteMap: Record<string, string[]> = {\n input: ['value', 'checked', 'disabled', 'readonly', 'required', 'placeholder', 'maxlength', 'minlength'],\n textarea: ['value', 'disabled', 'readonly', 'required', 'placeholder', 'maxlength', 'minlength'],\n select: ['value', 'disabled', 'required', 'multiple'],\n option: ['selected', 'disabled', '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', 'disabled', '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 (boundList && boundList.includes(propName) && propName in vnodeProps.attrs && !(vnodeProps.props && propName in vnodeProps.props)) {\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 }\n vnodeProps.props[propName] = attrValue;\n delete vnodeProps.attrs[propName];\n }\n }\n }\n // If this looks like a custom element (hyphenated tag), promote all bound attrs to props\n const isCustom = tagName.includes('-') || 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 (b in vnodeProps.attrs && !(vnodeProps.props && b in vnodeProps.props)) {\n // Convert kebab-case to camelCase for JS property names on custom elements\n const camel = b.includes('-') ? b.split('-').map((s, i) => i === 0 ? s : s.charAt(0).toUpperCase() + s.slice(1)).join('') : b;\n let attrValue = vnodeProps.attrs[b];\n // Unwrap reactive state objects during promotion\n if (attrValue && isReactiveState(attrValue)) {\n attrValue = (attrValue as any).value; // This triggers dependency tracking\n }\n vnodeProps.props[camel] = attrValue;\n // Preserve potential key attributes in attrs to avoid unstable keys\n if (!keyAttrs.has(b)) {\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 (directives && Object.keys(directives).some(k => k === 'model' || k.startsWith('model:'))) {\n try {\n const GLOBAL_REG_KEY = Symbol.for('cer.registry');\n const globalRegistry = (globalThis as any)[GLOBAL_REG_KEY] as Set<string> | Map<string, any> | undefined;\n const isInGlobalRegistry = Boolean(globalRegistry && typeof globalRegistry.has === 'function' && globalRegistry.has(tagName));\n\n const isInContext = Boolean(\n effectiveContext && (\n ((effectiveContext as any).__customElements instanceof Set && (effectiveContext as any).__customElements.has(tagName)) ||\n (Array.isArray((effectiveContext as any).__isCustomElements) && (effectiveContext as any).__isCustomElements.includes(tagName))\n )\n );\n\n const isHyphenated = tagName.includes('-');\n\n const isCustomFromContext = Boolean(isHyphenated || isInContext || isInGlobalRegistry);\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 { value: any; modifiers: string[]; arg?: string };\n const arg = model.arg ?? (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 ? ((effectiveContext as any)._state || effectiveContext) : 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 if (initial && isReactiveState(initial)) {\n initial = (initial as any).value; // This triggers dependency tracking\n }\n }\n\n vnodeProps.props[argToUse] = initial;\n\n try {\n const attrName = toKebab(argToUse);\n if (!vnodeProps.attrs) vnodeProps.attrs = {} as any;\n if (initial !== undefined) vnodeProps.attrs[attrName] = initial;\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(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n const handlerKey = 'on' + camelEventName.charAt(0).toUpperCase() + camelEventName.slice(1);\n\n vnodeProps.props[handlerKey] = function (ev: Event & { detail?: any }) {\n const newVal = (ev as any).detail !== undefined ? (ev as any).detail : (ev.target ? (ev.target as any).value : undefined);\n if (!actualState) return;\n \n // Handle reactive state objects (functional API)\n if (modelVal && isReactiveState(modelVal)) {\n const current = modelVal.value;\n const changed = Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n modelVal.value = newVal;\n if ((effectiveContext as any)?.requestRender) (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender) (effectiveContext as any)._requestRender();\n }\n } else {\n // Legacy string-based state handling\n const current = getNested(actualState, typeof modelVal === 'string' ? modelVal : String(modelVal));\n const changed = Array.isArray(newVal) && Array.isArray(current)\n ? JSON.stringify([...newVal].sort()) !== JSON.stringify([...current].sort())\n : newVal !== current;\n if (changed) {\n setNested(actualState, typeof modelVal === 'string' ? modelVal : String(modelVal), newVal);\n if ((effectiveContext as any)?.requestRender) (effectiveContext as any).requestRender();\n else if ((effectiveContext as any)?._requestRender) (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 targetChildren.push(textVNode(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 typeof child.children === \"string\" && child.children.trim() !== \"\";\n }\n return true;\n }\n // Always keep anchor blocks and non-element nodes\n return true;\n });\n\n if (cleanedFragments.length === 1) {\n // Single non-empty root node\n const out = cleanedFragments[0];\n if (canCache && cacheKey) TEMPLATE_COMPILE_CACHE.set(cacheKey, out);\n return out;\n } else if (cleanedFragments.length > 1) {\n // True multi-root: return array\n const out = cleanedFragments;\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}","import type { VNode } from \"./runtime/types\";\n\n/* --- When --- */\nexport function when(cond: boolean, children: VNode | VNode[]): VNode {\n const anchorKey = \"when-block\"; // stable key regardless of condition\n return anchorBlock(cond ? children : [], 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[]) {\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[]];\n\nfunction whenChain(...branches: Branch[]): VNode[] {\n for (let idx = 0; idx < branches.length; idx++) {\n const [cond, content] = branches[idx];\n if (cond) return [anchorBlock(content, `whenChain-branch-${idx}`)];\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 null/undefined\n const childArray = !children\n ? []\n : Array.isArray(children)\n ? children.filter(Boolean)\n : [children].filter(Boolean);\n\n return {\n tag: \"#anchor\",\n key: anchorKey,\n children: childArray,\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 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\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'\n ? partial(state)\n : 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","/**\n * Lightweight, scalable router for Custom Elements Runtime\n * - Functional API, zero dependencies, SSR/static site compatible\n * - Integrates with createStore and lib/index.ts\n */\n\nimport { html } from './runtime/template-compiler';\nimport { component } from './runtime/component';\nimport { createStore, type Store } from './store';\nimport { devError } from './runtime/logger';\nimport { match } from './directives';\n\nexport interface RouteComponent {\n // Can be any renderable type — adjust as needed for your framework\n new (...args: any[]): any; // class components\n // OR functional components\n (...args: any[]): any;\n}\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 /**\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 class?: string;\n style: 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 interface RouteState {\n path: string;\n params: Record<string, string>;\n query: Record<string, string>;\n}\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 = (routes: Route[], path: string): { 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// 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 = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.beforeEnter) {\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 return true;\n };\n\n const runOnEnter = async (to: RouteState, from: RouteState) => {\n const matched = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.onEnter) {\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 return true;\n };\n\n const runAfterEnter = (to: RouteState, from: RouteState) => {\n const matched = routes.find(r => matchRoute([r], to.path).route !== null);\n if (matched?.afterEnter) {\n try {\n matched.afterEnter(to, from);\n } catch (err) {\n devError('afterEnter error', err);\n }\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\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 (typeof window !== 'undefined' && typeof document !== 'undefined' && typeof initialUrl === 'undefined') {\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\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 = routes.find(r => matchRoute([r], to.path).route !== null);\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\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/**\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 \n component('router-view', (_props = {}, hooks: any = {}) => {\n const { onConnected } = hooks;\n // Set up router subscription on component connection\n if (onConnected) {\n onConnected(() => {\n if (router && typeof router.subscribe === 'function') {\n router.subscribe(() => {\n // The component will auto-rerender when router state changes\n });\n }\n });\n }\n\n if (!router) return html`<div>Router not initialized.</div>`;\n const current = router.getCurrent();\n const { path } = current;\n const match = router.matchRoute(path);\n if (!match.route) return html`<div>Not found</div>`;\n\n // Resolve the component (supports cached async loaders)\n return router.resolveRouteComponent(match.route).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 the function returned a string tag, render that element\n if (typeof resolvedComp === 'string') return { tag: resolvedComp, props: {}, children: [] };\n // Otherwise assume it's a VNode or VNode[] and return it directly\n return resolvedComp as any;\n });\n }\n\n // Unknown component type\n return html`<div>Invalid route component</div>`;\n }).catch(() => {\n // Propagate as an invalid route component to show a clear message in the view\n return html`<div>Invalid route component</div>`;\n });\n });\n\n component('router-link', (props: {\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 class?: string;\n } = {}, _hooks = {}) => {\n const {\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 class: userClass = ''\n } = props;\n // Recalculate computed values in render\n const current = router.getCurrent();\n \n // Computed\n const isExactActive = current.path === to;\n const isActive = exact\n ? isExactActive\n : current && typeof current.path === 'string'\n ? current.path.startsWith(to)\n : false;\n const ariaCurrent = isExactActive ? `aria-current=\"${ariaCurrentValue}\"` : '';\n \n // Build class object so JIT CSS can see the literal class names.\n const userClassList = (userClass || '').split(/\\s+/).filter(Boolean);\n const userClasses: Record<string, boolean> = {};\n for (const c of userClassList) userClasses[c] = true;\n const classObject = {\n ...userClasses,\n // Also include the configurable names (may duplicate the above)\n [activeClass]: isActive,\n [exactActiveClass]: isExactActive,\n };\n \n const isButton = tag === 'button';\n const disabledAttr = disabled\n ? isButton\n ? 'disabled aria-disabled=\"true\" tabindex=\"-1\"'\n : 'aria-disabled=\"true\" tabindex=\"-1\"'\n : '';\n const externalAttr = external && (tag === 'a' || !tag)\n ? 'target=\"_blank\" rel=\"noopener noreferrer\"'\n : '';\n\n const navigate = (e: MouseEvent) => {\n if (disabled) {\n e.preventDefault();\n return;\n }\n if (external && (tag === 'a' || !tag)) {\n return;\n }\n e.preventDefault();\n if (replace) {\n router.replace(to);\n } else {\n router.push(to);\n }\n };\n \n return html`\n ${match()\n .when(isButton, html`\n <button\n part=\"button\"\n :class=\"${classObject}\"\n ${ariaCurrent}\n ${disabledAttr}\n ${externalAttr}\n @click=\"${navigate}\"\n ><slot></slot></button>\n `)\n .otherwise(html`\n <a\n part=\"link\"\n href=\"${to}\"\n :class=\"${classObject}\"\n ${ariaCurrent}\n ${disabledAttr}\n ${externalAttr}\n @click=\"${navigate}\"\n ><slot></slot></a>\n `)\n .done()}\n `;\n });\n \n return router;\n}"],"names":["UpdateScheduler","update","componentId","key","updates","error","updateScheduler","scheduleDOMUpdate","proxiedObjects","ReactiveProxyCache","obj","reactiveState","isArray","cached","handler","proxy","ProxyOptimizer","target","prop","receiver","value","args","result","onUpdate","makeReactive","inner","reactiveContext","ReactiveSystem","renderFn","id","last","now","fn","wasDisabled","initialValue","ReactiveState","currentIndex","stateKey","stateInstance","state","dependencies","reactiveSystem","newValue","ref","isReactiveState","v","computed","computedState","watch","source","callback","options","oldValue","watcherId","updateWatcher","KEBAB_CASE_CACHE","CAMEL_CASE_CACHE","HTML_ESCAPE_CACHE","MAX_CACHE_SIZE","toKebab","str","toCamel","_","letter","escapeHTML","c","getNestedValue","path","current","setNestedValue","keys","lastKey","isDev","devError","message","devWarn","initWatchers","context","watchers","watchConfig","config","currentValue","triggerWatchers","isEqual","a","b","val","i","keysA","keysB","watcher","watchPath","watcherConfig","parseProp","type","applyPropsFromDefinitions","element","propDefinitions","def","kebab","attr","propValue","applyProps","cfg","handleConnected","isMounted","setMounted","handleDisconnected","listeners","clearListeners","clearWatchers","setTemplateLoading","setTemplateError","unsub","handleAttributeChanged","name","SecureExpressionEvaluator","expression","evaluator","firstKey","pattern","propertyPath","objectContent","properties","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","cond","parseLogicalOr","thenExpr","elseExpr","left","parseLogicalAnd","right","parseEquality","parseComparison","op","parseAdditive","parseMultiplicative","parseUnary","parsePrimary","arr","input","re","raw","EventManager","event","meta","list","cleanups","metaList","index","cleanupRefs","node","refs","refKey","child","assignRef","vnode","reactiveRef","processModelDirective","modifiers","props","attrs","el","arg","hasLazy","hasTrim","hasNumber","getCurrentValue","unwrapped","inputType","isNativeInput","propName","trueValue","option","attrName","eventType","eventListener","isTestEnv","fresh","trueV","falseV","o","n","actualState","currentStateValue","updated","watchKey","customEventName","customEvent","oldListener","eventName","newVal","eventNameFromKey","rest","processBindDirective","evaluated","evaluateExpression","processShowDirective","isVisible","currentStyle","newStyle","styleRules","rule","displayIndex","processClassDirective","classValue","classes","condition","className","existingClasses","allClasses","processStyleDirective","styleValue","styleString","property","kebabProperty","needsPx","cssValue","existingStyle","processRefDirective","resolvedValue","processDirectives","directives","vnodeAttrs","directiveName","directive","runtimeArg","assignKeysDeep","nodeOrNodes","baseKey","usedKeys","tagPart","idPart","uniqueKey","counter","children","patchProps","oldProps","newProps","newDirectives","processedDirectives","mergedProps","mergedAttrs","oldPropProps","newPropProps","elIsCustom","anyChange","oldVal","ev","listener","oldAttrs","newAttrs","oldUnwrapped","newUnwrapped","isSVG","camelKey","createElement","textNode","anchorVNode","start","end","frag","childNode","vnodeWithProcessedProps","patchChildren","parent","oldChildren","newChildren","oldNodes","oldVNodes","oldVNodeByKey","oldNodeByKey","k","usedNodes","nextSibling","markRangeUsed","cur","patchChildrenBetween","oldNodesInRange","oldVNodesInRange","oldVNodeByKeyRange","oldNodeByKeyRange","usedInRange","next","newVNode","oldVNode","patch","commonLength","aKey","startKey","endKey","dom","placeholder","newEl","vdomRenderer","root","vnodeOrArray","prevVNode","prevDom","newDom","nodesToRemove","renderToString","attrsString","propsString","css","strings","values","minifyCSS","baseResetSheet","getBaseResetSheet","baseReset","sanitizeCSS","fallbackHex","colors","shades","shade","hex","spacing","semanticSizes","generateSemanticSizeClasses","generateGridClasses","utilityMap","spacingProps","insertPseudoBeforeCombinator","sel","pseudo","depthSquare","depthParen","ch","selectorVariants","body","mediaVariants","responsiveOrder","parseSpacing","negative","numStr","num","sign","hexToRgb","clean","bigint","r","g","parseColorClass","colorName","colorValue","parseOpacityModifier","base","opacityStr","opacity","parseColorWithOpacity","paletteRule","rgb","arbitraryRule","parseArbitrary","parseOpacity","bracketStart","bracketEnd","propMap","cssProp","parseArbitraryVariant","token","escapeClassName","extractClassesFromHTML","html","classAttrRegex","classList","jitCssCache","JIT_CSS_THROTTLE_MS","jitCSS","bucket1","bucket2","bucket3","bucket4","ruleCache","generateRuleCached","cls","stripDark","cacheKey","generateRule","classify","before","hasResponsive","hasDark","splitVariants","out","buf","tokenToPseudo","important","basePart","p","cleanBase","baseRule","baseIndex","escapedClass","SUBJECT","selector","structural","subjectPseudos","innerPseudos","wrapperVariant","variantSelector","insertPseudosIntoPost","post","pseudos","subjectPseudoStr","innerPseudoStr","pre","subjectWithPseudos","currentSelector","postWithInner","responsiveTokens","lastResponsive","bucketNum","contextStack","renderComponent","shadowRoot","setHtmlString","setLoading","setError","applyStyle","outputOrPromise","output","renderOutput","requestRender","lastRenderTime","renderCount","setLastRenderTime","setRenderCount","renderTimeoutId","setRenderTimeoutId","timeoutId","htmlString","styleSheet","setStyleSheet","jitCss","userStyle","finalStyle","sheet","currentComponentContext","setCurrentComponentContext","clearCurrentComponentContext","useEmit","emitFn","detail","ensureHookCallbacks","useOnConnected","useOnDisconnected","useOnAttributeChanged","useOnError","useStyle","computedStyle","registry","GLOBAL_REG_KEY","createElementClass","tag","cfgToUse","internalValue","err","_cfg","createReactive","self","fullPath","newPath","component","normalizedTag","propDefaults","paramsMatch","propPairs","pair","equalIndex","defaultValue","lifecycleHooks","_context","hasProps","freshProps","hookCallbacks","LRUCache","maxSize","first","TEMPLATE_COMPILE_CACHE","validateEventHandler","h","finalKey","isAnchorBlock","isElementVNode","ensureKey","parseProps","bound","attrRegex","prefix","rawName","rawVal","interpMatch","knownDirectives","nameAndModifiers","argPart","maybeDirective","modifierParts","directiveKey","attrValue","originalHandler","wrappedHandler","onName","htmlImpl","injectedContext","effectiveContext","canCache","textVNode","text","template","tagRegex","stack","currentChildren","currentTag","currentProps","currentKey","nodeIndex","fragmentChildren","mergeIntoCurrentProps","maybe","newClasses","pushInterpolation","targetChildren","anchorKey","anchorChildren","voidElements","tagName","isClosing","isSelfClosing","rawProps","rawAttrs","boundList","vnodeProps","nativePromoteMap","lname","promotable","keyAttrs","camel","s","globalRegistry","isInGlobalRegistry","isInContext","dk","model","modelVal","argToUse","getNested","setNested","initial","camelEventName","handlerKey","prev","interp","cleanedFragments","when","anchorBlock","each","render","item","itemKey","branches","whenChain","childArray","unless","whenEmpty","collection","isEmpty","whenNotEmpty","hasItems","eachWhere","predicate","filtered","originalIndex","filteredIndex","switchOnLength","cases","length","eachGroup","groupBy","renderGroup","groups","groupKey","items","groupIndex","eachPage","pageSize","currentPage","startIndex","endIndex","pageIndex","globalIndex","switchOnPromise","promiseState","whenMedia","mediaQuery","matches","responsive","whenVariants","variants","conditions","responsiveVariants","responsiveSwitch","results","breakpoint","breakpointContent","switchOn","otherwiseContent","matcher","GlobalEventBus","data","eventHandlers","resolve","unsubscribe","stats","eventBus","emit","on","off","once","listen","createStore","subscribe","getState","setState","partial","notify","parseQuery","search","matchRoute","routes","route","paramNames","regexPath","regex","params","componentCache","resolveRouteComponent","mod","useRouter","initialUrl","getLocation","store","push","replaceFn","back","runBeforeEnter","to","from","matched","navigate","runOnEnter","runAfterEnter","replace","loc","url","query","navigateSSR","matchRouteSSR","initRouter","router","_props","hooks","onConnected","comp","resolvedComp","_hooks","exact","activeClass","exactActiveClass","ariaCurrentValue","disabled","external","userClass","isExactActive","isActive","ariaCurrent","userClassList","userClasses","classObject","isButton","disabledAttr","externalAttr","e"],"mappings":"gFAKA,MAAMA,EAAgB,CACZ,mBAAqB,IACrB,iBAAmB,GAM3B,SAASC,EAAoBC,EAA4B,CACvD,MAAMC,EAAMD,GAAeD,EAAO,SAAA,EAClC,KAAK,eAAe,IAAIE,EAAKF,CAAM,EAE9B,KAAK,mBACR,KAAK,iBAAmB,GAGN,OAAQ,WAAmB,QAAY,KACtC,WAAmB,QAAQ,KAAK,WAAa,QAC9C,OAAO,OAAW,MAAiB,OAAe,YAAe,OAAe,SAIhG,KAAK,MAAA,EAEL,eAAe,IAAM,KAAK,OAAO,EAGvC,CAKQ,OAAc,CACpB,MAAMG,EAAU,MAAM,KAAK,KAAK,eAAe,QAAQ,EACvD,KAAK,eAAe,MAAA,EACpB,KAAK,iBAAmB,GAGxB,UAAWH,KAAUG,EACnB,GAAI,CACFH,EAAA,CACF,OAASI,EAAO,CAEV,OAAO,QAAY,KAAe,QAAQ,OAC5C,QAAQ,MAAM,2BAA4BA,CAAK,CAEnD,CAEJ,CAKA,IAAI,cAAuB,CACzB,OAAO,KAAK,eAAe,IAC7B,CACF,CAGO,MA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