UNPKG

pullstate

Version:

Simple state stores using immer and React hooks

2 lines (1 loc) 25.3 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","react","immer"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pullstate={},e.React,e.immer)}(this,(function(e,t,s){"use strict";var r=function e(t,s){if(t===s)return!0;if(t&&s&&"object"==typeof t&&"object"==typeof s){if(t.constructor!==s.constructor)return!1;var r,n,o;if(Array.isArray(t)){if((r=t.length)!=s.length)return!1;for(n=r;0!=n--;)if(!e(t[n],s[n]))return!1;return!0}if(t instanceof Map&&s instanceof Map){if(t.size!==s.size)return!1;for(n of t.entries())if(!s.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],s.get(n[0])))return!1;return!0}if(t instanceof Set&&s instanceof Set){if(t.size!==s.size)return!1;for(n of t.entries())if(!s.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(s)){if((r=t.length)!=s.length)return!1;for(n=r;0!=n--;)if(t[n]!==s[n])return!1;return!0}if(t.constructor===RegExp)return t.source===s.source&&t.flags===s.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===s.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===s.toString();if((r=(o=Object.keys(t)).length)!==Object.keys(s).length)return!1;for(n=r;0!=n--;)if(!Object.prototype.hasOwnProperty.call(s,o[n]))return!1;for(n=r;0!=n--;){var a=o[n];if(!e(t[a],s[a]))return!1}return!0}return t!=t&&s!=s};function n(e,s,n){const o=t.useRef({state:void 0,initialized:!1});o.current.initialized||(o.current.state=s?s(e.getRawState()):e.getRawState(),o.current.initialized=!0);const[,a]=t.useState(0);if(t.useEffect((()=>{const t={shouldUpdate:!0};function n(){if(t.shouldUpdate){const n=s?s(e.getRawState()):e.getRawState();r(o.current.state,n)||t.shouldUpdate&&(o.current.state=n,a((e=>e+1)))}}return e._addUpdateListener(n),n(),()=>{t.shouldUpdate=!1,e._removeUpdateListener(n)}}),null!=n?n:[]),void 0!==n){const a=t.useRef(n);r(n,a)||(o.current.state=s(e.getRawState()))}return o.current.state}function o(e,s){const n=t.useRef();if(null==n.current&&(n.current=new c(e)),void 0!==s){const o=t.useRef(s);r(s,o)||(n.current=new c(e))}return n.current}const a={storeOrdinal:0,batching:!1,flushStores:{}};s.enablePatches();class c{constructor(e){if(this.updateListeners=[],this.ssr=!1,this.reactions=[],this.clientSubscriptions=[],this.reactionCreators=[],this.optimizedUpdateListeners={},this.optimizedUpdateListenerPaths={},this.optimizedListenerPropertyMap={},this._optListenerCount=0,this._patchListeners=[],e instanceof Function){const t=e();this.currentState=t,this.initialState=t,this.createInitialState=e}else this.currentState=e,this.initialState=e,this.createInitialState=()=>e;this.internalOrdId=a.storeOrdinal++}_setInternalOptions({ssr:e,reactionCreators:t=[]}){this.ssr=e,this.reactionCreators=t,this.reactions=t.map((e=>e(this)))}_getReactionCreators(){return this.reactionCreators}_instantiateReactions(){this.reactions=this.reactionCreators.map((e=>e(this)))}_getInitialState(){return this.createInitialState()}_updateStateWithoutReaction(e){this.currentState=e}_updateState(e,t=[]){this.currentState=e,this.batchState=void 0;for(const e of this.reactions)t.push(...e());if(!this.ssr){for(const e of this.clientSubscriptions)e();if(t.length>0){const e=new Set;for(const s of t)if(this.optimizedListenerPropertyMap[s])for(const t of this.optimizedListenerPropertyMap[s])e.add(t);for(const t of e.values())this.optimizedUpdateListeners[t]&&this.optimizedUpdateListeners[t]()}this.updateListeners.forEach((e=>e()))}}_addUpdateListener(e){this.updateListeners.push(e)}_removeUpdateListener(e){this.updateListeners=this.updateListeners.filter((t=>t!==e))}_removeUpdateListenerOpt(e){const t=this.optimizedUpdateListenerPaths[e];for(const s of t)this.optimizedListenerPropertyMap[s]=this.optimizedListenerPropertyMap[s].filter((t=>t!==e));delete this.optimizedUpdateListenerPaths[e],delete this.optimizedUpdateListeners[e],this._optListenerCount--}listenToPatches(e){return this._patchListeners.push(e),()=>{this._patchListeners=this._patchListeners.filter((t=>t!==e))}}subscribe(e,t){if(!this.ssr){const s=function(e,t,s){let n=t(e.getRawState());return()=>{const o=e.getRawState(),a=t(o);r(a,n)||(s(a,o,n),n=a)}}(this,e,t);return this.clientSubscriptions.push(s),()=>{this.clientSubscriptions=this.clientSubscriptions.filter((e=>e!==s))}}return()=>{console.warn("Pullstate: Subscriptions made on the server side are not registered - so therefor this call to unsubscribe does nothing.")}}createReaction(e,t,{runNow:n=!1,runNowWithSideEffects:o=!1}={}){const a=function(e,t){return n=>{let o=e(n.getRawState());return(a=!1)=>{const c=n.getRawState(),u=e(c);if(a||!r(u,o))if(n._optListenerCount>0){const[e,r,a]=s.produceWithPatches(c,(e=>t(u,e,c,o)));if(n._updateStateWithoutReaction(e),o=u,r.length>0)return n._patchListeners.forEach((e=>e(r,a))),Object.keys(i(r))}else{if(n._patchListeners.length>0){const[e,r,a]=s.produceWithPatches(c,(e=>t(u,e,c,o)));r.length>0&&n._patchListeners.forEach((e=>e(r,a))),n._updateStateWithoutReaction(e)}else n._updateStateWithoutReaction(s.produce(c,(e=>t(u,e,c,o))));o=u}return[]}}}(e,t);this.reactionCreators.push(a);const c=a(this);return this.reactions.push(c),(n||o)&&(c(!0),o&&!this.ssr&&this._updateState(this.currentState)),()=>{this.reactions=this.reactions.filter((e=>e!==c))}}getRawState(){return void 0!==this.batchState?this.batchState:this.currentState}useState(e,t){return n(this,e,t)}useLocalCopyInitial(e){return o(this.createInitialState,e)}useLocalCopySnapshot(e){return o(this.currentState,e)}flushBatch(e=!1){void 0!==this.batchState?this.batchState!==this.currentState&&this._updateState(this.batchState):e||console.error("Pullstate: Trying to flush batch state which was never created or updated on"),this.batchState=void 0}update(e,t){if(a.batching){void 0===this.batchState&&(this.batchState=this.currentState,a.flushStores[this.internalOrdId]=this);const s="function"==typeof e,[r,n,o]=u(this.batchState,e,s);n.length>0&&(this._patchListeners.length>0||t)&&(t&&t(n,o),this._patchListeners.forEach((e=>e(n,o)))),this.batchState=r}else this.batchState=void 0,l(this,e,t)}replace(e){this._updateState(e)}replaceFromCurrent(e){this._updateState(e(this.currentState))}applyPatches(e){!function(e,t){const r=e.getRawState(),n=s.applyPatches(r,t);n!==r&&e._updateState(n,Object.keys(i(t)))}(this,e)}}function i(e,t={}){for(const s of e){let e;for(const r of s.path)e=e?`${e}~._.~${r}`:r,t[e]=1}return t}function u(e,t,r){return r?s.produceWithPatches(e,(s=>t(s,e))):t.reduce((([e,t,r],n)=>{const o=s.produceWithPatches(e,(t=>n(t,e)));return t.push(...o[1]),r.push(...o[2]),[o[0],t,r]}),[e,[],[]])}function l(e,t,r){const n=e.getRawState(),o="function"==typeof t;if(e._optListenerCount>0){const[s,a,c]=u(n,t,o);a.length>0&&(r&&r(a,c),e._patchListeners.forEach((e=>e(a,c))),e._updateState(s,Object.keys(i(a))))}else{let a;if(e._patchListeners.length>0||r){const[s,c,i]=u(n,t,o);c.length>0&&(r&&r(c,i),e._patchListeners.forEach((e=>e(c,i)))),a=s}else a=s.produce(n,(e=>o?t(e,n):t.reduce(((e,t)=>s.produce(e,(s=>t(s,e)))),n)));a!==n&&e._updateState(a)}}var h,d;e.EAsyncEndTags=void 0,(h=e.EAsyncEndTags||(e.EAsyncEndTags={})).THREW_ERROR="THREW_ERROR",h.RETURNED_ERROR="RETURNED_ERROR",h.UNFINISHED="UNFINISHED",h.DORMANT="DORMANT",e.EPostActionContext=void 0,(d=e.EPostActionContext||(e.EPostActionContext={})).WATCH_HIT_CACHE="WATCH_HIT_CACHE",d.BECKON_HIT_CACHE="BECKON_HIT_CACHE",d.RUN_HIT_CACHE="RUN_HIT_CACHE",d.READ_HIT_CACHE="READ_HIT_CACHE",d.READ_RUN="READ_RUN",d.SHORT_CIRCUIT="SHORT_CIRCUIT",d.DIRECT_RUN="DIRECT_RUN",d.BECKON_RUN="BECKON_RUN",d.CACHE_UPDATE="CACHE_UPDATE";const f={listeners:{},results:{},actions:{},actionOrd:{}};let p,y=0;function C(e){if(null===e)return"(n)";const t=typeof e;if("object"!==t){if("undefined"===t)return"(u)";if("string"===t)return":"+e+";";if("boolean"===t||"number"===t)return"("+e+")"}let s="{";for(const t of Object.keys(e).sort())s+=t+C(e[t]);return s+"}"}function g(e){if(f.listeners.hasOwnProperty(e))for(const t of Object.keys(f.listeners[e]))f.listeners[e][t]()}function E(e,t=!0,s=!0){t&&f.actionOrd.hasOwnProperty(e)&&(f.actionOrd[e]+=1),delete f.results[e],s&&g(e)}function _(e,t){return e.actionOrd.hasOwnProperty(t)?e.actionOrd[t]+=1:e.actionOrd[t]=0,e.actionOrd[t]}function S(e=null,t=[],s=""){return{payload:e,tags:t,message:s,error:!1,errorPayload:null}}class k extends Error{constructor(e,t){super(e),this.tags=t}}try{p=new Proxy({},{get:function(e,t){throw new Error(`Pullstate: Trying to access store (${String(t)}) inside async actions without the correct usage or setup.\nIf this error occurred on the server:\n* If using run(), make use of your created instance for this request: instance.runAsyncAction()\n* If using read(), useWatch(), useBeckon() etc. - make sure you have properly set up your <PullstateProvider/>\n\nIf this error occurred on the client:\n* Make sure you have created your "pullstateCore" object with all your stores, using createPullstateCore(), and are making use of instantiate() before rendering.`)}})}catch{p={}}const A=[!0,!1,{message:"",tags:[e.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];function b(e,t={}){return m((async(t,s,r)=>S(await e(t,s,r))),t)}function R(e){if(null!=e)return"boolean"==typeof e?()=>e:"number"==typeof e?({timeCached:t,result:s})=>!!s.error||Date.now()-t>e:e}function m(n,{forceContext:o=!1,shortCircuitHook:a,cacheBreakHook:c,postActionHook:i,subsetKey:u,actionId:l}={}){const h=null!=l?"_"+l:y++,d="undefined"==typeof window;function b(e,t){return null!=t?`${h}-c-${t}`:void 0!==u?`${h}-${C(u(e))}`:`${h}-${C(e)}`}const m="def_wait_"+b({});let w={},O=0;const T={};function I(e,t,s,r){void 0!==i&&i({args:t,result:e,stores:s,context:r})}function B({args:e,cache:t,cacheBreakEnabled:s,context:r,fromListener:n,key:o,postActionEnabled:a,stores:i,customCacheBreak:u}){const l=null!=u?u:c;if(t.results.hasOwnProperty(o)){const c=w.hasOwnProperty(o)&&w[o]>2;if(!d&&!n&&s&&null!=l&&t.results[o][1]&&l({args:e,result:t.results[o][2],stores:i,timeCached:t.results[o][4]})&&!c){w.hasOwnProperty(o)?w[o]++:w[o]=1;const e=t.results[o];return delete t.results[o],{cacheBroke:!0,response:void 0,previous:e}}return c?console.error(`[${o}] Pullstate detected an infinite loop caused by cacheBreakHook()\nreturning true too often (breaking cache as soon as your action is resolving - hence\ncausing beckoned actions to run the action again) in one of your AsyncActions - Pullstate prevented\nfurther looping. Fix in your cacheBreakHook() is needed.`):w[o]=0,a&&t.results[o][1]&&!n&&I(t.results[o][2],e,i,r),{response:t.results[o],cacheBroke:!1,previous:void 0}}return{cacheBroke:!1,response:void 0,previous:void 0}}function x(t,s,r,o,a,c,i,u){return()=>n(r,o,u).then((e=>(a===s.actionOrd[t]&&(c&&I(e,r,o,i),s.results[t]=[!0,!0,e,!1,Date.now()]),e))).catch((n=>{console.error(n);const u={payload:null,errorPayload:null,error:!0,tags:[e.EAsyncEndTags.THREW_ERROR],message:n.message};return a===s.actionOrd[t]&&(c&&I(u,r,o,i),s.results[t]=[!0,!0,u,!1,Date.now()]),u})).then((e=>(a===s.actionOrd[t]&&(delete s.actions[t],d||g(t)),e)))}function H({key:t,cache:s,initiate:r,ssr:n,args:o,stores:c,fromListener:i=!1,postActionEnabled:u=!0,cacheBreakEnabled:l=!0,holdingResult:h,customContext:f,customCacheBreak:p,holdPrevious:y}){const C=B({key:t,cache:s,args:o,stores:c,context:r?e.EPostActionContext.BECKON_HIT_CACHE:e.EPostActionContext.WATCH_HIT_CACHE,postActionEnabled:u,cacheBreakEnabled:l,fromListener:i,customCacheBreak:p});if(C.response)return C.response;if(!s.actions.hasOwnProperty(t)){const i=_(s,t);if(!r){const r=[!1,!1,{message:"",tags:[e.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];if(d||(s.results[t]=r),y){if(h){const e=[...h];return e[3]=!0,e}if(null!=C.previous){const e=[...C.previous];return e[3]=!0,e}}return r}if(void 0!==a){const r=a({args:o,stores:c});if(!1!==r)return I(r,o,c,e.EPostActionContext.SHORT_CIRCUIT),s.results[t]=[!0,!0,r,!1,Date.now()],s.results[t]}if(!n&&d||(s.actions[t]=x(t,s,o,c,i,u,e.EPostActionContext.BECKON_RUN,f)),d)return A;s.actions[t](),s.results[t]=A}if(y){if(h){const e=[...h];return e[3]=!0,e}if(null!=C.previous){const e=[...C.previous];return e[3]=!0,e}}return A}const U=(s={},{initiate:n=!1,ssr:a=!0,postActionEnabled:c=!1,cacheBreakEnabled:i=!1,holdPrevious:u=!1,dormant:l=!1,key:h,cacheBreak:y}={})=>{const C=t.useRef(),g=t.useRef("."),E=l?".":b(s,h);let _=t.useRef(-1);-1===_.current&&(_.current=O++),l||(T.hasOwnProperty(E)?T[E][_.current]=!0:T[E]={[_.current]:!0});const S=d?t.useContext(v)._asyncCache:f;let k,A;if(d||o){const e=t.useContext(v);k=e.stores,A=e.customContext}else k=P.loaded?P.stores:p;if(!d){const e=()=>{if(T[E][_.current]&&!r(C.current,S.results[E])){const e=H({key:E,cache:S,initiate:n,ssr:a,args:s,stores:k,fromListener:!0,postActionEnabled:c,cacheBreakEnabled:i,holdingResult:void 0,customContext:A,holdPrevious:u});u&&!e[1]&&null!=C.current&&C.current[1]?(C.current=[...C.current],C.current[3]=!0):C.current=e,w((e=>e+1))}};l||(S.listeners.hasOwnProperty(E)||(S.listeners[E]={}),S.listeners[E][_.current]=e,T[E][_.current]=!0),t.useEffect((()=>(l||(S.listeners[E][_.current]=e,T[E][_.current]=!0),()=>{l||(delete S.listeners[E][_.current],T[E][_.current]=!1)})),[E])}const[m,w]=t.useState(0);return l?(C.current=u&&C.current&&C.current[1]?C.current:[!1,!1,{message:"",tags:[e.EAsyncEndTags.DORMANT],error:!0,payload:null},!1,-1],g.current="."):g.current!==E&&(null!==g.current&&T.hasOwnProperty(g.current)&&(delete S.listeners[g.current][_.current],T[g.current][_.current]=!1),g.current=E,C.current=H({key:E,cache:S,initiate:n,ssr:a,args:s,stores:k,fromListener:!1,postActionEnabled:c,cacheBreakEnabled:i,holdingResult:u&&C.current&&C.current[1]?C.current:void 0,customContext:A,customCacheBreak:R(y),holdPrevious:u})),C.current},L=async(t={},s={})=>{const{treatAsUpdate:r=!1,ignoreShortCircuit:n=!1,respectCache:o=!1,key:c,_asyncCache:i=f,_stores:u=(P.loaded?P.stores:p),_customContext:l,cacheBreak:h}=s,d=b(t,c);if(o){const s=B({key:d,cache:i,args:t,stores:u,context:e.EPostActionContext.RUN_HIT_CACHE,postActionEnabled:!0,cacheBreakEnabled:!0,fromListener:!1,customCacheBreak:R(h)});if(s.response&&s.response[0]){if(!s.response[1]){const e=O++;return i.listeners.hasOwnProperty(d)||(i.listeners[d]={}),new Promise((t=>{i.listeners[d][e]=()=>{const[,s,r]=i.results[d];s&&(delete i.listeners[d][e],t(r))}}))}return s.response[2]}}if(!n&&void 0!==a){const s=a({args:t,stores:u});if(!1!==s)return i.results[d]=[!0,!0,s,!1,Date.now()],I(s,t,u,e.EPostActionContext.SHORT_CIRCUIT),g(d),s}const[,y,C,E,S]=i.results[d]||[!1,!1,{error:!0,message:"",payload:null,tags:[e.EAsyncEndTags.UNFINISHED]},!1,-1];i.results[d]=y&&r?[!0,!0,C,!0,S]:[!0,!1,{error:!0,message:"",payload:null,tags:[e.EAsyncEndTags.UNFINISHED]},!1,-1];let k=_(i,d);return i.actions[d]=x(d,i,t,u,k,!0,e.EPostActionContext.DIRECT_RUN,l),g(d),i.actions[d]()},N=(e={},{key:t,notify:s=!0}={})=>{E(b(e,t),!0,s)},D=(e,s,r)=>{const{notify:n=!0,key:o}=r||{},a=b(e,o);(d?t.useContext(v)._asyncCache:f).results[a]=[!0,!0,s,!1,Date.now()],n&&g(a)},j=(e,t,s)=>D(e,S(t),s),W=(r,n,o)=>{const{notify:a=!0,resetTimeCached:c=!0,runPostActionHook:i=!1,key:u}=o||{},l=b(r,u),h=d?t.useContext(v)._asyncCache:f;if(h.results.hasOwnProperty(l)&&!h.results[l][2].error){const t=h.results[l][2].payload,o={payload:s(t,(e=>n(e,t))),error:!1,message:h.results[l][2].message,tags:h.results[l][2].tags};i&&I(o,r,P.loaded?P.stores:p,e.EPostActionContext.CACHE_UPDATE),h.results[l]=[!0,!0,o,h.results[l][3],c?Date.now():h.results[l][4]],a&&g(l)}},z=(s={},r)=>{var n;const{checkCacheBreak:o=!1,key:a,cacheBreak:i}=r||{},u=b(s,a);let l=!1;const h=f;if(h.results.hasOwnProperty(u)){const e=null!==(n=R(i))&&void 0!==n?n:c;if(o&&void 0!==e){const r=d?t.useContext(v).stores:P.loaded?P.stores:p;e({args:s,result:h.results[u][2],stores:r,timeCached:h.results[u][4]})&&(l=!0)}const[r,a,f,y,C]=h.results[u];return{started:r,finished:a,result:f,existed:!0,cacheBreakable:l,updating:y,timeCached:C}}return{started:!1,finished:!1,result:{message:"",tags:[e.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},updating:!1,existed:!1,cacheBreakable:l,timeCached:-1}};let F;const $=(e={},{initiate:s=!0,ssr:r=!0,postActionEnabled:n,cacheBreakEnabled:o,holdPrevious:a=!1,dormant:c=!1,key:i,onSuccess:u,cacheBreak:l}={})=>{null==n&&(n=s),null==o&&(o=s);const h=U(e,{initiate:s,ssr:r,postActionEnabled:n,cacheBreakEnabled:o,holdPrevious:a,dormant:c,key:i,cacheBreak:l}),[d,f,p,y]=h,C=f&&!p.error,g=f&&p.error;u&&t.useEffect((()=>{C&&!c&&u(p.payload,e)}),[C]);return{isStarted:d,isFinished:f,isUpdating:y,isSuccess:C,isFailure:g,isLoading:d&&(!f||y),endTags:p.tags,error:p.error,payload:p.payload,errorPayload:p.errorPayload,renderPayload:e=>p.error?t.Fragment:e(p.payload),message:p.message,raw:h,execute:t=>L(e,t),clearCached:()=>N(e),setCached:(t,s)=>{D(e,t,s)},setCachedPayload:(t,s)=>{j(e,t,s)},updateCached:(t,s)=>{W(e,t,s)}}};return{use:$,useDefer:(e={})=>{const[s,n]=t.useState((()=>({key:e.key?e.key:m,args:{}}))),o=$({},{...e,key:s.key,initiate:!1}),a=(t={},s={})=>{var r,n;const o=null!==(r=e.key)&&void 0!==r?r:b(t),{checkCacheBreak:a=!0,successOnly:c=!1}=s,i=z(t,{key:o,cacheBreak:null!==(n=s.cacheBreak)&&void 0!==n?n:e.cacheBreak,checkCacheBreak:a});return!(!i.existed||a&&i.cacheBreakable)&&(!c||!i.result.error)},c=()=>{n({key:m,args:{}})},i=(t={},r)=>{var o;const a=null!==(o=e.key)&&void 0!==o?o:b(t);return a!==s.key&&n({key:a,args:t}),L(t,{...r,key:a,cacheBreak:e.cacheBreak}).then((t=>(e.clearOnSuccess&&N({},{key:a}),t)))};return{...o,clearCached:()=>{N({},{key:s.key})},unwatchExecuted:c,setCached:(e,t={})=>{t.key=s.key,D({},e,t)},setCachedPayload:(e,t={})=>{t.key=s.key,j({},e,t)},updateCached:(e,t={})=>{t.key=s.key,W({},e,t)},useDebouncedExecution:(e,s,n={})=>{if(!d){const o=t.useRef({update:!1}),u=t.useRef(void 0),l=t.useRef(-1),h=t.useRef(void 0);t.useEffect((()=>(o.current.update=!0,()=>{o.current.update=!1})),[]);null!=n.equality?"function"==typeof n.equality?(void 0===u.current||n.equality(u.current,e))&&(u.current=e,l.current+=1):u.current!==n.equality&&(u.current=n.equality,l.current+=1):r(u.current,e)||(u.current=e,l.current+=1),t.useEffect((()=>{var t,r,u;clearTimeout(h.current);const l=()=>{var t;o.current.update&&i(e,null!==(t=n.executeOptions)&&void 0!==t?t:{respectCache:!0})};null===(r=null===(t=n.validInput)||void 0===t?void 0:t.call(n,e))||void 0===r||r?a(e)?l():h.current=setTimeout(l,s):null!==(u=n.watchLastValid)&&void 0!==u&&u||c()}),[l.current])}},hasCached:a,execute:i,args:s.args,key:s.key}},read:(s={},{cacheBreakEnabled:r=!0,postActionEnabled:n=!0,key:c}={})=>{const i=b(s,c),u=d?t.useContext(v)._asyncCache:f;let l,h;if(d||o){const e=t.useContext(v);l=e.stores,h=e.customContext}else l=P.loaded?P.stores:p;const y=B({key:i,cache:u,args:s,stores:l,context:e.EPostActionContext.READ_HIT_CACHE,postActionEnabled:n,cacheBreakEnabled:r,fromListener:!1});if(y.response){if(y.response[2].error)throw new k(y.response[2].message,y.response[2].tags);return y.response[2].payload}if(!u.actions.hasOwnProperty(i)){if(void 0!==a){const t=a({args:s,stores:l});if(!1!==t){if(I(t,s,l,e.EPostActionContext.SHORT_CIRCUIT),u.results[i]=[!0,!0,t,!1,Date.now()],t.error)throw new k(t.message,t.tags);return t.payload}}const t=_(u,i);if(u.actions[i]=x(i,u,s,l,t,n,e.EPostActionContext.READ_RUN,h),d)throw new Error("Pullstate Async Action: action.read() : Resolve all async state for Suspense actions before Server-side render ( make use of instance.runAsyncAction() )");throw u.actions[i]()}if(d)throw new Error("Pullstate Async Action: action.read() : Resolve all async state for Suspense actions before Server-side render ( make use of instance.runAsyncAction() )");const C=O++;throw new Promise((e=>{u.listeners[i][C]=()=>{delete u.listeners[i][C],e()}}))},useBeckon:(e={},{ssr:t=!0,postActionEnabled:s=!0,cacheBreakEnabled:r=!0,holdPrevious:n=!1,dormant:o=!1,key:a}={})=>{const c=U(e,{initiate:!0,ssr:t,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o,key:a});return[c[1],c[2],c[3]]},useWatch:U,run:L,delayedRun:(e={},{clearOldRun:t=!0,delay:s,immediateIfCached:r=!0,...n})=>{if(t&&clearTimeout(F),r){const{finished:t,cacheBreakable:s}=z(e,{checkCacheBreak:!0});if(t&&!s)return L(e,n),()=>{}}let o={cancelled:!1};return F=setTimeout((()=>{o.cancelled||L(e,n)}),s),()=>{o.cancelled=!0}},clearCache:N,clearAllCache:({notify:e=!0}={})=>{for(const t of Object.keys(f.actionOrd))t.startsWith(h+"-")&&E(t,!0,e)},clearAllUnwatchedCache:({notify:e=!0}={})=>{for(const t of Object.keys(T))Object.values(T[t]).some((e=>e))||(delete T[t],E(t,!1,e))},getCached:z,setCached:D,setCachedPayload:j,updateCached:W}}const v=t.createContext(null);let w=null;const P={internalClientStores:!0,loaded:!1,stores:{}};class O{constructor(e,t={}){this.options={},null!==w&&console.error("Pullstate: createPullstate() - Should not be creating the core Pullstate class more than once! In order to re-use pull state, you need to call instantiate() on your already created object."),w=this,P.stores=e,P.loaded=!0,this.options=t}instantiate({hydrateSnapshot:e,ssr:t=!1,customContext:s}={}){if(!t){const t=new T(P.stores,!1,s);return null!=e&&t.hydrateFromSnapshot(e),t.instantiateReactions(),t}const r={};for(const s of Object.keys(P.stores))null==e?r[s]=new c(P.stores[s]._getInitialState()):e.hasOwnProperty(s)?r[s]=new c(e.allState[s]):(r[s]=new c(P.stores[s]._getInitialState()),console.warn(`Pullstate (instantiate): store [${s}] didn't hydrate any state (data was non-existent on hydration object)`)),r[s]._setInternalOptions({ssr:t,reactionCreators:P.stores[s]._getReactionCreators()});return new T(r,!0,s)}useStores(){return I()}useInstance(){return B()}createAsyncActionDirect(e,t={}){return b(e,t)}createAsyncAction(e,t={}){var s;return(null===(s=this.options.asyncActions)||void 0===s?void 0:s.defaultCachingSeconds)&&!t.cacheBreakHook&&(t.cacheBreakHook=e=>e.timeCached<Date.now()-1e3*this.options.asyncActions.defaultCachingSeconds),m(e,t)}}class T{constructor(e,t,s){this._ssr=!1,this._stores={},this._asyncCache={listeners:{},results:{},actions:{},actionOrd:{}},this._stores=e,this._ssr=t,this._customContext=s}getAllUnresolvedAsyncActions(){return Object.keys(this._asyncCache.actions).map((e=>this._asyncCache.actions[e]()))}instantiateReactions(){for(const e of Object.keys(this._stores))this._stores[e]._instantiateReactions()}getPullstateSnapshot(){const e={};for(const t of Object.keys(this._stores))e[t]=this._stores[t].getRawState();return{allState:e,asyncResults:this._asyncCache.results,asyncActionOrd:this._asyncCache.actionOrd}}async resolveAsyncState(){const e=this.getAllUnresolvedAsyncActions();await Promise.all(e)}hasAsyncStateToResolve(){return Object.keys(this._asyncCache.actions).length>0}get stores(){return this._stores}get customContext(){return this._customContext}async runAsyncAction(e,t={},s={}){return this._ssr&&(s._asyncCache=this._asyncCache,s._stores=this._stores,s._customContext=this._customContext),await e.run(t,s)}hydrateFromSnapshot(e){for(const t of Object.keys(this._stores))e.allState.hasOwnProperty(t)?this._stores[t]._updateStateWithoutReaction(e.allState[t]):console.warn(t+" didn't hydrate any state (data was non-existent on hydration object)");f.results=e.asyncResults||{},f.actionOrd=e.asyncActionOrd||{}}}function I(){return t.useContext(v).stores}function B(){return t.useContext(v)}var x;e.EAsyncActionInjectType=void 0,(x=e.EAsyncActionInjectType||(e.EAsyncActionInjectType={})).WATCH="watch",x.BECKON="beckon";const H={};e.InjectAsyncAction=function(t){if(t.type===e.EAsyncActionInjectType.BECKON){const e=t.action.useBeckon(t.args,t.options);return t.children(e)}const s=t.action.useWatch(t.args,t.options);return t.children(s)},e.InjectStoreState=function({store:e,on:t=(e=>e),children:s}){return s(n(e,t))},e.PullstateContext=v,e.PullstateProvider=({instance:e,children:s})=>t.createElement(v.Provider,{value:e},s),e.Store=c,e.batch=function(e){if(a.batching)throw new Error("Pullstate: Can't enact two batch() update functions at the same time-\nmake sure you are not running a batch() inside of a batch() by mistake.");a.batching=!0;try{e()}finally{H.uiBatchFunction?H.uiBatchFunction((()=>{Object.values(a.flushStores).forEach((e=>e.flushBatch(!0)))})):Object.values(a.flushStores).forEach((e=>e.flushBatch(!0))),a.flushStores={},a.batching=!1}},e.createAsyncAction=m,e.createAsyncActionDirect=b,e.createPullstateCore=function(e={},t={}){return new O(e,t)},e.errorResult=function(t=[],s="",r){return{payload:null,tags:[e.EAsyncEndTags.RETURNED_ERROR,...t],message:s,error:!0,errorPayload:r}},e.registerInDevtools=function(e,{namespace:t=""}={}){const s="undefined"!=typeof window?null===window||void 0===window?void 0:window.__REDUX_DEVTOOLS_EXTENSION__:void 0;if(s)for(const r of Object.keys(e)){const n=e[r],o=s.connect({name:`${t}${r}`});o.init(n.getRawState());let a=!1;n.subscribe((e=>e),(e=>{a?a=!1:o.send("Change",e)})),o.subscribe((e=>{if("DISPATCH"===e.type&&e.state){a=!0;const t=JSON.parse(e.state);n.replace(t)}}))}},e.setupBatch=function({uiBatchFunction:e}){H.uiBatchFunction=e},e.successResult=S,e.update=l,e.useInstance=B,e.useLocalStore=o,e.useStoreState=n,e.useStores=I}));