march-hare 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +491 -211
  2. package/dist/actions/index.d.ts +46 -0
  3. package/dist/{hooks → actions}/utils.d.ts +0 -39
  4. package/dist/app/index.d.ts +132 -0
  5. package/dist/app/types.d.ts +82 -0
  6. package/dist/boundary/components/broadcast/utils.d.ts +1 -1
  7. package/dist/boundary/components/env/index.d.ts +26 -0
  8. package/dist/boundary/components/env/types.d.ts +11 -0
  9. package/dist/boundary/components/env/utils.d.ts +36 -0
  10. package/dist/boundary/components/scope/index.d.ts +1 -39
  11. package/dist/boundary/components/scope/types.d.ts +17 -13
  12. package/dist/boundary/components/scope/utils.d.ts +12 -8
  13. package/dist/boundary/components/sharing/index.d.ts +43 -0
  14. package/dist/boundary/components/tap/index.d.ts +36 -0
  15. package/dist/boundary/components/tap/types.d.ts +150 -0
  16. package/dist/boundary/components/tap/utils.d.ts +14 -0
  17. package/dist/boundary/index.d.ts +10 -10
  18. package/dist/boundary/types.d.ts +46 -14
  19. package/dist/cache/index.d.ts +4 -4
  20. package/dist/coalesce/index.d.ts +57 -0
  21. package/dist/context/index.d.ts +41 -0
  22. package/dist/context/types.d.ts +14 -0
  23. package/dist/error/index.d.ts +1 -1
  24. package/dist/error/types.d.ts +8 -19
  25. package/dist/index.d.ts +9 -13
  26. package/dist/march-hare.js +8 -5
  27. package/dist/march-hare.umd.cjs +1 -1
  28. package/dist/resource/index.d.ts +55 -78
  29. package/dist/resource/types.d.ts +87 -11
  30. package/dist/resource/utils.d.ts +1 -1
  31. package/dist/scope/index.d.ts +63 -0
  32. package/dist/scope/types.d.ts +55 -0
  33. package/dist/types/index.d.ts +108 -58
  34. package/dist/utils/index.d.ts +6 -5
  35. package/dist/with/index.d.ts +111 -0
  36. package/package.json +1 -1
  37. package/dist/boundary/components/store/index.d.ts +0 -41
  38. package/dist/boundary/components/store/types.d.ts +0 -11
  39. package/dist/boundary/components/store/utils.d.ts +0 -64
  40. package/dist/hooks/index.d.ts +0 -83
  41. /package/dist/{hooks → actions}/types.d.ts +0 -0
@@ -0,0 +1,150 @@
1
+ import { Reason } from '../../../error/types';
2
+ import { Task } from '../tasks/types';
3
+ import type * as React from "react";
4
+ /**
5
+ * Identity of a handler invocation: the action being handled and the
6
+ * payload supplied at dispatch. Appears on every {@link Tapped} event
7
+ * as `event.action`, alongside the `stage` / `result` discriminators.
8
+ */
9
+ export type Invocation = {
10
+ /** Human-readable name of the action being handled. */
11
+ readonly name: string;
12
+ /** Payload supplied at dispatch (typed `unknown`; cast at the call site). */
13
+ readonly payload: unknown;
14
+ };
15
+ /**
16
+ * Failure fields layered onto the `details` sub-object of the
17
+ * `end:error` variant of {@link Tapped}. Groups the thrown error with
18
+ * the {@link Reason} the dispatch pipeline classified it as —
19
+ * consumers branching on `Aborted` vs. `Errored` read both off the
20
+ * same place. The error variant's `details` is `Failure` merged with
21
+ * the common end-of-handler shape (`{ mutations }`), so a helper that
22
+ * takes a `Failure` accepts the error-variant `details` directly.
23
+ */
24
+ export type Failure = {
25
+ /** The Error instance thrown by the handler (or the abort cause). */
26
+ readonly error: Error;
27
+ /** Library classification of the failure: `Aborted` or `Errored`. */
28
+ readonly reason: Reason;
29
+ };
30
+ /**
31
+ * Reference snapshot for a single mutation surface (model or env)
32
+ * captured at handler start and end. The library compares references
33
+ * — Immer / Immertation produce a new reference iff a `produce`
34
+ * call actually committed a change, so reference inequality is a
35
+ * precise "did something change" signal with no deep-diff cost.
36
+ *
37
+ * Consumers diff `before` against `after` themselves (using the
38
+ * library's `changes` helper, a third-party diff lib, or a custom
39
+ * walk) when they need the per-field delta.
40
+ */
41
+ export type Snapshot<T> = {
42
+ readonly before: T;
43
+ readonly after: T;
44
+ };
45
+ /**
46
+ * Per-handler summary of which mutation surfaces changed during the
47
+ * invocation. `null` on a surface means "reference unchanged" &mdash;
48
+ * the handler did not commit any `produce` call that touched that
49
+ * surface. A non-null value carries the before/after references.
50
+ *
51
+ * Values are typed `unknown` at this seam because the library doesn't
52
+ * know the model or env shape; cast inside the tap callback at the
53
+ * boundary where you know your `App`'s typed shape.
54
+ *
55
+ * Note on nested dispatches: if a handler awaits a sibling dispatch
56
+ * that itself mutates the same surface, the outer handler's
57
+ * `mutations` reflects the net change observed across its lifetime
58
+ * &mdash; including downstream effects. This is usually what you want
59
+ * for tracing; if you need to attribute changes to the originating
60
+ * handler precisely, branch on the `action` field as well.
61
+ */
62
+ export type Mutations = {
63
+ readonly model: Snapshot<unknown> | null;
64
+ readonly env: Snapshot<unknown> | null;
65
+ };
66
+ /**
67
+ * Lifecycle event published by the tap. One pair of events is emitted
68
+ * per handler invocation, not per dispatch &mdash; a broadcast that
69
+ * reaches five subscribers produces five `start` events plus one `end`
70
+ * event per subscriber.
71
+ *
72
+ * The shape is a two-level discrimination:
73
+ *
74
+ * - **`stage`** &mdash; `"start"` (handler just began) or `"end"`
75
+ * (handler completed).
76
+ * - **`result`** &mdash; on `end` only, `"success"` or `"error"`
77
+ * describing the outcome. Mutually exclusive: the same handler
78
+ * invocation never produces both a success and an error.
79
+ *
80
+ * Per handler, exactly one of these two pairs is emitted:
81
+ * - **Succeeded:** `stage: "start"` &rarr; `stage: "end", result: "success"`.
82
+ * - **Failed:** `stage: "start"` &rarr; `stage: "end", result: "error"`.
83
+ *
84
+ * The {@link Invocation} identity (`action`, `payload`) and the
85
+ * discriminators (`stage`, `result`) sit at the top level so consumers
86
+ * can route and label events without diving into `details`. Everything
87
+ * else &mdash; the task handle, timing, mutation summary, failure
88
+ * info &mdash; lives on the `details` sub-object.
89
+ *
90
+ * `start` events carry just the {@link Task} in `details`;
91
+ * `end:success` adds `elapsed` and {@link Mutations}; `end:error`
92
+ * adds those plus the {@link Failure} fields.
93
+ *
94
+ * `elapsed` is measured in milliseconds against `performance.now()`,
95
+ * captured the moment the `end` event fires.
96
+ */
97
+ export type Tapped = {
98
+ /** Action being handled: `{ name, payload }`. */
99
+ readonly action: Invocation;
100
+ } & ({
101
+ readonly stage: "start";
102
+ readonly details: {
103
+ readonly task: Task;
104
+ };
105
+ } | {
106
+ readonly stage: "end";
107
+ readonly result: "success";
108
+ readonly details: {
109
+ readonly task: Task;
110
+ readonly elapsed: number;
111
+ readonly mutations: Mutations;
112
+ };
113
+ } | {
114
+ readonly stage: "end";
115
+ readonly result: "error";
116
+ readonly details: Failure & {
117
+ readonly task: Task;
118
+ readonly elapsed: number;
119
+ readonly mutations: Mutations;
120
+ };
121
+ });
122
+ /**
123
+ * Observer callback invoked for every action handler lifecycle event
124
+ * inside the surrounding `<Boundary>`. Synchronous &mdash; do not
125
+ * perform expensive or async work here; defer to a queue, ring buffer,
126
+ * or external transport if the receiver is slow.
127
+ *
128
+ * Tap is intended for cross-cutting observability concerns: analytics,
129
+ * audit logging, browser-extension devtools, Sentry breadcrumbs,
130
+ * replay traces for bug reports. Use {@link Lifecycle.Fault} for
131
+ * in-band error recovery; the two are independent.
132
+ */
133
+ export type Tap = (event: Tapped) => void;
134
+ /**
135
+ * Props accepted by the internal {@link Tappable} provider. The provider
136
+ * stores the supplied `tap` callback behind a ref so a parent re-render
137
+ * that changes the callback identity does not invalidate the React
138
+ * context value &mdash; every dispatch reads the latest callback at
139
+ * fire time.
140
+ */
141
+ export type Props = {
142
+ /**
143
+ * Observer invoked for every action handler lifecycle event inside
144
+ * the surrounding `<Boundary>`. Omit (or pass `undefined`) to
145
+ * disable observation &mdash; the dispatch path then pays only the
146
+ * cost of a single function call per handler invocation.
147
+ */
148
+ tap?: Tap;
149
+ children: React.ReactNode;
150
+ };
@@ -0,0 +1,14 @@
1
+ import { Tap } from './types';
2
+ import * as React from "react";
3
+ /**
4
+ * React context carrying the active {@link Tap} observer for the
5
+ * surrounding `<Boundary>`. Defaults to a no-op so `useTap()` callers
6
+ * never need to null-check.
7
+ */
8
+ export declare const Context: React.Context<Tap>;
9
+ /**
10
+ * Hook returning the active tap observer. Always returns a callable
11
+ * &mdash; if no `<Boundary tap={...}>` is mounted above, calls are
12
+ * silent no-ops with no allocation cost beyond the function call itself.
13
+ */
14
+ export declare function useTap(): Tap;
@@ -1,21 +1,21 @@
1
1
  import { Props } from './types';
