chizu 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +61 -58
  2. package/dist/chizu.js +6 -6
  3. package/dist/chizu.umd.cjs +1 -1
  4. package/dist/{action → src/library/action}/utils.d.ts +3 -3
  5. package/dist/src/library/boundary/components/mode/index.d.ts +15 -0
  6. package/dist/src/library/boundary/components/mode/types.d.ts +7 -0
  7. package/dist/src/library/boundary/components/mode/utils.d.ts +55 -0
  8. package/dist/src/library/boundary/components/scope/index.d.ts +40 -0
  9. package/dist/src/library/boundary/components/scope/types.d.ts +20 -0
  10. package/dist/{boundary → src/library/boundary}/components/scope/utils.d.ts +3 -6
  11. package/dist/{boundary → src/library/boundary}/index.d.ts +1 -1
  12. package/dist/src/library/error/index.d.ts +2 -0
  13. package/dist/{error → src/library/error}/types.d.ts +1 -18
  14. package/dist/{hooks → src/library/hooks}/index.d.ts +2 -2
  15. package/dist/{hooks → src/library/hooks}/types.d.ts +1 -17
  16. package/dist/{hooks → src/library/hooks}/utils.d.ts +25 -25
  17. package/dist/{index.d.ts → src/library/index.d.ts} +5 -5
  18. package/dist/{types → src/library/types}/index.d.ts +57 -325
  19. package/package.json +5 -2
  20. package/dist/boundary/components/regulators/index.d.ts +0 -14
  21. package/dist/boundary/components/regulators/types.d.ts +0 -52
  22. package/dist/boundary/components/regulators/utils.d.ts +0 -21
  23. package/dist/boundary/components/scope/index.d.ts +0 -83
  24. package/dist/boundary/components/scope/types.d.ts +0 -29
  25. package/dist/error/index.d.ts +0 -2
  26. /package/dist/{action → src/library/action}/index.d.ts +0 -0
  27. /package/dist/{annotate → src/library/annotate}/index.d.ts +0 -0
  28. /package/dist/{boundary → src/library/boundary}/components/broadcast/index.d.ts +0 -0
  29. /package/dist/{boundary → src/library/boundary}/components/broadcast/types.d.ts +0 -0
  30. /package/dist/{boundary → src/library/boundary}/components/broadcast/utils.d.ts +0 -0
  31. /package/dist/{boundary → src/library/boundary}/components/consumer/components/partition/index.d.ts +0 -0
  32. /package/dist/{boundary → src/library/boundary}/components/consumer/components/partition/types.d.ts +0 -0
  33. /package/dist/{boundary → src/library/boundary}/components/consumer/index.d.ts +0 -0
  34. /package/dist/{boundary → src/library/boundary}/components/consumer/types.d.ts +0 -0
  35. /package/dist/{boundary → src/library/boundary}/components/consumer/utils.d.ts +0 -0
  36. /package/dist/{boundary → src/library/boundary}/components/tasks/index.d.ts +0 -0
  37. /package/dist/{boundary → src/library/boundary}/components/tasks/types.d.ts +0 -0
  38. /package/dist/{boundary → src/library/boundary}/components/tasks/utils.d.ts +0 -0
  39. /package/dist/{boundary → src/library/boundary}/types.d.ts +0 -0
  40. /package/dist/{error → src/library/error}/utils.d.ts +0 -0
  41. /package/dist/{resource → src/library/resource}/index.d.ts +0 -0
  42. /package/dist/{utils → src/library/utils}/index.d.ts +0 -0
  43. /package/dist/{utils → src/library/utils}/utils.d.ts +0 -0
  44. /package/dist/{utils.d.ts → src/library/utils.d.ts} +0 -0
package/README.md CHANGED
@@ -36,7 +36,7 @@ For advanced topics, see the [recipes directory](./recipes/).
36
36
 
37
37
  ## Getting started
38
38
 
39
- We dispatch the `Actions.Name` event upon clicking the "Sign in" button and within `useNameActions` we subscribe to that same event so that when it's triggered it updates the model with the payload – in the React component we render `model.name`. The `With` helper binds the action's payload directly to a model property.
39
+ We dispatch the `Actions.Name` event upon clicking the "Sign in" button and within `useNameActions` we subscribe to that same event so that when it's triggered it updates the model with the payload – in the React component we render `model.name`. The `With.Update` helper binds the action's payload directly to a model property.
40
40
 
41
41
  ```tsx
42
42
  import { useActions, Action, With } from "chizu";
@@ -56,7 +56,7 @@ export class Actions {
56
56
  export default function useNameActions() {
57
57
  const actions = useActions<Model, typeof Actions>(model);
58
58
 
59
- actions.useAction(Actions.Name, With("name"));
59
+ actions.useAction(Actions.Name, With.Update("name"));
60
60
 
61
61
  return actions;
62
62
  }
@@ -357,100 +357,103 @@ actions.dispatch(Actions.UserUpdated, user);
357
357
 
358
358
  Channel values support non-nullable primitives: `string`, `number`, `boolean`, or `symbol`. By convention, use uppercase keys like `{UserId: 4}` to distinguish channel keys from payload properties.
359
359
 
360
- For scoped communication between component groups, use multicast actions with the `<Scope>` component. The scope name lives as a `static Scope` literal on the same class as the multicast actions &ndash; passing the class as a carrier prevents typos and keeps a single source of truth:
360
+ For scoped communication between component groups, use multicast actions with the `withScope` HOC. Each multicast action defines its own scope &ndash; pass the same action to `withScope` and to `dispatch`, no separate scope name required:
361
361
 
362
362
  ```tsx
363
- import { Action, Distribution, Scope } from "chizu";
363
+ import { Action, Distribution, withScope } from "chizu";
364
364
 
