@choksheak/react-utils 0.4.2 → 0.4.4
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/chunk-433OAJVP.min.cjs +2 -0
- package/chunk-433OAJVP.min.cjs.map +1 -0
- package/{chunk-GKNOICX3.cjs → chunk-7D2YNZO3.cjs} +25 -9
- package/chunk-BQIRLDQC.min.mjs +2 -0
- package/chunk-BQIRLDQC.min.mjs.map +1 -0
- package/{chunk-X6EKF4N7.mjs → chunk-FXCYHS3L.mjs} +23 -7
- package/{chunk-3X25NN6X.cjs → chunk-NGGNAAHA.cjs} +9 -1
- package/chunk-RP2TWHFU.min.cjs +2 -0
- package/chunk-RP2TWHFU.min.cjs.map +1 -0
- package/chunk-XRHQCN2J.min.mjs +2 -0
- package/chunk-XRHQCN2J.min.mjs.map +1 -0
- package/{chunk-KRXENFK3.mjs → chunk-YHU4KW2D.mjs} +9 -1
- package/index.cjs +3 -3
- package/index.d.cts +2 -2
- package/index.d.ts +2 -2
- package/index.min.cjs +1 -1
- package/index.min.mjs +1 -1
- package/index.mjs +2 -2
- package/package.json +11 -44
- package/sharedQuery.cjs +3 -3
- package/sharedQuery.d.cts +6 -1
- package/sharedQuery.d.ts +6 -1
- package/sharedQuery.min.cjs +1 -1
- package/sharedQuery.min.mjs +1 -1
- package/sharedQuery.mjs +2 -2
- package/sharedState.cjs +2 -2
- package/sharedState.d.cts +1 -0
- package/sharedState.d.ts +1 -0
- package/sharedState.min.cjs +1 -1
- package/sharedState.min.mjs +1 -1
- package/sharedState.mjs +1 -1
- package/chunk-BBCGQMWI.min.cjs +0 -2
- package/chunk-BBCGQMWI.min.cjs.map +0 -1
- package/chunk-KILGR7YA.min.mjs +0 -2
- package/chunk-KILGR7YA.min.mjs.map +0 -1
- package/chunk-NTFFK7ZH.min.cjs +0 -2
- package/chunk-NTFFK7ZH.min.cjs.map +0 -1
- package/chunk-U7RD7B3N.min.mjs +0 -2
- package/chunk-U7RD7B3N.min.mjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkUFJQLQFImincjs = require('./chunk-UFJQLQFI.min.cjs');var _timeConstants = require('@choksheak/ts-utils/timeConstants');var _react = require('react');var T={storeExpiryMs:30*_timeConstants.MS_PER_DAY,lazyLoad:!1};function E(e){Object.assign(T,e)}function g(){let e=new Map,i=new Map;function S(o,n,t){let a=i.get(o);if(!a)return;let c=Array.from(a.values());for(let d of c)try{d(n,t)}catch(f){console.error("Error invoking subscriber:",f)}}return{get(o){return e.get(o)},set(o,n){let t=e.get(o);t!==n&&(e.set(o,n),S(o,n,t))},delete(o){e.delete(o)},setNoNotify(o,n){e.set(o,n)},subscribe(o,n){let t=i.get(o);return t||(t=new Set,i.set(o,t)),t.add(n),()=>{t.delete(n),t.size===0&&i.delete(o)}}}}function h(){if(typeof window<"u"){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=g())}return g()}var u=h(),p="state",m=0;function R(e,i){let S=()=>{},o=new Promise(r=>{S=r}),n=S,t=String(m++),a=_chunkUFJQLQFImincjs.a.call(void 0, i,T.storeExpiryMs);u.setNoNotify(t,e);let c=_optionalChain([i, 'optionalAccess', _ => _.lazyLoad]),d=c!==void 0?c:T.lazyLoad;function f(r){let b=r!==void 0?r:e;u.set(t,b),s.initDone=!0,n()}let s={defaultValue:e,readyPromise:o,lazy:d,initStarted:!1,initDone:!1,subscribe(r){return u.subscribe(t,()=>r())},hasStore(){return!!a},setInStore(r){return _optionalChain([a, 'optionalAccess', _2 => _2.set, 'call', _3 => _3(p,r)])},getFromStore(){return _optionalChain([a, 'optionalAccess', _4 => _4.get, 'call', _5 => _5(p)])},getSnapshot(){return u.get(t)},setValue(r){if(typeof r=="function"){let b=u.get(t);r=r(b)}u.set(t,r),s.setInStore(r)},delete(){return u.set(t,e),_optionalChain([a, 'optionalAccess', _6 => _6.set, 'call', _7 => _7(p,e)])},initDefaultValueOnce(){if(s.initDone||s.initStarted)return;s.initStarted=!0;let r=s.getFromStore();if(r instanceof Promise)return r.then(f);f(r)}};return d||s.initDefaultValueOnce(),s}function P(e){return e.initDefaultValueOnce(),[_react.useSyncExternalStore.call(void 0, S=>e.subscribe(S),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function C(e){return P(e)[0]}function K(e){return e.initDefaultValueOnce(),e.setValue}exports.a = T; exports.b = E; exports.c = R; exports.d = P; exports.e = C; exports.f = K;
|
|
2
|
+
//# sourceMappingURL=chunk-433OAJVP.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-433OAJVP.min.cjs","../src/sharedState.ts"],"names":["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"],"mappings":"AAAA,4oBAA4C,kECwDjB,8BACoC,IAWlDA,CAAAA,CAAoB,CAK/B,aAAA,CAAe,EAAA,CAAKC,yBAAAA,CAMpB,QAAA,CAAU,CAAA,CACZ,CAAA,CAKO,SAASC,CAAAA,CAAqBC,CAAAA,CAAoC,CACvE,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oBAAA,CAAqB,CAAA,CAEzBA,CAAAA,CAAM,QACf,CAAA,yFAAA","file":"/Users/choksheaklau/src/react-utils/dist/chunk-433OAJVP.min.cjs","sourcesContent":[null,"/**\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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
var
|
|
4
|
+
var _chunkNGGNAAHAcjs = require('./chunk-NGGNAAHA.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
var _chunkCYTO5EZEcjs = require('./chunk-CYTO5EZE.cjs');
|
|
@@ -11,6 +11,7 @@ var _chunkWXLUEDBOcjs = require('./chunk-WXLUEDBO.cjs');
|
|
|
11
11
|
|
|
12
12
|
// src/sharedQuery.ts
|
|
13
13
|
var _http = require('@choksheak/ts-utils/http');
|
|
14
|
+
var _nonNil = require('@choksheak/ts-utils/nonNil');
|
|
14
15
|
var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);
|
|
15
16
|
|
|
16
17
|
|
|
@@ -47,7 +48,7 @@ function sharedQuery(options) {
|
|
|
47
48
|
throw new Error(`Either queryName or url must be specified.`);
|
|
48
49
|
}
|
|
49
50
|
if (seenQueryNames.has(queryName)) {
|
|
50
|
-
|
|
51
|
+
console.warn(`Duplicate shared query name "${queryName}"`);
|
|
51
52
|
}
|
|
52
53
|
seenQueryNames.add(queryName);
|
|
53
54
|
const inflightQueries = /* @__PURE__ */ new Map();
|
|
@@ -135,7 +136,7 @@ function sharedQuery(options) {
|
|
|
135
136
|
const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _6 => _6.maxBytes]), () => ( SharedQueryConfig.maxBytes));
|
|
136
137
|
const keepLastNonEmptyData = Boolean(_optionalChain([options, 'optionalAccess', _7 => _7.keepLastNonEmptyData]));
|
|
137
138
|
const log = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.log]), () => ( SharedQueryConfig.log));
|
|
138
|
-
const queryState =
|
|
139
|
+
const queryState = _chunkNGGNAAHAcjs.sharedState.call(void 0,
|
|
139
140
|
{},
|
|
140
141
|
// defaultValue
|
|
141
142
|
options
|
|
@@ -450,7 +451,7 @@ var DEFAULT_QUERY_STATE_ENTRY = {
|
|
|
450
451
|
};
|
|
451
452
|
function useSharedQuery(query, ...args) {
|
|
452
453
|
const stableArgs = _chunkWXLUEDBOcjs.useDeepMemo.call(void 0, args);
|
|
453
|
-
const [queryState, setQueryState] =
|
|
454
|
+
const [queryState, setQueryState] = _chunkNGGNAAHAcjs.useSharedState.call(void 0, query.queryState);
|
|
454
455
|
const isMounted = _react.useRef.call(void 0, true);
|
|
455
456
|
const queryKey = _react.useMemo.call(void 0,
|
|
456
457
|
() => query.getQueryKey(stableArgs),
|
|
@@ -473,7 +474,7 @@ function useSharedQuery(query, ...args) {
|
|
|
473
474
|
setLastNonEmptyData(queryStateValue.data);
|
|
474
475
|
}
|
|
475
476
|
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
476
|
-
const
|
|
477
|
+
const executeQuery = _react.useCallback.call(void 0,
|
|
477
478
|
async (isRefetch) => {
|
|
478
479
|
query.log(
|
|
479
480
|
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
@@ -502,6 +503,7 @@ function useSharedQuery(query, ...args) {
|
|
|
502
503
|
}
|
|
503
504
|
if (!isMounted.current) return;
|
|
504
505
|
setQueryStateValue({ ...state, loading: false });
|
|
506
|
+
return state.data;
|
|
505
507
|
} catch (e) {
|
|
506
508
|
if (!isMounted.current) return;
|
|
507
509
|
const now = Date.now();
|
|
@@ -520,12 +522,12 @@ function useSharedQuery(query, ...args) {
|
|
|
520
522
|
_react.useEffect.call(void 0, () => {
|
|
521
523
|
isMounted.current = true;
|
|
522
524
|
query.mount(queryKey);
|
|
523
|
-
void
|
|
525
|
+
void executeQuery(false);
|
|
524
526
|
return () => {
|
|
525
527
|
isMounted.current = false;
|
|
526
528
|
query.unmount(queryKey);
|
|
527
529
|
};
|
|
528
|
-
}, [
|
|
530
|
+
}, [executeQuery, query, queryKey]);
|
|
529
531
|
return _react.useMemo.call(void 0, () => {
|
|
530
532
|
return {
|
|
531
533
|
...queryStateValue,
|
|
@@ -540,8 +542,15 @@ function useSharedQuery(query, ...args) {
|
|
|
540
542
|
_optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
|
|
541
543
|
return Boolean(controller);
|
|
542
544
|
},
|
|
545
|
+
getCachedOrFetch: async () => {
|
|
546
|
+
const data = await query.getCachedOrFetch(...stableArgs);
|
|
547
|
+
return _nonNil.nonNil.call(void 0,
|
|
548
|
+
data.data,
|
|
549
|
+
typeof data.error === "string" ? data.error : JSON.stringify(data.error)
|
|
550
|
+
);
|
|
551
|
+
},
|
|
543
552
|
refetch: () => {
|
|
544
|
-
return
|
|
553
|
+
return executeQuery(true);
|
|
545
554
|
},
|
|
546
555
|
setData: (data, dataUpdatedMs) => {
|
|
547
556
|
query.setData(queryKey, data, dataUpdatedMs);
|
|
@@ -550,7 +559,14 @@ function useSharedQuery(query, ...args) {
|
|
|
550
559
|
query.deleteData(queryKey);
|
|
551
560
|
}
|
|
552
561
|
};
|
|
553
|
-
}, [
|
|
562
|
+
}, [
|
|
563
|
+
executeQuery,
|
|
564
|
+
lastNonEmptyData,
|
|
565
|
+
query,
|
|
566
|
+
queryKey,
|
|
567
|
+
queryStateValue,
|
|
568
|
+
stableArgs
|
|
569
|
+
]);
|
|
554
570
|
}
|
|
555
571
|
|
|
556
572
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as l}from"./chunk-VHMO75EY.min.mjs";import{MS_PER_DAY as y}from"@choksheak/ts-utils/timeConstants";import{useSyncExternalStore as v}from"react";var T={storeExpiryMs:30*y,lazyLoad:!1};function E(e){Object.assign(T,e)}function g(){let e=new Map,i=new Map;function S(o,n,t){let a=i.get(o);if(!a)return;let c=Array.from(a.values());for(let d of c)try{d(n,t)}catch(f){console.error("Error invoking subscriber:",f)}}return{get(o){return e.get(o)},set(o,n){let t=e.get(o);t!==n&&(e.set(o,n),S(o,n,t))},delete(o){e.delete(o)},setNoNotify(o,n){e.set(o,n)},subscribe(o,n){let t=i.get(o);return t||(t=new Set,i.set(o,t)),t.add(n),()=>{t.delete(n),t.size===0&&i.delete(o)}}}}function h(){if(typeof window<"u"){let e=window.globalThis;return e.reactUtilsPubSubStore||(e.reactUtilsPubSubStore=g())}return g()}var u=h(),p="state",m=0;function R(e,i){let S=()=>{},o=new Promise(r=>{S=r}),n=S,t=String(m++),a=l(i,T.storeExpiryMs);u.setNoNotify(t,e);let c=i?.lazyLoad,d=c!==void 0?c:T.lazyLoad;function f(r){let b=r!==void 0?r:e;u.set(t,b),s.initDone=!0,n()}let s={defaultValue:e,readyPromise:o,lazy:d,initStarted:!1,initDone:!1,subscribe(r){return u.subscribe(t,()=>r())},hasStore(){return!!a},setInStore(r){return a?.set(p,r)},getFromStore(){return a?.get(p)},getSnapshot(){return u.get(t)},setValue(r){if(typeof r=="function"){let b=u.get(t);r=r(b)}u.set(t,r),s.setInStore(r)},delete(){return u.set(t,e),a?.set(p,e)},initDefaultValueOnce(){if(s.initDone||s.initStarted)return;s.initStarted=!0;let r=s.getFromStore();if(r instanceof Promise)return r.then(f);f(r)}};return d||s.initDefaultValueOnce(),s}function P(e){return e.initDefaultValueOnce(),[v(S=>e.subscribe(S),()=>e.getSnapshot(),()=>e.getSnapshot()),e.setValue]}function C(e){return P(e)[0]}function K(e){return e.initDefaultValueOnce(),e.setValue}export{T as a,E as b,R as c,P as d,C as e,K as f};
|
|
2
|
+
//# sourceMappingURL=chunk-BQIRLDQC.min.mjs.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\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"],"mappings":"6CAwDA,OAAS,cAAAA,MAAkB,oCAC3B,OAAmC,wBAAAC,MAA4B,QAWxD,IAAMC,EAAoB,CAK/B,cAAe,GAAKC,EAMpB,SAAU,EACZ,EAKO,SAASC,EAAqBC,EAAo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,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","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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
sharedState,
|
|
3
3
|
useSharedState
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-YHU4KW2D.mjs";
|
|
5
5
|
import {
|
|
6
6
|
stringifyDeterministicForKeys
|
|
7
7
|
} from "./chunk-4235I4VO.mjs";
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
|
|
12
12
|
// src/sharedQuery.ts
|
|
13
13
|
import { http, retries } from "@choksheak/ts-utils/http";
|
|
14
|
+
import { nonNil } from "@choksheak/ts-utils/nonNil";
|
|
14
15
|
import getByteSize from "object-sizeof";
|
|
15
16
|
import {
|
|
16
17
|
useCallback,
|
|
@@ -47,7 +48,7 @@ function sharedQuery(options) {
|
|
|
47
48
|
throw new Error(`Either queryName or url must be specified.`);
|
|
48
49
|
}
|
|
49
50
|
if (seenQueryNames.has(queryName)) {
|
|
50
|
-
|
|
51
|
+
console.warn(`Duplicate shared query name "${queryName}"`);
|
|
51
52
|
}
|
|
52
53
|
seenQueryNames.add(queryName);
|
|
53
54
|
const inflightQueries = /* @__PURE__ */ new Map();
|
|
@@ -473,7 +474,7 @@ function useSharedQuery(query, ...args) {
|
|
|
473
474
|
setLastNonEmptyData(queryStateValue.data);
|
|
474
475
|
}
|
|
475
476
|
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
476
|
-
const
|
|
477
|
+
const executeQuery = useCallback(
|
|
477
478
|
async (isRefetch) => {
|
|
478
479
|
query.log(
|
|
479
480
|
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
@@ -502,6 +503,7 @@ function useSharedQuery(query, ...args) {
|
|
|
502
503
|
}
|
|
503
504
|
if (!isMounted.current) return;
|
|
504
505
|
setQueryStateValue({ ...state, loading: false });
|
|
506
|
+
return state.data;
|
|
505
507
|
} catch (e) {
|
|
506
508
|
if (!isMounted.current) return;
|
|
507
509
|
const now = Date.now();
|
|
@@ -520,12 +522,12 @@ function useSharedQuery(query, ...args) {
|
|
|
520
522
|
useEffect(() => {
|
|
521
523
|
isMounted.current = true;
|
|
522
524
|
query.mount(queryKey);
|
|
523
|
-
void
|
|
525
|
+
void executeQuery(false);
|
|
524
526
|
return () => {
|
|
525
527
|
isMounted.current = false;
|
|
526
528
|
query.unmount(queryKey);
|
|
527
529
|
};
|
|
528
|
-
}, [
|
|
530
|
+
}, [executeQuery, query, queryKey]);
|
|
529
531
|
return useMemo(() => {
|
|
530
532
|
return {
|
|
531
533
|
...queryStateValue,
|
|
@@ -540,8 +542,15 @@ function useSharedQuery(query, ...args) {
|
|
|
540
542
|
controller?.abort(reason);
|
|
541
543
|
return Boolean(controller);
|
|
542
544
|
},
|
|
545
|
+
getCachedOrFetch: async () => {
|
|
546
|
+
const data = await query.getCachedOrFetch(...stableArgs);
|
|
547
|
+
return nonNil(
|
|
548
|
+
data.data,
|
|
549
|
+
typeof data.error === "string" ? data.error : JSON.stringify(data.error)
|
|
550
|
+
);
|
|
551
|
+
},
|
|
543
552
|
refetch: () => {
|
|
544
|
-
return
|
|
553
|
+
return executeQuery(true);
|
|
545
554
|
},
|
|
546
555
|
setData: (data, dataUpdatedMs) => {
|
|
547
556
|
query.setData(queryKey, data, dataUpdatedMs);
|
|
@@ -550,7 +559,14 @@ function useSharedQuery(query, ...args) {
|
|
|
550
559
|
query.deleteData(queryKey);
|
|
551
560
|
}
|
|
552
561
|
};
|
|
553
|
-
}, [
|
|
562
|
+
}, [
|
|
563
|
+
executeQuery,
|
|
564
|
+
lastNonEmptyData,
|
|
565
|
+
query,
|
|
566
|
+
queryKey,
|
|
567
|
+
queryStateValue,
|
|
568
|
+
stableArgs
|
|
569
|
+
]);
|
|
554
570
|
}
|
|
555
571
|
|
|
556
572
|
export {
|
|
@@ -68,7 +68,14 @@ function createPubSubStore() {
|
|
|
68
68
|
}
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
function getOrCreatePubSubStore() {
|
|
72
|
+
if (typeof window !== "undefined") {
|
|
73
|
+
const t = window.globalThis;
|
|
74
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
75
|
+
}
|
|
76
|
+
return createPubSubStore();
|
|
77
|
+
}
|
|
78
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
72
79
|
var STORAGE_KEY = "state";
|
|
73
80
|
var stateKey = 0;
|
|
74
81
|
function sharedState(defaultValue, options) {
|
|
@@ -93,6 +100,7 @@ function sharedState(defaultValue, options) {
|
|
|
93
100
|
resolveReadyPromise();
|
|
94
101
|
}
|
|
95
102
|
const obj = {
|
|
103
|
+
defaultValue,
|
|
96
104
|
/** Allow users to await for the completion of data init. */
|
|
97
105
|
readyPromise,
|
|
98
106
|
lazy,
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk433OAJVPmincjs = require('./chunk-433OAJVP.min.cjs');var _chunkKGN4HQPPmincjs = require('./chunk-KGN4HQPP.min.cjs');var _chunkJOHZV3FDmincjs = require('./chunk-JOHZV3FD.min.cjs');var _http = require('@choksheak/ts-utils/http');var _nonNil = require('@choksheak/ts-utils/nonNil');var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);var _react = require('react');var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);var Q={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...a)=>console.log("[sharedQuery]",...a)};function ue(a){Object.assign(Q,a)}var j=new Set;function le(a){let M=a.url||"",i=a.queryName||M;if(!i)throw new Error("Either queryName or url must be specified.");j.has(i)&&console.warn(`Duplicate shared query name "${i}"`),j.add(i);let p=new Map,h=new Map,m;if(a.queryFn)m=a.queryFn;else if(M){let e=_http.http.use(_http.retries.call(void 0, ));m=async(...t)=>{let r="",n=_optionalChain([t, 'optionalAccess', _2 => _2[0]]);if(n){if(typeof n=="string")r=n;else if(typeof n=="object"){let f=[];for(let[b,w]of Object.entries(n))if(w!==void 0)if(Array.isArray(w))for(let $ of w)$!==void 0&&f.push([b,String($)]);else f.push([b,String(w)]);r=new URLSearchParams(f).toString()}r&&(M.includes("?")?r="&"+r:r="?"+r)}return await(await e.get(M+r)).json()}}else throw new Error("Either queryFn or url must be specified");let u=a.refetchFn,y=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _3 => _3.staleMs]), () => (Q.staleMs)),D=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _4 => _4.expiryMs]), () => (Q.expiryMs)),x=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _5 => _5.refetchOnStale]), () => (Q.refetchOnStale)),A=a.store;if(A){if("persistTo"in A&&A.isValid){let e=A.isValid;a={...a,store:{...A,isValid:t=>{if(!t||typeof t!="object")return!1;for(let r of Object.values(t))if(!r||typeof r!="object"||!("data"in r)||!("dataUpdatedMs"in r)||!("lastUpdatedMs"in r)||typeof r.dataUpdatedMs!="number"||typeof r.lastUpdatedMs!="number"||!e(r.data))return!1;return!0}}}}}else{let e=_nullishCoalesce(a.persistTo, () => (Q.persistTo));e&&(a={...a,store:{persistTo:e,key:i,expiryMs:D}})}let T=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _6 => _6.maxSize]), () => (Q.maxSize)),s=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _7 => _7.maxBytes]), () => (Q.maxBytes)),l=!!_optionalChain([a, 'optionalAccess', _8 => _8.keepLastNonEmptyData]),o=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _9 => _9.log]), () => (Q.log)),c=_chunk433OAJVPmincjs.c.call(void 0, {},a);function K(e){return y===0?!0:Date.now()-e>y}function k(e){return D===0?!1:Date.now()-e>D}function O(){if(!T&&!s)return;let e=c.getSnapshot(),t=Object.keys(e).length;if(t<=1)return;let r=_objectsizeof2.default.call(void 0, e),n=T?t-T:0,d=s?r-s:0;if(n<=0&&d<=0){o(`No need to trim data for ${i}: size=${t} (limit=${T}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}o(`Need to trim ${i}: numToCut=${n}, bytesToCut=${d}`);let f={...e},b=!1,w=(g,U)=>{if(h.has(g)){o(`Cannot clean up ${g} as it is mounted`);return}let N=_objectsizeof2.default.call(void 0, g)+_objectsizeof2.default.call(void 0, f[g]);o(`Cleaning up unmounted${U?", expired":""} ${g} (byteSize=${N.toLocaleString()})`),n--,d-=N,delete f[g],b=!0},$=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs);for(let[g]of $){if(!k(f[g].lastUpdatedMs))break;w(g,!0)}if(n>0||d>0){b&&($=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs));for(let[g]of $)if(w(g,!1),n<=0&&d<=0)break}if(!b){o(`No trimmable entries found for ${i}: size=${t} (limit=${T}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}c.setValue(f),o(`Trimmed data for ${i}: size=[${t} -> ${Object.keys(f).length}] (limit=${T}), byteSize=[${r.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, f).toLocaleString()}] (limit=${s.toLocaleString()})`)}function V(e,t,r=Date.now()){let n={lastUpdatedMs:Date.now(),loading:!1,data:t,dataUpdatedMs:r};c.setValue(d=>({...d,[e]:n})),O()}async function _(e,t,r){o(`Start fetching ${e}, queryType=${t}`);try{let n=await(t==="refetch"&&u?u(...r):m(...r));return o(`Successfully fetched ${e}`),V(e,n,Date.now()),n}catch(n){throw o(`Failed to fetch ${e} for queryType=${t}: ${n}`),n}finally{p.delete(e)}}function C(e,t,...r){let n=p.get(e);if(n)return o(`Deduplicating inflight fetch for ${e}, queryType=${t}`),n.promise;let d=_(e,t,r),f=new AbortController;return p.set(e,{promise:d,abortController:f}),d}let S={queryName:i,queryFn:m,refetchFn:u,expiryMs:D,staleMs:y,refetchOnStale:x,maxSize:T,maxBytes:s,keepLastNonEmptyData:l,log:o,queryState:c,getQueryKey(e){let t=_chunkKGN4HQPPmincjs.a.call(void 0, e);return t.length>30&&(t=_xxhashjs2.default.h32(t,39406).toString(16).slice(2)),i+":"+t},getAbortController(e){let t=S.getQueryKey(e);return S.getAbortControllerByKey(t)},getAbortControllerByKey(e){return _nullishCoalesce(_optionalChain([p, 'access', _10 => _10.get, 'call', _11 => _11(e), 'optionalAccess', _12 => _12.abortController]), () => (null))},getAbortSignal(e){let t=S.getQueryKey(e);return S.getAbortSignalByKey(t)},getAbortSignalByKey(e){return _nullishCoalesce(_optionalChain([S, 'access', _13 => _13.getAbortControllerByKey, 'call', _14 => _14(e), 'optionalAccess', _15 => _15.signal]), () => (null))},async getCachedOrFetch(...e){let t=Date.now();await c.readyPromise;let r=Date.now()-t,n=S.getQueryKey(e),d=_optionalChain([c, 'access', _16 => _16.getSnapshot, 'call', _17 => _17(), 'optionalAccess', _18 => _18[n]]);if(r&&o(`${n}: Waited for ${r}ms before data is ready`),_optionalChain([d, 'optionalAccess', _19 => _19.data])&&!k(_nullishCoalesce(d.dataUpdatedMs, () => (0))))return K(_nullishCoalesce(d.dataUpdatedMs, () => (0)))?(x&&(o(`refetchOnStale for ${n}`),C(n,"query",...e)),o(`Returning stale data for ${n}`),d):(o(`Return fresh data ${n} from cache without fetching`),d);let f=await C(n,"query",...e),b=Date.now();return{lastUpdatedMs:b,loading:!1,data:f,dataUpdatedMs:b}},getQueryValue(e){return _optionalChain([c, 'access', _20 => _20.getSnapshot, 'call', _21 => _21(), 'optionalAccess', _22 => _22[e]])},getData(e){let t=_optionalChain([c, 'access', _23 => _23.getSnapshot, 'call', _24 => _24(), 'optionalAccess', _25 => _25[e]]);if(_optionalChain([t, 'optionalAccess', _26 => _26.lastUpdatedMs])&&k(t.lastUpdatedMs)){S.deleteData(e);return}return _optionalChain([t, 'optionalAccess', _27 => _27.data])},setData:V,async updateFromSource(...e){let t=S.getQueryKey(e);return await C(t,"query",...e)},async refetch(...e){let t=S.getQueryKey(e);return await C(t,"refetch",...e)},deleteData(e){let r={...c.getSnapshot()};delete r[e],c.setValue(r);let n=p.get(e);n&&(p.delete(e),n.abortController.abort("Deleted"))},clear(){c.delete();for(let{abortController:e}of Array.from(p.values()))e.abort("Cleared");p.clear()},mount(e){h.set(e,(_nullishCoalesce(h.get(e), () => (0)))+1)},unmount(e){let t=h.get(e);t===1?h.delete(e):h.set(e,(_nullishCoalesce(t, () => (0)))-1)},enforceSizeLimit:O};return S}var W={lastUpdatedMs:0,loading:!0};function de(a,...M){let i=_chunkJOHZV3FDmincjs.a.call(void 0, M),[p,h]=_chunk433OAJVPmincjs.d.call(void 0, a.queryState),m=_react.useRef.call(void 0, !0),u=_react.useMemo.call(void 0, ()=>a.getQueryKey(i),[a,i]),y=_nullishCoalesce(p[u], () => (W)),D=_react.useCallback.call(void 0, s=>{h(l=>{let o={...l};return o[u]=typeof s=="function"?s(_nullishCoalesce(o[u], () => (W))):s,o})},[u,h]),[x,A]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{a.keepLastNonEmptyData&&y.data!==void 0&&A(y.data)},[a.keepLastNonEmptyData,y.data]);let T=_react.useCallback.call(void 0, async s=>{if(a.log(`Begin executing shared query ${u}, isRefetch=${s}`),!!m.current){D(l=>({...l,lastUpdatedMs:Date.now(),loading:!0}));try{let l;if(s){let o=await a.refetch(...i),c=Date.now();l={lastUpdatedMs:c,loading:!1,data:o,dataUpdatedMs:c}}else l=await a.getCachedOrFetch(...i);return m.current?(D({...l,loading:!1}),l.data):void 0}catch(l){if(!m.current)return;let o=Date.now();D(c=>({...c,lastUpdatedMs:o,loading:!1,error:l,errorUpdatedMs:o}))}}},[a,u,D,i]);return _react.useEffect.call(void 0, ()=>(m.current=!0,a.mount(u),T(!1),()=>{m.current=!1,a.unmount(u)}),[T,a,u]),_react.useMemo.call(void 0, ()=>({...y,data:y.data!==void 0?y.data:x,latestData:y.data,abortCurrentQuery:s=>{let l=a.getAbortControllerByKey(u);return _optionalChain([l, 'optionalAccess', _28 => _28.abort, 'call', _29 => _29(s)]),!!l},getCachedOrFetch:async()=>{let s=await a.getCachedOrFetch(...i);return _nonNil.nonNil.call(void 0, s.data,typeof s.error=="string"?s.error:JSON.stringify(s.error))},refetch:()=>T(!0),setData:(s,l)=>{a.setData(u,s,l)},deleteData:()=>{a.deleteData(u)}}),[T,x,a,u,y,i])}exports.a = Q; exports.b = ue; exports.c = le; exports.d = de;
|
|
2
|
+
//# sourceMappingURL=chunk-RP2TWHFU.min.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/choksheaklau/src/react-utils/dist/chunk-RP2TWHFU.min.cjs","../src/sharedQuery.ts"],"names":["SharedQueryConfig","args","configureSharedQuery","config","seenQueryNames","sharedQuery","options","url","queryName","inflightQueries","mountedKeys","queryFn","fetcher","http","retries","params","firstArg","entries","k","v","item","refetchFn","staleMs","expiryMs","refetchOnStale","store","isValid","u","persistTo","maxSize","maxBytes","keepLastNonEmptyData","log","queryState","sharedState","isStale","dataUpdatedMs","isExpired","enforceSizeLimit","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut"],"mappings":"AAAA,g1BAAmD,+DAA6C,+DAA6C,gDCqF/G,oDACP,yGACC,8BAQjB,wFACS,IAqLHA,CAAAA,CAAoB,CAE/B,OAAA,CAAS,CAAA,CAGT,QAAA,CAAU,EAAA,CAAK,KAAA,CAGf,cAAA,CAAgB,CAAA,CAAA,CAGhB,SAAA,CAAW,KAAA,CAAA,CAGX,OAAA,CAAS,GAAA,CAGT,QAAA,CAAU,GAAA,CAGV,GAAA,CAAK,CAAA,GAAIC,CAAAA,CAAAA,EAAoB,OAAA,CAAQ,GAAA,CAAI,eAAA,CAAiB,GAAGA,CAAI,CACnE,CAAA,CAKO,SAASC,EAAAA,CAAqBC,CAAAA,CAAoC,CACvE,MAAA,CAAO,MAAA,CAAOH,CAAAA,CAAmBG,CAAM,CACzC,CAMA,IAAMC,CAAAA,CAAiB,IAAI,GAAA,CAoBpB,SAASC,EAAAA,CAGdC,CAAAA,CACA,CAEA,IAAM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\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Think of shared queries as like the open source npm package \"react-query\",\n * but with strong type-checking and built-in support for persistence.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n * import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, userId);\n *\n * // You can check for user.loading and user.error if needed.\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { http, retries } from \"@choksheak/ts-utils/http\";\nimport { nonNil } from \"@choksheak/ts-utils/nonNil\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport XXH from \"xxhashjs\";\n\nimport { sharedState, SharedStateOptions, useSharedState } from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,\n * then this will contain the latest data (undefined when args just changed)\n * and data will contain the last non empty data.\n */\n latestData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Let the caller get the data immediately no matter what.\n */\n getCachedOrFetch: () => Promise<TData>;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => Promise<TData | undefined>;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\nexport type QueryTargetWithFn<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /** Function to fetch data. */\n queryFn: QueryFn<TArgs, TData>;\n};\n\nexport type QueryTargetWithUrl = {\n /**\n * The queryName can optionally be specified, else we will fallback to use\n * the url as the queryName.\n */\n queryName?: string;\n\n /**\n * URL to fetch data using HTTP GET. Note that using this field will cause\n * both TArgs and TData to be undefined (unknown). Therefore you can make up\n * for this by specifying types with useSharedQuery, like this:\n * ```\n * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n *\n * If `userId` were specified as [\"u1\", \"u2\"], the query url would be\n * \"/api/list-users?userId=u1&userId=u2\".\n *\n * You can also pass the params as a string like \"userId=u1&userId=u2\".\n * ```\n * const usersQuery = useSharedQuery<[string], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n */\n url: string;\n};\n\n/** Specifies how to fetch the data. */\nexport type QueryTarget<TArgs extends unknown[], TData> =\n | QueryTargetWithFn<TArgs, TData>\n | QueryTargetWithUrl;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<\n TArgs,\n TData\n> & {\n /**\n * Function to re-fetch data. Usually this would just be the `queryFn`, but\n * if you need a different behavior for refetching, then specify this.\n */\n refetchFn?: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * 86_400_000 /* MS_PER_DAY */,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Whether this is a normal query or an explicit refetch. */\ntype QueryType = \"query\" | \"refetch\";\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is mainly used for logging and also\n * used as the storage key when you use the top-level `persistTo`.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n // If queryName is not specified, fallback to use url as the queryName.\n const url = (options as QueryTargetWithUrl).url || \"\";\n const queryName = options.queryName || url;\n\n if (!queryName) {\n throw new Error(`Either queryName or url must be specified.`);\n }\n\n if (seenQueryNames.has(queryName)) {\n // In hot reloads, this keeps on triggering. So we just warn and not throw\n // an error.\n console.warn(`Duplicate shared query name \"${queryName}\"`);\n }\n seenQueryNames.add(queryName);\n\n const inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n const mountedKeys = new Map<string, number>();\n\n let queryFn: QueryFn<TArgs, TData>;\n\n if ((options as QueryTargetWithFn<TArgs, TData>).queryFn) {\n queryFn = (options as QueryTargetWithFn<TArgs, TData>).queryFn;\n } else if (url) {\n const fetcher = http.use(retries());\n\n // Auto-generate the queryFn as a HTTP GET request using the url.\n queryFn = async (...args: TArgs): Promise<TData> => {\n // If args are given, treat the first argument as a search param.\n let params = \"\";\n const firstArg = args?.[0];\n\n if (firstArg) {\n if (typeof firstArg === \"string\") {\n params = firstArg;\n } else if (typeof firstArg === \"object\") {\n const entries: [string, string][] = [];\n\n for (const [k, v] of Object.entries(firstArg)) {\n if (v === undefined) continue;\n\n // Allow the same param to be specified multiple times.\n if (Array.isArray(v)) {\n for (const item of v) {\n if (item === undefined) continue;\n\n // The field values can only be primitives, not objects.\n entries.push([k, String(item)]);\n }\n } else {\n // The field values can only be primitives, not objects.\n entries.push([k, String(v)]);\n }\n }\n\n params = new URLSearchParams(entries).toString();\n }\n\n if (params) {\n if (url.includes(\"?\")) {\n // Append more search params to existing ones.\n params = \"&\" + params;\n } else {\n // Set the full search params string.\n params = \"?\" + params;\n }\n }\n }\n\n const response = await fetcher.get(url + params);\n\n return await response.json();\n };\n } else {\n throw new Error(`Either queryFn or url must be specified`);\n }\n\n const refetchFn = options.refetchFn;\n\n const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n const refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n const store = options.store;\n\n if (store) {\n // Wrap the isValid to account for the query state wrapper.\n if (\"persistTo\" in store && store.isValid) {\n const isValid = store.isValid;\n\n options = {\n ...options,\n store: {\n ...store,\n isValid: (u) => {\n // Supposed type of u: SharedQueryState<TData>\n if (!u || typeof u !== \"object\") {\n return false;\n }\n\n // Since each stored key could contain multiple values, and isValid\n // checks for each value, we need to check every value to make sure\n // they are valid.\n // Supposed type of v: QueryStateValue<TData>\n for (const v of Object.values(u)) {\n if (\n !v ||\n typeof v !== \"object\" ||\n !(\"data\" in v) ||\n !(\"dataUpdatedMs\" in v) ||\n !(\"lastUpdatedMs\" in v) ||\n typeof v.dataUpdatedMs !== \"number\" ||\n typeof v.lastUpdatedMs !== \"number\" ||\n !isValid(v.data)\n ) {\n return false;\n }\n }\n\n return true;\n },\n },\n };\n }\n } else {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options = {\n ...options,\n store: {\n persistTo,\n key: queryName,\n expiryMs,\n },\n };\n }\n }\n\n const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n const log = options?.log ?? SharedQueryConfig.log;\n\n const queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n\n function isStale(dataUpdatedMs: number): boolean {\n if (staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > staleMs;\n }\n\n function isExpired(dataUpdatedMs: number): boolean {\n if (expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > expiryMs;\n }\n\n function enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!maxSize && !maxBytes) {\n return;\n }\n\n const oldState = queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = maxSize ? oldSize - maxSize : 0;\n let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n log(\n `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n log(\n `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (mountedKeys.has(key)) {\n log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n log(\n `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n log(\n `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`,\n );\n }\n\n function setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n enforceSizeLimit();\n }\n\n async function startFetching(\n queryKey: string,\n queryType: QueryType,\n args: TArgs,\n ) {\n log(`Start fetching ${queryKey}, queryType=${queryType}`);\n\n try {\n const data = await (queryType === \"refetch\" && refetchFn\n ? refetchFn(...args)\n : queryFn(...args));\n\n log(`Successfully fetched ${queryKey}`);\n setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);\n throw e;\n } finally {\n inflightQueries.delete(queryKey);\n }\n }\n\n function dedupedFetch(\n queryKey: string,\n queryType: QueryType,\n ...args: TArgs\n ): Promise<TData> {\n const inflightQuery = inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests. Note that queries and refetches are\n // also deduped because they should technically be trying to fetch the same\n // data.\n if (inflightQuery) {\n log(\n `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`,\n );\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = startFetching(queryKey, queryType, args);\n const abortController = new AbortController();\n\n inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n const obj = {\n queryName,\n queryFn,\n refetchFn,\n expiryMs,\n staleMs,\n refetchOnStale,\n maxSize,\n maxBytes,\n keepLastNonEmptyData,\n log,\n queryState,\n\n /** Returns a key to identify requests based on the given args. */\n getQueryKey(args: TArgs): string {\n let s = stringifyDeterministicForKeys(args);\n\n // Ensure the query key is not too long.\n if (s.length > 30) {\n s = XXH.h32(s, 0x99ee).toString(16).slice(2); // remove \"0x\"\n }\n\n return queryName + \":\" + s;\n },\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n getAbortController(args: TArgs): AbortController | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortControllerByKey(queryKey);\n },\n\n getAbortControllerByKey(queryKey: string): AbortController | null {\n return inflightQueries.get(queryKey)?.abortController ?? null;\n },\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example using fetch:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n *\n * Example using `http.ts`:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await http.get(`/users/${userId}`, { signal });\n * return await response.json();\n * },\n * });\n * ```\n */\n getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortSignalByKey(queryKey);\n },\n\n getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return obj.getAbortControllerByKey(queryKey)?.signal ?? null;\n },\n\n /** For cached data, we need to return the correct timestamps as well. */\n async getCachedOrFetch(...args: TArgs): Promise<QueryStateValue<TData>> {\n // Important: wait for data to be loaded from cache first before trying to\n // fetch from server. This fixes a bad bug where the data is big, and the\n // code here starts a server fetch before the cache data loaded.\n const startMs = Date.now();\n await queryState.readyPromise;\n const waitedMs = Date.now() - startMs;\n\n const queryKey = obj.getQueryKey(args);\n const cached = queryState.getSnapshot()?.[queryKey];\n\n if (waitedMs) {\n log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);\n }\n\n if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!isStale(cached.dataUpdatedMs ?? 0)) {\n log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached;\n }\n\n // If stale, optionally update the data in the background.\n if (refetchOnStale) {\n log(`refetchOnStale for ${queryKey}`);\n void dedupedFetch(queryKey, \"query\", ...args);\n }\n\n // Still return stale data immediately.\n log(`Returning stale data for ${queryKey}`);\n return cached;\n }\n\n const data = await dedupedFetch(queryKey, \"query\", ...args);\n const now = Date.now();\n\n return {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n },\n\n /** Get the entire stored entry for a query key. */\n getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return queryState.getSnapshot()?.[queryKey];\n },\n\n /** Get the current stored data for a query key. */\n getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (isExpired(stateValue.lastUpdatedMs)) {\n obj.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n },\n\n /** Set the data directly if the user obtained it from somewhere else. */\n setData,\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n async updateFromSource(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"query\", ...args);\n },\n\n /**\n * Perform an explicit refetch. If `options.refetchFn` was not specified,\n * then this would be identical to calling `obj.updateFromSource()`.\n */\n async refetch(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"refetch\", ...args);\n },\n\n /** Delete the cached data for one set of arguments. */\n deleteData(queryKey: string): void {\n const record = queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n queryState.setValue(clone);\n\n const inflight = inflightQueries.get(queryKey);\n if (inflight) {\n inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n },\n\n /** Delete all currently cached data & all inflight promises. */\n clear(): void {\n queryState.delete();\n\n for (const { abortController } of Array.from(inflightQueries.values())) {\n abortController.abort(\"Cleared\");\n }\n\n inflightQueries.clear();\n },\n\n /** Keep track of mounted keys. */\n mount(queryKey: string): void {\n mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);\n },\n\n /** Clean up mounted keys. */\n unmount(queryKey: string): void {\n const count = mountedKeys.get(queryKey);\n if (count === 1) {\n mountedKeys.delete(queryKey);\n } else {\n mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n },\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n enforceSizeLimit,\n } as const;\n\n return obj;\n}\n\nexport type SharedQuery<TArgs extends unknown[], TData> = ReturnType<\n typeof sharedQuery<TArgs, TData>\n>;\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const executeQuery = useCallback(\n async (isRefetch: boolean): Promise<TData | undefined> => {\n query.log(\n `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`,\n );\n\n if (!isMounted.current) return;\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n let state: QueryStateValue<TData>;\n\n if (isRefetch) {\n const data = await query.refetch(...stableArgs);\n const now = Date.now();\n\n state = {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n } else {\n state = await query.getCachedOrFetch(...stableArgs);\n }\n\n if (!isMounted.current) return;\n\n // Make sure to reset loading to false.\n setQueryStateValue({ ...state, loading: false });\n\n return state.data;\n } catch (e) {\n if (!isMounted.current) return;\n\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void executeQuery(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [executeQuery, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n\n // Fill with lastNonEmptyData when data is undefined.\n data:\n queryStateValue.data !== undefined\n ? queryStateValue.data\n : lastNonEmptyData,\n\n latestData: queryStateValue.data,\n\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown): boolean => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n getCachedOrFetch: async (): Promise<TData> => {\n const data = await query.getCachedOrFetch(...stableArgs);\n\n return nonNil(\n data.data,\n typeof data.error === \"string\"\n ? data.error\n : JSON.stringify(data.error),\n );\n },\n refetch: (): Promise<TData | undefined> => {\n return executeQuery(true);\n },\n setData: (data: TData, dataUpdatedMs?: number): void => {\n query.setData(queryKey, data, dataUpdatedMs);\n },\n deleteData: (): void => {\n query.deleteData(queryKey);\n },\n } satisfies UseQueryResult<TData>;\n }, [\n executeQuery,\n lastNonEmptyData,\n query,\n queryKey,\n queryStateValue,\n stableArgs,\n ]);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as P,d as v}from"./chunk-BQIRLDQC.min.mjs";import{a as z}from"./chunk-TI3FMEYP.min.mjs";import{a as B}from"./chunk-NL4FU2MJ.min.mjs";import{http as X,retries as Y}from"@choksheak/ts-utils/http";import{nonNil as H}from"@choksheak/ts-utils/nonNil";import F from"object-sizeof";import{useCallback as E,useEffect as L,useMemo as R,useRef as I,useState as J}from"react";import G from"xxhashjs";var Q={staleMs:0,expiryMs:30*864e5,refetchOnStale:!0,persistTo:void 0,maxSize:100,maxBytes:1e5,log:(...a)=>console.log("[sharedQuery]",...a)};function ue(a){Object.assign(Q,a)}var j=new Set;function le(a){let M=a.url||"",i=a.queryName||M;if(!i)throw new Error("Either queryName or url must be specified.");j.has(i)&&console.warn(`Duplicate shared query name "${i}"`),j.add(i);let p=new Map,h=new Map,m;if(a.queryFn)m=a.queryFn;else if(M){let e=X.use(Y());m=async(...t)=>{let r="",n=t?.[0];if(n){if(typeof n=="string")r=n;else if(typeof n=="object"){let f=[];for(let[b,w]of Object.entries(n))if(w!==void 0)if(Array.isArray(w))for(let $ of w)$!==void 0&&f.push([b,String($)]);else f.push([b,String(w)]);r=new URLSearchParams(f).toString()}r&&(M.includes("?")?r="&"+r:r="?"+r)}return await(await e.get(M+r)).json()}}else throw new Error("Either queryFn or url must be specified");let u=a.refetchFn,y=a?.staleMs??Q.staleMs,D=a?.expiryMs??Q.expiryMs,x=a?.refetchOnStale??Q.refetchOnStale,A=a.store;if(A){if("persistTo"in A&&A.isValid){let e=A.isValid;a={...a,store:{...A,isValid:t=>{if(!t||typeof t!="object")return!1;for(let r of Object.values(t))if(!r||typeof r!="object"||!("data"in r)||!("dataUpdatedMs"in r)||!("lastUpdatedMs"in r)||typeof r.dataUpdatedMs!="number"||typeof r.lastUpdatedMs!="number"||!e(r.data))return!1;return!0}}}}}else{let e=a.persistTo??Q.persistTo;e&&(a={...a,store:{persistTo:e,key:i,expiryMs:D}})}let T=a?.maxSize??Q.maxSize,s=a?.maxBytes??Q.maxBytes,l=!!a?.keepLastNonEmptyData,o=a?.log??Q.log,c=P({},a);function K(e){return y===0?!0:Date.now()-e>y}function k(e){return D===0?!1:Date.now()-e>D}function O(){if(!T&&!s)return;let e=c.getSnapshot(),t=Object.keys(e).length;if(t<=1)return;let r=F(e),n=T?t-T:0,d=s?r-s:0;if(n<=0&&d<=0){o(`No need to trim data for ${i}: size=${t} (limit=${T}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}o(`Need to trim ${i}: numToCut=${n}, bytesToCut=${d}`);let f={...e},b=!1,w=(g,U)=>{if(h.has(g)){o(`Cannot clean up ${g} as it is mounted`);return}let N=F(g)+F(f[g]);o(`Cleaning up unmounted${U?", expired":""} ${g} (byteSize=${N.toLocaleString()})`),n--,d-=N,delete f[g],b=!0},$=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs);for(let[g]of $){if(!k(f[g].lastUpdatedMs))break;w(g,!0)}if(n>0||d>0){b&&($=Object.entries(f).sort((g,U)=>g[1].lastUpdatedMs-U[1].lastUpdatedMs));for(let[g]of $)if(w(g,!1),n<=0&&d<=0)break}if(!b){o(`No trimmable entries found for ${i}: size=${t} (limit=${T}), byteSize=${r.toLocaleString()} (limit=${s.toLocaleString()})`);return}c.setValue(f),o(`Trimmed data for ${i}: size=[${t} -> ${Object.keys(f).length}] (limit=${T}), byteSize=[${r.toLocaleString()} -> ${F(f).toLocaleString()}] (limit=${s.toLocaleString()})`)}function V(e,t,r=Date.now()){let n={lastUpdatedMs:Date.now(),loading:!1,data:t,dataUpdatedMs:r};c.setValue(d=>({...d,[e]:n})),O()}async function _(e,t,r){o(`Start fetching ${e}, queryType=${t}`);try{let n=await(t==="refetch"&&u?u(...r):m(...r));return o(`Successfully fetched ${e}`),V(e,n,Date.now()),n}catch(n){throw o(`Failed to fetch ${e} for queryType=${t}: ${n}`),n}finally{p.delete(e)}}function C(e,t,...r){let n=p.get(e);if(n)return o(`Deduplicating inflight fetch for ${e}, queryType=${t}`),n.promise;let d=_(e,t,r),f=new AbortController;return p.set(e,{promise:d,abortController:f}),d}let S={queryName:i,queryFn:m,refetchFn:u,expiryMs:D,staleMs:y,refetchOnStale:x,maxSize:T,maxBytes:s,keepLastNonEmptyData:l,log:o,queryState:c,getQueryKey(e){let t=z(e);return t.length>30&&(t=G.h32(t,39406).toString(16).slice(2)),i+":"+t},getAbortController(e){let t=S.getQueryKey(e);return S.getAbortControllerByKey(t)},getAbortControllerByKey(e){return p.get(e)?.abortController??null},getAbortSignal(e){let t=S.getQueryKey(e);return S.getAbortSignalByKey(t)},getAbortSignalByKey(e){return S.getAbortControllerByKey(e)?.signal??null},async getCachedOrFetch(...e){let t=Date.now();await c.readyPromise;let r=Date.now()-t,n=S.getQueryKey(e),d=c.getSnapshot()?.[n];if(r&&o(`${n}: Waited for ${r}ms before data is ready`),d?.data&&!k(d.dataUpdatedMs??0))return K(d.dataUpdatedMs??0)?(x&&(o(`refetchOnStale for ${n}`),C(n,"query",...e)),o(`Returning stale data for ${n}`),d):(o(`Return fresh data ${n} from cache without fetching`),d);let f=await C(n,"query",...e),b=Date.now();return{lastUpdatedMs:b,loading:!1,data:f,dataUpdatedMs:b}},getQueryValue(e){return c.getSnapshot()?.[e]},getData(e){let t=c.getSnapshot()?.[e];if(t?.lastUpdatedMs&&k(t.lastUpdatedMs)){S.deleteData(e);return}return t?.data},setData:V,async updateFromSource(...e){let t=S.getQueryKey(e);return await C(t,"query",...e)},async refetch(...e){let t=S.getQueryKey(e);return await C(t,"refetch",...e)},deleteData(e){let r={...c.getSnapshot()};delete r[e],c.setValue(r);let n=p.get(e);n&&(p.delete(e),n.abortController.abort("Deleted"))},clear(){c.delete();for(let{abortController:e}of Array.from(p.values()))e.abort("Cleared");p.clear()},mount(e){h.set(e,(h.get(e)??0)+1)},unmount(e){let t=h.get(e);t===1?h.delete(e):h.set(e,(t??0)-1)},enforceSizeLimit:O};return S}var W={lastUpdatedMs:0,loading:!0};function de(a,...M){let i=B(M),[p,h]=v(a.queryState),m=I(!0),u=R(()=>a.getQueryKey(i),[a,i]),y=p[u]??W,D=E(s=>{h(l=>{let o={...l};return o[u]=typeof s=="function"?s(o[u]??W):s,o})},[u,h]),[x,A]=J();L(()=>{a.keepLastNonEmptyData&&y.data!==void 0&&A(y.data)},[a.keepLastNonEmptyData,y.data]);let T=E(async s=>{if(a.log(`Begin executing shared query ${u}, isRefetch=${s}`),!!m.current){D(l=>({...l,lastUpdatedMs:Date.now(),loading:!0}));try{let l;if(s){let o=await a.refetch(...i),c=Date.now();l={lastUpdatedMs:c,loading:!1,data:o,dataUpdatedMs:c}}else l=await a.getCachedOrFetch(...i);return m.current?(D({...l,loading:!1}),l.data):void 0}catch(l){if(!m.current)return;let o=Date.now();D(c=>({...c,lastUpdatedMs:o,loading:!1,error:l,errorUpdatedMs:o}))}}},[a,u,D,i]);return L(()=>(m.current=!0,a.mount(u),T(!1),()=>{m.current=!1,a.unmount(u)}),[T,a,u]),R(()=>({...y,data:y.data!==void 0?y.data:x,latestData:y.data,abortCurrentQuery:s=>{let l=a.getAbortControllerByKey(u);return l?.abort(s),!!l},getCachedOrFetch:async()=>{let s=await a.getCachedOrFetch(...i);return H(s.data,typeof s.error=="string"?s.error:JSON.stringify(s.error))},refetch:()=>T(!0),setData:(s,l)=>{a.setData(u,s,l)},deleteData:()=>{a.deleteData(u)}}),[T,x,a,u,y,i])}export{Q as a,ue as b,le as c,de as d};
|
|
2
|
+
//# sourceMappingURL=chunk-XRHQCN2J.min.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sharedQuery.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * The \"shared query\" is a data fetching convenience library that helps users\n * to load data, check for staleness and expiration, cache in memory, local\n * storage or indexed db, and be able to manipulate the data anytime.\n *\n * Each shared query creates a new private shared state that handles the data\n * storage. This shared state contains the records for all queries, where each\n * query is a unique set of arguments used to make the query. The number of\n * records and the total byte size of data can be limited so as to ensure the\n * query does not take up too much memory.\n *\n * Think of shared queries as like the open source npm package \"react-query\",\n * but with strong type-checking and built-in support for persistence.\n *\n * Example:\n * ```\n * import { sharedQuery, useSharedQuery } from \"@choksheak/react-utils/sharedQuery\";\n * import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\n *\n * // Create a new shared query in the top level scope.\n * // The query function `queryFn` here does not take any arguments.\n * //\n * // Only the queryName and queryFn are required and everything else is\n * // optional.\n * //\n * // The queryName must be unique, otherwise we will throw an\n * // error. This is because defining the same queryName for two different\n * // queries implies that the queries are the same, thus violating the idea\n * // of a \"shared\" query, and almost certainly points to a bug in the code.\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * // Example of using a query function with arguments.\n * export const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: getUser, // getUser(userId: string) => User\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n *\n * export const UsersComponent: React.FC = () => {\n * // Second argument is optional, and is an array of arguments to be\n * // passed to the `queryFn`.\n * const users = useSharedQuery(usersQuery);\n *\n * return (\n * <>\n * <h1>List of Users</h1>\n *\n * <button onclick={users.refetch}>Refresh</button>\n *\n * {users.loading && <Loader />}\n *\n * {users.error && !users.data && <p>Error: {String(users.error)}</p>}\n *\n * <p>Data: {users.data ? JSON.stringify(users.data) : \"-\"}</p>\n * </>\n * );\n * };\n *\n * export const AnotherComponent: React.FC = () => {\n * // This query will be deduped with the one above, sharing the same\n * // data and the same fetches.\n * const users = useSharedQuery(usersQuery);\n * ...\n * };\n *\n * export const DisplayOneUser: React.FC<{userId: string}> = ({userId}) => {\n * // Example of using the query with an argument. Whenever the argument\n * // changes, the data will be fetched and updated automatically.\n * const user = useSharedQuery(getUserQuery, userId);\n *\n * // You can check for user.loading and user.error if needed.\n *\n * return <>User: {user.data ? JSON.stringify(user.data) : \"-\"}</>;\n * };\n * ```\n */\n\nimport { http, retries } from \"@choksheak/ts-utils/http\";\nimport { nonNil } from \"@choksheak/ts-utils/nonNil\";\nimport getByteSize from \"object-sizeof\";\nimport {\n SetStateAction,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport XXH from \"xxhashjs\";\n\nimport { sharedState, SharedStateOptions, useSharedState } from \"./sharedState\";\nimport { PersistTo } from \"./storage\";\nimport { stringifyDeterministicForKeys } from \"./stringify\";\nimport { useDeepMemo } from \"./useDeepMemo\";\n\n/** Type of the queryFn used to fetch the data from source. */\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\n/** An entry for a persisted state corresponding to one query key. */\nexport type QueryStateValue<TData> = Readonly<{\n /**\n * When this record was last updated. Used for LRU determination. If you want\n * the data age, please use `dataUpdatedMs` instead.\n */\n lastUpdatedMs: number;\n\n loading: boolean;\n data?: TData;\n dataUpdatedMs?: number;\n\n /**\n * Use unknown type for error because we can't assume what type of variable\n * will be thrown from the query function. We also don't want to add this\n * type to QueryStateValue<TError> as it adds complexity to the type.\n */\n error?: unknown;\n\n errorUpdatedMs?: number;\n}>;\n\n/** Return type for useSharedQuery(). */\nexport type UseQueryResult<TData> = QueryStateValue<TData> &\n Readonly<{\n /**\n * Usually same as `data`, but if you specify `keepLastNonEmptyData: true`,\n * then this will contain the latest data (undefined when args just changed)\n * and data will contain the last non empty data.\n */\n latestData: TData | undefined;\n\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Let the caller get the data immediately no matter what.\n */\n getCachedOrFetch: () => Promise<TData>;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => Promise<TData | undefined>;\n\n /**\n * If you got the data from somewhere else (e.g. an in-memory data update),\n * just set it directly.\n */\n setData: (data: TData, dataUpdatedMs?: number) => void;\n\n deleteData: () => void;\n }>;\n\n/**\n * The full query state is a record of all the fetch states mapped by\n * query key to the state entry.\n */\nexport type SharedQueryState<TData> = Record<string, QueryStateValue<TData>>;\n\nexport type QueryTargetWithFn<TArgs extends unknown[], TData> = {\n /**\n * The name could have been auto-generated, but we let the user give us a\n * human-readable name that can be identified quickly in the logs.\n * Note that the queryKey is a string formed by the queryName plus the query\n * arguments.\n */\n queryName: string;\n\n /** Function to fetch data. */\n queryFn: QueryFn<TArgs, TData>;\n};\n\nexport type QueryTargetWithUrl = {\n /**\n * The queryName can optionally be specified, else we will fallback to use\n * the url as the queryName.\n */\n queryName?: string;\n\n /**\n * URL to fetch data using HTTP GET. Note that using this field will cause\n * both TArgs and TData to be undefined (unknown). Therefore you can make up\n * for this by specifying types with useSharedQuery, like this:\n * ```\n * const usersQuery = useSharedQuery<[{ userId?: string[] }], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n *\n * If `userId` were specified as [\"u1\", \"u2\"], the query url would be\n * \"/api/list-users?userId=u1&userId=u2\".\n *\n * You can also pass the params as a string like \"userId=u1&userId=u2\".\n * ```\n * const usersQuery = useSharedQuery<[string], User[]>({\n * url: \"/api/list-users\",\n * });\n * ```\n */\n url: string;\n};\n\n/** Specifies how to fetch the data. */\nexport type QueryTarget<TArgs extends unknown[], TData> =\n | QueryTargetWithFn<TArgs, TData>\n | QueryTargetWithUrl;\n\n/** Options to configure a shared query. */\nexport type SharedQueryOptions<TArgs extends unknown[], TData> = QueryTarget<\n TArgs,\n TData\n> & {\n /**\n * Function to re-fetch data. Usually this would just be the `queryFn`, but\n * if you need a different behavior for refetching, then specify this.\n */\n refetchFn?: QueryFn<TArgs, TData>;\n\n /**\n * ms before data considered stale; 0 means always stale.\n */\n staleMs?: number;\n\n /**\n * ms before data is removed from cache; 0 means never expire.\n */\n expiryMs?: number;\n\n /**\n * Trigger background re-fetch if stale.\n */\n refetchOnStale?: boolean;\n\n /**\n * Shortcut to set the localStorageKey or indexedDbKey automatically from\n * queryName. This is important because it avoids requiring the user to\n * specify the same queryName twice everytime.\n */\n persistTo?: PersistTo;\n\n /**\n * Max number of entries to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxSize?: number;\n\n /**\n * Max number of bytes to keep. The oldest entries will be discarded.\n * The last record cannot be discarded. 0 means no limit.\n */\n maxBytes?: number;\n\n /**\n * Keep a copy of the last non-empty data so that when you change the\n * query arguments, you can still display the old data while waiting for the\n * new data to load.\n */\n keepLastNonEmptyData?: boolean;\n\n /**\n * Customize the logger.\n */\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryConfig = {\n /** Refetch on every page load. */\n staleMs: 0,\n\n /** Keep in cache for a long time. */\n expiryMs: 30 * 86_400_000 /* MS_PER_DAY */,\n\n /** Always refetch automatically if the data is stale. */\n refetchOnStale: true,\n\n /** No default persistence configured. */\n persistTo: undefined as PersistTo | undefined,\n\n /** 100 is not too large, but please tweak accordingly. */\n maxSize: 100,\n\n /** 100kb limit before discarding old records. */\n maxBytes: 100_000,\n\n /** Default to log to console. */\n log: (...args: unknown[]) => console.log(\"[sharedQuery]\", ...args),\n};\n\nexport type SharedQueryConfig = typeof SharedQueryConfig;\n\n/** Convenience function to update global defaults. */\nexport function configureSharedQuery(config: Partial<SharedQueryConfig>) {\n Object.assign(SharedQueryConfig, config);\n}\n\n/** Whether this is a normal query or an explicit refetch. */\ntype QueryType = \"query\" | \"refetch\";\n\n// Disallow duplicate query names.\nconst seenQueryNames = new Set<string>();\n\n/**\n * Create a reusable shared query object that can be used to auto de-duplicate\n * and cache all data fetches, with auto-expiration and staleness checks.\n *\n * Each `queryName` must be unique, and can only be declared once, most often\n * in the top level scope. The queryName is mainly used for logging and also\n * used as the storage key when you use the top-level `persistTo`.\n *\n * Example:\n * ```\n * export const usersQuery = sharedQuery({\n * queryName: \"users\",\n * queryFn: listUsers,\n * persistTo: \"indexedDb\",\n * staleMs: MS_PER_DAY,\n * });\n * ```\n */\nexport function sharedQuery<TArgs extends unknown[], TData>(\n // The name could have been auto-generated, but we let the user give us a\n // human-readable name that can be identified quickly in the logs.\n options: SharedQueryOptions<TArgs, TData>,\n) {\n // If queryName is not specified, fallback to use url as the queryName.\n const url = (options as QueryTargetWithUrl).url || \"\";\n const queryName = options.queryName || url;\n\n if (!queryName) {\n throw new Error(`Either queryName or url must be specified.`);\n }\n\n if (seenQueryNames.has(queryName)) {\n // In hot reloads, this keeps on triggering. So we just warn and not throw\n // an error.\n console.warn(`Duplicate shared query name \"${queryName}\"`);\n }\n seenQueryNames.add(queryName);\n\n const inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n /**\n * Keep track of the mounted query keys. This handles the case where an\n * earlier-started query returns later, and when it returns, it was already\n * unmounted, thus making it eligible for clean up right after fetch.\n */\n const mountedKeys = new Map<string, number>();\n\n let queryFn: QueryFn<TArgs, TData>;\n\n if ((options as QueryTargetWithFn<TArgs, TData>).queryFn) {\n queryFn = (options as QueryTargetWithFn<TArgs, TData>).queryFn;\n } else if (url) {\n const fetcher = http.use(retries());\n\n // Auto-generate the queryFn as a HTTP GET request using the url.\n queryFn = async (...args: TArgs): Promise<TData> => {\n // If args are given, treat the first argument as a search param.\n let params = \"\";\n const firstArg = args?.[0];\n\n if (firstArg) {\n if (typeof firstArg === \"string\") {\n params = firstArg;\n } else if (typeof firstArg === \"object\") {\n const entries: [string, string][] = [];\n\n for (const [k, v] of Object.entries(firstArg)) {\n if (v === undefined) continue;\n\n // Allow the same param to be specified multiple times.\n if (Array.isArray(v)) {\n for (const item of v) {\n if (item === undefined) continue;\n\n // The field values can only be primitives, not objects.\n entries.push([k, String(item)]);\n }\n } else {\n // The field values can only be primitives, not objects.\n entries.push([k, String(v)]);\n }\n }\n\n params = new URLSearchParams(entries).toString();\n }\n\n if (params) {\n if (url.includes(\"?\")) {\n // Append more search params to existing ones.\n params = \"&\" + params;\n } else {\n // Set the full search params string.\n params = \"?\" + params;\n }\n }\n }\n\n const response = await fetcher.get(url + params);\n\n return await response.json();\n };\n } else {\n throw new Error(`Either queryFn or url must be specified`);\n }\n\n const refetchFn = options.refetchFn;\n\n const staleMs = options?.staleMs ?? SharedQueryConfig.staleMs;\n const expiryMs = options?.expiryMs ?? SharedQueryConfig.expiryMs;\n\n const refetchOnStale =\n options?.refetchOnStale ?? SharedQueryConfig.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the `store` will take precedence over `persistTo`.\n const store = options.store;\n\n if (store) {\n // Wrap the isValid to account for the query state wrapper.\n if (\"persistTo\" in store && store.isValid) {\n const isValid = store.isValid;\n\n options = {\n ...options,\n store: {\n ...store,\n isValid: (u) => {\n // Supposed type of u: SharedQueryState<TData>\n if (!u || typeof u !== \"object\") {\n return false;\n }\n\n // Since each stored key could contain multiple values, and isValid\n // checks for each value, we need to check every value to make sure\n // they are valid.\n // Supposed type of v: QueryStateValue<TData>\n for (const v of Object.values(u)) {\n if (\n !v ||\n typeof v !== \"object\" ||\n !(\"data\" in v) ||\n !(\"dataUpdatedMs\" in v) ||\n !(\"lastUpdatedMs\" in v) ||\n typeof v.dataUpdatedMs !== \"number\" ||\n typeof v.lastUpdatedMs !== \"number\" ||\n !isValid(v.data)\n ) {\n return false;\n }\n }\n\n return true;\n },\n },\n };\n }\n } else {\n const persistTo = options.persistTo ?? SharedQueryConfig.persistTo;\n\n if (persistTo) {\n options = {\n ...options,\n store: {\n persistTo,\n key: queryName,\n expiryMs,\n },\n };\n }\n }\n\n const maxSize = options?.maxSize ?? SharedQueryConfig.maxSize;\n const maxBytes = options?.maxBytes ?? SharedQueryConfig.maxBytes;\n\n const keepLastNonEmptyData = Boolean(options?.keepLastNonEmptyData);\n\n const log = options?.log ?? SharedQueryConfig.log;\n\n const queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n options,\n );\n\n function isStale(dataUpdatedMs: number): boolean {\n if (staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > staleMs;\n }\n\n function isExpired(dataUpdatedMs: number): boolean {\n if (expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > expiryMs;\n }\n\n function enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!maxSize && !maxBytes) {\n return;\n }\n\n const oldState = queryState.getSnapshot();\n const oldSize = Object.keys(oldState).length;\n\n // Cannot do GC if size is 1 or less.\n if (oldSize <= 1) {\n return;\n }\n\n const oldByteSize = getByteSize(oldState);\n\n let numToCut = maxSize ? oldSize - maxSize : 0;\n let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;\n\n // Log to indicate why trimming was not needed.\n if (numToCut <= 0 && bytesToCut <= 0) {\n log(\n `No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Log to inform user that trimming is needed.\n log(\n `Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`,\n );\n\n const newState = { ...oldState }; // shallow clone\n let needUpdate = false;\n\n const deleteKeyIfNotMounted = (key: string, expired: boolean) => {\n // Mounted keys cannot be cleaned up as they are visible in the UI.\n if (mountedKeys.has(key)) {\n log(`Cannot clean up ${key} as it is mounted`);\n return;\n }\n\n const byteSize = getByteSize(key) + getByteSize(newState[key]);\n log(\n `Cleaning up unmounted${expired ? \", expired\" : \"\"} ${key} (byteSize=${byteSize.toLocaleString()})`,\n );\n\n numToCut--;\n bytesToCut -= byteSize;\n\n delete newState[key];\n needUpdate = true;\n };\n\n let entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n // Clean up all expired entries. Note that the auto-expiration in the\n // storage adapter only applies to the entire state, which contains all\n // the different query keys and their values. Each query key has its own\n // timestamp and we need to apply our own expiration here.\n for (const [key] of entriesByTimeAscending) {\n // Anything after this is not expired yet.\n if (!isExpired(newState[key].lastUpdatedMs)) {\n break;\n }\n\n deleteKeyIfNotMounted(key, true);\n }\n\n if (numToCut > 0 || bytesToCut > 0) {\n if (needUpdate) {\n entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n }\n\n // Clean up starting from oldest entry first.\n for (const [key] of entriesByTimeAscending) {\n deleteKeyIfNotMounted(key, false);\n\n if (numToCut <= 0 && bytesToCut <= 0) {\n break;\n }\n }\n }\n\n // Log to indicate why trimming was not needed.\n if (!needUpdate) {\n log(\n `No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`,\n );\n return;\n }\n\n // Update the state.\n queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n log(\n `Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`,\n );\n }\n\n function setData(\n queryKey: string,\n data: TData,\n dataUpdatedMs = Date.now(),\n ): void {\n const entry: QueryStateValue<TData> = {\n lastUpdatedMs: Date.now(),\n loading: false,\n data,\n dataUpdatedMs,\n };\n\n queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n enforceSizeLimit();\n }\n\n async function startFetching(\n queryKey: string,\n queryType: QueryType,\n args: TArgs,\n ) {\n log(`Start fetching ${queryKey}, queryType=${queryType}`);\n\n try {\n const data = await (queryType === \"refetch\" && refetchFn\n ? refetchFn(...args)\n : queryFn(...args));\n\n log(`Successfully fetched ${queryKey}`);\n setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);\n throw e;\n } finally {\n inflightQueries.delete(queryKey);\n }\n }\n\n function dedupedFetch(\n queryKey: string,\n queryType: QueryType,\n ...args: TArgs\n ): Promise<TData> {\n const inflightQuery = inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests. Note that queries and refetches are\n // also deduped because they should technically be trying to fetch the same\n // data.\n if (inflightQuery) {\n log(\n `Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`,\n );\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = startFetching(queryKey, queryType, args);\n const abortController = new AbortController();\n\n inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n const obj = {\n queryName,\n queryFn,\n refetchFn,\n expiryMs,\n staleMs,\n refetchOnStale,\n maxSize,\n maxBytes,\n keepLastNonEmptyData,\n log,\n queryState,\n\n /** Returns a key to identify requests based on the given args. */\n getQueryKey(args: TArgs): string {\n let s = stringifyDeterministicForKeys(args);\n\n // Ensure the query key is not too long.\n if (s.length > 30) {\n s = XXH.h32(s, 0x99ee).toString(16).slice(2); // remove \"0x\"\n }\n\n return queryName + \":\" + s;\n },\n\n /**\n * Get the AbortController to abort the inflight query (if any).\n *\n * Note that once you get the controller, you can also get the signal easily\n * using `controller.signal`. So if you need both the controller and the\n * signal, just use this function.\n */\n getAbortController(args: TArgs): AbortController | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortControllerByKey(queryKey);\n },\n\n getAbortControllerByKey(queryKey: string): AbortController | null {\n return inflightQueries.get(queryKey)?.abortController ?? null;\n },\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example using fetch:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await fetch(`/users/${userId}`, { signal });\n *\n * // Check for errors.\n * if (!response.ok) {\n * throw new Error(response.statusText);\n * }\n *\n * // Return the data.\n * return await response.json();\n * },\n * });\n * ```\n *\n * Example using `http.ts`:\n * ```\n * const getUserQuery = sharedQuery({\n * queryName: \"getUser\",\n * queryFn: (userId: string) => {\n * // Get the signal for this current execution.\n * const signal = getUserQuery.getAbortSignal([userId]);\n *\n * // Pass the signal to fetch so that it can be aborted.\n * const response = await http.get(`/users/${userId}`, { signal });\n * return await response.json();\n * },\n * });\n * ```\n */\n getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = obj.getQueryKey(args);\n return obj.getAbortSignalByKey(queryKey);\n },\n\n getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return obj.getAbortControllerByKey(queryKey)?.signal ?? null;\n },\n\n /** For cached data, we need to return the correct timestamps as well. */\n async getCachedOrFetch(...args: TArgs): Promise<QueryStateValue<TData>> {\n // Important: wait for data to be loaded from cache first before trying to\n // fetch from server. This fixes a bad bug where the data is big, and the\n // code here starts a server fetch before the cache data loaded.\n const startMs = Date.now();\n await queryState.readyPromise;\n const waitedMs = Date.now() - startMs;\n\n const queryKey = obj.getQueryKey(args);\n const cached = queryState.getSnapshot()?.[queryKey];\n\n if (waitedMs) {\n log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);\n }\n\n if (cached?.data && !isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!isStale(cached.dataUpdatedMs ?? 0)) {\n log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached;\n }\n\n // If stale, optionally update the data in the background.\n if (refetchOnStale) {\n log(`refetchOnStale for ${queryKey}`);\n void dedupedFetch(queryKey, \"query\", ...args);\n }\n\n // Still return stale data immediately.\n log(`Returning stale data for ${queryKey}`);\n return cached;\n }\n\n const data = await dedupedFetch(queryKey, \"query\", ...args);\n const now = Date.now();\n\n return {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n },\n\n /** Get the entire stored entry for a query key. */\n getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return queryState.getSnapshot()?.[queryKey];\n },\n\n /** Get the current stored data for a query key. */\n getData(queryKey: string): TData | undefined {\n const stateValue: QueryStateValue<TData> | undefined =\n queryState.getSnapshot()?.[queryKey];\n\n // Check for expiration.\n if (stateValue?.lastUpdatedMs) {\n if (isExpired(stateValue.lastUpdatedMs)) {\n obj.deleteData(queryKey);\n return undefined;\n }\n }\n\n return stateValue?.data;\n },\n\n /** Set the data directly if the user obtained it from somewhere else. */\n setData,\n\n /**\n * Do a new fetch even when the data is already cached, but don't fetch if\n * another fetch is already inflight.\n */\n async updateFromSource(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"query\", ...args);\n },\n\n /**\n * Perform an explicit refetch. If `options.refetchFn` was not specified,\n * then this would be identical to calling `obj.updateFromSource()`.\n */\n async refetch(...args: TArgs): Promise<TData> {\n const key = obj.getQueryKey(args);\n return await dedupedFetch(key, \"refetch\", ...args);\n },\n\n /** Delete the cached data for one set of arguments. */\n deleteData(queryKey: string): void {\n const record = queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n queryState.setValue(clone);\n\n const inflight = inflightQueries.get(queryKey);\n if (inflight) {\n inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n },\n\n /** Delete all currently cached data & all inflight promises. */\n clear(): void {\n queryState.delete();\n\n for (const { abortController } of Array.from(inflightQueries.values())) {\n abortController.abort(\"Cleared\");\n }\n\n inflightQueries.clear();\n },\n\n /** Keep track of mounted keys. */\n mount(queryKey: string): void {\n mountedKeys.set(queryKey, (mountedKeys.get(queryKey) ?? 0) + 1);\n },\n\n /** Clean up mounted keys. */\n unmount(queryKey: string): void {\n const count = mountedKeys.get(queryKey);\n if (count === 1) {\n mountedKeys.delete(queryKey);\n } else {\n mountedKeys.set(queryKey, (count ?? 0) - 1);\n }\n },\n\n /**\n * Discard the oldest entries if the size exceeds the limit. The last\n * remaining record cannot be deleted no matter what the limit is.\n */\n enforceSizeLimit,\n } as const;\n\n return obj;\n}\n\nexport type SharedQuery<TArgs extends unknown[], TData> = ReturnType<\n typeof sharedQuery<TArgs, TData>\n>;\n\n// Using any so that we don't need to typecast later.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst DEFAULT_QUERY_STATE_ENTRY: Readonly<QueryStateValue<any>> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component. The\n * args do not need to be specified if no args are needed, i.e. this would work\n * ```\n * const allUsers = useSharedQuery(listUsersQuery);\n * ```\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, \"userid123\");\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Optional: Default to use no arguments.\n ...args: TArgs\n): UseQueryResult<TData> {\n // We don't expect users to provide a stable `args`, so stabilize it here.\n const stableArgs = useDeepMemo(args);\n\n const [queryState, setQueryState] = useSharedState(query.queryState);\n\n const isMounted = useRef(true);\n\n const queryKey = useMemo(\n () => query.getQueryKey(stableArgs),\n [query, stableArgs],\n );\n\n // Init with empty object.\n const queryStateValue: QueryStateValue<TData> =\n queryState[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY;\n\n const setQueryStateValue = useCallback(\n (next: SetStateAction<QueryStateValue<TData>>) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof next === \"function\"\n ? next(clone[queryKey] ?? DEFAULT_QUERY_STATE_ENTRY)\n : next;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // Keep the last non-empty data loaded in case you want to show a placeholder\n // during new loads.\n const [lastNonEmptyData, setLastNonEmptyData] = useState<TData | undefined>();\n\n useEffect(() => {\n if (query.keepLastNonEmptyData && queryStateValue.data !== undefined) {\n setLastNonEmptyData(queryStateValue.data);\n }\n }, [query.keepLastNonEmptyData, queryStateValue.data]);\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const executeQuery = useCallback(\n async (isRefetch: boolean): Promise<TData | undefined> => {\n query.log(\n `Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`,\n );\n\n if (!isMounted.current) return;\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...prev,\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n let state: QueryStateValue<TData>;\n\n if (isRefetch) {\n const data = await query.refetch(...stableArgs);\n const now = Date.now();\n\n state = {\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n };\n } else {\n state = await query.getCachedOrFetch(...stableArgs);\n }\n\n if (!isMounted.current) return;\n\n // Make sure to reset loading to false.\n setQueryStateValue({ ...state, loading: false });\n\n return state.data;\n } catch (e) {\n if (!isMounted.current) return;\n\n const now = Date.now();\n\n setQueryStateValue((prev) => ({\n // Keep old data.\n ...prev,\n lastUpdatedMs: now,\n loading: false,\n error: e,\n errorUpdatedMs: now,\n }));\n }\n },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n query.mount(queryKey);\n\n void executeQuery(false);\n\n return () => {\n isMounted.current = false;\n query.unmount(queryKey);\n };\n }, [executeQuery, query, queryKey]);\n\n return useMemo(() => {\n return {\n ...queryStateValue,\n\n // Fill with lastNonEmptyData when data is undefined.\n data:\n queryStateValue.data !== undefined\n ? queryStateValue.data\n : lastNonEmptyData,\n\n latestData: queryStateValue.data,\n\n // This works only if the user-given queryFn supports abort. If not,\n // this function doesn't do anything, since we don't have any means to\n // abort the running queryFn.\n abortCurrentQuery: (reason?: unknown): boolean => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n getCachedOrFetch: async (): Promise<TData> => {\n const data = await query.getCachedOrFetch(...stableArgs);\n\n return nonNil(\n data.data,\n typeof data.error === \"string\"\n ? data.error\n : JSON.stringify(data.error),\n );\n },\n refetch: (): Promise<TData | undefined> => {\n return executeQuery(true);\n },\n setData: (data: TData, dataUpdatedMs?: number): void => {\n query.setData(queryKey, data, dataUpdatedMs);\n },\n deleteData: (): void => {\n query.deleteData(queryKey);\n },\n } satisfies UseQueryResult<TData>;\n }, [\n executeQuery,\n lastNonEmptyData,\n query,\n queryKey,\n queryStateValue,\n stableArgs,\n ]);\n}\n"],"mappings":"8IAqFA,OAAS,QAAAA,EAAM,WAAAC,MAAe,2BAC9B,OAAS,UAAAC,MAAc,6BACvB,OAAOC,MAAiB,gBACxB,OAEE,eAAAC,EACA,aAAAC,EACA,WAAAC,EACA,UAAAC,EACA,YAAAC,MACK,QACP,OAAOC,MAAS,WAqLT,IAAMC,EAAoB,CAE/B,QAAS,EAGT,SAAU,GAAK,MAGf,eAAgB,GAGhB,UAAW,OAGX,QAAS,IAGT,SAAU,IAGV,IAAK,IAAIC,IAAoB,QAAQ,IAAI,gBAAiB,GAAGA,CAAI,CACnE,EAKO,SAASC,GAAqBC,EAAoC,CACvE,OAAO,OAAOH,EAAmBG,CAAM,CACzC,CAMA,IAAMC,EAAiB,IAAI,IAoBpB,SAASC,GAGdC,EACA,CAEA,IAAMC,EAAOD,EAA+B,KAAO,GAC7CE,EAAYF,EAAQ,WAAaC,EAEvC,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,4CAA4C,EAG1DJ,EAAe,IAAII,CAAS,GAG9B,QAAQ,KAAK,gCAAgCA,CAAS,GAAG,EAE3DJ,EAAe,IAAII,CAAS,EAE5B,IAAMC,EAAkB,IAAI,IAUtBC,EAAc,IAAI,IAEpBC,EAEJ,GAAKL,EAA4C,QAC/CK,EAAWL,EAA4C,gBAC9CC,EAAK,CACd,IAAMK,EAAUC,EAAK,IAAIC,EAAQ,CAAC,EAGlCH,EAAU,SAAUV,IAAgC,CAElD,IAAIc,EAAS,GACPC,EAA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,EAAG,CACV,GAAI,CAACwB,EAAU,QAAS,OAExB,IAAMZ,EAAM,KAAK,IAAI,EAErBgB,EAAoB/B,IAAU,CAE5B,GAAGA,EACH,cAAee,EACf,QAAS,GACT,MAAOZ,EACP,eAAgBY,CAClB,EAAE,CACJ,EACF,EACA,CAACO,EAAOzB,EAAUkC,EAAoBR,CAAU,CAClD,EAEA,OAAAc,EAAU,KACRV,EAAU,QAAU,GACpBL,EAAM,MAAMzB,CAAQ,EAEfyC,EAAa,EAAK,EAEhB,IAAM,CACXX,EAAU,QAAU,GACpBL,EAAM,QAAQzB,CAAQ,CACxB,GACC,CAACyC,EAAchB,EAAOzB,CAAQ,CAAC,EAE3BgC,EAAQ,KACN,CACL,GAAGC,EAGH,KACEA,EAAgB,OAAS,OACrBA,EAAgB,KAChBI,EAEN,WAAYJ,EAAgB,KAK5B,kBAAoBW,GAA8B,CAChD,IAAMC,EAAapB,EAAM,wBAAwBzB,CAAQ,EACzD,OAAA6C,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,iBAAkB,SAA4B,CAC5C,IAAM5C,EAAO,MAAMwB,EAAM,iBAAiB,GAAGC,CAAU,EAEvD,OAAOoB,EACL7C,EAAK,KACL,OAAOA,EAAK,OAAU,SAClBA,EAAK,MACL,KAAK,UAAUA,EAAK,KAAK,CAC/B,CACF,EACA,QAAS,IACAwC,EAAa,EAAI,EAE1B,QAAS,CAACxC,EAAapB,IAAiC,CACtD4C,EAAM,QAAQzB,EAAUC,EAAMpB,CAAa,CAC7C,EACA,WAAY,IAAY,CACtB4C,EAAM,WAAWzB,CAAQ,CAC3B,CACF,GACC,CACDyC,EACAJ,EACAZ,EACAzB,EACAiC,EACAP,CACF,CAAC,CACH","names":["http","retries","nonNil","getByteSize","useCallback","useEffect","useMemo","useRef","useState","XXH","SharedQueryConfig","args","configureSharedQuery","config","seenQueryNames","sharedQuery","options","url","queryName","inflightQueries","mountedKeys","queryFn","fetcher","http","retries","params","firstArg","entries","k","v","item","refetchFn","staleMs","expiryMs","refetchOnStale","store","isValid","u","persistTo","maxSize","maxBytes","keepLastNonEmptyData","log","queryState","sharedState","isStale","dataUpdatedMs","isExpired","enforceSizeLimit","oldState","oldSize","oldByteSize","getByteSize","numToCut","bytesToCut","newState","needUpdate","deleteKeyIfNotMounted","key","expired","byteSize","entriesByTimeAscending","entry1","entry2","setData","queryKey","data","entry","prev","startFetching","queryType","e","dedupedFetch","inflightQuery","promise","abortController","obj","s","stringifyDeterministicForKeys","XXH","startMs","waitedMs","cached","now","stateValue","clone","inflight","count","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","setQueryState","useSharedState","isMounted","useRef","useMemo","queryStateValue","setQueryStateValue","useCallback","next","lastNonEmptyData","setLastNonEmptyData","useState","useEffect","executeQuery","isRefetch","state","reason","controller","nonNil"]}
|
|
@@ -68,7 +68,14 @@ function createPubSubStore() {
|
|
|
68
68
|
}
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
function getOrCreatePubSubStore() {
|
|
72
|
+
if (typeof window !== "undefined") {
|
|
73
|
+
const t = window.globalThis;
|
|
74
|
+
return t.reactUtilsPubSubStore || (t.reactUtilsPubSubStore = createPubSubStore());
|
|
75
|
+
}
|
|
76
|
+
return createPubSubStore();
|
|
77
|
+
}
|
|
78
|
+
var pubSubStore = getOrCreatePubSubStore();
|
|
72
79
|
var STORAGE_KEY = "state";
|
|
73
80
|
var stateKey = 0;
|
|
74
81
|
function sharedState(defaultValue, options) {
|
|
@@ -93,6 +100,7 @@ function sharedState(defaultValue, options) {
|
|
|
93
100
|
resolveReadyPromise();
|
|
94
101
|
}
|
|
95
102
|
const obj = {
|
|
103
|
+
defaultValue,
|
|
96
104
|
/** Allow users to await for the completion of data init. */
|
|
97
105
|
readyPromise,
|
|
98
106
|
lazy,
|