@askrjs/askr 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +298 -0
- package/dist/chunk-4CV4JOE5.js +27 -0
- package/dist/chunk-4CV4JOE5.js.map +1 -0
- package/dist/chunk-HIWJVOS4.js +503 -0
- package/dist/chunk-HIWJVOS4.js.map +1 -0
- package/dist/chunk-L7RL4LYV.js +3442 -0
- package/dist/chunk-L7RL4LYV.js.map +1 -0
- package/dist/chunk-UUM5W2RM.js +84 -0
- package/dist/chunk-UUM5W2RM.js.map +1 -0
- package/dist/chunk-YNH3D4KW.js +29 -0
- package/dist/chunk-YNH3D4KW.js.map +1 -0
- package/dist/index.cjs +4733 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +446 -0
- package/dist/index.d.ts +446 -0
- package/dist/index.js +683 -0
- package/dist/index.js.map +1 -0
- package/dist/jsx/jsx-dev-runtime.cjs +40 -0
- package/dist/jsx/jsx-dev-runtime.cjs.map +1 -0
- package/dist/jsx/jsx-dev-runtime.d.cts +16 -0
- package/dist/jsx/jsx-dev-runtime.d.ts +16 -0
- package/dist/jsx/jsx-dev-runtime.js +16 -0
- package/dist/jsx/jsx-dev-runtime.js.map +1 -0
- package/dist/jsx/jsx-runtime.cjs +45 -0
- package/dist/jsx/jsx-runtime.cjs.map +1 -0
- package/dist/jsx/jsx-runtime.d.cts +17 -0
- package/dist/jsx/jsx-runtime.d.ts +17 -0
- package/dist/jsx/jsx-runtime.js +14 -0
- package/dist/jsx/jsx-runtime.js.map +1 -0
- package/dist/navigate-NLQOZQGM.js +16 -0
- package/dist/navigate-NLQOZQGM.js.map +1 -0
- package/dist/route-TVYWYCEJ.js +31 -0
- package/dist/route-TVYWYCEJ.js.map +1 -0
- package/dist/ssr-4ELUFK65.js +24 -0
- package/dist/ssr-4ELUFK65.js.map +1 -0
- package/dist/types-DUDmnzD8.d.cts +38 -0
- package/dist/types-DUDmnzD8.d.ts +38 -0
- package/package.json +83 -0
- package/src/jsx/jsx-dev-runtime.ts +26 -0
- package/src/jsx/jsx-runtime.ts +36 -0
- package/src/jsx/react-jsx-runtime.d.ts +0 -0
- package/src/jsx/types.ts +27 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/dev/invariant.ts","../src/dev/logger.ts","../src/runtime/scheduler.ts","../src/runtime/fastlane.ts","../src/jsx/jsx-runtime.ts","../src/runtime/context.ts","../src/renderer/dom.ts","../src/runtime/component.ts","../src/ssr/errors.ts","../src/ssr/context.ts","../src/ssr/data.ts","../src/router/match.ts","../src/router/route.ts","../src/router/navigate.ts","../src/ssr/sink.ts","../src/ssr/render.ts","../src/ssr/index.ts","../src/index.ts","../src/runtime/state.ts","../src/runtime/operations.ts","../src/runtime/resource_cell.ts","../src/app/createApp.ts","../src/router/layouts.ts","../src/components/Link.tsx"],"sourcesContent":["/**\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 unknown 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 unknown 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 diag = {\n flushVersion: this.flushVersion,\n queueLen: this.q.length - this.head,\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n globals: {\n __ASKR_LAST_FASTPATH_STATS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_LAST_FASTPATH_STATS,\n __ASKR_LAST_BULK_TEXT_FASTPATH_STATS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_LAST_BULK_TEXT_FASTPATH_STATS,\n __ASKR_FASTPATH_COUNTERS: (\n globalThis as unknown as Record<string, unknown>\n ).__ASKR_FASTPATH_COUNTERS,\n },\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","import { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n} from '../renderer/dom';\nimport type { ComponentInstance } from './component';\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. This is a safety\n // barrier to enforce quiescence for bulk commits.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_CLEARED_TASKS = cleared;\n }\n } catch (err) {\n // In the unlikely event clearing fails in production, ignore it; in dev rethrow\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\n/**\n * Attempt to execute a runtime fast-lane for a single component's synchronous\n * render result. Returns true if the fast-lane was used and commit was done.\n *\n * Preconditions (checked conservatively):\n * - The render result is an intrinsic element root with keyed children\n * - The renderer's fast-path heuristics indicate to use the fast-path\n * - No mount operations are pending on the component instance\n * - No child vnodes are component functions (avoid async/component mounts)\n */\nexport function classifyUpdate(instance: ComponentInstance, result: unknown) {\n // Returns a classification describing whether this update is eligible for\n // the reorder-only fast-lane. The classifier mirrors renderer-level\n // heuristics and performs runtime-level checks (mounts, effects, component\n // children) that the renderer cannot reason about.\n if (!result || typeof result !== 'object' || !('type' in result))\n return { useFastPath: false, reason: 'not-vnode' };\n const vnode = result as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n if (vnode == null || typeof vnode.type !== 'string')\n return { useFastPath: false, reason: 'not-intrinsic' };\n\n const parent = instance.target;\n if (!parent) return { useFastPath: false, reason: 'no-root' };\n\n const firstChild = parent.children[0] as Element | undefined;\n if (!firstChild) return { useFastPath: false, reason: 'no-first-child' };\n if (firstChild.tagName.toLowerCase() !== String(vnode.type).toLowerCase())\n return { useFastPath: false, reason: 'root-tag-mismatch' };\n\n const children =\n (vnode as { children?: unknown; props?: { children?: unknown } })\n .children ||\n (vnode as { props?: { children?: unknown } }).props?.children;\n if (!Array.isArray(children))\n return { useFastPath: false, reason: 'no-children-array' };\n\n // Avoid component child vnodes (they may mount/unmount or trigger async)\n for (let i = 0; i < children.length; i++) {\n const c = children[i];\n if (\n typeof c === 'object' &&\n c !== null &&\n 'type' in c &&\n typeof (c as { type?: unknown }).type === 'function'\n ) {\n return { useFastPath: false, reason: 'component-child-present' };\n }\n }\n\n if (instance.mountOperations.length > 0)\n return { useFastPath: false, reason: 'pending-mounts' };\n\n // Ask renderer for keyed reorder eligibility (prop differences & heuristics)\n const oldKeyMap = getKeyMapForElement(firstChild);\n const decision = isKeyedReorderFastPathEligible(\n firstChild,\n children,\n oldKeyMap\n );\n\n if (!decision.useFastPath || decision.totalKeyed < 128)\n return { ...decision, useFastPath: false, reason: 'renderer-declined' };\n\n return { ...decision, useFastPath: true } as const;\n}\n\nexport function commitReorderOnly(\n instance: ComponentInstance,\n result: unknown\n) {\n // Performs the minimal, synchronous reorder-only commit. Sets dev-only\n // diagnostic fields on globalThis for test assertions and verifies\n // invariants (no mounts, no effects, single DOM commit).\n const evaluate = (\n globalThis as unknown as {\n __ASKR_RENDERER?: {\n evaluate?: (node: unknown, target: Element | null) => void;\n };\n }\n ).__ASKR_RENDERER?.evaluate;\n if (typeof evaluate !== 'function') {\n logger.warn(\n '[Tempo][FASTPATH][DEV] renderer.evaluate not available; declining fast-lane'\n );\n return false;\n }\n\n const schedBefore =\n process.env.NODE_ENV !== 'production' ? globalScheduler.getState() : null;\n\n enterBulkCommit();\n\n try {\n // Execute the renderer synchronously inside a controlled scheduler\n // escape hatch that allows deterministic synchronous scheduler progress\n // while still preserving bulk-commit semantics (no async tasks, single DOM\n // mutation, and rollback safety).\n globalScheduler.runWithSyncProgress(() => {\n evaluate(result, instance.target);\n\n // Ensure runtime bookkeeping (read subscriptions / tokens) is finalized\n // even when we bypass the normal scheduler-driven commit path.\n try {\n // Import function dynamically to avoid circular import at module top-level\n // (component module defines finalizeReadSubscriptions).\n // eslint-disable-next-line @typescript-eslint/no-require-imports -- circular import; require used intentionally to perform a synchronous call\n const comp = require('./component') as typeof import('./component');\n if (typeof comp?.finalizeReadSubscriptions === 'function') {\n try {\n comp.finalizeReadSubscriptions(instance);\n } catch (e) {\n // Surface in dev, ignore in prod\n if (process.env.NODE_ENV !== 'production') throw e;\n }\n }\n } catch (e) {\n void e;\n }\n });\n\n // Safety: clear any synchronous tasks that were scheduled during the commit\n // but did not get executed due to flush reentrancy or microtask timing. This\n // ensures final quiescence for bulk commits.\n try {\n const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_CLEARED_AFTER = clearedAfter;\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Dev-only invariant checks and diagnostics\n if (process.env.NODE_ENV !== 'production') {\n // Commit count recorded by renderer (set by fast-path code)\n const _g = globalThis as unknown as Record<string, unknown>;\n const commitCount =\n (_g.__ASKR_LAST_FASTPATH_COMMIT_COUNT as number | undefined) ?? 0;\n const invariants = {\n commitCount,\n mountOps: instance.mountOperations.length,\n cleanupFns: instance.cleanupFns.length,\n } as const;\n _g.__ASKR_LAST_FASTLANE_INVARIANTS = invariants;\n\n if (commitCount !== 1) {\n throw new Error(\n 'Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit'\n );\n }\n if (invariants.mountOps > 0) {\n throw new Error(\n 'Fast-lane invariant violated: mount operations were registered during bulk commit'\n );\n }\n if (invariants.cleanupFns > 0) {\n throw new Error(\n 'Fast-lane invariant violated: cleanup functions were added during bulk commit'\n );\n }\n\n const schedAfter = globalScheduler.getState();\n if (\n schedBefore &&\n schedAfter &&\n // Only fail if outstanding tasks increased — consuming existing tasks is allowed\n schedAfter.taskCount > schedBefore.taskCount\n ) {\n try {\n console.error(\n '[FASTLANE] schedBefore, schedAfter',\n schedBefore,\n schedAfter\n );\n\n console.error(\n '[FASTLANE] enqueue logs',\n (globalThis as unknown as Record<string, unknown>)\n .__ASKR_ENQUEUE_LOGS\n );\n } catch (e) {\n void e;\n }\n throw new Error(\n 'Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit'\n );\n }\n\n // Final quiescence assertion: ensure scheduler has no pending sync tasks\n let finalState = globalScheduler.getState();\n // Adjust expected task count by subtracting the currently executing task\n // (we're inside that task at the time of this check). The goal is to\n // ensure there are no *other* pending tasks beyond the active execution.\n const executing = globalScheduler.isExecuting();\n const outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (executing ? 1 : 0)\n );\n\n if (outstandingAfter !== 0) {\n // Attempt to clear newly enqueued synchronous tasks that may have\n // been scheduled in microtasks or during remaining flush operations.\n // This loop is conservative and only runs in dev to help catch\n // flaky microtask timing windows; in prod we prefer to fail-safe by\n // dropping such tasks earlier.\n if (process.env.NODE_ENV !== 'production') {\n let attempts = 0;\n while (attempts < 5) {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n if (cleared === 0) break;\n attempts++;\n }\n finalState = globalScheduler.getState();\n const outstandingAfter2 = Math.max(\n 0,\n finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)\n );\n if (outstandingAfter2 !== 0) {\n try {\n const _g = globalThis as unknown as Record<string, unknown>;\n\n console.error(\n '[FASTLANE] Post-commit enqueue logs:',\n _g.__ASKR_ENQUEUE_LOGS\n );\n\n console.error(\n '[FASTLANE] Cleared counts:',\n _g.__ASKR_FASTLANE_CLEARED_TASKS,\n _g.__ASKR_FASTLANE_CLEARED_AFTER\n );\n } catch (err) {\n void err;\n }\n throw new Error(\n `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) after commit`\n );\n }\n } else {\n // In production, silently drop remaining synchronous tasks to preserve\n // atomicity and avoid leaving the system in a non-quiescent state.\n globalScheduler.clearPendingSyncTasks?.();\n }\n }\n }\n\n return true;\n } finally {\n exitBulkCommit();\n\n // Dev-time: ensure the bulk commit flag was cleared by the end of the operation\n // NOTE: avoid throwing inside `finally` (no-unsafe-finally). Capture the\n // failure and rethrow after the finally block.\n // We set a flag on `globalThis` to check after the finally, which will be\n // handled below.\n if (process.env.NODE_ENV !== 'production') {\n try {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE_BULK_FLAG_CHECK = isBulkCommitActive();\n } catch (e) {\n void e;\n }\n }\n }\n\n // Re-check the captured assertion outside of finally and throw if needed\n if (process.env.NODE_ENV !== 'production') {\n const _g = globalThis as unknown as Record<string, unknown>;\n if (_g.__ASKR_FASTLANE_BULK_FLAG_CHECK) {\n delete _g.__ASKR_FASTLANE_BULK_FLAG_CHECK;\n throw new Error(\n 'Fast-lane invariant violated: bulk commit flag still set after commit'\n );\n }\n }\n}\n\nexport function tryRuntimeFastLaneSync(\n instance: ComponentInstance,\n result: unknown\n): boolean {\n const cls = classifyUpdate(instance, result);\n if (!cls.useFastPath) return false;\n\n try {\n return commitReorderOnly(instance, result);\n } catch (err) {\n // Surface dev-only invariant failures, otherwise decline silently\n if (process.env.NODE_ENV !== 'production') throw err;\n return false;\n }\n}\n\n// Expose fastlane bridge on globalThis for environments/tests that access it\n// synchronously without using ES module dynamic imports.\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_FASTLANE = {\n isBulkCommitActive,\n enterBulkCommit,\n exitBulkCommit,\n tryRuntimeFastLaneSync,\n markFastPathApplied,\n isFastPathApplied,\n };\n}\n","/**\n * JSX runtime factory\n * Thin layer — no scheduling, no logic\n */\n\nimport './types';\n\nexport interface JSXElement {\n type: unknown;\n props: Record<string, unknown>;\n key?: string | number;\n}\n\nexport function jsx(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n): JSXElement {\n return {\n type,\n props: props || {},\n key,\n };\n}\n\nexport function jsxs(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n): JSXElement {\n return jsx(type, props, key);\n}\n\n// Fragment for rendering multiple elements without wrapper\n// Unique fragment symbol for Askr\nexport const Fragment = Symbol.for('@askrjs/askr.Fragment');\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';\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: T; 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: T; children?: unknown }): JSXElement => {\n // Scope component: creates a new frame and renders children within it\n return {\n type: ContextScopeComponent,\n props: { key, value: props.value, children: props.children },\n } as unknown 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 // 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 {\n type: ContextFunctionChildInvoker,\n props: {\n fn: child as () => Renderable,\n __frame: newFrame,\n __owner: getCurrentComponentInstance(),\n },\n } as unknown as Renderable;\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 {\n type: ContextFunctionChildInvoker,\n props: {\n fn: children as () => Renderable,\n __frame: newFrame,\n __owner: getCurrentComponentInstance(),\n },\n } as unknown as Renderable;\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}): 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\n/**\n * Deprecated aliases for backward compatibility\n * These should not be used in new code\n */\nexport function executeWithinFrame<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n return withContext(frame, fn);\n}\n","/**\n * DOM mounting and updates\n * Direct DOM manipulation, no VDOM - heavily optimized for speed\n */\n\nimport { globalScheduler, isSchedulerExecuting } from '../runtime/scheduler';\nimport {\n isBulkCommitActive,\n markFastPathApplied,\n isFastPathApplied,\n} from '../runtime/fastlane';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { Fragment } from '../jsx/jsx-runtime';\nimport {\n CONTEXT_FRAME_SYMBOL,\n type ContextFrame,\n withContext,\n getCurrentContextFrame,\n} from '../runtime/context';\nimport {\n createComponentInstance,\n renderComponentInline,\n mountInstanceInline,\n cleanupComponent,\n} from '../runtime/component';\nimport type {\n ComponentFunction,\n ComponentInstance,\n} from '../runtime/component';\n\ntype InstanceHost = Element & { __ASKR_INSTANCE?: ComponentInstance };\n\n// Helpers to clean up component instances when their host DOM nodes are removed\nfunction cleanupInstanceIfPresent(node: Node | null): void {\n if (!node) return;\n if (!(node instanceof Element)) return;\n try {\n const inst = (node as InstanceHost).__ASKR_INSTANCE;\n if (inst) {\n cleanupComponent(inst);\n try {\n delete (node as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n void e;\n }\n }\n } catch (err) {\n // Swallow cleanup errors but keep a reference to avoid empty-block lint error\n void err;\n }\n\n // Also attempt to clean up any nested instances that may be attached\n // on descendants (defensive: some components may attach to deeper nodes)\n try {\n const descendants = node.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n const inst = (d as InstanceHost).__ASKR_INSTANCE;\n if (inst) {\n cleanupComponent(inst);\n try {\n delete (d as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n void e;\n }\n }\n } catch (err) {\n void err;\n }\n }\n } catch (err) {\n void err;\n }\n}\n\ninterface DOMElement {\n type: string | ((props: Props) => unknown);\n props?: Props;\n children?: VNode[];\n key?: string | number;\n}\n\n// Type for virtual DOM nodes\nexport type VNode = DOMElement | string | number | boolean | null | undefined;\n\n// Type for elements that have context frames attached\ninterface ElementWithContext extends DOMElement {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n}\n\nfunction _isDOMElement(node: unknown): node is DOMElement {\n return typeof node === 'object' && node !== null && 'type' in node;\n}\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\nconst domRanges = new WeakMap<object, DOMRange>();\n\n// Track listeners so we can remove them on cleanup\ninterface ListenerMapEntry {\n handler: EventListener;\n original: EventListener;\n}\nconst elementListeners = new WeakMap<Element, Map<string, ListenerMapEntry>>();\n\n// Track keyed elements for reconciliation\ninterface _KeyedChild {\n key: string | number;\n vnode: unknown;\n}\nconst keyedElements = new WeakMap<Element, Map<string | number, Element>>();\n\n// Exported for runtime use: retrieve existing keyed map for a parent element\nexport function getKeyMapForElement(el: Element) {\n return keyedElements.get(el);\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.\nconst _reconcilerRecordedParents = new WeakSet<Element>();\n\nexport function removeElementListeners(element: Element): void {\n const map = elementListeners.get(element);\n if (map) {\n for (const [eventName, entry] of map) {\n 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\nexport function evaluate(\n node: unknown,\n target: Element | null,\n context?: object\n): void {\n if (!target) return;\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 const vnode = node;\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\n // Smart child update: if the only child is a single text node and vnode only has text children,\n // update the text node in place instead of replacing\n const vnodeChildren = vnode.children || vnode.props?.children;\n\n // Determine if this should be a simple text update\n let isSimpleTextVNode = false;\n let textContent: string | undefined;\n\n if (!Array.isArray(vnodeChildren)) {\n if (\n typeof vnodeChildren === 'string' ||\n typeof vnodeChildren === 'number'\n ) {\n isSimpleTextVNode = true;\n textContent = String(vnodeChildren);\n }\n } else if (vnodeChildren.length === 1) {\n // Array with single element - check if it's text\n const child = vnodeChildren[0];\n if (typeof child === 'string' || typeof child === 'number') {\n isSimpleTextVNode = true;\n textContent = String(child);\n }\n }\n\n if (\n isSimpleTextVNode &&\n firstChild.childNodes.length === 1 &&\n firstChild.firstChild?.nodeType === 3\n ) {\n // Update existing text node in place\n (firstChild.firstChild as Text).data = textContent!;\n } else {\n // Clear and repopulate children\n if (vnodeChildren) {\n if (Array.isArray(vnodeChildren)) {\n // Check if any children have keys - if so, use keyed reconciliation\n const hasKeys = vnodeChildren.some(\n (child) =>\n typeof child === 'object' && child !== null && 'key' in child\n );\n\n if (hasKeys) {\n // Get existing key map or create new one\n let oldKeyMap = keyedElements.get(firstChild);\n if (!oldKeyMap) {\n oldKeyMap = new Map();\n }\n\n // Optional forced positional bulk path for large keyed lists\n try {\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n try {\n const keyedVnodes: Array<{\n key: string | number;\n vnode: VNode;\n }> = [];\n for (\n let i = 0;\n i < (vnodeChildren as VNode[]).length;\n i++\n ) {\n const c = (vnodeChildren as VNode[])[i];\n if (\n _isDOMElement(c) &&\n (c as DOMElement).key !== undefined\n ) {\n keyedVnodes.push({\n key: (c as DOMElement).key as string | number,\n vnode: c,\n });\n }\n }\n // Only apply when all children are keyed and count matches\n if (\n keyedVnodes.length > 0 &&\n keyedVnodes.length === (vnodeChildren as VNode[]).length\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)'\n );\n const stats = performBulkPositionalKeyedTextUpdate(\n firstChild,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_COMMIT_COUNT?:\n | number\n | undefined;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n // Mark a single logical commit for dev diagnostics so\n // runtime fast-lane invariants can validate commit counts.\n gl.__ASKR_LAST_FASTPATH_COMMIT_COUNT = 1;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<\n string,\n number\n >) || {};\n counters.bulkKeyedPositionalForced =\n (counters.bulkKeyedPositionalForced || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n // Rebuild keyed map\n try {\n const map = new Map<string | number, Element>();\n const children = Array.from(firstChild.children);\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 keyedElements.set(firstChild, map);\n } catch (e) {\n void e;\n }\n } else {\n // Fall back to normal reconciliation below\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } catch (err) {\n logger.warn(\n '[Askr][FASTPATH] forced bulk path failed, falling back',\n err\n );\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } else {\n // Do reconciliation - this will reuse existing keyed elements\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } catch (e) {\n void e; // suppress unused variable lint\n // Fall back to normal reconciliation on error\n const newKeyMap = reconcileKeyedChildren(\n firstChild,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(firstChild, newKeyMap);\n }\n } else {\n // Unkeyed - consider bulk text fast-path for large text-dominant updates\n if (isBulkTextFastPathEligible(firstChild, vnodeChildren)) {\n const stats = performBulkTextReplace(firstChild, vnodeChildren);\n // Dev-only instrumentation counters\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_BULK_TEXT_FASTPATH_STATS?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_BULK_TEXT_FASTPATH_STATS as unknown) =\n stats;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkTextHits = (counters.bulkTextHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n } else {\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkTextMisses =\n (counters.bulkTextMisses || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n // Fall back to existing per-node updates\n updateUnkeyedChildren(firstChild, vnodeChildren);\n keyedElements.delete(firstChild);\n }\n }\n } else {\n // Non-array children\n firstChild.textContent = '';\n const dom = createDOMNode(vnodeChildren);\n if (dom) firstChild.appendChild(dom);\n keyedElements.delete(firstChild);\n }\n } else {\n // No children\n firstChild.textContent = '';\n keyedElements.delete(firstChild);\n }\n }\n\n // Update attributes and event listeners\n updateElementFromVnode(firstChild, vnode, false);\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 (_isDOMElement(vnode) && typeof vnode.type === 'string') {\n const children = vnode.children;\n if (\n Array.isArray(children) &&\n children.some(\n (child) =>\n typeof child === 'object' && child !== null && 'key' in child\n )\n ) {\n // Create the element first\n const el = document.createElement(vnode.type);\n target.appendChild(el);\n\n // Apply attributes\n const props = vnode.props || {};\n for (const [key, value] of Object.entries(props)) {\n if (key === 'children' || key === 'key') continue;\n if (value === undefined || value === null || value === false)\n continue;\n if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() +\n key.slice(3).toLowerCase();\n // Note: DOM event handlers run synchronously, but while in the\n // handler we mark the scheduler as \"in handler\" to defer any scheduled\n // flushes until the handler completes. This preserves synchronous\n // handler semantics (immediate reads observe state changes), while\n // keeping commits atomic and serialized.\n const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n // After handler completes, flush any pending tasks\n // globalScheduler.flush(); // Defer flush to manual control for testing\n };\n\n el.addEventListener(eventName, wrappedHandler);\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 });\n continue;\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 // Use keyed reconciliation for children\n const newKeyMap = reconcileKeyedChildren(el, children, undefined);\n keyedElements.set(el, newKeyMap);\n return;\n return;\n }\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\n/**\n * Reconcile children with keys, efficiently reusing existing elements\n */\n\n// Helper exported so the runtime can decide whether to activate a higher-level\n// runtime fast-lane before doing full render bookkeeping. Returns detailed\n// decision metadata for dev-mode diagnostics.\nexport function isKeyedReorderFastPathEligible(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n) {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n if (_isDOMElement(child) && child.key !== undefined) {\n keyedVnodes.push({ key: child.key, vnode: child });\n }\n }\n\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\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 const FAST_MOVE_THRESHOLD_ABS = 64;\n const FAST_MOVE_THRESHOLD_REL = 0.1; // 10%\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 let lisTrigger = false;\n let lisLen = 0;\n if (totalKeyed >= 128) {\n const parentChildren = Array.from(parent.children);\n const positions: number[] = new Array(keyedVnodes.length).fill(-1);\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const el = oldKeyMap?.get(key);\n if (el && el.parentElement === parent) {\n positions[i] = parentChildren.indexOf(el);\n }\n }\n\n const tails: number[] = [];\n for (let i = 0; i < positions.length; i++) {\n const pos = positions[i];\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 lisLen = tails.length;\n lisTrigger = lisLen < Math.floor(totalKeyed * 0.5);\n }\n\n // Conservative rule: if any keyed vnode declares non-trivial props\n // (excluding event handlers), decline the fast-path. This prevents edge\n // cases where props exist but match current DOM; the runtime fast-lane is\n // only for pure reorder-only updates.\n let hasPropsPresent = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue; // ignore event handlers\n if (k.startsWith('data-')) continue; // allow data-* attrs (keys/materialization)\n hasPropsPresent = true;\n break;\n }\n if (hasPropsPresent) break;\n }\n\n // Check for conservative prop differences on existing elements\n let hasPropChanges = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (!el || !_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue;\n if (k.startsWith('data-')) continue; // ignore data-* attrs (e.g. data-key)\n const v = (props as Record<string, unknown>)[k];\n try {\n if (k === 'class' || k === 'className') {\n if (el.className !== String(v)) {\n hasPropChanges = true;\n break;\n }\n } else if (k === 'value' || k === 'checked') {\n if ((el as HTMLElement & Record<string, unknown>)[k] !== v) {\n hasPropChanges = true;\n break;\n }\n } else {\n const attr = el.getAttribute(k);\n if (v === undefined || v === null || v === false) {\n if (attr !== null) {\n hasPropChanges = true;\n break;\n }\n } else if (String(v) !== attr) {\n hasPropChanges = true;\n break;\n }\n }\n } catch {\n hasPropChanges = true;\n break;\n }\n }\n if (hasPropChanges) break;\n }\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\nfunction reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n\n // First pass: collect all keyed vnodes and match to existing elements\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 if (_isDOMElement(child) && child.key !== undefined) {\n keyedVnodes.push({ key: child.key, vnode: child });\n } else {\n unkeyedVnodes.push(child);\n }\n }\n\n // Decide whether to use the fast-path. We use two heuristics:\n // - cheap move heuristic: positional mismatches in-memory (no DOM reads)\n // - LIS-based heuristic: compute Longest Increasing Subsequence on the\n // parent's current children order (requires reading current DOM order)\n // Additionally, the fast-path is only valid if there are NO prop/event\n // changes to existing keyed elements; it's strictly a bulk reorder escape.\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\n // Conservative mismatch count: positional differences or new insertions\n // count as moves. This intentionally avoids any DOM traversal.\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 // Fast-path eligibility is computed by `isKeyedReorderFastPathEligible`.\n // We intentionally avoid duplicating the heuristic computation here to keep\n // the logic centralized and prevent unused-variable lint errors.\n // Check for prop / event-handler changes on existing nodes. If any keyed vnode\n // introduces attribute/event handler changes compared to the current element\n // state, decline the fast-path to preserve correctness (we will do fine-grained updates).\n let hasPropChanges = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (!el || !_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n // If vnode declares event handlers, bail (we don't want to reattach handlers in bulk)\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) {\n // Ignore event handlers for fast-path activation: the fast-path\n // preserves existing element listeners (we do not reattach on each\n // reorder). Treat presence of a handler as non-blocking for fast-path.\n continue;\n }\n // Check `class`, `value`, `checked`, attribute differences conservatively\n const v = (props as Record<string, unknown>)[k];\n try {\n if (k === 'class' || k === 'className') {\n if (el.className !== String(v)) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch', {\n key,\n prop: k,\n expected: String(v),\n actual: el.className,\n });\n hasPropChanges = true;\n break;\n }\n } else if (k === 'value' || k === 'checked') {\n if ((el as HTMLElement & Record<string, unknown>)[k] !== v) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch', {\n key,\n prop: k,\n expected: v,\n actual: (el as HTMLElement & Record<string, unknown>)[k],\n });\n hasPropChanges = true;\n break;\n }\n } else {\n // Attribute check: presence/absence or string difference\n const attr = el.getAttribute(k);\n if (v === undefined || v === null || v === false) {\n if (attr !== null) {\n logger.warn(\n '[Askr][FASTPATH][DEV] prop mismatch (missing attr)',\n {\n key,\n prop: k,\n expected: v,\n actual: attr,\n }\n );\n hasPropChanges = true;\n break;\n }\n } else if (String(v) !== attr) {\n logger.warn('[Askr][FASTPATH][DEV] prop mismatch (attr diff)', {\n key,\n prop: k,\n expected: String(v),\n actual: attr,\n });\n hasPropChanges = true;\n break;\n }\n }\n } catch {\n // If any DOM read fails, be conservative and disable the fast path\n hasPropChanges = true;\n break;\n }\n }\n if (hasPropChanges) break;\n }\n\n const decision = isKeyedReorderFastPathEligible(\n parent,\n newChildren,\n oldKeyMap\n );\n const useFastPath = decision.useFastPath;\n\n // Dev debug: explain why we chose (or declined) fast-path for this update\n logger.warn('[Askr][FASTPATH][DEV] decision', decision);\n\n // Aggressive fallback for huge keyed lists that are text-dominant.\n // If the renderer declined the keyed fast-path but the list is extremely\n // large and each vnode is a simple intrinsic element with a single\n // primitive child (text), apply a positional bulk update to avoid\n // per-node reconciliation overhead.\n try {\n const hugeThreshold = Number(process.env.ASKR_BULK_HUGE_THRESHOLD) || 2048;\n if (!useFastPath && keyedVnodes.length >= hugeThreshold) {\n let allSimple = true;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) {\n allSimple = false;\n break;\n }\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') {\n allSimple = false;\n break;\n }\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) continue;\n if (Array.isArray(ch)) {\n if (\n ch.length !== 1 ||\n (typeof ch[0] !== 'string' && typeof ch[0] !== 'number')\n ) {\n allSimple = false;\n break;\n }\n } else if (typeof ch !== 'string' && typeof ch !== 'number') {\n allSimple = false;\n break;\n }\n }\n\n if (allSimple) {\n logger.warn('[Askr][FASTPATH] applying huge-list positional fallback');\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedHugeFallback =\n (counters.bulkKeyedHugeFallback || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-huge-fallback',\n stats,\n };\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n } catch (e) {\n void e;\n }\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as { __ASKR_BULK_DIAG?: unknown };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'keyed-decision',\n decision,\n totalKeyed,\n oldKeyMapSize: oldKeyMap?.size ?? 0,\n };\n } catch (e) {\n void e;\n }\n }\n\n // Heuristic: if many incoming keys are missing from the old key map (i.e.\n // keys changed en-masse) and all children are simple text, prefer the\n // positional bulk text fast-path rather than the keyed map fast-path which\n // would allocate many new elements.\n let allSimpleText = false;\n try {\n if (\n keyedVnodes.length >=\n (Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024)\n ) {\n let missing = 0;\n try {\n const present = new Set<string | number>();\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const attr = parentChildren[i].getAttribute('data-key');\n if (attr !== null) {\n present.add(attr);\n const n = Number(attr);\n if (!Number.isNaN(n)) present.add(n);\n }\n }\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n if (!present.has(k)) missing++;\n }\n } catch {\n // If DOM reads fail, be conservative and set missing low\n missing = 0;\n }\n\n // Determine whether all keyed vnodes are \"simple text\" candidates.\n // Moved here to ensure the predicate is available where it's needed.\n // Declare variable in outer scope so it can be referenced later in file\n // (some heuristics need this predicate after this try block).\n allSimpleText =\n keyedVnodes.length > 0 &&\n keyedVnodes.every(({ vnode }) => {\n if (!_isDOMElement(vnode)) return false;\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') return false;\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) return true;\n if (Array.isArray(ch)) {\n return (\n ch.length === 1 &&\n (typeof ch[0] === 'string' || typeof ch[0] === 'number')\n );\n }\n return typeof ch === 'string' || typeof ch === 'number';\n });\n\n // Conservative: do not apply positional bulk keyed fast-path when any\n // child vnode declares non-data props (class, value, etc). Such props\n // may require per-node updates and the bulk path assumes text-only\n // changes. Compute presence of non-data props here.\n let hasPropsPresent = false;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (!_isDOMElement(vnode)) continue;\n const props = vnode.props || {};\n for (const k of Object.keys(props)) {\n if (k === 'children' || k === 'key') continue;\n if (k.startsWith('on') && k.length > 2) continue; // ignore event handlers\n if (k.startsWith('data-')) continue; // ignore data-* attributes\n hasPropsPresent = true;\n break;\n }\n if (hasPropsPresent) break;\n }\n\n const missingRatio = missing / Math.max(1, keyedVnodes.length);\n if (missingRatio > 0.5 && allSimpleText && !hasPropsPresent) {\n logger.warn(\n '[Askr][FASTPATH] switching to positional bulk keyed fast-path due to missing keys ratio',\n missingRatio\n );\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n if (process.env.NODE_ENV !== 'production') {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_COMMIT_COUNT?: number | undefined;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n // Mark that reconciler recorded stats for this parent during this\n // render pass; this allows subsequent reconciliations in the same\n // pass to preserve the diagnostic fields instead of clearing them.\n try {\n _reconcilerRecordedParents.add(parent);\n } catch (e) {\n void e;\n }\n // Record a logical commit for diagnostics (even though the\n // reconciler performed in-place updates, treat it as a single\n // fast-path commit for runtime invariant checks).\n gl.__ASKR_LAST_FASTPATH_COMMIT_COUNT = 1;\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n } catch (e) {\n void e;\n }\n\n // Clear previous fast-path stats when we decline the fast-path to avoid\n // leaking prior run data across updates (tests rely on this behavior).\n // However, if a fast-path was applied synchronously for this parent in the\n // same render pass, preserve the recorded stats (they may be set by the\n // reconciler even when the runtime fast-lane was not taken).\n if (!useFastPath && typeof globalThis !== 'undefined') {\n try {\n let parentFastpathApplied = false;\n try {\n parentFastpathApplied = isFastPathApplied(parent);\n } catch {\n parentFastpathApplied = false;\n }\n if (!parentFastpathApplied) {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_LAST_FASTPATH_REUSED?: unknown;\n };\n // If the reconciler recorded stats for this parent in the current\n // render pass, preserve them and remove the transient marker so that\n // subsequent independent renders will not inherit the flag.\n try {\n if (_reconcilerRecordedParents.has(parent)) {\n _reconcilerRecordedParents.delete(parent);\n } else {\n delete gl.__ASKR_LAST_FASTPATH_STATS;\n delete gl.__ASKR_LAST_FASTPATH_REUSED;\n }\n } catch {\n // On any failure, clear diagnostics conservatively\n delete gl.__ASKR_LAST_FASTPATH_STATS;\n delete gl.__ASKR_LAST_FASTPATH_REUSED;\n }\n }\n } catch (e) {\n void e;\n }\n }\n\n // Heuristic: if keys changed but the new children are the same element tag\n // and only their text content differs, reuse existing elements by **position**\n // (positional reuse). This avoids allocating a new Element/Node per update\n // when the structure is stable and only textual content changes.\n // Conditions:\n // - oldKeyMap is missing or provides no matching keys\n // - parent has same number of children as keyed vnodes\n // - each keyed vnode is an intrinsic element (string type) whose children\n // are a single primitive (string/number)\n let _triedPositionalReuse = false;\n\n // New heuristic: bulk keyed text update fast-path\n // If there are many keyed elements (large lists) and **no moves** (stable key order)\n // and all keyed vnodes are simple intrinsic elements with a single primitive\n // child (text), we can build a DocumentFragment by reusing the existing\n // Element nodes and updating their text content in-memory, then perform a\n // single atomic `replaceChildren` to avoid per-node reconciliation overhead.\n // This preserves element identity and listeners while dramatically reducing\n // JS overhead for pure text churn.\n try {\n const bulkTextThreshold =\n Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024; // `allSimpleText` computed earlier near missing-ratio check\n\n if (\n !useFastPath &&\n keyedVnodes.length >= bulkTextThreshold &&\n allSimpleText &&\n !hasPropChanges\n ) {\n // If bulk fast-path was already applied synchronously on this parent in\n // this commit, avoid reapplying another structural fast-path which could\n // replace nodes again and inadvertently remove listeners. This marker\n // is cleared on the next tick.\n try {\n // Avoid reapplying a fast-path on the same parent during the same bulk\n // commit. Use runtime registry rather than DOM attributes to avoid\n // introducing async cleanup and to keep this logic synchronous.\n if (isFastPathApplied(parent)) {\n logger.warn(\n '[Askr][FASTPATH] fast-path already applied on parent; skipping'\n );\n return newKeyMap;\n }\n } catch (e) {\n void e;\n }\n // Two bulk behaviors:\n // 1) Stable keys & order: reuse elements from oldKeyMap by key and do an\n // atomic replaceChildren after updating text content (preserves identity).\n // 2) Keys changed en-masse but structure is stable: positional reuse - reuse\n // elements by position, update their text, and remap data-key attributes.\n let stable = true;\n try {\n const parentChildren = Array.from(parent.children);\n\n // If the parent and new children have identical length and all\n // keyed vnodes are simple text elements, we can apply the positional\n // bulk update. Allow a forced env var to bypass conservative checks\n // for benching/debugging scenarios where we know structure is stable.\n if (parentChildren.length === keyedVnodes.length) {\n const allSimple = keyedVnodes.every(({ vnode }) => {\n if (!_isDOMElement(vnode)) return false;\n const dv = vnode as DOMElement;\n if (typeof dv.type !== 'string') return false;\n const ch = dv.children || dv.props?.children;\n if (ch === undefined) return true;\n if (Array.isArray(ch)) {\n return (\n ch.length === 1 &&\n (typeof ch[0] === 'string' || typeof ch[0] === 'number')\n );\n }\n return typeof ch === 'string' || typeof ch === 'number';\n });\n\n if (allSimple || process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n logger.warn(\n '[Askr][FASTPATH] len-match heuristic triggered (positional bulk)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-trigger-lenmatch-early',\n totalKeyed: keyedVnodes.length,\n allSimple,\n forced: process.env.ASKR_FORCE_BULK_POSREUSE === '1',\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) || {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1')\n counters.bulkKeyedPositionalForced =\n (counters.bulkKeyedPositionalForced || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n\n if (parentChildren.length !== keyedVnodes.length) stable = false;\n else {\n // Check if keys match positions (stable-key case) and collect mismatch count\n let keyMismatches = 0;\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n const ch = parentChildren[i] as Element | undefined;\n if (!ch) {\n stable = false;\n break;\n }\n const attr = ch.getAttribute('data-key');\n if (attr === null) {\n stable = false;\n break;\n }\n if (String(k) !== attr && String(Number(attr)) !== String(k)) {\n keyMismatches++;\n }\n }\n\n if (stable) {\n if (keyMismatches === 0) {\n // Perfectly aligned - treat as stable keyed fast-path\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed text fast-path (stable keys)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-stable-trigger',\n totalKeyed: keyedVnodes.length,\n hasPropChanges,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkKeyedTextReplace(\n parent,\n keyedVnodes,\n oldKeyMap\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n (gl.__ASKR_LAST_FASTPATH_STATS as unknown) = stats;\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedTextHits =\n (counters.bulkKeyedTextHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n\n // If the parent shape (number of children) matches, prefer a\n // positional bulk update for large lists of simple text. This is a\n // conservative but practical heuristic: for very large lists the\n // per-node insert/move/update overhead dominates and a single\n // DocumentFragment-based positional update is much cheaper while\n // preserving identity and listeners.\n if (parentChildren.length === keyedVnodes.length) {\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed positional text fast-path (len-match)'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_BULK_DIAG?: unknown;\n };\n (gl.__ASKR_BULK_DIAG as unknown) = {\n phase: 'bulk-keyed-positional-trigger-lenmatch',\n totalKeyed: keyedVnodes.length,\n keyMismatches: keyMismatches,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n gl.__ASKR_LAST_FASTPATH_STATS = stats;\n gl.__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n\n // If many mismatches but structural shape is identical and all children\n // are simple text, attempt positional bulk keyed replace to avoid\n // alloc/move churn. This reuses elements by position, updates text,\n // and remaps the `data-key` attribute to the new key.\n const mismatchRatio = keyMismatches / keyedVnodes.length;\n const POSITIONAL_THRESHOLD = 0.5; // if >50% mismatched, use positional path\n if (mismatchRatio > POSITIONAL_THRESHOLD) {\n logger.warn(\n '[Askr][FASTPATH] applying bulk keyed positional text fast-path'\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-trigger',\n totalKeyed: keyedVnodes.length,\n keyMismatches: keyMismatches,\n };\n } catch (e) {\n void e;\n }\n }\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(\n parent,\n keyedVnodes\n );\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const gl = globalThis as unknown as {\n __ASKR_LAST_FASTPATH_STATS?: unknown;\n __ASKR_BULK_DIAG?: unknown;\n __ASKR_FASTPATH_COUNTERS?: Record<string, number>;\n };\n gl.__ASKR_LAST_FASTPATH_STATS = stats;\n gl.__ASKR_BULK_DIAG = {\n phase: 'bulk-keyed-positional-applied',\n stats,\n };\n const counters =\n (gl.__ASKR_FASTPATH_COUNTERS as Record<string, number>) ||\n {};\n counters.bulkKeyedPositionalHits =\n (counters.bulkKeyedPositionalHits || 0) + 1;\n gl.__ASKR_FASTPATH_COUNTERS = counters;\n } catch (e) {\n void e;\n }\n }\n return newKeyMap;\n }\n }\n }\n } catch {\n stable = false;\n }\n }\n } catch (e) {\n void e;\n }\n if (!useFastPath) {\n const totalKeyed = keyedVnodes.length;\n // Aggressive positional reuse heuristic for small lists where all\n // keyed vnodes are simple intrinsic elements with a single primitive\n // child (text or number). This handles cases where keys change each\n // update but structure is stable (common in bulk text updates).\n // Evaluate candidates from the raw newChildren array (handles both keyed and unkeyed)\n const candidates = newChildren.filter(\n (c) => _isDOMElement(c) && typeof (c as DOMElement).type === 'string'\n ) as DOMElement[];\n const smallListPositionalReuseEligible =\n candidates.length > 0 &&\n candidates.length <= 64 &&\n parent.children.length === candidates.length &&\n candidates.every((vnode) => {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (Array.isArray(children)) {\n return (\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n );\n }\n return (\n children === undefined ||\n typeof children === 'string' ||\n typeof children === 'number'\n );\n });\n\n try {\n if (smallListPositionalReuseEligible) {\n let eligible = true;\n for (let i = 0; i < totalKeyed; i++) {\n const vnode = keyedVnodes[i].vnode;\n if (\n !_isDOMElement(vnode) ||\n typeof (vnode as DOMElement).type !== 'string'\n ) {\n eligible = false;\n break;\n }\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n // Accept a single string/number child or no children\n if (Array.isArray(children)) {\n if (children.length !== 1) {\n eligible = false;\n break;\n }\n const c = children[0];\n if (typeof c !== 'string' && typeof c !== 'number') {\n eligible = false;\n break;\n }\n } else if (\n children !== undefined &&\n typeof children !== 'string' &&\n typeof children !== 'number'\n ) {\n eligible = false;\n break;\n }\n }\n\n // Safety guard: do not apply positional reuse when existing DOM keys match\n // incoming vnode keys. That indicates this is a keyed list reorder, and\n // identity must be preserved by key rather than by position.\n const anyKeyMatches =\n !!oldKeyMap && keyedVnodes.some((kv) => oldKeyMap!.has(kv.key));\n if (anyKeyMatches) {\n eligible = false;\n }\n\n if (eligible || process.env.ASKR_FORCE_POSREUSE === '1') {\n _triedPositionalReuse = true;\n if (process.env.ASKR_FORCE_POSREUSE === '1') {\n logger.warn(\n '[Askr][POSREUSE][FORCED] forcing positional reuse path for testing'\n );\n } else {\n logger.warn('[Askr][POSREUSE] positional reuse heuristic applied');\n }\n\n // Perform positional update in-place\n const existingChildren = parent.children;\n for (let i = 0; i < totalKeyed; i++) {\n const { key, vnode } = keyedVnodes[i];\n const current = existingChildren[i] as Element | undefined;\n if (current && _isDOMElement(vnode)) {\n const vnodeType = (vnode as DOMElement).type as string;\n if (current.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n // Update attributes and children in-place\n updateElementFromVnode(current, vnode as VNode);\n newKeyMap.set(key, current);\n continue;\n }\n }\n // Fall back: create a new node and replace\n const newEl = createDOMNode(vnode);\n if (newEl instanceof Element) {\n if (current) {\n // Clean up any component instance that owned the existing node\n cleanupInstanceIfPresent(current);\n parent.replaceChild(newEl, current);\n } else parent.appendChild(newEl);\n newKeyMap.set(key, newEl);\n }\n }\n // Add unkeyed nodes (should be none in this heuristic)\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) parent.appendChild(newEl as Node);\n }\n // Positional reuse done; return new key map\n return newKeyMap;\n }\n }\n } catch {\n // If any DOM read/write here fails, fall back to normal code path below\n }\n }\n\n if (useFastPath) {\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 // Build either a small linear scan cache or a map depending on size.\n // For small keyed lists (<= 20) we prefer linear scans to avoid Map\n // allocations and HashTable churn — O(N^2) is acceptable for small N.\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 {\n parentChildrenArr = undefined;\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 // also store numeric form for numeric keys\n const n = Number(k);\n if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);\n }\n }\n } catch {\n // ignore DOM read failures; we'll fall back to creation\n localOldKeyMap = undefined;\n }\n }\n\n logger.warn(\n '[Askr][FASTPATH] oldKeyMap size:',\n oldKeyMap?.size ?? 0,\n 'localOldKeyMap size:',\n localOldKeyMap?.size\n );\n\n // Build the final node array WITHOUT touching the DOM. For existing\n // elements we reuse the `oldKeyMap` or `localOldKeyMap` references; for\n // new vnodes we create detached nodes via `createDOMNode`.\n const tLookupStart =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\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 // Linear scan lookup for small lists (avoid Map allocation)\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 // Fallback to cached map if present\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 for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n const t_lookup =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - tLookupStart\n : 0;\n\n // Dev-only guard disabled for minimal fast-path to avoid prototype\n // monkey-patching during the tight commit. The fast-path now performs a\n // single DocumentFragment-based commit and is validated via micro-bench\n // instrumentation instead of dynamic API wrapping.\n if (process.env.ASKR_FASTPATH_GUARD === '1') {\n const replaceChildrenCount = 0;\n const otherMutationCount = 0;\n\n const orig: Record<string, unknown> = {};\n // Only wrap methods that exist in the current environment\n const elProto = Element.prototype as unknown as Record<string, unknown>;\n const nodeProto = Node.prototype as unknown as Record<string, unknown>;\n // Detect existence of `remove()` on nodes without referencing the\n // `ChildNode` type (which is a TS-only interface in some lib targets).\n const removeFn = (() => {\n if (\n typeof document === 'undefined' ||\n typeof document.createElement !== 'function'\n )\n return undefined;\n try {\n const el = document.createElement('div') as unknown as {\n remove?: () => void;\n };\n return typeof el.remove === 'function' ? el.remove : undefined;\n } catch {\n return undefined;\n }\n })();\n\n if (elProto.replaceChildren)\n orig.replaceChildren = elProto.replaceChildren;\n if (nodeProto.appendChild) orig.appendChild = nodeProto.appendChild;\n if (nodeProto.insertBefore) orig.insertBefore = nodeProto.insertBefore;\n if (nodeProto.removeChild) orig.removeChild = nodeProto.removeChild;\n if (nodeProto.replaceChild) orig.replaceChild = nodeProto.replaceChild;\n if (removeFn) orig.remove = removeFn;\n\n let violation = false;\n try {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n // Count commits explicitly in code (no prototype monkey-patching)\n let commitCount = 0;\n commitCount++;\n parent.replaceChildren(fragment);\n // Export commit count for dev diagnostics\n if (typeof globalThis !== 'undefined') {\n (globalThis as unknown as Record<string, unknown>)[\n '__ASKR_LAST_FASTPATH_COMMIT_COUNT'\n ] = commitCount;\n }\n } finally {\n // Restore parent's original\n\n // Restore originals (only those we replaced)\n\n // Assert invariants: no other structural mutation APIs were called\n // during the fast-path. We accept >=1 replaceChildren calls because\n // tests may install instance-level spies that wrap the call once.\n violation =\n (otherMutationCount as number) !== 0 ||\n (replaceChildrenCount as number) < 1;\n }\n if (violation) {\n logger.error(\n '[Askr][DEV] Fast-path structural mutation invariant violated:',\n {\n replaceChildrenCount,\n otherMutationCount,\n }\n );\n // Fail hard in dev so regressions are caught early\n throw new Error(\n 'Fast-path must perform a single structural replacement (replaceChildren) and no other structural mutations'\n );\n }\n } else {\n // Production: single atomic commit (measure phases if tracing)\n\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 const t_fragment = Date.now() - tFragmentStart;\n\n // Dev: capture scheduler state so we can assert no tasks were enqueued\n // during the fast-path commit. This ensures we didn't accidentally\n // invoke per-node scheduling work.\n const schedBefore =\n process.env.NODE_ENV !== 'production'\n ? globalScheduler.getState()\n : null;\n const wasExecuting =\n process.env.NODE_ENV !== 'production' ? isSchedulerExecuting() : false;\n\n const tCommitStart = Date.now();\n if (process.env.NODE_ENV !== 'production') {\n // Extra debug to help tests detect the structural change and to aid\n // diagnosing spy/observer mismatches in test harnesses.\n }\n // Count commits explicitly in code (no prototype monkey-patching)\n let commitCount = 0;\n commitCount++;\n // Clean up any mounted component instances that will be removed by\n // the atomic replaceChildren commit to avoid leaking subscriptions.\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n // Clean up any mounted component instances that will be removed by\n // the atomic replaceChildren commit to avoid leaking subscriptions.\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n parent.replaceChildren(fragment);\n // Export commit count for dev diagnostics\n if (typeof globalThis !== 'undefined') {\n (globalThis as unknown as Record<string, unknown>)[\n '__ASKR_LAST_FASTPATH_COMMIT_COUNT'\n ] = commitCount;\n }\n const t_commit = Date.now() - tCommitStart;\n\n // Dev assertions: validate scheduler state and final DOM structure\n if (process.env.NODE_ENV !== 'production') {\n const schedAfter = globalScheduler.getState();\n if (!wasExecuting) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path commit invoked outside scheduler execution'\n );\n }\n if (schedBefore && schedAfter) {\n if (schedBefore.taskCount !== schedAfter.taskCount) {\n logger.error(\n '[Askr][FASTPATH][DEV] Scheduler tasks were enqueued during fast-path commit',\n {\n before: schedBefore,\n after: schedAfter,\n }\n );\n throw new Error('Fast-path must not enqueue scheduler tasks');\n }\n }\n\n // Assert that the parent's children exactly match the final nodes\n // (single atomic replacement). If this fails, the fast-path violated\n // the single-commit invariant.\n const parentNodes = Array.from(parent.childNodes);\n if (parentNodes.length !== finalNodes.length) {\n logger.error('[Askr][FASTPATH][DEV] Parent child count mismatch', {\n parentCount: parentNodes.length,\n expected: finalNodes.length,\n });\n throw new Error(\n 'Fast-path must perform a single structural replacement'\n );\n }\n for (let i = 0; i < finalNodes.length; i++) {\n if (parentNodes[i] !== finalNodes[i]) {\n logger.error(\n '[Askr][FASTPATH][DEV] Final DOM order mismatch at index',\n i,\n {\n expected: finalNodes[i],\n found: parentNodes[i],\n }\n );\n throw new Error(\n 'Fast-path final DOM order does not match expected nodes'\n );\n }\n }\n }\n\n // Phase: minimal bookkeeping - populate newKeyMap\n const tBookkeepingStart = Date.now();\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 const t_bookkeeping = Date.now() - tBookkeepingStart;\n\n // Emit tracing stats in dev if requested\n if (\n process.env.ASKR_FASTPATH_TRACE === '1' ||\n process.env.NODE_ENV !== 'production'\n ) {\n const stats = {\n n: totalKeyed,\n moves: moveCount,\n lisLen: 0,\n t_lookup,\n t_fragment,\n t_commit,\n t_bookkeeping,\n fragmentAppendCount,\n mapLookups,\n createdNodes,\n reusedCount,\n } as const;\n if (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g['__ASKR_LAST_FASTPATH_STATS'] = stats;\n _g['__ASKR_LAST_FASTPATH_REUSED'] = reusedCount > 0;\n // Maintain a simple history for tooling/tests so we can assert\n // that fast-path was used at least once during a series of updates\n // even if subsequent non-fast-path updates clear the most recent\n // diagnostic fields. Use a typed temporary for the history array to\n // avoid explicit `any` in typings.\n const historyKey = '__ASKR_LAST_FASTPATH_HISTORY';\n let hist = _g[historyKey] as unknown[] | undefined;\n if (!hist) {\n hist = [];\n _g[historyKey] = hist;\n }\n hist.push(stats as unknown);\n }\n logger.warn('[Askr][FASTPATH]', JSON.stringify(stats));\n }\n }\n\n return newKeyMap;\n }\n\n // Fallback: Rebuild with minimal moves: insert before `anchor` as we go\n // Compute indices of existing keyed elements in parent's current order\n const parentChildren = Array.from(parent.children);\n const positions: number[] = new Array(keyedVnodes.length).fill(-1);\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const el = oldKeyMap?.get(key);\n if (el && el.parentElement === parent) {\n positions[i] = parentChildren.indexOf(el);\n }\n }\n\n // Compute Longest Increasing Subsequence (LIS) of positions to\n // determine which existing elements are already in correct order\n // and can be left in place (minimizes moves).\n const tailsStart =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n const keepSet = new Set<number>();\n const tails: number[] = [];\n const tailsIdx: number[] = [];\n const prev: number[] = new Array(positions.length).fill(-1);\n\n for (let i = 0; i < positions.length; i++) {\n const pos = positions[i];\n if (pos === -1) continue;\n // binary search for insertion point\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) {\n tails.push(pos);\n tailsIdx.push(i);\n } else {\n tails[lo] = pos;\n tailsIdx[lo] = i;\n }\n prev[i] = lo > 0 ? tailsIdx[lo - 1] : -1;\n }\n\n // Reconstruct LIS indices into keepSet\n let k = tailsIdx.length ? tailsIdx[tailsIdx.length - 1] : -1;\n while (k !== -1) {\n keepSet.add(k);\n k = prev[k];\n }\n const tLIS =\n (typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now()) - tailsStart;\n\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n const prev = (\n globalThis as unknown as { __ASKR_BULK_DIAG?: { decision?: unknown } }\n ).__ASKR_BULK_DIAG;\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'keyed-fallback-lis',\n positionsFound: positions.filter((p) => p !== -1).length,\n keepCount: keepSet.size,\n tLIS,\n previousDecision: prev?.decision,\n };\n } catch (e) {\n void e;\n }\n }\n\n let anchor: Node | null = parent.firstChild;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n\n if (el && el.parentElement === parent) {\n if (keepSet.has(i)) {\n // This element can stay; ensure anchor advances past it\n if (anchor === el) {\n anchor = el.nextSibling;\n }\n updateElementFromVnode(el, vnode);\n newKeyMap.set(key, el);\n } else {\n // Move existing element into place before anchor\n parent.insertBefore(el, anchor);\n updateElementFromVnode(el, vnode);\n newKeyMap.set(key, el);\n anchor = el.nextSibling;\n }\n } else {\n // New element - insert before anchor\n const newEl = createDOMNode(vnode);\n if (newEl instanceof Element) {\n parent.insertBefore(newEl, anchor);\n newKeyMap.set(key, newEl);\n anchor = newEl.nextSibling;\n }\n }\n }\n\n // Add unkeyed children at the end\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n parent.appendChild(newEl);\n }\n }\n\n return newKeyMap;\n}\n\n/**\n * Variant of bulk replace specialized for keyed lists where elements are\n * intrinsic elements whose only child is a primitive (text/number).\n * Reuses existing Element nodes (preserves identity/listeners) and updates\n * their text content before assembling a DocumentFragment and doing a\n * single atomic replacement.\n */\nfunction performBulkKeyedTextReplace(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap?: Map<string | number, Element>\n) {\n const total = keyedVnodes.length;\n const finalNodes: Node[] = [];\n let reused = 0;\n let created = 0;\n const t0 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n\n for (let i = 0; i < total; i++) {\n const { key, vnode } = keyedVnodes[i];\n const el = oldKeyMap?.get(key);\n if (\n el &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const children =\n (vnode as DOMElement).children || (vnode as DOMElement).props?.children;\n // Update text content in-place when possible\n if (typeof children === 'string' || typeof children === 'number') {\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 } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children[0]);\n } else {\n el.textContent = String(children[0]);\n }\n } else {\n // Fallback to normal element update\n updateElementFromVnode(el, vnode as VNode);\n }\n finalNodes.push(el);\n reused++;\n } else {\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n }\n }\n\n // Remove instances that won't be in final set\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !finalNodes.includes(n)\n );\n for (const n of toRemove) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n\n // Prepare to transfer listeners for positions where nodes are replaced\n const existingChildren = Array.from(parent.children);\n const listenerSnapshots: Array<Map<string, ListenerMapEntry> | undefined> =\n new Array(existingChildren.length).fill(undefined);\n try {\n for (let i = 0; i < existingChildren.length; i++) {\n const ch = existingChildren[i] as Element | undefined;\n if (ch) {\n const map = elementListeners.get(ch);\n if (map && map.size > 0) {\n // Clone the map entries to avoid mutation during transfer\n const clone = new Map<string, ListenerMapEntry>();\n for (const [k, v] of map) clone.set(k, v);\n listenerSnapshots[i] = clone;\n }\n }\n }\n } catch (e) {\n void e;\n }\n\n // Atomic replace using fragment\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n parent.replaceChildren(fragment);\n\n // Transfer listeners where nodes were replaced (preserve user handlers)\n try {\n for (let i = 0; i < finalNodes.length; i++) {\n const newNode = finalNodes[i];\n const snapshot = listenerSnapshots[i];\n if (snapshot && newNode instanceof Element) {\n // Reattach handlers to newNode\n for (const [eventName, entry] of snapshot) {\n // If newNode already has a listener with the same original, skip\n const existing = elementListeners.get(newNode)?.get(eventName);\n if (existing && existing.original === entry.original) continue;\n newNode.addEventListener(eventName, entry.handler);\n if (!elementListeners.has(newNode))\n elementListeners.set(newNode, new Map());\n elementListeners.get(newNode)!.set(eventName, entry);\n }\n }\n }\n } catch (e) {\n void e;\n }\n\n // Rebuild keyed map\n try {\n keyedElements.delete(parent);\n } catch (e) {\n void e;\n }\n\n const t =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n const stats = {\n n: total,\n reused,\n created,\n t,\n } as const;\n return stats;\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 */\nfunction 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 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.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 if (\n ch &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const vnodeType = (vnode as DOMElement).type as string;\n if (ch.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (typeof children === 'string' || typeof children === 'number') {\n if (ch.childNodes.length === 1 && ch.firstChild?.nodeType === 3) {\n (ch.firstChild as Text).data = String(children);\n } else {\n ch.textContent = String(children);\n }\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (ch.childNodes.length === 1 && ch.firstChild?.nodeType === 3) {\n (ch.firstChild as Text).data = String(children[0]);\n } else {\n ch.textContent = String(children[0]);\n }\n } else {\n updateElementFromVnode(ch, vnode as VNode);\n }\n // Update data-key attribute to reflect new key mapping\n try {\n ch.setAttribute('data-key', String(key));\n updatedKeys++;\n } catch (e) {\n void e;\n }\n reused++;\n continue;\n }\n }\n // Fallback: replace the node at position i\n const dom = createDOMNode(vnode);\n if (dom) {\n const existing = parent.children[i];\n if (existing) {\n cleanupInstanceIfPresent(existing);\n parent.replaceChild(dom, existing);\n } else parent.appendChild(dom);\n }\n }\n\n const t =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n\n // Rebuild keyed map to reflect new keys -> element mapping\n try {\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < total; 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 (e) {\n void e;\n }\n\n const stats = {\n n: total,\n reused,\n updatedKeys,\n t,\n } as const;\n return stats;\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 */\nfunction isBulkTextFastPathEligible(parent: Element, newChildren: VNode[]) {\n const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;\n const requiredFraction = 0.8; // 80% of children should be simple text\n\n const total = Array.isArray(newChildren) ? newChildren.length : 0;\n if (total < threshold) {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n reason: 'too-small',\n total,\n threshold,\n };\n } catch (e) {\n void e;\n }\n }\n return false;\n }\n\n let simple = 0;\n for (let i = 0; i < newChildren.length; i++) {\n const c = newChildren[i];\n if (typeof c === 'string' || typeof c === 'number') {\n simple++;\n continue;\n }\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const dv = c as DOMElement;\n if (typeof dv.type === 'function') {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n reason: 'component-child',\n index: i,\n };\n } catch (e) {\n void e;\n }\n }\n return false; // component child - decline\n }\n if (typeof dv.type === 'string') {\n const children = dv.children || dv.props?.children;\n if (!children) {\n // empty element - treat as simple\n simple++;\n continue;\n }\n if (Array.isArray(children)) {\n if (\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n simple++;\n continue;\n }\n } else if (\n typeof children === 'string' ||\n typeof children === 'number'\n ) {\n simple++;\n continue;\n }\n }\n }\n // complex child - not simple\n }\n\n const fraction = simple / total;\n const eligible =\n fraction >= requiredFraction && parent.childNodes.length >= total;\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n (\n globalThis as unknown as { __ASKR_BULK_DIAG?: unknown }\n ).__ASKR_BULK_DIAG = {\n phase: 'bulk-unkeyed-eligible',\n total,\n simple,\n fraction,\n requiredFraction,\n eligible,\n };\n } catch (e) {\n void e;\n }\n }\n\n return eligible;\n}\n\n/**\n * Perform a bulk replace using DocumentFragment while reusing existing nodes\n * where possible to preserve identity and listeners. We avoid per-node DOM\n * insert/remove churn and perform a single atomic replaceChildren.\n */\nfunction performBulkTextReplace(parent: Element, newChildren: VNode[]) {\n const t0 =\n typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.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 vnode = newChildren[i];\n const existingNode = existing[i];\n\n if (typeof vnode === 'string' || typeof vnode === 'number') {\n const text = String(vnode);\n if (existingNode && existingNode.nodeType === 3) {\n // Reuse existing text node\n (existingNode as Text).data = text;\n finalNodes.push(existingNode);\n reused++;\n } else {\n // Create detached text node\n finalNodes.push(document.createTextNode(text));\n created++;\n }\n continue;\n }\n\n if (typeof vnode === 'object' && vnode !== null && 'type' in vnode) {\n if (typeof (vnode as DOMElement).type === 'string') {\n const vtype = (vnode as DOMElement).type as string;\n if (\n existingNode &&\n existingNode.nodeType === 1 &&\n (existingNode as Element).tagName.toLowerCase() ===\n vtype.toLowerCase()\n ) {\n // Reuse existing element node and update its text content (simple case)\n const el = existingNode as Element;\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n if (typeof children === 'string' || typeof children === 'number') {\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 } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children[0]);\n } else {\n el.textContent = String(children[0]);\n }\n } else {\n // For slightly more complex children, fallback to existing update routine\n updateElementFromVnode(el, vnode as VNode);\n }\n finalNodes.push(el);\n reused++;\n continue;\n }\n\n // Not reusable - create detached DOM node\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n continue;\n }\n }\n\n // Fallback for anything else: create node\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n }\n }\n\n const tBuild =\n typeof performance !== 'undefined' && performance.now\n ? performance.now() - t0\n : 0;\n\n // Clean up instances that will be removed\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !finalNodes.includes(n)\n );\n for (const n of toRemove) cleanupInstanceIfPresent(n);\n } catch (e) {\n void e;\n }\n\n const fragStart = Date.now();\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n // Atomic replacement\n parent.replaceChildren(fragment);\n const tCommit = Date.now() - fragStart;\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\n return stats;\n}\n\n/**\n * Update an existing element's attributes and children from vnode\n */\nfunction 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 || {};\n\n // Ensure key is materialized on existing elements so DOM-based scans succeed\n if ((vnode as DOMElement).key !== undefined) {\n el.setAttribute('data-key', String((vnode as DOMElement).key));\n }\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 as Record<string, unknown>)[key];\n if (key === 'children' || key === 'key') continue;\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 (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n if (existingListeners && existingListeners.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n el.removeEventListener(eventName, entry.handler);\n existingListeners.delete(eventName);\n }\n continue;\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 (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n\n desiredEventNames.add(eventName);\n\n const existing = existingListeners?.get(eventName);\n // If the handler reference is 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 const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n };\n\n el.addEventListener(eventName, wrappedHandler);\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 });\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 // Iterate over keys to avoid allocating a transient array via Array.from\n for (const eventName of existingListeners.keys()) {\n const entry = existingListeners.get(eventName)!;\n if (!desiredEventNames.has(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\n/**\n * Update an existing element's children\n */\nfunction updateElementChildren(\n el: Element,\n children: VNode | VNode[] | undefined\n): void {\n if (!children) {\n el.textContent = '';\n return;\n }\n\n // Handle simple text case\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 // Update existing text node\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n return;\n }\n\n // For array children, update in-place to preserve positional identity\n if (Array.isArray(children)) {\n updateUnkeyedChildren(el, children);\n return;\n }\n\n // Fallback: clear and rebuild\n el.textContent = '';\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n}\n\n/**\n * Update unkeyed children by position, preserving element identity when tags match.\n */\nfunction updateUnkeyedChildren(parent: Element, newChildren: unknown[]): void {\n const existing = Array.from(parent.children);\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 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 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 cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n }\n}\n\nexport function createDOMNode(node: unknown): Node | null {\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 (let i = 0; i < node.length; i++) {\n const dom = createDOMNode(node[i]);\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 || {};\n\n // Intrinsic element (string type)\n if (typeof type === 'string') {\n const el = document.createElement(type);\n\n // Set attributes and event handlers in single pass (allocation-free)\n for (const key in props) {\n const value = (props as Record<string, unknown>)[key];\n // Skip special keys\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 const wrappedHandler = (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n (value as EventListener)(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 mirrors the behavior in scheduleEventHandler.\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 el.addEventListener(eventName, wrappedHandler);\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 });\n } else 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 el.setAttribute(key, String(value));\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Materialize key on created element so DOM-based fast-path can find it\n const vnodeKey = (node as DOMElement).key;\n if (vnodeKey !== undefined) {\n el.setAttribute('data-key', String(vnodeKey));\n }\n\n // Add children - batch append\n const children = props.children || (node as DOMElement).children;\n if (children) {\n if (Array.isArray(children)) {\n // Check for missing keys on dynamic lists in dev mode\n if (process.env.NODE_ENV !== 'production') {\n let hasElements = false;\n let hasKeys = false;\n for (let i = 0; i < children.length; i++) {\n const item = children[i];\n if (typeof item === 'object' && item !== null && 'type' in item) {\n hasElements = true;\n const itemProps = (item as DOMElement).props || {};\n if ('key' in itemProps) {\n hasKeys = true;\n break;\n }\n }\n }\n if (hasElements && !hasKeys) {\n if (typeof console !== 'undefined') {\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 for (let i = 0; i < children.length; i++) {\n const dom = createDOMNode(children[i]);\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 // Component (function type) - inline execution\n if (typeof type === 'function') {\n // Check if this vnode has a marked context frame\n const frame = (node as ElementWithContext)[CONTEXT_FRAME_SYMBOL];\n\n // Capture context snapshot for this component's render\n // If the vnode was not explicitly marked, fall back to the current\n // ambient frame so the component's returned subtree inherits lexical\n // provider context.\n const snapshot = frame || getCurrentContextFrame();\n\n // Components must be synchronous. Async components are not supported.\n // Use `resource()` for async work — it provides explicit pending/value/error\n // semantics, generation-based staleness, and lifecycle-bound cancellation.\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 const vnodeAny = node as ElementWithContext & {\n __instance?: ComponentInstance;\n };\n let childInstance = vnodeAny.__instance;\n if (!childInstance) {\n // Create a new instance for this component so it can own hooks and mount ops\n childInstance = createComponentInstance(\n `comp-${Math.random().toString(36).slice(2, 7)}`,\n componentFn as ComponentFunction,\n props || {},\n null\n );\n vnodeAny.__instance = childInstance;\n }\n\n // If this vnode was marked with a context frame, record it on the\n // instance as its incoming provider frame so future re-renders and\n // async operations (resources) can reference the correct provider chain.\n if (snapshot) {\n childInstance.ownerFrame = snapshot;\n }\n\n // Render the component inline using the instance so hooks register correctly.\n // IMPORTANT: also keep the snapshot active while materializing the returned\n // subtree so nested providers can chain to the correct parent frame.\n const result = withContext(snapshot, () =>\n renderComponentInline(childInstance)\n );\n\n if (result instanceof Promise) {\n // Defensive: disallow components that return a Promise\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n // Create DOM subtree for the component result (under the same snapshot)\n const dom = withContext(snapshot, () => createDOMNode(result));\n\n // Mount the instance inline now that its DOM is materialized\n if (dom instanceof Element) {\n mountInstanceInline(childInstance, dom);\n } else {\n // For non-element results (fragments or text nodes) create a host\n // element to serve as the instance target. This host is not attached\n // to the document; it only provides a stable element for mount ops.\n const host = document.createElement('div');\n mountInstanceInline(childInstance, host);\n }\n\n return dom;\n }\n\n // Fragment support: render children without wrapper element\n // Uses Askr's Fragment symbol\n if (\n typeof type === 'symbol' &&\n (type === Fragment || String(type) === 'Symbol(Fragment)')\n ) {\n const fragment = document.createDocumentFragment();\n const children = props.children || (node as DOMElement).children;\n if (children) {\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const dom = createDOMNode(children[i]);\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 return null;\n}\n\n// Expose minimal renderer bridge for runtime fast-lane to call `evaluate`\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as unknown as Record<string, unknown>;\n _g.__ASKR_RENDERER = {\n 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 { evaluate } from '../renderer/dom';\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';\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 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\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 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';\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 unknown 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 if (instance.target) {\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 try {\n evaluate(result, instance.target);\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\n instance.target.innerHTML = domSnapshot;\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 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 if (!hadToken) {\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n }\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 in dev mode\n if (process.env.NODE_ENV !== 'production') {\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\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 in dev mode\n if (process.env.NODE_ENV !== 'production') {\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n if (state && !state._hasBeenRead) {\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 = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._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 = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._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 for (const cleanup of instance.cleanupFns) {\n cleanup();\n }\n instance.cleanupFns = [];\n\n // Remove deterministic state subscriptions for this instance\n if (instance._lastReadStates) {\n for (const s of instance._lastReadStates) {\n const readers = (\n s as unknown as { _readers?: Map<ComponentInstance, number> }\n )?._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","export class SSRDataMissingError extends Error {\n readonly code = 'SSR_DATA_MISSING';\n constructor(\n message = 'Server-side rendering requires all data to be available synchronously. This component attempted to use async data during SSR.'\n ) {\n super(message);\n this.name = 'SSRDataMissingError';\n Object.setPrototypeOf(this, SSRDataMissingError.prototype);\n }\n}\n\nexport class SSRInvariantError extends Error {\n readonly code = 'SSR_INVARIANT_VIOLATION';\n constructor(message: string) {\n super(message);\n this.name = 'SSRInvariantError';\n Object.setPrototypeOf(this, SSRInvariantError.prototype);\n }\n}\n","import type { Props } from '../shared/types';\nimport { SSRDataMissingError } from './errors';\n\nexport type SSRData = Record<string, unknown>;\n\nexport type SSRContext = {\n url: string;\n seed: number;\n data?: SSRData;\n params?: Record<string, string>;\n signal?: AbortSignal;\n};\n\n// Optional: scoped access for sink-based streaming SSR (sync and stack-scoped)\nlet current: SSRContext | null = null;\n\nexport function getSSRContext(): SSRContext | null {\n return current;\n}\n\nexport function withSSRContext<T>(ctx: SSRContext, fn: () => T): T {\n const prev = current;\n current = ctx;\n try {\n return fn();\n } finally {\n current = prev;\n }\n}\n\n// --- Render-only context (compatibility from previous ssrContext.ts) ---------\n// Deterministic seeded RNG used only inside the render context\nexport class SeededRNG {\n private seed: number;\n\n constructor(seed = 12345) {\n this.seed = seed | 0;\n }\n\n reset(seed = 12345) {\n this.seed = seed | 0;\n }\n\n // Simple LCG, stable and deterministic\n random(): number {\n this.seed = (this.seed * 9301 + 49297) % 233280;\n return this.seed / 233280;\n }\n}\n\n/** Context passed through a single render pass */\nexport type RenderContext = {\n seed: number;\n rng: SeededRNG;\n};\n\n/** Create a RenderContext from a seed */\nexport function createRenderContext(seed = 12345): RenderContext {\n const rng = new SeededRNG(seed);\n return { seed, rng };\n}\n\n// Lightweight module-level current context for SSR detection (render-only)\nlet currentSSRContext: RenderContext | null = null;\n\nexport function getCurrentSSRContext(): RenderContext | null {\n return currentSSRContext;\n}\n\nexport function runWithSSRContext<T>(ctx: RenderContext, fn: () => T): T {\n const prev = currentSSRContext;\n currentSSRContext = ctx;\n try {\n return fn();\n } finally {\n currentSSRContext = prev;\n }\n}\n\n/**\n * Centralized SSR enforcement helper — use this to throw a single, consistent\n * error when async data is encountered during synchronous SSR.\n */\nexport function throwSSRDataMissing(): never {\n throw new SSRDataMissingError();\n}\n\nexport { SSRDataMissingError };\n\n// Deterministic RNG (explicitly used by components via ctx if desired)\nexport function makeSeededRandom(seed: number) {\n // LCG\n let s = seed >>> 0;\n return () => {\n s = (s * 1664525 + 1013904223) >>> 0;\n return s / 0x100000000;\n };\n}\n\n// Helper: merge params into props for route handlers if needed\nexport function mergeRouteProps(\n props: Props | undefined,\n params?: Record<string, string>\n): Props {\n if (!params) return (props ?? {}) as Props;\n return { ...(props ?? {}), ...params } as Props;\n}\n","import type { SSRRoute } from './index';\n\nexport type ResourceDescriptor = {\n key: string;\n fn: (opts: { signal?: AbortSignal }) => Promise<unknown> | unknown;\n deps: unknown[];\n index: number;\n};\n\nexport type ResourcePlan = {\n resources: ResourceDescriptor[]; // declarative manifest in stable order\n};\n\n// Internal collection state (collection/prepass removed)\nlet keyCounter = 0;\nlet currentRenderData: Record<string, unknown> | null = null;\n\nexport function getCurrentRenderData(): Record<string, unknown> | null {\n return currentRenderData;\n}\n\nexport function resetKeyCounter() {\n keyCounter = 0;\n}\n\nexport function getNextKey(): string {\n return `r:${keyCounter++}`;\n}\n\nexport function startCollection() {\n throw new Error(\n 'SSR collection/prepass is removed: SSR is strictly synchronous; do not call startCollection()'\n );\n}\n\nexport function stopCollection(): ResourcePlan {\n throw new Error(\n 'SSR collection/prepass is removed: SSR is strictly synchronous; do not call stopCollection()'\n );\n}\n\nexport function registerResourceIntent(\n _fn: ResourceDescriptor['fn'],\n _deps: unknown[]\n): string {\n throw new Error(\n 'SSR resource intents collection is removed: resource() no longer registers intents for prepass'\n );\n}\n\nexport function startRenderPhase(data: Record<string, unknown> | null) {\n currentRenderData = data ?? null;\n resetKeyCounter();\n}\n\nexport function stopRenderPhase() {\n currentRenderData = null;\n resetKeyCounter();\n}\n\n// Resolve a plan (execute resource functions in declared order)\nexport async function resolvePlan(\n _plan: ResourcePlan\n): Promise<Record<string, unknown>> {\n throw new Error(\n 'SSR resolution of prepass plans is removed: SSR is strictly synchronous and does not support resolving async resource plans'\n );\n}\n\nexport function collectResources(_opts: {\n url: string;\n routes: SSRRoute[];\n}): ResourcePlan {\n throw new Error(\n 'SSR collection/prepass (collectResources) is removed: SSR is strictly synchronous and does not support prepass collection'\n );\n}\n\n// Backwards-compatible alias: new public API prefers the name `resolveResources`\nexport const resolveResources = resolvePlan;\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 * 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 unknown as Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as unknown 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(\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 createApp().'\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 * 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 createApp)\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","export interface RenderSink {\n write(html: string): void;\n end(): void;\n}\n\nexport class StringSink implements RenderSink {\n private chunks: string[] = [];\n\n write(html: string) {\n if (html) this.chunks.push(html);\n }\n\n end() {}\n\n toString() {\n return this.chunks.join('');\n }\n}\n\nexport class StreamSink implements RenderSink {\n constructor(\n private readonly onChunk: (html: string) => void,\n private readonly onComplete: () => void\n ) {}\n\n write(html: string) {\n if (html) this.onChunk(html);\n }\n\n end() {\n this.onComplete();\n }\n}\n","import type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport type { RenderSink } from './sink';\nimport {\n withSSRContext,\n type SSRContext,\n throwSSRDataMissing,\n} from './context';\n\ntype VNode = {\n type: string | Component;\n props?: Props;\n // Some JSX runtimes put children on `props.children`, others on `children`.\n children?: unknown[];\n};\n\nexport type Component = (\n props: Props,\n context?: { signal?: AbortSignal }\n) => VNode | JSXElement | string | number | null;\n\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\nconst escapeCache = new Map<string, string>();\n\nfunction escapeText(text: string): string {\n const cached = escapeCache.get(text);\n if (cached) return cached;\n\n const str = String(text);\n if (!str.includes('&') && !str.includes('<') && !str.includes('>')) {\n if (escapeCache.size < 256) escapeCache.set(text, str);\n return str;\n }\n\n const result = str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n if (escapeCache.size < 256) escapeCache.set(text, result);\n return result;\n}\n\nfunction escapeAttr(value: string): string {\n const str = String(value);\n if (\n !str.includes('&') &&\n !str.includes('\"') &&\n !str.includes(\"'\") &&\n !str.includes('<') &&\n !str.includes('>')\n ) {\n return str;\n }\n return str\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\nfunction styleObjToCss(value: unknown): string | null {\n if (!value || typeof value !== 'object') return null;\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) return '';\n // camelCase -> kebab-case\n let out = '';\n for (const [k, v] of entries) {\n if (v === null || v === undefined || v === false) continue;\n const prop = k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n out += `${prop}:${String(v)};`;\n }\n return out;\n}\n\nfunction renderAttrs(props?: Props): string {\n if (!props || typeof props !== 'object') return '';\n\n let result = '';\n for (const [key, value] of Object.entries(props)) {\n // Skip children in attrs\n if (key === 'children') continue;\n\n // Skip event handlers: onClick, onChange, ...\n if (key.startsWith('on') && key[2] === key[2]?.toUpperCase()) continue;\n\n // Skip internal props\n if (key.startsWith('_')) continue;\n\n const attrName = key === 'class' || key === 'className' ? 'class' : key;\n\n if (attrName === 'style') {\n const css = typeof value === 'string' ? value : styleObjToCss(value);\n if (css === null) continue;\n if (css === '') continue;\n result += ` style=\"${escapeAttr(css)}\"`;\n continue;\n }\n\n if (value === true) {\n result += ` ${attrName}`;\n } else if (value === false || value === null || value === undefined) {\n continue;\n } else {\n result += ` ${attrName}=\"${escapeAttr(String(value))}\"`;\n }\n }\n\n return result;\n}\n\nfunction isVNodeLike(x: unknown): x is VNode | JSXElement {\n return (\n !!x && typeof x === 'object' && 'type' in (x as Record<string, unknown>)\n );\n}\n\nfunction normalizeChildren(node: unknown): unknown[] {\n // Prefer explicit node.children; fallback to props.children\n const n = node as Record<string, unknown> | null | undefined;\n const direct = Array.isArray(n?.children) ? (n?.children as unknown[]) : null;\n const fromProps = (n?.props as Record<string, unknown> | undefined)\n ?.children as unknown;\n\n const raw = direct ?? fromProps;\n\n if (raw === null || raw === undefined || raw === false) return [];\n if (Array.isArray(raw)) return raw;\n return [raw];\n}\n\n// Note: renderChildToSink was removed in favor of direct renderNodeToSink inlined calls\n\nfunction renderChildrenToSink(\n children: unknown[],\n sink: RenderSink,\n ctx: SSRContext\n) {\n for (const c of children)\n renderNodeToSink(\n c as VNode | JSXElement | string | number | null,\n sink,\n ctx\n );\n}\n\nfunction executeComponent(\n type: Component,\n props: Props | undefined,\n ctx: SSRContext\n): unknown {\n // Synchronous only. If a user returns a Promise, that's a hard error.\n const res = type(props ?? {}, { signal: ctx.signal });\n if (\n res &&\n typeof res === 'object' &&\n 'then' in res &&\n typeof (res as unknown as PromiseLike<unknown>).then === 'function'\n ) {\n // Use centralized SSR failure mode — async components are not allowed during\n // synchronous SSR and must be pre-resolved by the developer.\n throwSSRDataMissing();\n }\n return res;\n}\n\nexport function renderNodeToSink(\n node: VNode | JSXElement | string | number | null,\n sink: RenderSink,\n ctx: SSRContext\n) {\n if (node === null || node === undefined) return;\n\n if (typeof node === 'string') {\n sink.write(escapeText(node));\n return;\n }\n if (typeof node === 'number') {\n sink.write(escapeText(String(node)));\n return;\n }\n\n if (!isVNodeLike(node)) return;\n\n const { type, props } = node as VNode;\n\n // Function component\n if (typeof type === 'function') {\n const out = withSSRContext(ctx, () =>\n executeComponent(type as Component, props, ctx)\n );\n renderNodeToSink(\n out as VNode | JSXElement | string | number | null,\n sink,\n ctx\n );\n return;\n }\n\n // Element node\n const tag = String(type);\n const attrs = renderAttrs(props);\n\n // void element\n if (VOID_ELEMENTS.has(tag)) {\n sink.write(`<${tag}${attrs} />`);\n return;\n }\n\n sink.write(`<${tag}${attrs}>`);\n const children = normalizeChildren(node);\n renderChildrenToSink(children, sink, ctx);\n sink.write(`</${tag}>`);\n}\n","/**\n * SSR - Server-Side Rendering\n *\n * Renders Askr components to static HTML strings for server-side rendering.\n * SSR is synchronous: async components are not supported; async work should use\n * `resource()` which is rejected during synchronous SSR. This module throws\n * when an async component or async resource is encountered during sync SSR.\n */\n\nimport type { JSXElement } from '../jsx/types';\nimport type { RouteHandler } from '../router/route';\nimport * as RouteModule from '../router/route';\nimport type { Props } from '../shared/types';\nimport {\n createRenderContext,\n runWithSSRContext,\n throwSSRDataMissing,\n type RenderContext,\n type SSRData,\n} from './context';\nimport {\n createComponentInstance,\n setCurrentComponentInstance,\n getCurrentComponentInstance,\n} from '../runtime/component';\nimport type { ComponentFunction } from '../runtime/component';\n\nexport { SSRDataMissingError } from './context';\n\ntype VNode = {\n type: string;\n props?: Props;\n children?: (string | VNode | null | undefined | false)[];\n};\n\nexport type Component = (\n props: Props,\n context?: { signal?: AbortSignal; ssr?: RenderContext }\n) => VNode | JSXElement;\n\n// HTML5 void elements that don't have closing tags\nconst VOID_ELEMENTS = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n\n// Escape cache for common values\nconst escapeCache = new Map<string, string>();\n\n/**\n * Escape HTML special characters in text content (optimized with cache)\n */\nfunction escapeText(text: string): string {\n const cached = escapeCache.get(text);\n if (cached) return cached;\n\n const str = String(text);\n // Fast path: check if escaping needed\n if (!str.includes('&') && !str.includes('<') && !str.includes('>')) {\n escapeCache.set(text, str);\n return str;\n }\n\n const result = str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n\n if (escapeCache.size < 256) {\n escapeCache.set(text, result);\n }\n return result;\n}\n\n/**\n * Escape HTML special characters in attribute values\n */\nfunction escapeAttr(value: string): string {\n const str = String(value);\n // Fast path: check if escaping needed\n if (\n !str.includes('&') &&\n !str.includes('\"') &&\n !str.includes(\"'\") &&\n !str.includes('<') &&\n !str.includes('>')\n ) {\n return str;\n }\n\n return str\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\n/**\n * Render attributes to HTML string, excluding event handlers\n * Optimized for minimal allocations\n */\nfunction renderAttrs(props?: Props): string {\n if (!props || typeof props !== 'object') return '';\n\n let result = '';\n for (const [key, value] of Object.entries(props)) {\n // Skip event handlers (onClick, onChange, etc.)\n if (key.startsWith('on') && key[2] === key[2].toUpperCase()) {\n continue;\n }\n // Skip internal props\n if (key.startsWith('_')) {\n continue;\n }\n\n // Normalize class attribute (`class` preferred, accept `className` for compatibility)\n const attrName = key === 'class' || key === 'className' ? 'class' : key;\n\n // Boolean attributes\n if (value === true) {\n result += ` ${attrName}`;\n } else if (value === false || value === null || value === undefined) {\n // Skip falsy values\n continue;\n } else {\n // Regular attributes\n result += ` ${attrName}=\"${escapeAttr(String(value))}\"`;\n }\n }\n return result;\n}\n\n/**\n * Synchronous rendering helpers (used for strictly synchronous SSR)\n */\nfunction renderChildSync(child: unknown, ctx: RenderContext): string {\n if (typeof child === 'string') return escapeText(child);\n if (typeof child === 'number') return escapeText(String(child));\n if (child === null || child === undefined || child === false) return '';\n if (typeof child === 'object' && child !== null && 'type' in child) {\n return renderNodeSync(child as unknown as JSXElement | VNode, ctx);\n }\n return '';\n}\n\nfunction renderChildrenSync(\n children: unknown[] | undefined,\n ctx: RenderContext\n): string {\n if (!children || !Array.isArray(children) || children.length === 0) return '';\n let result = '';\n for (const child of children) result += renderChildSync(child, ctx);\n return result;\n}\n\n/**\n * Render a VNode synchronously. Throws if an async component is encountered.\n */\nfunction renderNodeSync(node: VNode | JSXElement, ctx: RenderContext): string {\n const { type, props } = node;\n\n if (typeof type === 'function') {\n const result = executeComponentSync(type as Component, props, ctx);\n if (result instanceof Promise) {\n // Use centralized SSR error to maintain a single failure mode\n throwSSRDataMissing();\n }\n return renderNodeSync(result as VNode | JSXElement, ctx);\n }\n\n const typeStr = type as string;\n if (VOID_ELEMENTS.has(typeStr)) {\n const attrs = renderAttrs(props);\n return `<${typeStr}${attrs} />`;\n }\n\n const attrs = renderAttrs(props);\n const children = (node as VNode).children;\n const childrenHtml = renderChildrenSync(children, ctx);\n return `<${typeStr}${attrs}>${childrenHtml}</${typeStr}>`;\n}\n\n/**\n * Execute a component function (synchronously or async) and return VNode\n */\n/**\n * Execute a component synchronously inside a render-only context.\n * This must not create or reuse runtime ComponentInstance objects. We pass\n * the render context explicitly as `context.ssr` in the second argument so\n * components can opt-in to deterministic randomness/time via the provided RNG.\n */\nfunction executeComponentSync(\n component: Component,\n props: Record<string, unknown> | undefined,\n ctx: RenderContext\n): VNode | JSXElement {\n // Dev-only: enforce SSR purity with clear messages. We temporarily override\n // `Math.random` and `Date.now` while rendering to produce a targeted error\n // if components call them directly. We restore them immediately afterwards.\n const originalRandom = Math.random;\n const originalDateNow = Date.now;\n\n try {\n if (process.env.NODE_ENV !== 'production') {\n (Math as unknown as { random: () => number }).random = () => {\n throw new Error(\n 'SSR Strict Purity: Math.random is not allowed during synchronous SSR. Use the provided `ssr` context RNG instead.'\n );\n };\n (Date as unknown as { now: () => number }).now = () => {\n throw new Error(\n 'SSR Strict Purity: Date.now is not allowed during synchronous SSR. Pass timestamps explicitly or use deterministic helpers.'\n );\n };\n }\n\n // Create a temporary, lightweight component instance so runtime APIs like\n // `state()` and `route()` can be called during SSR render. We avoid mounting\n // or side-effects by not attaching the instance to any DOM target.\n const prev = getCurrentComponentInstance();\n const temp = createComponentInstance(\n 'ssr-temp',\n component as unknown as ComponentFunction,\n (props || {}) as Props,\n null\n );\n temp.ssr = true;\n setCurrentComponentInstance(temp);\n try {\n return runWithSSRContext(ctx, () => {\n const result = component((props || {}) as Props, { ssr: ctx });\n if (result instanceof Promise) {\n // Use the centralized SSR error for async data/components during SSR\n throwSSRDataMissing();\n }\n return result as VNode | JSXElement;\n });\n } finally {\n // Restore the previous instance (if any)\n setCurrentComponentInstance(prev);\n }\n } finally {\n (Math as unknown as { random: () => number }).random = originalRandom;\n (Date as unknown as { now: () => number }).now = originalDateNow;\n }\n}\n\n/**\n * Single synchronous SSR entrypoint: render a component to an HTML string.\n * This is strictly synchronous and deterministic. Optionally provide a seed\n * for deterministic randomness via `options.seed`.\n */\nexport function renderToStringSync(\n component: (\n props?: Record<string, unknown>\n ) => VNode | JSXElement | string | number | null,\n props?: Record<string, unknown>,\n options?: { seed?: number; data?: SSRData }\n): string {\n const seed = options?.seed ?? 12345;\n // Start render-phase keying (aligns with collectResources)\n const ctx = createRenderContext(seed);\n // Provide optional SSR data via options.data\n startRenderPhase(options?.data ?? null);\n try {\n const node = executeComponentSync(component as Component, props || {}, ctx);\n return renderNodeSync(node, ctx);\n } finally {\n stopRenderPhase();\n }\n}\n\n// Synchronous server render for strict checks. Routes must be resolved before\n// the render pass so no route() calls happen during rendering.\nexport function renderToStringSyncForUrl(opts: {\n url: string;\n routes: Array<{ path: string; handler: RouteHandler; namespace?: string }>;\n options?: { seed?: number; data?: SSRData };\n}): string {\n const { url, routes, options } = opts;\n // Register routes synchronously using route() (already available in module scope)\n const {\n clearRoutes,\n route,\n setServerLocation,\n lockRouteRegistration,\n resolveRoute,\n } = RouteModule;\n\n clearRoutes();\n for (const r of routes) {\n route(r.path, r.handler, r.namespace);\n }\n\n setServerLocation(url);\n if (process.env.NODE_ENV === 'production') lockRouteRegistration();\n\n const resolved = resolveRoute(url);\n if (!resolved)\n throw new Error(`renderToStringSync: no route found for url: ${url}`);\n\n const seed = options?.seed ?? 12345;\n const ctx = createRenderContext(seed);\n // Start render-phase keying (aligns with collectResources)\n startRenderPhase(options?.data ?? null);\n try {\n const node = executeComponentSync(\n resolved.handler as Component,\n resolved.params || {},\n ctx\n );\n return renderNodeSync(node, ctx);\n } finally {\n stopRenderPhase();\n }\n}\n\n// --- Streaming sink-based renderer (v2) --------------------------------------------------\nimport { StringSink, StreamSink } from './sink';\nimport { renderNodeToSink } from './render';\nimport {\n startRenderPhase,\n stopRenderPhase,\n collectResources,\n resolvePlan,\n resolveResources,\n ResourcePlan,\n} from './data';\n\nexport type SSRRoute = {\n path: string;\n handler: RouteHandler;\n namespace?: string;\n};\n\nexport function renderToString(\n component: (\n props?: Record<string, unknown>\n ) => VNode | JSXElement | string | number | null\n): string;\nexport function renderToString(opts: {\n url: string;\n routes: SSRRoute[];\n seed?: number;\n data?: SSRData;\n}): string;\nexport function renderToString(arg: unknown): string {\n // Convenience: if a component function is passed, delegate to sync render\n if (typeof arg === 'function') {\n return renderToStringSync(\n arg as (\n props?: Record<string, unknown>\n ) => VNode | JSXElement | string | number | null\n );\n }\n const opts = arg as {\n url: string;\n routes: SSRRoute[];\n seed?: number;\n data?: SSRData;\n };\n const sink = new StringSink();\n renderToSinkInternal({ ...opts, sink });\n sink.end();\n return sink.toString();\n}\n\nexport function renderToStream(opts: {\n url: string;\n routes: SSRRoute[];\n seed?: number;\n data?: SSRData;\n onChunk(html: string): void;\n onComplete(): void;\n}): void {\n const sink = new StreamSink(opts.onChunk, opts.onComplete);\n renderToSinkInternal({ ...opts, sink });\n sink.end();\n}\n\nfunction renderToSinkInternal(opts: {\n url: string;\n routes: SSRRoute[];\n seed?: number;\n data?: SSRData;\n sink: { write(html: string): void; end(): void };\n}) {\n const { url, routes, seed = 1, data, sink } = opts;\n\n // Route resolution happens BEFORE render pass\n const {\n clearRoutes,\n route,\n setServerLocation,\n lockRouteRegistration,\n resolveRoute,\n } = RouteModule;\n\n clearRoutes();\n for (const r of routes) route(r.path, r.handler, r.namespace);\n\n setServerLocation(url);\n if (process.env.NODE_ENV === 'production') lockRouteRegistration();\n\n const resolved = resolveRoute(url);\n if (!resolved) throw new Error(`SSR: no route found for url: ${url}`);\n\n const ctx = {\n url,\n seed,\n data,\n params: resolved.params,\n signal: undefined as AbortSignal | undefined,\n };\n\n // Render the resolved handler with params\n const node = resolved.handler(resolved.params) as\n | VNode\n | JSXElement\n | string\n | number\n | null;\n\n // Start render-phase keying so resource() can lookup resolved `data` by key\n startRenderPhase(data || null);\n try {\n renderNodeToSink(node, sink, ctx);\n } finally {\n stopRenderPhase();\n }\n}\n\nexport { collectResources, resolvePlan, resolveResources, ResourcePlan };\n","/**\n * Askr: Actor-backed deterministic UI framework\n *\n * Public API surface — only users should import from here\n */\n\n// Runtime primitives\nexport { state } from './runtime/state';\nexport type { State } from './runtime/state';\nexport { getSignal } from './runtime/component';\nexport { scheduleEventHandler } from './runtime/scheduler';\n\n// Context (spec-defined, currently stubbed)\nexport { defineContext, readContext } from './runtime/context';\nexport type { Context } from './runtime/context';\n\n// Bindings (spec-defined, currently stubbed)\nexport { resource } from './runtime/operations';\nexport type { DataResult } from './runtime/operations';\n\n// App bootstrap (explicit startup APIs)\nexport {\n createApp,\n createIsland,\n createSPA,\n hydrateSPA,\n cleanupApp,\n hasApp,\n} from './app/createApp';\nexport type {\n IslandConfig,\n SPAConfig,\n HydrateSPAConfig,\n} from './app/createApp';\n\n// Routing\n// Public render-time accessor: route() (also supports route registration when called with args)\nexport {\n route,\n setServerLocation,\n type RouteSnapshot,\n type RouteMatch,\n} from './router/route';\nexport { layout } from './router/layouts';\n// Keep route registration utilities available under a distinct name to avoid\n// collision with the render-time accessor.\nexport {\n clearRoutes,\n getRoutes,\n getNamespaceRoutes,\n unloadNamespace,\n getLoadedNamespaces,\n} from './router/route';\nexport { navigate } from './router/navigate';\nexport type { Route, RouteHandler } from './router/route';\n\n// Components\nexport { Link } from './components/Link';\nexport type { LinkProps } from './components/Link';\n\n// Standard library helpers are unstable and not re-exported from core.\n\n// SSR - Server-side rendering (sync-only APIs)\nexport {\n renderToStringSync,\n renderToStringSyncForUrl,\n renderToString,\n renderToStream,\n collectResources,\n resolveResources,\n} from './ssr';\n\n// Re-export JSX runtime for tsconfig jsxImportSource\nexport { jsx, jsxs, Fragment } from './jsx/jsx-runtime';\n\n// Expose common APIs to globalThis for test-suite compatibility (legacy test patterns)\n// These are safe to export globally and make migrating tests simpler.\nimport { route, getRoutes } from './router/route';\nimport { navigate } from './router/navigate';\nimport {\n createApp,\n createIsland,\n createSPA,\n hydrateSPA,\n} from './app/createApp';\n\nif (typeof globalThis !== 'undefined') {\n const g = globalThis as unknown as Record<string, unknown>;\n if (!g.createApp) g.createApp = createApp;\n if (!g.createIsland) g.createIsland = createIsland;\n if (!g.createSPA) g.createSPA = createSPA;\n if (!g.hydrateSPA) g.hydrateSPA = hydrateSPA;\n if (!g.route) g.route = route;\n if (!g.getRoutes) g.getRoutes = getRoutes;\n if (!g.navigate) g.navigate = navigate;\n}\n\n// Public types\nexport type { Props } from './shared/types';\n","/**\n * State primitive for Askr components\n * Optimized for minimal overhead and fast updates\n *\n * INVARIANTS ENFORCED:\n * - state() only callable during component render (currentInstance exists)\n * - state() called at top-level only (indices must be monotonically increasing)\n * - state values persist across re-renders (stored in stateValues array)\n * - state.set() cannot be called during render (causes infinite loops)\n * - state.set() always enqueues through scheduler (never direct mutation)\n * - state.set() callback (notifyUpdate) always available\n */\n\nimport { globalScheduler } from './scheduler';\nimport {\n getCurrentInstance,\n getNextStateIndex,\n type ComponentInstance,\n} from './component';\nimport { invariant } from '../dev/invariant';\nimport { isBulkCommitActive } from './fastlane';\n\n/**\n * State value holder - callable to read, has set method to update\n * @example\n * const count = state(0);\n * count(); // read: 0\n * count.set(1); // write: triggers re-render\n */\nexport interface State<T> {\n (): T;\n set(value: T): void;\n _hasBeenRead?: boolean; // Internal: track if state has been read during render\n _readers?: Map<ComponentInstance, number>; // Internal: map of readers -> last committed token\n}\n\n/**\n * Creates a local state value for a component\n * Optimized for:\n * - O(1) read performance\n * - Minimal allocation per state\n * - Fast scheduler integration\n *\n * IMPORTANT: state() must be called during component render execution.\n * It captures the current component instance from context.\n * Calling outside a component function will throw an error.\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render\n * export function Counter() {\n * const count = state(0);\n * return { type: 'button', children: [count()] };\n * }\n *\n * // ❌ Wrong: called outside component\n * const count = state(0);\n * export function BadComponent() {\n * return { type: 'div' };\n * }\n * ```\n */\nexport function state<T>(initialValue: T): State<T> {\n // INVARIANT: state() must be called during component render\n const instance = getCurrentInstance();\n if (!instance) {\n throw new Error(\n 'state() can only be called during component render execution. ' +\n 'Move state() calls to the top level of your component function.'\n );\n }\n\n const index = getNextStateIndex();\n const stateValues = instance.stateValues;\n\n // INVARIANT: Detect conditional state() calls by validating index order\n // If indices go backward, state() was called conditionally\n if (index < instance.stateIndexCheck) {\n throw new Error(\n `State index violation: state() call at index ${index}, ` +\n `but previously saw index ${instance.stateIndexCheck}. ` +\n `This happens when state() is called conditionally (inside if/for/etc). ` +\n `Move all state() calls to the top level of your component function, ` +\n `before any conditionals.`\n );\n }\n\n // INVARIANT: stateIndexCheck advances monotonically\n invariant(\n index >= instance.stateIndexCheck,\n '[State] State indices must increase monotonically'\n );\n instance.stateIndexCheck = index;\n\n // INVARIANT: On subsequent renders, validate that state calls happen in same order\n if (instance.firstRenderComplete) {\n // Check if this index was expected based on first render\n if (!instance.expectedStateIndices.includes(index)) {\n throw new Error(\n `Hook order violation: state() called at index ${index}, ` +\n `but this index was not in the first render's sequence [${instance.expectedStateIndices.join(', ')}]. ` +\n `This usually means state() is inside a conditional or loop. ` +\n `Move all state() calls to the top level of your component function.`\n );\n }\n } else {\n // First render - record this index in the expected sequence\n instance.expectedStateIndices.push(index);\n }\n\n // INVARIANT: Reuse existing state if it exists (fast path on re-renders)\n // This ensures state identity and persistence and enforces ownership stability\n if (stateValues[index]) {\n const existing = stateValues[index] as State<T> & {\n _owner?: ComponentInstance;\n };\n // Ownership must be stable: the state cell belongs to the instance that\n // created it and must never change. This checks for accidental reuse.\n if (existing._owner !== instance) {\n throw new Error(\n `State ownership violation: state() called at index ${index} is owned by a different component instance. ` +\n `State ownership is positional and immutable.`\n );\n }\n return existing as State<T>;\n }\n\n // Create new state (slow path, only on first render) — delegated to helper\n const cell = createStateCell(initialValue, instance);\n\n // INVARIANT: Store state in instance for persistence across renders\n stateValues[index] = cell;\n\n return cell;\n}\n\n/**\n * Internal helper: create the backing state cell (value + readers + set semantics)\n * This extraction makes it easier to later split hook wiring from storage.\n */\nfunction createStateCell<T>(\n initialValue: T,\n instance: ComponentInstance\n): State<T> {\n let value = initialValue;\n\n // Per-state reader map: component -> last-committed render token\n const readers = new Map<ComponentInstance, number>();\n\n // Use a function as the state object (callable directly)\n function read(): T {\n (read as State<T>)._hasBeenRead = true;\n\n // Record that the current instance read this state during its in-progress render\n const inst = getCurrentInstance();\n if (inst && inst._currentRenderToken !== undefined) {\n if (!inst._pendingReadStates) inst._pendingReadStates = new Set();\n inst._pendingReadStates.add(read as State<T>);\n }\n\n return value;\n }\n\n // Attach the readers map to the callable so other runtime parts can access it\n (read as State<T>)._readers = readers;\n\n // Record explicit ownership of this state cell. Ownership is the component\n // instance that created the state cell and must never change for the life\n // of the cell. We expose this for runtime invariant checks/tests.\n (read as unknown as { _owner?: ComponentInstance })._owner = instance;\n\n // Attach set method directly to function\n read.set = (newValue: T): void => {\n // INVARIANT: State cannot be mutated during component render\n // (when currentInstance is non-null). It must be scheduled for consistency.\n // NOTE: Skip invariant checks in production for graceful degradation\n const currentInst = getCurrentInstance();\n if (currentInst !== null && process.env.NODE_ENV !== 'production') {\n throw new Error(\n `[Askr] state.set() cannot be called during component render. ` +\n `State mutations during render break the actor model and cause infinite loops. ` +\n `Move state updates to event handlers or use conditional rendering instead.`\n );\n }\n\n // PRODUCTION FALLBACK: Skip state updates during render to prevent infinite loops\n if (currentInst !== null && process.env.NODE_ENV === 'production') {\n return;\n }\n\n // Skip work if value didn't change\n if (Object.is(value, newValue)) return;\n\n // If a bulk commit is active, update backing value only and DO NOT notify or enqueue.\n // Bulk commits must be side-effect silent with respect to runtime notifications.\n if (isBulkCommitActive()) {\n // In bulk commit mode we must be side-effect free: update backing\n // value only and do not notify, enqueue, or log.\n value = newValue;\n return;\n }\n\n // INVARIANT: Update the value\n value = newValue;\n\n // notifyUpdate may be temporarily unavailable (e.g. during hydration).\n // We intentionally avoid logging here to keep the state mutation path\n // side-effect free. The scheduler will process updates when the system\n // is stable.\n\n // After value change, notify only components that *read* this state in their last committed render\n const readersMap = (read as State<T>)._readers as\n | Map<ComponentInstance, number>\n | undefined;\n if (readersMap) {\n for (const [subInst, token] of readersMap) {\n // Only notify if the component's last committed render token matches the token recorded\n // when it last read this state. This ensures we only wake components that actually\n // observed the state in their most recent render.\n if (subInst.lastRenderToken !== token) continue;\n if (!subInst.hasPendingUpdate) {\n // Log enqueue decision for subInst\n\n subInst.hasPendingUpdate = true;\n const subTask = subInst._pendingFlushTask;\n if (subTask) globalScheduler.enqueue(subTask);\n else\n globalScheduler.enqueue(() => {\n subInst.hasPendingUpdate = false;\n subInst.notifyUpdate?.();\n });\n }\n }\n }\n\n // OPTIMIZATION: Batch state updates from the same component within the same event loop tick\n // Only enqueue the owner component if it actually read this state during its last committed render\n const readersMapForOwner = readersMap;\n const ownerRecordedToken = readersMapForOwner?.get(instance);\n const ownerShouldEnqueue =\n // Normal case: owner read this state in last committed render\n ownerRecordedToken !== undefined &&\n instance.lastRenderToken === ownerRecordedToken;\n\n if (ownerShouldEnqueue && !instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // INVARIANT: All state updates go through scheduler\n // Use prebound task to avoid allocating a closure per update\n // Fallback to a safe closure if the prebound task is not present\n const task = instance._pendingFlushTask;\n if (task) globalScheduler.enqueue(task);\n else\n globalScheduler.enqueue(() => {\n instance.hasPendingUpdate = false;\n instance.notifyUpdate?.();\n });\n }\n };\n\n return read as State<T>;\n}\n","import {\n getCurrentComponentInstance,\n registerMountOperation,\n type ComponentInstance,\n} from './component';\nimport { getCurrentContextFrame } from './context';\nimport { ResourceCell } from './resource_cell';\nimport { state } from './state';\nimport { getDeriveCache } from '../shared/derive_cache';\nimport {\n getCurrentSSRContext,\n throwSSRDataMissing,\n SSRDataMissingError,\n} from '../ssr/context';\nimport { getCurrentRenderData, getNextKey } from '../ssr/data';\n\n// Memoization cache for derive() (centralized)\n\nexport interface DataResult<T> {\n value: T | null;\n pending: boolean;\n error: Error | null;\n refresh(): void;\n}\n\n/**\n * Resource primitive — simple, deterministic async primitive\n * Usage: resource(fn, deps)\n * - fn receives { signal }\n * - captures execution context once at creation (synchronous step only)\n * - executes at most once per generation; stale async results are ignored\n * - refresh() cancels in-flight execution, increments generation and re-runs\n * - exposes { value, pending, error, refresh }\n * - during SSR, async results are disallowed and will throw synchronously\n */\nexport function resource<T>(\n fn: (opts: { signal: AbortSignal }) => Promise<T> | T,\n deps: unknown[] = []\n): DataResult<T> {\n const instance = getCurrentComponentInstance();\n // Create a non-null alias early so it can be used in nested closures\n // without TypeScript complaining about possible null access.\n const inst = instance as ComponentInstance;\n\n if (!instance) {\n // If we're in a synchronous SSR render that has resolved data, use it.\n const renderData = getCurrentRenderData();\n if (renderData) {\n const key = getNextKey();\n if (!(key in renderData)) {\n throwSSRDataMissing();\n }\n const val = renderData[key] as T;\n return {\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n } as DataResult<T>;\n }\n\n // If we are in an SSR render pass without supplied data, throw for clarity.\n const ssrCtx = getCurrentSSRContext();\n if (ssrCtx) {\n throwSSRDataMissing();\n }\n\n // No active component instance and not in SSR render with data. Return a\n // pending snapshot for non-SSR usage (e.g., runtime usage outside render).\n return {\n value: null,\n pending: true,\n error: null,\n refresh: () => {},\n } as DataResult<T>;\n }\n\n // Internal ResourceCell — pure state machine now moved to its own module\n // to keep component wiring separate and ensure no component access here.\n // (See ./resource_cell.ts)\n\n // If we're in a synchronous SSR render that was supplied resolved data, use it\n const renderData = getCurrentRenderData();\n if (renderData) {\n // Deterministic key generation: the collection step and render step use\n // the same incremental key generation to align resources.\n const key = getNextKey();\n if (!(key in renderData)) {\n throwSSRDataMissing();\n }\n\n // Commit synchronous value from render data and return a stable snapshot\n const val = renderData[key] as T;\n\n const holder = state<{ cell?: ResourceCell<T>; snapshot: DataResult<T> }>({\n cell: undefined,\n snapshot: {\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n },\n });\n\n const h = holder();\n h.snapshot.value = val;\n h.snapshot.pending = false;\n h.snapshot.error = null;\n holder.set(h);\n return h.snapshot;\n }\n\n // Persist a holder so the snapshot identity is stable across renders.\n const holder = state<{ cell?: ResourceCell<T>; snapshot: DataResult<T> }>({\n cell: undefined,\n snapshot: {\n value: null,\n pending: true,\n error: null,\n refresh: () => {},\n },\n });\n\n const h = holder();\n\n // Initialize cell on first call\n if (!h.cell) {\n const frame = getCurrentContextFrame();\n const cell = new ResourceCell<T>(fn, deps, frame);\n h.cell = cell;\n h.snapshot = cell.snapshot as DataResult<T>;\n\n // Subscribe and schedule component updates when cell changes\n const unsubscribe = cell.subscribe(() => {\n const cur = holder();\n cur.snapshot.value = cell.snapshot.value;\n cur.snapshot.pending = cell.snapshot.pending;\n cur.snapshot.error = cell.snapshot.error;\n holder.set(cur);\n try {\n inst._enqueueRun?.();\n } catch {\n // ignore\n }\n });\n\n // Cleanup on unmount\n inst.cleanupFns.push(() => {\n unsubscribe();\n cell.abort();\n });\n\n // Start immediately (not tied to mount timing); SSR will throw if async\n try {\n // Avoid notifying subscribers synchronously during render — update\n // holder.snapshot in-place instead to prevent state.set() during render.\n cell.start(inst.ssr ?? false, false);\n // If the run completed synchronously, reflect the result into the holder\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n // Do not call holder.set() here — we are still in render; the host\n // component will read the snapshot immediately.\n }\n } catch (err) {\n if (err instanceof SSRDataMissingError) throw err;\n // Synchronous error — reflect into snapshot\n cell.error = err as Error;\n cell.pending = false;\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n // Do not call holder.set() here for the same reason as above\n }\n }\n\n const cell = h.cell!;\n\n // Detect dependency changes and refresh immediately\n const depsChanged =\n !cell.deps ||\n cell.deps.length !== deps.length ||\n cell.deps.some((d, i) => d !== deps[i]);\n\n if (depsChanged) {\n cell.deps = deps.slice();\n cell.generation++;\n cell.pending = true;\n cell.error = null;\n try {\n cell.start(inst.ssr ?? false, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n } catch (err) {\n if (err instanceof SSRDataMissingError) throw err;\n cell.error = err as Error;\n cell.pending = false;\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n }\n\n // Return the stable snapshot object owned by the cell\n return h.snapshot;\n}\n\nexport function derive<TIn, TOut>(\n source:\n | { value: TIn | null; pending?: boolean; error?: Error | null }\n | TIn\n | (() => TIn),\n map: (value: TIn) => TOut\n): TOut | null {\n // Extract the actual value\n let value: TIn;\n if (typeof source === 'function' && !('value' in source)) {\n // It's a function (not a binding object with value property)\n value = (source as () => TIn)();\n } else {\n value = (source as { value?: TIn | null })?.value ?? (source as TIn);\n }\n if (value == null) return null;\n\n // Get or create memoization cache for this component\n const instance = getCurrentComponentInstance();\n if (!instance) {\n // No component context - just compute eagerly\n return map(value as TIn);\n }\n\n // Get or create the cache map for this component\n const cache = getDeriveCache(instance);\n\n // Check if we already have a cached result for this source value\n if (cache.has(value)) {\n return cache.get(value) as TOut;\n }\n\n // Compute and cache the result\n const result = map(value as TIn);\n cache.set(value, result);\n return result;\n}\n\nexport function on(\n target: EventTarget,\n event: string,\n handler: EventListener\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the listener to be attached on mount. If the owner is not the\n // root app instance, fail loudly to prevent silent no-op behavior.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] on() may only be used in root components');\n }\n target.addEventListener(event, handler);\n // Return cleanup function\n return () => {\n target.removeEventListener(event, handler);\n };\n });\n}\n\nexport function timer(intervalMs: number, fn: () => void): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the timer to be started on mount. Fail loudly when used outside\n // of the root component to avoid silent no-ops.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] timer() may only be used in root components');\n }\n const id = setInterval(fn, intervalMs);\n // Return cleanup function\n return () => {\n clearInterval(id);\n };\n });\n}\n\nexport function stream<T>(\n _source: unknown,\n _options?: Record<string, unknown>\n): { value: T | null; pending: boolean; error: Error | null } {\n // Stub implementation: no-op.\n return { value: null, pending: true, error: null };\n}\n\nexport function task(\n fn: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the task to run on mount. Fail loudly when used outside the root\n // component so callers get immediate feedback rather than silent no-op.\n registerMountOperation(async () => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] task() may only be used in root components');\n }\n // Execute the task (may be async) and return its cleanup\n return await fn();\n });\n}\n\n/**\n * Capture the result of a synchronous expression at call time and return a\n * thunk that returns the captured value later. This is a low-level helper for\n * cases where async continuations need to observe a snapshot of values at the\n * moment scheduling occurred.\n *\n * Usage (public API):\n * const snapshot = capture(() => someState());\n * Promise.resolve().then(() => { use(snapshot()); });\n */\nexport function capture<T>(fn: () => T): () => T {\n const value = fn();\n return () => value;\n}\n","import { withAsyncResourceContext, type ContextFrame } from './context';\nimport { logger } from '../dev/logger';\nimport { throwSSRDataMissing } from '../ssr/context';\n\n/**\n * Pure, component-agnostic ResourceCell state machine.\n * - Holds value/pending/error/generation/controller\n * - Exposes a stable `snapshot` object: { value, pending, error, refresh }\n * - Uses `withAsyncResourceContext` to bind the synchronous execution step\n * to a captured frame. Continuations after await do not see the frame.\n */\nexport class ResourceCell<U> {\n value: U | null = null;\n pending = true;\n error: Error | null = null;\n generation = 0;\n controller: AbortController | null = null;\n deps: unknown[] | null = null;\n resourceFrame: ContextFrame | null = null;\n\n private subscribers = new Set<() => void>();\n\n readonly snapshot: {\n value: U | null;\n pending: boolean;\n error: Error | null;\n refresh: () => void;\n };\n\n private readonly fn: (opts: { signal: AbortSignal }) => Promise<U> | U;\n\n constructor(\n fn: (opts: { signal: AbortSignal }) => Promise<U> | U,\n deps: unknown[] | null,\n resourceFrame: ContextFrame | null\n ) {\n this.fn = fn;\n this.deps = deps ? deps.slice() : null;\n this.resourceFrame = resourceFrame;\n this.snapshot = {\n value: null,\n pending: true,\n error: null,\n refresh: () => this.refresh(),\n };\n }\n\n subscribe(cb: () => void): () => void {\n this.subscribers.add(cb);\n return () => this.subscribers.delete(cb);\n }\n\n private notifySubscribers() {\n this.snapshot.value = this.value;\n this.snapshot.pending = this.pending;\n this.snapshot.error = this.error;\n for (const cb of this.subscribers) cb();\n }\n\n start(ssr = false, notify = true) {\n const generation = this.generation;\n\n this.controller?.abort();\n const controller = new AbortController();\n this.controller = controller;\n this.pending = true;\n this.error = null;\n if (notify) this.notifySubscribers();\n\n let result: Promise<U> | U;\n try {\n // Execute only the synchronous step inside the frozen resource frame.\n result = withAsyncResourceContext(this.resourceFrame, () =>\n this.fn({ signal: controller.signal })\n );\n } catch (err) {\n this.pending = false;\n this.error = err as Error;\n if (notify) this.notifySubscribers();\n return;\n }\n\n if (!(result instanceof Promise)) {\n this.value = result as U;\n this.pending = false;\n this.error = null;\n if (notify) this.notifySubscribers();\n return;\n }\n\n if (ssr) {\n // During SSR async results are disallowed\n throwSSRDataMissing();\n }\n\n (result as Promise<U>)\n .then((val) => {\n if (this.generation !== generation) return;\n if (this.controller !== controller) return;\n this.value = val;\n this.pending = false;\n this.error = null;\n this.notifySubscribers();\n })\n .catch((err) => {\n if (this.generation !== generation) return;\n this.pending = false;\n this.error = err as Error;\n try {\n logger.error('[Askr] Async resource error:', err);\n } catch {\n /* ignore logging errors */\n }\n this.notifySubscribers();\n });\n }\n\n refresh() {\n this.generation++;\n this.controller?.abort();\n this.start();\n }\n\n abort() {\n this.controller?.abort();\n }\n}\n","/**\n * App bootstrap and mount\n */\n\nimport {\n createComponentInstance,\n mountComponent,\n cleanupComponent,\n type ComponentFunction,\n type ComponentInstance,\n} from '../runtime/component';\nimport { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport { removeAllListeners } from '../renderer/dom';\nimport { registerAppInstance, initializeNavigation } from '../router/navigate';\n\nlet componentIdCounter = 0;\n\n// Track instances by root element to support multiple createApp calls on same root\nconst instancesByRoot = new WeakMap<Element, ComponentInstance>();\n\n// Symbol for storing cleanup on elements\nconst CLEANUP_SYMBOL = Symbol.for('__tempoCleanup__');\n\n// Type for elements that have cleanup functions attached\ninterface ElementWithCleanup extends Element {\n [CLEANUP_SYMBOL]?: () => void;\n}\n\nexport interface AppConfig {\n root: Element | string;\n component: ComponentFunction;\n}\n\n/**\n * Bootstrap and mount app on client\n * Supports both sync and async components\n *\n * If createApp is called multiple times on the same root, the existing instance\n * is reused and its component function is updated. This ensures:\n * - Generation tokens work correctly (old async renders don't overwrite new ones)\n * - State is preserved across updates (if desired)\n * - DOM is diffed/updated rather than replaced\n */\n// Backcompat wrapper for test-suite migration and user feedback.\n// If called with `routes` a hard error is thrown to encourage migration to\n// `createSPA`/`hydrateSPA`. Otherwise, delegate to `createIsland` to preserve\n// legacy single-root enhancement behavior during the migration period.\nexport function createApp(config: AppConfig | SPAConfig): void {\n if (!config || typeof config !== 'object') {\n throw new Error('createApp requires a config object');\n }\n // Routed apps must use createSPA/hydrateSPA explicitly\n if ('routes' in config) {\n throw new Error(\n 'The `createApp` API is removed. Use `createSPA({ root, routes })` for routed apps, or `hydrateSPA({ root, routes })` for SSR hydration.'\n );\n }\n // Treat remaining calls as islands for backwards compatibility during tests\n // and guide users to use `createIsland` in migration docs/tests.\n const appCfg = config as AppConfig;\n createIsland({\n root: appCfg.root,\n component: appCfg.component,\n });\n}\n\nfunction attachCleanupForRoot(\n rootElement: Element,\n instance: ComponentInstance\n) {\n (rootElement as ElementWithCleanup)[CLEANUP_SYMBOL] = () => {\n removeAllListeners(rootElement);\n cleanupComponent(instance as ComponentInstance);\n };\n\n try {\n const descriptor =\n Object.getOwnPropertyDescriptor(rootElement, 'innerHTML') ||\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(rootElement),\n 'innerHTML'\n ) ||\n Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');\n\n if (descriptor && (descriptor.get || descriptor.set)) {\n Object.defineProperty(rootElement, 'innerHTML', {\n get: descriptor.get\n ? function (this: Element) {\n return descriptor.get!.call(this);\n }\n : undefined,\n set: function (this: Element, value: string) {\n if (value === '' && instancesByRoot.get(this) === instance) {\n removeAllListeners(rootElement);\n cleanupComponent(instance as ComponentInstance);\n }\n if (descriptor.set) {\n return descriptor.set.call(this, value);\n }\n },\n configurable: true,\n });\n }\n } catch {\n // If Object.defineProperty fails, ignore\n }\n}\n\nfunction mountOrUpdate(rootElement: Element, componentFn: ComponentFunction) {\n // Clean up existing cleanup function before mounting new one\n const existingCleanup = (rootElement as ElementWithCleanup)[CLEANUP_SYMBOL];\n if (existingCleanup) existingCleanup();\n\n let instance = instancesByRoot.get(rootElement);\n\n if (instance) {\n removeAllListeners(rootElement);\n cleanupComponent(instance);\n\n instance.fn = componentFn;\n instance.evaluationGeneration++;\n instance.mounted = false;\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.isRoot = true;\n } else {\n const componentId = String(++componentIdCounter);\n instance = createComponentInstance(\n componentId,\n componentFn,\n {},\n rootElement\n );\n instancesByRoot.set(rootElement, instance);\n instance.isRoot = true;\n }\n\n attachCleanupForRoot(rootElement, instance);\n mountComponent(instance);\n globalScheduler.flush();\n}\n\n// New strongly-typed init functions\nimport type { Route } from '../router/route';\n\nexport type IslandConfig = {\n root: Element | string;\n component: ComponentFunction;\n // Explicitly disallow routes on islands at type level\n routes?: never;\n};\n\nexport type SPAConfig = {\n root: Element | string;\n routes: Route[]; // routes are required\n component?: never;\n};\n\nexport type HydrateSPAConfig = {\n root: Element | string;\n routes: Route[];\n};\n\n/**\n * createIsland: Enhances existing DOM (no router, mounts once)\n */\nexport function createIsland(config: IslandConfig): void {\n if (!config || typeof config !== 'object') {\n throw new Error('createIsland requires a config object');\n }\n if (typeof config.component !== 'function') {\n throw new Error('createIsland: component must be a function');\n }\n\n const rootElement =\n typeof config.root === 'string'\n ? document.getElementById(config.root)\n : config.root;\n if (!rootElement) throw new Error(`Root element not found: ${config.root}`);\n\n // Islands must not initialize router or routes\n if ('routes' in config) {\n throw new Error(\n 'createIsland does not accept routes; use createSPA for routed apps'\n );\n }\n\n mountOrUpdate(rootElement, config.component);\n}\n\n/**\n * createSPA: Initializes router and mounts the app with provided route table\n */\nexport async function createSPA(config: SPAConfig): Promise<void> {\n if (!config || typeof config !== 'object') {\n throw new Error('createSPA requires a config object');\n }\n if (!Array.isArray(config.routes) || config.routes.length === 0) {\n throw new Error(\n 'createSPA requires a route table. If you are enhancing existing HTML, use createIsland instead.'\n );\n }\n\n const rootElement =\n typeof config.root === 'string'\n ? document.getElementById(config.root)\n : config.root;\n if (!rootElement) throw new Error(`Root element not found: ${config.root}`);\n\n // Register routes at startup (clear previous registrations to avoid surprises)\n const { clearRoutes, route, lockRouteRegistration, resolveRoute } =\n await import('../router/route');\n\n clearRoutes();\n for (const r of config.routes) {\n // Using typed Route from router; allow handler functions\n route(r.path, r.handler, r.namespace);\n }\n // Lock registration in production to prevent late registration surprises\n if (process.env.NODE_ENV === 'production') lockRouteRegistration();\n\n // Mount the currently-resolved route handler (if any)\n const path = typeof window !== 'undefined' ? window.location.pathname : '/';\n const resolved = resolveRoute(path);\n if (!resolved) {\n // If no route currently matches, mount an empty placeholder and continue.\n // This supports cases where routes are registered but the current URL is\n // not one of them (common in router tests that navigate programmatically).\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(\n `createSPA: no route found for current path (${path}). Mounting empty placeholder; navigation will activate routes when requested.`\n );\n }\n\n // Mount a no-op component until navigation occurs\n mountOrUpdate(rootElement, () => ({ type: 'div', children: [] }));\n\n // Still register app instance and initialize navigation so future navigations work\n const instance = instancesByRoot.get(rootElement);\n if (!instance) throw new Error('Internal error: app instance missing');\n registerAppInstance(instance as ComponentInstance, path);\n initializeNavigation();\n return;\n }\n\n // Mount resolved handler as the root component\n // Convert resolved.handler to a ComponentFunction-compatible shape\n mountOrUpdate(rootElement, resolved.handler as ComponentFunction);\n\n // Register for navigation and wire up history handling\n const instance = instancesByRoot.get(rootElement);\n if (!instance) throw new Error('Internal error: app instance missing');\n registerAppInstance(instance as ComponentInstance, path);\n initializeNavigation();\n}\n\n/**\n * hydrateSPA: Hydrate server-rendered HTML with explicit routes\n */\nexport async function hydrateSPA(config: HydrateSPAConfig): Promise<void> {\n if (!config || typeof config !== 'object') {\n throw new Error('hydrateSPA requires a config object');\n }\n if (!Array.isArray(config.routes) || config.routes.length === 0) {\n throw new Error(\n 'hydrateSPA requires a route table. If you are enhancing existing HTML, use createIsland instead.'\n );\n }\n\n const rootElement =\n typeof config.root === 'string'\n ? document.getElementById(config.root)\n : config.root;\n if (!rootElement) throw new Error(`Root element not found: ${config.root}`);\n\n // Capture server HTML for mismatch detection\n const serverHTML = rootElement.innerHTML;\n\n // Register routes for hydration and set server location for deterministic route()\n const {\n clearRoutes,\n route,\n setServerLocation,\n lockRouteRegistration,\n resolveRoute,\n } = await import('../router/route');\n\n clearRoutes();\n for (const r of config.routes) {\n route(r.path, r.handler, r.namespace);\n }\n // Set server location so route() reflects server URL during SSR checks\n const path = typeof window !== 'undefined' ? window.location.pathname : '/';\n setServerLocation(path);\n if (process.env.NODE_ENV === 'production') lockRouteRegistration();\n\n // Resolve handler for current path\n const resolved = resolveRoute(path);\n if (!resolved) {\n throw new Error(`hydrateSPA: no route found for current path (${path}).`);\n }\n\n // Synchronously render expected HTML using SSR helper\n const { renderToStringSync } = await import('../ssr');\n // renderToStringSync takes a zero-arg component factory; wrap the handler to pass params\n const expectedHTML = renderToStringSync(() => {\n const out = resolved.handler(resolved.params);\n return (out ?? {\n type: 'div',\n children: [],\n }) as ReturnType<ComponentFunction>;\n });\n\n // Prefer a DOM-based comparison to avoid false positives from attribute order\n // or whitespace differences between server and expected HTML.\n const serverContainer = document.createElement('div');\n serverContainer.innerHTML = serverHTML;\n const expectedContainer = document.createElement('div');\n expectedContainer.innerHTML = expectedHTML;\n\n if (!serverContainer.isEqualNode(expectedContainer)) {\n throw new Error(\n '[Askr] Hydration mismatch detected. Server HTML does not match expected server-render output.'\n );\n }\n\n // Proceed to mount the client SPA (this will attach listeners and start navigation)\n // Reuse createSPA path but we already registered routes and set server location, so just mount\n // Mount resolved handler\n mountOrUpdate(rootElement, resolved.handler as ComponentFunction);\n\n // Register navigation and instance\n const { registerAppInstance, initializeNavigation } =\n await import('../router/navigate');\n const instance = instancesByRoot.get(rootElement);\n if (!instance) throw new Error('Internal error: app instance missing');\n registerAppInstance(instance as ComponentInstance, path);\n initializeNavigation();\n}\n\nexport async function hydrate(_config: AppConfig): Promise<void> {\n throw new Error(\n 'The legacy `hydrate` API is removed. Use `hydrateSPA({ root, routes })` for SSR hydration with an explicit route table.'\n );\n}\n\n/**\n * Cleanup an app mounted on a root element (element or id).\n * Safe to call multiple times — no-op when nothing is mounted.\n */\nexport function cleanupApp(root: Element | string): void {\n const rootElement =\n typeof root === 'string' ? document.getElementById(root) : root;\n\n if (!rootElement) return;\n\n const cleanupFn = (rootElement as ElementWithCleanup)[CLEANUP_SYMBOL];\n if (typeof cleanupFn === 'function') {\n cleanupFn();\n }\n\n instancesByRoot.delete(rootElement);\n}\n\n/**\n * Check whether an app is mounted on the given root\n */\nexport function hasApp(root: Element | string): boolean {\n const rootElement =\n typeof root === 'string' ? document.getElementById(root) : root;\n\n if (!rootElement) return false;\n return instancesByRoot.has(rootElement);\n}\n","/**\n * Small layout helper (centralized)\n * Usage: const parent = layout(ParentLayout); route('/parent', () => parent(<Child />));\n *\n * A layout is simply a component that receives `children`.\n * This helper intentionally avoids vnode inspection, heuristics, or double-invocation.\n * Prefer boring, explicit code over cleverness.\n *\n * Example:\n * const Parent = ({ children }: { children?: unknown }) => <div class=\"parent\">{children}</div>;\n * const parent = layout(Parent);\n * route('/parent', () => parent(<div class=\"child\">C</div>));\n */\nexport type Component<P = object> = (\n props: P & { children?: unknown }\n) => unknown;\n\nexport function layout<P>(Layout: Component<P>) {\n return (children?: unknown) =>\n Layout({ children } as P & { children?: unknown });\n}\n","/**\n * Link component for client-side navigation\n */\n\nimport { navigate } from '../router/navigate';\nimport type { JSXElement } from '../jsx/types';\n\nexport interface LinkProps {\n href: string;\n children?: unknown;\n}\n\n/**\n * Link component that prevents default navigation and uses navigate()\n * Provides declarative way to navigate between routes\n *\n * Respects:\n * - Middle-click (opens in new tab)\n * - Ctrl/Cmd+click (opens in new tab)\n * - Shift+click (opens in new window)\n * - Right-click context menu\n */\nexport function Link({ href, children }: LinkProps): JSXElement {\n return {\n type: 'a',\n props: {\n href,\n children,\n onClick: (e: Event) => {\n const event = e as MouseEvent;\n\n // Only handle left-click without modifiers\n // Default button to 0 if undefined (for mock events in tests)\n const button = event.button ?? 0;\n if (\n button !== 0 || // not left-click\n event.ctrlKey || // Ctrl/Cmd+click\n event.metaKey || // Cmd on Mac\n event.shiftKey || // Shift+click\n event.altKey // Alt+click\n ) {\n return; // Let browser handle it (new tab, etc.)\n }\n\n event.preventDefault();\n navigate(href);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,UACd,WACA,SACA,SACmB;AACnB,MAAI,CAAC,WA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A;AAQA,IAAI,OAAO,eAAe,aAAa;AACrC,QAAM,IAAI;AACV,MAAI,CAAC,EAAE,UAAW,GAAE,YAAY;AAChC,MAAI,CAAC,EAAE,aAAc,GAAE,eAAe;AACtC,MAAI,CAAC,EAAE,UAAW,GAAE,YAAY;AAChC,MAAI,CAAC,EAAE,WAAY,GAAE,aAAa;AAClC,MAAI,CAAC,EAAE,MAAO,GAAE,QAAQ;AACxB,MAAI,CAAC,EAAE,UAAW,GAAE,YAAY;AAChC,MAAI,CAAC,EAAE,SAAU,GAAE,WAAW;AAChC;","names":["state","isBulkCommitActive","evaluate","_g","current","current","k","isBulkCommitActive","parentChildren","totalKeyed","prev","dom","state","isBulkCommitActive","state","init_context","getSpecificity","currentInstance","executeComponent","init_context","escapeText","escapeCache","escapeAttr","renderAttrs","executeComponentSync","VOID_ELEMENTS","attrs","routes","clearRoutes","route","setServerLocation","lockRouteRegistration","resolveRoute","init_context","isBulkCommitActive","init_context","init_context","renderData","holder","h","cell","clearRoutes","route","lockRouteRegistration","resolveRoute","instance","setServerLocation","renderToStringSync","registerAppInstance","initializeNavigation"]}
|