{"version":3,"file":"march-hare.umd.cjs","sources":["../node_modules/eventemitter3/index.js","../src/library/boundary/components/broadcast/utils.ts","../src/library/boundary/components/broadcast/index.tsx","../src/library/boundary/components/tasks/utils.ts","../src/library/boundary/components/tasks/index.tsx","../src/library/boundary/components/env/utils.ts","../src/library/utils.ts","../src/library/types/index.ts","../src/library/boundary/components/env/index.tsx","../src/library/boundary/components/sharing/index.tsx","../src/library/boundary/components/tap/utils.ts","../src/library/error/types.ts","../src/library/error/index.ts","../src/library/action/utils.ts","../src/library/action/index.ts","../src/library/utils/utils.ts","../src/library/actions/utils.ts","../src/library/error/utils.ts","../src/library/boundary/components/sse/utils.ts","../src/library/boundary/components/sse/index.tsx","../src/library/boundary/components/tap/index.tsx","../src/library/boundary/components/consumer/utils.ts","../src/library/boundary/index.tsx","../src/library/boundary/components/scope/utils.ts","../src/library/cache/index.ts","../src/library/resource/utils.ts","../src/library/resource/index.ts","../node_modules/immertation/dist/immertation.mjs","../src/library/boundary/components/consumer/components/partition/index.tsx","../src/library/actions/index.ts","../src/library/with/utils.ts","../src/library/context/index.ts","../src/library/coalesce/index.ts","../src/library/scope/utils.tsx","../src/library/app/index.tsx","../src/library/with/index.ts","../src/library/annotate/index.ts","../src/library/utils/index.ts","../src/library/shared/index.ts","../src/library/scope/index.tsx"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n  , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n  Events.prototype = Object.create(null);\n\n  //\n  // This hack is needed because the `__proto__` property is still inherited in\n  // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n  //\n  if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n  this.fn = fn;\n  this.context = context;\n  this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n  if (typeof fn !== 'function') {\n    throw new TypeError('The listener must be a function');\n  }\n\n  var listener = new EE(fn, context || emitter, once)\n    , evt = prefix ? prefix + event : event;\n\n  if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n  else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n  else emitter._events[evt] = [emitter._events[evt], listener];\n\n  return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n  if (--emitter._eventsCount === 0) emitter._events = new Events();\n  else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n  this._events = new Events();\n  this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n  var names = []\n    , events\n    , name;\n\n  if (this._eventsCount === 0) return names;\n\n  for (name in (events = this._events)) {\n    if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n  }\n\n  if (Object.getOwnPropertySymbols) {\n    return names.concat(Object.getOwnPropertySymbols(events));\n  }\n\n  return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n  var evt = prefix ? prefix + event : event\n    , handlers = this._events[evt];\n\n  if (!handlers) return [];\n  if (handlers.fn) return [handlers.fn];\n\n  for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n    ee[i] = handlers[i].fn;\n  }\n\n  return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n  var evt = prefix ? prefix + event : event\n    , listeners = this._events[evt];\n\n  if (!listeners) return 0;\n  if (listeners.fn) return 1;\n  return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n  var evt = prefix ? prefix + event : event;\n\n  if (!this._events[evt]) return false;\n\n  var listeners = this._events[evt]\n    , len = arguments.length\n    , args\n    , i;\n\n  if (listeners.fn) {\n    if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n    switch (len) {\n      case 1: return listeners.fn.call(listeners.context), true;\n      case 2: return listeners.fn.call(listeners.context, a1), true;\n      case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n      case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n      case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n      case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n    }\n\n    for (i = 1, args = new Array(len -1); i < len; i++) {\n      args[i - 1] = arguments[i];\n    }\n\n    listeners.fn.apply(listeners.context, args);\n  } else {\n    var length = listeners.length\n      , j;\n\n    for (i = 0; i < length; i++) {\n      if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n      switch (len) {\n        case 1: listeners[i].fn.call(listeners[i].context); break;\n        case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n        case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n        case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n        default:\n          if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n            args[j - 1] = arguments[j];\n          }\n\n          listeners[i].fn.apply(listeners[i].context, args);\n      }\n    }\n  }\n\n  return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n  return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n  return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n  var evt = prefix ? prefix + event : event;\n\n  if (!this._events[evt]) return this;\n  if (!fn) {\n    clearEvent(this, evt);\n    return this;\n  }\n\n  var listeners = this._events[evt];\n\n  if (listeners.fn) {\n    if (\n      listeners.fn === fn &&\n      (!once || listeners.once) &&\n      (!context || listeners.context === context)\n    ) {\n      clearEvent(this, evt);\n    }\n  } else {\n    for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n      if (\n        listeners[i].fn !== fn ||\n        (once && !listeners[i].once) ||\n        (context && listeners[i].context !== context)\n      ) {\n        events.push(listeners[i]);\n      }\n    }\n\n    //\n    // Reset the array, or remove it completely if we have no more listeners.\n    //\n    if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n    else clearEvent(this, evt);\n  }\n\n  return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n  var evt;\n\n  if (event) {\n    evt = prefix ? prefix + event : event;\n    if (this._events[evt]) clearEvent(this, evt);\n  } else {\n    this._events = new Events();\n    this._eventsCount = 0;\n  }\n\n  return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n  module.exports = EventEmitter;\n}\n","import EventEmitter from \"eventemitter3\";\nimport * as React from \"react\";\nimport type { Filter } from \"../../../types/index.ts\";\n\n/**\n * Sentinel key used to store the cache entry for dispatches that\n * carried no channel (uncalled actions). Real channels are hashed via\n * `JSON.stringify`, which can never produce the empty string &mdash;\n * the two namespaces are safely disjoint.\n */\nconst DEFAULT_CHANNEL_KEY = \"\";\n\n/**\n * Cache entry stored per `(event, channelHash)`. The original channel\n * object is preserved so mount replay can re-emit with the exact\n * channel the producer used &mdash; otherwise late-mounting subscribers\n * could not satisfy filtered-channel matching.\n */\ntype Entry = {\n  readonly channel: Filter | undefined;\n  readonly value: unknown;\n};\n\nfunction channelKey(channel: Filter | undefined): string {\n  if (channel === undefined) return DEFAULT_CHANNEL_KEY;\n  return JSON.stringify(channel);\n}\n\n/**\n * EventEmitter subclass that caches the latest payload per `(event,\n * channel)` pair. When a broadcast or multicast action is dispatched,\n * the payload is stored so that late-mounting components can replay it\n * via {@link useLifecycles} and handlers can read it via\n * `context.actions.final()`. Cache entries are keyed by both the\n * action and the channel object &mdash; multi-channel actions retain\n * one entry per channel rather than overwriting on every dispatch.\n */\nexport class BroadcastEmitter extends EventEmitter {\n  private cache = new Map<string | symbol, Map<string, Entry>>();\n  private latest = new Map<string | symbol, Entry>();\n\n  override emit(event: string | symbol, ...args: unknown[]): boolean {\n    this.setCache(event, args[0], undefined);\n    return super.emit(event, ...args);\n  }\n\n  /**\n   * Cache a value for a given event/channel pair without emitting to\n   * listeners. Used by {@link emitAsync} to preserve caching when\n   * bypassing `emit()`.\n   */\n  setCache(\n    event: string | symbol,\n    value: unknown,\n    channel: Filter | undefined,\n  ): void {\n    const inner = this.cache.get(event) ?? new Map<string, Entry>();\n    const entry: Entry = { channel, value };\n    inner.set(channelKey(channel), entry);\n    this.cache.set(event, inner);\n    this.latest.set(event, entry);\n  }\n\n  /**\n   * Retrieve the most recently cached payload across every channel for\n   * a given event. Returns `undefined` if no value has ever been\n   * dispatched. Use {@link getCachedAll} when channel-specific replay\n   * is required &mdash; this overload exists for `context.actions\n   * .final()`, which resolves to the most recent broadcast regardless\n   * of channel.\n   */\n  getCached(event: string | symbol): unknown {\n    return this.latest.get(event)?.value;\n  }\n\n  /**\n   * Iterate every cached `(channel, value)` pair for a given event.\n   * Mount replay walks this to re-emit per-channel values so that\n   * late-mounting subscribers see the same broadcasts they would have\n   * received had they been mounted at dispatch time.\n   */\n  getCachedAll(event: string | symbol): Iterable<Entry> {\n    return this.cache.get(event)?.values() ?? [];\n  }\n\n  /**\n   * Emit without caching the payload. Used by the framework to publish\n   * fire-and-forget events (such as `Lifecycle.Fault`) where late-mounting\n   * subscribers must not replay a stale value.\n   */\n  fire(event: string | symbol, ...args: unknown[]): boolean {\n    return super.emit(event, ...args);\n  }\n}\n\n/**\n * React context for broadcasting distributed actions across components.\n */\nexport const Context = React.createContext<BroadcastEmitter>(\n  new BroadcastEmitter(),\n);\n\n/**\n * Hook to access the broadcast EventEmitter for emitting and listening to distributed actions.\n *\n * @returns The BroadcastEmitter instance for distributed actions.\n */\nexport function useBroadcast(): BroadcastEmitter {\n  return React.useContext(Context);\n}\n","import { Props } from \"./types.ts\";\nimport { Context, BroadcastEmitter } from \"./utils.ts\";\nimport * as React from \"react\";\n\nexport { useBroadcast, BroadcastEmitter } from \"./utils.ts\";\n\n/**\n * Creates a new broadcast context for distributed actions. Only needed if you\n * want to isolate a broadcast context, useful for libraries that want to provide\n * their own broadcast context without interfering with the app's broadcast context.\n *\n * @param props.children - The children to render within the broadcast context.\n * @returns The children wrapped in a broadcast context provider.\n */\nexport function Broadcaster({ children }: Props): React.ReactNode {\n  const context = React.useMemo(() => new BroadcastEmitter(), []);\n\n  return <Context.Provider value={context}>{children}</Context.Provider>;\n}\n","import { Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the shared tasks Set.\n * Tasks are ordered by creation time (oldest first) since Sets maintain insertion order.\n */\nexport const Context = React.createContext<Tasks>(new Set());\n\n/**\n * Hook to access the shared tasks Set from context.\n * Returns the Set of all currently running tasks across all components in the context.\n *\n * @returns The Set of Task instances in the current context.\n *\n * @example\n * ```ts\n * const tasks = useTasks();\n *\n * // Abort all tasks for a specific action\n * for (const task of tasks) {\n *   if (task.action === Actions.Fetch) {\n *     task.controller.abort();\n *   }\n * }\n * ```\n */\nexport function useTasks(): Tasks {\n  return React.useContext(Context);\n}\n","import { Context } from \"./utils.ts\";\nimport type { Props, Tasks } from \"./types.ts\";\nimport * as React from \"react\";\n\nexport type { Task } from \"./types.ts\";\n\n/**\n * Creates a new tasks context for action control. Only needed if you\n * want to isolate a tasks context, useful for libraries that want to provide\n * their own tasks context without interfering with the app's tasks context.\n *\n * Tasks added within this context are isolated from tasks in other contexts.\n *\n * @param props.children - The children to render within the tasks context.\n * @returns The children wrapped in a tasks context provider.\n */\nexport function Tasks({ children }: Props): React.ReactNode {\n  const tasks = React.useMemo<Tasks>(() => new Set(), []);\n\n  return <Context.Provider value={tasks}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { RefObject } from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env } from \"./types.ts\";\n\n/**\n * Internal singleton fallback used when `useEnv` is read outside any\n * `<Boundary>` (or `<Env>` provider). Reads see `{}`; writes through\n * `context.actions.produce(({ env }) => ...)` mutate this slot but\n * are not observed by any handler.\n *\n * @internal\n */\nconst fallback: RefObject<Env> = { current: <Env>{} };\n\n/**\n * React context exposing the per-Boundary Env ref. The ref itself is\n * stable across renders &mdash; readers grab `.current` at call time.\n *\n * @internal\n */\nexport const Context = React.createContext<RefObject<Env>>(fallback);\n\n/**\n * Hook that returns a read-only handle to the per-Boundary {@link Env}.\n * Reads use plain dot notation (`env.session`) and always reflect the\n * latest value, even after `await` boundaries &mdash; the handle is a\n * `Proxy` that delegates property access to the live ref.\n *\n * Writes are not exposed here. Mutate the Env inside an action handler\n * via `context.actions.produce(({ model, env }) => { env.x = ... })`\n * &mdash; the same Immer-style recipe used for the model. Mutations do\n * **not** trigger a re-render; drive view state through the model.\n *\n * Prefer `app.useEnv()` from an {@link App} instance &mdash; the App\n * factory infers the Env's shape from `app.env` and types every\n * read/write against it. The bare `useEnv()` exists for non-App\n * call sites and returns the loose {@link Env} record type.\n */\nexport function useEnv(): Env {\n  const ref = React.useContext(Context);\n  return React.useMemo<Env>(\n    () =>\n      new Proxy(<Env>{}, {\n        get(_target, key) {\n          return Reflect.get(ref.current, key);\n        },\n        has(_target, key) {\n          return key in ref.current;\n        },\n        ownKeys() {\n          return Reflect.ownKeys(ref.current);\n        },\n        getOwnPropertyDescriptor(_target, key) {\n          const descriptor = Object.getOwnPropertyDescriptor(ref.current, key);\n          if (G.isUndefined(descriptor)) return undefined;\n          return { ...descriptor, configurable: true };\n        },\n        set() {\n          throw new TypeError(\n            \"Env is read-only outside `context.actions.produce`. \" +\n              \"Mutate via produce(({ env }) => { env.x = ... }) instead.\",\n          );\n        },\n      }),\n    [ref],\n  );\n}\n\n/**\n * Internal accessor for the per-Boundary Env ref &mdash; used by the\n * Resource layer to pass a fresh snapshot to each fetcher invocation\n * and by the action layer to write through `context.actions.produce`.\n * Not exported from the library.\n *\n * @internal\n */\nexport function useEnvRef(): RefObject<Env> {\n  return React.useContext(Context);\n}\n","/**\n * Internal symbol description factories. Each function returns a namespaced\n * string suitable for `Symbol()` descriptions or `startsWith` checks.\n *\n * @internal\n */\nexport const describe = {\n  /** Unicast action description. `describe.action(\"Fetch\")` &rarr; `\"march-hare.action/Fetch\"` */\n  action: (name = \"\") => `march-hare.action/${name}`,\n  /** Broadcast action description. `describe.broadcast(\"User\")` &rarr; `\"march-hare.action/broadcast/User\"` */\n  broadcast: (name = \"\") => `march-hare.action/broadcast/${name}`,\n  /** Multicast action description. `describe.multicast(\"Update\")` &rarr; `\"march-hare.action/multicast/Update\"` */\n  multicast: (name = \"\") => `march-hare.action/multicast/${name}`,\n  /** Omnicast action description. `describe.omnicast(\"Adopted\")` &rarr; `\"march-hare.action/omnicast/Adopted\"` */\n  omnicast: (name = \"\") => `march-hare.action/omnicast/${name}`,\n  /** Channeled action description. `describe.channel(\"user\")` &rarr; `\"march-hare.channel/user\"` */\n  channel: (name = \"\") => `march-hare.channel/${name}`,\n  /** Cache entry description. `describe.cache(\"users\")` &rarr; `\"march-hare.cache/users\"` */\n  cache: (name = \"\") => `march-hare.cache/${name}`,\n  /** Lifecycle action description. `describe.lifecycle(\"Mount\")` &rarr; `\"march-hare.action.lifecycle/Mount\"` */\n  lifecycle: (name = \"\") => `march-hare.action.lifecycle/${name}`,\n};\n\n/**\n * Flat record used for shallow property comparison in {@link changes}.\n * @internal\n */\ntype Changes = Record<string, unknown>;\n\n/**\n * Get high-level changed paths between two objects.\n * Returns an object containing only the properties that were added or updated.\n *\n * @param previous - The previous state object\n * @param next - The next state object\n * @returns Object with changed property keys and their new values\n */\nexport function changes(previous: Changes, next: Changes): Changes {\n  return <Changes>(\n    Object.keys(next).reduce(\n      (result, key) =>\n        previous[key] !== next[key] ? { ...result, [key]: next[key] } : result,\n      {},\n    )\n  );\n}\n","import * as React from \"react\";\nimport { Operation } from \"immertation\";\nimport { Process, Inspect as ImmInspect, Box } from \"immertation\";\nimport type {\n  ActionId,\n  Task,\n  Tasks,\n  CurrentTask,\n} from \"../boundary/components/tasks/types.ts\";\nimport type { Fault } from \"../error/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { Invocation, LocalInvocation } from \"../resource/types.ts\";\nimport type { WithHandle } from \"../with/types.ts\";\n\n/**\n * Bounded recursion depths for {@link Inspect}. Matches Immertation's\n * `DepthLimiter` shape so the two stay in lock-step.\n */\ntype DepthLimiter = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8];\n\n/** Union of all keys across each arm of `T`. */\ntype UnionKeys<T> = T extends unknown ? keyof T : never;\n\n/** The value at `K` for each arm of `T`, falling back to `undefined` if `K` is absent on that arm. */\ntype ValueAt<T, K extends PropertyKey> = T extends unknown\n  ? K extends keyof T\n    ? T[K]\n    : undefined\n  : never;\n\n/**\n * March-hare's `Inspect<T>` wraps Immertation's so that property\n * navigation works when `T` is a discriminated union (e.g. the App's\n * Env union). For each key that appears on **any** union arm, the\n * resulting Inspect is `Inspect<ValueAt<T, K>>` &mdash; arms missing\n * the key contribute `undefined`, so optional chaining stays sound.\n *\n * For a single concrete `T`, the wrapper is transparent.\n */\nexport type Inspect<T, D extends number = 8> = ImmInspect<T> &\n  ([D] extends [0]\n    ? object\n    : {\n        [\n          K in UnionKeys<T> as ValueAt<T, K> extends (\n            ...args: unknown[]\n          ) => unknown\n            ? never\n            : K\n        ]: Inspect<ValueAt<T, K>, DepthLimiter[D]>;\n      });\n\n/**\n * Fetch-configured chain returned from `.exceeds(...)` and\n * `.isolated()`. Awaiting the chain runs the fetch with whichever\n * options are set; `.evict()` is intentionally absent because the\n * \"configured a fetch then evicted instead\" sequence has no coherent\n * meaning &mdash; eviction is always available off the bare\n * `context.actions.resource(...)` call.\n *\n * Concurrent callers with the same `(Resource, params)` automatically\n * share a single in-flight fetch &mdash; one network request, every\n * caller resolves with the same payload. The shared fetch runs on a\n * detached `AbortController` so one caller's abort never cancels work\n * other callers are still waiting on; when every caller has released\n * (their `context.task.controller` aborted) the shared controller is\n * aborted too. Chain `.isolated()` to opt out for the rare case that\n * needs an independent request.\n */\nexport type ResourceFetch<T> = PromiseLike<T> & {\n  /**\n   * Skip the fetch when the cached payload is within `duration`.\n   * Accepts a `Temporal.Duration`, a `DurationLike` object\n   * (`{ minutes: 5 }`), or an ISO 8601 string (`\"PT5M\"`).\n   */\n  readonly exceeds: (duration: Temporal.DurationLike) => ResourceFetch<T>;\n  /**\n   * Opt this call out of the default `(Resource, params)` coalesce\n   * path. The fetch fires as an independent network request against\n   * the caller's own `context.task.controller` &mdash; no joining of\n   * any in-flight fetch, no refcounted detached controller. Aborting\n   * the caller's task cancels the network exactly as a regular fetch\n   * would.\n   *\n   * Reach for this only when two callers need parallel fetches with\n   * byte-identical params and the difference in intent genuinely can't\n   * be modelled by differing params. The default is almost always\n   * what you want.\n   */\n  readonly isolated: () => ResourceFetch<T>;\n};\n\n/**\n * Chainable handle returned from `context.actions.resource(invocation)`.\n * Either resolve to the fetched value (`.exceeds`/`.isolated` + await)\n * or drop the cache slot (`.evict`) &mdash; the two paths are mutually\n * exclusive, so once `.exceeds` or `.isolated` runs the chain narrows\n * to {@link ResourceFetch} and `.evict` is no longer available.\n */\n/**\n * Handle returned from `context.actions.resource(invocation)` when the\n * invocation came from a local (fetcherless) Resource. There is no\n * fetch to await and no freshness window to configure, so the handle\n * is not thenable and carries no `.exceeds(...)`/`.isolated()` &mdash;\n * only the two cache transitions a local Resource supports.\n */\nexport type LocalResourceCall<T> = {\n  /**\n   * Write `value` into the slot addressed by the originating call's\n   * params, then fire the Resource's `.action()` auto-broadcast with\n   * the value as the payload and the params as the channel &mdash; the\n   * same cache-write-then-broadcast sequence a successful fetch\n   * performs on a fetched Resource. Synchronous; subscribers observe a\n   * warm cache.\n   *\n   * ```ts\n   * context.actions.resource(resource.draft({ id: 5 })).set(draft);\n   * ```\n   */\n  readonly set: (value: T) => void;\n  /**\n   * Drop cache entries for the primed resource. Identical semantics to\n   * the fetched variant's `.evict` &mdash; partial-match on the stored\n   * params, `null` broadcast per evicted slot.\n   */\n  readonly evict: (where?: Record<string, unknown>) => void;\n};\n\n/**\n * Dispatch surface exposed as `context.actions.resource`. Overloaded on\n * the invocation's origin: a local (fetcherless) invocation resolves to\n * a {@link LocalResourceCall} (`.set`/`.evict` only), a fetched\n * invocation to a {@link ResourceCall} (awaitable fetch chain plus\n * `.evict`). `.nuke(where?)` spans every Resource in the process.\n */\nexport type ResourceDispatcher = (<T, P extends object>(\n  invocation: LocalInvocation<T, P>,\n) => LocalResourceCall<T>) &\n  (<T, P extends object>(invocation: Invocation<T, P>) => ResourceCall<T>) & {\n    nuke(where?: Record<string, unknown>): void;\n  };\n\nexport type ResourceCall<T> = ResourceFetch<T> & {\n  /**\n   * Drop cache entries for the primed resource without fetching. With\n   * no argument, uses the params from the originating call as the\n   * pattern. With an argument, evicts every stored entry whose params\n   * satisfy the pattern's keys (partial match &mdash; extra keys in\n   * the stored params are ignored).\n   *\n   * Strictly synchronous &mdash; the Adapter contract is sync, so the\n   * warm-start `Map` and the user adapter both settle in the current\n   * tick. Async backends fire-and-forget their underlying delete from\n   * inside the adapter body; the call site doesn't `await` anything.\n   *\n   * The `where` pattern is typed as `Record<string, unknown>` rather\n   * than `Partial<P>` because the resource's params type `P` isn't\n   * threaded through the chain. Pass the literal you'd pass to the\n   * underlying fetcher &mdash; TypeScript won't catch typos in pattern\n   * keys, so prefer the no-argument form when possible.\n   *\n   * ```ts\n   * // Drop the {id: 5} slot.\n   * context.actions.resource(resource.user({ id: 5 })).evict();\n   *\n   * // Drop every user slot whose stored params include name \"Adam\".\n   * context.actions.resource(resource.user()).evict({ name: \"Adam\" });\n   * ```\n   */\n  readonly evict: (where?: Record<string, unknown>) => void;\n};\nimport { describe } from \"../utils.ts\";\n\nexport type { ActionId, Box, Task, Tasks, CurrentTask };\n/**\n * Type for objects with a Brand.Action symbol property.\n * Used for type-safe access to the action symbol.\n */\nexport type BrandedAction = { readonly [K in typeof Brand.Action]: symbol };\n\n/**\n * Type for objects with a Brand.Broadcast symbol property.\n * Used for type-safe access to the broadcast flag.\n */\nexport type BrandedBroadcast = {\n  readonly [K in typeof Brand.Broadcast]: boolean;\n};\n\n/**\n * Type for objects with a Brand.Multicast symbol property.\n * Used for type-safe access to the multicast flag.\n */\nexport type BrandedMulticast = {\n  readonly [K in typeof Brand.Multicast]: boolean;\n};\n\n/**\n * Base type for any object that may contain branded symbol properties.\n * Used as a permissive input type for action utilities.\n */\nexport type BrandedObject = { readonly [x: symbol]: unknown };\n\n/**\n * Recursive readonly. Locks every nested property so that read-only\n * projections on `context` (model, data, env) reject direct assignment\n * &mdash; mutation must go through `context.actions.produce(...)`.\n *\n * Function types pass through untouched so method calls (e.g.\n * `AbortController#abort`) remain callable. Built-in mutable containers\n * are mapped to their readonly counterparts.\n *\n * @internal\n */\nexport type DeepReadonly<T> = T extends (...args: never) => unknown\n  ? T\n  : T extends ReadonlyArray<infer U>\n    ? ReadonlyArray<DeepReadonly<U>>\n    : T extends ReadonlyMap<infer K, infer V>\n      ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>\n      : T extends ReadonlySet<infer U>\n        ? ReadonlySet<DeepReadonly<U>>\n        : T extends object\n          ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n          : T;\n\n/**\n * Union type representing any valid action that can be passed to action utilities.\n * Covers raw ActionIds (symbol/string), branded action values (`Action()` /\n * `Lifecycle.*()` results carrying `Brand.Action`), and any other symbol-keyed\n * branded object.\n */\nexport type AnyAction = ActionId | BrandedAction | BrandedObject;\n\n/**\n * Internal symbols used as brand keys to distinguish typed objects at runtime.\n * These enable TypeScript to differentiate between HandlerPayload, BroadcastPayload,\n * and channeled actions through branded types.\n * @internal\n */\nexport class Brand {\n  /** Brand key for HandlerPayload type */\n  static readonly Payload = Symbol(\"march-hare.brand/Payload\");\n  /** Brand key for BroadcastPayload type */\n  static readonly Broadcast = Symbol(\"march-hare.brand/Broadcast\");\n  /** Brand key for MulticastPayload type */\n  static readonly Multicast = Symbol(\"march-hare.brand/Multicast\");\n  /**\n   * Brand key for OmnicastPayload type. Carries the action's runtime\n   * schema (or `null` for payloadless events) so the SSE bridge can\n   * validate incoming envelopes before dispatching them.\n   */\n  static readonly Omnicast = Symbol(\"march-hare.brand/Omnicast\");\n  /** Access the underlying symbol from an action */\n  static readonly Action = Symbol(\"march-hare.brand/Action\");\n  /** Identifies channeled actions (result of calling Action(channel)) */\n  static readonly Channel = Symbol(\"march-hare.brand/Channel\");\n  /**\n   * Phantom brand carrying the action's literal name. Used purely at the\n   * type level to make `Action(\"X\")` and `Action(\"Y\")` produce\n   * structurally-distinct types so `dispatch`/`useAction` can reject\n   * symbols imported from a class outside `AC`.\n   */\n  static readonly Name = Symbol(\"march-hare.brand/Name\");\n  /**\n   * Phantom brand identifying lifecycle actions returned by\n   * `Lifecycle.Mount()`, `Lifecycle.Paint()`, `Lifecycle.Unmount()`,\n   * `Lifecycle.Error()`, and `Lifecycle.Update()`. Carries the lifecycle's\n   * literal kind so that `useAction` can pick distinct overloads &mdash; in\n   * particular,\n   * `Lifecycle.Update` resolves its payload to `Partial<DeepReadonly<D>>`\n   * against the surrounding `useActions` data generic instead of the\n   * factory-level `Record<string, unknown>` placeholder. Without this\n   * brand a user-defined `Action<P>(\"Update\")` would collide with the\n   * lifecycle overload.\n   */\n  static readonly Lifecycle = Symbol(\"march-hare.brand/Lifecycle\");\n  /**\n   * Identifies reactive bindings &mdash; the result of calling a\n   * `Lifecycle.Reactive` static with a value at the `useAction` site\n   * (e.g. `Actions.User(user)`). The binding carries the observed value\n   * so the registration can diff it between renders and dispatch through\n   * the standard handler pipeline when it changes.\n   */\n  static readonly Reactive = Symbol(\"march-hare.brand/Reactive\");\n}\n\n/**\n * Creates a lifecycle action with the given name.\n * Produces a branded `HandlerPayload` backed by a fresh\n * `Symbol(\"march-hare.action.lifecycle/${name}\")` on each call.\n *\n * @internal\n */\nfunction createLifecycleAction<\n  P = never,\n  C extends Filter = never,\n  K extends string = string,\n>(name: K): LifecyclePayload<P, C, K> {\n  const symbol = Symbol(`march-hare.action.lifecycle/${name}`);\n  const action = function (channel: C): ChanneledAction<P, C, K> {\n    return {\n      [Brand.Action]: symbol,\n      [Brand.Payload]: <P>undefined,\n      [Brand.Channel]: channel,\n      [Brand.Name]: name,\n      channel,\n    };\n  };\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Action, {\n    value: symbol,\n    enumerable: false,\n  });\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Payload, {\n    value: undefined,\n    enumerable: false,\n  });\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Lifecycle, {\n    value: name,\n    enumerable: false,\n  });\n  return <LifecyclePayload<P, C, K>>action;\n}\n\n/**\n * Internal symbol for the global `Lifecycle.Fault` broadcast. Exposed so the\n * dispatch pipeline can fire faults without depending on the `Lifecycle`\n * class at runtime.\n *\n * @internal\n */\nexport const FaultSymbol: unique symbol = <typeof FaultSymbol>(\n  Symbol(describe.broadcast(\"Fault\"))\n);\n\n/**\n * Internal symbol for the global `Lifecycle.Env` broadcast. The env\n * mutation path in `useActions` fires this symbol whenever a\n * `produce({ env })` call changes the slot reference.\n *\n * @internal\n */\nexport const EnvSymbol: unique symbol = <typeof EnvSymbol>(\n  Symbol(describe.broadcast(\"Env\"))\n);\n\n/**\n * Factory functions for lifecycle actions.\n *\n * Each call returns a **unique** action symbol so that each component can\n * subscribe independently. Assign the result as a static property in your\n * Actions class:\n *\n * @example\n * ```ts\n * export class Actions {\n *   static Mount = Lifecycle.Mount();\n *   static Paint = Lifecycle.Paint();\n *   static Unmount = Lifecycle.Unmount();\n *   static Error = Lifecycle.Error();\n *   static Update = Lifecycle.Update();\n *\n *   static Increment = Action(\"Increment\");\n * }\n * ```\n *\n * `Lifecycle.Fault` and `Lifecycle.Env` are singleton broadcasts (not\n * factories). All components subscribe to the same shared symbol &mdash;\n * `Fault` delivers global fault notifications, `Env` delivers per-`Boundary`\n * env-change notifications.\n */\nexport class Lifecycle {\n  /** Creates a Mount lifecycle action. Triggered once on component mount (`useLayoutEffect`). */\n  static Mount(): LifecyclePayload<never, never, \"Mount\"> {\n    return createLifecycleAction<never, never, \"Mount\">(\"Mount\");\n  }\n\n  /**\n   * Creates a Paint lifecycle action. Triggered once after the browser has\n   * committed the first frame (`useEffect`). Pairs with {@link Lifecycle.Mount}\n   * (pre-paint) &mdash; use Paint for work that should not delay the first\n   * paint: analytics &ldquo;viewed&rdquo; events, focus management, scroll-into-view,\n   * non-blocking prefetch, etc.\n   */\n  static Paint(): LifecyclePayload<never, never, \"Paint\"> {\n    return createLifecycleAction<never, never, \"Paint\">(\"Paint\");\n  }\n\n  /** Creates an Unmount lifecycle action. Triggered when the component unmounts. */\n  static Unmount(): LifecyclePayload<never, never, \"Unmount\"> {\n    return createLifecycleAction<never, never, \"Unmount\">(\"Unmount\");\n  }\n\n  /** Creates an Error lifecycle action. Triggered when an action throws. Receives `Fault` as payload. */\n  static Error(): LifecyclePayload<Fault, never, \"Error\"> {\n    return createLifecycleAction<Fault, never, \"Error\">(\"Error\");\n  }\n\n  /**\n   * Creates an Update lifecycle action. Fires once on mount &mdash; with the\n   * initial data keys, or `{}` when there is no data &mdash; then on every\n   * subsequent `context.data` change. The handler payload is typed as\n   * `Partial<DeepReadonly<D>>` at the subscription site: only the keys whose\n   * values changed since the previous render are present. The mount fire runs\n   * while `context.phase` is `Mounting`.\n   */\n  static Update(): LifecyclePayload<Record<string, unknown>, never, \"Update\"> {\n    return createLifecycleAction<Record<string, unknown>, never, \"Update\">(\n      \"Update\",\n    );\n  }\n\n  /**\n   * Creates a Reactive lifecycle action. Declare it as a static, then bind\n   * an external value at the `useAction` site by calling the static with\n   * it &mdash; the handler fires through the standard dispatch pipeline\n   * whenever the bound value changes between renders, receiving the latest\n   * value as its payload:\n   *\n   * ```ts\n   * export class Actions {\n   *   static User = Lifecycle.Reactive<User | undefined>(\"User\");\n   * }\n   *\n   * const { data: user } = useQuery({ queryKey: [\"user\"], queryFn: fetchUser });\n   *\n   * actions.useAction(Actions.User(user), async (context, user) => {\n   *   context.actions.produce(({ model }) => void (model.profile = user));\n   * });\n   * ```\n   *\n   * Changes are detected with `Object.is` against the last-dispatched\n   * value. The handler fires once on mount with the bound value &mdash;\n   * whether defined (e.g. a hydrated React Query cache) or `undefined`\n   * &mdash; then again on every change. Like `Lifecycle.Update`, mount is\n   * treated as the first change.\n   *\n   * Subscribing with the uncalled static (`useAction(Actions.User,\n   * handler)`) receives every reactive dispatch of the action, and\n   * `dispatch(Actions.User, value)` re-fires all handlers manually.\n   *\n   * @param name Optional name surfaced in taps and fault reports.\n   */\n  static Reactive<P>(name?: string): ReactivePayload<P> {\n    const symbol = Symbol(\n      describe.lifecycle(name ? `Reactive/${name}` : \"Reactive\"),\n    );\n    const action = function (value: P): ReactiveBinding<P> {\n      return <ReactiveBinding<P>>{\n        [Brand.Action]: symbol,\n        [Brand.Payload]: <P>undefined,\n        [Brand.Name]: name ?? \"Reactive\",\n        [Brand.Reactive]: true,\n        value,\n      };\n    };\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Action, {\n      value: symbol,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Payload, {\n      value: undefined,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Name, {\n      value: name ?? \"Reactive\",\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Lifecycle, {\n      value: \"Reactive\",\n      enumerable: false,\n    });\n    return <ReactivePayload<P>>(<unknown>action);\n  }\n\n  /**\n   * Global fault broadcast. Receives a `Fault` whenever any action in the\n   * `<Boundary>` errors, times out, or is supplanted. Subscribe via\n   * `actions.useAction(Lifecycle.Fault, handler)`.\n   *\n   * Unlike the per-component `Lifecycle.Error()` factory, `Fault` is a single\n   * shared broadcast — every subscriber points at the same symbol.\n   *\n   * @example\n   * ```tsx\n   * const actions = useActions<void, typeof Actions>();\n   *\n   * actions.useAction(Lifecycle.Fault, (context, fault) => {\n   *   if (fault.reason === Reason.Errored) {\n   *     console.error(`Action \"${fault.action}\" failed`, fault.error);\n   *   }\n   * });\n   * ```\n   */\n  static Fault: BroadcastPayload<Fault, never, \"Fault\"> = (() => {\n    const action: Record<symbol, unknown> = {};\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Action, {\n      value: FaultSymbol,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Payload, {\n      value: undefined,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Broadcast, {\n      value: true,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Name, {\n      value: \"Fault\",\n      enumerable: false,\n    });\n    return <BroadcastPayload<Fault, never, \"Fault\">>(<unknown>action);\n  })();\n\n  /**\n   * Global env-change broadcast. Receives the latest {@link Env}\n   * snapshot whenever a `context.actions.produce(({ env }) => ...)` call\n   * mutates the slot. Subscribe via\n   * `actions.useAction(Lifecycle.Env, handler)` &mdash; or render against\n   * it directly with `actions.stream(Lifecycle.Env, (env) => ...)`.\n   *\n   * Like `Lifecycle.Fault`, this is a singleton broadcast (not a factory):\n   * every subscriber points at the same shared symbol. The latest value is\n   * cached on the broadcast emitter so that late-mounting handlers and\n   * streams receive the current env on mount.\n   *\n   * @example\n   * ```tsx\n   * actions.useAction(Lifecycle.Env, (context, env) => {\n   *   console.log(\"env changed\", env);\n   * });\n   *\n   * // In JSX:\n   * {actions.stream(Lifecycle.Env, (env) => (\n   *   <span>{env.locale}</span>\n   * ))}\n   * ```\n   */\n  static Env: BroadcastPayload<Env, never, \"Env\"> = (() => {\n    const action: Record<symbol, unknown> = {};\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Action, {\n      value: EnvSymbol,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Payload, {\n      value: undefined,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Broadcast, {\n      value: true,\n      enumerable: false,\n    });\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Name, {\n      value: \"Env\",\n      enumerable: false,\n    });\n    return <BroadcastPayload<Env, never, \"Env\">>(<unknown>action);\n  })();\n}\n\n/**\n * Distribution modes for actions.\n *\n * - **Unicast** &ndash; Action is scoped to the component that defines it and cannot be\n *   consumed by other components. This is the default behaviour.\n * - **Broadcast** &ndash; Action is distributed to all mounted components that have\n *   defined a handler for it. Values are cached for late-mounting components.\n * - **Multicast** &ndash; Action defines its own scope. Components reach it by\n *   rendering inside a `<scope.Boundary>` produced by `app.Scope<MulticastActions>()`.\n *\n * @example\n * ```ts\n * export class MulticastActions {\n *   static Mood = Action<Mood>(\"Mood\", Distribution.Multicast);\n * }\n *\n * export const scope = app.Scope<typeof MulticastActions>();\n *\n * // Wrap the subtree where the scope applies.\n * export default function Mood() {\n *   return (\n *     <scope.Boundary>\n *       <Happy />\n *       <Sad />\n *     </scope.Boundary>\n *   );\n * }\n *\n * // Dispatch / subscribe — no extra options.\n * actions.dispatch(MulticastActions.Mood, mood);\n * actions.useAction(MulticastActions.Mood, (context, mood) => { ... });\n * ```\n */\nexport enum Distribution {\n  /** Action is scoped to the component that defines it. This is the default. */\n  Unicast = \"unicast\",\n  /** Action is broadcast to all mounted components and can be consumed. */\n  Broadcast = \"broadcast\",\n  /** Action is multicast to every component inside its `<scope.Boundary>`. */\n  Multicast = \"multicast\",\n}\n\n/**\n * Marker produced by `Distribution.Omnicast(schema?)` and consumed by the\n * `Action` factory. Carries the runtime schema (or `null` for payloadless\n * events) that omnicast dispatches validate against &mdash; the payload\n * type `T` is inferred from the schema at the declaration site.\n */\nexport type OmnicastDistribution<T = never, C extends Filter = never> = {\n  readonly [Brand.Omnicast]: null | Schema<T>;\n  readonly [Brand.Channel]?: C;\n};\n\nexport namespace Distribution {\n  /**\n   * Declares an action as omnicast &mdash; broadcast within its own\n   * `<Boundary>`, and additionally carried to every other connected client\n   * when the App is configured with an `sse` endpoint. The payload type is\n   * inferred from the supplied Zod-style schema (any object exposing a\n   * `parse(value)` method), so the compile-time type and the runtime\n   * validator can never drift apart. Envelopes arriving over the wire are\n   * validated with `parse` and rejected when invalid (`Reason.Rejected`\n   * through `Lifecycle.Error` / `Lifecycle.Fault`); omit the schema for\n   * payloadless events.\n   *\n   * For channeled omnicast actions, supply both generics explicitly &mdash;\n   * the payload type alias and the channel shape. Channel values must be\n   * JSON-serialisable primitives (`string`, `number`, `boolean`) as they\n   * travel inside the wire envelope.\n   *\n   * @example\n   * ```ts\n   * export class Cat {\n   *   static Adopted = Action(\"Cat.Adopted\", Distribution.Omnicast(Payload.Adoption));\n   *\n   *   static Renamed = Action(\n   *     \"Cat.Renamed\",\n   *     Distribution.Omnicast<Payload.Cat, { Id: string }>(Payload.Cat),\n   *   );\n   * }\n   *\n   * export class Cattery {\n   *   static Opened = Action(\"Cattery.Opened\", Distribution.Omnicast());\n   * }\n   * ```\n   */\n  export function Omnicast(): OmnicastDistribution<never>;\n  export function Omnicast<T, C extends Filter = never>(\n    schema: Schema<T>,\n  ): OmnicastDistribution<T, C>;\n  export function Omnicast<T, C extends Filter = never>(\n    schema?: Schema<T>,\n  ): OmnicastDistribution<T, C> {\n    return { [Brand.Omnicast]: schema ?? null };\n  }\n}\n\n/**\n * Lifecycle phase of a component using useActions.\n * Tracks whether the component is in the process of mounting, fully mounted,\n * unmounting, or completely unmounted.\n *\n * @example\n * ```ts\n * actions.useAction(Actions.Counter, (context, payload) => {\n *   if (context.phase === Phase.Mounting) {\n *     // Handler called during mount (e.g., cached distributed action value)\n *   } else if (context.phase === Phase.Mounted) {\n *     // Handler called after component is fully mounted\n *   }\n * });\n * ```\n */\nexport enum Phase {\n  /** Component is in the process of mounting (before useLayoutEffect completes). */\n  Mounting = \"mounting\",\n  /** Component has fully mounted (after useLayoutEffect). */\n  Mounted = \"mounted\",\n  /** Component is in the process of unmounting. */\n  Unmounting = \"unmounting\",\n  /** Component has fully unmounted. */\n  Unmounted = \"unmounted\",\n}\n\n/**\n * Primary key type for identifying entities in collections.\n * Can be undefined (not yet assigned), a symbol (temporary/local), or a concrete value T.\n *\n * @template T - The concrete primary key type (e.g., string, number)\n */\nexport type Pk<T> = undefined | symbol | T;\n\n/**\n * Maybe-present field type &mdash; a value that may be a concrete `T`,\n * or `null` / `undefined` while loading, awaiting a fetch, or before\n * upstream data has arrived. Use this for model fields whose presence\n * is determined by async or external state.\n *\n * @template T - The concrete value type\n */\nexport type Maybe<T> = T | null | undefined;\n\n/**\n * Base constraint type for model state objects.\n * Models must be plain objects with string keys.\n *\n * @template M - The specific model shape\n */\nexport type Model<M = Record<string, unknown>> = M;\n\n/**\n * Branded type for action objects created with `Action()`.\n * The phantom type parameters carry the payload and channel types at the type level.\n *\n * Actions wrap an internal symbol (used as event emitter keys) in a callable object.\n * When a channel type is specified, the action can be called to create a channeled dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never = no channel)\n *\n * @example\n * ```ts\n * // Action without channel support\n * const Increment = Action<number>(\"Increment\");\n * dispatch(Increment, 5);\n *\n * // Action with channel support\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n * dispatch(UserUpdated, user);                    // broadcast to all handlers\n * dispatch(UserUpdated({ UserId: 5 }), user);     // channeled dispatch\n * ```\n */\nexport type HandlerPayload<\n  P = unknown,\n  C extends Filter = never,\n  Name extends string = string,\n> = {\n  readonly [Brand.Action]: symbol;\n  readonly [Brand.Payload]: P;\n  readonly [Brand.Name]: Name;\n  readonly [Brand.Broadcast]?: boolean;\n} & ([C] extends [never]\n  ? unknown\n  : {\n      (channel: C): ChanneledAction<P, C, Name>;\n    });\n\n/**\n * Branded type returned by `Lifecycle.Mount`, `Lifecycle.Paint`,\n * `Lifecycle.Unmount`, `Lifecycle.Error`, and `Lifecycle.Update`.\n * Structurally identical to a `HandlerPayload` but carries a phantom\n * `Brand.Lifecycle` brand whose value is the lifecycle's literal kind. The\n * brand is what lets `useAction` and `Handlers` resolve `Lifecycle.Update`'s\n * payload to `Partial<DeepReadonly<D>>` (against the surrounding `useActions`\n * data generic) instead of the factory-level `Record<string, unknown>`\n * placeholder &mdash; a user-defined `Action<P>(\"Update\")` would have\n * `Name = \"Update\"` but no `Brand.Lifecycle`, so it falls into the generic\n * payload overload as expected.\n *\n * @template P Payload type for the lifecycle.\n * @template C Channel filter (always `never` for lifecycles &mdash; they are\n *   not channeled).\n * @template Name Literal name (`\"Mount\"`, `\"Paint\"`, `\"Unmount\"`, `\"Error\"`, `\"Update\"`).\n */\nexport type LifecyclePayload<\n  P = unknown,\n  C extends Filter = never,\n  Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n  readonly [Brand.Lifecycle]: Name;\n};\n\n/**\n * Result of calling a `Lifecycle.Reactive` static with a value at the\n * `useAction` site (e.g. `Actions.User(user)`). Carries the observed\n * value alongside the action brands so the registration can diff it\n * against the previous render and dispatch through the standard handler\n * pipeline when it changes.\n *\n * Mirrors {@link ChanneledAction} &mdash; a per-render wrapper produced\n * by calling the declared static &mdash; but binds a payload value rather\n * than a channel filter. Bindings are subscribe-only: they are admitted\n * by `useAction` and excluded from `dispatch`.\n *\n * @template P The observed value type; also the handler payload type.\n * @template Name Literal name supplied to `Lifecycle.Reactive(name)`.\n */\nexport type ReactiveBinding<P = unknown, Name extends string = string> = {\n  readonly [Brand.Action]: symbol;\n  readonly [Brand.Payload]: P;\n  readonly [Brand.Name]: Name;\n  readonly [Brand.Reactive]: true;\n  readonly value: P;\n};\n\n/**\n * Branded type returned by `Lifecycle.Reactive`. Declared as a static on\n * an Actions class like every other lifecycle, and callable with the\n * observed value to produce a {@link ReactiveBinding} at the `useAction`\n * site. The `Brand.Lifecycle` value is always `\"Reactive\"` (the lifecycle\n * kind), independent of the user-supplied `Name`.\n *\n * @template P The observed value type; also the handler payload type.\n * @template Name Literal name supplied to `Lifecycle.Reactive(name)`.\n */\nexport type ReactivePayload<\n  P = unknown,\n  Name extends string = string,\n> = HandlerPayload<P, never, Name> & {\n  readonly [Brand.Lifecycle]: \"Reactive\";\n  (value: P): ReactiveBinding<P, Name>;\n};\n\n/**\n * Result of calling an action with a channel argument.\n * Contains the action reference and the channel data for filtered dispatch.\n *\n * @template P - The payload type for the action\n * @template C - The channel type\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * // UserUpdated({ UserId: 5 }) returns ChanneledAction<User, { UserId: number }>\n * dispatch(UserUpdated({ UserId: 5 }), user);\n * ```\n */\nexport type ChanneledAction<\n  P = unknown,\n  C = unknown,\n  Name extends string = string,\n> = {\n  readonly [Brand.Action]: symbol;\n  readonly [Brand.Payload]: P;\n  readonly [Brand.Channel]: C;\n  readonly [Brand.Name]: Name;\n  readonly [Brand.Broadcast]?: boolean;\n  readonly channel: C;\n};\n\n/**\n * `ChanneledAction` that carries the broadcast brand. Produced by calling\n * a broadcast `Action` with a channel (e.g. `Resource.action({ id: 5 })`,\n * or `UserBroadcast({ UserId: 5 })`). Any boundary subscriber can listen\n * to one, so it's admitted by `Subscribable<AC>` regardless of `AC`\n * &mdash; the same carve-out applied to `Lifecycle.Fault` / `Lifecycle.Env`.\n */\nexport type BroadcastChanneled<\n  P = unknown,\n  C = unknown,\n  Name extends string = string,\n> = ChanneledAction<P, C, Name> & {\n  readonly [Brand.Broadcast]: true;\n};\n\n/**\n * Branded type for broadcast action objects created with `Action()` and `Distribution.Broadcast`.\n * Broadcast actions are sent to all mounted components. Values are cached so that\n * late-mounting components receive the most recent payload.\n *\n * Late-mounting components receive the most recent cached payload via their\n * `useAction` handler during mount. Use `peek()` in a `Lifecycle.Mount` handler\n * to check whether a cached value exists before performing default fetches.\n *\n * This type extends `HandlerPayload<P, C>` with an additional brand to enforce at compile-time\n * that only broadcast actions can be passed to `context.actions.final()`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```ts\n * const SignedOut = Action<User>(\"SignedOut\", Distribution.Broadcast);\n *\n * // Resolve the latest value inside a handler\n * const user = await context.actions.final(SignedOut);\n * ```\n */\nexport type BroadcastPayload<\n  P = unknown,\n  C extends Filter = never,\n  Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n  readonly [Brand.Broadcast]: true;\n};\n\n/**\n * Branded type for multicast action objects created with `Action()` and `Distribution.Multicast`.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * When dispatching a multicast action, you MUST provide the scope name as the third argument:\n * ```ts\n * actions.dispatch(Actions.Multicast.Update, payload, { scope: Actions.Multicast.Scope });\n * ```\n *\n * Components receive multicast events only if they are descendants of a `<Scope of={...}>`.\n *\n * @template P - The payload type for the action\n * @template C - The channel type for channeled dispatches (defaults to never)\n *\n * @example\n * ```tsx\n * export enum Scope {\n *   Counter = \"counter\",\n * }\n *\n * class MulticastActions {\n *   static Update = Action<number>(\"Update\", Distribution.Multicast(Scope.Counter));\n * }\n *\n * // Reference from component-level Actions\n * class Actions {\n *   static Multicast = MulticastActions;\n * }\n *\n * // Wrap the subtree where the scope applies via the withScope HOC.\n * export default withScope(Scope.Counter, function Counters() {\n *   return (\n *     <>\n *       <CounterA />\n *       <CounterB />\n *     </>\n *   );\n * });\n *\n * // Dispatch — the scope is read from the action itself.\n * actions.dispatch(Actions.Multicast.Update, 42);\n * ```\n */\nexport type MulticastPayload<\n  P = unknown,\n  C extends Filter = never,\n  Name extends string = string,\n> = HandlerPayload<P, C, Name> & {\n  readonly [Brand.Multicast]: true;\n};\n\n/**\n * Minimal runtime validator contract satisfied by Zod schemas (and any\n * library exposing a Zod-style `parse`): given an untrusted value, either\n * return the typed value or throw. Used by `Omnicast` actions to validate\n * payloads arriving over the wire before they are dispatched locally.\n */\nexport type Schema<T> = {\n  parse(value: unknown): T;\n};\n\n/**\n * Branded type for omnicast action objects created with `Action(name,\n * Distribution.Omnicast(schema?))`. An omnicast action is a broadcast\n * action that additionally travels between clients when the App is\n * configured with an `sse` endpoint; the brand carries the runtime schema\n * used to validate payloads received from the wire, or `null` for\n * payloadless events.\n */\nexport type OmnicastPayload<\n  P = unknown,\n  C extends Filter = never,\n  Name extends string = string,\n> = ([C] extends [never]\n  ? unknown\n  : {\n      (channel: C): ChanneledAction<P, C, Name> & {\n        readonly [Brand.Omnicast]: null | Schema<P>;\n      };\n    }) &\n  BroadcastPayload<P, C, Name> & {\n    readonly [Brand.Omnicast]: null | Schema<P>;\n  };\n\n/**\n * Extracts the payload type `P` from a `HandlerPayload<P>` or `ChanneledAction<P, C>`.\n * Use this in handler signatures to get the action's payload type.\n *\n * Works with both plain actions and channeled actions:\n * - `Payload<Action<User>>` → `User`\n * - `Payload<ChanneledAction<User, { UserId: number }>>` → `User`\n *\n * @template A - The action type (HandlerPayload or ChanneledAction)\n */\n\nexport type Payload<A> = A extends { readonly [Brand.Payload]: infer P }\n  ? P\n  : never;\n\n/**\n * Filter object for channeled actions.\n * Must be an object where each value is a non-nullable primitive.\n *\n * By convention, use uppercase keys (e.g., `{UserId: 4}` not `{userId: 4}`)\n * to distinguish filter keys from payload properties.\n *\n * **Matching direction:** the subscriber's filter is the constraint;\n * every key the subscriber supplies must be present and equal on the\n * dispatch channel. Extra keys on the dispatch channel are ignored, so a\n * dispatcher is free to be more specific than any single subscriber\n * needs. A subscriber that supplies no keys (uncalled action or empty\n * filter) matches every dispatch.\n *\n * @example\n * ```ts\n * actions.useAction(Actions.User({ UserId: 1 }), handler);\n *\n * actions.dispatch(Actions.User({ UserId: 1 }), payload);                       // Matches (exact)\n * actions.dispatch(Actions.User({ UserId: 2 }), payload);                       // No match (UserId mismatch)\n * actions.dispatch(Actions.User({ UserId: 1, Role: \"admin\" }), payload);        // Matches (extra dispatch keys ignored)\n * actions.dispatch(Actions.User({}), payload);                                  // No match (subscriber asked for UserId)\n * actions.dispatch(Actions.User, payload);                                      // Matches ALL handlers (uncalled bypasses channel filtering)\n * ```\n */\nexport type Filter = Record<\n  string,\n  string | number | bigint | boolean | symbol\n>;\n\n/**\n * Union type representing either a plain action or a channeled action.\n * Used in `useAction` and `dispatch` signatures to accept both forms.\n *\n * @template A - The action type\n *\n * @example\n * ```ts\n * class Actions {\n *   static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\", Distribution.Broadcast);\n * }\n *\n * // Subscribe to updates for a specific user (channeled)\n * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n *   context.actions.produce((draft) => {\n *     draft.model.user = user;\n *   });\n * });\n *\n * // Dispatch to specific user (channeled)\n * actions.dispatch(Actions.UserUpdated({ UserId: user.id }), user);\n *\n * // Dispatch to ALL handlers (plain)\n * actions.dispatch(Actions.UserUpdated, user);\n * ```\n */\nexport type ActionOrChanneled<A extends HandlerPayload = HandlerPayload> =\n  A | ChanneledAction;\n\n/**\n * Type guard that produces a compile-time error if an async function is\n * passed. Used to enforce synchronous callbacks in `produce()`.\n *\n * The `[F]` tuple wrapping prevents distribution over function unions, and\n * checking the actual signature (`(...args: never[]) => Promise<unknown>`)\n * sidesteps TypeScript's lenient `Promise<void>`→`void` assignability that\n * would otherwise let an async recipe satisfy a `(draft) => void`\n * constraint. Async F collapses the argument type to `never`, which no\n * function value can satisfy.\n *\n * @internal\n */\ntype AssertSync<F> = [F] extends [(...args: never[]) => Promise<unknown>]\n  ? never\n  : F;\n\n/**\n * Base type for data props passed to useActions.\n * Represents any object that can be captured as reactive data.\n */\nexport type Props = Record<string, unknown>;\n\n/**\n * Constraint type for action containers.\n * Actions are symbols grouped in an object (typically a class with static properties).\n */\nexport type Actions = object;\n\n/**\n * Internal result container for tracking Immertation processes during action execution.\n * @internal\n */\nexport type Result = {\n  processes: Set<Process>;\n};\n\nexport type HandlerContext<\n  M extends Model | void,\n  AC extends Actions | void,\n  D extends Props = Props,\n  E extends Env = Env,\n> = {\n  readonly model: DeepReadonly<M>;\n  readonly phase: Phase;\n  readonly task: CurrentTask;\n  readonly data: DeepReadonly<D>;\n  readonly tasks: ReadonlySet<Task>;\n  readonly env: Readonly<E>;\n  readonly actions: {\n    produce<\n      F extends (draft: {\n        model: M;\n        env: E;\n        readonly inspect: Readonly<Inspect<M>>;\n      }) => void,\n    >(\n      ƒ: F & AssertSync<F>,\n    ): void;\n    dispatch(\n      action: NoPayloadActions<WithoutOmnicast<Dispatchable<AC>>>,\n    ): Promise<void>;\n    dispatch<A extends WithPayloadActions<WithoutOmnicast<Dispatchable<AC>>>>(\n      action: A,\n      payload: Payload<A>,\n    ): Promise<void>;\n    dispatch(\n      action: NoPayloadActions<OmnicastOnly<Dispatchable<AC>>>,\n      audience: Audience,\n    ): Promise<void>;\n    dispatch<A extends WithPayloadActions<OmnicastOnly<Dispatchable<AC>>>>(\n      action: A,\n      audience: Audience,\n      payload: Payload<A>,\n    ): Promise<void>;\n    /**\n     * Mutates the SSE connection's tag set, changing which\n     * `Audience.Private(tags)` dispatches this client receives. `add` and\n     * `remove` are variadic and idempotent &mdash; only tags that actually\n     * change the set reach the server. The returned promises resolve once\n     * the server has acknowledged the mutation, so awaiting a mutator\n     * before a dependent dispatch guarantees the subscription is\n     * registered ahead of any tag-targeted replies. Mutations are\n     * remembered and re-applied after reconnects. When the App has no\n     * `sse` endpoint configured, the mutators resolve as no-ops.\n     */\n    tag: {\n      add(...tags: readonly [string, ...string[]]): Promise<void>;\n      remove(...tags: readonly [string, ...string[]]): Promise<void>;\n      /** True when the connection holds **all** of the supplied tags. */\n      has(...tags: readonly [string, ...string[]]): boolean;\n      clear(): Promise<void>;\n    };\n    annotate<T>(value: T, operation?: Operation): T;\n    readonly inspect: Readonly<Inspect<M>>;\n    resource: ResourceDispatcher;\n    final<T>(\n      action: BroadcastPayload<T> | MulticastPayload<T>,\n    ): Promise<T | null>;\n    peek<T>(action: BroadcastPayload<T> | MulticastPayload<T>): T | null;\n  };\n};\n\n/**\n * Return type for the useActions hook.\n *\n * A tuple containing:\n * 1. The current model state of type M\n * 2. An actions object with dispatch and inspect capabilities\n * 3. The current data snapshot of type D &mdash; the same React-owned values\n *    that handlers read via `context.data`, exposed here for JSX consumption\n *    so the view and the handler share a single named source of truth.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @example\n * ```tsx\n * const [model, actions, data] = useActions<Model, typeof Actions, Data>(\n *   model,\n *   () => ({ user, theme }),\n * );\n *\n * // Access state\n * model.count;\n *\n * // Dispatch actions\n * actions.dispatch(Actions.Increment, 5);\n *\n * // Read React-owned dependencies in JSX (same values as context.data)\n * data.user.name;\n *\n * // Check pending state\n * actions.inspect.count.pending();\n * ```\n */\n/**\n * Utility type for defining a single action handler function.\n * Use this when you need to type a specific handler directly.\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template K - The action key (keyof AC) — determines payload type via lookup\n * @template D - Optional data/props type (defaults to Props)\n *\n * @see {@link Handlers} for the recommended HKT pattern\n */\nexport type Handler<\n  M extends Model | void,\n  AC extends Actions | void,\n  K extends keyof AC & string,\n  D extends Props = Props,\n  E extends Env = Env,\n> = (\n  context: HandlerContext<M, AC, D, E>,\n  ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n    ? []\n    : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n) => void | Promise<void> | AsyncGenerator | Generator;\n\n/**\n * String keys of `AC` excluding inherited `prototype` from class constructors.\n * When action containers are classes (`typeof MyActions`), TypeScript includes\n * `\"prototype\"` in `keyof`. Excluding it prevents `prototype` from appearing\n * as a handler key and avoids recursion into Function internals.\n */\ntype OwnKeys<AC> = Exclude<keyof AC & string, \"prototype\">;\n\n/**\n * Recursively flattens an actions class into the union of its leaf action\n * types. A \"leaf\" is any property whose own string keys are empty &mdash; the\n * branded `HandlerPayload` / `BroadcastPayload` / `MulticastPayload` values\n * produced by `Action(...)` and `Lifecycle.*()`. Nested namespace classes\n * (e.g. `static Broadcast = BroadcastActions`) are descended into.\n *\n * Used to constrain `dispatch` and `useAction` so that only actions owned by\n * the component's `AC` (plus the global `Lifecycle.Fault` /\n * `Lifecycle.Env`) can be referenced.\n */\nexport type LeafActions<AC> = AC extends void\n  ? never\n  : {\n      [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n        ? AC[K]\n        : LeafActions<AC[K]>;\n    }[OwnKeys<AC>];\n\n/**\n * Maps each action in a union to its channeled-call variant, when one exists.\n * Distributes over unions so a mixed bag of leaf actions produces the union\n * of their `ChanneledAction<P, C>` results.\n */\nexport type ChanneledOf<A> =\n  A extends OmnicastPayload<infer P, infer C>\n    ? [C] extends [never]\n      ? never\n      : ChanneledAction<P, C> & {\n          readonly [Brand.Omnicast]: null | Schema<P>;\n        }\n    : A extends HandlerPayload<infer P, infer C>\n      ? [C] extends [never]\n        ? never\n        : ChanneledAction<P, C>\n      : never;\n\n/**\n * Everything `dispatch` accepts for a given `AC`: leaf actions on the class\n * and their channeled-call variants. The shared `Lifecycle.Fault` broadcast\n * is excluded — it's library-internal and not user-dispatchable.\n */\nexport type Dispatchable<AC> = LeafActions<AC> | ChanneledOf<LeafActions<AC>>;\n\n/**\n * Everything `useAction` will subscribe to for a given `AC`. Includes:\n *\n * - `Dispatchable<AC>` &mdash; leaf actions on `AC` plus their channeled\n *   variants.\n * - `Lifecycle.Fault` / `Lifecycle.Env` &mdash; shared boundary broadcasts.\n * - Any `LifecyclePayload` (`Lifecycle.Mount()`, `Lifecycle.Unmount()`,\n *   etc.) &mdash; the runtime scans the handler registry for a matching\n *   lifecycle brand on emit, so a self-declared lifecycle outside `AC`\n *   still fires.\n * - Any broadcast-branded channeled action &mdash; resource auto-broadcasts\n *   (`resource.x.action(...)`) live outside `AC` but any boundary\n *   subscriber can listen to them.\n * - Any `ReactiveBinding` &mdash; the result of calling a\n *   `Lifecycle.Reactive` static with a value (`Actions.User(user)`).\n *   Bindings are subscribe-only, so they appear here but not in\n *   `Dispatchable<AC>`.\n */\nexport type Subscribable<AC> =\n  | Dispatchable<AC>\n  | typeof Lifecycle.Fault\n  | typeof Lifecycle.Env\n  | LifecyclePayload<unknown, never, string>\n  | BroadcastChanneled\n  | ReactiveBinding;\n\n/**\n * Subset of a union of actions whose payload type is `never`. Used to split\n * `dispatch`/`useAction` into a no-payload and a with-payload overload so\n * TypeScript reports a clear \"no overload matches\" error instead of widening\n * the inferred action type when constraints don't match.\n */\nexport type NoPayloadActions<U> = Extract<\n  U,\n  { readonly [Brand.Payload]: never }\n>;\n\n/** Subset of a union of actions whose payload type is non-`never`. */\nexport type WithPayloadActions<U> = Exclude<\n  U,\n  { readonly [Brand.Payload]: never }\n>;\n\n/**\n * Subset of a union of actions carrying the omnicast brand. Omnicast\n * dispatches require an explicit {@link Audience} argument, so `dispatch`\n * splits its overloads on this boundary.\n */\nexport type OmnicastOnly<U> = Extract<\n  U,\n  { readonly [Brand.Omnicast]: null | Schema<unknown> }\n>;\n\n/** Subset of a union of actions without the omnicast brand. */\nexport type WithoutOmnicast<U> = Exclude<\n  U,\n  { readonly [Brand.Omnicast]: null | Schema<unknown> }\n>;\n\n/**\n * Explicit delivery audience for an omnicast dispatch. Omnicast actions\n * leave the machine, so the audience is a **required** second argument of\n * `dispatch` (before the payload, when there is one) &mdash; there is no\n * public-by-default. Construct one with `Audience.Public()` or\n * `Audience.Private(tags)`.\n */\nexport type Audience = {\n  readonly tags: null | readonly string[];\n};\n\nexport const Audience = {\n  /**\n   * Declares an omnicast dispatch as deliverable to **every** connected\n   * client. Deliberately explicit &mdash; broadcasting to the world should\n   * read as a decision at the call site, not a default.\n   *\n   * @example\n   * ```ts\n   * await context.actions.dispatch(\n   *   Actions.Omnicast.Cat.Adopted,\n   *   Audience.Public(),\n   *   adoption,\n   * );\n   * ```\n   */\n  Public(): Audience {\n    return { tags: null };\n  },\n  /**\n   * Restricts an omnicast dispatch to clients holding **all** of the\n   * given tags (holding extras is fine). At least one tag is required\n   * &mdash; an empty list would silently behave as `Audience.Public()`,\n   * so the parameter type demands a non-empty tuple.\n   *\n   * @example\n   * ```ts\n   * await context.actions.dispatch(\n   *   Actions.Omnicast.Cat.Adopted,\n   *   Audience.Private([\"vip\"]),\n   *   adoption,\n   * );\n   * ```\n   */\n  Private(tags: readonly [string, ...string[]]): Audience {\n    return { tags };\n  },\n};\n\n/**\n * Recursive mapped type for action handlers that mirrors the action class hierarchy.\n *\n * For leaf actions (values with no own string keys, i.e. `HandlerPayload`), produces\n * a handler function signature. For namespace objects (containing nested actions),\n * produces a nested `Handlers` object.\n *\n * Access handlers using bracket notation matching the action structure:\n *\n * @template M - The model type\n * @template AC - The actions class type\n * @template D - Optional data/props type (defaults to Props)\n *\n * @example\n * ```ts\n * import { Action, Distribution, type Handlers } from \"march-hare\";\n *\n * class BroadcastActions {\n *   static PaymentSent = Action(\"PaymentSent\", Distribution.Broadcast);\n *   static PaymentLink = Action<PaymentLinkData>(\n *     \"PaymentLink\",\n *     Distribution.Broadcast,\n *   );\n * }\n *\n * class Actions {\n *   static SetName = Action<string>(\"SetName\");\n *   static Broadcast = BroadcastActions;\n * }\n *\n * type H = Handlers<Model, typeof Actions>;\n *\n * // Flat actions\n * export const handleSetName: H[\"SetName\"] = (context, name) => { ... };\n *\n * // Nested actions use chained bracket notation\n * export const handlePaymentSent: H[\"Broadcast\"][\"PaymentSent\"] = (context) => { ... };\n * ```\n */\nexport type Handlers<\n  M extends Model | void,\n  AC extends Actions | void,\n  D extends Props = Props,\n  RootAC extends Actions | void = AC,\n  E extends Env = Env,\n> = {\n  [K in OwnKeys<AC>]: OwnKeys<AC[K]> extends never\n    ? AC[K] extends { readonly [Brand.Lifecycle]: \"Update\" }\n      ? (\n          context: HandlerContext<M, RootAC, D, E>,\n          changes: Partial<DeepReadonly<D>>,\n        ) => void | Promise<void> | AsyncGenerator | Generator\n      : (\n          context: HandlerContext<M, RootAC, D, E>,\n          ...args: [Payload<AC[K] & HandlerPayload<unknown>>] extends [never]\n            ? []\n            : [payload: Payload<AC[K] & HandlerPayload<unknown>>]\n        ) => void | Promise<void> | AsyncGenerator | Generator\n    : Handlers<M, AC[K] & Actions, D, RootAC, E>;\n};\n\nexport type UseActions<\n  M extends Model | void,\n  AC extends Actions | void,\n  D extends Props = Props,\n  E extends Env = Env,\n> = [\n  Readonly<M>,\n  {\n    /**\n     * Dispatches an action with an optional payload. Multicast actions read\n     * their scope from the action declaration, so no extra options are\n     * required at the call site.\n     */\n    dispatch(\n      action: NoPayloadActions<WithoutOmnicast<Dispatchable<AC>>>,\n    ): Promise<void>;\n    dispatch<A extends WithPayloadActions<WithoutOmnicast<Dispatchable<AC>>>>(\n      action: A,\n      payload: Payload<A>,\n    ): Promise<void>;\n    dispatch(\n      action: NoPayloadActions<OmnicastOnly<Dispatchable<AC>>>,\n      audience: Audience,\n    ): Promise<void>;\n    dispatch<A extends WithPayloadActions<OmnicastOnly<Dispatchable<AC>>>>(\n      action: A,\n      audience: Audience,\n      payload: Payload<A>,\n    ): Promise<void>;\n    inspect: Inspect<M>;\n    /**\n     * Streams broadcast values declaratively in JSX using a render-prop pattern.\n     *\n     * Subscribes to the given broadcast action and re-renders when a new value\n     * is dispatched. Returns `null` until the first dispatch. The renderer\n     * receives the value and an inspect proxy for annotation tracking.\n     *\n     * @param action - The broadcast action to subscribe to.\n     * @param renderer - Callback that receives value and inspect, returns React nodes.\n     * @returns React nodes from the renderer, or null if no value has been dispatched.\n     *\n     * @example\n     * ```tsx\n     * return (\n     *   <div>\n     *     {actions.stream(Actions.Broadcast.User, (user, inspect) => (\n     *       <span>{user.name}</span>\n     *     ))}\n     *   </div>\n     * );\n     * ```\n     */\n    stream(\n      action: typeof Lifecycle.Env,\n      renderer: (value: Readonly<E>, inspect: Inspect<E>) => React.ReactNode,\n    ): React.ReactNode;\n    stream<T extends object | null>(\n      action: BroadcastPayload<T> | BroadcastChanneled<T>,\n      renderer: (value: T, inspect: Inspect<T>) => React.ReactNode,\n    ): React.ReactNode;\n  },\n  DeepReadonly<D>,\n] & {\n  /**\n   * Dispatches an action with an optional payload &mdash; same as\n   * `result[1].dispatch`, exposed on the tuple itself so call sites that\n   * already have `actions` in scope can write `actions.dispatch(...)`\n   * without indexing into `actions[1]`.\n   */\n  dispatch(\n    action: NoPayloadActions<WithoutOmnicast<Dispatchable<AC>>>,\n  ): Promise<void>;\n  dispatch<A extends WithPayloadActions<WithoutOmnicast<Dispatchable<AC>>>>(\n    action: A,\n    payload: Payload<A>,\n  ): Promise<void>;\n  dispatch(\n    action: NoPayloadActions<OmnicastOnly<Dispatchable<AC>>>,\n    audience: Audience,\n  ): Promise<void>;\n  dispatch<A extends WithPayloadActions<OmnicastOnly<Dispatchable<AC>>>>(\n    action: A,\n    audience: Audience,\n    payload: Payload<A>,\n  ): Promise<void>;\n\n  /**\n   * Registers an action handler with the current scope.\n   * Types are pre-baked from the `channel.use(...)` call, so no type\n   * parameter is needed.\n   *\n   * Supports two subscription patterns:\n   * 1. **Plain action** - Receives ALL dispatches for that action (including channeled ones)\n   * 2. **Channeled action** `Action(channel)` - Receives only dispatches matching the channel\n   *\n   * @param action - The action or channeled action (e.g., `Action({ UserId: 1 })`)\n   * @param handler - The handler function receiving context and payload\n   *\n   * @example\n   * ```ts\n   * const context = useContext<Model, typeof Actions>();\n   * const actions = context.useActions(model);\n   *\n   * // Subscribe to ALL UserUpdated events\n   * actions.useAction(Actions.UserUpdated, (context, user) => {\n   *   // Fires for any UserUpdated dispatch\n   * });\n   *\n   * // Subscribe to UserUpdated for a specific user only (channeled)\n   * actions.useAction(Actions.UserUpdated({ UserId: props.userId }), (context, user) => {\n   *   // Only fires when dispatched with matching channel\n   * });\n   * ```\n   */\n  useAction(\n    action: NoPayloadActions<Subscribable<AC>>,\n    handler: (\n      context: HandlerContext<M, AC, D, E>,\n    ) => void | Promise<void> | AsyncGenerator | Generator,\n  ): void;\n  useAction(\n    action: typeof Lifecycle.Env,\n    handler: (\n      context: HandlerContext<M, AC, D, E>,\n      env: Readonly<E>,\n    ) => void | Promise<void> | AsyncGenerator | Generator,\n  ): void;\n  useAction<\n    A extends Extract<\n      Subscribable<AC>,\n      { readonly [Brand.Lifecycle]: \"Update\" }\n    >,\n  >(\n    action: A,\n    handler: (\n      context: HandlerContext<M, AC, D, E>,\n      changes: Partial<DeepReadonly<D>>,\n    ) => void | Promise<void> | AsyncGenerator | Generator,\n  ): void;\n  useAction<A extends WithPayloadActions<Subscribable<AC>>>(\n    action: A,\n    handler: (\n      context: HandlerContext<M, AC, D, E>,\n      payload: Payload<A>,\n    ) => void | Promise<void> | AsyncGenerator | Generator,\n  ): void;\n};\n\n/**\n * Stable, typed dispatch function for the actions class `AC`. Same call\n * signatures as `actions.dispatch` returned by `useActions`, available\n * before the paired `useActions` has run via {@link Context}.\n */\nexport type Dispatch<AC extends Actions | void> = {\n  (action: NoPayloadActions<WithoutOmnicast<Dispatchable<AC>>>): Promise<void>;\n  <A extends WithPayloadActions<WithoutOmnicast<Dispatchable<AC>>>>(\n    action: A,\n    payload: Payload<A>,\n  ): Promise<void>;\n  (\n    action: NoPayloadActions<OmnicastOnly<Dispatchable<AC>>>,\n    audience: Audience,\n  ): Promise<void>;\n  <A extends WithPayloadActions<OmnicastOnly<Dispatchable<AC>>>>(\n    action: A,\n    audience: Audience,\n    payload: Payload<A>,\n  ): Promise<void>;\n};\n\n/**\n * Handle returned by `useContext<M, AC, D>()`. Exposes\n * `dispatch(action, payload?)` and a `useActions` method that materialises\n * the component-local model and reactive data against the same dispatch\n * target. Generics are declared on `useContext`; `useActions` inherits\n * them &mdash; the call site does not re-state `Model` / `Actions` /\n * `Data`.\n *\n * Note: this `Context` type is distinct from React's `useContext` /\n * `React.Context` &mdash; it's the March Hare action surface returned by\n * the `useContext` hook of this library.\n */\nexport type Context<\n  M extends Model | void,\n  AC extends Actions | void,\n  D extends Props = Props,\n  E extends Env = Env,\n> = {\n  readonly actions: { dispatch: Dispatch<AC> };\n  /**\n   * Typed bag of handler factories bound to `M`. Methods accept lodash-style\n   * dotted paths with array indices (e.g. `\"a.b.c\"`, `\"items.0.id\"`) and\n   * autocomplete from the model. See {@link WithHandle}.\n   */\n  readonly with: WithHandle<M>;\n  useActions(getData?: () => D): UseActions<M, AC, D, E>;\n  useActions(\n    model: M extends void ? never : M,\n    getData?: () => D,\n  ): UseActions<M, AC, D, E>;\n};\n","import * as React from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { Env as EnvType, Props } from \"./types.ts\";\nimport { Context } from \"./utils.ts\";\nimport { useBroadcast } from \"../broadcast/index.tsx\";\nimport { EnvSymbol } from \"../../../types/index.ts\";\n\nexport { useEnv } from \"./utils.ts\";\n\n/**\n * Provides a per-Boundary {@link EnvType} value to every component inside\n * the boundary. Usually wired in via the `<Boundary env={initial}>`\n * prop rather than used directly.\n *\n * The Env is **not** reactive. Mutating it does not trigger a\n * re-render. Drive view state through the model; use the Env for\n * cross-handler coordination.\n */\n\nexport function Env({ initial, children }: Props): React.ReactNode {\n  const ref = React.useRef<EnvType>(initial);\n  const broadcast = useBroadcast();\n\n  if (G.isUndefined(broadcast.getCached(EnvSymbol))) {\n    broadcast.setCache(EnvSymbol, ref.current, undefined);\n  }\n\n  return <Context.Provider value={ref}>{children}</Context.Provider>;\n}\n","import * as React from \"react\";\nimport type { Invocation } from \"../../../resource/index.ts\";\n\n/**\n * Per-caller record stored in the {@link Sharing} registry. The\n * `promise` is the shared in-flight fetch, `controller` is the\n * detached `AbortController` driving it, and `refs` tracks how many\n * callers are currently waiting. When the last caller releases (its\n * `context.task.controller` aborts), the entry aborts its controller\n * so the underlying work is cancelled rather than orphaned.\n *\n * @internal\n */\nexport type Share<T = unknown> = {\n  promise: Promise<T>;\n  controller: AbortController;\n  refs: number;\n};\n\n/**\n * Per-`<Boundary>` registry for the default coalesce path. Outer map\n * keys on the `Invocation.run` function identity (stable per Resource\n * via the `build()` closure); inner map keys on\n * `JSON.stringify(params)`. While an entry exists every caller for the\n * same Resource + params joins the same {@link Share} record and\n * resolves against its promise.\n *\n * Lifted into React context so each `<app.Boundary>` owns its own\n * registry &mdash; two `App` instances in the same tree cannot collide\n * on the same `(Resource, params)` pair.\n *\n * @internal\n */\nexport type Sharing = WeakMap<\n  Invocation<unknown, object>[\"run\"],\n  Map<string, Share>\n>;\n\nconst fallback: Sharing = new WeakMap();\n\n/**\n * React context exposing the per-Boundary sharing registry. The\n * fallback is a fresh `WeakMap` used when `useSharing()` is read\n * outside any `<Boundary>` &mdash; calls work but never share with any\n * other component.\n *\n * @internal\n */\nexport const Context = React.createContext<Sharing>(fallback);\n\n/**\n * Wraps children with a Boundary-scoped sharing registry for the\n * default coalesce path. Rendered as part of {@link Boundary}; not\n * exposed standalone.\n *\n * @internal\n */\nexport function SharingProvider({\n  children,\n}: {\n  children: React.ReactNode;\n}): React.ReactElement {\n  const registry = React.useMemo<Sharing>(() => new WeakMap(), []);\n  return <Context.Provider value={registry}>{children}</Context.Provider>;\n}\n\n/**\n * Hook returning the per-Boundary sharing registry. Used by the\n * default coalesce path inside `useActions`.\n *\n * @internal\n */\nexport function useSharing(): Sharing {\n  return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport type { Tap } from \"./types.ts\";\n\nconst noop: Tap = () => {};\n\n/**\n * React context carrying the active {@link Tap} observer for the\n * surrounding `<Boundary>`. Defaults to a no-op so `useTap()` callers\n * never need to null-check.\n */\nexport const Context = React.createContext<Tap>(noop);\n\n/**\n * Hook returning the active tap observer. Always returns a callable\n * &mdash; if no `<Boundary tap={...}>` is mounted above, calls are\n * silent no-ops with no allocation cost beyond the function call itself.\n */\nexport function useTap(): Tap {\n  return React.useContext(Context);\n}\n","import type { Task } from \"../boundary/components/tasks/types.ts\";\n\n/**\n * Reasons why an action error occurred.\n */\nexport enum Reason {\n  /** Action was aborted &mdash; superseded by a newer dispatch, the\n   *  component unmounted, or `task.controller.abort()` was called. */\n  Aborted,\n  /** A generic error thrown in the user's action handler. */\n  Errored,\n  /** An omnicast payload was rejected by its action's schema &mdash;\n   *  either an outgoing dispatch failing fast on the sender, or an\n   *  envelope arriving over the wire that did not validate. */\n  Rejected,\n}\n\n/**\n * Details about an error that occurred during action execution.\n *\n * Faults are delivered through the global `Lifecycle.Fault` broadcast.\n * Subscribe with `actions.useAction(Lifecycle.Fault, handler)` near the\n * root of your application for app-level concerns (logging, sign-out on\n * auth failure, abort cascades). For component-local recovery, use a\n * `Lifecycle.Error()` factory instead.\n *\n * @template E Custom error types to include in the union with Error.\n */\nexport type Fault<E extends Error = never> = {\n  /** The reason for the error. */\n  reason: Reason;\n  /** The Error object that was thrown. */\n  error: Error | E;\n  /** The name of the action that caused the error (e.g., \"Increment\"). */\n  action: string;\n  /** Whether the component has a `Lifecycle.Error()` handler registered. */\n  handled: boolean;\n  /**\n   * All currently running tasks across the application.\n   * Use this to programmatically abort in-flight actions during error recovery\n   * (e.g., on 403/500 responses to prevent cascading failures).\n   *\n   * @example\n   * ```ts\n   * actions.useAction(Lifecycle.Fault, (context, fault) => {\n   *   if (fault.reason === Reason.Errored) {\n   *     for (const task of fault.tasks) task.controller.abort();\n   *   }\n   * });\n   * ```\n   */\n  tasks: ReadonlySet<Task>;\n  /**\n   * Re-dispatches the failed action with the original payload and channel,\n   * routed through the same emitter (broadcast, multicast, or unicast) as the\n   * original dispatch. Resolves when every triggered handler has settled.\n   *\n   * `retry` is independent of the failed task's `AbortController`: even when\n   * the failure was an `Aborted` reason, calling `retry()` fires a fresh\n   * dispatch with a new task. The closure stays callable after the fault\n   * handler returns, which makes it safe to surface from a UI &mdash; e.g. a\n   * \"Retry\" button bound to `fault.retry`.\n   *\n   * @example\n   * ```ts\n   * actions.useAction(Lifecycle.Fault, (_context, fault) => {\n   *   if (fault.reason === Reason.Errored && isTransient(fault.error)) {\n   *     void fault.retry();\n   *   }\n   * });\n   * ```\n   */\n  retry: () => Promise<void>;\n};\n","export { Reason } from \"./types\";\nexport type { Fault } from \"./types\";\n\n/**\n * Error thrown when an action is aborted, e.g., when a component unmounts\n * or when a newer dispatch cancels a previous run. Works across all platforms\n * including React Native where `DOMException` is unavailable.\n *\n * The instance's `name` field stays as `\"AbortError\"` so it can be\n * pattern-matched alongside native `DOMException`s and ky/fetch aborts.\n *\n * @example\n * ```ts\n * throw new Aborted(\"User cancelled the request\");\n * ```\n */\nexport class Aborted extends Error {\n  override name = \"AbortError\";\n  constructor(message = \"Aborted\") {\n    super(message);\n  }\n}\n\n/**\n * Error raised when an omnicast payload fails its action's schema\n * validation &mdash; on the dispatching side before anything reaches the\n * wire, or on the receiving side when a peer's envelope does not parse.\n * Faults carrying this error report `Reason.Rejected`, and the underlying\n * validator error (e.g. the `ZodError`) is preserved on `cause`.\n *\n * @example\n * ```ts\n * actions.useAction(Actions.Error, (context, fault) => {\n *   if (fault.reason === Reason.Rejected) {\n *     console.error(fault.error.cause);\n *   }\n * });\n * ```\n */\nexport class Rejected extends Error {\n  override name = \"RejectError\";\n  constructor(message = \"Rejected\", options?: { cause?: unknown }) {\n    super(message, options);\n  }\n}\n","import {\n  ChanneledAction,\n  Brand,\n  BrandedAction,\n  BrandedBroadcast,\n  BrandedMulticast,\n  AnyAction,\n  OmnicastPayload,\n  ReactiveBinding,\n  Schema,\n} from \"../types/index.ts\";\nimport type { ActionId } from \"../boundary/components/tasks/types.ts\";\nimport { Rejected } from \"../error/index.ts\";\nimport { describe } from \"../utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nconst isSymbol = (value: unknown): value is symbol => typeof value === \"symbol\";\n\n/**\n * Extracts the underlying symbol from an action or channeled action.\n * This symbol is used as the event emitter key for dispatching.\n *\n * @param action The action or channeled action to extract the symbol from.\n * @returns The underlying symbol, or the action itself if it's already a symbol/string.\n *\n * @example\n * ```typescript\n * const Increment = Action<number>(\"Increment\");\n * getActionSymbol(Increment); // Symbol(march-hare.action/Increment)\n * getActionSymbol(Increment({ UserId: 5 })); // Symbol(march-hare.action/Increment)\n * ```\n */\nexport function getActionSymbol(action: AnyAction): ActionId {\n  if (G.isString(action)) return action;\n  if (isSymbol(action)) return action;\n  if ((G.isObject(action) || G.isFunction(action)) && Brand.Action in action) {\n    return (<BrandedAction>action)[Brand.Action];\n  }\n  return <ActionId>(<unknown>action);\n}\n\n/**\n * Checks whether an action is a broadcast action.\n * Broadcast actions are sent to all mounted components that have defined a handler for them.\n *\n * @param action The action to check.\n * @returns True if the action is a broadcast action, false otherwise.\n */\nexport function isBroadcastAction(action: AnyAction): boolean {\n  if (G.isString(action))\n    return (\n      action.startsWith(describe.broadcast()) ||\n      action.startsWith(describe.omnicast())\n    );\n\n  if (isSymbol(action))\n    return (\n      (action.description?.startsWith(describe.broadcast()) ?? false) ||\n      (action.description?.startsWith(describe.omnicast()) ?? false)\n    );\n\n  if (G.isObject(action) || G.isFunction(action)) {\n    if (\n      Brand.Broadcast in action &&\n      (<BrandedBroadcast>action)[Brand.Broadcast]\n    ) {\n      return true;\n    }\n\n    if (Brand.Action in action) {\n      const actionSymbol = (<BrandedAction>action)[Brand.Action];\n      return (\n        (actionSymbol.description?.startsWith(describe.broadcast()) ?? false) ||\n        (actionSymbol.description?.startsWith(describe.omnicast()) ?? false)\n      );\n    }\n  }\n\n  return false;\n}\n\n/**\n * Checks whether an action is an omnicast action &mdash; a broadcast\n * action declared with `Distribution.Omnicast(schema?)` that additionally\n * travels between clients when the App is configured with an `sse`\n * endpoint.\n *\n * @param action The action to check.\n * @returns True if the action is an omnicast action, false otherwise.\n */\nexport function isOmnicastAction(action: AnyAction): boolean {\n  if (G.isString(action)) return action.startsWith(describe.omnicast());\n\n  if (isSymbol(action))\n    return action.description?.startsWith(describe.omnicast()) ?? false;\n\n  if (G.isObject(action) || G.isFunction(action)) {\n    if (Brand.Omnicast in action) return true;\n\n    if (Brand.Action in action) {\n      const actionSymbol = (<BrandedAction>action)[Brand.Action];\n      return actionSymbol.description?.startsWith(describe.omnicast()) ?? false;\n    }\n  }\n\n  return false;\n}\n\n/**\n * Reads the runtime schema off an omnicast action; `null` when the action\n * was declared without a payload or is not an omnicast action at all.\n *\n * @param action The action to read the schema from.\n * @returns The Zod-style schema supplied at declaration time, or `null`.\n */\nexport function schemaOf(action: AnyAction): null | Schema<unknown> {\n  if (\n    (G.isObject(action) || G.isFunction(action)) &&\n    Brand.Omnicast in action\n  ) {\n    return (<OmnicastPayload<unknown>>action)[Brand.Omnicast];\n  }\n  return null;\n}\n\n/**\n * Parses an omnicast payload arriving over the wire against the action's\n * schema, wrapping any validation failure in a {@link Rejected} error\n * (with the validator's error preserved on `cause`) so faults report\n * `Reason.Rejected` through the global `Lifecycle.Fault`. Outgoing\n * dispatches are deliberately not parsed &mdash; the payload type is\n * inferred from the same schema, so the compiler already guarantees the\n * sender's side; runtime validation is reserved for the trust boundary.\n * Payloadless actions pass through untouched.\n *\n * @param action The omnicast action whose schema applies.\n * @param payload The untrusted payload to validate.\n * @returns The parsed payload.\n */\nexport function validate(action: AnyAction, payload: unknown): unknown {\n  const schema = schemaOf(action);\n  if (G.isNull(schema)) return payload;\n  try {\n    return schema.parse(payload);\n  } catch (error) {\n    throw new Rejected(\n      `march-hare: the payload for omnicast \"${getName(action)}\" failed schema validation.`,\n      { cause: error },\n    );\n  }\n}\n\n/**\n * Extracts the action name from an action.\n *\n * Parses regular actions (`march-hare.action/Name`), distributed actions\n * (`march-hare.action/distributed/Name`), and lifecycle actions\n * (`march-hare.action.lifecycle/Name`) to extract just the name portion.\n *\n * @param action The action to extract the name from.\n * @returns The extracted action name, or \"unknown\" if parsing fails.\n *\n * @example\n * ```typescript\n * const Increment = Action(\"Increment\");\n * getName(Increment); // \"Increment\"\n *\n * const SignedOut = Action(\"SignedOut\", Distribution.Broadcast);\n * getName(SignedOut); // \"SignedOut\"\n *\n * const Mount = Lifecycle.Mount();\n * getName(Mount); // \"Mount\"\n *\n * const User = Lifecycle.Reactive<User>(\"User\");\n * getName(User); // \"User\"\n * ```\n */\nexport function getName(action: AnyAction): string {\n  const symbol = getActionSymbol(action);\n  const description = G.isString(symbol) ? symbol : (symbol.description ?? \"\");\n  const recognised =\n    description.startsWith(describe.action()) ||\n    description.startsWith(describe.lifecycle());\n  if (!recognised) return \"unknown\";\n  const name = description.slice(description.lastIndexOf(\"/\") + 1);\n  return name || \"unknown\";\n}\n\n/**\n * Checks if the given action is a channeled action (result of calling `Action(channel)`).\n *\n * @param action - The action to check\n * @returns `true` if the action is a channeled action with a channel property, `false` otherwise\n *\n * @example\n * ```ts\n * const UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n * isChanneledAction(UserUpdated); // false\n * isChanneledAction(UserUpdated({ UserId: 1 })); // true\n * ```\n */\nexport function isChanneledAction(\n  action: AnyAction,\n): action is ChanneledAction {\n  return G.isObject(action) && Brand.Channel in action && \"channel\" in action;\n}\n\n/**\n * Checks if the given action is a reactive binding (result of calling a\n * `Lifecycle.Reactive` static with a value).\n *\n * @param action - The action to check\n * @returns `true` if the action is a reactive binding carrying a bound value\n *\n * @example\n * ```ts\n * const User = Lifecycle.Reactive<User>(\"User\");\n *\n * isReactiveBinding(User); // false\n * isReactiveBinding(User(user)); // true\n * ```\n */\nexport function isReactiveBinding(\n  action: AnyAction,\n): action is ReactiveBinding {\n  return G.isObject(action) && Brand.Reactive in action && \"value\" in action;\n}\n\n/**\n * Extracts the lifecycle type from an action's symbol description.\n *\n * Returns the lifecycle name (`\"Mount\"`, `\"Paint\"`, `\"Unmount\"`, `\"Error\"`,\n * `\"Update\"`) when the action symbol's description starts with the lifecycle\n * prefix, or `null` for non-lifecycle actions.\n *\n * @param action The action to inspect.\n * @returns The lifecycle name, or `null` if not a lifecycle action.\n *\n * @example\n * ```typescript\n * class Actions {\n *   static Mount = Lifecycle.Mount();\n * }\n *\n * getLifecycleType(Actions.Mount); // \"Mount\"\n * getLifecycleType(Action(\"Increment\")); // null\n * ```\n */\nexport function getLifecycleType(action: AnyAction): string | null {\n  const symbol = getActionSymbol(action);\n  const description = isSymbol(symbol) ? (symbol.description ?? \"\") : symbol;\n  if (!description.startsWith(describe.lifecycle())) return null;\n  return description.slice(describe.lifecycle().length) || null;\n}\n\n/**\n * Checks whether an action is a multicast action.\n * Multicast actions are dispatched to all components within a named scope boundary.\n *\n * @param action The action to check.\n * @returns True if the action is a multicast action, false otherwise.\n */\nexport function isMulticastAction(action: AnyAction): boolean {\n  if (G.isString(action)) return action.startsWith(describe.multicast());\n\n  if (isSymbol(action))\n    return action.description?.startsWith(describe.multicast()) ?? false;\n\n  if (G.isObject(action) || G.isFunction(action)) {\n    if (\n      Brand.Multicast in action &&\n      (<BrandedMulticast>action)[Brand.Multicast]\n    ) {\n      return true;\n    }\n\n    if (Brand.Action in action) {\n      const actionSymbol = (<BrandedAction>action)[Brand.Action];\n      return (\n        actionSymbol.description?.startsWith(describe.multicast()) ?? false\n      );\n    }\n  }\n\n  return false;\n}\n","import {\n  HandlerPayload,\n  BroadcastPayload,\n  MulticastPayload,\n  OmnicastPayload,\n  OmnicastDistribution,\n  Distribution,\n  ChanneledAction,\n  Brand,\n  Filter,\n} from \"../types/index.ts\";\nimport { describe } from \"../utils.ts\";\n\nexport {\n  getActionSymbol,\n  getLifecycleType,\n  isBroadcastAction,\n  isMulticastAction,\n  isOmnicastAction,\n  getName,\n  isChanneledAction,\n  isReactiveBinding,\n  schemaOf,\n  validate,\n} from \"./utils.ts\";\n\n/**\n * Interface for the Action factory function.\n */\ntype ActionFactory = {\n  /**\n   * Creates a new unicast action with an optional name.\n   *\n   * `K` is the literal type of the action name and is captured as a phantom\n   * brand so `Action(\"A\")` and `Action(\"B\")` produce structurally-distinct\n   * types. **Note:** when the caller supplies any explicit generic\n   * (`Action<P>(\"Name\")`), TypeScript fills `K` from its default and the\n   * literal is lost. The Name brand still helps for `Action(\"Name\")` calls\n   * (e.g. lifecycle / no-payload actions) which is the most common source of\n   * foreign-class collisions.\n   *\n   * Omitting the name produces an action whose symbol description has no\n   * suffix. Symbol identity (and therefore dispatch routing) is unaffected\n   * — names are only used for fault reporting and debugger readability.\n   *\n   * @template P The payload type for the action.\n   * @template C The channel type for channeled dispatches.\n   * @template K The literal type of the action name (inferred when no other\n   *   generics are supplied; defaults to `string` otherwise).\n   */\n  <P = never, C extends Filter = never, K extends string = string>(\n    name?: K,\n  ): HandlerPayload<P, C, K>;\n\n  /**\n   * Creates a new action with the specified distribution mode.\n   */\n  <P = never, C extends Filter = never, K extends string = string>(\n    name: K | undefined,\n    distribution: Distribution.Broadcast,\n  ): BroadcastPayload<P, C, K>;\n  <P = never, C extends Filter = never, K extends string = string>(\n    name: K | undefined,\n    distribution: Distribution.Multicast,\n  ): MulticastPayload<P, C, K>;\n\n  /**\n   * Creates an omnicast action from a `Distribution.Omnicast(schema?)`\n   * marker. The payload type is inferred from the marker's schema rather\n   * than an explicit generic, keeping the compile-time type and the\n   * runtime validator in lockstep. The channel type flows from the marker\n   * when declared via `Distribution.Omnicast<T, C>(schema)`.\n   */\n  <T, C extends Filter, K extends string = string>(\n    name: K | undefined,\n    distribution: OmnicastDistribution<T, C>,\n  ): OmnicastPayload<T, C, K>;\n  <P = never, C extends Filter = never, K extends string = string>(\n    name: K | undefined,\n    distribution: Distribution.Unicast,\n  ): HandlerPayload<P, C, K>;\n  <P = never, C extends Filter = never, K extends string = string>(\n    name: K | undefined,\n    distribution: Distribution,\n  ):\n    | HandlerPayload<P, C, K>\n    | BroadcastPayload<P, C, K>\n    | MulticastPayload<P, C, K>;\n};\n\n/**\n * Creates a new action with a given payload type, optional channel type, and optional distribution mode.\n *\n * Actions are strongly typed identifiers used to dispatch and handle state changes.\n * By default, actions use `Distribution.Unicast` (local to the defining component).\n * Use `Distribution.Broadcast` for actions that need to be shared across components.\n *\n * When a channel type is specified, the action becomes callable to create channeled dispatches:\n * - `Action({ UserId: 5 })` creates a channeled action targeting that specific channel\n * - Plain `Action` (uncalled) broadcasts to all handlers\n *\n * @template P The type of the payload that the action will carry.\n * @template C The type of the channel for channeled dispatches (defaults to never).\n *\n * @example\n * ```ts\n * export class Actions {\n *   // Unicast action with no payload\n *   static Reset = Action(\"Reset\");\n *\n *   // Unicast action with typed payload\n *   static Increment = Action<number>(\"Increment\");\n *\n *   // Action with channel support for targeted dispatches\n *   static UserUpdated = Action<User, { UserId: number }>(\"UserUpdated\");\n *\n *   // Broadcast action - can be read across components\n *   static Counter = Action<number>(\"Counter\", Distribution.Broadcast);\n * }\n *\n * // Usage\n * actions.dispatch(Actions.Reset);\n * actions.dispatch(Actions.Increment, 5);\n * actions.dispatch(Actions.UserUpdated, user);                    // broadcast to all\n * actions.dispatch(Actions.UserUpdated({ UserId: 5 }), user);     // channeled dispatch\n * actions.stream(Actions.Counter, (box) => box.value);\n * ```\n */\nexport const Action = <ActionFactory>(<unknown>(<\n  P = never,\n  C extends Filter = never,\n>(\n  name: string = \"\",\n  distribution: Distribution | OmnicastDistribution<P> = Distribution.Unicast,\n): HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C> => {\n  const omnicast =\n    typeof distribution === \"object\" && Brand.Omnicast in distribution\n      ? distribution\n      : null;\n  const broadcast =\n    omnicast !== null || distribution === Distribution.Broadcast;\n\n  const symbol =\n    omnicast !== null\n      ? Symbol(describe.omnicast(name))\n      : distribution === Distribution.Broadcast\n        ? Symbol(describe.broadcast(name))\n        : distribution === Distribution.Multicast\n          ? Symbol(describe.multicast(name))\n          : Symbol(describe.action(name));\n\n  const action = function (channel: C): ChanneledAction<P, C> {\n    const channeled: ChanneledAction<P, C> = {\n      [Brand.Action]: symbol,\n      [Brand.Payload]: <P>undefined,\n      [Brand.Channel]: channel,\n      [Brand.Name]: name,\n      channel,\n    };\n    if (broadcast) {\n      // eslint-disable-next-line fp/no-mutating-methods\n      Object.defineProperty(channeled, Brand.Broadcast, {\n        value: true,\n        enumerable: false,\n      });\n    }\n    if (omnicast !== null) {\n      // eslint-disable-next-line fp/no-mutating-methods\n      Object.defineProperty(channeled, Brand.Omnicast, {\n        value: omnicast[Brand.Omnicast],\n        enumerable: false,\n      });\n    }\n    return channeled;\n  };\n\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Action, {\n    value: symbol,\n    enumerable: false,\n  });\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Payload, {\n    value: undefined,\n    enumerable: false,\n  });\n  // eslint-disable-next-line fp/no-mutating-methods\n  Object.defineProperty(action, Brand.Name, { value: name, enumerable: false });\n  if (broadcast) {\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Broadcast, {\n      value: true,\n      enumerable: false,\n    });\n  }\n  if (omnicast !== null) {\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Omnicast, {\n      value: omnicast[Brand.Omnicast],\n      enumerable: false,\n    });\n  }\n  if (distribution === Distribution.Multicast) {\n    // eslint-disable-next-line fp/no-mutating-methods\n    Object.defineProperty(action, Brand.Multicast, {\n      value: true,\n      enumerable: false,\n    });\n  }\n\n  return <\n    HandlerPayload<P, C> | BroadcastPayload<P, C> | MulticastPayload<P, C>\n  >action;\n}));\n","import * as React from \"react\";\nimport type { Stored } from \"./types.ts\";\n\n/**\n * Sentinel symbol marking \"no value present yet\". Shared by the Resource\n * cache and by storage handles so callers can distinguish \"nothing has been\n * recorded\" from \"a legitimately stored null\".\n */\nexport const unset: unique symbol = Symbol(\"march-hare.unset\");\n\n/**\n * Internal configuration shared across the Resource and Cache layers.\n *\n * - `unset` &mdash; re-export of the shared sentinel so consumers can pull\n *   both fields from a single object.\n * - `storageNamespace` &mdash; global prefix the Cache layer prepends to\n *   every key it persists. Lets `Cache.clear()` and the partial-match\n *   evictors scope themselves to the library's own entries on shared\n *   backends (`localStorage`, `chrome.storage.local`, MMKV) without\n *   nuking third-party state on the same origin.\n *\n * @internal\n */\nexport const config = <const>{\n  unset,\n  storageNamespace: \"mh:\",\n};\n\n/**\n * Returns a function to force a component re-render. Useful when state is\n * managed externally (e.g., refs) but the UI needs updating.\n *\n * @returns A zero-arg callback that schedules a re-render of the host\n *          component when invoked.\n */\nexport function useRerender(): () => void {\n  const [, rerender] = React.useReducer((x: number) => x + 1, 0);\n  return rerender;\n}\n\n/**\n * Constructs a {@link Stored} in the empty state. Internal helper shared\n * by the storage layer and the Resource snapshot accessor.\n *\n * @template T The payload type the resulting Stored would carry if populated.\n * @returns A Stored with `data` set to {@link unset} and `at` set to `null`.\n * @internal\n */\nexport function empty<T>(): Stored<T> {\n  return { data: unset, at: null };\n}\n\n/**\n * Constructs a {@link Stored} wrapping a present payload and timestamp.\n *\n * @template T The payload type carried by the Stored.\n * @param data The payload value to wrap.\n * @param at The instant the payload was recorded — flows through to the\n *           Resource cache as the entry's `at` timestamp.\n * @internal\n */\nexport function present<T>(data: T, at: Temporal.Instant): Stored<T> {\n  return { data, at };\n}\n","import * as React from \"react\";\nimport { RefObject } from \"react\";\nimport {\n  Props,\n  Phase,\n  Model,\n  Actions,\n  Filter,\n  ActionId,\n  HandlerPayload,\n  ChanneledAction,\n  HandlerContext,\n} from \"../types/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/index.tsx\";\n\nimport type { Dispatchers, LifecycleConfig, Handler, Scope } from \"./types.ts\";\nimport { A, G } from \"@mobily/ts-belt\";\nimport { changes } from \"../utils.ts\";\nimport {\n  isChanneledAction,\n  getActionSymbol,\n  getLifecycleType,\n  isReactiveBinding,\n} from \"../action/index.ts\";\nimport { unset } from \"../utils/utils.ts\";\n\n/**\n * Creates a new object with getters for each property of the input object.\n * The getters retrieve the current value from a ref, ensuring that the latest value is always accessed.\n */\nexport function withGetters<P extends Props>(a: P, b: RefObject<P>): P {\n  return Object.keys(a).reduce(\n    (proxy, key) => {\n      Object.defineProperty(proxy, key, {\n        get() {\n          return b.current[key];\n        },\n        enumerable: true,\n      });\n\n      return proxy;\n    },\n    <P>{},\n  );\n}\n\n/**\n * Checks if the given result is a generator or async generator object.\n * Uses `Object.prototype.toString` which reliably returns\n * `\"[object Generator]\"` or `\"[object AsyncGenerator]\"` regardless of\n * the generator function's name.\n */\nexport function isGenerator(\n  result: unknown,\n): result is Generator | AsyncGenerator {\n  if (!result || typeof result !== \"object\") return false;\n  const tag = Object.prototype.toString.call(result);\n  return tag === \"[object Generator]\" || tag === \"[object AsyncGenerator]\";\n}\n\n/**\n * Invokes all listeners for an event and returns a promise that resolves\n * when every handler has settled. For {@link BroadcastEmitter} instances the\n * payload is cached &mdash; sharded by channel &mdash; before listeners\n * fire so late-mounting components see every cached entry.\n *\n * @internal\n */\nexport function emitAsync(\n  emitter: EventEmitter,\n  event: string | symbol,\n  ...args: unknown[]\n): Promise<void> {\n  if (emitter instanceof BroadcastEmitter) {\n    emitter.setCache(event, args[0], <Filter | undefined>args[1]);\n  }\n\n  const listeners = emitter.listeners(event);\n  if (listeners.length === 0) return Promise.resolve();\n\n  return Promise.all(listeners.map((fn) => Promise.resolve(fn(...args)))).then(\n    () => {},\n  );\n}\n\n/**\n * Emits lifecycle events across a component's mount cycle and tracks the\n * `phase` ref.\n *\n * The Mount effect (layout) fires `Mount`, replays cached broadcast /\n * multicast values, and &mdash; on first mount &mdash; the initial `Update`\n * with the starting data (`{}` when there is no data). All of these run while\n * `phase` is `Mounting`. It skips when `phase` is already `Mounted` (catching\n * Strict Mode's dev-only double-invocation) and accepts both `Mounting`\n * (first mount) and `Unmounted` (re-mount after `<Activity>` show) as entry\n * states.\n *\n * The Paint effect (passive `useEffect`) fires after the first frame commits\n * and is where `phase` becomes `Mounted` &mdash; so every layout-phase\n * emission, including each `useAction`'s reactive mount fire, observes\n * `Mounting`. It ref-guards itself to fire once per mount cycle (re-firing\n * after `<Activity>` show).\n *\n * The Update effect (layout) fires `Update` with the changed data keys on\n * every render after the first; the first render's Update is owned by the\n * Mount effect so `context.phase` reads `Mounting` there.\n *\n * Phase transitions:\n * - First mount:           Mounting → (paint) Mounted\n * - Activity hide / show:  Mounted → Unmounting → Unmounted → Mounting → (paint) Mounted\n */\nexport function useLifecycles({\n  unicast,\n  broadcast,\n  dispatchers,\n  scope,\n  phase,\n  data,\n  handlers,\n}: LifecycleConfig): void {\n  const previous = React.useRef<Props>({});\n  const painted = React.useRef<boolean>(false);\n\n  React.useLayoutEffect(() => {\n    if (phase.current === Phase.Mounted) return;\n    const firstMount = phase.current === Phase.Mounting;\n    phase.current = Phase.Mounting;\n\n    const mountAction = findLifecycleAction(handlers, \"Mount\");\n    if (mountAction) unicast.emit(mountAction);\n\n    dispatchers.broadcast.forEach((action) => {\n      for (const { channel, value } of broadcast.getCachedAll(action)) {\n        if (G.isNullable(value)) continue;\n        unicast.emit(action, value, channel);\n      }\n    });\n\n    if (scope) {\n      dispatchers.multicast.forEach((action) => {\n        for (const { channel, value } of scope.emitter.getCachedAll(action)) {\n          if (G.isNullable(value)) continue;\n          unicast.emit(action, value, channel);\n        }\n      });\n    }\n\n    if (firstMount) {\n      const updateAction = findLifecycleAction(handlers, \"Update\");\n      if (updateAction) unicast.emit(updateAction, changes({}, data));\n      previous.current = data;\n    }\n\n    painted.current = false;\n  }, []);\n\n  React.useEffect(() => {\n    if (painted.current) return;\n    painted.current = true;\n    phase.current = Phase.Mounted;\n\n    const paintAction = findLifecycleAction(handlers, \"Paint\");\n    if (paintAction) unicast.emit(paintAction);\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const differences = changes(previous.current, data);\n    if (A.isNotEmpty(Object.keys(differences))) {\n      const updateAction = findLifecycleAction(handlers, \"Update\");\n      if (updateAction) unicast.emit(updateAction, differences);\n    }\n\n    previous.current = data;\n  }, [data, unicast]);\n}\n\n/**\n * Creates a data proxy for a given object, returning a memoized version.\n * The proxy provides stable access to the object's properties,\n * even as the original object changes across renders.\n *\n * The ref is updated synchronously during render so the proxy is current\n * both during the render itself (for JSX reading the third tuple element\n * returned by {@link useActions}) and afterwards (for handler reads via\n * `context.data` across `await` boundaries).\n *\n * @template P The type of the object.\n * @param props The object to create a data proxy for.\n * @returns A memoized data proxy of the object.\n */\nexport function useData<P extends Props>(props: P): P {\n  const ref = React.useRef<P>(props);\n  ref.current = props;\n  return React.useMemo(() => withGetters<P>(props, ref), [props]);\n}\n\n/**\n * Scans a handler registry for a lifecycle action of the given type.\n *\n * When lifecycle actions become per-class instances (via `Lifecycle.Mount()`),\n * each Actions class has its own unique symbol. Emission sites can no longer\n * emit to a shared singleton — they must discover the component's lifecycle\n * action by scanning the registry keys for matching lifecycle prefixes.\n *\n * Handler maps typically contain 5–15 entries, so the O(n) scan is trivial.\n *\n * @param handlers The handler map from a component's scope.\n * @param type The lifecycle type to find (e.g. `\"Mount\"`, `\"Unmount\"`, `\"Error\"`).\n * @returns The matching ActionId, or `null` if no lifecycle action of that type is registered.\n *\n * @internal\n */\nexport function findLifecycleAction(\n  handlers: Map<ActionId, Set<unknown>>,\n  type: string,\n): ActionId | null {\n  for (const action of handlers.keys()) {\n    if (getLifecycleType(action) === type) return action;\n  }\n  return null;\n}\n\n// Re-export isChanneledAction and getActionSymbol for convenience\nexport { isChanneledAction, getActionSymbol };\n\n/**\n * Manages sets of broadcast and multicast action IDs.\n *\n * This hook creates stable refs for tracking which actions have been registered\n * as broadcast or multicast within a component. These sets are used to:\n * - Replay cached broadcast values on mount\n * - Track multicast subscriptions for scope-based dispatch\n *\n * @returns Object with `broadcast` and `multicast` Sets for action tracking\n *\n * @example\n * ```ts\n * const actions = useDispatchers();\n *\n * // Register a broadcast action\n * actions.broadcast.add(getActionSymbol(MyBroadcastAction));\n *\n * // Check if an action is registered as multicast\n * if (actions.multicast.has(actionId)) {\n *   // Handle multicast dispatch\n * }\n * ```\n *\n * @internal\n */\nexport function useDispatchers(): Dispatchers {\n  const broadcast = React.useRef<Set<ActionId>>(new Set());\n  const multicast = React.useRef<Set<ActionId>>(new Set());\n\n  return React.useMemo(\n    () => ({\n      broadcast: broadcast.current,\n      multicast: multicast.current,\n    }),\n    [],\n  );\n}\n\n/**\n * Registers an action handler within a component's scope.\n *\n * This hook binds a handler function to an action, supporting both regular and channeled\n * actions. The handler is wrapped with `useEffectEvent` to ensure it always has access\n * to the latest closure values while maintaining a stable reference.\n *\n * For generator handlers (sync or async), the hook automatically iterates through\n * all yielded values to completion.\n *\n * @template M - The model type representing the component's state\n * @template AC - The actions class containing action definitions\n * @template D - The data type for reactive external values\n *\n * @param scope - Ref to the component's handler scope containing registered handlers\n * @param action - The action to register (ActionId, HandlerPayload, ChanneledAction, or ReactiveBinding)\n * @param handler - The handler function to invoke when the action is dispatched\n * @param site - Per-call-site symbol; registered as the channel for reactive\n *   bindings so each binding's emission reaches only its own handler\n *\n * @example\n * ```ts\n * useRegisterHandler(scope, Actions.Increment, async (context, payload) => {\n *   context.actions.produce((draft) => {\n *     draft.model.count += payload;\n *   });\n * }, site);\n *\n * // With channeled action\n * useRegisterHandler(scope, Actions.UserUpdated({ UserId: 5 }), (context, user) => {\n *   // Only called when UserId matches 5\n * }, site);\n * ```\n *\n * @internal\n */\nexport function useRegisterHandler<\n  M extends Model | void,\n  A extends Actions | void,\n  D extends Props,\n>(\n  scope: React.RefObject<Scope<M, A, D>>,\n  action: ActionId | HandlerPayload | ChanneledAction,\n  handler: (\n    context: HandlerContext<M, A, D>,\n    payload: unknown,\n  ) => void | Promise<void> | AsyncGenerator | Generator,\n  site: symbol,\n): void {\n  // Store latest handler in ref to avoid stale closures (replaces useEffectEvent)\n  const handlerRef = React.useRef(handler);\n  React.useLayoutEffect(() => {\n    handlerRef.current = handler;\n  });\n\n  // Store latest action for channel resolution\n  const actionRef = React.useRef(action);\n  React.useLayoutEffect(() => {\n    actionRef.current = action;\n  });\n\n  // Stable handler wrapper that always calls the latest handler.\n  // Generator detection and iteration is handled by createHandler in hooks/index.ts\n  // so that generators can be excluded from the awaitable dispatch promise.\n  const stableHandler = React.useCallback(\n    (context: HandlerContext<M, A, D>, payload: unknown) =>\n      handlerRef.current(context, payload),\n    [],\n  );\n\n  // Stable channel getter. Reactive bindings register their call-site\n  // symbol as the channel so that a binding's emission (which dispatches\n  // on the same channel) reaches only its own handler &mdash; two bindings\n  // of one Reactive static within a component stay isolated, while an\n  // uncalled subscription (no channel) still hears every dispatch.\n  const getChannel = React.useCallback((): Filter | undefined => {\n    if (isChanneledAction(actionRef.current)) {\n      return <Filter>actionRef.current.channel;\n    }\n    if (isReactiveBinding(actionRef.current)) return { Site: site };\n    return undefined;\n  }, [site]);\n\n  const base = getActionSymbol(action);\n  const entries = scope.current.handlers.get(base) ?? new Set();\n  if (entries.size === 0) scope.current.handlers.set(base, entries);\n  entries.add({ getChannel, handler: <Handler<M, A, D>>stableHandler });\n}\n\n/**\n * Emits a reactive binding's value through the component's unicast\n * emitter whenever it changes between renders. No-ops for every other\n * registration kind &mdash; it is called unconditionally per `useAction`\n * call site so the hook order stays stable.\n *\n * The comparison is `Object.is` against the last-dispatched value, seeded\n * with the shared {@link unset} sentinel so the mount emission always fires once\n * &mdash; whether the initial value is defined (a hydrated React Query\n * cache) or `undefined`. Every later render fires only on a change, so the\n * `Object.is` guard makes unchanged renders free.\n *\n * The effect runs after every commit (no dependency array) because the\n * binding is a fresh wrapper each render. It also runs after the\n * subscription effect in `useActions` (declared earlier in the hook\n * order), so the mount emission is never lost.\n *\n * The emission carries the registration's site symbol as its channel so\n * that two bindings of the same static within one component stay\n * isolated &mdash; each site's dispatch reaches only its own handler,\n * while uncalled subscriptions on the static hear every site.\n *\n * @internal\n */\nexport function useReactiveEmit(\n  action: ActionId | HandlerPayload | ChanneledAction,\n  unicast: EventEmitter,\n  site: symbol,\n): void {\n  const binding = isReactiveBinding(action) ? action : null;\n  const dispatched = React.useRef<unknown>(unset);\n  React.useLayoutEffect(() => {\n    if (G.isNull(binding)) return;\n    if (Object.is(dispatched.current, binding.value)) return;\n    dispatched.current = binding.value;\n    unicast.emit(getActionSymbol(binding), binding.value, { Site: site });\n  });\n}\n\n/**\n * Checks whether a dispatch channel satisfies a registered handler's\n * channel filter. The handler's channel is the filter: every key the\n * subscriber supplied must be present and equal on the dispatch channel.\n * Extra keys on the dispatch channel are ignored &mdash; the dispatcher\n * is free to be more specific than any single subscriber needs.\n *\n * Mental model: \"the subscriber declares everything it wants matched\n * against; the dispatcher matches what it can.\" A subscriber that\n * registers no channel keys (`{}` or no channel at all) matches every\n * dispatch on the action.\n *\n * @param dispatchChannel - The channel from the dispatch call (from ChanneledAction)\n * @param registeredChannel - The channel registered with useAction\n * @returns `true` if every key on the registered channel is satisfied by the dispatch channel\n *\n * @example\n * ```ts\n * matchesChannel({ UserId: 1 }, { UserId: 1 });                            // true (exact)\n * matchesChannel({ UserId: 1, Role: \"admin\" }, { UserId: 1 });             // true (subscriber narrower)\n * matchesChannel({ UserId: 1 }, { UserId: 1, Role: \"admin\" });             // false (subscriber asked for Role, dispatch did not supply it)\n * matchesChannel({ UserId: 1 }, { UserId: 2 });                            // false (value mismatch)\n * matchesChannel({ UserId: 1, Role: \"admin\" }, {});                        // true (subscriber filters nothing)\n * matchesChannel({}, { UserId: 1 });                                       // false (subscriber asked for UserId, dispatch did not supply it)\n * ```\n */\nexport function matchesChannel(\n  dispatchChannel: Filter,\n  registeredChannel: Filter,\n): boolean {\n  for (const key of Object.keys(registeredChannel)) {\n    if (dispatchChannel[key] !== registeredChannel[key]) return false;\n  }\n  return true;\n}\n","import { Reason } from \"./types.ts\";\n\n/**\n * Determines the error reason based on what was thrown.\n *\n * @param error - The value that was thrown.\n * @returns The appropriate Reason enum value.\n */\nexport function getReason(error: unknown): Reason {\n  if (error instanceof Error && error.name === \"AbortError\")\n    return Reason.Aborted;\n  if (error instanceof Error && error.name === \"RejectError\")\n    return Reason.Rejected;\n  return Reason.Errored;\n}\n\n/**\n * Gets an Error instance from a thrown value.\n *\n * @param error - The value that was thrown.\n * @returns An Error instance (original if already Error, wrapped otherwise).\n */\nexport function getError(error: unknown): Error {\n  return error instanceof Error ? error : new Error(String(error));\n}\n","import { G } from \"@mobily/ts-belt\";\nimport { getName, isOmnicastAction } from \"../../../action/utils.ts\";\nimport type { Actions, OmnicastPayload } from \"../../../types/index.ts\";\n\nconst depthLimit = 4;\n\n/**\n * Finds the omnicast action whose name matches an incoming envelope,\n * walking nested classes and namespaces (e.g. `Omnicast.Cat.Adopted`) up\n * to a small fixed depth. Non-omnicast members and unknown names resolve\n * to `null`, so the configured actions act as an allow-list for what a\n * remote peer may dispatch into the local Boundary.\n */\nexport function lookup(\n  actions: Actions,\n  name: string,\n  depth = 0,\n): null | OmnicastPayload<unknown> {\n  if (depth > depthLimit) return null;\n  for (const candidate of Object.values(actions)) {\n    if (isOmnicastAction(<OmnicastPayload<unknown>>candidate)) {\n      if (getName(<OmnicastPayload<unknown>>candidate) === name)\n        return <OmnicastPayload<unknown>>candidate;\n      continue;\n    }\n    if (G.isObject(candidate) || G.isFunction(candidate)) {\n      const nested = lookup(<Actions>candidate, name, depth + 1);\n      if (G.isNotNullable(nested)) return nested;\n    }\n  }\n  return null;\n}\n\n/**\n * Splits the desired tag set against the tags the server currently holds\n * for the connection, yielding the mutations required to align the server.\n * Used after every `connected` event so tag mutations survive the\n * automatic `EventSource` reconnect, which reverts the server to the\n * query-string tags.\n */\nexport function reconcile(\n  desired: ReadonlySet<string>,\n  held: readonly string[],\n): { add: string[]; remove: string[] } {\n  const current = new Set(held);\n  return {\n    add: [...desired].filter((tag) => !current.has(tag)),\n    remove: held.filter((tag) => !desired.has(tag)),\n  };\n}\n\n/**\n * Builds the `/sse` address, appending the initial tags as a query string\n * when any are configured.\n */\nexport function address(url: string, tags: ReadonlySet<string>): string {\n  if (tags.size === 0) return `${url}/sse`;\n  return `${url}/sse?tags=${encodeURIComponent([...tags].join(\",\"))}`;\n}\n\n/**\n * Decides whether an arriving envelope is still deliverable to this\n * client: the envelope's audience tags (embedded at dispatch time) must\n * **all** be held by the client's current tag set. The server applied the\n * same rule at send time, but the client's tags may have changed while\n * the event was in flight &mdash; a downgrade racing an in-flight `vip`\n * event &mdash; so the receiving side re-validates against its live set\n * and quietly drops envelopes it no longer qualifies for.\n */\nexport function eligible(\n  required: undefined | readonly string[],\n  held: ReadonlySet<string>,\n): boolean {\n  if (G.isNullable(required) || required.length === 0) return true;\n  return required.every((tag) => held.has(tag));\n}\n\n/**\n * Parses an SSE `data` field, absorbing malformed JSON from a misbehaving\n * server into a logged `null` instead of an uncaught listener error.\n */\nexport function parse<T>(data: string): null | T {\n  try {\n    return <T>JSON.parse(data);\n  } catch {\n    // eslint-disable-next-line no-console\n    console.warn(\"march-hare: discarded a malformed SSE envelope.\");\n    return null;\n  }\n}\n","import * as React from \"react\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useBroadcast } from \"../broadcast/index.tsx\";\nimport { useTasks } from \"../tasks/utils.ts\";\nimport { useTap } from \"../tap/utils.ts\";\nimport { emitAsync } from \"../../../actions/utils.ts\";\nimport { getActionSymbol, getName, validate } from \"../../../action/utils.ts\";\nimport { getError, getReason } from \"../../../error/utils.ts\";\nimport { FaultSymbol } from \"../../../types/index.ts\";\nimport type {\n  SseConfig,\n  SseConnected,\n  SseEnvelope,\n  SseHandle,\n} from \"./types.ts\";\nimport { address, eligible, lookup, parse, reconcile } from \"./utils.ts\";\n\nexport type {\n  SseConfig,\n  SseConnected,\n  SseEnvelope,\n  SseHandle,\n} from \"./types.ts\";\n\nexport const SseContext = React.createContext<null | SseHandle>(null);\n\n/**\n * Reads the enclosing Boundary's SSE handle; `null` when the App was\n * configured without an `sse` endpoint.\n *\n * @internal\n */\nexport function useSse(): null | SseHandle {\n  return React.useContext(SseContext);\n}\n\n/**\n * Per-Boundary SSE connection, mounted automatically by `<Boundary>` when\n * the App is configured with an `sse` endpoint. Owns the connection\n * lifecycle end to end: it connects on mount, disconnects on unmount,\n * rides `EventSource`'s automatic reconnection (re-reading the client id\n * and re-applying tag mutations after every reconnect), and re-dispatches\n * validated incoming envelopes into the Boundary as ordinary broadcasts.\n *\n * The handle it provides through {@link SseContext} is what `dispatch`\n * uses to publish omnicast actions to the wire; without a config the\n * context stays `null` and omnicast dispatches degrade to plain\n * broadcasts.\n *\n * @internal\n */\nexport function Sse({\n  config,\n  children,\n}: {\n  config?: SseConfig;\n  children: React.ReactNode;\n}): React.ReactElement {\n  const broadcast = useBroadcast();\n  const tasks = useTasks();\n  const tap = useTap();\n  const client = React.useRef<null | string>(null);\n  const desired = React.useRef<null | Set<string>>(null);\n  desired.current ??= new Set(config?.tags ?? []);\n  const align = React.useRef<\n    null | ((method: \"PUT\" | \"DELETE\", tag: string) => Promise<void>)\n  >(null);\n\n  const handle = React.useMemo<null | SseHandle>(() => {\n    if (G.isUndefined(config)) return null;\n    const endpoint = config;\n\n    async function mutate(\n      method: \"PUT\" | \"DELETE\",\n      tag: string,\n    ): Promise<void> {\n      if (G.isNull(client.current)) return;\n      const response = await fetch(\n        `${endpoint.url}/clients/${client.current}/tags/${encodeURIComponent(tag)}`,\n        { method },\n      );\n      if (!response.ok)\n        throw new Error(\n          `march-hare: SSE tag mutation failed with HTTP ${response.status}.`,\n        );\n    }\n\n    align.current = mutate;\n\n    return {\n      async publish(envelope: SseEnvelope) {\n        const body: Record<string, unknown> = { data: envelope };\n        if (G.isNotNullable(envelope.tags) && envelope.tags.length > 0)\n          body.tags = envelope.tags;\n        if (G.isNotNullable(client.current)) body.client = client.current;\n        const response = await fetch(`${endpoint.url}/send`, {\n          method: \"POST\",\n          headers: { \"content-type\": \"application/json\" },\n          body: JSON.stringify(body),\n        });\n        if (!response.ok)\n          throw new Error(\n            `march-hare: SSE publish failed with HTTP ${response.status}.`,\n          );\n      },\n      client: () => client.current,\n      tag: {\n        async add(...tags: readonly [string, ...string[]]) {\n          const fresh = [...new Set(tags)].filter(\n            (tag) => !(desired.current?.has(tag) ?? false),\n          );\n          fresh.forEach((tag) => desired.current?.add(tag));\n          await Promise.all(fresh.map((tag) => mutate(\"PUT\", tag)));\n        },\n        async remove(...tags: readonly [string, ...string[]]) {\n          const held = [...new Set(tags)].filter(\n            (tag) => desired.current?.has(tag) ?? false,\n          );\n          held.forEach((tag) => desired.current?.delete(tag));\n          await Promise.all(held.map((tag) => mutate(\"DELETE\", tag)));\n        },\n        has(...tags: readonly [string, ...string[]]) {\n          return tags.every((tag) => desired.current?.has(tag) ?? false);\n        },\n        async clear() {\n          const held = [...(desired.current ?? [])];\n          desired.current?.clear();\n          await Promise.all(held.map((tag) => mutate(\"DELETE\", tag)));\n        },\n      },\n    };\n  }, [config]);\n\n  React.useEffect(() => {\n    if (G.isUndefined(config) || G.isNull(handle)) return;\n    const tags = desired.current ?? new Set<string>();\n    const source = new EventSource(address(config.url, tags));\n\n    source.addEventListener(\"connected\", (event: MessageEvent<string>) => {\n      const connected = parse<SseConnected>(event.data);\n      if (G.isNull(connected)) return;\n      client.current = connected.client;\n      const { add, remove } = reconcile(tags, connected.tags);\n      void Promise.all([\n        ...add.map((tag) => align.current?.(\"PUT\", tag)),\n        ...remove.map((tag) => align.current?.(\"DELETE\", tag)),\n      ]).catch((error) => {\n        // eslint-disable-next-line no-console\n        console.warn(\n          \"march-hare: failed to re-apply tags after an SSE reconnect.\",\n          error,\n        );\n      });\n    });\n\n    source.addEventListener(\"message\", (event: MessageEvent<string>) => {\n      const envelope = parse<SseEnvelope>(event.data);\n      if (G.isNull(envelope)) return;\n      const action = lookup(config.actions, envelope.name);\n      if (G.isNull(action)) return;\n      if (!eligible(envelope.tags, desired.current ?? new Set())) return;\n      const deliver = (): Promise<void> => {\n        try {\n          const payload = validate(action, envelope.payload);\n          return emitAsync(\n            broadcast,\n            getActionSymbol(action),\n            payload,\n            envelope.channel,\n          );\n        } catch (caught) {\n          const identity = { name: getName(action), payload: envelope.payload };\n          const task = {\n            controller: new AbortController(),\n            action: getActionSymbol(action),\n            payload: envelope.payload,\n          };\n          const startedAt = performance.now();\n          tap({ stage: \"start\", action: identity, details: { task } });\n          tap({\n            stage: \"end\",\n            result: \"error\",\n            action: identity,\n            details: {\n              task,\n              elapsed: performance.now() - startedAt,\n              mutations: { model: null, env: null },\n              error: getError(caught),\n              reason: getReason(caught),\n            },\n          });\n          broadcast.fire(FaultSymbol, {\n            reason: getReason(caught),\n            error: getError(caught),\n            action: envelope.name,\n            handled: false,\n            tasks,\n            retry: deliver,\n          });\n          return Promise.resolve();\n        }\n      };\n      void deliver();\n    });\n\n    return () => {\n      source.close();\n      client.current = null;\n    };\n  }, [config, handle, broadcast, tasks, tap]);\n\n  return <SseContext.Provider value={handle}>{children}</SseContext.Provider>;\n}\n","import * as React from \"react\";\nimport { Context } from \"./utils.ts\";\nimport type { Props, Tap } from \"./types.ts\";\n\nexport { useTap } from \"./utils.ts\";\nexport type {\n  Tap,\n  Taps,\n  Invocation,\n  Failure,\n  Mutations,\n  Snapshot,\n} from \"./types.ts\";\n\n/**\n * Internal provider that wires a {@link Tap} observer into the React\n * context consumed by `useActions` during dispatch. Rendered by the\n * top-level `<Boundary>` (and indirectly by `<app.Boundary>`); not\n * exposed on the public surface &mdash; consumers should pass the\n * callback via the `tap` prop of either boundary instead of mounting\n * this provider directly.\n *\n * The supplied `tap` callback is held in a `useRef` and indirected\n * through a stable `useMemo` wrapper. The ref is synchronised inside a\n * `useLayoutEffect` &mdash; React's sanctioned write-after-commit\n * window &mdash; so the provider stays compatible with Concurrent\n * rendering, where the render function may be invoked more than once\n * per commit and direct mutation during render would race the\n * scheduler.\n *\n * Keeping the context value referentially constant for the lifetime of\n * the boundary means callers may pass inline arrow functions without\n * invalidating the dispatch pipeline on every render &mdash; the\n * latest callback is read at fire time, not at provider-render time.\n * When `tap` is `undefined`, the wrapper short-circuits via optional\n * chaining: no allocation per event beyond the wrapper call itself.\n *\n * @param props.tap Observer to receive lifecycle events for every action\n *   handler dispatched inside the boundary. See {@link Tap}.\n * @param props.children Subtree that should observe the supplied tap.\n * @returns Children rendered inside the tap context provider.\n *\n * @see {@link Tap} &mdash; the observer signature.\n * @see {@link Taps} &mdash; the discriminated union of event shapes.\n */\nexport function Tappable({ tap, children }: Props): React.ReactNode {\n  const ref = React.useRef<Tap | undefined>(tap);\n  React.useLayoutEffect(() => void (ref.current = tap), [tap]);\n\n  const value = React.useMemo<Tap>(() => (event) => ref.current?.(event), []);\n\n  return <Context.Provider value={value}>{children}</Context.Provider>;\n}\n","import type { ConsumerContext } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the consumer store.\n * Stores the latest value for each distributed action with full annotation support.\n */\nexport const Context = React.createContext<ConsumerContext>(new Map());\n\n/**\n * Hook to access the consumer store from context.\n *\n * @returns The Map of action symbols to their State entries.\n */\nexport function useConsumer(): ConsumerContext {\n  return React.useContext(Context);\n}\n","import * as React from \"react\";\nimport { Broadcaster } from \"./components/broadcast/index.tsx\";\nimport { Tasks } from \"./components/tasks/index.tsx\";\nimport { Env } from \"./components/env/index.tsx\";\nimport type { Env as EnvType } from \"./components/env/types.ts\";\nimport { SharingProvider } from \"./components/sharing/index.tsx\";\nimport { Sse } from \"./components/sse/index.tsx\";\nimport { Tappable } from \"./components/tap/index.tsx\";\nimport { Context as ConsumerContext } from \"./components/consumer/utils.ts\";\nimport type { ConsumerContext as ConsumerStore } from \"./components/consumer/types.ts\";\nimport type { Props } from \"./types.ts\";\n\n/**\n * Low-level boundary primitive. Wraps children with the Broadcaster,\n * Env, and Tasks providers required by every March Hare hook.\n *\n * Most applications should reach for {@link App} instead &mdash;\n * `App<E>({ env })` returns a typed `app.Boundary` along with\n * matching `useContext` / `useEnv` / `Resource` factories that all\n * close over the App's inferred env shape `E`. The bare `Boundary`\n * is exposed for advanced or library-internal use where the loose\n * Env record type is sufficient.\n *\n * @example\n * ```tsx\n * <Boundary env={{ session: null, locale: \"en-GB\" }}>\n *   <App />\n * </Boundary>\n * ```\n */\nexport function Boundary({ env, tap, sse, children }: Props): React.ReactNode {\n  const consumer = React.useMemo<ConsumerStore>(() => new Map(), []);\n  return (\n    <Broadcaster>\n      <ConsumerContext.Provider value={consumer}>\n        <Env initial={env ?? ({} as EnvType)}>\n          <Tasks>\n            <Tappable tap={tap}>\n              <SharingProvider>\n                <Sse config={sse}>{children}</Sse>\n              </SharingProvider>\n            </Tappable>\n          </Tasks>\n        </Env>\n      </ConsumerContext.Provider>\n    </Broadcaster>\n  );\n}\n","import type { ScopeContext, ScopeEntry } from \"./types.ts\";\nimport * as React from \"react\";\n\n/**\n * React context for the nearest multicast scope. `null` at the root.\n *\n * @internal\n */\nexport const Context = React.createContext<ScopeContext>(null);\n\n/**\n * Hook that returns the nearest multicast scope entry. `null` when\n * the caller is not rendered inside any `<app.Scope().Boundary>`.\n *\n * @internal\n */\nexport function useScope(): ScopeContext {\n  return React.useContext(Context);\n}\n\n/**\n * Pass-through accessor. Kept for the dispatch/subscribe sites that\n * previously needed an action-keyed lookup; now the scope is a single\n * entry (or `null`), so this returns it as-is.\n *\n * @internal\n */\nexport function getScope(context: ScopeContext): ScopeEntry | null {\n  return context;\n}\n","import type { Adapter, Encoded, Stored } from \"./types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { config, empty, present, unset } from \"../utils/utils.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type { Adapter, Encoded } from \"./types.ts\";\n\n/**\n * Context passed to {@link CacheConfig.key}. Mirrors the shape an\n * `app.Resource` fetcher receives, restricted to the field the cache\n * needs to scope on: the live per-`<Boundary>` Env. Future-extensible\n * &mdash; new fields can land here without breaking the call shape.\n *\n * @template E The Env shape the cache is parameterised by.\n */\nexport type CacheContext<E extends object> = {\n  readonly env: E;\n};\n\n/**\n * Optional `key(context)` callback shared by both {@link CacheConfig}\n * variants. Derives a per-context cache scope. Called every time a\n * cache key is assembled with the same `{ env }` shape an\n * `app.Resource` fetcher receives; the returned string is prepended\n * to the per-resource namespace and params so different scopes\n * (e.g. one cache slot per access token, locale, or tenant id) can\n * coexist in the same backing store. Return `\"\"`, `null`, or\n * `undefined` to skip prefixing &mdash; useful for \"not signed in\"\n * gaps where the scope is genuinely empty.\n */\ntype CacheKeyOnly<E extends object> = {\n  readonly key?: (context: CacheContext<E>) => string | null | undefined;\n  readonly get?: never;\n  readonly set?: never;\n  readonly remove?: never;\n  readonly keys?: never;\n};\n\ntype CacheAdapter<E extends object> = Adapter & {\n  readonly key?: (context: CacheContext<E>) => string | null | undefined;\n};\n\n/**\n * Configuration accepted by the {@link Cache} factory. A discriminated\n * union with two shapes:\n *\n * - **Adapter-only / adapter + `key`** &mdash; supply the four\n *   adapter methods (`get`/`set`/`remove`/`keys`) and an optional\n *   `key(context)` callback. The cache is backed by the adapter;\n *   persistence is the caller's responsibility. There is no `clear`\n *   &mdash; the Cache layer synthesises one by iterating `keys()`\n *   and removing only entries inside the `mh:` namespace it owns,\n *   so third-party state on shared backends stays untouched.\n * - **`key`-only** &mdash; supply just `key(context)` (no adapter\n *   methods at all). The cache falls back to a per-instance in-memory\n *   adapter but still scopes every slot by the live Env, which is\n *   useful for tests, ephemeral state, or signed-out sessions where\n *   you want env-scoped isolation without touching storage.\n *\n * The split is enforced by the union: passing a partial adapter\n * (e.g. just `get`) is a type error &mdash; either all four required\n * adapter methods are present or none of them are. {@link Cache} also\n * accepts no argument at all for a plain in-memory cache.\n */\nexport type CacheConfig<E extends object> = CacheAdapter<E> | CacheKeyOnly<E>;\n\n/**\n * Persistence-aware cache for a single {@link Resource}. Wraps a\n * **strictly synchronous** {@link Adapter} (localStorage, MMKV,\n * chrome.storage with a sync facade, etc.) and traffics in {@link\n * Stored} envelopes &mdash; storage entries serialise as {@link\n * Encoded}`<T>` so the `Temporal.Instant` timestamp survives the\n * string round-trip and `.exceeds({...})` can short-circuit on the\n * persisted timestamp after a reload.\n *\n * Every method on the Cache is sync &mdash; the model-literal sync\n * read has no place to wait, so the adapter contract foregoes\n * `Promise` entirely. Async backends (IndexedDB, AsyncStorage,\n * `chrome.storage.local`) need a sync facade hydrated at app entry;\n * see `recipes/storage.md` for the pattern. React Native projects\n * should reach for {@link https://github.com/mrousavy/react-native-mmkv\n * `react-native-mmkv`} &mdash; it's synchronous out of the box and\n * drops straight into the Adapter contract.\n *\n * Call with no arguments for an in-memory cache scoped to this\n * instance &mdash; useful for tests, ephemeral state, or when you\n * want a first-class cache object to share between Resources without\n * persistence. Pass an {@link Adapter} to back the cache with a\n * persistent store; when supplied, the adapter is the **only** tier\n * &mdash; the Cache does not maintain a separate in-memory mirror.\n *\n * `key(context)` is independently optional. Pass it alongside the\n * adapter methods to scope a persistent cache by the live Env, or on\n * its own (with no adapter) for an env-scoped in-memory cache. The\n * adapter methods are an all-or-nothing group: supply all four\n * (`get`/`set`/`remove`/`keys`) or none. Supplying a partial adapter\n * is a type error.\n *\n * The `E` generic lives on the {@link Cache} factory and on\n * {@link CacheConfig}: it parameterises the `key(context)` callback\n * at construction time so the caller can read `context.env.X` with\n * full typing. The returned {@link Cache} value is itself\n * env-agnostic &mdash; the runtime `scope(env)` method takes the\n * loose {@link Env} record and narrows internally before invoking\n * the callback &mdash; which keeps it freely assignable across\n * differently-typed Apps without variance gymnastics.\n *\n * @example\n * ```ts\n * // In-memory, scoped to this instance.\n * const cache = Cache();\n *\n * // Persisted via localStorage.\n * const cache = Cache({\n *   get: (key) => localStorage.getItem(key),\n *   set: (key, value) => localStorage.setItem(key, value),\n *   remove: (key) => localStorage.removeItem(key),\n *   keys: () => Object.keys(localStorage),\n * });\n *\n * // Multi-tenant: writes go under `${accessToken}:…`.\n * type AppEnv = { session: { accessToken: string } | null };\n * const cache = Cache<AppEnv>({\n *   get: (key) => localStorage.getItem(key),\n *   set: (key, value) => localStorage.setItem(key, value),\n *   remove: (key) => localStorage.removeItem(key),\n *   keys: () => Object.keys(localStorage),\n *   key: ({ env }) => env.session?.accessToken ?? \"\",\n * });\n *\n * // Env-scoped in-memory cache: no adapter, just `key`.\n * const cache = Cache<AppEnv>({\n *   key: ({ env }) => env.session?.accessToken ?? \"\",\n * });\n *\n * // Wire it into a Resource — successful runs write through automatically.\n * export const cat = Resource({\n *   cache,\n *   fetch: (context) => fetchCat(context.controller.signal),\n * });\n * ```\n */\nexport type Cache = {\n  /**\n   * Returns the {@link Stored} envelope for `key`. The envelope is\n   * `empty()` when nothing is persisted; otherwise it carries the\n   * decoded payload and the timestamp recorded at write-time.\n   *\n   * @template T The payload type expected at `key`.\n   * @param key Cache slot identifier &mdash; usually the JSON-stringified\n   *   call-site params, prefixed by the Resource's namespace.\n   */\n  get<T>(key: string): Stored<T>;\n  /**\n   * Writes `value` to `key`. Skipped when the envelope has no concrete\n   * payload (e.g. an `empty()` slot), since there is nothing meaningful\n   * to persist. Serialisation, quota errors, and unserialisable payloads\n   * are swallowed &mdash; writes are best-effort.\n   *\n   * @template T The payload type contained in `value`.\n   * @param key Cache slot identifier &mdash; usually the JSON-stringified\n   *   call-site params, prefixed by the Resource's namespace.\n   * @param value Stored envelope carrying the payload and its\n   *   write-time `Temporal.Instant`.\n   */\n  set<T>(key: string, value: Stored<T>): void;\n  /**\n   * Drops a single cache slot. Best-effort &mdash; backing-store errors\n   * are swallowed.\n   *\n   * @param key Cache slot identifier.\n   */\n  remove(key: string): void;\n  /**\n   * Drops every cache slot in the backing store. Best-effort &mdash;\n   * backing-store errors are swallowed.\n   */\n  clear(): void;\n  /**\n   * Returns every key currently held by the backing store. Used by\n   * partial-match eviction (`evict(where)`) to iterate slots whose\n   * stored params satisfy a `where` pattern.\n   */\n  keys(): Iterable<string>;\n  /**\n   * Returns the per-context prefix derived from the configured\n   * `key(context)`. The returned string is appended with `:` by the\n   * Resource layer to compose the full cache key. Always `\"\"` when\n   * no `key` option was supplied or when the callback returned an\n   * empty value &mdash; \"no scope\" is encoded as the empty string.\n   *\n   * Takes the loose {@link Env} record at runtime &mdash; the typed\n   * `E` lives on the `key(context)` callback registered at\n   * construction time, which the cache narrows to `E` internally\n   * before invoking.\n   *\n   * @internal Public surface lives on the Resource layer; consumers\n   *   should not need to call this directly.\n   */\n  scope(env: Env | undefined): string;\n};\n\n/**\n * Type guard: narrows {@link CacheConfig} to its adapter-bearing arm.\n * Distinguishes the two variants of the union at runtime by checking\n * whether `get` is a real function &mdash; the `CacheKeyOnly` arm\n * declares the adapter members as `never`, so the only way `config.get`\n * can be a function at runtime is if the caller passed a real\n * {@link Adapter}.\n *\n * @internal\n */\nfunction isCacheAdapter<E extends object>(\n  options: CacheConfig<E> | undefined,\n): options is CacheAdapter<E> {\n  return (\n    !G.isUndefined(options) &&\n    \"get\" in options &&\n    typeof options.get === \"function\"\n  );\n}\n\n/**\n * In-memory {@link Adapter} backed by a `Map`. Created on demand inside\n * {@link Cache} when no adapter is supplied; tests and ephemeral use\n * cases get an isolated slot without touching storage.\n *\n * @internal\n */\nfunction memoryAdapter(): Adapter {\n  const memory = new Map<string, string>();\n  return {\n    get: (key) => memory.get(key) ?? null,\n    set: (key, value) => {\n      memory.set(key, value);\n    },\n    remove: (key) => {\n      memory.delete(key);\n    },\n    keys: () => memory.keys(),\n  };\n}\n\n/**\n * Constructs a {@link Cache} from `config`. The config object is a\n * discriminated union of two shapes:\n *\n * - Adapter methods (`get`/`set`/`remove`/`keys`) plus an optional\n *   `key(context)`.\n * - Just `key(context)` &mdash; no adapter methods at all, which falls\n *   back to a per-instance in-memory adapter while still scoping every\n *   slot by the live Env.\n *\n * Supplying a partial adapter (e.g. just `get` and `set`, or omitting\n * `keys`) is a type error: the adapter members are an all-or-nothing\n * group. Omit `config` entirely for a plain in-memory cache.\n *\n * When `key` is supplied, it runs each time the Resource layer\n * assembles a cache key, receiving the same `{ env }` shape an\n * `app.Resource` fetcher sees; its return value is prepended\n * (separated by `:`) to the per-resource namespace and params JSON.\n *\n * @template E The Env shape `config.key` is typed against. Defaults\n *   to the loose {@link Env} record so callers that don't scope by\n *   env can keep using `Cache({ ...adapter })` without supplying a\n *   generic.\n * @param config Optional config literal. Omit for an in-memory cache;\n *   supply adapter methods for a persisted cache; supply `key` to\n *   scope writes by the live Env (with or without an adapter).\n */\nexport function Cache<E extends object = Env>(options?: CacheConfig<E>): Cache {\n  const backing: Adapter = isCacheAdapter(options) ? options : memoryAdapter();\n  const scopeFn = options?.key;\n\n  function ownedKeys(): readonly string[] {\n    try {\n      return Array.from(backing.keys()).reduce<readonly string[]>(\n        (acc, cacheKey) =>\n          cacheKey.startsWith(config.storageNamespace)\n            ? [...acc, cacheKey]\n            : acc,\n        [],\n      );\n    } catch {\n      return [];\n    }\n  }\n\n  return {\n    /**\n     * Reads `key` from the backing store (with the `mh:` namespace\n     * applied), parses the {@link Encoded} envelope, and re-hydrates\n     * the `Temporal.Instant`. Returns `empty()` when the slot is\n     * missing or the stored JSON is malformed.\n     */\n    get<T>(key: string): Stored<T> {\n      try {\n        const raw = backing.get(config.storageNamespace + key);\n        if (G.isNull(raw)) return empty<T>();\n        const parsed = <Encoded<T>>JSON.parse(raw);\n        return present(parsed.data, Temporal.Instant.from(parsed.at));\n      } catch {\n        return empty<T>();\n      }\n    },\n    /**\n     * Serialises `value` to JSON and writes it under the namespaced\n     * key. Skips envelopes whose payload is unset or whose timestamp\n     * is missing, and swallows quota / encoding / private-mode errors.\n     */\n    set<T>(key: string, value: Stored<T>): void {\n      if (value.data === unset || G.isNull(value.at)) return;\n      try {\n        backing.set(\n          config.storageNamespace + key,\n          JSON.stringify(<Encoded<T>>{\n            data: value.data,\n            at: value.at.toString(),\n          }),\n        );\n      } catch {\n        return;\n      }\n    },\n    /**\n     * Removes a single slot. Backing-store errors are swallowed\n     * &mdash; eviction is best-effort.\n     */\n    remove(key: string): void {\n      try {\n        backing.remove(config.storageNamespace + key);\n      } catch {\n        return;\n      }\n    },\n    /**\n     * Removes every entry in the `mh:` namespace from the backing\n     * store. Non-March-Hare keys (third-party `localStorage` writes,\n     * dismissed banners, route hints, etc.) are left in place. Errors\n     * from individual `remove` calls are swallowed &mdash; clear is\n     * best-effort.\n     */\n    clear(): void {\n      for (const cacheKey of ownedKeys()) {\n        try {\n          backing.remove(cacheKey);\n        } catch {\n          continue;\n        }\n      }\n    },\n    /**\n     * Yields every `mh:`-namespaced key the backing store currently\n     * holds, with the namespace stripped so callers see the same key\n     * shape they passed to `set`/`get`/`remove`. Throws from the\n     * adapter (decryption, IPC, sandboxed iframes) are swallowed and\n     * surface as an empty iterable so eviction stays best-effort.\n     */\n    *keys(): IterableIterator<string> {\n      for (const cacheKey of ownedKeys()) {\n        yield cacheKey.slice(config.storageNamespace.length);\n      }\n    },\n    scope(env: Env | undefined): string {\n      if (G.isUndefined(scopeFn) || G.isNullable(env)) return \"\";\n      try {\n        const prefix = scopeFn({ env: <E>(<unknown>env) });\n        return G.isNullable(prefix) ? \"\" : prefix;\n      } catch {\n        return \"\";\n      }\n    },\n  };\n}\n","import { Cache } from \"../cache/index.ts\";\nimport { present, unset } from \"../utils/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { Action } from \"../action/index.ts\";\nimport { Distribution, type Filter } from \"../types/index.ts\";\nimport type {\n  Args,\n  Dispatch,\n  Fetcher,\n  Invocation,\n  LocalInvocation,\n  LocalResourceHandle,\n  ResourceEvictor,\n  ResourceHandle,\n} from \"./types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport { Cache } from \"../cache/index.ts\";\n\n/**\n * Default in-memory `Cache` used when {@link Resource} is constructed\n * without an explicit one. Each fetcher gets its own slot via the\n * outer `WeakMap` so unrelated Resources don't share a string-key\n * namespace.\n *\n * @internal\n */\nexport const defaults = new WeakMap<object, Cache>();\n\n/**\n * Returns the {@link Cache} bound to `fetcher`, allocating a fresh\n * in-memory Cache on first access.\n *\n * @internal\n */\nexport function defaultCache(fetcher: object): Cache {\n  const existing = defaults.get(fetcher);\n  if (G.isNotNullable(existing)) return existing;\n  const cache = Cache();\n  defaults.set(fetcher, cache);\n  return cache;\n}\n\n/**\n * Stable string key derived from the call-site `params`. Two calls with\n * the same logical params (same key order, same primitive values) hit\n * the same slot. JSON.stringify is sufficient for the March Hare params\n * convention (primitive-leaf objects); callers who need order-stable\n * keying should normalise the object before passing it in.\n *\n * @internal\n */\nexport function key(params: object): string {\n  return JSON.stringify(params);\n}\n\n/**\n * Per-fetcher namespace registry. Each declared Resource takes a stable\n * id derived from the order of insertion (`namespaces.size`), used to\n * prefix cache keys when an App-shared {@link Cache} is configured.\n *\n * @internal\n */\nconst namespaces = new Map<object, string>();\n\n/**\n * Per-Resource eviction callbacks. Each `Resource` declaration registers\n * one entry on construction; the public `nuke(...)` (defined in\n * {@link \"./index.ts\"}) iterates them to drop cache slots across every\n * Resource in the process.\n *\n * @internal\n */\nexport const evictors: Array<ResourceEvictor> = [];\n\n/**\n * Mints the next namespace id for an app-shared cache. Each `app.Resource`\n * declaration consumes one id so the shared {@link Cache} can keep\n * resource-specific slots from colliding on shared params keys.\n *\n * @internal\n */\nexport function nextResourceId(fetcher: object): string {\n  const existing = namespaces.get(fetcher);\n  if (G.isNotNullable(existing)) return existing;\n  const namespace = String(namespaces.size);\n  namespaces.set(fetcher, namespace);\n  return namespace;\n}\n\n/**\n * Allocates the per-Resource closures shared by the fetched and local\n * builders: cache-key composition, the auto-broadcast action, sync\n * reads, the write-then-broadcast path, eviction, and the handle-level\n * `.get`/`.action` members. `build` layers the fetcher's `run` on top;\n * `buildLocal` exposes the write path directly as `.set(...)`.\n *\n * `getEnv` is the App-supplied accessor used to resolve the live env at\n * sync read time (`.get(params)`) and at App-side eviction (when the\n * handler context isn't available). It returns `undefined` when no\n * Boundary has mounted yet &mdash; in which case `cache.scope(undefined)`\n * yields the empty prefix and the read/evict targets the unscoped slot.\n *\n * @internal\n */\nfunction foundations<T, P extends object>(\n  backing: Cache,\n  namespace: string | null,\n  getEnv: () => Env | undefined,\n  label: string,\n) {\n  const suffix = G.isNull(namespace) ? \"\" : `${namespace}:`;\n  const composeKey = (env: Env | undefined, params: P) => {\n    const scope = backing.scope(env);\n    const prefix = scope === \"\" ? \"\" : `${scope}:`;\n    return `${prefix}${suffix}${key(params)}`;\n  };\n\n  const action = Action<T | null, Filter>(\n    `resource:${label}`,\n    Distribution.Broadcast,\n  );\n\n  const read = (params: P, env: Env | undefined) => {\n    const stored = backing.get<T>(composeKey(env, params));\n    if (stored.data === unset || G.isNull(stored.at)) {\n      return { data: unset, at: null };\n    }\n    return { data: <T>stored.data, at: stored.at };\n  };\n\n  const write = (\n    env: Env | undefined,\n    params: P,\n    value: T,\n    dispatch: Dispatch,\n  ): void => {\n    backing.set(\n      composeKey(env, params),\n      present(value, Temporal.Now.instant()),\n    );\n    void dispatch(action(<Filter>(<unknown>params)), value);\n  };\n\n  function actionFn(channel?: Partial<P> & Filter) {\n    return action(<Filter>(channel ?? {}));\n  }\n\n  const evict = (where: object, dispatch?: Dispatch): void => {\n    const env = getEnv();\n    const scope = backing.scope(env);\n    const fullPrefix = scope === \"\" ? suffix : `${scope}:${suffix}`;\n    const entries = Object.entries(where);\n    const evicted: Array<Filter> = [];\n    for (const cacheKey of [...backing.keys()]) {\n      if (!cacheKey.startsWith(fullPrefix)) continue;\n      try {\n        const parsed = <Record<string, unknown>>(\n          JSON.parse(cacheKey.slice(fullPrefix.length))\n        );\n        if (entries.every(([field, value]) => parsed[field] === value)) {\n          backing.remove(cacheKey);\n          evicted.push(<Filter>parsed);\n        }\n      } catch {\n        continue;\n      }\n    }\n    if (G.isNotNullable(dispatch)) {\n      for (const channel of evicted) {\n        void dispatch(action(channel), null);\n      }\n    }\n  };\n\n  evictors.push(evict);\n\n  function get(params?: P): T | null {\n    const { data } = read(<P>(params ?? {}), getEnv());\n    return data === unset ? null : <T>data;\n  }\n\n  return { read, write, evict, actionFn, get };\n}\n\n/**\n * Allocates the per-Resource closure shared by `app.Resource` and\n * `shared.Resource`. The returned callable produces an\n * {@link Invocation} on every call &mdash; pass it to\n * `context.actions.resource(...)` for fetch/evict. `.get(params)` reads\n * the per-params cache slot synchronously.\n *\n * @internal\n */\nexport function build<T, P extends object>(\n  ƒ: Fetcher<T, P>,\n  backing: Cache,\n  namespace: string | null,\n  getEnv: () => Env | undefined,\n): ResourceHandle<T, P> {\n  const { read, write, evict, actionFn, get } = foundations<T, P>(\n    backing,\n    namespace,\n    getEnv,\n    ƒ.name || \"anonymous\",\n  );\n\n  const run = (\n    env: Env,\n    controller: AbortController,\n    params: P,\n    dispatch: Dispatch,\n  ): Promise<T> =>\n    ƒ(<Args<P>>{ env, controller, params, dispatch }).then((resolved) => {\n      write(env, params, resolved, dispatch);\n      return resolved;\n    });\n\n  function call(params?: P): Invocation<T, P> {\n    const effective = <P>(params ?? {});\n    return <Invocation<T, P>>{\n      run,\n      read: (params: P) => read(params, getEnv()),\n      evict,\n      params: effective,\n    };\n  }\n\n  Object.defineProperty(call, \"get\", { value: get, enumerable: false });\n  Object.defineProperty(call, \"action\", { value: actionFn, enumerable: false });\n\n  return <ResourceHandle<T, P>>(<unknown>call);\n}\n\n/**\n * Allocates the per-Resource closure for a fetcherless (local)\n * declaration. The returned callable produces a {@link LocalInvocation}\n * on every call &mdash; pass it to `context.actions.resource(...)` for\n * `.set(value)`/`.evict(where?)`. The invocation carries no `run`, so\n * it cannot be awaited and the fetch chain never applies. `.set` walks\n * the same write path a successful fetch would: cache write first, then\n * the auto-broadcast with the call params as the channel.\n *\n * @internal\n */\nexport function buildLocal<T, P extends object>(\n  backing: Cache,\n  namespace: string | null,\n  getEnv: () => Env | undefined,\n): LocalResourceHandle<T, P> {\n  const { read, write, evict, actionFn, get } = foundations<T, P>(\n    backing,\n    namespace,\n    getEnv,\n    \"local\",\n  );\n\n  function call(params?: P): LocalInvocation<T, P> {\n    const effective = <P>(params ?? {});\n    return <LocalInvocation<T, P>>{\n      write,\n      read: (params: P) => read(params, getEnv()),\n      evict,\n      params: effective,\n    };\n  }\n\n  Object.defineProperty(call, \"get\", { value: get, enumerable: false });\n  Object.defineProperty(call, \"action\", { value: actionFn, enumerable: false });\n\n  return <LocalResourceHandle<T, P>>(<unknown>call);\n}\n","import type {\n  Dispatch,\n  Fetcher,\n  LocalResourceHandle,\n  ResourceHandle,\n} from \"./types.ts\";\nimport {\n  Cache,\n  build,\n  buildLocal,\n  defaultCache,\n  evictors,\n  nextResourceId,\n} from \"./utils.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type {\n  Fetcher,\n  Invocation,\n  LocalInvocation,\n  LocalResourceHandle,\n  ResourceHandle,\n} from \"./types.ts\";\n\n/**\n * Evicts cache entries across every Resource constructed in the\n * current process. Resources register themselves on declaration, so\n * `nuke` covers both `app.Resource` and `shared.Resource`. Pass a\n * `where` pattern to drop only slots whose stored params satisfy the\n * pattern's keys (partial match &mdash; extra keys in the stored\n * params are ignored). Pass nothing to clear every known slot.\n *\n * When called via `context.actions.resource.nuke(...)`, the calling\n * boundary's `dispatch` is threaded through so each evicted slot fires\n * a `null` broadcast on its Resource's `.action()` &mdash; subscribers\n * inside that boundary see the eviction as a `null` payload with the\n * evicted params as the channel.\n *\n * @internal Public surface lives on `context.actions.resource.nuke(...)`.\n */\nexport function nuke(where?: object, dispatch?: Dispatch): void {\n  const pattern = where ?? {};\n  for (const evict of evictors) evict(pattern, dispatch);\n}\n\n/**\n * Defines a remote resource &mdash; declared at module scope and used\n * directly. Exported as `shared.Resource` and (via the app factory) as\n * `app.Resource`. Calling the returned handle with `params` produces an\n * {@link Invocation} suitable for `context.actions.resource(...)` (fetch\n * path) or `context.actions.resource(...).evict(where?)` (partial-match\n * invalidation). Use `.get(params)` on the handle for a synchronous\n * cache read returning `T | null`. Persistence happens automatically\n * when the App is declared with `App({ cache })`.\n *\n * Takes the **Env shape `E` as a mandatory first generic** &mdash;\n * `context.env` inside the fetcher is typed as `E`. Pass a union of\n * every App's Env if the resource is shared across reusable\n * components. For single-app resources, prefer `app.Resource` &mdash;\n * the Env is captured from `app` automatically and you only need the\n * payload generic.\n *\n * The fetcher receives a single `context` argument carrying `env`,\n * `controller`, `params`, and a broadcast/multicast-only `dispatch`.\n * `env` is a live handle &mdash; dot reads inside the fetcher always\n * see the latest per-`<Boundary>` Env, even after `await` boundaries.\n *\n * Cache behaviour is decided at the App level: when `App({ cache })`\n * is supplied, every `app.Resource` declaration on that App writes\n * through to (and seeds from) the shared cache, isolated per resource\n * by a stable module-order namespace. When the App is constructed\n * without a `cache`, every resource keeps its own in-memory slot.\n * Standalone `shared.Resource` declarations always use an in-memory\n * cache &mdash; reach for `app.Resource` when persistence is required.\n *\n * Concurrent calls with the same `(Resource, params)` share a single\n * in-flight fetch by default &mdash; one network request, every caller\n * resolves with the same payload. The underlying work is refcounted: if\n * every caller aborts, the shared `AbortController` is aborted too.\n * Chain `.isolated()` on the thenable returned from\n * `context.actions.resource(...)` to opt out (own controller, own\n * request) for the rare cases that need it.\n *\n * @template E The Env shape (or union) the fetcher's `context.env` is\n *   typed against.\n * @template T The payload type the fetcher resolves to.\n * @template P The call-time params type.\n *\n * @example\n * ```ts\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n *\n * export const user = shared.Resource<WebEnv, User, { id: number }>((context) =>\n *   ky\n *     .get(`users/${context.params.id}`, {\n *       headers: context.env.session\n *         ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n *         : {},\n *       signal: context.controller.signal,\n *     })\n *     .json<User>(),\n * );\n * ```\n *\n * Calling `Resource()` with **no fetcher** declares a **local\n * Resource** &mdash; the same cache, sync `.get(params)`, `.action()`\n * auto-broadcast, eviction, and persistence machinery, but with the\n * app as the only writer: values enter exclusively through\n * `context.actions.resource(resource.draft(params)).set(value)`. One\n * write path per variant &mdash; a fetched Resource's cache is only\n * ever written by its fetcher, a local Resource's only ever by\n * `.set(...)` &mdash; so the origin of a cached value is always\n * unambiguous. Local invocations are not awaitable and carry no\n * `.exceeds(...)`/`.isolated()` chain.\n *\n * @example\n * ```ts\n * import { shared } from \"march-hare\";\n *\n * export const draft = shared.Resource<WebEnv, Draft, { id: number }>();\n *\n * actions.useAction(Actions.Save, (context, { id, draft: value }) => {\n *   context.actions.resource(draft({ id })).set(value);\n * });\n * ```\n *\n * @internal The optional `cache` argument is reserved for `app.Resource`\n *   &mdash; consumers should use `App({ cache })` instead of passing it\n *   directly.\n */\nexport function Resource<\n  _E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(): LocalResourceHandle<T, P>;\nexport function Resource<\n  E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(\n  ƒ: AppFetcher<E, T, P>,\n  cache?: Cache,\n  getEnv?: () => Env | undefined,\n): ResourceHandle<T, P>;\nexport function Resource<\n  _E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(\n  ƒ: undefined,\n  cache?: Cache,\n  getEnv?: () => Env | undefined,\n): LocalResourceHandle<T, P>;\nexport function Resource<\n  E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(\n  ƒ?: AppFetcher<E, T, P>,\n  cache?: Cache,\n  getEnv?: () => Env | undefined,\n): ResourceHandle<T, P> | LocalResourceHandle<T, P> {\n  const resolveEnv = getEnv ?? (() => undefined);\n  if (G.isUndefined(ƒ)) {\n    if (G.isUndefined(cache)) {\n      return buildLocal<T, P>(Cache(), null, resolveEnv);\n    }\n    return buildLocal<T, P>(cache, nextResourceId({}), resolveEnv);\n  }\n  const inner = <Fetcher<T, P>>(<unknown>ƒ);\n  if (G.isUndefined(cache)) {\n    return build(inner, defaultCache(inner), null, resolveEnv);\n  }\n  return build(inner, cache, nextResourceId(inner), resolveEnv);\n}\n","import{immerable as t,enablePatches as e,Immer as r}from\"immer\";import{G as i,A as n}from\"@mobily/ts-belt\";let s=(t=21)=>{let e=\"\",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\"[63&r[t]];return e};var o=/* @__PURE__ */(t=>(t[t.Add=1]=\"Add\",t[t.Remove=2]=\"Remove\",t[t.Update=4]=\"Update\",t[t.Move=8]=\"Move\",t[t.Replace=16]=\"Replace\",t[t.Sort=32]=\"Sort\",t[t.Create=64]=\"Create\",t[t.Fetch=128]=\"Fetch\",t[t.Clone=256]=\"Clone\",t[t.Archive=512]=\"Archive\",t[t.Restore=1024]=\"Restore\",t[t.Merge=2048]=\"Merge\",t[t.Reorder=4096]=\"Reorder\",t[t.Sync=8192]=\"Sync\",t[t.Publish=16384]=\"Publish\",t[t.Link=32768]=\"Link\",t[t.Unlink=65536]=\"Unlink\",t[t.Lock=131072]=\"Lock\",t[t.Unlock=262144]=\"Unlock\",t[t.Import=524288]=\"Import\",t[t.Export=1048576]=\"Export\",t[t.Transfer=2097152]=\"Transfer\",t))(o||{}),a=/* @__PURE__ */(t=>(t[t.Produce=0]=\"Produce\",t[t.Hydrate=1]=\"Hydrate\",t))(a||{}),c=/* @__PURE__ */(t=>(t.Property=\"property\",t.Process=\"process\",t.Value=\"value\",t.Operation=\"operation\",t))(c||{});class u{[t]=!0;static keys=new Set(Object.values(c));property=null;process=null;value;operation;constructor(t,e){this.value=t,this.operation=e}assign(t,e){const r=new u(this.value,this.operation);return r.property=t,r.process=e,r}}class l{static immer=(()=>{e();const t=new r;return t.setAutoFreeze(!1),t})();static tag=\"κ\";static id=s}const p=Symbol(\"Box\");function y(t,e){const r=\"string\"==typeof e?\"\"===e?[]:e.split(\".\"):e;let i=t;for(const n of r){if(null==i)return;i=i[n]}return i}function f(t){if(i.isNullable(t)||m(t))return t;if(i.isArray(t))return t.map(t=>f(t));if(i.isObject(t)&&h(t)){const e=Object.entries(t).map(([t,e])=>[t,f(e)]);return{...Object.fromEntries(e),[l.tag]:t[l.tag]??l.id()}}return t}function d(t){if(Array.isArray(t))return t.filter(t=>l.tag in t).map(t=>t[l.tag]??\"\").join(\",\");const e=t[l.tag];if(e)return e;try{return JSON.stringify(t)}catch{return`[unserializable:${typeof t}]`}}function h(t){const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e}function m(t){return i.isNullable(t)||i.isString(t)||i.isNumber(t)||i.isBoolean(t)||\"symbol\"==typeof t||\"bigint\"==typeof t}function b(t){return i.isObject(t)&&p in t}function g(t,e,r,n,s,o){return function c(l,p=e.path){if(l instanceof u){const e=y(r,p.join(\".\"));if(Object.entries(l).filter(([t,e])=>!u.keys.has(t)&&e instanceof u).forEach(([t,e])=>c(e,p.concat(t))),m(l.value)){if(t===a.Hydrate)return l.value;const c=p.slice(0,-1),u=c.length>0?y(r,c.join(\".\")):r;return i.isNullable(u)||v(u,l,p.at(-1),n,s,o),e??l.value}if(t===a.Hydrate){const t=f(c(l.value,p));return v(t,l,null,n,s,o),t}const d=e??f(l.value);return v(d,l,null,n,s,o),i.isNullable(e)?d:(c(l.value,p),e)}if(i.isArray(l))return l.map((t,e)=>c(t,p.concat(e)));if(i.isObject(l)&&!h(l))return l;if(i.isObject(l)){const e=Object.entries(l).map(([t,e])=>[t,c(e,p.concat(t))]),r=Object.fromEntries(e);if(t===a.Hydrate){const t=f(r);return Object.entries(l).forEach(([e,r])=>{r instanceof u&&m(r.value)&&v(t,r,e,n,s,o)}),t}return r}return l}(e.value)}function v(t,e,r,i,n,s){const o=s(t),a=n.get(o)??[];n.set(o,[e.assign(r,i),...a])}class O{#t={};#e;#r=/* @__PURE__ */new Map;#i=/* @__PURE__ */new Set;#n=!1;constructor(t=d){this.#e=t}static pk(){return s()}static\"κ\"=O.pk;annotate(t,e){return new u(e,t)}\"δ\"=this.annotate;get model(){return this.#t}get inspect(){return function(t,e,r,s,o){function a(s){const o=s.at(-1),a=y(t(),s),c=s.slice(0,-1),u=n.isNotEmpty(c)?y(t(),c):t();return[...i.isObject(a)||i.isArray(a)?e.get(r(a))?.filter(t=>i.isNullable(t.property))??[]:[],...i.isObject(u)?e.get(r(u))?.filter(t=>t.property===o)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(i,c)=>\"pending\"===c?()=>!n.isEmpty(a(r)):\"remaining\"===c?()=>n.length(a(r)):\"box\"===c?()=>({value:y(t(),r),inspect:e(r),[p]:!0}):\"is\"===c?t=>a(r).some(e=>0!==(e.operation&t)):\"draft\"===c?()=>n.head(a(r))?.value??y(t(),r):\"settled\"===c?()=>new Promise(e=>{if(n.isEmpty(a(r)))return e(y(t(),r));const i=()=>{n.isEmpty(a(r))&&(o(i),e(y(t(),r)))};s(i)}):e([...r,String(c)])})}([])}(()=>this.#t,this.#r,this.#e,t=>this.#i.add(t),t=>this.#i.delete(t))}hydrate(t){return this.#n=!0,this.#s(a.Hydrate,()=>t)}produce(t){if(!this.#n)throw new Error(\"State must be hydrated using hydrate() before calling produce()\");return this.#s(a.Produce,t)}#s(t,e){const r=Symbol(\"process\"),[,i]=l.immer.produceWithPatches(this.#t,e);return this.#t=i.reduce((e,i)=>l.immer.applyPatches(e,[{...i,value:g(t,i,e,r,this.#r,this.#e)}]),this.#t),this.#t=f(this.#t),this.#o(),r}prune(t){this.#r.forEach((e,r)=>{const i=e.filter(e=>e.process!==t);n.isEmpty(i)?this.#r.delete(r):this.#r.set(r,i)}),this.#o()}#o(){this.#i.forEach(t=>t())}observe(t){const e=()=>t(this.#t);return this.#i.add(e),()=>this.#i.delete(e)}}export{o as Op,o as Operation,O as State,b as isBox};\n","import * as React from \"react\";\nimport { State, Inspect } from \"immertation\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useBroadcast } from \"../../../broadcast/index.tsx\";\nimport { useConsumer } from \"../../utils.ts\";\nimport { useRerender } from \"../../../../../utils/utils.ts\";\nimport { Entry, Model } from \"../../types.ts\";\nimport { Props } from \"./types.ts\";\n\n/**\n * Renders output for the `stream()` method by subscribing to distributed action events.\n *\n * This component manages a subscription to the broadcast emitter for distributed actions,\n * storing the latest dispatched value in the Consumer context. When a new value arrives,\n * all mounted Partition instances for that action re-render with the updated value.\n *\n * On mount, if a value was previously dispatched for this action, it renders immediately\n * with that cached value. If no value exists yet, it renders `null` until the first dispatch.\n *\n * Uses Immertation's State class internally to manage consumed values, providing real\n * annotation tracking through the `inspect` proxy. When a payload containing annotated\n * values is dispatched, the annotations are preserved and accessible via `inspect`.\n *\n * The renderer callback receives two arguments:\n * - `value`: The latest dispatched payload\n * - `inspect`: A proxy for checking annotation status (pending, is, draft, settled, etc.)\n *\n * @template T - The payload type for the action (must be an object type)\n * @param props.action - The distributed action symbol to subscribe to\n * @param props.renderer - Callback that receives value and inspect, returns React nodes\n * @returns The result of calling renderer, or null if no value exists\n * @internal\n */\nexport function Partition<T extends object>({\n  action,\n  renderer,\n}: Props<T>): React.ReactNode {\n  const broadcast = useBroadcast();\n  const consumer = useConsumer();\n  const rerender = useRerender();\n\n  const entry = React.useMemo(() => {\n    const existing = consumer.get(action);\n    if (existing) return existing as Entry<T>;\n\n    const state = new State<Model<T>>();\n    const cached = broadcast.getCached(action);\n    if (G.isNotNullable(cached)) state.hydrate({ value: cached as T });\n    const entry: Entry<T> = { state, listeners: new Set() };\n    consumer.set(action, entry as unknown as Entry);\n    return entry;\n  }, [action, broadcast, consumer]);\n\n  React.useLayoutEffect(() => {\n    entry.listeners.add(rerender);\n\n    function handlePayload(payload: T) {\n      entry.state.hydrate({ value: payload });\n      entry.listeners.forEach((listener) => listener());\n    }\n\n    broadcast.on(action, handlePayload);\n\n    return () => {\n      entry.listeners.delete(rerender);\n      broadcast.off(action, handlePayload);\n    };\n  }, [action, broadcast, entry]);\n\n  const value = entry.state.model?.value;\n  if (G.isNullable(value)) return null;\n\n  const inspect = entry.state.inspect as unknown as { value: Inspect<T> };\n\n  return renderer(value, inspect.value);\n}\n","import * as React from \"react\";\nimport {\n  useLifecycles,\n  useData,\n  isChanneledAction,\n  getActionSymbol,\n  matchesChannel,\n  useRegisterHandler,\n  useReactiveEmit,\n  useDispatchers,\n  findLifecycleAction,\n  isGenerator,\n  emitAsync,\n} from \"./utils.ts\";\nimport { useRerender } from \"../utils/utils.ts\";\nimport type { Data, Handler, Scope } from \"./types.ts\";\nimport {\n  HandlerContext,\n  Phase,\n  Model,\n  HandlerPayload,\n  Props,\n  Actions,\n  ActionId,\n  UseActions,\n  Result,\n  Task,\n  CurrentTask,\n  Filter,\n  ChanneledAction,\n  ActionOrChanneled,\n  AnyAction,\n  Audience,\n  FaultSymbol,\n  EnvSymbol,\n} from \"../types/index.ts\";\n\nimport { getReason, getError } from \"../error/utils.ts\";\nimport { Aborted } from \"../error/index.ts\";\nimport EventEmitter from \"eventemitter3\";\nimport { useBroadcast } from \"../boundary/components/broadcast/index.tsx\";\nimport { useScope, getScope } from \"../boundary/components/scope/index.tsx\";\nimport { useEnv, useEnvRef } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { produce as produceImmer } from \"immer\";\nimport { nuke } from \"../resource/index.ts\";\nimport type { Invocation, LocalInvocation } from \"../resource/types.ts\";\nimport type {\n  LocalResourceCall,\n  ResourceCall,\n  ResourceDispatcher,\n} from \"../types/index.ts\";\nimport { withAbort } from \"../coalesce/index.ts\";\nimport type { Share } from \"../boundary/components/sharing/index.tsx\";\nimport { unset } from \"../utils/utils.ts\";\nimport {\n  isBroadcastAction,\n  isMulticastAction,\n  isOmnicastAction,\n  getName,\n} from \"../action/index.ts\";\nimport { useSse } from \"../boundary/components/sse/index.tsx\";\n\n/**\n * Stand-in for `context.actions.tag` when the App has no `sse` endpoint\n * configured: tag mutations are connection-level concerns, so without a\n * connection they resolve as no-ops and components stay portable between\n * connected and unconnected Apps.\n */\nconst idleTag = {\n  add: () => Promise.resolve(),\n  remove: () => Promise.resolve(),\n  has: () => false,\n  clear: () => Promise.resolve(),\n};\nimport { State, Operation, Process, Inspect } from \"immertation\";\nimport { useTasks } from \"../boundary/components/tasks/utils.ts\";\nimport { Partition } from \"../boundary/components/consumer/index.tsx\";\nimport type { ConsumerRenderer } from \"../boundary/components/consumer/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\nimport { useSharing } from \"../boundary/components/sharing/index.tsx\";\nimport { useTap } from \"../boundary/components/tap/utils.ts\";\n\n/**\n * A hook for managing state with actions.\n *\n * Call `useActions` first, then use `actions.useAction` to bind handlers\n * to action symbols. Types are pre-baked from the generic parameters, so\n * no additional type annotations are needed on handler calls.\n *\n * The hook returns a result containing:\n * 1. The current model state\n * 2. An actions object with `dispatch`, `inspect`, and `useAction`\n * 3. A read-only snapshot of the data values produced by `getData` &mdash;\n *    the same values handlers read via `context.data`, exposed here for\n *    JSX consumption so the view and the handler share one named source.\n *\n * The `inspect` property provides access to Immertation's annotation system,\n * allowing you to check for pending operations on model properties.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n * @param model The initial model state.\n * @param getData Optional function that returns reactive values as data.\n *   Values returned are accessible via `context.data` in action handlers,\n *   always reflecting the latest values even after await operations.\n * @returns A result `[model, actions, data]` with pre-typed `useAction` method.\n *\n * @example\n * ```typescript\n * // Basic usage\n * const [model, actions] = useActions<Model, typeof Actions>(model);\n *\n * // Without a model (actions-only)\n * const [, actions] = useActions<void, typeof Actions>();\n *\n * // With reactive data &mdash; consumed in JSX and handlers alike.\n * const [model, actions, data] = useActions<\n *   Model,\n *   typeof Actions,\n *   { query: string }\n * >(model, () => ({ query: props.query }));\n * ```\n */\nexport function useActions<\n  M extends void = void,\n  A extends Actions | void = void,\n  D extends Props = Props,\n>(getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n  M extends Model,\n  A extends Actions | void = void,\n  D extends Props = Props,\n>(model: M, getData?: Data<D>): UseActions<M, A, D>;\nexport function useActions<\n  M extends Model | void,\n  A extends Actions | void,\n  D extends Props = Props,\n>(...args: unknown[]): unknown {\n  const isVoidModel = G.isUndefined(args[0]) || G.isFunction(args[0]);\n  const initialModel = <Model>(isVoidModel ? {} : args[0]);\n  const getData: Data<D> = G.isFunction(args[0])\n    ? <Data<D>>args[0]\n    : <Data<D>>(args[1] ?? (() => <D>{}));\n\n  const broadcast = useBroadcast();\n  const scope = useScope();\n  const sse = useSse();\n  const tasks = useTasks();\n  const env = useEnv();\n  const slot = useEnvRef();\n  const sharing = useSharing();\n  const tap = useTap();\n  const rerender = useRerender();\n  const initialised = React.useRef(false);\n  const hydration = React.useRef<Process | null>(null);\n  const state = React.useRef(new State<Model>());\n\n  if (!initialised.current) {\n    initialised.current = true;\n    hydration.current = state.current.hydrate(initialModel);\n  }\n  const [model, setModel] = React.useState<M>(\n    () => <M>(<unknown>state.current.model),\n  );\n  const data = useData(getData());\n  const unicast = React.useMemo(() => new EventEmitter(), []);\n  const registry = React.useRef<Scope<M, A, D>>({ handlers: new Map() });\n  registry.current.handlers = new Map();\n  const dispatchers = useDispatchers();\n  const phase = React.useRef<Phase>(Phase.Mounting);\n  const localTasks = React.useRef<Set<Task>>(new Set());\n  const unmountGeneration = React.useRef(0);\n\n  /**\n   * Creates the context object passed to action handlers during dispatch.\n   *\n   * @param action The action symbol being dispatched.\n   * @param payload The payload passed with the action.\n   * @param result Container for tracking Immertation processes created during execution.\n   * @returns A fully-typed Context object for the action handler.\n   */\n  const getContext = React.useCallback(\n    (action: ActionId, payload: unknown, result: Result) => {\n      const controller = new AbortController();\n      const task: CurrentTask = {\n        controller,\n        action,\n        payload,\n        supersede() {\n          for (const sibling of tasks) {\n            if (sibling !== task && sibling.action === action) {\n              sibling.controller.abort(new Aborted(\"Superseded\"));\n            }\n          }\n        },\n      };\n      tasks.add(task);\n      localTasks.current.add(task);\n\n      return <HandlerContext<M, A, D>>(<unknown>{\n        get model() {\n          return state.current.model;\n        },\n        get phase() {\n          return phase.current;\n        },\n        task,\n        data,\n        tasks,\n        env,\n        actions: {\n          produce(\n            f: (draft: {\n              model: M;\n              readonly inspect: Readonly<Inspect<M>>;\n              env: Env;\n            }) => void,\n          ) {\n            if (controller.signal.aborted) return;\n            const slotBefore = slot.current;\n            const process = state.current.produce((draft) => {\n              slot.current = produceImmer(slot.current, (envDraft) => {\n                f({\n                  model: <M>(<unknown>draft),\n                  inspect: <Readonly<Inspect<M>>>(\n                    (<unknown>state.current.inspect)\n                  ),\n                  env: <Env>envDraft,\n                });\n              });\n            });\n            setModel(<M>(<unknown>state.current.model));\n            if (slot.current !== slotBefore) {\n              broadcast.emit(EnvSymbol, slot.current);\n            }\n            result.processes.add(process);\n            if (hydration.current) {\n              result.processes.add(hydration.current);\n              hydration.current = null;\n            }\n          },\n          dispatch(\n            action: ActionOrChanneled,\n            second?: HandlerPayload | Audience,\n            third?: HandlerPayload,\n          ): Promise<void> {\n            if (controller.signal.aborted) return Promise.resolve();\n            const base = getActionSymbol(action);\n            const channel = isChanneledAction(action)\n              ? action.channel\n              : undefined;\n            const omnicast = isOmnicastAction(action);\n            const payload = omnicast ? third : <HandlerPayload>second;\n            const audience = omnicast\n              ? <Audience | undefined>second\n              : undefined;\n\n            if (isMulticastAction(action)) {\n              const scoped = getScope(scope);\n              if (scoped)\n                return emitAsync(scoped.emitter, base, payload, channel);\n              return Promise.resolve();\n            }\n\n            if (omnicast && G.isNotNullable(sse)) {\n              return Promise.all([\n                emitAsync(broadcast, base, payload, channel),\n                sse.publish({\n                  name: getName(action),\n                  payload,\n                  channel: <Filter | undefined>channel,\n                  tags: audience?.tags ?? undefined,\n                }),\n              ]).then(() => undefined);\n            }\n\n            const emitter = isBroadcastAction(action) ? broadcast : unicast;\n            return emitAsync(emitter, base, payload, channel);\n          },\n          tag: G.isNotNullable(sse) ? sse.tag : idleTag,\n          annotate<T>(value: T, operation: Operation = Operation.Update): T {\n            return state.current.annotate(operation, value);\n          },\n          get inspect() {\n            return state.current.inspect;\n          },\n          resource: (() => {\n            const dispatchFromResource = (\n              action: unknown,\n              payload?: unknown,\n            ): Promise<void> => {\n              const a = <AnyAction>action;\n              const base = getActionSymbol(a);\n              const channel = isChanneledAction(a) ? a.channel : undefined;\n              if (isMulticastAction(a)) {\n                const scoped = getScope(scope);\n                if (scoped)\n                  return emitAsync(scoped.emitter, base, payload, channel);\n                return Promise.resolve();\n              }\n              if (isBroadcastAction(a)) {\n                return emitAsync(broadcast, base, payload, channel);\n              }\n              return Promise.resolve();\n            };\n            function resourceCall<T, P extends object>(\n              call: LocalInvocation<T, P>,\n            ): LocalResourceCall<T>;\n            function resourceCall<T, P extends object>(\n              call: Invocation<T, P>,\n            ): ResourceCall<T>;\n            function resourceCall<T, P extends object>(\n              call: Invocation<T, P> | LocalInvocation<T, P>,\n            ): LocalResourceCall<T> | ResourceCall<T> {\n              if (\"write\" in call) {\n                return {\n                  set(value: T): void {\n                    call.write(env, call.params, value, dispatchFromResource);\n                  },\n                  evict(where?: Record<string, unknown>): void {\n                    call.evict(where ?? call.params, dispatchFromResource);\n                  },\n                };\n              }\n              const options: {\n                exceedsWindow: Temporal.DurationLike | null;\n                isolated: boolean;\n              } = { exceedsWindow: null, isolated: false };\n              const fetch = (): Promise<T> => {\n                if (G.isNotNullable(options.exceedsWindow)) {\n                  const { data, at } = call.read(call.params);\n                  if (data !== unset && G.isNotNullable(at)) {\n                    const elapsed = Temporal.Now.instant().since(at);\n                    const window = Temporal.Duration.from(\n                      options.exceedsWindow,\n                    );\n                    if (Temporal.Duration.compare(elapsed, window) <= 0) {\n                      return Promise.resolve(<T>data);\n                    }\n                  }\n                }\n                if (options.isolated) {\n                  return <Promise<T>>(\n                    call.run(env, controller, call.params, dispatchFromResource)\n                  );\n                }\n                let mutable = sharing.get(call.run);\n                if (G.isUndefined(mutable)) {\n                  mutable = new Map<string, Share>();\n                  sharing.set(call.run, mutable);\n                }\n                const bucket = mutable;\n                const slot = JSON.stringify(call.params);\n                let share = <Share<T> | undefined>bucket.get(slot);\n                if (G.isUndefined(share)) {\n                  const detached = new AbortController();\n                  const created: Share<T> = <Share<T>>{\n                    controller: detached,\n                    refs: 0,\n                  };\n                  created.promise = (<Promise<T>>(\n                    call.run(env, detached, call.params, dispatchFromResource)\n                  )).finally(() => {\n                    bucket.delete(slot);\n                  });\n                  bucket.set(slot, <Share>(<unknown>created));\n                  share = created;\n                }\n                const joined = share;\n                joined.refs += 1;\n                const release = (): void => {\n                  joined.refs -= 1;\n                  if (joined.refs === 0) {\n                    bucket.delete(slot);\n                    joined.controller.abort(controller.signal.reason);\n                  }\n                };\n                if (controller.signal.aborted) {\n                  release();\n                } else {\n                  controller.signal.addEventListener(\"abort\", release, {\n                    once: true,\n                  });\n                  const cleanup = (): void =>\n                    controller.signal.removeEventListener(\"abort\", release);\n                  joined.promise.then(cleanup, cleanup);\n                }\n                return withAbort(joined.promise, controller.signal);\n              };\n              const handle = {\n                then<U = T, V = never>(\n                  onFulfilled?:\n                    ((value: T) => U | PromiseLike<U>) | null | undefined,\n                  onRejected?:\n                    | ((reason: unknown) => V | PromiseLike<V>)\n                    | null\n                    | undefined,\n                ): Promise<U | V> {\n                  return fetch().then(onFulfilled, onRejected);\n                },\n                exceeds(duration: Temporal.DurationLike) {\n                  options.exceedsWindow = duration;\n                  return handle;\n                },\n                isolated() {\n                  options.isolated = true;\n                  return handle;\n                },\n                evict(where?: object): void {\n                  call.evict(where ?? call.params, dispatchFromResource);\n                },\n              };\n              return handle;\n            }\n            return <ResourceDispatcher>Object.defineProperty(\n              resourceCall,\n              \"nuke\",\n              {\n                value: (where?: object): void =>\n                  nuke(where, dispatchFromResource),\n                enumerable: false,\n              },\n            );\n          })(),\n          async final(action: AnyAction) {\n            if (controller.signal.aborted) return null;\n            const key = getActionSymbol(action);\n            const emitter = isMulticastAction(action)\n              ? (getScope(scope)?.emitter ?? null)\n              : broadcast;\n            if (!emitter) return null;\n            const cached = emitter.getCached(key);\n            if (G.isUndefined(cached)) return null;\n            const inspector = state.current.inspect;\n            if (inspector.pending()) {\n              await new Promise<void>((resolve, reject) => {\n                if (controller.signal.aborted)\n                  return void reject(controller.signal.reason);\n                const onAbort = () => reject(controller.signal.reason);\n                controller.signal.addEventListener(\"abort\", onAbort, {\n                  once: true,\n                });\n                void inspector.settled().then(() => {\n                  controller.signal.removeEventListener(\"abort\", onAbort);\n                  resolve();\n                });\n              });\n            }\n            return emitter.getCached(key) ?? null;\n          },\n          peek(action: AnyAction) {\n            if (controller.signal.aborted) return null;\n            const key = getActionSymbol(action);\n            const emitter = isMulticastAction(action)\n              ? (getScope(scope)?.emitter ?? null)\n              : broadcast;\n            if (!emitter) return null;\n            return emitter.getCached(key) ?? null;\n          },\n        },\n      });\n    },\n    [model],\n  );\n\n  React.useLayoutEffect(() => {\n    unmountGeneration.current++;\n\n    function createHandler(\n      action: ActionId,\n      actionHandler: Handler<M, A, D>,\n      getChannel: () => Filter | undefined,\n    ) {\n      return function handler(\n        payload: HandlerPayload,\n        dispatchChannel?: Filter,\n      ) {\n        const registeredChannel = getChannel();\n\n        if (\n          G.isNotNullable(dispatchChannel) &&\n          G.isNotNullable(registeredChannel)\n        ) {\n          if (!matchesChannel(dispatchChannel, registeredChannel)) return;\n        }\n\n        const result = <Result>{ processes: new Set<Process>() };\n        const completion = Promise.withResolvers<void>();\n        const context = getContext(action, payload, result);\n        const actionName = getName(action);\n        const startedAt = performance.now();\n        const modelBefore = <unknown>state.current.model;\n        const envBefore = <unknown>slot.current;\n        let errored = false;\n\n        function mutations() {\n          const modelAfter = <unknown>state.current.model;\n          const envAfter = <unknown>slot.current;\n          return {\n            model:\n              modelBefore === modelAfter\n                ? null\n                : { before: modelBefore, after: modelAfter },\n            env:\n              envBefore === envAfter\n                ? null\n                : { before: envBefore, after: envAfter },\n          };\n        }\n\n        tap({\n          stage: \"start\",\n          action: { name: actionName, payload },\n          details: { task: context.task },\n        });\n\n        function retry(): Promise<void> {\n          if (isMulticastAction(action)) {\n            const scoped = getScope(scope);\n            if (!scoped) return Promise.resolve();\n            return emitAsync(scoped.emitter, action, payload, dispatchChannel);\n          }\n          const emitter = isBroadcastAction(action) ? broadcast : unicast;\n          return emitAsync(emitter, action, payload, dispatchChannel);\n        }\n\n        function onError(caught: unknown) {\n          errored = true;\n          const errorAction = findLifecycleAction(\n            registry.current.handlers,\n            \"Error\",\n          );\n          const handled = G.isNotNullable(errorAction);\n          const reason = getReason(caught);\n          const error = getError(caught);\n          const details = {\n            reason,\n            error,\n            action: actionName,\n            handled,\n            tasks,\n            retry,\n          };\n          broadcast.fire(FaultSymbol, details);\n          if (handled && errorAction) unicast.emit(errorAction, details);\n          tap({\n            stage: \"end\",\n            result: \"error\",\n            action: { name: actionName, payload },\n            details: {\n              task: context.task,\n              elapsed: performance.now() - startedAt,\n              mutations: mutations(),\n              error,\n              reason,\n            },\n          });\n        }\n\n        function onSettled() {\n          for (const task of tasks) {\n            if (task === context.task) {\n              tasks.delete(task);\n              localTasks.current.delete(task);\n              break;\n            }\n          }\n          result.processes.forEach((process) => state.current.prune(process));\n          if (result.processes.size > 0) rerender();\n          if (!errored) {\n            tap({\n              stage: \"end\",\n              result: \"success\",\n              action: { name: actionName, payload },\n              details: {\n                task: context.task,\n                elapsed: performance.now() - startedAt,\n                mutations: mutations(),\n              },\n            });\n          }\n          completion.resolve();\n        }\n\n        let returnValue: ReturnType<Handler<M, A, D>>;\n        try {\n          returnValue = actionHandler(context, payload);\n        } catch (caught) {\n          onError(caught);\n          onSettled();\n          return completion.promise;\n        }\n\n        if (isGenerator(returnValue)) {\n          (async () => {\n            for await (const _ of returnValue) void 0;\n          })()\n            .catch(onError)\n            .finally(onSettled);\n          return completion.promise;\n        }\n\n        Promise.resolve(returnValue).catch(onError).finally(onSettled);\n        return completion.promise;\n      };\n    }\n\n    const cleanups = new Set<() => void>();\n\n    registry.current.handlers.forEach((entries, action) => {\n      for (const { getChannel, handler: actionHandler } of entries) {\n        const handler = createHandler(action, actionHandler, getChannel);\n\n        if (isMulticastAction(action)) {\n          if (scope) {\n            const emitter = scope.emitter;\n            emitter.on(action, handler);\n            cleanups.add(() => emitter.off(action, handler));\n          }\n          unicast.on(action, handler);\n          dispatchers.multicast.add(action);\n          cleanups.add(() => unicast.off(action, handler));\n        } else if (isBroadcastAction(action)) {\n          broadcast.on(action, handler);\n          unicast.on(action, handler);\n          dispatchers.broadcast.add(action);\n          cleanups.add(() => {\n            broadcast.off(action, handler);\n            unicast.off(action, handler);\n          });\n        } else {\n          unicast.on(action, handler);\n          cleanups.add(() => unicast.off(action, handler));\n        }\n      }\n    });\n\n    return () => {\n      const generation = ++unmountGeneration.current;\n      const pendingCleanups = new Set(cleanups);\n\n      queueMicrotask(() => {\n        if (unmountGeneration.current !== generation) {\n          for (const cleanup of pendingCleanups) cleanup();\n          return;\n        }\n\n        for (const task of localTasks.current) {\n          task.controller.abort(new Aborted(\"Component unmounted\"));\n          tasks.delete(task);\n        }\n        localTasks.current.clear();\n\n        phase.current = Phase.Unmounting;\n        const unmountAction = findLifecycleAction(\n          registry.current.handlers,\n          \"Unmount\",\n        );\n        if (unmountAction) unicast.emit(unmountAction);\n        phase.current = Phase.Unmounted;\n\n        for (const cleanup of pendingCleanups) cleanup();\n      });\n    };\n  }, [unicast]);\n\n  useLifecycles({\n    unicast,\n    broadcast,\n    tasks,\n    dispatchers,\n    scope,\n    phase,\n    data: getData(),\n    handlers: registry.current.handlers,\n  });\n\n  const actionsApi = React.useMemo(\n    () => ({\n      dispatch(\n        action: ActionOrChanneled,\n        second?: HandlerPayload | Audience,\n        third?: HandlerPayload,\n      ): Promise<void> {\n        const base = getActionSymbol(action);\n        const channel = isChanneledAction(action) ? action.channel : undefined;\n        const omnicast = isOmnicastAction(action);\n        const payload = omnicast ? third : <HandlerPayload>second;\n        const audience = omnicast ? <Audience | undefined>second : undefined;\n\n        if (isMulticastAction(action)) {\n          const scoped = getScope(scope);\n          if (scoped) return emitAsync(scoped.emitter, base, payload, channel);\n          return Promise.resolve();\n        }\n\n        if (omnicast && G.isNotNullable(sse)) {\n          return Promise.all([\n            emitAsync(broadcast, base, payload, channel),\n            sse.publish({\n              name: getName(action),\n              payload,\n              channel: <Filter | undefined>channel,\n              tags: audience?.tags ?? undefined,\n            }),\n          ]).then(() => undefined);\n        }\n\n        const emitter = isBroadcastAction(action) ? broadcast : unicast;\n        return emitAsync(emitter, base, payload, channel);\n      },\n      get inspect() {\n        return state.current.inspect;\n      },\n      stream(\n        action: AnyAction,\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        renderer: ConsumerRenderer<any>,\n      ): React.ReactNode {\n        return React.createElement(Partition, {\n          action: <symbol>getActionSymbol(action),\n          renderer,\n        });\n      },\n    }),\n    [model, unicast],\n  );\n\n  const result = React.useMemo(\n    () => <UseActions<M, A, D>>(<unknown>[model, actionsApi, data]),\n    [model, actionsApi, data],\n  );\n\n  // The public `useAction` signature constrains the action argument to\n  // `Subscribable<AC>` (leaf actions on `AC` plus `Lifecycle.Fault`) split\n  // into no-payload / with-payload overloads. The runtime is AC-agnostic,\n  // so the impl is typed against the loose `ActionOrChanneled` union and\n  // cast back to the strict public type.\n  //\n  // Each call site owns a stable symbol shared by its registration and its\n  // reactive emission, pairing a `Lifecycle.Reactive` binding's dispatch\n  // with exactly its own handler via the channel machinery.\n  const useActionImpl = (\n    action: ActionId | HandlerPayload | ChanneledAction,\n    handler: Handler<M, A, D>,\n  ): void => {\n    const site = React.useRef<symbol | null>(null);\n    site.current ??= Symbol(\"march-hare.reactive/site\");\n    useRegisterHandler<M, A, D>(registry, action, handler, site.current);\n    useReactiveEmit(action, unicast, site.current);\n  };\n  (<UseActions<M, A, D>>result).useAction = <UseActions<M, A, D>[\"useAction\"]>(\n    (<unknown>useActionImpl)\n  );\n  (<UseActions<M, A, D>>result).dispatch = <UseActions<M, A, D>[\"dispatch\"]>(\n    (<unknown>result[1].dispatch)\n  );\n\n  return <UseActions<M, A, D>>result;\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { WithHandle } from \"./types.ts\";\n\n/**\n * Walks the lodash-style dotted `path` on `target`, stopping one segment\n * short so callers can mutate or read the leaf via the returned `cursor`\n * and `key`. Used by every assignment helper below to avoid duplicating\n * the per-segment descent.\n *\n * @internal\n */\nexport function walk(\n  target: unknown,\n  path: string,\n): { cursor: Record<string, unknown>; key: string } {\n  const segments = path.split(\".\");\n  let cursor = <Record<string, unknown>>target;\n  for (let i = 0; i < segments.length - 1; i++) {\n    cursor = <Record<string, unknown>>cursor[segments[i]];\n  }\n  return { cursor, key: segments[segments.length - 1] };\n}\n\n/**\n * Assigns `value` to the leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function setPath(target: unknown, path: string, value: unknown): void {\n  const { cursor, key } = walk(target, path);\n  cursor[key] = value;\n}\n\n/**\n * Flips the boolean leaf of `target` reached by lodash-style `path`.\n * Mutates in place &mdash; expected to be called from inside an Immer\n * `produce` draft.\n *\n * @internal\n */\nexport function invertPath(target: unknown, path: string): void {\n  const { cursor, key } = walk(target, path);\n  cursor[key] = !cursor[key];\n}\n\n/**\n * Returns a handler that assigns the dispatched payload to the model\n * leaf at lodash-style `key`. Underlies both `context.with.update` and\n * the top-level `With.Update`.\n *\n * @internal\n */\nexport function makeUpdate(key: string) {\n  return (\n    context: HandlerContext<Model, Actions, Props, Env>,\n    payload: unknown,\n  ) => {\n    context.actions.produce((draft) => {\n      setPath(draft.model, key, payload);\n    });\n  };\n}\n\n/**\n * Returns a handler that flips the boolean model leaf at lodash-style\n * `key`. Underlies both `context.with.invert` and `With.Invert`.\n *\n * @internal\n */\nexport function makeInvert(key: string) {\n  return (context: HandlerContext<Model, Actions, Props, Env>) => {\n    context.actions.produce((draft) => {\n      invertPath(draft.model, key);\n    });\n  };\n}\n\n/**\n * Returns a handler that assigns the constant `value` to the model\n * leaf at lodash-style `key`, ignoring any dispatched payload.\n * Underlies both `context.with.always` and `With.Always`.\n *\n * @internal\n */\nexport function makeAlways(key: string, value: unknown) {\n  return (context: HandlerContext<Model, Actions, Props, Env>) => {\n    context.actions.produce((draft) => {\n      setPath(draft.model, key, value);\n    });\n  };\n}\n\n/**\n * Builds the {@link WithHandle} object returned via `context.with`. The\n * runtime is identical for any model &mdash; only the call-site types differ.\n *\n * @internal\n */\nexport function bindWith<M extends Model | void>(): WithHandle<M> {\n  return <WithHandle<M>>(<unknown>{\n    update<K extends string>(key: K) {\n      return makeUpdate(key);\n    },\n    invert<K extends string>(key: K) {\n      return makeInvert(key);\n    },\n    always<K extends string>(key: K, value: unknown) {\n      return makeAlways(key, value);\n    },\n  });\n}\n","import * as React from \"react\";\nimport { useActions } from \"../actions/index.ts\";\nimport { bindWith } from \"../with/utils.ts\";\nimport type {\n  Actions,\n  Context as ContextHandle,\n  Model,\n  Props,\n  UseActions,\n} from \"../types/index.ts\";\nimport type { DispatchTarget } from \"./types.ts\";\n\n/**\n * Returns a stable, typed controller handle up-front &mdash; before a\n * model is declared via `context.useActions(...)`. Use this when an\n * external imperative library (form, animation, third-party SDK) needs a\n * dispatch callback at construction time, while the value that library\n * returns must flow back into the controller's data callback.\n *\n * The handle exposes `dispatch(action, payload?)`, a `useActions(...)`\n * method that materialises the component-local model and reactive data\n * &mdash; the M and D pair of `useContext<M, AC, D>` &mdash; and\n * returns the `[model, actions, data]` tuple with `useAction`, `dispatch`,\n * `inspect`, and `stream` attached, plus `with` &mdash; a bag of handler\n * factories (`update`/`invert`/`always`) typed against the declared model\n * and accepting lodash-style dotted paths and array indices. The first\n * invocation of `context.actions.dispatch(...)` must come from an event\n * handler &mdash; not synchronously during render &mdash; because the\n * underlying dispatch target is wired up when `context.useActions(...)`\n * runs in the same render pass.\n *\n * @template M The model type representing the component's state.\n * @template AC The actions class containing action definitions.\n * @template D The data type for reactive external values.\n *\n * @example\n * ```ts\n * const context = useContext<Model, typeof Actions, Data>();\n *\n * const form = useForm({\n *   onSubmit: () => void context.actions.dispatch(Actions.Submit),\n * });\n *\n * const actions = context.useActions(\n *   { user: resource.user.get() },\n *   () => ({ form }),\n * );\n * ```\n *\n * @internal\n */\nexport function useContext<\n  M extends Model | void = void,\n  AC extends Actions | void = void,\n  D extends Props = Props,\n>(): ContextHandle<M, AC, D> {\n  const ref = React.useRef<DispatchTarget | null>(null);\n\n  return React.useMemo(() => {\n    function dispatch(action: unknown, payload?: unknown): Promise<void> {\n      const target = ref.current;\n      if (!target) {\n        throw new Error(\n          \"march-hare: useContext handle dispatched before its paired \" +\n            \"context.useActions(...) ran. Call context.actions.dispatch from \" +\n            \"event handlers, not synchronously during render.\",\n        );\n      }\n      return target(action, payload);\n    }\n\n    function useActionsMethod(...args: unknown[]): unknown {\n      const invoke = <(...passed: unknown[]) => UseActions<M, AC, D>>(\n        (<unknown>useActions)\n      );\n      const result = invoke(...args);\n      ref.current = <DispatchTarget>(<unknown>result.dispatch);\n      return result;\n    }\n\n    return <ContextHandle<M, AC, D>>(<unknown>{\n      actions: { dispatch },\n      useActions: useActionsMethod,\n      with: bindWith<M>(),\n    });\n  }, []);\n}\n","/**\n * Wraps `promise` so that aborting `signal` rejects the returned\n * promise with `signal.reason`, even when `promise` itself never\n * settles. The original promise is left alone &mdash; the underlying\n * work continues (other awaiters keep their grip) and only this\n * caller's view of it is severed.\n *\n * Used by the default coalesce path: a shared in-flight fetch runs on\n * a detached `AbortController` so one caller's abort does not cancel\n * work the other callers are still waiting on, while each caller's own\n * `context.task.controller` still aborts its personal await via this\n * wrapper. The `{ once: true }` listener and the cleanup on settle keep\n * the wrapper free of leaks across long-lived signals.\n *\n * @internal\n */\nexport function withAbort<T>(\n  promise: Promise<T>,\n  signal: AbortSignal,\n): Promise<T> {\n  return new Promise<T>((resolve, reject) => {\n    if (signal.aborted) {\n      reject(signal.reason);\n      return;\n    }\n    const onAbort = (): void => reject(signal.reason);\n    signal.addEventListener(\"abort\", onAbort, { once: true });\n    promise.then(\n      (value) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        resolve(value);\n      },\n      (error: unknown) => {\n        signal.removeEventListener(\"abort\", onAbort);\n        reject(error);\n      },\n    );\n  });\n}\n","import * as React from \"react\";\nimport { BroadcastEmitter } from \"../boundary/components/broadcast/utils.ts\";\nimport { Context as ScopeReactContext } from \"../boundary/components/scope/utils.ts\";\nimport type { ScopeEntry } from \"../boundary/components/scope/types.ts\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { LocalResourceHandle, ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { AppContextHandle, AppFetcher } from \"../app/types.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport { G } from \"@mobily/ts-belt\";\nimport type { ScopeHandle } from \"./types.ts\";\n\n/**\n * Internal constructor for a {@link ScopeHandle}. Called from inside\n * `App<E>()` so the enclosing Env shape `E` is captured at the type\n * level. The optional `cache` is the same value `App({ cache })` was\n * constructed with &mdash; resources declared via `scope.Resource`\n * share that cache. `getEnv` resolves the live Env from the enclosing\n * `app.Boundary` so cache-key scoping works for sync `.get()` reads.\n *\n * @internal\n */\nexport function createScope<E extends object, MulticastActions>(\n  cache?: Cache,\n  getEnv?: () => Env | undefined,\n): ScopeHandle<E, MulticastActions> {\n  function Boundary({\n    children,\n  }: {\n    children: React.ReactNode;\n  }): React.ReactElement {\n    const entry = React.useMemo<ScopeEntry>(\n      () => ({\n        id: Symbol(\"march-hare.scope/instance\"),\n        emitter: new BroadcastEmitter(),\n      }),\n      [],\n    );\n    return (\n      <ScopeReactContext.Provider value={entry}>\n        {children}\n      </ScopeReactContext.Provider>\n    );\n  }\n\n  function useTypedContext<\n    LocalModel extends Model | void = void,\n    AC extends Actions | void = void,\n    D extends Props = Props,\n  >(): AppContextHandle<\n    LocalModel,\n    MulticastActions extends Actions\n      ? AC extends Actions\n        ? AC & MulticastActions\n        : MulticastActions\n      : AC,\n    D,\n    E\n  > {\n    return baseUseContext() as unknown as AppContextHandle<\n      LocalModel,\n      MulticastActions extends Actions\n        ? AC extends Actions\n          ? AC & MulticastActions\n          : MulticastActions\n        : AC,\n      D,\n      E\n    >;\n  }\n\n  function useTypedEnv(): Readonly<E> {\n    return baseUseEnv() as unknown as Readonly<E>;\n  }\n\n  function Resource<\n    T,\n    P extends object = Record<never, never>,\n  >(): LocalResourceHandle<T, P>;\n  function Resource<T, P extends object = Record<never, never>>(\n    fetcher: AppFetcher<E, T, P>,\n  ): ResourceHandle<T, P>;\n  function Resource<T, P extends object = Record<never, never>>(\n    fetcher?: AppFetcher<E, T, P>,\n  ): ResourceHandle<T, P> | LocalResourceHandle<T, P> {\n    if (G.isUndefined(fetcher)) {\n      return BaseResource<E, T, P>(undefined, cache, getEnv);\n    }\n    return BaseResource<E, T, P>(fetcher, cache, getEnv);\n  }\n\n  return {\n    Boundary,\n    useContext: useTypedContext,\n    useEnv: useTypedEnv,\n    Resource,\n  };\n}\n","import * as React from \"react\";\nimport { Boundary as BaseBoundary } from \"../boundary/index.tsx\";\nimport { useContext as baseUseContext } from \"../context/index.ts\";\nimport { useEnv as baseUseEnv } from \"../boundary/components/env/utils.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport { Resource as BaseResource } from \"../resource/index.ts\";\nimport type { LocalResourceHandle, ResourceHandle } from \"../resource/types.ts\";\nimport type { Cache } from \"../cache/index.ts\";\nimport type { SseConfig } from \"../boundary/components/sse/types.ts\";\nimport type { Actions, Model, Props } from \"../types/index.ts\";\nimport { createScope } from \"../scope/utils.tsx\";\nimport type { AppHandle, AppContextHandle, AppFetcher } from \"./types.ts\";\nimport type { Tap } from \"../boundary/components/tap/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport type {\n  AppArgs,\n  AppContextHandle,\n  AppFetcher,\n  AppResource,\n} from \"./types.ts\";\n\nexport type { AppHandle } from \"./types.ts\";\n\n/**\n * Creates an `App` &mdash; the entrypoint for a typed Env shape `E`,\n * inferred from `config.env`. `App<E>` exposes `Boundary`, hooks, and\n * a `Resource` factory all wired against the same shape.\n *\n * Each `<app.Boundary>` instance owns its own Env, so different `App`s\n * can coexist in the same tree with completely independent shapes.\n *\n * Pass `tap` to subscribe to every action handler's dispatch / settle /\n * error inside the boundary &mdash; useful for analytics, audit logging,\n * Sentry breadcrumbs. See `recipes/tap.md`. Pass `cache` to persist\n * every `app.Resource(fetcher)` declaration through a single\n * {@link Cache} &mdash; each resource is namespaced inside the cache by\n * its declaration order, so reloads seed from storage automatically and\n * resources do not collide on shared params keys. Omit `cache` to keep\n * each resource's payloads in an isolated in-memory slot.\n *\n * `env`, `tap`, and `cache` are all fixed at `App()` time;\n * `<app.Boundary>` does not accept overrides. Mutate the live Env\n * through `context.actions.produce(({ env }) => …)`, and declare a\n * separate `App` when a test or storybook needs a different initial\n * value.\n *\n * @example\n * ```tsx\n * import { App, Cache, type Taps } from \"march-hare\";\n *\n * type Session = { accessToken: string };\n *\n * function tap(event: Taps) {\n *   if (event.type === \"error\") {\n *     Sentry.captureException(event.error, { tags: { action: event.action } });\n *   }\n * }\n *\n * export const app = App({\n *   env: {\n *     session: null as Session | null,\n *     operating: \"idle\" as \"idle\" | \"signing-out\",\n *   },\n *   tap,\n *   cache: Cache({\n *     get: (key) => localStorage.getItem(key),\n *     set: (key, value) => localStorage.setItem(key, value),\n *     remove: (key) => localStorage.removeItem(key),\n *     keys: () => Object.keys(localStorage),\n *   }),\n * });\n *\n * // Root render.\n * <app.Boundary>\n *   <Root />\n * </app.Boundary>;\n *\n * // In resources.ts &mdash; persisted via the App's cache.\n * export const user = app.Resource<User>((context) =>\n *   ky\n *     .get(\"/api/user\", {\n *       headers: context.env.session\n *         ? { Authorization: `Bearer ${context.env.session.accessToken}` }\n *         : {},\n *       signal: context.controller.signal,\n *     })\n *     .json<User>(),\n * );\n * ```\n */\nexport function App<E extends object = Env>(config?: {\n  env?: E;\n  tap?: Tap;\n  cache?: Cache;\n  sse?: SseConfig;\n}): AppHandle<E> {\n  const envHolder: { current: Env | undefined } = { current: undefined };\n\n  function Boundary({\n    children,\n  }: {\n    children: React.ReactNode;\n  }): React.ReactElement {\n    return (\n      <BaseBoundary\n        env={config?.env as Env}\n        tap={config?.tap}\n        sse={config?.sse}\n      >\n        <SyncEnvHolder holder={envHolder} />\n        {children}\n      </BaseBoundary>\n    );\n  }\n\n  function useTypedContext<\n    M extends Model | void = void,\n    AC extends Actions | void = void,\n    D extends Props = Props,\n  >(): AppContextHandle<M, AC, D, E> {\n    return baseUseContext() as unknown as AppContextHandle<M, AC, D, E>;\n  }\n\n  function useTypedEnv(): Readonly<E> {\n    return baseUseEnv() as unknown as Readonly<E>;\n  }\n\n  function Resource<\n    T,\n    P extends object = Record<never, never>,\n  >(): LocalResourceHandle<T, P>;\n  function Resource<T, P extends object = Record<never, never>>(\n    fetcher: AppFetcher<E, T, P>,\n  ): ResourceHandle<T, P>;\n  function Resource<T, P extends object = Record<never, never>>(\n    fetcher?: AppFetcher<E, T, P>,\n  ): ResourceHandle<T, P> | LocalResourceHandle<T, P> {\n    if (G.isUndefined(fetcher)) {\n      return BaseResource<E, T, P>(\n        undefined,\n        config?.cache,\n        () => envHolder.current,\n      );\n    }\n    return BaseResource<E, T, P>(\n      fetcher,\n      config?.cache,\n      () => envHolder.current,\n    );\n  }\n\n  return {\n    Boundary,\n    useContext: useTypedContext,\n    useEnv: useTypedEnv,\n    Resource,\n    Scope<MulticastActions>() {\n      return createScope<E, MulticastActions>(\n        config?.cache,\n        () => envHolder.current,\n      );\n    },\n  };\n}\n\n/**\n * Side-effect-only child of `app.Boundary` that captures the live Env\n * proxy from the enclosing `<Env>` provider and writes it into the\n * App's `envHolder` on every render. The proxy itself is stable per\n * boundary &mdash; subsequent renders re-assign the same reference, so\n * the holder behaves like a `ref.current` slot the App's `Resource`\n * factory can read from at any time (including from sync `.get()`\n * calls executed outside of action handlers).\n *\n * @internal\n */\nfunction SyncEnvHolder({\n  holder,\n}: {\n  holder: { current: Env | undefined };\n}): null {\n  const env = baseUseEnv();\n  holder.current = env;\n  return null;\n}\n\n/**\n * Standalone counterpart to `app.useContext`, exported as\n * `shared.useContext` &mdash; same call shape, but takes the **Env\n * shape `E` as a mandatory first generic** so the caller can be a\n * reusable component that isn't tied to a single `App` import.\n *\n * `E` is the Env type your component expects to see &mdash; usually\n * a union of every App's Env shape it might run under. Inside the\n * handler, `context.env` is typed as `E`; reach for `in` / `typeof`\n * narrowing for keys present on only a subset.\n *\n * Pass `app` directly if you only need to talk to one App &mdash;\n * `app.useContext<Model, typeof Actions>()` is shorter and infers the\n * Env from the value. Reach for the standalone form only when a\n * component must support more than one App.\n *\n * @template E The Env shape (or union) the component supports.\n * @template M The model type, or `void`.\n * @template AC The Actions class, or `void`.\n * @template D The reactive data type returned from the `useActions`\n *   data callback.\n *\n * @example\n * ```tsx\n * import { Action, shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null; locale: string };\n * type MobileEnv = { session: Session | null; platform: \"ios\" | \"android\" };\n * type Envs = WebEnv | MobileEnv;\n *\n * type Model = { name: string | null };\n * const model: Model = { name: null };\n *\n * class Actions {\n *   static Sign = Action<string>(\"Sign\");\n * }\n *\n * function useProfileActions() {\n *   const context = shared.useContext<Envs, Model, typeof Actions>();\n *   const actions = context.useActions(model);\n *\n *   actions.useAction(Actions.Sign, (context, name) =>\n *     context.actions.produce(({ model }) => void (model.name = name)),\n *   );\n *\n *   return actions;\n * }\n * ```\n */\nexport function useContext<\n  E extends object,\n  M extends Model | void = void,\n  A extends Actions | void = void,\n  D extends Props = Props,\n>(): AppContextHandle<M, A, D, E> {\n  return baseUseContext() as unknown as AppContextHandle<M, A, D, E>;\n}\n\n/**\n * Standalone counterpart to `app.useEnv`, exported as `shared.useEnv`\n * &mdash; reads the nearest `<app.Boundary>`'s Env, typed against the\n * Env shape `E` supplied at the call site. For reusable components\n * that need an Env read outside any action handler (e.g. to hand a\n * closure to an external library at module bridge time).\n *\n * @template E The Env shape (or union) the component supports.\n *\n * @example\n * ```tsx\n * import { shared } from \"march-hare\";\n *\n * type WebEnv = { session: Session | null };\n * type MobileEnv = { session: Session | null };\n *\n * function SessionBadge() {\n *   const env = shared.useEnv<WebEnv | MobileEnv>();\n *   return <span>{env.session ? env.session.user.name : \"Signed out\"}</span>;\n * }\n * ```\n */\nexport function useEnv<E extends object>(): Readonly<E> {\n  return baseUseEnv() as unknown as Readonly<E>;\n}\n","import type { Actions, HandlerContext, Model, Props } from \"../types/index.ts\";\nimport type { Env } from \"../boundary/components/env/types.ts\";\nimport type { BooleanPaths, Get, Paths } from \"./types.ts\";\nimport { makeAlways, makeInvert, makeUpdate } from \"./utils.ts\";\n\n/**\n * Handler factories that wire an action directly to a model field. Prefer\n * `context.with` from `useContext<Model>()` for first-class autocompletion\n * over dotted paths; this top-level form is kept for callers that don't have\n * a typed `context` in scope.\n *\n * - {@link With.Update} assigns the dispatched payload to a model path.\n * - {@link With.Invert} flips a boolean leaf at a model path.\n * - {@link With.Always} assigns a fixed value to a model path, ignoring any\n *   dispatched payload.\n *\n * Keys may be lodash-style dotted paths (`\"a.b.c\"`) and support array\n * indices (`\"items.0.name\"`). The model type is inferred at handler-bind\n * time; an invalid path or mismatched payload fails to compile when the\n * handler is registered with `useAction`.\n *\n * @example\n * ```ts\n * import { With } from \"march-hare\";\n *\n * type Model = {\n *   name: string;\n *   sidebar: boolean;\n *   nested: { open: boolean };\n *   items: { id: number }[];\n * };\n *\n * actions.useAction(Actions.SetName, With.Update(\"name\"));\n * actions.useAction(Actions.SetFirstId, With.Update(\"items.0.id\"));\n * actions.useAction(Actions.ToggleSidebar, With.Invert(\"sidebar\"));\n * actions.useAction(Actions.ToggleNested, With.Invert(\"nested.open\"));\n * actions.useAction(Actions.Open, With.Always(\"nested.open\", true));\n * ```\n */\nexport const With = {\n  /**\n   * Returns a handler that assigns the action payload to the model leaf at\n   * the given lodash-style path. The payload type must match `Get<M, K>`,\n   * and the path must exist on the model.\n   *\n   * @template K The dotted-path string indexing into the model.\n   * @param key The lodash-style path to the model leaf being assigned.\n   */\n  Update<K extends string>(\n    key: K,\n  ): <\n    M extends Model,\n    A extends Actions | void,\n    D extends Props,\n    P extends (K extends Paths<M> ? Get<M, K> : never),\n    E extends Env = Env,\n  >(\n    context: HandlerContext<M, A, D, E>,\n    payload: P,\n  ) => void {\n    return <(context: unknown, payload: unknown) => void>makeUpdate(key);\n  },\n  /**\n   * Returns a handler that inverts a boolean leaf at the given lodash-style\n   * path. The leaf must be a `boolean` on the model.\n   *\n   * @template K The dotted-path string indexing into a boolean leaf.\n   * @param key The lodash-style path to the boolean leaf being toggled.\n   */\n  Invert<K extends string>(\n    key: K,\n  ): <\n    M extends Model,\n    A extends Actions | void,\n    D extends Props,\n    E extends Env = Env,\n  >(\n    context: K extends BooleanPaths<M> ? HandlerContext<M, A, D, E> : never,\n  ) => void {\n    return <(context: unknown) => void>makeInvert(key);\n  },\n  /**\n   * Returns a handler that assigns a fixed `value` to the model leaf at the\n   * given lodash-style path. The dispatched payload (if any) is ignored.\n   *\n   * @template K The dotted-path string indexing into the model.\n   * @template V The constant value type; must be assignable to the leaf at `K`.\n   * @param key The lodash-style path to the model leaf being assigned.\n   * @param value The constant value pinned to the leaf.\n   */\n  Always<K extends string, V>(\n    key: K,\n    value: V,\n  ): <\n    M extends Model,\n    A extends Actions | void,\n    D extends Props,\n    E extends Env = Env,\n  >(\n    context: K extends Paths<M>\n      ? V extends Get<M, K>\n        ? HandlerContext<M, A, D, E>\n        : never\n      : never,\n  ) => void {\n    return <(context: unknown) => void>makeAlways(key, value);\n  },\n};\n","import { State, Operation } from \"immertation\";\n\n/**\n * Module-level Immertation state instance used to annotate initial model values\n * with operation metadata (e.g., {@link Operation}) before hydration.\n *\n * This is intentionally a singleton — it exists solely to provide the\n * {@link annotate} helper with access to `State.annotate`, without requiring\n * consumers to instantiate their own `State` object.\n */\nconst state = new State();\n\n/**\n * Wraps a value with an operation annotation for use in initial model definitions.\n * When passed as part of the initial model to `useActions`, the annotation is\n * registered during hydration so that `actions.inspect` reports the field as pending\n * from the very first render.\n *\n * @param value - The value to annotate.\n * @param operation - The operation type (defaults to {@link Operation.Update}).\n * @returns The annotated value (typed as T for assignment compatibility).\n *\n * @example\n * ```ts\n * import { annotate } from \"march-hare\";\n *\n * type Model = { user: User | null };\n *\n * const model: Model = {\n *   user: annotate(null),\n * };\n *\n * // actions.inspect.user.pending() === true from the first render\n * ```\n */\nexport function annotate<T>(\n  value: T,\n  operation: Operation = Operation.Update,\n): T {\n  return state.annotate(operation, value);\n}\n","import { Pk } from \"../types/index.ts\";\nimport { Aborted } from \"../error/index.ts\";\n\nexport { unset } from \"./utils.ts\";\nexport type { Stored, Unset } from \"./types.ts\";\n\n/**\n * Returns a promise that resolves after the specified number of\n * milliseconds, or rejects with an {@link Aborted} when the signal is aborted. Use to inject a cancellable\n * delay into an action handler.\n *\n * @param ms How long to wait before resolving.\n * @param signal Optional {@link AbortSignal} that cancels the sleep early.\n *               Pass `context.task.controller.signal` to tie the wait to\n *               the lifetime of the current action.\n * @returns A promise that resolves after `ms` milliseconds or rejects with\n *          an {@link Aborted} if `signal` aborts first.\n */\nexport function sleep(\n  ms: number,\n  signal: AbortSignal | undefined,\n): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(new Aborted());\n      return;\n    }\n\n    const timer = setTimeout(resolve, ms);\n\n    signal?.addEventListener(\n      \"abort\",\n      () => {\n        clearTimeout(timer);\n        reject(new Aborted());\n      },\n      { once: true },\n    );\n  });\n}\n\n/**\n * Repeatedly calls a function at a fixed interval until it returns `true`\n * or the signal is aborted. The function is invoked immediately on the\n * first iteration, then after each interval.\n *\n * @param ms Interval in milliseconds between invocations of `fn`.\n * @param signal Optional {@link AbortSignal} that cancels polling early.\n *               Aborts propagate as an {@link Aborted} rejection.\n * @param fn Predicate invoked each iteration. Return `true` to stop\n *           polling, `false` to schedule another invocation after `ms`.\n *           May be sync or async.\n * @returns A promise that resolves when `fn` returns `true`, or rejects\n *          with a `DOMException(\"aborted\", \"Aborted\")` if `signal`\n *          aborts first.\n */\nexport async function poll(\n  ms: number,\n  signal: AbortSignal | undefined,\n  fn: () => boolean | Promise<boolean>,\n): Promise<void> {\n  if (signal?.aborted) throw new Aborted();\n\n  while (true) {\n    const done = await fn();\n    if (done) return;\n    await sleep(ms, signal);\n  }\n}\n\n/**\n * Generates a unique primary key.\n *\n * @returns A new unique symbol representing the primary key.\n */\nexport function pk(): symbol;\n/**\n * Checks if the provided ID is a valid primary key. A valid primary key\n * is any value that is not a symbol.\n *\n * @template T The model type the key identifies.\n * @param id The primary key to validate.\n * @returns `true` if `id` is a non-symbol value, `false` otherwise.\n */\nexport function pk<T>(id: Pk<T>): boolean;\nexport function pk<T>(id?: Pk<T>): boolean | symbol {\n  if (id) return Boolean(id && typeof id !== \"symbol\");\n  return Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`);\n}\n\n/** Shorthand alias for {@link sleep}. */\nexport const ζ = sleep;\n\n/** Shorthand alias for {@link poll}. */\nexport const π = poll;\n\n/** Shorthand alias for {@link pk}. */\nexport const κ = pk;\n","/**\n * `shared` namespace &mdash; standalone counterparts to the `app.X`\n * factories returned by `App<E>()`. Each export takes the Env shape\n * `E` as a mandatory first generic so reusable components can run\n * under more than one App without binding to a single `app` import.\n *\n * Reach for `shared.X` only when a component must support more than\n * one App. Single-app code should keep using `app.X` &mdash; the Env\n * is captured from `app` automatically and the call site is one\n * generic shorter.\n *\n * | Bound to an App                  | Standalone (`shared.X`)                  |\n * | -------------------------------- | ---------------------------------------- |\n * | `app.useContext<M, A, D>()`      | `shared.useContext<E, M, A, D>()`        |\n * | `app.useEnv()`                   | `shared.useEnv<E>()`                     |\n * | `app.Resource<T, P>(...)`        | `shared.Resource<E, T, P>(...)`          |\n * | `app.Scope<A>()`                 | `shared.Scope<E, A>()`                   |\n *\n * `shared.Resource` declarations always read from and write to an\n * in-memory cache &mdash; persistence is an App-level concern wired up\n * via `App({ cache })`. Reach for `app.Resource` instead when a resource\n * needs to survive reloads.\n *\n * @see {@link ./app/index.tsx App}\n */\n\nimport { Resource as InternalResource } from \"../resource/index.ts\";\nimport type { AppFetcher } from \"../app/types.ts\";\nimport type { LocalResourceHandle, ResourceHandle } from \"../resource/types.ts\";\nimport { G } from \"@mobily/ts-belt\";\n\nexport { useContext, useEnv } from \"../app/index.tsx\";\nexport { Scope } from \"../scope/index.tsx\";\n\n/**\n * Standalone counterpart to `app.Resource`, exported as\n * `shared.Resource`. Takes the **Env shape `E` as a mandatory first\n * generic** so the fetcher's `context.env` is typed even when the\n * resource isn't bound to a single App.\n *\n * Call with **no fetcher** (`shared.Resource<E, T, P>()`) to declare a\n * local Resource whose slots are written exclusively through\n * `context.actions.resource(...).set(value)` rather than by a fetch.\n *\n * Always uses an isolated in-memory cache &mdash; persistent caching\n * is an App-level concern wired through `App({ cache })`, so reach for\n * `app.Resource` when a resource needs to survive reloads.\n */\nexport function Resource<\n  _E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(): LocalResourceHandle<T, P>;\nexport function Resource<\n  E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(fetcher: AppFetcher<E, T, P>): ResourceHandle<T, P>;\nexport function Resource<\n  E extends object,\n  T,\n  P extends object = Record<never, never>,\n>(\n  fetcher?: AppFetcher<E, T, P>,\n): ResourceHandle<T, P> | LocalResourceHandle<T, P> {\n  if (G.isUndefined(fetcher)) {\n    return InternalResource<E, T, P>(undefined);\n  }\n  return InternalResource<E, T, P>(fetcher);\n}\n","import type { ScopeHandle } from \"./types.ts\";\nimport { createScope } from \"./utils.tsx\";\n\nexport type { ScopeHandle } from \"./types.ts\";\nexport { createScope } from \"./utils.tsx\";\n\n/**\n * Standalone counterpart to `app.Scope<MulticastActions>()`, exported\n * as `shared.Scope` &mdash; opens a typed multicast scope without\n * going through an `App` handle. Takes the **Env shape `E` as a\n * mandatory first generic**, mirroring the other standalone exports\n * (`shared.useContext`, `shared.useEnv`, `shared.Resource`). The Env\n * carried by `scope.useContext()` is typed as `E`.\n *\n * Use this in reusable feature modules that need to open their own\n * multicast scope without binding to one App's `app.Scope` factory.\n * For single-app code, prefer `app.Scope<MulticastActions>()` &mdash;\n * the Env is captured from `app` automatically.\n *\n * @template E The Env shape (or union) the scope's `useContext` types\n *   `context.env` against.\n * @template A The multicast Actions class (or union of classes) the\n *   scope's dispatch surface is widened to include.\n *\n * @example\n * ```tsx\n * import { Action, Distribution, shared } from \"march-hare\";\n *\n * class MulticastActions {\n *   static Mood = Action<\"happy\" | \"sad\">(\n *     \"Mood\",\n *     Distribution.Multicast,\n *   );\n * }\n *\n * type MoodEnv = { tracker: string };\n *\n * export const scope = shared.Scope<MoodEnv, typeof MulticastActions>();\n * ```\n */\nexport function Scope<E extends object, A>(): ScopeHandle<E, A> {\n  return createScope<E, A>();\n}\n"],"names":["has","Object","prototype","hasOwnProperty","prefix","Events","EE","fn","context","once","this","addListener","emitter","event","TypeError","listener","evt","_events","push","_eventsCount","clearEvent","EventEmitter","create","__proto__","eventNames","events","name","names","call","slice","getOwnPropertySymbols","concat","listeners","handlers","i","l","length","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","args","len","arguments","removeListener","apply","j","on","removeAllListeners","off","prefixed","module","BroadcastEmitter","cache","Map","latest","setCache","undefined","super","value","channel","inner","get","entry","set","JSON","stringify","channelKey","getCached","getCachedAll","values","fire","Context","React","createContext","useBroadcast","useContext","Broadcaster","children","useMemo","Provider","Set","useTasks","Tasks","tasks","current","useEnv","ref","Proxy","_target","key","Reflect","ownKeys","getOwnPropertyDescriptor","descriptor","G","isUndefined","configurable","describe","action","broadcast","multicast","omnicast","lifecycle","changes","previous","next","keys","reduce","result","key2","Brand","static","Symbol","createLifecycleAction","symbol","Action","Payload","Channel","Name","defineProperty","enumerable","Lifecycle","FaultSymbol","EnvSymbol","Mount","Paint","Unmount","Error","Update","Reactive","Broadcast","Distribution","Unicast","Multicast","Omnicast","schema","Phase","Mounting","Mounted","Unmounting","Unmounted","Env","initial","useRef","WeakMap","SharingProvider","registry","noop","useTap","Reason","Aborted","Errored","Rejected","constructor","message","options","isSymbol","getActionSymbol","isString","isObject","isFunction","isBroadcastAction","startsWith","description","actionSymbol","isOmnicastAction","getName","lastIndexOf","isChanneledAction","isReactiveBinding","getLifecycleType","isMulticastAction","distribution","channeled","unset","config","useRerender","rerender","useReducer","x","empty","data","at","present","emitAsync","Promise","resolve","all","map","then","findLifecycleAction","type","getReason","error","getError","String","lookup","actions","depth","candidate","nested","isNotNullable","parse","SseContext","Sse","tap","client","desired","tags","align","handle","endpoint","async","mutate","method","tag","isNull","response","fetch","url","encodeURIComponent","ok","status","publish","envelope","body","headers","add","fresh","filter","forEach","remove","held","delete","every","clear","useEffect","source","EventSource","size","join","address","addEventListener","connected","reconcile","catch","required","isNullable","deliver","payload","schemaOf","cause","validate","caught","identity","task","controller","AbortController","startedAt","performance","now","stage","details","elapsed","mutations","model","env","reason","handled","retry","close","Tappable","useLayoutEffect","jsx","Boundary","sse","consumer","ConsumerContext","Cache","backing","isCacheAdapter","memory","memoryAdapter","scopeFn","ownedKeys","from","acc","cacheKey","raw","parsed","Temporal","Instant","toString","scope","defaults","namespaces","evictors","nextResourceId","fetcher","existing","namespace","foundations","getEnv","label","suffix","composeKey","params","read","stored","evict","where","dispatch","fullPrefix","entries","evicted","field","write","Now","instant","actionFn","build","ƒ","run","resolved","buildLocal","Resource","resolveEnv","defaultCache","s","t","e","r","crypto","getRandomValues","Uint8Array","o","Add","Remove","Move","Replace","Sort","Create","Fetch","Clone","Archive","Restore","Merge","Reorder","Sync","Publish","Link","Unlink","Lock","Unlock","Import","Export","Transfer","a","Produce","Hydrate","c","Property","Process","Value","Operation","u","property","process","operation","assign","setAutoFreeze","p","y","split","n","f","m","isArray","h","fromEntries","id","d","getPrototypeOf","isNumber","isBoolean","g","path","v","O","pk","annotate","inspect","isNotEmpty","isEmpty","some","head","hydrate","produce","immer","produceWithPatches","applyPatches","prune","observe","Partition","renderer","state","State","cached","handlePayload","idleTag","walk","target","segments","cursor","setPath","makeUpdate","draft","makeInvert","invertPath","makeAlways","useActions","initialModel","getData","slot","sharing","initialised","hydration","setModel","useState","props","withGetters","b","proxy","useData","unicast","dispatchers","useDispatchers","phase","localTasks","unmountGeneration","getContext","useCallback","supersede","sibling","abort","signal","aborted","slotBefore","produceImmer","envDraft","processes","second","third","base","audience","resource","dispatchFromResource","exceedsWindow","isolated","onFulfilled","onRejected","since","window","Duration","compare","mutable","bucket","share","detached","created","refs","promise","finally","joined","release","cleanup","removeEventListener","reject","onAbort","exceeds","duration","pattern","nuke","final","inspector","pending","settled","peek","createHandler","actionHandler","getChannel","dispatchChannel","registeredChannel","matchesChannel","completion","withResolvers","actionName","modelBefore","envBefore","returnValue","errored","modelAfter","envAfter","before","after","onError","errorAction","onSettled","isGenerator","_","cleanups","handler","generation","pendingCleanups","queueMicrotask","unmountAction","painted","firstMount","mountAction","updateAction","paintAction","differences","A","useLifecycles","actionsApi","stream","createElement","useAction","useActionImpl","site","handlerRef","actionRef","stableHandler","Site","useRegisterHandler","binding","dispatched","is","useReactiveEmit","invoke","with","update","invert","always","createScope","ScopeReactContext","baseUseContext","baseUseEnv","BaseResource","SyncEnvHolder","holder","With","Invert","Always","sleep","ms","timer","setTimeout","clearTimeout","poll","Boolean","Date","randomUUID","InternalResource","envHolder","jsxs","BaseBoundary","Scope","Public","Private"],"mappings":"gfAEA,IAAIA,EAAMC,OAAOC,UAAUC,eACvBC,EAAS,IASb,SAASC,IAAS,CA4BlB,SAASC,EAAGC,EAAIC,EAASC,GACvBC,KAAKH,GAAKA,EACVG,KAAKF,QAAUA,EACfE,KAAKD,KAAOA,IAAQ,CACtB,CAaA,SAASE,EAAYC,EAASC,EAAON,EAAIC,EAASC,GAChD,GAAkB,mBAAPF,EACT,MAAM,IAAIO,UAAU,mCAGtB,IAAIC,EAAW,IAAIT,EAAGC,EAAIC,GAAWI,EAASH,GAC1CO,EAAMZ,EAASA,EAASS,EAAQA,EAMpC,OAJKD,EAAQK,QAAQD,GACXJ,EAAQK,QAAQD,GAAKT,GAC1BK,EAAQK,QAAQD,GAAO,CAACJ,EAAQK,QAAQD,GAAMD,GADhBH,EAAQK,QAAQD,GAAKE,KAAKH,MAD1BE,QAAQD,GAAOD,EAAUH,EAAQO,gBAI7DP,CACT,CASA,SAASQ,EAAWR,EAASI,GACI,MAAzBJ,EAAQO,aAAoBP,EAAQK,QAAU,IAAIZ,SAC5CO,EAAQK,QAAQD,EAC9B,CASA,SAASK,IACPX,KAAKO,QA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