@askrjs/askr 0.0.5 → 0.0.6

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.
@@ -0,0 +1,177 @@
1
+ import { P as Props, J as JSXElement } from './jsx-AzPM8gMS.js';
2
+
3
+ /**
4
+ * State primitive for Askr components
5
+ * Optimized for minimal overhead and fast updates
6
+ *
7
+ * INVARIANTS ENFORCED:
8
+ * - state() only callable during component render (currentInstance exists)
9
+ * - state() called at top-level only (indices must be monotonically increasing)
10
+ * - state values persist across re-renders (stored in stateValues array)
11
+ * - state.set() cannot be called during render (causes infinite loops)
12
+ * - state.set() always enqueues through scheduler (never direct mutation)
13
+ * - state.set() callback (notifyUpdate) always available
14
+ */
15
+
16
+ /**
17
+ * State value holder - callable to read, has set method to update
18
+ * @example
19
+ * const count = state(0);
20
+ * count(); // read: 0
21
+ * count.set(1); // write: triggers re-render
22
+ */
23
+ interface State<T> {
24
+ (): T;
25
+ set(value: T): void;
26
+ set(updater: (prev: T) => T): void;
27
+ _hasBeenRead?: boolean;
28
+ _readers?: Map<ComponentInstance, number>;
29
+ }
30
+ /**
31
+ * Creates a local state value for a component
32
+ * Optimized for:
33
+ * - O(1) read performance
34
+ * - Minimal allocation per state
35
+ * - Fast scheduler integration
36
+ *
37
+ * IMPORTANT: state() must be called during component render execution.
38
+ * It captures the current component instance from context.
39
+ * Calling outside a component function will throw an error.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * // ✅ Correct: called during render
44
+ * export function Counter() {
45
+ * const count = state(0);
46
+ * return { type: 'button', children: [count()] };
47
+ * }
48
+ *
49
+ * // ❌ Wrong: called outside component
50
+ * const count = state(0);
51
+ * export function BadComponent() {
52
+ * return { type: 'div' };
53
+ * }
54
+ * ```
55
+ */
56
+ declare function state<T>(initialValue: T): State<T>;
57
+
58
+ /**
59
+ * Common call contracts: Component signatures
60
+ */
61
+
62
+ type ComponentContext = {
63
+ signal: AbortSignal;
64
+ };
65
+ type ComponentVNode = {
66
+ type: string;
67
+ props?: Props;
68
+ children?: (string | ComponentVNode | null | undefined | false)[];
69
+ };
70
+ type ComponentFunction = (props: Props, context?: ComponentContext) => JSXElement | ComponentVNode | string | number | null;
71
+
72
+ /**
73
+ * Context system: lexical scope + render-time snapshots
74
+ *
75
+ * CORE SEMANTIC (Option A — Snapshot-Based):
76
+ * ============================================
77
+ * An async resource observes the context of the render that created it.
78
+ * Context changes only take effect via re-render, not magically mid-await.
79
+ *
80
+ * This ensures:
81
+ * - Deterministic behavior
82
+ * - Concurrency safety
83
+ * - Replayable execution
84
+ * - Debuggability
85
+ *
86
+ * INVARIANTS:
87
+ * - readContext() only works during component render (has currentContextFrame)
88
+ * - Each render captures a context snapshot
89
+ * - Async continuations see the snapshot from render start (frozen)
90
+ * - Provider (Scope) creates a new frame that shadows parent
91
+ * - Context updates require re-render to take effect
92
+ */
93
+
94
+ type ContextKey = symbol;
95
+ interface ContextFrame {
96
+ parent: ContextFrame | null;
97
+ values: Map<ContextKey, unknown> | null;
98
+ }
99
+
100
+ /**
101
+ * Component instance lifecycle management
102
+ * Internal only — users never see this
103
+ */
104
+
105
+ interface ComponentInstance {
106
+ id: string;
107
+ fn: ComponentFunction;
108
+ props: Props;
109
+ target: Element | null;
110
+ mounted: boolean;
111
+ abortController: AbortController;
112
+ ssr?: boolean;
113
+ cleanupStrict?: boolean;
114
+ stateValues: State<unknown>[];
115
+ evaluationGeneration: number;
116
+ notifyUpdate: (() => void) | null;
117
+ _pendingFlushTask?: () => void;
118
+ _pendingRunTask?: () => void;
119
+ _enqueueRun?: () => void;
120
+ stateIndexCheck: number;
121
+ expectedStateIndices: number[];
122
+ firstRenderComplete: boolean;
123
+ mountOperations: Array<() => void | (() => void) | Promise<void | (() => void)>>;
124
+ cleanupFns: Array<() => void>;
125
+ hasPendingUpdate: boolean;
126
+ ownerFrame: ContextFrame | null;
127
+ isRoot?: boolean;
128
+ _currentRenderToken?: number;
129
+ lastRenderToken?: number;
130
+ _pendingReadStates?: Set<State<unknown>>;
131
+ _lastReadStates?: Set<State<unknown>>;
132
+ _placeholder?: Comment;
133
+ }
134
+ /**
135
+ * Get the abort signal for the current component
136
+ * Used to cancel async operations on unmount/navigation
137
+ *
138
+ * The signal is guaranteed to be aborted when:
139
+ * - Component unmounts
140
+ * - Navigation occurs (different route)
141
+ * - Parent is destroyed
142
+ *
143
+ * IMPORTANT: getSignal() must be called during component render execution.
144
+ * It captures the current component instance from context.
145
+ *
146
+ * @returns AbortSignal that will be aborted when component unmounts
147
+ * @throws Error if called outside component execution
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * // ✅ Correct: called during render, used in async operation
152
+ * export async function UserPage({ id }: { id: string }) {
153
+ * const signal = getSignal();
154
+ * const user = await fetch(`/api/users/${id}`, { signal });
155
+ * return <div>{user.name}</div>;
156
+ * }
157
+ *
158
+ * // ✅ Correct: passed to event handler
159
+ * export function Button() {
160
+ * const signal = getSignal();
161
+ * return {
162
+ * type: 'button',
163
+ * props: {
164
+ * onClick: async () => {
165
+ * const data = await fetch(url, { signal });
166
+ * }
167
+ * }
168
+ * };
169
+ * }
170
+ *
171
+ * // ❌ Wrong: called outside component context
172
+ * const signal = getSignal(); // Error: not in component
173
+ * ```
174
+ */
175
+ declare function getSignal(): AbortSignal;
176
+
177
+ export { type ComponentFunction as C, type State as S, getSignal as g, state as s };
@@ -0,0 +1,32 @@
1
+ export { L as LayoutComponent, l as layout } from '../layout-D5MqtW_q.js';
2
+ import '../types-uOPfcrdz.js';
3
+ import { J as JSXElement } from '../jsx-AzPM8gMS.js';
4
+
5
+ type SlotProps = {
6
+ asChild: true;
7
+ children: JSXElement;
8
+ [key: string]: unknown;
9
+ } | {
10
+ asChild?: false;
11
+ children?: unknown;
12
+ };
13
+ declare function Slot(props: SlotProps): JSXElement | null;
14
+
15
+ /**
16
+ * Portal / Host primitive.
17
+ *
18
+ * A portal is a named render slot within the existing tree.
19
+ * It does NOT create a second tree or touch the DOM directly.
20
+ */
21
+ interface Portal<T = unknown> {
22
+ /** Mount point — rendered exactly once */
23
+ (): unknown;
24
+ /** Render content into the portal */
25
+ render(props: {
26
+ children?: T;
27
+ }): unknown;
28
+ }
29
+ declare function definePortal<T = unknown>(): Portal<T>;
30
+ declare const DefaultPortal: Portal<unknown>;
31
+
32
+ export { DefaultPortal, JSXElement, type Portal, Slot, type SlotProps, definePortal };
@@ -0,0 +1,146 @@
1
+ // src/foundations/layout.tsx
2
+ function layout(Layout) {
3
+ return (children, props) => Layout({ ...props, children });
4
+ }
5
+
6
+ // src/dev/logger.ts
7
+ function callConsole(method, args) {
8
+ const c = typeof console !== "undefined" ? console : void 0;
9
+ if (!c) return;
10
+ const fn = c[method];
11
+ if (typeof fn === "function") {
12
+ try {
13
+ fn.apply(console, args);
14
+ } catch {
15
+ }
16
+ }
17
+ }
18
+ var logger = {
19
+ debug: (...args) => {
20
+ if (process.env.NODE_ENV === "production") return;
21
+ callConsole("debug", args);
22
+ },
23
+ info: (...args) => {
24
+ if (process.env.NODE_ENV === "production") return;
25
+ callConsole("info", args);
26
+ },
27
+ warn: (...args) => {
28
+ if (process.env.NODE_ENV === "production") return;
29
+ callConsole("warn", args);
30
+ },
31
+ error: (...args) => {
32
+ callConsole("error", args);
33
+ }
34
+ };
35
+
36
+ // src/common/jsx.ts
37
+ var ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("askr.element");
38
+ var Fragment = /* @__PURE__ */ Symbol.for("askr.fragment");
39
+
40
+ // src/jsx/utils.ts
41
+ function isElement(value) {
42
+ return typeof value === "object" && value !== null && value.$$typeof === ELEMENT_TYPE;
43
+ }
44
+ function cloneElement(element, props) {
45
+ return {
46
+ ...element,
47
+ props: { ...element.props, ...props }
48
+ };
49
+ }
50
+
51
+ // src/foundations/slot.tsx
52
+ function Slot(props) {
53
+ if (props.asChild) {
54
+ const { children, ...rest } = props;
55
+ if (isElement(children)) {
56
+ return cloneElement(children, rest);
57
+ }
58
+ logger.warn("<Slot asChild> expects a single JSX element child.");
59
+ return null;
60
+ }
61
+ return {
62
+ $$typeof: ELEMENT_TYPE,
63
+ type: Fragment,
64
+ props: { children: props.children }
65
+ };
66
+ }
67
+
68
+ // src/runtime/component.ts
69
+ var currentInstance = null;
70
+ function getCurrentComponentInstance() {
71
+ return currentInstance;
72
+ }
73
+
74
+ // src/foundations/portal.tsx
75
+ function definePortal() {
76
+ if (typeof createPortalSlot !== "function") {
77
+ let HostFallback2 = function() {
78
+ const inst = getCurrentComponentInstance();
79
+ if (process.env.NODE_ENV !== "production") {
80
+ const ns = globalThis.__ASKR__ || (globalThis.__ASKR__ = {});
81
+ ns.__PORTAL_READS = (ns.__PORTAL_READS || 0) + 1;
82
+ }
83
+ if (process.env.NODE_ENV !== "production") ;
84
+ return inst && owner && inst === owner ? pending : void 0;
85
+ };
86
+ let owner = null;
87
+ let pending;
88
+ HostFallback2.render = function RenderFallback(props) {
89
+ return null;
90
+ };
91
+ return HostFallback2;
92
+ }
93
+ const slot = createPortalSlot();
94
+ function PortalHost() {
95
+ return slot.read();
96
+ }
97
+ PortalHost.render = function PortalRender(props) {
98
+ if (process.env.NODE_ENV !== "production") {
99
+ const ns = globalThis.__ASKR__ || (globalThis.__ASKR__ = {});
100
+ ns.__PORTAL_WRITES = (ns.__PORTAL_WRITES || 0) + 1;
101
+ }
102
+ slot.write(props.children);
103
+ return null;
104
+ };
105
+ return PortalHost;
106
+ }
107
+ var _defaultPortal;
108
+ var _defaultPortalIsFallback = false;
109
+ function ensureDefaultPortal() {
110
+ if (!_defaultPortal) {
111
+ if (typeof createPortalSlot === "function") {
112
+ _defaultPortal = definePortal();
113
+ _defaultPortalIsFallback = false;
114
+ } else {
115
+ _defaultPortal = definePortal();
116
+ _defaultPortalIsFallback = true;
117
+ }
118
+ return _defaultPortal;
119
+ }
120
+ if (_defaultPortalIsFallback && typeof createPortalSlot === "function") {
121
+ const real = definePortal();
122
+ _defaultPortal = real;
123
+ _defaultPortalIsFallback = false;
124
+ }
125
+ if (!_defaultPortalIsFallback && typeof createPortalSlot !== "function") {
126
+ const fallback = definePortal();
127
+ _defaultPortal = fallback;
128
+ _defaultPortalIsFallback = true;
129
+ }
130
+ return _defaultPortal;
131
+ }
132
+ var DefaultPortal = (() => {
133
+ function Host() {
134
+ const v = ensureDefaultPortal()();
135
+ return v === void 0 ? null : v;
136
+ }
137
+ Host.render = function Render(props) {
138
+ ensureDefaultPortal().render(props);
139
+ return null;
140
+ };
141
+ return Host;
142
+ })();
143
+
144
+ export { DefaultPortal, Slot, definePortal, layout };
145
+ //# sourceMappingURL=index.js.map
146
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,OAAA,KAAY,WAAA,GAAe,OAAA,GAAsB,MAAA;AAClE,EAAA,IAAI,CAAC,CAAA,EAAG;AACR,EAAA,MAAM,EAAA,GAAM,EAA8B,MAAM,CAAA;AAChD,EAAA,IAAI,OAAO,OAAO,UAAA,EAAY;AAC5B,IAAA,IAAI;AACF,MAAC,EAAA,CAAoC,KAAA,CAAM,OAAA,EAAS,IAAiB,CAAA;AAAA,IACvE,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEO,IAAM,MAAA,GAAS;AAAA,EACpB,KAAA,EAAO,IAAI,IAAA,KAAoB;AAC7B,IAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA,EAAc;AAC3C,IAAA,WAAA,CAAY,S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AAoB,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"]}
@@ -632,5 +632,5 @@ function scheduleRetry(fn, options) {
632
632
  }