2
2
  import * as React from "react";
3
3
  /**
4
- * Creates a unified context boundary for all March Hare features.
5
- * Wraps children with Broadcaster, Store, and Tasks providers.
4
+ * Low-level boundary primitive. Wraps children with the Broadcaster,
5
+ * Env, and Tasks providers required by every March Hare hook.
6
6
  *
7
- * Use this at the root of your application or to create isolated context
8
- * boundaries for libraries that need their own March Hare context.
9
- *
10
- * Pass the `store` prop with the initial Store value (session, locale,
11
- * feature flags, etc.) &mdash; the shape is determined by module
12
- * augmentation on the library's `Store` interface.
7
+ * Most applications should reach for {@link App} instead &mdash;
8
+ * `App<S>({ env })` returns a typed `app.Boundary` along with
9
+ * matching `useContext` / `useEnv` / `Resource` factories that all
10
+ * close over the App's inferred env shape `S`. The bare `Boundary`
11
+ * is exposed for advanced or library-internal use where the loose
12
+ * Env record type is sufficient.
13
13
  *
14
14
  * @example
15
15
  * ```tsx
16
- * <Boundary store={{ session: null, locale: "en-GB" }}>
16
+ * <Boundary env={{ session: null, locale: "en-GB" }}>
17
17
  * <App />
18
18
  * </Boundary>
19
19
  * ```
20
20
  */
21
- export declare function Boundary({ store, children }: Props): React.ReactNode;
21
+ export declare function Boundary({ env, tap, children }: Props): React.ReactNode;
@@ -1,22 +1,54 @@
1
- import { Store } from './components/store/types';
1
+ import { Env } from './components/env/types';
2
+ import { Tap } from './components/tap/types';
2
3
  import type * as React from "react";
4
+ /**
5
+ * Props accepted by the bare `<Boundary>` provider.
6
+ *
7
+ * Most applications declare these once via {@link App} and let the
8
+ * generated `<app.Boundary>` thread them through &mdash; the bare
9
+ * Boundary is exposed for advanced use (custom wrappers, isolated test
10
+ * renders) where the loose {@link Env} record type is sufficient and
11
+ * the typed `app.useContext` / `app.useEnv` surface isn't needed.
12
+ *
13
+ * All fields are optional. Omit them all and the Boundary still wraps
14
+ * its subtree with the Broadcaster, Env, Tasks, and Tap providers
15
+ * required by every March Hare hook &mdash; just with a default empty
16
+ * env and a no-op tap.
17
+ */
3
18
  export type Props = {
4
19
  /**
5
- * Initial value of the per-Boundary {@link Store}. The shape is
6
- * derived from module augmentation &mdash; declare the keys your
7
- * application needs once via:
20
+ * Initial value of the per-Boundary {@link Env}. Prefer `App({ env })`
21
+ * &mdash; it infers the Env shape `S` and threads it through
22
+ * `app.useContext`, `app.useEnv`, and `app.Resource`, so handler
23
+ * `context.env` is typed accordingly. Pass `env` directly here only
24
+ * for advanced cases where the loose record type is sufficient.
8
25
  *
9
- * ```ts
10
- * declare module "march-hare" {
11
- * interface Store {
12
- * session: Session | null;
13
- * locale: string;
14
- * }
15
- * }
16
- * ```
26
+ * The value is captured on mount; subsequent prop updates do not
27
+ * replace the live env. Mutations during the boundary's lifetime
28
+ * flow through `context.actions.produce(({ env }) => { ... })`.
29
+ */
30
+ env?: Env;
31
+ /**
32
+ * Observer invoked for every action handler lifecycle event inside
33
+ * this Boundary. One event fires per handler invocation, not per
34
+ * dispatch &mdash; a broadcast that reaches five subscribers
35
+ * produces five `dispatch` events, five `settle` events, and an
36
+ * `error` event for any of the five that throws.
37
+ *
38
+ * The callback is synchronous: it blocks the dispatch path until it
39
+ * returns. Defer slow work (network transports, file IO) to a queue
40
+ * or idle callback rather than running it inline.
17
41
  *
18
- * Optional only when the augmented Store has no required keys.
42
+ * Typical uses: analytics histograms, audit-log ring buffers,
43
+ * Sentry breadcrumbs, replay traces for bug reports. For in-band
44
+ * error recovery use {@link Lifecycle.Fault} instead &mdash; the two
45
+ * channels are independent. See `recipes/tap.md`.
46
+ */
47
+ tap?: Tap;
48
+ /**
49
+ * Subtree that should receive the boundary's broadcast, env, tasks,
50
+ * and tap providers. Every March Hare hook called inside this
51
+ * subtree resolves against this boundary's context.
19
52
  */
20
- store?: Store;
21
53
  children: React.ReactNode;
22
54
  };
@@ -28,11 +28,11 @@ export type { Adapter, Encoded } from './types';
28
28
  * clear: () => localStorage.clear(),
29
29
  * });
30
30
  *
