Comparing version 1.20.4 to 1.20.5
@@ -100,2 +100,3 @@ import { IPullstateAllStores } from "./PullstateCore"; | ||
_stores?: S; | ||
_customContext?: any; | ||
} | ||
@@ -169,3 +170,3 @@ export interface IAsyncActionGetCachedOptions { | ||
} | ||
export declare type TPullstateAsyncAction<A, R, T extends string, N, S extends IPullstateAllStores> = (args: A, stores: S) => Promise<TAsyncActionResult<R, T, N>>; | ||
export declare type TPullstateAsyncAction<A, R, T extends string, N, S extends IPullstateAllStores> = (args: A, stores: S, customContext: any) => Promise<TAsyncActionResult<R, T, N>>; | ||
export interface ICreateAsyncActionOptions<A, R, T extends string, N, S extends IPullstateAllStores> { | ||
@@ -177,2 +178,3 @@ forceContext?: boolean; | ||
subsetKey?: (args: A) => any; | ||
actionId?: string | number; | ||
} | ||
@@ -179,0 +181,0 @@ export declare type TRunWithPayload<R> = (func: (payload: R) => any) => any; |
@@ -11,3 +11,3 @@ import { IPullstateAllStores } from "./PullstateCore"; | ||
} | ||
export declare function createAsyncActionDirect<A extends any = any, R extends any = any, N extends any = any, S extends IPullstateAllStores = IPullstateAllStores>(action: (args: A) => Promise<R>, options?: ICreateAsyncActionOptions<A, R, string, N, S>): IOCreateAsyncActionOutput<A, R, string, N>; | ||
export declare function createAsyncAction<A = any, R = any, T extends string = string, N extends any = any, S extends IPullstateAllStores = IPullstateAllStores>(action: TPullstateAsyncAction<A, R, T, N, S>, { forceContext, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey }?: ICreateAsyncActionOptions<A, R, T, N, S>): IOCreateAsyncActionOutput<A, R, T, N>; | ||
export declare function createAsyncActionDirect<A extends any = any, R extends any = any, N extends any = any, S extends IPullstateAllStores = IPullstateAllStores>(action: (args: A, stores: S, customContext: any) => Promise<R>, options?: ICreateAsyncActionOptions<A, R, string, N, S>): IOCreateAsyncActionOutput<A, R, string, N>; | ||
export declare function createAsyncAction<A = any, R = any, T extends string = string, N extends any = any, S extends IPullstateAllStores = IPullstateAllStores>(action: TPullstateAsyncAction<A, R, T, N, S>, { forceContext, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, actionId }?: ICreateAsyncActionOptions<A, R, T, N, S>): IOCreateAsyncActionOutput<A, R, T, N>; |
@@ -477,8 +477,8 @@ 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) { | ||
function createAsyncActionDirect(action, options = {}) { | ||
return createAsyncAction(async (args) => { | ||
return successResult(await action(args)); | ||
return createAsyncAction(async (args, stores, customContext) => { | ||
return successResult(await action(args, stores, customContext)); | ||
}, options); | ||
} | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey } = {}) { | ||
const ordinal = asyncCreationOrdinal++; | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, actionId } = {}) { | ||
const ordinal = actionId != null ? `_${actionId}` : asyncCreationOrdinal++; | ||
const onServer = typeof window === "undefined"; | ||
@@ -541,8 +541,8 @@ function _createKey(args, customKey) { | ||
} | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, context) { | ||
return () => action(args, stores) | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, executionContext, customContext) { | ||
return () => action(args, stores, customContext) | ||
.then((resp) => { | ||
if (currentActionOrd === cache.actionOrd[key]) { | ||
if (postActionEnabled) { | ||
runPostActionHook(resp, args, stores, context); | ||
runPostActionHook(resp, args, stores, executionContext); | ||
} | ||
@@ -564,3 +564,3 @@ cache.results[key] = [true, true, resp, false, Date.now()]; | ||
if (postActionEnabled) { | ||
runPostActionHook(result, args, stores, context); | ||
runPostActionHook(result, args, stores, executionContext); | ||
} | ||
@@ -581,3 +581,3 @@ cache.results[key] = [true, true, result, false, Date.now()]; | ||
} | ||
function checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult = undefined) { | ||
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); | ||
@@ -599,3 +599,3 @@ if (cached) { | ||
if (ssr || !onServer) { | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, EPostActionContext.BECKON_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, EPostActionContext.BECKON_RUN, customContext); | ||
} | ||
@@ -645,7 +645,15 @@ if (!onServer) { | ||
const cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
const cached = getCachedResult(key, cache, args, stores, EPostActionContext.READ_HIT_CACHE, postActionEnabled, cacheBreakEnabled, false); | ||
@@ -675,3 +683,3 @@ if (cached) { | ||
const currentActionOrd = actionOrdUpdate(cache, key); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, EPostActionContext.READ_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, EPostActionContext.READ_RUN, customContext); | ||
if (onServer) { | ||
@@ -712,11 +720,19 @@ 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 cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
if (!onServer) { | ||
const onAsyncStateChanged = () => { | ||
if (shouldUpdate[key][watchId.current] && !isEqual(responseRef.current, cache.results[key])) { | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled, undefined, customContext); | ||
setWatchUpdate((prev) => { | ||
@@ -772,3 +788,3 @@ 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); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, false, postActionEnabled, cacheBreakEnabled, holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, customContext); | ||
} | ||
@@ -789,3 +805,3 @@ return responseRef.current; | ||
}; | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy } = {}) => { | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy, _customContext } = {}) => { | ||
const key = _createKey(args, customKey); | ||
@@ -852,3 +868,3 @@ if (respectCache) { | ||
let currentActionOrd = actionOrdUpdate(_asyncCache, key); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, EPostActionContext.DIRECT_RUN); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, EPostActionContext.DIRECT_RUN, _customContext); | ||
notifyListeners(key); | ||
@@ -1120,5 +1136,5 @@ return _asyncCache.actions[key](); | ||
} | ||
instantiate({ hydrateSnapshot, ssr = false } = {}) { | ||
instantiate({ hydrateSnapshot, ssr = false, customContext } = {}) { | ||
if (!ssr) { | ||
const instantiated = new PullstateInstance(clientStores.stores, false); | ||
const instantiated = new PullstateInstance(clientStores.stores, false, customContext); | ||
if (hydrateSnapshot != null) { | ||
@@ -1147,3 +1163,3 @@ instantiated.hydrateFromSnapshot(hydrateSnapshot); | ||
} | ||
return new PullstateInstance(newStores, true); | ||
return new PullstateInstance(newStores, true, customContext); | ||
} | ||
@@ -1168,3 +1184,3 @@ useStores() { | ||
class PullstateInstance { | ||
constructor(allStores, ssr) { | ||
constructor(allStores, ssr, customContext) { | ||
this._ssr = false; | ||
@@ -1180,2 +1196,3 @@ this._stores = {}; | ||
this._ssr = ssr; | ||
this._customContext = customContext; | ||
} | ||
@@ -1207,2 +1224,5 @@ getAllUnresolvedAsyncActions() { | ||
} | ||
get customContext() { | ||
return this._customContext; | ||
} | ||
async runAsyncAction(asyncAction, args = {}, runOptions = {}) { | ||
@@ -1212,2 +1232,3 @@ if (this._ssr) { | ||
runOptions._stores = this._stores; | ||
runOptions._customContext = this._customContext; | ||
} | ||
@@ -1214,0 +1235,0 @@ return await asyncAction.run(args, runOptions); |
@@ -475,8 +475,8 @@ '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) { | ||
function createAsyncActionDirect(action, options = {}) { | ||
return createAsyncAction(async (args) => { | ||
return successResult(await action(args)); | ||
return createAsyncAction(async (args, stores, customContext) => { | ||
return successResult(await action(args, stores, customContext)); | ||
}, options); | ||
} | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey } = {}) { | ||
const ordinal = asyncCreationOrdinal++; | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, actionId } = {}) { | ||
const ordinal = actionId != null ? `_${actionId}` : asyncCreationOrdinal++; | ||
const onServer = typeof window === "undefined"; | ||
@@ -539,8 +539,8 @@ function _createKey(args, customKey) { | ||
} | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, context) { | ||
return () => action(args, stores) | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, executionContext, customContext) { | ||
return () => action(args, stores, customContext) | ||
.then((resp) => { | ||
if (currentActionOrd === cache.actionOrd[key]) { | ||
if (postActionEnabled) { | ||
runPostActionHook(resp, args, stores, context); | ||
runPostActionHook(resp, args, stores, executionContext); | ||
} | ||
@@ -562,3 +562,3 @@ cache.results[key] = [true, true, resp, false, Date.now()]; | ||
if (postActionEnabled) { | ||
runPostActionHook(result, args, stores, context); | ||
runPostActionHook(result, args, stores, executionContext); | ||
} | ||
@@ -579,3 +579,3 @@ cache.results[key] = [true, true, result, false, Date.now()]; | ||
} | ||
function checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult = undefined) { | ||
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); | ||
@@ -597,3 +597,3 @@ if (cached) { | ||
if (ssr || !onServer) { | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.BECKON_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.BECKON_RUN, customContext); | ||
} | ||
@@ -643,7 +643,15 @@ if (!onServer) { | ||
const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? React.useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = React.useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
const cached = getCachedResult(key, cache, args, stores, exports.EPostActionContext.READ_HIT_CACHE, postActionEnabled, cacheBreakEnabled, false); | ||
@@ -673,3 +681,3 @@ if (cached) { | ||
const currentActionOrd = actionOrdUpdate(cache, key); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.READ_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.READ_RUN, customContext); | ||
if (onServer) { | ||
@@ -710,11 +718,19 @@ 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 cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? React.useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = React.useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
if (!onServer) { | ||
const onAsyncStateChanged = () => { | ||
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); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled, undefined, customContext); | ||
setWatchUpdate((prev) => { | ||
@@ -770,3 +786,3 @@ 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); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, false, postActionEnabled, cacheBreakEnabled, holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, customContext); | ||
} | ||
@@ -787,3 +803,3 @@ return responseRef.current; | ||
}; | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy } = {}) => { | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy, _customContext } = {}) => { | ||
const key = _createKey(args, customKey); | ||
@@ -850,3 +866,3 @@ if (respectCache) { | ||
let currentActionOrd = actionOrdUpdate(_asyncCache, key); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, exports.EPostActionContext.DIRECT_RUN); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, exports.EPostActionContext.DIRECT_RUN, _customContext); | ||
notifyListeners(key); | ||
@@ -1118,5 +1134,5 @@ return _asyncCache.actions[key](); | ||
} | ||
instantiate({ hydrateSnapshot, ssr = false } = {}) { | ||
instantiate({ hydrateSnapshot, ssr = false, customContext } = {}) { | ||
if (!ssr) { | ||
const instantiated = new PullstateInstance(clientStores.stores, false); | ||
const instantiated = new PullstateInstance(clientStores.stores, false, customContext); | ||
if (hydrateSnapshot != null) { | ||
@@ -1145,3 +1161,3 @@ instantiated.hydrateFromSnapshot(hydrateSnapshot); | ||
} | ||
return new PullstateInstance(newStores, true); | ||
return new PullstateInstance(newStores, true, customContext); | ||
} | ||
@@ -1166,3 +1182,3 @@ useStores() { | ||
class PullstateInstance { | ||
constructor(allStores, ssr) { | ||
constructor(allStores, ssr, customContext) { | ||
this._ssr = false; | ||
@@ -1178,2 +1194,3 @@ this._stores = {}; | ||
this._ssr = ssr; | ||
this._customContext = customContext; | ||
} | ||
@@ -1205,2 +1222,5 @@ getAllUnresolvedAsyncActions() { | ||
} | ||
get customContext() { | ||
return this._customContext; | ||
} | ||
async runAsyncAction(asyncAction, args = {}, runOptions = {}) { | ||
@@ -1210,2 +1230,3 @@ if (this._ssr) { | ||
runOptions._stores = this._stores; | ||
runOptions._customContext = this._customContext; | ||
} | ||
@@ -1212,0 +1233,0 @@ return await asyncAction.run(args, runOptions); |
@@ -563,8 +563,8 @@ (function (global, factory) { | ||
function createAsyncActionDirect(action, options = {}) { | ||
return createAsyncAction(async (args) => { | ||
return successResult(await action(args)); | ||
return createAsyncAction(async (args, stores, customContext) => { | ||
return successResult(await action(args, stores, customContext)); | ||
}, options); | ||
} | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey } = {}) { | ||
const ordinal = asyncCreationOrdinal++; | ||
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, actionId } = {}) { | ||
const ordinal = actionId != null ? `_${actionId}` : asyncCreationOrdinal++; | ||
const onServer = typeof window === "undefined"; | ||
@@ -627,8 +627,8 @@ function _createKey(args, customKey) { | ||
} | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, context) { | ||
return () => action(args, stores) | ||
function createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, executionContext, customContext) { | ||
return () => action(args, stores, customContext) | ||
.then((resp) => { | ||
if (currentActionOrd === cache.actionOrd[key]) { | ||
if (postActionEnabled) { | ||
runPostActionHook(resp, args, stores, context); | ||
runPostActionHook(resp, args, stores, executionContext); | ||
} | ||
@@ -650,3 +650,3 @@ cache.results[key] = [true, true, resp, false, Date.now()]; | ||
if (postActionEnabled) { | ||
runPostActionHook(result, args, stores, context); | ||
runPostActionHook(result, args, stores, executionContext); | ||
} | ||
@@ -667,3 +667,3 @@ cache.results[key] = [true, true, result, false, Date.now()]; | ||
} | ||
function checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, fromListener = false, postActionEnabled = true, cacheBreakEnabled = true, holdingResult = undefined) { | ||
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); | ||
@@ -685,3 +685,3 @@ if (cached) { | ||
if (ssr || !onServer) { | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.BECKON_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.BECKON_RUN, customContext); | ||
} | ||
@@ -731,7 +731,15 @@ if (!onServer) { | ||
const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? React.useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = React.useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
const cached = getCachedResult(key, cache, args, stores, exports.EPostActionContext.READ_HIT_CACHE, postActionEnabled, cacheBreakEnabled, false); | ||
@@ -761,3 +769,3 @@ if (cached) { | ||
const currentActionOrd = actionOrdUpdate(cache, key); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.READ_RUN); | ||
cache.actions[key] = createInternalAction(key, cache, args, stores, currentActionOrd, postActionEnabled, exports.EPostActionContext.READ_RUN, customContext); | ||
if (onServer) { | ||
@@ -798,11 +806,19 @@ 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 cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache; | ||
const stores = onServer || forceContext | ||
? React.useContext(PullstateContext).stores | ||
: clientStores.loaded | ||
? clientStores.stores | ||
: storeErrorProxy; | ||
let stores; | ||
let customContext; | ||
if (onServer || forceContext) { | ||
const pullstateContext = React.useContext(PullstateContext); | ||
stores = pullstateContext.stores; | ||
customContext = pullstateContext.customContext; | ||
} | ||
else if (clientStores.loaded) { | ||
stores = clientStores.stores; | ||
} | ||
else { | ||
stores = storeErrorProxy; | ||
} | ||
if (!onServer) { | ||
const onAsyncStateChanged = () => { | ||
if (shouldUpdate[key][watchId.current] && !es6(responseRef.current, cache.results[key])) { | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, true, postActionEnabled, cacheBreakEnabled, undefined, customContext); | ||
setWatchUpdate((prev) => { | ||
@@ -858,3 +874,3 @@ 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); | ||
responseRef.current = checkKeyAndReturnResponse(key, cache, initiate, ssr, args, stores, false, postActionEnabled, cacheBreakEnabled, holdPrevious && responseRef.current && responseRef.current[1] ? responseRef.current : undefined, customContext); | ||
} | ||
@@ -875,3 +891,3 @@ return responseRef.current; | ||
}; | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy } = {}) => { | ||
const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy, _customContext } = {}) => { | ||
const key = _createKey(args, customKey); | ||
@@ -938,3 +954,3 @@ if (respectCache) { | ||
let currentActionOrd = actionOrdUpdate(_asyncCache, key); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, exports.EPostActionContext.DIRECT_RUN); | ||
_asyncCache.actions[key] = createInternalAction(key, _asyncCache, args, _stores, currentActionOrd, true, exports.EPostActionContext.DIRECT_RUN, _customContext); | ||
notifyListeners(key); | ||
@@ -1208,5 +1224,5 @@ return _asyncCache.actions[key](); | ||
} | ||
instantiate({ hydrateSnapshot, ssr = false } = {}) { | ||
instantiate({ hydrateSnapshot, ssr = false, customContext } = {}) { | ||
if (!ssr) { | ||
const instantiated = new PullstateInstance(clientStores.stores, false); | ||
const instantiated = new PullstateInstance(clientStores.stores, false, customContext); | ||
if (hydrateSnapshot != null) { | ||
@@ -1235,3 +1251,3 @@ instantiated.hydrateFromSnapshot(hydrateSnapshot); | ||
} | ||
return new PullstateInstance(newStores, true); | ||
return new PullstateInstance(newStores, true, customContext); | ||
} | ||
@@ -1256,3 +1272,3 @@ useStores() { | ||
class PullstateInstance { | ||
constructor(allStores, ssr) { | ||
constructor(allStores, ssr, customContext) { | ||
this._ssr = false; | ||
@@ -1268,2 +1284,3 @@ this._stores = {}; | ||
this._ssr = ssr; | ||
this._customContext = customContext; | ||
} | ||
@@ -1295,2 +1312,5 @@ getAllUnresolvedAsyncActions() { | ||
} | ||
get customContext() { | ||
return this._customContext; | ||
} | ||
async runAsyncAction(asyncAction, args = {}, runOptions = {}) { | ||
@@ -1300,2 +1320,3 @@ if (this._ssr) { | ||
runOptions._stores = this._stores; | ||
runOptions._customContext = this._customContext; | ||
} | ||
@@ -1302,0 +1323,0 @@ return await asyncAction.run(args, runOptions); |
@@ -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){g(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 g(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 _,E;(_=t.EAsyncEndTags||(t.EAsyncEndTags={})).THREW_ERROR="THREW_ERROR",_.RETURNED_ERROR="RETURNED_ERROR",_.UNFINISHED="UNFINISHED",_.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 k(t,e){return t.actionOrd.hasOwnProperty(e)?t.actionOrd[e]+=1:t.actionOrd[e]=0,t.actionOrd[e]}function m(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 U(t,e={}){return v((async e=>m(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 g(t,e,s,r){void 0!==u&&u({args:e,result:t,stores:s,context:r})}function _(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&&g(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&&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],h||O(e)),t)))}function U(e,s,r,n,o,a,c=!1,u=!0,l=!0,d){const f=_(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=k(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 g(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(),g=e.useRef("."),_=l?".":f(s,d);let E=e.useRef(-1);-1===E.current&&(E.current=y++),l||(C.hasOwnProperty(_)?C[_][E.current]=!0:C[_]={[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[_][E.current]&&!a(p.current,R.results[_])&&(p.current=U(_,R,n,o,s,P,!0,i,c),w((t=>t+1)))};l||(R.listeners.hasOwnProperty(_)||(R.listeners[_]={}),R.listeners[_][E.current]=t,C[_][E.current]=!0),e.useEffect((()=>(l||(R.listeners[_][E.current]=t,C[_][E.current]=!0),()=>{l||(delete R.listeners[_][E.current],C[_][E.current]=!1)})),[_])}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],g.current="."):g.current!==_&&(null!==g.current&&C.hasOwnProperty(g.current)&&(delete R.listeners[g.current][E.current],C[g.current][E.current]=!1),g.current=_,p.current=U(_,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=_(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()],g(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=k(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,m(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&&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)}},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,g=f&&p.error;l&&e.useEffect((()=>{C&&!c&&l(p.payload,t)}),[C]);return{isStarted:h,isFinished:f,isUpdating:y,isSuccess:C,isFailure:g,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((()=>({key:t.key?t.key:f({}),args:{}})));return{...W({},{...t,key:s.key,initiate:!1}),clearCached:()=>{N({},s.key)},setCached:(t,e={})=>{e.key=s.key,x({},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:f(e);return a!==s.key&&r({key:a,args:e}),H(e,{...n,key:a}).then((e=>(t.clearOnSuccess&&N({},a),e)))},args:s.args,key:s.key}},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=_(c,u,s,l,t.EPostActionContext.READ_HIT_CACHE,o,n,!1);if(d){if(d[2].error)throw new b(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(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=k(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,key:a}={})=>{const i=v(t,{initiate:!0,ssr:e,postActionEnabled:s,cacheBreakEnabled:r,holdPrevious:n,dormant:o,key:a});return[i[1],i[2],i[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=m,t.update=g,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 m(t,e=!0){e&&S.actionOrd.hasOwnProperty(t)&&(S.actionOrd[t]+=1),delete S.results[t],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={},e)=>{m(p(t,e))},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({},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({},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:()=>{for(const t of Object.keys(S.actionOrd))t.startsWith(h+"-")&&m(t)},clearAllUnwatchedCache:()=>{for(const t of Object.keys(_))Object.values(_[t]).some((t=>t))||(delete _[t],m(t,!1))},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})})); |
@@ -26,5 +26,6 @@ import React from "react"; | ||
constructor(allStores: S, options?: IPullstateSingletonOptions); | ||
instantiate({ hydrateSnapshot, ssr }?: { | ||
instantiate({ hydrateSnapshot, ssr, customContext }?: { | ||
hydrateSnapshot?: IPullstateSnapshot; | ||
ssr?: boolean; | ||
customContext?: any; | ||
}): PullstateInstance<S>; | ||
@@ -56,5 +57,6 @@ useStores(): S; | ||
private _ssr; | ||
private _customContext; | ||
private readonly _stores; | ||
_asyncCache: IPullstateAsyncCache; | ||
constructor(allStores: T, ssr: boolean); | ||
constructor(allStores: T, ssr: boolean, customContext: any); | ||
private getAllUnresolvedAsyncActions; | ||
@@ -66,2 +68,3 @@ instantiateReactions(): void; | ||
get stores(): T; | ||
get customContext(): any; | ||
runAsyncAction<A, R, X extends string, N>(asyncAction: IOCreateAsyncActionOutput<A, R, X, N>, args?: A, runOptions?: Pick<IAsyncActionRunOptions, "ignoreShortCircuit" | "respectCache">): TPullstateAsyncRunResponse<R, X, N>; | ||
@@ -68,0 +71,0 @@ hydrateFromSnapshot(snapshot: IPullstateSnapshot): void; |
{ | ||
"name": "pullstate", | ||
"version": "1.20.4", | ||
"version": "1.20.5", | ||
"description": "Simple state stores using immer and React hooks", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
237459
4550