@choksheak/react-utils 0.4.4 → 0.4.6
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 +985 -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 +922 -25
- package/package.json +1 -41
- package/sharedQuery.cjs +944 -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 +912 -10
- package/sharedState.cjs +334 -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 +299 -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.mjs
CHANGED
|
@@ -1,13 +1,302 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
// src/sharedState.ts
|
|
2
|
+
import { MS_PER_DAY } from "@choksheak/ts-utils/timeConstants";
|
|
3
|
+
import { useSyncExternalStore } from "react";
|
|
4
|
+
|
|
5
|
+
// src/storage.ts
|
|
6
|
+
import { kvStore } from "@choksheak/ts-utils/kvStore";
|
|
7
|
+
import { createLocalStore } from "@choksheak/ts-utils/localStore";
|
|
8
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
9
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
10
|
+
const { store } = options ?? {};
|
|
11
|
+
if (!store) {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
|
|
15
|
+
const expiryMs = store.expiryMs || defaultStoreExpiryMs;
|
|
16
|
+
const config = { ...store, expiryMs };
|
|
17
|
+
switch (store.persistTo) {
|
|
18
|
+
case "localStorage":
|
|
19
|
+
return localStoreAdapter(config);
|
|
20
|
+
case "indexedDb":
|
|
21
|
+
return kvStoreAdapter(config);
|
|
22
|
+
default:
|
|
23
|
+
store.persistTo;
|
|
24
|
+
throw new Error(`Unknown store.adapter ${store.persistTo}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return store;
|
|
28
|
+
}
|
|
29
|
+
function localStoreAdapter({
|
|
30
|
+
key,
|
|
31
|
+
expiryMs,
|
|
32
|
+
isValid
|
|
33
|
+
}) {
|
|
34
|
+
const STORE_NAME = "react-utils";
|
|
35
|
+
const adapter = createLocalStore(STORE_NAME, {
|
|
36
|
+
defaultExpiryMs: expiryMs
|
|
37
|
+
});
|
|
38
|
+
const keyPrefix = key + ":";
|
|
39
|
+
return {
|
|
40
|
+
set: (key2, value) => {
|
|
41
|
+
if (IS_NOT_BROWSER) return;
|
|
42
|
+
adapter.set(keyPrefix + key2, value);
|
|
43
|
+
},
|
|
44
|
+
get: (key2) => {
|
|
45
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
46
|
+
const fullKey = keyPrefix + key2;
|
|
47
|
+
const value = adapter.get(fullKey);
|
|
48
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
49
|
+
console.warn(
|
|
50
|
+
`localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
|
|
51
|
+
);
|
|
52
|
+
adapter.delete(fullKey);
|
|
53
|
+
return void 0;
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
},
|
|
57
|
+
delete: (key2) => {
|
|
58
|
+
if (IS_NOT_BROWSER) return;
|
|
59
|
+
adapter.delete(keyPrefix + key2);
|
|
60
|
+
},
|
|
61
|
+
/** Note that this will clear all keys in all shared states. */
|
|
62
|
+
clear: () => {
|
|
63
|
+
if (IS_NOT_BROWSER) return;
|
|
64
|
+
adapter.clear();
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function kvStoreAdapter({
|
|
69
|
+
key,
|
|
70
|
+
expiryMs,
|
|
71
|
+
isValid
|
|
72
|
+
}) {
|
|
73
|
+
const keyPrefix = key + ":";
|
|
74
|
+
return {
|
|
75
|
+
set: async (key2, value) => {
|
|
76
|
+
if (IS_NOT_BROWSER) return;
|
|
77
|
+
await kvStore.set(keyPrefix + key2, value, expiryMs);
|
|
78
|
+
},
|
|
79
|
+
get: async (key2) => {
|
|
80
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
81
|
+
const fullKey = keyPrefix + key2;
|
|
82
|
+
const value = await kvStore.get(fullKey);
|
|
83
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
84
|
+
console.warn(
|
|
85
|
+
`indexedDb adapter: Auto-discard invalid value for ${key2}:`,
|
|
86
|
+
value
|
|
87
|
+
);
|
|
88
|
+
await kvStore.delete(fullKey);
|
|
89
|
+
return void 0;
|
|
90
|
+
}
|
|
91
|
+
return value;
|
|
92
|
+
},
|
|
93
|
+
delete: async (key2) => {
|
|
94
|
+
if (IS_NOT_BROWSER) return;
|
|
95
|
+
await kvStore.delete(keyPrefix + key2);
|
|
96
|
+
},
|
|
97
|
+
clear: async () => {
|
|
98
|
+
if (IS_NOT_BROWSER) return;
|
|
99
|
+
await kvStore.clear();
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/sharedState.ts
|
|
105
|
+
var SharedStateConfig = {
|
|
106
|
+
/**
|
|
107
|
+
* Default duration for storage expiration in milliseconds. Initial value
|
|
108
|
+
* is 30 days, but can be changed to anything.
|
|
109
|
+
*/
|
|
110
|
+
storeExpiryMs: 30 * MS_PER_DAY,
|
|
111
|
+
/**
|
|
112
|
+
* True to load from storage only on mount, false (default) to load in
|
|
113
|
+
* the top level scope when the shared state is defined.
|
|
114
|
+
*/
|
|
115
|
+
lazyLoad: false
|
|
116
|
+
};
|
|
117
|
+
function configureSharedState(config) {
|
|
118
|
+
Object.assign(SharedStateConfig, config);
|
|
119
|
+
}
|
|
120
|
+
function createPubSubStore() {
|
|
121
|
+
const dataByKey = /* @__PURE__ */ new Map();
|
|
122
|
+
const subscribersByKey = /* @__PURE__ */ new Map();
|
|
123
|
+
function notify(key, next, prev) {
|
|
124
|
+
const subscribers = subscribersByKey.get(key);
|
|
125
|
+
if (!subscribers) return;
|
|
126
|
+
const copy = Array.from(subscribers.values());
|
|
127
|
+
for (const subscriber of copy) {
|
|
128
|
+
try {
|
|
129
|
+
subscriber(next, prev);
|
|
130
|
+
} catch (e) {
|
|
131
|
+
console.error(`Error invoking subscriber:`, e);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
// This could be undefined if T includes undefined, else it should never
|
|
137
|
+
// return undefined because the user has to always specify the default value.
|
|
138
|
+
get(key) {
|
|
139
|
+
return dataByKey.get(key);
|
|
140
|
+
},
|
|
141
|
+
set(key, value) {
|
|
142
|
+
const prev = dataByKey.get(key);
|
|
143
|
+
if (prev === value) return;
|
|
144
|
+
dataByKey.set(key, value);
|
|
145
|
+
notify(key, value, prev);
|
|
146
|
+
},
|
|
147
|
+
delete(key) {
|
|
148
|
+
dataByKey.delete(key);
|
|
149
|
+
},
|
|
150
|
+
setNoNotify(key, value) {
|
|
151
|
+
dataByKey.set(key, value);
|
|
152
|
+
},
|
|
153
|
+
// Subscribe to changes of a specific key
|
|
154
|
+
subscribe(key, subscriber) {
|
|
155
|
+
let subscribers = subscribersByKey.get(key);
|
|
156
|
+
if (!subscribers) {
|
|
157
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
158
|
+
subscribersByKey.set(key, subscribers);
|
|
159
|
+
}
|
|
160
|
+
subscribers.add(subscriber);
|
|
161
|
+
return () => {
|
|
162
|
+
subscribers.delete(subscriber);
|
|
163
|
+
if (subscribers.size === 0) subscribersByKey.delete(key);
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function getOrCreatePubSubStore() {
|
|
169
|
+
if (typeof window !== "undefined") {
|
|
170
|
+
const t = window.globalThis;
|
|
171
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
172
|
+
}
|
|
173
|
+
return createPubSubStore();
|
|
174
|
+
}
|
|
175
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
176
|
+
var STORAGE_KEY = "state";
|
|
177
|
+
var stateKey = 0;
|
|
178
|
+
function getNextStateKey() {
|
|
179
|
+
if (typeof window !== "undefined") {
|
|
180
|
+
const t = window.globalThis;
|
|
181
|
+
t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;
|
|
182
|
+
return t.reactUtilsStateKey;
|
|
183
|
+
}
|
|
184
|
+
return ++stateKey;
|
|
185
|
+
}
|
|
186
|
+
function sharedState(defaultValue, options) {
|
|
187
|
+
let readyResolve = () => {
|
|
188
|
+
};
|
|
189
|
+
const readyPromise = new Promise((resolve) => {
|
|
190
|
+
readyResolve = resolve;
|
|
191
|
+
});
|
|
192
|
+
const resolveReadyPromise = readyResolve;
|
|
193
|
+
const pubSubKey = String(getNextStateKey());
|
|
194
|
+
const storageAdapter = getStorageAdapter(
|
|
195
|
+
options,
|
|
196
|
+
SharedStateConfig.storeExpiryMs
|
|
197
|
+
);
|
|
198
|
+
pubSubStore.setNoNotify(pubSubKey, defaultValue);
|
|
199
|
+
const lazyLoad = options?.lazyLoad;
|
|
200
|
+
const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
|
|
201
|
+
function completeInit(stored) {
|
|
202
|
+
const value = stored !== void 0 ? stored : defaultValue;
|
|
203
|
+
pubSubStore.set(pubSubKey, value);
|
|
204
|
+
obj.initDone = true;
|
|
205
|
+
resolveReadyPromise();
|
|
206
|
+
}
|
|
207
|
+
const obj = {
|
|
208
|
+
defaultValue,
|
|
209
|
+
/** Allow users to await for the completion of data init. */
|
|
210
|
+
readyPromise,
|
|
211
|
+
lazy,
|
|
212
|
+
initStarted: false,
|
|
213
|
+
initDone: false,
|
|
214
|
+
/** `subscribe` function required by useSyncExternalStore. */
|
|
215
|
+
subscribe(subscriber) {
|
|
216
|
+
return pubSubStore.subscribe(pubSubKey, () => subscriber());
|
|
217
|
+
},
|
|
218
|
+
/** Returns true if there is a backing store. */
|
|
219
|
+
hasStore() {
|
|
220
|
+
return Boolean(storageAdapter);
|
|
221
|
+
},
|
|
222
|
+
/**
|
|
223
|
+
* Set a value directly into the store. Does nothing if there is no
|
|
224
|
+
* backing store.
|
|
225
|
+
*
|
|
226
|
+
* Warning: If you want to set the value properly, you should use
|
|
227
|
+
* `setValue()` instead which also updates the in-memory copy.
|
|
228
|
+
*/
|
|
229
|
+
setInStore(value) {
|
|
230
|
+
return storageAdapter?.set(STORAGE_KEY, value);
|
|
231
|
+
},
|
|
232
|
+
/**
|
|
233
|
+
* Get a value directly from the store. Returns undefined if there is no
|
|
234
|
+
* backing store.
|
|
235
|
+
*/
|
|
236
|
+
getFromStore() {
|
|
237
|
+
return storageAdapter?.get(STORAGE_KEY);
|
|
238
|
+
},
|
|
239
|
+
/**
|
|
240
|
+
* Get the value of the shared state.
|
|
241
|
+
* `getSnapshot` function — must return same ref if value unchanged.
|
|
242
|
+
* Note that this would return the default value if data init from store is
|
|
243
|
+
* not completed yet.
|
|
244
|
+
*/
|
|
245
|
+
getSnapshot() {
|
|
246
|
+
return pubSubStore.get(pubSubKey);
|
|
247
|
+
},
|
|
248
|
+
/** Set the value of the shared state. */
|
|
249
|
+
setValue(next) {
|
|
250
|
+
if (typeof next === "function") {
|
|
251
|
+
const prev = pubSubStore.get(pubSubKey);
|
|
252
|
+
next = next(prev);
|
|
253
|
+
}
|
|
254
|
+
pubSubStore.set(pubSubKey, next);
|
|
255
|
+
void obj.setInStore(next);
|
|
256
|
+
},
|
|
257
|
+
/**
|
|
258
|
+
* Remove the value of the shared state. Actually this just sets the value
|
|
259
|
+
* back to the given default value.
|
|
260
|
+
*/
|
|
261
|
+
delete() {
|
|
262
|
+
pubSubStore.set(pubSubKey, defaultValue);
|
|
263
|
+
return storageAdapter?.set(STORAGE_KEY, defaultValue);
|
|
264
|
+
},
|
|
265
|
+
/** Initial default handling. */
|
|
266
|
+
initDefaultValueOnce() {
|
|
267
|
+
if (obj.initDone || obj.initStarted) return;
|
|
268
|
+
obj.initStarted = true;
|
|
269
|
+
const maybePromise = obj.getFromStore();
|
|
270
|
+
if (maybePromise instanceof Promise) {
|
|
271
|
+
return maybePromise.then(completeInit);
|
|
272
|
+
} else {
|
|
273
|
+
const stored = maybePromise;
|
|
274
|
+
completeInit(stored);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
if (!lazy) {
|
|
279
|
+
obj.initDefaultValueOnce();
|
|
280
|
+
}
|
|
281
|
+
return obj;
|
|
282
|
+
}
|
|
283
|
+
function useSharedState(state) {
|
|
284
|
+
void state.initDefaultValueOnce();
|
|
285
|
+
const value = useSyncExternalStore(
|
|
286
|
+
(onStoreChange) => state.subscribe(onStoreChange),
|
|
287
|
+
() => state.getSnapshot(),
|
|
288
|
+
// getServerSnapshot is needed to prevent SSR dev errors in nextjs.
|
|
289
|
+
() => state.getSnapshot()
|
|
290
|
+
);
|
|
291
|
+
return [value, state.setValue];
|
|
292
|
+
}
|
|
293
|
+
function useSharedStateValue(state) {
|
|
294
|
+
return useSharedState(state)[0];
|
|
295
|
+
}
|
|
296
|
+
function useSharedStateSetter(state) {
|
|
297
|
+
void state.initDefaultValueOnce();
|
|
298
|
+
return state.setValue;
|
|
299
|
+
}
|
|
11
300
|
export {
|
|
12
301
|
SharedStateConfig,
|
|
13
302
|
configureSharedState,
|
package/storage.cjs
CHANGED
|
@@ -1,11 +1,130 @@
|
|
|
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
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
20
|
+
// src/storage.ts
|
|
21
|
+
var storage_exports = {};
|
|
22
|
+
__export(storage_exports, {
|
|
23
|
+
getStorageAdapter: () => getStorageAdapter,
|
|
24
|
+
kvStoreAdapter: () => kvStoreAdapter,
|
|
25
|
+
localStoreAdapter: () => localStoreAdapter
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(storage_exports);
|
|
28
|
+
var import_kvStore = require("@choksheak/ts-utils/kvStore");
|
|
29
|
+
var import_localStore = require("@choksheak/ts-utils/localStore");
|
|
30
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
31
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
32
|
+
const { store } = options ?? {};
|
|
33
|
+
if (!store) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
|
|
37
|
+
const expiryMs = store.expiryMs || defaultStoreExpiryMs;
|
|
38
|
+
const config = { ...store, expiryMs };
|
|
39
|
+
switch (store.persistTo) {
|
|
40
|
+
case "localStorage":
|
|
41
|
+
return localStoreAdapter(config);
|
|
42
|
+
case "indexedDb":
|
|
43
|
+
return kvStoreAdapter(config);
|
|
44
|
+
default:
|
|
45
|
+
store.persistTo;
|
|
46
|
+
throw new Error(`Unknown store.adapter ${store.persistTo}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return store;
|
|
50
|
+
}
|
|
51
|
+
function localStoreAdapter({
|
|
52
|
+
key,
|
|
53
|
+
expiryMs,
|
|
54
|
+
isValid
|
|
55
|
+
}) {
|
|
56
|
+
const STORE_NAME = "react-utils";
|
|
57
|
+
const adapter = (0, import_localStore.createLocalStore)(STORE_NAME, {
|
|
58
|
+
defaultExpiryMs: expiryMs
|
|
59
|
+
});
|
|
60
|
+
const keyPrefix = key + ":";
|
|
61
|
+
return {
|
|
62
|
+
set: (key2, value) => {
|
|
63
|
+
if (IS_NOT_BROWSER) return;
|
|
64
|
+
adapter.set(keyPrefix + key2, value);
|
|
65
|
+
},
|
|
66
|
+
get: (key2) => {
|
|
67
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
68
|
+
const fullKey = keyPrefix + key2;
|
|
69
|
+
const value = adapter.get(fullKey);
|
|
70
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
71
|
+
console.warn(
|
|
72
|
+
`localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
|
|
73
|
+
);
|
|
74
|
+
adapter.delete(fullKey);
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
},
|
|
79
|
+
delete: (key2) => {
|
|
80
|
+
if (IS_NOT_BROWSER) return;
|
|
81
|
+
adapter.delete(keyPrefix + key2);
|
|
82
|
+
},
|
|
83
|
+
/** Note that this will clear all keys in all shared states. */
|
|
84
|
+
clear: () => {
|
|
85
|
+
if (IS_NOT_BROWSER) return;
|
|
86
|
+
adapter.clear();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function kvStoreAdapter({
|
|
91
|
+
key,
|
|
92
|
+
expiryMs,
|
|
93
|
+
isValid
|
|
94
|
+
}) {
|
|
95
|
+
const keyPrefix = key + ":";
|
|
96
|
+
return {
|
|
97
|
+
set: async (key2, value) => {
|
|
98
|
+
if (IS_NOT_BROWSER) return;
|
|
99
|
+
await import_kvStore.kvStore.set(keyPrefix + key2, value, expiryMs);
|
|
100
|
+
},
|
|
101
|
+
get: async (key2) => {
|
|
102
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
103
|
+
const fullKey = keyPrefix + key2;
|
|
104
|
+
const value = await import_kvStore.kvStore.get(fullKey);
|
|
105
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
106
|
+
console.warn(
|
|
107
|
+
`indexedDb adapter: Auto-discard invalid value for ${key2}:`,
|
|
108
|
+
value
|
|
109
|
+
);
|
|
110
|
+
await import_kvStore.kvStore.delete(fullKey);
|
|
111
|
+
return void 0;
|
|
112
|
+
}
|
|
113
|
+
return value;
|
|
114
|
+
},
|
|
115
|
+
delete: async (key2) => {
|
|
116
|
+
if (IS_NOT_BROWSER) return;
|
|
117
|
+
await import_kvStore.kvStore.delete(keyPrefix + key2);
|
|
118
|
+
},
|
|
119
|
+
clear: async () => {
|
|
120
|
+
if (IS_NOT_BROWSER) return;
|
|
121
|
+
await import_kvStore.kvStore.clear();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
126
|
+
0 && (module.exports = {
|
|
127
|
+
getStorageAdapter,
|
|
128
|
+
kvStoreAdapter,
|
|
129
|
+
localStoreAdapter
|
|
130
|
+
});
|
package/storage.min.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(
|
|
1
|
+
"use strict";var f=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var x=(o,r)=>{for(var e in r)f(o,e,{get:r[e],enumerable:!0})},m=(o,r,e,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of S(r))!y.call(o,t)&&t!==e&&f(o,t,{get:()=>r[t],enumerable:!(i=T(r,t))||i.enumerable});return o};var v=o=>m(f({},"__esModule",{value:!0}),o);var A={};x(A,{getStorageAdapter:()=>w,kvStoreAdapter:()=>g,localStoreAdapter:()=>l});module.exports=v(A);var d=require("@choksheak/ts-utils/kvStore"),c=require("@choksheak/ts-utils/localStore"),a=typeof window>"u";function w(o,r){let{store:e}=o??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let i=e.expiryMs||r,t={...e,expiryMs:i};switch(e.persistTo){case"localStorage":return l(t);case"indexedDb":return g(t);default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}function l({key:o,expiryMs:r,isValid:e}){let t=(0,c.createLocalStore)("react-utils",{defaultExpiryMs:r}),s=o+":";return{set:(n,u)=>{a||t.set(s+n,u)},get:n=>{if(a)return;let u=s+n,p=t.get(u);if(p!==void 0&&e&&!e(p)){console.warn(`localStorage adapter: Auto-discard invalid value for ${u}: ${JSON.stringify(p)}`),t.delete(u);return}return p},delete:n=>{a||t.delete(s+n)},clear:()=>{a||t.clear()}}}function g({key:o,expiryMs:r,isValid:e}){let i=o+":";return{set:async(t,s)=>{a||await d.kvStore.set(i+t,s,r)},get:async t=>{if(a)return;let s=i+t,n=await d.kvStore.get(s);if(n!==void 0&&e&&!e(n)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,n),await d.kvStore.delete(s);return}return n},delete:async t=>{a||await d.kvStore.delete(i+t)},clear:async()=>{a||await d.kvStore.clear()}}}0&&(module.exports={getStorageAdapter,kvStoreAdapter,localStoreAdapter});
|
|
2
2
|
//# sourceMappingURL=storage.min.cjs.map
|
package/storage.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/
|
|
1
|
+
{"version":3,"sources":["../src/storage.ts"],"sourcesContent":["/**\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,mBAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAL,GAYA,IAAAM,EAAwB,uCACxBC,EAAiC,0CAkC3BC,EAAiB,OAAO,OAAW,IAMlC,SAASN,EACdO,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,SAAAC,CAAS,EAEpC,OAAQD,EAAM,UAAW,CACvB,IAAK,eACH,OAAOP,EAAqBS,CAAM,EAEpC,IAAK,YACH,OAAOV,EAAkBU,CAAM,EAEjC,QACE,MAAAF,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT,CAMO,SAASP,EAAqB,CACnC,IAAAU,EACA,SAAAF,EACA,QAAAG,CACF,EAAyB,CAIvB,IAAMC,KAAU,oBAFG,cAE0B,CAC3C,gBAAiBJ,CACnB,CAAC,EAGKK,EAAYH,EAAM,IAExB,MAAO,CACL,IAAK,CAACA,EAAaI,IAAmB,CAChCV,GAGJQ,EAAQ,IAAIC,EAAYH,EAAKI,CAAK,CACpC,EAEA,IAAMJ,GAA+B,CACnC,GAAIN,EAAgB,OAEpB,IAAMW,EAAUF,EAAYH,EACtBI,EAAQF,EAAQ,IAAOG,CAAO,EAGpC,GAAID,IAAU,QAAaH,GAAW,CAACA,EAAQG,CAAK,EAAG,CACrD,QAAQ,KACN,wDAAwDC,CAAO,KAAK,KAAK,UAAUD,CAAK,CAAC,EAC3F,EACAF,EAAQ,OAAOG,CAAO,EACtB,MACF,CAEA,OAAOD,CACT,EAEA,OAASJ,GAAsB,CACzBN,GAEJQ,EAAQ,OAAOC,EAAYH,CAAG,CAChC,EAGA,MAAO,IAAY,CACbN,GAEJQ,EAAQ,MAAM,CAChB,CACF,CACF,CAMO,SAASb,EAAkB,CAChC,IAAAW,EACA,SAAAF,EACA,QAAAG,CACF,EAAyB,CAEvB,IAAME,EAAYH,EAAM,IAKxB,MAAO,CACL,IAAK,MAAOA,EAAaI,IAA4B,CAC/CV,GAGJ,MAAM,UAAQ,IAAIS,EAAYH,EAAKI,EAAON,CAAQ,CACpD,EACA,IAAK,MAAOE,GAAwC,CAClD,GAAIN,EAAgB,OAEpB,IAAMW,EAAUF,EAAYH,EACtBI,EAAQ,MAAM,UAAQ,IAAOC,CAAO,EAG1C,GAAID,IAAU,QAAaH,GAAW,CAACA,EAAQG,CAAK,EAAG,CACrD,QAAQ,KACN,qDAAqDJ,CAAG,IACxDI,CACF,EACA,MAAM,UAAQ,OAAOC,CAAO,EAC5B,MACF,CAEA,OAAOD,CACT,EACA,OAAQ,MAAOJ,GAA+B,CACxCN,GAEJ,MAAM,UAAQ,OAAOS,EAAYH,CAAG,CACtC,EACA,MAAO,SAA2B,CAC5BN,GAEJ,MAAM,UAAQ,MAAM,CACtB,CACF,CACF","names":["storage_exports","__export","getStorageAdapter","kvStoreAdapter","localStoreAdapter","__toCommonJS","import_kvStore","import_localStore","IS_NOT_BROWSER","options","defaultStoreExpiryMs","store","expiryMs","config","key","isValid","adapter","keyPrefix","value","fullKey"]}
|
package/storage.min.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,
|
|
1
|
+
import{kvStore as u}from"@choksheak/ts-utils/kvStore";import{createLocalStore as f}from"@choksheak/ts-utils/localStore";var n=typeof window>"u";function S(s,a){let{store:e}=s??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let i=e.expiryMs||a,t={...e,expiryMs:i};switch(e.persistTo){case"localStorage":return c(t);case"indexedDb":return l(t);default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}function c({key:s,expiryMs:a,isValid:e}){let t=f("react-utils",{defaultExpiryMs:a}),o=s+":";return{set:(r,d)=>{n||t.set(o+r,d)},get:r=>{if(n)return;let d=o+r,p=t.get(d);if(p!==void 0&&e&&!e(p)){console.warn(`localStorage adapter: Auto-discard invalid value for ${d}: ${JSON.stringify(p)}`),t.delete(d);return}return p},delete:r=>{n||t.delete(o+r)},clear:()=>{n||t.clear()}}}function l({key:s,expiryMs:a,isValid:e}){let i=s+":";return{set:async(t,o)=>{n||await u.set(i+t,o,a)},get:async t=>{if(n)return;let o=i+t,r=await u.get(o);if(r!==void 0&&e&&!e(r)){console.warn(`indexedDb adapter: Auto-discard invalid value for ${t}:`,r),await u.delete(o);return}return r},delete:async t=>{n||await u.delete(i+t)},clear:async()=>{n||await u.clear()}}}export{S as getStorageAdapter,l as kvStoreAdapter,c as localStoreAdapter};
|
|
2
2
|
//# sourceMappingURL=storage.min.mjs.map
|
package/storage.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/storage.ts"],"sourcesContent":["/**\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":"AAYA,OAAS,WAAAA,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,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAC7BG,EAAS,CAAE,GAAGF,EAAO,SAAAC,CAAS,EAEpC,OAAQD,EAAM,UAAW,CACvB,IAAK,eACH,OAAOG,EAAqBD,CAAM,EAEpC,IAAK,YACH,OAAOE,EAAkBF,CAAM,EAEjC,QACE,MAAAF,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT,CAMO,SAASG,EAAqB,CACnC,IAAAE,EACA,SAAAJ,EACA,QAAAK,CACF,EAAyB,CAIvB,IAAMC,EAAUZ,EAFG,cAE0B,CAC3C,gBAAiBM,CACnB,CAAC,EAGKO,EAAYH,EAAM,IAExB,MAAO,CACL,IAAK,CAACA,EAAaI,IAAmB,CAChCb,GAGJW,EAAQ,IAAIC,EAAYH,EAAKI,CAAK,CACpC,EAEA,IAAMJ,GAA+B,CACnC,GAAIT,EAAgB,OAEpB,IAAMc,EAAUF,EAAYH,EACtBI,EAAQF,EAAQ,IAAOG,CAAO,EAGpC,GAAID,IAAU,QAAaH,GAAW,CAACA,EAAQG,CAAK,EAAG,CACrD,QAAQ,KACN,wDAAwDC,CAAO,KAAK,KAAK,UAAUD,CAAK,CAAC,EAC3F,EACAF,EAAQ,OAAOG,CAAO,EACtB,MACF,CAEA,OAAOD,CACT,EAEA,OAASJ,GAAsB,CACzBT,GAEJW,EAAQ,OAAOC,EAAYH,CAAG,CAChC,EAGA,MAAO,IAAY,CACbT,GAEJW,EAAQ,MAAM,CAChB,CACF,CACF,CAMO,SAASH,EAAkB,CAChC,IAAAC,EACA,SAAAJ,EACA,QAAAK,CACF,EAAyB,CAEvB,IAAME,EAAYH,EAAM,IAKxB,MAAO,CACL,IAAK,MAAOA,EAAaI,IAA4B,CAC/Cb,GAGJ,MAAMF,EAAQ,IAAIc,EAAYH,EAAKI,EAAOR,CAAQ,CACpD,EACA,IAAK,MAAOI,GAAwC,CAClD,GAAIT,EAAgB,OAEpB,IAAMc,EAAUF,EAAYH,EACtBI,EAAQ,MAAMf,EAAQ,IAAOgB,CAAO,EAG1C,GAAID,IAAU,QAAaH,GAAW,CAACA,EAAQG,CAAK,EAAG,CACrD,QAAQ,KACN,qDAAqDJ,CAAG,IACxDI,CACF,EACA,MAAMf,EAAQ,OAAOgB,CAAO,EAC5B,MACF,CAEA,OAAOD,CACT,EACA,OAAQ,MAAOJ,GAA+B,CACxCT,GAEJ,MAAMF,EAAQ,OAAOc,EAAYH,CAAG,CACtC,EACA,MAAO,SAA2B,CAC5BT,GAEJ,MAAMF,EAAQ,MAAM,CACtB,CACF,CACF","names":["kvStore","createLocalStore","IS_NOT_BROWSER","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","config","localStoreAdapter","kvStoreAdapter","key","isValid","adapter","keyPrefix","value","fullKey"]}
|
package/storage.mjs
CHANGED
|
@@ -1,9 +1,101 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
// src/storage.ts
|
|
2
|
+
import { kvStore } from "@choksheak/ts-utils/kvStore";
|
|
3
|
+
import { createLocalStore } from "@choksheak/ts-utils/localStore";
|
|
4
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
5
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
6
|
+
const { store } = options ?? {};
|
|
7
|
+
if (!store) {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
|
|
11
|
+
const expiryMs = store.expiryMs || defaultStoreExpiryMs;
|
|
12
|
+
const config = { ...store, expiryMs };
|
|
13
|
+
switch (store.persistTo) {
|
|
14
|
+
case "localStorage":
|
|
15
|
+
return localStoreAdapter(config);
|
|
16
|
+
case "indexedDb":
|
|
17
|
+
return kvStoreAdapter(config);
|
|
18
|
+
default:
|
|
19
|
+
store.persistTo;
|
|
20
|
+
throw new Error(`Unknown store.adapter ${store.persistTo}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return store;
|
|
24
|
+
}
|
|
25
|
+
function localStoreAdapter({
|
|
26
|
+
key,
|
|
27
|
+
expiryMs,
|
|
28
|
+
isValid
|
|
29
|
+
}) {
|
|
30
|
+
const STORE_NAME = "react-utils";
|
|
31
|
+
const adapter = createLocalStore(STORE_NAME, {
|
|
32
|
+
defaultExpiryMs: expiryMs
|
|
33
|
+
});
|
|
34
|
+
const keyPrefix = key + ":";
|
|
35
|
+
return {
|
|
36
|
+
set: (key2, value) => {
|
|
37
|
+
if (IS_NOT_BROWSER) return;
|
|
38
|
+
adapter.set(keyPrefix + key2, value);
|
|
39
|
+
},
|
|
40
|
+
get: (key2) => {
|
|
41
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
42
|
+
const fullKey = keyPrefix + key2;
|
|
43
|
+
const value = adapter.get(fullKey);
|
|
44
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
45
|
+
console.warn(
|
|
46
|
+
`localStorage adapter: Auto-discard invalid value for ${fullKey}: ${JSON.stringify(value)}`
|
|
47
|
+
);
|
|
48
|
+
adapter.delete(fullKey);
|
|
49
|
+
return void 0;
|
|
50
|
+
}
|
|
51
|
+
return value;
|
|
52
|
+
},
|
|
53
|
+
delete: (key2) => {
|
|
54
|
+
if (IS_NOT_BROWSER) return;
|
|
55
|
+
adapter.delete(keyPrefix + key2);
|
|
56
|
+
},
|
|
57
|
+
/** Note that this will clear all keys in all shared states. */
|
|
58
|
+
clear: () => {
|
|
59
|
+
if (IS_NOT_BROWSER) return;
|
|
60
|
+
adapter.clear();
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function kvStoreAdapter({
|
|
65
|
+
key,
|
|
66
|
+
expiryMs,
|
|
67
|
+
isValid
|
|
68
|
+
}) {
|
|
69
|
+
const keyPrefix = key + ":";
|
|
70
|
+
return {
|
|
71
|
+
set: async (key2, value) => {
|
|
72
|
+
if (IS_NOT_BROWSER) return;
|
|
73
|
+
await kvStore.set(keyPrefix + key2, value, expiryMs);
|
|
74
|
+
},
|
|
75
|
+
get: async (key2) => {
|
|
76
|
+
if (IS_NOT_BROWSER) return void 0;
|
|
77
|
+
const fullKey = keyPrefix + key2;
|
|
78
|
+
const value = await kvStore.get(fullKey);
|
|
79
|
+
if (value !== void 0 && isValid && !isValid(value)) {
|
|
80
|
+
console.warn(
|
|
81
|
+
`indexedDb adapter: Auto-discard invalid value for ${key2}:`,
|
|
82
|
+
value
|
|
83
|
+
);
|
|
84
|
+
await kvStore.delete(fullKey);
|
|
85
|
+
return void 0;
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
},
|
|
89
|
+
delete: async (key2) => {
|
|
90
|
+
if (IS_NOT_BROWSER) return;
|
|
91
|
+
await kvStore.delete(keyPrefix + key2);
|
|
92
|
+
},
|
|
93
|
+
clear: async () => {
|
|
94
|
+
if (IS_NOT_BROWSER) return;
|
|
95
|
+
await kvStore.clear();
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
7
99
|
export {
|
|
8
100
|
getStorageAdapter,
|
|
9
101
|
kvStoreAdapter,
|