chizu 0.2.71 → 0.3.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.
@@ -1 +1 @@
1
- var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function c(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 s=c(r);class i{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node");static Cache=Symbol("chizu.brand/Cache")}function a(e){const t=Symbol(`chizu.action.lifecycle/${e}`),n=function(e){return{[i.Action]:t,[i.Payload]:void 0,[i.Channel]:e,channel:e}};return Object.defineProperty(n,i.Action,{value:t,enumerable:!1}),Object.defineProperty(n,i.Payload,{value:void 0,enumerable:!1}),n}var u=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(u||{}),l=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(l||{}),f=(e=>(e.On="on",e.Off="off",e.Toggle="toggle",e))(f||{}),d=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(d||{});class h extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class p extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}const m={actionPrefix:"chizu.action/",broadcastActionPrefix:"chizu.action/broadcast/",multicastActionPrefix:"chizu.action/multicast/",channelPrefix:"chizu.channel/",cachePrefix:"chizu.cache/",lifecyclePrefix:"chizu.action.lifecycle/"};function b(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new h);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new h)},{once:!0})})}async function y(e,t,n){if(t?.aborted)throw new h;for(;;){if(await n())return;await b(e,t)}}function v(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const g=Object.freeze(Object.defineProperty({__proto__:null,config:m,pk:v,poll:y,sleep:b,"ζ":b,"κ":v,"π":y},Symbol.toStringTag,{value:"Module"})),w=e=>"symbol"==typeof e;function x(e){return t.G.isString(e)||w(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&i.Action in e?e[i.Action]:e}function j(e){if(t.G.isString(e))return e.startsWith(m.broadcastActionPrefix);if(w(e))return e.description?.startsWith(m.broadcastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(i.Broadcast in e&&e[i.Broadcast])return!0;if(i.Action in e){const t=e[i.Action];return t.description?.startsWith(m.broadcastActionPrefix)??!1}}return!1}function P(e){const n=x(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(m.actionPrefix)&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function S(e){return t.G.isObject(e)&&i.Channel in e&&"channel"in e}function O(e){const t=x(e),n=w(t)?t.description??"":t;return n.startsWith(m.lifecyclePrefix)&&n.slice(m.lifecyclePrefix.length)||null}function E(e){if(t.G.isString(e))return e.startsWith(m.multicastActionPrefix);if(w(e))return e.description?.startsWith(m.multicastActionPrefix)??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(i.Multicast in e&&e[i.Multicast])return!0;if(i.Action in e){const t=e[i.Action];return t.description?.startsWith(m.multicastActionPrefix)??!1}}return!1}function A(e){const t=function(e){return e[i.Cache]}(e),n=function(e){return"channel"in e}(e)&&(r=e.channel)?[...Object.keys(r)].toSorted().map(e=>`${e}=${String(r[e])}`).join("&"):"";var r;return`${String(t)}:${n}`}function C(e){if(e instanceof Error){if("TimeoutError"===e.name)return d.Timedout;if("AbortError"===e.name)return d.Supplanted;if("DisallowedError"===e.name)return d.Disallowed}return d.Errored}function M(e){return e instanceof Error?e:new Error(String(e))}const k=r.createContext(void 0);let G=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var _=(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))(_||{}),R=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(R||{}),N=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(N||{});class U{[o.immerable]=!0;static keys=new Set(Object.values(N));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new U(this.value,this.operation);return n.property=e,n.process=t,n}}class L{static immer=(()=>{o.enablePatches();const e=new o.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=G}function z(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function T(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)&&$(e)){const t=Object.entries(e).map(([e,t])=>[e,T(t)]);return{...Object.fromEntries(t),[L.tag]:e[L.tag]??L.id()}}return e}function D(e){if(Array.isArray(e))return e.filter(e=>L.tag in e).map(e=>e[L.tag]??"").join(",");const t=e[L.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function $(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 W(e,n,r,o,c,s){return function i(a,u=n.path){if(a instanceof U){const n=z(r,u.join("."));if(Object.entries(a).filter(([e,t])=>!U.keys.has(e)&&t instanceof U).forEach(([e,t])=>i(t,u.concat(e))),B(a.value)){if(e===R.Hydrate)return a.value;const i=u.slice(0,-1),l=i.length>0?z(r,i.join(".")):r;return t.G.isNullable(l)||F(l,a,u.at(-1),o,c,s),n??a.value}if(e===R.Hydrate){const e=T(i(a.value,u));return F(e,a,null,o,c,s),e}const l=n??T(a.value);return F(l,a,null,o,c,s),t.G.isNullable(n)?l:(i(a.value,u),n)}if(t.G.isArray(a))return a.map((e,t)=>i(e,u.concat(t)));if(t.G.isObject(a)&&!$(a))return a;if(t.G.isObject(a)){const t=Object.entries(a).map(([e,t])=>[e,i(t,u.concat(e))]),n=Object.fromEntries(t);if(e===R.Hydrate){const e=T(n);return Object.entries(a).forEach(([t,n])=>{n instanceof U&&B(n.value)&&F(e,n,t,o,c,s)}),e}return n}return a}(n.value)}function F(e,t,n,r,o,c){const s=c(e),i=o.get(s)??[];o.set(s,[t.assign(n,r),...i])}class H{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=D){this.#t=e}static pk(){return G()}static"κ"=H.pk;annotate(e,t){return new U(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,c){function s(o){const c=o.at(-1),s=z(e(),o),i=o.slice(0,-1),a=t.A.isNotEmpty(i)?z(e(),i):e();return[...t.G.isObject(s)||t.G.isArray(s)?n.get(r(s))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(a)?n.get(r(a))?.filter(e=>e.property===c)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,a)=>"pending"===a?()=>!t.A.isEmpty(s(r)):"remaining"===a?()=>t.A.length(s(r)):"box"===a?()=>({value:z(e(),r),inspect:n(r)}):"is"===a?e=>s(r).some(t=>0!==(t.operation&e)):"draft"===a?()=>t.A.head(s(r))?.value??z(e(),r):"settled"===a?()=>new Promise(n=>{if(t.A.isEmpty(s(r)))return n(z(e(),r));const i=()=>{t.A.isEmpty(s(r))&&(c(i),n(z(e(),r)))};o(i)}):n([...r,String(a)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#c(R.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#c(R.Produce,e)}#c(e,t){const n=Symbol("process"),[,r]=L.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>L.immer.applyPatches(t,[{...r,value:W(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=T(this.#e),this.#s(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#s()}#s(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const I=new H;function q(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var V,J={exports:{}},K=(V||(V=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 c(e,t,r,c,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,c||e,s),a=n?n+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],i]:e._events[a].push(i):(e._events[a]=i,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),i.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},i.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,c=new Array(o);r<o;r++)c[r]=t[r].fn;return c},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,c,s){var i=n?n+e:e;if(!this._events[i])return!1;var a,u,l=this._events[i],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,c),!0;case 6:return l.fn.call(l.context,t,r,o,c,s),!0}for(u=1,a=new Array(f-1);u<f;u++)a[u-1]=arguments[u];l.fn.apply(l.context,a)}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(!a)for(d=1,a=new Array(f-1);d<f;d++)a[d-1]=arguments[d];l[u].fn.apply(l[u].context,a)}}return!0},i.prototype.on=function(e,t,n){return c(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return c(this,e,t,n,!0)},i.prototype.removeListener=function(e,t,r,o){var c=n?n+e:e;if(!this._events[c])return this;if(!t)return s(this,c),this;var i=this._events[c];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||s(this,c);else{for(var a=0,u=[],l=i.length;a<l;a++)(i[a].fn!==t||o&&!i[a].once||r&&i[a].context!==r)&&u.push(i[a]);u.length?this._events[c]=1===u.length?u[0]:u:s(this,c)}return this},i.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&s(this,t):(this._events=new r,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(J)),J.exports);const Q=q(K);class X extends Q{cache=new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}}const Y=s.createContext(new X);function Z(){return s.useContext(Y)}function ee({children:e}){const t=s.useMemo(()=>new X,[]);return n.jsx(Y.Provider,{value:t,children:e})}const te=s.createContext(new Map);function ne({children:e}){const t=s.useMemo(()=>new Map,[]);return n.jsx(te.Provider,{value:t,children:e})}const re=s.createContext(new Set);function oe({children:e}){const t=s.useMemo(()=>new Set,[]);return n.jsx(re.Provider,{value:t,children:e})}const ce=s.createContext({mode:"allow-all",actions:new Set});function se({children:e}){const t=s.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return n.jsx(ce.Provider,{value:t,children:e})}const ie=s.createContext(null);function ae(){return s.useContext(ie)}function ue(e,t){return e?.get(t)??null}function le({name:e,children:t}){const r=ae(),o=s.useMemo(()=>({name:e,emitter:new X}),[]),c=s.useMemo(()=>{const t=new Map(r??[]);return t.set(e,o),t},[r,e,o]);return n.jsx(ie.Provider,{value:c,children:t})}function fe(e,t,n){const r=e.features;switch(n){case f.On:r[t]=!0;break;case f.Off:r[t]=!1;break;case f.Toggle:r[t]=!r[t]}}function de(e,t,...n){e instanceof X&&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 he(e,t){for(const n of e.keys())if(O(n)===t)return n;return null}function pe(){const[,e]=s.useReducer(e=>e+1,0);return e}const me=s.createContext(new Map);function be({action:e,renderer:n}){const r=Z(),o=s.useContext(me),c=pe(),i=s.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new H,listeners:new Set};return o.set(e,n),n},[e,o]);s.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(c),r.on(e,t),()=>{i.listeners.delete(c),r.off(e,t)}},[e,r,i]);const a=i.state.model?.value;return t.G.isNullable(a)?null:n(a,i.state.inspect.value)}e.Action=(e,t=u.Unicast)=>{const n=t===u.Broadcast?Symbol(`${m.broadcastActionPrefix}${e}`):t===u.Multicast?Symbol(`${m.multicastActionPrefix}${e}`):Symbol(`${m.actionPrefix}${e}`),r=function(e){return{[i.Action]:n,[i.Payload]:void 0,[i.Channel]:e,channel:e}};return Object.defineProperty(r,i.Action,{value:n,enumerable:!1}),Object.defineProperty(r,i.Payload,{value:void 0,enumerable:!1}),t===u.Broadcast&&Object.defineProperty(r,i.Broadcast,{value:!0,enumerable:!1}),t===u.Multicast&&Object.defineProperty(r,i.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return n.jsx(ee,{children:n.jsx(ne,{children:n.jsx(se,{children:n.jsx(oe,{children:e})})})})},e.DisallowedError=p,e.Distribution=u,e.Entry=function(){const e=Symbol("chizu.cache/Entry"),t=function(t){return{[i.Cache]:e,channel:t}};return Object.defineProperty(t,i.Cache,{value:e,enumerable:!1}),t},e.Error=function({handler:e,children:t}){return n.jsx(k.Provider,{value:e,children:t})},e.Feature=f,e.Lifecycle=class{static Mount(){return a("Mount")}static Unmount(){return a("Unmount")}static Error(){return a("Error")}static Update(){return a("Update")}static Node(){return a("Node")}},e.Op=_,e.Operation=_,e.Reason=d,e.Regulators=se,e.Scope=le,e.State=H,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return I.annotate(e,t)},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]??(()=>({})),c=Z(),i=ae(),a=r.useContext(k),u=s.useContext(re),f=s.useContext(te),h=s.useContext(ce),m=pe(),b=s.useRef(!1),y=s.useRef(null),v=s.useRef(new H);b.current||(b.current=!0,y.current=v.current.hydrate(n));const[g,w]=s.useState(()=>v.current.model),O=function(e){const t=s.useRef(e);return s.useLayoutEffect(()=>{t.current=e},[e]),s.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()),G=s.useMemo(()=>new Q,[]),_=s.useRef({handlers:new Map});_.current.handlers=new Map;const R=function(){const e=s.useRef(new Set),t=s.useRef(new Set);return s.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),N=s.useRef(l.Mounting),U=function(){const e=s.useRef({}),t=s.useRef(new Map),n=s.useRef(new Map);return s.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),L=s.useRef(new Set),z=s.useRef(0),T=s.useCallback((e,t,n)=>{const r=new AbortController,o={controller:r,action:e,payload:t};return u.add(o),L.current.add(o),{model:v.current.model,get phase(){return N.current},task:o,data:O,tasks:u,nodes:U.refs.current,regulator:{disallow(...e){if(h.actions.clear(),0===e.length)h.mode="disallow-all";else{h.mode="disallow-matching";for(const t of e)h.actions.add(x(t))}},allow(...e){if(h.actions.clear(),0===e.length)h.mode="allow-all";else{h.mode="allow-matching";for(const t of e)h.actions.add(x(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=v.current.produce(t=>e({model:t,inspect:v.current.inspect}));w(v.current.model),n.processes.add(t),y.current&&(n.processes.add(y.current),y.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const o=x(e),s=S(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ue(i,n.scope);return e?de(e.emitter,o,t,s):Promise.resolve()}return de(j(e)?c:G,o,t,s)},annotate:(e,t)=>v.current.annotate(e,t),async cacheable(e,t,n){if(r.signal.aborted)return{data:null};const o=A(e),c=f.get(o);if(c&&Date.now()<c.expiry)return{data:c.value};const s=function(e){return null!=e&&"object"==typeof e&&"TAG"in e?0===e.TAG?{ok:!0,value:e._0}:{ok:!1}:null==e?{ok:!1}:{ok:!0,value:e}}(await n());return s.ok?(f.set(o,{value:s.value,expiry:Date.now()+t}),{data:s.value}):{data:null}},invalidate(e){f.delete(A(e))},feature(e,t){if(r.signal.aborted)return;const o=v.current.produce(n=>fe(n,e,t));w(v.current.model),n.processes.add(o),y.current&&(n.processes.add(y.current),y.current=null)},async read(e,t){if(r.signal.aborted)return null;const n=x(e),o=E(e)&&t?.scope?ue(i,t.scope)?.emitter??null:c;if(!o)return null;if(void 0===o.getCached(n))return null;const s=P(e),a="unknown"!==s?s[0].toLowerCase()+s.slice(1):null;if(a){const e=v.current.inspect[a];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return o.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=x(e),o=E(e)&&t?.scope?ue(i,t.scope)?.emitter??null:c;return o?o.getCached(n)??null:null}}}},[g]);s.useLayoutEffect(()=>{function e(e,n,r){return function(o,c){if(!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(e,h)){const t=he(_.current.handlers,"Error"),n=null!==t,r={reason:d.Disallowed,error:new p,action:P(e),handled:n,tasks:u};return a?.(r),void(n&&t&&G.emit(t,r))}const s=r();if(t.G.isNotNullable(c)&&t.G.isNotNullable(s)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,s))return;const i={processes:new Set},l=Promise.withResolvers(),f=T(e,o,i);function b(t){const n=he(_.current.handlers,"Error"),r=null!==n,o={reason:C(t),error:M(t),action:P(e),handled:r,tasks:u};a?.(o),r&&n&&G.emit(n,o)}function y(){for(const e of u)if(e===f.task){u.delete(e),L.current.delete(e);break}i.processes.forEach(e=>v.current.prune(e)),i.processes.size>0&&m(),l.resolve()}let g;try{g=n(f,o)}catch(w){return b(w),void y()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(g))return Promise.resolve(g).catch(b).finally(y),l.promise;(async()=>{for await(const e of g);})().catch(b).finally(y)}}z.current++;const n=new Set;return _.current.handlers.forEach((t,r)=>{for(const{getChannel:o,handler:s}of t){const t=e(r,s,o);if(E(r)){if(i)for(const e of i.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}G.on(r,t),R.multicast.add(r),n.add(()=>G.off(r,t))}else j(r)?(c.on(r,t),G.on(r,t),R.broadcast.add(r),n.add(()=>{c.off(r,t),G.off(r,t)})):(G.on(r,t),n.add(()=>G.off(r,t)))}}),()=>{const e=++z.current,t=new Set(n);queueMicrotask(()=>{if(z.current!==e){for(const e of t)e();return}for(const e of L.current)e.controller.abort(),u.delete(e);L.current.clear(),N.current=l.Unmounting;const n=he(_.current.handlers,"Unmount");n&&G.emit(n),N.current=l.Unmounted;for(const e of t)e()})}},[G]),s.useLayoutEffect(()=>{const e=he(_.current.handlers,"Node");for(const[t,n]of U.pending.current)U.emitted.current.get(t)!==n&&(U.emitted.current.set(t,n),e&&G.emit(e,n,{Name:t}));U.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:c,data:i,handlers:a}){const u=s.useRef(null);s.useLayoutEffect(()=>{if(c.current!==l.Mounting)return;const s=he(a,"Mount");s&&e.emit(s),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o)}}),c.current=l.Mounted},[]),s.useLayoutEffect(()=>{if(t.G.isNotNullable(u.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(u.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=he(a,"Update");t&&e.emit(t,n)}}u.current=i},[i,e])}({unicast:G,broadcast:c,dispatchers:R,scope:i,phase:N,data:o(),handlers:_.current.handlers});const D=s.useMemo(()=>[g,{dispatch(e,t,n){const r=x(e),o=S(e)?e.channel:void 0;if(E(e)&&n?.scope){const e=ue(i,n.scope);return e?de(e.emitter,r,t,o):Promise.resolve()}return de(j(e)?c:G,r,t,o)},get inspect(){return v.current.inspect},get nodes(){return U.refs.current},node(e,t){U.refs.current[e]=t,U.pending.current.set(e,t)},feature(e,t){const n=v.current.produce(n=>fe(n,e,t));w(v.current.model),v.current.prune(n)},stream:(e,t)=>s.createElement(be,{action:x(e),renderer:t})}],[g,G]);return D.useAction=(e,t)=>{!function(e,t,n){const r=s.useRef(n);s.useLayoutEffect(()=>{r.current=n});const o=s.useRef(t);s.useLayoutEffect(()=>{o.current=t});const c=s.useCallback((e,t)=>r.current(e,t),[]),i=s.useCallback(()=>S(o.current)?o.current.channel:void 0,[]),a=x(t),u=e.current.handlers.get(a)??new Set;0===u.size&&e.current.handlers.set(a,u),u.add({getChannel:i,handler:c})}(_,e,t)},D},e.utils=g,e.withScope=function(e,t){const r=`Scoped${t.displayName||t.name||"Component"}`;return{[r]:r=>n.jsx(le,{name:e,children:n.jsx(t,{...r})})}[r]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("react/jsx-runtime"),require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","react/jsx-runtime","react","immer"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.jsxRuntime,global.React,global.Immer);
1
+ var global,factory;global=this,factory=function(e,t,n,r,o){"use strict";function s(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const c=s(o),i=(e="")=>`chizu.action/${e}`,u=(e="")=>`chizu.action/broadcast/${e}`,a=(e="")=>`chizu.action/multicast/${e}`,l=(e="")=>`chizu.action.lifecycle/${e}`;class f{static Payload=Symbol("chizu.brand/Payload");static Broadcast=Symbol("chizu.brand/Broadcast");static Multicast=Symbol("chizu.brand/Multicast");static Action=Symbol("chizu.brand/Action");static Channel=Symbol("chizu.brand/Channel");static Node=Symbol("chizu.action.lifecycle/Node")}function d(e){const t=Symbol(`chizu.action.lifecycle/${e}`),n=function(e){return{[f.Action]:t,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(n,f.Action,{value:t,enumerable:!1}),Object.defineProperty(n,f.Payload,{value:void 0,enumerable:!1}),n}const p=Symbol(u("Fault"));class h{static Mount(){return d("Mount")}static Unmount(){return d("Unmount")}static Error(){return d("Error")}static Update(){return d("Update")}static Node(){return d("Node")}static Fault=(()=>{const e={};return Object.defineProperty(e,f.Action,{value:p,enumerable:!1}),Object.defineProperty(e,f.Payload,{value:void 0,enumerable:!1}),Object.defineProperty(e,f.Broadcast,{value:!0,enumerable:!1}),e})()}var m=(e=>(e.Unicast="unicast",e.Broadcast="broadcast",e.Multicast="multicast",e))(m||{}),b=(e=>(e.Mounting="mounting",e.Mounted="mounted",e.Unmounting="unmounting",e.Unmounted="unmounted",e))(b||{});const y=e=>"symbol"==typeof e;function v(e){return t.G.isString(e)||y(e)?e:(t.G.isObject(e)||t.G.isFunction(e))&&f.Action in e?e[f.Action]:e}function g(e){if(t.G.isString(e))return e.startsWith(u());if(y(e))return e.description?.startsWith(u())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Broadcast in e&&e[f.Broadcast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(u())??!1}}return!1}function w(e){const n=v(e),r=t.G.isString(n)?n:n.description??"";return r.startsWith(i())&&r.slice(r.lastIndexOf("/")+1)||"unknown"}function j(e){return t.G.isObject(e)&&f.Channel in e&&"channel"in e}function S(e){const t=v(e),n=y(t)?t.description??"":t;return n.startsWith(l())&&n.slice(l().length)||null}function O(e){if(t.G.isString(e))return e.startsWith(a());if(y(e))return e.description?.startsWith(a())??!1;if(t.G.isObject(e)||t.G.isFunction(e)){if(f.Multicast in e&&e[f.Multicast])return!0;if(f.Action in e){const t=e[f.Action];return t.description?.startsWith(a())??!1}}return!1}var E=(e=>(e[e.Timedout=0]="Timedout",e[e.Supplanted=1]="Supplanted",e[e.Disallowed=2]="Disallowed",e[e.Errored=3]="Errored",e[e.Unmounted=4]="Unmounted",e))(E||{});class x extends Error{name="AbortError";constructor(e="Aborted"){super(e)}}class P extends Error{name="TimeoutError";constructor(e="Timeout"){super(e)}}class M extends Error{name="DisallowedError";constructor(e="Disallowed"){super(e)}}let A=(e=21)=>{let t="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&n[e]];return t};var C=(e=>(e[e.Add=1]="Add",e[e.Remove=2]="Remove",e[e.Update=4]="Update",e[e.Move=8]="Move",e[e.Replace=16]="Replace",e[e.Sort=32]="Sort",e[e.Create=64]="Create",e[e.Fetch=128]="Fetch",e[e.Clone=256]="Clone",e[e.Archive=512]="Archive",e[e.Restore=1024]="Restore",e[e.Merge=2048]="Merge",e[e.Reorder=4096]="Reorder",e[e.Sync=8192]="Sync",e[e.Publish=16384]="Publish",e[e.Link=32768]="Link",e[e.Unlink=65536]="Unlink",e[e.Lock=131072]="Lock",e[e.Unlock=262144]="Unlock",e[e.Import=524288]="Import",e[e.Export=1048576]="Export",e[e.Transfer=2097152]="Transfer",e))(C||{}),G=(e=>(e[e.Produce=0]="Produce",e[e.Hydrate=1]="Hydrate",e))(G||{}),k=(e=>(e.Property="property",e.Process="process",e.Value="value",e.Operation="operation",e))(k||{});class R{[n.immerable]=!0;static keys=new Set(Object.values(k));property=null;process=null;value;operation;constructor(e,t){this.value=e,this.operation=t}assign(e,t){const n=new R(this.value,this.operation);return n.property=e,n.process=t,n}}class _{static immer=(()=>{n.enablePatches();const e=new n.Immer;return e.setAutoFreeze(!1),e})();static tag="κ";static id=A}function N(e,t){const n="string"==typeof t?""===t?[]:t.split("."):t;let r=e;for(const o of n){if(null==r)return;r=r[o]}return r}function U(e){if(t.G.isNullable(e)||T(e))return e;if(t.G.isArray(e))return e.map(e=>U(e));if(t.G.isObject(e)&&z(e)){const t=Object.entries(e).map(([e,t])=>[e,U(t)]);return{...Object.fromEntries(t),[_.tag]:e[_.tag]??_.id()}}return e}function L(e){if(Array.isArray(e))return e.filter(e=>_.tag in e).map(e=>e[_.tag]??"").join(",");const t=e[_.tag];if(t)return t;try{return JSON.stringify(e)}catch{return`[unserializable:${typeof e}]`}}function z(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function T(e){return t.G.isNullable(e)||t.G.isString(e)||t.G.isNumber(e)||t.G.isBoolean(e)||"symbol"==typeof e||"bigint"==typeof e}function B(e,n,r,o,s,c){return function i(u,a=n.path){if(u instanceof R){const n=N(r,a.join("."));if(Object.entries(u).filter(([e,t])=>!R.keys.has(e)&&t instanceof R).forEach(([e,t])=>i(t,a.concat(e))),T(u.value)){if(e===G.Hydrate)return u.value;const i=a.slice(0,-1),l=i.length>0?N(r,i.join(".")):r;return t.G.isNullable(l)||D(l,u,a.at(-1),o,s,c),n??u.value}if(e===G.Hydrate){const e=U(i(u.value,a));return D(e,u,null,o,s,c),e}const l=n??U(u.value);return D(l,u,null,o,s,c),t.G.isNullable(n)?l:(i(u.value,a),n)}if(t.G.isArray(u))return u.map((e,t)=>i(e,a.concat(t)));if(t.G.isObject(u)&&!z(u))return u;if(t.G.isObject(u)){const t=Object.entries(u).map(([e,t])=>[e,i(t,a.concat(e))]),n=Object.fromEntries(t);if(e===G.Hydrate){const e=U(n);return Object.entries(u).forEach(([t,n])=>{n instanceof R&&T(n.value)&&D(e,n,t,o,s,c)}),e}return n}return u}(n.value)}function D(e,t,n,r,o,s){const c=s(e),i=o.get(c)??[];o.set(c,[t.assign(n,r),...i])}class F{#e={};#t;#n=new Map;#r=new Set;#o=!1;constructor(e=L){this.#t=e}static pk(){return A()}static"κ"=F.pk;annotate(e,t){return new R(t,e)}"δ"=this.annotate;get model(){return this.#e}get inspect(){return function(e,n,r,o,s){function c(o){const s=o.at(-1),c=N(e(),o),i=o.slice(0,-1),u=t.A.isNotEmpty(i)?N(e(),i):e();return[...t.G.isObject(c)||t.G.isArray(c)?n.get(r(c))?.filter(e=>t.G.isNullable(e.property))??[]:[],...t.G.isObject(u)?n.get(r(u))?.filter(e=>e.property===s)??[]:[]]}return function n(r){return new Proxy(()=>{},{get:(i,u)=>"pending"===u?()=>!t.A.isEmpty(c(r)):"remaining"===u?()=>t.A.length(c(r)):"box"===u?()=>({value:N(e(),r),inspect:n(r)}):"is"===u?e=>c(r).some(t=>0!==(t.operation&e)):"draft"===u?()=>t.A.head(c(r))?.value??N(e(),r):"settled"===u?()=>new Promise(n=>{if(t.A.isEmpty(c(r)))return n(N(e(),r));const i=()=>{t.A.isEmpty(c(r))&&(s(i),n(N(e(),r)))};o(i)}):n([...r,String(u)])})}([])}(()=>this.#e,this.#n,this.#t,e=>this.#r.add(e),e=>this.#r.delete(e))}hydrate(e){return this.#o=!0,this.#s(G.Hydrate,()=>e)}produce(e){if(!this.#o)throw new Error("State must be hydrated using hydrate() before calling produce()");return this.#s(G.Produce,e)}#s(e,t){const n=Symbol("process"),[,r]=_.immer.produceWithPatches(this.#e,t);return this.#e=r.reduce((t,r)=>_.immer.applyPatches(t,[{...r,value:B(e,r,t,n,this.#n,this.#t)}]),this.#e),this.#e=U(this.#e),this.#c(),n}prune(e){this.#n.forEach((n,r)=>{const o=n.filter(t=>t.process!==e);t.A.isEmpty(o)?this.#n.delete(r):this.#n.set(r,o)}),this.#c()}#c(){this.#r.forEach(e=>e())}observe(e){const t=()=>e(this.#e);return this.#r.add(t),()=>this.#r.delete(t)}}const W=new F;function $(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var H,I={exports:{}},q=(H||(H=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function o(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function s(e,t,r,s,c){if("function"!=typeof r)throw new TypeError("The listener must be a function");var i=new o(r,s||e,c),u=n?n+t:t;return e._events[u]?e._events[u].fn?e._events[u]=[e._events[u],i]:e._events[u].push(i):(e._events[u]=i,e._eventsCount++),e}function c(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function i(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),i.prototype.eventNames=function(){var e,r,o=[];if(0===this._eventsCount)return o;for(r in e=this._events)t.call(e,r)&&o.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},i.prototype.listeners=function(e){var t=this._events[n?n+e:e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,s=new Array(o);r<o;r++)s[r]=t[r].fn;return s},i.prototype.listenerCount=function(e){var t=this._events[n?n+e:e];return t?t.fn?1:t.length:0},i.prototype.emit=function(e,t,r,o,s,c){var i=n?n+e:e;if(!this._events[i])return!1;var u,a,l=this._events[i],f=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),f){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,r),!0;case 4:return l.fn.call(l.context,t,r,o),!0;case 5:return l.fn.call(l.context,t,r,o,s),!0;case 6:return l.fn.call(l.context,t,r,o,s,c),!0}for(a=1,u=new Array(f-1);a<f;a++)u[a-1]=arguments[a];l.fn.apply(l.context,u)}else{var d,p=l.length;for(a=0;a<p;a++)switch(l[a].once&&this.removeListener(e,l[a].fn,void 0,!0),f){case 1:l[a].fn.call(l[a].context);break;case 2:l[a].fn.call(l[a].context,t);break;case 3:l[a].fn.call(l[a].context,t,r);break;case 4:l[a].fn.call(l[a].context,t,r,o);break;default:if(!u)for(d=1,u=new Array(f-1);d<f;d++)u[d-1]=arguments[d];l[a].fn.apply(l[a].context,u)}}return!0},i.prototype.on=function(e,t,n){return s(this,e,t,n,!1)},i.prototype.once=function(e,t,n){return s(this,e,t,n,!0)},i.prototype.removeListener=function(e,t,r,o){var s=n?n+e:e;if(!this._events[s])return this;if(!t)return c(this,s),this;var i=this._events[s];if(i.fn)i.fn!==t||o&&!i.once||r&&i.context!==r||c(this,s);else{for(var u=0,a=[],l=i.length;u<l;u++)(i[u].fn!==t||o&&!i[u].once||r&&i[u].context!==r)&&a.push(i[u]);a.length?this._events[s]=1===a.length?a[0]:a:c(this,s)}return this},i.prototype.removeAllListeners=function(e){var t;return e?this._events[t=n?n+e:e]&&c(this,t):(this._events=new r,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,e.exports=i}(I)),I.exports);const J=$(q);class V extends J{cache=new Map;emit(e,...t){return this.cache.set(e,t[0]),super.emit(e,...t)}setCache(e,t){this.cache.set(e,t)}getCached(e){return this.cache.get(e)}fire(e,...t){return super.emit(e,...t)}}const K=c.createContext(new V);function Q(){return c.useContext(K)}function X({children:e}){const t=c.useMemo(()=>new V,[]);return r.jsx(K.Provider,{value:t,children:e})}const Y=c.createContext(new Set);function Z({children:e}){const t=c.useMemo(()=>new Set,[]);return r.jsx(Y.Provider,{value:t,children:e})}const ee=c.createContext({mode:"allow-all",actions:new Set});function te({children:e}){const t=c.useMemo(()=>({mode:"allow-all",actions:new Set}),[]);return r.jsx(ee.Provider,{value:t,children:e})}const ne=c.createContext(null);function re(){return c.useContext(ne)}function oe(e,t){return e?.get(t)??null}function se({of:e,children:t}){const n=re(),o=e.Scope,s=c.useMemo(()=>({name:o,emitter:new V}),[]),i=c.useMemo(()=>{const e=new Map(n??[]);return e.set(o,s),e},[n,o,s]);return r.jsx(ne.Provider,{value:i,children:t})}const ce=Symbol(((e="")=>`chizu/replay${e}`)());function ie(e,t,...n){e instanceof V&&e.setCache(t,n[0]);const r=e.listeners(t);return 0===r.length?Promise.resolve():Promise.all(r.map(e=>Promise.resolve(e(...n)))).then(()=>{})}function ue(e,t){for(const n of e.keys())if(S(n)===t)return n;return null}function ae(){const[,e]=c.useReducer(e=>e+1,0);return e}function le(e){if(e instanceof Error){if("TimeoutError"===e.name)return E.Timedout;if("AbortError"===e.name)return E.Supplanted;if("DisallowedError"===e.name)return E.Disallowed}return E.Errored}const fe=c.createContext(new Map);function de({action:e,renderer:n}){const r=Q(),o=c.useContext(fe),s=ae(),i=c.useMemo(()=>{const t=o.get(e);if(t)return t;const n={state:new F,listeners:new Set};return o.set(e,n),n},[e,o]);c.useLayoutEffect(()=>{function t(e){i.state.hydrate({value:e}),i.listeners.forEach(e=>e())}return i.listeners.add(s),r.on(e,t),()=>{i.listeners.delete(s),r.off(e,t)}},[e,r,i]);const u=i.state.model?.value;return t.G.isNullable(u)?null:n(u,i.state.inspect.value)}function pe(e,t){return new Promise((n,r)=>{if(t?.aborted)return void r(new x);const o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),r(new x)},{once:!0})})}async function he(e,t,n){if(t?.aborted)throw new x;for(;;){if(await n())return;await pe(e,t)}}function me(e){return e?Boolean(e&&"symbol"!=typeof e):Symbol(`pk.${Date.now()}.${crypto.randomUUID()}`)}const be=Object.freeze(Object.defineProperty({__proto__:null,pk:me,poll:he,sleep:pe,"ζ":pe,"κ":me,"π":he},Symbol.toStringTag,{value:"Module"}));e.AbortError=x,e.Action=(e,t=m.Unicast)=>{const n=t===m.Broadcast?Symbol(u(e)):t===m.Multicast?Symbol(a(e)):Symbol(i(e)),r=function(e){return{[f.Action]:n,[f.Payload]:void 0,[f.Channel]:e,channel:e}};return Object.defineProperty(r,f.Action,{value:n,enumerable:!1}),Object.defineProperty(r,f.Payload,{value:void 0,enumerable:!1}),t===m.Broadcast&&Object.defineProperty(r,f.Broadcast,{value:!0,enumerable:!1}),t===m.Multicast&&Object.defineProperty(r,f.Multicast,{value:!0,enumerable:!1}),r},e.Boundary=function({children:e}){return r.jsx(X,{children:r.jsx(te,{children:r.jsx(Z,{children:e})})})},e.DisallowedError=M,e.Distribution=m,e.Lifecycle=h,e.Op=C,e.Operation=C,e.Reason=E,e.Regulators=te,e.Resource=function(e,t,n,r){const o=new Map;return{key:e,fetch:(e,s,...c)=>{const i=JSON.stringify(c),u=o.get(i);if(u)return u;const a=t(...c).then(t=>(o.get(i)===a&&o.delete(i),n?.({response:t,data:s,dispatch:e}),t),t=>{throw o.get(i)===a&&o.delete(i),r?.({error:t,data:s,dispatch:e}),t});return o.set(i,a),a}}},e.Scope=se,e.State=F,e.TimeoutError=P,e.With=function(e){return(t,n)=>{t.actions.produce(t=>{t.model[e]=n})}},e.annotate=function(e,t){return W.annotate(e,t)},e.useActions=function(...e){const n=t.G.isUndefined(e[0])||t.G.isFunction(e[0])?{}:e[0],r=t.G.isFunction(e[0])?e[0]:e[1]??(()=>({})),o=Q(),s=re(),i=c.useContext(Y),u=c.useContext(ee),a=ae(),l=c.useRef(!1),f=c.useRef(null),d=c.useRef(new F),h=c.useRef({features:null,nodes:null});function m(){null===h.current.features&&null===h.current.nodes||(d.current.model.meta={...null!==h.current.features?{features:h.current.features}:{},...null!==h.current.nodes?{nodes:h.current.nodes}:{}})}if(!l.current){l.current=!0;const e=n,t=e.meta;t?.features&&(h.current.features=t.features),t?.nodes&&(h.current.nodes=t.nodes);const{meta:r,...o}=e;f.current=d.current.hydrate(o),m()}const[y,S]=c.useState(()=>d.current.model),x=function(e){const t=c.useRef(e);return c.useLayoutEffect(()=>{t.current=e},[e]),c.useMemo(()=>{return n=t,Object.keys(e).reduce((e,t)=>(Object.defineProperty(e,t,{get:()=>n.current[t],enumerable:!0}),e),{});var n},[e])}(r()),P=c.useMemo(()=>new J,[]),A=c.useRef({handlers:new Map});A.current.handlers=new Map;const C=function(){const e=c.useRef(new Set),t=c.useRef(new Set);return c.useMemo(()=>({broadcast:e.current,multicast:t.current}),[])}(),G=c.useRef(b.Mounting),k=function(){const e=c.useRef({}),t=c.useRef(new Map),n=c.useRef(new Map);return c.useMemo(()=>({refs:e,pending:t,emitted:n}),[])}(),R=c.useRef(new Set),_=c.useRef(0),N=c.useCallback((e,t,n)=>{const r=new AbortController,c={controller:r,action:e,payload:t};return i.add(c),R.current.add(c),{model:d.current.model,get phase(){return G.current},task:c,data:x,tasks:i,get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},regulator:{disallow(...e){if(u.actions.clear(),0===e.length)u.mode="disallow-all";else{u.mode="disallow-matching";for(const t of e)u.actions.add(v(t))}},allow(...e){if(u.actions.clear(),0===e.length)u.mode="allow-all";else{u.mode="allow-matching";for(const t of e)u.actions.add(v(t))}}},actions:{produce(e){if(r.signal.aborted)return;const t=d.current.produce(t=>{e({model:t,inspect:d.current.inspect})});m(),S(d.current.model),n.processes.add(t),f.current&&(n.processes.add(f.current),f.current=null)},dispatch(e,t,n){if(r.signal.aborted)return Promise.resolve();const c=v(e),i=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,c,t,i):Promise.resolve()}return ie(g(e)?o:P,c,t,i)},annotate:(e,t)=>d.current.annotate(e,t),features:{on(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},off(e){r.signal.aborted||(h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null))},invert(e){if(r.signal.aborted)return;const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model),f.current&&(n.processes.add(f.current),f.current=null)}},async resolution(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;if(!c)return null;if(void 0===c.getCached(n))return null;const i=w(e),u="unknown"!==i?i[0].toLowerCase()+i.slice(1):null;if(u){const e=d.current.inspect[u];e?.pending?.()&&await new Promise((t,n)=>{if(r.signal.aborted)return void n(r.signal.reason);const o=()=>n(r.signal.reason);r.signal.addEventListener("abort",o,{once:!0}),e.settled().then(()=>{r.signal.removeEventListener("abort",o),t()})})}return c.getCached(n)??null},peek(e,t){if(r.signal.aborted)return null;const n=v(e),c=O(e)&&t?.scope?oe(s,t.scope.Scope)?.emitter??null:o;return c?c.getCached(n)??null:null}}}},[y]);c.useLayoutEffect(()=>{function e(e,n,r){return function(s,c){if(e!==p&&!function(e,t){switch(t.mode){case"allow-all":return!0;case"disallow-all":return!1;case"disallow-matching":return!t.actions.has(e);case"allow-matching":return t.actions.has(e)}}(e,u)){const t=ue(A.current.handlers,"Error"),n=null!==t,r={reason:E.Disallowed,error:new M,action:w(e),handled:n,tasks:i};return o.fire(p,r),void(n&&t&&P.emit(t,r))}const l=r();if(c===ce&&t.G.isNotNullable(l))return;if(t.G.isNotNullable(c)&&c!==ce&&t.G.isNotNullable(l)&&!function(e,t){for(const n of Object.keys(e))if(t[n]!==e[n])return!1;return!0}(c,l))return;const f={processes:new Set},h=Promise.withResolvers(),m=N(e,s,f);function b(t){const n=ue(A.current.handlers,"Error"),r=null!==n,s={reason:le(t),error:(c=t,c instanceof Error?c:new Error(String(c))),action:w(e),handled:r,tasks:i};var c;o.fire(p,s),r&&n&&P.emit(n,s)}function y(){for(const e of i)if(e===m.task){i.delete(e),R.current.delete(e);break}f.processes.forEach(e=>d.current.prune(e)),f.processes.size>0&&a(),h.resolve()}let v;try{v=n(m,s)}catch(g){return b(g),void y()}if(!function(e){if(!e||"object"!=typeof e)return!1;const t=Object.prototype.toString.call(e);return"[object Generator]"===t||"[object AsyncGenerator]"===t}(v))return Promise.resolve(v).catch(b).finally(y),h.promise;(async()=>{for await(const e of v);})().catch(b).finally(y)}}_.current++;const n=new Set;return A.current.handlers.forEach((t,r)=>{for(const{getChannel:c,handler:i}of t){const t=e(r,i,c);if(O(r)){if(s)for(const e of s.values()){const o=e.emitter;o.on(r,t),n.add(()=>o.off(r,t))}P.on(r,t),C.multicast.add(r),n.add(()=>P.off(r,t))}else g(r)?(o.on(r,t),P.on(r,t),C.broadcast.add(r),n.add(()=>{o.off(r,t),P.off(r,t)})):(P.on(r,t),n.add(()=>P.off(r,t)))}}),()=>{const e=++_.current,t=new Set(n);queueMicrotask(()=>{if(_.current!==e){for(const e of t)e();return}for(const e of R.current)e.controller.abort(),i.delete(e);R.current.clear(),G.current=b.Unmounting;const n=ue(A.current.handlers,"Unmount");n&&P.emit(n),G.current=b.Unmounted;for(const e of t)e()})}},[P]),c.useLayoutEffect(()=>{const e=ue(A.current.handlers,"Node");let t=!1;for(const[n,r]of k.pending.current)if(k.emitted.current.get(n)!==r){if(k.emitted.current.set(n,r),null!==h.current.nodes){const e={...h.current.nodes};e[n]=r,h.current.nodes=e,t=!0}e&&P.emit(e,r,{Name:n})}t&&(m(),S(d.current.model)),k.pending.current.clear()}),function({unicast:e,broadcast:n,dispatchers:r,scope:o,phase:s,data:i,handlers:u}){const a=c.useRef(null);c.useLayoutEffect(()=>{if(s.current!==b.Mounting)return;const c=ue(u,"Mount");c&&e.emit(c),r.broadcast.forEach(r=>{const o=n.getCached(r);t.G.isNullable(o)||e.emit(r,o,ce)}),o&&r.multicast.forEach(n=>{for(const r of o.values()){const o=r.emitter.getCached(n);t.G.isNullable(o)||e.emit(n,o,ce)}}),s.current=b.Mounted},[]),c.useLayoutEffect(()=>{if(t.G.isNotNullable(a.current)){const n=function(e,t){return Object.keys(t).reduce((n,r)=>e[r]!==t[r]?{...n,[r]:t[r]}:n,{})}(a.current,i);if(t.A.isNotEmpty(Object.keys(n))){const t=ue(u,"Update");t&&e.emit(t,n)}}a.current=i},[i,e])}({unicast:P,broadcast:o,dispatchers:C,scope:s,phase:G,data:r(),handlers:A.current.handlers});const U=c.useMemo(()=>[y,{dispatch(e,t,n){const r=v(e),c=j(e)?e.channel:void 0;if(O(e)&&n?.scope){const e=oe(s,n.scope.Scope);return e?ie(e.emitter,r,t,c):Promise.resolve()}return ie(g(e)?o:P,r,t,c)},get inspect(){return d.current.inspect},get meta(){return{nodes:k.refs.current,features:h.current.features??{}}},node(e,t){k.refs.current[e]=t,k.pending.current.set(e,t)},features:{on(e){h.current.features={...h.current.features,[e]:!0},m(),S(d.current.model)},off(e){h.current.features={...h.current.features,[e]:!1},m(),S(d.current.model)},invert(e){const t=h.current.features?.[e]??!1;h.current.features={...h.current.features,[e]:!t},m(),S(d.current.model)}},stream:(e,t)=>c.createElement(de,{action:v(e),renderer:t})}],[y,P]);return U.useAction=(e,t)=>{!function(e,t,n){const r=c.useRef(n);c.useLayoutEffect(()=>{r.current=n});const o=c.useRef(t);c.useLayoutEffect(()=>{o.current=t});const s=c.useCallback((e,t)=>r.current(e,t),[]),i=c.useCallback(()=>j(o.current)?o.current.channel:void 0,[]),u=v(t),a=e.current.handlers.get(u)??new Set;0===a.size&&e.current.handlers.set(u,a),a.add({getChannel:i,handler:s})}(A,e,t)},U.useResource=e=>{const t=c.useMemo(()=>(e,t)=>{const n=j(e)?e.channel:void 0;return ie(o,v(e),t,n)},[o]);return c.useCallback((...n)=>e.fetch(t,x,...n),[e,t,x])},U},e.utils=be,e.withScope=function(e,t){const n=`Scoped${t.displayName||t.name||"Component"}`;return{[n]:n=>r.jsx(se,{of:e,children:r.jsx(t,{...n})})}[n]},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?factory(exports,require("@mobily/ts-belt"),require("immer"),require("react/jsx-runtime"),require("react")):"function"==typeof define&&define.amd?define(["exports","@mobily/ts-belt","immer","react/jsx-runtime","react"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Chizu={},global.TsBelt,global.Immer,global.jsxRuntime,global.React);
@@ -1,24 +1,2 @@
1
- import { Props } from './types';
2
- export { useError } from './utils';
3
1
  export { Reason, AbortError, TimeoutError, DisallowedError } from './types';
4
- export type { Fault, Catcher } from './types';
5
- /**
6
- * Error boundary component for catching and handling errors from actions.
7
- *
8
- * @template E Custom error types to include in the handler's error union.
9
- * @param props.handler - The error handler function to call when an error occurs.
10
- * @param props.children - The children to render within the error boundary.
11
- * @returns The children wrapped in an error context provider.
12
- *
13
- * @example
14
- * ```tsx
15
- * <Error<ApiError | ValidationError>
16
- * handler={({ error }) => {
17
- * if (error instanceof ApiError) handleApiError(error);
18
- * }}
19
- * >
20
- * <App />
21
- * </Error>
22
- * ```
23
- */
24
- export declare function Error<E extends Error = never>({ handler, children, }: Props<E>): import("react/jsx-runtime").JSX.Element;
2
+ export type { Fault } from './types';
@@ -1,4 +1,3 @@
1
- import { ReactNode } from 'react';
2
1
  import { Task } from '../boundary/components/tasks/types.ts';
3
2
  /**
4
3
  * Reasons why an action error occurred.
@@ -57,6 +56,13 @@ export declare class DisallowedError extends Error {
57
56
  }
58
57
  /**
59
58
  * Details about an error that occurred during action execution.
59
+ *
60
+ * Faults are delivered through the global `Lifecycle.Fault` broadcast.
61
+ * Subscribe with `actions.useAction(Lifecycle.Fault, handler)` near the
62
+ * root of your application for app-level concerns (logging, sign-out on
63
+ * auth failure, abort cascades). For component-local recovery, use a
64
+ * `Lifecycle.Error()` factory instead.
65
+ *
60
66
  * @template E Custom error types to include in the union with Error.
61
67
  */
62
68
  export type Fault<E extends Error = never> = {
@@ -74,35 +80,13 @@ export type Fault<E extends Error = never> = {
74
80
  * (e.g., on 403/500 responses to prevent cascading failures).
75
81
  *
76
82
  * @example
77
- * ```tsx
78
- * <Error handler={({ reason, tasks }) => {
79
- * if (reason === Reason.Errored) {
80
- * // Abort all in-flight tasks to prevent cascading errors
81
- * for (const task of tasks) {
82
- * task.controller.abort();
83
- * }
84
- * // Trigger re-authentication flow
83
+ * ```ts
84
+ * actions.useAction(Lifecycle.Fault, (context, fault) => {
85
+ * if (fault.reason === Reason.Errored) {
86
+ * for (const task of fault.tasks) task.controller.abort();
85
87
  * }
86
- * }}>
87
- * {children}
88
- * </Error>
88
+ * });
89
89
  * ```
90
90
  */
91
91
  tasks: ReadonlySet<Task>;
92
92
  };
93
- /**
94
- * Catcher function called when an action error occurs.
95
- * @template E Custom error types to include in the union with Error.
96
- * @param details Information about the error.
97
- */
98
- export type Catcher<E extends Error = never> = (details: Fault<E>) => void;
99
- /**
100
- * Props for the Error boundary component.
101
- * @template E Custom error types to include in the union with Error.
102
- */
103
- export type Props<E extends Error = never> = {
104
- /** Catcher function called when an action error occurs. */
105
- handler: Catcher<E>;
106
- /** Child components to wrap with error handling. */
107
- children?: ReactNode;
108
- };
@@ -1,4 +1,4 @@
1
- import { Catcher, Reason } from './types.ts';
1
+ import { Reason } from './types.ts';
2
2
  /**
3
3
  * Determines the error reason based on what was thrown.
4
4
  *
@@ -13,13 +13,3 @@ export declare function getReason(error: unknown): Reason;
13
13
  * @returns An Error instance (original if already Error, wrapped otherwise).
14
14
  */
15
15
  export declare function getError(error: unknown): Error;
16
- /**
17
- * React context for handling errors that occur within actions.
18
- */
19
- export declare const ErrorContext: import('react').Context<Catcher | undefined>;
20
- /**
21
- * Hook to access the error handler from the nearest Error provider.
22
- *
23
- * @returns The error handler function, or undefined if not within an Error provider.
24
- */
25
- export declare function useError(): Catcher | undefined;
@@ -1,5 +1,5 @@
1
1
  import { Data } from './types.ts';
2
- import { Model, Props, Actions, UseActions } from '../types/index.ts';
2
+ import { Model, Props, Actions, UseActions, ValidateFeatures, NullableNodes } from '../types/index.ts';
3
3
  export { With } from './utils.ts';
4
4
  /**
5
5
  * A hook for managing state with actions.
@@ -40,4 +40,4 @@ export { With } from './utils.ts';
40
40
  * ```
41
41
  */
42
42
  export declare function useActions<_M extends void = void, A extends Actions | void = void, D extends Props = Props>(getData?: Data<D>): UseActions<void, A, D>;
43
- export declare function useActions<M extends Model, A extends Actions | void = void, D extends Props = Props>(initialModel: M, getData?: Data<D>): UseActions<M, A, D>;
43
+ export declare function useActions<M extends Model, A extends Actions | void = void, D extends Props = Props>(initialModel: NullableNodes<M> & ValidateFeatures<M>, getData?: Data<D>): UseActions<M, A, D>;
@@ -1,6 +1,6 @@
1
1
  import { default as EventEmitter } from 'eventemitter3';
2
2
  import { RefObject } from 'react';
3
- import { Model, HandlerContext, Actions, Props, Tasks, ActionId, Phase, Filter, Nodes } from '../types/index.ts';
3
+ import { Model, HandlerContext, Actions, Props, Tasks, ActionId, Phase, Filter, ExtractNodes } from '../types/index.ts';
4
4
  import { BroadcastEmitter } from '../boundary/components/broadcast/utils.ts';
5
5
  import { ScopeContext } from '../boundary/components/scope/types.ts';
6
6
  /**
@@ -12,12 +12,12 @@ import { ScopeContext } from '../boundary/components/scope/types.ts';
12
12
  export type References<M extends Model | void> = {
13
13
  /** Ref containing captured DOM nodes by name */
14
14
  refs: RefObject<{
15
- [K in keyof Nodes<M>]: Nodes<M>[K] | null;
15
+ [K in keyof ExtractNodes<M>]: ExtractNodes<M>[K] | null;
16
16
  }>;
17
17
  /** Ref containing pending node captures to be processed after render */
18
- pending: RefObject<Map<keyof Nodes<M>, Nodes<M>[keyof Nodes<M>] | null>>;
18
+ pending: RefObject<Map<keyof ExtractNodes<M>, ExtractNodes<M>[keyof ExtractNodes<M>] | null>>;
19
19
  /** Ref containing last emitted node values to detect true changes */
20
- emitted: RefObject<Map<keyof Nodes<M>, Nodes<M>[keyof Nodes<M>] | null>>;
20
+ emitted: RefObject<Map<keyof ExtractNodes<M>, ExtractNodes<M>[keyof ExtractNodes<M>] | null>>;
21
21
  };
22
22
  /**
23
23
  * Function signature for action handlers registered via `useAction`.
@@ -1,5 +1,5 @@
1
1
  import { RefObject } from 'react';
2
- import { Props, Model, Actions, Filter, ActionId, HandlerPayload, ChanneledAction, HandlerContext, Feature } from '../types/index.ts';
2
+ import { Props, Model, Actions, Filter, ActionId, HandlerPayload, ChanneledAction, HandlerContext } from '../types/index.ts';
3
3
  import { default as EventEmitter } from 'eventemitter3';
4
4
  import { Dispatchers, LifecycleConfig, References, Scope } from './types.ts';
5
5
  import { isChanneledAction, getActionSymbol } from '../action/index.ts';
@@ -17,10 +17,13 @@ export declare function withGetters<P extends Props>(a: P, b: RefObject<P>): P;
17
17
  */
18
18
  export declare function isGenerator(result: unknown): result is Generator | AsyncGenerator;
19
19
  /**
20
- * Applies a Feature operation to a boolean feature flag on an Immertation draft.
20
+ * Sentinel passed as the dispatch channel during mount replay. Channeled
21
+ * handlers check for this to skip replay &mdash; they require specific
22
+ * channel context and cannot meaningfully process a replay without it.
23
+ *
21
24
  * @internal
22
25
  */
23
- export declare function applyFeature(draft: Record<string, unknown>, name: string, operation: Feature): void;
26
+ export declare const replay: unique symbol;
24
27
  /**
25
28
  * Invokes all listeners for an event and returns a promise that resolves
26
29
  * when every handler has settled. For {@link BroadcastEmitter} instances the
package/dist/index.d.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  export { Action } from './action/index.ts';
2
- export { Entry } from './cache/index.ts';
3
- export { Distribution, Feature, Lifecycle } from './types/index.ts';
4
- export { Error, Reason, DisallowedError } from './error/index.tsx';
2
+ export { Distribution, Lifecycle } from './types/index.ts';
3
+ export { Reason, AbortError, TimeoutError, DisallowedError, } from './error/index.ts';
5
4
  export { Operation, Op, State } from 'immertation';
6
5
  export { annotate } from './annotate/index.ts';
7
6
  export { Boundary } from './boundary/index.tsx';
8
7
  export { Regulators } from './boundary/components/regulators/index.tsx';
9
8
  export { Scope, withScope } from './boundary/components/scope/index.tsx';
10
9
  export { useActions, With } from './hooks/index.ts';
10
+ export { Resource } from './resource/index.ts';
11
+ export type { ResourceHandle, ResourceDispatch, ResourceSuccess, ResourceFailure, } from './resource/index.ts';
11
12
  export * as utils from './utils/index.ts';
12
13
  export type { Box } from 'immertation';
13
- export type { Fault, Catcher } from './error/index.tsx';
14
- export type { Pk, Task, Tasks, Handlers } from './types/index.ts';
14
+ export type { Fault } from './error/index.ts';
15
+ export type { Pk, Task, Tasks, Handlers, Meta, ScopeCarrier, } from './types/index.ts';
15
16
  export type { Regulator } from './boundary/components/regulators/index.tsx';
@@ -0,0 +1,78 @@
1
+ import { BroadcastPayload, ChanneledAction, Filter, Props } from '../types/index.ts';
2
+ /**
3
+ * Fan-out dispatcher passed to a {@link Resource}'s `onSuccess` and
4
+ * `onError` callbacks. Restricted to broadcast actions (and channeled
5
+ * broadcasts) because resource-level events have no single owning
6
+ * component to scope unicast or multicast to.
7
+ */
8
+ export type ResourceDispatch = {
9
+ <P>(action: BroadcastPayload<P>, payload?: P): Promise<void>;
10
+ <P, C extends Filter>(action: ChanneledAction<P, C>, payload?: P): Promise<void>;
11
+ };
12
+ /**
13
+ * Context passed to a {@link Resource}'s `onSuccess` callback after a
14
+ * successful fetch.
15
+ */
16
+ export type ResourceSuccess<T> = {
17
+ /** The resolved value from the fetcher. */
18
+ readonly response: T;
19
+ /** The reactive `data` proxy of the component that triggered the fetch. */
20
+ readonly data: Props;
21
+ /** Pre-bound dispatcher for the surrounding Boundary's broadcaster. */
22
+ readonly dispatch: ResourceDispatch;
23
+ };
24
+ /**
25
+ * Context passed to a {@link Resource}'s `onError` callback after a
26
+ * failed fetch.
27
+ */
28
+ export type ResourceFailure<E> = {
29
+ /** The thrown error, narrowed to the second generic on `Resource`. */
30
+ readonly error: E;
31
+ /** The reactive `data` proxy of the component that triggered the fetch. */
32
+ readonly data: Props;
33
+ /** Pre-bound dispatcher for the surrounding Boundary's broadcaster. */
34
+ readonly dispatch: ResourceDispatch;
35
+ };
36
+ /**
37
+ * Module-scope handle returned by {@link Resource}. Pass to
38
+ * `actions.useResource(handle)` inside a component to obtain a fetcher
39
+ * thunk bound to the surrounding Boundary's broadcaster and the
40
+ * component's reactive `data`.
41
+ */
42
+ export type ResourceHandle<T, E = Error, Args extends readonly unknown[] = []> = {
43
+ readonly key: string;
44
+ /** @internal */
45
+ readonly fetch: (dispatch: ResourceDispatch, data: Props, ...args: Args) => Promise<T>;
46
+ /** @internal — phantom marker so TS distinguishes by error type */
47
+ readonly _error?: E;
48
+ /** @internal — phantom marker so TS distinguishes by args */
49
+ readonly _args?: Args;
50
+ };
51
+ /**
52
+ * Defines a remote resource &mdash; declare at module scope and consume via
53
+ * `actions.useResource(handle)`. Mirrors the {@link Action} factory pattern:
54
+ * the declaration is a value, not a hook.
55
+ *
56
+ * The fetcher may take arguments. The thunk returned by `actions.useResource`
57
+ * forwards them, and in-flight dedup keys per arg-tuple &ndash; so
58
+ * `fetchPage(null)` and `fetchPage("abc")` run independently, while two
59
+ * concurrent `fetchPage("abc")` calls share one network request.
60
+ *
61
+ * Once a fetch resolves, the next call with the same args fetches anew &ndash;
62
+ * there is no stale cache. Coordination across components happens via the
63
+ * broadcast actions dispatched in `onSuccess` / `onError`.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { Resource } from "chizu";
68
+ *
69
+ * export const feed = Resource<Page<Item>, ApiError, [cursor: string | null]>(
70
+ * "feed",
71
+ * (cursor) =>
72
+ * http.get("feed", { searchParams: { cursor: cursor ?? "" } }).json(),
73
+ * ({ response, dispatch }) =>
74
+ * dispatch(Actions.Broadcast.PageLoaded, response),
75
+ * );
76
+ * ```
77
+ */
78
+ export declare function Resource<T, E = Error, Args extends readonly unknown[] = []>(key: string, fetcher: (...args: Args) => Promise<T>, onSuccess?: (context: ResourceSuccess<T>) => void, onError?: (context: ResourceFailure<E>) => void): ResourceHandle<T, E, Args>;