@choksheak/react-utils 0.2.5 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/package.json +1 -4
- package/sharedQuery.d.mts +14 -0
- package/sharedQuery.d.ts +13 -0
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.mjs.map +1 -1
- package/sharedState.d.mts +3 -0
- package/sharedState.d.ts +3 -1
- package/sharedState.min.cjs.map +1 -1
- package/sharedState.min.mjs.map +1 -1
- package/index.cjs +0 -4
- package/index.d.mts +0 -2
- package/index.d.ts +0 -0
- package/index.min.cjs +0 -2
- package/index.min.cjs.map +0 -1
- package/index.min.mjs +0 -2
- package/index.min.mjs.map +0 -1
- package/index.mjs +0 -12
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@choksheak/react-utils",
|
|
3
3
|
"license": "The Unlicense",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.6",
|
|
5
5
|
"description": "Miscellaneous React+TypeScript utilities with support for full tree-shaking.",
|
|
6
6
|
"private": false,
|
|
7
|
-
"main": "index.js",
|
|
8
|
-
"module": "index.mjs",
|
|
9
|
-
"types": "index.d.ts",
|
|
10
7
|
"files": [
|
|
11
8
|
"**/*"
|
|
12
9
|
],
|
package/sharedQuery.d.mts
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { SharedStateOptions, SharedState } from './sharedState.mjs';
|
|
2
2
|
import './utils/storage.mjs';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* The "shared query" is a data fetching convenience library that helps users
|
|
6
|
+
* to load data, check for staleness and expiration, cache in memory, local
|
|
7
|
+
* storage or indexed db, and be able to manipulate the data anytime.
|
|
8
|
+
*
|
|
9
|
+
* Each shared query creates a new private shared state that handles the data
|
|
10
|
+
* storage. This shared state contains the records for all queries, where each
|
|
11
|
+
* query is a unique set of arguments used to make the query. The number of
|
|
12
|
+
* records and the total byte size of data can be limited so as to ensure the
|
|
13
|
+
* query does not take up too much memory.
|
|
14
|
+
*
|
|
15
|
+
* @packageDocumentation
|
|
16
|
+
*/
|
|
17
|
+
|
|
4
18
|
type QueryFn<TArgs extends unknown[], TData> = (...args: TArgs) => Promise<TData> | TData;
|
|
5
19
|
type QueryStateValue<TData> = {
|
|
6
20
|
/**
|
package/sharedQuery.d.ts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "shared query" is a data fetching convenience library that helps users
|
|
3
|
+
* to load data, check for staleness and expiration, cache in memory, local
|
|
4
|
+
* storage or indexed db, and be able to manipulate the data anytime.
|
|
5
|
+
*
|
|
6
|
+
* Each shared query creates a new private shared state that handles the data
|
|
7
|
+
* storage. This shared state contains the records for all queries, where each
|
|
8
|
+
* query is a unique set of arguments used to make the query. The number of
|
|
9
|
+
* records and the total byte size of data can be limited so as to ensure the
|
|
10
|
+
* query does not take up too much memory.
|
|
11
|
+
*
|
|
12
|
+
* @packageDocumentation
|
|
13
|
+
*/
|
|
1
14
|
import { SharedState, SharedStateOptions } from "./sharedState";
|
|
2
15
|
export type QueryFn<TArgs extends unknown[], TData> = (...args: TArgs) => Promise<TData> | TData;
|
|
3
16
|
export type QueryStateValue<TData> = {
|
package/sharedQuery.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/utils/storage.ts","../src/utils/stringify.ts","../src/utils/useDeepMemo.ts"],"sourcesContent":["import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { stringifyDeterministicForKeys } from \"./utils/stringify\";\nimport { useDeepMemo } from \"./utils/useDeepMemo\";\n\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\nexport type QueryStateValue<TData> = {\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\nexport type UseQueryResult<TData> = QueryStateValue<TData> & {\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\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\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\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 SharedQueryOptions<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 queryName: string;\n\n // Function to fetch data.\n queryFn: QueryFn<TArgs, TData>;\n\n // ms before data considered stale; 0 means always stale.\n staleMs?: number;\n\n // ms before data is removed from cache; 0 means never expire.\n expiryMs?: number;\n\n // Trigger background re-fetch if stale.\n refetchOnStale?: boolean;\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 persistTo?: PersistTo;\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 maxSize?: number;\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 maxBytes?: number;\n\n // Customize the logger.\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryDefaults = {\n // Refetch on every page load.\n staleMs: 0,\n\n // Keep in cache for a long time.\n expiryMs: 30 * 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 class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryDefaults.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryDefaults.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryDefaults.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the storage keys will take precedence over `persistTo`.\n if (!options.localStorageKey && !options.indexedDbKey) {\n const persistTo = options.persistTo ?? SharedQueryDefaults.persistTo;\n\n if (persistTo === \"localStorage\") {\n options.localStorageKey = options.queryName;\n } else if (persistTo === \"indexedDb\") {\n options.indexedDbKey = options.queryName;\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryDefaults.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryDefaults.maxBytes;\n\n this.log = options?.log ?? SharedQueryDefaults.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n {\n ...options,\n // Fallback to use expiryMs for the storeExpiryMs.\n storeExpiryMs: options?.storeExpiryMs || this.expiryMs,\n },\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\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 public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\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 public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n return this.queryState.getSnapshot()?.[queryKey]?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public 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 this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\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 public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\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 public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.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 newState = oldState;\n let needUpdate = false;\n\n // Limit by number of records.\n if (this.maxSize) {\n const numToCut = oldSize - this.maxSize;\n\n if (numToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to size ${oldSize} > ${this.maxSize}`,\n );\n\n newState = { ...newState }; // shallow clone\n needUpdate = true;\n\n Object.entries(newState)\n .sort(\n (entry1, entry2) =>\n // Sort descending.\n entry2[1].lastUpdatedMs - entry1[1].lastUpdatedMs,\n )\n .slice(-numToCut)\n .forEach(([key]) => {\n delete newState[key];\n });\n }\n }\n\n // Limit by byte size.\n if (this.maxBytes && Object.keys(newState).length > 1) {\n // Recompute only if changed by above code.\n const currentByteSize = needUpdate ? getByteSize(newState) : oldByteSize;\n\n let bytesToCut = currentByteSize - this.maxBytes;\n\n if (bytesToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to byte size ${currentByteSize.toLocaleString()} > ${this.maxBytes.toLocaleString()}`,\n );\n\n // Shallow clone only if not already cloned above.\n if (!needUpdate) {\n newState = { ...newState };\n needUpdate = true;\n }\n\n const entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n for (\n let i = 0;\n // Leave the last record entriesByTimeAscending[len-1] untouched.\n i < entriesByTimeAscending.length - 1 && bytesToCut > 0;\n i++\n ) {\n const key = entriesByTimeAscending[i][0];\n const thisSize = getByteSize(key) + getByteSize(newState[key]);\n delete newState[key];\n bytesToCut -= thisSize;\n }\n }\n }\n\n // Update the state.\n if (needUpdate) {\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=(${oldSize} -> ${Object.keys(newState).length}) (limit=${this.maxSize}), byteSize=(${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}) (limit=${this.maxBytes.toLocaleString()})`,\n );\n\n return;\n }\n\n // Log to indicate why trimming was not needed.\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\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 used for logging only.\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): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\nconst DEFAULT_QUERY_STATE_ENTRY: QueryStateValue<unknown> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component.\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, [\"123\"]);\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Default to use no arguments.\n args: TArgs = [] as unknown as 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 // Make sure typechecker knows this could be undefined.\n const queryStateValue = queryState[queryKey] as\n | QueryStateValue<TData>\n | undefined;\n\n const setQueryStateValue = useCallback(\n (\n arg:\n | QueryStateValue<TData>\n | ((\n prev: QueryStateValue<TData> | undefined,\n ) => QueryStateValue<TData>),\n ) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof arg === \"function\" ? arg(clone[queryKey]) : arg;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...(prev ?? {}),\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\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 },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n };\n }, [execute]);\n\n return useMemo(() => {\n const state =\n queryStateValue ?? (DEFAULT_QUERY_STATE_ENTRY as QueryStateValue<TData>);\n\n return {\n ...state,\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) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...(prev ?? {}),\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n };\n }, [\n execute,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n */\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/** Provides a stable value for T based on deep equality. */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,IAAA,eAAAC,EAAAN,GAAA,IAAAO,EAA2B,6CAC3BC,EAAwB,4BACxBC,EAAwD,iBCFxD,IAAAC,EAA2B,6CAC3BC,EAAqC,iBCDrC,IAAAC,EAAwB,uCAuBjB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,gBAAAC,EAAiB,aAAAC,EAAc,cAAAC,EAAe,MAAAC,CAAM,EAAIL,GAAW,CAAC,EAE5E,GAAIK,EACF,OAAOA,EAGT,IAAMC,EAAWF,GAAiBH,EAElC,OAAIC,EACK,IAAIK,EAAuBL,EAAiBI,CAAQ,EAGzDH,EACK,IAAIK,EAAoBL,EAAcG,CAAQ,EAGhD,IACT,CA+CO,IAAMG,EAAN,KAA0D,CACxD,YACWC,EACAC,EAChB,CAFgB,eAAAD,EACA,cAAAC,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AAQ,CAAE,GAAGF,CAAK,EACxB,cAAOE,EAAMX,CAAQ,EACdW,CACT,CAAC,CACH,CACF,GACC,CACD8B,EACAV,EACA/B,EACAsC,EACAH,EACAI,CACF,CAAC,CACH","names":["sharedQuery_exports","__export","SharedQuery","SharedQueryDefaults","sharedQuery","useSharedQuery","__toCommonJS","import_timeConstants","import_object_sizeof","import_react","import_timeConstants","import_react","import_kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","k","SharedStateDefaults","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","import_isEqual","import_react","useDeepMemo","value","state","setState","isEqual","SharedQueryDefaults","args","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","entry","prev","key","clone","inflight","oldState","oldSize","oldByteSize","getByteSize","newState","needUpdate","numToCut","entry1","entry2","currentByteSize","bytesToCut","entriesByTimeAscending","i","thisSize","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","queryStateValue","setQueryStateValue","arg","execute","forceRefresh","now","reason","controller"]}
|
|
1
|
+
{"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/utils/storage.ts","../src/utils/stringify.ts","../src/utils/useDeepMemo.ts"],"sourcesContent":["/**\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 * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { stringifyDeterministicForKeys } from \"./utils/stringify\";\nimport { useDeepMemo } from \"./utils/useDeepMemo\";\n\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\nexport type QueryStateValue<TData> = {\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\nexport type UseQueryResult<TData> = QueryStateValue<TData> & {\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\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\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\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 SharedQueryOptions<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 queryName: string;\n\n // Function to fetch data.\n queryFn: QueryFn<TArgs, TData>;\n\n // ms before data considered stale; 0 means always stale.\n staleMs?: number;\n\n // ms before data is removed from cache; 0 means never expire.\n expiryMs?: number;\n\n // Trigger background re-fetch if stale.\n refetchOnStale?: boolean;\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 persistTo?: PersistTo;\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 maxSize?: number;\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 maxBytes?: number;\n\n // Customize the logger.\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryDefaults = {\n // Refetch on every page load.\n staleMs: 0,\n\n // Keep in cache for a long time.\n expiryMs: 30 * 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 class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryDefaults.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryDefaults.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryDefaults.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the storage keys will take precedence over `persistTo`.\n if (!options.localStorageKey && !options.indexedDbKey) {\n const persistTo = options.persistTo ?? SharedQueryDefaults.persistTo;\n\n if (persistTo === \"localStorage\") {\n options.localStorageKey = options.queryName;\n } else if (persistTo === \"indexedDb\") {\n options.indexedDbKey = options.queryName;\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryDefaults.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryDefaults.maxBytes;\n\n this.log = options?.log ?? SharedQueryDefaults.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n {\n ...options,\n // Fallback to use expiryMs for the storeExpiryMs.\n storeExpiryMs: options?.storeExpiryMs || this.expiryMs,\n },\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\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 public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\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 public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n return this.queryState.getSnapshot()?.[queryKey]?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public 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 this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\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 public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\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 public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.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 newState = oldState;\n let needUpdate = false;\n\n // Limit by number of records.\n if (this.maxSize) {\n const numToCut = oldSize - this.maxSize;\n\n if (numToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to size ${oldSize} > ${this.maxSize}`,\n );\n\n newState = { ...newState }; // shallow clone\n needUpdate = true;\n\n Object.entries(newState)\n .sort(\n (entry1, entry2) =>\n // Sort descending.\n entry2[1].lastUpdatedMs - entry1[1].lastUpdatedMs,\n )\n .slice(-numToCut)\n .forEach(([key]) => {\n delete newState[key];\n });\n }\n }\n\n // Limit by byte size.\n if (this.maxBytes && Object.keys(newState).length > 1) {\n // Recompute only if changed by above code.\n const currentByteSize = needUpdate ? getByteSize(newState) : oldByteSize;\n\n let bytesToCut = currentByteSize - this.maxBytes;\n\n if (bytesToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to byte size ${currentByteSize.toLocaleString()} > ${this.maxBytes.toLocaleString()}`,\n );\n\n // Shallow clone only if not already cloned above.\n if (!needUpdate) {\n newState = { ...newState };\n needUpdate = true;\n }\n\n const entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n for (\n let i = 0;\n // Leave the last record entriesByTimeAscending[len-1] untouched.\n i < entriesByTimeAscending.length - 1 && bytesToCut > 0;\n i++\n ) {\n const key = entriesByTimeAscending[i][0];\n const thisSize = getByteSize(key) + getByteSize(newState[key]);\n delete newState[key];\n bytesToCut -= thisSize;\n }\n }\n }\n\n // Update the state.\n if (needUpdate) {\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=(${oldSize} -> ${Object.keys(newState).length}) (limit=${this.maxSize}), byteSize=(${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}) (limit=${this.maxBytes.toLocaleString()})`,\n );\n\n return;\n }\n\n // Log to indicate why trimming was not needed.\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\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 used for logging only.\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): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\nconst DEFAULT_QUERY_STATE_ENTRY: QueryStateValue<unknown> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component.\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, [\"123\"]);\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Default to use no arguments.\n args: TArgs = [] as unknown as 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 // Make sure typechecker knows this could be undefined.\n const queryStateValue = queryState[queryKey] as\n | QueryStateValue<TData>\n | undefined;\n\n const setQueryStateValue = useCallback(\n (\n arg:\n | QueryStateValue<TData>\n | ((\n prev: QueryStateValue<TData> | undefined,\n ) => QueryStateValue<TData>),\n ) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof arg === \"function\" ? arg(clone[queryKey]) : arg;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...(prev ?? {}),\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\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 },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n };\n }, [execute]);\n\n return useMemo(() => {\n const state =\n queryStateValue ?? (DEFAULT_QUERY_STATE_ENTRY as QueryStateValue<TData>);\n\n return {\n ...state,\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) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...(prev ?? {}),\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n };\n }, [\n execute,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/** Provides a stable value for T based on deep equality. */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,IAAA,eAAAC,EAAAN,GAcA,IAAAO,EAA2B,6CAC3BC,EAAwB,4BACxBC,EAAwD,iBCHxD,IAAAC,EAA2B,6CAC3BC,EAAqC,iBCdrC,IAAAC,EAAwB,uCAuBjB,SAASC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wB/B,CAAQ,EACzD,OAAA6C,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,QAAS,IAAM,CACRJ,EAAQ,EAAI,CACnB,EACA,QAAS,CAACnC,EAAaL,IAA2B,CAChD,IAAM0C,EAAM,KAAK,IAAI,EACrBJ,EAAoB9B,IAAU,CAC5B,GAAIA,GAAQ,CAAC,EACb,KAAAH,EACA,cAAeL,GAAiB0C,EAChC,cAAeA,EACf,QAAS,EACX,EAAE,CACJ,EACA,WAAY,IAAM,CAChBR,EAAe1B,GAAS,CACtB,IAAME,EAAQ,CAAE,GAAGF,CAAK,EACxB,cAAOE,EAAMX,CAAQ,EACdW,CACT,CAAC,CACH,CACF,GACC,CACD8B,EACAV,EACA/B,EACAsC,EACAH,EACAI,CACF,CAAC,CACH","names":["sharedQuery_exports","__export","SharedQuery","SharedQueryDefaults","sharedQuery","useSharedQuery","__toCommonJS","import_timeConstants","import_object_sizeof","import_react","import_timeConstants","import_react","import_kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","k","SharedStateDefaults","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","import_isEqual","import_react","useDeepMemo","value","state","setState","isEqual","SharedQueryDefaults","args","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","entry","prev","key","clone","inflight","oldState","oldSize","oldByteSize","getByteSize","newState","needUpdate","numToCut","entry1","entry2","currentByteSize","bytesToCut","entriesByTimeAscending","i","thisSize","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","queryStateValue","setQueryStateValue","arg","execute","forceRefresh","now","reason","controller"]}
|
package/sharedQuery.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/utils/storage.ts","../src/utils/stringify.ts","../src/utils/useDeepMemo.ts"],"sourcesContent":["import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { stringifyDeterministicForKeys } from \"./utils/stringify\";\nimport { useDeepMemo } from \"./utils/useDeepMemo\";\n\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\nexport type QueryStateValue<TData> = {\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\nexport type UseQueryResult<TData> = QueryStateValue<TData> & {\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\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\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\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 SharedQueryOptions<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 queryName: string;\n\n // Function to fetch data.\n queryFn: QueryFn<TArgs, TData>;\n\n // ms before data considered stale; 0 means always stale.\n staleMs?: number;\n\n // ms before data is removed from cache; 0 means never expire.\n expiryMs?: number;\n\n // Trigger background re-fetch if stale.\n refetchOnStale?: boolean;\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 persistTo?: PersistTo;\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 maxSize?: number;\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 maxBytes?: number;\n\n // Customize the logger.\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryDefaults = {\n // Refetch on every page load.\n staleMs: 0,\n\n // Keep in cache for a long time.\n expiryMs: 30 * 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 class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryDefaults.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryDefaults.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryDefaults.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the storage keys will take precedence over `persistTo`.\n if (!options.localStorageKey && !options.indexedDbKey) {\n const persistTo = options.persistTo ?? SharedQueryDefaults.persistTo;\n\n if (persistTo === \"localStorage\") {\n options.localStorageKey = options.queryName;\n } else if (persistTo === \"indexedDb\") {\n options.indexedDbKey = options.queryName;\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryDefaults.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryDefaults.maxBytes;\n\n this.log = options?.log ?? SharedQueryDefaults.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n {\n ...options,\n // Fallback to use expiryMs for the storeExpiryMs.\n storeExpiryMs: options?.storeExpiryMs || this.expiryMs,\n },\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\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 public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\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 public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n return this.queryState.getSnapshot()?.[queryKey]?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public 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 this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\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 public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\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 public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.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 newState = oldState;\n let needUpdate = false;\n\n // Limit by number of records.\n if (this.maxSize) {\n const numToCut = oldSize - this.maxSize;\n\n if (numToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to size ${oldSize} > ${this.maxSize}`,\n );\n\n newState = { ...newState }; // shallow clone\n needUpdate = true;\n\n Object.entries(newState)\n .sort(\n (entry1, entry2) =>\n // Sort descending.\n entry2[1].lastUpdatedMs - entry1[1].lastUpdatedMs,\n )\n .slice(-numToCut)\n .forEach(([key]) => {\n delete newState[key];\n });\n }\n }\n\n // Limit by byte size.\n if (this.maxBytes && Object.keys(newState).length > 1) {\n // Recompute only if changed by above code.\n const currentByteSize = needUpdate ? getByteSize(newState) : oldByteSize;\n\n let bytesToCut = currentByteSize - this.maxBytes;\n\n if (bytesToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to byte size ${currentByteSize.toLocaleString()} > ${this.maxBytes.toLocaleString()}`,\n );\n\n // Shallow clone only if not already cloned above.\n if (!needUpdate) {\n newState = { ...newState };\n needUpdate = true;\n }\n\n const entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n for (\n let i = 0;\n // Leave the last record entriesByTimeAscending[len-1] untouched.\n i < entriesByTimeAscending.length - 1 && bytesToCut > 0;\n i++\n ) {\n const key = entriesByTimeAscending[i][0];\n const thisSize = getByteSize(key) + getByteSize(newState[key]);\n delete newState[key];\n bytesToCut -= thisSize;\n }\n }\n }\n\n // Update the state.\n if (needUpdate) {\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=(${oldSize} -> ${Object.keys(newState).length}) (limit=${this.maxSize}), byteSize=(${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}) (limit=${this.maxBytes.toLocaleString()})`,\n );\n\n return;\n }\n\n // Log to indicate why trimming was not needed.\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\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 used for logging only.\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): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\nconst DEFAULT_QUERY_STATE_ENTRY: QueryStateValue<unknown> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component.\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, [\"123\"]);\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Default to use no arguments.\n args: TArgs = [] as unknown as 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 // Make sure typechecker knows this could be undefined.\n const queryStateValue = queryState[queryKey] as\n | QueryStateValue<TData>\n | undefined;\n\n const setQueryStateValue = useCallback(\n (\n arg:\n | QueryStateValue<TData>\n | ((\n prev: QueryStateValue<TData> | undefined,\n ) => QueryStateValue<TData>),\n ) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof arg === \"function\" ? arg(clone[queryKey]) : arg;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...(prev ?? {}),\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\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 },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n };\n }, [execute]);\n\n return useMemo(() => {\n const state =\n queryStateValue ?? (DEFAULT_QUERY_STATE_ENTRY as QueryStateValue<TData>);\n\n return {\n ...state,\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) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...(prev ?? {}),\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n };\n }, [\n execute,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n */\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/** Provides a stable value for T based on deep equality. */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,oCAC3B,OAAOC,MAAiB,gBACxB,OAAS,eAAAC,EAAa,aAAAC,EAAW,WAAAC,EAAS,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EAAU,QAAU,EACtB,GACC,CAACO,CAAO,CAAC,EAELL,EAAQ,KAIN,CACL,GAHAC,GAAoBX,EAOpB,kBAAoBmB,GAAqB,CACvC,IAAMC,EAAalB,EAAM,wBAAwB/B,CAAQ,EACzD,OAAAiD,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,QAAS,IAAM,CACRL,EAAQ,EAAI,CACnB,EACA,QAAS,CAACtC,EAAaL,IAA2B,CAChD,IAAM6C,EAAM,KAAK,IAAI,EACrBL,EAAoBhC,IAAU,CAC5B,GAAIA,GAAQ,CAAC,EACb,KAAAH,EACA,cAAeL,GAAiB6C,EAChC,cAAeA,EACf,QAAS,EACX,EAAE,CACJ,EACA,WAAY,IAAM,CAChBX,EAAe1B,GAAS,CACtB,IAAME,EAAQ,CAAE,GAAGF,CAAK,EACxB,cAAOE,EAAMX,CAAQ,EACdW,CACT,CAAC,CACH,CACF,GACC,CACDiC,EACAb,EACA/B,EACAwC,EACAL,EACAM,CACF,CAAC,CACH","names":["MS_PER_DAY","getByteSize","useCallback","useEffect","useMemo","useRef","MS_PER_DAY","useSyncExternalStore","kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","kvStore","k","SharedStateDefaults","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","isEqual","useMemo","useState","useDeepMemo","value","state","setState","SharedQueryDefaults","MS_PER_DAY","args","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","entry","prev","key","clone","inflight","oldState","oldSize","oldByteSize","getByteSize","newState","needUpdate","numToCut","entry1","entry2","currentByteSize","bytesToCut","entriesByTimeAscending","i","thisSize","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","useRef","useMemo","queryStateValue","setQueryStateValue","useCallback","arg","execute","forceRefresh","now","useEffect","reason","controller"]}
|
|
1
|
+
{"version":3,"sources":["../src/sharedQuery.ts","../src/sharedState.ts","../src/utils/storage.ts","../src/utils/stringify.ts","../src/utils/useDeepMemo.ts"],"sourcesContent":["/**\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 * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport getByteSize from \"object-sizeof\";\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\n\nimport {\n SharedState,\n sharedState,\n SharedStateOptions,\n useSharedState,\n} from \"./sharedState\";\nimport { stringifyDeterministicForKeys } from \"./utils/stringify\";\nimport { useDeepMemo } from \"./utils/useDeepMemo\";\n\nexport type QueryFn<TArgs extends unknown[], TData> = (\n ...args: TArgs\n) => Promise<TData> | TData;\n\nexport type QueryStateValue<TData> = {\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\nexport type UseQueryResult<TData> = QueryStateValue<TData> & {\n /**\n * Cancels the inflight query (if any). Returns true if canceled.\n */\n abortCurrentQuery: (reason?: unknown) => boolean;\n\n /**\n * Manually refresh the data by doing a new query.\n */\n refetch: () => void;\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\nexport type PersistTo = \"localStorage\" | \"indexedDb\";\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 SharedQueryOptions<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 queryName: string;\n\n // Function to fetch data.\n queryFn: QueryFn<TArgs, TData>;\n\n // ms before data considered stale; 0 means always stale.\n staleMs?: number;\n\n // ms before data is removed from cache; 0 means never expire.\n expiryMs?: number;\n\n // Trigger background re-fetch if stale.\n refetchOnStale?: boolean;\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 persistTo?: PersistTo;\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 maxSize?: number;\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 maxBytes?: number;\n\n // Customize the logger.\n log?: (...args: unknown[]) => void;\n} & SharedStateOptions<SharedQueryState<TData>>;\n\n/** Users can override these values globally. */\nexport const SharedQueryDefaults = {\n // Refetch on every page load.\n staleMs: 0,\n\n // Keep in cache for a long time.\n expiryMs: 30 * 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 class SharedQuery<TArgs extends unknown[], TData> {\n private readonly inflightQueries = new Map<\n string,\n { promise: Promise<TData>; abortController: AbortController }\n >();\n\n public readonly queryState: SharedState<SharedQueryState<TData>>;\n\n public readonly queryName: string;\n private readonly queryFn: QueryFn<TArgs, TData>;\n public readonly expiryMs: number;\n public readonly staleMs: number;\n public readonly refetchOnStale: boolean;\n public readonly maxSize: number;\n public readonly maxBytes: number;\n public readonly log: (...args: unknown[]) => void;\n\n public constructor(options: SharedQueryOptions<TArgs, TData>) {\n this.queryName = options.queryName;\n this.queryFn = options.queryFn;\n\n this.staleMs = options?.staleMs ?? SharedQueryDefaults.staleMs;\n this.expiryMs = options?.expiryMs ?? SharedQueryDefaults.expiryMs;\n\n this.refetchOnStale =\n options?.refetchOnStale ?? SharedQueryDefaults.refetchOnStale;\n\n // Apply shortcut when using `persistTo`.\n // Specifying the storage keys will take precedence over `persistTo`.\n if (!options.localStorageKey && !options.indexedDbKey) {\n const persistTo = options.persistTo ?? SharedQueryDefaults.persistTo;\n\n if (persistTo === \"localStorage\") {\n options.localStorageKey = options.queryName;\n } else if (persistTo === \"indexedDb\") {\n options.indexedDbKey = options.queryName;\n }\n }\n\n this.maxSize = options?.maxSize ?? SharedQueryDefaults.maxSize;\n this.maxBytes = options?.maxBytes ?? SharedQueryDefaults.maxBytes;\n\n this.log = options?.log ?? SharedQueryDefaults.log;\n\n this.queryState = sharedState<SharedQueryState<TData>>(\n {}, // defaultValue\n {\n ...options,\n // Fallback to use expiryMs for the storeExpiryMs.\n storeExpiryMs: options?.storeExpiryMs || this.expiryMs,\n },\n );\n }\n\n /** Returns a key to identify requests based on the given args. */\n public getQueryKey(args: TArgs): string {\n return this.queryName + \":\" + stringifyDeterministicForKeys(args);\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 public getAbortController(args: TArgs): AbortController | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortControllerByKey(queryKey);\n }\n\n public getAbortControllerByKey(queryKey: string): AbortController | null {\n return this.inflightQueries.get(queryKey)?.abortController ?? null;\n }\n\n /**\n * Get the AbortSignal to check for query abortions.\n *\n * Example:\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 public getAbortSignal(args: TArgs): AbortSignal | null {\n const queryKey = this.getQueryKey(args);\n return this.getAbortSignalByKey(queryKey);\n }\n\n public getAbortSignalByKey(queryKey: string): AbortSignal | null {\n return this.getAbortControllerByKey(queryKey)?.signal ?? null;\n }\n\n private isStale(dataUpdatedMs: number): boolean {\n if (this.staleMs === 0) return true; // always stale\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.staleMs;\n }\n\n private isExpired(dataUpdatedMs: number): boolean {\n if (this.expiryMs === 0) return false; // never expire\n\n const ageMs = Date.now() - dataUpdatedMs;\n return ageMs > this.expiryMs;\n }\n\n public async getCachedOrFetch(...args: TArgs): Promise<TData> {\n const queryKey = this.getQueryKey(args);\n const cached = this.queryState.getSnapshot()?.[queryKey];\n\n if (cached?.data && !this.isExpired(cached.dataUpdatedMs ?? 0)) {\n // Return cached value if not stale.\n if (!this.isStale(cached.dataUpdatedMs ?? 0)) {\n this.log(`Return fresh data ${queryKey} from cache without fetching`);\n return cached.data;\n }\n\n // If stale, optionally update the data in the background.\n if (this.refetchOnStale) {\n this.log(`refetchOnStale for ${queryKey}`);\n void this.dedupedFetch(queryKey, ...args);\n }\n\n // Still return stale data immediately.\n this.log(`Returning stale data for ${queryKey}`);\n return cached.data;\n }\n\n return await this.dedupedFetch(queryKey, ...args);\n }\n\n private dedupedFetch(queryKey: string, ...args: TArgs): Promise<TData> {\n const inflightQuery = this.inflightQueries.get(queryKey);\n\n // De-duplicate in-flight requests\n if (inflightQuery) {\n this.log(`Deduplicating inflight fetch for ${queryKey}`);\n return inflightQuery.promise;\n }\n\n // Fetch new data\n const promise = this.startFetching(queryKey, args);\n const abortController = new AbortController();\n\n this.inflightQueries.set(queryKey, { promise, abortController });\n\n return promise;\n }\n\n private async startFetching(queryKey: string, args: TArgs) {\n this.log(`Start fetching ${queryKey}`);\n\n try {\n const data = await this.queryFn(...args);\n\n this.log(`Successfully fetched ${queryKey}`);\n this.setData(queryKey, data, Date.now());\n return data;\n } catch (e) {\n this.log(`Failed to fetch ${queryKey}: ${e}`);\n throw e;\n } finally {\n this.inflightQueries.delete(queryKey);\n }\n }\n\n /** Get the entire stored entry for a query key. */\n public getQueryValue(queryKey: string): QueryStateValue<TData> | undefined {\n return this.queryState.getSnapshot()?.[queryKey];\n }\n\n /** Get the current stored data for a query key. */\n public getData(queryKey: string): TData | undefined {\n return this.queryState.getSnapshot()?.[queryKey]?.data;\n }\n\n /** Set the data directly if the user obtained it from somewhere else. */\n public 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 this.queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));\n\n this.enforceSizeLimit();\n }\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 public async updateFromSource(...args: TArgs): Promise<TData> {\n const key = this.getQueryKey(args);\n return await this.dedupedFetch(key, ...args);\n }\n\n /** Delete the cached data for one set of arguments. */\n public deleteData(queryKey: string): void {\n const record = this.queryState.getSnapshot();\n const clone = { ...record };\n delete clone[queryKey];\n this.queryState.setValue(clone);\n\n const inflight = this.inflightQueries.get(queryKey);\n if (inflight) {\n this.inflightQueries.delete(queryKey);\n inflight.abortController.abort(\"Deleted\");\n }\n }\n\n /** Delete all currently cached data & all inflight promises. */\n public clear(): void {\n this.queryState.delete();\n\n for (const { abortController } of Array.from(\n this.inflightQueries.values(),\n )) {\n abortController.abort(\"Cleared\");\n }\n\n this.inflightQueries.clear();\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 public enforceSizeLimit(): void {\n // Skip if there are no limits.\n if (!this.maxSize && !this.maxBytes) {\n return;\n }\n\n const oldState = this.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 newState = oldState;\n let needUpdate = false;\n\n // Limit by number of records.\n if (this.maxSize) {\n const numToCut = oldSize - this.maxSize;\n\n if (numToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to size ${oldSize} > ${this.maxSize}`,\n );\n\n newState = { ...newState }; // shallow clone\n needUpdate = true;\n\n Object.entries(newState)\n .sort(\n (entry1, entry2) =>\n // Sort descending.\n entry2[1].lastUpdatedMs - entry1[1].lastUpdatedMs,\n )\n .slice(-numToCut)\n .forEach(([key]) => {\n delete newState[key];\n });\n }\n }\n\n // Limit by byte size.\n if (this.maxBytes && Object.keys(newState).length > 1) {\n // Recompute only if changed by above code.\n const currentByteSize = needUpdate ? getByteSize(newState) : oldByteSize;\n\n let bytesToCut = currentByteSize - this.maxBytes;\n\n if (bytesToCut > 0) {\n this.log(\n `enforceSizeLimit for ${this.queryName} needed due to byte size ${currentByteSize.toLocaleString()} > ${this.maxBytes.toLocaleString()}`,\n );\n\n // Shallow clone only if not already cloned above.\n if (!needUpdate) {\n newState = { ...newState };\n needUpdate = true;\n }\n\n const entriesByTimeAscending = Object.entries(newState).sort(\n (entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs,\n );\n\n for (\n let i = 0;\n // Leave the last record entriesByTimeAscending[len-1] untouched.\n i < entriesByTimeAscending.length - 1 && bytesToCut > 0;\n i++\n ) {\n const key = entriesByTimeAscending[i][0];\n const thisSize = getByteSize(key) + getByteSize(newState[key]);\n delete newState[key];\n bytesToCut -= thisSize;\n }\n }\n }\n\n // Update the state.\n if (needUpdate) {\n this.queryState.setValue(newState);\n\n // Log to inform user that the data was trimmed.\n this.log(\n `Trimmed data for ${this.queryName}: size=(${oldSize} -> ${Object.keys(newState).length}) (limit=${this.maxSize}), byteSize=(${oldByteSize.toLocaleString()} -> ${getByteSize(newState).toLocaleString()}) (limit=${this.maxBytes.toLocaleString()})`,\n );\n\n return;\n }\n\n // Log to indicate why trimming was not needed.\n this.log(\n `No need to trim data for ${this.queryName}: size=${oldSize} (limit=${this.maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${this.maxBytes.toLocaleString()})`,\n );\n }\n}\n\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 used for logging only.\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): SharedQuery<TArgs, TData> {\n if (seenQueryNames.has(options.queryName)) {\n throw new Error(`Duplicate shared query \"${options.queryName}\"`);\n }\n seenQueryNames.add(options.queryName);\n\n return new SharedQuery(options);\n}\n\nconst DEFAULT_QUERY_STATE_ENTRY: QueryStateValue<unknown> = {\n lastUpdatedMs: 0,\n loading: true,\n};\n\n/**\n * React hook to make use of a shared query inside any React component.\n *\n * Example:\n * ```\n * const users = useSharedQuery(usersQuery, [\"123\"]);\n * ```\n */\nexport function useSharedQuery<TArgs extends unknown[], TData>(\n query: SharedQuery<TArgs, TData>,\n // Default to use no arguments.\n args: TArgs = [] as unknown as 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 // Make sure typechecker knows this could be undefined.\n const queryStateValue = queryState[queryKey] as\n | QueryStateValue<TData>\n | undefined;\n\n const setQueryStateValue = useCallback(\n (\n arg:\n | QueryStateValue<TData>\n | ((\n prev: QueryStateValue<TData> | undefined,\n ) => QueryStateValue<TData>),\n ) => {\n setQueryState((prev) => {\n const clone = { ...prev };\n clone[queryKey] =\n typeof arg === \"function\" ? arg(clone[queryKey]) : arg;\n return clone;\n });\n },\n [queryKey, setQueryState],\n );\n\n // The fetch logic wrapped in useCallback to be stable for useEffect\n const execute = useCallback(\n async (forceRefresh: boolean) => {\n query.log(`Begin executing shared query ${queryKey}`);\n\n setQueryStateValue((prev) => ({\n // Keep old data and error.\n ...(prev ?? {}),\n lastUpdatedMs: Date.now(),\n loading: true,\n }));\n\n try {\n const data = await (forceRefresh\n ? query.updateFromSource(...stableArgs)\n : query.getCachedOrFetch(...stableArgs));\n\n if (isMounted.current) {\n const now = Date.now();\n\n setQueryStateValue({\n // Don't keep old error.\n lastUpdatedMs: now,\n loading: false,\n data,\n dataUpdatedMs: now,\n });\n }\n } catch (e) {\n if (isMounted.current) {\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 },\n [query, queryKey, setQueryStateValue, stableArgs],\n );\n\n useEffect(() => {\n isMounted.current = true;\n\n void execute(false);\n\n return () => {\n isMounted.current = false;\n };\n }, [execute]);\n\n return useMemo(() => {\n const state =\n queryStateValue ?? (DEFAULT_QUERY_STATE_ENTRY as QueryStateValue<TData>);\n\n return {\n ...state,\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) => {\n const controller = query.getAbortControllerByKey(queryKey);\n controller?.abort(reason);\n return Boolean(controller);\n },\n refetch: () => {\n void execute(true);\n },\n setData: (data: TData, dataUpdatedMs?: number) => {\n const now = Date.now();\n setQueryStateValue((prev) => ({\n ...(prev ?? {}),\n data,\n dataUpdatedMs: dataUpdatedMs ?? now,\n lastUpdatedMs: now,\n loading: false,\n }));\n },\n deleteData: () => {\n setQueryState((prev) => {\n const clone = { ...prev };\n delete clone[queryKey];\n return clone;\n });\n },\n };\n }, [\n execute,\n query,\n queryKey,\n queryStateValue,\n setQueryState,\n setQueryStateValue,\n ]);\n}\n","/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n","/**\n * JSON stringify a value of any type, and returns an unsafe string. The string\n * is \"unsafe\" because you might not be able to restore the original object\n * using the serialized JSON. This is specifically used for query key generation\n * and is not suitable for more general uses.\n *\n * Note: The given value should not contain any functions because functions\n * cannot be serialized and deserialized properly.\n */\nexport function stringifyDeterministicForKeys(params: unknown): string {\n const cache = new Set();\n\n return JSON.stringify(params, (_, value) => {\n if (typeof value === \"function\") {\n throw new Error(`Functions should not be passed into query parameters`);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n\n if (cache.has(value)) {\n // Circular reference detected! Return a placeholder string.\n return \"[Circular]\";\n }\n\n cache.add(value);\n\n // Don't crash on circular references, but don't mark the top level object\n // as circular because we want to return as much string as possible.\n if (value !== params) {\n try {\n JSON.stringify(value);\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n return Object.keys(value)\n .sort()\n .reduce(\n (result: Record<string, unknown>, key: string) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n });\n}\n","import isEqual from \"lodash/isEqual\";\nimport { useMemo, useState } from \"react\";\n\n/** Provides a stable value for T based on deep equality. */\nexport function useDeepMemo<T>(value: T): T {\n const [state, setState] = useState<T>(value);\n\n return useMemo(() => {\n if (state === value || isEqual(state, value)) {\n return state;\n }\n\n // We check equality, so this should be safe.\n // eslint-disable-next-line react-hooks/set-state-in-render\n setState(value);\n\n return value;\n }, [state, value]);\n}\n"],"mappings":"AAcA,OAAS,cAAAA,MAAkB,oCAC3B,OAAOC,MAAiB,gBACxB,OAAS,eAAAC,EAAa,aAAAC,EAAW,WAAAC,EAAS,UAAAC,MAAc,QCHxD,OAAS,cAAAC,MAAkB,oCAC3B,OAAS,wBAAAC,MAA4B,QCdrC,OAAS,WAAAC,MAAe,8BAuBjB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,gBAAAC,EAAiB,aAAAC,EAAc,cAAAC,EAAe,MAAAC,CAAM,EAAIL,GAAW,CAAC,EAE5E,GAAIK,EACF,OAAOA,EAGT,IAAMC,EAAWF,GAAiBH,EAElC,OAAIC,EACK,IAAIK,EAAuBL,EAAiBI,CAAQ,EAGzDH,EACK,IAAIK,EAAoBL,EAAcG,CAAQ,EAGhD,IACT,CA+CO,IAAMG,EAAN,KAA0D,CACxD,YACWC,EACAC,EAChB,CAFgB,eAAAD,EACA,cAAAC,CACf,CAEI,KAAKC,EAAaC,EAAgB,CACvC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAMC,EAAU,KAAK,UAAY,IAAMF,EACvC,OAAO,aAAa,QAClBE,EACA,KAAK,UAAU,CACb,MAAAD,EACA,UAAW,KAAK,SAAW,KAAK,IAAI,EAAI,KAAK,SAAW,CAC1D,CAAkC,CACpC,CACF,CAEO,KAAKD,EAA4B,CACtC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAME,EAAU,KAAK,UAAY,IAAMF,EACjCG,EAAM,OAAO,aAAa,QAAQD,CAAO,EAC/C,GAAKC,EAEL,GAAI,CACF,IAAMC,E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KAAAxC,EACA,cAAewC,CACjB,CAAC,CACH,CACF,OAASvC,EAAG,CACV,GAAI8B,EAAU,QAAS,CACrB,IAAMS,EAAM,KAAK,IAAI,EAErBL,EAAoBhC,IAAU,CAE5B,GAAIA,GAAQ,CAAC,EACb,cAAeqC,EACf,QAAS,GACT,MAAOvC,EACP,eAAgBuC,CAClB,EAAE,CACJ,CACF,CACF,EACA,CAACf,EAAO/B,EAAUyC,EAAoBT,CAAU,CAClD,EAEA,OAAAe,EAAU,KACRV,EAAU,QAAU,GAEfO,EAAQ,EAAK,EAEX,IAAM,CACXP,EAAU,QAAU,EACtB,GACC,CAACO,CAAO,CAAC,EAELL,EAAQ,KAIN,CACL,GAHAC,GAAoBX,EAOpB,kBAAoBmB,GAAqB,CACvC,IAAMC,EAAalB,EAAM,wBAAwB/B,CAAQ,EACzD,OAAAiD,GAAY,MAAMD,CAAM,EACjB,EAAQC,CACjB,EACA,QAAS,IAAM,CACRL,EAAQ,EAAI,CACnB,EACA,QAAS,CAACtC,EAAaL,IAA2B,CAChD,IAAM6C,EAAM,KAAK,IAAI,EACrBL,EAAoBhC,IAAU,CAC5B,GAAIA,GAAQ,CAAC,EACb,KAAAH,EACA,cAAeL,GAAiB6C,EAChC,cAAeA,EACf,QAAS,EACX,EAAE,CACJ,EACA,WAAY,IAAM,CAChBX,EAAe1B,GAAS,CACtB,IAAME,EAAQ,CAAE,GAAGF,CAAK,EACxB,cAAOE,EAAMX,CAAQ,EACdW,CACT,CAAC,CACH,CACF,GACC,CACDiC,EACAb,EACA/B,EACAwC,EACAL,EACAM,CACF,CAAC,CACH","names":["MS_PER_DAY","getByteSize","useCallback","useEffect","useMemo","useRef","MS_PER_DAY","useSyncExternalStore","kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","kvStore","k","SharedStateDefaults","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","stringifyDeterministicForKeys","params","cache","_","value","result","key","isEqual","useMemo","useState","useDeepMemo","value","state","setState","SharedQueryDefaults","MS_PER_DAY","args","SharedQuery","options","persistTo","sharedState","stringifyDeterministicForKeys","queryKey","dataUpdatedMs","cached","inflightQuery","promise","abortController","data","e","entry","prev","key","clone","inflight","oldState","oldSize","oldByteSize","getByteSize","newState","needUpdate","numToCut","entry1","entry2","currentByteSize","bytesToCut","entriesByTimeAscending","i","thisSize","seenQueryNames","sharedQuery","DEFAULT_QUERY_STATE_ENTRY","useSharedQuery","query","stableArgs","useDeepMemo","queryState","setQueryState","useSharedState","isMounted","useRef","useMemo","queryStateValue","setQueryStateValue","useCallback","arg","execute","forceRefresh","now","useEffect","reason","controller"]}
|
package/sharedState.d.mts
CHANGED
|
@@ -9,7 +9,10 @@ import { StorageOptions } from './utils/storage.mjs';
|
|
|
9
9
|
* This library aims to be the shortest, simplest, easiest to use, and most
|
|
10
10
|
* efficient implementation of shared global React states with seamless support
|
|
11
11
|
* for client persistence.
|
|
12
|
+
*
|
|
13
|
+
* @packageDocumentation
|
|
12
14
|
*/
|
|
15
|
+
|
|
13
16
|
/************************************************************************/
|
|
14
17
|
/************************************************************************/
|
|
15
18
|
/**
|
package/sharedState.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { StorageOptions } from "./utils/storage";
|
|
2
1
|
/**
|
|
3
2
|
* The "shared state" is a React state that shares the same value across the
|
|
4
3
|
* entire app. It is largely similar to the jotai library, but is much smaller
|
|
@@ -8,7 +7,10 @@ import { StorageOptions } from "./utils/storage";
|
|
|
8
7
|
* This library aims to be the shortest, simplest, easiest to use, and most
|
|
9
8
|
* efficient implementation of shared global React states with seamless support
|
|
10
9
|
* for client persistence.
|
|
10
|
+
*
|
|
11
|
+
* @packageDocumentation
|
|
11
12
|
*/
|
|
13
|
+
import { StorageOptions } from "./utils/storage";
|
|
12
14
|
/************************************************************************/
|
|
13
15
|
/************************************************************************/
|
|
14
16
|
/**
|
package/sharedState.min.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sharedState.ts","../src/utils/storage.ts"],"sourcesContent":["import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n */\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAR,GAAA,IAAAS,EAA2B,6CAC3BC,EAAqC,iBCDrC,IAAAC,EAAwB,uCAuBjB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,gBAAAC,EAAiB,aAAAC,EAAc,cAAAC,EAAe,MAAAC,CAAM,EAAIL,GAAW,CAAC,EAE5E,GAAIK,EACF,OAAOA,EAGT,IAAMC,EAAWF,GAAiBH,EAElC,OAAIC,EACK,IAAIK,EAAuBL,EAAiBI,CAAQ,EAGzDH,EACK,IAAIK,EAAoBL,EAAcG,CAAQ,EAGhD,IACT,CA+CO,IAAMG,EAAN,KAA0D,CACxD,YACWC,EACAC,EAChB,CAFgB,eAAAD,EACA,cAAAC,CACf,CAEI,KAAKC,EAAaC,EAAgB,CACvC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAMC,EAAU,KAAK,UAAY,IAAMF,EACvC,OAAO,aAAa,QAClBE,EACA,KAAK,UAAU,CACb,MAAAD,EACA,UAAW,KAAK,SAAW,KAAK,IAAI,EAAI,KAAK,SAAW,CAC1D,CAAkC,CACpC,CACF,CAEO,KAAKD,EAA4B,CACtC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAME,EAAU,KAAK,UAAY,IAAMF,EACjCG,EAAM,OAAO,aAAa,QAAQD,CAAO,EAC/C,GAAK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AAY,CAC1B,EAEeA,EAAM,eAAe,CACtC,CAGO,SAASE,EAAuBF,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAGO,SAASG,EAAwBH,EAAuB,CAC7D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC","names":["sharedState_exports","__export","SharedState","SharedStateDefaults","sharedState","useSharedState","useSharedStateSetter","useSharedStateValue","__toCommonJS","import_timeConstants","import_react","import_kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","k","SharedStateDefaults","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.ts","../src/utils/storage.ts"],"sourcesContent":["/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAR,GAaA,IAAAS,EAA2B,6CAC3BC,EAAqC,iBCdrC,IAAAC,EAAwB,uCAuBjB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,gBAAAC,EAAiB,aAAAC,EAAc,cAAAC,EAAe,MAAAC,CAAM,EAAIL,GAAW,CAAC,EAE5E,GAAIK,EACF,OAAOA,EAGT,IAAMC,EAAWF,GAAiBH,EAElC,OAAIC,EACK,IAAIK,EAAuBL,EAAiBI,CAAQ,EAGzDH,EACK,IAAIK,EAAoBL,EAAcG,CAAQ,EAGhD,IACT,CA+CO,IAAMG,EAAN,KAA0D,CACxD,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D,CAGA,MAAa,sBAAuB,CAClC,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMQ,EAAI,MAAM,KAAK,gBAAgB,KAAKR,CAAW,EACrDD,EAAY,IAAI,KAAK,UAAWS,IAAM,OAAYA,EAAI,KAAK,YAAY,CACzE,CACF,EAOO,SAASC,EACdN,EACAC,EACgB,CAChB,OAAO,IAAIF,EAAYC,EAAcC,CAAO,CAC9C,CAMO,SAASM,EACdC,EAC2C,CAC3C,OAAAA,EAAM,qBAAqB,EASpB,IAPO,wBACXC,GAAkBD,EAAM,UAAUC,CAAa,EAChD,IAAMD,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,eAAe,CACtC,CAGO,SAASE,EAAuBF,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAGO,SAASG,EAAwBH,EAAuB,CAC7D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC","names":["sharedState_exports","__export","SharedState","SharedStateDefaults","sharedState","useSharedState","useSharedStateSetter","useSharedStateValue","__toCommonJS","import_timeConstants","import_react","import_kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","k","SharedStateDefaults","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
package/sharedState.min.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sharedState.ts","../src/utils/storage.ts"],"sourcesContent":["import { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n */\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,oCAC3B,OAAS,wBAAAC,MAA4B,QCDrC,OAAS,WAAAC,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AAK,SAAS,CACvC,CAGO,SAASH,EAAkC,CAChD,GAAI,OAAOA,GAAS,WAAY,CAC9B,IAAMH,EAAOM,EAAY,IAAO,KAAK,SAAS,EAC9CH,EAAQA,EAAqBH,CAAI,CACnC,CAEAM,EAAY,IAAI,KAAK,UAAWH,CAAI,EAC/B,KAAK,gBAAgB,KAAKI,EAAaJ,CAAI,CAClD,CAIO,QAAS,CACdG,EAAY,IAAI,KAAK,UAAW,KAAK,YAAY,EAC5C,KAAK,gBAAgB,KAAKC,EAAa,KAAK,YAAY,CAC/D,CAGA,MAAa,sBAAuB,CAClC,GAAI,KAAK,SAAU,OACnB,KAAK,SAAW,GAEhB,IAAMQ,EAAI,MAAM,KAAK,gBAAgB,KAAKR,CAAW,EACrDD,EAAY,IAAI,KAAK,UAAWS,IAAM,OAAYA,EAAI,KAAK,YAAY,CACzE,CACF,EAOO,SAASC,EACdN,EACAC,EACgB,CAChB,OAAO,IAAIF,EAAYC,EAAcC,CAAO,CAC9C,CAMO,SAASM,EACdC,EAC2C,CAC3C,OAAAA,EAAM,qBAAqB,EASpB,CAPOC,EACXC,GAAkBF,EAAM,UAAUE,CAAa,EAChD,IAAMF,EAAM,YAAY,EAExB,IAAMA,EAAM,YAAY,CAC1B,EAEeA,EAAM,eAAe,CACtC,CAGO,SAASG,EAAuBH,EAAuB,CAC5D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC,CAGO,SAASI,EAAwBJ,EAAuB,CAC7D,OAAOD,EAAeC,CAAK,EAAE,CAAC,CAChC","names":["MS_PER_DAY","useSyncExternalStore","kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","kvStore","k","SharedStateDefaults","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
|
1
|
+
{"version":3,"sources":["../src/sharedState.ts","../src/utils/storage.ts"],"sourcesContent":["/**\n * The \"shared state\" is a React state that shares the same value across the\n * entire app. It is largely similar to the jotai library, but is much smaller\n * and much easier to work with when used for persisting in local storage or\n * indexed db, with an automatic expiration for persisted values.\n *\n * This library aims to be the shortest, simplest, easiest to use, and most\n * efficient implementation of shared global React states with seamless support\n * for client persistence.\n *\n * @packageDocumentation\n */\n\nimport { MS_PER_DAY } from \"@choksheak/ts-utils/timeConstants\";\nimport { useSyncExternalStore } from \"react\";\n\nimport {\n getStorageAdapter,\n StorageAdapter,\n StorageOptions,\n} from \"./utils/storage\";\n\n/************************************************************************/\n/* Global config */\n/************************************************************************/\n\n/**\n * These values are configurable by the user at any time.\n */\nexport const SharedStateDefaults = {\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\n/************************************************************************/\n/* Shared state implementation */\n/************************************************************************/\n\ntype Subscriber<T> = (next: T, prev: T) => void;\n\nclass PubSubStore {\n private dataByKey = new Map<string, unknown>();\n private subscribersByKey = new Map<string, Set<Subscriber<unknown>>>();\n\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 public get<T>(key: string): T {\n return this.dataByKey.get(key) as T;\n }\n\n public set<T>(key: string, value: T): void {\n const prev = this.dataByKey.get(key) as T;\n\n // Do nothing if no change.\n if (prev === value) return;\n\n this.dataByKey.set(key, value);\n this.notify(key, value, prev);\n }\n\n public delete(key: string): void {\n this.dataByKey.delete(key);\n }\n\n public setNoNotify<T>(key: string, value: T): void {\n this.dataByKey.set(key, value);\n }\n\n // Subscribe to changes of a specific key\n public subscribe<T>(key: string, subscriber: Subscriber<T>): () => void {\n let subscribers = this.subscribersByKey.get(key);\n if (!subscribers) {\n subscribers = new Set();\n this.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) this.subscribersByKey.delete(key);\n };\n }\n\n private notify<T>(key: string, next: T, prev: T): void {\n const subscribers = this.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\nconst pubSubStore = new PubSubStore();\n\nconst STORAGE_KEY = \"state\";\n\nexport type SharedStateOptions<T> = {\n lazyLoad?: boolean;\n} & StorageOptions<T>;\n\nlet stateKey = 0;\n\nexport class SharedState<T> {\n private readonly pubSubKey: string;\n private readonly storageAdapter: StorageAdapter<T> | null;\n public readonly setValueBounded: (next: T | ((prev: T) => T)) => void;\n public initDone = false;\n\n public constructor(\n private readonly defaultValue: T,\n options?: SharedStateOptions<T>,\n ) {\n this.pubSubKey = String(stateKey++);\n\n // Use max of 1 storage adapter per shared state.\n this.storageAdapter = getStorageAdapter(\n options,\n SharedStateDefaults.storeExpiryMs,\n );\n\n // Same as this.setValue, but binding the `this` reference.\n this.setValueBounded = (arg) => this.setValue(arg);\n\n // Always set the default value first to avoid returning undefineds if that\n // is not part of T.\n pubSubStore.setNoNotify(this.pubSubKey, defaultValue);\n\n const lazyLoad = options?.lazyLoad;\n const lazy =\n lazyLoad !== undefined ? lazyLoad : SharedStateDefaults.lazyLoad;\n\n if (!lazy) {\n void this.initDefaultValueOnce();\n }\n }\n\n // `subscribe` function required by useSyncExternalStore\n public subscribe(subscriber: () => void): () => void {\n return pubSubStore.subscribe(this.pubSubKey, () => subscriber());\n }\n\n // Get the value of the shared state.\n // `getSnapshot` function — must return same ref if value unchanged\n public getSnapshot(): T {\n return pubSubStore.get(this.pubSubKey);\n }\n\n // Set the value of the shared state.\n public setValue(next: T | ((prev: T) => T)): void {\n if (typeof next === \"function\") {\n const prev = pubSubStore.get<T>(this.pubSubKey);\n next = (next as (p: T) => T)(prev);\n }\n\n pubSubStore.set(this.pubSubKey, next);\n void this.storageAdapter?.save(STORAGE_KEY, next);\n }\n\n // Remove the value of the shared state. Actually this just sets the value\n // back to the given default value.\n public delete() {\n pubSubStore.set(this.pubSubKey, this.defaultValue);\n void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);\n }\n\n // Initial default handling\n public async initDefaultValueOnce() {\n if (this.initDone) return;\n this.initDone = true;\n\n const v = await this.storageAdapter?.load(STORAGE_KEY);\n pubSubStore.set(this.pubSubKey, v !== undefined ? v : this.defaultValue);\n }\n}\n\n/**\n * Create a new shared state object. Put this code at the top level scope:\n *\n * const myState = sharedState<number>(0);\n */\nexport function sharedState<T>(\n defaultValue: T,\n options?: SharedStateOptions<T>,\n): SharedState<T> {\n return new SharedState(defaultValue, options);\n}\n\n/**\n * React hook for subscribing to a key in the global store.\n * const [my, setMy] = useSharedState(myState);\n */\nexport function useSharedState<T>(\n state: SharedState<T>,\n): [T, (next: T | ((prev: T) => T)) => void] {\n 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.setValueBounded];\n}\n\n/** E.g. const my = useSharedStateValue(myState) */\nexport function useSharedStateValue<T>(state: SharedState<T>) {\n return useSharedState(state)[0];\n}\n\n/** E.g. const setMy = useSharedStateSetter(myState) */\nexport function useSharedStateSetter<T>(state: SharedState<T>) {\n return useSharedState(state)[1];\n}\n","import { kvStore } from \"@choksheak/ts-utils/kvStore\";\n\nexport type StorageAdapter<T> = {\n save: (key: string, value: T) => Promise<void> | void;\n load: (key: string) => Promise<T | undefined> | T | undefined;\n delete: (key: string) => Promise<void> | void;\n clear: () => Promise<void> | void;\n};\n\nexport type StorageOptions<T> = {\n // If specified, this will be used and all other fields will be ignored.\n store?: StorageAdapter<T>;\n\n // Storage key in local storage for this data.\n localStorageKey?: string;\n\n // Storage key in indexed db for this data.\n indexedDbKey?: string;\n\n // How long to wait before the value is considered expired.\n storeExpiryMs?: number;\n};\n\nexport function getStorageAdapter<T>(\n options: StorageOptions<T> | undefined,\n defaultStoreExpiryMs: number,\n): StorageAdapter<T> | null {\n const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};\n\n if (store) {\n return store;\n }\n\n const expiryMs = storeExpiryMs || defaultStoreExpiryMs;\n\n if (localStorageKey) {\n return new LocalStorageAdapter<T>(localStorageKey, expiryMs);\n }\n\n if (indexedDbKey) {\n return new IndexedDbAdapter<T>(indexedDbKey, expiryMs);\n }\n\n return null;\n}\n\n/************************************************************************/\n/* Storage adapters */\n/************************************************************************/\n\ntype ValueWithExpiration<T> = { value: T; expiresAt: number };\n\n/** Save state to memory only - not persisted. */\nexport class InMemoryStorageAdapter<T> implements StorageAdapter<T> {\n private readonly cache = new Map<string, ValueWithExpiration<T>>();\n\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.set(fullKey, {\n value,\n expiresAt: Date.now() + this.expiryMs,\n });\n }\n\n public load(key: string): T | undefined {\n const fullKey = this.keyPrefix + \":\" + key;\n const cached = this.cache.get(fullKey);\n\n if (cached && Date.now() < cached.expiresAt) {\n return cached.value;\n }\n\n return undefined;\n }\n\n public delete(key: string): void {\n const fullKey = this.keyPrefix + \":\" + key;\n this.cache.delete(fullKey);\n }\n\n public clear(): void {\n this.cache.clear();\n }\n}\n\n/** Save state to local storage. */\nexport class LocalStorageAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public save(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.setItem(\n fullKey,\n JSON.stringify({\n value,\n expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0,\n } satisfies ValueWithExpiration<T>),\n );\n }\n\n public load(key: string): T | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = window.localStorage.getItem(fullKey);\n if (!raw) return undefined;\n\n try {\n const box = JSON.parse(raw) as ValueWithExpiration<T>;\n if (!box || (box.expiresAt && Date.now() >= box.expiresAt)) {\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n\n return box.value;\n } catch {\n // Ignore error.\n window.localStorage.removeItem(fullKey);\n return undefined;\n }\n }\n\n public delete(key: string): void {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n window.localStorage.removeItem(fullKey);\n }\n\n public clear(): void {\n if (typeof window === \"undefined\") return;\n\n for (const key of Object.keys(window.localStorage)) {\n if (key.startsWith(this.keyPrefix)) {\n window.localStorage.removeItem(key);\n }\n }\n }\n}\n\n/** Save state to indexed db. */\nexport class IndexedDbAdapter<T> implements StorageAdapter<T> {\n public constructor(\n public readonly keyPrefix: string,\n public readonly expiryMs: number,\n ) {}\n\n public async save(key: string, value: T): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);\n }\n\n public async load(key: string): Promise<T | undefined> {\n if (typeof window === \"undefined\") return undefined;\n\n const fullKey = this.keyPrefix + \":\" + key;\n const raw = await kvStore.get<string>(fullKey);\n if (raw === undefined) return undefined;\n\n try {\n return JSON.parse(raw);\n } catch {\n // Ignore error.\n await kvStore.delete(fullKey);\n return undefined;\n }\n }\n\n public async delete(key: string): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n const fullKey = this.keyPrefix + \":\" + key;\n await kvStore.delete(fullKey);\n }\n\n public async clear(): Promise<void> {\n if (typeof window === \"undefined\") return;\n\n await kvStore.forEach(async (k) => {\n if (k.startsWith(this.keyPrefix)) {\n await kvStore.delete(k);\n }\n });\n }\n}\n"],"mappings":"AAaA,OAAS,cAAAA,MAAkB,oCAC3B,OAAS,wBAAAC,MAA4B,QCdrC,OAAS,WAAAC,MAAe,8BAuBjB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,gBAAAC,EAAiB,aAAAC,EAAc,cAAAC,EAAe,MAAAC,CAAM,EAAIL,GAAW,CAAC,EAE5E,GAAIK,EACF,OAAOA,EAGT,IAAMC,EAAWF,GAAiBH,EAElC,OAAIC,EACK,IAAIK,EAAuBL,EAAiBI,CAAQ,EAGzDH,EACK,IAAIK,EAAoBL,EAAcG,CAAQ,EAGhD,IACT,CA+CO,IAAMG,EAAN,KAA0D,CACxD,YACWC,EACAC,EAChB,CAFgB,eAAAD,EACA,cAAAC,CACf,CAEI,KAAKC,EAAaC,EAAgB,CACvC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAMC,EAAU,KAAK,UAAY,IAAMF,EACvC,OAAO,aAAa,QAClBE,EACA,KAAK,UAAU,CACb,MAAAD,EACA,UAAW,KAAK,SAAW,KAAK,IAAI,EAAI,KAAK,SAAW,CAC1D,CAAkC,CACpC,CACF,CAEO,KAAKD,EAA4B,CACtC,GAAI,OAAO,OAAW,IAAa,OAEnC,IAAME,EAAU,KAAK,UAAY,IAAMF,EACjCG,EAAM,OAAO,aAAa,QAAQD,CAAO,EAC/C,GAAKC,EAEL,GAAI,CACF,IAAMC,EAAM,KAAK,MAAMD,CAAG,EAC1B,GAAI,CAACC,GAAQA,EAAI,WAAa,KAAK,IAAI,GAAKA,EAAI,UAAY,CAC1D,OAAO,aAAa,WAAWF,CAAO,EACtC,MACF,CAEA,OAAOE,EAAI,KACb,MAAQ,CAEN,OAAO,a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_DAY","useSyncExternalStore","kvStore","getStorageAdapter","options","defaultStoreExpiryMs","localStorageKey","indexedDbKey","storeExpiryMs","store","expiryMs","LocalStorageAdapter","IndexedDbAdapter","LocalStorageAdapter","keyPrefix","expiryMs","key","value","fullKey","raw","box","IndexedDbAdapter","kvStore","k","SharedStateDefaults","MS_PER_DAY","PubSubStore","key","value","prev","subscriber","subscribers","next","copy","e","pubSubStore","STORAGE_KEY","stateKey","SharedState","defaultValue","options","getStorageAdapter","arg","lazyLoad","v","sharedState","useSharedState","state","useSyncExternalStore","onStoreChange","useSharedStateValue","useSharedStateSetter"]}
|
package/index.cjs
DELETED
package/index.d.mts
DELETED
package/index.d.ts
DELETED
|
File without changes
|
package/index.min.cjs
DELETED
package/index.min.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Unused file. To support full tree-shaking, please import from the individual\n// files directly.\n\nconsole.log(`Hello from Chok's React Utils`);\n"],"mappings":"aAGA,QAAQ,IAAI,+BAA+B","names":[]}
|
package/index.min.mjs
DELETED
package/index.min.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Unused file. To support full tree-shaking, please import from the individual\n// files directly.\n\nconsole.log(`Hello from Chok's React Utils`);\n"],"mappings":"8DAAA,IAAAA,EAAAC,EAAA,KAGA,QAAQ,IAAI,+BAA+B","names":["require_index","__commonJSMin"]}
|
package/index.mjs
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
2
|
-
var __commonJS = (cb, mod) => function __require() {
|
|
3
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
4
|
-
};
|
|
5
|
-
|
|
6
|
-
// src/index.ts
|
|
7
|
-
var require_index = __commonJS({
|
|
8
|
-
"src/index.ts"() {
|
|
9
|
-
console.log(`Hello from Chok's React Utils`);
|
|
10
|
-
}
|
|
11
|
-
});
|
|
12
|
-
export default require_index();
|