@askrjs/askr 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-MIPES65F.js → chunk-2ONGHQ7Z.js} +1575 -1483
- package/dist/chunk-2ONGHQ7Z.js.map +1 -0
- package/dist/{chunk-RJWOOUYV.js → chunk-H3NSVHA7.js} +2 -6
- package/dist/{chunk-RJWOOUYV.js.map → chunk-H3NSVHA7.js.map} +1 -1
- package/dist/chunk-JHOGWTAW.js +16 -0
- package/dist/{chunk-QECQ2TF6.js.map → chunk-JHOGWTAW.js.map} +1 -1
- package/dist/{chunk-PFOLLB6A.js → chunk-OFW6DFBM.js} +330 -138
- package/dist/chunk-OFW6DFBM.js.map +1 -0
- package/dist/chunk-SALJX5PZ.js +26 -0
- package/dist/{chunk-KR6HG7HF.js.map → chunk-SALJX5PZ.js.map} +1 -1
- package/dist/index.cjs +1869 -1199
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -8
- package/dist/index.d.ts +51 -8
- package/dist/index.js +251 -79
- package/dist/index.js.map +1 -1
- package/dist/jsx/jsx-dev-runtime.js +2 -5
- package/dist/jsx/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx/jsx-runtime.js +2 -4
- package/dist/{navigate-SDZNA2ZE.js → navigate-CZEUXFPM.js} +5 -5
- package/dist/{route-P5YQBT4T.js → route-USEXGOBT.js} +4 -4
- package/dist/{ssr-65K3IJ6B.js → ssr-QJ5NTQR6.js} +5 -5
- package/package.json +4 -3
- package/dist/chunk-KR6HG7HF.js +0 -38
- package/dist/chunk-MIPES65F.js.map +0 -1
- package/dist/chunk-PFOLLB6A.js.map +0 -1
- package/dist/chunk-QECQ2TF6.js +0 -28
- /package/dist/{navigate-SDZNA2ZE.js.map → navigate-CZEUXFPM.js.map} +0 -0
- /package/dist/{route-P5YQBT4T.js.map → route-USEXGOBT.js.map} +0 -0
- /package/dist/{ssr-65K3IJ6B.js.map → ssr-QJ5NTQR6.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dev/invariant.ts","../src/dev/logger.ts","../src/runtime/scheduler.ts","../src/runtime/context.ts","../src/renderer/diag/index.ts","../src/runtime/fastlane-shared.ts","../src/renderer/types.ts","../src/renderer/cleanup.ts","../src/renderer/keyed.ts","../src/jsx/types.ts","../src/jsx/jsx-runtime.ts","../src/renderer/dom.ts","../src/renderer/fastpath.ts","../src/renderer/reconcile.ts","../src/renderer/evaluate.ts","../src/renderer/index.ts","../src/runtime/component.ts","../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/shared/derive_cache.ts","../src/boot/index.ts","../src/components/Link.tsx","../src/foundations/layout.ts","../src/foundations/slot.ts","../src/jsx/index.ts","../src/jsx/utils.ts","../src/foundations/portal.ts"],"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 {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private q: Task[] = [];\n private head = 0;\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n enqueue(task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.q.push(task);\n this.taskCount++;\n\n // Microtask kick: best-effort, but avoid if we are in handler or running or bulk commit\n if (\n !this.running &&\n !this.kickScheduled &&\n !this.inHandler &&\n !isBulkCommitActive()\n ) {\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running) return;\n if (isBulkCommitActive()) return;\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n\n try {\n while (this.head < this.q.length) {\n this.depth++;\n if (\n process.env.NODE_ENV !== 'production' &&\n this.depth > MAX_FLUSH_DEPTH\n ) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = this.q[this.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n } catch (err) {\n // ensure executionDepth stays balanced\n if (this.executionDepth > 0) this.executionDepth = 0;\n fatal = err;\n break;\n }\n\n // Account for executed task in taskCount\n if (this.taskCount > 0) this.taskCount--;\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n // Compact queue\n if (this.head >= this.q.length) {\n this.q.length = 0;\n this.head = 0;\n } else if (this.head > 0) {\n const remaining = this.q.length - this.head;\n if (this.head > 1024 || this.head > remaining) {\n this.q = this.q.slice(this.head);\n } else {\n for (let i = 0; i < remaining; i++) {\n this.q[i] = this.q[this.head + i];\n }\n this.q.length = remaining;\n }\n this.head = 0;\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n const g = globalThis as {\n queueMicrotask?: (...args: unknown[]) => void;\n setTimeout?: (...args: unknown[]) => unknown;\n };\n const origQueueMicrotask = g.queueMicrotask;\n const origSetTimeout = g.setTimeout;\n\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = () => {\n throw new Error(\n '[Scheduler] queueMicrotask not allowed during runWithSyncProgress'\n );\n };\n g.setTimeout = () => {\n throw new Error(\n '[Scheduler] setTimeout not allowed during runWithSyncProgress'\n );\n };\n }\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.q.length - this.head > 0) {\n this.flush();\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (this.q.length - this.head > 0) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // Restore guarded globals\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = origQueueMicrotask;\n g.setTimeout = origSetTimeout;\n }\n\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const ns =\n (\n globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n }\n ).__ASKR__ || {};\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.q.length - this.head,\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n namespace: ns,\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.q.length - this.head,\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.q.length - this.head;\n if (remaining <= 0) return 0;\n\n if (this.running) {\n this.q.length = this.head;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n this.q.length = 0;\n this.head = 0;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler.call(null, event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them now that the handler\n // has completed. This avoids tests timing out waiting for flush.\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n}\n","/**\n * Context system: lexical scope + render-time snapshots\n *\n * CORE SEMANTIC (Option A — Snapshot-Based):\n * ============================================\n * An async resource observes the context of the render that created it.\n * Context changes only take effect via re-render, not magically mid-await.\n *\n * This ensures:\n * - Deterministic behavior\n * - Concurrency safety\n * - Replayable execution\n * - Debuggability\n *\n * INVARIANTS:\n * - readContext() only works during component render (has currentContextFrame)\n * - Each render captures a context snapshot\n * - Async continuations see the snapshot from render start (frozen)\n * - Provider (Scope) creates a new frame that shadows parent\n * - Context updates require re-render to take effect\n */\n\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: unknown; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\n// Global context frame stack (maintained during render)\n// INVARIANT: Must NEVER be non-null across an await boundary\nlet currentContextFrame: ContextFrame | null = null;\n\n// Async resource frame (maintained during async resource execution)\n// INVARIANT: Set only for synchronous execution steps, cleared in finally\n// This allows async resources to access their frozen render-time snapshot\nlet currentAsyncResourceFrame: ContextFrame | null = null;\n\n/**\n * Execute a function within a specific context frame.\n *\n * CORE PRIMITIVE for context restoration:\n * - Saves the current context\n * - Sets the provided frame as current\n * - Executes the function\n * - Restores the previous context in finally\n *\n * This ensures no context frame remains globally active across await.\n */\nexport function withContext<T>(frame: ContextFrame | null, fn: () => T): T {\n const oldFrame = currentContextFrame;\n currentContextFrame = frame;\n try {\n return fn();\n } finally {\n currentContextFrame = oldFrame;\n }\n}\n\n/**\n * Execute an async resource step within its frozen context snapshot.\n *\n * CRITICAL: This wrapper is applied only to synchronous execution steps of\n * an async resource (the initial call). We intentionally DO NOT restore\n * the resource frame for post-await continuations — continuations must not\n * observe or rely on a live resource frame. This keeps semantics simple and\n * deterministic: async resources see only their creation-time snapshot.\n */\nexport function withAsyncResourceContext<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n const oldFrame = currentAsyncResourceFrame;\n // Only set the frame for the synchronous execution step\n currentAsyncResourceFrame = frame;\n try {\n return fn();\n } finally {\n // Clear the frame to avoid exposing it across await boundaries\n currentAsyncResourceFrame = oldFrame;\n }\n}\n\nexport function defineContext<T>(defaultValue: T): Context<T> {\n const key = Symbol('AskrContext');\n\n return {\n key,\n defaultValue,\n Scope: (props: { value: unknown; children?: unknown }): JSXElement => {\n // Scope component: accepts an unknown value (tests often pass loosely typed values)\n // Cast to the expected T at the call site to preserve runtime behavior.\n const value = props.value as T;\n // Scope component: creates a new frame and renders children within it\n return {\n type: ContextScopeComponent,\n props: { key, value, children: props.children },\n } as JSXElement;\n },\n };\n}\n\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // Helper: create a function-child invoker node (centralized cast)\n function createFunctionChildInvoker(\n fn: () => Renderable,\n frame: ContextFrame,\n owner: ComponentInstance | null\n ): Renderable {\n return {\n type: ContextFunctionChildInvoker,\n props: { fn, __frame: frame, __owner: owner },\n } as unknown as Renderable;\n }\n\n // The renderer will set ownerFrame on child component instances when they're created.\n // We mark vnodes with the frame so the renderer knows which frame to assign.\n if (Array.isArray(children)) {\n // Mark array elements with the frame. If an element is a function-child,\n // convert it into a lazy invoker so it's executed later inside the frame.\n return children.map((child) => {\n if (typeof child === 'function') {\n return createFunctionChildInvoker(\n child as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n }\n return markWithFrame(child, newFrame);\n }) as unknown as Renderable;\n } else if (typeof children === 'function') {\n // If children is a function (render callback), do NOT execute it eagerly\n // during the parent render. Instead, return a small internal component\n // that will execute the function later (when it itself is rendered) and\n // will execute it within the provider frame so any reads performed during\n // that execution observe the provider's frame.\n return createFunctionChildInvoker(\n children as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n } else if (children) {\n return markWithFrame(children, newFrame);\n }\n\n return null;\n}\n\n/**\n * Internal: Mark a vnode with a context frame\n * The renderer will restore this frame before executing component functions\n */\nfunction markWithFrame(node: Renderable, frame: ContextFrame): Renderable {\n // Recursively mark node and its subtree so nested provider/component\n // executions will restore the correct frame when they are rendered.\n if (typeof node === 'object' && node !== null) {\n const obj = node as Record<string | symbol, unknown>;\n obj[CONTEXT_FRAME_SYMBOL] = frame;\n\n // If the node is a VNode with children, recursively mark its children\n const children = obj.children as unknown;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const child = children[i] as Renderable;\n if (child) {\n children[i] = markWithFrame(child, frame) as Renderable;\n }\n }\n } else if (children) {\n obj.children = markWithFrame(children as Renderable, frame) as Renderable;\n }\n }\n return node;\n}\n\n/**\n * Internal helper component: executes a function-child lazily inside the\n * provided frame and marks the returned subtree with that frame so later\n * component executions will restore the correct context frame.\n *\n * SNAPSHOT SEMANTIC: The frame passed here is the snapshot captured at render\n * time. Any resources created during this execution will observe this frozen\n * snapshot, ensuring deterministic behavior.\n */\nfunction ContextFunctionChildInvoker(props: {\n fn: () => Renderable;\n __frame: ContextFrame;\n __owner?: ComponentInstance | null;\n}): Renderable {\n const { fn, __frame } = props;\n\n // Execute the function-child within the provider frame.\n // The owner's ownerFrame is already set by the renderer when the component was created.\n // Any resources started during this execution will capture this frame as their\n // snapshot, ensuring they see the context values from this render, not future renders.\n const res = withContext(__frame, () => fn());\n\n // Mark the result so the renderer knows to set ownerFrame on child instances\n if (res) return markWithFrame(res, __frame);\n return null;\n}\n\n/**\n * Push a new context frame (for render entry)\n * Called by component runtime when render starts\n */\nexport function pushContextFrame(): ContextFrame {\n // Lazily allocate the `values` map to avoid per-render allocations when\n // components do not use context. The map will be created when a provider\n // sets a value or when a read discovers no map and needs to behave as empty.\n const frame: ContextFrame = {\n parent: currentContextFrame,\n values: null,\n };\n currentContextFrame = frame;\n return frame;\n}\n\n/**\n * Pop context frame (for render exit)\n * Called by component runtime when render ends\n */\nexport function popContextFrame(): void {\n if (currentContextFrame) {\n currentContextFrame = currentContextFrame.parent;\n }\n}\n\n/**\n * Get the current context frame for inspection (used by tests/diagnostics only)\n */\nexport function getCurrentContextFrame(): ContextFrame | null {\n return currentContextFrame;\n}\n\n/**\n * Get the top of the context snapshot stack (used by runtime when deciding\n * how to link snapshots for async continuations). Returns null if stack empty.\n */\nexport function getTopContextSnapshot(): ContextFrame | null {\n return currentContextFrame;\n}\n\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","type DiagMap = Record<string, unknown>;\n\nfunction getDiagMap(): DiagMap {\n try {\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR_DIAG?: DiagMap;\n };\n if (!root.__ASKR_DIAG) root.__ASKR_DIAG = {} as DiagMap;\n return root.__ASKR_DIAG!;\n } catch (e) {\n void e;\n return {} as DiagMap;\n }\n}\n\nexport function __ASKR_set(key: string, value: unknown): void {\n try {\n const g = getDiagMap();\n (g as DiagMap)[key] = value;\n try {\n // Consolidate diagnostics under a single namespace to avoid\n // polluting the top-level global scope. Expose a namespaced view on\n // `globalThis.__ASKR__` so tools and tests can inspect diagnostic keys.\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n try {\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n ns[key] = value;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n\nexport function __ASKR_incCounter(key: string): void {\n try {\n const g = getDiagMap();\n const prev = typeof g[key] === 'number' ? (g[key] as number) : 0;\n const next = prev + 1;\n (g as DiagMap)[key] = next;\n try {\n // Mirror counter into namespaced diagnostics\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n const nsPrev = typeof ns[key] === 'number' ? (ns[key] as number) : 0;\n ns[key] = nsPrev + 1;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n","import { globalScheduler } from './scheduler';\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 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","import type { Props } from '../shared/types';\n\nexport interface DOMElement {\n type: string | ((props: Props) => unknown);\n props?: Props;\n children?: VNode[];\n key?: string | number;\n [Symbol.iterator]?: never;\n}\n\n// Type for virtual DOM nodes\nexport type VNode = DOMElement | string | number | boolean | null | undefined;\n\nexport function _isDOMElement(node: unknown): node is DOMElement {\n return typeof node === 'object' && node !== null && 'type' in node;\n}\n","import { cleanupComponent } from '../runtime/component';\nimport type { ComponentInstance } from '../runtime/component';\nimport { logger } from '../dev/logger';\n\ntype InstanceHost = Element & { __ASKR_INSTANCE?: unknown };\n\n// Helpers to clean up component instances when their host DOM nodes are removed\n// Accepts an optional `opts.strict` flag to surface errors instead of swallowing them.\nexport function cleanupInstanceIfPresent(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n if (!node) return;\n if (!(node instanceof Element)) return;\n\n const errors: unknown[] = [];\n\n try {\n const inst = (node as InstanceHost).__ASKR_INSTANCE;\n if (inst) {\n try {\n cleanupComponent(inst as unknown as ComponentInstance);\n } catch (err) {\n if (opts?.strict) errors.push(err);\n else if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] cleanupComponent failed:', err);\n }\n try {\n delete (node as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n if (opts?.strict) errors.push(e);\n else void e;\n }\n }\n } catch (err) {\n if (opts?.strict) errors.push(err);\n else if (process.env.NODE_ENV !== 'production') {\n logger.warn('[Askr] cleanupInstanceIfPresent failed:', err);\n }\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 try {\n cleanupComponent(inst as unknown as ComponentInstance);\n } catch (err) {\n if (opts?.strict) errors.push(err);\n else if (process.env.NODE_ENV !== 'production') {\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant cleanup failed:',\n err\n );\n }\n }\n try {\n delete (d as InstanceHost).__ASKR_INSTANCE;\n } catch (e) {\n if (opts?.strict) errors.push(e);\n else void e;\n }\n }\n } catch (err) {\n if (opts?.strict) errors.push(err);\n else if (process.env.NODE_ENV !== 'production') {\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant cleanup failed:',\n err\n );\n }\n }\n }\n } catch (err) {\n if (opts?.strict) errors.push(err);\n else if (process.env.NODE_ENV !== 'production') {\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant query failed:',\n err\n );\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'cleanupInstanceIfPresent failed');\n }\n}\n\n// Public helper to clean up any component instances under a node. Used by\n// runtime commit logic to ensure component instances are torn down when their\n// host nodes are removed during an update.\nexport function cleanupInstancesUnder(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n cleanupInstanceIfPresent(node, opts);\n}\n\n// Track listeners so we can remove them on cleanup\nexport interface ListenerMapEntry {\n handler: EventListener;\n original: EventListener;\n options?: boolean | AddEventListenerOptions;\n}\nexport const elementListeners = new WeakMap<\n Element,\n Map<string, ListenerMapEntry>\n>();\n\nexport function removeElementListeners(element: Element): void {\n const map = elementListeners.get(element);\n if (map) {\n for (const [eventName, entry] of map) {\n // When removing, reuse the original options if present for correctness\n if (entry.options !== undefined)\n element.removeEventListener(eventName, entry.handler, entry.options);\n else element.removeEventListener(eventName, entry.handler);\n }\n elementListeners.delete(element);\n }\n}\n\nexport function removeAllListeners(root: Element | null): void {\n if (!root) return;\n\n // Remove listeners from root\n removeElementListeners(root);\n\n // Recursively remove from all children\n const children = root.querySelectorAll('*');\n for (let i = 0; i < children.length; i++) {\n removeElementListeners(children[i]);\n }\n}\n","import type { VNode } from './types';\n\ninterface _KeyedChild {\n key: string | number;\n vnode: unknown;\n}\n\nexport const keyedElements = new WeakMap<\n Element,\n Map<string | number, Element>\n>();\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// Populate a keyed map for an element by scanning its immediate children for\n// `data-key` attributes. This can be called proactively by runtime layers\n// that want to ensure keyed maps are available before reconciliation.\nexport function populateKeyMapForElement(parent: Element): void {\n try {\n if (keyedElements.has(parent)) return;\n const domMap = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n for (let i = 0; i < children.length; i++) {\n const ch = children[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n domMap.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) domMap.set(n, ch);\n }\n }\n if (domMap.size === 0) {\n // Fallback: map by textContent when keys are not materialized as attrs\n for (let i = 0; i < children.length; i++) {\n const ch = children[i] as Element;\n const text = (ch.textContent || '').trim();\n if (text) {\n domMap.set(text, ch);\n const n = Number(text);\n if (!Number.isNaN(n)) domMap.set(n, ch);\n }\n }\n }\n if (domMap.size > 0) keyedElements.set(parent, domMap);\n } catch (e) {\n void e;\n }\n}\n\n// Track which parents had the reconciler record fast-path stats during the\n// current evaluation, so we can preserve diagnostics across additional\n// reconciliations within the same render pass without leaking between runs.\nexport const _reconcilerRecordedParents = new WeakSet<Element>();\n\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 (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as unknown as Record<string, unknown>;\n if (childObj.key !== undefined) {\n keyedVnodes.push({\n key: childObj.key as string | number,\n vnode: child,\n });\n }\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 (typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n const props = vnodeObj.props || {};\n for (const k of Object.keys(props)) {\n if (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 || typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n const props = vnodeObj.props || {};\n for (const k of Object.keys(props)) {\n if (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 (e) {\n hasPropChanges = true;\n void e;\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","/**\n * JSX type definitions\n *\n * These define the canonical JSX element shape used by:\n * - jsx-runtime\n * - jsx-dev-runtime\n * - Slot / cloneElement\n * - the reconciler\n */\n\nimport type { Props } from '../shared/types';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n /** Internal element marker (optional for plain vnode objects) */\n $$typeof?: symbol;\n\n /** Element type: string, component, Fragment, etc */\n type: unknown;\n\n /** Props bag */\n props: Props;\n\n /** Optional key (normalized by runtime) */\n key?: string | number | null;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n // Components must be synchronous\n type Element = JSXElement;\n\n interface IntrinsicElements {\n [elem: string]: Props;\n }\n\n interface ElementAttributesProperty {\n props: Props;\n }\n }\n}\n\nexport {};\n","/**\n * JSX dev runtime\n * Same shape as production runtime, with room for dev warnings.\n */\n\nimport './types';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n $$typeof: symbol;\n type: unknown;\n props: Record<string, unknown>;\n key: string | number | null;\n}\n\nexport function jsxDEV(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n): JSXElement {\n return {\n $$typeof: ELEMENT_TYPE,\n type,\n props: props ?? {},\n key: key ?? null,\n };\n}\n\n// Production-style helpers: alias to the DEV factory for now\nexport function jsx(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n) {\n return jsxDEV(type, props, key);\n}\n\nexport function jsxs(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n) {\n return jsxDEV(type, props, key);\n}\n\n// `Fragment` is already exported above.\n","import { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { Fragment } from '../jsx/jsx-runtime';\nimport {\n CONTEXT_FRAME_SYMBOL,\n withContext,\n getCurrentContextFrame,\n ContextFrame,\n} from '../runtime/context';\nimport {\n createComponentInstance,\n renderComponentInline,\n mountInstanceInline,\n getCurrentInstance,\n} from '../runtime/component';\nimport type {\n ComponentInstance,\n ComponentFunction,\n} from '../runtime/component';\nimport {\n cleanupInstanceIfPresent,\n elementListeners,\n removeAllListeners,\n} from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport { keyedElements } from './keyed';\n\ntype ElementWithContext = DOMElement & {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n __instance?: ComponentInstance;\n};\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Create a DOM node from a VNode\nexport function createDOMNode(node: unknown): Node | null {\n // SSR guard: don't attempt DOM ops when document is unavailable\n if (!IS_DOM_AVAILABLE) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[Askr] createDOMNode called in non-DOM environment');\n } catch (e) {\n void e;\n }\n }\n return null;\n }\n\n // Fast paths for primitives (most common)\n if (typeof node === 'string') {\n return document.createTextNode(node);\n }\n if (typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n\n // Null/undefined/false\n if (!node) {\n return null;\n }\n\n // Array (fragment) - batch all at once\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (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 queueMicrotask(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n\n // Determine sensible default options (use passive for touch/scroll/wheel where appropriate)\n const options: boolean | AddEventListenerOptions | undefined =\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ? { passive: true }\n : undefined;\n if (options !== undefined)\n el.addEventListener(eventName, wrappedHandler, options);\n else 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 options,\n });\n } else if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n // Only set `value`/`checked` on form controls where it's meaningful\n const tag = type.toLowerCase();\n if (key === 'value') {\n if (tag === 'input' || tag === 'textarea' || tag === 'select') {\n (el as HTMLInputElement & Props).value = String(value);\n el.setAttribute('value', String(value));\n } else {\n el.setAttribute('value', String(value));\n }\n } else {\n if (tag === 'input') {\n (el as HTMLInputElement & Props).checked = Boolean(value);\n el.setAttribute('checked', String(Boolean(value)));\n } else {\n el.setAttribute('checked', String(Boolean(value)));\n }\n }\n } 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 =\n (node as DOMElement).key ?? (props as Record<string, unknown>)?.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 try {\n const inst = getCurrentInstance();\n const name = inst?.fn?.name || '<anonymous>';\n logger.warn(\n `Missing keys on dynamic lists in ${name}. Each child in a list should have a unique \"key\" prop.`\n );\n } catch (e) {\n logger.warn(\n 'Missing keys on dynamic lists. Each child in a list should have a unique \"key\" prop.'\n );\n void e;\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 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 let childInstance = vnodeAny.__instance;\n if (!childInstance) {\n childInstance = createComponentInstance(\n `comp-${Math.random().toString(36).slice(2, 7)}`,\n componentFn as ComponentFunction,\n props || {},\n null\n );\n vnodeAny.__instance = childInstance;\n }\n\n if (snapshot) {\n childInstance.ownerFrame = snapshot;\n }\n\n const result = withContext(snapshot, () =>\n renderComponentInline(childInstance)\n );\n\n if (result instanceof Promise) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n const dom = withContext(snapshot, () => createDOMNode(result));\n\n if (dom instanceof Element) {\n mountInstanceInline(childInstance, dom);\n return dom;\n }\n\n // For non-Element returns (Text nodes or DocumentFragment), ensure the\n // instance backref is attached to an Element that will actually be\n // inserted into the DOM. Append returned nodes into a host element and\n // mount the instance on that host so cleanup works deterministically.\n const host = document.createElement('div');\n if (dom instanceof DocumentFragment) {\n host.appendChild(dom);\n } else if (dom) {\n host.appendChild(dom);\n }\n mountInstanceInline(childInstance, host);\n return host;\n }\n\n // Fragment support\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/**\n * Update an existing element's attributes and children from vnode\n */\nexport function updateElementFromVnode(\n el: Element,\n vnode: VNode,\n updateChildren = true\n): void {\n if (!_isDOMElement(vnode)) {\n return;\n }\n\n const props = vnode.props || {};\n\n // Ensure key is materialized on existing elements so DOM-based scans succeed\n // Respect both top-level `key` and `props.key` for compatibility with\n // tests and manual vnode construction.\n const vnodeKey =\n (vnode as DOMElement).key ?? (vnode as DOMElement).props?.key;\n if (vnodeKey !== undefined) {\n el.setAttribute('data-key', String(vnodeKey));\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 if (entry.options !== undefined)\n el.removeEventListener(eventName, entry.handler, entry.options);\n else 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 const options: boolean | AddEventListenerOptions | undefined =\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ? { passive: true }\n : undefined;\n if (options !== undefined)\n el.addEventListener(eventName, wrappedHandler, options);\n else 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 options,\n });\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Remove any remaining listeners not desired by current props\n if (existingListeners) {\n // 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\nexport function updateElementChildren(\n el: Element,\n children: VNode | VNode[] | undefined\n): void {\n if (!children) {\n el.textContent = '';\n return;\n }\n\n if (\n !Array.isArray(children) &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n return;\n }\n\n if (Array.isArray(children)) {\n updateUnkeyedChildren(el, children as unknown[]);\n return;\n }\n\n el.textContent = '';\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n}\n\nexport function updateUnkeyedChildren(\n parent: Element,\n newChildren: unknown[]\n): void {\n const existing = Array.from(parent.children);\n // If there are only text nodes (no element children), clear before updating\n if (existing.length === 0 && parent.childNodes.length > 0) {\n parent.textContent = '';\n }\n const max = Math.max(existing.length, newChildren.length);\n\n for (let i = 0; i < max; i++) {\n const current = existing[i];\n const next = newChildren[i];\n\n // Remove extra existing children\n if (next === undefined && current) {\n // Clean up any component instance mounted on this node\n cleanupInstanceIfPresent(current);\n current.remove();\n continue;\n }\n\n // Append new children beyond existing length\n if (!current && next !== undefined) {\n const dom = createDOMNode(next);\n if (dom) parent.appendChild(dom);\n continue;\n }\n\n if (!current || next === undefined) continue;\n\n // Update existing element based on next vnode/primitive\n if (typeof next === 'string' || typeof next === 'number') {\n current.textContent = String(next);\n } else if (_isDOMElement(next)) {\n if (typeof next.type === 'string') {\n // If element type matches, update in place; otherwise replace\n if (current.tagName.toLowerCase() === next.type.toLowerCase()) {\n updateElementFromVnode(current, next);\n } else {\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Non-string types: replace conservatively\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Fallback for other types: replace\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n }\n}\n\n/**\n * Positional update for keyed lists where keys changed en-masse but structure\n * (element tags and simple text children) remains identical. This updates\n * text content in-place and remaps the `data-key` attribute to the new key so\n * subsequent updates can find elements by their data-key.\n */\nexport function performBulkPositionalKeyedTextUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n) {\n const total = keyedVnodes.length;\n let reused = 0;\n let updatedKeys = 0;\n const t0 =\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\n try {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn('[Askr][FASTPATH] positional idx', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n chChildNodes: ch.childNodes.length,\n childrenType: Array.isArray(children) ? 'array' : typeof children,\n });\n }\n } catch (e) {\n void e;\n }\n\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 try {\n ch.setAttribute('data-key', String(key));\n updatedKeys++;\n } catch (e) {\n void e;\n }\n reused++;\n continue;\n } else {\n try {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn('[Askr][FASTPATH] positional tag mismatch', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n });\n }\n } catch (e) {\n void e;\n }\n }\n } else {\n try {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn('[Askr][FASTPATH] positional missing or invalid', i, {\n ch: !!ch,\n });\n }\n } catch (e) {\n void e;\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 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: total, reused, updatedKeys, t } as const;\n\n try {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn('[Askr][FASTPATH] bulk positional stats', stats);\n }\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkKeyedPositionalHits');\n } catch (e) {\n void e;\n }\n\n return stats;\n}\n\nexport function 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 existing node is an element and tags match, update in place\n const vnodeObj = vnode as unknown as {\n type?: unknown;\n children?: unknown;\n props?: Record<string, unknown>;\n };\n if (typeof vnodeObj.type === 'string') {\n const tag = vnodeObj.type as string;\n if (\n existingNode &&\n existingNode.nodeType === 1 &&\n (existingNode as Element).tagName.toLowerCase() === tag.toLowerCase()\n ) {\n updateElementFromVnode(existingNode as Element, vnode as VNode);\n finalNodes.push(existingNode);\n reused++;\n continue;\n }\n }\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n created++;\n continue;\n }\n }\n\n // Fallback: skip invalid vnode\n }\n\n const tBuild =\n (typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now()) - t0;\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) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\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 try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set('__LAST_DOM_REPLACE_STACK_DOM', new Error().stack);\n } catch (e) {\n void e;\n }\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 try {\n // Record bulk-unkeyed fast-path stats for diagnostics/tests\n __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkTextFastpathHits');\n } catch (e) {\n void e;\n }\n\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 */\nexport function isBulkTextFastPathEligible(\n parent: Element,\n newChildren: VNode[]\n) {\n const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;\n const requiredFraction = 0.8; // 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 __ASKR_set('__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 __ASKR_set('__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 __ASKR_set('__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","import type { VNode } from './types';\nimport { createDOMNode } from './dom';\nimport { _reconcilerRecordedParents } from './keyed';\nimport { logger } from '../dev/logger';\nimport { cleanupInstanceIfPresent, removeAllListeners } from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { isSchedulerExecuting } from '../runtime/scheduler';\nimport {\n isBulkCommitActive,\n markFastPathApplied,\n} from '../runtime/fastlane-shared';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Apply the \"renderer\" fast-path: build final node list reusing existing\n// elements by key when possible, then perform a single atomic replaceChildren\n// commit. Returns a new key map when the fast-path is applied, otherwise\n// returns null to indicate the caller should continue with fallback paths.\nexport function applyRendererFastPath(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap?: Map<string | number, Element>,\n unkeyedVnodes?: VNode[]\n): Map<string | number, Element> | null {\n // SSR guard: fast-path is DOM-specific\n if (typeof document === 'undefined') return null;\n\n const totalKeyed = keyedVnodes.length;\n if (totalKeyed === 0 && (!unkeyedVnodes || unkeyedVnodes.length === 0))\n return null;\n\n // Dev invariant: ensure we are executing inside the scheduler/commit flush\n if (!isSchedulerExecuting()) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path reconciliation invoked outside scheduler execution'\n );\n }\n\n // Choose lookup strategy depending on size (linear scan for small lists)\n let parentChildrenArr: Element[] | undefined;\n let localOldKeyMap: Map<string | number, Element> | undefined;\n\n if (totalKeyed <= 20) {\n try {\n const pc = parent.children;\n parentChildrenArr = new Array(pc.length);\n for (let i = 0; i < pc.length; i++)\n parentChildrenArr[i] = pc[i] as Element;\n } catch (e) {\n parentChildrenArr = undefined;\n void e;\n }\n } else {\n localOldKeyMap = new Map<string | number, Element>();\n try {\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const ch = parentChildren[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n localOldKeyMap.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);\n }\n }\n } catch (e) {\n localOldKeyMap = undefined;\n void e;\n }\n }\n\n const finalNodes: Node[] = [];\n let mapLookups = 0;\n let createdNodes = 0;\n let reusedCount = 0;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n mapLookups++;\n\n let el: Element | undefined;\n if (totalKeyed <= 20 && parentChildrenArr) {\n const ks = String(key);\n for (let j = 0; j < parentChildrenArr.length; j++) {\n const ch = parentChildrenArr[j];\n const k = ch.getAttribute('data-key');\n if (k !== null && (k === ks || Number(k) === (key as number))) {\n el = ch;\n break;\n }\n }\n if (!el) el = oldKeyMap?.get(key);\n } else {\n el = localOldKeyMap?.get(key as string | number) ?? oldKeyMap?.get(key);\n }\n\n if (el) {\n finalNodes.push(el);\n reusedCount++;\n } else {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Add unkeyed nodes (detached as well)\n if (unkeyedVnodes && unkeyedVnodes.length) {\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Atomic commit\n try {\n const tFragmentStart = Date.now();\n const fragment = document.createDocumentFragment();\n let fragmentAppendCount = 0;\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n fragmentAppendCount++;\n }\n\n // Pre-cleanup: remove component instances that will be removed by replaceChildren\n try {\n const existing = Array.from(parent.childNodes);\n // Only cleanup nodes that are *not* part of the finalNodes list so we don't\n // remove listeners from elements we're reusing (critical invariant)\n const toRemove = existing.filter((n) => !finalNodes.includes(n));\n for (const n of toRemove) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch (e) {\n void e;\n }\n\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set('__LAST_DOM_REPLACE_STACK_FASTPATH', new Error().stack);\n } catch (e) {\n void e;\n }\n\n parent.replaceChildren(fragment);\n\n // Record that we performed exactly one DOM commit.\n try {\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n } catch (e) {\n void e;\n }\n\n // If a runtime bulk commit is active, mark this parent as fast-path applied.\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n // Phase: bookkeeping - populate newKeyMap\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const node = finalNodes[i];\n if (node instanceof Element) newKeyMap.set(key, node as Element);\n }\n\n // Dev tracing\n try {\n const stats = {\n n: totalKeyed,\n moves: 0,\n lisLen: 0,\n t_lookup: 0,\n t_fragment: Date.now() - tFragmentStart,\n t_commit: 0,\n t_bookkeeping: 0,\n fragmentAppendCount,\n mapLookups,\n createdNodes,\n reusedCount,\n } as const;\n if (typeof globalThis !== 'undefined') {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_REUSED', reusedCount > 0);\n __ASKR_incCounter('fastpathHistoryPush');\n }\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH]',\n JSON.stringify({ n: totalKeyed, createdNodes, reusedCount })\n );\n }\n } catch (e) {\n void e;\n }\n\n // Record that reconciler recorded stats for this parent in this pass\n try {\n _reconcilerRecordedParents.add(parent);\n } catch (e) {\n void e;\n }\n\n return newKeyMap;\n } catch (e) {\n void e;\n return null;\n }\n}\n","import type { VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n performBulkPositionalKeyedTextUpdate,\n} from './dom';\nimport {\n keyedElements,\n _reconcilerRecordedParents,\n isKeyedReorderFastPathEligible,\n} from './keyed';\nimport { removeAllListeners, cleanupInstanceIfPresent } from './cleanup';\nimport { isBulkCommitActive } from '../runtime/fastlane-shared';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { applyRendererFastPath } from './fastpath';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\nexport function 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 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 (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as unknown as Record<string, unknown>;\n const rawKey =\n childObj.key ??\n (childObj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey !== undefined) {\n const key: string | number =\n typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n keyedVnodes.push({ key, vnode: child });\n } else {\n unkeyedVnodes.push(child);\n }\n } else {\n unkeyedVnodes.push(child);\n }\n }\n\n // Helper type for narrowings to avoid `any` casts in lint rules\n type VnodeObj = VNode & { type?: unknown; props?: Record<string, unknown> };\n\n // Try renderer fast-path early for large keyed reorder-only updates.\n try {\n const decision = isKeyedReorderFastPathEligible(\n parent,\n newChildren,\n oldKeyMap\n );\n if (\n (decision.useFastPath && keyedVnodes.length >= 128) ||\n // If we're executing inside a runtime bulk commit (fastlane), prefer the\n // renderer fast-path to ensure the single-commit invariant is preserved.\n isBulkCommitActive()\n ) {\n try {\n const map = applyRendererFastPath(\n parent,\n keyedVnodes,\n oldKeyMap,\n unkeyedVnodes\n );\n if (map) {\n try {\n keyedElements.set(parent, map);\n } catch (e) {\n void e;\n }\n return map;\n }\n } catch (e) {\n void e;\n }\n }\n\n // Heuristic: if the majority of children *by position* have matching tags\n // and are simple text/intrinsic children, prefer the positional bulk\n // positional update path which reuses existing elements by index and\n // preserves listeners. This is conservative and only used for relatively\n // small lists where the renderer fast-path declines.\n try {\n const total = keyedVnodes.length;\n if (total >= 10) {\n let matchCount = 0;\n try {\n for (let i = 0; i < total; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n if (\n !vnode ||\n typeof vnode !== 'object' ||\n typeof vnode.type !== 'string'\n )\n continue;\n const el = parent.children[i] as Element | undefined;\n if (!el) continue;\n if (el.tagName.toLowerCase() === String(vnode.type).toLowerCase())\n matchCount++;\n }\n } catch (e) {\n void e;\n }\n // Require high positional match fraction to keep this conservative\n if (matchCount / total >= 0.9) {\n // Additionally, decline this positional path if prop changes are present\n // that we cannot safely patch by remapping keys in-place. This mirrors\n // the conservative rule in the runtime classifier.\n let hasPropChanges = false;\n try {\n for (let i = 0; i < total; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const el = parent.children[i] as Element | undefined;\n if (!el || !vnode || typeof vnode !== 'object') continue;\n 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;\n const v = props[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 (\n (el as HTMLElement & Record<string, unknown>)[k] !== v\n ) {\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 (e) {\n hasPropChanges = true;\n void e;\n break;\n }\n }\n if (hasPropChanges) break;\n }\n } catch (e) {\n void e;\n }\n\n if (hasPropChanges) {\n // Decline positional path when props differ\n } else {\n try {\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 __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkKeyedPositionalHits');\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(parent.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(parent, map);\n } catch (e) {\n void e;\n }\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch (e) {\n void e;\n }\n }\n }\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n\n const finalNodes: Node[] = [];\n // Track used old elements to handle duplicate keys deterministically\n const usedOldEls = new WeakSet<Node>();\n\n const resolveOldElOnce = (k: string | number) => {\n if (!oldKeyMap) return undefined;\n // Fast-path: directly from oldKeyMap if available and not used\n const direct = oldKeyMap.get(k);\n if (direct && !usedOldEls.has(direct)) {\n usedOldEls.add(direct);\n return direct;\n }\n const s = String(k);\n const byString = oldKeyMap.get(s);\n if (byString && !usedOldEls.has(byString)) {\n usedOldEls.add(byString);\n return byString;\n }\n const n = Number(String(k));\n if (!Number.isNaN(n)) {\n const byNum = oldKeyMap.get(n as number);\n if (byNum && !usedOldEls.has(byNum)) {\n usedOldEls.add(byNum);\n return byNum;\n }\n }\n\n // Fallback: scan parent children to find the next matching element\n try {\n const children = Array.from(parent.children) as Element[];\n for (const ch of children) {\n if (usedOldEls.has(ch)) continue;\n const attr = ch.getAttribute('data-key');\n if (attr === s) {\n usedOldEls.add(ch);\n return ch;\n }\n const numAttr = Number(attr);\n if (!Number.isNaN(numAttr) && numAttr === (k as number)) {\n usedOldEls.add(ch);\n return ch;\n }\n }\n } catch (e) {\n void e;\n }\n\n return undefined;\n };\n\n // Positional reconciliation: iterate over new children and decide reuse\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n\n // Keyed child\n if (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as unknown as Record<string, unknown>;\n const rawKey =\n childObj.key ??\n (childObj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey !== undefined) {\n const key: string | number =\n typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n const el = resolveOldElOnce(key);\n if (el && el.parentElement === parent) {\n updateElementFromVnode(el, child as VNode);\n finalNodes.push(el);\n newKeyMap.set(key, el);\n continue;\n }\n const dom = createDOMNode(child as VNode);\n if (dom) {\n finalNodes.push(dom);\n if (dom instanceof Element) newKeyMap.set(key, dom);\n }\n continue;\n }\n }\n\n // Unkeyed or primitive child — try positional reuse if existing child is unkeyed\n try {\n const existing = parent.children[i] as Element | undefined;\n if (\n existing &&\n (typeof child === 'string' || typeof child === 'number') &&\n existing.nodeType === 1\n ) {\n // primitive -> existing element: update text content\n existing.textContent = String(child);\n finalNodes.push(existing);\n usedOldEls.add(existing);\n continue;\n }\n if (\n existing &&\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n (existing.getAttribute('data-key') === null ||\n existing.getAttribute('data-key') === undefined) &&\n typeof (child as VnodeObj).type === 'string' &&\n existing.tagName.toLowerCase() ===\n String((child as VnodeObj).type).toLowerCase()\n ) {\n updateElementFromVnode(existing, child as VNode);\n finalNodes.push(existing);\n usedOldEls.add(existing);\n continue;\n }\n\n // If the slot is occupied by a keyed node, try to find an available\n // unkeyed element elsewhere to preserve positional identity for\n // unkeyed siblings (critical for mixed keyed/unkeyed cases).\n try {\n const avail = Array.from(parent.children).find(\n (ch) => !usedOldEls.has(ch) && ch.getAttribute('data-key') === null\n );\n if (avail) {\n if (typeof child === 'string' || typeof child === 'number') {\n avail.textContent = String(child);\n } else if (\n typeof child === 'object' &&\n child !== null &&\n 'type' in child &&\n typeof (child as VnodeObj).type === 'string' &&\n avail.tagName.toLowerCase() ===\n String((child as VnodeObj).type).toLowerCase()\n ) {\n updateElementFromVnode(avail, child as VNode);\n } else {\n // If shape mismatches, rebuild\n const dom = createDOMNode(child as VNode);\n if (dom) {\n finalNodes.push(dom);\n continue;\n }\n }\n usedOldEls.add(avail);\n finalNodes.push(avail);\n continue;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n\n // Fallback: create DOM node\n const dom = createDOMNode(child as VNode);\n if (dom) finalNodes.push(dom);\n }\n\n // SSR guard: if DOM unavailable, do a conservative no-op\n if (typeof document === 'undefined') return newKeyMap;\n\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++)\n fragment.appendChild(finalNodes[i]);\n\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch (e) {\n void e;\n }\n\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set('__LAST_DOM_REPLACE_STACK_RECONCILE', new Error().stack);\n } catch (e) {\n void e;\n }\n\n parent.replaceChildren(fragment);\n keyedElements.delete(parent);\n return newKeyMap;\n}\n","import { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { elementListeners } from './cleanup';\nimport { keyedElements } from './keyed';\nimport { reconcileKeyedChildren } from './reconcile';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n updateUnkeyedChildren,\n performBulkPositionalKeyedTextUpdate,\n performBulkTextReplace,\n isBulkTextFastPathEligible,\n} from './dom';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\n\n/**\n * Internal marker for component-owned DOM ranges\n * Allows efficient partial DOM updates instead of clearing entire target\n */\ninterface DOMRange {\n start: Node; // Start marker (comment node)\n end: Node; // End marker (comment node)\n}\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\nconst domRanges = new WeakMap<object, DOMRange>();\n\nexport function evaluate(\n node: unknown,\n target: Element | null,\n context?: object\n): void {\n if (!target) return;\n // SSR guard: avoid DOM ops when not in a browser-like environment\n if (typeof document === 'undefined') {\n if (process.env.NODE_ENV !== 'production') {\n try {\n // Keep this lightweight and non-throwing so test harnesses and SSR\n // imports don't crash at runtime; callers should avoid calling\n // `evaluate` in SSR, but we make it safe as a no-op.\n console.warn('[Askr] evaluate() called in non-DOM environment; no-op.');\n } catch (e) {\n void e;\n }\n }\n return;\n }\n // Debug tracing to help understand why initial mounts sometimes don't\n // result in DOM mutations during tests.\n\n // If context provided, use component-owned DOM range (only replace that range)\n if (context && domRanges.has(context)) {\n const range = domRanges.get(context)!;\n // Remove all nodes between start and end markers\n let current = range.start.nextSibling;\n while (current && current !== range.end) {\n const next = current.nextSibling;\n current.remove();\n current = next;\n }\n // Append new DOM before end marker\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, range.end);\n }\n } else if (context) {\n // First render with context: create range markers\n const start = document.createComment('component-start');\n const end = document.createComment('component-end');\n target.appendChild(start);\n target.appendChild(end);\n domRanges.set(context, { start, end });\n // Render into the range\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, end);\n }\n } else {\n // Root render (no context): smart update strategy\n // If target has exactly one child of the same element type as the vnode,\n // reuse the element and just update its content.\n // This preserves the element reference and event handlers across renders.\n\n 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 // Attempt to populate oldKeyMap from DOM attributes if the\n // keyedElements registry hasn't been initialized yet. This\n // supports cases where initial render or previous updates set\n // `data-key` attributes but the runtime registry was not set.\n oldKeyMap = new Map();\n try {\n const children = Array.from(firstChild.children);\n for (let i = 0; i < children.length; i++) {\n const ch = children[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n oldKeyMap.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) oldKeyMap.set(n, ch);\n }\n }\n // Persist the discovered mapping so future updates can use\n // the move-by-key fast-path without re-scanning the DOM.\n if (oldKeyMap.size > 0)\n keyedElements.set(firstChild, oldKeyMap);\n } catch (e) {\n void e;\n }\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 if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)'\n );\n }\n 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 __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkKeyedPositionalForced');\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 if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced bulk path failed, falling back',\n err\n );\n }\n 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 __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_incCounter('bulkTextHits');\n } catch (e) {\n void e;\n }\n }\n } else {\n if (process.env.NODE_ENV !== 'production') {\n try {\n __ASKR_incCounter('bulkTextMisses');\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 const options: boolean | AddEventListenerOptions | undefined =\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ? { passive: true }\n : undefined;\n if (options !== undefined)\n el.addEventListener(eventName, wrappedHandler, options);\n else 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 options,\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","// Renderer barrel entrypoint.\n// Keep this file small: re-export the public surface and attach the\n// runtime fast-lane bridge on import.\n\nexport * from './types';\nexport * from './cleanup';\nexport * from './keyed';\nexport * from './dom';\nexport { evaluate, clearDOMRange } from './evaluate';\n\nimport { evaluate as _evaluate } from './evaluate';\nimport { isKeyedReorderFastPathEligible, getKeyMapForElement } from './keyed';\n\n// Expose minimal renderer bridge for runtime fast-lane to call `evaluate`\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as Record<string, unknown>;\n _g.__ASKR_RENDERER = {\n evaluate: _evaluate,\n isKeyedReorderFastPathEligible,\n getKeyMapForElement,\n };\n}\n","/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport { logger } from '../dev/logger';\nimport { __ASKR_incCounter, __ASKR_set } from '../renderer/diag';\n\nexport type ComponentFunction = (\n props: Props,\n context?: { signal: AbortSignal }\n) => JSXElement | VNode | string | number | null;\n\ntype VNode = {\n type: string;\n props?: Props;\n children?: (string | VNode | null | undefined | false)[];\n};\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController; // Per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of state indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadStates?: Set<State<unknown>>; // States read during the in-progress render\n _lastReadStates?: Set<State<unknown>>; // States read during the last committed render\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: new AbortController(), // Create per-component\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadStates: new Set(),\n _lastReadStates: new Set(),\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n instance._pendingFlushTask = () => {\n // Called by state.set() when we want to flush a pending update\n instance.hasPendingUpdate = false;\n // Trigger a run via enqueue helper — this will schedule the component run\n instance._enqueueRun?.();\n };\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane-shared';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n for (const operation of instance.mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element)\n (\n target as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n\n // Atomic rendering: capture DOM state for rollback on error\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) return;\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n if (instance.target) {\n // Keep `oldChildren` in the outer scope so rollback handlers can\n // reference the original node list even if the inner try block\n // throws. This preserves listeners and instance backrefs on rollback.\n let oldChildren: Node[] = [];\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n try {\n evaluate(result, instance.target);\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n for (const n of newChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n for (const n of currentChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n 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\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n // Warn if render takes more than 5ms\n logger.warn(\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n // Check for unused state\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n if (state && !state._hasBeenRead) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n logger.warn(\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n logger.warn(\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Create a fresh abort controller on mount to allow remounting\n // (old one may have been aborted during previous cleanup)\n instance.abortController = new AbortController();\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(() => runComponent(instance));\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return currentInstance.abortController.signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n const newSet = instance._pendingReadStates ?? new Set();\n const oldSet = instance._lastReadStates ?? new Set();\n const token = instance._currentRenderToken;\n\n if (token === undefined) return;\n\n // Remove subscriptions for states that were read previously but not in this render\n for (const s of oldSet) {\n if (!newSet.has(s)) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n }\n\n // Commit token becomes the authoritative token for this instance's last render\n instance.lastRenderToken = token;\n\n // Record subscriptions for states read during this render\n for (const s of newSet) {\n let readers = (s as State<unknown>)._readers;\n if (!readers) {\n readers = new Map();\n // s is a State object; assign its _readers map\n (s as State<unknown>)._readers = readers;\n }\n readers.set(instance, instance.lastRenderToken ?? 0);\n }\n\n instance._lastReadStates = newSet;\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n // Execute cleanup functions (from mount effects)\n const cleanupErrors: unknown[] = [];\n for (const cleanup of instance.cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else {\n // Preserve previous behavior: log warnings in dev and continue\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('[Askr] cleanup function threw:', err);\n }\n }\n }\n }\n instance.cleanupFns = [];\n if (cleanupErrors.length > 0) {\n // If strict mode, surface all cleanup errors as an AggregateError after attempting all cleanups\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n\n // Remove deterministic state subscriptions for this instance\n if (instance._lastReadStates) {\n for (const s of instance._lastReadStates) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n instance._lastReadStates = new Set();\n }\n\n // Abort all pending operations\n instance.abortController.abort();\n}\n","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 Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as Record<string, unknown>)[key];\n if (value && typeof value === 'object') deepFreeze(value);\n }\n }\n return obj;\n}\n\n// Build an immutable query helper from a search string\nfunction makeQuery(search: string): RouteQuery {\n const usp = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n for (const [k, v] of usp.entries()) {\n const existing = mapping.get(k);\n if (existing) existing.push(v);\n else mapping.set(k, [v]);\n }\n\n const obj: RouteQuery = {\n get(key: string) {\n const arr = mapping.get(key);\n return arr ? arr[0] : null;\n },\n getAll(key: string) {\n const arr = mapping.get(key);\n return arr ? [...arr] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const out: Record<string, string | string[]> = {};\n for (const [k, arr] of mapping.entries()) {\n out[k] = arr.length > 1 ? [...arr] : arr[0];\n }\n return out;\n },\n };\n\n return deepFreeze(obj);\n}\n\n// Compute matches by scanning registered routes (public API: getRoutes)\nfunction computeMatches(pathname: string): RouteMatch[] {\n const routesList = getRoutes();\n const matches: Array<{\n pattern: string;\n params: Record<string, string>;\n name?: string;\n namespace?: string;\n specificity: number;\n }> = [];\n\n function getSpecificity(path: string) {\n // Reuse same heuristic as above\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n if (normalized === '/*') return 0;\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) score += 2;\n else if (segment === '*') score += 1;\n else score += 3;\n }\n return score;\n }\n\n for (const r of routesList) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n matches.push({\n pattern: r.path,\n params: result.params,\n name: (r as { name?: string }).name,\n namespace: r.namespace,\n specificity: getSpecificity(r.path),\n });\n }\n }\n\n matches.sort((a, b) => b.specificity - a.specificity);\n\n return matches.map((m) => ({\n path: m.pattern,\n params: deepFreeze({ ...m.params }),\n name: m.name,\n namespace: m.namespace,\n }));\n}\n\n/**\n * Dual-purpose `route` function:\n * - route() → returns a read-only, deeply frozen RouteSnapshot (render-time)\n * - route(path, handler, namespace?) → registers a route handler (existing semantics)\n */\n// Prevent runtime registrations after the app has started\nlet registrationLocked = false;\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\n// Internal test helpers\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\nexport function route(): RouteSnapshot;\nexport function route(\n path: string,\n handler?: RouteHandler,\n namespace?: string\n): void;\nexport function route(\n path?: string,\n handler?: RouteHandler,\n namespace?: string\n): void | RouteSnapshot {\n // If called with no args, act as render-time accessor\n if (typeof path === 'undefined') {\n // Access the current component instance to ensure route() is only\n // called during render.\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'route() can only be called during component render execution. ' +\n 'Call route() from inside your component function.'\n );\n }\n\n // Determine location source: client window if present; otherwise SSR override\n let pathname = '/';\n let search = '';\n let hash = '';\n\n if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const params = deepFreeze({\n ...((instance.props as Record<string, string>) || {}),\n });\n const query = makeQuery(search);\n const matches = computeMatches(pathname);\n\n const snapshot: RouteSnapshot = Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n\n return snapshot;\n }\n\n // Disallow route registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n // Disallow registrations after app startup\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. Register routes at module load time before calling createIsland().'\n );\n }\n\n // Otherwise register a route (backwards compatible behavior)\n if (typeof handler !== 'function') {\n throw new Error(\n 'route(path, handler) requires a function handler that returns a VNode (e.g. () => <Page />). ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n const routeObj: Route = { path, handler: handler as RouteHandler, namespace };\n routes.push(routeObj);\n\n // Index by depth (maintains insertion order within depth)\n const depth = getDepth(path);\n\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n\n depthRoutes.push(routeObj);\n\n if (namespace) {\n namespaces.add(namespace);\n }\n}\n\n/**\n * Get all registered routes\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/**\n * Get routes for a specific namespace\n */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/**\n * Unload all routes from a namespace (for MFE unmounting)\n */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n // Remove from main array\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n // Remove from depth index\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) {\n depthRoutes.splice(idx, 1);\n }\n }\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/**\n * Clear all registered routes (mainly for testing)\n */\nexport function clearRoutes(): void {\n routes.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n}\n\n/**\n * RouteDescriptor type — used by `registerRoute` for nested descriptors.\n *\n * Note: `registerRouteTree` helper was removed; prefer explicit `route()` registrations.\n */\nexport type RouteDescriptor = {\n path: string;\n handler?: RouteHandler | unknown;\n children?: RouteDescriptor[];\n _isDescriptor?: true;\n};\n\n// `registerRouteTree` was removed — register explicit absolute paths with `route(path, handler)` instead.\n// If you need a helper to register descriptor trees, add a small wrapper in userland that\n// calls `route()` recursively.\n\n// Helper: normalize common handler shapes\n// NOTE: Only function handlers are accepted — passing raw JSX/VNodes at register\n// time is not allowed. This keeps registration data-only and avoids surprising\n// semantics between module-load-time and render-time.\nfunction normalizeHandler(handler: unknown): RouteHandler | undefined {\n if (handler == null) return undefined;\n if (typeof handler === 'function') {\n // Accept both (params) => ... handlers and component functions that take no args / props\n return (params: Record<string, string>, ctx?: { signal?: AbortSignal }) => {\n // Call with params and ctx; component functions can ignore them\n // Allow handler to return JSX element, VNode, Promise, etc.\n // If the function expects only props, passing params is safe (extra args ignored)\n try {\n return handler(params, ctx);\n } catch {\n return handler(params);\n }\n };\n }\n return undefined;\n}\n\n// Register route with flexible handler shapes and optional nested descriptors.\n// Usage patterns supported:\n// - Absolute flat registration: registerRoute('/pages', () => List())\n// - Nested descriptors: registerRoute('/', () => Home(), registerRoute('pages', () => List(), registerRoute('{id}', () => Detail())))\n// Note: child descriptors should use relative paths (no leading '/').\nexport function registerRoute(\n path: string,\n handler?: unknown,\n ...children: Array<RouteDescriptor | undefined>\n): RouteDescriptor {\n const isRelative = !path.startsWith('/');\n\n // Build descriptor that can be used for nesting\n const descriptor: RouteDescriptor = {\n path,\n handler,\n children: children.filter(Boolean) as RouteDescriptor[],\n _isDescriptor: true,\n };\n\n // If path is absolute, perform registration immediately and recurse into children\n if (!isRelative) {\n const normalized = normalizeHandler(handler);\n if (handler != null && !normalized) {\n throw new Error(\n 'registerRoute(path, handler) requires a function handler. Passing JSX elements or VNodes directly is not supported.'\n );\n }\n if (normalized) route(path, normalized);\n\n for (const child of descriptor.children || []) {\n // Compute child full path\n const base = path === '/' ? '' : path.replace(/\\/$/, '');\n const childPath = `${base}/${child.path.replace(/^\\//, '')}`.replace(\n /\\/\\//g,\n '/'\n );\n // Recurse: if child.handler is provided, register it\n if (child.handler) {\n const childNormalized = normalizeHandler(child.handler);\n if (!childNormalized) {\n throw new Error(\n 'registerRoute child handler must be a function. Passing JSX elements directly is not supported.'\n );\n }\n if (childNormalized) route(childPath, childNormalized);\n }\n // Recurse into grandchildren\n if (child.children && child.children.length) {\n // Convert child.children into descriptors and register them\n // Use registerRoute recursively with absolute childPath\n registerRoute(\n childPath,\n null,\n ...(child.children as RouteDescriptor[])\n );\n }\n }\n\n return descriptor;\n }\n\n // If relative, return descriptor for nesting (do not register yet)\n return descriptor;\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\n/**\n * Resolve a path to a route handler with optimized lookup\n * Routes are matched by specificity: literals > parameters > wildcards > catch-all\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const depth =\n normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n\n // Collect all matching routes with their specificity\n const candidates: Array<{\n route: Route;\n specificity: number;\n params: Record<string, string>;\n }> = [];\n\n // Try routes at this depth first (most likely match)\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n for (const r of depthRoutes) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n }\n\n // Fallback: scan all routes for different depths\n // (handles edge cases like wildcard routes)\n for (const r of routes) {\n // Skip if already checked in depth routes\n if (depthRoutes?.includes(r)) continue;\n\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n\n // Sort by specificity (highest first)\n candidates.sort((a, b) => b.specificity - a.specificity);\n\n // Return most specific match\n if (candidates.length > 0) {\n const best = candidates[0];\n return { handler: best.route.handler, params: best.params };\n }\n\n return null;\n}\n","/**\n * Client-side navigation with History API\n */\n\nimport { resolveRoute, lockRouteRegistration } from './route';\nimport {\n mountComponent,\n cleanupComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport { logger } from '../dev/logger';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\n\n/**\n * Register the current app instance (called by createIsland)\n */\nexport function registerAppInstance(\n instance: ComponentInstance,\n _path: string\n): void {\n currentInstance = instance;\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (process.env.NODE_ENV === 'production') {\n lockRouteRegistration();\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n // Resolve the new path to a route\n const resolved = resolveRoute(path);\n\n if (!resolved) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n // Update browser history\n window.history.pushState({ path }, '', path);\n\n // Re-render with the new route handler and params\n if (currentInstance) {\n // Cleanup previous route (abort pending operations)\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n // It takes params as props and renders the route\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for new route\n // Old controller is already aborted; we need a fresh one for async operations\n currentInstance.abortController = new AbortController();\n\n // Re-execute and re-mount component\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const path = window.location.pathname;\n\n if (!currentInstance) {\n return;\n }\n\n const resolved = resolveRoute(path);\n\n if (resolved) {\n // Cleanup old component\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for back/forward navigation\n currentInstance.abortController = new AbortController();\n\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window !== 'undefined') {\n window.addEventListener('popstate', handlePopState);\n }\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n if (typeof window !== 'undefined') {\n window.removeEventListener('popstate', handlePopState);\n }\n}\n","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 isPromiseLike(x: unknown): x is PromiseLike<unknown> {\n if (!x || typeof x !== 'object') return false;\n const then = (x as { then?: unknown }).then;\n return typeof then === 'function';\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 (isPromiseLike(res)) {\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// Dev-only SSR strictness guard helpers. We mutate globals in dev to make\n// accidental usage of Math.random/Date.now during sync SSR fail fast.\n// We implement a re-entrant stack so nested or concurrent calls don't clobber\n// global values unexpectedly.\nconst __ssrGuardStack: Array<{ random: () => number; now: () => number }> = [];\n\nexport function pushSSRStrictPurityGuard() {\n /* istanbul ignore if - dev-only guard */\n if (process.env.NODE_ENV === 'production') return;\n __ssrGuardStack.push({\n random: Reflect.get(Math, 'random') as () => number,\n now: Reflect.get(Date, 'now') as () => number,\n });\n Reflect.set(Math, '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 Reflect.set(Date, '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\nexport function popSSRStrictPurityGuard() {\n /* istanbul ignore if - dev-only guard */\n if (process.env.NODE_ENV === 'production') return;\n const prev = __ssrGuardStack.pop();\n if (prev) {\n Reflect.set(Math, 'random', prev.random);\n Reflect.set(Date, 'now', prev.now);\n }\n}\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 // We already verified the shape above; assert as VNode for the sync renderer\n return renderNodeSync(child as 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 // Re-entrant guard for dev-only SSR strict purity checks.\n // We avoid clobbering globals permanently by pushing the original functions\n // onto a stack and restoring them on exit. This is safer for nested or\n // stacked SSR render invocations.\n\n try {\n if (process.env.NODE_ENV !== 'production') {\n pushSSRStrictPurityGuard();\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 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 if (process.env.NODE_ENV !== 'production') popSSRStrictPurityGuard();\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, task, derive } from './runtime/operations';\nexport type { DataResult } from './runtime/operations';\n\n// App bootstrap (explicit startup APIs)\nexport {\n createIsland,\n createSPA,\n hydrateSPA,\n cleanupApp,\n hasApp,\n} from './boot';\nexport type { IslandConfig, SPAConfig, HydrateSPAConfig } from './boot';\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';\n\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// Foundations (public convenience exports)\nexport { layout } from './foundations/layout';\nexport type { LayoutComponent } from './foundations/layout';\nexport { Slot } from './foundations/slot';\nexport type { SlotProps } from './foundations/slot';\nexport { definePortal } from './foundations/portal';\nexport type { Portal } from './foundations/portal';\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 { createIsland, createSPA, hydrateSPA } from './boot';\n\n// Ensure fastlane bridge is initialized for environments (tests/global access)\n// This file exports a side-effectful module that attaches helpers to globalThis.\nimport './runtime/fastlane';\n\nif (typeof globalThis !== 'undefined') {\n const g = globalThis as Record<string, unknown>;\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-shared';\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 set(updater: (prev: T) => 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 State<T> & { _owner?: ComponentInstance })._owner = instance;\n\n // Attach set method directly to function\n read.set = (newValueOrUpdater: T | ((prev: T) => 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 // Compute new value if an updater was provided\n let newValue: T;\n if (typeof newValueOrUpdater === 'function') {\n // Note: function-valued state cannot be set directly via a function argument;\n // such an argument is treated as a functional updater (this follows the common\n // convention from other libraries). If you need to store a function as state,\n // wrap it in an object.\n const updater = newValueOrUpdater as (prev: T) => T;\n newValue = updater(value);\n } else {\n newValue = newValueOrUpdater as T;\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 // Attach debug label (component name) for richer logs\n cell.ownerName = inst.fn?.name || '<anonymous>';\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\n// Short-form overload: accept a single function that returns the derived value\nexport function derive<TOut>(fn: () => TOut): TOut | null;\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 // Short-form: derive(() => someExpression)\n if (map === undefined && typeof source === 'function') {\n const value = (source as () => TOut)();\n if (value == null) return null;\n\n const instance = getCurrentComponentInstance();\n if (!instance) {\n return value as TOut;\n }\n\n const cache = getDeriveCache(instance);\n if (cache.has(value as unknown)) return cache.get(value as unknown) as TOut;\n\n cache.set(value as unknown, value as unknown);\n return value as TOut;\n }\n\n // Normal form: derive(source, map)\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 as (v: TIn) => TOut)(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 as unknown)) {\n return cache.get(value as unknown) as TOut;\n }\n\n // Compute and cache the result\n const result = (map as (v: TIn) => TOut)(value as TIn);\n cache.set(value as unknown, result as unknown);\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 // Optional debug label set by caller (component name) to improve logs\n ownerName?: string;\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 if (this.ownerName) {\n logger.error(\n `[Askr] Async resource error in ${this.ownerName}:`,\n err\n );\n } else {\n logger.error('[Askr] Async resource error:', err);\n }\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","// Centralized memoization cache for derive()\n// Maps (component_instance) -> Map<source_value, result>\nconst deriveCacheMap = new WeakMap<{ id: string }, Map<unknown, unknown>>();\n\nexport function getDeriveCache(instance: {\n id: string;\n}): Map<unknown, unknown> {\n let cache = deriveCacheMap.get(instance);\n if (!cache) {\n cache = new Map();\n deriveCacheMap.set(instance, cache);\n }\n return cache;\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 { registerAppInstance, initializeNavigation } from '../router/navigate';\n\nlet componentIdCounter = 0;\n\n// Track instances by root element to support multiple createIsland 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 // Opt-in: surface cleanup errors during teardown for this app instance\n cleanupStrict?: boolean;\n}\n\nfunction attachCleanupForRoot(\n rootElement: Element,\n instance: ComponentInstance\n) {\n (rootElement as ElementWithCleanup)[CLEANUP_SYMBOL] = () => {\n // Attempt to remove listeners and cleanup instances under the root.\n // In non-strict mode we preserve previous behavior by swallowing errors\n // (but logging in dev); in strict mode we aggregate and re-throw.\n const errors: unknown[] = [];\n try {\n removeAllListeners(rootElement);\n } catch (e) {\n errors.push(e);\n }\n\n // Manually traverse descendants and attempt to cleanup their instances.\n // Avoids import cycles by using local traversal and existing cleanupComponent.\n try {\n const descendants = rootElement.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n const inst = (d as Element & { __ASKR_INSTANCE?: ComponentInstance })\n .__ASKR_INSTANCE;\n if (inst) {\n try {\n cleanupComponent(inst);\n } catch (err) {\n errors.push(err);\n }\n try {\n delete (d as Element & { __ASKR_INSTANCE?: ComponentInstance })\n .__ASKR_INSTANCE;\n } catch (err) {\n errors.push(err);\n }\n }\n } catch (err) {\n errors.push(err);\n }\n }\n } catch (e) {\n errors.push(e);\n }\n\n try {\n cleanupComponent(instance as ComponentInstance);\n } catch (e) {\n errors.push(e);\n }\n\n if (errors.length > 0) {\n if (instance.cleanupStrict) {\n throw new AggregateError(errors, `cleanup failed for app root`);\n } else if (process.env.NODE_ENV !== 'production') {\n for (const err of errors) logger.warn('[Askr] cleanup error:', err);\n }\n }\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 try {\n removeAllListeners(rootElement);\n } catch (e) {\n if (instance.cleanupStrict) throw e;\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] cleanup error:', e);\n }\n\n try {\n cleanupComponent(instance as ComponentInstance);\n } catch (e) {\n if (instance.cleanupStrict) throw e;\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] cleanup error:', e);\n }\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\n/**\n * Explicitly teardown an app mounted on `root` if present. This is the\n * recommended API for deterministic cleanup rather than relying on overriding\n * `innerHTML` setter behavior.\n */\nexport function teardownApp(_root: Element | string) {\n throw new Error(\n 'The `teardownApp` alias has been removed. Use `cleanupApp(root)` instead.'\n );\n}\n\nfunction mountOrUpdate(\n rootElement: Element,\n componentFn: ComponentFunction,\n options?: { cleanupStrict?: boolean }\n) {\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 try {\n cleanupComponent(instance);\n } catch (e) {\n // If previous cleanup threw in strict mode, log but continue mounting new instance\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] prior cleanup threw:', e);\n }\n\n instance.fn = componentFn;\n instance.evaluationGeneration++;\n instance.mounted = false;\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.isRoot = true;\n // Update strict flag if provided\n if (options && typeof options.cleanupStrict === 'boolean') {\n instance.cleanupStrict = options.cleanupStrict;\n }\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 // Initialize strict flag from options\n if (options && typeof options.cleanupStrict === 'boolean') {\n instance.cleanupStrict = options.cleanupStrict;\n }\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';\nimport { removeAllListeners } from '../renderer';\n\nexport type IslandConfig = {\n root: Element | string;\n component: ComponentFunction;\n // Optional: surface cleanup errors during teardown for this island\n cleanupStrict?: boolean;\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 // Optional: surface cleanup errors during teardown for this SPA\n cleanupStrict?: boolean;\n component?: never;\n};\n\nexport type HydrateSPAConfig = {\n root: Element | string;\n routes: Route[];\n // Optional: surface cleanup errors during teardown for this SPA\n cleanupStrict?: boolean;\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 cleanupStrict: config.cleanupStrict,\n });\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 cleanupStrict: false,\n });\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 cleanupStrict: false,\n });\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 cleanupStrict: false,\n });\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 * Link component for client-side navigation\n */\n\nimport { navigate } from '../router/navigate';\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): unknown {\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","/**\n * Layout helper.\n *\n * A layout is just a normal component that wraps children.\n * Persistence and reuse are handled by the runtime via component identity.\n *\n * This helper exists purely for readability and convention.\n */\n\nexport type LayoutComponent<P = object> = (\n props: P & { children?: unknown }\n) => unknown;\n\nexport function layout<P = object>(Layout: LayoutComponent<P>) {\n return (children?: unknown, props?: P) =>\n Layout({ ...(props as P), children });\n}\n","import { logger } from '../dev/logger';\nimport { Fragment, cloneElement, isElement } from '../jsx';\n\nexport type SlotProps =\n | {\n asChild: true;\n children: unknown;\n [key: string]: unknown;\n }\n | {\n asChild?: false;\n children?: unknown;\n };\n\nexport function Slot(props: SlotProps) {\n if (props.asChild) {\n const { children, ...rest } = props;\n\n if (isElement(children)) {\n return cloneElement(children, rest);\n }\n\n logger.warn('<Slot asChild> expects a single JSX element child.');\n\n return null;\n }\n\n // Structural no-op: Slot does not introduce DOM\n // Return a vnode object for the fragment to avoid using JSX in a .ts file.\n return { type: Fragment, props: { children: props.children } } as unknown;\n}\n","export { Fragment, ELEMENT_TYPE } from './types';\nexport type { JSXElement } from './types';\n\nexport { isElement, cloneElement } from './utils';\n","import { ELEMENT_TYPE, JSXElement } from './types';\n\nexport function isElement(value: unknown): value is JSXElement {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as JSXElement).$$typeof === ELEMENT_TYPE\n );\n}\n\nexport function cloneElement(\n element: JSXElement,\n props: Record<string, unknown>\n): JSXElement {\n return {\n ...element,\n props: { ...element.props, ...props },\n };\n}\n","/**\n * Portal / Host primitive.\n *\n * A portal is a named render slot within the existing tree.\n * It does NOT create a second tree or touch the DOM directly.\n */\n\nexport interface Portal<T = unknown> {\n /** Mount point — rendered exactly once */\n (): unknown;\n\n /** Render content into the portal */\n render(props: { children?: T }): unknown;\n}\n\nexport function definePortal<T = unknown>(): Portal<T> {\n // Runtime-provided slot implementation\n const slot = createPortalSlot<T>();\n\n function PortalHost() {\n return slot.read();\n }\n\n PortalHost.render = function PortalRender(props: { children?: T }) {\n slot.write(props.children);\n return null;\n };\n\n return PortalHost as Portal<T>;\n}\n\n/**\n * NOTE:\n * createPortalSlot is a runtime primitive.\n * It owns scheduling, consistency, and SSR behavior.\n */\ndeclare function createPortalSlot<T>(): {\n read(): unknown;\n write(value: T | undefined): void;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,UACd,WACA,SACA,SACmB;AACnB,MAAI,CAAC,WAAW;AACd,UAAM,aAAa,UAAU,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI;AACvE,UAAM,IAAI,MAAM,oBAAoB,OAAO,GAAG,UAAU,EAAE;AAAA,EAC5D;AACF;AA0GO,SAAS,6BACd,WACA,kB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E,SAAU,GAAE,WAAW;AAChC;","names":["state","task","current","isBulkCommitActive","init_types","ELEMENT_TYPE","Fragment","init_types","state","Fragment","current","isBulkCommitActive","isBulkCommitActive","dom","current","isBulkCommitActive","e","state","init_context","getSpecificity","currentInstance","executeComponent","init_context","escapeText","escapeCache","escapeAttr","renderAttrs","executeComponentSync","VOID_ELEMENTS","attrs","routes","clearRoutes","route","setServerLocation","lockRouteRegistration","resolveRoute","init_context","Fragment","isBulkCommitActive","task","init_context","init_context","renderData","holder","h","cell","value","instance","cache","clearRoutes","route","lockRouteRegistration","resolveRoute","instance","setServerLocation","renderToStringSync","registerAppInstance","initializeNavigation","init_types","init_types"]}
|
|
1
|
+
{"version":3,"sources":["../src/dev/invariant.ts","../src/dev/logger.ts","../src/runtime/scheduler.ts","../src/runtime/context.ts","../src/renderer/diag/index.ts","../src/runtime/dev-namespace.ts","../src/runtime/fastlane-shared.ts","../src/renderer/types.ts","../src/renderer/cleanup.ts","../src/renderer/utils.ts","../src/renderer/keyed.ts","../src/jsx/types.ts","../src/jsx/jsx-runtime.ts","../src/renderer/dom.ts","../src/renderer/fastpath.ts","../src/renderer/reconcile.ts","../src/renderer/evaluate.ts","../src/renderer/index.ts","../src/runtime/component.ts","../src/ssr/errors.ts","../src/ssr/context.ts","../src/ssr/render-keys.ts","../src/router/match.ts","../src/router/route.ts","../src/router/navigate.ts","../src/jsx/utils.ts","../src/jsx/index.ts","../src/foundations/portal.tsx","../src/ssr/escape.ts","../src/ssr/attrs.ts","../src/ssr/sink.ts","../src/ssr/stream-render.ts","../src/ssr/index.ts","../src/index.ts","../src/runtime/state.ts","../src/runtime/operations.ts","../src/runtime/resource-cell.ts","../src/shared/derive-cache.ts","../src/boot/index.ts","../src/components/Link.tsx","../src/foundations/layout.tsx","../src/foundations/slot.tsx","../src/runtime/fastlane.ts"],"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 {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private q: Task[] = [];\n private head = 0;\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n enqueue(task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.q.push(task);\n this.taskCount++;\n\n // Microtask kick: best-effort, but avoid if we are in handler or running or bulk commit\n if (\n !this.running &&\n !this.kickScheduled &&\n !this.inHandler &&\n !isBulkCommitActive()\n ) {\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running) return;\n if (isBulkCommitActive()) return;\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n\n try {\n while (this.head < this.q.length) {\n this.depth++;\n if (\n process.env.NODE_ENV !== 'production' &&\n this.depth > MAX_FLUSH_DEPTH\n ) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = this.q[this.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n } catch (err) {\n // ensure executionDepth stays balanced\n if (this.executionDepth > 0) this.executionDepth = 0;\n fatal = err;\n break;\n }\n\n // Account for executed task in taskCount\n if (this.taskCount > 0) this.taskCount--;\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n // Compact queue\n if (this.head >= this.q.length) {\n this.q.length = 0;\n this.head = 0;\n } else if (this.head > 0) {\n const remaining = this.q.length - this.head;\n if (this.head > 1024 || this.head > remaining) {\n this.q = this.q.slice(this.head);\n } else {\n for (let i = 0; i < remaining; i++) {\n this.q[i] = this.q[this.head + i];\n }\n this.q.length = remaining;\n }\n this.head = 0;\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n const g = globalThis as {\n queueMicrotask?: (...args: unknown[]) => void;\n setTimeout?: (...args: unknown[]) => unknown;\n };\n const origQueueMicrotask = g.queueMicrotask;\n const origSetTimeout = g.setTimeout;\n\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = () => {\n throw new Error(\n '[Scheduler] queueMicrotask not allowed during runWithSyncProgress'\n );\n };\n g.setTimeout = () => {\n throw new Error(\n '[Scheduler] setTimeout not allowed during runWithSyncProgress'\n );\n };\n }\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.q.length - this.head > 0) {\n this.flush();\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (this.q.length - this.head > 0) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // Restore guarded globals\n if (process.env.NODE_ENV !== 'production') {\n g.queueMicrotask = origQueueMicrotask;\n g.setTimeout = origSetTimeout;\n }\n\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const ns =\n (\n globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n }\n ).__ASKR__ || {};\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.q.length - this.head,\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n namespace: ns,\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.q.length - this.head,\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.q.length - this.head;\n if (remaining <= 0) return 0;\n\n if (this.running) {\n this.q.length = this.head;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n this.q.length = 0;\n this.head = 0;\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler.call(null, event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them now that the handler\n // has completed. This avoids tests timing out waiting for flush.\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n };\n}\n","/**\n * Context system: lexical scope + render-time snapshots\n *\n * CORE SEMANTIC (Option A — Snapshot-Based):\n * ============================================\n * An async resource observes the context of the render that created it.\n * Context changes only take effect via re-render, not magically mid-await.\n *\n * This ensures:\n * - Deterministic behavior\n * - Concurrency safety\n * - Replayable execution\n * - Debuggability\n *\n * INVARIANTS:\n * - readContext() only works during component render (has currentContextFrame)\n * - Each render captures a context snapshot\n * - Async continuations see the snapshot from render start (frozen)\n * - Provider (Scope) creates a new frame that shadows parent\n * - Context updates require re-render to take effect\n */\n\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport { getCurrentComponentInstance } from './component';\nimport type { ComponentInstance } from './component';\n\nexport type ContextKey = symbol;\n\n// Lightweight VNode definition used for JSX typing in this module\ntype VNode = {\n type: string;\n props?: Record<string, unknown>;\n children?: (string | VNode | null | undefined | false)[];\n};\n\n// Union of allowed render return values (text, vnode, JSX element, etc.)\ntype Renderable =\n | JSXElement\n | VNode\n | string\n | number\n | null\n | undefined\n | false;\n\nexport interface Context<T> {\n readonly key: ContextKey;\n readonly defaultValue: T;\n // A Scope is a JSX-style element factory returning a JSXElement (component invocation)\n readonly Scope: (props: { value: unknown; children?: unknown }) => JSXElement;\n}\n\nexport interface ContextFrame {\n parent: ContextFrame | null;\n // Lazily allocate `values` Map only when a provider sets values or a read occurs.\n values: Map<ContextKey, unknown> | null;\n}\n\n// Symbol to mark vnodes that need frame restoration\nexport const CONTEXT_FRAME_SYMBOL = Symbol('__tempoContextFrame__');\n\n// Global context frame stack (maintained during render)\n// INVARIANT: Must NEVER be non-null across an await boundary\nlet currentContextFrame: ContextFrame | null = null;\n\n// Async resource frame (maintained during async resource execution)\n// INVARIANT: Set only for synchronous execution steps, cleared in finally\n// This allows async resources to access their frozen render-time snapshot\nlet currentAsyncResourceFrame: ContextFrame | null = null;\n\n/**\n * Execute a function within a specific context frame.\n *\n * CORE PRIMITIVE for context restoration:\n * - Saves the current context\n * - Sets the provided frame as current\n * - Executes the function\n * - Restores the previous context in finally\n *\n * This ensures no context frame remains globally active across await.\n */\nexport function withContext<T>(frame: ContextFrame | null, fn: () => T): T {\n const oldFrame = currentContextFrame;\n currentContextFrame = frame;\n try {\n return fn();\n } finally {\n currentContextFrame = oldFrame;\n }\n}\n\n/**\n * Execute an async resource step within its frozen context snapshot.\n *\n * CRITICAL: This wrapper is applied only to synchronous execution steps of\n * an async resource (the initial call). We intentionally DO NOT restore\n * the resource frame for post-await continuations — continuations must not\n * observe or rely on a live resource frame. This keeps semantics simple and\n * deterministic: async resources see only their creation-time snapshot.\n */\nexport function withAsyncResourceContext<T>(\n frame: ContextFrame | null,\n fn: () => T\n): T {\n const oldFrame = currentAsyncResourceFrame;\n // Only set the frame for the synchronous execution step\n currentAsyncResourceFrame = frame;\n try {\n return fn();\n } finally {\n // Clear the frame to avoid exposing it across await boundaries\n currentAsyncResourceFrame = oldFrame;\n }\n}\n\nexport function defineContext<T>(defaultValue: T): Context<T> {\n const key = Symbol('AskrContext');\n\n return {\n key,\n defaultValue,\n Scope: (props: { value: unknown; children?: unknown }): JSXElement => {\n // Scope component: accepts an unknown value (tests often pass loosely typed values)\n // Cast to the expected T at the call site to preserve runtime behavior.\n const value = props.value as T;\n // Scope component: creates a new frame and renders children within it\n return {\n type: ContextScopeComponent,\n props: { key, value, children: props.children },\n } as JSXElement;\n },\n };\n}\n\nexport function readContext<T>(context: Context<T>): T {\n // Check render frame first (components), then async resource frame (resources)\n const frame = currentContextFrame || currentAsyncResourceFrame;\n\n if (!frame) {\n throw new Error(\n 'readContext() can only be called during component render or async resource execution. ' +\n 'Ensure you are calling this from inside your component or resource function.'\n );\n }\n\n let current: ContextFrame | null = frame;\n while (current) {\n // `values` may be null when no provider has created it yet — treat as empty\n const values = current.values;\n if (values && values.has(context.key)) {\n return values.get(context.key) as T;\n }\n current = current.parent;\n }\n return context.defaultValue;\n}\n\n/**\n * Internal component that manages context frame\n * Used by Context.Scope to provide shadowed value to children\n */\nfunction ContextScopeComponent(props: Props): Renderable {\n // Extract expected properties (we accept a loose shape so this can be used as a component type)\n const key = props['key'] as ContextKey;\n const value = props['value'];\n const children = props['children'] as Renderable;\n\n // Create a new frame with this value\n const instance = getCurrentComponentInstance();\n const parentFrame: ContextFrame | null = (() => {\n // Prefer the live render frame.\n // Note: the runtime executes component functions inside an empty \"render frame\"\n // whose parent points at the nearest provider chain. Even if this frame has no\n // values, it must still be used to preserve the parent linkage.\n if (currentContextFrame) return currentContextFrame;\n\n // If there is no live render frame (should be rare), fall back to the\n // instance's owner frame.\n if (instance && instance.ownerFrame) return instance.ownerFrame;\n\n // Do NOT fall back to the async snapshot stack here: that stack represents\n // unrelated async continuations and must not affect lexical provider chaining.\n return null;\n })();\n\n const newFrame: ContextFrame = {\n parent: parentFrame,\n values: new Map([[key, value]]),\n };\n\n // Helper: create a function-child invoker node (centralized cast)\n function createFunctionChildInvoker(\n fn: () => Renderable,\n frame: ContextFrame,\n owner: ComponentInstance | null\n ): Renderable {\n return {\n type: ContextFunctionChildInvoker,\n props: { fn, __frame: frame, __owner: owner },\n } as unknown as Renderable;\n }\n\n // The renderer will set ownerFrame on child component instances when they're created.\n // We mark vnodes with the frame so the renderer knows which frame to assign.\n if (Array.isArray(children)) {\n // Mark array elements with the frame. If an element is a function-child,\n // convert it into a lazy invoker so it's executed later inside the frame.\n return children.map((child) => {\n if (typeof child === 'function') {\n return createFunctionChildInvoker(\n child as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n }\n return markWithFrame(child, newFrame);\n }) as unknown as Renderable;\n } else if (typeof children === 'function') {\n // If children is a function (render callback), do NOT execute it eagerly\n // during the parent render. Instead, return a small internal component\n // that will execute the function later (when it itself is rendered) and\n // will execute it within the provider frame so any reads performed during\n // that execution observe the provider's frame.\n return createFunctionChildInvoker(\n children as () => Renderable,\n newFrame,\n getCurrentComponentInstance()\n );\n } else if (children) {\n return markWithFrame(children, newFrame);\n }\n\n return null;\n}\n\n/**\n * Internal: Mark a vnode with a context frame\n * The renderer will restore this frame before executing component functions\n */\nfunction markWithFrame(node: Renderable, frame: ContextFrame): Renderable {\n // Recursively mark node and its subtree so nested provider/component\n // executions will restore the correct frame when they are rendered.\n if (typeof node === 'object' && node !== null) {\n const obj = node as Record<string | symbol, unknown>;\n obj[CONTEXT_FRAME_SYMBOL] = frame;\n\n // If the node is a VNode with children, recursively mark its children\n const children = obj.children as unknown;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length; i++) {\n const child = children[i] as Renderable;\n if (child) {\n children[i] = markWithFrame(child, frame) as Renderable;\n }\n }\n } else if (children) {\n obj.children = markWithFrame(children as Renderable, frame) as Renderable;\n }\n }\n return node;\n}\n\n/**\n * Internal helper component: executes a function-child lazily inside the\n * provided frame and marks the returned subtree with that frame so later\n * component executions will restore the correct context frame.\n *\n * SNAPSHOT SEMANTIC: The frame passed here is the snapshot captured at render\n * time. Any resources created during this execution will observe this frozen\n * snapshot, ensuring deterministic behavior.\n */\nfunction ContextFunctionChildInvoker(props: {\n fn: () => Renderable;\n __frame: ContextFrame;\n __owner?: ComponentInstance | null;\n}): Renderable {\n const { fn, __frame } = props;\n\n // Execute the function-child within the provider frame.\n // The owner's ownerFrame is already set by the renderer when the component was created.\n // Any resources started during this execution will capture this frame as their\n // snapshot, ensuring they see the context values from this render, not future renders.\n const res = withContext(__frame, () => fn());\n\n // Mark the result so the renderer knows to set ownerFrame on child instances\n if (res) return markWithFrame(res, __frame);\n return null;\n}\n\n/**\n * Push a new context frame (for render entry)\n * Called by component runtime when render starts\n */\nexport function pushContextFrame(): ContextFrame {\n // Lazily allocate the `values` map to avoid per-render allocations when\n // components do not use context. The map will be created when a provider\n // sets a value or when a read discovers no map and needs to behave as empty.\n const frame: ContextFrame = {\n parent: currentContextFrame,\n values: null,\n };\n currentContextFrame = frame;\n return frame;\n}\n\n/**\n * Pop context frame (for render exit)\n * Called by component runtime when render ends\n */\nexport function popContextFrame(): void {\n if (currentContextFrame) {\n currentContextFrame = currentContextFrame.parent;\n }\n}\n\n/**\n * Get the current context frame for inspection (used by tests/diagnostics only)\n */\nexport function getCurrentContextFrame(): ContextFrame | null {\n return currentContextFrame;\n}\n\n/**\n * Get the top of the context snapshot stack (used by runtime when deciding\n * how to link snapshots for async continuations). Returns null if stack empty.\n */\nexport function getTopContextSnapshot(): ContextFrame | null {\n return currentContextFrame;\n}\n","type DiagMap = Record<string, unknown>;\n\nfunction getDiagMap(): DiagMap {\n try {\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR_DIAG?: DiagMap;\n };\n if (!root.__ASKR_DIAG) root.__ASKR_DIAG = {} as DiagMap;\n return root.__ASKR_DIAG!;\n } catch (e) {\n void e;\n return {} as DiagMap;\n }\n}\n\nexport function __ASKR_set(key: string, value: unknown): void {\n try {\n const g = getDiagMap();\n (g as DiagMap)[key] = value;\n try {\n // Consolidate diagnostics under a single namespace to avoid\n // polluting the top-level global scope. Expose a namespaced view on\n // `globalThis.__ASKR__` so tools and tests can inspect diagnostic keys.\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n try {\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n ns[key] = value;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n\nexport function __ASKR_incCounter(key: string): void {\n try {\n const g = getDiagMap();\n const prev = typeof g[key] === 'number' ? (g[key] as number) : 0;\n const next = prev + 1;\n (g as DiagMap)[key] = next;\n try {\n // Mirror counter into namespaced diagnostics\n const root = globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n };\n const ns = root.__ASKR__ || (root.__ASKR__ = {});\n try {\n const nsPrev = typeof ns[key] === 'number' ? (ns[key] as number) : 0;\n ns[key] = nsPrev + 1;\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n } catch (e) {\n void e;\n }\n}\n","/**\n * Dev-only namespace helpers for diagnostics\n *\n * Centralizes the repetitive globalThis.__ASKR__ access pattern\n * used throughout runtime for dev-mode diagnostics.\n */\n\ntype DevNamespace = Record<string, unknown>;\n\n/**\n * Get or create the __ASKR__ dev namespace on globalThis.\n * Returns empty object in production to avoid allocations.\n */\nexport function getDevNamespace(): DevNamespace {\n if (process.env.NODE_ENV === 'production') return {};\n try {\n const g = globalThis as unknown as Record<string, DevNamespace>;\n if (!g.__ASKR__) g.__ASKR__ = {};\n return g.__ASKR__;\n } catch {\n return {};\n }\n}\n\n/**\n * Set a value in the dev namespace (no-op in production).\n */\nexport function setDevValue(key: string, value: unknown): void {\n if (process.env.NODE_ENV === 'production') return;\n try {\n getDevNamespace()[key] = value;\n } catch {\n // ignore\n }\n}\n\n/**\n * Get a value from the dev namespace (returns undefined in production).\n */\nexport function getDevValue<T>(key: string): T | undefined {\n if (process.env.NODE_ENV === 'production') return undefined;\n try {\n return getDevNamespace()[key] as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Delete a value from the dev namespace (no-op in production).\n */\nexport function deleteDevValue(key: string): void {\n if (process.env.NODE_ENV === 'production') return;\n try {\n delete getDevNamespace()[key];\n } catch {\n // ignore\n }\n}\n","import { globalScheduler } from './scheduler';\nimport { setDevValue } from './dev-namespace';\n\nlet _bulkCommitActive = false;\nlet _appliedParents: WeakSet<Element> | null = null;\n\nexport function enterBulkCommit(): void {\n _bulkCommitActive = true;\n // Initialize registry of parents that had fast-path applied during this bulk commit\n _appliedParents = new WeakSet<Element>();\n\n // Clear any previously scheduled synchronous scheduler tasks so they don't\n // retrigger evaluations during the committed fast-path.\n try {\n const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__ASKR_FASTLANE_CLEARED_TASKS', cleared);\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n}\n\nexport function exitBulkCommit(): void {\n _bulkCommitActive = false;\n // Clear registry to avoid leaking across commits\n _appliedParents = null;\n}\n\nexport function isBulkCommitActive(): boolean {\n return _bulkCommitActive;\n}\n\n// Mark that a fast-path was applied on a parent element during the active\n// bulk commit. No-op if there is no active bulk commit.\nexport function markFastPathApplied(parent: Element): void {\n if (!_appliedParents) return;\n try {\n _appliedParents.add(parent);\n } catch (e) {\n void e;\n }\n}\n\nexport function isFastPathApplied(parent: Element): boolean {\n return !!(_appliedParents && _appliedParents.has(parent));\n}\n","import type { Props } from '../shared/types';\n\nexport interface DOMElement {\n // Element `type` can be an intrinsic tag name, a component function, or\n // a special symbol (e.g. `Fragment`). Include `symbol` in the type union\n // so runtime comparisons against `Fragment` are type-safe.\n type: string | ((props: Props) => unknown) | symbol;\n props?: Props;\n children?: VNode[];\n key?: string | number;\n [Symbol.iterator]?: never;\n}\n\n// Type for virtual DOM nodes\nexport type VNode = DOMElement | string | number | boolean | null | undefined;\n\nexport function _isDOMElement(node: unknown): node is DOMElement {\n return typeof node === 'object' && node !== null && 'type' in node;\n}\n","import { cleanupComponent } from '../runtime/component';\nimport type { ComponentInstance } from '../runtime/component';\nimport { logger } from '../dev/logger';\n\ntype InstanceHost = Element & { __ASKR_INSTANCE?: unknown };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Instance Cleanup Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction cleanupSingleInstance(\n node: InstanceHost,\n errors: unknown[],\n strict: boolean\n): void {\n const inst = node.__ASKR_INSTANCE;\n if (!inst) return;\n\n try {\n cleanupComponent(inst as ComponentInstance);\n } catch (err) {\n if (strict) errors.push(err);\n else logger.warn('[Askr] cleanupComponent failed:', err);\n }\n\n try {\n delete node.__ASKR_INSTANCE;\n } catch (e) {\n if (strict) errors.push(e);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public API\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Clean up component instance attached to a DOM node\n * Accepts an optional `opts.strict` flag to surface errors instead of swallowing them.\n */\nexport function cleanupInstanceIfPresent(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n if (!node || !(node instanceof Element)) return;\n\n const errors: unknown[] = [];\n const strict = opts?.strict ?? false;\n\n // Clean up the node itself\n try {\n cleanupSingleInstance(node as InstanceHost, errors, strict);\n } catch (err) {\n if (strict) errors.push(err);\n else logger.warn('[Askr] cleanupInstanceIfPresent failed:', err);\n }\n\n // Clean up any nested instances on descendants\n try {\n const descendants = node.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n cleanupSingleInstance(d as InstanceHost, errors, strict);\n } catch (err) {\n if (strict) errors.push(err);\n else\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant cleanup failed:',\n err\n );\n }\n }\n } catch (err) {\n if (strict) errors.push(err);\n else\n logger.warn(\n '[Askr] cleanupInstanceIfPresent descendant query failed:',\n err\n );\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, 'cleanupInstanceIfPresent failed');\n }\n}\n\n// Public helper to clean up any component instances under a node. Used by\n// runtime commit logic to ensure component instances are torn down when their\n// host nodes are removed during an update.\nexport function cleanupInstancesUnder(\n node: Node | null,\n opts?: { strict?: boolean }\n): void {\n cleanupInstanceIfPresent(node, opts);\n}\n\n// Track listeners so we can remove them on cleanup\nexport interface ListenerMapEntry {\n handler: EventListener;\n original: EventListener;\n options?: boolean | AddEventListenerOptions;\n}\nexport const elementListeners = new WeakMap<\n Element,\n Map<string, ListenerMapEntry>\n>();\n\nexport function removeElementListeners(element: Element): void {\n const map = elementListeners.get(element);\n if (map) {\n for (const [eventName, entry] of map) {\n // When removing, reuse the original options if present for correctness\n if (entry.options !== undefined)\n element.removeEventListener(eventName, entry.handler, entry.options);\n else element.removeEventListener(eventName, entry.handler);\n }\n elementListeners.delete(element);\n }\n}\n\nexport function removeAllListeners(root: Element | null): void {\n if (!root) return;\n\n // Remove listeners from root\n removeElementListeners(root);\n\n // Recursively remove from all children\n const children = root.querySelectorAll('*');\n for (let i = 0; i < children.length; i++) {\n removeElementListeners(children[i]);\n }\n}\n","/**\n * Shared utilities for the renderer module.\n * Consolidates common patterns to reduce code duplication.\n */\n\nimport { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ListenerEntry {\n handler: EventListener;\n original: EventListener;\n options?: boolean | AddEventListenerOptions;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse an event prop name (e.g., 'onClick') to its DOM event name (e.g., 'click')\n */\nexport function parseEventName(propName: string): string | null {\n if (!propName.startsWith('on') || propName.length <= 2) return null;\n return (\n propName.slice(2).charAt(0).toLowerCase() + propName.slice(3).toLowerCase()\n );\n}\n\n/**\n * Get default event listener options for passive events\n */\nexport function getPassiveOptions(\n eventName: string\n): AddEventListenerOptions | undefined {\n if (\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ) {\n return { passive: true };\n }\n return undefined;\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n */\nexport function createWrappedHandler(\n handler: EventListener,\n flushAfter = false\n): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n if (flushAfter) {\n // If the handler enqueued tasks while we disallowed microtask kicks,\n // ensure we schedule a microtask to flush them\n const state = globalScheduler.getState();\n if ((state.queueLength ?? 0) > 0 && !state.running) {\n queueMicrotask(() => {\n try {\n if (!globalScheduler.isExecuting()) globalScheduler.flush();\n } catch (err) {\n queueMicrotask(() => {\n throw err;\n });\n }\n });\n }\n }\n }\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Prop/Attribute Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Props that should be skipped during attribute processing */\nexport function isSkippedProp(key: string): boolean {\n return key === 'children' || key === 'key';\n}\n\n/** Check if prop should be ignored for prop-change detection */\nexport function isIgnoredForPropChanges(key: string): boolean {\n if (key === 'children' || key === 'key') return true;\n if (key.startsWith('on') && key.length > 2) return true;\n if (key.startsWith('data-')) return true;\n return false;\n}\n\n/**\n * Check if an element's current attribute value differs from vnode value\n */\nexport function hasPropChanged(\n el: Element,\n key: string,\n value: unknown\n): boolean {\n try {\n if (key === 'class' || key === 'className') {\n return el.className !== String(value);\n }\n if (key === 'value' || key === 'checked') {\n return (el as HTMLElement & Record<string, unknown>)[key] !== value;\n }\n const attr = el.getAttribute(key);\n if (value === undefined || value === null || value === false) {\n return attr !== null;\n }\n return String(value) !== attr;\n } catch {\n return true;\n }\n}\n\n/**\n * Check if a vnode has non-trivial props (excluding events and data-*)\n */\nexport function hasNonTrivialProps(props: Record<string, unknown>): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n return true;\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnode and existing element\n */\nexport function checkPropChanges(\n el: Element,\n props: Record<string, unknown>\n): boolean {\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n return false;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Extract key from a vnode object\n */\nexport function extractKey(vnode: unknown): string | number | undefined {\n if (typeof vnode !== 'object' || vnode === null) return undefined;\n const obj = vnode as Record<string, unknown>;\n const rawKey =\n obj.key ?? (obj.props as Record<string, unknown> | undefined)?.key;\n if (rawKey === undefined) return undefined;\n return typeof rawKey === 'symbol'\n ? String(rawKey)\n : (rawKey as string | number);\n}\n\n/**\n * Build a key map from element's children\n */\nexport function buildKeyMapFromChildren(\n parent: Element\n): Map<string | number, Element> {\n const map = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n for (const ch of children) {\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n map.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, ch);\n }\n }\n return map;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Diagnostic Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Record DOM replace operation for diagnostics\n */\nexport function recordDOMReplace(source: string): void {\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);\n } catch {\n // ignore\n }\n}\n\n/**\n * Record fast-path stats for diagnostics\n */\nexport function recordFastPathStats(\n stats: Record<string, unknown>,\n counterName?: string\n): void {\n try {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n if (counterName) {\n __ASKR_incCounter(counterName);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Conditionally log debug info for fast-path operations\n */\nexport function logFastPathDebug(\n message: string,\n indexOrData?: number | unknown,\n data?: unknown\n): void {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n if (data !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);\n } else if (indexOrData !== undefined) {\n logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);\n } else {\n logger.warn(`[Askr][FASTPATH] ${message}`);\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Get current high-resolution timestamp\n */\nexport function now(): number {\n return typeof performance !== 'undefined' && performance.now\n ? performance.now()\n : Date.now();\n}\n","import type { VNode } from './types';\nimport {\n extractKey,\n buildKeyMapFromChildren,\n isIgnoredForPropChanges,\n hasPropChanged,\n hasNonTrivialProps,\n} from './utils';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Key Map Registry\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const keyedElements = new WeakMap<\n Element,\n Map<string | number, Element>\n>();\n\n/**\n * Retrieve existing keyed map for a parent element (runtime use)\n */\nexport function getKeyMapForElement(el: Element) {\n return keyedElements.get(el);\n}\n\n/**\n * Populate a keyed map for an element by scanning its immediate children\n * for `data-key` attributes. Proactive initialization for runtime layers.\n */\nexport function populateKeyMapForElement(parent: Element): void {\n try {\n if (keyedElements.has(parent)) return;\n\n let domMap = buildKeyMapFromChildren(parent);\n\n // Fallback: map by textContent when keys are not materialized as attrs\n if (domMap.size === 0) {\n domMap = new Map();\n const children = Array.from(parent.children);\n for (const ch of children) {\n const text = (ch.textContent || '').trim();\n if (text) {\n domMap.set(text, ch);\n const n = Number(text);\n if (!Number.isNaN(n)) domMap.set(n, ch);\n }\n }\n }\n\n if (domMap.size > 0) keyedElements.set(parent, domMap);\n } catch {\n // ignore\n }\n}\n\n// Track which parents had the reconciler record fast-path stats during the\n// current evaluation, so we can preserve diagnostics across additional\n// reconciliations within the same render pass without leaking between runs.\nexport const _reconcilerRecordedParents = new WeakSet<Element>();\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fast-Path Eligibility\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface KeyedVnode {\n key: string | number;\n vnode: VNode;\n}\n\n/**\n * Extract keyed vnodes from children array\n */\nfunction extractKeyedVnodes(newChildren: VNode[]): KeyedVnode[] {\n const result: KeyedVnode[] = [];\n for (const child of newChildren) {\n const key = extractKey(child);\n if (key !== undefined) {\n result.push({ key, vnode: child });\n }\n }\n return result;\n}\n\n/**\n * Compute LIS (Longest Increasing Subsequence) length for positions\n */\nfunction computeLISLength(positions: number[]): number {\n const tails: number[] = [];\n for (const pos of positions) {\n if (pos === -1) continue;\n let lo = 0;\n let hi = tails.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (tails[mid] < pos) lo = mid + 1;\n else hi = mid;\n }\n if (lo === tails.length) tails.push(pos);\n else tails[lo] = pos;\n }\n return tails.length;\n}\n\n/**\n * Check if any vnode has non-trivial props\n */\nfunction checkVnodesHaveProps(keyedVnodes: KeyedVnode[]): boolean {\n for (const { vnode } of keyedVnodes) {\n if (typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n if (vnodeObj.props && hasNonTrivialProps(vnodeObj.props)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check for prop changes between vnodes and existing elements\n */\nfunction checkVnodePropChanges(\n keyedVnodes: KeyedVnode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): boolean {\n for (const { key, vnode } of keyedVnodes) {\n const el = oldKeyMap?.get(key);\n if (!el || typeof vnode !== 'object' || vnode === null) continue;\n const vnodeObj = vnode as unknown as { props?: Record<string, unknown> };\n const props = vnodeObj.props || {};\n for (const k of Object.keys(props)) {\n if (isIgnoredForPropChanges(k)) continue;\n if (hasPropChanged(el, k, props[k])) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Determine if keyed reorder fast-path should be used\n */\nexport function isKeyedReorderFastPathEligible(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n) {\n const keyedVnodes = extractKeyedVnodes(newChildren);\n const totalKeyed = keyedVnodes.length;\n const newKeyOrder = keyedVnodes.map((kv) => kv.key);\n const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];\n\n // Count moves needed\n let moveCount = 0;\n for (let i = 0; i < newKeyOrder.length; i++) {\n const k = newKeyOrder[i];\n if (i >= oldKeyOrder.length || oldKeyOrder[i] !== k || !oldKeyMap?.has(k)) {\n moveCount++;\n }\n }\n\n // Check move threshold triggers\n const FAST_MOVE_THRESHOLD_ABS = 64;\n const FAST_MOVE_THRESHOLD_REL = 0.1;\n const cheapMoveTrigger =\n totalKeyed >= 128 &&\n oldKeyOrder.length > 0 &&\n moveCount >\n Math.max(\n FAST_MOVE_THRESHOLD_ABS,\n Math.floor(totalKeyed * FAST_MOVE_THRESHOLD_REL)\n );\n\n // Compute LIS trigger for large lists\n let lisTrigger = false;\n let lisLen = 0;\n if (totalKeyed >= 128) {\n const parentChildren = Array.from(parent.children);\n const positions = keyedVnodes.map(({ key }) => {\n const el = oldKeyMap?.get(key);\n return el?.parentElement === parent ? parentChildren.indexOf(el) : -1;\n });\n lisLen = computeLISLength(positions);\n lisTrigger = lisLen < Math.floor(totalKeyed * 0.5);\n }\n\n // Check for props that would prevent fast-path\n const hasPropsPresent = checkVnodesHaveProps(keyedVnodes);\n const hasPropChanges = checkVnodePropChanges(keyedVnodes, oldKeyMap);\n\n const useFastPath =\n (cheapMoveTrigger || lisTrigger) && !hasPropChanges && !hasPropsPresent;\n\n return {\n useFastPath,\n totalKeyed,\n moveCount,\n lisLen,\n hasPropChanges,\n } as const;\n}\n","/**\n * JSX type definitions\n *\n * These define the canonical JSX element shape used by:\n * - jsx-runtime\n * - jsx-dev-runtime\n * - Slot / cloneElement\n * - the reconciler\n */\n\nimport type { Props } from '../shared/types';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n /** Internal element marker (optional for plain vnode objects) */\n $$typeof?: symbol;\n\n /** Element type: string, component, Fragment, etc */\n type: unknown;\n\n /** Props bag */\n props: Props;\n\n /** Optional key (normalized by runtime) */\n key?: string | number | null;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace JSX {\n // Components must be synchronous\n type Element = JSXElement;\n\n interface IntrinsicElements {\n [elem: string]: Props;\n }\n\n interface ElementAttributesProperty {\n props: Props;\n }\n }\n}\n\nexport {};\n","/**\n * JSX dev runtime\n * Same shape as production runtime, with room for dev warnings.\n */\n\nimport './types';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n $$typeof: symbol;\n type: unknown;\n props: Record<string, unknown>;\n key: string | number | null;\n}\n\nexport function jsxDEV(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n): JSXElement {\n return {\n $$typeof: ELEMENT_TYPE,\n type,\n props: props ?? {},\n key: key ?? null,\n };\n}\n\n// Production-style helpers: alias to the DEV factory for now\nexport function jsx(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n) {\n return jsxDEV(type, props, key);\n}\n\nexport function jsxs(\n type: unknown,\n props: Record<string, unknown> | null,\n key?: string | number\n) {\n return jsxDEV(type, props, key);\n}\n\n// `Fragment` is already exported above.\n","import { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { Fragment } from '../jsx/jsx-runtime';\nimport {\n CONTEXT_FRAME_SYMBOL,\n withContext,\n getCurrentContextFrame,\n ContextFrame,\n} from '../runtime/context';\nimport {\n createComponentInstance,\n renderComponentInline,\n mountInstanceInline,\n getCurrentInstance,\n} from '../runtime/component';\nimport type {\n ComponentInstance,\n ComponentFunction,\n} from '../runtime/component';\nimport {\n cleanupInstanceIfPresent,\n elementListeners,\n removeAllListeners,\n} from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport { keyedElements } from './keyed';\nimport {\n parseEventName,\n getPassiveOptions,\n createWrappedHandler,\n isSkippedProp,\n now,\n recordDOMReplace,\n recordFastPathStats,\n logFastPathDebug,\n} from './utils';\n\ntype ElementWithContext = DOMElement & {\n [CONTEXT_FRAME_SYMBOL]?: ContextFrame;\n __instance?: ComponentInstance;\n};\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event Handler Management\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Add an event listener to an element with tracking\n */\nfunction addTrackedListener(\n el: Element,\n eventName: string,\n handler: EventListener\n): void {\n const wrappedHandler = createWrappedHandler(handler, true);\n const options = getPassiveOptions(eventName);\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: handler,\n options,\n });\n}\n\n/**\n * Apply attributes and event listeners to an element from props\n */\nfunction applyPropsToElement(\n el: Element,\n props: Record<string, unknown>,\n tagName: string\n): void {\n for (const key in props) {\n const value = props[key];\n if (isSkippedProp(key)) continue;\n if (value === undefined || value === null || value === false) continue;\n\n const eventName = parseEventName(key);\n if (eventName) {\n addTrackedListener(el, eventName, value as EventListener);\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n applyFormControlProp(el, key, value, tagName);\n } else {\n el.setAttribute(key, String(value));\n }\n }\n}\n\n/**\n * Apply value/checked props to form controls\n */\nfunction applyFormControlProp(\n el: Element,\n key: string,\n value: unknown,\n tagName: string\n): void {\n const tag = tagName.toLowerCase();\n if (key === 'value') {\n if (tag === 'input' || tag === 'textarea' || tag === 'select') {\n (el as HTMLInputElement & Props).value = String(value);\n el.setAttribute('value', String(value));\n } else {\n el.setAttribute('value', String(value));\n }\n } else if (key === 'checked') {\n if (tag === 'input') {\n (el as HTMLInputElement & Props).checked = Boolean(value);\n el.setAttribute('checked', String(Boolean(value)));\n } else {\n el.setAttribute('checked', String(Boolean(value)));\n }\n }\n}\n\n/**\n * Materialize vnode key as data-key attribute\n */\nfunction materializeKey(\n el: Element,\n vnode: DOMElement,\n props: Record<string, unknown>\n): void {\n const vnodeKey = vnode.key ?? props?.key;\n if (vnodeKey !== undefined) {\n el.setAttribute('data-key', String(vnodeKey));\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Dynamic List Warnings\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Warn about missing keys on dynamic lists (dev only)\n */\nfunction warnMissingKeys(children: unknown[]): void {\n if (process.env.NODE_ENV === 'production') return;\n\n let hasElements = false;\n let hasKeys = false;\n\n for (const item of children) {\n if (typeof item === 'object' && item !== null && 'type' in item) {\n hasElements = true;\n const rawKey =\n (item as DOMElement).key ??\n ((item as DOMElement).props as Record<string, unknown> | undefined)\n ?.key;\n if (rawKey !== undefined) {\n hasKeys = true;\n break;\n }\n }\n }\n\n if (hasElements && !hasKeys) {\n try {\n const inst = getCurrentInstance();\n const name = inst?.fn?.name || '<anonymous>';\n logger.warn(\n `Missing keys on dynamic lists in ${name}. Each child in a list should have a unique \"key\" prop.`\n );\n } catch {\n logger.warn(\n 'Missing keys on dynamic lists. Each child in a list should have a unique \"key\" prop.'\n );\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// DOM Node Creation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Create a DOM node from a VNode\n */\nexport function createDOMNode(node: unknown): Node | null {\n // SSR guard: don't attempt DOM ops when document is unavailable\n if (!IS_DOM_AVAILABLE) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[Askr] createDOMNode called in non-DOM environment');\n } catch {\n // ignore\n }\n }\n return null;\n }\n\n // Fast paths for primitives (most common)\n if (typeof node === 'string') {\n return document.createTextNode(node);\n }\n if (typeof node === 'number') {\n return document.createTextNode(String(node));\n }\n\n // Null/undefined/false\n if (!node) {\n return null;\n }\n\n // Array (fragment) - batch all at once\n if (Array.isArray(node)) {\n const fragment = document.createDocumentFragment();\n for (const child of node) {\n const dom = createDOMNode(child);\n if (dom) fragment.appendChild(dom);\n }\n return fragment;\n }\n\n // Element or Component\n if (typeof node === 'object' && node !== null && 'type' in node) {\n const type = (node as DOMElement).type;\n const props = ((node as DOMElement).props || {}) as Record<string, unknown>;\n\n // Intrinsic element (string type)\n if (typeof type === 'string') {\n return createIntrinsicElement(node as DOMElement, type, props);\n }\n\n // Component (function type) - inline execution\n if (typeof type === 'function') {\n return createComponentElement(node as ElementWithContext, type, props);\n }\n\n // Fragment support\n if (\n typeof type === 'symbol' &&\n (type === Fragment || String(type) === 'Symbol(Fragment)')\n ) {\n return createFragmentElement(node as DOMElement, props);\n }\n }\n\n return null;\n}\n\n/**\n * Create an intrinsic DOM element (div, span, etc.)\n */\nfunction createIntrinsicElement(\n node: DOMElement,\n type: string,\n props: Record<string, unknown>\n): Element {\n const el = document.createElement(type);\n\n // Materialize key into DOM attribute\n materializeKey(el, node, props);\n\n // Apply props/attributes\n applyPropsToElement(el, props, type);\n\n // Add children\n const children = props.children || node.children;\n if (children) {\n if (Array.isArray(children)) {\n warnMissingKeys(children);\n for (const child of children) {\n const dom = createDOMNode(child);\n if (dom) el.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n }\n }\n\n return el;\n}\n\n/**\n * Create element from a component function\n */\nfunction createComponentElement(\n node: ElementWithContext,\n type: (props: Props) => unknown,\n props: Record<string, unknown>\n): Node {\n // Check if this vnode has a marked context frame\n const frame = node[CONTEXT_FRAME_SYMBOL];\n const snapshot = frame || getCurrentContextFrame();\n\n const componentFn = type as (props: Props) => unknown;\n const isAsync = componentFn.constructor.name === 'AsyncFunction';\n\n if (isAsync) {\n throw new Error(\n 'Async components are not supported. Use resource() for async work.'\n );\n }\n\n // Ensure there is a persistent instance object attached to this vnode\n let childInstance = node.__instance;\n if (!childInstance) {\n childInstance = createComponentInstance(\n `comp-${Math.random().toString(36).slice(2, 7)}`,\n componentFn as ComponentFunction,\n props || {},\n null\n );\n node.__instance = childInstance;\n }\n\n if (snapshot) {\n childInstance.ownerFrame = snapshot;\n }\n\n const result = withContext(snapshot, () =>\n renderComponentInline(childInstance)\n );\n\n if (result instanceof Promise) {\n throw new Error(\n 'Async components are not supported. Components must return synchronously.'\n );\n }\n\n const dom = withContext(snapshot, () => createDOMNode(result));\n\n if (dom instanceof Element) {\n mountInstanceInline(childInstance, dom);\n return dom;\n }\n\n // For null/undefined returns, use a comment placeholder that can be replaced\n // when the component re-renders with actual content. This is necessary for\n // portals and other components that may initially return null but later have content.\n if (!dom) {\n const placeholder = document.createComment('');\n // Store reference so we can find and replace it on re-render\n childInstance._placeholder = placeholder;\n childInstance.mounted = true;\n // Ensure notifyUpdate is set so the component can be re-rendered when content appears\n childInstance.notifyUpdate = childInstance._enqueueRun!;\n return placeholder;\n }\n\n // For non-Element returns (Text nodes or DocumentFragment), wrap in host\n const host = document.createElement('div');\n host.appendChild(dom);\n mountInstanceInline(childInstance, host);\n return host;\n}\n\n/**\n * Create a document fragment from Fragment vnode\n */\nfunction createFragmentElement(\n node: DOMElement,\n props: Record<string, unknown>\n): DocumentFragment {\n const fragment = document.createDocumentFragment();\n const children = props.children || node.children;\n if (children) {\n if (Array.isArray(children)) {\n for (const child of children) {\n const dom = createDOMNode(child);\n if (dom) fragment.appendChild(dom);\n }\n } else {\n const dom = createDOMNode(children);\n if (dom) fragment.appendChild(dom);\n }\n }\n return fragment;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Element Updates\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Update an existing element's attributes and children from vnode\n */\nexport function updateElementFromVnode(\n el: Element,\n vnode: VNode,\n updateChildren = true\n): void {\n if (!_isDOMElement(vnode)) {\n return;\n }\n\n const props = (vnode.props || {}) as Record<string, unknown>;\n\n // Ensure key is materialized\n materializeKey(el, vnode, props);\n\n // Diff and update event listeners and other attributes\n const existingListeners = elementListeners.get(el);\n const desiredEventNames = new Set<string>();\n\n for (const key in props) {\n const value = props[key];\n if (isSkippedProp(key)) continue;\n\n const eventName = parseEventName(key);\n\n // Handle removal cases\n if (value === undefined || value === null || value === false) {\n if (key === 'class' || key === 'className') {\n el.className = '';\n } else if (eventName && existingListeners?.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n if (entry.options !== undefined) {\n el.removeEventListener(eventName, entry.handler, entry.options);\n } else {\n el.removeEventListener(eventName, entry.handler);\n }\n existingListeners.delete(eventName);\n } else {\n el.removeAttribute(key);\n }\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Record<string, unknown>)[key] = value;\n } else if (eventName) {\n desiredEventNames.add(eventName);\n\n const existing = existingListeners?.get(eventName);\n // If handler reference unchanged, keep existing wrapped handler\n if (existing && existing.original === value) {\n continue;\n }\n\n // Remove old handler if present\n if (existing) {\n el.removeEventListener(eventName, existing.handler);\n }\n\n // Add new handler\n const wrappedHandler = createWrappedHandler(\n value as EventListener,\n false\n );\n const options = getPassiveOptions(eventName);\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n options,\n });\n } else {\n el.setAttribute(key, String(value));\n }\n }\n\n // Remove any remaining listeners not desired by current props\n if (existingListeners) {\n for (const eventName of existingListeners.keys()) {\n if (!desiredEventNames.has(eventName)) {\n const entry = existingListeners.get(eventName)!;\n el.removeEventListener(eventName, entry.handler);\n existingListeners.delete(eventName);\n }\n }\n if (existingListeners.size === 0) elementListeners.delete(el);\n }\n\n // Update children\n if (updateChildren) {\n const children =\n vnode.children || (props.children as VNode | VNode[] | undefined);\n updateElementChildren(el, children);\n }\n}\n\nexport function updateElementChildren(\n el: Element,\n children: VNode | VNode[] | undefined\n): void {\n if (!children) {\n el.textContent = '';\n return;\n }\n\n if (\n !Array.isArray(children) &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = String(children);\n } else {\n el.textContent = String(children);\n }\n return;\n }\n\n if (Array.isArray(children)) {\n updateUnkeyedChildren(el, children as unknown[]);\n return;\n }\n\n el.textContent = '';\n const dom = createDOMNode(children);\n if (dom) el.appendChild(dom);\n}\n\nexport function updateUnkeyedChildren(\n parent: Element,\n newChildren: unknown[]\n): void {\n const existing = Array.from(parent.children);\n\n // Special case: if we have a single text/number child and the parent has a single text node,\n // update the text node in place to preserve identity\n if (\n newChildren.length === 1 &&\n existing.length === 0 &&\n parent.childNodes.length === 1\n ) {\n const firstNewChild = newChildren[0];\n const firstExisting = parent.firstChild;\n if (\n (typeof firstNewChild === 'string' ||\n typeof firstNewChild === 'number') &&\n firstExisting?.nodeType === 3 // Text node\n ) {\n (firstExisting as Text).data = String(firstNewChild);\n return;\n }\n }\n\n // If there are only text nodes (no element children), clear before updating\n if (existing.length === 0 && parent.childNodes.length > 0) {\n parent.textContent = '';\n }\n const max = Math.max(existing.length, newChildren.length);\n\n for (let i = 0; i < max; i++) {\n const current = existing[i];\n const next = newChildren[i];\n\n // Remove extra existing children\n if (next === undefined && current) {\n // Clean up any component instance mounted on this node\n cleanupInstanceIfPresent(current);\n current.remove();\n continue;\n }\n\n // Append new children beyond existing length\n if (!current && next !== undefined) {\n const dom = createDOMNode(next);\n if (dom) parent.appendChild(dom);\n continue;\n }\n\n if (!current || next === undefined) continue;\n\n // Update existing element based on next vnode/primitive\n if (typeof next === 'string' || typeof next === 'number') {\n current.textContent = String(next);\n } else if (_isDOMElement(next)) {\n if (typeof next.type === 'string') {\n // If element type matches, update in place; otherwise replace\n if (current.tagName.toLowerCase() === next.type.toLowerCase()) {\n updateElementFromVnode(current, next);\n } else {\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Non-string types: replace conservatively\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n } else {\n // Fallback for other types: replace\n const dom = createDOMNode(next);\n if (dom) {\n if (current instanceof Element) removeAllListeners(current);\n cleanupInstanceIfPresent(current);\n parent.replaceChild(dom, current);\n }\n }\n }\n}\n\n/**\n * Positional update for keyed lists where keys changed en-masse but structure\n * (element tags and simple text children) remains identical. This updates\n * text content in-place and remaps the `data-key` attribute to the new key so\n * subsequent updates can find elements by their data-key.\n */\nexport function performBulkPositionalKeyedTextUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n) {\n const total = keyedVnodes.length;\n let reused = 0;\n let updatedKeys = 0;\n const t0 = now();\n\n for (let i = 0; i < total; i++) {\n const { key, vnode } = keyedVnodes[i];\n const ch = parent.children[i] as Element | undefined;\n\n if (\n ch &&\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'string'\n ) {\n const vnodeType = (vnode as DOMElement).type as string;\n\n if (ch.tagName.toLowerCase() === vnodeType.toLowerCase()) {\n const children =\n (vnode as DOMElement).children ||\n (vnode as DOMElement).props?.children;\n\n logFastPathDebug('positional idx', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n chChildNodes: ch.childNodes.length,\n childrenType: Array.isArray(children) ? 'array' : typeof children,\n });\n\n updateTextContent(ch, children);\n setDataKey(ch, key, () => updatedKeys++);\n reused++;\n continue;\n } else {\n logFastPathDebug('positional tag mismatch', i, {\n chTag: ch.tagName.toLowerCase(),\n vnodeType,\n });\n }\n } else {\n logFastPathDebug('positional missing or invalid', i, { ch: !!ch });\n }\n\n // Fallback: replace the node at position i\n replaceNodeAtPosition(parent, i, vnode);\n }\n\n const t = now() - t0;\n updateKeyedElementsMap(parent, keyedVnodes);\n\n const stats = { n: total, reused, updatedKeys, t } as const;\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n return stats;\n}\n\n/** Update text content of element from children prop */\nfunction updateTextContent(el: Element, children: unknown): void {\n if (typeof children === 'string' || typeof children === 'number') {\n setTextNodeData(el, String(children));\n } else if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n setTextNodeData(el, String(children[0]));\n } else {\n updateElementFromVnode(el, el as unknown as VNode);\n }\n}\n\n/** Set text node data or textContent */\nfunction setTextNodeData(el: Element, text: string): void {\n if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {\n (el.firstChild as Text).data = text;\n } else {\n el.textContent = text;\n }\n}\n\n/** Set data-key attribute with counter callback */\nfunction setDataKey(\n el: Element,\n key: string | number,\n onSet: () => void\n): void {\n try {\n el.setAttribute('data-key', String(key));\n onSet();\n } catch {\n // Ignore errors setting data-key\n }\n}\n\n/** Replace node at position with new vnode */\nfunction replaceNodeAtPosition(\n parent: Element,\n index: number,\n vnode: VNode\n): void {\n const dom = createDOMNode(vnode);\n if (dom) {\n const existing = parent.children[index];\n if (existing) {\n cleanupInstanceIfPresent(existing);\n parent.replaceChild(dom, existing);\n } else {\n parent.appendChild(dom);\n }\n }\n}\n\n/** Update keyed elements map after bulk operation */\nfunction updateKeyedElementsMap(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): void {\n try {\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const k = keyedVnodes[i].key;\n const ch = parent.children[i] as Element | undefined;\n if (ch) newKeyMap.set(k, ch);\n }\n keyedElements.set(parent, newKeyMap);\n } catch {\n // Ignore errors updating key map\n }\n}\n\nexport function performBulkTextReplace(parent: Element, newChildren: VNode[]) {\n const t0 = now();\n const existing = Array.from(parent.childNodes);\n const finalNodes: Node[] = [];\n let reused = 0;\n let created = 0;\n\n for (let i = 0; i < newChildren.length; i++) {\n const result = processChildNode(newChildren[i], existing[i], finalNodes);\n if (result === 'reused') reused++;\n else if (result === 'created') created++;\n }\n\n const tBuild = now() - t0;\n cleanupRemovedNodes(parent, finalNodes);\n const tCommit = commitBulkReplace(parent, finalNodes);\n\n // Clear keyed map for unkeyed path\n keyedElements.delete(parent);\n\n const stats = {\n n: newChildren.length,\n reused,\n created,\n tBuild,\n tCommit,\n } as const;\n recordBulkTextStats(stats);\n\n return stats;\n}\n\n/** Process a single child vnode for bulk replace */\nfunction processChildNode(\n vnode: VNode,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' | 'skipped' {\n if (typeof vnode === 'string' || typeof vnode === 'number') {\n return processTextVnode(String(vnode), existingNode, finalNodes);\n }\n\n if (typeof vnode === 'object' && vnode !== null && 'type' in vnode) {\n return processElementVnode(vnode, existingNode, finalNodes);\n }\n\n return 'skipped';\n}\n\n/** Process text vnode */\nfunction processTextVnode(\n text: string,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' {\n if (existingNode && existingNode.nodeType === 3) {\n (existingNode as Text).data = text;\n finalNodes.push(existingNode);\n return 'reused';\n }\n finalNodes.push(document.createTextNode(text));\n return 'created';\n}\n\n/** Process element vnode */\nfunction processElementVnode(\n vnode: VNode,\n existingNode: ChildNode | undefined,\n finalNodes: Node[]\n): 'reused' | 'created' | 'skipped' {\n const vnodeObj = vnode as unknown as { type?: unknown };\n\n if (typeof vnodeObj.type === 'string') {\n const tag = vnodeObj.type;\n if (\n existingNode &&\n existingNode.nodeType === 1 &&\n (existingNode as Element).tagName.toLowerCase() === tag.toLowerCase()\n ) {\n updateElementFromVnode(existingNode as Element, vnode);\n finalNodes.push(existingNode);\n return 'reused';\n }\n }\n\n const dom = createDOMNode(vnode);\n if (dom) {\n finalNodes.push(dom);\n return 'created';\n }\n return 'skipped';\n}\n\n/** Clean up nodes that will be removed */\nfunction cleanupRemovedNodes(parent: Element, keepNodes: Node[]): void {\n try {\n const toRemove = Array.from(parent.childNodes).filter(\n (n) => !keepNodes.includes(n)\n );\n for (const n of toRemove) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch {\n // Ignore cleanup errors\n }\n}\n\n/** Commit bulk replace with fragment */\nfunction commitBulkReplace(parent: Element, nodes: Node[]): number {\n const fragStart = Date.now();\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < nodes.length; i++) {\n fragment.appendChild(nodes[i]);\n }\n recordDOMReplace('bulk-text-replace');\n parent.replaceChildren(fragment);\n return Date.now() - fragStart;\n}\n\n/** Record bulk text fast-path stats */\nfunction recordBulkTextStats(stats: {\n n: number;\n reused: number;\n created: number;\n tBuild: number;\n tCommit: number;\n}): void {\n try {\n __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkTextFastpathHits');\n } catch {\n // Ignore stats errors\n }\n}\n\n/**\n * Heuristic to detect large bulk text-dominant updates eligible for fast-path.\n * Conditions:\n * - total children >= threshold\n * - majority of children are simple text (string/number) or intrinsic elements\n * with a single primitive child\n * - conservative: avoid when component children or complex shapes present\n */\nexport function isBulkTextFastPathEligible(\n parent: Element,\n newChildren: VNode[]\n) {\n const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;\n const requiredFraction = 0.8;\n\n const total = Array.isArray(newChildren) ? newChildren.length : 0;\n\n if (total < threshold) {\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n reason: 'too-small',\n total,\n threshold,\n });\n return false;\n }\n\n const result = countSimpleChildren(newChildren);\n if (result.componentFound !== undefined) {\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n reason: 'component-child',\n index: result.componentFound,\n });\n return false;\n }\n\n const fraction = result.simple / total;\n const eligible =\n fraction >= requiredFraction && parent.childNodes.length >= total;\n\n recordBulkDiag({\n phase: 'bulk-unkeyed-eligible',\n total,\n simple: result.simple,\n fraction,\n requiredFraction,\n eligible,\n });\n\n return eligible;\n}\n\n/** Count simple children (text/number or simple intrinsic elements) */\nfunction countSimpleChildren(children: VNode[]): {\n simple: number;\n componentFound?: number;\n} {\n let simple = 0;\n\n for (let i = 0; i < children.length; i++) {\n const c = children[i];\n\n if (typeof c === 'string' || typeof c === 'number') {\n simple++;\n continue;\n }\n\n if (typeof c === 'object' && c !== null && 'type' in c) {\n const dv = c as DOMElement;\n\n // Component child - decline fast path\n if (typeof dv.type === 'function') {\n return { simple, componentFound: i };\n }\n\n if (typeof dv.type === 'string' && isSimpleElement(dv)) {\n simple++;\n }\n }\n }\n\n return { simple };\n}\n\n/** Check if element is simple (empty or single text child) */\nfunction isSimpleElement(dv: DOMElement): boolean {\n const children = dv.children || dv.props?.children;\n\n if (!children) return true; // empty element\n\n if (typeof children === 'string' || typeof children === 'number') {\n return true;\n }\n\n if (\n Array.isArray(children) &&\n children.length === 1 &&\n (typeof children[0] === 'string' || typeof children[0] === 'number')\n ) {\n return true;\n }\n\n return false;\n}\n\n/** Record bulk diagnostics */\nfunction recordBulkDiag(data: Record<string, unknown>): void {\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n __ASKR_set('__BULK_DIAG', data);\n } catch {\n // Ignore\n }\n }\n}\n","import type { VNode } from './types';\nimport { createDOMNode } from './dom';\nimport { _reconcilerRecordedParents } from './keyed';\nimport { logger } from '../dev/logger';\nimport { cleanupInstanceIfPresent, removeAllListeners } from './cleanup';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { isSchedulerExecuting } from '../runtime/scheduler';\nimport {\n isBulkCommitActive,\n markFastPathApplied,\n} from '../runtime/fastlane-shared';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Apply the \"renderer\" fast-path: build final node list reusing existing\n// elements by key when possible, then perform a single atomic replaceChildren\n// commit. Returns a new key map when the fast-path is applied, otherwise\n// returns null to indicate the caller should continue with fallback paths.\nexport function applyRendererFastPath(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap?: Map<string | number, Element>,\n unkeyedVnodes?: VNode[]\n): Map<string | number, Element> | null {\n // SSR guard: fast-path is DOM-specific\n if (typeof document === 'undefined') return null;\n\n const totalKeyed = keyedVnodes.length;\n if (totalKeyed === 0 && (!unkeyedVnodes || unkeyedVnodes.length === 0))\n return null;\n\n // Dev invariant: ensure we are executing inside the scheduler/commit flush\n if (!isSchedulerExecuting()) {\n logger.warn(\n '[Askr][FASTPATH][DEV] Fast-path reconciliation invoked outside scheduler execution'\n );\n }\n\n // Choose lookup strategy depending on size (linear scan for small lists)\n let parentChildrenArr: Element[] | undefined;\n let localOldKeyMap: Map<string | number, Element> | undefined;\n\n if (totalKeyed <= 20) {\n try {\n const pc = parent.children;\n parentChildrenArr = new Array(pc.length);\n for (let i = 0; i < pc.length; i++)\n parentChildrenArr[i] = pc[i] as Element;\n } catch (e) {\n parentChildrenArr = undefined;\n void e;\n }\n } else {\n localOldKeyMap = new Map<string | number, Element>();\n try {\n const parentChildren = Array.from(parent.children);\n for (let i = 0; i < parentChildren.length; i++) {\n const ch = parentChildren[i] as Element;\n const k = ch.getAttribute('data-key');\n if (k !== null) {\n localOldKeyMap.set(k, ch);\n const n = Number(k);\n if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);\n }\n }\n } catch (e) {\n localOldKeyMap = undefined;\n void e;\n }\n }\n\n const finalNodes: Node[] = [];\n let mapLookups = 0;\n let createdNodes = 0;\n let reusedCount = 0;\n\n for (let i = 0; i < keyedVnodes.length; i++) {\n const { key, vnode } = keyedVnodes[i];\n mapLookups++;\n\n let el: Element | undefined;\n if (totalKeyed <= 20 && parentChildrenArr) {\n const ks = String(key);\n for (let j = 0; j < parentChildrenArr.length; j++) {\n const ch = parentChildrenArr[j];\n const k = ch.getAttribute('data-key');\n if (k !== null && (k === ks || Number(k) === (key as number))) {\n el = ch;\n break;\n }\n }\n if (!el) el = oldKeyMap?.get(key);\n } else {\n el = localOldKeyMap?.get(key as string | number) ?? oldKeyMap?.get(key);\n }\n\n if (el) {\n finalNodes.push(el);\n reusedCount++;\n } else {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Add unkeyed nodes (detached as well)\n if (unkeyedVnodes && unkeyedVnodes.length) {\n for (const vnode of unkeyedVnodes) {\n const newEl = createDOMNode(vnode);\n if (newEl) {\n finalNodes.push(newEl);\n createdNodes++;\n }\n }\n }\n\n // Atomic commit\n try {\n const tFragmentStart = Date.now();\n const fragment = document.createDocumentFragment();\n let fragmentAppendCount = 0;\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n fragmentAppendCount++;\n }\n\n // Pre-cleanup: remove component instances that will be removed by replaceChildren\n try {\n const existing = Array.from(parent.childNodes);\n // Only cleanup nodes that are *not* part of the finalNodes list so we don't\n // remove listeners from elements we're reusing (critical invariant)\n const toRemove = existing.filter((n) => !finalNodes.includes(n));\n for (const n of toRemove) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch (e) {\n void e;\n }\n\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set('__LAST_DOM_REPLACE_STACK_FASTPATH', new Error().stack);\n } catch (e) {\n void e;\n }\n\n parent.replaceChildren(fragment);\n\n // Record that we performed exactly one DOM commit.\n try {\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n } catch (e) {\n void e;\n }\n\n // If a runtime bulk commit is active, mark this parent as fast-path applied.\n try {\n if (isBulkCommitActive()) markFastPathApplied(parent);\n } catch (e) {\n void e;\n }\n\n // Phase: bookkeeping - populate newKeyMap\n const newKeyMap = new Map<string | number, Element>();\n for (let i = 0; i < keyedVnodes.length; i++) {\n const key = keyedVnodes[i].key;\n const node = finalNodes[i];\n if (node instanceof Element) newKeyMap.set(key, node as Element);\n }\n\n // Dev tracing\n try {\n const stats = {\n n: totalKeyed,\n moves: 0,\n lisLen: 0,\n t_lookup: 0,\n t_fragment: Date.now() - tFragmentStart,\n t_commit: 0,\n t_bookkeeping: 0,\n fragmentAppendCount,\n mapLookups,\n createdNodes,\n reusedCount,\n } as const;\n if (typeof globalThis !== 'undefined') {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_REUSED', reusedCount > 0);\n __ASKR_incCounter('fastpathHistoryPush');\n }\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH]',\n JSON.stringify({ n: totalKeyed, createdNodes, reusedCount })\n );\n }\n } catch (e) {\n void e;\n }\n\n // Record that reconciler recorded stats for this parent in this pass\n try {\n _reconcilerRecordedParents.add(parent);\n } catch (e) {\n void e;\n }\n\n return newKeyMap;\n } catch (e) {\n void e;\n return null;\n }\n}\n","import type { VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n performBulkPositionalKeyedTextUpdate,\n} from './dom';\nimport {\n keyedElements,\n _reconcilerRecordedParents,\n isKeyedReorderFastPathEligible,\n} from './keyed';\nimport { removeAllListeners, cleanupInstanceIfPresent } from './cleanup';\nimport { isBulkCommitActive } from '../runtime/fastlane-shared';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { applyRendererFastPath } from './fastpath';\nimport { logger } from '../dev/logger';\nimport {\n extractKey,\n checkPropChanges,\n recordFastPathStats,\n recordDOMReplace,\n} from './utils';\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\n// Helper type for narrowings\ntype VnodeObj = VNode & { type?: unknown; props?: Record<string, unknown> };\n\nexport function reconcileKeyedChildren(\n parent: Element,\n newChildren: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n logReconcileDebug(newChildren);\n\n const { keyedVnodes, unkeyedVnodes } = partitionChildren(newChildren);\n\n // Try fast paths first\n const fastPathResult = tryFastPaths(\n parent,\n newChildren,\n keyedVnodes,\n unkeyedVnodes,\n oldKeyMap\n );\n if (fastPathResult) return fastPathResult;\n\n // Full reconciliation\n return performFullReconciliation(parent, newChildren, keyedVnodes, oldKeyMap);\n}\n\n/** Log reconcile debug info */\nfunction logReconcileDebug(newChildren: VNode[]): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn(\n '[Askr][RECONCILE] reconcileKeyedChildren newChildren sample',\n {\n sample: (newChildren && newChildren.length && newChildren[0]) || null,\n len: newChildren.length,\n }\n );\n } catch {\n // Ignore\n }\n }\n}\n\n/** Partition children into keyed and unkeyed */\nfunction partitionChildren(newChildren: VNode[]): {\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>;\n unkeyedVnodes: VNode[];\n} {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n const unkeyedVnodes: VNode[] = [];\n\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const key = extractKey(child);\n if (key !== undefined) {\n keyedVnodes.push({ key, vnode: child });\n } else {\n unkeyedVnodes.push(child);\n }\n }\n\n return { keyedVnodes, unkeyedVnodes };\n}\n\n/** Try fast paths before full reconciliation */\nfunction tryFastPaths(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n unkeyedVnodes: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n try {\n // Try renderer fast-path for large keyed reorder-only updates\n const rendererResult = tryRendererFastPath(\n parent,\n newChildren,\n keyedVnodes,\n unkeyedVnodes,\n oldKeyMap\n );\n if (rendererResult) return rendererResult;\n\n // Try positional bulk update for medium-sized lists\n const positionalResult = tryPositionalBulkUpdate(parent, keyedVnodes);\n if (positionalResult) return positionalResult;\n } catch {\n // Fall through to full reconciliation\n }\n\n return null;\n}\n\n/** Try renderer fast-path */\nfunction tryRendererFastPath(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n unkeyedVnodes: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> | null {\n const decision = isKeyedReorderFastPathEligible(\n parent,\n newChildren,\n oldKeyMap\n );\n\n if (\n (decision.useFastPath && keyedVnodes.length >= 128) ||\n isBulkCommitActive()\n ) {\n try {\n const map = applyRendererFastPath(\n parent,\n keyedVnodes,\n oldKeyMap,\n unkeyedVnodes\n );\n if (map) {\n keyedElements.set(parent, map);\n return map;\n }\n } catch {\n // Fall through\n }\n }\n\n return null;\n}\n\n/** Try positional bulk update for medium-sized lists */\nfunction tryPositionalBulkUpdate(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): Map<string | number, Element> | null {\n const total = keyedVnodes.length;\n if (total < 10) return null;\n\n const matchCount = countPositionalMatches(parent, keyedVnodes);\n\n logPositionalCheck(total, matchCount, parent.children.length);\n\n // Require high positional match fraction\n if (matchCount / total < 0.9) return null;\n\n // Check for prop changes that would prevent positional update\n if (hasPositionalPropChanges(parent, keyedVnodes)) return null;\n\n // Perform positional update\n try {\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n recordFastPathStats(stats, 'bulkKeyedPositionalHits');\n\n rebuildKeyedMap(parent);\n return keyedElements.get(parent) as Map<string | number, Element>;\n } catch {\n return null;\n }\n}\n\n/** Count how many vnodes match parent children by position and tag */\nfunction countPositionalMatches(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): number {\n let matchCount = 0;\n\n try {\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n if (!vnode || typeof vnode !== 'object' || typeof vnode.type !== 'string')\n continue;\n\n const el = parent.children[i] as Element | undefined;\n if (!el) continue;\n\n if (el.tagName.toLowerCase() === String(vnode.type).toLowerCase()) {\n matchCount++;\n }\n }\n } catch {\n // Ignore\n }\n\n return matchCount;\n}\n\n/** Log positional check debug info */\nfunction logPositionalCheck(\n total: number,\n matchCount: number,\n parentChildren: number\n): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[Askr][FASTPATH] positional check', {\n total,\n matchCount,\n parentChildren,\n });\n } catch {\n // Ignore\n }\n }\n}\n\n/** Check if positional prop changes would prevent bulk update */\nfunction hasPositionalPropChanges(\n parent: Element,\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>\n): boolean {\n try {\n for (let i = 0; i < keyedVnodes.length; i++) {\n const vnode = keyedVnodes[i].vnode as VnodeObj;\n const el = parent.children[i] as Element | undefined;\n if (!el || !vnode || typeof vnode !== 'object') continue;\n\n if (checkPropChanges(el, vnode.props || {})) {\n return true;\n }\n }\n } catch {\n return true;\n }\n\n return false;\n}\n\n/** Rebuild keyed map from parent children */\nfunction rebuildKeyedMap(parent: Element): void {\n try {\n const map = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n\n for (let i = 0; i < children.length; i++) {\n const el = children[i] as Element;\n const k = el.getAttribute('data-key');\n if (k !== null) {\n map.set(k, el);\n const n = Number(k);\n if (!Number.isNaN(n)) map.set(n, el);\n }\n }\n\n keyedElements.set(parent, map);\n } catch {\n // Ignore\n }\n}\n\n/** Perform full reconciliation when fast paths don't apply */\nfunction performFullReconciliation(\n parent: Element,\n newChildren: VNode[],\n keyedVnodes: Array<{ key: string | number; vnode: VNode }>,\n oldKeyMap: Map<string | number, Element> | undefined\n): Map<string | number, Element> {\n const newKeyMap = new Map<string | number, Element>();\n const finalNodes: Node[] = [];\n const usedOldEls = new WeakSet<Node>();\n\n const resolveOldElOnce = createOldElResolver(parent, oldKeyMap, usedOldEls);\n\n // Positional reconciliation\n for (let i = 0; i < newChildren.length; i++) {\n const child = newChildren[i];\n const node = reconcileSingleChild(\n child,\n i,\n parent,\n resolveOldElOnce,\n usedOldEls,\n newKeyMap\n );\n if (node) finalNodes.push(node);\n }\n\n // SSR guard\n if (typeof document === 'undefined') return newKeyMap;\n\n commitReconciliation(parent, finalNodes);\n keyedElements.delete(parent);\n\n return newKeyMap;\n}\n\n/** Create resolver for finding old elements by key */\nfunction createOldElResolver(\n parent: Element,\n oldKeyMap: Map<string | number, Element> | undefined,\n usedOldEls: WeakSet<Node>\n): (k: string | number) => Element | undefined {\n return (k: string | number) => {\n if (!oldKeyMap) return undefined;\n\n // Fast-path: directly from oldKeyMap\n const direct = oldKeyMap.get(k);\n if (direct && !usedOldEls.has(direct)) {\n usedOldEls.add(direct);\n return direct;\n }\n\n // Try string form\n const s = String(k);\n const byString = oldKeyMap.get(s);\n if (byString && !usedOldEls.has(byString)) {\n usedOldEls.add(byString);\n return byString;\n }\n\n // Try numeric form\n const n = Number(s);\n if (!Number.isNaN(n)) {\n const byNum = oldKeyMap.get(n);\n if (byNum && !usedOldEls.has(byNum)) {\n usedOldEls.add(byNum);\n return byNum;\n }\n }\n\n // Fallback: scan parent children\n return scanForElementByKey(parent, k, s, usedOldEls);\n };\n}\n\n/** Scan parent children for element with matching key */\nfunction scanForElementByKey(\n parent: Element,\n k: string | number,\n keyStr: string,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n try {\n const children = Array.from(parent.children) as Element[];\n for (const ch of children) {\n if (usedOldEls.has(ch)) continue;\n const attr = ch.getAttribute('data-key');\n if (attr === keyStr) {\n usedOldEls.add(ch);\n return ch;\n }\n const numAttr = Number(attr);\n if (!Number.isNaN(numAttr) && numAttr === (k as number)) {\n usedOldEls.add(ch);\n return ch;\n }\n }\n } catch {\n // Ignore\n }\n return undefined;\n}\n\n/** Reconcile a single child */\nfunction reconcileSingleChild(\n child: VNode,\n index: number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n usedOldEls: WeakSet<Node>,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n // Keyed child\n const key = extractKey(child);\n if (key !== undefined) {\n return reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap);\n }\n\n // Unkeyed or primitive child\n return reconcileUnkeyedChild(child, index, parent, usedOldEls);\n}\n\n/** Reconcile a keyed child */\nfunction reconcileKeyedChild(\n child: VNode,\n key: string | number,\n parent: Element,\n resolveOldElOnce: (k: string | number) => Element | undefined,\n newKeyMap: Map<string | number, Element>\n): Node | null {\n const el = resolveOldElOnce(key);\n\n if (el && el.parentElement === parent) {\n updateElementFromVnode(el, child);\n newKeyMap.set(key, el);\n return el;\n }\n\n const dom = createDOMNode(child);\n if (dom) {\n if (dom instanceof Element) newKeyMap.set(key, dom);\n return dom;\n }\n\n return null;\n}\n\n/** Reconcile an unkeyed or primitive child */\nfunction reconcileUnkeyedChild(\n child: VNode,\n index: number,\n parent: Element,\n usedOldEls: WeakSet<Node>\n): Node | null {\n try {\n const existing = parent.children[index] as Element | undefined;\n\n // Primitive child with existing element\n if (\n existing &&\n (typeof child === 'string' || typeof child === 'number') &&\n existing.nodeType === 1\n ) {\n existing.textContent = String(child);\n usedOldEls.add(existing);\n return existing;\n }\n\n // Element child matching existing unkeyed element\n if (canReuseElement(existing, child)) {\n updateElementFromVnode(existing!, child);\n usedOldEls.add(existing!);\n return existing!;\n }\n\n // Try to find available unkeyed element elsewhere\n const avail = findAvailableUnkeyedElement(parent, usedOldEls);\n if (avail) {\n const reuseResult = tryReuseElement(avail, child, usedOldEls);\n if (reuseResult) return reuseResult;\n }\n } catch {\n // Fall through to create new\n }\n\n const dom = createDOMNode(child);\n return dom;\n}\n\n/** Check if existing element can be reused for child */\nfunction canReuseElement(existing: Element | undefined, child: VNode): boolean {\n if (!existing) return false;\n if (typeof child !== 'object' || child === null || !('type' in child))\n return false;\n\n const childObj = child as VnodeObj;\n const hasNoKey =\n existing.getAttribute('data-key') === null ||\n existing.getAttribute('data-key') === undefined;\n\n return (\n hasNoKey &&\n typeof childObj.type === 'string' &&\n existing.tagName.toLowerCase() === String(childObj.type).toLowerCase()\n );\n}\n\n/** Find available unkeyed element in parent */\nfunction findAvailableUnkeyedElement(\n parent: Element,\n usedOldEls: WeakSet<Node>\n): Element | undefined {\n return Array.from(parent.children).find(\n (ch) => !usedOldEls.has(ch) && ch.getAttribute('data-key') === null\n );\n}\n\n/** Try to reuse available element for child */\nfunction tryReuseElement(\n avail: Element,\n child: VNode,\n usedOldEls: WeakSet<Node>\n): Node | null {\n if (typeof child === 'string' || typeof child === 'number') {\n avail.textContent = String(child);\n usedOldEls.add(avail);\n return avail;\n }\n\n if (typeof child === 'object' && child !== null && 'type' in child) {\n const childObj = child as VnodeObj;\n if (\n typeof childObj.type === 'string' &&\n avail.tagName.toLowerCase() === String(childObj.type).toLowerCase()\n ) {\n updateElementFromVnode(avail, child);\n usedOldEls.add(avail);\n return avail;\n }\n }\n\n return null;\n}\n\n/** Commit reconciliation by replacing parent children */\nfunction commitReconciliation(parent: Element, finalNodes: Node[]): void {\n const fragment = document.createDocumentFragment();\n for (let i = 0; i < finalNodes.length; i++) {\n fragment.appendChild(finalNodes[i]);\n }\n\n // Cleanup existing nodes\n try {\n const existing = Array.from(parent.childNodes);\n for (const n of existing) {\n if (n instanceof Element) removeAllListeners(n);\n cleanupInstanceIfPresent(n);\n }\n } catch {\n // Ignore\n }\n\n recordDOMReplace('reconcile');\n parent.replaceChildren(fragment);\n}\n","import { globalScheduler } from '../runtime/scheduler';\nimport { logger } from '../dev/logger';\nimport type { Props } from '../shared/types';\nimport { elementListeners } from './cleanup';\nimport { keyedElements } from './keyed';\nimport { reconcileKeyedChildren } from './reconcile';\nimport { _isDOMElement, type DOMElement, type VNode } from './types';\nimport {\n createDOMNode,\n updateElementFromVnode,\n updateUnkeyedChildren,\n performBulkPositionalKeyedTextUpdate,\n performBulkTextReplace,\n isBulkTextFastPathEligible,\n} from './dom';\nimport { __ASKR_set, __ASKR_incCounter } from './diag';\nimport { Fragment } from '../jsx/types';\n\n/**\n * Internal marker for component-owned DOM ranges\n * Allows efficient partial DOM updates instead of clearing entire target\n */\ninterface DOMRange {\n start: Node; // Start marker (comment node)\n end: Node; // End marker (comment node)\n}\n\nexport const IS_DOM_AVAILABLE = typeof document !== 'undefined';\n\nconst domRanges = new WeakMap<object, DOMRange>();\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helper Types & Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface SimpleTextResult {\n isSimple: true;\n text: string;\n}\n\ninterface NotSimpleTextResult {\n isSimple: false;\n text?: undefined;\n}\n\ntype TextCheckResult = SimpleTextResult | NotSimpleTextResult;\n\n/**\n * Check if vnode children represent a simple text value\n */\nfunction checkSimpleText(vnodeChildren: unknown): TextCheckResult {\n if (!Array.isArray(vnodeChildren)) {\n if (\n typeof vnodeChildren === 'string' ||\n typeof vnodeChildren === 'number'\n ) {\n return { isSimple: true, text: String(vnodeChildren) };\n }\n } else if (vnodeChildren.length === 1) {\n const child = vnodeChildren[0];\n if (typeof child === 'string' || typeof child === 'number') {\n return { isSimple: true, text: String(child) };\n }\n }\n return { isSimple: false };\n}\n\n/**\n * Try to update a single text node in place\n * Returns true if update was performed, false otherwise\n */\nfunction tryUpdateTextInPlace(element: Element, text: string): boolean {\n if (\n element.childNodes.length === 1 &&\n element.firstChild?.nodeType === 3 // TEXT_NODE\n ) {\n (element.firstChild as Text).data = text;\n return true;\n }\n return false;\n}\n\n/**\n * Build a key map from existing DOM children\n */\nfunction buildKeyMapFromDOM(parent: Element): Map<string | number, Element> {\n const keyMap = new Map<string | number, Element>();\n const children = Array.from(parent.children);\n for (const child of children) {\n const k = child.getAttribute('data-key');\n if (k !== null) {\n keyMap.set(k, child);\n const n = Number(k);\n if (!Number.isNaN(n)) keyMap.set(n, child);\n }\n }\n return keyMap;\n}\n\n/**\n * Get or initialize key map for an element\n */\nfunction getOrBuildKeyMap(\n parent: Element\n): Map<string | number, Element> | undefined {\n let keyMap = keyedElements.get(parent);\n if (!keyMap) {\n keyMap = buildKeyMapFromDOM(parent);\n if (keyMap.size > 0) {\n keyedElements.set(parent, keyMap);\n }\n }\n return keyMap.size > 0 ? keyMap : undefined;\n}\n\n/**\n * Check if children array contains keyed elements\n */\nfunction hasKeyedChildren(children: unknown[]): boolean {\n return children.some(\n (child) => typeof child === 'object' && child !== null && 'key' in child\n );\n}\n\n/**\n * Track bulk text fast-path stats (dev only)\n */\nfunction trackBulkTextStats(\n stats: ReturnType<typeof performBulkTextReplace>\n): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n __ASKR_set('__LAST_BULK_TEXT_FASTPATH_STATS', stats);\n __ASKR_incCounter('bulkTextHits');\n } catch {\n // ignore\n }\n }\n}\n\n/**\n * Track bulk text miss (dev only)\n */\nfunction trackBulkTextMiss(): void {\n if (process.env.NODE_ENV !== 'production') {\n try {\n __ASKR_incCounter('bulkTextMisses');\n } catch {\n // ignore\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Child Reconciliation Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Reconcile keyed children with optional forced bulk path\n */\nfunction reconcileKeyed(\n parent: Element,\n children: VNode[],\n oldKeyMap: Map<string | number, Element> | undefined\n): void {\n // Optional forced positional bulk path for large keyed lists\n if (process.env.ASKR_FORCE_BULK_POSREUSE === '1') {\n const result = tryForcedBulkKeyedPath(parent, children);\n if (result) return;\n }\n\n // Standard keyed reconciliation\n const newKeyMap = reconcileKeyedChildren(parent, children, oldKeyMap);\n keyedElements.set(parent, newKeyMap);\n}\n\n/**\n * Try the forced bulk keyed positional path\n * Returns true if applied, false to fall back to normal reconciliation\n */\nfunction tryForcedBulkKeyedPath(parent: Element, children: VNode[]): boolean {\n try {\n const keyedVnodes: Array<{ key: string | number; vnode: VNode }> = [];\n for (const child of children) {\n if (_isDOMElement(child) && (child as DOMElement).key !== undefined) {\n keyedVnodes.push({\n key: (child as DOMElement).key as string | number,\n vnode: child,\n });\n }\n }\n\n // Only apply when all children are keyed and count matches\n if (keyedVnodes.length === 0 || keyedVnodes.length !== children.length) {\n return false;\n }\n\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)'\n );\n }\n\n const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);\n\n if (\n process.env.NODE_ENV !== 'production' ||\n process.env.ASKR_FASTPATH_DEBUG === '1'\n ) {\n try {\n __ASKR_set('__LAST_FASTPATH_STATS', stats);\n __ASKR_set('__LAST_FASTPATH_COMMIT_COUNT', 1);\n __ASKR_incCounter('bulkKeyedPositionalForced');\n } catch {\n // ignore\n }\n }\n\n // Rebuild keyed map from DOM\n const newMap = buildKeyMapFromDOM(parent);\n keyedElements.set(parent, newMap);\n return true;\n } catch (err) {\n if (\n process.env.ASKR_FASTPATH_DEBUG === '1' ||\n process.env.ASKR_FASTPATH_DEBUG === 'true'\n ) {\n logger.warn(\n '[Askr][FASTPATH] forced bulk path failed, falling back',\n err\n );\n }\n return false;\n }\n}\n\n/**\n * Reconcile unkeyed children, using bulk fast-path when eligible\n */\nfunction reconcileUnkeyed(parent: Element, children: VNode[]): void {\n if (isBulkTextFastPathEligible(parent, children)) {\n const stats = performBulkTextReplace(parent, children);\n trackBulkTextStats(stats);\n } else {\n trackBulkTextMiss();\n updateUnkeyedChildren(parent, children);\n }\n keyedElements.delete(parent);\n}\n\n/**\n * Update element children (handles keyed, unkeyed, and non-array cases)\n */\nfunction updateElementChildren(element: Element, vnodeChildren: unknown): void {\n if (!vnodeChildren) {\n element.textContent = '';\n keyedElements.delete(element);\n return;\n }\n\n if (!Array.isArray(vnodeChildren)) {\n element.textContent = '';\n const dom = createDOMNode(vnodeChildren);\n if (dom) element.appendChild(dom);\n keyedElements.delete(element);\n return;\n }\n\n if (hasKeyedChildren(vnodeChildren)) {\n const oldKeyMap = getOrBuildKeyMap(element);\n try {\n reconcileKeyed(element, vnodeChildren, oldKeyMap);\n } catch {\n // Fall back on error\n const newKeyMap = reconcileKeyedChildren(\n element,\n vnodeChildren,\n oldKeyMap\n );\n keyedElements.set(element, newKeyMap);\n }\n } else {\n reconcileUnkeyed(element, vnodeChildren);\n }\n}\n\n/**\n * Perform a smart update on an existing element\n * Tries text-in-place update first, then full child reconciliation\n */\nfunction smartUpdateElement(element: Element, vnode: DOMElement): void {\n const vnodeChildren = vnode.children || vnode.props?.children;\n const textCheck = checkSimpleText(vnodeChildren);\n\n if (textCheck.isSimple && tryUpdateTextInPlace(element, textCheck.text)) {\n // Text updated in place, nothing more to do for children\n } else {\n updateElementChildren(element, vnodeChildren);\n }\n\n updateElementFromVnode(element, vnode, false);\n}\n\n/**\n * Process Fragment children with smart updates for each child\n */\nfunction processFragmentChildren(target: Element, childArray: unknown[]): void {\n const existingChildren = Array.from(target.children) as Element[];\n\n for (let i = 0; i < childArray.length; i++) {\n const childVnode = childArray[i];\n const existingNode = existingChildren[i];\n\n // Apply the same smart update logic as the single-element case\n if (\n existingNode &&\n _isDOMElement(childVnode) &&\n typeof (childVnode as DOMElement).type === 'string' &&\n existingNode.tagName.toLowerCase() ===\n ((childVnode as DOMElement).type as string).toLowerCase()\n ) {\n // Same element type - do smart update\n smartUpdateElement(existingNode, childVnode as DOMElement);\n continue;\n }\n\n // Different type or no existing node - replace\n const newDom = createDOMNode(childVnode);\n if (newDom) {\n if (existingNode) {\n target.replaceChild(newDom, existingNode);\n } else {\n target.appendChild(newDom);\n }\n }\n }\n\n // Remove extra children\n while (target.children.length > childArray.length) {\n target.removeChild(target.lastChild!);\n }\n}\n\n/**\n * Create a wrapped event handler that integrates with the scheduler\n */\nfunction createWrappedEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n globalScheduler.setInHandler(true);\n try {\n handler(event);\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n } finally {\n globalScheduler.setInHandler(false);\n }\n };\n}\n\n/**\n * Apply props/attributes to an element (used for first render with keyed children)\n */\nfunction applyPropsToElement(el: Element, props: Props): void {\n for (const [key, value] of Object.entries(props)) {\n if (key === 'children' || key === 'key') continue;\n if (value === undefined || value === null || value === false) continue;\n\n if (key.startsWith('on') && key.length > 2) {\n const eventName =\n key.slice(2).charAt(0).toLowerCase() + key.slice(3).toLowerCase();\n\n const wrappedHandler = createWrappedEventHandler(value as EventListener);\n\n const options: boolean | AddEventListenerOptions | undefined =\n eventName === 'wheel' ||\n eventName === 'scroll' ||\n eventName.startsWith('touch')\n ? { passive: true }\n : undefined;\n\n if (options !== undefined) {\n el.addEventListener(eventName, wrappedHandler, options);\n } else {\n el.addEventListener(eventName, wrappedHandler);\n }\n\n if (!elementListeners.has(el)) {\n elementListeners.set(el, new Map());\n }\n elementListeners.get(el)!.set(eventName, {\n handler: wrappedHandler,\n original: value as EventListener,\n options,\n });\n continue;\n }\n\n if (key === 'class' || key === 'className') {\n el.className = String(value);\n } else if (key === 'value' || key === 'checked') {\n (el as HTMLElement & Props)[key] = value;\n } else {\n el.setAttribute(key, String(value));\n }\n }\n}\n\n/**\n * Try to handle first render of element with keyed children\n * Returns true if handled, false to fall back to default rendering\n */\nfunction tryFirstRenderKeyedChildren(\n target: Element,\n vnode: DOMElement\n): boolean {\n const children = vnode.children;\n if (!Array.isArray(children) || !hasKeyedChildren(children)) {\n return false;\n }\n\n const el = document.createElement(vnode.type as string);\n target.appendChild(el);\n\n applyPropsToElement(el, vnode.props || {});\n\n const newKeyMap = reconcileKeyedChildren(el, children, undefined);\n keyedElements.set(el, newKeyMap);\n return true;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Fragment Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Check if a vnode is a Fragment\n */\nfunction isFragment(vnode: unknown): vnode is DOMElement {\n return (\n _isDOMElement(vnode) &&\n typeof (vnode as DOMElement).type === 'symbol' &&\n ((vnode as DOMElement).type === Fragment ||\n String((vnode as DOMElement).type) === 'Symbol(askr.fragment)')\n );\n}\n\n/**\n * Unwrap Fragment to get children array\n */\nfunction getFragmentChildren(vnode: DOMElement): unknown[] {\n const fragmentChildren = vnode.props?.children || vnode.children || [];\n return Array.isArray(fragmentChildren)\n ? fragmentChildren\n : [fragmentChildren];\n}\n\nexport function evaluate(\n node: unknown,\n target: Element | null,\n context?: object\n): void {\n if (!target) return;\n // SSR guard: avoid DOM ops when not in a browser-like environment\n if (typeof document === 'undefined') {\n if (process.env.NODE_ENV !== 'production') {\n try {\n // Keep this lightweight and non-throwing so test harnesses and SSR\n // imports don't crash at runtime; callers should avoid calling\n // `evaluate` in SSR, but we make it safe as a no-op.\n console.warn('[Askr] evaluate() called in non-DOM environment; no-op.');\n } catch (e) {\n void e;\n }\n }\n return;\n }\n // Debug tracing to help understand why initial mounts sometimes don't\n // result in DOM mutations during tests.\n\n // If context provided, use component-owned DOM range (only replace that range)\n if (context && domRanges.has(context)) {\n const range = domRanges.get(context)!;\n // Remove all nodes between start and end markers\n let current = range.start.nextSibling;\n while (current && current !== range.end) {\n const next = current.nextSibling;\n current.remove();\n current = next;\n }\n // Append new DOM before end marker\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, range.end);\n }\n } else if (context) {\n // First render with context: create range markers\n const start = document.createComment('component-start');\n const end = document.createComment('component-end');\n target.appendChild(start);\n target.appendChild(end);\n domRanges.set(context, { start, end });\n // Render into the range\n const dom = createDOMNode(node);\n if (dom) {\n target.insertBefore(dom, end);\n }\n } else {\n // Root render (no context): smart update strategy\n // If target has exactly one child of the same element type as the vnode,\n // reuse the element and just update its content.\n // This preserves the element reference and event handlers across renders.\n\n let vnode = node;\n\n // If vnode is a Fragment, unwrap it to get the actual content for the smart update path.\n // Fragments become invisible in the DOM - their children are placed directly in the parent.\n // So for smart updates, we need to compare against the Fragment's children, not the Fragment itself.\n if (isFragment(vnode)) {\n const childArray = getFragmentChildren(vnode as DOMElement);\n // If Fragment has exactly one child that's an element, unwrap to that child\n // This allows the smart update path to match against it\n if (\n childArray.length === 1 &&\n _isDOMElement(childArray[0]) &&\n typeof (childArray[0] as DOMElement).type === 'string'\n ) {\n vnode = childArray[0];\n } else {\n // Fragment with multiple children - process each child with full smart update logic\n processFragmentChildren(target, childArray);\n return;\n }\n }\n\n const firstChild = target.children[0] as Element | undefined;\n\n if (\n firstChild &&\n _isDOMElement(vnode) &&\n typeof vnode.type === 'string' &&\n firstChild.tagName.toLowerCase() === vnode.type.toLowerCase()\n ) {\n // Reuse the existing element - it's the same type\n smartUpdateElement(firstChild, vnode as DOMElement);\n } else {\n // Clear and rebuild (first render or structure changed)\n target.textContent = '';\n\n // Check if this is an element with keyed children even on first render\n if (\n _isDOMElement(vnode) &&\n typeof vnode.type === 'string' &&\n tryFirstRenderKeyedChildren(target, vnode as DOMElement)\n ) {\n return;\n }\n\n // Default: create whole tree\n const dom = createDOMNode(vnode);\n if (dom) {\n target.appendChild(dom);\n }\n }\n }\n}\n\nexport function clearDOMRange(context: object): void {\n domRanges.delete(context);\n}\n","// Renderer barrel entrypoint.\n// Keep this file small: re-export the public surface and attach the\n// runtime fast-lane bridge on import.\n\nexport * from './types';\nexport * from './cleanup';\nexport * from './keyed';\nexport * from './dom';\nexport { evaluate, clearDOMRange } from './evaluate';\n\nimport { evaluate as _evaluate } from './evaluate';\nimport { isKeyedReorderFastPathEligible, getKeyMapForElement } from './keyed';\n\n// Expose minimal renderer bridge for runtime fast-lane to call `evaluate`\nif (typeof globalThis !== 'undefined') {\n const _g = globalThis as Record<string, unknown>;\n _g.__ASKR_RENDERER = {\n evaluate: _evaluate,\n isKeyedReorderFastPathEligible,\n getKeyMapForElement,\n };\n}\n","/**\n * Component instance lifecycle management\n * Internal only — users never see this\n */\n\nimport { type State } from './state';\nimport { globalScheduler } from './scheduler';\nimport type { JSXElement } from '../jsx/types';\nimport type { Props } from '../shared/types';\nimport {\n // withContext is the sole primitive for context restoration\n withContext,\n type ContextFrame,\n} from './context';\nimport { logger } from '../dev/logger';\nimport { __ASKR_incCounter, __ASKR_set } from '../renderer/diag';\n\nexport type ComponentFunction = (\n props: Props,\n context?: { signal: AbortSignal }\n) => JSXElement | VNode | string | number | null;\n\ntype VNode = {\n type: string;\n props?: Props;\n children?: (string | VNode | null | undefined | false)[];\n};\n\nexport interface ComponentInstance {\n id: string;\n fn: ComponentFunction;\n props: Props;\n target: Element | null;\n mounted: boolean;\n abortController: AbortController; // Per-component abort lifecycle\n ssr?: boolean; // Set to true for SSR temporary instances\n // Opt-in strict cleanup mode: when true cleanup errors are aggregated and re-thrown\n cleanupStrict?: boolean;\n stateValues: State<unknown>[]; // Persistent state storage across renders\n evaluationGeneration: number; // Prevents stale async evaluation completions\n notifyUpdate: (() => void) | null; // Callback for state updates (persisted on instance)\n // Internal: prebound helpers to avoid per-update closures (allocation hot-path)\n _pendingFlushTask?: () => void; // Clears hasPendingUpdate and triggers notifyUpdate\n _pendingRunTask?: () => void; // Clears hasPendingUpdate and runs component\n _enqueueRun?: () => void; // Batches run requests and enqueues _pendingRunTask\n stateIndexCheck: number; // Track state indices to catch conditional calls\n expectedStateIndices: number[]; // Expected sequence of state indices (frozen after first render)\n firstRenderComplete: boolean; // Flag to detect transition from first to subsequent renders\n mountOperations: Array<\n () => void | (() => void) | Promise<void | (() => void)>\n >; // Operations to run when component mounts\n cleanupFns: Array<() => void>; // Cleanup functions to run on unmount\n hasPendingUpdate: boolean; // Flag to batch state updates (coalescing)\n ownerFrame: ContextFrame | null; // Provider chain for this component (set by Scope, never overwritten)\n isRoot?: boolean;\n\n // Render-tracking for precise subscriptions (internal)\n _currentRenderToken?: number; // Token for the in-progress render (set before render)\n lastRenderToken?: number; // Token of the last *committed* render\n _pendingReadStates?: Set<State<unknown>>; // States read during the in-progress render\n _lastReadStates?: Set<State<unknown>>; // States read during the last committed render\n\n // Placeholder for null-returning components. When a component initially returns\n // null, we create a comment placeholder so updates can replace it with content.\n _placeholder?: Comment;\n}\n\nexport function createComponentInstance(\n id: string,\n fn: ComponentFunction,\n props: Props,\n target: Element | null\n): ComponentInstance {\n const instance: ComponentInstance = {\n id,\n fn,\n props,\n target,\n mounted: false,\n abortController: new AbortController(), // Create per-component\n stateValues: [],\n evaluationGeneration: 0,\n notifyUpdate: null,\n // Prebound helpers (initialized below) to avoid per-update allocations\n _pendingFlushTask: undefined,\n _pendingRunTask: undefined,\n _enqueueRun: undefined,\n stateIndexCheck: -1,\n expectedStateIndices: [],\n firstRenderComplete: false,\n mountOperations: [],\n cleanupFns: [],\n hasPendingUpdate: false,\n ownerFrame: null, // Will be set by renderer when vnode is marked\n ssr: false,\n cleanupStrict: false,\n isRoot: false,\n\n // Render-tracking (for precise state subscriptions)\n _currentRenderToken: undefined,\n lastRenderToken: 0,\n _pendingReadStates: new Set(),\n _lastReadStates: new Set(),\n };\n\n // Initialize prebound helper tasks once per instance to avoid allocations\n instance._pendingRunTask = () => {\n // Clear pending flag when the run task executes\n instance.hasPendingUpdate = false;\n // Execute component run (will set up notifyUpdate before render)\n runComponent(instance);\n };\n\n instance._enqueueRun = () => {\n if (!instance.hasPendingUpdate) {\n instance.hasPendingUpdate = true;\n // Enqueue single run task (coalesces multiple writes)\n globalScheduler.enqueue(instance._pendingRunTask!);\n }\n };\n\n instance._pendingFlushTask = () => {\n // Called by state.set() when we want to flush a pending update\n instance.hasPendingUpdate = false;\n // Trigger a run via enqueue helper — this will schedule the component run\n instance._enqueueRun?.();\n };\n\n return instance;\n}\n\nlet currentInstance: ComponentInstance | null = null;\nlet stateIndex = 0;\n\n// Export for state.ts to access\nexport function getCurrentComponentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n// Export for SSR to set temporary instance\nexport function setCurrentComponentInstance(\n instance: ComponentInstance | null\n): void {\n currentInstance = instance;\n}\n\n/**\n * Register a mount operation that will run after the component is mounted\n * Used by operations (task, on, timer, etc) to execute after render completes\n */\nimport { isBulkCommitActive } from './fastlane-shared';\nimport { evaluate, cleanupInstancesUnder } from '../renderer';\n\nexport function registerMountOperation(\n operation: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const instance = getCurrentComponentInstance();\n if (instance) {\n // If we're in bulk-commit fast lane, registering mount operations is a\n // violation of the fast-lane preconditions. Throw in dev, otherwise ignore\n // silently in production (we must avoid scheduling work during bulk commit).\n if (isBulkCommitActive()) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n 'registerMountOperation called during bulk commit fast-lane'\n );\n }\n return;\n }\n instance.mountOperations.push(operation);\n }\n}\n\n/**\n * Execute all mount operations for a component\n * These run after the component is rendered and mounted to the DOM\n */\nfunction executeMountOperations(instance: ComponentInstance): void {\n // Only execute mount operations for root app instance. Child component\n // operations are currently registered but should not be executed (per\n // contract tests). They remain registered for cleanup purposes.\n if (!instance.isRoot) return;\n\n for (const operation of instance.mountOperations) {\n const result = operation();\n if (result instanceof Promise) {\n result.then((cleanup) => {\n if (typeof cleanup === 'function') {\n instance.cleanupFns.push(cleanup);\n }\n });\n } else if (typeof result === 'function') {\n instance.cleanupFns.push(result);\n }\n }\n // Clear the operations array so they don't run again on subsequent renders\n instance.mountOperations = [];\n}\n\nexport function mountInstanceInline(\n instance: ComponentInstance,\n target: Element | null\n): void {\n instance.target = target;\n // Record backref on host element so renderer can clean up when the\n // node is removed. Avoids leaks if the node is detached or replaced.\n try {\n if (target instanceof Element)\n (\n target as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n } catch (err) {\n void err;\n }\n\n // Ensure notifyUpdate is available for async resource completions that may\n // try to trigger re-render. This mirrors the setup in executeComponent().\n // Use prebound enqueue helper to avoid allocating a new closure\n instance.notifyUpdate = instance._enqueueRun!;\n\n const wasFirstMount = !instance.mounted;\n instance.mounted = true;\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n}\n\n/**\n * Run a component synchronously: execute function, handle result\n * This is the internal workhorse that manages async continuations and generation tracking.\n * Must always be called through the scheduler.\n *\n * ACTOR INVARIANT: This function is enqueued as a task, never called directly.\n */\nlet _globalRenderCounter = 0;\n\nfunction runComponent(instance: ComponentInstance): void {\n // CRITICAL: Ensure notifyUpdate is available for state.set() calls during this render.\n // This must be set before executeComponentSync() runs, not after.\n // Use prebound enqueue helper to avoid allocating per-render closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Assign a token for this in-progress render and start a fresh pending-read set\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n\n // Atomic rendering: capture DOM state for rollback on error\n const domSnapshot = instance.target ? instance.target.innerHTML : '';\n\n const result = executeComponentSync(instance);\n if (result instanceof Promise) {\n // Async components are not supported. Components must be synchronous and\n // must not return a Promise from their render function.\n throw new Error(\n 'Async components are not supported. Components must be synchronous.'\n );\n } else {\n // Try runtime fast-lane synchronously; if it activates we do not enqueue\n // follow-up work and the commit happens atomically in this task.\n // (Runtime fast-lane has conservative preconditions.)\n const fastlaneBridge = (\n globalThis as {\n __ASKR_FASTLANE?: {\n tryRuntimeFastLaneSync?: (\n instance: unknown,\n result: unknown\n ) => boolean;\n };\n }\n ).__ASKR_FASTLANE;\n try {\n const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);\n if (used) return;\n } catch (err) {\n // If invariant check failed in dev, surface the error; otherwise fall back\n if (process.env.NODE_ENV !== 'production') throw err;\n }\n\n // Fallback: enqueue the render/commit normally\n globalScheduler.enqueue(() => {\n // Handle placeholder-based updates: when a component initially returned null,\n // we created a comment placeholder. If it now has content, we need to create\n // a host element and replace the placeholder.\n if (!instance.target && instance._placeholder) {\n // Component previously returned null (has placeholder), check if now has content\n if (result === null || result === undefined) {\n // Still null - nothing to do, keep placeholder\n finalizeReadSubscriptions(instance);\n return;\n }\n\n // Has content now - need to create DOM and replace placeholder\n const placeholder = instance._placeholder;\n const parent = placeholder.parentNode;\n if (!parent) {\n // Placeholder was removed from DOM - can't render\n logger.warn(\n '[Askr] placeholder no longer in DOM, cannot render component'\n );\n return;\n }\n\n // Create a new host element for the content\n const host = document.createElement('div');\n\n // Set up instance for normal updates\n const oldInstance = currentInstance;\n currentInstance = instance;\n try {\n evaluate(result, host);\n\n // Replace placeholder with host\n parent.replaceChild(host, placeholder);\n\n // Set up instance for future updates\n instance.target = host;\n instance._placeholder = undefined;\n (\n host as Element & { __ASKR_INSTANCE?: ComponentInstance }\n ).__ASKR_INSTANCE = instance;\n\n finalizeReadSubscriptions(instance);\n } finally {\n currentInstance = oldInstance;\n }\n return;\n }\n\n if (instance.target) {\n // Keep `oldChildren` in the outer scope so rollback handlers can\n // reference the original node list even if the inner try block\n // throws. This preserves listeners and instance backrefs on rollback.\n let oldChildren: Node[] = [];\n try {\n const wasFirstMount = !instance.mounted;\n // Ensure nested component executions during evaluation have access to\n // the current component instance. This allows nested components to\n // call `state()`, `resource()`, and other runtime helpers which\n // rely on `getCurrentComponentInstance()` being available.\n const oldInstance = currentInstance;\n currentInstance = instance;\n // Capture snapshot of current children (by reference) so we can\n // restore them on render failure without losing event listeners or\n // instance attachments.\n oldChildren = Array.from(instance.target.childNodes);\n\n try {\n evaluate(result, instance.target);\n } catch (e) {\n // If evaluation failed, attempt to cleanup any partially-added nodes\n // and restore the old children to preserve listeners and instances.\n try {\n const newChildren = Array.from(instance.target.childNodes);\n for (const n of newChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up failed commit children:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n // Restore original children by re-inserting the old node references\n // this preserves attached listeners and instance backrefs.\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n throw e;\n } finally {\n currentInstance = oldInstance;\n }\n\n // Commit succeeded — finalize recorded state reads so subscriptions reflect\n // the last *committed* render. This updates per-state reader maps\n // deterministically and synchronously with the commit.\n finalizeReadSubscriptions(instance);\n\n instance.mounted = true;\n // Execute mount operations after first mount (do NOT run these with\n // currentInstance set - they may perform state mutations/registrations)\n if (wasFirstMount && instance.mountOperations.length > 0) {\n executeMountOperations(instance);\n }\n } catch (renderError) {\n // Atomic rendering: rollback on render error. Attempt non-lossy restore of\n // original child node references to preserve listeners/instances.\n try {\n const currentChildren = Array.from(instance.target.childNodes);\n for (const n of currentChildren) {\n try {\n cleanupInstancesUnder(n);\n } catch (err) {\n logger.warn(\n '[Askr] error cleaning up partial children during rollback:',\n err\n );\n }\n }\n } catch (_err) {\n void _err;\n }\n\n try {\n try {\n __ASKR_incCounter('__DOM_REPLACE_COUNT');\n __ASKR_set(\n '__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK',\n new Error().stack\n );\n } catch (e) {\n void e;\n }\n instance.target.replaceChildren(...oldChildren);\n } catch {\n // Fallback to innerHTML restore if replaceChildren fails for some reason.\n instance.target.innerHTML = domSnapshot;\n }\n\n throw renderError;\n }\n }\n });\n }\n}\n\n/**\n * Execute a component's render function synchronously.\n * Returns either a vnode/promise immediately (does NOT render).\n * Rendering happens separately through runComponent.\n */\nexport function renderComponentInline(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Ensure inline executions (rendered during parent's evaluate) still\n // receive a render token and have their state reads finalized so\n // subscriptions are correctly recorded. If this function is called\n // as part of a scheduled run, the token will already be set by\n // runComponent and we should not overwrite it.\n const hadToken = instance._currentRenderToken !== undefined;\n const prevToken = instance._currentRenderToken;\n const prevPendingReads = instance._pendingReadStates;\n if (!hadToken) {\n instance._currentRenderToken = ++_globalRenderCounter;\n instance._pendingReadStates = new Set();\n }\n\n try {\n const result = executeComponentSync(instance);\n // If we set the token for inline execution, finalize subscriptions now\n // because the component is effectively committed as part of the parent's\n // synchronous evaluation.\n if (!hadToken) {\n finalizeReadSubscriptions(instance);\n }\n return result;\n } finally {\n // Restore previous token/read states for nested inline render scenarios\n instance._currentRenderToken = prevToken;\n instance._pendingReadStates = prevPendingReads ?? new Set();\n }\n}\n\nfunction executeComponentSync(\n instance: ComponentInstance\n): unknown | Promise<unknown> {\n // Reset state index tracking for this render\n instance.stateIndexCheck = -1;\n\n // Reset read tracking for all existing state\n for (const state of instance.stateValues) {\n if (state) {\n state._hasBeenRead = false;\n }\n }\n\n // Prepare pending read set for this render (reads will be finalized on commit)\n instance._pendingReadStates = new Set();\n\n currentInstance = instance;\n stateIndex = 0;\n\n try {\n // Track render time in dev mode\n const renderStartTime =\n process.env.NODE_ENV !== 'production' ? Date.now() : 0;\n\n // Create context object with abort signal\n const context = {\n signal: instance.abortController.signal,\n };\n\n // Execute component within its owner frame (provider chain).\n // This ensures all context reads see the correct provider values.\n // We create a new execution frame whose parent is the ownerFrame. The\n // `values` map is lazily allocated to avoid per-render Map allocations\n // for components that do not use context.\n const executionFrame: ContextFrame = {\n parent: instance.ownerFrame,\n values: null,\n };\n const result = withContext(executionFrame, () =>\n instance.fn(instance.props, context)\n );\n\n // Check render time\n const renderTime = Date.now() - renderStartTime;\n if (renderTime > 5) {\n // Warn if render takes more than 5ms\n logger.warn(\n `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`\n );\n }\n\n // Mark first render complete after successful execution\n // This enables hook order validation on subsequent renders\n if (!instance.firstRenderComplete) {\n instance.firstRenderComplete = true;\n }\n\n // Check for unused state\n for (let i = 0; i < instance.stateValues.length; i++) {\n const state = instance.stateValues[i];\n if (state && !state._hasBeenRead) {\n try {\n const name = instance.fn?.name || '<anonymous>';\n logger.warn(\n `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`\n );\n } catch {\n logger.warn(\n `[askr] Unused state variable detected. State should be read during render or removed.`\n );\n }\n }\n }\n\n return result;\n } finally {\n // Synchronous path: we did not push a fresh frame, so nothing to pop here.\n currentInstance = null;\n }\n}\n\n/**\n * Public entry point: Execute component with full lifecycle (execute + render)\n * Handles both initial mount and re-execution. Always enqueues through scheduler.\n * Single entry point to avoid lifecycle divergence.\n */\nexport function executeComponent(instance: ComponentInstance): void {\n // Create a fresh abort controller on mount to allow remounting\n // (old one may have been aborted during previous cleanup)\n instance.abortController = new AbortController();\n\n // Setup notifyUpdate callback using prebound helper to avoid per-call closures\n instance.notifyUpdate = instance._enqueueRun!;\n\n // Enqueue the initial component run\n globalScheduler.enqueue(() => runComponent(instance));\n}\n\nexport function getCurrentInstance(): ComponentInstance | null {\n return currentInstance;\n}\n\n/**\n * Get the abort signal for the current component\n * Used to cancel async operations on unmount/navigation\n *\n * The signal is guaranteed to be aborted when:\n * - Component unmounts\n * - Navigation occurs (different route)\n * - Parent is destroyed\n *\n * IMPORTANT: getSignal() must be called during component render execution.\n * It captures the current component instance from context.\n *\n * @returns AbortSignal that will be aborted when component unmounts\n * @throws Error if called outside component execution\n *\n * @example\n * ```ts\n * // ✅ Correct: called during render, used in async operation\n * export async function UserPage({ id }: { id: string }) {\n * const signal = getSignal();\n * const user = await fetch(`/api/users/${id}`, { signal });\n * return <div>{user.name}</div>;\n * }\n *\n * // ✅ Correct: passed to event handler\n * export function Button() {\n * const signal = getSignal();\n * return {\n * type: 'button',\n * props: {\n * onClick: async () => {\n * const data = await fetch(url, { signal });\n * }\n * }\n * };\n * }\n *\n * // ❌ Wrong: called outside component context\n * const signal = getSignal(); // Error: not in component\n * ```\n */\nexport function getSignal(): AbortSignal {\n if (!currentInstance) {\n throw new Error(\n 'getSignal() can only be called during component render execution. ' +\n 'Ensure you are calling this from inside your component function.'\n );\n }\n return currentInstance.abortController.signal;\n}\n\n/**\n * Finalize read subscriptions for an instance after a successful commit.\n * - Update per-state readers map to point to this instance's last committed token\n * - Remove this instance from states it no longer reads\n * This is deterministic and runs synchronously with commit to ensure\n * subscribers are only notified when they actually read a state in their\n * last committed render.\n */\nexport function finalizeReadSubscriptions(instance: ComponentInstance): void {\n const newSet = instance._pendingReadStates ?? new Set();\n const oldSet = instance._lastReadStates ?? new Set();\n const token = instance._currentRenderToken;\n\n if (token === undefined) return;\n\n // Remove subscriptions for states that were read previously but not in this render\n for (const s of oldSet) {\n if (!newSet.has(s)) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n }\n\n // Commit token becomes the authoritative token for this instance's last render\n instance.lastRenderToken = token;\n\n // Record subscriptions for states read during this render\n for (const s of newSet) {\n let readers = (s as State<unknown>)._readers;\n if (!readers) {\n readers = new Map();\n // s is a State object; assign its _readers map\n (s as State<unknown>)._readers = readers;\n }\n readers.set(instance, instance.lastRenderToken ?? 0);\n }\n\n instance._lastReadStates = newSet;\n instance._pendingReadStates = new Set();\n instance._currentRenderToken = undefined;\n}\n\nexport function getNextStateIndex(): number {\n return stateIndex++;\n}\n\n/**\n * Mount a component instance.\n * This is just an alias to executeComponent() to maintain API compatibility.\n * All lifecycle logic is unified in executeComponent().\n */\nexport function mountComponent(instance: ComponentInstance): void {\n executeComponent(instance);\n}\n\n/**\n * Clean up component — abort pending operations\n * Called on unmount or route change\n */\nexport function cleanupComponent(instance: ComponentInstance): void {\n // Execute cleanup functions (from mount effects)\n const cleanupErrors: unknown[] = [];\n for (const cleanup of instance.cleanupFns) {\n try {\n cleanup();\n } catch (err) {\n if (instance.cleanupStrict) {\n cleanupErrors.push(err);\n } else {\n // Preserve previous behavior: log warnings in dev and continue\n if (process.env.NODE_ENV !== 'production') {\n logger.warn('[Askr] cleanup function threw:', err);\n }\n }\n }\n }\n instance.cleanupFns = [];\n if (cleanupErrors.length > 0) {\n // If strict mode, surface all cleanup errors as an AggregateError after attempting all cleanups\n throw new AggregateError(\n cleanupErrors,\n `Cleanup failed for component ${instance.id}`\n );\n }\n\n // Remove deterministic state subscriptions for this instance\n if (instance._lastReadStates) {\n for (const s of instance._lastReadStates) {\n const readers = (s as State<unknown>)._readers;\n if (readers) readers.delete(instance);\n }\n instance._lastReadStates = new Set();\n }\n\n // Abort all pending operations\n instance.abortController.abort();\n\n // Clear update callback to prevent dangling references and stale updates\n instance.notifyUpdate = null;\n\n // Mark instance as unmounted so external tracking (e.g., portal host lists)\n // can deterministically prune stale instances. Not marking this leads to\n // retained \"mounted\" flags across cleanup boundaries which breaks\n // owner selection in the portal fallback.\n instance.mounted = false;\n}\n","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","/**\n * SSR Context Management\n *\n * Provides context for server-side rendering including:\n * - SSRContext: Full context for sink-based streaming SSR\n * - RenderContext: Lightweight context for sync render passes\n */\n\nimport { SSRDataMissingError } from './errors';\n\nexport type SSRData = Record<string, unknown>;\n\n/** Full context for sink-based streaming SSR */\nexport type SSRContext = {\n url: string;\n seed: number;\n data?: SSRData;\n params?: Record<string, string>;\n signal?: AbortSignal;\n};\n\n// Stack-scoped SSRContext for sink-based rendering\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/** Lightweight context for synchronous render passes */\nexport type RenderContext = {\n seed: number;\n};\n\nexport function createRenderContext(seed = 12345): RenderContext {\n return { seed };\n}\n\n// Stack-scoped RenderContext for sync SSR detection\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 — throws a consistent error when async\n * data is encountered during synchronous SSR.\n */\nexport function throwSSRDataMissing(): never {\n throw new SSRDataMissingError();\n}\n\nexport { SSRDataMissingError };\n","/**\n * SSR Data Management\n *\n * Manages render-phase keying for deterministic SSR data lookup.\n * Note: SSR collection/prepass APIs have been removed — SSR is strictly synchronous.\n */\n\nimport 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 render-phase state\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 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// --- Deprecated APIs (throw descriptive errors) ---\n\nconst PREPASS_REMOVED_MSG =\n 'SSR collection/prepass is removed: SSR is strictly synchronous';\n\n/** @deprecated SSR prepass has been removed */\nexport function startCollection(): never {\n throw new Error(`${PREPASS_REMOVED_MSG}; do not call startCollection()`);\n}\n\n/** @deprecated SSR prepass has been removed */\nexport function stopCollection(): ResourcePlan {\n throw new Error(`${PREPASS_REMOVED_MSG}; do not call stopCollection()`);\n}\n\n/** @deprecated SSR prepass has been removed */\nexport function registerResourceIntent(\n _fn: ResourceDescriptor['fn'],\n _deps: unknown[]\n): string {\n throw new Error(\n `${PREPASS_REMOVED_MSG}; resource() no longer registers intents for prepass`\n );\n}\n\n/** @deprecated SSR prepass has been removed */\nexport async function resolvePlan(\n _plan: ResourcePlan\n): Promise<Record<string, unknown>> {\n throw new Error(\n `${PREPASS_REMOVED_MSG}; async resource plans are not supported`\n );\n}\n\n/** @deprecated SSR prepass has been removed */\nexport function collectResources(_opts: {\n url: string;\n routes: SSRRoute[];\n}): ResourcePlan {\n throw new Error(`${PREPASS_REMOVED_MSG}; collectResources is disabled`);\n}\n\n/** @deprecated Alias for resolvePlan */\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 Record<string, unknown>);\n for (const key of Object.keys(obj as Record<string, unknown>)) {\n const value = (obj as Record<string, unknown>)[key];\n if (value && typeof value === 'object') deepFreeze(value);\n }\n }\n return obj;\n}\n\n// Build an immutable query helper from a search string\nfunction makeQuery(search: string): RouteQuery {\n const usp = new URLSearchParams(search || '');\n const mapping = new Map<string, string[]>();\n for (const [k, v] of usp.entries()) {\n const existing = mapping.get(k);\n if (existing) existing.push(v);\n else mapping.set(k, [v]);\n }\n\n const obj: RouteQuery = {\n get(key: string) {\n const arr = mapping.get(key);\n return arr ? arr[0] : null;\n },\n getAll(key: string) {\n const arr = mapping.get(key);\n return arr ? [...arr] : [];\n },\n has(key: string) {\n return mapping.has(key);\n },\n toJSON() {\n const out: Record<string, string | string[]> = {};\n for (const [k, arr] of mapping.entries()) {\n out[k] = arr.length > 1 ? [...arr] : arr[0];\n }\n return out;\n },\n };\n\n return deepFreeze(obj);\n}\n\n// Compute matches by scanning registered routes (public API: getRoutes)\nfunction computeMatches(pathname: string): RouteMatch[] {\n const routesList = getRoutes();\n const matches: Array<{\n pattern: string;\n params: Record<string, string>;\n name?: string;\n namespace?: string;\n specificity: number;\n }> = [];\n\n function getSpecificity(path: string) {\n // Reuse same heuristic as above\n const normalized =\n path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;\n if (normalized === '/*') return 0;\n const segments = normalized.split('/').filter(Boolean);\n let score = 0;\n for (const segment of segments) {\n if (segment.startsWith('{') && segment.endsWith('}')) score += 2;\n else if (segment === '*') score += 1;\n else score += 3;\n }\n return score;\n }\n\n for (const r of routesList) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n matches.push({\n pattern: r.path,\n params: result.params,\n name: (r as { name?: string }).name,\n namespace: r.namespace,\n specificity: getSpecificity(r.path),\n });\n }\n }\n\n matches.sort((a, b) => b.specificity - a.specificity);\n\n return matches.map((m) => ({\n path: m.pattern,\n params: deepFreeze({ ...m.params }),\n name: m.name,\n namespace: m.namespace,\n }));\n}\n\n/**\n * Dual-purpose `route` function:\n * - route() → returns a read-only, deeply frozen RouteSnapshot (render-time)\n * - route(path, handler, namespace?) → registers a route handler (existing semantics)\n */\n// Prevent runtime registrations after the app has started\nlet registrationLocked = false;\n\nexport function lockRouteRegistration(): void {\n registrationLocked = true;\n}\n\n// Internal test helpers\nexport function _lockRouteRegistrationForTests(): void {\n registrationLocked = true;\n}\n\nexport function _unlockRouteRegistrationForTests(): void {\n registrationLocked = false;\n}\n\nexport function route(): RouteSnapshot;\nexport function route(\n path: string,\n handler?: RouteHandler,\n namespace?: string\n): void;\nexport function route(\n path?: string,\n handler?: RouteHandler,\n namespace?: string\n): void | RouteSnapshot {\n // If called with no args, act as render-time accessor\n if (typeof path === 'undefined') {\n // Access the current component instance to ensure route() is only\n // called during render.\n const instance = getCurrentComponentInstance();\n if (!instance) {\n throw new Error(\n 'route() can only be called during component render execution. ' +\n 'Call route() from inside your component function.'\n );\n }\n\n // Determine location source: client window if present; otherwise SSR override\n let pathname = '/';\n let search = '';\n let hash = '';\n\n if (typeof window !== 'undefined' && window.location) {\n pathname = window.location.pathname || '/';\n search = window.location.search || '';\n hash = window.location.hash || '';\n } else if (serverLocation) {\n const parsed = parseLocation(serverLocation);\n pathname = parsed.pathname;\n search = parsed.search;\n hash = parsed.hash;\n }\n\n const params = deepFreeze({\n ...((instance.props as Record<string, string>) || {}),\n });\n const query = makeQuery(search);\n const matches = computeMatches(pathname);\n\n const snapshot: RouteSnapshot = Object.freeze({\n path: pathname,\n params,\n query,\n hash: hash || null,\n matches: Object.freeze(matches),\n });\n\n return snapshot;\n }\n\n // Disallow route registration during SSR render\n const currentInst = getCurrentComponentInstance();\n if (currentInst && currentInst.ssr) {\n throw new Error(\n 'route() cannot be called during SSR rendering. Register routes at module load time instead.'\n );\n }\n\n // Disallow registrations after app startup\n if (registrationLocked) {\n throw new Error(\n 'Route registration is locked after app startup. Register routes at module load time before calling createIsland().'\n );\n }\n\n // Otherwise register a route (backwards compatible behavior)\n if (typeof handler !== 'function') {\n throw new Error(\n 'route(path, handler) requires a function handler that returns a VNode (e.g. () => <Page />). ' +\n 'Passing JSX elements or VNodes directly is not supported.'\n );\n }\n\n const routeObj: Route = { path, handler: handler as RouteHandler, namespace };\n routes.push(routeObj);\n\n // Index by depth (maintains insertion order within depth)\n const depth = getDepth(path);\n\n let depthRoutes = routesByDepth.get(depth);\n if (!depthRoutes) {\n depthRoutes = [];\n routesByDepth.set(depth, depthRoutes);\n }\n\n depthRoutes.push(routeObj);\n\n if (namespace) {\n namespaces.add(namespace);\n }\n}\n\n/**\n * Get all registered routes\n */\nexport function getRoutes(): Route[] {\n return [...routes];\n}\n\n/**\n * Get routes for a specific namespace\n */\nexport function getNamespaceRoutes(namespace: string): Route[] {\n return routes.filter((r) => r.namespace === namespace);\n}\n\n/**\n * Unload all routes from a namespace (for MFE unmounting)\n */\nexport function unloadNamespace(namespace: string): number {\n const before = routes.length;\n\n // Remove from main array\n for (let i = routes.length - 1; i >= 0; i--) {\n if (routes[i].namespace === namespace) {\n const removed = routes[i];\n routes.splice(i, 1);\n\n // Remove from depth index\n const depth = getDepth(removed.path);\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n const idx = depthRoutes.indexOf(removed);\n if (idx >= 0) {\n depthRoutes.splice(idx, 1);\n }\n }\n }\n }\n\n namespaces.delete(namespace);\n return before - routes.length;\n}\n\n/**\n * Clear all registered routes (mainly for testing)\n */\nexport function clearRoutes(): void {\n routes.length = 0;\n namespaces.clear();\n routesByDepth.clear();\n}\n\n/**\n * RouteDescriptor type — used by `registerRoute` for nested descriptors.\n *\n * Note: `registerRouteTree` helper was removed; prefer explicit `route()` registrations.\n */\nexport type RouteDescriptor = {\n path: string;\n handler?: RouteHandler | unknown;\n children?: RouteDescriptor[];\n _isDescriptor?: true;\n};\n\n// `registerRouteTree` was removed — register explicit absolute paths with `route(path, handler)` instead.\n// If you need a helper to register descriptor trees, add a small wrapper in userland that\n// calls `route()` recursively.\n\n// Helper: normalize common handler shapes\n// NOTE: Only function handlers are accepted — passing raw JSX/VNodes at register\n// time is not allowed. This keeps registration data-only and avoids surprising\n// semantics between module-load-time and render-time.\nfunction normalizeHandler(handler: unknown): RouteHandler | undefined {\n if (handler == null) return undefined;\n if (typeof handler === 'function') {\n // Accept both (params) => ... handlers and component functions that take no args / props\n return (params: Record<string, string>, ctx?: { signal?: AbortSignal }) => {\n // Call with params and ctx; component functions can ignore them\n // Allow handler to return JSX element, VNode, Promise, etc.\n // If the function expects only props, passing params is safe (extra args ignored)\n try {\n return handler(params, ctx);\n } catch {\n return handler(params);\n }\n };\n }\n return undefined;\n}\n\n// Register route with flexible handler shapes and optional nested descriptors.\n// Usage patterns supported:\n// - Absolute flat registration: registerRoute('/pages', () => List())\n// - Nested descriptors: registerRoute('/', () => Home(), registerRoute('pages', () => List(), registerRoute('{id}', () => Detail())))\n// Note: child descriptors should use relative paths (no leading '/').\nexport function registerRoute(\n path: string,\n handler?: unknown,\n ...children: Array<RouteDescriptor | undefined>\n): RouteDescriptor {\n const isRelative = !path.startsWith('/');\n\n // Build descriptor that can be used for nesting\n const descriptor: RouteDescriptor = {\n path,\n handler,\n children: children.filter(Boolean) as RouteDescriptor[],\n _isDescriptor: true,\n };\n\n // If path is absolute, perform registration immediately and recurse into children\n if (!isRelative) {\n const normalized = normalizeHandler(handler);\n if (handler != null && !normalized) {\n throw new Error(\n 'registerRoute(path, handler) requires a function handler. Passing JSX elements or VNodes directly is not supported.'\n );\n }\n if (normalized) route(path, normalized);\n\n for (const child of descriptor.children || []) {\n // Compute child full path\n const base = path === '/' ? '' : path.replace(/\\/$/, '');\n const childPath = `${base}/${child.path.replace(/^\\//, '')}`.replace(\n /\\/\\//g,\n '/'\n );\n // Recurse: if child.handler is provided, register it\n if (child.handler) {\n const childNormalized = normalizeHandler(child.handler);\n if (!childNormalized) {\n throw new Error(\n 'registerRoute child handler must be a function. Passing JSX elements directly is not supported.'\n );\n }\n if (childNormalized) route(childPath, childNormalized);\n }\n // Recurse into grandchildren\n if (child.children && child.children.length) {\n // Convert child.children into descriptors and register them\n // Use registerRoute recursively with absolute childPath\n registerRoute(\n childPath,\n null,\n ...(child.children as RouteDescriptor[])\n );\n }\n }\n\n return descriptor;\n }\n\n // If relative, return descriptor for nesting (do not register yet)\n return descriptor;\n}\n\n/**\n * Get all loaded namespaces (MFE identifiers)\n */\nexport function getLoadedNamespaces(): string[] {\n return Array.from(namespaces);\n}\n\n/**\n * Resolve a path to a route handler with optimized lookup\n * Routes are matched by specificity: literals > parameters > wildcards > catch-all\n */\nexport function resolveRoute(pathname: string): ResolvedRoute | null {\n const normalized =\n pathname.endsWith('/') && pathname !== '/'\n ? pathname.slice(0, -1)\n : pathname;\n const depth =\n normalized === '/' ? 0 : normalized.split('/').filter(Boolean).length;\n\n // Collect all matching routes with their specificity\n const candidates: Array<{\n route: Route;\n specificity: number;\n params: Record<string, string>;\n }> = [];\n\n // Try routes at this depth first (most likely match)\n const depthRoutes = routesByDepth.get(depth);\n if (depthRoutes) {\n for (const r of depthRoutes) {\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n }\n\n // Fallback: scan all routes for different depths\n // (handles edge cases like wildcard routes)\n for (const r of routes) {\n // Skip if already checked in depth routes\n if (depthRoutes?.includes(r)) continue;\n\n const result = matchPath(pathname, r.path);\n if (result.matched) {\n candidates.push({\n route: r,\n specificity: getSpecificity(r.path),\n params: result.params,\n });\n }\n }\n\n // Sort by specificity (highest first)\n candidates.sort((a, b) => b.specificity - a.specificity);\n\n // Return most specific match\n if (candidates.length > 0) {\n const best = candidates[0];\n return { handler: best.route.handler, params: best.params };\n }\n\n return null;\n}\n","/**\n * Client-side navigation with History API\n */\n\nimport { resolveRoute, lockRouteRegistration } from './route';\nimport {\n mountComponent,\n cleanupComponent,\n type ComponentInstance,\n} from '../runtime/component';\nimport { logger } from '../dev/logger';\n\n// Global app state for navigation\nlet currentInstance: ComponentInstance | null = null;\n\n/**\n * Register the current app instance (called by createIsland)\n */\nexport function registerAppInstance(\n instance: ComponentInstance,\n _path: string\n): void {\n currentInstance = instance;\n // Lock further route registrations after the app has started — but allow tests to register routes.\n // Enforce only in production to avoid breaking test infra which registers routes dynamically.\n if (process.env.NODE_ENV === 'production') {\n lockRouteRegistration();\n }\n}\n\n/**\n * Navigate to a new path\n * Updates URL, resolves route, and re-mounts app with new handler\n */\nexport function navigate(path: string): void {\n if (typeof window === 'undefined') {\n // SSR context\n return;\n }\n\n // Resolve the new path to a route\n const resolved = resolveRoute(path);\n\n if (!resolved) {\n if (process.env.NODE_ENV !== 'production') {\n logger.warn(`No route found for path: ${path}`);\n }\n return;\n }\n\n // Update browser history\n window.history.pushState({ path }, '', path);\n\n // Re-render with the new route handler and params\n if (currentInstance) {\n // Cleanup previous route (abort pending operations)\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n // It takes params as props and renders the route\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n // Each route navigation starts completely fresh\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for new route\n // Old controller is already aborted; we need a fresh one for async operations\n currentInstance.abortController = new AbortController();\n\n // Re-execute and re-mount component\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Handle browser back/forward buttons\n */\nfunction handlePopState(_event: PopStateEvent): void {\n const path = window.location.pathname;\n\n if (!currentInstance) {\n return;\n }\n\n const resolved = resolveRoute(path);\n\n if (resolved) {\n // Cleanup old component\n cleanupComponent(currentInstance);\n\n // The route handler IS the component function\n currentInstance.fn = resolved.handler as ComponentInstance['fn'];\n currentInstance.props = resolved.params;\n\n // Reset state to prevent leakage from previous route\n currentInstance.stateValues = [];\n currentInstance.expectedStateIndices = [];\n currentInstance.firstRenderComplete = false;\n currentInstance.stateIndexCheck = -1;\n // Increment generation to invalidate pending async evaluations from previous route\n currentInstance.evaluationGeneration++;\n currentInstance.notifyUpdate = null;\n\n // CRITICAL FIX: Create new AbortController for back/forward navigation\n currentInstance.abortController = new AbortController();\n\n mountComponent(currentInstance);\n }\n}\n\n/**\n * Setup popstate listener for browser navigation\n */\nexport function initializeNavigation(): void {\n if (typeof window !== 'undefined') {\n window.addEventListener('popstate', handlePopState);\n }\n}\n\n/**\n * Cleanup navigation listeners\n */\nexport function cleanupNavigation(): void {\n if (typeof window !== 'undefined') {\n window.removeEventListener('popstate', handlePopState);\n }\n}\n","import { ELEMENT_TYPE, JSXElement } from './types';\n\nexport function isElement(value: unknown): value is JSXElement {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as JSXElement).$$typeof === ELEMENT_TYPE\n );\n}\n\nexport function cloneElement(\n element: JSXElement,\n props: Record<string, unknown>\n): JSXElement {\n return {\n ...element,\n props: { ...element.props, ...props },\n };\n}\n","export { Fragment, ELEMENT_TYPE } from './types';\nexport type { JSXElement } from './types';\n\nexport { isElement, cloneElement } from './utils';\n","/**\n * Portal / Host primitive.\n *\n * A portal is a named render slot within the existing tree.\n * It does NOT create a second tree or touch the DOM directly.\n */\n\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { logger } from '../dev/logger';\n\nexport interface Portal<T = unknown> {\n /** Mount point — rendered exactly once */\n (): unknown;\n\n /** Render content into the portal */\n render(props: { children?: T }): unknown;\n}\n\nexport function definePortal<T = unknown>(): Portal<T> {\n // If the runtime primitive isn't installed yet, provide a no-op fallback.\n // Using `typeof createPortalSlot` is safe even if the identifier is not\n // defined at runtime (it returns 'undefined' rather than throwing).\n if (typeof createPortalSlot !== 'function') {\n // Fallback implementation for environments where the runtime primitive\n // isn't available (tests, SSR).\n //\n // Invariants this fallback tries to maintain:\n // - Always use the *current* host instance (update `owner` each render)\n // - Preserve the last `value` written before host mounts and expose it so\n // it can be flushed into a real portal if/when the runtime installs\n // - Schedule `owner.notifyUpdate()` when a host exists so updates are\n // reflected immediately\n // Track all hosts that read the portal so we can deterministically\n // select a single owner and prune stale mounts across islands.\n let hosts: import('../runtime/component').ComponentInstance[] = [];\n let pending: T | undefined;\n\n function HostFallback() {\n // Prune unmounted hosts\n hosts = hosts.filter((h) => h.mounted !== false);\n\n const inst = getCurrentComponentInstance();\n if (inst && !hosts.includes(inst)) hosts.push(inst);\n\n // Owner is the first host that is fully mounted (must be mounted === true)\n // This prevents capturing pre-mount instances which can lead to early-write\n // replay or ghost-toasts. Only a fully-mounted host can be an owner.\n const owner = hosts.find((h) => h.mounted === true) || null;\n\n // If more than one host is mounted at the same time, this is a violation\n // of the portal contract. In dev mode we throw to make the issue explicit.\n const mountedHosts = hosts.filter((h) => h.mounted === true);\n if (mountedHosts.length > 1) {\n // Warn in dev to make multiple mounted hosts visible; do NOT throw\n // because multiple islands mounting is a valid use-case. We assert only\n // that exactly one host may render portal content at a time.\n // Logger will no-op in production, so this check need not be wrapped.\n logger.warn(\n '[Portal] multiple hosts are mounted for same portal; first mounted host will be owner'\n );\n }\n\n // If this reader is not the owner, but a mounted owner exists, warn in dev\n if (inst && owner && owner !== inst) {\n logger.debug(\n '[Portal] non-owner reader detected; only owner renders portal content'\n );\n }\n\n // Dev debug: increment read counter\n /* istanbul ignore if */\n if (process.env.NODE_ENV !== 'production') {\n const ns =\n (globalThis as unknown as { __ASKR__?: Record<string, unknown> })\n .__ASKR__ ||\n ((\n globalThis as unknown as { __ASKR__?: Record<string, unknown> }\n ).__ASKR__ = {} as Record<string, unknown>);\n ns.__PORTAL_READS = ((ns.__PORTAL_READS as number) || 0) + 1;\n }\n\n // Only the owner should render the pending value; other readers see nothing\n /* istanbul ignore if */\n if (\n process.env.NODE_ENV !== 'production' &&\n inst &&\n owner &&\n inst === owner\n ) {\n logger.debug('[Portal] owner read ->', inst.id, 'pending=', pending);\n // Dev diagnostic: record whether the owner instance has an attached DOM target\n const ns =\n (globalThis as unknown as { __ASKR__?: Record<string, unknown> })\n .__ASKR__ ||\n ((\n globalThis as unknown as { __ASKR__?: Record<string, unknown> }\n ).__ASKR__ = {} as Record<string, unknown>);\n ns.__PORTAL_HOST_ATTACHED = !!(inst && inst.target);\n ns.__PORTAL_HOST_ID = inst ? inst.id : undefined;\n }\n return inst === owner ? (pending as unknown) : undefined;\n }\n\n HostFallback.render = function RenderFallback(props: { children?: T }) {\n // Refresh host list and determine current owner\n hosts = hosts.filter((h) => h.mounted !== false);\n // Owner must be fully mounted (mounted === true) to accept writes — this\n // prevents capturing pre-mount instances and avoids replaying early writes.\n const owner = hosts.find((h) => h.mounted === true) || null;\n\n // If no owner exists yet, drop the write (avoid buffering early writes)\n if (!owner) {\n // Logger will no-op in production so we can call directly without wrapping.\n logger.debug(\n '[Portal] fallback.write dropped -> no owner or not mounted',\n props?.children\n );\n return null;\n }\n\n // Update pending value for the live owner\n pending = props.children as T | undefined;\n\n // Record debug write counter in dev so tests can assert writes occurred\n // Logger will no-op in production; keep counter update guarded for dev only\n logger.debug('[Portal] fallback.write ->', pending, 'owner=', owner.id);\n /* istanbul ignore if */\n if (process.env.NODE_ENV !== 'production') {\n const ns =\n (globalThis as unknown as { __ASKR__?: Record<string, unknown> })\n .__ASKR__ ||\n ((\n globalThis as unknown as { __ASKR__?: Record<string, unknown> }\n ).__ASKR__ = {} as Record<string, unknown>);\n ns.__PORTAL_WRITES = ((ns.__PORTAL_WRITES as number) || 0) + 1;\n }\n\n // Schedule an update on the owner so it re-renders\n if (owner && owner.notifyUpdate) {\n if (process.env.NODE_ENV !== 'production')\n logger.debug(\n '[Portal] fallback.write notify ->',\n owner.id,\n !!owner.notifyUpdate\n );\n owner.notifyUpdate();\n }\n return null;\n };\n\n return HostFallback as Portal<T>;\n }\n\n // Runtime-provided slot implementation\n const slot = createPortalSlot<T>();\n\n function PortalHost() {\n return slot.read();\n }\n\n PortalHost.render = function PortalRender(props: { children?: T }) {\n // Logger will no-op in production; keep counter increment guarded for dev-only behavior\n logger.debug('[Portal] write ->', props?.children);\n /* istanbul ignore if */\n if (process.env.NODE_ENV !== 'production') {\n const ns =\n (globalThis as unknown as { __ASKR__?: Record<string, unknown> })\n .__ASKR__ ||\n ((\n globalThis as unknown as { __ASKR__?: Record<string, unknown> }\n ).__ASKR__ = {} as Record<string, unknown>);\n ns.__PORTAL_WRITES = ((ns.__PORTAL_WRITES as number) || 0) + 1;\n }\n slot.write(props.children);\n return null;\n };\n\n return PortalHost as Portal<T>;\n}\n\n// Default portal instance: lazily created wrapper so runtime primitive is not\n// invoked during module initialization (avoids ReferenceError when runtime\n// slot primitive is not yet installed).\nlet _defaultPortal: Portal<unknown> | undefined;\nlet _defaultPortalIsFallback = false;\n\n/**\n * Reset the default portal state. Used by tests to ensure isolation.\n * @internal\n */\nexport function _resetDefaultPortal(): void {\n _defaultPortal = undefined;\n _defaultPortalIsFallback = false;\n}\n\nfunction ensureDefaultPortal(): Portal<unknown> {\n // If a portal hasn't been initialized yet, create a real portal if the\n // runtime primitive exists; otherwise create a fallback. If a fallback\n // was previously created and the runtime primitive becomes available\n // later, replace the fallback with a real portal on first use.\n logger.debug(\n '[DefaultPortal] ensureDefaultPortal _defaultPortalIsFallback=',\n _defaultPortalIsFallback,\n 'createPortalSlot=',\n typeof createPortalSlot === 'function'\n );\n\n if (!_defaultPortal) {\n if (typeof createPortalSlot === 'function') {\n _defaultPortal = definePortal<unknown>();\n _defaultPortalIsFallback = false;\n logger.debug('[DefaultPortal] created real portal');\n } else {\n // Create a fallback via definePortal so it uses the same owner/pending\n // semantics as the non-default portals (keeps runtime and fallback\n // behavior consistent).\n _defaultPortal = definePortal<unknown>();\n _defaultPortalIsFallback = true;\n logger.debug('[DefaultPortal] created fallback portal');\n }\n return _defaultPortal;\n }\n\n // Replace fallback with real portal once runtime primitive becomes available\n // NOTE: We intentionally do NOT replay pending writes from a fallback.\n // Early writes are dropped by design to avoid replaying invisible UI.\n if (_defaultPortalIsFallback && typeof createPortalSlot === 'function') {\n const real = definePortal<unknown>();\n _defaultPortal = real;\n _defaultPortalIsFallback = false;\n }\n\n // If the runtime primitive is removed (tests may simulate this by\n // deleting `createPortalSlot` between runs), revert to a fallback so\n // subsequent tests observe the appropriate fallback semantics.\n if (!_defaultPortalIsFallback && typeof createPortalSlot !== 'function') {\n const fallback = definePortal<unknown>();\n _defaultPortal = fallback;\n _defaultPortalIsFallback = true;\n logger.debug('[DefaultPortal] reverted to fallback portal');\n }\n\n return _defaultPortal;\n}\n\nexport const DefaultPortal: Portal<unknown> = (() => {\n function Host() {\n // Delegate to the lazily-created portal host (created when runtime is ready)\n // Return null when no pending value exists so the component renders nothing\n // (consistent with SSR which renders Fragment children as empty string)\n const v = ensureDefaultPortal()();\n return v === undefined ? null : v;\n }\n Host.render = function Render(props: { children?: unknown }) {\n ensureDefaultPortal().render(props);\n return null;\n };\n return Host as Portal<unknown>;\n})();\n\n/**\n * NOTE:\n * createPortalSlot is a runtime primitive.\n * It owns scheduling, consistency, and SSR behavior.\n */\ndeclare function createPortalSlot<T>(): {\n read(): unknown;\n write(value: T | undefined): void;\n};\n","/**\n * HTML escaping utilities for SSR\n *\n * Centralizes text and attribute escaping to avoid duplication\n * between sync and streaming SSR renderers.\n */\n\n// HTML5 void elements that don't have closing tags\nexport const 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 (bounded and clearable for long-running servers)\nconst escapeCache = new Map<string, string>();\nconst MAX_CACHE_SIZE = 256;\n\n/**\n * Clear the escape cache. Call between SSR requests in long-running servers\n * to prevent memory buildup from unique strings.\n */\nexport function clearEscapeCache(): void {\n escapeCache.clear();\n}\n\n/**\n * Escape HTML special characters in text content (optimized with cache)\n */\nexport function escapeText(text: string): string {\n // Only use cache for short strings (likely to be repeated)\n const useCache = text.length <= 64;\n\n if (useCache) {\n const cached = escapeCache.get(text);\n if (cached !== undefined) return cached;\n }\n\n const str = String(text);\n // Fast path: check if escaping needed\n if (!str.includes('&') && !str.includes('<') && !str.includes('>')) {\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, str);\n }\n return str;\n }\n\n const result = str\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n\n if (useCache && escapeCache.size < MAX_CACHE_SIZE) {\n escapeCache.set(text, result);\n }\n return result;\n}\n\n/**\n * Escape HTML special characters in attribute values\n */\nexport function 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 * Escape CSS value to prevent injection attacks.\n * Removes characters that could break out of CSS context.\n */\nfunction escapeCssValue(value: string): string {\n // Remove or escape characters that could enable CSS injection:\n // - Semicolons (could end the property and start a new one)\n // - Curly braces (could break out of rule context)\n // - Angle brackets (could inject HTML in some contexts)\n // - Backslashes (CSS escape sequences)\n // - url() and expression() are common attack vectors\n const str = String(value);\n\n // Block dangerous CSS functions\n if (/(?:url|expression|javascript)\\s*\\(/i.test(str)) {\n return '';\n }\n\n // Remove characters that could break out of CSS value context\n return str.replace(/[{}<>\\\\]/g, '');\n}\n\n/**\n * Convert style object to CSS string with value escaping\n */\nexport function 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 const safeValue = escapeCssValue(String(v));\n if (safeValue) {\n out += `${prop}:${safeValue};`;\n }\n }\n return out;\n}\n","/**\n * HTML attribute rendering for SSR\n */\n\nimport type { Props } from '../shared/types';\nimport { escapeAttr, styleObjToCss } from './escape';\n\n/** Result of renderAttrs including any raw HTML from dangerouslySetInnerHTML */\nexport type AttrsResult = {\n attrs: string;\n dangerousHtml?: string;\n};\n\n/**\n * Render attributes to HTML string, excluding event handlers\n * Optimized for minimal allocations\n *\n * Returns both the attribute string and any dangerouslySetInnerHTML content.\n */\nexport function renderAttrs(props?: Props): string;\nexport function renderAttrs(\n props: Props | undefined,\n opts: { returnDangerousHtml: true }\n): AttrsResult;\nexport function renderAttrs(\n props?: Props,\n opts?: { returnDangerousHtml?: boolean }\n): string | AttrsResult {\n if (!props || typeof props !== 'object') {\n return opts?.returnDangerousHtml ? { attrs: '' } : '';\n }\n\n let result = '';\n let dangerousHtml: string | undefined;\n\n for (const [key, value] of Object.entries(props)) {\n // Skip children in attrs\n if (key === 'children') continue;\n\n // Handle dangerouslySetInnerHTML\n if (key === 'dangerouslySetInnerHTML') {\n if (value && typeof value === 'object' && '__html' in (value as object)) {\n dangerousHtml = String((value as { __html: unknown }).__html);\n }\n continue;\n }\n\n // Skip event handlers (onClick, onChange, etc.)\n // Must have at least 3 chars and 3rd char must be uppercase\n if (\n key.length >= 3 &&\n key[0] === 'o' &&\n key[1] === 'n' &&\n key[2] >= 'A' &&\n key[2] <= 'Z'\n ) {\n continue;\n }\n\n // Skip internal props\n if (key.startsWith('_')) continue;\n\n // Normalize class attribute (`class` preferred, accept `className` for compatibility)\n const attrName = key === 'class' || key === 'className' ? 'class' : key;\n\n // Handle style objects\n if (attrName === 'style') {\n const css = typeof value === 'string' ? value : styleObjToCss(value);\n if (css === null || css === '') continue;\n result += ` style=\"${escapeAttr(css)}\"`;\n continue;\n }\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\n if (opts?.returnDangerousHtml) {\n return { attrs: result, dangerousHtml };\n }\n return result;\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 type { VNode, SSRComponent } from './types';\nimport { Fragment } from '../jsx';\nimport {\n withSSRContext,\n type SSRContext,\n throwSSRDataMissing,\n} from './context';\nimport { VOID_ELEMENTS, escapeText } from './escape';\nimport { renderAttrs } from './attrs';\n\n// Re-export for backwards compatibility\nexport type Component = SSRComponent;\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 isPromiseLike(x: unknown): x is PromiseLike<unknown> {\n if (!x || typeof x !== 'object') return false;\n const then = (x as { then?: unknown }).then;\n return typeof then === 'function';\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 (isPromiseLike(res)) {\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 // Fragment: render children in-place\n if (\n typeof type === 'symbol' &&\n (type === Fragment || String(type) === 'Symbol(Fragment)')\n ) {\n const children = normalizeChildren(node);\n renderChildrenToSink(children, sink, ctx);\n return;\n }\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, dangerousHtml } = renderAttrs(props, {\n returnDangerousHtml: true,\n });\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 // If dangerouslySetInnerHTML is set, use it instead of children\n if (dangerousHtml !== undefined) {\n sink.write(dangerousHtml);\n } else {\n const children = normalizeChildren(node);\n renderChildrenToSink(children, sink, ctx);\n }\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 { Fragment, ELEMENT_TYPE } from '../jsx';\nimport { DefaultPortal } from '../foundations/portal';\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';\nimport { VOID_ELEMENTS, escapeText } from './escape';\nimport { renderAttrs } from './attrs';\nimport type { VNode, SSRComponent } from './types';\n\nimport { logger } from '../dev/logger';\n\nexport { SSRDataMissingError } from './context';\nexport type { VNode, SSRComponent } from './types';\n\n// Re-export for backwards compatibility\nexport type Component = SSRComponent;\n\n// Dev-only SSR strictness guard helpers. We mutate globals in dev to make\n// accidental usage of Math.random/Date.now during sync SSR fail fast.\n// We implement a re-entrant stack so nested or concurrent calls don't clobber\n// global values unexpectedly.\nconst __ssrGuardStack: Array<{ random: () => number; now: () => number }> = [];\n\nexport function pushSSRStrictPurityGuard() {\n /* istanbul ignore if - dev-only guard */\n if (process.env.NODE_ENV === 'production') return;\n __ssrGuardStack.push({\n random: Reflect.get(Math, 'random') as () => number,\n now: Reflect.get(Date, 'now') as () => number,\n });\n Reflect.set(Math, '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 Reflect.set(Date, '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\nexport function popSSRStrictPurityGuard() {\n /* istanbul ignore if - dev-only guard */\n if (process.env.NODE_ENV === 'production') return;\n const prev = __ssrGuardStack.pop();\n if (prev) {\n Reflect.set(Math, 'random', prev.random);\n Reflect.set(Date, 'now', prev.now);\n }\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 // We already verified the shape above; assert as VNode for the sync renderer\n return renderNodeSync(child as 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 /* istanbul ignore if - dev-only debug */\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[SSR] renderNodeSync type:', typeof type, type);\n } catch {\n // Ignore coercion errors for Symbols\n }\n }\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 // executeComponentSync already normalizes primitives into VNode wrappers,\n // so result is always a VNode or JSXElement here. Safe to recurse directly.\n return renderNodeSync(result, ctx);\n }\n\n // Special-case fragments (symbols) - render children directly\n if (typeof type === 'symbol') {\n if (type === Fragment) {\n // Prefer explicit `children` array; fallback to `props.children` for\n // JSX runtimes that place children on props.\n const childrenArr = Array.isArray((node as VNode).children)\n ? (node as VNode).children\n : Array.isArray(props?.children)\n ? (props?.children as unknown[])\n : undefined;\n /* istanbul ignore if - dev-only debug */\n if (process.env.NODE_ENV !== 'production') {\n try {\n logger.warn('[SSR] fragment children length:', childrenArr?.length);\n } catch {\n // Ignore\n }\n }\n return renderChildrenSync(childrenArr, ctx);\n }\n // Unknown symbol type - throw a helpful error instead of letting\n // a built-in TypeError bubble up when attempting to coerce to string.\n throw new Error(\n `renderNodeSync: unsupported VNode symbol type: ${String(type)}`\n );\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, dangerousHtml } = renderAttrs(props, {\n returnDangerousHtml: true,\n });\n // If dangerouslySetInnerHTML is set, use it instead of children\n if (dangerousHtml !== undefined) {\n return `<${typeStr}${attrs}>${dangerousHtml}</${typeStr}>`;\n }\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 // Re-entrant guard for dev-only SSR strict purity checks.\n // We avoid clobbering globals permanently by pushing the original functions\n // onto a stack and restoring them on exit. This is safer for nested or\n // stacked SSR render invocations.\n\n try {\n if (process.env.NODE_ENV !== 'production') {\n pushSSRStrictPurityGuard();\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 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 if (\n typeof result === 'string' ||\n typeof result === 'number' ||\n typeof result === 'boolean' ||\n result === null ||\n result === undefined\n ) {\n // Return a Fragment with the text content, not a div wrapper\n const inner =\n result === null || result === undefined || result === false\n ? ''\n : String(result);\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: inner ? [inner] : [] },\n } as unknown as VNode | JSXElement;\n }\n return result as VNode | JSXElement;\n });\n } finally {\n // Restore the previous instance (if any)\n setCurrentComponentInstance(prev);\n }\n } finally {\n if (process.env.NODE_ENV !== 'production') popSSRStrictPurityGuard();\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 wrapped: Component = (\n p?: Record<string, unknown>,\n c?: { signal?: AbortSignal; ssr?: RenderContext }\n ) => {\n const out = (component as unknown as Component)(p ?? {}, c);\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n if (out == null) {\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: [portalVNode] },\n } as unknown as VNode | JSXElement;\n }\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: [out as unknown, portalVNode] },\n } as unknown as VNode | JSXElement;\n };\n\n const node = executeComponentSync(wrapped, props || {}, ctx);\n if (!node) {\n throw new Error('renderToStringSync: wrapped component returned empty');\n }\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.\n//\n// ⚠️ WARNING: This function mutates global route state. It is NOT safe to call\n// concurrently from multiple async contexts. In long-running servers, ensure\n// SSR requests are serialized or use isolated route contexts per request.\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 wrapped: Component = (\n p?: Record<string, unknown>,\n c?: { signal?: AbortSignal; ssr?: RenderContext }\n ) => {\n const out = (resolved.handler as unknown as Component)(p ?? {}, c);\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n if (out == null) {\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: [portalVNode] },\n } as unknown as VNode | JSXElement;\n }\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: [out as unknown, portalVNode] },\n } as unknown as VNode | JSXElement;\n };\n\n const node = executeComponentSync(wrapped, resolved.params || {}, ctx);\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 './stream-render';\nimport {\n startRenderPhase,\n stopRenderPhase,\n collectResources,\n resolvePlan,\n resolveResources,\n ResourcePlan,\n} from './render-keys';\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 = 12345, data, sink } = opts;\n\n // ⚠️ WARNING: This function mutates global route state. It is NOT safe to call\n // concurrently from multiple async contexts. In long-running servers, ensure\n // SSR requests are serialized or use isolated route contexts per request.\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, task, derive } from './runtime/operations';\nexport type { DataResult } from './runtime/operations';\n\n// App bootstrap (explicit startup APIs)\nexport {\n createIsland,\n createSPA,\n hydrateSPA,\n cleanupApp,\n hasApp,\n} from './boot';\nexport type { IslandConfig, SPAConfig, HydrateSPAConfig } from './boot';\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';\n\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// Foundations (public convenience exports)\nexport { layout } from './foundations/layout';\nexport type { LayoutComponent } from './foundations/layout';\nexport { Slot } from './foundations/slot';\nexport type { SlotProps } from './foundations/slot';\nexport {\n definePortal,\n DefaultPortal,\n _resetDefaultPortal,\n} from './foundations/portal';\nexport type { Portal } from './foundations/portal';\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 { createIsland, createSPA, hydrateSPA } from './boot';\n\n// Ensure fastlane bridge is initialized for environments (tests/global access)\n// This file exports a side-effectful module that attaches helpers to globalThis.\nimport './runtime/fastlane';\n\nif (typeof globalThis !== 'undefined') {\n const g = globalThis as Record<string, unknown>;\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-shared';\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 set(updater: (prev: T) => 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 State<T> & { _owner?: ComponentInstance })._owner = instance;\n\n // Attach set method directly to function\n read.set = (newValueOrUpdater: T | ((prev: T) => 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 // This should never happen if code follows best practices, but we gracefully degrade\n // rather than crashing in production.\n if (currentInst !== null && process.env.NODE_ENV === 'production') {\n // Log once in production to help debugging without throwing\n if (typeof console !== 'undefined' && console.warn) {\n console.warn(\n '[Askr] state.set() called during render - update skipped. ' +\n 'Move state updates to event handlers.'\n );\n }\n return;\n }\n\n // Compute new value if an updater was provided\n let newValue: T;\n if (typeof newValueOrUpdater === 'function') {\n // Note: function-valued state cannot be set directly via a function argument;\n // such an argument is treated as a functional updater (this follows the common\n // convention from other libraries). If you need to store a function as state,\n // wrap it in an object.\n const updater = newValueOrUpdater as (prev: T) => T;\n newValue = updater(value);\n } else {\n newValue = newValueOrUpdater as T;\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/render-keys';\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 // Attach debug label (component name) for richer logs\n cell.ownerName = inst.fn?.name || '<anonymous>';\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\n// Short-form overload: accept a single function that returns the derived value\nexport function derive<TOut>(fn: () => TOut): TOut | null;\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 // Short-form: derive(() => someExpression)\n if (map === undefined && typeof source === 'function') {\n const value = (source as () => TOut)();\n if (value == null) return null;\n\n const instance = getCurrentComponentInstance();\n if (!instance) {\n return value as TOut;\n }\n\n const cache = getDeriveCache(instance);\n if (cache.has(value as unknown)) return cache.get(value as unknown) as TOut;\n\n cache.set(value as unknown, value as unknown);\n return value as TOut;\n }\n\n // Normal form: derive(source, map)\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 as (v: TIn) => TOut)(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 as unknown)) {\n return cache.get(value as unknown) as TOut;\n }\n\n // Compute and cache the result\n const result = (map as (v: TIn) => TOut)(value as TIn);\n cache.set(value as unknown, result as unknown);\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 // Optional debug label set by caller (component name) to improve logs\n ownerName?: string;\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 if (this.ownerName) {\n logger.error(\n `[Askr] Async resource error in ${this.ownerName}:`,\n err\n );\n } else {\n logger.error('[Askr] Async resource error:', err);\n }\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","// Centralized memoization cache for derive()\n// Maps (component_instance) -> Map<source_value, result>\nconst deriveCacheMap = new WeakMap<{ id: string }, Map<unknown, unknown>>();\n\nexport function getDeriveCache(instance: {\n id: string;\n}): Map<unknown, unknown> {\n let cache = deriveCacheMap.get(instance);\n if (!cache) {\n cache = new Map();\n deriveCacheMap.set(instance, cache);\n }\n return cache;\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 { registerAppInstance, initializeNavigation } from '../router/navigate';\n\nlet componentIdCounter = 0;\n\n// Track instances by root element to support multiple createIsland 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 // Opt-in: surface cleanup errors during teardown for this app instance\n cleanupStrict?: boolean;\n}\n\nfunction attachCleanupForRoot(\n rootElement: Element,\n instance: ComponentInstance\n) {\n (rootElement as ElementWithCleanup)[CLEANUP_SYMBOL] = () => {\n // Attempt to remove listeners and cleanup instances under the root.\n // In non-strict mode we preserve previous behavior by swallowing errors\n // (but logging in dev); in strict mode we aggregate and re-throw.\n const errors: unknown[] = [];\n try {\n removeAllListeners(rootElement);\n } catch (e) {\n errors.push(e);\n }\n\n // Manually traverse descendants and attempt to cleanup their instances.\n // Avoids import cycles by using local traversal and existing cleanupComponent.\n try {\n const descendants = rootElement.querySelectorAll('*');\n for (const d of Array.from(descendants)) {\n try {\n const inst = (d as Element & { __ASKR_INSTANCE?: ComponentInstance })\n .__ASKR_INSTANCE;\n if (inst) {\n try {\n cleanupComponent(inst);\n } catch (err) {\n errors.push(err);\n }\n try {\n delete (d as Element & { __ASKR_INSTANCE?: ComponentInstance })\n .__ASKR_INSTANCE;\n } catch (err) {\n errors.push(err);\n }\n }\n } catch (err) {\n errors.push(err);\n }\n }\n } catch (e) {\n errors.push(e);\n }\n\n try {\n cleanupComponent(instance as ComponentInstance);\n } catch (e) {\n errors.push(e);\n }\n\n if (errors.length > 0) {\n if (instance.cleanupStrict) {\n throw new AggregateError(errors, `cleanup failed for app root`);\n } else if (process.env.NODE_ENV !== 'production') {\n for (const err of errors) logger.warn('[Askr] cleanup error:', err);\n }\n }\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 try {\n removeAllListeners(rootElement);\n } catch (e) {\n if (instance.cleanupStrict) throw e;\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] cleanup error:', e);\n }\n\n try {\n cleanupComponent(instance as ComponentInstance);\n } catch (e) {\n if (instance.cleanupStrict) throw e;\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] cleanup error:', e);\n }\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\n/**\n * Explicitly teardown an app mounted on `root` if present. This is the\n * recommended API for deterministic cleanup rather than relying on overriding\n * `innerHTML` setter behavior.\n */\nexport function teardownApp(_root: Element | string) {\n throw new Error(\n 'The `teardownApp` alias has been removed. Use `cleanupApp(root)` instead.'\n );\n}\n\nimport { Fragment, ELEMENT_TYPE } from '../jsx';\nimport { DefaultPortal } from '../foundations/portal';\n\nfunction mountOrUpdate(\n rootElement: Element,\n componentFn: ComponentFunction,\n options?: { cleanupStrict?: boolean }\n) {\n // Ensure root component always includes a DefaultPortal host by wrapping it.\n const wrappedFn: ComponentFunction = (props, ctx) => {\n const out = componentFn(props, ctx);\n const portalVNode = {\n $$typeof: ELEMENT_TYPE,\n type: DefaultPortal,\n props: {},\n key: '__default_portal',\n } as unknown;\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: {\n children:\n out === undefined || out === null\n ? [portalVNode]\n : [out, portalVNode],\n },\n } as unknown as ReturnType<ComponentFunction>;\n };\n // Preserve the original component name for debugging/dev warnings\n Object.defineProperty(wrappedFn, 'name', {\n value: componentFn.name || 'Component',\n });\n\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 try {\n cleanupComponent(instance);\n } catch (e) {\n // If previous cleanup threw in strict mode, log but continue mounting new instance\n if (process.env.NODE_ENV !== 'production')\n logger.warn('[Askr] prior cleanup threw:', e);\n }\n\n instance.fn = wrappedFn;\n instance.evaluationGeneration++;\n instance.mounted = false;\n instance.expectedStateIndices = [];\n instance.firstRenderComplete = false;\n instance.isRoot = true;\n // Update strict flag if provided\n if (options && typeof options.cleanupStrict === 'boolean') {\n instance.cleanupStrict = options.cleanupStrict;\n }\n } else {\n const componentId = String(++componentIdCounter);\n instance = createComponentInstance(componentId, wrappedFn, {}, rootElement);\n instancesByRoot.set(rootElement, instance);\n instance.isRoot = true;\n // Initialize strict flag from options\n if (options && typeof options.cleanupStrict === 'boolean') {\n instance.cleanupStrict = options.cleanupStrict;\n }\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';\nimport { removeAllListeners } from '../renderer';\n\nexport type IslandConfig = {\n root: Element | string;\n component: ComponentFunction;\n // Optional: surface cleanup errors during teardown for this island\n cleanupStrict?: boolean;\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 // Optional: surface cleanup errors during teardown for this SPA\n cleanupStrict?: boolean;\n component?: never;\n};\n\nexport type HydrateSPAConfig = {\n root: Element | string;\n routes: Route[];\n // Optional: surface cleanup errors during teardown for this SPA\n cleanupStrict?: boolean;\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 cleanupStrict: config.cleanupStrict,\n });\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 cleanupStrict: false,\n });\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 cleanupStrict: false,\n });\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 cleanupStrict: false,\n });\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 * Link component for client-side navigation\n */\n\nimport { navigate } from '../router/navigate';\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): unknown {\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","/**\n * Layout helper.\n *\n * A layout is just a normal component that wraps children.\n * Persistence and reuse are handled by the runtime via component identity.\n *\n * This helper exists purely for readability and convention.\n */\n\nexport type LayoutComponent<P = object> = (\n props: P & { children?: unknown }\n) => unknown;\n\nexport function layout<P = object>(Layout: LayoutComponent<P>) {\n return (children?: unknown, props?: P) =>\n Layout({ ...(props as P), children });\n}\n","import { logger } from '../dev/logger';\nimport { Fragment, cloneElement, isElement, ELEMENT_TYPE } from '../jsx';\nimport type { JSXElement } from '../jsx';\n\nexport type SlotProps =\n | {\n asChild: true;\n children: JSXElement;\n [key: string]: unknown;\n }\n | {\n asChild?: false;\n children?: unknown;\n };\n\nexport function Slot(props: SlotProps): JSXElement | null {\n if (props.asChild) {\n const { children, ...rest } = props;\n\n if (isElement(children)) {\n return cloneElement(children, rest);\n }\n\n logger.warn('<Slot asChild> expects a single JSX element child.');\n\n return null;\n }\n\n // Structural no-op: Slot does not introduce DOM\n // Return a vnode object for the fragment with the internal element marker.\n return {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: props.children },\n } as JSXElement;\n}\n","import { globalScheduler } from './scheduler';\nimport { logger } from '../dev/logger';\nimport { type ComponentInstance, finalizeReadSubscriptions } from './component';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n populateKeyMapForElement,\n} from '../renderer';\n\nimport {\n enterBulkCommit,\n exitBulkCommit,\n isBulkCommitActive,\n markFastPathApplied,\n isFastPathApplied,\n} from './fastlane-shared';\nimport { Fragment } from '../jsx/types';\nimport { setDevValue, getDevValue } from './dev-namespace';\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 */\n\n// Helper to unwrap Fragment vnodes to get the first intrinsic element child\nfunction unwrapFragmentForFastPath(vnode: unknown): unknown {\n if (!vnode || typeof vnode !== 'object' || !('type' in vnode)) return vnode;\n const v = vnode as {\n type: unknown;\n children?: unknown;\n props?: { children?: unknown };\n };\n // Check if it's a Fragment\n if (\n typeof v.type === 'symbol' &&\n (v.type === Fragment || String(v.type) === 'Symbol(askr.fragment)')\n ) {\n const children = v.children || v.props?.children;\n if (Array.isArray(children) && children.length > 0) {\n // Return the first child that's an intrinsic element\n for (const child of children) {\n if (child && typeof child === 'object' && 'type' in child) {\n const c = child as { type: unknown };\n if (typeof c.type === 'string') {\n return child;\n }\n }\n }\n }\n }\n return vnode;\n}\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\n // Unwrap Fragment to get the actual element vnode for classification\n const unwrappedResult = unwrapFragmentForFastPath(result);\n\n if (\n !unwrappedResult ||\n typeof unwrappedResult !== 'object' ||\n !('type' in unwrappedResult)\n )\n return { useFastPath: false, reason: 'not-vnode' };\n\n const vnode = unwrappedResult 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 = vnode.children || vnode.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 (const c of children) {\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 // Ensure a keyed map is available for the first child by populating it proactively.\n try {\n populateKeyMapForElement(firstChild);\n } catch {\n // ignore\n }\n\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): boolean {\n // Performs the minimal, synchronous reorder-only commit.\n const evaluate = (\n globalThis as {\n __ASKR_RENDERER?: {\n evaluate?: (node: unknown, target: Element | null) => void;\n };\n }\n ).__ASKR_RENDERER?.evaluate;\n\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 globalScheduler.runWithSyncProgress(() => {\n evaluate(result, instance.target);\n\n // Finalize runtime bookkeeping (read subscriptions / tokens)\n try {\n finalizeReadSubscriptions(instance);\n } catch (e) {\n if (process.env.NODE_ENV !== 'production') throw e;\n }\n });\n\n // Clear any synchronous tasks scheduled during the commit\n const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;\n setDevValue('__FASTLANE_CLEARED_AFTER', clearedAfter);\n\n // Dev-only invariant checks\n if (process.env.NODE_ENV !== 'production') {\n validateFastLaneInvariants(instance, schedBefore);\n }\n\n return true;\n } finally {\n exitBulkCommit();\n }\n // Dev-only: verify bulk commit flag was properly cleared (after finally to avoid no-unsafe-finally)\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive()) {\n throw new Error(\n 'Fast-lane invariant violated: bulk commit flag still set after commit'\n );\n }\n }\n}\n\n/**\n * Validates fast-lane invariants in dev mode.\n * Extracted to reduce complexity in commitReorderOnly.\n */\nfunction validateFastLaneInvariants(\n instance: ComponentInstance,\n schedBefore: ReturnType<typeof globalScheduler.getState> | null\n): void {\n const commitCount = getDevValue<number>('__LAST_FASTPATH_COMMIT_COUNT') ?? 0;\n const invariants = {\n commitCount,\n mountOps: instance.mountOperations.length,\n cleanupFns: instance.cleanupFns.length,\n };\n setDevValue('__LAST_FASTLANE_INVARIANTS', invariants);\n\n if (commitCount !== 1) {\n console.error(\n '[FASTLANE][INV] commitCount',\n commitCount,\n 'diag',\n (globalThis as Record<string, unknown>).__ASKR_DIAG\n );\n throw new Error(\n 'Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit'\n );\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\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 schedAfter.taskCount > schedBefore.taskCount\n ) {\n console.error(\n '[FASTLANE] schedBefore, schedAfter',\n schedBefore,\n schedAfter\n );\n console.error('[FASTLANE] enqueue logs', getDevValue('__ENQUEUE_LOGS'));\n throw new Error(\n 'Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit'\n );\n }\n\n // Final quiescence assertion\n let finalState = globalScheduler.getState();\n const executing = globalScheduler.isExecuting();\n let 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\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 outstandingAfter = Math.max(\n 0,\n finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)\n );\n if (outstandingAfter !== 0) {\n console.error(\n '[FASTLANE] Post-commit enqueue logs:',\n getDevValue('__ENQUEUE_LOGS')\n );\n console.error(\n '[FASTLANE] Cleared counts:',\n getDevValue('__FASTLANE_CLEARED_TASKS'),\n getDevValue('__FASTLANE_CLEARED_AFTER')\n );\n throw new Error(\n `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) 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) {\n // Clear stale fast-path diagnostics\n setDevValue('__LAST_FASTPATH_STATS', undefined);\n setDevValue('__LAST_FASTPATH_COMMIT_COUNT', 0);\n return false;\n }\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\nif (typeof globalThis !== 'undefined') {\n (globalThis as Record<string, unknown>).__ASKR_FASTLANE = {\n isBulkCommitActive,\n enterBulkCommit,\n exitBulkCommit,\n tryRuntimeFastLaneSync,\n markFastPathApplied,\n isFastPathApplied,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAYO,SAAS,UACd,WACA,SACA,SACmB;AACnB,MAAI,CAAC,WAAW;AACd,UAAM,aAAa,UAAU,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC,IAAI;AACvE,UAAM,IAAI,MAAM,oBAAoB,OAAO,GAAG,UAAU,EAAE;AAAA,EAC5D;AACF;AA0GO,SAAS,6BACd,WACA,kBACmB;AACnB,YAAU,WAAW,4BAA4B,gBAAgB,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,eAAe,aAAa;AACrC,QAAM,IAAI;AACV,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","task","current","isBulkCommitActive","state","init_types","ELEMENT_TYPE","Fragment","init_types","Fragment","current","isBulkCommitActive","isBulkCommitActive","updateElementChildren","applyPropsToElement","current","init_types","isBulkCommitActive","e","state","init_context","getSpecificity","currentInstance","init_utils","init_types","init_types","init_utils","HostFallback","executeComponent","init_context","executeComponentSync","attrs","routes","clearRoutes","route","setServerLocation","lockRouteRegistration","resolveRoute","init_context","Fragment","isBulkCommitActive","task","init_context","init_context","renderData","holder","h","cell","value","instance","cache","clearRoutes","route","lockRouteRegistration","resolveRoute","instance","setServerLocation","renderToStringSync","registerAppInstance","initializeNavigation","init_types","evaluate","isBulkCommitActive"]}
|