@choksheak/react-utils 0.4.7 → 0.4.8
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 +5 -2
- package/{NoSSR.mjs → NoSSR.js} +4 -1
- package/NoSSR.min.cjs +14 -1
- package/NoSSR.min.cjs.map +1 -1
- package/NoSSR.min.js +15 -0
- package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
- package/chunk-4YV72T4D.min.js +105 -0
- package/{storage.min.mjs.map → chunk-4YV72T4D.min.js.map} +1 -1
- package/chunk-5PDGU37E.cjs +104 -0
- package/{storage.mjs → chunk-7CPBZFDV.js} +5 -3
- package/{stringify.mjs → chunk-7XC6EVMX.js} +2 -0
- package/chunk-AXDXFCZV.min.js +35 -0
- package/{stringify.min.mjs.map → chunk-AXDXFCZV.min.js.map} +1 -1
- package/chunk-C6X4GPZ4.min.cjs +596 -0
- package/chunk-C6X4GPZ4.min.cjs.map +1 -0
- package/{sharedState.mjs → chunk-CIDQGOPA.js} +23 -8
- package/chunk-CYTO5EZE.cjs +34 -0
- package/chunk-HFIQE4XZ.cjs +595 -0
- package/chunk-IS3BZTWE.cjs +35 -0
- package/chunk-JYZY2SHD.min.js +596 -0
- package/chunk-JYZY2SHD.min.js.map +1 -0
- package/chunk-K2L3OVGY.min.cjs +18 -0
- package/chunk-K2L3OVGY.min.cjs.map +1 -0
- package/chunk-KGDXU6Q2.min.cjs +222 -0
- package/chunk-KGDXU6Q2.min.cjs.map +1 -0
- package/chunk-MNWSPF5J.min.js +18 -0
- package/{useDeepMemo.min.mjs.map → chunk-MNWSPF5J.min.js.map} +1 -1
- package/chunk-P2E73RBM.min.cjs +35 -0
- package/chunk-P2E73RBM.min.cjs.map +1 -0
- package/chunk-PCGGKBOL.min.js +222 -0
- package/chunk-PCGGKBOL.min.js.map +1 -0
- package/chunk-PHITDXZT.min.js +36 -0
- package/chunk-PHITDXZT.min.js.map +1 -0
- package/{sharedQuery.mjs → chunk-RFKUMDNU.js} +17 -6
- package/chunk-RRQBFF4W.min.cjs +105 -0
- package/chunk-RRQBFF4W.min.cjs.map +1 -0
- package/chunk-TST6JKQ5.min.cjs +36 -0
- package/chunk-TST6JKQ5.min.cjs.map +1 -0
- package/chunk-U67V476Y.js +35 -0
- package/chunk-UNDIVFP5.cjs +221 -0
- package/chunk-WXLUEDBO.cjs +17 -0
- package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
- package/dist-4BDJ7HYS.min.js +546 -0
- package/dist-4BDJ7HYS.min.js.map +1 -0
- package/dist-HKOCAKHU.min.cjs +546 -0
- package/dist-HKOCAKHU.min.cjs.map +1 -0
- package/dist-RQU6CWRG.js +545 -0
- package/dist-UKP7SPWZ.cjs +545 -0
- package/index.cjs +43 -5
- package/index.d.cts +2 -2
- package/index.d.ts +2 -2
- package/index.js +43 -0
- package/index.min.cjs +43 -1
- package/index.min.cjs.map +1 -1
- package/index.min.js +44 -0
- package/index.min.js.map +1 -0
- package/magic-string.es-2AQNCEBL.min.js +1309 -0
- package/magic-string.es-2AQNCEBL.min.js.map +1 -0
- package/magic-string.es-HC5PDAU3.cjs +1308 -0
- package/magic-string.es-KDMUXKGI.js +1308 -0
- package/magic-string.es-XJ27RPMN.min.cjs +1309 -0
- package/magic-string.es-XJ27RPMN.min.cjs.map +1 -0
- package/package.json +48 -8
- package/sharedQuery.cjs +8 -575
- package/sharedQuery.d.cts +7 -92
- package/sharedQuery.d.ts +7 -92
- package/sharedQuery.js +17 -0
- package/sharedQuery.min.cjs +17 -1
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.js +18 -0
- package/sharedQuery.min.js.map +1 -0
- package/sharedState.cjs +11 -199
- package/sharedState.d.cts +12 -57
- package/sharedState.d.ts +12 -57
- package/sharedState.js +18 -0
- package/sharedState.min.cjs +18 -1
- package/sharedState.min.cjs.map +1 -1
- package/sharedState.min.js +19 -0
- package/sharedState.min.js.map +1 -0
- package/storage.cjs +7 -98
- package/storage.js +11 -0
- package/storage.min.cjs +11 -1
- package/storage.min.cjs.map +1 -1
- package/storage.min.js +12 -0
- package/storage.min.js.map +1 -0
- package/stringify.cjs +5 -30
- package/stringify.js +7 -0
- package/stringify.min.cjs +7 -1
- package/stringify.min.cjs.map +1 -1
- package/stringify.min.js +8 -0
- package/stringify.min.js.map +1 -0
- package/useDeepMemo.cjs +5 -13
- package/useDeepMemo.js +7 -0
- package/useDeepMemo.min.cjs +7 -1
- package/useDeepMemo.min.cjs.map +1 -1
- package/useDeepMemo.min.js +8 -0
- package/useDeepMemo.min.js.map +1 -0
- package/NoSSR.min.mjs +0 -2
- package/index.min.mjs +0 -2
- package/index.min.mjs.map +0 -1
- package/index.mjs +0 -5
- package/sharedQuery.min.mjs +0 -2
- package/sharedQuery.min.mjs.map +0 -1
- package/sharedState.min.mjs +0 -2
- package/sharedState.min.mjs.map +0 -1
- package/storage.min.mjs +0 -2
- package/stringify.min.mjs +0 -2
- package/useDeepMemo.min.mjs +0 -2
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getStorageAdapter
|
|
3
|
+
} from "./chunk-4YV72T4D.min.js";
|
|
4
|
+
|
|
5
|
+
// src/sharedState.ts
|
|
6
|
+
import { MS_PER_DAY } from "@choksheak/ts-utils/timeConstants";
|
|
7
|
+
import { useSyncExternalStore } from "react";
|
|
8
|
+
var SharedStateConfig = {
|
|
9
|
+
/**
|
|
10
|
+
* Default duration for storage expiration in milliseconds. Initial value
|
|
11
|
+
* is 30 days, but can be changed to anything.
|
|
12
|
+
*/
|
|
13
|
+
storeExpiryMs: 30 * MS_PER_DAY,
|
|
14
|
+
/**
|
|
15
|
+
* True to load from storage only on mount, false (default) to load in
|
|
16
|
+
* the top level scope when the shared state is defined.
|
|
17
|
+
*/
|
|
18
|
+
lazyLoad: false,
|
|
19
|
+
/** Default to log to console. */
|
|
20
|
+
log: (...args) => console.log("[sharedState]", ...args)
|
|
21
|
+
};
|
|
22
|
+
function configureSharedState(config) {
|
|
23
|
+
Object.assign(SharedStateConfig, config);
|
|
24
|
+
}
|
|
25
|
+
function createPubSubStore() {
|
|
26
|
+
const dataByKey = /* @__PURE__ */ new Map();
|
|
27
|
+
const subscribersByKey = /* @__PURE__ */ new Map();
|
|
28
|
+
function notify(key, next, prev) {
|
|
29
|
+
const subscribers = subscribersByKey.get(key);
|
|
30
|
+
if (!subscribers) return;
|
|
31
|
+
const copy = Array.from(subscribers.values());
|
|
32
|
+
for (const subscriber of copy) {
|
|
33
|
+
try {
|
|
34
|
+
subscriber(next, prev);
|
|
35
|
+
} catch (e) {
|
|
36
|
+
console.error(`Error invoking subscriber:`, e);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
// This could be undefined if T includes undefined, else it should never
|
|
42
|
+
// return undefined because the user has to always specify the default value.
|
|
43
|
+
get(key) {
|
|
44
|
+
return dataByKey.get(key);
|
|
45
|
+
},
|
|
46
|
+
set(key, value) {
|
|
47
|
+
const prev = dataByKey.get(key);
|
|
48
|
+
if (prev === value) return;
|
|
49
|
+
dataByKey.set(key, value);
|
|
50
|
+
notify(key, value, prev);
|
|
51
|
+
},
|
|
52
|
+
delete(key) {
|
|
53
|
+
dataByKey.delete(key);
|
|
54
|
+
},
|
|
55
|
+
setNoNotify(key, value) {
|
|
56
|
+
dataByKey.set(key, value);
|
|
57
|
+
},
|
|
58
|
+
// Subscribe to changes of a specific key
|
|
59
|
+
subscribe(key, subscriber) {
|
|
60
|
+
let subscribers = subscribersByKey.get(key);
|
|
61
|
+
if (!subscribers) {
|
|
62
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
63
|
+
subscribersByKey.set(key, subscribers);
|
|
64
|
+
}
|
|
65
|
+
subscribers.add(subscriber);
|
|
66
|
+
return () => {
|
|
67
|
+
subscribers.delete(subscriber);
|
|
68
|
+
if (subscribers.size === 0) subscribersByKey.delete(key);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function getOrCreatePubSubStore() {
|
|
74
|
+
if (typeof window !== "undefined") {
|
|
75
|
+
const t = window.globalThis;
|
|
76
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
77
|
+
}
|
|
78
|
+
return createPubSubStore();
|
|
79
|
+
}
|
|
80
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
81
|
+
var STORAGE_KEY = "state";
|
|
82
|
+
var stateKey = 0;
|
|
83
|
+
function getNextStateKey() {
|
|
84
|
+
if (typeof window !== "undefined") {
|
|
85
|
+
const t = window.globalThis;
|
|
86
|
+
t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;
|
|
87
|
+
return t.reactUtilsStateKey;
|
|
88
|
+
}
|
|
89
|
+
return ++stateKey;
|
|
90
|
+
}
|
|
91
|
+
function sharedState(defaultValue, options) {
|
|
92
|
+
let readyResolve = () => {
|
|
93
|
+
};
|
|
94
|
+
const readyPromise = new Promise((resolve) => {
|
|
95
|
+
readyResolve = resolve;
|
|
96
|
+
});
|
|
97
|
+
const resolveReadyPromise = readyResolve;
|
|
98
|
+
const log = options?.log || SharedStateConfig.log;
|
|
99
|
+
const pubSubKey = String(getNextStateKey());
|
|
100
|
+
if (log && options?.name) {
|
|
101
|
+
log(`${options.name} -> ${pubSubKey}`);
|
|
102
|
+
}
|
|
103
|
+
const storageAdapter = getStorageAdapter(
|
|
104
|
+
options,
|
|
105
|
+
SharedStateConfig.storeExpiryMs
|
|
106
|
+
);
|
|
107
|
+
pubSubStore.setNoNotify(pubSubKey, defaultValue);
|
|
108
|
+
const lazyLoad = options?.lazyLoad;
|
|
109
|
+
const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
|
|
110
|
+
function completeInit(stored) {
|
|
111
|
+
const value = stored !== void 0 ? stored : defaultValue;
|
|
112
|
+
pubSubStore.set(pubSubKey, value);
|
|
113
|
+
obj.initDone = true;
|
|
114
|
+
resolveReadyPromise();
|
|
115
|
+
}
|
|
116
|
+
const obj = {
|
|
117
|
+
name: options?.name,
|
|
118
|
+
defaultValue,
|
|
119
|
+
pubSubKey,
|
|
120
|
+
/** Allow users to await for the completion of data init. */
|
|
121
|
+
readyPromise,
|
|
122
|
+
storeExpiryMs: SharedStateConfig.storeExpiryMs,
|
|
123
|
+
lazy,
|
|
124
|
+
storageAdapter,
|
|
125
|
+
initStarted: false,
|
|
126
|
+
initDone: false,
|
|
127
|
+
/** `subscribe` function required by useSyncExternalStore. */
|
|
128
|
+
subscribe(subscriber) {
|
|
129
|
+
return pubSubStore.subscribe(pubSubKey, () => subscriber());
|
|
130
|
+
},
|
|
131
|
+
/** Returns true if there is a backing store. */
|
|
132
|
+
hasStore() {
|
|
133
|
+
return Boolean(storageAdapter);
|
|
134
|
+
},
|
|
135
|
+
/**
|
|
136
|
+
* Set a value directly into the store. Does nothing if there is no
|
|
137
|
+
* backing store.
|
|
138
|
+
*
|
|
139
|
+
* Warning: If you want to set the value properly, you should use
|
|
140
|
+
* `setValue()` instead which also updates the in-memory copy.
|
|
141
|
+
*/
|
|
142
|
+
setInStore(value) {
|
|
143
|
+
return storageAdapter?.set(STORAGE_KEY, value);
|
|
144
|
+
},
|
|
145
|
+
/**
|
|
146
|
+
* Get a value directly from the store. Returns undefined if there is no
|
|
147
|
+
* backing store.
|
|
148
|
+
*/
|
|
149
|
+
getFromStore() {
|
|
150
|
+
return storageAdapter?.get(STORAGE_KEY);
|
|
151
|
+
},
|
|
152
|
+
/**
|
|
153
|
+
* Get the value of the shared state.
|
|
154
|
+
* `getSnapshot` function — must return same ref if value unchanged.
|
|
155
|
+
* Note that this would return the default value if data init from store is
|
|
156
|
+
* not completed yet.
|
|
157
|
+
*/
|
|
158
|
+
getSnapshot() {
|
|
159
|
+
return pubSubStore.get(pubSubKey);
|
|
160
|
+
},
|
|
161
|
+
/** Set the value of the shared state. */
|
|
162
|
+
setValue(next) {
|
|
163
|
+
if (typeof next === "function") {
|
|
164
|
+
const prev = pubSubStore.get(pubSubKey);
|
|
165
|
+
next = next(prev);
|
|
166
|
+
}
|
|
167
|
+
pubSubStore.set(pubSubKey, next);
|
|
168
|
+
void obj.setInStore(next);
|
|
169
|
+
},
|
|
170
|
+
/**
|
|
171
|
+
* Remove the value of the shared state. Actually this just sets the value
|
|
172
|
+
* back to the given default value.
|
|
173
|
+
*/
|
|
174
|
+
delete() {
|
|
175
|
+
pubSubStore.set(pubSubKey, defaultValue);
|
|
176
|
+
return storageAdapter?.set(STORAGE_KEY, defaultValue);
|
|
177
|
+
},
|
|
178
|
+
/** Initial default handling. */
|
|
179
|
+
initDefaultValueOnce() {
|
|
180
|
+
if (obj.initDone || obj.initStarted) return;
|
|
181
|
+
obj.initStarted = true;
|
|
182
|
+
const maybePromise = obj.getFromStore();
|
|
183
|
+
if (maybePromise instanceof Promise) {
|
|
184
|
+
return maybePromise.then(completeInit);
|
|
185
|
+
} else {
|
|
186
|
+
const stored = maybePromise;
|
|
187
|
+
completeInit(stored);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
if (!lazy) {
|
|
192
|
+
obj.initDefaultValueOnce();
|
|
193
|
+
}
|
|
194
|
+
return obj;
|
|
195
|
+
}
|
|
196
|
+
function useSharedState(state) {
|
|
197
|
+
void state.initDefaultValueOnce();
|
|
198
|
+
const value = useSyncExternalStore(
|
|
199
|
+
(onStoreChange) => state.subscribe(onStoreChange),
|
|
200
|
+
() => state.getSnapshot(),
|
|
201
|
+
// getServerSnapshot is needed to prevent SSR dev errors in nextjs.
|
|
202
|
+
() => state.getSnapshot()
|
|
203
|
+
);
|
|
204
|
+
return [value, state.setValue];
|
|
205
|
+
}
|
|
206
|
+
function useSharedStateValue(state) {
|
|
207
|
+
return useSharedState(state)[0];
|
|
208
|
+
}
|
|
209
|
+
function useSharedStateSetter(state) {
|
|
210
|
+
void state.initDefaultValueOnce();
|
|
211
|
+
return state.setValue;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export {
|
|
215
|
+
SharedStateConfig,
|
|
216
|
+
configureSharedState,
|
|
217
|
+
sharedState,
|
|
218
|
+
useSharedState,
|
|
219
|
+
useSharedStateValue,
|
|
220
|
+
useSharedStateSetter
|
|
221
|
+
};
|
|
222
|
+
//# sourceMappingURL=chunk-PCGGKBOL.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.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 /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedState]\", ...args),\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 {\n reactUtilsPubSubStore?: ReturnType<typeof createPubSubStore>;\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 /** Load from store only on first use of useSharedState(). */\n lazyLoad?: boolean;\n /** Used for debug logging. */\n name?: string;\n /** Customize the logger. */\n log?: (...args: unknown[]) => void;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\n// Try to make this safe across hot reloads and bundling.\nfunction getNextStateKey() {\n if (typeof window !== \"undefined\") {\n const t = window.globalThis as { reactUtilsStateKey?: number };\n t.reactUtilsStateKey = (t.reactUtilsStateKey ?? 0) + 1;\n return t.reactUtilsStateKey;\n }\n return ++stateKey;\n}\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 log = options?.log || SharedStateConfig.log;\n\n // We'll make a new key with each hot reload, but that's ok.\n const pubSubKey = String(getNextStateKey());\n\n if (log && options?.name) {\n log(`${options.name} -> ${pubSubKey}`);\n }\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 name: options?.name,\n defaultValue,\n pubSubKey,\n\n /** Allow users to await for the completion of data init. */\n readyPromise,\n\n storeExpiryMs: SharedStateConfig.storeExpiryMs,\n lazy,\n storageAdapter,\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"],"mappings":";;;;;AAwDA,SAAS,k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AI,qBAAqB;AAAA,EAC3B;AAEA,SAAO;AACT;AAYO,SAAS,eACd,OACkC;AAClC,OAAK,MAAM,qBAAqB;AAEhC,QAAM,QAAQ;AAAA,IACZ,CAAC,kBAAkB,MAAM,UAAU,aAAa;AAAA,IAChD,MAAM,MAAM,YAAY;AAAA;AAAA,IAExB,MAAM,MAAM,YAAY;AAAA,EAC1B;AAEA,SAAO,CAAC,OAAO,MAAM,QAAQ;AAC/B;AAUO,SAAS,oBAAuB,OAAuB;AAC5D,SAAO,eAAe,KAAK,EAAE,CAAC;AAChC;AAUO,SAAS,qBAAwB,OAAuB;AAC7D,OAAK,MAAM,qBAAqB;AAEhC,SAAO,MAAM;AACf;","names":[]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
+
mod
|
|
29
|
+
));
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
__commonJS,
|
|
33
|
+
__export,
|
|
34
|
+
__toESM
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=chunk-PHITDXZT.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
import {
|
|
2
|
+
sharedState,
|
|
3
|
+
useSharedState
|
|
4
|
+
} from "./chunk-CIDQGOPA.js";
|
|
5
|
+
import {
|
|
6
|
+
stringifyDeterministicForKeys
|
|
7
|
+
} from "./chunk-7XC6EVMX.js";
|
|
8
|
+
import {
|
|
9
|
+
useDeepMemo
|
|
10
|
+
} from "./chunk-YTXGK6BR.js";
|
|
11
|
+
|
|
12
|
+
// src/sharedQuery.ts
|
|
1
13
|
import { http, retries } from "@choksheak/ts-utils/http";
|
|
2
14
|
import { nonNil } from "@choksheak/ts-utils/nonNil";
|
|
3
15
|
import getByteSize from "object-sizeof";
|
|
@@ -9,10 +21,7 @@ import {
|
|
|
9
21
|
useState
|
|
10
22
|
} from "react";
|
|
11
23
|
import XXH from "xxhashjs";
|
|
12
|
-
|
|
13
|
-
import { stringifyDeterministicForKeys } from "./stringify";
|
|
14
|
-
import { useDeepMemo } from "./useDeepMemo";
|
|
15
|
-
const SharedQueryConfig = {
|
|
24
|
+
var SharedQueryConfig = {
|
|
16
25
|
/** Refetch on every page load. */
|
|
17
26
|
staleMs: 0,
|
|
18
27
|
/** Keep in cache for a long time. */
|
|
@@ -31,7 +40,7 @@ const SharedQueryConfig = {
|
|
|
31
40
|
function configureSharedQuery(config) {
|
|
32
41
|
Object.assign(SharedQueryConfig, config);
|
|
33
42
|
}
|
|
34
|
-
|
|
43
|
+
var moduleQueryRegistry = /* @__PURE__ */ new Map();
|
|
35
44
|
function getOrCreateQueryRegistry() {
|
|
36
45
|
if (typeof window !== "undefined") {
|
|
37
46
|
const g = window.globalThis;
|
|
@@ -141,6 +150,7 @@ function sharedQuery2(options) {
|
|
|
141
150
|
const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;
|
|
142
151
|
const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);
|
|
143
152
|
const log = options?.log ?? SharedQueryConfig.log;
|
|
153
|
+
options.name = queryName;
|
|
144
154
|
const queryState = sharedState(
|
|
145
155
|
{},
|
|
146
156
|
// defaultValue
|
|
@@ -453,7 +463,7 @@ function sharedQuery2(options) {
|
|
|
453
463
|
function sharedQuery(options) {
|
|
454
464
|
return sharedQuery1(options);
|
|
455
465
|
}
|
|
456
|
-
|
|
466
|
+
var DEFAULT_QUERY_STATE_ENTRY = {
|
|
457
467
|
lastUpdatedMs: 0,
|
|
458
468
|
loading: true
|
|
459
469
|
};
|
|
@@ -576,6 +586,7 @@ function useSharedQuery(query, ...args) {
|
|
|
576
586
|
stableArgs
|
|
577
587
|
]);
|
|
578
588
|
}
|
|
589
|
+
|
|
579
590
|
export {
|
|
580
591
|
SharedQueryConfig,
|
|
581
592
|
configureSharedQuery,
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/storage.ts
|
|
2
|
+
var _kvStore = require('@choksheak/ts-utils/kvStore');
|
|
3
|
+
var _localStore = require('@choksheak/ts-utils/localStore');
|
|
4
|
+
var IS_NOT_BROWSER = typeof window === "undefined";
|
|
5
|
+
function getStorageAdapter(options, defaultStoreExpiryMs) {
|
|
6
|
+
const { store } = _nullishCoalesce(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 = _localStore.createLocalStore.call(void 0, 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.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.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.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.kvStore.delete(keyPrefix + key2);
|
|
92
|
+
},
|
|
93
|
+
clear: async () => {
|
|
94
|
+
if (IS_NOT_BROWSER) return;
|
|
95
|
+
await _kvStore.kvStore.clear();
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
exports.getStorageAdapter = getStorageAdapter; exports.localStoreAdapter = localStoreAdapter; exports.kvStoreAdapter = kvStoreAdapter;
|
|
105
|
+
//# sourceMappingURL=chunk-RRQBFF4W.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-RRQBFF4W.min.cjs","../src/storage.ts"],"names":["key"],"mappings":"AAAA;ACYA,sDAAwB;AACxB,4DAAiC;AAkCjC,IAAM,eAAA,EAAiB,OAAO,OAAA,IAAW,WAAA;AAMlC,SAAS,iBAAA,CACd,OAAA,EACA,oBAAA,EAC0B;AAC1B,EAAA,MAAM,EAAE,MAAM,EAAA,mBAAI,OAAA,UAAW,CAAC,GAAA;AAE9B,EAAA,GAAA,CAAI,CAAC,KAAA,EAAO;AACV,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,GAAA,CACE,YAAA,GAAe,MAAA,GACf,OAAO,KAAA,CAAM,UAAA,IAAc,SAAA,GAC3B,MAAA,GAAS,MAAA,GACT,OAAO,KAAA,CAAM,IAAA,IAAQ,QAAA,EACrB;AACA,IAAA,MAAM,SAAA,EAAW,KAAA,CAAM,SAAA,GAAY,oBAAA;AACnC,IAAA,MAAM,OAAA,EAAS,EAAE,GAAG,KAAA,EAAO,SAAS,CAAA;AAEpC,IAAA,OAAA,CAAQ,KAAA,CAAM,SAAA,EAAW;AAAA,MACvB,KAAK,cAAA;AACH,QAAA,OAAO,iBAAA,CAAqB,MAAM,CAAA;AAAA,MAEpC,KAAK,WAAA;AACH,QAAA,OAAO,cAAA,CAAkB,MAAM,CAAA;AAAA,MAEjC,OAAA;AACE,QAAA,KAAA,CAAM,SAAA;AACN,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyB,KAAA,CAAM,SAAS,CAAA,CAAA;AAC5D,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAMqC;AACnC,EAAA;AACA,EAAA;AACA,EAAA;AACuB;AAEJ,EAAA;AAE0B,EAAA;AAC1B,IAAA;AAClB,EAAA;AAGuB,EAAA;AAEjB,EAAA;AACiC,IAAA;AAChB,MAAA;AAGc,MAAA;AACpC,IAAA;AAEqC,IAAA;AACR,MAAA;AAECA,MAAAA;AACQ,MAAA;AAGmB,MAAA;AAC7C,QAAA;AACN,UAAA;AACF,QAAA;AACsB,QAAA;AACf,QAAA;AACT,MAAA;AAEO,MAAA;AACT,IAAA;AAE+B,IAAA;AACT,MAAA;AAEU,MAAA;AAChC,IAAA;AAAA;AAGmB,IAAA;AACG,MAAA;AAEN,MAAA;AAChB,IAAA;AACF,EAAA;AACF;AAMkC;AAChC,EAAA;AACA,EAAA;AACA,EAAA;AACuB;AAEC,EAAA;AAKjB,EAAA;AACgD,IAAA;AAC/B,MAAA;AAG8B,MAAA;AACpD,IAAA;AACoD,IAAA;AACvB,MAAA;AAECA,MAAAA;AACc,MAAA;AAGa,MAAA;AAC7C,QAAA;AAC+CA,UAAAA;AACrD,UAAA;AACF,QAAA;AAC4B,QAAA;AACrB,QAAA;AACT,MAAA;AAEO,MAAA;AACT,IAAA;AAC8C,IAAA;AACxB,MAAA;AAEgB,MAAA;AACtC,IAAA;AACkC,IAAA;AACZ,MAAA;AAEA,MAAA;AACtB,IAAA;AACF,EAAA;AACF;ADrGiE;AACA;AACA;AACA;AACA;AACA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-RRQBFF4W.min.cjs","sourcesContent":[null,"/**\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"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
+
mod
|
|
29
|
+
));
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
exports.__commonJS = __commonJS; exports.__export = __export; exports.__toESM = __toESM;
|
|
36
|
+
//# sourceMappingURL=chunk-TST6JKQ5.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-TST6JKQ5.min.cjs"],"names":[],"mappings":"AAAA,6EAAI,SAAS,EAAE,MAAM,CAAC,MAAM;AAC5B,IAAI,UAAU,EAAE,MAAM,CAAC,cAAc;AACrC,IAAI,iBAAiB,EAAE,MAAM,CAAC,wBAAwB;AACtD,IAAI,kBAAkB,EAAE,MAAM,CAAC,mBAAmB;AAClD,IAAI,aAAa,EAAE,MAAM,CAAC,cAAc;AACxC,IAAI,aAAa,EAAE,MAAM,CAAC,SAAS,CAAC,cAAc;AAClD,IAAI,WAAW,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,GAAG,SAAS,SAAS,CAAC,EAAE;AACnD,EAAE,OAAO,IAAI,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,OAAO;AACpG,CAAC;AACD,IAAI,SAAS,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG;AAChC,EAAE,IAAI,CAAC,IAAI,KAAK,GAAG,GAAG;AACtB,IAAI,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,EAAE,GA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0 +1,35 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
+
mod
|
|
29
|
+
));
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
__commonJS,
|
|
33
|
+
__export,
|
|
34
|
+
__toESM
|
|
35
|
+
};
|