@dr.pogodin/react-global-state 0.18.0 → 0.19.0

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.
Files changed (57) hide show
  1. package/LICENSE.md +1 -1
  2. package/build/{module → code}/GlobalState.js +15 -5
  3. package/build/code/GlobalState.js.map +1 -0
  4. package/build/{module → code}/GlobalStateProvider.js +18 -18
  5. package/build/code/GlobalStateProvider.js.map +1 -0
  6. package/build/code/SsrContext.js.map +1 -0
  7. package/build/{module → code}/index.js +9 -3
  8. package/build/code/index.js.map +1 -0
  9. package/build/{module → code}/useAsyncCollection.js +60 -27
  10. package/build/code/useAsyncCollection.js.map +1 -0
  11. package/build/{module → code}/useAsyncData.js +19 -17
  12. package/build/code/useAsyncData.js.map +1 -0
  13. package/build/{module → code}/useGlobalState.js +25 -8
  14. package/build/code/useGlobalState.js.map +1 -0
  15. package/build/{module → code}/utils.js +1 -1
  16. package/build/code/utils.js.map +1 -0
  17. package/build/types/GlobalState.d.ts +2 -2
  18. package/build/types/GlobalStateProvider.d.ts +3 -3
  19. package/build/types/SsrContext.d.ts +3 -3
  20. package/build/types/useAsyncCollection.d.ts +4 -6
  21. package/build/types/useAsyncData.d.ts +2 -2
  22. package/build/types/utils.d.ts +2 -3
  23. package/eslint.config.mjs +19 -0
  24. package/package.json +25 -41
  25. package/build/common/GlobalState.js +0 -279
  26. package/build/common/GlobalState.js.map +0 -1
  27. package/build/common/GlobalStateProvider.js +0 -97
  28. package/build/common/GlobalStateProvider.js.map +0 -1
  29. package/build/common/SsrContext.js +0 -15
  30. package/build/common/SsrContext.js.map +0 -1
  31. package/build/common/index.js +0 -84
  32. package/build/common/index.js.map +0 -1
  33. package/build/common/useAsyncCollection.js +0 -242
  34. package/build/common/useAsyncCollection.js.map +0 -1
  35. package/build/common/useAsyncData.js +0 -233
  36. package/build/common/useAsyncData.js.map +0 -1
  37. package/build/common/useGlobalState.js +0 -134
  38. package/build/common/useGlobalState.js.map +0 -1
  39. package/build/common/utils.js +0 -91
  40. package/build/common/utils.js.map +0 -1
  41. package/build/module/GlobalState.js.map +0 -1
  42. package/build/module/GlobalStateProvider.js.map +0 -1
  43. package/build/module/SsrContext.js.map +0 -1
  44. package/build/module/index.js.map +0 -1
  45. package/build/module/useAsyncCollection.js.map +0 -1
  46. package/build/module/useAsyncData.js.map +0 -1
  47. package/build/module/useGlobalState.js.map +0 -1
  48. package/build/module/utils.js.map +0 -1
  49. package/src/GlobalState.ts +0 -342
  50. package/src/GlobalStateProvider.tsx +0 -117
  51. package/src/SsrContext.ts +0 -11
  52. package/src/index.ts +0 -84
  53. package/src/useAsyncCollection.ts +0 -471
  54. package/src/useAsyncData.ts +0 -362
  55. package/src/useGlobalState.ts +0 -225
  56. package/src/utils.ts +0 -116
  57. /package/build/{module → code}/SsrContext.js +0 -0