31
- * // Wired into a Resource — successful runs write through automatically.
32
- * export const cat = Resource(
33
- * async ({ controller }) => fetchCat(controller.signal),
31
+ * // Wire it into a Resource — successful runs write through automatically.
32
+ * export const cat = Resource({
34
33
  * cache,
35
- * );
34
+ * fetch: (context) => fetchCat(context.controller.signal),
35
+ * });
36
36
  * ```
37
37
  */
38
38
  export type Cache = {
@@ -0,0 +1,57 @@
1
+ import { Coalesce } from '../resource/types';
2
+ /**
3
+ * Sentinel token used when `.coalesce()` is called with no explicit
4
+ * argument. Every untokened caller for the same `(Resource, params)`
5
+ * slot collapses onto this single key, so multiple callers chaining
6
+ * `.coalesce()` share one in-flight fetch.
7
+ *
8
+ * The symbol description follows the `march-hare.{category}/{name}`
9
+ * convention used by the rest of the library's internal symbols.
10
+ *
11
+ * @internal
12
+ */
13
+ export declare const token: unique symbol;
14
+ /**
15
+ * Builds the per-call dedupe key for `.coalesce(token)`.
16
+ *
17
+ * The full registry key (constructed at the call site) is
18
+ * `${JSON.stringify(params)}|${coalesceKey(token)}`; this function is
19
+ * responsible only for the trailing token segment. Every supported
20
+ * `Coalesce` primitive (`string`, `number`, `bigint`, `boolean`,
21
+ * `symbol`) is prefixed with a single-character type tag so that
22
+ * structurally identical values from different types stay distinct
23
+ * &mdash; e.g. the string `"5"` does not collide with the number `5`,
24
+ * and `Symbol("X")` does not collide with the string `"X"`.
25
+ *
26
+ * Symbols are keyed by their `description` (falling back to
27
+ * `String(value)` for description-less symbols) so two `Symbol("X")`
28
+ * instances declared in separate modules still hash to the same key.
29
+ * That is intentional: the public contract is "same description &rarr;
30
+ * same coalesce group", which keeps the API friendly for the common
31
+ * enum-token pattern at call sites.
32
+ *
33
+ * Any unrecognised value falls through to the object branch and is
34
+ * keyed by its JSON shape; `Coalesce` is constrained to primitives at
35
+ * the type level, so this branch is reachable only from `unknown`
36
+ * coercion in tests.
37
+ *
38
+ * @internal
39
+ */
40
+ export declare function coalesceKey(value: Coalesce): string;
41
+ /**
42
+ * Wraps `promise` so that aborting `signal` rejects the returned
43
+ * promise with `signal.reason`, even when `promise` itself never
44
+ * settles. The original promise is left alone &mdash; the underlying
45
+ * work continues (other awaiters keep their grip) and only this
46
+ * caller's view of it is severed.
47
+ *
48
+ * Used by the `.coalesce(token)` chainable: the shared in-flight fetch
49
+ * runs on a detached `AbortController` so one caller's abort does not
50
+ * cancel work the others are still waiting on, while each caller's own
51
+ * `context.task.controller` still aborts its personal await via this
52
+ * wrapper. The `{ once: true }` listener and the cleanup on settle keep
53
+ * the wrapper free of leaks across long-lived signals.
54
+ *
55
+ * @internal
56
+ */
57
+ export declare function withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
@@ -0,0 +1,41 @@
1
+ import { Actions, Context as ContextHandle, Model, Props } from '../types/index';
2
+ /**
3
+ * Returns a stable, typed controller handle up-front &mdash; before a
4
+ * model is declared via `context.useActions(...)`. Use this when an
5
+ * external imperative library (form, animation, third-party SDK) needs a
6
+ * dispatch callback at construction time, while the value that library
7
+ * returns must flow back into the controller's data callback.
8
+ *
9
+ * The handle exposes `dispatch(action, payload?)`, a `useActions(...)`
10
+ * method that materialises the component-local model and reactive data
11
+ * &mdash; the M and D pair of `useContext<M, AC, D>` &mdash; and
12
+ * returns the `[model, actions, data]` tuple with `useAction`, `dispatch`,
13
+ * `inspect`, and `stream` attached, plus `with` &mdash; a bag of handler
14
+ * factories (`update`/`invert`/`always`) typed against the declared model
15
+ * and accepting lodash-style dotted paths and array indices. The first
16
+ * invocation of `context.actions.dispatch(...)` must come from an event
17
+ * handler &mdash; not synchronously during render &mdash; because the
18
+ * underlying dispatch target is wired up when `context.useActions(...)`
19
+ * runs in the same render pass.
20
+ *
21
+ * @template M The model type representing the component's state.
22
+ * @template AC The actions class containing action definitions.
23
+ * @template D The data type for reactive external values.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * const context = useContext<Model, typeof Actions, Data>();
28
+ *
29
+ * const form = useForm({
30
+ * onSubmit: () => void context.actions.dispatch(Actions.Submit),
31
+ * });
32
+ *
33
+ * const actions = context.useActions(
34
+ * { user: resource.user() },
35
+ * () => ({ form }),
36
+ * );
37
+ * ```
38
+ *
39
+ * @internal
40
+ */
41
+ export declare function useContext<M extends Model | void = void, AC extends Actions | void = void, D extends Props = Props>(): ContextHandle<M, AC, D>;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The signature `useContext` stores in a ref once
3
+ * `context.useActions(...)` runs &mdash; the underlying dispatch target.
4
+ * `context.actions.dispatch(action, payload?)` forwards through this
5
+ * function so the handle returned by `useContext` is callable before
6
+ * the matching `useActions` call has wired everything up.
7
+ *
8
+ * Erased to `unknown` because the public surface re-types `dispatch` per
9
+ * call site via the action's generic constraints; the runtime contract
10
+ * is just "(action, payload?) => Promise<void>".
11
+ *
12
+ * @internal
13
+ */
14
+ export type DispatchTarget = (action: unknown, payload?: unknown) => Promise<void>;
@@ -1,2 +1,2 @@
1
- export { Reason, AbortError, TimeoutError } from './types';
1
+ export { Reason, Aborted } from './types';
2
2
  export type { Fault } from './types';
@@ -3,37 +3,26 @@ import { Task } from '../boundary/components/tasks/types';
3
3
  * Reasons why an action error occurred.
4
4
  */
5
5
  export declare enum Reason {
6
- /** Action exceeded its timeout limit. */
7
- Timedout = 0,
8
- /** Action was cancelled by a newer dispatch. */
9
- Supplanted = 1,
6
+ /** Action was aborted &mdash; superseded by a newer dispatch, the
7
+ * component unmounted, or `task.controller.abort()` was called. */
8
+ Aborted = 0,
10
9
  /** A generic error thrown in the user's action handler. */
11
- Errored = 2
10
+ Errored = 1
12
11
  }
13
12
  /**
14
13
  * Error thrown when an action is aborted, e.g., when a component unmounts
15
14
  * or when a newer dispatch cancels a previous run. Works across all platforms
16
15
  * including React Native where `DOMException` is unavailable.
17
16
  *
18
- * @example
19
- * ```ts
20
- * throw new AbortError("User cancelled the request");
21
- * ```
22
- */
23
- export declare class AbortError extends Error {
24
- name: string;
25
- constructor(message?: string);
26
- }
27
- /**
28
- * Error thrown when an action exceeds its timeout limit.
29
- * Works across all platforms including React Native where `DOMException` is unavailable.
17
+ * The instance's `name` field stays as `"AbortError"` so it can be
18
+ * pattern-matched alongside native `DOMException`s and ky/fetch aborts.
30
19
  *
31
20
  * @example
32
21
  * ```ts
33
- * throw new TimeoutError("Request took too long");
22
+ * throw new Aborted("User cancelled the request");
34
23
  * ```
35
24
  */
