Comparing version 1.20.6 to 1.21.0
@@ -71,8 +71,9 @@ import { IPullstateAllStores } from "./PullstateCore"; | ||
}) => void; | ||
export interface IAsyncActionReadOptions { | ||
export interface IAsyncActionReadOptions<A, R, T extends string, N, S extends IPullstateAllStores> { | ||
postActionEnabled?: boolean; | ||
cacheBreakEnabled?: boolean; | ||
key?: string; | ||
cacheBreak?: boolean | TPullstateAsyncCacheBreakHook<A, R, T, N, S>; | ||
} | ||
export interface IAsyncActionBeckonOptions extends IAsyncActionReadOptions { | ||
export interface IAsyncActionBeckonOptions<A, R, T extends string, N, S extends IPullstateAllStores> extends IAsyncActionReadOptions<A, R, T, N, S> { | ||
ssr?: boolean; | ||
@@ -82,9 +83,9 @@ holdPrevious?: boolean; | ||
} | ||
export interface IAsyncActionWatchOptions extends IAsyncActionBeckonOptions { | ||
export interface IAsyncActionWatchOptions<A, R, T extends string, N, S extends IPullstateAllStores> extends IAsyncActionBeckonOptions<A, R, T, N, S> { | ||
initiate?: boolean; | ||
} | ||
export interface IAsyncActionUseOptions<R, A> extends IAsyncActionWatchOptions { | ||
export interface IAsyncActionUseOptions<A, R, T extends string, N, S extends IPullstateAllStores> extends IAsyncActionWatchOptions<A, R, T, N, S> { | ||
onSuccess?: (result: R, args: A) => void; | ||
} | ||
export interface IAsyncActionUseDeferOptions<R, A> extends Omit<IAsyncActionReadOptions, "key"> { | ||
export interface IAsyncActionUseDeferOptions<A, R, T extends string, N, S extends IPullstateAllStores> extends Omit<IAsyncActionReadOptions<A, R, T, N, S>, "key"> { | ||
key?: string; | ||
@@ -127,6 +128,6 @@ holdPrevious?: boolean; | ||
} | ||
export declare type TAsyncActionUse<A, R, T extends string, N> = (args?: A, options?: IAsyncActionUseOptions<R, A>) => TUseResponse<R, T, N>; | ||
export declare type TAsyncActionUseDefer<A, R, T extends string, N> = (options?: IAsyncActionUseDeferOptions<R, A>) => TUseDeferResponse<A, R, T, N>; | ||
export declare type TAsyncActionBeckon<A, R, T extends string, N> = (args?: A, options?: IAsyncActionBeckonOptions) => TPullstateAsyncBeckonResponse<R, T, N>; | ||
export declare type TAsyncActionWatch<A, R, T extends string, N> = (args?: A, options?: IAsyncActionWatchOptions) => TPullstateAsyncWatchResponse<R, T, N>; | ||
export declare type TAsyncActionUse<A, R, T extends string, N, S extends IPullstateAllStores> = (args?: A, options?: IAsyncActionUseOptions<A, R, T, N, S>) => TUseResponse<R, T, N>; | ||
export declare type TAsyncActionUseDefer<A, R, T extends string, N, S extends IPullstateAllStores> = (options?: IAsyncActionUseDeferOptions<A, R, T, N, S>) => TUseDeferResponse<A, R, T, N>; | ||
export declare type TAsyncActionBeckon<A, R, T extends string, N, S extends IPullstateAllStores> = (args?: A, options?: IAsyncActionBeckonOptions<A, R, T, N, S>) => TPullstateAsyncBeckonResponse<R, T, N>; | ||
export declare type TAsyncActionWatch<A, R, T extends string, N, S extends IPullstateAllStores> = (args?: A, options?: IAsyncActionWatchOptions<A, R, T, N, S>) => TPullstateAsyncWatchResponse<R, T, N>; | ||
export declare type TAsyncActionRun<A, R, T extends string, N> = (args?: A, options?: IAsyncActionRunOptions) => TPullstateAsyncRunResponse<R, T, N>; | ||
@@ -140,3 +141,3 @@ export declare type TAsyncActionClearCache<A> = (args?: A, options?: IAsyncActionSetOrClearCachedValueOptions) => void; | ||
export declare type TAsyncActionUpdateCached<A, R> = (args: A, updater: TUpdateFunction<R>, options?: IAsyncActionUpdateCachedOptions) => void; | ||
export declare type TAsyncActionRead<A, R> = (args?: A, options?: IAsyncActionReadOptions) => R; | ||
export declare type TAsyncActionRead<A, R, T extends string, N, S extends IPullstateAllStores> = (args?: A, options?: IAsyncActionReadOptions<A, R, T, N, S>) => R; | ||
export declare type TAsyncActionDelayedRun<A> = (args: A, options: IAsyncActionRunOptions & { | ||
@@ -147,8 +148,8 @@ delay: number; | ||
}) => () => void; | ||
export interface IOCreateAsyncActionOutput<A = any, R = any, T extends string = string, N = any> { | ||
use: TAsyncActionUse<A, R, T, N>; | ||
useDefer: TAsyncActionUseDefer<A, R, T, N>; | ||
read: TAsyncActionRead<A, R>; | ||
useBeckon: TAsyncActionBeckon<A, R, T, N>; | ||
useWatch: TAsyncActionWatch<A, R, T, N>; | ||
export interface IOCreateAsyncActionOutput<A = any, R = any, T extends string = string, N = any, S extends IPullstateAllStores = IPullstateAllStores> { | ||
use: TAsyncActionUse<A, R, T, N, S>; | ||
useDefer: TAsyncActionUseDefer<A, R, T, N, S>; | ||
read: TAsyncActionRead<A, R, T, N, S>; | ||
useBeckon: TAsyncActionBeckon<A, R, T, N, S>; | ||
useWatch: TAsyncActionWatch<A, R, T, N, S>; | ||
run: TAsyncActionRun<A, R, T, N>; | ||
@@ -155,0 +156,0 @@ delayedRun: TAsyncActionDelayedRun<A>; |
@@ -13,4 +13,5 @@ import { useStoreState } from "./useStoreState"; | ||
import { useLocalStore } from "./useLocalStore"; | ||
import { batch, setupBatch } from "./batch"; | ||
export * from "./async-types"; | ||
export { useStoreState, useStoreStateOpt, useLocalStore, update, Store, InjectStoreState, InjectStoreStateOpt, PullstateProvider, useStores, useInstance, createPullstateCore, createAsyncAction, createAsyncActionDirect, successResult, errorResult, IPullstateInstanceConsumable, IPullstateAllStores, InjectAsyncAction, EAsyncActionInjectType, TInjectAsyncActionProps, TUpdateFunction, TStoreAction, TMultiStoreAction, PullstateContext, TUseResponse, registerInDevtools }; | ||
export { useStoreState, useStoreStateOpt, useLocalStore, update, Store, InjectStoreState, InjectStoreStateOpt, PullstateProvider, useStores, useInstance, createPullstateCore, createAsyncAction, createAsyncActionDirect, successResult, errorResult, IPullstateInstanceConsumable, IPullstateAllStores, InjectAsyncAction, EAsyncActionInjectType, TInjectAsyncActionProps, TUpdateFunction, TStoreAction, TMultiStoreAction, PullstateContext, TUseResponse, registerInDevtools, batch, setupBatch }; | ||
export type { PullstateSingleton }; |
@@ -76,3 +76,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) { | ||
if (storeRef.current == null) { | ||
storeRef.current = new Store(typeof initialState === "function" ? initialState() : initialState); | ||
storeRef.current = new Store(initialState); | ||
} | ||
@@ -82,7 +82,11 @@ if (deps !== undefined) { | ||
if (!isEqual(deps, prevDeps)) { | ||
storeRef.current = new Store(typeof initialState === "function" ? initialState() : initialState); | ||
storeRef.current = new Store(initialState); | ||
} | ||
} | ||
return storeRef.current; | ||
}enablePatches(); | ||
}const globalClientState = { | ||
storeOrdinal: 0, | ||
batching: false, | ||
flushStores: {} | ||
};enablePatches(); | ||
function makeSubscriptionFunction(store, watch, listener) { | ||
@@ -146,4 +150,14 @@ let lastWatchState = watch(store.getRawState()); | ||
this._patchListeners = []; | ||
this.currentState = initialState; | ||
this.initialState = initialState; | ||
if (initialState instanceof Function) { | ||
const state = initialState(); | ||
this.currentState = state; | ||
this.initialState = state; | ||
this.createInitialState = initialState; | ||
} | ||
else { | ||
this.currentState = initialState; | ||
this.initialState = initialState; | ||
this.createInitialState = () => initialState; | ||
} | ||
this.internalOrdId = globalClientState.storeOrdinal++; | ||
} | ||
@@ -162,3 +176,3 @@ _setInternalOptions({ ssr, reactionCreators = [] }) { | ||
_getInitialState() { | ||
return this.initialState; | ||
return this.createInitialState(); | ||
} | ||
@@ -270,3 +284,3 @@ _updateStateWithoutReaction(nextState) { | ||
useLocalCopyInitial(deps) { | ||
return useLocalStore(() => this.initialState, deps); | ||
return useLocalStore(this.createInitialState, deps); | ||
} | ||
@@ -276,4 +290,33 @@ useLocalCopySnapshot(deps) { | ||
} | ||
flushBatch(ignoreError = false) { | ||
if (this.batchState !== undefined) { | ||
if (this.batchState !== this.currentState) { | ||
this._updateState(this.batchState); | ||
} | ||
} | ||
else if (!ignoreError) { | ||
console.error(`Pullstate: Trying to flush batch state which was never created or updated on`); | ||
} | ||
this.batchState = undefined; | ||
} | ||
update(updater, patchesCallback) { | ||
update(this, updater, patchesCallback); | ||
if (globalClientState.batching) { | ||
if (this.batchState === undefined) { | ||
this.batchState = this.currentState; | ||
globalClientState.flushStores[this.internalOrdId] = this; | ||
} | ||
const func = typeof updater === "function"; | ||
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func); | ||
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) { | ||
if (patchesCallback) { | ||
patchesCallback(patches, inversePatches); | ||
} | ||
this._patchListeners.forEach((listener) => listener(patches, inversePatches)); | ||
} | ||
this.batchState = nextState; | ||
} | ||
else { | ||
this.batchState = undefined; | ||
update(this, updater, patchesCallback); | ||
} | ||
} | ||
@@ -509,9 +552,12 @@ replace(newState) { | ||
} | ||
function getCachedResult(key, cache, args, stores, context, postActionEnabled, cacheBreakEnabled, fromListener) { | ||
function getCachedResult({ args, cache, cacheBreakEnabled, context, fromListener, key, postActionEnabled, stores, customCacheBreak }) { | ||
const useCacheBreakHook = customCacheBreak !== null && customCacheBreak !== void 0 ? customCacheBreak : cacheBreakHook; | ||
if (cache.results.hasOwnProperty(key)) { | ||
const cacheBreakLoop = cacheBreakWatcher.hasOwnProperty(key) && cacheBreakWatcher[key] > 2; | ||
if (cache.results[key][1] && | ||
if (!onServer && | ||
!fromListener && | ||
cacheBreakEnabled && | ||
cacheBreakHook !== undefined && | ||
cacheBreakHook({ | ||
useCacheBreakHook != null | ||
&& cache.results[key][1] && | ||
useCacheBreakHook({ | ||
args, | ||
@@ -529,3 +575,5 @@ result: cache.results[key][2], | ||
} | ||
const previous = cache.results[key]; | ||
delete cache.results[key]; | ||
return { cacheBroke: true, response: undefined, previous }; | ||
} | ||
@@ -545,6 +593,10 @@ else { | ||
} | ||
return cache.results[key]; | ||
return { | ||
response: cache.results[key], | ||
cacheBroke: false, | ||
previous: undefined | ||
}; | ||
} | ||
} | ||
return undefined; | ||
return { cacheBroke: false, response: undefined, previous: undefined }; | ||
} | ||
@@ -589,6 +641,16 @@ function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, executionContext, customContext) { | ||
} | ||
function checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult, customContext) { | ||
const cached = getCachedResult(key, cache, args, stores, initiate ? EPostActionContext.BECKON_HIT_CACHE : EPostActionContext.WATCH_HIT_CACHE, postActionEnabled, cacheBreakEnabled, fromListener); | ||
if (cached) { | ||
return cached; | ||
function checkKeyAndReturnResponse({ key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult, customContext, customCacheBreak, holdPrevious }) { | ||
const cached = getCachedResult({ | ||
key, | ||
cache, | ||
args, | ||
stores, | ||
context: initiate ? EPostActionContext.BECKON_HIT_CACHE : EPostActionContext.WATCH_HIT_CACHE, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
fromListener, | ||
customCacheBreak | ||
}); | ||
if (cached.response) { | ||
return cached.response; | ||
} | ||
@@ -634,6 +696,13 @@ if (!cache.actions.hasOwnProperty(key)) { | ||
} | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
if (holdPrevious) { | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
} | ||
if (cached.previous != null) { | ||
const response = [...cached.previous]; | ||
response[3] = true; | ||
return response; | ||
} | ||
} | ||
@@ -643,6 +712,13 @@ return resp; | ||
} | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
if (holdPrevious) { | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
} | ||
if (cached.previous != null) { | ||
const response = [...cached.previous]; | ||
response[3] = true; | ||
return response; | ||
} | ||
} | ||
@@ -667,9 +743,18 @@ return startedButUnfinishedResult; | ||
} | ||
const cached = getCachedResult(key, cache, args, stores, EPostActionContext.READ_HIT_CACHE, postActionEnabled, cacheBreakEnabled, false); | ||
if (cached) { | ||
if (!cached[2].error) { | ||
return cached[2].payload; | ||
const cached = getCachedResult({ | ||
key, | ||
cache, | ||
args, | ||
stores, | ||
context: EPostActionContext.READ_HIT_CACHE, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
fromListener: false | ||
}); | ||
if (cached.response) { | ||
if (!cached.response[2].error) { | ||
return cached.response[2].payload; | ||
} | ||
else { | ||
throw new PullstateAsyncError(cached[2].message, cached[2].tags); | ||
throw new PullstateAsyncError(cached.response[2].message, cached.response[2].tags); | ||
} | ||
@@ -709,3 +794,3 @@ } | ||
}; | ||
const useWatch = (args = {}, { initiate = false, ssr = true, postActionEnabled = false, cacheBreakEnabled = false, holdPrevious = false, dormant = false, key: customKey } = {}) => { | ||
const useWatch = (args = {}, { initiate = false, ssr = true, postActionEnabled = false, cacheBreakEnabled = false, holdPrevious = false, dormant = false, key: customKey, cacheBreak: customCacheBreak } = {}) => { | ||
const responseRef = useRef(); | ||
@@ -745,3 +830,16 @@ const prevKeyRef = useRef("."); | ||
if (shouldUpdate[key][watchId.current] && !isEqual(responseRef.current, cache.results[key])) { | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled, undefined, customContext); | ||
responseRef.current = checkKeyAndReturnResponse({ | ||
key, | ||
cache, | ||
initiate, | ||
ssr, | ||
args, | ||
stores, | ||
fromListener: true, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdingResult: undefined, | ||
customContext, | ||
holdPrevious | ||
}); | ||
setWatchUpdate((prev) => { | ||
@@ -797,3 +895,17 @@ return prev + 1; | ||
prevKeyRef.current = key; | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, false, postActionEnabled, cacheBreakEnabled, holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, customContext); | ||
responseRef.current = checkKeyAndReturnResponse({ | ||
key, | ||
cache, | ||
initiate, | ||
ssr, | ||
args, | ||
stores, | ||
fromListener: false, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdingResult: holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, | ||
customContext, | ||
customCacheBreak: typeof customCacheBreak === "boolean" ? () => customCacheBreak : customCacheBreak, | ||
holdPrevious | ||
}); | ||
} | ||
@@ -817,5 +929,14 @@ return responseRef.current; | ||
if (respectCache) { | ||
const cached = getCachedResult(key, _asyncCache, args, _stores, EPostActionContext.RUN_HIT_CACHE, true, true, false); | ||
if (cached) { | ||
if (!cached[1]) { | ||
const cached = getCachedResult({ | ||
key, | ||
cache: _asyncCache, | ||
args, | ||
stores: _stores, | ||
context: EPostActionContext.RUN_HIT_CACHE, | ||
postActionEnabled: true, | ||
cacheBreakEnabled: true, | ||
fromListener: false | ||
}); | ||
if (cached.response) { | ||
if (!cached.response[1]) { | ||
const watchOrd = watchIdOrd++; | ||
@@ -835,3 +956,3 @@ if (!_asyncCache.listeners.hasOwnProperty(key)) { | ||
} | ||
return cached[2]; | ||
return cached.response[2]; | ||
} | ||
@@ -1013,3 +1134,3 @@ } | ||
}; | ||
const use = (args = {}, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, onSuccess } = {}) => { | ||
const use = (args = {}, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, onSuccess, cacheBreak: customCacheBreakHook } = {}) => { | ||
if (postActionEnabled == null) { | ||
@@ -1021,3 +1142,12 @@ postActionEnabled = initiate; | ||
} | ||
const raw = useWatch(args, { initiate, ssr, postActionEnabled, cacheBreakEnabled, holdPrevious, dormant, key }); | ||
const raw = useWatch(args, { | ||
initiate, | ||
ssr, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdPrevious, | ||
dormant, | ||
key, | ||
cacheBreak: customCacheBreakHook | ||
}); | ||
const [isStarted, isFinished, result, isUpdating] = raw; | ||
@@ -1245,3 +1375,3 @@ const isSuccess = isFinished && !result.error; | ||
if (snapshot.allState.hasOwnProperty(storeName)) { | ||
this._stores[storeName]._updateState(snapshot.allState[storeName]); | ||
this._stores[storeName]._updateStateWithoutReaction(snapshot.allState[storeName]); | ||
} | ||
@@ -1304,2 +1434,27 @@ else { | ||
} | ||
}export{EAsyncActionInjectType,EAsyncEndTags,EPostActionContext,InjectAsyncAction,InjectStoreState,InjectStoreStateOpt,PullstateContext,PullstateProvider,Store,createAsyncAction,createAsyncActionDirect,createPullstateCore,errorResult,registerInDevtools,successResult,update,useInstance,useLocalStore,useStoreState,useStoreStateOpt,useStores}; | ||
}const batchState = {}; | ||
function setupBatch({ uiBatchFunction }) { | ||
batchState.uiBatchFunction = uiBatchFunction; | ||
} | ||
function batch(runUpdates) { | ||
if (globalClientState.batching) { | ||
throw new Error("Pullstate: Can't enact two batch() update functions at the same time-\n" + | ||
"make sure you are not running a batch() inside of a batch() by mistake."); | ||
} | ||
globalClientState.batching = true; | ||
try { | ||
runUpdates(); | ||
} | ||
finally { | ||
if (batchState.uiBatchFunction) { | ||
batchState.uiBatchFunction(() => { | ||
Object.values(globalClientState.flushStores).forEach(store => store.flushBatch(true)); | ||
}); | ||
} | ||
else { | ||
Object.values(globalClientState.flushStores).forEach(store => store.flushBatch(true)); | ||
} | ||
globalClientState.flushStores = {}; | ||
globalClientState.batching = false; | ||
} | ||
}export{EAsyncActionInjectType,EAsyncEndTags,EPostActionContext,InjectAsyncAction,InjectStoreState,InjectStoreStateOpt,PullstateContext,PullstateProvider,Store,batch,createAsyncAction,createAsyncActionDirect,createPullstateCore,errorResult,registerInDevtools,setupBatch,successResult,update,useInstance,useLocalStore,useStoreState,useStoreStateOpt,useStores}; |
@@ -76,3 +76,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) { | ||
if (storeRef.current == null) { | ||
storeRef.current = new Store(typeof initialState === "function" ? initialState() : initialState); | ||
storeRef.current = new Store(initialState); | ||
} | ||
@@ -82,7 +82,11 @@ if (deps !== undefined) { | ||
if (!isEqual__default['default'](deps, prevDeps)) { | ||
storeRef.current = new Store(typeof initialState === "function" ? initialState() : initialState); | ||
storeRef.current = new Store(initialState); | ||
} | ||
} | ||
return storeRef.current; | ||
}produce.enablePatches(); | ||
}const globalClientState = { | ||
storeOrdinal: 0, | ||
batching: false, | ||
flushStores: {} | ||
};produce.enablePatches(); | ||
function makeSubscriptionFunction(store, watch, listener) { | ||
@@ -146,4 +150,14 @@ let lastWatchState = watch(store.getRawState()); | ||
this._patchListeners = []; | ||
this.currentState = initialState; | ||
this.initialState = initialState; | ||
if (initialState instanceof Function) { | ||
const state = initialState(); | ||
this.currentState = state; | ||
this.initialState = state; | ||
this.createInitialState = initialState; | ||
} | ||
else { | ||
this.currentState = initialState; | ||
this.initialState = initialState; | ||
this.createInitialState = () => initialState; | ||
} | ||
this.internalOrdId = globalClientState.storeOrdinal++; | ||
} | ||
@@ -162,3 +176,3 @@ _setInternalOptions({ ssr, reactionCreators = [] }) { | ||
_getInitialState() { | ||
return this.initialState; | ||
return this.createInitialState(); | ||
} | ||
@@ -270,3 +284,3 @@ _updateStateWithoutReaction(nextState) { | ||
useLocalCopyInitial(deps) { | ||
return useLocalStore(() => this.initialState, deps); | ||
return useLocalStore(this.createInitialState, deps); | ||
} | ||
@@ -276,4 +290,33 @@ useLocalCopySnapshot(deps) { | ||
} | ||
flushBatch(ignoreError = false) { | ||
if (this.batchState !== undefined) { | ||
if (this.batchState !== this.currentState) { | ||
this._updateState(this.batchState); | ||
} | ||
} | ||
else if (!ignoreError) { | ||
console.error(`Pullstate: Trying to flush batch state which was never created or updated on`); | ||
} | ||
this.batchState = undefined; | ||
} | ||
update(updater, patchesCallback) { | ||
update(this, updater, patchesCallback); | ||
if (globalClientState.batching) { | ||
if (this.batchState === undefined) { | ||
this.batchState = this.currentState; | ||
globalClientState.flushStores[this.internalOrdId] = this; | ||
} | ||
const func = typeof updater === "function"; | ||
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func); | ||
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) { | ||
if (patchesCallback) { | ||
patchesCallback(patches, inversePatches); | ||
} | ||
this._patchListeners.forEach((listener) => listener(patches, inversePatches)); | ||
} | ||
this.batchState = nextState; | ||
} | ||
else { | ||
this.batchState = undefined; | ||
update(this, updater, patchesCallback); | ||
} | ||
} | ||
@@ -507,9 +550,12 @@ replace(newState) { | ||
} | ||
function getCachedResult(key, cache, args, stores, context, postActionEnabled, cacheBreakEnabled, fromListener) { | ||
function getCachedResult({ args, cache, cacheBreakEnabled, context, fromListener, key, postActionEnabled, stores, customCacheBreak }) { | ||
const useCacheBreakHook = customCacheBreak !== null && customCacheBreak !== void 0 ? customCacheBreak : cacheBreakHook; | ||
if (cache.results.hasOwnProperty(key)) { | ||
const cacheBreakLoop = cacheBreakWatcher.hasOwnProperty(key) && cacheBreakWatcher[key] > 2; | ||
if (cache.results[key][1] && | ||
if (!onServer && | ||
!fromListener && | ||
cacheBreakEnabled && | ||
cacheBreakHook !== undefined && | ||
cacheBreakHook({ | ||
useCacheBreakHook != null | ||
&& cache.results[key][1] && | ||
useCacheBreakHook({ | ||
args, | ||
@@ -527,3 +573,5 @@ result: cache.results[key][2], | ||
} | ||
const previous = cache.results[key]; | ||
delete cache.results[key]; | ||
return { cacheBroke: true, response: undefined, previous }; | ||
} | ||
@@ -543,6 +591,10 @@ else { | ||
} | ||
return cache.results[key]; | ||
return { | ||
response: cache.results[key], | ||
cacheBroke: false, | ||
previous: undefined | ||
}; | ||
} | ||
} | ||
return undefined; | ||
return { cacheBroke: false, response: undefined, previous: undefined }; | ||
} | ||
@@ -587,6 +639,16 @@ function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, executionContext, customContext) { | ||
} | ||
function checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult, customContext) { | ||
const cached = getCachedResult(key, cache, args, stores, initiate ? exports.EPostActionContext.BECKON_HIT_CACHE : exports.EPostActionContext.WATCH_HIT_CACHE, postActionEnabled, cacheBreakEnabled, fromListener); | ||
if (cached) { | ||
return cached; | ||
function checkKeyAndReturnResponse({ key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult, customContext, customCacheBreak, holdPrevious }) { | ||
const cached = getCachedResult({ | ||
key, | ||
cache, | ||
args, | ||
stores, | ||
context: initiate ? exports.EPostActionContext.BECKON_HIT_CACHE : exports.EPostActionContext.WATCH_HIT_CACHE, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
fromListener, | ||
customCacheBreak | ||
}); | ||
if (cached.response) { | ||
return cached.response; | ||
} | ||
@@ -632,6 +694,13 @@ if (!cache.actions.hasOwnProperty(key)) { | ||
} | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
if (holdPrevious) { | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
} | ||
if (cached.previous != null) { | ||
const response = [...cached.previous]; | ||
response[3] = true; | ||
return response; | ||
} | ||
} | ||
@@ -641,6 +710,13 @@ return resp; | ||
} | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
if (holdPrevious) { | ||
if (holdingResult) { | ||
const response = [...holdingResult]; | ||
response[3] = true; | ||
return response; | ||
} | ||
if (cached.previous != null) { | ||
const response = [...cached.previous]; | ||
response[3] = true; | ||
return response; | ||
} | ||
} | ||
@@ -665,9 +741,18 @@ return startedButUnfinishedResult; | ||
} | ||
const cached = getCachedResult(key, cache, args, stores, exports.EPostActionContext.READ_HIT_CACHE, postActionEnabled, cacheBreakEnabled, false); | ||
if (cached) { | ||
if (!cached[2].error) { | ||
return cached[2].payload; | ||
const cached = getCachedResult({ | ||
key, | ||
cache, | ||
args, | ||
stores, | ||
context: exports.EPostActionContext.READ_HIT_CACHE, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
fromListener: false | ||
}); | ||
if (cached.response) { | ||
if (!cached.response[2].error) { | ||
return cached.response[2].payload; | ||
} | ||
else { | ||
throw new PullstateAsyncError(cached[2].message, cached[2].tags); | ||
throw new PullstateAsyncError(cached.response[2].message, cached.response[2].tags); | ||
} | ||
@@ -707,3 +792,3 @@ } | ||
}; | ||
const useWatch = (args = {}, { initiate = false, ssr = true, postActionEnabled = false, cacheBreakEnabled = false, holdPrevious = false, dormant = false, key: customKey } = {}) => { | ||
const useWatch = (args = {}, { initiate = false, ssr = true, postActionEnabled = false, cacheBreakEnabled = false, holdPrevious = false, dormant = false, key: customKey, cacheBreak: customCacheBreak } = {}) => { | ||
const responseRef = React.useRef(); | ||
@@ -743,3 +828,16 @@ const prevKeyRef = React.useRef("."); | ||
if (shouldUpdate[key][watchId.current] && !isEqual__default['default'](responseRef.current, cache.results[key])) { | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled, undefined, customContext); | ||
responseRef.current = checkKeyAndReturnResponse({ | ||
key, | ||
cache, | ||
initiate, | ||
ssr, | ||
args, | ||
stores, | ||
fromListener: true, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdingResult: undefined, | ||
customContext, | ||
holdPrevious | ||
}); | ||
setWatchUpdate((prev) => { | ||
@@ -795,3 +893,17 @@ return prev + 1; | ||
prevKeyRef.current = key; | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, false, postActionEnabled, cacheBreakEnabled, holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, customContext); | ||
responseRef.current = checkKeyAndReturnResponse({ | ||
key, | ||
cache, | ||
initiate, | ||
ssr, | ||
args, | ||
stores, | ||
fromListener: false, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdingResult: holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, | ||
customContext, | ||
customCacheBreak: typeof customCacheBreak === "boolean" ? () => customCacheBreak : customCacheBreak, | ||
holdPrevious | ||
}); | ||
} | ||
@@ -815,5 +927,14 @@ return responseRef.current; | ||
if (respectCache) { | ||
const cached = getCachedResult(key, _asyncCache, args, _stores, exports.EPostActionContext.RUN_HIT_CACHE, true, true, false); | ||
if (cached) { | ||
if (!cached[1]) { | ||
const cached = getCachedResult({ | ||
key, | ||
cache: _asyncCache, | ||
args, | ||
stores: _stores, | ||
context: exports.EPostActionContext.RUN_HIT_CACHE, | ||
postActionEnabled: true, | ||
cacheBreakEnabled: true, | ||
fromListener: false | ||
}); | ||
if (cached.response) { | ||
if (!cached.response[1]) { | ||
const watchOrd = watchIdOrd++; | ||
@@ -833,3 +954,3 @@ if (!_asyncCache.listeners.hasOwnProperty(key)) { | ||
} | ||
return cached[2]; | ||
return cached.response[2]; | ||
} | ||
@@ -1011,3 +1132,3 @@ } | ||
}; | ||
const use = (args = {}, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, onSuccess } = {}) => { | ||
const use = (args = {}, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, onSuccess, cacheBreak: customCacheBreakHook } = {}) => { | ||
if (postActionEnabled == null) { | ||
@@ -1019,3 +1140,12 @@ postActionEnabled = initiate; | ||
} | ||
const raw = useWatch(args, { initiate, ssr, postActionEnabled, cacheBreakEnabled, holdPrevious, dormant, key }); | ||
const raw = useWatch(args, { | ||
initiate, | ||
ssr, | ||
postActionEnabled, | ||
cacheBreakEnabled, | ||
holdPrevious, | ||
dormant, | ||
key, | ||
cacheBreak: customCacheBreakHook | ||
}); | ||
const [isStarted, isFinished, result, isUpdating] = raw; | ||
@@ -1243,3 +1373,3 @@ const isSuccess = isFinished && !result.error; | ||
if (snapshot.allState.hasOwnProperty(storeName)) { | ||
this._stores[storeName]._updateState(snapshot.allState[storeName]); | ||
this._stores[storeName]._updateStateWithoutReaction(snapshot.allState[storeName]); | ||
} | ||
@@ -1301,2 +1431,27 @@ else { | ||
} | ||
}exports.InjectAsyncAction=InjectAsyncAction;exports.InjectStoreState=InjectStoreState;exports.InjectStoreStateOpt=InjectStoreStateOpt;exports.PullstateContext=PullstateContext;exports.PullstateProvider=PullstateProvider;exports.Store=Store;exports.createAsyncAction=createAsyncAction;exports.createAsyncActionDirect=createAsyncActionDirect;exports.createPullstateCore=createPullstateCore;exports.errorResult=errorResult;exports.registerInDevtools=registerInDevtools;exports.successResult=successResult;exports.update=update;exports.useInstance=useInstance;exports.useLocalStore=useLocalStore;exports.useStoreState=useStoreState;exports.useStoreStateOpt=useStoreStateOpt;exports.useStores=useStores; | ||
}const batchState = {}; | ||
function setupBatch({ uiBatchFunction }) { | ||
batchState.uiBatchFunction = uiBatchFunction; | ||
} | ||
function batch(runUpdates) { | ||
if (globalClientState.batching) { | ||
throw new Error("Pullstate: Can't enact two batch() update functions at the same time-\n" + | ||
"make sure you are not running a batch() inside of a batch() by mistake."); | ||
} | ||
globalClientState.batching = true; | ||
try { | ||
runUpdates(); | ||
} | ||
finally { | ||
if (batchState.uiBatchFunction) { | ||
batchState.uiBatchFunction(() => { | ||
Object.values(globalClientState.flushStores).forEach(store => store.flushBatch(true)); | ||
}); | ||
} | ||
else { | ||
Object.values(globalClientState.flushStores).forEach(store => store.flushBatch(true)); | ||
} | ||
globalClientState.flushStores = {}; | ||
globalClientState.batching = false; | ||
} | ||
}exports.InjectAsyncAction=InjectAsyncAction;exports.InjectStoreState=InjectStoreState;exports.InjectStoreStateOpt=InjectStoreStateOpt;exports.PullstateContext=PullstateContext;exports.PullstateProvider=PullstateProvider;exports.Store=Store;exports.batch=batch;exports.createAsyncAction=createAsyncAction;exports.createAsyncActionDirect=createAsyncActionDirect;exports.createPullstateCore=createPullstateCore;exports.errorResult=errorResult;exports.registerInDevtools=registerInDevtools;exports.setupBatch=setupBatch;exports.successResult=successResult;exports.update=update;exports.useInstance=useInstance;exports.useLocalStore=useLocalStore;exports.useStoreState=useStoreState;exports.useStoreStateOpt=useStoreStateOpt;exports.useStores=useStores; |
import React from "react"; | ||
import { IAsyncActionBeckonOptions, IAsyncActionWatchOptions, IOCreateAsyncActionOutput, TPullstateAsyncBeckonResponse, TPullstateAsyncWatchResponse } from "./async-types"; | ||
import { IPullstateAllStores } from "./PullstateCore"; | ||
export declare enum EAsyncActionInjectType { | ||
@@ -11,11 +12,11 @@ WATCH = "watch", | ||
} | ||
export interface IPropsInjectAsyncActionBeckon<A = any, R = any, T extends string = string, N = any> extends IPropsInjectAsyncActionBase<A, R, T, N> { | ||
export interface IPropsInjectAsyncActionBeckon<A = any, R = any, T extends string = string, N = any, S extends IPullstateAllStores = IPullstateAllStores> extends IPropsInjectAsyncActionBase<A, R, T, N> { | ||
type: EAsyncActionInjectType.BECKON; | ||
options?: IAsyncActionBeckonOptions; | ||
options?: IAsyncActionBeckonOptions<A, R, T, N, S>; | ||
children: (response: TPullstateAsyncBeckonResponse<R, T>) => React.ReactElement; | ||
} | ||
export interface IPropsInjectAsyncActionWatch<A = any, R = any, T extends string = string, N = any> extends IPropsInjectAsyncActionBase<A, R, T, N> { | ||
export interface IPropsInjectAsyncActionWatch<A = any, R = any, T extends string = string, N = any, S extends IPullstateAllStores = IPullstateAllStores> extends IPropsInjectAsyncActionBase<A, R, T, N> { | ||
type: EAsyncActionInjectType.WATCH; | ||
children: (response: TPullstateAsyncWatchResponse<R, T, N>) => React.ReactElement; | ||
options?: IAsyncActionWatchOptions; | ||
options?: IAsyncActionWatchOptions<A, R, T, N, S>; | ||
} | ||
@@ -22,0 +23,0 @@ export declare type TInjectAsyncActionProps = IPropsInjectAsyncActionBeckon | IPropsInjectAsyncActionWatch; |
@@ -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),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 m(t,e=!0,s=!0){e&&S.actionOrd.hasOwnProperty(t)&&(S.actionOrd[t]+=1),delete S.results[t],s&&O(t)}function w(t,e){return t.actionOrd.hasOwnProperty(e)?t.actionOrd[e]+=1:t.actionOrd[e]=0,t.actionOrd[e]}function k(t=null,e=[],s=""){return{payload:t,tags:e,message:s,error:!1,errorPayload:null}}class b 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 v(t,e={}){return U((async(e,s,r)=>k(await t(e,s,r))),e)}function U(s,{forceContext:r=!1,shortCircuitHook:i,cacheBreakHook:c,postActionHook:u,subsetKey:l,actionId:d}={}){const h=null!=d?"_"+d:R++,f="undefined"==typeof window;function p(t,e){return null!=e?`${h}-c-${e}`:void 0!==l?`${h}-${P(l(t))}`:`${h}-${P(t)}`}let y={},C=0;const _={};function g(t,e,s,r){void 0!==u&&u({args:e,result:t,stores:s,context:r})}function E(t,e,s,r,n,o,a,i){if(e.results.hasOwnProperty(t)){const u=y.hasOwnProperty(t)&&y[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.`):y[t]=0,o&&e.results[t][1]&&!i&&g(e.results[t][2],s,r,n),e.results[t];y.hasOwnProperty(t)?y[t]++:y[t]=1,delete e.results[t]}}function v(e,r,n,o,a,i,c,u){return()=>s(n,o,u).then((t=>(a===r.actionOrd[e]&&(i&&g(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&&g(u,n,o,c),r.results[e]=[!0,!0,u,!1,Date.now()]),u})).then((t=>(a===r.actionOrd[e]&&(delete r.actions[e],f||O(e)),t)))}function U(e,s,r,n,o,a,c=!1,u=!0,l=!0,d,h){const p=E(e,s,o,a,r?t.EPostActionContext.BECKON_HIT_CACHE:t.EPostActionContext.WATCH_HIT_CACHE,u,l,c);if(p)return p;if(!s.actions.hasOwnProperty(e)){const c=w(s,e);if(!r){const r=[!1,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];if(f||(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 g(r,o,a,t.EPostActionContext.SHORT_CIRCUIT),s.results[e]=[!0,!0,r,!1,Date.now()],s.results[e]}if(!n&&f||(s.actions[e]=v(e,s,o,a,c,u,t.EPostActionContext.BECKON_RUN,h)),f)return T;s.actions[e](),s.results[e]=T}if(d){const t=[...d];return t[3]=!0,t}return T}const H=(s={},{initiate:n=!1,ssr:o=!0,postActionEnabled:i=!1,cacheBreakEnabled:c=!1,holdPrevious:u=!1,dormant:l=!1,key:d}={})=>{const h=e.useRef(),y=e.useRef("."),g=l?".":p(s,d);let E=e.useRef(-1);-1===E.current&&(E.current=C++),l||(_.hasOwnProperty(g)?_[g][E.current]=!0:_[g]={[E.current]:!0});const R=f?e.useContext(I)._asyncCache:S;let P,O;if(f||r){const t=e.useContext(I);P=t.stores,O=t.customContext}else P=L.loaded?L.stores:A;if(!f){const t=()=>{_[g][E.current]&&!a(h.current,R.results[g])&&(h.current=U(g,R,n,o,s,P,!0,i,c,void 0,O),w((t=>t+1)))};l||(R.listeners.hasOwnProperty(g)||(R.listeners[g]={}),R.listeners[g][E.current]=t,_[g][E.current]=!0),e.useEffect((()=>(l||(R.listeners[g][E.current]=t,_[g][E.current]=!0),()=>{l||(delete R.listeners[g][E.current],_[g][E.current]=!1)})),[g])}const[m,w]=e.useState(0);return l?(h.current=u&&h.current&&h.current[1]?h.current:[!1,!1,{message:"",tags:[t.EAsyncEndTags.DORMANT],error:!0,payload:null},!1,-1],y.current="."):y.current!==g&&(null!==y.current&&_.hasOwnProperty(y.current)&&(delete R.listeners[y.current][E.current],_[y.current][E.current]=!1),y.current=g,h.current=U(g,R,n,o,s,P,!1,i,c,u&&h.current&&h.current[1]?h.current:void 0,O)),h.current},x=async(e={},{treatAsUpdate:s=!1,ignoreShortCircuit:r=!1,respectCache:n=!1,key:o,_asyncCache:a=S,_stores:c=(L.loaded?L.stores:A),_customContext:u}={})=>{const l=p(e,o);if(n){const s=E(l,a,e,c,t.EPostActionContext.RUN_HIT_CACHE,!0,!0,!1);if(s){if(!s[1]){const t=C++;return a.listeners.hasOwnProperty(l)||(a.listeners[l]={}),new Promise((e=>{a.listeners[l][t]=()=>{const[,s,r]=a.results[l];s&&(delete a.listeners[l][t],e(r))}}))}return s[2]}}if(!r&&void 0!==i){const s=i({args:e,stores:c});if(!1!==s)return a.results[l]=[!0,!0,s,!1,Date.now()],g(s,e,c,t.EPostActionContext.SHORT_CIRCUIT),O(l),s}const[,d,h,f,y]=a.results[l]||[!1,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];a.results[l]=d&&s?[!0,!0,h,!0,y]:[!0,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];let _=w(a,l);return a.actions[l]=v(l,a,e,c,_,!0,t.EPostActionContext.DIRECT_RUN,u),O(l),a.actions[l]()},N=(t={},{key:e,notify:s=!0}={})=>{m(p(t,e),!0,s)},D=(t,s,r)=>{const{notify:n=!0,key:o}=r||{},a=p(t,o);(f?e.useContext(I)._asyncCache:S).results[a]=[!0,!0,s,!1,Date.now()],n&&O(a)},j=(t,e,s)=>D(t,k(e),s),B=(s,r,n)=>{const{notify:a=!0,resetTimeCached:i=!0,runPostActionHook:c=!1,key:u}=n||{},l=p(s,u),d=f?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&&g(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)}},z=(s={},r)=>{const{checkCacheBreak:n=!1,key:o}=r||{},a=p(s,o);let i=!1;const u=f?e.useContext(I)._asyncCache:S;if(u.results.hasOwnProperty(a)){if(n&&void 0!==c){const t=f?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 W;const M=(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=H(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=>x(t,e),clearCached:()=>N(t),setCached:(e,s)=>{D(t,e,s)},setCachedPayload:(e,s)=>{j(t,e,s)},updateCached:(e,s)=>{B(t,e,s)}}};return{use:M,useDefer:(t={})=>{const[s,r]=e.useState((()=>({key:t.key?t.key:p({}),args:{}})));return{...M({},{...t,key:s.key,initiate:!1}),clearCached:()=>{N({},{key:s.key})},setCached:(t,e={})=>{e.key=s.key,D({},t,e)},setCachedPayload:(t,e={})=>{e.key=s.key,j({},t,e)},updateCached:(t,e={})=>{e.key=s.key,B({},t,e)},execute:(e={},n)=>{var o;const a=null!==(o=t.key)&&void 0!==o?o:p(e);return a!==s.key&&r({key:a,args:e}),x(e,{...n,key:a}).then((e=>(t.clearOnSuccess&&N({},{key:a}),e)))},args:s.args,key:s.key}},read:(s={},{cacheBreakEnabled:n=!0,postActionEnabled:o=!0,key:a}={})=>{const c=p(s,a),u=f?e.useContext(I)._asyncCache:S;let l,d;if(f||r){const t=e.useContext(I);l=t.stores,d=t.customContext}else l=L.loaded?L.stores:A;const h=E(c,u,s,l,t.EPostActionContext.READ_HIT_CACHE,o,n,!1);if(h){if(h[2].error)throw new b(h[2].message,h[2].tags);return h[2].payload}if(!u.actions.hasOwnProperty(c)){if(void 0!==i){const e=i({args:s,stores:l});if(!1!==e){if(g(e,s,l,t.EPostActionContext.SHORT_CIRCUIT),u.results[c]=[!0,!0,e,!1,Date.now()],e.error)throw new b(e.message,e.tags);return e.payload}}const e=w(u,c);if(u.actions[c]=v(c,u,s,l,e,o,t.EPostActionContext.READ_RUN,d),f)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(f)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 y=C++;throw new Promise((t=>{u.listeners[c][y]=()=>{delete u.listeners[c][y],t()}}))},useBeckon:(t={},{ssr:e=!0,postActionEnabled:s=!0,cacheBreakEnabled:r=!0,holdPrevious:n=!1,dormant:o=!1,key:a}={})=>{const i=H(t,{initiate:!0,ssr:e,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o,key:a});return[i[1],i[2],i[3]]},useWatch:H,run:x,delayedRun:(t={},{clearOldRun:e=!0,delay:s,immediateIfCached:r=!0,...n})=>{if(e&&clearTimeout(W),r){const{finished:e,cacheBreakable:s}=z(t,{checkCacheBreak:!0});if(e&&!s)return x(t,n),()=>{}}let o={cancelled:!1};return W=setTimeout((()=>{o.cancelled||x(t,n)}),s),()=>{o.cancelled=!0}},clearCache:N,clearAllCache:({notify:t=!0}={})=>{for(const e of Object.keys(S.actionOrd))e.startsWith(h+"-")&&m(e,!0,t)},clearAllUnwatchedCache:({notify:t=!0}={})=>{for(const e of Object.keys(_))Object.values(_[e]).some((t=>t))||(delete _[e],m(e,!1,t))},getCached:z,setCached:D,setCachedPayload:j,updateCached:B}}const I=n.default.createContext(null);let H=null;const L={internalClientStores:!0,loaded:!1,stores:{}};class x{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,customContext:s}={}){if(!e){const e=new N(L.stores,!1,s);return null!=t&&e.hydrateFromSnapshot(t),e.instantiateReactions(),e}const r={};for(const s of Object.keys(L.stores))null==t?r[s]=new p(L.stores[s]._getInitialState()):t.hasOwnProperty(s)?r[s]=new p(t.allState[s]):(r[s]=new p(L.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:e,reactionCreators:L.stores[s]._getReactionCreators()});return new N(r,!0,s)}useStores(){return D()}useInstance(){return j()}createAsyncActionDirect(t,e={}){return v(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),U(t,e)}}class N{constructor(t,e,s){this._ssr=!1,this._stores={},this._asyncCache={listeners:{},results:{},actions:{},actionOrd:{}},this._stores=t,this._ssr=e,this._customContext=s}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}get customContext(){return this._customContext}async runAsyncAction(t,e={},s={}){return this._ssr&&(s._asyncCache=this._asyncCache,s._stores=this._stores,s._customContext=this._customContext),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=U,t.createAsyncActionDirect=v,t.createPullstateCore=function(t={},e={}){return new x(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=k,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 h(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 d(t,s){const r=e.useRef();if(null==r.current&&(r.current=new y(t)),void 0!==s){const n=e.useRef(s);a(s,n)||(r.current=new y(t))}return r.current}const f={storeOrdinal:0,batching:!1,flushStores:{}};s.enablePatches();const p="~._.~";class y{constructor(t){if(this.updateListeners=[],this.ssr=!1,this.reactions=[],this.clientSubscriptions=[],this.reactionCreators=[],this.optimizedUpdateListeners={},this.optimizedUpdateListenerPaths={},this.optimizedListenerPropertyMap={},this._optListenerCount=0,this._patchListeners=[],t instanceof Function){const e=t();this.currentState=e,this.initialState=e,this.createInitialState=t}else this.currentState=t,this.initialState=t,this.createInitialState=()=>t;this.internalOrdId=f.storeOrdinal++}_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.createInitialState()}_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(p)));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(C(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 d(this.createInitialState,t)}useLocalCopySnapshot(t){return d(this.currentState,t)}flushBatch(t=!1){void 0!==this.batchState?this.batchState!==this.currentState&&this._updateState(this.batchState):t||console.error("Pullstate: Trying to flush batch state which was never created or updated on"),this.batchState=void 0}update(t,e){if(f.batching){void 0===this.batchState&&(this.batchState=this.currentState,f.flushStores[this.internalOrdId]=this);const s="function"==typeof t,[r,n,o]=g(this.batchState,t,s);n.length>0&&(this._patchListeners.length>0||e)&&(e&&e(n,o),this._patchListeners.forEach((t=>t(n,o)))),this.batchState=r}else this.batchState=void 0,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(C(e)))}(this,t)}}function C(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 g(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 E(t,e,r){const n=t.getRawState(),o="function"==typeof e;if(t._optListenerCount>0){const[s,a,i]=g(n,e,o);a.length>0&&(r&&r(a,i),t._patchListeners.forEach((t=>t(a,i))),t._updateState(s,Object.keys(C(a))))}else{let a;if(t._patchListeners.length>0||r){const[s,i,c]=g(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 S,_;(S=t.EAsyncEndTags||(t.EAsyncEndTags={})).THREW_ERROR="THREW_ERROR",S.RETURNED_ERROR="RETURNED_ERROR",S.UNFINISHED="UNFINISHED",S.DORMANT="DORMANT",(_=t.EPostActionContext||(t.EPostActionContext={})).WATCH_HIT_CACHE="WATCH_HIT_CACHE",_.BECKON_HIT_CACHE="BECKON_HIT_CACHE",_.RUN_HIT_CACHE="RUN_HIT_CACHE",_.READ_HIT_CACHE="READ_HIT_CACHE",_.READ_RUN="READ_RUN",_.SHORT_CIRCUIT="SHORT_CIRCUIT",_.DIRECT_RUN="DIRECT_RUN",_.BECKON_RUN="BECKON_RUN",_.CACHE_UPDATE="CACHE_UPDATE";const A={listeners:{},results:{},actions:{},actionOrd:{}};let b,k=0;function R(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+R(t[e]);return s+"}"}function m(t){if(A.listeners.hasOwnProperty(t))for(const e of Object.keys(A.listeners[t]))A.listeners[t][e]()}function P(t,e=!0,s=!0){e&&A.actionOrd.hasOwnProperty(t)&&(A.actionOrd[t]+=1),delete A.results[t],s&&m(t)}function O(t,e){return t.actionOrd.hasOwnProperty(e)?t.actionOrd[e]+=1:t.actionOrd[e]=0,t.actionOrd[e]}function w(t=null,e=[],s=""){return{payload:t,tags:e,message:s,error:!1,errorPayload:null}}class v extends Error{constructor(t,e){super(t),this.tags=e}}try{b=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{b={}}const I=[!0,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];function T(t,e={}){return U((async(e,s,r)=>w(await t(e,s,r))),e)}function U(s,{forceContext:r=!1,shortCircuitHook:i,cacheBreakHook:c,postActionHook:u,subsetKey:l,actionId:h}={}){const d=null!=h?"_"+h:k++,f="undefined"==typeof window;function p(t,e){return null!=e?`${d}-c-${e}`:void 0!==l?`${d}-${R(l(t))}`:`${d}-${R(t)}`}let y={},C=0;const g={};function E(t,e,s,r){void 0!==u&&u({args:e,result:t,stores:s,context:r})}function S({args:t,cache:e,cacheBreakEnabled:s,context:r,fromListener:n,key:o,postActionEnabled:a,stores:i,customCacheBreak:u}){const l=null!=u?u:c;if(e.results.hasOwnProperty(o)){const c=y.hasOwnProperty(o)&&y[o]>2;if(!f&&!n&&s&&null!=l&&e.results[o][1]&&l({args:t,result:e.results[o][2],stores:i,timeCached:e.results[o][4]})&&!c){y.hasOwnProperty(o)?y[o]++:y[o]=1;const t=e.results[o];return delete e.results[o],{cacheBroke:!0,response:void 0,previous:t}}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.`):y[o]=0,a&&e.results[o][1]&&!n&&E(e.results[o][2],t,i,r),{response:e.results[o],cacheBroke:!1,previous:void 0}}return{cacheBroke:!1,response:void 0,previous:void 0}}function _(e,r,n,o,a,i,c,u){return()=>s(n,o,u).then((t=>(a===r.actionOrd[e]&&(i&&E(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&&E(u,n,o,c),r.results[e]=[!0,!0,u,!1,Date.now()]),u})).then((t=>(a===r.actionOrd[e]&&(delete r.actions[e],f||m(e)),t)))}function T({key:e,cache:s,initiate:r,ssr:n,args:o,stores:a,fromListener:c=!1,postActionEnabled:u=!0,cacheBreakEnabled:l=!0,holdingResult:h,customContext:d,customCacheBreak:p,holdPrevious:y}){const C=S({key:e,cache:s,args:o,stores:a,context:r?t.EPostActionContext.BECKON_HIT_CACHE:t.EPostActionContext.WATCH_HIT_CACHE,postActionEnabled:u,cacheBreakEnabled:l,fromListener:c,customCacheBreak:p});if(C.response)return C.response;if(!s.actions.hasOwnProperty(e)){const c=O(s,e);if(!r){const r=[!1,!1,{message:"",tags:[t.EAsyncEndTags.UNFINISHED],error:!0,payload:null,errorPayload:null},!1,-1];if(f||(s.results[e]=r),y){if(h){const t=[...h];return t[3]=!0,t}if(null!=C.previous){const t=[...C.previous];return t[3]=!0,t}}return r}if(void 0!==i){const r=i({args:o,stores:a});if(!1!==r)return E(r,o,a,t.EPostActionContext.SHORT_CIRCUIT),s.results[e]=[!0,!0,r,!1,Date.now()],s.results[e]}if(!n&&f||(s.actions[e]=_(e,s,o,a,c,u,t.EPostActionContext.BECKON_RUN,d)),f)return I;s.actions[e](),s.results[e]=I}if(y){if(h){const t=[...h];return t[3]=!0,t}if(null!=C.previous){const t=[...C.previous];return t[3]=!0,t}}return I}const U=(s={},{initiate:n=!1,ssr:o=!0,postActionEnabled:i=!1,cacheBreakEnabled:c=!1,holdPrevious:u=!1,dormant:l=!1,key:h,cacheBreak:d}={})=>{const y=e.useRef(),E=e.useRef("."),S=l?".":p(s,h);let _=e.useRef(-1);-1===_.current&&(_.current=C++),l||(g.hasOwnProperty(S)?g[S][_.current]=!0:g[S]={[_.current]:!0});const k=f?e.useContext(L)._asyncCache:A;let R,m;if(f||r){const t=e.useContext(L);R=t.stores,m=t.customContext}else R=H.loaded?H.stores:b;if(!f){const t=()=>{g[S][_.current]&&!a(y.current,k.results[S])&&(y.current=T({key:S,cache:k,initiate:n,ssr:o,args:s,stores:R,fromListener:!0,postActionEnabled:i,cacheBreakEnabled:c,holdingResult:void 0,customContext:m,holdPrevious:u}),O((t=>t+1)))};l||(k.listeners.hasOwnProperty(S)||(k.listeners[S]={}),k.listeners[S][_.current]=t,g[S][_.current]=!0),e.useEffect((()=>(l||(k.listeners[S][_.current]=t,g[S][_.current]=!0),()=>{l||(delete k.listeners[S][_.current],g[S][_.current]=!1)})),[S])}const[P,O]=e.useState(0);return l?(y.current=u&&y.current&&y.current[1]?y.current:[!1,!1,{message:"",tags:[t.EAsyncEndTags.DORMANT],error:!0,payload:null},!1,-1],E.current="."):E.current!==S&&(null!==E.current&&g.hasOwnProperty(E.current)&&(delete k.listeners[E.current][_.current],g[E.current][_.current]=!1),E.current=S,y.current=T({key:S,cache:k,initiate:n,ssr:o,args:s,stores:R,fromListener:!1,postActionEnabled:i,cacheBreakEnabled:c,holdingResult:u&&y.current&&y.current[1]?y.current:void 0,customContext:m,customCacheBreak:"boolean"==typeof d?()=>d:d,holdPrevious:u})),y.current},x=async(e={},{treatAsUpdate:s=!1,ignoreShortCircuit:r=!1,respectCache:n=!1,key:o,_asyncCache:a=A,_stores:c=(H.loaded?H.stores:b),_customContext:u}={})=>{const l=p(e,o);if(n){const s=S({key:l,cache:a,args:e,stores:c,context:t.EPostActionContext.RUN_HIT_CACHE,postActionEnabled:!0,cacheBreakEnabled:!0,fromListener:!1});if(s.response){if(!s.response[1]){const t=C++;return a.listeners.hasOwnProperty(l)||(a.listeners[l]={}),new Promise((e=>{a.listeners[l][t]=()=>{const[,s,r]=a.results[l];s&&(delete a.listeners[l][t],e(r))}}))}return s.response[2]}}if(!r&&void 0!==i){const s=i({args:e,stores:c});if(!1!==s)return a.results[l]=[!0,!0,s,!1,Date.now()],E(s,e,c,t.EPostActionContext.SHORT_CIRCUIT),m(l),s}const[,h,d,f,y]=a.results[l]||[!1,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];a.results[l]=h&&s?[!0,!0,d,!0,y]:[!0,!1,{error:!0,message:"",payload:null,tags:[t.EAsyncEndTags.UNFINISHED]},!1,-1];let g=O(a,l);return a.actions[l]=_(l,a,e,c,g,!0,t.EPostActionContext.DIRECT_RUN,u),m(l),a.actions[l]()},B=(t={},{key:e,notify:s=!0}={})=>{P(p(t,e),!0,s)},N=(t,s,r)=>{const{notify:n=!0,key:o}=r||{},a=p(t,o);(f?e.useContext(L)._asyncCache:A).results[a]=[!0,!0,s,!1,Date.now()],n&&m(a)},D=(t,e,s)=>N(t,w(e),s),j=(s,r,n)=>{const{notify:a=!0,resetTimeCached:i=!0,runPostActionHook:c=!1,key:u}=n||{},l=p(s,u),h=f?e.useContext(L)._asyncCache:A;if(h.results.hasOwnProperty(l)&&!h.results[l][2].error){const e=h.results[l][2].payload,n={payload:o.default(e,(t=>r(t,e))),error:!1,message:h.results[l][2].message,tags:h.results[l][2].tags};c&&E(n,s,H.loaded?H.stores:b,t.EPostActionContext.CACHE_UPDATE),h.results[l]=[!0,!0,n,h.results[l][3],i?Date.now():h.results[l][4]],a&&m(l)}},z=(s={},r)=>{const{checkCacheBreak:n=!1,key:o}=r||{},a=p(s,o);let i=!1;const u=f?e.useContext(L)._asyncCache:A;if(u.results.hasOwnProperty(a)){if(n&&void 0!==c){const t=f?e.useContext(L).stores:H.loaded?H.stores:b;c({args:s,result:u.results[a][2],stores:t,timeCached:u.results[a][4]})&&(i=!0)}const[t,r,o,l,h]=u.results[a];return{started:t,finished:r,result:o,existed:!0,cacheBreakable:i,updating:l,timeCached:h}}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 W;const F=(t={},{initiate:s=!0,ssr:r=!0,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i=!1,dormant:c=!1,key:u,onSuccess:l,cacheBreak:h}={})=>{null==o&&(o=s),null==a&&(a=s);const d=U(t,{initiate:s,ssr:r,postActionEnabled:o,cacheBreakEnabled:a,holdPrevious:i,dormant:c,key:u,cacheBreak:h}),[f,p,y,C]=d,g=p&&!y.error,E=p&&y.error;l&&e.useEffect((()=>{g&&!c&&l(y.payload,t)}),[g]);return{isStarted:f,isFinished:p,isUpdating:C,isSuccess:g,isFailure:E,isLoading:f&&(!p||C),endTags:y.tags,error:y.error,payload:y.payload,errorPayload:y.errorPayload,renderPayload:t=>y.error?n.default.Fragment:t(y.payload),message:y.message,raw:d,execute:e=>x(t,e),clearCached:()=>B(t),setCached:(e,s)=>{N(t,e,s)},setCachedPayload:(e,s)=>{D(t,e,s)},updateCached:(e,s)=>{j(t,e,s)}}};return{use:F,useDefer:(t={})=>{const[s,r]=e.useState((()=>({key:t.key?t.key:p({}),args:{}})));return{...F({},{...t,key:s.key,initiate:!1}),clearCached:()=>{B({},{key:s.key})},setCached:(t,e={})=>{e.key=s.key,N({},t,e)},setCachedPayload:(t,e={})=>{e.key=s.key,D({},t,e)},updateCached:(t,e={})=>{e.key=s.key,j({},t,e)},execute:(e={},n)=>{var o;const a=null!==(o=t.key)&&void 0!==o?o:p(e);return a!==s.key&&r({key:a,args:e}),x(e,{...n,key:a}).then((e=>(t.clearOnSuccess&&B({},{key:a}),e)))},args:s.args,key:s.key}},read:(s={},{cacheBreakEnabled:n=!0,postActionEnabled:o=!0,key:a}={})=>{const c=p(s,a),u=f?e.useContext(L)._asyncCache:A;let l,h;if(f||r){const t=e.useContext(L);l=t.stores,h=t.customContext}else l=H.loaded?H.stores:b;const d=S({key:c,cache:u,args:s,stores:l,context:t.EPostActionContext.READ_HIT_CACHE,postActionEnabled:o,cacheBreakEnabled:n,fromListener:!1});if(d.response){if(d.response[2].error)throw new v(d.response[2].message,d.response[2].tags);return d.response[2].payload}if(!u.actions.hasOwnProperty(c)){if(void 0!==i){const e=i({args:s,stores:l});if(!1!==e){if(E(e,s,l,t.EPostActionContext.SHORT_CIRCUIT),u.results[c]=[!0,!0,e,!1,Date.now()],e.error)throw new v(e.message,e.tags);return e.payload}}const e=O(u,c);if(u.actions[c]=_(c,u,s,l,e,o,t.EPostActionContext.READ_RUN,h),f)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(f)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 y=C++;throw new Promise((t=>{u.listeners[c][y]=()=>{delete u.listeners[c][y],t()}}))},useBeckon:(t={},{ssr:e=!0,postActionEnabled:s=!0,cacheBreakEnabled:r=!0,holdPrevious:n=!1,dormant:o=!1,key:a}={})=>{const i=U(t,{initiate:!0,ssr:e,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o,key:a});return[i[1],i[2],i[3]]},useWatch:U,run:x,delayedRun:(t={},{clearOldRun:e=!0,delay:s,immediateIfCached:r=!0,...n})=>{if(e&&clearTimeout(W),r){const{finished:e,cacheBreakable:s}=z(t,{checkCacheBreak:!0});if(e&&!s)return x(t,n),()=>{}}let o={cancelled:!1};return W=setTimeout((()=>{o.cancelled||x(t,n)}),s),()=>{o.cancelled=!0}},clearCache:B,clearAllCache:({notify:t=!0}={})=>{for(const e of Object.keys(A.actionOrd))e.startsWith(d+"-")&&P(e,!0,t)},clearAllUnwatchedCache:({notify:t=!0}={})=>{for(const e of Object.keys(g))Object.values(g[e]).some((t=>t))||(delete g[e],P(e,!1,t))},getCached:z,setCached:N,setCachedPayload:D,updateCached:j}}const L=n.default.createContext(null);let x=null;const H={internalClientStores:!0,loaded:!1,stores:{}};class B{constructor(t,e={}){this.options={},null!==x&&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."),x=this,H.stores=t,H.loaded=!0,this.options=e}instantiate({hydrateSnapshot:t,ssr:e=!1,customContext:s}={}){if(!e){const e=new N(H.stores,!1,s);return null!=t&&e.hydrateFromSnapshot(t),e.instantiateReactions(),e}const r={};for(const s of Object.keys(H.stores))null==t?r[s]=new y(H.stores[s]._getInitialState()):t.hasOwnProperty(s)?r[s]=new y(t.allState[s]):(r[s]=new y(H.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:e,reactionCreators:H.stores[s]._getReactionCreators()});return new N(r,!0,s)}useStores(){return D()}useInstance(){return j()}createAsyncActionDirect(t,e={}){return T(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),U(t,e)}}class N{constructor(t,e,s){this._ssr=!1,this._stores={},this._asyncCache={listeners:{},results:{},actions:{},actionOrd:{}},this._stores=t,this._ssr=e,this._customContext=s}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}get customContext(){return this._customContext}async runAsyncAction(t,e={},s={}){return this._ssr&&(s._asyncCache=this._asyncCache,s._stores=this._stores,s._customContext=this._customContext),await t.run(e,s)}hydrateFromSnapshot(t){for(const e of Object.keys(this._stores))t.allState.hasOwnProperty(e)?this._stores[e]._updateStateWithoutReaction(t.allState[e]):console.warn(e+" didn't hydrate any state (data was non-existent on hydration object)");A.results=t.asyncResults||{},A.actionOrd=t.asyncActionOrd||{}}}function D(){return e.useContext(L).stores}function j(){return e.useContext(L)}var z;(z=t.EAsyncActionInjectType||(t.EAsyncActionInjectType={})).WATCH="watch",z.BECKON="beckon";const W={};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(h(t,e))},t.PullstateContext=L,t.PullstateProvider=({instance:t,children:e})=>n.default.createElement(L.Provider,{value:t},e),t.Store=y,t.batch=function(t){if(f.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.");f.batching=!0;try{t()}finally{W.uiBatchFunction?W.uiBatchFunction((()=>{Object.values(f.flushStores).forEach((t=>t.flushBatch(!0)))})):Object.values(f.flushStores).forEach((t=>t.flushBatch(!0))),f.flushStores={},f.batching=!1}},t.createAsyncAction=U,t.createAsyncActionDirect=T,t.createPullstateCore=function(t={},e={}){return new B(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.setupBatch=function({uiBatchFunction:t}){W.uiBatchFunction=t},t.successResult=w,t.update=E,t.useInstance=j,t.useLocalStore=d,t.useStoreState=i,t.useStoreStateOpt=h,t.useStores=D,Object.defineProperty(t,"__esModule",{value:!0})})); |
@@ -21,4 +21,6 @@ import { Draft, Patch, PatchListener } from "immer"; | ||
private currentState; | ||
private readonly initialState; | ||
private readonly createInitialState; | ||
private internalOrdId; | ||
private batchState; | ||
private readonly initialState; | ||
private ssr; | ||
@@ -33,3 +35,3 @@ private reactions; | ||
_patchListeners: PatchListener[]; | ||
constructor(initialState: S); | ||
constructor(initialState: S | (() => S)); | ||
_setInternalOptions({ ssr, reactionCreators }: IStoreInternalOptions<S>): void; | ||
@@ -53,2 +55,3 @@ _getReactionCreators(): TReactionCreator<S>[]; | ||
useLocalCopySnapshot(deps?: ReadonlyArray<any>): Store<S>; | ||
flushBatch(ignoreError?: boolean): void; | ||
update(updater: TUpdateFunction<S> | TUpdateFunction<S>[], patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void): void; | ||
@@ -55,0 +58,0 @@ replace(newState: S): void; |
{ | ||
"name": "pullstate", | ||
"version": "1.20.6", | ||
"version": "1.21.0", | ||
"description": "Simple state stores using immer and React hooks", | ||
@@ -79,5 +79,4 @@ "main": "dist/index.js", | ||
"peerDependencies": { | ||
"immer": "^8.0.1", | ||
"react": "^16.12.0" | ||
"react": "^16.12.0 || ^17.0.0" | ||
} | ||
} |
Sorry, the diff of this file is too big to display
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
258814
3
23
5059