@@ -1,279 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _lodash = require("lodash");
8
- var _utils = require("./utils");
9
- const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
10
- class GlobalState {
11
- #asyncDataAbortCallbacks = {};
12
- #dependencies = {};
13
- #initialState;
14
-
15
- // TODO: It is tempting to replace watchers here by
16
- // Emitter from @dr.pogodin/js-utils, but we need to clone
17
- // current watchers for emitting later, and this is not something
18
- // Emitter supports right now.
19
- #watchers = [];
20
- #nextNotifierId;
21
- #currentState;
22
-
23
- /**
24
- * Creates a new global state object.
25
- * @param initialState Intial global state content.
26
- * @param ssrContext Server-side rendering context.
27
- */
28
- constructor(initialState, ssrContext) {
29
- this.#currentState = initialState;
30
- this.#initialState = initialState;
31
- if (ssrContext) {
32
- /* eslint-disable no-param-reassign */
33
- ssrContext.dirty = false;
34
- ssrContext.pending = [];
35
- ssrContext.state = this.#currentState;
36
- /* eslint-enable no-param-reassign */
37
-
38
- this.ssrContext = ssrContext;
39
- }
40
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
41
- /* eslint-disable no-console */
42
- let msg = 'New ReactGlobalState created';
43
- if (ssrContext) msg += ' (SSR mode)';
44
- console.groupCollapsed(msg);
45
- console.log('Initial state:', (0, _utils.cloneDeepForLog)(initialState));
46
- console.groupEnd();
47
- /* eslint-enable no-console */
48
- }
49
- }
50
-
51
- /**
52
- * Returns the number of currently registered async data abort callbacks,
53
- * just for the sake of testing the library.
54
- */
55
- get numAsyncDataAbortCallbacks() {
56
- return Object.keys(this.#asyncDataAbortCallbacks).length;
57
- }
58
-
59
- /**
60
- * If `aborted` is "true" and there is an abort callback registered for
61
- * the specified operation, it triggers the callback. Then, in any case,
62
- * it drops the callback.
63
- */
64
- asyncDataLoadDone(opid, aborted) {
65
- if (aborted) this.#asyncDataAbortCallbacks[opid]?.();
66
- delete this.#asyncDataAbortCallbacks[opid];
67
- }
68
-
69
- /**
70
- * Drops the record of dependencies, if any, for the given path.
71
- */
72
- dropDependencies(path) {
73
- delete this.#dependencies[path];
74
- }
75
-
76
- /**
77
- * Checks if given `deps` are different from previously recorded ones for
78
- * the given `path`. If they are, `deps` are recorded as the new deps for
79
- * the `path`, and also the array is frozen, to prevent it from being
80
- * modified.
81
- *
82
- * TODO: This may not work as expected if path string is not normalized,
83
- * and the for the same path different alternative ways to spell it down
84
- * are used. We should normalize given path here, I guess, or on a higher
85
- * level in the logic?
86
- */
87
- hasChangedDependencies(path, deps) {
88
- const prevDeps = this.#dependencies[path];
89
- let changed = !prevDeps || prevDeps.length !== deps.length;
90
- for (let i = 0; !changed && i < deps.length; ++i) {
91
- changed = prevDeps[i] !== deps[i];
92
- }
93
- this.#dependencies[path] = Object.freeze(deps);
94
- return changed;
95
- }
96
-
97
- /**
98
- * Gets entire state, the same way as .get(null, opts) would do.
99
- * @param opts.initialState
100
- * @param opts.initialValue
101
- */
102
- getEntireState(opts) {
103
- let state = opts?.initialState ? this.#initialState : this.#currentState;
104
- if (state !== undefined || opts?.initialValue === undefined) return state;
105
- const iv = opts.initialValue;
106
- state = (0, _lodash.isFunction)(iv) ? iv() : iv;
107
- if (this.#currentState === undefined) this.setEntireState(state);
108
- return state;
109
- }
110
-
111
- /**
112
- * Notifies all connected state watchers that a state update has happened.
113
- */
114
- notifyStateUpdate(path, value) {
115
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
116
- /* eslint-disable no-console */
117
- const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
118
- console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
119
- console.log('New value:', (0, _utils.cloneDeepForLog)(value, path ?? ''));
120
- console.log('New state:', (0, _utils.cloneDeepForLog)(this.#currentState));
121
- console.groupEnd();
122
- /* eslint-enable no-console */
123
- }
124
- if (this.ssrContext) {
125
- this.ssrContext.dirty = true;
126
- this.ssrContext.state = this.#currentState;
127
- } else if (!this.#nextNotifierId) {
128
- this.#nextNotifierId = setTimeout(() => {
129
- this.#nextNotifierId = undefined;
130
- const watchers = [...this.#watchers];
131
- for (let i = 0; i < watchers.length; ++i) {
132
- watchers[i]();
133
- }
134
- });
135
- }
136
- }
137
-
138
- /**
139
- * Registers an abort callback for an async data retrieval operation with
140
- * the given operation ID. Throws if already registered.
141
- */
142
- setAsyncDataAbortCallback(opid, cb) {
143
- this.#asyncDataAbortCallbacks[opid] = cb;
144
- }
145
-
146
- /**
147
- * Sets entire state, the same way as .set(null, value) would do.
148
- * @param value
149
- */
150
- setEntireState(value) {
151
- if (this.#currentState !== value) {
152
- this.#currentState = value;
153
- this.notifyStateUpdate(null, value);
154
- }
155
- return value;
156
- }
157
-
158
- /**
159
- * Gets current or initial value at the specified "path" of the global state.
160
- * @param path Dot-delimitered state path.
161
- * @param options Additional options.
162
- * @param options.initialState If "true" the value will be read
163
- * from the initial state instead of the current one.
164
- * @param options.initialValue If the value read from the "path" is
165
- * "undefined", this "initialValue" will be returned instead. In such case
166
- * "initialValue" will also be written to the "path" of the current global
167
- * state (no matter "initialState" flag), if "undefined" is stored there.
168
- * @return Retrieved value.
169
- */
170
-
171
- // .get() without arguments just falls back to .getEntireState().
172
-
173
- // This variant attempts to automatically resolve and check the type of value
174
- // at the given path, as precise as the actual state and path types permit.
175
- // If the automatic path resolution is not possible, the ValueT fallsback
176
- // to `never` (or to `undefined` in some cases), effectively forbidding
177
- // to use this .get() variant.
178
-
179
- // This variant is not callable by default (without generic arguments),
180
- // otherwise it allows to set the correct ValueT directly.
181
-
182
- get(path, opts) {
183
- if ((0, _lodash.isNil)(path)) {
184
- const res = this.getEntireState(opts);
185
- return res;
186
- }
187
- const state = opts?.initialState ? this.#initialState : this.#currentState;
188
- let res = (0, _lodash.get)(state, path);
189
- if (res !== undefined || opts?.initialValue === undefined) return res;
190
- const iv = opts.initialValue;
191
- res = (0, _lodash.isFunction)(iv) ? iv() : iv;
192
- if (!opts?.initialState || this.get(path) === undefined) {
193
- this.set(path, res);
194
- }
195
- return res;
196
- }
197
-
198
- /**
199
- * Writes the `value` to given global state `path`.
200
- * @param path Dot-delimitered state path. If not given, entire
201
- * global state content is replaced by the `value`.
202
- * @param value The value.
203
- * @return Given `value` itself.
204
- */
205
-
206
- // This variant attempts automatic value type resolution & checking.
207
-
208
- // This variant is disabled by default, otherwise allows to give
209
- // expected value type explicitly.
210
-
211
- set(path, value) {
212
- if ((0, _lodash.isNil)(path)) return this.setEntireState(value);
213
- if (value !== this.get(path)) {
214
- const root = {
215
- state: this.#currentState
216
- };
217
- let segIdx = 0;
218
- let pos = root;
219
- const pathSegments = (0, _lodash.toPath)(`state.${path}`);
220
- for (; segIdx < pathSegments.length - 1; segIdx += 1) {
221
- const seg = pathSegments[segIdx];
222
- const next = pos[seg];
223
- if (Array.isArray(next)) pos[seg] = [...next];else if ((0, _lodash.isObject)(next)) pos[seg] = {
224
- ...next
225
- };else {
226
- // We arrived to a state sub-segment, where the remaining part of
227
- // the update path does not exist yet. We rely on lodash's set()
228
- // function to create the remaining path, and set the value.
229
- (0, _lodash.set)(pos, pathSegments.slice(segIdx), value);
230
- break;
231
- }
232
- pos = pos[seg];
233
- }
234
- if (segIdx === pathSegments.length - 1) {
235
- pos[pathSegments[segIdx]] = value;
236
- }
237
- this.#currentState = root.state;
238
- this.notifyStateUpdate(path, value);
239
- }
240
- return value;
241
- }
242
-
243
- /**
244
- * Unsubscribes `callback` from watching state updates; no operation if
245
- * `callback` is not subscribed to the state updates.
246
- * @param callback
247
- * @throws if {@link SsrContext} is attached to the state instance: the state
248
- * watching functionality is intended for client-side (non-SSR) only.
249
- */
250
- unWatch(callback) {
251
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
252
- const watchers = this.#watchers;
253
- const pos = watchers.indexOf(callback);
254
- if (pos >= 0) {
255
- watchers[pos] = watchers[watchers.length - 1];
256
- watchers.pop();
257
- }
258
- }
259
-
260
- /**
261
- * Subscribes `callback` to watch state updates; no operation if
262
- * `callback` is already subscribed to this state instance.
263
- * @param callback It will be called without any arguments every
264
- * time the state content changes (note, howhever, separate state updates can
265
- * be applied to the state at once, and watching callbacks will be called once
266
- * after such bulk update).
267
- * @throws if {@link SsrContext} is attached to the state instance: the state
268
- * watching functionality is intended for client-side (non-SSR) only.
269
- */
270
- watch(callback) {
271
- if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
272
- const watchers = this.#watchers;
273
- if (watchers.indexOf(callback) < 0) {
274
- watchers.push(callback);
275
- }
276
- }
277
- }
278
- exports.default = GlobalState;
279
- //# sourceMappingURL=GlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalState.js","names":["_lodash","require","_utils","ERR_NO_SSR_WATCH","GlobalState","asyncDataAbortCallbacks","dependencies","initialState","watchers","nextNotifierId","currentState","constructor","ssrContext","dirty","pending","state","process","env","NODE_ENV","isDebugMode","msg","console","groupCollapsed","log","cloneDeepForLog","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","freeze","getEntireState","opts","undefined","initialValue","iv","isFunction","setEntireState","notifyStateUpdate","value","p","setTimeout","setAsyncDataAbortCallback","cb","get","isNil","res","set","root","segIdx","pos","pathSegments","toPath","seg","next","Array","isArray","isObject","slice","unWatch","callback","Error","indexOf","pop","watch","push","exports","default"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\n\nimport 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: { [key: string]: Readonly<any[]> } = {};\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) {\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) {\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: any[]): 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 = isFunction(iv) ? iv() : 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 (let i = 0; i < watchers.length; ++i) {\n watchers[i]!();\n }\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) {\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 (isNil(path)) {\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);\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = isFunction(iv) ? iv() : iv;\n\n if (!opts?.initialState || this.get(path) === 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 (isNil(path)) return this.setEntireState(value as StateT);\n\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n let pos: any = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...next];\n else if (isObject(next)) 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];\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) {\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) {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (watchers.indexOf(callback) < 0) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAWA,IAAAC,MAAA,GAAAD,OAAA;AAWA,MAAME,gBAAgB,GAAG,gDAAgD;AAO1D,MAAMC,WAAW,CAG9B;EAGA,CAACC,uBAAuB,GAA+B,CAAC,CAAC;EAEzD,CAACC,YAAY,GAAuC,CAAC,CAAC;EAEtD,CAACC,YAAY;;EAEb;EACA;EACA;EACA;EACA,CAACC,QAAQ,GAAgB,EAAE;EAE3B,CAACC,cAAc;EAEf,CAACC,YAAY;;EAEb;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTJ,YAAoB,EACpBK,UAAwB,EACxB;IACA,IAAI,CAA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3B,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACpE,gBAAgB,CAAC;IAEtD,MAAMK,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,MAAMoD,GAAG,GAAGpD,QAAQ,CAACgE,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIV,GAAG,IAAI,CAAC,EAAE;MACZpD,QAAQ,CAACoD,GAAG,CAAC,GAAGpD,QAAQ,CAACA,QAAQ,CAACqB,MAAM,GAAG,CAAC,CAAE;MAC9CrB,QAAQ,CAACiE,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAE;IACzB,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACpE,gBAAgB,CAAC;IAEtD,MAAMK,QAAQ,GAAG,IAAI,CAAC,CAACA,QAAQ;IAC/B,IAAIA,QAAQ,CAACgE,OAAO,CAACF,QAAQ,CAAC,GAAG,CAAC,EAAE;MAClC9D,QAAQ,CAACmE,IAAI,CAACL,QAAQ,CAAC;IACzB;EACF;AACF;AAACM,OAAA,CAAAC,OAAA,GAAAzE,WAAA","ignoreList":[]}
@@ -1,97 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.default = void 0;
8
- exports.getGlobalState = getGlobalState;
9
- exports.getSsrContext = getSsrContext;
10
- var _lodash = require("lodash");
11
- var _react = require("react");
12
- var _GlobalState = _interopRequireDefault(require("./GlobalState"));
13
- var _jsxRuntime = require("react/jsx-runtime");
14
- const Context = /*#__PURE__*/(0, _react.createContext)(null);
15
-
16
- /**
17
- * Gets {@link GlobalState} instance from the context. In most cases
18
- * you should use {@link useGlobalState}, and other hooks to interact with
19
- * the global state, instead of accessing it directly.
20
- * @return
21
- */
22
- function getGlobalState() {
23
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
24
- // convention that hook names should start with use... This is intentional in
25
- // our case, as getGlobalState() hook is intended for advance scenarious,
26
- // while the normal interaction with the global state should happen via
27
- // another hook, useGlobalState().
28
- /* eslint-disable react-hooks/rules-of-hooks */
29
- const globalState = (0, _react.use)(Context);
30
- /* eslint-enable react-hooks/rules-of-hooks */
31
- if (!globalState) throw new Error('Missing GlobalStateProvider');
32
- return globalState;
33
- }
34
-
35
- /**
36
- * @category Hooks
37
- * @desc Gets SSR context.
38
- * @param throwWithoutSsrContext If `true` (default),
39
- * this hook will throw if no SSR context is attached to the global state;
40
- * set `false` to not throw in such case. In either case the hook will throw
41
- * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.
42
- * @returns SSR context.
43
- * @throws
44
- * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}
45
- * in the rendered React tree.
46
- * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
47
- * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
48
- */
49
- function getSsrContext(throwWithoutSsrContext = true) {
50
- const {
51
- ssrContext
52
- } = getGlobalState();
53
- if (!ssrContext && throwWithoutSsrContext) {
54
- throw new Error('No SSR context found');
55
- }
56
- return ssrContext;
57
- }
58
- /**
59
- * Provides global state to its children.
60
- * @param prop.children Component children, which will be provided with
61
- * the global state, and rendered in place of the provider.
62
- * @param prop.initialState Initial content of the global state.
63
- * @param prop.ssrContext Server-side rendering (SSR) context.
64
- * @param prop.stateProxy This option is useful for code
65
- * splitting and SSR implementation:
66
- * - If `true`, this provider instance will fetch and reuse the global state
67
- * from a parent provider.
68
- * - If `GlobalState` instance, it will be used by this provider.
69
- * - If not given, a new `GlobalState` instance will be created and used.
70
- */
71
- const GlobalStateProvider = ({
72
- children,
73
- ...rest
74
- }) => {
75
- const state = (0, _react.useRef)(undefined);
76
- if (!state.current) {
77
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
78
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
79
- // is given, we want to follow the second branch, which creates a new
80
- // GlobalState with whatever intiialState given.
81
- if ('stateProxy' in rest && rest.stateProxy) {
82
- if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
83
- } else {
84
- const {
85
- initialState,
86
- ssrContext
87
- } = rest;
88
- state.current = new _GlobalState.default((0, _lodash.isFunction)(initialState) ? initialState() : initialState, ssrContext);
89
- }
90
- }
91
- return /*#__PURE__*/(0, _jsxRuntime.jsx)(Context, {
92
- value: state.current,
93
- children: children
94
- });
95
- };
96
- var _default = exports.default = GlobalStateProvider;
97
- //# sourceMappingURL=GlobalStateProvider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["_lodash","require","_react","_GlobalState","_interopRequireDefault","_jsxRuntime","Context","createContext","getGlobalState","globalState","use","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","state","useRef","undefined","current","stateProxy","initialState","GlobalState","isFunction","jsx","value","_default","exports","default"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport 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 // Here Rules of Hooks are violated because \"getGlobalState()\" does not follow\n // convention that hook names should start with use... This is intentional in\n // our case, as getGlobalState() hook is intended for advance scenarious,\n // while the normal interaction with the global state should happen via\n // another hook, useGlobalState().\n /* eslint-disable react-hooks/rules-of-hooks */\n const globalState = use(Context);\n /* eslint-enable react-hooks/rules-of-hooks */\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>({ children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>) => {\n const state = useRef<GlobalState<StateT, SsrContextT>>(undefined);\n if (!state.current) {\n // NOTE: The last part of condition, \"&& rest.stateProxy\", is needed for\n // graceful compatibility with JavaScript - if \"undefined\" stateProxy value\n // is given, we want to follow the second branch, which creates a new\n // GlobalState with whatever intiialState given.\n if ('stateProxy' in rest && rest.stateProxy) {\n if (rest.stateProxy === true) state.current = getGlobalState();\n else state.current = rest.stateProxy;\n } else {\n const { initialState, ssrContext } = rest as NewStateProps<StateT, SsrContextT>;\n\n state.current = new GlobalState<StateT, SsrContextT>(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n }\n return <Context value={state.current}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AAOA,IAAAE,YAAA,GAAAC,sBAAA,CAAAH,OAAA;AAAwC,IAAAI,WAAA,GAAAJ,OAAA;AAKxC,MAAMK,OAAO,gBAAG,IAAAC,oBAAa,EAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,cAAcA,CAAA,EAGQ;EACpC;EACA;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAG,IAAAC,UAAG,EAACJ,OAAO,CAAC;EAChC;EACA,IAAI,CAACG,WAAW,EAAE,MAAM,IAAIE,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOF,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASG,aAAaA,CAG3BC,sBAAsB,GAAG,IAAI,EACJ;EACzB,MAAM;IAAEC;EAAW,CAAC,GAAGN,cAAc,CAAoC,CAAC;EAC1E,IAAI,CAACM,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,CAG1B;EAAEC,QAAQ;EAAE,GAAGC;AAAoD,CAAC,KAAK;EACzE,MAAMC,KAAK,GAAG,IAAAC,aAAM,EAAmCC,SAAS,CAAC;EACjE,IAAI,CAACF,KAAK,CAACG,OAAO,EAAE;IAClB;IACA;IACA;IACA;IACA,IAAI,YAAY,IAAIJ,IAAI,IAAIA,IAAI,CAACK,UAAU,EAAE;MAC3C,IAAIL,IAAI,CAACK,UAAU,KAAK,IAAI,EAAEJ,KAAK,CAACG,OAAO,GAAGb,cAAc,CAAC,CAAC,CAAC,KAC1DU,KAAK,CAACG,OAAO,GAAGJ,IAAI,CAACK,UAAU;IACtC,CAAC,MAAM;MACL,MAAM;QAAEC,YAAY;QAAET;MAAW,CAAC,GAAGG,IAA0C;MAE/EC,KAAK,CAACG,OAAO,GAAG,IAAIG,oBAAW,CAC7B,IAAAC,kBAAU,EAACF,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDT,UACF,CAAC;IACH;EACF;EACA,oBAAO,IAAAT,WAAA,CAAAqB,GAAA,EAACpB,OAAO;IAACqB,KAAK,EAAET,KAAK,CAACG,OAAQ;IAAAL,QAAA,EAAEA;EAAQ,CAAU,CAAC;AAC5D,CAAC;AAAC,IAAAY,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaf,mBAAmB","ignoreList":[]}
@@ -1,15 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- class SsrContext {
8
- dirty = false;
9
- pending = [];
10
- constructor(state) {
11
- this.state = state;
12
- }
13
- }
14
- exports.default = SsrContext;
15
- //# sourceMappingURL=SsrContext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"SsrContext.js","names":["SsrContext","dirty","pending","constructor","state","exports","default"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Promise<void>[] = [];\n\n state?: StateT;\n\n constructor(state?: StateT) {\n this.state = state;\n }\n}\n"],"mappings":";;;;;;AAAe,MAAMA,UAAU,CAAS;EACtCC,KAAK,GAAY,KAAK;EAEtBC,OAAO,GAAoB,EAAE;EAI7BC,WAAWA,CAACC,KAAc,EAAE;IAC1B,IAAI,CAACA,KAAK,GAAGA,KAAK;EACpB;AACF;AAACC,OAAA,CAAAC,OAAA,GAAAN,UAAA","ignoreList":[]}
@@ -1,84 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- Object.defineProperty(exports, "GlobalState", {
8
- enumerable: true,
9
- get: function () {
10
- return _GlobalState.default;
11
- }
12
- });
13
- Object.defineProperty(exports, "GlobalStateProvider", {
14
- enumerable: true,
15
- get: function () {
16
- return _GlobalStateProvider.default;
17
- }
18
- });
19
- Object.defineProperty(exports, "SsrContext", {
20
- enumerable: true,
21
- get: function () {
22
- return _SsrContext.default;
23
- }
24
- });
25
- Object.defineProperty(exports, "getGlobalState", {
26
- enumerable: true,
27
- get: function () {
28
- return _GlobalStateProvider.getGlobalState;
29
- }
30
- });
31
- Object.defineProperty(exports, "getSsrContext", {
32
- enumerable: true,
33
- get: function () {
34
- return _GlobalStateProvider.getSsrContext;
35
- }
36
- });
37
- Object.defineProperty(exports, "newAsyncDataEnvelope", {
38
- enumerable: true,
39
- get: function () {
40
- return _useAsyncData.newAsyncDataEnvelope;
41
- }
42
- });
43
- Object.defineProperty(exports, "useAsyncCollection", {
44
- enumerable: true,
45
- get: function () {
46
- return _useAsyncCollection.default;
47
- }
48
- });
49
- Object.defineProperty(exports, "useAsyncData", {
50
- enumerable: true,
51
- get: function () {
52
- return _useAsyncData.useAsyncData;
53
- }
54
- });
55
- Object.defineProperty(exports, "useGlobalState", {
56
- enumerable: true,
57
- get: function () {
58
- return _useGlobalState.default;
59
- }
60
- });
61
- exports.withGlobalStateType = withGlobalStateType;
62
- var _GlobalState = _interopRequireDefault(require("./GlobalState"));
63
- var _GlobalStateProvider = _interopRequireWildcard(require("./GlobalStateProvider"));
64
- var _SsrContext = _interopRequireDefault(require("./SsrContext"));
65
- var _useAsyncCollection = _interopRequireDefault(require("./useAsyncCollection"));
66
- var _useAsyncData = require("./useAsyncData");
67
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
68
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
69
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
70
- const api = {
71
- getGlobalState: _GlobalStateProvider.getGlobalState,
72
- getSsrContext: _GlobalStateProvider.getSsrContext,
73
- GlobalState: _GlobalState.default,
74
- GlobalStateProvider: _GlobalStateProvider.default,
75
- newAsyncDataEnvelope: _useAsyncData.newAsyncDataEnvelope,
76
- SsrContext: _SsrContext.default,
77
- useAsyncCollection: _useAsyncCollection.default,
78
- useAsyncData: _useAsyncData.useAsyncData,
79
- useGlobalState: _useGlobalState.default
80
- };
81
- function withGlobalStateType() {
82
- return api;
83
- }
84
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","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 { AsyncCollectionLoaderT, AsyncCollectionT } 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\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 getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAL,OAAA;AAWA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAAwE,SAAAO,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAA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