633
633
 
634
634
  export { debounce, debounceEvent, defer, idle, once, raf, rafEvent, retry, scheduleIdle, scheduleRetry, scheduleTimeout, throttle, throttleEvent, timeout };
635
- //# sourceMappingURL=fx.js.map
636
- //# sourceMappingURL=fx.js.map
635
+ //# sourceMappingURL=index.js.map
636
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/fx/timing.ts","../../src/dev/invariant.ts","../../src/dev/logger.ts","../../src/runtime/schedu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;AACb,MAAA,CAAA,CAAE,IAAA;AAAA,QACA,MAAM;AAAA,QAEN,CAAA;AAAA,QACA,MAAM;AACJ,UAAA,IAAI,SAAA,EAAW;AACf,UAAA,IAAI,KAAA,GAAQ,IAAI,WAAA,EAAa;AAC3B,YAAA,MAAM,KAAA,GAAQ,QAAQ,KAAK,CAAA;AAE3B,YAAA,UAAA,CAAW,MAAM;AACf,cAAA,OAAA,CAAQ,QAAQ,CAAC,CAAA;AAAA,YACnB,GAAG,KAAK,CAAA;AAAA,UACV;AAAA,QACF;AAAA,OACF,CAAE,KAAA,CAAM,CAAC,CAAA,KAAM;AACb,QAAA,MAAA,CAAO,KAAA,CAAM,+BAA+B,CAAC,CAAA;AAAA,MAC/C,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH,CAAA;AAGA,EAAA,OAAA,CAAQ,CAAC,CAAA;AAET,EAAA,MAAM,SAAS,MAAM;AACnB,IAAA,SAAA,GAAY,IAAA;AAAA,EACd,CAAA;AAGA,EAAA,OAAO,EAAE,MAAA,EAAO;AAClB","file":"index.js","sourcesContent":["/**\n * Timing utilities — pure helpers for common async patterns\n * No framework coupling. No lifecycle awareness.\n */\n\nexport interface DebounceOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\nexport interface ThrottleOptions {\n leading?: boolean;\n trailing?: boolean;\n}\n\nexport interface RetryOptions {\n maxAttempts?: number;\n delayMs?: number;\n backoff?: (attemptIndex: number) => number;\n}\n\n/**\n * Debounce — delay execution, coalesce rapid calls\n *\n * Useful for: text input, resize, autosave\n *\n * @param fn Function to debounce\n * @param ms Delay in milliseconds\n * @param options trailing (default true), leading\n * @returns Debounced function with cancel() method\n *\n * @example\n * ```ts\n * const save = debounce((text) => api.save(text), 500);\n * input.addEventListener('input', (e) => save(e.target.value));\n * save.cancel(); // stop any pending execution\n * ```\n */\nexport function debounce<T extends (...args: unknown[]) => unknown>(\n fn: T,\n ms: number,\n options?: DebounceOptions\n): T & { cancel(): void } {\n let timeoutId: NodeJS.Timeout | null = null;\n const { leading = false, trailing = true } = options || {};\n let lastArgs: unknown[] | null = null;\n let lastThis: unknown = null;\n let lastCallTime = 0;\n\n const debounced = function (this: unknown, ...args: unknown[]) {\n const callTime = Date.now();\n lastArgs = args;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n lastThis = this;\n\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n }\n\n if (leading && callTime - lastCallTime >= ms) {\n fn.apply(this, args);\n lastCallTime = callTime;\n }\n\n if (trailing) {\n timeoutId = setTimeout(() => {\n fn.apply(lastThis, lastArgs!);\n timeoutId = null;\n lastCallTime = Date.now();\n }, ms);\n }\n };\n\n debounced.cancel = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debounced as T & { cancel(): void };\n}\n\n/**\n * Throttle — rate-limit execution, keep first/last\n *\n * Useful for: scroll, mouse move, high-frequency events\n *\n * @param fn Function to throttle\n * @param ms Minimum interval between calls in milliseconds\n * @param options leading (default true), trailing (default true)\n * @returns Throttled function with cancel() method\n *\n * @example\n * ```ts\n * const handleScroll = throttle(updateUI, 100);\n * window.addEventListener('scroll', handleScroll);\n * handleScroll.cancel();\n * ```\n */\nexport function throttle<T extends (...args: unknown[]) => unknown>(\n fn: T,\n ms: number,\n options?: ThrottleOptions\n): T & { cancel(): void } {\n let lastCallTime = 0;\n let timeoutId: NodeJS.Timeout | null = null;\n const { leading = true, trailing = true } = options || {};\n let lastArgs: unknown[] | null = null;\n let lastThis: unknown = null;\n\n const throttled = function (this: unknown, ...args: unknown[]) {\n const callTime = Date.now();\n lastArgs = args;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n lastThis = this;\n\n if (leading && callTime - lastCallTime >= ms) {\n fn.apply(this, args);\n lastCallTime = callTime;\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n } else if (!leading && lastCallTime === 0) {\n lastCallTime = callTime;\n }\n\n if (trailing && timeoutId === null) {\n timeoutId = setTimeout(\n () => {\n fn.apply(lastThis, lastArgs!);\n lastCallTime = Date.now();\n timeoutId = null;\n },\n ms - (callTime - lastCallTime)\n );\n }\n };\n\n throttled.cancel = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return throttled as T & { cancel(): void };\n}\n\n/**\n * Once — guard against double execution\n *\n * Useful for: init logic, event safety\n *\n * @param fn Function to call at most once\n * @returns Function that executes fn only on first call\n *\n * @example\n * ```ts\n * const init = once(setup);\n * init(); // runs\n * init(); // does nothing\n * init(); // does nothing\n * ```\n */\nexport function once<T extends (...args: unknown[]) => unknown>(fn: T): T {\n let called = false;\n let result: unknown;\n\n return ((...args: unknown[]) => {\n if (!called) {\n called = true;\n result = fn(...args);\n }\n return result;\n }) as T;\n}\n\n/**\n * Defer — schedule on microtask queue\n *\n * Useful for: run-after-current-stack logic\n * More reliable than setTimeout(..., 0)\n *\n * @param fn Function to defer\n *\n * @example\n * ```ts\n * defer(() => update()); // runs after current stack, before next macrotask\n * ```\n */\nexport function defer(fn: () => void): void {\n Promise.resolve().then(fn);\n}\n\n/**\n * RAF — coalesce multiple updates into single frame\n *\n * Useful for: animation, layout work, render updates\n *\n * @param fn Function to schedule on next animation frame\n * @returns Function that schedules fn on requestAnimationFrame\n *\n * @example\n * ```ts\n * const update = raf(render);\n * update(); // schedules on next frame\n * update(); // same frame, no duplicate\n * ```\n */\nexport function raf<T extends (...args: unknown[]) => unknown>(fn: T): T {\n let frameId: number | null = null;\n let lastArgs: unknown[] | null = null;\n let lastThis: unknown = null;\n\n return function (this: unknown, ...args: unknown[]) {\n lastArgs = args;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n lastThis = this;\n\n if (frameId === null) {\n frameId = requestAnimationFrame(() => {\n fn.apply(lastThis, lastArgs!);\n frameId = null;\n });\n }\n } as T;\n}\n\n/**\n * Idle — schedule low-priority work\n *\n * Useful for: background prep, non-urgent updates\n * Falls back to setTimeout if requestIdleCallback unavailable\n *\n * @param fn Function to call when idle\n * @param options timeout for fallback\n *\n * @example\n * ```ts\n * idle(() => prefetchData());\n * ```\n */\nexport function idle(fn: () => void, options?: { timeout?: number }): void {\n if (typeof requestIdleCallback !== 'undefined') {\n requestIdleCallback(fn, options ? { timeout: options.timeout } : undefined);\n } else {\n // Fallback: defer to microtask, then use setTimeout\n Promise.resolve().then(() => {\n setTimeout(fn, 0);\n });\n }\n}\n\n/**\n * Timeout — Promise-based delay\n *\n * Useful for: readable async code, waiting between retries\n *\n * @param ms Milliseconds to wait\n * @returns Promise that resolves after delay\n *\n * @example\n * ```ts\n * await timeout(300);\n * console.log('300ms later');\n * ```\n */\nexport function timeout(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry — attempt function with backoff\n *\n * Useful for: network calls, transient failures\n *\n * @param fn Async function to retry\n * @param options maxAttempts, delayMs, backoff function\n * @returns Promise with final result or error\n *\n * @example\n * ```ts\n * const data = await retry(() => fetch(url), {\n * maxAttempts: 3,\n * delayMs: 100,\n * });\n * ```\n */\nexport async function retry<T>(\n fn: () => Promise<T>,\n options?: RetryOptions\n): Promise<T> {\n const {\n maxAttempts = 3,\n delayMs = 100,\n backoff = (i: number) => delayMs * Math.pow(2, i),\n } = options || {};\n\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n if (attempt < maxAttempts - 1) {\n const delay = backoff(attempt);\n await timeout(delay);\n }\n }\n }\n\n throw lastError || new Error('Retry failed');\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","// Lightweight shared no-op helpers to avoid double-casts and duplicated definitions\n\nexport const noop: () => void = () => {};\n\nexport const noopEventListener: EventListener & { cancel(): void } =\n Object.assign((_ev?: Event) => {}, { cancel() {} });\n\nexport const noopEventListenerWithFlush: EventListener & {\n cancel(): void;\n flush(): void;\n} = Object.assign((_ev?: Event) => {}, { cancel() {}, flush() {} });\n\nexport const noopCancel: { cancel(): void } = { cancel() {} };\n","import { globalScheduler } from '../runtime/scheduler';\nimport { getCurrentComponentInstance } from '../runtime/component';\nimport { logger } from '../dev/logger';\nimport { noopEventListener, noopEventListenerWithFlush } from './noop';\n\nexport type CancelFn = () => void;\n\n// Platform-specific timer handle types\ntype TimeoutHandle = ReturnType<typeof setTimeout> | null;\n// rAF may fall back to setTimeout in some environments/tests, include both\ntype RafHandle =\n | ReturnType<typeof requestAnimationFrame>\n | ReturnType<typeof setTimeout>\n | null;\n// requestIdleCallback may be unavailable; allow setTimeout fallback handle\ntype IdleHandle =\n | ReturnType<typeof requestIdleCallback>\n | ReturnType<typeof setTimeout>\n | null;\n\nfunction throwIfDuringRender(): void {\n const inst = getCurrentComponentInstance();\n if (inst !== null) {\n throw new Error(\n '[Askr] calling FX handler during render is not allowed. Move calls to event handlers or effects.'\n );\n }\n}\n\n/**\n * Helper: schedule a user callback through the global scheduler\n */\nfunction enqueueUserCallback(fn: () => void) {\n globalScheduler.enqueue(() => {\n try {\n fn();\n } catch (err) {\n // Keep behavior consistent with other scheduler-queued work\n logger.error('[Askr] FX handler error:', err);\n }\n });\n}\n\n// ---------- Event handlers ----------\n\nexport function debounceEvent(\n ms: number,\n handler: EventListener,\n options?: { leading?: boolean; trailing?: boolean }\n): EventListener & { cancel(): void; flush(): void } {\n const { leading = false, trailing = true } = options || {};\n\n const inst = getCurrentComponentInstance();\n // On SSR, event handlers are inert\n if (inst && inst.ssr) {\n return noopEventListenerWithFlush;\n }\n\n let timeoutId: TimeoutHandle = null;\n let lastEvent: Event | null = null;\n let lastCallTime = 0;\n\n const debounced = function (this: unknown, ev: Event) {\n // Disallow using returned handler during render\n throwIfDuringRender();\n\n const now = Date.now();\n lastEvent = ev;\n\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n if (leading && now - lastCallTime >= ms) {\n enqueueUserCallback(() => handler.call(null, ev));\n lastCallTime = now;\n }\n\n if (trailing) {\n timeoutId = setTimeout(() => {\n // Schedule through scheduler\n if (lastEvent) {\n enqueueUserCallback(() => handler.call(null, lastEvent!));\n }\n timeoutId = null;\n lastCallTime = Date.now();\n }, ms);\n }\n } as EventListener & { cancel(): void; flush(): void };\n\n debounced.cancel = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n lastEvent = null;\n };\n\n debounced.flush = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n const ev = lastEvent;\n lastEvent = null;\n timeoutId = null;\n if (ev) enqueueUserCallback(() => handler.call(null, ev));\n }\n };\n\n // Auto-cleanup on component unmount\n if (inst) {\n inst.cleanupFns.push(() => {\n debounced.cancel();\n });\n }\n\n return debounced;\n}\n\nexport function throttleEvent(\n ms: number,\n handler: EventListener,\n options?: { leading?: boolean; trailing?: boolean }\n): EventListener & { cancel(): void } {\n const { leading = true, trailing = true } = options || {};\n\n const inst = getCurrentComponentInstance();\n if (inst && inst.ssr) {\n return noopEventListener;\n }\n\n let lastCallTime = 0;\n let timeoutId: TimeoutHandle = null;\n let lastEvent: Event | null = null;\n\n const throttled = function (this: unknown, ev: Event) {\n throwIfDuringRender();\n\n const now = Date.now();\n lastEvent = ev;\n\n if (leading && now - lastCallTime >= ms) {\n enqueueUserCallback(() => handler.call(null, ev));\n lastCallTime = now;\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n } else if (!leading && lastCallTime === 0) {\n lastCallTime = now;\n }\n\n if (trailing && timeoutId === null) {\n const wait = ms - (now - lastCallTime);\n timeoutId = setTimeout(\n () => {\n if (lastEvent)\n enqueueUserCallback(() => handler.call(null, lastEvent!));\n lastCallTime = Date.now();\n timeoutId = null;\n },\n Math.max(0, wait)\n );\n }\n } as EventListener & { cancel(): void };\n\n throttled.cancel = () => {\n if (timeoutId !== null) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n lastEvent = null;\n };\n\n if (inst) {\n inst.cleanupFns.push(() => throttled.cancel());\n }\n\n return throttled;\n}\n\nexport function rafEvent(\n handler: EventListener\n): EventListener & { cancel(): void } {\n const inst = getCurrentComponentInstance();\n if (inst && inst.ssr) {\n return noopEventListener;\n }\n\n let frameId: RafHandle = null;\n let lastEvent: Event | null = null;\n\n const scheduleFrame = () => {\n const rAF =\n typeof requestAnimationFrame !== 'undefined'\n ? requestAnimationFrame\n : (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 16);\n\n frameId = rAF(() => {\n frameId = null;\n if (lastEvent) {\n const ev = lastEvent;\n lastEvent = null;\n enqueueUserCallback(() => handler.call(null, ev));\n }\n });\n };\n\n const fn = function (this: unknown, ev: Event) {\n throwIfDuringRender();\n lastEvent = ev;\n if (frameId === null) scheduleFrame();\n } as EventListener & { cancel(): void };\n\n fn.cancel = () => {\n if (frameId !== null) {\n // If frameId is numeric and cancelAnimationFrame is available, use it;\n // otherwise fall back to clearTimeout for the setTimeout fallback.\n if (\n typeof cancelAnimationFrame !== 'undefined' &&\n typeof frameId === 'number'\n ) {\n cancelAnimationFrame(frameId);\n } else {\n clearTimeout(frameId as ReturnType<typeof setTimeout>);\n }\n frameId = null;\n }\n lastEvent = null;\n };\n\n if (inst) inst.cleanupFns.push(() => fn.cancel());\n\n return fn;\n}\n\n// ---------- Scheduled work ----------\n\nexport function scheduleTimeout(ms: number, fn: () => void): CancelFn {\n throwIfDuringRender();\n const inst = getCurrentComponentInstance();\n if (inst && inst.ssr) {\n return () => {};\n }\n\n let id: TimeoutHandle = setTimeout(() => {\n id = null;\n enqueueUserCallback(fn);\n }, ms);\n\n const cancel = () => {\n if (id !== null) {\n clearTimeout(id);\n id = null;\n }\n };\n\n if (inst) inst.cleanupFns.push(cancel);\n return cancel;\n}\n\nexport function scheduleIdle(\n fn: () => void,\n options?: { timeout?: number }\n): CancelFn {\n throwIfDuringRender();\n const inst = getCurrentComponentInstance();\n if (inst && inst.ssr) return () => {};\n\n let id: IdleHandle = null;\n let usingRIC = false;\n\n if (typeof requestIdleCallback !== 'undefined') {\n usingRIC = true;\n id = requestIdleCallback(() => {\n id = null;\n enqueueUserCallback(fn);\n }, options);\n } else {\n // Fallback: schedule on next macrotask\n id = setTimeout(() => {\n id = null;\n enqueueUserCallback(fn);\n }, 0);\n }\n\n const cancel = () => {\n if (id !== null) {\n // If using requestIdleCallback and available, call cancelIdleCallback for numeric ids.\n if (\n usingRIC &&\n typeof cancelIdleCallback !== 'undefined' &&\n typeof id === 'number'\n ) {\n cancelIdleCallback(id);\n } else {\n clearTimeout(id as ReturnType<typeof setTimeout>);\n }\n id = null;\n }\n };\n\n if (inst) inst.cleanupFns.push(cancel);\n return cancel;\n}\n\nexport interface RetryOptions {\n maxAttempts?: number;\n delayMs?: number;\n backoff?: (attemptIndex: number) => number;\n}\n\nexport function scheduleRetry<T>(\n fn: () => Promise<T>,\n options?: RetryOptions\n): { cancel(): void } {\n throwIfDuringRender();\n const inst = getCurrentComponentInstance();\n if (inst && inst.ssr) return { cancel: () => {} };\n\n const {\n maxAttempts = 3,\n delayMs = 100,\n backoff = (i: number) => delayMs * Math.pow(2, i),\n } = options || {};\n\n let cancelled = false;\n\n const attempt = (index: number) => {\n if (cancelled) return;\n // Run user fn inside scheduler\n globalScheduler.enqueue(() => {\n if (cancelled) return;\n // Call fn (it may be async)\n const p = fn();\n p.then(\n () => {\n // Completed successfully\n },\n () => {\n if (cancelled) return;\n if (index + 1 < maxAttempts) {\n const delay = backoff(index);\n // Schedule next attempt via setTimeout so it gets enqueued through scheduleTimeout\n setTimeout(() => {\n attempt(index + 1);\n }, delay);\n }\n }\n ).catch((e) => {\n logger.error('[Askr] scheduleRetry error:', e);\n });\n });\n };\n\n // Start first attempt\n attempt(0);\n\n const cancel = () => {\n cancelled = true;\n };\n\n if (inst) inst.cleanupFns.push(cancel);\n return { cancel };\n}\n"]}