march-hare 0.12.1 → 0.13.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.
@@ -18,37 +18,51 @@ export type Encoded<T> = {
18
18
  * facade, etc.) and pass to {@link Cache}. The adapter shuttles raw
19
19
  * strings; JSON encoding and `Temporal.Instant` round-tripping happen
20
20
  * inside the Cache wrapper, so adapters stay trivial.
21
+ *
22
+ * **Every method is strictly synchronous.** The library never awaits
23
+ * adapter calls &mdash; the model-literal sync read has no place to
24
+ * wait. Async backends (IndexedDB, AsyncStorage, chrome.storage.local)
25
+ * need a sync facade hydrated at app entry; see `recipes/storage.md`
26
+ * for the pattern. React Native projects should use
27
+ * {@link https://github.com/mrousavy/react-native-mmkv `react-native-mmkv`}
28
+ * &mdash; it's sync out of the box and drops straight into this
29
+ * contract.
21
30
  */
22
31
  export type Adapter = {
23
32
  /**
24
33
  * Return the raw string stored under `key`, or `null` when no entry
25
- * exists. The Cache wrapper handles JSON parsing and `Temporal.Instant`
26
- * round-tripping, so this stays a plain string getter. Treat any
27
- * read-time error (decryption, IPC, etc.) as "not found" and return
28
- * `null` &mdash; the Cache falls through to its next fallback rather
29
- * than crashing the render.
34
+ * exists. **Strictly sync.** Treat any read-time error (decryption,
35
+ * IPC, etc.) as "not found" and return `null` &mdash; the Cache will
36
+ * fall back to its empty state.
30
37
  */
31
38
  readonly get: (key: string) => string | null;
32
39
  /**
33
- * Persist the raw string `value` under `key`. The Cache guarantees
34
- * `value` is a JSON-encoded `{ data, at }` envelope produced by a
35
- * resolved snapshot &mdash; never a placeholder. Throwing is fine on
36
- * quota, private mode, sandboxed iframes, etc.; the Cache catches and
37
- * swallows so a write failure can't poison an already-resolved fetch.
40
+ * Persist the raw string `value` under `key`. **Strictly sync.**
41
+ * Throwing is fine on quota, private mode, sandboxed iframes, etc.;
42
+ * the Cache catches and swallows so a failure can't poison an
43
+ * already-resolved fetch.
38
44
  */
39
45
  readonly set: (key: string, value: string) => void;
40
46
  /**
41
- * Drop the entry at `key`. Idempotent &mdash; calling `remove` for a
42
- * key that isn't present must not throw.
47
+ * Drop the entry at `key`. **Strictly sync.** Idempotent &mdash;
48
+ * calling `remove` for a key that isn't present must not throw.
43
49
  */
44
50
  readonly remove: (key: string) => void;
45
51
  /**
46
- * Wipe every entry this adapter can see. On a shared backend such as
47
- * `localStorage` this means the whole origin &mdash; third-party SDK
48
- * state, dismissed banners, route hints, etc. all go with it. Adapter
49
- * authors should either delegate to the backend's native clear
50
- * (accepting that scope) or namespace by key prefix and remove only
51
- * their own.
52
+ * Wipe every entry this adapter can see. **Strictly sync.** On a
53
+ * shared backend such as `localStorage` this means the whole origin
54
+ * &mdash; third-party SDK state, dismissed banners, route hints, etc.
55
+ * all go with it. Adapter authors should either delegate to the
56
+ * backend's native clear (accepting that scope) or namespace by key
57
+ * prefix and remove only their own.
52
58
  */
53
59
  readonly clear: () => void;
60
+ /**
61
+ * Optional enumerator over every key the adapter currently knows
62
+ * about. **Strictly sync** when implemented &mdash; partial-match
63
+ * evictions sweep these keys in the current tick. `localStorage`
64
+ * exposes this via `Object.keys(localStorage)`; MMKV via
65
+ * `getAllKeys()`.
66
+ */
67
+ readonly keys?: () => Iterable<string>;
54
68
  };
@@ -31,7 +31,7 @@ import { Actions, Context as ContextHandle, Model, Props } from '../types/index'
31
31
  * });
32
32
  *
33
33
  * const actions = context.useActions(
34
- * { user: resource.user() },
34
+ * { user: resource.user.get() },
35
35
  * () => ({ form }),
36
36
  * );
37
37
  * ```
@@ -1,2 +1,19 @@
1
- export { Reason, Aborted } from './types';
1
+ export { Reason } from './types';
2
2
  export type { Fault } from './types';
3
+ /**
4
+ * Error thrown when an action is aborted, e.g., when a component unmounts
5
+ * or when a newer dispatch cancels a previous run. Works across all platforms
6
+ * including React Native where `DOMException` is unavailable.
7
+ *
8
+ * The instance's `name` field stays as `"AbortError"` so it can be
9
+ * pattern-matched alongside native `DOMException`s and ky/fetch aborts.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * throw new Aborted("User cancelled the request");
14
+ * ```
15
+ */
16
+ export declare class Aborted extends Error {
17
+ name: string;
18
+ constructor(message?: string);
19
+ }
@@ -9,23 +9,6 @@ export declare enum Reason {
9
9
  /** A generic error thrown in the user's action handler. */
10
10
  Errored = 1
11
11
  }
