@dr.pogodin/react-global-state 0.21.1 → 0.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -90,7 +90,7 @@ export default class GlobalState {
90
90
  */
91
91
  hasChangedDependencies(path, deps) {
92
92
  const prevDeps = _classPrivateFieldGet(_dependencies, this)[path];
93
- let changed = !prevDeps || prevDeps.length !== deps.length;
93
+ let changed = (prevDeps === null || prevDeps === void 0 ? void 0 : prevDeps.length) !== deps.length;
94
94
  for (let i = 0; !changed && i < deps.length; ++i) {
95
95
  changed = prevDeps[i] !== deps[i];
96
96
  }
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalState.js","names":["get","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_asyncDataAbortCallbacks","WeakMap","_dependencies","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","_classPrivateFieldGet2","_classPrivateFieldGet3","call","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","watcher","setAsyncDataAbortCallback","cb","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","includes","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks: Record<string, () => void> = {};\n\n #dependencies: Record<string, readonly unknown[]> = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return Object.keys(this.#asyncDataAbortCallbacks).length;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks[opid]?.();\n delete this.#asyncDataAbortCallbacks[opid];\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = typeof iv === 'function' ? (iv as () => StateT)() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks[opid] = cb;\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (typeof path !== 'string') {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = typeof iv === 'function' ? (iv as () => ValueT)() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (typeof path !== 'string') return this.setEntireState(value as StateT);\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\n else if (typeof next === 'object') pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg] as Record<string, unknown>;\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SAASA,GAAG,EAAEC,GAAG,EAAEC,MAAM,QAAQ,WAAW;AAAC,SAW3CC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,wBAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,aAAA,oBAAAF,OAAA;AAAA,IAAAG,SAAA,oBAAAH,OAAA;AAAA,IAAAI,eAAA,oBAAAJ,OAAA;AAAA,IAAAK,aAAA,oBAAAL,OAAA;AAO1E,eAAe,MAAMM,WAAW,CAG9B;EAmBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAxBFC,0BAAA,OAAAX,wBAAwB,EAA+B,CAAC,CAAC;IAEzDW,0BAAA,OAAAT,aAAa,EAAuC,CAAC,CAAC;IAEtDS,0BAAA,OAAAR,aAAa;IAEb;IACA;IACA;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EAAE,MAAM,IAAI2D,KAAK,CAACtE,gBAAgB,CAAC;IAEtD,MAAMsD,QAAQ,GAAGrC,qBAAA,CAAKZ,SAAS,EAAd,IAAa,CAAC;IAC/B,IAAI,CAACiD,QAAQ,CAACoB,QAAQ,CAACL,QAAQ,CAAC,EAAE;MAChCf,QAAQ,CAACqB,IAAI,CAACN,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
1
+ {"version":3,"file":"GlobalState.js","names":["get","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_asyncDataAbortCallbacks","WeakMap","_dependencies","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","_classPrivateFieldGet2","_classPrivateFieldGet3","call","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","watcher","setAsyncDataAbortCallback","cb","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","includes","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks: Record<string, () => void> = {};\n\n #dependencies: Record<string, readonly unknown[]> = {};\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return Object.keys(this.#asyncDataAbortCallbacks).length;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks[opid]?.();\n delete this.#asyncDataAbortCallbacks[opid];\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n delete this.#dependencies[path];\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies[path];\n let changed = prevDeps?.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[path] = Object.freeze(deps);\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = typeof iv === 'function' ? (iv as () => StateT)() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks[opid] = cb;\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (typeof path !== 'string') {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = typeof iv === 'function' ? (iv as () => ValueT)() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (typeof path !== 'string') return this.setEntireState(value as StateT);\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\n else if (typeof next === 'object') pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg] as Record<string, unknown>;\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SAASA,GAAG,EAAEC,GAAG,EAAEC,MAAM,QAAQ,WAAW;AAAC,SAW3CC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,wBAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,aAAA,oBAAAF,OAAA;AAAA,IAAAG,SAAA,oBAAAH,OAAA;AAAA,IAAAI,eAAA,oBAAAJ,OAAA;AAAA,IAAAK,aAAA,oBAAAL,OAAA;AAO1E,eAAe,MAAMM,WAAW,CAG9B;EAmBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAxBFC,0BAAA,OAAAX,wBAAwB,EAA+B,CAAC,CAAC;IAEzDW,0BAAA,OAAAT,aAAa,EAAuC,CAAC,CAAC;IAEtDS,0BAAA,OAAAR,aAAa;IAEb;IACA;IACA;IACA;IACAQ,0BAAA,OAAAP,SAAS,EAAgB,EAAE;IAE3BO,0BAAA,OAAAN,eAAe;IAEfM,0BAAA,OAAAL,aAAa;IAWXM,qBAAA,CAAKN,aAAa,EAAlB,IAAI,EAAiBG,YAA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QAAQ,CAACoB,QAAQ,CAACL,QAAQ,CAAC,EAAE;MAChCf,QAAQ,CAACqB,IAAI,CAACN,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["createContext","use","useState","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localState","setLocalState","state","stateProxy","undefined","initialState","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nimport type { ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\n});\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAEEA,aAAa,EACbC,GAAG,EACHC,QAAQ,QACH,OAAO;AAAC,OAERC,WAAW;AAAA,SAAAC,GAAA,IAAAC,IAAA;AAKlB,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGL,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACK,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGA,CAI1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KACtD;EAGd,MAAM,CAACC,UAAU,EAAEC,aAAa,CAAC,GAAGf,QAAQ,CAAM,CAAC;EAEnD,IAAIgB,KAAU;;EAEd;EACA;EACA;EACA;EACA,IAAI,YAAY,IAAIH,IAAI,IAAKA,IAAI,CAACI,UAAsB,EAAE;IACxD,IAAIH,UAAU,EAAEC,aAAa,CAACG,SAAS,CAAC;IACxCF,KAAK,GAAGH,IAAI,CAACI,UAAU,KAAK,IAAI,GAAGZ,cAAc,CAAC,CAAC,GAAGQ,IAAI,CAACI,UAAU;EACvE,CAAC,MAAM,IAAIH,UAAU,EAAE;IACrBE,KAAK,GAAGF,UAAU;EACpB,CAAC,MAAM;IACL,MAAM;MACJK,YAAY;MACZT;IACF,CAAC,GAAGG,IAA0C;IAE9CG,KAAK,GAAG,IAAIf,WAAW,CACrB,OAAOkB,YAAY,KAAK,UAAU,GAAIA,YAAY,CAAkB,CAAC,GAAGA,YAAY,EACpFT,UACF,CAAC;IAEDK,aAAa,CAACC,KAAK,CAAC;EACtB;EAEA,oBAAOb,IAAA,CAACC,OAAO;IAACgB,KAAK,EAAEJ,KAAM;IAAAJ,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeD,mBAAmB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["createContext","use","useState","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localState","setLocalState","state","stateProxy","undefined","initialState","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nimport type { ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = (NewStateProps<StateT, SsrContextT> | {\n stateProxy: GlobalState<StateT, SsrContextT> | true;\n}) & {\n children?: ReactNode;\n};\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAEEA,aAAa,EACbC,GAAG,EACHC,QAAQ,QACH,OAAO;AAAC,OAERC,WAAW;AAAA,SAAAC,GAAA,IAAAC,IAAA;AAKlB,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASE,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGL,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACK,UAAU,IAAID,sBAAsB,EAAE;IACzC,MAAM,IAAIF,KAAK,CAAC,sBAAsB,CAAC;EACzC;EACA,OAAOG,UAAU;AACnB;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGA,CAI1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KACtD;EAGd,MAAM,CAACC,UAAU,EAAEC,aAAa,CAAC,GAAGf,QAAQ,CAAM,CAAC;EAEnD,IAAIgB,KAAU;;EAEd;EACA;EACA;EACA;EACA,IAAI,YAAY,IAAIH,IAAI,IAAKA,IAAI,CAACI,UAAsB,EAAE;IACxD,IAAIH,UAAU,EAAEC,aAAa,CAACG,SAAS,CAAC;IACxCF,KAAK,GAAGH,IAAI,CAACI,UAAU,KAAK,IAAI,GAAGZ,cAAc,CAAC,CAAC,GAAGQ,IAAI,CAACI,UAAU;EACvE,CAAC,MAAM,IAAIH,UAAU,EAAE;IACrBE,KAAK,GAAGF,UAAU;EACpB,CAAC,MAAM;IACL,MAAM;MACJK,YAAY;MACZT;IACF,CAAC,GAAGG,IAA0C;IAE9CG,KAAK,GAAG,IAAIf,WAAW,CACrB,OAAOkB,YAAY,KAAK,UAAU,GAAIA,YAAY,CAAkB,CAAC,GAAGA,YAAY,EACpFT,UACF,CAAC;IAEDK,aAAa,CAACC,KAAK,CAAC;EACtB;EAEA,oBAAOb,IAAA,CAACC,OAAO;IAACgB,KAAK,EAAEJ,KAAM;IAAAJ,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeD,mBAAmB","ignoreList":[]}
@@ -4,7 +4,7 @@ import SsrContext from "./SsrContext.js";
4
4
  import useAsyncCollection from "./useAsyncCollection.js";
5
5
  import { newAsyncDataEnvelope, useAsyncData } from "./useAsyncData.js";
6
6
  import useGlobalState from "./useGlobalState.js";
7
- export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState };
7
+ export { GlobalState, GlobalStateProvider, SsrContext, getGlobalState, getSsrContext, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState };
8
8
 
9
9
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
10
10
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n SsrContext: typeof SsrContext<StateT>;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"OAAOA,WAAW;AAAA,OAEXC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAAA,OAGRC,UAAU;AAAA,OAEVC,kBAAkB;AAAA,SAYvBC,oBAAoB,EACpBC,YAAY;AAAA,OAGPC,cAAc;AAYrB,SAOEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;;AAGhB;;AAgBA,MAAMC,GAAG,GAAG;EACV;EACA;EACA;EACAT,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVF,cAAc;EACdC,aAAa;EACbG,oBAAoB;EACpBD,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateI,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n SsrContext: typeof SsrContext<StateT>;\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"OAAOA,WAAW;AAAA,OAEXC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAAA,OAGRC,UAAU;AAAA,OAEVC,kBAAkB;AAAA,SAYvBC,oBAAoB,EACpBC,YAAY;AAAA,OAGPC,cAAc;AAYrB,SAIER,WAAW,EACXC,mBAAmB,EACnBG,UAAU,EAOVF,cAAc,EACdC,aAAa,EACbG,oBAAoB,EACpBD,kBAAkB,EAClBE,YAAY,EACZC,cAAc;;AAGhB;;AAgBA,MAAMC,GAAG,GAAG;EACV;EACA;EACA;EACAT,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVF,cAAc;EACdC,aAAa;EACbG,oBAAoB;EACpBD,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","useState","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","_options$maxage","_options$refreshAge","_options$garbageColle","_ref$current","maxage","refreshAge","garbageCollectAge","globalState","ssrContext","disabled","noSSR","operationId","itemPath","state","initialValue","promiseOrVoid","args","data","Promise","pending","push","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","localState","ref","current","stable","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | null> => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n\n // Client-side logic.\n } else {\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await load(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = load(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,OAAO;AACnD,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAAC,SAGzBC,cAAc;AAAA,SASrBC,cAAc,EACdC,IAAI,EACJC,oBAAoB;AAAA,OAGfC,cAAc;AAAA,SAMnBC,IAAI,EACJC,WAAW;AAmDb;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,MAAMI,EAAE,IAAIL,GAAG,EAAE;IACpB,IAAIM,QAAQ,GAAGH,UAAU,CAACE,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAAQ;MAAEC,OAAO,EAAE,CAAC,GAAGD,QAA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X7E,GAAG,CAAC6E,OAAO,GAAKA,OAAO;IACvB,IAAI7E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe4B,kBAAkB;;AAEjC","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","useState","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","_options$maxage","_options$refreshAge","_options$garbageColle","_ref$current","maxage","refreshAge","garbageCollectAge","globalState","ssrContext","disabled","noSSR","operationId","itemPath","state","initialValue","promiseOrVoid","args","data","Promise","pending","push","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","localState","ref","current","stable","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n DEFAULT_MAXAGE,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: DataT | null, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void> | void;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = getGlobalState();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | Promise<DataT | null> | null => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n\n // Client-side logic.\n } else {\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsHash,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await load(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old as DataT, ...args),\n globalState,\n {\n data: state2?.data,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n }\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = load(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>\n | UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,OAAO;AACnD,SAASC,EAAE,IAA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MAAMkF,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAElC,WAAW;IAChC,MAAM7B,SAAS,IAAAoE,aAAA,GAAGL,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAE/D,SAAS,cAAAoE,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCjF,GAAG,CAAC8E,KAAK,CAACnF,EAAE,CAAC,GAAG;MACdqD,IAAI,EAAEb,MAAM,GAAG1B,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,IAAAqE,QAAA,GAAGN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAE5B,IAAI,cAAAkC,QAAA,cAAAA,QAAA,GAAI,IAAI;MAC9DL,OAAO;MACPhE;IACF,CAAC;IACDb,GAAG,CAAC6E,OAAO,KAAX7E,GAAG,CAAC6E,OAAO,GAAKA,OAAO;IACvB,IAAI7E,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe4B,kBAAkB;;AAEjC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","setState","path","gs","prevState","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","load","loader","globalState","old","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","_options$maxage","_options$refreshAge","_options$garbageColle","_heap$reload","_heap$set","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: string | null | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): void | Promise<void> {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n set?: (data: DataT | null) => void;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n heap.set ??= (data: DataT | null) => {\n if (!heap.globalState) throw Error('Internal error');\n setState(data, heap.path, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n set: heap.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;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IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,EAAE,EAAE8D,IAAI;;QAE5D;QAAA,GAEEjB,UAAU,GAAGlC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGgD,MAAM,CAAChE,SAAS,KACtC,CAACgE,MAAM,CAAC9D,WAAW,IAAI8D,MAAM,CAAC9D,WAAW,CAACkE,UAAU,CAAC,GAAG,CAAC,CAC9D,EACD;UACA,IAAI,CAACF,IAAI,EAAE3C,WAAW,CAAC0C,gBAAgB,CAAC7D,IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,EAAE,CAAC;UACnD,KAAKiB,IAAI,CAACjB,IAAI,EAAEkB,MAAM,EAAEC,WAAW,EAAE;YACnCtB,IAAI,EAAE+D,MAAM,CAAC/D,IAAI;YACjBD,SAAS,EAAEgE,MAAM,CAAChE;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAACqE,UAAU,CAAC,GAAG5E,cAAc,CACjCW,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE+C,MAAM,GAAGjC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGqD,UAAU,CAACrE,SAAS,GAAG,IAAI,GAAGqE,UAAU,CAACpE,IAAI;IACzEqE,OAAO,EAAEC,OAAO,CAACF,UAAU,CAACnE,WAAW,CAAC;IACxCoD,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBxC,GAAG,EAAEuC,IAAI,CAACvC,GAAG;IACbd,SAAS,EAAEqE,UAAU,CAACrE;EACxB,CAAC;AACH;AAEA,SAASyC,YAAY;;AAErB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","setState","path","gs","prevState","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","load","loader","globalState","old","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","_options$maxage","_options$refreshAge","_options$garbageColle","_heap$reload","_heap$set","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport type SsrContext from './SsrContext';\n\nimport useGlobalState from './useGlobalState';\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: DataT | null, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => Promise<void> | void;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: DataT | null;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function load<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${uuid()}`,\n): Promise<void> | void {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n loader?: AsyncDataLoaderT<DataT>;\n path?: null | string;\n reload?: AsyncDataReloaderT<DataT>;\n set?: (data: DataT | null) => void;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): Promise<void> | void => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n heap.set ??= (data: DataT | null) => {\n if (!heap.globalState) throw Error('Internal error');\n setState(data, heap.path, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n set: heap.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAAC,SAGrCC,cAAc;AAAA,OAIhBC,cAAc;AAAA,SAMnBC,eAAe,EACfC,WAAW;AAGb,OAAO,MAAMC,cAAc,GAAG,CAAC,GAAGL,MAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBA,OAAO,SAASM,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAmBA;AACA;AACA;AACA;AACA,SAASG,QAAQA,CAIfF,IAAW,EACXG,IAA+B,EAC/BC,EAA6C,EAC7CC,SAAe,GAAGD,EAAE,CAACE,GAAG,CAAeH,IAAI,CAAC,EAC5C;EACA,IAAII,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAIf,WAAW,CAAC,CAAC,EAAE;IAC1D;IACAgB,OAAO,CAACC,cAAc,CACpB,oDACER,IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,EAAE,GAEd,CAAC;IACDO,OAAO,CAACE,GAAG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uC,IAAI,CAACvC,GAAG;IACbd,SAAS,EAAEqE,UAAU,CAACrE;EACxB,CAAC;AACH;AAEA,SAASyC,YAAY;;AAErB","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","time","add","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\n\nimport { cloneDeep } from 'lodash-es';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');\n}\n"],"mappings":"AAEA,SAASA,SAAS,QAAQ,WAAW;;AAIrC;AACA;;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
1
+ {"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","time","add","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\n\nimport { cloneDeep } from 'lodash-es';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = (() => ValueT) | ValueT;\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');\n}\n"],"mappings":"AAEA,SAASA,SAAS,QAAQ,WAAW;;AAIrC;AACA;;AAiBA;AACA;A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CAAC,CAAC;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
@@ -28,11 +28,11 @@ type NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {
28
28
  initialState: ValueOrInitializerT<StateT>;
29
29
  ssrContext?: SsrContextT;
30
30
  };
31
- type GlobalStateProviderProps<StateT, SsrContextT extends SsrContext<StateT>> = {
31
+ type GlobalStateProviderProps<StateT, SsrContextT extends SsrContext<StateT>> = (NewStateProps<StateT, SsrContextT> | {
32
+ stateProxy: GlobalState<StateT, SsrContextT> | true;
33
+ }) & {
32
34
  children?: ReactNode;
33
- } & (NewStateProps<StateT, SsrContextT> | {
34
- stateProxy: true | GlobalState<StateT, SsrContextT>;
35
- });
35
+ };
36
36
  /**
37
37
  * Provides global state to its children.
38
38
  * @param prop.children Component children, which will be provided with
@@ -7,14 +7,14 @@ import useGlobalState, { type UseGlobalStateI } from './useGlobalState';
7
7
  export type { AsyncCollectionLoaderT, AsyncCollectionReloaderT, AsyncCollectionT, } from './useAsyncCollection';
8
8
  export type { SetterT, UseGlobalStateResT } from './useGlobalState';
9
9
  export type { ForceT, ValueOrInitializerT } from './utils';
10
- export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, type UseAsyncCollectionResT, type UseAsyncDataOptionsT, type UseAsyncDataResT, getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState, };
10
+ export { type AsyncDataEnvelopeT, type AsyncDataLoaderT, type AsyncDataReloaderT, GlobalState, GlobalStateProvider, SsrContext, type UseAsyncCollectionI, type UseAsyncCollectionResT, type UseAsyncDataI, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateI, getGlobalState, getSsrContext, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, };
11
11
  interface API<StateT, SsrContextT extends SsrContext<StateT> = SsrContext<StateT>> {
12
- getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
13
- getSsrContext: typeof getSsrContext<SsrContextT>;
14
12
  GlobalState: typeof GlobalState<StateT, SsrContextT>;
15
13
  GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;
16
- newAsyncDataEnvelope: typeof newAsyncDataEnvelope;
17
14
  SsrContext: typeof SsrContext<StateT>;
15
+ getGlobalState: typeof getGlobalState<StateT, SsrContextT>;
16
+ getSsrContext: typeof getSsrContext<SsrContextT>;
17
+ newAsyncDataEnvelope: typeof newAsyncDataEnvelope;
18
18
  useAsyncCollection: UseAsyncCollectionI<StateT>;
19
19
  useAsyncData: UseAsyncDataI<StateT>;
20
20
  useGlobalState: UseGlobalStateI<StateT>;
@@ -4,12 +4,12 @@
4
4
  import { type AsyncDataEnvelopeT, type DataInEnvelopeAtPathT, type UseAsyncDataOptionsT, type UseAsyncDataResT } from './useAsyncData';
5
5
  import { type ForceT, type LockT, type TypeLock } from './utils';
6
6
  export type AsyncCollectionT<DataT = unknown, IdT extends number | string = number | string> = Record<IdT, AsyncDataEnvelopeT<DataT>>;
7
- export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number | string> = (id: IdT, oldData: null | DataT, meta: {
7
+ export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number | string> = (id: IdT, oldData: DataT | null, meta: {
8
8
  isAborted: () => boolean;
9
9
  oldDataTimestamp: number;
10
10
  setAbortCallback: (cb: () => void) => void;
11
- }) => DataT | null | Promise<DataT | null>;
12
- export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;
11
+ }) => DataT | Promise<DataT | null> | null;
12
+ export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void> | void;
13
13
  type CollectionItemT<DataT> = {
14
14
  data: DataT | null;
15
15
  loading: boolean;
@@ -29,12 +29,12 @@ declare function useAsyncCollection<StateT, PathT extends null | string | undefi
29
29
  declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
30
30
  declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
31
31
  declare function useAsyncCollection<Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
32
- declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;
32
+ declare function useAsyncCollection<StateT, PathT extends null | string | undefined, IdT extends number | string, DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataT, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT>;
33
33
  export default useAsyncCollection;
34
34
  export interface UseAsyncCollectionI<StateT> {
35
35
  <PathT extends null | string | undefined, IdT extends number | string>(id: IdT, path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
36
36
  <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT, path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;
37
37
  <PathT extends null | string | undefined, IdT extends number | string>(id: IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
38
38
  <Forced extends ForceT | LockT = LockT, DataT = unknown, IdT extends number | string = number | string>(id: IdT[], path: null | string | undefined, loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataT, IdT>;
39
- <PathT extends null | string | undefined, IdT extends number | string>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>> | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;
39
+ <PathT extends null | string | undefined, IdT extends number | string>(id: IdT | IdT[], path: PathT, loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>, options?: UseAsyncDataOptionsT): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT> | UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;
40
40
  }
@@ -1,18 +1,18 @@
1
1
  /**
2
2
  * Loads and uses async data into the GlobalState path.
3
3
  */
4
- import { type ForceT, type LockT, type TypeLock, type ValueAtPathT } from './utils';
5
4
  import type GlobalState from './GlobalState';
6
5
  import type SsrContext from './SsrContext';
6
+ import { type ForceT, type LockT, type TypeLock, type ValueAtPathT } from './utils';
7
7
  export declare const DEFAULT_MAXAGE: number;
8
- export type AsyncDataLoaderT<DataT> = (oldData: null | DataT, meta: {
8
+ export type AsyncDataLoaderT<DataT> = (oldData: DataT | null, meta: {
9
9
  isAborted: () => boolean;
10
10
  oldDataTimestamp: number;
11
11
  setAbortCallback: (cb: () => void) => void;
12
- }) => DataT | null | Promise<DataT | null>;
13
- export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;
12
+ }) => DataT | Promise<DataT | null> | null;
13
+ export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => Promise<void> | void;
14
14
  export type AsyncDataEnvelopeT<DataT> = {
15
- data: null | DataT;
15
+ data: DataT | null;
16
16
  numRefs: number;
17
17
  operationId: string;
18
18
  timestamp: number;
@@ -54,7 +54,7 @@ export type UseAsyncDataResT<DataT> = {
54
54
  export declare function load<DataT>(path: null | string | undefined, loader: AsyncDataLoaderT<DataT>, globalState: GlobalState<unknown, SsrContext<unknown>>, old?: {
55
55
  data: DataT | null;
56
56
  timestamp: number;
57
- }, operationId?: OperationIdT): void | Promise<void>;
57
+ }, operationId?: OperationIdT): Promise<void> | void;
58
58
  /**
59
59
  * Resolves asynchronous data, and stores them at given `path` of global
60
60
  * state.
@@ -19,7 +19,7 @@ export type TypeLock<Unlocked extends ForceT | LockT, LockedT extends never | vo
19
19
  * paths.
20
20
  */
21
21
  export type ValueAtPathT<StateT, PathT extends null | string | undefined, UnknownT extends never | undefined | void> = unknown extends StateT ? UnknownT : string extends PathT ? UnknownT : PathT extends null | undefined ? StateT : GetFieldType<StateT, PathT> extends undefined ? UnknownT : GetFieldType<StateT, PathT>;
22
- export type ValueOrInitializerT<ValueT> = ValueT | (() => ValueT);
22
+ export type ValueOrInitializerT<ValueT> = (() => ValueT) | ValueT;
23
23
  /**
24
24
  * Returns 'true' if debug logging should be performed; 'false' otherwise.
25
25
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.21.1",
3
+ "version": "0.21.3",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/code/index.js",
6
6
  "types": "./build/types/index.d.ts",
@@ -15,9 +15,9 @@
15
15
  "jest": "npm run jest:types && npm run jest:logic",
16
16
  "jest:logic": "jest --config jest/config.json -w 1 --no-cache",
17
17
  "jest:types": "tstyche",
18
- "lint": "eslint",
18
+ "lint": "eslint --cache",
19
19
  "test": "npm run lint && npm run typecheck && npm run jest",
20
- "typecheck": "tsc --project __tests__/tsconfig.json"
20
+ "typecheck": "tsc --noEmit"
21
21
  },
22
22
  "repository": "github:birdofpreyru/react-global-state",
23
23
  "keywords": [
@@ -39,41 +39,41 @@
39
39
  "node": ">=20"
40
40
  },
41
41
  "dependencies": {
42
- "@babel/runtime": "^7.28.4",
43
- "@dr.pogodin/js-utils": "^0.1.4",
44
- "@types/lodash": "^4.17.20",
45
- "lodash-es": "^4.17.21",
42
+ "@babel/runtime": "^7.28.6",
43
+ "@dr.pogodin/js-utils": "^0.1.5",
44
+ "@types/lodash": "^4.17.23",
45
+ "lodash-es": "^4.17.23",
46
46
  "uuid": "^13.0.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@babel/cli": "^7.28.3",
50
- "@babel/core": "^7.28.5",
51
- "@babel/node": "^7.28.0",
52
- "@babel/plugin-transform-runtime": "^7.28.5",
53
- "@babel/preset-env": "^7.28.5",
49
+ "@babel/cli": "^7.28.6",
50
+ "@babel/core": "^7.29.0",
51
+ "@babel/node": "^7.29.0",
52
+ "@babel/plugin-transform-runtime": "^7.29.0",
53
+ "@babel/preset-env": "^7.29.0",
54
54
  "@babel/preset-react": "^7.28.5",
55
55
  "@babel/preset-typescript": "^7.28.5",
56
- "@dr.pogodin/eslint-configs": "^0.1.1",
56
+ "@dr.pogodin/eslint-configs": "^0.2.7",
57
57
  "@testing-library/dom": "^10.4.1",
58
- "@testing-library/react": "^16.3.0",
59
- "@tsconfig/recommended": "^1.0.11",
58
+ "@testing-library/react": "^16.3.2",
59
+ "@tsconfig/recommended": "^1.0.13",
60
60
  "@types/jest": "^30.0.0",
61
61
  "@types/lodash-es": "^4.17.12",
62
62
  "@types/pretty": "^2.0.3",
63
- "@types/react": "^19.2.2",
64
- "@types/react-dom": "^19.2.2",
63
+ "@types/react": "^19.2.14",
64
+ "@types/react-dom": "^19.2.3",
65
65
  "babel-jest": "^30.2.0",
66
66
  "babel-plugin-add-import-extension": "^1.6.0",
67
67
  "babel-plugin-module-resolver": "^5.0.2",
68
68
  "jest": "^30.2.0",
69
69
  "jest-environment-jsdom": "^30.2.0",
70
70
  "mockdate": "^3.0.5",
71
- "rimraf": "^6.1.0",
72
- "tstyche": "^5.0.0",
71
+ "rimraf": "^6.1.2",
72
+ "tstyche": "^6.2.0",
73
73
  "typescript": "^5.9.3"
74
74
  },
75
75
  "peerDependencies": {
76
- "react": "^19.2.0",
77
- "react-dom": "^19.2.0"
76
+ "react": "^19.2.4",
77
+ "react-dom": "^19.2.4"
78
78
  }
79
79
  }
package/tsconfig.json CHANGED
@@ -1,5 +1,11 @@
1
1
  {
2
2
  "extends": "@tsconfig/recommended",
3
+
4
+ // TODO: This actually breaks VSCode code analysis inside ts-types. We should
5
+ // do no exclusion here, but provide a different TS config file for Jest tests
6
+ // to use.
7
+ "exclude": ["__tests__/ts-types"],
8
+
3
9
  "compilerOptions": {
4
10
  "declaration": true,
5
11
  "jsx": "react-jsx",