@choksheak/react-utils 0.4.4 → 0.4.5
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.
- package/NoSSR.cjs +30 -7
- package/NoSSR.min.cjs +1 -1
- package/NoSSR.min.cjs.map +1 -1
- package/NoSSR.min.mjs +1 -1
- package/NoSSR.min.mjs.map +1 -1
- package/NoSSR.mjs +0 -2
- package/index.cjs +979 -43
- package/index.d.cts +1 -1
- package/index.d.ts +1 -1
- package/index.min.cjs +1 -1
- package/index.min.cjs.map +1 -1
- package/index.min.mjs +1 -1
- package/index.min.mjs.map +1 -1
- package/index.mjs +916 -25
- package/package.json +1 -41
- package/sharedQuery.cjs +938 -10
- package/sharedQuery.d.cts +21 -20
- package/sharedQuery.d.ts +21 -20
- package/sharedQuery.min.cjs +1 -1
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.mjs +1 -1
- package/sharedQuery.min.mjs.map +1 -1
- package/sharedQuery.mjs +906 -10
- package/sharedState.cjs +326 -15
- package/sharedState.min.cjs +1 -1
- package/sharedState.min.cjs.map +1 -1
- package/sharedState.min.mjs +1 -1
- package/sharedState.min.mjs.map +1 -1
- package/sharedState.mjs +291 -10
- package/storage.cjs +129 -10
- package/storage.min.cjs +1 -1
- package/storage.min.cjs.map +1 -1
- package/storage.min.mjs +1 -1
- package/storage.min.mjs.map +1 -1
- package/storage.mjs +98 -6
- package/stringify.cjs +57 -6
- package/stringify.min.cjs +1 -1
- package/stringify.min.cjs.map +1 -1
- package/stringify.min.mjs +1 -1
- package/stringify.min.mjs.map +1 -1
- package/stringify.mjs +30 -4
- package/useDeepMemo.cjs +40 -6
- package/useDeepMemo.min.cjs +1 -1
- package/useDeepMemo.min.cjs.map +1 -1
- package/useDeepMemo.min.mjs +1 -1
- package/useDeepMemo.min.mjs.map +1 -1
- package/useDeepMemo.mjs +13 -4
- package/chunk-4235I4VO.mjs +0 -34
- package/chunk-433OAJVP.min.cjs +0 -2
- package/chunk-433OAJVP.min.cjs.map +0 -1
- package/chunk-4J7TN5JN.mjs +0 -17
- package/chunk-5PDGU37E.cjs +0 -104
- package/chunk-7D2YNZO3.cjs +0 -577
- package/chunk-BQIRLDQC.min.mjs +0 -2
- package/chunk-BQIRLDQC.min.mjs.map +0 -1
- package/chunk-CYTO5EZE.cjs +0 -34
- package/chunk-FXCYHS3L.mjs +0 -577
- package/chunk-HRE7YPUJ.min.mjs +0 -2
- package/chunk-HRE7YPUJ.min.mjs.map +0 -1
- package/chunk-IS3BZTWE.cjs +0 -35
- package/chunk-JOHZV3FD.min.cjs +0 -2
- package/chunk-JOHZV3FD.min.cjs.map +0 -1
- package/chunk-KGN4HQPP.min.cjs +0 -2
- package/chunk-KGN4HQPP.min.cjs.map +0 -1
- package/chunk-NGGNAAHA.cjs +0 -203
- package/chunk-NL4FU2MJ.min.mjs +0 -2
- package/chunk-NL4FU2MJ.min.mjs.map +0 -1
- package/chunk-PHLY3LR4.mjs +0 -104
- package/chunk-R7POPVJR.mjs +0 -35
- package/chunk-RP2TWHFU.min.cjs +0 -2
- package/chunk-RP2TWHFU.min.cjs.map +0 -1
- package/chunk-TI3FMEYP.min.mjs +0 -2
- package/chunk-TI3FMEYP.min.mjs.map +0 -1
- package/chunk-UFJQLQFI.min.cjs +0 -2
- package/chunk-UFJQLQFI.min.cjs.map +0 -1
- package/chunk-VHMO75EY.min.mjs +0 -2
- package/chunk-VHMO75EY.min.mjs.map +0 -1
- package/chunk-WXLUEDBO.cjs +0 -17
- package/chunk-XRHQCN2J.min.mjs +0 -2
- package/chunk-XRHQCN2J.min.mjs.map +0 -1
- package/chunk-YHU4KW2D.mjs +0 -203
- package/chunk-ZCDXPV3A.min.cjs +0 -2
- package/chunk-ZCDXPV3A.min.cjs.map +0 -1
- package/dist-O6NNX4Y3.min.mjs +0 -2
- package/dist-O6NNX4Y3.min.mjs.map +0 -1
- package/dist-SEGTJ72R.min.cjs +0 -2
- package/dist-SEGTJ72R.min.cjs.map +0 -1
- package/dist-UKP7SPWZ.cjs +0 -545
- package/dist-YXYQDOH5.mjs +0 -545
- package/magic-string.es-5QZEPJXJ.min.mjs +0 -14
- package/magic-string.es-5QZEPJXJ.min.mjs.map +0 -1
- package/magic-string.es-EREYSDLL.mjs +0 -1308
- package/magic-string.es-FXUUD55Y.min.cjs +0 -14
- package/magic-string.es-FXUUD55Y.min.cjs.map +0 -1
- package/magic-string.es-HC5PDAU3.cjs +0 -1308
package/sharedState.cjs
CHANGED
|
@@ -1,18 +1,329 @@
|
|
|
1
|
-
"use strict";
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
2
19
|
|
|
20
|
+
// src/sharedState.ts
|
|
21
|
+
var sharedState_exports = {};
|
|
22
|
+
__export(sharedState_exports, {
|
|
23
|
+
SharedStateConfig: () => SharedStateConfig,
|
|
24
|
+
configureSharedState: () => configureSharedState,
|
|
25
|
+
sharedState: () => sharedState,
|
|
26
|
+
useSharedState: () => useSharedState,
|
|
27
|
+
useSharedStateSetter: () => useSharedStateSetter,
|
|
28
|
+
useSharedStateValue: () => useSharedStateValue
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(sharedState_exports);
|
|
31
|
+
var import_timeConstants = require("@choksheak/ts-utils/timeConstants");
|
|
32
|
+
var import_react = require("react");
|
|
3
33
|
|
|
34
|
+
// src/storage.ts
|
|
35
|
+
var import_kvStore = require("@choksheak/ts-utils/kvStore");
|
|
36
|
+
var import_localStore = require("@choksheak/ts-utils/localStore");
|
|
37
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
38
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
39
|
+
const { store } = options ?? {};
|
|
40
|
+
if (!store) {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
|
|
44
|
+
const expiryMs = store.expiryMs || defaultStoreExpiryMs;
|
|
45
|
+
const config = { ...store, expiryMs };
|
|
46
|
+
switch (store.persistTo) {
|
|
47
|
+
case "localStorage":
|
|
48
|
+
return localStoreAdapter(config);
|
|
49
|
+
case "indexedDb":
|
|
50
|
+
return kvStoreAdapter(config);
|
|
51
|
+
default:
|
|
52
|
+
store.persistTo;
|
|
53
|
+
throw new Error(`Unknown store.adapter ${store.persistTo}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return store;
|
|
57
|
+
}
|
|
58
|
+
function localStoreAdapter({
|
|
59
|
+
key,
|
|
60
|
+
expiryMs,
|
|
61
|
+
isValid
|
|
62
|
+
}) {
|
|
63
|
+
const STORE_NAME = "react-utils";
|
|
64
|
+
const adapter = (0, import_localStore.createLocalStore)(STORE_NAME, {
|
|
65
|
+
defaultExpiryMs: expiryMs
|
|
66
|
+
});
|
|
67
|
+
const keyPrefix = key + ":";
|
|
68
|
+
return {
|
|
69
|
+
set: (key2, value) => {
|
|
70
|
+
if (IS_NOT_BROWSER) return;
|
|
71
|
+
adapter.set(keyPrefix + key2, value);
|
|
72
|
+
},
|
|
73
|
+
get: (key2) => {
|
|
74
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
75
|
+
const fullKey = keyPrefix + key2;
|
|
76
|
+
const value = adapter.get(fullKey);
|
|
77
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
78
|
+
console.warn(
|
|
79
|
+
`localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
|
|
80
|
+
);
|
|
81
|
+
adapter.delete(fullKey);
|
|
82
|
+
return void 0;
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
},
|
|
86
|
+
delete: (key2) => {
|
|
87
|
+
if (IS_NOT_BROWSER) return;
|
|
88
|
+
adapter.delete(keyPrefix + key2);
|
|
89
|
+
},
|
|
90
|
+
/** Note that this will clear all keys in all shared states. */
|
|
91
|
+
clear: () => {
|
|
92
|
+
if (IS_NOT_BROWSER) return;
|
|
93
|
+
adapter.clear();
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function kvStoreAdapter({
|
|
98
|
+
key,
|
|
99
|
+
expiryMs,
|
|
100
|
+
isValid
|
|
101
|
+
}) {
|
|
102
|
+
const keyPrefix = key + ":";
|
|
103
|
+
return {
|
|
104
|
+
set: async (key2, value) => {
|
|
105
|
+
if (IS_NOT_BROWSER) return;
|
|
106
|
+
await import_kvStore.kvStore.set(keyPrefix + key2, value, expiryMs);
|
|
107
|
+
},
|
|
108
|
+
get: async (key2) => {
|
|
109
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
110
|
+
const fullKey = keyPrefix + key2;
|
|
111
|
+
const value = await import_kvStore.kvStore.get(fullKey);
|
|
112
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
113
|
+
console.warn(
|
|
114
|
+
`indexedDb adapter: Auto-discard invalid value for ${key2}:`,
|
|
115
|
+
value
|
|
116
|
+
);
|
|
117
|
+
await import_kvStore.kvStore.delete(fullKey);
|
|
118
|
+
return void 0;
|
|
119
|
+
}
|
|
120
|
+
return value;
|
|
121
|
+
},
|
|
122
|
+
delete: async (key2) => {
|
|
123
|
+
if (IS_NOT_BROWSER) return;
|
|
124
|
+
await import_kvStore.kvStore.delete(keyPrefix + key2);
|
|
125
|
+
},
|
|
126
|
+
clear: async () => {
|
|
127
|
+
if (IS_NOT_BROWSER) return;
|
|
128
|
+
await import_kvStore.kvStore.clear();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
4
132
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
133
|
+
// src/sharedState.ts
|
|
134
|
+
var SharedStateConfig = {
|
|
135
|
+
/**
|
|
136
|
+
* Default duration for storage expiration in milliseconds. Initial value
|
|
137
|
+
* is 30 days, but can be changed to anything.
|
|
138
|
+
*/
|
|
139
|
+
storeExpiryMs: 30 * import_timeConstants.MS_PER_DAY,
|
|
140
|
+
/**
|
|
141
|
+
* True to load from storage only on mount, false (default) to load in
|
|
142
|
+
* the top level scope when the shared state is defined.
|
|
143
|
+
*/
|
|
144
|
+
lazyLoad: false
|
|
145
|
+
};
|
|
146
|
+
function configureSharedState(config) {
|
|
147
|
+
Object.assign(SharedStateConfig, config);
|
|
148
|
+
}
|
|
149
|
+
function createPubSubStore() {
|
|
150
|
+
const dataByKey = /* @__PURE__ */ new Map();
|
|
151
|
+
const subscribersByKey = /* @__PURE__ */ new Map();
|
|
152
|
+
function notify(key, next, prev) {
|
|
153
|
+
const subscribers = subscribersByKey.get(key);
|
|
154
|
+
if (!subscribers) return;
|
|
155
|
+
const copy = Array.from(subscribers.values());
|
|
156
|
+
for (const subscriber of copy) {
|
|
157
|
+
try {
|
|
158
|
+
subscriber(next, prev);
|
|
159
|
+
} catch (e) {
|
|
160
|
+
console.error(`Error invoking subscriber:`, e);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
// This could be undefined if T includes undefined, else it should never
|
|
166
|
+
// return undefined because the user has to always specify the default value.
|
|
167
|
+
get(key) {
|
|
168
|
+
return dataByKey.get(key);
|
|
169
|
+
},
|
|
170
|
+
set(key, value) {
|
|
171
|
+
const prev = dataByKey.get(key);
|
|
172
|
+
if (prev === value) return;
|
|
173
|
+
dataByKey.set(key, value);
|
|
174
|
+
notify(key, value, prev);
|
|
175
|
+
},
|
|
176
|
+
delete(key) {
|
|
177
|
+
dataByKey.delete(key);
|
|
178
|
+
},
|
|
179
|
+
setNoNotify(key, value) {
|
|
180
|
+
dataByKey.set(key, value);
|
|
181
|
+
},
|
|
182
|
+
// Subscribe to changes of a specific key
|
|
183
|
+
subscribe(key, subscriber) {
|
|
184
|
+
let subscribers = subscribersByKey.get(key);
|
|
185
|
+
if (!subscribers) {
|
|
186
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
187
|
+
subscribersByKey.set(key, subscribers);
|
|
188
|
+
}
|
|
189
|
+
subscribers.add(subscriber);
|
|
190
|
+
return () => {
|
|
191
|
+
subscribers.delete(subscriber);
|
|
192
|
+
if (subscribers.size === 0) subscribersByKey.delete(key);
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function getOrCreatePubSubStore() {
|
|
198
|
+
if (typeof window !== "undefined") {
|
|
199
|
+
const t = window.globalThis;
|
|
200
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
201
|
+
}
|
|
202
|
+
return createPubSubStore();
|
|
203
|
+
}
|
|
204
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
205
|
+
var STORAGE_KEY = "state";
|
|
206
|
+
var stateKey = 0;
|
|
207
|
+
function sharedState(defaultValue, options) {
|
|
208
|
+
let readyResolve = () => {
|
|
209
|
+
};
|
|
210
|
+
const readyPromise = new Promise((resolve) => {
|
|
211
|
+
readyResolve = resolve;
|
|
212
|
+
});
|
|
213
|
+
const resolveReadyPromise = readyResolve;
|
|
214
|
+
const pubSubKey = String(stateKey++);
|
|
215
|
+
const storageAdapter = getStorageAdapter(
|
|
216
|
+
options,
|
|
217
|
+
SharedStateConfig.storeExpiryMs
|
|
218
|
+
);
|
|
219
|
+
pubSubStore.setNoNotify(pubSubKey, defaultValue);
|
|
220
|
+
const lazyLoad = options?.lazyLoad;
|
|
221
|
+
const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
|
|
222
|
+
function completeInit(stored) {
|
|
223
|
+
const value = stored !== void 0 ? stored : defaultValue;
|
|
224
|
+
pubSubStore.set(pubSubKey, value);
|
|
225
|
+
obj.initDone = true;
|
|
226
|
+
resolveReadyPromise();
|
|
227
|
+
}
|
|
228
|
+
const obj = {
|
|
229
|
+
defaultValue,
|
|
230
|
+
/** Allow users to await for the completion of data init. */
|
|
231
|
+
readyPromise,
|
|
232
|
+
lazy,
|
|
233
|
+
initStarted: false,
|
|
234
|
+
initDone: false,
|
|
235
|
+
/** `subscribe` function required by useSyncExternalStore. */
|
|
236
|
+
subscribe(subscriber) {
|
|
237
|
+
return pubSubStore.subscribe(pubSubKey, () => subscriber());
|
|
238
|
+
},
|
|
239
|
+
/** Returns true if there is a backing store. */
|
|
240
|
+
hasStore() {
|
|
241
|
+
return Boolean(storageAdapter);
|
|
242
|
+
},
|
|
243
|
+
/**
|
|
244
|
+
* Set a value directly into the store. Does nothing if there is no
|
|
245
|
+
* backing store.
|
|
246
|
+
*
|
|
247
|
+
* Warning: If you want to set the value properly, you should use
|
|
248
|
+
* `setValue()` instead which also updates the in-memory copy.
|
|
249
|
+
*/
|
|
250
|
+
setInStore(value) {
|
|
251
|
+
return storageAdapter?.set(STORAGE_KEY, value);
|
|
252
|
+
},
|
|
253
|
+
/**
|
|
254
|
+
* Get a value directly from the store. Returns undefined if there is no
|
|
255
|
+
* backing store.
|
|
256
|
+
*/
|
|
257
|
+
getFromStore() {
|
|
258
|
+
return storageAdapter?.get(STORAGE_KEY);
|
|
259
|
+
},
|
|
260
|
+
/**
|
|
261
|
+
* Get the value of the shared state.
|
|
262
|
+
* `getSnapshot` function — must return same ref if value unchanged.
|
|
263
|
+
* Note that this would return the default value if data init from store is
|
|
264
|
+
* not completed yet.
|
|
265
|
+
*/
|
|
266
|
+
getSnapshot() {
|
|
267
|
+
return pubSubStore.get(pubSubKey);
|
|
268
|
+
},
|
|
269
|
+
/** Set the value of the shared state. */
|
|
270
|
+
setValue(next) {
|
|
271
|
+
if (typeof next === "function") {
|
|
272
|
+
const prev = pubSubStore.get(pubSubKey);
|
|
273
|
+
next = next(prev);
|
|
274
|
+
}
|
|
275
|
+
pubSubStore.set(pubSubKey, next);
|
|
276
|
+
void obj.setInStore(next);
|
|
277
|
+
},
|
|
278
|
+
/**
|
|
279
|
+
* Remove the value of the shared state. Actually this just sets the value
|
|
280
|
+
* back to the given default value.
|
|
281
|
+
*/
|
|
282
|
+
delete() {
|
|
283
|
+
pubSubStore.set(pubSubKey, defaultValue);
|
|
284
|
+
return storageAdapter?.set(STORAGE_KEY, defaultValue);
|
|
285
|
+
},
|
|
286
|
+
/** Initial default handling. */
|
|
287
|
+
initDefaultValueOnce() {
|
|
288
|
+
if (obj.initDone || obj.initStarted) return;
|
|
289
|
+
obj.initStarted = true;
|
|
290
|
+
const maybePromise = obj.getFromStore();
|
|
291
|
+
if (maybePromise instanceof Promise) {
|
|
292
|
+
return maybePromise.then(completeInit);
|
|
293
|
+
} else {
|
|
294
|
+
const stored = maybePromise;
|
|
295
|
+
completeInit(stored);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
if (!lazy) {
|
|
300
|
+
obj.initDefaultValueOnce();
|
|
301
|
+
}
|
|
302
|
+
return obj;
|
|
303
|
+
}
|
|
304
|
+
function useSharedState(state) {
|
|
305
|
+
void state.initDefaultValueOnce();
|
|
306
|
+
const value = (0, import_react.useSyncExternalStore)(
|
|
307
|
+
(onStoreChange) => state.subscribe(onStoreChange),
|
|
308
|
+
() => state.getSnapshot(),
|
|
309
|
+
// getServerSnapshot is needed to prevent SSR dev errors in nextjs.
|
|
310
|
+
() => state.getSnapshot()
|
|
311
|
+
);
|
|
312
|
+
return [value, state.setValue];
|
|
313
|
+
}
|
|
314
|
+
function useSharedStateValue(state) {
|
|
315
|
+
return useSharedState(state)[0];
|
|
316
|
+
}
|
|
317
|
+
function useSharedStateSetter(state) {
|
|
318
|
+
void state.initDefaultValueOnce();
|
|
319
|
+
return state.setValue;
|
|
320
|
+
}
|
|
321
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
322
|
+
0 && (module.exports = {
|
|
323
|
+
SharedStateConfig,
|
|
324
|
+
configureSharedState,
|
|
325
|
+
sharedState,
|
|
326
|
+
useSharedState,
|
|
327
|
+
useSharedStateSetter,
|
|
328
|
+
useSharedStateValue
|
|
329
|
+
});
|
package/sharedState.min.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(
|
|
1
|
+
"use strict";var b=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var E=(e,i)=>{for(var r in i)b(e,r,{get:i[r],enumerable:!0})},M=(e,i,r,n)=>{if(i&&typeof i=="object"||typeof i=="function")for(let t of O(i))!D.call(e,t)&&t!==r&&b(e,t,{get:()=>i[t],enumerable:!(n=A(i,t))||n.enumerable});return e};var k=e=>M(b({},"__esModule",{value:!0}),e);var I={};E(I,{SharedStateConfig:()=>g,configureSharedState:()=>N,sharedState:()=>_,useSharedState:()=>P,useSharedStateSetter:()=>B,useSharedStateValue:()=>L});module.exports=k(I);var w=require("@choksheak/ts-utils/timeConstants"),x=require("react");var p=require("@choksheak/ts-utils/kvStore"),v=require("@choksheak/ts-utils/localStore"),S=typeof window>"u";function m(e,i){let{store:r}=e??{};if(!r)return null;if("persistTo"in r&&typeof r.persistTo=="string"&&"key"in r&&typeof r.key=="string"){let n=r.expiryMs||i,t={...r,expiryMs:n};switch(r.persistTo){case"localStorage":return R(t);case"indexedDb":return C(t);default:throw r.persistTo,new Error(`Unknown store.adapter ${r.persistTo}`)}}return r}function R({key:e,expiryMs:i,isValid:r}){let t=(0,v.createLocalStore)("react-utils",{defaultExpiryMs:i}),o=e+":";return{set:(s,u)=>{S||t.set(o+s,u)},get:s=>{if(S)return;let u=o+s,d=t.get(u);if(d!==void 0&&r&&!r(d)){console.warn(`localStorage adapter: Auto-discard invalid value for ${u}: ${JSON.stringify(d)}`),t.delete(u);return}return d},delete:s=>{S||t.delete(o+s)},clear:()=>{S||t.clear()}}}function C({key:e,expiryMs:i,isValid:r}){let n=e+":";return{set:async(t,o)=>{S||await p.kvStore.set(n+t,o,i)},get:async t=>{if(S)return;let o=n+t,s=await p.kvStore.get(o);if(s!==void 0&&r&&!r(s)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,s),await p.kvStore.delete(o);return}return s},delete:async t=>{S||await p.kvStore.delete(n+t)},clear:async()=>{S||await p.kvStore.clear()}}}var g={storeExpiryMs:30*w.MS_PER_DAY,lazyLoad:!1};function N(e){Object.assign(g,e)}function h(){let e=new Map,i=new Map;function r(n,t,o){let s=i.get(n);if(!s)return;let u=Array.from(s.values());for(let d of u)try{d(t,o)}catch(l){console.error("Error invoking subscriber:",l)}}return{get(n){return e.get(n)},set(n,t){let o=e.get(n);o!==t&&(e.set(n,t),r(n,t,o))},delete(n){e.delete(n)},setNoNotify(n,t){e.set(n,t)},subscribe(n,t){let o=i.get(n);return o||(o=new Set,i.set(n,o)),o.add(t),()=>{o.delete(t),o.size===0&&i.delete(n)}}}}function z(){if(typeof window<"u"){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=h())}return h()}var f=z(),y="state",K=0;function _(e,i){let r=()=>{},n=new Promise(a=>{r=a}),t=r,o=String(K++),s=m(i,g.storeExpiryMs);f.setNoNotify(o,e);let u=i?.lazyLoad,d=u!==void 0?u:g.lazyLoad;function l(a){let T=a!==void 0?a:e;f.set(o,T),c.initDone=!0,t()}let c={defaultValue:e,readyPromise:n,lazy:d,initStarted:!1,initDone:!1,subscribe(a){return f.subscribe(o,()=>a())},hasStore(){return!!s},setInStore(a){return s?.set(y,a)},getFromStore(){return s?.get(y)},getSnapshot(){return f.get(o)},setValue(a){if(typeof a=="function"){let T=f.get(o);a=a(T)}f.set(o,a),c.setInStore(a)},delete(){return f.set(o,e),s?.set(y,e)},initDefaultValueOnce(){if(c.initDone||c.initStarted)return;c.initStarted=!0;let a=c.getFromStore();if(a instanceof Promise)return a.then(l);l(a)}};return d||c.initDefaultValueOnce(),c}function P(e){return e.initDefaultValueOnce(),[(0,x.useSyncExternalStore)(r=>e.subscribe(r),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function L(e){return P(e)[0]}function B(e){return e.initDefaultValueOnce(),e.setValue}0&&(module.exports={SharedStateConfig,configureSharedState,sharedState,useSharedState,useSharedStateSetter,useSharedStateValue});
|
|
2
2
|
//# sourceMappingURL=sharedState.min.cjs.map
|
package/sharedState.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs"],"names":[],"mappings":"AAAA,wIAAiD,oCAAiC,oCAAiC,sTAAiJ","file":"/Users/choksheaklau/src/react-utils/dist/sharedState.min.cjs"}
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.ts","../src/storage.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as unknown as {\n reactUtilsPubSubStore: ReturnType<typeof createPubSubStore> | undefined;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n function completeInit(stored: T | undefined) {\n const value = stored !== undefined ? stored : defaultValue;\n\n pubSubStore.set(pubSubKey, value);\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n }\n\n const obj = {\n defaultValue,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n lazy,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(pubSubKey, next);\n void obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n pubSubStore.set(pubSubKey, defaultValue);\n return storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const maybePromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (maybePromise instanceof Promise) {\n return maybePromise.then(completeInit);\n } else {\n const stored = maybePromise;\n completeInit(stored);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n","/**\n * @packageDocumentation\n *\n * Backing storage implementation for the shared state. Note that this uses the\n * LocalStore and KvStore from package \"@choksheak/ts-utils\", but is customized\n * to be used for shared states.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\nimport { Duration } from \"@choksheak/ts-utils/duration\";\nimport { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { createLocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\n/** Options to configure a pre-built store adapter. */\nexport type StoreOptions = {\n /** Choose which pre-built store adapter to use. */\n persistTo: PersistTo;\n\n /** Storage key to act as a namespace to store the data. */\n key: string;\n\n /** How long to wait before the value is considered expired. */\n expiryMs?: number | Duration;\n\n /** Returns true if the given value supposed to be of type T is valid. */\n isValid?: (u: unknown) => boolean;\n};\n\nexport type StoreConstructorArgs = Omit<StoreOptions, \"persistTo\">;\n\n/** Either use a pre-built store, or a custom one you provide. */\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\n// In SSR (Server-Side Rendering) mode, we never want to use our storage\n// adapters for anything.\nconst IS_NOT_BROWSER = typeof window === \"undefined\";\n\n/**\n * Convert a StorageOptions<T> config object into an actual storage adapter, or\n * returns null if a storage adapter is not configured.\n */\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n const config = { ...store, expiryMs };\n\n switch (store.persistTo) {\n case \"localStorage\":\n return localStoreAdapter<T>(config);\n\n case \"indexedDb\":\n return kvStoreAdapter<T>(config);\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n\n/**\n * Create a new SSR-safe local store adapter, which allows users to reuse the\n * same adapter in multiple shared states or shared queries.\n */\nexport function localStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Put everything in the same store so that we can GC properly.\n const STORE_NAME = \"react-utils\";\n\n const adapter = createLocalStore(STORE_NAME, {\n defaultExpiryMs: expiryMs,\n });\n\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n return {\n set: (key: string, value: T): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(keyPrefix + key, value);\n },\n\n get: (key: string): T | undefined => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = adapter.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`,\n );\n adapter.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n\n delete: (key: string): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.delete(keyPrefix + key);\n },\n\n /** Note that this will clear all keys in all shared states. */\n clear: (): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.clear();\n },\n };\n}\n\n/**\n * Create a new SSR-safe indexed DB KV store adapter, which allows users to\n * reuse the same adapter in multiple shared states or shared queries.\n */\nexport function kvStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = await kvStore.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `indexedDb adapter: Auto-discard invalid value for ${key}:`,\n value,\n );\n await kvStore.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n delete: async (key: string): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.clear();\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,uBAAAE,EAAA,yBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAR,GAwDA,IAAAS,EAA2B,6CAC3BC,EAA+D,iBC7C/D,IAAAC,EAAwB,uCACxBC,EAAiC,0CAkC3BC,EAAiB,OAAO,OAAW,IAMlC,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAC7BG,EAAS,CAAE,GAAGF,EAAO,S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GA,SAASnB,EAA+B,CACtC,GAAI,OAAOA,GAAS,WAAY,CAC9B,IAAMC,EAAOQ,EAAY,IAAOU,CAAS,EACzCnB,EAAQA,EAAqBC,CAAI,CACnC,CAEAQ,EAAY,IAAIU,EAAWnB,CAAI,EAC1B0B,EAAI,WAAW1B,CAAI,CAC1B,EAMA,QAA+B,CAC7B,OAAAS,EAAY,IAAIU,EAAWN,CAAY,EAChCO,GAAgB,IAAIV,EAAaG,CAAY,CACtD,EAGA,sBAA6C,CAC3C,GAAIa,EAAI,UAAYA,EAAI,YAAa,OAErCA,EAAI,YAAc,GAElB,IAAMC,EAAeD,EAAI,aAAa,EAItC,GAAIC,aAAwB,QAC1B,OAAOA,EAAa,KAAKH,CAAY,EAGrCA,EADeG,CACI,CAEvB,CACF,EAEA,OAAKJ,GACHG,EAAI,qBAAqB,EAGpBA,CACT,CAYO,SAASE,EACdC,EACkC,CAClC,OAAKA,EAAM,qBAAqB,EASzB,IAPO,wBACXC,GAAkBD,EAAM,UAAUC,CAAa,EAChD,IAAMD,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,QAAQ,CAC/B,CAUO,SAASE,EAAuBF,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASG,EAAwBH,EAAuB,CAC7D,OAAKA,EAAM,qBAAqB,EAEzBA,EAAM,QACf","names":["sharedState_exports","__export","SharedStateConfig","configureSharedState","sharedState","useSharedState","useSharedStateSetter","useSharedStateValue","__toCommonJS","import_timeConstants","import_react","import_kvStore","import_localStore","IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter","key","isValid","adapter","keyPrefix","value","fullKey","SharedStateConfig","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","pubSubKey","storageAdapter","getStorageAdapter","lazyLoad","lazy","completeInit","stored","obj","maybePromise","useSharedState","state","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
package/sharedState.min.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,
|
|
1
|
+
import{MS_PER_DAY as x}from"@choksheak/ts-utils/timeConstants";import{useSyncExternalStore as P}from"react";import{kvStore as p}from"@choksheak/ts-utils/kvStore";import{createLocalStore as m}from"@choksheak/ts-utils/localStore";var S=typeof window>"u";function y(e,a){let{store:o}=e??{};if(!o)return null;if("persistTo"in o&&typeof o.persistTo=="string"&&"key"in o&&typeof o.key=="string"){let n=o.expiryMs||a,t={...o,expiryMs:n};switch(o.persistTo){case"localStorage":return h(t);case"indexedDb":return w(t);default:throw o.persistTo,new Error(`Unknown store.adapter ${o.persistTo}`)}}return o}function h({key:e,expiryMs:a,isValid:o}){let t=m("react-utils",{defaultExpiryMs:a}),r=e+":";return{set:(i,u)=>{S||t.set(r+i,u)},get:i=>{if(S)return;let u=r+i,d=t.get(u);if(d!==void 0&&o&&!o(d)){console.warn(`localStorage adapter: Auto-discard invalid value for ${u}: ${JSON.stringify(d)}`),t.delete(u);return}return d},delete:i=>{S||t.delete(r+i)},clear:()=>{S||t.clear()}}}function w({key:e,expiryMs:a,isValid:o}){let n=e+":";return{set:async(t,r)=>{S||await p.set(n+t,r,a)},get:async t=>{if(S)return;let r=n+t,i=await p.get(r);if(i!==void 0&&o&&!o(i)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,i),await p.delete(r);return}return i},delete:async t=>{S||await p.delete(n+t)},clear:async()=>{S||await p.clear()}}}var b={storeExpiryMs:30*x,lazyLoad:!1};function L(e){Object.assign(b,e)}function v(){let e=new Map,a=new Map;function o(n,t,r){let i=a.get(n);if(!i)return;let u=Array.from(i.values());for(let d of u)try{d(t,r)}catch(l){console.error("Error invoking subscriber:",l)}}return{get(n){return e.get(n)},set(n,t){let r=e.get(n);r!==t&&(e.set(n,t),o(n,t,r))},delete(n){e.delete(n)},setNoNotify(n,t){e.set(n,t)},subscribe(n,t){let r=a.get(n);return r||(r=new Set,a.set(n,r)),r.add(t),()=>{r.delete(t),r.size===0&&a.delete(n)}}}}function A(){if(typeof window<"u"){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=v())}return v()}var f=A(),g="state",O=0;function B(e,a){let o=()=>{},n=new Promise(s=>{o=s}),t=o,r=String(O++),i=y(a,b.storeExpiryMs);f.setNoNotify(r,e);let u=a?.lazyLoad,d=u!==void 0?u:b.lazyLoad;function l(s){let T=s!==void 0?s:e;f.set(r,T),c.initDone=!0,t()}let c={defaultValue:e,readyPromise:n,lazy:d,initStarted:!1,initDone:!1,subscribe(s){return f.subscribe(r,()=>s())},hasStore(){return!!i},setInStore(s){return i?.set(g,s)},getFromStore(){return i?.get(g)},getSnapshot(){return f.get(r)},setValue(s){if(typeof s=="function"){let T=f.get(r);s=s(T)}f.set(r,s),c.setInStore(s)},delete(){return f.set(r,e),i?.set(g,e)},initDefaultValueOnce(){if(c.initDone||c.initStarted)return;c.initStarted=!0;let s=c.getFromStore();if(s instanceof Promise)return s.then(l);l(s)}};return d||c.initDefaultValueOnce(),c}function D(e){return e.initDefaultValueOnce(),[P(o=>e.subscribe(o),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function I(e){return D(e)[0]}function U(e){return e.initDefaultValueOnce(),e.setValue}export{b as SharedStateConfig,L as configureSharedState,B as sharedState,D as useSharedState,U as useSharedStateSetter,I as useSharedStateValue};
|
|
2
2
|
//# sourceMappingURL=sharedState.min.mjs.map
|
package/sharedState.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.ts","../src/storage.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. Users declare a shared state constant that can be reused across\n * multiple components with the same underlying value.\n *\n * Shared states provide persistence to local storage and/or indexed DB out of\n * the box, by using \"@choksheak/ts-utils\". Note that no matter if the shared\n * state uses persistence or not, it will always maintain a copy of the state\n * in memory. Persisted values can be configured with an automatic expiration\n * duration.\n *\n * This module is largely similar to the open source \"jotai\" npm library. You\n * can use shared states to replace \"jotai\" in your code, and optionally make\n * use of the persistence mechanism. A quick migration guide from jotai is:\n *\n * ```\n * atom() --> sharedState()\n * useAtom() --> useSharedState()\n * useAtomValue() --> useSharedStateValue()\n * useSetAtom() --> useSharedStateSetter()\n * ```\n *\n * Example:\n * ```\n * import { sharedState, useSharedState } from \"@choksheak/react-utils/sharedState\";\n *\n * // Create a new shared state in the top level scope.\n * // The first argument is the default value, which is required.\n * // The second argument is an options object, and is optional (defaults\n * // to storing in memory only without any persistence).\n * const usersState = sharedState(\n * [], { store: { persistTo: \"indexedDb\", key: \"users\" }}\n * );\n *\n * export const UsersComponent: React.FC = () => {\n * // Get both the value and the setter.\n * const [users, setUsers] = useSharedState(usersState);\n * ...\n * };\n *\n * export const ReadOnlyComponent: React.FC = () => {\n * // Get the value only.\n * const users = useSharedStateValue(usersState);\n * ...\n * };\n *\n * export const WriteOnlyComponent: React.FC = () => {\n * // Get the setter only.\n * const setUsers = useSharedStateSetter(usersState);\n * ...\n * };\n * ```\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { Dispatch, SetStateAction, useSyncExternalStore } from \"react\";\n\nimport { getStorageAdapter, StorageOptions } from \"./storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateConfig = {\n /**\n * Default duration for storage expiration in milliseconds. Initial value\n * is 30 days, but can be changed to anything.\n */\n storeExpiryMs: 30 * MS_PER_DAY,\n\n /**\n * True to load from storage only on mount, false (default) to load in\n * the top level scope when the shared state is defined.\n */\n lazyLoad: false,\n};\n\nexport type SharedStateConfig = typeof SharedStateConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedState(config: Partial<SharedStateConfig>) {\n Object.assign(SharedStateConfig, config);\n}\n\n/************************************************************************/\n/* Pub-sub store\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nfunction createPubSubStore() {\n const dataByKey = new Map<string, unknown>();\n const subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\n function notify<T>(key: string, next: T, prev: T): void {\n const subscribers = subscribersByKey.get(key);\n if (!subscribers) return;\n\n // Make copy to protect against mutation during iteration.\n const copy = Array.from(subscribers.values());\n for (const subscriber of copy) {\n try {\n subscriber(next, prev);\n } catch (e) {\n console.error(`Error invoking subscriber:`, e);\n }\n }\n }\n\n return {\n // This could be undefined if T includes undefined, else it should never\n // return undefined because the user has to always specify the default value.\n get<T>(key: string): T {\n return dataByKey.get(key) as T;\n },\n\n set<T>(key: string, value: T): void {\n const prev = dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n dataByKey.set(key, value);\n notify(key, value, prev);\n },\n\n delete(key: string): void {\n dataByKey.delete(key);\n },\n\n setNoNotify<T>(key: string, value: T): void {\n dataByKey.set(key, value);\n },\n\n // Subscribe to changes of a specific key\n subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n subscribersByKey.set(key, subscribers);\n }\n\n // Type coercion: we store Subscriber<unknown>\n subscribers.add(subscriber as Subscriber<unknown>);\n\n // Return unsubscribe function\n return () => {\n subscribers.delete(subscriber as Subscriber<unknown>);\n if (subscribers.size === 0) subscribersByKey.delete(key);\n };\n },\n } as const;\n}\n\n/**\n * Ensure we always use the same store. If we create two stores, then the\n * reactive updates will fail.\n */\nfunction getOrCreatePubSubStore() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as unknown as {\n reactUtilsPubSubStore: ReturnType<typeof createPubSubStore> | undefined;\n };\n return (\n t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore())\n );\n }\n return createPubSubStore();\n}\n\nconst pubSubStore = getOrCreatePubSubStore();\n\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\nconst STORAGE_KEY = \"state\";\n\n/** Options to configure a shared state. */\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * Example:\n * ```\n * const counterState = sharedState<number>(0);\n * ```\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n) {\n let readyResolve: () => void = () => {};\n\n const readyPromise = new Promise<void>((resolve) => {\n readyResolve = resolve;\n });\n\n const resolveReadyPromise = readyResolve;\n\n const pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n const storageAdapter = getStorageAdapter(\n options,\n SharedStateConfig.storeExpiryMs,\n );\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T. Don't notify with the default value.\n pubSubStore.setNoNotify(pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy = lazyLoad !== undefined ? lazyLoad : SharedStateConfig.lazyLoad;\n\n function completeInit(stored: T | undefined) {\n const value = stored !== undefined ? stored : defaultValue;\n\n pubSubStore.set(pubSubKey, value);\n\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initDone = true;\n resolveReadyPromise();\n }\n\n const obj = {\n defaultValue,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n lazy,\n\n initStarted: false,\n initDone: false,\n\n /** `subscribe` function required by useSyncExternalStore. */\n subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(pubSubKey, () => subscriber());\n },\n\n /** Returns true if there is a backing store. */\n hasStore(): boolean {\n return Boolean(storageAdapter);\n },\n\n /**\n * Set a value directly into the store. Does nothing if there is no\n * backing store.\n *\n * Warning: If you want to set the value properly, you should use\n * `setValue()` instead which also updates the in-memory copy.\n */\n setInStore(value: T): Promise<void> | void {\n return storageAdapter?.set(STORAGE_KEY, value);\n },\n\n /**\n * Get a value directly from the store. Returns undefined if there is no\n * backing store.\n */\n getFromStore(): Promise<T | undefined> | T | undefined {\n return storageAdapter?.get(STORAGE_KEY);\n },\n\n /**\n * Get the value of the shared state.\n * `getSnapshot` function — must return same ref if value unchanged.\n * Note that this would return the default value if data init from store is\n * not completed yet.\n */\n getSnapshot(): T {\n return pubSubStore.get(pubSubKey);\n },\n\n /** Set the value of the shared state. */\n setValue(next: SetStateAction<T>): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(pubSubKey, next);\n void obj.setInStore(next);\n },\n\n /**\n * Remove the value of the shared state. Actually this just sets the value\n * back to the given default value.\n */\n delete(): Promise<void> | void {\n pubSubStore.set(pubSubKey, defaultValue);\n return storageAdapter?.set(STORAGE_KEY, defaultValue);\n },\n\n /** Initial default handling. */\n initDefaultValueOnce(): Promise<void> | void {\n if (obj.initDone || obj.initStarted) return;\n // @ts-expect-error ts(2540) - Assign to readonly property.\n obj.initStarted = true;\n\n const maybePromise = obj.getFromStore();\n\n // Allow sync vs async code paths. This allows init to be fully completed\n // from store before the sharedState() function returns.\n if (maybePromise instanceof Promise) {\n return maybePromise.then(completeInit);\n } else {\n const stored = maybePromise;\n completeInit(stored);\n }\n },\n } as const;\n\n if (!lazy) {\n obj.initDefaultValueOnce();\n }\n\n return obj;\n}\n\nexport type SharedState<T> = ReturnType<typeof sharedState<T>>;\n\n/**\n * React hook for subscribing to a key in the global store.\n *\n * Example:\n * ```\n * const [counter, setCounter] = useSharedState(counterState);\n * ```\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, Dispatch<SetStateAction<T>>] {\n void state.initDefaultValueOnce();\n\n const value = useSyncExternalStore(\n (onStoreChange) => state.subscribe(onStoreChange),\n () => state.getSnapshot(),\n // getServerSnapshot is needed to prevent SSR dev errors in nextjs.\n () => state.getSnapshot(),\n );\n\n return [value, state.setValue];\n}\n\n/**\n * Same as useSharedState(), but returns the value only.\n *\n * Example:\n * ```\n * const counter = useSharedStateValue(counterState);\n * ```\n */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/**\n * Same as useSharedState(), but returns the setter only.\n *\n * Example:\n * ```\n * const setCounter = useSharedStateSetter(counterState);\n * ```\n */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n void state.initDefaultValueOnce();\n\n return state.setValue;\n}\n","/**\n * @packageDocumentation\n *\n * Backing storage implementation for the shared state. Note that this uses the\n * LocalStore and KvStore from package \"@choksheak/ts-utils\", but is customized\n * to be used for shared states.\n *\n * Normally you will not need to use this module directly, but if you have a\n * need for it, feel free to use it.\n */\n\nimport { Duration } from \"@choksheak/ts-utils/duration\";\nimport { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { createLocalStore } from \"@choksheak/ts-utils/localStore\";\nimport { StorageAdapter } from \"@choksheak/ts-utils/storageAdapter\";\n\n/** List of all available pre-built persistence options. */\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\n\n/** Options to configure a pre-built store adapter. */\nexport type StoreOptions = {\n /** Choose which pre-built store adapter to use. */\n persistTo: PersistTo;\n\n /** Storage key to act as a namespace to store the data. */\n key: string;\n\n /** How long to wait before the value is considered expired. */\n expiryMs?: number | Duration;\n\n /** Returns true if the given value supposed to be of type T is valid. */\n isValid?: (u: unknown) => boolean;\n};\n\nexport type StoreConstructorArgs = Omit<StoreOptions, \"persistTo\">;\n\n/** Either use a pre-built store, or a custom one you provide. */\nexport type StorageOptions<T> = {\n /**\n * You can either specify the storage adapter directly to use a custom\n * store, or specify the properties to use the pre-built ones.\n */\n store?: StorageAdapter<T> | StoreOptions;\n};\n\n// In SSR (Server-Side Rendering) mode, we never want to use our storage\n// adapters for anything.\nconst IS_NOT_BROWSER = typeof window === \"undefined\";\n\n/**\n * Convert a StorageOptions<T> config object into an actual storage adapter, or\n * returns null if a storage adapter is not configured.\n */\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { store } = options ?? {};\n\n if (!store) {\n return null;\n }\n\n if (\n \"persistTo\" in store &&\n typeof store.persistTo === \"string\" &&\n \"key\" in store &&\n typeof store.key === \"string\"\n ) {\n const expiryMs = store.expiryMs || defaultStoreExpiryMs;\n const config = { ...store, expiryMs };\n\n switch (store.persistTo) {\n case \"localStorage\":\n return localStoreAdapter<T>(config);\n\n case \"indexedDb\":\n return kvStoreAdapter<T>(config);\n\n default:\n store.persistTo satisfies never;\n throw new Error(`Unknown store.adapter ${store.persistTo}`);\n }\n }\n\n return store as StorageAdapter<T>;\n}\n\n/**\n * Create a new SSR-safe local store adapter, which allows users to reuse the\n * same adapter in multiple shared states or shared queries.\n */\nexport function localStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Put everything in the same store so that we can GC properly.\n const STORE_NAME = \"react-utils\";\n\n const adapter = createLocalStore(STORE_NAME, {\n defaultExpiryMs: expiryMs,\n });\n\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n return {\n set: (key: string, value: T): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n adapter.set(keyPrefix + key, value);\n },\n\n get: (key: string): T | undefined => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = adapter.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`,\n );\n adapter.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n\n delete: (key: string): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.delete(keyPrefix + key);\n },\n\n /** Note that this will clear all keys in all shared states. */\n clear: (): void => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n adapter.clear();\n },\n };\n}\n\n/**\n * Create a new SSR-safe indexed DB KV store adapter, which allows users to\n * reuse the same adapter in multiple shared states or shared queries.\n */\nexport function kvStoreAdapter<T>({\n key,\n expiryMs,\n isValid,\n}: StoreConstructorArgs) {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = key + \":\";\n\n // Prefix all keys using `keyPrefix` so that we can keep all data in\n // the same store in the same DB. If we keep the data in different\n // DB stores, then GC will not be able to clean up abandoned stores.\n return {\n set: async (key: string, value: T): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n // Also apply the custom expiryMs on every item in this store.\n await kvStore.set(keyPrefix + key, value, expiryMs);\n },\n get: async (key: string): Promise<T | undefined> => {\n if (IS_NOT_BROWSER) return undefined; // handle SSR\n\n const fullKey = keyPrefix + key;\n const value = await kvStore.get<T>(fullKey);\n\n // If there is no value, don't try to check for validatity.\n if (value !== undefined && isValid && !isValid(value)) {\n console.warn(\n `indexedDb adapter: Auto-discard invalid value for ${key}:`,\n value,\n );\n await kvStore.delete(fullKey);\n return undefined;\n }\n\n return value;\n },\n delete: async (key: string): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n if (IS_NOT_BROWSER) return; // handle SSR\n\n await kvStore.clear();\n },\n };\n}\n"],"mappings":"AAwDA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QC7C/D,OAAS,WAAAC,MAAe,8BACxB,OAAS,oBAAAC,MAAwB,iCAkCjC,IAAMC,EAAiB,OAAO,OAAW,IAMlC,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM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IV,EAAaJ,CAAK,CAC/C,EAMA,cAAuD,CACrD,OAAOc,GAAgB,IAAIV,CAAW,CACxC,EAQA,aAAiB,CACf,OAAOD,EAAY,IAAIU,CAAS,CAClC,EAGA,SAASnB,EAA+B,CACtC,GAAI,OAAOA,GAAS,WAAY,CAC9B,IAAMC,EAAOQ,EAAY,IAAOU,CAAS,EACzCnB,EAAQA,EAAqBC,CAAI,CACnC,CAEAQ,EAAY,IAAIU,EAAWnB,CAAI,EAC1B0B,EAAI,WAAW1B,CAAI,CAC1B,EAMA,QAA+B,CAC7B,OAAAS,EAAY,IAAIU,EAAWN,CAAY,EAChCO,GAAgB,IAAIV,EAAaG,CAAY,CACtD,EAGA,sBAA6C,CAC3C,GAAIa,EAAI,UAAYA,EAAI,YAAa,OAErCA,EAAI,YAAc,GAElB,IAAMC,EAAeD,EAAI,aAAa,EAItC,GAAIC,aAAwB,QAC1B,OAAOA,EAAa,KAAKH,CAAY,EAGrCA,EADeG,CACI,CAEvB,CACF,EAEA,OAAKJ,GACHG,EAAI,qBAAqB,EAGpBA,CACT,CAYO,SAASE,EACdC,EACkC,CAClC,OAAKA,EAAM,qBAAqB,EASzB,CAPOC,EACXC,GAAkBF,EAAM,UAAUE,CAAa,EAChD,IAAMF,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,QAAQ,CAC/B,CAUO,SAASG,EAAuBH,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAUO,SAASI,EAAwBJ,EAAuB,CAC7D,OAAKA,EAAM,qBAAqB,EAEzBA,EAAM,QACf","names":["MS_PER_DAY","useSyncExternalStore","kvStore","createLocalStore","IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter","key","isValid","adapter","keyPrefix","value","fullKey","SharedStateConfig","MS_PER_DAY","configureSharedState","config","createPubSubStore","dataByKey","subscribersByKey","notify","key","next","prev","subscribers","copy","subscriber","e","value","getOrCreatePubSubStore","t","pubSubStore","STORAGE_KEY","stateKey","sharedState","defaultValue","options","readyResolve","readyPromise","resolve","resolveReadyPromise","pubSubKey","storageAdapter","getStorageAdapter","lazyLoad","lazy","completeInit","stored","obj","maybePromise","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|