12
- /**
13
- * Error thrown when an action is aborted, e.g., when a component unmounts
14
- * or when a newer dispatch cancels a previous run. Works across all platforms
15
- * including React Native where `DOMException` is unavailable.
16
- *
17
- * The instance's `name` field stays as `"AbortError"` so it can be
18
- * pattern-matched alongside native `DOMException`s and ky/fetch aborts.
19
- *
20
- * @example
21
- * ```ts
22
- * throw new Aborted("User cancelled the request");
23
- * ```
24
- */
25
- export declare class Aborted extends Error {
26
- name: string;
27
- constructor(message?: string);
28
- }
29
12
  /**
30
13
  * Details about an error that occurred during action execution.
31
14
  *
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { App } from './app/index';
2
+ export type { AppHandle } from './app/index';
2
3
  export { Action } from './action/index';
3
4
  export { Distribution, Lifecycle } from './types/index';
4
5
  export { With } from './with/index';
@@ -13,4 +14,5 @@ export type { Fault } from './error/index';
13
14
  export type { Adapter } from './cache/index';
14
15
  export type { Box } from 'immertation';
15
16
  export type { Pk, Maybe, Handler, Handlers } from './types/index';
17
+ export type { Envless } from './boundary/components/env/index';
16
18
  export type { Tap, Taps } from './boundary/components/tap/types';
@@ -1,8 +1,9 @@
1
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,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}(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 p=t.createContext(new d);function h(){return t.useContext(p)}function m({children:n}){const r=t.useMemo(()=>new d,[]);/* @__PURE__ */
2
- return e(p.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}`,S=(e="")=>`march-hare.action.lifecycle/${e}`;class j{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{[j.Action]:t,[j.Payload]:void 0,[j.Channel]:n,[j.Name]:e,channel:n}};return Object.defineProperty(n,j.Action,{value:t,enumerable:!1}),Object.defineProperty(n,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,j.Name,{value:e,enumerable:!1}),n}const C=Symbol(O("Fault")),E=Symbol(O("Env"));class k{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,j.Action,{value:C,enumerable:!1}),Object.defineProperty(e,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,j.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,j.Name,{value:"Fault",enumerable:!1}),e})();static Env=(()=>{const e={};return Object.defineProperty(e,j.Action,{value:E,enumerable:!1}),Object.defineProperty(e,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,j.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,j.Name,{value:"Env",enumerable:!1}),e})()}var N=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(N||{}),M=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(M||{});function A({initial:r,children:o}){const s=t.useRef(r),c=h();return n.isUndefined(c.getCached(E))&&c.setCache(E,s.current),/* @__PURE__ */e(v.Provider,{value:s,children:o})}const _=t.createContext(/* @__PURE__ */new WeakMap);function R({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new WeakMap,[]);/* @__PURE__ */
2
+ return e(p.Provider,{value:r,children:n})}const y=t.createContext(/* @__PURE__ */new Set);function b({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new Set,[]);/* @__PURE__ */
3
+ return e(y.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}`,S=(e="")=>`march-hare.action.lifecycle/${e}`;class j{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");static Lifecycle=/* @__PURE__ */Symbol("march-hare.brand/Lifecycle")}function E(e){const t=/* @__PURE__ */Symbol(`march-hare.action.lifecycle/${e}`),n=function(n){return{[j.Action]:t,[j.Payload]:void 0,[j.Channel]:n,[j.Name]:e,channel:n}};return Object.defineProperty(n,j.Action,{value:t,enumerable:!1}),Object.defineProperty(n,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(n,j.Name,{value:e,enumerable:!1}),Object.defineProperty(n,j.Lifecycle,{value:e,enumerable:!1}),n}const x=Symbol(O("Fault")),k=Symbol(O("Env"));class C{static Mount(){return E("Mount")}static Unmount(){return E("Unmount")}static Error(){return E("Error")}static Update(){return E("Update")}static Fault=(()=>{const e={};return Object.defineProperty(e,j.Action,{value:x,enumerable:!1}),Object.defineProperty(e,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,j.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,j.Name,{value:"Fault",enumerable:!1}),e})();static Env=(()=>{const e={};return Object.defineProperty(e,j.Action,{value:k,enumerable:!1}),Object.defineProperty(e,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,j.Broadcast,{value:!0,enumerable:!1}),Object.defineProperty(e,j.Name,{value:"Env",enumerable:!1}),e})()}var N=/* @__PURE__ */(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(N||{}),M=/* @__PURE__ */(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(M||{});function A({initial:r,children:o}){const s=t.useRef(r),c=h();return n.isUndefined(c.getCached(k))&&c.setCache(k,s.current),/* @__PURE__ */e(v.Provider,{value:s,children:o})}const _=t.createContext(/* @__PURE__ */new WeakMap);function R({children:n}){const r=t.useMemo(()=>/* @__PURE__ */new WeakMap,[]);/* @__PURE__ */
4
4
  return e(_.Provider,{value:r,children:n})}const U=t.createContext(()=>{});function L({tap:n,children:r}){const o=t.useRef(n);t.useLayoutEffect(()=>{o.current=n},[n]);const s=t.useMemo(()=>e=>o.current?.(e),[]);/* @__PURE__ */
5
- return e(U.Provider,{value:s,children:r})}function T({env:t,tap:n,children:r}){/* @__PURE__ */
6
- return e(m,{children:/* @__PURE__ */e(A,{initial:t??{},children:/* @__PURE__ */e(y,{children:/* @__PURE__ */e(L,{tap:n,children:/* @__PURE__ */e(R,{children:r})})})})})}const W=e=>"symbol"==typeof e;function $(e){return n.isString(e)||W(e)?e:(n.isObject(e)||n.isFunction(e))&&j.Action in e?e[j.Action]:e}function B(e){if(n.isString(e))return e.startsWith(O());if(W(e))return e.description?.startsWith(O())??!1;if(n.isObject(e)||n.isFunction(e)){if(j.Broadcast in e&&e[j.Broadcast])return!0;if(j.Action in e){const t=e[j.Action];return t.description?.startsWith(O())??!1}}return!1}function F(e){return n.isObject(e)&&j.Channel in e&&"channel"in e}function z(e){const t=$(e),n=W(t)?t.description??"":t;return n.startsWith(S())&&n.slice(S().length)||null}function D(e){if(n.isString(e))return e.startsWith(P());if(W(e))return e.description?.startsWith(P())??!1;if(n.isObject(e)||n.isFunction(e)){if(j.Multicast in e&&e[j.Multicast])return!0;if(j.Action in e){const t=e[j.Action];return t.description?.startsWith(P())??!1}}return!1}const H=(e="",t=N.Unicast)=>{const n=t===N.Broadcast?Symbol(O(e)):t===N.Multicast?Symbol(P(e)):Symbol(w(e)),r=function(t){return{[j.Action]:n,[j.Payload]:void 0,[j.Channel]:t,[j.Name]:e,channel:t}};return Object.defineProperty(r,j.Action,{value:n,enumerable:!1}),Object.defineProperty(r,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,j.Name,{value:e,enumerable:!1}),t===N.Broadcast&&Object.defineProperty(r,j.Broadcast,{value:!0,enumerable:!1}),t===N.Multicast&&Object.defineProperty(r,j.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 q(e,t){for(const n of e.keys())if(z(n)===t)return n;return null}const G=/* @__PURE__ */Symbol("march-hare.unset");function K(){const[,e]=t.useReducer(e=>e+1,0);return e}function V(){return{data:G,at:null,else:e=>e}}function Q(e,t){return{data:e,at:t,else:t=>e}}var X=/* @__PURE__ */(e=>(e[e.Aborted=0]="Aborted",e[e.Errored=1]="Errored",e))(X||{});class Y extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const Z=t.createContext(null);function ee(e){const t=/* @__PURE__ */new Map,r=e??{get:e=>t.get(e)??null,set:(e,n)=>{t.set(e,n)},remove:e=>{t.delete(e)},clear:()=>{t.clear()}};return{get(e){try{const t=r.get(e);if(n.isNull(t))return V();const o=JSON.parse(t);return Q(o.data,Temporal.Instant.from(o.at))}catch{return V()}},set(e,t){if(t.data===G||n.isNull(t.at))return!1;try{return r.set(e,JSON.stringify({data:t.data,at:t.at.toString()})),!0}catch{return!1}},remove(e){r.remove(e)},clear(){r.clear()}}}function te(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new Y);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Y)},{once:!0})})}async function ne(e,t,n){if(t?.aborted)throw new Y;for(;;){if(await n())return;await te(e,t)}}function re(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const oe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:re,poll:ne,sleep:te,unset:G,"ζ":te,"κ":re,"π":ne},Symbol.toStringTag,{value:"Module"})),se=/* @__PURE__ */new WeakMap;function ce(e){return JSON.stringify(e)}let ae=null;function ie(){if(n.isNull(ae))throw new Error("context.actions.resource(...) and context.actions.resource.set(...) must be called with a fresh resource invocation, e.g. context.actions.resource(resource.cat({ id: 5 })).");const e=ae;return ae=null,e}function ue(e,t){const r=e=>{const r=t.get(ce(e));return r.data===G||n.isNull(r.at)?{data:G,at:null}:{data:r.data,at:r.at}},o=(n,r,o,s)=>e({env:n,controller:r,params:o,dispatch:s}).then(e=>(t.set(ce(o),Q(e,Temporal.Now.instant())),e)),s=(e,n,r)=>{t.set(ce(e),Q(n,r))};return function(e){const t=e??{};ae={run:o,read:r,seed:s,params:t},queueMicrotask(()=>{n.isNotNullable(ae)&&ae.params===t&&(ae=null)});const{data:c}=r(t);return c===G?null:c}}function le(e){return ue(e,function(e){let t=se.get(e);return n.isUndefined(t)&&(t=ee(),se.set(e,t)),t}(e))}(le||(le={})).Cachable=function(e,t){return ue(t,e)};const fe=/* @__PURE__ */Symbol("march-hare.coalesce/default");function de(e,t){return new Promise((n,r)=>{if(t.aborted)return void r(t.reason);const o=()=>r(t.reason);t.addEventListener("abort",o,{once:!0}),e.then(e=>{t.removeEventListener("abort",o),n(e)},e=>{t.removeEventListener("abort",o),r(e)})})}let pe=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var he=/* @__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))(he||{}),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=pe}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)||Se(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 Se(e){return n.isNullable(e)||n.isString(e)||n.isNumber(e)||n.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function je(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))),Se(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&&Se(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 Ce{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=Oe){this.#t=e}static pk(){return pe()}static"κ"=Ce.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:je(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 Ee=t.createContext(/* @__PURE__ */new Map);function ke({action:e,renderer:r}){const o=h(),s=t.useContext(Ee),c=K(),a=t.useMemo(()=>{const t=s.get(e);if(t)return t;const r=new Ce,c=o.getCached(e);n.isNotNullable(c)&&r.hydrate({value:c});const a={state:r,listeners:/* @__PURE__ */new Set};return s.set(e,a),a},[e,o,s]);t.useLayoutEffect(()=>{function t(e){a.state.hydrate({value:e}),a.listeners.forEach(e=>e())}return a.listeners.add(c),o.on(e,t),()=>{a.listeners.delete(c),o.off(e,t)}},[e,o,a]);const i=a.state.model?.value;return n.isNullable(i)?null:r(i,a.state.inspect.value)}function Ne(e,t){const n=t.split(".");let r=e;for(let o=0;o<n.length-1;o++)r=r[n[o]];return{cursor:r,key:n[n.length-1]}}function Me(e,t,n){const{cursor:r,key:o}=Ne(e,t);r[o]=n}function Ae(e){return(t,n)=>{t.actions.produce(t=>{Me(t.model,e,n)})}}function _e(e){return t=>{t.actions.produce(t=>{!function(e,t){const{cursor:n,key:r}=Ne(e,t);n[r]=!n[r]}(t.model,e)})}}function Re(e,t){return n=>{n.actions.produce(n=>{Me(n.model,e,t)})}}const Ue={Update:e=>Ae(e),Invert:e=>_e(e),Always:(e,t)=>Re(e,t)};function Le(){const e=t.useRef(null);return t.useMemo(()=>({actions:{dispatch:function(t,n){const r=e.current;if(!r)throw new Error("march-hare: useContext handle dispatched before its paired context.useActions(...) ran. Call context.actions.dispatch from event handlers, not synchronously during render.");return r(t,n)}},useActions:function(...o){const s=function(...e){const o=n.isUndefined(e[0])||n.isFunction(e[0])?{}:e[0],s=n.isFunction(e[0])?e[0]:e[1]??(()=>({})),c=h(),i=t.useContext(Z),u=t.useContext(b),l=g(),d=t.useContext(v),p=t.useContext(_),m=t.useContext(U),y=K(),O=t.useRef(!1),P=t.useRef(null),S=t.useRef(new Ce);O.current||(O.current=!0,P.current=S.current.hydrate(o));const[j,x]=t.useState(()=>S.current.model),k=function(e){const n=t.useRef(e);return n.current=e,t.useMemo(()=>{return t=n,Object.keys(e).reduce((e,n)=>(Object.defineProperty(e,n,{get:()=>t.current[n],enumerable:!0}),e),{});var t},[e])}(s()),N=t.useMemo(()=>new f,[]),A=t.useRef({handlers:/* @__PURE__ */new Map});A.current.handlers=/* @__PURE__ */new Map;const R=function(){const e=t.useRef(/* @__PURE__ */new Set),n=t.useRef(/* @__PURE__ */new Set);return t.useMemo(()=>({broadcast:e.current,multicast:n.current}),[])}(),L=t.useRef(M.Mounting),T=t.useRef(/* @__PURE__ */new Set),W=t.useRef(0),z=t.useCallback((e,t,r)=>{const o=new AbortController,s={controller:o,action:e,payload:t};return u.add(s),T.current.add(s),{model:S.current.model,get phase(){return L.current},task:s,data:k,tasks:u,env:l,actions:{produce(e){if(o.signal.aborted)return;const t=d.current,n=S.current.produce(t=>{d.current=a(d.current,n=>{e({model:t,inspect:S.current.inspect,env:n})})});x(S.current.model),d.current!==t&&c.emit(E,d.current),r.processes.add(n),P.current&&(r.processes.add(P.current),P.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=$(e),r=F(e)?e.channel:void 0;return D(e)?i?J(i.emitter,n,t,r):Promise.resolve():J(B(e)?c:N,n,t,r)},annotate:(e,t=he.Update)=>S.current.annotate(t,e),get inspect(){return S.current.inspect},resource:Object.assign(function(e){const t=ie(),r=(e,t)=>{if(o.signal.aborted)return Promise.resolve();const n=e,r=$(n);return D(n)?i?J(i.emitter,r,t,void 0):Promise.resolve():B(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!==G&&n.isNotNullable(r)){const t=Temporal.Now.instant().since(r),n=Temporal.Duration.from(s.exceedsWindow);if(Temporal.Duration.compare(t,n)<=0)return Promise.resolve(e)}}if(n.isUndefined(s.coalesceToken))return t.run(l,o,t.params,r);let e=p.get(t.run);n.isUndefined(e)&&(e=/* @__PURE__ */new Map,p.set(t.run,e));const c=e,a=`${JSON.stringify(t.params)}|${function(e){switch(typeof e){case"string":return`s:${e}`;case"number":return`n:${e}`;case"bigint":return`i:${e.toString()}`;case"boolean":return`b:${e}`;case"symbol":return`y:${e.description??String(e)}`;default:return`o:${JSON.stringify(e)}`}}(s.coalesceToken)}`,i=c.get(a);if(i)return de(i,o.signal);const u=new AbortController,f=t.run(l,u,t.params,r).finally(()=>{c.delete(a)});return c.set(a,f),de(f,o.signal)})().then(e,c),exceeds:e=>(s.exceedsWindow=e,a),coalesce:e=>(s.coalesceToken=e??fe,a)};return a},{set:(e,t)=>{const n=ie();n.seed(n.params,t,Temporal.Now.instant())}}),async final(e){if(o.signal.aborted)return null;const t=$(e),r=D(e)?i?.emitter??null:c;if(!r)return null;const s=r.getCached(t);if(n.isUndefined(s))return null;const a=S.current.inspect;return a.pending()&&await new Promise((e,t)=>{if(o.signal.aborted)return void t(o.signal.reason);const n=()=>t(o.signal.reason);o.signal.addEventListener("abort",n,{once:!0}),a.settled().then(()=>{o.signal.removeEventListener("abort",n),e()})}),r.getCached(t)??null},peek(e){if(o.signal.aborted)return null;const t=$(e),n=D(e)?i?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[j]);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 l={processes:/* @__PURE__ */new Set},f=Promise.withResolvers(),p=z(e,o,l),h=function(e){const t=$(e),r=n.isString(t)?t:t.description??"";return r.startsWith(w())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}(e),b=performance.now(),v=S.current.model,g=d.current;let O,P=!1;function j(){const e=S.current.model,t=d.current;return{model:v===e?null:{before:v,after:e},env:g===t?null:{before:g,after:t}}}function x(){const t=s===I?void 0:s;return D(e)?i?J(i.emitter,e,o,t):Promise.resolve():J(B(e)?c:N,e,o,t)}function E(e){P=!0;const t=q(A.current.handlers,"Error"),r=n.isNotNullable(t),s=function(e){return e instanceof Error&&"AbortError"===e.name?X.Aborted:X.Errored}(e),a=function(e){return e instanceof Error?e:new Error(String(e))}(e),i={reason:s,error:a,action:h,handled:r,tasks:u,retry:x};c.fire(C,i),r&&t&&N.emit(t,i),m({stage:"end",result:"error",action:{name:h,payload:o},details:{task:p.task,elapsed:performance.now()-b,mutations:j(),error:a,reason:s}})}function k(){for(const e of u)if(e===p.task){u.delete(e),T.current.delete(e);break}l.processes.forEach(e=>S.current.prune(e)),l.processes.size>0&&y(),P||m({stage:"end",result:"success",action:{name:h,payload:o},details:{task:p.task,elapsed:performance.now()-b,mutations:j()}}),f.resolve()}m({stage:"start",action:{name:h,payload:o},details:{task:p.task}});try{O=t(p,o)}catch(M){return E(M),k(),f.promise}return function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(O)?((async()=>{for await(const e of O);})().catch(E).finally(k),f.promise):(Promise.resolve(O).catch(E).finally(k),f.promise)}}W.current++;const t=/* @__PURE__ */new Set;return A.current.handlers.forEach((n,r)=>{for(const{getChannel:o,handler:s}of n){const n=e(r,s,o);if(D(r)){if(i){const e=i.emitter;e.on(r,n),t.add(()=>e.off(r,n))}N.on(r,n),R.multicast.add(r),t.add(()=>N.off(r,n))}else B(r)?(c.on(r,n),N.on(r,n),R.broadcast.add(r),t.add(()=>{c.off(r,n),N.off(r,n)})):(N.on(r,n),t.add(()=>N.off(r,n)))}}),()=>{const e=++W.current,n=new Set(t);queueMicrotask(()=>{if(W.current!==e){for(const e of n)e();return}for(const e of T.current)e.controller.abort(new Y("Component unmounted")),u.delete(e);T.current.clear(),L.current=M.Unmounting;const t=q(A.current.handlers,"Unmount");t&&N.emit(t),L.current=M.Unmounted;for(const e of n)e()})}},[N]),function({unicast:e,broadcast:o,dispatchers:s,scope:c,phase:a,data:i,handlers:u}){const l=t.useRef(null);t.useLayoutEffect(()=>{if(a.current===M.Mounted)return;a.current=M.Mounting;const t=q(u,"Mount");t&&e.emit(t),s.broadcast.forEach(t=>{const r=o.getCached(t);n.isNullable(r)||e.emit(t,r,I)}),c&&s.multicast.forEach(t=>{const r=c.emitter.getCached(t);n.isNullable(r)||e.emit(t,r,I)}),a.current=M.Mounted},[]),t.useLayoutEffect(()=>{if(n.isNotNullable(l.current)){const t=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(r.isNotEmpty(Object.keys(t))){const n=q(u,"Update");n&&e.emit(n,t)}}l.current=i},[i,e])}({unicast:N,broadcast:c,dispatchers:R,scope:i,phase:L,data:s(),handlers:A.current.handlers});const H=t.useMemo(()=>({dispatch(e,t){const n=$(e),r=F(e)?e.channel:void 0;return D(e)?i?J(i.emitter,n,t,r):Promise.resolve():J(B(e)?c:N,n,t,r)},get inspect(){return S.current.inspect},stream:(e,n)=>t.createElement(ke,{action:$(e),renderer:n})}),[j,N]),V=t.useMemo(()=>[j,H,k],[j,H,k]);return V.useAction=(e,n)=>{!function(e,n,r){const o=t.useRef(r);t.useLayoutEffect(()=>{o.current=r});const s=t.useRef(n);t.useLayoutEffect(()=>{s.current=n});const c=t.useCallback((e,t)=>o.current(e,t),[]),a=t.useCallback(()=>F(s.current)?s.current.channel:void 0,[]),i=$(n),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:c})}(A,e,n)},V.dispatch=V[1].dispatch,V}(...o);return e.current=s.dispatch,s},with:{update:e=>Ae(e),invert:e=>_e(e),always:(e,t)=>Re(e,t)}}),[])}function Te(){return{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 Le()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)})}}function We(t){return{Boundary:function({children:n}){/* @__PURE__ */
8
- return e(T,{env:t?.env,tap:t?.tap,children:n})},useContext:function(){return Le()},useEnv:function(){return g()},Resource:Object.assign(function(e){return le(e)},{Cachable:(e,t)=>le.Cachable(e,t)}),Scope:()=>Te()}}const $e=new Ce;function Be(e,t=he.Update){return $e.annotate(t,e)}const Fe=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,get Resource(){return le},Scope:function(){return Te()},useContext:function(){return Le()},useEnv:function(){return g()}},Symbol.toStringTag,{value:"Module"}));export{Y as Aborted,H as Action,We as App,T as Boundary,ee as Cache,N as Distribution,k as Lifecycle,he as Op,he as Operation,X as Reason,Ce as State,Ue as With,Be as annotate,Fe as shared,oe as utils};
5
+ return e(U.Provider,{value:s,children:r})}function $({env:t,tap:n,children:r}){/* @__PURE__ */
6
+ return e(m,{children:/* @__PURE__ */e(A,{initial:t??{},children:/* @__PURE__ */e(b,{children:/* @__PURE__ */e(L,{tap:n,children:/* @__PURE__ */e(R,{children:r})})})})})}const T=e=>"symbol"==typeof e;function W(e){return n.isString(e)||T(e)?e:(n.isObject(e)||n.isFunction(e))&&j.Action in e?e[j.Action]:e}function B(e){if(n.isString(e))return e.startsWith(O());if(T(e))return e.description?.startsWith(O())??!1;if(n.isObject(e)||n.isFunction(e)){if(j.Broadcast in e&&e[j.Broadcast])return!0;if(j.Action in e){const t=e[j.Action];return t.description?.startsWith(O())??!1}}return!1}function F(e){return n.isObject(e)&&j.Channel in e&&"channel"in e}function z(e){const t=W(e),n=T(t)?t.description??"":t;return n.startsWith(S())&&n.slice(S().length)||null}function J(e){if(n.isString(e))return e.startsWith(P());if(T(e))return e.description?.startsWith(P())??!1;if(n.isObject(e)||n.isFunction(e)){if(j.Multicast in e&&e[j.Multicast])return!0;if(j.Action in e){const t=e[j.Action];return t.description?.startsWith(P())??!1}}return!1}const D=(e="",t=N.Unicast)=>{const n=t===N.Broadcast?Symbol(O(e)):t===N.Multicast?Symbol(P(e)):Symbol(w(e)),r=function(t){return{[j.Action]:n,[j.Payload]:void 0,[j.Channel]:t,[j.Name]:e,channel:t}};return Object.defineProperty(r,j.Action,{value:n,enumerable:!1}),Object.defineProperty(r,j.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(r,j.Name,{value:e,enumerable:!1}),t===N.Broadcast&&Object.defineProperty(r,j.Broadcast,{value:!0,enumerable:!1}),t===N.Multicast&&Object.defineProperty(r,j.Multicast,{value:!0,enumerable:!1}),r},H=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 G(e,t){for(const n of e.keys())if(z(n)===t)return n;return null}const K=/* @__PURE__ */Symbol("march-hare.unset");function V(){const[,e]=t.useReducer(e=>e+1,0);return e}function q(){return{data:K,at:null}}function Q(e,t){return{data:e,at:t}}var X=/* @__PURE__ */(e=>(e[e.Aborted=0]="Aborted",e[e.Errored=1]="Errored",e))(X||{});class Y extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}const Z=t.createContext(null);function ee(e){const t=e??function(){const e=/* @__PURE__ */new Map;return{get:t=>e.get(t)??null,set:(t,n)=>{e.set(t,n)},remove:t=>{e.delete(t)},clear:()=>{e.clear()},keys:()=>e.keys()}}();return{get(e){try{const r=t.get(e);if(n.isNull(r))return q();const o=JSON.parse(r);return Q(o.data,Temporal.Instant.from(o.at))}catch{return q()}},set(e,r){if(r.data!==K&&!n.isNull(r.at))try{t.set(e,JSON.stringify({data:r.data,at:r.at.toString()}))}catch{return}},remove(e){try{t.remove(e)}catch{return}},clear(){try{t.clear()}catch{return}},keys(){try{return t.keys?.()??[]}catch{return[]}}}}const te=/* @__PURE__ */new WeakMap,ne=/* @__PURE__ */new Map,re=[];function oe(e,t,r){const o=n.isNull(r)?"":`${r}:`,s=e=>`${o}${function(e){return JSON.stringify(e)}(e)}`,c=e=>{const r=t.get(s(e));return r.data===K||n.isNull(r.at)?{data:K,at:null}:{data:r.data,at:r.at}},a=(n,r,o,c)=>e({env:n,controller:r,params:o,dispatch:c}).then(e=>(t.set(s(o),Q(e,Temporal.Now.instant())),e)),i=e=>{const n=Object.entries(e);for(const r of[...t.keys()])if(r.startsWith(o))try{const e=JSON.parse(r.slice(o.length));n.every(([t,n])=>e[t]===n)&&t.remove(r)}catch{continue}};function u(e){return{run:a,read:c,evict:i,params:e??{}}}return re.push(i),Object.defineProperty(u,"get",{value:function(e){const{data:t}=c(e??{});return t===K?null:t},enumerable:!1}),u}function se(e,t){const r=e;return n.isUndefined(t)?oe(r,function(e){const t=te.get(e);if(n.isNotNullable(t))return t;const r=ee();return te.set(e,r),r}(r),null):oe(r,t,function(e){const t=ne.get(e);if(n.isNotNullable(t))return t;const r=String(ne.size);return ne.set(e,r),r}(r))}const ce=/* @__PURE__ */Symbol("march-hare.coalesce/default");function ae(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 ie=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var ue=/* @__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))(ue||{}),le=/* @__PURE__ */(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(le||{}),fe=/* @__PURE__ */(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(fe||{});class de{[o]=!0;static keys=new Set(Object.values(fe));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new de(this.value,this.operation);return n.property=e,n.process=t,n}}class pe{static immer=(()=>{s();const e=new c;return e.setAutoFreeze(!1),e})();static tag="κ";static id=ie}function he(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 me(e){if(n.isNullable(e)||ve(e))return e;if(n.isArray(e))return e.map(e=>me(e));if(n.isObject(e)&&be(e)){const t=Object.entries(e).map(([e,t])=>[e,me(t)]);return{...Object.fromEntries(t),[pe.tag]:e[pe.tag]??pe.id()}}return e}function ye(e){if(Array.isArray(e))return e.filter(e=>pe.tag in e).map(e=>e[pe.tag]??"").join(",");const t=e[pe.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function be(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function ve(e){return n.isNullable(e)||n.isString(e)||n.isNumber(e)||n.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function ge(e,t,r,o,s,c){return function a(i,u=t.path){if(i instanceof de){const t=he(r,u.join("."));if(Object.entries(i).filter(([e,t])=>!de.keys.has(e)&&t instanceof de).forEach(([e,t])=>a(t,u.concat(e))),ve(i.value)){if(e===le.Hydrate)return i.value;const a=u.slice(0,-1),l=a.length>0?he(r,a.join(".")):r;return n.isNullable(l)||we(l,i,u.at(-1),o,s,c),t??i.value}if(e===le.Hydrate){const e=me(a(i.value,u));return we(e,i,null,o,s,c),e}const l=t??me(i.value);return we(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)&&!be(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===le.Hydrate){const e=me(n);return Object.entries(i).forEach(([t,n])=>{n instanceof de&&ve(n.value)&&we(e,n,t,o,s,c)}),e}return n}return i}(t.value)}function we(e,t,n,r,o,s){const c=s(e),a=o.get(c)??[];o.set(c,[t.assign(n,r),...a])}class Oe{#e={};#t;#n=/* @__PURE__ */new Map;#r=/* @__PURE__ */new Set;#o=!1;constructor(e=ye){this.#t=e}static pk(){return ie()}static"κ"=Oe.pk;annotate(e,t){return new de(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=he(e(),s),i=s.slice(0,-1),u=r.isNotEmpty(i)?he(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:he(e(),n),inspect:t(n)}):"is"===i?e=>a(n).some(t=>0!==(t.operation&e)):"draft"===i?()=>r.head(a(n))?.value??he(e(),n):"settled"===i?()=>new Promise(t=>{if(r.isEmpty(a(n)))return t(he(e(),n));const o=()=>{r.isEmpty(a(n))&&(c(o),t(he(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(le.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(le.Produce,e)}#s(e,t){const n=/* @__PURE__ */Symbol("process"),[,r]=pe.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>pe.immer.applyPatches(t,[{...r,value:ge(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=me(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 Pe=t.createContext(/* @__PURE__ */new Map);function Se({action:e,renderer:r}){const o=h(),s=t.useContext(Pe),c=V(),a=t.useMemo(()=>{const t=s.get(e);if(t)return t;const r=new Oe,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 je(e,t){const n=t.split(".");let r=e;for(let o=0;o<n.length-1;o++)r=r[n[o]];return{cursor:r,key:n[n.length-1]}}function Ee(e,t,n){const{cursor:r,key:o}=je(e,t);r[o]=n}function xe(e){return(t,n)=>{t.actions.produce(t=>{Ee(t.model,e,n)})}}function ke(e){return t=>{t.actions.produce(t=>{!function(e,t){const{cursor:n,key:r}=je(e,t);n[r]=!n[r]}(t.model,e)})}}function Ce(e,t){return n=>{n.actions.produce(n=>{Ee(n.model,e,t)})}}function Ne(){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=h(),i=t.useContext(Z),u=t.useContext(y),l=g(),d=t.useContext(v),p=t.useContext(_),m=t.useContext(U),b=V(),O=t.useRef(!1),P=t.useRef(null),S=t.useRef(new Oe);O.current||(O.current=!0,P.current=S.current.hydrate(o));const[j,E]=t.useState(()=>S.current.model),C=function(e){const n=t.useRef(e);return n.current=e,t.useMemo(()=>{return t=n,Object.keys(e).reduce((e,n)=>(Object.defineProperty(e,n,{get:()=>t.current[n],enumerable:!0}),e),{});var t},[e])}(s()),N=t.useMemo(()=>new f,[]),A=t.useRef({handlers:/* @__PURE__ */new Map});A.current.handlers=/* @__PURE__ */new Map;const R=function(){const e=t.useRef(/* @__PURE__ */new Set),n=t.useRef(/* @__PURE__ */new Set);return t.useMemo(()=>({broadcast:e.current,multicast:n.current}),[])}(),L=t.useRef(M.Mounting),$=t.useRef(/* @__PURE__ */new Set),T=t.useRef(0),z=t.useCallback((e,t,r)=>{const o=new AbortController,s={controller:o,action:e,payload:t};return u.add(s),$.current.add(s),{model:S.current.model,get phase(){return L.current},task:s,data:C,tasks:u,env:l,actions:{produce(e){if(o.signal.aborted)return;const t=d.current,n=S.current.produce(t=>{d.current=a(d.current,n=>{e({model:t,inspect:S.current.inspect,env:n})})});E(S.current.model),d.current!==t&&c.emit(k,d.current),r.processes.add(n),P.current&&(r.processes.add(P.current),P.current=null)},dispatch(e,t){if(o.signal.aborted)return Promise.resolve();const n=W(e),r=F(e)?e.channel:void 0;return J(e)?i?I(i.emitter,n,t,r):Promise.resolve():I(B(e)?c:N,n,t,r)},annotate:(e,t=ue.Update)=>S.current.annotate(t,e),get inspect(){return S.current.inspect},resource:Object.assign(function(e){const t=(e,t)=>{if(o.signal.aborted)return Promise.resolve();const n=e,r=W(n);return J(n)?i?I(i.emitter,r,t,void 0):Promise.resolve():B(n)?I(c,r,t,void 0):Promise.resolve()},r={exceedsWindow:null,coalesceToken:void 0},s={then:(s,c)=>(()=>{if(n.isNotNullable(r.exceedsWindow)){const{data:t,at:o}=e.read(e.params);if(t!==K&&n.isNotNullable(o)){const e=Temporal.Now.instant().since(o),n=Temporal.Duration.from(r.exceedsWindow);if(Temporal.Duration.compare(e,n)<=0)return Promise.resolve(t)}}if(n.isUndefined(r.coalesceToken))return e.run(l,o,e.params,t);let s=p.get(e.run);n.isUndefined(s)&&(s=/* @__PURE__ */new Map,p.set(e.run,s));const c=s,a=`${JSON.stringify(e.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)}`}}(r.coalesceToken)}`,i=c.get(a);if(i)return ae(i,o.signal);const u=new AbortController,f=e.run(l,u,e.params,t).finally(()=>{c.delete(a)});return c.set(a,f),ae(f,o.signal)})().then(s,c),exceeds:e=>(r.exceedsWindow=e,s),coalesce:e=>(r.coalesceToken=e??ce,s),evict(t){e.evict(t??e.params)}};return s},{nuke:e=>function(e){const t=e??{};for(const n of re)n(t)}(e)}),async final(e){if(o.signal.aborted)return null;const t=W(e),r=J(e)?i?.emitter??null:c;if(!r)return null;const s=r.getCached(t);if(n.isUndefined(s))return null;const a=S.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=W(e),n=J(e)?i?.emitter??null:c;return n?n.getCached(t)??null:null}}}},[j]);t.useLayoutEffect(()=>{function e(e,t,r){return function(o,s){const a=r();if(s===H&&n.isNotNullable(a))return;if(n.isNotNullable(s)&&s!==H&&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 l={processes:/* @__PURE__ */new Set},f=Promise.withResolvers(),p=z(e,o,l),h=function(e){const t=W(e),r=n.isString(t)?t:t.description??"";return r.startsWith(w())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}(e),y=performance.now(),v=S.current.model,g=d.current;let O,P=!1;function j(){const e=S.current.model,t=d.current;return{model:v===e?null:{before:v,after:e},env:g===t?null:{before:g,after:t}}}function E(){const t=s===H?void 0:s;return J(e)?i?I(i.emitter,e,o,t):Promise.resolve():I(B(e)?c:N,e,o,t)}function k(e){P=!0;const t=G(A.current.handlers,"Error"),r=n.isNotNullable(t),s=function(e){return e instanceof Error&&"AbortError"===e.name?X.Aborted:X.Errored}(e),a=function(e){return e instanceof Error?e:new Error(String(e))}(e),i={reason:s,error:a,action:h,handled:r,tasks:u,retry:E};c.fire(x,i),r&&t&&N.emit(t,i),m({stage:"end",result:"error",action:{name:h,payload:o},details:{task:p.task,elapsed:performance.now()-y,mutations:j(),error:a,reason:s}})}function C(){for(const e of u)if(e===p.task){u.delete(e),$.current.delete(e);break}l.processes.forEach(e=>S.current.prune(e)),l.processes.size>0&&b(),P||m({stage:"end",result:"success",action:{name:h,payload:o},details:{task:p.task,elapsed:performance.now()-y,mutations:j()}}),f.resolve()}m({stage:"start",action:{name:h,payload:o},details:{task:p.task}});try{O=t(p,o)}catch(M){return k(M),C(),f.promise}return function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(O)?((async()=>{for await(const e of O);})().catch(k).finally(C),f.promise):(Promise.resolve(O).catch(k).finally(C),f.promise)}}T.current++;const t=/* @__PURE__ */new Set;return A.current.handlers.forEach((n,r)=>{for(const{getChannel:o,handler:s}of n){const n=e(r,s,o);if(J(r)){if(i){const e=i.emitter;e.on(r,n),t.add(()=>e.off(r,n))}N.on(r,n),R.multicast.add(r),t.add(()=>N.off(r,n))}else B(r)?(c.on(r,n),N.on(r,n),R.broadcast.add(r),t.add(()=>{c.off(r,n),N.off(r,n)})):(N.on(r,n),t.add(()=>N.off(r,n)))}}),()=>{const e=++T.current,n=new Set(t);queueMicrotask(()=>{if(T.current!==e){for(const e of n)e();return}for(const e of $.current)e.controller.abort(new Y("Component unmounted")),u.delete(e);$.current.clear(),L.current=M.Unmounting;const t=G(A.current.handlers,"Unmount");t&&N.emit(t),L.current=M.Unmounted;for(const e of n)e()})}},[N]),function({unicast:e,broadcast:o,dispatchers:s,scope:c,phase:a,data:i,handlers:u}){const l=t.useRef(null);t.useLayoutEffect(()=>{if(a.current===M.Mounted)return;a.current=M.Mounting;const t=G(u,"Mount");t&&e.emit(t),s.broadcast.forEach(t=>{const r=o.getCached(t);n.isNullable(r)||e.emit(t,r,H)}),c&&s.multicast.forEach(t=>{const r=c.emitter.getCached(t);n.isNullable(r)||e.emit(t,r,H)}),a.current=M.Mounted},[]),t.useLayoutEffect(()=>{if(n.isNotNullable(l.current)){const t=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(l.current,i);if(r.isNotEmpty(Object.keys(t))){const n=G(u,"Update");n&&e.emit(n,t)}}l.current=i},[i,e])}({unicast:N,broadcast:c,dispatchers:R,scope:i,phase:L,data:s(),handlers:A.current.handlers});const D=t.useMemo(()=>({dispatch(e,t){const n=W(e),r=F(e)?e.channel:void 0;return J(e)?i?I(i.emitter,n,t,r):Promise.resolve():I(B(e)?c:N,n,t,r)},get inspect(){return S.current.inspect},stream:(e,n)=>t.createElement(Se,{action:W(e),renderer:n})}),[j,N]),q=t.useMemo(()=>[j,D,C],[j,D,C]);return q.useAction=(e,n)=>{!function(e,n,r){const o=t.useRef(r);t.useLayoutEffect(()=>{o.current=r});const s=t.useRef(n);t.useLayoutEffect(()=>{s.current=n});const c=t.useCallback((e,t)=>o.current(e,t),[]),a=t.useCallback(()=>F(s.current)?s.current.channel:void 0,[]),i=W(n),u=e.current.handlers.get(i)??/* @__PURE__ */new Set;0===u.size&&e.current.handlers.set(i,u),u.add({getChannel:a,handler:c})}(A,e,n)},q.dispatch=q[1].dispatch,q}(...o);return e.current=s.dispatch,s},with:{update:e=>xe(e),invert:e=>ke(e),always:(e,t)=>Ce(e,t)}}),[])}function Me(n){return{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 Ne()},useEnv:function(){return g()},Resource:function(e){return se(e,n)}}}function Ae(t){return{Boundary:function({children:n}){/* @__PURE__ */
8
+ return e($,{env:t?.env,tap:t?.tap,children:n})},useContext:function(){return Ne()},useEnv:function(){return g()},Resource:function(e){return se(e,t?.cache)},Scope:()=>Me(t?.cache)}}const _e={Update:e=>xe(e),Invert:e=>ke(e),Always:(e,t)=>Ce(e,t)},Re=new Oe;function Ue(e,t=ue.Update){return Re.annotate(t,e)}function Le(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new Y);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new Y)},{once:!0})})}async function $e(e,t,n){if(t?.aborted)throw new Y;for(;;){if(await n())return;await Le(e,t)}}function Te(e){return e?Boolean(e&&"symbol"!=typeof e):/* @__PURE__ */Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const We=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,pk:Te,poll:$e,sleep:Le,unset:K,"ζ":Le,"κ":Te,"π":$e},Symbol.toStringTag,{value:"Module"})),Be=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,Resource:function(e){return se(e)},Scope:function(){return Me()},useContext:function(){return Ne()},useEnv:function(){return g()}},Symbol.toStringTag,{value:"Module"}));export{Y as Aborted,D as Action,Ae as App,$ as Boundary,ee as Cache,N as Distribution,C as Lifecycle,ue as Op,ue as Operation,X as Reason,Oe as State,_e as With,Ue as annotate,Be as shared,We as utils};
9
+ //# sourceMappingURL=march-hare.js.map