@kontsedal/olas-core 0.0.5 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/index.cjs +0 -0
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +109 -27
  4. package/dist/index.d.cts.map +1 -1
  5. package/dist/index.d.mts +109 -27
  6. package/dist/index.d.mts.map +1 -1
  7. package/dist/index.mjs +0 -0
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/{root-DqWolle_.mjs → root-Byq-QYTp.mjs} +1478 -347
  10. package/dist/root-Byq-QYTp.mjs.map +1 -0
  11. package/dist/{root-lBp7qziQ.cjs → root-CPSL5kpR.cjs} +1483 -346
  12. package/dist/root-CPSL5kpR.cjs.map +1 -0
  13. package/dist/testing.cjs +5 -1
  14. package/dist/testing.cjs.map +1 -1
  15. package/dist/testing.d.cts +3 -2
  16. package/dist/testing.d.cts.map +1 -1
  17. package/dist/testing.d.mts +3 -2
  18. package/dist/testing.d.mts.map +1 -1
  19. package/dist/testing.mjs +5 -2
  20. package/dist/testing.mjs.map +1 -1
  21. package/dist/{types-BH1o6nYa.d.mts → types-Brp-4WaZ.d.mts} +244 -23
  22. package/dist/types-Brp-4WaZ.d.mts.map +1 -0
  23. package/dist/{types-C4Vtkxbn.d.cts → types-DzDIypPo.d.cts} +244 -23
  24. package/dist/types-DzDIypPo.d.cts.map +1 -0
  25. package/package.json +4 -1
  26. package/src/controller/instance.ts +360 -94
  27. package/src/controller/root.ts +58 -30
  28. package/src/controller/types.ts +66 -4
  29. package/src/emitter.ts +8 -2
  30. package/src/errors.ts +39 -3
  31. package/src/forms/field.ts +219 -25
  32. package/src/forms/form-types.ts +16 -3
  33. package/src/forms/form.ts +360 -38
  34. package/src/forms/index.ts +3 -1
  35. package/src/forms/types.ts +27 -1
  36. package/src/forms/validators.ts +45 -11
  37. package/src/index.ts +13 -7
  38. package/src/query/client.ts +237 -58
  39. package/src/query/define.ts +0 -0
  40. package/src/query/entry.ts +259 -15
  41. package/src/query/focus-online.ts +53 -11
  42. package/src/query/infinite.ts +351 -47
  43. package/src/query/keys.ts +33 -2
  44. package/src/query/local.ts +3 -0
  45. package/src/query/mutation.ts +27 -6
  46. package/src/query/plugin.ts +43 -4
  47. package/src/query/types.ts +76 -6
  48. package/src/query/use.ts +53 -10
  49. package/src/selection.ts +49 -12
  50. package/src/signals/readonly.ts +3 -0
  51. package/src/signals/runtime.ts +27 -0
  52. package/src/signals/types.ts +10 -0
  53. package/src/testing.ts +9 -0
  54. package/src/timing/debounced.ts +106 -23
  55. package/src/timing/index.ts +1 -1
  56. package/src/timing/throttled.ts +85 -28
  57. package/src/utils.ts +15 -2
  58. package/dist/root-DqWolle_.mjs.map +0 -1
  59. package/dist/root-lBp7qziQ.cjs.map +0 -1
  60. package/dist/types-BH1o6nYa.d.mts.map +0 -1
  61. package/dist/types-C4Vtkxbn.d.cts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"root-CPSL5kpR.cjs","names":["internal","standaloneEffect","factoryOpts"],"sources":["../src/controller/define.ts","../src/devtools.ts","../src/errors.ts","../src/signals/readonly.ts","../src/signals/runtime.ts","../src/utils.ts","../src/query/focus-online.ts","../src/query/structural-share.ts","../src/query/entry.ts","../src/query/infinite.ts","../src/query/keys.ts","../src/query/plugin.ts","../src/query/client.ts","../src/emitter.ts","../src/forms/field.ts","../src/forms/form.ts","../src/query/local.ts","../src/query/mutation.ts","../src/query/use.ts","../src/controller/instance.ts","../src/controller/root.ts"],"sourcesContent":["import type { ControllerDef, Ctx } from './types'\n\ntype InternalControllerDef<Props, Api> = ControllerDef<Props, Api> & {\n readonly __factory: (ctx: Ctx, props: Props) => Api\n readonly __name?: string\n}\n\n/** Optional configuration for `defineController`. */\nexport type DefineControllerOptions = {\n /**\n * A short, human-readable name for this controller — used in the devtools\n * tree, `controller:*` events, and error contexts (e.g. `[\"root\",\"board[0]\"]`).\n *\n * When omitted, the runtime falls back to `factory.name` (the JS-inferred\n * function name) or `\"anonymous\"` for arrow-function factories defined\n * inline. Naming is strongly recommended in app code.\n */\n name?: string\n}\n\n/**\n * Create a controller definition. The factory is stored on the returned object\n * and invoked during `createRoot` / `ctx.child` to build instances.\n *\n * `Props` defaults to `void` so a factory written as `(ctx) => ...` is typed\n * as `ControllerDef<void, Api>` — the form `createRoot` requires.\n */\nexport function defineController<Props = void, Api = unknown>(\n factory: (ctx: Ctx, props: Props) => Api,\n options?: DefineControllerOptions,\n): ControllerDef<Props, Api> {\n const def: InternalControllerDef<Props, Api> = {\n __olas: 'controller',\n __factory: factory,\n ...(options?.name !== undefined ? { __name: options.name } : {}),\n } as InternalControllerDef<Props, Api>\n return def\n}\n\n/** Internal — extracts the factory from a ControllerDef. */\nexport function getFactory<Props, Api>(\n def: ControllerDef<Props, Api>,\n): (ctx: Ctx, props: Props) => Api {\n return (def as InternalControllerDef<Props, Api>).__factory\n}\n\n/** Internal — extracts the explicit `name` option from a ControllerDef, if any. */\nexport function getName<Props, Api>(def: ControllerDef<Props, Api>): string | undefined {\n return (def as InternalControllerDef<Props, Api>).__name\n}\n","/**\n * Discriminated union of devtools events emitted by a root via\n * `root.__debug.subscribe(handler)`. Spec §20.9. Adding new variants is\n * non-breaking — consumers `switch` on `type` and ignore unknowns.\n */\nexport type DebugEvent =\n | { type: 'controller:constructed'; path: readonly string[]; props: unknown }\n | { type: 'controller:suspended'; path: readonly string[] }\n | { type: 'controller:resumed'; path: readonly string[] }\n | { type: 'controller:disposed'; path: readonly string[] }\n | {\n type: 'cache:subscribed'\n queryKey: readonly unknown[]\n subscriberPath: readonly string[]\n }\n | { type: 'cache:fetch-start'; queryKey: readonly unknown[] }\n | { type: 'cache:fetch-success'; queryKey: readonly unknown[]; durationMs: number }\n | {\n type: 'cache:fetch-error'\n queryKey: readonly unknown[]\n error: unknown\n durationMs: number\n }\n | { type: 'cache:invalidated'; queryKey: readonly unknown[] }\n | { type: 'cache:gc'; queryKey: readonly unknown[] }\n | { type: 'mutation:run'; path: readonly string[]; name?: string; vars: unknown }\n | { type: 'mutation:success'; path: readonly string[]; name?: string; result: unknown }\n | { type: 'mutation:error'; path: readonly string[]; name?: string; error: unknown }\n | { type: 'mutation:rollback'; path: readonly string[]; name?: string }\n | {\n type: 'field:validated'\n path: readonly string[]\n field: string\n valid: boolean\n errors: string[]\n }\n\n/**\n * Snapshot of one live cache entry — produced by `root.__debug.queryEntries()`\n * so devtools panels can show *current data*, not just past fetch events.\n */\nexport type DebugCacheEntry = {\n key: readonly unknown[]\n status: 'idle' | 'pending' | 'success' | 'error'\n data: unknown\n error: unknown\n lastUpdatedAt: number | undefined\n isStale: boolean\n isFetching: boolean\n hasPendingMutations: boolean\n}\n\n/**\n * The shape of `root.__debug`. Subscribe to receive every `DebugEvent` until\n * the returned unsubscribe is called.\n *\n * The bus replays a snapshot of the *live controller tree* to every new\n * subscriber synchronously inside `subscribe(...)` — so a panel that mounts\n * after `createRoot()` sees the existing tree immediately, not just future\n * events. Event types other than `controller:*` are not buffered.\n *\n * `queryEntries()` returns a fresh inspector snapshot — current state of\n * every cached entry. Useful for \"what's in the cache right now?\" views.\n */\nexport type DebugBus = {\n subscribe(handler: (event: DebugEvent) => void): () => void\n queryEntries(): DebugCacheEntry[]\n}\n\ntype LiveControllerEntry = {\n path: readonly string[]\n props: unknown\n state: 'active' | 'suspended'\n}\n\nfunction pathKey(path: readonly string[]): string {\n return path.join('\u0000')\n}\n\n/**\n * Per-root devtools event multiplexer. Emit is a no-op when no one is\n * subscribed (one Set size check), so leaving the bus in production has\n * effectively zero cost until a consumer attaches.\n *\n * Internal — exposed to consumers via `root.__debug`.\n *\n * Tracks a snapshot of every live controller (constructed but not yet\n * disposed) and replays construction events to new subscribers, so the\n * devtools tree populates on mount instead of staying blank until the\n * next event.\n */\nexport class DevtoolsEmitter {\n private handlers = new Set<(event: DebugEvent) => void>()\n /** Path → entry for every live (constructed, not disposed) controller. */\n private liveControllers = new Map<string, LiveControllerEntry>()\n\n subscribe(handler: (event: DebugEvent) => void): () => void {\n // Replay the snapshot of the current tree, in insertion order. Insertion\n // order matches construction order, which is parent-before-child (parents\n // construct their children inside their factories). The replayed handler\n // gets the same event shape it would have seen live.\n for (const entry of this.liveControllers.values()) {\n try {\n handler({\n type: 'controller:constructed',\n path: entry.path,\n props: entry.props,\n })\n if (entry.state === 'suspended') {\n handler({ type: 'controller:suspended', path: entry.path })\n }\n } catch {\n // Devtools handlers must not break replay for other handlers.\n }\n }\n this.handlers.add(handler)\n return () => {\n this.handlers.delete(handler)\n }\n }\n\n emit(event: DebugEvent): void {\n // Track live controllers regardless of subscriber count — the snapshot\n // must be accurate even when no one was watching.\n this.recordLifecycle(event)\n if (this.handlers.size === 0) return\n // Snapshot — handlers may unsubscribe.\n const snapshot = Array.from(this.handlers)\n for (const handler of snapshot) {\n try {\n handler(event)\n } catch {\n // Devtools handlers must not break the program.\n }\n }\n }\n\n get hasSubscribers(): boolean {\n return this.handlers.size > 0\n }\n\n private recordLifecycle(event: DebugEvent): void {\n if (event.type === 'controller:constructed') {\n this.liveControllers.set(pathKey(event.path), {\n path: event.path,\n props: event.props,\n state: 'active',\n })\n return\n }\n if (event.type === 'controller:suspended') {\n const key = pathKey(event.path)\n const cur = this.liveControllers.get(key)\n if (cur !== undefined) cur.state = 'suspended'\n return\n }\n if (event.type === 'controller:resumed') {\n const key = pathKey(event.path)\n const cur = this.liveControllers.get(key)\n if (cur !== undefined) cur.state = 'active'\n return\n }\n if (event.type === 'controller:disposed') {\n this.liveControllers.delete(pathKey(event.path))\n return\n }\n }\n}\n","/**\n * Context passed to a root's `onError` handler. `kind` identifies where in\n * the controller's surface the throw originated; `controllerPath` is the\n * path from root to the controller that owned the failing code; `queryKey`\n * is set for `cache` kinds. Spec §12, §20.9.\n *\n * `'plugin'` is used for exceptions raised by `QueryClientPlugin` callbacks\n * (`@kontsedal/olas-cross-tab` and friends); SPEC §13.2.\n *\n * The remaining fields are correlation hooks for telemetry adapters\n * (Sentry / OpenTelemetry breadcrumbs / Datadog RUM): `eventId` is a stable\n * per-dispatch UUID, `timestamp` is wall-clock ms, `attempt` is the\n * 0-based retry attempt for cache/mutation paths, `cause` is the\n * `Error.cause`-style underlying error if the surfaced error wrapped it,\n * `pluginName` identifies the throwing plugin (set only when `kind ==\n * 'plugin'`).\n */\nexport type ErrorContext = {\n kind: 'effect' | 'cache' | 'mutation' | 'emitter' | 'construction' | 'plugin'\n controllerPath: readonly string[]\n queryKey?: readonly unknown[]\n eventId: string\n timestamp: number\n attempt?: number\n cause?: unknown\n pluginName?: string\n}\n\n/** Signature of `RootOptions.onError`. */\nexport type ErrorHandler = (err: unknown, context: ErrorContext) => void\n\n/**\n * Partial context — `dispatchError` fills in `eventId` + `timestamp`. Call\n * sites pass the diagnostic fields they know about; the dispatcher stamps\n * the per-dispatch correlation data.\n */\nexport type ErrorContextInput = Omit<ErrorContext, 'eventId' | 'timestamp'>\n\nconst defaultHandler: ErrorHandler = (err, context) => {\n // eslint-disable-next-line no-console\n console.error('[olas]', context, err)\n}\n\nlet eventCounter = 0\nfunction nextEventId(): string {\n // 24 bits of randomness + a monotonic counter. Cheap (no crypto) and\n // unique-per-process. Adapters that need stronger guarantees can\n // re-stamp inside their own handler.\n eventCounter = (eventCounter + 1) >>> 0\n const r = ((Math.random() * 0x1000000) | 0).toString(16).padStart(6, '0')\n const c = eventCounter.toString(16).padStart(6, '0')\n return `e_${r}${c}`\n}\n\n/**\n * Dispatch an error to a user-provided handler, falling back to console.error.\n * The handler itself is wrapped — if it throws, the throw is swallowed and\n * logged so an `onError` bug never tears down the tree.\n *\n * Internal — used by the controller container and query client.\n */\nexport function dispatchError(\n handler: ErrorHandler | undefined,\n err: unknown,\n context: ErrorContextInput,\n): void {\n const fn = handler ?? defaultHandler\n const full: ErrorContext = {\n ...context,\n eventId: nextEventId(),\n timestamp: Date.now(),\n }\n try {\n fn(err, full)\n } catch (handlerErr) {\n try {\n // eslint-disable-next-line no-console\n console.error('[olas] onError handler threw:', handlerErr)\n // eslint-disable-next-line no-console\n console.error('[olas] original error:', err, full)\n } catch {\n // Console itself failed — give up silently.\n }\n }\n}\n","import type { ReadSignal } from './types'\n\n/**\n * Project a Signal (or any object with a reactive `value` + `peek` + `subscribe`)\n * as a `ReadSignal`. The returned object does not expose `set` / `update` /\n * settable `value`, so it can be returned from APIs without callers mutating it.\n *\n * Internal helper — not exported from the package's public surface.\n */\nexport function readOnly<T>(source: ReadSignal<T>): ReadSignal<T> {\n return Object.freeze({\n get value() {\n return source.value\n },\n peek() {\n return source.peek()\n },\n subscribe(handler: (value: T) => void) {\n return source.subscribe(handler)\n },\n subscribeChanges(handler: (value: T) => void) {\n return source.subscribeChanges(handler)\n },\n })\n}\n","import {\n batch as _batch,\n computed as _computed,\n effect as _effect,\n signal as _signal,\n untracked as _untracked,\n type ReadonlySignal as PreactReadonlySignal,\n type Signal as PreactSignal,\n} from '@preact/signals-core'\n\nimport type { Computed, Signal } from './types'\n\nclass SignalImpl<T> implements Signal<T> {\n private readonly inner: PreactSignal<T>\n\n constructor(initial: T) {\n this.inner = _signal<T>(initial)\n }\n\n get value(): T {\n return this.inner.value\n }\n\n set value(next: T) {\n this.inner.value = next\n }\n\n peek(): T {\n return this.inner.peek()\n }\n\n subscribe(handler: (value: T) => void): () => void {\n return this.inner.subscribe(handler)\n }\n\n subscribeChanges(handler: (value: T) => void): () => void {\n return subscribeChangesImpl(this.inner, handler)\n }\n\n set(value: T): void {\n this.inner.value = value\n }\n\n update(fn: (prev: T) => T): void {\n this.inner.value = fn(this.inner.peek())\n }\n}\n\nclass ComputedImpl<T> implements Computed<T> {\n private readonly inner: PreactReadonlySignal<T>\n\n constructor(fn: () => T) {\n this.inner = _computed<T>(fn)\n }\n\n get value(): T {\n return this.inner.value\n }\n\n peek(): T {\n return this.inner.peek()\n }\n\n subscribe(handler: (value: T) => void): () => void {\n return this.inner.subscribe(handler)\n }\n\n subscribeChanges(handler: (value: T) => void): () => void {\n return subscribeChangesImpl(this.inner, handler)\n }\n}\n\n/**\n * Shared skip-initial wrapper around `signal.subscribe`. Preact fires the\n * subscribe callback synchronously with the current value (the \"initial\n * fire\"); the wrapper swallows it and forwards every subsequent change.\n */\nfunction subscribeChangesImpl<T>(\n inner: PreactSignal<T> | PreactReadonlySignal<T>,\n handler: (value: T) => void,\n): () => void {\n let initial = true\n return inner.subscribe((value) => {\n if (initial) {\n initial = false\n return\n }\n handler(value)\n })\n}\n\n/**\n * Create a writable `Signal<T>`. Reads track the current auto-tracking scope\n * (effect / computed); writes notify all subscribers (deduped via `Object.is`).\n *\n * Spec §20.1. For a single-pass non-tracked read use `signal.peek()`.\n */\nexport function signal<T>(initial: T): Signal<T> {\n return new SignalImpl(initial)\n}\n\n/**\n * Create a `Computed<T>` — a read-only derived signal. The provided `fn` is\n * re-evaluated whenever a signal it read during its last run changes; the\n * resulting value is cached until then.\n *\n * Spec §20.1. The graph is glitch-free: a `computed` re-runs at most once per\n * batched-write cycle.\n */\nexport function computed<T>(fn: () => T): Computed<T> {\n return new ComputedImpl(fn)\n}\n\n/**\n * Run `fn` immediately and again whenever any signal it reads changes. If\n * `fn` returns a function, that function is called as a cleanup before the\n * next re-run and on dispose.\n *\n * Returns a `dispose` function. Inside a controller use `ctx.effect(...)`\n * instead — that variant is auto-disposed with the controller.\n */\nexport function effect(fn: () => void | (() => void)): () => void {\n return _effect(fn)\n}\n\n/**\n * Batch synchronous signal writes so subscribers see one notification at the\n * end of the batch rather than one per write. Returns whatever `fn` returns.\n */\nexport function batch<T>(fn: () => T): T {\n return _batch(fn)\n}\n\n/**\n * Run `fn` with auto-tracking suppressed — signals read inside don't become\n * dependencies of the surrounding `computed` / `effect`. Useful for \"read\n * these signals once to log them\" or for snapshotting state inside an effect\n * without subscribing to it. For a single-signal peek, prefer `signal.peek()`.\n */\nexport function untracked<T>(fn: () => T): T {\n return _untracked(fn)\n}\n","/**\n * True iff `err` looks like an AbortError. Matches the standard `DOMException`\n * shape thrown by `AbortController` AND any object whose `name === 'AbortError'`\n * — that covers axios / msw / user-thrown plain Errors that signal abort.\n *\n * Spec: §20.12. Node 17+ exposes a global DOMException, so the instanceof\n * branch works server-side; the name-based branch is the portable fallback.\n */\nexport function isAbortError(err: unknown): boolean {\n if (typeof DOMException !== 'undefined' && err instanceof DOMException) {\n return err.name === 'AbortError'\n }\n if (err != null && typeof err === 'object' && 'name' in err) {\n return (err as { name: unknown }).name === 'AbortError'\n }\n return false\n}\n\n/**\n * `setTimeout` wrapped in a promise that rejects with `AbortError` if the\n * passed signal fires. Internal — used by the retry loops in `Entry`,\n * `InfiniteEntry`, and `Mutation` so a slow backoff never blocks a supersede.\n */\nexport function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(abortReason(signal))\n return\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n reject(abortReason(signal))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/**\n * Read the caller-supplied abort reason if present, falling back to the\n * canonical `DOMException('Aborted', 'AbortError')`. `signal.reason` lets\n * users propagate context (e.g. \"supersededByLatestWins\") through abort\n * chains — discarding it would force every caller to wrap with custom\n * cancellation tokens.\n */\nfunction abortReason(signal: AbortSignal): unknown {\n const reason: unknown = (signal as { reason?: unknown }).reason\n if (reason !== undefined) return reason\n return new DOMException('Aborted', 'AbortError')\n}\n","/**\n * Lazy pub/sub for window-focus and reconnect events.\n *\n * Each `ClientEntry` with `refetchOnWindowFocus` or `refetchOnReconnect` set\n * subscribes here on its first subscriber and unsubscribes when it has none.\n * We install a single window/document listener for each event the first time\n * anyone subscribes; after that, we fan out to all subscribers ourselves.\n *\n * SSR-safe: no-ops when `window` is undefined. Spec §5.9.\n */\n\ntype Sub = () => void\n\nconst focusSubs = new Set<Sub>()\nconst onlineSubs = new Set<Sub>()\n\nfunction fireFocus(): void {\n for (const fn of focusSubs) {\n try {\n fn()\n } catch {\n // Subscriber failures must not break the fan-out.\n }\n }\n}\n\nfunction fireOnline(): void {\n for (const fn of onlineSubs) {\n try {\n fn()\n } catch {\n // ditto\n }\n }\n}\n\n// A tab-return commonly fires BOTH `focus` and `visibilitychange` in the same\n// tick. Coalesce them into a single `fireFocus` via a microtask flag so\n// subscribers refetch once, not twice (T3.9).\nlet focusScheduled = false\nfunction scheduleFocus(): void {\n if (focusScheduled) return\n focusScheduled = true\n queueMicrotask(() => {\n focusScheduled = false\n fireFocus()\n })\n}\n\nfunction onVisibilityChange(): void {\n if (document.visibilityState === 'visible') scheduleFocus()\n}\n\nlet focusInstalled = false\nlet onlineInstalled = false\n\nfunction installFocus(): void {\n if (focusInstalled) return\n if (typeof window === 'undefined') return\n window.addEventListener('focus', scheduleFocus)\n if (typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', onVisibilityChange)\n }\n focusInstalled = true\n}\n\nfunction uninstallFocus(): void {\n if (!focusInstalled) return\n if (typeof window === 'undefined') return\n window.removeEventListener('focus', scheduleFocus)\n if (typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n focusInstalled = false\n}\n\nfunction installOnline(): void {\n if (onlineInstalled) return\n if (typeof window === 'undefined') return\n window.addEventListener('online', fireOnline)\n onlineInstalled = true\n}\n\nfunction uninstallOnline(): void {\n if (!onlineInstalled) return\n if (typeof window === 'undefined') return\n window.removeEventListener('online', fireOnline)\n onlineInstalled = false\n}\n\nexport function subscribeWindowFocus(fn: Sub): () => void {\n installFocus()\n focusSubs.add(fn)\n return () => {\n focusSubs.delete(fn)\n if (focusSubs.size === 0) uninstallFocus()\n }\n}\n\nexport function subscribeReconnect(fn: Sub): () => void {\n installOnline()\n onlineSubs.add(fn)\n return () => {\n onlineSubs.delete(fn)\n if (onlineSubs.size === 0) uninstallOnline()\n }\n}\n\n/** Test-only — force-detach global listeners regardless of subscriber state. */\nexport function __resetFocusOnlineForTests(): void {\n focusSubs.clear()\n onlineSubs.clear()\n uninstallFocus()\n uninstallOnline()\n}\n","/**\n * Walk `prev` and `next` in parallel. Wherever a sub-tree in `next` is\n * structurally equal to the corresponding sub-tree in `prev`, return `prev`'s\n * reference for that sub-tree. Otherwise return `next`'s.\n *\n * Result: a value that is `===` to `prev` on every refetch where the payload\n * didn't actually change, and shares maximum ref-identity on partial changes.\n * Downstream `computed`s and React `useSyncExternalStore` snapshots stop\n * thrashing because reference equality holds where content equality holds.\n *\n * Bails (returns the `next` ref unchanged, no recursion) on:\n * - Mismatched constructors / different `typeof` between `prev` and `next`\n * - `Map`, `Set`, `Date`, `RegExp`, class instances (anything where the\n * plain-object / array fast path isn't safe)\n * - Functions, symbols, promises\n *\n * Handles cycles via a `WeakSet` of in-progress objects — a self-referential\n * payload that compares structurally identical against itself won't loop.\n */\nexport function structuralShare<T>(prev: T, next: T): T {\n // Identity short-circuit — both branches see the exact same allocation.\n if (Object.is(prev, next)) return prev\n return walk(prev, next, new WeakSet<object>()) as T\n}\n\nfunction walk(prev: unknown, next: unknown, seen: WeakSet<object>): unknown {\n if (Object.is(prev, next)) return prev\n if (prev === null || next === null) return next\n if (typeof prev !== 'object' || typeof next !== 'object') return next\n\n // Cycle guard. If either side is already on the in-flight stack, we can't\n // safely recurse — fall back to `next`'s ref. Real cyclic payloads are\n // exceedingly rare in HTTP responses; defensive bail.\n if (seen.has(prev as object) || seen.has(next as object)) return next\n\n // Arrays — only matched against arrays.\n if (Array.isArray(prev) && Array.isArray(next)) {\n return walkArray(prev, next, seen)\n }\n if (Array.isArray(prev) !== Array.isArray(next)) return next\n\n // Constructor / prototype check. Plain objects have `Object.prototype`\n // (and a Map/Set/Date/RegExp/class instance does not). We require an exact\n // prototype match on both sides AND `Object.prototype` so we never deep-\n // walk into class instances whose identity might encode hidden state.\n const prevProto = Object.getPrototypeOf(prev)\n if (prevProto !== Object.getPrototypeOf(next)) return next\n if (prevProto !== Object.prototype && prevProto !== null) return next\n\n return walkPlainObject(prev as Record<string, unknown>, next as Record<string, unknown>, seen)\n}\n\nfunction walkArray(\n prev: ReadonlyArray<unknown>,\n next: ReadonlyArray<unknown>,\n seen: WeakSet<object>,\n): ReadonlyArray<unknown> {\n if (prev.length !== next.length) {\n // Length changed — we can still preserve refs for matching prefixes via\n // index-aligned walking. That's the right trade-off for tables / lists:\n // appending an item keeps the head's refs stable, prepending invalidates\n // everything (which it does anyway — items shifted).\n }\n seen.add(prev)\n seen.add(next)\n try {\n const out: unknown[] = new Array(next.length)\n let changed = next.length !== prev.length\n for (let i = 0; i < next.length; i++) {\n const prevItem = i < prev.length ? prev[i] : undefined\n const shared = walk(prevItem, next[i], seen)\n out[i] = shared\n if (shared !== prev[i]) changed = true\n }\n if (!changed) return prev\n return out\n } finally {\n seen.delete(prev)\n seen.delete(next)\n }\n}\n\nfunction walkPlainObject(\n prev: Record<string, unknown>,\n next: Record<string, unknown>,\n seen: WeakSet<object>,\n): Record<string, unknown> {\n const prevKeys = Object.keys(prev)\n const nextKeys = Object.keys(next)\n let changed = prevKeys.length !== nextKeys.length\n\n seen.add(prev)\n seen.add(next)\n try {\n const out: Record<string, unknown> = {}\n // Iterate `next`'s keys in order so the output preserves payload's\n // key ordering (matters for downstream `JSON.stringify` callers and\n // for predictable React reconciliation when an object is rendered).\n for (const key of nextKeys) {\n const shared = walk(prev[key], next[key], seen)\n out[key] = shared\n if (shared !== prev[key]) changed = true\n else if (!(key in prev)) changed = true\n }\n // Keys present in `prev` but not in `next` are dropped — that's already\n // expressed by `next.keys`. But the length-mismatch flag above catches\n // the changed shape.\n if (!changed) return prev\n return out\n } finally {\n seen.delete(prev)\n seen.delete(next)\n }\n}\n","import { batch, type Signal, signal } from '../signals'\nimport { abortableSleep, isAbortError } from '../utils'\nimport { subscribeReconnect } from './focus-online'\nimport { structuralShare } from './structural-share'\nimport type { AsyncStatus, NetworkMode, RetryDelay, RetryPolicy, Snapshot } from './types'\n\nexport type EntryEvents = {\n onFetchStart?: () => void\n onFetchSuccess?: (durationMs: number) => void\n onFetchError?: (durationMs: number, error: unknown) => void\n}\n\nexport type EntryOptions<T> = {\n fetcher: () => (signal: AbortSignal) => Promise<T>\n staleTime?: number\n initialData?: T | undefined\n initialUpdatedAt?: number | undefined\n retry?: RetryPolicy\n retryDelay?: RetryDelay\n networkMode?: NetworkMode\n structuralShare?: boolean\n events?: EntryEvents\n /**\n * Fired after a successful fetch result is written to `data`. Used by the\n * `QueryClient` to emit a plugin-visible `SetDataEvent` with\n * `source: 'fetch'` (devtools events live on `events` above). Distinct\n * from `events.onFetchSuccess`, which carries timing info for the\n * devtools bus.\n *\n * Privileged closure — set up by `ClientEntry` to call\n * `client.emitSetData(...)`, which already individually try/catches every\n * plugin via `callPlugin` and routes thrown exceptions through `onError`\n * with `kind: 'plugin'`. Not wrapped here; an exception escaping this\n * callback is a programming error in core (not a plugin) and SHOULD\n * surface so the bug is visible.\n */\n onSuccessData?: (data: T) => void\n}\n\ntype SnapshotRecord<T> = {\n id: number\n prev: T | undefined\n live: boolean\n}\n\n/**\n * One cache entry's state machine. Owns the AsyncState signals, race\n * protection, retry loop, optimistic-update snapshot stack.\n *\n * Internal — not exported from the public surface.\n */\nexport class Entry<T> {\n readonly data: Signal<T | undefined>\n readonly error: Signal<unknown | undefined> = signal(undefined)\n readonly status: Signal<AsyncStatus>\n readonly isLoading: Signal<boolean> = signal(false)\n readonly isFetching: Signal<boolean> = signal(false)\n readonly lastUpdatedAt: Signal<number | undefined>\n readonly hasPendingMutations: Signal<boolean> = signal(false)\n readonly isStale: Signal<boolean> = signal(true)\n /** True while a fetch is parked waiting for reconnect (online-mode defer or\n * offlineFirst network-error park). See spec §5.5, T3.5. */\n readonly isPaused: Signal<boolean> = signal(false)\n\n fetcherProvider: () => (signal: AbortSignal) => Promise<T>\n private staleTime: number\n private retry: RetryPolicy\n private retryDelay: RetryDelay | undefined\n private networkMode: NetworkMode\n private structuralShareEnabled: boolean\n private currentFetchId = 0\n private currentAbort: AbortController | null = null\n private staleTimer: ReturnType<typeof setTimeout> | null = null\n /** Set by `markStale()` (invalidate without fetch); forces `isStaleNow()`\n * true until the next successful fetch clears it. Spec §5.7, T3.9. */\n private forcedStale = false\n private snapshots: Array<SnapshotRecord<T>> = []\n private nextSnapshotId = 0\n private disposed = false\n /** Subscribers to reconnect — installed lazily when a deferred fetch lands. */\n private reconnectUnsub: (() => void) | null = null\n /**\n * Set of deferred-fetch resolvers waiting for reconnect (online mode).\n * Stored at `unknown` to keep `Entry<T>` covariant in `T` — same trick as\n * `onSuccessData`. Each resolver is fed the same value from\n * `applySuccess`, which is `T`, then cast at the fan-out call site.\n */\n private deferredResolvers: Array<{\n resolve: (value: unknown) => void\n reject: (reason?: unknown) => void\n }> = []\n private readonly events: EntryEvents\n // Stored at `unknown` (not `T`) to keep `Entry<T>` covariant in `T`. The\n // callback only forwards the value through; Entry never inspects it.\n private readonly onSuccessData: ((data: unknown) => void) | undefined\n private fetchStartTime = 0\n /**\n * Promises returned by `firstValue()` that haven't settled. Rejected on\n * `dispose()` so awaiters (most notably `prefetch` and `subscription.firstValue`)\n * don't hang when the controller tree is torn down mid-fetch.\n */\n private pendingFirstValueRejects: Array<(err: unknown) => void> = []\n\n constructor(options: EntryOptions<T>) {\n this.fetcherProvider = options.fetcher\n this.staleTime = options.staleTime ?? 0\n this.retry = options.retry ?? 0\n // Left undefined when not given so `computeDelay` can pick the exponential\n // default only when retries are actually enabled (T3.9).\n this.retryDelay = options.retryDelay\n this.networkMode = options.networkMode ?? 'online'\n this.structuralShareEnabled = options.structuralShare ?? true\n this.events = options.events ?? {}\n this.onSuccessData = options.onSuccessData as ((data: unknown) => void) | undefined\n this.data = signal<T | undefined>(options.initialData)\n if (options.initialData !== undefined) {\n this.status = signal<AsyncStatus>('success')\n // For hydrated data, derive `isStale` from the *actual* age of the\n // payload, not the timer alone — otherwise a payload older than\n // `staleTime` would read `isStale === false` until the (fresh, full-\n // length) timer fires. `isStaleNow()` already does this correctly for\n // the subscribe-time refetch check; mirror that here for the signal.\n if (this.staleTime === 0) {\n this.isStale.set(true)\n } else {\n const last = options.initialUpdatedAt\n const alreadyStale = last === undefined || Date.now() - last >= this.staleTime\n this.isStale.set(alreadyStale)\n // Only schedule a timer if the data isn't already stale. If it is,\n // there's nothing to wait for.\n if (!alreadyStale) {\n const remaining = this.staleTime - (Date.now() - (last as number))\n this.staleTimer = setTimeout(() => {\n this.staleTimer = null\n if (!this.disposed) this.isStale.set(true)\n }, remaining)\n }\n }\n } else {\n this.status = signal<AsyncStatus>('idle')\n }\n this.lastUpdatedAt = signal<number | undefined>(options.initialUpdatedAt)\n }\n\n startFetch(): Promise<T> {\n if (this.disposed) {\n return Promise.reject(new Error('Entry disposed'))\n }\n // `online` mode: defer until reconnect when the browser thinks we're\n // offline. Don't touch status — the UI keeps showing last-known data.\n // `always` / `offlineFirst` proceed to the fetcher; `offlineFirst` will\n // re-handle a network rejection inside the catch path.\n if (this.networkMode === 'online' && this.isOffline()) {\n return this.scheduleDeferredFetch()\n }\n const myId = ++this.currentFetchId\n this.currentAbort?.abort()\n const abort = new AbortController()\n this.currentAbort = abort\n\n const previouslyHadData = this.data.peek() !== undefined\n batch(() => {\n this.status.set('pending')\n this.isFetching.set(true)\n this.isLoading.set(!previouslyHadData)\n this.isPaused.set(false)\n })\n\n this.fetchStartTime = Date.now()\n try {\n this.events.onFetchStart?.()\n } catch {\n // devtools handlers must not break the program.\n }\n\n return this.runWithRetry(myId, abort)\n }\n\n private isOffline(): boolean {\n return typeof navigator !== 'undefined' && navigator.onLine === false\n }\n\n private scheduleDeferredFetch(): Promise<T> {\n // Parked waiting for reconnect — surface it so the UI can show \"waiting\n // for network\" instead of a silent `idle` (T3.5). Cleared when the fetch\n // actually starts (`startFetch` batch) or settles.\n this.isPaused.set(true)\n // Lazy-install one reconnect listener for the entry. Cleared on dispose\n // and on the first successful drain. Each call appends a fresh resolver.\n if (this.reconnectUnsub === null) {\n this.reconnectUnsub = subscribeReconnect(() => this.drainDeferred())\n }\n return new Promise<T>((resolve, reject) => {\n this.deferredResolvers.push({\n resolve: resolve as (value: unknown) => void,\n reject,\n })\n })\n }\n\n private drainDeferred(): void {\n if (this.deferredResolvers.length === 0) return\n if (this.disposed) return\n const pending = this.deferredResolvers\n this.deferredResolvers = []\n // One real fetch fans out to every pending resolver. Tearing down the\n // reconnect listener avoids accumulating listeners across many deferrals.\n if (this.reconnectUnsub !== null) {\n this.reconnectUnsub()\n this.reconnectUnsub = null\n }\n this.startFetch().then(\n (value) => {\n for (const p of pending) p.resolve(value)\n },\n (err) => {\n for (const p of pending) p.reject(err)\n },\n )\n }\n\n private async runWithRetry(myId: number, abort: AbortController): Promise<T> {\n let attempt = 0\n while (true) {\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n try {\n const fetcher = this.fetcherProvider()\n const result = await fetcher(abort.signal)\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n return this.applySuccess(result)\n } catch (err) {\n if (myId !== this.currentFetchId || this.disposed || isAbortError(err)) {\n throw err\n }\n // offlineFirst: a network-shaped failure while offline parks the entry\n // (wait for reconnect, then retry) instead of surfacing the error. A\n // `fetch()` network failure surfaces as a `TypeError`; `AbortError` is\n // already handled above. Spec §5.5, T3.5.\n if (this.networkMode === 'offlineFirst' && this.isOffline() && err instanceof TypeError) {\n batch(() => {\n this.isFetching.set(false)\n this.isLoading.set(false)\n this.status.set(this.data.peek() !== undefined ? 'success' : 'idle')\n })\n return this.scheduleDeferredFetch()\n }\n if (!this.shouldRetry(attempt, err)) {\n return this.applyFailure(err)\n }\n const delay = this.computeDelay(attempt)\n await abortableSleep(delay, abort.signal)\n attempt += 1\n }\n }\n }\n\n private shouldRetry(attempt: number, err: unknown): boolean {\n const retry = this.retry\n if (retry === 0) return false\n if (typeof retry === 'number') return attempt < retry\n return retry(attempt, err)\n }\n\n private computeDelay(attempt: number): number {\n const d = this.retryDelay\n // Default to exponential backoff (capped at 30s) when `retry > 0` but no\n // `retryDelay` was given — a constant 1s default hammered a flapping\n // backend on every attempt (T3.9). Explicit number/function still wins.\n if (d === undefined) return Math.min(1000 * 2 ** attempt, 30_000)\n return typeof d === 'function' ? d(attempt) : d\n }\n\n private applySuccess(result: T): T {\n // Structurally share with the previous value so unchanged sub-trees\n // keep their `===` identity. Downstream `computed`s and React snapshots\n // stop thrashing on no-op refetches. Bails on Maps/Sets/class instances\n // — see `structural-share.ts`. Disabled per-query via `structuralShare:\n // false` for large payloads where the O(payload) walk costs more than\n // the re-render savings.\n const prev = this.data.peek() as T | undefined\n const shared =\n prev === undefined || !this.structuralShareEnabled ? result : structuralShare(prev, result)\n // Rebase live optimistic snapshots onto the fresh server truth: a\n // subsequent rollback should restore to THIS value, not the pre-fetch\n // baseline the snapshot captured before the fetch resolved. Without this,\n // a fetch landing during an optimistic mutation, then that mutation\n // failing, resurrects pre-fetch data (spec §6.4, T3.4).\n if (this.snapshots.length > 0) {\n for (const s of this.snapshots) s.prev = shared\n }\n batch(() => {\n this.data.set(shared)\n this.error.set(undefined)\n this.status.set('success')\n this.isLoading.set(false)\n this.isFetching.set(false)\n this.lastUpdatedAt.set(Date.now())\n this.isStale.set(this.staleTime === 0)\n })\n this.forcedStale = false // fresh data clears a prior markStale() (T3.9)\n if (this.staleTime > 0) this.scheduleStaleness()\n try {\n this.events.onFetchSuccess?.(Date.now() - this.fetchStartTime)\n } catch {\n // devtools handlers must not break the program.\n }\n this.onSuccessData?.(shared)\n return shared\n }\n\n private applyFailure(err: unknown): never {\n batch(() => {\n this.error.set(err)\n this.status.set('error')\n this.isLoading.set(false)\n this.isFetching.set(false)\n })\n try {\n this.events.onFetchError?.(Date.now() - this.fetchStartTime, err)\n } catch {\n // devtools handlers must not break the program.\n }\n throw err\n }\n\n private scheduleStaleness(): void {\n if (this.staleTimer != null) clearTimeout(this.staleTimer)\n if (this.staleTime > 0) {\n this.staleTimer = setTimeout(() => {\n this.staleTimer = null\n if (!this.disposed) this.isStale.set(true)\n }, this.staleTime)\n }\n }\n\n refetch(): Promise<T> {\n return this.startFetch()\n }\n\n /**\n * Apply a server-supplied data + timestamp without going through the\n * fetcher path. Used by streaming SSR hydration: each `<Suspense>` boundary\n * that resolves on the server pushes its entry's data to the client, and\n * the client routes it through here so the entry transitions to `success`\n * without burning the user's fetcher.\n *\n * Distinct from `setData`: no Snapshot returned (no rollback semantics —\n * this is canonical data, not an optimistic patch), no\n * `hasPendingMutations` flip, and `lastUpdatedAt` honors the supplied\n * server timestamp instead of `Date.now()`. Also bumps `currentFetchId`\n * so any in-flight fetch supersedes itself rather than overwriting the\n * fresher hydrated value.\n */\n applyHydration(data: T, lastUpdatedAt: number): void {\n if (this.disposed) return\n // Bump fetch id: an inflight fetcher will now lose the supersede check\n // in `runWithRetry` and won't write its (likely-stale) result.\n this.currentFetchId += 1\n this.currentAbort?.abort()\n this.currentAbort = null\n if (this.staleTimer !== null) {\n clearTimeout(this.staleTimer)\n this.staleTimer = null\n }\n const alreadyStale = this.staleTime === 0 || Date.now() - lastUpdatedAt >= this.staleTime\n batch(() => {\n this.data.set(data)\n this.error.set(undefined)\n this.status.set('success')\n this.isLoading.set(false)\n this.isFetching.set(false)\n this.lastUpdatedAt.set(lastUpdatedAt)\n this.isStale.set(alreadyStale)\n })\n if (!alreadyStale && this.staleTime > 0) {\n const remaining = this.staleTime - (Date.now() - lastUpdatedAt)\n this.staleTimer = setTimeout(() => {\n this.staleTimer = null\n if (!this.disposed) this.isStale.set(true)\n }, remaining)\n }\n this.onSuccessData?.(data)\n // Resolve any awaiters parked in firstValue / promise.\n if (this.pendingFirstValueRejects.length > 0) {\n // First-value awaiters are subscribed to `this.status`; the batched\n // `status.set('success')` above wakes them through the normal\n // subscribe path. We don't need to do anything else here.\n }\n }\n\n /**\n * Force this entry stale WITHOUT fetching. `isStaleNow()` returns true until\n * the next successful fetch clears the flag, so the next subscriber refetches.\n * Used by `client.invalidate` for subscriber-less entries — spec §5.7 says\n * invalidate refetches only IF subscribed (T3.9).\n */\n markStale(): void {\n if (this.disposed) return\n if (this.staleTimer != null) {\n clearTimeout(this.staleTimer)\n this.staleTimer = null\n }\n this.forcedStale = true\n this.isStale.set(true)\n }\n\n invalidate(): Promise<T> {\n this.markStale()\n return this.startFetch()\n }\n\n reset(): void {\n if (this.disposed) return\n batch(() => {\n this.error.set(undefined)\n this.status.set(this.data.peek() !== undefined ? 'success' : 'idle')\n })\n }\n\n /**\n * Cancel an in-flight fetch without touching `data`. Aborts the current\n * request and supersedes it (bumps `currentFetchId` so its result can never\n * land), then restores a settled status: `'success'` if data exists, else\n * `'idle'`. No-op when nothing is fetching. This is the primitive behind\n * `query.cancel(...)` / `subscription.cancel()`: the canonical optimistic\n * recipe cancels outgoing refetches before an optimistic `setData` so a\n * stale response can't clobber the optimistic value (spec §5, §6.4). T3.4.\n */\n cancel(): void {\n if (this.disposed || !this.isFetching.peek()) return\n this.currentFetchId += 1\n this.currentAbort?.abort()\n this.currentAbort = null\n batch(() => {\n this.isFetching.set(false)\n this.isLoading.set(false)\n this.status.set(this.data.peek() !== undefined ? 'success' : 'idle')\n })\n }\n\n /**\n * Write data into the entry.\n *\n * `track` (default `true`) is the optimistic-update path: it pushes a\n * snapshot record and flips `hasPendingMutations`, so the returned\n * `Snapshot.rollback()` can restore the pre-write baseline and\n * `finalize()` commits it. This is what `query.setData(...)` inside a\n * mutation's `onMutate` uses (spec §6.4).\n *\n * `track: false` is a canonical cache write — cross-tab receive, entities\n * backprop, realtime patches (spec §13.2). It updates the data signal but\n * pushes NO snapshot and does NOT flip `hasPendingMutations`, so a\n * fire-and-forget plugin write can't wedge the pending flag at `true`\n * forever. Returns a no-op `Snapshot`.\n */\n setData(updater: (prev: T | undefined) => T, opts?: { track?: boolean }): Snapshot {\n if (this.disposed) {\n return { rollback: () => {}, finalize: () => {} }\n }\n const prev = this.data.peek()\n const next = updater(prev)\n const track = opts?.track ?? true\n const record: SnapshotRecord<T> | null = track\n ? { id: this.nextSnapshotId++, prev, live: true }\n : null\n if (record) this.snapshots.push(record)\n\n batch(() => {\n this.data.set(next)\n if (this.status.peek() === 'idle' || this.status.peek() === 'pending') {\n this.status.set('success')\n }\n this.lastUpdatedAt.set(Date.now())\n if (record) this.hasPendingMutations.set(true)\n })\n\n if (!record) {\n return { rollback: () => {}, finalize: () => {} }\n }\n const id = record.id\n return {\n rollback: () => {\n if (!record.live || this.disposed) return\n record.live = false\n batch(() => {\n const i = this.snapshots.indexOf(record)\n if (i !== -1) {\n if (i === this.snapshots.length - 1) {\n // Top of the stack: restore this layer's captured baseline as\n // the current data.\n this.data.set(record.prev as T)\n } else {\n // Not the top: leave the currently-displayed value alone and\n // thread this layer's baseline down onto the next layer, so a\n // later top-rollback lands on the correct pre-everything value\n // instead of resurrecting this layer's delta (chain-splice —\n // T3.1, spec §6.4). Out-of-order rollback of all layers now\n // returns to the original pre-mutation value.\n const below = this.snapshots[i + 1] as SnapshotRecord<T>\n below.prev = record.prev\n }\n this.snapshots.splice(i, 1)\n }\n this.hasPendingMutations.set(this.snapshots.some((s) => s.live))\n })\n },\n finalize: () => {\n if (!record.live || this.disposed) return\n record.live = false\n this.snapshots = this.snapshots.filter((s) => s.id !== id)\n if (!this.snapshots.some((s) => s.live)) {\n this.hasPendingMutations.set(false)\n }\n },\n }\n }\n\n firstValue(): Promise<T> {\n if (this.disposed) {\n return Promise.reject(new DOMException('Entry disposed', 'AbortError'))\n }\n if (this.status.peek() === 'success') {\n return Promise.resolve(this.data.peek() as T)\n }\n if (this.status.peek() === 'error') {\n return Promise.reject(this.error.peek())\n }\n return new Promise<T>((resolve, reject) => {\n const tracked = (err: unknown): void => {\n this.pendingFirstValueRejects = this.pendingFirstValueRejects.filter((f) => f !== tracked)\n reject(err)\n }\n this.pendingFirstValueRejects.push(tracked)\n const unsub = this.status.subscribe((s) => {\n if (s === 'success') {\n unsub()\n this.pendingFirstValueRejects = this.pendingFirstValueRejects.filter((f) => f !== tracked)\n resolve(this.data.peek() as T)\n } else if (s === 'error') {\n unsub()\n tracked(this.error.peek())\n }\n })\n })\n }\n\n /**\n * True iff data is older than `staleTime` (or no data has been fetched yet).\n * Used by the query client to decide whether to refetch on subscribe.\n */\n isStaleNow(): boolean {\n if (this.forcedStale) return true\n const last = this.lastUpdatedAt.peek()\n if (last === undefined) return true\n return Date.now() - last >= this.staleTime\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.staleTimer != null) {\n clearTimeout(this.staleTimer)\n this.staleTimer = null\n }\n this.currentAbort?.abort()\n this.currentAbort = null\n // A disposed entry is idle. Reset the in-flight flags so `waitForIdle`\n // (which waits on `isFetching`) can't hang when a fetch races dispose — the\n // aborted fetcher's applySuccess/applyFailure never runs to clear them (T3.9).\n batch(() => {\n this.isFetching.set(false)\n this.isLoading.set(false)\n })\n if (this.reconnectUnsub !== null) {\n this.reconnectUnsub()\n this.reconnectUnsub = null\n }\n if (this.deferredResolvers.length > 0) {\n const disposed = new DOMException('Entry disposed', 'AbortError')\n const pending = this.deferredResolvers\n this.deferredResolvers = []\n for (const p of pending) p.reject(disposed)\n }\n if (this.pendingFirstValueRejects.length > 0) {\n const disposed = new DOMException('Entry disposed', 'AbortError')\n const rejects = this.pendingFirstValueRejects\n this.pendingFirstValueRejects = []\n for (const fn of rejects) fn(disposed)\n }\n }\n}\n","import { batch, computed, type Signal, signal } from '../signals'\nimport type { ReadSignal } from '../signals/types'\nimport { abortableSleep, isAbortError } from '../utils'\nimport { subscribeReconnect } from './focus-online'\nimport { structuralShare } from './structural-share'\nimport type {\n AsyncState,\n AsyncStatus,\n NetworkMode,\n RetryDelay,\n RetryPolicy,\n Snapshot,\n} from './types'\n\n/**\n * Configuration for `defineInfiniteQuery({ ... })`. Spec §5.7, §20.4.\n *\n * - `getNextPageParam(lastPage, allPages)` returns the param for the next\n * page, or `null` when there's no more.\n * - `getPreviousPageParam` (optional) enables bidirectional infinite lists.\n * - `itemsOf(page)` (optional) flattens pages into items for the\n * `subscription.flat` convenience signal.\n */\nexport type InfiniteFetchCtx<PageParam> = {\n pageParam: PageParam\n signal: AbortSignal\n deps: import('../controller/types').AmbientDeps\n}\n\nexport type InfiniteQuerySpec<Args extends unknown[], PageParam, TPage, TItem = TPage> = {\n key: (...args: Args) => unknown[]\n /**\n * Fetcher receives an `InfiniteFetchCtx` (pageParam + signal + deps) as\n * the first arg and positional cache args after. See `FetchCtx` for the\n * regular-query analogue.\n */\n fetcher: (ctx: InfiniteFetchCtx<PageParam>, ...args: Args) => Promise<TPage>\n initialPageParam: PageParam\n getNextPageParam: (lastPage: TPage, allPages: TPage[]) => PageParam | null\n getPreviousPageParam?: (firstPage: TPage, allPages: TPage[]) => PageParam | null\n itemsOf?: (page: TPage) => TItem[]\n staleTime?: number\n gcTime?: number\n refetchInterval?: number\n keepPreviousData?: boolean\n retry?: RetryPolicy\n retryDelay?: RetryDelay\n /** See `QuerySpec.networkMode`. Defaults to `'online'`. */\n networkMode?: NetworkMode\n /** See `QuerySpec.structuralShare`. Applies to the head-page refresh. */\n structuralShare?: boolean\n /**\n * Stable identifier used by `QueryClientPlugin`s (`@kontsedal/olas-cross-tab`,\n * etc.). Infinite queries do NOT propagate cross-tab in v1 — the\n * page-array payload is too heavy to be a safe default — but the field is\n * accepted for forward compatibility. SPEC §13.2.\n */\n queryId?: string\n /**\n * Accepted for API symmetry, but infinite queries do NOT propagate\n * cross-tab: peers can't apply page-array payloads (core's remote-apply\n * paths early-return for infinite defs). The `'infinite'` / `'both'` values\n * were removed in T6.4; infinite cross-tab is tracked in `BACKLOG.md`.\n */\n crossTab?: boolean | 'data'\n}\n\n/**\n * Module-scoped handle for a paginated query. Mirrors `Query<Args, TPage[]>`\n * with paginated `setData` semantics.\n */\nexport type InfiniteQuery<Args extends unknown[], TPage, _TItem> = {\n readonly __olas: 'infiniteQuery'\n invalidate(...args: Args): void\n invalidateAll(): void\n setData(...args: [...Args, updater: (prev: TPage[] | undefined) => TPage[]]): Snapshot\n /** Cancel the in-flight fetch (initial/refetch or paging) for a key. See\n * `Query.cancel` (spec §5, §6.4). */\n cancel(...args: Args): void\n /** Cancel in-flight fetches for every keyed entry of this infinite query. */\n cancelAll(): void\n prefetch(...args: Args): Promise<TPage>\n}\n\n/**\n * What `ctx.use(infiniteQuery, ...)` returns. Extends `AsyncState<TPage[]>`\n * with paginated controls: `fetchNextPage` / `fetchPreviousPage`,\n * `hasNextPage` / `hasPreviousPage`, and per-direction `isFetching` signals.\n *\n * `flat` is a convenience: present when the query spec provides `itemsOf` —\n * otherwise it's an empty array.\n */\nexport type InfiniteQuerySubscription<TPage, TItem> = AsyncState<TPage[]> & {\n pages: ReadSignal<TPage[]>\n flat: ReadSignal<TItem[]>\n hasNextPage: ReadSignal<boolean>\n hasPreviousPage: ReadSignal<boolean>\n isFetchingNextPage: ReadSignal<boolean>\n isFetchingPreviousPage: ReadSignal<boolean>\n fetchNextPage: () => Promise<void>\n fetchPreviousPage: () => Promise<void>\n /** Cancel this subscription's in-flight fetch (if any). See `Query.cancel`. */\n cancel: () => void\n}\n\n/**\n * Holds an array of pages plus their pageParams. Supports fetchNextPage /\n * fetchPreviousPage / invalidate (drops all pages). Race-protected.\n *\n * Internal.\n */\nexport class InfiniteEntry<TPage, TItem, PageParam> {\n readonly pages: Signal<TPage[]> = signal<TPage[]>([])\n readonly pageParams: Signal<PageParam[]>\n readonly data: ReadSignal<TPage[] | undefined>\n readonly error: Signal<unknown | undefined> = signal(undefined)\n readonly status: Signal<AsyncStatus> = signal<AsyncStatus>('idle')\n readonly isLoading: Signal<boolean> = signal(false)\n readonly isFetching: Signal<boolean> = signal(false)\n readonly isStale: Signal<boolean> = signal(true)\n readonly lastUpdatedAt: Signal<number | undefined> = signal(undefined)\n readonly hasPendingMutations: Signal<boolean> = signal(false)\n /** True while a fetch is parked waiting for reconnect (online-mode defer).\n * See spec §5.5, T3.5. Mirrors `Entry.isPaused`. */\n readonly isPaused: Signal<boolean> = signal(false)\n\n readonly isFetchingNextPage: Signal<boolean> = signal(false)\n readonly isFetchingPreviousPage: Signal<boolean> = signal(false)\n\n readonly hasNextPage: ReadSignal<boolean>\n readonly hasPreviousPage: ReadSignal<boolean>\n readonly flat: ReadSignal<TItem[]>\n\n private currentFetchId = 0\n private currentAbort: AbortController | null = null\n private staleTimer: ReturnType<typeof setTimeout> | null = null\n /** Set by `markStale()` (invalidate without fetch). See `Entry.forcedStale`. */\n private forcedStale = false\n private snapshots: Array<{\n id: number\n prev: TPage[]\n prevParams: PageParam[]\n live: boolean\n }> = []\n private nextSnapshotId = 0\n private disposed = false\n /** Mirrors `Entry.pendingFirstValueRejects` — see that field for context. */\n private pendingFirstValueRejects: Array<(err: unknown) => void> = []\n\n private readonly fetcher: (pageCtx: {\n pageParam: PageParam\n signal: AbortSignal\n }) => Promise<TPage>\n private readonly initialPageParam: PageParam\n private readonly getNextPageParam: (lastPage: TPage, allPages: TPage[]) => PageParam | null\n private readonly getPreviousPageParam:\n | ((firstPage: TPage, allPages: TPage[]) => PageParam | null)\n | undefined\n private readonly staleTime: number\n private readonly retry: RetryPolicy\n private readonly retryDelay: RetryDelay | undefined\n private readonly networkMode: NetworkMode\n private readonly structuralShareEnabled: boolean\n private reconnectUnsub: (() => void) | null = null\n private deferredResolvers: Array<{\n direction: 'initial' | 'next' | 'prev'\n resolve: () => void\n reject: (err: unknown) => void\n }> = []\n private readonly itemsOf?: (page: TPage) => TItem[]\n /**\n * Mirrors `Entry.onSuccessData`. Fires from `applyFetchSuccess`-equivalent\n * branches AFTER `pages.set(...)` settles. Used by `InfiniteClientEntry`\n * to emit `SetDataEvent { kind: 'infinite', source: 'fetch' }` for\n * `QueryClientPlugin`s (e.g. entity normalization).\n */\n private readonly onSuccessData?: (pages: TPage[]) => void\n\n constructor(opts: {\n fetcher: (pageCtx: { pageParam: PageParam; signal: AbortSignal }) => Promise<TPage>\n initialPageParam: PageParam\n getNextPageParam: (lastPage: TPage, allPages: TPage[]) => PageParam | null\n getPreviousPageParam?: (firstPage: TPage, allPages: TPage[]) => PageParam | null\n itemsOf?: (page: TPage) => TItem[]\n staleTime?: number\n retry?: RetryPolicy\n retryDelay?: RetryDelay\n networkMode?: NetworkMode\n structuralShare?: boolean\n onSuccessData?: (pages: TPage[]) => void\n }) {\n this.fetcher = opts.fetcher\n this.initialPageParam = opts.initialPageParam\n this.getNextPageParam = opts.getNextPageParam\n this.getPreviousPageParam = opts.getPreviousPageParam\n this.itemsOf = opts.itemsOf\n this.staleTime = opts.staleTime ?? 0\n this.retry = opts.retry ?? 0\n this.retryDelay = opts.retryDelay\n this.networkMode = opts.networkMode ?? 'online'\n this.structuralShareEnabled = opts.structuralShare ?? true\n this.onSuccessData = opts.onSuccessData\n this.pageParams = signal<PageParam[]>([])\n this.data = computed(() => {\n const ps = this.pages.value\n return ps.length === 0 ? undefined : ps\n })\n this.flat = computed<TItem[]>(() => {\n const ps = this.pages.value\n if (!this.itemsOf) return ps as unknown as TItem[]\n const out: TItem[] = []\n for (const p of ps) {\n for (const item of this.itemsOf(p)) out.push(item)\n }\n return out\n })\n this.hasNextPage = computed(() => {\n const ps = this.pages.value\n if (ps.length === 0) return false\n return this.getNextPageParam(ps[ps.length - 1] as TPage, ps) !== null\n })\n this.hasPreviousPage = computed(() => {\n const ps = this.pages.value\n if (ps.length === 0) return false\n const fn = this.getPreviousPageParam\n if (!fn) return false\n return fn(ps[0] as TPage, ps) !== null\n })\n }\n\n /**\n * Initial load / refetch. On the initial load (no pages yet) this fetches\n * the first page. On a refetch of an already-loaded entry (interval,\n * invalidate, focus/reconnect) it **refetches every currently-loaded page**\n * sequentially, re-deriving each page's param from the freshly-fetched data\n * via `getNextPageParam` — matching TanStack and avoiding the old\n * \"collapse to page one\" truncation that dropped every loaded page but the\n * first on each refetch (T3.7). Pages/params update atomically at the end,\n * so subscribers never observe a mid-refetch truncation flash.\n */\n startFetch(): Promise<TPage> {\n if (this.disposed) return Promise.reject(new Error('Entry disposed'))\n if (this.networkMode === 'online' && this.isOffline()) {\n return this.scheduleDeferredFetch('initial') as Promise<TPage>\n }\n const myId = ++this.currentFetchId\n this.currentAbort?.abort()\n const abort = new AbortController()\n this.currentAbort = abort\n\n const previousPages = this.pages.peek()\n batch(() => {\n this.status.set('pending')\n this.isFetching.set(true)\n this.isLoading.set(previousPages.length === 0)\n this.isPaused.set(false)\n })\n\n return this.runRefetchAll(myId, abort.signal, Math.max(1, previousPages.length), previousPages)\n }\n\n /**\n * Fetch `targetCount` pages from `initialPageParam`, chaining each next param\n * via `getNextPageParam` from the freshly-fetched pages. Applies the query's\n * retry policy per page. Stops early if the dataset shrank (a page yields\n * `getNextPageParam === null`). Writes pages/params in ONE batch at the end;\n * a per-page failure keeps the existing pages and surfaces the error; a\n * supersede/dispose throws `AbortError` without writing.\n */\n private async runRefetchAll(\n myId: number,\n signal: AbortSignal,\n targetCount: number,\n previousPages: TPage[],\n ): Promise<TPage> {\n const newPages: TPage[] = []\n const newParams: PageParam[] = []\n let pageParam: PageParam = this.initialPageParam\n try {\n for (let i = 0; i < targetCount; i++) {\n let attempt = 0\n while (true) {\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n try {\n const page = await this.fetcher({ pageParam, signal })\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n newPages.push(page)\n newParams.push(pageParam)\n break\n } catch (err) {\n if (myId !== this.currentFetchId || this.disposed || isAbortError(err)) throw err\n const shouldRetry =\n typeof this.retry === 'number' ? attempt < this.retry : this.retry(attempt, err)\n if (!shouldRetry) {\n batch(() => {\n this.error.set(err)\n this.status.set('error')\n this.isLoading.set(false)\n this.isFetching.set(false)\n })\n throw err\n }\n const delay = this.computeRetryDelay(attempt)\n await abortableSleep(delay, signal)\n attempt += 1\n }\n }\n const next = this.getNextPageParam(newPages[newPages.length - 1] as TPage, newPages)\n if (next === null) break\n pageParam = next\n }\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n // Structurally share the head page so an unchanged first page keeps its\n // ref (downstream `computed`s / React snapshots don't thrash).\n const finalPages =\n previousPages.length > 0 && this.structuralShareEnabled && newPages.length > 0\n ? [structuralShare(previousPages[0] as TPage, newPages[0] as TPage), ...newPages.slice(1)]\n : newPages\n batch(() => {\n this.pages.set(finalPages)\n this.pageParams.set(newParams)\n this.error.set(undefined)\n this.status.set('success')\n this.isLoading.set(false)\n this.isFetching.set(false)\n this.lastUpdatedAt.set(Date.now())\n this.isStale.set(this.staleTime === 0)\n })\n this.forcedStale = false // fresh pages clear a prior markStale() (T3.9)\n if (this.staleTime > 0) this.scheduleStaleness()\n this.onSuccessData?.(this.pages.peek())\n return finalPages[0] as TPage\n } finally {\n // Status repair (T3.3): a superseded refetch must never leave the entry\n // wedged at 'pending' when data is present and nothing is fetching. The\n // superseder owns the final status; this only fires for the terminal\n // fetch of a supersede chain. Never clobbers a real 'error'.\n if (\n !this.disposed &&\n this.status.peek() === 'pending' &&\n !this.isFetching.peek() &&\n this.pages.peek().length > 0\n ) {\n this.status.set('success')\n }\n }\n }\n\n fetchNextPage(): Promise<void> {\n if (this.disposed) return Promise.reject(new Error('Entry disposed'))\n if (this.isFetchingNextPage.peek()) return Promise.resolve()\n if (this.networkMode === 'online' && this.isOffline()) {\n return this.scheduleDeferredFetch('next') as Promise<void>\n }\n const ps = this.pages.peek()\n if (ps.length === 0) {\n return this.startFetch().then(() => {})\n }\n const nextParam = this.getNextPageParam(ps[ps.length - 1] as TPage, ps)\n if (nextParam === null) return Promise.resolve()\n\n const myId = ++this.currentFetchId\n const abort = new AbortController()\n this.currentAbort?.abort()\n this.currentAbort = abort\n batch(() => {\n this.isFetchingNextPage.set(true)\n this.isFetching.set(true)\n })\n\n return this.runFetch(\n myId,\n abort.signal,\n nextParam,\n (page, param) => {\n if (myId !== this.currentFetchId || this.disposed) return\n batch(() => {\n this.pages.set([...this.pages.peek(), page])\n this.pageParams.set([...this.pageParams.peek(), param])\n this.error.set(undefined)\n // A successful page op owns the terminal status: restore 'success'\n // so paging that superseded a mid-flight full refetch (which left\n // status at 'pending') can't wedge the entry / Suspense (T3.3).\n this.status.set('success')\n this.isFetchingNextPage.set(false)\n this.isFetching.set(false)\n this.lastUpdatedAt.set(Date.now())\n })\n this.onSuccessData?.(this.pages.peek())\n },\n 'next',\n ).then(() => {})\n }\n\n fetchPreviousPage(): Promise<void> {\n if (this.disposed) return Promise.reject(new Error('Entry disposed'))\n if (this.isFetchingPreviousPage.peek()) return Promise.resolve()\n if (!this.getPreviousPageParam) return Promise.resolve()\n if (this.networkMode === 'online' && this.isOffline()) {\n return this.scheduleDeferredFetch('prev') as Promise<void>\n }\n const ps = this.pages.peek()\n if (ps.length === 0) {\n return this.startFetch().then(() => {})\n }\n const prevParam = this.getPreviousPageParam(ps[0] as TPage, ps)\n if (prevParam === null) return Promise.resolve()\n\n const myId = ++this.currentFetchId\n const abort = new AbortController()\n this.currentAbort?.abort()\n this.currentAbort = abort\n batch(() => {\n this.isFetchingPreviousPage.set(true)\n this.isFetching.set(true)\n })\n\n return this.runFetch(\n myId,\n abort.signal,\n prevParam,\n (page, param) => {\n if (myId !== this.currentFetchId || this.disposed) return\n batch(() => {\n this.pages.set([page, ...this.pages.peek()])\n this.pageParams.set([param, ...this.pageParams.peek()])\n this.error.set(undefined)\n // A successful page op owns the terminal status — see fetchNextPage\n // (T3.3).\n this.status.set('success')\n this.isFetchingPreviousPage.set(false)\n this.isFetching.set(false)\n this.lastUpdatedAt.set(Date.now())\n })\n this.onSuccessData?.(this.pages.peek())\n },\n 'prev',\n ).then(() => {})\n }\n\n private async runFetch(\n myId: number,\n signal: AbortSignal,\n pageParam: PageParam,\n onSuccess: (page: TPage, param: PageParam) => void,\n direction: 'initial' | 'next' | 'prev',\n ): Promise<TPage> {\n let attempt = 0\n let succeeded = false\n try {\n while (true) {\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n try {\n const page = await this.fetcher({ pageParam, signal })\n if (myId !== this.currentFetchId || this.disposed) {\n throw new DOMException('Superseded', 'AbortError')\n }\n onSuccess(page, pageParam)\n succeeded = true\n return page\n } catch (err) {\n if (myId !== this.currentFetchId || this.disposed || isAbortError(err)) {\n throw err\n }\n const shouldRetry =\n typeof this.retry === 'number' ? attempt < this.retry : this.retry(attempt, err)\n if (!shouldRetry) {\n batch(() => {\n this.error.set(err)\n this.status.set('error')\n this.isLoading.set(false)\n this.isFetching.set(false)\n if (direction === 'next') this.isFetchingNextPage.set(false)\n if (direction === 'prev') this.isFetchingPreviousPage.set(false)\n })\n throw err\n }\n const delay = this.computeRetryDelay(attempt)\n await abortableSleep(delay, signal)\n attempt += 1\n }\n }\n } finally {\n // Catch-all reset for the supersede/abort path. The success and explicit\n // failure paths already reset these via `onSuccess` and the\n // `applyFailure`-equivalent branch above; this guarantees that an\n // aborted-mid-flight `fetchNextPage` (e.g., user calls `invalidate()`\n // while paging) doesn't wedge the spinner.\n if (!succeeded) {\n batch(() => {\n if (direction === 'next') this.isFetchingNextPage.set(false)\n if (direction === 'prev') this.isFetchingPreviousPage.set(false)\n // Status repair (T3.3): a superseded fetch must never leave the\n // entry wedged at 'pending' when data is present and nothing is\n // fetching. The superseding fetch normally owns the final status\n // (its onSuccess sets 'success'); this is the safety net for the\n // terminal fetch of a supersede chain. Only repair 'pending' — never\n // clobber a real 'error' — and only when no fetch is still running.\n if (\n !this.disposed &&\n this.status.peek() === 'pending' &&\n !this.isFetching.peek() &&\n this.pages.peek().length > 0\n ) {\n this.status.set('success')\n }\n })\n }\n }\n }\n\n refetch(): Promise<TPage> {\n return this.startFetch()\n }\n\n /** Force stale without fetching — see `Entry.markStale` (spec §5.7, T3.9). */\n markStale(): void {\n if (this.disposed) return\n if (this.staleTimer != null) {\n clearTimeout(this.staleTimer)\n this.staleTimer = null\n }\n this.forcedStale = true\n this.isStale.set(true)\n }\n\n invalidate(): Promise<TPage> {\n this.markStale()\n return this.startFetch()\n }\n\n reset(): void {\n if (this.disposed) return\n batch(() => {\n this.error.set(undefined)\n this.status.set(this.pages.peek().length > 0 ? 'success' : 'idle')\n })\n }\n\n /** Cancel an in-flight fetch (initial/refetch or paging) without touching\n * pages. Supersedes + aborts the current request, then restores a settled\n * status. No-op when idle. Mirrors `Entry.cancel` (spec §5, §6.4, T3.4). */\n cancel(): void {\n if (this.disposed || !this.isFetching.peek()) return\n this.currentFetchId += 1\n this.currentAbort?.abort()\n this.currentAbort = null\n batch(() => {\n this.isFetching.set(false)\n this.isLoading.set(false)\n this.isFetchingNextPage.set(false)\n this.isFetchingPreviousPage.set(false)\n this.status.set(this.pages.peek().length > 0 ? 'success' : 'idle')\n })\n }\n\n setData(updater: (prev: TPage[] | undefined) => TPage[], opts?: { track?: boolean }): Snapshot {\n if (this.disposed) {\n return { rollback: () => {}, finalize: () => {} }\n }\n const prev = this.pages.peek()\n const prevParams = this.pageParams.peek()\n const next = updater(prev.length === 0 ? undefined : prev)\n // `track: false` is a canonical cache write (plugin/remote/entities\n // backprop) — no optimistic snapshot, no `hasPendingMutations` flip. See\n // `Entry.setData` for the full rationale. Default `true` keeps the\n // optimistic-update path (`query.setData` in `onMutate`).\n const track = opts?.track ?? true\n // Snapshot BOTH pages and pageParams so rollback restores a consistent\n // pair. Without `prevParams`, an optimistic insert would shift `pages`\n // permanently out of sync with `pageParams` on rollback — and any\n // subsequent `fetchNextPage`/`getNextPageParam` would operate on the\n // wrong head.\n const record = track ? { id: this.nextSnapshotId++, prev, prevParams, live: true } : null\n if (record) this.snapshots.push(record)\n\n // If the updater changed the page count, trim or pad pageParams so the\n // two arrays stay length-aligned. Padding uses the last known param,\n // which is the safest neutral choice — the caller of `setData` should\n // re-key via a real fetch (or use a future param-aware overload) if\n // the new page needs a fresh param.\n let nextParams: PageParam[] = prevParams\n if (next.length !== prevParams.length) {\n if (next.length < prevParams.length) {\n nextParams = prevParams.slice(0, next.length)\n } else {\n const pad = prevParams[prevParams.length - 1]\n nextParams = prevParams.slice()\n for (let i = prevParams.length; i < next.length; i++) {\n nextParams.push(pad as PageParam)\n }\n }\n }\n\n batch(() => {\n this.pages.set(next)\n if (nextParams !== prevParams) this.pageParams.set(nextParams)\n if (this.status.peek() === 'idle' || this.status.peek() === 'pending') {\n this.status.set('success')\n }\n this.lastUpdatedAt.set(Date.now())\n if (record) this.hasPendingMutations.set(true)\n })\n\n if (!record) {\n return { rollback: () => {}, finalize: () => {} }\n }\n const id = record.id\n return {\n rollback: () => {\n if (!record.live || this.disposed) return\n record.live = false\n batch(() => {\n const i = this.snapshots.indexOf(record)\n if (i !== -1) {\n if (i === this.snapshots.length - 1) {\n // Top of the stack: restore this layer's captured baseline pair\n // (pages + params stay length-aligned — see the snapshot note).\n this.pages.set(record.prev)\n this.pageParams.set(record.prevParams)\n } else {\n // Not the top: leave current pages/params alone and thread this\n // layer's baseline down onto the next layer, so a later\n // top-rollback lands on the correct pre-everything pages instead\n // of resurrecting this layer's delta (chain-splice — T3.1, spec\n // §6.4). Mirrors `Entry.setData`.\n const below = this.snapshots[i + 1] as (typeof this.snapshots)[number]\n below.prev = record.prev\n below.prevParams = record.prevParams\n }\n this.snapshots.splice(i, 1)\n }\n this.hasPendingMutations.set(this.snapshots.some((s) => s.live))\n })\n },\n finalize: () => {\n if (!record.live || this.disposed) return\n record.live = false\n this.snapshots = this.snapshots.filter((s) => s.id !== id)\n if (!this.snapshots.some((s) => s.live)) {\n this.hasPendingMutations.set(false)\n }\n },\n }\n }\n\n firstValue(): Promise<TPage[]> {\n if (this.disposed) {\n return Promise.reject(new DOMException('Entry disposed', 'AbortError'))\n }\n if (this.status.peek() === 'success') {\n return Promise.resolve(this.pages.peek())\n }\n if (this.status.peek() === 'error') {\n return Promise.reject(this.error.peek())\n }\n return new Promise<TPage[]>((resolve, reject) => {\n const tracked = (err: unknown): void => {\n this.pendingFirstValueRejects = this.pendingFirstValueRejects.filter((f) => f !== tracked)\n reject(err)\n }\n this.pendingFirstValueRejects.push(tracked)\n const unsub = this.status.subscribe((s) => {\n if (s === 'success') {\n unsub()\n this.pendingFirstValueRejects = this.pendingFirstValueRejects.filter((f) => f !== tracked)\n resolve(this.pages.peek())\n } else if (s === 'error') {\n unsub()\n tracked(this.error.peek())\n }\n })\n })\n }\n\n isStaleNow(): boolean {\n if (this.forcedStale) return true\n const last = this.lastUpdatedAt.peek()\n if (last === undefined) return true\n return Date.now() - last >= this.staleTime\n }\n\n private computeRetryDelay(attempt: number): number {\n const d = this.retryDelay\n // Exponential backoff default when retries are on but no retryDelay given\n // (mirrors Entry.computeDelay — T3.9).\n if (d === undefined) return Math.min(1000 * 2 ** attempt, 30_000)\n return typeof d === 'function' ? d(attempt) : d\n }\n\n private isOffline(): boolean {\n return typeof navigator !== 'undefined' && navigator.onLine === false\n }\n\n private scheduleDeferredFetch(direction: 'initial' | 'next' | 'prev'): Promise<unknown> {\n // Parked waiting for reconnect (T3.5). Cleared when a fetch actually\n // starts (`startFetch` batch) or on drain.\n this.isPaused.set(true)\n if (this.reconnectUnsub === null) {\n this.reconnectUnsub = subscribeReconnect(() => this.drainDeferred())\n }\n return new Promise<void>((resolve, reject) => {\n this.deferredResolvers.push({ direction, resolve, reject })\n })\n }\n\n private drainDeferred(): void {\n if (this.deferredResolvers.length === 0) return\n if (this.disposed) return\n this.isPaused.set(false)\n const pending = this.deferredResolvers\n this.deferredResolvers = []\n if (this.reconnectUnsub !== null) {\n this.reconnectUnsub()\n this.reconnectUnsub = null\n }\n // Collapse multiple deferrals of the same direction into one real fetch.\n // Order matters: initial first (it may produce data the others need),\n // then prev / next.\n const seen = new Set<'initial' | 'next' | 'prev'>()\n const order: Array<'initial' | 'next' | 'prev'> = ['initial', 'prev', 'next']\n for (const d of pending) {\n seen.add(d.direction)\n }\n const run = async () => {\n for (const dir of order) {\n if (!seen.has(dir)) continue\n if (dir === 'initial') await this.startFetch()\n else if (dir === 'next') await this.fetchNextPage()\n else await this.fetchPreviousPage()\n }\n }\n run().then(\n () => {\n for (const p of pending) p.resolve()\n },\n (err) => {\n for (const p of pending) p.reject(err)\n },\n )\n }\n\n private scheduleStaleness(): void {\n if (this.staleTimer != null) clearTimeout(this.staleTimer)\n if (this.staleTime > 0) {\n this.staleTimer = setTimeout(() => {\n this.staleTimer = null\n if (!this.disposed) this.isStale.set(true)\n }, this.staleTime)\n }\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n if (this.staleTimer != null) {\n clearTimeout(this.staleTimer)\n this.staleTimer = null\n }\n this.currentAbort?.abort()\n this.currentAbort = null\n // A disposed entry is idle — reset the in-flight flags so `waitForIdle`\n // can't hang on a fetch racing dispose (T3.9). Mirrors `Entry.dispose`.\n batch(() => {\n this.isFetching.set(false)\n this.isLoading.set(false)\n this.isFetchingNextPage.set(false)\n this.isFetchingPreviousPage.set(false)\n })\n if (this.reconnectUnsub !== null) {\n this.reconnectUnsub()\n this.reconnectUnsub = null\n }\n if (this.deferredResolvers.length > 0) {\n const disposed = new DOMException('Entry disposed', 'AbortError')\n const pending = this.deferredResolvers\n this.deferredResolvers = []\n for (const p of pending) p.reject(disposed)\n }\n if (this.pendingFirstValueRejects.length > 0) {\n const disposed = new DOMException('Entry disposed', 'AbortError')\n const rejects = this.pendingFirstValueRejects\n this.pendingFirstValueRejects = []\n for (const fn of rejects) fn(disposed)\n }\n }\n}\n","/**\n * Stable string hash of a key tuple. Two equal-by-content args produce the\n * same string regardless of property iteration order. Handles primitives,\n * arrays, plain objects, Date, BigInt, NaN, ±Infinity.\n *\n * Functions and symbols throw — keys must be serializable so distinct\n * subscribers can share entries.\n */\nexport function stableHash(args: readonly unknown[]): string {\n return JSON.stringify(args, replacer)\n}\n\n// A regular `function` (not an arrow) so `this` is bound to the holder object\n// by `JSON.stringify`. Critical: `JSON.stringify` applies `toJSON()` to a value\n// BEFORE calling the replacer, so the `value` argument for a `Date` is already\n// its ISO string and a class instance with a `toJSON` is already its serialized\n// form — inspecting `value` would miss both (the old arrow did, making the Date\n// tag and the class-instance throw dead code: `stableHash([date])` collided\n// with `stableHash([date.toISOString()])`). Reading the RAW property off the\n// holder (`this[key]`) recovers the true pre-`toJSON` value. Spec §5.4; T3.8.\nconst replacer = function (this: unknown, key: string, _value: unknown): unknown {\n const value = (this as Record<string, unknown>)[key]\n if (typeof value === 'function') {\n throw new Error('[olas] query keys cannot contain functions')\n }\n if (typeof value === 'symbol') {\n throw new Error('[olas] query keys cannot contain symbols')\n }\n if (typeof value === 'bigint') {\n // JSON has no bigint; serialize as a tagged string so `1n` and `'1'`\n // don't collide. The tag survives round-trips for debugging.\n return { __bigint: value.toString() }\n }\n if (typeof value === 'number') {\n // `JSON.stringify(NaN)` → `'null'` and likewise for Infinity, which\n // would collide with a literal `null` key. Tag them explicitly.\n if (Number.isNaN(value)) return '__nan__'\n if (value === Number.POSITIVE_INFINITY) return '__+inf__'\n if (value === Number.NEGATIVE_INFINITY) return '__-inf__'\n return value\n }\n if (value === undefined) return '__undefined__'\n if (value instanceof Date) return { __date: value.toISOString() }\n if (value instanceof Map || value instanceof Set) {\n throw new Error('[olas] query keys cannot contain Map/Set — use arrays/objects')\n }\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n // Reject class instances (proto !== Object.prototype): two `new MyKey(1)`\n // calls would serialize identically to `{}` and collide. Plain objects\n // pass through with sorted keys.\n const proto = Object.getPrototypeOf(value)\n if (proto !== null && proto !== Object.prototype) {\n throw new Error(\n `[olas] query keys cannot contain class instances (got ${proto.constructor?.name ?? 'unknown'}) — pass plain object/array data`,\n )\n }\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(value).sort()) {\n sorted[k] = (value as Record<string, unknown>)[k]\n }\n return sorted\n }\n return value\n}\n","/**\n * `QueryClientPlugin` — a slot for layered cache concerns (cross-tab sync,\n * server-push patches, persistence-like layers) that need to observe\n * `setData` / `invalidate` / `gc` and apply remote writes back into the\n * cache without re-triggering their own outbound side-effects.\n *\n * Plugins are installed via `RootOptions.plugins[]`; lifecycle is bound to\n * the root's `QueryClient` (`init` is called once after construction;\n * `dispose` is called from `QueryClient.dispose`).\n *\n * SPEC §13.2.\n */\n\n/**\n * Surface the plugin gets at `init` time. Used to push remote-originated\n * cache writes through the normal `setData`/`invalidate` paths without\n * triggering the plugin's own outbound hooks for those writes (the inbound\n * writes are marked `isRemote: true` and rebroadcast must be skipped).\n *\n * `subscribedKeys(queryId)` walks the per-root entry registry for the\n * matching query and returns every bound entry's `keyArgs`. Cross-tab\n * plugins use this to scope outbound traffic (e.g. only echo invalidations\n * for queries the local tab actually has entries for).\n */\nexport type QueryClientPluginApi = {\n /**\n * Apply a remote snapshot. The plugin's own `onSetData` IS fired for the\n * resulting cache write, but the event carries `isRemote: true` — plugins\n * MUST skip rebroadcast in that case.\n */\n applyRemoteSetData(queryId: string, keyArgs: readonly unknown[], data: unknown): void\n applyRemoteInvalidate(queryId: string, keyArgs: readonly unknown[]): void\n /**\n * Apply a local-originated `setData` to the entry identified by\n * `(queryId, keyArgs)`. The resulting plugin events fire with\n * `isRemote: false` and `source: 'set'` — cross-tab plugins WILL\n * rebroadcast (the write is treated as if a controller called\n * `client.setData(...)` directly).\n *\n * Drops silently when the queryId is unknown, the registered query is\n * infinite, or no local entry exists for that key. The `updater`\n * receives the previous data (typed as `unknown` because plugins are\n * type-erased) and returns the next.\n *\n * Use case: entity-normalization plugins that want to backpropagate an\n * `entity.update(...)` patch into every query holding that entity.\n * Mutations / optimistic updates already go through the public\n * `client.setData` and don't need this API.\n */\n setEntryData(\n queryId: string,\n keyArgs: readonly unknown[],\n updater: (prev: unknown) => unknown,\n ): void\n /**\n * Snapshot of currently bound entry keys for a query (by `queryId`). Empty\n * array when the query isn't registered, has no client entries, or the\n * `queryId` doesn't match any registered query.\n *\n * @example\n * ```ts\n * // Plugin sees an incoming invalidate; only echo it outward if any local\n * // controller is actually subscribed to that key — otherwise the message\n * // is unilateral noise.\n * const plugin: QueryClientPlugin = {\n * init(api) { this.api = api },\n * onInvalidate(ev) {\n * if (ev.isRemote) return\n * const subscribed = this.api.subscribedKeys(ev.queryId)\n * if (subscribed.length === 0) return // no local subscribers → don't send\n * transport.send({ type: 'invalidate', queryId: ev.queryId, keyArgs: ev.keyArgs })\n * },\n * }\n * ```\n */\n subscribedKeys(queryId: string): readonly (readonly unknown[])[]\n}\n\nexport type SetDataEvent = {\n queryId: string\n keyArgs: readonly unknown[]\n data: unknown\n /**\n * `'data'` for regular queries, `'infinite'` for paginated queries.\n * Cross-tab plugins skip `'infinite'` in v1 — page-array payloads are\n * too heavy to be a safe default.\n */\n kind: 'data' | 'infinite'\n /**\n * True iff this write originated from `applyRemoteSetData`. Plugins MUST\n * skip rebroadcast in that case — otherwise the message would echo back.\n */\n isRemote: boolean\n /**\n * Origin of the write. `'set'` covers explicit `client.setData` (mutations,\n * optimistic updates AND their `snapshot.rollback()`, plugin-initiated\n * patches) — a rollback re-broadcasts the restored value so peers drop the\n * failed optimistic state (T3.6). `'fetch'` fires when the\n * query fetcher resolved successfully and wrote the result into the entry\n * — emitted after the data signal is settled. `'remote'` is the\n * `applyRemoteSetData` path (cross-tab / server-push); equivalent to\n * `isRemote === true`.\n *\n * Layered plugins use this to decide whether to react: cross-tab broadcasts\n * only on `'set'`, an entity-normalization plugin observes all sources.\n */\n source: 'set' | 'fetch' | 'remote'\n}\n\nexport type InvalidateEvent = {\n queryId: string\n keyArgs: readonly unknown[]\n kind: 'data' | 'infinite'\n isRemote: boolean\n}\n\nexport type GcEvent = {\n queryId: string\n keyArgs: readonly unknown[]\n kind: 'data' | 'infinite'\n}\n\n/**\n * Emitted when a persistable mutation (`spec.persist === true`) starts\n * executing — before the user's `mutate` is invoked. Plugins use this to\n * persist the variables to durable storage; if the page reloads mid-run,\n * the queue replays from these entries.\n *\n * `runId` is unique per execution (a single `mutation.run(...)` call OR a\n * replay attempt). `attempt` counts retry passes within a single runId.\n */\nexport type MutationEnqueueEvent = {\n mutationId: string\n runId: string\n variables: unknown\n attempt: number\n}\n\n/**\n * Emitted after a persistable mutation settles. Plugins use this to drop\n * the run from the durable queue (on `'success'` or `'error'` after retries\n * exhaust), or to leave it pending (on `'cancelled'` — e.g. parent dispose\n * mid-flight).\n */\nexport type MutationSettleEvent = {\n mutationId: string\n runId: string\n outcome: 'success' | 'error' | 'cancelled'\n /** Only present on `'error'` — the final thrown value after retries. */\n error?: unknown\n}\n\n/**\n * Plugin contract. Every hook is optional. Hooks are wrapped in try/catch\n * by `QueryClient`; thrown exceptions are routed through the root's\n * `onError` handler with `kind: 'plugin'`.\n */\nexport type QueryClientPlugin = {\n /**\n * Optional human-readable identifier surfaced in `ErrorContext.pluginName`\n * when this plugin's callback throws. Without it, `pluginName` is left\n * `undefined`. Recommended for shipped plugins so Sentry/OTel adapters\n * can attribute errors back to the right package.\n */\n readonly name?: string\n /**\n * Called once after the `QueryClient` is constructed. Use it to wire up\n * transport listeners and capture the `QueryClientPluginApi`. SPEC §13.2.\n *\n * Persistable-mutation replay typically happens HERE — module-scope\n * `defineMutation(...)` calls have already registered their handlers by\n * the time `createRoot(...)` runs, so `init` can walk durable storage\n * and re-invoke registered mutates for any pending entries.\n */\n init?(api: QueryClientPluginApi): void\n onSetData?(event: SetDataEvent): void\n onInvalidate?(event: InvalidateEvent): void\n onGc?(event: GcEvent): void\n /**\n * Fired when a persistable mutation (`spec.persist === true`) starts\n * executing. SPEC §13.3.\n */\n onMutationEnqueue?(event: MutationEnqueueEvent): void\n /** Fired after a persistable mutation settles. SPEC §13.3. */\n onMutationSettle?(event: MutationSettleEvent): void\n /** Called from `QueryClient.dispose`. Tear down transports / listeners here. */\n dispose?(): void\n}\n\n/**\n * Internal helper — fetch the `queryId` from a query's spec without\n * peeking into private types. Returns `undefined` for queries that didn't\n * declare a `queryId`; plugin events are then skipped (a plugin can't route\n * by name without one).\n */\nexport function readQueryId(query: { readonly __spec: { queryId?: string } }): string | undefined {\n return query.__spec.queryId\n}\n\n/**\n * Shape of values stored in the `queryId → Query` registry. Either a\n * regular `Query` or an `InfiniteQuery`, both branded by `__olas`.\n */\nexport type RegisteredQuery = {\n readonly __olas: 'query' | 'infiniteQuery'\n readonly __spec: { queryId?: string; crossTab?: boolean }\n}\n\n/**\n * Back a module-level registry on `globalThis` under a shared `Symbol.for`\n * key. Guards the dual-package hazard: if a consumer ends up with both the ESM\n * and CJS build of `@kontsedal/olas-core` (common with mixed bundler configs),\n * each copy would otherwise own a SEPARATE registry `Map` — a mutation\n * registered via the ESM copy would be invisible to the mutation-queue plugin\n * loaded against the CJS copy, and cross-tab query lookups would miss. Sharing\n * one Map on `globalThis` makes both copies agree. T3.9.\n */\nfunction globalRegistry<V>(key: symbol): Map<string, V> {\n const store = globalThis as unknown as Record<symbol, Map<string, V> | undefined>\n const existing = store[key]\n if (existing) return existing\n const created = new Map<string, V>()\n store[key] = created\n return created\n}\n\nconst queryRegistry = globalRegistry<RegisteredQuery>(Symbol.for('olas.queryRegistry'))\n\n/**\n * Register a query by its `queryId`. Internal — called from `defineQuery` /\n * `defineInfiniteQuery`. Replaces any previous registration with the same\n * id (matches Olas's \"full root rebuild\" HMR story; a mid-flight remote\n * message routed against the old `Query` simply misses). Dev-warns when a\n * *different* query overwrites an existing id — a genuine collision, since\n * cross-tab / persistence route by `queryId` (expected during HMR).\n */\nexport function registerQueryById(queryId: string, query: RegisteredQuery): void {\n if (__DEV__) {\n const existing = queryRegistry.get(queryId)\n if (existing !== undefined && existing !== query) {\n console.warn(\n `[olas] duplicate queryId \"${queryId}\": a different query is replacing an existing ` +\n 'registration. `queryId` must be unique per query (cross-tab / persistence route by it). ' +\n 'Expected during HMR; a collision bug otherwise.',\n )\n }\n }\n queryRegistry.set(queryId, query)\n}\n\n/**\n * Look up a query by its declared `queryId`. Returns `undefined` when no\n * query with that id has been defined yet (e.g. the module isn't imported\n * in the receiving tab).\n */\nexport function lookupRegisteredQuery(queryId: string): RegisteredQuery | undefined {\n return queryRegistry.get(queryId)\n}\n\n/**\n * Test-only — drop a registered entry. Lets tests defining the same\n * `queryId` across cases avoid bleed. Not exported from `@kontsedal/olas-core`.\n */\nexport function _unregisterQueryById(queryId: string): void {\n queryRegistry.delete(queryId)\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Mutation registry — parallel to query registry. Persistable mutations\n// (`spec.persist === true`) register themselves at module-import time via\n// `defineMutation(...)` so the mutation-queue plugin can replay pending\n// runs at `init` time, BEFORE controllers reconstruct.\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Shape stored in the `mutationId → handler` registry. Only the `mutate`\n * function and the id are needed for replay — lifecycle hooks like\n * `onSuccess` / `onError` are per-controller and can't be safely replayed\n * across page reloads (the controller doesn't exist yet).\n */\nexport type RegisteredMutation = {\n readonly mutationId: string\n /**\n * Replay-safe `mutate`. Matches `MutationSpec.mutate` 1:1 — receives the\n * variables and an `AbortSignal`. The mutation-queue plugin invokes this\n * directly on replay, so the implementation MUST NOT close over\n * controller-instance state. Module-level deps (a shared `api` client,\n * etc.) are fine.\n */\n readonly mutate: (vars: unknown, signal: AbortSignal) => Promise<unknown>\n}\n\nconst mutationRegistry = globalRegistry<RegisteredMutation>(Symbol.for('olas.mutationRegistry'))\n\n/** Register a mutation by its `mutationId`. Internal — called from `defineMutation`. */\nexport function registerMutationById(mutationId: string, entry: RegisteredMutation): void {\n mutationRegistry.set(mutationId, entry)\n}\n\n/**\n * Look up a registered mutation by id. Returns `undefined` when no\n * mutation with that id has been defined — typical when a queue entry\n * references a mutation whose module hasn't been imported (e.g. a\n * code-split route boundary). The plugin should leave such entries in\n * place and retry once the module loads.\n */\nexport function lookupRegisteredMutation(mutationId: string): RegisteredMutation | undefined {\n return mutationRegistry.get(mutationId)\n}\n\n/** Test-only — drop a registered mutation. Not exported from the package. */\nexport function _unregisterMutationById(mutationId: string): void {\n mutationRegistry.delete(mutationId)\n}\n","import type { DevtoolsEmitter } from '../devtools'\nimport { dispatchError, type ErrorHandler } from '../errors'\nimport { type Signal, signal } from '../signals'\nimport { isAbortError } from '../utils'\nimport { Entry } from './entry'\nimport { subscribeReconnect, subscribeWindowFocus } from './focus-online'\nimport { InfiniteEntry, type InfiniteQuery, type InfiniteQuerySpec } from './infinite'\nimport { stableHash } from './keys'\nimport {\n type GcEvent,\n type InvalidateEvent,\n lookupRegisteredQuery,\n type QueryClientPlugin,\n type QueryClientPluginApi,\n type SetDataEvent,\n} from './plugin'\nimport type { DehydratedState, Query, QuerySpec, RetryDelay, RetryPolicy, Snapshot } from './types'\n\nconst DEFAULT_GC_TIME = 5 * 60_000\n\ntype AnyQuery = Query<any, any> & {\n readonly __spec: QuerySpec<any, any>\n readonly __id: string\n __clients: Set<QueryClient>\n}\n\ntype AnyInfiniteQuery = InfiniteQuery<any, any, any> & {\n readonly __spec: InfiniteQuerySpec<any, any, any, any>\n readonly __id: string\n __clients: Set<QueryClient>\n}\n\n/**\n * Composite hydration-buffer key: query identity + key hash. Namespacing by\n * identity stops a dehydrated entry for query A being adopted by query B that\n * merely hashes to the same key (spec §15, T1.2). `JSON.stringify` of the pair\n * is used rather than string concatenation so no separator char is ambiguous —\n * both `id` (an arbitrary user `queryId`) and `hash` are unbounded strings.\n */\nconst hydrationKey = (id: string, hash: string): string => JSON.stringify([id, hash])\n\nexport class ClientEntry<T> {\n readonly entry: Entry<T>\n /** The result of `spec.key(...args)` — used for hashing/identity. */\n readonly keyArgs: readonly unknown[]\n /** The original args the consumer passed — what the fetcher receives. */\n readonly callArgs: readonly unknown[]\n readonly client: QueryClient\n readonly query: AnyQuery\n private subscriberCount = 0\n private gcTimer: ReturnType<typeof setTimeout> | null = null\n private intervalTimer: ReturnType<typeof setInterval> | null = null\n private unsubFocus: (() => void) | null = null\n private unsubOnline: (() => void) | null = null\n private gcTime: number\n private refetchInterval: number | undefined\n private refetchOnWindowFocus: boolean\n private refetchOnReconnect: boolean\n\n constructor(\n client: QueryClient,\n query: AnyQuery,\n callArgs: readonly unknown[],\n keyArgs: readonly unknown[],\n spec: QuerySpec<any, T>,\n hydrated: { data: T; lastUpdatedAt: number } | undefined,\n /**\n * Prepared by `QueryClient.bindEntry` (which is the only construction\n * site). When the query has a `queryId`, the closure calls back into\n * `QueryClient.emitSetData` with `source: 'fetch'` after every\n * successful fetch. We accept it pre-built rather than reach into the\n * client from here because `emitSetData` is `private` on `QueryClient`\n * — restricting the access path is the whole point.\n */\n onFetchSuccess: ((data: T) => void) | undefined,\n ) {\n this.client = client\n this.query = query\n this.callArgs = callArgs\n this.keyArgs = keyArgs\n this.gcTime = spec.gcTime ?? DEFAULT_GC_TIME\n this.refetchInterval = spec.refetchInterval\n this.refetchOnWindowFocus = spec.refetchOnWindowFocus ?? client.refetchOnWindowFocus\n this.refetchOnReconnect = spec.refetchOnReconnect ?? client.refetchOnReconnect\n const fetcherFn = spec.fetcher\n const deps = client.deps as import('../controller/types').AmbientDeps\n const devtools = client.devtools\n const queryKey = this.keyArgs\n this.entry = new Entry<T>({\n fetcher: () => (signal) => fetcherFn({ signal, deps }, ...(callArgs as never[])),\n staleTime: spec.staleTime,\n retry: spec.retry as RetryPolicy | undefined,\n retryDelay: spec.retryDelay as RetryDelay | undefined,\n networkMode: spec.networkMode,\n structuralShare: spec.structuralShare,\n initialData: hydrated?.data,\n initialUpdatedAt: hydrated?.lastUpdatedAt,\n events:\n __DEV__ && devtools !== undefined\n ? {\n onFetchStart: () => devtools.emit({ type: 'cache:fetch-start', queryKey }),\n onFetchSuccess: (durationMs) =>\n devtools.emit({ type: 'cache:fetch-success', queryKey, durationMs }),\n onFetchError: (durationMs, error) =>\n devtools.emit({\n type: 'cache:fetch-error',\n queryKey,\n durationMs,\n error,\n }),\n }\n : undefined,\n onSuccessData: onFetchSuccess,\n })\n }\n\n acquire(): void {\n this.subscriberCount += 1\n if (this.gcTimer != null) {\n clearTimeout(this.gcTimer)\n this.gcTimer = null\n }\n if (this.subscriberCount === 1) {\n if (this.refetchInterval != null) this.startIntervalTimer()\n if (this.refetchOnWindowFocus) {\n this.unsubFocus = subscribeWindowFocus(() => this.triggerEventRefetch())\n }\n if (this.refetchOnReconnect) {\n this.unsubOnline = subscribeReconnect(() => this.triggerEventRefetch())\n }\n }\n }\n\n release(): void {\n this.subscriberCount -= 1\n if (this.subscriberCount <= 0) {\n this.stopIntervalTimer()\n this.stopEventSubscriptions()\n if (this.gcTime === 0) {\n this.client.dropEntry(this)\n } else {\n this.gcTimer = setTimeout(() => {\n this.gcTimer = null\n this.client.dropEntry(this)\n }, this.gcTime)\n }\n }\n }\n\n hasSubscribers(): boolean {\n return this.subscriberCount > 0\n }\n\n startIntervalTimer(): void {\n if (this.refetchInterval == null) return\n if (this.intervalTimer != null) return\n this.intervalTimer = setInterval(() => {\n // Skip when the tab is hidden — refetching while in background wastes\n // battery and network. `refetchOnWindowFocus` (when enabled) will\n // catch the entry up on visibility return; pure-interval users without\n // focus-refetch get the catch-up via `acquire()` re-arming the timer\n // when they next mount.\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {\n return\n }\n // Join an in-flight fetch instead of aborting it. `startFetch()` aborts\n // the current request, so a fetch slower than the interval would\n // livelock — abort→restart every tick, never completing, hammering one\n // aborted request per interval (T3.2). Skip the tick; the running fetch\n // will finish and the next tick re-arms once it's idle.\n if (this.entry.isFetching.peek()) return\n this.entry.startFetch().catch(() => {\n /* error already captured on entry */\n })\n }, this.refetchInterval)\n }\n\n stopIntervalTimer(): void {\n if (this.intervalTimer != null) {\n clearInterval(this.intervalTimer)\n this.intervalTimer = null\n }\n }\n\n stopEventSubscriptions(): void {\n if (this.unsubFocus != null) {\n this.unsubFocus()\n this.unsubFocus = null\n }\n if (this.unsubOnline != null) {\n this.unsubOnline()\n this.unsubOnline = null\n }\n }\n\n /**\n * Schedule a gc timer for an entry that was just created via a non-subscribing\n * path (`prefetch`, `setData`, `invalidate`). Without this, those entries\n * never trigger `release()` and would live until root dispose. Called by\n * `QueryClient.bindEntry` right after creating a fresh entry; `acquire()`\n * (e.g., from a subscriber that arrives shortly after a prefetch) clears it.\n * No-op if the entry already has subscribers or a gc timer pending.\n */\n scheduleGcIfOrphan(): void {\n if (this.subscriberCount > 0 || this.gcTimer != null) return\n if (this.gcTime === 0) {\n // Defer one microtask so the current caller (e.g. a `setData` that\n // writes then expects to read back in the same tick) sees the entry.\n queueMicrotask(() => {\n if (this.subscriberCount === 0 && this.gcTimer == null) {\n this.client.dropEntry(this)\n }\n })\n return\n }\n this.gcTimer = setTimeout(() => {\n this.gcTimer = null\n this.client.dropEntry(this)\n }, this.gcTime)\n }\n\n /** Refetch on focus / reconnect, but only if the data is actually stale. */\n private triggerEventRefetch(): void {\n if (!this.entry.isStaleNow()) return\n // Join an in-flight fetch instead of aborting + restarting it — a focus /\n // reconnect landing mid-fetch shouldn't cancel it (T3.9, cf. T3.2 interval).\n if (this.entry.isFetching.peek()) return\n this.entry.startFetch().catch(() => {\n /* error already captured on entry */\n })\n }\n\n dispose(): void {\n if (this.gcTimer != null) {\n clearTimeout(this.gcTimer)\n this.gcTimer = null\n }\n this.stopIntervalTimer()\n this.stopEventSubscriptions()\n this.entry.dispose()\n }\n}\n\nexport class InfiniteClientEntry<TPage, TItem, PageParam> {\n readonly entry: InfiniteEntry<TPage, TItem, PageParam>\n readonly keyArgs: readonly unknown[]\n readonly callArgs: readonly unknown[]\n readonly client: QueryClient\n readonly query: AnyInfiniteQuery\n private subscriberCount = 0\n private gcTimer: ReturnType<typeof setTimeout> | null = null\n private intervalTimer: ReturnType<typeof setInterval> | null = null\n private gcTime: number\n private refetchInterval: number | undefined\n\n constructor(\n client: QueryClient,\n query: AnyInfiniteQuery,\n callArgs: readonly unknown[],\n keyArgs: readonly unknown[],\n spec: InfiniteQuerySpec<any, PageParam, TPage, TItem>,\n /**\n * Prepared by `QueryClient.bindInfiniteEntry`. When the infinite query\n * has a `queryId`, the closure calls back into `QueryClient.emitSetData`\n * with `kind: 'infinite', source: 'fetch'` after every successful page\n * write (initial, next, prev). Mirrors `ClientEntry.onFetchSuccess`.\n */\n onFetchSuccess: ((pages: TPage[]) => void) | undefined,\n ) {\n this.client = client\n this.query = query\n this.callArgs = callArgs\n this.keyArgs = keyArgs\n this.gcTime = spec.gcTime ?? DEFAULT_GC_TIME\n this.refetchInterval = spec.refetchInterval\n const fetcherFn = spec.fetcher\n const deps = client.deps as import('../controller/types').AmbientDeps\n this.entry = new InfiniteEntry<TPage, TItem, PageParam>({\n fetcher: ({ pageParam, signal }) =>\n fetcherFn({ pageParam, signal, deps }, ...(callArgs as never[])),\n initialPageParam: spec.initialPageParam,\n getNextPageParam: spec.getNextPageParam,\n getPreviousPageParam: spec.getPreviousPageParam,\n itemsOf: spec.itemsOf,\n staleTime: spec.staleTime,\n retry: spec.retry as RetryPolicy | undefined,\n retryDelay: spec.retryDelay as RetryDelay | undefined,\n networkMode: spec.networkMode,\n structuralShare: spec.structuralShare,\n // Fire SetDataEvent { kind: 'infinite', source: 'fetch' } whenever a\n // fetch settles successfully. Plugins (e.g. entity normalization) use\n // this to walk the pages and update their normalized stores. Mirrors\n // the regular `ClientEntry`'s `onFetchSuccess` closure plumbing.\n onSuccessData: onFetchSuccess,\n })\n }\n\n acquire(): void {\n this.subscriberCount += 1\n if (this.gcTimer != null) {\n clearTimeout(this.gcTimer)\n this.gcTimer = null\n }\n if (this.subscriberCount === 1 && this.refetchInterval != null) {\n this.startIntervalTimer()\n }\n }\n\n hasSubscribers(): boolean {\n return this.subscriberCount > 0\n }\n\n release(): void {\n this.subscriberCount -= 1\n if (this.subscriberCount <= 0) {\n this.stopIntervalTimer()\n if (this.gcTime === 0) {\n this.client.dropInfiniteEntry(\n this as unknown as InfiniteClientEntry<unknown, unknown, unknown>,\n )\n } else {\n this.gcTimer = setTimeout(() => {\n this.gcTimer = null\n this.client.dropInfiniteEntry(\n this as unknown as InfiniteClientEntry<unknown, unknown, unknown>,\n )\n }, this.gcTime)\n }\n }\n }\n\n private startIntervalTimer(): void {\n if (this.refetchInterval == null || this.intervalTimer != null) return\n this.intervalTimer = setInterval(() => {\n // Same visibility-gate as the regular `ClientEntry.startIntervalTimer`.\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {\n return\n }\n // Join an in-flight fetch instead of aborting it (T3.2) — see the\n // regular `ClientEntry.startIntervalTimer` for the livelock rationale.\n if (this.entry.isFetching.peek()) return\n this.entry.startFetch().catch(() => {\n /* error captured on entry */\n })\n }, this.refetchInterval)\n }\n\n private stopIntervalTimer(): void {\n if (this.intervalTimer != null) {\n clearInterval(this.intervalTimer)\n this.intervalTimer = null\n }\n }\n\n /** See `ClientEntry.scheduleGcIfOrphan`. */\n scheduleGcIfOrphan(): void {\n if (this.subscriberCount > 0 || this.gcTimer != null) return\n if (this.gcTime === 0) {\n queueMicrotask(() => {\n if (this.subscriberCount === 0 && this.gcTimer == null) {\n this.client.dropInfiniteEntry(\n this as unknown as InfiniteClientEntry<unknown, unknown, unknown>,\n )\n }\n })\n return\n }\n this.gcTimer = setTimeout(() => {\n this.gcTimer = null\n this.client.dropInfiniteEntry(\n this as unknown as InfiniteClientEntry<unknown, unknown, unknown>,\n )\n }, this.gcTime)\n }\n\n dispose(): void {\n if (this.gcTimer != null) {\n clearTimeout(this.gcTimer)\n this.gcTimer = null\n }\n this.stopIntervalTimer()\n this.entry.dispose()\n }\n}\n\n/**\n * Per-root entry registry. Owns the keyed `Map<hash, ClientEntry>` per query,\n * GC timers, refetch-interval timers. Subscribers are routed in/out via\n * `acquire` / `release`.\n */\nexport class QueryClient {\n private readonly maps = new Map<AnyQuery, Map<string, ClientEntry<unknown>>>()\n private readonly infiniteMaps = new Map<\n AnyInfiniteQuery,\n Map<string, InfiniteClientEntry<unknown, unknown, unknown>>\n >()\n private readonly touchedQueries = new Set<AnyQuery>()\n private readonly touchedInfiniteQueries = new Set<AnyInfiniteQuery>()\n private readonly hydratedData = new Map<string, { data: unknown; lastUpdatedAt: number }>()\n /** Mutations inflight across the whole root — used by `waitForIdle`. */\n readonly mutationsInflight$: Signal<number> = signal(0)\n private onError: ErrorHandler | undefined\n private disposed = false\n /** Devtools bus, if any — passed by `createRoot`. Used to emit cache events. */\n readonly devtools: DevtoolsEmitter | undefined\n\n /** Root-level deps; passed to every `QuerySpec.fetcher` via `FetchCtx`. */\n readonly deps: Record<string, unknown>\n\n /** Root-wide defaults for refetch triggers; per-query spec overrides win. Spec §5.9. */\n readonly refetchOnWindowFocus: boolean\n readonly refetchOnReconnect: boolean\n\n /**\n * Installed plugins. Fired on every `setData` / `invalidate` / `gc` so\n * cross-tab / persistence-like layers can observe and react. SPEC §13.2.\n */\n private readonly plugins: QueryClientPlugin[]\n /**\n * Flipped to `true` while a remote-originated write (via\n * `applyRemoteSetData` / `applyRemoteInvalidate`) is being applied. The\n * resulting plugin events carry `isRemote: true` so plugins know to skip\n * rebroadcast.\n */\n private applyingRemote = false\n\n constructor(opts?: {\n onError?: ErrorHandler\n hydrate?: DehydratedState\n devtools?: DevtoolsEmitter\n deps?: Record<string, unknown>\n refetchOnWindowFocus?: boolean\n refetchOnReconnect?: boolean\n plugins?: QueryClientPlugin[]\n }) {\n this.onError = opts?.onError\n this.devtools = opts?.devtools\n this.deps = opts?.deps ?? {}\n this.refetchOnWindowFocus = opts?.refetchOnWindowFocus ?? false\n this.refetchOnReconnect = opts?.refetchOnReconnect ?? false\n this.plugins = opts?.plugins ?? []\n if (opts?.hydrate) this.hydrate(opts.hydrate)\n const api = this.makePluginApi()\n for (const plugin of this.plugins) {\n this.callPlugin(plugin, () => plugin.init?.(api))\n }\n }\n\n /**\n * Build the `QueryClientPluginApi` view that plugins receive at `init`\n * time. Closes over `this`; safe to hand out — plugins call back through\n * these methods to push remote-originated writes into the local cache.\n */\n private makePluginApi(): QueryClientPluginApi {\n const self = this\n return {\n applyRemoteSetData(queryId, keyArgs, data) {\n self.applyRemoteSetData(queryId, keyArgs, data)\n },\n applyRemoteInvalidate(queryId, keyArgs) {\n self.applyRemoteInvalidate(queryId, keyArgs)\n },\n setEntryData(queryId, keyArgs, updater) {\n self.setEntryData(queryId, keyArgs, updater)\n },\n subscribedKeys(queryId) {\n return self.subscribedKeysFor(queryId)\n },\n }\n }\n\n /** Invoke a plugin callback; route exceptions through `onError`. */\n private callPlugin(plugin: QueryClientPlugin, fn: () => void): void {\n try {\n fn()\n } catch (err) {\n dispatchError(this.onError, err, {\n kind: 'plugin',\n controllerPath: [],\n pluginName: plugin.name,\n })\n }\n }\n\n /**\n * Emit a `SetDataEvent` to every installed plugin. The `source` field\n * tells layered plugins where the write originated:\n * - `'set'`: explicit `client.setData`, including mutations and plugin-\n * initiated `setEntryData` calls (e.g. entity backpropagation).\n * - `'fetch'`: a query fetcher resolved successfully (`Entry.applySuccess`\n * reaches this through `onSuccessData`), or hydrated data was first\n * bound (a per-tab arrival of pre-fetched data; cross-tab skips\n * `'fetch'` so this stays a per-tab concern).\n * - `'remote'`: `applyRemoteSetData` — cross-tab / server-push. Mirrors\n * `isRemote === true`.\n *\n * Private — fetcher-success emission goes through the `onFetchSuccess`\n * closure that `bindEntry` builds and hands to each new `ClientEntry`.\n * Hydrated emission goes through this method directly from `bindEntry`.\n * Mutation / remote paths call it from within QueryClient methods.\n */\n private emitSetData(\n query: AnyQuery | AnyInfiniteQuery,\n keyArgs: readonly unknown[],\n data: unknown,\n kind: 'data' | 'infinite',\n source: 'set' | 'fetch' | 'remote',\n ): void {\n if (this.plugins.length === 0) return\n const queryId = query.__spec.queryId\n if (queryId == null) return\n const event: SetDataEvent = {\n queryId,\n keyArgs,\n data,\n kind,\n isRemote: this.applyingRemote,\n source,\n }\n for (const plugin of this.plugins) {\n if (plugin.onSetData) {\n const cb = plugin.onSetData\n this.callPlugin(plugin, () => cb.call(plugin, event))\n }\n }\n }\n\n private emitInvalidate(\n query: AnyQuery | AnyInfiniteQuery,\n keyArgs: readonly unknown[],\n kind: 'data' | 'infinite',\n ): void {\n if (this.plugins.length === 0) return\n const queryId = query.__spec.queryId\n if (queryId == null) return\n const event: InvalidateEvent = {\n queryId,\n keyArgs,\n kind,\n isRemote: this.applyingRemote,\n }\n for (const plugin of this.plugins) {\n if (plugin.onInvalidate) {\n const cb = plugin.onInvalidate\n this.callPlugin(plugin, () => cb.call(plugin, event))\n }\n }\n }\n\n private emitGc(\n query: AnyQuery | AnyInfiniteQuery,\n keyArgs: readonly unknown[],\n kind: 'data' | 'infinite',\n ): void {\n if (this.plugins.length === 0) return\n const queryId = query.__spec.queryId\n if (queryId == null) return\n const event: GcEvent = { queryId, keyArgs, kind }\n for (const plugin of this.plugins) {\n if (plugin.onGc) {\n const cb = plugin.onGc\n this.callPlugin(plugin, () => cb.call(plugin, event))\n }\n }\n }\n\n /**\n * Fan out a `MutationEnqueueEvent` to every installed plugin. Called from\n * `MutationImpl.executeRun` when `spec.persist === true`. Plugins use this\n * to write the run to durable storage; the queue replays on reload. SPEC §13.3.\n */\n emitMutationEnqueue(event: {\n mutationId: string\n runId: string\n variables: unknown\n attempt: number\n }): void {\n if (this.plugins.length === 0) return\n for (const plugin of this.plugins) {\n if (plugin.onMutationEnqueue) {\n const cb = plugin.onMutationEnqueue\n this.callPlugin(plugin, () => cb.call(plugin, event))\n }\n }\n }\n\n /** Fan out a `MutationSettleEvent` to every installed plugin. SPEC §13.3. */\n emitMutationSettle(event: {\n mutationId: string\n runId: string\n outcome: 'success' | 'error' | 'cancelled'\n error?: unknown\n }): void {\n if (this.plugins.length === 0) return\n for (const plugin of this.plugins) {\n if (plugin.onMutationSettle) {\n const cb = plugin.onMutationSettle\n this.callPlugin(plugin, () => cb.call(plugin, event))\n }\n }\n }\n\n /** Resolve `queryId → live entry-map keys`. Empty array when unknown. */\n private subscribedKeysFor(queryId: string): readonly (readonly unknown[])[] {\n // Defer the registry lookup to avoid an eager circular import — `define.ts`\n // imports `QueryClient` as a type, and we import the registry helper here\n // for runtime use only.\n const query = lookupRegisteredQuery(queryId)\n if (!query) return []\n const out: (readonly unknown[])[] = []\n if (query.__olas === 'query') {\n const map = this.maps.get(query as unknown as AnyQuery)\n if (map) for (const ce of map.values()) out.push(ce.keyArgs)\n } else {\n const map = this.infiniteMaps.get(query as unknown as AnyInfiniteQuery)\n if (map) for (const ce of map.values()) out.push(ce.keyArgs)\n }\n return out\n }\n\n /**\n * Apply a remote-originated `setData` for the query identified by\n * `queryId`, scoped to the entry already keyed by `keyArgs` in this\n * client. Goes through the underlying `Entry.setData` so subscribers see\n * the write; plugin `onSetData` fires with `isRemote: true`.\n *\n * Drops silently when:\n * - No query with that id is registered (the receiving tab hasn't\n * imported the module that defined it).\n * - The registered query is an infinite query (cross-tab infinite sync\n * is deferred — see `plugin.ts` `SetDataEvent.kind`).\n * - No local entry exists for that key (the receiving tab isn't\n * subscribed; nothing useful to write to without callArgs for a\n * future refetch).\n */\n applyRemoteSetData(queryId: string, keyArgs: readonly unknown[], data: unknown): void {\n const query = lookupRegisteredQuery(queryId)\n if (!query) return\n if (query.__olas !== 'query') return // infinite — deferred for v1\n const internal = query as unknown as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n const hash = stableHash(keyArgs)\n const entry = map.get(hash)\n if (!entry) return\n this.applyingRemote = true\n try {\n entry.entry.setData(() => data as never, { track: false })\n this.emitSetData(internal, entry.keyArgs, data, 'data', 'remote')\n } finally {\n this.applyingRemote = false\n }\n }\n\n /**\n * Apply a single dehydrated entry to the cache. Idempotent across\n * pre-bind / post-bind:\n *\n * - If the matching `ClientEntry` already exists (a subscriber has\n * bound this key), `Entry.applyHydration(data, lastUpdatedAt)` writes\n * through with the server's timestamp + supersedes any inflight\n * fetch. Plugins see a `SetDataEvent` with `source: 'remote'`.\n * - If no `ClientEntry` exists yet (the subscribing component hasn't\n * mounted), the entry is buffered in `hydratedData` so the next\n * `bindEntry` for that hash picks it up — same path the constructor\n * `hydrate(state)` uses.\n *\n * Designed for streaming SSR: each `<Suspense>` boundary that resolves\n * on the server pushes its dehydrated entry through this method on the\n * client as the bootstrap script executes.\n */\n applyDehydratedEntry(\n queryId: string,\n keyArgs: readonly unknown[],\n data: unknown,\n lastUpdatedAt: number,\n ): void {\n const query = lookupRegisteredQuery(queryId)\n const hash = stableHash(keyArgs)\n if (query && query.__olas === 'query') {\n const internal = query as unknown as AnyQuery\n const map = this.maps.get(internal)\n const entry = map?.get(hash)\n if (entry !== undefined) {\n this.applyingRemote = true\n try {\n entry.entry.applyHydration(data, lastUpdatedAt)\n this.emitSetData(internal, entry.keyArgs, data, 'data', 'remote')\n } finally {\n this.applyingRemote = false\n }\n return\n }\n }\n // No local entry yet — buffer in the same map the constructor uses.\n // The next bindEntry for this query + key will adopt the buffered payload\n // and clear the slot. Namespaced by queryId so a colliding-key query can't\n // steal it (spec §15, T1.2).\n this.hydratedData.set(hydrationKey(queryId, hash), { data, lastUpdatedAt })\n }\n\n /**\n * Local-originated `setData` keyed by `queryId + keyArgs`. Plugin-facing\n * (exposed via `QueryClientPluginApi.setEntryData`); used by the\n * `@kontsedal/olas-entities` plugin to backpropagate entity patches into\n * every query holding the entity, without forcing the plugin to recover\n * the original `callArgs`.\n *\n * Drops silently in the same cases as `applyRemoteSetData` (unknown\n * queryId / infinite query / no local entry). Emits `SetDataEvent` with\n * `isRemote: false`, `source: 'set'` — cross-tab WILL rebroadcast.\n */\n setEntryData(\n queryId: string,\n keyArgs: readonly unknown[],\n updater: (prev: unknown) => unknown,\n ): void {\n const query = lookupRegisteredQuery(queryId)\n if (!query) return\n const hash = stableHash(keyArgs)\n if (query.__olas === 'query') {\n const internal = query as unknown as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n const entry = map.get(hash)\n if (!entry) return\n entry.entry.setData(updater as (prev: unknown) => never, { track: false })\n this.emitSetData(internal, entry.keyArgs, entry.entry.data.peek(), 'data', 'set')\n return\n }\n // Infinite query. The plugin's `SetDataEvent.data` for `kind: 'infinite'`\n // is `TPage[]` (the pages array), so the same path-based walk + write\n // mechanics apply — we just route through `InfiniteEntry.setData` and\n // re-emit with `kind: 'infinite'`.\n const internal = query as unknown as AnyInfiniteQuery\n const map = this.infiniteMaps.get(internal)\n if (!map) return\n const entry = map.get(hash)\n if (!entry) return\n entry.entry.setData(updater as (prev: unknown[] | undefined) => unknown[], { track: false })\n this.emitSetData(internal, entry.keyArgs, entry.entry.pages.peek(), 'infinite', 'set')\n }\n\n applyRemoteInvalidate(queryId: string, keyArgs: readonly unknown[]): void {\n const query = lookupRegisteredQuery(queryId)\n if (!query) return\n if (query.__olas !== 'query') return // infinite — deferred for v1\n const internal = query as unknown as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n const hash = stableHash(keyArgs)\n const entry = map.get(hash)\n if (!entry) return\n this.applyingRemote = true\n try {\n // Emit AFTER kicking off invalidate so plugins reading entry state see\n // post-invalidation values, mirroring setData's emit-after-write order.\n entry.entry.invalidate().catch((err) => {\n // Two rapid invalidates on the same key supersede each other, which\n // raises AbortError. That's not a cache error — swallow.\n if (isAbortError(err)) return\n dispatchError(this.onError, err, {\n kind: 'cache',\n controllerPath: [],\n queryKey: entry.keyArgs,\n })\n })\n this.emitInvalidate(internal, entry.keyArgs, 'data')\n } finally {\n this.applyingRemote = false\n }\n }\n\n hydrate(state: DehydratedState): void {\n if (state.version !== 1) {\n // Silent drop hid schema-bumped payloads. Warn so a future spec bump is\n // detectable from the client side without code archaeology.\n if (__DEV__) {\n // eslint-disable-next-line no-console\n console.warn(\n '[olas] hydrate(): unsupported state.version =',\n state.version,\n '— expected 1. Dropping payload; cache will fetch fresh.',\n )\n }\n return\n }\n for (const entry of state.entries) {\n const hash = stableHash(entry.key)\n this.hydratedData.set(hydrationKey(entry.id, hash), {\n data: entry.data,\n lastUpdatedAt: entry.lastUpdatedAt,\n })\n }\n }\n\n /**\n * Snapshot every live cache entry (regular + infinite) as a flat list of\n * `DebugCacheEntry`. Exposed via `root.__debug.queryEntries()` for the\n * devtools cache inspector — shows current data and state, not past\n * fetch events. Spec §20.9.\n */\n queryEntriesSnapshot(): import('../devtools').DebugCacheEntry[] {\n const out: import('../devtools').DebugCacheEntry[] = []\n for (const map of this.maps.values()) {\n for (const ce of map.values()) {\n out.push({\n key: ce.keyArgs as readonly unknown[],\n status: ce.entry.status.peek(),\n data: ce.entry.data.peek(),\n error: ce.entry.error.peek(),\n lastUpdatedAt: ce.entry.lastUpdatedAt.peek(),\n isStale: ce.entry.isStale.peek(),\n isFetching: ce.entry.isFetching.peek(),\n hasPendingMutations: ce.entry.hasPendingMutations.peek(),\n })\n }\n }\n for (const map of this.infiniteMaps.values()) {\n for (const ce of map.values()) {\n out.push({\n key: ce.keyArgs as readonly unknown[],\n status: ce.entry.status.peek(),\n // Infinite entries carry an array of pages; expose them verbatim.\n data: ce.entry.pages.peek(),\n error: ce.entry.error.peek(),\n lastUpdatedAt: ce.entry.lastUpdatedAt.peek(),\n isStale: ce.entry.isStale.peek(),\n isFetching: ce.entry.isFetching.peek(),\n hasPendingMutations: ce.entry.hasPendingMutations.peek(),\n })\n }\n }\n return out\n }\n\n dehydrate(): DehydratedState {\n const entries: DehydratedState['entries'] = []\n for (const [query, map] of this.maps) {\n for (const ce of map.values()) {\n if (ce.entry.status.peek() === 'success') {\n entries.push({\n id: query.__id,\n key: ce.keyArgs,\n data: ce.entry.data.peek(),\n lastUpdatedAt: ce.entry.lastUpdatedAt.peek() ?? Date.now(),\n })\n }\n }\n }\n return { version: 1, entries }\n }\n\n async waitForIdle(): Promise<void> {\n for (let safety = 0; safety < 100; safety++) {\n const tasks: Promise<void>[] = []\n for (const map of this.maps.values()) {\n for (const ce of map.values()) {\n if (ce.entry.isFetching.peek()) {\n tasks.push(waitUntilFalse(ce.entry.isFetching))\n }\n }\n }\n for (const map of this.infiniteMaps.values()) {\n for (const ce of map.values()) {\n if (ce.entry.isFetching.peek()) {\n tasks.push(waitUntilFalse(ce.entry.isFetching))\n }\n }\n }\n if (this.mutationsInflight$.peek() > 0) {\n tasks.push(\n new Promise<void>((resolve) => {\n const unsub = this.mutationsInflight$.subscribe((v) => {\n if (v === 0) {\n unsub()\n resolve()\n }\n })\n }),\n )\n }\n if (tasks.length === 0) return\n await Promise.all(tasks)\n }\n // The 100-iteration safety bound exists so a pathological setup that\n // keeps starting new fetches doesn't lock the dehydrate path. This is\n // a correctness failure for SSR: silently returning would let\n // `dehydrate()` ship an incomplete payload that looks clean. Throw so\n // the SSR boundary surfaces it instead of pretending success.\n const unsettled: Array<{ key: readonly unknown[]; kind: 'data' | 'infinite' }> = []\n for (const map of this.maps.values()) {\n for (const ce of map.values()) {\n if (ce.entry.isFetching.peek()) unsettled.push({ key: ce.keyArgs, kind: 'data' })\n }\n }\n for (const map of this.infiniteMaps.values()) {\n for (const ce of map.values()) {\n if (ce.entry.isFetching.peek()) unsettled.push({ key: ce.keyArgs, kind: 'infinite' })\n }\n }\n const err = new Error(\n '[olas] waitForIdle: exceeded 100-iteration safety bound — cache or mutations keep restarting',\n ) as Error & { unsettled: typeof unsettled; mutationsInflight: number }\n err.unsettled = unsettled\n err.mutationsInflight = this.mutationsInflight$.peek()\n throw err\n }\n\n bindEntry<Args extends unknown[], T>(query: Query<Args, T>, args: Args): ClientEntry<T> {\n const internal = query as AnyQuery\n let map = this.maps.get(internal)\n if (!map) {\n map = new Map()\n this.maps.set(internal, map)\n this.touchedQueries.add(internal)\n internal.__clients.add(this)\n }\n const keyArgs = internal.__spec.key(...args)\n const hash = stableHash(keyArgs)\n let entry = map.get(hash) as ClientEntry<T> | undefined\n if (!entry) {\n const hkey = hydrationKey(internal.__id, hash)\n const hydrated = this.hydratedData.get(hkey) as { data: T; lastUpdatedAt: number } | undefined\n if (hydrated) this.hydratedData.delete(hkey)\n // Build the fetcher-success emitter here so `emitSetData` can stay\n // `private` — `ClientEntry` doesn't reach back into the client to call\n // it; the closure captures (query, keyArgs, this) in this scope and\n // is consumed by `Entry.onSuccessData` from inside `applySuccess`.\n const onFetchSuccess: ((data: T) => void) | undefined =\n internal.__spec.queryId != null\n ? (data) => this.emitSetData(internal, keyArgs, data, 'data', 'fetch')\n : undefined\n entry = new ClientEntry<T>(\n this,\n internal,\n args,\n keyArgs,\n internal.__spec,\n hydrated,\n onFetchSuccess,\n )\n map.set(hash, entry as ClientEntry<unknown>)\n // The entry is created without an immediate subscriber (callers like\n // `prefetch`/`setData`/`invalidate` reach `bindEntry` first; subscribing\n // callers then call `acquire()` right after, which clears the gc timer).\n entry.scheduleGcIfOrphan()\n // Hydrated data lands in `initialData` on the new Entry — `applySuccess`\n // is never called, so plugins observing fetch results (entities, ...)\n // would otherwise miss every hydrated row. Emit a SetDataEvent with\n // `source: 'fetch'` here once the entry is registered (and the plugin\n // is already init'd, since the QueryClient constructor runs hydrate →\n // plugin init before any subscriber can reach bindEntry). The fetch\n // source is correct for layered consumers: each tab hydrates\n // independently, so cross-tab's \"skip 'fetch'\" gate continues to do\n // the right thing.\n if (hydrated !== undefined) {\n this.emitSetData(internal, keyArgs, hydrated.data, 'data', 'fetch')\n }\n } else if (__DEV__) {\n // The fetcher closure is captured on first `bindEntry`. If a later\n // subscriber binds the SAME `keyArgs` (same hash) but DIFFERENT\n // `callArgs`, the next refetch will still use the first caller's\n // arguments — a silent staleness footgun when a `key()` function\n // collapses non-key args (e.g. headers, abort tokens). Warn so the\n // mismatch is surfaced; the consumer should either include the diff\n // in the key or accept the documented \"first wins\" behavior.\n const prev = entry.callArgs\n const len = Math.max(prev.length, args.length)\n let mismatch = prev.length !== args.length\n for (let i = 0; i < len && !mismatch; i++) {\n if (!Object.is(prev[i], args[i])) mismatch = true\n }\n if (mismatch) {\n // eslint-disable-next-line no-console\n console.warn(\n `[olas] bindEntry: hash collision with diverging callArgs for query` +\n ` ${internal.__spec.queryId ?? '<anonymous>'} key=${JSON.stringify(keyArgs)}.` +\n ` First bind's args are used by the fetcher; later args ignored.` +\n ` Either include the difference in spec.key(...) or pass identical args.`,\n )\n }\n }\n return entry\n }\n\n dropEntry(entry: ClientEntry<unknown>): void {\n const map = this.maps.get(entry.query)\n if (!map) return\n const hash = stableHash(entry.keyArgs)\n if (map.get(hash) !== entry) return\n map.delete(hash)\n entry.dispose()\n if (map.size === 0) {\n this.maps.delete(entry.query)\n }\n if (__DEV__) {\n this.devtools?.emit({ type: 'cache:gc', queryKey: entry.keyArgs })\n }\n this.emitGc(entry.query, entry.keyArgs, 'data')\n }\n\n /**\n * Invalidate one entry: if it has subscribers, mark stale AND refetch; if\n * not, mark stale only — the next subscriber refetches. Spec §5.7 says\n * invalidate refetches only IF subscribed; the old always-fetch behavior woke\n * orphaned entries that no one was watching (T3.9). Works for both\n * `ClientEntry` and `InfiniteClientEntry`.\n */\n private invalidateEntry(entry: {\n hasSubscribers(): boolean\n keyArgs: readonly unknown[]\n entry: { invalidate(): Promise<unknown>; markStale(): void }\n }): void {\n if (entry.hasSubscribers()) {\n entry.entry.invalidate().catch((err) => {\n if (isAbortError(err)) return\n dispatchError(this.onError, err, {\n kind: 'cache',\n controllerPath: [],\n queryKey: entry.keyArgs,\n })\n })\n } else {\n entry.entry.markStale()\n }\n }\n\n invalidate<Args extends unknown[]>(query: Query<Args, any>, args: Args): void {\n const internal = query as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n const keyArgs = internal.__spec.key(...args)\n const hash = stableHash(keyArgs)\n const entry = map.get(hash)\n if (!entry) return\n if (__DEV__) {\n this.devtools?.emit({ type: 'cache:invalidated', queryKey: keyArgs })\n }\n this.invalidateEntry(entry)\n this.emitInvalidate(internal, keyArgs, 'data')\n }\n\n invalidateAll(query: Query<any, any>): void {\n const internal = query as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n for (const [hash, entry] of map) {\n void hash\n if (__DEV__) {\n this.devtools?.emit({ type: 'cache:invalidated', queryKey: entry.keyArgs })\n }\n this.invalidateEntry(entry)\n this.emitInvalidate(internal, entry.keyArgs, 'data')\n }\n }\n\n cancel<Args extends unknown[]>(query: Query<Args, any>, args: Args): void {\n const internal = query as AnyQuery\n const map = this.maps.get(internal)\n if (!map) return\n const hash = stableHash(internal.__spec.key(...args))\n map.get(hash)?.entry.cancel()\n }\n\n cancelAll(query: Query<any, any>): void {\n const map = this.maps.get(query as AnyQuery)\n if (!map) return\n for (const entry of map.values()) entry.entry.cancel()\n }\n\n setData<Args extends unknown[], T>(\n query: Query<Args, T>,\n args: Args,\n updater: (prev: T | undefined) => T,\n ): Snapshot {\n const entry = this.bindEntry(query, args)\n const snapshot = entry.entry.setData(updater)\n // Read the post-update value to broadcast — plugins want the new state,\n // not the updater function (which would be uncloneable across\n // BroadcastChannel).\n this.emitSetData(entry.query, entry.keyArgs, entry.entry.data.peek(), 'data', 'set')\n // Re-broadcast on rollback so cross-tab / entity plugins drop the failed\n // optimistic value instead of keeping it (T3.6). Guard on an actual data\n // change: a non-top chain-splice rollback (§6.4) leaves current data\n // untouched, so there is nothing new to broadcast.\n return {\n rollback: () => {\n const before = entry.entry.data.peek()\n snapshot.rollback()\n const after = entry.entry.data.peek()\n if (!Object.is(before, after)) {\n this.emitSetData(entry.query, entry.keyArgs, after, 'data', 'set')\n }\n },\n finalize: () => snapshot.finalize(),\n }\n }\n\n bindInfiniteEntry<Args extends unknown[], TPage, TItem>(\n query: InfiniteQuery<Args, TPage, TItem>,\n args: Args,\n ): InfiniteClientEntry<TPage, TItem, unknown> {\n const internal = query as AnyInfiniteQuery\n let map = this.infiniteMaps.get(internal)\n if (!map) {\n map = new Map()\n this.infiniteMaps.set(internal, map)\n this.touchedInfiniteQueries.add(internal)\n internal.__clients.add(this)\n }\n const keyArgs = internal.__spec.key(...args)\n const hash = stableHash(keyArgs)\n let entry = map.get(hash) as InfiniteClientEntry<TPage, TItem, unknown> | undefined\n if (!entry) {\n // Mirror the regular-query plumbing in `bindEntry`: build the\n // SetDataEvent emitter here so `emitSetData` stays private. The\n // closure captures (query, keyArgs, this) and is consumed by\n // `InfiniteEntry.onSuccessData` from inside each successful page\n // batch (initial, next, prev).\n const onFetchSuccess: ((pages: TPage[]) => void) | undefined =\n internal.__spec.queryId != null\n ? (pages) => this.emitSetData(internal, keyArgs, pages, 'infinite', 'fetch')\n : undefined\n entry = new InfiniteClientEntry<TPage, TItem, unknown>(\n this,\n internal,\n args,\n keyArgs,\n internal.__spec,\n onFetchSuccess,\n )\n map.set(hash, entry as InfiniteClientEntry<unknown, unknown, unknown>)\n entry.scheduleGcIfOrphan()\n }\n return entry\n }\n\n dropInfiniteEntry(entry: InfiniteClientEntry<unknown, unknown, unknown>): void {\n const map = this.infiniteMaps.get(entry.query)\n if (!map) return\n const hash = stableHash(entry.keyArgs)\n if (map.get(hash) !== entry) return\n map.delete(hash)\n entry.dispose()\n if (map.size === 0) {\n this.infiniteMaps.delete(entry.query)\n }\n this.emitGc(entry.query, entry.keyArgs, 'infinite')\n }\n\n invalidateInfinite<Args extends unknown[]>(\n query: InfiniteQuery<Args, any, any>,\n args: Args,\n ): void {\n const internal = query as AnyInfiniteQuery\n const map = this.infiniteMaps.get(internal)\n if (!map) return\n const keyArgs = internal.__spec.key(...args)\n const hash = stableHash(keyArgs)\n const entry = map.get(hash)\n if (!entry) return\n this.invalidateEntry(entry)\n this.emitInvalidate(internal, keyArgs, 'infinite')\n }\n\n invalidateAllInfinite(query: InfiniteQuery<any, any, any>): void {\n const internal = query as AnyInfiniteQuery\n const map = this.infiniteMaps.get(internal)\n if (!map) return\n for (const entry of map.values()) {\n this.invalidateEntry(entry)\n this.emitInvalidate(internal, entry.keyArgs, 'infinite')\n }\n }\n\n cancelInfinite<Args extends unknown[]>(query: InfiniteQuery<Args, any, any>, args: Args): void {\n const internal = query as AnyInfiniteQuery\n const map = this.infiniteMaps.get(internal)\n if (!map) return\n const hash = stableHash(internal.__spec.key(...args))\n map.get(hash)?.entry.cancel()\n }\n\n cancelAllInfinite(query: InfiniteQuery<any, any, any>): void {\n const map = this.infiniteMaps.get(query as AnyInfiniteQuery)\n if (!map) return\n for (const entry of map.values()) entry.entry.cancel()\n }\n\n setInfiniteData<Args extends unknown[], TPage>(\n query: InfiniteQuery<Args, TPage, any>,\n args: Args,\n updater: (prev: TPage[] | undefined) => TPage[],\n ): Snapshot {\n const entry = this.bindInfiniteEntry(query, args)\n const snapshot = entry.entry.setData(updater)\n this.emitSetData(entry.query, entry.keyArgs, entry.entry.pages.peek(), 'infinite', 'set')\n // Re-broadcast on rollback so peers drop the failed optimistic pages\n // (T3.6); guard on an actual change (non-top chain-splice is a no-op).\n return {\n rollback: () => {\n const before = entry.entry.pages.peek()\n snapshot.rollback()\n const after = entry.entry.pages.peek()\n if (!Object.is(before, after)) {\n this.emitSetData(entry.query, entry.keyArgs, after, 'infinite', 'set')\n }\n },\n finalize: () => snapshot.finalize(),\n }\n }\n\n prefetchInfinite<Args extends unknown[], TPage>(\n query: InfiniteQuery<Args, TPage, any>,\n args: Args,\n ): Promise<TPage> {\n const entry = this.bindInfiniteEntry(query, args)\n // Acquire/release wraps the fetch so the entry isn't gc'd mid-flight by\n // the orphan-gc timer scheduled in `bindInfiniteEntry`.\n entry.acquire()\n const promise = (async () => {\n const status = entry.entry.status.peek()\n if (status === 'success' && !entry.entry.isStaleNow()) {\n return entry.entry.pages.peek()[0] as TPage\n }\n return entry.entry.startFetch()\n })()\n return promise.finally(() => entry.release())\n }\n\n prefetch<Args extends unknown[], T>(query: Query<Args, T>, args: Args): Promise<T> {\n const entry = this.bindEntry(query, args)\n entry.acquire()\n const promise = (async () => {\n const status = entry.entry.status.peek()\n if (status === 'success' && !entry.entry.isStaleNow()) {\n return entry.entry.data.peek() as T\n }\n if (entry.entry.isFetching.peek()) {\n return entry.entry.firstValue()\n }\n return entry.entry.startFetch()\n })()\n return promise.finally(() => entry.release())\n }\n\n inflightCount(): number {\n let count = 0\n for (const [, map] of this.maps) {\n for (const [, entry] of map) {\n if (entry.entry.isFetching.peek()) count++\n }\n }\n return count\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n for (const map of this.maps.values()) {\n for (const entry of map.values()) {\n entry.dispose()\n }\n }\n this.maps.clear()\n for (const map of this.infiniteMaps.values()) {\n for (const entry of map.values()) {\n entry.dispose()\n }\n }\n this.infiniteMaps.clear()\n for (const q of this.touchedQueries) {\n q.__clients.delete(this)\n }\n this.touchedQueries.clear()\n for (const q of this.touchedInfiniteQueries) {\n q.__clients.delete(this)\n }\n this.touchedInfiniteQueries.clear()\n this.hydratedData.clear()\n for (const plugin of this.plugins) {\n if (plugin.dispose) {\n const cb = plugin.dispose\n this.callPlugin(plugin, () => cb.call(plugin))\n }\n }\n }\n}\n\nfunction waitUntilFalse(sig: {\n peek(): boolean\n subscribe(h: (v: boolean) => void): () => void\n}): Promise<void> {\n if (!sig.peek()) return Promise.resolve()\n return new Promise<void>((resolve) => {\n const unsub = sig.subscribe((v) => {\n if (!v) {\n unsub()\n resolve()\n }\n })\n })\n}\n","/**\n * Synchronous fan-out event bus. Handlers run in the order they subscribed.\n *\n * Emission iterates a SNAPSHOT of the handler set taken at the start of\n * `emit()`. So within one emission: a handler added during emit does NOT fire\n * for the current emission, and a handler removed during emit STILL fires for\n * the current emission (it was captured in the snapshot).\n *\n * Handlers are stored in a `Set` keyed by reference — calling `on(h)` twice\n * with the same `h` registers it ONCE; a single unsubscribe then removes it.\n *\n * `Emitter<void>` exposes `emit()` (no argument); other shapes expose\n * `emit(value: T)`.\n *\n * Spec §7, §20.6.\n */\nexport type Emitter<T> = {\n emit: [T] extends [void] ? () => void : (value: T) => void\n /** Subscribe to every emission. Returns the unsubscribe function. */\n on(handler: (value: T) => void): () => void\n /** Subscribe to the next emission only. Auto-unsubscribes after firing. */\n once(handler: (value: T) => void): () => void\n /** Tear down the emitter. Subsequent `emit` / `on` / `once` are no-ops. */\n dispose(): void\n}\n\ntype AnyHandler = (value: unknown) => void\n\n/**\n * Optional escape hatch for emit-time handler throws. If supplied, a thrown\n * handler is reported here and emission continues with the remaining handlers\n * (spec §20.6 — one throwing handler must not block the rest). If absent,\n * the throw is logged via `console.error`.\n */\nexport type EmitterErrorReporter = (err: unknown) => void\n\nclass EmitterImpl<T> {\n private handlers = new Set<AnyHandler>()\n private disposed = false\n\n constructor(private onError?: EmitterErrorReporter) {}\n\n emit(value: T): void {\n if (this.disposed) return\n // Snapshot so a handler that unsubscribes itself (or another) doesn't\n // mutate the set mid-iteration.\n const snapshot = Array.from(this.handlers)\n for (const handler of snapshot) {\n try {\n handler(value as unknown)\n } catch (err) {\n // Spec §20.6: isolate handler throws so siblings still fire.\n if (this.onError) {\n try {\n this.onError(err)\n } catch {\n // Reporter itself threw — last resort.\n // eslint-disable-next-line no-console\n console.error('[olas] emitter handler threw and reporter threw:', err)\n }\n } else {\n // eslint-disable-next-line no-console\n console.error('[olas] emitter handler threw:', err)\n }\n }\n }\n }\n\n on(handler: (value: T) => void): () => void {\n if (this.disposed) return () => {}\n const wrapped = handler as AnyHandler\n this.handlers.add(wrapped)\n return () => {\n this.handlers.delete(wrapped)\n }\n }\n\n once(handler: (value: T) => void): () => void {\n if (this.disposed) return () => {}\n const wrapped: AnyHandler = (value) => {\n this.handlers.delete(wrapped)\n handler(value as T)\n }\n this.handlers.add(wrapped)\n return () => {\n this.handlers.delete(wrapped)\n }\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.handlers.clear()\n }\n}\n\n/**\n * Create a standalone emitter. Handlers persist until explicitly unsubscribed\n * (or the emitter is disposed). Use this for emitters that live outside any\n * single controller — typically in deps. Use `ctx.emitter()` for emitters that\n * should auto-clean with a controller.\n *\n * Pass `onError` to receive emit-time handler throws (spec §20.6 — one\n * throwing handler must not block the rest of the fan-out). `ctx.emitter()`\n * wires this to the root's `onError` so deps-level emitters get isolation\n * by default when constructed via `ctx`.\n */\nexport function createEmitter<T = void>(options?: { onError?: EmitterErrorReporter }): Emitter<T> {\n const impl = new EmitterImpl<T>(options?.onError)\n return {\n emit: ((value?: T) => impl.emit(value as T)) as Emitter<T>['emit'],\n on: (handler) => impl.on(handler),\n once: (handler) => impl.once(handler),\n dispose: () => impl.dispose(),\n }\n}\n","import type { Field } from '../controller/types'\nimport type { DevtoolsEmitter } from '../devtools'\nimport {\n batch,\n type Computed,\n computed,\n effect,\n type ReadSignal,\n type Signal,\n signal,\n} from '../signals'\nimport { isAbortError } from '../utils'\nimport type { Validator, ValidatorResult } from './types'\n\n/**\n * Flatten a single validator result to plain message strings for a leaf field.\n * A leaf has no descendants, so a `FormIssue[]`'s paths don't route anywhere —\n * every issue's `message` applies to this field. `null` → no messages.\n */\nfunction messagesFromResult(result: ValidatorResult): string[] {\n if (result == null) return []\n if (typeof result === 'string') return [result]\n return result.map((issue) => issue.message)\n}\n\n/**\n * Structural equality used by `Field.set` to decide whether a write returns\n * the field to its initial value (clearing `isDirty`). Cheap path for\n * primitives + `Object.is`; deep walk for arrays and plain objects. Class\n * instances, Map, Set, Date fall back to reference identity — same trade-off\n * `structural-share.ts` makes for cache data.\n */\nfunction isStructurallyEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (!isStructurallyEqual(a[i], b[i])) return false\n }\n return true\n }\n if (Array.isArray(b)) return false\n const protoA = Object.getPrototypeOf(a)\n const protoB = Object.getPrototypeOf(b)\n // Plain-object guard only — class instances aren't safe to walk by keys.\n if (protoA !== Object.prototype && protoA !== null) return false\n if (protoB !== Object.prototype && protoB !== null) return false\n const keysA = Object.keys(a as Record<string, unknown>)\n const keysB = Object.keys(b as Record<string, unknown>)\n if (keysA.length !== keysB.length) return false\n for (const k of keysA) {\n if (!Object.hasOwn(b as object, k)) return false\n if (\n !isStructurallyEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * Hook attached by `ctx.form` (or `createForm`) so a Field can publish\n * `field:validated` devtools events with its owning controller path + the\n * field's name within the form schema. See devtools §20.9 and FieldImpl.bind.\n */\nexport type FieldDevtoolsOwner = {\n controllerPath: readonly string[]\n fieldName: string\n emitter: DevtoolsEmitter\n}\n\n/**\n * Optional reporter for synchronous validator throws — wired in by `ctx.field`\n * (and `createForm` for leaf fields inside a form) so a thrown validator\n * doesn't escape the signal effect silently. Without this, a buggy validator\n * just stops contributing to `errors` and the field reads as \"valid\" while\n * silently broken. With it, the throw is routed through `root.onError` as\n * `kind: 'effect'` AND the throw's message lands in the field's `errors`\n * array so the UI surfaces the problem.\n */\nexport type ValidatorErrorReporter = (err: unknown) => void\n\n/**\n * When a field's validators are first allowed to run.\n *\n * - `'change'` (default) — validators run on every `set()`. Matches the\n * current behavior, ideal for \"type and see errors live.\"\n * - `'blur'` — first run is gated on `markTouched()`. After that, subsequent\n * value changes do trigger re-validation. UI binding should call\n * `markTouched()` on `onBlur`.\n * - `'submit'` — first run is gated on `revalidate()` / `Form.submit()`.\n * After that, subsequent value changes re-validate. Use when you want\n * \"show errors only after the user explicitly tried to submit.\"\n *\n * `revalidate()` always unlocks the field regardless of mode.\n */\nexport type ValidateOn = 'change' | 'blur' | 'submit'\n\nexport type FieldOptions = {\n onValidatorError?: ValidatorErrorReporter\n validateOn?: ValidateOn\n}\n\nclass FieldImpl<T> implements Field<T> {\n private readonly value$: Signal<T>\n /**\n * Validator-produced errors. The public `errors` getter merges this with\n * `serverErrors$` and `formErrors$` so consumers see a single flat array.\n * Kept separate so a re-run of validators (after a new value) doesn't clobber\n * the other two channels.\n */\n private readonly validatorErrors$: Signal<string[]>\n /**\n * Externally-injected errors — see `setErrors`. Cleared on the next user\n * `set()`, on `reset()`, or via an explicit `setErrors([])`.\n */\n private readonly serverErrors$: Signal<string[]>\n /**\n * Errors routed here by a parent (or ancestor) form-level validator that\n * targeted this field via a `FormIssue` path — the third error channel\n * beside validator + server errors (T5.2). Owned by the routing form: cleared\n * and re-applied on every form-level validation run, so it does NOT clear on\n * the field's own `set()` (a stale cross-field error survives until the next\n * form-level run recomputes it). Cleared by `reset()` / `setAsInitial()`.\n */\n private readonly formErrors$: Signal<string[]>\n private readonly errors$: Computed<string[]>\n private readonly touched$: Signal<boolean>\n private readonly dirty$: Signal<boolean>\n private readonly validating$: Signal<boolean>\n private readonly isValid$: Computed<boolean>\n /**\n * Validity as of the last *settled* validation pass. While a pass is in\n * flight (`validating$`), `isValid` reads this instead of the live `errors`\n * — otherwise a `debouncedValidator` would flip `isValid` to `false` on every\n * keystroke (the async-start clears `validatorErrors$`), strobing a submit\n * button. Updated only when a pass completes (T5.3). Defaults `true` (an\n * untouched field with a pending first run reads valid, not invalid).\n */\n private readonly lastValid$: Signal<boolean>\n private readonly revalidateTrigger$: Signal<number>\n\n private readonly validators: ReadonlyArray<Validator<T>>\n /** The value `reset()` returns to. Mutated by `setAsInitial()` so a form\n * initialized from server data resets to *that* data, not the empty seed. */\n private initial: T\n private validatorDispose: (() => void) | null = null\n private currentAbort: AbortController | null = null\n private runId = 0\n private disposed = false\n private devtoolsOwner: FieldDevtoolsOwner | null = null\n private onValidatorError: ValidatorErrorReporter | null = null\n private readonly validateOn: ValidateOn\n /** Reactive gate — when false, the validator effect skips its run. Flipped\n * on by the relevant trigger for the field's `validateOn` mode. Once on,\n * stays on for the lifetime of the field (matches RHF's `mode + reValidateMode`\n * default semantics: after the first activation, subsequent changes\n * re-validate). `reset()` flips it back to false. */\n private readonly validateUnlocked$: Signal<boolean>\n\n constructor(initial: T, validators: ReadonlyArray<Validator<T>> = [], options?: FieldOptions) {\n this.initial = initial\n this.validators = validators\n // Capture the reporter BEFORE the validator effect kicks off so a sync\n // throw on the very first pass routes through `onError` instead of\n // disappearing into the effect (`bindValidatorErrorReporter` is a\n // post-construct hook so it can't catch the first run).\n this.onValidatorError = options?.onValidatorError ?? null\n this.validateOn = options?.validateOn ?? 'change'\n this.value$ = signal(initial)\n this.validatorErrors$ = signal<string[]>([])\n this.serverErrors$ = signal<string[]>([])\n this.formErrors$ = signal<string[]>([])\n this.touched$ = signal(false)\n this.dirty$ = signal(false)\n this.validating$ = signal(false)\n this.lastValid$ = signal(true)\n this.revalidateTrigger$ = signal(0)\n // 'change' mode is unlocked from construction; 'blur' / 'submit' wait\n // for their trigger so initial typing doesn't surface errors.\n this.validateUnlocked$ = signal(this.validateOn === 'change')\n this.errors$ = computed(() => {\n const v = this.validatorErrors$.value\n const s = this.serverErrors$.value\n const f = this.formErrors$.value\n if (s.length === 0 && f.length === 0) return v\n if (v.length === 0 && f.length === 0) return s\n if (v.length === 0 && s.length === 0) return f\n return [...v, ...s, ...f]\n })\n this.isValid$ = computed(() =>\n // While a validation pass is in flight, hold the last settled validity so\n // the field doesn't strobe invalid mid-check (T5.3). Otherwise it's live.\n this.validating$.value ? this.lastValid$.value : this.errors$.value.length === 0,\n )\n\n if (validators.length > 0) {\n this.validatorDispose = effect(() => {\n this.runValidators()\n })\n }\n }\n\n /**\n * Internal hook for `ctx.field` / `createForm` to route synchronous\n * validator throws through `root.onError`. See `ValidatorErrorReporter`.\n */\n bindValidatorErrorReporter(reporter: ValidatorErrorReporter | null): void {\n this.onValidatorError = reporter\n }\n\n // --- ReadSignal<T> ---\n get value(): T {\n return this.value$.value\n }\n\n peek(): T {\n return this.value$.peek()\n }\n\n subscribe(handler: (value: T) => void): () => void {\n return this.value$.subscribe(handler)\n }\n\n subscribeChanges(handler: (value: T) => void): () => void {\n return this.value$.subscribeChanges(handler)\n }\n\n // --- Field-only signals ---\n get errors(): ReadSignal<string[]> {\n return this.errors$\n }\n\n get isValid(): ReadSignal<boolean> {\n return this.isValid$\n }\n\n get isDirty(): ReadSignal<boolean> {\n return this.dirty$\n }\n\n get touched(): ReadSignal<boolean> {\n return this.touched$\n }\n\n get isValidating(): ReadSignal<boolean> {\n return this.validating$\n }\n\n // --- mutating methods ---\n set(value: T): void {\n if (this.disposed) return\n batch(() => {\n this.value$.set(value)\n // Equality-aware dirty: setting back to initial clears dirty, so\n // \"Disable Save when unchanged\" UIs work without consumer code. Uses\n // a structural comparison for primitive / shallow-object / array\n // payloads; falls back to reference identity for class instances.\n this.dirty$.set(!isStructurallyEqual(value, this.initial))\n // Server errors are pinned externally and survive validator re-runs,\n // but they MUST clear when the user edits the field — otherwise a\n // server error like \"username taken\" would persist after the user\n // typed a different username.\n if (this.serverErrors$.peek().length > 0) this.serverErrors$.set([])\n })\n }\n\n setErrors(errors: ReadonlyArray<string>): void {\n if (this.disposed) return\n const next = errors.length === 0 ? [] : [...errors]\n this.serverErrors$.set(next)\n }\n\n /**\n * Internal — set the parent-form-validator error channel (`formErrors$`).\n * Called by the owning form's issue router when a `FormIssue` path resolves\n * to this field. Guards against churning the signal when nothing changes so\n * a whole-tree clear pass doesn't wake unrelated subscribers. See T5.2 /\n * `routeFormIssues` in `form.ts`.\n */\n setFormErrors(errors: ReadonlyArray<string>): void {\n if (this.disposed) return\n if (this.formErrors$.peek().length === 0 && errors.length === 0) return\n this.formErrors$.set(errors.length === 0 ? [] : [...errors])\n }\n\n /**\n * Reseat the field as if this value had been its constructor `initial`.\n * Sets the value, re-anchors `reset()`'s target, and does NOT mark dirty.\n * Used by `Form` when applying its own `initial` (in the constructor and\n * on `reset()`), so server-loaded forms don't start dirty. Internal-ish —\n * exposed for `Form`'s use, not for user code that just wants to write.\n */\n setAsInitial(value: T): void {\n if (this.disposed) return\n this.initial = value\n batch(() => {\n this.value$.set(value)\n this.dirty$.set(false)\n // Re-seating from a fresh server payload means the previous server\n // response is no longer relevant. Without clearing, errors like\n // \"username taken\" persist across a successful re-hydrate.\n if (this.serverErrors$.peek().length > 0) this.serverErrors$.set([])\n // A stale cross-field error from the old value is likewise irrelevant;\n // the next form-level run recomputes it against the fresh value.\n if (this.formErrors$.peek().length > 0) this.formErrors$.set([])\n })\n }\n\n reset(): void {\n if (this.disposed) return\n this.currentAbort?.abort()\n this.currentAbort = null\n batch(() => {\n this.value$.set(this.initial)\n this.dirty$.set(false)\n this.touched$.set(false)\n this.validatorErrors$.set([])\n this.serverErrors$.set([])\n this.formErrors$.set([])\n this.validating$.set(false)\n // Re-lock validation if the field was in blur/submit mode — a reset\n // means we're back to a clean slate, so the user shouldn't immediately\n // see errors again until they re-trigger.\n if (this.validateOn !== 'change') this.validateUnlocked$.set(false)\n })\n }\n\n markTouched(): void {\n if (this.disposed) return\n this.touched$.set(true)\n // 'blur' mode unlocks validation on first blur. Subsequent set() calls\n // then re-validate live (matches RHF `reValidateMode: onChange` default).\n if (this.validateOn === 'blur' && !this.validateUnlocked$.peek()) {\n this.validateUnlocked$.set(true)\n }\n }\n\n async revalidate(): Promise<boolean> {\n if (this.disposed) return this.isValid$.peek()\n // `revalidate()` always unlocks the field — same trigger as a successful\n // submit attempt. 'submit' mode uses this as its first activation.\n if (!this.validateUnlocked$.peek()) this.validateUnlocked$.set(true)\n // Bump the trigger to force re-run.\n this.revalidateTrigger$.update((n) => n + 1)\n await this.waitUntilSettled()\n return this.isValid$.peek()\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.validatorDispose?.()\n this.validatorDispose = null\n this.currentAbort?.abort()\n this.currentAbort = null\n this.devtoolsOwner = null\n }\n\n /**\n * Bind this field to a devtools owner. Each subsequent validation pass\n * publishes a `field:validated` event with the supplied path + name.\n * Idempotent — calling again replaces the owner. Internal: called by\n * `createForm` / `createFieldArray` so the form's keys reach the panel.\n */\n bindDevtoolsOwner(owner: FieldDevtoolsOwner | null): void {\n this.devtoolsOwner = owner\n }\n\n private emitValidated(valid: boolean, errors: readonly string[]): void {\n if (!__DEV__) return\n const owner = this.devtoolsOwner\n if (owner === null) return\n owner.emitter.emit({\n type: 'field:validated',\n path: owner.controllerPath,\n field: owner.fieldName,\n valid,\n errors: [...errors],\n })\n }\n\n // --- internal ---\n private async waitUntilSettled(): Promise<void> {\n // If a validation pass is in progress, wait for validating$ to become false.\n if (!this.validating$.peek()) return\n await new Promise<void>((resolve) => {\n const unsub = this.validating$.subscribe((v) => {\n if (!v) {\n unsub()\n resolve()\n }\n })\n })\n }\n\n private runValidators(): void {\n if (this.disposed) return\n\n // Track value and revalidate trigger.\n const value = this.value$.value\n void this.revalidateTrigger$.value\n // Track the gate so the effect re-runs when the field becomes unlocked.\n // While locked, skip the pass entirely — errors stay empty, the field\n // reads as valid, no async work starts.\n if (!this.validateUnlocked$.value) {\n batch(() => {\n if (this.validatorErrors$.peek().length > 0) this.validatorErrors$.set([])\n if (this.validating$.peek()) this.validating$.set(false)\n this.lastValid$.set(this.errors$.peek().length === 0)\n })\n return\n }\n\n // Abort previous in-flight run.\n this.currentAbort?.abort()\n const abort = new AbortController()\n this.currentAbort = abort\n const myId = ++this.runId\n\n const syncErrors: string[] = []\n const asyncPromises: Promise<ValidatorResult>[] = []\n\n for (const validator of this.validators) {\n try {\n const result = validator(value, abort.signal)\n if (result instanceof Promise) {\n // Defend against the validator promise rejecting *synchronously*\n // with a thrown error (rare but legal) — the catch-handler in\n // `Promise.allSettled` covers true async rejection.\n asyncPromises.push(result)\n } else {\n // A Standard-Schema validator returns `FormIssue[]`; a stdlib one\n // returns `string | null`. Flatten both to messages (a leaf field\n // has no descendants to route issue paths to).\n const msgs = messagesFromResult(result)\n if (msgs.length > 0) syncErrors.push(...msgs)\n }\n } catch (err) {\n // A buggy validator that throws synchronously: surface it twice.\n // (1) Route through `onError` so the developer knows something is wrong.\n // (2) Mark the field invalid until the bug is fixed (don't pretend OK).\n // In prod the user-visible message is generic — leaking an internal\n // error's text into form errors is a footgun; the real error still\n // reaches `onValidatorError` (T5.3). Dev keeps the message for DX.\n try {\n this.onValidatorError?.(err)\n } catch {\n // The reporter must not propagate.\n }\n syncErrors.push(\n __DEV__ ? (err instanceof Error ? err.message : String(err)) : 'Validation failed',\n )\n }\n }\n\n if (syncErrors.length > 0) {\n batch(() => {\n this.validatorErrors$.set(syncErrors)\n this.validating$.set(false)\n this.lastValid$.set(this.errors$.peek().length === 0)\n })\n this.emitValidated(false, syncErrors)\n return\n }\n\n if (asyncPromises.length === 0) {\n batch(() => {\n this.validatorErrors$.set([])\n this.validating$.set(false)\n this.lastValid$.set(this.errors$.peek().length === 0)\n })\n this.emitValidated(true, [])\n return\n }\n\n batch(() => {\n this.validatorErrors$.set([])\n this.validating$.set(true)\n })\n\n Promise.allSettled(asyncPromises).then((results) => {\n if (myId !== this.runId || this.disposed) return\n const asyncErrors: string[] = []\n for (const r of results) {\n if (r.status === 'fulfilled') {\n asyncErrors.push(...messagesFromResult(r.value))\n } else if (!isAbortError(r.reason)) {\n const msg = r.reason instanceof Error ? r.reason.message : String(r.reason)\n asyncErrors.push(msg)\n }\n }\n batch(() => {\n this.validatorErrors$.set(asyncErrors)\n this.validating$.set(false)\n this.lastValid$.set(this.errors$.peek().length === 0)\n })\n this.emitValidated(asyncErrors.length === 0, asyncErrors)\n })\n }\n}\n\n/**\n * Internal — type guard / accessor for the binding hook. Avoids exposing\n * `bindDevtoolsOwner` on the public `Field<T>` type while letting `createForm`\n * call it via a structural check.\n */\nexport function bindFieldDevtoolsOwner<T>(field: Field<T>, owner: FieldDevtoolsOwner | null): void {\n const impl = field as { bindDevtoolsOwner?: (o: FieldDevtoolsOwner | null) => void }\n if (typeof impl.bindDevtoolsOwner === 'function') {\n impl.bindDevtoolsOwner(owner)\n }\n}\n\n/**\n * Internal — install a synchronous-validator-throw reporter on a `Field`\n * (matched structurally to keep the public `Field<T>` surface stable).\n * Called by `ctx.field` and `bindTreeToDevtools` so leaves inside a form/\n * field-array tree get the same reporting as a standalone field.\n */\nexport function bindFieldValidatorErrorReporter<T>(\n field: Field<T>,\n reporter: ValidatorErrorReporter | null,\n): void {\n const impl = field as { bindValidatorErrorReporter?: (r: ValidatorErrorReporter | null) => void }\n if (typeof impl.bindValidatorErrorReporter === 'function') {\n impl.bindValidatorErrorReporter(reporter)\n }\n}\n\nexport function createField<T>(\n initial: T,\n validators?: ReadonlyArray<Validator<T>>,\n options?: FieldOptions,\n): Field<T> {\n return new FieldImpl(initial, validators, options)\n}\n\n/**\n * A bidirectional `T ↔ string` transform, suitable for HTML input bindings\n * where DOM values are always strings.\n *\n * `parse(raw)` converts the input's string value into the field's type;\n * `format(value)` converts the field's typed value back into a string for\n * the input. Both must be pure — `useFieldInput` calls them on every\n * render and every input event respectively.\n *\n * ```ts\n * const numberTransform: FieldTransform<number> = {\n * parse: (raw) => Number(raw),\n * format: (v) => String(v),\n * }\n * ```\n */\nexport type FieldTransform<T> = {\n parse: (raw: string) => T\n format: (value: T) => string\n}\n\n/**\n * Wrap an async validator with a debounce. The debounce timer resets on every\n * value change. While debouncing or the request is in flight, the field's\n * `isValidating` is true and `isValid` HOLDS its last settled value (T5.3) — so\n * editing an already-valid field doesn't strobe a submit button to disabled on\n * every keystroke. A field with no prior settled validation defaults to valid.\n */\nexport function debouncedValidator<T>(\n fn: (value: T, signal: AbortSignal) => Promise<string | null>,\n ms: number,\n): (value: T, signal: AbortSignal) => Promise<string | null> {\n // Precise return (not the wide `Validator<T>`): the wrapped `fn` only ever\n // yields `string | null`, so callers that invoke the debounced validator\n // directly — e.g. surfacing its result in a signal — keep that narrow type\n // after `Validator<T>` was widened to allow `FormIssue[]` (T5.2). Still\n // assignable wherever a `Validator<T>` is expected.\n return (value, signal) =>\n new Promise<string | null>((resolve, reject) => {\n if (signal.aborted) {\n reject(new DOMException('Aborted', 'AbortError'))\n return\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n fn(value, signal).then(resolve, reject)\n }, ms)\n const onAbort = () => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n reject(new DOMException('Aborted', 'AbortError'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n","import type { Field } from '../controller/types'\nimport { batch, computed, effect, type Signal, signal, untracked } from '../signals'\nimport type { ReadSignal } from '../signals/types'\nimport {\n bindFieldDevtoolsOwner,\n bindFieldValidatorErrorReporter,\n createField,\n type ValidatorErrorReporter,\n} from './field'\nimport type {\n DeepPartial,\n FieldArray,\n FieldArrayItemErrors,\n FieldArrayOptions,\n FieldArrayValidator,\n FieldArrayValue,\n Form,\n FormErrors,\n FormOptions,\n FormSchema,\n FormValidator,\n FormValue,\n ItemInitial,\n} from './form-types'\nimport type { FormIssue, ValidatorResult } from './types'\n\nconst FORM_BRAND = Symbol.for('olas.form')\nconst FIELD_ARRAY_BRAND = Symbol.for('olas.fieldArray')\n\nconst isForm = (x: unknown): x is Form<FormSchema> =>\n typeof x === 'object' && x !== null && (x as Record<symbol, unknown>)[FORM_BRAND] === true\n\nconst isFieldArray = (x: unknown): x is FieldArray<Field<unknown> | Form<FormSchema>> =>\n typeof x === 'object' && x !== null && (x as Record<symbol, unknown>)[FIELD_ARRAY_BRAND] === true\n\nconst isField = (x: unknown): x is Field<unknown> =>\n typeof x === 'object' && x !== null && !isForm(x) && !isFieldArray(x)\n\n/** Any node that can receive parent-form-validator-routed errors (T5.2). */\ntype FormErrorTarget = { setFormErrors?: (msgs: ReadonlyArray<string>) => void }\n\n/**\n * Walk a form tree from `root` following `FormIssue.path` segments. Forms walk\n * keys; field-arrays walk numeric indices. Returns the resolved node, or\n * `undefined` if the path runs off the tree (bad index, or a leaf reached with\n * an unconsumed path segment). Reads are untracked (`fields` is a static object;\n * `at()` peeks) so calling this inside a validator effect adds no dependencies.\n */\nfunction resolveNode(root: unknown, segments: ReadonlyArray<string | number>): unknown {\n let cursor: unknown = root\n for (const seg of segments) {\n if (cursor === undefined || cursor === null) return undefined\n if (isForm(cursor)) {\n cursor = (cursor.fields as Record<string, unknown>)[String(seg)]\n } else if (isFieldArray(cursor)) {\n const idx = Number(seg)\n if (!Number.isInteger(idx) || idx < 0) return undefined\n cursor = (cursor as { at(i: number): unknown }).at(idx)\n } else {\n return undefined\n }\n }\n return cursor\n}\n\n/**\n * Normalize one validator result into the shared `FormIssue[]` shape. A plain\n * string is a message on the node itself (empty path); `null` contributes\n * nothing; a `FormIssue[]` is appended verbatim.\n */\nfunction appendIssues(out: FormIssue[], result: ValidatorResult): void {\n if (result == null) return\n if (typeof result === 'string') {\n out.push({ path: [], message: result })\n return\n }\n for (const issue of result) out.push(issue)\n}\n\n/**\n * Route a fully-collected issue set for one form-level validation run:\n * - empty-path (and unresolvable) issues → `topLevelErrors$` on the owning node\n * - path issues → the resolved descendant's `setFormErrors`\n *\n * Targets that received an error last run but not this one are cleared, so a\n * fixed cross-field rule removes its message from the field it landed on.\n * Returns the new target set for the caller to retain. MUST run inside a batch.\n */\nfunction routeFormIssues(\n root: unknown,\n issues: FormIssue[],\n topLevelErrors$: Signal<string[]>,\n lastTargets: Set<FormErrorTarget>,\n): Set<FormErrorTarget> {\n const topLevel: string[] = []\n const byTarget = new Map<FormErrorTarget, string[]>()\n for (const issue of issues) {\n if (issue.path.length === 0) {\n topLevel.push(issue.message)\n continue\n }\n const target = resolveNode(root, issue.path) as FormErrorTarget | undefined\n if (target === undefined || typeof target.setFormErrors !== 'function') {\n // Unresolvable path — surface at the top level rather than dropping it.\n topLevel.push(issue.message)\n continue\n }\n const list = byTarget.get(target)\n if (list) list.push(issue.message)\n else byTarget.set(target, [issue.message])\n }\n topLevelErrors$.set(topLevel)\n for (const t of lastTargets) {\n if (!byTarget.has(t)) t.setFormErrors?.([])\n }\n for (const [t, msgs] of byTarget) t.setFormErrors?.(msgs)\n return new Set(byTarget.keys())\n}\n\nclass FormImpl<S extends FormSchema> implements Form<S> {\n readonly [FORM_BRAND] = true\n\n readonly fields: S\n readonly value: ReadSignal<FormValue<S>>\n readonly errors: ReadSignal<FormErrors<S>>\n readonly isValid: ReadSignal<boolean>\n readonly isDirty: ReadSignal<boolean>\n readonly touched: ReadSignal<boolean>\n readonly isValidating: ReadSignal<boolean>\n readonly flatErrors: ReadSignal<Array<{ path: string; errors: string[] }>>\n /**\n * Dotted paths of every leaf whose `isDirty` is `true`. Recomputes when\n * any child's dirty state flips; ordered by depth-first traversal so two\n * snapshots of a stable tree compare with `===`-friendly references on\n * unchanged subsets. Useful for partial-update PATCH payloads and\n * \"highlight the changed inputs\" UIs.\n */\n readonly dirtyFields: ReadSignal<string[]>\n\n private readonly topLevelErrors$: Signal<string[]> = signal([])\n /**\n * Errors routed to THIS form by an ancestor form-level validator (a\n * `FormIssue` whose path resolves to this node). Merged into `topLevelErrors`\n * beside this form's own validator output, so `topLevelErrors` means \"errors\n * attached to this node itself, whatever their source\". Owned by the ancestor\n * router (T5.2) — see `setFormErrors`.\n */\n private readonly parentFormErrors$: Signal<string[]> = signal([])\n readonly topLevelErrors: ReadSignal<string[]> = computed(() => {\n const own = this.topLevelErrors$.value\n const parent = this.parentFormErrors$.value\n if (parent.length === 0) return own\n if (own.length === 0) return parent\n return [...own, ...parent]\n })\n private readonly topLevelValidating$: Signal<boolean> = signal(false)\n /** Targets written by the last form-level run — cleared next run if absent. */\n private lastFormErrorTargets: Set<FormErrorTarget> = new Set()\n\n // Submission lifecycle.\n private readonly isSubmitting$: Signal<boolean> = signal(false)\n private readonly submitCount$: Signal<number> = signal(0)\n private readonly submitError$: Signal<unknown> = signal(undefined)\n readonly isSubmitting: ReadSignal<boolean> = this.isSubmitting$\n readonly submitCount: ReadSignal<number> = this.submitCount$\n readonly submitError: ReadSignal<unknown> = this.submitError$\n\n private readonly validators: ReadonlyArray<FormValidator<S>>\n private readonly options: FormOptions<S> | undefined\n private validatorDispose: (() => void) | null = null\n private initialDispose: (() => void) | null = null\n private currentValidatorRun = 0\n private currentValidatorAbort: AbortController | null = null\n private disposed = false\n private onValidatorError: ((err: unknown) => void) | null = null\n\n /** Internal — wire a sync-throw reporter for the top-level validators. */\n bindValidatorErrorReporter(reporter: ((err: unknown) => void) | null): void {\n this.onValidatorError = reporter\n }\n\n constructor(\n schema: S,\n options?: FormOptions<S>,\n internalOptions?: { onValidatorError?: (err: unknown) => void },\n ) {\n this.fields = schema\n this.options = options\n this.validators = options?.validators ?? []\n // Capture reporter BEFORE the top-level validator effect kicks off in\n // this constructor — mirrors the FieldImpl fix.\n this.onValidatorError = internalOptions?.onValidatorError ?? null\n\n // Initial values — supports both the static shape and the tracked-function\n // shape from spec §8.4. For the function form, wrap in an effect so a\n // change to any tracked signal re-seats the form (subject to the dirty\n // guard from `resetOnInitialChange`).\n if (options?.initial !== undefined) {\n if (typeof options.initial === 'function') {\n const initialFn = options.initial\n const mode = options.resetOnInitialChange ?? 'when-clean'\n let firstRun = true\n this.initialDispose = effect(() => {\n // Track signals read by `initialFn`. The dirty-guard MUST run\n // untracked — otherwise `isDirty` would become a dep and re-seating\n // on user input would cascade.\n const ini = initialFn()\n if (ini === undefined) return\n untracked(() => {\n if (this.disposed) return\n if (firstRun) {\n firstRun = false\n this.applyPartial(ini as DeepPartial<FormValue<S>>, true)\n return\n }\n if (mode === 'never') return\n if (mode === 'when-clean' && this.isDirty.peek()) return\n this.applyPartial(ini as DeepPartial<FormValue<S>>, true)\n })\n })\n } else {\n this.applyPartial(options.initial as DeepPartial<FormValue<S>>, true)\n }\n }\n\n this.value = computed(() => this.computeValue())\n this.errors = computed(() => this.computeErrors())\n this.isDirty = computed(() => this.computeBool('isDirty'))\n this.touched = computed(() => this.computeBool('touched'))\n this.isValidating = computed(() => {\n if (this.topLevelValidating$.value) return true\n for (const child of Object.values(this.fields)) {\n if ((child as { isValidating: ReadSignal<boolean> }).isValidating.value) return true\n }\n return false\n })\n this.isValid = computed(() => {\n // Merged view: this form's own top-level validators AND any errors an\n // ancestor form-level validator routed onto this node (T5.2).\n if (this.topLevelErrors.value.length > 0) return false\n if (this.isValidating.value) return false\n for (const child of Object.values(this.fields)) {\n if (!(child as { isValid: ReadSignal<boolean> }).isValid.value) return false\n }\n return true\n })\n this.flatErrors = computed(() => this.computeFlatErrors())\n this.dirtyFields = computed(() => {\n const out: string[] = []\n collectDirtyFields(this.fields, '', out)\n return out\n })\n\n if (this.validators.length > 0) {\n this.validatorDispose = effect(() => this.runTopLevelValidators())\n }\n }\n\n private computeValue(): FormValue<S> {\n const out: Record<string, unknown> = {}\n for (const [k, child] of Object.entries(this.fields)) {\n if (isForm(child) || isFieldArray(child)) {\n out[k] = (child as { value: ReadSignal<unknown> }).value.value\n } else {\n // Field<T> is itself a ReadSignal<T>; .value returns T (tracked).\n out[k] = (child as Field<unknown>).value\n }\n }\n return out as FormValue<S>\n }\n\n private computeErrors(): FormErrors<S> {\n const out: Record<string, unknown> = {}\n for (const [k, child] of Object.entries(this.fields)) {\n if (isForm(child)) {\n out[k] = child.errors.value\n } else if (isFieldArray(child)) {\n out[k] = child.errors.value\n } else {\n const errs = (child as Field<unknown>).errors.value\n out[k] = errs.length > 0 ? errs : undefined\n }\n }\n return out as FormErrors<S>\n }\n\n private computeBool(key: 'isDirty' | 'touched'): boolean {\n for (const child of Object.values(this.fields)) {\n const sig = (child as unknown as Record<string, ReadSignal<boolean>>)[key]\n if (sig?.value) return true\n }\n return false\n }\n\n private computeFlatErrors(): Array<{ path: string; errors: string[] }> {\n const out: Array<{ path: string; errors: string[] }> = []\n const tle = this.topLevelErrors.value\n if (tle.length > 0) out.push({ path: '', errors: tle })\n walkErrors(this.fields, '', out)\n return out\n }\n\n set(partial: DeepPartial<FormValue<S>>): void {\n if (this.disposed) return\n batch(() => this.applyPartial(partial, false))\n }\n\n private applyPartial(partial: DeepPartial<FormValue<S>>, asInitial: boolean): void {\n for (const [k, val] of Object.entries(partial)) {\n const child = (this.fields as Record<string, unknown>)[k]\n if (!child) continue\n // `partial.someNestedForm === undefined` means \"leave this subtree\n // alone\", not \"reset it with undefined\" — which would crash on\n // `Object.entries(undefined)`.\n if (val === undefined) continue\n if (isForm(child)) {\n // Nested form: recurse via its own `set` (user) or rebuild via reset\n // through the same `applyPartial`-with-`asInitial` flag (initial).\n if (asInitial) {\n ;(child as Form<FormSchema>).resetWithInitial(val as DeepPartial<FormValue<FormSchema>>)\n } else {\n child.set(val as DeepPartial<FormValue<FormSchema>>)\n }\n } else if (isFieldArray(child)) {\n const arr = child\n const newValues = val as unknown[]\n if (asInitial) {\n // Reset-style application: replace items wholesale and re-anchor\n // them as the new initial so a later `reset()` returns here.\n arr.clear()\n for (const itemVal of newValues) {\n arr.add(itemVal as ItemInitial<Field<unknown>>)\n }\n // Internal: re-anchor the initialItems list. `replaceInitialItems`\n // is only exposed for this exact use case.\n ;(\n arr as unknown as {\n replaceInitialItems: (items: ReadonlyArray<unknown>) => void\n }\n ).replaceInitialItems(newValues)\n } else {\n // User-driven patch: preserve item identity where the lengths\n // overlap so touched / dirty / in-flight validators on existing\n // items survive. Tail diff handles grow / shrink.\n const current = arr.items.peek() as ReadonlyArray<Field<unknown> | Form<FormSchema>>\n const overlap = Math.min(current.length, newValues.length)\n for (let i = 0; i < overlap; i++) {\n const item = current[i]\n const v = newValues[i]\n if (isForm(item)) {\n item.set(v as DeepPartial<FormValue<FormSchema>>)\n } else {\n ;(item as Field<unknown>).set(v)\n }\n }\n for (let i = current.length; i < newValues.length; i++) {\n arr.add(newValues[i] as ItemInitial<Field<unknown>>)\n }\n for (let i = current.length - 1; i >= newValues.length; i--) {\n arr.remove(i)\n }\n }\n } else {\n const f = child as Field<unknown>\n if (asInitial) f.setAsInitial(val)\n else f.set(val)\n }\n }\n }\n\n /** Internal: re-seat this form's leaves from `partial` as their new initial. */\n resetWithInitial(partial: DeepPartial<FormValue<S>>): void {\n if (this.disposed) return\n batch(() => this.applyPartial(partial, true))\n }\n\n reset(): void {\n if (this.disposed) return\n batch(() => {\n for (const child of Object.values(this.fields)) {\n if (isForm(child) || isFieldArray(child)) {\n ;(child as { reset: () => void }).reset()\n } else {\n ;(child as Field<unknown>).reset()\n }\n }\n this.topLevelErrors$.set([])\n this.parentFormErrors$.set([])\n // Submission lifecycle is conceptually part of \"form state\"; resetting\n // a form means the user is starting over. Without these clears, a UI\n // bound to `submitCount`/`submitError` would show stale state after\n // `reset()`. `isSubmitting` is deliberately NOT cleared — only the\n // owning submit() flow can flip it back.\n this.submitCount$.set(0)\n this.submitError$.set(undefined)\n // Re-apply initial (as initial, no dirty bump) INSIDE the batch — a\n // separate pass would fire a second notification and briefly expose the\n // \"reset to construction seed, then re-seat to current initial\" tearing\n // (visible with a reactive `initial: () => …` whose deps changed) (T5.3).\n if (this.options?.initial !== undefined) {\n const ini =\n typeof this.options.initial === 'function' ? this.options.initial() : this.options.initial\n if (ini !== undefined) this.applyPartial(ini as DeepPartial<FormValue<S>>, true)\n }\n })\n }\n\n markAllTouched(): void {\n if (this.disposed) return\n for (const child of Object.values(this.fields)) {\n if (isForm(child)) child.markAllTouched()\n else if (isFieldArray(child)) child.markAllTouched()\n else (child as Field<unknown>).markTouched()\n }\n }\n\n async validate(): Promise<boolean> {\n if (this.disposed) return this.isValid.peek()\n const tasks: Promise<unknown>[] = []\n for (const child of Object.values(this.fields)) {\n if (isForm(child) || isFieldArray(child)) {\n tasks.push((child as { validate: () => Promise<boolean> }).validate())\n } else {\n tasks.push((child as Field<unknown>).revalidate())\n }\n }\n await Promise.all(tasks)\n // Kick a fresh top-level run so the surface matches \"re-run every\n // validator\" — without this, `validate()` would skip top-level if it\n // settled before the call and the value hasn't tracked-changed since.\n if (this.validators.length > 0) {\n this.runTopLevelValidators()\n }\n // Wait for top-level validators to finish.\n if (this.topLevelValidating$.peek()) {\n await new Promise<void>((resolve) => {\n const unsub = this.topLevelValidating$.subscribe((v) => {\n if (!v) {\n unsub()\n resolve()\n }\n })\n })\n }\n return this.isValid.peek()\n }\n\n /**\n * Run a submission against this form. Wraps `handler(value)` with:\n * - `isSubmitting` set true while the handler is in flight.\n * - `submitCount` incremented before the handler runs.\n * - `submitError` set to the throw, if any.\n * - Optional pre-submit `validate()` (default true). When invalid every\n * field is marked touched and the handler is skipped — the returned\n * promise resolves with `{ ok: false }` and `submitError` is left\n * untouched (validation failure is not a thrown error).\n *\n * The handler may return a value (synchronously or via Promise); it's\n * captured in the resolved object's `data` field. Throws are captured\n * unless `onError: 'rethrow'`. A `resetOnSuccess: true` option calls\n * `reset()` after the handler resolves successfully.\n */\n async submit<R = unknown>(\n handler: (value: FormValue<S>) => R | Promise<R>,\n options?: {\n validateBeforeSubmit?: boolean\n resetOnSuccess?: boolean\n onError?: 'rethrow' | 'capture'\n },\n ): Promise<{ ok: boolean; data?: Awaited<R>; error?: unknown }> {\n if (this.disposed) return { ok: false, error: new Error('form is disposed') }\n\n // Double-submit guard — refusing to start a second submission while one\n // is in flight matches RHF / TanStack-Form. Consumers wanting parallel\n // submits should run them off the form directly.\n if (this.isSubmitting$.peek()) {\n return { ok: false, error: new Error('submit already in progress') }\n }\n\n const validateFirst = options?.validateBeforeSubmit ?? true\n const onErrorMode = options?.onError ?? 'capture'\n\n batch(() => {\n this.submitCount$.update((n) => n + 1)\n this.submitError$.set(undefined)\n this.isSubmitting$.set(true)\n })\n\n try {\n if (validateFirst) {\n const ok = await this.validate()\n if (!ok) {\n this.markAllTouched()\n this.isSubmitting$.set(false)\n return { ok: false }\n }\n }\n const result = (await handler(this.value.peek())) as Awaited<R>\n if (options?.resetOnSuccess) this.reset()\n this.isSubmitting$.set(false)\n return { ok: true, data: result }\n } catch (err) {\n batch(() => {\n this.submitError$.set(err)\n this.isSubmitting$.set(false)\n })\n if (onErrorMode === 'rethrow') throw err\n return { ok: false, error: err }\n }\n }\n\n /**\n * Pin externally-sourced errors on specific fields — typically server-side\n * validation results from a failed submit. Paths are dot-separated and\n * traverse nested `Form` / `FieldArray` children (numeric segments are\n * array indices). Errors land in the field's `serverErrors` channel and\n * clear automatically on the next user write to that field. Passing an\n * empty array for a path clears that field's server errors immediately.\n */\n setErrors(errors: Record<string, ReadonlyArray<string>>): void {\n if (this.disposed) return\n batch(() => {\n for (const [path, msgs] of Object.entries(errors)) {\n const target = this.resolvePath(path)\n if (target === undefined) continue\n if ((target as { setErrors?: unknown }).setErrors === undefined) continue\n ;(target as { setErrors: (e: ReadonlyArray<string>) => void }).setErrors(msgs)\n }\n })\n }\n\n /**\n * Internal — receive errors routed here by an ancestor form-level validator\n * (a `FormIssue` whose path resolved to this nested form). Guards against\n * spurious writes so a whole-tree clear pass doesn't wake subscribers. See\n * `routeFormIssues`.\n */\n setFormErrors(errors: ReadonlyArray<string>): void {\n if (this.disposed) return\n if (this.parentFormErrors$.peek().length === 0 && errors.length === 0) return\n this.parentFormErrors$.set(errors.length === 0 ? [] : [...errors])\n }\n\n /**\n * Reset a named subtree to its initial. `path` uses the same dotted /\n * bracket notation as `setErrors` / `flatErrors`. Useful when\n * `Form.set({foo: undefined})` would be ambiguous (\"clear\" vs \"leave\n * alone\" — the latter is what `set` does today).\n *\n * Walks via `resolvePath`; the resolved target must expose `reset()`\n * (Field, Form, or FieldArray all do). Unknown paths are silently\n * ignored — `flatErrors`-shaped paths from upstream code shouldn't\n * crash this. Pass an empty string to reset the whole form (same as\n * `form.reset()`).\n */\n clearSubtree(path: string): void {\n if (this.disposed) return\n if (path === '') {\n this.reset()\n return\n }\n const target = this.resolvePath(path) as { reset?: () => void } | undefined\n if (target === undefined) return\n if (typeof target.reset === 'function') target.reset()\n }\n\n private resolvePath(path: string): unknown {\n if (path === '') return undefined\n const segments = splitPath(path)\n if (segments === null) return undefined\n let cursor: unknown = this\n for (const seg of segments) {\n if (cursor === undefined || cursor === null) return undefined\n if (isForm(cursor)) {\n cursor = (cursor.fields as Record<string, unknown>)[seg]\n continue\n }\n if (isFieldArray(cursor)) {\n const idx = Number(seg)\n if (!Number.isInteger(idx) || idx < 0) return undefined\n cursor = (cursor as { at(i: number): unknown }).at(idx)\n continue\n }\n // Top-level dispatch — `this` is the FormImpl; walk via `fields`.\n if (cursor === this) {\n cursor = (this.fields as Record<string, unknown>)[seg]\n continue\n }\n return undefined\n }\n return cursor\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.validatorDispose?.()\n this.initialDispose?.()\n this.currentValidatorAbort?.abort()\n for (const child of Object.values(this.fields)) {\n ;(child as { dispose?: () => void }).dispose?.()\n }\n }\n\n private runTopLevelValidators(): void {\n if (this.disposed) return\n const value = this.value.value\n this.currentValidatorAbort?.abort()\n const abort = new AbortController()\n this.currentValidatorAbort = abort\n const myId = ++this.currentValidatorRun\n\n const syncIssues: FormIssue[] = []\n const asyncPromises: Promise<ValidatorResult>[] = []\n for (const v of this.validators) {\n try {\n const r = v(value, abort.signal)\n if (r instanceof Promise) asyncPromises.push(r)\n else appendIssues(syncIssues, r)\n } catch (err) {\n try {\n this.onValidatorError?.(err)\n } catch {\n // The reporter must not propagate.\n }\n // Prod shows a generic message (don't leak internal error text into\n // form errors); the real error still reaches `onValidatorError` (T5.3).\n syncIssues.push({\n path: [],\n message: __DEV__\n ? err instanceof Error\n ? err.message\n : String(err)\n : 'Validation failed',\n })\n }\n }\n\n if (syncIssues.length > 0) {\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n syncIssues,\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n return\n }\n\n if (asyncPromises.length === 0) {\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n [],\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n return\n }\n\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n [],\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(true)\n })\n\n Promise.allSettled(asyncPromises).then((results) => {\n if (myId !== this.currentValidatorRun || this.disposed) return\n const issues: FormIssue[] = []\n for (const r of results) {\n if (r.status === 'fulfilled') appendIssues(issues, r.value)\n }\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n issues,\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n })\n }\n}\n\n/**\n * Split a path string into segments, accepting both dot syntax (`users.0.name`)\n * and the bracket syntax `walkErrors` emits for array items (`users[0].name`).\n * Returns `null` if the path is malformed (unclosed bracket, empty bracket,\n * non-numeric bracket index).\n */\nfunction splitPath(path: string): string[] | null {\n const out: string[] = []\n let current = ''\n for (let i = 0; i < path.length; i++) {\n const ch = path[i]\n if (ch === '.') {\n if (current !== '') {\n out.push(current)\n current = ''\n }\n continue\n }\n if (ch === '[') {\n if (current !== '') {\n out.push(current)\n current = ''\n }\n const close = path.indexOf(']', i + 1)\n if (close === -1) return null\n const idx = path.slice(i + 1, close)\n if (idx === '' || !/^\\d+$/.test(idx)) return null\n out.push(idx)\n i = close\n continue\n }\n if (ch === ']') return null\n current += ch\n }\n if (current !== '') out.push(current)\n return out\n}\n\nfunction collectDirtyFields(fields: FormSchema, prefix: string, out: string[]): void {\n for (const [k, child] of Object.entries(fields)) {\n const path = prefix ? `${prefix}.${k}` : k\n if (isForm(child)) {\n collectDirtyFields(child.fields, path, out)\n } else if (isFieldArray(child)) {\n const items = child.items.value\n items.forEach((item, idx) => {\n const itemPath = `${path}[${idx}]`\n if (isForm(item)) {\n collectDirtyFields(item.fields, itemPath, out)\n } else if ((item as Field<unknown>).isDirty.value) {\n out.push(itemPath)\n }\n })\n } else if ((child as Field<unknown>).isDirty.value) {\n out.push(path)\n }\n }\n}\n\nfunction walkErrors(\n fields: FormSchema,\n prefix: string,\n out: Array<{ path: string; errors: string[] }>,\n): void {\n for (const [k, child] of Object.entries(fields)) {\n const path = prefix ? `${prefix}.${k}` : k\n if (isForm(child)) {\n const tle = child.topLevelErrors.value\n if (tle.length > 0) out.push({ path, errors: tle })\n walkErrors(child.fields, path, out)\n } else if (isFieldArray(child)) {\n const tle = child.topLevelErrors.value\n if (tle.length > 0) out.push({ path, errors: tle })\n const items = child.items.value\n items.forEach((item, idx) => {\n const itemPath = `${path}[${idx}]`\n if (isForm(item)) {\n const itle = item.topLevelErrors.value\n if (itle.length > 0) out.push({ path: itemPath, errors: itle })\n walkErrors(item.fields, itemPath, out)\n } else {\n const errs = (item as Field<unknown>).errors.value\n if (errs.length > 0) out.push({ path: itemPath, errors: errs })\n }\n })\n } else {\n const errs = (child as Field<unknown>).errors.value\n if (errs.length > 0) out.push({ path, errors: errs })\n }\n }\n}\n\nclass FieldArrayImpl<I extends Field<any> | Form<any>> implements FieldArray<I> {\n readonly [FIELD_ARRAY_BRAND] = true\n\n readonly items: ReadSignal<ReadonlyArray<I>>\n readonly value: ReadSignal<FieldArrayValue<I>>\n readonly errors: ReadSignal<Array<FieldArrayItemErrors<I> | undefined>>\n readonly size: ReadSignal<number>\n readonly isValid: ReadSignal<boolean>\n readonly isDirty: ReadSignal<boolean>\n readonly touched: ReadSignal<boolean>\n readonly isValidating: ReadSignal<boolean>\n\n private readonly items$: Signal<I[]>\n /**\n * Structural dirtiness — flipped by `add`/`insert`/`remove`/`move`/`clear`.\n * Item-level `isDirty` alone misses these, so a reactive `initial` + the\n * default `resetOnInitialChange: 'when-clean'` would re-seat the array on a\n * background refetch and delete rows the user just added (T5.1). Reset by\n * `reset()` and by an initial-driven re-anchor (`replaceInitialItems`).\n */\n private readonly structurallyDirty$: Signal<boolean> = signal(false)\n private readonly topLevelErrors$: Signal<string[]> = signal([])\n /** Errors routed to this array by an ancestor form-level validator (T5.2) —\n * merged into `topLevelErrors` beside the array's own validator output. */\n private readonly parentFormErrors$: Signal<string[]> = signal([])\n readonly topLevelErrors: ReadSignal<string[]> = computed(() => {\n const own = this.topLevelErrors$.value\n const parent = this.parentFormErrors$.value\n if (parent.length === 0) return own\n if (own.length === 0) return parent\n return [...own, ...parent]\n })\n private readonly topLevelValidating$: Signal<boolean> = signal(false)\n /** Targets written by the last array-level run — cleared next run if absent. */\n private lastFormErrorTargets: Set<FormErrorTarget> = new Set()\n\n private readonly itemFactory: (initial?: ItemInitial<I>) => I\n private initialItems: Array<ItemInitial<I>> = []\n private readonly validators: ReadonlyArray<FieldArrayValidator<I>>\n private currentValidatorRun = 0\n private currentValidatorAbort: AbortController | null = null\n private validatorDispose: (() => void) | null = null\n private disposed = false\n private onValidatorError: ((err: unknown) => void) | null = null\n\n /** Internal — see `FormImpl.bindValidatorErrorReporter`. */\n bindValidatorErrorReporter(reporter: ((err: unknown) => void) | null): void {\n this.onValidatorError = reporter\n }\n\n constructor(\n itemFactory: (initial?: ItemInitial<I>) => I,\n options?: FieldArrayOptions<I>,\n internalOptions?: { onValidatorError?: (err: unknown) => void },\n ) {\n this.itemFactory = itemFactory\n this.validators = options?.validators ?? []\n this.onValidatorError = internalOptions?.onValidatorError ?? null\n this.items$ = signal<I[]>([])\n if (options?.initial) {\n this.initialItems = options.initial\n for (const ini of options.initial) {\n this.items$.peek().push(itemFactory(ini))\n }\n // re-set to trigger subscribers\n this.items$.set([...this.items$.peek()])\n }\n\n this.items = this.items$\n this.size = computed(() => this.items$.value.length)\n this.value = computed(\n () =>\n this.items$.value.map((item) => {\n if (isForm(item)) return item.value.value\n // Field is a ReadSignal — `.value` is the actual value.\n return (item as Field<unknown>).value\n }) as FieldArrayValue<I>,\n )\n this.errors = computed(() =>\n this.items$.value.map((item) => {\n if (isForm(item)) return item.errors.value as FieldArrayItemErrors<I>\n const errs = (item as Field<unknown>).errors.value\n return (errs.length > 0 ? errs : undefined) as FieldArrayItemErrors<I> | undefined\n }),\n )\n this.isDirty = computed(() => {\n if (this.structurallyDirty$.value) return true // add/remove/move/clear\n for (const item of this.items$.value) {\n if ((item as { isDirty: ReadSignal<boolean> }).isDirty.value) return true\n }\n return false\n })\n this.touched = computed(() => {\n for (const item of this.items$.value) {\n if ((item as { touched: ReadSignal<boolean> }).touched.value) return true\n }\n return false\n })\n this.isValidating = computed(() => {\n if (this.topLevelValidating$.value) return true\n for (const item of this.items$.value) {\n if ((item as { isValidating: ReadSignal<boolean> }).isValidating.value) return true\n }\n return false\n })\n this.isValid = computed(() => {\n // Merged view: the array's own top-level validators AND any errors an\n // ancestor form-level validator routed onto this node (T5.2).\n if (this.topLevelErrors.value.length > 0) return false\n if (this.isValidating.value) return false\n for (const item of this.items$.value) {\n if (!(item as { isValid: ReadSignal<boolean> }).isValid.value) return false\n }\n return true\n })\n\n if (this.validators.length > 0) {\n this.validatorDispose = effect(() => this.runTopLevelValidators())\n }\n }\n\n at(index: number): I | undefined {\n return this.items$.peek()[index]\n }\n\n /**\n * Internal — receive errors routed here by an ancestor form-level validator\n * (a `FormIssue` whose path resolved to this array). See `routeFormIssues`.\n */\n setFormErrors(errors: ReadonlyArray<string>): void {\n if (this.disposed) return\n if (this.parentFormErrors$.peek().length === 0 && errors.length === 0) return\n this.parentFormErrors$.set(errors.length === 0 ? [] : [...errors])\n }\n\n add(initial?: ItemInitial<I>): void {\n if (this.disposed) return\n const item = this.itemFactory(initial)\n this.items$.set([...this.items$.peek(), item])\n this.structurallyDirty$.set(true)\n }\n\n insert(index: number, initial?: ItemInitial<I>): void {\n if (this.disposed) return\n const item = this.itemFactory(initial)\n const next = [...this.items$.peek()]\n next.splice(index, 0, item)\n this.items$.set(next)\n this.structurallyDirty$.set(true)\n }\n\n remove(index: number): void {\n if (this.disposed) return\n const next = [...this.items$.peek()]\n const [removed] = next.splice(index, 1)\n if (removed) {\n ;(removed as { dispose?: () => void }).dispose?.()\n }\n this.items$.set(next)\n this.structurallyDirty$.set(true)\n }\n\n move(from: number, to: number): void {\n if (this.disposed) return\n const next = [...this.items$.peek()]\n const [item] = next.splice(from, 1)\n if (item) next.splice(to, 0, item)\n this.items$.set(next)\n this.structurallyDirty$.set(true)\n }\n\n clear(): void {\n if (this.disposed) return\n for (const item of this.items$.peek()) {\n ;(item as { dispose?: () => void }).dispose?.()\n }\n this.items$.set([])\n this.structurallyDirty$.set(true)\n }\n\n /**\n * Internal — used by `Form.resetWithInitial` to re-anchor the array's\n * initial items after a parent-driven `applyPartial(..., asInitial: true)`.\n * Without this, a subsequent `reset()` would revert to the construction-\n * time initials rather than the most-recently-applied ones.\n */\n replaceInitialItems(items: ReadonlyArray<ItemInitial<I>>): void {\n this.initialItems = [...items]\n // The array was just re-seated from `initial` (reactive-initial re-apply or\n // `resetWithInitial`) — this is the new clean baseline, so the clear()/add()\n // that drove it must not leave the array structurally dirty (T5.1).\n this.structurallyDirty$.set(false)\n }\n\n reset(): void {\n if (this.disposed) return\n batch(() => {\n this.clear()\n for (const ini of this.initialItems) {\n this.add(ini)\n }\n this.topLevelErrors$.set([])\n this.parentFormErrors$.set([])\n // clear()/add() above flipped structural dirt; reset() lands on the\n // clean initial baseline (T5.1).\n this.structurallyDirty$.set(false)\n })\n }\n\n markAllTouched(): void {\n for (const item of this.items$.peek()) {\n if (isForm(item)) item.markAllTouched()\n else (item as Field<unknown>).markTouched()\n }\n }\n\n async validate(): Promise<boolean> {\n if (this.disposed) return this.isValid.peek()\n const tasks: Promise<unknown>[] = []\n for (const item of this.items$.peek()) {\n if (isForm(item)) tasks.push(item.validate())\n else tasks.push((item as Field<unknown>).revalidate())\n }\n await Promise.all(tasks)\n // Fresh top-level run — see `FormImpl.validate` for the rationale.\n if (this.validators.length > 0) {\n this.runTopLevelValidators()\n }\n if (this.topLevelValidating$.peek()) {\n await new Promise<void>((resolve) => {\n const unsub = this.topLevelValidating$.subscribe((v) => {\n if (!v) {\n unsub()\n resolve()\n }\n })\n })\n }\n return this.isValid.peek()\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.validatorDispose?.()\n this.currentValidatorAbort?.abort()\n for (const item of this.items$.peek()) {\n ;(item as { dispose?: () => void }).dispose?.()\n }\n }\n\n private runTopLevelValidators(): void {\n if (this.disposed) return\n const value = this.value.value\n this.currentValidatorAbort?.abort()\n const abort = new AbortController()\n this.currentValidatorAbort = abort\n const myId = ++this.currentValidatorRun\n\n const syncIssues: FormIssue[] = []\n const asyncPromises: Promise<ValidatorResult>[] = []\n for (const v of this.validators) {\n try {\n const r = v(value, abort.signal)\n if (r instanceof Promise) asyncPromises.push(r)\n else appendIssues(syncIssues, r)\n } catch (err) {\n try {\n this.onValidatorError?.(err)\n } catch {\n // The reporter must not propagate.\n }\n // Prod shows a generic message (don't leak internal error text into\n // form errors); the real error still reaches `onValidatorError` (T5.3).\n syncIssues.push({\n path: [],\n message: __DEV__\n ? err instanceof Error\n ? err.message\n : String(err)\n : 'Validation failed',\n })\n }\n }\n\n if (syncIssues.length > 0) {\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n syncIssues,\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n return\n }\n\n if (asyncPromises.length === 0) {\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n [],\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n return\n }\n\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n [],\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(true)\n })\n\n Promise.allSettled(asyncPromises).then((results) => {\n if (myId !== this.currentValidatorRun || this.disposed) return\n const issues: FormIssue[] = []\n for (const r of results) {\n if (r.status === 'fulfilled') appendIssues(issues, r.value)\n }\n batch(() => {\n this.lastFormErrorTargets = routeFormIssues(\n this,\n issues,\n this.topLevelErrors$,\n this.lastFormErrorTargets,\n )\n this.topLevelValidating$.set(false)\n })\n })\n }\n}\n\nexport function createForm<S extends FormSchema>(\n schema: S,\n options?: FormOptions<S>,\n internalOptions?: { onValidatorError?: (err: unknown) => void },\n): Form<S> {\n return new FormImpl(schema, options, internalOptions)\n}\n\nexport function createFieldArray<I extends Field<any> | Form<any>>(\n itemFactory: (initial?: ItemInitial<I>) => I,\n options?: FieldArrayOptions<I>,\n internalOptions?: { onValidatorError?: (err: unknown) => void },\n): FieldArray<I> {\n return new FieldArrayImpl<I>(itemFactory, options, internalOptions)\n}\n\n/**\n * Recursively wire every leaf `Field` in a form / field-array tree to a\n * devtools emitter. Returns a single disposer that tears down every standalone\n * `effect()` registered along the way (used for FieldArray watching), so the\n * caller — `ctx.form` / `ctx.fieldArray` in the controller — can register one\n * cleanup entry and have the whole subtree's reactive work die with the\n * controller. Spec §20.9.\n */\nexport function bindTreeToDevtools(\n node: Field<unknown> | Form<FormSchema> | FieldArray<Field<unknown> | Form<FormSchema>>,\n prefix: string,\n controllerPath: readonly string[],\n emitter: import('../devtools').DevtoolsEmitter,\n): () => void {\n const disposers: Array<() => void> = []\n bindTreeToDevtoolsInto(node, prefix, controllerPath, emitter, disposers)\n return () => {\n for (const d of disposers) {\n try {\n d()\n } catch {\n // Disposer failures must not break sibling cleanup.\n }\n }\n disposers.length = 0\n }\n}\n\nfunction bindTreeToDevtoolsInto(\n node: Field<unknown> | Form<FormSchema> | FieldArray<Field<unknown> | Form<FormSchema>>,\n prefix: string,\n controllerPath: readonly string[],\n emitter: import('../devtools').DevtoolsEmitter,\n disposers: Array<() => void>,\n): void {\n if (isForm(node)) {\n for (const [key, child] of Object.entries(node.fields)) {\n bindTreeToDevtoolsInto(\n child,\n prefix === '' ? key : `${prefix}.${key}`,\n controllerPath,\n emitter,\n disposers,\n )\n }\n return\n }\n if (isFieldArray(node)) {\n // Re-bind on every items change so dynamically-added entries get tracked.\n // Each re-bind has its own disposer set scoped to that pass; on the next\n // items change we flush the previous pass's disposers BEFORE creating the\n // new effects, so a churning array doesn't accumulate reactive work.\n // (Pre-fix, every items mutation appended fresh effects to the outer\n // `disposers` array and never released the old ones.)\n const arr = node as FieldArray<Field<unknown> | Form<FormSchema>>\n let perPass: Array<() => void> = []\n const stop = effect(() => {\n const items = arr.items.value\n // Flush previous pass before rebinding the new item set.\n for (const d of perPass) {\n try {\n d()\n } catch {\n // Disposer failures must not break sibling cleanup.\n }\n }\n perPass = []\n items.forEach((item, idx) => {\n bindTreeToDevtoolsInto(item, `${prefix}[${idx}]`, controllerPath, emitter, perPass)\n })\n })\n disposers.push(stop)\n // On final dispose, drain the per-pass disposers too.\n disposers.push(() => {\n for (const d of perPass) {\n try {\n d()\n } catch {\n // Ignore.\n }\n }\n perPass = []\n })\n return\n }\n // Leaf Field.\n bindFieldDevtoolsOwner(node as Field<unknown>, {\n controllerPath,\n fieldName: prefix,\n emitter,\n })\n}\n\n/**\n * Walk a Form/FieldArray subtree and install `reporter` on every level —\n * leaf fields, nested forms' top-level validators, and field-arrays' top-level\n * validators. Called by `ctx.form` / `ctx.fieldArray` so synchronous validator\n * throws anywhere in the tree route through `root.onError`. See\n * `ValidatorErrorReporter` in `./field.ts`.\n */\nexport function bindTreeValidatorErrorReporter(\n node: Field<unknown> | Form<FormSchema> | FieldArray<Field<unknown> | Form<FormSchema>>,\n reporter: ValidatorErrorReporter | null,\n): void {\n if (isForm(node)) {\n const impl = node as { bindValidatorErrorReporter?: (r: ValidatorErrorReporter | null) => void }\n impl.bindValidatorErrorReporter?.(reporter)\n for (const child of Object.values(node.fields)) {\n bindTreeValidatorErrorReporter(child, reporter)\n }\n return\n }\n if (isFieldArray(node)) {\n const impl = node as { bindValidatorErrorReporter?: (r: ValidatorErrorReporter | null) => void }\n impl.bindValidatorErrorReporter?.(reporter)\n // Items currently in the array. (Items added later won't get the reporter\n // unless `ctx.fieldArray` is wrapped to rebind — but the leaf items in the\n // typical pattern come from a user factory that constructs through\n // `createField` and is bound here by the parent traversal.)\n for (const item of node.items.value) {\n bindTreeValidatorErrorReporter(item, reporter)\n }\n return\n }\n bindFieldValidatorErrorReporter(node as Field<unknown>, reporter)\n}\n\n// Quiet unused-import linter without exporting these symbols publicly.\nvoid createField\nvoid untracked\nvoid isField\n","import { effect, untracked } from '../signals'\nimport type { ReadSignal } from '../signals/types'\nimport { Entry } from './entry'\nimport type { LocalCache, Snapshot } from './types'\n\nexport type LocalCacheOptions<T> = {\n key?: () => readonly unknown[]\n staleTime?: number\n keepPreviousData?: boolean\n initialData?: T | undefined\n}\n\nclass LocalCacheImpl<T> implements LocalCache<T> {\n private readonly entry: Entry<T>\n private keyEffectDispose: (() => void) | null = null\n private disposed = false\n private readonly keepPreviousData: boolean\n private lastSucceededFor: unknown[] | null = null\n\n constructor(fetcher: (signal: AbortSignal) => Promise<T>, options: LocalCacheOptions<T>) {\n this.keepPreviousData = options.keepPreviousData ?? false\n this.entry = new Entry<T>({\n fetcher: () => fetcher,\n staleTime: options.staleTime ?? 0,\n initialData: options.initialData,\n })\n\n if (options.key) {\n const keyFn = options.key\n this.keyEffectDispose = effect(() => {\n // Track keys.\n const keyArgs = keyFn() as unknown[]\n untracked(() => {\n if (!this.keepPreviousData) {\n // Reset data on key change so consumers see \"loading\" rather than\n // the previous key's stale value.\n if (this.lastSucceededFor != null && !arraysEqual(this.lastSucceededFor, keyArgs)) {\n this.entry.data.set(undefined)\n }\n }\n this.entry.startFetch().then(\n () => {\n this.lastSucceededFor = [...keyArgs]\n },\n () => {\n /* error already captured on entry */\n },\n )\n })\n })\n } else {\n this.entry.startFetch().catch(() => {\n /* error already captured on entry */\n })\n }\n }\n\n get data(): ReadSignal<T | undefined> {\n return this.entry.data\n }\n get error(): ReadSignal<unknown | undefined> {\n return this.entry.error\n }\n get status(): ReadSignal<'idle' | 'pending' | 'success' | 'error'> {\n return this.entry.status\n }\n get isLoading(): ReadSignal<boolean> {\n return this.entry.isLoading\n }\n get isFetching(): ReadSignal<boolean> {\n return this.entry.isFetching\n }\n get isStale(): ReadSignal<boolean> {\n return this.entry.isStale\n }\n get lastUpdatedAt(): ReadSignal<number | undefined> {\n return this.entry.lastUpdatedAt\n }\n get hasPendingMutations(): ReadSignal<boolean> {\n return this.entry.hasPendingMutations\n }\n get isPaused(): ReadSignal<boolean> {\n return this.entry.isPaused\n }\n\n refetch = (): Promise<T> => this.entry.refetch()\n reset = (): void => this.entry.reset()\n firstValue = (): Promise<T> => this.entry.firstValue()\n promise = (): Promise<T> => this.entry.firstValue()\n invalidate = (): void => {\n this.entry.invalidate().catch(() => {})\n }\n setData = (updater: (prev: T | undefined) => T): Snapshot => this.entry.setData(updater)\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.keyEffectDispose?.()\n this.keyEffectDispose = null\n this.entry.dispose()\n }\n}\n\nexport function createLocalCache<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n options?: LocalCacheOptions<T>,\n): LocalCache<T> {\n return new LocalCacheImpl(fetcher, options ?? {})\n}\n\nfunction arraysEqual(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) {\n if (!Object.is(a[i], b[i])) return false\n }\n return true\n}\n","import type { DevtoolsEmitter } from '../devtools'\nimport { dispatchError, type ErrorHandler } from '../errors'\nimport { batch, type Signal, signal } from '../signals'\nimport type { ReadSignal } from '../signals/types'\nimport { abortableSleep, isAbortError } from '../utils'\nimport { registerMutationById } from './plugin'\nimport type { AsyncStatus, RetryDelay, RetryPolicy, Snapshot } from './types'\n\n/**\n * How concurrent calls to `mutation.run(...)` interact:\n * - `parallel` (default): every call runs concurrently.\n * - `latest-wins`: a new call aborts any in-flight previous call (`AbortSignal` fires).\n * - `serial`: calls queue and run one at a time in order.\n *\n * Spec §6.3.\n */\nexport type MutationConcurrency = 'parallel' | 'latest-wins' | 'serial'\n\n/**\n * The configuration object passed to `ctx.mutation(spec)`. See spec §20.5 for\n * the full lifecycle semantics. `onMutate` may return a `Snapshot` (from\n * `query.setData(...)`) to enable automatic rollback on error.\n */\nexport type MutationSpec<V, R> = {\n /**\n * A short human-readable name. Surfaces in the devtools mutation log so the\n * user sees `moveCard` instead of just the controller path. Strongly\n * recommended in app code; cosmetic only — no runtime semantics depend on it.\n */\n name?: string\n /** The actual write. Receives the user-supplied vars and an `AbortSignal`. */\n mutate: (vars: V, signal: AbortSignal) => Promise<R>\n /**\n * Runs before `mutate`. Return a `Snapshot` from `query.setData(...)` to\n * apply an optimistic update; the snapshot is rolled back on error.\n */\n onMutate?: (vars: V) => Snapshot | void\n onSuccess?: (result: R, vars: V) => void\n onError?: (err: unknown, vars: V, snapshot: Snapshot | undefined) => void\n onSettled?: (result: R | undefined, err: unknown | undefined, vars: V) => void\n concurrency?: MutationConcurrency\n retry?: RetryPolicy\n retryDelay?: RetryDelay\n /**\n * Stable identifier used by the mutation-queue plugin\n * (`@kontsedal/olas-mutation-queue`) to route persistable runs across a\n * page reload. REQUIRED when `persist: true`. Recommended even without\n * `persist` if you want devtools to group runs across mutation instances\n * — same shape as `defineQuery({ queryId })`.\n *\n * Don't auto-derive from `name` or function identity; both are fragile\n * under minification.\n */\n mutationId?: string\n /**\n * Opt this mutation into durable persistence. When `true`, the runner\n * emits `onMutationEnqueue` to plugins before the user's `mutate` runs\n * and `onMutationSettle` after retries exhaust. Requires `mutationId`.\n * SPEC §13.3.\n */\n persist?: boolean\n}\n\n/**\n * Module-scope handle for a persistable mutation. Returned by\n * `defineMutation(...)`. Pass it to `ctx.mutation(...)` (spread or as-is)\n * so per-controller lifecycle hooks (`onSuccess` / `onError` / ...) can be\n * layered on top.\n *\n * Registering at module import time means the mutation-queue plugin can\n * replay pending runs from durable storage during `init` — before any\n * controller reconstructs.\n */\nexport type MutationDef<V, R> = MutationSpec<V, R> & {\n readonly __olas: 'mutation'\n readonly mutationId: string\n}\n\n/**\n * Register a persistable mutation at module scope. Returns the spec\n * unchanged (with a `__olas: 'mutation'` brand) so consumers can pass it\n * to `ctx.mutation(...)`, optionally spreading per-controller hooks on\n * top:\n *\n * ```ts\n * // module-scope\n * export const createOrder = defineMutation({\n * mutationId: 'order/create',\n * mutate: async (vars: OrderInput, { signal }) => api.createOrder(vars, { signal }),\n * })\n *\n * // controller\n * const m = ctx.mutation({\n * ...createOrder,\n * onSuccess: () => toast('Order placed'),\n * })\n * ```\n *\n * The `mutate` function MUST NOT close over controller-instance state — on\n * replay there is no controller. Module-level dependencies (a shared `api`\n * client, etc.) are fine.\n */\nexport function defineMutation<V, R>(\n spec: MutationSpec<V, R> & { mutationId: string; persist?: boolean },\n): MutationDef<V, R> {\n if (typeof spec.mutationId !== 'string' || spec.mutationId.length === 0) {\n throw new Error('[olas] defineMutation requires a non-empty `mutationId`.')\n }\n // Default `persist: true` for defined mutations — that's the whole point\n // of using the module-scope helper. Consumers who want a non-persistable\n // module-scope handle can override with `persist: false`.\n const persistSpec: MutationSpec<V, R> = { ...spec, persist: spec.persist ?? true }\n registerMutationById(spec.mutationId, {\n mutationId: spec.mutationId,\n mutate: spec.mutate as (vars: unknown, signal: AbortSignal) => Promise<unknown>,\n })\n return Object.assign(persistSpec, {\n __olas: 'mutation' as const,\n mutationId: spec.mutationId,\n })\n}\n\n/**\n * A running mutation. Created via `ctx.mutation(spec)` — the controller owns\n * its lifetime. Each `run(vars)` returns a Promise; the four signals reflect\n * the last-resolved run for UI binding.\n *\n * Spec §6, §20.5.\n */\n/**\n * Call signature for `mutation.run`:\n * - When `V` is `void` → no args. (`mutation.run()`)\n * - When `V` was not constrained (default-inferred as `unknown`) → optional\n * arg. Lets `ctx.mutation({ mutate: async () => 1 })` call `run()` *or*\n * `run(anything)` without a type error.\n * - Otherwise → arg required. (`mutation.run(vars)`)\n *\n * Defined as a variadic-tuple conditional so consumers see the right shape\n * without writing `run(undefined as unknown as void)`.\n */\nexport type MutationRun<V, R> = (\n ...args: unknown extends V ? [V?] : [V] extends [void] ? [] : [V]\n) => Promise<R>\n\nexport type Mutation<V, R> = {\n /** Trigger a run. Returns a Promise that resolves with the mutate result. */\n run: MutationRun<V, R>\n data: ReadSignal<R | undefined>\n error: ReadSignal<unknown | undefined>\n isPending: ReadSignal<boolean>\n /**\n * Outcome of the latest run: `'idle'` (never run / reset), `'pending'`\n * (in flight), `'success'`, `'error'`. Distinct from `isPending` (which\n * stays true while ANY run is in flight, for parallel mode) and from `data`\n * — a `void` mutation still reports `status: 'success'` after it resolves.\n * A superseded `latest-wins` run does NOT flip status to `'error'`; the\n * superseder owns the final status.\n */\n status: ReadSignal<AsyncStatus>\n lastVariables: ReadSignal<V | undefined>\n /** Clear `data` / `error` / `lastVariables` / `status` without aborting in-flight runs. */\n reset(): void\n /** Abort in-flight runs and tear down. Idempotent. Called by the parent controller's dispose. */\n dispose(): void\n}\n\ntype RunHandle = {\n abort: AbortController\n snapshot: Snapshot | undefined\n}\n\ntype SerialEntry<V, R> = {\n vars: V\n resolve: (value: R) => void\n reject: (err: unknown) => void\n}\n\n/**\n * Hooks for emitting persistable-mutation lifecycle events back to the\n * `QueryClient`. Wired from `createMutation` when `spec.persist === true`.\n * Internal — not part of any public surface.\n */\nexport type MutationLifecycleHooks = {\n emitEnqueue(event: {\n mutationId: string\n runId: string\n variables: unknown\n attempt: number\n }): void\n emitSettle(event: {\n mutationId: string\n runId: string\n outcome: 'success' | 'error' | 'cancelled'\n error?: unknown\n }): void\n}\n\nclass MutationImpl<V, R> implements Mutation<V, R> {\n readonly data: Signal<R | undefined> = signal(undefined)\n readonly error: Signal<unknown | undefined> = signal(undefined)\n readonly isPending: Signal<boolean> = signal(false)\n readonly status: Signal<AsyncStatus> = signal<AsyncStatus>('idle')\n readonly lastVariables: Signal<V | undefined> = signal(undefined)\n\n private inflight = new Set<RunHandle>()\n private serialQueue: Array<SerialEntry<V, R>> = []\n private serialActive = false\n private disposed = false\n\n constructor(\n private readonly spec: MutationSpec<V, R>,\n private readonly onError: ErrorHandler | undefined,\n private readonly controllerPath: readonly string[],\n private readonly inflightCounter?: {\n update(fn: (n: number) => number): void\n },\n private readonly devtools?: DevtoolsEmitter,\n private readonly lifecycle?: MutationLifecycleHooks,\n ) {}\n\n /**\n * True iff this mutation should emit persistable-lifecycle events.\n * Validated at construction time (in `createMutation`) so any malformed\n * `persist: true`-without-`mutationId` config surfaces early.\n */\n private get isPersistable(): boolean {\n return this.spec.persist === true && this.lifecycle !== undefined\n }\n\n private emit(event: { type: 'mutation:run'; vars: unknown }): void\n private emit(event: { type: 'mutation:success'; result: unknown }): void\n private emit(event: { type: 'mutation:error'; error: unknown }): void\n private emit(event: { type: 'mutation:rollback' }): void\n private emit(\n event:\n | { type: 'mutation:run'; vars: unknown }\n | { type: 'mutation:success'; result: unknown }\n | { type: 'mutation:error'; error: unknown }\n | { type: 'mutation:rollback' },\n ): void {\n if (!__DEV__) return\n if (this.devtools === undefined) return\n const out: Record<string, unknown> = { ...event, path: this.controllerPath }\n if (this.spec.name !== undefined) out.name = this.spec.name\n this.devtools.emit(out as Parameters<DevtoolsEmitter['emit']>[0])\n }\n\n // Implementation-side signature accepts an optional `vars` (defaults to\n // `undefined`) so call sites for `Mutation<void, R>` can call `.run()` with\n // no args. The public type forces the right shape per `V`.\n run = ((vars: V = undefined as V): Promise<R> => {\n if (this.disposed) {\n return Promise.reject(new Error('Mutation disposed'))\n }\n const mode = this.spec.concurrency ?? 'parallel'\n switch (mode) {\n case 'parallel':\n return this.executeRun(vars)\n case 'latest-wins':\n // Spec §6.1: rollback the superseded run's snapshot BEFORE the new\n // run's onMutate runs, so the new optimistic update doesn't stack on\n // top of the obsolete one.\n for (const handle of this.inflight) {\n handle.abort.abort()\n handle.snapshot?.rollback()\n handle.snapshot = undefined\n }\n return this.executeRun(vars)\n case 'serial':\n return this.enqueueSerial(vars)\n }\n }) as MutationRun<V, R>\n\n private enqueueSerial(vars: V): Promise<R> {\n if (this.serialActive) {\n return new Promise<R>((resolve, reject) => {\n this.serialQueue.push({ vars, resolve, reject })\n })\n }\n this.serialActive = true\n return this.executeRun(vars).finally(() => this.advanceSerialQueue())\n }\n\n private advanceSerialQueue(): void {\n const next = this.serialQueue.shift()\n if (!next) {\n this.serialActive = false\n return\n }\n this.executeRun(next.vars).then(\n (result) => {\n next.resolve(result)\n this.advanceSerialQueue()\n },\n (err) => {\n next.reject(err)\n this.advanceSerialQueue()\n },\n )\n }\n\n private async executeRun(vars: V): Promise<R> {\n const abort = new AbortController()\n let snapshot: Snapshot | undefined\n try {\n const raw = this.spec.onMutate?.(vars) ?? undefined\n snapshot = raw === undefined ? undefined : this.wrapSnapshot(raw)\n } catch (err) {\n // onMutate threw — the optimistic setup failed, so running `mutate`\n // against a half-applied state is unsafe. Abort the whole run: surface\n // via the error signal, the mutation's onError/onSettled, and the\n // rejected run promise (mirrors the mutate-failure path). No snapshot\n // exists yet, so nothing to roll back; `mutate` is never called. T3.9.\n this.error.set(err)\n this.status.set('error')\n if (__DEV__) this.emit({ type: 'mutation:error', error: err })\n this.safeCall(() => this.spec.onError?.(err, vars, undefined), 'mutation')\n this.safeCall(() => this.spec.onSettled?.(undefined, err, vars), 'mutation')\n throw err\n }\n\n const handle: RunHandle = { abort, snapshot }\n this.inflight.add(handle)\n this.inflightCounter?.update((n) => n + 1)\n batch(() => {\n this.isPending.set(true)\n this.status.set('pending')\n this.lastVariables.set(vars)\n })\n\n if (__DEV__) this.emit({ type: 'mutation:run', vars })\n\n // Persistable mutations emit an enqueue event BEFORE the user's `mutate`\n // runs. If the page reloads mid-mutation, the queue plugin replays from\n // this entry. `runId` is unique per `executeRun` invocation; retries\n // within `runWithRetry` reuse it via `attempt` bumps inside that loop.\n const runId = this.isPersistable ? makeRunId() : ''\n const mutationId = this.spec.mutationId\n if (this.isPersistable && mutationId !== undefined) {\n try {\n this.lifecycle?.emitEnqueue({ mutationId, runId, variables: vars, attempt: 0 })\n } catch (err) {\n dispatchError(this.onError, err, {\n kind: 'plugin',\n controllerPath: this.controllerPath,\n })\n }\n }\n\n try {\n const result = await raceAbort(this.runWithRetry(vars, abort.signal), abort.signal)\n if (abort.signal.aborted || this.disposed) {\n snapshot?.rollback()\n if (this.isPersistable && mutationId !== undefined) {\n this.safeEmitSettle({ mutationId, runId, outcome: 'cancelled' })\n }\n throw new DOMException('Superseded', 'AbortError')\n }\n batch(() => {\n this.data.set(result)\n this.error.set(undefined)\n this.status.set('success')\n })\n if (__DEV__) this.emit({ type: 'mutation:success', result })\n this.safeCall(() => this.spec.onSuccess?.(result, vars), 'mutation')\n // Commit the optimistic snapshot so `hasPendingMutations` clears on the\n // affected entry. Symmetric to the auto-rollback in the error path.\n // Spec §6.4.\n snapshot?.finalize()\n this.safeCall(() => this.spec.onSettled?.(result, undefined, vars), 'mutation')\n if (this.isPersistable && mutationId !== undefined) {\n this.safeEmitSettle({ mutationId, runId, outcome: 'success' })\n }\n return result\n } catch (err) {\n if (isAbortError(err) || abort.signal.aborted) {\n snapshot?.rollback()\n if (this.isPersistable && mutationId !== undefined) {\n this.safeEmitSettle({ mutationId, runId, outcome: 'cancelled' })\n }\n // Reserve `error` signal for genuine failures.\n throw err\n }\n this.error.set(err)\n this.status.set('error')\n if (__DEV__) this.emit({ type: 'mutation:error', error: err })\n this.safeCall(() => this.spec.onError?.(err, vars, snapshot), 'mutation')\n // Auto-rollback after the user's onError. The wrapped snapshot is\n // single-consume, so an `onError` that already called `snapshot.rollback()`\n // turns the auto-call into a no-op. Spec §6.4.\n snapshot?.rollback()\n this.safeCall(() => this.spec.onSettled?.(undefined, err, vars), 'mutation')\n if (this.isPersistable && mutationId !== undefined) {\n this.safeEmitSettle({ mutationId, runId, outcome: 'error', error: err })\n }\n throw err\n } finally {\n this.inflight.delete(handle)\n this.inflightCounter?.update((n) => Math.max(0, n - 1))\n if (this.inflight.size === 0) {\n this.isPending.set(false)\n }\n }\n }\n\n private safeEmitSettle(event: {\n mutationId: string\n runId: string\n outcome: 'success' | 'error' | 'cancelled'\n error?: unknown\n }): void {\n try {\n this.lifecycle?.emitSettle(event)\n } catch (err) {\n dispatchError(this.onError, err, {\n kind: 'plugin',\n controllerPath: this.controllerPath,\n })\n }\n }\n\n // Wrap so any rollback / finalize path runs the raw operation at most\n // once. The mutation auto-finalizes on success and auto-rolls-back on\n // error; user code may also call rollback() from onError. Whichever\n // happens first wins; subsequent calls (including the auto-call) no-op.\n private wrapSnapshot(raw: Snapshot): Snapshot {\n let consumed = false\n return {\n rollback: () => {\n if (consumed) return\n consumed = true\n raw.rollback()\n if (__DEV__) this.emit({ type: 'mutation:rollback' })\n },\n finalize: () => {\n if (consumed) return\n consumed = true\n raw.finalize()\n },\n }\n }\n\n private async runWithRetry(vars: V, signal: AbortSignal): Promise<R> {\n const retry = this.spec.retry ?? 0\n const retryDelay = this.spec.retryDelay ?? 1000\n let attempt = 0\n while (true) {\n try {\n return await this.spec.mutate(vars, signal)\n } catch (err) {\n if (signal.aborted || isAbortError(err)) throw err\n const shouldRetry = typeof retry === 'number' ? attempt < retry : retry(attempt, err)\n if (!shouldRetry) throw err\n const delay = typeof retryDelay === 'function' ? retryDelay(attempt) : retryDelay\n await abortableSleep(delay, signal)\n attempt += 1\n }\n }\n }\n\n private safeCall(fn: () => void, kind: 'mutation'): void {\n try {\n fn()\n } catch (err) {\n dispatchError(this.onError, err, {\n kind,\n controllerPath: this.controllerPath,\n })\n }\n }\n\n reset(): void {\n if (this.disposed) return\n for (const handle of this.inflight) handle.abort.abort()\n // Reject queued serial runs so their awaiters don't hang — symmetric with\n // `dispose()`. Without this, callers of `mutation.run(...)` on a serial\n // mutation that get reset mid-queue wait forever.\n if (this.serialQueue.length > 0) {\n const aborted = new DOMException('Aborted', 'AbortError')\n const queue = this.serialQueue\n this.serialQueue = []\n for (const queued of queue) queued.reject(aborted)\n }\n this.serialActive = false\n batch(() => {\n this.data.set(undefined)\n this.error.set(undefined)\n this.lastVariables.set(undefined)\n this.isPending.set(false)\n this.status.set('idle')\n })\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n for (const handle of this.inflight) handle.abort.abort()\n for (const queued of this.serialQueue) {\n queued.reject(new DOMException('Disposed', 'AbortError'))\n }\n this.serialQueue.length = 0\n }\n}\n\nexport function createMutation<V, R>(\n spec: MutationSpec<V, R>,\n onError: ErrorHandler | undefined,\n controllerPath: readonly string[],\n inflightCounter?: { update(fn: (n: number) => number): void },\n devtools?: DevtoolsEmitter,\n lifecycle?: MutationLifecycleHooks,\n): Mutation<V, R> {\n // Validate persistable-mutation config at construction time so misconfig\n // surfaces synchronously rather than on first `run()`.\n if (spec.persist === true) {\n if (typeof spec.mutationId !== 'string' || spec.mutationId.length === 0) {\n throw new Error(\n '[olas] ctx.mutation({ persist: true, ... }) requires a non-empty `mutationId`.',\n )\n }\n }\n return new MutationImpl<V, R>(spec, onError, controllerPath, inflightCounter, devtools, lifecycle)\n}\n\n/**\n * Generate a unique-enough run id for the persistable-mutation lifecycle.\n * Uses `crypto.randomUUID` where available (Node 19+, modern browsers),\n * with a timestamp+random fallback for older runtimes. Collisions only\n * affect dedup at the plugin layer, not correctness, so the fallback's\n * weakness is acceptable.\n */\nfunction makeRunId(): string {\n const g = globalThis as { crypto?: { randomUUID?: () => string } }\n if (typeof g.crypto?.randomUUID === 'function') return g.crypto.randomUUID()\n const rand = Math.random().toString(36).slice(2, 12)\n return `${Date.now().toString(36)}-${rand}`\n}\n\n/**\n * Race a promise against an AbortSignal. If the signal fires before the\n * promise settles, the returned promise rejects with AbortError — regardless\n * of whether the underlying promise ever resolves. Protects against\n * misbehaving mutate fns that ignore their signal.\n */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(new DOMException('Aborted', 'AbortError'))\n }\n return new Promise<T>((resolve, reject) => {\n let settled = false\n const onAbort = () => {\n if (settled) return\n settled = true\n reject(new DOMException('Aborted', 'AbortError'))\n }\n signal.addEventListener('abort', onAbort, { once: true })\n promise.then(\n (v) => {\n if (settled) return\n settled = true\n signal.removeEventListener('abort', onAbort)\n resolve(v)\n },\n (e) => {\n if (settled) return\n settled = true\n signal.removeEventListener('abort', onAbort)\n reject(e)\n },\n )\n })\n}\n","import { computed, effect, type Signal, signal, untracked } from '../signals'\nimport type { ReadSignal } from '../signals/types'\nimport { isAbortError } from '../utils'\nimport type { ClientEntry, InfiniteClientEntry, QueryClient } from './client'\nimport type { InfiniteQuery, InfiniteQuerySpec, InfiniteQuerySubscription } from './infinite'\nimport type {\n AsyncStatus,\n Query,\n QuerySpec,\n QuerySubscription,\n UseInternalOptions,\n UseOptions,\n} from './types'\n\ntype QueryInternal<Args extends unknown[], T> = Query<Args, T> & {\n readonly __spec: QuerySpec<Args, T>\n}\n\nclass SubscriptionImpl<T, U = T> implements QuerySubscription<U> {\n private readonly current$: Signal<ClientEntry<T> | null> = signal(null)\n private readonly previousData$: Signal<T | undefined> = signal(undefined)\n\n readonly data: ReadSignal<U | undefined>\n readonly error: ReadSignal<unknown | undefined>\n readonly status: ReadSignal<AsyncStatus>\n readonly isLoading: ReadSignal<boolean>\n readonly isFetching: ReadSignal<boolean>\n readonly isStale: ReadSignal<boolean>\n readonly lastUpdatedAt: ReadSignal<number | undefined>\n readonly hasPendingMutations: ReadSignal<boolean>\n readonly isPaused: ReadSignal<boolean>\n\n constructor(\n private readonly keepPreviousData: boolean,\n private readonly select?: (data: T) => U,\n ) {\n // The underlying entry stores `T`. The subscription's `data` is `U`\n // (or `T` when no projection). We compute the raw `T` once, then layer\n // `select` in a second computed so the projection's `Object.is` dedup\n // applies BEFORE downstream subscribers run — combined with structural\n // sharing on the entry, an unchanged payload + a stable `select`\n // outputs the same `U` reference and doesn't churn the React tree.\n const rawData = computed(() => {\n const cur = this.current$.value\n const curData = cur?.entry.data.value\n if (curData !== undefined) return curData\n if (keepPreviousData) return this.previousData$.value\n return undefined\n })\n this.data =\n select === undefined\n ? (rawData as unknown as ReadSignal<U | undefined>)\n : computed<U | undefined>(() => {\n const raw = rawData.value\n return raw === undefined ? undefined : select(raw)\n })\n this.error = computed(() => this.current$.value?.entry.error.value)\n this.status = computed<AsyncStatus>(() => this.current$.value?.entry.status.value ?? 'idle')\n this.isLoading = computed(() => {\n const cur = this.current$.value\n if (!cur) return false\n if (keepPreviousData && this.previousData$.value !== undefined) return false\n return cur.entry.isLoading.value\n })\n this.isFetching = computed(() => this.current$.value?.entry.isFetching.value ?? false)\n this.isStale = computed(() => this.current$.value?.entry.isStale.value ?? true)\n this.lastUpdatedAt = computed(() => this.current$.value?.entry.lastUpdatedAt.value)\n this.hasPendingMutations = computed(\n () => this.current$.value?.entry.hasPendingMutations.value ?? false,\n )\n this.isPaused = computed(() => this.current$.value?.entry.isPaused.value ?? false)\n }\n\n attach(entry: ClientEntry<T>): void {\n const prev = this.current$.peek()\n if (prev === entry) return\n if (prev && this.keepPreviousData) {\n const prevData = prev.entry.data.peek()\n if (prevData !== undefined) this.previousData$.set(prevData)\n }\n this.current$.set(entry)\n }\n\n detach(): void {\n this.current$.set(null)\n }\n\n refetch = (): Promise<U> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.reject(new Error('[olas] no active subscription'))\n return cur.entry.refetch().then(\n (v) => this.project(v),\n (err) => {\n // A supersede (newer refetch / key change) aborts this fetch. Don't\n // surface the spurious AbortError — resolve with the superseding\n // fetch's eventual outcome instead (T3.9). Real errors still reject.\n if (isAbortError(err)) return this.firstValue()\n throw err\n },\n )\n }\n\n reset = (): void => {\n this.current$.peek()?.entry.reset()\n }\n\n cancel = (): void => {\n this.current$.peek()?.entry.cancel()\n }\n\n firstValue = (): Promise<U> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.reject(new Error('[olas] no active subscription'))\n return cur.entry.firstValue().then((v) => this.project(v))\n }\n\n // Alias surfaced on `AsyncState` for Suspense / React 19 `use(...)`.\n promise = (): Promise<U> => this.firstValue()\n\n private project(v: T): U {\n return this.select === undefined ? (v as unknown as U) : this.select(v)\n }\n}\n\n/**\n * Build a subscription + the effect that keeps it bound to the right entry.\n * The controller container wires the disposer into the lifecycle.\n *\n * `keyOrOptions` may carry an optional `select` projection that maps the\n * underlying `T` to a view `U`; the returned subscription's data shape\n * widens accordingly. Without `select`, `U = T` and the projection\n * computed is skipped.\n */\nexport function createUse<Args extends unknown[], T, U = T>(\n client: QueryClient,\n query: Query<Args, T>,\n keyOrOptions?: (() => Args) | UseInternalOptions<Args, T, U>,\n): {\n subscription: QuerySubscription<U>\n dispose: () => void\n /** Suspend the subscription — release the entry (its refetchInterval +\n * focus/online listeners pause) without disposing it. Spec §4.1. */\n suspend: () => void\n /** Resume after `suspend`. Re-acquires the entry and refetches if stale. */\n resume: () => void\n} {\n const internal = query as unknown as QueryInternal<Args, T>\n const spec = internal.__spec\n const keepPreviousData = spec.keepPreviousData ?? false\n\n const keyFn = typeof keyOrOptions === 'function' ? keyOrOptions : keyOrOptions?.key\n const enabledFn =\n typeof keyOrOptions === 'object' && keyOrOptions !== null ? keyOrOptions.enabled : undefined\n const select =\n typeof keyOrOptions === 'object' && keyOrOptions !== null ? keyOrOptions.select : undefined\n\n const sub = new SubscriptionImpl<T, U>(keepPreviousData, select)\n let currentEntry: ClientEntry<T> | null = null\n let suspended = false\n\n const effectDispose = effect(() => {\n // Read tracked signals (enabled, then key when enabled) BEFORE the\n // `suspended` early-return, so the effect keeps its dependency set while\n // suspended. Otherwise a key/enabled change during suspension re-runs the\n // effect, it reads nothing, its deps go empty, and it stays inert forever\n // — resume() then only rebinds to the key as of suspend time, silently\n // dropping every later change (T2.1). Key is read only when enabled,\n // preserving the `enabled`-guards-`key` pattern (the key thunk may deref\n // state that only exists once enabled).\n const isEnabled = enabledFn ? enabledFn() : true\n const args = isEnabled ? ((keyFn ? keyFn() : ([] as unknown as Args)) as Args) : undefined\n\n if (suspended) return\n\n if (!isEnabled) {\n untracked(() => {\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n sub.detach()\n })\n return\n }\n\n untracked(() => {\n const entry = client.bindEntry<Args, T>(query, args as Args)\n if (currentEntry === entry) return\n if (currentEntry) currentEntry.release()\n entry.acquire()\n currentEntry = entry\n sub.attach(entry)\n\n const status = entry.entry.status.peek()\n const fetching = entry.entry.isFetching.peek()\n if (!fetching && (status === 'idle' || entry.entry.isStaleNow() || status === 'error')) {\n entry.entry.startFetch().catch(() => {\n /* error captured on entry */\n })\n }\n })\n })\n\n const dispose = () => {\n effectDispose()\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n sub.detach()\n }\n\n const suspend = (): void => {\n if (suspended) return\n suspended = true\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n // Keep subscription detached so reads return the last committed values\n // via the entry's signals if still alive (the entry may be gc'd after\n // its gcTime; that's fine — resume re-binds).\n }\n\n const resume = (): void => {\n if (!suspended) return\n suspended = false\n // Re-evaluate the keyFn + enabled flag and rebind. The effect's deps\n // didn't change while suspended, so toggling `suspended` here doesn't\n // re-fire the effect on its own — force a sync rebind through the same\n // code path.\n const isEnabled = enabledFn ? enabledFn() : true\n if (!isEnabled) return\n const args = (keyFn ? keyFn() : ([] as unknown as Args)) as Args\n const entry = client.bindEntry<Args, T>(query, args)\n entry.acquire()\n currentEntry = entry\n sub.attach(entry)\n // On resume, refetch if stale (matches the spec §4.1 \"stale-on-resume\"\n // requirement). Non-stale data stays as-is.\n const status = entry.entry.status.peek()\n if (status === 'idle' || entry.entry.isStaleNow() || status === 'error') {\n entry.entry.startFetch().catch(() => {\n /* error captured on entry */\n })\n }\n }\n\n return { subscription: sub, dispose, suspend, resume }\n}\n\ntype InfiniteQueryInternal<Args extends unknown[], TPage, TItem> = InfiniteQuery<\n Args,\n TPage,\n TItem\n> & {\n readonly __spec: InfiniteQuerySpec<Args, any, TPage, TItem>\n}\n\nclass InfiniteSubscriptionImpl<TPage, TItem> implements InfiniteQuerySubscription<TPage, TItem> {\n private readonly current$: Signal<InfiniteClientEntry<TPage, TItem, unknown> | null> =\n signal(null)\n private readonly previousPages$: Signal<TPage[] | undefined> = signal(undefined)\n\n readonly data: ReadSignal<TPage[] | undefined>\n readonly pages: ReadSignal<TPage[]>\n readonly flat: ReadSignal<TItem[]>\n readonly error: ReadSignal<unknown | undefined>\n readonly status: ReadSignal<AsyncStatus>\n readonly isLoading: ReadSignal<boolean>\n readonly isFetching: ReadSignal<boolean>\n readonly isStale: ReadSignal<boolean>\n readonly lastUpdatedAt: ReadSignal<number | undefined>\n readonly hasPendingMutations: ReadSignal<boolean>\n readonly isPaused: ReadSignal<boolean>\n readonly hasNextPage: ReadSignal<boolean>\n readonly hasPreviousPage: ReadSignal<boolean>\n readonly isFetchingNextPage: ReadSignal<boolean>\n readonly isFetchingPreviousPage: ReadSignal<boolean>\n\n constructor(private readonly keepPreviousData: boolean) {\n this.pages = computed(() => {\n const cur = this.current$.value\n const ps = cur?.entry.pages.value\n if (ps && ps.length > 0) return ps\n if (keepPreviousData) return this.previousPages$.value ?? []\n return ps ?? []\n })\n this.data = computed(() => {\n const cur = this.current$.value\n const ps = cur?.entry.pages.value\n if (ps && ps.length > 0) return ps\n if (keepPreviousData) {\n const prev = this.previousPages$.value\n if (prev && prev.length > 0) return prev\n }\n return undefined\n })\n this.flat = computed(() => this.current$.value?.entry.flat.value ?? [])\n this.error = computed(() => this.current$.value?.entry.error.value)\n this.status = computed<AsyncStatus>(() => this.current$.value?.entry.status.value ?? 'idle')\n this.isLoading = computed(() => {\n const cur = this.current$.value\n if (!cur) return false\n if (keepPreviousData) {\n const prev = this.previousPages$.value\n if (prev && prev.length > 0) return false\n }\n return cur.entry.isLoading.value\n })\n this.isFetching = computed(() => this.current$.value?.entry.isFetching.value ?? false)\n this.isStale = computed(() => this.current$.value?.entry.isStale.value ?? true)\n this.lastUpdatedAt = computed(() => this.current$.value?.entry.lastUpdatedAt.value)\n this.hasPendingMutations = computed(\n () => this.current$.value?.entry.hasPendingMutations.value ?? false,\n )\n this.isPaused = computed(() => this.current$.value?.entry.isPaused.value ?? false)\n this.hasNextPage = computed(() => this.current$.value?.entry.hasNextPage.value ?? false)\n this.hasPreviousPage = computed(() => this.current$.value?.entry.hasPreviousPage.value ?? false)\n this.isFetchingNextPage = computed(\n () => this.current$.value?.entry.isFetchingNextPage.value ?? false,\n )\n this.isFetchingPreviousPage = computed(\n () => this.current$.value?.entry.isFetchingPreviousPage.value ?? false,\n )\n }\n\n attach(entry: InfiniteClientEntry<TPage, TItem, unknown>): void {\n const prev = this.current$.peek()\n if (prev === entry) return\n if (prev && this.keepPreviousData) {\n const prevPages = prev.entry.pages.peek()\n if (prevPages.length > 0) this.previousPages$.set(prevPages)\n }\n this.current$.set(entry)\n }\n\n detach(): void {\n this.current$.set(null)\n }\n\n refetch = (): Promise<TPage[]> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.reject(new Error('[olas] no active subscription'))\n return cur.entry.refetch().then(\n () => cur.entry.pages.peek(),\n (err) => {\n // Supersede → resolve with the superseder's outcome, not AbortError (T3.9).\n if (isAbortError(err)) return this.firstValue()\n throw err\n },\n )\n }\n\n reset = (): void => {\n this.current$.peek()?.entry.reset()\n }\n\n cancel = (): void => {\n this.current$.peek()?.entry.cancel()\n }\n\n firstValue = (): Promise<TPage[]> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.reject(new Error('[olas] no active subscription'))\n return cur.entry.firstValue()\n }\n\n // Alias of firstValue() for Suspense / React 19 `use(...)` ergonomics.\n promise = (): Promise<TPage[]> => this.firstValue()\n\n fetchNextPage = (): Promise<void> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.resolve()\n return cur.entry.fetchNextPage()\n }\n\n fetchPreviousPage = (): Promise<void> => {\n const cur = this.current$.peek()\n if (!cur) return Promise.resolve()\n return cur.entry.fetchPreviousPage()\n }\n}\n\nexport function createInfiniteUse<Args extends unknown[], TPage, TItem>(\n client: QueryClient,\n query: InfiniteQuery<Args, TPage, TItem>,\n keyOrOptions?: (() => Args) | UseOptions<Args>,\n): {\n subscription: InfiniteQuerySubscription<TPage, TItem>\n dispose: () => void\n suspend: () => void\n resume: () => void\n} {\n const spec = (query as unknown as InfiniteQueryInternal<Args, TPage, TItem>).__spec\n const keepPreviousData = spec.keepPreviousData ?? false\n const keyFn = typeof keyOrOptions === 'function' ? keyOrOptions : keyOrOptions?.key\n const enabledFn =\n typeof keyOrOptions === 'object' && keyOrOptions !== null ? keyOrOptions.enabled : undefined\n\n const sub = new InfiniteSubscriptionImpl<TPage, TItem>(keepPreviousData)\n let currentEntry: InfiniteClientEntry<TPage, TItem, unknown> | null = null\n let suspended = false\n\n const effectDispose = effect(() => {\n // See the regular-query variant above: read enabled + key (when enabled)\n // BEFORE the `suspended` early-return so the effect keeps its deps through\n // suspension; otherwise a key change during suspend empties them and the\n // subscription goes inert after resume (T2.1).\n const isEnabled = enabledFn ? enabledFn() : true\n const args = isEnabled ? ((keyFn ? keyFn() : ([] as unknown as Args)) as Args) : undefined\n\n if (suspended) return\n\n if (!isEnabled) {\n untracked(() => {\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n sub.detach()\n })\n return\n }\n\n untracked(() => {\n const entry = client.bindInfiniteEntry<Args, TPage, TItem>(query, args as Args)\n if (currentEntry === entry) return\n if (currentEntry) currentEntry.release()\n entry.acquire()\n currentEntry = entry\n sub.attach(entry)\n\n const status = entry.entry.status.peek()\n const fetching = entry.entry.isFetching.peek()\n if (!fetching && (status === 'idle' || entry.entry.isStaleNow() || status === 'error')) {\n entry.entry.startFetch().catch(() => {\n /* error captured on entry */\n })\n }\n })\n })\n\n const dispose = () => {\n effectDispose()\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n sub.detach()\n }\n\n const suspend = (): void => {\n if (suspended) return\n suspended = true\n if (currentEntry) {\n currentEntry.release()\n currentEntry = null\n }\n }\n\n const resume = (): void => {\n if (!suspended) return\n suspended = false\n const isEnabled = enabledFn ? enabledFn() : true\n if (!isEnabled) return\n const args = (keyFn ? keyFn() : ([] as unknown as Args)) as Args\n const entry = client.bindInfiniteEntry<Args, TPage, TItem>(query, args)\n entry.acquire()\n currentEntry = entry\n sub.attach(entry)\n const status = entry.entry.status.peek()\n if (status === 'idle' || entry.entry.isStaleNow() || status === 'error') {\n entry.entry.startFetch().catch(() => {\n /* error captured on entry */\n })\n }\n }\n\n return { subscription: sub, dispose, suspend, resume }\n}\n","import type { DevtoolsEmitter } from '../devtools'\nimport { createEmitter, type Emitter } from '../emitter'\nimport { dispatchError, type ErrorHandler } from '../errors'\nimport { bindFieldDevtoolsOwner, createField } from '../forms/field'\nimport {\n bindTreeToDevtools,\n bindTreeValidatorErrorReporter,\n createFieldArray,\n createForm,\n} from '../forms/form'\nimport type {\n FieldArray,\n FieldArrayOptions,\n Form,\n FormOptions,\n FormSchema,\n ItemInitial,\n} from '../forms/form-types'\nimport type { Validator } from '../forms/types'\nimport type { QueryClient } from '../query/client'\nimport type { InfiniteQuery } from '../query/infinite'\nimport { createLocalCache, type LocalCacheOptions } from '../query/local'\nimport { createMutation, type Mutation, type MutationSpec } from '../query/mutation'\nimport type { LocalCache, Query } from '../query/types'\nimport { createInfiniteUse, createUse } from '../query/use'\nimport type { Scope } from '../scope'\nimport { computed, signal, effect as standaloneEffect, untracked } from '../signals'\nimport { readOnly } from '../signals/readonly'\nimport { getFactory, getName } from './define'\nimport type {\n Collection,\n CollectionFactoryApi,\n CollectionFactoryOptions,\n CollectionFactoryResult,\n CollectionHomogeneousOptions,\n ControllerDef,\n Ctx,\n Field,\n LazyChild,\n} from './types'\n\nexport type RootShared = {\n readonly devtools: DevtoolsEmitter\n readonly onError: ErrorHandler | undefined\n readonly queryClient: QueryClient\n /**\n * Monotonic counter bumped by every `ctx.provide(...)` call inside this\n * root's tree. `ctx.inject(...)` caches its scope-walk result alongside\n * the version it was computed at; a mismatch forces a re-walk. Cheap\n * compared to the linear ancestor walk (most controllers never call\n * provide, so cache hits dominate).\n */\n readonly scopesVersion: { value: number }\n}\n\ntype LifecycleEntry =\n | {\n kind: 'effect'\n factory: () => void | (() => void)\n dispose: (() => void) | null\n }\n | { kind: 'cleanup'; dispose: () => void }\n | {\n /**\n * Cache subscription via `ctx.use`. Suspend/resume call the\n * `suspend`/`resume` hooks so the underlying entry's `refetchInterval`\n * and event listeners pause for the duration. Spec §4.1.\n */\n kind: 'subscription-cache'\n dispose: () => void\n suspend: () => void\n resume: () => void\n }\n | { kind: 'child'; instance: ControllerInstance; explicitlySuspended?: boolean }\n | { kind: 'onDispose'; fn: () => void }\n | { kind: 'onSuspend'; fn: () => void }\n | { kind: 'onResume'; fn: () => void }\n | { kind: 'subscription'; unsubscribe: () => void }\n\ntype State = 'constructing' | 'active' | 'suspended' | 'disposed'\n\n/**\n * Doubly-linked-list node wrapping a `LifecycleEntry`. Holding a reference\n * to the node lets call sites unlink in O(1) instead of the old\n * `entries.indexOf(...) + splice(...)` which was quadratic for long-lived\n * collections / lazyChildren / attach-style children.\n *\n * `unlinked: true` is a defensive flag — re-unlinking a node should be a\n * no-op (the parent's dispose cascade may race with an explicit unlink\n * from a `dispose()` returned to user code).\n */\ntype LifecycleNode = {\n entry: LifecycleEntry\n prev: LifecycleNode | null\n next: LifecycleNode | null\n unlinked: boolean\n}\n\n/**\n * Append-and-unlink container for `LifecycleEntry`s. Replaces the historical\n * `LifecycleEntry[]` to make per-entry removal O(1) — important for\n * controllers that churn entries (`ctx.collection` reconcile, `lazyChild`\n * loop, `attach` short-lived children).\n *\n * Iteration order is insertion order for `forward()` and reverse-insertion\n * for `reverse()`. Iteration is safe against `push` during traversal (the\n * generator captures `next`/`prev` *before* yielding) but not against\n * unlinking the current node from inside the visitor — visitors must not\n * call `unlink` on the entry they're currently inspecting.\n */\nclass LifecycleList {\n private head: LifecycleNode | null = null\n private tail: LifecycleNode | null = null\n private _size = 0\n\n get size(): number {\n return this._size\n }\n\n push(entry: LifecycleEntry): LifecycleNode {\n const node: LifecycleNode = { entry, prev: this.tail, next: null, unlinked: false }\n if (this.tail !== null) this.tail.next = node\n else this.head = node\n this.tail = node\n this._size += 1\n return node\n }\n\n unlink(node: LifecycleNode): void {\n if (node.unlinked) return\n node.unlinked = true\n if (node.prev !== null) node.prev.next = node.next\n else this.head = node.next\n if (node.next !== null) node.next.prev = node.prev\n else this.tail = node.prev\n this._size -= 1\n }\n\n clear(): void {\n this.head = null\n this.tail = null\n this._size = 0\n }\n\n /** Yield entries in insertion order. */\n *forward(): Generator<LifecycleEntry> {\n let n = this.head\n while (n !== null) {\n const next = n.next\n yield n.entry\n n = next\n }\n }\n\n /** Yield entries in reverse-insertion order — used by dispose / suspend. */\n *reverse(): Generator<LifecycleEntry> {\n let n = this.tail\n while (n !== null) {\n const prev = n.prev\n yield n.entry\n n = prev\n }\n }\n}\n\nexport class ControllerInstance {\n readonly path: readonly string[]\n readonly deps: Record<string, unknown>\n\n private state: State = 'constructing'\n private readonly entries: LifecycleList = new LifecycleList()\n private readonly rootShared: RootShared\n private readonly parent: ControllerInstance | null\n private childCounter = 0\n /** Scope values provided on this instance, keyed by `Scope.__id`. */\n private scopes: Map<symbol, unknown> | null = null\n /**\n * Memoized result of `ctx.inject(scope)` per scope id, stamped with the\n * `scopesVersion` the lookup observed. A bump invalidates every cache\n * entry implicitly — the next `inject(scope)` finds a stale version\n * stamp and re-walks. Provide is rare; reads dominate.\n */\n private injectCache: Map<symbol, { value: unknown; version: number }> | null = null\n\n /**\n * Pre-seed scopes from outside the factory — used by `createRoot`'s\n * `scopes:` option so an adapter (e.g. `@kontsedal/olas-router-tanstack`)\n * can publish cross-cutting values without forcing the user to call\n * `ctx.provide(...)` in their root controller. Idempotent per scope id:\n * later calls override.\n */\n seedScopes(bindings: ReadonlyArray<readonly [{ __id: symbol }, unknown]>): void {\n if (bindings.length === 0) return\n if (this.scopes === null) this.scopes = new Map()\n for (const [scope, value] of bindings) {\n this.scopes.set(scope.__id, value)\n }\n }\n\n constructor(\n parent: ControllerInstance | null,\n rootShared: RootShared,\n pathSegment: string,\n deps: Record<string, unknown>,\n ) {\n this.parent = parent\n this.rootShared = rootShared\n this.path = parent ? [...parent.path, pathSegment] : [pathSegment]\n this.deps = deps\n }\n\n /**\n * Run the factory and produce an api. On throw, the partially-constructed\n * state is rolled back (entries disposed in reverse) and the error is rethrown.\n */\n construct<Props, Api>(factory: (ctx: Ctx, props: Props) => Api, props: Props): Api {\n const ctx = this.buildCtx()\n let api: Api\n try {\n api = factory(ctx, props)\n } catch (err) {\n this.rollbackPartialConstruction()\n throw err\n }\n this.state = 'active'\n if (__DEV__) {\n this.rootShared.devtools.emit({\n type: 'controller:constructed',\n path: this.path,\n props: props as unknown,\n })\n }\n return api\n }\n\n private rollbackPartialConstruction(): void {\n // Tear down what was built before the throw, in reverse order.\n for (const entry of this.entries.reverse()) {\n try {\n this.disposeEntry(entry)\n } catch (err) {\n // A teardown error during rollback must not mask the original\n // construction throw or abort the rest of the rollback — route it to\n // onError, same as dispose(). (T2.8)\n dispatchError(this.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: this.path,\n })\n }\n }\n this.entries.clear()\n this.state = 'disposed'\n }\n\n dispose(): void {\n if (this.state === 'disposed') return\n this.state = 'disposed'\n\n for (const entry of this.entries.reverse()) {\n try {\n this.disposeEntry(entry)\n } catch (err) {\n dispatchError(this.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: this.path,\n })\n }\n }\n this.entries.clear()\n this.scopes = null\n this.injectCache = null\n\n if (__DEV__) {\n this.rootShared.devtools.emit({ type: 'controller:disposed', path: this.path })\n }\n }\n\n private disposeEntry(entry: LifecycleEntry): void {\n switch (entry.kind) {\n case 'effect':\n entry.dispose?.()\n entry.dispose = null\n break\n case 'cleanup':\n entry.dispose()\n break\n case 'subscription-cache':\n entry.dispose()\n break\n case 'child':\n entry.instance.dispose()\n break\n case 'subscription':\n entry.unsubscribe()\n break\n case 'onDispose':\n entry.fn()\n break\n case 'onSuspend':\n case 'onResume':\n // No work on dispose.\n break\n }\n }\n\n isSuspended(): boolean {\n return this.state === 'suspended'\n }\n\n suspend(): void {\n if (this.state !== 'active') return\n this.state = 'suspended'\n\n for (const entry of this.entries.reverse()) {\n try {\n switch (entry.kind) {\n case 'effect':\n entry.dispose?.()\n entry.dispose = null\n break\n case 'subscription-cache':\n // Pause `refetchInterval` + focus/online listeners + release the\n // entry from this subscriber. Spec §4.1.\n entry.suspend()\n break\n case 'child':\n entry.instance.suspend()\n break\n case 'onSuspend':\n entry.fn()\n break\n default:\n break\n }\n } catch (err) {\n dispatchError(this.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: this.path,\n })\n }\n }\n\n if (__DEV__) {\n this.rootShared.devtools.emit({ type: 'controller:suspended', path: this.path })\n }\n }\n\n resume(): void {\n if (this.state !== 'suspended') return\n this.state = 'active'\n\n for (const entry of this.entries.forward()) {\n try {\n switch (entry.kind) {\n case 'effect':\n // Skip effects that are already live. An effect registered DURING\n // this resume (e.g. from an onResume handler) was activated\n // immediately by `ctx.effect` while state is 'active'; the forward\n // loop then reaches its freshly-pushed node. Re-activating would\n // overwrite the live `dispose` ref without calling it — the effect\n // would run twice per change and one copy would survive dispose().\n // Only re-activate effects that `suspend()` cleared (dispose null).\n // (T2.2)\n if (entry.dispose === null) {\n entry.dispose = standaloneEffect(entry.factory)\n }\n break\n case 'subscription-cache':\n // Re-acquire the entry, restart `refetchInterval`, and re-check\n // staleness (a stale entry refetches on resume — spec §4.1).\n entry.resume()\n break\n case 'child':\n // Skip children explicitly suspended via attach.suspend() or\n // collection suspendItem() — a whole-tree resume (KeepAlive) must\n // not wake them. They resume only via their own attach.resume() /\n // resumeItem(). (T2.6)\n if (entry.explicitlySuspended) break\n entry.instance.resume()\n break\n case 'onResume':\n entry.fn()\n break\n default:\n break\n }\n } catch (err) {\n dispatchError(this.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: this.path,\n })\n }\n }\n\n if (__DEV__) {\n this.rootShared.devtools.emit({ type: 'controller:resumed', path: this.path })\n }\n }\n\n // --- Ctx surface --------------------------------------------------------\n\n private buildCtx(): Ctx {\n const self = this\n // A ctx.* factory called after the controller was disposed would push into\n // a cleared lifecycle list — a live child / subscription / effect that\n // never gets torn down. It is always a programming error (a captured `ctx`\n // used past its owner's lifetime), so throw rather than leak or no-op. Not\n // routed through dispatchError — this is a bug in the caller, not a runtime\n // condition. (T2.4, spec §4)\n const assertLive = (method: string): void => {\n if (self.isTerminal()) {\n throw new Error(`[olas] ctx.${method}() called after the controller was disposed`)\n }\n }\n const ctx: Ctx = {\n get deps() {\n return self.deps\n },\n\n effect(fn) {\n assertLive('effect')\n const entry: LifecycleEntry = {\n kind: 'effect',\n factory: () => fn(),\n dispose: null,\n }\n // Wrap with error reporting so an effect throw goes through onError.\n const wrapped = (): void | (() => void) => {\n try {\n const cleanup = fn()\n // The effect body may return a cleanup fn that the signals runtime\n // calls on re-run / dispose — OUTSIDE this try. Wrap it so a throw\n // there also routes to onError instead of escaping. (T2.8)\n if (typeof cleanup === 'function') {\n return () => {\n try {\n cleanup()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n }\n }\n return cleanup\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n return undefined\n }\n }\n entry.factory = wrapped\n // If we're suspended, register the entry but defer activation to\n // `resume()` — otherwise the resume loop would overwrite a live\n // `dispose` ref (the just-activated effect), leaking it.\n if (self.state !== 'suspended') {\n entry.dispose = standaloneEffect(wrapped)\n }\n self.entries.push(entry)\n },\n\n cache<T>(\n fetcher: (signal: AbortSignal) => Promise<T>,\n options?: LocalCacheOptions<T>,\n ): LocalCache<T> {\n assertLive('cache')\n const cache = createLocalCache<T>(fetcher, options)\n self.entries.push({ kind: 'cleanup', dispose: () => cache.dispose() })\n return cache\n },\n\n use(query: any, keyOrOptions?: any): any {\n assertLive('use')\n const brand = (query as { __olas?: string }).__olas\n if (brand === 'infiniteQuery') {\n const handle = createInfiniteUse(\n self.rootShared.queryClient,\n query as InfiniteQuery<unknown[], unknown, unknown>,\n keyOrOptions,\n )\n self.entries.push({\n kind: 'subscription-cache',\n dispose: handle.dispose,\n suspend: handle.suspend,\n resume: handle.resume,\n })\n return handle.subscription\n }\n const handle = createUse(\n self.rootShared.queryClient,\n query as Query<unknown[], unknown>,\n keyOrOptions,\n )\n self.entries.push({\n kind: 'subscription-cache',\n dispose: handle.dispose,\n suspend: handle.suspend,\n resume: handle.resume,\n })\n return handle.subscription\n },\n\n mutation<V, R>(spec: MutationSpec<V, R>): Mutation<V, R> {\n assertLive('mutation')\n const queryClient = self.rootShared.queryClient\n const m = createMutation<V, R>(\n spec,\n self.rootShared.onError,\n self.path,\n queryClient.mutationsInflight$,\n self.rootShared.devtools,\n // Lifecycle hooks for persistable mutations — only wired when\n // `spec.persist === true`. `createMutation` validates the\n // `mutationId` requirement before construction.\n spec.persist === true\n ? {\n emitEnqueue: (ev) => queryClient.emitMutationEnqueue(ev),\n emitSettle: (ev) => queryClient.emitMutationSettle(ev),\n }\n : undefined,\n )\n self.entries.push({ kind: 'cleanup', dispose: () => m.dispose() })\n return m\n },\n\n emitter<T>(): Emitter<T> {\n assertLive('emitter')\n const e = createEmitter<T>({\n // Spec §20.6: emit-time handler throws must not block sibling\n // handlers. Route to the root's onError with kind: 'emitter' and\n // this controller's path.\n onError: (err) => {\n dispatchError(self.rootShared.onError, err, {\n kind: 'emitter',\n controllerPath: self.path,\n })\n },\n })\n self.entries.push({ kind: 'cleanup', dispose: () => e.dispose() })\n return e\n },\n\n signal,\n computed,\n\n field<T>(\n initial: T,\n validators?: ReadonlyArray<Validator<T>>,\n options?: { validateOn?: 'change' | 'blur' | 'submit' },\n ): Field<T> {\n assertLive('field')\n // Pass the reporter at construct time so the FIRST validator pass\n // (which runs synchronously in the FieldImpl constructor's\n // validator-effect) is covered.\n const f = createField(initial, validators, {\n onValidatorError: (err) => {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n },\n validateOn: options?.validateOn,\n })\n self.entries.push({ kind: 'cleanup', dispose: () => f.dispose() })\n // Standalone fields (not inside a form) still publish field:validated\n // events. Use the controller path with field name \"(field)\" — the\n // devtools panel groups by path so this is fine.\n bindFieldDevtoolsOwner(f, {\n controllerPath: self.path,\n fieldName: '(field)',\n emitter: self.rootShared.devtools,\n })\n return f\n },\n\n form<S extends FormSchema>(schema: S, options?: FormOptions<S>): Form<S> {\n assertLive('form')\n const reporter = (err: unknown): void => {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n const f = createForm(schema, options, { onValidatorError: reporter })\n self.entries.push({ kind: 'cleanup', dispose: () => f.dispose() })\n // Make every leaf field publish `field:validated` to the devtools bus\n // with its key path inside the form. See spec §20.9.\n const stop = bindTreeToDevtools(\n f as unknown as Form<FormSchema>,\n '',\n self.path,\n self.rootShared.devtools,\n )\n self.entries.push({ kind: 'cleanup', dispose: stop })\n // Bind the reporter onto every leaf in the tree too (the form itself\n // got it via the constructor option; nested forms/arrays inside the\n // schema didn't, since they were constructed by the caller before\n // ctx.form ran). Idempotent — leaves that already got the reporter\n // via ctx.field get the same one set again.\n bindTreeValidatorErrorReporter(f as unknown as Form<FormSchema>, reporter)\n return f\n },\n\n fieldArray<I extends Field<any> | Form<any>>(\n itemFactory: (initial?: ItemInitial<I>) => I,\n options?: FieldArrayOptions<I>,\n ): FieldArray<I> {\n assertLive('fieldArray')\n const reporter = (err: unknown): void => {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n const fa = createFieldArray<I>(itemFactory, options, { onValidatorError: reporter })\n self.entries.push({ kind: 'cleanup', dispose: () => fa.dispose() })\n const stop = bindTreeToDevtools(\n fa as unknown as FieldArray<Field<unknown> | Form<FormSchema>>,\n '',\n self.path,\n self.rootShared.devtools,\n )\n self.entries.push({ kind: 'cleanup', dispose: stop })\n bindTreeValidatorErrorReporter(\n fa as unknown as FieldArray<Field<unknown> | Form<FormSchema>>,\n reporter,\n )\n return fa\n },\n\n provide<T>(scope: Scope<T>, value: T): void {\n if (self.scopes === null) self.scopes = new Map()\n self.scopes.set(scope.__id, value)\n // Invalidate every cached inject lookup tree-wide. A descendant\n // that resolved this scope from a higher ancestor (or from a\n // default) would now resolve to the new value, but its cache\n // still holds the old value. Cheap: just bump the counter; cache\n // entries check against it on next read.\n self.rootShared.scopesVersion.value += 1\n },\n\n inject<T>(scope: Scope<T>): T {\n const version = self.rootShared.scopesVersion.value\n const cache = self.injectCache\n if (cache !== null) {\n const cached = cache.get(scope.__id)\n if (cached !== undefined && cached.version === version) {\n return cached.value as T\n }\n }\n const ensureMemo = (): Map<symbol, { value: unknown; version: number }> => {\n if (self.injectCache === null) self.injectCache = new Map()\n return self.injectCache\n }\n let node: ControllerInstance | null = self\n while (node !== null) {\n const map = node.scopes\n if (map?.has(scope.__id)) {\n const value = map.get(scope.__id) as T\n ensureMemo().set(scope.__id, { value, version })\n return value\n }\n node = node.parent\n }\n if (scope.hasDefault) {\n ensureMemo().set(scope.__id, { value: scope.default, version })\n return scope.default as T\n }\n const label = scope.name ?? scope.__id.description ?? 'unnamed'\n throw new Error(\n `[olas] ctx.inject(): no provider for scope '${label}' and no default. Provide it on an ancestor via ctx.provide(${label}, ...) or pass a default to defineScope.`,\n )\n },\n\n on<T>(emitter: Emitter<T>, handler: (value: T) => void): void {\n assertLive('on')\n const wrapped = (value: T) => {\n try {\n handler(value)\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'emitter',\n controllerPath: self.path,\n })\n }\n }\n const unsubscribe = emitter.on(wrapped)\n self.entries.push({ kind: 'subscription', unsubscribe })\n },\n\n child<Props, Api>(\n def: ControllerDef<Props, Api>,\n props: Props,\n options?: { deps?: Partial<Record<string, unknown>> },\n ): Api {\n assertLive('child')\n const segment = self.makeChildSegment(getFactory(def), getName(def))\n const override = options?.deps\n const childDeps = override !== undefined ? { ...self.deps, ...override } : self.deps\n const childInstance = new ControllerInstance(self, self.rootShared, segment, childDeps)\n // child.construct() rolls back its own partial state on throw; we let\n // the throw propagate so the parent's rollback handles cleanup.\n const api = childInstance.construct(getFactory(def), props)\n self.entries.push({ kind: 'child', instance: childInstance })\n return api\n },\n\n attach<Props, Api>(\n def: ControllerDef<Props, Api>,\n props: Props,\n options?: { deps?: Partial<Record<string, unknown>> },\n ): { api: Api; dispose: () => void; suspend: () => void; resume: () => void } {\n assertLive('attach')\n const segment = self.makeChildSegment(getFactory(def), getName(def))\n const override = options?.deps\n const childDeps = override !== undefined ? { ...self.deps, ...override } : self.deps\n const childInstance = new ControllerInstance(self, self.rootShared, segment, childDeps)\n const api = childInstance.construct(getFactory(def), props)\n const entry = {\n kind: 'child' as const,\n instance: childInstance,\n explicitlySuspended: false,\n }\n const node = self.entries.push(entry)\n let disposed = false\n return {\n api,\n dispose: () => {\n if (disposed) return\n disposed = true\n self.entries.unlink(node)\n try {\n childInstance.dispose()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n // Suspend / resume cascade through the child instance's lifecycle\n // entries (same code path as `root.suspend()`); the child's state\n // machine handles the no-op cases (suspending a disposed child,\n // resuming an active child) on its own — no need to track an\n // extra flag here.\n suspend: () => {\n if (disposed) return\n entry.explicitlySuspended = true\n try {\n childInstance.suspend()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n resume: () => {\n if (disposed) return\n // Clear the explicit-suspend mark. Under a still-suspended parent,\n // DON'T activate now — a child must not run inside a frozen tree; it\n // rejoins the parent's next resume cascade (which no longer skips it\n // now the mark is clear). (T2.6)\n entry.explicitlySuspended = false\n if (self.isSuspended()) return\n try {\n childInstance.resume()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n }\n },\n\n session<Props, Api>(\n def: ControllerDef<Props, Api>,\n props: Props,\n options?: { deps?: Partial<Record<string, unknown>> },\n ): readonly [Api, () => void] {\n assertLive('session')\n const segment = self.makeChildSegment(getFactory(def), getName(def))\n const override = options?.deps\n const childDeps = override !== undefined ? { ...self.deps, ...override } : self.deps\n const childInstance = new ControllerInstance(self, self.rootShared, segment, childDeps)\n const api = childInstance.construct(getFactory(def), props)\n const entry: LifecycleEntry = { kind: 'child', instance: childInstance }\n const node = self.entries.push(entry)\n let disposed = false\n const dispose = (): void => {\n if (disposed) return\n disposed = true\n self.entries.unlink(node)\n try {\n childInstance.dispose()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n }\n return [api, dispose] as const\n },\n\n collection<Item, K, Props, Api, R extends CollectionFactoryResult>(\n options:\n | CollectionHomogeneousOptions<Item, K, Props, Api>\n | CollectionFactoryOptions<Item, K, R>,\n ): Collection<K, Api> | Collection<K, CollectionFactoryApi<R>> {\n assertLive('collection')\n type ChildInfo = {\n instance: ControllerInstance\n api: Api\n node: LifecycleNode\n // For factory form: the controller def used to construct this child.\n // A different def on a future render means \"rebuild with new type\".\n def: ControllerDef<unknown, unknown>\n }\n const childMap = new Map<K, ChildInfo>()\n const items$ = signal<ReadonlyArray<{ key: K; api: Api }>>([])\n const size$ = computed(() => items$.value.length)\n\n const isFactoryForm =\n (options as CollectionFactoryOptions<Item, K, R>).factory !== undefined\n\n const buildChild = (\n item: Item,\n ): {\n instance: ControllerInstance\n api: Api\n def: ControllerDef<unknown, unknown>\n } | null => {\n let def: ControllerDef<unknown, unknown>\n let childProps: unknown\n if (isFactoryForm) {\n const factoryOpts = options as CollectionFactoryOptions<Item, K, R>\n const result = factoryOpts.factory(item) as CollectionFactoryResult\n def = result.controller as ControllerDef<unknown, unknown>\n childProps = result.props\n } else {\n const homoOpts = options as CollectionHomogeneousOptions<Item, K, Props, Api>\n def = homoOpts.controller as unknown as ControllerDef<unknown, unknown>\n childProps = homoOpts.propsOf(item)\n }\n const segment = self.makeChildSegment(getFactory(def), getName(def))\n const childDeps =\n options.deps !== undefined ? { ...self.deps, ...options.deps } : self.deps\n const instance = new ControllerInstance(self, self.rootShared, segment, childDeps)\n try {\n const api = instance.construct(\n getFactory(def) as (ctx: Ctx, props: unknown) => Api,\n childProps,\n )\n return { instance, api, def }\n } catch (err) {\n // SPEC §12.1.6: runtime construction errors in collection items\n // route to onError; the bad item is skipped.\n dispatchError(self.rootShared.onError, err, {\n kind: 'construction',\n controllerPath: self.path,\n })\n return null\n }\n }\n\n const removeKey = (key: K): void => {\n const info = childMap.get(key)\n if (info === undefined) return\n childMap.delete(key)\n self.entries.unlink(info.node)\n try {\n info.instance.dispose()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n }\n\n const reconcile = (): void => {\n // Only `source` is a tracked dependency — everything else (keyOf, the\n // item factory, child construct/dispose) runs untracked so a child\n // factory reading an unrelated signal can't force the whole\n // collection to re-reconcile on every write to it (T2.3). Mirrors the\n // untracked bind in ctx.use.\n const source = options.source.value\n untracked(() => {\n const itemByKey = new Map<K, Item>()\n for (const item of source) {\n const key = options.keyOf(item)\n if (itemByKey.has(key)) {\n if (__DEV__) {\n // eslint-disable-next-line no-console\n console.warn(\n `[olas] ctx.collection: duplicate key ${String(key)} in source — only the` +\n ' first occurrence is kept. This is usually a bug in `keyOf(item)`;' +\n ' return a unique identifier per item.',\n )\n }\n continue\n }\n itemByKey.set(key, item)\n }\n\n // Drop removed keys.\n for (const key of [...childMap.keys()]) {\n if (!itemByKey.has(key)) removeKey(key)\n }\n\n // Add new keys + rebuild factory-form type changes.\n for (const [key, item] of itemByKey) {\n const existing = childMap.get(key)\n if (existing !== undefined) {\n if (isFactoryForm) {\n const result = (options as CollectionFactoryOptions<Item, K, R>).factory(\n item,\n ) as CollectionFactoryResult\n if ((result.controller as unknown) !== existing.def) {\n removeKey(key)\n const built = buildChild(item)\n if (built !== null) {\n const entry: LifecycleEntry = { kind: 'child', instance: built.instance }\n const node = self.entries.push(entry)\n childMap.set(key, { ...built, node })\n }\n }\n }\n continue\n }\n const built = buildChild(item)\n if (built !== null) {\n const entry: LifecycleEntry = { kind: 'child', instance: built.instance }\n const node = self.entries.push(entry)\n childMap.set(key, { ...built, node })\n }\n }\n\n // Project to items signal in source order, deduped, skipping failures.\n const next: Array<{ key: K; api: Api }> = []\n const seen = new Set<K>()\n for (const item of source) {\n const key = options.keyOf(item)\n if (seen.has(key)) continue\n seen.add(key)\n const info = childMap.get(key)\n if (info !== undefined) next.push({ key, api: info.api })\n }\n items$.set(next)\n })\n }\n\n // Register the diff loop as an 'effect' entry so it pauses on suspend\n // and re-runs on resume — mirrors how `ctx.effect` is wired.\n const wrapped = (): void => {\n try {\n reconcile()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n }\n const effectEntry: LifecycleEntry = {\n kind: 'effect',\n factory: wrapped,\n dispose: null,\n }\n if (self.state !== 'suspended') {\n effectEntry.dispose = standaloneEffect(wrapped)\n }\n self.entries.push(effectEntry)\n\n return {\n // readOnly so the writable backing signals can't be mutated through\n // the ReadSignal-typed public surface. (T2.8)\n items: readOnly(items$),\n size: readOnly(size$),\n get: (key: K) => childMap.get(key)?.api,\n has: (key: K) => childMap.has(key),\n suspendItem: (key: K) => {\n const info = childMap.get(key)\n if (info === undefined) return\n // Mark the child entry so a whole-tree resume cascade skips it. (T2.6)\n if (info.node.entry.kind === 'child') info.node.entry.explicitlySuspended = true\n info.instance.suspend()\n },\n resumeItem: (key: K) => {\n const info = childMap.get(key)\n if (info === undefined) return\n if (info.node.entry.kind === 'child') info.node.entry.explicitlySuspended = false\n // Under a suspended parent, defer to the parent's next resume\n // cascade (which no longer skips the cleared entry). (T2.6)\n if (self.isSuspended()) return\n info.instance.resume()\n },\n isItemSuspended: (key: K) => {\n const info = childMap.get(key)\n if (info === undefined) return false\n return info.instance.isSuspended()\n },\n }\n },\n\n lazyChild<Props, Api>(\n loader: () => Promise<ControllerDef<Props, Api>>,\n props: Props,\n options?: { deps?: Partial<Record<string, unknown>> },\n ): LazyChild<Api> {\n assertLive('lazyChild')\n const status$ = signal<'idle' | 'loading' | 'ready' | 'error'>('idle')\n const api$ = signal<Api | undefined>(undefined)\n const error$ = signal<unknown | undefined>(undefined)\n\n let childInstance: ControllerInstance | null = null\n let childNode: LifecycleNode | null = null\n let pendingLoad: Promise<Api> | null = null\n let disposed = false\n\n // Parent dispose flag; the child entry (when present) is disposed\n // via the parent's normal cascade, so we don't double-tear-down.\n const flagEntry: LifecycleEntry = {\n kind: 'onDispose',\n fn: () => {\n disposed = true\n },\n }\n const flagNode = self.entries.push(flagEntry)\n\n const handleFailure = (err: unknown): void => {\n status$.set('error')\n error$.set(err)\n dispatchError(self.rootShared.onError, err, {\n kind: 'construction',\n controllerPath: self.path,\n })\n }\n\n const load = (): Promise<Api> => {\n if (disposed) {\n return Promise.reject(new Error('[olas] ctx.lazyChild: cannot load after dispose'))\n }\n // Cached fulfilled or in-flight loads share a promise. A previously\n // *rejected* load doesn't — we clear `pendingLoad` in the catch\n // branch so the next `load()` reattempts the loader. Sticky\n // rejections trap consumers on a transient import-failure.\n if (pendingLoad !== null) return pendingLoad\n status$.set('loading')\n const attempt = loader().then(\n (def) => {\n if (disposed) {\n throw new Error('[olas] ctx.lazyChild: disposed during load')\n }\n const segment = self.makeChildSegment(getFactory(def), getName(def))\n const childDeps =\n options?.deps !== undefined ? { ...self.deps, ...options.deps } : self.deps\n const instance = new ControllerInstance(self, self.rootShared, segment, childDeps)\n try {\n const api = instance.construct(getFactory(def), props)\n childInstance = instance\n childNode = self.entries.push({ kind: 'child', instance })\n api$.set(api)\n status$.set('ready')\n return api\n } catch (err) {\n handleFailure(err)\n throw err\n }\n },\n (err) => {\n if (disposed) throw err\n handleFailure(err)\n throw err\n },\n )\n pendingLoad = attempt\n attempt.catch(() => {\n // Allow retry: drop the cached rejection if this is still the\n // current attempt. A successful load leaves `pendingLoad` in\n // place so repeat `load()` calls return the same fulfilled api.\n if (pendingLoad === attempt) pendingLoad = null\n })\n return attempt\n }\n\n const dispose = (): void => {\n if (disposed) return\n disposed = true\n if (childNode !== null && childInstance !== null) {\n self.entries.unlink(childNode)\n try {\n childInstance.dispose()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n childInstance = null\n childNode = null\n }\n // Unlink the parent-dispose flag entry too — its only job was to\n // signal disposal to an in-flight loader, and `disposed` is now\n // already true. Leaving it behind leaks one closure per ever-\n // disposed lazyChild for the parent's remaining lifetime.\n self.entries.unlink(flagNode)\n }\n\n return {\n status: readOnly(status$),\n api: readOnly(api$),\n error: readOnly(error$),\n load,\n dispose,\n }\n },\n\n onDispose(fn) {\n assertLive('onDispose')\n self.entries.push({\n kind: 'onDispose',\n fn: () => {\n try {\n fn()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n })\n },\n\n onSuspend(fn) {\n assertLive('onSuspend')\n self.entries.push({\n kind: 'onSuspend',\n fn: () => {\n try {\n fn()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n })\n },\n\n onResume(fn) {\n assertLive('onResume')\n self.entries.push({\n kind: 'onResume',\n fn: () => {\n try {\n fn()\n } catch (err) {\n dispatchError(self.rootShared.onError, err, {\n kind: 'effect',\n controllerPath: self.path,\n })\n }\n },\n })\n },\n }\n return ctx\n }\n\n private isTerminal(): boolean {\n return this.state === 'disposed'\n }\n\n // biome-ignore lint/complexity/noBannedTypes: Function is the precise type for \"any function with a .name\"\n private makeChildSegment(factory: Function, explicitName: string | undefined): string {\n const idx = this.childCounter++\n const base = explicitName ?? factory.name ?? ''\n return `${base !== '' ? base : 'anonymous'}[${idx}]`\n }\n}\n","import { DevtoolsEmitter } from '../devtools'\nimport { QueryClient } from '../query/client'\nimport { getFactory } from './define'\nimport { ControllerInstance, type RootShared } from './instance'\nimport type { AmbientDeps, ControllerDef, Root, RootOptions } from './types'\n\nconst ROOT_METHODS = [\n 'dispose',\n 'suspend',\n 'resume',\n 'dehydrate',\n 'waitForIdle',\n 'applyDehydratedEntry',\n '__debug',\n] as const\n\n/**\n * Construct a root controller.\n *\n * Internal: this is the shared engine. The public `createRoot` (props-less)\n * and `createTestController` (props-allowing) both call through here.\n */\nexport function createRootWithProps<Props, Api, TDeps extends Record<string, unknown>>(\n def: ControllerDef<Props, Api>,\n props: Props,\n options: RootOptions<TDeps>,\n): Root<Api> {\n const devtools = new DevtoolsEmitter()\n const queryClient = new QueryClient({\n onError: options.onError,\n hydrate: options.hydrate,\n devtools,\n deps: options.deps as Record<string, unknown>,\n refetchOnWindowFocus: options.refetchOnWindowFocus,\n refetchOnReconnect: options.refetchOnReconnect,\n plugins: options.plugins,\n })\n const rootShared: RootShared = {\n devtools,\n onError: options.onError,\n queryClient,\n scopesVersion: { value: 0 },\n }\n\n const instance = new ControllerInstance(\n null,\n rootShared,\n 'root',\n options.deps as Record<string, unknown>,\n )\n\n // Pre-seed scopes from RootOptions before the factory runs so\n // ctx.inject() resolves them from any descendant. SPEC §10.3.\n if (options.scopes !== undefined && options.scopes.length > 0) {\n instance.seedScopes(options.scopes)\n }\n\n // Bootstrap failure throws straight out of createRoot. Spec §12.1.5.\n // Tear down the QueryClient and any plugins it spawned (window/storage\n // listeners, transports) before re-throwing so the failure doesn't leak.\n let api: Api\n try {\n api = instance.construct(getFactory(def), props)\n } catch (err) {\n queryClient.dispose()\n throw err\n }\n\n // Non-object apis get wrapped so root controls have somewhere to live.\n let target = api\n if (typeof api !== 'object' || api === null) {\n // Allow primitive APIs in principle but root controls must live somewhere.\n // Wrap in a holder. The declared `Root<Api>` type intersection lies in\n // this branch — `(holder as Api).dispose` won't be present on the\n // primitive itself. Dev-warn so the footgun is visible at first run\n // instead of as a confusing \"undefined.value\" later.\n if (__DEV__) {\n // eslint-disable-next-line no-console\n console.warn(\n '[olas] createRoot: controller returned a non-object api ' +\n `(${api === null ? 'null' : typeof api}). ` +\n 'Wrapping as { value: api } so root controls (dispose / suspend / ...) ' +\n \"can be attached. Prefer returning an object from a root controller's factory.\",\n )\n }\n target = { value: api } as unknown as Api\n }\n\n // attachRootControls throws on a root-controls NAME CONFLICT (the api defines\n // `dispose`/`suspend`/...) — AFTER the tree is fully constructed. Tear down\n // the live instance + queryClient (effects, focus/online listeners, plugin\n // transports) before rethrowing so the conflict doesn't leak the whole tree.\n // The construct-throw path above rolls back via queryClient.dispose(); this\n // is the symmetric guard for the post-construction failure. (T2.5)\n try {\n return attachRootControls(target, instance, devtools, queryClient)\n } catch (err) {\n instance.dispose()\n queryClient.dispose()\n throw err\n }\n}\n\nfunction attachRootControls<Api>(\n api: Api,\n instance: ControllerInstance,\n devtools: DevtoolsEmitter,\n queryClient: QueryClient,\n): Root<Api> {\n let suspendTimer: ReturnType<typeof setTimeout> | null = null\n\n const dispose = () => {\n if (suspendTimer != null) {\n clearTimeout(suspendTimer)\n suspendTimer = null\n }\n instance.dispose()\n queryClient.dispose()\n }\n\n const suspend = (opts?: { maxIdle?: number }) => {\n instance.suspend()\n if (suspendTimer != null) {\n clearTimeout(suspendTimer)\n suspendTimer = null\n }\n const maxIdle = opts?.maxIdle\n if (maxIdle != null && maxIdle !== Number.POSITIVE_INFINITY) {\n suspendTimer = setTimeout(() => {\n suspendTimer = null\n dispose()\n }, maxIdle)\n }\n }\n\n const resume = () => {\n if (suspendTimer != null) {\n clearTimeout(suspendTimer)\n suspendTimer = null\n }\n instance.resume()\n }\n\n const debug = {\n subscribe: (handler: Parameters<DevtoolsEmitter['subscribe']>[0]) =>\n devtools.subscribe(handler),\n queryEntries: () => queryClient.queryEntriesSnapshot(),\n }\n\n const target = api as Record<string, unknown>\n for (const method of ROOT_METHODS) {\n // Use `in` rather than `Object.hasOwn` so class-based apis with\n // prototype methods like `dispose()` still trigger the conflict\n // detection instead of being silently overwritten by defineProperty.\n if (method in target) {\n throw new Error(\n `[olas] Root controller api defines '${method}' which conflicts with the root controls.`,\n )\n }\n }\n // Lock root controls: writable:false + configurable:false so user code\n // can't `delete api.dispose` (orphaning the root) or shadow them with a\n // typo. The `in`-check above is the friendly preflight; this is the\n // hard fence in case a consumer mutates the api after construction.\n const lock = { enumerable: false, writable: false, configurable: false }\n Object.defineProperty(target, 'dispose', { value: dispose, ...lock })\n Object.defineProperty(target, 'suspend', { value: suspend, ...lock })\n Object.defineProperty(target, 'resume', { value: resume, ...lock })\n Object.defineProperty(target, '__debug', { value: debug, ...lock })\n Object.defineProperty(target, 'dehydrate', {\n value: () => queryClient.dehydrate(),\n ...lock,\n })\n Object.defineProperty(target, 'waitForIdle', {\n value: () => queryClient.waitForIdle(),\n ...lock,\n })\n Object.defineProperty(target, 'applyDehydratedEntry', {\n value: (queryId: string, keyArgs: readonly unknown[], data: unknown, lastUpdatedAt: number) =>\n queryClient.applyDehydratedEntry(queryId, keyArgs, data, lastUpdatedAt),\n ...lock,\n })\n\n return api as Root<Api>\n}\n\n/**\n * Construct a root controller. Root factories take no props — startup config\n * goes in `deps`.\n */\nexport function createRoot<Api extends object, TDeps extends Record<string, unknown> = AmbientDeps>(\n def: ControllerDef<void, Api>,\n options: RootOptions<TDeps>,\n): Root<Api> {\n return createRootWithProps<void, Api, TDeps>(def, undefined as void, options)\n}\n"],"mappings":";;;;;;;;;AA2BA,SAAgB,iBACd,SACA,SAC2B;CAM3B,OAAO;EAJL,QAAQ;EACR,WAAW;EACX,GAAI,SAAS,SAAS,KAAA,IAAY,EAAE,QAAQ,QAAQ,KAAK,IAAI,CAAC;CAEvD;AACX;;AAGA,SAAgB,WACd,KACiC;CACjC,OAAQ,IAA0C;AACpD;;AAGA,SAAgB,QAAoB,KAAoD;CACtF,OAAQ,IAA0C;AACpD;;;AC0BA,SAAS,QAAQ,MAAiC;CAChD,OAAO,KAAK,KAAK,IAAG;AACtB;;;;;;;;;;;;;AAcA,IAAa,kBAAb,MAA6B;CAC3B,2BAAmB,IAAI,IAAiC;;CAExD,kCAA0B,IAAI,IAAiC;CAE/D,UAAU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