@askrjs/askr 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +8 -5
  2. package/dist/chunk-64C7W2AE.js +43 -0
  3. package/dist/chunk-64C7W2AE.js.map +1 -0
  4. package/dist/chunk-6FLMH4EL.js +124 -0
  5. package/dist/chunk-6FLMH4EL.js.map +1 -0
  6. package/dist/{chunk-JHOGWTAW.js → chunk-FJUXFA72.js} +2 -2
  7. package/dist/chunk-FJUXFA72.js.map +1 -0
  8. package/dist/{chunk-H3NSVHA7.js → chunk-VRAEBIJ3.js} +7 -5
  9. package/dist/chunk-VRAEBIJ3.js.map +1 -0
  10. package/dist/chunk-WTFWRSHB.js +98 -0
  11. package/dist/chunk-WTFWRSHB.js.map +1 -0
  12. package/dist/chunk-XHKZGJE3.js +2907 -0
  13. package/dist/chunk-XHKZGJE3.js.map +1 -0
  14. package/dist/chunk-Z5ZSTLYF.js +420 -0
  15. package/dist/chunk-Z5ZSTLYF.js.map +1 -0
  16. package/dist/fx/index.cjs +1193 -0
  17. package/dist/fx/index.cjs.map +1 -0
  18. package/dist/fx/index.d.cts +186 -0
  19. package/dist/fx/index.d.ts +186 -0
  20. package/dist/fx/index.js +418 -0
  21. package/dist/fx/index.js.map +1 -0
  22. package/dist/index.cjs +1369 -2525
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +74 -407
  25. package/dist/index.d.ts +74 -407
  26. package/dist/index.js +63 -803
  27. package/dist/index.js.map +1 -1
  28. package/dist/jsx/jsx-dev-runtime.cjs +1 -1
  29. package/dist/jsx/jsx-dev-runtime.cjs.map +1 -1
  30. package/dist/jsx/jsx-dev-runtime.d.cts +3 -2
  31. package/dist/jsx/jsx-dev-runtime.d.ts +3 -2
  32. package/dist/jsx/jsx-dev-runtime.js +1 -1
  33. package/dist/jsx/jsx-runtime.d.cts +2 -1
  34. package/dist/jsx/jsx-runtime.d.ts +2 -1
  35. package/dist/jsx/jsx-runtime.js +1 -1
  36. package/dist/{types-DLTViI21.d.cts → jsx-AzPM8gMS.d.cts} +6 -21
  37. package/dist/{types-DLTViI21.d.ts → jsx-AzPM8gMS.d.ts} +6 -21
  38. package/dist/{navigate-CZEUXFPM.js → navigate-LUVYHYZZ.js} +5 -4
  39. package/dist/resources/index.cjs +1200 -0
  40. package/dist/resources/index.cjs.map +1 -0
  41. package/dist/resources/index.d.cts +21 -0
  42. package/dist/resources/index.d.ts +21 -0
  43. package/dist/resources/index.js +278 -0
  44. package/dist/resources/index.js.map +1 -0
  45. package/dist/{route-USEXGOBT.js → route-BCND6MPK.js} +4 -3
  46. package/dist/{chunk-2ONGHQ7Z.js → router/index.cjs} +775 -643
  47. package/dist/router/index.cjs.map +1 -0
  48. package/dist/router/index.d.cts +64 -0
  49. package/dist/router/index.d.ts +64 -0
  50. package/dist/router/index.js +49 -0
  51. package/dist/router/index.js.map +1 -0
  52. package/dist/router-DaGtH1Sq.d.cts +36 -0
  53. package/dist/router-DaGtH1Sq.d.ts +36 -0
  54. package/dist/ssr/index.cjs +4059 -0
  55. package/dist/ssr/index.cjs.map +1 -0
  56. package/dist/ssr/index.d.cts +123 -0
  57. package/dist/ssr/index.d.ts +123 -0
  58. package/dist/{chunk-OFW6DFBM.js → ssr/index.js} +202 -252
  59. package/dist/ssr/index.js.map +1 -0
  60. package/dist/types-CZ5sWur5.d.cts +23 -0
  61. package/dist/types-CZHOAiC1.d.ts +23 -0
  62. package/package.json +19 -6
  63. package/src/jsx/types.ts +4 -17
  64. package/dist/chunk-2ONGHQ7Z.js.map +0 -1
  65. package/dist/chunk-H3NSVHA7.js.map +0 -1
  66. package/dist/chunk-JHOGWTAW.js.map +0 -1
  67. package/dist/chunk-OFW6DFBM.js.map +0 -1
  68. package/dist/ssr-QJ5NTQR6.js +0 -28
  69. package/dist/ssr-QJ5NTQR6.js.map +0 -1
  70. /package/dist/{navigate-CZEUXFPM.js.map → navigate-LUVYHYZZ.js.map} +0 -0
  71. /package/dist/{route-USEXGOBT.js.map → route-BCND6MPK.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/route.ts","../src/router/match.ts","../src/dev/invariant.ts","../src/dev/logger.ts","../src/runtime/scheduler.ts","../src/runtime/context.ts","../src/renderer/diag/index.ts","../src/runtime/dev-namespace.ts","../src/runtime/fastlane-shared.ts","../src/renderer/types.ts","../src/renderer/cleanup.ts","../src/renderer/utils.ts","../src/renderer/keyed.ts","../src/renderer/dom.ts","../src/renderer/fastpath.ts","../src/renderer/reconcile.ts","../src/renderer/evaluate.ts","../src/renderer/index.ts","../src/runtime/component.ts"],"sourcesContent":["/**\n * Route definition and matching\n * Supports dynamic route registration for micro frontends\n *\n * Optimization: Index by depth but maintain insertion order within each depth\n */\n\nimport { match as matchPath } from './match';\nimport { getCurrentComponentInstance } from '../runtime/component';\n\nexport interface RouteHandler {\n (params: Record<string, string>, context?: { signal: AbortSignal }): unknown;\n}\n\nexport interface Route {\n path: string;\n handler: RouteHandler;\n namespace?: string;\n}\n\nexport interface ResolvedRoute {\n handler: RouteHandler;\n params: Record<string, string>;\n}\n\nconst routes: Route[] = [];\nconst namespaces = new Set<string>();\n\n// Route index by depth - maintains insertion order\nconst routesByDepth = new Map<number, Route[]>();\n\n/**\n * Parse route path depth\n */\nfunction getDepth(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n return normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n}\n\n/**\n * Calculate route specificity for priority matching\n * Higher score = more specific\n * - Literal segments: 3 points each\n * - Parameter segments ({id}): 2 points each\n * - Wildcard segments (*): 1 point each\n * - Catch-all (/*): 0 points\n */\nfunction getSpecificity(path: string): number {\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n\n // Special case: catch-all pattern\n if (normalized === '/*') {\n return 0;\n }\n\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) {\n score += 2; // Parameter\n } else if (segment === '*') {\n score += 1; // Wildcard\n } else {\n score += 3; // Literal\n }\n }\n\n return score;\n}\n\n/**\n * RouteMatch, RouteQuery, RouteSnapshot\n * These describe the read-only snapshot returned by the render-time route() accessor\n */\nexport interface RouteMatch {\n path: string;\n params: Readonly<Record<string, string>>;\n name?: string;\n namespace?: string;\n}\n\nexport interface RouteQuery {\n get(key: string): string | null;\n getAll(key: string): string[];\n has(key: string): boolean;\n toJSON(): Record<string, string | string[]>;\n}\n\nexport interface RouteSnapshot {\n path: string;\n params: Readonly<Record<string, string>>;\n query: Readonly<RouteQuery>;\n hash: string | null;\n\n name?: string;\n namespace?: string;\n matches: readonly RouteMatch[];\n}\n\n// SSR helper: when rendering on the server, callers may set a location so that\n// render-time route() returns deterministic server values that match client\n// hydration. This is deliberately an opt-in escape for SSR and tests.\nlet serverLocation: string | null = null;\n\nexport function setServerLocation(url: string | null): void {\n serverLocation = url;\n}\n\n// Helper: parse a URL string into components\nfunction parseLocation(url: string) {\n try {\n const u = new URL(url, 'http://localhost');\n return { pathname: u.pathname, search: u.search, hash: u.hash };\n } catch {\n return { pathname: '/', search: '', hash: '' };\n }\n}\n\n// Deep freeze utility for small objects\nfunction deepFreeze<T>(obj: T): T {\n if (obj && typeof obj === 'object' && !Object.isFrozen(obj)) {\n Object.freeze(obj as Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as Record<string, unknown>)[key];\n if (value && typeof value === 'object') deepFreeze(value);\n }\n }\n return obj;\n}\n\n// Build an immutable query helper from a search string\nfunction makeQuery(search: string): RouteQuery {\n const usp = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n for (const [k, v] of usp.entries()) {\n const existing = mapping.get(k);\n if (existing) existing.push(v);\n else mapping.set(k, [v]);\n }\n\n const obj: RouteQuery = {\n get(key: string) {\n const arr = mapping.get(key);\n return arr ? arr[0] : null;\n },\n getAll(key: string) {\n const arr = mapping.get(key);\n return arr ? [...arr] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const out: Record<string, string | string[]> = {};\n for (const [k, arr] of mapping.entries()) {\n out[k] = arr.length > 1 ? [...arr] : arr[0];\n }\n return out;\n },\n };\n\n return deepFreeze(obj);\n}\n\n// Compute matches by scanning registered routes (public API: getRoutes)\nfunction computeMatches(pathname: string): RouteMatch[] {\n const routesList = getRoutes();\n const matches: Array<{\n pattern: string;\n params: Record<string, string>;\n name?: string;\n namespace?: string;\n specificity: number;\n }> = [];\n\n function getSpecificity(path: string) {\n // Reuse same heuristic as above\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n if (normalized === '/*') return 0;\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) score += 2;\n else if (segment === '*') score += 1;\n else score += 3;\n }\n return score;\n }\n\n for (const r of routesList) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n matches.push({\n pattern: r.path,\n params: result.params,\n name: (r as { name?: string }).name,\n namespace: r.namespace,\n specificity: getSpecificity(r.path),\n });\n }\n }\n\n matches.sort((a, b) => b.specificity - a.specificity);\n\n return matches.map((m) => ({\n path: m.pattern,\n params: deepFreeze({ ...m.params }),\n name: m.name,\n namespace: m.namespace,\n }));\n}\n\n/**\n * Dual-purpose `route` function:\n * - route() → returns a read-only, deeply frozen RouteSnapshot (render-time)\n * - route(path, handler, namespace?) → registers a route handler (existing semantics)\n */\n// Prevent runtime registrations after the app has started\nlet registrationLocked = false;\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\n// Internal test helpers\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\nexport function route(): RouteSnapshot;\nexport function route(\n path: string,\n handler?: RouteHandler,\n namespace?: string\n): void;\nexport function route(\n path?: string,\n handler?: RouteHandler,\n namespace?: string\n): void | RouteSnapshot {\n // If called with no args, act as render-time accessor\n if (typeof path === 'undefined') {\n // Access the current component instance to ensure route() is only\n // called during render.\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'route() can only be called during component render execution. ' +\n 'Call route() from inside your component function.'\n );\n }\n\n // Determine location source: client window if present; otherwise SSR override\n let pathname = '/';\n let search = '';\n let hash = '';\n\n if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const params = deepFreeze({\n ...((instance.props as Record<string, string>) || {}),\n });\n const query = makeQuery(search);\n const matches = computeMatches(pathname);\n\n const snapshot: RouteSnapshot = Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n\n return snapshot;\n }\n\n // Disallow route registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n // Disallow registrations after app startup\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. Register routes at module load time before calling createIsland().'\n );\n }\n\n // Otherwise register a route (backwards compatible behavior)\n if (typeof handler !== 'function') {\n throw new Error(\n 'route(path, handler) requires a function handler that returns a VNode (e.g. () => <Page />). ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n const routeObj: Route = { path, handler: handler as RouteHandler, namespace };\n routes.push(routeObj);\n\n // Index by depth (maintains insertion order within depth)\n const depth = getDepth(path);\n\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n\n depthRoutes.push(routeObj);\n\n if (namespace) {\n namespaces.add(namespace);\n }\n}\n\n/**\n * Get all registered routes\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/**\n * Get routes for a specific namespace\n */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/**\n * Unload all routes from a namespace (for MFE unmounting)\n */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n // Remove from main array\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n // Remove from depth index\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) {\n depthRoutes.splice(idx, 1);\n }\n }\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/**\n * Clear all registered routes (mainly for testing)\n */\nexport function clearRoutes(): void {\n routes.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n}\n\n/**\n * RouteDescriptor type — used by `registerRoute` for nested descriptors.\n *\n * Note: `registerRouteTree` helper was removed; prefer explicit `route()` registrations.\n */\nexport type RouteDescriptor = {\n path: string;\n handler?: RouteHandler | unknown;\n children?: RouteDescriptor[];\n _isDescriptor?: true;\n};\n\n// `registerRouteTree` was removed — register explicit absolute paths with `route(path, handler)` instead.\n// If you need a helper to register descriptor trees, add a small wrapper in userland that\n// calls `route()` recursively.\n\n// Helper: normalize common handler shapes\n// NOTE: Only function handlers are accepted — passing raw JSX/VNodes at register\n// time is not allowed. This keeps registration data-only and avoids surprising\n// semantics between module-load-time and render-time.\nfunction normalizeHandler(handler: unknown): RouteHandler | undefined {\n if (handler == null) return undefined;\n if (typeof handler === 'function') {\n // Accept both (params) => ... handlers and component functions that take no args / props\n return (params: Record<string, string>, ctx?: { signal?: AbortSignal }) => {\n // Call with params and ctx; component functions can ignore them\n // Allow handler to return JSX element, VNode, Promise, etc.\n // If the function expects only props, passing params is safe (extra args ignored)\n try {\n return handler(params, ctx);\n } catch {\n return handler(params);\n }\n };\n }\n return undefined;\n}\n\n// Register route with flexible handler shapes and optional nested descriptors.\n// Usage patterns supported:\n// - Absolute flat registration: registerRoute('/pages', () => List())\n// - Nested descriptors: registerRoute('/', () => Home(), registerRoute('pages', () => List(), registerRoute('{id}', () => Detail())))\n// Note: child descriptors should use relative paths (no leading '/').\nexport function registerRoute(\n path: string,\n handler?: unknown,\n ...children: Array<RouteDescriptor | undefined>\n): RouteDescriptor {\n const isRelative = !path.startsWith('/');\n\n // Build descriptor that can be used for nesting\n const descriptor: RouteDescriptor = {\n path,\n handler,\n children: children.filter(Boolean) as RouteDescriptor[],\n _isDescriptor: true,\n };\n\n // If path is absolute, perform registration immediately and recurse into children\n if (!isRelative) {\n const normalized = normalizeHandler(handler);\n if (handler != null && !normalized) {\n throw new Error(\n 'registerRoute(path, handler) requires a function handler. Passing JSX elements or VNodes directly is not supported.'\n );\n }\n if (normalized) route(path, normalized);\n\n for (const child of descriptor.children || []) {\n // Compute child full path\n const base = path === '/' ? '' : path.replace(/\\/$/, '');\n const childPath = `${base}/${child.path.replace(/^\\//, '')}`.replace(\n /\\/\\//g,\n '/'\n );\n // Recurse: if child.handler is provided, register it\n if (child.handler) {\n const childNormalized = normalizeHandler(child.handler);\n if (!childNormalized) {\n throw new Error(\n 'registerRoute child handler must be a function. Passing JSX elements directly is not supported.'\n );\n }\n if (childNormalized) route(childPath, childNormalized);\n }\n // Recurse into grandchildren\n if (child.children && child.children.length) {\n // Convert child.children into descriptors and register them\n // Use registerRoute recursively with absolute childPath\n registerRoute(\n childPath,\n null,\n ...(child.children as RouteDescriptor[])\n );\n }\n }\n\n return descriptor;\n }\n\n // If relative, return descriptor for nesting (do not register yet)\n return descriptor;\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\n/**\n * Resolve a path to a route handler with optimized lookup\n * Routes are matched by specificity: literals > parameters > wildcards > catch-all\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const depth =\n normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n\n // Collect all matching routes with their specificity\n const candidates: Array<{\n route: Route;\n specificity: number;\n params: Record<string, string>;\n }> = [];\n\n // Try routes at this depth first (most likely match)\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n for (const r of depthRoutes) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n }\n\n // Fallback: scan all routes for different depths\n // (handles edge cases like wildcard routes)\n for (const r of routes) {\n // Skip if already checked in depth routes\n if (depthRoutes?.includes(r)) continue;\n\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n\n // Sort by specificity (highest first)\n candidates.sort((a, b) => b.specificity - a.specificity);\n\n // Return most specific match\n if (candidates.length > 0) {\n const best = candidates[0];\n return { handler: best.route.handler, params: best.params };\n }\n\n return null;\n}\n","/**\n * Path matching and parameter extraction\n */\n\nexport interface MatchResult {\n matched: boolean;\n params: Record<string, string>;\n}\n\n/**\n * Match a path against a route pattern and extract params\n *\n * @example\n * match('/users/123', '/users/{id}')\n * // → { matched: true, params: { id: '123' } }\n *\n * match('/posts/hello-world/edit', '/posts/{slug}/{action}')\n * // → { matched: true, params: { slug: 'hello-world', action: 'edit' } }\n *\n * match('/users', '/posts/{id}')\n * // → { matched: false, params: {} }\n */\nexport function match(path: string, pattern: string): MatchResult {\n // Normalize trailing slashes\n const normalizedPath =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n const normalizedPattern =\n pattern.endsWith('/') && pattern !== '/' ? pattern.slice(0, -1) : pattern;\n\n // Split into segments\n const pathSegments = normalizedPath.split('/').filter(Boolean);\n const patternSegments = normalizedPattern.split('/').filter(Boolean);\n\n // Support catch-all route: /* matches any path at any depth\n if (patternSegments.length === 1 && patternSegments[0] === '*') {\n // For multi-segment paths, preserve the leading slash\n // For single-segment paths, return just the segment\n return {\n matched: true,\n params: {\n '*': pathSegments.length > 1 ? normalizedPath : pathSegments[0],\n },\n };\n }\n\n // Check if lengths match (wildcard segments still need to match one segment)\n if (pathSegments.length !== patternSegments.length) {\n return { matched: false, params: {} };\n }\n\n const params: Record<string, string> = {};\n\n // Match each segment\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n const pathSegment = pathSegments[i];\n\n // Parameter: {paramName}\n if (patternSegment.startsWith('{') && patternSegment.endsWith('}')) {\n const paramName = patternSegment.slice(1, -1);\n params[paramName] = decodeURIComponent(pathSegment);\n } else if (patternSegment === '*') {\n // Wildcard: match single segment\n params['*'] = pathSegment;\n } else if (patternSegment !== pathSegment) {\n // Literal segment mismatch\n return { matched: false, params: {} };\n }\n }\n\n return { matched: true, params };\n}\n","/**\n * Invariant assertion utilities for correctness checking\n * Production-safe: invariants are enforced at build-time or with minimal overhead\n *\n * Core principle: fail fast when invariants are violated\n * All functions throw descriptive errors for debugging\n */\n\n/**\n * Assert a condition; throw with context if false\n * @internal\n */\nexport function invariant(\n condition: boolean,\n message: string,\n context?: Record<string, unknown>\n): asserts condition {\n if (!condition) {\n const contextStr = context ? '\\n' + JSON.stringify(context, null, 2) : '';\n throw new Error(`[Askr Invariant] ${message}${contextStr}`);\n }\n}\n\n/**\n * Assert object property exists and has correct type\n * @internal\n */\nexport function assertProperty<T extends object, K extends keyof T>(\n obj: T,\n prop: K,\n expectedType?: string\n): asserts obj is T & Required<Pick<T, K>> {\n invariant(prop in obj, `Object missing required property '${String(prop)}'`, {\n object: obj,\n });\n\n if (expectedType) {\n const actualType = typeof obj[prop];\n invariant(\n actualType === expectedType,\n `Property '${String(prop)}' has type '${actualType}', expected '${expectedType}'`,\n { value: obj[prop], expectedType }\n );\n }\n}\n\n/**\n * Assert a reference is not null/undefined\n * @internal\n */\nexport function assertDefined<T>(\n value: T | null | undefined,\n message: string\n): asserts value is T {\n invariant(value !== null && value !== undefined, message, { value });\n}\n\n/**\n * Assert a task runs exactly once atomically\n * Useful for verifying lifecycle events fire precisely when expected\n * @internal\n */\nexport class Once {\n private called = false;\n private calledAt: number | null = null;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n }\n\n check(): boolean {\n return this.called;\n }\n\n mark(): void {\n invariant(\n !this.called,\n `${this.name} called multiple times (previously at ${this.calledAt}ms)`,\n { now: Date.now() }\n );\n this.called = true;\n this.calledAt = Date.now();\n }\n\n reset(): void {\n this.called = false;\n this.calledAt = null;\n }\n}\n\n/**\n * Assert a value falls in an enumerated set\n * @internal\n */\nexport function assertEnum<T extends readonly unknown[]>(\n value: unknown,\n allowedValues: T,\n fieldName: string\n): asserts value is T[number] {\n invariant(\n allowedValues.includes(value),\n `${fieldName} must be one of [${allowedValues.join(', ')}], got ${JSON.stringify(value)}`,\n { value, allowed: allowedValues }\n );\n}\n\n/**\n * Assert execution context (scheduler, component, etc)\n * @internal\n */\nexport function assertContext(\n actual: unknown,\n expected: unknown,\n contextName: string\n): asserts actual is typeof expected {\n invariant(\n actual === expected,\n `Invalid ${contextName} context. Expected ${expected}, got ${actual}`,\n { expected, actual }\n );\n}\n\n/**\n * Assert scheduling precondition (not reentering, not during render, etc)\n * @internal\n */\nexport function assertSchedulingPrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[Scheduler Precondition] ${violationMessage}`);\n}\n\n/**\n * Assert state precondition\n * @internal\n */\nexport function assertStatePrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[State Precondition] ${violationMessage}`);\n}\n\n/**\n * Verify AbortController lifecycle\n * @internal\n */\nexport function assertAbortControllerState(\n signal: AbortSignal,\n expectedAborted: boolean,\n context: string\n): void {\n invariant(\n signal.aborted === expectedAborted,\n `AbortSignal ${expectedAborted ? 'should be' : 'should not be'} aborted in ${context}`,\n { actual: signal.aborted, expected: expectedAborted }\n );\n}\n\n/**\n * Guard: throw if callback is null when it shouldn't be\n * Used for notifyUpdate, event handlers, etc.\n * @internal\n */\nexport function assertCallbackAvailable<\n T extends (...args: unknown[]) => unknown,\n>(callback: T | null | undefined, callbackName: string): asserts callback is T {\n invariant(\n callback !== null && callback !== undefined,\n `${callbackName} callback is required but not available`,\n { callback }\n );\n}\n\n/**\n * Verify evaluation generation prevents stale evaluations\n * @internal\n */\nexport function assertEvaluationGeneration(\n current: number,\n latest: number,\n context: string\n): void {\n invariant(\n current === latest,\n `Stale evaluation generation in ${context}: current ${current}, latest ${latest}`,\n { current, latest }\n );\n}\n\n/**\n * Verify mounted flag state\n * @internal\n */\nexport function assertMountedState(\n mounted: boolean,\n expectedMounted: boolean,\n context: string\n): void {\n invariant(\n mounted === expectedMounted,\n `Invalid mounted state in ${context}: expected ${expectedMounted}, got ${mounted}`,\n { mounted, expected: expectedMounted }\n );\n}\n\n/**\n * Verify no null target when rendering\n * @internal\n */\nexport function assertRenderTarget(\n target: Element | null,\n context: string\n): asserts target is Element {\n invariant(target !== null, `Cannot render in ${context}: target is null`, {\n target,\n });\n}\n","/**\n * Centralized logger interface\n * - Keeps production builds silent for debug/warn/info messages\n * - Ensures consistent behavior across the codebase\n * - Protects against missing `console` in some environments\n */\n\nfunction callConsole(method: string, args: unknown[]): void {\n const c = typeof console !== 'undefined' ? (console as unknown) : undefined;\n if (!c) return;\n const fn = (c as Record<string, unknown>)[method];\n if (typeof fn === 'function') {\n try {\n (fn as (...a: unknown[]) => unknown).apply(console, args as unknown[]);\n } catch {\n // ignore logging errors\n }\n }\n}\n\nexport const logger = {\n debug: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('debug', args);\n },\n\n info: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('info', args);\n },\n\n warn: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('warn', args);\n },\n\n error: (...args: unknown[]) => {\n callConsole('error', args);\n },\n};\n","/**\n * Serialized update scheduler — safer design (no inline execution, explicit flush)\n *\n * Key ideas:\n * - Never execute a task inline from `enqueue`.\n * - `flush()` is explicit and non-reentrant.\n * - `runWithSyncProgress()` allows enqueues temporarily but does not run tasks\n * inline; it runs `fn` and then does an explicit `flush()`.\n * - `waitForFlush()` is race-free with a monotonic `flushVersion`.\n */\n\nimport { assertSchedulingPrecondition, invariant } from '../dev/invariant';\nimport { logger } from '../dev/logger';\n\nconst MAX_FLUSH_DEPTH = 50;\n\ntype Task = () => void;\n\nfunction isBulkCommitActive(): boolean {\n try {\n const fb = (\n globalThis as {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private q: Task[] = [];\n private head = 0;\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n enqueue(task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.q.push(task);\n this.taskCount++;\n\n // Microtask kick: best-effort, but avoid if we are in handler or running or bulk commit\n if (\n !this.running &&\n !this.kickScheduled &&\n !this.inHandler &&\n !isBulkCommitActive()\n ) {\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running) return;\n if (isBulkCommitActive()) return;\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n\n try {\n while (this.head < this.q.length) {\n this.depth++;\n if (\n process.env.NODE_ENV !== 'production' &&\n this.depth > MAX_FLUSH_DEPTH\n ) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = this.q[this.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n } catch (err) {\n // ensure executionDepth stays balanced\n if (this.executionDepth > 0) this.executionDepth = 0;\n fatal = err;\n break;\n }\n\n // Account for executed task in taskCount\n if (this.taskCount > 0) this.taskCount--;\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n // Compact queue\n if (this.head >= this.q.length) {\n this.q.length = 0;\n this.head = 0;\n } else if (this.head > 0) {\n const remaining = this.q.length - this.head;\n if (this.head > 1024 || this.head > remaining) {\n this.q = this.q.slice(this.head);\n } else {\n for (let i = 0; i < remaining; i++) {\n this.q[i] = this.q[this.head + i];\n }\n this.q.length = remaining;\n }\n this.head = 0;\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n const g = globalThis as {\n queueMicrotask?: (...args: unknown[]) => void;\n setTimeout?: (...args: unknown[]) => unknown;\n };\n const origQueueMicrotask = g.queueMicrotask;\n const origSetTimeout = g.setTimeout;\n\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = () => {\n throw new Error(\n '[Scheduler] queueMicrotask not allowed during runWithSyncProgress'\n );\n };\n g.setTimeout = () => {\n throw new Error(\n '[Scheduler] setTimeout not allowed during runWithSyncProgress'\n );\n };\n }\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.q.length - this.head > 0) {\n this.flush();\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (this.q.length - this.head > 0) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // Restore guarded globals\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = origQueueMicrotask;\n g.setTimeout = origSetTimeout;\n }\n\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const ns =\n (\n globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n }\n ).__ASKR__ || {};\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.q.length - this.head,\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n namespace: ns,\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.q.length - this.head,\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.q.length - this.head;\n if (remaining <= 0) return 0;\n\n if (this.running) {\n this.q.length = this.head;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n this.q.length = 0;\n this.head = 0;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler.call(null, event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them now that the handler\n // has completed. This avoids tests timing out waiting for flush.\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n}\n","/**\n * Context system: lexical scope + render-time snapshots\n *\n * CORE SEMANTIC (Option A — Snapshot-Based):\n * ============================================\n * An async resource observes the context of the render that created it.\n * Context changes only take effect via re-render, not magically mid-await.\n *\n * This ensures:\n * - Deterministic behavior\n * - Concurrency safety\n * - Replayable execution\n * - Debuggability\n *\n * INVARIANTS:\n * - readContext() only works during component render (has currentContextFrame)\n * - Each render captures a context snapshot\n * - Async continuations see the snapshot from render start (frozen)\n * - Provider (Scope) creates a new frame that shadows parent\n * - Context updates require re-render to take effect\n */\n\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: unknown; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\n// Global context frame stack (maintained during render)\n// INVARIANT: Must NEVER be non-null across an await boundary\nlet currentContextFrame: ContextFrame | null = null;\n\n// Async resource frame (maintained during async resource execution)\n// INVARIANT: Set only for synchronous execution steps, cleared in finally\n// This allows async resources to access their frozen render-time snapshot\nlet currentAsyncResourceFrame: ContextFrame | null = null;\n\n/**\n * Execute a function within a specific context frame.\n *\n * CORE PRIMITIVE for context restoration:\n * - Saves the current context\n * - Sets the provided frame as current\n * - Executes the function\n * - Restores the previous context in finally\n *\n * This ensures no context frame remains globally active across await.\n */\nexport function withContext<T>(frame: ContextFrame | null, fn: () => T): T {\n const oldFrame = currentContextFrame;\n currentContextFrame = frame;\n try {\n return fn();\n } finally {\n currentContextFrame = oldFrame;\n }\n}\n\n/**\n * Execute an async resource step within its frozen context snapshot.\n *\n * CRITICAL: This wrapper is applied only to synchronous execution steps of\n * an async resource (the initial call). We intentionally DO NOT restore\n * the resource frame for post-await continuations — continuations must not\n * observe or rely on a live resource frame. This keeps semantics simple and\n * deterministic: async resources see only their creation-time snapshot.\n */\nexport function withAsyncResourceContext<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n const oldFrame = currentAsyncResourceFrame;\n // Only set the frame for the synchronous execution step\n currentAsyncResourceFrame = frame;\n try {\n return fn();\n } finally {\n // Clear the frame to avoid exposing it across await boundaries\n currentAsyncResourceFrame = oldFrame;\n }\n}\n\nexport function defineContext<T>(defaultValue: T): Context<T> {\n const key = Symbol('AskrContext');\n\n return {\n key,\n defaultValue,\n Scope: (props: { value: unknown; children?: unknown }): JSXElement => {\n // Scope component: accepts an unknown value (tests often pass loosely typed values)\n // Cast to the expected T at the call site to preserve runtime behavior.\n const value = props.value as T;\n // Scope component: creates a new frame and renders children within it\n return {\n type: ContextScopeComponent,\n props: { key, value, children: props.children },\n } as JSXElement;\n },\n };\n}\n\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // Helper: create a function-child invoker node (centralized cast)\n function createFunctionChildInvoker(\n fn: () => Renderable,\n frame: ContextFrame,\n owner: ComponentInstance | null\n ): Renderable {\n return {\n type: ContextFunctionChildInvoker,\n props: { fn, __frame: frame, __owner: owner },\n } as unknown as Renderable;\n }\n\n // The renderer will set ownerFrame on child component instances when they're created.\n // We mark vnodes with the frame so the renderer knows which frame to assign.\n if (Array.isArray(children)) {\n // Mark array elements with the frame. If an element is a function-child,\n // convert it into a lazy invoker so it's executed later inside the frame.\n return children.map((child) => {\n if (typeof child === 'function') {\n return createFunctionChildInvoker(\n child as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n }\n return markWithFrame(child, newFrame);\n }) as unknown as Renderable;\n } else if (typeof children === 'function') {\n // If children is a function (render callback), do NOT execute it eagerly\n // during the parent render. Instead, return a small internal component\n // that will execute the function later (when it itself is rendered) and\n // will execute it within the provider frame so any reads performed during\n // that execution observe the provider's frame.\n return createFunctionChildInvoker(\n children as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n } else if (children) {\n return markWithFrame(children, newFrame);\n }\n\n return null;\n}\n\n/**\n * Internal: Mark a vnode with a context frame\n * The renderer will restore this frame before executing component functions\n */\nfunction markWithFrame(node: Renderable, frame: ContextFrame): Renderable {\n // Recursively mark node and its subtree so nested provider/component\n // executions will restore the correct frame when they are rendered.\n if (typeof node === 'object' && node !== null) {\n const obj = node as Record<string | symbol, unknown>;\n obj[CONTEXT_FRAME_SYMBOL] = frame;\n\n // If the node is a VNode with children, recursively mark its children\n const children = obj.children as unknown;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const child = children[i] as Renderable;\n if (child) {\n children[i] = markWithFrame(child, frame) as Renderable;\n }\n }\n } else if (children) {\n obj.children = markWithFrame(children as Renderable, frame) as Renderable;\n }\n }\n return node;\n}\n\n/**\n * Internal helper component: executes a function-child lazily inside the\n * provided frame and marks the returned subtree with that frame so later\n * component executions will restore the correct context frame.\n *\n * SNAPSHOT SEMANTIC: The frame passed here is the snapshot captured at render\n * time. Any resources created during this execution will observe this frozen\n * snapshot, ensuring deterministic behavior.\n */\nfunction ContextFunctionChildInvoker(props: {\n fn: () => Renderable;\n __frame: ContextFrame;\n __owner?: ComponentInstance | null;\n}): Renderable {\n const { fn, __frame } = props;\n\n // Execute the function-child within the provider frame.\n // The owner's ownerFrame is already set by the renderer when the component was created.\n // Any resources started during this execution will capture this frame as their\n // snapshot, ensuring they see the context values from this render, not future renders.\n const res = withContext(__frame, () => fn());\n\n // Mark the result so the renderer knows to set ownerFrame on child instances\n if (res) return markWithFrame(res, __frame);\n return null;\n}\n\n/**\n * Push a new context frame (for render entry)\n * Called by component runtime when render starts\n */\nexport function pushContextFrame(): ContextFrame {\n // Lazily allocate the `values` map to avoid per-render allocations when\n // components do not use context. The map will be created when a provider\n // sets a value or when a read discovers no map and needs to behave as empty.\n const frame: ContextFrame = {\n parent: currentContextFrame,\n values: null,\n };\n currentContextFrame = frame;\n return frame;\n}\n\n/**\n * Pop context frame (for render exit)\n * Called by component runtime when render ends\n */\nexport function popContextFrame(): void {\n if (currentContextFrame) {\n currentContextFrame = currentContextFrame.parent;\n }\n}\n\n/**\n * Get the current context frame for inspection (used by tests/diagnostics only)\n */\nexport function getCurrentContextFrame(): ContextFrame | null {\n return currentContextFrame;\n}\n\n/**\n * Get the top of the context snapshot stack (used by runtime when deciding\n * how to link snapshots for async continuations). Returns null if stack empty.\n */\nexport function getTopContextSnapshot(): ContextFrame | null {\n return currentContextFrame;\n}\n","type DiagMap = Record<string, unknown>;\n\nfunction getDiagMap(): DiagMap {\n try {\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR_DIAG?: DiagMap;\n };\n if (!root.__ASKR_DIAG) root.__ASKR_DIAG = {} as DiagMap;\n return root.__ASKR_DIAG!;\n } catch (e) {\n void e;\n return {} as DiagMap;\n }\n}\n\nexport function __ASKR_set(key: string, value: unknown): void {\n try {\n const g = getDiagMap();\n (g as DiagMap)[key] = value;\n try {\n // Consolidate diagnostics under a single namespace to avoid\n // polluting the top-level global scope. Expose a namespaced view on\n // `globalThis.__ASKR__` so tools and tests can inspect diagnostic keys.\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n try {\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n ns[key] = value;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n\nexport function __ASKR_incCounter(key: string): void {\n try {\n const g = getDiagMap();\n const prev = typeof g[key] === 'number' ? (g[key] as number) : 0;\n const next = prev + 1;\n (g as DiagMap)[key] = next;\n try {\n // Mirror counter into namespaced diagnostics\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n const nsPrev = typeof ns[key] === 'number' ? (ns[key] as number) : 0;\n ns[key] = nsPrev + 1;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n","/**\n * Dev-only namespace helpers for diagnostics\n *\n * Centralizes the repetitive globalThis.__ASKR__ access pattern\n * used throughout runtime for dev-mode diagnostics.\n */\n\ntype DevNamespace = Record<string, unknown>;\n\n/**\n * Get or create the __ASKR__ dev namespace on globalThis.\n * Returns empty object in production to avoid allocations.\n */\nexport function getDevNamespace(): DevNamespace {\n if (process.env.NODE_ENV === 'production') return {};\n try {\n const g = globalThis as unknown as Record<string, DevNamespace>;\n if (!g.__ASKR__) g.__ASKR__ = {};\n return g.__ASKR__;\n } catch {\n return {};\n }\n}\n\n/**\n * Set a value in the dev namespace (no-op in production).\n */\nexport function setDevValue(key: string, value: unknown): void {\n if (process.env.NODE_ENV === 'production') return;\n try {\n getDevNamespace()[key] = value;\n } catch {\n // ignore\n }\n}\n\n/**\n * Get a value from the dev namespace (returns undefined in production).\n */\nexport function getDevValue<T>(key: string): T | undefined {\n if (process.env.NODE_ENV === 'production') return undefined;\n try {\n return getDevNamespace()[key] as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Delete a value from the dev namespace (no-op in production).\n */\nexport function deleteDevValue(key: string): void {\n if (process.env.NODE_ENV === 'production') return;\n try {\n delete getDevNamespace()[key];\n } catch {\n // ignore\n }\n}\n","import { globalScheduler } from './scheduler';\nimport { setDevValue } from './dev-namespace';\n\nlet _bulkCommitActive = false;\nlet _appliedParents: WeakSet<Element> | null = null;\n\nexport function enterBulkCommit(): void {\n _bulkCommitActive = true;\n // Initialize registry of parents that had fast-path applied during this bulk commit\n _appliedParents = new WeakSet<Element>();\n\n // Clear any previously scheduled synchronous scheduler tasks so they don't\n // retrigger evaluations during the committed fast-path.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__ASKR_FASTLANE_CLEARED_TASKS', cleared);\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n}\n\nexport function exitBulkCommit(): void {\n _bulkCommitActive = false;\n // Clear registry to avoid leaking across commits\n _appliedParents = null;\n}\n\nexport function isBulkCommitActive(): boolean {\n return _bulkCommitActive;\n}\n\n// Mark that a fast-path was applied on a parent element during the active\n// bulk commit. No-op if there is no active bulk commit.\nexport function markFastPathApplied(parent: Element): void {\n if (!_appliedParents) return;\n try {\n _appliedParents.add(parent);\n } catch (e) {\n void e;\n }\n}\n\nexport function isFastPathApplied(parent: Element): boolean {\n return !!(_appliedParents && _appliedParents.has(parent));\n}\n","import type { Props } from '../shared/types';\n\nexport interface DOMElement {\n // Element `type` can be an intrinsic tag name, a component function, or\n // a special symbol (e.g. `Fragment`). Include `symbol` in the type union\n // so runtime comparisons against `Fragment` are type-safe.\n type: string | ((props: Props) => unknown) | symbol;\n props?: Props;\n children?: VNode[];\n key?: string | number;\n [Symbol.iterator]?: never;\n}\n\n// Type for virtual DOM nodes\nexport type VNode = DOMElement | string | number | boolean | null | undefined;\n\nexport function _isDOMElement(node: unknown): node is DOMElement {\n return typeof node === 'object' && node !== null && 'type' in node;\n}\n","import { cleanupComponent } from '../runtime/component';\nimport type { ComponentInstance } from '../runtime/component';\nimport { logger } from '../dev/logger';\n\ntype InstanceHost = Element & { __ASKR_INSTANCE?: unknown };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Instance Cleanup Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction cleanupSingleInstance(\n node: InstanceHost,\n errors: unknown[],\n strict: boolean\n): void {\n const inst = node.__ASKR_INSTANCE;\n if (!inst) return;\n\n try {\n cleanupComponent(inst as ComponentInstance);\n } catch (err) {\n if (strict) errors.push(err);\n else logger.warn('[Askr] cleanupComponent failed:', err);\n }\n\n try {\n delete node.__ASKR_INSTANCE;\n } catch (e) {\n if (strict) errors.push(e);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Clean up component instance attached to a DOM node\n * Accepts an optional `opts.strict` flag to surface errors instead of swallowing them.\n */\nexport function cleanupInstanceIfPresent(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n if (!node || !(node instanceof Element)) return;\n\n const errors: unknown[] = [];\n const strict = opts?.strict ?? false;\n\n // Clean up the node itself\n try {\n cleanupSingleInstance(node as InstanceHost, errors, strict);\n } catch (err) {\n if (strict) errors.push(err);\n else logger.warn('[Askr] cleanupInstanceIfPresent failed:', err);\n }\n\n // Clean up any nested instances on descendants\n try {\n const descendants = node.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n cleanupSingleInstance(d as InstanceHost, errors, strict);\n } catch (err) {\n if (strict) errors.push(err);\n else\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant cleanup failed:',\n err\n );\n }\n }\n } catch (err) {\n if (strict) errors.push(err);\n else\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant query failed:',\n err\n );\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'cleanupInstanceIfPresent failed');\n }\n}\n\n// Public helper to clean up any component instances under a node. Used by\n// runtime commit logic to ensure component instances are torn down when their\n// host nodes are removed during an update.\nexport function cleanupInstancesUnder(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n cleanupInstanceIfPresent(node, opts);\n}\n\n// Track listeners so we can remove them on cleanup\nexport interface ListenerMapEntry {\n handler: EventListener;\n original: EventListener;\n options?: boolean | AddEventListenerOptions;\n}\nexport const elementListeners = new WeakMap<\n Element,\n Map<string, ListenerMapEntry>\n>();\n\nexport function removeElementListeners(element: Element): void {\n const map = elementListeners.get(element);\n if (map) {\n for (const [eventName, entry] of map) {\n // When removing, reuse the original options if present for correctness\n if (entry.options !== undefined)\n element.removeEventListener(eventName, entry.handler, entry.options);\n else element.removeEventListener(eventName, entry.handler);\n }\n elementListeners.delete(element);\n }\n}\n\nexport function removeAllListeners(root: Element | null): void {\n if (!root) return;\n\n // Remove listeners from root\n removeElementListeners(root);\n\n // Recursively remove from all children\n const children = root.querySelectorAll('*');\n for (let i = 0; i < children.length; i++) {\n removeElementListeners(children[i]);\n }\n}\n","/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n options?: boolean | AddEventListenerOptions;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n return (\n propName.slice(2).charAt(0).toLowerCase() + propName.slice(3).toLowerCase()\n );\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n if (flushAfter) {\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n queueMicrotask(() => {\n throw err;\n });\n }\n });\n }\n }\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return el.className !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(key);\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n for (const ch of children) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n __ASKR_incCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n","import type { VNode } from './types';\nimport {\n extractKey,\n buildKeyMapFromChildren,\n isIgnoredForPropChanges,\n hasPropChanged,\n hasNonTrivialProps,\n} from './utils';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Map Registry\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const keyedElements = new WeakMap<\n Element,\n Map<string | number, Element>\n>();\n\n/**\n * Retrieve existing keyed map for a parent element (runtime use)\n */\nexport function getKeyMapForElement(el: Element) {\n return keyedElements.get(el);\n}\n\n/**\n * Populate a keyed map for an element by scanning its immediate children\n * for `data-key` attributes. Proactive initialization for runtime layers.\n */\nexport function populateKeyMapForElement(parent: Element): void {\n try {\n if (keyedElements.has(parent)) return;\n\n let domMap = buildKeyMapFromChildren(parent);\n\n // Fallback: map by textContent when keys are not materialized as attrs\n if (domMap.size === 0) {\n domMap = new Map();\n const children = Array.from(parent.children);\n for (const ch of children) {\n const text = (ch.textContent || '').trim();\n if (text) {\n domMap.set(text, ch);\n const n = Number(text);\n if (!Number.isNaN(n)) domMap.set(n, ch);\n }\n }\n }\n\n if (domMap.size > 0) keyedElements.set(parent, domMap);\n } catch {\n // ignore\n }\n}\n\n// Track which parents had the reconciler record fast-path stats during the\n// current evaluation, so we can preserve diagnostics across additional\n// reconciliations within the same render pass without leaking between runs.\nexport const _reconcilerRecordedParents = new WeakSet<Element>();\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fast-Path Eligibility\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface KeyedVnode {\n key: string | number;\n vnode: VNode;\n}\n\n/**\n * Extract keyed vnodes from children array\n */\nfunction extractKeyedVnodes(newChildren: VNode[]): KeyedVnode[] {\n const result: KeyedVnode[] = [];\n for (const child of newChildren) {\n const key = extractKey(child);\n if (key !== undefined) {\n result.push({ key, vnode: child });\n }\n }\n return result;\n}\n\n/**\n * Compute LIS (Longest Increasing Subsequence) length for positions\n */\nfunction computeLISLength(positions: number[]): number {\n const tails: number[] = [];\n for (const pos of positions) {\n if (pos === -1) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (tails[mid] < pos) lo = mid + 1;\n else hi = mid;\n }\n if (lo === tails.length) tails.push(pos);\n else tails[lo] = pos;\n }\n return tails.length;\n}\n\n/**\n * Check if any vnode has non-trivial props\n */\nfunction checkVnodesHaveProps(keyedVnodes: KeyedVnode[]): boolean {\n for (const { vnode } of keyedVnodes) {\n if (typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n if (vnodeObj.props && hasNonTrivialProps(vnodeObj.props)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnodes and existing elements\n */\nfunction checkVnodePropChanges(\n keyedVnodes: KeyedVnode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): boolean {\n for (const { key, vnode } of keyedVnodes) {\n const el = oldKeyMap?.get(key);\n if (!el || typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n const props = vnodeObj.props || {};\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determine if keyed reorder fast-path should be used\n */\nexport function isKeyedReorderFastPathEligible(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n) {\n const keyedVnodes = extractKeyedVnodes(newChildren);\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\n // Count moves needed\n let moveCount = 0;\n for (let i = 0; i < newKeyOrder.length; i++) {\n const k = newKeyOrder[i];\n if (i >= oldKeyOrder.length || oldKeyOrder[i] !== k || !oldKeyMap?.has(k)) {\n moveCount++;\n }\n }\n\n // Check move threshold triggers\n const FAST_MOVE_THRESHOLD_ABS = 64;\n const FAST_MOVE_THRESHOLD_REL = 0.1;\n const cheapMoveTrigger =\n totalKeyed >= 128 &&\n oldKeyOrder.length > 0 &&\n moveCount >\n Math.max(\n FAST_MOVE_THRESHOLD_ABS,\n Math.floor(totalKeyed * FAST_MOVE_THRESHOLD_REL)\n );\n\n // Compute LIS trigger for large lists\n let lisTrigger = false;\n let lisLen = 0;\n if (totalKeyed >= 128) {\n const parentChildren = Array.from(parent.children);\n const positions = keyedVnodes.map(({ key }) => {\n const el = oldKeyMap?.get(key);\n return el?.parentElement === parent ? parentChildren.indexOf(el) : -1;\n });\n lisLen = computeLISLength(positions);\n lisTrigger = lisLen < Math.floor(totalKeyed * 0.5);\n }\n\n // Check for props that would prevent fast-path\n const hasPropsPresent = checkVnodesHaveProps(keyedVnodes);\n const hasPropChanges = checkVnodePropChanges(keyedVnodes, oldKeyMap);\n\n const useFastPath =\n (cheapMoveTrigger || lisTrigger) && !hasPropChanges && !hasPropsPresent;\n\n return {\n useFastPath,\n totalKeyed,\n moveCount,\n lisLen,\n hasPropChanges,\n } as const;\n}\n","import { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { Fragment } from '../jsx/jsx-runtime';\nimport {\n CONTEXT_FRAME_SYMBOL,\n withContext,\n getCurrentContextFrame,\n ContextFrame,\n} from '../runtime/context';\nimport {\n createComponentInstance,\n renderComponentInline,\n mountInstanceInline,\n getCurrentInstance,\n} from '../runtime/component';\nimport type {\n ComponentInstance,\n ComponentFunction,\n} from '../runtime/component';\nimport {\n cleanupInstanceIfPresent,\n elementListeners,\n removeAllListeners,\n} from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport { keyedElements } from './keyed';\nimport {\n parseEventName,\n getPassiveOptions,\n createWrappedHandler,\n isSkippedProp,\n now,\n recordDOMReplace,\n recordFastPathStats,\n logFastPathDebug,\n} from './utils';\n\ntype ElementWithContext = DOMElement & {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n __instance?: ComponentInstance;\n};\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Management\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Add an event listener to an element with tracking\n */\nfunction addTrackedListener(\n el: Element,\n eventName: string,\n handler: EventListener\n): void {\n const wrappedHandler = createWrappedHandler(handler, true);\n const options = getPassiveOptions(eventName);\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: handler,\n options,\n });\n}\n\n/**\n * Apply attributes and event listeners to an element from props\n */\nfunction applyPropsToElement(\n el: Element,\n props: Record<string, unknown>,\n tagName: string\n): void {\n for (const key in props) {\n const value = props[key];\n if (isSkippedProp(key)) continue;\n if (value === undefined || value === null || value === false) continue;\n\n const eventName = parseEventName(key);\n if (eventName) {\n addTrackedListener(el, eventName, value as EventListener);\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n applyFormControlProp(el, key, value, tagName);\n } else {\n el.setAttribute(key, String(value));\n }\n }\n}\n\n/**\n * Apply value/checked props to form controls\n */\nfunction applyFormControlProp(\n el: Element,\n key: string,\n value: unknown,\n tagName: string\n): void {\n const tag = tagName.toLowerCase();\n if (key === 'value') {\n if (tag === 'input' || tag === 'textarea' || tag === 'select') {\n (el as HTMLInputElement & Props).value = String(value);\n el.setAttribute('value', String(value));\n } else {\n el.setAttribute('value', String(value));\n }\n } else if (key === 'checked') {\n if (tag === 'input') {\n (el as HTMLInputElement & Props).checked = Boolean(value);\n el.setAttribute('checked', String(Boolean(value)));\n } else {\n el.setAttribute('checked', String(Boolean(value)));\n }\n }\n}\n\n/**\n * Materialize vnode key as data-key attribute\n */\nfunction materializeKey(\n el: Element,\n vnode: DOMElement,\n props: Record<string, unknown>\n): void {\n const vnodeKey = vnode.key ?? props?.key;\n if (vnodeKey !== undefined) {\n el.setAttribute('data-key', String(vnodeKey));\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dynamic List Warnings\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Warn about missing keys on dynamic lists (dev only)\n */\nfunction warnMissingKeys(children: unknown[]): void {\n if (process.env.NODE_ENV === 'production') return;\n\n let hasElements = false;\n let hasKeys = false;\n\n for (const item of children) {\n if (typeof item === 'object' && item !== null && 'type' in item) {\n hasElements = true;\n const rawKey =\n (item as DOMElement).key ??\n ((item as DOMElement).props as Record<string, unknown> | undefined)\n ?.key;\n if (rawKey !== undefined) {\n hasKeys = true;\n break;\n }\n }\n }\n\n if (hasElements && !hasKeys) {\n try {\n const inst = getCurrentInstance();\n const name = inst?.fn?.name || '<anonymous>';\n logger.warn(\n `Missing keys on dynamic lists in ${name}. Each child in a list should have a unique \"key\" prop.`\n );\n } catch {\n logger.warn(\n 'Missing keys on dynamic lists. Each child in a list should have a unique \"key\" prop.'\n );\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM Node Creation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Create a DOM node from a VNode\n */\nexport function createDOMNode(node: unknown): Node | null {\n // SSR guard: don't attempt DOM ops when document is unavailable\n if (!IS_DOM_AVAILABLE) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[Askr] createDOMNode called in non-DOM environment');\n } catch {\n // ignore\n }\n }\n return null;\n }\n\n // Fast paths for primitives (most common)\n if (typeof node === 'string') {\n return document.createTextNode(node);\n }\n if (typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n\n // Null/undefined/false\n if (!node) {\n return null;\n }\n\n // Array (fragment) - batch all at once\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (const child of node) {\n const dom = createDOMNode(child);\n if (dom) fragment.appendChild(dom);\n }\n return fragment;\n }\n\n // Element or Component\n if (typeof node === 'object' && node !== null && 'type' in node) {\n const type = (node as DOMElement).type;\n const props = ((node as DOMElement).props || {}) as Record<string, unknown>;\n\n // Intrinsic element (string type)\n if (typeof type === 'string') {\n return createIntrinsicElement(node as DOMElement, type, props);\n }\n\n // Component (function type) - inline execution\n if (typeof type === 'function') {\n return createComponentElement(node as ElementWithContext, type, props);\n }\n\n // Fragment support\n if (\n typeof type === 'symbol' &&\n (type === Fragment || String(type) === 'Symbol(Fragment)')\n ) {\n return createFragmentElement(node as DOMElement, props);\n }\n }\n\n return null;\n}\n\n/**\n * Create an intrinsic DOM element (div, span, etc.)\n */\nfunction createIntrinsicElement(\n node: DOMElement,\n type: string,\n props: Record<string, unknown>\n): Element {\n const el = document.createElement(type);\n\n // Materialize key into DOM attribute\n materializeKey(el, node, props);\n\n // Apply props/attributes\n applyPropsToElement(el, props, type);\n\n // Add children\n const children = props.children || node.children;\n if (children) {\n if (Array.isArray(children)) {\n warnMissingKeys(children);\n for (const child of children) {\n const dom = createDOMNode(child);\n if (dom) el.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n }\n }\n\n return el;\n}\n\n/**\n * Create element from a component function\n */\nfunction createComponentElement(\n node: ElementWithContext,\n type: (props: Props) => unknown,\n props: Record<string, unknown>\n): Node {\n // Check if this vnode has a marked context frame\n const frame = node[CONTEXT_FRAME_SYMBOL];\n const snapshot = frame || getCurrentContextFrame();\n\n const componentFn = type as (props: Props) => unknown;\n const isAsync = componentFn.constructor.name === 'AsyncFunction';\n\n if (isAsync) {\n throw new Error(\n 'Async components are not supported. Use resource() for async work.'\n );\n }\n\n // Ensure there is a persistent instance object attached to this vnode\n let childInstance = node.__instance;\n if (!childInstance) {\n childInstance = createComponentInstance(\n `comp-${Math.random().toString(36).slice(2, 7)}`,\n componentFn as ComponentFunction,\n props || {},\n null\n );\n node.__instance = childInstance;\n }\n\n if (snapshot) {\n childInstance.ownerFrame = snapshot;\n }\n\n const result = withContext(snapshot, () =>\n renderComponentInline(childInstance)\n );\n\n if (result instanceof Promise) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n const dom = withContext(snapshot, () => createDOMNode(result));\n\n if (dom instanceof Element) {\n mountInstanceInline(childInstance, dom);\n return dom;\n }\n\n // For null/undefined returns, use a comment placeholder that can be replaced\n // when the component re-renders with actual content. This is necessary for\n // portals and other components that may initially return null but later have content.\n if (!dom) {\n const placeholder = document.createComment('');\n // Store reference so we can find and replace it on re-render\n childInstance._placeholder = placeholder;\n childInstance.mounted = true;\n // Ensure notifyUpdate is set so the component can be re-rendered when content appears\n childInstance.notifyUpdate = childInstance._enqueueRun!;\n return placeholder;\n }\n\n // For non-Element returns (Text nodes or DocumentFragment), wrap in host\n const host = document.createElement('div');\n host.appendChild(dom);\n mountInstanceInline(childInstance, host);\n return host;\n}\n\n/**\n * Create a document fragment from Fragment vnode\n */\nfunction createFragmentElement(\n node: DOMElement,\n props: Record<string, unknown>\n): DocumentFragment {\n const fragment = document.createDocumentFragment();\n const children = props.children || node.children;\n if (children) {\n if (Array.isArray(children)) {\n for (const child of children) {\n const dom = createDOMNode(child);\n if (dom) fragment.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) fragment.appendChild(dom);\n }\n }\n return fragment;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Element Updates\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Update an existing element's attributes and children from vnode\n */\nexport function updateElementFromVnode(\n el: Element,\n vnode: VNode,\n updateChildren = true\n): void {\n if (!_isDOMElement(vnode)) {\n return;\n }\n\n const props = (vnode.props || {}) as Record<string, unknown>;\n\n // Ensure key is materialized\n materializeKey(el, vnode, props);\n\n // Diff and update event listeners and other attributes\n const existingListeners = elementListeners.get(el);\n const desiredEventNames = new Set<string>();\n\n for (const key in props) {\n const value = props[key];\n if (isSkippedProp(key)) continue;\n\n const eventName = parseEventName(key);\n\n // Handle removal cases\n if (value === undefined || value === null || value === false) {\n if (key === 'class' || key === 'className') {\n el.className = '';\n } else if (eventName && existingListeners?.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n if (entry.options !== undefined) {\n el.removeEventListener(eventName, entry.handler, entry.options);\n } else {\n el.removeEventListener(eventName, entry.handler);\n }\n existingListeners.delete(eventName);\n } else {\n el.removeAttribute(key);\n }\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Record<string, unknown>)[key] = value;\n } else if (eventName) {\n desiredEventNames.add(eventName);\n\n const existing = existingListeners?.get(eventName);\n // If handler reference unchanged, keep existing wrapped handler\n if (existing && existing.original === value) {\n continue;\n }\n\n // Remove old handler if present\n if (existing) {\n el.removeEventListener(eventName, existing.handler);\n }\n\n // Add new handler\n const wrappedHandler = createWrappedHandler(\n value as EventListener,\n false\n );\n const options = getPassiveOptions(eventName);\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n options,\n });\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Remove any remaining listeners not desired by current props\n if (existingListeners) {\n for (const eventName of existingListeners.keys()) {\n if (!desiredEventNames.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n el.removeEventListener(eventName, entry.handler);\n existingListeners.delete(eventName);\n }\n }\n if (existingListeners.size === 0) elementListeners.delete(el);\n }\n\n // Update children\n if (updateChildren) {\n const children =\n vnode.children || (props.children as VNode | VNode[] | undefined);\n updateElementChildren(el, children);\n }\n}\n\nexport function updateElementChildren(\n el: Element,\n children: VNode | VNode[] | undefined\n): void {\n if (!children) {\n el.textContent = '';\n return;\n }\n\n if (\n !Array.isArray(children) &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n return;\n }\n\n if (Array.isArray(children)) {\n updateUnkeyedChildren(el, children as unknown[]);\n return;\n }\n\n el.textContent = '';\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n}\n\nexport function updateUnkeyedChildren(\n parent: Element,\n newChildren: unknown[]\n): void {\n const existing = Array.from(parent.children);\n\n // Special case: if we have a single text/number child and the parent has a single text node,\n // update the text node in place to preserve identity\n if (\n newChildren.length === 1 &&\n existing.length === 0 &&\n parent.childNodes.length === 1\n ) {\n const firstNewChild = newChildren[0];\n const firstExisting = parent.firstChild;\n if (\n (typeof firstNewChild === 'string' ||\n typeof firstNewChild === 'number') &&\n firstExisting?.nodeType === 3 // Text node\n ) {\n (firstExisting as Text).data = String(firstNewChild);\n return;\n }\n }\n\n // If there are only text nodes (no element children), clear before updating\n if (existing.length === 0 && parent.childNodes.length > 0) {\n parent.textContent = '';\n }\n const max = Math.max(existing.length, newChildren.length);\n\n for (let i = 0; i < max; i++) {\n const current = existing[i];\n const next = newChildren[i];\n\n // Remove extra existing children\n if (next === undefined && current) {\n // Clean up any component instance mounted on this node\n cleanupInstanceIfPresent(current);\n current.remove();\n continue;\n }\n\n // Append new children beyond existing length\n if (!current && next !== undefined) {\n const dom = createDOMNode(next);\n if (dom) parent.appendChild(dom);\n continue;\n }\n\n if (!current || next === undefined) continue;\n\n // Update existing element based on next vnode/primitive\n if (typeof next === 'string' || typeof next === 'number') {\n current.textContent = String(next);\n } else if (_isDOMElement(next)) {\n if (typeof next.type === 'string') {\n // If element type matches, update in place; otherwise replace\n if (current.tagName.toLowerCase() === next.type.toLowerCase()) {\n updateElementFromVnode(current, next);\n } else {\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Non-string types: replace conservatively\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Fallback for other types: replace\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n }\n}\n\n/**\n * Positional update for keyed lists where keys changed en-masse but structure\n * (element tags and simple text children) remains identical. This updates\n * text content in-place and remaps the `data-key` attribute to the new key so\n * subsequent updates can find elements by their data-key.\n */\nexport function performBulkPositionalKeyedTextUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n) {\n const total = keyedVnodes.length;\n let reused = 0;\n let updatedKeys = 0;\n const t0 = now();\n\n for (let i = 0; i < total; i++) {\n const { key, vnode } = keyedVnodes[i];\n const ch = parent.children[i] as Element | undefined;\n\n if (\n ch &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const vnodeType = (vnode as DOMElement).type as string;\n\n if (ch.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n\n logFastPathDebug('positional idx', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n chChildNodes: ch.childNodes.length,\n childrenType: Array.isArray(children) ? 'array' : typeof children,\n });\n\n updateTextContent(ch, children);\n setDataKey(ch, key, () => updatedKeys++);\n reused++;\n continue;\n } else {\n logFastPathDebug('positional tag mismatch', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n });\n }\n } else {\n logFastPathDebug('positional missing or invalid', i, { ch: !!ch });\n }\n\n // Fallback: replace the node at position i\n replaceNodeAtPosition(parent, i, vnode);\n }\n\n const t = now() - t0;\n updateKeyedElementsMap(parent, keyedVnodes);\n\n const stats = { n: total, reused, updatedKeys, t } as const;\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n return stats;\n}\n\n/** Update text content of element from children prop */\nfunction updateTextContent(el: Element, children: unknown): void {\n if (typeof children === 'string' || typeof children === 'number') {\n setTextNodeData(el, String(children));\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n setTextNodeData(el, String(children[0]));\n } else {\n updateElementFromVnode(el, el as unknown as VNode);\n }\n}\n\n/** Set text node data or textContent */\nfunction setTextNodeData(el: Element, text: string): void {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = text;\n } else {\n el.textContent = text;\n }\n}\n\n/** Set data-key attribute with counter callback */\nfunction setDataKey(\n el: Element,\n key: string | number,\n onSet: () => void\n): void {\n try {\n el.setAttribute('data-key', String(key));\n onSet();\n } catch {\n // Ignore errors setting data-key\n }\n}\n\n/** Replace node at position with new vnode */\nfunction replaceNodeAtPosition(\n parent: Element,\n index: number,\n vnode: VNode\n): void {\n const dom = createDOMNode(vnode);\n if (dom) {\n const existing = parent.children[index];\n if (existing) {\n cleanupInstanceIfPresent(existing);\n parent.replaceChild(dom, existing);\n } else {\n parent.appendChild(dom);\n }\n }\n}\n\n/** Update keyed elements map after bulk operation */\nfunction updateKeyedElementsMap(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): void {\n try {\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n const ch = parent.children[i] as Element | undefined;\n if (ch) newKeyMap.set(k, ch);\n }\n keyedElements.set(parent, newKeyMap);\n } catch {\n // Ignore errors updating key map\n }\n}\n\nexport function performBulkTextReplace(parent: Element, newChildren: VNode[]) {\n const t0 = now();\n const existing = Array.from(parent.childNodes);\n const finalNodes: Node[] = [];\n let reused = 0;\n let created = 0;\n\n for (let i = 0; i < newChildren.length; i++) {\n const result = processChildNode(newChildren[i], existing[i], finalNodes);\n if (result === 'reused') reused++;\n else if (result === 'created') created++;\n }\n\n const tBuild = now() - t0;\n cleanupRemovedNodes(parent, finalNodes);\n const tCommit = commitBulkReplace(parent, finalNodes);\n\n // Clear keyed map for unkeyed path\n keyedElements.delete(parent);\n\n const stats = {\n n: newChildren.length,\n reused,\n created,\n tBuild,\n tCommit,\n } as const;\n recordBulkTextStats(stats);\n\n return stats;\n}\n\n/** Process a single child vnode for bulk replace */\nfunction processChildNode(\n vnode: VNode,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' | 'skipped' {\n if (typeof vnode === 'string' || typeof vnode === 'number') {\n return processTextVnode(String(vnode), existingNode, finalNodes);\n }\n\n if (typeof vnode === 'object' && vnode !== null && 'type' in vnode) {\n return processElementVnode(vnode, existingNode, finalNodes);\n }\n\n return 'skipped';\n}\n\n/** Process text vnode */\nfunction processTextVnode(\n text: string,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' {\n if (existingNode && existingNode.nodeType === 3) {\n (existingNode as Text).data = text;\n finalNodes.push(existingNode);\n return 'reused';\n }\n finalNodes.push(document.createTextNode(text));\n return 'created';\n}\n\n/** Process element vnode */\nfunction processElementVnode(\n vnode: VNode,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' | 'skipped' {\n const vnodeObj = vnode as unknown as { type?: unknown };\n\n if (typeof vnodeObj.type === 'string') {\n const tag = vnodeObj.type;\n if (\n existingNode &&\n existingNode.nodeType === 1 &&\n (existingNode as Element).tagName.toLowerCase() === tag.toLowerCase()\n ) {\n updateElementFromVnode(existingNode as Element, vnode);\n finalNodes.push(existingNode);\n return 'reused';\n }\n }\n\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n return 'created';\n }\n return 'skipped';\n}\n\n/** Clean up nodes that will be removed */\nfunction cleanupRemovedNodes(parent: Element, keepNodes: Node[]): void {\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !keepNodes.includes(n)\n );\n for (const n of toRemove) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch {\n // Ignore cleanup errors\n }\n}\n\n/** Commit bulk replace with fragment */\nfunction commitBulkReplace(parent: Element, nodes: Node[]): number {\n const fragStart = Date.now();\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < nodes.length; i++) {\n fragment.appendChild(nodes[i]);\n }\n recordDOMReplace('bulk-text-replace');\n parent.replaceChildren(fragment);\n return Date.now() - fragStart;\n}\n\n/** Record bulk text fast-path stats */\nfunction recordBulkTextStats(stats: {\n n: number;\n reused: number;\n created: number;\n tBuild: number;\n tCommit: number;\n}): void {\n try {\n __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkTextFastpathHits');\n } catch {\n // Ignore stats errors\n }\n}\n\n/**\n * Heuristic to detect large bulk text-dominant updates eligible for fast-path.\n * Conditions:\n * - total children >= threshold\n * - majority of children are simple text (string/number) or intrinsic elements\n * with a single primitive child\n * - conservative: avoid when component children or complex shapes present\n */\nexport function isBulkTextFastPathEligible(\n parent: Element,\n newChildren: VNode[]\n) {\n const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;\n const requiredFraction = 0.8;\n\n const total = Array.isArray(newChildren) ? newChildren.length : 0;\n\n if (total < threshold) {\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n reason: 'too-small',\n total,\n threshold,\n });\n return false;\n }\n\n const result = countSimpleChildren(newChildren);\n if (result.componentFound !== undefined) {\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n reason: 'component-child',\n index: result.componentFound,\n });\n return false;\n }\n\n const fraction = result.simple / total;\n const eligible =\n fraction >= requiredFraction && parent.childNodes.length >= total;\n\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n total,\n simple: result.simple,\n fraction,\n requiredFraction,\n eligible,\n });\n\n return eligible;\n}\n\n/** Count simple children (text/number or simple intrinsic elements) */\nfunction countSimpleChildren(children: VNode[]): {\n simple: number;\n componentFound?: number;\n} {\n let simple = 0;\n\n for (let i = 0; i < children.length; i++) {\n const c = children[i];\n\n if (typeof c === 'string' || typeof c === 'number') {\n simple++;\n continue;\n }\n\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const dv = c as DOMElement;\n\n // Component child - decline fast path\n if (typeof dv.type === 'function') {\n return { simple, componentFound: i };\n }\n\n if (typeof dv.type === 'string' && isSimpleElement(dv)) {\n simple++;\n }\n }\n }\n\n return { simple };\n}\n\n/** Check if element is simple (empty or single text child) */\nfunction isSimpleElement(dv: DOMElement): boolean {\n const children = dv.children || dv.props?.children;\n\n if (!children) return true; // empty element\n\n if (typeof children === 'string' || typeof children === 'number') {\n return true;\n }\n\n if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n return true;\n }\n\n return false;\n}\n\n/** Record bulk diagnostics */\nfunction recordBulkDiag(data: Record<string, unknown>): void {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n __ASKR_set('__BULK_DIAG', data);\n } catch {\n // Ignore\n }\n }\n}\n","import type { VNode } from './types';\nimport { createDOMNode } from './dom';\nimport { _reconcilerRecordedParents } from './keyed';\nimport { logger } from '../dev/logger';\nimport { cleanupInstanceIfPresent, removeAllListeners } from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { isSchedulerExecuting } from '../runtime/scheduler';\nimport {\n isBulkCommitActive,\n markFastPathApplied,\n} from '../runtime/fastlane-shared';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Apply the \"renderer\" fast-path: build final node list reusing existing\n// elements by key when possible, then perform a single atomic replaceChildren\n// commit. Returns a new key map when the fast-path is applied, otherwise\n// returns null to indicate the caller should continue with fallback paths.\nexport function applyRendererFastPath(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap?: Map<string | number, Element>,\n unkeyedVnodes?: VNode[]\n): Map<string | number, Element> | null {\n // SSR guard: fast-path is DOM-specific\n if (typeof document === 'undefined') return null;\n\n const totalKeyed = keyedVnodes.length;\n if (totalKeyed === 0 && (!unkeyedVnodes || unkeyedVnodes.length === 0))\n return null;\n\n // Dev invariant: ensure we are executing inside the scheduler/commit flush\n if (!isSchedulerExecuting()) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path reconciliation invoked outside scheduler execution'\n );\n }\n\n // Choose lookup strategy depending on size (linear scan for small lists)\n let parentChildrenArr: Element[] | undefined;\n let localOldKeyMap: Map<string | number, Element> | undefined;\n\n if (totalKeyed <= 20) {\n try {\n const pc = parent.children;\n parentChildrenArr = new Array(pc.length);\n for (let i = 0; i < pc.length; i++)\n parentChildrenArr[i] = pc[i] as Element;\n } catch (e) {\n parentChildrenArr = undefined;\n void e;\n }\n } else {\n localOldKeyMap = new Map<string | number, Element>();\n try {\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const ch = parentChildren[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n localOldKeyMap.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);\n }\n }\n } catch (e) {\n localOldKeyMap = undefined;\n void e;\n }\n }\n\n const finalNodes: Node[] = [];\n let mapLookups = 0;\n let createdNodes = 0;\n let reusedCount = 0;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n mapLookups++;\n\n let el: Element | undefined;\n if (totalKeyed <= 20 && parentChildrenArr) {\n const ks = String(key);\n for (let j = 0; j < parentChildrenArr.length; j++) {\n const ch = parentChildrenArr[j];\n const k = ch.getAttribute('data-key');\n if (k !== null && (k === ks || Number(k) === (key as number))) {\n el = ch;\n break;\n }\n }\n if (!el) el = oldKeyMap?.get(key);\n } else {\n el = localOldKeyMap?.get(key as string | number) ?? oldKeyMap?.get(key);\n }\n\n if (el) {\n finalNodes.push(el);\n reusedCount++;\n } else {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Add unkeyed nodes (detached as well)\n if (unkeyedVnodes && unkeyedVnodes.length) {\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Atomic commit\n try {\n const tFragmentStart = Date.now();\n const fragment = document.createDocumentFragment();\n let fragmentAppendCount = 0;\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n fragmentAppendCount++;\n }\n\n // Pre-cleanup: remove component instances that will be removed by replaceChildren\n try {\n const existing = Array.from(parent.childNodes);\n // Only cleanup nodes that are *not* part of the finalNodes list so we don't\n // remove listeners from elements we're reusing (critical invariant)\n const toRemove = existing.filter((n) => !finalNodes.includes(n));\n for (const n of toRemove) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch (e) {\n void e;\n }\n\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set('__LAST_DOM_REPLACE_STACK_FASTPATH', new Error().stack);\n } catch (e) {\n void e;\n }\n\n parent.replaceChildren(fragment);\n\n // Record that we performed exactly one DOM commit.\n try {\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n } catch (e) {\n void e;\n }\n\n // If a runtime bulk commit is active, mark this parent as fast-path applied.\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n // Phase: bookkeeping - populate newKeyMap\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const node = finalNodes[i];\n if (node instanceof Element) newKeyMap.set(key, node as Element);\n }\n\n // Dev tracing\n try {\n const stats = {\n n: totalKeyed,\n moves: 0,\n lisLen: 0,\n t_lookup: 0,\n t_fragment: Date.now() - tFragmentStart,\n t_commit: 0,\n t_bookkeeping: 0,\n fragmentAppendCount,\n mapLookups,\n createdNodes,\n reusedCount,\n } as const;\n if (typeof globalThis !== 'undefined') {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_REUSED', reusedCount > 0);\n __ASKR_incCounter('fastpathHistoryPush');\n }\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH]',\n JSON.stringify({ n: totalKeyed, createdNodes, reusedCount })\n );\n }\n } catch (e) {\n void e;\n }\n\n // Record that reconciler recorded stats for this parent in this pass\n try {\n _reconcilerRecordedParents.add(parent);\n } catch (e) {\n void e;\n }\n\n return newKeyMap;\n } catch (e) {\n void e;\n return null;\n }\n}\n","import type { VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n performBulkPositionalKeyedTextUpdate,\n} from './dom';\nimport {\n keyedElements,\n _reconcilerRecordedParents,\n isKeyedReorderFastPathEligible,\n} from './keyed';\nimport { removeAllListeners, cleanupInstanceIfPresent } from './cleanup';\nimport { isBulkCommitActive } from '../runtime/fastlane-shared';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { applyRendererFastPath } from './fastpath';\nimport { logger } from '../dev/logger';\nimport {\n extractKey,\n checkPropChanges,\n recordFastPathStats,\n recordDOMReplace,\n} from './utils';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Helper type for narrowings\ntype VnodeObj = VNode & { type?: unknown; props?: Record<string, unknown> };\n\nexport function reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n logReconcileDebug(newChildren);\n\n const { keyedVnodes, unkeyedVnodes } = partitionChildren(newChildren);\n\n // Try fast paths first\n const fastPathResult = tryFastPaths(\n parent,\n newChildren,\n keyedVnodes,\n unkeyedVnodes,\n oldKeyMap\n );\n if (fastPathResult) return fastPathResult;\n\n // Full reconciliation\n return performFullReconciliation(parent, newChildren, keyedVnodes, oldKeyMap);\n}\n\n/** Log reconcile debug info */\nfunction logReconcileDebug(newChildren: VNode[]): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn(\n '[Askr][RECONCILE] reconcileKeyedChildren newChildren sample',\n {\n sample: (newChildren && newChildren.length && newChildren[0]) || null,\n len: newChildren.length,\n }\n );\n } catch {\n // Ignore\n }\n }\n}\n\n/** Partition children into keyed and unkeyed */\nfunction partitionChildren(newChildren: VNode[]): {\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>;\n unkeyedVnodes: VNode[];\n} {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n const unkeyedVnodes: VNode[] = [];\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const key = extractKey(child);\n if (key !== undefined) {\n keyedVnodes.push({ key, vnode: child });\n } else {\n unkeyedVnodes.push(child);\n }\n }\n\n return { keyedVnodes, unkeyedVnodes };\n}\n\n/** Try fast paths before full reconciliation */\nfunction tryFastPaths(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n unkeyedVnodes: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n try {\n // Try renderer fast-path for large keyed reorder-only updates\n const rendererResult = tryRendererFastPath(\n parent,\n newChildren,\n keyedVnodes,\n unkeyedVnodes,\n oldKeyMap\n );\n if (rendererResult) return rendererResult;\n\n // Try positional bulk update for medium-sized lists\n const positionalResult = tryPositionalBulkUpdate(parent, keyedVnodes);\n if (positionalResult) return positionalResult;\n } catch {\n // Fall through to full reconciliation\n }\n\n return null;\n}\n\n/** Try renderer fast-path */\nfunction tryRendererFastPath(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n unkeyedVnodes: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n const decision = isKeyedReorderFastPathEligible(\n parent,\n newChildren,\n oldKeyMap\n );\n\n if (\n (decision.useFastPath && keyedVnodes.length >= 128) ||\n isBulkCommitActive()\n ) {\n try {\n const map = applyRendererFastPath(\n parent,\n keyedVnodes,\n oldKeyMap,\n unkeyedVnodes\n );\n if (map) {\n keyedElements.set(parent, map);\n return map;\n }\n } catch {\n // Fall through\n }\n }\n\n return null;\n}\n\n/** Try positional bulk update for medium-sized lists */\nfunction tryPositionalBulkUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n const total = keyedVnodes.length;\n if (total < 10) return null;\n\n const matchCount = countPositionalMatches(parent, keyedVnodes);\n\n logPositionalCheck(total, matchCount, parent.children.length);\n\n // Require high positional match fraction\n if (matchCount / total < 0.9) return null;\n\n // Check for prop changes that would prevent positional update\n if (hasPositionalPropChanges(parent, keyedVnodes)) return null;\n\n // Perform positional update\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Count how many vnodes match parent children by position and tag */\nfunction countPositionalMatches(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): number {\n let matchCount = 0;\n\n try {\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n if (!vnode || typeof vnode !== 'object' || typeof vnode.type !== 'string')\n continue;\n\n const el = parent.children[i] as Element | undefined;\n if (!el) continue;\n\n if (el.tagName.toLowerCase() === String(vnode.type).toLowerCase()) {\n matchCount++;\n }\n }\n } catch {\n // Ignore\n }\n\n return matchCount;\n}\n\n/** Log positional check debug info */\nfunction logPositionalCheck(\n total: number,\n matchCount: number,\n parentChildren: number\n): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[Askr][FASTPATH] positional check', {\n total,\n matchCount,\n parentChildren,\n });\n } catch {\n // Ignore\n }\n }\n}\n\n/** Check if positional prop changes would prevent bulk update */\nfunction hasPositionalPropChanges(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): boolean {\n try {\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const el = parent.children[i] as Element | undefined;\n if (!el || !vnode || typeof vnode !== 'object') continue;\n\n if (checkPropChanges(el, vnode.props || {})) {\n return true;\n }\n }\n } catch {\n return true;\n }\n\n return false;\n}\n\n/** Rebuild keyed map from parent children */\nfunction rebuildKeyedMap(parent: Element): void {\n try {\n const map = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n\n for (let i = 0; i < children.length; i++) {\n const el = children[i] as Element;\n const k = el.getAttribute('data-key');\n if (k !== null) {\n map.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, el);\n }\n }\n\n keyedElements.set(parent, map);\n } catch {\n // Ignore\n }\n}\n\n/** Perform full reconciliation when fast paths don't apply */\nfunction performFullReconciliation(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n const finalNodes: Node[] = [];\n const usedOldEls = new WeakSet<Node>();\n\n const resolveOldElOnce = createOldElResolver(parent, oldKeyMap, usedOldEls);\n\n // Positional reconciliation\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const node = reconcileSingleChild(\n child,\n i,\n parent,\n resolveOldElOnce,\n usedOldEls,\n newKeyMap\n );\n if (node) finalNodes.push(node);\n }\n\n // SSR guard\n if (typeof document === 'undefined') return newKeyMap;\n\n commitReconciliation(parent, finalNodes);\n keyedElements.delete(parent);\n\n return newKeyMap;\n}\n\n/** Create resolver for finding old elements by key */\nfunction createOldElResolver(\n parent: Element,\n oldKeyMap: Map<string | number, Element> | undefined,\n usedOldEls: WeakSet<Node>\n): (k: string | number) => Element | undefined {\n return (k: string | number) => {\n if (!oldKeyMap) return undefined;\n\n // Fast-path: directly from oldKeyMap\n const direct = oldKeyMap.get(k);\n if (direct && !usedOldEls.has(direct)) {\n usedOldEls.add(direct);\n return direct;\n }\n\n // Try string form\n const s = String(k);\n const byString = oldKeyMap.get(s);\n if (byString && !usedOldEls.has(byString)) {\n usedOldEls.add(byString);\n return byString;\n }\n\n // Try numeric form\n const n = Number(s);\n if (!Number.isNaN(n)) {\n const byNum = oldKeyMap.get(n);\n if (byNum && !usedOldEls.has(byNum)) {\n usedOldEls.add(byNum);\n return byNum;\n }\n }\n\n // Fallback: scan parent children\n return scanForElementByKey(parent, k, s, usedOldEls);\n };\n}\n\n/** Scan parent children for element with matching key */\nfunction scanForElementByKey(\n parent: Element,\n k: string | number,\n keyStr: string,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n try {\n const children = Array.from(parent.children) as Element[];\n for (const ch of children) {\n if (usedOldEls.has(ch)) continue;\n const attr = ch.getAttribute('data-key');\n if (attr === keyStr) {\n usedOldEls.add(ch);\n return ch;\n }\n const numAttr = Number(attr);\n if (!Number.isNaN(numAttr) && numAttr === (k as number)) {\n usedOldEls.add(ch);\n return ch;\n }\n }\n } catch {\n // Ignore\n }\n return undefined;\n}\n\n/** Reconcile a single child */\nfunction reconcileSingleChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n usedOldEls: WeakSet<Node>,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n // Keyed child\n const key = extractKey(child);\n if (key !== undefined) {\n return reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap);\n }\n\n // Unkeyed or primitive child\n return reconcileUnkeyedChild(child, index, parent, usedOldEls);\n}\n\n/** Reconcile a keyed child */\nfunction reconcileKeyedChild(\n child: VNode,\n key: string | number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const el = resolveOldElOnce(key);\n\n if (el && el.parentElement === parent) {\n updateElementFromVnode(el, child);\n newKeyMap.set(key, el);\n return el;\n }\n\n const dom = createDOMNode(child);\n if (dom) {\n if (dom instanceof Element) newKeyMap.set(key, dom);\n return dom;\n }\n\n return null;\n}\n\n/** Reconcile an unkeyed or primitive child */\nfunction reconcileUnkeyedChild(\n child: VNode,\n index: number,\n parent: Element,\n usedOldEls: WeakSet<Node>\n): Node | null {\n try {\n const existing = parent.children[index] as Element | undefined;\n\n // Primitive child with existing element\n if (\n existing &&\n (typeof child === 'string' || typeof child === 'number') &&\n existing.nodeType === 1\n ) {\n existing.textContent = String(child);\n usedOldEls.add(existing);\n return existing;\n }\n\n // Element child matching existing unkeyed element\n if (canReuseElement(existing, child)) {\n updateElementFromVnode(existing!, child);\n usedOldEls.add(existing!);\n return existing!;\n }\n\n // Try to find available unkeyed element elsewhere\n const avail = findAvailableUnkeyedElement(parent, usedOldEls);\n if (avail) {\n const reuseResult = tryReuseElement(avail, child, usedOldEls);\n if (reuseResult) return reuseResult;\n }\n } catch {\n // Fall through to create new\n }\n\n const dom = createDOMNode(child);\n return dom;\n}\n\n/** Check if existing element can be reused for child */\nfunction canReuseElement(existing: Element | undefined, child: VNode): boolean {\n if (!existing) return false;\n if (typeof child !== 'object' || child === null || !('type' in child))\n return false;\n\n const childObj = child as VnodeObj;\n const hasNoKey =\n existing.getAttribute('data-key') === null ||\n existing.getAttribute('data-key') === undefined;\n\n return (\n hasNoKey &&\n typeof childObj.type === 'string' &&\n existing.tagName.toLowerCase() === String(childObj.type).toLowerCase()\n );\n}\n\n/** Find available unkeyed element in parent */\nfunction findAvailableUnkeyedElement(\n parent: Element,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n return Array.from(parent.children).find(\n (ch) => !usedOldEls.has(ch) && ch.getAttribute('data-key') === null\n );\n}\n\n/** Try to reuse available element for child */\nfunction tryReuseElement(\n avail: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (typeof child === 'string' || typeof child === 'number') {\n avail.textContent = String(child);\n usedOldEls.add(avail);\n return avail;\n }\n\n if (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as VnodeObj;\n if (\n typeof childObj.type === 'string' &&\n avail.tagName.toLowerCase() === String(childObj.type).toLowerCase()\n ) {\n updateElementFromVnode(avail, child);\n usedOldEls.add(avail);\n return avail;\n }\n }\n\n return null;\n}\n\n/** Commit reconciliation by replacing parent children */\nfunction commitReconciliation(parent: Element, finalNodes: Node[]): void {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n }\n\n // Cleanup existing nodes\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch {\n // Ignore\n }\n\n recordDOMReplace('reconcile');\n parent.replaceChildren(fragment);\n}\n","import { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { elementListeners } from './cleanup';\nimport { keyedElements } from './keyed';\nimport { reconcileKeyedChildren } from './reconcile';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n updateUnkeyedChildren,\n performBulkPositionalKeyedTextUpdate,\n performBulkTextReplace,\n isBulkTextFastPathEligible,\n} from './dom';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { Fragment } from '../jsx/types';\n\n/**\n * Internal marker for component-owned DOM ranges\n * Allows efficient partial DOM updates instead of clearing entire target\n */\ninterface DOMRange {\n start: Node; // Start marker (comment node)\n end: Node; // End marker (comment node)\n}\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\nconst domRanges = new WeakMap<object, DOMRange>();\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helper Types & Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface SimpleTextResult {\n isSimple: true;\n text: string;\n}\n\ninterface NotSimpleTextResult {\n isSimple: false;\n text?: undefined;\n}\n\ntype TextCheckResult = SimpleTextResult | NotSimpleTextResult;\n\n/**\n * Check if vnode children represent a simple text value\n */\nfunction checkSimpleText(vnodeChildren: unknown): TextCheckResult {\n if (!Array.isArray(vnodeChildren)) {\n if (\n typeof vnodeChildren === 'string' ||\n typeof vnodeChildren === 'number'\n ) {\n return { isSimple: true, text: String(vnodeChildren) };\n }\n } else if (vnodeChildren.length === 1) {\n const child = vnodeChildren[0];\n if (typeof child === 'string' || typeof child === 'number') {\n return { isSimple: true, text: String(child) };\n }\n }\n return { isSimple: false };\n}\n\n/**\n * Try to update a single text node in place\n * Returns true if update was performed, false otherwise\n */\nfunction tryUpdateTextInPlace(element: Element, text: string): boolean {\n if (\n element.childNodes.length === 1 &&\n element.firstChild?.nodeType === 3 // TEXT_NODE\n ) {\n (element.firstChild as Text).data = text;\n return true;\n }\n return false;\n}\n\n/**\n * Build a key map from existing DOM children\n */\nfunction buildKeyMapFromDOM(parent: Element): Map<string | number, Element> {\n const keyMap = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n for (const child of children) {\n const k = child.getAttribute('data-key');\n if (k !== null) {\n keyMap.set(k, child);\n const n = Number(k);\n if (!Number.isNaN(n)) keyMap.set(n, child);\n }\n }\n return keyMap;\n}\n\n/**\n * Get or initialize key map for an element\n */\nfunction getOrBuildKeyMap(\n parent: Element\n): Map<string | number, Element> | undefined {\n let keyMap = keyedElements.get(parent);\n if (!keyMap) {\n keyMap = buildKeyMapFromDOM(parent);\n if (keyMap.size > 0) {\n keyedElements.set(parent, keyMap);\n }\n }\n return keyMap.size > 0 ? keyMap : undefined;\n}\n\n/**\n * Check if children array contains keyed elements\n */\nfunction hasKeyedChildren(children: unknown[]): boolean {\n return children.some(\n (child) => typeof child === 'object' && child !== null && 'key' in child\n );\n}\n\n/**\n * Track bulk text fast-path stats (dev only)\n */\nfunction trackBulkTextStats(\n stats: ReturnType<typeof performBulkTextReplace>\n): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_incCounter('bulkTextHits');\n } catch {\n // ignore\n }\n }\n}\n\n/**\n * Track bulk text miss (dev only)\n */\nfunction trackBulkTextMiss(): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n __ASKR_incCounter('bulkTextMisses');\n } catch {\n // ignore\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Child Reconciliation Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reconcile keyed children with optional forced bulk path\n */\nfunction reconcileKeyed(\n parent: Element,\n children: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): void {\n // Optional forced positional bulk path for large keyed lists\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n const result = tryForcedBulkKeyedPath(parent, children);\n if (result) return;\n }\n\n // Standard keyed reconciliation\n const newKeyMap = reconcileKeyedChildren(parent, children, oldKeyMap);\n keyedElements.set(parent, newKeyMap);\n}\n\n/**\n * Try the forced bulk keyed positional path\n * Returns true if applied, false to fall back to normal reconciliation\n */\nfunction tryForcedBulkKeyedPath(parent: Element, children: VNode[]): boolean {\n try {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n for (const child of children) {\n if (_isDOMElement(child) && (child as DOMElement).key !== undefined) {\n keyedVnodes.push({\n key: (child as DOMElement).key as string | number,\n vnode: child,\n });\n }\n }\n\n // Only apply when all children are keyed and count matches\n if (keyedVnodes.length === 0 || keyedVnodes.length !== children.length) {\n return false;\n }\n\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)'\n );\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkKeyedPositionalForced');\n } catch {\n // ignore\n }\n }\n\n // Rebuild keyed map from DOM\n const newMap = buildKeyMapFromDOM(parent);\n keyedElements.set(parent, newMap);\n return true;\n } catch (err) {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced bulk path failed, falling back',\n err\n );\n }\n return false;\n }\n}\n\n/**\n * Reconcile unkeyed children, using bulk fast-path when eligible\n */\nfunction reconcileUnkeyed(parent: Element, children: VNode[]): void {\n if (isBulkTextFastPathEligible(parent, children)) {\n const stats = performBulkTextReplace(parent, children);\n trackBulkTextStats(stats);\n } else {\n trackBulkTextMiss();\n updateUnkeyedChildren(parent, children);\n }\n keyedElements.delete(parent);\n}\n\n/**\n * Update element children (handles keyed, unkeyed, and non-array cases)\n */\nfunction updateElementChildren(element: Element, vnodeChildren: unknown): void {\n if (!vnodeChildren) {\n element.textContent = '';\n keyedElements.delete(element);\n return;\n }\n\n if (!Array.isArray(vnodeChildren)) {\n element.textContent = '';\n const dom = createDOMNode(vnodeChildren);\n if (dom) element.appendChild(dom);\n keyedElements.delete(element);\n return;\n }\n\n if (hasKeyedChildren(vnodeChildren)) {\n const oldKeyMap = getOrBuildKeyMap(element);\n try {\n reconcileKeyed(element, vnodeChildren, oldKeyMap);\n } catch {\n // Fall back on error\n const newKeyMap = reconcileKeyedChildren(\n element,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(element, newKeyMap);\n }\n } else {\n reconcileUnkeyed(element, vnodeChildren);\n }\n}\n\n/**\n * Perform a smart update on an existing element\n * Tries text-in-place update first, then full child reconciliation\n */\nfunction smartUpdateElement(element: Element, vnode: DOMElement): void {\n const vnodeChildren = vnode.children || vnode.props?.children;\n const textCheck = checkSimpleText(vnodeChildren);\n\n if (textCheck.isSimple && tryUpdateTextInPlace(element, textCheck.text)) {\n // Text updated in place, nothing more to do for children\n } else {\n updateElementChildren(element, vnodeChildren);\n }\n\n updateElementFromVnode(element, vnode, false);\n}\n\n/**\n * Process Fragment children with smart updates for each child\n */\nfunction processFragmentChildren(target: Element, childArray: unknown[]): void {\n const existingChildren = Array.from(target.children) as Element[];\n\n for (let i = 0; i < childArray.length; i++) {\n const childVnode = childArray[i];\n const existingNode = existingChildren[i];\n\n // Apply the same smart update logic as the single-element case\n if (\n existingNode &&\n _isDOMElement(childVnode) &&\n typeof (childVnode as DOMElement).type === 'string' &&\n existingNode.tagName.toLowerCase() ===\n ((childVnode as DOMElement).type as string).toLowerCase()\n ) {\n // Same element type - do smart update\n smartUpdateElement(existingNode, childVnode as DOMElement);\n continue;\n }\n\n // Different type or no existing node - replace\n const newDom = createDOMNode(childVnode);\n if (newDom) {\n if (existingNode) {\n target.replaceChild(newDom, existingNode);\n } else {\n target.appendChild(newDom);\n }\n }\n }\n\n // Remove extra children\n while (target.children.length > childArray.length) {\n target.removeChild(target.lastChild!);\n }\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n */\nfunction createWrappedEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n };\n}\n\n/**\n * Apply props/attributes to an element (used for first render with keyed children)\n */\nfunction applyPropsToElement(el: Element, props: Props): void {\n for (const [key, value] of Object.entries(props)) {\n if (key === 'children' || key === 'key') continue;\n if (value === undefined || value === null || value === false) continue;\n\n if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n\n const wrappedHandler = createWrappedEventHandler(value as EventListener);\n\n const options: boolean | AddEventListenerOptions | undefined =\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ? { passive: true }\n : undefined;\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n options,\n });\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Props)[key] = value;\n } else {\n el.setAttribute(key, String(value));\n }\n }\n}\n\n/**\n * Try to handle first render of element with keyed children\n * Returns true if handled, false to fall back to default rendering\n */\nfunction tryFirstRenderKeyedChildren(\n target: Element,\n vnode: DOMElement\n): boolean {\n const children = vnode.children;\n if (!Array.isArray(children) || !hasKeyedChildren(children)) {\n return false;\n }\n\n const el = document.createElement(vnode.type as string);\n target.appendChild(el);\n\n applyPropsToElement(el, vnode.props || {});\n\n const newKeyMap = reconcileKeyedChildren(el, children, undefined);\n keyedElements.set(el, newKeyMap);\n return true;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fragment Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Check if a vnode is a Fragment\n */\nfunction isFragment(vnode: unknown): vnode is DOMElement {\n return (\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'symbol' &&\n ((vnode as DOMElement).type === Fragment ||\n String((vnode as DOMElement).type) === 'Symbol(askr.fragment)')\n );\n}\n\n/**\n * Unwrap Fragment to get children array\n */\nfunction getFragmentChildren(vnode: DOMElement): unknown[] {\n const fragmentChildren = vnode.props?.children || vnode.children || [];\n return Array.isArray(fragmentChildren)\n ? fragmentChildren\n : [fragmentChildren];\n}\n\nexport function evaluate(\n node: unknown,\n target: Element | null,\n context?: object\n): void {\n if (!target) return;\n // SSR guard: avoid DOM ops when not in a browser-like environment\n if (typeof document === 'undefined') {\n if (process.env.NODE_ENV !== 'production') {\n try {\n // Keep this lightweight and non-throwing so test harnesses and SSR\n // imports don't crash at runtime; callers should avoid calling\n // `evaluate` in SSR, but we make it safe as a no-op.\n console.warn('[Askr] evaluate() called in non-DOM environment; no-op.');\n } catch (e) {\n void e;\n }\n }\n return;\n }\n // Debug tracing to help understand why initial mounts sometimes don't\n // result in DOM mutations during tests.\n\n // If context provided, use component-owned DOM range (only replace that range)\n if (context && domRanges.has(context)) {\n const range = domRanges.get(context)!;\n // Remove all nodes between start and end markers\n let current = range.start.nextSibling;\n while (current && current !== range.end) {\n const next = current.nextSibling;\n current.remove();\n current = next;\n }\n // Append new DOM before end marker\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, range.end);\n }\n } else if (context) {\n // First render with context: create range markers\n const start = document.createComment('component-start');\n const end = document.createComment('component-end');\n target.appendChild(start);\n target.appendChild(end);\n domRanges.set(context, { start, end });\n // Render into the range\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, end);\n }\n } else {\n // Root render (no context): smart update strategy\n // If target has exactly one child of the same element type as the vnode,\n // reuse the element and just update its content.\n // This preserves the element reference and event handlers across renders.\n\n let vnode = node;\n\n // If vnode is a Fragment, unwrap it to get the actual content for the smart update path.\n // Fragments become invisible in the DOM - their children are placed directly in the parent.\n // So for smart updates, we need to compare against the Fragment's children, not the Fragment itself.\n if (isFragment(vnode)) {\n const childArray = getFragmentChildren(vnode as DOMElement);\n // If Fragment has exactly one child that's an element, unwrap to that child\n // This allows the smart update path to match against it\n if (\n childArray.length === 1 &&\n _isDOMElement(childArray[0]) &&\n typeof (childArray[0] as DOMElement).type === 'string'\n ) {\n vnode = childArray[0];\n } else {\n // Fragment with multiple children - process each child with full smart update logic\n processFragmentChildren(target, childArray);\n return;\n }\n }\n\n const firstChild = target.children[0] as Element | undefined;\n\n if (\n firstChild &&\n _isDOMElement(vnode) &&\n typeof vnode.type === 'string' &&\n firstChild.tagName.toLowerCase() === vnode.type.toLowerCase()\n ) {\n // Reuse the existing element - it's the same type\n smartUpdateElement(firstChild, vnode as DOMElement);\n } else {\n // Clear and rebuild (first render or structure changed)\n target.textContent = '';\n\n // Check if this is an element with keyed children even on first render\n if (\n _isDOMElement(vnode) &&\n typeof vnode.type === 'string' &&\n tryFirstRenderKeyedChildren(target, vnode as DOMElement)\n ) {\n return;\n }\n\n // Default: create whole tree\n const dom = createDOMNode(vnode);\n if (dom) {\n target.appendChild(dom);\n }\n }\n }\n}\n\nexport function clearDOMRange(context: object): void {\n domRanges.delete(context);\n}\n","// Renderer barrel entrypoint.\n// Keep this file small: re-export the public surface and attach the\n// runtime fast-lane bridge on import.\n\nexport * from './types';\nexport * from './cleanup';\nexport * from './keyed';\nexport * from './dom';\nexport { evaluate, clearDOMRange } from './evaluate';\n\nimport { evaluate as _evaluate } from './evaluate';\nimport { isKeyedReorderFastPathEligible, getKeyMapForElement } from './keyed';\n\n// Expose minimal renderer bridge for runtime fast-lane to call `evaluate`\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as Record<string, unknown>;\n _g.__ASKR_RENDERER = {\n evaluate: _evaluate,\n isKeyedReorderFastPathEligible,\n getKeyMapForElement,\n };\n}\n","/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport { logger } from '../dev/logger';\nimport { __ASKR_incCounter, __ASKR_set } from '../renderer/diag';\n\nexport type ComponentFunction = (\n props: Props,\n context?: { signal: AbortSignal }\n) => JSXElement | VNode | string | number | null;\n\ntype VNode = {\n type: string;\n props?: Props;\n children?: (string | VNode | null | undefined | false)[];\n};\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController; // Per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of state indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadStates?: Set<State<unknown>>; // States read during the in-progress render\n _lastReadStates?: Set<State<unknown>>; // States read during the last committed render\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: new AbortController(), // Create per-component\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadStates: new Set(),\n _lastReadStates: new Set(),\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n instance._pendingFlushTask = () => {\n // Called by state.set() when we want to flush a pending update\n instance.hasPendingUpdate = false;\n // Trigger a run via enqueue helper — this will schedule the component run\n instance._enqueueRun?.();\n };\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane-shared';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n for (const operation of instance.mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element)\n (\n target as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n\n // Atomic rendering: capture DOM state for rollback on error\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) return;\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n try {\n evaluate(result, host);\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n finalizeReadSubscriptions(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n // Keep `oldChildren` in the outer scope so rollback handlers can\n // reference the original node list even if the inner try block\n // throws. This preserves listeners and instance backrefs on rollback.\n let oldChildren: Node[] = [];\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n try {\n evaluate(result, instance.target);\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n for (const n of newChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n for (const n of currentChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadStates;\n if (!hadToken) {\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // because the component is effectively committed as part of the parent's\n // synchronous evaluation.\n if (!hadToken) {\n finalizeReadSubscriptions(instance);\n }\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadStates = prevPendingReads ?? new Set();\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Reset state index tracking for this render\n instance.stateIndexCheck = -1;\n\n // Reset read tracking for all existing state\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n // Prepare pending read set for this render (reads will be finalized on commit)\n instance._pendingReadStates = new Set();\n\n currentInstance = instance;\n stateIndex = 0;\n\n try {\n // Track render time in dev mode\n const renderStartTime =\n process.env.NODE_ENV !== 'production' ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n signal: instance.abortController.signal,\n };\n\n // Execute component within its owner frame (provider chain).\n // This ensures all context reads see the correct provider values.\n // We create a new execution frame whose parent is the ownerFrame. The\n // `values` map is lazily allocated to avoid per-render Map allocations\n // for components that do not use context.\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, () =>\n instance.fn(instance.props, context)\n );\n\n // Check render time\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n // Warn if render takes more than 5ms\n logger.warn(\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n // Check for unused state\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n if (state && !state._hasBeenRead) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n logger.warn(\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n logger.warn(\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Create a fresh abort controller on mount to allow remounting\n // (old one may have been aborted during previous cleanup)\n instance.abortController = new AbortController();\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(() => runComponent(instance));\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return currentInstance.abortController.signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n const newSet = instance._pendingReadStates ?? new Set();\n const oldSet = instance._lastReadStates ?? new Set();\n const token = instance._currentRenderToken;\n\n if (token === undefined) return;\n\n // Remove subscriptions for states that were read previously but not in this render\n for (const s of oldSet) {\n if (!newSet.has(s)) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n }\n\n // Commit token becomes the authoritative token for this instance's last render\n instance.lastRenderToken = token;\n\n // Record subscriptions for states read during this render\n for (const s of newSet) {\n let readers = (s as State<unknown>)._readers;\n if (!readers) {\n readers = new Map();\n // s is a State object; assign its _readers map\n (s as State<unknown>)._readers = readers;\n }\n readers.set(instance, instance.lastRenderToken ?? 0);\n }\n\n instance._lastReadStates = newSet;\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n // Execute cleanup functions (from mount effects)\n const cleanupErrors: unknown[] = [];\n for (const cleanup of instance.cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else {\n // Preserve previous behavior: log warnings in dev and continue\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('[Askr] cleanup function threw:', err);\n }\n }\n }\n }\n instance.cleanupFns = [];\n if (cleanupErrors.length > 0) {\n // If strict mode, surface all cleanup errors as an AggregateError after attempting all cleanups\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n\n // Remove deterministic state subscriptions for this instance\n if (instance._lastReadStates) {\n for (const s of instance._lastReadStates) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n instance._lastReadStates = new Set();\n }\n\n // Abort all pending operations\n instance.abortController.abort();\n\n // Clear update callback to prevent dangling references and stale updates\n instance.notifyUpdate = null;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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ateElementChildren","applyPropsToElement","isBulkCommitActive","e","getSpecificity"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/navigate.ts"],"sourcesContent":["/**\n * Client-side navigation with History API\n */\n\nimport { resolveRoute, lockRouteRegistration } from './route';\nimport {\n mountComponent,\n cleanupComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport { logger } from '../dev/logger';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\n\n/**\n * Register the current app instance (called by createIsland)\n */\nexport function registerAppInstance(\n instance: ComponentInstance,\n _path: string\n): void {\n currentInstance = instance;\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (process.env.NODE_ENV === 'production') {\n lockRouteRegistration();\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n // Resolve the new path to a route\n const resolved = resolveRoute(path);\n\n if (!resolved) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n // Update browser history\n window.history.pushState({ path }, '', path);\n\n // Re-render with the new route handler and params\n if (currentInstance) {\n // Cleanup previous route (abort pending operations)\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n // It takes params as props and renders the route\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for new route\n // Old controller is already aborted; we need a fresh one for async operations\n currentInstance.abortController = new AbortController();\n\n // Re-execute and re-mount component\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const path = window.location.pathname;\n\n if (!currentInstance) {\n return;\n }\n\n const resolved = resolveRoute(path);\n\n if (resolved) {\n // Cleanup old component\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for back/forward navigation\n currentInstance.abortController = new AbortController();\n\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window !== 'undefined') {\n window.addEventListener('popstate', handlePopState);\n }\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n if (typeof window !== 'undefined') {\n window.removeEventListener('popstate', handlePopState);\n }\n}\n"],"mappings":";;;;;;;;;AAaA,IAAI,kBAA4C;AAKzC,SAAS,oBACd,UACA,OACM;AACN,oBAAkB;AAGlB,MAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,0BAAsB;AAAA,EACxB;AACF;AAMO,SAAS,SAAS,MAAoB;AAC3C,MAAI,OAAO,WAAW,aAAa;AAEjC;AAAA,EACF;AAGA,QAAM,WAAW,aAAa,IAAI;AAElC,MAAI,CAAC,UAAU;AACb,QAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,aAAO,KAAK,4BAA4B,IAAI,EAAE;AAAA,IAChD;AACA;AAAA,EACF;AAGA,SAAO,QAAQ,UAAU,EAAE,KAAK,GAAG,IAAI,IAAI;AAG3C,MAAI,iBAAiB;AAEnB,qBAAiB,eAAe;AAIhC,oBAAgB,KAAK,SAAS;AAC9B,oBAAgB,QAAQ,SAAS;AAIjC,oBAAgB,cAAc,CAAC;AAC/B,oBAAgB,uBAAuB,CAAC;AACxC,oBAAgB,sBAAsB;AACtC,oBAAgB,kBAAkB;AAElC,oBAAgB;AAChB,oBAAgB,eAAe;AAI/B,oBAAgB,kBAAkB,IAAI,gBAAgB;AAGtD,mBAAe,eAAe;AAAA,EAChC;AACF;AAKA,SAAS,eAAe,QAA6B;AACnD,QAAM,OAAO,OAAO,SAAS;AAE7B,MAAI,CAAC,iBAAiB;AACpB;AAAA,EACF;AAEA,QAAM,WAAW,aAAa,IAAI;AAElC,MAAI,UAAU;AAEZ,qBAAiB,eAAe;AAGhC,oBAAgB,KAAK,SAAS;AAC9B,oBAAgB,QAAQ,SAAS;AAGjC,oBAAgB,cAAc,CAAC;AAC/B,oBAAgB,uBAAuB,CAAC;AACxC,oBAAgB,sBAAsB;AACtC,oBAAgB,kBAAkB;AAElC,oBAAgB;AAChB,oBAAgB,eAAe;AAG/B,oBAAgB,kBAAkB,IAAI,gBAAgB;AAEtD,mBAAe,eAAe;AAAA,EAChC;AACF;AAKO,SAAS,uBAA6B;AAC3C,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,iBAAiB,YAAY,cAAc;AAAA,EACpD;AACF;AAKO,SAAS,oBAA0B;AACxC,MAAI,OAAO,WAAW,aAAa;AACjC,WAAO,oBAAoB,YAAY,cAAc;AAAA,EACvD;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/jsx/types.ts"],"sourcesContent":["/**\n * JSX type definitions\n *\n * These define the canonical JSX element shape used by:\n * - jsx-runtime\n * - jsx-dev-runtime\n * - Slot / cloneElement\n * - the reconciler\n */\n\nimport type { Props } from '../shared/types';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n /** Internal element marker (optional for plain vnode objects) */\n $$typeof?: symbol;\n\n /** Element type: string, component, Fragment, etc */\n type: unknown;\n\n /** Props bag */\n props: Props;\n\n /** Optional key (normalized by runtime) */\n key?: string | number | null;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n // Components must be synchronous\n type Element = JSXElement;\n\n interface IntrinsicElements {\n [elem: string]: Props;\n }\n\n interface ElementAttributesProperty {\n props: Props;\n }\n }\n}\n\nexport {};\n"],"mappings":";;;;;;;AAYO,IAAM,eAAe,uBAAO,IAAI,cAAc;AAC9C,IAAM,WAAW,uBAAO,IAAI,eAAe;","names":[]}