365
- // Scope name and multicast actions live on the same class
366
- class MulticastActions {
367
- static Scope = "scoreboard" as const;
365
+ // Group multicast actions on a class named `Scope`.
366
+ class Scope {
368
367
  static Update = Action<number>("Update", Distribution.Multicast);
369
368
  }
370
369
 
371
- // Component-level actions reference the shared multicast
372
370
  class Actions {
373
- static Multicast = MulticastActions;
374
371
  static Increment = Action("Increment");
375
372
  }
376
373
 
377
- function App() {
374
+ function ScoreArea() {
378
375
  return (
379
- <Scope of={MulticastActions}>
376
+ <>
380
377
  <ScoreBoard />
381
378
  <PlayerList />
382
- </Scope>
379
+ </>
383
380
  );
384
381
  }
385
382
 
386
- // Dispatch to every component inside the scope
387
- actions.dispatch(Actions.Multicast.Update, 42, { scope: Actions.Multicast });
383
+ // Wrap the subtree where the scope applies.
384
+ export default withScope(Scope.Update, ScoreArea);
385
+
386
+ // Dispatch to every component inside the scope.
387
+ actions.dispatch(Scope.Update, 42);
388
388
  ```
389
389
 
390
- Unlike broadcast which reaches all components, multicast is scoped to the named boundary &ndash; perfect for isolated widget groups, form sections, or distinct UI regions. Like broadcast, multicast caches dispatched values per scope &ndash; components that mount later automatically receive the cached value. See the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) if you also fetch data in `Lifecycle.Mount()`.
390
+ Unlike broadcast which reaches all mounted components, multicast is confined to the wrapped subtree &ndash; perfect for isolated widget groups, form sections, or distinct UI regions. Like broadcast, multicast caches dispatched values per scope &ndash; components that mount later automatically receive the cached value. See the [mount deduplication recipe](./recipes/mount-broadcast-deduplication.md) if you also fetch data in `Lifecycle.Mount()`.
391
391
 
392
- For components that always render inside a scope, use the `withScope` HOC to eliminate the manual `<Scope>` wrapper:
392
+ See the [multicast recipe](./recipes/multicast-actions.md) for more details.
393
393
 
394
- ```tsx
395
- import { withScope } from "chizu";
396
- import { MulticastActions } from "./types";
394
+ 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.
397
395
 
398
- export default withScope(MulticastActions, function Layout(): ReactElement {
399
- return (
400
- <div>
401
- <PaymentLink />
402
- <Outlet />
403
- </div>
396
+ ```ts
397
+ import { useMode, useActions } from "chizu";
398
+
399
+ enum Mode {
400
+ Idle,
401
+ SigningOut,
402
+ }
403
+
404
+ function useSignOutActions() {
405
+ const mode = useMode<Mode>();
406
+ // Spell the data shape as the third generic so `context.data.mode` keeps
407
+ // its concrete type inside handlers.
408
+ const actions = useActions<Model, typeof Actions, { mode: typeof mode }>(
409
+ model,
410
+ () => ({ mode }),
404
411
  );
405
- });
406
- ```
407
412
 
408
- See the [multicast recipe](./recipes/multicast-actions.md) for more details.
413
+ actions.useAction(Actions.SignOut, async (context) => {
414
+ context.data.mode.update(Mode.SigningOut);
415
+ await api.signOut();
416
+ context.data.mode.update(Mode.Idle);
417
+ });
409
418
 
410
- The action regulator lets handlers control which actions may be dispatched across all components within a `<Boundary>`. Use `context.regulator` to block or allow actions:
419
+ actions.useAction(Actions.Refresh, async (context) => {
420
+ if (context.data.mode.read() === Mode.SigningOut) return;
421
+ // ...
422
+ });
411
423
 
412
- ```ts
413
- actions.useAction(Actions.Checkout, async (context) => {
414
- // Allow only the cancel action during checkout
415
- context.regulator.allow(Actions.Cancel);
416
-
417
- try {
418
- await processPayment(context.task.controller.signal);
419
- } finally {
420
- context.regulator.allow();
421
- }
422
- });
424
+ return actions;
425
+ }
423
426
  ```
424
427
 
425
- `disallow()` blocks all, `disallow(A, B)` blocks specific actions, `allow()` allows all (reset), and `allow(A, B)` allows only those actions. Each call replaces the previous policy (last-write-wins). Blocked actions fire `Reason.Disallowed` through the error system without allocating resources. See the [action regulator recipe](./recipes/action-regulator.md) for more details.
426
-
427
- Toggling boolean UI state &ndash; modals, sidebars, drawers &ndash; is one of the most common patterns. Instead of defining actions and handlers, use the `actions.features` methods:
428
+ Toggling boolean UI state &ndash; modals, sidebars, drawers &ndash; is one of the most common patterns. Bind a unicast action to a boolean field on the model with `With.Invert`:
428
429
 
429
430
  ```tsx
430
- import { useActions } from "chizu";
431
- import type { Meta } from "chizu";
431
+ import { useActions, Action, With } from "chizu";
432
432
 
433
- type F = {
433
+ type Model = {
434
434
  paymentDialog: boolean;
435
435
  sidebar: boolean;
436
436
  };
437
437
 
438
- type Model = {
439
- name: string;
440
- meta: Meta.Features<F>;
441
- };
438
+ export class Actions {
439
+ static TogglePaymentDialog = Action("TogglePaymentDialog");
440
+ static ToggleSidebar = Action("ToggleSidebar");
441
+ }
442
+
443
+ const [model, actions] = useActions<Model, typeof Actions>({
444
+ paymentDialog: false,
445
+ sidebar: false,
446
+ });
442
447
 
443
- const [model, actions] = useFeatureActions();
448
+ actions.useAction(Actions.TogglePaymentDialog, With.Invert("paymentDialog"));
449
+ actions.useAction(Actions.ToggleSidebar, With.Invert("sidebar"));
444
450
 
445
- // Mutate via actions.features
446
- actions.features.invert("paymentDialog");
447
- actions.features.on("paymentDialog");
448
- actions.features.off("paymentDialog");
451
+ // Dispatch from anywhere with access to the actions object.
452
+ actions.dispatch(Actions.TogglePaymentDialog);
449
453
 
450
- // Read from model
451
454
  {
452
- model.meta.features.paymentDialog && <PaymentDialog />;
455
+ model.paymentDialog && <PaymentDialog />;
453
456
  }
454
457
  ```
455
458
 
456
- The methods also work inside action handlers via `context.actions.features`. See the [feature toggles recipe](./recipes/feature-toggles.md) for more details.
459
+ `With.Invert` only compiles when the named property is a boolean on the model. `With.Update("name")` works the same way for arbitrary fields, and the payload type must match `model[name]`.
package/dist/chizu.js CHANGED
@@ -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 c from"react";const i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel");static Node=/* @__PURE__ */Symbol("chizu.action.lifecycle/Node")}function d(e){const t=/* @__PURE__ */Symbol(`chizu.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(u("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Node(){return d("Node")}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(u());if(b(t))return t.description?.startsWith(u())??!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(u())??!1}}return!1}function w(t){const n=v(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)&&f.Channel in t&&"channel"in t}function E(e){const t=v(e),n=b(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function O(t){if(e.isString(t))return t.startsWith(a());if(b(t))return t.description?.startsWith(a())??!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(a())??!1}}return!1}const j=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(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 P=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(P||{});class M extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class C extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}class x extends Error{name="DisallowedError";constructor(e="Disallowed"){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 A=/* @__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))(A||{}),_=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(_||{}),N=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(N||{});class R{[n]=!0;static keys=new Set(Object.values(N));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 z(t){if(e.isNullable(t)||F(t))return t;if(e.isArray(t))return t.map(e=>z(e));if(e.isObject(t)&&B(t)){const e=Object.entries(t).map(([e,t])=>[e,z(t)]);return{...Object.fromEntries(e),[U.tag]:t[U.tag]??U.id()}}return t}function T(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 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 D(t,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof R){const n=L(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>i(t,a.concat(e))),F(u.value)){if(t===_.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?L(r,i.join(".")):r;return e.isNullable(l)||W(l,u,a.at(-1),o,s,c),n??u.value}if(t===_.Hydrate){const e=z(i(u.value,a));return W(e,u,null,o,s,c),e}const l=n??z(u.value);return W(l,u,null,o,s,c),e.isNullable(n)?l:(i(u.value,a),n)}if(e.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(e.isObject(u)&&!B(u))return u;if(e.isObject(u)){const e=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=z(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&F(n.value)&&W(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function W(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class ${#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=T){this.#t=e}static pk(){return k()}static"κ"=$.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 i(s){const c=s.at(-1),i=L(n(),s),u=s.slice(0,-1),a=t.isNotEmpty(u)?L(n(),u):n();return[...e.isObject(i)||e.isArray(i)?r.get(o(i))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(a)?r.get(o(a))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,u)=>"pending"===u?()=>!t.isEmpty(i(r)):"remaining"===u?()=>t.length(i(r)):"box"===u?()=>({value:L(n(),r),inspect:e(r)}):"is"===u?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.head(i(r))?.value??L(n(),r):"settled"===u?()=>new Promise(e=>{if(t.isEmpty(i(r)))return e(L(n(),r));const o=()=>{t.isEmpty(i(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(u)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(_.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(_.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=U.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>U.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=z(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 H=new $;function I(e,t){return H.annotate(e,t)}function G(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var J,V={exports:{}};const q=/* @__PURE__ */G((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,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),i.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},i.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},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,l=this._events[i],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(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.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 i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.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},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(V)),V.exports));class K extends q{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=c.createContext(new K);function X(){return c.useContext(Q)}function Y({children:e}){const t=c.useMemo(()=>new K,[]);/* @__PURE__ */
2
- return s(Q.Provider,{value:t,children:e})}const Z=c.createContext(/* @__PURE__ */new Set);function ee({children:e}){const t=c.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
- return s(Z.Provider,{value:t,children:e})}const te=c.createContext({mode:"allow-all",actions:/* @__PURE__ */new Set});function ne({children:e}){const t=c.useMemo(()=>({mode:"allow-all",actions:/* @__PURE__ */new Set}),[]);/* @__PURE__ */
4
- return s(te.Provider,{value:t,children:e})}function re({children:e}){/* @__PURE__ */
5
- return s(Y,{children:/* @__PURE__ */s(ne,{children:/* @__PURE__ */s(ee,{children:e})})})}const oe=c.createContext(null);function se(){return c.useContext(oe)}function ce(e,t){return e?.get(t)??null}function ie({of:e,children:t}){const n=se(),r=e.Scope,o=c.useMemo(()=>({name:r,emitter:new K}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,r,o]);/* @__PURE__ */
6
- return s(oe.Provider,{value:i,children:t})}function ue(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`;return{[n]:n=>/* @__PURE__ */s(ie,{of:e,children:/* @__PURE__ */s(t,{...n})})}[n]}const ae=Symbol(((e="")=>`chizu/replay${e}`)());function le(e,t,...n){e instanceof K&&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 fe(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}}function de(e,t){for(const n of e.keys())if(E(n)===t)return n;return null}function pe(){const[,e]=c.useReducer(e=>e+1,0);return e}function he(e){if(e instanceof Error){if("TimeoutError"===e.name)return P.Timedout;if("AbortError"===e.name)return P.Supplanted;if("DisallowedError"===e.name)return P.Disallowed}return P.Errored}const me=c.createContext(/* @__PURE__ */new Map);function ye({action:t,renderer:n}){const r=X(),o=c.useContext(me),s=pe(),i=c.useMemo(()=>{const e=o.get(t);if(e)return e;const n={state:new $,listeners:/* @__PURE__ */new Set};return o.set(t,n),n},[t,o]);c.useLayoutEffect(()=>{function e(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(t,e),()=>{i.listeners.delete(s),r.off(t,e)}},[t,r,i]);const u=i.state.model?.value;return e.isNullable(u)?null:n(u,i.state.inspect.value)}function be(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),s=X(),i=se(),u=c.useContext(Z),a=c.useContext(te),l=pe(),f=c.useRef(!1),d=c.useRef(null),h=c.useRef(new $),m=c.useRef({features:null,nodes:null});function b(){null===m.current.features&&null===m.current.nodes||(h.current.model.meta={...null!==m.current.features?{features:m.current.features}:{},...null!==m.current.nodes?{nodes:m.current.nodes}:{}})}if(!f.current){f.current=!0;const e=r,t=e.meta;t?.features&&(m.current.features=t.features),t?.nodes&&(m.current.nodes=t.nodes);const{meta:n,...o}=e;d.current=h.current.hydrate(o),b()}const[E,j]=c.useState(()=>h.current.model),M=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()),C=c.useMemo(()=>new q,[]),k=c.useRef({handlers:/* @__PURE__ */new Map});k.current.handlers=/* @__PURE__ */new Map;const A=function(){const e=c.useRef(/* @__PURE__ */new Set),t=c.useRef(/* @__PURE__ */new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),_=c.useRef(y.Mounting),N=function(){const e=c.useRef({}),t=c.useRef(/* @__PURE__ */new Map),n=c.useRef(/* @__PURE__ */new Map);return c.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),R=c.useRef(/* @__PURE__ */new Set),U=c.useRef(0),L=c.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),R.current.add(o),{model:h.current.model,get phase(){return _.current},task:o,data:M,tasks:u,get meta(){return{nodes:N.refs.current,features:m.current.features??{}}},regulator:{disallow(...e){if(a.actions.clear(),0===e.length)a.mode="disallow-all";else{a.mode="disallow-matching";for(const t of e)a.actions.add(v(t))}},allow(...e){if(a.actions.clear(),0===e.length)a.mode="allow-all";else{a.mode="allow-matching";for(const t of e)a.actions.add(v(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=h.current.produce(t=>{e({model:t,inspect:h.current.inspect})});b(),j(h.current.model),n.processes.add(t),d.current&&(n.processes.add(d.current),d.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const o=v(e),c=S(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=ce(i,n.scope.Scope);return e?le(e.emitter,o,t,c):Promise.resolve()}return le(g(e)?s:C,o,t,c)},annotate:(e,t)=>h.current.annotate(e,t),features:{on(e){r.signal.aborted||(m.current.features={...m.current.features,[e]:!0},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null))},off(e){r.signal.aborted||(m.current.features={...m.current.features,[e]:!1},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null))},invert(e){if(r.signal.aborted)return;const t=m.current.features?.[e]??!1;m.current.features={...m.current.features,[e]:!t},b(),j(h.current.model),d.current&&(n.processes.add(d.current),d.current=null)}},async resolution(e,t){if(r.signal.aborted)return null;const n=v(e),o=O(e)&&t?.scope?ce(i,t.scope.Scope)?.emitter??null:s;if(!o)return null;if(void 0===o.getCached(n))return null;const c=w(e),u="unknown"!==c?c[0].toLowerCase()+c.slice(1):null;if(u){const e=h.current.inspect[u];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 o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=v(e),o=O(e)&&t?.scope?ce(i,t.scope.Scope)?.emitter??null:s;return o?o.getCached(n)??null:null}}}},[E]);c.useLayoutEffect(()=>{function t(t,n,r){return function(o,c){if(t!==p&&!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(t,a)){const e=de(k.current.handlers,"Error"),n=null!==e,r={reason:P.Disallowed,error:new x,action:w(t),handled:n,tasks:u};return s.fire(p,r),void(n&&e&&C.emit(e,r))}const i=r();if(c===ae&&e.isNotNullable(i))return;if(e.isNotNullable(c)&&c!==ae&&e.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const f={processes:/* @__PURE__ */new Set},d=Promise.withResolvers(),m=L(t,o,f);function y(e){const n=de(k.current.handlers,"Error"),r=null!==n,o={reason:he(e),error:(c=e,c instanceof Error?c:new Error(String(c))),action:w(t),handled:r,tasks:u};var c;s.fire(p,o),r&&n&&C.emit(n,o)}function b(){for(const e of u)if(e===m.task){u.delete(e),R.current.delete(e);break}f.processes.forEach(e=>h.current.prune(e)),f.processes.size>0&&l(),d.resolve()}let v;try{v=n(m,o)}catch(g){return y(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(y).finally(b),d.promise;(async()=>{for await(const e of v);})().catch(y).finally(b)}}U.current++;const n=/* @__PURE__ */new Set;return k.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(O(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}C.on(r,e),A.multicast.add(r),n.add(()=>C.off(r,e))}else g(r)?(s.on(r,e),C.on(r,e),A.broadcast.add(r),n.add(()=>{s.off(r,e),C.off(r,e)})):(C.on(r,e),n.add(()=>C.off(r,e)))}}),()=>{const e=++U.current,t=new Set(n);queueMicrotask(()=>{if(U.current!==e){for(const e of t)e();return}for(const e of R.current)e.controller.abort(),u.delete(e);R.current.clear(),_.current=y.Unmounting;const n=de(k.current.handlers,"Unmount");n&&C.emit(n),_.current=y.Unmounted;for(const e of t)e()})}},[C]),c.useLayoutEffect(()=>{const e=de(k.current.handlers,"Node");let t=!1;for(const[n,r]of N.pending.current)if(N.emitted.current.get(n)!==r){if(N.emitted.current.set(n,r),null!==m.current.nodes){const e={...m.current.nodes};e[n]=r,m.current.nodes=e,t=!0}e&&C.emit(e,r,{Name:n})}t&&(b(),j(h.current.model)),N.pending.current.clear()}),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:i,data:u,handlers:a}){const l=c.useRef(null);c.useLayoutEffect(()=>{if(i.current!==y.Mounting)return;const t=de(a,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,ae)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,ae)}}),i.current=y.Mounted},[]),c.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,u);if(t.isNotEmpty(Object.keys(e))){const t=de(a,"Update");t&&n.emit(t,e)}}l.current=u},[u,n])}({unicast:C,broadcast:s,dispatchers:A,scope:i,phase:_,data:o(),handlers:k.current.handlers});const z=c.useMemo(()=>[E,{dispatch(e,t,n){const r=v(e),o=S(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=ce(i,n.scope.Scope);return e?le(e.emitter,r,t,o):Promise.resolve()}return le(g(e)?s:C,r,t,o)},get inspect(){return h.current.inspect},get meta(){return{nodes:N.refs.current,features:m.current.features??{}}},node(e,t){N.refs.current[e]=t,N.pending.current.set(e,t)},features:{on(e){m.current.features={...m.current.features,[e]:!0},b(),j(h.current.model)},off(e){m.current.features={...m.current.features,[e]:!1},b(),j(h.current.model)},invert(e){const t=m.current.features?.[e]??!1;m.current.features={...m.current.features,[e]:!t},b(),j(h.current.model)}},stream:(e,t)=>c.createElement(ye,{action:v(e),renderer:t})}],[E,C]);return z.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),[]),i=c.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??/* @__PURE__ */new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(k,e,t)},z.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=S(e)?e.channel:void 0;return le(s,v(e),t,n)},[s]);return c.useCallback((...n)=>e.fetch(t,M,...n),[e,t,M])},z}function ve(e,t,n,r){const o=/* @__PURE__ */new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}}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 Se(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Ee=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Se,poll:we,sleep:ge,"ζ":ge,"κ":Se,"π":we},Symbol.toStringTag,{value:"Module"}));export{M as AbortError,j as Action,re as Boundary,x as DisallowedError,m as Distribution,h as Lifecycle,A as Op,A as Operation,P as Reason,ne as Regulators,ve as Resource,ie as Scope,$ as State,C as TimeoutError,fe as With,I as annotate,be as useActions,Ee as utils,ue as withScope};
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 c from"react";const i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{static Payload=/* @__PURE__ */Symbol("chizu.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("chizu.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("chizu.brand/Multicast");static Action=/* @__PURE__ */Symbol("chizu.brand/Action");static Channel=/* @__PURE__ */Symbol("chizu.brand/Channel")}function d(e){const t=/* @__PURE__ */Symbol(`chizu.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(u("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(u());if(b(t))return t.description?.startsWith(u())??!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(u())??!1}}return!1}function w(t){const n=v(t),r=e.isString(n)?n:n.description??"";return r.startsWith(i())&&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 E(t){if(e.isString(t))return t.startsWith(a());if(b(t))return t.description?.startsWith(a())??!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(a())??!1}}return!1}const j=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(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 P=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(P||{});class C extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class M 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 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 N{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)||B(t))return t;if(e.isArray(t))return t.map(e=>L(e));if(e.isObject(t)&&T(t)){const e=Object.entries(t).map(([e,t])=>[e,L(t)]);return{...Object.fromEntries(e),[N.tag]:t[N.tag]??N.id()}}return t}function z(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 T(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function B(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function F(t,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof R){const n=U(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>i(t,a.concat(e))),B(u.value)){if(t===A.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?U(r,i.join(".")):r;return e.isNullable(l)||W(l,u,a.at(-1),o,s,c),n??u.value}if(t===A.Hydrate){const e=L(i(u.value,a));return W(e,u,null,o,s,c),e}const l=n??L(u.value);return W(l,u,null,o,s,c),e.isNullable(n)?l:(i(u.value,a),n)}if(e.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(e.isObject(u)&&!T(u))return u;if(e.isObject(u)){const e=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(e);if(t===A.Hydrate){const e=L(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&B(n.value)&&W(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function W(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class ${#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=z){this.#t=e}static pk(){return x()}static"κ"=$.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 i(s){const c=s.at(-1),i=U(n(),s),u=s.slice(0,-1),a=t.isNotEmpty(u)?U(n(),u):n();return[...e.isObject(i)||e.isArray(i)?r.get(o(i))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(a)?r.get(o(a))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,u)=>"pending"===u?()=>!t.isEmpty(i(r)):"remaining"===u?()=>t.length(i(r)):"box"===u?()=>({value:U(n(),r),inspect:e(r)}):"is"===u?e=>i(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.head(i(r))?.value??U(n(),r):"settled"===u?()=>new Promise(e=>{if(t.isEmpty(i(r)))return e(U(n(),r));const o=()=>{t.isEmpty(i(r))&&(c(o),e(U(n(),r)))};s(o)}):e([...r,String(u)])})}([])}(()=>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]=N.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>N.immer.applyPatches(t,[{...r,value:F(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=L(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 H=new $;function I(e,t){return H.annotate(e,t)}function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var G,J={exports:{}};const V=/* @__PURE__ */D((G||(G=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),i.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},i.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},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,l=this._events[i],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(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.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 i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.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},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(J)),J.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=c.createContext(new q);function Q(){return c.useContext(K)}function X({children:e}){const t=c.useMemo(()=>new q,[]);/* @__PURE__ */
2
+ return s(K.Provider,{value:t,children:e})}const Y=c.createContext(/* @__PURE__ */new Set);function Z({children:e}){const t=c.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return s(Y.Provider,{value:t,children:e})}const ee=c.createContext({current:null});function te(){const e=c.useContext(ee);return c.useMemo(()=>({read:()=>e.current,update(t){e.current=t}}),[e])}function ne({children:e}){const t=c.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=c.createContext(null);function se(){return c.useContext(oe)}function ce(e,t){return e?.get(t)??null}function ie(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=v(e);return{[n](e){const n=se(),o=c.useMemo(()=>({action:r,emitter:new q}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
6
+ return s(oe.Provider,{value:i,children:/* @__PURE__ */s(t,{...e})})}}[n]}const ue=Symbol(((e="")=>`chizu/replay${e}`)());function ae(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}function de(){const[,e]=c.useReducer(e=>e+1,0);return e}function pe(e){if(e instanceof Error){if("TimeoutError"===e.name)return P.Timedout;if("AbortError"===e.name)return P.Supplanted}return P.Errored}const he=c.createContext(/* @__PURE__ */new Map);function me({action:t,renderer:n}){const r=Q(),o=c.useContext(he),s=de(),i=c.useMemo(()=>{const e=o.get(t);if(e)return e;const n={state:new $,listeners:/* @__PURE__ */new Set};return o.set(t,n),n},[t,o]);c.useLayoutEffect(()=>{function e(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(t,e),()=>{i.listeners.delete(s),r.off(t,e)}},[t,r,i]);const u=i.state.model?.value;return e.isNullable(u)?null:n(u,i.state.inspect.value)}function ye(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),s=Q(),i=se(),u=c.useContext(Y),a=de(),l=c.useRef(!1),f=c.useRef(null),d=c.useRef(new $);l.current||(l.current=!0,f.current=d.current.hydrate(r));const[h,m]=c.useState(()=>d.current.model),b=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()),S=c.useMemo(()=>new V,[]),j=c.useRef({handlers:/* @__PURE__ */new Map});j.current.handlers=/* @__PURE__ */new Map;const P=function(){const e=c.useRef(/* @__PURE__ */new Set),t=c.useRef(/* @__PURE__ */new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),C=c.useRef(y.Mounting),M=c.useRef(/* @__PURE__ */new Set),x=c.useRef(0),k=c.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),M.current.add(o),{model:d.current.model,get phase(){return C.current},task:o,data:b,tasks:u,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(E(e)){const e=ce(i,n);return e?ae(e.emitter,n,t,o):Promise.resolve()}return ae(g(e)?s:S,n,t,o)},annotate:(e,t)=>d.current.annotate(e,t),async resolution(e){if(r.signal.aborted)return null;const t=v(e),n=E(e)?ce(i,t)?.emitter??null:s;if(!n)return null;if(void 0===n.getCached(t))return null;const o=w(e),c="unknown"!==o?o[0].toLowerCase()+o.slice(1):null;if(c){const e=d.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=E(e)?ce(i,t)?.emitter??null:s;return n?n.getCached(t)??null:null}}}},[h]);c.useLayoutEffect(()=>{function t(t,n,r){return function(o,c){const i=r();if(c===ue&&e.isNotNullable(i))return;if(e.isNotNullable(c)&&c!==ue&&e.isNotNullable(i)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,i))return;const l={processes:/* @__PURE__ */new Set},f=Promise.withResolvers(),h=k(t,o,l);function m(e){const n=fe(j.current.handlers,"Error"),r=null!==n,o={reason:pe(e),error:(c=e,c instanceof Error?c:new Error(String(c))),action:w(t),handled:r,tasks:u};var c;s.fire(p,o),r&&n&&S.emit(n,o)}function y(){for(const e of u)if(e===h.task){u.delete(e),M.current.delete(e);break}l.processes.forEach(e=>d.current.prune(e)),l.processes.size>0&&a(),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 j.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:c}of e){const e=t(r,c,o);if(E(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}S.on(r,e),P.multicast.add(r),n.add(()=>S.off(r,e))}else g(r)?(s.on(r,e),S.on(r,e),P.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 M.current)e.controller.abort(),u.delete(e);M.current.clear(),C.current=y.Unmounting;const n=fe(j.current.handlers,"Unmount");n&&S.emit(n),C.current=y.Unmounted;for(const e of t)e()})}},[S]),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:i,data:u,handlers:a}){const l=c.useRef(null);c.useLayoutEffect(()=>{if(i.current!==y.Mounting)return;const t=fe(a,"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)}}),i.current=y.Mounted},[]),c.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,u);if(t.isNotEmpty(Object.keys(e))){const t=fe(a,"Update");t&&n.emit(t,e)}}l.current=u},[u,n])}({unicast:S,broadcast:s,dispatchers:P,scope:i,phase:C,data:o(),handlers:j.current.handlers});const A=c.useMemo(()=>[h,{dispatch(e,t){const n=v(e),r=O(e)?e.channel:void 0;if(E(e)){const e=ce(i,n);return e?ae(e.emitter,n,t,r):Promise.resolve()}return ae(g(e)?s:S,n,t,r)},get inspect(){return d.current.inspect},stream:(e,t)=>c.createElement(me,{action:v(e),renderer:t})}],[h,S]);return A.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),[]),i=c.useCallback(()=>O(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??/* @__PURE__ */new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(j,e,t)},A.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=O(e)?e.channel:void 0;return ae(s,v(e),t,n)},[s]);return c.useCallback((...n)=>e.fetch(t,b,...n),[e,t,b])},A}function be(e,t,n,r){const o=/* @__PURE__ */new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}}function ve(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new C);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new C)},{once:!0})})}async function ge(e,t,n){if(t?.aborted)throw new C;for(;;){if(await n())return;await ve(e,t)}}function we(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Oe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:we,poll:ge,sleep:ve,"ζ":ve,"κ":we,"π":ge},Symbol.toStringTag,{value:"Module"}));export{C as AbortError,j as Action,re as Boundary,m as Distribution,h as Lifecycle,k as Op,k as Operation,P as Reason,be as Resource,$ as State,M as TimeoutError,le as With,I as annotate,ye as useActions,te as useMode,Oe 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 c=s(o),i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node")}function d(e){const t=Symbol(`chizu.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(u("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Node(){return d("Node")}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(u());if(y(e))return e.description?.startsWith(u())??!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(u())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=v(e),n=y(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function O(e){if(t.G.isString(e))return e.startsWith(a());if(y(e))return e.description?.startsWith(a())??!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(a())??!1}}return!1}var E=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(E||{});class x extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class P extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}class M extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}let A=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var C=(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))(C||{}),G=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(G||{}),k=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(k||{});class R{[n.immerable]=!0;static keys=new Set(Object.values(k));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 _{static immer=(()=>{n.enablePatches();const e=new n.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=A}function N(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 U(e){if(t.G.isNullable(e)||T(e))return e;if(t.G.isArray(e))return e.map(e=>U(e));if(t.G.isObject(e)&&z(e)){const t=Object.entries(e).map(([e,t])=>[e,U(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function L(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 z(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function T(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 i(u,a=n.path){if(u instanceof R){const n=N(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>i(t,a.concat(e))),T(u.value)){if(e===G.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?N(r,i.join(".")):r;return t.G.isNullable(l)||D(l,u,a.at(-1),o,s,c),n??u.value}if(e===G.Hydrate){const e=U(i(u.value,a));return D(e,u,null,o,s,c),e}const l=n??U(u.value);return D(l,u,null,o,s,c),t.G.isNullable(n)?l:(i(u.value,a),n)}if(t.G.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(t.G.isObject(u)&&!z(u))return u;if(t.G.isObject(u)){const t=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(t);if(e===G.Hydrate){const e=U(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&T(n.value)&&D(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function D(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=L){this.#t=e}static pk(){return A()}static"κ"=F.pk;annotate(e,t){return new R(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=N(e(),o),i=o.slice(0,-1),u=t.A.isNotEmpty(i)?N(e(),i):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(u)?n.get(r(u))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,u)=>"pending"===u?()=>!t.A.isEmpty(c(r)):"remaining"===u?()=>t.A.length(c(r)):"box"===u?()=>({value:N(e(),r),inspect:n(r)}):"is"===u?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.A.head(c(r))?.value??N(e(),r):"settled"===u?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(N(e(),r));const i=()=>{t.A.isEmpty(c(r))&&(s(i),n(N(e(),r)))};o(i)}):n([...r,String(u)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(G.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(G.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=U(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 W=new F;function $(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,I={exports:{}},q=(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,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),i.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},i.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},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,l=this._events[i],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(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.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 i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.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},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(I)),I.exports);const J=$(q);class V extends J{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 V);function Q(){return c.useContext(K)}function X({children:e}){const t=c.useMemo(()=>new V,[]);return r.jsx(K.Provider,{value:t,children:e})}const Y=c.createContext(new Set);function Z({children:e}){const t=c.useMemo(()=>new Set,[]);return r.jsx(Y.Provider,{value:t,children:e})}const ee=c.createContext({mode:"allow-all",actions:new Set});function te({children:e}){const t=c.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return r.jsx(ee.Provider,{value:t,children:e})}const ne=c.createContext(null);function re(){return c.useContext(ne)}function oe(e,t){return e?.get(t)??null}function se({of:e,children:t}){const n=re(),o=e.Scope,s=c.useMemo(()=>({name:o,emitter:new V}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,o,s]);return r.jsx(ne.Provider,{value:i,children:t})}const ce=Symbol(((e="")=>`chizu/replay${e}`)());function ie(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(()=>{})}function ue(e,t){for(const n of e.keys())if(S(n)===t)return n;return null}function ae(){const[,e]=c.useReducer(e=>e+1,0);return e}function le(e){if(e instanceof Error){if("TimeoutError"===e.name)return E.Timedout;if("AbortError"===e.name)return E.Supplanted;if("DisallowedError"===e.name)return E.Disallowed}return E.Errored}const fe=c.createContext(new Map);function de({action:e,renderer:n}){const r=Q(),o=c.useContext(fe),s=ae(),i=c.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]);c.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(e,t),()=>{i.listeners.delete(s),r.off(e,t)}},[e,r,i]);const u=i.state.model?.value;return t.G.isNullable(u)?null:n(u,i.state.inspect.value)}function pe(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 he(e,t,n){if(t?.aborted)throw new x;for(;;){if(await n())return;await pe(e,t)}}function me(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const be=Object.freeze(Object.defineProperty({__proto__:null,pk:me,poll:he,sleep:pe,"ζ":pe,"κ":me,"π":he},Symbol.toStringTag,{value:"Module"}));e.AbortError=x,e.Action=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(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(X,{children:r.jsx(te,{children:r.jsx(Z,{children:e})})})},e.DisallowedError=M,e.Distribution=m,e.Lifecycle=h,e.Op=C,e.Operation=C,e.Reason=E,e.Regulators=te,e.Resource=function(e,t,n,r){const o=new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}},e.Scope=se,e.State=F,e.TimeoutError=P,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return W.annotate(e,t)},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=Q(),s=re(),i=c.useContext(Y),u=c.useContext(ee),a=ae(),l=c.useRef(!1),f=c.useRef(null),d=c.useRef(new F),h=c.useRef({features:null,nodes:null});function m(){null===h.current.features&&null===h.current.nodes||(d.current.model.meta={...null!==h.current.features?{features:h.current.features}:{},...null!==h.current.nodes?{nodes:h.current.nodes}:{}})}if(!l.current){l.current=!0;const e=n,t=e.meta;t?.features&&(h.current.features=t.features),t?.nodes&&(h.current.nodes=t.nodes);const{meta:r,...o}=e;f.current=d.current.hydrate(o),m()}const[y,S]=c.useState(()=>d.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])}(r()),P=c.useMemo(()=>new J,[]),A=c.useRef({handlers:new Map});A.current.handlers=new Map;const C=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),G=c.useRef(b.Mounting),k=function(){const e=c.useRef({}),t=c.useRef(new Map),n=c.useRef(new Map);return c.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),R=c.useRef(new Set),_=c.useRef(0),N=c.useCallback((e,t,n)=>{const r=new AbortController,c={controller:r,action:e,payload:t};return i.add(c),R.current.add(c),{model:d.current.model,get phase(){return G.current},task:c,data:x,tasks:i,get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},regulator:{disallow(...e){if(u.actions.clear(),0===e.length)u.mode="disallow-all";else{u.mode="disallow-matching";for(const t of e)u.actions.add(v(t))}},allow(...e){if(u.actions.clear(),0===e.length)u.mode="allow-all";else{u.mode="allow-matching";for(const t of e)u.actions.add(v(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=d.current.produce(t=>{e({model:t,inspect:d.current.inspect})});m(),S(d.current.model),n.processes.add(t),f.current&&(n.processes.add(f.current),f.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const c=v(e),i=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,c,t,i):Promise.resolve()}return ie(g(e)?o:P,c,t,i)},annotate:(e,t)=>d.current.annotate(e,t),features:{on(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},off(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},invert(e){if(r.signal.aborted)return;const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null)}},async resolution(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;if(!c)return null;if(void 0===c.getCached(n))return null;const i=w(e),u="unknown"!==i?i[0].toLowerCase()+i.slice(1):null;if(u){const e=d.current.inspect[u];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 c.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;return c?c.getCached(n)??null:null}}}},[y]);c.useLayoutEffect(()=>{function e(e,n,r){return function(s,c){if(e!==p&&!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(e,u)){const t=ue(A.current.handlers,"Error"),n=null!==t,r={reason:E.Disallowed,error:new M,action:w(e),handled:n,tasks:i};return o.fire(p,r),void(n&&t&&P.emit(t,r))}const l=r();if(c===ce&&t.G.isNotNullable(l))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(l)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,l))return;const f={processes:new Set},h=Promise.withResolvers(),m=N(e,s,f);function b(t){const n=ue(A.current.handlers,"Error"),r=null!==n,s={reason:le(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:w(e),handled:r,tasks:i};var c;o.fire(p,s),r&&n&&P.emit(n,s)}function y(){for(const e of i)if(e===m.task){i.delete(e),R.current.delete(e);break}f.processes.forEach(e=>d.current.prune(e)),f.processes.size>0&&a(),h.resolve()}let v;try{v=n(m,s)}catch(g){return b(g),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}(v))return Promise.resolve(v).catch(b).finally(y),h.promise;(async()=>{for await(const e of v);})().catch(b).finally(y)}}_.current++;const n=new Set;return A.current.handlers.forEach((t,r)=>{for(const{getChannel:c,handler:i}of t){const t=e(r,i,c);if(O(r)){if(s)for(const e of s.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}P.on(r,t),C.multicast.add(r),n.add(()=>P.off(r,t))}else g(r)?(o.on(r,t),P.on(r,t),C.broadcast.add(r),n.add(()=>{o.off(r,t),P.off(r,t)})):(P.on(r,t),n.add(()=>P.off(r,t)))}}),()=>{const e=++_.current,t=new Set(n);queueMicrotask(()=>{if(_.current!==e){for(const e of t)e();return}for(const e of R.current)e.controller.abort(),i.delete(e);R.current.clear(),G.current=b.Unmounting;const n=ue(A.current.handlers,"Unmount");n&&P.emit(n),G.current=b.Unmounted;for(const e of t)e()})}},[P]),c.useLayoutEffect(()=>{const e=ue(A.current.handlers,"Node");let t=!1;for(const[n,r]of k.pending.current)if(k.emitted.current.get(n)!==r){if(k.emitted.current.set(n,r),null!==h.current.nodes){const e={...h.current.nodes};e[n]=r,h.current.nodes=e,t=!0}e&&P.emit(e,r,{Name:n})}t&&(m(),S(d.current.model)),k.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:i,handlers:u}){const a=c.useRef(null);c.useLayoutEffect(()=>{if(s.current!==b.Mounting)return;const c=ue(u,"Mount");c&&e.emit(c),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o,ce)}),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,ce)}}),s.current=b.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(a.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(a.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=ue(u,"Update");t&&e.emit(t,n)}}a.current=i},[i,e])}({unicast:P,broadcast:o,dispatchers:C,scope:s,phase:G,data:r(),handlers:A.current.handlers});const U=c.useMemo(()=>[y,{dispatch(e,t,n){const r=v(e),c=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,r,t,c):Promise.resolve()}return ie(g(e)?o:P,r,t,c)},get inspect(){return d.current.inspect},get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},node(e,t){k.refs.current[e]=t,k.pending.current.set(e,t)},features:{on(e){h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model)},off(e){h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model)},invert(e){const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model)}},stream:(e,t)=>c.createElement(de,{action:v(e),renderer:t})}],[y,P]);return U.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),[]),i=c.useCallback(()=>j(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(A,e,t)},U.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=j(e)?e.channel:void 0;return ie(o,v(e),t,n)},[o]);return c.useCallback((...n)=>e.fetch(t,x,...n),[e,t,x])},U},e.utils=be,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`;return{[n]:n=>r.jsx(se,{of:e,children:r.jsx(t,{...n})})}[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).Chizu={},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),i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel")}function d(e){const t=Symbol(`chizu.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(u("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(u());if(y(e))return e.description?.startsWith(u())??!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(u())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(i())&&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(a());if(y(e))return e.description?.startsWith(a())??!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(a())??!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 A=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var M=(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))(M||{}),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=A}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)||T(e))return e;if(t.G.isArray(e))return e.map(e=>N(e));if(t.G.isObject(e)&&L(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 L(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function T(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 z(e,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof k){const n=R(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!k.keys.has(e)&&t instanceof k).forEach(([e,t])=>i(t,a.concat(e))),T(u.value)){if(e===C.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?R(r,i.join(".")):r;return t.G.isNullable(l)||B(l,u,a.at(-1),o,s,c),n??u.value}if(e===C.Hydrate){const e=N(i(u.value,a));return B(e,u,null,o,s,c),e}const l=n??N(u.value);return B(l,u,null,o,s,c),t.G.isNullable(n)?l:(i(u.value,a),n)}if(t.G.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(t.G.isObject(u)&&!L(u))return u;if(t.G.isObject(u)){const t=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(t);if(e===C.Hydrate){const e=N(n);return Object.entries(u).forEach(([t,n])=>{n instanceof k&&T(n.value)&&B(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function B(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return A()}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 c(o){const s=o.at(-1),c=R(e(),o),i=o.slice(0,-1),u=t.A.isNotEmpty(i)?R(e(),i):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(u)?n.get(r(u))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,u)=>"pending"===u?()=>!t.A.isEmpty(c(r)):"remaining"===u?()=>t.A.length(c(r)):"box"===u?()=>({value:R(e(),r),inspect:n(r)}):"is"===u?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.A.head(c(r))?.value??R(e(),r):"settled"===u?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(R(e(),r));const i=()=>{t.A.isEmpty(c(r))&&(s(i),n(R(e(),r)))};o(i)}):n([...r,String(u)])})}([])}(()=>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:z(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=N(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 W=new F;function $(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 i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),i.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},i.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},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,l=this._events[i],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(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.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 i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.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},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(H)),H.exports);const D=$(q);class J extends D{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=c.createContext(new J);function K(){return c.useContext(V)}function Q({children:e}){const t=c.useMemo(()=>new J,[]);return r.jsx(V.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:null});function ee({children:e}){const t=c.useRef(null);return r.jsx(Z.Provider,{value:t,children:e})}const te=c.createContext(null);function ne(){return c.useContext(te)}function re(e,t){return e?.get(t)??null}const oe=Symbol(((e="")=>`chizu/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 ce(e,t){for(const n of e.keys())if(O(n)===t)return n;return null}function ie(){const[,e]=c.useReducer(e=>e+1,0);return e}function ue(e){if(e instanceof Error){if("TimeoutError"===e.name)return P.Timedout;if("AbortError"===e.name)return P.Supplanted}return P.Errored}const ae=c.createContext(new Map);function le({action:e,renderer:n}){const r=K(),o=c.useContext(ae),s=ie(),i=c.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]);c.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(e,t),()=>{i.listeners.delete(s),r.off(e,t)}},[e,r,i]);const u=i.state.model?.value;return t.G.isNullable(u)?null:n(u,i.state.inspect.value)}function fe(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 de(e,t,n){if(t?.aborted)throw new x;for(;;){if(await n())return;await fe(e,t)}}function pe(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const he=Object.freeze(Object.defineProperty({__proto__:null,pk:pe,poll:de,sleep:fe,"ζ":fe,"κ":pe,"π":de},Symbol.toStringTag,{value:"Module"}));e.AbortError=x,e.Action=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(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=M,e.Operation=M,e.Reason=P,e.Resource=function(e,t,n,r){const o=new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}},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){return W.annotate(e,t)},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(),i=c.useContext(X),u=ie(),a=c.useRef(!1),l=c.useRef(null),f=c.useRef(new F);a.current||(a.current=!0,l.current=f.current.hydrate(n));const[d,h]=c.useState(()=>f.current.model),m=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])}(r()),y=c.useMemo(()=>new D,[]),O=c.useRef({handlers:new Map});O.current.handlers=new Map;const P=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),x=c.useRef(b.Mounting),E=c.useRef(new Set),A=c.useRef(0),M=c.useCallback((e,t,n)=>{const r=new AbortController,c={controller:r,action:e,payload:t};return i.add(c),E.current.add(c),{model:f.current.model,get phase(){return x.current},task:c,data:m,tasks:i,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),c=j(e)?e.channel:void 0;if(S(e)){const e=re(s,n);return e?se(e.emitter,n,t,c):Promise.resolve()}return se(g(e)?o:y,n,t,c)},annotate:(e,t)=>f.current.annotate(e,t),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 c=w(e),i="unknown"!==c?c[0].toLowerCase()+c.slice(1):null;if(i){const e=f.current.inspect[i];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]);c.useLayoutEffect(()=>{function e(e,n,r){return function(s,c){const a=r();if(c===oe&&t.G.isNotNullable(a))return;if(t.G.isNotNullable(c)&&c!==oe&&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 l={processes:new Set},d=Promise.withResolvers(),h=M(e,s,l);function m(t){const n=ce(O.current.handlers,"Error"),r=null!==n,s={reason:ue(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:w(e),handled:r,tasks:i};var c;o.fire(p,s),r&&n&&y.emit(n,s)}function b(){for(const e of i)if(e===h.task){i.delete(e),E.current.delete(e);break}l.processes.forEach(e=>f.current.prune(e)),l.processes.size>0&&u(),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)}}A.current++;const n=new Set;return O.current.handlers.forEach((t,r)=>{for(const{getChannel:c,handler:i}of t){const t=e(r,i,c);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=++A.current,t=new Set(n);queueMicrotask(()=>{if(A.current!==e){for(const e of t)e();return}for(const e of E.current)e.controller.abort(),i.delete(e);E.current.clear(),x.current=b.Unmounting;const n=ce(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:i,handlers:u}){const a=c.useRef(null);c.useLayoutEffect(()=>{if(s.current!==b.Mounting)return;const c=ce(u,"Mount");c&&e.emit(c),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},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(a.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(a.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=ce(u,"Update");t&&e.emit(t,n)}}a.current=i},[i,e])}({unicast:y,broadcast:o,dispatchers:P,scope:s,phase:x,data:r(),handlers:O.current.handlers});const C=c.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)=>c.createElement(le,{action:v(e),renderer:t})}],[d,y]);return C.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),[]),i=c.useCallback(()=>j(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(O,e,t)},C.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=j(e)?e.channel:void 0;return se(o,v(e),t,n)},[o]);return c.useCallback((...n)=>e.fetch(t,m,...n),[e,t,m])},C},e.useMode=function(){const e=c.useContext(Z);return c.useMemo(()=>({read:()=>e.current,update(t){e.current=t}}),[e])},e.utils=he,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,o=v(e);return{[n](e){const n=ne(),s=c.useMemo(()=>({action:o,emitter:new J}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,s]);return r.jsx(te.Provider,{value:i,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).Chizu={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
@@ -61,9 +61,9 @@ export declare function isChanneledAction(action: AnyAction): action is Channele
61
61
  /**
62
62
  * Extracts the lifecycle type from an action's symbol description.
63
63
  *
64
- * Returns the lifecycle name (`"Mount"`, `"Unmount"`, `"Error"`, `"Update"`,
65
- * `"Node"`) when the action symbol's description starts with the lifecycle
66
- * prefix, or `null` for non-lifecycle actions.
64
+ * Returns the lifecycle name (`"Mount"`, `"Unmount"`, `"Error"`, `"Update"`)
65
+ * when the action symbol's description starts with the lifecycle prefix, or
66
+ * `null` for non-lifecycle actions.
67
67
  *
68
68
  * @param action The action to inspect.
69
69
  * @returns The lifecycle name, or `null` if not a lifecycle action.
@@ -0,0 +1,15 @@
1
+ import { Props } from './types.ts';
2
+ import * as React from "react";
3
+ export { useMode } from './utils.ts';
4
+ export type { ModeHandle } from './utils.ts';
5
+ /**
6
+ * Provides a single mutable mode handle to every component inside the
7
+ * boundary. Components opt in by calling {@link useMode} and threading the
8
+ * returned handle through {@link useActions}'s `data` callback.
9
+ *
10
+ * Mode is **not** reactive &mdash; mutating it does not trigger a re-render.
11
+ * Use it for cross-handler coordination (e.g. flagging an in-progress
12
+ * sign-out) when you do not want the value showing up as render-time UI
13
+ * state.
14
+ */
15
+ export declare function Mode({ children }: Props): React.ReactNode;
@@ -0,0 +1,7 @@
1
+ import { ReactNode } from 'react';
2
+ /**
3
+ * Props for the Mode provider component.
4
+ */
5
+ export type Props = {
6
+ children: ReactNode;
7
+ };
@@ -0,0 +1,55 @@
1
+ import * as React from "react";
2
+ /**
3
+ * React context exposing the per-Boundary mode handle. The handle itself
4
+ * is stable across renders &mdash; readers grab `.current` at call time.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare const Context: React.Context<React.RefObject<unknown>>;
9
+ /**
10
+ * Handle returned by {@link useMode}. Reads always reflect the latest
11
+ * write, even after `await` boundaries.
12
+ */
13
+ export type ModeHandle<T> = {
14
+ read(): T | null;
15
+ update(value: T | null): void;
16
+ };
17
+ /**
18
+ * Hook that returns a `{ read, update }` handle to the per-Boundary mode
19
+ * value.
20
+ *
21
+ * Mode is a single mutable value shared across every component inside the
22
+ * surrounding `<Boundary>`. It is **not** reactive &mdash; mutating it does
23
+ * not trigger a re-render. Use it for coordinating between async action
24
+ * handlers (e.g. short-circuiting refreshes during sign-out).
25
+ *
26
+ * Pass the handle through the {@link useActions} `data` callback so it
27
+ * shows up under `context.data` inside handlers, fully typed.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * enum Mode {
32
+ * Idle,
33
+ * SigningOut,
34
+ * }
35
+ *
36
+ * function useSignOutActions() {
37
+ * const mode = useMode<Mode>();
38
+ * const actions = useActions<Model, typeof Actions>(model, () => ({ mode }));
39
+ *
40
+ * actions.useAction(Actions.SignOut, async (context) => {
41
+ * context.data.mode.update(Mode.SigningOut);
42
+ * await api.signOut();
43
+ * context.data.mode.update(Mode.Idle);
44
+ * });
45
+ *
46
+ * actions.useAction(Actions.Refresh, async (context) => {
47
+ * if (context.data.mode.read() === Mode.SigningOut) return;
48
+ * // ...
49
+ * });
50
+ *
51
+ * return actions;
52
+ * }
53
+ * ```
54
+ */
55
+ export declare function useMode<T>(): ModeHandle<T>;
@@ -0,0 +1,40 @@
1
+ import { MulticastPayload } from '../../../types/index.ts';
2
+ import { ComponentType, ReactNode } from 'react';
3
+ export { useScope, getScope } from './utils.ts';
4
+ export type { ScopeEntry, ScopeContext } from './types.ts';
5
+ /**
6
+ * Higher-order component that opens a multicast scope keyed by the supplied
7
+ * multicast action. Components rendered inside the wrapped tree (and any
8
+ * descendants) participate in the scope: every dispatch of `action` reaches
9
+ * every subscriber inside this boundary.
10
+ *
11
+ * Each multicast action defines its own scope &mdash; pass the same action you
12
+ * declared with `Distribution.Multicast` to both `withScope` and
13
+ * `actions.dispatch`.
14
+ *
15
+ * Multicast caches the most recent dispatched value per scope so late-mounted
16
+ * components can read it via `context.actions.resolution()`.
17
+ *
18
+ * @param action - The multicast action that opens this scope.
19
+ * @param Component - The component to wrap.
20
+ * @returns A component that renders the original inside a fresh scope boundary.
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * export class Scope {
25
+ * static Mood = Action<Mood>("Mood", Distribution.Multicast);
26
+ * }
27
+ *
28
+ * function Mood() {
29
+ * return (
30
+ * <>
31
+ * <Happy />
32
+ * <Sad />
33
+ * </>
34
+ * );
35
+ * }
36
+ *
37
+ * export default withScope(Scope.Mood, Mood);
38
+ * ```
39
+ */
40
+ export declare function withScope<P extends object, T = unknown>(action: MulticastPayload<T>, Component: ComponentType<P>): (props: P) => ReactNode;
@@ -0,0 +1,20 @@
1
+ import { BroadcastEmitter } from '../broadcast/utils.ts';
2
+ import { ActionId } from '../tasks/types.ts';
3
+ /**
4
+ * Represents a single scope in the ancestor chain. The scope key is the
5
+ * action id of the multicast action that opens the scope; each multicast
6
+ * action defines its own scope.
7
+ */
8
+ export type ScopeEntry = {
9
+ /** The action id that opened this scope */
10
+ action: ActionId;
11
+ /** BroadcastEmitter for multicast events within this scope (caches last payload per event) */
12
+ emitter: BroadcastEmitter;
13
+ };
14
+ /**
15
+ * The scope context is a flattened map of ancestor scopes keyed by the
16
+ * multicast action that opened each scope. Each `withScope` merges its entry
17
+ * with the parent's map, building up a complete lookup table for O(1)
18
+ * retrieval. null indicates no scope ancestor.
19
+ */
20
+ export type ScopeContext = Map<ActionId, ScopeEntry> | null;
@@ -1,4 +1,5 @@
1
1
  import { ScopeContext, ScopeEntry } from './types.ts';
2
+ import { ActionId } from '../tasks/types.ts';
2
3
  import * as React from "react";
3
4
  /**
4
5
  * React context for the scope chain.
@@ -12,11 +13,7 @@ export declare const Context: React.Context<ScopeContext>;
12
13
  */
13
14
  export declare function useScope(): ScopeContext;
14
15
  /**
15
- * Gets the scope with the given name.
16
+ * Looks up the scope opened by the given multicast action.
16
17
  * O(1) lookup from the flattened scope map.
17
- *
18
- * @param context - The current scope context (map of all ancestor scopes)
19
- * @param name - The scope name to find
20
- * @returns The matching ScopeEntry, or null if not found
21
18
  */
22
- export declare function getScope(context: ScopeContext, name: string): ScopeEntry | null;
19
+ export declare function getScope(context: ScopeContext, action: ActionId): ScopeEntry | null;
@@ -2,7 +2,7 @@ import { Props } from './types.ts';
2
2
  import * as React from "react";
3
3
  /**
4
4
  * Creates a unified context boundary for all Chizu features.
5
- * Wraps children with Broadcaster, Regulators, and Tasks providers.
5
+ * Wraps children with Broadcaster, Mode, and Tasks providers.
6
6
  *
7
7
  * Use this at the root of your application or to create isolated context boundaries
8
8
  * for libraries that need their own Chizu context.
@@ -0,0 +1,2 @@
1
+ export { Reason, AbortError, TimeoutError } from './types';
2
+ export type { Fault } from './types';