march-hare 0.6.1 → 0.7.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.
package/README.md CHANGED
@@ -76,27 +76,26 @@ export default function Profile(): React.ReactElement {
76
76
  }
77
77
  ```
78
78
 
79
- When you need to do more than just assign the payload – such as making an API request – expand `useAction` to a full function. It can be synchronous, asynchronous, or even a generator. Remote data goes through `Resource` rather than a bare `fetch` – declare the resource at module scope and consume it via `useResource`:
79
+ When you need to do more than just assign the payload – such as making an API request – expand `useAction` to a full function. It can be synchronous, asynchronous, or even a generator. Remote data goes through `Resource` rather than a bare `fetch` – declare the resource at module scope, fetch from handlers via `context.actions.resource(...)`:
80
80
 
81
81
  ```ts
82
82
  // resources.ts
83
83
  import { Resource } from "march-hare";
84
84
 
85
- export const user = Resource(() => ky.get(api.user()).json<User>());
85
+ export const user = Resource(({ controller }) =>
86
+ ky.get(api.user(), { signal: controller.signal }).json<User>(),
87
+ );
86
88
  ```
87
89
 
88
90
  ```tsx
89
- const get = {
90
- user: useResource(resource.user),
91
- };
92
-
93
91
  actions.useAction(Actions.Name, async (context) => {
94
92
  context.actions.produce(
95
93
  ({ model }) =>
96
94
  void (model.name = context.actions.annotate(model.name, Op.Update)),
97
95
  );
98
96
 
99
- const data = await get.user();
97
+ // Auto-threads context.task.controller and the Store snapshot.
98
+ const data = await context.actions.resource(user());
100
99
 
101
100
  context.actions.produce(({ model }) => void (model.name = data.name));
102
101
  });
