march-hare 0.7.5 → 0.9.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 (36) hide show
  1. package/README.md +496 -204
  2. package/dist/{hooks → actions}/index.d.ts +1 -2
  3. package/dist/{hooks → actions}/utils.d.ts +0 -39
  4. package/dist/app/index.d.ts +112 -0
  5. package/dist/app/types.d.ts +49 -0
  6. package/dist/boundary/components/broadcast/utils.d.ts +1 -1
  7. package/dist/boundary/components/env/index.d.ts +26 -0
  8. package/dist/boundary/components/env/types.d.ts +11 -0
  9. package/dist/boundary/components/env/utils.d.ts +36 -0
  10. package/dist/boundary/components/scope/index.d.ts +1 -39
  11. package/dist/boundary/components/scope/types.d.ts +17 -13
  12. package/dist/boundary/components/scope/utils.d.ts +12 -8
  13. package/dist/boundary/components/sharing/index.d.ts +43 -0
  14. package/dist/boundary/index.d.ts +10 -10
  15. package/dist/boundary/types.d.ts +6 -16
  16. package/dist/cache/index.d.ts +4 -4
  17. package/dist/coalesce/index.d.ts +57 -0
  18. package/dist/context/index.d.ts +39 -0
  19. package/dist/context/types.d.ts +14 -0
  20. package/dist/error/index.d.ts +1 -1
  21. package/dist/error/types.d.ts +8 -19
  22. package/dist/index.d.ts +8 -12
  23. package/dist/march-hare.js +7 -5
  24. package/dist/march-hare.umd.cjs +1 -1
  25. package/dist/resource/index.d.ts +52 -78
  26. package/dist/resource/types.d.ts +83 -10
  27. package/dist/scope/index.d.ts +63 -0
  28. package/dist/scope/types.d.ts +55 -0
  29. package/dist/types/index.d.ts +116 -229
  30. package/dist/utils/index.d.ts +6 -5
  31. package/dist/with/index.d.ts +40 -0
  32. package/package.json +1 -1
  33. package/dist/boundary/components/store/index.d.ts +0 -41
  34. package/dist/boundary/components/store/types.d.ts +0 -11
  35. package/dist/boundary/components/store/utils.d.ts +0 -64
  36. /package/dist/{hooks → actions}/types.d.ts +0 -0
@@ -1,2 +1,2 @@
1
- export { Reason, AbortError, TimeoutError } from './types';
1
+ export { Reason, Aborted } from './types';
2
2
  export type { Fault } from './types';
@@ -3,37 +3,26 @@ import { Task } from '../boundary/components/tasks/types';
3
3
  * Reasons why an action error occurred.
4
4
  */
5
5
  export declare enum Reason {
6
- /** Action exceeded its timeout limit. */
7
- Timedout = 0,
8
- /** Action was cancelled by a newer dispatch. */
9
- Supplanted = 1,
6
+ /** Action was aborted — superseded by a newer dispatch, the
7
+ * component unmounted, or `task.controller.abort()` was called. */
8
+ Aborted = 0,
10
9
  /** A generic error thrown in the user's action handler. */
11
- Errored = 2
10
+ Errored = 1
12
11
  }
13
12
  /**
14
13
  * Error thrown when an action is aborted, e.g., when a component unmounts
15
14
  * or when a newer dispatch cancels a previous run. Works across all platforms
16
15
  * including React Native where `DOMException` is unavailable.
17
16
  *
18
- * @example
19
- * ```ts
20
- * throw new AbortError("User cancelled the request");
21
- * ```
22
- */
23
- export declare class AbortError extends Error {
24
- name: string;
25
- constructor(message?: string);
26
- }
27
- /**
28
- * Error thrown when an action exceeds its timeout limit.
29
- * Works across all platforms including React Native where `DOMException` is unavailable.
17
+ * The instance's `name` field stays as `"AbortError"` so it can be
18
+ * pattern-matched alongside native `DOMException`s and ky/fetch aborts.
30
19
  *
31
20
  * @example
32
21
  * ```ts
33
- * throw new TimeoutError("Request took too long");
22
+ * throw new Aborted("User cancelled the request");
34
23
  * ```
35
24
  */