36
- export declare class TimeoutError extends Error {
25
+ export declare class Aborted extends Error {
37
26
  name: string;
38
27
  constructor(message?: string);
39
28
  }
package/dist/index.d.ts CHANGED
@@ -1,20 +1,16 @@
1
+ export { App } from './app/index';
1
2
  export { Action } from './action/index';
2
3
  export { Distribution, Lifecycle } from './types/index';
3
- export { Reason, AbortError, TimeoutError } from './error/index';
4
- export { Operation, Op, State } from 'immertation';
5
- export { annotate } from './annotate/index';
4
+ export { With } from './with/index';
6
5
  export { Boundary } from './boundary/index';
7
- export { withScope } from './boundary/components/scope/index';
8
- export { useStore } from './boundary/components/store/index';
9
- export type { Store } from './boundary/components/store/index';
10
- export { useContext, With } from './hooks/index';
11
- export type { Dispatch, Context } from './types/index';
12
6
  export { Resource } from './resource/index';
13
- export type { Fetcher } from './resource/index';
14
7
  export { Cache } from './cache/index';
15
- export type { Adapter, Encoded } from './cache/index';
8
+ export { Reason, Aborted } from './error/index';
9
+ export { annotate } from './annotate/index';
10
+ export { Operation, Op, State } from 'immertation';
16
11
  export * as utils from './utils/index';
17
- export type { Stored, Unset } from './utils/index';
18
- export type { Box } from 'immertation';
19
12
  export type { Fault } from './error/index';
20
- export type { Pk, Reactive, Task, Tasks, Handlers, Handler, LeafActions, Dispatchable, Subscribable, } from './types/index';
13
+ export type { Adapter } from './cache/index';
14
+ export type { Box } from 'immertation';
15
+ export type { Pk, Task, Tasks, Maybe, Handler, Handlers, } from './types/index';
16
+ export type { Tap, Tapped, Invocation, Failure, Mutations, Snapshot, } from './boundary/components/tap/types';
@@ -1,5 +1,8 @@
1
- import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o,produce as s}from"immer";import{jsx as c}from"react/jsx-runtime";import*as a from"react";const i=(e="")=>`march-hare.action/${e}`,u=(e="")=>`march-hare.action/broadcast/${e}`,l=(e="")=>`march-hare.action/multicast/${e}`,f=(e="")=>`march-hare.action.lifecycle/${e}`;class d{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function p(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[d.Action]:t,[d.Payload]:void 0,[d.Channel]:n,[d.Name]:e,channel:n}};return Object.defineProperty(n,d.Action,{value:t,enumerable:!1}),Object.defineProperty(n,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,d.Name,{value:e,enumerable:!1}),n}const h=Symbol(u("Fault")),m=Symbol(u("Store"));class y{static Mount(){return p("Mount")}static Unmount(){return p("Unmount")}static Error(){return p("Error")}static Update(){return p("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:h,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:m,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Store",enumerable:!1}),e})()}var b=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),v=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(v||{});const g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&d.Action in t?t[d.Action]:t}function O(t){if(e.isString(t))return t.startsWith(u());if(g(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Broadcast in t&&t[d.Broadcast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(u())??!1}}return!1}function P(t){const n=w(t),r=e.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function S(t){return e.isObject(t)&&d.Channel in t&&"channel"in t}function j(e){const t=w(e),n=g(t)?t.description??"":t;return n.startsWith(f())&&n.slice(f().length)||null}function E(t){if(e.isString(t))return t.startsWith(l());if(g(t))return t.description?.startsWith(l())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Multicast in t&&t[d.Multicast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(l())??!1}}return!1}const x=(e="",t=b.Unicast)=>{const n=t===b.Broadcast?Symbol(u(e)):t===b.Multicast?Symbol(l(e)):Symbol(i(e)),r=function(t){return{[d.Action]:n,[d.Payload]:void 0,[d.Channel]:t,[d.Name]:e,channel:t}};return Object.defineProperty(r,d.Action,{value:n,enumerable:!1}),Object.defineProperty(r,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,d.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(r,d.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(r,d.Multicast,{value:!0,enumerable:!1}),r};var C=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(C||{});class M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class A extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let k=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var N=/* @__PURE__ */(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(N||{}),_=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(_||{}),R=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(R||{});class U{[n]=!0;static keys=new Set(Object.values(R));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new U(this.value,this.operation);return n.property=e,n.process=t,n}}class T{static immer=(()=>{r();const e=new o;return e.setAutoFreeze(!1),e})();static tag="κ";static id=k}function L(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function B(t){if(e.isNullable(t)||$(t))return t;if(e.isArray(t))return t.map(e=>B(e));if(e.isObject(t)&&W(t)){const e=Object.entries(t).map(([e,t])=>[e,B(t)]);return{...Object.fromEntries(e),[T.tag]:t[T.tag]??T.id()}}return t}function F(e){if(Array.isArray(e))return e.filter(e=>T.tag in e).map(e=>e[T.tag]??"").join(",");const t=e[T.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function W(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function D(t,n,r,o,s,c){return function a(i,u=n.path){if(i instanceof U){const n=L(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>a(t,u.concat(e))),$(i.value)){if(t===_.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?L(r,a.join(".")):r;return e.isNullable(l)||H(l,i,u.at(-1),o,s,c),n??i.value}if(t===_.Hydrate){const e=B(a(i.value,u));return H(e,i,null,o,s,c),e}const l=n??B(i.value);return H(l,i,null,o,s,c),e.isNullable(n)?l:(a(i.value,u),n)}if(e.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(e.isObject(i)&&!W(i))return i;if(e.isObject(i)){const e=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=B(n);return Object.entries(i).forEach(([t,n])=>{n instanceof U&&$(n.value)&&H(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function H(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class I{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=F){this.#t=e}static pk(){return k()}static"κ"=I.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,c){function a(s){const c=s.at(-1),a=L(n(),s),i=s.slice(0,-1),u=t.isNotEmpty(i)?L(n(),i):n();return[...e.isObject(a)||e.isArray(a)?r.get(o(a))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!t.isEmpty(a(r)):"remaining"===i?()=>t.length(a(r)):"box"===i?()=>({value:L(n(),r),inspect:e(r)}):"is"===i?e=>a(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.head(a(r))?.value??L(n(),r):"settled"===i?()=>new Promise(e=>{if(t.isEmpty(a(r)))return e(L(n(),r));const o=()=>{t.isEmpty(a(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(i)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(_.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(_.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=T.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>T.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=B(this.#e),this.#c(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const z=new I;function J(e,t=N.Update){return z.annotate(t,e)}function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var G,K={exports:{}};const V=/* @__PURE__ */q((G||(G=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(K)),K.exports));class Q extends V{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}fire(e,...t){return super.emit(e,...t)}}const X=a.createContext(new Q);function Y(){return a.useContext(X)}function Z({children:e}){const t=a.useMemo(()=>new Q,[]);/* @__PURE__ */
2
- return c(X.Provider,{value:t,children:e})}const ee=a.createContext(/* @__PURE__ */new Set);function te({children:e}){const t=a.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
- return c(ee.Provider,{value:t,children:e})}const ne=a.createContext({current:{}});function re(){const e=a.useContext(ne);return a.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,n){const r=Object.getOwnPropertyDescriptor(e.current,n);if(void 0!==r)return{...r,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function oe({initial:e,children:t}){const n=a.useRef(e),r=Y();return void 0===r.getCached(m)&&r.setCache(m,n.current),/* @__PURE__ */c(ne.Provider,{value:n,children:t})}function se({store:e,children:t}){/* @__PURE__ */
4
- return c(Z,{children:/* @__PURE__ */c(oe,{initial:e??{},children:/* @__PURE__ */c(te,{children:t})})})}const ce=a.createContext(null);function ae(){return a.useContext(ce)}function ie(e,t){return e?.get(t)??null}function ue(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=w(e);return{[n](e){const n=ae(),o=a.useMemo(()=>({action:r,emitter:new Q}),[]),s=a.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
5
- return c(ce.Provider,{value:s,children:/* @__PURE__ */c(t,{...e})})}}[n]}const le=Symbol(((e="")=>`march-hare/replay${e}`)());function fe(e,t,...n){e instanceof Q&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}const de={Update:e=>(t,n)=>{t.actions.produce(t=>{t.model[e]=n})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}};function pe(e,t){for(const n of e.keys())if(j(n)===t)return n;return null}const he=/* @__PURE__ */Symbol("march-hare.unset");function me(){const[,e]=a.useReducer(e=>e+1,0);return e}function ye(){return{data:he,at:null,else:e=>e}}function be(e,t){return{data:e,at:t,else:t=>e}}function ve(e){if(e instanceof Error){if("TimeoutError"===e.name)return C.Timedout;if("AbortError"===e.name)return C.Supplanted}return C.Errored}function ge(e){const t=/* @__PURE__ */new Map,n=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=n.get(e);if(null===t)return ye();const r=JSON.parse(t);return be(r.data,Temporal.Instant.from(r.at))}catch{return ye()}},set(e,t){if(t.data===he||null===t.at)return!1;try{return n.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){n.remove(e)},clear(){n.clear()}}}function we(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new M);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new M)},{once:!0})})}async function Oe(e,t,n){if(t?.aborted)throw new M;for(;;){if(await n())return;await we(e,t)}}function Pe(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Se=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Pe,poll:Oe,sleep:we,unset:he,"ζ":we,"κ":Pe,"π":Oe},Symbol.toStringTag,{value:"Module"})),je=/* @__PURE__ */new WeakMap;function Ee(e){return JSON.stringify(e)}let xe=null;function Ce(){if(null===xe)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=xe;return xe=null,e}function Me(e,t){const n=t??function(e){let t=je.get(e);return void 0===t&&(t=ge(),je.set(e,t)),t}(e),r=e=>{const t=n.get(Ee(e));return t.data===he||null===t.at?{data:he,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(Ee(o),be(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(Ee(e),be(t,r))};return function(e){const t=e??{};xe={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==xe&&xe.params===t&&(xe=null)});const{data:n}=r(t);return n===he?null:n}}const Ae=a.createContext(/* @__PURE__ */new Map);function ke({action:t,renderer:n}){const r=Y(),o=a.useContext(Ae),s=me(),c=a.useMemo(()=>{const e=o.get(t);if(e)return e;const n=new I,s=r.getCached(t);void 0!==s&&n.hydrate({value:s});const c={state:n,listeners:/* @__PURE__ */new Set};return o.set(t,c),c},[t,r,o]);a.useLayoutEffect(()=>{function e(e){c.state.hydrate({value:e}),c.listeners.forEach(e=>e())}return c.listeners.add(s),r.on(t,e),()=>{c.listeners.delete(s),r.off(t,e)}},[t,r,c]);const i=c.state.model?.value;return e.isNullable(i)?null:n(i,c.state.inspect.value)}function Ne(){const n=a.useRef(null);return a.useMemo(()=>({actions:{dispatch:function(e,t){const r=n.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(e,t)}},useActions:function(...r){const o=function(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),c=Y(),i=ae(),u=a.useContext(ee),l=re(),f=a.useContext(ne),d=me(),p=a.useRef(!1),y=a.useRef(null),b=a.useRef(new I);p.current||(p.current=!0,y.current=b.current.hydrate(r));const[g,j]=a.useState(()=>b.current.model),x=function(e){const t=a.useRef(e);return t.current=e,a.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(o()),C=a.useMemo(()=>new V,[]),M=a.useRef({handlers:/* @__PURE__ */new Map});M.current.handlers=/* @__PURE__ */new Map;const A=function(){const e=a.useRef(/* @__PURE__ */new Set),t=a.useRef(/* @__PURE__ */new Set);return a.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),k=a.useRef(v.Mounting),_=a.useRef(/* @__PURE__ */new Set),R=a.useRef(0),U=a.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),_.current.add(o),{model:b.current.model,get phase(){return k.current},task:o,data:x,tasks:u,store:l,actions:{produce(e){if(r.signal.aborted)return;const t=f.current,o=b.current.produce(t=>{f.current=s(f.current,n=>{e({model:t,inspect:b.current.inspect,store:n})})});j(b.current.model),f.current!==t&&c.emit(m,f.current),n.processes.add(o),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=w(e),o=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,o):Promise.resolve()}return fe(O(e)?c:C,n,t,o)},annotate:(e,t=N.Update)=>b.current.annotate(t,e),get inspect(){return b.current.inspect},resource:Object.assign(function(e){const t=Ce(),n=()=>t.run(f.current,r,t.params);return{then:(e,t)=>n().then(e,t),exceeds:e=>{const{data:r,at:o}=t.read(t.params);if(r!==he&&null!==o){const t=Temporal.Now.instant().since(o),n=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(r)}return n()}}},{set:(e,t)=>{const n=Ce();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;if(!n)return null;if(void 0===n.getCached(t))return null;const o=b.current.inspect;return o.pending()&&await new Promise((e,t)=>{if(r.signal.aborted)return void t(r.signal.reason);const n=()=>t(r.signal.reason);r.signal.addEventListener("abort",n,{once:!0}),o.settled().then(()=>{r.signal.removeEventListener("abort",n),e()})}),n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[g]);a.useLayoutEffect(()=>{function t(t,n,r){return function(o,s){const a=r();if(s===le&&e.isNotNullable(a))return;if(e.isNotNullable(s)&&s!==le&&e.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(s,a))return;const i={processes:/* @__PURE__ */new Set},l=Promise.withResolvers(),f=U(t,o,i);function p(e){const n=pe(M.current.handlers,"Error"),r=null!==n,o={reason:ve(e),error:(s=e,s instanceof Error?s:new Error(String(s))),action:P(t),handled:r,tasks:u};var s;c.fire(h,o),r&&n&&C.emit(n,o)}function m(){for(const e of u)if(e===f.task){u.delete(e),_.current.delete(e);break}i.processes.forEach(e=>b.current.prune(e)),i.processes.size>0&&d(),l.resolve()}let y;try{y=n(f,o)}catch(v){return p(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(p).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(p).finally(m)}}R.current++;const n=/* @__PURE__ */new Set;return M.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:s}of e){const e=t(r,s,o);if(E(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}C.on(r,e),A.multicast.add(r),n.add(()=>C.off(r,e))}else O(r)?(c.on(r,e),C.on(r,e),A.broadcast.add(r),n.add(()=>{c.off(r,e),C.off(r,e)})):(C.on(r,e),n.add(()=>C.off(r,e)))}}),()=>{const e=++R.current,t=new Set(n);queueMicrotask(()=>{if(R.current!==e){for(const e of t)e();return}for(const e of _.current)e.controller.abort(),u.delete(e);_.current.clear(),k.current=v.Unmounting;const n=pe(M.current.handlers,"Unmount");n&&C.emit(n),k.current=v.Unmounted;for(const e of t)e()})}},[C]),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:c,data:i,handlers:u}){const l=a.useRef(null);a.useLayoutEffect(()=>{if(c.current===v.Mounted)return;c.current=v.Mounting;const t=pe(u,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,le)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,le)}}),c.current=v.Mounted},[]),a.useLayoutEffect(()=>{if(e.isNotNullable(l.current)){const e=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(t.isNotEmpty(Object.keys(e))){const t=pe(u,"Update");t&&n.emit(t,e)}}l.current=i},[i,n])}({unicast:C,broadcast:c,dispatchers:A,scope:i,phase:k,data:o(),handlers:M.current.handlers});const T=a.useMemo(()=>({dispatch(e,t){const n=w(e),r=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,r):Promise.resolve()}return fe(O(e)?c:C,n,t,r)},get inspect(){return b.current.inspect},stream:(e,t)=>a.createElement(ke,{action:w(e),renderer:t})}),[g,C]),L=a.useMemo(()=>[g,T,x],[g,T,x]);return L.useAction=(e,t)=>{!function(e,t,n){const r=a.useRef(n);a.useLayoutEffect(()=>{r.current=n});const o=a.useRef(t);a.useLayoutEffect(()=>{o.current=t});const s=a.useCallback((e,t)=>r.current(e,t),[]),c=a.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),i=w(t),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:c,handler:s})}(M,e,t)},L.dispatch=L[1].dispatch,L}(...r);return n.current=o.dispatch,o}}),[])}export{M as AbortError,x as Action,se as Boundary,ge as Cache,b as Distribution,y as Lifecycle,N as Op,N as Operation,C as Reason,Me as Resource,I as State,A as TimeoutError,de as With,J as annotate,Ne as useContext,re as useStore,Se as utils,ue as withScope};
1
+ import{jsx as e}from"react/jsx-runtime";import*as t from"react";import{G as n,A as r}from"@mobily/ts-belt";import{immerable as o,enablePatches as s,Immer as c,produce as a}from"immer";function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var u,l={exports:{}};const f=/* @__PURE__ */i((u||(u=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,h=l.length;for(u=0;u<h;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(l)),l.exports));class d extends f{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}fire(e,...t){return super.emit(e,...t)}}const h=t.createContext(new d);function p(){return t.useContext(h)}function m({children:n}){const r=t.useMemo(()=>new d,[]);/* @__PURE__ */
2
+ return e(h.Provider,{value:r,children:n})}const b=t.createContext(/* @__PURE__ */new Set);function y({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return e(b.Provider,{value:r,children:n})}const v=t.createContext({current:{}});function g(){const e=t.useContext(v);return t.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,r){const o=Object.getOwnPropertyDescriptor(e.current,r);if(!n.isUndefined(o))return{...o,configurable:!0}},set(){throw new TypeError("Env is read-only outside `context.actions.produce`. Mutate via produce(({ env }) => { env.x = ... }) instead.")}}),[e])}const w=(e="")=>`march-hare.action/${e}`,O=(e="")=>`march-hare.action/broadcast/${e}`,P=(e="")=>`march-hare.action/multicast/${e}`,j=(e="")=>`march-hare.action.lifecycle/${e}`;class x{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function S(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[x.Action]:t,[x.Payload]:void 0,[x.Channel]:n,[x.Name]:e,channel:n}};return Object.defineProperty(n,x.Action,{value:t,enumerable:!1}),Object.defineProperty(n,x.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,x.Name,{value:e,enumerable:!1}),n}const E=Symbol(O("Fault")),C=Symbol(O("Env"));class k{static Mount(){return S("Mount")}static Unmount(){return S("Unmount")}static Error(){return S("Error")}static Update(){return S("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,x.Action,{value:E,enumerable:!1}),Object.defineProperty(e,x.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,x.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,x.Name,{value:"Fault",enumerable:!1}),e})();static Env=(()=>{const e={};return Object.defineProperty(e,x.Action,{value:C,enumerable:!1}),Object.defineProperty(e,x.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,x.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,x.Name,{value:"Env",enumerable:!1}),e})()}var N=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(N||{}),M=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(M||{});function A({initial:r,children:o}){const s=t.useRef(r),c=p();return n.isUndefined(c.getCached(C))&&c.setCache(C,s.current),/* @__PURE__ */e(v.Provider,{value:s,children:o})}const _=t.createContext(/* @__PURE__ */new WeakMap);function R({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new WeakMap,[]);/* @__PURE__ */
4
+ return e(_.Provider,{value:r,children:n})}const U=t.createContext(()=>{});function L({tap:n,children:r}){const o=t.useRef(n);t.useLayoutEffect(()=>{o.current=n},[n]);const s=t.useMemo(()=>e=>o.current?.(e),[]);/* @__PURE__ */
5
+ return e(U.Provider,{value:s,children:r})}function T({env:t,tap:n,children:r}){/* @__PURE__ */
6
+ return e(m,{children:/* @__PURE__ */e(A,{initial:t??{},children:/* @__PURE__ */e(y,{children:/* @__PURE__ */e(L,{tap:n,children:/* @__PURE__ */e(R,{children:r})})})})})}const W=e=>"symbol"==typeof e;function $(e){return n.isString(e)||W(e)?e:(n.isObject(e)||n.isFunction(e))&&x.Action in e?e[x.Action]:e}function B(e){if(n.isString(e))return e.startsWith(O());if(W(e))return e.description?.startsWith(O())??!1;if(n.isObject(e)||n.isFunction(e)){if(x.Broadcast in e&&e[x.Broadcast])return!0;if(x.Action in e){const t=e[x.Action];return t.description?.startsWith(O())??!1}}return!1}function F(e){return n.isObject(e)&&x.Channel in e&&"channel"in e}function D(e){const t=$(e),n=W(t)?t.description??"":t;return n.startsWith(j())&&n.slice(j().length)||null}function H(e){if(n.isString(e))return e.startsWith(P());if(W(e))return e.description?.startsWith(P())??!1;if(n.isObject(e)||n.isFunction(e)){if(x.Multicast in e&&e[x.Multicast])return!0;if(x.Action in e){const t=e[x.Action];return t.description?.startsWith(P())??!1}}return!1}const I=(e="",t=N.Unicast)=>{const n=t===N.Broadcast?Symbol(O(e)):t===N.Multicast?Symbol(P(e)):Symbol(w(e)),r=function(t){return{[x.Action]:n,[x.Payload]:void 0,[x.Channel]:t,[x.Name]:e,channel:t}};return Object.defineProperty(r,x.Action,{value:n,enumerable:!1}),Object.defineProperty(r,x.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,x.Name,{value:e,enumerable:!1}),t===N.Broadcast&&Object.defineProperty(r,x.Broadcast,{value:!0,enumerable:!1}),t===N.Multicast&&Object.defineProperty(r,x.Multicast,{value:!0,enumerable:!1}),r},J=Symbol(((e="")=>`march-hare/replay${e}`)());function z(e,t,...n){e instanceof d&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function q(e,t){for(const n of e.keys())if(D(n)===t)return n;return null}const G=/* @__PURE__ */Symbol("march-hare.unset");function K(){const[,e]=t.useReducer(e=>e+1,0);return e}function V(){return{data:G,at:null,else:e=>e}}function Q(e,t){return{data:e,at:t,else:t=>e}}var X=/* @__PURE__ */(e=>(e[e.Aborted=0]="Aborted",e[e.Errored=1]="Errored",e))(X||{});class Y extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const Z=t.createContext(null);function ee(e){const t=/* @__PURE__ */new Map,r=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=r.get(e);if(n.isNull(t))return V();const o=JSON.parse(t);return Q(o.data,Temporal.Instant.from(o.at))}catch{return V()}},set(e,t){if(t.data===G||n.isNull(t.at))return!1;try{return r.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){r.remove(e)},clear(){r.clear()}}}function te(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new Y);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Y)},{once:!0})})}async function ne(e,t,n){if(t?.aborted)throw new Y;for(;;){if(await n())return;await te(e,t)}}function re(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const oe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:re,poll:ne,sleep:te,unset:G,"ζ":te,"κ":re,"π":ne},Symbol.toStringTag,{value:"Module"})),se=/* @__PURE__ */new WeakMap;function ce(e){return JSON.stringify(e)}let ae=null;function ie(){if(n.isNull(ae))throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(resource.cat({ id: 5 })).");const e=ae;return ae=null,e}function ue(e,t){const r=e=>{const r=t.get(ce(e));return r.data===G||n.isNull(r.at)?{data:G,at:null}:{data:r.data,at:r.at}},o=(n,r,o,s)=>e({env:n,controller:r,params:o,dispatch:s}).then(e=>(t.set(ce(o),Q(e,Temporal.Now.instant())),e)),s=(e,n,r)=>{t.set(ce(e),Q(n,r))};return function(e){const t=e??{};ae={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{n.isNotNullable(ae)&&ae.params===t&&(ae=null)});const{data:c}=r(t);return c===G?null:c}}function le(e){return ue(e,function(e){let t=se.get(e);return n.isUndefined(t)&&(t=ee(),se.set(e,t)),t}(e))}(le||(le={})).Cachable=function(e,t){return ue(t,e)};const fe=/* @__PURE__ */Symbol("march-hare.coalesce/default");function de(e,t){return new Promise((n,r)=>{if(t.aborted)return void r(t.reason);const o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})})}let he=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var pe=/* @__PURE__ */(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(pe||{}),me=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(me||{}),be=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(be||{});class ye{[o]=!0;static keys=new Set(Object.values(be));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new ye(this.value,this.operation);return n.property=e,n.process=t,n}}class ve{static immer=(()=>{s();const e=new c;return e.setAutoFreeze(!1),e})();static tag="κ";static id=he}function ge(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function we(e){if(n.isNullable(e)||je(e))return e;if(n.isArray(e))return e.map(e=>we(e));if(n.isObject(e)&&Pe(e)){const t=Object.entries(e).map(([e,t])=>[e,we(t)]);return{...Object.fromEntries(t),[ve.tag]:e[ve.tag]??ve.id()}}return e}function Oe(e){if(Array.isArray(e))return e.filter(e=>ve.tag in e).map(e=>e[ve.tag]??"").join(",");const t=e[ve.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function Pe(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return n.isNullable(e)||n.isString(e)||n.isNumber(e)||n.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function xe(e,t,r,o,s,c){return function a(i,u=t.path){if(i instanceof ye){const t=ge(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!ye.keys.has(e)&&t instanceof ye).forEach(([e,t])=>a(t,u.concat(e))),je(i.value)){if(e===me.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?ge(r,a.join(".")):r;return n.isNullable(l)||Se(l,i,u.at(-1),o,s,c),t??i.value}if(e===me.Hydrate){const e=we(a(i.value,u));return Se(e,i,null,o,s,c),e}const l=t??we(i.value);return Se(l,i,null,o,s,c),n.isNullable(t)?l:(a(i.value,u),t)}if(n.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(n.isObject(i)&&!Pe(i))return i;if(n.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(t);if(e===me.Hydrate){const e=we(n);return Object.entries(i).forEach(([t,n])=>{n instanceof ye&&je(n.value)&&Se(e,n,t,o,s,c)}),e}return n}return i}(t.value)}function Se(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class Ee{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=Oe){this.#t=e}static pk(){return he()}static"κ"=Ee.pk;annotate(e,t){return new ye(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,t,o,s,c){function a(s){const c=s.at(-1),a=ge(e(),s),i=s.slice(0,-1),u=r.isNotEmpty(i)?ge(e(),i):e();return[...n.isObject(a)||n.isArray(a)?t.get(o(a))?.filter(e=>n.isNullable(e.property))??[]:[],...n.isObject(u)?t.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function t(n){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!r.isEmpty(a(n)):"remaining"===i?()=>r.length(a(n)):"box"===i?()=>({value:ge(e(),n),inspect:t(n)}):"is"===i?e=>a(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>r.head(a(n))?.value??ge(e(),n):"settled"===i?()=>new Promise(t=>{if(r.isEmpty(a(n)))return t(ge(e(),n));const o=()=>{r.isEmpty(a(n))&&(c(o),t(ge(e(),n)))};s(o)}):t([...n,String(i)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(me.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(me.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=ve.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>ve.immer.applyPatches(t,[{...r,value:xe(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=we(this.#e),this.#c(),n}prune(e){this.#n.forEach((t,n)=>{const o=t.filter(t=>t.process!==e);r.isEmpty(o)?this.#n.delete(n):this.#n.set(n,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const Ce=t.createContext(/* @__PURE__ */new Map);function ke({action:e,renderer:r}){const o=p(),s=t.useContext(Ce),c=K(),a=t.useMemo(()=>{const t=s.get(e);if(t)return t;const r=new Ee,c=o.getCached(e);n.isNotNullable(c)&&r.hydrate({value:c});const a={state:r,listeners:/* @__PURE__ */new Set};return s.set(e,a),a},[e,o,s]);t.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(c),o.on(e,t),()=>{a.listeners.delete(c),o.off(e,t)}},[e,o,a]);const i=a.state.model?.value;return n.isNullable(i)?null:r(i,a.state.inspect.value)}function Ne(e,t){const n=t.split(".");let r=e;for(let o=0;o<n.length-1;o++)r=r[n[o]];return{cursor:r,key:n[n.length-1]}}function Me(e,t,n){const{cursor:r,key:o}=Ne(e,t);r[o]=n}function Ae(e){return(t,n)=>{t.actions.produce(t=>{Me(t.model,e,n)})}}function _e(e){return t=>{t.actions.produce(t=>{!function(e,t){const{cursor:n,key:r}=Ne(e,t);n[r]=!n[r]}(t.model,e)})}}function Re(e,t){return n=>{n.actions.produce(n=>{Me(n.model,e,t)})}}const Ue={Update:e=>Ae(e),Invert:e=>_e(e),Always:(e,t)=>Re(e,t)};function Le(){const e=t.useRef(null);return t.useMemo(()=>({actions:{dispatch:function(t,n){const r=e.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(t,n)}},useActions:function(...o){const s=function(...e){const o=n.isUndefined(e[0])||n.isFunction(e[0])?{}:e[0],s=n.isFunction(e[0])?e[0]:e[1]??(()=>({})),c=p(),i=t.useContext(Z),u=t.useContext(b),l=g(),d=t.useContext(v),h=t.useContext(_),m=t.useContext(U),y=K(),O=t.useRef(!1),P=t.useRef(null),j=t.useRef(new Ee);O.current||(O.current=!0,P.current=j.current.hydrate(o));const[x,S]=t.useState(()=>j.current.model),k=function(e){const n=t.useRef(e);return n.current=e,t.useMemo(()=>{return t=n,Object.keys(e).reduce((e,n)=>(Object.defineProperty(e,n,{get:()=>t.current[n],enumerable:!0}),e),{});var t},[e])}(s()),N=t.useMemo(()=>new f,[]),A=t.useRef({handlers:/* @__PURE__ */new Map});A.current.handlers=/* @__PURE__ */new Map;const R=function(){const e=t.useRef(/* @__PURE__ */new Set),n=t.useRef(/* @__PURE__ */new Set);return t.useMemo(()=>({broadcast:e.current,multicast:n.current}),[])}(),L=t.useRef(M.Mounting),T=t.useRef(/* @__PURE__ */new Set),W=t.useRef(0),D=t.useCallback((e,t,r)=>{const o=new AbortController,s={controller:o,action:e,payload:t};return u.add(s),T.current.add(s),{model:j.current.model,get phase(){return L.current},task:s,data:k,tasks:u,env:l,actions:{produce(e){if(o.signal.aborted)return;const t=d.current,n=j.current.produce(t=>{d.current=a(d.current,n=>{e({model:t,inspect:j.current.inspect,env:n})})});S(j.current.model),d.current!==t&&c.emit(C,d.current),r.processes.add(n),P.current&&(r.processes.add(P.current),P.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=$(e),r=F(e)?e.channel:void 0;return H(e)?i?z(i.emitter,n,t,r):Promise.resolve():z(B(e)?c:N,n,t,r)},annotate:(e,t=pe.Update)=>j.current.annotate(t,e),get inspect(){return j.current.inspect},resource:Object.assign(function(e){const t=ie(),r=(e,t)=>{if(o.signal.aborted)return Promise.resolve();const n=e,r=$(n);return H(n)?i?z(i.emitter,r,t,void 0):Promise.resolve():B(n)?z(c,r,t,void 0):Promise.resolve()},s={exceedsWindow:null,coalesceToken:void 0},a={then:(e,c)=>(()=>{if(n.isNotNullable(s.exceedsWindow)){const{data:e,at:r}=t.read(t.params);if(e!==G&&n.isNotNullable(r)){const t=Temporal.Now.instant().since(r),n=Temporal.Duration.from(s.exceedsWindow);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(e)}}if(n.isUndefined(s.coalesceToken))return t.run(l,o,t.params,r);let e=h.get(t.run);n.isUndefined(e)&&(e=/* @__PURE__ */new Map,h.set(t.run,e));const c=e,a=`${JSON.stringify(t.params)}|${function(e){switch(typeof e){case"string":return`s:${e}`;case"number":return`n:${e}`;case"bigint":return`i:${e.toString()}`;case"boolean":return`b:${e}`;case"symbol":return`y:${e.description??String(e)}`;default:return`o:${JSON.stringify(e)}`}}(s.coalesceToken)}`,i=c.get(a);if(i)return de(i,o.signal);const u=new AbortController,f=t.run(l,u,t.params,r).finally(()=>{c.delete(a)});return c.set(a,f),de(f,o.signal)})().then(e,c),exceeds:e=>(s.exceedsWindow=e,a),coalesce:e=>(s.coalesceToken=e??fe,a)};return a},{set:(e,t)=>{const n=ie();n.seed(n.params,t,Temporal.Now.instant())}}),async final(e){if(o.signal.aborted)return null;const t=$(e),r=H(e)?i?.emitter??null:c;if(!r)return null;const s=r.getCached(t);if(n.isUndefined(s))return null;const a=j.current.inspect;return a.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const n=()=>t(o.signal.reason);o.signal.addEventListener("abort",n,{once:!0}),a.settled().then(()=>{o.signal.removeEventListener("abort",n),e()})}),r.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=$(e),n=H(e)?i?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[x]);t.useLayoutEffect(()=>{function e(e,t,r){return function(o,s){const a=r();if(s===J&&n.isNotNullable(a))return;if(n.isNotNullable(s)&&s!==J&&n.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(s,a))return;const i={processes:/* @__PURE__ */new Set},l=Promise.withResolvers(),f=D(e,o,i),h=function(e){const t=$(e),r=n.isString(t)?t:t.description??"";return r.startsWith(w())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}(e),p=performance.now(),b=j.current.model,v=d.current;let g,O=!1;function P(){const e=j.current.model,t=d.current;return{model:b===e?null:{before:b,after:e},env:v===t?null:{before:v,after:t}}}function x(e){O=!0;const t=q(A.current.handlers,"Error"),r=n.isNotNullable(t),s=function(e){return e instanceof Error&&"AbortError"===e.name?X.Aborted:X.Errored}(e),a=function(e){return e instanceof Error?e:new Error(String(e))}(e),i={reason:s,error:a,action:h,handled:r,tasks:u};c.fire(E,i),r&&t&&N.emit(t,i),m({stage:"end",result:"error",action:{name:h,payload:o},details:{task:f.task,elapsed:performance.now()-p,mutations:P(),error:a,reason:s}})}function S(){for(const e of u)if(e===f.task){u.delete(e),T.current.delete(e);break}i.processes.forEach(e=>j.current.prune(e)),i.processes.size>0&&y(),O||m({stage:"end",result:"success",action:{name:h,payload:o},details:{task:f.task,elapsed:performance.now()-p,mutations:P()}}),l.resolve()}m({stage:"start",action:{name:h,payload:o},details:{task:f.task}});try{g=t(f,o)}catch(C){return x(C),S(),l.promise}return function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(g)?((async()=>{for await(const e of g);})().catch(x).finally(S),l.promise):(Promise.resolve(g).catch(x).finally(S),l.promise)}}W.current++;const t=/* @__PURE__ */new Set;return A.current.handlers.forEach((n,r)=>{for(const{getChannel:o,handler:s}of n){const n=e(r,s,o);if(H(r)){if(i){const e=i.emitter;e.on(r,n),t.add(()=>e.off(r,n))}N.on(r,n),R.multicast.add(r),t.add(()=>N.off(r,n))}else B(r)?(c.on(r,n),N.on(r,n),R.broadcast.add(r),t.add(()=>{c.off(r,n),N.off(r,n)})):(N.on(r,n),t.add(()=>N.off(r,n)))}}),()=>{const e=++W.current,n=new Set(t);queueMicrotask(()=>{if(W.current!==e){for(const e of n)e();return}for(const e of T.current)e.controller.abort(),u.delete(e);T.current.clear(),L.current=M.Unmounting;const t=q(A.current.handlers,"Unmount");t&&N.emit(t),L.current=M.Unmounted;for(const e of n)e()})}},[N]),function({unicast:e,broadcast:o,dispatchers:s,scope:c,phase:a,data:i,handlers:u}){const l=t.useRef(null);t.useLayoutEffect(()=>{if(a.current===M.Mounted)return;a.current=M.Mounting;const t=q(u,"Mount");t&&e.emit(t),s.broadcast.forEach(t=>{const r=o.getCached(t);n.isNullable(r)||e.emit(t,r,J)}),c&&s.multicast.forEach(t=>{const r=c.emitter.getCached(t);n.isNullable(r)||e.emit(t,r,J)}),a.current=M.Mounted},[]),t.useLayoutEffect(()=>{if(n.isNotNullable(l.current)){const t=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(r.isNotEmpty(Object.keys(t))){const n=q(u,"Update");n&&e.emit(n,t)}}l.current=i},[i,e])}({unicast:N,broadcast:c,dispatchers:R,scope:i,phase:L,data:s(),handlers:A.current.handlers});const I=t.useMemo(()=>({dispatch(e,t){const n=$(e),r=F(e)?e.channel:void 0;return H(e)?i?z(i.emitter,n,t,r):Promise.resolve():z(B(e)?c:N,n,t,r)},get inspect(){return j.current.inspect},stream:(e,n)=>t.createElement(ke,{action:$(e),renderer:n})}),[x,N]),V=t.useMemo(()=>[x,I,k],[x,I,k]);return V.useAction=(e,n)=>{!function(e,n,r){const o=t.useRef(r);t.useLayoutEffect(()=>{o.current=r});const s=t.useRef(n);t.useLayoutEffect(()=>{s.current=n});const c=t.useCallback((e,t)=>o.current(e,t),[]),a=t.useCallback(()=>F(s.current)?s.current.channel:void 0,[]),i=$(n),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:c})}(A,e,n)},V.dispatch=V[1].dispatch,V}(...o);return e.current=s.dispatch,s},with:{update:e=>Ae(e),invert:e=>_e(e),always:(e,t)=>Re(e,t)}}),[])}function Te(n){return{Boundary:function({env:t,tap:r,children:o}){/* @__PURE__ */
7
+ return e(T,{env:t??n?.env,tap:r??n?.tap,children:o})},useContext:function(){return Le()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)}),Scope:()=>({Boundary:function({children:n}){const r=t.useMemo(()=>({id:/* @__PURE__ */Symbol("march-hare.scope/instance"),emitter:new d}),[]);/* @__PURE__ */
8
+ return e(Z.Provider,{value:r,children:n})},useContext:function(){return Le()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)})})}}const We=new Ee;function $e(e,t=pe.Update){return We.annotate(t,e)}export{Y as Aborted,I as Action,Te as App,T as Boundary,ee as Cache,N as Distribution,k as Lifecycle,pe as Op,pe as Operation,X as Reason,le as Resource,Ee as State,Ue as With,$e as annotate,oe as utils};