@askrjs/askr 0.0.6 → 0.0.8
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/{component-BBGWJdqJ.d.ts → component-DHAn9JxU.d.ts} +1 -1
- package/dist/foundations/index.d.ts +348 -6
- package/dist/foundations/index.js +1011 -84
- package/dist/foundations/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +80 -81
- package/dist/index.js.map +1 -1
- package/dist/{jsx-AzPM8gMS.d.ts → jsx-CSWf4VFg.d.ts} +2 -2
- package/dist/jsx-dev-runtime.d.ts +3 -3
- package/dist/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx-runtime.d.ts +3 -3
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/layout-BINPv-nz.d.ts +29 -0
- package/dist/resources/index.d.ts +2 -2
- package/dist/resources/index.js +3 -3
- package/dist/resources/index.js.map +1 -1
- package/dist/router/index.d.ts +1 -1
- package/dist/router/index.js +57 -8
- package/dist/router/index.js.map +1 -1
- package/dist/ssr/index.d.ts +1 -1
- package/dist/ssr/index.js +80 -71
- package/dist/ssr/index.js.map +1 -1
- package/dist/{types-uOPfcrdz.d.ts → types-DxdosFWx.d.ts} +1 -1
- package/package.json +5 -5
- package/dist/layout-D5MqtW_q.d.ts +0 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/foundations/layout.tsx","../../src/dev/logger.ts","../../src/common/jsx.ts","../../src/jsx/utils.ts","../../src/foundations/slot.tsx","../../src/runtime/component.ts","../../src/foundations/portal.tsx"],"names":["HostFallback"],"mappings":";AAaO,SAAS,OAAmB,MAAA,EAA4B;AAC7D,EAAA,OAAO,CAAC,UAAoB,KAAA,KAC1B,MAAA,CAAO,EAAE,GAAI,KAAA,EAAa,UAAU,CAAA;AACxC;;;ACTA,SAAS,WAAA,CAAY,QAAgB,IAAA,EAAuB;AAC1D,EAAA,MAAM,CAAA,GAAI,OAAO,OAA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AI,wBAAA,IAA4B,OAAO,gBAAA,KAAqB,UAAA,EAAY;AACtE,IAAA,MAAM,OAAO,YAAA,EAAsB;AACnC,IAAA,cAAA,GAAiB,IAAA;AACjB,IAAA,wBAAA,GAA2B,KAAA;AAAA,EAC7B;AAKA,EAAA,IAAI,CAAC,wBAAA,IAA4B,OAAO,gBAAA,KAAqB,UAAA,EAAY;AACvE,IAAA,MAAM,WAAW,YAAA,EAAsB;AACvC,IAAA,cAAA,GAAiB,QAAA;AACjB,IAAA,wBAAA,GAA2B,IAAA;AAAA,EAC7B;AAEA,EAAA,OAAO,cAAA;AACT;AAEO,IAAM,iBAAkC,MAAM;AACnD,EAAA,SAAS,IAAA,GAAO;AAId,IAAA,MAAM,CAAA,GAAI,qBAAoB,EAAE;AAChC,IAAA,OAAO,CAAA,KAAM,SAAY,IAAA,GAAO,CAAA;AAAA,EAClC;AACA,EAAA,IAAA,CAAK,MAAA,GAAS,SAAS,MAAA,CAAO,KAAA,EAA+B;AAC3D,IAAA,mBAAA,EAAoB,CAAE,OAAO,KAAK,CAAA;AAClC,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AACA,EAAA,OAAO,IAAA;AACT,CAAA","file":"index.js","sourcesContent":["/**\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","/**\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 * Common call contracts: JSX element shape\n */\n\nimport type { Props } from './props';\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","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","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","/**\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 { Props } from '../common/props';\nimport type { ComponentFunction } from '../common/component';\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 } from '../common/component';\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';\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","/**\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 type { ComponentInstance } 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 // Fast fallback for module/SSR/test environments.\n // Track a single owner to avoid per-render array scans.\n let owner: ComponentInstance | null = null;\n let pending: T | undefined;\n\n function HostFallback() {\n // Drop owner + pending when owner unmounts to avoid replay.\n if (owner && owner.mounted === false) {\n owner = null;\n pending = undefined;\n }\n\n const inst = getCurrentComponentInstance();\n\n // Capture the first host as the owner.\n // We intentionally do NOT require `mounted === true` here because the\n // host can render before the runtime flips its mounted flag. Capturing\n // early ensures `DefaultPortal.render()` works immediately after mount.\n if (!owner && inst) owner = inst;\n\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 /* istanbul ignore if */\n if (process.env.NODE_ENV !== 'production') {\n // Minimal dev diagnostics; avoid heavy allocations in the hot path.\n if (inst && owner && inst !== owner && inst.mounted === true) {\n logger.warn(\n '[Portal] multiple mounted hosts detected; first mounted host is owner'\n );\n }\n }\n\n return inst && owner && inst === owner ? (pending as unknown) : undefined;\n }\n\n HostFallback.render = function RenderFallback(props: { children?: T }) {\n // Owner must be fully mounted (mounted === true) to accept writes.\n if (!owner || owner.mounted !== true) return null;\n\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 // Update pending value for the live owner\n pending = props.children as T | undefined;\n\n // Schedule an update on the owner so it re-renders\n if (owner.notifyUpdate) owner.notifyUpdate();\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 // Keep counter increment guarded for dev-only behavior\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 if (!_defaultPortal) {\n if (typeof createPortalSlot === 'function') {\n _defaultPortal = definePortal<unknown>();\n _defaultPortalIsFallback = false;\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 }\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 }\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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/foundations/structures/layout.tsx","../../src/common/jsx.ts","../../src/jsx/utils.ts","../../src/foundations/structures/slot.tsx","../../src/foundations/structures/presence.ts","../../src/foundations/structures/portal.tsx","../../src/foundations/utilities/composeHandlers.ts","../../src/foundations/utilities/mergeProps.ts","../../src/foundations/utilities/aria.ts","../../src/foundations/utilities/composeRef.ts","../../src/foundations/utilities/useId.ts","../../src/dev/invariant.ts","../../src/dev/logger.ts","../../src/runtime/scheduler.ts","../../src/renderer/utils.ts","../../src/renderer/keyed.ts","../../src/runtime/dev-namespace.ts","../../src/runtime/fastlane.ts","../../src/runtime/state.ts","../../src/foundations/state/controllable.ts","../../src/foundations/interactions/pressable.ts","../../src/foundations/interactions/dismissable.ts","../../src/foundations/interactions/focusable.ts","../../src/foundations/interactions/hoverable.ts"],"names":["PortalHost","isBulkCommitActive","isControlled"],"mappings":";AA4BO,SAAS,OAAmB,MAAA,EAA4B;AAC7D,EAAA,OAAO,CAAC,UAAoB,KAAA,KAAc;AACxC,IAAA,MAAM,WAAA,GAAc,EAAE,GAAG,KAAA,EAAO,QAAA,EAAS;AACzC,IAAA,OAAO,OAAO,WAAW,CAAA;AAAA,EAC3B,CAAA;AACF;;;AC3BO,IAAM,YAAA,mBAAe,MAAA,CAAO,GAAA,CAAI,cAAc,CAAA;AAC9C,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,eAAe,CAAA;;;ACL3C,SAAS,UAAU,KAAA,EAAqC;AAC7D,EAAA,OACE,OAAO,KAAA,KAAU,QAAA,IACjB,KAAA,KAAU,IAAA,IACT,MAAqB,QAAA,KAAa,YAAA;AAEvC;AAEO,SAAS,YAAA,CACd,SACA,KAAA,EACY;AACZ,EAAA,OAAO;AAAA,IACL,GAAG,OAAA;AA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AAA;AAAA,IACb,CAAA;AAAA,IACJ,cAAA,EAAgB,QAAA,GACZ,MAAA,GACA,CAAC,CAAA,KAAM;AACL,MAAA,OAAA,GAAU,CAAC,CAAA;AAAA,IACb;AAAA,GACN;AACF","file":"index.js","sourcesContent":["/**\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 * POLICY DECISIONS (LOCKED):\n *\n * 1. Return Type is Opaque (unknown)\n * Layout components return `unknown` to remain runtime-agnostic.\n * The runtime owns concrete JSX element types.\n *\n * 2. Children Positioning\n * Layout receives children as first argument (router-friendly).\n * Props come second. This matches route layout conventions where\n * children represent the nested route content.\n *\n * 3. Props Spreading\n * Props are spread into the layout component. This is intentional\n * and deterministic — no merging or composition.\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 const mergedProps = { ...props, children } as P & { children?: unknown };\n return Layout(mergedProps);\n };\n}\n","/**\n * Common call contracts: JSX element shape\n */\n\nimport type { Props } from './props';\n\nexport const ELEMENT_TYPE = Symbol.for('askr.element');\nexport const Fragment = Symbol.for('askr.fragment');\n\nexport interface JSXElement {\n /** Internal element marker */\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","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","import { 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\n/**\n * Slot\n *\n * Structural primitive for prop forwarding patterns.\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. asChild Pattern\n * When asChild=true, merges props into the single child element.\n * Child must be a valid JSXElement; non-element children return null.\n * **Slot props override child props** (injection pattern).\n *\n * 2. Fallback Behavior\n * When asChild=false, returns a Fragment (structural no-op).\n * No DOM element is introduced.\n *\n * 3. Type Safety\n * asChild=true requires exactly one JSXElement child (enforced by type).\n * Runtime validates with isElement() check.\n */\nexport function Slot(props: SlotProps): JSXElement | null {\n if (props.asChild) {\n const { children, asChild: _asChild, ...rest } = props;\n\n if (isElement(children)) {\n return cloneElement(children, rest);\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 const element: JSXElement = {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children: props.children },\n key: null,\n };\n return element;\n}\n","import { ELEMENT_TYPE, Fragment } from '../../jsx';\nimport type { JSXElement } from '../../jsx';\n\nexport interface PresenceProps {\n present: boolean | (() => boolean);\n children?: unknown;\n}\n\n/**\n * Presence\n *\n * Structural policy primitive for conditional mount/unmount.\n * - No timers\n * - No animation coupling\n * - No DOM side-effects\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Present as Function\n * Accepts boolean OR function to support lazy evaluation patterns.\n * Function is called once per render. Use boolean form for static values.\n *\n * 2. Children Type\n * `children` is intentionally `unknown` to remain runtime-agnostic.\n * The runtime owns child normalization and validation.\n *\n * 3. Immediate Mount/Unmount\n * No exit animations or transitions. When `present` becomes false,\n * children are removed immediately. Animation must be layered above\n * this primitive.\n */\nexport function Presence({\n present,\n children,\n}: PresenceProps): JSXElement | null {\n const isPresent =\n typeof present === 'function' ? present() : Boolean(present);\n if (!isPresent) return null;\n\n const element: JSXElement = {\n $$typeof: ELEMENT_TYPE,\n type: Fragment,\n props: { children },\n key: null,\n };\n return element;\n}\n","/**\n * Portal / Host primitive.\n *\n * Foundations remain runtime-agnostic: a portal is an explicit read/write slot.\n * Scheduling and attachment are owned by the runtime when `createPortalSlot`\n * exists; otherwise this falls back to a local slot (deterministic, but does\n * not schedule updates).\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Local Mutable State\n * Foundations may use local mutable state ONLY to model deterministic slots,\n * never to coordinate timing, effects, or ordering. The fallback mode uses\n * closure-local `mounted` and `value` variables which are non-escaping and\n * deterministic.\n *\n * 2. Return Type Philosophy\n * Portal call signatures return `unknown` (intentionally opaque). The runtime\n * owns the concrete type. This prevents foundations from assuming JSX.Element\n * or DOM node types, maintaining runtime-agnostic portability.\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 // 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 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 // Deterministic local fallback (SSR/tests). No runtime scheduling.\n // Writes are accepted only after the host has rendered at least once.\n //\n // CRITICAL BEHAVIOR:\n // - Writes update local state but do NOT trigger re-renders\n // - The portal host will reflect changes only when the component tree\n // re-renders for other reasons (e.g., parent state change)\n // - This is safe for SSR and tests where rendering is synchronous\n // and externally controlled\n // - In runtime mode, createPortalSlot handles scheduling automatically\n let mounted = false;\n let value: T | undefined;\n\n function PortalHostFallback() {\n mounted = true;\n return value as unknown;\n }\n\n PortalHostFallback.render = function PortalRenderFallback(props: {\n children?: T;\n }) {\n if (!mounted) return null;\n value = props.children;\n return null;\n };\n\n return PortalHostFallback as Portal<T>;\n}\n\n/**\n * Default Portal Singleton\n *\n * POLICY (LOCKED):\n * There is exactly one default portal per runtime.\n * Tests must reset it explicitly using _resetDefaultPortal().\n * This ensures consistent portal behavior across the application\n * while maintaining test isolation.\n */\nlet _defaultPortal: Portal<unknown> | undefined;\n\nexport function _resetDefaultPortal(): void {\n _defaultPortal = undefined;\n}\n\nfunction ensureDefaultPortal(): Portal<unknown> {\n if (!_defaultPortal) _defaultPortal = definePortal<unknown>();\n return _defaultPortal;\n}\n\nexport const DefaultPortal: Portal<unknown> = (() => {\n function Host() {\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 * composeHandlers\n *\n * Compose two event handlers into one. The first handler runs, and unless it\n * calls `event.preventDefault()` (or sets `defaultPrevented`), the second\n * handler runs. This prevents accidental clobbering of child handlers when\n * injecting props.\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Execution Order\n * First handler runs before second (injected before base).\n * This allows injected handlers to prevent default behavior.\n *\n * 2. Default Prevention Check\n * By default, checks `defaultPrevented` on first argument.\n * Can be disabled via options.checkDefaultPrevented = false.\n *\n * 3. Undefined Handler Support\n * Undefined handlers are skipped (no-op). This simplifies usage\n * where handlers are optional.\n *\n * 4. Type Safety\n * Args are readonly to prevent mutation. Return type matches input.\n */\n\nexport interface ComposeHandlersOptions {\n /**\n * When true (default), do not run the second handler if the first prevented default.\n * When false, always run both handlers.\n */\n checkDefaultPrevented?: boolean;\n}\n\nfunction isDefaultPrevented(\n value: unknown\n): value is { defaultPrevented: true } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'defaultPrevented' in value &&\n (value as { defaultPrevented?: boolean }).defaultPrevented === true\n );\n}\n\nexport function composeHandlers<A extends readonly unknown[]>(\n first?: (...args: A) => void,\n second?: (...args: A) => void,\n options?: ComposeHandlersOptions\n): (...args: A) => void {\n // Fast path: if neither handler exists, return stable no-op\n if (!first && !second) {\n return noop as (...args: A) => void;\n }\n\n // Fast path: if only one handler exists, return it directly\n if (!first) return second!;\n if (!second) return first;\n\n // Composition path: both handlers exist\n const checkDefaultPrevented = options?.checkDefaultPrevented !== false;\n\n return function composed(...args: A) {\n first(...args);\n\n if (checkDefaultPrevented && isDefaultPrevented(args[0])) {\n return;\n }\n\n second(...args);\n } as (...args: A) => void;\n}\n\n// Stable no-op for fast path\nfunction noop() {}\n","/**\n * mergeProps\n *\n * Deterministic props merging.\n * - For non-handlers: `base` overwrites `injected`.\n * - For handlers present in both: handlers are composed with `injected` running\n * first; it may call `preventDefault()` to suppress the `base` handler.\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Merge Strategy\n * Base props overwrite injected props (base wins).\n * Exception: Event handlers are composed, not overwritten.\n *\n * 2. Event Handler Detection\n * Keys starting with \"on\" are treated as event handlers.\n * This matches JSX conventions.\n *\n * 3. Handler Composition Order\n * Injected handler runs first, base handler second.\n * This allows injected handlers to prevent default.\n *\n * 4. Return Type\n * Returns intersection type (TInjected & TBase) for type safety.\n */\nimport { composeHandlers } from './composeHandlers';\n\ntype Fn = (...args: readonly unknown[]) => void;\n\nfunction isEventHandlerKey(key: string): boolean {\n return key.startsWith('on');\n}\n\nexport function mergeProps<TBase extends object, TInjected extends object>(\n base: TBase,\n injected: TInjected\n): TInjected & TBase {\n // Fast path: if base is empty, return injected as-is\n const baseKeys = Object.keys(base);\n if (baseKeys.length === 0) {\n return injected as TInjected & TBase;\n }\n\n const out = { ...(injected as object) } as TInjected & TBase;\n\n for (const key of baseKeys as Array<Extract<keyof TBase, string>>) {\n const baseValue = (base as Record<string, unknown>)[key];\n const injectedValue = (injected as Record<string, unknown>)[key];\n\n if (\n isEventHandlerKey(key) &&\n typeof baseValue === 'function' &&\n typeof injectedValue === 'function'\n ) {\n // Invariant: injected runs first; it may call preventDefault() to\n // suppress base behaviour.\n (out as Record<string, unknown>)[key] = composeHandlers(\n injectedValue as unknown as Fn,\n baseValue as unknown as Fn\n );\n continue;\n }\n\n (out as Record<string, unknown>)[key] = baseValue;\n }\n\n return out;\n}\n","/**\n * Tiny aria helpers\n */\n\nexport function ariaDisabled(disabled?: boolean): { 'aria-disabled'?: 'true' } {\n return disabled ? { 'aria-disabled': 'true' } : {};\n}\n\nexport function ariaExpanded(expanded?: boolean): {\n 'aria-expanded'?: 'true' | 'false';\n} {\n return expanded === undefined\n ? {}\n : { 'aria-expanded': String(expanded) as 'true' | 'false' };\n}\n\nexport function ariaSelected(selected?: boolean): {\n 'aria-selected'?: 'true' | 'false';\n} {\n return selected === undefined\n ? {}\n : { 'aria-selected': String(selected) as 'true' | 'false' };\n}\n","/**\n * Ref composition utilities\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Ref Types Supported\n * - Callback refs: (value: T | null) => void\n * - Object refs: { current: T | null }\n * - null/undefined (no-op)\n *\n * 2. Write Failure Handling\n * setRef catches write failures (readonly refs) and ignores them.\n * This is intentional — refs may be readonly in some contexts.\n *\n * 3. Composition Order\n * composeRefs applies refs in array order (left to right).\n * All refs are called even if one fails.\n */\n\nexport type Ref<T> =\n | ((value: T | null) => void)\n | { current: T | null }\n | null\n | undefined;\n\nexport function setRef<T>(ref: Ref<T>, value: T | null): void {\n if (!ref) return;\n if (typeof ref === 'function') {\n ref(value);\n return;\n }\n try {\n (ref as { current: T | null }).current = value;\n } catch {\n // Ignore write failures for readonly refs\n }\n}\n\nexport function composeRefs<T>(\n ...refs: Array<Ref<T>>\n): (value: T | null) => void {\n return (value: T | null) => {\n for (const ref of refs) setRef(ref, value);\n };\n}\n","export interface UseIdOptions {\n /** Defaults to 'askr' */\n prefix?: string;\n /** Stable, caller-provided identity */\n id: string | number;\n}\n\n/**\n * useId\n *\n * Formats a stable ID from a caller-provided identity.\n * - Pure and deterministic (no time/randomness/global counters)\n * - SSR-safe\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. No Auto-Generation\n * Caller must provide the `id`. No random/sequential generation.\n * This ensures determinism and SSR safety.\n *\n * 2. Format Convention\n * IDs are formatted as `{prefix}-{id}`.\n * Default prefix is \"askr\".\n *\n * 3. Type Coercion\n * Numbers are coerced to strings via String().\n * This is deterministic and consistent.\n */\nexport function useId(options: UseIdOptions): string {\n const prefix = options.prefix ?? 'askr';\n return `${prefix}-${String(options.id)}`;\n}\n","/**\n * Invariant assertion utilities for correctness checking\n * Production-safe: invariants are enforced at build-time or with minimal overhead\n *\n * Core principle: fail fast when invariants are violated\n * All functions throw descriptive errors for debugging\n */\n\n/**\n * Assert a condition; throw with context if false\n * @internal\n */\nexport function invariant(\n condition: boolean,\n message: string,\n context?: Record<string, unknown>\n): asserts condition {\n if (!condition) {\n const contextStr = context ? '\\n' + JSON.stringify(context, null, 2) : '';\n throw new Error(`[Askr Invariant] ${message}${contextStr}`);\n }\n}\n\n/**\n * Assert object property exists and has correct type\n * @internal\n */\nexport function assertProperty<T extends object, K extends keyof T>(\n obj: T,\n prop: K,\n expectedType?: string\n): asserts obj is T & Required<Pick<T, K>> {\n invariant(prop in obj, `Object missing required property '${String(prop)}'`, {\n object: obj,\n });\n\n if (expectedType) {\n const actualType = typeof obj[prop];\n invariant(\n actualType === expectedType,\n `Property '${String(prop)}' has type '${actualType}', expected '${expectedType}'`,\n { value: obj[prop], expectedType }\n );\n }\n}\n\n/**\n * Assert a reference is not null/undefined\n * @internal\n */\nexport function assertDefined<T>(\n value: T | null | undefined,\n message: string\n): asserts value is T {\n invariant(value !== null && value !== undefined, message, { value });\n}\n\n/**\n * Assert a task runs exactly once atomically\n * Useful for verifying lifecycle events fire precisely when expected\n * @internal\n */\nexport class Once {\n private called = false;\n private calledAt: number | null = null;\n readonly name: string;\n\n constructor(name: string) {\n this.name = name;\n }\n\n check(): boolean {\n return this.called;\n }\n\n mark(): void {\n invariant(\n !this.called,\n `${this.name} called multiple times (previously at ${this.calledAt}ms)`,\n { now: Date.now() }\n );\n this.called = true;\n this.calledAt = Date.now();\n }\n\n reset(): void {\n this.called = false;\n this.calledAt = null;\n }\n}\n\n/**\n * Assert a value falls in an enumerated set\n * @internal\n */\nexport function assertEnum<T extends readonly unknown[]>(\n value: unknown,\n allowedValues: T,\n fieldName: string\n): asserts value is T[number] {\n invariant(\n allowedValues.includes(value),\n `${fieldName} must be one of [${allowedValues.join(', ')}], got ${JSON.stringify(value)}`,\n { value, allowed: allowedValues }\n );\n}\n\n/**\n * Assert execution context (scheduler, component, etc)\n * @internal\n */\nexport function assertContext(\n actual: unknown,\n expected: unknown,\n contextName: string\n): asserts actual is typeof expected {\n invariant(\n actual === expected,\n `Invalid ${contextName} context. Expected ${expected}, got ${actual}`,\n { expected, actual }\n );\n}\n\n/**\n * Assert scheduling precondition (not reentering, not during render, etc)\n * @internal\n */\nexport function assertSchedulingPrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[Scheduler Precondition] ${violationMessage}`);\n}\n\n/**\n * Assert state precondition\n * @internal\n */\nexport function assertStatePrecondition(\n condition: boolean,\n violationMessage: string\n): asserts condition {\n invariant(condition, `[State Precondition] ${violationMessage}`);\n}\n\n/**\n * Verify AbortController lifecycle\n * @internal\n */\nexport function assertAbortControllerState(\n signal: AbortSignal,\n expectedAborted: boolean,\n context: string\n): void {\n invariant(\n signal.aborted === expectedAborted,\n `AbortSignal ${expectedAborted ? 'should be' : 'should not be'} aborted in ${context}`,\n { actual: signal.aborted, expected: expectedAborted }\n );\n}\n\n/**\n * Guard: throw if callback is null when it shouldn't be\n * Used for notifyUpdate, event handlers, etc.\n * @internal\n */\nexport function assertCallbackAvailable<\n T extends (...args: unknown[]) => unknown,\n>(callback: T | null | undefined, callbackName: string): asserts callback is T {\n invariant(\n callback !== null && callback !== undefined,\n `${callbackName} callback is required but not available`,\n { callback }\n );\n}\n\n/**\n * Verify evaluation generation prevents stale evaluations\n * @internal\n */\nexport function assertEvaluationGeneration(\n current: number,\n latest: number,\n context: string\n): void {\n invariant(\n current === latest,\n `Stale evaluation generation in ${context}: current ${current}, latest ${latest}`,\n { current, latest }\n );\n}\n\n/**\n * Verify mounted flag state\n * @internal\n */\nexport function assertMountedState(\n mounted: boolean,\n expectedMounted: boolean,\n context: string\n): void {\n invariant(\n mounted === expectedMounted,\n `Invalid mounted state in ${context}: expected ${expectedMounted}, got ${mounted}`,\n { mounted, expected: expectedMounted }\n );\n}\n\n/**\n * Verify no null target when rendering\n * @internal\n */\nexport function assertRenderTarget(\n target: Element | null,\n context: string\n): asserts target is Element {\n invariant(target !== null, `Cannot render in ${context}: target is null`, {\n target,\n });\n}\n","/**\n * Centralized logger interface\n * - Keeps production builds silent for debug/warn/info messages\n * - Ensures consistent behavior across the codebase\n * - Protects against missing `console` in some environments\n */\n\nfunction callConsole(method: string, args: unknown[]): void {\n const c = typeof console !== 'undefined' ? (console as unknown) : undefined;\n if (!c) return;\n const fn = (c as Record<string, unknown>)[method];\n if (typeof fn === 'function') {\n try {\n (fn as (...a: unknown[]) => unknown).apply(console, args as unknown[]);\n } catch {\n // ignore logging errors\n }\n }\n}\n\nexport const logger = {\n debug: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('debug', args);\n },\n\n info: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('info', args);\n },\n\n warn: (...args: unknown[]) => {\n if (process.env.NODE_ENV === 'production') return;\n callConsole('warn', args);\n },\n\n error: (...args: unknown[]) => {\n callConsole('error', args);\n },\n};\n","/**\n * Serialized update scheduler — safer design (no inline execution, explicit flush)\n *\n * Key ideas:\n * - Never execute a task inline from `enqueue`.\n * - `flush()` is explicit and non-reentrant.\n * - `runWithSyncProgress()` allows enqueues temporarily but does not run tasks\n * inline; it runs `fn` and then does an explicit `flush()`.\n * - `waitForFlush()` is race-free with a monotonic `flushVersion`.\n */\n\nimport { assertSchedulingPrecondition, invariant } from '../dev/invariant';\nimport { logger } from '../dev/logger';\n\nconst MAX_FLUSH_DEPTH = 50;\n\ntype Task = () => void;\n\nfunction isBulkCommitActive(): boolean {\n try {\n const fb = (\n globalThis as {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private q: Task[] = [];\n private head = 0;\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n enqueue(task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (process.env.NODE_ENV !== 'production') {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.q.push(task);\n this.taskCount++;\n\n // Microtask kick: best-effort, but avoid if we are in handler or running or bulk commit\n if (\n !this.running &&\n !this.kickScheduled &&\n !this.inHandler &&\n !isBulkCommitActive()\n ) {\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running) return;\n if (isBulkCommitActive()) return;\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (process.env.NODE_ENV !== 'production') {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n\n try {\n while (this.head < this.q.length) {\n this.depth++;\n if (\n process.env.NODE_ENV !== 'production' &&\n this.depth > MAX_FLUSH_DEPTH\n ) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = this.q[this.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n } catch (err) {\n // ensure executionDepth stays balanced\n if (this.executionDepth > 0) this.executionDepth = 0;\n fatal = err;\n break;\n }\n\n // Account for executed task in taskCount\n if (this.taskCount > 0) this.taskCount--;\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n // Compact queue\n if (this.head >= this.q.length) {\n this.q.length = 0;\n this.head = 0;\n } else if (this.head > 0) {\n const remaining = this.q.length - this.head;\n // HOT PATH: compact in-place to avoid slice() allocations (GC tail spikes)\n for (let i = 0; i < remaining; i++) {\n this.q[i] = this.q[this.head + i];\n }\n this.q.length = remaining;\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 * 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' || key === 'ref';\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 for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {\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 * 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 { logger } from '../dev/logger';\nimport type { ComponentInstance } from './component';\nimport {\n getKeyMapForElement,\n isKeyedReorderFastPathEligible,\n populateKeyMapForElement,\n} from '../renderer/keyed';\nimport { Fragment } from '../common/jsx';\nimport { setDevValue, getDevValue } 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\nfunction 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 { _readers?: Map<ComponentInstance, number> })\n ._readers;\n if (readers) readers.delete(instance);\n }\n }\n\n // Commit token becomes the authoritative token for this instance's last render\n instance.lastRenderToken = token;\n\n // Record subscriptions for states read during this render\n for (const s of newSet) {\n let readers = (s as { _readers?: Map<ComponentInstance, number> })._readers;\n if (!readers) {\n readers = new Map();\n (s as { _readers?: Map<ComponentInstance, number> })._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\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","/**\n * State primitive for Askr components\n * Optimized for minimal overhead and fast updates\n *\n * INVARIANTS ENFORCED:\n * - state() only callable during component render (currentInstance exists)\n * - state() called at top-level only (indices must be monotonically increasing)\n * - state values persist across re-renders (stored in stateValues array)\n * - state.set() cannot be called during render (causes infinite loops)\n * - state.set() always enqueues through scheduler (never direct mutation)\n * - state.set() callback (notifyUpdate) always available\n */\n\nimport { globalScheduler } from './scheduler';\nimport {\n getCurrentInstance,\n getNextStateIndex,\n type ComponentInstance,\n} from './component';\nimport { invariant } from '../dev/invariant';\nimport { isBulkCommitActive } from './fastlane';\n\n/**\n * State value holder - callable to read, has set method to update\n * @example\n * const count = state(0);\n * count(); // read: 0\n * count.set(1); // write: triggers re-render\n */\nexport interface State<T> {\n (): T;\n set(value: T): void;\n 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 const currentInst = getCurrentInstance();\n if (currentInst !== null) {\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 // 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","/**\n * controllable\n *\n * Small utilities for controlled vs uncontrolled components. These helpers are\n * intentionally minimal and do not manage state themselves; they help component\n * implementations make correct decisions about when to call `onChange` vs\n * update internal state.\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Controlled Detection\n * A value is \"controlled\" if it is not `undefined`.\n * This matches React conventions and is SSR-safe.\n *\n * 2. onChange Timing\n * - Controlled mode: onChange called immediately, no internal update\n * - Uncontrolled mode: internal state updated first, then onChange called\n * This ensures onChange sees the new value in both modes.\n *\n * 3. Value Equality\n * controllableState uses Object.is() to prevent unnecessary onChange calls.\n * This is intentional — strict equality, no deep comparison.\n */\n\nimport { state, type State } from '../../runtime/state';\n\nexport function isControlled<T>(value: T | undefined): value is T {\n return value !== undefined;\n}\n\nexport function resolveControllable<T>(\n value: T | undefined,\n defaultValue: T\n): { value: T; isControlled: boolean } {\n const controlled = isControlled(value);\n return {\n value: controlled ? (value as T) : defaultValue,\n isControlled: controlled,\n };\n}\n\nexport function makeControllable<T>(options: {\n value: T | undefined;\n defaultValue: T;\n onChange?: (next: T) => void;\n setInternal?: (next: T) => void;\n}) {\n const { value, defaultValue, onChange, setInternal } = options;\n const { isControlled } = resolveControllable(value, defaultValue);\n\n function set(next: T) {\n if (isControlled) {\n onChange?.(next);\n } else {\n setInternal?.(next);\n onChange?.(next);\n }\n }\n\n return { set, isControlled };\n}\n\nexport type ControllableState<T> = State<T> & { isControlled: boolean };\n\n/**\n * controllableState\n *\n * Hook-like primitive that mirrors `state()` semantics while supporting\n * controlled/uncontrolled behavior.\n */\nexport function controllableState<T>(options: {\n value: T | undefined;\n defaultValue: T;\n onChange?: (next: T) => void;\n}): ControllableState<T> {\n const internal = state<T>(options.defaultValue);\n const isControlled = options.value !== undefined;\n\n function read(): T {\n return isControlled ? (options.value as T) : internal();\n }\n\n read.set = (nextOrUpdater: T | ((prev: T) => T)) => {\n const prev = read();\n const next =\n typeof nextOrUpdater === 'function'\n ? (nextOrUpdater as (p: T) => T)(prev)\n : (nextOrUpdater as T);\n\n if (Object.is(prev, next)) return;\n\n if (isControlled) {\n options.onChange?.(next);\n return;\n }\n\n internal.set(nextOrUpdater as never);\n options.onChange?.(next);\n };\n\n (read as ControllableState<T>).isControlled = isControlled;\n return read as ControllableState<T>;\n}\n","/**\n * pressable\n *\n * Interaction helper that produces VNode props for 'press' semantics.\n * - Pure and deterministic: no DOM construction or mutation here\n * - The runtime owns event attachment and scheduling\n * - This helper returns plain props (handlers) intended to be attached by the runtime\n *\n * Behaviour:\n * - For native buttons: only an `onClick` prop is provided (no ARIA or keyboard shims)\n * - For non-button elements: add `role=\"button\"` and `tabIndex` and keyboard handlers\n * - Activation: `Enter` activates on keydown, `Space` activates on keyup (matches native button)\n * - Disabled: handlers short-circuit and `aria-disabled` is set for all hosts\n *\n * POLICY DECISIONS (LOCKED):\n *\n * 1. Activation Timing (Platform Parity)\n * - Enter fires on keydown (immediate response)\n * - Space fires on keyup (allows cancel by moving focus, matches native)\n * - Space keydown prevents scroll (matches native button behavior)\n *\n * 2. Disabled Enforcement Strategy\n * - Native buttons: Use HTML `disabled` attribute (platform-enforced non-interactivity)\n * AND `aria-disabled` (consistent a11y signaling)\n * - Non-native: Use `tabIndex=-1` (removes from tab order)\n * AND `aria-disabled` (signals disabled state to AT)\n * - Click handler short-circuits as defense-in-depth (prevents leaked focus issues)\n *\n * 3. Key Repeat Behavior\n * - Held Enter/Space will fire onPress repeatedly (matches native button)\n * - No debouncing or repeat prevention (platform parity)\n */\n\nexport interface PressableOptions {\n disabled?: boolean;\n onPress?: (e: PressEvent) => void;\n /**\n * Whether the host is a native button. Defaults to false.\n */\n isNativeButton?: boolean;\n}\n\nimport type {\n DefaultPreventable,\n KeyboardLikeEvent,\n PropagationStoppable,\n} from '../utilities/eventTypes';\nimport { ariaDisabled } from '../utilities/aria';\n\ntype PressEvent = DefaultPreventable & PropagationStoppable;\n\nexport interface PressableResult {\n onClick: (e: PressEvent) => void;\n disabled?: true;\n role?: 'button';\n tabIndex?: number;\n onKeyDown?: (e: KeyboardLikeEvent) => void;\n onKeyUp?: (e: KeyboardLikeEvent) => void;\n 'aria-disabled'?: 'true';\n}\n\nexport function pressable({\n disabled,\n onPress,\n isNativeButton = false,\n}: PressableOptions): PressableResult {\n const props: PressableResult = {\n onClick: (e) => {\n if (disabled) {\n e.preventDefault?.();\n e.stopPropagation?.();\n return;\n }\n onPress?.(e);\n },\n };\n\n if (isNativeButton) {\n if (disabled) {\n props.disabled = true;\n Object.assign(props, ariaDisabled(disabled));\n }\n return props;\n }\n\n props.role = 'button';\n props.tabIndex = disabled ? -1 : 0;\n\n props.onKeyDown = (e) => {\n if (disabled) {\n e.preventDefault?.();\n e.stopPropagation?.();\n return;\n }\n\n if (e.key === 'Enter') {\n e.preventDefault?.();\n onPress?.(e);\n return;\n }\n\n if (e.key === ' ') {\n // Prevent scrolling while Space is held.\n e.preventDefault?.();\n }\n };\n\n props.onKeyUp = (e) => {\n if (disabled) {\n e.preventDefault?.();\n e.stopPropagation?.();\n return;\n }\n if (e.key === ' ') {\n e.preventDefault?.();\n onPress?.(e);\n }\n };\n\n if (disabled) Object.assign(props, ariaDisabled(disabled));\n return props;\n}\n","/**\n * dismissable\n *\n * Provides props and helpers to support dismissal behaviour. This helper is\n * runtime-agnostic:\n * - It returns `onKeyDown` prop which will call onDismiss when Escape is\n * pressed.\n * - It also provides `outsideListener` factory which given an `isInside`\n * predicate returns a handler suitable to attach at the document level that\n * will call onDismiss when the pointerdown target is outside the component.\n */\n\nexport interface DismissableOptions {\n onDismiss?: () => void;\n disabled?: boolean;\n}\n\nimport type {\n KeyboardLikeEvent,\n PointerLikeEvent,\n} from '../utilities/eventTypes';\n\nexport function dismissable({ onDismiss, disabled }: DismissableOptions) {\n return {\n // Prop for the component root to handle Escape\n onKeyDown: disabled\n ? undefined\n : (e: KeyboardLikeEvent) => {\n if (e.key === 'Escape') {\n e.preventDefault?.();\n e.stopPropagation?.();\n onDismiss?.();\n }\n },\n\n // Factory: runtime should attach this listener at the appropriate scope.\n outsideListener: disabled\n ? undefined\n : (isInside: (target: unknown) => boolean) => (e: PointerLikeEvent) => {\n if (!isInside(e.target)) {\n e.preventDefault?.();\n e.stopPropagation?.();\n onDismiss?.();\n }\n },\n };\n}\n","/**\n * focusable\n *\n * Normalize focus-related props for hosts.\n * - No DOM manipulation here; returns props that the runtime may attach.\n */\n\nimport { ariaDisabled } from '../utilities/aria';\n\nexport interface FocusableOptions {\n disabled?: boolean;\n tabIndex?: number | undefined;\n}\n\nexport interface FocusableResult {\n tabIndex?: number;\n 'aria-disabled'?: 'true';\n}\n\nexport function focusable({\n disabled,\n tabIndex,\n}: FocusableOptions): FocusableResult {\n return {\n tabIndex: disabled ? -1 : tabIndex === undefined ? 0 : tabIndex,\n ...ariaDisabled(disabled),\n };\n}\n","/**\n * hoverable\n *\n * Produces props for pointer enter/leave handling. Pure and deterministic.\n */\n\nexport interface HoverableOptions {\n disabled?: boolean;\n onEnter?: (e: HoverEvent) => void;\n onLeave?: (e: HoverEvent) => void;\n}\n\nimport type {\n DefaultPreventable,\n PropagationStoppable,\n} from '../utilities/eventTypes';\n\ntype HoverEvent = DefaultPreventable & PropagationStoppable;\n\nexport interface HoverableResult {\n onPointerEnter?: (e: HoverEvent) => void;\n onPointerLeave?: (e: HoverEvent) => void;\n}\n\nexport function hoverable({\n disabled,\n onEnter,\n onLeave,\n}: HoverableOptions): HoverableResult {\n return {\n onPointerEnter: disabled\n ? undefined\n : (e) => {\n onEnter?.(e);\n },\n onPointerLeave: disabled\n ? undefined\n : (e) => {\n onLeave?.(e);\n },\n };\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as ComponentFunction } from './component-
|
|
2
|
-
export { S as State, s as state } from './component-
|
|
1
|
+
import { C as ComponentFunction } from './component-DHAn9JxU.js';
|
|
2
|
+
export { S as State, s as state } from './component-DHAn9JxU.js';
|
|
3
3
|
import { R as Route } from './router-DaGtH1Sq.js';
|
|
4
|
-
export { P as Props } from './jsx-
|
|
4
|
+
export { P as Props } from './jsx-CSWf4VFg.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* App bootstrap and mount
|