@@ -109,17 +108,17 @@ If you need to access external reactive values (like props or `useState` from pa
109
108
  ```tsx
110
109
  const actions = useActions<Model, typeof Actions, { query: string }>(
111
110
  model,
112
- () => ({ query: props.query }),
111
+ () => ({
112
+ query: props.query,
113
+ }),
113
114
  );
114
115
 
115
- const get = {
116
- search: useResource(resource.search),
117
- };
118
-
119
116
  actions.useAction(Actions.Search, async (context) => {
120
- await get.search({ query: context.data.query });
117
+ const results = await context.actions.resource(
118
+ search({ query: context.data.query }),
119
+ );
121
120
  // context.data.query is always the latest value, even after await
122
- console.log(context.data.query);
121
+ console.log(context.data.query, results);
123
122
  });
124
123
  ```
125
124
 
@@ -177,17 +176,13 @@ class Actions {
177
176
  ```
178
177
 
179
178
  ```tsx
180
- const get = {
181
- user: useResource(resource.user),
182
- };
183
-
184
179
  actions.useAction(Actions.Profile, async (context) => {
185
180
  context.actions.produce(
186
181
  ({ model }) =>
187
182
  void (model.name = context.actions.annotate(model.name, Op.Update)),
188
183
  );
189
184
 
190
- const data = await get.user();
185
+ const data = await context.actions.resource(user());
191
186
 
192
187
  context.actions.produce(({ model }) => void (model.name = data.name));
193
188
 
@@ -198,12 +193,8 @@ actions.useAction(Actions.Profile, async (context) => {
198
193
  Once we have the broadcast action, if we want to listen for it and perform another operation in our local component we can do that via `useAction`:
199
194
 
200
195
  ```tsx
201
- const get = {
202
- friends: useResource(resource.friends),
203
- };
204
-
205
196
  actions.useAction(Actions.Broadcast.Name, async (context, name) => {
206
- const data = await get.friends({ name });
197
+ const data = await context.actions.resource(friends({ name }));
207
198
 
208
199
  context.actions.produce(({ model }) => void (model.friends = data));
209
200
  });
@@ -212,14 +203,10 @@ actions.useAction(Actions.Broadcast.Name, async (context, name) => {
212
203
  Both `read` and `peek` access the latest cached broadcast value without subscribing via `useAction`. The difference is that `read` waits for any pending annotations on the corresponding model field to settle before resolving, whereas `peek` returns the value immediately:
213
204
 
214
205
  ```tsx
215
- const get = {
216
- friends: useResource(resource.friends),
217
- };
218
-
219
206
  actions.useAction(Actions.FetchFriends, async (context) => {
220
207
  const name = await context.actions.resolution(Actions.Broadcast.Name);
221
208
  if (!name) return;
222
- const data = await get.friends({ name });
209
+ const data = await context.actions.resource(friends({ name }));
223
210
  context.actions.produce(({ model }) => void (model.friends = data));
224
211
  });
225
212
  ```
@@ -268,52 +255,42 @@ Components that mount after a broadcast has already been dispatched automaticall
268
255
 
269
256
  <a id="remote-data"></a>
270
257
 
271
- For remote data, declare a `Resource` at module scope and consume it via `useResource`. Every call fires its own request; the most recent successful response is cached in a module-level `WeakMap` keyed by the fetcher so `.if(...)` and `.else(...)` on the bound handle have something to read from. Convention is to keep all resources in `resources.ts` and import them as a namespace:
258
+ For remote data, declare a `Resource` at module scope and use it directly. `user(params)` is the unified call form &mdash; it returns the sync cache read (`User | null`) and primes a slot that `context.actions.resource(user(params))` consumes for the fetch path (with auto-threaded abort controller and Store snapshot). Every successful fetch caches the response in a module-level slot keyed by the fetcher and the stringified params, so different param-sets are independent. Keep all resources in `resources.ts` and pull them in with named imports:
272
259
 
273
260
  ```ts
274
261
  // resources.ts
275
262
  import { Resource } from "march-hare";
276
263
 
277
- export const user = Resource(() => ky.get("/api/user").json<User>());
264
+ export const user = Resource(({ controller }) =>
265
+ ky.get("/api/user", { signal: controller.signal }).json<User>(),
266
+ );
278
267
 
279
- export const pay = Resource((signal, body: Body) =>
280
- ky.post("/api/pay", { json: body, signal }).json<Receipt>(),
268
+ export const pay = Resource<Receipt, Body>(({ controller, params }) =>
269
+ ky
270
+ .post("/api/pay", { json: params, signal: controller.signal })
271
+ .json<Receipt>(),
281
272
  );
282
273
  ```
283
274
 
284
275
  ```tsx
285
276
  // actions.ts
286
- import { useActions, useResource } from "march-hare";
287
- import * as resource from "./resources";
277
+ import { useActions } from "march-hare";
278
+ import { user, pay } from "./resources";
288
279
 
289
280
  export function useActions() {
290
- // Bind the resources first so we can seed the initial model from the
291
- // cache via `.else(fallback)` — if a previous mount populated the
292
- // slot, the model starts with that value; otherwise the fallback.
293
- // Bindings are grouped by HTTP verb so call sites advertise read vs.
294
- // write at a glance.
295
- const get = {
296
- user: useResource(resource.user),
297
- };
298
- const post = {
299
- pay: useResource(resource.pay),
300
- };
301
-
302
281
  const actions = useActions<Model, typeof Actions>({
303
- user: get.user.else(null),
304
- receipt: post.pay.else(null),
282
+ // Sync cache read at the model literal — returns null when nothing is cached.
283
+ user: user(),
284
+ receipt: null,
305
285
  });
306
286
 
307
287
  actions.useAction(Actions.Mount, async (context) => {
308
- const data = await get.user.if(
309
- { over: { minutes: 5 } },
310
- context.task.controller.signal,
311
- );
288
+ const data = await context.actions.resource(user()).exceeds({ minutes: 5 });
312
289
  context.actions.produce(({ model }) => void (model.user = data));
313
290
  });
314
291
 
315
292
  actions.useAction(Actions.Submit, async (context, body) => {
316
- const receipt = await post.pay(context.task.controller.signal, body);
293
+ const receipt = await context.actions.resource(pay(body));
317
294
  context.actions.produce(({ model }) => void (model.receipt = receipt));
318
295
  });
319
296
 
@@ -321,15 +298,17 @@ export function useActions() {
321
298
  }
322
299
  ```
323
300
 
324
- `useResource(handle)` returns the fetch callable directly. The callable has two attached methods: `.if({ over })` skips the network when the cached payload is still fresh, and `.else(fallback)` reads the cached payload synchronously with a default. `Temporal` is read from the host runtime &ndash; bring a polyfill (e.g. [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill)) if your target environment does not yet expose it natively. `.if({ over })` accepts a `Temporal.Duration`, a `DurationLike` object, or an ISO 8601 duration string.
301
+ `context.actions.resource(invocation)` returns a thenable. Awaiting it fires the fetch unconditionally; chaining `.exceeds({ minutes: 5 })` short-circuits when the per-params cache age does not yet exceed the supplied freshness window. `.exceeds(duration)` accepts a `Temporal.Duration`, a `DurationLike` object, or an ISO 8601 duration string. `Temporal` is read from the host runtime &ndash; bring a polyfill (e.g. [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill)) if your target environment does not yet expose it natively.
325
302
 
326
- `Resource` takes a single fetcher argument. The fetcher receives the call-site `params` object as its only argument and returns a `Promise<T>`. There are no callbacks &ndash; no `onSuccess`, no `onError`, no injected `dispatch`. Side-effects after a run (broadcasting, analytics, model writes) live in the `useAction` handler that awaited the call, next to the rest of the flow:
303
+ `Resource` takes a single fetcher argument. The fetcher receives `{ store, controller, params }` &mdash; destructure whichever you need. There are no callbacks &ndash; no `onSuccess`, no `onError`, no injected `dispatch`. Side-effects after a run (broadcasting, analytics, model writes) live in the `useAction` handler that awaited the call, next to the rest of the flow:
327
304
 
328
305
  ```ts
329
- export const user = Resource(() => ky.get("/api/user").json<User>());
306
+ export const user = Resource(({ controller }) =>
307
+ ky.get("/api/user", { signal: controller.signal }).json<User>(),
308
+ );
330
309
 
331
310
  actions.useAction(Actions.Mount, async (context) => {
332
- const data = await get.user();
311
+ const data = await context.actions.resource(user());
333
312
  await context.actions.dispatch(Actions.Broadcast.UserUpdated, data);
334
313
  context.actions.produce(({ model }) => void (model.user = data));
335
314
  });
@@ -340,16 +319,18 @@ actions.useAction(Actions.Mount, async (context) => {
340
319
  ```ts
341
320
  type Params = { cursor: string | null };
342
321
 
343
- export const feed = Resource((signal, { cursor }: Params) =>
322
+ export const feed = Resource<Page<Item>, Params>(({ controller, params }) =>
344
323
  http
345
- .get("feed", { searchParams: { cursor: cursor ?? "" }, signal })
324
+ .get("feed", {
325
+ searchParams: { cursor: params.cursor ?? "" },
326
+ signal: controller.signal,
327
+ })
346
328
  .json<Page<Item>>(),
347
329
  );
348
330
 
349
- const get = {
350
- feed: useResource(resource.feed),
351
- };
352
- const page = await get.feed({ cursor: context.model.cursor });
331
+ const page = await context.actions.resource(
332
+ feed({ cursor: context.model.cursor }),
333
+ );
353
334
  ```
354
335
 
355
336
  A complete IntersectionObserver-driven infinite-scroll demo lives at [`src/example/transactions/`](./src/example/transactions/) &ndash; mock paginated API, scroll-triggered `LoadMore`, `pending()` guard, broadcast on success.
@@ -359,7 +340,7 @@ For typed failure routing, wrap the call in `try/catch` and use `instanceof` &nd
359
340
  ```ts
360
341
  actions.useAction(Actions.Mount, async (context) => {
361
342
  try {
362
- const data = await get.user();
343
+ const data = await context.actions.resource(user());
363
344
  context.actions.produce(({ model }) => void (model.user = data));
364
345
  } catch (error) {
365
346
  if (error instanceof RateLimitedError) {
@@ -377,38 +358,42 @@ See the [Resource recipe](./recipes/use-resource.md) for the three-tier error ha
377
358
 
378
359
  ### Persisting resources across reloads
379
360
 
380
- `useResource`'s cache lives in a `WeakMap` that's reset on every page load. To keep the most recent successful payload around between sessions, pair it with `utils.store(...)` &ndash; a synchronous key/value wrapper around any backing store (`localStorage` on web, `MMKV` on React Native, etc.) that traffics in the same `Stored<T>` shape as the Resource cache.
361
+ By default a `Resource`'s cache is in-memory only &ndash; it resets on every page load. To keep the most recent successful payload around between sessions, wire a `Cache` instance to the `Resource` definition. The Cache writes through to its adapter on every successful run and seeds the per-params slot from storage on first read, so call sites stay free of explicit `store.set` / `store.get` ceremony.
381
362
 
382
363
  ```ts
383
- import { utils } from "march-hare";
364
+ // resources.ts
365
+ import { Cache, Resource } from "march-hare";
384
366
 
385
- export const store = utils.store({
367
+ const cache = Cache({
386
368
  get: (key) => localStorage.getItem(key),
387
369
  set: (key, value) => localStorage.setItem(key, value),
388
370
  remove: (key) => localStorage.removeItem(key),
371
+ clear: () => localStorage.clear(),
389
372
  });
390
- ```
391
373
 
392
- `get.cat.else(...)` is overloaded: pass a `Stored<T>` (from `store.get(key)`) and the bound handle seeds its own cache from it when empty &ndash; then chain `.else(null)` for the leaf fallback. `get.cat.snapshot()` produces the symmetric `Stored<T>` for writing back. After this single chain, `.if({ over })` short-circuits on the persisted timestamp on the _first_ mount after a reload, with no second method to call.
374
+ export const cat = Resource(
375
+ async ({ controller }) => fetchCat(controller.signal),
376
+ cache,
377
+ );
378
+ ```
393
379
 
394
380
  ```ts
395
- const get = { cat: useResource(resource.cat) };
381
+ // actions.ts
396
382
  const actions = useActions<Model, typeof Actions>({
397
- // First render reads cache storage → null.
398
- cat: get.cat.else(store.get(Snapshots.Cat)).else(null),
383
+ // First render reads the Cache automatically.
384
+ cat: cat(),
399
385
  });
400
386
 
401
387
  actions.useAction(Actions.Mount, async (context) => {
402
- // Short-circuits when storage held a payload < 5 minutes old.
403
- const fresh = await get.cat.if(
404
- { over: { minutes: 5 } },
405
- context.task.controller.signal,
406
- );
407
- store.set(Snapshots.Cat, get.cat.snapshot());
388
+ // Short-circuits when the persisted payload is < 5 minutes old.
389
+ // The Cache writes through automatically on success.
390
+ const fresh = await context.actions.resource(cat()).exceeds({ minutes: 5 });
408
391
  context.actions.produce(({ model }) => void (model.cat = fresh));
409
392
  });
410
393
  ```
411
394
 
395
+ `Cache()` with no adapter is an in-memory scope &ndash; useful in tests or when you want a holdable cache without persistence. Per-params keying via `JSON.stringify(params)` is automatic, so `user({ id: 5 })` and `user({ id: 6 })` are distinct slots.
396
+
412
397
  See the [storage recipe](./recipes/storage.md) for backend adapters (React Native MMKV, browser extension `chrome.storage`), sign-out purge, and the `unset` sentinel that keeps "nothing stored" distinct from "a legitimately stored null".
413
398
 
414
399
  For targeted event delivery, use channeled actions. Define a channel type as the second generic argument and call the action with a channel object &ndash; handlers fire when the dispatch channel matches:
@@ -481,33 +466,41 @@ Unlike broadcast which reaches all mounted components, multicast is confined to
481
466
 
482
467
  See the [multicast recipe](./recipes/multicast-actions.md) for more details.
483
468
 
484
- For coordinating between async handlers without re-rendering the JSX tree, use the per-`<Boundary>` mode handle returned by `useMode()`. Thread it through the `useActions` data callback so it shows up as `context.data.mode` inside handlers, fully typed. Mode is **not** reactive &mdash; drive view state through the model, not mode.
469
+ For coordinating between async handlers and threading ambient values (session tokens, locale, feature flags, current operational mode) without re-rendering the JSX tree, use the per-`<Boundary>` `Store`. Declare your app's Store shape once via module augmentation, supply the initial value to `<Boundary store={...}>`, read via dot notation (`store.session`, `context.store.locale`), and write via `context.actions.produce(({ store }) => { ... })` &mdash; the same Immer-style recipe used for the model. Every `Resource` fetcher also receives a snapshot of the Store on its args object. Store is **not** reactive &mdash; drive view state through the model.
485
470
 
486
471
  ```ts
487
- import { useActions, useMode } from "march-hare";
488
-
489
- enum Mode {
490
- Idle,
491
- SigningOut,
472
+ import { useActions } from "march-hare";
473
+
474
+ // Declare your Store's shape once. Every read/write is typed against this.
475
+ declare module "march-hare" {
476
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
477
+ interface Store {
478
+ session: Session | null;
479
+ operating: "idle" | "signing-out";
480
+ }
492
481
  }
493
482
 
494
- export function useActions() {
495
- const mode = useMode<Mode>();
496
- // Spell the data shape as the third generic so `context.data.mode` keeps
497
- // its concrete type inside handlers.
498
- const actions = useActions<Model, typeof Actions, { mode: typeof mode }>(
499
- model,
500
- () => ({ mode }),
501
- );
483
+ // Wire the initial Store into Boundary at app root.
484
+ <Boundary store={{ session: null, operating: "idle" }}>
485
+ <App />
486
+ </Boundary>;
487
+
488
+ export function useAuthActions() {
489
+ const actions = useActions<void, typeof Actions>();
502
490
 
503
491
  actions.useAction(Actions.SignOut, async (context) => {
504
- context.data.mode.update(Mode.SigningOut);
492
+ context.actions.produce(({ store }) => {
493
+ store.operating = "signing-out";
494
+ });
505
495
  await api.signOut();
506
- context.data.mode.update(Mode.Idle);
496
+ context.actions.produce(({ store }) => {
497
+ store.session = null;
498
+ store.operating = "idle";
499
+ });
507
500
  });
508
501
 
509
502
  actions.useAction(Actions.Refresh, async (context) => {
510
- if (context.data.mode.read() === Mode.SigningOut) return;
503
+ if (context.store.operating === "signing-out") return;
511
504
  // ...
512
505
  });
513
506
 
@@ -1,6 +1,6 @@
1
- import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o}from"immer";import{jsx as s}from"react/jsx-runtime";import*as a from"react";const c=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{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")}function d(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(e){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),n}const p=Symbol(i("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),e})()}var m=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),y=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(y||{});const b=e=>"symbol"==typeof e;function v(t){return e.isString(t)||b(t)?t:(e.isObject(t)||e.isFunction(t))&&f.Action in t?t[f.Action]:t}function g(t){if(e.isString(t))return t.startsWith(i());if(b(t))return t.description?.startsWith(i())??!1;if(e.isObject(t)||e.isFunction(t)){if(f.Broadcast in t&&t[f.Broadcast])return!0;if(f.Action in t){const e=t[f.Action];return e.description?.startsWith(i())??!1}}return!1}function w(t){const n=v(t),r=e.isString(n)?n:n.description??"";return r.startsWith(c())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function O(t){return e.isObject(t)&&f.Channel in t&&"channel"in t}function S(e){const t=v(e),n=b(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function j(t){if(e.isString(t))return t.startsWith(u());if(b(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(f.Multicast in t&&t[f.Multicast])return!0;if(f.Action in t){const e=t[f.Action];return e.description?.startsWith(u())??!1}}return!1}const P=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(i(e)):t===m.Multicast?Symbol(u(e)):Symbol(c(e)),r=function(e){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),t===m.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===m.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r};var E=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(E||{});class M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class C extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let x=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var k=/* @__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))(k||{}),A=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(A||{}),_=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(_||{});class N{[n]=!0;static keys=new Set(Object.values(_));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new N(this.value,this.operation);return n.property=e,n.process=t,n}}class R{static immer=(()=>{r();const e=new o;return e.setAutoFreeze(!1),e})();static tag="κ";static id=x}function U(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 L(t){if(e.isNullable(t)||F(t))return t;if(e.isArray(t))return t.map(e=>L(e));if(e.isObject(t)&&B(t)){const e=Object.entries(t).map(([e,t])=>[e,L(t)]);return{...Object.fromEntries(e),[R.tag]:t[R.tag]??R.id()}}return t}function T(e){if(Array.isArray(e))return e.filter(e=>R.tag in e).map(e=>e[R.tag]??"").join(",");const t=e[R.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function B(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function F(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function W(t,n,r,o,s,a){return function c(i,u=n.path){if(i instanceof N){const n=U(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!N.keys.has(e)&&t instanceof N).forEach(([e,t])=>c(t,u.concat(e))),F(i.value)){if(t===A.Hydrate)return i.value;const c=u.slice(0,-1),l=c.length>0?U(r,c.join(".")):r;return e.isNullable(l)||$(l,i,u.at(-1),o,s,a),n??i.value}if(t===A.Hydrate){const e=L(c(i.value,u));return $(e,i,null,o,s,a),e}const l=n??L(i.value);return $(l,i,null,o,s,a),e.isNullable(n)?l:(c(i.value,u),n)}if(e.isArray(i))return i.map((e,t)=>c(e,u.concat(t)));if(e.isObject(i)&&!B(i))return i;if(e.isObject(i)){const e=Object.entries(i).map(([e,t])=>[e,c(t,u.concat(e))]),n=Object.fromEntries(e);if(t===A.Hydrate){const e=L(n);return Object.entries(i).forEach(([t,n])=>{n instanceof N&&F(n.value)&&$(e,n,t,o,s,a)}),e}return n}return i}(n.value)}function $(e,t,n,r,o,s){const a=s(e),c=o.get(a)??[];o.set(a,[t.assign(n,r),...c])}class H{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=T){this.#t=e}static pk(){return x()}static"κ"=H.pk;annotate(e,t){return new N(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,a){function c(s){const a=s.at(-1),c=U(n(),s),i=s.slice(0,-1),u=t.isNotEmpty(i)?U(n(),i):n();return[...e.isObject(c)||e.isArray(c)?r.get(o(c))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===a)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!t.isEmpty(c(r)):"remaining"===i?()=>t.length(c(r)):"box"===i?()=>({value:U(n(),r),inspect:e(r)}):"is"===i?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.head(c(r))?.value??U(n(),r):"settled"===i?()=>new Promise(e=>{if(t.isEmpty(c(r)))return e(U(n(),r));const o=()=>{t.isEmpty(c(r))&&(a(o),e(U(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(A.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(A.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=R.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>R.immer.applyPatches(t,[{...r,value:W(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=L(this.#e),this.#a(),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.#a()}#a(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const I=new H;function z(e,t=k.Update){return I.annotate(t,e)}function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var J,G={exports:{}};const V=/* @__PURE__ */D((J||(J=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,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var c=new o(r,s||e,a),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],c]:e._events[i].push(c):(e._events[i]=c,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),c.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},c.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},c.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},c.prototype.emit=function(e,t,r,o,s,a){var c=n?n+e:e;if(!this._events[c])return!1;var i,u,l=this._events[c],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,a),!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},c.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var c=this._events[s];if(c.fn)c.fn!==t||o&&!c.once||r&&c.context!==r||a(this,s);else{for(var i=0,u=[],l=c.length;i<l;i++)(c[i].fn!==t||o&&!c[i].once||r&&c[i].context!==r)&&u.push(c[i]);u.length?this._events[s]=1===u.length?u[0]:u:a(this,s)}return this},c.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&a(this,t):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,e.exports=c}(G)),G.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 K=a.createContext(new q);function Q(){return a.useContext(K)}function X({children:e}){const t=a.useMemo(()=>new q,[]);/* @__PURE__ */
2
- return s(K.Provider,{value:t,children:e})}const Y=a.createContext(/* @__PURE__ */new Set);function Z({children:e}){const t=a.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
- return s(Y.Provider,{value:t,children:e})}const ee=a.createContext({current:null});function te(){const e=a.useContext(ee);return a.useMemo(()=>({read:()=>e.current,update(t){e.current=t}}),[e])}function ne({children:e}){const t=a.useRef(null);/* @__PURE__ */
4
- return s(ee.Provider,{value:t,children:e})}function re({children:e}){/* @__PURE__ */
5
- return s(X,{children:/* @__PURE__ */s(ne,{children:/* @__PURE__ */s(Z,{children:e})})})}const oe=a.createContext(null);function se(){return a.useContext(oe)}function ae(e,t){return e?.get(t)??null}function ce(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=v(e);return{[n](e){const n=se(),o=a.useMemo(()=>({action:r,emitter:new q}),[]),c=a.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
6
- return s(oe.Provider,{value:c,children:/* @__PURE__ */s(t,{...e})})}}[n]}const ie=Symbol(((e="")=>`march-hare/replay${e}`)());function ue(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 le={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 fe(e,t){for(const n of e.keys())if(S(n)===t)return n;return null}const de=/* @__PURE__ */Symbol("march-hare.unset");function pe(){const[,e]=a.useReducer(e=>e+1,0);return e}function he(){return{data:de,at:null,else:e=>e}}function me(e,t){return{data:e,at:t,else:t=>e}}function ye(e){if(e instanceof Error){if("TimeoutError"===e.name)return E.Timedout;if("AbortError"===e.name)return E.Supplanted}return E.Errored}const be=a.createContext(/* @__PURE__ */new Map);function ve({action:t,renderer:n}){const r=Q(),o=a.useContext(be),s=pe(),c=a.useMemo(()=>{const e=o.get(t);if(e)return e;const n={state:new H,listeners:/* @__PURE__ */new Set};return o.set(t,n),n},[t,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 ge(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),s=Q(),c=se(),i=a.useContext(Y),u=pe(),l=a.useRef(!1),f=a.useRef(null),d=a.useRef(new H);l.current||(l.current=!0,f.current=d.current.hydrate(r));const[h,m]=a.useState(()=>d.current.model),b=function(e){const t=a.useRef(e);return a.useLayoutEffect(()=>{t.current=e},[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()),S=a.useMemo(()=>new V,[]),P=a.useRef({handlers:/* @__PURE__ */new Map});P.current.handlers=/* @__PURE__ */new Map;const E=function(){const e=a.useRef(/* @__PURE__ */new Set),t=a.useRef(/* @__PURE__ */new Set);return a.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),M=a.useRef(y.Mounting),C=a.useRef(/* @__PURE__ */new Set),x=a.useRef(0),A=a.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return i.add(o),C.current.add(o),{model:d.current.model,get phase(){return M.current},task:o,data:b,tasks:i,actions:{produce(e){if(r.signal.aborted)return;const t=d.current.produce(t=>{e({model:t,inspect:d.current.inspect})});m(d.current.model),n.processes.add(t),f.current&&(n.processes.add(f.current),f.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=v(e),o=O(e)?e.channel:void 0;if(j(e)){const e=ae(c,n);return e?ue(e.emitter,n,t,o):Promise.resolve()}return ue(g(e)?s:S,n,t,o)},annotate:(e,t=k.Update)=>d.current.annotate(t,e),async resolution(e){if(r.signal.aborted)return null;const t=v(e),n=j(e)?ae(c,t)?.emitter??null:s;if(!n)return null;if(void 0===n.getCached(t))return null;const o=w(e),a="unknown"!==o?o[0].toLowerCase()+o.slice(1):null;if(a){const e=d.current.inspect[a];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=v(e),n=j(e)?ae(c,t)?.emitter??null:s;return n?n.getCached(t)??null:null}}}},[h]);a.useLayoutEffect(()=>{function t(t,n,r){return function(o,a){const c=r();if(a===ie&&e.isNotNullable(c))return;if(e.isNotNullable(a)&&a!==ie&&e.isNotNullable(c)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(a,c))return;const l={processes:/* @__PURE__ */new Set},f=Promise.withResolvers(),h=A(t,o,l);function m(e){const n=fe(P.current.handlers,"Error"),r=null!==n,o={reason:ye(e),error:(a=e,a instanceof Error?a:new Error(String(a))),action:w(t),handled:r,tasks:i};var a;s.fire(p,o),r&&n&&S.emit(n,o)}function y(){for(const e of i)if(e===h.task){i.delete(e),C.current.delete(e);break}l.processes.forEach(e=>d.current.prune(e)),l.processes.size>0&&u(),f.resolve()}let b;try{b=n(h,o)}catch(v){return m(v),void y()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(b))return Promise.resolve(b).catch(m).finally(y),f.promise;(async()=>{for await(const e of b);})().catch(m).finally(y)}}x.current++;const n=/* @__PURE__ */new Set;return P.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:a}of e){const e=t(r,a,o);if(j(r)){if(c)for(const t of c.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}S.on(r,e),E.multicast.add(r),n.add(()=>S.off(r,e))}else g(r)?(s.on(r,e),S.on(r,e),E.broadcast.add(r),n.add(()=>{s.off(r,e),S.off(r,e)})):(S.on(r,e),n.add(()=>S.off(r,e)))}}),()=>{const e=++x.current,t=new Set(n);queueMicrotask(()=>{if(x.current!==e){for(const e of t)e();return}for(const e of C.current)e.controller.abort(),i.delete(e);C.current.clear(),M.current=y.Unmounting;const n=fe(P.current.handlers,"Unmount");n&&S.emit(n),M.current=y.Unmounted;for(const e of t)e()})}},[S]),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===y.Mounted)return;c.current=y.Mounting;const t=fe(u,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,ie)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,ie)}}),c.current=y.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=fe(u,"Update");t&&n.emit(t,e)}}l.current=i},[i,n])}({unicast:S,broadcast:s,dispatchers:E,scope:c,phase:M,data:o(),handlers:P.current.handlers});const _=a.useMemo(()=>[h,{dispatch(e,t){const n=v(e),r=O(e)?e.channel:void 0;if(j(e)){const e=ae(c,n);return e?ue(e.emitter,n,t,r):Promise.resolve()}return ue(g(e)?s:S,n,t,r)},get inspect(){return d.current.inspect},stream:(e,t)=>a.createElement(ve,{action:v(e),renderer:t})}],[h,S]);return _.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(()=>O(o.current)?o.current.channel:void 0,[]),i=v(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})}(P,e,t)},_}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 Se(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}function je(e){return{get(t){try{const n=e.get(t);if(null===n)return he();const r=JSON.parse(n);return me(r.data,Temporal.Instant.from(r.at))}catch{return he()}},set(t,n){if(n.data===de||null===n.at)return!1;try{return e.set(t,JSON.stringify({data:n.data,at:n.at.toString()})),!0}catch{return!1}},remove(t){e.remove(t)},clear(){e.clear()}}}const Pe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Se,poll:Oe,sleep:we,store:je,unset:de,"ζ":we,"κ":Se,"π":Oe,"σ":je},Symbol.toStringTag,{value:"Module"})),Ee=/* @__PURE__ */new WeakMap;function Me(e){return{run:(t,n)=>e(t,n).then(t=>(Ee.set(e,{data:t,at:Temporal.Now.instant()}),t)),get data(){const t=Ee.get(e);return void 0===t?de:t.data},get at(){return Ee.get(e)?.at??null},seed(t,n){Ee.set(e,{data:t,at:n})}}}function Ce(e){return a.useMemo(()=>{const t=(t,n)=>e.run(t??void 0,n??{});return Object.defineProperties(t,{if:{value:(t,n,r)=>{const o=e.data,s=e.at;if(o!==de&&null!==s){const e=Temporal.Now.instant().since(s),n=Temporal.Duration.from(t.over);if(Temporal.Duration.compare(e,n)<=0)return Promise.resolve(o)}return e.run(n??void 0,r??{})},enumerable:!0},else:{value:function(n){if(null!==(r=n)&&"object"==typeof r&&"data"in r&&"at"in r&&"else"in r)return e.data===de&&n.data!==de&&null!==n.at&&e.seed(n.data,n.at),t;var r;const o=e.data;return o===de?n:o},enumerable:!0},snapshot:{value:()=>{const t=e.data,n=e.at;return t===de||null===n?he():me(t,n)},enumerable:!0},data:{get:()=>e.data,enumerable:!0},at:{get:()=>e.at,enumerable:!0}}),t},[e])}export{M as AbortError,P as Action,re as Boundary,m as Distribution,h as Lifecycle,k as Op,k as Operation,E as Reason,Me as Resource,H as State,C as TimeoutError,le as With,z as annotate,ge as useActions,te as useMode,Ce as useResource,Pe as utils,ce as withScope};
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"));class m{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})()}var y=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(y||{}),b=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(b||{});const v=e=>"symbol"==typeof e;function g(t){return e.isString(t)||v(t)?t:(e.isObject(t)||e.isFunction(t))&&d.Action in t?t[d.Action]:t}function w(t){if(e.isString(t))return t.startsWith(u());if(v(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 O(t){const n=g(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 P(e){const t=g(e),n=v(t)?t.description??"":t;return n.startsWith(f())&&n.slice(f().length)||null}function j(t){if(e.isString(t))return t.startsWith(l());if(v(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 E=(e,t=y.Unicast)=>{const n=t===y.Broadcast?Symbol(u(e)):t===y.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===y.Broadcast&&Object.defineProperty(r,d.Broadcast,{value:!0,enumerable:!1}),t===y.Multicast&&Object.defineProperty(r,d.Multicast,{value:!0,enumerable:!1}),r};var x=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(x||{});class M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class C 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||{}),A=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(A||{}),_=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(_||{});class R{[n]=!0;static keys=new Set(Object.values(_));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new R(this.value,this.operation);return n.property=e,n.process=t,n}}class U{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 T(t){if(e.isNullable(t)||W(t))return t;if(e.isArray(t))return t.map(e=>T(e));if(e.isObject(t)&&F(t)){const e=Object.entries(t).map(([e,t])=>[e,T(t)]);return{...Object.fromEntries(e),[U.tag]:t[U.tag]??U.id()}}return t}function B(e){if(Array.isArray(e))return e.filter(e=>U.tag in e).map(e=>e[U.tag]??"").join(",");const t=e[U.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function F(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function W(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function $(t,n,r,o,s,c){return function a(i,u=n.path){if(i instanceof R){const n=L(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>a(t,u.concat(e))),W(i.value)){if(t===A.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?L(r,a.join(".")):r;return e.isNullable(l)||D(l,i,u.at(-1),o,s,c),n??i.value}if(t===A.Hydrate){const e=T(a(i.value,u));return D(e,i,null,o,s,c),e}const l=n??T(i.value);return D(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)&&!F(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===A.Hydrate){const e=T(n);return Object.entries(i).forEach(([t,n])=>{n instanceof R&&W(n.value)&&D(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function D(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class H{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=B){this.#t=e}static pk(){return k()}static"κ"=H.pk;annotate(e,t){return new R(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(A.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(A.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=U.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>U.immer.applyPatches(t,[{...r,value:$(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=T(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 I=new H;function z(e,t=N.Update){return I.annotate(t,e)}function J(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var q,G={exports:{}};const K=/* @__PURE__ */J((q||(q=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}(G)),G.exports));class V extends K{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 Q=a.createContext(new V);function X(){return a.useContext(Q)}function Y({children:e}){const t=a.useMemo(()=>new V,[]);/* @__PURE__ */
2
+ return c(Q.Provider,{value:t,children:e})}const Z=a.createContext(/* @__PURE__ */new Set);function ee({children:e}){const t=a.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return c(Z.Provider,{value:t,children:e})}const te=a.createContext({current:{}});function ne(){const e=a.useContext(te);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 re({initial:e,children:t}){const n=a.useRef(e);/* @__PURE__ */
4
+ return c(te.Provider,{value:n,children:t})}function oe({store:e,children:t}){/* @__PURE__ */
5
+ return c(Y,{children:/* @__PURE__ */c(re,{initial:e??{},children:/* @__PURE__ */c(ee,{children:t})})})}const se=a.createContext(null);function ce(){return a.useContext(se)}function ae(e,t){return e?.get(t)??null}function ie(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=g(e);return{[n](e){const n=ce(),o=a.useMemo(()=>({action:r,emitter:new V}),[]),s=a.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
6
+ return c(se.Provider,{value:s,children:/* @__PURE__ */c(t,{...e})})}}[n]}const ue=Symbol(((e="")=>`march-hare/replay${e}`)());function le(e,t,...n){e instanceof V&&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 fe={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 de(e,t){for(const n of e.keys())if(P(n)===t)return n;return null}const pe=/* @__PURE__ */Symbol("march-hare.unset");function he(){const[,e]=a.useReducer(e=>e+1,0);return e}function me(){return{data:pe,at:null,else:e=>e}}function ye(e,t){return{data:e,at:t,else:t=>e}}function be(e){if(e instanceof Error){if("TimeoutError"===e.name)return x.Timedout;if("AbortError"===e.name)return x.Supplanted}return x.Errored}function ve(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 me();const r=JSON.parse(t);return ye(r.data,Temporal.Instant.from(r.at))}catch{return me()}},set(e,t){if(t.data===pe||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 ge(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 we(e,t,n){if(t?.aborted)throw new M;for(;;){if(await n())return;await ge(e,t)}}function Oe(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:Oe,poll:we,sleep:ge,unset:pe,"ζ":ge,"κ":Oe,"π":we},Symbol.toStringTag,{value:"Module"})),Pe=/* @__PURE__ */new WeakMap;function je(e){return JSON.stringify(e)}let Ee=null;function xe(){if(null===Ee)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=Ee;return Ee=null,e}function Me(e,t){const n=t??function(e){let t=Pe.get(e);return void 0===t&&(t=ve(),Pe.set(e,t)),t}(e),r=e=>{const t=n.get(je(e));return t.data===pe||null===t.at?{data:pe,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(je(o),ye(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(je(e),ye(t,r))};return function(e){const t=e??{};Ee={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==Ee&&Ee.params===t&&(Ee=null)});const{data:n}=r(t);return n===pe?null:n}}const Ce=a.createContext(/* @__PURE__ */new Map);function ke({action:t,renderer:n}){const r=X(),o=a.useContext(Ce),s=he(),c=a.useMemo(()=>{const e=o.get(t);if(e)return e;const n={state:new H,listeners:/* @__PURE__ */new Set};return o.set(t,n),n},[t,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(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),c=X(),i=ce(),u=a.useContext(Z),l=ne(),f=a.useContext(te),d=he(),p=a.useRef(!1),m=a.useRef(null),y=a.useRef(new H);p.current||(p.current=!0,m.current=y.current.hydrate(r));const[v,P]=a.useState(()=>y.current.model),E=function(e){const t=a.useRef(e);return a.useLayoutEffect(()=>{t.current=e},[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()),x=a.useMemo(()=>new K,[]),M=a.useRef({handlers:/* @__PURE__ */new Map});M.current.handlers=/* @__PURE__ */new Map;const C=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(b.Mounting),A=a.useRef(/* @__PURE__ */new Set),_=a.useRef(0),R=a.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),A.current.add(o),{model:y.current.model,get phase(){return k.current},task:o,data:E,tasks:u,store:l,actions:{produce(e){if(r.signal.aborted)return;const t=y.current.produce(t=>{f.current=s(f.current,n=>{e({model:t,inspect:y.current.inspect,store:n})})});P(y.current.model),n.processes.add(t),m.current&&(n.processes.add(m.current),m.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=g(e),o=S(e)?e.channel:void 0;if(j(e)){const e=ae(i,n);return e?le(e.emitter,n,t,o):Promise.resolve()}return le(w(e)?c:x,n,t,o)},annotate:(e,t=N.Update)=>y.current.annotate(t,e),resource:Object.assign(function(e){const t=xe(),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!==pe&&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=xe();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(r.signal.aborted)return null;const t=g(e),n=j(e)?ae(i,t)?.emitter??null:c;if(!n)return null;if(void 0===n.getCached(t))return null;const o=O(e),s="unknown"!==o?o[0].toLowerCase()+o.slice(1):null;if(s){const e=y.current.inspect[s];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=g(e),n=j(e)?ae(i,t)?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[v]);a.useLayoutEffect(()=>{function t(t,n,r){return function(o,s){const a=r();if(s===ue&&e.isNotNullable(a))return;if(e.isNotNullable(s)&&s!==ue&&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=R(t,o,i);function p(e){const n=de(M.current.handlers,"Error"),r=null!==n,o={reason:be(e),error:(s=e,s instanceof Error?s:new Error(String(s))),action:O(t),handled:r,tasks:u};var s;c.fire(h,o),r&&n&&x.emit(n,o)}function m(){for(const e of u)if(e===f.task){u.delete(e),A.current.delete(e);break}i.processes.forEach(e=>y.current.prune(e)),i.processes.size>0&&d(),l.resolve()}let b;try{b=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}(b))return Promise.resolve(b).catch(p).finally(m),l.promise;(async()=>{for await(const e of b);})().catch(p).finally(m)}}_.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(j(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}x.on(r,e),C.multicast.add(r),n.add(()=>x.off(r,e))}else w(r)?(c.on(r,e),x.on(r,e),C.broadcast.add(r),n.add(()=>{c.off(r,e),x.off(r,e)})):(x.on(r,e),n.add(()=>x.off(r,e)))}}),()=>{const e=++_.current,t=new Set(n);queueMicrotask(()=>{if(_.current!==e){for(const e of t)e();return}for(const e of A.current)e.controller.abort(),u.delete(e);A.current.clear(),k.current=b.Unmounting;const n=de(M.current.handlers,"Unmount");n&&x.emit(n),k.current=b.Unmounted;for(const e of t)e()})}},[x]),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===b.Mounted)return;c.current=b.Mounting;const t=de(u,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,ue)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,ue)}}),c.current=b.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=de(u,"Update");t&&n.emit(t,e)}}l.current=i},[i,n])}({unicast:x,broadcast:c,dispatchers:C,scope:i,phase:k,data:o(),handlers:M.current.handlers});const U=a.useMemo(()=>[v,{dispatch(e,t){const n=g(e),r=S(e)?e.channel:void 0;if(j(e)){const e=ae(i,n);return e?le(e.emitter,n,t,r):Promise.resolve()}return le(w(e)?c:x,n,t,r)},get inspect(){return y.current.inspect},stream:(e,t)=>a.createElement(ke,{action:g(e),renderer:t})}],[v,x]);return U.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=g(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)},U}export{M as AbortError,E as Action,oe as Boundary,ve as Cache,y as Distribution,m as Lifecycle,N as Op,N as Operation,x as Reason,Me as Resource,H as State,C as TimeoutError,fe as With,z as annotate,Ne as useActions,ne as useStore,Se as utils,ie as withScope};
@@ -1 +1 @@
1
- var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const a=s(o),c=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel")}function d(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),n=function(e){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),n}const p=Symbol(i("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),e})()}var m=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),b=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(b||{});const y=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||y(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(i());if(y(e))return e.description?.startsWith(i())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Broadcast in e&&e[f.Broadcast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(i())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(c())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function O(e){const t=v(e),n=y(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function S(e){if(t.G.isString(e))return e.startsWith(u());if(y(e))return e.description?.startsWith(u())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Multicast in e&&e[f.Multicast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(u())??!1}}return!1}var P=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(P||{});class x extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class E extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let M=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var A=(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))(A||{}),C=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(C||{}),G=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(G||{});class k{[n.immerable]=!0;static keys=new Set(Object.values(G));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new k(this.value,this.operation);return n.property=e,n.process=t,n}}class _{static immer=(()=>{n.enablePatches();const e=new n.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=M}function R(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 N(e){if(t.G.isNullable(e)||L(e))return e;if(t.G.isArray(e))return e.map(e=>N(e));if(t.G.isObject(e)&&T(e)){const t=Object.entries(e).map(([e,t])=>[e,N(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function U(e){if(Array.isArray(e))return e.filter(e=>_.tag in e).map(e=>e[_.tag]??"").join(",");const t=e[_.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function T(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function L(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function B(e,n,r,o,s,a){return function c(i,u=n.path){if(i instanceof k){const n=R(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!k.keys.has(e)&&t instanceof k).forEach(([e,t])=>c(t,u.concat(e))),L(i.value)){if(e===C.Hydrate)return i.value;const c=u.slice(0,-1),l=c.length>0?R(r,c.join(".")):r;return t.G.isNullable(l)||W(l,i,u.at(-1),o,s,a),n??i.value}if(e===C.Hydrate){const e=N(c(i.value,u));return W(e,i,null,o,s,a),e}const l=n??N(i.value);return W(l,i,null,o,s,a),t.G.isNullable(n)?l:(c(i.value,u),n)}if(t.G.isArray(i))return i.map((e,t)=>c(e,u.concat(t)));if(t.G.isObject(i)&&!T(i))return i;if(t.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,c(t,u.concat(e))]),n=Object.fromEntries(t);if(e===C.Hydrate){const e=N(n);return Object.entries(i).forEach(([t,n])=>{n instanceof k&&L(n.value)&&W(e,n,t,o,s,a)}),e}return n}return i}(n.value)}function W(e,t,n,r,o,s){const a=s(e),c=o.get(a)??[];o.set(a,[t.assign(n,r),...c])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return M()}static"κ"=F.pk;annotate(e,t){return new k(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,s){function a(o){const s=o.at(-1),a=R(e(),o),c=o.slice(0,-1),i=t.A.isNotEmpty(c)?R(e(),c):e();return[...t.G.isObject(a)||t.G.isArray(a)?n.get(r(a))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(i)?n.get(r(i))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(c,i)=>"pending"===i?()=>!t.A.isEmpty(a(r)):"remaining"===i?()=>t.A.length(a(r)):"box"===i?()=>({value:R(e(),r),inspect:n(r)}):"is"===i?e=>a(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.A.head(a(r))?.value??R(e(),r):"settled"===i?()=>new Promise(n=>{if(t.A.isEmpty(a(r)))return n(R(e(),r));const c=()=>{t.A.isEmpty(a(r))&&(s(c),n(R(e(),r)))};o(c)}):n([...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(C.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(C.Produce,e)}#s(e,t){const n=Symbol("process"),[,r]=_.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>_.immer.applyPatches(t,[{...r,value:B(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=N(this.#e),this.#a(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#a()}#a(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const $=new F;function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,z={exports:{}},D=(H||(H=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,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var c=new o(r,s||e,a),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],c]:e._events[i].push(c):(e._events[i]=c,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function c(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),c.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},c.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},c.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},c.prototype.emit=function(e,t,r,o,s,a){var c=n?n+e:e;if(!this._events[c])return!1;var i,u,l=this._events[c],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,a),!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},c.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return a(this,s),this;var c=this._events[s];if(c.fn)c.fn!==t||o&&!c.once||r&&c.context!==r||a(this,s);else{for(var i=0,u=[],l=c.length;i<l;i++)(c[i].fn!==t||o&&!c[i].once||r&&c[i].context!==r)&&u.push(c[i]);u.length?this._events[s]=1===u.length?u[0]:u:a(this,s)}return this},c.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&a(this,t):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=n,c.EventEmitter=c,e.exports=c}(z)),z.exports);const q=I(D);class J extends q{cache=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 V=a.createContext(new J);function K(){return a.useContext(V)}function Q({children:e}){const t=a.useMemo(()=>new J,[]);return r.jsx(V.Provider,{value:t,children:e})}const X=a.createContext(new Set);function Y({children:e}){const t=a.useMemo(()=>new Set,[]);return r.jsx(X.Provider,{value:t,children:e})}const Z=a.createContext({current:null});function ee({children:e}){const t=a.useRef(null);return r.jsx(Z.Provider,{value:t,children:e})}const te=a.createContext(null);function ne(){return a.useContext(te)}function re(e,t){return e?.get(t)??null}const oe=Symbol(((e="")=>`march-hare/replay${e}`)());function se(e,t,...n){e instanceof J&&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 ae(e,t){for(const n of e.keys())if(O(n)===t)return n;return null}const ce=Symbol("march-hare.unset");function ie(){const[,e]=a.useReducer(e=>e+1,0);return e}function ue(){return{data:ce,at:null,else:e=>e}}function le(e,t){return{data:e,at:t,else:t=>e}}function fe(e){if(e instanceof Error){if("TimeoutError"===e.name)return P.Timedout;if("AbortError"===e.name)return P.Supplanted}return P.Errored}const de=a.createContext(new Map);function pe({action:e,renderer:n}){const r=K(),o=a.useContext(de),s=ie(),c=a.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new F,listeners:new Set};return o.set(e,n),n},[e,o]);a.useLayoutEffect(()=>{function t(e){c.state.hydrate({value:e}),c.listeners.forEach(e=>e())}return c.listeners.add(s),r.on(e,t),()=>{c.listeners.delete(s),r.off(e,t)}},[e,r,c]);const i=c.state.model?.value;return t.G.isNullable(i)?null:n(i,c.state.inspect.value)}function he(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new x);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new x)},{once:!0})})}async function me(e,t,n){if(t?.aborted)throw new x;for(;;){if(await n())return;await he(e,t)}}function be(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}function ye(e){return{get(t){try{const n=e.get(t);if(null===n)return ue();const r=JSON.parse(n);return le(r.data,Temporal.Instant.from(r.at))}catch{return ue()}},set(t,n){if(n.data===ce||null===n.at)return!1;try{return e.set(t,JSON.stringify({data:n.data,at:n.at.toString()})),!0}catch{return!1}},remove(t){e.remove(t)},clear(){e.clear()}}}const ve=Object.freeze(Object.defineProperty({__proto__:null,pk:be,poll:me,sleep:he,store:ye,unset:ce,"ζ":he,"κ":be,"π":me,"σ":ye},Symbol.toStringTag,{value:"Module"})),ge=new WeakMap;e.AbortError=x,e.Action=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(i(e)):t===m.Multicast?Symbol(u(e)):Symbol(c(e)),r=function(e){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),t===m.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===m.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return r.jsx(Q,{children:r.jsx(ee,{children:r.jsx(Y,{children:e})})})},e.Distribution=m,e.Lifecycle=h,e.Op=A,e.Operation=A,e.Reason=P,e.Resource=function(e){return{run:(t,n)=>e(t,n).then(t=>(ge.set(e,{data:t,at:Temporal.Now.instant()}),t)),get data(){const t=ge.get(e);return void 0===t?ce:t.data},get at(){return ge.get(e)?.at??null},seed(t,n){ge.set(e,{data:t,at:n})}}},e.State=F,e.TimeoutError=E,e.With={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]})}},e.annotate=function(e,t=A.Update){return $.annotate(t,e)},e.useActions=function(...e){const n=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],r=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),o=K(),s=ne(),c=a.useContext(X),i=ie(),u=a.useRef(!1),l=a.useRef(null),f=a.useRef(new F);u.current||(u.current=!0,l.current=f.current.hydrate(n));const[d,h]=a.useState(()=>f.current.model),m=function(e){const t=a.useRef(e);return a.useLayoutEffect(()=>{t.current=e},[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])}(r()),y=a.useMemo(()=>new q,[]),O=a.useRef({handlers:new Map});O.current.handlers=new Map;const P=function(){const e=a.useRef(new Set),t=a.useRef(new Set);return a.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),x=a.useRef(b.Mounting),E=a.useRef(new Set),M=a.useRef(0),C=a.useCallback((e,t,n)=>{const r=new AbortController,a={controller:r,action:e,payload:t};return c.add(a),E.current.add(a),{model:f.current.model,get phase(){return x.current},task:a,data:m,tasks:c,actions:{produce(e){if(r.signal.aborted)return;const t=f.current.produce(t=>{e({model:t,inspect:f.current.inspect})});h(f.current.model),n.processes.add(t),l.current&&(n.processes.add(l.current),l.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=v(e),a=j(e)?e.channel:void 0;if(S(e)){const e=re(s,n);return e?se(e.emitter,n,t,a):Promise.resolve()}return se(g(e)?o:y,n,t,a)},annotate:(e,t=A.Update)=>f.current.annotate(t,e),async resolution(e){if(r.signal.aborted)return null;const t=v(e),n=S(e)?re(s,t)?.emitter??null:o;if(!n)return null;if(void 0===n.getCached(t))return null;const a=w(e),c="unknown"!==a?a[0].toLowerCase()+a.slice(1):null;if(c){const e=f.current.inspect[c];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=v(e),n=S(e)?re(s,t)?.emitter??null:o;return n?n.getCached(t)??null:null}}}},[d]);a.useLayoutEffect(()=>{function e(e,n,r){return function(s,a){const u=r();if(a===oe&&t.G.isNotNullable(u))return;if(t.G.isNotNullable(a)&&a!==oe&&t.G.isNotNullable(u)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(a,u))return;const l={processes:new Set},d=Promise.withResolvers(),h=C(e,s,l);function m(t){const n=ae(O.current.handlers,"Error"),r=null!==n,s={reason:fe(t),error:(a=t,a instanceof Error?a:new Error(String(a))),action:w(e),handled:r,tasks:c};var a;o.fire(p,s),r&&n&&y.emit(n,s)}function b(){for(const e of c)if(e===h.task){c.delete(e),E.current.delete(e);break}l.processes.forEach(e=>f.current.prune(e)),l.processes.size>0&&i(),d.resolve()}let v;try{v=n(h,s)}catch(g){return m(g),void b()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(v))return Promise.resolve(v).catch(m).finally(b),d.promise;(async()=>{for await(const e of v);})().catch(m).finally(b)}}M.current++;const n=new Set;return O.current.handlers.forEach((t,r)=>{for(const{getChannel:a,handler:c}of t){const t=e(r,c,a);if(S(r)){if(s)for(const e of s.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}y.on(r,t),P.multicast.add(r),n.add(()=>y.off(r,t))}else g(r)?(o.on(r,t),y.on(r,t),P.broadcast.add(r),n.add(()=>{o.off(r,t),y.off(r,t)})):(y.on(r,t),n.add(()=>y.off(r,t)))}}),()=>{const e=++M.current,t=new Set(n);queueMicrotask(()=>{if(M.current!==e){for(const e of t)e();return}for(const e of E.current)e.controller.abort(),c.delete(e);E.current.clear(),x.current=b.Unmounting;const n=ae(O.current.handlers,"Unmount");n&&y.emit(n),x.current=b.Unmounted;for(const e of t)e()})}},[y]),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:c,handlers:i}){const u=a.useRef(null);a.useLayoutEffect(()=>{if(s.current===b.Mounted)return;s.current=b.Mounting;const a=ae(i,"Mount");a&&e.emit(a),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o,oe)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o,oe)}}),s.current=b.Mounted},[]),a.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,c);if(t.A.isNotEmpty(Object.keys(n))){const t=ae(i,"Update");t&&e.emit(t,n)}}u.current=c},[c,e])}({unicast:y,broadcast:o,dispatchers:P,scope:s,phase:x,data:r(),handlers:O.current.handlers});const G=a.useMemo(()=>[d,{dispatch(e,t){const n=v(e),r=j(e)?e.channel:void 0;if(S(e)){const e=re(s,n);return e?se(e.emitter,n,t,r):Promise.resolve()}return se(g(e)?o:y,n,t,r)},get inspect(){return f.current.inspect},stream:(e,t)=>a.createElement(pe,{action:v(e),renderer:t})}],[d,y]);return G.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(()=>j(o.current)?o.current.channel:void 0,[]),i=v(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:c,handler:s})}(O,e,t)},G},e.useMode=function(){const e=a.useContext(Z);return a.useMemo(()=>({read:()=>e.current,update(t){e.current=t}}),[e])},e.useResource=function(e){return a.useMemo(()=>{const t=(t,n)=>e.run(t??void 0,n??{});return Object.defineProperties(t,{if:{value:(t,n,r)=>{const o=e.data,s=e.at;if(o!==ce&&null!==s){const e=Temporal.Now.instant().since(s),n=Temporal.Duration.from(t.over);if(Temporal.Duration.compare(e,n)<=0)return Promise.resolve(o)}return e.run(n??void 0,r??{})},enumerable:!0},else:{value:function(n){if(null!==(r=n)&&"object"==typeof r&&"data"in r&&"at"in r&&"else"in r)return e.data===ce&&n.data!==ce&&null!==n.at&&e.seed(n.data,n.at),t;var r;const o=e.data;return o===ce?n:o},enumerable:!0},snapshot:{value:()=>{const t=e.data,n=e.at;return t===ce||null===n?ue():le(t,n)},enumerable:!0},data:{get:()=>e.data,enumerable:!0},at:{get:()=>e.at,enumerable:!0}}),t},[e])},e.utils=ve,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,o=v(e);return{[n](e){const n=ne(),s=a.useMemo(()=>({action:o,emitter:new J}),[]),c=a.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,s]);return r.jsx(te.Provider,{value:c,children:r.jsx(t,{...e})})}}[n]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("immer"),require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","immer","react/jsx-runtime","react"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).MarchHare={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
1
+ var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=s(o),a=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel");static Name=Symbol("march-hare.brand/Name")}function d(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:n,[f.Name]:e,channel:n}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,f.Name,{value:e,enumerable:!1}),n}const p=Symbol(i("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,f.Name,{value:"Fault",enumerable:!1}),e})()}var m=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),b=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(b||{});const y=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||y(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(i());if(y(e))return e.description?.startsWith(i())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Broadcast in e&&e[f.Broadcast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(i())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(a())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function O(e){const t=v(e),n=y(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function S(e){if(t.G.isString(e))return e.startsWith(u());if(y(e))return e.description?.startsWith(u())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Multicast in e&&e[f.Multicast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(u())??!1}}return!1}var x=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(x||{});class P extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class E extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let M=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var A=(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))(A||{}),C=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(C||{}),G=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(G||{});class k{[n.immerable]=!0;static keys=new Set(Object.values(G));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new k(this.value,this.operation);return n.property=e,n.process=t,n}}class N{static immer=(()=>{n.enablePatches();const e=new n.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=M}function _(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 R(e){if(t.G.isNullable(e)||L(e))return e;if(t.G.isArray(e))return e.map(e=>R(e));if(t.G.isObject(e)&&U(e)){const t=Object.entries(e).map(([e,t])=>[e,R(t)]);return{...Object.fromEntries(t),[N.tag]:e[N.tag]??N.id()}}return e}function T(e){if(Array.isArray(e))return e.filter(e=>N.tag in e).map(e=>e[N.tag]??"").join(",");const t=e[N.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function U(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function L(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function B(e,n,r,o,s,c){return function a(i,u=n.path){if(i instanceof k){const n=_(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!k.keys.has(e)&&t instanceof k).forEach(([e,t])=>a(t,u.concat(e))),L(i.value)){if(e===C.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?_(r,a.join(".")):r;return t.G.isNullable(l)||F(l,i,u.at(-1),o,s,c),n??i.value}if(e===C.Hydrate){const e=R(a(i.value,u));return F(e,i,null,o,s,c),e}const l=n??R(i.value);return F(l,i,null,o,s,c),t.G.isNullable(n)?l:(a(i.value,u),n)}if(t.G.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(t.G.isObject(i)&&!U(i))return i;if(t.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(t);if(e===C.Hydrate){const e=R(n);return Object.entries(i).forEach(([t,n])=>{n instanceof k&&L(n.value)&&F(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function F(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class W{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=T){this.#t=e}static pk(){return M()}static"κ"=W.pk;annotate(e,t){return new k(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,s){function c(o){const s=o.at(-1),c=_(e(),o),a=o.slice(0,-1),i=t.A.isNotEmpty(a)?_(e(),a):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(i)?n.get(r(i))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(a,i)=>"pending"===i?()=>!t.A.isEmpty(c(r)):"remaining"===i?()=>t.A.length(c(r)):"box"===i?()=>({value:_(e(),r),inspect:n(r)}):"is"===i?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.A.head(c(r))?.value??_(e(),r):"settled"===i?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(_(e(),r));const a=()=>{t.A.isEmpty(c(r))&&(s(a),n(_(e(),r)))};o(a)}):n([...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(C.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(C.Produce,e)}#s(e,t){const n=Symbol("process"),[,r]=N.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>N.immer.applyPatches(t,[{...r,value:B(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=R(this.#e),this.#c(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.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 $=new W;function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var I,H={exports:{}},q=(I||(I=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=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}(H)),H.exports);const z=D(q);class J extends z{cache=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 K=c.createContext(new J);function V(){return c.useContext(K)}function Q({children:e}){const t=c.useMemo(()=>new J,[]);return r.jsx(K.Provider,{value:t,children:e})}const X=c.createContext(new Set);function Y({children:e}){const t=c.useMemo(()=>new Set,[]);return r.jsx(X.Provider,{value:t,children:e})}const Z=c.createContext({current:{}});function ee(){const e=c.useContext(Z);return c.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 te({initial:e,children:t}){const n=c.useRef(e);return r.jsx(Z.Provider,{value:n,children:t})}const ne=c.createContext(null);function re(){return c.useContext(ne)}function oe(e,t){return e?.get(t)??null}const se=Symbol(((e="")=>`march-hare/replay${e}`)());function ce(e,t,...n){e instanceof J&&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 ae(e,t){for(const n of e.keys())if(O(n)===t)return n;return null}const ie=Symbol("march-hare.unset");function ue(){const[,e]=c.useReducer(e=>e+1,0);return e}function le(){return{data:ie,at:null,else:e=>e}}function fe(e,t){return{data:e,at:t,else:t=>e}}function de(e){if(e instanceof Error){if("TimeoutError"===e.name)return x.Timedout;if("AbortError"===e.name)return x.Supplanted}return x.Errored}function pe(e){const t=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 le();const r=JSON.parse(t);return fe(r.data,Temporal.Instant.from(r.at))}catch{return le()}},set(e,t){if(t.data===ie||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 he(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new P);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new P)},{once:!0})})}async function me(e,t,n){if(t?.aborted)throw new P;for(;;){if(await n())return;await he(e,t)}}function be(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const ye=Object.freeze(Object.defineProperty({__proto__:null,pk:be,poll:me,sleep:he,unset:ie,"ζ":he,"κ":be,"π":me},Symbol.toStringTag,{value:"Module"})),ve=new WeakMap;function ge(e){return JSON.stringify(e)}let we=null;function je(){if(null===we)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=we;return we=null,e}const Oe=c.createContext(new Map);function Se({action:e,renderer:n}){const r=V(),o=c.useContext(Oe),s=ue(),a=c.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new W,listeners:new Set};return o.set(e,n),n},[e,o]);c.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(s),r.on(e,t),()=>{a.listeners.delete(s),r.off(e,t)}},[e,r,a]);const i=a.state.model?.value;return t.G.isNullable(i)?null:n(i,a.state.inspect.value)}e.AbortError=P,e.Action=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(i(e)):t===m.Multicast?Symbol(u(e)):Symbol(a(e)),r=function(t){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:t,[f.Name]:e,channel:t}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,f.Name,{value:e,enumerable:!1}),t===m.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===m.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({store:e,children:t}){return r.jsx(Q,{children:r.jsx(te,{initial:e??{},children:r.jsx(Y,{children:t})})})},e.Cache=pe,e.Distribution=m,e.Lifecycle=h,e.Op=A,e.Operation=A,e.Reason=x,e.Resource=function(e,t){const n=t??function(e){let t=ve.get(e);return void 0===t&&(t=pe(),ve.set(e,t)),t}(e),r=e=>{const t=n.get(ge(e));return t.data===ie||null===t.at?{data:ie,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(ge(o),fe(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(ge(e),fe(t,r))};return function(e){const t=e??{};we={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==we&&we.params===t&&(we=null)});const{data:n}=r(t);return n===ie?null:n}},e.State=W,e.TimeoutError=E,e.With={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]})}},e.annotate=function(e,t=A.Update){return $.annotate(t,e)},e.useActions=function(...e){const r=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],o=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),s=V(),a=re(),i=c.useContext(X),u=ee(),l=c.useContext(Z),f=ue(),d=c.useRef(!1),h=c.useRef(null),m=c.useRef(new W);d.current||(d.current=!0,h.current=m.current.hydrate(r));const[y,O]=c.useState(()=>m.current.model),x=function(e){const t=c.useRef(e);return c.useLayoutEffect(()=>{t.current=e},[e]),c.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()),P=c.useMemo(()=>new z,[]),E=c.useRef({handlers:new Map});E.current.handlers=new Map;const M=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),C=c.useRef(b.Mounting),G=c.useRef(new Set),k=c.useRef(0),N=c.useCallback((e,t,r)=>{const o=new AbortController,c={controller:o,action:e,payload:t};return i.add(c),G.current.add(c),{model:m.current.model,get phase(){return C.current},task:c,data:x,tasks:i,store:u,actions:{produce(e){if(o.signal.aborted)return;const t=m.current.produce(t=>{l.current=n.produce(l.current,n=>{e({model:t,inspect:m.current.inspect,store:n})})});O(m.current.model),r.processes.add(t),h.current&&(r.processes.add(h.current),h.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=v(e),r=j(e)?e.channel:void 0;if(S(e)){const e=oe(a,n);return e?ce(e.emitter,n,t,r):Promise.resolve()}return ce(g(e)?s:P,n,t,r)},annotate:(e,t=A.Update)=>m.current.annotate(t,e),resource:Object.assign(function(e){const t=je(),n=()=>t.run(l.current,o,t.params);return{then:(e,t)=>n().then(e,t),exceeds:e=>{const{data:r,at:o}=t.read(t.params);if(r!==ie&&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=je();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(o.signal.aborted)return null;const t=v(e),n=S(e)?oe(a,t)?.emitter??null:s;if(!n)return null;if(void 0===n.getCached(t))return null;const r=w(e),c="unknown"!==r?r[0].toLowerCase()+r.slice(1):null;if(c){const e=m.current.inspect[c];e?.pending?.()&&await new Promise((t,n)=>{if(o.signal.aborted)return void n(o.signal.reason);const r=()=>n(o.signal.reason);o.signal.addEventListener("abort",r,{once:!0}),e.settled().then(()=>{o.signal.removeEventListener("abort",r),t()})})}return n.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=v(e),n=S(e)?oe(a,t)?.emitter??null:s;return n?n.getCached(t)??null:null}}}},[y]);c.useLayoutEffect(()=>{function e(e,n,r){return function(o,c){const a=r();if(c===se&&t.G.isNotNullable(a))return;if(t.G.isNotNullable(c)&&c!==se&&t.G.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,a))return;const u={processes:new Set},l=Promise.withResolvers(),d=N(e,o,u);function h(t){const n=ae(E.current.handlers,"Error"),r=null!==n,o={reason:de(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:w(e),handled:r,tasks:i};var c;s.fire(p,o),r&&n&&P.emit(n,o)}function b(){for(const e of i)if(e===d.task){i.delete(e),G.current.delete(e);break}u.processes.forEach(e=>m.current.prune(e)),u.processes.size>0&&f(),l.resolve()}let y;try{y=n(d,o)}catch(v){return h(v),void b()}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(h).finally(b),l.promise;(async()=>{for await(const e of y);})().catch(h).finally(b)}}k.current++;const n=new Set;return E.current.handlers.forEach((t,r)=>{for(const{getChannel:o,handler:c}of t){const t=e(r,c,o);if(S(r)){if(a)for(const e of a.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}P.on(r,t),M.multicast.add(r),n.add(()=>P.off(r,t))}else g(r)?(s.on(r,t),P.on(r,t),M.broadcast.add(r),n.add(()=>{s.off(r,t),P.off(r,t)})):(P.on(r,t),n.add(()=>P.off(r,t)))}}),()=>{const e=++k.current,t=new Set(n);queueMicrotask(()=>{if(k.current!==e){for(const e of t)e();return}for(const e of G.current)e.controller.abort(),i.delete(e);G.current.clear(),C.current=b.Unmounting;const n=ae(E.current.handlers,"Unmount");n&&P.emit(n),C.current=b.Unmounted;for(const e of t)e()})}},[P]),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:a,handlers:i}){const u=c.useRef(null);c.useLayoutEffect(()=>{if(s.current===b.Mounted)return;s.current=b.Mounting;const c=ae(i,"Mount");c&&e.emit(c),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o,se)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o,se)}}),s.current=b.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,a);if(t.A.isNotEmpty(Object.keys(n))){const t=ae(i,"Update");t&&e.emit(t,n)}}u.current=a},[a,e])}({unicast:P,broadcast:s,dispatchers:M,scope:a,phase:C,data:o(),handlers:E.current.handlers});const _=c.useMemo(()=>[y,{dispatch(e,t){const n=v(e),r=j(e)?e.channel:void 0;if(S(e)){const e=oe(a,n);return e?ce(e.emitter,n,t,r):Promise.resolve()}return ce(g(e)?s:P,n,t,r)},get inspect(){return m.current.inspect},stream:(e,t)=>c.createElement(Se,{action:v(e),renderer:t})}],[y,P]);return _.useAction=(e,t)=>{!function(e,t,n){const r=c.useRef(n);c.useLayoutEffect(()=>{r.current=n});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>r.current(e,t),[]),a=c.useCallback(()=>j(o.current)?o.current.channel:void 0,[]),i=v(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:s})}(E,e,t)},_},e.useStore=ee,e.utils=ye,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,o=v(e);return{[n](e){const n=re(),s=c.useMemo(()=>({action:o,emitter:new J}),[]),a=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,s]);return r.jsx(ne.Provider,{value:a,children:r.jsx(t,{...e})})}}[n]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("immer"),require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","immer","react/jsx-runtime","react"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).MarchHare={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);