36
- export declare class TimeoutError extends Error {
25
+ export declare class Aborted extends Error {
37
26
  name: string;
38
27
  constructor(message?: string);
39
28
  }
package/dist/index.d.ts CHANGED
@@ -1,19 +1,15 @@
1
+ export { App } from './app/index';
1
2
  export { Action } from './action/index';
2
3
  export { Distribution, Lifecycle } from './types/index';
3
- export { Reason, AbortError, TimeoutError } from './error/index';
4
- export { Operation, Op, State } from 'immertation';
5
- export { annotate } from './annotate/index';
4
+ export { With } from './with/index';
6
5
  export { Boundary } from './boundary/index';
7
- export { withScope } from './boundary/components/scope/index';
8
- export { useStore } from './boundary/components/store/index';
9
- export type { Store } from './boundary/components/store/index';
10
- export { useActions, With } from './hooks/index';
11
6
  export { Resource } from './resource/index';
12
- export type { Fetcher } from './resource/index';
13
7
  export { Cache } from './cache/index';
14
- export type { Adapter, Encoded } from './cache/index';
8
+ export { Reason, Aborted } from './error/index';
9
+ export { annotate } from './annotate/index';
10
+ export { Operation, Op, State } from 'immertation';
15
11
  export * as utils from './utils/index';
16
- export type { Stored, Unset } from './utils/index';
17
- export type { Box } from 'immertation';
18
12
  export type { Fault } from './error/index';
19
- export type { Pk, Task, Tasks, Handlers, Handler, LeafActions, Dispatchable, Subscribable, } from './types/index';
13
+ export type { Adapter } from './cache/index';
14
+ export type { Box } from 'immertation';
15
+ export type { Pk, Task, Tasks, Maybe, Handler, Handlers, } from './types/index';
@@ -1,5 +1,7 @@
1
- import{G as e,A as t}from"@mobily/ts-belt";import{immerable as n,enablePatches as r,Immer as o,produce as s}from"immer";import{jsx as c}from"react/jsx-runtime";import*as a from"react";const i=(e="")=>`march-hare.action/${e}`,u=(e="")=>`march-hare.action/broadcast/${e}`,l=(e="")=>`march-hare.action/multicast/${e}`,f=(e="")=>`march-hare.action.lifecycle/${e}`;class d{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function p(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[d.Action]:t,[d.Payload]:void 0,[d.Channel]:n,[d.Name]:e,channel:n}};return Object.defineProperty(n,d.Action,{value:t,enumerable:!1}),Object.defineProperty(n,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,d.Name,{value:e,enumerable:!1}),n}const h=Symbol(u("Fault")),m=Symbol(u("Store"));class y{static Mount(){return p("Mount")}static Unmount(){return p("Unmount")}static Error(){return p("Error")}static Update(){return p("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:h,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,d.Action,{value:m,enumerable:!1}),Object.defineProperty(e,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,d.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,d.Name,{value:"Store",enumerable:!1}),e})()}var b=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),v=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(v||{});const g=e=>"symbol"==typeof e;function w(t){return e.isString(t)||g(t)?t:(e.isObject(t)||e.isFunction(t))&&d.Action in t?t[d.Action]:t}function O(t){if(e.isString(t))return t.startsWith(u());if(g(t))return t.description?.startsWith(u())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Broadcast in t&&t[d.Broadcast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(u())??!1}}return!1}function P(t){const n=w(t),r=e.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function S(t){return e.isObject(t)&&d.Channel in t&&"channel"in t}function j(e){const t=w(e),n=g(t)?t.description??"":t;return n.startsWith(f())&&n.slice(f().length)||null}function E(t){if(e.isString(t))return t.startsWith(l());if(g(t))return t.description?.startsWith(l())??!1;if(e.isObject(t)||e.isFunction(t)){if(d.Multicast in t&&t[d.Multicast])return!0;if(d.Action in t){const e=t[d.Action];return e.description?.startsWith(l())??!1}}return!1}const x=(e="",t=b.Unicast)=>{const n=t===b.Broadcast?Symbol(u(e)):t===b.Multicast?Symbol(l(e)):Symbol(i(e)),r=function(t){return{[d.Action]:n,[d.Payload]:void 0,[d.Channel]:t,[d.Name]:e,channel:t}};return Object.defineProperty(r,d.Action,{value:n,enumerable:!1}),Object.defineProperty(r,d.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,d.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(r,d.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(r,d.Multicast,{value:!0,enumerable:!1}),r};var M=/* @__PURE__ */(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(M||{});class C extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class k extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let N=(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))(_||{}),R=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(R||{});class U{[n]=!0;static keys=new Set(Object.values(R));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new U(this.value,this.operation);return n.property=e,n.process=t,n}}class T{static immer=(()=>{r();const e=new o;return e.setAutoFreeze(!1),e})();static tag="κ";static id=N}function L(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function B(t){if(e.isNullable(t)||$(t))return t;if(e.isArray(t))return t.map(e=>B(e));if(e.isObject(t)&&W(t)){const e=Object.entries(t).map(([e,t])=>[e,B(t)]);return{...Object.fromEntries(e),[T.tag]:t[T.tag]??T.id()}}return t}function F(e){if(Array.isArray(e))return e.filter(e=>T.tag in e).map(e=>e[T.tag]??"").join(",");const t=e[T.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function W(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function $(t){return e.isNullable(t)||e.isString(t)||e.isNumber(t)||e.isBoolean(t)||"symbol"==typeof t||"bigint"==typeof t}function D(t,n,r,o,s,c){return function a(i,u=n.path){if(i instanceof U){const n=L(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>a(t,u.concat(e))),$(i.value)){if(t===_.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?L(r,a.join(".")):r;return e.isNullable(l)||H(l,i,u.at(-1),o,s,c),n??i.value}if(t===_.Hydrate){const e=B(a(i.value,u));return H(e,i,null,o,s,c),e}const l=n??B(i.value);return H(l,i,null,o,s,c),e.isNullable(n)?l:(a(i.value,u),n)}if(e.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(e.isObject(i)&&!W(i))return i;if(e.isObject(i)){const e=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(e);if(t===_.Hydrate){const e=B(n);return Object.entries(i).forEach(([t,n])=>{n instanceof U&&$(n.value)&&H(e,n,t,o,s,c)}),e}return n}return i}(n.value)}function H(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class I{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=F){this.#t=e}static pk(){return N()}static"κ"=I.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(n,r,o,s,c){function a(s){const c=s.at(-1),a=L(n(),s),i=s.slice(0,-1),u=t.isNotEmpty(i)?L(n(),i):n();return[...e.isObject(a)||e.isArray(a)?r.get(o(a))?.filter(t=>e.isNullable(t.property))??[]:[],...e.isObject(u)?r.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function e(r){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!t.isEmpty(a(r)):"remaining"===i?()=>t.length(a(r)):"box"===i?()=>({value:L(n(),r),inspect:e(r)}):"is"===i?e=>a(r).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.head(a(r))?.value??L(n(),r):"settled"===i?()=>new Promise(e=>{if(t.isEmpty(a(r)))return e(L(n(),r));const o=()=>{t.isEmpty(a(r))&&(c(o),e(L(n(),r)))};s(o)}):e([...r,String(i)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(_.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(_.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=T.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>T.immer.applyPatches(t,[{...r,value:D(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=B(this.#e),this.#c(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const z=new I;function J(e,t=A.Update){return z.annotate(t,e)}function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var G,K={exports:{}};const V=/* @__PURE__ */q((G||(G=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(K)),K.exports));class Q extends V{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}fire(e,...t){return super.emit(e,...t)}}const X=a.createContext(new Q);function Y(){return a.useContext(X)}function Z({children:e}){const t=a.useMemo(()=>new Q,[]);/* @__PURE__ */
2
- return c(X.Provider,{value:t,children:e})}const ee=a.createContext(/* @__PURE__ */new Set);function te({children:e}){const t=a.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
- return c(ee.Provider,{value:t,children:e})}const ne=a.createContext({current:{}});function re(){const e=a.useContext(ne);return a.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,n){const r=Object.getOwnPropertyDescriptor(e.current,n);if(void 0!==r)return{...r,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function oe({initial:e,children:t}){const n=a.useRef(e),r=Y();return void 0===r.getCached(m)&&r.setCache(m,n.current),/* @__PURE__ */c(ne.Provider,{value:n,children:t})}function se({store:e,children:t}){/* @__PURE__ */
4
- return c(Z,{children:/* @__PURE__ */c(oe,{initial:e??{},children:/* @__PURE__ */c(te,{children:t})})})}const ce=a.createContext(null);function ae(){return a.useContext(ce)}function ie(e,t){return e?.get(t)??null}function ue(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`,r=w(e);return{[n](e){const n=ae(),o=a.useMemo(()=>({action:r,emitter:new Q}),[]),s=a.useMemo(()=>{const e=new Map(n??[]);return e.set(r,o),e},[n,o]);/* @__PURE__ */
5
- return c(ce.Provider,{value:s,children:/* @__PURE__ */c(t,{...e})})}}[n]}const le=Symbol(((e="")=>`march-hare/replay${e}`)());function fe(e,t,...n){e instanceof Q&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}const de={Update:e=>(t,n)=>{t.actions.produce(t=>{t.model[e]=n})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}};function pe(e,t){for(const n of e.keys())if(j(n)===t)return n;return null}const he=/* @__PURE__ */Symbol("march-hare.unset");function me(){const[,e]=a.useReducer(e=>e+1,0);return e}function ye(){return{data:he,at:null,else:e=>e}}function be(e,t){return{data:e,at:t,else:t=>e}}function ve(e){if(e instanceof Error){if("TimeoutError"===e.name)return M.Timedout;if("AbortError"===e.name)return M.Supplanted}return M.Errored}function ge(e){const t=/* @__PURE__ */new Map,n=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=n.get(e);if(null===t)return ye();const r=JSON.parse(t);return be(r.data,Temporal.Instant.from(r.at))}catch{return ye()}},set(e,t){if(t.data===he||null===t.at)return!1;try{return n.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){n.remove(e)},clear(){n.clear()}}}function we(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new C);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new C)},{once:!0})})}async function Oe(e,t,n){if(t?.aborted)throw new C;for(;;){if(await n())return;await we(e,t)}}function Pe(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const Se=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Pe,poll:Oe,sleep:we,unset:he,"ζ":we,"κ":Pe,"π":Oe},Symbol.toStringTag,{value:"Module"})),je=/* @__PURE__ */new WeakMap;function Ee(e){return JSON.stringify(e)}let xe=null;function Me(){if(null===xe)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=xe;return xe=null,e}function Ce(e,t){const n=t??function(e){let t=je.get(e);return void 0===t&&(t=ge(),je.set(e,t)),t}(e),r=e=>{const t=n.get(Ee(e));return t.data===he||null===t.at?{data:he,at:null}:{data:t.data,at:t.at}},o=(t,r,o)=>e({store:t,controller:r,params:o}).then(e=>(n.set(Ee(o),be(e,Temporal.Now.instant())),e)),s=(e,t,r)=>{n.set(Ee(e),be(t,r))};return function(e){const t=e??{};xe={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{null!==xe&&xe.params===t&&(xe=null)});const{data:n}=r(t);return n===he?null:n}}const ke=a.createContext(/* @__PURE__ */new Map);function Ne({action:t,renderer:n}){const r=Y(),o=a.useContext(ke),s=me(),c=a.useMemo(()=>{const e=o.get(t);if(e)return e;const n=new I,s=r.getCached(t);void 0!==s&&n.hydrate({value:s});const c={state:n,listeners:/* @__PURE__ */new Set};return o.set(t,c),c},[t,r,o]);a.useLayoutEffect(()=>{function e(e){c.state.hydrate({value:e}),c.listeners.forEach(e=>e())}return c.listeners.add(s),r.on(t,e),()=>{c.listeners.delete(s),r.off(t,e)}},[t,r,c]);const i=c.state.model?.value;return e.isNullable(i)?null:n(i,c.state.inspect.value)}function Ae(...n){const r=e.isUndefined(n[0])||e.isFunction(n[0])?{}:n[0],o=e.isFunction(n[0])?n[0]:n[1]??(()=>({})),c=Y(),i=ae(),u=a.useContext(ee),l=re(),f=a.useContext(ne),d=me(),p=a.useRef(!1),y=a.useRef(null),b=a.useRef(new I);p.current||(p.current=!0,y.current=b.current.hydrate(r));const[g,j]=a.useState(()=>b.current.model),x=function(e){const t=a.useRef(e);return t.current=e,a.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(o()),M=a.useMemo(()=>new V,[]),C=a.useRef({handlers:/* @__PURE__ */new Map});C.current.handlers=/* @__PURE__ */new Map;const k=function(){const e=a.useRef(/* @__PURE__ */new Set),t=a.useRef(/* @__PURE__ */new Set);return a.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),N=a.useRef(v.Mounting),_=a.useRef(/* @__PURE__ */new Set),R=a.useRef(0),U=a.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),_.current.add(o),{model:b.current.model,get phase(){return N.current},task:o,data:x,tasks:u,store:l,actions:{produce(e){if(r.signal.aborted)return;const t=f.current,o=b.current.produce(t=>{f.current=s(f.current,n=>{e({model:t,inspect:b.current.inspect,store:n})})});j(b.current.model),f.current!==t&&c.emit(m,f.current),n.processes.add(o),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t){if(r.signal.aborted)return Promise.resolve();const n=w(e),o=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,o):Promise.resolve()}return fe(O(e)?c:M,n,t,o)},annotate:(e,t=A.Update)=>b.current.annotate(t,e),resource:Object.assign(function(e){const t=Me(),n=()=>t.run(f.current,r,t.params);return{then:(e,t)=>n().then(e,t),exceeds:e=>{const{data:r,at:o}=t.read(t.params);if(r!==he&&null!==o){const t=Temporal.Now.instant().since(o),n=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(r)}return n()}}},{set:(e,t)=>{const n=Me();n.seed(n.params,t,Temporal.Now.instant())}}),async resolution(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;if(!n)return null;if(void 0===n.getCached(t))return null;const o=b.current.inspect;return o.pending()&&await new Promise((e,t)=>{if(r.signal.aborted)return void t(r.signal.reason);const n=()=>t(r.signal.reason);r.signal.addEventListener("abort",n,{once:!0}),o.settled().then(()=>{r.signal.removeEventListener("abort",n),e()})}),n.getCached(t)??null},peek(e){if(r.signal.aborted)return null;const t=w(e),n=E(e)?ie(i,t)?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[g]);a.useLayoutEffect(()=>{function t(t,n,r){return function(o,s){const a=r();if(s===le&&e.isNotNullable(a))return;if(e.isNotNullable(s)&&s!==le&&e.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(s,a))return;const i={processes:/* @__PURE__ */new Set},l=Promise.withResolvers(),f=U(t,o,i);function p(e){const n=pe(C.current.handlers,"Error"),r=null!==n,o={reason:ve(e),error:(s=e,s instanceof Error?s:new Error(String(s))),action:P(t),handled:r,tasks:u};var s;c.fire(h,o),r&&n&&M.emit(n,o)}function m(){for(const e of u)if(e===f.task){u.delete(e),_.current.delete(e);break}i.processes.forEach(e=>b.current.prune(e)),i.processes.size>0&&d(),l.resolve()}let y;try{y=n(f,o)}catch(v){return p(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(p).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(p).finally(m)}}R.current++;const n=/* @__PURE__ */new Set;return C.current.handlers.forEach((e,r)=>{for(const{getChannel:o,handler:s}of e){const e=t(r,s,o);if(E(r)){if(i)for(const t of i.values()){const o=t.emitter;o.on(r,e),n.add(()=>o.off(r,e))}M.on(r,e),k.multicast.add(r),n.add(()=>M.off(r,e))}else O(r)?(c.on(r,e),M.on(r,e),k.broadcast.add(r),n.add(()=>{c.off(r,e),M.off(r,e)})):(M.on(r,e),n.add(()=>M.off(r,e)))}}),()=>{const e=++R.current,t=new Set(n);queueMicrotask(()=>{if(R.current!==e){for(const e of t)e();return}for(const e of _.current)e.controller.abort(),u.delete(e);_.current.clear(),N.current=v.Unmounting;const n=pe(C.current.handlers,"Unmount");n&&M.emit(n),N.current=v.Unmounted;for(const e of t)e()})}},[M]),function({unicast:n,broadcast:r,dispatchers:o,scope:s,phase:c,data:i,handlers:u}){const l=a.useRef(null);a.useLayoutEffect(()=>{if(c.current===v.Mounted)return;c.current=v.Mounting;const t=pe(u,"Mount");t&&n.emit(t),o.broadcast.forEach(t=>{const o=r.getCached(t);e.isNullable(o)||n.emit(t,o,le)}),s&&o.multicast.forEach(t=>{for(const r of s.values()){const o=r.emitter.getCached(t);e.isNullable(o)||n.emit(t,o,le)}}),c.current=v.Mounted},[]),a.useLayoutEffect(()=>{if(e.isNotNullable(l.current)){const e=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(t.isNotEmpty(Object.keys(e))){const t=pe(u,"Update");t&&n.emit(t,e)}}l.current=i},[i,n])}({unicast:M,broadcast:c,dispatchers:k,scope:i,phase:N,data:o(),handlers:C.current.handlers});const T=a.useMemo(()=>({dispatch(e,t){const n=w(e),r=S(e)?e.channel:void 0;if(E(e)){const e=ie(i,n);return e?fe(e.emitter,n,t,r):Promise.resolve()}return fe(O(e)?c:M,n,t,r)},get inspect(){return b.current.inspect},stream:(e,t)=>a.createElement(Ne,{action:w(e),renderer:t})}),[g,M]),L=a.useMemo(()=>[g,T,x],[g,T,x]);return L.useAction=(e,t)=>{!function(e,t,n){const r=a.useRef(n);a.useLayoutEffect(()=>{r.current=n});const o=a.useRef(t);a.useLayoutEffect(()=>{o.current=t});const s=a.useCallback((e,t)=>r.current(e,t),[]),c=a.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),i=w(t),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:c,handler:s})}(C,e,t)},L.dispatch=L[1].dispatch,L}export{C as AbortError,x as Action,se as Boundary,ge as Cache,b as Distribution,y as Lifecycle,A as Op,A as Operation,M as Reason,Ce as Resource,I as State,k as TimeoutError,de as With,J as annotate,Ae as useActions,re as useStore,Se as utils,ue as withScope};
1
+ import{jsx as e}from"react/jsx-runtime";import*as t from"react";import{G as n,A as r}from"@mobily/ts-belt";import{immerable as o,enablePatches as s,Immer as c,produce as a}from"immer";function i(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var u,l={exports:{}};const f=/* @__PURE__ */i((u||(u=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,h=l.length;for(u=0;u<h;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(l)),l.exports));class d extends f{cache=/* @__PURE__ */new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}fire(e,...t){return super.emit(e,...t)}}const h=t.createContext(new d);function p(){return t.useContext(h)}function m({children:n}){const r=t.useMemo(()=>new d,[]);/* @__PURE__ */
2
+ return e(h.Provider,{value:r,children:n})}const b=t.createContext(/* @__PURE__ */new Set);function y({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return e(b.Provider,{value:r,children:n})}const v=t.createContext({current:{}});function g(){const e=t.useContext(v);return t.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,r){const o=Object.getOwnPropertyDescriptor(e.current,r);if(!n.isUndefined(o))return{...o,configurable:!0}},set(){throw new TypeError("Env is read-only outside `context.actions.produce`. Mutate via produce(({ env }) => { env.x = ... }) instead.")}}),[e])}const w=(e="")=>`march-hare.action/${e}`,O=(e="")=>`march-hare.action/broadcast/${e}`,P=(e="")=>`march-hare.action/multicast/${e}`,j=(e="")=>`march-hare.action.lifecycle/${e}`;class S{static Payload=/* @__PURE__ */Symbol("march-hare.brand/Payload");static Broadcast=/* @__PURE__ */Symbol("march-hare.brand/Broadcast");static Multicast=/* @__PURE__ */Symbol("march-hare.brand/Multicast");static Action=/* @__PURE__ */Symbol("march-hare.brand/Action");static Channel=/* @__PURE__ */Symbol("march-hare.brand/Channel");static Name=/* @__PURE__ */Symbol("march-hare.brand/Name")}function x(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[S.Action]:t,[S.Payload]:void 0,[S.Channel]:n,[S.Name]:e,channel:n}};return Object.defineProperty(n,S.Action,{value:t,enumerable:!1}),Object.defineProperty(n,S.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,S.Name,{value:e,enumerable:!1}),n}const E=Symbol(O("Fault")),C=Symbol(O("Env"));class N{static Mount(){return x("Mount")}static Unmount(){return x("Unmount")}static Error(){return x("Error")}static Update(){return x("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,S.Action,{value:E,enumerable:!1}),Object.defineProperty(e,S.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,S.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,S.Name,{value:"Fault",enumerable:!1}),e})();static Env=(()=>{const e={};return Object.defineProperty(e,S.Action,{value:C,enumerable:!1}),Object.defineProperty(e,S.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,S.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,S.Name,{value:"Env",enumerable:!1}),e})()}var M=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(M||{}),k=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(k||{});function A({initial:r,children:o}){const s=t.useRef(r),c=p();return n.isUndefined(c.getCached(C))&&c.setCache(C,s.current),/* @__PURE__ */e(v.Provider,{value:s,children:o})}const _=t.createContext(/* @__PURE__ */new WeakMap);function U({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new WeakMap,[]);/* @__PURE__ */
4
+ return e(_.Provider,{value:r,children:n})}function R({env:t,children:n}){/* @__PURE__ */
5
+ return e(m,{children:/* @__PURE__ */e(A,{initial:t??{},children:/* @__PURE__ */e(y,{children:/* @__PURE__ */e(U,{children:n})})})})}const L=e=>"symbol"==typeof e;function T(e){return n.isString(e)||L(e)?e:(n.isObject(e)||n.isFunction(e))&&S.Action in e?e[S.Action]:e}function W(e){if(n.isString(e))return e.startsWith(O());if(L(e))return e.description?.startsWith(O())??!1;if(n.isObject(e)||n.isFunction(e)){if(S.Broadcast in e&&e[S.Broadcast])return!0;if(S.Action in e){const t=e[S.Action];return t.description?.startsWith(O())??!1}}return!1}function $(e){const t=T(e),r=n.isString(t)?t:t.description??"";return r.startsWith(w())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function B(e){return n.isObject(e)&&S.Channel in e&&"channel"in e}function F(e){const t=T(e),n=L(t)?t.description??"":t;return n.startsWith(j())&&n.slice(j().length)||null}function D(e){if(n.isString(e))return e.startsWith(P());if(L(e))return e.description?.startsWith(P())??!1;if(n.isObject(e)||n.isFunction(e)){if(S.Multicast in e&&e[S.Multicast])return!0;if(S.Action in e){const t=e[S.Action];return t.description?.startsWith(P())??!1}}return!1}const H=(e="",t=M.Unicast)=>{const n=t===M.Broadcast?Symbol(O(e)):t===M.Multicast?Symbol(P(e)):Symbol(w(e)),r=function(t){return{[S.Action]:n,[S.Payload]:void 0,[S.Channel]:t,[S.Name]:e,channel:t}};return Object.defineProperty(r,S.Action,{value:n,enumerable:!1}),Object.defineProperty(r,S.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,S.Name,{value:e,enumerable:!1}),t===M.Broadcast&&Object.defineProperty(r,S.Broadcast,{value:!0,enumerable:!1}),t===M.Multicast&&Object.defineProperty(r,S.Multicast,{value:!0,enumerable:!1}),r},I=Symbol(((e="")=>`march-hare/replay${e}`)());function J(e,t,...n){e instanceof d&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function z(e,t){for(const n of e.keys())if(F(n)===t)return n;return null}const q=/* @__PURE__ */Symbol("march-hare.unset");function G(){const[,e]=t.useReducer(e=>e+1,0);return e}function K(){return{data:q,at:null,else:e=>e}}function V(e,t){return{data:e,at:t,else:t=>e}}var Q=/* @__PURE__ */(e=>(e[e.Aborted=0]="Aborted",e[e.Errored=1]="Errored",e))(Q||{});class X extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}function Y(e){return e instanceof Error?e:new Error(String(e))}const Z=t.createContext(null);function ee(e){const t=/* @__PURE__ */new Map,r=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=r.get(e);if(n.isNull(t))return K();const o=JSON.parse(t);return V(o.data,Temporal.Instant.from(o.at))}catch{return K()}},set(e,t){if(t.data===q||n.isNull(t.at))return!1;try{return r.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){r.remove(e)},clear(){r.clear()}}}function te(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new X);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new X)},{once:!0})})}async function ne(e,t,n){if(t?.aborted)throw new X;for(;;){if(await n())return;await te(e,t)}}function re(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const oe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:re,poll:ne,sleep:te,unset:q,"ζ":te,"κ":re,"π":ne},Symbol.toStringTag,{value:"Module"})),se=/* @__PURE__ */new WeakMap;function ce(e){return JSON.stringify(e)}let ae=null;function ie(){if(n.isNull(ae))throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(resource.cat({ id: 5 })).");const e=ae;return ae=null,e}function ue(e,t){const r=e=>{const r=t.get(ce(e));return r.data===q||n.isNull(r.at)?{data:q,at:null}:{data:r.data,at:r.at}},o=(n,r,o,s)=>e({env:n,controller:r,params:o,dispatch:s}).then(e=>(t.set(ce(o),V(e,Temporal.Now.instant())),e)),s=(e,n,r)=>{t.set(ce(e),V(n,r))};return function(e){const t=e??{};ae={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{n.isNotNullable(ae)&&ae.params===t&&(ae=null)});const{data:c}=r(t);return c===q?null:c}}function le(e){return ue(e,function(e){let t=se.get(e);return n.isUndefined(t)&&(t=ee(),se.set(e,t)),t}(e))}(le||(le={})).Cachable=function(e,t){return ue(t,e)};const fe=/* @__PURE__ */Symbol("march-hare.coalesce/default");function de(e,t){return new Promise((n,r)=>{if(t.aborted)return void r(t.reason);const o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})})}let he=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var pe=/* @__PURE__ */(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(pe||{}),me=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(me||{}),be=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(be||{});class ye{[o]=!0;static keys=new Set(Object.values(be));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new ye(this.value,this.operation);return n.property=e,n.process=t,n}}class ve{static immer=(()=>{s();const e=new c;return e.setAutoFreeze(!1),e})();static tag="κ";static id=he}function ge(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function we(e){if(n.isNullable(e)||je(e))return e;if(n.isArray(e))return e.map(e=>we(e));if(n.isObject(e)&&Pe(e)){const t=Object.entries(e).map(([e,t])=>[e,we(t)]);return{...Object.fromEntries(t),[ve.tag]:e[ve.tag]??ve.id()}}return e}function Oe(e){if(Array.isArray(e))return e.filter(e=>ve.tag in e).map(e=>e[ve.tag]??"").join(",");const t=e[ve.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function Pe(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function je(e){return n.isNullable(e)||n.isString(e)||n.isNumber(e)||n.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function Se(e,t,r,o,s,c){return function a(i,u=t.path){if(i instanceof ye){const t=ge(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!ye.keys.has(e)&&t instanceof ye).forEach(([e,t])=>a(t,u.concat(e))),je(i.value)){if(e===me.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?ge(r,a.join(".")):r;return n.isNullable(l)||xe(l,i,u.at(-1),o,s,c),t??i.value}if(e===me.Hydrate){const e=we(a(i.value,u));return xe(e,i,null,o,s,c),e}const l=t??we(i.value);return xe(l,i,null,o,s,c),n.isNullable(t)?l:(a(i.value,u),t)}if(n.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(n.isObject(i)&&!Pe(i))return i;if(n.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(t);if(e===me.Hydrate){const e=we(n);return Object.entries(i).forEach(([t,n])=>{n instanceof ye&&je(n.value)&&xe(e,n,t,o,s,c)}),e}return n}return i}(t.value)}function xe(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class Ee{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=Oe){this.#t=e}static pk(){return he()}static"κ"=Ee.pk;annotate(e,t){return new ye(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,t,o,s,c){function a(s){const c=s.at(-1),a=ge(e(),s),i=s.slice(0,-1),u=r.isNotEmpty(i)?ge(e(),i):e();return[...n.isObject(a)||n.isArray(a)?t.get(o(a))?.filter(e=>n.isNullable(e.property))??[]:[],...n.isObject(u)?t.get(o(u))?.filter(e=>e.property===c)??[]:[]]}return function t(n){return new Proxy(()=>{},{get:(o,i)=>"pending"===i?()=>!r.isEmpty(a(n)):"remaining"===i?()=>r.length(a(n)):"box"===i?()=>({value:ge(e(),n),inspect:t(n)}):"is"===i?e=>a(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>r.head(a(n))?.value??ge(e(),n):"settled"===i?()=>new Promise(t=>{if(r.isEmpty(a(n)))return t(ge(e(),n));const o=()=>{r.isEmpty(a(n))&&(c(o),t(ge(e(),n)))};s(o)}):t([...n,String(i)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(me.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(me.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=ve.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>ve.immer.applyPatches(t,[{...r,value:Se(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=we(this.#e),this.#c(),n}prune(e){this.#n.forEach((t,n)=>{const o=t.filter(t=>t.process!==e);r.isEmpty(o)?this.#n.delete(n):this.#n.set(n,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const Ce=t.createContext(/* @__PURE__ */new Map);function Ne({action:e,renderer:r}){const o=p(),s=t.useContext(Ce),c=G(),a=t.useMemo(()=>{const t=s.get(e);if(t)return t;const r=new Ee,c=o.getCached(e);n.isNotNullable(c)&&r.hydrate({value:c});const a={state:r,listeners:/* @__PURE__ */new Set};return s.set(e,a),a},[e,o,s]);t.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(c),o.on(e,t),()=>{a.listeners.delete(c),o.off(e,t)}},[e,o,a]);const i=a.state.model?.value;return n.isNullable(i)?null:r(i,a.state.inspect.value)}function Me(){const e=t.useRef(null);return t.useMemo(()=>({actions:{dispatch:function(t,n){const r=e.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(t,n)}},useActions:function(...o){const s=function(...e){const o=n.isUndefined(e[0])||n.isFunction(e[0])?{}:e[0],s=n.isFunction(e[0])?e[0]:e[1]??(()=>({})),c=p(),i=t.useContext(Z),u=t.useContext(b),l=g(),d=t.useContext(v),h=t.useContext(_),m=G(),y=t.useRef(!1),w=t.useRef(null),O=t.useRef(new Ee);y.current||(y.current=!0,w.current=O.current.hydrate(o));const[P,j]=t.useState(()=>O.current.model),S=function(e){const n=t.useRef(e);return n.current=e,t.useMemo(()=>{return t=n,Object.keys(e).reduce((e,n)=>(Object.defineProperty(e,n,{get:()=>t.current[n],enumerable:!0}),e),{});var t},[e])}(s()),x=t.useMemo(()=>new f,[]),N=t.useRef({handlers:/* @__PURE__ */new Map});N.current.handlers=/* @__PURE__ */new Map;const M=function(){const e=t.useRef(/* @__PURE__ */new Set),n=t.useRef(/* @__PURE__ */new Set);return t.useMemo(()=>({broadcast:e.current,multicast:n.current}),[])}(),A=t.useRef(k.Mounting),U=t.useRef(/* @__PURE__ */new Set),R=t.useRef(0),L=t.useCallback((e,t,r)=>{const o=new AbortController,s={controller:o,action:e,payload:t};return u.add(s),U.current.add(s),{model:O.current.model,get phase(){return A.current},task:s,data:S,tasks:u,env:l,actions:{produce(e){if(o.signal.aborted)return;const t=d.current,n=O.current.produce(t=>{d.current=a(d.current,n=>{e({model:t,inspect:O.current.inspect,env:n})})});j(O.current.model),d.current!==t&&c.emit(C,d.current),r.processes.add(n),w.current&&(r.processes.add(w.current),w.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=T(e),r=B(e)?e.channel:void 0;return D(e)?i?J(i.emitter,n,t,r):Promise.resolve():J(W(e)?c:x,n,t,r)},annotate:(e,t=pe.Update)=>O.current.annotate(t,e),get inspect(){return O.current.inspect},resource:Object.assign(function(e){const t=ie(),r=(e,t)=>{if(o.signal.aborted)return Promise.resolve();const n=e,r=T(n);return D(n)?i?J(i.emitter,r,t,void 0):Promise.resolve():W(n)?J(c,r,t,void 0):Promise.resolve()},s={exceedsWindow:null,coalesceToken:void 0},a={then:(e,c)=>(()=>{if(n.isNotNullable(s.exceedsWindow)){const{data:e,at:r}=t.read(t.params);if(e!==q&&n.isNotNullable(r)){const t=Temporal.Now.instant().since(r),n=Temporal.Duration.from(s.exceedsWindow);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(e)}}if(n.isUndefined(s.coalesceToken))return t.run(d.current,o,t.params,r);let e=h.get(t.run);n.isUndefined(e)&&(e=/* @__PURE__ */new Map,h.set(t.run,e));const c=e,a=`${JSON.stringify(t.params)}|${function(e){switch(typeof e){case"string":return`s:${e}`;case"number":return`n:${e}`;case"bigint":return`i:${e.toString()}`;case"boolean":return`b:${e}`;case"symbol":return`y:${e.description??String(e)}`;default:return`o:${JSON.stringify(e)}`}}(s.coalesceToken)}`,i=c.get(a);if(i)return de(i,o.signal);const u=new AbortController,l=t.run(d.current,u,t.params,r).finally(()=>{c.delete(a)});return c.set(a,l),de(l,o.signal)})().then(e,c),exceeds:e=>(s.exceedsWindow=e,a),coalesce:e=>(s.coalesceToken=e??fe,a)};return a},{set:(e,t)=>{const n=ie();n.seed(n.params,t,Temporal.Now.instant())}}),async final(e){if(o.signal.aborted)return null;const t=T(e),r=D(e)?i?.emitter??null:c;if(!r)return null;const s=r.getCached(t);if(n.isUndefined(s))return null;const a=O.current.inspect;return a.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const n=()=>t(o.signal.reason);o.signal.addEventListener("abort",n,{once:!0}),a.settled().then(()=>{o.signal.removeEventListener("abort",n),e()})}),r.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=T(e),n=D(e)?i?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[P]);t.useLayoutEffect(()=>{function e(e,t,r){return function(o,s){const a=r();if(s===I&&n.isNotNullable(a))return;if(n.isNotNullable(s)&&s!==I&&n.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(s,a))return;const i={processes:/* @__PURE__ */new Set},l=Promise.withResolvers(),f=L(e,o,i);function d(t){const r=z(N.current.handlers,"Error"),o=n.isNotNullable(r),s={reason:(a=t,a instanceof Error&&"AbortError"===a.name?Q.Aborted:Q.Errored),error:Y(t),action:$(e),handled:o,tasks:u};var a;c.fire(E,s),o&&r&&x.emit(r,s)}function h(){for(const e of u)if(e===f.task){u.delete(e),U.current.delete(e);break}i.processes.forEach(e=>O.current.prune(e)),i.processes.size>0&&m(),l.resolve()}let p;try{p=t(f,o)}catch(b){return d(b),void h()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(p))return Promise.resolve(p).catch(d).finally(h),l.promise;(async()=>{for await(const e of p);})().catch(d).finally(h)}}R.current++;const t=/* @__PURE__ */new Set;return N.current.handlers.forEach((n,r)=>{for(const{getChannel:o,handler:s}of n){const n=e(r,s,o);if(D(r)){if(i){const e=i.emitter;e.on(r,n),t.add(()=>e.off(r,n))}x.on(r,n),M.multicast.add(r),t.add(()=>x.off(r,n))}else W(r)?(c.on(r,n),x.on(r,n),M.broadcast.add(r),t.add(()=>{c.off(r,n),x.off(r,n)})):(x.on(r,n),t.add(()=>x.off(r,n)))}}),()=>{const e=++R.current,n=new Set(t);queueMicrotask(()=>{if(R.current!==e){for(const e of n)e();return}for(const e of U.current)e.controller.abort(),u.delete(e);U.current.clear(),A.current=k.Unmounting;const t=z(N.current.handlers,"Unmount");t&&x.emit(t),A.current=k.Unmounted;for(const e of n)e()})}},[x]),function({unicast:e,broadcast:o,dispatchers:s,scope:c,phase:a,data:i,handlers:u}){const l=t.useRef(null);t.useLayoutEffect(()=>{if(a.current===k.Mounted)return;a.current=k.Mounting;const t=z(u,"Mount");t&&e.emit(t),s.broadcast.forEach(t=>{const r=o.getCached(t);n.isNullable(r)||e.emit(t,r,I)}),c&&s.multicast.forEach(t=>{const r=c.emitter.getCached(t);n.isNullable(r)||e.emit(t,r,I)}),a.current=k.Mounted},[]),t.useLayoutEffect(()=>{if(n.isNotNullable(l.current)){const t=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(r.isNotEmpty(Object.keys(t))){const n=z(u,"Update");n&&e.emit(n,t)}}l.current=i},[i,e])}({unicast:x,broadcast:c,dispatchers:M,scope:i,phase:A,data:s(),handlers:N.current.handlers});const F=t.useMemo(()=>({dispatch(e,t){const n=T(e),r=B(e)?e.channel:void 0;return D(e)?i?J(i.emitter,n,t,r):Promise.resolve():J(W(e)?c:x,n,t,r)},get inspect(){return O.current.inspect},stream:(e,n)=>t.createElement(Ne,{action:T(e),renderer:n})}),[P,x]),H=t.useMemo(()=>[P,F,S],[P,F,S]);return H.useAction=(e,n)=>{!function(e,n,r){const o=t.useRef(r);t.useLayoutEffect(()=>{o.current=r});const s=t.useRef(n);t.useLayoutEffect(()=>{s.current=n});const c=t.useCallback((e,t)=>o.current(e,t),[]),a=t.useCallback(()=>B(s.current)?s.current.channel:void 0,[]),i=T(n),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:c})}(N,e,n)},H.dispatch=H[1].dispatch,H}(...o);return e.current=s.dispatch,s}}),[])}function ke(n){return{Boundary:function({children:t}){/* @__PURE__ */
6
+ return e(R,{env:n?.env,children:t})},useContext:function(){return Me()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)}),Scope:()=>({Boundary:function({children:n}){const r=t.useMemo(()=>({id:/* @__PURE__ */Symbol("march-hare.scope/instance"),emitter:new d}),[]);/* @__PURE__ */
7
+ return e(Z.Provider,{value:r,children:n})},useContext:function(){return Me()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)})})}}const Ae={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=new Ee;function Ue(e,t=pe.Update){return _e.annotate(t,e)}export{X as Aborted,H as Action,ke as App,R as Boundary,ee as Cache,M as Distribution,N as Lifecycle,pe as Op,pe as Operation,Q as Reason,le as Resource,Ee as State,Ae as With,Ue as annotate,oe as utils};
@@ -1 +1 @@
1
- var global,factory;global=this,factory=function(e,t,r,n,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const c=s(o),a=(e="")=>`march-hare.action/${e}`,i=(e="")=>`march-hare.action/broadcast/${e}`,u=(e="")=>`march-hare.action/multicast/${e}`,l=(e="")=>`march-hare.action.lifecycle/${e}`;class f{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel");static Name=Symbol("march-hare.brand/Name")}function d(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),r=function(r){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:r,[f.Name]:e,channel:r}};return Object.defineProperty(r,f.Action,{value:t,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,f.Name,{value:e,enumerable:!1}),r}const p=Symbol(i("Fault")),h=Symbol(i("Store"));class m{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,f.Name,{value:"Fault",enumerable:!1}),e})();static Store=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:h,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,f.Name,{value:"Store",enumerable:!1}),e})()}var b=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(b||{}),y=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(y||{});const v=e=>"symbol"==typeof e;function g(e){return t.G.isString(e)||v(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function w(e){if(t.G.isString(e))return e.startsWith(i());if(v(e))return e.description?.startsWith(i())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Broadcast in e&&e[f.Broadcast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(i())??!1}}return!1}function j(e){const r=g(e),n=t.G.isString(r)?r:r.description??"";return n.startsWith(a())&&n.slice(n.lastIndexOf("/")+1)||"unknown"}function O(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=g(e),r=v(t)?t.description??"":t;return r.startsWith(l())&&r.slice(l().length)||null}function P(e){if(t.G.isString(e))return e.startsWith(u());if(v(e))return e.description?.startsWith(u())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Multicast in e&&e[f.Multicast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(u())??!1}}return!1}var x=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Errored=2]="Errored",e))(x||{});class E extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class M extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}let A=(e=21)=>{let t="",r=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&r[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 N{[r.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 r=new N(this.value,this.operation);return r.property=e,r.process=t,r}}class _{static immer=(()=>{r.enablePatches();const e=new r.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=A}function R(e,t){const r="string"==typeof t?""===t?[]:t.split("."):t;let n=e;for(const o of r){if(null==n)return;n=n[o]}return n}function T(e){if(t.G.isNullable(e)||B(e))return e;if(t.G.isArray(e))return e.map(e=>T(e));if(t.G.isObject(e)&&L(e)){const t=Object.entries(e).map(([e,t])=>[e,T(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 B(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 F(e,r,n,o,s,c){return function a(i,u=r.path){if(i instanceof N){const r=R(n,u.join("."));if(Object.entries(i).filter(([e,t])=>!N.keys.has(e)&&t instanceof N).forEach(([e,t])=>a(t,u.concat(e))),B(i.value)){if(e===G.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?R(n,a.join(".")):n;return t.G.isNullable(l)||W(l,i,u.at(-1),o,s,c),r??i.value}if(e===G.Hydrate){const e=T(a(i.value,u));return W(e,i,null,o,s,c),e}const l=r??T(i.value);return W(l,i,null,o,s,c),t.G.isNullable(r)?l:(a(i.value,u),r)}if(t.G.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(t.G.isObject(i)&&!L(i))return i;if(t.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),r=Object.fromEntries(t);if(e===G.Hydrate){const e=T(r);return Object.entries(i).forEach(([t,r])=>{r instanceof N&&B(r.value)&&W(e,r,t,o,s,c)}),e}return r}return i}(r.value)}function W(e,t,r,n,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(r,n),...a])}class ${#e={};#t;#r=new Map;#n=new Set;#o=!1;constructor(e=U){this.#t=e}static pk(){return A()}static"κ"=$.pk;annotate(e,t){return new N(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,r,n,o,s){function c(o){const s=o.at(-1),c=R(e(),o),a=o.slice(0,-1),i=t.A.isNotEmpty(a)?R(e(),a):e();return[...t.G.isObject(c)||t.G.isArray(c)?r.get(n(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(i)?r.get(n(i))?.filter(e=>e.property===s)??[]:[]]}return function r(n){return new Proxy(()=>{},{get:(a,i)=>"pending"===i?()=>!t.A.isEmpty(c(n)):"remaining"===i?()=>t.A.length(c(n)):"box"===i?()=>({value:R(e(),n),inspect:r(n)}):"is"===i?e=>c(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>t.A.head(c(n))?.value??R(e(),n):"settled"===i?()=>new Promise(r=>{if(t.A.isEmpty(c(n)))return r(R(e(),n));const a=()=>{t.A.isEmpty(c(n))&&(s(a),r(R(e(),n)))};o(a)}):r([...n,String(i)])})}([])}(()=>this.#e,this.#r,this.#t,e=>this.#n.add(e),e=>this.#n.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 r=Symbol("process"),[,n]=_.immer.produceWithPatches(this.#e,t);return this.#e=n.reduce((t,n)=>_.immer.applyPatches(t,[{...n,value:F(e,n,t,r,this.#r,this.#t)}]),this.#e),this.#e=T(this.#e),this.#c(),r}prune(e){this.#r.forEach((r,n)=>{const o=r.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#r.delete(n):this.#r.set(n,o)}),this.#c()}#c(){this.#n.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#n.add(t),()=>this.#n.delete(t)}}const D=new $;function I(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,q={exports:{}},z=(H||(H=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,c){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new o(n,s||e,c),i=r?r+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,o=[];if(0===this._eventsCount)return o;for(n in e=this._events)t.call(e,n)&&o.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[r?r+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var n=0,o=t.length,s=new Array(o);n<o;n++)s[n]=t[n].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[r?r+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,n,o,s,c){var a=r?r+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,n),!0;case 4:return l.fn.call(l.context,t,n,o),!0;case 5:return l.fn.call(l.context,t,n,o,s),!0;case 6:return l.fn.call(l.context,t,n,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,n);break;case 4:l[u].fn.call(l[u].context,t,n,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,r){return s(this,e,t,r,!1)},a.prototype.once=function(e,t,r){return s(this,e,t,r,!0)},a.prototype.removeListener=function(e,t,n,o){var s=r?r+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||n&&a.context!==n||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||n&&a[i].context!==n)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=r?r+e:e]&&c(this,t):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,e.exports=a}(q)),q.exports);const J=I(z);class K 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 V=c.createContext(new K);function Q(){return c.useContext(V)}function X({children:e}){const t=c.useMemo(()=>new K,[]);return n.jsx(V.Provider,{value:t,children:e})}const Y=c.createContext(new Set);function Z({children:e}){const t=c.useMemo(()=>new Set,[]);return n.jsx(Y.Provider,{value:t,children:e})}const ee=c.createContext({current:{}});function te(){const e=c.useContext(ee);return c.useMemo(()=>new Proxy({},{get:(t,r)=>Reflect.get(e.current,r),has:(t,r)=>r in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,r){const n=Object.getOwnPropertyDescriptor(e.current,r);if(void 0!==n)return{...n,configurable:!0}},set(){throw new TypeError("Store is read-only outside `context.actions.produce`. Mutate via produce(({ store }) => { store.x = ... }) instead.")}}),[e])}function re({initial:e,children:t}){const r=c.useRef(e),o=Q();return void 0===o.getCached(h)&&o.setCache(h,r.current),n.jsx(ee.Provider,{value:r,children:t})}const ne=c.createContext(null);function oe(){return c.useContext(ne)}function se(e,t){return e?.get(t)??null}const ce=Symbol(((e="")=>`march-hare/replay${e}`)());function ae(e,t,...r){e instanceof K&&e.setCache(t,r[0]);const n=e.listeners(t);return 0===n.length?Promise.resolve():Promise.all(n.map(e=>Promise.resolve(e(...r)))).then(()=>{})}function ie(e,t){for(const r of e.keys())if(S(r)===t)return r;return null}const ue=Symbol("march-hare.unset");function le(){const[,e]=c.useReducer(e=>e+1,0);return e}function fe(){return{data:ue,at:null,else:e=>e}}function de(e,t){return{data:e,at:t,else:t=>e}}function pe(e){if(e instanceof Error){if("TimeoutError"===e.name)return x.Timedout;if("AbortError"===e.name)return x.Supplanted}return x.Errored}function he(e){const t=new Map,r=e??{get:e=>t.get(e)??null,set:(e,r)=>{t.set(e,r)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=r.get(e);if(null===t)return fe();const n=JSON.parse(t);return de(n.data,Temporal.Instant.from(n.at))}catch{return fe()}},set(e,t){if(t.data===ue||null===t.at)return!1;try{return r.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){r.remove(e)},clear(){r.clear()}}}function me(e,t){return new Promise((r,n)=>{if(t?.aborted)return void n(new E);const o=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(o),n(new E)},{once:!0})})}async function be(e,t,r){if(t?.aborted)throw new E;for(;;){if(await r())return;await me(e,t)}}function ye(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const ve=Object.freeze(Object.defineProperty({__proto__:null,pk:ye,poll:be,sleep:me,unset:ue,"ζ":me,"κ":ye,"π":be},Symbol.toStringTag,{value:"Module"})),ge=new WeakMap;function we(e){return JSON.stringify(e)}let je=null;function Oe(){if(null===je)throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(cat({ id: 5 })).");const e=je;return je=null,e}const Se=c.createContext(new Map);function Pe({action:e,renderer:r}){const n=Q(),o=c.useContext(Se),s=le(),a=c.useMemo(()=>{const t=o.get(e);if(t)return t;const r=new $,s=n.getCached(e);void 0!==s&&r.hydrate({value:s});const c={state:r,listeners:new Set};return o.set(e,c),c},[e,n,o]);c.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(s),n.on(e,t),()=>{a.listeners.delete(s),n.off(e,t)}},[e,n,a]);const i=a.state.model?.value;return t.G.isNullable(i)?null:r(i,a.state.inspect.value)}e.AbortError=E,e.Action=(e="",t=b.Unicast)=>{const r=t===b.Broadcast?Symbol(i(e)):t===b.Multicast?Symbol(u(e)):Symbol(a(e)),n=function(t){return{[f.Action]:r,[f.Payload]:void 0,[f.Channel]:t,[f.Name]:e,channel:t}};return Object.defineProperty(n,f.Action,{value:r,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,f.Name,{value:e,enumerable:!1}),t===b.Broadcast&&Object.defineProperty(n,f.Broadcast,{value:!0,enumerable:!1}),t===b.Multicast&&Object.defineProperty(n,f.Multicast,{value:!0,enumerable:!1}),n},e.Boundary=function({store:e,children:t}){return n.jsx(X,{children:n.jsx(re,{initial:e??{},children:n.jsx(Z,{children:t})})})},e.Cache=he,e.Distribution=b,e.Lifecycle=m,e.Op=C,e.Operation=C,e.Reason=x,e.Resource=function(e,t){const r=t??function(e){let t=ge.get(e);return void 0===t&&(t=he(),ge.set(e,t)),t}(e),n=e=>{const t=r.get(we(e));return t.data===ue||null===t.at?{data:ue,at:null}:{data:t.data,at:t.at}},o=(t,n,o)=>e({store:t,controller:n,params:o}).then(e=>(r.set(we(o),de(e,Temporal.Now.instant())),e)),s=(e,t,n)=>{r.set(we(e),de(t,n))};return function(e){const t=e??{};je={run:o,read:n,seed:s,params:t},queueMicrotask(()=>{null!==je&&je.params===t&&(je=null)});const{data:r}=n(t);return r===ue?null:r}},e.State=$,e.TimeoutError=M,e.With={Update:e=>(t,r)=>{t.actions.produce(t=>{t.model[e]=r})},Invert:e=>t=>{t.actions.produce(t=>{t.model[e]=!t.model[e]})}},e.annotate=function(e,t=C.Update){return D.annotate(t,e)},e.useActions=function(...e){const n=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],o=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),s=Q(),a=oe(),i=c.useContext(Y),u=te(),l=c.useContext(ee),f=le(),d=c.useRef(!1),m=c.useRef(null),b=c.useRef(new $);d.current||(d.current=!0,m.current=b.current.hydrate(n));const[v,S]=c.useState(()=>b.current.model),x=function(e){const t=c.useRef(e);return t.current=e,c.useMemo(()=>{return r=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>r.current[t],enumerable:!0}),e),{});var r},[e])}(o()),E=c.useMemo(()=>new J,[]),M=c.useRef({handlers:new Map});M.current.handlers=new Map;const A=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),G=c.useRef(y.Mounting),k=c.useRef(new Set),N=c.useRef(0),_=c.useCallback((e,t,n)=>{const o=new AbortController,c={controller:o,action:e,payload:t};return i.add(c),k.current.add(c),{model:b.current.model,get phase(){return G.current},task:c,data:x,tasks:i,store:u,actions:{produce(e){if(o.signal.aborted)return;const t=l.current,c=b.current.produce(t=>{l.current=r.produce(l.current,r=>{e({model:t,inspect:b.current.inspect,store:r})})});S(b.current.model),l.current!==t&&s.emit(h,l.current),n.processes.add(c),m.current&&(n.processes.add(m.current),m.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const r=g(e),n=O(e)?e.channel:void 0;if(P(e)){const e=se(a,r);return e?ae(e.emitter,r,t,n):Promise.resolve()}return ae(w(e)?s:E,r,t,n)},annotate:(e,t=C.Update)=>b.current.annotate(t,e),resource:Object.assign(function(e){const t=Oe(),r=()=>t.run(l.current,o,t.params);return{then:(e,t)=>r().then(e,t),exceeds:e=>{const{data:n,at:o}=t.read(t.params);if(n!==ue&&null!==o){const t=Temporal.Now.instant().since(o),r=Temporal.Duration.from(e);if(Temporal.Duration.compare(t,r)<=0)return Promise.resolve(n)}return r()}}},{set:(e,t)=>{const r=Oe();r.seed(r.params,t,Temporal.Now.instant())}}),async resolution(e){if(o.signal.aborted)return null;const t=g(e),r=P(e)?se(a,t)?.emitter??null:s;if(!r)return null;if(void 0===r.getCached(t))return null;const n=b.current.inspect;return n.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const r=()=>t(o.signal.reason);o.signal.addEventListener("abort",r,{once:!0}),n.settled().then(()=>{o.signal.removeEventListener("abort",r),e()})}),r.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=g(e),r=P(e)?se(a,t)?.emitter??null:s;return r?r.getCached(t)??null:null}}}},[v]);c.useLayoutEffect(()=>{function e(e,r,n){return function(o,c){const a=n();if(c===ce&&t.G.isNotNullable(a))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(a)&&!function(e,t){for(const r of Object.keys(e))if(t[r]!==e[r])return!1;return!0}(c,a))return;const u={processes:new Set},l=Promise.withResolvers(),d=_(e,o,u);function h(t){const r=ie(M.current.handlers,"Error"),n=null!==r,o={reason:pe(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:j(e),handled:n,tasks:i};var c;s.fire(p,o),n&&r&&E.emit(r,o)}function m(){for(const e of i)if(e===d.task){i.delete(e),k.current.delete(e);break}u.processes.forEach(e=>b.current.prune(e)),u.processes.size>0&&f(),l.resolve()}let y;try{y=r(d,o)}catch(v){return h(v),void m()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(y))return Promise.resolve(y).catch(h).finally(m),l.promise;(async()=>{for await(const e of y);})().catch(h).finally(m)}}N.current++;const r=new Set;return M.current.handlers.forEach((t,n)=>{for(const{getChannel:o,handler:c}of t){const t=e(n,c,o);if(P(n)){if(a)for(const e of a.values()){const o=e.emitter;o.on(n,t),r.add(()=>o.off(n,t))}E.on(n,t),A.multicast.add(n),r.add(()=>E.off(n,t))}else w(n)?(s.on(n,t),E.on(n,t),A.broadcast.add(n),r.add(()=>{s.off(n,t),E.off(n,t)})):(E.on(n,t),r.add(()=>E.off(n,t)))}}),()=>{const e=++N.current,t=new Set(r);queueMicrotask(()=>{if(N.current!==e){for(const e of t)e();return}for(const e of k.current)e.controller.abort(),i.delete(e);k.current.clear(),G.current=y.Unmounting;const r=ie(M.current.handlers,"Unmount");r&&E.emit(r),G.current=y.Unmounted;for(const e of t)e()})}},[E]),function({unicast:e,broadcast:r,dispatchers:n,scope:o,phase:s,data:a,handlers:i}){const u=c.useRef(null);c.useLayoutEffect(()=>{if(s.current===y.Mounted)return;s.current=y.Mounting;const c=ie(i,"Mount");c&&e.emit(c),n.broadcast.forEach(n=>{const o=r.getCached(n);t.G.isNullable(o)||e.emit(n,o,ce)}),o&&n.multicast.forEach(r=>{for(const n of o.values()){const o=n.emitter.getCached(r);t.G.isNullable(o)||e.emit(r,o,ce)}}),s.current=y.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const r=function(e,t){return Object.keys(t).reduce((r,n)=>e[n]!==t[n]?{...r,[n]:t[n]}:r,{})}(u.current,a);if(t.A.isNotEmpty(Object.keys(r))){const t=ie(i,"Update");t&&e.emit(t,r)}}u.current=a},[a,e])}({unicast:E,broadcast:s,dispatchers:A,scope:a,phase:G,data:o(),handlers:M.current.handlers});const R=c.useMemo(()=>({dispatch(e,t){const r=g(e),n=O(e)?e.channel:void 0;if(P(e)){const e=se(a,r);return e?ae(e.emitter,r,t,n):Promise.resolve()}return ae(w(e)?s:E,r,t,n)},get inspect(){return b.current.inspect},stream:(e,t)=>c.createElement(Pe,{action:g(e),renderer:t})}),[v,E]),T=c.useMemo(()=>[v,R,x],[v,R,x]);return T.useAction=(e,t)=>{!function(e,t,r){const n=c.useRef(r);c.useLayoutEffect(()=>{n.current=r});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>n.current(e,t),[]),a=c.useCallback(()=>O(o.current)?o.current.channel:void 0,[]),i=g(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:s})}(M,e,t)},T.dispatch=T[1].dispatch,T},e.useStore=te,e.utils=ve,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`,o=g(e);return{[r](e){const r=oe(),s=c.useMemo(()=>({action:o,emitter:new K}),[]),a=c.useMemo(()=>{const e=new Map(r??[]);return e.set(o,s),e},[r,s]);return n.jsx(ne.Provider,{value:a,children:n.jsx(t,{...e})})}}[r]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("immer"),require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","immer","react/jsx-runtime","react"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).MarchHare={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
1
+ var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=s(n);function a(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i,u={exports:{}},l=(i||(i=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new o(r,s||e,c),i=n?n+t:t;return e._events[i]?e._events[i].fn?e._events[i]=[e._events[i],a]:e._events[i].push(a):(e._events[i]=a,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),a.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},a.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},a.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},a.prototype.emit=function(e,t,r,o,s,c){var a=n?n+e:e;if(!this._events[a])return!1;var i,u,l=this._events[a],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(u=1,i=new Array(f-1);u<f;u++)i[u-1]=arguments[u];l.fn.apply(l.context,i)}else{var d,h=l.length;for(u=0;u<h;u++)switch(l[u].once&&this.removeListener(e,l[u].fn,void 0,!0),f){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,t);break;case 3:l[u].fn.call(l[u].context,t,r);break;case 4:l[u].fn.call(l[u].context,t,r,o);break;default:if(!i)for(d=1,i=new Array(f-1);d<f;d++)i[d-1]=arguments[d];l[u].fn.apply(l[u].context,i)}}return!0},a.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},a.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},a.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var a=this._events[s];if(a.fn)a.fn!==t||o&&!a.once||r&&a.context!==r||c(this,s);else{for(var i=0,u=[],l=a.length;i<l;i++)(a[i].fn!==t||o&&!a[i].once||r&&a[i].context!==r)&&u.push(a[i]);u.length?this._events[s]=1===u.length?u[0]:u:c(this,s)}return this},a.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,e.exports=a}(u)),u.exports);const f=a(l);class d extends f{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 h=c.createContext(new d);function p(){return c.useContext(h)}function m({children:e}){const n=c.useMemo(()=>new d,[]);return t.jsx(h.Provider,{value:n,children:e})}const b=c.createContext(new Set);function y({children:e}){const n=c.useMemo(()=>new Set,[]);return t.jsx(b.Provider,{value:n,children:e})}const v=c.createContext({current:{}});function g(){const e=c.useContext(v);return c.useMemo(()=>new Proxy({},{get:(t,n)=>Reflect.get(e.current,n),has:(t,n)=>n in e.current,ownKeys:()=>Reflect.ownKeys(e.current),getOwnPropertyDescriptor(t,n){const o=Object.getOwnPropertyDescriptor(e.current,n);if(!r.G.isUndefined(o))return{...o,configurable:!0}},set(){throw new TypeError("Env is read-only outside `context.actions.produce`. Mutate via produce(({ env }) => { env.x = ... }) instead.")}}),[e])}const w=(e="")=>`march-hare.action/${e}`,j=(e="")=>`march-hare.action/broadcast/${e}`,O=(e="")=>`march-hare.action/multicast/${e}`,x=(e="")=>`march-hare.action.lifecycle/${e}`;class P{static Payload=Symbol("march-hare.brand/Payload");static Broadcast=Symbol("march-hare.brand/Broadcast");static Multicast=Symbol("march-hare.brand/Multicast");static Action=Symbol("march-hare.brand/Action");static Channel=Symbol("march-hare.brand/Channel");static Name=Symbol("march-hare.brand/Name")}function S(e){const t=Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[P.Action]:t,[P.Payload]:void 0,[P.Channel]:n,[P.Name]:e,channel:n}};return Object.defineProperty(n,P.Action,{value:t,enumerable:!1}),Object.defineProperty(n,P.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,P.Name,{value:e,enumerable:!1}),n}const E=Symbol(j("Fault")),C=Symbol(j("Env"));class G{static Mount(){return S("Mount")}static Unmount(){return S("Unmount")}static Error(){return S("Error")}static Update(){return S("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,P.Action,{value:E,enumerable:!1}),Object.defineProperty(e,P.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,P.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,P.Name,{value:"Fault",enumerable:!1}),e})();static Env=(()=>{const e={};return Object.defineProperty(e,P.Action,{value:C,enumerable:!1}),Object.defineProperty(e,P.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,P.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,P.Name,{value:"Env",enumerable:!1}),e})()}var A=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(A||{}),M=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(M||{});function N({initial:e,children:n}){const o=c.useRef(e),s=p();return r.G.isUndefined(s.getCached(C))&&s.setCache(C,o.current),t.jsx(v.Provider,{value:o,children:n})}const k=c.createContext(new WeakMap);function R({children:e}){const n=c.useMemo(()=>new WeakMap,[]);return t.jsx(k.Provider,{value:n,children:e})}function _({env:e,children:n}){return t.jsx(m,{children:t.jsx(N,{initial:e??{},children:t.jsx(y,{children:t.jsx(R,{children:n})})})})}const U=e=>"symbol"==typeof e;function L(e){return r.G.isString(e)||U(e)?e:(r.G.isObject(e)||r.G.isFunction(e))&&P.Action in e?e[P.Action]:e}function T(e){if(r.G.isString(e))return e.startsWith(j());if(U(e))return e.description?.startsWith(j())??!1;if(r.G.isObject(e)||r.G.isFunction(e)){if(P.Broadcast in e&&e[P.Broadcast])return!0;if(P.Action in e){const t=e[P.Action];return t.description?.startsWith(j())??!1}}return!1}function W(e){const t=L(e),n=r.G.isString(t)?t:t.description??"";return n.startsWith(w())&&n.slice(n.lastIndexOf("/")+1)||"unknown"}function B(e){return r.G.isObject(e)&&P.Channel in e&&"channel"in e}function $(e){const t=L(e),n=U(t)?t.description??"":t;return n.startsWith(x())&&n.slice(x().length)||null}function F(e){if(r.G.isString(e))return e.startsWith(O());if(U(e))return e.description?.startsWith(O())??!1;if(r.G.isObject(e)||r.G.isFunction(e)){if(P.Multicast in e&&e[P.Multicast])return!0;if(P.Action in e){const t=e[P.Action];return t.description?.startsWith(O())??!1}}return!1}const D=Symbol(((e="")=>`march-hare/replay${e}`)());function I(e,t,...n){e instanceof d&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function H(e,t){for(const n of e.keys())if($(n)===t)return n;return null}const q=Symbol("march-hare.unset");function z(){const[,e]=c.useReducer(e=>e+1,0);return e}function J(){return{data:q,at:null,else:e=>e}}function K(e,t){return{data:e,at:t,else:t=>e}}var V=(e=>(e[e.Aborted=0]="Aborted",e[e.Errored=1]="Errored",e))(V||{});class Q extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}function X(e){return e instanceof Error?e:new Error(String(e))}const Y=c.createContext(null);function Z(e){const t=new Map,n=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=n.get(e);if(r.G.isNull(t))return J();const o=JSON.parse(t);return K(o.data,Temporal.Instant.from(o.at))}catch{return J()}},set(e,t){if(t.data===q||r.G.isNull(t.at))return!1;try{return n.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){n.remove(e)},clear(){n.clear()}}}function ee(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new Q);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Q)},{once:!0})})}async function te(e,t,n){if(t?.aborted)throw new Q;for(;;){if(await n())return;await ee(e,t)}}function ne(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const re=Object.freeze(Object.defineProperty({__proto__:null,pk:ne,poll:te,sleep:ee,unset:q,"ζ":ee,"κ":ne,"π":te},Symbol.toStringTag,{value:"Module"})),oe=new WeakMap;function se(e){return JSON.stringify(e)}let ce=null;function ae(){if(r.G.isNull(ce))throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(resource.cat({ id: 5 })).");const e=ce;return ce=null,e}function ie(e,t){const n=e=>{const n=t.get(se(e));return n.data===q||r.G.isNull(n.at)?{data:q,at:null}:{data:n.data,at:n.at}},o=(n,r,o,s)=>e({env:n,controller:r,params:o,dispatch:s}).then(e=>(t.set(se(o),K(e,Temporal.Now.instant())),e)),s=(e,n,r)=>{t.set(se(e),K(n,r))};return function(e){const t=e??{};ce={run:o,read:n,seed:s,params:t},queueMicrotask(()=>{r.G.isNotNullable(ce)&&ce.params===t&&(ce=null)});const{data:c}=n(t);return c===q?null:c}}function ue(e){return ie(e,function(e){let t=oe.get(e);return r.G.isUndefined(t)&&(t=Z(),oe.set(e,t)),t}(e))}(ue||(ue={})).Cachable=function(e,t){return ie(t,e)};const le=Symbol("march-hare.coalesce/default");function fe(e,t){return new Promise((n,r)=>{if(t.aborted)return void r(t.reason);const o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})})}let de=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var he=(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))(he||{}),pe=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(pe||{}),me=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(me||{});class be{[o.immerable]=!0;static keys=new Set(Object.values(me));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new be(this.value,this.operation);return n.property=e,n.process=t,n}}class ye{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=de}function ve(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 ge(e){if(r.G.isNullable(e)||Oe(e))return e;if(r.G.isArray(e))return e.map(e=>ge(e));if(r.G.isObject(e)&&je(e)){const t=Object.entries(e).map(([e,t])=>[e,ge(t)]);return{...Object.fromEntries(t),[ye.tag]:e[ye.tag]??ye.id()}}return e}function we(e){if(Array.isArray(e))return e.filter(e=>ye.tag in e).map(e=>e[ye.tag]??"").join(",");const t=e[ye.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function je(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Oe(e){return r.G.isNullable(e)||r.G.isString(e)||r.G.isNumber(e)||r.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function xe(e,t,n,o,s,c){return function a(i,u=t.path){if(i instanceof be){const t=ve(n,u.join("."));if(Object.entries(i).filter(([e,t])=>!be.keys.has(e)&&t instanceof be).forEach(([e,t])=>a(t,u.concat(e))),Oe(i.value)){if(e===pe.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?ve(n,a.join(".")):n;return r.G.isNullable(l)||Pe(l,i,u.at(-1),o,s,c),t??i.value}if(e===pe.Hydrate){const e=ge(a(i.value,u));return Pe(e,i,null,o,s,c),e}const l=t??ge(i.value);return Pe(l,i,null,o,s,c),r.G.isNullable(t)?l:(a(i.value,u),t)}if(r.G.isArray(i))return i.map((e,t)=>a(e,u.concat(t)));if(r.G.isObject(i)&&!je(i))return i;if(r.G.isObject(i)){const t=Object.entries(i).map(([e,t])=>[e,a(t,u.concat(e))]),n=Object.fromEntries(t);if(e===pe.Hydrate){const e=ge(n);return Object.entries(i).forEach(([t,n])=>{n instanceof be&&Oe(n.value)&&Pe(e,n,t,o,s,c)}),e}return n}return i}(t.value)}function Pe(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class Se{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=we){this.#t=e}static pk(){return de()}static"κ"=Se.pk;annotate(e,t){return new be(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,t,n,o,s){function c(o){const s=o.at(-1),c=ve(e(),o),a=o.slice(0,-1),i=r.A.isNotEmpty(a)?ve(e(),a):e();return[...r.G.isObject(c)||r.G.isArray(c)?t.get(n(c))?.filter(e=>r.G.isNullable(e.property))??[]:[],...r.G.isObject(i)?t.get(n(i))?.filter(e=>e.property===s)??[]:[]]}return function t(n){return new Proxy(()=>{},{get:(a,i)=>"pending"===i?()=>!r.A.isEmpty(c(n)):"remaining"===i?()=>r.A.length(c(n)):"box"===i?()=>({value:ve(e(),n),inspect:t(n)}):"is"===i?e=>c(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>r.A.head(c(n))?.value??ve(e(),n):"settled"===i?()=>new Promise(t=>{if(r.A.isEmpty(c(n)))return t(ve(e(),n));const a=()=>{r.A.isEmpty(c(n))&&(s(a),t(ve(e(),n)))};o(a)}):t([...n,String(i)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(pe.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(pe.Produce,e)}#s(e,t){const n=Symbol("process"),[,r]=ye.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>ye.immer.applyPatches(t,[{...r,value:xe(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=ge(this.#e),this.#c(),n}prune(e){this.#n.forEach((t,n)=>{const o=t.filter(t=>t.process!==e);r.A.isEmpty(o)?this.#n.delete(n):this.#n.set(n,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const Ee=c.createContext(new Map);function Ce({action:e,renderer:t}){const n=p(),o=c.useContext(Ee),s=z(),a=c.useMemo(()=>{const t=o.get(e);if(t)return t;const s=new Se,c=n.getCached(e);r.G.isNotNullable(c)&&s.hydrate({value:c});const a={state:s,listeners:new Set};return o.set(e,a),a},[e,n,o]);c.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(s),n.on(e,t),()=>{a.listeners.delete(s),n.off(e,t)}},[e,n,a]);const i=a.state.model?.value;return r.G.isNullable(i)?null:t(i,a.state.inspect.value)}function Ge(){const e=c.useRef(null);return c.useMemo(()=>({actions:{dispatch:function(t,n){const r=e.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(t,n)}},useActions:function(...t){const n=function(...e){const t=r.G.isUndefined(e[0])||r.G.isFunction(e[0])?{}:e[0],n=r.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),s=p(),a=c.useContext(Y),i=c.useContext(b),u=g(),l=c.useContext(v),d=c.useContext(k),h=z(),m=c.useRef(!1),y=c.useRef(null),w=c.useRef(new Se);m.current||(m.current=!0,y.current=w.current.hydrate(t));const[j,O]=c.useState(()=>w.current.model),x=function(e){const t=c.useRef(e);return t.current=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])}(n()),P=c.useMemo(()=>new f,[]),S=c.useRef({handlers:new Map});S.current.handlers=new Map;const G=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),A=c.useRef(M.Mounting),N=c.useRef(new Set),R=c.useRef(0),_=c.useCallback((e,t,n)=>{const c=new AbortController,f={controller:c,action:e,payload:t};return i.add(f),N.current.add(f),{model:w.current.model,get phase(){return A.current},task:f,data:x,tasks:i,env:u,actions:{produce(e){if(c.signal.aborted)return;const t=l.current,r=w.current.produce(t=>{l.current=o.produce(l.current,n=>{e({model:t,inspect:w.current.inspect,env:n})})});O(w.current.model),l.current!==t&&s.emit(C,l.current),n.processes.add(r),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t){if(c.signal.aborted)return Promise.resolve();const n=L(e),r=B(e)?e.channel:void 0;return F(e)?a?I(a.emitter,n,t,r):Promise.resolve():I(T(e)?s:P,n,t,r)},annotate:(e,t=he.Update)=>w.current.annotate(t,e),get inspect(){return w.current.inspect},resource:Object.assign(function(e){const t=ae(),n=(e,t)=>{if(c.signal.aborted)return Promise.resolve();const n=e,r=L(n);return F(n)?a?I(a.emitter,r,t,void 0):Promise.resolve():T(n)?I(s,r,t,void 0):Promise.resolve()},o={exceedsWindow:null,coalesceToken:void 0},i={then:(e,s)=>(()=>{if(r.G.isNotNullable(o.exceedsWindow)){const{data:e,at:n}=t.read(t.params);if(e!==q&&r.G.isNotNullable(n)){const t=Temporal.Now.instant().since(n),r=Temporal.Duration.from(o.exceedsWindow);if(Temporal.Duration.compare(t,r)<=0)return Promise.resolve(e)}}if(r.G.isUndefined(o.coalesceToken))return t.run(l.current,c,t.params,n);let e=d.get(t.run);r.G.isUndefined(e)&&(e=new Map,d.set(t.run,e));const s=e,a=`${JSON.stringify(t.params)}|${function(e){switch(typeof e){case"string":return`s:${e}`;case"number":return`n:${e}`;case"bigint":return`i:${e.toString()}`;case"boolean":return`b:${e}`;case"symbol":return`y:${e.description??String(e)}`;default:return`o:${JSON.stringify(e)}`}}(o.coalesceToken)}`,i=s.get(a);if(i)return fe(i,c.signal);const u=new AbortController,f=t.run(l.current,u,t.params,n).finally(()=>{s.delete(a)});return s.set(a,f),fe(f,c.signal)})().then(e,s),exceeds:e=>(o.exceedsWindow=e,i),coalesce:e=>(o.coalesceToken=e??le,i)};return i},{set:(e,t)=>{const n=ae();n.seed(n.params,t,Temporal.Now.instant())}}),async final(e){if(c.signal.aborted)return null;const t=L(e),n=F(e)?a?.emitter??null:s;if(!n)return null;const o=n.getCached(t);if(r.G.isUndefined(o))return null;const i=w.current.inspect;return i.pending()&&await new Promise((e,t)=>{if(c.signal.aborted)return void t(c.signal.reason);const n=()=>t(c.signal.reason);c.signal.addEventListener("abort",n,{once:!0}),i.settled().then(()=>{c.signal.removeEventListener("abort",n),e()})}),n.getCached(t)??null},peek(e){if(c.signal.aborted)return null;const t=L(e),n=F(e)?a?.emitter??null:s;return n?n.getCached(t)??null:null}}}},[j]);c.useLayoutEffect(()=>{function e(e,t,n){return function(o,c){const a=n();if(c===D&&r.G.isNotNullable(a))return;if(r.G.isNotNullable(c)&&c!==D&&r.G.isNotNullable(a)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,a))return;const u={processes:new Set},l=Promise.withResolvers(),f=_(e,o,u);function d(t){const n=H(S.current.handlers,"Error"),o=r.G.isNotNullable(n),c={reason:(a=t,a instanceof Error&&"AbortError"===a.name?V.Aborted:V.Errored),error:X(t),action:W(e),handled:o,tasks:i};var a;s.fire(E,c),o&&n&&P.emit(n,c)}function p(){for(const e of i)if(e===f.task){i.delete(e),N.current.delete(e);break}u.processes.forEach(e=>w.current.prune(e)),u.processes.size>0&&h(),l.resolve()}let m;try{m=t(f,o)}catch(b){return d(b),void p()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(m))return Promise.resolve(m).catch(d).finally(p),l.promise;(async()=>{for await(const e of m);})().catch(d).finally(p)}}R.current++;const t=new Set;return S.current.handlers.forEach((n,r)=>{for(const{getChannel:o,handler:c}of n){const n=e(r,c,o);if(F(r)){if(a){const e=a.emitter;e.on(r,n),t.add(()=>e.off(r,n))}P.on(r,n),G.multicast.add(r),t.add(()=>P.off(r,n))}else T(r)?(s.on(r,n),P.on(r,n),G.broadcast.add(r),t.add(()=>{s.off(r,n),P.off(r,n)})):(P.on(r,n),t.add(()=>P.off(r,n)))}}),()=>{const e=++R.current,n=new Set(t);queueMicrotask(()=>{if(R.current!==e){for(const e of n)e();return}for(const e of N.current)e.controller.abort(),i.delete(e);N.current.clear(),A.current=M.Unmounting;const t=H(S.current.handlers,"Unmount");t&&P.emit(t),A.current=M.Unmounted;for(const e of n)e()})}},[P]),function({unicast:e,broadcast:t,dispatchers:n,scope:o,phase:s,data:a,handlers:i}){const u=c.useRef(null);c.useLayoutEffect(()=>{if(s.current===M.Mounted)return;s.current=M.Mounting;const c=H(i,"Mount");c&&e.emit(c),n.broadcast.forEach(n=>{const o=t.getCached(n);r.G.isNullable(o)||e.emit(n,o,D)}),o&&n.multicast.forEach(t=>{const n=o.emitter.getCached(t);r.G.isNullable(n)||e.emit(t,n,D)}),s.current=M.Mounted},[]),c.useLayoutEffect(()=>{if(r.G.isNotNullable(u.current)){const t=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,a);if(r.A.isNotEmpty(Object.keys(t))){const n=H(i,"Update");n&&e.emit(n,t)}}u.current=a},[a,e])}({unicast:P,broadcast:s,dispatchers:G,scope:a,phase:A,data:n(),handlers:S.current.handlers});const U=c.useMemo(()=>({dispatch(e,t){const n=L(e),r=B(e)?e.channel:void 0;return F(e)?a?I(a.emitter,n,t,r):Promise.resolve():I(T(e)?s:P,n,t,r)},get inspect(){return w.current.inspect},stream:(e,t)=>c.createElement(Ce,{action:L(e),renderer:t})}),[j,P]),$=c.useMemo(()=>[j,U,x],[j,U,x]);return $.useAction=(e,t)=>{!function(e,t,n){const r=c.useRef(n);c.useLayoutEffect(()=>{r.current=n});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>r.current(e,t),[]),a=c.useCallback(()=>B(o.current)?o.current.channel:void 0,[]),i=L(t),u=e.current.handlers.get(i)??new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:s})}(S,e,t)},$.dispatch=$[1].dispatch,$}(...t);return e.current=n.dispatch,n}}),[])}const Ae=new Se;e.Aborted=Q,e.Action=(e="",t=A.Unicast)=>{const n=t===A.Broadcast?Symbol(j(e)):t===A.Multicast?Symbol(O(e)):Symbol(w(e)),r=function(t){return{[P.Action]:n,[P.Payload]:void 0,[P.Channel]:t,[P.Name]:e,channel:t}};return Object.defineProperty(r,P.Action,{value:n,enumerable:!1}),Object.defineProperty(r,P.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,P.Name,{value:e,enumerable:!1}),t===A.Broadcast&&Object.defineProperty(r,P.Broadcast,{value:!0,enumerable:!1}),t===A.Multicast&&Object.defineProperty(r,P.Multicast,{value:!0,enumerable:!1}),r},e.App=function(e){return{Boundary:function({children:n}){return t.jsx(_,{env:e?.env,children:n})},useContext:function(){return Ge()},useEnv:function(){return g()},Resource:Object.assign(function(e){return ue(e)},{Cachable:(e,t)=>ue.Cachable(e,t)}),Scope:()=>({Boundary:function({children:e}){const n=c.useMemo(()=>({id:Symbol("march-hare.scope/instance"),emitter:new d}),[]);return t.jsx(Y.Provider,{value:n,children:e})},useContext:function(){return Ge()},useEnv:function(){return g()},Resource:Object.assign(function(e){return ue(e)},{Cachable:(e,t)=>ue.Cachable(e,t)})})}},e.Boundary=_,e.Cache=Z,e.Distribution=A,e.Lifecycle=G,e.Op=he,e.Operation=he,e.Reason=V,e.Resource=ue,e.State=Se,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=he.Update){return Ae.annotate(t,e)},e.utils=re,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("react/jsx-runtime"),require("react"),require("@mobily/ts-belt"),require("immer")):"function"==typeof define&&define.amd?define(["exports","react/jsx-runtime","react","@mobily/ts-belt","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).MarchHare={},global.jsxRuntime,global.React,global.TsBelt,global.Immer);
@@ -1,53 +1,15 @@
1
- import { Fetcher } from './types';
1
+ import { Fetcher, PendingCall, ResourceHandle } from './types';
2
2
  import { Cache } from './utils';
3
- import { Store } from '../boundary/components/store/index';
4
- export type { Fetcher } from './types';
5
- /**
6
- * Snapshot of the most recent resource invocation. `cat(params)` writes
7
- * one of these into a module-scope slot; the next
8
- * `context.actions.resource(...)` / `.set(...)` call consumes it via
9
- * {@link consumePending}.
10
- *
11
- * @internal
12
- */
13
- export type PendingCall = {
14
- readonly run: (store: Store, controller: AbortController, params: object) => Promise<unknown>;
15
- readonly read: (params: object) => {
16
- data: unknown;
17
- at: Temporal.Instant | null;
18
- };
19
- readonly seed: (params: object, data: unknown, at: Temporal.Instant) => void;
20
- readonly params: object;
21
- };
3
+ export type { Coalesce, Fetcher, PendingCall, ResourceHandle, } from './types';
22
4
  /**
23
5
  * Reads and clears the slot populated by the most recent resource
24
6
  * invocation. Throws when the slot is empty &mdash; the public
25
- * `.resource(...)` shape requires a fresh `cat(params)` call as its
26
- * argument.
7
+ * `.resource(...)` shape requires a fresh `resource.cat(params)` call
8
+ * as its argument.
27
9
  *
28
10
  * @internal
29
11
  */
30
12
  export declare function consumePending(): PendingCall;
31
- /**
32
- * Resource handle returned by `Resource(...)`. Call it with `params` to
33
- * read the per-params cache slot synchronously and prime the slot
34
- * consumed by `context.actions.resource(...)` for a follow-up fetch or
35
- * `context.actions.resource.set(...)` for an out-of-band write.
36
- *
37
- * ```ts
38
- * // Sync cache read in a model literal.
39
- * { cat: cat({ id: 5 }) }
40
- *
41
- * // Fetch with `.exceeds(...)` for cache-aware refresh.
42
- * await context.actions.resource(cat({ id: 5 })).exceeds({ minutes: 5 });
43
- *
44
- * // Write through to the per-params cache slot.
45
- * context.actions.resource.set(cat({ id: 5 }), data);
46
- * ```
47
- */
48
- export type Resource<T, P extends object = Record<never, never>> = [
49
- keyof P
50
- ] extends [never] ? (params?: P) => T | null : (params: P) => T | null;
51
13
  /**
52
14
  * Defines a remote resource &mdash; declared at module scope and used
53
15
  * directly. Calling the returned handle with `params` returns the sync
@@ -55,48 +17,60 @@ export type Resource<T, P extends object = Record<never, never>> = [
55
17
  * `context.actions.resource(...)` / `.set(...)` for fetch and write
56
18
  * paths.
57
19
  *
58
- * The fetcher receives a single args object `{ store, controller, params }`:
59
- *
60
- * - `store` &ndash; snapshot of the per-`<Boundary>` Store (session,
61
- * locale, feature flags, etc.). Reads only; writes go through
62
- * `context.actions.produce(({ store }) => ...)` in handlers.
63
- * - `controller` &ndash; the `AbortController` auto-threaded from the
64
- * calling handler's `context.task.controller`. Pass `controller.signal`
65
- * to `fetch`/`ky`, or call `controller.abort()` to fail fast.
66
- * - `params` &ndash; the call-site params object (defaults to `{}`).
20
+ * The fetcher receives a single `context` argument carrying `env`,
21
+ * `controller`, `params`, and a broadcast/multicast-only `dispatch`.
22
+ * Every successful fetch writes through to a per-resource in-memory
23
+ * cache; pair with {@link Resource.Cachable} to persist across reloads.
67
24
  *
68
- * Resources do **not** carry any callbacks &ndash; side-effects
69
- * (broadcasting, logging, model updates) belong in the `useAction`
70
- * handler that awaited `context.actions.resource(...)`.
71
- *
72
- * Every successful fetch writes through to the per-fetcher {@link Cache}
73
- * (in-memory by default, persistent when an adapter is supplied via the
74
- * second argument).
25
+ * Concurrent calls fire fresh requests by default. Opt in to in-flight
26
+ * sharing per call via `.coalesce(key)` on the thenable returned from
27
+ * `context.actions.resource(...)`.
75
28
  *
76
29
  * @example
77
30
  * ```ts
78
- * import { Resource, Cache } from "march-hare";
31
+ * import { Resource } from "march-hare";
79
32
  *
80
- * export const user = Resource<User, { id: number }>(
81
- * ({ store, controller, params }) =>
82
- * ky.get(`users/${params.id}`, {
83
- * headers: store.session
84
- * ? { Authorization: `Bearer ${store.session.accessToken}` }
33
+ * export const user = Resource<User, { id: number }>((context) =>
34
+ * ky
35
+ * .get(`users/${context.params.id}`, {
36
+ * headers: context.env.session
37
+ * ? { Authorization: `Bearer ${context.env.session.accessToken}` }
85
38
  * : {},
86
- * signal: controller.signal,
87
- * }).json<User>(),
39
+ * signal: context.controller.signal,
40
+ * })
41
+ * .json<User>(),
88
42
  * );
89
- *
90
- * // Sync cache read at module scope or in the model literal.
91
- * const cached: User | null = user({ id: 5 });
92
- *
93
- * // Fetch inside a handler — controller and Store auto-threaded.
94
- * actions.useAction(Actions.Mount, async (context) => {
95
- * const data = await context.actions
96
- * .resource(user({ id: 5 }))
97
- * .exceeds({ minutes: 5 });
98
- * context.actions.produce(({ model }) => void (model.user = data));
99
- * });
100
43
  * ```
101
44
  */
102
- export declare function Resource<T, P extends object = Record<never, never>>(fetcher: Fetcher<T, P>, cache?: Cache): Resource<T, P>;
45
+ export declare function Resource<T, P extends object = Record<never, never>>(ƒ: Fetcher<T, P>): ResourceHandle<T, P>;
46
+ export declare namespace Resource {
47
+ /**
48
+ * Cache-aware variant of {@link Resource}. The supplied {@link Cache}
49
+ * is the **first** argument &mdash; persistence is the headline of
50
+ * this form, the fetcher is the operation. Every successful fetch
51
+ * writes through to the cache; first reads via the call form
52
+ * auto-seed from the cache's adapter.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { Cache, Resource } from "march-hare";
57
+ *
58
+ * const cache = Cache({
59
+ * get: (key) => localStorage.getItem(key),
60
+ * set: (key, value) => localStorage.setItem(key, value),
61
+ * remove: (key) => localStorage.removeItem(key),
62
+ * clear: () => localStorage.clear(),
63
+ * });
64
+ *
65
+ * export const cat = Resource.Cachable(cache, async (context) =>
66
+ * ky
67
+ * .get("https://api.thecatapi.com/v1/images/search", {
68
+ * signal: context.controller.signal,
69
+ * })
70
+ * .json<Cat[]>()
71
+ * .then((cats) => cats[0]),
72
+ * );
73
+ * ```
74
+ */
75
+ function Cachable<T, P extends object = Record<never, never>>(cache: Cache, ƒ: Fetcher<T, P>): ResourceHandle<T, P>;
76
+ }
@@ -1,27 +1,100 @@
1
- import { Store } from '../boundary/components/store/index';
1
+ import { Env } from '../boundary/components/env/index';
2
+ import { Cache } from '../cache/index';
3
+ import { BroadcastPayload, MulticastPayload, Filter } from '../types/index';
2
4
  /**
3
- * Args object passed to every {@link Fetcher}. The fetcher destructures
4
- * whatever it needs; unused fields can be omitted.
5
+ * Dispatch surface exposed on a Resource fetcher's `context`. Restricted
6
+ * to broadcast and multicast actions &mdash; unicast targets the calling
7
+ * component, which a Resource fetcher does not have.
8
+ */
9
+ export type Dispatch = {
10
+ <C extends Filter = never>(action: BroadcastPayload<never, C> | MulticastPayload<never, C>): Promise<void>;
11
+ <P, C extends Filter = never>(action: BroadcastPayload<P, C> | MulticastPayload<P, C>, payload: P): Promise<void>;
12
+ };
13
+ /**
14
+ * `context` object passed to every {@link Fetcher}.
5
15
  *
6
- * - `store` &mdash; snapshot of the per-`<Boundary>` Store at the
16
+ * - `env` &mdash; snapshot of the per-`<Boundary>` Env at the
7
17
  * moment the fetcher is invoked.
8
18
  * - `controller` &mdash; the `AbortController` auto-threaded from the
9
19
  * calling handler's `context.task.controller`. Pass
10
20
  * `controller.signal` to `fetch`/`ky`/`EventSource`, or call
11
21
  * `controller.abort()` to fail fast.
12
22
  * - `params` &mdash; the call-site params object. Defaults to `{}`.
23
+ * - `dispatch` &mdash; fire broadcast or multicast actions from inside
24
+ * the fetcher. Unicast is rejected at compile time.
13
25
  *
14
26
  * @internal
15
27
  */
16
28
  export type Args<P extends object = Record<never, never>> = {
17
- readonly store: Store;
29
+ readonly env: Env;
18
30
  readonly controller: AbortController;
19
31
  readonly params: P;
32
+ readonly dispatch: Dispatch;
20
33
  };
21
34
  /**
22
- * Fetcher signature accepted by `Resource`. Receives the args object
23
- * `{ store, controller, params }`. Side-effects (dispatching broadcasts,
24
- * analytics, etc.) belong in the calling `useAction` handler, not
25
- * inside the fetcher.
35
+ * Fetcher signature accepted by `Resource`. Receives a single `context`
36
+ * argument carrying the Env snapshot, the abort controller, params,
37
+ * and a broadcast/multicast-only `dispatch`.
38
+ */
39
+ export type Fetcher<T, P extends object = Record<never, never>> = (context: Args<P>) => Promise<T>;
40
+ /**
41
+ * Per-call coalescing token. Two callers with the same Resource, same
42
+ * structural params, and equal `Coalesce` value share a single in-flight
43
+ * promise; different tokens (or different params) fire independent
44
+ * fetches. Primitives compose naturally via stringification; objects
45
+ * are serialised with `JSON.stringify`.
46
+ */
47
+ export type Coalesce = string | number | bigint | boolean | symbol | object;
48
+ /**
49
+ * Config form accepted by `Resource`. The fetcher shorthand
50
+ * `Resource(fetcher)` is equivalent to `Resource({ fetch: fetcher })`.
51
+ *
52
+ * - `fetch` &mdash; the fetcher.
53
+ * - `cache` &mdash; persist successful payloads via a {@link Cache}
54
+ * wired to an `Adapter` (localStorage, MMKV, etc). Omit for an
55
+ * in-memory cache scoped to this Resource.
56
+ */
57
+ export type Config<T, P extends object = Record<never, never>> = {
58
+ readonly fetch: Fetcher<T, P>;
59
+ readonly cache?: Cache;
60
+ };
61
+ /**
62
+ * Snapshot of the most recent resource invocation. `resource.cat(params)`
63
+ * writes one of these into a module-scope slot; the next
64
+ * `context.actions.resource(...)` / `.set(...)` call consumes it via
65
+ * `consumePending` and then clears the slot.
66
+ *
67
+ * @internal
68
+ */
69
+ export type PendingCall = {
70
+ readonly run: (env: Env, controller: AbortController, params: object, dispatch: Dispatch) => Promise<unknown>;
71
+ readonly read: (params: object) => {
72
+ data: unknown;
73
+ at: Temporal.Instant | null;
74
+ };
75
+ readonly seed: (params: object, data: unknown, at: Temporal.Instant) => void;
76
+ readonly params: object;
77
+ };
78
+ /**
79
+ * Resource handle returned by `Resource(...)` or `Resource.Cachable(...)`.
80
+ * Call it with `params` to read the per-params cache slot synchronously
81
+ * and prime the slot consumed by `context.actions.resource(...)` for a
82
+ * follow-up fetch or `context.actions.resource.set(...)` for an
83
+ * out-of-band write.
84
+ *
85
+ * ```ts
86
+ * // Sync cache read in a model literal.
87
+ * { cat: resource.cat({ id: 5 }) }
88
+ *
89
+ * // Fetch with `.exceeds(...)` for cache-aware refresh.
90
+ * await context.actions
91
+ * .resource(resource.cat({ id: 5 }))
92
+ * .exceeds({ minutes: 5 });
93
+ *
94
+ * // Write through to the per-params cache slot.
95
+ * context.actions.resource.set(resource.cat({ id: 5 }), data);
96
+ * ```
26
97
  */
27
- export type Fetcher<T, P extends object = Record<never, never>> = (args: Args<P>) => Promise<T>;
98
+ export type ResourceHandle<T, P extends object = Record<never, never>> = [
99
+ keyof P
100
+ ] extends [never] ? (params?: P) => T | null : (params: P) => T | null;