Comparing version 1.20.2 to 1.20.3
@@ -24,2 +24,3 @@ import isEqual from'fast-deep-equal/es6';import React,{useRef,useState,useEffect,useContext}from'react';import produce$1,{enablePatches,produceWithPatches,produce,applyPatches}from'immer';function useStoreState(store, getSubState, deps) { | ||
store._addUpdateListener(update); | ||
update(); | ||
return () => { | ||
@@ -26,0 +27,0 @@ effectState.shouldUpdate = false; |
@@ -24,2 +24,3 @@ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var isEqual=require('fast-deep-equal/es6'),React=require('react'),produce=require('immer');function _interopDefaultLegacy(e){return e&&typeof e==='object'&&'default'in e?e:{'default':e}}var isEqual__default=/*#__PURE__*/_interopDefaultLegacy(isEqual);var React__default=/*#__PURE__*/_interopDefaultLegacy(React);var produce__default=/*#__PURE__*/_interopDefaultLegacy(produce);function useStoreState(store, getSubState, deps) { | ||
store._addUpdateListener(update); | ||
update(); | ||
return () => { | ||
@@ -26,0 +27,0 @@ effectState.shouldUpdate = false; |
@@ -100,2 +100,3 @@ (function (global, factory) { | ||
store._addUpdateListener(update); | ||
update(); | ||
return () => { | ||
@@ -102,0 +103,0 @@ effectState.shouldUpdate = false; |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","react","immer"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).pullstate={},t.React,t.immer)}(this,(function(t,e,s){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=r(e),o=r(s),a=function t(e,s){if(e===s)return!0;if(e&&s&&"object"==typeof e&&"object"==typeof s){if(e.constructor!==s.constructor)return!1;var r,n,o;if(Array.isArray(e)){if((r=e.length)!=s.length)return!1;for(n=r;0!=n--;)if(!t(e[n],s[n]))return!1;return!0}if(e instanceof Map&&s instanceof Map){if(e.size!==s.size)return!1;for(n of e.entries())if(!s.has(n[0]))return!1;for(n of e.entries())if(!t(n[1],s.get(n[0])))return!1;return!0}if(e instanceof Set&&s instanceof Set){if(e.size!==s.size)return!1;for(n of e.entries())if(!s.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(s)){if((r=e.length)!=s.length)return!1;for(n=r;0!=n--;)if(e[n]!==s[n])return!1;return!0}if(e.constructor===RegExp)return e.source===s.source&&e.flags===s.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===s.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===s.toString();if((r=(o=Object.keys(e)).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(!t(e[a],s[a]))return!1}return!0}return e!=e&&s!=s};function i(t,s,r){const n=e.useRef({state:void 0,initialized:!1});n.current.initialized||(n.current.state=s?s(t.getRawState()):t.getRawState(),n.current.initialized=!0);const[,o]=e.useState(0);if(e.useEffect((()=>{const e={shouldUpdate:!0};function r(){if(e.shouldUpdate){const r=s?s(t.getRawState()):t.getRawState();a(n.current.state,r)||e.shouldUpdate&&(n.current.state=r,o((t=>t+1)))}}return t._addUpdateListener(r),()=>{e.shouldUpdate=!1,t._removeUpdateListener(r)}}),null!=r?r:[]),void 0!==r){const o=e.useRef(r);a(r,o)||(n.current.state=s(t.getRawState()))}return n.current.state}let c=0;function u(t,e){return e.reduce(((e=t,s)=>e[s]),void 0)}function l(t,e){const s=t.getRawState(),r=[];for(const t of e)r.push(u(s,t));return r}function d(t,s){const[r,n]=e.useState((()=>l(t,s))),o=e.useRef({shouldUpdate:!0,onStoreUpdate:null,currentSubState:null,ordKey:"_"+c++});return o.current.currentSubState=r,null===o.current.onStoreUpdate&&(o.current.onStoreUpdate=function(){o.current.shouldUpdate&&n(l(t,s))},t._addUpdateListenerOpt(o.current.onStoreUpdate,o.current.ordKey,s)),e.useEffect((()=>()=>{o.current.shouldUpdate=!1,t._removeUpdateListenerOpt(o.current.ordKey)}),[]),r}function h(t,s){const r=e.useRef();if(null==r.current&&(r.current=new p("function"==typeof t?t():t)),void 0!==s){const n=e.useRef(s);a(s,n)||(r.current=new p("function"==typeof t?t():t))}return r.current}s.enablePatches();const f="~._.~";class p{constructor(t){this.updateListeners=[],this.ssr=!1,this.reactions=[],this.clientSubscriptions=[],this.reactionCreators=[],this.optimizedUpdateListeners={},this.optimizedUpdateListenerPaths={},this.optimizedListenerPropertyMap={},this._optListenerCount=0,this._patchListeners=[],this.currentState=t,this.initialState=t}_setInternalOptions({ssr:t,reactionCreators:e=[]}){this.ssr=t,this.reactionCreators=e,this.reactions=e.map((t=>t(this)))}_getReactionCreators(){return this.reactionCreators}_instantiateReactions(){this.reactions=this.reactionCreators.map((t=>t(this)))}_getInitialState(){return this.initialState}_updateStateWithoutReaction(t){this.currentState=t}_updateState(t,e=[]){this.currentState=t,this.batchState=void 0;for(const t of this.reactions)e.push(...t());if(!this.ssr){for(const t of this.clientSubscriptions)t();if(e.length>0){const t=new Set;for(const s of e)if(this.optimizedListenerPropertyMap[s])for(const e of this.optimizedListenerPropertyMap[s])t.add(e);for(const e of t.values())this.optimizedUpdateListeners[e]&&this.optimizedUpdateListeners[e]()}this.updateListeners.forEach((t=>t()))}}_addUpdateListener(t){this.updateListeners.push(t)}_addUpdateListenerOpt(t,e,s){this.optimizedUpdateListeners[e]=t;const r=s.map((t=>t.join(f)));this.optimizedUpdateListenerPaths[e]=r;for(const t of r)null==this.optimizedListenerPropertyMap[t]?this.optimizedListenerPropertyMap[t]=[e]:this.optimizedListenerPropertyMap[t].push(e);this._optListenerCount++}_removeUpdateListener(t){this.updateListeners=this.updateListeners.filter((e=>e!==t))}_removeUpdateListenerOpt(t){const e=this.optimizedUpdateListenerPaths[t];for(const s of e)this.optimizedListenerPropertyMap[s]=this.optimizedListenerPropertyMap[s].filter((e=>e!==t));delete this.optimizedUpdateListenerPaths[t],delete this.optimizedUpdateListeners[t],this._optListenerCount--}listenToPatches(t){return this._patchListeners.push(t),()=>{this._patchListeners=this._patchListeners.filter((e=>e!==t))}}subscribe(t,e){if(!this.ssr){const s=function(t,e,s){let r=e(t.getRawState());return()=>{const n=t.getRawState(),o=e(n);a(o,r)||(s(o,n,r),r=o)}}(this,t,e);return this.clientSubscriptions.push(s),()=>{this.clientSubscriptions=this.clientSubscriptions.filter((t=>t!==s))}}return()=>{console.warn("Pullstate: Subscriptions made on the server side are not registered - so therefor this call to unsubscribe does nothing.")}}createReaction(t,e,{runNow:r=!1,runNowWithSideEffects:n=!1}={}){const o=function(t,e){return r=>{let n=t(r.getRawState());return(o=!1)=>{const i=r.getRawState(),c=t(i);if(o||!a(c,n))if(r._optListenerCount>0){const[t,o,a]=s.produceWithPatches(i,(t=>e(c,t,i,n)));if(r._updateStateWithoutReaction(t),n=c,o.length>0)return r._patchListeners.forEach((t=>t(o,a))),Object.keys(y(o))}else{if(r._patchListeners.length>0){const[t,o,a]=s.produceWithPatches(i,(t=>e(c,t,i,n)));o.length>0&&r._patchListeners.forEach((t=>t(o,a))),r._updateStateWithoutReaction(t)}else r._updateStateWithoutReaction(s.produce(i,(t=>e(c,t,i,n))));n=c}return[]}}}(t,e);this.reactionCreators.push(o);const i=o(this);return this.reactions.push(i),(r||n)&&(i(!0),n&&!this.ssr&&this._updateState(this.currentState)),()=>{this.reactions=this.reactions.filter((t=>t!==i))}}getRawState(){return void 0!==this.batchState?this.batchState:this.currentState}useState(t,e){return i(this,t,e)}useLocalCopyInitial(t){return h((()=>this.initialState),t)}useLocalCopySnapshot(t){return h(this.currentState,t)}update(t,e){_(this,t,e)}replace(t){this._updateState(t)}applyPatches(t){!function(t,e){const r=t.getRawState(),n=s.applyPatches(r,e);n!==r&&t._updateState(n,Object.keys(y(e)))}(this,t)}}function y(t,e={}){for(const s of t){let t;for(const r of s.path)t=t?`${t}~._.~${r}`:r,e[t]=1}return e}function C(t,e,r){return r?s.produceWithPatches(t,(s=>e(s,t))):e.reduce((([t,e,r],n)=>{const o=s.produceWithPatches(t,(e=>n(e,t)));return e.push(...o[1]),r.push(...o[2]),[o[0],e,r]}),[t,[],[]])}function _(t,e,r){const n=t.getRawState(),o="function"==typeof e;if(t._optListenerCount>0){const[s,a,i]=C(n,e,o);a.length>0&&(r&&r(a,i),t._patchListeners.forEach((t=>t(a,i))),t._updateState(s,Object.keys(y(a))))}else{let a;if(t._patchListeners.length>0||r){const[s,i,c]=C(n,e,o);i.length>0&&(r&&r(i,c),t._patchListeners.forEach((t=>t(i,c)))),a=s}else a=s.produce(n,(t=>o?e(t,n):e.reduce(((t,e)=>s.produce(t,(s=>e(s,t)))),n)));a!==n&&t._updateState(a)}}var g,E;(g=t.EAsyncEndTags||(t.EAsyncEndTags={})).THREW_ERROR="THREW_ERROR",g.RETURNED_ERROR="RETURNED_ERROR",g.UNFINISHED="UNFINISHED",g.DORMANT="DORMANT",(E=t.EPostActionContext||(t.EPostActionContext={})).WATCH_HIT_CACHE="WATCH_HIT_CACHE",E.BECKON_HIT_CACHE="BECKON_HIT_CACHE",E.RUN_HIT_CACHE="RUN_HIT_CACHE",E.READ_HIT_CACHE="READ_HIT_CACHE",E.READ_RUN="READ_RUN",E.SHORT_CIRCUIT="SHORT_CIRCUIT",E.DIRECT_RUN="DIRECT_RUN",E.BECKON_RUN="BECKON_RUN",E.CACHE_UPDATE="CACHE_UPDATE";const S={listeners:{},results:{},actions:{},actionOrd:{}};let A,R=0;function P(t){if(null===t)return"(n)";const e=typeof t;if("object"!==e){if("undefined"===e)return"(u)";if("string"===e)return":"+t+";";if("boolean"===e||"number"===e)return"("+t+")"}let s="{";for(const e of Object.keys(t).sort())s+=e+P(t[e]);return s+"}"}function O(t){if(S.listeners.hasOwnProperty(t))for(const e of Object.keys(S.listeners[t]))S.listeners[t][e]()}function w(t,e=!0){e&&S.actionOrd.hasOwnProperty(t)&&(S.actionOrd[t]+=1),delete S.results[t],O(t)}function m(t,e){return t.actionOrd.hasOwnProperty(e)?t.actionOrd[e]+=1:t.actionOrd[e]=0,t.actionOrd[e]}function b(t=null,e=[],s=""){return{payload:t,tags:e,message:s,error:!1,errorPayload:null}}class k extends Error{constructor(t,e){super(t),this.tags=e}}try{A=new Proxy({},{get:function(t,e){throw new Error(`Pullstate: Trying to access store (${String(e)}) 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{A={}}const T=[!0,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];function U(t,e={}){return v((async e=>b(await t(e))),e)}function v(s,{forceContext:r=!1,shortCircuitHook:i,cacheBreakHook:c,postActionHook:u,subsetKey:l}={}){const d=R++,h="undefined"==typeof window;function f(t,e){return null!=e?`${d}-c-${e}`:void 0!==l?`${d}-${P(l(t))}`:`${d}-${P(t)}`}let p={},y=0;const C={};function _(t,e,s,r){void 0!==u&&u({args:e,result:t,stores:s,context:r})}function g(t,e,s,r,n,o,a,i){if(e.results.hasOwnProperty(t)){const u=p.hasOwnProperty(t)&&p[t]>2;if(!(e.results[t][1]&&a&&void 0!==c&&c({args:s,result:e.results[t][2],stores:r,timeCached:e.results[t][4]}))||u)return u?console.error(`[${t}] 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.`):p[t]=0,o&&e.results[t][1]&&!i&&_(e.results[t][2],s,r,n),e.results[t];p.hasOwnProperty(t)?p[t]++:p[t]=1,delete e.results[t]}}function E(e,r,n,o,a,i,c){return()=>s(n,o).then((t=>(a===r.actionOrd[e]&&(i&&_(t,n,o,c),r.results[e]=[!0,!0,t,!1,Date.now()]),t))).catch((s=>{console.error(s);const u={payload:null,errorPayload:null,error:!0,tags:[t.EAsyncEndTags.THREW_ERROR],message:s.message};return a===r.actionOrd[e]&&(i&&_(u,n,o,c),r.results[e]=[!0,!0,u,!1,Date.now()]),u})).then((t=>(a===r.actionOrd[e]&&(delete r.actions[e],h||O(e)),t)))}function U(e,s,r,n,o,a,c=!1,u=!0,l=!0,d){const f=g(e,s,o,a,r?t.EPostActionContext.BECKON_HIT_CACHE:t.EPostActionContext.WATCH_HIT_CACHE,u,l,c);if(f)return f;if(!s.actions.hasOwnProperty(e)){const c=m(s,e);if(!r){const r=[!1,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];if(h||(s.results[e]=r),d){const t=[...d];return t[3]=!0,t}return r}if(void 0!==i){const r=i({args:o,stores:a});if(!1!==r)return _(r,o,a,t.EPostActionContext.SHORT_CIRCUIT),s.results[e]=[!0,!0,r,!1,Date.now()],s.results[e]}if(!n&&h||(s.actions[e]=E(e,s,o,a,c,u,t.EPostActionContext.BECKON_RUN)),h)return T;s.actions[e](),s.results[e]=T}if(d){const t=[...d];return t[3]=!0,t}return T}const v=(s={},{initiate:n=!1,ssr:o=!0,postActionEnabled:i=!1,cacheBreakEnabled:c=!1,holdPrevious:u=!1,dormant:l=!1,key:d}={})=>{const p=e.useRef(),_=e.useRef("."),g=l?".":f(s,d);let E=e.useRef(-1);-1===E.current&&(E.current=y++),l||(C.hasOwnProperty(g)?C[g][E.current]=!0:C[g]={[E.current]:!0});const R=h?e.useContext(I)._asyncCache:S,P=h||r?e.useContext(I).stores:L.loaded?L.stores:A;if(!h){const t=()=>{C[g][E.current]&&!a(p.current,R.results[g])&&(p.current=U(g,R,n,o,s,P,!0,i,c),w((t=>t+1)))};l||(R.listeners.hasOwnProperty(g)||(R.listeners[g]={}),R.listeners[g][E.current]=t,C[g][E.current]=!0),e.useEffect((()=>(l||(R.listeners[g][E.current]=t,C[g][E.current]=!0),()=>{l||(delete R.listeners[g][E.current],C[g][E.current]=!1)})),[g])}const[O,w]=e.useState(0);return l?(p.current=u&&p.current&&p.current[1]?p.current:[!1,!1,{message:"",tags:[t.EAsyncEndTags.DORMANT],error:!0,payload:null},!1,-1],_.current="."):_.current!==g&&(null!==_.current&&C.hasOwnProperty(_.current)&&(delete R.listeners[_.current][E.current],C[_.current][E.current]=!1),_.current=g,p.current=U(g,R,n,o,s,P,!1,i,c,u&&p.current&&p.current[1]?p.current:void 0)),p.current},H=async(e={},{treatAsUpdate:s=!1,ignoreShortCircuit:r=!1,respectCache:n=!1,key:o,_asyncCache:a=S,_stores:c=(L.loaded?L.stores:A)}={})=>{const u=f(e,o);if(n){const s=g(u,a,e,c,t.EPostActionContext.RUN_HIT_CACHE,!0,!0,!1);if(s){if(!s[1]){const t=y++;return a.listeners.hasOwnProperty(u)||(a.listeners[u]={}),new Promise((e=>{a.listeners[u][t]=()=>{const[,s,r]=a.results[u];s&&(delete a.listeners[u][t],e(r))}}))}return s[2]}}if(!r&&void 0!==i){const s=i({args:e,stores:c});if(!1!==s)return a.results[u]=[!0,!0,s,!1,Date.now()],_(s,e,c,t.EPostActionContext.SHORT_CIRCUIT),O(u),s}const[,l,d,h,p]=a.results[u]||[!1,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];a.results[u]=l&&s?[!0,!0,d,!0,p]:[!0,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];let C=m(a,u);return a.actions[u]=E(u,a,e,c,C,!0,t.EPostActionContext.DIRECT_RUN),O(u),a.actions[u]()},N=(t={},e)=>{w(f(t,e))},x=(t,s,r)=>{const{notify:n=!0,key:o}=r||{},a=f(t,o);(h?e.useContext(I)._asyncCache:S).results[a]=[!0,!0,s,!1,Date.now()],n&&O(a)},D=(t,e,s)=>x(t,b(e),s),j=(s,r,n)=>{const{notify:a=!0,resetTimeCached:i=!0,runPostActionHook:c=!1,key:u}=n||{},l=f(s,u),d=h?e.useContext(I)._asyncCache:S;if(d.results.hasOwnProperty(l)&&!d.results[l][2].error){const e=d.results[l][2].payload,n={payload:o.default(e,(t=>r(t,e))),error:!1,message:d.results[l][2].message,tags:d.results[l][2].tags};c&&_(n,s,L.loaded?L.stores:A,t.EPostActionContext.CACHE_UPDATE),d.results[l]=[!0,!0,n,d.results[l][3],i?Date.now():d.results[l][4]],a&&O(l)}},B=(s={},r)=>{const{checkCacheBreak:n=!1,key:o}=r||{},a=f(s,o);let i=!1;const u=h?e.useContext(I)._asyncCache:S;if(u.results.hasOwnProperty(a)){if(n&&void 0!==c){const t=h?e.useContext(I).stores:L.loaded?L.stores:A;c({args:s,result:u.results[a][2],stores:t,timeCached:u.results[a][4]})&&(i=!0)}const[t,r,o,l,d]=u.results[a];return{started:t,finished:r,result:o,existed:!0,cacheBreakable:i,updating:l,timeCached:d}}return{started:!1,finished:!1,result:{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},updating:!1,existed:!1,cacheBreakable:i,timeCached:-1}};let z;const W=(t={},{initiate:s=!0,ssr:r=!0,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i=!1,dormant:c=!1,key:u,onSuccess:l}={})=>{null==o&&(o=s),null==a&&(a=s);const d=v(t,{initiate:s,ssr:r,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i,dormant:c,key:u}),[h,f,p,y]=d,C=f&&!p.error,_=f&&p.error;l&&e.useEffect((()=>{C&&!c&&l(p.payload,t)}),[C]);return{isStarted:h,isFinished:f,isUpdating:y,isSuccess:C,isFailure:_,isLoading:h&&(!f||y),endTags:p.tags,error:p.error,payload:p.payload,errorPayload:p.errorPayload,renderPayload:t=>p.error?n.default.Fragment:t(p.payload),message:p.message,raw:d,execute:e=>H(t,e),clearCached:()=>N(t),setCached:(e,s)=>{x(t,e,s)},setCachedPayload:(e,s)=>{D(t,e,s)},updateCached:(e,s)=>{j(t,e,s)}}};return{use:W,useDefer:(t={})=>{const[s,r]=e.useState((()=>t.key?t.key:f({})));return{...W({},{...t,key:s,initiate:!1}),clearCached:()=>{N({},s)},setCached:(t,e={})=>{e.key=s,x({},t,e)},setCachedPayload:(t,e={})=>{e.key=s,D({},t,e)},updateCached:(t,e={})=>{e.key=s,j({},t,e)},execute:(e={},s)=>{var n;const o=null!==(n=t.key)&&void 0!==n?n:f(e);return r(o),H(e,{...s,key:o}).then((e=>(t.clearOnSuccess&&N({},o),e)))}}},read:(s={},{cacheBreakEnabled:n=!0,postActionEnabled:o=!0,key:a}={})=>{const c=f(s,a),u=h?e.useContext(I)._asyncCache:S,l=h||r?e.useContext(I).stores:L.loaded?L.stores:A,d=g(c,u,s,l,t.EPostActionContext.READ_HIT_CACHE,o,n,!1);if(d){if(d[2].error)throw new k(d[2].message,d[2].tags);return d[2].payload}if(!u.actions.hasOwnProperty(c)){if(void 0!==i){const e=i({args:s,stores:l});if(!1!==e){if(_(e,s,l,t.EPostActionContext.SHORT_CIRCUIT),u.results[c]=[!0,!0,e,!1,Date.now()],e.error)throw new k(e.message,e.tags);return e.payload}}const e=m(u,c);if(u.actions[c]=E(c,u,s,l,e,o,t.EPostActionContext.READ_RUN),h)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[c]()}if(h)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 p=y++;throw new Promise((t=>{u.listeners[c][p]=()=>{delete u.listeners[c][p],t()}}))},useBeckon:(t={},{ssr:e=!0,postActionEnabled:s=!0,cacheBreakEnabled:r=!0,holdPrevious:n=!1,dormant:o=!1}={})=>{const a=v(t,{initiate:!0,ssr:e,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o});return[a[1],a[2],a[3]]},useWatch:v,run:H,delayedRun:(t={},{clearOldRun:e=!0,delay:s,immediateIfCached:r=!0,...n})=>{if(e&&clearTimeout(z),r){const{finished:e,cacheBreakable:s}=B(t,{checkCacheBreak:!0});if(e&&!s)return H(t,n),()=>{}}let o={cancelled:!1};return z=setTimeout((()=>{o.cancelled||H(t,n)}),s),()=>{o.cancelled=!0}},clearCache:N,clearAllCache:()=>{for(const t of Object.keys(S.actionOrd))t.startsWith(d+"-")&&w(t)},clearAllUnwatchedCache:()=>{for(const t of Object.keys(C))Object.values(C[t]).some((t=>t))||(delete C[t],w(t,!1))},getCached:B,setCached:x,setCachedPayload:D,updateCached:j}}const I=n.default.createContext(null);let H=null;const L={internalClientStores:!0,loaded:!1,stores:{}};class N{constructor(t,e={}){this.options={},null!==H&&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."),H=this,L.stores=t,L.loaded=!0,this.options=e}instantiate({hydrateSnapshot:t,ssr:e=!1}={}){if(!e){const e=new x(L.stores,!1);return null!=t&&e.hydrateFromSnapshot(t),e.instantiateReactions(),e}const s={};for(const r of Object.keys(L.stores))null==t?s[r]=new p(L.stores[r]._getInitialState()):t.hasOwnProperty(r)?s[r]=new p(t.allState[r]):(s[r]=new p(L.stores[r]._getInitialState()),console.warn(`Pullstate (instantiate): store [${r}] didn't hydrate any state (data was non-existent on hydration object)`)),s[r]._setInternalOptions({ssr:e,reactionCreators:L.stores[r]._getReactionCreators()});return new x(s,!0)}useStores(){return D()}useInstance(){return j()}createAsyncActionDirect(t,e={}){return U(t,e)}createAsyncAction(t,e={}){var s;return(null===(s=this.options.asyncActions)||void 0===s?void 0:s.defaultCachingSeconds)&&!e.cacheBreakHook&&(e.cacheBreakHook=t=>t.timeCached<Date.now()-1e3*this.options.asyncActions.defaultCachingSeconds),v(t,e)}}class x{constructor(t,e){this._ssr=!1,this._stores={},this._asyncCache={listeners:{},results:{},actions:{},actionOrd:{}},this._stores=t,this._ssr=e}getAllUnresolvedAsyncActions(){return Object.keys(this._asyncCache.actions).map((t=>this._asyncCache.actions[t]()))}instantiateReactions(){for(const t of Object.keys(this._stores))this._stores[t]._instantiateReactions()}getPullstateSnapshot(){const t={};for(const e of Object.keys(this._stores))t[e]=this._stores[e].getRawState();return{allState:t,asyncResults:this._asyncCache.results,asyncActionOrd:this._asyncCache.actionOrd}}async resolveAsyncState(){const t=this.getAllUnresolvedAsyncActions();await Promise.all(t)}hasAsyncStateToResolve(){return Object.keys(this._asyncCache.actions).length>0}get stores(){return this._stores}async runAsyncAction(t,e={},s={}){return this._ssr&&(s._asyncCache=this._asyncCache,s._stores=this._stores),await t.run(e,s)}hydrateFromSnapshot(t){for(const e of Object.keys(this._stores))t.allState.hasOwnProperty(e)?this._stores[e]._updateState(t.allState[e]):console.warn(e+" didn't hydrate any state (data was non-existent on hydration object)");S.results=t.asyncResults||{},S.actionOrd=t.asyncActionOrd||{}}}function D(){return e.useContext(I).stores}function j(){return e.useContext(I)}var B;(B=t.EAsyncActionInjectType||(t.EAsyncActionInjectType={})).WATCH="watch",B.BECKON="beckon",t.InjectAsyncAction=function(e){if(e.type===t.EAsyncActionInjectType.BECKON){const t=e.action.useBeckon(e.args,e.options);return e.children(t)}const s=e.action.useWatch(e.args,e.options);return e.children(s)},t.InjectStoreState=function({store:t,on:e=(t=>t),children:s}){return s(i(t,e))},t.InjectStoreStateOpt=function({store:t,paths:e,children:s}){return s(d(t,e))},t.PullstateContext=I,t.PullstateProvider=({instance:t,children:e})=>n.default.createElement(I.Provider,{value:t},e),t.Store=p,t.createAsyncAction=v,t.createAsyncActionDirect=U,t.createPullstateCore=function(t={},e={}){return new N(t,e)},t.errorResult=function(e=[],s="",r){return{payload:null,tags:[t.EAsyncEndTags.RETURNED_ERROR,...e],message:s,error:!0,errorPayload:r}},t.registerInDevtools=function(t,{namespace:e=""}={}){var s;const r="undefined"!=typeof window?null===(s=window)||void 0===s?void 0:s.__REDUX_DEVTOOLS_EXTENSION__:void 0;if(r)for(const s of Object.keys(t)){const n=t[s],o=r.connect({name:`${e}${s}`});o.init(n.getRawState());let a=!1;n.subscribe((t=>t),(t=>{a?a=!1:o.send("Change",t)})),o.subscribe((t=>{if("DISPATCH"===t.type&&t.state){a=!0;const e=JSON.parse(t.state);n.replace(e)}}))}},t.successResult=b,t.update=_,t.useInstance=j,t.useLocalStore=h,t.useStoreState=i,t.useStoreStateOpt=d,t.useStores=D,Object.defineProperty(t,"__esModule",{value:!0})})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("immer")):"function"==typeof define&&define.amd?define(["exports","react","immer"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).pullstate={},t.React,t.immer)}(this,(function(t,e,s){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=r(e),o=r(s),a=function t(e,s){if(e===s)return!0;if(e&&s&&"object"==typeof e&&"object"==typeof s){if(e.constructor!==s.constructor)return!1;var r,n,o;if(Array.isArray(e)){if((r=e.length)!=s.length)return!1;for(n=r;0!=n--;)if(!t(e[n],s[n]))return!1;return!0}if(e instanceof Map&&s instanceof Map){if(e.size!==s.size)return!1;for(n of e.entries())if(!s.has(n[0]))return!1;for(n of e.entries())if(!t(n[1],s.get(n[0])))return!1;return!0}if(e instanceof Set&&s instanceof Set){if(e.size!==s.size)return!1;for(n of e.entries())if(!s.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(s)){if((r=e.length)!=s.length)return!1;for(n=r;0!=n--;)if(e[n]!==s[n])return!1;return!0}if(e.constructor===RegExp)return e.source===s.source&&e.flags===s.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===s.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===s.toString();if((r=(o=Object.keys(e)).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(!t(e[a],s[a]))return!1}return!0}return e!=e&&s!=s};function i(t,s,r){const n=e.useRef({state:void 0,initialized:!1});n.current.initialized||(n.current.state=s?s(t.getRawState()):t.getRawState(),n.current.initialized=!0);const[,o]=e.useState(0);if(e.useEffect((()=>{const e={shouldUpdate:!0};function r(){if(e.shouldUpdate){const r=s?s(t.getRawState()):t.getRawState();a(n.current.state,r)||e.shouldUpdate&&(n.current.state=r,o((t=>t+1)))}}return t._addUpdateListener(r),r(),()=>{e.shouldUpdate=!1,t._removeUpdateListener(r)}}),null!=r?r:[]),void 0!==r){const o=e.useRef(r);a(r,o)||(n.current.state=s(t.getRawState()))}return n.current.state}let c=0;function u(t,e){return e.reduce(((e=t,s)=>e[s]),void 0)}function l(t,e){const s=t.getRawState(),r=[];for(const t of e)r.push(u(s,t));return r}function d(t,s){const[r,n]=e.useState((()=>l(t,s))),o=e.useRef({shouldUpdate:!0,onStoreUpdate:null,currentSubState:null,ordKey:"_"+c++});return o.current.currentSubState=r,null===o.current.onStoreUpdate&&(o.current.onStoreUpdate=function(){o.current.shouldUpdate&&n(l(t,s))},t._addUpdateListenerOpt(o.current.onStoreUpdate,o.current.ordKey,s)),e.useEffect((()=>()=>{o.current.shouldUpdate=!1,t._removeUpdateListenerOpt(o.current.ordKey)}),[]),r}function h(t,s){const r=e.useRef();if(null==r.current&&(r.current=new p("function"==typeof t?t():t)),void 0!==s){const n=e.useRef(s);a(s,n)||(r.current=new p("function"==typeof t?t():t))}return r.current}s.enablePatches();const f="~._.~";class p{constructor(t){this.updateListeners=[],this.ssr=!1,this.reactions=[],this.clientSubscriptions=[],this.reactionCreators=[],this.optimizedUpdateListeners={},this.optimizedUpdateListenerPaths={},this.optimizedListenerPropertyMap={},this._optListenerCount=0,this._patchListeners=[],this.currentState=t,this.initialState=t}_setInternalOptions({ssr:t,reactionCreators:e=[]}){this.ssr=t,this.reactionCreators=e,this.reactions=e.map((t=>t(this)))}_getReactionCreators(){return this.reactionCreators}_instantiateReactions(){this.reactions=this.reactionCreators.map((t=>t(this)))}_getInitialState(){return this.initialState}_updateStateWithoutReaction(t){this.currentState=t}_updateState(t,e=[]){this.currentState=t,this.batchState=void 0;for(const t of this.reactions)e.push(...t());if(!this.ssr){for(const t of this.clientSubscriptions)t();if(e.length>0){const t=new Set;for(const s of e)if(this.optimizedListenerPropertyMap[s])for(const e of this.optimizedListenerPropertyMap[s])t.add(e);for(const e of t.values())this.optimizedUpdateListeners[e]&&this.optimizedUpdateListeners[e]()}this.updateListeners.forEach((t=>t()))}}_addUpdateListener(t){this.updateListeners.push(t)}_addUpdateListenerOpt(t,e,s){this.optimizedUpdateListeners[e]=t;const r=s.map((t=>t.join(f)));this.optimizedUpdateListenerPaths[e]=r;for(const t of r)null==this.optimizedListenerPropertyMap[t]?this.optimizedListenerPropertyMap[t]=[e]:this.optimizedListenerPropertyMap[t].push(e);this._optListenerCount++}_removeUpdateListener(t){this.updateListeners=this.updateListeners.filter((e=>e!==t))}_removeUpdateListenerOpt(t){const e=this.optimizedUpdateListenerPaths[t];for(const s of e)this.optimizedListenerPropertyMap[s]=this.optimizedListenerPropertyMap[s].filter((e=>e!==t));delete this.optimizedUpdateListenerPaths[t],delete this.optimizedUpdateListeners[t],this._optListenerCount--}listenToPatches(t){return this._patchListeners.push(t),()=>{this._patchListeners=this._patchListeners.filter((e=>e!==t))}}subscribe(t,e){if(!this.ssr){const s=function(t,e,s){let r=e(t.getRawState());return()=>{const n=t.getRawState(),o=e(n);a(o,r)||(s(o,n,r),r=o)}}(this,t,e);return this.clientSubscriptions.push(s),()=>{this.clientSubscriptions=this.clientSubscriptions.filter((t=>t!==s))}}return()=>{console.warn("Pullstate: Subscriptions made on the server side are not registered - so therefor this call to unsubscribe does nothing.")}}createReaction(t,e,{runNow:r=!1,runNowWithSideEffects:n=!1}={}){const o=function(t,e){return r=>{let n=t(r.getRawState());return(o=!1)=>{const i=r.getRawState(),c=t(i);if(o||!a(c,n))if(r._optListenerCount>0){const[t,o,a]=s.produceWithPatches(i,(t=>e(c,t,i,n)));if(r._updateStateWithoutReaction(t),n=c,o.length>0)return r._patchListeners.forEach((t=>t(o,a))),Object.keys(y(o))}else{if(r._patchListeners.length>0){const[t,o,a]=s.produceWithPatches(i,(t=>e(c,t,i,n)));o.length>0&&r._patchListeners.forEach((t=>t(o,a))),r._updateStateWithoutReaction(t)}else r._updateStateWithoutReaction(s.produce(i,(t=>e(c,t,i,n))));n=c}return[]}}}(t,e);this.reactionCreators.push(o);const i=o(this);return this.reactions.push(i),(r||n)&&(i(!0),n&&!this.ssr&&this._updateState(this.currentState)),()=>{this.reactions=this.reactions.filter((t=>t!==i))}}getRawState(){return void 0!==this.batchState?this.batchState:this.currentState}useState(t,e){return i(this,t,e)}useLocalCopyInitial(t){return h((()=>this.initialState),t)}useLocalCopySnapshot(t){return h(this.currentState,t)}update(t,e){_(this,t,e)}replace(t){this._updateState(t)}applyPatches(t){!function(t,e){const r=t.getRawState(),n=s.applyPatches(r,e);n!==r&&t._updateState(n,Object.keys(y(e)))}(this,t)}}function y(t,e={}){for(const s of t){let t;for(const r of s.path)t=t?`${t}~._.~${r}`:r,e[t]=1}return e}function C(t,e,r){return r?s.produceWithPatches(t,(s=>e(s,t))):e.reduce((([t,e,r],n)=>{const o=s.produceWithPatches(t,(e=>n(e,t)));return e.push(...o[1]),r.push(...o[2]),[o[0],e,r]}),[t,[],[]])}function _(t,e,r){const n=t.getRawState(),o="function"==typeof e;if(t._optListenerCount>0){const[s,a,i]=C(n,e,o);a.length>0&&(r&&r(a,i),t._patchListeners.forEach((t=>t(a,i))),t._updateState(s,Object.keys(y(a))))}else{let a;if(t._patchListeners.length>0||r){const[s,i,c]=C(n,e,o);i.length>0&&(r&&r(i,c),t._patchListeners.forEach((t=>t(i,c)))),a=s}else a=s.produce(n,(t=>o?e(t,n):e.reduce(((t,e)=>s.produce(t,(s=>e(s,t)))),n)));a!==n&&t._updateState(a)}}var g,E;(g=t.EAsyncEndTags||(t.EAsyncEndTags={})).THREW_ERROR="THREW_ERROR",g.RETURNED_ERROR="RETURNED_ERROR",g.UNFINISHED="UNFINISHED",g.DORMANT="DORMANT",(E=t.EPostActionContext||(t.EPostActionContext={})).WATCH_HIT_CACHE="WATCH_HIT_CACHE",E.BECKON_HIT_CACHE="BECKON_HIT_CACHE",E.RUN_HIT_CACHE="RUN_HIT_CACHE",E.READ_HIT_CACHE="READ_HIT_CACHE",E.READ_RUN="READ_RUN",E.SHORT_CIRCUIT="SHORT_CIRCUIT",E.DIRECT_RUN="DIRECT_RUN",E.BECKON_RUN="BECKON_RUN",E.CACHE_UPDATE="CACHE_UPDATE";const S={listeners:{},results:{},actions:{},actionOrd:{}};let A,R=0;function P(t){if(null===t)return"(n)";const e=typeof t;if("object"!==e){if("undefined"===e)return"(u)";if("string"===e)return":"+t+";";if("boolean"===e||"number"===e)return"("+t+")"}let s="{";for(const e of Object.keys(t).sort())s+=e+P(t[e]);return s+"}"}function O(t){if(S.listeners.hasOwnProperty(t))for(const e of Object.keys(S.listeners[t]))S.listeners[t][e]()}function w(t,e=!0){e&&S.actionOrd.hasOwnProperty(t)&&(S.actionOrd[t]+=1),delete S.results[t],O(t)}function m(t,e){return t.actionOrd.hasOwnProperty(e)?t.actionOrd[e]+=1:t.actionOrd[e]=0,t.actionOrd[e]}function b(t=null,e=[],s=""){return{payload:t,tags:e,message:s,error:!1,errorPayload:null}}class k extends Error{constructor(t,e){super(t),this.tags=e}}try{A=new Proxy({},{get:function(t,e){throw new Error(`Pullstate: Trying to access store (${String(e)}) 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{A={}}const T=[!0,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];function U(t,e={}){return v((async e=>b(await t(e))),e)}function v(s,{forceContext:r=!1,shortCircuitHook:i,cacheBreakHook:c,postActionHook:u,subsetKey:l}={}){const d=R++,h="undefined"==typeof window;function f(t,e){return null!=e?`${d}-c-${e}`:void 0!==l?`${d}-${P(l(t))}`:`${d}-${P(t)}`}let p={},y=0;const C={};function _(t,e,s,r){void 0!==u&&u({args:e,result:t,stores:s,context:r})}function g(t,e,s,r,n,o,a,i){if(e.results.hasOwnProperty(t)){const u=p.hasOwnProperty(t)&&p[t]>2;if(!(e.results[t][1]&&a&&void 0!==c&&c({args:s,result:e.results[t][2],stores:r,timeCached:e.results[t][4]}))||u)return u?console.error(`[${t}] 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.`):p[t]=0,o&&e.results[t][1]&&!i&&_(e.results[t][2],s,r,n),e.results[t];p.hasOwnProperty(t)?p[t]++:p[t]=1,delete e.results[t]}}function E(e,r,n,o,a,i,c){return()=>s(n,o).then((t=>(a===r.actionOrd[e]&&(i&&_(t,n,o,c),r.results[e]=[!0,!0,t,!1,Date.now()]),t))).catch((s=>{console.error(s);const u={payload:null,errorPayload:null,error:!0,tags:[t.EAsyncEndTags.THREW_ERROR],message:s.message};return a===r.actionOrd[e]&&(i&&_(u,n,o,c),r.results[e]=[!0,!0,u,!1,Date.now()]),u})).then((t=>(a===r.actionOrd[e]&&(delete r.actions[e],h||O(e)),t)))}function U(e,s,r,n,o,a,c=!1,u=!0,l=!0,d){const f=g(e,s,o,a,r?t.EPostActionContext.BECKON_HIT_CACHE:t.EPostActionContext.WATCH_HIT_CACHE,u,l,c);if(f)return f;if(!s.actions.hasOwnProperty(e)){const c=m(s,e);if(!r){const r=[!1,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];if(h||(s.results[e]=r),d){const t=[...d];return t[3]=!0,t}return r}if(void 0!==i){const r=i({args:o,stores:a});if(!1!==r)return _(r,o,a,t.EPostActionContext.SHORT_CIRCUIT),s.results[e]=[!0,!0,r,!1,Date.now()],s.results[e]}if(!n&&h||(s.actions[e]=E(e,s,o,a,c,u,t.EPostActionContext.BECKON_RUN)),h)return T;s.actions[e](),s.results[e]=T}if(d){const t=[...d];return t[3]=!0,t}return T}const v=(s={},{initiate:n=!1,ssr:o=!0,postActionEnabled:i=!1,cacheBreakEnabled:c=!1,holdPrevious:u=!1,dormant:l=!1,key:d}={})=>{const p=e.useRef(),_=e.useRef("."),g=l?".":f(s,d);let E=e.useRef(-1);-1===E.current&&(E.current=y++),l||(C.hasOwnProperty(g)?C[g][E.current]=!0:C[g]={[E.current]:!0});const R=h?e.useContext(I)._asyncCache:S,P=h||r?e.useContext(I).stores:L.loaded?L.stores:A;if(!h){const t=()=>{C[g][E.current]&&!a(p.current,R.results[g])&&(p.current=U(g,R,n,o,s,P,!0,i,c),w((t=>t+1)))};l||(R.listeners.hasOwnProperty(g)||(R.listeners[g]={}),R.listeners[g][E.current]=t,C[g][E.current]=!0),e.useEffect((()=>(l||(R.listeners[g][E.current]=t,C[g][E.current]=!0),()=>{l||(delete R.listeners[g][E.current],C[g][E.current]=!1)})),[g])}const[O,w]=e.useState(0);return l?(p.current=u&&p.current&&p.current[1]?p.current:[!1,!1,{message:"",tags:[t.EAsyncEndTags.DORMANT],error:!0,payload:null},!1,-1],_.current="."):_.current!==g&&(null!==_.current&&C.hasOwnProperty(_.current)&&(delete R.listeners[_.current][E.current],C[_.current][E.current]=!1),_.current=g,p.current=U(g,R,n,o,s,P,!1,i,c,u&&p.current&&p.current[1]?p.current:void 0)),p.current},H=async(e={},{treatAsUpdate:s=!1,ignoreShortCircuit:r=!1,respectCache:n=!1,key:o,_asyncCache:a=S,_stores:c=(L.loaded?L.stores:A)}={})=>{const u=f(e,o);if(n){const s=g(u,a,e,c,t.EPostActionContext.RUN_HIT_CACHE,!0,!0,!1);if(s){if(!s[1]){const t=y++;return a.listeners.hasOwnProperty(u)||(a.listeners[u]={}),new Promise((e=>{a.listeners[u][t]=()=>{const[,s,r]=a.results[u];s&&(delete a.listeners[u][t],e(r))}}))}return s[2]}}if(!r&&void 0!==i){const s=i({args:e,stores:c});if(!1!==s)return a.results[u]=[!0,!0,s,!1,Date.now()],_(s,e,c,t.EPostActionContext.SHORT_CIRCUIT),O(u),s}const[,l,d,h,p]=a.results[u]||[!1,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];a.results[u]=l&&s?[!0,!0,d,!0,p]:[!0,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];let C=m(a,u);return a.actions[u]=E(u,a,e,c,C,!0,t.EPostActionContext.DIRECT_RUN),O(u),a.actions[u]()},N=(t={},e)=>{w(f(t,e))},x=(t,s,r)=>{const{notify:n=!0,key:o}=r||{},a=f(t,o);(h?e.useContext(I)._asyncCache:S).results[a]=[!0,!0,s,!1,Date.now()],n&&O(a)},D=(t,e,s)=>x(t,b(e),s),j=(s,r,n)=>{const{notify:a=!0,resetTimeCached:i=!0,runPostActionHook:c=!1,key:u}=n||{},l=f(s,u),d=h?e.useContext(I)._asyncCache:S;if(d.results.hasOwnProperty(l)&&!d.results[l][2].error){const e=d.results[l][2].payload,n={payload:o.default(e,(t=>r(t,e))),error:!1,message:d.results[l][2].message,tags:d.results[l][2].tags};c&&_(n,s,L.loaded?L.stores:A,t.EPostActionContext.CACHE_UPDATE),d.results[l]=[!0,!0,n,d.results[l][3],i?Date.now():d.results[l][4]],a&&O(l)}},B=(s={},r)=>{const{checkCacheBreak:n=!1,key:o}=r||{},a=f(s,o);let i=!1;const u=h?e.useContext(I)._asyncCache:S;if(u.results.hasOwnProperty(a)){if(n&&void 0!==c){const t=h?e.useContext(I).stores:L.loaded?L.stores:A;c({args:s,result:u.results[a][2],stores:t,timeCached:u.results[a][4]})&&(i=!0)}const[t,r,o,l,d]=u.results[a];return{started:t,finished:r,result:o,existed:!0,cacheBreakable:i,updating:l,timeCached:d}}return{started:!1,finished:!1,result:{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},updating:!1,existed:!1,cacheBreakable:i,timeCached:-1}};let z;const W=(t={},{initiate:s=!0,ssr:r=!0,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i=!1,dormant:c=!1,key:u,onSuccess:l}={})=>{null==o&&(o=s),null==a&&(a=s);const d=v(t,{initiate:s,ssr:r,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i,dormant:c,key:u}),[h,f,p,y]=d,C=f&&!p.error,_=f&&p.error;l&&e.useEffect((()=>{C&&!c&&l(p.payload,t)}),[C]);return{isStarted:h,isFinished:f,isUpdating:y,isSuccess:C,isFailure:_,isLoading:h&&(!f||y),endTags:p.tags,error:p.error,payload:p.payload,errorPayload:p.errorPayload,renderPayload:t=>p.error?n.default.Fragment:t(p.payload),message:p.message,raw:d,execute:e=>H(t,e),clearCached:()=>N(t),setCached:(e,s)=>{x(t,e,s)},setCachedPayload:(e,s)=>{D(t,e,s)},updateCached:(e,s)=>{j(t,e,s)}}};return{use:W,useDefer:(t={})=>{const[s,r]=e.useState((()=>t.key?t.key:f({})));return{...W({},{...t,key:s,initiate:!1}),clearCached:()=>{N({},s)},setCached:(t,e={})=>{e.key=s,x({},t,e)},setCachedPayload:(t,e={})=>{e.key=s,D({},t,e)},updateCached:(t,e={})=>{e.key=s,j({},t,e)},execute:(e={},s)=>{var n;const o=null!==(n=t.key)&&void 0!==n?n:f(e);return r(o),H(e,{...s,key:o}).then((e=>(t.clearOnSuccess&&N({},o),e)))}}},read:(s={},{cacheBreakEnabled:n=!0,postActionEnabled:o=!0,key:a}={})=>{const c=f(s,a),u=h?e.useContext(I)._asyncCache:S,l=h||r?e.useContext(I).stores:L.loaded?L.stores:A,d=g(c,u,s,l,t.EPostActionContext.READ_HIT_CACHE,o,n,!1);if(d){if(d[2].error)throw new k(d[2].message,d[2].tags);return d[2].payload}if(!u.actions.hasOwnProperty(c)){if(void 0!==i){const e=i({args:s,stores:l});if(!1!==e){if(_(e,s,l,t.EPostActionContext.SHORT_CIRCUIT),u.results[c]=[!0,!0,e,!1,Date.now()],e.error)throw new k(e.message,e.tags);return e.payload}}const e=m(u,c);if(u.actions[c]=E(c,u,s,l,e,o,t.EPostActionContext.READ_RUN),h)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[c]()}if(h)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 p=y++;throw new Promise((t=>{u.listeners[c][p]=()=>{delete u.listeners[c][p],t()}}))},useBeckon:(t={},{ssr:e=!0,postActionEnabled:s=!0,cacheBreakEnabled:r=!0,holdPrevious:n=!1,dormant:o=!1}={})=>{const a=v(t,{initiate:!0,ssr:e,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o});return[a[1],a[2],a[3]]},useWatch:v,run:H,delayedRun:(t={},{clearOldRun:e=!0,delay:s,immediateIfCached:r=!0,...n})=>{if(e&&clearTimeout(z),r){const{finished:e,cacheBreakable:s}=B(t,{checkCacheBreak:!0});if(e&&!s)return H(t,n),()=>{}}let o={cancelled:!1};return z=setTimeout((()=>{o.cancelled||H(t,n)}),s),()=>{o.cancelled=!0}},clearCache:N,clearAllCache:()=>{for(const t of Object.keys(S.actionOrd))t.startsWith(d+"-")&&w(t)},clearAllUnwatchedCache:()=>{for(const t of Object.keys(C))Object.values(C[t]).some((t=>t))||(delete C[t],w(t,!1))},getCached:B,setCached:x,setCachedPayload:D,updateCached:j}}const I=n.default.createContext(null);let H=null;const L={internalClientStores:!0,loaded:!1,stores:{}};class N{constructor(t,e={}){this.options={},null!==H&&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."),H=this,L.stores=t,L.loaded=!0,this.options=e}instantiate({hydrateSnapshot:t,ssr:e=!1}={}){if(!e){const e=new x(L.stores,!1);return null!=t&&e.hydrateFromSnapshot(t),e.instantiateReactions(),e}const s={};for(const r of Object.keys(L.stores))null==t?s[r]=new p(L.stores[r]._getInitialState()):t.hasOwnProperty(r)?s[r]=new p(t.allState[r]):(s[r]=new p(L.stores[r]._getInitialState()),console.warn(`Pullstate (instantiate): store [${r}] didn't hydrate any state (data was non-existent on hydration object)`)),s[r]._setInternalOptions({ssr:e,reactionCreators:L.stores[r]._getReactionCreators()});return new x(s,!0)}useStores(){return D()}useInstance(){return j()}createAsyncActionDirect(t,e={}){return U(t,e)}createAsyncAction(t,e={}){var s;return(null===(s=this.options.asyncActions)||void 0===s?void 0:s.defaultCachingSeconds)&&!e.cacheBreakHook&&(e.cacheBreakHook=t=>t.timeCached<Date.now()-1e3*this.options.asyncActions.defaultCachingSeconds),v(t,e)}}class x{constructor(t,e){this._ssr=!1,this._stores={},this._asyncCache={listeners:{},results:{},actions:{},actionOrd:{}},this._stores=t,this._ssr=e}getAllUnresolvedAsyncActions(){return Object.keys(this._asyncCache.actions).map((t=>this._asyncCache.actions[t]()))}instantiateReactions(){for(const t of Object.keys(this._stores))this._stores[t]._instantiateReactions()}getPullstateSnapshot(){const t={};for(const e of Object.keys(this._stores))t[e]=this._stores[e].getRawState();return{allState:t,asyncResults:this._asyncCache.results,asyncActionOrd:this._asyncCache.actionOrd}}async resolveAsyncState(){const t=this.getAllUnresolvedAsyncActions();await Promise.all(t)}hasAsyncStateToResolve(){return Object.keys(this._asyncCache.actions).length>0}get stores(){return this._stores}async runAsyncAction(t,e={},s={}){return this._ssr&&(s._asyncCache=this._asyncCache,s._stores=this._stores),await t.run(e,s)}hydrateFromSnapshot(t){for(const e of Object.keys(this._stores))t.allState.hasOwnProperty(e)?this._stores[e]._updateState(t.allState[e]):console.warn(e+" didn't hydrate any state (data was non-existent on hydration object)");S.results=t.asyncResults||{},S.actionOrd=t.asyncActionOrd||{}}}function D(){return e.useContext(I).stores}function j(){return e.useContext(I)}var B;(B=t.EAsyncActionInjectType||(t.EAsyncActionInjectType={})).WATCH="watch",B.BECKON="beckon",t.InjectAsyncAction=function(e){if(e.type===t.EAsyncActionInjectType.BECKON){const t=e.action.useBeckon(e.args,e.options);return e.children(t)}const s=e.action.useWatch(e.args,e.options);return e.children(s)},t.InjectStoreState=function({store:t,on:e=(t=>t),children:s}){return s(i(t,e))},t.InjectStoreStateOpt=function({store:t,paths:e,children:s}){return s(d(t,e))},t.PullstateContext=I,t.PullstateProvider=({instance:t,children:e})=>n.default.createElement(I.Provider,{value:t},e),t.Store=p,t.createAsyncAction=v,t.createAsyncActionDirect=U,t.createPullstateCore=function(t={},e={}){return new N(t,e)},t.errorResult=function(e=[],s="",r){return{payload:null,tags:[t.EAsyncEndTags.RETURNED_ERROR,...e],message:s,error:!0,errorPayload:r}},t.registerInDevtools=function(t,{namespace:e=""}={}){var s;const r="undefined"!=typeof window?null===(s=window)||void 0===s?void 0:s.__REDUX_DEVTOOLS_EXTENSION__:void 0;if(r)for(const s of Object.keys(t)){const n=t[s],o=r.connect({name:`${e}${s}`});o.init(n.getRawState());let a=!1;n.subscribe((t=>t),(t=>{a?a=!1:o.send("Change",t)})),o.subscribe((t=>{if("DISPATCH"===t.type&&t.state){a=!0;const e=JSON.parse(t.state);n.replace(e)}}))}},t.successResult=b,t.update=_,t.useInstance=j,t.useLocalStore=h,t.useStoreState=i,t.useStoreStateOpt=d,t.useStores=D,Object.defineProperty(t,"__esModule",{value:!0})})); |
{ | ||
"name": "pullstate", | ||
"version": "1.20.2", | ||
"version": "1.20.3", | ||
"description": "Simple state stores using immer and React hooks", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
232747
4434