@estjs/template 0.0.15-beta.9 → 0.0.16-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3E4EK64L.dev.esm.js +152 -0
- package/dist/chunk-3E4EK64L.dev.esm.js.map +1 -0
- package/dist/chunk-IRDMO5MX.esm.js +2 -0
- package/dist/chunk-IRDMO5MX.esm.js.map +1 -0
- package/dist/internal-Bz6h0aPa.d.cts +84 -0
- package/dist/internal-Bz6h0aPa.d.ts +84 -0
- package/dist/internal.cjs.js +2 -0
- package/dist/internal.cjs.js.map +1 -0
- package/dist/internal.d.cts +1 -0
- package/dist/internal.d.ts +1 -0
- package/dist/internal.dev.cjs.js +110 -0
- package/dist/internal.dev.cjs.js.map +1 -0
- package/dist/internal.dev.esm.js +3 -0
- package/dist/internal.dev.esm.js.map +1 -0
- package/dist/internal.esm.js +2 -0
- package/dist/internal.esm.js.map +1 -0
- package/dist/template.cjs.js +2 -2
- package/dist/template.cjs.js.map +1 -1
- package/dist/template.d.cts +439 -312
- package/dist/template.d.ts +439 -312
- package/dist/template.dev.cjs.js +1523 -1109
- package/dist/template.dev.cjs.js.map +1 -1
- package/dist/template.dev.esm.js +1445 -1178
- package/dist/template.dev.esm.js.map +1 -1
- package/dist/template.esm.js +2 -2
- package/dist/template.esm.js.map +1 -1
- package/package.json +13 -3
package/dist/template.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/renderer.ts","../src/scope.ts","../src/constants.ts","../src/key.ts","../src/utils/node.ts","../src/utils/dom.ts","../src/patch.ts","../src/utils/shared.ts","../src/binding.ts","../src/lifecycle.ts","../src/component.ts","../src/provide.ts","../src/events.ts","../src/utils/props.ts","../src/operations/class.ts","../src/operations/styles.ts","../src/operations/attr.ts","../src/operations/event.ts","../src/components/Fragment.ts","../src/components/Portal.ts","../src/components/Suspense.ts","../src/components/createResource.ts"],"names":["activeScope","scopeId","getActiveScope","setActiveScope","scope","createScope","parent","runWithScope","fn","prevScope","disposeScope","_a","_b","_c","_d","_e","child","hook","error_","onCleanup","SPREAD_NAME","SVG_NAMESPACE","XLINK_NAMESPACE","XMLNS_NAMESPACE","MAX_KEY_LENGTH","componentKeyPrefixCache","getComponentKey","type","prefix","name","hash","simpleHash","str","len","i","symbolIdCounter","normalizeKey","key","isFalsy","isString","isNumber","isSymbol","globalKey","desc","NODE_KEY_SYMBOL","setNodeKey","node","isComponent","normalizedKey","getNodeKey","normalizeNode","isHTMLElement","isPrimitive","textContent","isSameNode","a","b","keyA","keyB","aIsComponent","bIsComponent","aNode","bNode","shallowCompare","removeNode","element","_error","error","insertNode","before","beforeNode","replaceNode","newNode","oldNode","getFirstDOMNode","transferKey","oldKey","patch","oldIsElement","oldAttrs","newAttrs","attrName","attr","isTextNode","oldIsComponent","newIsComponent","patchChildren","oldChildren","newChildren","anchor","oldLength","newLength","o0","o1","n0","n1","dom1","dom0","patchKeyedChildren","oldStartIdx","newStartIdx","oldEndIdx","newEndIdx","oldStartNode","oldEndNode","newStartNode","newEndNode","anchorNode","patchUnknownSequence","keyToNewIndexMap","newIndexToOldIndexMap","moved","maxNewIndexSoFar","patched","newIndex","j","increasingNewIndexSequence","getSequence","cachedAnchor","nextIndex","nextNode","domNode","arr","result","p","u","v","arrI","isHydrationActive","startHydration","endHydration","isHydrating","addEventListener","event","handler","options","bindElement","defaultValue","setter","isHtmlInputElement","bindInputElement","isHtmlSelectElement","bindSelectElement","isHtmlTextAreaElement","values","option","isFirstRun","executeReactiveUpdate","ownerScope","nodeFactory","renderedNodes","executeUpdate","rawNodes","isFunction","nodes","coerceArray","item","insert","cleanup","effect","mapNodes","template","indexes","tree","indexSet","index","found","walk","registerMountHook","registerUpdateHook","registerDestroyHook","triggerMountHooks","triggerUpdateHooks","onMount","onDestroy","onUpdate","Component","component","props","shallowReactive","__spreadValues","dom","parentNode","isSignal","isComputed","prevNode","hasChanges","newValue","oldValue","isObject","__async","originalNodes","newNodes","lastNode","lastDom","firstElement","propName","propValue","startsWith","eventName","createComponent","componentFn","html","create","firstChild","createApp","target","container","rootComponent","provide","value","inject","current","eventHandler","oriTarget","oriCurrentTarget","reTarget","handleNode","data","walkUpTree","path","$EVENTS","delegateEvents","eventNames","document","docWithEvents","eventSet","omitProps","keys","excludeSet","obj","prop","patchClass","el","prev","next","isSVG","normalizedNext","normalizeClass","normalizedPrev","normalizeClassName","importantRE","prefixes","prefixCache","patchStyle","style","isCssString","setStyle","prevStyles","stylePart","colonIndex","val","isArray","prefixed","autoPrefix","camelCase","rawName","cached","capitalize","patchAttr","k","elementIsSVG","isXlink","isXmlns","isBoolean","isSpecialBooleanAttr","isBooleanAttr","lowerKey","localName","includeBooleanAttr","attrValue","e","addEvent","selector","wrappedHandler","cleanOptions","Fragment","isFragment","Portal","children","placeholder","childArray","targetElement","normalized","isPortal","SuspenseContext","Suspense","isUndefined","fallback","isMounted","pendingCount","isShowingFallback","resolvedChildren","showFallback","showChildren","isPromise","renderChildren","currentScope","suspenseContext","promise","resolved","isSuspense","createResource","fetcher","signal","loading","state","fetchId","currentPromise","fetch","currentFetchId","resource"],"mappings":"mFAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,qBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,oBAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,G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MAAMuH,CAAAA,GACR,CAAA,CACF,CAEyB,CAC3B","file":"template.cjs.js","sourcesContent":["import { error, isString } from '@estjs/shared';\nimport { createComponent } from './component';\nimport type { ComponentFn, ComponentProps } from './types';\n\n/**\n * Create a template factory function from HTML string\n *\n * This function creates a reusable template factory that efficiently clones\n * DOM nodes from the provided HTML string. The template is parsed once and\n *\n * @param html - The HTML string to create template from\n * @returns Factory function that returns a cloned node of the template\n * @throws {Error} When template content is empty or invalid\n *\n * @example\n * ```typescript\n * const buttonTemplate = template('<button>Click me</button>');\n * const button1 = buttonTemplate(); // Creates first button instance\n * const button2 = buttonTemplate(); // Creates second button instance\n * ```\n */\nexport function template(html: string) {\n let node: Node | undefined;\n\n const create = (): Node => {\n // Regular HTML template\n const template = document.createElement('template');\n template.innerHTML = html;\n const firstChild = template.content.firstChild;\n if (!firstChild) {\n throw new Error('Invalid template: empty content');\n }\n return firstChild;\n };\n\n // return a factory function: create the template when first called, reuse the cached template when called later\n return () => (node || (node = create())).cloneNode(true);\n}\n\n/**\n * Create and mount an application with the specified component\n *\n * This function initializes an application by mounting a root component\n * to a target DOM element. It handles target validation and cleanup.\n *\n * @param component - The root component function to mount\n * @param target - CSS selector string or DOM element to mount to\n * @returns The mount root component instance, or undefined if target not found\n *\n * @example\n * ```typescript\n * const App = () => template('<div>Hello World</div>')\n * const app = createApp(App, '#root');\n *\n * // Or with DOM element\n * const container = document.getElementById('app');\n * const app = createApp(App, container);\n * ```\n */\nexport function createApp<P extends ComponentProps = {}>(\n component: ComponentFn<P>,\n target: string | Element,\n) {\n const container = isString(target)\n ? document.querySelector(target as string)\n : (target as Element);\n if (!container) {\n error(`Target element not found: ${target}`);\n return;\n }\n\n const existingContext = container.innerHTML;\n if (existingContext) {\n error(`Target element is not empty, it will be delete: ${target}`);\n container.innerHTML = '';\n }\n\n const rootComponent = createComponent(component);\n rootComponent.mount(container);\n\n return rootComponent;\n}\n","import { error } from '@estjs/shared';\nimport type { InjectionKey } from './provide';\n\n/**\n * Scope represents an execution context in the component tree.\n * It manages provides, cleanup functions, and lifecycle hooks.\n */\nexport interface Scope {\n /** Unique identifier for debugging */\n readonly id: number;\n\n /** Parent scope in the hierarchy */\n parent: Scope | null;\n\n /** Child scopes (lazy initialized) */\n children: Set<Scope> | null;\n\n /** Provided values (lazy initialized) */\n provides: Map<InjectionKey<unknown> | string | number | symbol, unknown> | null;\n\n /** Cleanup functions (lazy initialized) */\n cleanup: Set<() => void> | null;\n\n /** Mount lifecycle hooks (lazy initialized) */\n onMount: Set<() => void | Promise<void>> | null;\n\n /** Update lifecycle hooks (lazy initialized) */\n onUpdate: Set<() => void | Promise<void>> | null;\n\n /** Destroy lifecycle hooks (lazy initialized) */\n onDestroy: Set<() => void | Promise<void>> | null;\n\n /** Whether the scope has been mounted */\n isMounted: boolean;\n\n /** Whether the scope has been destroyed */\n isDestroyed: boolean;\n}\n\n/** Currently active scope */\nlet activeScope: Scope | null = null;\n\n/** Scope ID counter for unique identification */\nlet scopeId = 0;\n\n/**\n * Get the currently active scope.\n * @returns The active scope or null if none is active\n */\nexport function getActiveScope(): Scope | null {\n return activeScope;\n}\n\n/**\n * Set the active scope (internal use).\n * @param scope - The scope to set as active\n */\nexport function setActiveScope(scope: Scope | null): void {\n activeScope = scope;\n}\n\n/**\n * Create a new scope with optional parent.\n * If no parent is provided, uses the current active scope as parent.\n *\n * @param parent - Optional parent scope (defaults to active scope)\n * @returns A new scope instance\n */\nexport function createScope(parent: Scope | null = activeScope): Scope {\n const scope: Scope = {\n id: ++scopeId,\n parent,\n children: null, // Lazy initialized\n provides: null, // Lazy initialized\n cleanup: null, // Lazy initialized\n onMount: null, // Lazy initialized\n onUpdate: null, // Lazy initialized\n onDestroy: null, // Lazy initialized\n isMounted: false,\n isDestroyed: false,\n };\n\n // Establish parent-child relationship\n if (parent) {\n if (!parent.children) {\n parent.children = new Set();\n }\n parent.children.add(scope);\n }\n\n return scope;\n}\n\n/**\n * Run a function within a scope, ensuring proper cleanup.\n * The previous active scope is restored even if the function throws.\n *\n * @param scope - The scope to run within\n * @param fn - The function to execute\n * @returns The return value of the function\n */\nexport function runWithScope<T>(scope: Scope, fn: () => T): T {\n const prevScope = activeScope;\n activeScope = scope;\n\n try {\n return fn();\n } finally {\n // Restore previous scope directly\n activeScope = prevScope;\n }\n}\n\n/**\n * Dispose a scope and all its children.\n * Children are disposed first (depth-first), then the scope itself.\n *\n * @param scope - The scope to dispose\n */\nexport function disposeScope(scope: Scope): void {\n // Idempotent: already destroyed\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n // Dispose children first (depth-first)\n // Iterate directly without copying to avoid allocation\n if (scope.children) {\n // Use while loop since children will remove themselves during dispose\n while (scope.children.size > 0) {\n const child = scope.children.values().next().value;\n if (child) {\n disposeScope(child);\n }\n }\n }\n\n // Execute destroy lifecycle hooks\n if (scope.onDestroy) {\n for (const hook of scope.onDestroy) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in destroy hook:`, error_);\n }\n }\n }\n scope.onDestroy.clear();\n }\n\n // Execute cleanup functions\n if (scope.cleanup) {\n for (const fn of scope.cleanup) {\n try {\n fn();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in cleanup:`, error_);\n }\n }\n }\n scope.cleanup.clear();\n }\n\n // Remove from parent's children\n if (scope.parent?.children) {\n scope.parent.children.delete(scope);\n }\n\n // Clear all internal collections\n scope.children?.clear();\n scope.provides?.clear();\n scope.onMount?.clear();\n scope.onUpdate?.clear();\n\n // reset active with parent scope\n setActiveScope(scope.parent);\n\n // Break parent reference to prevent memory leaks\n scope.parent = null;\n\n // Mark as destroyed\n scope.isDestroyed = true;\n}\n\n/**\n * Register a cleanup function in the current scope.\n * The function will be called when the scope is disposed.\n *\n * @param fn - The cleanup function\n */\nexport function onCleanup(fn: () => void): void {\n const scope = activeScope;\n\n if (!scope) {\n if (__DEV__) {\n error('onCleanup() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize cleanup set\n if (!scope.cleanup) {\n scope.cleanup = new Set();\n }\n\n scope.cleanup.add(fn);\n}\n","/**\n * event prefix, used to distinguish event handler properties\n */\nexport const EVENT_PREFIX = 'on';\n\n/**\n * update prefix, used to identify update callback properties\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * children property name\n */\nexport const CHILDREN_PROP = 'children';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * used to get the DOM element reference\n */\nexport const REF_KEY = 'ref';\n/**\n * Component key property name\n */\nexport const KEY_PROP = 'key' as const;\n\n/**\n * SVG namespace constant\n */\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n/**\n * XML namespace for xlink attributes\n */\nexport const XLINK_NAMESPACE = 'http://www.w3.org/2000/xlink';\n\n/**\n * xmlns namespace for SVG elements\n */\nexport const XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';\n\n/**\n * Defines various states of components for state management and debugging\n */\nexport enum COMPONENT_STATE {\n /** Initial state */\n INITIAL,\n /** Mounting */\n MOUNTING,\n /** MOUNTED */\n MOUNTED,\n /** Updating */\n UPDATING,\n /** Destroying */\n DESTROYING,\n /** destroy */\n DESTROYED,\n}\n\nexport enum COMPONENT_TYPE {\n NORMAL = 'normal',\n FRAGMENT = 'fragment',\n PORTAL = 'portal',\n SUSPENSE = 'suspense',\n FOR = 'for',\n}\n","import { error, isFalsy, isHTMLElement, isNumber, isString, isSymbol, warn } from '@estjs/shared';\nimport { isComponent } from './component';\nimport type { AnyNode } from './types';\n\n/** Maximum allowed key length before truncation */\nconst MAX_KEY_LENGTH = 1000;\n\nexport type NodeKey = string | number | symbol;\n\n/** Cache for component type key prefixes */\nconst componentKeyPrefixCache = new WeakMap<Function, string>();\n\n/**\n * Generates a stable key prefix for a component type.\n *\n * @param type - The component function\n * @returns The generated key prefix\n */\nexport function getComponentKey(type: Function): string {\n let prefix = componentKeyPrefixCache.get(type);\n if (!prefix) {\n const name = type.name || 'anonymous';\n const hash = simpleHash(type.toString()).toString(36);\n prefix = `${name}_${hash}`;\n componentKeyPrefixCache.set(type, prefix);\n }\n return prefix;\n}\n\n/**\n * DJB2 hash variant - fast string hashing.\n * Limited to first 100 chars for performance.\n *\n * @param str - The input string\n * @returns The hash code (always positive)\n */\nfunction simpleHash(str: string): number {\n let hash = 0;\n const len = str.length < 100 ? str.length : 100;\n for (let i = 0; i < len; i++) {\n hash = Math.trunc((hash << 5) - hash + str.charCodeAt(i));\n }\n return hash < 0 ? -hash : hash;\n}\n\n/** Counter for generating unique IDs for local symbols */\nlet symbolIdCounter = 0;\n\n/**\n * Normalize any key value to a string.\n * Optimized with inline type checks for hot path performance.\n *\n * @param key - The key value to normalize\n * @returns Normalized string key or undefined for null/undefined\n */\nexport function normalizeKey(key: any): string | undefined {\n if (isFalsy(key)) {\n return undefined;\n }\n\n if (isString(key)) {\n if (key.length <= MAX_KEY_LENGTH) {\n return key;\n }\n if (__DEV__) {\n warn(\n `[Key System] Key length exceeds ${MAX_KEY_LENGTH} characters. ` +\n 'Consider using a shorter identifier.',\n );\n }\n return `${key.slice(0, MAX_KEY_LENGTH - 10)}_${simpleHash(key).toString(36)}`;\n }\n\n if (isNumber(key)) {\n if (__DEV__) {\n if (key !== key) {\n warn('[Key System] NaN cannot be used as a key');\n return undefined;\n }\n if (!Number.isFinite(key)) {\n warn('[Key System] Infinity cannot be used as a key');\n return undefined;\n }\n }\n return String(key);\n }\n\n // Symbol path\n if (isSymbol(key)) {\n const globalKey = Symbol.keyFor(key);\n if (globalKey) {\n return `_s.${globalKey}`;\n }\n const desc = key.description;\n return desc ? `_s.${desc}` : `${symbolIdCounter++}`;\n }\n\n return String(key);\n}\n\n/**\n * Check if two nodes have the same type for reconciliation.\n * Used in hot paths - optimized for minimal branching.\n *\n * @param a - First node\n * @param b - Second node\n * @returns True if nodes are the same type\n */\nexport function isSameNodeType(a: AnyNode, b: AnyNode): boolean {\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n // Both components - compare component function\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n // Both DOM nodes - compare nodeType and tagName\n const aNode = a as Node;\n const bNode = b as Node;\n\n return (\n aNode.nodeType === bNode.nodeType &&\n (aNode.nodeType !== Node.ELEMENT_NODE ||\n (aNode as Element).tagName === (bNode as Element).tagName)\n );\n}\n\n/** Symbol for storing keys on DOM nodes */\nconst NODE_KEY_SYMBOL = Symbol('essor.key');\n\n/**\n * Set a key on a DOM node using Symbol property.\n * Symbol properties are ~40% faster than WeakMap access.\n *\n * @param node - The node to set key on\n * @param key - The key value (will be normalized)\n */\nexport function setNodeKey(node: AnyNode, key: NodeKey | undefined): void {\n // Skip components - they manage their own keys\n if (isComponent(node)) {\n return;\n }\n\n // Validate node\n if (!node || (node as Node).nodeType === Node.DOCUMENT_NODE) {\n if (__DEV__) {\n warn('[Key System] Cannot set key on invalid node');\n }\n return;\n }\n\n const normalizedKey = normalizeKey(key);\n if (isFalsy(normalizedKey)) {\n delete (node as any)[NODE_KEY_SYMBOL];\n } else {\n (node as any)[NODE_KEY_SYMBOL] = normalizedKey;\n }\n}\n\n/**\n * Get the key from a node or component.\n * Optimized for inline usage in hot paths.\n *\n * @param node - The node to get key from\n * @returns The key string or undefined\n */\nexport function getNodeKey(node: AnyNode): string | undefined {\n if (!node) return undefined;\n return isComponent(node) ? node.key : (node as any)[NODE_KEY_SYMBOL];\n}\n\n/**\n * Get node's key or return an index-based fallback.\n * Fallback keys start with '.' to distinguish from user keys.\n *\n * @param node - The node to get key from\n * @param fallbackIndex - Index to use if no key exists\n * @returns The key or fallback string\n */\nexport function getKeyOrFallback(node: AnyNode, fallbackIndex: number): string {\n return getNodeKey(node) || `.${fallbackIndex}`;\n}\n\n/**\n * Validate that child keys are unique (Development only).\n * Logs errors for duplicate keys to help debugging.\n *\n * @param children - Array of child nodes\n * @param parent - Optional parent node for error context\n */\nexport function validateKeys(children: AnyNode[], parent?: Node): void {\n if (!__DEV__) return;\n\n const keySet = new Set<string>();\n const duplicates: string[] = [];\n const len = children.length;\n\n for (let i = 0; i < len; i++) {\n const key = getKeyOrFallback(children[i], i);\n\n // Skip auto-generated fallback keys (start with '.')\n if (key[0] === '.') continue;\n\n if (keySet.has(key)) {\n duplicates.push(key);\n } else {\n keySet.add(key);\n }\n }\n\n if (duplicates.length > 0) {\n const parentTag = isHTMLElement(parent) ? parent.tagName.toLowerCase() : 'unknown';\n error(\n `Duplicate keys detected in <${parentTag}>: [${duplicates.join(', ')}]\\n` +\n 'Keys must be unique among siblings.',\n );\n }\n}\n","/**\n * Node normalization and comparison utilities\n */\n\nimport { isFalsy, isHTMLElement, isPrimitive, isTextNode } from '@estjs/shared';\nimport { isComponent } from '../component';\nimport { getNodeKey } from '../key';\nimport type { AnyNode } from '../types';\n\n/**\n * Normalize node for reconciliation\n * Converts primitives to text nodes\n *\n * @param node - Node to normalize\n * @returns Normalized DOM node\n */\nexport function normalizeNode(node: unknown): Node {\n // Already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n\n // Handle primitives - convert to text nodes\n if (isPrimitive(node)) {\n const textContent = isFalsy(node) ? '' : String(node);\n return document.createTextNode(textContent);\n }\n\n return node as Node;\n}\n\n/**\n * Check if two nodes are the same (for reconciliation)\n * Combines key check and type check\n *\n * @param a - First node\n * @param b - Second node\n * @returns true if nodes are considered the same\n */\nexport function isSameNode(a: AnyNode, b: AnyNode): boolean {\n // Check key equality first (fast path)\n const keyA = getNodeKey(a);\n const keyB = getNodeKey(b);\n\n if (keyA !== keyB) {\n return false;\n }\n\n // Inline type check to avoid function call\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n if (aIsComponent !== bIsComponent) {\n return false;\n }\n\n if (isPrimitive(a) || isPrimitive(b)) {\n return a === b;\n }\n\n const aNode = a as Node;\n const bNode = b as Node;\n\n if (aNode.nodeType !== bNode.nodeType) {\n return false;\n }\n\n if (aNode.nodeType === Node.ELEMENT_NODE) {\n return (aNode as Element).tagName === (bNode as Element).tagName;\n }\n\n return true;\n}\n\n/**\n * Check if a value is a Text node\n * Re-exported from shared for convenience\n */\nexport function isHtmlTextElement(val: unknown): val is Text {\n return isTextNode(val);\n}\n\n/**\n * Shallow compare two objects\n *\n * @param a - First object\n * @param b - Second object\n * @returns true if objects are shallowly equal\n */\nexport function shallowCompare(a: any, b: any): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n\n for (const key in a) {\n if (a[key] !== b[key]) return false;\n }\n\n for (const key in b) {\n if (!(key in a)) return false;\n }\n\n return true;\n}\n","/**\n * DOM manipulation utilities\n */\n\nimport { error, isPrimitive } from '@estjs/shared';\nimport { isComponent } from '../component';\nimport type { AnyNode } from '../types';\n\n/**\n * Remove node from its parent\n *\n * @param node - Node to remove\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n try {\n if (isComponent(node)) {\n node.destroy();\n } else {\n const element = node as Element;\n if (element.parentElement) {\n element.remove();\n }\n }\n } catch (_error) {\n error('Failed to remove node:', _error);\n }\n}\n\n/**\n * Insert child node into parent\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param child - Child node to insert\n * @param before - Reference node for insertion position\n */\nexport function insertNode(parent: Node, child: AnyNode, before?: AnyNode): void {\n if (!parent || !child) return;\n\n try {\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (isComponent(child)) {\n child.mount(parent, beforeNode);\n return;\n }\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n if (__DEV__) {\n if (!child) {\n error('insertNode: child is not a Node', child);\n }\n }\n parent.appendChild(child as Node);\n }\n } catch (_error) {\n error('Failed to insert node:', _error);\n }\n}\n\n/**\n * Replace child node with a new node\n * Handles both component nodes and DOM nodes\n *\n * @param parent - Parent node\n * @param newNode - New node to insert\n * @param oldNode - Old node to be replaced\n */\nexport function replaceNode(parent: Node, newNode: AnyNode, oldNode: AnyNode): void {\n if (!parent || !newNode || !oldNode || newNode === oldNode) return;\n\n try {\n const beforeNode: AnyNode | undefined = isComponent(oldNode)\n ? oldNode.beforeNode\n : (oldNode as Node).nextSibling!;\n removeNode(oldNode);\n insertNode(parent, newNode, beforeNode);\n } catch (_error) {\n error('Failed to replace node:', _error);\n }\n}\n\n/**\n * Get the first DOM node from a node or component\n *\n * @param node - Node or component\n * @returns The first DOM node or undefined\n */\nexport function getFirstDOMNode(node: AnyNode): Node | undefined {\n if (!node) {\n return;\n }\n\n if (isComponent(node)) {\n return node.firstChild;\n }\n\n if (isPrimitive(node)) {\n return undefined;\n }\n\n return node as Node;\n}\n","import { isHTMLElement, isTextNode } from '@estjs/shared';\nimport { isComponent } from './component';\nimport { getNodeKey, setNodeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode, replaceNode } from './utils/dom';\nimport { isSameNode } from './utils/node';\n\nimport type { AnyNode } from './types';\n\n/**\n * Transfer key from old node to new node if new node doesn't have one.\n * Skips component nodes as they manage their own keys.\n *\n * @param oldNode - Source node to transfer key from\n * @param newNode - Target node to receive key\n */\nexport function transferKey(oldNode: AnyNode, newNode: AnyNode): void {\n // Components manage their own keys, skip them\n if (isComponent(oldNode) || isComponent(newNode)) {\n return;\n }\n\n const oldKey = getNodeKey(oldNode);\n if (oldKey && !getNodeKey(newNode)) {\n setNodeKey(newNode, oldKey);\n }\n}\n\n/**\n * Patches a single node, updating it if possible or replacing it.\n * Optimized for common cases with early returns and minimal allocations.\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(a) where a is the number of attributes\n * - Same reference check: O(1)\n * - Element equality check: O(a) for attribute comparison\n * - Attribute patching: O(a) for iterating attributes\n * - Text node update: O(1)\n * - Component update: O(1) for type check, O(n) for component update\n * - Node replacement: O(1) for DOM operation\n *\n * - **Space Complexity**: O(1) - no additional allocations for common cases\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path for same reference**: Returns immediately if nodes are identical\n * 2. **Fast path for equal nodes**: Uses isEqualNode() for structural equality\n * 3. **In-place attribute updates**: Modifies existing DOM nodes when possible\n * 4. **Minimal allocations**: Avoids creating intermediate arrays\n *\n * @param parent - The parent node\n * @param oldNode - The old node\n * @param newNode - The new node\n * @returns The patched node (reused old node or new node)\n */\nexport function patch(parent: Node, oldNode: AnyNode, newNode: AnyNode): AnyNode {\n // Fast path: same reference\n if (newNode === oldNode) {\n return oldNode;\n }\n\n // Cache type checks to avoid repeated function calls\n const oldIsElement = isHTMLElement(oldNode);\n const newIsElement = isHTMLElement(newNode);\n\n // Both are HTML elements - optimize attribute patching\n if (newIsElement && oldIsElement) {\n // Fast path: structurally equal nodes\n if (newNode.isEqualNode(oldNode)) {\n return oldNode;\n }\n\n // Patch attributes if tags are same\n if (oldNode.tagName === newNode.tagName) {\n // Iterate directly without creating intermediate arrays\n const oldAttrs = oldNode.attributes;\n const newAttrs = newNode.attributes;\n\n // Remove old attributes not in new (iterate backwards to handle live collection)\n for (let i = oldAttrs.length - 1; i >= 0; i--) {\n const attrName = oldAttrs[i].name;\n if (!newNode.hasAttribute(attrName)) {\n oldNode.removeAttribute(attrName);\n }\n }\n\n // Set new/changed attributes\n for (let i = 0, len = newAttrs.length; i < len; i++) {\n const attr = newAttrs[i];\n if (oldNode.getAttribute(attr.name) !== attr.value) {\n oldNode.setAttribute(attr.name, attr.value);\n }\n }\n\n transferKey(oldNode, newNode);\n return oldNode;\n }\n }\n\n // Handle text nodes\n if (isTextNode(oldNode) && isTextNode(newNode)) {\n if (oldNode.textContent !== newNode.textContent) {\n oldNode.textContent = newNode.textContent;\n }\n transferKey(oldNode, newNode);\n return oldNode;\n }\n\n // Handle component instances - cache isComponent results\n const oldIsComponent = isComponent(oldNode);\n const newIsComponent = isComponent(newNode);\n\n if (oldIsComponent && newIsComponent) {\n if (oldNode.component === newNode.component) {\n return newNode.update(oldNode);\n }\n }\n\n // Different types, replace\n replaceNode(parent, newNode, oldNode);\n return newNode;\n}\n\n/**\n * Unified children patching with Map-based diffing and LIS optimization.\n *\n * ## Algorithm Complexity\n *\n * - **Best Case**: O(1) - both arrays empty\n * - **Fast Paths**: O(n) - mount all, unmount all, single child, two children\n * - **General Case**: O(n + m) where n = old children, m = new children\n * - Common prefix/suffix sync: O(min(n, m))\n * - Unknown sequence with LIS: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**:\n * - Fast paths: O(1)\n * - General case: O(m) for index mapping + O(k) for LIS\n *\n * ## Optimization Strategy\n *\n * 1. **Fast path 0**: Both empty - O(1) immediate return\n * 2. **Fast path 1**: Mount all - O(m) simple insertion loop\n * 3. **Fast path 2**: Unmount all - O(n) simple removal loop\n * 4. **Fast path 3**: Single child - O(1) direct patch or replace\n * 5. **Fast path 4**: Two children - O(1) handles same order and swap\n * 6. **General algorithm**: Full diff with LIS optimization\n *\n * ## When Each Path is Used\n *\n * - **Empty arrays**: Initial render or complete removal\n * - **Mount all**: First render of a list\n * - **Unmount all**: Conditional rendering (v-if becomes false)\n * - **Single child**: Most common case in practice\n * - **Two children**: Common for toggle/swap scenarios\n * - **General**: Complex list updates with reordering\n *\n * @param parent - The parent DOM node\n * @param oldChildren - Array of current children\n * @param newChildren - Array of new children\n * @param anchor - Optional anchor node for insertions\n * @returns Patched array of children\n */\nexport function patchChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n const oldLength = oldChildren.length;\n const newLength = newChildren.length;\n\n // FAST PATH 0: Both empty\n if (oldLength === 0 && newLength === 0) {\n return [];\n }\n\n // FAST PATH 1: Mount all (no old children)\n if (oldLength === 0) {\n for (let i = 0; i < newLength; i++) {\n insertNode(parent, newChildren[i], anchor);\n }\n return newChildren;\n }\n\n // FAST PATH 2: Unmount all (no new children)\n if (newLength === 0) {\n // Remove all children efficiently\n for (let i = 0; i < oldLength; i++) {\n removeNode(oldChildren[i]);\n }\n return [];\n }\n\n // FAST PATH 3: Single child\n if (oldLength === 1 && newLength === 1) {\n const oldNode = oldChildren[0];\n const newNode = newChildren[0];\n if (isSameNode(oldNode, newNode)) {\n patch(parent, oldNode, newNode);\n newChildren[0] = oldNode;\n } else {\n replaceNode(parent, newNode, oldNode);\n }\n return newChildren;\n }\n\n // FAST PATH 4: Two children\n if (oldLength === 2 && newLength === 2) {\n const o0 = oldChildren[0];\n const o1 = oldChildren[1];\n const n0 = newChildren[0];\n const n1 = newChildren[1];\n\n // Same order\n if (isSameNode(o0, n0) && isSameNode(o1, n1)) {\n patch(parent, o0, n0);\n patch(parent, o1, n1);\n newChildren[0] = o0;\n newChildren[1] = o1;\n return newChildren;\n }\n\n // Swapped\n if (isSameNode(o0, n1) && isSameNode(o1, n0)) {\n patch(parent, o0, n1);\n patch(parent, o1, n0);\n // Move o1 before o0\n const dom1 = getFirstDOMNode(o1);\n const dom0 = getFirstDOMNode(o0);\n if (dom1 && dom0 && dom1.parentNode === parent) {\n parent.insertBefore(dom1, dom0);\n }\n newChildren[0] = o1;\n newChildren[1] = o0;\n return newChildren;\n }\n }\n\n // GENERAL ALGORITHM: Map-based diffing with LIS\n return patchKeyedChildren(parent, oldChildren, newChildren, anchor);\n}\n\n/**\n * General-purpose keyed children patching using optimized diff algorithm.\n *\n * ## Algorithm Overview\n *\n * This implements a two-pointer algorithm similar to Vue 3's diff algorithm:\n * 1. **Sync from start**: Match common prefix (same keys in same order)\n * 2. **Sync from end**: Match common suffix (same keys in same order)\n * 3. **Handle remaining**: Mount new, unmount old, or diff unknown sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m) where n = old length, m = new length\n * - Prefix sync: O(min(n, m))\n * - Suffix sync: O(min(n, m))\n * - Remaining: O(max(n, m))\n * - Unknown sequence: O(n + m + k log k) where k = moved nodes\n *\n * - **Space Complexity**: O(1) for sync phases, O(m) for unknown sequence\n *\n * ## Why This Algorithm?\n *\n * Real-world list updates often have:\n * - **Common prefix**: Items at the start rarely change\n * - **Common suffix**: Items at the end rarely change\n * - **Small changes**: Only a few items in the middle change\n *\n * By syncing prefix and suffix first, we minimize the \"unknown sequence\"\n * that requires expensive diffing.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [A, B, X, Y, E]\n *\n * Step 1: Sync prefix → A, B matched\n * Step 2: Sync suffix → E matched\n * Step 3: Unknown sequence → [C, D] vs [X, Y]\n * ```\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param anchor - Optional anchor node\n * @returns Patched new children array\n */\nfunction patchKeyedChildren(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n anchor?: Node,\n): AnyNode[] {\n let oldStartIdx = 0;\n let newStartIdx = 0;\n let oldEndIdx = oldChildren.length - 1;\n let newEndIdx = newChildren.length - 1;\n\n let oldStartNode = oldChildren[0];\n let oldEndNode = oldChildren[oldEndIdx];\n let newStartNode = newChildren[0];\n let newEndNode = newChildren[newEndIdx];\n\n // 1. Sync from start - skip common prefix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldStartNode, newStartNode)) {\n patch(parent, oldStartNode, newStartNode);\n newChildren[newStartIdx] = oldStartNode;\n oldStartNode = oldChildren[++oldStartIdx];\n newStartNode = newChildren[++newStartIdx];\n } else {\n break;\n }\n }\n\n // 2. Sync from end - skip common suffix\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (!oldStartNode) {\n oldStartNode = oldChildren[++oldStartIdx];\n } else if (!oldEndNode) {\n oldEndNode = oldChildren[--oldEndIdx];\n } else if (isSameNode(oldEndNode, newEndNode)) {\n patch(parent, oldEndNode, newEndNode);\n newChildren[newEndIdx] = oldEndNode;\n oldEndNode = oldChildren[--oldEndIdx];\n newEndNode = newChildren[--newEndIdx];\n } else {\n break;\n }\n }\n\n // 3. Common sequence + mount new nodes\n if (oldStartIdx > oldEndIdx) {\n if (newStartIdx <= newEndIdx) {\n // Cache anchor calculation\n const anchorNode =\n newEndIdx + 1 < newChildren.length ? getFirstDOMNode(newChildren[newEndIdx + 1]) : anchor;\n\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n insertNode(parent, newChildren[i], anchorNode);\n }\n }\n }\n // 4. Common sequence + unmount old nodes\n else if (newStartIdx > newEndIdx) {\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const node = oldChildren[i];\n if (node) {\n removeNode(node);\n }\n }\n }\n // 5. Unknown sequence - use optimized LIS algorithm\n else {\n patchUnknownSequence(\n parent,\n oldChildren,\n newChildren,\n oldStartIdx,\n oldEndIdx,\n newStartIdx,\n newEndIdx,\n anchor,\n );\n }\n\n return newChildren;\n}\n\n/**\n * Patch unknown sequence with optimized LIS (Longest Increasing Subsequence).\n * Uses Object literal instead of Map for faster string key lookup.\n *\n * ## Algorithm Overview\n *\n * This is the most complex part of the diff algorithm, handling arbitrary\n * reordering of children. It uses the LIS algorithm to minimize DOM moves.\n *\n * ## Algorithm Steps\n *\n * 1. **Build key map**: Create O(1) lookup for new children by key\n * 2. **Map old to new**: For each old child, find its position in new children\n * 3. **Detect moves**: Track if any nodes moved out of order\n * 4. **Calculate LIS**: Find longest increasing subsequence (nodes that don't need to move)\n * 5. **Apply changes**: Mount new nodes, move nodes not in LIS\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n + m + k log k)\n * - Build key map: O(m)\n * - Map old to new: O(n × m) worst case, O(n) with keys\n * - Calculate LIS: O(k log k) where k = number of moved nodes\n * - Apply changes: O(m)\n *\n * - **Space Complexity**: O(m)\n * - Key map: O(m)\n * - Index map: O(m) using Int32Array\n * - LIS result: O(k) where k ≤ m\n *\n * ## Why LIS?\n *\n * The LIS represents nodes that are already in correct relative order.\n * These nodes don't need to move, minimizing expensive DOM operations.\n *\n * ## Example\n *\n * ```\n * Old: [A, B, C, D, E]\n * New: [E, C, A, D, B]\n *\n * Index mapping: [2, 4, 1, 3, 0]\n * LIS: [1, 3] → C and D are in correct order\n * Result: Only move E, A, B; keep C and D in place\n * ```\n *\n * ## Optimization: Object vs Map\n *\n * Using Object.create(null) for key lookup is ~30% faster than Map\n * for string keys, which is the common case.\n *\n * @param parent - Parent DOM node\n * @param oldChildren - Old children array\n * @param newChildren - New children array\n * @param oldStartIdx - Start index in old children\n * @param oldEndIdx - End index in old children\n * @param newStartIdx - Start index in new children\n * @param newEndIdx - End index in new children\n * @param anchor - Optional anchor node\n */\nfunction patchUnknownSequence(\n parent: Node,\n oldChildren: AnyNode[],\n newChildren: AnyNode[],\n oldStartIdx: number,\n oldEndIdx: number,\n newStartIdx: number,\n newEndIdx: number,\n anchor?: Node,\n): void {\n // Cache length calculation\n const newLength = newEndIdx - newStartIdx + 1;\n\n // Use Object literal for faster string key lookup\n let keyToNewIndexMap: Record<string, number> | undefined;\n\n // Build key to index map for new children\n for (let i = newStartIdx; i <= newEndIdx; i++) {\n const key = getNodeKey(newChildren[i]);\n if (key !== undefined) {\n if (!keyToNewIndexMap) {\n keyToNewIndexMap = Object.create(null);\n }\n keyToNewIndexMap![key] = i;\n }\n }\n\n // Use Int32Array for better memory layout and performance\n const newIndexToOldIndexMap = new Int32Array(newLength);\n let moved = false;\n let maxNewIndexSoFar = 0;\n let patched = 0;\n\n // Map old children to new positions\n for (let i = oldStartIdx; i <= oldEndIdx; i++) {\n const oldNode = oldChildren[i];\n if (!oldNode) continue;\n\n // All new nodes have been patched, remove remaining old nodes\n if (patched >= newLength) {\n removeNode(oldNode);\n continue;\n }\n\n let newIndex: number | undefined;\n const oldKey = getNodeKey(oldNode);\n\n // Fast path: keyed lookup using object property access\n if (oldKey !== undefined && keyToNewIndexMap && oldKey in keyToNewIndexMap) {\n newIndex = keyToNewIndexMap[oldKey];\n } else {\n // Fallback: type-based matching for unkeyed nodes\n for (let j = newStartIdx; j <= newEndIdx; j++) {\n if (\n newIndexToOldIndexMap[j - newStartIdx] === 0 &&\n oldKey === undefined &&\n getNodeKey(newChildren[j]) === undefined &&\n isSameNode(oldNode, newChildren[j])\n ) {\n newIndex = j;\n break;\n }\n }\n }\n\n if (newIndex === undefined) {\n // No match found, remove old node\n removeNode(oldNode);\n } else {\n // Record mapping (add 1 to distinguish from 0 which means unmapped)\n newIndexToOldIndexMap[newIndex - newStartIdx] = i + 1;\n\n // Track if nodes have moved (for LIS optimization)\n if (newIndex >= maxNewIndexSoFar) {\n maxNewIndexSoFar = newIndex;\n } else {\n moved = true;\n }\n\n // Patch the matched nodes\n patch(parent, oldNode, newChildren[newIndex]);\n newChildren[newIndex] = oldNode;\n patched++;\n }\n }\n\n // Calculate LIS only if nodes have moved\n const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];\n let j = increasingNewIndexSequence.length - 1;\n\n // Cache anchor nodes to avoid repeated getFirstDOMNode calls\n let cachedAnchor: Node | undefined = anchor;\n\n // Loop backwards to ensure correct anchor calculation\n for (let i = newLength - 1; i >= 0; i--) {\n const nextIndex = newStartIdx + i;\n const nextNode = newChildren[nextIndex];\n\n if (newIndexToOldIndexMap[i] === 0) {\n // New node - insert it\n insertNode(parent, nextNode, cachedAnchor);\n // Update cached anchor for next iteration\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n } else if (moved) {\n // Existing node - move if not in LIS\n if (j < 0 || i !== increasingNewIndexSequence[j]) {\n const domNode = getFirstDOMNode(nextNode);\n if (domNode && domNode.parentNode === parent) {\n insertNode(parent, domNode, cachedAnchor);\n }\n // Update cached anchor\n cachedAnchor = domNode || cachedAnchor;\n } else {\n // Node is in LIS, update anchor but don't move\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n j--;\n }\n } else {\n // No moves, just update anchor\n cachedAnchor = getFirstDOMNode(nextNode) || cachedAnchor;\n }\n }\n}\n\n/**\n * Compute the Longest Increasing Subsequence (LIS).\n * Uses patience sorting with binary search for O(n log n) time complexity.\n *\n * ## Algorithm: Patience Sorting\n *\n * This algorithm is based on the patience sorting card game:\n * 1. Maintain an array of \"piles\" (result array)\n * 2. For each element, find the leftmost pile where it can be placed\n * 3. Use binary search to find the correct pile in O(log n)\n * 4. Track predecessors to reconstruct the sequence\n *\n * ## Algorithm Complexity\n *\n * - **Time Complexity**: O(n log n)\n * - Main loop: O(n) iterations\n * - Binary search per iteration: O(log n)\n * - Sequence reconstruction: O(k) where k = LIS length\n *\n * - **Space Complexity**: O(n)\n * - Result array: O(k) where k ≤ n\n * - Predecessor array: O(n) using Int32Array\n *\n * ## Why This Algorithm?\n *\n * The LIS problem has multiple solutions:\n * - **Brute force**: O(2^n) - try all subsequences\n * - **Dynamic programming**: O(n²) - classic DP solution\n * - **Patience sorting**: O(n log n) - optimal solution\n *\n * We use patience sorting because:\n * 1. Optimal time complexity for large lists\n * 2. Simple to implement and understand\n * 3. Works well with the diff algorithm's needs\n *\n * ## Example\n *\n * ```\n * Input: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]\n * Output: [0, 2, 6, 9, 11, 15] (indices of LIS)\n * LIS: [0, 2, 6, 9, 13, 15] (actual values)\n * ```\n *\n * ## Special Cases\n *\n * - **Empty array**: Returns []\n * - **Single element**: Returns [0] if element !== 0\n * - **All zeros**: Returns [] (zeros mean \"no mapping\" in diff context)\n * - **Strictly decreasing**: Returns [last_non_zero_index]\n *\n * ## Diff Context\n *\n * In the diff algorithm, the input array represents:\n * - Index: Position in new children\n * - Value: Position in old children + 1 (0 means new node)\n *\n * The LIS represents nodes that are already in correct relative order\n * and don't need to be moved.\n *\n * @param arr - Array of indices (0 means no mapping)\n * @returns Array of indices representing the LIS\n */\nexport function getSequence(arr: Int32Array | number[]): number[] {\n const len = arr.length;\n if (len === 0) return [];\n\n // Fast path: single element\n if (len === 1) return arr[0] !== 0 ? [0] : [];\n\n const result: number[] = [];\n const p = new Int32Array(len);\n\n let i: number;\n let j: number;\n let u: number;\n let v: number;\n let c: number;\n\n for (i = 0; i < len; i++) {\n const arrI = arr[i];\n if (arrI !== 0) {\n j = result[result.length - 1];\n\n // Append to result if greater than last element\n if (result.length === 0 || arr[j] < arrI) {\n p[i] = j;\n result.push(i);\n continue;\n }\n\n // Binary search for the correct position\n u = 0;\n v = result.length - 1;\n\n while (u < v) {\n c = (u + v) >> 1;\n if (arr[result[c]] < arrI) {\n u = c + 1;\n } else {\n v = c;\n }\n }\n\n // Update result if smaller value found\n if (arrI < arr[result[u]]) {\n if (u > 0) {\n p[i] = result[u - 1];\n }\n result[u] = i;\n }\n }\n }\n\n // Reconstruct the sequence\n u = result.length;\n v = result[u - 1];\n\n while (u-- > 0) {\n result[u] = v;\n v = p[v];\n }\n\n return result;\n}\n","/** Whether hydration is currently active */\nlet isHydrationActive = false;\n\n/**\n * Start hydration mode\n * Called when beginning client-side hydration of server-rendered content\n */\nexport function startHydration(): void {\n isHydrationActive = true;\n}\n\n/**\n * End hydration mode\n * Called when hydration is complete\n */\nexport function endHydration(): void {\n isHydrationActive = false;\n}\n\n/**\n * Check if hydration is currently active\n * @returns true if hydration is in progress\n */\nexport function isHydrating(): boolean {\n return isHydrationActive;\n}\n","import {\n coerceArray,\n isFunction,\n isHtmlInputElement,\n isHtmlSelectElement,\n isHtmlTextAreaElement,\n} from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { normalizeNode } from './utils/node';\nimport { removeNode } from './utils/dom';\nimport { patchChildren } from './patch';\nimport { type Scope, getActiveScope, onCleanup, runWithScope } from './scope';\nimport { isHydrating } from './utils/shared';\nimport type { AnyNode } from './types';\n\n/**\n * Add event listener with automatic cleanup on scope destruction\n *\n * @param element - Element to attach listener to\n * @param event - Event name\n * @param handler - Event handler function\n * @param options - Event listener options\n */\nexport function addEventListener(\n element: Element,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n): void {\n element.addEventListener(event, handler, options);\n\n onCleanup(() => {\n element.removeEventListener(event, handler, options);\n });\n}\n\n/**\n * Bind an element to a setter function for two-way data binding\n *\n * @param node - The element to bind\n * @param key - The property key (unused, kept for API compatibility)\n * @param defaultValue - Default value (unused, kept for API compatibility)\n * @param setter - The setter function to call when the element's value changes\n */\nexport function bindElement(\n node: Element,\n key: string,\n defaultValue: unknown,\n setter: (value: unknown) => void,\n): void {\n if (isHtmlInputElement(node)) {\n bindInputElement(node, setter);\n } else if (isHtmlSelectElement(node)) {\n bindSelectElement(node, setter);\n } else if (isHtmlTextAreaElement(node)) {\n addEventListener(node, 'input', () => {\n setter((node as HTMLTextAreaElement).value);\n });\n }\n}\n\n/**\n * Bind input element based on its type\n */\nfunction bindInputElement(node: HTMLInputElement, setter: (value: unknown) => void): void {\n switch (node.type) {\n case 'checkbox':\n addEventListener(node, 'change', () => {\n setter(Boolean(node.checked));\n });\n break;\n\n case 'radio':\n addEventListener(node, 'change', () => {\n setter(node.checked ? node.value : '');\n });\n break;\n\n case 'file':\n addEventListener(node, 'change', () => {\n setter(node.files);\n });\n break;\n\n case 'number':\n case 'range':\n addEventListener(node, 'input', () => {\n setter(node.value || '');\n });\n break;\n\n case 'date':\n case 'datetime-local':\n case 'month':\n case 'time':\n case 'week':\n addEventListener(node, 'change', () => {\n setter(node.value || '');\n });\n break;\n\n default:\n // text, email, password, search, tel, url, etc.\n addEventListener(node, 'input', () => {\n setter(node.value);\n });\n break;\n }\n}\n\n/**\n * Bind select element\n */\nfunction bindSelectElement(node: HTMLSelectElement, setter: (value: unknown) => void): void {\n addEventListener(node, 'change', () => {\n if (node.multiple) {\n const values = Array.from(node.options)\n .filter(option => option.selected)\n .map(option => option.value);\n setter(values);\n } else {\n setter(node.value);\n }\n });\n}\n\nlet isFirstRun = true;\n/**\n * Execute reactive update within the appropriate scope\n */\nfunction executeReactiveUpdate(\n ownerScope: Scope | null,\n parent: Node,\n nodeFactory: AnyNode,\n before: Node | undefined,\n renderedNodes: AnyNode[],\n): AnyNode[] {\n const executeUpdate = () => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = coerceArray(rawNodes as unknown)\n .map(item => (isFunction(item) ? item() : item))\n .flatMap(i => i)\n .map(normalizeNode) as AnyNode[];\n\n // Hydration mode: skip DOM operations on first run\n // but still execute nodeFactory() to collect dependencies\n if (isFirstRun && isHydrating()) {\n isFirstRun = false;\n return renderedNodes;\n }\n\n return patchChildren(parent, renderedNodes, nodes, before) as AnyNode[];\n };\n\n // If we have an owner scope, run within it to maintain context hierarchy\n if (ownerScope && !ownerScope.isDestroyed) {\n return runWithScope(ownerScope, executeUpdate);\n }\n return executeUpdate();\n}\n\n/**\n * Reactive node insertion with binding support\n *\n * @param parent - Parent node\n * @param nodeFactory - Node factory function or static node\n * @param before - Reference node for insertion position\n * @returns Array of rendered nodes\n *\n * @example\n * ```typescript\n * insert(container, () => message.value, null);\n * insert(container, staticElement, referenceNode);\n * insert(container, \"Hello World\", null);\n * ```\n */\nexport function insert(parent: Node, nodeFactory: AnyNode, before?: Node): AnyNode[] | undefined {\n if (!parent) return;\n\n // Capture owner scope at call time - critical for correct context inheritance\n const ownerScope: Scope | null = getActiveScope();\n\n let renderedNodes: AnyNode[] = [];\n\n // Create effect for reactive updates\n const cleanup = effect(() => {\n renderedNodes = executeReactiveUpdate(ownerScope, parent, nodeFactory, before, renderedNodes);\n });\n\n onCleanup(() => {\n cleanup();\n renderedNodes.forEach(node => removeNode(node));\n renderedNodes.length = 0;\n });\n\n return renderedNodes;\n}\n\n/**\n * Map nodes from template by indexes\n *\n * @param template - Template node to traverse\n * @param indexes - Array of indexes to map\n * @returns Array of mapped nodes\n */\nexport function mapNodes(template: Node, indexes: number[]): Node[] {\n const len = indexes.length;\n const tree = new Array<Node>(len);\n const indexSet = new Set(indexes);\n\n let index = 1;\n let found = 0;\n\n const walk = (node: Node): boolean => {\n if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {\n if (indexSet.has(index)) {\n tree[found++] = node;\n if (found === len) return true;\n }\n index++;\n }\n\n let child = node.firstChild;\n while (child) {\n if (walk(child)) return true;\n child = child.nextSibling;\n }\n\n return false;\n };\n\n walk(template);\n return tree;\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope, runWithScope } from './scope';\n\nexport type LifecycleHook = () => void | Promise<void>;\n\nexport const LIFECYCLE = {\n mount: 'mount',\n destroy: 'destroy',\n update: 'update',\n} as const;\n\nexport type LifecycleType = (typeof LIFECYCLE)[keyof typeof LIFECYCLE];\n\nexport type LifecycleHooks = {\n [key in LifecycleType]: Set<LifecycleHook>;\n};\n\n/**\n * Create a new lifecycle context (deprecated)\n * @deprecated Lifecycle hooks are now managed by Scope\n * @returns A new lifecycle hooks object\n */\nexport function createLifecycleContext(): LifecycleHooks {\n return {\n mount: new Set<LifecycleHook>(),\n destroy: new Set<LifecycleHook>(),\n update: new Set<LifecycleHook>(),\n };\n}\n\n/**\n * Register a lifecycle hook\n * @param type - The type of lifecycle hook to register\n * @param hook - The hook function to register\n */\nexport function registerLifecycleHook(type: LifecycleType, hook: LifecycleHook): void {\n switch (type) {\n case LIFECYCLE.mount:\n registerMountHook(hook);\n break;\n case LIFECYCLE.update:\n registerUpdateHook(hook);\n break;\n case LIFECYCLE.destroy:\n registerDestroyHook(hook);\n break;\n default:\n if (__DEV__) {\n error(`Invalid lifecycle type: ${type}`);\n }\n }\n}\n\n/**\n * Register a mount lifecycle hook.\n * If the scope is already mounted, the hook is executed immediately.\n *\n * @param hook - The mount hook function\n */\nexport function registerMountHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onMount() must be called within a scope');\n }\n return;\n }\n\n // If already mounted, execute immediately\n if (scope.isMounted) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in mount hook:`, error_);\n }\n }\n return;\n }\n\n // Lazy initialize mount hooks set\n if (!scope.onMount) {\n scope.onMount = new Set();\n }\n\n scope.onMount.add(hook);\n}\n\n/**\n * Register an update lifecycle hook.\n *\n * @param hook - The update hook function\n */\nexport function registerUpdateHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onUpdate() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize update hooks set\n if (!scope.onUpdate) {\n scope.onUpdate = new Set();\n }\n\n scope.onUpdate.add(hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n *\n * @param hook - The destroy hook function\n */\nexport function registerDestroyHook(hook: () => void | Promise<void>): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('onDestroy() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize destroy hooks set\n if (!scope.onDestroy) {\n scope.onDestroy = new Set();\n }\n\n scope.onDestroy.add(hook);\n}\n\n/**\n * Trigger mount lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger mount hooks for\n */\nexport function triggerMountHooks(scope: Scope): void {\n if (!scope || scope.isDestroyed || scope.isMounted) {\n return;\n }\n\n scope.isMounted = true;\n\n if (scope.onMount) {\n runWithScope(scope, () => {\n for (const hook of scope.onMount!) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in mount hook:`, error_);\n }\n }\n }\n });\n }\n}\n\n/**\n * Trigger update lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger update hooks for\n */\nexport function triggerUpdateHooks(scope: Scope): void {\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n if (scope.onUpdate) {\n for (const hook of scope.onUpdate) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in update hook:`, error_);\n }\n }\n }\n }\n}\n\n/**\n * Trigger lifecycle hooks of a specific type for the active scope.\n * @param type - The type of lifecycle hooks to trigger\n */\nexport function triggerLifecycleHook(type: LifecycleType): void | Promise<void> {\n const scope = getActiveScope();\n if (!scope) {\n if (__DEV__) {\n error(`triggerLifecycleHook(${type}) called outside of a scope`);\n }\n return;\n }\n\n switch (type) {\n case LIFECYCLE.mount:\n return triggerMountHooks(scope);\n case LIFECYCLE.update:\n return triggerUpdateHooks(scope);\n case LIFECYCLE.destroy:\n if (scope.onDestroy) {\n for (const hook of scope.onDestroy) {\n try {\n hook();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in destroy hook:`, error_);\n }\n }\n }\n }\n break;\n }\n}\n/**\n * Register a mount lifecycle hook.\n * Called after the component is mounted to the DOM.\n *\n * @param hook - The hook function to execute on mount\n */\nexport function onMount(hook: LifecycleHook): void {\n registerMountHook(hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n * Called before the component is removed from the DOM.\n *\n * @param hook - The hook function to execute on destroy\n */\nexport function onDestroy(hook: LifecycleHook): void {\n registerDestroyHook(hook);\n}\n\n/**\n * Register an update lifecycle hook.\n * Called after the component updates.\n *\n * @param hook - The hook function to execute on update\n */\nexport function onUpdate(hook: LifecycleHook): void {\n registerUpdateHook(hook);\n}\n\n/**\n * Cleanup lifecycle hooks for a context (deprecated)\n * @deprecated Use disposeScope instead\n * @param context - The context to cleanup\n */\nexport function cleanupLifecycle(context?: Scope): void {\n const scope = context || getActiveScope();\n if (!scope) {\n return;\n }\n\n // Clear all lifecycle hooks\n scope.onMount?.clear();\n scope.onDestroy?.clear();\n scope.onUpdate?.clear();\n}\n","import { isComputed, isSignal, shallowReactive } from '@estjs/signals';\nimport { coerceArray, isFunction, isHTMLElement, isObject, startsWith } from '@estjs/shared';\nimport { type Scope, createScope, disposeScope, getActiveScope, runWithScope } from './scope';\nimport { COMPONENT_STATE, COMPONENT_TYPE, EVENT_PREFIX, REF_KEY } from './constants';\nimport { addEventListener, insert } from './binding';\nimport { getComponentKey, normalizeKey } from './key';\nimport { getFirstDOMNode, insertNode, removeNode } from './utils/dom';\nimport { shallowCompare } from './utils/node';\nimport { triggerMountHooks, triggerUpdateHooks } from './lifecycle';\nimport type { AnyNode, ComponentFn, ComponentProps } from './types';\n\nexport class Component<P extends ComponentProps = ComponentProps> {\n // component rendered nodes (supports arrays and fragments)\n protected renderedNodes: AnyNode[] = [];\n\n // component scope (unified context management)\n protected scope: Scope | null = null;\n\n // component parent node\n protected parentNode: Node | undefined = undefined;\n\n // component before node\n public beforeNode: Node | undefined = undefined;\n\n // component reactive props\n private reactiveProps: P = {} as P;\n\n // component key\n public readonly key: string | undefined;\n // component state\n protected state: number = COMPONENT_STATE.INITIAL;\n\n // parent scope captured at construction time\n protected parentScope: Scope | null = null;\n\n // component type\n // @ts-ignore\n private [COMPONENT_TYPE.NORMAL] = true;\n\n get isConnected(): boolean {\n return this.state === COMPONENT_STATE.MOUNTED;\n }\n\n get firstChild(): Node | undefined {\n // Get the first meaningful DOM node from rendered nodes\n // Skip empty text nodes (anchors or null renders)\n for (const node of this.renderedNodes) {\n const dom = getFirstDOMNode(node);\n if (dom) {\n return dom;\n }\n }\n return undefined;\n }\n\n constructor(\n public component: ComponentFn<P>,\n public props: P = {} as P,\n ) {\n this.key = props.key ? normalizeKey(props.key) : getComponentKey(component);\n\n this.reactiveProps = shallowReactive({ ...(props || {}) }) as P;\n\n // Capture parent scope at construction time for correct hierarchy\n this.parentScope = getActiveScope();\n }\n\n mount(parentNode: Node, beforeNode?: Node): AnyNode[] {\n this.parentNode = parentNode;\n this.beforeNode = beforeNode;\n this.state = COMPONENT_STATE.MOUNTING;\n\n // if the component already has rendered nodes, re-insert them\n if (this.renderedNodes.length > 0) {\n for (const node of this.renderedNodes) {\n insertNode(parentNode, node, beforeNode);\n }\n this.state = COMPONENT_STATE.MOUNTED;\n return this.renderedNodes;\n }\n\n // Create scope with correct parent (captured at construction or current active)\n const parent = this.parentScope ?? getActiveScope();\n this.scope = createScope(parent);\n\n // Run component within its scope\n const renderedNodes = runWithScope(this.scope, () => {\n // render the component\n let result = this.component(this.reactiveProps);\n\n // unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // unwrap signals and computed values\n if (isSignal<Element>(result) || isComputed<Element>(result)) {\n result = result.value;\n }\n\n const nodes = insert(parentNode, result as any, beforeNode) ?? [];\n\n return nodes;\n });\n\n this.renderedNodes = renderedNodes;\n\n // apply props (events, refs) - must be after renderedNodes is set\n // so that this.firstChild returns the correct element\n runWithScope(this.scope, () => {\n this.applyProps(this.props || ({} as P));\n });\n\n // update marks\n this.state = COMPONENT_STATE.MOUNTED;\n\n // Trigger scope mount hooks (unified lifecycle system)\n if (this.scope) {\n triggerMountHooks(this.scope);\n }\n\n return this.renderedNodes;\n }\n\n update(prevNode: Component<any>): Component<P> {\n // if key is different, mount the component\n if (this.key !== prevNode.key) {\n this.mount(prevNode.parentNode!, prevNode.beforeNode);\n return this;\n }\n\n // Take previous node's properties and reactive state\n this.parentNode = prevNode.parentNode;\n this.beforeNode = prevNode.beforeNode;\n this.scope = prevNode.scope; // Reuse existing scope\n this.parentScope = prevNode.parentScope;\n this.renderedNodes = prevNode.renderedNodes;\n this.state = prevNode.state;\n this.reactiveProps = prevNode.reactiveProps as P; // Reuse same reactive object\n\n // Early return if no new props to update\n if (!this.props || Object.keys(this.props).length === 0) {\n // still need to check mounting status\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n return this;\n }\n\n // Apply props and trigger update if mounted\n if (this.scope) {\n runWithScope(this.scope, () => {\n this.applyProps(this.props || ({} as P));\n });\n triggerUpdateHooks(this.scope);\n }\n return this;\n }\n\n // Track if any props actually changed\n let hasChanges = false;\n\n for (const key in this.props) {\n if (key === 'key') continue;\n\n const newValue = this.props[key];\n const oldValue = this.reactiveProps[key];\n\n // 1. reference same\n if (Object.is(oldValue, newValue)) {\n continue;\n }\n // 2. object shallow compare\n if (isObject(oldValue) && isObject(newValue)) {\n if (shallowCompare(oldValue, newValue)) {\n continue;\n }\n }\n\n // 3. update reactiveProps\n this.reactiveProps[key] = newValue;\n hasChanges = true;\n }\n\n // check if the component is already mount\n if (!this.isConnected && this.parentNode) {\n this.mount(this.parentNode, this.beforeNode);\n }\n\n // if the component is mount and has scope, apply new props and trigger update lifecycle\n // Only trigger update hooks if props actually changed\n if (this.scope && (hasChanges || !this.isConnected)) {\n runWithScope(this.scope, () => {\n this.applyProps(this.props || ({} as P));\n });\n // Trigger scope update hooks only if there were changes\n if (hasChanges) {\n triggerUpdateHooks(this.scope);\n }\n }\n\n return this;\n }\n\n async forceUpdate(): Promise<void> {\n await Promise.resolve();\n if (this.state === COMPONENT_STATE.DESTROYED || !this.parentNode || !this.scope) {\n return;\n }\n\n const originalNodes = [...this.renderedNodes];\n\n try {\n runWithScope(this.scope, () => {\n // Re-render the component\n let result = (this.component as Function)(this.reactiveProps);\n\n // Unwrap function (render function pattern)\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signals and computed values\n if (isSignal<AnyNode>(result) || isComputed<AnyNode>(result)) {\n result = result.value;\n }\n\n // Normalize to array\n const newNodes = coerceArray(result) as AnyNode[];\n\n // Replace old nodes with new ones (complete re-render)\n if (this.parentNode) {\n let anchor: Node | undefined = this.beforeNode;\n if (!anchor && this.renderedNodes.length > 0) {\n const lastNode = this.renderedNodes[this.renderedNodes.length - 1];\n const lastDom = getFirstDOMNode(lastNode);\n if (lastDom) {\n anchor = lastDom.nextSibling as Node | undefined;\n }\n }\n\n // Remove old rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Insert new nodes before anchor\n for (const node of newNodes) {\n insertNode(this.parentNode, node, anchor);\n }\n\n this.renderedNodes = newNodes;\n }\n });\n\n if (this.scope) {\n triggerUpdateHooks(this.scope);\n }\n } catch (error) {\n // Rollback\n this.renderedNodes = originalNodes;\n throw error;\n }\n }\n\n /**\n * Destroy component\n */\n destroy(): void {\n // Prevent duplicate destruction\n if (this.state === COMPONENT_STATE.DESTROYING || this.state === COMPONENT_STATE.DESTROYED) {\n return;\n }\n\n this.state = COMPONENT_STATE.DESTROYING;\n\n const scope = this.scope;\n if (scope) {\n // Dispose scope (handles cleanup, destroy hooks, and children)\n // The disposeScope function triggers destroy hooks internally\n disposeScope(scope);\n this.scope = null;\n }\n\n // Remove all rendered nodes\n for (const node of this.renderedNodes) {\n removeNode(node);\n }\n\n // Reset all component properties\n this.renderedNodes = [];\n this.parentNode = undefined;\n this.beforeNode = undefined;\n this.parentScope = null;\n this.reactiveProps = {} as P;\n this.props = {} as P;\n this.state = COMPONENT_STATE.DESTROYED;\n }\n\n applyProps(props: P): void {\n // check if props is defined\n if (!props) {\n return;\n }\n\n // Get first element for event handling and refs\n const firstElement = this.firstChild;\n\n // iterate over all properties and apply them\n for (const [propName, propValue] of Object.entries(props)) {\n if (startsWith(propName, EVENT_PREFIX) && firstElement) {\n // event handling: extract the event name after on\n const eventName = propName.slice(2).toLowerCase();\n\n if (isHTMLElement(firstElement)) {\n addEventListener(firstElement, eventName, propValue as EventListener);\n }\n } else if (propName === REF_KEY && isSignal(propValue)) {\n // handle reference: store the DOM reference into the signal value\n propValue.value = firstElement;\n }\n }\n\n // save props reference\n this.props = props;\n }\n}\n\n/**\n * check if a node is a component\n * @param {unknown} node - the node to check\n * @returns {boolean} true if the node is a component, false otherwise\n */\nexport function isComponent(node: unknown): node is Component {\n return !!node && !!node[COMPONENT_TYPE.NORMAL];\n}\n\n/**\n * create a component\n * @param {Function} componentFn - the component function\n * @param {ComponentProps} props - the component props\n * @returns {Component} the component\n */\nexport function createComponent<P extends ComponentProps>(\n componentFn: ComponentFn<P>,\n props?: P,\n): Component<P> {\n if (isComponent(componentFn)) {\n return componentFn as unknown as Component<P>;\n }\n return new Component(componentFn, props);\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope } from './scope';\n\n/**\n * InjectionKey is a unique identifier for provided values.\n * Using Symbol ensures type safety and prevents key collisions.\n */\n// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types, unused-imports/no-unused-vars\nexport interface InjectionKey<T> extends Symbol {}\n\n/**\n * Provide a value in the current scope.\n * The value can be injected by this scope or any descendant scope.\n *\n * @param key - The injection key\n * @param value - The value to provide\n */\nexport function provide<T>(key: InjectionKey<T> | string | number, value: T): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('provide() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize provides map\n if (!scope.provides) {\n scope.provides = new Map();\n }\n\n scope.provides.set(key, value);\n}\n\n/**\n * Inject a value from the scope hierarchy.\n * Traverses up the parent chain until finding a matching key.\n *\n * @param key - The injection key\n * @param defaultValue - Default value if key is not found\n * @returns The injected value or default value\n */\nexport function inject<T>(key: InjectionKey<T> | string | number, defaultValue?: T): T {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('inject() must be called within a scope');\n }\n return defaultValue as T;\n }\n\n // Traverse up the hierarchy\n let current: Scope | null = scope;\n while (current) {\n if (current.provides) {\n const value = current.provides.get(key);\n if (value) {\n return value as T;\n }\n }\n current = current.parent;\n }\n\n return defaultValue as T;\n}\n","import { isFunction, isString } from '@estjs/shared';\n\n/**\n * Event handler for delegated events\n * @param {Event} e - The event object\n */\nfunction eventHandler(e: Event): void {\n let node = e.target as any;\n const key = `${e.type}`;\n const oriTarget = e.target;\n const oriCurrentTarget = e.currentTarget;\n\n /**\n * Retarget the event's target property\n * @param {EventTarget} value - New target value\n */\n const reTarget = (value: EventTarget) =>\n Object.defineProperty(e, 'target', {\n configurable: true,\n value,\n });\n\n /**\n * Handle event on current node\n * @returns {boolean} Whether to continue propagation\n */\n const handleNode = (): boolean => {\n const handler = node[`_$${key}`];\n if (handler && isFunction(handler) && !node.disabled) {\n const data = node[`${key}Data`];\n data ? handler.call(node, data, e) : handler.call(node, e);\n if (e.cancelBubble) return false;\n }\n\n // Handle host element retargeting\n if (\n node.host &&\n !isString(node.host) &&\n !node.host._$host &&\n isFunction(node.contains) &&\n node.contains(e.target)\n ) {\n reTarget(node.host);\n }\n return true;\n };\n\n /**\n * Walk up the DOM tree handling events\n */\n const walkUpTree = (): void => {\n while (handleNode() && (node = node._$host || node.parentNode || node.host));\n };\n\n // simulate currentTarget\n Object.defineProperty(e, 'currentTarget', {\n configurable: true,\n get() {\n return node || document;\n },\n });\n\n if (e.composedPath) {\n const path = e.composedPath();\n reTarget(path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i] as any;\n if (!handleNode()) break;\n if (node._$host) {\n node = node._$host;\n // bubble up from portal mount instead of composedPath\n walkUpTree();\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // don't bubble above root of event delegation\n }\n }\n }\n // fallback for browsers that don't support composedPath\n else walkUpTree();\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here.\n reTarget(oriTarget!);\n}\n\n/**\n * Symbol for storing delegated events on document\n */\nconst $EVENTS = Symbol('_$EVENTS');\n\n/**\n * Set up event delegation for specified event types\n * @param {string[]} eventNames - Array of event names to delegate\n * @param {Document} document - Document to attach events to (defaults to window.document)\n */\nexport function delegateEvents(eventNames: string[], document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS] || (docWithEvents[$EVENTS] = new Set<string>());\n\n for (const name of eventNames) {\n if (!eventSet.has(name)) {\n eventSet.add(name);\n document.addEventListener(name, eventHandler);\n }\n }\n}\n\n/**\n * Clear all delegated events from document\n * @param {Document} document - Document to clear events from (defaults to window.document)\n */\nexport function clearDelegatedEvents(document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS];\n if (eventSet) {\n for (const name of eventSet.keys()) {\n document.removeEventListener(name, eventHandler);\n }\n delete docWithEvents[$EVENTS];\n }\n}\n","/**\n * Create a reactive proxy that excludes specified properties\n *\n * @param target - The original reactive object\n * @param keys - List of property names to exclude\n * @returns A reactive proxy with specified properties excluded\n */\nexport function omitProps<T extends object, K extends keyof T>(target: T, keys: K[]): Omit<T, K> {\n const excludeSet = new Set(keys);\n\n return new Proxy(target, {\n // Intercept property reads\n get(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.get(obj, prop);\n },\n\n // Intercept property enumeration (for...in, Object.keys, etc.)\n ownKeys(obj) {\n return Reflect.ownKeys(obj).filter(key => !excludeSet.has(key as K));\n },\n\n // Intercept property descriptor retrieval\n getOwnPropertyDescriptor(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n\n // Intercept the 'in' operator\n has(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return false;\n }\n return Reflect.has(obj, prop);\n },\n });\n}\n","import { normalizeClassName } from '@estjs/shared';\nimport { isHydrating } from '../utils/shared';\n\n/**\n * Type definition for class values\n * @public\n */\nexport type ClassValue = string | Record<string, boolean> | ClassValue[] | null | undefined;\n\n/**\n * Patches the class attribute of an element\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch classes on\n * @param prev - Previous class value for diffing\n * @param next - New class value to apply\n * @param isSVG - Whether the element is an SVG element\n * @public\n */\nexport function patchClass(\n el: Element,\n prev: unknown,\n next: unknown,\n isSVG: boolean = false,\n): void {\n if (prev === next) {\n return;\n }\n if (isHydrating()) {\n return;\n }\n const normalizedNext = normalizeClass(next);\n const normalizedPrev = normalizeClass(prev);\n // Skip DOM update if classes haven't changed\n if (normalizedNext && normalizedPrev === normalizedNext) {\n return;\n }\n\n // Apply classes based on element type\n if (!normalizedNext) {\n el.removeAttribute('class');\n } else if (isSVG) {\n el.setAttribute('class', normalizedNext);\n } else {\n el.className = normalizedNext;\n }\n}\n\n/**\n * Normalizes different class value formats into a single string\n * Re-exports normalizeClassName from shared as normalizeClass for backward compatibility\n *\n * @param value - The class value to normalize\n * @returns A normalized class string\n * @public\n */\nexport function normalizeClass(value: unknown): string {\n return normalizeClassName(value);\n}\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/shared';\nimport { isHydrating } from '../utils/shared';\n\n/**\n * Symbol for storing CSS variable text in style objects\n * @internal\n */\nexport const CSS_VAR_TEXT: unique symbol = Symbol('CSS_VAR_TEXT');\n\n// Cache regex patterns for better performance\nconst importantRE = /\\s*!important$/;\n\n// Cache browser prefixes for better performance\nconst prefixes = ['Webkit', 'Moz', 'ms'];\nconst prefixCache: Record<string, string> = {};\n\n/**\n * Type definition for style values\n * @public\n */\nexport type Style = string | Record<string, string | string[]> | null | undefined;\n\n/**\n * Patches the style of an element, optimized for different style formats\n * Supports silent hydration (skips DOM updates during hydration phase)\n *\n * @param el - The element to patch styles on\n * @public\n */\nexport function patchStyle(el: HTMLElement, prev: unknown, next: unknown) {\n const style = el.style;\n const isCssString = isString(next);\n if (isHydrating()) {\n return;\n }\n if (next && isCssString) {\n if (prev !== next) {\n style.cssText = next;\n }\n return;\n }\n\n if (!next) {\n if (prev) {\n el.removeAttribute('style');\n }\n return;\n }\n\n // Handle object-based styles\n if (prev && !isString(prev)) {\n // Remove styles that are no longer present\n for (const key in prev) {\n if (!next || next[key as keyof typeof next] == null) {\n setStyle(style, key, '');\n }\n }\n } else if (prev && isString(prev)) {\n // Handle previous string-based styles\n const prevStyles = prev.split(';');\n for (const stylePart of prevStyles) {\n const colonIndex = stylePart.indexOf(':');\n if (colonIndex > 0) {\n const key = stylePart.slice(0, colonIndex).trim();\n if (next && isObject(next) && next[key] == null) {\n setStyle(style, key, '');\n }\n }\n }\n }\n\n // Set new styles\n if (next && !isString(next)) {\n for (const key in next) {\n const value = next[key];\n if ((!prev || isString(prev) || prev[key] !== value) && value != null) {\n setStyle(style, key, value);\n }\n }\n }\n}\n\n/**\n * Sets an individual style property with various optimizations\n *\n * @param style - The style object to modify\n * @param name - The style property name\n * @param val - The style property value\n * @private\n */\nexport function setStyle(style: CSSStyleDeclaration, name: string, val: string | string[]): void {\n // Handle array values (vendor prefixed values)\n if (isArray(val)) {\n for (const element of val) {\n setStyle(style, name, element);\n }\n return;\n }\n\n if (val == null || val === '') {\n val = '';\n }\n\n // Handle CSS custom properties\n if (name.startsWith('--')) {\n style.setProperty(name, val);\n return;\n }\n\n // Handle regular CSS properties with potential prefixing\n const prefixed = autoPrefix(style, name);\n\n // Handle !important\n if (typeof val === 'string' && importantRE.test(val)) {\n style.setProperty(camelCase(prefixed), val.replace(importantRE, ''), 'important');\n } else {\n style[prefixed] = val;\n }\n}\n\n/**\n * Adds vendor prefixes to style properties as needed\n *\n * @param style - The style object to check against\n * @param rawName - The raw property name\n * @returns The prefixed property name if needed\n * @private\n */\nfunction autoPrefix(style: CSSStyleDeclaration, rawName: string): string {\n // Check cache first\n const cached = prefixCache[rawName];\n if (cached) {\n return cached;\n }\n\n // Try camelCase version directly\n let name = camelCase(rawName);\n if (name !== 'filter' && name in style) {\n return (prefixCache[rawName] = name);\n }\n\n // Try with vendor prefixes\n name = capitalize(name);\n for (const prefix of prefixes) {\n const prefixed = prefix + name;\n if (prefixed in style) {\n return (prefixCache[rawName] = prefixed);\n }\n }\n\n return rawName;\n}\n","import {\n includeBooleanAttr,\n isBooleanAttr,\n isObject,\n isSpecialBooleanAttr,\n isSymbol,\n warn,\n} from '@estjs/shared';\nimport {\n KEY_PROP,\n SPREAD_NAME,\n SVG_NAMESPACE,\n XLINK_NAMESPACE,\n XMLNS_NAMESPACE,\n} from '../constants';\nimport { setNodeKey } from '../key';\nimport { isHydrating } from '../utils/shared';\n\nexport type AttrValue = string | boolean | number | null | undefined | Record<string, unknown>;\n\nexport function patchAttr(el: Element, key: string, prev: AttrValue, next: AttrValue) {\n if (key === KEY_PROP) {\n if (next == null) {\n setNodeKey(el, undefined);\n } else {\n setNodeKey(el, String(next));\n }\n return;\n }\n if (key === SPREAD_NAME) {\n if (__DEV__) {\n if (!isObject(next)) {\n warn('spread attribute must be an object');\n }\n }\n Object.keys(next as Record<string, unknown>).forEach(k => {\n patchAttr(el, k, prev?.[k], next?.[k]);\n });\n return;\n }\n\n if (isHydrating()) {\n return;\n }\n const elementIsSVG = el?.namespaceURI === SVG_NAMESPACE;\n const isXlink = elementIsSVG && key.startsWith('xlink:');\n const isXmlns = elementIsSVG && key.startsWith('xmlns:');\n\n const isBoolean = isSpecialBooleanAttr(key) || isBooleanAttr(key);\n\n // Early return if values are the same\n if (prev === next) {\n return;\n }\n\n // Compute lowerKey only when needed (after early exits)\n const lowerKey = key.toLowerCase();\n\n // Cache event handler check (faster than regex for common case)\n if (lowerKey.length > 2 && lowerKey.charCodeAt(0) === 111 && lowerKey.charCodeAt(1) === 110) {\n // 'on'\n return;\n }\n\n if (lowerKey === 'innerhtml') {\n return;\n }\n\n if (next == null) {\n if (isXlink) {\n el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));\n } else if (isXmlns) {\n const localName = key.slice(6);\n el.removeAttributeNS(XMLNS_NAMESPACE, localName);\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n if (isXlink) {\n el.setAttributeNS(XLINK_NAMESPACE, key, String(next));\n return;\n }\n\n if (isXmlns) {\n el.setAttributeNS(XMLNS_NAMESPACE, key, String(next));\n return;\n }\n\n if (isBoolean) {\n if (includeBooleanAttr(next)) {\n el.setAttribute(key, '');\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n const attrValue = isSymbol(next) ? String(next) : next;\n\n const isUrlAttr = lowerKey === 'href' || lowerKey === 'src' || lowerKey === 'xlink:href';\n if (isUrlAttr && typeof attrValue === 'string') {\n const v = attrValue.trim().toLowerCase();\n if (v.startsWith('javascript:') || v.startsWith('data:')) {\n return;\n }\n }\n\n if (elementIsSVG) {\n el.setAttribute(key, String(attrValue));\n } else {\n if (key in el) {\n try {\n (el as any)[key] = attrValue;\n } catch {\n el.setAttribute(key, String(attrValue));\n }\n } else {\n el.setAttribute(key, String(attrValue));\n }\n }\n}\n","/**\n * Extended event options with delegation support\n * @public\n */\nexport interface EventOptions extends AddEventListenerOptions {\n /**\n * CSS selector for event delegation\n * When provided, the event will only trigger if the target matches this selector\n */\n delegate?: string;\n}\n\n/**\n * Event handler cleanup function\n * @public\n */\nexport type EventCleanup = () => void;\n\n/**\n * Adds an event listener to an element with optional delegation\n *\n * @param el - The element to attach the event to\n * @param event - The event name (e.g., 'click', 'input')\n * @param handler - The event handler function\n * @param options - Additional event options including delegation\n * @returns A cleanup function to remove the event listener\n * @public\n */\nexport function addEvent(\n el: Element,\n event: string,\n handler: EventListener,\n options?: EventOptions,\n): EventCleanup {\n if (!options?.delegate) {\n el.addEventListener(event, handler, options);\n return () => el.removeEventListener(event, handler, options);\n }\n\n // Delegation path: use simple wrapper\n const selector = options.delegate;\n const wrappedHandler = (e: Event) => {\n const target = e.target as Element;\n if (target.matches(selector) || target.closest(selector)) {\n handler.call(el, e);\n }\n };\n\n // Clean options object by removing delegate property\n const cleanOptions = { ...options };\n cleanOptions.delegate = undefined;\n\n // Add the event listener with the wrapped handler\n el.addEventListener(event, wrappedHandler, cleanOptions);\n\n // Return cleanup function\n return () => {\n el.removeEventListener(event, wrappedHandler, cleanOptions);\n };\n}\n","import { error } from '@estjs/shared';\nimport { COMPONENT_TYPE } from '../constants';\nimport type { AnyNode, ComponentProps } from '../types';\n\nexport interface FragmentProps extends ComponentProps {\n children?: AnyNode | AnyNode[];\n}\n\n/**\n * Fragment component - renders multiple children without wrapper elements\n *\n * @param props - Component props with children\n * @returns DocumentFragment containing all children\n *\n * @example\n * ```tsx\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\n * </Fragment>\n * ```\n */\nexport function Fragment(props?: FragmentProps): AnyNode {\n if (__DEV__) {\n if (!props) {\n error('Fragment component requires props');\n return null;\n }\n if (!props.children) {\n error('Fragment component requires children');\n return null;\n }\n }\n\n return props?.children as Element;\n}\n\nFragment[COMPONENT_TYPE.FRAGMENT] = true;\n\n/**\n * Check if a node is a Fragment component\n * @param node - Node to check\n * @returns true if node is a Fragment\n */\nexport function isFragment(node: unknown): boolean {\n return !!node && !!(node as any)[COMPONENT_TYPE.FRAGMENT];\n}\n","import { isArray, isString, warn } from '@estjs/shared';\nimport { insertNode } from '../utils/dom';\nimport { normalizeNode } from '../utils/node';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onMount } from '../lifecycle';\nimport { onCleanup } from '../scope';\nimport type { AnyNode } from '../types';\n\nexport interface PortalProps {\n children?: AnyNode | AnyNode[];\n target: string | HTMLElement;\n key?: string;\n}\n\n/**\n * Portal component - renders children into a different DOM node\n *\n * @param props - Component props with children and target\n * @returns Comment node as placeholder in parent tree\n *\n * @example\n * ```tsx\n * <Portal target=\"#modal-root\">\n * <div>Modal content</div>\n * </Portal>\n * ```\n */\nexport function Portal(props: PortalProps): Comment | string {\n // Check if we're in SSR mode (no document)\n if (typeof document === 'undefined') {\n const children = props.children;\n if (!children) return '';\n const childArray = isArray(children) ? children : [children];\n // In SSR, convert children to string\n return childArray.map(child => String(child || '')).join('');\n }\n // Create placeholder comment for parent tree\n const placeholder = document.createComment('portal');\n // Mark as portal for isPortal check\n (placeholder as any)[COMPONENT_TYPE.PORTAL] = true;\n\n const children = props.children;\n if (children) {\n const childArray = isArray(children) ? children : [children];\n const nodes: (Node | string)[] = [];\n\n onMount(() => {\n // Get target element\n const targetElement = isString(props.target)\n ? document.querySelector(props.target)\n : props.target;\n\n if (!targetElement) {\n if (__DEV__) {\n warn(`[Portal] Target element not found: ${props.target}`);\n }\n return;\n }\n\n childArray.forEach(child => {\n if (child != null) {\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(targetElement as Node, normalized);\n nodes.push(normalized);\n }\n }\n });\n\n onCleanup(() => {\n nodes.forEach(node => {\n if (typeof node !== 'string' && node.parentNode === targetElement) {\n targetElement.removeChild(node);\n }\n });\n });\n });\n }\n\n return placeholder;\n}\n\nPortal[COMPONENT_TYPE.PORTAL] = true;\n\n/**\n * Check if a node is a Portal component\n * @param node - Node to check\n * @returns true if node is a Portal\n */\nexport function isPortal(node: unknown): boolean {\n return !!node && !!(node as any)[COMPONENT_TYPE.PORTAL];\n}\n","import { isArray, isPromise, isUndefined, warn } from '@estjs/shared';\nimport { provide } from '../provide';\nimport { isComponent } from '../component';\nimport { normalizeNode } from '../utils/node';\nimport { COMPONENT_TYPE } from '../constants';\nimport { onDestroy } from '../lifecycle';\nimport { getActiveScope } from '../scope';\nimport { insertNode } from '../utils/dom';\nimport type { AnyNode } from '../types';\n\nexport interface SuspenseProps {\n /** The content to render. Can be a Promise for async loading. */\n children?: AnyNode | AnyNode[] | Promise<AnyNode | AnyNode[]>;\n /** Fallback content to display while children is loading (Promise pending). */\n fallback?: AnyNode;\n /** Optional key for reconciliation. */\n key?: string;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport const SuspenseContext = Symbol('SuspenseContext');\n\nexport interface SuspenseContextType {\n register: (promise: Promise<any>) => void;\n increment: () => void;\n decrement: () => void;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI\n *\n * @param props - Component props with children, fallback, and optional key\n * @returns Placeholder node or fallback content\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport function Suspense(props: SuspenseProps): AnyNode {\n // Check if we're in SSR mode (no document)\n if (isUndefined(document)) {\n // In SSR, return fallback as string if available\n const fallback = props.fallback;\n if (fallback) {\n return String(fallback || '');\n }\n return '';\n }\n\n // Create a container to manage content swapping\n const container = document.createElement('div');\n container.style.display = 'contents'; // Invisible wrapper\n\n // Track if component is still mounted (for async cleanup)\n let isMounted = true;\n let pendingCount = 0;\n let isShowingFallback = false;\n\n let resolvedChildren: AnyNode | AnyNode[] | null = null;\n\n const showFallback = () => {\n if (isShowingFallback) return;\n isShowingFallback = true;\n\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n };\n\n const showChildren = () => {\n if (!isShowingFallback) return;\n\n // Check if we have something to show\n // If children is a promise, we need resolvedChildren.\n // If children is not a promise, we use it directly.\n const hasContent = resolvedChildren || (props.children != null && !isPromise(props.children));\n\n if (!hasContent) {\n // If we don't have content (e.g. promise rejected), keep fallback\n return;\n }\n\n isShowingFallback = false;\n\n // Clear container (remove fallback)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n // Simple implementation: Re-render children\n if (resolvedChildren) {\n renderChildren(resolvedChildren);\n } else if (props.children != null && !isPromise(props.children)) {\n renderChildren(props.children);\n }\n };\n\n /**\n * Render children into the container\n */\n const renderChildren = (children: AnyNode | AnyNode[]): void => {\n // Clear existing content\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n if (children == null) return;\n\n const currentScope = getActiveScope();\n const childArray = isArray(children) ? children : [children];\n childArray.forEach(child => {\n if (child != null) {\n // Reparent component to current context to ensure it can access SuspenseContext\n // This is necessary because children are created in the parent scope\n if (isComponent(child)) {\n (child as any).parentContext = currentScope;\n }\n\n const normalized = normalizeNode(child);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n });\n\n // Fix: If a child suspended during insertion, we might have both fallback and children in the container.\n // We need to ensure that if we are in fallback mode, only fallback is shown.\n if (isShowingFallback) {\n // We are in fallback mode.\n // Clear everything (including the just-inserted children)\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n // Re-insert fallback\n if (props.fallback != null) {\n const normalized = normalizeNode(props.fallback);\n if (normalized) {\n insertNode(container, normalized);\n }\n }\n }\n };\n\n // Context for resources to register themselves\n const suspenseContext: SuspenseContextType = {\n register: (promise: Promise<any>) => {\n pendingCount++;\n showFallback();\n\n promise\n .then(() => {\n if (!isMounted) return;\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n })\n .catch(error => {\n if (__DEV__) {\n warn('[Suspense] Resource failed:', error);\n }\n if (!isMounted) return;\n pendingCount--;\n // For now, if error happens, we still try to show children (or maybe error boundary later)\n if (pendingCount === 0) {\n showChildren();\n }\n });\n },\n increment: () => {\n pendingCount++;\n showFallback();\n },\n decrement: () => {\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n },\n };\n\n provide(SuspenseContext, suspenseContext);\n\n const children = props.children;\n\n // Initial render logic\n if (isPromise(children)) {\n // Async children - show fallback immediately, then resolve\n children\n .then(resolved => {\n resolvedChildren = resolved;\n })\n .catch(() => {\n // Ignore error, handled by register\n });\n suspenseContext.register(children);\n } else if (children != null) {\n // Sync children - render immediately\n // If any child is a resource read, it will call register() synchronously during this render\n renderChildren(children);\n } else {\n // No children - show fallback if available\n showFallback();\n }\n\n onDestroy(() => {\n isMounted = false;\n // Clear container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n });\n\n return container;\n}\n\nSuspense[COMPONENT_TYPE.SUSPENSE] = true;\n\n/**\n * Check if a node is a Suspense component\n * @param node - Node to check\n * @returns true if node is a Suspense\n */\nexport function isSuspense(node: unknown): boolean {\n return !!node && !!(node as any)[COMPONENT_TYPE.SUSPENSE];\n}\n","import { type Signal, signal } from '@estjs/signals';\nimport { inject } from '../provide';\nimport { SuspenseContext } from './Suspense';\n\nexport type ResourceState = 'pending' | 'ready' | 'errored';\n\nexport interface Resource<T> {\n (): T | undefined;\n loading: Signal<boolean>;\n error: Signal<Error | null>;\n state: Signal<ResourceState>;\n}\n\nexport interface ResourceActions<T> {\n mutate: (value: T) => void;\n refetch: () => Promise<void>;\n}\n\nexport interface ResourceOptions<T> {\n initialValue?: T;\n}\n\n/**\n * Create a resource for async data fetching\n * Inspired by SolidJS createResource\n *\n * @param fetcher - Function that returns a Promise with the data\n * @param options - Optional configuration\n * @returns Tuple of [resource, actions]\n *\n * @example\n * ```typescript\n * const [data, { refetch, mutate }] = createResource(\n * () => fetch('/api/user').then(r => r.json()),\n * { initialValue: null }\n * );\n *\n * // Access data\n * console.log(data());\n * console.log(data.loading.value);\n * console.log(data.state.value);\n *\n * // Refetch data\n * await refetch();\n *\n * // Update data directly\n * mutate({ name: 'John' });\n * ```\n */\nexport function createResource<T>(\n fetcher: () => Promise<T>,\n options?: ResourceOptions<T>,\n): [Resource<T>, ResourceActions<T>] {\n // Internal state\n const value = signal<T | undefined>(options?.initialValue);\n const loading = signal<boolean>(true);\n const error = signal<Error | null>(null);\n const state = signal<ResourceState>('pending');\n\n let fetchId = 0;\n\n let currentPromise: Promise<void> | null = null;\n\n // Fetch function\n const fetch = async (): Promise<void> => {\n const currentFetchId = ++fetchId;\n loading.value = true;\n state.value = 'pending';\n error.value = null;\n\n try {\n const promise = fetcher();\n currentPromise = promise.then(() => {}).catch(() => {}); // Ensure promise is handled\n const result = await promise;\n\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n value.value = result;\n state.value = 'ready';\n loading.value = false;\n }\n } catch (error_) {\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n error.value = error_ instanceof Error ? error_ : new Error(String(error_));\n state.value = 'errored';\n loading.value = false;\n }\n }\n };\n\n // Start initial fetch\n fetch();\n\n // Resource accessor function\n const resource = (() => {\n // If we are loading and have a suspense context, register the promise\n if (loading.value && currentPromise) {\n const suspenseContext = inject(SuspenseContext, null) as any;\n if (suspenseContext) {\n suspenseContext.register(currentPromise);\n }\n }\n return value.value;\n }) as Resource<T>;\n resource.loading = loading;\n resource.error = error;\n resource.state = state;\n\n // Actions\n const actions: ResourceActions<T> = {\n mutate: (newValue: T) => {\n value.value = newValue;\n state.value = 'ready';\n loading.value = false;\n error.value = null;\n },\n refetch: async () => {\n await fetch();\n },\n };\n\n return [resource, actions];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/scope.ts","../src/operations/attr.ts","../src/operations/class.ts","../src/operations/style.ts","../src/hydration.ts","../src/reconcile.ts","../src/dom.ts","../src/operations/event.ts","../src/lifecycle.ts","../src/component.ts","../src/renderer.ts","../src/provide.ts","../src/events.ts","../src/binding.ts","../src/utils.ts","../src/components/Fragment.ts","../src/components/Portal.ts","../src/components/Suspense.ts","../src/components/createResource.ts","../src/components/AsyncComponent.ts","../src/components/For.ts"],"names":["SPREAD_NAME","SVG_NAMESPACE","XLINK_NAMESPACE","XMLNS_NAMESPACE","FRAGMENT_COMPONENT","PORTAL_COMPONENT","SUSPENSE_COMPONENT","FOR_COMPONENT","activeScope","scopeId","getActiveScope","createScope","parent","scope","runWithScope","fn","prevScope","disposeScope","_a","child","i","error_","onCleanup","patchAttr","el","key","prev","next","prevObj","isObject","nextObj","attrKey","elementIsSVG","isXlink","isXmlns","isBoolean","isSpecialBooleanAttr","isBooleanAttr","lowerKey","localName","includeBooleanAttr","attrValue","isSymbol","isString","v","e","patchClass","isSVG","normalizedNext","normalizeClass","normalizeClassName","importantRE","prefixes","prefixCache","patchStyle","style","setStyle","declRE","match","value","name","val","isArray","element","prefixed","autoPrefix","camelCase","rawName","cached","capitalize","prefix","_hydrationKey","getHydrationKey","resetHydrationKey","_isHydrating","isHydrating","_registry","gatherHydratable","root","nodes","node","_teleportCallsiteAnchors","_teleportTargetStarts","gatherTeleportAnchors","walker","data","bucket","consumeTeleportAnchor","consumeTeleportBlock","target","start","cursor","beginHydration","endHydration","getRenderedElement","html","isBrowser","_csrFactory","template","warn","patchClassHydrate","patchAttrHydrate","patchStyleHydrate","resolveInsertAnchor","candidate","reconcileArrays","oldNodes","newNodes","anchor","fallbackAnchor","oldLength","newLength","insertNode","removeNode","oldEnd","newEnd","nextPos","nextNode","reconcileUnknownSequence","newIndexMap","newIndexToOldIndexMap","patched","moved","maxNewIndexSoFar","oldNode","newIndex","increasingNewIndexSequence","getSequence","j","nextIndex","anchorNode","arr","p","result","len","u","c","arrI","isComponent","before","beforeNode","normalizeNode","isHTMLElement","isPrimitive","isFalsy","insert","nodeFactory","ownerScope","renderedNodes","isFirstRun","resolveNodes","raw","isNull","isUndefined","isNumber","coerceArray","item","isFunction","effectRunner","effect","executeUpdate","rawNodes","step","nthChild","index","current","addEvent","event","handler","options","selector","wrappedHandler","_","nativeOptions","__objRest","registerScopedHook","listKey","hook","hookList","executeHooks","hooks","phase","pending","isPromise","safePromise","onMount","onUpdate","onDestroy","triggerMountHooks","mountHooks","triggerUpdateHooks","syncDescriptors","source","pruneMissing","seen","readProp","descriptor","Component","component","props","container","shallowReactive","parentNode","isSignal","isComputed","isOn","eventName","cleanup","previousValue","createComponent","componentFn","create","firstChild","createApp","rootNode","mountedRoot","hydrate","provide","inject","defaultValue","reTargetEvent","eventHandler","oriTarget","oriCurrentTarget","handleNode","walkUpTree","path","$EVENTS","delegateEvents","eventNames","document","docWithEvents","eventSet","clearDelegatedEvents","addEventListener","INPUT_CHECKBOX_CHECKED","n","INPUT_RADIO_CHECKED","INPUT_FILE_FILES","INPUT_VALUE","SELECT_VALUE","s","o","set","opt","TEXTAREA_VALUE","resolveStrategy","prop","tag","type","castValue","trim","number","parsed","isFocused","bindElement","getter","setter","modifiers","strategy","lazy","isFiles","readModel","transform","composing","syncFromDom","runner","omitProps","keys","excludeSet","obj","Fragment","isFragment","resolveTarget","evalDisabled","Portal","adopted","tryHydratePortal","placeholder","children","innerScope","mountAt","teardown","apply","disabled","mounted","isPortal","clearContainer","resolveNodeValue","SuspenseContext","Suspense","isMounted","pendingCount","isShowingFallback","resolvedChildren","materializeChild","materialized","insertMaterializedChild","normalized","renderFallbackContent","showFallback","showChildren","renderChildren","childArray","suspenseContext","promise","error","resolved","isSuspense","createResource","fetcher","signal","loading","state","fetchId","currentPromise","suspenseRegistered","fetch","__async","currentFetchId","resource","newValue","resolveModule","mod","renderInto","comp","defineAsyncComponent","loader","delay","timeout","ssr","onError","ssrResolved","ssrPromise","ssrLoad","ssrWrapper","cachedComponent","cachedError","cachedStatus","loadPromise","load","AsyncWrapper","alive","currentComp","swap","swapProps","retry","delayTimer","timeoutTimer","retryWith","retryProps","suspenseCtx","showResolved","compFn","showError","err","showLoading","instancePromise","For","fragment","marker","entries","fallbackNodes","keyFn","renderFn","getList","_b","input","getKey","normalizeNodes","mountValue","mountFallback","clearFallback","renderItem","parentScope","mountedNodes","disposeItem","entry","newItems","idx","newItem","reconcile","oldLen","newLen","batchFragment","oldKeyMap","list","pair","newEntries","toRemove","newIndexToOldIndex","maxOldSeen","newKeys","oldList","reused","oldIndex","lis","lisCursor"],"mappings":"ikBAiBO,IAAMA,EAAAA,CAAc,YAcpB,IAAMC,EAAAA,CAAgB,6BAKhBC,EAAAA,CAAkB,8BAAA,CAKlBC,GAAkB,+BAAA,CAGxB,IAAMC,GAAqB,MAAA,CAAwC,EAAE,EAC/DC,EAAAA,CAAmB,MAAA,CAAsC,EAAE,CAAA,CAC3DC,EAAAA,CAAqB,OAAwC,EAAE,CAAA,CAC/DC,GAAgB,MAAA,CAAmC,EAAE,CAAA,CCPlE,IAAIC,EAA4B,IAAA,CAG5BC,EAAAA,CAAU,EAOP,SAASC,CAAAA,EAA+B,CAC7C,OAAOF,CACT,CAmBO,SAASG,CAAAA,CAAYC,EAAuBJ,CAAAA,CAAoB,CACrE,IAAMK,CAAAA,CAAe,CACnB,EAAA,CAAI,EAAEJ,EAAAA,CACN,MAAA,CAAAG,EACA,QAAA,CAAU,IAAA,CACV,SAAU,IAAA,CACV,OAAA,CAAS,KACT,OAAA,CAAS,IAAA,CACT,SAAU,IAAA,CACV,SAAA,CAAW,KACX,SAAA,CAAW,KAAA,CACX,YAAa,KACf,CAAA,CAGA,OAAIA,CAAAA,GACGA,CAAAA,CAAO,WACVA,CAAAA,CAAO,QAAA,CAAW,IAAI,GAAA,CAAA,CAExBA,CAAAA,CAAO,SAAS,GAAA,CAAIC,CAAK,GAGpBA,CACT,CAUO,SAASC,CAAAA,CAAgBD,CAAAA,CAAcE,EAAgB,CAC5D,IAAMC,EAAYR,CAAAA,CAClBA,CAAAA,CAAcK,CAAAA,CAEd,GAAI,CACF,OAAOE,GACT,CAAA,OAAE,CAEAP,CAAAA,CAAcQ,EAChB,CACF,CASO,SAASC,EAAaJ,CAAAA,CAAoB,CA3HjD,IAAAK,CAAAA,CA6HE,GAAI,CAACL,CAAAA,EAASA,CAAAA,CAAM,YAClB,OASF,GAJAA,CAAAA,CAAM,WAAA,CAAc,IAAA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I2W,CAAAA,CAAS,CAAA,CAAG3W,CAAAA,EAAK,CAAA,CAAGA,IAAK,CAEpC,IAAM2D,EADQqT,CAAAA,CAAWhX,CAAC,EACN,KAAA,CAIpB,GAFc,EADEkX,CAAAA,CAAmBlX,CAAC,IAAM,CAAA,CAAA,EAChBsG,CAAAA,EAASmR,GAAa,CAAA,EAAKzX,CAAAA,GAAMwX,EAAIC,CAAS,CAAA,CAE7D,CAGTA,CAAAA,EAAAA,CACA,IAAA,IAAS7Q,EAAIjD,CAAAA,CAAM,MAAA,CAAS,EAAGiD,CAAAA,EAAK,CAAA,CAAGA,IAAKX,CAAAA,CAAWtC,CAAAA,CAAMiD,CAAC,CAAA,CAC9D,QACF,CAKA,IAAA,IAASA,CAAAA,CAAIjD,EAAM,MAAA,CAAS,CAAA,CAAGiD,GAAK,CAAA,CAAGA,CAAAA,EAAAA,CAAK,CAC1C,IAAMhD,EAAAA,CAAOD,CAAAA,CAAMiD,CAAC,CAAA,CAChBhD,EAAAA,CAAK,cAAgBqC,CAAAA,EACvBzG,CAAAA,CAAO,aAAaoE,EAAAA,CAAMqC,CAAQ,EAEpCA,CAAAA,CAAWrC,GACb,CACF,CAEAyR,CAAAA,CAAU2B,EACZ,CAEA,OAAA9W,EAAU,IAAM,CACdwI,CAAAA,CAAa,IAAA,EAAK,CAClB,IAAA,IAAW2N,KAAShB,CAAAA,CAClBe,CAAAA,CAAYC,CAAK,CAAA,CAEnBhB,CAAAA,CAAU,EAAC,CACXW,CAAAA,GACIZ,CAAAA,CAAO,UAAA,EACTA,EAAO,UAAA,CAAW,WAAA,CAAYA,CAAM,EAExC,CAAC,EAEMD,CACT,CAEAD,EAAAA,CAAI/V,EAAa,CAAA,CAAI,IAAA","file":"template.cjs.js","sourcesContent":["/**\n * event prefix, used to distinguish event handler properties\n */\nexport const EVENT_PREFIX = 'on';\n\n/**\n * update prefix, used to identify update callback properties\n */\nexport const UPDATE_PREFIX = 'update';\n\n/**\n * children property name\n */\nexport const CHILDREN_PROP = 'children';\n/**\n * Key name for the Spread attribute\n */\nexport const SPREAD_NAME = '_$spread$';\n\n/**\n * used to get the DOM element reference\n */\nexport const REF_KEY = 'ref';\n/**\n * Component key property name\n */\nexport const KEY_PROP = 'key' as const;\n\n/**\n * SVG namespace constant\n */\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n\n/**\n * XML namespace for xlink attributes\n */\nexport const XLINK_NAMESPACE = 'http://www.w3.org/2000/xlink';\n\n/**\n * xmlns namespace for SVG elements\n */\nexport const XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/';\n\nexport const NORMAL_COMPONENT = Symbol(__DEV__ ? 'Normal Component' : '');\nexport const FRAGMENT_COMPONENT = Symbol(__DEV__ ? 'Fragment Component' : '');\nexport const PORTAL_COMPONENT = Symbol(__DEV__ ? 'Portal Component' : '');\nexport const SUSPENSE_COMPONENT = Symbol(__DEV__ ? 'Suspense Component' : '');\nexport const FOR_COMPONENT = Symbol(__DEV__ ? 'For Component' : '');\nexport enum COMPONENT_STATE {\n /** Initial state */\n INITIAL,\n /** Mounting */\n MOUNTING,\n /** MOUNTED */\n MOUNTED,\n /** Updating */\n UPDATING,\n /** Destroying */\n DESTROYING,\n /** destroy */\n DESTROYED,\n}\nexport enum COMPONENT_TYPE {\n NORMAL = 'normal',\n FRAGMENT = 'fragment',\n PORTAL = 'portal',\n SUSPENSE = 'suspense',\n FOR = 'for',\n}\n","import { error } from '@estjs/shared';\nimport type { InjectionKey } from './provide';\n\n/**\n * Scope represents an execution context in the component tree.\n * It manages provides, cleanup functions, and lifecycle hooks.\n */\nexport interface Scope {\n /** Unique identifier for debugging */\n readonly id: number;\n\n /** Parent scope in the hierarchy */\n parent: Scope | null;\n\n /** Child scopes (lazy initialized) */\n children: Set<Scope> | null;\n\n /** Provided values (lazy initialized) */\n provides: Map<InjectionKey<unknown> | string | number | symbol, unknown> | null;\n\n /** Cleanup functions (lazy initialized) */\n cleanup: Array<() => void> | null;\n\n /** Mount lifecycle hooks (lazy initialized) */\n onMount: Array<() => void | Promise<void>> | null;\n\n /** Update lifecycle hooks (lazy initialized) */\n onUpdate: Array<() => void | Promise<void>> | null;\n\n /** Destroy lifecycle hooks (lazy initialized) */\n onDestroy: Array<() => void | Promise<void>> | null;\n\n /** Whether the scope has been mounted */\n isMounted: boolean;\n\n /** Whether the scope has been destroyed */\n isDestroyed: boolean;\n}\n\n/** Currently active scope */\nlet activeScope: Scope | null = null;\n\n/** Scope ID counter for unique identification */\nlet scopeId = 0;\n\n/**\n * Get the currently active scope.\n *\n * @returns The active scope or null if none is active.\n */\nexport function getActiveScope(): Scope | null {\n return activeScope;\n}\n\n/**\n * Set the active scope (internal use).\n *\n * @param scope - The scope to set as active.\n * @returns {void}\n */\nexport function setActiveScope(scope: Scope | null): void {\n activeScope = scope;\n}\n\n/**\n * Create a new scope with optional parent.\n * If no parent is provided, uses the current active scope as parent.\n *\n * @param parent - Optional parent scope (defaults to active scope).\n * @returns A new scope instance.\n */\nexport function createScope(parent: Scope | null = activeScope): Scope {\n const scope: Scope = {\n id: ++scopeId,\n parent,\n children: null, // Lazy initialized\n provides: null, // Lazy initialized\n cleanup: null, // Lazy initialized\n onMount: null, // Lazy initialized\n onUpdate: null, // Lazy initialized\n onDestroy: null, // Lazy initialized\n isMounted: false,\n isDestroyed: false,\n };\n\n // Establish parent-child relationship\n if (parent) {\n if (!parent.children) {\n parent.children = new Set();\n }\n parent.children.add(scope);\n }\n\n return scope;\n}\n\n/**\n * Run a function within a scope, ensuring proper cleanup.\n * The previous active scope is restored even if the function throws.\n *\n * @param scope - The scope to run within.\n * @param fn - The function to execute.\n * @returns The return value of the function.\n */\nexport function runWithScope<T>(scope: Scope, fn: () => T): T {\n const prevScope = activeScope;\n activeScope = scope;\n\n try {\n return fn();\n } finally {\n // Restore previous scope directly\n activeScope = prevScope;\n }\n}\n\n/**\n * Dispose a scope and all its children.\n * Children are disposed first (depth-first), then the scope itself.\n *\n * @param scope - The scope to dispose.\n * @returns {void}\n */\nexport function disposeScope(scope: Scope): void {\n // Idempotent: already destroyed\n if (!scope || scope.isDestroyed) {\n return;\n }\n\n // Mark destroyed immediately to block re-entrant disposeScope calls\n // (e.g. an onDestroy hook that accidentally disposes the same scope again).\n scope.isDestroyed = true;\n\n // Dispose children first (depth-first)\n // Iterate directly safely by unlinking parent reference to prevent mutation during iteration\n if (scope.children && scope.children.size > 0) {\n for (const child of scope.children) {\n if (child) {\n child.parent = null;\n disposeScope(child);\n }\n }\n scope.children.clear();\n }\n\n // Execute destroy lifecycle hooks and cleanup functions within the scope's\n // context so that inject/provide/getActiveScope work correctly in callbacks.\n //\n // We inline the scope-switching instead of calling `runWithScope()` to avoid\n // an extra function frame on the teardown hot path (disposeScope is called\n // recursively for every child scope in the tree).\n //\n // NOTE: `scope.isDestroyed` is already `true` at this point — this is\n // intentional to prevent re-entrant `disposeScope()` calls from within\n // hooks. Callbacks that inspect `getActiveScope()?.isDestroyed` should\n // be aware of this.\n const prevScope = activeScope;\n activeScope = scope;\n try {\n // Execute destroy lifecycle hooks\n if (scope.onDestroy) {\n for (let i = 0; i < scope.onDestroy.length; i++) {\n try {\n scope.onDestroy[i]();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in destroy hook:`, error_);\n }\n }\n }\n scope.onDestroy = null;\n }\n\n // Execute cleanup functions\n if (scope.cleanup) {\n for (let i = 0; i < scope.cleanup.length; i++) {\n try {\n scope.cleanup[i]();\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scope.id}): Error in cleanup:`, error_);\n }\n }\n }\n scope.cleanup = null;\n }\n } finally {\n activeScope = prevScope;\n }\n\n // Remove from parent's children\n if (scope.parent?.children) {\n scope.parent.children.delete(scope);\n }\n\n // Clear all internal collections to prevent memory leaks\n if (scope.provides) {\n scope.provides.clear();\n scope.provides = null;\n }\n scope.onMount = null;\n scope.onUpdate = null;\n scope.children = null;\n\n // Break parent reference to prevent memory leaks\n scope.parent = null;\n}\n\n/**\n * Register a cleanup function in the current scope.\n * The function will be called when the scope is disposed.\n *\n * @param fn - The cleanup function.\n */\nexport function onCleanup(fn: () => void): void {\n const scope = activeScope;\n\n if (!scope) {\n if (__DEV__) {\n error('onCleanup() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize cleanup array\n if (!scope.cleanup) {\n scope.cleanup = [];\n }\n\n scope.cleanup.push(fn);\n}\n","import {\n includeBooleanAttr,\n isBooleanAttr,\n isObject,\n isSpecialBooleanAttr,\n isString,\n isSymbol,\n warn,\n} from '@estjs/shared';\nimport {\n KEY_PROP,\n SPREAD_NAME,\n SVG_NAMESPACE,\n XLINK_NAMESPACE,\n XMLNS_NAMESPACE,\n} from '../constants';\n\n/**\n * Supported value types for the attribute patch layer.\n *\n * In addition to primitive values, spread objects are also accepted, so the\n * type keeps `Record<string, unknown>`.\n */\nexport type AttrValue = string | boolean | number | null | undefined | Record<string, unknown>;\n\n/**\n * Applies a minimal attribute update to an element.\n *\n * This is the most general-purpose attribute updater in the template runtime.\n * It is responsible for:\n * - skipping internal reserved fields;\n * - expanding spread attribute objects;\n * - handling boolean attributes and SVG / xlink / xmlns namespaces;\n * - applying basic dangerous-URL protection;\n * - refusing raw HTML sinks such as `innerHTML` / `srcdoc`;\n * - staying silent during hydration to avoid overwriting SSR DOM.\n *\n * @param el - The element to patch.\n * @param key - The attribute key.\n * @param prev - Previous attribute value.\n * @param next - Next attribute value.\n */\nexport function patchAttr(el: Element, key: string, prev: AttrValue, next: AttrValue) {\n if (key === KEY_PROP) {\n if (next == null) {\n el.removeAttribute(key);\n } else {\n el.setAttribute(key, String(next));\n }\n return;\n }\n if (key === SPREAD_NAME) {\n const prevObj = isObject(prev) ? (prev as Record<string, unknown>) : null;\n const nextObj = isObject(next) ? (next as Record<string, unknown>) : null;\n\n if (__DEV__) {\n if (next != null && !nextObj) {\n warn('spread attribute must be an object');\n }\n }\n\n if (prevObj) {\n for (const attrKey in prevObj) {\n if (attrKey === SPREAD_NAME) {\n if (__DEV__) {\n warn('nested spread attributes are ignored');\n }\n continue;\n }\n if (!nextObj || !(attrKey in nextObj)) {\n patchAttr(el, attrKey, prevObj[attrKey] as AttrValue, null);\n }\n }\n }\n\n if (nextObj) {\n for (const attrKey in nextObj) {\n if (attrKey === SPREAD_NAME) {\n if (__DEV__) {\n warn('nested spread attributes are ignored');\n }\n continue;\n }\n patchAttr(el, attrKey, prevObj?.[attrKey] as AttrValue, nextObj[attrKey] as AttrValue);\n }\n }\n return;\n }\n\n const elementIsSVG = el?.namespaceURI === SVG_NAMESPACE;\n const isXlink = elementIsSVG && key.startsWith('xlink:');\n const isXmlns = elementIsSVG && key.startsWith('xmlns:');\n\n const isBoolean = isSpecialBooleanAttr(key) || isBooleanAttr(key);\n\n // Early return if values are the same\n if (prev === next) {\n return;\n }\n\n // Event attributes are handled by the dedicated event layer, so skip them here.\n if (key.length > 2 && key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110) {\n return;\n }\n\n // Lowercase only after early returns, since it is only needed for specific checks like href.\n const lowerKey = key.toLowerCase();\n\n if (lowerKey === 'innerhtml' || lowerKey === 'srcdoc') {\n if (__DEV__) {\n warn(`${key} updates are ignored by patchAttr`);\n }\n return;\n }\n\n if (next == null) {\n if (isXlink) {\n el.removeAttributeNS(XLINK_NAMESPACE, key.slice(6));\n } else if (isXmlns) {\n const localName = key.slice(6);\n el.removeAttributeNS(XMLNS_NAMESPACE, localName);\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n if (isBoolean) {\n if (includeBooleanAttr(next)) {\n el.setAttribute(key, '');\n } else {\n el.removeAttribute(key);\n }\n return;\n }\n\n const attrValue = isSymbol(next) ? String(next) : next;\n\n // Basic safety guard: block dangerous protocols on common URL attributes.\n const isUrlAttr =\n lowerKey === 'href' ||\n lowerKey === 'src' ||\n lowerKey === 'xlink:href' ||\n lowerKey === 'action' ||\n lowerKey === 'formaction' ||\n lowerKey === 'poster';\n if (isUrlAttr && isString(attrValue)) {\n const v = attrValue.trim().toLowerCase();\n if (v.startsWith('javascript:') || v.startsWith('data:')) {\n return;\n }\n }\n\n if (isXlink) {\n el.setAttributeNS(XLINK_NAMESPACE, key, String(attrValue));\n return;\n }\n\n if (isXmlns) {\n el.setAttributeNS(XMLNS_NAMESPACE, key, String(attrValue));\n return;\n }\n\n if (elementIsSVG) {\n el.setAttribute(key, String(attrValue));\n } else {\n if (key in el) {\n try {\n el[key] = attrValue;\n } catch {\n el.setAttribute(key, String(attrValue));\n }\n } else {\n el.setAttribute(key, String(attrValue));\n }\n }\n}\n","import { isString, normalizeClassName } from '@estjs/shared';\n\n/**\n * Supported value types for the class patch layer.\n */\nexport type ClassValue = string | Record<string, boolean> | ClassValue[] | null | undefined;\n\n/**\n * Applies a minimal class update to an element.\n *\n * Class values are normalized into a string first, then written through\n * `className` or `setAttribute('class')` depending on the element type.\n * Hydration stays silent and reuses the server-rendered result by default.\n *\n * @param el - The element to patch.\n * @param prev - Previous class value.\n * @param next - Next class value.\n * @param isSVG - Whether the element is an SVG element.\n * @returns {void}\n */\nexport function patchClass(\n el: Element,\n prev: unknown,\n next: unknown,\n isSVG: boolean = false,\n): void {\n if (prev === next) {\n return;\n }\n\n const normalizedNext = normalizeClass(next);\n if (!normalizedNext) {\n el.removeAttribute('class');\n return;\n }\n\n // Skip DOM write if normalized values are identical.\n // For string prev, it's already normalized; otherwise normalize.\n const normalizedPrev = isString(prev) ? prev : normalizeClass(prev);\n if (normalizedPrev === normalizedNext) {\n return;\n }\n\n // SVG nodes cannot rely on `className` consistently, so use the attribute path.\n if (isSVG) {\n el.setAttribute('class', normalizedNext);\n } else {\n el.className = normalizedNext;\n }\n}\n\n/**\n * Normalizes supported class inputs into a single string.\n */\nexport const normalizeClass = normalizeClassName;\n","import { camelCase, capitalize, isArray, isObject, isString } from '@estjs/shared';\n\n/**\n * Internal symbol used to mark raw CSS variable text in style objects.\n * @internal\n */\nexport const CSS_VAR_TEXT: unique symbol = Symbol('CSS_VAR_TEXT');\n\n// Precompile the `!important` detector to avoid recreating it on every write.\nconst importantRE = /\\s*!important$/;\n\n// Candidate vendor prefixes and their lookup cache.\nconst prefixes = ['Webkit', 'Moz', 'ms'];\nconst prefixCache: Record<string, string> = {};\n\n/**\n * Supported value types for the style patch layer.\n */\nexport type Style = string | Record<string, string | string[]> | null | undefined;\n\n/**\n * Applies a minimal style update to an element.\n *\n * Supports both string-based and object-based styles, while staying silent\n * during hydration so the server-rendered DOM can be reused.\n *\n * @param el - The element to patch.\n * @param prev - Previous style value.\n * @param next - Next style value.\n * @returns {void}\n */\nexport function patchStyle(el: HTMLElement, prev: unknown, next?: unknown) {\n const style = el.style;\n\n if (next && isString(next)) {\n if (prev !== next) {\n style.cssText = next;\n }\n return;\n }\n\n if (!next) {\n if (prev) {\n el.removeAttribute('style');\n }\n return;\n }\n\n // When the previous value is an object, remove keys that disappeared in the next value.\n if (prev && !isString(prev)) {\n const prevObj = prev as Record<string, unknown>;\n for (const key in prevObj) {\n if (!next || (next as Record<string, unknown>)[key] == null) {\n setStyle(style, key, '');\n }\n }\n } else if (prev && isString(prev)) {\n // When the previous value is a string, approximate its keys and remove missing ones.\n // Match only CSS property-name tokens (letters/digits/hyphens before a colon).\n // This is linear and ignores semicolons inside url() or quoted values because\n // those fragments never match /letter+:/.\n const declRE = /(?:^|;)\\s*([a-z][a-z\\d-]*)\\s*:/gi;\n let match: RegExpExecArray | null;\n while ((match = declRE.exec(prev)) !== null) {\n const key = match[1].trim();\n if (key && next && isObject(next) && (next as Record<string, unknown>)[key] == null) {\n setStyle(style, key, '');\n }\n }\n }\n\n // Apply the next style values last.\n if (next && !isString(next)) {\n const nextObj = next as Record<string, unknown>;\n for (const key in nextObj) {\n const value = nextObj[key];\n if (\n (!prev || isString(prev) || (prev as Record<string, unknown>)[key] !== value) &&\n value != null\n ) {\n setStyle(style, key, value as string | string[]);\n }\n }\n }\n}\n\n/**\n * Sets a single style property.\n *\n * Centralizes array-value expansion, CSS variable writes, vendor-prefix\n * resolution, and `!important` handling in one place.\n *\n * @param style - Target style object.\n * @param name - Style property name.\n * @param val - Style value.\n * @private\n */\nexport function setStyle(style: CSSStyleDeclaration, name: string, val: string | string[]): void {\n // Array values represent multiple candidates for the same property.\n if (isArray(val)) {\n for (const element of val) {\n setStyle(style, name, element);\n }\n return;\n }\n\n if (val == null || val === '') {\n val = '';\n }\n\n // CSS variables must be written through `setProperty()`.\n if (name.startsWith('--')) {\n style.setProperty(name, val);\n return;\n }\n\n // Regular properties try vendor prefix resolution first.\n const prefixed = autoPrefix(style, name);\n\n // `!important` cannot use direct property assignment and must go through `setProperty()`.\n if (isString(val) && importantRE.test(val)) {\n style.setProperty(camelCase(prefixed), val.replace(importantRE, ''), 'important');\n } else {\n style[prefixed] = val;\n }\n}\n\n/**\n * Resolves the correct vendor-prefixed style property name.\n *\n * Results are cached in `prefixCache` to avoid repeated hot-path detection.\n *\n * @param style - Target style object.\n * @param rawName - Original property name.\n * @returns The property name that can be written to `style` directly.\n * @private\n */\nfunction autoPrefix(style: CSSStyleDeclaration, rawName: string): string {\n // Check the cache first.\n const cached = prefixCache[rawName];\n if (cached) {\n return cached;\n }\n\n // Try the standard camelCase property first.\n let name = camelCase(rawName);\n if (name !== 'filter' && name in style) {\n return (prefixCache[rawName] = name);\n }\n\n // If the standard property does not exist, try vendor-prefixed variants.\n name = capitalize(name);\n for (const prefix of prefixes) {\n const prefixed = prefix + name;\n if (prefixed in style) {\n return (prefixCache[rawName] = prefixed);\n }\n }\n\n return rawName;\n}\n","import { isBrowser, warn } from '@estjs/shared';\nimport { patchAttr } from './operations/attr';\nimport { patchClass } from './operations/class';\nimport { patchStyle } from './operations/style';\nimport { template } from './renderer';\n\n// ---------------------------------------------------------------------------\n// Hydration key counter (mirrors server-side getHydrationKey / resetHydrationKey)\n// ---------------------------------------------------------------------------\n\nlet _hydrationKey = 0;\n\n/**\n * Returns a new hydration key.\n *\n * @returns The new hydration key as a string.\n */\nexport function getHydrationKey(): string {\n return String(_hydrationKey++);\n}\n\n/**\n * Resets the client-side hydration key counter.\n *\n * @returns {void}\n */\nexport function resetHydrationKey(): void {\n _hydrationKey = 0;\n}\n\n// ---------------------------------------------------------------------------\n// Hydration state + registry\n// ---------------------------------------------------------------------------\n\n/**\n * Module-private hydration flag.\n *\n * Read via `isHydrating()` instead of importing as a `let` binding — this\n * avoids cross-bundle \"live binding\" pitfalls when consumers go through a\n * barrel-export (`import { isHydrating } from '@estjs/template'`).\n */\nlet _isHydrating = false;\n\n/**\n * Returns whether the runtime is currently in the hydration first-pass.\n *\n * @returns True while hydrating, false otherwise.\n */\nexport function isHydrating(): boolean {\n return _isHydrating;\n}\n\n/**\n * Pre-built map of data-hk → Element, populated by beginHydration().\n * Mirrors SolidJS's sharedConfig.registry / gatherHydratable().\n */\nconst _registry = new Map<string, Element>();\n\n/**\n * Gather all [data-hk] elements under `root` into the registry.\n * Called once at hydration start — O(n) DOM query, then O(1) lookups.\n *\n * @param root - The root element to scan.\n */\nfunction gatherHydratable(root: Element): void {\n const nodes = root.querySelectorAll('[data-hk]');\n for (const node of nodes) {\n const key = (node as HTMLElement).dataset.hk;\n if (key != null && !_registry.has(key)) {\n _registry.set(key, node as Element);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Teleport (Portal) hydration anchors\n// ---------------------------------------------------------------------------\n\n/** FIFO queue of `<!--teleport-anchor-->` comments at Portal call sites. */\nconst _teleportCallsiteAnchors: Comment[] = [];\n\n/** Per-target FIFO of `<!--teleport-start-->` comments inside teleport targets. */\nconst _teleportTargetStarts = new Map<Element, Comment[]>();\n\n/** Scan `document.body` for teleport comment markers, classifying each into its queue. */\nfunction gatherTeleportAnchors(): void {\n if (typeof document === 'undefined') return;\n const walker = document.createNodeIterator(document.body, NodeFilter.SHOW_COMMENT);\n let node: Comment | null;\n\n while ((node = walker.nextNode() as Comment | null)) {\n const data = node.data;\n if (data === 'teleport-anchor') {\n _teleportCallsiteAnchors.push(node);\n } else if (data === 'teleport-start') {\n const parent = node.parentElement;\n if (!parent) continue;\n let bucket = _teleportTargetStarts.get(parent);\n if (!bucket) {\n bucket = [];\n _teleportTargetStarts.set(parent, bucket);\n }\n bucket.push(node);\n }\n }\n}\n\n/** Pop the next call-site anchor comment, or `null` if exhausted. */\nexport function consumeTeleportAnchor(): Comment | null {\n return _teleportCallsiteAnchors.shift() ?? null;\n}\n\n/** Pop the next teleport block from `target`, returning start/end markers and inner nodes. */\nexport function consumeTeleportBlock(\n target: Element,\n): { start: Comment; end: Comment; nodes: Node[] } | null {\n const bucket = _teleportTargetStarts.get(target);\n const start = bucket?.shift();\n if (!start) return null;\n\n const nodes: Node[] = [];\n let cursor: Node | null = start.nextSibling;\n while (cursor) {\n if (cursor.nodeType === Node.COMMENT_NODE && (cursor as Comment).data === 'teleport-end') {\n return { start, end: cursor as Comment, nodes };\n }\n nodes.push(cursor);\n cursor = cursor.nextSibling;\n }\n\n // Malformed block — no <!--teleport-end--> found. Return null to signal\n // a hydration mismatch rather than returning `{ start, end: start }` which\n // would be semantically incorrect.\n if (__DEV__) {\n warn('[Portal] hydration: orphaned <!--teleport-start--> without matching <!--teleport-end-->');\n }\n return null;\n}\n\n/**\n * Begins hydration.\n *\n * @param root - The root element to hydrate.\n */\nexport function beginHydration(root: Element): void {\n _isHydrating = true;\n _hydrationKey = 0;\n _registry.clear();\n _teleportCallsiteAnchors.length = 0;\n _teleportTargetStarts.clear();\n gatherHydratable(root);\n gatherTeleportAnchors();\n}\n\n/**\n * Ends hydration.\n *\n * @returns {void}\n */\nexport function endHydration(): void {\n _isHydrating = false;\n _registry.clear();\n _teleportCallsiteAnchors.length = 0;\n _teleportTargetStarts.clear();\n}\n\n/**\n * Returns a factory function that, when called at component render time:\n * - During hydration: increments the key, looks up the pre-built registry,\n * and returns the ACTUAL SSR DOM node (no cloneNode).\n * - During CSR: clones the parsed template as usual.\n *\n * @param html - The HTML template string.\n * @returns A factory function that returns a DOM element.\n */\nexport function getRenderedElement(html: string): () => Element {\n if (!isBrowser()) {\n return () => {\n throw new Error('[essor] getRenderedElement called in non-browser environment');\n };\n }\n\n let _csrFactory: (() => Element) | null = null;\n\n return (): Element => {\n if (!_isHydrating) {\n // CSR path — clone the template as normal\n if (!_csrFactory) _csrFactory = template(html) as () => Element;\n return _csrFactory();\n }\n\n // Hydration path — key incremented HERE (render time) to match server order\n const key = getHydrationKey();\n const node = _registry.get(key);\n\n if (node) {\n _registry.delete(key);\n return node; // TRUE DOM reuse — no cloneNode\n }\n\n // Mismatch: SSR node not found, fall back to CSR creation\n warn(`[essor] hydration mismatch: no SSR element for key \"${key}\"`);\n if (!_csrFactory) _csrFactory = template(html) as () => Element;\n return _csrFactory();\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hydrate-mode patch wrappers (silence DOM writes during first hydration run)\n// ---------------------------------------------------------------------------\n\n/**\n * Patches class while considering hydration state.\n *\n * @param el - The element to patch.\n * @param prev - Previous class value.\n * @param next - Next class value.\n * @param isSVG - Whether the element is an SVG element.\n */\nexport function patchClassHydrate(\n el: Element,\n prev: unknown,\n next: unknown,\n isSVG?: boolean,\n): void {\n if (_isHydrating) return;\n patchClass(el, prev, next, isSVG);\n}\n\n/**\n * Patches attribute while considering hydration state.\n *\n * @param el - The element to patch.\n * @param key - The attribute key.\n * @param prev - Previous attribute value.\n * @param next - Next attribute value.\n */\nexport function patchAttrHydrate(el: Element, key: string, prev: unknown, next: unknown): void {\n if (_isHydrating) return;\n patchAttr(el, key, prev as never, next as never);\n}\n\n/**\n * Patches style while considering hydration state.\n *\n * @param el - The element to patch.\n * @param prev - Previous style value.\n * @param next - Next style value.\n */\nexport function patchStyleHydrate(el: HTMLElement, prev: unknown, next?: unknown): void {\n if (_isHydrating) return;\n patchStyle(el, prev, next);\n}\n","import { insertNode, removeNode } from './dom';\n\n/**\n * Resolves insert anchor.\n *\n * @param parent - The parent node.\n * @param candidate - The candidate anchor node.\n * @returns The resolved anchor node or null.\n */\nfunction resolveInsertAnchor(parent: Node, candidate?: Node | null): Node | null {\n return candidate && candidate.parentNode === parent ? candidate : null;\n}\n\n/**\n * Reconcile two arrays of real DOM nodes with minimal DOM operations.\n * This is the list reconciler for fine-grained rendering.\n *\n * @param parent - The parent node.\n * @param oldNodes - The array of current nodes.\n * @param newNodes - The array of new nodes.\n * @param anchor - Optional reference node for insertion.\n * @returns The new array of nodes.\n */\nexport function reconcileArrays(\n parent: Node,\n oldNodes: Node[],\n newNodes: Node[],\n anchor?: Node,\n): Node[] {\n const fallbackAnchor = resolveInsertAnchor(parent, anchor);\n const oldLength = oldNodes.length;\n const newLength = newNodes.length;\n\n if (oldLength === 0 && newLength === 0) return newNodes;\n\n if (oldLength === 0) {\n for (let i = 0; i < newLength; i++) {\n insertNode(parent, newNodes[i], fallbackAnchor);\n }\n return newNodes;\n }\n\n if (newLength === 0) {\n for (let i = 0; i < oldLength; i++) {\n removeNode(oldNodes[i]);\n }\n return [];\n }\n\n let start = 0;\n let oldEnd = oldLength - 1;\n let newEnd = newLength - 1;\n\n while (start <= oldEnd && start <= newEnd) {\n if (oldNodes[start] === newNodes[start]) {\n start++;\n } else {\n break;\n }\n }\n\n while (oldEnd >= start && newEnd >= start) {\n if (oldNodes[oldEnd] === newNodes[newEnd]) {\n oldEnd--;\n newEnd--;\n } else {\n break;\n }\n }\n\n if (start > oldEnd) {\n if (start <= newEnd) {\n const nextPos = newEnd + 1;\n const nextNode = resolveInsertAnchor(\n parent,\n nextPos < newLength ? newNodes[nextPos] : fallbackAnchor,\n );\n for (let i = start; i <= newEnd; i++) {\n insertNode(parent, newNodes[i], nextNode);\n }\n }\n } else if (start > newEnd) {\n for (let i = start; i <= oldEnd; i++) {\n removeNode(oldNodes[i]);\n }\n } else {\n reconcileUnknownSequence(parent, oldNodes, newNodes, start, oldEnd, newEnd, fallbackAnchor);\n }\n\n return newNodes;\n}\n\n/**\n * Reconciles unknown sequence of nodes.\n *\n * @param parent - The parent node.\n * @param oldNodes - Current nodes.\n * @param newNodes - New nodes.\n * @param start - Start index of the sequence.\n * @param oldEnd - End index of the old sequence.\n * @param newEnd - End index of the new sequence.\n * @param anchor - Optional reference node for insertion.\n * @returns {void}\n */\nfunction reconcileUnknownSequence(\n parent: Node,\n oldNodes: Node[],\n newNodes: Node[],\n start: number,\n oldEnd: number,\n newEnd: number,\n anchor?: Node | null,\n): void {\n const newLength = newEnd - start + 1;\n const newIndexMap = new Map<Node, number>();\n for (let i = start; i <= newEnd; i++) {\n newIndexMap.set(newNodes[i], i);\n }\n\n const newIndexToOldIndexMap = new Int32Array(newLength);\n newIndexToOldIndexMap.fill(0);\n\n let patched = 0;\n let moved = false;\n let maxNewIndexSoFar = 0;\n\n for (let i = start; i <= oldEnd; i++) {\n const oldNode = oldNodes[i];\n\n if (patched >= newLength) {\n removeNode(oldNode);\n continue;\n }\n\n const newIndex = newIndexMap.get(oldNode);\n\n if (newIndex === undefined) {\n removeNode(oldNode);\n } else {\n newIndexToOldIndexMap[newIndex - start] = i + 1;\n\n if (newIndex >= maxNewIndexSoFar) {\n maxNewIndexSoFar = newIndex;\n } else {\n moved = true;\n }\n patched++;\n }\n }\n\n const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : [];\n let j = increasingNewIndexSequence.length - 1;\n\n for (let i = newLength - 1; i >= 0; i--) {\n const nextIndex = start + i;\n const nextNode = newNodes[nextIndex];\n const anchorNode = resolveInsertAnchor(\n parent,\n nextIndex + 1 < newNodes.length ? newNodes[nextIndex + 1] : anchor,\n );\n\n if (newIndexToOldIndexMap[i] === 0) {\n insertNode(parent, nextNode, anchorNode);\n } else if (moved) {\n if (j < 0 || i !== increasingNewIndexSequence[j]) {\n insertNode(parent, nextNode, anchorNode);\n } else {\n j--;\n }\n }\n }\n}\n\n/**\n * Compute the Longest Increasing Subsequence using patience sorting.\n * O(n log n) time, O(n) space.\n *\n * @param arr - The array of indices.\n * @returns The LIS indices.\n */\nexport function getSequence(arr: Int32Array): number[] {\n const p = new Int32Array(arr.length);\n const result = [0];\n const len = arr.length;\n let i: number;\n let j: number;\n let u: number;\n let v: number;\n let c: number;\n\n for (i = 0; i < len; i++) {\n const arrI = arr[i];\n if (arrI !== 0) {\n j = result[result.length - 1];\n if (arr[j] < arrI) {\n p[i] = j;\n result.push(i);\n continue;\n }\n u = 0;\n v = result.length - 1;\n while (u < v) {\n c = (u + v) >> 1;\n if (arr[result[c]] < arrI) {\n u = c + 1;\n } else {\n v = c;\n }\n }\n if (arrI < arr[result[u]]) {\n if (u > 0) {\n p[i] = result[u - 1];\n }\n result[u] = i;\n }\n }\n }\n u = result.length;\n v = result[u - 1];\n while (u-- > 0) {\n result[u] = v;\n v = p[v];\n }\n return result;\n}\n","import {\n coerceArray,\n error,\n hasOwn,\n isBoolean,\n isFalsy,\n isFunction,\n isHTMLElement,\n isNull,\n isNumber,\n isObject,\n isPrimitive,\n isString,\n isUndefined,\n} from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { isComponent } from './component';\nimport { KEY_PROP } from './constants';\nimport { type Scope, getActiveScope, onCleanup, runWithScope } from './scope';\nimport { isHydrating } from './hydration';\nimport { reconcileArrays } from './reconcile';\nimport type { AnyNode } from './types';\n\n/**\n * Remove node from its parent\n *\n * @param node Node to remove\n *\n * @example\n * ```typescript\n * removeNode(elementToRemove);\n * ```\n */\nexport function removeNode(node: AnyNode): void {\n if (!node) return;\n\n if (isComponent(node)) {\n node.destroy();\n } else {\n const element = node as ChildNode;\n if (element.parentNode) {\n element.remove();\n }\n }\n}\n\n/**\n * Insert child node\n * Handle insertion of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param child Child node\n * @param before Reference node for insertion\n */\nexport function insertNode(parent: Node, child: AnyNode, before?: AnyNode): void {\n if (!parent || !child) return;\n\n const beforeNode = isComponent(before) ? before.firstChild : (before as Node);\n\n if (isComponent(child)) {\n child.mount(parent, beforeNode);\n return;\n }\n\n if (beforeNode) {\n parent.insertBefore(child as Node, beforeNode);\n } else {\n if (__DEV__) {\n if (!child) {\n error('insertNode: child is not a Node', child);\n }\n }\n parent.appendChild(child as Node);\n }\n}\n\n/**\n * Replace child node\n * Handle replacement of component nodes and DOM nodes\n *\n * @param parent Parent node\n * @param newNode New node\n * @param oldNode Old node to be replaced\n */\nexport function replaceNode(parent: Node, newNode: AnyNode, oldNode: AnyNode): void {\n if (!parent || !newNode || !oldNode || newNode === oldNode) return;\n\n const beforeNode: AnyNode | undefined = isComponent(oldNode)\n ? oldNode.beforeNode\n : (oldNode as Node).nextSibling!;\n removeNode(oldNode);\n insertNode(parent, newNode, beforeNode);\n}\n\n/**\n * Check if two nodes are the same (inline for performance)\n * This combines key check and type check\n */\nexport function isSameNode(a: AnyNode, b: AnyNode): boolean {\n // Check key equality first (fast path)\n const keyA = getNodeKey(a);\n const keyB = getNodeKey(b);\n\n if (keyA !== keyB) {\n return false;\n }\n\n // Inline type check to avoid function call\n const aIsComponent = isComponent(a);\n const bIsComponent = isComponent(b);\n\n if (aIsComponent && bIsComponent) {\n return a.component === b.component;\n }\n\n if (aIsComponent !== bIsComponent) {\n return false;\n }\n\n if (isPrimitive(a) || isPrimitive(b)) {\n return a === b;\n }\n\n const aNode = a as Node;\n const bNode = b as Node;\n\n if (aNode.nodeType !== bNode.nodeType) {\n return false;\n }\n\n if (aNode.nodeType === Node.ELEMENT_NODE) {\n return (aNode as Element).tagName === (bNode as Element).tagName;\n }\n\n return true;\n}\n\n/**\n * Extract the optional stable key associated with a runtime node.\n */\nfunction getNodeKey(node: AnyNode): unknown {\n if (!node) {\n return undefined;\n }\n\n if (isComponent(node)) {\n return hasOwn(node.props, KEY_PROP) ? node.props[KEY_PROP] : undefined;\n }\n\n if (node instanceof Element) {\n return node.getAttribute(KEY_PROP);\n }\n\n if (isObject(node) && hasOwn(node, KEY_PROP)) {\n return Reflect.get(node as object, KEY_PROP);\n }\n\n return undefined;\n}\n\n/**\n * Normalize node for reconciliation\n */\nexport function normalizeNode(node: unknown): Node {\n // already a Node\n if (isHTMLElement(node)) {\n return node;\n }\n\n if (isPrimitive(node)) {\n return document.createTextNode(isFalsy(node) ? '' : String(node));\n }\n\n return node as Node;\n}\n/**\n * Reactive node insertion with binding support\n *\n * @param parent Parent node\n * @param nodeFactory Node factory function or static node\n * @param before Reference node for insertion position\n * @example\n * ```typescript\n * insert(container, () => message.value, null);\n * insert(container, staticElement, referenceNode);\n * insert(container, \"Hello World\", null); // Direct string support\n * ```\n */\nexport function insert(parent: Node, nodeFactory: AnyNode, before?: Node) {\n if (!parent) return;\n // Capture owner scope at call time - this is critical for correct context inheritance\n // When dynamic components are created inside effects, they need to inherit from\n // the scope that was active when insert() was called, not when the effect runs\n const ownerScope: Scope | null = getActiveScope();\n\n let renderedNodes: Node[] = [];\n let isFirstRun = true;\n\n /**\n * Resolves a raw node value into a flat array of DOM Nodes.\n * Fast-paths simple cases (single Node, single primitive) to avoid\n * intermediate array allocations.\n */\n const resolveNodes = (raw: unknown): Node[] => {\n // Fast path: already a DOM Node\n if (raw instanceof Node) return [raw];\n\n // Fast path: single primitive → text node\n if (isNull(raw) || isUndefined(raw) || isString(raw) || isNumber(raw) || isBoolean(raw)) {\n return [normalizeNode(raw)];\n }\n\n // General path: coerce, resolve nested functions, flatten, normalize\n return coerceArray(raw)\n .map((item) => (isFunction(item) ? item() : item))\n .flatMap((i) => i)\n .map(normalizeNode) as Node[];\n };\n\n // Create effect for reactive updates\n const effectRunner = effect(() => {\n const executeUpdate = () => {\n const rawNodes = isFunction(nodeFactory) ? nodeFactory() : nodeFactory;\n const nodes = resolveNodes(rawNodes);\n // Hydration mode: skip DOM operations on first run only when every\n // node already exists under the target parent. Component instances and\n // fallback CSR nodes still need the normal reconcile path.\n if (\n isFirstRun &&\n isHydrating() &&\n nodes.every((node) => node instanceof Node && node.parentNode === parent)\n ) {\n renderedNodes = nodes;\n isFirstRun = false;\n return;\n }\n renderedNodes = reconcileArrays(parent, renderedNodes as Node[], nodes, before) as Node[];\n isFirstRun = false;\n };\n\n // If we have an owner scope, run within it to maintain context hierarchy\n if (ownerScope && !ownerScope.isDestroyed) {\n runWithScope(ownerScope, executeUpdate);\n } else {\n executeUpdate();\n }\n });\n\n onCleanup(() => {\n effectRunner.stop();\n for (const node of renderedNodes) removeNode(node);\n renderedNodes = [];\n });\n\n return renderedNodes;\n}\n/**\n * Returns the first child of a node.\n *\n * @param node - The node to get the child from.\n * @returns The first child node or null.\n */\nexport function child(node: Node | null): Node | null {\n return node?.firstChild || null;\n}\n\n/**\n * Returns the next sibling after advancing by `step`.\n *\n * @param node - The starting node.\n * @param step - Number of steps to advance.\n * @returns The resulting sibling node or null.\n */\nexport function next(node: Node | null, step: number = 1): Node | null {\n while (node && step > 0) {\n node = node.nextSibling;\n step--;\n }\n return node || null;\n}\n\n/**\n * Returns the child node at the requested index.\n *\n * @param node - The parent node.\n * @param index - The child index.\n * @returns The child node at index or null.\n */\nexport function nthChild(node: Node | null, index: number): Node | null {\n if (!node || index < 0) return null;\n let current = node.firstChild;\n while (current && index > 0) {\n current = current.nextSibling;\n index--;\n }\n return current || null;\n}\n","/**\n * Extended listener options with optional event delegation support.\n */\nexport interface EventOptions extends AddEventListenerOptions {\n /**\n * Selector used for event delegation.\n *\n * When provided, the handler only runs if the event target matches the selector.\n */\n delegate?: string;\n}\n\n/**\n * Cleanup function signature for event listeners.\n */\nexport type EventCleanup = () => void;\n\n/**\n * Adds an event listener to an element with optional simple delegation.\n *\n * Without `delegate`, this is a thin wrapper around native `addEventListener()`.\n * When `delegate` is provided, the runtime first checks the selector match before\n * dispatching the real handler to the caller.\n *\n * @param el - The element to add the listener to.\n * @param event - The name of the event to listen for.\n * @param handler - The event handler function.\n * @param options - Optional event listener options.\n * @returns A cleanup function that removes the listener.\n */\nexport function addEvent(\n el: Element,\n event: string,\n handler: EventListener,\n options?: EventOptions,\n): EventCleanup {\n if (!options?.delegate) {\n el.addEventListener(event, handler, options);\n return () => el.removeEventListener(event, handler, options);\n }\n\n // Delegation path: match the selector first, then forward the event to the caller.\n const selector = options.delegate;\n /**\n * Dispatches delegated events only for matching descendants.\n */\n const wrappedHandler = (e: Event) => {\n const target = e.target as Element;\n if (target.matches(selector) || target.closest(selector)) {\n handler.call(el, e);\n }\n };\n\n // Extract delegate from options and pass the rest to addEventListener\n const { delegate: _, ...nativeOptions } = options;\n\n el.addEventListener(event, wrappedHandler, nativeOptions);\n\n return () => {\n el.removeEventListener(event, wrappedHandler, nativeOptions);\n };\n}\n","import { error, isPromise } from '@estjs/shared';\nimport { type Scope, getActiveScope, runWithScope } from './scope';\n\nexport type LifecycleHook = () => void | Promise<void>;\n\n/**\n * Registers scoped hook.\n *\n * @param scope - The scope to register the hook for.\n * @param listKey - The key of the hook list.\n * @param hook - The hook function to register.\n */\nfunction registerScopedHook(\n scope: Scope,\n listKey: 'onMount' | 'onUpdate' | 'onDestroy',\n hook: LifecycleHook,\n): void {\n let hookList = scope[listKey];\n if (!hookList) {\n hookList = [];\n scope[listKey] = hookList;\n }\n hookList.push(hook);\n}\n\n/**\n * Executes lifecycle hooks and captures async rejections in dev mode.\n *\n * @param hooks - The array of hooks to execute.\n * @param scopeId - The ID of the scope.\n * @param phase - The lifecycle phase.\n * @returns A promise if any hooks are asynchronous, or undefined.\n */\nfunction executeHooks(\n hooks: LifecycleHook[],\n scopeId: number,\n phase: 'mount' | 'update' | 'destroy',\n): void | Promise<void> {\n const len = hooks.length;\n if (len === 0) return;\n\n let pending: Promise<void>[] | undefined;\n\n for (let i = 0; i < len; i++) {\n try {\n const result = hooks[i]();\n if (isPromise(result)) {\n const safePromise = result.catch((error_) => {\n if (__DEV__) {\n error(`Scope(${scopeId}): Async ${phase} hook rejected:`, error_);\n }\n });\n (pending || (pending = [])).push(safePromise);\n }\n } catch (error_) {\n if (__DEV__) {\n error(`Scope(${scopeId}): Error in ${phase} hook:`, error_);\n }\n }\n }\n\n if (!pending) return;\n return Promise.all(pending).then(() => {});\n}\n\n/**\n * Register a mount lifecycle hook.\n * If the scope is already mounted, the hook is executed immediately.\n *\n * @param hook - The hook function to register.\n * @returns {void}\n */\nexport function onMount(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onMount() must be called within a scope');\n return;\n }\n\n if (scope.isMounted) {\n try {\n const result = hook();\n if (isPromise(result)) {\n result.catch((error_) => {\n if (__DEV__) error(`Scope(${scope.id}): Async mount hook rejected:`, error_);\n });\n }\n } catch (error_) {\n if (__DEV__) error(`Scope(${scope.id}): Error in mount hook:`, error_);\n }\n return;\n }\n\n registerScopedHook(scope, 'onMount', hook);\n}\n\n/**\n * Register an update lifecycle hook.\n *\n * @param hook - The hook function to register.\n * @returns {void}\n */\nexport function onUpdate(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onUpdate() must be called within a scope');\n return;\n }\n\n registerScopedHook(scope, 'onUpdate', hook);\n}\n\n/**\n * Register a destroy lifecycle hook.\n *\n * @param hook - The hook function to register.\n * @returns {void}\n */\nexport function onDestroy(hook: LifecycleHook): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) error('onDestroy() must be called within a scope');\n return;\n }\n\n registerScopedHook(scope, 'onDestroy', hook);\n}\n\n/**\n * Trigger mount lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger hooks for.\n * @returns A promise if any hooks are asynchronous, or undefined.\n */\nexport function triggerMountHooks(scope: Scope): void | Promise<void> {\n if (scope.isDestroyed) {\n return;\n }\n if (!scope.onMount || scope.onMount.length === 0) {\n scope.isMounted = true;\n return;\n }\n\n const mountHooks = scope.onMount;\n const result = runWithScope(scope, () => executeHooks(mountHooks, scope.id, 'mount'));\n mountHooks.length = 0;\n scope.isMounted = true;\n return result;\n}\n\n/**\n * Trigger update lifecycle hooks for a scope.\n *\n * @param scope - The scope to trigger hooks for.\n * @returns A promise if any hooks are asynchronous, or undefined.\n */\nexport function triggerUpdateHooks(scope: Scope): void | Promise<void> {\n if (scope.isDestroyed || !scope.onUpdate || scope.onUpdate.length === 0) return;\n return runWithScope(scope, () => executeHooks(scope.onUpdate!, scope.id, 'update'));\n}\n\n// NOTE: destroy hooks are executed directly inside `disposeScope` to keep\n// the teardown path synchronous and free of extra `runWithScope` frames.\n// See `./scope.ts`.\n","import { isComputed, isSignal, shallowReactive } from '@estjs/signals';\nimport { isFunction, isOn } from '@estjs/shared';\n\nimport { COMPONENT_STATE, COMPONENT_TYPE, REF_KEY } from './constants';\nimport { insert, insertNode, removeNode } from './dom';\nimport { createScope, disposeScope, getActiveScope, runWithScope } from './scope';\nimport { type EventCleanup, addEvent } from './operations/event';\nimport { triggerMountHooks, triggerUpdateHooks } from './lifecycle';\nimport type { AnyNode, ComponentFn, ComponentProps } from './types';\nimport type { Scope } from './scope';\n\n/**\n * Install every own-key descriptor from `source` onto `target` verbatim\n * (getters stay getters), optionally deleting any target key not present\n * in the incoming source.\n *\n * Preserving getter descriptors is the whole reason the component body can\n * read `props.foo` and transparently get the latest reactive value — the\n * compiler emits dynamic props as `{ get foo() { return signal.value } }`.\n * `{ ...props }` would snapshot each getter once and kill reactivity;\n * `defineProperty` keeps it alive.\n */\nfunction syncDescriptors(target: object, source: object, pruneMissing = false): void {\n const seen = pruneMissing ? new Set<string>() : null;\n for (const key of Object.getOwnPropertyNames(source)) {\n seen?.add(key);\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)!);\n }\n if (seen) {\n for (const key of Object.getOwnPropertyNames(target)) {\n if (!seen.has(key)) delete (target as Record<string, unknown>)[key];\n }\n }\n}\n\n/**\n * Read a prop value through its descriptor so dynamic getters (ref/event\n * handlers emitted as `get onClick() { ... }`) resolve to the latest value.\n */\nfunction readProp(source: object, key: string): unknown {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)!;\n return descriptor.get ? descriptor.get.call(source) : descriptor.value;\n}\n\nexport class Component<P extends ComponentProps = {}> {\n public readonly [COMPONENT_TYPE.NORMAL] = true;\n\n public scope: Scope | null = null;\n public state: COMPONENT_STATE = COMPONENT_STATE.INITIAL;\n public beforeNode: Node | undefined = undefined;\n public renderedNodes: Node[] = [];\n public firstChild: Node | undefined = undefined;\n\n protected parentNode: Node | undefined = undefined;\n\n private readonly parentScope: Scope | null;\n private readonly reactiveProps: P;\n private rootEventCleanups: EventCleanup[] = [];\n private rootRefCleanup?: () => void;\n\n constructor(\n public readonly component: ComponentFn<P>,\n public props: P = {} as P,\n ) {\n this.parentScope = getActiveScope();\n // Shallow-reactive container that inherits the raw props' descriptors.\n // The component body reads from this container; `update()` re-installs\n // new descriptors in-place so existing closures keep working.\n const container = {} as P;\n syncDescriptors(container, props);\n this.reactiveProps = shallowReactive(container) as P;\n }\n\n /**\n * Mount the component into `parentNode` (optionally before `beforeNode`).\n * If already rendered, the existing DOM is re-inserted without re-running\n * the component function.\n */\n mount(parentNode: Node, beforeNode?: Node): AnyNode[] {\n this.parentNode = parentNode;\n this.beforeNode = beforeNode;\n this.state = COMPONENT_STATE.MOUNTING;\n\n // Fast path: already rendered — just move the nodes.\n if (this.renderedNodes.length > 0) {\n for (const node of this.renderedNodes) {\n insertNode(parentNode, node, beforeNode);\n }\n this.state = COMPONENT_STATE.MOUNTED;\n return this.renderedNodes;\n }\n\n const scope = createScope(this.parentScope ?? getActiveScope());\n this.scope = scope;\n\n const renderedNodes = runWithScope(scope, () => {\n let result: unknown = this.component(this.reactiveProps);\n\n // Render-function pattern: a component may return a factory instead of\n // the element directly.\n if (isFunction(result)) {\n result = (result as Function)(this.reactiveProps);\n }\n\n // Unwrap signal / computed — only their current value reaches the DOM.\n if (isSignal<Element>(result) || isComputed<Element>(result)) {\n result = result.value;\n }\n\n return insert(parentNode, result as AnyNode, beforeNode) ?? [];\n });\n\n this.renderedNodes = renderedNodes;\n this.firstChild = renderedNodes[0];\n\n // Wire refs/events only after renderedNodes/firstChild are set.\n this.syncSpecialProps(this.props);\n\n this.state = COMPONENT_STATE.MOUNTED;\n triggerMountHooks(scope);\n\n return this.renderedNodes;\n }\n\n /**\n * Re-install props into the same `reactiveProps` container (preserving\n * any closures already holding a reference to it) and re-apply\n * refs/events against the current root element.\n */\n update(props: P): void {\n this.props = props;\n const scope = this.scope;\n if (!scope || scope.isDestroyed) return;\n\n syncDescriptors(this.reactiveProps as object, props ?? {}, /* pruneMissing */ true);\n this.syncSpecialProps(props);\n\n triggerUpdateHooks(scope);\n }\n\n /**\n * Tear down and re-mount the component at its current insertion point.\n * No-op if the component has never been mounted.\n */\n forceUpdate(): void {\n if (!this.parentNode) return;\n const parent = this.parentNode;\n const before = this.beforeNode;\n this.destroy();\n this.mount(parent, before);\n }\n\n /**\n * Dispose the scope, remove all rendered nodes, and clear bookkeeping.\n * Idempotent: subsequent calls are no-ops.\n */\n destroy(): void {\n const scope = this.scope;\n if (!scope || scope.isDestroyed) return;\n this.scope = null;\n this.releaseSpecialProps();\n disposeScope(scope);\n for (const node of this.renderedNodes) removeNode(node);\n this.renderedNodes = [];\n this.firstChild = undefined;\n this.parentNode = undefined;\n }\n\n /**\n * Apply props that bind to the root DOM element rather than flowing into\n * the component body: `ref` (signal/function) and `onXxx` event handlers.\n * The render-facing `reactiveProps` already has those keys; here we just\n * wire them to the actual DOM node.\n */\n private syncSpecialProps(props: P): void {\n if (!props) return;\n const root = this.firstChild as Element | undefined;\n if (!root) return;\n\n this.releaseSpecialProps();\n\n for (const key of Object.getOwnPropertyNames(props)) {\n const value = readProp(props, key);\n\n if (key === REF_KEY) {\n this.rootRefCleanup = this.bindRootRef(value, root);\n continue;\n }\n\n if (isOn(key) && isFunction(value)) {\n const eventName = key.slice(2).toLowerCase();\n this.rootEventCleanups.push(addEvent(root, eventName, value as EventListener));\n }\n }\n }\n\n /**\n * Remove all listeners/ref bindings currently attached to the root element.\n */\n private releaseSpecialProps(): void {\n for (const cleanup of this.rootEventCleanups) {\n cleanup();\n }\n this.rootEventCleanups.length = 0;\n\n if (this.rootRefCleanup) {\n this.rootRefCleanup();\n this.rootRefCleanup = undefined;\n }\n }\n\n /**\n * Bind the root ref prop and return a cleanup that restores the previous ref state.\n */\n private bindRootRef(value: unknown, root: Element): (() => void) | undefined {\n if (isFunction(value)) {\n value(root);\n return () => value(null);\n }\n\n if (isSignal(value)) {\n const previousValue = value.value;\n value.value = root;\n return () => {\n if (value.value === root) {\n value.value = previousValue;\n }\n };\n }\n\n return undefined;\n }\n}\n\n/**\n * Check if a value is a Component instance.\n */\nexport function isComponent(node: unknown): node is Component {\n return !!node && !!(node as Record<PropertyKey, unknown>)[COMPONENT_TYPE.NORMAL];\n}\n\n/**\n * Wrap a component function in a Component instance, or pass an existing\n * Component instance through unchanged.\n */\nexport function createComponent<P extends ComponentProps>(\n componentFn: ComponentFn<P>,\n props?: P,\n): Component<P> {\n if (isComponent(componentFn)) {\n return componentFn as unknown as Component<P>;\n }\n return new Component(componentFn, props);\n}\n","import { isString, warn } from '@estjs/shared';\nimport { type Component, createComponent, isComponent } from './component';\nimport { createScope, disposeScope, runWithScope } from './scope';\nimport { beginHydration, endHydration } from './hydration';\nimport { insert, insertNode } from './dom';\nimport type { ComponentFn, ComponentProps } from './types';\n\n/**\n * Create a template factory function from HTML string.\n *\n * This function creates a reusable template factory that efficiently clones\n * DOM nodes from the provided HTML string. The template is parsed once.\n *\n * Security note: `template(html)` is a raw HTML entrypoint. The caller is\n * responsible for ensuring `html` is trusted and not derived from unsanitized\n * user input.\n *\n * @param html - The HTML string to create template from.\n * @returns Factory function that returns a cloned node of the template.\n * @throws {Error} When template content is empty or invalid.\n *\n * @example\n * ```typescript\n * const buttonTemplate = template('<button>Click me</button>');\n * const button1 = buttonTemplate(); // Creates first button instance\n * const button2 = buttonTemplate(); // Creates second button instance\n * ```\n */\nexport function template(html: string) {\n let node: Node | undefined;\n\n /**\n * Creates the cached template root node on first use.\n */\n const create = (): Node => {\n // Regular HTML template\n const template = document.createElement('template');\n template.innerHTML = html;\n const firstChild = template.content.firstChild;\n if (!firstChild) {\n throw new Error('Invalid template: empty content');\n }\n return firstChild;\n };\n\n // return a factory function: create the template when first called, reuse the cached template when called later\n return () => (node || (node = create())).cloneNode(true);\n}\n\n/**\n * Create and mount an application with the specified component.\n *\n * This function initializes an application by mounting a root component\n * to a target DOM element. It handles target validation and cleanup.\n *\n * @param component - The root component function to mount.\n * @param target - CSS selector string or DOM element to mount to.\n * @returns Object with root component and unmount function.\n *\n * @example\n * ```typescript\n * const App = () => template('<div>Hello World</div>')\n * const app = createApp(App, '#root');\n *\n * // Or with DOM element\n * const container = document.getElementById('app');\n * const app = createApp(App, container);\n * ```\n */\nexport function createApp<P extends ComponentProps = {}>(\n component: ComponentFn<P>,\n target: string | Element,\n) {\n const container = isString(target) ? document.querySelector(target) : (target as Element);\n if (!container) {\n if (__DEV__) {\n warn(`Target element not found: ${target}`);\n }\n return;\n }\n\n const existingContent = container.innerHTML;\n if (existingContent) {\n if (__DEV__) {\n warn(`Target element is not empty, it will be cleared: ${target}`);\n }\n container.innerHTML = '';\n }\n\n const scope = createScope();\n let rootNode: Component | undefined;\n try {\n runWithScope(scope, () => {\n const mountedRoot = createComponent(component);\n if (isComponent(mountedRoot)) {\n rootNode = mountedRoot;\n insertNode(container, mountedRoot);\n }\n });\n } catch (error_) {\n disposeScope(scope);\n throw error_;\n }\n\n return {\n root: rootNode,\n unmount: () => {\n disposeScope(scope);\n rootNode?.destroy();\n },\n };\n}\n\nexport function hydrate<P extends ComponentProps = {}>(\n component: ComponentFn<P>,\n target: string | Element,\n) {\n const container = isString(target) ? document.querySelector(target) : (target as Element);\n if (!container) {\n if (__DEV__) {\n warn(`[essor] hydrate: target element not found: ${target}`);\n }\n return;\n }\n\n beginHydration(container);\n\n const scope = createScope();\n let rootNode: Component | undefined;\n try {\n runWithScope(scope, () => {\n const mountedRoot = createComponent(component);\n if (isComponent(mountedRoot)) {\n rootNode = mountedRoot;\n insert(container, mountedRoot);\n }\n });\n } catch (error_) {\n disposeScope(scope);\n throw error_;\n } finally {\n endHydration();\n }\n\n return {\n root: rootNode,\n unmount: () => {\n disposeScope(scope);\n rootNode?.destroy();\n },\n };\n}\n","import { error } from '@estjs/shared';\nimport { type Scope, getActiveScope } from './scope';\n\n/**\n * InjectionKey is a unique identifier for provided values.\n * Using Symbol ensures type safety and prevents key collisions.\n */\n// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types, unused-imports/no-unused-vars\nexport interface InjectionKey<T> extends Symbol {}\n\n/**\n * Provide a value in the current scope.\n * The value can be injected by this scope or any descendant scope.\n *\n * @param key - The injection key.\n * @param value - The value to provide.\n * @returns {void}\n */\nexport function provide<T>(key: InjectionKey<T> | string | number, value: T): void {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('provide() must be called within a scope');\n }\n return;\n }\n\n // Lazy initialize provides map\n if (!scope.provides) {\n scope.provides = new Map();\n }\n\n scope.provides.set(key, value);\n}\n\n/**\n * Inject a value from the scope hierarchy.\n * Traverses up the parent chain until finding a matching key.\n *\n * @param key - The injection key.\n * @param defaultValue - Default value if key is not found.\n * @returns The injected value or default value.\n */\nexport function inject<T>(key: InjectionKey<T> | string | number, defaultValue?: T): T {\n const scope = getActiveScope();\n\n if (!scope) {\n if (__DEV__) {\n error('inject() must be called within a scope');\n }\n return defaultValue as T;\n }\n\n // Traverse up the hierarchy\n let current: Scope | null = scope;\n while (current) {\n if (current.provides) {\n if (current.provides.has(key)) {\n return current.provides.get(key) as T;\n }\n }\n current = current.parent;\n }\n\n return defaultValue as T;\n}\n","import { isFunction, isString } from '@estjs/shared';\nimport { addEvent } from './operations/event';\nimport { getActiveScope, onCleanup } from './scope';\n\n/**\n * Retargets an event to a delegated host node.\n *\n * @param e - The event object.\n * @param value - The new target value.\n * @returns {void}\n */\nfunction reTargetEvent(e: Event, value: EventTarget): void {\n Object.defineProperty(e, 'target', {\n configurable: true,\n value,\n });\n}\n\n/**\n * Event handler for delegated events.\n *\n * @param e - The event object.\n */\nfunction eventHandler(e: Event): void {\n let node = e.target as any;\n const key = e.type;\n const oriTarget = e.target;\n const oriCurrentTarget = e.currentTarget;\n\n /**\n * Handle event on current node\n * @returns {boolean} Whether to continue propagation\n */\n const handleNode = (): boolean => {\n const handler = node[`_$${key}`];\n if (handler && isFunction(handler) && !node.disabled) {\n const data = node[`${key}Data`];\n data ? handler.call(node, data, e) : handler.call(node, e);\n if (e.cancelBubble) return false;\n }\n\n // Handle host element retargeting\n if (\n node.host &&\n !isString(node.host) &&\n !node.host._$host &&\n isFunction(node.contains) &&\n node.contains(e.target)\n ) {\n reTargetEvent(e, node.host);\n }\n return true;\n };\n\n /**\n * Walk up the DOM tree handling events\n */\n const walkUpTree = (): void => {\n while (handleNode() && (node = node._$host || node.parentNode || node.host));\n };\n\n // simulate currentTarget\n Object.defineProperty(e, 'currentTarget', {\n configurable: true,\n /**\n * Returns the current delegated target for the event.\n */\n get() {\n return node || document;\n },\n });\n\n if (e.composedPath) {\n const path = e.composedPath();\n reTargetEvent(e, path[0]);\n for (let i = 0; i < path.length - 2; i++) {\n node = path[i] as any;\n if (!handleNode()) break;\n if (node._$host) {\n node = node._$host;\n // bubble up from portal mount instead of composedPath\n walkUpTree();\n break;\n }\n if (node.parentNode === oriCurrentTarget) {\n break; // don't bubble above root of event delegation\n }\n }\n }\n // fallback for browsers that don't support composedPath\n else walkUpTree();\n // Mixing portals and shadow dom can lead to a nonstandard target, so reset here.\n reTargetEvent(e, oriTarget!);\n}\n\n/**\n * Symbol for storing delegated events on document\n */\nconst $EVENTS = Symbol('_$EVENTS');\n\n/**\n * Set up event delegation for specified event types.\n *\n * @param eventNames - Array of event names to delegate.\n * @param document - Document to attach events to (defaults to window.document).\n */\nexport function delegateEvents(eventNames: string[], document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS] || (docWithEvents[$EVENTS] = new Set<string>());\n\n for (const name of eventNames) {\n if (!eventSet.has(name)) {\n eventSet.add(name);\n document.addEventListener(name, eventHandler);\n }\n }\n}\n\n/**\n * Clear all delegated events from document.\n *\n * @param document - Document to clear events from (defaults to window.document).\n */\nexport function clearDelegatedEvents(document: Document = window.document): void {\n const docWithEvents = document as Document & { [$EVENTS]?: Set<string> };\n const eventSet = docWithEvents[$EVENTS];\n if (eventSet) {\n for (const name of eventSet.keys()) {\n document.removeEventListener(name, eventHandler);\n }\n delete docWithEvents[$EVENTS];\n }\n}\n/**\n * Registers an event listener and scopes its cleanup when needed.\n *\n * @param element - The element to add the listener to.\n * @param event - The event name.\n * @param handler - The event handler.\n * @param options - Optional event listener options.\n * @returns {void}\n */\nexport function addEventListener(\n element: Element,\n event: string,\n handler: EventListener,\n options?: AddEventListenerOptions,\n): void {\n const cleanup = addEvent(element, event, handler, options);\n\n if (getActiveScope()) {\n onCleanup(cleanup);\n }\n}\n","import { isFunction, isString } from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { addEventListener } from './events';\nimport { getActiveScope, onCleanup } from './scope';\n\n/**\n * Modifiers supported by `bind:*` two-way bindings.\n *\n * - `trim` strip surrounding whitespace from string values\n * - `number` coerce numeric strings to numbers (no-op on `NaN`)\n * - `lazy` commit on `change` instead of `input`\n */\nexport interface BindModifiers {\n trim?: boolean;\n number?: boolean;\n lazy?: boolean;\n [key: string]: boolean | undefined;\n}\n\n// ─── Bind Strategy Table ───\n\ninterface BindStrategy {\n /** Default DOM event used to sync DOM → model. */\n event: string;\n read: (node: Element) => unknown;\n write: (node: Element, value: unknown) => void;\n /** Force using `change` even when not lazy (e.g. checkbox / select / file). */\n forceChangeEvent?: boolean;\n /** Element accepts free-form text and may emit composition events (IME). */\n needsComposition?: boolean;\n}\n\nconst INPUT_CHECKBOX_CHECKED: BindStrategy = {\n event: 'change',\n forceChangeEvent: true,\n read: (n) => (n as HTMLInputElement).checked,\n write: (n, v) => {\n const el = n as HTMLInputElement;\n const next = Boolean(v);\n if (el.checked !== next) el.checked = next;\n },\n};\n\nconst INPUT_RADIO_CHECKED: BindStrategy = {\n event: 'change',\n forceChangeEvent: true,\n read: (n) => {\n const el = n as HTMLInputElement;\n return el.checked ? el.value : '';\n },\n write: (n, v) => {\n const el = n as HTMLInputElement;\n const next = String(v) === el.value;\n if (el.checked !== next) el.checked = next;\n },\n};\n\nconst INPUT_FILE_FILES: BindStrategy = {\n event: 'change',\n forceChangeEvent: true,\n read: (n) => (n as HTMLInputElement).files,\n // Browsers do not allow programmatic writes to <input type=\"file\">.\n write: () => {},\n};\n\nconst INPUT_VALUE: BindStrategy = {\n event: 'input',\n needsComposition: true,\n read: (n) => (n as HTMLInputElement).value,\n write: (n, v) => {\n const el = n as HTMLInputElement;\n const next = v == null ? '' : String(v);\n if (el.value !== next) el.value = next;\n },\n};\n\nconst SELECT_VALUE: BindStrategy = {\n event: 'change',\n forceChangeEvent: true,\n read: (n) => {\n const s = n as HTMLSelectElement;\n return s.multiple ? Array.from(s.selectedOptions, (o) => o.value) : s.value;\n },\n write: (n, v) => {\n const s = n as HTMLSelectElement;\n if (s.multiple) {\n const set = new Set((Array.isArray(v) ? v : []).map(String));\n for (const opt of Array.from(s.options)) opt.selected = set.has(opt.value);\n } else {\n const next = v == null ? '' : String(v);\n if (s.value !== next) s.value = next;\n }\n },\n};\n\nconst TEXTAREA_VALUE: BindStrategy = {\n event: 'input',\n needsComposition: true,\n read: (n) => (n as HTMLTextAreaElement).value,\n write: (n, v) => {\n const el = n as HTMLTextAreaElement;\n const next = v == null ? '' : String(v);\n if (el.value !== next) el.value = next;\n },\n};\n\n/**\n * Resolves the read/write/event strategy for a DOM element + prop combination.\n */\nfunction resolveStrategy(node: Element, prop: string): BindStrategy {\n const tag = node.nodeName;\n if (tag === 'INPUT') {\n const type = (node as HTMLInputElement).type;\n if (prop === 'checked') {\n return type === 'radio' ? INPUT_RADIO_CHECKED : INPUT_CHECKBOX_CHECKED;\n }\n if (prop === 'files') return INPUT_FILE_FILES;\n return INPUT_VALUE;\n }\n if (tag === 'SELECT') return SELECT_VALUE;\n if (tag === 'TEXTAREA') return TEXTAREA_VALUE;\n // Fallback for custom elements or contenteditable hosts.\n return {\n event: 'input',\n read: (n) => (n as any)[prop],\n write: (n, v) => {\n (n as any)[prop] = v;\n },\n };\n}\n\n/**\n * Applies built-in modifiers (trim, number) to a raw value.\n */\nfunction castValue(val: unknown, trim?: boolean, number?: boolean): unknown {\n if (!isString(val)) return val;\n if (trim) val = (val as string).trim();\n if (number && val !== '') {\n const parsed = Number(val);\n if (!Number.isNaN(parsed)) return parsed;\n }\n return val;\n}\n\n/** Whether `node` is the currently focused element (Document / ShadowRoot aware). */\nfunction isFocused(node: Element): boolean {\n const root = node.getRootNode();\n return (root instanceof Document || root instanceof ShadowRoot) && root.activeElement === node;\n}\n\n/**\n * Synchronizes a DOM element property with a model getter and setter.\n *\n * @param node The element to bind. `null` is tolerated (no-op).\n * @param prop Bound property: `value` / `checked` / `files` / arbitrary.\n * @param getter Reactive getter or static initial value.\n * @param setter Receives the new value when the user edits the DOM.\n * @param modifiers Optional `BindModifiers`.\n */\nexport function bindElement(\n node: Element | null,\n prop: 'value' | 'checked' | 'files' | string,\n getter: (() => unknown) | unknown,\n setter: (value: unknown) => void,\n modifiers: BindModifiers = {},\n): void {\n if (!node) return;\n\n const strategy = resolveStrategy(node, prop);\n const { trim, number, lazy } = modifiers;\n const isFiles = prop === 'files';\n\n const readModel = (): unknown => (isFunction(getter) ? (getter as () => unknown)() : getter);\n\n // File inputs hold a `FileList` and never benefit from string casting.\n const transform = (v: unknown): unknown => (isFiles ? v : castValue(v, trim, number));\n\n // ── DOM → Model ──\n const eventName = lazy || strategy.forceChangeEvent ? 'change' : strategy.event;\n\n // Closure flag (avoids polluting the DOM node with a `_composing` property).\n let composing = false;\n\n const syncFromDom = (): void => {\n if (composing) return;\n const raw = strategy.read(node);\n if (raw === undefined) return;\n\n if (isFiles) {\n setter(raw);\n return;\n }\n\n const next = transform(raw);\n if (!Object.is(readModel(), next)) {\n setter(next);\n }\n };\n\n addEventListener(node, eventName, syncFromDom);\n\n // For trim/number, also normalize the displayed value on `change` (blur), so the\n // input shows the canonical form (e.g. trimmed whitespace) even when bound lazily.\n if (!lazy && !isFiles && (trim || number) && eventName !== 'change') {\n addEventListener(node, 'change', () => {\n strategy.write(node, transform(strategy.read(node)));\n });\n }\n\n // IME composition: pause sync during composition; resume on end.\n if (strategy.needsComposition && !lazy) {\n addEventListener(node, 'compositionstart', () => {\n composing = true;\n });\n addEventListener(node, 'compositionend', () => {\n if (!composing) return;\n composing = false;\n // Run the same sync path now that composition has finished.\n syncFromDom();\n });\n }\n\n // ── Model → DOM ──\n const runner = effect(() => {\n const value = readModel();\n\n // Avoid disturbing the user while they are typing in a focused text input.\n if (strategy.needsComposition && !lazy && isFocused(node)) {\n if (composing) return;\n const current = transform(strategy.read(node));\n if (Object.is(current, value)) return;\n }\n\n strategy.write(node, value);\n });\n\n if (getActiveScope()) {\n onCleanup(() => runner.stop());\n }\n}\n","/**\n * Shallow compare two objects\n * @param {any} a - The first object to compare\n * @param {any} b - The second object to compare\n * @returns {boolean} - Returns true if the objects are equal, false otherwise\n */\nexport function shallowCompare(a: any, b: any): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n\n for (const key in a) {\n if (a[key] !== b[key]) return false;\n }\n\n for (const key in b) {\n if (!(key in a)) return false;\n }\n\n return true;\n}\n\n/**\n * Omits props from a target object using a proxy.\n *\n * @param target - The target object.\n * @param keys - The keys to omit.\n * @returns A proxy that omits specified keys.\n */\nexport function omitProps<T extends object, K extends keyof T>(target: T, keys: K[]): Omit<T, K> {\n const excludeSet = new Set(keys);\n\n return new Proxy(target, {\n /**\n * Returns a property unless it is excluded by the proxy.\n */\n get(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.get(obj, prop);\n },\n /**\n * Returns the enumerable keys that are not excluded from the proxy.\n */\n ownKeys(obj) {\n return Reflect.ownKeys(obj).filter((key) => !excludeSet.has(key as K));\n },\n /**\n * Returns the property descriptor unless the key is excluded.\n */\n getOwnPropertyDescriptor(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return undefined;\n }\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n /**\n * Returns whether the requested value exists.\n */\n has(obj, prop) {\n if (excludeSet.has(prop as K)) {\n return false;\n }\n return Reflect.has(obj, prop);\n },\n });\n}\n","import { FRAGMENT_COMPONENT } from '../constants';\nimport type { AnyNode, ComponentProps } from '../types';\n\nexport interface FragmentProps extends ComponentProps {\n children?: AnyNode | AnyNode[];\n}\n\n/**\n * Fragment component - renders multiple children without wrapper elements (Client-side only).\n *\n * **Client-side behavior:**\n * - Returns children directly for rendering.\n * - Hydration system matches children using hydration keys.\n * - The template system handles array children automatically.\n *\n * @param props - Component props with children.\n * @returns {AnyNode} Children directly without wrapper.\n *\n * @example\n * ```tsx\n * // Basic usage\n * <Fragment>\n * <div>First</div>\n * <span>Second</span>\n * </Fragment>\n *\n * // Nested fragments\n * <Fragment>\n * <Fragment>\n * <div>Nested 1</div>\n * <div>Nested 2</div>\n * </Fragment>\n * <div>Third</div>\n * </Fragment>\n *\n * // Empty fragment (renders nothing)\n * <Fragment />\n * ```\n */\nexport function Fragment(props?: FragmentProps): AnyNode {\n // `<Fragment />` and `<Fragment>{null}</Fragment>` are legitimate:\n // they render nothing. Returning `null` here keeps the caller tree\n // valid and lets the template runtime drop the placeholder.\n if (!props || props.children == null) return null;\n\n // Client-side rendering: return children directly — the template\n // system handles arrays/signals/components on its own.\n return props.children as AnyNode;\n}\n\nFragment[FRAGMENT_COMPONENT] = true;\n\n/**\n * Check if a node is a Fragment component.\n *\n * @param node - Node to check.\n * @returns {boolean} True if node is a Fragment.\n */\nexport function isFragment(node: unknown): boolean {\n return !!node && !!node[FRAGMENT_COMPONENT];\n}\n","import { isFunction, isString, warn } from '@estjs/shared';\nimport { effect } from '@estjs/signals';\nimport { PORTAL_COMPONENT } from '../constants';\nimport { consumeTeleportAnchor, consumeTeleportBlock, isHydrating } from '../hydration';\nimport { onMount } from '../lifecycle';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n onCleanup,\n runWithScope,\n} from '../scope';\nimport { insert } from '../dom';\nimport type { AnyNode } from '../types';\n\nexport interface PortalProps {\n /** Children to render at the target location. */\n children?: AnyNode | AnyNode[];\n /**\n * Mount target — CSS selector string, `Element`, or reactive getter.\n * When the getter result changes, the Portal re-mounts at the new target.\n */\n target?: string | Element | (() => string | Element | null | undefined);\n /**\n * When truthy, children render inline at the call site instead of being teleported.\n * May be a static value or a reactive getter.\n */\n disabled?: boolean | (() => boolean);\n}\n\n/** Resolve `props.target` to an Element, handling string / Element / getter. */\nfunction resolveTarget(props: PortalProps): Element | null {\n const raw = isFunction(props.target) ? (props.target as () => unknown)() : props.target;\n if (raw == null) return null;\n if (isString(raw)) return document.querySelector(raw as string);\n return raw as Element;\n}\n\n/** Evaluate `props.disabled`, supporting both static booleans and getters. */\nfunction evalDisabled(props: PortalProps): boolean {\n return isFunction(props.disabled) ? !!(props.disabled as () => boolean)() : !!props.disabled;\n}\n\n/**\n * Portal — teleports children into a different DOM node.\n *\n * - `disabled=true` renders children inline at the call site.\n * - Otherwise children are teleported into `target`.\n * - Both `target` and `disabled` may be reactive; changes trigger re-mount.\n *\n * @returns A placeholder comment node that marks the call site.\n *\n * @example\n * ```tsx\n * <Portal target=\"#modal-root\" disabled={isMobile}>\n * <div>Modal content</div>\n * </Portal>\n * ```\n */\nexport function Portal(props: PortalProps): Comment {\n // Hydration: adopt SSR-emitted anchors + target block.\n if (isHydrating()) {\n const adopted = tryHydratePortal(props);\n if (adopted) return adopted;\n }\n\n const placeholder = document.createComment('portal');\n placeholder[PORTAL_COMPONENT] = true;\n\n const { children } = props;\n if (children == null) return placeholder;\n\n const ownerScope = getActiveScope();\n let innerScope: Scope | null = null;\n\n /**\n * Mount children into the given parent, inside a fresh inner scope\n * that inherits from the owning scope. This allows `insert()` effects\n * to be properly disposed on teardown.\n */\n const mountAt = (parent: Node, before?: Node): void => {\n innerScope = createScope(ownerScope);\n runWithScope(innerScope, () => {\n insert(parent, () => children, before);\n });\n };\n\n /**\n * Tear down the inner scope, removing all mounted children and their\n * reactive effects.\n */\n const teardown = (): void => {\n if (innerScope) {\n disposeScope(innerScope);\n innerScope = null;\n }\n };\n\n /**\n * Evaluate disabled/target and (re-)mount, tearing down the previous\n * mount first. Accepts pre-evaluated values to avoid redundant getter\n * invocations when called from within the tracking effect.\n */\n const apply = (disabled: boolean, target: Element | null): void => {\n teardown();\n\n if (disabled) {\n const parent = placeholder.parentNode;\n if (!parent) return;\n mountAt(parent, placeholder);\n return;\n }\n\n if (!target) {\n if (__DEV__) {\n warn(`[Portal] Target element not found: ${String(props.target)}`);\n }\n return;\n }\n mountAt(target);\n };\n\n // Track reactive deps immediately but defer DOM work until placeholder\n // is attached. On subsequent runs (reactive change) the effect runs\n // apply() directly with the freshly evaluated values — no redundant\n // double-evaluation.\n let mounted = false;\n\n const effectRunner = effect(() => {\n const disabled = evalDisabled(props);\n const target = disabled ? null : resolveTarget(props);\n\n if (mounted) {\n apply(disabled, target);\n }\n });\n\n onMount(() => {\n mounted = true;\n\n const disabled = evalDisabled(props);\n const target = disabled ? null : resolveTarget(props);\n\n // Try mounting synchronously — works when target is already in the document.\n if (disabled || target) {\n apply(disabled, target);\n return;\n }\n\n // Target may not be in the document yet (sibling elements mount bottom-up).\n // Defer to microtask — flushes before paint.\n queueMicrotask(() => {\n if (!placeholder.parentNode) return;\n apply(evalDisabled(props), resolveTarget(props));\n });\n });\n\n onCleanup(() => {\n effectRunner.stop();\n teardown();\n });\n\n return placeholder;\n}\n\nPortal[PORTAL_COMPONENT] = true;\n\n/**\n * Hydration adoption for Portal.\n *\n * Returns the SSR call-site anchor as placeholder on match, `null` on mismatch\n * (falls back to CSR mount path).\n */\nfunction tryHydratePortal(props: PortalProps): Comment | null {\n if (evalDisabled(props)) return null;\n\n const anchor = consumeTeleportAnchor();\n if (!anchor) {\n if (__DEV__) {\n warn('[Portal] hydration mismatch: no <!--teleport-anchor--> at call site.');\n }\n return null;\n }\n\n const target = resolveTarget(props);\n if (!target) {\n if (__DEV__) {\n warn(`[Portal] hydration mismatch: target not found: ${String(props.target)}`);\n }\n return null;\n }\n\n const block = consumeTeleportBlock(target);\n if (!block) {\n if (__DEV__) {\n warn(\n `[Portal] hydration mismatch: no <!--teleport-start--> in target ${String(props.target)}`,\n );\n }\n return null;\n }\n\n anchor[PORTAL_COMPONENT] = true;\n return anchor;\n}\n\n/**\n * Check if a node is a Portal component.\n *\n * @param node - Node to check.\n * @returns True if node is a Portal.\n */\nexport function isPortal(node: unknown): boolean {\n return !!node && !!node[PORTAL_COMPONENT];\n}\n","import { isArray, isBrowser, isFunction, isPromise, warn } from '@estjs/shared';\nimport { isComputed, isSignal } from '@estjs/signals';\nimport { insertNode, normalizeNode } from '../dom';\nimport { provide } from '../provide';\nimport { onDestroy } from '../lifecycle';\nimport { SUSPENSE_COMPONENT } from '../constants';\nimport type { AnyNode } from '../types';\n\n/** Clear all children from an element */\nfunction clearContainer(el: HTMLElement): void {\n while (el.firstChild) {\n el.removeChild(el.firstChild);\n }\n}\nexport function resolveNodeValue(value: unknown): unknown {\n let current = value;\n\n while (isFunction(current)) {\n current = (current as Function)();\n }\n\n if (isSignal(current) || isComputed(current)) {\n return resolveNodeValue((current as any).value);\n }\n\n return current;\n}\nexport interface SuspenseProps {\n /** The content to render. Can be a Promise for async loading. */\n children?: Node | Node[] | Promise<Node | Node[]>;\n /** Fallback content to display while children is loading (Promise pending). */\n fallback?: Node;\n /** Optional key for reconciliation. */\n key?: string;\n}\n\nexport const SuspenseContext = Symbol('SuspenseContext');\n\nexport interface SuspenseContextType {\n register: (promise: Promise<any>) => void;\n increment: () => void;\n decrement: () => void;\n}\n\n/**\n * Suspense component - handles async content with a fallback UI.\n *\n * @param props - Component props with children, fallback, and optional key.\n * @returns {AnyNode} Placeholder node or fallback content.\n *\n * @example\n * ```tsx\n * <Suspense fallback={<div>Loading...</div>}>\n * {asyncContent}\n * </Suspense>\n * ```\n */\nexport function Suspense(props: SuspenseProps): Node {\n // Check if we're in SSR mode (no DOM globals)\n if (!isBrowser()) {\n // In SSR, keep structure deterministic and never touch DOM APIs.\n // Suspense boundary renders fallback while async resources are unresolved.\n return props.fallback ?? ('' as unknown as Node);\n }\n // Create a container to manage content swapping\n const container = document.createElement('div');\n container.style.display = 'contents'; // Invisible wrapper\n\n // Track if component is still mounted (for async cleanup)\n let isMounted = true;\n let pendingCount = 0;\n let isShowingFallback = false;\n\n let resolvedChildren: AnyNode | AnyNode[] | null = null;\n\n /**\n * Materializes child.\n */\n const materializeChild = (value: AnyNode): AnyNode => {\n const current = resolveNodeValue(value);\n\n if (isArray(current)) {\n const nodes: AnyNode[] = [];\n for (const item of current as AnyNode[]) {\n const materialized = materializeChild(item);\n if (isArray(materialized)) {\n nodes.push(...(materialized as AnyNode[]));\n } else {\n nodes.push(materialized);\n }\n }\n return nodes as AnyNode;\n }\n\n return normalizeNode(current);\n };\n\n /**\n * Inserts a materialized child or child list into the container.\n */\n const insertMaterializedChild = (value: AnyNode) => {\n const normalized = materializeChild(value);\n const nodes = isArray(normalized) ? normalized : [normalized];\n\n for (const node of nodes) {\n if (node != null) {\n insertNode(container, node);\n }\n }\n };\n\n /**\n * Renders fallback content.\n */\n const renderFallbackContent = () => {\n clearContainer(container);\n\n if (props.fallback != null) {\n insertMaterializedChild(props.fallback);\n }\n };\n\n /**\n * Switches the boundary into its fallback view.\n */\n const showFallback = () => {\n if (isShowingFallback) return;\n isShowingFallback = true;\n renderFallbackContent();\n };\n\n /**\n * Restores the resolved children when the boundary can leave fallback mode.\n */\n const showChildren = () => {\n if (!isShowingFallback) return;\n\n // Check if we have something to show\n const hasContent = resolvedChildren || (props.children != null && !isPromise(props.children));\n\n if (!hasContent) {\n return;\n }\n\n isShowingFallback = false;\n\n clearContainer(container);\n\n if (resolvedChildren) {\n renderChildren(resolvedChildren);\n } else if (props.children != null && !isPromise(props.children)) {\n renderChildren(props.children);\n }\n };\n\n /**\n * Render children into the container.\n *\n * @param children - The children to render.\n * @returns {void}\n */\n const renderChildren = (children: AnyNode | AnyNode[]): void => {\n // Guard: don't render children if we should be showing fallback\n if (isShowingFallback) return;\n\n clearContainer(container);\n\n if (children == null) return;\n\n const childArray = isArray(children) ? children : [children];\n for (const child of childArray) {\n if (child != null) {\n insertMaterializedChild(child);\n }\n }\n\n // Resource registration may flip to fallback while children are mounting.\n if (isShowingFallback) {\n renderFallbackContent();\n }\n };\n\n // Context for resources to register themselves\n const suspenseContext: SuspenseContextType = {\n register: (promise: Promise<any>) => {\n pendingCount++;\n showFallback();\n\n promise\n .then(() => {\n if (!isMounted) return;\n pendingCount--;\n if (pendingCount === 0) {\n showChildren();\n }\n })\n .catch((error) => {\n if (__DEV__) {\n warn('[Suspense] Resource failed:', error);\n }\n if (!isMounted) return;\n pendingCount--;\n // For now, if error happens, we still try to show children (or maybe error boundary later)\n if (pendingCount === 0) {\n showChildren();\n }\n });\n },\n increment: () => {\n pendingCount++;\n showFallback();\n },\n decrement: () => {\n pendingCount = Math.max(0, pendingCount - 1);\n if (pendingCount === 0) {\n showChildren();\n }\n },\n };\n\n provide(SuspenseContext, suspenseContext);\n\n const children = props.children;\n\n // Initial render logic\n if (isPromise(children)) {\n // Async children - show fallback immediately, then resolve\n children\n .then((resolved) => {\n resolvedChildren = resolved;\n })\n .catch(() => {\n // Ignore error, handled by register\n });\n suspenseContext.register(children);\n } else if (children != null) {\n // Sync children - render immediately\n // If any child is a resource read, it will call register() synchronously during this render\n renderChildren(children);\n } else {\n // No children - show fallback if available\n showFallback();\n }\n\n onDestroy(() => {\n isMounted = false;\n pendingCount = 0;\n resolvedChildren = null;\n clearContainer(container);\n container.remove();\n });\n\n return container;\n}\n\nSuspense[SUSPENSE_COMPONENT] = true;\n\n/**\n * Check if a node is a Suspense component.\n *\n * @param node - Node to check.\n * @returns {boolean} True if node is a Suspense.\n */\nexport function isSuspense(node: unknown): boolean {\n return !!node && !!node[SUSPENSE_COMPONENT];\n}\n","import { type Signal, signal } from '@estjs/signals';\nimport { inject } from '../provide';\nimport { SuspenseContext } from './Suspense';\n\nexport type ResourceState = 'pending' | 'ready' | 'errored';\n\nexport interface Resource<T> {\n (): T | undefined;\n loading: Signal<boolean>;\n error: Signal<Error | null>;\n state: Signal<ResourceState>;\n}\n\nexport interface ResourceActions<T> {\n mutate: (value: T) => void;\n refetch: () => Promise<void>;\n}\n\nexport interface ResourceOptions<T> {\n initialValue?: T;\n}\n\n/**\n * Create a resource for async data fetching.\n * Inspired by SolidJS createResource.\n *\n * @param fetcher - Function that returns a Promise with the data.\n * @param options - Optional configuration.\n * @returns {[Resource<T>, ResourceActions<T>]} Tuple of [resource, actions].\n */\nexport function createResource<T>(\n fetcher: () => Promise<T>,\n options?: ResourceOptions<T>,\n): [Resource<T>, ResourceActions<T>] {\n // Internal state\n const value = signal<T | undefined>(options?.initialValue);\n const loading = signal<boolean>(true);\n const error = signal<Error | null>(null);\n const state = signal<ResourceState>('pending');\n\n let fetchId = 0;\n\n let currentPromise: Promise<void> | null = null;\n let suspenseRegistered = false;\n const suspenseContext = inject<any>(SuspenseContext, null);\n\n /**\n * Fetch function.\n */\n const fetch = async (): Promise<void> => {\n const currentFetchId = ++fetchId;\n loading.value = true;\n state.value = 'pending';\n error.value = null;\n suspenseRegistered = false;\n if (suspenseContext) {\n // Track pending fetches even when callers branch on loading/state before reading the resource.\n suspenseContext.increment();\n }\n\n try {\n const promise = fetcher();\n currentPromise = promise as any; // Track original promise for Suspense\n promise.catch(() => {}); // Prevent unhandled rejection\n const result = await promise;\n\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n value.value = result;\n state.value = 'ready';\n loading.value = false;\n }\n } catch (error_) {\n // Only update if this is still the latest fetch\n if (currentFetchId === fetchId) {\n error.value = error_ instanceof Error ? error_ : new Error(String(error_));\n state.value = 'errored';\n loading.value = false;\n }\n } finally {\n if (suspenseContext) {\n suspenseContext.decrement();\n }\n }\n };\n\n // Start initial fetch\n fetch();\n\n // Resource accessor function\n const resource = (() => {\n // Register with Suspense only once per fetch cycle\n if (!suspenseRegistered && loading.value && currentPromise && suspenseContext) {\n suspenseRegistered = true;\n // @ts-ignore\n suspenseContext.register(currentPromise);\n }\n return value.value;\n }) as Resource<T>;\n resource.loading = loading;\n resource.error = error;\n resource.state = state;\n\n // Actions\n const actions: ResourceActions<T> = {\n mutate: (newValue: T) => {\n value.value = newValue;\n state.value = 'ready';\n loading.value = false;\n error.value = null;\n },\n refetch: async () => {\n await fetch();\n },\n };\n\n return [resource, actions];\n}\n","import { isFunction } from '@estjs/shared';\nimport { inject } from '../provide';\nimport { onDestroy } from '../lifecycle';\nimport { onCleanup } from '../scope';\nimport { Component } from '../component';\nimport { SuspenseContext, type SuspenseContextType } from './Suspense';\nimport type { AnyNode, ComponentFn, ComponentProps } from '../types';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface AsyncComponentOptions {\n /**\n * Component to render while the async component is loading.\n * Only shown after `delay` ms has elapsed (prevents flash of loading state).\n */\n loading?: ComponentFn;\n\n /**\n * Component to render when the async component fails to load.\n * Receives `{ error, retry }` as props.\n */\n error?: ComponentFn<{ error: Error; retry: () => void }>;\n\n /**\n * Delay in ms before showing the `loading` component (default: 200).\n */\n delay?: number;\n\n /**\n * Timeout in ms. If loading exceeds this, the error component is shown.\n */\n timeout?: number;\n\n /**\n * SSR rendering strategy (default: `'blocking'`).\n *\n * - `'blocking'` — Pre-calls the loader at definition time. If the module\n * resolves before the component body runs (e.g. pre-loaded via\n * `renderToStringAsync`), the real component is inlined in the HTML.\n * - `'client-only'` — Renders `null` on the server; loads only in browser.\n */\n ssr?: 'blocking' | 'client-only';\n\n /**\n * Called when loading fails. Useful for logging or error tracking.\n */\n onError?: (error: Error, retry: () => void) => void;\n}\n\ntype LoaderResult<P> = { default: ComponentFn<P> } | ComponentFn<P>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Resolves the default export from a module.\n *\n * @param mod - The module result to resolve.\n * @returns {ComponentFn<P>} The resolved component function.\n */\nfunction resolveModule<P>(mod: LoaderResult<P>): ComponentFn<P> {\n return isFunction(mod) ? (mod as ComponentFn<P>) : (mod as { default: ComponentFn<P> }).default;\n}\n\n/**\n * Mount a ComponentFn into a container element, returning the Component instance.\n *\n * @param el - The element to render into.\n * @param fn - The component function.\n * @param props - The component props.\n * @returns The component instance.\n */\nfunction renderInto<P extends ComponentProps>(\n el: HTMLElement,\n fn: ComponentFn<P>,\n props?: P,\n): Component<P> {\n const comp = new Component(fn, props);\n comp.mount(el);\n return comp;\n}\n\n// ============================================================================\n// defineAsyncComponent\n// ============================================================================\n\n/**\n * Define an async (lazy-loaded) component.\n *\n * Compatible with client, SSR, and SSG. Integrates with `<Suspense>` via\n * `SuspenseContext` when rendered inside a Suspense boundary.\n *\n *\n * @param loader - The async loader function.\n * @param options - Configuration options.\n * @returns {ComponentFn<P>} The async component wrapper function.\n *\n * @example\n * ```tsx\n * // Simple\n * const Chart = defineAsyncComponent(() => import('./Chart'));\n *\n * // With options\n * const Chart = defineAsyncComponent(\n * () => import('./Chart'),\n * {\n * loading: () => <Spinner />,\n * error: ({ error, retry }) => (\n * <div>\n * <p>{error.message}</p>\n * <button onClick={retry}>Retry</button>\n * </div>\n * ),\n * delay: 200,\n * timeout: 10_000,\n * }\n * );\n *\n * // Works standalone or inside Suspense\n * function App() {\n * return (\n * <Suspense fallback={<div>Loading…</div>}>\n * <Chart data={data} />\n * </Suspense>\n * );\n * }\n * ```\n */\nexport function defineAsyncComponent<P extends ComponentProps = ComponentProps>(\n loader: () => Promise<LoaderResult<P>>,\n options: AsyncComponentOptions = {},\n): ComponentFn<P> {\n const { delay = 200, timeout, ssr = 'blocking', onError } = options;\n\n // ── Server-side rendering ─────────────────────────────────────────────────\n if (typeof window === 'undefined') {\n if (ssr === 'client-only') {\n /**\n * Returns the async component placeholder output.\n */\n const placeholder: ComponentFn<P> = () => '' as unknown as AnyNode;\n (placeholder as any).__asyncLoader = loader;\n (placeholder as any).__asyncResolved = () => null;\n return placeholder;\n }\n\n // 'blocking': pre-call the loader so that if the module is already cached\n // the component is available synchronously when the component body runs.\n let ssrResolved: ComponentFn<P> | null = null;\n let ssrPromise: Promise<void> | null = null;\n\n /**\n * SSR loader matches the client-side signature `() => Promise<void>`\n * so external consumers can treat `__asyncLoader` uniformly across\n * environments.\n */\n const ssrLoad = (): Promise<void> => {\n if (ssrPromise) return ssrPromise;\n ssrPromise = loader()\n .then((mod) => {\n ssrResolved = resolveModule(mod);\n })\n .catch(() => {});\n return ssrPromise;\n };\n\n // Kick off loading eagerly so that pre-resolved modules are inlined.\n ssrLoad();\n\n /**\n * Renders the server-side async wrapper.\n */\n const ssrWrapper: ComponentFn<P> = (props: P) => {\n if (ssrResolved) {\n return ssrResolved(props);\n }\n\n return '' as unknown as AnyNode;\n };\n\n (ssrWrapper as any).__asyncLoader = ssrLoad;\n (ssrWrapper as any).__asyncResolved = () => ssrResolved;\n\n return ssrWrapper;\n }\n\n // ── Client-side ──────────────────────────────────────────────────────────\n //\n // Module-level cache: all instances share one loader invocation.\n\n let cachedComponent: ComponentFn<P> | null = null;\n let cachedError: Error | null = null;\n type CacheStatus = 'pending' | 'resolved' | 'errored';\n let cachedStatus: CacheStatus = 'pending';\n let loadPromise: Promise<void> | null = null;\n\n /**\n * Loads the requested resource.\n */\n function load(): Promise<void> {\n if (loadPromise) return loadPromise;\n\n loadPromise = loader()\n .then((mod) => {\n cachedComponent = resolveModule(mod);\n cachedStatus = 'resolved';\n })\n .catch((error) => {\n cachedError = error instanceof Error ? error : new Error(String(error));\n cachedStatus = 'errored';\n loadPromise = null; // allow retry\n });\n\n return loadPromise;\n }\n\n // Kick off loading eagerly\n load();\n\n // ── Wrapper component ────────────────────────────────────────────────────\n //\n // Mirrors the Suspense pattern: return a plain DOM element (display:contents)\n // and perform imperative DOM swaps when async state changes.\n // This avoids issues with the Component class calling the inner render\n // function immediately instead of tracking it reactively.\n\n /**\n * Renders the async component wrapper.\n */\n function AsyncWrapper(props: P): AnyNode {\n // Fast path: already resolved\n if (cachedStatus === 'resolved' && cachedComponent) {\n const el = document.createElement('div');\n el.style.display = 'contents';\n const comp = renderInto(el, cachedComponent, props);\n onCleanup(() => comp.destroy());\n return el;\n }\n\n // Fast path: already errored\n if (cachedStatus === 'errored' && cachedError) {\n const el = document.createElement('div');\n el.style.display = 'contents';\n if (options.error) {\n let alive = true;\n let currentComp: Component | null = null;\n\n const swap = (fn: ComponentFn<any>, swapProps?: any) => {\n if (!alive) return;\n currentComp?.destroy();\n currentComp = renderInto(el, fn, swapProps);\n };\n\n const retry = () => {\n loadPromise = null;\n cachedStatus = 'pending';\n cachedError = null;\n if (options.loading) swap(options.loading);\n load().then(() => {\n if (!alive) return;\n if (cachedStatus === 'resolved' && cachedComponent) {\n swap(cachedComponent, props);\n } else if (cachedStatus === 'errored' && cachedError) {\n if (options.error) swap(options.error, { error: cachedError!, retry });\n }\n });\n };\n\n swap(options.error, { error: cachedError, retry });\n\n onDestroy(() => {\n alive = false;\n currentComp?.destroy();\n currentComp = null;\n });\n }\n return el;\n }\n\n // ─ Pending state ──────────────────────────────────────────────────────\n const container = document.createElement('div');\n container.style.display = 'contents';\n\n let alive = true;\n let currentComp: Component | null = null;\n let delayTimer: ReturnType<typeof setTimeout> | null = null;\n let timeoutTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * Swaps the current rendered component.\n */\n const swap = (fn: ComponentFn<any>, swapProps?: any) => {\n if (!alive) return;\n currentComp?.destroy();\n currentComp = renderInto(container, fn, swapProps);\n };\n\n /**\n * Creates a retry handler for the current props.\n */\n const retryWith =\n (retryProps: P): (() => void) =>\n () => {\n loadPromise = null;\n cachedStatus = 'pending';\n cachedError = null;\n if (options.loading) swap(options.loading);\n load().then(() => {\n if (cachedStatus === 'resolved' && cachedComponent) {\n swap(cachedComponent, retryProps);\n } else if (cachedStatus === 'errored' && cachedError) {\n if (options.error) {\n swap(options.error, {\n error: cachedError,\n retry: retryWith(retryProps),\n });\n }\n }\n });\n };\n\n onDestroy(() => {\n alive = false;\n currentComp?.destroy();\n currentComp = null;\n if (delayTimer != null) clearTimeout(delayTimer);\n if (timeoutTimer != null) clearTimeout(timeoutTimer);\n });\n\n // Inject Suspense context (undefined when not inside a Suspense boundary)\n const suspenseCtx = inject<SuspenseContextType>(SuspenseContext) ?? null;\n\n /**\n * Displays the resolved component.\n */\n const showResolved = (compFn: ComponentFn<P>) => swap(compFn, props);\n\n /**\n * Displays the error state.\n */\n const showError = (err: Error) => {\n if (options.error) swap(options.error, { error: err, retry: retryWith(props) });\n };\n\n /**\n * Displays the loading state.\n */\n const showLoading = () => {\n if (options.loading) swap(options.loading);\n };\n\n const instancePromise = load().then(() => {\n if (!alive) return;\n if (cachedStatus === 'resolved' && cachedComponent) {\n showResolved(cachedComponent);\n } else if (cachedStatus === 'errored' && cachedError) {\n showError(cachedError);\n if (onError) onError(cachedError, retryWith(props));\n }\n if (delayTimer != null) clearTimeout(delayTimer);\n if (timeoutTimer != null) clearTimeout(timeoutTimer);\n });\n\n // Notify Suspense boundary about this pending async work\n if (suspenseCtx) {\n suspenseCtx.register(instancePromise);\n }\n\n // Delay before showing loading indicator\n if (delay > 0) {\n delayTimer = setTimeout(() => {\n if (alive && cachedStatus === 'pending') {\n showLoading();\n }\n }, delay);\n } else if (options.loading) {\n showLoading();\n }\n\n // Optional timeout\n if (timeout != null) {\n timeoutTimer = setTimeout(() => {\n if (alive && cachedStatus === 'pending') {\n const err = new Error(`[defineAsyncComponent] Timeout after ${timeout}ms`);\n cachedError = err;\n cachedStatus = 'errored';\n showError(err);\n if (onError) onError(err, retryWith(props));\n }\n }, timeout);\n }\n\n return container;\n }\n\n (AsyncWrapper as any).__asyncLoader = load;\n (AsyncWrapper as any).__asyncResolved = () => cachedComponent;\n\n return AsyncWrapper;\n}\n\n// ============================================================================\n// Utilities\n// ============================================================================\n\n/**\n * Returns true if a function was created by `defineAsyncComponent`.\n *\n * @param fn - The function to check.\n * @returns {boolean} True if it is an async component.\n */\nexport function isAsyncComponent(fn: unknown): boolean {\n return isFunction(fn) && !!(fn as any).__asyncLoader;\n}\n","import { type Signal, effect, isSignal } from '@estjs/signals';\nimport { isFunction } from '@estjs/shared';\nimport {\n type Scope,\n createScope,\n disposeScope,\n getActiveScope,\n onCleanup,\n runWithScope,\n} from '../scope';\nimport { FOR_COMPONENT } from '../constants';\nimport { normalizeNode } from '../dom';\nimport { getSequence } from '../reconcile';\nimport type { AnyNode } from '../types';\n\nexport interface ForProps<T> {\n each: T[] | Signal<T[]> | (() => T[]);\n children: (item: T, index: number) => AnyNode;\n key?: (item: T) => unknown;\n fallback?: () => AnyNode;\n}\n\ninterface ItemEntry {\n key: unknown;\n item: unknown;\n nodes: Node[];\n scope: Scope; // Track scope for cleanup\n}\n\n/**\n * Optimized For Component\n * - Uses createDetachedScope to avoid parent.children Set overhead (SolidJS style)\n * - Uses DocumentFragment batching for mass creation\n * - Inlines scope switching for performance\n */\nexport function For<T>(props: ForProps<T>): Node {\n const fragment = document.createDocumentFragment();\n const marker = document.createComment('');\n fragment.appendChild(marker);\n\n let entries: ItemEntry[] = [];\n let fallbackNodes: Node[] = [];\n\n const keyFn = props.key;\n const renderFn = props.children;\n\n const getList = (): T[] => {\n const input = props.each;\n if (isSignal(input)) return (input as Signal<T[]>).value ?? [];\n if (isFunction(input)) return (input as () => T[])() ?? [];\n return (input as T[]) ?? [];\n };\n\n const getKey = (item: T): unknown => (keyFn ? keyFn(item) : item);\n\n const normalizeNodes = (value: AnyNode): Node[] => {\n if (Array.isArray(value)) {\n const nodes: Node[] = [];\n for (const item of value) {\n nodes.push(...normalizeNodes(item as AnyNode));\n }\n return nodes;\n }\n return [normalizeNode(value)];\n };\n\n const mountValue = (value: AnyNode, parent: Node, before: Node | null): Node[] => {\n const nodes = normalizeNodes(value);\n for (const node of nodes) {\n if (before) {\n parent.insertBefore(node, before);\n } else {\n parent.appendChild(node);\n }\n }\n return nodes;\n };\n\n const mountFallback = (parent: Node, before: Node | null) => {\n if (!props.fallback) return;\n const nodes = mountValue(props.fallback(), parent, before);\n fallbackNodes = nodes;\n };\n\n const clearFallback = () => {\n for (const node of fallbackNodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n fallbackNodes = [];\n };\n\n /**\n * Render item with detached scope.\n */\n const renderItem = (item: T, index: number, parent: Node, before: Node | null): ItemEntry => {\n const parentScope = getActiveScope();\n const scope = createScope(parentScope);\n let mountedNodes: Node[] = [];\n runWithScope(scope, () => {\n mountedNodes = mountValue(renderFn(item, index), parent, before);\n });\n\n return { key: getKey(item), item, nodes: mountedNodes, scope };\n };\n\n const disposeItem = (entry: ItemEntry) => {\n disposeScope(entry.scope);\n for (const node of entry.nodes) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n }\n };\n\n const effectRunner = effect(() => {\n const newItems = getList();\n\n const parent = marker.parentNode;\n\n // Initial mount (parent is null because fragment is not attached yet)\n if (!parent) {\n if (newItems.length === 0) {\n mountFallback(fragment, marker);\n } else {\n entries = new Array(newItems.length);\n let idx = 0;\n for (const newItem of newItems) {\n entries[idx] = renderItem(newItem, idx, fragment, marker);\n idx++;\n }\n }\n // Skip reconcile on initial mount — entries are already created\n return;\n }\n\n // Before the fragment is attached, `marker.parentNode` is the fragment\n // itself; afterwards it is the real host (e.g. the container the user\n // mounted into). All reconciliation must target the live parent, or\n // `insertBefore(node, marker)` throws NotFoundError because `marker`\n // already moved out of the fragment on the first flush.\n reconcile(parent, newItems);\n });\n\n /**\n * Reconciles the rendered entries against the latest item list.\n *\n * @param parent - The parent node.\n * @param newItems - The new items list.\n * @returns {void}\n */\n function reconcile(parent: Node, newItems: T[]): void {\n const oldLen = entries.length;\n const newLen = newItems.length;\n\n // ===== FAST PATH 1: Clear all =====\n if (newLen === 0) {\n for (let i = 0; i < oldLen; i++) {\n disposeItem(entries[i]);\n }\n entries = [];\n\n if (props.fallback && fallbackNodes.length === 0) {\n mountFallback(parent, marker);\n }\n return;\n }\n\n // ===== FAST PATH 2: Create all (from empty/fallback) =====\n if (oldLen === 0 || fallbackNodes.length > 0) {\n if (fallbackNodes.length > 0) {\n clearFallback();\n }\n\n entries = new Array(newLen);\n\n // Batch creation in fragment\n const batchFragment = document.createDocumentFragment();\n\n for (let i = 0; i < newLen; i++) {\n // Render to batchFragment, append to end (before=null)\n entries[i] = renderItem(newItems[i], i, batchFragment, null);\n }\n\n parent.insertBefore(batchFragment, marker);\n return;\n }\n\n // ===== Keyed reconciliation =====\n //\n // Each `oldKeyMap` value preserves the entry together with its original\n // index. The index is the fuel for the LIS-based move minimisation\n // further down: by mapping each new position to an old position we can\n // find the longest slice that is already in order and leave it alone.\n const oldKeyMap = new Map<unknown, Array<[ItemEntry, number]>>();\n for (let i = 0; i < oldLen; i++) {\n const entry = entries[i];\n const list = oldKeyMap.get(entry.key);\n const pair: [ItemEntry, number] = [entry, i];\n if (list) list.push(pair);\n else oldKeyMap.set(entry.key, [pair]);\n }\n\n const newEntries: ItemEntry[] = new Array(newLen);\n const toRemove: ItemEntry[] = [];\n\n // Batch new nodes in a fragment so multiple creations turn into a\n // single native DOM insertion. Created lazily — only when a fresh\n // item is actually rendered so we avoid the allocation when every\n // entry is reused.\n let batchFragment: DocumentFragment | null = null;\n\n // `newIndexToOldIndex[i] === 0` → newEntries[i] is freshly created.\n // `newIndexToOldIndex[i] === k + 1` → reused from `entries[k]`.\n const newIndexToOldIndex = new Int32Array(newLen);\n let moved = false;\n let maxOldSeen = 0;\n\n // Pre-compute keys for all new items to avoid redundant getKey calls\n const newKeys = new Array<unknown>(newLen);\n for (let i = 0; i < newLen; i++) {\n newKeys[i] = getKey(newItems[i]);\n }\n\n for (let i = 0; i < newLen; i++) {\n const item = newItems[i];\n const key = newKeys[i];\n const oldList = oldKeyMap.get(key);\n\n if (oldList && oldList.length > 0) {\n const [reused, oldIndex] = oldList.shift()!;\n if (Object.is(reused.item, item)) {\n reused.item = item;\n newEntries[i] = reused;\n newIndexToOldIndex[i] = oldIndex + 1;\n if (oldIndex < maxOldSeen) moved = true;\n else maxOldSeen = oldIndex;\n } else {\n if (!batchFragment) batchFragment = document.createDocumentFragment();\n disposeItem(reused);\n newEntries[i] = renderItem(item, i, batchFragment, null);\n }\n } else {\n if (!batchFragment) batchFragment = document.createDocumentFragment();\n newEntries[i] = renderItem(item, i, batchFragment, null);\n // newIndexToOldIndex[i] remains 0 (fresh entry).\n }\n }\n\n for (const list of oldKeyMap.values()) {\n for (const [entry] of list) toRemove.push(entry);\n }\n for (const entry of toRemove) disposeItem(entry);\n\n // ===== Position correction with LIS =====\n // We walk the new array right-to-left using `marker` as the initial\n // anchor, which lets us use `insertBefore(node, nextNode)` uniformly.\n const lis = moved ? getSequence(newIndexToOldIndex) : [];\n let lisCursor = lis.length - 1;\n let nextNode: Node = marker;\n\n for (let i = newLen - 1; i >= 0; i--) {\n const entry = newEntries[i];\n const nodes = entry.nodes;\n const isFresh = newIndexToOldIndex[i] === 0;\n const inLis = !isFresh && moved && lisCursor >= 0 && i === lis[lisCursor];\n\n if (inLis) {\n // Stable skeleton — leave every node untouched, but still update\n // `nextNode` so the next iteration has the correct anchor.\n lisCursor--;\n for (let j = nodes.length - 1; j >= 0; j--) nextNode = nodes[j];\n continue;\n }\n\n // Fresh entry OR reused entry that is out of place → (re)insert each\n // node. The nextSibling guard keeps us from redundant writes for\n // multi-node rows whose internal order is already correct.\n for (let j = nodes.length - 1; j >= 0; j--) {\n const node = nodes[j];\n if (node.nextSibling !== nextNode) {\n parent.insertBefore(node, nextNode);\n }\n nextNode = node;\n }\n }\n\n entries = newEntries;\n }\n\n onCleanup(() => {\n effectRunner.stop();\n for (const entry of entries) {\n disposeItem(entry);\n }\n entries = [];\n clearFallback();\n if (marker.parentNode) {\n marker.parentNode.removeChild(marker);\n }\n });\n\n return fragment;\n}\n\nFor[FOR_COMPONENT] = true;\n\nexport function isFor(node: unknown): boolean {\n return !!node && !!(node as Record<symbol, boolean>)[FOR_COMPONENT];\n}\n"]}
|